1use std::{
18 any::{Any, TypeId},
19 cell::{Cell, RefCell, UnsafeCell},
20 fmt,
21 marker::PhantomData,
22 mem::ManuallyDrop,
23 panic::AssertUnwindSafe,
24 rc::Rc,
25};
26
27use crate::reactive::{self as r, DISPOSED, Equals, Kind, NONE, UNOWNED};
28
29type Value = Option<Rc<dyn Any>>;
31type Func = Rc<dyn Compute>;
32type Compare = fn(&dyn Any, &dyn Any) -> bool;
33
34pub(crate) trait Compute {
37 fn run(&self, prev: Value) -> Value;
38}
39
40impl<F: Fn(Value) -> Value> Compute for F {
41 fn run(&self, prev: Value) -> Value {
42 self(prev)
43 }
44}
45
46#[derive(Clone, Copy)]
49pub(crate) struct Rust;
50
51#[derive(Default)]
53pub(crate) struct RustData {
54 failures: Vec<(u32, String)>,
57 runaway: bool,
58 emits: Vec<super::once::Emitted>,
60 pub(crate) ambient: super::Ambient,
62 apis: rustc_hash::FxHashMap<crate::NodeId, ApiEntry>,
64 boundaries: rustc_hash::FxHashMap<Owner, Signal<Option<super::ComponentError>>>,
67}
68
69pub(crate) fn register_boundary(failed: Signal<Option<super::ComponentError>>) {
72 let owner = Owner::current();
73 with_data(|d| d.boundaries.insert(owner, failed));
74 cleanup(move || {
75 with_data(|d| d.boundaries.remove(&owner));
76 });
77}
78
79pub(crate) fn boundary_of(owner: Owner) -> Option<Signal<Option<super::ComponentError>>> {
81 let mut at = Some(owner);
82 while let Some(owner) = at.filter(Owner::is_live) {
83 if let Some(signal) = with_data(|d| d.boundaries.get(&owner).copied()) {
84 return Some(signal);
85 }
86 at = owner.parent();
87 }
88 None
89}
90
91#[derive(Clone)]
94struct ApiEntry {
95 api: Rc<dyn Any>,
96}
97
98pub(crate) fn register_api<A: super::Api>(host: crate::NodeId, api: A) {
101 let entry = ApiEntry { api: Rc::new(api) };
102 with_data(|d| d.apis.insert(host, entry));
103 cleanup(move || {
104 with_data(|d| d.apis.remove(&host));
105 });
106}
107
108pub(crate) fn api_of<A: super::Api>(host: crate::NodeId) -> Option<Rc<A>> {
110 let entry = with_data(|d| d.apis.get(&host).cloned())?;
111 entry.api.downcast::<A>().ok()
112}
113
114pub(crate) fn call_api(host: crate::NodeId, call: super::MethodCall) -> Option<super::JsResult> {
118 let entry = with_data(|d| d.apis.get(&host).cloned())?;
120 call(&*entry.api)
121}
122
123pub(crate) fn with_data<R>(f: impl FnOnce(&mut RustData) -> R) -> R {
125 f(&mut graph().data)
126}
127
128pub(crate) fn try_with_data<R>(f: impl FnOnce(&mut RustData) -> R) -> Option<R> {
131 let graph = CURRENT.with(Cell::get);
132 (!graph.is_null()).then(|| f(unsafe { &mut (*graph).data }))
135}
136
137pub(crate) fn emit(host: crate::NodeId, event: Box<dyn super::builder::AnyEvent>) {
139 graph().data.emits.push((host, event));
140}
141
142thread_local! {
143 #[allow(
145 clippy::missing_const_for_thread_local,
146 reason = "it is const; clippy misreads Android's expansion"
147 )]
148 static CURRENT: Cell<*mut r::Graph<Rust>> = const { Cell::new(std::ptr::null_mut()) };
149}
150
151unsafe impl r::Host for Rust {
154 type Value = Value;
155 type Func = Func;
156 type Equals = Compare;
157 type Cleanup = Box<dyn FnOnce()>;
158 type Context = (TypeId, Rc<dyn Any>);
159 type Data = RustData;
160
161 #[inline]
162 unsafe fn graph<'a>(self) -> &'a mut r::Graph<Rust> {
163 let graph = CURRENT.with(Cell::get);
164 assert!(
165 !graph.is_null(),
166 "no reactive runtime: signals are used on the engine thread, while components run"
167 );
168 unsafe { &mut *graph }
170 }
171
172 #[inline]
173 fn empty() -> Value {
174 None
175 }
176
177 #[inline]
178 fn dup(self, v: &Value) -> Value {
179 v.clone()
180 }
181
182 #[inline]
183 fn free(self, v: Value) {
184 drop(v);
185 }
186
187 #[inline]
188 fn dup_func(self, f: &Func) -> Func {
189 f.clone()
190 }
191
192 #[inline]
193 fn free_func(self, f: Func) {
194 drop(f);
195 }
196
197 fn dup_equals(self, e: &Compare) -> Compare {
198 *e
199 }
200
201 fn free_equals(self, _: Compare) {}
202
203 fn call(self, f: &Func, prev: Value) -> Option<Value> {
204 match std::panic::catch_unwind(AssertUnwindSafe(|| f.run(prev))) {
205 Ok(value) => Some(value),
206 Err(panic) => {
207 let message = super::component::panic_message(panic);
208 let graph = unsafe { self.graph() };
210 let owner = graph.owner();
211 graph.data.failures.push((owner, message));
212 None
213 }
214 }
215 }
216
217 #[inline]
218 fn same(self, a: &Value, b: &Value) -> bool {
219 match (a, b) {
220 (Some(a), Some(b)) => Rc::ptr_eq(a, b),
221 (None, None) => true,
222 _ => false,
223 }
224 }
225
226 fn truthy(self, v: &Value) -> bool {
227 v.as_ref()
228 .and_then(|v| v.downcast_ref::<bool>())
229 .copied()
230 .unwrap_or(v.is_some())
231 }
232
233 fn custom_changed(self, e: &Compare, prev: Value, next: &Value) -> bool {
234 match (&prev, next) {
235 (Some(a), Some(b)) => !e(&**a, &**b),
236 (None, None) => false,
237 _ => true,
238 }
239 }
240
241 fn run_cleanup(self, f: Box<dyn FnOnce()>) {
242 if let Err(panic) = std::panic::catch_unwind(AssertUnwindSafe(f)) {
243 let message = super::component::panic_message(panic);
244 let graph = unsafe { self.graph() };
246 let owner = graph.owner();
247 graph.data.failures.push((owner, message));
248 }
249 }
250
251 fn free_cleanup(self, f: Box<dyn FnOnce()>) {
252 drop(f);
253 }
254
255 fn runaway(self) {
256 let graph = unsafe { self.graph() };
258 graph.data.runaway = true;
259 log::error!(target: "js", "potential infinite loop: an effect keeps changing what it reads");
260 }
261}
262
263fn graph<'a>() -> &'a mut r::Graph<Rust> {
264 unsafe { r::Host::graph(Rust) }
267}
268
269pub struct Runtime {
271 graph: Box<UnsafeCell<r::Graph<Rust>>>,
272}
273
274impl Default for Runtime {
275 fn default() -> Self {
276 let mut data = RustData::default();
278 data.ambient.engine_id = Some(super::EngineId::next());
279 Self {
280 graph: Box::new(UnsafeCell::new(r::Graph::new(data))),
281 }
282 }
283}
284
285impl fmt::Debug for Runtime {
286 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
287 f.write_str("Runtime")
288 }
289}
290
291#[must_use = "the runtime is entered while the guard lives"]
294pub struct Entered {
295 previous: *mut r::Graph<Rust>,
296}
297
298impl Drop for Entered {
299 fn drop(&mut self) {
300 CURRENT.with(|c| c.set(self.previous));
301 }
302}
303
304impl Runtime {
305 pub fn enter(&self) -> Entered {
307 let previous = CURRENT.with(|c| c.replace(self.graph.get()));
308 Entered { previous }
309 }
310
311 pub(crate) fn take_failures(&self) -> Vec<(Owner, String)> {
314 let _entered = self.enter();
315 let graph = graph();
316 std::mem::take(&mut graph.data.failures)
317 .into_iter()
318 .map(|(id, message)| (Owner::of(graph, id), message))
319 .collect()
320 }
321
322 pub(crate) fn take_emits(&self) -> Vec<super::once::Emitted> {
324 let _entered = self.enter();
325 std::mem::take(&mut graph().data.emits)
326 }
327
328 #[cfg(test)]
330 pub(crate) fn slots_in_use(&self) -> usize {
331 let _entered = self.enter();
332 graph().slots().0
333 }
334
335 pub(crate) fn free_all(&self) {
337 let _entered = self.enter();
338 graph().free_all(Rust);
339 }
340}
341
342impl Drop for Runtime {
343 fn drop(&mut self) {
344 self.free_all();
347 }
348}
349
350#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
352struct Handle {
353 id: u32,
354 generation: u32,
355}
356
357impl Handle {
358 fn of(graph: &r::Graph<Rust>, id: u32) -> Self {
359 Self {
360 id,
361 generation: graph.generation(id),
362 }
363 }
364
365 fn live(self) -> bool {
366 graph().live(self.id, self.generation, u32::MAX)
367 }
368
369 #[track_caller]
371 fn expect(self, what: &str) -> u32 {
372 assert!(
373 self.live(),
374 "{what} read or written after its owner was disposed"
375 );
376 self.id
377 }
378}
379
380#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
382pub(crate) struct Node(Handle);
383
384impl Node {
385 pub(crate) fn is_live(self) -> bool {
387 self.0.live()
388 }
389
390 #[track_caller]
393 pub(crate) fn with<T: 'static, R>(self, what: &str, f: impl FnOnce(&T) -> R) -> R {
394 read_value(self.0.expect(what), true, f)
395 }
396
397 #[track_caller]
400 pub(crate) fn with_untracked<T: 'static, R>(self, what: &str, f: impl FnOnce(&T) -> R) -> R {
401 read_value(self.0.expect(what), false, f)
402 }
403
404 pub(crate) fn is_outdated(self) -> bool {
407 self.0.live() && graph().outdated(self.0.id)
408 }
409
410 pub(crate) fn bring_up_to_date(self) {
414 if self.is_outdated() {
415 untracked(|| drop(r::read(Rust, self.0.id)));
416 }
417 }
418
419 #[track_caller]
422 pub(crate) fn set<T: 'static>(self, value: T) {
423 r::write(Rust, self.0.expect("a prop"), Some(Rc::new(value)));
424 }
425}
426
427fn read_value<T: 'static, R>(id: u32, tracked: bool, f: impl FnOnce(&T) -> R) -> R {
428 let value = read_any(id, tracked, TypeId::of::<T>());
429 f(unsafe { &*value.as_ptr().cast::<T>() })
432}
433
434#[cfg_attr(target_arch = "wasm32", inline(never))]
437fn read_any(id: u32, tracked: bool, ty: TypeId) -> ReadValue {
438 let value = if tracked {
439 r::read(Rust, id)
440 } else {
441 graph().value(id).clone()
442 };
443 let value = value.expect("a signal always holds a value");
444 assert!(
445 (*value).type_id() == ty,
446 "a handle reads the type it was made with"
447 );
448 ReadValue(ManuallyDrop::new(value))
449}
450
451struct ReadValue(ManuallyDrop<Rc<dyn Any>>);
453
454impl ReadValue {
455 fn as_ptr(&self) -> *const dyn Any {
456 Rc::as_ptr(&self.0)
457 }
458}
459
460impl Drop for ReadValue {
461 #[cfg_attr(target_arch = "wasm32", inline(never))]
462 fn drop(&mut self) {
463 unsafe { ManuallyDrop::drop(&mut self.0) }
465 }
466}
467
468fn compare<T: PartialEq + 'static>(a: &dyn Any, b: &dyn Any) -> bool {
469 match both_of(a, b, TypeId::of::<T>()) {
470 Ok((a, b)) => unsafe { *a.cast::<T>() == *b.cast::<T>() },
472 Err(equal) => equal,
473 }
474}
475
476#[cfg_attr(target_arch = "wasm32", inline(never))]
479fn both_of(a: &dyn Any, b: &dyn Any, ty: TypeId) -> Result<(*const (), *const ()), bool> {
480 match (a.type_id() == ty, b.type_id() == ty) {
481 (true, true) => Ok((
482 (a as *const dyn Any).cast::<()>(),
483 (b as *const dyn Any).cast::<()>(),
484 )),
485 (a, b) => Err(a == b),
486 }
487}
488
489#[derive(Debug, Clone, Copy, PartialEq, Eq)]
491pub enum SignalEquals {
492 Never,
495}
496
497pub struct Signal<T> {
500 handle: Handle,
501 _t: PhantomData<fn() -> T>,
502}
503
504impl<T> Clone for Signal<T> {
505 fn clone(&self) -> Self {
506 *self
507 }
508}
509
510impl<T> Copy for Signal<T> {}
511
512impl<T> PartialEq for Signal<T> {
513 fn eq(&self, other: &Self) -> bool {
514 self.handle == other.handle
515 }
516}
517
518impl<T> fmt::Debug for Signal<T> {
519 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
520 write!(f, "Signal({})", self.handle.id)
521 }
522}
523
524pub fn signal<T: PartialEq + 'static>(value: T) -> Signal<T> {
527 make_signal(value, Equals::Custom(compare::<T>))
528}
529
530pub fn signal_with<T: 'static>(value: T, equals: SignalEquals) -> Signal<T> {
532 match equals {
533 SignalEquals::Never => make_signal(value, Equals::Never),
534 }
535}
536
537pub struct Stored<T: 'static>(Signal<Rc<RefCell<T>>>);
541
542impl<T> Clone for Stored<T> {
543 fn clone(&self) -> Self {
544 *self
545 }
546}
547
548impl<T> Copy for Stored<T> {}
549
550impl<T: 'static> Stored<T> {
551 #[track_caller]
554 pub fn with<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
555 self.0.with_untracked(|cell| f(&mut cell.borrow_mut()))
556 }
557
558 pub fn try_with<R>(&self, f: impl FnOnce(&mut T) -> R) -> Option<R> {
561 self.0.is_live().then(|| self.with(f))
562 }
563
564 #[track_caller]
566 pub fn replace(&self, value: T) -> T {
567 self.with(|v| std::mem::replace(v, value))
568 }
569}
570
571impl<T: Clone + 'static> Stored<T> {
572 #[track_caller]
575 pub fn get(&self) -> T {
576 self.with(|v| v.clone())
577 }
578}
579
580pub fn stored<T: 'static>(value: T) -> Stored<T> {
583 Stored(signal_with(
584 Rc::new(RefCell::new(value)),
585 SignalEquals::Never,
586 ))
587}
588
589pub(crate) struct Kept<T: 'static> {
595 handle: Handle,
596 _t: PhantomData<fn() -> T>,
597}
598
599impl<T> Clone for Kept<T> {
600 fn clone(&self) -> Self {
601 *self
602 }
603}
604
605impl<T> Copy for Kept<T> {}
606
607impl<T> PartialEq for Kept<T> {
608 fn eq(&self, other: &Self) -> bool {
609 self.handle == other.handle
610 }
611}
612
613impl<T: 'static> Kept<T> {
614 pub(crate) fn new(value: Rc<T>) -> Self {
617 Self {
618 handle: owned_signal(Some(value as Rc<dyn Any>), Equals::Never),
619 _t: PhantomData,
620 }
621 }
622
623 pub(crate) fn gone() -> Self {
625 Self {
626 handle: Handle {
627 id: u32::MAX,
628 generation: 0,
629 },
630 _t: PhantomData,
631 }
632 }
633
634 fn raw<R>(self, f: impl FnOnce(&Rc<dyn Any>) -> R) -> Option<R> {
637 let graph = CURRENT.with(Cell::get);
638 if graph.is_null() {
639 return None;
640 }
641 let graph = unsafe { &*graph };
644 let Handle { id, generation } = self.handle;
645 if !graph.live(id, generation, u32::MAX) {
646 return None;
647 }
648 graph.value(id).as_ref().map(f)
649 }
650
651 pub(crate) fn with<R>(self, f: impl FnOnce(&T) -> R) -> Option<R> {
654 self.raw(|v| v.downcast_ref::<T>().map(f)).flatten()
655 }
656
657 pub(crate) fn is_live(self) -> bool {
659 self.raw(|_| ()).is_some()
660 }
661
662 pub(crate) fn get(self) -> Option<Rc<T>> {
664 self.raw(Rc::clone)?.downcast::<T>().ok()
665 }
666}
667
668fn make_signal<T: 'static>(value: T, equals: Equals<Compare>) -> Signal<T> {
669 Signal {
670 handle: owned_signal(Some(Rc::new(value)), equals),
671 _t: PhantomData,
672 }
673}
674
675fn owned_signal(value: Value, equals: Equals<Compare>) -> Handle {
678 let graph = graph();
679 let id = graph.owned_signal(value, equals);
680 let handle = Handle::of(graph, id);
681 if graph.owner() == DISPOSED {
682 r::dispose(Rust, id);
683 }
684 handle
685}
686
687impl<T: 'static> Signal<T> {
688 #[track_caller]
690 pub fn get(&self) -> T
691 where
692 T: Clone,
693 {
694 self.with(T::clone)
695 }
696
697 #[track_caller]
699 pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
700 read_value(self.handle.expect("a signal"), true, f)
701 }
702
703 #[track_caller]
705 pub fn get_untracked(&self) -> T
706 where
707 T: Clone,
708 {
709 self.with_untracked(T::clone)
710 }
711
712 #[track_caller]
714 pub fn with_untracked<R>(&self, f: impl FnOnce(&T) -> R) -> R {
715 read_value(self.handle.expect("a signal"), false, f)
716 }
717
718 pub(crate) fn is_live(&self) -> bool {
720 self.handle.live()
721 }
722
723 pub fn try_get(&self) -> Option<T>
725 where
726 T: Clone,
727 {
728 self.handle.live().then(|| self.get())
729 }
730
731 #[track_caller]
734 pub fn set(&self, value: T) {
735 r::write(Rust, self.handle.expect("a signal"), Some(Rc::new(value)));
736 }
737
738 pub fn try_set(&self, value: T) -> bool {
741 if !self.handle.live() {
742 return false;
743 }
744 r::write(Rust, self.handle.id, Some(Rc::new(value)));
745 true
746 }
747
748 #[track_caller]
752 pub fn update(&self, f: impl FnOnce(&mut T))
753 where
754 T: Clone,
755 {
756 let id = self.handle.expect("a signal");
757 let taken = graph().replace_value(id, None);
758 let shared = taken
759 .and_then(|v| v.downcast::<T>().ok())
760 .expect("a signal holds its type");
761 let mut value = Rc::try_unwrap(shared).unwrap_or_else(|shared| (*shared).clone());
762 f(&mut value);
763 r::write(Rust, id, Some(Rc::new(value)));
764 }
765
766 pub(crate) fn node(&self) -> Node {
768 Node(self.handle)
769 }
770
771 pub fn read_only(&self) -> ReadSignal<T> {
773 ReadSignal {
774 handle: self.handle,
775 _t: PhantomData,
776 }
777 }
778}
779
780pub struct ReadSignal<T> {
782 handle: Handle,
783 _t: PhantomData<fn() -> T>,
784}
785
786impl<T> Clone for ReadSignal<T> {
787 fn clone(&self) -> Self {
788 *self
789 }
790}
791
792impl<T> Copy for ReadSignal<T> {}
793
794impl<T> PartialEq for ReadSignal<T> {
795 fn eq(&self, other: &Self) -> bool {
796 self.handle == other.handle
797 }
798}
799
800impl<T> fmt::Debug for ReadSignal<T> {
801 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
802 write!(f, "ReadSignal({})", self.handle.id)
803 }
804}
805
806pub struct Memo<T> {
810 handle: Handle,
811 _t: PhantomData<fn() -> T>,
812}
813
814impl<T> Clone for Memo<T> {
815 fn clone(&self) -> Self {
816 *self
817 }
818}
819
820impl<T> Copy for Memo<T> {}
821
822impl<T> PartialEq for Memo<T> {
823 fn eq(&self, other: &Self) -> bool {
824 self.handle == other.handle
825 }
826}
827
828impl<T> fmt::Debug for Memo<T> {
829 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
830 write!(f, "Memo({})", self.handle.id)
831 }
832}
833
834pub fn computed<T: PartialEq + 'static>(f: impl Fn() -> T + 'static) -> Memo<T> {
836 let func: Func = Rc::new(move |_| Some(Rc::new(f()) as Rc<dyn Any>));
837 let id = r::memo(Rust, func, None, Equals::Custom(compare::<T>), false);
838 Memo {
839 handle: Handle::of(graph(), id),
840 _t: PhantomData,
841 }
842}
843
844macro_rules! readable {
845 ($name:ident, $what:literal) => {
846 impl<T: 'static> $name<T> {
847 #[track_caller]
849 pub fn get(&self) -> T
850 where
851 T: Clone,
852 {
853 self.with(T::clone)
854 }
855
856 #[track_caller]
858 pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
859 read_value(self.handle.expect($what), true, f)
860 }
861
862 #[track_caller]
864 pub fn get_untracked(&self) -> T
865 where
866 T: Clone,
867 {
868 self.with_untracked(T::clone)
869 }
870
871 #[track_caller]
873 pub fn with_untracked<R>(&self, f: impl FnOnce(&T) -> R) -> R {
874 untracked(|| self.with(f))
876 }
877
878 pub fn try_get(&self) -> Option<T>
880 where
881 T: Clone,
882 {
883 self.handle.live().then(|| self.get())
884 }
885
886 pub(crate) fn node(&self) -> Node {
888 Node(self.handle)
889 }
890 }
891 };
892}
893
894readable!(ReadSignal, "a signal");
895readable!(Memo, "a memo");
896
897pub fn effect(f: impl Fn() + 'static) {
901 let func: Func = Rc::new(move |_| {
902 f();
903 None
904 });
905 r::effect(Rust, Kind::UserEffect, func, None);
906}
907
908pub(crate) fn render_effect(f: impl Fn() + 'static) {
911 let func: Func = Rc::new(move |_| {
912 f();
913 None
914 });
915 r::effect(Rust, Kind::Effect, func, None);
916}
917
918pub fn cleanup(f: impl FnOnce() + 'static) {
922 cleanup_boxed(Box::new(f));
923}
924
925#[cfg_attr(target_arch = "wasm32", inline(never))]
927fn cleanup_boxed(f: Box<dyn FnOnce()>) {
928 if let Err(f) = graph().on_cleanup(f)
929 && graph().owner() == DISPOSED
930 {
931 r::Host::run_cleanup(Rust, f);
932 }
933}
934
935#[cfg(test)]
937pub(crate) fn cleanup_count(owner: Owner) -> usize {
938 owner
939 .0
940 .filter(|h| h.live())
941 .map_or(0, |h| graph().cleanup_count(h.id))
942}
943
944pub(crate) struct RemovableCleanup {
947 owner: Owner,
948 key: *const (),
951 pending: Rc<Cell<bool>>,
952}
953
954struct Pending(Rc<Cell<bool>>);
956
957impl Drop for Pending {
958 fn drop(&mut self) {
959 self.0.set(false);
960 }
961}
962
963pub(crate) fn removable_cleanup(f: impl FnOnce() + 'static) -> Option<RemovableCleanup> {
966 let pending = Rc::new(Cell::new(true));
967 let marker = Pending(pending.clone());
968 let f: Box<dyn FnOnce()> = Box::new(move || {
969 drop(marker);
973 f();
974 });
975 let key = (&*f as *const dyn FnOnce()).cast::<()>();
976 let owner = Owner::current();
977 match graph().on_cleanup(f) {
978 Ok(()) => Some(RemovableCleanup {
979 owner,
980 key,
981 pending,
982 }),
983 Err(f) => {
984 if graph().owner() == DISPOSED {
985 r::Host::run_cleanup(Rust, f);
986 }
987 None
988 }
989 }
990}
991
992impl RemovableCleanup {
993 pub(crate) fn remove(self) {
996 if !self.pending.get() || CURRENT.with(Cell::get).is_null() || !self.owner.is_live() {
997 return;
998 }
999 let Some(h) = self.owner.0 else { return };
1000 let key = self.key;
1001 let removed = graph().remove_cleanup(h.id, |c| {
1002 std::ptr::eq((&**c as *const dyn FnOnce()).cast::<()>(), key)
1003 });
1004 drop(removed);
1006 }
1007}
1008
1009pub fn batch<R>(f: impl FnOnce() -> R) -> R {
1011 erased(f, batch_dyn)
1012}
1013
1014#[inline(never)]
1017fn batch_dyn(f: &mut dyn FnMut()) {
1018 rethrow(r::batch(Rust, shielded(f)))
1019}
1020
1021pub fn untracked<R>(f: impl FnOnce() -> R) -> R {
1023 erased(f, untracked_dyn)
1024}
1025
1026#[inline(never)]
1028fn untracked_dyn(f: &mut dyn FnMut()) {
1029 rethrow(r::untracked(Rust, shielded(f)))
1030}
1031
1032#[inline(always)]
1036fn erased<R>(f: impl FnOnce() -> R, run: impl FnOnce(&mut dyn FnMut())) -> R {
1037 let mut f = Some(f);
1038 let mut result = None;
1039 run(&mut || {
1040 if let Some(f) = f.take() {
1041 result = Some(f());
1042 }
1043 });
1044 result.unwrap_or_else(|| unreachable!("an erased closure did not run"))
1046}
1047
1048fn shielded<R>(f: impl FnOnce() -> R) -> impl FnOnce() -> std::thread::Result<R> {
1053 move || std::panic::catch_unwind(AssertUnwindSafe(f))
1054}
1055
1056fn rethrow<R>(result: std::thread::Result<R>) -> R {
1058 result.unwrap_or_else(|panic| std::panic::resume_unwind(panic))
1059}
1060
1061pub fn provide_context<T: Clone + 'static>(value: T) {
1064 let replaced = graph().provide((TypeId::of::<T>(), Rc::new(value) as Rc<dyn Any>));
1065 drop(replaced);
1066}
1067
1068pub fn use_context<T: Clone + 'static>() -> Option<T> {
1070 let mut frame = graph().context();
1071 while let Some(f) = frame {
1072 if f.data.0 == TypeId::of::<T>() {
1073 return f.data.1.downcast_ref::<T>().cloned();
1074 }
1075 frame = f.parent.clone();
1076 }
1077 None
1078}
1079
1080#[derive(Clone, Copy, PartialEq, Eq, Hash)]
1082pub struct Owner(Option<Handle>);
1083
1084impl fmt::Debug for Owner {
1085 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1086 match self.0 {
1087 Some(h) => write!(f, "Owner({})", h.id),
1088 None => f.write_str("Owner(none)"),
1089 }
1090 }
1091}
1092
1093impl Owner {
1094 pub fn detached() -> Self {
1096 Owner(None)
1097 }
1098
1099 fn of(graph: &r::Graph<Rust>, id: u32) -> Self {
1100 if id == NONE || id == UNOWNED {
1101 Owner(None)
1102 } else if id == DISPOSED {
1103 Owner(Some(Handle { id, generation: 0 }))
1105 } else {
1106 Owner(Some(Handle::of(graph, id)))
1107 }
1108 }
1109
1110 pub fn current() -> Self {
1112 let graph = graph();
1113 Self::of(graph, graph.owner())
1114 }
1115
1116 pub(crate) fn parent(&self) -> Option<Owner> {
1118 let h = self.0?;
1119 if !h.live() {
1120 return None;
1121 }
1122 let graph = graph();
1123 let parent = Self::of(graph, graph.parent(h.id));
1124 parent.0.map(|_| parent)
1125 }
1126
1127 pub fn is_live(&self) -> bool {
1129 self.0.is_some_and(|h| h.live() && !graph().disposed(h.id))
1130 }
1131
1132 pub fn run<R>(&self, f: impl FnOnce() -> R) -> R {
1135 erased(f, |f| self.run_dyn(f))
1136 }
1137
1138 #[inline(never)]
1140 fn run_dyn(&self, f: &mut dyn FnMut()) {
1141 rethrow(r::with_owner(Rust, self.graph_id(), shielded(f)))
1142 }
1143
1144 fn graph_id(&self) -> u32 {
1146 match self.0 {
1147 Some(h) if self.is_live() => h.id,
1148 Some(_) => DISPOSED,
1149 None => NONE,
1150 }
1151 }
1152
1153 pub(crate) fn current_or_detached() -> Self {
1155 if CURRENT.with(Cell::get).is_null() {
1156 Self::detached()
1157 } else {
1158 Self::current()
1159 }
1160 }
1161
1162 pub(crate) fn scope<R>(&self, f: impl FnOnce() -> R) -> R {
1171 struct Restore(r::SavedOwner);
1173 impl Drop for Restore {
1174 fn drop(&mut self) {
1175 graph().leave_owner(self.0);
1176 }
1177 }
1178 let _restore = Restore(graph().enter_owner(self.graph_id()));
1179 f()
1180 }
1181
1182 pub fn dispose(&self) {
1184 if let Some(h) = self.0
1185 && h.live()
1186 {
1187 r::dispose_owner(Rust, h.id);
1188 }
1189 }
1190}
1191
1192pub fn create_root<R>(f: impl FnOnce() -> R) -> (Owner, R) {
1196 let mut owner = Owner::detached();
1197 let r = erased(f, |f| owner = create_root_dyn(f));
1198 (owner, r)
1199}
1200
1201#[inline(never)]
1203fn create_root_dyn(f: &mut dyn FnMut()) -> Owner {
1204 let (id, result) = r::with_root(Rust, shielded(f));
1205 let owner = root_owner(id);
1206 match result {
1207 Ok(()) => owner,
1208 Err(panic) => dispose_and_resume(owner, panic),
1209 }
1210}
1211
1212#[cfg_attr(target_arch = "wasm32", inline(never))]
1214fn root_owner(id: u32) -> Owner {
1215 Owner::of(graph(), id)
1216}
1217
1218#[cold]
1221#[inline(never)]
1222fn dispose_and_resume(owner: Owner, panic: Box<dyn Any + Send>) -> ! {
1223 owner.dispose();
1224 std::panic::resume_unwind(panic)
1225}
1226
1227pub enum Reactive<T> {
1230 Static(T),
1232 Bound(Rc<dyn Fn() -> T>),
1235}
1236
1237impl<T: Clone> Clone for Reactive<T> {
1238 fn clone(&self) -> Self {
1239 match self {
1240 Self::Static(v) => Self::Static(v.clone()),
1241 Self::Bound(f) => Self::Bound(f.clone()),
1242 }
1243 }
1244}
1245
1246impl<T: fmt::Debug> fmt::Debug for Reactive<T> {
1247 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1248 match self {
1249 Self::Static(v) => f.debug_tuple("Static").field(v).finish(),
1250 Self::Bound(_) => f.write_str("Bound"),
1251 }
1252 }
1253}
1254
1255impl<T: Clone> Reactive<T> {
1256 pub fn get(&self) -> T {
1259 match self {
1260 Self::Static(v) => v.clone(),
1261 Self::Bound(f) => f(),
1262 }
1263 }
1264}
1265
1266impl<T: 'static> Reactive<T> {
1267 pub fn map<U: 'static>(self, f: impl Fn(T) -> U + 'static) -> Reactive<U> {
1269 match self {
1270 Self::Static(v) => Reactive::Static(f(v)),
1271 Self::Bound(g) => Reactive::Bound(Rc::new(move || f(g()))),
1272 }
1273 }
1274}
1275
1276pub trait IntoReactive<T> {
1280 fn into_reactive(self) -> Reactive<T>;
1282}
1283
1284impl<T> IntoReactive<T> for Reactive<T> {
1285 fn into_reactive(self) -> Reactive<T> {
1286 self
1287 }
1288}
1289
1290impl<T: 'static, U: Into<T>, F: Fn() -> U + 'static> IntoReactive<T> for F {
1291 fn into_reactive(self) -> Reactive<T> {
1292 Reactive::Bound(Rc::new(move || self().into()))
1293 }
1294}
1295
1296macro_rules! bound_handles {
1297 ($($handle:ident),*) => {$(
1298 impl<T: Clone + 'static> IntoReactive<T> for $handle<T> {
1299 fn into_reactive(self) -> Reactive<T> {
1300 Reactive::Bound(Rc::new(move || self.get()))
1301 }
1302 }
1303 )*};
1304}
1305
1306bound_handles!(Signal, Memo, ReadSignal);
1307
1308#[macro_export]
1314macro_rules! static_reactive {
1315 ($target:ty: $($source:ty),* $(,)?) => {$(
1316 impl $crate::element::IntoReactive<$target> for $source {
1317 fn into_reactive(self) -> $crate::element::Reactive<$target> {
1318 $crate::element::Reactive::Static(<$target>::from(self))
1319 }
1320 }
1321 )*};
1322}
1323
1324static_reactive!(bool: bool);
1325static_reactive!(f32: f32);
1326static_reactive!(f64: f64);
1327static_reactive!(u32: u32);
1328static_reactive!(i32: i32);
1329static_reactive!(usize: usize);
1330static_reactive!(u8: u8);
1331static_reactive!(u64: u64);
1332static_reactive!(u128: u128);
1333static_reactive!(i8: i8);
1334static_reactive!(i64: i64);
1335static_reactive!(i128: i128);
1336static_reactive!(isize: isize);
1337static_reactive!((u32, u32): (u32, u32));
1338static_reactive!(String: String);
1339static_reactive!(Vec<String>: Vec<String>);
1340static_reactive!(std::time::Duration: std::time::Duration);
1341
1342impl IntoReactive<String> for &str {
1343 fn into_reactive(self) -> Reactive<String> {
1344 Reactive::Static(self.to_owned())
1345 }
1346}
1347
1348impl IntoReactive<String> for &String {
1350 fn into_reactive(self) -> Reactive<String> {
1351 Reactive::Static(self.clone())
1352 }
1353}
1354static_reactive!(super::SharedString: super::SharedString, String, &'static str);
1355
1356macro_rules! some_shared_string {
1358 ($($source:ty),*) => {$(
1359 impl IntoReactive<Option<super::SharedString>> for $source {
1360 fn into_reactive(self) -> Reactive<Option<super::SharedString>> {
1361 Reactive::Static(Some(self.into()))
1362 }
1363 }
1364 )*};
1365}
1366
1367some_shared_string!(super::SharedString, String, &'static str);
1368
1369impl<T: 'static> IntoReactive<Option<T>> for Option<T> {
1370 fn into_reactive(self) -> Reactive<Option<T>> {
1371 Reactive::Static(self)
1372 }
1373}
1374
1375#[cfg(test)]
1376mod tests;