euv-core 0.8.28

A declarative, cross-platform UI framework for Rust with virtual DOM, reactive signals, and HTML macros for WebAssembly.
Documentation
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
use crate::*;

/// Implementation of reactive signal operations.
impl<T> Signal<T>
where
    T: Clone + PartialEq + 'static,
{
    /// Creates a new `Signal` with the given initial value.
    ///
    /// Allocates `SignalInner<T>` on the heap via `Box`, stores the raw pointer
    /// address, and registers it in the global registry for lifecycle tracking.
    ///
    /// # Arguments
    ///
    /// - `T: Clone + PartialEq + 'static` - The initial value of the signal.
    ///
    /// # Returns
    ///
    /// - `Self` - A handle to the newly created reactive signal.
    pub fn create(value: T) -> Self {
        let mut inner: SignalInner<T> = SignalInner::new(value, Vec::new(), true);
        inner.set_listeners_replaced(false);
        let boxed: Box<SignalInner<T>> = Box::new(inner);
        let ptr: *mut SignalInner<T> = Box::into_raw(boxed);
        let addr: usize = ptr as usize;
        Self::registry_mut().insert(addr);
        let mut signal: Self = Self::new(0, std::marker::PhantomData);
        signal.set_inner(addr);
        signal
    }

    /// Returns the current value of the signal.
    ///
    /// Directly reads the value from the heap-allocated inner state via raw
    /// pointer dereference. No runtime borrow checking overhead.
    ///
    /// If the signal has been marked inactive (`alive == false`), returns the
    /// last stored value without registering tracking dependencies. This
    /// ensures that stale async callbacks (e.g., orphaned `setInterval`)
    /// holding a `Signal` copy can still call `.get()` safely without
    /// triggering side effects or panics.
    ///
    /// If a tracking context is active (i.e., a DynamicNode is being rendered),
    /// automatically registers the current dynamic node as a dependent of
    /// this signal for precise reactive updates.
    ///
    /// # Returns
    ///
    /// - `T: Clone + PartialEq + 'static` - The current value of the signal.
    pub fn get(&self) -> T {
        let inner: &mut SignalInner<T> = Self::inner_mut(self.get_inner());
        if !inner.get_alive() {
            return inner.get_value().clone();
        }
        let tracking_id: usize = CURRENT_TRACKING_DYNAMIC_ID.load(Ordering::Relaxed);
        if tracking_id != usize::MAX {
            self.add_dependent(tracking_id);
        }
        inner.get_value().clone()
    }

    /// Subscribes a callback to be invoked when the signal changes.
    ///
    /// # Arguments
    ///
    /// - `FnMut() + 'static` - The callback to invoke when the signal changes.
    pub fn subscribe<F>(&self, callback: F)
    where
        F: FnMut() + 'static,
    {
        Self::inner_mut(self.get_inner())
            .get_mut_listeners()
            .push(Box::new(callback));
    }

    /// Replaces all listeners with a single new callback.
    ///
    /// Unlike `subscribe`, which appends a listener, this method clears any
    /// existing listeners first and then adds the new one.
    ///
    /// # Arguments
    ///
    /// - `FnMut() + 'static` - The callback to invoke when the signal changes.
    pub(crate) fn replace_listener<F>(&self, callback: F)
    where
        F: FnMut() + 'static,
    {
        let inner: &mut SignalInner<T> = Self::inner_mut(self.get_inner());
        inner.get_mut_listeners().clear();
        inner.get_mut_listeners().push(Box::new(callback));
        inner.set_listeners_replaced(true);
    }

    /// Detaches this signal from the reactive system without freeing memory.
    ///
    /// Marks the signal inactive and clears its listeners and dependents, but
    /// intentionally keeps the heap allocation alive.
    ///
    /// This is the only supported teardown path for a signal, and is used by
    /// both DOM-bound subscribe closures (when their node is removed) and the
    /// `use_signal` hook cleanup (when a component unmounts or a `match` arm
    /// switches). Freeing the allocation is deliberately never done at these
    /// points because `Signal<T>` is `Copy` (just a `usize` address): async
    /// callbacks (`spawn_local` futures, `setTimeout` / `setInterval`
    /// closures, Promise continuations) may still hold copies of the signal,
    /// and freeing would turn their later `.get()` / `.set()` calls into a
    /// use-after-free. Deactivating instead makes those stale calls safe
    /// no-ops.
    ///
    /// The allocation remains valid until the page unloads. For SPAs this is
    /// acceptable; a long-lived app could add a periodic sweep that frees
    /// `alive == false` entries once no async references remain. This mirrors
    /// the contract documented on `clear_signal_listeners`.
    pub(crate) fn deactivate(&self) {
        let inner: &mut SignalInner<T> = Self::inner_mut(self.get_inner());
        inner.set_alive(false);
        inner.get_mut_listeners().clear();
        inner.get_mut_dependents().clear();
    }

    /// Core implementation of value update and listener notification.
    ///
    /// Returns `true` if the value was updated and listeners were notified.
    /// Returns `false` if the signal is inactive or the value is unchanged.
    ///
    /// Uses a swap-out pattern for listeners: moves all listeners into a local
    /// `Vec`, drops the mutable reference to inner state, then invokes each
    /// listener. After invocation, listeners are moved back. This prevents
    /// issues with re-entrant access during listener callbacks.
    fn update(&self, value: T) -> bool {
        let inner: &mut SignalInner<T> = Self::inner_mut(self.get_inner());
        if !inner.get_alive() {
            return false;
        }
        if *inner.get_value() == value {
            return false;
        }
        inner.set_value(value);
        inner.set_listeners_replaced(false);
        let mut listeners: Vec<Box<dyn FnMut()>> = Vec::new();
        swap(inner.get_mut_listeners(), &mut listeners);
        for listener in listeners.iter_mut() {
            listener();
        }
        if !Self::is_alive(self.get_inner()) {
            return true;
        }
        let inner: &mut SignalInner<T> = Self::inner_mut(self.get_inner());
        if inner.get_alive() {
            if inner.get_listeners_replaced() {
                inner.set_listeners_replaced(false);
            } else {
                let new_listeners: &mut Vec<Box<dyn FnMut()>> = inner.get_mut_listeners();
                if new_listeners.is_empty() {
                    swap(new_listeners, &mut listeners);
                } else {
                    listeners.append(new_listeners);
                    swap(new_listeners, &mut listeners);
                }
            }
        }
        true
    }

    /// Registers a dynamic node ID as a dependent of this signal.
    ///
    /// When this signal changes, only its registered dependents will be
    /// marked dirty for re-rendering, enabling precise updates instead
    /// of broadcasting to all dynamic nodes.
    ///
    /// # Arguments
    ///
    /// - `usize` - The dynamic node ID to register as a dependent.
    pub(crate) fn add_dependent(&self, dynamic_id: usize) {
        let deps: &mut Vec<usize> = Self::inner_mut(self.get_inner()).get_mut_dependents();
        if !deps.contains(&dynamic_id) {
            deps.push(dynamic_id);
        }
    }

    /// Removes a dynamic node ID from the dependents list of this signal.
    ///
    /// Called during cleanup when a dynamic node is removed from the DOM
    /// and its dependency relationships need to be severed.
    ///
    /// # Arguments
    ///
    /// - `usize` - The dynamic node ID to remove.
    #[allow(dead_code)]
    pub(crate) fn remove_dependent(&self, dynamic_id: usize) {
        Self::inner_mut(self.get_inner())
            .get_mut_dependents()
            .retain(|id: &usize| *id != dynamic_id);
    }

    /// Returns the list of dependent dynamic node IDs for this signal.
    ///
    /// # Returns
    ///
    /// - `Vec<usize>` - Clone of the dependents list.
    pub(crate) fn get_dependents(&self) -> Vec<usize> {
        Self::inner_mut(self.get_inner()).get_dependents().clone()
    }

    /// Sets the value of the signal and notifies listeners.
    ///
    /// Uses precise dirty marking: only dynamic nodes that depend on
    /// this signal are marked dirty, avoiding full broadcast.
    ///
    /// When called inside `batch`, the dispatch is
    /// deferred (dirty slots are still marked precisely), and the
    /// outermost `set()` call outside the suppressed scope will
    /// trigger the actual dispatch cycle.
    ///
    /// # Arguments
    ///
    /// - `T: Clone + PartialEq + 'static` - The new value to assign to the signal.
    pub fn set(&self, value: T) {
        if self.update(value) {
            let dependents: Vec<usize> = self.get_dependents();
            App::schedule_update(&dependents);
        }
    }

    /// Retrieves a mutable pointer to `SignalInner<T>` directly from the
    /// signal's stored address.
    ///
    /// SAFETY: The address stored in `Signal::inner` is always a valid pointer
    /// to a `SignalInner<T>` that is kept alive by the global registry. Since
    /// WASM is single-threaded, the pointer is always valid as long as the
    /// signal has not been explicitly freed.
    fn inner_mut(addr: usize) -> &'static mut SignalInner<T> {
        unsafe { &mut *(addr as *mut SignalInner<T>) }
    }

    /// Returns whether the signal allocation at `addr` is still present in
    /// the global registry (i.e. has not been freed).
    fn is_alive(addr: usize) -> bool {
        Self::registry_mut().contains(&addr)
    }

    /// Ensures the signal inner registry is initialized and returns a mutable
    /// reference to the global signal address registry.
    #[allow(static_mut_refs)]
    fn registry_mut() -> &'static mut HashSet<usize> {
        unsafe {
            if (*SIGNAL_INNER_REGISTRY.get_0().get()).is_none() {
                (*SIGNAL_INNER_REGISTRY.get_0().get()) = Some(HashSet::new());
            }
            (*SIGNAL_INNER_REGISTRY.get_0().get())
                .as_mut()
                .unwrap_unchecked()
        }
    }
}

/// Provides a safe default for `Signal<T>` by creating a valid signal
/// initialized with `T::default()`.
///
/// This prevents the creation of invalid signals with `inner = 0` (null
/// pointer), which would cause a panic when `.get()` is called.
///
/// # Returns
///
/// - `Self` - A valid signal initialized with `T::default()`.
impl<T> Default for Signal<T>
where
    T: Clone + Default + PartialEq + 'static,
{
    fn default() -> Self {
        Self::create(T::default())
    }
}

/// Clones the signal, sharing the same inner state.
///
/// Since `Signal` is `Copy`, this simply returns `*self`.
///
/// # Returns
///
/// - `Self` - A copy of the signal handle sharing the same inner state.
impl<T> Clone for Signal<T>
where
    T: Clone + PartialEq + 'static,
{
    fn clone(&self) -> Self {
        *self
    }
}

/// Copies the signal, sharing the same inner state.
///
/// Safe because only the inner address (a `usize`) is copied;
/// the actual heap allocation is owned by the global signal registry.
impl<T> Copy for Signal<T> where T: Clone + PartialEq + 'static {}

/// Marks `SignalCell` as `Sync` for single-threaded WASM contexts.
///
/// SAFETY: `SignalCell` is only used in single-threaded WASM contexts.
/// Concurrent access from multiple threads would be undefined behavior.
unsafe impl<T> Sync for SignalCell<T> where T: Clone + PartialEq + 'static {}

/// Implementation of SignalCell construction and access.
impl<T> SignalCell<T>
where
    T: Clone + PartialEq + 'static,
{
    /// Creates a new `SignalCell` with no signal stored.
    ///
    /// # Returns
    ///
    /// - `Self` - An empty `SignalCell` with `None` stored in the inner `UnsafeCell`.
    pub const fn none() -> Self {
        Self {
            inner: UnsafeCell::new(None),
        }
    }

    /// Stores a signal into the cell.
    ///
    /// # Arguments
    ///
    /// - `Signal<T>` - The signal to store.
    ///
    /// # Panics
    ///
    /// Panics if a signal has already been stored.
    pub fn set(&self, signal: Signal<T>) {
        unsafe {
            let ptr: &mut Option<Signal<T>> = &mut *self.get_inner().get();
            if ptr.is_some() {
                panic!("SignalCell::set called on an already-initialized cell");
            }
            *ptr = Some(signal);
        }
    }

    /// Returns the signal stored in the cell.
    ///
    /// # Returns
    ///
    /// - `Signal<T>` - The stored signal.
    ///
    /// # Panics
    ///
    /// Panics if no signal has been stored via `set`.
    pub fn get(&self) -> Signal<T> {
        unsafe {
            let ptr: &Option<Signal<T>> = &*self.get_inner().get();
            match ptr {
                Some(signal) => *signal,
                None => panic!("SignalCell::get called on an uninitialized cell"),
            }
        }
    }
}

/// Provides a default empty `SignalCell`.
///
/// Creates a `SignalCell` with `None` stored in the inner `UnsafeCell`.
///
/// # Returns
///
/// - `Self` - An empty `SignalCell` with no signal stored.
impl<T> Default for SignalCell<T>
where
    T: Clone + PartialEq + 'static,
{
    fn default() -> Self {
        Self::new(UnsafeCell::new(None))
    }
}

/// Marks `SignalInnerRegistryCell` as `Sync` for single-threaded WASM contexts.
///
/// SAFETY: `SignalInnerRegistryCell` is only used in single-threaded WASM contexts.
/// Concurrent access from multiple threads would be undefined behavior.
unsafe impl Sync for SignalInnerRegistryCell {}

/// String-specific signal operations.
impl Signal<String> {
    /// Clears DOM-binding listeners on a bridge signal identified by its inner
    /// pointer address, deactivates the bridge signal, and releases its value
    /// memory.
    ///
    /// This function is used during DOM cleanup (`cleanup_dom_subtree`) to
    /// release bridge `Signal<String>` instances that are no longer needed.
    ///
    /// Bridge signals are internal `Signal<String>` instances created by
    /// `as_reactive_text` and `AttributeValue::Signal` for DOM binding.
    /// They have exactly one consumer (the DOM element), so deactivating them
    /// is safe when the element is removed. User-created source signals are
    /// never passed to this function — they are tracked by `SignalInner.dependents`
    /// and cleaned up by `use_signal`'s `deactivate()` on hook context teardown.
    ///
    /// The bridge signal's value is replaced with `String::new()` to release
    /// the original string data, and `alive` is set to `false` so that any
    /// stale async references become safe no-ops.
    ///
    /// # Arguments
    ///
    /// - `usize` - The inner pointer address of the bridge signal.
    pub(crate) fn clear_listeners(addr: usize) {
        let inner: &mut SignalInner<String> = Self::inner_mut(addr);
        inner.get_mut_listeners().clear();
        inner.set_alive(false);
        inner.set_value(String::new());
        Registry::cleanup_attr_slot(addr);
    }
}