1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
use crate::{
diagnostics,
diagnostics::*,
node::NodeId,
runtime::{with_runtime, Runtime},
SignalGet, SignalSet, SignalUpdate,
};
/// Reactive Trigger, notifies reactive code to rerun.
///
/// See [`create_trigger`] for more.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Trigger {
pub(crate) id: NodeId,
#[cfg(debug_assertions)]
pub(crate) defined_at: &'static std::panic::Location<'static>,
}
impl Trigger {
/// Notifies any reactive code where this trigger is tracked to rerun.
///
/// ## Panics
/// Panics if there is no current reactive runtime, or if the
/// trigger has been disposed.
pub fn notify(&self) {
assert!(self.try_notify(), "Trigger::notify(): runtime not alive")
}
/// Attempts to notify any reactive code where this trigger is tracked to rerun.
///
/// Returns `false` if there is no current reactive runtime.
pub fn try_notify(&self) -> bool {
with_runtime(|runtime| {
runtime.mark_dirty(self.id);
runtime.run_effects();
})
.is_ok()
}
/// Subscribes the running effect to this trigger.
///
/// ## Panics
/// Panics if there is no current reactive runtime, or if the
/// trigger has been disposed.
pub fn track(&self) {
assert!(self.try_track(), "Trigger::track(): runtime not alive")
}
/// Attempts to subscribe the running effect to this trigger, returning
/// `false` if there is no current reactive runtime.
pub fn try_track(&self) -> bool {
let diagnostics = diagnostics!(self);
with_runtime(|runtime| {
self.id.subscribe(runtime, diagnostics);
})
.is_ok()
}
}
/// Creates a [`Trigger`](crate::Trigger), a kind of reactive primitive.
///
/// A trigger is a data-less signal with the sole purpose
/// of notifying other reactive code of a change. This can be useful
/// for when using external data not stored in signals, for example.
/// ```
/// # use leptos_reactive::*;
/// # let runtime = create_runtime();
/// use std::{cell::RefCell, fmt::Write, rc::Rc};
///
/// let external_data = Rc::new(RefCell::new(1));
/// let output = Rc::new(RefCell::new(String::new()));
///
/// let rerun_on_data = create_trigger();
///
/// let o = output.clone();
/// let e = external_data.clone();
/// create_effect(move |_| {
/// // can be `rerun_on_data()` on nightly
/// rerun_on_data.track();
/// write!(o.borrow_mut(), "{}", *e.borrow());
/// *e.borrow_mut() += 1;
/// });
/// # if !cfg!(feature = "ssr") {
/// assert_eq!(*output.borrow(), "1");
///
/// rerun_on_data.notify(); // reruns the above effect
///
/// assert_eq!(*output.borrow(), "12");
/// # }
/// # runtime.dispose();
/// ```
#[cfg_attr(debug_assertions, instrument(level = "trace", skip_all,))]
#[track_caller]
pub fn create_trigger() -> Trigger {
Runtime::current().create_trigger()
}
impl SignalGet for Trigger {
type Value = ();
#[cfg_attr(
debug_assertions,
instrument(
level = "trace",
name = "Trigger::get()",
skip_all,
fields(
id = ?self.id,
defined_at = %self.defined_at
)
)
)]
#[track_caller]
#[inline(always)]
fn get(&self) {
self.track()
}
#[cfg_attr(
debug_assertions,
instrument(
level = "trace",
name = "Trigger::try_get()",
skip_all,
fields(
id = ?self.id,
defined_at = %self.defined_at
)
)
)]
#[inline(always)]
fn try_get(&self) -> Option<()> {
self.try_track().then_some(())
}
}
impl SignalUpdate for Trigger {
type Value = ();
#[cfg_attr(
debug_assertions,
instrument(
name = "Trigger::update()",
level = "trace",
skip_all,
fields(
id = ?self.id,
defined_at = %self.defined_at
)
)
)]
#[inline(always)]
fn update(&self, f: impl FnOnce(&mut ())) {
self.try_update(f).expect("runtime to be alive")
}
#[cfg_attr(
debug_assertions,
instrument(
name = "Trigger::try_update()",
level = "trace",
skip_all,
fields(
id = ?self.id,
defined_at = %self.defined_at
)
)
)]
#[inline(always)]
fn try_update<O>(&self, f: impl FnOnce(&mut ()) -> O) -> Option<O> {
// run callback with runtime before dirtying the trigger,
// consistent with signals.
with_runtime(|runtime| {
let res = f(&mut ());
runtime.mark_dirty(self.id);
runtime.run_effects();
Some(res)
})
.ok()
.flatten()
}
}
impl SignalSet for Trigger {
type Value = ();
#[cfg_attr(
debug_assertions,
instrument(
level = "trace",
name = "Trigger::set()",
skip_all,
fields(
id = ?self.id,
defined_at = %self.defined_at
)
)
)]
#[inline(always)]
fn set(&self, _: ()) {
self.notify();
}
#[cfg_attr(
debug_assertions,
instrument(
level = "trace",
name = "Trigger::try_set()",
skip_all,
fields(
id = ?self.id,
defined_at = %self.defined_at
)
)
)]
#[inline(always)]
fn try_set(&self, _: ()) -> Option<()> {
self.try_notify().then_some(())
}
}
#[cfg(feature = "nightly")]
impl FnOnce<()> for Trigger {
type Output = ();
#[inline(always)]
extern "rust-call" fn call_once(self, _args: ()) -> Self::Output {
self.track()
}
}
#[cfg(feature = "nightly")]
impl FnMut<()> for Trigger {
#[inline(always)]
extern "rust-call" fn call_mut(&mut self, _args: ()) -> Self::Output {
self.track()
}
}
#[cfg(feature = "nightly")]
impl Fn<()> for Trigger {
#[inline(always)]
extern "rust-call" fn call(&self, _args: ()) -> Self::Output {
self.track()
}
}