1use std::{
19 any::{Any, TypeId},
20 cell::{Ref, RefCell, RefMut},
21 fmt,
22 rc::Rc,
23};
24
25use super::{
26 JsValue, PropError, TsType, TsTypes,
27 call::{JsResult, TaskStart},
28 callback::{Trace, Tracer},
29 js::{JsHost, JsIn, JsOwned, JsRaw},
30 module::ModuleParam,
31};
32
33pub trait Class: Trace + Sized + 'static {
38 const DEF: &'static ClassDef;
40}
41
42pub struct ClassDef {
44 pub name: &'static str,
46 pub doc: &'static str,
48 pub type_id: fn() -> TypeId,
50 pub type_name: fn() -> &'static str,
52 pub members: &'static [Member],
54 pub interface: bool,
58}
59
60impl ClassDef {
61 pub fn constructor(&self) -> Option<&'static Member> {
63 self.members
64 .iter()
65 .find(|m| m.kind == MemberKind::Constructor)
66 }
67}
68
69impl fmt::Debug for ClassDef {
70 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71 f.debug_struct("ClassDef")
72 .field("name", &self.name)
73 .finish_non_exhaustive()
74 }
75}
76
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
79pub enum MemberKind {
80 Constructor,
82 Method,
84 Getter,
86 Setter,
88 Static,
90}
91
92pub struct Member {
94 pub name: &'static str,
96 pub doc: &'static str,
98 pub kind: MemberKind,
100 pub params: &'static [ModuleParam],
102 pub returns: Option<TsType>,
104 pub refs: ClassRefs,
106 pub call: MemberCall,
108 pub overloads: &'static [super::Overload],
112}
113
114pub type ClassRefs = fn(&mut Vec<&'static ClassDef>);
119
120pub type AsyncCall = fn(&dyn JsHost) -> Result<TaskStart, Thrown>;
123
124#[derive(Clone, Copy)]
126pub enum MemberCall {
127 Sync(fn(&dyn JsHost) -> Result<JsRaw, Thrown>),
130 Async(AsyncCall),
133 Start(AsyncCall),
136}
137
138impl MemberCall {
139 pub fn is_async(&self) -> bool {
141 matches!(self, MemberCall::Async(_) | MemberCall::Start(_))
142 }
143}
144
145#[derive(Debug, Clone, PartialEq, Eq)]
147pub enum Thrown {
148 Type(String),
150 Range(String),
152 Error(String),
154 Fields(Box<super::ErrorFields>),
156}
157
158impl Thrown {
159 pub fn message(&self) -> &str {
161 match self {
162 Thrown::Type(m) | Thrown::Range(m) | Thrown::Error(m) => m,
163 Thrown::Fields(f) => &f.message,
164 }
165 }
166}
167
168impl From<PropError> for Thrown {
169 fn from(e: PropError) -> Self {
170 Thrown::Type(e.0)
171 }
172}
173
174impl From<String> for Thrown {
175 fn from(message: String) -> Self {
176 Thrown::Error(message)
177 }
178}
179
180impl From<&str> for Thrown {
181 fn from(message: &str) -> Self {
182 Thrown::Error(message.to_owned())
183 }
184}
185
186impl fmt::Display for Thrown {
187 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188 f.write_str(self.message())
189 }
190}
191
192pub struct Instance<C: 'static> {
207 cell: Rc<InstanceCell<C>>,
208}
209
210impl<C> Clone for Instance<C> {
211 fn clone(&self) -> Self {
212 Self {
213 cell: self.cell.clone(),
214 }
215 }
216}
217
218impl<C> fmt::Debug for Instance<C> {
219 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220 write!(f, "Instance<{}>", std::any::type_name::<C>())
221 }
222}
223
224struct InstanceCell<C> {
226 value: RefCell<Option<C>>,
228}
229
230impl<C: Class> Instance<C> {
231 pub fn new(value: C) -> Self {
234 Self {
235 cell: Rc::new(InstanceCell {
236 value: RefCell::new(Some(value)),
237 }),
238 }
239 }
240
241 #[track_caller]
248 pub fn with<R>(&self, f: impl FnOnce(&C) -> R) -> R {
249 match self.borrow() {
250 Ok(value) => f(&value),
251 Err(e) => panic!("{e}"),
252 }
253 }
254
255 #[track_caller]
262 pub fn with_mut<R>(&self, f: impl FnOnce(&mut C) -> R) -> R {
263 match self.borrow_mut() {
264 Ok(mut value) => f(&mut value),
265 Err(e) => panic!("{e}"),
266 }
267 }
268
269 pub fn is_disposed(&self) -> bool {
272 matches!(self.cell.value.try_borrow().as_deref(), Ok(None))
273 }
274
275 #[track_caller]
282 pub fn dispose(&self) {
283 if let Err(e) = self.cell.dispose() {
284 panic!("{e}");
285 }
286 }
287
288 pub fn ptr_eq(&self, other: &Self) -> bool {
290 Rc::ptr_eq(&self.cell, &other.cell)
291 }
292
293 fn borrow(&self) -> Result<Ref<'_, C>, Thrown> {
294 let value = self
295 .cell
296 .value
297 .try_borrow()
298 .map_err(|_| Thrown::Type(format!("{} used re-entrantly", C::DEF.name)))?;
299 Ref::filter_map(value, Option::as_ref)
300 .map_err(|_| Thrown::Type(format!("{} is disposed", C::DEF.name)))
301 }
302
303 fn borrow_mut(&self) -> Result<RefMut<'_, C>, Thrown> {
304 let value = self
305 .cell
306 .value
307 .try_borrow_mut()
308 .map_err(|_| Thrown::Type(format!("{} used re-entrantly", C::DEF.name)))?;
309 RefMut::filter_map(value, Option::as_mut)
310 .map_err(|_| Thrown::Type(format!("{} is disposed", C::DEF.name)))
311 }
312
313 pub(super) fn only_handle(&self) -> bool {
316 Rc::strong_count(&self.cell) == 1
317 }
318
319 pub(super) fn trace_value(&self, tracer: &mut Tracer<'_>) {
321 self.cell.trace(tracer);
322 }
323
324 fn erased(&self) -> Rc<dyn ClassInstance> {
326 self.cell.clone()
327 }
328
329 fn of(any: Rc<dyn ClassInstance>) -> Option<Self> {
331 let any: Rc<dyn Any> = any;
332 any.downcast::<InstanceCell<C>>()
333 .ok()
334 .map(|cell| Self { cell })
335 }
336}
337
338#[doc(hidden)]
340pub trait ClassInstance: Any {
341 fn def(&self) -> &'static ClassDef;
343 fn dispose(&self) -> Result<(), String>;
345 fn disposed(&self) -> bool;
347 fn trace(&self, tracer: &mut Tracer<'_>);
350}
351
352impl<C: Class> ClassInstance for InstanceCell<C> {
353 fn def(&self) -> &'static ClassDef {
354 C::DEF
355 }
356
357 fn dispose(&self) -> Result<(), String> {
358 let value = self
359 .value
360 .try_borrow_mut()
361 .map_err(|_| format!("{} used re-entrantly", C::DEF.name))?
362 .take();
363 drop(value);
365 Ok(())
366 }
367
368 fn disposed(&self) -> bool {
369 matches!(self.value.try_borrow().as_deref(), Ok(None))
370 }
371
372 fn trace(&self, tracer: &mut Tracer<'_>) {
373 if let Ok(value) = self.value.try_borrow()
374 && let Some(value) = &*value
375 {
376 value.trace(tracer);
377 }
378 }
379}
380
381pub trait Arg: Sized {
387 fn ts_type(types: &mut TsTypes) -> String;
389 fn from_js(value: JsIn<'_>) -> Result<Self, PropError>;
391 #[doc(hidden)]
394 fn classes(_out: &mut Vec<&'static ClassDef>) {}
395}
396
397impl<T: JsValue> Arg for T {
398 fn ts_type(types: &mut TsTypes) -> String {
399 T::ts_type(types)
400 }
401
402 fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
403 T::from_js(value)
404 }
405}
406
407impl<C: Class> Arg for Instance<C> {
410 fn ts_type(types: &mut TsTypes) -> String {
411 types.class(C::DEF)
412 }
413
414 fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
415 value
416 .host()
417 .instance(value.raw())
418 .and_then(Instance::of)
419 .ok_or_else(|| value.expected(&format!("a {}", C::DEF.name)))
420 }
421
422 fn classes(out: &mut Vec<&'static ClassDef>) {
423 out.push(C::DEF);
424 }
425}
426
427impl<C: Class> Arg for Option<Instance<C>> {
429 fn ts_type(types: &mut TsTypes) -> String {
430 format!("{} | null", <Instance<C> as Arg>::ts_type(types))
431 }
432
433 fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
434 if value.is_nullish() {
435 return Ok(None);
436 }
437 Instance::from_js(value).map(Some)
438 }
439
440 fn classes(out: &mut Vec<&'static ClassDef>) {
441 out.push(C::DEF);
442 }
443}
444
445pub trait Ret: Sized {
449 const UNIT: bool = false;
451 fn ts_type(types: &mut TsTypes) -> String;
453 fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError>;
455 #[doc(hidden)]
457 fn classes(_out: &mut Vec<&'static ClassDef>) {}
458}
459
460impl<T: JsValue> Ret for T {
461 fn ts_type(types: &mut TsTypes) -> String {
462 T::ts_type(types)
463 }
464
465 fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
466 self.to_js(host)
467 }
468}
469
470impl Ret for () {
471 const UNIT: bool = true;
472
473 fn ts_type(_types: &mut TsTypes) -> String {
474 "void".into()
475 }
476
477 fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
478 Ok(JsOwned::new(host, host.undefined()))
479 }
480}
481
482impl<C: Class> Ret for Instance<C> {
483 fn ts_type(types: &mut TsTypes) -> String {
484 types.class(C::DEF)
485 }
486
487 fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
488 Ok(JsOwned::new(host, host.wrap(self.erased())?))
489 }
490
491 fn classes(out: &mut Vec<&'static ClassDef>) {
492 out.push(C::DEF);
493 }
494}
495
496impl<C: Class> Ret for Vec<Instance<C>> {
498 fn ts_type(types: &mut TsTypes) -> String {
499 format!("{}[]", types.class(C::DEF))
500 }
501
502 fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
503 let mut items = Vec::with_capacity(self.len());
505 for instance in self {
506 items.push(instance.into_js(host)?);
507 }
508 let raws = items.into_iter().map(JsOwned::into_raw).collect();
509 Ok(JsOwned::new(host, host.new_array(raws)?))
510 }
511
512 fn classes(out: &mut Vec<&'static ClassDef>) {
513 out.push(C::DEF);
514 }
515}
516
517impl<C: Class> Ret for Option<Instance<C>> {
518 fn ts_type(types: &mut TsTypes) -> String {
519 format!("{} | null", <Instance<C> as Ret>::ts_type(types))
520 }
521
522 fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
523 match self {
524 Some(i) => i.into_js(host),
525 None => Ok(JsOwned::new(host, host.null())),
526 }
527 }
528
529 fn classes(out: &mut Vec<&'static ClassDef>) {
530 out.push(C::DEF);
531 }
532}
533
534#[derive(Debug, Clone)]
538pub struct MemberSpec {
539 pub name: &'static str,
541 pub doc: &'static str,
543 pub kind: MemberKind,
545 pub params: Vec<(&'static str, String, bool)>,
547 pub returns: Option<String>,
549 pub is_async: bool,
551 pub overloads: Vec<super::OverloadSpec>,
553}
554
555#[derive(Debug, Clone)]
557pub struct ClassSpec {
558 pub name: &'static str,
560 pub doc: &'static str,
562 pub members: Vec<MemberSpec>,
564 pub types: TsTypes,
566 pub def: &'static ClassDef,
568}
569
570impl ClassSpec {
571 pub(crate) fn of(def: &'static ClassDef) -> Self {
572 let mut types = TsTypes::default();
573 let members = def
574 .members
575 .iter()
576 .map(|m| MemberSpec {
577 name: m.name,
578 doc: m.doc,
579 kind: m.kind,
580 params: m
581 .params
582 .iter()
583 .map(|(n, ts, optional)| (*n, ts(&mut types), *optional))
584 .collect(),
585 returns: m.returns.map(|ts| ts(&mut types)),
586 is_async: m.call.is_async(),
587 overloads: m
588 .overloads
589 .iter()
590 .map(|o| {
591 let params = o
592 .params
593 .iter()
594 .map(|(n, ts, optional)| (*n, ts(&mut types), *optional))
595 .collect();
596 (params, o.returns.map(|ts| ts(&mut types)))
597 })
598 .collect(),
599 })
600 .collect();
601 Self {
602 name: def.name,
603 doc: def.doc,
604 members,
605 types,
606 def,
607 }
608 }
609}
610
611#[doc(hidden)]
615pub(crate) mod __private {
616 use super::*;
617
618 pub const fn arg_ts<T: Arg>() -> TsType {
621 if crate::ui::DECLARATIONS {
622 T::ts_type
623 } else {
624 |_| String::new()
625 }
626 }
627
628 pub fn named_arg_ts<T: crate::ui::callback::NamedArgs>(
632 types: &mut TsTypes,
633 names: &[&str],
634 ) -> String {
635 if crate::ui::DECLARATIONS {
636 T::ts_named(types, names)
637 } else {
638 String::new()
639 }
640 }
641
642 pub const fn ret_ts<T: Ret>() -> TsType {
644 if crate::ui::DECLARATIONS {
645 T::ts_type
646 } else {
647 |_| String::new()
648 }
649 }
650
651 pub fn class_into_js<C: Class>(value: C, host: &dyn JsHost) -> Result<JsOwned<'_>, PropError> {
653 Instance::new(value).into_js(host)
654 }
655
656 pub fn class_ts<C: Class>(types: &mut TsTypes) -> String {
658 types.class(C::DEF)
659 }
660
661 pub fn arg_classes<T: Arg>(out: &mut Vec<&'static ClassDef>) {
663 T::classes(out);
664 }
665
666 pub fn ret_classes<T: Ret>(out: &mut Vec<&'static ClassDef>) {
668 T::classes(out);
669 }
670
671 pub fn class_refs<C: Class>(out: &mut Vec<&'static ClassDef>) {
673 out.push(C::DEF);
674 }
675
676 pub fn arg<T: Arg>(host: &dyn JsHost, i: usize, what: &str, name: &str) -> Result<T, Thrown> {
679 T::from_js(JsIn::new(host, host.arg(i)))
680 .map_err(|e| Thrown::Type(format!("{what}: `{name}`: {e}")))
681 }
682
683 pub fn this<C: Class>(host: &dyn JsHost, what: &str) -> Result<Instance<C>, Thrown> {
685 host.instance(host.this())
686 .and_then(Instance::of)
687 .ok_or_else(|| {
688 Thrown::Type(format!("{what}: Illegal invocation: not a {}", C::DEF.name))
689 })
690 }
691
692 pub fn borrow<C: Class>(instance: &Instance<C>) -> Result<Ref<'_, C>, Thrown> {
694 instance.borrow()
695 }
696
697 pub fn borrow_mut<C: Class>(instance: &Instance<C>) -> Result<RefMut<'_, C>, Thrown> {
699 instance.borrow_mut()
700 }
701
702 pub fn borrow_arg<'a, C: Class>(
706 instance: &'a Instance<C>,
707 what: &str,
708 name: &str,
709 ) -> Result<Ref<'a, C>, Thrown> {
710 instance.borrow().map_err(|e| arg_error(e, what, name))
711 }
712
713 pub fn borrow_arg_mut<'a, C: Class>(
715 instance: &'a Instance<C>,
716 what: &str,
717 name: &str,
718 ) -> Result<RefMut<'a, C>, Thrown> {
719 instance.borrow_mut().map_err(|e| arg_error(e, what, name))
720 }
721
722 fn arg_error(e: Thrown, what: &str, name: &str) -> Thrown {
724 match e {
725 Thrown::Type(m) => Thrown::Type(format!("{what}: `{name}`: {m}")),
726 Thrown::Range(m) => Thrown::Range(format!("{what}: `{name}`: {m}")),
727 Thrown::Error(m) => Thrown::Error(format!("{what}: `{name}`: {m}")),
728 Thrown::Fields(mut f) => {
729 f.message = format!("{what}: `{name}`: {}", f.message);
730 Thrown::Fields(f)
731 }
732 }
733 }
734
735 pub fn ret<T: Ret>(host: &dyn JsHost, value: T) -> Result<JsRaw, Thrown> {
737 value
738 .into_js(host)
739 .map(JsOwned::into_raw)
740 .map_err(|e| Thrown::Error(e.0))
741 }
742
743 pub fn ret_result<T: Ret, E: crate::ui::IntoThrown>(
746 host: &dyn JsHost,
747 value: Result<T, E>,
748 ) -> Result<JsRaw, Thrown> {
749 match value {
750 Ok(v) => ret(host, v),
751 Err(e) => Err(e.into_thrown()),
752 }
753 }
754
755 pub fn start<T: Ret + 'static>(value: crate::ui::Later<T>) -> Result<TaskStart, Thrown> {
757 Ok(Box::new(move || value.into_future()))
758 }
759
760 pub fn start_result<T: Ret + 'static, E: crate::ui::IntoThrown>(
762 value: Result<crate::ui::Later<T>, E>,
763 ) -> Result<TaskStart, Thrown> {
764 value.map_err(E::into_thrown).and_then(start)
765 }
766
767 pub fn call_cx(host: &dyn JsHost) -> crate::ui::CallCx<'_> {
769 crate::ui::CallCx::new(host)
770 }
771
772 pub fn system(host: &dyn JsHost) -> crate::ui::System {
774 host.system()
775 }
776
777 pub fn construct<C: Class>(host: &dyn JsHost, value: C) -> Result<JsRaw, Thrown> {
779 host.construct(Instance::new(value).erased())
780 .map_err(|e| Thrown::Error(e.0))
781 }
782
783 pub fn construct_result<C: Class, E: crate::ui::IntoThrown>(
785 host: &dyn JsHost,
786 value: Result<C, E>,
787 ) -> Result<JsRaw, Thrown> {
788 match value {
789 Ok(v) => construct(host, v),
790 Err(e) => Err(e.into_thrown()),
791 }
792 }
793
794 pub fn boxed<T: Ret + 'static>(value: T) -> JsResult {
796 Ok(Box::new(value))
797 }
798
799 pub fn boxed_result<T: Ret + 'static, E: crate::ui::IntoThrown>(
802 value: Result<T, E>,
803 ) -> JsResult {
804 match value {
805 Ok(v) => Ok(Box::new(v)),
806 Err(e) => Err(e.into_thrown()),
807 }
808 }
809
810 #[diagnostic::on_unimplemented(
812 message = "`{Self}` needs `#[class]` on its struct too",
813 label = "a class's struct and its `impl` block both have `#[class]`"
814 )]
815 pub trait ClassDoc {
816 const DOC: &'static str;
818 const INTERFACE: bool;
820 }
821
822 #[diagnostic::on_unimplemented(
825 message = "`{Self}` needs `#[module]` on its struct too",
826 label = "a module's struct and its `impl` block both have `#[module]` (the struct's doc comment documents it)"
827 )]
828 pub trait ModuleDoc {
829 const DOC: &'static str;
831 }
832
833 pub struct Field<'a, T>(pub &'a T);
838
839 pub trait TraceField {
841 fn trace_field(&self, tracer: &mut Tracer<'_>);
843 }
844
845 impl<T: Trace> TraceField for &Field<'_, T> {
846 fn trace_field(&self, tracer: &mut Tracer<'_>) {
847 self.0.trace(tracer);
848 }
849 }
850
851 pub trait SkipField {
853 fn trace_field(&self, tracer: &mut Tracer<'_>);
855 }
856
857 impl<T> SkipField for Field<'_, T> {
858 fn trace_field(&self, _tracer: &mut Tracer<'_>) {}
859 }
860
861 pub fn type_id<T: 'static>() -> TypeId {
863 TypeId::of::<T>()
864 }
865
866 pub fn type_name<T: 'static>() -> &'static str {
868 std::any::type_name::<T>()
869 }
870}
871
872#[cfg(test)]
873mod tests {
874 use crate::ui::{Registry, declarations, prelude::*};
875
876 #[allow(dead_code)]
878 fn drop() {}
879
880 #[class]
882 struct Configured {
883 #[cfg(any())]
884 gone: NoSuchType,
885 kept: Option<Callback>,
886 }
887
888 #[class]
889 impl Configured {}
890
891 #[allow(dead_code)]
892 fn configured() -> Configured {
893 Configured { kept: None }
894 }
895
896 #[class]
898 struct Tally {
899 count: i64,
900 label: Option<String>,
901 }
902
903 #[class]
904 impl Tally {
905 pub(crate) fn new(start: Option<i64>) -> Self {
907 Tally {
908 count: start.unwrap_or(0),
909 label: None,
910 }
911 }
912
913 pub(crate) fn add(&mut self, by: i64, label: Option<String>) -> i64 {
915 let _ = label;
916 self.count += by;
917 self.count
918 }
919
920 #[getter]
922 pub(crate) fn count(&self) -> i64 {
923 self.count
924 }
925
926 #[setter]
927 pub(crate) fn set_count(&mut self, count: i64) {
928 self.count = count;
929 }
930
931 #[getter]
932 pub(crate) fn label(&self) -> Option<String> {
933 self.label.clone()
934 }
935
936 #[setter]
938 pub(crate) fn set_label(&mut self, label: Option<String>) {
939 self.label = label;
940 }
941
942 #[cfg(any())]
944 pub(crate) fn nowhere(&self) -> i64 {
945 0
946 }
947
948 pub(crate) fn parse(text: String) -> Result<Tally, String> {
950 text.parse()
951 .map(|count| Tally { count, label: None })
952 .map_err(|_| text)
953 }
954
955 pub(crate) fn reset(&mut self, to: Option<i64>, by: i64) {
956 self.count = to.unwrap_or(0) + by;
957 }
958
959 pub(crate) fn absorb(
960 &mut self,
961 other: &Tally,
962 token: Option<Instance<Token>>,
963 ) -> Instance<Token> {
964 self.count += other.count;
965 token.unwrap_or_else(|| Instance::new(Token))
966 }
967
968 pub(crate) async fn save(this: Instance<Self>, path: String) -> Result<(), String> {
970 let _ = (this, path);
971 Ok(())
972 }
973
974 pub(crate) async fn later(start: i64) -> Tally {
975 Tally {
976 count: start,
977 label: None,
978 }
979 }
980
981 pub(crate) fn sort_by(&mut self, compare: Callback<(String, String), f64>) {
983 let _ = compare;
984 }
985
986 pub(crate) fn on(
987 &mut self,
988 #[args(count)] listener: Option<Callback<i64>>,
989 done: Option<Callback>,
990 ) {
991 let _ = (listener, done);
992 }
993
994 #[allow(dead_code)]
996 fn bump(&mut self) {
997 self.count += 1;
998 }
999
1000 #[allow(dead_code)]
1002 async fn private_later() -> i64 {
1003 0
1004 }
1005 }
1006
1007 #[class]
1009 struct Token;
1010
1011 #[class]
1012 impl Token {
1013 pub(crate) fn mint() -> Token {
1014 Token
1015 }
1016 }
1017
1018 #[test]
1019 fn classes_are_declared_from_their_definitions() {
1020 let mut registry = Registry::ui_set("test/ui");
1021 registry.class::<Tally>().class::<Token>();
1022 assert!(
1024 !<Tally as crate::ui::Class>::DEF
1025 .members
1026 .iter()
1027 .any(|m| m.name == "bump" || m.name == "privateLater")
1028 );
1029 assert_eq!(
1030 declarations(®istry, &[]),
1031 r#"/** A tally kept in Rust. */
1032export declare class Tally {
1033 /** Starts at `start` (0 when left out). */
1034 constructor(start?: number | null);
1035 /** Adds `by`; the new count. */
1036 add(by: number, label?: string | null): number;
1037 /** The count. */
1038 get count(): number;
1039 set count(count: number);
1040 get label(): string | null;
1041 /** A setter's value is required, even an `Option`. */
1042 set label(label: string | null);
1043 /** A tally from `"12"`; throws on anything else. */
1044 static parse(text: string): Tally;
1045 reset(to: number | null, by: number): void;
1046 absorb(other: Tally, token?: Token | null): Token;
1047 /** Saves the count; resolves when it is written. */
1048 save(path: string): Promise<void>;
1049 static later(start: number): Promise<Tally>;
1050 /** Sorts with the app's comparison. */
1051 sortBy(compare: (a: string, b: string) => number): void;
1052 on(listener?: ((count: number) => void) | null, done?: (() => void) | null): void;
1053 /** Frees the Rust value now (else when the object is collected); the object throws after. */
1054 dispose(): void;
1055 [Symbol.dispose](): void;
1056}
1057
1058/** Made by its members only. */
1059export declare class Token {
1060 /** Made by the class's members only. */
1061 private constructor();
1062 static mint(): Token;
1063 /** Frees the Rust value now (else when the object is collected); the object throws after. */
1064 dispose(): void;
1065 [Symbol.dispose](): void;
1066}
1067
1068"#
1069 );
1070 }
1071
1072 #[module]
1074 struct Tools;
1075
1076 #[module]
1077 impl Tools {
1078 pub(crate) fn sum(values: Vec<f64>) -> f64 {
1080 values.iter().sum()
1081 }
1082
1083 pub(crate) fn shout(text: String) {
1084 let _ = text;
1085 }
1086
1087 pub(crate) fn measure(text: String, cx: &mut ModuleCx) -> usize {
1089 let _ = cx;
1090 text.len()
1091 }
1092
1093 pub(crate) fn pick(#[args(old_value, new_value)] choose: Callback<(f64, f64), f64>) -> f64 {
1095 choose.call((0.0, 1.0)).unwrap_or(0.0)
1096 }
1097
1098 pub(crate) fn beep(cx: &mut ModuleCx) {
1100 let _ = cx;
1101 }
1102
1103 pub(crate) fn check(cx: &mut ModuleCx) -> Result<(), String> {
1105 let _ = cx;
1106 Ok(())
1107 }
1108
1109 #[allow(clippy::unused_unit)]
1111 pub(crate) fn hum(cx: &mut ModuleCx) -> () {
1112 let _ = cx;
1113 }
1114
1115 pub(crate) async fn settle() {}
1117
1118 pub(crate) async fn later(listener: Callback<i64, String>) -> Result<String, String> {
1119 listener.call_async(1).await
1120 }
1121
1122 #[cfg(any())]
1124 pub(crate) fn nowhere() {}
1125
1126 #[allow(dead_code)]
1128 fn helper(text: String) -> String {
1129 text
1130 }
1131 }
1132
1133 #[test]
1134 fn functions_without_a_context_return_their_values() {
1135 let mut registry = Registry::ui_set("test/ui");
1136 registry.module::<Tools>();
1137 assert!(
1138 !<Tools as crate::ui::Module>::FUNCTIONS
1139 .iter()
1140 .any(|f| f.name == "helper")
1141 );
1142 assert_eq!(
1143 declarations(®istry, &[]),
1144 r#"/** Functions of the three kinds. */
1145export interface ToolsModule {
1146 /** The sum, at once. */
1147 sum(values: (number)[]): number;
1148 shout(text: string): void;
1149 /** A promise of the length. */
1150 measure(text: string): Promise<number>;
1151 /** Picks with the app's choice, its arguments named. */
1152 pick(choose: (oldValue: number, newValue: number) => number): number;
1153 /** An op returning nothing: a plain call. */
1154 beep(): void;
1155 /** An op that may fail: a promise, rejected with an `Err`. */
1156 check(): Promise<void>;
1157 /** `-> ()` written out: the same as no return type. */
1158 hum(): void;
1159 /** A task returning nothing. */
1160 settle(): Promise<void>;
1161 later(listener: (value: number) => string): Promise<string>;
1162}
1163
1164/** Functions of the three kinds. */
1165export declare const Tools: ToolsModule;
1166
1167"#
1168 );
1169 }
1170
1171 #[test]
1174 fn registering_a_class_again_does_nothing() {
1175 let mut r = Registry::ui_set("test/ui");
1176 r.class::<Tally>().class::<Tally>();
1177 let tallies = r.class_specs().iter().filter(|c| c.name == "Tally").count();
1178 assert_eq!(tallies, 1);
1179 }
1180
1181 mod view {
1183 use crate::ui::prelude::*;
1184
1185 pub(super) struct Tally;
1186
1187 impl Component for Tally {
1188 type Props = ();
1189 type Event = NoEvent;
1190
1191 fn view(_: (), _: Scope<NoEvent>) -> impl IntoElement {
1192 view()
1193 }
1194 }
1195 }
1196
1197 #[test]
1199 fn a_class_and_a_component_share_no_name() {
1200 let class_first = std::panic::catch_unwind(|| {
1201 Registry::ui_set("test/ui")
1202 .class::<Tally>()
1203 .register::<view::Tally>();
1204 });
1205 assert!(class_first.is_err(), "a component after a class");
1206 let component_first = std::panic::catch_unwind(|| {
1207 Registry::ui_set("test/ui")
1208 .register::<view::Tally>()
1209 .class::<Tally>();
1210 });
1211 assert!(component_first.is_err(), "a class after a component");
1212 }
1213}