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] = &[
412 "class",
413 "classList",
414 "style",
415 "activeStyle",
416 "hoverStyle",
417 "focusStyle",
418 "focusWithinStyle",
419 "focusVisibleStyle",
420 "disabledStyle",
421 "testID",
422 "accessible",
423 "accessibilityLabel",
424 "accessibilityHint",
425 "accessibilityDescription",
426 "role",
427 "accessibilityState",
428 "accessibilityValue",
429 "accessibilityElementsHidden",
430 "importantForAccessibility",
431 "accessibilityLiveRegion",
432 "accessibilityActions",
433 "accessibilityLevel",
434 "accessibilityActiveDescendant",
435 "accessibilityControls",
436 "accessibilityDescribedBy",
437 "tooltip",
438 "focusable",
439 "onLayout",
440 "onFileDragEnter",
441 "onFileDragLeave",
442 "onFileDrop",
443 "onMouseEnter",
444 "onMouseMove",
445 "onMouseLeave",
446 "onMouseUp",
447 "onContextMenu",
448 "onAccessibilityAction",
449];
450
451type Specs = (
453 fn(&mut TsTypes) -> Vec<PropSpec>,
454 fn(&mut TsTypes) -> Vec<EventSpec>,
455 fn(&mut TsTypes) -> Vec<MethodSpec>,
456);
457
458impl ComponentSpec {
459 pub fn host_props(&self) -> impl Iterator<Item = &'static str> + '_ {
463 HOST_PROPS.iter().copied().filter(|&name| {
464 !self.props.iter().any(|p| p.name == name)
465 && !self.events.iter().any(|e| handler_name(e.name) == name)
466 })
467 }
468
469 pub(crate) fn of<C: Component>() -> Self {
470 Self::build(
471 name_of::<C>(),
472 C::DOC,
473 (C::Props::spec, C::Event::spec, C::METHODS.specs),
474 C::Props::LAZY_CHILDREN,
475 C::Props::GENERIC,
476 )
477 }
478
479 #[inline(never)]
481 fn build(
482 name: &'static str,
483 doc: &'static str,
484 (props, events, methods): Specs,
485 lazy_children: bool,
486 generic: bool,
487 ) -> Self {
488 let mut types = TsTypes::default();
489 let props = props(&mut types);
490 let events = events(&mut types);
491 let methods = methods(&mut types);
492 Self {
493 name,
494 export: export_name(name).to_owned(),
495 doc,
496 props,
497 events,
498 methods,
499 types,
500 lazy_children,
501 generic,
502 }
503 }
504
505 pub fn slots(&self) -> impl Iterator<Item = &'static str> + '_ {
507 self.props
508 .iter()
509 .filter(|p| p.kind == PropKind::Slot)
510 .map(|p| p.name)
511 }
512
513 pub fn renderers(&self) -> impl Iterator<Item = &'static str> + '_ {
515 self.props
516 .iter()
517 .filter(|p| p.kind == PropKind::Renderer)
518 .map(|p| p.name)
519 }
520
521 pub fn takes_children(&self) -> bool {
523 self.props.iter().any(|p| p.kind == PropKind::Children)
524 }
525
526 pub fn items(&self) -> Option<&'static str> {
528 self.props
529 .iter()
530 .find(|p| p.kind == PropKind::Items)
531 .map(|p| p.name)
532 }
533
534 pub(crate) fn holder(&self, name: &str) -> Option<&'static str> {
536 self.props
537 .iter()
538 .find(|p| matches!(p.kind, PropKind::Slot | PropKind::Items) && p.name == name)
539 .map(|p| p.name)
540 }
541}
542
543pub(crate) fn name_of<C: Component>() -> &'static str {
547 std::any::type_name::<C>()
548}
549
550pub(crate) fn export_name(type_name: &str) -> &str {
553 let path = type_name.split('<').next().unwrap_or(type_name);
554 path.rsplit("::").next().unwrap_or(path)
555}
556
557pub(crate) trait AnyInstance {
559 fn set_prop(&mut self, name: &str, value: Option<AnyValue>) -> Result<bool, PropError>;
560 fn set_props(&mut self, props: &dyn Any);
562 fn set_slot(&mut self, name: &'static str, filled: bool);
563 fn set_children(&mut self, present: bool);
564 fn cleanup(&mut self);
566 fn view(&mut self) -> ElNode;
568 fn name(&self) -> &'static str;
570 fn call(&mut self, call: MethodCall) -> Option<JsResult>;
573 fn owner(&self) -> Option<super::Owner>;
575 fn failure_owner(&self) -> super::Owner;
578 fn adopt(&mut self, parent: super::Owner);
582 fn place(&mut self, host: crate::NodeId, parent: super::Owner);
584}
585
586#[derive(Clone)]
590pub struct Root {
591 make: Arc<dyn Fn() -> super::AnyElement + Send + Sync>,
592 tokens: Option<Arc<super::Tokens>>,
593 fonts: Vec<Arc<[u8]>>,
594 appearance: Option<crate::platform::Appearance>,
595 app_id: Option<String>,
596 links: crate::url_scheme::AppLinks,
597 capabilities: Option<crate::access::Capabilities>,
598 status_bar: Option<crate::StatusBarSetting>,
599 main_window: Option<crate::desktop::MainWindowOptions>,
600 application: Option<crate::desktop::ApplicationOptions>,
601 translations: Option<crate::i18n::Translations>,
602 app_info: Option<crate::platform::AppInfo>,
603}
604
605impl Root {
606 pub fn new<C: Component>(props: impl Fn() -> C::Props + Send + Sync + 'static) -> Self {
608 Self {
609 make: Arc::new(move || super::IntoElement::into_element(C::element(props()))),
610 tokens: None,
611 fonts: Vec::new(),
612 appearance: None,
613 app_id: None,
614 links: crate::url_scheme::AppLinks::default(),
615 capabilities: None,
616 status_bar: None,
617 main_window: None,
618 application: None,
619 translations: None,
620 app_info: None,
621 }
622 }
623
624 pub fn translations(mut self, translations: crate::i18n::Translations) -> Self {
627 self.translations = Some(translations);
628 self
629 }
630
631 #[doc(hidden)]
634 pub fn translations_json(self, json: &str) -> Self {
635 match crate::i18n::Translations::from_json(json) {
636 Ok(translations) => self.translations(translations),
637 Err(e) => {
638 log::warn!("locales: {e}");
639 self
640 }
641 }
642 }
643
644 pub fn translations_ref(&self) -> Option<&crate::i18n::Translations> {
646 self.translations.as_ref()
647 }
648
649 pub fn app_id(mut self, id: impl Into<String>) -> Self {
652 self.app_id = Some(id.into());
653 self
654 }
655
656 pub fn app_id_ref(&self) -> Option<&str> {
658 self.app_id.as_deref()
659 }
660
661 pub fn app_info(mut self, info: crate::platform::AppInfo) -> Self {
665 self.app_info = Some(info);
666 self
667 }
668
669 #[doc(hidden)]
673 pub fn app_info_json(self, json: &str) -> Self {
674 let info = match serde_json::from_str(json) {
675 Ok(value) => crate::platform::AppInfo::from_json(&value),
676 Err(e) => {
677 log::warn!("appInfo: {e}, ignored");
678 crate::platform::AppInfo::default()
679 }
680 };
681 self.app_info(info)
682 }
683
684 #[doc(hidden)]
686 pub fn app_info_ref(&self) -> Option<&crate::platform::AppInfo> {
687 self.app_info.as_ref()
688 }
689
690 pub fn url_schemes(mut self, schemes: impl IntoIterator<Item = impl Into<String>>) -> Self {
695 self.links.set_schemes(schemes);
696 self
697 }
698
699 pub fn url_schemes_ref(&self) -> &[String] {
701 self.links.schemes()
702 }
703
704 pub fn links(mut self, links: crate::url_scheme::AppLinks) -> Self {
709 self.links = links;
710 self
711 }
712
713 #[doc(hidden)]
718 pub fn links_json(self, json: &str) -> Self {
719 let links = match serde_json::from_str::<serde_json::Value>(json) {
720 Ok(config) => {
721 let (links, ignored) = crate::url_scheme::AppLinks::from_json_lenient(&config);
722 for what in ignored {
723 log::warn!("nsh.json: {what}, ignored");
724 }
725 links
726 }
727 Err(e) => {
728 log::warn!("nsh.json: links: {e}; none claimed");
729 crate::url_scheme::AppLinks::default()
730 }
731 };
732 self.links(links)
733 }
734
735 pub fn links_ref(&self) -> &crate::url_scheme::AppLinks {
737 &self.links
738 }
739
740 pub fn capabilities(mut self, capabilities: crate::access::Capabilities) -> Self {
746 self.capabilities = Some(capabilities);
747 self
748 }
749
750 #[doc(hidden)]
756 pub fn capabilities_json(self, json: &str) -> Self {
757 let read = serde_json::from_str::<serde_json::Value>(json)
758 .map_err(|e| e.to_string())
759 .and_then(|v| crate::access::Capabilities::from_json_lenient(&v));
760 let capabilities = match read {
761 Ok((capabilities, dropped)) => {
762 for what in dropped {
763 log::warn!("nsh.json: {what}, not granted");
764 }
765 capabilities
766 }
767 Err(e) => {
768 log::warn!("nsh.json: capabilities: {e}; nothing granted");
769 crate::access::Capabilities::default()
770 }
771 };
772 self.capabilities(capabilities)
773 }
774
775 pub fn capabilities_ref(&self) -> Option<&crate::access::Capabilities> {
778 self.capabilities.as_ref()
779 }
780
781 pub fn tokens(mut self, tokens: super::Tokens) -> Self {
784 self.tokens = Some(Arc::new(tokens));
785 self
786 }
787
788 pub fn font(mut self, data: impl Into<Arc<[u8]>>) -> Self {
791 self.fonts.push(data.into());
792 self
793 }
794
795 pub fn appearance(mut self, appearance: crate::platform::Appearance) -> Self {
799 self.appearance = Some(appearance);
800 self
801 }
802
803 pub fn status_bar(mut self, setting: crate::StatusBarSetting) -> Self {
806 self.status_bar = Some(setting);
807 self
808 }
809
810 pub fn main_window(mut self, options: crate::desktop::MainWindowOptions) -> Self {
815 self.main_window = Some(options);
816 self
817 }
818
819 #[doc(hidden)]
823 pub fn main_window_json(self, json: &str) -> Self {
824 let options = serde_json::from_str::<serde_json::Value>(json)
825 .map_err(|e| e.to_string())
826 .and_then(|v| {
827 crate::desktop::MainWindowOptions::from_json(&v).map_err(|e| e.to_string())
828 });
829 match options {
830 Ok(options) => self.main_window(options),
831 Err(e) => {
832 log::warn!("nsh.json: window: {e}");
833 self
834 }
835 }
836 }
837
838 pub fn main_window_ref(&self) -> Option<&crate::desktop::MainWindowOptions> {
840 self.main_window.as_ref()
841 }
842
843 pub fn application(mut self, options: crate::desktop::ApplicationOptions) -> Self {
847 self.application = Some(options);
848 self
849 }
850
851 #[doc(hidden)]
855 pub fn application_json(self, json: &str) -> Self {
856 let options = serde_json::from_str::<serde_json::Value>(json)
857 .map_err(|e| e.to_string())
858 .and_then(|v| {
859 crate::desktop::ApplicationOptions::from_json(&v).map_err(|e| e.to_string())
860 });
861 match options {
862 Ok(options) => self.application(options),
863 Err(e) => {
864 log::warn!("nsh.json: application: {e}");
865 self
866 }
867 }
868 }
869
870 pub fn application_ref(&self) -> Option<&crate::desktop::ApplicationOptions> {
872 self.application.as_ref()
873 }
874
875 pub fn status_bar_ref(&self) -> Option<crate::StatusBarSetting> {
877 self.status_bar
878 }
879
880 pub fn appearance_ref(&self) -> Option<crate::platform::Appearance> {
883 self.appearance
884 }
885
886 pub fn tokens_ref(&self) -> Option<&super::Tokens> {
888 self.tokens.as_deref()
889 }
890
891 pub fn fonts(&self) -> &[Arc<[u8]>] {
893 &self.fonts
894 }
895
896 pub fn of<C: Component>() -> Self
898 where
899 C::Props: Default,
900 {
901 Self::new::<C>(C::Props::default)
902 }
903
904 pub(crate) fn element(&self) -> super::AnyElement {
906 (self.make)()
907 }
908}
909
910impl fmt::Debug for Root {
911 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
912 f.write_str("Root")
913 }
914}
915
916pub const BY_NAME_MARKER: &str = "missing_instance";
921
922#[inline(never)]
926pub(crate) fn missing_instance() -> Box<dyn AnyInstance> {
927 unreachable!("a component made by name is made by its registry")
928}
929
930pub(crate) fn missing_spec() -> ComponentSpec {
932 unreachable!("a component made by name is made by its registry")
933}
934
935pub(crate) fn make_instance<C: Component>() -> Box<dyn AnyInstance> {
937 Box::new(super::once::OnceInstance::<C>::new())
938}
939
940#[derive(Clone)]
941struct ComponentType {
942 spec: Arc<ComponentSpec>,
943 make: fn() -> Box<dyn AnyInstance>,
944 id: TypeId,
946}
947
948#[derive(Clone)]
949struct ModuleType {
950 spec: Arc<ModuleSpec>,
951 type_name: &'static str,
953}
954
955#[derive(Clone)]
956struct ClassType {
957 spec: Arc<ClassSpec>,
958 type_name: &'static str,
960}
961
962#[derive(Debug, Clone, Default)]
965#[non_exhaustive]
966pub struct BuiltInScrollbar {
967 pub target: crate::NodeId,
969 pub horizontal: bool,
971 pub theme: Option<Arc<crate::JsonValue>>,
974 pub theme_value: Option<super::AnyValue>,
978 pub app_theme: Option<super::AnyValue>,
981}
982
983pub type ScrollbarSource = fn(&BuiltInScrollbar) -> Option<super::AnyElement>;
988
989#[derive(Clone)]
996pub struct ScrollbarThemeValue {
997 source: ScrollbarSource,
998 theme: super::AnyValue,
999}
1000
1001impl ScrollbarThemeValue {
1002 pub fn new(source: ScrollbarSource, theme: super::AnyValue) -> Self {
1005 Self { source, theme }
1006 }
1007
1008 pub fn source(&self) -> ScrollbarSource {
1010 self.source
1011 }
1012
1013 pub fn theme(&self) -> &super::AnyValue {
1015 &self.theme
1016 }
1017}
1018
1019impl PartialEq for ScrollbarThemeValue {
1020 fn eq(&self, other: &Self) -> bool {
1021 self.theme == other.theme
1022 }
1023}
1024
1025impl std::fmt::Debug for ScrollbarThemeValue {
1026 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1027 f.debug_tuple("ScrollbarThemeValue")
1028 .field(&self.theme)
1029 .finish()
1030 }
1031}
1032
1033#[derive(Clone, Default)]
1036pub struct Registry {
1037 types: Arc<FxHashMap<&'static str, ComponentType>>,
1038 modules: Arc<FxHashMap<&'static str, ModuleType>>,
1039 classes: Arc<FxHashMap<(Option<&'static str>, &'static str), ClassType>>,
1042 reexports: Arc<(Vec<&'static str>, Vec<&'static str>)>,
1044 native_values: Arc<Vec<&'static str>>,
1047 namespace: Option<&'static str>,
1050 ui_set: Option<&'static str>,
1052 assets: Arc<Vec<(&'static [crate::platform::Os], &'static [super::AssetFile])>>,
1055 tokens: Option<super::TokenSource>,
1057 scrollbars: Option<ScrollbarSource>,
1059 submodules: Arc<Vec<Registry>>,
1062 setups: Arc<Vec<Setup>>,
1064 fakes: Arc<Vec<(&'static str, Arc<dyn crate::fake::Fake>)>>,
1067 gpu_renderers: Arc<Vec<(&'static str, crate::gpu::GpuSource)>>,
1069}
1070
1071type Setup = Arc<dyn Fn() + Send + Sync>;
1073
1074impl fmt::Debug for Registry {
1075 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1076 f.debug_set().entries(self.types.keys()).finish()
1077 }
1078}
1079
1080impl Registry {
1081 pub fn new() -> Self {
1083 Self::default()
1084 }
1085
1086 #[track_caller]
1095 pub fn register<C: Component>(&mut self) -> &mut Self {
1096 let spec = ComponentSpec::of::<C>();
1097 let mut refs = Vec::new();
1098 (C::METHODS.refs)(&mut refs);
1099 self.register_erased(spec, make_instance::<C>, TypeId::of::<C>(), refs)
1100 }
1101
1102 #[track_caller]
1105 #[inline(never)]
1106 fn register_erased(
1107 &mut self,
1108 spec: ComponentSpec,
1109 make: fn() -> Box<dyn AnyInstance>,
1110 id: TypeId,
1111 refs: Vec<&'static ClassDef>,
1112 ) -> &mut Self {
1113 let types = Arc::make_mut(&mut self.types);
1114 if let Some(old) = types.get(spec.name) {
1115 let set = self.ui_set.or(self.namespace);
1116 panic!("{}", same_name(spec.name, old.id, id, set));
1117 }
1118 if self.classes.keys().any(|(_, name)| *name == spec.export) {
1119 panic!(
1120 "component `{}` is exported as `{}` like a class{}: rename one",
1121 spec.name,
1122 spec.export,
1123 of_set(self.ui_set.or(self.namespace)),
1124 );
1125 }
1126 if let Some(other) = types.values().find(|t| t.spec.export == spec.export) {
1127 panic!(
1128 "components `{}` and `{}` are both exported as `{}`{}: rename one",
1129 other.spec.name,
1130 spec.name,
1131 spec.export,
1132 of_set(self.ui_set.or(self.namespace)),
1133 );
1134 }
1135 types.insert(
1136 spec.name,
1137 ComponentType {
1138 spec: Arc::new(spec),
1139 make,
1140 id,
1141 },
1142 );
1143 self.classes_named(refs)
1144 }
1145
1146 #[track_caller]
1154 pub fn module<M: Module>(&mut self) -> &mut Self {
1155 let type_name = std::any::type_name::<M>();
1156 if self.classes.keys().any(|(_, name)| *name == M::NAME) {
1157 panic!(
1158 "module `{type_name}` is named `{}` like a class{}: rename one",
1159 M::NAME,
1160 of_set(self.ui_set.or(self.namespace))
1161 );
1162 }
1163 let modules = Arc::make_mut(&mut self.modules);
1164 if let Some(old) = modules.get(M::NAME) {
1165 panic!(
1166 "{}",
1167 same_module(
1168 M::NAME,
1169 old.type_name,
1170 type_name,
1171 self.ui_set.or(self.namespace)
1172 )
1173 );
1174 }
1175 modules.insert(
1176 M::NAME,
1177 ModuleType {
1178 spec: Arc::new(ModuleSpec::of::<M>()),
1179 type_name,
1180 },
1181 );
1182 let mut refs = Vec::new();
1183 for f in M::FUNCTIONS {
1184 (f.refs)(&mut refs);
1185 }
1186 self.classes_named(refs)
1187 }
1188
1189 #[track_caller]
1202 pub fn class<C: Class>(&mut self) -> &mut Self {
1203 self.class_def(C::DEF)
1204 }
1205
1206 #[track_caller]
1209 fn classes_named(&mut self, refs: Vec<&'static ClassDef>) -> &mut Self {
1210 for def in refs {
1211 self.class_def(def);
1212 }
1213 self
1214 }
1215
1216 #[track_caller]
1217 fn class_def(&mut self, def: &'static ClassDef) -> &mut Self {
1218 let type_name = (def.type_name)();
1219 let set = self.ui_set.or(self.namespace);
1220 if let Some(old) = self.classes.get(&(set, def.name)) {
1221 if (old.spec.def.type_id)() == (def.type_id)() {
1222 return self;
1223 }
1224 panic!("{}", same_class(def.name, old.type_name, type_name, set));
1225 }
1226 if self.modules.contains_key(def.name)
1227 || self.types.values().any(|t| t.spec.export == def.name)
1228 {
1229 panic!(
1230 "class `{type_name}` is named `{}` like a module or a component{}: rename one",
1231 def.name,
1232 of_set(set)
1233 );
1234 }
1235 Arc::make_mut(&mut self.classes).insert(
1236 (set, def.name),
1237 ClassType {
1238 spec: Arc::new(ClassSpec::of(def)),
1239 type_name,
1240 },
1241 );
1242 let mut refs = Vec::new();
1244 for m in def.members {
1245 (m.refs)(&mut refs);
1246 }
1247 self.classes_named(refs)
1248 }
1249
1250 pub fn reexport(&mut self, values: &[&'static str], types: &[&'static str]) -> &mut Self {
1253 let r = Arc::make_mut(&mut self.reexports);
1254 r.0.extend_from_slice(values);
1255 r.1.extend_from_slice(types);
1256 self
1257 }
1258
1259 #[track_caller]
1270 pub fn merged(sets: &[Registry]) -> Self {
1271 let mut out = Self::default();
1272 for set in sets.iter().flat_map(Registry::sets) {
1273 out.tokens = out.tokens.or(set.tokens);
1274 out.scrollbars = out.scrollbars.or(set.scrollbars);
1275 Arc::make_mut(&mut out.setups).extend(set.setups.iter().cloned());
1276 let fakes = Arc::make_mut(&mut out.fakes);
1277 for (name, fake) in set.fakes.iter() {
1278 assert!(
1279 fakes.iter().all(|(n, _)| n != name),
1280 "two fakes are named `{name}`, by two UI sets"
1281 );
1282 fakes.push((name, fake.clone()));
1283 }
1284 let renderers = Arc::make_mut(&mut out.gpu_renderers);
1285 for (name, source) in set.gpu_renderers.iter() {
1286 assert!(
1287 renderers.iter().all(|(n, _)| n != name),
1288 "two GPU renderers are named `{name}`, by two UI sets"
1289 );
1290 renderers.push((name, source.clone()));
1291 }
1292 let types = Arc::make_mut(&mut out.types);
1293 for (name, ty) in set.types.iter() {
1294 if let Some(old) = types.insert(name, ty.clone()) {
1295 panic!("{}, by two UI sets", same_name(name, old.id, ty.id, None));
1296 }
1297 }
1298 }
1299 out
1300 }
1301
1302 pub fn ui_set(specifier: &'static str) -> Self {
1306 Self {
1307 ui_set: Some(specifier),
1308 ..Self::default()
1309 }
1310 }
1311
1312 pub fn specifier(&self) -> Option<&'static str> {
1315 self.ui_set.or(self.namespace)
1316 }
1317
1318 pub fn reexports(&self) -> (&[&'static str], &[&'static str]) {
1321 (&self.reexports.0, &self.reexports.1)
1322 }
1323
1324 #[track_caller]
1336 pub fn submodule(&mut self, set: Registry) -> &mut Self {
1337 let under = match (self.ui_set, set.ui_set) {
1338 (Some(parent), Some(child)) => child
1339 .strip_prefix(parent)
1340 .is_some_and(|rest| rest.len() > 1 && rest.starts_with('/')),
1341 _ => false,
1342 };
1343 assert!(
1344 under,
1345 "a submodule is a UI set under a path of its set's specifier: {:?} under {:?}",
1346 set.ui_set, self.ui_set
1347 );
1348 Arc::make_mut(&mut self.submodules).push(set);
1349 self
1350 }
1351
1352 pub fn sets(&self) -> Vec<&Registry> {
1356 let mut out = vec![self];
1357 for sub in self.submodules.iter() {
1358 out.extend(sub.sets());
1359 }
1360 out
1361 }
1362
1363 pub fn native_values(&mut self, values: &[&'static str]) -> &mut Self {
1366 Arc::make_mut(&mut self.native_values).extend_from_slice(values);
1367 self
1368 }
1369
1370 pub fn assets(&mut self, files: &'static [super::AssetFile]) -> &mut Self {
1376 self.assets_for(&[], files)
1377 }
1378
1379 pub fn assets_for(
1385 &mut self,
1386 targets: &'static [crate::platform::Os],
1387 files: &'static [super::AssetFile],
1388 ) -> &mut Self {
1389 Arc::make_mut(&mut self.assets).push((targets, files));
1390 self
1391 }
1392
1393 pub fn tokens_from(&mut self, source: super::TokenSource) -> &mut Self {
1396 self.tokens = Some(source);
1397 self
1398 }
1399
1400 pub fn scrollbars_from(&mut self, source: ScrollbarSource) -> &mut Self {
1405 self.scrollbars = Some(source);
1406 self
1407 }
1408
1409 pub(crate) fn scrollbar_source(&self) -> Option<ScrollbarSource> {
1412 self.scrollbars
1413 }
1414
1415 pub fn setup(&mut self, f: impl Fn() + Send + Sync + 'static) -> &mut Self {
1423 Arc::make_mut(&mut self.setups).push(Arc::new(f));
1424 self
1425 }
1426
1427 pub fn gpu_renderer_source(
1433 &mut self,
1434 name: &'static str,
1435 source: crate::gpu::GpuSource,
1436 ) -> &mut Self {
1437 let renderers = Arc::make_mut(&mut self.gpu_renderers);
1438 renderers.retain(|(n, _)| *n != name);
1439 renderers.push((name, source));
1440 self
1441 }
1442
1443 pub fn registered_gpu_renderer(&self, name: &str) -> Option<&crate::gpu::GpuSource> {
1445 self.gpu_renderers
1446 .iter()
1447 .find(|(n, _)| *n == name)
1448 .map(|(_, s)| s)
1449 }
1450
1451 #[track_caller]
1463 pub fn fake(&mut self, name: &'static str, fake: Arc<dyn crate::fake::Fake>) -> &mut Self {
1464 assert!(
1465 self.fakes.iter().all(|(n, _)| *n != name),
1466 "two fakes are named `{name}`{}",
1467 of_set(self.ui_set.or(self.namespace))
1468 );
1469 Arc::make_mut(&mut self.fakes).push((name, fake));
1470 self
1471 }
1472
1473 #[doc(hidden)]
1476 pub fn fakes(&self) -> Vec<(&'static str, Arc<dyn crate::fake::Fake>)> {
1477 self.sets()
1478 .into_iter()
1479 .flat_map(|set| set.fakes.iter().cloned())
1480 .collect()
1481 }
1482
1483 pub(crate) fn run_setups(&self) {
1486 for setup in self.setups.iter() {
1487 setup();
1488 }
1489 }
1490
1491 pub(crate) fn run_setups_not_in(&self, old: &Registry) {
1494 for setup in self.setups.iter() {
1495 let known = old
1496 .setups
1497 .iter()
1498 .any(|o| std::ptr::addr_eq(Arc::as_ptr(o), Arc::as_ptr(setup)));
1499 if !known {
1500 setup();
1501 }
1502 }
1503 }
1504
1505 pub fn tokens(
1509 &self,
1510 json: Option<&str>,
1511 ) -> Option<Result<(super::Tokens, Vec<String>), String>> {
1512 self.tokens.map(|source| source(json))
1513 }
1514
1515 pub(crate) fn token_source(&self) -> Option<super::TokenSource> {
1517 self.tokens
1518 }
1519
1520 pub fn asset_files(&self) -> impl Iterator<Item = &'static super::AssetFile> + '_ {
1523 self.assets.iter().flat_map(|(_, files)| files.iter())
1524 }
1525
1526 pub fn scoped_asset_files(
1529 &self,
1530 ) -> impl Iterator<Item = (&'static [crate::platform::Os], &'static super::AssetFile)> + '_
1531 {
1532 self.assets
1533 .iter()
1534 .flat_map(|&(targets, files)| files.iter().map(move |file| (targets, file)))
1535 }
1536
1537 pub fn native_value_names(&self) -> &[&'static str] {
1539 &self.native_values
1540 }
1541
1542 pub(crate) fn runtime(namespace: &'static str) -> Self {
1544 Self {
1545 namespace: Some(namespace),
1546 ..Self::default()
1547 }
1548 }
1549
1550 pub fn namespace(&self) -> Option<&'static str> {
1553 self.namespace
1554 }
1555
1556 pub fn class_specs(&self) -> Vec<Arc<ClassSpec>> {
1558 let mut specs: Vec<_> = self.classes.values().map(|c| c.spec.clone()).collect();
1559 specs.sort_by_key(|s| s.name);
1560 specs
1561 }
1562
1563 pub fn module_specs(&self) -> Vec<Arc<ModuleSpec>> {
1565 let mut specs: Vec<_> = self.modules.values().map(|m| m.spec.clone()).collect();
1566 specs.sort_by_key(|s| s.name);
1567 specs
1568 }
1569
1570 pub fn function_members(&self, function: &str) -> Option<Arc<ModuleSpec>> {
1575 let exported = self.modules.values().any(|m| {
1576 m.spec.flat
1577 && m.spec
1578 .functions
1579 .iter()
1580 .any(|f| !f.getter && f.name == function)
1581 });
1582 exported
1583 .then(|| {
1584 self.modules
1585 .values()
1586 .find(|m| !m.spec.flat && m.spec.name == function)
1587 .map(|m| m.spec.clone())
1588 })
1589 .flatten()
1590 }
1591
1592 pub fn specs(&self) -> Vec<Arc<ComponentSpec>> {
1594 let mut specs: Vec<_> = self.types.values().map(|t| t.spec.clone()).collect();
1595 specs.sort_by(|a, b| a.export.cmp(&b.export).then(a.name.cmp(b.name)));
1596 specs
1597 }
1598
1599 pub fn undocumented(&self) -> Vec<String> {
1608 let mut out = Vec::new();
1609 let specs = self.specs();
1610 for c in &specs {
1611 if c.doc.is_empty() {
1612 out.push(c.export.clone());
1613 }
1614 for p in c.props.iter().filter(|p| p.doc.is_empty()) {
1615 out.push(format!("{}.{}", c.export, p.name));
1616 }
1617 for e in c.events.iter().filter(|e| e.doc.is_empty()) {
1618 out.push(format!("{}.{}", c.export, handler_name(e.name)));
1619 }
1620 for m in c.methods.iter().filter(|m| m.doc.is_empty()) {
1621 out.push(format!("{}.{}", c.export, m.name));
1622 }
1623 }
1624 for m in self.module_specs() {
1625 let merged = specs.iter().any(|c| c.export == m.name)
1626 || (!m.flat && self.function_members(m.name).is_some());
1627 if m.doc.is_empty() && !merged && !m.flat {
1628 out.push(m.name.to_owned());
1629 }
1630 for f in m.functions.iter().filter(|f| f.doc.is_empty()) {
1631 out.push(if m.flat {
1632 f.name.to_owned()
1633 } else {
1634 format!("{}.{}", m.name, f.name)
1635 });
1636 }
1637 }
1638 for c in self.class_specs() {
1639 if c.doc.is_empty() {
1640 out.push(c.name.to_owned());
1641 }
1642 let documented_getter = |name: &str| {
1643 c.members
1644 .iter()
1645 .any(|m| m.kind == MemberKind::Getter && m.name == name && !m.doc.is_empty())
1646 };
1647 for m in c.members.iter().filter(|m| m.doc.is_empty()) {
1648 match m.kind {
1649 MemberKind::Constructor => out.push(format!("new {}", c.name)),
1650 MemberKind::Setter if documented_getter(m.name) => {}
1651 _ => out.push(format!("{}.{}", c.name, m.name)),
1652 }
1653 }
1654 }
1655 out
1656 }
1657
1658 pub(crate) fn make_type(
1661 &self,
1662 id: TypeId,
1663 ) -> Option<(Arc<ComponentSpec>, Box<dyn AnyInstance>)> {
1664 self.types
1665 .values()
1666 .find(|t| t.id == id)
1667 .map(|t| (t.spec.clone(), (t.make)()))
1668 }
1669
1670 pub(crate) fn make(&self, name: &str) -> Option<(Arc<ComponentSpec>, Box<dyn AnyInstance>)> {
1672 self.types.get(name).map(|t| (t.spec.clone(), (t.make)()))
1673 }
1674}
1675
1676fn same_name(name: &str, old: TypeId, new: TypeId, set: Option<&str>) -> String {
1678 if old == new {
1679 format!("component `{name}` is registered twice{}", of_set(set))
1680 } else {
1681 format!(
1682 "two different types named `{name}` are registered{} (two versions of one crate?)",
1683 of_set(set)
1684 )
1685 }
1686}
1687
1688fn same_module(name: &str, old: &str, new: &str, set: Option<&str>) -> String {
1690 if old == new {
1691 format!("module `{old}` is registered twice{}", of_set(set))
1692 } else {
1693 format!(
1694 "modules `{old}` and `{new}` are both named `{name}`{}: rename one",
1695 of_set(set)
1696 )
1697 }
1698}
1699
1700fn same_class(name: &str, old: &str, new: &str, set: Option<&str>) -> String {
1702 if old == new {
1703 format!("class `{old}` is registered twice{}", of_set(set))
1704 } else {
1705 format!(
1706 "classes `{old}` and `{new}` are both named `{name}`{}: rename one",
1707 of_set(set)
1708 )
1709 }
1710}
1711
1712fn of_set(set: Option<&str>) -> String {
1714 set.map(|s| format!(" in `{s}`")).unwrap_or_default()
1715}
1716
1717pub fn declarations(registry: &Registry, omit: &[&str]) -> String {
1726 let specs = registry.specs();
1727 let modules = registry.module_specs();
1728 let classes = registry.class_specs();
1729 use std::fmt::Write as _;
1730 let mut out = String::new();
1731 let doc = |out: &mut String, indent: &str, doc: &str| {
1732 if !doc.is_empty() {
1733 let _ = writeln!(out, "{indent}/** {doc} */");
1734 }
1735 };
1736 let mut types = TsTypes::default();
1738 for spec in &specs {
1739 types.merge(&spec.types);
1740 }
1741 for m in &modules {
1742 types.merge(&m.types);
1743 }
1744 for c in &classes {
1745 types.merge(&c.types);
1746 }
1747 for declaration in types.declarations() {
1748 let _ = write!(out, "{declaration}\n\n");
1749 }
1750 let module_of = |name: &str| modules.iter().find(|m| m.name == name);
1751 let signatures = |f: &FunctionSpec| {
1753 let one = |params: &[(&str, String, bool)], returns: &Option<String>| {
1754 let params = params
1755 .iter()
1756 .map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
1757 .collect::<Vec<_>>()
1758 .join(", ");
1759 let value = returns.clone().unwrap_or_else(|| "void".to_owned());
1760 let returns = if f.promises() {
1761 format!("Promise<{value}>")
1762 } else {
1763 value
1764 };
1765 (params, returns)
1766 };
1767 if f.overloads.is_empty() {
1768 vec![one(&f.params, &f.returns)]
1769 } else {
1770 f.overloads
1771 .iter()
1772 .map(|(params, returns)| one(params, returns))
1773 .collect()
1774 }
1775 };
1776 let module_object = |out: &mut String, m: &ModuleSpec| {
1778 out.push_str("{\n");
1779 for f in &m.functions {
1780 for (params, returns) in signatures(f) {
1781 doc(out, " ", f.doc);
1782 if f.getter {
1783 let _ = writeln!(out, " readonly {}: {returns};", f.name);
1784 continue;
1785 }
1786 let _ = writeln!(out, " {}({params}): {returns};", f.name);
1787 }
1788 }
1789 for constant in &m.constants {
1790 doc(out, " ", constant.doc);
1791 let _ = writeln!(
1792 out,
1793 " readonly {}: {};",
1794 constant.name,
1795 constant.value.ts_type()
1796 );
1797 }
1798 out.push('}');
1799 };
1800 for spec in &specs {
1801 let (generic, params, extends) = match spec.items() {
1805 Some(_) => ("<T>", "<T>", ", ListItemsProps<T>"),
1806 None if spec.generic => ("<T>", "<T = any>", ""),
1807 None => ("", "", ""),
1808 };
1809 let mut omit: Vec<&str> = HOST_PROPS
1812 .iter()
1813 .copied()
1814 .filter(|&h| !spec.host_props().any(|p| p == h))
1815 .collect();
1816 if !spec.methods.is_empty() {
1817 omit.insert(0, "ref");
1818 }
1819 let host = if omit.is_empty() {
1820 "ComponentHostProps".to_owned()
1821 } else {
1822 let names = omit.iter().map(|n| format!("\"{n}\"")).collect::<Vec<_>>();
1823 format!("Omit<ComponentHostProps, {}>", names.join(" | "))
1824 };
1825 if !spec.methods.is_empty() {
1826 let _ = write!(
1827 out,
1828 "/** The ref of `{0}`: its methods. */\nexport interface {0}Ref {{\n /** The component's host node. */\n readonly node: ViewRef;\n",
1829 spec.export
1830 );
1831 for m in &spec.methods {
1832 doc(&mut out, " ", m.doc);
1833 let params = m
1834 .params
1835 .iter()
1836 .map(|(n, ts, optional)| {
1837 format!("{n}{}: {ts}", if *optional { "?" } else { "" })
1838 })
1839 .collect::<Vec<_>>()
1840 .join(", ");
1841 let returns = match &m.returns {
1842 Some(ts) => format!("Promise<{ts}>"),
1843 None => "void".to_owned(),
1844 };
1845 let _ = writeln!(out, " {}({params}): {returns};", m.name);
1846 }
1847 out.push_str("}\n\n");
1848 }
1849 let _ = writeln!(
1850 out,
1851 "export interface {}Props{params} extends {host}{extends} {{",
1852 spec.export
1853 );
1854 if !spec.methods.is_empty() {
1855 let _ = writeln!(
1856 out,
1857 " ref?: {0}Ref | ((ref: {0}Ref) => void);",
1858 spec.export
1859 );
1860 }
1861 for p in spec.props.iter().filter(|p| p.kind != PropKind::Items) {
1862 doc(&mut out, " ", p.doc);
1863 let optional = if p.optional { "?" } else { "" };
1864 let _ = writeln!(out, " {}{optional}: {};", p.name, p.ts);
1865 }
1866 for e in &spec.events {
1867 doc(&mut out, " ", e.doc);
1868 let handler = handler_name(e.name);
1869 let arg = if e.data == "void" {
1870 String::new()
1871 } else {
1872 format!("{}: {}", e.arg, e.data)
1873 };
1874 let _ = writeln!(out, " {handler}?: ({arg}) => void;");
1875 }
1876 out.push_str("}\n\n");
1877 if omit.contains(&spec.export.as_str()) {
1878 continue;
1879 }
1880 doc(&mut out, "", spec.doc);
1881 let mut with = String::new();
1883 if let Some(m) = module_of(&spec.export) {
1884 with.push_str(" & ");
1885 module_object(&mut with, m);
1886 }
1887 let _ = write!(
1888 out,
1889 "export declare const {}: ({params}(props: {}Props{generic}) => JSX.Element){with};\n\n",
1890 spec.export, spec.export,
1891 );
1892 }
1893 for m in &modules {
1894 if specs.iter().any(|s| s.export == m.name)
1895 || (!m.flat && registry.function_members(m.name).is_some())
1896 {
1897 continue;
1898 }
1899 if m.flat {
1900 for f in m
1901 .functions
1902 .iter()
1903 .filter(|f| !f.getter && !omit.contains(&f.name))
1904 {
1905 for (params, returns) in signatures(f) {
1906 doc(&mut out, "", f.doc);
1907 let _ = writeln!(
1908 out,
1909 "export declare function {}({params}): {returns};",
1910 f.name
1911 );
1912 }
1913 if let Some(members) = registry.function_members(f.name) {
1915 let _ = writeln!(out, "export declare namespace {} {{", f.name);
1916 for member in &members.functions {
1917 for (params, returns) in signatures(member) {
1918 doc(&mut out, " ", member.doc);
1919 let _ = if member.getter {
1920 writeln!(out, " const {}: {returns};", member.name)
1921 } else {
1922 writeln!(out, " function {}({params}): {returns};", member.name)
1923 };
1924 }
1925 }
1926 for constant in &members.constants {
1927 doc(&mut out, " ", constant.doc);
1928 let _ = writeln!(
1929 out,
1930 " const {}: {};",
1931 constant.name,
1932 constant.value.ts_type()
1933 );
1934 }
1935 out.push_str("}\n");
1936 }
1937 out.push('\n');
1938 }
1939 for constant in &m.constants {
1940 if !omit.contains(&constant.name) {
1941 doc(&mut out, "", constant.doc);
1942 let _ = writeln!(
1943 out,
1944 "export declare const {}: {};\n",
1945 constant.name,
1946 constant.value.ts_type()
1947 );
1948 }
1949 }
1950 if m.default && !omit.contains(&"default") {
1951 let _ = write!(out, "declare const defaultExport: ");
1952 module_object(&mut out, m);
1953 for native in registry.native_value_names() {
1955 let _ = write!(out, " & {{ {native}: typeof {native} }}");
1956 }
1957 out.push_str(";\nexport default defaultExport;\n\n");
1958 }
1959 continue;
1960 }
1961 doc(&mut out, "", m.doc);
1962 let _ = write!(out, "export interface {}Module ", m.name);
1963 module_object(&mut out, m);
1964 out.push_str("\n\n");
1965 if !omit.contains(&m.name) {
1966 doc(&mut out, "", m.doc);
1967 let _ = write!(out, "export declare const {0}: {0}Module;\n\n", m.name);
1968 }
1969 if m.default && !omit.contains(&"default") {
1970 let _ = write!(
1971 out,
1972 "declare const defaultExport: {}Module;\nexport default defaultExport;\n\n",
1973 m.name
1974 );
1975 }
1976 }
1977 for c in classes.iter().filter(|c| !omit.contains(&c.name)) {
1978 class_declaration(&mut out, c);
1979 }
1980 out
1981}
1982
1983fn class_declaration(out: &mut String, c: &ClassSpec) {
1985 use std::fmt::Write as _;
1986 let doc = |out: &mut String, indent: &str, doc: &str| {
1987 if !doc.is_empty() {
1988 let _ = writeln!(out, "{indent}/** {doc} */");
1989 }
1990 };
1991 doc(out, "", c.doc);
1992 if c.def.interface {
1993 let _ = writeln!(out, "export interface {} {{", c.name);
1995 for m in &c.members {
1996 let params = m
1997 .params
1998 .iter()
1999 .map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
2000 .collect::<Vec<_>>()
2001 .join(", ");
2002 let value = m.returns.clone().unwrap_or_else(|| "void".to_owned());
2003 let returns = if m.is_async {
2004 format!("Promise<{value}>")
2005 } else {
2006 value
2007 };
2008 doc(out, " ", m.doc);
2009 let has_setter = |name| {
2010 c.members
2011 .iter()
2012 .any(|s| s.kind == MemberKind::Setter && s.name == name)
2013 };
2014 let _ = match m.kind {
2015 MemberKind::Method => writeln!(out, " {}({params}): {returns};", m.name),
2016 MemberKind::Getter if has_setter(m.name) => {
2017 writeln!(out, " {}: {returns};", m.name)
2018 }
2019 MemberKind::Getter => writeln!(out, " readonly {}: {returns};", m.name),
2020 _ => Ok(()),
2023 };
2024 }
2025 out.push_str("}\n\n");
2026 return;
2027 }
2028 let _ = writeln!(out, "export declare class {} {{", c.name);
2029 if !c.members.iter().any(|m| m.kind == MemberKind::Constructor) {
2030 out.push_str(" /** Made by the class's members only. */\n private constructor();\n");
2031 }
2032 let one = |m: &super::MemberSpec, params: &[(&str, String, bool)], returns: &Option<String>| {
2033 let params = params
2034 .iter()
2035 .map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
2036 .collect::<Vec<_>>()
2037 .join(", ");
2038 let value = returns.clone().unwrap_or_else(|| "void".to_owned());
2039 let returns = if m.is_async {
2040 format!("Promise<{value}>")
2041 } else {
2042 value
2043 };
2044 (params, returns)
2045 };
2046 for m in &c.members {
2047 if !m.overloads.is_empty() {
2048 for (params, returns) in &m.overloads {
2049 doc(out, " ", m.doc);
2050 let (params, returns) = one(m, params, returns);
2051 let _ = match m.kind {
2052 MemberKind::Static => {
2053 writeln!(out, " static {}({params}): {returns};", m.name)
2054 }
2055 _ => writeln!(out, " {}({params}): {returns};", m.name),
2056 };
2057 }
2058 continue;
2059 }
2060 doc(out, " ", m.doc);
2061 let (params, returns) = one(m, &m.params, &m.returns);
2062 let _ = match m.kind {
2063 MemberKind::Constructor => writeln!(out, " constructor({params});"),
2064 MemberKind::Method => writeln!(out, " {}({params}): {returns};", m.name),
2065 MemberKind::Getter => writeln!(out, " get {}(): {returns};", m.name),
2066 MemberKind::Setter => writeln!(out, " set {}({params});", m.name),
2067 MemberKind::Static => writeln!(out, " static {}({params}): {returns};", m.name),
2068 };
2069 }
2070 out.push_str(
2071 " /** 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",
2072 );
2073}
2074
2075fn handler_name(event: &str) -> String {
2077 let mut chars = event.chars();
2078 match chars.next() {
2079 Some(first) => format!("on{}{}", first.to_ascii_uppercase(), chars.as_str()),
2080 None => "on".to_owned(),
2081 }
2082}
2083
2084#[cfg(test)]
2085mod tests {
2086 use super::*;
2087 use crate::prelude::*;
2088
2089 #[test]
2090 fn by_name_marker_names_the_stand_in_make() {
2091 let name = std::any::type_name_of_val(&missing_instance);
2092 assert!(
2093 name.ends_with(&format!("::{BY_NAME_MARKER}")),
2094 "{name} is not {BY_NAME_MARKER}: update nsh-cli's by-name detection"
2095 );
2096 }
2097
2098 #[component]
2099 fn ByName() -> impl IntoElement {
2100 text("by name")
2101 }
2102
2103 #[test]
2104 fn a_component_made_by_name_has_the_marked_make() {
2105 let mut element = crate::element::ComponentElement::<ByName>::named(());
2106 let crate::element::ElKind::Component(c) = &element.node().kind else {
2107 panic!("not a component element");
2108 };
2109 assert!(std::ptr::fn_addr_eq(
2110 c.make,
2111 missing_instance as fn() -> Box<dyn AnyInstance>
2112 ));
2113 }
2114
2115 #[derive(Default)]
2116 struct Stepper;
2117
2118 #[derive(Clone, PartialEq, Props)]
2120 struct StepperProps {
2121 value: f64,
2123 #[prop(default)]
2124 size: StepperSize,
2125 max_value: Option<f64>,
2126 label: Option<Slot>,
2128 children: Children,
2129 }
2130
2131 #[derive(Clone, Copy, PartialEq, Default, PropEnum)]
2132 enum StepperSize {
2133 #[default]
2134 Regular,
2135 ExtraLarge,
2136 }
2137
2138 #[derive(Event)]
2139 enum StepperEvent {
2140 Change {
2142 new_value: f64,
2143 },
2144 #[args(limit)]
2145 Limit(u32),
2146 Reset,
2147 }
2148
2149 struct StepperApi;
2150
2151 #[methods]
2152 impl StepperApi {
2153 pub(crate) fn jump_to(&self, value: f64) {
2155 let _ = value;
2156 }
2157
2158 pub(crate) fn value(&self) -> f64 {
2159 0.0
2160 }
2161
2162 #[allow(dead_code)]
2164 fn clamp(&self, value: f64) -> f64 {
2165 value
2166 }
2167 }
2168
2169 impl Component for Stepper {
2170 type Props = StepperProps;
2171 type Event = StepperEvent;
2172 const METHODS: Methods = Methods::of::<StepperApi>();
2173 const DOC: &'static str = "Picks a number.";
2174
2175 fn view(_: StepperProps, _: super::super::Scope<StepperEvent>) -> impl IntoElement {
2176 view()
2177 }
2178 }
2179
2180 #[test]
2181 fn the_declarations_come_from_the_types() {
2182 let mut registry = Registry::new();
2183 registry.register::<Stepper>();
2184 let ts = declarations(®istry, &[]);
2185 for line in [
2186 " /** The value. */\n value: number;",
2187 "export type StepperSize = \"regular\" | \"extraLarge\";",
2188 " size?: StepperSize;",
2189 " maxValue?: number | null;",
2190 " /** Above the control. */\n label?: JSX.Element;",
2191 " children?: JSX.Element;",
2192 " /** The value changed. */\n onChange?: (event: { newValue: number }) => void;",
2193 " onLimit?: (event: { limit: number }) => void;",
2194 " onReset?: () => void;",
2195 "/** Picks a number. */",
2196 "export interface StepperRef {",
2197 " /** Jumps to `value`. */\n jumpTo(value: number): void;",
2198 " value(): Promise<number>;",
2199 "export interface StepperProps extends Omit<ComponentHostProps, \"ref\"> {\n ref?: StepperRef | ((ref: StepperRef) => void);",
2200 "export declare const Stepper: ((props: StepperProps) => JSX.Element);",
2201 ] {
2202 assert!(ts.contains(line), "missing {line:?} in\n{ts}");
2203 }
2204 assert!(!ts.contains("clamp"), "a helper is not a method:\n{ts}");
2205 assert_eq!(StepperApi::METHODS.len(), 2);
2206 let mut props = StepperProps::initial();
2207 let size = |json| {
2208 let specs = StepperProps::spec(&mut TsTypes::default());
2209 let decode = specs
2210 .iter()
2211 .find(|p| p.name == "size")
2212 .unwrap()
2213 .decode
2214 .unwrap();
2215 super::super::json_host::decode(decode, json)
2216 };
2217 assert!(
2218 props
2219 .set("size", Some(size(serde_json::json!("extraLarge")).unwrap()))
2220 .unwrap()
2221 );
2222 assert!(props.size == StepperSize::ExtraLarge);
2223 assert!(size(serde_json::json!("huge")).is_err());
2227 assert!(props.set("size", Some(AnyValue::new(1.0f64))).is_err());
2228 assert!(props.set("size", None).unwrap());
2229 assert!(props.size == StepperSize::Regular);
2230 let data = |e: &StepperEvent| super::super::json_host::event_data(e);
2231 assert_eq!(
2232 data(&StepperEvent::Change { new_value: 2.5 }),
2233 Some(serde_json::json!({ "newValue": 2.5 }))
2234 );
2235 assert_eq!(
2236 data(&StepperEvent::Limit(3)),
2237 Some(serde_json::json!({ "limit": 3 }))
2238 );
2239 assert_eq!(data(&StepperEvent::Reset), None);
2240 assert_eq!(StepperEvent::Reset.name(), "reset");
2241 }
2242
2243 #[test]
2244 fn exports_without_docs_are_listed() {
2245 let mut registry = Registry::new();
2246 registry.register::<Stepper>();
2247 assert_eq!(
2250 registry.undocumented(),
2251 [
2252 "Stepper.size",
2253 "Stepper.maxValue",
2254 "Stepper.children",
2255 "Stepper.onLimit",
2256 "Stepper.onReset",
2257 "Stepper.value",
2258 ]
2259 );
2260 let mut r = Registry::ui_set("test/maker");
2261 r.module::<Maker>();
2262 assert_eq!(r.undocumented(), ["Maker.make", "new Lonely"]);
2263 }
2264
2265 #[crate::element::class]
2267 struct Lonely;
2268
2269 #[crate::element::class]
2270 impl Lonely {
2271 pub(crate) fn new() -> Self {
2272 Lonely
2273 }
2274 }
2275
2276 #[crate::element::module]
2278 struct Maker;
2279
2280 #[crate::element::module]
2281 impl Maker {
2282 pub(crate) fn make() -> Instance<Lonely> {
2283 Instance::new(Lonely)
2284 }
2285 }
2286
2287 #[test]
2288 fn the_classes_a_signature_names_are_registered_with_it() {
2289 let mut r = Registry::ui_set("test/maker");
2290 r.module::<Maker>();
2291 let names: Vec<_> = r.class_specs().iter().map(|c| c.name).collect();
2294 assert_eq!(names, ["Lonely"]);
2295 let ts = declarations(&r, &[]);
2296 assert!(ts.contains("export declare class Lonely"), "{ts}");
2297 assert!(ts.contains("make(): Lonely;"), "{ts}");
2298 r.class::<Lonely>();
2300 assert_eq!(r.class_specs().len(), 1);
2301 let _ = Registry::merged(&[r]);
2302 }
2303
2304 #[crate::element::module]
2306 struct Checks;
2307
2308 #[crate::element::module(flat)]
2309 impl Checks {
2310 pub(crate) fn check(name: String) {
2312 let _ = name;
2313 }
2314 }
2315
2316 #[crate::element::module]
2318 struct CheckVariants;
2319
2320 #[crate::element::module(name = "check")]
2321 impl CheckVariants {
2322 pub(crate) const COUNT: u32 = 2;
2324
2325 pub(crate) fn skip(name: String) {
2327 let _ = name;
2328 }
2329
2330 pub(crate) fn todo(name: String) {
2331 let _ = name;
2332 }
2333 }
2334
2335 #[crate::element::module]
2337 struct Loose;
2338
2339 #[crate::element::module(name = "loose")]
2340 impl Loose {
2341 pub(crate) fn nothing() {}
2343 }
2344
2345 #[test]
2346 fn a_module_named_like_a_function_puts_its_functions_on_it() {
2347 let mut r = Registry::ui_set("test/checks");
2348 r.module::<Checks>()
2349 .module::<CheckVariants>()
2350 .module::<Loose>();
2351 assert_eq!(r.function_members("check").unwrap().name, "check");
2352 assert!(r.function_members("loose").is_none());
2353 let ts = declarations(&r, &[]);
2354 assert!(
2355 ts.contains(
2356 "/** Declares a check. */\n\
2357 export declare function check(name: string): void;\n\
2358 export declare namespace check {\n \
2359 /** Declares a check that does not run. */\n \
2360 function skip(name: string): void;\n \
2361 function todo(name: string): void;\n \
2362 /** How many variants there are. */\n \
2363 const COUNT: number;\n}\n"
2364 ),
2365 "{ts}"
2366 );
2367 assert!(
2368 !ts.contains("CheckVariants") && !ts.contains("checkModule"),
2369 "{ts}"
2370 );
2371 assert!(
2372 ts.contains("export declare const loose: looseModule;"),
2373 "{ts}"
2374 );
2375 assert_eq!(r.undocumented(), ["check.todo"]);
2377 let described = super::super::description::SetDescription::of(&r).unwrap();
2378 let exports: Vec<_> = described
2379 .exports
2380 .iter()
2381 .map(|e| (e.name.as_str(), e.kind))
2382 .collect();
2383 assert_eq!(
2384 exports,
2385 [
2386 ("check", super::super::description::ExportKind::Function),
2387 ("loose", super::super::description::ExportKind::Module)
2388 ]
2389 );
2390 }
2391
2392 mod clash {
2393 #[crate::element::class]
2395 pub(super) struct Lonely;
2396
2397 #[crate::element::class]
2398 impl Lonely {
2399 pub(super) fn new() -> Self {
2400 Lonely
2401 }
2402 }
2403 }
2404
2405 #[test]
2406 fn a_clash_through_a_signature_names_both_types() {
2407 let mut r = Registry::ui_set("test/maker");
2408 r.class::<clash::Lonely>();
2409 let failed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2411 r.module::<Maker>();
2412 }))
2413 .unwrap_err();
2414 let message = failed.downcast_ref::<String>().unwrap();
2415 assert!(
2416 message.contains("`nsh_core::element::component::tests::clash::Lonely`")
2417 && message.contains("`nsh_core::element::component::tests::Lonely`"),
2418 "{message}"
2419 );
2420 }
2421
2422 #[test]
2423 fn components_are_named_after_their_types() {
2424 let mut registry = Registry::ui_set("test/ui");
2425 registry.register::<Stepper>();
2426 let specs = registry.specs();
2427 assert_eq!(
2428 specs[0].name,
2429 "nsh_core::element::component::tests::Stepper"
2430 );
2431 assert_eq!(specs[0].export, "Stepper");
2432 assert_eq!(export_name("app::picker::Picker<app::Fruit>"), "Picker");
2433 assert_eq!(export_name("Bare"), "Bare");
2434 }
2435
2436 mod other {
2437 use crate::prelude::*;
2438
2439 #[derive(Default)]
2441 pub(super) struct Stepper;
2442
2443 impl Component for Stepper {
2444 type Props = ();
2445 type Event = NoEvent;
2446
2447 fn view(_: (), _: crate::element::Scope<NoEvent>) -> impl IntoElement {
2448 view()
2449 }
2450 }
2451 }
2452
2453 #[test]
2454 #[should_panic(
2455 expected = "components `nsh_core::element::component::tests::Stepper` and `nsh_core::element::component::tests::other::Stepper` are both exported as `Stepper` in `test/ui`"
2456 )]
2457 fn two_components_of_one_set_cannot_share_an_export() {
2458 Registry::ui_set("test/ui")
2459 .register::<Stepper>()
2460 .register::<other::Stepper>();
2461 }
2462
2463 #[test]
2464 #[should_panic(
2465 expected = "component `nsh_core::element::component::tests::Stepper` is registered twice"
2466 )]
2467 fn a_component_is_registered_once() {
2468 Registry::new().register::<Stepper>().register::<Stepper>();
2469 }
2470
2471 #[test]
2474 fn a_sets_submodules_come_with_it() {
2475 let mut sub = Registry::ui_set("test/set/sub");
2476 sub.register::<Stepper>();
2477 let mut set = Registry::ui_set("test/set");
2478 set.submodule(sub);
2479 let specifiers: Vec<_> = set.sets().iter().map(|s| s.specifier()).collect();
2480 assert_eq!(specifiers, [Some("test/set"), Some("test/set/sub")]);
2481 assert_eq!(Registry::merged(&[set]).specs().len(), 1);
2482 let elsewhere = std::panic::catch_unwind(|| {
2484 Registry::ui_set("test/set").submodule(Registry::ui_set("test/settings"));
2485 });
2486 assert!(elsewhere.is_err());
2487 }
2488
2489 #[test]
2490 fn sets_may_share_exports_but_not_components() {
2491 let mut a = Registry::ui_set("test/a");
2492 a.register::<Stepper>();
2493 let mut b = Registry::ui_set("test/b");
2494 b.register::<other::Stepper>();
2495 let merged = Registry::merged(&[a.clone(), b]);
2496 assert_eq!(merged.specs().len(), 2);
2497 let twice = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2498 Registry::merged(&[a.clone(), a])
2499 }));
2500 let message = *twice.unwrap_err().downcast::<String>().unwrap();
2501 assert_eq!(
2502 message,
2503 "component `nsh_core::element::component::tests::Stepper` is registered twice, by two UI sets"
2504 );
2505 }
2506
2507 struct NoFake;
2508
2509 impl crate::fake::Fake for NoFake {
2510 fn install(&self) {}
2511
2512 fn call(&self, _: &str, _: &[crate::JsonValue]) -> Result<crate::JsonValue, String> {
2513 Ok(crate::JsonValue::Null)
2514 }
2515 }
2516
2517 #[test]
2519 fn fake_names_are_unique_across_sets() {
2520 let mut a = Registry::ui_set("test/a");
2521 a.fake("test/mic", Arc::new(NoFake));
2522 let mut b = Registry::ui_set("test/b");
2523 b.fake("test/camera", Arc::new(NoFake));
2524 let names: Vec<_> = Registry::merged(&[a.clone(), b])
2525 .fakes()
2526 .into_iter()
2527 .map(|(name, _)| name)
2528 .collect();
2529 assert_eq!(names, ["test/mic", "test/camera"]);
2530 let mut c = Registry::ui_set("test/c");
2531 c.fake("test/mic", Arc::new(NoFake));
2532 let twice =
2533 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| Registry::merged(&[a, c])));
2534 let message = *twice.unwrap_err().downcast::<String>().unwrap();
2535 assert_eq!(message, "two fakes are named `test/mic`, by two UI sets");
2536 }
2537}
2538
2539#[cfg(test)]
2540mod root_tests {
2541 use super::Root;
2542 use crate::{access::Capabilities, prelude::*};
2543
2544 #[component]
2545 fn Empty() -> impl IntoElement {
2546 view()
2547 }
2548
2549 #[test]
2550 fn a_root_reads_its_declared_capabilities_as_packages_are_read() {
2551 assert_eq!(Root::of::<Empty>().capabilities_ref(), None);
2552 let root = Root::of::<Empty>().capabilities_json(r#"{"clipboard":true,"bluetooth":true}"#);
2554 let expected = Capabilities {
2555 clipboard: true,
2556 ..Capabilities::default()
2557 };
2558 assert_eq!(root.capabilities_ref(), Some(&expected));
2559 let root = Root::of::<Empty>().capabilities_json("not json");
2561 assert_eq!(root.capabilities_ref(), Some(&Capabilities::default()));
2562 }
2563}