dioxus_lib::prelude

Struct VirtualDom

source
pub struct VirtualDom { /* private fields */ }
Expand description

A virtual node system that progresses user events and diffs UI trees.

§Guide

Components are defined as simple functions that take crate::properties::Properties and return an Element.


#[derive(Props, PartialEq, Clone)]
struct AppProps {
    title: String
}

fn app(cx: AppProps) -> Element {
    rsx!(
        div {"hello, {cx.title}"}
    )
}

Components may be composed to make complex apps.



static ROUTES: &str = "";

#[component]
fn app(cx: AppProps) -> Element {
    rsx!(
        NavBar { routes: ROUTES }
        Title { "{cx.title}" }
        Footer {}
    )
}

#[component]
fn NavBar( routes: &'static str) -> Element {
    rsx! {
        div { "Routes: {routes}" }
    }
}

#[component]
fn Footer() -> Element {
    rsx! { div { "Footer" } }
}

#[component]
fn Title( children: Element) -> Element {
    rsx! {
        div { id: "title", {children} }
    }
}

To start an app, create a VirtualDom and call VirtualDom::rebuild to get the list of edits required to draw the UI.


let mut vdom = VirtualDom::new(app);
let edits = vdom.rebuild_to_vec();

To call listeners inside the VirtualDom, call Runtime::handle_event with the appropriate event data.

let event = Event::new(std::rc::Rc::new(0) as std::rc::Rc<dyn std::any::Any>, true);
runtime.handle_event("onclick", event, ElementId(0));

While no events are ready, call VirtualDom::wait_for_work to poll any futures inside the VirtualDom.

tokio::runtime::Runtime::new().unwrap().block_on(async {
    vdom.wait_for_work().await;
});

Once work is ready, call VirtualDom::render_immediate to compute the differences between the previous and current UI trees. This will write edits to a WriteMutations object you pass in that contains with edits that need to be handled by the renderer.

let mut mutations = Mutations::default();

vdom.render_immediate(&mut mutations);

To not wait for suspense while diffing the VirtualDom, call VirtualDom::render_immediate.

§Building an event loop around Dioxus:

Putting everything together, you can build an event loop around Dioxus by using the methods outlined above.

let mut real_dom = RealDom::new();

#[component]
fn app() -> Element {
    rsx! {
        div { "Hello World" }
    }
}

let mut dom = VirtualDom::new(app);

dom.rebuild(&mut real_dom.apply());

loop {
    tokio::select! {
        _ = dom.wait_for_work() => {}
        evt = real_dom.wait_for_event() => {
            let evt = dioxus_core::Event::new(evt, true);
            dom.runtime().handle_event("onclick", evt, ElementId(0))
        },
    }

    dom.render_immediate(&mut real_dom.apply());
}

§Waiting for suspense

Because Dioxus supports suspense, you can use it for server-side rendering, static site generation, and other use cases where waiting on portions of the UI to finish rendering is important. To wait for suspense, use the VirtualDom::wait_for_suspense method:

tokio::runtime::Runtime::new().unwrap().block_on(async {
    let mut dom = VirtualDom::new(app);

    dom.rebuild_in_place();
    dom.wait_for_suspense().await;
});

// Render the virtual dom

Implementations§

source§

impl VirtualDom

source

pub fn new(app: fn() -> Result<VNode, RenderError>) -> VirtualDom

Create a new VirtualDom with a component that does not have special props.

§Description

Later, the props can be updated by calling “update” with a new set of props, causing a set of re-renders.

This is useful when a component tree can be driven by external state (IE SSR) but it would be too expensive to toss out the entire tree.

§Example
fn Example() -> Element  {
    rsx!( div { "hello world" } )
}

let dom = VirtualDom::new(Example);

Note: the VirtualDom is not progressed, you must either “run_with_deadline” or use “rebuild” to progress it.

source

pub fn new_with_props<P, M>( root: impl ComponentFunction<P, M>, root_props: P, ) -> VirtualDom
where P: Clone + 'static, M: 'static,

Create a new VirtualDom with the given properties for the root component.

§Description

Later, the props can be updated by calling “update” with a new set of props, causing a set of re-renders.

This is useful when a component tree can be driven by external state (IE SSR) but it would be too expensive to toss out the entire tree.

§Example
#[derive(PartialEq, Props, Clone)]
struct SomeProps {
    name: &'static str
}

fn Example(cx: SomeProps) -> Element  {
    rsx! { div { "hello {cx.name}" } }
}

let dom = VirtualDom::new_with_props(Example, SomeProps { name: "world" });

Note: the VirtualDom is not progressed on creation. You must either “run_with_deadline” or use “rebuild” to progress it.

let mut dom = VirtualDom::new_with_props(Example, SomeProps { name: "jane" });
dom.rebuild_in_place();
source

pub fn prebuilt(app: fn() -> Result<VNode, RenderError>) -> VirtualDom

Create a new virtualdom and build it immediately

source

pub fn get_scope(&self, id: ScopeId) -> Option<&ScopeState>

Get the state for any scope given its ID

This is useful for inserting or removing contexts from a scope, or rendering out its root node

source

pub fn base_scope(&self) -> &ScopeState

Get the single scope at the top of the VirtualDom tree that will always be around

This scope has a ScopeId of 0 and is the root of the tree

source

pub fn in_runtime<O>(&self, f: impl FnOnce() -> O) -> O

Run a closure inside the dioxus runtime

source

pub fn with_root_context<T>(self, context: T) -> VirtualDom
where T: Clone + 'static,

Build the virtualdom with a global context inserted into the base scope

This is useful for what is essentially dependency injection when building the app

source

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

Provide a context to the root scope

source

pub fn insert_any_root_context(&mut self, context: Box<dyn Any>)

Build the virtualdom with a global context inserted into the base scope

This method is useful for when you want to provide a context in your app without knowing its type

source

pub fn mark_dirty(&mut self, id: ScopeId)

Manually mark a scope as requiring a re-render

Whenever the Runtime “works”, it will re-render this scope

source

pub async fn wait_for_work(&mut self)

Wait for the scheduler to have any work.

This method polls the internal future queue, waiting for suspense nodes, tasks, or other work. This completes when any work is ready. If multiple scopes are marked dirty from a task or a suspense tree is finished, this method will exit.

This method is cancel-safe, so you’re fine to discard the future in a select block.

This lets us poll async tasks and suspended trees during idle periods without blocking the main thread.

§Example
let dom = VirtualDom::new(app);
source

pub fn process_events(&mut self)

Process all events in the queue until there are no more left

source

pub fn rebuild_in_place(&mut self)

Rebuild the virtualdom without handling any of the mutations

This is useful for testing purposes and in cases where you render the output of the virtualdom without handling any of its mutations.

source

pub fn rebuild_to_vec(&mut self) -> Mutations

VirtualDom::rebuild to a vector of mutations for testing purposes

source

pub fn rebuild(&mut self, to: &mut impl WriteMutations)

Performs a full rebuild of the virtual dom, returning every edit required to generate the actual dom from scratch.

The mutations item expects the RealDom’s stack to be the root of the application.

Tasks will not be polled with this method, nor will any events be processed from the event queue. Instead, the root component will be run once and then diffed. All updates will flow out as mutations.

All state stored in components will be completely wiped away.

Any templates previously registered will remain.

§Example
fn app() -> Element {
    rsx! { "hello world" }
}

let mut dom = VirtualDom::new(app);
let mut mutations = Mutations::default();
dom.rebuild(&mut mutations);
source

pub fn render_immediate(&mut self, to: &mut impl WriteMutations)

Render whatever the VirtualDom has ready as fast as possible without requiring an executor to progress suspended subtrees.

source

pub fn render_immediate_to_vec(&mut self) -> Mutations

Self::render_immediate to a vector of mutations for testing purposes

source

pub async fn wait_for_suspense(&mut self)

Render the virtual dom, waiting for all suspense to be finished

The mutations will be thrown out, so it’s best to use this method for things like SSR that have async content

We don’t call “flush_sync” here since there’s no sync work to be done. Futures will be progressed like usual, however any futures waiting on flush_sync will remain pending

source

pub fn suspended_tasks_remaining(&self) -> bool

Check if there are any suspended tasks remaining

source

pub async fn wait_for_suspense_work(&mut self)

Wait for the scheduler to have any work that should be run during suspense.

source

pub async fn render_suspense_immediate(&mut self) -> Vec<ScopeId>

Render any dirty scopes immediately, but don’t poll any futures that are client only on that scope Returns a list of suspense boundaries that were resolved

source

pub fn runtime(&self) -> Rc<Runtime>

Get the current runtime

source

pub fn handle_event( &self, name: &str, event: Rc<dyn Any>, element: ElementId, bubbling: bool, )

👎Deprecated: Use [VirtualDom::runtime().handle_event] instead

Handle an event with the Virtual Dom. This method is deprecated in favor of [VirtualDom::runtime().handle_event] and will be removed in a future release.

Trait Implementations§

source§

impl Drop for VirtualDom

source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where 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.

source§

impl<T> InitializeFromFunction<T> for T

source§

fn initialize_from_function(f: fn() -> T) -> T

Create an instance of this type from an initialization function
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 T
where 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.

source§

impl<Ret> SpawnIfAsync<(), Ret> for Ret

source§

fn spawn(self) -> Ret

Spawn the value into the dioxus runtime if it is an async block
source§

impl<T, O> SuperFrom<T> for O
where O: From<T>,

source§

fn super_from(input: T) -> O

Convert from a type to another type.
source§

impl<T, O, M> SuperInto<O, M> for T
where O: SuperFrom<T, M>,

source§

fn super_into(self) -> O

Convert from a type to another type.
source§

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

source§

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 T
where U: TryFrom<T>,

source§

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.
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