Skip to main content

lexical_ui/extension/
signals.rs

1//! `signals.ts`: the reactive core `@lexical/extension` re-exports from
2//! `@preact/signals-core` 1.14.4 (MIT, Copyright (c) 2022-present Preact
3//! Team): `signal`, `computed`, `effect`, `batch` and `untracked`, ported
4//! without a dependency. The algorithm is preact's: versioned dependency
5//! nodes, lazily recomputed computeds, batched effects, and the batch
6//! snapshots that keep a value set back to what it was inside a batch from
7//! rerunning anything. Its linked lists are vectors kept in the same order,
8//! so targets are notified and effects run in preact's order. The state is
9//! per thread, as signals are neither `Send` nor `Sync`.
10//!
11//! Where it differs, from Rust: a value is compared with `==`
12//! ([`SignalValue`]), where JS's `!==` compares objects by identity (a type
13//! whose `==` is `Rc::ptr_eq` compares as JS does); effect and computed bodies can't throw, so
14//! preact's error paths (`HAS_ERROR`, rethrowing after a batch) have no
15//! counterpart, and a cycle panics with preact's message. `name`, `action`,
16//! `createModel` and `Symbol.dispose` aren't ported.
17
18use crate::{EditorState, Unregister};
19use std::any::Any;
20use std::cell::{Cell, RefCell};
21use std::marker::PhantomData;
22use std::rc::{Rc, Weak};
23
24const RUNNING: u8 = 1 << 0;
25const NOTIFIED: u8 = 1 << 1;
26const OUTDATED: u8 = 1 << 2;
27const DISPOSED: u8 = 1 << 3;
28const TRACKING: u8 = 1 << 5;
29
30type Value = Rc<dyn Any>;
31type SourceCallback = Option<Rc<dyn Fn(&Rc<Source>)>>;
32type EffectFn = Rc<dyn Fn() -> Option<Unregister>>;
33/// `SignalOptions`' `watched` and `unwatched`.
34pub type SignalCallback<T> = Option<Rc<dyn Fn(&Signal<T>)>>;
35
36/// A dependency edge (preact's `Node`): `target` read `source` at
37/// `version`.
38struct Node {
39    source: Rc<Source>,
40    target: Target,
41    version: Cell<i64>,
42    rollback_node: RefCell<Option<Rc<Node>>>,
43}
44
45/// What reads signals: a computed (weakly, as it owns its sources) or an
46/// effect.
47#[derive(Clone)]
48enum Target {
49    Computed(Weak<Source>),
50    Effect(Rc<EffectInner>),
51}
52
53impl Target {
54    fn is(&self, other: &Target) -> bool {
55        match (self, other) {
56            (Target::Computed(a), Target::Computed(b)) => a.ptr_eq(b),
57            (Target::Effect(a), Target::Effect(b)) => Rc::ptr_eq(a, b),
58            _ => false,
59        }
60    }
61
62    fn flags(&self) -> u8 {
63        match self {
64            Target::Computed(c) => c
65                .upgrade()
66                .map_or(0, |c| c.computed.as_ref().expect("computed").flags.get()),
67            Target::Effect(e) => e.flags.get(),
68        }
69    }
70
71    fn with_sources<R>(&self, f: impl FnOnce(&RefCell<Vec<Rc<Node>>>) -> R) -> Option<R> {
72        match self {
73            Target::Computed(c) => {
74                let c = c.upgrade()?;
75                Some(f(&c.computed.as_ref().expect("computed").sources))
76            }
77            Target::Effect(e) => Some(f(&e.sources)),
78        }
79    }
80
81    fn notify(&self) {
82        match self {
83            Target::Computed(c) => {
84                if let Some(c) = c.upgrade() {
85                    computed_notify(&c);
86                }
87            }
88            Target::Effect(e) => effect_notify(e),
89        }
90    }
91}
92
93/// A signal or a computed (preact's `Signal`, which `Computed` extends).
94struct Source {
95    value: RefCell<Option<Value>>,
96    version: Cell<i64>,
97    node: RefCell<Option<Rc<Node>>>,
98    /// `_targets`, head first: the newest subscriber is notified first.
99    targets: RefCell<Vec<Rc<Node>>>,
100    batch_snapshot_version: Cell<u64>,
101    watched: SourceCallback,
102    unwatched: SourceCallback,
103    /// JS's `===` on two values of this source.
104    same: fn(&dyn Any, &dyn Any) -> bool,
105    computed: Option<ComputedData>,
106}
107
108struct ComputedData {
109    func: Box<dyn Fn() -> Value>,
110    sources: RefCell<Vec<Rc<Node>>>,
111    global_version: Cell<u64>,
112    flags: Cell<u8>,
113}
114
115struct EffectInner {
116    func: RefCell<Option<EffectFn>>,
117    cleanup: RefCell<Option<Unregister>>,
118    sources: RefCell<Vec<Rc<Node>>>,
119    flags: Cell<u8>,
120}
121
122struct BatchSnapshot {
123    source: Rc<Source>,
124    value: Option<Value>,
125    version: i64,
126}
127
128/// signals-core's module-scope variables.
129#[derive(Default)]
130struct State {
131    eval_context: RefCell<Option<Target>>,
132    /// `batchedEffect`, in notification order; preact runs the newest first.
133    batched_effects: RefCell<Vec<Rc<EffectInner>>>,
134    batch_depth: Cell<u32>,
135    batch_iteration: Cell<u32>,
136    batch_snapshot_version: Cell<u64>,
137    current_batch_snapshot_version: Cell<u64>,
138    /// `batchSnapshots`, head first.
139    batch_snapshots: RefCell<Vec<BatchSnapshot>>,
140    global_version: Cell<u64>,
141}
142
143thread_local! {
144    static STATE: State = State::default();
145}
146
147fn with_state<R>(f: impl FnOnce(&State) -> R) -> R {
148    STATE.with(f)
149}
150
151/// A value a signal can hold: JS's `===` on it is [`is_same`](Self::is_same),
152/// which is `==` for any `PartialEq` value. An [`EditorState`] is the same
153/// only as itself, as JS compares the objects.
154pub trait SignalValue: Clone + 'static {
155    fn is_same(&self, other: &Self) -> bool;
156}
157
158impl<T: Clone + PartialEq + 'static> SignalValue for T {
159    fn is_same(&self, other: &Self) -> bool {
160        self == other
161    }
162}
163
164impl SignalValue for EditorState {
165    fn is_same(&self, other: &Self) -> bool {
166        self.ptr_eq(other)
167    }
168}
169
170fn same_value<T: SignalValue>(a: &dyn Any, b: &dyn Any) -> bool {
171    match (a.downcast_ref::<T>(), b.downcast_ref::<T>()) {
172        (Some(a), Some(b)) => a.is_same(b),
173        _ => false,
174    }
175}
176
177fn values_same(source: &Source, a: &Option<Value>, b: &Option<Value>) -> bool {
178    match (a, b) {
179        (Some(a), Some(b)) => (source.same)(a.as_ref(), b.as_ref()),
180        (None, None) => true,
181        _ => false,
182    }
183}
184
185fn start_batch() {
186    with_state(|s| s.batch_depth.set(s.batch_depth.get() + 1));
187}
188
189fn end_batch() {
190    if with_state(|s| {
191        let depth = s.batch_depth.get();
192        if depth > 1 {
193            s.batch_depth.set(depth - 1);
194        }
195        depth > 1
196    }) {
197        return;
198    }
199    reconcile_batch_snapshots();
200    loop {
201        let effects = with_state(|s| std::mem::take(&mut *s.batched_effects.borrow_mut()));
202        if effects.is_empty() {
203            break;
204        }
205        with_state(|s| s.batch_iteration.set(s.batch_iteration.get() + 1));
206        for effect in effects.iter().rev() {
207            effect.flags.set(effect.flags.get() & !NOTIFIED);
208            if effect.flags.get() & DISPOSED == 0
209                && needs_to_recompute(&Target::Effect(effect.clone()))
210            {
211                effect_callback(effect);
212            }
213        }
214    }
215    with_state(|s| {
216        s.batch_iteration.set(0);
217        s.batch_depth.set(s.batch_depth.get() - 1);
218    });
219}
220
221/// `batch(fn)`: runs `fn`, and the effects the signals it sets trigger once,
222/// when it returns (or when the outermost batch does).
223pub fn batch<R>(f: impl FnOnce() -> R) -> R {
224    if with_state(|s| s.batch_depth.get() > 0) {
225        return f();
226    }
227    with_state(|s| {
228        let version = s.batch_snapshot_version.get() + 1;
229        s.batch_snapshot_version.set(version);
230        s.current_batch_snapshot_version.set(version);
231    });
232    start_batch();
233    let result = f();
234    end_batch();
235    result
236}
237
238/// Restores the evaluation context when dropped.
239struct ContextGuard(Option<Target>);
240
241impl Drop for ContextGuard {
242    fn drop(&mut self) {
243        let prev = self.0.take();
244        with_state(|s| *s.eval_context.borrow_mut() = prev);
245    }
246}
247
248fn set_eval_context(target: Option<Target>) -> Option<Target> {
249    with_state(|s| std::mem::replace(&mut *s.eval_context.borrow_mut(), target))
250}
251
252/// `untracked(fn)`: runs `fn` without subscribing the running computed or
253/// effect to the signals it reads.
254pub fn untracked<R>(f: impl FnOnce() -> R) -> R {
255    let _guard = ContextGuard(set_eval_context(None));
256    f()
257}
258
259fn record_batch_snapshot(source: &Rc<Source>) {
260    with_state(|s| {
261        if s.batch_depth.get() == 0 || s.batch_iteration.get() != 0 {
262            return;
263        }
264        let current = s.current_batch_snapshot_version.get();
265        if source.batch_snapshot_version.get() != current {
266            source.batch_snapshot_version.set(current);
267            s.batch_snapshots.borrow_mut().insert(
268                0,
269                BatchSnapshot {
270                    source: source.clone(),
271                    value: source.value.borrow().clone(),
272                    version: source.version.get(),
273                },
274            );
275        }
276    });
277}
278
279fn reconcile_batch_snapshots() {
280    let snapshots = with_state(|s| std::mem::take(&mut *s.batch_snapshots.borrow_mut()));
281    for snapshot in snapshots {
282        let source = &snapshot.source;
283        if values_same(source, &source.value.borrow(), &snapshot.value) {
284            for node in source.targets.borrow().iter() {
285                if node.version.get() == snapshot.version {
286                    node.version.set(source.version.get());
287                }
288            }
289        }
290    }
291}
292
293fn add_dependency(source: &Rc<Source>) -> Option<Rc<Node>> {
294    let context = with_state(|s| s.eval_context.borrow().clone())?;
295    let existing = source.node.borrow().clone();
296    match existing {
297        Some(node) if node.target.is(&context) => {
298            if node.version.get() != -1 {
299                return None;
300            }
301            node.version.set(0);
302            // Moves the node to the end of the sources, so they stay in the
303            // order they were first read.
304            context.with_sources(|sources| {
305                let mut sources = sources.borrow_mut();
306                if let Some(i) = sources.iter().position(|n| Rc::ptr_eq(n, &node))
307                    && i != sources.len() - 1
308                {
309                    let node = sources.remove(i);
310                    sources.push(node);
311                }
312            });
313            Some(node)
314        }
315        existing => {
316            let node = Rc::new(Node {
317                source: source.clone(),
318                target: context.clone(),
319                version: Cell::new(0),
320                rollback_node: RefCell::new(existing),
321            });
322            context.with_sources(|sources| sources.borrow_mut().push(node.clone()));
323            *source.node.borrow_mut() = Some(node.clone());
324            if context.flags() & TRACKING != 0 {
325                subscribe(source, &node);
326            }
327            Some(node)
328        }
329    }
330}
331
332fn subscribe(source: &Rc<Source>, node: &Rc<Node>) {
333    if let Some(computed) = &source.computed
334        && source.targets.borrow().is_empty()
335    {
336        computed
337            .flags
338            .set(computed.flags.get() | OUTDATED | TRACKING);
339        let sources = computed.sources.borrow().clone();
340        for n in &sources {
341            subscribe(&n.source, n);
342        }
343    }
344    let was_empty = {
345        let mut targets = source.targets.borrow_mut();
346        if targets.iter().any(|n| Rc::ptr_eq(n, node)) {
347            return;
348        }
349        let was_empty = targets.is_empty();
350        targets.insert(0, node.clone());
351        was_empty
352    };
353    if was_empty && let Some(watched) = source.watched.clone() {
354        untracked(|| watched(source));
355    }
356}
357
358fn unsubscribe(source: &Rc<Source>, node: &Rc<Node>) {
359    if source.targets.borrow().is_empty() {
360        return;
361    }
362    let removed_last = {
363        let mut targets = source.targets.borrow_mut();
364        match targets.iter().position(|n| Rc::ptr_eq(n, node)) {
365            Some(i) => {
366                targets.remove(i);
367                targets.is_empty()
368            }
369            None => false,
370        }
371    };
372    if removed_last && let Some(unwatched) = source.unwatched.clone() {
373        untracked(|| unwatched(source));
374    }
375    // `Computed._unsubscribe`: a computed nothing reads stops tracking its
376    // sources.
377    if let Some(computed) = &source.computed
378        && source.targets.borrow().is_empty()
379    {
380        computed.flags.set(computed.flags.get() & !TRACKING);
381        let sources = computed.sources.borrow().clone();
382        for n in &sources {
383            unsubscribe(&n.source, n);
384        }
385    }
386}
387
388fn refresh(source: &Rc<Source>) -> bool {
389    match &source.computed {
390        None => true,
391        Some(_) => computed_refresh(source),
392    }
393}
394
395fn needs_to_recompute(target: &Target) -> bool {
396    let sources = target
397        .with_sources(|s| s.borrow().clone())
398        .unwrap_or_default();
399    for node in &sources {
400        if node.source.version.get() != node.version.get()
401            || !refresh(&node.source)
402            || node.source.version.get() != node.version.get()
403        {
404            return true;
405        }
406    }
407    false
408}
409
410fn prepare_sources(target: &Target) {
411    target.with_sources(|sources| {
412        for node in sources.borrow().iter() {
413            if let Some(rollback) = node.source.node.borrow().clone() {
414                *node.rollback_node.borrow_mut() = Some(rollback);
415            }
416            *node.source.node.borrow_mut() = Some(node.clone());
417            node.version.set(-1);
418        }
419    });
420}
421
422fn cleanup_sources(target: &Target) {
423    let sources = target
424        .with_sources(|s| s.borrow().clone())
425        .unwrap_or_default();
426    let mut kept = Vec::new();
427    for node in sources.iter().rev() {
428        if node.version.get() == -1 {
429            unsubscribe(&node.source, node);
430        } else {
431            kept.push(node.clone());
432        }
433        let rollback = node.rollback_node.borrow_mut().take();
434        *node.source.node.borrow_mut() = rollback;
435    }
436    kept.reverse();
437    target.with_sources(|s| *s.borrow_mut() = kept);
438}
439
440fn computed_refresh(source: &Rc<Source>) -> bool {
441    let computed = source.computed.as_ref().expect("computed");
442    let flags = &computed.flags;
443    flags.set(flags.get() & !NOTIFIED);
444    if flags.get() & RUNNING != 0 {
445        return false;
446    }
447    if flags.get() & (OUTDATED | TRACKING) == TRACKING {
448        return true;
449    }
450    flags.set(flags.get() & !OUTDATED);
451    let global_version = with_state(|s| s.global_version.get());
452    if computed.global_version.get() == global_version {
453        return true;
454    }
455    computed.global_version.set(global_version);
456    flags.set(flags.get() | RUNNING);
457    let target = Target::Computed(Rc::downgrade(source));
458    if source.version.get() > 0 && !needs_to_recompute(&target) {
459        flags.set(flags.get() & !RUNNING);
460        return true;
461    }
462    prepare_sources(&target);
463    let prev = set_eval_context(Some(target.clone()));
464    let value = Some((computed.func)());
465    if source.version.get() == 0 || !values_same(source, &source.value.borrow(), &value) {
466        *source.value.borrow_mut() = value;
467        source.version.set(source.version.get() + 1);
468    }
469    set_eval_context(prev);
470    cleanup_sources(&target);
471    flags.set(flags.get() & !RUNNING);
472    true
473}
474
475fn computed_notify(source: &Rc<Source>) {
476    let computed = source.computed.as_ref().expect("computed");
477    if computed.flags.get() & NOTIFIED == 0 {
478        computed
479            .flags
480            .set(computed.flags.get() | OUTDATED | NOTIFIED);
481        let targets = source.targets.borrow().clone();
482        for node in &targets {
483            node.target.notify();
484        }
485    }
486}
487
488fn effect_notify(effect: &Rc<EffectInner>) {
489    if effect.flags.get() & NOTIFIED == 0 {
490        effect.flags.set(effect.flags.get() | NOTIFIED);
491        with_state(|s| s.batched_effects.borrow_mut().push(effect.clone()));
492    }
493}
494
495fn effect_callback(effect: &Rc<EffectInner>) {
496    let prev = effect_start(effect);
497    if effect.flags.get() & DISPOSED == 0 {
498        let func = effect.func.borrow().clone();
499        if let Some(func) = func
500            && let Some(cleanup) = func()
501        {
502            *effect.cleanup.borrow_mut() = Some(cleanup);
503        }
504    }
505    effect_end(effect, prev);
506}
507
508fn effect_start(effect: &Rc<EffectInner>) -> Option<Target> {
509    if effect.flags.get() & RUNNING != 0 {
510        panic!("Cycle detected");
511    }
512    effect.flags.set((effect.flags.get() | RUNNING) & !DISPOSED);
513    cleanup_effect(effect);
514    let target = Target::Effect(effect.clone());
515    prepare_sources(&target);
516    start_batch();
517    set_eval_context(Some(target))
518}
519
520fn effect_end(effect: &Rc<EffectInner>, prev: Option<Target>) {
521    let target = Target::Effect(effect.clone());
522    let current = with_state(|s| s.eval_context.borrow().clone());
523    assert!(
524        current.is_some_and(|c| c.is(&target)),
525        "Out-of-order effect"
526    );
527    cleanup_sources(&target);
528    set_eval_context(prev);
529    effect.flags.set(effect.flags.get() & !RUNNING);
530    if effect.flags.get() & DISPOSED != 0 {
531        dispose_effect(effect);
532    }
533    end_batch();
534}
535
536fn cleanup_effect(effect: &Rc<EffectInner>) {
537    let cleanup = effect.cleanup.borrow_mut().take();
538    if let Some(cleanup) = cleanup {
539        start_batch();
540        let prev = set_eval_context(None);
541        cleanup();
542        set_eval_context(prev);
543        end_batch();
544    }
545}
546
547fn dispose_effect(effect: &Rc<EffectInner>) {
548    let sources = std::mem::take(&mut *effect.sources.borrow_mut());
549    for node in &sources {
550        unsubscribe(&node.source, node);
551    }
552    *effect.func.borrow_mut() = None;
553    cleanup_effect(effect);
554}
555
556fn effect_dispose(effect: &Rc<EffectInner>) {
557    effect.flags.set(effect.flags.get() | DISPOSED);
558    if effect.flags.get() & RUNNING == 0 {
559        dispose_effect(effect);
560    }
561}
562
563/// `SignalOptions`: callbacks for when the signal gains its first
564/// subscriber (`watched`) and loses its last (`unwatched`).
565pub struct SignalOptions<T> {
566    pub watched: SignalCallback<T>,
567    pub unwatched: SignalCallback<T>,
568}
569
570impl<T> Default for SignalOptions<T> {
571    fn default() -> Self {
572        Self {
573            watched: None,
574            unwatched: None,
575        }
576    }
577}
578
579/// `Signal`: a value that the computeds and effects reading it track.
580/// Cloning it shares the signal.
581pub struct Signal<T>(Rc<Source>, PhantomData<T>);
582
583impl<T> Clone for Signal<T> {
584    fn clone(&self) -> Self {
585        Signal(self.0.clone(), PhantomData)
586    }
587}
588
589/// `ReadonlySignal`: a signal that can only be read, such as a
590/// [`computed`].
591pub struct ReadonlySignal<T>(Rc<Source>, PhantomData<T>);
592
593impl<T> Clone for ReadonlySignal<T> {
594    fn clone(&self) -> Self {
595        ReadonlySignal(self.0.clone(), PhantomData)
596    }
597}
598
599fn read_value<T: Clone + 'static>(source: &Rc<Source>) -> T {
600    source
601        .value
602        .borrow()
603        .as_ref()
604        .and_then(|v| v.downcast_ref::<T>())
605        .cloned()
606        .expect("a signal holds a value of its type")
607}
608
609fn source_value<T: Clone + 'static>(source: &Rc<Source>) -> T {
610    if let Some(computed) = &source.computed {
611        if computed.flags.get() & RUNNING != 0 {
612            panic!("Cycle detected");
613        }
614        let node = add_dependency(source);
615        computed_refresh(source);
616        if let Some(node) = node {
617            node.version.set(source.version.get());
618        }
619    } else if let Some(node) = add_dependency(source) {
620        node.version.set(source.version.get());
621    }
622    read_value(source)
623}
624
625/// `signal(value)`.
626pub fn signal<T: SignalValue>(value: T) -> Signal<T> {
627    signal_with_options(value, SignalOptions::default())
628}
629
630/// `signal(value, options)`.
631pub fn signal_with_options<T: SignalValue>(value: T, options: SignalOptions<T>) -> Signal<T> {
632    let typed = |f: SignalCallback<T>| -> SourceCallback {
633        f.map(|f| Rc::new(move |s: &Rc<Source>| f(&Signal(s.clone(), PhantomData))) as _)
634    };
635    Signal(
636        Rc::new(Source {
637            value: RefCell::new(Some(Rc::new(value))),
638            version: Cell::new(0),
639            node: RefCell::new(None),
640            targets: RefCell::new(Vec::new()),
641            batch_snapshot_version: Cell::new(0),
642            watched: typed(options.watched),
643            unwatched: typed(options.unwatched),
644            same: same_value::<T>,
645            computed: None,
646        }),
647        PhantomData,
648    )
649}
650
651impl<T: SignalValue> Signal<T> {
652    /// `signal.value`: the value, subscribing the running computed or effect
653    /// to the signal.
654    pub fn value(&self) -> T {
655        source_value(&self.0)
656    }
657
658    /// `signal.value = value`: sets the value and, unless it is the same
659    /// (`==`), runs the effects that depend on it, at the end of the batch
660    /// if one is running.
661    pub fn set_value(&self, value: T) {
662        let source = &self.0;
663        if source
664            .value
665            .borrow()
666            .as_ref()
667            .and_then(|v| v.downcast_ref::<T>())
668            .is_some_and(|v| v.is_same(&value))
669        {
670            return;
671        }
672        if with_state(|s| s.batch_iteration.get()) > 100 {
673            panic!("Cycle detected");
674        }
675        record_batch_snapshot(source);
676        *source.value.borrow_mut() = Some(Rc::new(value));
677        source.version.set(source.version.get() + 1);
678        with_state(|s| s.global_version.set(s.global_version.get() + 1));
679        start_batch();
680        let targets = source.targets.borrow().clone();
681        for node in &targets {
682            node.target.notify();
683        }
684        end_batch();
685    }
686
687    /// `signal.peek()`: the value, without subscribing.
688    pub fn peek(&self) -> T {
689        untracked(|| self.value())
690    }
691
692    /// `signal.subscribe(fn)`: calls `fn` with the value now and after each
693    /// change; returns the function that stops it.
694    pub fn subscribe(&self, f: impl Fn(T) + 'static) -> Unregister {
695        let this = self.clone();
696        effect(move || {
697            let value = this.value();
698            untracked(|| f(value));
699            None
700        })
701    }
702
703    /// This signal, read-only.
704    pub fn as_readonly(&self) -> ReadonlySignal<T> {
705        ReadonlySignal(self.0.clone(), PhantomData)
706    }
707}
708
709impl<T: Clone + 'static> ReadonlySignal<T> {
710    /// `signal.value`.
711    pub fn value(&self) -> T {
712        source_value(&self.0)
713    }
714
715    /// `signal.peek()`.
716    pub fn peek(&self) -> T {
717        untracked(|| self.value())
718    }
719}
720
721/// `computed(fn)`: a signal whose value `fn` computes from the signals it
722/// reads, lazily, again only after one of them changed.
723pub fn computed<T: SignalValue>(f: impl Fn() -> T + 'static) -> ReadonlySignal<T> {
724    let global_version = with_state(|s| s.global_version.get());
725    ReadonlySignal(
726        Rc::new(Source {
727            value: RefCell::new(None),
728            version: Cell::new(0),
729            node: RefCell::new(None),
730            targets: RefCell::new(Vec::new()),
731            batch_snapshot_version: Cell::new(0),
732            watched: None,
733            unwatched: None,
734            same: same_value::<T>,
735            computed: Some(ComputedData {
736                func: Box::new(move || Rc::new(f()) as Value),
737                sources: RefCell::new(Vec::new()),
738                global_version: Cell::new(global_version.wrapping_sub(1)),
739                flags: Cell::new(OUTDATED),
740            }),
741        }),
742        PhantomData,
743    )
744}
745
746/// `effect(fn)`: runs `fn` now and again after a signal it read changes.
747/// The clean-up `fn` returns runs before its next run and when it is
748/// disposed. Returns the function that disposes it.
749pub fn effect(f: impl Fn() -> Option<Unregister> + 'static) -> Unregister {
750    let effect = Rc::new(EffectInner {
751        func: RefCell::new(Some(Rc::new(f))),
752        cleanup: RefCell::new(None),
753        sources: RefCell::new(Vec::new()),
754        flags: Cell::new(TRACKING),
755    });
756    effect_callback(&effect);
757    Box::new(move || effect_dispose(&effect))
758}