1use std::{
6 any::{Any, TypeId},
7 fmt,
8 sync::Arc,
9};
10
11use rustc_hash::FxHashMap;
12
13use super::{
14 Children, Context, Environment, IntoElement, PropError, Slot, TsType, TsTypes,
15 element::{ComponentElement, ElNode, ErasedCx, RenderCx, RenderReads, RenderScope},
16 module::{Function, FunctionSpec, Module, ModuleSpec},
17};
18use crate::JsonValue;
19
20pub trait Component: Default + 'static {
44 type Props: Props;
46
47 type Event: Event;
49
50 const METHODS: &'static [Method<Self>] = &[];
53
54 fn setup(&mut self, props: &Self::Props, cx: &mut Context<'_, Self>) {
57 let _ = (props, cx);
58 }
59
60 fn props_changed(&mut self, old: &Self::Props, new: &Self::Props, cx: &mut Context<'_, Self>) {
63 let _ = (old, new, cx);
64 }
65
66 fn environment_changed(
70 &mut self,
71 props: &Self::Props,
72 old: &Environment,
73 new: &Environment,
74 cx: &mut Context<'_, Self>,
75 ) {
76 let _ = (props, old, new, cx);
77 }
78
79 fn cleanup(&mut self, props: &Self::Props, cx: &mut Context<'_, Self>) {
83 let _ = (props, cx);
84 }
85
86 fn render(&self, props: &Self::Props, cx: &mut RenderCx<'_, Self>) -> impl IntoElement;
90
91 fn catch_error(&mut self, error: &ComponentError, cx: &mut Context<'_, Self>) -> bool {
98 let _ = (error, cx);
99 false
100 }
101
102 fn element(props: Self::Props) -> ComponentElement<Self> {
104 ComponentElement::new(props)
105 }
106}
107
108#[derive(Debug, Clone, PartialEq, Eq)]
110pub struct ComponentError {
111 pub component: &'static str,
113 pub message: String,
115}
116
117impl fmt::Display for ComponentError {
118 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119 write!(f, "{} failed: {}", self.component, self.message)
120 }
121}
122
123pub(crate) fn caught<R>(f: impl FnOnce() -> R) -> Result<R, String> {
125 std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).map_err(|payload| {
126 match payload.downcast::<String>() {
127 Ok(s) => *s,
128 Err(payload) => match payload.downcast::<&'static str>() {
129 Ok(s) => (*s).to_owned(),
130 Err(_) => "a panic".to_owned(),
131 },
132 }
133 })
134}
135
136pub struct Method<C: Component> {
138 pub name: &'static str,
140 pub doc: &'static str,
142 pub params: &'static [Param],
144 pub returns: Option<TsType>,
147 #[allow(clippy::type_complexity)]
149 pub call: fn(&mut C, Vec<JsonValue>, &mut Context<'_, C>) -> Result<JsonValue, PropError>,
150}
151
152pub type Param = (&'static str, TsType);
154
155#[derive(Debug, Clone)]
157pub struct MethodSpec {
158 pub name: &'static str,
160 pub doc: &'static str,
162 pub params: Vec<(&'static str, String)>,
164 pub returns: Option<String>,
166}
167
168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
170pub enum PropKind {
171 Value,
173 Slot,
175 Children,
177 Items,
180}
181
182#[derive(Debug, Clone)]
184pub struct PropSpec {
185 pub name: &'static str,
187 pub ts: String,
189 pub optional: bool,
191 pub doc: &'static str,
193 pub kind: PropKind,
195}
196
197#[derive(Debug, Clone)]
199pub struct EventSpec {
200 pub name: &'static str,
202 pub data: String,
204 pub doc: &'static str,
206}
207
208pub trait Props: Clone + PartialEq + 'static {
210 #[doc(hidden)]
212 const ITEMS: Option<&'static str> = None;
213
214 #[doc(hidden)]
217 const LAZY_CHILDREN: bool = false;
218
219 fn doc() -> &'static str;
221
222 fn spec(types: &mut TsTypes) -> Vec<PropSpec>;
224
225 fn initial() -> Self;
227
228 fn set(&mut self, name: &str, value: Option<JsonValue>) -> Result<bool, PropError>;
231
232 fn set_slot(&mut self, name: &str, slot: Option<Slot>) -> bool;
234
235 fn set_children(&mut self, children: Children) -> bool;
237}
238
239impl Props for () {
241 fn doc() -> &'static str {
242 ""
243 }
244
245 fn spec(_: &mut TsTypes) -> Vec<PropSpec> {
246 Vec::new()
247 }
248
249 fn initial() -> Self {}
250
251 fn set(&mut self, name: &str, _: Option<JsonValue>) -> Result<bool, PropError> {
252 Err(PropError(format!("unknown prop `{name}`")))
253 }
254
255 fn set_slot(&mut self, _: &str, _: Option<Slot>) -> bool {
256 false
257 }
258
259 fn set_children(&mut self, _: Children) -> bool {
260 false
261 }
262}
263
264pub trait Event: 'static {
266 fn spec(types: &mut TsTypes) -> Vec<EventSpec>;
268
269 fn name(&self) -> &'static str;
271
272 fn data(&self) -> JsonValue;
274}
275
276#[derive(Debug, Clone, Copy, PartialEq, Eq)]
278pub enum NoEvent {}
279
280impl Event for NoEvent {
281 fn spec(_types: &mut TsTypes) -> Vec<EventSpec> {
282 Vec::new()
283 }
284
285 fn name(&self) -> &'static str {
286 match *self {}
287 }
288
289 fn data(&self) -> JsonValue {
290 match *self {}
291 }
292}
293
294#[derive(Debug, Clone)]
297pub struct ComponentSpec {
298 pub name: &'static str,
301 pub export: String,
303 pub doc: &'static str,
305 pub props: Vec<PropSpec>,
307 pub events: Vec<EventSpec>,
309 pub methods: Vec<MethodSpec>,
311 pub types: TsTypes,
313 pub lazy_children: bool,
317}
318
319impl ComponentSpec {
320 pub(crate) fn of<C: Component>() -> Self {
321 let mut types = TsTypes::default();
322 let props = C::Props::spec(&mut types);
323 let events = C::Event::spec(&mut types);
324 let methods = C::METHODS
325 .iter()
326 .map(|m| MethodSpec {
327 name: m.name,
328 doc: m.doc,
329 params: m
330 .params
331 .iter()
332 .map(|(n, ts)| (*n, ts(&mut types)))
333 .collect(),
334 returns: m.returns.map(|ts| ts(&mut types)),
335 })
336 .collect();
337 let name = name_of::<C>();
338 Self {
339 name,
340 export: export_name(name).to_owned(),
341 doc: C::Props::doc(),
342 props,
343 events,
344 methods,
345 types,
346 lazy_children: C::Props::LAZY_CHILDREN,
347 }
348 }
349
350 pub fn slots(&self) -> impl Iterator<Item = &'static str> + '_ {
352 self.props
353 .iter()
354 .filter(|p| p.kind == PropKind::Slot)
355 .map(|p| p.name)
356 }
357
358 pub fn takes_children(&self) -> bool {
360 self.props.iter().any(|p| p.kind == PropKind::Children)
361 }
362
363 pub fn items(&self) -> Option<&'static str> {
365 self.props
366 .iter()
367 .find(|p| p.kind == PropKind::Items)
368 .map(|p| p.name)
369 }
370
371 pub(crate) fn holder(&self, name: &str) -> Option<&'static str> {
373 self.props
374 .iter()
375 .find(|p| matches!(p.kind, PropKind::Slot | PropKind::Items) && p.name == name)
376 .map(|p| p.name)
377 }
378}
379
380pub(crate) fn name_of<C: Component>() -> &'static str {
384 std::any::type_name::<C>()
385}
386
387fn export_name(type_name: &str) -> &str {
391 let path = type_name.split('<').next().unwrap_or(type_name);
392 path.rsplit("::").next().unwrap_or(path)
393}
394
395pub(crate) trait AnyInstance {
397 fn set_prop(&mut self, name: &str, value: Option<JsonValue>) -> Result<bool, PropError>;
398 fn set_props(&mut self, props: &dyn Any) -> bool;
401 fn set_slot(&mut self, name: &'static str, filled: bool) -> bool;
402 fn set_children(&mut self, present: bool) -> bool;
403 fn update(&mut self, cx: &mut ErasedCx);
405 fn cleanup(&mut self, cx: &mut ErasedCx);
407 fn environment_changed(&mut self, old: &Environment, new: &Environment, cx: &mut ErasedCx);
409 fn render(&mut self, scope: &RenderScope<'_>) -> (ElNode, RenderReads);
411 fn catch_error(&mut self, error: &ComponentError, cx: &mut ErasedCx) -> bool;
413 fn name(&self) -> &'static str;
415 fn parts(&mut self) -> (&mut dyn Any, &dyn Any);
417 fn call(
419 &mut self,
420 name: &str,
421 args: Vec<JsonValue>,
422 cx: &mut ErasedCx,
423 ) -> Option<Result<JsonValue, PropError>>;
424}
425
426struct Instance<C: Component> {
427 state: C,
428 props: C::Props,
429 rendered: Option<C::Props>,
431 set_up: bool,
432}
433
434impl<C: Component> AnyInstance for Instance<C> {
435 fn set_prop(&mut self, name: &str, value: Option<JsonValue>) -> Result<bool, PropError> {
436 self.props.set(name, value)
437 }
438
439 fn set_props(&mut self, props: &dyn Any) -> bool {
440 match props.downcast_ref::<C::Props>() {
441 Some(p) if *p != self.props => {
442 self.props = p.clone();
443 true
444 }
445 _ => false,
446 }
447 }
448
449 fn set_slot(&mut self, name: &'static str, filled: bool) -> bool {
450 self.props.set_slot(name, filled.then(|| Slot::new(name)))
451 }
452
453 fn set_children(&mut self, present: bool) -> bool {
454 self.props.set_children(Children::new(present))
455 }
456
457 fn update(&mut self, cx: &mut ErasedCx) {
458 if !self.set_up {
459 self.set_up = true;
460 self.state
461 .setup(&self.props, &mut Context::new(cx, &self.props));
462 } else if let Some(old) = &self.rendered
463 && *old != self.props
464 {
465 self.state
466 .props_changed(old, &self.props, &mut Context::new(cx, &self.props));
467 }
468 }
469
470 fn environment_changed(&mut self, old: &Environment, new: &Environment, cx: &mut ErasedCx) {
471 if self.set_up {
472 self.state.environment_changed(
473 &self.props,
474 old,
475 new,
476 &mut Context::new(cx, &self.props),
477 );
478 }
479 }
480
481 fn cleanup(&mut self, cx: &mut ErasedCx) {
482 if self.set_up {
483 self.state
484 .cleanup(&self.props, &mut Context::new(cx, &self.props));
485 }
486 }
487
488 fn render(&mut self, scope: &RenderScope<'_>) -> (ElNode, RenderReads) {
489 let mut cx = RenderCx::new(scope);
490 let node = self.state.render(&self.props, &mut cx).into_element().0;
491 match &mut self.rendered {
492 Some(old) if *old == self.props => {}
493 rendered => *rendered = Some(self.props.clone()),
494 }
495 (node, cx.reads.into_inner())
496 }
497
498 fn parts(&mut self) -> (&mut dyn Any, &dyn Any) {
499 (&mut self.state, &self.props)
500 }
501
502 fn catch_error(&mut self, error: &ComponentError, cx: &mut ErasedCx) -> bool {
503 self.state
504 .catch_error(error, &mut Context::new(cx, &self.props))
505 }
506
507 fn name(&self) -> &'static str {
508 name_of::<C>()
509 }
510
511 fn call(
512 &mut self,
513 name: &str,
514 args: Vec<JsonValue>,
515 cx: &mut ErasedCx,
516 ) -> Option<Result<JsonValue, PropError>> {
517 let method = C::METHODS.iter().find(|m| m.name == name)?;
518 Some((method.call)(
519 &mut self.state,
520 args,
521 &mut Context::new(cx, &self.props),
522 ))
523 }
524}
525
526#[derive(Clone)]
530pub struct Root {
531 make: Arc<dyn Fn() -> super::AnyElement + Send + Sync>,
532 theme: Option<Arc<super::Theme>>,
533 fonts: Vec<Arc<[u8]>>,
534}
535
536impl Root {
537 pub fn new<C: Component>(props: impl Fn() -> C::Props + Send + Sync + 'static) -> Self {
539 Self {
540 make: Arc::new(move || super::IntoElement::into_element(C::element(props()))),
541 theme: None,
542 fonts: Vec::new(),
543 }
544 }
545
546 pub fn theme(mut self, theme: super::Theme) -> Self {
548 self.theme = Some(Arc::new(theme));
549 self
550 }
551
552 pub fn font(mut self, data: impl Into<Arc<[u8]>>) -> Self {
555 self.fonts.push(data.into());
556 self
557 }
558
559 pub fn theme_ref(&self) -> Option<&super::Theme> {
561 self.theme.as_deref()
562 }
563
564 pub fn fonts(&self) -> &[Arc<[u8]>] {
566 &self.fonts
567 }
568
569 pub fn of<C: Component>() -> Self
571 where
572 C::Props: Default,
573 {
574 Self::new::<C>(C::Props::default)
575 }
576
577 pub(crate) fn element(&self) -> super::AnyElement {
579 (self.make)()
580 }
581}
582
583impl fmt::Debug for Root {
584 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
585 f.write_str("Root")
586 }
587}
588
589pub(crate) fn make_instance<C: Component>() -> Box<dyn AnyInstance> {
591 Box::new(Instance::<C> {
592 state: C::default(),
593 props: C::Props::initial(),
594 rendered: None,
595 set_up: false,
596 })
597}
598
599#[derive(Clone)]
600struct ComponentType {
601 spec: Arc<ComponentSpec>,
602 make: fn() -> Box<dyn AnyInstance>,
603 id: TypeId,
605}
606
607#[derive(Clone)]
608struct ModuleType {
609 spec: Arc<ModuleSpec>,
610 functions: &'static [Function],
611 type_name: &'static str,
613}
614
615#[derive(Clone, Default)]
618pub struct Registry {
619 types: Arc<FxHashMap<&'static str, ComponentType>>,
620 modules: Arc<FxHashMap<&'static str, ModuleType>>,
621 reexports: Arc<(Vec<&'static str>, Vec<&'static str>)>,
623 native_values: Arc<Vec<&'static str>>,
626 namespace: Option<&'static str>,
629 ui_set: Option<&'static str>,
631 assets: Arc<Vec<&'static [super::AssetFile]>>,
633}
634
635impl fmt::Debug for Registry {
636 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
637 f.debug_set().entries(self.types.keys()).finish()
638 }
639}
640
641impl Registry {
642 pub fn new() -> Self {
644 Self::default()
645 }
646
647 #[track_caller]
656 pub fn register<C: Component>(&mut self) -> &mut Self {
657 let spec = ComponentSpec::of::<C>();
658 let types = Arc::make_mut(&mut self.types);
659 if let Some(old) = types.get(spec.name) {
660 let set = self.ui_set.or(self.namespace);
661 panic!("{}", same_name(spec.name, old.id, TypeId::of::<C>(), set));
662 }
663 if let Some(other) = types.values().find(|t| t.spec.export == spec.export) {
664 panic!(
665 "components `{}` and `{}` are both exported as `{}`{}: rename one",
666 other.spec.name,
667 spec.name,
668 spec.export,
669 of_set(self.ui_set.or(self.namespace)),
670 );
671 }
672 types.insert(
673 spec.name,
674 ComponentType {
675 spec: Arc::new(spec),
676 make: make_instance::<C>,
677 id: TypeId::of::<C>(),
678 },
679 );
680 self
681 }
682
683 #[track_caller]
691 pub fn module<M: Module>(&mut self) -> &mut Self {
692 let type_name = std::any::type_name::<M>();
693 let modules = Arc::make_mut(&mut self.modules);
694 if let Some(old) = modules.get(M::NAME) {
695 panic!(
696 "{}",
697 same_module(
698 M::NAME,
699 old.type_name,
700 type_name,
701 self.ui_set.or(self.namespace)
702 )
703 );
704 }
705 modules.insert(
706 M::NAME,
707 ModuleType {
708 spec: Arc::new(ModuleSpec::of::<M>()),
709 functions: M::FUNCTIONS,
710 type_name,
711 },
712 );
713 self
714 }
715
716 pub fn reexport(&mut self, values: &[&'static str], types: &[&'static str]) -> &mut Self {
719 let r = Arc::make_mut(&mut self.reexports);
720 r.0.extend_from_slice(values);
721 r.1.extend_from_slice(types);
722 self
723 }
724
725 #[track_caller]
735 pub fn merged(sets: &[Registry]) -> Self {
736 let mut out = Self::default();
737 for set in sets {
738 let types = Arc::make_mut(&mut out.types);
739 for (name, ty) in set.types.iter() {
740 if let Some(old) = types.insert(name, ty.clone()) {
741 panic!("{}, by two UI sets", same_name(name, old.id, ty.id, None));
742 }
743 }
744 let modules = Arc::make_mut(&mut out.modules);
745 for (name, m) in set.modules.iter() {
746 if let Some(old) = modules.insert(name, m.clone()) {
747 panic!(
748 "{}, by two UI sets",
749 same_module(name, old.type_name, m.type_name, None)
750 );
751 }
752 }
753 }
754 out
755 }
756
757 pub fn ui_set(specifier: &'static str) -> Self {
761 Self {
762 ui_set: Some(specifier),
763 ..Self::default()
764 }
765 }
766
767 pub fn specifier(&self) -> Option<&'static str> {
770 self.ui_set.or(self.namespace)
771 }
772
773 pub fn reexports(&self) -> (&[&'static str], &[&'static str]) {
776 (&self.reexports.0, &self.reexports.1)
777 }
778
779 pub fn native_values(&mut self, values: &[&'static str]) -> &mut Self {
782 Arc::make_mut(&mut self.native_values).extend_from_slice(values);
783 self
784 }
785
786 pub fn assets(&mut self, files: &'static [super::AssetFile]) -> &mut Self {
791 Arc::make_mut(&mut self.assets).push(files);
792 self
793 }
794
795 pub fn asset_files(&self) -> impl Iterator<Item = &'static super::AssetFile> + '_ {
797 self.assets.iter().flat_map(|files| files.iter())
798 }
799
800 pub fn native_value_names(&self) -> &[&'static str] {
802 &self.native_values
803 }
804
805 pub(crate) fn runtime(namespace: &'static str) -> Self {
807 Self {
808 namespace: Some(namespace),
809 ..Self::default()
810 }
811 }
812
813 pub fn namespace(&self) -> Option<&'static str> {
816 self.namespace
817 }
818
819 pub(crate) fn function(&self, name: &str) -> Option<&'static Function> {
822 let name = match self.namespace {
823 Some(namespace) => name.strip_prefix(namespace)?.strip_prefix(':')?,
824 None => name,
825 };
826 let (module, function) = name.split_once('.')?;
827 self.modules
828 .get(module)?
829 .functions
830 .iter()
831 .find(|f| f.name == function)
832 }
833
834 pub fn module_specs(&self) -> Vec<Arc<ModuleSpec>> {
836 let mut specs: Vec<_> = self.modules.values().map(|m| m.spec.clone()).collect();
837 specs.sort_by_key(|s| s.name);
838 specs
839 }
840
841 pub fn specs(&self) -> Vec<Arc<ComponentSpec>> {
843 let mut specs: Vec<_> = self.types.values().map(|t| t.spec.clone()).collect();
844 specs.sort_by(|a, b| a.export.cmp(&b.export).then(a.name.cmp(b.name)));
845 specs
846 }
847
848 pub(crate) fn make(&self, name: &str) -> Option<(Arc<ComponentSpec>, Box<dyn AnyInstance>)> {
850 self.types.get(name).map(|t| (t.spec.clone(), (t.make)()))
851 }
852}
853
854fn same_name(name: &str, old: TypeId, new: TypeId, set: Option<&str>) -> String {
856 if old == new {
857 format!("component `{name}` is registered twice{}", of_set(set))
858 } else {
859 format!(
860 "two different types named `{name}` are registered{} (two versions of one crate?)",
861 of_set(set)
862 )
863 }
864}
865
866fn same_module(name: &str, old: &str, new: &str, set: Option<&str>) -> String {
868 if old == new {
869 format!("module `{old}` is registered twice{}", of_set(set))
870 } else {
871 format!(
872 "modules `{old}` and `{new}` are both named `{name}`{}: rename one",
873 of_set(set)
874 )
875 }
876}
877
878fn of_set(set: Option<&str>) -> String {
880 set.map(|s| format!(" in `{s}`")).unwrap_or_default()
881}
882
883pub fn declarations(registry: &Registry, omit: &[&str]) -> String {
891 let specs = registry.specs();
892 let modules = registry.module_specs();
893 use std::fmt::Write as _;
894 let mut out = String::new();
895 let doc = |out: &mut String, indent: &str, doc: &str| {
896 if !doc.is_empty() {
897 let _ = writeln!(out, "{indent}/** {doc} */");
898 }
899 };
900 let mut types = TsTypes::default();
902 for spec in &specs {
903 types.merge(&spec.types);
904 }
905 for m in &modules {
906 types.merge(&m.types);
907 }
908 for declaration in types.declarations() {
909 let _ = write!(out, "{declaration}\n\n");
910 }
911 let module_of = |name: &str| modules.iter().find(|m| m.name == name);
912 let signature = |f: &FunctionSpec| {
913 let params = f
914 .params
915 .iter()
916 .map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
917 .collect::<Vec<_>>()
918 .join(", ");
919 let returns = match &f.returns {
920 Some(ts) => format!("Promise<{ts}>"),
921 None => "void".to_owned(),
922 };
923 (params, returns)
924 };
925 let module_object = |out: &mut String, m: &ModuleSpec| {
927 out.push_str("{\n");
928 for f in &m.functions {
929 doc(out, " ", f.doc);
930 let (params, returns) = signature(f);
931 let _ = writeln!(out, " {}({params}): {returns};", f.name);
932 }
933 out.push('}');
934 };
935 for spec in &specs {
936 let (generic, extends) = match spec.items() {
938 Some(_) => ("<T>", ", ListItemsProps<T>"),
939 None => ("", ""),
940 };
941 let host = if spec.methods.is_empty() {
943 "ComponentHostProps"
944 } else {
945 let _ = write!(
946 out,
947 "/** The ref of `{0}`: its methods. */\nexport interface {0}Ref {{\n /** The component's host node. */\n readonly node: YNode;\n",
948 spec.export
949 );
950 for m in &spec.methods {
951 doc(&mut out, " ", m.doc);
952 let params = m
953 .params
954 .iter()
955 .map(|(n, ts)| format!("{n}: {ts}"))
956 .collect::<Vec<_>>()
957 .join(", ");
958 let returns = match &m.returns {
959 Some(ts) => format!("Promise<{ts}>"),
960 None => "void".to_owned(),
961 };
962 let _ = writeln!(out, " {}({params}): {returns};", m.name);
963 }
964 out.push_str("}\n\n");
965 "Omit<ComponentHostProps, \"ref\">"
966 };
967 let _ = writeln!(
968 out,
969 "export interface {}Props{generic} extends {host}{extends} {{",
970 spec.export
971 );
972 if !spec.methods.is_empty() {
973 let _ = writeln!(
974 out,
975 " ref?: {0}Ref | ((ref: {0}Ref) => void);",
976 spec.export
977 );
978 }
979 for p in spec.props.iter().filter(|p| p.kind != PropKind::Items) {
980 doc(&mut out, " ", p.doc);
981 let optional = if p.optional { "?" } else { "" };
982 let _ = writeln!(out, " {}{optional}: {};", p.name, p.ts);
983 }
984 for e in &spec.events {
985 doc(&mut out, " ", e.doc);
986 let handler = handler_name(e.name);
987 let arg = if e.data == "void" {
988 String::new()
989 } else {
990 format!("data: {}", e.data)
991 };
992 let _ = writeln!(out, " {handler}?: ({arg}) => void;");
993 }
994 out.push_str("}\n\n");
995 if omit.contains(&spec.export.as_str()) {
996 continue;
997 }
998 doc(&mut out, "", spec.doc);
999 let mut with = String::new();
1001 if let Some(m) = module_of(&spec.export) {
1002 with.push_str(" & ");
1003 module_object(&mut with, m);
1004 }
1005 let _ = write!(
1006 out,
1007 "export declare const {}: ({generic}(props: {}Props{generic}) => JSX.Element){with};\n\n",
1008 spec.export, spec.export,
1009 );
1010 }
1011 for m in &modules {
1012 if specs.iter().any(|s| s.export == m.name) {
1013 continue;
1014 }
1015 if m.flat {
1016 for f in m.functions.iter().filter(|f| !omit.contains(&f.name)) {
1017 doc(&mut out, "", f.doc);
1018 let (params, returns) = signature(f);
1019 let _ = write!(
1020 out,
1021 "export declare function {}({params}): {returns};\n\n",
1022 f.name
1023 );
1024 }
1025 continue;
1026 }
1027 doc(&mut out, "", m.doc);
1028 let _ = write!(out, "export interface {}Module ", m.name);
1029 module_object(&mut out, m);
1030 out.push_str("\n\n");
1031 if !omit.contains(&m.name) {
1032 doc(&mut out, "", m.doc);
1033 let _ = write!(out, "export declare const {0}: {0}Module;\n\n", m.name);
1034 }
1035 }
1036 out
1037}
1038
1039fn handler_name(event: &str) -> String {
1041 let mut chars = event.chars();
1042 match chars.next() {
1043 Some(first) => format!("on{}{}", first.to_ascii_uppercase(), chars.as_str()),
1044 None => "on".to_owned(),
1045 }
1046}
1047
1048#[cfg(test)]
1049mod tests {
1050 use super::*;
1051 use crate::ui::prelude::*;
1052
1053 #[derive(Default)]
1054 struct Stepper;
1055
1056 #[derive(Clone, PartialEq, Props)]
1058 struct StepperProps {
1059 value: f64,
1061 #[prop(default)]
1062 size: StepperSize,
1063 max_value: Option<f64>,
1064 label: Option<Slot>,
1066 children: Children,
1067 }
1068
1069 #[derive(Clone, Copy, PartialEq, Default, PropEnum)]
1070 enum StepperSize {
1071 #[default]
1072 Regular,
1073 ExtraLarge,
1074 }
1075
1076 #[derive(Event)]
1077 enum StepperEvent {
1078 Change {
1080 new_value: f64,
1081 },
1082 Limit(u32),
1083 Reset,
1084 }
1085
1086 #[methods]
1087 impl Stepper {
1088 fn jump_to(&mut self, value: f64, cx: &mut Context<'_, Self>) {
1090 let _ = (value, cx);
1091 }
1092
1093 fn value(&self) -> f64 {
1094 0.0
1095 }
1096 }
1097
1098 impl Component for Stepper {
1099 type Props = StepperProps;
1100 type Event = StepperEvent;
1101 const METHODS: &'static [Method<Self>] = Self::JS_METHODS;
1102
1103 fn render(&self, _props: &StepperProps, _cx: &mut RenderCx<'_, Self>) -> impl IntoElement {
1104 view()
1105 }
1106 }
1107
1108 #[test]
1109 fn the_declarations_come_from_the_types() {
1110 let mut registry = Registry::new();
1111 registry.register::<Stepper>();
1112 let ts = declarations(®istry, &[]);
1113 for line in [
1114 " /** The value. */\n value: number;",
1115 "export type StepperSize = \"regular\" | \"extraLarge\";",
1116 " size?: StepperSize;",
1117 " maxValue?: number | null;",
1118 " /** Above the control. */\n label?: JSX.Element;",
1119 " children?: JSX.Element;",
1120 " /** The value changed. */\n onChange?: (data: { newValue: number }) => void;",
1121 " onLimit?: (data: number) => void;",
1122 " onReset?: () => void;",
1123 "/** Picks a number. */",
1124 "export interface StepperRef {",
1125 " /** Jumps to `value`. */\n jumpTo(value: number): void;",
1126 " value(): Promise<number>;",
1127 "export interface StepperProps extends Omit<ComponentHostProps, \"ref\"> {\n ref?: StepperRef | ((ref: StepperRef) => void);",
1128 "export declare const Stepper: ((props: StepperProps) => JSX.Element);",
1129 ] {
1130 assert!(ts.contains(line), "missing {line:?} in\n{ts}");
1131 }
1132 let mut props = StepperProps::initial();
1133 assert!(
1134 props
1135 .set("size", Some(serde_json::json!("extraLarge")))
1136 .unwrap()
1137 );
1138 assert!(props.size == StepperSize::ExtraLarge);
1139 assert!(props.set("size", Some(serde_json::json!("huge"))).is_err());
1140 assert!(props.set("size", None).unwrap());
1141 assert!(props.size == StepperSize::Regular);
1142 assert_eq!(
1143 StepperEvent::Change { new_value: 2.5 }.data(),
1144 serde_json::json!({ "newValue": 2.5 })
1145 );
1146 assert_eq!(StepperEvent::Limit(3).data(), serde_json::json!(3));
1147 assert_eq!(StepperEvent::Reset.name(), "reset");
1148 }
1149
1150 #[test]
1151 fn components_are_named_after_their_types() {
1152 let mut registry = Registry::ui_set("test/ui");
1153 registry.register::<Stepper>();
1154 let specs = registry.specs();
1155 assert_eq!(specs[0].name, "nsh_core::ui::component::tests::Stepper");
1156 assert_eq!(specs[0].export, "Stepper");
1157 assert_eq!(export_name("app::picker::Picker<app::Fruit>"), "Picker");
1158 assert_eq!(export_name("Bare"), "Bare");
1159 }
1160
1161 mod other {
1162 use crate::ui::prelude::*;
1163
1164 #[derive(Default)]
1166 pub(super) struct Stepper;
1167
1168 impl Component for Stepper {
1169 type Props = ();
1170 type Event = NoEvent;
1171
1172 fn render(&self, _: &(), _: &mut RenderCx<'_, Self>) -> impl IntoElement {
1173 view()
1174 }
1175 }
1176 }
1177
1178 #[test]
1179 #[should_panic(
1180 expected = "components `nsh_core::ui::component::tests::Stepper` and `nsh_core::ui::component::tests::other::Stepper` are both exported as `Stepper` in `test/ui`"
1181 )]
1182 fn two_components_of_one_set_cannot_share_an_export() {
1183 Registry::ui_set("test/ui")
1184 .register::<Stepper>()
1185 .register::<other::Stepper>();
1186 }
1187
1188 #[test]
1189 #[should_panic(
1190 expected = "component `nsh_core::ui::component::tests::Stepper` is registered twice"
1191 )]
1192 fn a_component_is_registered_once() {
1193 Registry::new().register::<Stepper>().register::<Stepper>();
1194 }
1195
1196 #[test]
1197 fn sets_may_share_exports_but_not_components() {
1198 let mut a = Registry::ui_set("test/a");
1199 a.register::<Stepper>();
1200 let mut b = Registry::ui_set("test/b");
1201 b.register::<other::Stepper>();
1202 let merged = Registry::merged(&[a.clone(), b]);
1203 assert_eq!(merged.specs().len(), 2);
1204 let twice = std::panic::catch_unwind(|| Registry::merged(&[a.clone(), a]));
1205 let message = *twice.unwrap_err().downcast::<String>().unwrap();
1206 assert_eq!(
1207 message,
1208 "component `nsh_core::ui::component::tests::Stepper` is registered twice, by two UI sets"
1209 );
1210 }
1211}