Struct freya::prelude::Scoped

pub struct Scoped<'a, T = ()> {
    pub scope: &'a ScopeState,
    pub props: &'a T,
}
Expand description

A wrapper around a component’s ScopeState and properties. The ScopeState provides the majority of methods for the VirtualDom and component state.

Fields§

§scope: &'a ScopeState

The component’s state and handle to the scheduler.

Stores things like the custom bump arena, spawn functions, hooks, and the scheduler.

§props: &'a T

The component’s properties.

Methods from Deref<Target = &'a ScopeState>§

pub fn name(&self) -> &str

Get the name of this component

pub fn generation(&self) -> usize

Get the current render since the inception of this component

This can be used as a helpful diagnostic when debugging hooks/renders, etc

pub fn bump(&self) -> &Bump

Get a handle to the currently active bump arena for this Scope

This is a bump memory allocator. Be careful using this directly since the contents will be wiped on the next render. It’s easy to leak memory here since the drop implementation will not be called for any objects allocated in this arena.

If you need to allocate items that need to be dropped, use bumpalo’s box.

pub fn root_node(&self) -> &RenderReturn<'_>

Get a handle to the currently active head node arena for this Scope

This is useful for traversing the tree outside of the VirtualDom, such as in a custom renderer or in SSR.

Panics if the tree has not been built yet.

pub fn try_root_node(&self) -> Option<&RenderReturn<'_>>

Try to get a handle to the currently active head node arena for this Scope

This is useful for traversing the tree outside of the VirtualDom, such as in a custom renderer or in SSR.

Returns None if the tree has not been built yet.

pub fn height(&self) -> u32

Get the height of this Scope - IE the number of scopes above it.

A Scope with a height of 0 is the root scope - there are no other scopes above it.

Example
let mut dom = VirtualDom::new(|cx|  cx.render(rsx!{ div {} }));
dom.rebuild();

let base = dom.base_scope();

assert_eq!(base.height(), 0);

pub fn parent(&self) -> Option<ScopeId>

Get the Parent of this Scope within this Dioxus crate::VirtualDom.

This ID is not unique across Dioxus crate::VirtualDoms or across time. IDs will be reused when components are unmounted.

The base component will not have a parent, and will return None.

Example
let mut dom = VirtualDom::new(|cx|  cx.render(rsx!{ div {} }));
dom.rebuild();

let base = dom.base_scope();

assert_eq!(base.parent(), None);

pub fn scope_id(&self) -> ScopeId

Get the ID of this Scope within this Dioxus crate::VirtualDom.

This ID is not unique across Dioxus crate::VirtualDoms or across time. IDs will be reused when components are unmounted.

Example
let mut dom = VirtualDom::new(|cx|  cx.render(rsx!{ div {} }));
dom.rebuild();
let base = dom.base_scope();

assert_eq!(base.scope_id(), 0);

pub fn schedule_update(&self) -> Arc<dyn Fn() + Sync + Send>

Create a subscription that schedules a future render for the reference component

Notice: you should prefer using Self::schedule_update_any and Self::scope_id

pub fn schedule_update_any(&self) -> Arc<dyn Fn(ScopeId) + Sync + Send>

Schedule an update for any component given its ScopeId.

A component’s ScopeId can be obtained from use_hook or the ScopeState::scope_id method.

This method should be used when you want to schedule an update for a component

pub fn needs_update(&self)

Mark this scope as dirty, and schedule a render for it.

pub fn needs_update_any(&self, id: ScopeId)

Get the ScopeId of a mounted component.

ScopeId is not unique for the lifetime of the crate::VirtualDom - a ScopeId will be reused if a component is unmounted.

pub fn has_context<T>(&self) -> Option<T>where T: 'static + Clone,

Return any context of type T if it exists on this scope

pub fn consume_context<T>(&self) -> Option<T>where T: 'static + Clone,

Try to retrieve a shared state with type T from any parent scope.

Clones the state if it exists.

pub fn provide_context<T>(&self, value: T) -> Twhere T: 'static + Clone,

Expose state to children further down the crate::VirtualDom Tree. Requires Clone on the context to allow getting values down the tree.

This is a “fundamental” operation and should only be called during initialization of a hook.

For a hook that provides the same functionality, use use_provide_context and use_context instead.

Example
struct SharedState(&'static str);

static App: Component = |cx| {
    cx.use_hook(|| cx.provide_context(SharedState("world")));
    render!(Child {})
}

static Child: Component = |cx| {
    let state = cx.consume_state::<SharedState>();
    render!(div { "hello {state.0}" })
}

pub fn provide_root_context<T>(&self, context: T) -> Twhere T: 'static + Clone,

Provide a context to the root and then consume it

This is intended for “global” state management solutions that would rather be implicit for the entire app. Things like signal runtimes and routers are examples of “singletons” that would benefit from lazy initialization.

Note that you should be checking if the context existed before trying to provide a new one. Providing a context when a context already exists will swap the context out for the new one, which may not be what you want.

pub fn push_future(&self, fut: impl Future<Output = ()> + 'static) -> TaskId

Pushes the future onto the poll queue to be polled after the component renders.

pub fn spawn(&self, fut: impl Future<Output = ()> + 'static)

Spawns the future but does not return the TaskId

pub fn spawn_forever(&self, fut: impl Future<Output = ()> + 'static) -> TaskId

Spawn a future that Dioxus won’t clean up when this component is unmounted

This is good for tasks that need to be run after the component has been dropped.

pub fn remove_future(&self, id: TaskId)

Informs the scheduler that this task is no longer needed and should be removed.

This drops the task immediately.

pub fn render(&'src self, rsx: LazyNodes<'src, '_>) -> Option<VNode<'src>>

Take a lazy crate::VNode structure and actually build it with the context of the efficient [bumpalo::Bump] allocator.

Example
fn Component(cx: Scope<Props>) -> Element {
    // Lazy assemble the VNode tree
    let lazy_nodes = rsx!("hello world");

    // Actually build the tree and allocate it
    cx.render(lazy_tree)
}

pub fn text_node(&'src self, args: Arguments<'_>) -> DynamicNode<'src>

Create a dynamic text node using Arguments and the ScopeState’s internal [Bump] allocator

pub fn raw_text(&'src self, args: Arguments<'_>) -> &'src str

Allocate some text inside the ScopeState from Arguments

Uses the currently active [Bump] allocator

pub fn make_node<'c, I>( &'src self, into: impl IntoDynNode<'src, I> + 'c ) -> DynamicNode<'src>

Convert any item that implements [IntoDynNode] into a [DynamicNode] using the internal [Bump] allocator

pub fn attr( &'src self, name: &'static str, value: impl IntoAttributeValue<'src>, namespace: Option<&'static str>, volatile: bool ) -> Attribute<'src>

Create a new [Attribute] from a name, value, namespace, and volatile bool

“Volatile” referes to whether or not Dioxus should always override the value. This helps prevent the UI in some renderers stay in sync with the VirtualDom’s understanding of the world

pub fn component<'child, P>( &'src self, component: fn(_: &'child Scoped<'child, P>) -> Option<VNode<'child>>, props: P, fn_name: &'static str ) -> DynamicNode<'src>where 'src: 'child, P: Properties + 'src,

Create a new [DynamicNode::Component] variant

The given component can be any of four signatures. Remember that an Element is really a Result<VNode>.

// Without explicit props
fn(Scope) -> Element;
async fn(Scope<'_>) -> Element;

// With explicit props
fn(Scope<Props>) -> Element;
async fn(Scope<Props<'_>>) -> Element;

pub fn event_handler<T>( &'src self, f: impl FnMut(T) + 'src ) -> EventHandler<'src, T>

Create a new [EventHandler] from an FnMut

pub fn listener<T>( &'src self, callback: impl FnMut(Event<T>) + 'src ) -> AttributeValue<'src>where T: 'static,

Create a new AttributeValue with the listener variant from a callback

The callback must be confined to the lifetime of the ScopeState

pub fn any_value<T>(&'src self, value: T) -> AttributeValue<'src>where T: AnyValue,

Create a new AttributeValue with a value that implements [AnyValue]

pub fn throw(&self, error: impl Debug + 'static) -> Option<()>

Inject an error into the nearest error boundary and quit rendering

The error doesn’t need to implement Error or any specific traits since the boundary itself will downcast the error into a trait object.

pub fn suspend(&self) -> Option<Option<VNode<'_>>>

Mark this component as suspended and then return None

pub fn use_hook<State>(&self, initializer: impl FnOnce() -> State) -> &mut Statewhere State: 'static,

Store a value between renders. The foundational hook for all other hooks.

Accepts an initializer closure, which is run on the first use of the hook (typically the initial render). The return value of this closure is stored for the lifetime of the component, and a mutable reference to it is provided on every render as the return value of use_hook.

When the component is unmounted (removed from the UI), the value is dropped. This means you can return a custom type and provide cleanup code by implementing the Drop trait

Example
use dioxus_core::ScopeState;

// prints a greeting on the initial render
pub fn use_hello_world(cx: &ScopeState) {
    cx.use_hook(|| println!("Hello, world!"));
}

Trait Implementations§

§

impl<'a, T> Deref for Scoped<'a, T>

§

type Target = &'a ScopeState

The resulting type after dereferencing.
§

fn deref(&self) -> &<Scoped<'a, T> as Deref>::Target

Dereferences the value.

Auto Trait Implementations§

§

impl<'a, T = ()> !RefUnwindSafe for Scoped<'a, T>

§

impl<'a, T = ()> !Send for Scoped<'a, T>

§

impl<'a, T = ()> !Sync for Scoped<'a, T>

§

impl<'a, T> Unpin for Scoped<'a, T>

§

impl<'a, T = ()> !UnwindSafe for Scoped<'a, T>

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> 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
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

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

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

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> Same<T> for T

§

type Output = T

Should always be Self
§

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

§

fn to<T>(self) -> Twhere Self: Into<T>,

Converts to T by calling Into<T>::into.
§

fn try_to<T>(self) -> Result<T, Self::Error>where Self: TryInto<T>,

Tries to convert to T by calling TryInto<T>::try_into.
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<V, T> VZip<V> for Twhere V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self>

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