euv-core 0.18.24

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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
use super::*;

/// SAFETY: `HandlerRegistryCell` is only used in single-threaded WASM contexts.
unsafe impl Sync for HandlerRegistryCell {}

/// SAFETY: `DelegatedEventsCell` is only used in single-threaded WASM contexts.
unsafe impl Sync for DelegatedEventsCell {}

/// SAFETY: `SignalUpdateRegistryCell` is only used in single-threaded WASM contexts.
unsafe impl Sync for SignalUpdateRegistryCell {}

/// SAFETY: `DirtyUpdateIdsCell` is only used in single-threaded WASM contexts.
unsafe impl Sync for DirtyUpdateIdsCell {}

/// SAFETY: `WindowEventRegistryCell` is only used in single-threaded WASM contexts.
unsafe impl Sync for WindowEventRegistryCell {}

/// Implementation of `From` trait for converting `usize` address into `&'static mut HandlerSlot`.
impl From<usize> for &'static mut HandlerSlot {
    /// Converts a memory address into a mutable reference to `HandlerSlot`.
    ///
    /// # Arguments
    ///
    /// - `usize` - The memory address of the `HandlerSlot` instance.
    ///
    /// # Returns
    ///
    /// - `&'static mut HandlerSlot` - A mutable reference at the given address.
    ///
    /// # Safety
    ///
    /// - The address is guaranteed to be a valid `HandlerSlot` instance
    ///   that was previously converted from a reference and is managed by the runtime.
    fn from(address: usize) -> Self {
        unsafe { &mut *(address as *mut HandlerSlot) }
    }
}

/// Static methods for managing framework registries.
///
/// Provides centralized access to event delegation, signal updates, window events,
/// and DOM event handler registries. All methods are thread-safe for single-threaded
/// WASM contexts.
impl Registry {
    /// Returns a shared reference to the delegated events set.
    ///
    /// # Returns
    ///
    /// - `&'static HashSet<&'static str>` - A shared reference to the global set of delegated event names.
    #[allow(static_mut_refs)]
    pub(crate) fn get_delegated_events() -> &'static HashSet<&'static str> {
        unsafe { &*DELEGATED_EVENTS.deref().get_0().get() }
    }

    /// Returns a mutable reference to the delegated events set.
    ///
    /// # Returns
    ///
    /// - `&'static mut HashSet<&'static str>` - A mutable reference to the global set of delegated event names.
    #[allow(static_mut_refs)]
    pub(crate) fn get_mut_delegated_events() -> &'static mut HashSet<&'static str> {
        unsafe { &mut *DELEGATED_EVENTS.deref().get_0().get() }
    }

    /// Returns a mutable reference to the signal update registry.
    ///
    /// # Returns
    ///
    /// - `&'static mut HashMap<usize, SignalUpdateEntry>` - A mutable reference to the global signal update registry.
    #[allow(static_mut_refs)]
    pub(crate) fn get_mut_update_registry() -> &'static mut HashMap<usize, SignalUpdateEntry> {
        unsafe { &mut *SIGNAL_UPDATE_REGISTRY.deref().get_0().get() }
    }

    /// Returns a mutable reference to the dirty-id set used by the OPT 6
    /// dispatcher fast path.
    ///
    /// # Returns
    ///
    /// - `&'static mut HashSet<usize>` - A mutable reference to the global dirty-id set.
    #[allow(static_mut_refs)]
    pub(crate) fn get_mut_dirty_update_ids() -> &'static mut HashSet<usize> {
        unsafe { &mut *DIRTY_UPDATE_IDS.deref().get_0().get() }
    }

    /// Returns a shared reference to the window event registry.
    ///
    /// # Returns
    ///
    /// - `&'static WindowEventRegistryMap` - A shared reference to the global window event registry.
    #[allow(static_mut_refs)]
    pub(crate) fn get_window_registry() -> &'static WindowEventRegistryMap {
        unsafe { &*WINDOW_EVENT_REGISTRY.deref().get_0().get() }
    }

    /// Returns a mutable reference to the window event registry.
    ///
    /// # Returns
    ///
    /// - `&'static mut WindowEventRegistryMap` - A mutable reference to the global window event registry.
    #[allow(static_mut_refs)]
    pub(crate) fn get_mut_window_registry() -> &'static mut WindowEventRegistryMap {
        unsafe { &mut *WINDOW_EVENT_REGISTRY.deref().get_0().get() }
    }

    /// Returns a shared reference to the handler registry.
    ///
    /// # Returns
    ///
    /// - `&'static HandlerRegistryMap` - A shared reference to the global handler registry.
    #[allow(static_mut_refs)]
    pub(crate) fn get_handler_registry() -> &'static HandlerRegistryMap {
        unsafe { &*HANDLER_REGISTRY.deref().get_0().get() }
    }

    /// Returns a mutable reference to the handler registry.
    ///
    /// # Returns
    ///
    /// - `&'static mut HandlerRegistryMap` - A mutable reference to the global handler registry.
    #[allow(static_mut_refs)]
    pub(crate) fn get_mut_handler_registry() -> &'static mut HandlerRegistryMap {
        unsafe { &mut *HANDLER_REGISTRY.deref().get_0().get() }
    }

    /// Dispatches a delegated event by walking up from `event.target` to
    /// find the nearest element with a `data-euv-id` attribute, then
    /// invoking the matching handler from the global registry.
    ///
    /// `max_depth` caps the ancestor walk at this many `parent_element`
    /// hops. The walk counts `event.target()` itself as depth 0. Pass
    /// `usize::MAX` for an unbounded walk (the original behaviour).
    /// Events named in `HIGH_FREQUENCY_EVENTS` use a smaller cap
    /// (see `MAX_ANCESTOR_DEPTH_FOR_HIGH_FREQ`) because their handlers
    /// almost always live within a handful of ancestors of the target
    /// (e.g. a `mousemove` listener attached to a scroll container).
    ///
    /// # Arguments
    ///
    /// - `&Event` - The DOM event to dispatch.
    /// - `&'static str` - The event name (e.g., "click", "input").
    /// - `usize` - Upper bound on ancestor walk depth; `usize::MAX` for unbounded.
    fn dispatch_delegated_event(event: &Event, event_name: &'static str, max_depth: usize) {
        let target: EventTarget = match event.target() {
            Some(event_target) => event_target,
            None => return,
        };
        let mut current: Option<Element> = target.dyn_ref::<Element>().cloned().or_else(|| {
            target
                .dyn_ref::<Node>()
                .and_then(|node: &Node| node.parent_node())
                .and_then(|parent: Node| parent.dyn_ref::<Element>().cloned())
        });
        // Bound the ancestor walk so high-frequency events
        // (mousemove / touchmove / pointermove / scroll / wheel /
        // mousewheel) don't pay the cost of `get_attribute` +
        // `parse::<usize>` + HashMap lookup at every intermediate DOM
        // node between the target and the handler. The cap is wide
        // enough to reach a typical scroll/drag container (a few levels
        // above the deepest leaf) while keeping the worst case
        // proportional to constant time rather than DOM depth.
        let mut depth: usize = 0;
        while let Some(element) = current {
            if depth >= max_depth {
                break;
            }
            if let Some(euv_id_str) = element.get_attribute(DATA_EUV_ID)
                && let Ok(euv_id) = euv_id_str.parse::<usize>()
            {
                let handler_found: Option<NativeEventHandler> = Self::get_handler_registry()
                    .get(&euv_id)
                    .and_then(|event_map: &HashMap<&'static str, HandlerEntry>| {
                        event_map.get(event_name)
                    })
                    .and_then(|entry: &HandlerEntry| {
                        let slot: &HandlerSlot = unsafe { &**entry };
                        slot.try_get_handler().as_ref().cloned()
                    });
                if let Some(active_handler) = handler_found {
                    active_handler.handle(event.clone());
                    return;
                }
            }
            current = element.parent_element();
            depth += 1;
        }
    }

    /// Ensures a global capturing-phase listener is registered on `window`
    /// for the given event type.
    ///
    /// Uses event delegation to minimize the number of event listeners attached
    /// to the DOM. All events of the same type are handled by a single window-level
    /// listener that walks the DOM tree to find the appropriate handler.
    ///
    /// # Arguments
    ///
    /// - `&'static str` - The event name to delegate (e.g., "click", "input").
    pub(crate) fn delegation(event_name: &'static str) {
        if Self::is_delegated(event_name) {
            return;
        }
        // Compute the depth cap for this event name once at registration
        // time and capture it in the closure — avoids re-computing on
        // every event dispatch. Events listed in HIGH_FREQUENCY_EVENTS
        // get a bounded walk (see MAX_ANCESTOR_DEPTH_FOR_HIGH_FREQ);
        // everything else gets the original unbounded behaviour.
        let max_depth: usize = if HIGH_FREQUENCY_EVENTS.contains(&event_name) {
            MAX_ANCESTOR_DEPTH_FOR_HIGH_FREQ
        } else {
            usize::MAX
        };
        let closure: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |event: Event| {
            Self::dispatch_delegated_event(&event, event_name, max_depth);
        }));
        let window: Window = match window() {
            Some(window_instance) => window_instance,
            None => return,
        };
        let _: Result<(), JsValue> = window.add_event_listener_with_callback_and_bool(
            event_name,
            closure.as_ref().unchecked_ref(),
            true,
        );
        closure.forget();
        Self::mark_delegated(event_name);
    }

    /// Marks the specified dynamic node IDs as dirty, scheduling them for re-render.
    ///
    /// Called when a signal changes to notify all dependent dynamic nodes
    /// that they need to update their DOM representation.
    ///
    /// OPT 6: also inserts each id into `DIRTY_UPDATE_IDS` so the
    /// dispatcher's `drain()` loop only visits dynamic nodes that actually
    /// changed, instead of scanning the whole registry. The previous
    /// `has_dirty` implementation iterated every registry entry and
    /// dereferenced a raw pointer per entry just to read the `dirty` flag.
    ///
    /// # Arguments
    ///
    /// - `&[usize]` - The dynamic node IDs to mark as dirty.
    pub(crate) fn mark_dirty(dynamic_ids: &[usize]) {
        let dirty_ids: &mut HashSet<usize> = Self::get_mut_dirty_update_ids();
        for dynamic_id in dynamic_ids {
            dirty_ids.insert(*dynamic_id);
        }
        let registry: &mut HashMap<usize, SignalUpdateEntry> = Self::get_mut_update_registry();
        for dynamic_id in dynamic_ids {
            if let Some(entry) = registry.get(dynamic_id) {
                let slot: &mut SignalUpdateSlot = unsafe { &mut **entry };
                if !slot.get_removed() {
                    slot.set_dirty(true);
                } else {
                    dirty_ids.remove(dynamic_id);
                }
            } else {
                dirty_ids.remove(dynamic_id);
            }
        }
    }

    /// Returns whether the signal update registry contains any dirty slots.
    ///
    /// OPT 6: now an O(1) check against `DIRTY_UPDATE_IDS` instead of an
    /// O(N) scan of every dynamic node.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if at least one dynamic node is marked dirty and not removed.
    pub(crate) fn has_dirty() -> bool {
        Self::get_mut_dirty_update_ids().iter().any(|id: &usize| {
            let registry: &HashMap<usize, SignalUpdateEntry> = Self::get_mut_update_registry();
            registry.get(id).is_some_and(|entry: &SignalUpdateEntry| {
                let slot: &SignalUpdateSlot = unsafe { &**entry };
                !slot.get_removed()
            })
        })
    }

    /// Registers a signal update callback for a DynamicNode placeholder.
    ///
    /// Associates a re-render callback with a dynamic node ID so that when
    /// the node is marked dirty, the callback can be invoked to update the DOM.
    ///
    /// # Arguments
    ///
    /// - `usize` - The unique dynamic node ID.
    /// - `Box<dyn FnMut()>` - The callback to invoke when the node needs re-rendering.
    pub(crate) fn register_dynamic(dynamic_id: usize, callback: Box<dyn FnMut()>) {
        let slot: Box<SignalUpdateSlot> =
            Box::new(SignalUpdateSlot::new(Some(callback), false, true));
        let entry: SignalUpdateEntry = Box::into_raw(slot);
        if let Some(old_entry) = Self::get_mut_update_registry().insert(dynamic_id, entry) {
            unsafe {
                let _: Box<SignalUpdateSlot> = Box::from_raw(old_entry);
            }
        }
    }

    /// Registers a signal update callback for an attribute signal.
    ///
    /// Similar to `register_dynamic`, but for attribute-level signals that
    /// need to update DOM element attributes rather than entire subtrees.
    ///
    /// # Arguments
    ///
    /// - `usize` - The signal's inner address used as the registry key.
    /// - `Box<dyn FnMut()>` - The callback to invoke when the attribute needs updating.
    pub(crate) fn register_attr_listener(signal_key: usize, callback: Box<dyn FnMut()>) {
        let slot: Box<SignalUpdateSlot> =
            Box::new(SignalUpdateSlot::new(Some(callback), false, true));
        let entry: SignalUpdateEntry = Box::into_raw(slot);
        if let Some(old_entry) = Self::get_mut_update_registry().insert(signal_key, entry) {
            unsafe {
                let _: Box<SignalUpdateSlot> = Box::from_raw(old_entry);
            }
        }
    }

    /// Cleans up all handler entries associated with a DOM element.
    ///
    /// Removes all event handlers registered for the given element ID,
    /// detaching any direct event listeners from the DOM.
    ///
    /// # Arguments
    ///
    /// - `usize` - The element's unique `data-euv-id` value.
    pub(crate) fn cleanup_element(euv_id: usize) {
        let registry_ref: &mut HandlerRegistryMap = Self::get_mut_handler_registry();
        let Some(event_map) = registry_ref.remove(&euv_id) else {
            return;
        };
        for (event_name, entry) in event_map {
            let slot: &mut HandlerSlot = unsafe { &mut *entry };
            if let Some(element) = slot.try_get_element().as_ref().cloned()
                && let Some(listener_function) = slot.get_mut_listener_function().take()
            {
                let listener: &Function = listener_function.unchecked_ref::<Function>();
                let _: Result<(), JsValue> =
                    element.remove_event_listener_with_callback(event_name, listener);
            }
            slot.set_handler(None);
            unsafe {
                let _: Box<HandlerSlot> = Box::from_raw(entry);
            }
        }
    }

    /// Marks the slot backing a DynamicNode as removed and frees its backing
    /// allocation.
    ///
    /// Intended to be called when the placeholder element is removed
    /// from the DOM by the surrounding diff / patch logic; this
    /// function itself only updates the registry and does not touch
    /// the DOM.
    ///
    /// The `SignalUpdateSlot` is removed from the registry and its
    /// `Box` is freed immediately rather than waiting for the next
    /// dispatch cycle's sweep, so that detached subtrees do not pin
    /// their callback allocations in the registry between unmount and
    /// the next scheduled update. This is safe because the registry is
    /// only mutated from the main thread; if a dispatch is in progress
    /// it is running in a separate microtask turn and cannot observe
    /// a stale `Some(entry)` here.
    ///
    /// OPT 6: also drops the id from `DIRTY_UPDATE_IDS` so the
    /// dispatcher does not re-discover a freed pointer on the next tick.
    ///
    /// # Arguments
    ///
    /// - `usize` - The dynamic node's unique ID.
    pub(crate) fn cleanup_dynamic_node(dynamic_id: usize) {
        Self::get_mut_dirty_update_ids().remove(&dynamic_id);
        if let Some(entry) = Self::get_mut_update_registry().remove(&dynamic_id) {
            unsafe {
                let _: Box<SignalUpdateSlot> = Box::from_raw(entry);
            }
        }
    }

    /// Removes the signal update slot for an attribute signal from the registry.
    ///
    /// Marks the attribute slot as removed, frees its backing allocation
    /// eagerly (see `cleanup_dynamic_node` for the rationale), and
    /// prevents further updates to detached DOM elements.
    ///
    /// OPT 6: also drops the address from `DIRTY_UPDATE_IDS` so a
    /// recycled heap address does not pick up a stale dispatch slot
    /// the next time `mark_dirty` runs.
    ///
    /// # Arguments
    ///
    /// - `usize` - The signal's inner address used as the registry key.
    pub(crate) fn cleanup_attr_slot(addr: usize) {
        Self::get_mut_dirty_update_ids().remove(&addr);
        if let Some(entry) = Self::get_mut_update_registry().remove(&addr) {
            unsafe {
                let _: Box<SignalUpdateSlot> = Box::from_raw(entry);
            }
        }
    }

    /// Returns whether the given event name is a non-bubbling event.
    ///
    /// Non-bubbling events (like "load", "error", "focus") must be attached
    /// directly to elements rather than using event delegation.
    ///
    /// # Arguments
    ///
    /// - `&str` - The event name to check.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if the event does not bubble up the DOM tree.
    pub(crate) fn is_non_bubbling(event_name: &str) -> bool {
        NON_BUBBLING_EVENTS.contains(&event_name)
    }

    /// Returns whether the event name is already delegated.
    ///
    /// # Arguments
    ///
    /// - `&str` - The event name to check.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if a window-level listener already exists for this event type.
    pub(crate) fn is_delegated(event_name: &str) -> bool {
        Self::get_delegated_events().contains(event_name)
    }

    /// Marks an event name as delegated in the global set.
    ///
    /// # Arguments
    ///
    /// - `&'static str` - The event name to mark as delegated.
    pub(crate) fn mark_delegated(event_name: &'static str) {
        Self::get_mut_delegated_events().insert(event_name);
    }

    /// Registers a callback for a window-level event using the proxy pattern.
    ///
    /// Creates a shared window event listener that dispatches to all registered
    /// callbacks for the same event type. Returns a unique handler ID for later
    /// unregistration.
    ///
    /// # Arguments
    ///
    /// - `&str` - The event name to listen for (e.g., "resize", "hashchange").
    /// - `F: FnMut() + 'static` - The callback to invoke when the event fires.
    ///
    /// # Returns
    ///
    /// - `usize` - A unique handler ID that can be used to unregister the callback.
    pub(crate) fn register_window_event<F>(event_name: &str, callback: F) -> usize
    where
        F: FnMut() + 'static,
    {
        let handler_id: usize = NEXT_WINDOW_HANDLER_ID.fetch_add(1, Ordering::Relaxed);
        let boxed: Box<Box<dyn FnMut()>> = Box::new(Box::new(callback));
        let entry: WindowEventHandlerEntry = (handler_id, Box::into_raw(boxed));
        let registry: &mut WindowEventRegistryMap = Self::get_mut_window_registry();
        let is_new_event: bool = !registry.contains_key(event_name);
        registry
            .entry(event_name.to_string())
            .or_default()
            .push(entry);
        if is_new_event {
            Self::window_event_listener(event_name);
        }
        handler_id
    }

    /// Unregisters a window event handler by its event name and handler ID.
    ///
    /// Removes the callback from the registry and frees its memory.
    ///
    /// # Arguments
    ///
    /// - `&str` - The event name the handler was registered for.
    /// - `usize` - The handler ID returned by `register_window_event`.
    pub(crate) fn unregister_window_event(event_name: &str, handler_id: usize) {
        let registry: &mut WindowEventRegistryMap = Self::get_mut_window_registry();
        if let Some(handlers) = registry.get_mut(event_name) {
            handlers.retain(|(id, ptr): &WindowEventHandlerEntry| {
                if *id == handler_id {
                    unsafe {
                        let _: Box<Box<dyn FnMut()>> = Box::from_raw(*ptr);
                    }
                    false
                } else {
                    true
                }
            });
        }
    }

    /// Ensures a single `window.addEventListener` listener is registered
    /// for the given event name that dispatches to all registered callbacks.
    ///
    /// # Arguments
    ///
    /// - `&str` - The event name to register the listener for.
    fn window_event_listener(event_name: &str) {
        let event_name_owned: String = event_name.to_string();
        let closure: Closure<dyn FnMut()> = Closure::wrap(Box::new(move || {
            let handler_ids: Vec<usize> = match Self::get_window_registry().get(&event_name_owned) {
                Some(handlers) => handlers.iter().map(|(id, _ptr)| *id).collect(),
                None => return,
            };
            for handler_id in handler_ids {
                let callback_ptr: *mut Box<dyn FnMut() + 'static> =
                    match Self::get_window_registry().get(&event_name_owned) {
                        Some(handlers) => {
                            match handlers.iter().find(|(id, _ptr)| *id == handler_id) {
                                Some((_id, ptr)) => *ptr,
                                None => continue,
                            }
                        }
                        None => return,
                    };
                let callback: &mut Box<dyn FnMut() + 'static> = unsafe { &mut *callback_ptr };
                callback();
            }
        }));
        let window: Window = match window() {
            Some(window_instance) => window_instance,
            None => return,
        };
        let _: Result<(), JsValue> =
            window.add_event_listener_with_callback(event_name, closure.as_ref().unchecked_ref());
        closure.forget();
    }
}