Struct freya::prelude::VirtualDom

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 Scope and return an Element.


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

fn App(cx: Scope<AppProps>) -> Element {
    cx.render(rsx!(
        div {"hello, {cx.props.title}"}
    ))
}

Components may be composed to make complex apps.



static ROUTES: &str = "";

fn App(cx: Scope<AppProps>) -> Element {
    cx.render(rsx!(
        NavBar { routes: ROUTES }
        Title { "{cx.props.title}" }
        Footer {}
    ))
}

#[inline_props]
fn NavBar(cx: Scope, routes: &'static str) -> Element {
    cx.render(rsx! {
        div { "Routes: {routes}" }
    })
}

fn Footer(cx: Scope) -> Element {
    cx.render(rsx! { div { "Footer" } })
}

#[inline_props]
fn Title<'a>(cx: Scope<'a>, children: Element<'a>) -> Element {
    cx.render(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 call listeners inside the VirtualDom, call VirtualDom::handle_event with the appropriate event data.

vdom.handle_event(event);

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

vdom.wait_for_work().await;

Once work is ready, call VirtualDom::render_with_deadline to compute the differences between the previous and current UI trees. This will return a [Mutations] object that contains Edits, Effects, and NodeRefs that need to be handled by the renderer.

let mutations = vdom.work_with_deadline(tokio::time::sleep(Duration::from_millis(100)));

for edit in mutations.edits {
    real_dom.apply(edit);
}

To not wait for suspense while diffing the VirtualDom, call VirtualDom::render_immediate or pass an immediately ready future to VirtualDom::render_with_deadline.

Building an event loop around Dioxus:

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

fn app(cx: Scope) -> Element {
    cx.render(rsx! {
        div { "Hello World" }
    })
}

let dom = VirtualDom::new(app);

real_dom.apply(dom.rebuild());

loop {
    select! {
        _ = dom.wait_for_work() => {}
        evt = real_dom.wait_for_event() => dom.handle_event(evt),
    }

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

Waiting for suspense

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

let dom = VirtualDom::new(app);

let deadline = tokio::time::sleep(Duration::from_millis(100));
let edits = dom.render_with_deadline(deadline).await;

Use with streaming

If not all rendering is done by the deadline, it might be worthwhile to stream the rest later. To do this, we suggest rendering with a deadline, and then looping between VirtualDom::wait_for_work and render_immediate until no suspended work is left.

let dom = VirtualDom::new(app);

let deadline = tokio::time::sleep(Duration::from_millis(20));
let edits = dom.render_with_deadline(deadline).await;

real_dom.apply(edits);

while dom.has_suspended_work() {
   dom.wait_for_work().await;
   real_dom.apply(dom.render_immediate());
}

Implementations§

§

impl VirtualDom

pub fn new(app: fn(_: &Scoped<'_, ()>) -> Option<VNode<'_>>) -> 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(cx: Scope) -> Element  {
    cx.render(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.

pub fn new_with_props<P>( root: fn(_: &Scoped<'_, P>) -> Option<VNode<'_>>, root_props: P ) -> VirtualDomwhere P: '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)]
struct SomeProps {
    name: &'static str
}

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

let dom = VirtualDom::new(Example);

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" });
let mutations = dom.rebuild();

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

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

pub fn with_root_context<T>(self, context: T) -> VirtualDomwhere 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

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

Manually mark a scope as requiring a re-render

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

pub fn is_scope_suspended(&self, id: ScopeId) -> bool

Determine whether or not a scope is currently in a suspended state

This does not mean the scope is waiting on its own futures, just that the tree that the scope exists in is currently suspended.

pub fn has_suspended_work(&self) -> bool

Determine if the tree is at all suspended. Used by SSR and other outside mechanisms to determine if the tree is ready to be rendered.

pub fn handle_event( &mut self, name: &str, data: Rc<dyn Any + 'static>, element: ElementId, bubbles: bool )

Call a listener inside the VirtualDom with data from outside the VirtualDom.

This method will identify the appropriate element. The data must match up with the listener delcared. Note that this method does not give any indication as to the success of the listener call. If the listener is not found, nothing will happen.

It is up to the listeners themselves to mark nodes as dirty.

If you have multiple events, you can call this method multiple times before calling “render_with_deadline”

pub async fn wait_for_work(&mut self) -> impl Future<Output = ()>

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);
let sender = dom.get_scheduler_channel();

pub fn process_events(&mut self)

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

pub fn replace_template(&mut self, template: Template<'static>)

Replace a template at runtime. This will re-render all components that use this template. This is the primitive that enables hot-reloading.

The caller must ensure that the template refrences the same dynamic attributes and nodes as the original template.

This will only replace the the parent template, not any nested templates.

pub fn rebuild(&mut self) -> Mutations<'_>

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 ran 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
static App: Component = |cx|  cx.render(rsx!{ "hello world" });

let mut dom = VirtualDom::new();
let edits = dom.rebuild();

apply_edits(edits);

pub fn render_immediate(&mut self) -> Mutations<'_>

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

pub async fn render_with_deadline( &mut self, deadline: impl Future<Output = ()> ) -> impl Future<Output = Mutations<'_>>

Render what you can given the timeline and then move on

It’s generally a good idea to put some sort of limit on the suspense process in case a future is having issues.

If no suspense trees are present

Trait Implementations§

§

impl Drop for VirtualDom

§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

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,

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

const: unstable · source§

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

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

const: unstable · 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>,

const: unstable · 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.
const: unstable · 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.
const: unstable · 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

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