euv_core/reactive/schedule/fn.rs
1use crate::*;
2
3/// Invokes `callback` with a reference to the persistent dispatch `Function`.
4///
5/// The dispatch closure is created once per thread and stored in
6/// `DISPATCH_CLOSURE`. This helper exposes it as a `&Function` so it can be
7/// passed to the various browser scheduling APIs (`setTimeout`,
8/// `queueMicrotask`, `requestAnimationFrame`) without recreating the closure
9/// on every schedule.
10///
11/// # Arguments
12///
13/// - `FnOnce(&Function) -> R` - Receives the dispatch function reference.
14///
15/// # Returns
16///
17/// - `R` - The value returned by `callback`.
18fn with_dispatch_function<F, R>(callback: F) -> R
19where
20 F: FnOnce(&Function) -> R,
21{
22 DISPATCH_CLOSURE.with(|dispatch_closure| {
23 let dispatch_function: &Function = dispatch_closure.as_ref().unchecked_ref::<Function>();
24 callback(dispatch_function)
25 })
26}
27
28/// Schedules a deferred signal update with precise dirty marking.
29///
30/// Marks only the specified dynamic node IDs as dirty, then queues a
31/// single microtask dispatch if one is not already pending. When
32/// `SUPPRESS_SCHEDULE` is `true`, slots are still marked dirty but no
33/// dispatch is scheduled, allowing `batch` to batch
34/// precise dirty marks without triggering premature DOM updates.
35///
36/// # Arguments
37///
38/// - `&[usize]` - Dynamic node IDs to mark dirty.
39pub fn schedule_update(dependents: &[usize]) {
40 mark_slots_dirty_targeted(dependents);
41 if SUPPRESS_SCHEDULE.load(Ordering::Relaxed) {
42 return;
43 }
44 if SCHEDULED.load(Ordering::Relaxed) {
45 return;
46 }
47 SCHEDULED.store(true, Ordering::Relaxed);
48 let window_value: Window = match window() {
49 Some(window_instance) => window_instance,
50 None => {
51 SCHEDULED.store(false, Ordering::Relaxed);
52 return;
53 }
54 };
55 let queued_microtask: bool = with_dispatch_function(|dispatch_function| {
56 let queue_microtask_value: JsValue =
57 Reflect::get(&window_value, &JsValue::from_str(QUEUE_MICROTASK))
58 .unwrap_or(JsValue::UNDEFINED);
59 matches!(
60 queue_microtask_value.dyn_into::<Function>(),
61 Ok(queue_microtask) if queue_microtask.call1(&window_value, dispatch_function).is_ok()
62 )
63 });
64 if queued_microtask {
65 return;
66 }
67 let scheduled: bool = with_dispatch_function(|dispatch_function| {
68 window_value
69 .set_timeout_with_callback_and_timeout_and_arguments_0(dispatch_function, 0)
70 .is_ok()
71 });
72 if scheduled {
73 return;
74 }
75 let requested_frame: bool = with_dispatch_function(|dispatch_function| {
76 window_value
77 .request_animation_frame(dispatch_function)
78 .is_ok()
79 });
80 if requested_frame {
81 return;
82 }
83 SCHEDULED.store(false, Ordering::Relaxed);
84}
85
86/// Batches signal updates within a closure, deferring DOM dispatch until the
87/// outermost batch completes.
88///
89/// Sets `SUPPRESS_SCHEDULE` to `true` so that any `Signal::set()` calls
90/// inside the closure mark their dependents dirty precisely but do not
91/// queue a microtask dispatch. The previous suppress flag is restored on
92/// exit, allowing the outermost `set()` call to trigger the actual
93/// dispatch cycle that processes all accumulated dirty slots.
94///
95/// Unlike the legacy full-broadcast approach, this uses precise dependency
96/// tracking: only the dynamic nodes that actually depend on the changed
97/// signals are marked dirty and re-rendered.
98///
99/// # Arguments
100///
101/// - `FnOnce() -> R` - The closure to execute with batched updates.
102///
103/// # Returns
104///
105/// - `R` - The result of the closure execution.
106pub fn batch<F, R>(callback: F) -> R
107where
108 F: FnOnce() -> R,
109{
110 let was_outermost: bool = !SUPPRESS_SCHEDULE.load(Ordering::Relaxed);
111 SUPPRESS_SCHEDULE.store(true, Ordering::Relaxed);
112 let result: R = callback();
113 SUPPRESS_SCHEDULE.store(!was_outermost, Ordering::Relaxed);
114 result
115}
116
117/// Subscribes an attribute signal to the global signal update dispatch cycle.
118///
119/// Creates a callback that re-computes the attribute value and sets
120/// it on the signal whenever a signal update cycle runs. The callback
121/// is registered in the signal update registry using the signal's
122/// inner address as the key.
123///
124/// # Arguments
125///
126/// - `Signal<String>` - The attribute signal to subscribe.
127/// - `Fn() -> String + 'static` - A closure that computes the current attribute value string.
128pub(crate) fn subscribe_attr<F>(attr_signal: Signal<String>, compute: F)
129where
130 F: Fn() -> String + 'static,
131{
132 register_attr_signal_listener(
133 attr_signal.get_inner(),
134 Box::new(move || {
135 attr_signal.set(compute());
136 }),
137 );
138}
139
140/// Converts a bool signal into a reactive `Signal<String>` attribute value.
141///
142/// Creates a `Signal<String>` initialized with the bool's string
143/// representation, then subscribes to the source signal so that
144/// whenever the bool changes, the string signal is updated accordingly.
145///
146/// # Arguments
147///
148/// - `Signal<bool>` - The source boolean signal.
149///
150/// # Returns
151///
152/// - `AttributeValue` - An `AttributeValue::Signal` wrapping the derived string signal.
153pub(crate) fn bool_to_attr(source: Signal<bool>) -> AttributeValue {
154 let string_signal: Signal<String> = Signal::create(source.get().to_string());
155 let string_signal_clone: Signal<String> = string_signal;
156 let source_for_sub: Signal<bool> = source;
157 source_for_sub.replace_subscribe(move || {
158 string_signal_clone.set(source_for_sub.get().to_string());
159 });
160 AttributeValue::Signal(string_signal)
161}
162
163/// Returns a mutable reference to the current hook context.
164///
165/// SAFETY: Must only be called from the main thread (WASM single-threaded context).
166///
167/// # Returns
168///
169/// - `&'static mut Option<HookContextRc>`: A mutable reference to the global hook context.
170#[allow(static_mut_refs)]
171pub(crate) fn try_get_current_hook_context_mut() -> &'static mut Option<HookContextRc> {
172 unsafe { &mut *CURRENT_HOOK_CONTEXT.get_0().get() }
173}
174
175/// Returns a shared reference to the current hook context.
176///
177/// SAFETY: Must only be called from the main thread (WASM single-threaded context).
178///
179/// # Returns
180///
181/// - `&'static Option<HookContextRc>`: A shared reference to the global hook context.
182#[allow(static_mut_refs)]
183pub(crate) fn try_get_current_hook_context() -> &'static Option<HookContextRc> {
184 unsafe { &*CURRENT_HOOK_CONTEXT.get_0().get() }
185}