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