Struct ambient_element::Hooks

source ·
pub struct Hooks<'a> { /* private fields */ }
Expand description

Hooks are a way to hook into the state and lifecycle of an Element.

They are inspired by React hooks.

Using hooks, you can store state, interact with the world, and generally do operations that go beyond the pure rendering of an Element.

Implementations§

source§

impl<'a> Hooks<'a>

source

pub fn use_state<T: Clone + Debug + Send + 'static>( &mut self, init: T ) -> (T, Setter<T>)

Preserve state between rerenders.

The state can be mutated by the setter, which will re-render the origin Element.

Note: The new value set by the returned setter won’t be visible until the next re-render.

let (value, setter) = hooks.use_state(5);

setter(7);

println!("{value}"); // Prints 5
source

pub fn use_state_with<T: Clone + Debug + Send + 'static, F: FnOnce(&mut World) -> T>( &mut self, init: F ) -> (T, Setter<T>)

The same as Hooks::use_state, but with a function that returns the initial value.

This can be used to avoid cloning the initial value each time the Element is re-rendered.

source

pub fn use_rerender_signal(&mut self) -> Cb<dyn Fn() + Sync + Send>

Provides a function that, when called, will cause this Element to be re-rendered.

source

pub fn provide_context<T: Clone + Debug + Send + Sync + 'static>( &mut self, default_value: impl FnOnce() -> T ) -> Setter<T>

Provide a value which is accessible to all children further down the tree.

Note: This hook does not rely on order, and is therefore safe to use inside conditionals.

source

pub fn consume_context<T: Clone + Debug + Sync + Send + 'static>( &mut self ) -> Option<(T, Setter<T>)>

Consume a context of type T provided further up the tree.

To provide context, use Self::provide_context.

source

pub fn use_spawn<F: FnOnce(&mut World) -> R + Sync + Send + 'static, R: FnOnce(&mut World) + Sync + Send + 'static>( &mut self, func: F )

Execute a function when the Element is mounted/rendered for the first time.

The function should return another function; that function will be called when the Element is unmounted.

source

pub fn use_runtime_message<T: RuntimeMessage>( &mut self, func: impl Fn(&mut World, &T) + Sync + Send + 'static )

Register a function to be called when a [RuntimeMessage] is received.

The subscription will be automatically cancelled when this Element is unmounted.

source

pub fn use_task<Fut: Future<Output = ()> + Send + 'static>( &mut self, task: impl FnOnce(&mut World) -> Fut + Send + Sync + 'static )

Spawns the provided future as a task.

The task is aborted when this Element is removed.

source

pub fn use_async<T, U>( &mut self, future: impl FnOnce(&mut World) -> T + Send + Sync + 'static ) -> Option<U>where T: Future<Output = U> + Send + 'static, U: Debug + ComponentValue,

Use a value provided by a future.

Returns None until the future completes.

Automatically triggers a re-render on this Element when the future completes.

source

pub fn use_memo_async<T, F, D, U>(&mut self, deps: D, init: F) -> Option<T>where F: FnOnce(&mut World, D) -> U, U: 'static + Future<Output = T> + Send, T: ComponentValue, D: PartialEq + ComponentValue,

Use memoized state dependent on a future

source

pub fn use_frame<F: Fn(&mut World) + Sync + Send + 'static>( &mut self, on_frame: F )

Executes a function each frame.

source

pub fn use_ref_with<T: Send + Debug + 'static>( &mut self, init: impl FnOnce(&mut World) -> T ) -> Arc<Mutex<T>>

Provides internally mutable state that is preserved between re-renders.

This should be used over Self::use_state when reference semantics are required for the state as opposed to value semantics.

Note: Locking the mutex and modifying the value won’t cause a re-render. To re-render the element, use Self::use_rerender_signal.

source

pub fn use_memo_with<T: Clone + ComponentValue + Debug + Sync + Send + 'static, D: PartialEq + Clone + Sync + Send + Debug + 'static>( &mut self, dependencies: D, compute: impl FnOnce(&mut World, &D) -> T ) -> T

A computation that runs once on spawn, and when dependencies change. The computation is not re-run if the dependencies are the same - that is, the computation is memoized.

Note: using external captures for the create function will not cause the memoized value to be recalculated when the captures change.

Prefer to route as much as possible through the dependencies; these dependencies are available as arguments to compute.

source

pub fn use_effect<D: PartialEq + Debug + Sync + Send + 'static, R: FnOnce(&mut World) + Sync + Send + 'static>( &mut self, dependencies: D, run: impl FnOnce(&mut World, &D) -> R + Sync + Send )

Run a function for its side effects each time a dependency changes.

The function should return another function; that function will be called when the Element is unmounted.

source

pub fn use_system<'b, R: ComponentQuery<'b> + Clone + 'static, F: Fn(&TypedReadQuery<R>, &mut World, Option<&mut QueryState>, &FrameEvent) + Send + Sync + 'static>( &mut self, query: TypedReadQuery<R>, run: F )

Run a native system each frame

source

pub fn use_interval<F: Fn() + Sync + Send + 'static>( &mut self, seconds: f32, cb: F )

Run cb every seconds seconds.

If your cb depends on some state, consider using Self::use_interval_deps instead. This function will capture the state at the time it is called, and will not update if the state changes.

source

pub fn use_interval_deps<D>( &mut self, duration: Duration, run_immediately: bool, dependencies: D, func: impl 'static + Send + Sync + FnMut(&D) )where D: 'static + Send + Sync + Clone + Debug + PartialEq,

Run cb every duration, passing in the current value of dependencies.

This should be used when the callback depends on some value that can change over time.

source

pub fn instance_id(&self) -> &str

Instance ID is a unique ID for this instance of the component. It is used to identify the component for updates. It is not the same as the entity ID.

Auto Trait Implementations§

§

impl<'a> !RefUnwindSafe for Hooks<'a>

§

impl<'a> Send for Hooks<'a>

§

impl<'a> !Sync for Hooks<'a>

§

impl<'a> Unpin for Hooks<'a>

§

impl<'a> !UnwindSafe for Hooks<'a>

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> AsAny for Twhere T: Any,

source§

fn as_any(&self) -> &(dyn Any + 'static)

source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

source§

fn type_name(&self) -> &'static str

Gets the type name of self
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> Downcast<T> for T

§

fn downcast(&self) -> &T

§

impl<T> Downcast for Twhere T: Any,

§

fn into_any(self: Box<T, Global>) -> Box<dyn Any + 'static, Global>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any + 'static>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
source§

impl<T> ElementComponentName for T

source§

fn element_component_name(&self) -> &'static str

Returns the name of the type implementing ElementComponent.
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> Pointable for T

§

const ALIGN: usize = mem::align_of::<T>()

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> Upcast<T> for T

§

fn upcast(&self) -> Option<&T>

§

impl<V, T> VZip<V> for Twhere V: MultiLane<T>,

§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more