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 call::{AnyValue, JsResult, MethodCall},
16 class::{Class, ClassDef, ClassSpec, MemberKind, Thrown},
17 element::{ComponentElement, ElNode},
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.params.iter().map(|(n, ts)| (*n, ts(types))).collect(),
173 returns: m.returns.map(|ts| ts(types)),
174 call: m.call,
175 })
176 .collect()
177}
178
179pub type Param = (&'static str, TsType);
181
182#[derive(Debug, Clone)]
184pub struct MethodSpec {
185 pub name: &'static str,
187 pub doc: &'static str,
189 pub params: Vec<(&'static str, String)>,
191 pub returns: Option<String>,
193 pub call: fn(&dyn JsHost) -> Result<MethodCall, Thrown>,
195}
196
197impl MethodSpec {
198 pub fn promises(&self) -> bool {
203 self.returns.is_some()
204 }
205}
206
207#[derive(Debug, Clone, Copy, PartialEq, Eq)]
209pub enum PropKind {
210 Value,
213 Renderer,
217 Slot,
219 Children,
221 Items,
224}
225
226pub type PropDecode = fn(JsIn<'_>) -> Result<AnyValue, PropError>;
230
231#[derive(Debug, Clone)]
233pub struct PropSpec {
234 pub name: &'static str,
236 pub ts: String,
238 pub optional: bool,
240 pub doc: &'static str,
242 pub kind: PropKind,
244 pub decode: Option<PropDecode>,
246}
247
248#[derive(Debug, Clone)]
250pub struct EventSpec {
251 pub name: &'static str,
253 pub arg: &'static str,
256 pub data: String,
258 pub doc: &'static str,
260 pub spread: bool,
264}
265
266pub trait Props: Clone + PartialEq + 'static {
268 #[doc(hidden)]
270 const ITEMS: Option<&'static str> = None;
271
272 #[doc(hidden)]
275 const LAZY_CHILDREN: bool = false;
276
277 fn spec(types: &mut TsTypes) -> Vec<PropSpec>;
279
280 fn initial() -> Self;
282
283 fn set(&mut self, name: &str, value: Option<AnyValue>) -> Result<bool, PropError>;
286
287 fn set_slot(&mut self, name: &str, slot: Option<Slot>) -> bool;
289
290 fn set_children(&mut self, children: Children) -> bool;
292
293 #[doc(hidden)]
296 fn held(&self) -> Self {
297 self.clone()
298 }
299
300 #[doc(hidden)]
304 fn update_from(&mut self, new: &Self) -> bool {
305 if self == new {
306 return false;
307 }
308 *self = new.clone();
309 true
310 }
311}
312
313impl Props for () {
315 fn spec(_: &mut TsTypes) -> Vec<PropSpec> {
316 Vec::new()
317 }
318
319 fn initial() -> Self {}
320
321 fn set(&mut self, name: &str, _: Option<AnyValue>) -> Result<bool, PropError> {
322 Err(PropError(format!("unknown prop `{name}`")))
323 }
324
325 fn set_slot(&mut self, _: &str, _: Option<Slot>) -> bool {
326 false
327 }
328
329 fn set_children(&mut self, _: Children) -> bool {
330 false
331 }
332}
333
334pub trait Event: 'static {
341 fn spec(types: &mut TsTypes) -> Vec<EventSpec>;
343
344 fn name(&self) -> &'static str;
346
347 fn data_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError>;
349
350 fn spread(&self) -> bool {
353 false
354 }
355}
356
357#[derive(Debug, Clone, Copy, PartialEq, Eq)]
359pub enum NoEvent {}
360
361impl Event for NoEvent {
362 fn spec(_types: &mut TsTypes) -> Vec<EventSpec> {
363 Vec::new()
364 }
365
366 fn name(&self) -> &'static str {
367 match *self {}
368 }
369
370 fn data_js<'a>(&self, _host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
371 match *self {}
372 }
373}
374
375#[derive(Debug, Clone)]
378pub struct ComponentSpec {
379 pub name: &'static str,
382 pub export: String,
384 pub doc: &'static str,
386 pub props: Vec<PropSpec>,
388 pub events: Vec<EventSpec>,
390 pub methods: Vec<MethodSpec>,
392 pub types: TsTypes,
394 pub lazy_children: bool,
398}
399
400impl ComponentSpec {
401 pub(crate) fn of<C: Component>() -> Self {
402 let mut types = TsTypes::default();
403 let props = C::Props::spec(&mut types);
404 let events = C::Event::spec(&mut types);
405 let methods = (C::METHODS.specs)(&mut types);
406 let name = name_of::<C>();
407 Self {
408 name,
409 export: export_name(name).to_owned(),
410 doc: C::DOC,
411 props,
412 events,
413 methods,
414 types,
415 lazy_children: C::Props::LAZY_CHILDREN,
416 }
417 }
418
419 pub fn slots(&self) -> impl Iterator<Item = &'static str> + '_ {
421 self.props
422 .iter()
423 .filter(|p| p.kind == PropKind::Slot)
424 .map(|p| p.name)
425 }
426
427 pub fn renderers(&self) -> impl Iterator<Item = &'static str> + '_ {
429 self.props
430 .iter()
431 .filter(|p| p.kind == PropKind::Renderer)
432 .map(|p| p.name)
433 }
434
435 pub fn takes_children(&self) -> bool {
437 self.props.iter().any(|p| p.kind == PropKind::Children)
438 }
439
440 pub fn items(&self) -> Option<&'static str> {
442 self.props
443 .iter()
444 .find(|p| p.kind == PropKind::Items)
445 .map(|p| p.name)
446 }
447
448 pub(crate) fn holder(&self, name: &str) -> Option<&'static str> {
450 self.props
451 .iter()
452 .find(|p| matches!(p.kind, PropKind::Slot | PropKind::Items) && p.name == name)
453 .map(|p| p.name)
454 }
455}
456
457pub(crate) fn name_of<C: Component>() -> &'static str {
461 std::any::type_name::<C>()
462}
463
464fn export_name(type_name: &str) -> &str {
467 let path = type_name.split('<').next().unwrap_or(type_name);
468 path.rsplit("::").next().unwrap_or(path)
469}
470
471pub(crate) trait AnyInstance {
473 fn set_prop(&mut self, name: &str, value: Option<AnyValue>) -> Result<bool, PropError>;
474 fn set_props(&mut self, props: &dyn Any);
476 fn set_slot(&mut self, name: &'static str, filled: bool);
477 fn set_children(&mut self, present: bool);
478 fn cleanup(&mut self);
480 fn view(&mut self) -> ElNode;
482 fn name(&self) -> &'static str;
484 fn call(&mut self, call: MethodCall) -> Option<JsResult>;
487 fn owner(&self) -> Option<super::Owner>;
489 fn failure_owner(&self) -> super::Owner;
492 fn adopt(&mut self, parent: super::Owner);
496 fn place(&mut self, host: crate::NodeId, parent: super::Owner);
498}
499
500#[derive(Clone)]
504pub struct Root {
505 make: Arc<dyn Fn() -> super::AnyElement + Send + Sync>,
506 tokens: Option<Arc<super::Tokens>>,
507 fonts: Vec<Arc<[u8]>>,
508 appearance: Option<crate::platform::Appearance>,
509 app_id: Option<String>,
510 status_bar: Option<crate::StatusBarSetting>,
511}
512
513impl Root {
514 pub fn new<C: Component>(props: impl Fn() -> C::Props + Send + Sync + 'static) -> Self {
516 Self {
517 make: Arc::new(move || super::IntoElement::into_element(C::element(props()))),
518 tokens: None,
519 fonts: Vec::new(),
520 appearance: None,
521 app_id: None,
522 status_bar: None,
523 }
524 }
525
526 pub fn app_id(mut self, id: impl Into<String>) -> Self {
529 self.app_id = Some(id.into());
530 self
531 }
532
533 pub fn app_id_ref(&self) -> Option<&str> {
535 self.app_id.as_deref()
536 }
537
538 pub fn tokens(mut self, tokens: super::Tokens) -> Self {
541 self.tokens = Some(Arc::new(tokens));
542 self
543 }
544
545 pub fn font(mut self, data: impl Into<Arc<[u8]>>) -> Self {
548 self.fonts.push(data.into());
549 self
550 }
551
552 pub fn appearance(mut self, appearance: crate::platform::Appearance) -> Self {
556 self.appearance = Some(appearance);
557 self
558 }
559
560 pub fn status_bar(mut self, setting: crate::StatusBarSetting) -> Self {
563 self.status_bar = Some(setting);
564 self
565 }
566
567 pub fn status_bar_ref(&self) -> Option<crate::StatusBarSetting> {
569 self.status_bar
570 }
571
572 pub fn appearance_ref(&self) -> Option<crate::platform::Appearance> {
575 self.appearance
576 }
577
578 pub fn tokens_ref(&self) -> Option<&super::Tokens> {
580 self.tokens.as_deref()
581 }
582
583 pub fn fonts(&self) -> &[Arc<[u8]>] {
585 &self.fonts
586 }
587
588 pub fn of<C: Component>() -> Self
590 where
591 C::Props: Default,
592 {
593 Self::new::<C>(C::Props::default)
594 }
595
596 pub(crate) fn element(&self) -> super::AnyElement {
598 (self.make)()
599 }
600}
601
602impl fmt::Debug for Root {
603 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
604 f.write_str("Root")
605 }
606}
607
608pub(crate) fn make_instance<C: Component>() -> Box<dyn AnyInstance> {
610 Box::new(super::once::OnceInstance::<C>::new())
611}
612
613#[derive(Clone)]
614struct ComponentType {
615 spec: Arc<ComponentSpec>,
616 make: fn() -> Box<dyn AnyInstance>,
617 id: TypeId,
619}
620
621#[derive(Clone)]
622struct ModuleType {
623 spec: Arc<ModuleSpec>,
624 type_name: &'static str,
626}
627
628#[derive(Clone)]
629struct ClassType {
630 spec: Arc<ClassSpec>,
631 type_name: &'static str,
633}
634
635#[derive(Clone, Default)]
638pub struct Registry {
639 types: Arc<FxHashMap<&'static str, ComponentType>>,
640 modules: Arc<FxHashMap<&'static str, ModuleType>>,
641 classes: Arc<FxHashMap<(Option<&'static str>, &'static str), ClassType>>,
644 reexports: Arc<(Vec<&'static str>, Vec<&'static str>)>,
646 native_values: Arc<Vec<&'static str>>,
649 namespace: Option<&'static str>,
652 ui_set: Option<&'static str>,
654 assets: Arc<Vec<&'static [super::AssetFile]>>,
656 tokens: Option<super::TokenSource>,
658}
659
660impl fmt::Debug for Registry {
661 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
662 f.debug_set().entries(self.types.keys()).finish()
663 }
664}
665
666impl Registry {
667 pub fn new() -> Self {
669 Self::default()
670 }
671
672 #[track_caller]
681 pub fn register<C: Component>(&mut self) -> &mut Self {
682 let spec = ComponentSpec::of::<C>();
683 let types = Arc::make_mut(&mut self.types);
684 if let Some(old) = types.get(spec.name) {
685 let set = self.ui_set.or(self.namespace);
686 panic!("{}", same_name(spec.name, old.id, TypeId::of::<C>(), set));
687 }
688 if self.classes.keys().any(|(_, name)| *name == spec.export) {
689 panic!(
690 "component `{}` is exported as `{}` like a class{}: rename one",
691 spec.name,
692 spec.export,
693 of_set(self.ui_set.or(self.namespace)),
694 );
695 }
696 if let Some(other) = types.values().find(|t| t.spec.export == spec.export) {
697 panic!(
698 "components `{}` and `{}` are both exported as `{}`{}: rename one",
699 other.spec.name,
700 spec.name,
701 spec.export,
702 of_set(self.ui_set.or(self.namespace)),
703 );
704 }
705 types.insert(
706 spec.name,
707 ComponentType {
708 spec: Arc::new(spec),
709 make: make_instance::<C>,
710 id: TypeId::of::<C>(),
711 },
712 );
713 let mut refs = Vec::new();
714 (C::METHODS.refs)(&mut refs);
715 self.classes_named(refs)
716 }
717
718 #[track_caller]
726 pub fn module<M: Module>(&mut self) -> &mut Self {
727 let type_name = std::any::type_name::<M>();
728 if self.classes.keys().any(|(_, name)| *name == M::NAME) {
729 panic!(
730 "module `{type_name}` is named `{}` like a class{}: rename one",
731 M::NAME,
732 of_set(self.ui_set.or(self.namespace))
733 );
734 }
735 let modules = Arc::make_mut(&mut self.modules);
736 if let Some(old) = modules.get(M::NAME) {
737 panic!(
738 "{}",
739 same_module(
740 M::NAME,
741 old.type_name,
742 type_name,
743 self.ui_set.or(self.namespace)
744 )
745 );
746 }
747 modules.insert(
748 M::NAME,
749 ModuleType {
750 spec: Arc::new(ModuleSpec::of::<M>()),
751 type_name,
752 },
753 );
754 let mut refs = Vec::new();
755 for f in M::FUNCTIONS {
756 (f.refs)(&mut refs);
757 }
758 self.classes_named(refs)
759 }
760
761 #[track_caller]
774 pub fn class<C: Class>(&mut self) -> &mut Self {
775 self.class_def(C::DEF)
776 }
777
778 #[track_caller]
781 fn classes_named(&mut self, refs: Vec<&'static ClassDef>) -> &mut Self {
782 for def in refs {
783 self.class_def(def);
784 }
785 self
786 }
787
788 #[track_caller]
789 fn class_def(&mut self, def: &'static ClassDef) -> &mut Self {
790 let type_name = (def.type_name)();
791 let set = self.ui_set.or(self.namespace);
792 if let Some(old) = self.classes.get(&(set, def.name)) {
793 if (old.spec.def.type_id)() == (def.type_id)() {
794 return self;
795 }
796 panic!("{}", same_class(def.name, old.type_name, type_name, set));
797 }
798 if self.modules.contains_key(def.name)
799 || self.types.values().any(|t| t.spec.export == def.name)
800 {
801 panic!(
802 "class `{type_name}` is named `{}` like a module or a component{}: rename one",
803 def.name,
804 of_set(set)
805 );
806 }
807 Arc::make_mut(&mut self.classes).insert(
808 (set, def.name),
809 ClassType {
810 spec: Arc::new(ClassSpec::of(def)),
811 type_name,
812 },
813 );
814 let mut refs = Vec::new();
816 for m in def.members {
817 (m.refs)(&mut refs);
818 }
819 self.classes_named(refs)
820 }
821
822 pub fn reexport(&mut self, values: &[&'static str], types: &[&'static str]) -> &mut Self {
825 let r = Arc::make_mut(&mut self.reexports);
826 r.0.extend_from_slice(values);
827 r.1.extend_from_slice(types);
828 self
829 }
830
831 #[track_caller]
842 pub fn merged(sets: &[Registry]) -> Self {
843 let mut out = Self::default();
844 for set in sets {
845 out.tokens = out.tokens.or(set.tokens);
846 let types = Arc::make_mut(&mut out.types);
847 for (name, ty) in set.types.iter() {
848 if let Some(old) = types.insert(name, ty.clone()) {
849 panic!("{}, by two UI sets", same_name(name, old.id, ty.id, None));
850 }
851 }
852 }
853 out
854 }
855
856 pub fn ui_set(specifier: &'static str) -> Self {
860 Self {
861 ui_set: Some(specifier),
862 ..Self::default()
863 }
864 }
865
866 pub fn specifier(&self) -> Option<&'static str> {
869 self.ui_set.or(self.namespace)
870 }
871
872 pub fn reexports(&self) -> (&[&'static str], &[&'static str]) {
875 (&self.reexports.0, &self.reexports.1)
876 }
877
878 pub fn native_values(&mut self, values: &[&'static str]) -> &mut Self {
881 Arc::make_mut(&mut self.native_values).extend_from_slice(values);
882 self
883 }
884
885 pub fn assets(&mut self, files: &'static [super::AssetFile]) -> &mut Self {
890 Arc::make_mut(&mut self.assets).push(files);
891 self
892 }
893
894 pub fn tokens_from(&mut self, source: super::TokenSource) -> &mut Self {
897 self.tokens = Some(source);
898 self
899 }
900
901 pub fn tokens(&self, json: Option<&str>) -> Option<Result<super::Tokens, String>> {
905 self.tokens.map(|source| source(json))
906 }
907
908 pub fn asset_files(&self) -> impl Iterator<Item = &'static super::AssetFile> + '_ {
910 self.assets.iter().flat_map(|files| files.iter())
911 }
912
913 pub fn native_value_names(&self) -> &[&'static str] {
915 &self.native_values
916 }
917
918 pub(crate) fn runtime(namespace: &'static str) -> Self {
920 Self {
921 namespace: Some(namespace),
922 ..Self::default()
923 }
924 }
925
926 pub fn namespace(&self) -> Option<&'static str> {
929 self.namespace
930 }
931
932 pub fn class_specs(&self) -> Vec<Arc<ClassSpec>> {
934 let mut specs: Vec<_> = self.classes.values().map(|c| c.spec.clone()).collect();
935 specs.sort_by_key(|s| s.name);
936 specs
937 }
938
939 pub fn module_specs(&self) -> Vec<Arc<ModuleSpec>> {
941 let mut specs: Vec<_> = self.modules.values().map(|m| m.spec.clone()).collect();
942 specs.sort_by_key(|s| s.name);
943 specs
944 }
945
946 pub fn function_members(&self, function: &str) -> Option<Arc<ModuleSpec>> {
951 let exported = self.modules.values().any(|m| {
952 m.spec.flat
953 && m.spec
954 .functions
955 .iter()
956 .any(|f| !f.getter && f.name == function)
957 });
958 exported
959 .then(|| {
960 self.modules
961 .values()
962 .find(|m| !m.spec.flat && m.spec.name == function)
963 .map(|m| m.spec.clone())
964 })
965 .flatten()
966 }
967
968 pub fn specs(&self) -> Vec<Arc<ComponentSpec>> {
970 let mut specs: Vec<_> = self.types.values().map(|t| t.spec.clone()).collect();
971 specs.sort_by(|a, b| a.export.cmp(&b.export).then(a.name.cmp(b.name)));
972 specs
973 }
974
975 pub fn undocumented(&self) -> Vec<String> {
984 let mut out = Vec::new();
985 let specs = self.specs();
986 for c in &specs {
987 if c.doc.is_empty() {
988 out.push(c.export.clone());
989 }
990 for p in c.props.iter().filter(|p| p.doc.is_empty()) {
991 out.push(format!("{}.{}", c.export, p.name));
992 }
993 for e in c.events.iter().filter(|e| e.doc.is_empty()) {
994 out.push(format!("{}.{}", c.export, handler_name(e.name)));
995 }
996 for m in c.methods.iter().filter(|m| m.doc.is_empty()) {
997 out.push(format!("{}.{}", c.export, m.name));
998 }
999 }
1000 for m in self.module_specs() {
1001 let merged = specs.iter().any(|c| c.export == m.name)
1002 || (!m.flat && self.function_members(m.name).is_some());
1003 if m.doc.is_empty() && !merged && !m.flat {
1004 out.push(m.name.to_owned());
1005 }
1006 for f in m.functions.iter().filter(|f| f.doc.is_empty()) {
1007 out.push(if m.flat {
1008 f.name.to_owned()
1009 } else {
1010 format!("{}.{}", m.name, f.name)
1011 });
1012 }
1013 }
1014 for c in self.class_specs() {
1015 if c.doc.is_empty() {
1016 out.push(c.name.to_owned());
1017 }
1018 let documented_getter = |name: &str| {
1019 c.members
1020 .iter()
1021 .any(|m| m.kind == MemberKind::Getter && m.name == name && !m.doc.is_empty())
1022 };
1023 for m in c.members.iter().filter(|m| m.doc.is_empty()) {
1024 match m.kind {
1025 MemberKind::Constructor => out.push(format!("new {}", c.name)),
1026 MemberKind::Setter if documented_getter(m.name) => {}
1027 _ => out.push(format!("{}.{}", c.name, m.name)),
1028 }
1029 }
1030 }
1031 out
1032 }
1033
1034 pub(crate) fn make(&self, name: &str) -> Option<(Arc<ComponentSpec>, Box<dyn AnyInstance>)> {
1036 self.types.get(name).map(|t| (t.spec.clone(), (t.make)()))
1037 }
1038}
1039
1040fn same_name(name: &str, old: TypeId, new: TypeId, set: Option<&str>) -> String {
1042 if old == new {
1043 format!("component `{name}` is registered twice{}", of_set(set))
1044 } else {
1045 format!(
1046 "two different types named `{name}` are registered{} (two versions of one crate?)",
1047 of_set(set)
1048 )
1049 }
1050}
1051
1052fn same_module(name: &str, old: &str, new: &str, set: Option<&str>) -> String {
1054 if old == new {
1055 format!("module `{old}` is registered twice{}", of_set(set))
1056 } else {
1057 format!(
1058 "modules `{old}` and `{new}` are both named `{name}`{}: rename one",
1059 of_set(set)
1060 )
1061 }
1062}
1063
1064fn same_class(name: &str, old: &str, new: &str, set: Option<&str>) -> String {
1066 if old == new {
1067 format!("class `{old}` is registered twice{}", of_set(set))
1068 } else {
1069 format!(
1070 "classes `{old}` and `{new}` are both named `{name}`{}: rename one",
1071 of_set(set)
1072 )
1073 }
1074}
1075
1076fn of_set(set: Option<&str>) -> String {
1078 set.map(|s| format!(" in `{s}`")).unwrap_or_default()
1079}
1080
1081pub fn declarations(registry: &Registry, omit: &[&str]) -> String {
1090 let specs = registry.specs();
1091 let modules = registry.module_specs();
1092 let classes = registry.class_specs();
1093 use std::fmt::Write as _;
1094 let mut out = String::new();
1095 let doc = |out: &mut String, indent: &str, doc: &str| {
1096 if !doc.is_empty() {
1097 let _ = writeln!(out, "{indent}/** {doc} */");
1098 }
1099 };
1100 let mut types = TsTypes::default();
1102 for spec in &specs {
1103 types.merge(&spec.types);
1104 }
1105 for m in &modules {
1106 types.merge(&m.types);
1107 }
1108 for c in &classes {
1109 types.merge(&c.types);
1110 }
1111 for declaration in types.declarations() {
1112 let _ = write!(out, "{declaration}\n\n");
1113 }
1114 let module_of = |name: &str| modules.iter().find(|m| m.name == name);
1115 let signatures = |f: &FunctionSpec| {
1117 let one = |params: &[(&str, String, bool)], returns: &Option<String>| {
1118 let params = params
1119 .iter()
1120 .map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
1121 .collect::<Vec<_>>()
1122 .join(", ");
1123 let value = returns.clone().unwrap_or_else(|| "void".to_owned());
1124 let returns = if f.promises() {
1125 format!("Promise<{value}>")
1126 } else {
1127 value
1128 };
1129 (params, returns)
1130 };
1131 if f.overloads.is_empty() {
1132 vec![one(&f.params, &f.returns)]
1133 } else {
1134 f.overloads
1135 .iter()
1136 .map(|(params, returns)| one(params, returns))
1137 .collect()
1138 }
1139 };
1140 let module_object = |out: &mut String, m: &ModuleSpec| {
1142 out.push_str("{\n");
1143 for f in &m.functions {
1144 for (params, returns) in signatures(f) {
1145 doc(out, " ", f.doc);
1146 if f.getter {
1147 let _ = writeln!(out, " readonly {}: {returns};", f.name);
1148 continue;
1149 }
1150 let _ = writeln!(out, " {}({params}): {returns};", f.name);
1151 }
1152 }
1153 for constant in &m.constants {
1154 doc(out, " ", constant.doc);
1155 let _ = writeln!(
1156 out,
1157 " readonly {}: {};",
1158 constant.name,
1159 constant.value.ts_type()
1160 );
1161 }
1162 out.push('}');
1163 };
1164 for spec in &specs {
1165 let (generic, extends) = match spec.items() {
1167 Some(_) => ("<T>", ", ListItemsProps<T>"),
1168 None => ("", ""),
1169 };
1170 let host = if spec.methods.is_empty() {
1172 "ComponentHostProps"
1173 } else {
1174 let _ = write!(
1175 out,
1176 "/** The ref of `{0}`: its methods. */\nexport interface {0}Ref {{\n /** The component's host node. */\n readonly node: YNode;\n",
1177 spec.export
1178 );
1179 for m in &spec.methods {
1180 doc(&mut out, " ", m.doc);
1181 let params = m
1182 .params
1183 .iter()
1184 .map(|(n, ts)| format!("{n}: {ts}"))
1185 .collect::<Vec<_>>()
1186 .join(", ");
1187 let returns = match &m.returns {
1188 Some(ts) => format!("Promise<{ts}>"),
1189 None => "void".to_owned(),
1190 };
1191 let _ = writeln!(out, " {}({params}): {returns};", m.name);
1192 }
1193 out.push_str("}\n\n");
1194 "Omit<ComponentHostProps, \"ref\">"
1195 };
1196 let _ = writeln!(
1197 out,
1198 "export interface {}Props{generic} extends {host}{extends} {{",
1199 spec.export
1200 );
1201 if !spec.methods.is_empty() {
1202 let _ = writeln!(
1203 out,
1204 " ref?: {0}Ref | ((ref: {0}Ref) => void);",
1205 spec.export
1206 );
1207 }
1208 for p in spec.props.iter().filter(|p| p.kind != PropKind::Items) {
1209 doc(&mut out, " ", p.doc);
1210 let optional = if p.optional { "?" } else { "" };
1211 let _ = writeln!(out, " {}{optional}: {};", p.name, p.ts);
1212 }
1213 for e in &spec.events {
1214 doc(&mut out, " ", e.doc);
1215 let handler = handler_name(e.name);
1216 let arg = if e.data == "void" {
1217 String::new()
1218 } else if e.spread {
1219 e.data.clone()
1220 } else {
1221 format!("{}: {}", e.arg, e.data)
1222 };
1223 let _ = writeln!(out, " {handler}?: ({arg}) => void;");
1224 }
1225 out.push_str("}\n\n");
1226 if omit.contains(&spec.export.as_str()) {
1227 continue;
1228 }
1229 doc(&mut out, "", spec.doc);
1230 let mut with = String::new();
1232 if let Some(m) = module_of(&spec.export) {
1233 with.push_str(" & ");
1234 module_object(&mut with, m);
1235 }
1236 let _ = write!(
1237 out,
1238 "export declare const {}: ({generic}(props: {}Props{generic}) => JSX.Element){with};\n\n",
1239 spec.export, spec.export,
1240 );
1241 }
1242 for m in &modules {
1243 if specs.iter().any(|s| s.export == m.name)
1244 || (!m.flat && registry.function_members(m.name).is_some())
1245 {
1246 continue;
1247 }
1248 if m.flat {
1249 for f in m
1250 .functions
1251 .iter()
1252 .filter(|f| !f.getter && !omit.contains(&f.name))
1253 {
1254 for (params, returns) in signatures(f) {
1255 doc(&mut out, "", f.doc);
1256 let _ = writeln!(
1257 out,
1258 "export declare function {}({params}): {returns};",
1259 f.name
1260 );
1261 }
1262 if let Some(members) = registry.function_members(f.name) {
1264 let _ = writeln!(out, "export declare namespace {} {{", f.name);
1265 for member in &members.functions {
1266 for (params, returns) in signatures(member) {
1267 doc(&mut out, " ", member.doc);
1268 let _ = if member.getter {
1269 writeln!(out, " const {}: {returns};", member.name)
1270 } else {
1271 writeln!(out, " function {}({params}): {returns};", member.name)
1272 };
1273 }
1274 }
1275 for constant in &members.constants {
1276 doc(&mut out, " ", constant.doc);
1277 let _ = writeln!(
1278 out,
1279 " const {}: {};",
1280 constant.name,
1281 constant.value.ts_type()
1282 );
1283 }
1284 out.push_str("}\n");
1285 }
1286 out.push('\n');
1287 }
1288 for constant in &m.constants {
1289 if !omit.contains(&constant.name) {
1290 doc(&mut out, "", constant.doc);
1291 let _ = writeln!(
1292 out,
1293 "export declare const {}: {};\n",
1294 constant.name,
1295 constant.value.ts_type()
1296 );
1297 }
1298 }
1299 if m.default && !omit.contains(&"default") {
1300 let _ = write!(out, "declare const defaultExport: ");
1301 module_object(&mut out, m);
1302 for native in registry.native_value_names() {
1304 let _ = write!(out, " & {{ {native}: typeof {native} }}");
1305 }
1306 out.push_str(";\nexport default defaultExport;\n\n");
1307 }
1308 continue;
1309 }
1310 doc(&mut out, "", m.doc);
1311 let _ = write!(out, "export interface {}Module ", m.name);
1312 module_object(&mut out, m);
1313 out.push_str("\n\n");
1314 if !omit.contains(&m.name) {
1315 doc(&mut out, "", m.doc);
1316 let _ = write!(out, "export declare const {0}: {0}Module;\n\n", m.name);
1317 }
1318 if m.default && !omit.contains(&"default") {
1319 let _ = write!(
1320 out,
1321 "declare const defaultExport: {}Module;\nexport default defaultExport;\n\n",
1322 m.name
1323 );
1324 }
1325 }
1326 for c in classes.iter().filter(|c| !omit.contains(&c.name)) {
1327 class_declaration(&mut out, c);
1328 }
1329 out
1330}
1331
1332fn class_declaration(out: &mut String, c: &ClassSpec) {
1334 use std::fmt::Write as _;
1335 let doc = |out: &mut String, indent: &str, doc: &str| {
1336 if !doc.is_empty() {
1337 let _ = writeln!(out, "{indent}/** {doc} */");
1338 }
1339 };
1340 doc(out, "", c.doc);
1341 if c.def.interface {
1342 let _ = writeln!(out, "export interface {} {{", c.name);
1344 for m in &c.members {
1345 let params = m
1346 .params
1347 .iter()
1348 .map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
1349 .collect::<Vec<_>>()
1350 .join(", ");
1351 let value = m.returns.clone().unwrap_or_else(|| "void".to_owned());
1352 let returns = if m.is_async {
1353 format!("Promise<{value}>")
1354 } else {
1355 value
1356 };
1357 doc(out, " ", m.doc);
1358 let has_setter = |name| {
1359 c.members
1360 .iter()
1361 .any(|s| s.kind == MemberKind::Setter && s.name == name)
1362 };
1363 let _ = match m.kind {
1364 MemberKind::Method => writeln!(out, " {}({params}): {returns};", m.name),
1365 MemberKind::Getter if has_setter(m.name) => {
1366 writeln!(out, " {}: {returns};", m.name)
1367 }
1368 MemberKind::Getter => writeln!(out, " readonly {}: {returns};", m.name),
1369 _ => Ok(()),
1372 };
1373 }
1374 out.push_str("}\n\n");
1375 return;
1376 }
1377 let _ = writeln!(out, "export declare class {} {{", c.name);
1378 if !c.members.iter().any(|m| m.kind == MemberKind::Constructor) {
1379 out.push_str(" /** Made by the class's members only. */\n private constructor();\n");
1380 }
1381 let one = |m: &super::MemberSpec, params: &[(&str, String, bool)], returns: &Option<String>| {
1382 let params = params
1383 .iter()
1384 .map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
1385 .collect::<Vec<_>>()
1386 .join(", ");
1387 let value = returns.clone().unwrap_or_else(|| "void".to_owned());
1388 let returns = if m.is_async {
1389 format!("Promise<{value}>")
1390 } else {
1391 value
1392 };
1393 (params, returns)
1394 };
1395 for m in &c.members {
1396 if !m.overloads.is_empty() {
1397 for (params, returns) in &m.overloads {
1398 doc(out, " ", m.doc);
1399 let (params, returns) = one(m, params, returns);
1400 let _ = match m.kind {
1401 MemberKind::Static => {
1402 writeln!(out, " static {}({params}): {returns};", m.name)
1403 }
1404 _ => writeln!(out, " {}({params}): {returns};", m.name),
1405 };
1406 }
1407 continue;
1408 }
1409 doc(out, " ", m.doc);
1410 let (params, returns) = one(m, &m.params, &m.returns);
1411 let _ = match m.kind {
1412 MemberKind::Constructor => writeln!(out, " constructor({params});"),
1413 MemberKind::Method => writeln!(out, " {}({params}): {returns};", m.name),
1414 MemberKind::Getter => writeln!(out, " get {}(): {returns};", m.name),
1415 MemberKind::Setter => writeln!(out, " set {}({params});", m.name),
1416 MemberKind::Static => writeln!(out, " static {}({params}): {returns};", m.name),
1417 };
1418 }
1419 out.push_str(
1420 " /** 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",
1421 );
1422}
1423
1424fn handler_name(event: &str) -> String {
1426 let mut chars = event.chars();
1427 match chars.next() {
1428 Some(first) => format!("on{}{}", first.to_ascii_uppercase(), chars.as_str()),
1429 None => "on".to_owned(),
1430 }
1431}
1432
1433#[cfg(test)]
1434mod tests {
1435 use super::*;
1436 use crate::ui::prelude::*;
1437
1438 #[derive(Default)]
1439 struct Stepper;
1440
1441 #[derive(Clone, PartialEq, Props)]
1443 struct StepperProps {
1444 value: f64,
1446 #[prop(default)]
1447 size: StepperSize,
1448 max_value: Option<f64>,
1449 label: Option<Slot>,
1451 children: Children,
1452 }
1453
1454 #[derive(Clone, Copy, PartialEq, Default, PropEnum)]
1455 enum StepperSize {
1456 #[default]
1457 Regular,
1458 ExtraLarge,
1459 }
1460
1461 #[derive(Event)]
1462 enum StepperEvent {
1463 Change {
1465 new_value: f64,
1466 },
1467 #[args(limit)]
1468 Limit(u32),
1469 Reset,
1470 }
1471
1472 struct StepperApi;
1473
1474 #[methods]
1475 impl StepperApi {
1476 pub(crate) fn jump_to(&self, value: f64) {
1478 let _ = value;
1479 }
1480
1481 pub(crate) fn value(&self) -> f64 {
1482 0.0
1483 }
1484
1485 #[allow(dead_code)]
1487 fn clamp(&self, value: f64) -> f64 {
1488 value
1489 }
1490 }
1491
1492 impl Component for Stepper {
1493 type Props = StepperProps;
1494 type Event = StepperEvent;
1495 const METHODS: Methods = Methods::of::<StepperApi>();
1496 const DOC: &'static str = "Picks a number.";
1497
1498 fn view(_: StepperProps, _: super::super::Scope<StepperEvent>) -> impl IntoElement {
1499 view()
1500 }
1501 }
1502
1503 #[test]
1504 fn the_declarations_come_from_the_types() {
1505 let mut registry = Registry::new();
1506 registry.register::<Stepper>();
1507 let ts = declarations(®istry, &[]);
1508 for line in [
1509 " /** The value. */\n value: number;",
1510 "export type StepperSize = \"regular\" | \"extraLarge\";",
1511 " size?: StepperSize;",
1512 " maxValue?: number | null;",
1513 " /** Above the control. */\n label?: JSX.Element;",
1514 " children?: JSX.Element;",
1515 " /** The value changed. */\n onChange?: (event: { newValue: number }) => void;",
1516 " onLimit?: (limit: number) => void;",
1517 " onReset?: () => void;",
1518 "/** Picks a number. */",
1519 "export interface StepperRef {",
1520 " /** Jumps to `value`. */\n jumpTo(value: number): void;",
1521 " value(): Promise<number>;",
1522 "export interface StepperProps extends Omit<ComponentHostProps, \"ref\"> {\n ref?: StepperRef | ((ref: StepperRef) => void);",
1523 "export declare const Stepper: ((props: StepperProps) => JSX.Element);",
1524 ] {
1525 assert!(ts.contains(line), "missing {line:?} in\n{ts}");
1526 }
1527 assert!(!ts.contains("clamp"), "a helper is not a method:\n{ts}");
1528 assert_eq!(StepperApi::METHODS.len(), 2);
1529 let mut props = StepperProps::initial();
1530 let size = |json| {
1531 let specs = StepperProps::spec(&mut TsTypes::default());
1532 let decode = specs
1533 .iter()
1534 .find(|p| p.name == "size")
1535 .unwrap()
1536 .decode
1537 .unwrap();
1538 super::super::json_host::decode(decode, json)
1539 };
1540 assert!(
1541 props
1542 .set("size", Some(size(serde_json::json!("extraLarge")).unwrap()))
1543 .unwrap()
1544 );
1545 assert!(props.size == StepperSize::ExtraLarge);
1546 assert!(size(serde_json::json!("huge")).is_err());
1550 assert!(props.set("size", Some(AnyValue::new(1.0f64))).is_err());
1551 assert!(props.set("size", None).unwrap());
1552 assert!(props.size == StepperSize::Regular);
1553 let data = |e: &StepperEvent| super::super::json_host::event_data(e);
1554 assert_eq!(
1555 data(&StepperEvent::Change { new_value: 2.5 }),
1556 Some(serde_json::json!({ "newValue": 2.5 }))
1557 );
1558 assert_eq!(data(&StepperEvent::Limit(3)), Some(serde_json::json!(3)));
1559 assert_eq!(data(&StepperEvent::Reset), None);
1560 assert_eq!(StepperEvent::Reset.name(), "reset");
1561 }
1562
1563 #[test]
1564 fn exports_without_docs_are_listed() {
1565 let mut registry = Registry::new();
1566 registry.register::<Stepper>();
1567 assert_eq!(
1570 registry.undocumented(),
1571 [
1572 "Stepper.size",
1573 "Stepper.maxValue",
1574 "Stepper.children",
1575 "Stepper.onLimit",
1576 "Stepper.onReset",
1577 "Stepper.value",
1578 ]
1579 );
1580 let mut r = Registry::ui_set("test/maker");
1581 r.module::<Maker>();
1582 assert_eq!(r.undocumented(), ["Maker.make", "new Lonely"]);
1583 }
1584
1585 #[crate::ui::class]
1587 struct Lonely;
1588
1589 #[crate::ui::class]
1590 impl Lonely {
1591 pub(crate) fn new() -> Self {
1592 Lonely
1593 }
1594 }
1595
1596 #[crate::ui::module]
1598 struct Maker;
1599
1600 #[crate::ui::module]
1601 impl Maker {
1602 pub(crate) fn make() -> Instance<Lonely> {
1603 Instance::new(Lonely)
1604 }
1605 }
1606
1607 #[test]
1608 fn the_classes_a_signature_names_are_registered_with_it() {
1609 let mut r = Registry::ui_set("test/maker");
1610 r.module::<Maker>();
1611 let names: Vec<_> = r.class_specs().iter().map(|c| c.name).collect();
1614 assert_eq!(names, ["Lonely"]);
1615 let ts = declarations(&r, &[]);
1616 assert!(ts.contains("export declare class Lonely"), "{ts}");
1617 assert!(ts.contains("make(): Lonely;"), "{ts}");
1618 r.class::<Lonely>();
1620 assert_eq!(r.class_specs().len(), 1);
1621 let _ = Registry::merged(&[r]);
1622 }
1623
1624 #[crate::ui::module]
1626 struct Checks;
1627
1628 #[crate::ui::module(flat)]
1629 impl Checks {
1630 pub(crate) fn check(name: String) {
1632 let _ = name;
1633 }
1634 }
1635
1636 #[crate::ui::module]
1638 struct CheckVariants;
1639
1640 #[crate::ui::module(name = "check")]
1641 impl CheckVariants {
1642 pub(crate) const COUNT: u32 = 2;
1644
1645 pub(crate) fn skip(name: String) {
1647 let _ = name;
1648 }
1649
1650 pub(crate) fn todo(name: String) {
1651 let _ = name;
1652 }
1653 }
1654
1655 #[crate::ui::module]
1657 struct Loose;
1658
1659 #[crate::ui::module(name = "loose")]
1660 impl Loose {
1661 pub(crate) fn nothing() {}
1663 }
1664
1665 #[test]
1666 fn a_module_named_like_a_function_puts_its_functions_on_it() {
1667 let mut r = Registry::ui_set("test/checks");
1668 r.module::<Checks>()
1669 .module::<CheckVariants>()
1670 .module::<Loose>();
1671 assert_eq!(r.function_members("check").unwrap().name, "check");
1672 assert!(r.function_members("loose").is_none());
1673 let ts = declarations(&r, &[]);
1674 assert!(
1675 ts.contains(
1676 "/** Declares a check. */\n\
1677 export declare function check(name: string): void;\n\
1678 export declare namespace check {\n \
1679 /** Declares a check that does not run. */\n \
1680 function skip(name: string): void;\n \
1681 function todo(name: string): void;\n \
1682 /** How many variants there are. */\n \
1683 const COUNT: number;\n}\n"
1684 ),
1685 "{ts}"
1686 );
1687 assert!(
1688 !ts.contains("CheckVariants") && !ts.contains("checkModule"),
1689 "{ts}"
1690 );
1691 assert!(
1692 ts.contains("export declare const loose: looseModule;"),
1693 "{ts}"
1694 );
1695 assert_eq!(r.undocumented(), ["check.todo"]);
1697 let described = super::super::description::SetDescription::of(&r).unwrap();
1698 let exports: Vec<_> = described
1699 .exports
1700 .iter()
1701 .map(|e| (e.name.as_str(), e.kind))
1702 .collect();
1703 assert_eq!(
1704 exports,
1705 [
1706 ("check", super::super::description::ExportKind::Function),
1707 ("loose", super::super::description::ExportKind::Module)
1708 ]
1709 );
1710 }
1711
1712 mod clash {
1713 #[crate::ui::class]
1715 pub(super) struct Lonely;
1716
1717 #[crate::ui::class]
1718 impl Lonely {
1719 pub(super) fn new() -> Self {
1720 Lonely
1721 }
1722 }
1723 }
1724
1725 #[test]
1726 fn a_clash_through_a_signature_names_both_types() {
1727 let mut r = Registry::ui_set("test/maker");
1728 r.class::<clash::Lonely>();
1729 let failed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1731 r.module::<Maker>();
1732 }))
1733 .unwrap_err();
1734 let message = failed.downcast_ref::<String>().unwrap();
1735 assert!(
1736 message.contains("`nsh_core::ui::component::tests::clash::Lonely`")
1737 && message.contains("`nsh_core::ui::component::tests::Lonely`"),
1738 "{message}"
1739 );
1740 }
1741
1742 #[test]
1743 fn components_are_named_after_their_types() {
1744 let mut registry = Registry::ui_set("test/ui");
1745 registry.register::<Stepper>();
1746 let specs = registry.specs();
1747 assert_eq!(specs[0].name, "nsh_core::ui::component::tests::Stepper");
1748 assert_eq!(specs[0].export, "Stepper");
1749 assert_eq!(export_name("app::picker::Picker<app::Fruit>"), "Picker");
1750 assert_eq!(export_name("Bare"), "Bare");
1751 }
1752
1753 mod other {
1754 use crate::ui::prelude::*;
1755
1756 #[derive(Default)]
1758 pub(super) struct Stepper;
1759
1760 impl Component for Stepper {
1761 type Props = ();
1762 type Event = NoEvent;
1763
1764 fn view(_: (), _: crate::ui::Scope<NoEvent>) -> impl IntoElement {
1765 view()
1766 }
1767 }
1768 }
1769
1770 #[test]
1771 #[should_panic(
1772 expected = "components `nsh_core::ui::component::tests::Stepper` and `nsh_core::ui::component::tests::other::Stepper` are both exported as `Stepper` in `test/ui`"
1773 )]
1774 fn two_components_of_one_set_cannot_share_an_export() {
1775 Registry::ui_set("test/ui")
1776 .register::<Stepper>()
1777 .register::<other::Stepper>();
1778 }
1779
1780 #[test]
1781 #[should_panic(
1782 expected = "component `nsh_core::ui::component::tests::Stepper` is registered twice"
1783 )]
1784 fn a_component_is_registered_once() {
1785 Registry::new().register::<Stepper>().register::<Stepper>();
1786 }
1787
1788 #[test]
1789 fn sets_may_share_exports_but_not_components() {
1790 let mut a = Registry::ui_set("test/a");
1791 a.register::<Stepper>();
1792 let mut b = Registry::ui_set("test/b");
1793 b.register::<other::Stepper>();
1794 let merged = Registry::merged(&[a.clone(), b]);
1795 assert_eq!(merged.specs().len(), 2);
1796 let twice = std::panic::catch_unwind(|| Registry::merged(&[a.clone(), a]));
1797 let message = *twice.unwrap_err().downcast::<String>().unwrap();
1798 assert_eq!(
1799 message,
1800 "component `nsh_core::ui::component::tests::Stepper` is registered twice, by two UI sets"
1801 );
1802 }
1803}