1use std::{
6 any::{Any, TypeId},
7 fmt,
8 sync::Arc,
9};
10
11use rustc_hash::FxHashMap;
12
13use super::{
14 Children, IntoElement, PropError, Slot, TsType, TsTypes,
15 builder::{ComponentElement, ElNode},
16 call::{AnyValue, JsResult, MethodCall},
17 class::{Class, ClassDef, ClassSpec, MemberKind, Thrown},
18 js::{JsHost, JsIn, JsOwned},
19 module::{FunctionSpec, Module, ModuleSpec},
20};
21
22pub trait Component: 'static {
44 type Props: Props;
46
47 type Event: Event;
49
50 const METHODS: Methods = Methods::NONE;
53
54 const DOC: &'static str = "";
57
58 fn view(props: Self::Props, cx: super::Scope<Self::Event>) -> impl IntoElement;
62
63 fn element(props: Self::Props) -> ComponentElement<Self>
68 where
69 Self: Sized,
70 {
71 ComponentElement::new(props)
72 }
73}
74
75#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct ComponentError {
79 pub component: &'static str,
81 pub message: String,
83}
84
85impl fmt::Display for ComponentError {
86 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87 write!(f, "{} failed: {}", self.component, self.message)
88 }
89}
90
91pub(crate) fn caught<R>(f: impl FnOnce() -> R) -> Result<R, String> {
93 std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).map_err(panic_message)
94}
95
96pub(crate) fn panic_message(payload: Box<dyn std::any::Any + Send>) -> String {
98 match payload.downcast::<String>() {
99 Ok(s) => *s,
100 Err(payload) => match payload.downcast::<&'static str>() {
101 Ok(s) => (*s).to_owned(),
102 Err(_) => "a panic".to_owned(),
103 },
104 }
105}
106
107pub struct Method {
110 pub name: &'static str,
112 pub doc: &'static str,
114 pub params: &'static [Param],
116 pub returns: Option<TsType>,
120 pub refs: super::ClassRefs,
122 pub call: fn(&dyn JsHost) -> Result<MethodCall, Thrown>,
127}
128
129pub trait Api: Sized + 'static {
134 const METHODS: &'static [Method];
136}
137
138#[derive(Clone, Copy)]
141pub struct Methods {
142 specs: fn(&mut TsTypes) -> Vec<MethodSpec>,
143 refs: super::ClassRefs,
144}
145
146impl Methods {
147 pub const NONE: Self = Self {
149 specs: |_| Vec::new(),
150 refs: |_| {},
151 };
152
153 pub const fn of<A: Api>() -> Self {
155 Self {
156 specs: specs_of::<A>,
157 refs: |out| {
158 for m in A::METHODS {
159 (m.refs)(out);
160 }
161 },
162 }
163 }
164}
165
166fn specs_of<A: Api>(types: &mut TsTypes) -> Vec<MethodSpec> {
167 A::METHODS
168 .iter()
169 .map(|m| MethodSpec {
170 name: m.name,
171 doc: m.doc,
172 params: m
173 .params
174 .iter()
175 .map(|(n, ts, optional)| (*n, ts(types), *optional))
176 .collect(),
177 returns: m.returns.map(|ts| ts(types)),
178 call: m.call,
179 })
180 .collect()
181}
182
183pub type Param = (&'static str, TsType, bool);
186
187#[derive(Debug, Clone)]
189pub struct MethodSpec {
190 pub name: &'static str,
192 pub doc: &'static str,
194 pub params: Vec<(&'static str, String, bool)>,
197 pub returns: Option<String>,
199 pub call: fn(&dyn JsHost) -> Result<MethodCall, Thrown>,
201}
202
203impl MethodSpec {
204 pub fn promises(&self) -> bool {
209 self.returns.is_some()
210 }
211}
212
213#[derive(Debug, Clone, Copy, PartialEq, Eq)]
215pub enum PropKind {
216 Value,
219 Renderer,
223 Slot,
225 Children,
227 Items,
230}
231
232pub type PropDecode = fn(JsIn<'_>) -> Result<AnyValue, PropError>;
236
237#[derive(Debug, Clone)]
239pub struct PropSpec {
240 pub name: &'static str,
242 pub ts: String,
244 pub optional: bool,
246 pub doc: &'static str,
248 pub kind: PropKind,
250 pub decode: Option<PropDecode>,
252}
253
254#[derive(Debug, Clone)]
256pub struct EventSpec {
257 pub name: &'static str,
259 pub arg: &'static str,
262 pub data: String,
265 pub doc: &'static str,
267}
268
269pub trait Props: Clone + PartialEq + 'static {
271 #[doc(hidden)]
273 const ITEMS: Option<&'static str> = None;
274
275 #[doc(hidden)]
278 const LAZY_CHILDREN: bool = false;
279
280 #[doc(hidden)]
284 const GENERIC: bool = false;
285
286 fn spec(types: &mut TsTypes) -> Vec<PropSpec>;
288
289 fn initial() -> Self;
291
292 fn set(&mut self, name: &str, value: Option<AnyValue>) -> Result<bool, PropError>;
295
296 fn set_slot(&mut self, name: &str, slot: Option<Slot>) -> bool;
298
299 fn set_children(&mut self, children: Children) -> bool;
301
302 #[doc(hidden)]
305 fn held(&self) -> Self {
306 self.clone()
307 }
308
309 #[doc(hidden)]
313 fn update_from(&mut self, new: &Self) -> bool {
314 if self == new {
315 return false;
316 }
317 *self = new.clone();
318 true
319 }
320}
321
322impl Props for () {
324 fn spec(_: &mut TsTypes) -> Vec<PropSpec> {
325 Vec::new()
326 }
327
328 fn initial() -> Self {}
329
330 fn set(&mut self, name: &str, _: Option<AnyValue>) -> Result<bool, PropError> {
331 Err(PropError(format!("unknown prop `{name}`")))
332 }
333
334 fn set_slot(&mut self, _: &str, _: Option<Slot>) -> bool {
335 false
336 }
337
338 fn set_children(&mut self, _: Children) -> bool {
339 false
340 }
341}
342
343pub trait Event: 'static {
350 fn spec(types: &mut TsTypes) -> Vec<EventSpec>;
352
353 fn name(&self) -> &'static str;
355
356 fn data_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError>;
358}
359
360#[derive(Debug, Clone, Copy, PartialEq, Eq)]
362pub enum NoEvent {}
363
364impl Event for NoEvent {
365 fn spec(_types: &mut TsTypes) -> Vec<EventSpec> {
366 Vec::new()
367 }
368
369 fn name(&self) -> &'static str {
370 match *self {}
371 }
372
373 fn data_js<'a>(&self, _host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
374 match *self {}
375 }
376}
377
378#[derive(Debug, Clone)]
381pub struct ComponentSpec {
382 pub name: &'static str,
385 pub export: String,
387 pub doc: &'static str,
389 pub props: Vec<PropSpec>,
391 pub events: Vec<EventSpec>,
393 pub methods: Vec<MethodSpec>,
395 pub types: TsTypes,
397 pub lazy_children: bool,
401 pub generic: bool,
404}
405
406pub const HOST_PROPS: &[&str] = &[
410 "class",
411 "classList",
412 "style",
413 "activeStyle",
414 "hoverStyle",
415 "focusStyle",
416 "focusWithinStyle",
417 "focusVisibleStyle",
418 "disabledStyle",
419 "testID",
420 "tooltip",
421 "onLayout",
422 "onFileDragEnter",
423 "onFileDragLeave",
424 "onFileDrop",
425 "onMouseEnter",
426 "onMouseMove",
427 "onMouseLeave",
428 "onMouseUp",
429 "onContextMenu",
430];
431
432type Specs = (
434 fn(&mut TsTypes) -> Vec<PropSpec>,
435 fn(&mut TsTypes) -> Vec<EventSpec>,
436 fn(&mut TsTypes) -> Vec<MethodSpec>,
437);
438
439impl ComponentSpec {
440 pub fn host_props(&self) -> impl Iterator<Item = &'static str> + '_ {
444 HOST_PROPS.iter().copied().filter(|&name| {
445 !self.props.iter().any(|p| p.name == name)
446 && !self.events.iter().any(|e| handler_name(e.name) == name)
447 })
448 }
449
450 pub(crate) fn of<C: Component>() -> Self {
451 Self::build(
452 name_of::<C>(),
453 C::DOC,
454 (C::Props::spec, C::Event::spec, C::METHODS.specs),
455 C::Props::LAZY_CHILDREN,
456 C::Props::GENERIC,
457 )
458 }
459
460 #[inline(never)]
462 fn build(
463 name: &'static str,
464 doc: &'static str,
465 (props, events, methods): Specs,
466 lazy_children: bool,
467 generic: bool,
468 ) -> Self {
469 let mut types = TsTypes::default();
470 let props = props(&mut types);
471 let events = events(&mut types);
472 let methods = methods(&mut types);
473 Self {
474 name,
475 export: export_name(name).to_owned(),
476 doc,
477 props,
478 events,
479 methods,
480 types,
481 lazy_children,
482 generic,
483 }
484 }
485
486 pub fn slots(&self) -> impl Iterator<Item = &'static str> + '_ {
488 self.props
489 .iter()
490 .filter(|p| p.kind == PropKind::Slot)
491 .map(|p| p.name)
492 }
493
494 pub fn renderers(&self) -> impl Iterator<Item = &'static str> + '_ {
496 self.props
497 .iter()
498 .filter(|p| p.kind == PropKind::Renderer)
499 .map(|p| p.name)
500 }
501
502 pub fn takes_children(&self) -> bool {
504 self.props.iter().any(|p| p.kind == PropKind::Children)
505 }
506
507 pub fn items(&self) -> Option<&'static str> {
509 self.props
510 .iter()
511 .find(|p| p.kind == PropKind::Items)
512 .map(|p| p.name)
513 }
514
515 pub(crate) fn holder(&self, name: &str) -> Option<&'static str> {
517 self.props
518 .iter()
519 .find(|p| matches!(p.kind, PropKind::Slot | PropKind::Items) && p.name == name)
520 .map(|p| p.name)
521 }
522}
523
524pub(crate) fn name_of<C: Component>() -> &'static str {
528 std::any::type_name::<C>()
529}
530
531pub(crate) fn export_name(type_name: &str) -> &str {
534 let path = type_name.split('<').next().unwrap_or(type_name);
535 path.rsplit("::").next().unwrap_or(path)
536}
537
538pub(crate) trait AnyInstance {
540 fn set_prop(&mut self, name: &str, value: Option<AnyValue>) -> Result<bool, PropError>;
541 fn set_props(&mut self, props: &dyn Any);
543 fn set_slot(&mut self, name: &'static str, filled: bool);
544 fn set_children(&mut self, present: bool);
545 fn cleanup(&mut self);
547 fn view(&mut self) -> ElNode;
549 fn name(&self) -> &'static str;
551 fn call(&mut self, call: MethodCall) -> Option<JsResult>;
554 fn owner(&self) -> Option<super::Owner>;
556 fn failure_owner(&self) -> super::Owner;
559 fn adopt(&mut self, parent: super::Owner);
563 fn place(&mut self, host: crate::NodeId, parent: super::Owner);
565}
566
567#[derive(Clone)]
571pub struct Root {
572 make: Arc<dyn Fn() -> super::AnyElement + Send + Sync>,
573 tokens: Option<Arc<super::Tokens>>,
574 fonts: Vec<Arc<[u8]>>,
575 appearance: Option<crate::platform::Appearance>,
576 app_id: Option<String>,
577 links: crate::url_scheme::AppLinks,
578 capabilities: Option<crate::access::Capabilities>,
579 status_bar: Option<crate::StatusBarSetting>,
580 main_window: Option<crate::desktop::MainWindowOptions>,
581 application: Option<crate::desktop::ApplicationOptions>,
582 translations: Option<crate::i18n::Translations>,
583 app_info: Option<crate::platform::AppInfo>,
584}
585
586impl Root {
587 pub fn new<C: Component>(props: impl Fn() -> C::Props + Send + Sync + 'static) -> Self {
589 Self {
590 make: Arc::new(move || super::IntoElement::into_element(C::element(props()))),
591 tokens: None,
592 fonts: Vec::new(),
593 appearance: None,
594 app_id: None,
595 links: crate::url_scheme::AppLinks::default(),
596 capabilities: None,
597 status_bar: None,
598 main_window: None,
599 application: None,
600 translations: None,
601 app_info: None,
602 }
603 }
604
605 pub fn translations(mut self, translations: crate::i18n::Translations) -> Self {
608 self.translations = Some(translations);
609 self
610 }
611
612 #[doc(hidden)]
615 pub fn translations_json(self, json: &str) -> Self {
616 match crate::i18n::Translations::from_json(json) {
617 Ok(translations) => self.translations(translations),
618 Err(e) => {
619 log::warn!("locales: {e}");
620 self
621 }
622 }
623 }
624
625 pub fn translations_ref(&self) -> Option<&crate::i18n::Translations> {
627 self.translations.as_ref()
628 }
629
630 pub fn app_id(mut self, id: impl Into<String>) -> Self {
633 self.app_id = Some(id.into());
634 self
635 }
636
637 pub fn app_id_ref(&self) -> Option<&str> {
639 self.app_id.as_deref()
640 }
641
642 pub fn app_info(mut self, info: crate::platform::AppInfo) -> Self {
646 self.app_info = Some(info);
647 self
648 }
649
650 #[doc(hidden)]
654 pub fn app_info_json(self, json: &str) -> Self {
655 let info = match serde_json::from_str(json) {
656 Ok(value) => crate::platform::AppInfo::from_json(&value),
657 Err(e) => {
658 log::warn!("appInfo: {e}, ignored");
659 crate::platform::AppInfo::default()
660 }
661 };
662 self.app_info(info)
663 }
664
665 #[doc(hidden)]
667 pub fn app_info_ref(&self) -> Option<&crate::platform::AppInfo> {
668 self.app_info.as_ref()
669 }
670
671 pub fn url_schemes(mut self, schemes: impl IntoIterator<Item = impl Into<String>>) -> Self {
676 self.links.set_schemes(schemes);
677 self
678 }
679
680 pub fn url_schemes_ref(&self) -> &[String] {
682 self.links.schemes()
683 }
684
685 pub fn links(mut self, links: crate::url_scheme::AppLinks) -> Self {
690 self.links = links;
691 self
692 }
693
694 #[doc(hidden)]
699 pub fn links_json(self, json: &str) -> Self {
700 let links = match serde_json::from_str::<serde_json::Value>(json) {
701 Ok(config) => {
702 let (links, ignored) = crate::url_scheme::AppLinks::from_json_lenient(&config);
703 for what in ignored {
704 log::warn!("nsh.json: {what}, ignored");
705 }
706 links
707 }
708 Err(e) => {
709 log::warn!("nsh.json: links: {e}; none claimed");
710 crate::url_scheme::AppLinks::default()
711 }
712 };
713 self.links(links)
714 }
715
716 pub fn links_ref(&self) -> &crate::url_scheme::AppLinks {
718 &self.links
719 }
720
721 pub fn capabilities(mut self, capabilities: crate::access::Capabilities) -> Self {
727 self.capabilities = Some(capabilities);
728 self
729 }
730
731 #[doc(hidden)]
737 pub fn capabilities_json(self, json: &str) -> Self {
738 let read = serde_json::from_str::<serde_json::Value>(json)
739 .map_err(|e| e.to_string())
740 .and_then(|v| crate::access::Capabilities::from_json_lenient(&v));
741 let capabilities = match read {
742 Ok((capabilities, dropped)) => {
743 for what in dropped {
744 log::warn!("nsh.json: {what}, not granted");
745 }
746 capabilities
747 }
748 Err(e) => {
749 log::warn!("nsh.json: capabilities: {e}; nothing granted");
750 crate::access::Capabilities::default()
751 }
752 };
753 self.capabilities(capabilities)
754 }
755
756 pub fn capabilities_ref(&self) -> Option<&crate::access::Capabilities> {
759 self.capabilities.as_ref()
760 }
761
762 pub fn tokens(mut self, tokens: super::Tokens) -> Self {
765 self.tokens = Some(Arc::new(tokens));
766 self
767 }
768
769 pub fn font(mut self, data: impl Into<Arc<[u8]>>) -> Self {
772 self.fonts.push(data.into());
773 self
774 }
775
776 pub fn appearance(mut self, appearance: crate::platform::Appearance) -> Self {
780 self.appearance = Some(appearance);
781 self
782 }
783
784 pub fn status_bar(mut self, setting: crate::StatusBarSetting) -> Self {
787 self.status_bar = Some(setting);
788 self
789 }
790
791 pub fn main_window(mut self, options: crate::desktop::MainWindowOptions) -> Self {
796 self.main_window = Some(options);
797 self
798 }
799
800 #[doc(hidden)]
804 pub fn main_window_json(self, json: &str) -> Self {
805 let options = serde_json::from_str::<serde_json::Value>(json)
806 .map_err(|e| e.to_string())
807 .and_then(|v| {
808 crate::desktop::MainWindowOptions::from_json(&v).map_err(|e| e.to_string())
809 });
810 match options {
811 Ok(options) => self.main_window(options),
812 Err(e) => {
813 log::warn!("nsh.json: window: {e}");
814 self
815 }
816 }
817 }
818
819 pub fn main_window_ref(&self) -> Option<&crate::desktop::MainWindowOptions> {
821 self.main_window.as_ref()
822 }
823
824 pub fn application(mut self, options: crate::desktop::ApplicationOptions) -> Self {
828 self.application = Some(options);
829 self
830 }
831
832 #[doc(hidden)]
836 pub fn application_json(self, json: &str) -> Self {
837 let options = serde_json::from_str::<serde_json::Value>(json)
838 .map_err(|e| e.to_string())
839 .and_then(|v| {
840 crate::desktop::ApplicationOptions::from_json(&v).map_err(|e| e.to_string())
841 });
842 match options {
843 Ok(options) => self.application(options),
844 Err(e) => {
845 log::warn!("nsh.json: application: {e}");
846 self
847 }
848 }
849 }
850
851 pub fn application_ref(&self) -> Option<&crate::desktop::ApplicationOptions> {
853 self.application.as_ref()
854 }
855
856 pub fn status_bar_ref(&self) -> Option<crate::StatusBarSetting> {
858 self.status_bar
859 }
860
861 pub fn appearance_ref(&self) -> Option<crate::platform::Appearance> {
864 self.appearance
865 }
866
867 pub fn tokens_ref(&self) -> Option<&super::Tokens> {
869 self.tokens.as_deref()
870 }
871
872 pub fn fonts(&self) -> &[Arc<[u8]>] {
874 &self.fonts
875 }
876
877 pub fn of<C: Component>() -> Self
879 where
880 C::Props: Default,
881 {
882 Self::new::<C>(C::Props::default)
883 }
884
885 pub(crate) fn element(&self) -> super::AnyElement {
887 (self.make)()
888 }
889}
890
891impl fmt::Debug for Root {
892 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
893 f.write_str("Root")
894 }
895}
896
897pub(crate) fn missing_instance() -> Box<dyn AnyInstance> {
900 unreachable!("a component made by name is made by its registry")
901}
902
903pub(crate) fn missing_spec() -> ComponentSpec {
905 unreachable!("a component made by name is made by its registry")
906}
907
908pub(crate) fn make_instance<C: Component>() -> Box<dyn AnyInstance> {
910 Box::new(super::once::OnceInstance::<C>::new())
911}
912
913#[derive(Clone)]
914struct ComponentType {
915 spec: Arc<ComponentSpec>,
916 make: fn() -> Box<dyn AnyInstance>,
917 id: TypeId,
919}
920
921#[derive(Clone)]
922struct ModuleType {
923 spec: Arc<ModuleSpec>,
924 type_name: &'static str,
926}
927
928#[derive(Clone)]
929struct ClassType {
930 spec: Arc<ClassSpec>,
931 type_name: &'static str,
933}
934
935#[derive(Debug, Clone, Default)]
938#[non_exhaustive]
939pub struct BuiltInScrollbar {
940 pub target: crate::NodeId,
942 pub horizontal: bool,
944 pub theme: Option<Arc<crate::JsonValue>>,
947 pub theme_value: Option<super::AnyValue>,
951 pub app_theme: Option<super::AnyValue>,
954}
955
956pub type ScrollbarSource = fn(&BuiltInScrollbar) -> Option<super::AnyElement>;
961
962#[derive(Clone)]
969pub struct ScrollbarThemeValue {
970 source: ScrollbarSource,
971 theme: super::AnyValue,
972}
973
974impl ScrollbarThemeValue {
975 pub fn new(source: ScrollbarSource, theme: super::AnyValue) -> Self {
978 Self { source, theme }
979 }
980
981 pub fn source(&self) -> ScrollbarSource {
983 self.source
984 }
985
986 pub fn theme(&self) -> &super::AnyValue {
988 &self.theme
989 }
990}
991
992impl PartialEq for ScrollbarThemeValue {
993 fn eq(&self, other: &Self) -> bool {
994 self.theme == other.theme
995 }
996}
997
998impl std::fmt::Debug for ScrollbarThemeValue {
999 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1000 f.debug_tuple("ScrollbarThemeValue")
1001 .field(&self.theme)
1002 .finish()
1003 }
1004}
1005
1006#[derive(Clone, Default)]
1009pub struct Registry {
1010 types: Arc<FxHashMap<&'static str, ComponentType>>,
1011 modules: Arc<FxHashMap<&'static str, ModuleType>>,
1012 classes: Arc<FxHashMap<(Option<&'static str>, &'static str), ClassType>>,
1015 reexports: Arc<(Vec<&'static str>, Vec<&'static str>)>,
1017 native_values: Arc<Vec<&'static str>>,
1020 namespace: Option<&'static str>,
1023 ui_set: Option<&'static str>,
1025 assets: Arc<Vec<(&'static [crate::platform::Os], &'static [super::AssetFile])>>,
1028 tokens: Option<super::TokenSource>,
1030 scrollbars: Option<ScrollbarSource>,
1032 submodules: Arc<Vec<Registry>>,
1035 setups: Arc<Vec<Setup>>,
1037 fakes: Arc<Vec<(&'static str, Arc<dyn crate::fake::Fake>)>>,
1040}
1041
1042type Setup = Arc<dyn Fn() + Send + Sync>;
1044
1045impl fmt::Debug for Registry {
1046 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1047 f.debug_set().entries(self.types.keys()).finish()
1048 }
1049}
1050
1051impl Registry {
1052 pub fn new() -> Self {
1054 Self::default()
1055 }
1056
1057 #[track_caller]
1066 pub fn register<C: Component>(&mut self) -> &mut Self {
1067 let spec = ComponentSpec::of::<C>();
1068 let mut refs = Vec::new();
1069 (C::METHODS.refs)(&mut refs);
1070 self.register_erased(spec, make_instance::<C>, TypeId::of::<C>(), refs)
1071 }
1072
1073 #[track_caller]
1076 #[inline(never)]
1077 fn register_erased(
1078 &mut self,
1079 spec: ComponentSpec,
1080 make: fn() -> Box<dyn AnyInstance>,
1081 id: TypeId,
1082 refs: Vec<&'static ClassDef>,
1083 ) -> &mut Self {
1084 let types = Arc::make_mut(&mut self.types);
1085 if let Some(old) = types.get(spec.name) {
1086 let set = self.ui_set.or(self.namespace);
1087 panic!("{}", same_name(spec.name, old.id, id, set));
1088 }
1089 if self.classes.keys().any(|(_, name)| *name == spec.export) {
1090 panic!(
1091 "component `{}` is exported as `{}` like a class{}: rename one",
1092 spec.name,
1093 spec.export,
1094 of_set(self.ui_set.or(self.namespace)),
1095 );
1096 }
1097 if let Some(other) = types.values().find(|t| t.spec.export == spec.export) {
1098 panic!(
1099 "components `{}` and `{}` are both exported as `{}`{}: rename one",
1100 other.spec.name,
1101 spec.name,
1102 spec.export,
1103 of_set(self.ui_set.or(self.namespace)),
1104 );
1105 }
1106 types.insert(
1107 spec.name,
1108 ComponentType {
1109 spec: Arc::new(spec),
1110 make,
1111 id,
1112 },
1113 );
1114 self.classes_named(refs)
1115 }
1116
1117 #[track_caller]
1125 pub fn module<M: Module>(&mut self) -> &mut Self {
1126 let type_name = std::any::type_name::<M>();
1127 if self.classes.keys().any(|(_, name)| *name == M::NAME) {
1128 panic!(
1129 "module `{type_name}` is named `{}` like a class{}: rename one",
1130 M::NAME,
1131 of_set(self.ui_set.or(self.namespace))
1132 );
1133 }
1134 let modules = Arc::make_mut(&mut self.modules);
1135 if let Some(old) = modules.get(M::NAME) {
1136 panic!(
1137 "{}",
1138 same_module(
1139 M::NAME,
1140 old.type_name,
1141 type_name,
1142 self.ui_set.or(self.namespace)
1143 )
1144 );
1145 }
1146 modules.insert(
1147 M::NAME,
1148 ModuleType {
1149 spec: Arc::new(ModuleSpec::of::<M>()),
1150 type_name,
1151 },
1152 );
1153 let mut refs = Vec::new();
1154 for f in M::FUNCTIONS {
1155 (f.refs)(&mut refs);
1156 }
1157 self.classes_named(refs)
1158 }
1159
1160 #[track_caller]
1173 pub fn class<C: Class>(&mut self) -> &mut Self {
1174 self.class_def(C::DEF)
1175 }
1176
1177 #[track_caller]
1180 fn classes_named(&mut self, refs: Vec<&'static ClassDef>) -> &mut Self {
1181 for def in refs {
1182 self.class_def(def);
1183 }
1184 self
1185 }
1186
1187 #[track_caller]
1188 fn class_def(&mut self, def: &'static ClassDef) -> &mut Self {
1189 let type_name = (def.type_name)();
1190 let set = self.ui_set.or(self.namespace);
1191 if let Some(old) = self.classes.get(&(set, def.name)) {
1192 if (old.spec.def.type_id)() == (def.type_id)() {
1193 return self;
1194 }
1195 panic!("{}", same_class(def.name, old.type_name, type_name, set));
1196 }
1197 if self.modules.contains_key(def.name)
1198 || self.types.values().any(|t| t.spec.export == def.name)
1199 {
1200 panic!(
1201 "class `{type_name}` is named `{}` like a module or a component{}: rename one",
1202 def.name,
1203 of_set(set)
1204 );
1205 }
1206 Arc::make_mut(&mut self.classes).insert(
1207 (set, def.name),
1208 ClassType {
1209 spec: Arc::new(ClassSpec::of(def)),
1210 type_name,
1211 },
1212 );
1213 let mut refs = Vec::new();
1215 for m in def.members {
1216 (m.refs)(&mut refs);
1217 }
1218 self.classes_named(refs)
1219 }
1220
1221 pub fn reexport(&mut self, values: &[&'static str], types: &[&'static str]) -> &mut Self {
1224 let r = Arc::make_mut(&mut self.reexports);
1225 r.0.extend_from_slice(values);
1226 r.1.extend_from_slice(types);
1227 self
1228 }
1229
1230 #[track_caller]
1241 pub fn merged(sets: &[Registry]) -> Self {
1242 let mut out = Self::default();
1243 for set in sets.iter().flat_map(Registry::sets) {
1244 out.tokens = out.tokens.or(set.tokens);
1245 out.scrollbars = out.scrollbars.or(set.scrollbars);
1246 Arc::make_mut(&mut out.setups).extend(set.setups.iter().cloned());
1247 let fakes = Arc::make_mut(&mut out.fakes);
1248 for (name, fake) in set.fakes.iter() {
1249 assert!(
1250 fakes.iter().all(|(n, _)| n != name),
1251 "two fakes are named `{name}`, by two UI sets"
1252 );
1253 fakes.push((name, fake.clone()));
1254 }
1255 let types = Arc::make_mut(&mut out.types);
1256 for (name, ty) in set.types.iter() {
1257 if let Some(old) = types.insert(name, ty.clone()) {
1258 panic!("{}, by two UI sets", same_name(name, old.id, ty.id, None));
1259 }
1260 }
1261 }
1262 out
1263 }
1264
1265 pub fn ui_set(specifier: &'static str) -> Self {
1269 Self {
1270 ui_set: Some(specifier),
1271 ..Self::default()
1272 }
1273 }
1274
1275 pub fn specifier(&self) -> Option<&'static str> {
1278 self.ui_set.or(self.namespace)
1279 }
1280
1281 pub fn reexports(&self) -> (&[&'static str], &[&'static str]) {
1284 (&self.reexports.0, &self.reexports.1)
1285 }
1286
1287 #[track_caller]
1299 pub fn submodule(&mut self, set: Registry) -> &mut Self {
1300 let under = match (self.ui_set, set.ui_set) {
1301 (Some(parent), Some(child)) => child
1302 .strip_prefix(parent)
1303 .is_some_and(|rest| rest.len() > 1 && rest.starts_with('/')),
1304 _ => false,
1305 };
1306 assert!(
1307 under,
1308 "a submodule is a UI set under a path of its set's specifier: {:?} under {:?}",
1309 set.ui_set, self.ui_set
1310 );
1311 Arc::make_mut(&mut self.submodules).push(set);
1312 self
1313 }
1314
1315 pub fn sets(&self) -> Vec<&Registry> {
1319 let mut out = vec![self];
1320 for sub in self.submodules.iter() {
1321 out.extend(sub.sets());
1322 }
1323 out
1324 }
1325
1326 pub fn native_values(&mut self, values: &[&'static str]) -> &mut Self {
1329 Arc::make_mut(&mut self.native_values).extend_from_slice(values);
1330 self
1331 }
1332
1333 pub fn assets(&mut self, files: &'static [super::AssetFile]) -> &mut Self {
1339 self.assets_for(&[], files)
1340 }
1341
1342 pub fn assets_for(
1348 &mut self,
1349 targets: &'static [crate::platform::Os],
1350 files: &'static [super::AssetFile],
1351 ) -> &mut Self {
1352 Arc::make_mut(&mut self.assets).push((targets, files));
1353 self
1354 }
1355
1356 pub fn tokens_from(&mut self, source: super::TokenSource) -> &mut Self {
1359 self.tokens = Some(source);
1360 self
1361 }
1362
1363 pub fn scrollbars_from(&mut self, source: ScrollbarSource) -> &mut Self {
1368 self.scrollbars = Some(source);
1369 self
1370 }
1371
1372 pub(crate) fn scrollbar_source(&self) -> Option<ScrollbarSource> {
1375 self.scrollbars
1376 }
1377
1378 pub fn setup(&mut self, f: impl Fn() + Send + Sync + 'static) -> &mut Self {
1386 Arc::make_mut(&mut self.setups).push(Arc::new(f));
1387 self
1388 }
1389
1390 #[track_caller]
1402 pub fn fake(&mut self, name: &'static str, fake: Arc<dyn crate::fake::Fake>) -> &mut Self {
1403 assert!(
1404 self.fakes.iter().all(|(n, _)| *n != name),
1405 "two fakes are named `{name}`{}",
1406 of_set(self.ui_set.or(self.namespace))
1407 );
1408 Arc::make_mut(&mut self.fakes).push((name, fake));
1409 self
1410 }
1411
1412 #[doc(hidden)]
1415 pub fn fakes(&self) -> Vec<(&'static str, Arc<dyn crate::fake::Fake>)> {
1416 self.sets()
1417 .into_iter()
1418 .flat_map(|set| set.fakes.iter().cloned())
1419 .collect()
1420 }
1421
1422 pub(crate) fn run_setups(&self) {
1425 for setup in self.setups.iter() {
1426 setup();
1427 }
1428 }
1429
1430 pub(crate) fn run_setups_not_in(&self, old: &Registry) {
1433 for setup in self.setups.iter() {
1434 let known = old
1435 .setups
1436 .iter()
1437 .any(|o| std::ptr::addr_eq(Arc::as_ptr(o), Arc::as_ptr(setup)));
1438 if !known {
1439 setup();
1440 }
1441 }
1442 }
1443
1444 pub fn tokens(
1448 &self,
1449 json: Option<&str>,
1450 ) -> Option<Result<(super::Tokens, Vec<String>), String>> {
1451 self.tokens.map(|source| source(json))
1452 }
1453
1454 pub(crate) fn token_source(&self) -> Option<super::TokenSource> {
1456 self.tokens
1457 }
1458
1459 pub fn asset_files(&self) -> impl Iterator<Item = &'static super::AssetFile> + '_ {
1462 self.assets.iter().flat_map(|(_, files)| files.iter())
1463 }
1464
1465 pub fn scoped_asset_files(
1468 &self,
1469 ) -> impl Iterator<Item = (&'static [crate::platform::Os], &'static super::AssetFile)> + '_
1470 {
1471 self.assets
1472 .iter()
1473 .flat_map(|&(targets, files)| files.iter().map(move |file| (targets, file)))
1474 }
1475
1476 pub fn native_value_names(&self) -> &[&'static str] {
1478 &self.native_values
1479 }
1480
1481 pub(crate) fn runtime(namespace: &'static str) -> Self {
1483 Self {
1484 namespace: Some(namespace),
1485 ..Self::default()
1486 }
1487 }
1488
1489 pub fn namespace(&self) -> Option<&'static str> {
1492 self.namespace
1493 }
1494
1495 pub fn class_specs(&self) -> Vec<Arc<ClassSpec>> {
1497 let mut specs: Vec<_> = self.classes.values().map(|c| c.spec.clone()).collect();
1498 specs.sort_by_key(|s| s.name);
1499 specs
1500 }
1501
1502 pub fn module_specs(&self) -> Vec<Arc<ModuleSpec>> {
1504 let mut specs: Vec<_> = self.modules.values().map(|m| m.spec.clone()).collect();
1505 specs.sort_by_key(|s| s.name);
1506 specs
1507 }
1508
1509 pub fn function_members(&self, function: &str) -> Option<Arc<ModuleSpec>> {
1514 let exported = self.modules.values().any(|m| {
1515 m.spec.flat
1516 && m.spec
1517 .functions
1518 .iter()
1519 .any(|f| !f.getter && f.name == function)
1520 });
1521 exported
1522 .then(|| {
1523 self.modules
1524 .values()
1525 .find(|m| !m.spec.flat && m.spec.name == function)
1526 .map(|m| m.spec.clone())
1527 })
1528 .flatten()
1529 }
1530
1531 pub fn specs(&self) -> Vec<Arc<ComponentSpec>> {
1533 let mut specs: Vec<_> = self.types.values().map(|t| t.spec.clone()).collect();
1534 specs.sort_by(|a, b| a.export.cmp(&b.export).then(a.name.cmp(b.name)));
1535 specs
1536 }
1537
1538 pub fn undocumented(&self) -> Vec<String> {
1547 let mut out = Vec::new();
1548 let specs = self.specs();
1549 for c in &specs {
1550 if c.doc.is_empty() {
1551 out.push(c.export.clone());
1552 }
1553 for p in c.props.iter().filter(|p| p.doc.is_empty()) {
1554 out.push(format!("{}.{}", c.export, p.name));
1555 }
1556 for e in c.events.iter().filter(|e| e.doc.is_empty()) {
1557 out.push(format!("{}.{}", c.export, handler_name(e.name)));
1558 }
1559 for m in c.methods.iter().filter(|m| m.doc.is_empty()) {
1560 out.push(format!("{}.{}", c.export, m.name));
1561 }
1562 }
1563 for m in self.module_specs() {
1564 let merged = specs.iter().any(|c| c.export == m.name)
1565 || (!m.flat && self.function_members(m.name).is_some());
1566 if m.doc.is_empty() && !merged && !m.flat {
1567 out.push(m.name.to_owned());
1568 }
1569 for f in m.functions.iter().filter(|f| f.doc.is_empty()) {
1570 out.push(if m.flat {
1571 f.name.to_owned()
1572 } else {
1573 format!("{}.{}", m.name, f.name)
1574 });
1575 }
1576 }
1577 for c in self.class_specs() {
1578 if c.doc.is_empty() {
1579 out.push(c.name.to_owned());
1580 }
1581 let documented_getter = |name: &str| {
1582 c.members
1583 .iter()
1584 .any(|m| m.kind == MemberKind::Getter && m.name == name && !m.doc.is_empty())
1585 };
1586 for m in c.members.iter().filter(|m| m.doc.is_empty()) {
1587 match m.kind {
1588 MemberKind::Constructor => out.push(format!("new {}", c.name)),
1589 MemberKind::Setter if documented_getter(m.name) => {}
1590 _ => out.push(format!("{}.{}", c.name, m.name)),
1591 }
1592 }
1593 }
1594 out
1595 }
1596
1597 pub(crate) fn make_type(
1600 &self,
1601 id: TypeId,
1602 ) -> Option<(Arc<ComponentSpec>, Box<dyn AnyInstance>)> {
1603 self.types
1604 .values()
1605 .find(|t| t.id == id)
1606 .map(|t| (t.spec.clone(), (t.make)()))
1607 }
1608
1609 pub(crate) fn make(&self, name: &str) -> Option<(Arc<ComponentSpec>, Box<dyn AnyInstance>)> {
1611 self.types.get(name).map(|t| (t.spec.clone(), (t.make)()))
1612 }
1613}
1614
1615fn same_name(name: &str, old: TypeId, new: TypeId, set: Option<&str>) -> String {
1617 if old == new {
1618 format!("component `{name}` is registered twice{}", of_set(set))
1619 } else {
1620 format!(
1621 "two different types named `{name}` are registered{} (two versions of one crate?)",
1622 of_set(set)
1623 )
1624 }
1625}
1626
1627fn same_module(name: &str, old: &str, new: &str, set: Option<&str>) -> String {
1629 if old == new {
1630 format!("module `{old}` is registered twice{}", of_set(set))
1631 } else {
1632 format!(
1633 "modules `{old}` and `{new}` are both named `{name}`{}: rename one",
1634 of_set(set)
1635 )
1636 }
1637}
1638
1639fn same_class(name: &str, old: &str, new: &str, set: Option<&str>) -> String {
1641 if old == new {
1642 format!("class `{old}` is registered twice{}", of_set(set))
1643 } else {
1644 format!(
1645 "classes `{old}` and `{new}` are both named `{name}`{}: rename one",
1646 of_set(set)
1647 )
1648 }
1649}
1650
1651fn of_set(set: Option<&str>) -> String {
1653 set.map(|s| format!(" in `{s}`")).unwrap_or_default()
1654}
1655
1656pub fn declarations(registry: &Registry, omit: &[&str]) -> String {
1665 let specs = registry.specs();
1666 let modules = registry.module_specs();
1667 let classes = registry.class_specs();
1668 use std::fmt::Write as _;
1669 let mut out = String::new();
1670 let doc = |out: &mut String, indent: &str, doc: &str| {
1671 if !doc.is_empty() {
1672 let _ = writeln!(out, "{indent}/** {doc} */");
1673 }
1674 };
1675 let mut types = TsTypes::default();
1677 for spec in &specs {
1678 types.merge(&spec.types);
1679 }
1680 for m in &modules {
1681 types.merge(&m.types);
1682 }
1683 for c in &classes {
1684 types.merge(&c.types);
1685 }
1686 for declaration in types.declarations() {
1687 let _ = write!(out, "{declaration}\n\n");
1688 }
1689 let module_of = |name: &str| modules.iter().find(|m| m.name == name);
1690 let signatures = |f: &FunctionSpec| {
1692 let one = |params: &[(&str, String, bool)], returns: &Option<String>| {
1693 let params = params
1694 .iter()
1695 .map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
1696 .collect::<Vec<_>>()
1697 .join(", ");
1698 let value = returns.clone().unwrap_or_else(|| "void".to_owned());
1699 let returns = if f.promises() {
1700 format!("Promise<{value}>")
1701 } else {
1702 value
1703 };
1704 (params, returns)
1705 };
1706 if f.overloads.is_empty() {
1707 vec![one(&f.params, &f.returns)]
1708 } else {
1709 f.overloads
1710 .iter()
1711 .map(|(params, returns)| one(params, returns))
1712 .collect()
1713 }
1714 };
1715 let module_object = |out: &mut String, m: &ModuleSpec| {
1717 out.push_str("{\n");
1718 for f in &m.functions {
1719 for (params, returns) in signatures(f) {
1720 doc(out, " ", f.doc);
1721 if f.getter {
1722 let _ = writeln!(out, " readonly {}: {returns};", f.name);
1723 continue;
1724 }
1725 let _ = writeln!(out, " {}({params}): {returns};", f.name);
1726 }
1727 }
1728 for constant in &m.constants {
1729 doc(out, " ", constant.doc);
1730 let _ = writeln!(
1731 out,
1732 " readonly {}: {};",
1733 constant.name,
1734 constant.value.ts_type()
1735 );
1736 }
1737 out.push('}');
1738 };
1739 for spec in &specs {
1740 let (generic, params, extends) = match spec.items() {
1744 Some(_) => ("<T>", "<T>", ", ListItemsProps<T>"),
1745 None if spec.generic => ("<T>", "<T = any>", ""),
1746 None => ("", "", ""),
1747 };
1748 let mut omit: Vec<&str> = HOST_PROPS
1751 .iter()
1752 .copied()
1753 .filter(|&h| !spec.host_props().any(|p| p == h))
1754 .collect();
1755 if !spec.methods.is_empty() {
1756 omit.insert(0, "ref");
1757 }
1758 let host = if omit.is_empty() {
1759 "ComponentHostProps".to_owned()
1760 } else {
1761 let names = omit.iter().map(|n| format!("\"{n}\"")).collect::<Vec<_>>();
1762 format!("Omit<ComponentHostProps, {}>", names.join(" | "))
1763 };
1764 if !spec.methods.is_empty() {
1765 let _ = write!(
1766 out,
1767 "/** The ref of `{0}`: its methods. */\nexport interface {0}Ref {{\n /** The component's host node. */\n readonly node: ViewRef;\n",
1768 spec.export
1769 );
1770 for m in &spec.methods {
1771 doc(&mut out, " ", m.doc);
1772 let params = m
1773 .params
1774 .iter()
1775 .map(|(n, ts, optional)| {
1776 format!("{n}{}: {ts}", if *optional { "?" } else { "" })
1777 })
1778 .collect::<Vec<_>>()
1779 .join(", ");
1780 let returns = match &m.returns {
1781 Some(ts) => format!("Promise<{ts}>"),
1782 None => "void".to_owned(),
1783 };
1784 let _ = writeln!(out, " {}({params}): {returns};", m.name);
1785 }
1786 out.push_str("}\n\n");
1787 }
1788 let _ = writeln!(
1789 out,
1790 "export interface {}Props{params} extends {host}{extends} {{",
1791 spec.export
1792 );
1793 if !spec.methods.is_empty() {
1794 let _ = writeln!(
1795 out,
1796 " ref?: {0}Ref | ((ref: {0}Ref) => void);",
1797 spec.export
1798 );
1799 }
1800 for p in spec.props.iter().filter(|p| p.kind != PropKind::Items) {
1801 doc(&mut out, " ", p.doc);
1802 let optional = if p.optional { "?" } else { "" };
1803 let _ = writeln!(out, " {}{optional}: {};", p.name, p.ts);
1804 }
1805 for e in &spec.events {
1806 doc(&mut out, " ", e.doc);
1807 let handler = handler_name(e.name);
1808 let arg = if e.data == "void" {
1809 String::new()
1810 } else {
1811 format!("{}: {}", e.arg, e.data)
1812 };
1813 let _ = writeln!(out, " {handler}?: ({arg}) => void;");
1814 }
1815 out.push_str("}\n\n");
1816 if omit.contains(&spec.export.as_str()) {
1817 continue;
1818 }
1819 doc(&mut out, "", spec.doc);
1820 let mut with = String::new();
1822 if let Some(m) = module_of(&spec.export) {
1823 with.push_str(" & ");
1824 module_object(&mut with, m);
1825 }
1826 let _ = write!(
1827 out,
1828 "export declare const {}: ({params}(props: {}Props{generic}) => JSX.Element){with};\n\n",
1829 spec.export, spec.export,
1830 );
1831 }
1832 for m in &modules {
1833 if specs.iter().any(|s| s.export == m.name)
1834 || (!m.flat && registry.function_members(m.name).is_some())
1835 {
1836 continue;
1837 }
1838 if m.flat {
1839 for f in m
1840 .functions
1841 .iter()
1842 .filter(|f| !f.getter && !omit.contains(&f.name))
1843 {
1844 for (params, returns) in signatures(f) {
1845 doc(&mut out, "", f.doc);
1846 let _ = writeln!(
1847 out,
1848 "export declare function {}({params}): {returns};",
1849 f.name
1850 );
1851 }
1852 if let Some(members) = registry.function_members(f.name) {
1854 let _ = writeln!(out, "export declare namespace {} {{", f.name);
1855 for member in &members.functions {
1856 for (params, returns) in signatures(member) {
1857 doc(&mut out, " ", member.doc);
1858 let _ = if member.getter {
1859 writeln!(out, " const {}: {returns};", member.name)
1860 } else {
1861 writeln!(out, " function {}({params}): {returns};", member.name)
1862 };
1863 }
1864 }
1865 for constant in &members.constants {
1866 doc(&mut out, " ", constant.doc);
1867 let _ = writeln!(
1868 out,
1869 " const {}: {};",
1870 constant.name,
1871 constant.value.ts_type()
1872 );
1873 }
1874 out.push_str("}\n");
1875 }
1876 out.push('\n');
1877 }
1878 for constant in &m.constants {
1879 if !omit.contains(&constant.name) {
1880 doc(&mut out, "", constant.doc);
1881 let _ = writeln!(
1882 out,
1883 "export declare const {}: {};\n",
1884 constant.name,
1885 constant.value.ts_type()
1886 );
1887 }
1888 }
1889 if m.default && !omit.contains(&"default") {
1890 let _ = write!(out, "declare const defaultExport: ");
1891 module_object(&mut out, m);
1892 for native in registry.native_value_names() {
1894 let _ = write!(out, " & {{ {native}: typeof {native} }}");
1895 }
1896 out.push_str(";\nexport default defaultExport;\n\n");
1897 }
1898 continue;
1899 }
1900 doc(&mut out, "", m.doc);
1901 let _ = write!(out, "export interface {}Module ", m.name);
1902 module_object(&mut out, m);
1903 out.push_str("\n\n");
1904 if !omit.contains(&m.name) {
1905 doc(&mut out, "", m.doc);
1906 let _ = write!(out, "export declare const {0}: {0}Module;\n\n", m.name);
1907 }
1908 if m.default && !omit.contains(&"default") {
1909 let _ = write!(
1910 out,
1911 "declare const defaultExport: {}Module;\nexport default defaultExport;\n\n",
1912 m.name
1913 );
1914 }
1915 }
1916 for c in classes.iter().filter(|c| !omit.contains(&c.name)) {
1917 class_declaration(&mut out, c);
1918 }
1919 out
1920}
1921
1922fn class_declaration(out: &mut String, c: &ClassSpec) {
1924 use std::fmt::Write as _;
1925 let doc = |out: &mut String, indent: &str, doc: &str| {
1926 if !doc.is_empty() {
1927 let _ = writeln!(out, "{indent}/** {doc} */");
1928 }
1929 };
1930 doc(out, "", c.doc);
1931 if c.def.interface {
1932 let _ = writeln!(out, "export interface {} {{", c.name);
1934 for m in &c.members {
1935 let params = m
1936 .params
1937 .iter()
1938 .map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
1939 .collect::<Vec<_>>()
1940 .join(", ");
1941 let value = m.returns.clone().unwrap_or_else(|| "void".to_owned());
1942 let returns = if m.is_async {
1943 format!("Promise<{value}>")
1944 } else {
1945 value
1946 };
1947 doc(out, " ", m.doc);
1948 let has_setter = |name| {
1949 c.members
1950 .iter()
1951 .any(|s| s.kind == MemberKind::Setter && s.name == name)
1952 };
1953 let _ = match m.kind {
1954 MemberKind::Method => writeln!(out, " {}({params}): {returns};", m.name),
1955 MemberKind::Getter if has_setter(m.name) => {
1956 writeln!(out, " {}: {returns};", m.name)
1957 }
1958 MemberKind::Getter => writeln!(out, " readonly {}: {returns};", m.name),
1959 _ => Ok(()),
1962 };
1963 }
1964 out.push_str("}\n\n");
1965 return;
1966 }
1967 let _ = writeln!(out, "export declare class {} {{", c.name);
1968 if !c.members.iter().any(|m| m.kind == MemberKind::Constructor) {
1969 out.push_str(" /** Made by the class's members only. */\n private constructor();\n");
1970 }
1971 let one = |m: &super::MemberSpec, params: &[(&str, String, bool)], returns: &Option<String>| {
1972 let params = params
1973 .iter()
1974 .map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
1975 .collect::<Vec<_>>()
1976 .join(", ");
1977 let value = returns.clone().unwrap_or_else(|| "void".to_owned());
1978 let returns = if m.is_async {
1979 format!("Promise<{value}>")
1980 } else {
1981 value
1982 };
1983 (params, returns)
1984 };
1985 for m in &c.members {
1986 if !m.overloads.is_empty() {
1987 for (params, returns) in &m.overloads {
1988 doc(out, " ", m.doc);
1989 let (params, returns) = one(m, params, returns);
1990 let _ = match m.kind {
1991 MemberKind::Static => {
1992 writeln!(out, " static {}({params}): {returns};", m.name)
1993 }
1994 _ => writeln!(out, " {}({params}): {returns};", m.name),
1995 };
1996 }
1997 continue;
1998 }
1999 doc(out, " ", m.doc);
2000 let (params, returns) = one(m, &m.params, &m.returns);
2001 let _ = match m.kind {
2002 MemberKind::Constructor => writeln!(out, " constructor({params});"),
2003 MemberKind::Method => writeln!(out, " {}({params}): {returns};", m.name),
2004 MemberKind::Getter => writeln!(out, " get {}(): {returns};", m.name),
2005 MemberKind::Setter => writeln!(out, " set {}({params});", m.name),
2006 MemberKind::Static => writeln!(out, " static {}({params}): {returns};", m.name),
2007 };
2008 }
2009 out.push_str(
2010 " /** 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",
2011 );
2012}
2013
2014fn handler_name(event: &str) -> String {
2016 let mut chars = event.chars();
2017 match chars.next() {
2018 Some(first) => format!("on{}{}", first.to_ascii_uppercase(), chars.as_str()),
2019 None => "on".to_owned(),
2020 }
2021}
2022
2023#[cfg(test)]
2024mod tests {
2025 use super::*;
2026 use crate::prelude::*;
2027
2028 #[derive(Default)]
2029 struct Stepper;
2030
2031 #[derive(Clone, PartialEq, Props)]
2033 struct StepperProps {
2034 value: f64,
2036 #[prop(default)]
2037 size: StepperSize,
2038 max_value: Option<f64>,
2039 label: Option<Slot>,
2041 children: Children,
2042 }
2043
2044 #[derive(Clone, Copy, PartialEq, Default, PropEnum)]
2045 enum StepperSize {
2046 #[default]
2047 Regular,
2048 ExtraLarge,
2049 }
2050
2051 #[derive(Event)]
2052 enum StepperEvent {
2053 Change {
2055 new_value: f64,
2056 },
2057 #[args(limit)]
2058 Limit(u32),
2059 Reset,
2060 }
2061
2062 struct StepperApi;
2063
2064 #[methods]
2065 impl StepperApi {
2066 pub(crate) fn jump_to(&self, value: f64) {
2068 let _ = value;
2069 }
2070
2071 pub(crate) fn value(&self) -> f64 {
2072 0.0
2073 }
2074
2075 #[allow(dead_code)]
2077 fn clamp(&self, value: f64) -> f64 {
2078 value
2079 }
2080 }
2081
2082 impl Component for Stepper {
2083 type Props = StepperProps;
2084 type Event = StepperEvent;
2085 const METHODS: Methods = Methods::of::<StepperApi>();
2086 const DOC: &'static str = "Picks a number.";
2087
2088 fn view(_: StepperProps, _: super::super::Scope<StepperEvent>) -> impl IntoElement {
2089 view()
2090 }
2091 }
2092
2093 #[test]
2094 fn the_declarations_come_from_the_types() {
2095 let mut registry = Registry::new();
2096 registry.register::<Stepper>();
2097 let ts = declarations(®istry, &[]);
2098 for line in [
2099 " /** The value. */\n value: number;",
2100 "export type StepperSize = \"regular\" | \"extraLarge\";",
2101 " size?: StepperSize;",
2102 " maxValue?: number | null;",
2103 " /** Above the control. */\n label?: JSX.Element;",
2104 " children?: JSX.Element;",
2105 " /** The value changed. */\n onChange?: (event: { newValue: number }) => void;",
2106 " onLimit?: (event: { limit: number }) => void;",
2107 " onReset?: () => void;",
2108 "/** Picks a number. */",
2109 "export interface StepperRef {",
2110 " /** Jumps to `value`. */\n jumpTo(value: number): void;",
2111 " value(): Promise<number>;",
2112 "export interface StepperProps extends Omit<ComponentHostProps, \"ref\"> {\n ref?: StepperRef | ((ref: StepperRef) => void);",
2113 "export declare const Stepper: ((props: StepperProps) => JSX.Element);",
2114 ] {
2115 assert!(ts.contains(line), "missing {line:?} in\n{ts}");
2116 }
2117 assert!(!ts.contains("clamp"), "a helper is not a method:\n{ts}");
2118 assert_eq!(StepperApi::METHODS.len(), 2);
2119 let mut props = StepperProps::initial();
2120 let size = |json| {
2121 let specs = StepperProps::spec(&mut TsTypes::default());
2122 let decode = specs
2123 .iter()
2124 .find(|p| p.name == "size")
2125 .unwrap()
2126 .decode
2127 .unwrap();
2128 super::super::json_host::decode(decode, json)
2129 };
2130 assert!(
2131 props
2132 .set("size", Some(size(serde_json::json!("extraLarge")).unwrap()))
2133 .unwrap()
2134 );
2135 assert!(props.size == StepperSize::ExtraLarge);
2136 assert!(size(serde_json::json!("huge")).is_err());
2140 assert!(props.set("size", Some(AnyValue::new(1.0f64))).is_err());
2141 assert!(props.set("size", None).unwrap());
2142 assert!(props.size == StepperSize::Regular);
2143 let data = |e: &StepperEvent| super::super::json_host::event_data(e);
2144 assert_eq!(
2145 data(&StepperEvent::Change { new_value: 2.5 }),
2146 Some(serde_json::json!({ "newValue": 2.5 }))
2147 );
2148 assert_eq!(
2149 data(&StepperEvent::Limit(3)),
2150 Some(serde_json::json!({ "limit": 3 }))
2151 );
2152 assert_eq!(data(&StepperEvent::Reset), None);
2153 assert_eq!(StepperEvent::Reset.name(), "reset");
2154 }
2155
2156 #[test]
2157 fn exports_without_docs_are_listed() {
2158 let mut registry = Registry::new();
2159 registry.register::<Stepper>();
2160 assert_eq!(
2163 registry.undocumented(),
2164 [
2165 "Stepper.size",
2166 "Stepper.maxValue",
2167 "Stepper.children",
2168 "Stepper.onLimit",
2169 "Stepper.onReset",
2170 "Stepper.value",
2171 ]
2172 );
2173 let mut r = Registry::ui_set("test/maker");
2174 r.module::<Maker>();
2175 assert_eq!(r.undocumented(), ["Maker.make", "new Lonely"]);
2176 }
2177
2178 #[crate::element::class]
2180 struct Lonely;
2181
2182 #[crate::element::class]
2183 impl Lonely {
2184 pub(crate) fn new() -> Self {
2185 Lonely
2186 }
2187 }
2188
2189 #[crate::element::module]
2191 struct Maker;
2192
2193 #[crate::element::module]
2194 impl Maker {
2195 pub(crate) fn make() -> Instance<Lonely> {
2196 Instance::new(Lonely)
2197 }
2198 }
2199
2200 #[test]
2201 fn the_classes_a_signature_names_are_registered_with_it() {
2202 let mut r = Registry::ui_set("test/maker");
2203 r.module::<Maker>();
2204 let names: Vec<_> = r.class_specs().iter().map(|c| c.name).collect();
2207 assert_eq!(names, ["Lonely"]);
2208 let ts = declarations(&r, &[]);
2209 assert!(ts.contains("export declare class Lonely"), "{ts}");
2210 assert!(ts.contains("make(): Lonely;"), "{ts}");
2211 r.class::<Lonely>();
2213 assert_eq!(r.class_specs().len(), 1);
2214 let _ = Registry::merged(&[r]);
2215 }
2216
2217 #[crate::element::module]
2219 struct Checks;
2220
2221 #[crate::element::module(flat)]
2222 impl Checks {
2223 pub(crate) fn check(name: String) {
2225 let _ = name;
2226 }
2227 }
2228
2229 #[crate::element::module]
2231 struct CheckVariants;
2232
2233 #[crate::element::module(name = "check")]
2234 impl CheckVariants {
2235 pub(crate) const COUNT: u32 = 2;
2237
2238 pub(crate) fn skip(name: String) {
2240 let _ = name;
2241 }
2242
2243 pub(crate) fn todo(name: String) {
2244 let _ = name;
2245 }
2246 }
2247
2248 #[crate::element::module]
2250 struct Loose;
2251
2252 #[crate::element::module(name = "loose")]
2253 impl Loose {
2254 pub(crate) fn nothing() {}
2256 }
2257
2258 #[test]
2259 fn a_module_named_like_a_function_puts_its_functions_on_it() {
2260 let mut r = Registry::ui_set("test/checks");
2261 r.module::<Checks>()
2262 .module::<CheckVariants>()
2263 .module::<Loose>();
2264 assert_eq!(r.function_members("check").unwrap().name, "check");
2265 assert!(r.function_members("loose").is_none());
2266 let ts = declarations(&r, &[]);
2267 assert!(
2268 ts.contains(
2269 "/** Declares a check. */\n\
2270 export declare function check(name: string): void;\n\
2271 export declare namespace check {\n \
2272 /** Declares a check that does not run. */\n \
2273 function skip(name: string): void;\n \
2274 function todo(name: string): void;\n \
2275 /** How many variants there are. */\n \
2276 const COUNT: number;\n}\n"
2277 ),
2278 "{ts}"
2279 );
2280 assert!(
2281 !ts.contains("CheckVariants") && !ts.contains("checkModule"),
2282 "{ts}"
2283 );
2284 assert!(
2285 ts.contains("export declare const loose: looseModule;"),
2286 "{ts}"
2287 );
2288 assert_eq!(r.undocumented(), ["check.todo"]);
2290 let described = super::super::description::SetDescription::of(&r).unwrap();
2291 let exports: Vec<_> = described
2292 .exports
2293 .iter()
2294 .map(|e| (e.name.as_str(), e.kind))
2295 .collect();
2296 assert_eq!(
2297 exports,
2298 [
2299 ("check", super::super::description::ExportKind::Function),
2300 ("loose", super::super::description::ExportKind::Module)
2301 ]
2302 );
2303 }
2304
2305 mod clash {
2306 #[crate::element::class]
2308 pub(super) struct Lonely;
2309
2310 #[crate::element::class]
2311 impl Lonely {
2312 pub(super) fn new() -> Self {
2313 Lonely
2314 }
2315 }
2316 }
2317
2318 #[test]
2319 fn a_clash_through_a_signature_names_both_types() {
2320 let mut r = Registry::ui_set("test/maker");
2321 r.class::<clash::Lonely>();
2322 let failed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2324 r.module::<Maker>();
2325 }))
2326 .unwrap_err();
2327 let message = failed.downcast_ref::<String>().unwrap();
2328 assert!(
2329 message.contains("`nsh_core::element::component::tests::clash::Lonely`")
2330 && message.contains("`nsh_core::element::component::tests::Lonely`"),
2331 "{message}"
2332 );
2333 }
2334
2335 #[test]
2336 fn components_are_named_after_their_types() {
2337 let mut registry = Registry::ui_set("test/ui");
2338 registry.register::<Stepper>();
2339 let specs = registry.specs();
2340 assert_eq!(
2341 specs[0].name,
2342 "nsh_core::element::component::tests::Stepper"
2343 );
2344 assert_eq!(specs[0].export, "Stepper");
2345 assert_eq!(export_name("app::picker::Picker<app::Fruit>"), "Picker");
2346 assert_eq!(export_name("Bare"), "Bare");
2347 }
2348
2349 mod other {
2350 use crate::prelude::*;
2351
2352 #[derive(Default)]
2354 pub(super) struct Stepper;
2355
2356 impl Component for Stepper {
2357 type Props = ();
2358 type Event = NoEvent;
2359
2360 fn view(_: (), _: crate::element::Scope<NoEvent>) -> impl IntoElement {
2361 view()
2362 }
2363 }
2364 }
2365
2366 #[test]
2367 #[should_panic(
2368 expected = "components `nsh_core::element::component::tests::Stepper` and `nsh_core::element::component::tests::other::Stepper` are both exported as `Stepper` in `test/ui`"
2369 )]
2370 fn two_components_of_one_set_cannot_share_an_export() {
2371 Registry::ui_set("test/ui")
2372 .register::<Stepper>()
2373 .register::<other::Stepper>();
2374 }
2375
2376 #[test]
2377 #[should_panic(
2378 expected = "component `nsh_core::element::component::tests::Stepper` is registered twice"
2379 )]
2380 fn a_component_is_registered_once() {
2381 Registry::new().register::<Stepper>().register::<Stepper>();
2382 }
2383
2384 #[test]
2387 fn a_sets_submodules_come_with_it() {
2388 let mut sub = Registry::ui_set("test/set/sub");
2389 sub.register::<Stepper>();
2390 let mut set = Registry::ui_set("test/set");
2391 set.submodule(sub);
2392 let specifiers: Vec<_> = set.sets().iter().map(|s| s.specifier()).collect();
2393 assert_eq!(specifiers, [Some("test/set"), Some("test/set/sub")]);
2394 assert_eq!(Registry::merged(&[set]).specs().len(), 1);
2395 let elsewhere = std::panic::catch_unwind(|| {
2397 Registry::ui_set("test/set").submodule(Registry::ui_set("test/settings"));
2398 });
2399 assert!(elsewhere.is_err());
2400 }
2401
2402 #[test]
2403 fn sets_may_share_exports_but_not_components() {
2404 let mut a = Registry::ui_set("test/a");
2405 a.register::<Stepper>();
2406 let mut b = Registry::ui_set("test/b");
2407 b.register::<other::Stepper>();
2408 let merged = Registry::merged(&[a.clone(), b]);
2409 assert_eq!(merged.specs().len(), 2);
2410 let twice = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2411 Registry::merged(&[a.clone(), a])
2412 }));
2413 let message = *twice.unwrap_err().downcast::<String>().unwrap();
2414 assert_eq!(
2415 message,
2416 "component `nsh_core::element::component::tests::Stepper` is registered twice, by two UI sets"
2417 );
2418 }
2419
2420 struct NoFake;
2421
2422 impl crate::fake::Fake for NoFake {
2423 fn install(&self) {}
2424
2425 fn call(&self, _: &str, _: &[crate::JsonValue]) -> Result<crate::JsonValue, String> {
2426 Ok(crate::JsonValue::Null)
2427 }
2428 }
2429
2430 #[test]
2432 fn fake_names_are_unique_across_sets() {
2433 let mut a = Registry::ui_set("test/a");
2434 a.fake("test/mic", Arc::new(NoFake));
2435 let mut b = Registry::ui_set("test/b");
2436 b.fake("test/camera", Arc::new(NoFake));
2437 let names: Vec<_> = Registry::merged(&[a.clone(), b])
2438 .fakes()
2439 .into_iter()
2440 .map(|(name, _)| name)
2441 .collect();
2442 assert_eq!(names, ["test/mic", "test/camera"]);
2443 let mut c = Registry::ui_set("test/c");
2444 c.fake("test/mic", Arc::new(NoFake));
2445 let twice =
2446 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| Registry::merged(&[a, c])));
2447 let message = *twice.unwrap_err().downcast::<String>().unwrap();
2448 assert_eq!(message, "two fakes are named `test/mic`, by two UI sets");
2449 }
2450}
2451
2452#[cfg(test)]
2453mod root_tests {
2454 use super::Root;
2455 use crate::{access::Capabilities, prelude::*};
2456
2457 #[component]
2458 fn Empty() -> impl IntoElement {
2459 view()
2460 }
2461
2462 #[test]
2463 fn a_root_reads_its_declared_capabilities_as_packages_are_read() {
2464 assert_eq!(Root::of::<Empty>().capabilities_ref(), None);
2465 let root = Root::of::<Empty>().capabilities_json(r#"{"clipboard":true,"bluetooth":true}"#);
2467 let expected = Capabilities {
2468 clipboard: true,
2469 ..Capabilities::default()
2470 };
2471 assert_eq!(root.capabilities_ref(), Some(&expected));
2472 let root = Root::of::<Empty>().capabilities_json("not json");
2474 assert_eq!(root.capabilities_ref(), Some(&Capabilities::default()));
2475 }
2476}