euv_core/reactive/schedule/fn.rs
1use crate::*;
2
3/// Ensures the `window.__euv_dispatch` callback is registered.
4///
5/// Creates a `Closure` that resets the `SCHEDULED` flag and directly
6/// invokes `dispatch_signal_update_callbacks`, then stores it on the
7/// `window` object so it can be invoked via `requestAnimationFrame`.
8///
9fn ensure_dispatch_callback() {
10 let window_value: Window = match window() {
11 Some(window_instance) => window_instance,
12 None => return,
13 };
14 let key: JsValue = JsValue::from_str(EUV_DISPATCH);
15 if Reflect::get(&window_value, &key)
16 .unwrap_or(JsValue::UNDEFINED)
17 .is_undefined()
18 {
19 let closure: closure::Closure<dyn FnMut()> = closure::Closure::wrap(Box::new(|| {
20 SCHEDULED.store(false, Ordering::Relaxed);
21 dispatch_signal_update_callbacks();
22 }));
23 let _ = Reflect::set(&window_value, &key, closure.as_ref());
24 closure.forget();
25 }
26}
27
28/// Schedules a deferred signal update event via `requestAnimationFrame`.
29///
30/// If a schedule is already pending (`SCHEDULED` is true) or updates
31/// are suppressed (`SUPPRESS_SCHEDULE` is true), this is a no-op.
32/// Otherwise, sets `SCHEDULED` to true and queues the
33/// `window.__euv_dispatch` callback via `requestAnimationFrame` on WASM
34/// targets. This ensures that no matter how many signal updates occur
35/// within a single animation frame, only one dispatch cycle runs,
36/// preventing CPU spikes during rapid input events (e.g., slider dragging).
37///
38/// On non-WASM targets, resets `SCHEDULED` immediately since there is
39/// no event loop to schedule on.
40pub fn schedule_signal_update() {
41 if SCHEDULED.load(Ordering::Relaxed) || SUPPRESS_SCHEDULE.load(Ordering::Relaxed) {
42 return;
43 }
44 SCHEDULED.store(true, Ordering::Relaxed);
45 mark_all_slots_dirty();
46 let window_option: Option<Window> = window();
47 if window_option.is_none() {
48 SCHEDULED.store(false, Ordering::Relaxed);
49 return;
50 }
51 ensure_dispatch_callback();
52 let window_value: Window = match window_option {
53 Some(window_instance) => window_instance,
54 None => {
55 SCHEDULED.store(false, Ordering::Relaxed);
56 return;
57 }
58 };
59 let dispatch_fn: JsValue =
60 Reflect::get(&window_value, &JsValue::from_str(EUV_DISPATCH)).unwrap_or(JsValue::UNDEFINED);
61 if dispatch_fn.is_undefined() {
62 SCHEDULED.store(false, Ordering::Relaxed);
63 return;
64 }
65 let request_animation_frame_value: JsValue =
66 Reflect::get(&window_value, &JsValue::from_str(REQUEST_ANIMATION_FRAME))
67 .unwrap_or(JsValue::UNDEFINED);
68 if request_animation_frame_value.is_undefined() {
69 let queue_microtask_value: JsValue =
70 Reflect::get(&window_value, &JsValue::from_str(QUEUE_MICROTASK))
71 .unwrap_or(JsValue::UNDEFINED);
72 if queue_microtask_value.is_undefined() {
73 SCHEDULED.store(false, Ordering::Relaxed);
74 return;
75 }
76 let queue_microtask: Function = queue_microtask_value.into();
77 let _ = queue_microtask.call1(&JsValue::NULL, &dispatch_fn);
78 return;
79 }
80 let request_animation_frame: Function = request_animation_frame_value.into();
81 let _ = request_animation_frame.call1(&JsValue::NULL, &dispatch_fn);
82}
83
84/// Batches signal updates within a closure, deferring DOM synchronization until completion.
85///
86/// Saves the current `SUPPRESS_SCHEDULE` flag, sets it to `true`,
87/// executes the closure, and restores the previous flag value.
88/// This prevents `schedule_signal_update` from queuing microtasks
89/// during the closure execution, allowing multiple signal mutations
90/// to be applied before triggering a single DOM update cycle.
91///
92/// # Arguments
93///
94/// - `FnOnce() -> R` - The closure to execute with batched updates.
95///
96/// # Returns
97///
98/// - `R` - The result of the closure execution.
99pub fn batch_updates<F, R>(callback: F) -> R
100where
101 F: FnOnce() -> R,
102{
103 let previous: bool = SUPPRESS_SCHEDULE.load(Ordering::Relaxed);
104 SUPPRESS_SCHEDULE.store(true, Ordering::Relaxed);
105 let result: R = callback();
106 SUPPRESS_SCHEDULE.store(previous, Ordering::Relaxed);
107 result
108}
109
110/// Subscribes an attribute signal to the global signal update dispatch cycle.
111///
112/// Creates a callback that re-computes the attribute value and sets
113/// it on the signal whenever a signal update cycle runs. The callback
114/// is registered in the signal update registry using the signal's
115/// inner address as the key.
116///
117/// # Arguments
118///
119/// - `Signal<String>` - The attribute signal to subscribe.
120/// - `Fn() -> String + 'static` - A closure that computes the current attribute value string.
121pub(crate) fn subscribe_attr_signal<F>(attr_signal: Signal<String>, compute: F)
122where
123 F: Fn() -> String + 'static,
124{
125 register_attr_signal_listener(
126 attr_signal.get_inner(),
127 Box::new(move || {
128 attr_signal.set_silent(compute());
129 }),
130 );
131}
132
133/// Converts a bool signal into a reactive `Signal<String>` attribute value.
134///
135/// Creates a `Signal<String>` initialized with the bool's string
136/// representation, then subscribes to the source signal so that
137/// whenever the bool changes, the string signal is updated accordingly.
138///
139/// # Arguments
140///
141/// - `Signal<bool>` - The source boolean signal.
142///
143/// # Returns
144///
145/// - `AttributeValue` - An `AttributeValue::Signal` wrapping the derived string signal.
146pub(crate) fn bool_signal_to_string_attribute_value(source: Signal<bool>) -> AttributeValue {
147 let string_signal: Signal<String> = Signal::create(source.get().to_string());
148 let string_signal_clone: Signal<String> = string_signal;
149 source.replace_subscribe({
150 let source_inner: Signal<bool> = source;
151 move || {
152 string_signal_clone.set_silent(source_inner.get().to_string());
153 }
154 });
155 AttributeValue::Signal(string_signal)
156}
157
158/// Returns a mutable reference to the current hook context.
159///
160/// SAFETY: Must only be called from the main thread (WASM single-threaded context).
161///
162/// # Returns
163///
164/// - `&'static mut Option<HookContextRc>`: A mutable reference to the global hook context.
165#[allow(static_mut_refs)]
166pub(crate) fn current_hook_context_mut() -> &'static mut Option<HookContextRc> {
167 unsafe { &mut *CURRENT_HOOK_CONTEXT.get_0().get() }
168}
169
170/// Returns a shared reference to the current hook context.
171///
172/// SAFETY: Must only be called from the main thread (WASM single-threaded context).
173///
174/// # Returns
175///
176/// - `&'static Option<HookContextRc>`: A shared reference to the global hook context.
177#[allow(static_mut_refs)]
178pub(crate) fn current_hook_context() -> &'static Option<HookContextRc> {
179 unsafe { &*CURRENT_HOOK_CONTEXT.get_0().get() }
180}