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 element::{ComponentElement, ElNode},
16 module::{Function, FunctionSpec, Module, ModuleSpec},
17};
18use crate::JsonValue;
19
20pub trait Component: 'static {
42 type Props: Props;
44
45 type Event: Event;
47
48 const METHODS: Methods = Methods::NONE;
51
52 fn view(props: Self::Props, cx: super::Scope<Self::Event>) -> impl IntoElement;
56
57 fn element(props: Self::Props) -> ComponentElement<Self>
59 where
60 Self: Sized,
61 {
62 ComponentElement::new(props)
63 }
64}
65
66#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct ComponentError {
70 pub component: &'static str,
72 pub message: String,
74}
75
76impl fmt::Display for ComponentError {
77 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78 write!(f, "{} failed: {}", self.component, self.message)
79 }
80}
81
82pub(crate) fn caught<R>(f: impl FnOnce() -> R) -> Result<R, String> {
84 std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).map_err(panic_message)
85}
86
87pub(crate) fn panic_message(payload: Box<dyn std::any::Any + Send>) -> String {
89 match payload.downcast::<String>() {
90 Ok(s) => *s,
91 Err(payload) => match payload.downcast::<&'static str>() {
92 Ok(s) => (*s).to_owned(),
93 Err(_) => "a panic".to_owned(),
94 },
95 }
96}
97
98pub struct Method<A: 'static> {
101 pub name: &'static str,
103 pub doc: &'static str,
105 pub params: &'static [Param],
107 pub returns: Option<TsType>,
110 pub call: fn(&A, Vec<JsonValue>) -> Result<JsonValue, PropError>,
112}
113
114pub trait Api: Sized + 'static {
119 const METHODS: &'static [Method<Self>];
121}
122
123#[derive(Clone, Copy)]
126pub struct Methods {
127 specs: fn(&mut TsTypes) -> Vec<MethodSpec>,
128}
129
130impl Methods {
131 pub const NONE: Self = Self {
133 specs: |_| Vec::new(),
134 };
135
136 pub const fn of<A: Api>() -> Self {
138 Self {
139 specs: specs_of::<A>,
140 }
141 }
142}
143
144fn specs_of<A: Api>(types: &mut TsTypes) -> Vec<MethodSpec> {
145 A::METHODS
146 .iter()
147 .map(|m| MethodSpec {
148 name: m.name,
149 doc: m.doc,
150 params: m.params.iter().map(|(n, ts)| (*n, ts(types))).collect(),
151 returns: m.returns.map(|ts| ts(types)),
152 })
153 .collect()
154}
155
156pub type Param = (&'static str, TsType);
158
159#[derive(Debug, Clone)]
161pub struct MethodSpec {
162 pub name: &'static str,
164 pub doc: &'static str,
166 pub params: Vec<(&'static str, String)>,
168 pub returns: Option<String>,
170}
171
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
174pub enum PropKind {
175 Value,
177 Slot,
179 Children,
181 Items,
184}
185
186#[derive(Debug, Clone)]
188pub struct PropSpec {
189 pub name: &'static str,
191 pub ts: String,
193 pub optional: bool,
195 pub doc: &'static str,
197 pub kind: PropKind,
199}
200
201#[derive(Debug, Clone)]
203pub struct EventSpec {
204 pub name: &'static str,
206 pub data: String,
208 pub doc: &'static str,
210}
211
212pub trait Props: Clone + PartialEq + 'static {
214 #[doc(hidden)]
216 const ITEMS: Option<&'static str> = None;
217
218 #[doc(hidden)]
221 const LAZY_CHILDREN: bool = false;
222
223 fn doc() -> &'static str;
225
226 fn spec(types: &mut TsTypes) -> Vec<PropSpec>;
228
229 fn initial() -> Self;
231
232 fn set(&mut self, name: &str, value: Option<JsonValue>) -> Result<bool, PropError>;
235
236 fn set_slot(&mut self, name: &str, slot: Option<Slot>) -> bool;
238
239 fn set_children(&mut self, children: Children) -> bool;
241
242 #[doc(hidden)]
245 fn held(&self) -> Self {
246 self.clone()
247 }
248
249 #[doc(hidden)]
253 fn update_from(&mut self, new: &Self) -> bool {
254 if self == new {
255 return false;
256 }
257 *self = new.clone();
258 true
259 }
260}
261
262impl Props for () {
264 fn doc() -> &'static str {
265 ""
266 }
267
268 fn spec(_: &mut TsTypes) -> Vec<PropSpec> {
269 Vec::new()
270 }
271
272 fn initial() -> Self {}
273
274 fn set(&mut self, name: &str, _: Option<JsonValue>) -> Result<bool, PropError> {
275 Err(PropError(format!("unknown prop `{name}`")))
276 }
277
278 fn set_slot(&mut self, _: &str, _: Option<Slot>) -> bool {
279 false
280 }
281
282 fn set_children(&mut self, _: Children) -> bool {
283 false
284 }
285}
286
287pub trait Event: 'static {
289 fn spec(types: &mut TsTypes) -> Vec<EventSpec>;
291
292 fn name(&self) -> &'static str;
294
295 fn data(&self) -> JsonValue;
297}
298
299#[derive(Debug, Clone, Copy, PartialEq, Eq)]
301pub enum NoEvent {}
302
303impl Event for NoEvent {
304 fn spec(_types: &mut TsTypes) -> Vec<EventSpec> {
305 Vec::new()
306 }
307
308 fn name(&self) -> &'static str {
309 match *self {}
310 }
311
312 fn data(&self) -> JsonValue {
313 match *self {}
314 }
315}
316
317#[derive(Debug, Clone)]
320pub struct ComponentSpec {
321 pub name: &'static str,
324 pub export: String,
326 pub doc: &'static str,
328 pub props: Vec<PropSpec>,
330 pub events: Vec<EventSpec>,
332 pub methods: Vec<MethodSpec>,
334 pub types: TsTypes,
336 pub lazy_children: bool,
340}
341
342impl ComponentSpec {
343 pub(crate) fn of<C: Component>() -> Self {
344 let mut types = TsTypes::default();
345 let props = C::Props::spec(&mut types);
346 let events = C::Event::spec(&mut types);
347 let methods = (C::METHODS.specs)(&mut types);
348 let name = name_of::<C>();
349 Self {
350 name,
351 export: export_name(name).to_owned(),
352 doc: C::Props::doc(),
353 props,
354 events,
355 methods,
356 types,
357 lazy_children: C::Props::LAZY_CHILDREN,
358 }
359 }
360
361 pub fn slots(&self) -> impl Iterator<Item = &'static str> + '_ {
363 self.props
364 .iter()
365 .filter(|p| p.kind == PropKind::Slot)
366 .map(|p| p.name)
367 }
368
369 pub fn takes_children(&self) -> bool {
371 self.props.iter().any(|p| p.kind == PropKind::Children)
372 }
373
374 pub fn items(&self) -> Option<&'static str> {
376 self.props
377 .iter()
378 .find(|p| p.kind == PropKind::Items)
379 .map(|p| p.name)
380 }
381
382 pub(crate) fn holder(&self, name: &str) -> Option<&'static str> {
384 self.props
385 .iter()
386 .find(|p| matches!(p.kind, PropKind::Slot | PropKind::Items) && p.name == name)
387 .map(|p| p.name)
388 }
389}
390
391pub(crate) fn name_of<C: Component>() -> &'static str {
395 std::any::type_name::<C>()
396}
397
398fn export_name(type_name: &str) -> &str {
402 let path = type_name.split('<').next().unwrap_or(type_name);
403 path.rsplit("::").next().unwrap_or(path)
404}
405
406pub(crate) trait AnyInstance {
408 fn set_prop(&mut self, name: &str, value: Option<JsonValue>) -> Result<bool, PropError>;
409 fn set_props(&mut self, props: &dyn Any);
411 fn set_slot(&mut self, name: &'static str, filled: bool);
412 fn set_children(&mut self, present: bool);
413 fn cleanup(&mut self);
415 fn view(&mut self) -> ElNode;
417 fn name(&self) -> &'static str;
419 fn call(&mut self, name: &str, args: Vec<JsonValue>) -> Option<Result<JsonValue, PropError>>;
421 fn owner(&self) -> Option<super::Owner>;
423 fn failure_owner(&self) -> super::Owner;
426 fn adopt(&mut self, parent: super::Owner);
430 fn place(&mut self, host: crate::NodeId, parent: super::Owner);
432}
433
434#[derive(Clone)]
438pub struct Root {
439 make: Arc<dyn Fn() -> super::AnyElement + Send + Sync>,
440 theme: Option<Arc<super::Theme>>,
441 fonts: Vec<Arc<[u8]>>,
442}
443
444impl Root {
445 pub fn new<C: Component>(props: impl Fn() -> C::Props + Send + Sync + 'static) -> Self {
447 Self {
448 make: Arc::new(move || super::IntoElement::into_element(C::element(props()))),
449 theme: None,
450 fonts: Vec::new(),
451 }
452 }
453
454 pub fn theme(mut self, theme: super::Theme) -> Self {
456 self.theme = Some(Arc::new(theme));
457 self
458 }
459
460 pub fn font(mut self, data: impl Into<Arc<[u8]>>) -> Self {
463 self.fonts.push(data.into());
464 self
465 }
466
467 pub fn theme_ref(&self) -> Option<&super::Theme> {
469 self.theme.as_deref()
470 }
471
472 pub fn fonts(&self) -> &[Arc<[u8]>] {
474 &self.fonts
475 }
476
477 pub fn of<C: Component>() -> Self
479 where
480 C::Props: Default,
481 {
482 Self::new::<C>(C::Props::default)
483 }
484
485 pub(crate) fn element(&self) -> super::AnyElement {
487 (self.make)()
488 }
489}
490
491impl fmt::Debug for Root {
492 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
493 f.write_str("Root")
494 }
495}
496
497pub(crate) fn make_instance<C: Component>() -> Box<dyn AnyInstance> {
499 Box::new(super::once::OnceInstance::<C>::new())
500}
501
502#[derive(Clone)]
503struct ComponentType {
504 spec: Arc<ComponentSpec>,
505 make: fn() -> Box<dyn AnyInstance>,
506 id: TypeId,
508}
509
510#[derive(Clone)]
511struct ModuleType {
512 spec: Arc<ModuleSpec>,
513 functions: &'static [Function],
514 type_name: &'static str,
516}
517
518#[derive(Clone, Default)]
521pub struct Registry {
522 types: Arc<FxHashMap<&'static str, ComponentType>>,
523 modules: Arc<FxHashMap<&'static str, ModuleType>>,
524 reexports: Arc<(Vec<&'static str>, Vec<&'static str>)>,
526 native_values: Arc<Vec<&'static str>>,
529 namespace: Option<&'static str>,
532 ui_set: Option<&'static str>,
534 assets: Arc<Vec<&'static [super::AssetFile]>>,
536}
537
538impl fmt::Debug for Registry {
539 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
540 f.debug_set().entries(self.types.keys()).finish()
541 }
542}
543
544impl Registry {
545 pub fn new() -> Self {
547 Self::default()
548 }
549
550 #[track_caller]
559 pub fn register<C: Component>(&mut self) -> &mut Self {
560 let spec = ComponentSpec::of::<C>();
561 let types = Arc::make_mut(&mut self.types);
562 if let Some(old) = types.get(spec.name) {
563 let set = self.ui_set.or(self.namespace);
564 panic!("{}", same_name(spec.name, old.id, TypeId::of::<C>(), set));
565 }
566 if let Some(other) = types.values().find(|t| t.spec.export == spec.export) {
567 panic!(
568 "components `{}` and `{}` are both exported as `{}`{}: rename one",
569 other.spec.name,
570 spec.name,
571 spec.export,
572 of_set(self.ui_set.or(self.namespace)),
573 );
574 }
575 types.insert(
576 spec.name,
577 ComponentType {
578 spec: Arc::new(spec),
579 make: make_instance::<C>,
580 id: TypeId::of::<C>(),
581 },
582 );
583 self
584 }
585
586 #[track_caller]
594 pub fn module<M: Module>(&mut self) -> &mut Self {
595 let type_name = std::any::type_name::<M>();
596 let modules = Arc::make_mut(&mut self.modules);
597 if let Some(old) = modules.get(M::NAME) {
598 panic!(
599 "{}",
600 same_module(
601 M::NAME,
602 old.type_name,
603 type_name,
604 self.ui_set.or(self.namespace)
605 )
606 );
607 }
608 modules.insert(
609 M::NAME,
610 ModuleType {
611 spec: Arc::new(ModuleSpec::of::<M>()),
612 functions: M::FUNCTIONS,
613 type_name,
614 },
615 );
616 self
617 }
618
619 pub fn reexport(&mut self, values: &[&'static str], types: &[&'static str]) -> &mut Self {
622 let r = Arc::make_mut(&mut self.reexports);
623 r.0.extend_from_slice(values);
624 r.1.extend_from_slice(types);
625 self
626 }
627
628 #[track_caller]
638 pub fn merged(sets: &[Registry]) -> Self {
639 let mut out = Self::default();
640 for set in sets {
641 let types = Arc::make_mut(&mut out.types);
642 for (name, ty) in set.types.iter() {
643 if let Some(old) = types.insert(name, ty.clone()) {
644 panic!("{}, by two UI sets", same_name(name, old.id, ty.id, None));
645 }
646 }
647 let modules = Arc::make_mut(&mut out.modules);
648 for (name, m) in set.modules.iter() {
649 if let Some(old) = modules.insert(name, m.clone()) {
650 panic!(
651 "{}, by two UI sets",
652 same_module(name, old.type_name, m.type_name, None)
653 );
654 }
655 }
656 }
657 out
658 }
659
660 pub fn ui_set(specifier: &'static str) -> Self {
664 Self {
665 ui_set: Some(specifier),
666 ..Self::default()
667 }
668 }
669
670 pub fn specifier(&self) -> Option<&'static str> {
673 self.ui_set.or(self.namespace)
674 }
675
676 pub fn reexports(&self) -> (&[&'static str], &[&'static str]) {
679 (&self.reexports.0, &self.reexports.1)
680 }
681
682 pub fn native_values(&mut self, values: &[&'static str]) -> &mut Self {
685 Arc::make_mut(&mut self.native_values).extend_from_slice(values);
686 self
687 }
688
689 pub fn assets(&mut self, files: &'static [super::AssetFile]) -> &mut Self {
694 Arc::make_mut(&mut self.assets).push(files);
695 self
696 }
697
698 pub fn asset_files(&self) -> impl Iterator<Item = &'static super::AssetFile> + '_ {
700 self.assets.iter().flat_map(|files| files.iter())
701 }
702
703 pub fn native_value_names(&self) -> &[&'static str] {
705 &self.native_values
706 }
707
708 pub(crate) fn runtime(namespace: &'static str) -> Self {
710 Self {
711 namespace: Some(namespace),
712 ..Self::default()
713 }
714 }
715
716 pub fn namespace(&self) -> Option<&'static str> {
719 self.namespace
720 }
721
722 pub(crate) fn function(&self, name: &str) -> Option<&'static Function> {
725 let name = match self.namespace {
726 Some(namespace) => name.strip_prefix(namespace)?.strip_prefix(':')?,
727 None => name,
728 };
729 let (module, function) = name.split_once('.')?;
730 self.modules
731 .get(module)?
732 .functions
733 .iter()
734 .find(|f| f.name == function)
735 }
736
737 pub fn module_specs(&self) -> Vec<Arc<ModuleSpec>> {
739 let mut specs: Vec<_> = self.modules.values().map(|m| m.spec.clone()).collect();
740 specs.sort_by_key(|s| s.name);
741 specs
742 }
743
744 pub fn specs(&self) -> Vec<Arc<ComponentSpec>> {
746 let mut specs: Vec<_> = self.types.values().map(|t| t.spec.clone()).collect();
747 specs.sort_by(|a, b| a.export.cmp(&b.export).then(a.name.cmp(b.name)));
748 specs
749 }
750
751 pub(crate) fn make(&self, name: &str) -> Option<(Arc<ComponentSpec>, Box<dyn AnyInstance>)> {
753 self.types.get(name).map(|t| (t.spec.clone(), (t.make)()))
754 }
755}
756
757fn same_name(name: &str, old: TypeId, new: TypeId, set: Option<&str>) -> String {
759 if old == new {
760 format!("component `{name}` is registered twice{}", of_set(set))
761 } else {
762 format!(
763 "two different types named `{name}` are registered{} (two versions of one crate?)",
764 of_set(set)
765 )
766 }
767}
768
769fn same_module(name: &str, old: &str, new: &str, set: Option<&str>) -> String {
771 if old == new {
772 format!("module `{old}` is registered twice{}", of_set(set))
773 } else {
774 format!(
775 "modules `{old}` and `{new}` are both named `{name}`{}: rename one",
776 of_set(set)
777 )
778 }
779}
780
781fn of_set(set: Option<&str>) -> String {
783 set.map(|s| format!(" in `{s}`")).unwrap_or_default()
784}
785
786pub fn declarations(registry: &Registry, omit: &[&str]) -> String {
794 let specs = registry.specs();
795 let modules = registry.module_specs();
796 use std::fmt::Write as _;
797 let mut out = String::new();
798 let doc = |out: &mut String, indent: &str, doc: &str| {
799 if !doc.is_empty() {
800 let _ = writeln!(out, "{indent}/** {doc} */");
801 }
802 };
803 let mut types = TsTypes::default();
805 for spec in &specs {
806 types.merge(&spec.types);
807 }
808 for m in &modules {
809 types.merge(&m.types);
810 }
811 for declaration in types.declarations() {
812 let _ = write!(out, "{declaration}\n\n");
813 }
814 let module_of = |name: &str| modules.iter().find(|m| m.name == name);
815 let signature = |f: &FunctionSpec| {
816 let params = f
817 .params
818 .iter()
819 .map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
820 .collect::<Vec<_>>()
821 .join(", ");
822 let returns = match &f.returns {
823 Some(ts) => format!("Promise<{ts}>"),
824 None => "void".to_owned(),
825 };
826 (params, returns)
827 };
828 let module_object = |out: &mut String, m: &ModuleSpec| {
830 out.push_str("{\n");
831 for f in &m.functions {
832 doc(out, " ", f.doc);
833 let (params, returns) = signature(f);
834 let _ = writeln!(out, " {}({params}): {returns};", f.name);
835 }
836 out.push('}');
837 };
838 for spec in &specs {
839 let (generic, extends) = match spec.items() {
841 Some(_) => ("<T>", ", ListItemsProps<T>"),
842 None => ("", ""),
843 };
844 let host = if spec.methods.is_empty() {
846 "ComponentHostProps"
847 } else {
848 let _ = write!(
849 out,
850 "/** The ref of `{0}`: its methods. */\nexport interface {0}Ref {{\n /** The component's host node. */\n readonly node: YNode;\n",
851 spec.export
852 );
853 for m in &spec.methods {
854 doc(&mut out, " ", m.doc);
855 let params = m
856 .params
857 .iter()
858 .map(|(n, ts)| format!("{n}: {ts}"))
859 .collect::<Vec<_>>()
860 .join(", ");
861 let returns = match &m.returns {
862 Some(ts) => format!("Promise<{ts}>"),
863 None => "void".to_owned(),
864 };
865 let _ = writeln!(out, " {}({params}): {returns};", m.name);
866 }
867 out.push_str("}\n\n");
868 "Omit<ComponentHostProps, \"ref\">"
869 };
870 let _ = writeln!(
871 out,
872 "export interface {}Props{generic} extends {host}{extends} {{",
873 spec.export
874 );
875 if !spec.methods.is_empty() {
876 let _ = writeln!(
877 out,
878 " ref?: {0}Ref | ((ref: {0}Ref) => void);",
879 spec.export
880 );
881 }
882 for p in spec.props.iter().filter(|p| p.kind != PropKind::Items) {
883 doc(&mut out, " ", p.doc);
884 let optional = if p.optional { "?" } else { "" };
885 let _ = writeln!(out, " {}{optional}: {};", p.name, p.ts);
886 }
887 for e in &spec.events {
888 doc(&mut out, " ", e.doc);
889 let handler = handler_name(e.name);
890 let arg = if e.data == "void" {
891 String::new()
892 } else {
893 format!("data: {}", e.data)
894 };
895 let _ = writeln!(out, " {handler}?: ({arg}) => void;");
896 }
897 out.push_str("}\n\n");
898 if omit.contains(&spec.export.as_str()) {
899 continue;
900 }
901 doc(&mut out, "", spec.doc);
902 let mut with = String::new();
904 if let Some(m) = module_of(&spec.export) {
905 with.push_str(" & ");
906 module_object(&mut with, m);
907 }
908 let _ = write!(
909 out,
910 "export declare const {}: ({generic}(props: {}Props{generic}) => JSX.Element){with};\n\n",
911 spec.export, spec.export,
912 );
913 }
914 for m in &modules {
915 if specs.iter().any(|s| s.export == m.name) {
916 continue;
917 }
918 if m.flat {
919 for f in m.functions.iter().filter(|f| !omit.contains(&f.name)) {
920 doc(&mut out, "", f.doc);
921 let (params, returns) = signature(f);
922 let _ = write!(
923 out,
924 "export declare function {}({params}): {returns};\n\n",
925 f.name
926 );
927 }
928 continue;
929 }
930 doc(&mut out, "", m.doc);
931 let _ = write!(out, "export interface {}Module ", m.name);
932 module_object(&mut out, m);
933 out.push_str("\n\n");
934 if !omit.contains(&m.name) {
935 doc(&mut out, "", m.doc);
936 let _ = write!(out, "export declare const {0}: {0}Module;\n\n", m.name);
937 }
938 }
939 out
940}
941
942fn handler_name(event: &str) -> String {
944 let mut chars = event.chars();
945 match chars.next() {
946 Some(first) => format!("on{}{}", first.to_ascii_uppercase(), chars.as_str()),
947 None => "on".to_owned(),
948 }
949}
950
951#[cfg(test)]
952mod tests {
953 use super::*;
954 use crate::ui::prelude::*;
955
956 #[derive(Default)]
957 struct Stepper;
958
959 #[derive(Clone, PartialEq, Props)]
961 struct StepperProps {
962 value: f64,
964 #[prop(default)]
965 size: StepperSize,
966 max_value: Option<f64>,
967 label: Option<Slot>,
969 children: Children,
970 }
971
972 #[derive(Clone, Copy, PartialEq, Default, PropEnum)]
973 enum StepperSize {
974 #[default]
975 Regular,
976 ExtraLarge,
977 }
978
979 #[derive(Event)]
980 enum StepperEvent {
981 Change {
983 new_value: f64,
984 },
985 Limit(u32),
986 Reset,
987 }
988
989 struct StepperApi;
990
991 #[methods]
992 impl StepperApi {
993 fn jump_to(&self, value: f64) {
995 let _ = value;
996 }
997
998 fn value(&self) -> f64 {
999 0.0
1000 }
1001 }
1002
1003 impl Component for Stepper {
1004 type Props = StepperProps;
1005 type Event = StepperEvent;
1006 const METHODS: Methods = Methods::of::<StepperApi>();
1007
1008 fn view(_: StepperProps, _: super::super::Scope<StepperEvent>) -> impl IntoElement {
1009 view()
1010 }
1011 }
1012
1013 #[test]
1014 fn the_declarations_come_from_the_types() {
1015 let mut registry = Registry::new();
1016 registry.register::<Stepper>();
1017 let ts = declarations(®istry, &[]);
1018 for line in [
1019 " /** The value. */\n value: number;",
1020 "export type StepperSize = \"regular\" | \"extraLarge\";",
1021 " size?: StepperSize;",
1022 " maxValue?: number | null;",
1023 " /** Above the control. */\n label?: JSX.Element;",
1024 " children?: JSX.Element;",
1025 " /** The value changed. */\n onChange?: (data: { newValue: number }) => void;",
1026 " onLimit?: (data: number) => void;",
1027 " onReset?: () => void;",
1028 "/** Picks a number. */",
1029 "export interface StepperRef {",
1030 " /** Jumps to `value`. */\n jumpTo(value: number): void;",
1031 " value(): Promise<number>;",
1032 "export interface StepperProps extends Omit<ComponentHostProps, \"ref\"> {\n ref?: StepperRef | ((ref: StepperRef) => void);",
1033 "export declare const Stepper: ((props: StepperProps) => JSX.Element);",
1034 ] {
1035 assert!(ts.contains(line), "missing {line:?} in\n{ts}");
1036 }
1037 let mut props = StepperProps::initial();
1038 assert!(
1039 props
1040 .set("size", Some(serde_json::json!("extraLarge")))
1041 .unwrap()
1042 );
1043 assert!(props.size == StepperSize::ExtraLarge);
1044 assert!(props.set("size", Some(serde_json::json!("huge"))).is_err());
1045 assert!(props.set("size", None).unwrap());
1046 assert!(props.size == StepperSize::Regular);
1047 assert_eq!(
1048 StepperEvent::Change { new_value: 2.5 }.data(),
1049 serde_json::json!({ "newValue": 2.5 })
1050 );
1051 assert_eq!(StepperEvent::Limit(3).data(), serde_json::json!(3));
1052 assert_eq!(StepperEvent::Reset.name(), "reset");
1053 }
1054
1055 #[test]
1056 fn components_are_named_after_their_types() {
1057 let mut registry = Registry::ui_set("test/ui");
1058 registry.register::<Stepper>();
1059 let specs = registry.specs();
1060 assert_eq!(specs[0].name, "nsh_core::ui::component::tests::Stepper");
1061 assert_eq!(specs[0].export, "Stepper");
1062 assert_eq!(export_name("app::picker::Picker<app::Fruit>"), "Picker");
1063 assert_eq!(export_name("Bare"), "Bare");
1064 }
1065
1066 mod other {
1067 use crate::ui::prelude::*;
1068
1069 #[derive(Default)]
1071 pub(super) struct Stepper;
1072
1073 impl Component for Stepper {
1074 type Props = ();
1075 type Event = NoEvent;
1076
1077 fn view(_: (), _: crate::ui::Scope<NoEvent>) -> impl IntoElement {
1078 view()
1079 }
1080 }
1081 }
1082
1083 #[test]
1084 #[should_panic(
1085 expected = "components `nsh_core::ui::component::tests::Stepper` and `nsh_core::ui::component::tests::other::Stepper` are both exported as `Stepper` in `test/ui`"
1086 )]
1087 fn two_components_of_one_set_cannot_share_an_export() {
1088 Registry::ui_set("test/ui")
1089 .register::<Stepper>()
1090 .register::<other::Stepper>();
1091 }
1092
1093 #[test]
1094 #[should_panic(
1095 expected = "component `nsh_core::ui::component::tests::Stepper` is registered twice"
1096 )]
1097 fn a_component_is_registered_once() {
1098 Registry::new().register::<Stepper>().register::<Stepper>();
1099 }
1100
1101 #[test]
1102 fn sets_may_share_exports_but_not_components() {
1103 let mut a = Registry::ui_set("test/a");
1104 a.register::<Stepper>();
1105 let mut b = Registry::ui_set("test/b");
1106 b.register::<other::Stepper>();
1107 let merged = Registry::merged(&[a.clone(), b]);
1108 assert_eq!(merged.specs().len(), 2);
1109 let twice = std::panic::catch_unwind(|| Registry::merged(&[a.clone(), a]));
1110 let message = *twice.unwrap_err().downcast::<String>().unwrap();
1111 assert_eq!(
1112 message,
1113 "component `nsh_core::ui::component::tests::Stepper` is registered twice, by two UI sets"
1114 );
1115 }
1116}