Skip to content

Commit

Permalink
feat: add NodeRef::on_load() and writeable NodeRef (#3305)
Browse files Browse the repository at this point in the history
  • Loading branch information
gbj authored Nov 30, 2024
1 parent d2803c9 commit be740b3
Showing 1 changed file with 53 additions and 1 deletion.
54 changes: 53 additions & 1 deletion tachys/src/reactive_graph/node_ref.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
use crate::html::{element::ElementType, node_ref::NodeRefContainer};
use reactive_graph::{
effect::Effect,
signal::{
guards::{Derefable, ReadGuard},
RwSignal,
},
traits::{DefinedAt, ReadUntracked, Set, Track},
traits::{
DefinedAt, Get, Notify, ReadUntracked, Set, Track, UntrackableGuard,
Write,
},
};
use send_wrapper::SendWrapper;
use std::{cell::Cell, ops::DerefMut};
use wasm_bindgen::JsCast;

/// A reactive reference to a DOM node that can be used with the `node_ref` attribute.
Expand All @@ -26,6 +31,25 @@ where
pub fn new() -> Self {
Self(RwSignal::new(None))
}

/// Runs the provided closure when the `NodeRef` has been connected
/// with its element.
#[inline(always)]
pub fn on_load<F>(self, f: F)
where
E: 'static,
F: FnOnce(E::Output) + 'static,
E: ElementType,
E::Output: JsCast + Clone + 'static,
{
let f = Cell::new(Some(f));

Effect::new(move |_| {
if let Some(node_ref) = self.get() {
f.take().unwrap()(node_ref);
}
});
}
}

impl<E> Default for NodeRef<E>
Expand Down Expand Up @@ -78,6 +102,34 @@ where
}
}

impl<E> Notify for NodeRef<E>
where
E: ElementType,
E::Output: JsCast + Clone + 'static,
{
fn notify(&self) {
self.0.notify();
}
}

impl<E> Write for NodeRef<E>
where
E: ElementType,
E::Output: JsCast + Clone + 'static,
{
type Value = Option<SendWrapper<E::Output>>;

fn try_write(&self) -> Option<impl UntrackableGuard<Target = Self::Value>> {
self.0.try_write()
}

fn try_write_untracked(
&self,
) -> Option<impl DerefMut<Target = Self::Value>> {
self.0.try_write_untracked()
}
}

impl<E> ReadUntracked for NodeRef<E>
where
E: ElementType,
Expand Down

0 comments on commit be740b3

Please sign in to comment.