Internationalization: move guide to en folder and preserve its history. (#494)
* chore: move guide to en folder * docs: add english as language
No files matched your search
@@ -0,0 +1,43 @@
|
||||
# Summary
|
||||
|
||||
[Introduction](index.md)
|
||||
|
||||
- [Getting Started](getting_started/index.md)
|
||||
- [Desktop](getting_started/desktop.md)
|
||||
- [Web](getting_started/web.md)
|
||||
- [Hot Reload](getting_started/hot_reload.md)
|
||||
- [Server-Side Rendering](getting_started/ssr.md)
|
||||
- [Terminal UI](getting_started/tui.md)
|
||||
- [Mobile](getting_started/mobile.md)
|
||||
- [Describing the UI](describing_ui/index.md)
|
||||
- [Special Attributes](describing_ui/special_attributes.md)
|
||||
- [Components](describing_ui/components.md)
|
||||
- [Props](describing_ui/component_props.md)
|
||||
- [Component Children](describing_ui/component_children.md)
|
||||
- [Interactivity](interactivity/index.md)
|
||||
- [Event Listeners](interactivity/event_handlers.md)
|
||||
- [Hooks & Component State](interactivity/hooks.md)
|
||||
- [User Input](interactivity/user_input.md)
|
||||
- [Sharing State](interactivity/sharing_state.md)
|
||||
- [Custom Hooks](interactivity/custom_hooks.md)
|
||||
- [Dynamic Rendering](interactivity/dynamic_rendering.md)
|
||||
- [Routing](interactivity/router.md)
|
||||
- [Async](async/index.md)
|
||||
- [UseFuture](async/use_future.md)
|
||||
- [UseCoroutine](async/use_coroutine.md)
|
||||
- [Spawning Futures](async/spawn.md)
|
||||
- [Best Practices](best_practices/index.md)
|
||||
- [Error Handling](best_practices/error_handling.md)
|
||||
- [Antipatterns](best_practices/antipatterns.md)
|
||||
- [Publishing](publishing/index.md)
|
||||
- [Desktop](publishing/desktop.md)
|
||||
- [Web](publishing/web.md)
|
||||
|
||||
-----------
|
||||
|
||||
- [Custom Renderer](custom_renderer/index.md)
|
||||
|
||||
-----------
|
||||
|
||||
[Roadmap](roadmap.md)
|
||||
[Contributing](contributing.md)
|
||||
@@ -0,0 +1,6 @@
|
||||
This directory includes:
|
||||
|
||||
- Very outdated docs
|
||||
- Docs for features which haven't been implemented (yet?)
|
||||
- Information which has already been covered in the guide in a more organized fashion
|
||||
- A few things yet to be integrated into the guide nicely
|
||||
@@ -0,0 +1,33 @@
|
||||
# Subscriptions
|
||||
|
||||
Yew subscriptions are used to schedule update for components into the future. The `Context` object can create subscriptions:
|
||||
|
||||
```rust
|
||||
fn Component(cx: Component) -> DomTree {
|
||||
let update = cx.schedule();
|
||||
|
||||
// Now, when the subscription is called, the component will be re-evaluated
|
||||
update.consume();
|
||||
}
|
||||
```
|
||||
|
||||
Whenever a component's subscription is called, the component will then re-evaluated. You can consider the input properties of
|
||||
a component to be just another form of subscription. By default, the Dioxus component system automatically diffs a component's props
|
||||
when the parent function is called, and if the props are different, the child component's subscription is called.
|
||||
|
||||
The subscription API exposes this functionality allowing hooks and state management solutions the ability to update components whenever
|
||||
some state or event occurs outside of the component. For instance, the `use_context` hook uses this to subscribe components that use a
|
||||
particular context.
|
||||
|
||||
```rust
|
||||
fn use_context<I>(cx: Scope<T>) -> I {
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
```
|
||||
@@ -0,0 +1,82 @@
|
||||
# Concurrent mode
|
||||
|
||||
Concurrent mode provides a mechanism for building efficient asynchronous components. With this feature, components don't need to render immediately, and instead can schedule a future render by returning a future.
|
||||
|
||||
To make a component asynchronous, simply change its function signature to async.
|
||||
|
||||
```rust
|
||||
fn Example(cx: Scope) -> Vnode {
|
||||
rsx!{ <div> "Hello world!" </div> }
|
||||
}
|
||||
```
|
||||
|
||||
becomes
|
||||
|
||||
```rust
|
||||
async fn Example(cx: Scope) -> Vnode {
|
||||
rsx!{ <div> "Hello world!" </div> }
|
||||
}
|
||||
```
|
||||
|
||||
Now, logic in components can be awaited to delay updates of the component and its children. Like so:
|
||||
|
||||
```rust
|
||||
async fn Example(cx: Scope) -> Vnode {
|
||||
let name = fetch_name().await;
|
||||
rsx!{ <div> "Hello {name}" </div> }
|
||||
}
|
||||
|
||||
async fetch_name() -> String {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
This component will only schedule its render once the fetch is complete. However, we _don't_ recommend using async/await directly in your components.
|
||||
|
||||
Async is a notoriously challenging yet rewarding tool for efficient tools. If not careful, locking and unlocking shared aspects of the component's context can lead to data races and panics. If a shared resource is locked while the component is awaiting, then other components can be locked or panic when trying to access the same resource. These rules are especially important when references to shared global state are accessed using the context object's lifetime. If mutable references to data captured immutably by the context are taken, then the component will panic, causing confusion.
|
||||
|
||||
Instead, we suggest using hooks and future combinators that can safely utilize the safeguards of the component's Context when interacting with async tasks.
|
||||
|
||||
As part of our Dioxus hooks crate, we provide a data loader hook which pauses a component until its async dependencies are ready. This caches requests, reruns the fetch if dependencies have changed, and provides the option to render something else while the component is loading.
|
||||
|
||||
```rust
|
||||
async fn ExampleLoader(cx: Scope) -> Vnode {
|
||||
/*
|
||||
Fetch, pause the component from rendering at all.
|
||||
|
||||
The component is locked while waiting for the request to complete
|
||||
While waiting, an alternate component is scheduled in its place.
|
||||
|
||||
This API stores the result on the Context object, so the loaded data is taken as reference.
|
||||
*/
|
||||
let name: &Result<SomeStructure> = use_fetch_data("http://example.com/json", ())
|
||||
.place_holder(|cx| rsx!{<div> "loading..." </div>})
|
||||
.delayed_place_holder(1000, |cx| rsx!{ <div> "still loading..." </div>})
|
||||
.await;
|
||||
|
||||
match name {
|
||||
Ok(name) => rsx! { <div> "Hello {something}" </div> },
|
||||
Err(e) => rsx! { <div> "An error occurred :(" </div>}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```rust
|
||||
async fn Example(cx: Scope) -> DomTree {
|
||||
// Diff this set between the last set
|
||||
// Check if we have any outstanding tasks?
|
||||
//
|
||||
// Eventually, render the component into the VDOM when the future completes
|
||||
<div>
|
||||
<Example />
|
||||
</div>
|
||||
|
||||
// Render a div, queue a component
|
||||
// Render the placeholder first, then when the component is ready, then render the component
|
||||
<div>
|
||||
<Suspense placeholder={html!{<div>"Loading"</div>}}>
|
||||
<Example />
|
||||
</Suspense>
|
||||
</div>
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,58 @@
|
||||
# Memoization and the arena allocator
|
||||
|
||||
Dioxus differs slightly from other UI virtual doms in some subtle ways due to its memory allocator.
|
||||
|
||||
One important aspect to understand is how props are passed down from parent components to children. All "components" (custom user-made UI elements) are tightly allocated together in an arena. However, because props and hooks are generically typed, they are casted to `Any` and allocated on the heap – not in the arena with the components.
|
||||
|
||||
With this system, we try to be more efficient when leaving the component arena and entering the heap. By default, props are memoized between renders using COW and context. This makes props comparisons fast – done via ptr comparisons on the cow pointer. Because memoization is done by default, parent re-renders will _not_ cascade to children if the child's props did not change.
|
||||
|
||||
https://dmitripavlutin.com/use-react-memo-wisely/
|
||||
|
||||
This behavior is defined as an attribute implicit to user components. When in React land you might wrap a component with `react.memo`, Dioxus components are automatically memoized via an implicit attribute. You can manually configure this behavior on any component with "nomemo" to disable memoization.
|
||||
|
||||
```rust
|
||||
fn test() -> DomTree {
|
||||
html! {
|
||||
<>
|
||||
<SomeComponent nomemo />
|
||||
// same as
|
||||
<SomeComponent nomemo=true />
|
||||
</>
|
||||
}
|
||||
}
|
||||
|
||||
static TestComponent: Component = |cx| html!{<div>"Hello world"</div>};
|
||||
|
||||
static TestComponent: Component = |cx|{
|
||||
let g = "BLAH";
|
||||
html! {
|
||||
<div> "Hello world" </div>
|
||||
}
|
||||
};
|
||||
|
||||
#[inline_props]
|
||||
fn test_component(cx: Scope, name: String) -> Element {
|
||||
rsx!(cx, "Hello, {name}")
|
||||
}
|
||||
```
|
||||
|
||||
## Why this behavior?
|
||||
|
||||
"This is different than React, why differ?".
|
||||
|
||||
Take a component like this:
|
||||
|
||||
```rust
|
||||
fn test(cx: Scope) -> DomTree {
|
||||
let Bundle { alpha, beta, gamma } = use_context::<SomeContext>(cx);
|
||||
html! {
|
||||
<div>
|
||||
<Component name=alpha />
|
||||
<Component name=beta />
|
||||
<Component name=gamma />
|
||||
</div>
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
While the contents of the destructured bundle might change, not every child component will need to be re-rendered every time the context changes.
|
||||
@@ -0,0 +1,155 @@
|
||||
# Signals: Skipping the Diff
|
||||
|
||||
In most cases, the traditional VirtualDOM diffing pattern is plenty fast. Dioxus will compare trees of VNodes, find the differences, and then update the Renderer's DOM with the diffs. However, this can generate a lot of overhead for certain types of components. In apps where reducing visual latency is a top priority, you can opt into the `Signals` api to entirely disable diffing of hot-path components. Dioxus will then automatically construct a state machine for your component, making updates nearly instant.
|
||||
|
||||
Signals build on the same infrastructure that powers asynchronous rendering where in-tree values can be updated outside of the render phase. In async rendering, a future is used as the signal source. With the raw signal API, any value can be used as a signal source.
|
||||
|
||||
By default, Dioxus will only try to diff subtrees of components with dynamic content, automatically skipping diffing static content.
|
||||
|
||||
## What does this look like?
|
||||
|
||||
Your component today might look something like this:
|
||||
|
||||
```rust
|
||||
fn Comp(cx: Scope) -> DomTree {
|
||||
let (title, set_title) = use_state(&cx, || "Title".to_string());
|
||||
cx.render(rsx!{
|
||||
input {
|
||||
value: title,
|
||||
onchange: move |new| set_title(new.value())
|
||||
}
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
This component is fairly straightforward – the input updates its own value on every change. However, every call to set_title will re-render the component. If we add a large list, then every time we update the title input, Dioxus will need to diff the entire list, over, and over, and over. This is **a lot** of wasted clock-cycles!
|
||||
|
||||
```rust
|
||||
fn Comp(cx: Scope) -> DomTree {
|
||||
let (title, set_title) = use_state(&cx, || "Title".to_string());
|
||||
cx.render(rsx!{
|
||||
div {
|
||||
input {
|
||||
value: title,
|
||||
onchange: move |new| set_title(new.value())
|
||||
}
|
||||
ul {
|
||||
{0..10000.map(|f| rsx!{
|
||||
li { "{f}" }
|
||||
})}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
Many experienced React developers will just say "this is bad design" – but we consider it to be a pit of failure, rather than a pit of success! That's why signals exist – to push you in a more performant (and ergonomic) direction. Signals let us directly bind values to their final place in the VirtualDOM. Whenever the signal value is updated, Dioxus will only the DOM nodes where that signal is used. Signals are built into Dioxus, so we can directly bind attributes of elements to their updates.
|
||||
|
||||
We can use signals to generate a two-way binding between data and the input box. Our text input is now just a two-line component!
|
||||
|
||||
```rust
|
||||
fn Comp(cx: Scope) -> DomTree {
|
||||
let mut title = use_signal(&cx, || String::from("Title"));
|
||||
cx.render(rsx!(input { value: title }))
|
||||
}
|
||||
```
|
||||
|
||||
For a slightly more interesting example, this component calculates the sum between two numbers, but totally skips the diffing process.
|
||||
|
||||
```rust
|
||||
fn Calculator(cx: Scope) -> DomTree {
|
||||
let mut a = use_signal(&cx, || 0);
|
||||
let mut b = use_signal(&cx, || 0);
|
||||
let mut c = a + b;
|
||||
rsx! {
|
||||
input { value: a }
|
||||
input { value: b }
|
||||
p { "a + b = {c}" }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Do you notice how we can use built-in operations on signals? Under the hood, we actually create a new derived signal that depends on `a` and `b`. Whenever `a` or `b` update, then `c` will update. If we need to create a new derived signal that's more complex than a basic operation (`std::ops`) we can either chain signals together or combine them:
|
||||
|
||||
```rust
|
||||
let mut a = use_signal(&cx, || 0);
|
||||
let mut b = use_signal(&cx, || 0);
|
||||
|
||||
// Chain signals together using the `with` method
|
||||
let c = a.with(b).map(|(a, b)| *a + *b);
|
||||
```
|
||||
|
||||
## Deref and DerefMut
|
||||
|
||||
If we ever need to get the value out of a signal, we can simply `deref` it.
|
||||
|
||||
```rust
|
||||
let mut a = use_signal(&cx, || 0);
|
||||
let c = *a + *b;
|
||||
```
|
||||
|
||||
Calling `deref` or `deref_mut` is actually more complex than it seems. When a value is derefed, you're essentially telling Dioxus that _this_ element _needs_ to be subscribed to the signal. If a signal is derefed outside of an element, the entire component will be subscribed and the advantage of skipping diffing will be lost. Dioxus will throw an error in the console when this happens to tell you that you're using signals wrong, but your component will continue to work.
|
||||
|
||||
## Global Signals
|
||||
|
||||
Sometimes you want a signal to propagate across your app, either through far-away siblings or through deeply-nested components. In these cases, we use Dirac: Dioxus's first-class state management toolkit. Dirac atoms automatically implement the Signal API. This component will bind the input element to the `TITLE` atom.
|
||||
|
||||
```rust
|
||||
const TITLE: Atom<String> = || "".to_string();
|
||||
const Provider: Component = |cx|{
|
||||
let title = use_signal(&cx, &TITLE);
|
||||
rsx!(cx, input { value: title })
|
||||
};
|
||||
```
|
||||
|
||||
If we use the `TITLE` atom in another component, we can cause updates to flow between components without calling render or diffing either component trees:
|
||||
|
||||
```rust
|
||||
const Receiver: Component = |cx|{
|
||||
let title = use_signal(&cx, &TITLE);
|
||||
log::info!("This will only be called once!");
|
||||
rsx!(cx,
|
||||
div {
|
||||
h1 { "{title}" }
|
||||
div {}
|
||||
footer {}
|
||||
}
|
||||
)
|
||||
};
|
||||
```
|
||||
|
||||
Dioxus knows that the receiver's `title` signal is used only in the text node, and skips diffing Receiver entirely, knowing to update _just_ the text node.
|
||||
|
||||
If you build a complex app on top of Dirac, you'll likely notice that many of your components simply won't be diffed at all. For instance, our Receiver component will never be diffed once it has been mounted!
|
||||
|
||||
## Signals and Iterators
|
||||
|
||||
Sometimes you want to use a collection of items. With Signals, you can bypass diffing for collections – a very powerful technique to avoid re-rendering on large collections.
|
||||
|
||||
By default, Dioxus is limited when you use iter/map. With the `For` component, you can provide an iterator and a function for the iterator to map to.
|
||||
|
||||
Dioxus automatically understands how to use your signals when mixed with iterators through `Deref`/`DerefMut`. This lets you efficiently map collections while avoiding the re-rendering of lists. In essence, signals act as a hint to Dioxus on how to avoid un-necessary checks and renders, making your app faster.
|
||||
|
||||
```rust
|
||||
const DICT: AtomFamily<String, String> = |_| {};
|
||||
const List: Component = |cx|{
|
||||
let dict = use_signal(&cx, &DICT);
|
||||
cx.render(rsx!(
|
||||
ul {
|
||||
For { each: dict, map: |k, v| rsx!( li { "{v}" }) }
|
||||
}
|
||||
))
|
||||
};
|
||||
```
|
||||
|
||||
## Remote Signals
|
||||
|
||||
Apps that use signals will enjoy a pleasant hybrid of server-side and client-side rendering.
|
||||
|
||||
```rust
|
||||
|
||||
```
|
||||
|
||||
## How does it work?
|
||||
|
||||
Signals internally use Dioxus' asynchronous rendering infrastructure to perform updates out of the tree.
|
||||
@@ -0,0 +1,54 @@
|
||||
# Subtrees
|
||||
|
||||
One way of extending the Dioxus VirtualDom is through the use of "Subtrees." Subtrees are chunks of the VirtualDom tree distinct from the rest of the tree. They still participate in event bubbling, diffing, etc, but will have a separate set of edits generated during the diff phase.
|
||||
|
||||
For a VirtualDom that has a root tree with two subtrees, the edits follow a pattern of:
|
||||
|
||||
Root
|
||||
-> Tree 1
|
||||
-> Tree 2
|
||||
-> Original root tree
|
||||
|
||||
- Root edits
|
||||
- Tree 1 Edits
|
||||
- Tree 2 Edits
|
||||
- Root Edits
|
||||
|
||||
The goal of this functionality is to enable things like Portals, Windows, and inline alternative renderers without needing to spin up a new VirtualDom.
|
||||
|
||||
With the right renderer plugins, a subtree could be rendered as anything – a 3D scene, SVG, or even as the contents of a new window or modal. This functionality is similar to "Portals" in React, but much more "renderer agnostic." Portals, by nature, are not necessarily cross-platform and rely on renderer functionality, so it makes sense to abstract their purpose into the subtree concept.
|
||||
|
||||
The desktop renderer comes pre-loaded with the window and notification subtree plugins, making it possible to render subtrees into entirely different windows.
|
||||
|
||||
Subtrees also solve the "bridging" issues in React where two different renderers need two different VirtualDoms to work properly. In Dioxus, you only ever need one VirtualDom and the right renderer plugins.
|
||||
|
||||
|
||||
## API
|
||||
|
||||
Due to their importance in the hierarchy, Components – not nodes – are treated as subtree roots.
|
||||
|
||||
|
||||
```rust
|
||||
|
||||
fn Subtree<P>(cx: Scope<P>) -> DomTree {
|
||||
|
||||
}
|
||||
|
||||
fn Window() -> DomTree {
|
||||
Subtree {
|
||||
onassign: move |e| {
|
||||
// create window
|
||||
}
|
||||
children()
|
||||
}
|
||||
}
|
||||
|
||||
fn 3dRenderer -> DomTree {
|
||||
Subtree {
|
||||
onassign: move |e| {
|
||||
// initialize bevy
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
@@ -0,0 +1,272 @@
|
||||
# Custom Renderer
|
||||
|
||||
Dioxus is an incredibly portable framework for UI development. The lessons, knowledge, hooks, and components you acquire over time can always be used for future projects. However, sometimes those projects cannot leverage a supported renderer or you need to implement your own better renderer.
|
||||
|
||||
Great news: the design of the renderer is entirely up to you! We provide suggestions and inspiration with the 1st party renderers, but only really require implementation of the `RealDom` trait for things to function properly.
|
||||
|
||||
## The specifics:
|
||||
|
||||
Implementing the renderer is fairly straightforward. The renderer needs to:
|
||||
|
||||
1. Handle the stream of edits generated by updates to the virtual DOM
|
||||
2. Register listeners and pass events into the virtual DOM's event system
|
||||
3. Progress the virtual DOM with an async executor (or disable the suspense API and use `progress_sync`)
|
||||
|
||||
Essentially, your renderer needs to implement the `RealDom` trait and generate `EventTrigger` objects to update the VirtualDOM. From there, you'll have everything needed to render the VirtualDOM to the screen.
|
||||
|
||||
Internally, Dioxus handles the tree relationship, diffing, memory management, and the event system, leaving as little as possible required for renderers to implement themselves.
|
||||
|
||||
For reference, check out the WebSys renderer as a starting point for your custom renderer.
|
||||
|
||||
## Trait implementation and DomEdits
|
||||
|
||||
The current `RealDom` trait lives in `dioxus-core/diff`. A version of it is provided here (but might not be up-to-date):
|
||||
|
||||
```rust
|
||||
pub trait RealDom<'a> {
|
||||
fn handle_edit(&mut self, edit: DomEdit);
|
||||
fn request_available_node(&mut self) -> ElementId;
|
||||
fn raw_node_as_any(&self) -> &mut dyn Any;
|
||||
}
|
||||
```
|
||||
|
||||
For reference, the "DomEdit" type is a serialized enum that represents an atomic operation occurring on the RealDom. The variants roughly follow this set:
|
||||
|
||||
```rust
|
||||
enum DomEdit {
|
||||
PushRoot,
|
||||
AppendChildren,
|
||||
ReplaceWith,
|
||||
CreateTextNode,
|
||||
CreateElement,
|
||||
CreateElementNs,
|
||||
CreatePlaceholder,
|
||||
NewEventListener,
|
||||
RemoveEventListener,
|
||||
SetText,
|
||||
SetAttribute,
|
||||
RemoveAttribute,
|
||||
}
|
||||
```
|
||||
|
||||
The Dioxus diffing mechanism operates as a [stack machine](https://en.wikipedia.org/wiki/Stack_machine) where the "push_root" method pushes a new "real" DOM node onto the stack and "append_child" and "replace_with" both remove nodes from the stack.
|
||||
|
||||
|
||||
### An example
|
||||
|
||||
For the sake of understanding, lets consider this example – a very simple UI declaration:
|
||||
|
||||
```rust
|
||||
rsx!( h1 {"hello world"} )
|
||||
```
|
||||
|
||||
To get things started, Dioxus must first navigate to the container of this h1 tag. To "navigate" here, the internal diffing algorithm generates the DomEdit `PushRoot` where the ID of the root is the container.
|
||||
|
||||
When the renderer receives this instruction, it pushes the actual Node onto its own stack. The real renderer's stack will look like this:
|
||||
|
||||
```rust
|
||||
instructions: [
|
||||
PushRoot(Container)
|
||||
]
|
||||
stack: [
|
||||
ContainerNode,
|
||||
]
|
||||
```
|
||||
|
||||
Next, Dioxus will encounter the h1 node. The diff algorithm decides that this node needs to be created, so Dioxus will generate the DomEdit `CreateElement`. When the renderer receives this instruction, it will create an unmounted node and push into its own stack:
|
||||
|
||||
```rust
|
||||
instructions: [
|
||||
PushRoot(Container),
|
||||
CreateElement(h1),
|
||||
]
|
||||
stack: [
|
||||
ContainerNode,
|
||||
h1,
|
||||
]
|
||||
```
|
||||
Next, Dioxus sees the text node, and generates the `CreateTextNode` DomEdit:
|
||||
```rust
|
||||
instructions: [
|
||||
PushRoot(Container),
|
||||
CreateElement(h1),
|
||||
CreateTextNode("hello world")
|
||||
]
|
||||
stack: [
|
||||
ContainerNode,
|
||||
h1,
|
||||
"hello world"
|
||||
]
|
||||
```
|
||||
Remember, the text node is not attached to anything (it is unmounted) so Dioxus needs to generate an Edit that connects the text node to the h1 element. It depends on the situation, but in this case we use `AppendChildren`. This pops the text node off the stack, leaving the h1 element as the next element in line.
|
||||
|
||||
```rust
|
||||
instructions: [
|
||||
PushRoot(Container),
|
||||
CreateElement(h1),
|
||||
CreateTextNode("hello world"),
|
||||
AppendChildren(1)
|
||||
]
|
||||
stack: [
|
||||
ContainerNode,
|
||||
h1
|
||||
]
|
||||
```
|
||||
We call `AppendChildren` again, popping off the h1 node and attaching it to the parent:
|
||||
```rust
|
||||
instructions: [
|
||||
PushRoot(Container),
|
||||
CreateElement(h1),
|
||||
CreateTextNode("hello world"),
|
||||
AppendChildren(1),
|
||||
AppendChildren(1)
|
||||
]
|
||||
stack: [
|
||||
ContainerNode,
|
||||
]
|
||||
```
|
||||
Finally, the container is popped since we don't need it anymore.
|
||||
```rust
|
||||
instructions: [
|
||||
PushRoot(Container),
|
||||
CreateElement(h1),
|
||||
CreateTextNode("hello world"),
|
||||
AppendChildren(1),
|
||||
AppendChildren(1),
|
||||
Pop(1)
|
||||
]
|
||||
stack: []
|
||||
```
|
||||
Over time, our stack looked like this:
|
||||
```rust
|
||||
[]
|
||||
[Container]
|
||||
[Container, h1]
|
||||
[Container, h1, "hello world"]
|
||||
[Container, h1]
|
||||
[Container]
|
||||
[]
|
||||
```
|
||||
|
||||
Notice how our stack is empty once UI has been mounted. Conveniently, this approach completely separates the VirtualDOM and the Real DOM. Additionally, these edits are serializable, meaning we can even manage UIs across a network connection. This little stack machine and serialized edits makes Dioxus independent of platform specifics.
|
||||
|
||||
Dioxus is also really fast. Because Dioxus splits the diff and patch phase, it's able to make all the edits to the RealDOM in a very short amount of time (less than a single frame) making rendering very snappy. It also allows Dioxus to cancel large diffing operations if higher priority work comes in while it's diffing.
|
||||
|
||||
It's important to note that there _is_ one layer of connectedness between Dioxus and the renderer. Dioxus saves and loads elements (the PushRoot edit) with an ID. Inside the VirtualDOM, this is just tracked as a u64.
|
||||
|
||||
Whenever a `CreateElement` edit is generated during diffing, Dioxus increments its node counter and assigns that new element its current NodeCount. The RealDom is responsible for remembering this ID and pushing the correct node when PushRoot(ID) is generated. Dioxus doesn't reclaim IDs of elements its removed, but your renderer probably will want to. To do this, we suggest using a `SecondarySlotMap` if implementing the renderer in Rust, or just deferring to a HashMap-type approach.
|
||||
|
||||
This little demo serves to show exactly how a Renderer would need to process an edit stream to build UIs. A set of serialized EditStreams for various demos is available for you to test your custom renderer against.
|
||||
|
||||
## Event loop
|
||||
|
||||
Like most GUIs, Dioxus relies on an event loop to progress the VirtualDOM. The VirtualDOM itself can produce events as well, so it's important that your custom renderer can handle those too.
|
||||
|
||||
The code for the WebSys implementation is straightforward, so we'll add it here to demonstrate how simple an event loop is:
|
||||
|
||||
```rust
|
||||
pub async fn run(&mut self) -> dioxus_core::error::Result<()> {
|
||||
// Push the body element onto the WebsysDom's stack machine
|
||||
let mut websys_dom = crate::new::WebsysDom::new(prepare_websys_dom());
|
||||
websys_dom.stack.push(root_node);
|
||||
|
||||
// Rebuild or hydrate the virtualdom
|
||||
self.internal_dom.rebuild(&mut websys_dom)?;
|
||||
|
||||
// Wait for updates from the real dom and progress the virtual dom
|
||||
loop {
|
||||
let user_input_future = websys_dom.wait_for_event();
|
||||
let internal_event_future = self.internal_dom.wait_for_event();
|
||||
|
||||
match select(user_input_future, internal_event_future).await {
|
||||
Either::Left((trigger, _)) => trigger,
|
||||
Either::Right((trigger, _)) => trigger,
|
||||
}
|
||||
}
|
||||
|
||||
while let Some(trigger) = {
|
||||
websys_dom.stack.push(body_element.first_child().unwrap());
|
||||
self.internal_dom
|
||||
.progress_with_event(&mut websys_dom, trigger)?;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
It's important that you decode the real events from your event system into Dioxus' synthetic event system (synthetic meaning abstracted). This simply means matching your event type and creating a Dioxus `VirtualEvent` type. Your custom event must implement the corresponding event trait. Right now, the VirtualEvent system is modeled almost entirely around the HTML spec, but we are interested in slimming it down.
|
||||
|
||||
```rust
|
||||
fn virtual_event_from_websys_event(event: &web_sys::Event) -> VirtualEvent {
|
||||
match event.type_().as_str() {
|
||||
"keydown" | "keypress" | "keyup" => {
|
||||
struct CustomKeyboardEvent(web_sys::KeyboardEvent);
|
||||
impl dioxus::events::KeyboardEvent for CustomKeyboardEvent {
|
||||
fn char_code(&self) -> usize { self.0.char_code() }
|
||||
fn ctrl_key(&self) -> bool { self.0.ctrl_key() }
|
||||
fn key(&self) -> String { self.0.key() }
|
||||
fn key_code(&self) -> usize { self.0.key_code() }
|
||||
fn location(&self) -> usize { self.0.location() }
|
||||
fn meta_key(&self) -> bool { self.0.meta_key() }
|
||||
fn repeat(&self) -> bool { self.0.repeat() }
|
||||
fn shift_key(&self) -> bool { self.0.shift_key() }
|
||||
fn which(&self) -> usize { self.0.which() }
|
||||
fn get_modifier_state(&self, key_code: usize) -> bool { self.0.get_modifier_state() }
|
||||
}
|
||||
VirtualEvent::KeyboardEvent(Rc::new(event.clone().dyn_into().unwrap()))
|
||||
}
|
||||
_ => todo!()
|
||||
```
|
||||
|
||||
## Custom raw elements
|
||||
|
||||
If you need to go as far as relying on custom elements for your renderer – you totally can. This still enables you to use Dioxus' reactive nature, component system, shared state, and other features, but will ultimately generate different nodes. All attributes and listeners for the HTML and SVG namespace are shuttled through helper structs that essentially compile away (pose no runtime overhead). You can drop in your own elements any time you want, with little hassle. However, you must be absolutely sure your renderer can handle the new type, or it will crash and burn.
|
||||
|
||||
These custom elements are defined as unit structs with trait implementations.
|
||||
|
||||
For example, the `div` element is (approximately!) defined as such:
|
||||
|
||||
```rust
|
||||
struct div;
|
||||
impl div {
|
||||
/// Some glorious documentation about the class property.
|
||||
#[inline]
|
||||
fn class<'a>(&self, cx: NodeFactory<'a>, val: Arguments) -> Attribute<'a> {
|
||||
cx.attr("class", val, None, false)
|
||||
}
|
||||
// more attributes
|
||||
}
|
||||
```
|
||||
You've probably noticed that many elements in the `rsx!` and `html!` macros support on-hover documentation. The approach we take to custom elements means that the unit struct is created immediately where the element is used in the macro. When the macro is expanded, the doc comments still apply to the unit struct, giving tons of in-editor feedback, even inside a proc macro.
|
||||
|
||||
|
||||
## Compatibility
|
||||
|
||||
Forewarning: not every hook and service will work on your platform. Dioxus wraps things that need to be cross-platform in "synthetic" types. However, downcasting to a native type might fail if the types don't match.
|
||||
|
||||
There are three opportunities for platform incompatibilities to break your program:
|
||||
|
||||
1. When downcasting elements via `Ref.downcast_ref<T>()`
|
||||
2. When downcasting events via `Event.downcast_ref<T>()`
|
||||
3. Calling platform-specific APIs that don't exist
|
||||
|
||||
The best hooks will properly detect the target platform and still provide functionality, failing gracefully when a platform is not supported. We encourage – and provide – an indication to the user on what platforms a hook supports. For issues 1 and 2, these return a result as to not cause panics on unsupported platforms. When designing your hooks, we recommend propagating this error upwards into user facing code, making it obvious that this particular service is not supported.
|
||||
|
||||
This particular code _will panic_ due to the unwrap on downcast_ref. Try to avoid these types of patterns.
|
||||
|
||||
```rust
|
||||
let div_ref = use_node_ref(cx);
|
||||
|
||||
cx.render(rsx!{
|
||||
div { ref: div_ref, class: "custom class",
|
||||
button { "click me to see my parent's class"
|
||||
onclick: move |_| if let Some(div_ref) = div_ref {
|
||||
log::info!("Div class is {}", div_ref.downcast_ref::<web_sys::Element>().unwrap().class())
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
```
|
||||
|
||||
## Conclusion
|
||||
|
||||
That should be it! You should have nearly all the knowledge required on how to implement your own renderer. We're super interested in seeing Dioxus apps brought to custom desktop renderers, mobile renderer, video game UI, and even augmented reality! If you're interesting in contributing to any of the these projects, don't be afraid to reach out or join the community.
|
||||
@@ -0,0 +1,32 @@
|
||||
# Dioxus Liveview
|
||||
Liveview is a configuration where a server and a client work together to render a Dioxus app. Liveview monomorphizes a web application, eliminating the need for frontend-specific APIs.
|
||||
|
||||
This is a developer-friendly alternative to the JAM-stack (Javascript + API + Markdown), combining the Wasm-compatibility and async performance of Rust.
|
||||
|
||||
## Why liveview?
|
||||
|
||||
### No APIs necessary!
|
||||
Because Liveview combines the server and the client, you'll find dedicated APIs unnecessary. You'll still want to implement a data-fetching service for Live-apps, but this can be implemented as a crate and shared between apps. This approach was designed to let you model out your data requirements without needing to maintain a public versioned API.
|
||||
|
||||
You can find more information to data modeling and fetching for LiveApps in the "Book of Dioxus Patterns".
|
||||
|
||||
### Ease of deployment
|
||||
There is no hassle for deploying Dioxus liveview apps – simply upload the binary to your hosting provider of choice. There simply is no need to deal with intermediate APIs. An app's frontend and backend are tightly coupled to each other, meaning that the backed and frontend are always up to date.
|
||||
|
||||
This is especially powerful for small teams, where fast iteration, versioned unique prototypes, and simple deployments are important. As your app grows, Dioxus will happily grow with you, serving up to 100K RPS (thanks to async Rust performance).
|
||||
|
||||
### Power of server rendering combined with the reactive nature of JavaScript
|
||||
Liveview apps are backed by a server and enhanced with web-assembly. This completely eliminates the need to write Javascript to add dynamic content to webpages. Apps are written in only **one** language and require essentially 0 knowledge of build systems, transpiling or ECMAScript versions. Minimum browser support is guaranteed to cover 95% of users, and the Dioxus-CLI can be configured to generate polyfills for even more support.
|
||||
|
||||
### Support with LiveHost by Dioxus-Labs
|
||||
The Dioxus-CLI comes ready for use with premium Dioxus-Labs services, like LiveHost. Simply link up your git repo to the Dioxus LiveHost and start deploying your fullstack Dioxus app today. LiveHost supports:
|
||||
|
||||
- Versioned fronted/backend with unique links
|
||||
- Builtin CI/CD
|
||||
- Managed and pluggable storage database backends
|
||||
- Serverless support for minimal latency
|
||||
- Site Analytics
|
||||
- Lighthouse optimization
|
||||
- On-premise support (see license terms)
|
||||
|
||||
Dioxus LiveHost is a Dioxus LiveApp management service with all supported features in a single binary. For OSS, we permit free usage and deployment of LiveHost to your favorite hosting provider.
|
||||
@@ -0,0 +1,63 @@
|
||||
# VNodes with RSX, HTML, and NodeFactory
|
||||
|
||||
Many modern frameworks provide a domain-specific-language for declaring user-interfaces. In the case of React, this language extension is called JSX and must be handled through additional dependencies and pre/post processors to transform your source code. With Rust, we can simply provide a procedural macro in the Dioxus dependency itself that mimics the JSX language.
|
||||
|
||||
With Dioxus, we actually ship two different macros – a macro that mimics JSX (the `html!` macro) and a macro that mimics Rust's native nested-struct syntax (the `rsx!` macro). These macros simply transform their inputs into NodeFactory calls.
|
||||
|
||||
For instance, this html! call:
|
||||
```rust
|
||||
html!(<div> "hello world" </div>)
|
||||
```
|
||||
becomes this NodeFactory call:
|
||||
```rust
|
||||
|f| f.element(
|
||||
dioxus_elements::div, // tag
|
||||
[], // listeners
|
||||
[], // attributes
|
||||
[f.static_text("hello world")], // children
|
||||
None // key
|
||||
)
|
||||
```
|
||||
The NodeFactory API is fairly ergonomic, making it a viable option to use directly. The NodeFactory API is also compile-time correct and has incredible syntax highlighting support. We use what Rust calls a "unit type" – the `dioxus_elements::div` and associated methods to ensure that a `div` can only have attributes associated with `div`s. This lets us tack on relevant documentation, autocomplete support, and jump-to-definition for methods and attributes.
|
||||
|
||||

|
||||
|
||||
## html! macro
|
||||
|
||||
The html! macro supports a limited subset of the html standard. Rust's macro parsing tools are somewhat limited, so all text between tags _must be quoted_.
|
||||
|
||||
However, writing HTML by hand is a bit tedious – IDE tools for Rust don't support linting/autocomplete/syntax highlighting. We suggest using RSX – it's more natural for Rust programs and _does_ integrate well with Rust IDE tools.
|
||||
|
||||
```rust
|
||||
let name = "jane";
|
||||
let pending = false;
|
||||
let count = 10;
|
||||
|
||||
dioxus::ssr::render_lazy(html! {
|
||||
<div>
|
||||
<p> "Hello, {name}!" </p>
|
||||
<p> "Status: {pending}!" </p>
|
||||
<p> "Count {count}!" </p>
|
||||
</div>
|
||||
});
|
||||
```
|
||||
|
||||
## rsx! macro
|
||||
|
||||
The rsx! macro is a VNode builder macro designed especially for Rust programs. Writing these should feel very natural, much like assembling a struct. VSCode also supports these with code folding, bracket-tabbing, bracket highlighting, section selecting, inline documentation, GOTO definition, and refactoring support.
|
||||
|
||||
When helpful, the Dioxus VSCode extension provides a way of converting a selection of HTML directly to RSX, so you can import templates from the web directly into your existing app.
|
||||
|
||||
It's also a bit easier on the eyes than HTML.
|
||||
|
||||
```rust
|
||||
dioxus::ssr::render_lazy(rsx! {
|
||||
div {
|
||||
p {"Hello, {name}!"}
|
||||
p {"Status: {pending}!"}
|
||||
p {"Count {count}!"}
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
In the next section, we'll cover the `rsx!` macro in more depth.
|
||||
@@ -0,0 +1,29 @@
|
||||
## Testing
|
||||
|
||||
To test your Rust code, you can annotate any function with the `#[test]` block. In VSCode with RA, this will provide a lens to click and run the test.
|
||||
|
||||
```rust
|
||||
#[test]
|
||||
fn component_runs() {
|
||||
assert!(true)
|
||||
}
|
||||
```
|
||||
|
||||
This will test your Rust code _without_ going through the browser. This is ideal for squashing logic bugs and ensuring components render appropriately when the browsers's DOM is not needed. If you need to run tests in the browser, you can annotate your blocks with the `#[dioxus::test]` block.
|
||||
|
||||
```rust
|
||||
#[dioxus::test]
|
||||
fn runs_in_browser() {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
Then, when you run
|
||||
|
||||
```console
|
||||
dioxus test --chrome
|
||||
```
|
||||
|
||||
Dioxus will build and test your code using the Chrome browser as a harness.
|
||||
|
||||
There's a lot more to testing if you dive in, so check out the [Testing]() guide for more information
|
||||
@@ -0,0 +1,29 @@
|
||||
In the cases where you need to pass arbitrary element properties into a component – say to add more functionality to the `<a>` tag, Dioxus will accept any quoted fields. This is similar to adding arbitrary fields to regular elements using quotes.
|
||||
|
||||
```rust
|
||||
|
||||
rsx!(
|
||||
Clickable {
|
||||
"class": "blue-button",
|
||||
"style": "background: red;"
|
||||
}
|
||||
)
|
||||
|
||||
```
|
||||
|
||||
For a component to accept these attributes, you must add an `attributes` field to your component's properties. We can use the spread syntax to add these attributes to whatever nodes are in our component.
|
||||
|
||||
```rust
|
||||
#[derive(Props)]
|
||||
struct ClickableProps<'a> {
|
||||
attributes: Attributes<'a>
|
||||
}
|
||||
|
||||
fn clickable(cx: Scope<ClickableProps<'a>>) -> Element {
|
||||
cx.render(rsx!(
|
||||
a {
|
||||
..cx.props.attributes,
|
||||
"Any link, anywhere"
|
||||
}
|
||||
))
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
# Thinking in Reactively
|
||||
|
||||
We've finally reached the point in our tutorial where we can talk about the theory of Reactivity. We've talked about defining a declarative view, but not about the aspects that make our code *reactive*.
|
||||
|
||||
Understanding the theory of reactive programming is essential to making sense of Dioxus and writing effective, performant UIs.
|
||||
|
||||
In this section, we'll talk about:
|
||||
|
||||
- One-way data flow
|
||||
- Modifying data
|
||||
- Forcing renders
|
||||
- How renders propagate
|
||||
|
||||
This section is a bit long, but worth the read. We recommend coffee, tea, and/or snacks.
|
||||
|
||||
## Reactive Programming
|
||||
|
||||
Dioxus is one of a handful of Rust libraries that provide a "Reactive Programming Model". The term "Reactive programming" is a classification of programming paradigm – much like functional or imperative programming. This is a very important distinction since it affects how we *think* about our code.
|
||||
|
||||
Reactive programming is a programming model concerned with deriving computations from asynchronous data flow. Most reactive programs are comprised of datasources, intermediate computations, and a final result.
|
||||
|
||||
We consider the rendered GUI to be the final result of our Dioxus apps. The datasources for our apps include local and global state.
|
||||
|
||||
For example, the model presented in the figure below is comprised of two data sources: time and a constant. These values are passed through our computation graph to achieve a final result: `g`.
|
||||
|
||||

|
||||
|
||||
Whenever our `seconds` variable changes, we will then reevaluate the computation for `t`. Because `g` relies on `t`, we will also reevaluate its computation too. Notice that we would've reevaluated the computation for `g` even if `t` didn't change because `seconds` is used to calculate `g`.
|
||||
|
||||
However, if we somehow changed our constant from `1` to `2`, then we need to reevaluate `t`. If, for whatever reason, this change did not affect the result of `t`, then we wouldn't try to reevaluate `g`.
|
||||
|
||||
In Reactive Programming, we don't think about whether or not we should reevaluate `t` or `g`; instead, we simply provide functions of computation and let the framework figure out the rest for us.
|
||||
|
||||
In Rust, our reactive app would look something like:
|
||||
|
||||
```rust
|
||||
fn compute_g(t: i32, seconds: i32) -> bool {
|
||||
t > seconds
|
||||
}
|
||||
|
||||
fn compute_t(constant: i32, seconds: i32) -> i32 {
|
||||
constant + seconds
|
||||
}
|
||||
|
||||
fn compute_graph(constant: i32, seconds: i32) -> bool {
|
||||
let t = compute_t(constant, seconds);
|
||||
let g = compute_g(t, seconds);
|
||||
g
|
||||
}
|
||||
```
|
||||
|
||||
## How is Dioxus Reactive?
|
||||
|
||||
The Dioxus VirtualDom provides us a framework for reactive programming. When we build apps with dioxus, we need to provide our own datasources. This can be either initial props or some values fetched from the network. We then pass this data through our app into components through properties.
|
||||
|
||||
If we represented the reactive graph presented above in Dioxus, it would look very similar:
|
||||
|
||||
```rust
|
||||
// Declare a component that holds our datasources and calculates `g`
|
||||
fn RenderGraph(cx: Scope) -> Element {
|
||||
let seconds = use_datasource(SECONDS);
|
||||
let constant = use_state(&cx, || 1);
|
||||
|
||||
cx.render(rsx!(
|
||||
RenderG { seconds: seconds }
|
||||
RenderT { seconds: seconds, constant: constant }
|
||||
))
|
||||
}
|
||||
|
||||
// "calculate" g by rendering `t` and `seconds`
|
||||
#[inline_props]
|
||||
fn RenderG(cx: Scope, seconds: i32) -> Element {
|
||||
cx.render(rsx!{ "There are {seconds} seconds remaining..." })
|
||||
}
|
||||
|
||||
// calculate and render `t` in its own component
|
||||
#[inline_props]
|
||||
fn RenderT(cx: Scope, seconds: i32, constant: i32) -> Element {
|
||||
let res = seconds + constant;
|
||||
cx.render(rsx!{ "{res}" })
|
||||
}
|
||||
```
|
||||
|
||||
With this app, we've defined three components. Our top-level component provides our datasources (the hooks), computation nodes (child components), and a final value (what's "rendered").
|
||||
|
||||
Now, whenever the `constant` changes, our `RenderT` component will be re-rendered. However, if `seconds` doesn't change, then we don't need to re-render `RenderG` because the input is the same. If `seconds` *does* change, then both RenderG and RenderT will be reevaluated.
|
||||
|
||||
Dioxus is "Reactive" because it provides this framework for us. All we need to do is write our own tiny units of computation and Dioxus figures out which components need to be reevaluated automatically.
|
||||
|
||||
These extra checks and algorithms add some overhead, which is why you see projects like [Sycamore](http://sycamore-rs.netlify.app) and [SolidJS](http://solidjs.com) eliminating them altogether. Dioxus is *really* fast, so we're willing to exchange the added overhead for improved developer experience.
|
||||
|
||||
## How do we update values in our dataflow graph?
|
||||
|
||||
Dioxus will automatically figure out how to regenerate parts of our app when datasources change. But how exactly can we update our data sources?
|
||||
|
||||
In Dioxus there are two datasources:
|
||||
|
||||
1. Local state in `use_hook` and all other hooks
|
||||
2. Global state through `provide_context`.
|
||||
|
||||
Technically, the root props of the VirtualDom are a third datasource, but since we cannot modify them, they are not worth talking about.
|
||||
|
||||
### Local State
|
||||
|
||||
For local state in hooks, Dioxus gives us the `use_hook` method which returns an `&mut T` without any requirements. This means raw hook values are not tracked by Dioxus. In fact, we could write a component that modifies a hook value directly:
|
||||
|
||||
```rust
|
||||
fn app(cx: Scope) -> Element {
|
||||
let mut count = cx.use_hook(|_| 0);
|
||||
cx.render(rsx!{
|
||||
button {
|
||||
onclick: move |_| *count += 1,
|
||||
"Count: {count}"
|
||||
}
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
However, when this value is written to, the component does not know to be reevaluated. We must explicitly tell Dioxus that this component is "dirty" and needs to be re-rendered. This is done through the `cx.needs_update` method:
|
||||
|
||||
```rust
|
||||
button {
|
||||
onclick: move |_| {
|
||||
*count += 1;
|
||||
cx.needs_update();
|
||||
},
|
||||
"Count: {count}"
|
||||
}
|
||||
```
|
||||
|
||||
Now, whenever we click the button, the value will change and the component will be re-rendered.
|
||||
|
||||
> Re-rendering is when Dioxus calls your function component *again*. Component functions will be called over and over throughout their lifetime, so they should be mostly side-effect free.
|
||||
|
||||
### Understand this!
|
||||
|
||||
Your component functions will be called ("rendered" in our lingo) for as long as the component is present in the tree.
|
||||
|
||||
A single component will be called multiple times, modifying its own internal state or rendering new nodes with new values from its properties.
|
||||
|
||||
### App-Global State
|
||||
|
||||
With the `provide_context` and `consume_context` methods on `Scope`, we can share values to descendants without having to pass values through component props. This has the side-effect of making our datasources less obvious from a high-level perspective, but it makes our components more modular within the same codebase.
|
||||
|
||||
To make app-global state easier to reason about, Dioxus makes all values provided through `provide_context` immutable. This means any library built on top of `provide_context` needs to use interior mutability to modify shared global state.
|
||||
|
||||
In these cases, App-Global state needs to manually track which components need to be re-generated.
|
||||
|
||||
To regenerate *any* component in your app, you can get a handle to the Dioxus' internal scheduler through `schedule_update_any`:
|
||||
|
||||
```rust
|
||||
let force_render = cx.schedule_update_any();
|
||||
|
||||
// force a render of the root component
|
||||
force_render(ScopeId(0));
|
||||
```
|
||||
|
||||
## What does it mean for a component to "re-render"?
|
||||
|
||||
In our guides, we frequently use the phrase "re-render" to describe updates to our app. You'll often hear this paired with "preventing unnecessary re-renders." But what exactly does this mean?
|
||||
|
||||
When we call `dioxus::desktop::launch`, Dioxus will create a new `Scope` object and call the component we gave it. Our `rsx!` calls will create new nodes which we return back to the VirtualDom. Dioxus will then look through these nodes for child components, call their functions, and so on until every component has been "rendered." We consider these nodes "rendered" because they were created because of our explicit actions.
|
||||
|
||||
The tree of UI that dioxus creates will roughly look like the tree of components presented earlier:
|
||||
|
||||

|
||||
|
||||
But what happens when we call `needs_update` after modifying some important state? Well, if Dioxus called our component's function again, then we would produce new, different nodes. In fact, this is exactly what Dioxus does!
|
||||
|
||||
At this point, we have some old nodes and some new nodes. Again, we call this "rendering" because Dioxus had to create new nodes because of our explicit actions. Any time new nodes get created, our VirtualDom is being "rendered."
|
||||
|
||||
These nodes are stored in an extremely efficient memory allocator called a "bump arena." For example, a div with a handler and attribute would be stored in memory in two locations: the "old" tree and the "new" tree.
|
||||
|
||||

|
||||
|
||||
From here, Dioxus computes the difference between these trees and updates the Real DOM to make it look like the new version of what we've declared.
|
||||
|
||||

|
||||
|
||||
## Suppressing Renders
|
||||
|
||||
So, we know how to make Dioxus render, but how do we *stop* it? What if we *know* that our state didn't change and we shouldn't render and diff new nodes because they'll be exactly the same as the last time?
|
||||
|
||||
In these cases, you want to reach for *memoization*. In Dioxus, memoization involves preventing a component from rendering again if its props didn't change since the last time it attempted to render.
|
||||
|
||||
Visually, you can tell that a component will only re-render if the new value is sufficiently different than the old one.
|
||||
|
||||
| props.val | re-render |
|
||||
| --------- | --------- |
|
||||
| 10 | true |
|
||||
| 20 | true |
|
||||
| 20 | false |
|
||||
| 20 | false |
|
||||
| 10 | true |
|
||||
| 30 | false |
|
||||
|
||||
This is why when you `derive(Props)`, you must also implement the `PartialEq` trait. To override the memoization strategy for a component, you can simply implement your own PartialEq.
|
||||
|
||||
```rust
|
||||
struct CustomProps {
|
||||
val: i32,
|
||||
}
|
||||
|
||||
impl PartialEq for CustomProps {
|
||||
fn partial_eq(&self, other: &Self) -> bool {
|
||||
// we don't render components that have a val less than 5
|
||||
if other.val > 5 && self.val > 5{
|
||||
self.val == other.val
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
However, for components that borrow data, it doesn't make sense to implement PartialEq since the actual references in memory might be different.
|
||||
|
||||
You can technically override this behavior by implementing the `Props` trait manually, though it's unsafe and easy to mess up:
|
||||
|
||||
```rust
|
||||
unsafe impl Properties for CustomProps {
|
||||
fn memoize(&self, other &Self) -> bool {
|
||||
self != other
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
TLDR:
|
||||
- Dioxus checks if props changed between renders
|
||||
- If props changed according to PartialEq, Dioxus re-renders the component
|
||||
- Props that have a lifetime (ie `<'a>`) will always be re-rendered
|
||||
|
||||
## Wrapping Up
|
||||
|
||||
Wow, that was a lot of material!
|
||||
|
||||
Let's see if we can recap what was presented:
|
||||
|
||||
- Reactive programming calculates a final value from datasources and computation
|
||||
- Dioxus is "reactive" since it figures out which computations to check
|
||||
- `schedule_update` must be called to mark a component as dirty
|
||||
- dirty components will be re-rendered (called multiple times) to produce a new UI
|
||||
- Renders can be suppressed with memoization
|
||||
|
||||
This theory is crucial to understand how to compose components and how to control renders in your app.
|
||||
@@ -0,0 +1,26 @@
|
||||
|
||||
## JavaScript Handlers
|
||||
|
||||
Instead of passing a closure, you can also pass a string to event handlers – this lets you use JavaScript (if your renderer can execute JavaScript):
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/event_javascript.rs:rsx}}
|
||||
```
|
||||
|
||||
|
||||
#![allow(non_snake_case)]
|
||||
use dioxus::prelude::*;
|
||||
|
||||
fn main() {
|
||||
dioxus::desktop::launch(App);
|
||||
}
|
||||
|
||||
fn App(cx: Scope) -> Element {
|
||||
cx.render(rsx! {
|
||||
// ANCHOR: rsx
|
||||
div {
|
||||
onclick: "alert('hello world')",
|
||||
}
|
||||
// ANCHOR_END: rsx
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
# Fanning Out
|
||||
|
||||
One of the most reliable state management patterns in large Dioxus apps is `fan-out`. The fan-out pattern is the ideal way to structure your app to maximize code reuse, testability, and deterministic rendering.
|
||||
|
||||
## The structure
|
||||
|
||||
With `fan-out`, our individual components at "leaf" position of our VirtualDom are "pure", making them easily reusable, testable, and deterministic. For instance, the "title" bar of our app might be a fairly complicated component.
|
||||
|
||||
```rust
|
||||
#[derive(Props, PartialEq)]
|
||||
struct TitlebarProps {
|
||||
title: String,
|
||||
subtitle: String,
|
||||
}
|
||||
|
||||
fn Titlebar(cx: Scope<TitlebarProps>) -> Element {
|
||||
cx.render(rsx!{
|
||||
div {
|
||||
class: "titlebar"
|
||||
h1 { "{cx.props.title}" }
|
||||
h1 { "{cx.props.subtitle}" }
|
||||
}
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
If we used global state like use_context or fermi, we might be tempted to inject our `use_read` directly into the component.
|
||||
|
||||
```rust
|
||||
fn Titlebar(cx: Scope<TitlebarProps>) -> Element {
|
||||
let title = use_read(&cx, TITLE);
|
||||
let subtitle = use_read(&cx, SUBTITLE);
|
||||
|
||||
cx.render(rsx!{/* ui */})
|
||||
}
|
||||
```
|
||||
|
||||
For many apps – this is a fine pattern, especially if the component is a one-off. However, if we want to reuse the component outside of this app, then we'll start to run into issues where our contexts are unavailable.
|
||||
|
||||
## Fanning Out
|
||||
|
||||
To enable our titlebar component to be used across apps, we want to lift our atoms upwards and out of the Titlebar component. We would organize a bunch of other components in this section of the app to share some of the same state.
|
||||
|
||||
```rust
|
||||
fn DocsiteTitlesection(cx: Scope) {
|
||||
let title = use_read(&cx, TITLE);
|
||||
let subtitle = use_read(&cx, SUBTITLE);
|
||||
|
||||
let username = use_read(&cx, USERNAME);
|
||||
let points = use_read(&cx, POINTS);
|
||||
|
||||
cx.render(rsx!{
|
||||
TitleBar { title: title, subtitle: subtitle }
|
||||
UserBar { username: username, points: points }
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
This particular wrapper component unfortunately cannot be reused across apps. However, because it simply wraps other real elements, it doesn't have to. We are free to reuse our TitleBar and UserBar components across apps with ease. We also know that this particular component is plenty performant because the wrapper doesn't have any props and is always memoized. The only times this component re-renders is when any of the atoms change.
|
||||
|
||||
This is the beauty of Dioxus – we always know where our components are likely to be re-rendered. Our wrapper components can easily prevent any large re-renders by simply memoizing their components. This system might not be as elegant or precise as signal systems found in libraries like Sycamore or SolidJS, but it is quite ergonomic.
|
||||
@@ -0,0 +1,14 @@
|
||||
# "Hello, World" desktop app
|
||||
|
||||
|
||||
|
||||
If you plan to develop extensions for the `Dioxus` ecosystem, please use the `dioxus` crate with the `core` feature to limit the amount of dependencies your project brings in.
|
||||
|
||||
|
||||
### What is this `Scope` object?
|
||||
|
||||
Coming from React, the `Scope` object might be confusing. In React, you'll want to store data between renders with hooks. However, hooks rely on global variables which make them difficult to integrate in multi-tenant systems like server-rendering.
|
||||
|
||||
In Dioxus, you are given an explicit `Scope` object to control how the component renders and stores data. The `Scope` object provides a handful of useful APIs for features like suspense, rendering, and more.
|
||||
|
||||
For now, just know that `Scope` lets you store state with hooks and render elements with `cx.render`.
|
||||
@@ -0,0 +1,47 @@
|
||||
# Helper Crates
|
||||
|
||||
Because the Dioxus ecosystem is fairly young, there aren't a ton of third-party libraries designed to "get things done." That's where the Dioxus helper crates come in. These are officially supported crates built on top of existing libraries to solve some of the common barriers to building apps.
|
||||
|
||||
## Router
|
||||
|
||||
Quickly add a cross-platform router to structure your app.
|
||||
|
||||
[Link](https://github.com/DioxusLabs/dioxus/tree/master/packages/router)
|
||||
|
||||
## Fermi
|
||||
|
||||
Global state as easy as `use_state`.
|
||||
|
||||
[Link](https://github.com/DioxusLabs/dioxus/tree/master/packages/fermi)
|
||||
|
||||
## Query
|
||||
|
||||
This crate has yet to be developed! However, we do plan on providing a crate for good fetching and query support.
|
||||
|
||||
## 3rd-party – Toast
|
||||
|
||||
Toast notifications, curtesy of [@mrxiaozhuox](https://github.com/mrxiaozhuox).
|
||||
|
||||
[Link](https://github.com/mrxiaozhuox/dioxus-toast)
|
||||
|
||||
## 3rd-party – HeroIcon
|
||||
|
||||
Collection of helpful hero icons, curtesy of [@autarch](https://github.com/autarch).
|
||||
|
||||
|
||||
[Link](https://github.com/houseabsolute/dioxus-heroicons)
|
||||
|
||||
## 3rd-party – Katex
|
||||
|
||||
Draw beautiful equations, curtesy of [@oovm](https://github.com/oovm)
|
||||
|
||||
[Link](https://github.com/oovm/katex-wasm/tree/dev/projects/dioxus-katex)
|
||||
|
||||
|
||||
## 3rd-party – PrimsJS
|
||||
|
||||
Highlight your code blocks with ease, curtesy of [@oovm](https://github.com/oovm)
|
||||
|
||||
[Link](https://github.com/oovm/katex-wasm/tree/dev/projects/dioxus-katex)
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
# Managing State
|
||||
|
||||
Every app you'll build with Dioxus will have some sort of state that needs to be maintained and updated as your users interact with it. However, managing state can be particularly challenging at times, and is frequently the source of bugs in many GUI frameworks.
|
||||
|
||||
In this chapter, we'll cover the various ways to manage state, the appropriate terminology, various patterns, and some problems you might run into.
|
||||
|
||||
|
||||
## The Problem
|
||||
|
||||
Why do people say state management is so difficult? What does it mean?
|
||||
|
||||
Generally, state management is the code you need to write to ensure that your app renders the *correct* content. If the user inputs a name, then you need to display the appropriate response – like alerts, validation, and disable/enable various elements on the page. Things can quickly become tricky if you need loading screens and cancellable tasks.
|
||||
|
||||
For the simplest of apps, all of your state can enter the app from the root props. This is common in server-side rendering – we can collect all of the required state *before* rendering the content.
|
||||
|
||||
```rust
|
||||
let all_content = get_all_content().await;
|
||||
|
||||
let output = dioxus::ssr::render_lazy(rsx!{
|
||||
div {
|
||||
RenderContent { content: all_content }
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
With this incredibly simple setup, it is highly unlikely that you'll have rendering bugs. There simply is barely any state to manage.
|
||||
|
||||
However, most of your apps will store state inside of the Dioxus VirtualDom – either through local state or global state.
|
||||
|
||||
|
||||
## Your options
|
||||
|
||||
To deal with complexity, you have a couple of options:
|
||||
|
||||
- Refactor state out of shared state and into reusable components and hooks.
|
||||
- Lift state upwards to be spread across multiple components (fan out).
|
||||
- Use the Context API to share state globally.
|
||||
- Use a dedicated state management solution like Fermi.
|
||||
@@ -0,0 +1,110 @@
|
||||
# Local State
|
||||
|
||||
The first step to dealing with complexity in your app is to refactor your state to be purely local. This encourages good code reuse and prevents leakage of abstractions across component boundaries.
|
||||
|
||||
## What it looks like
|
||||
|
||||
Let's say we're managing the state for a list of Todos. Whenever we edit the todo, we want the list to update. We might've started building our app but putting everything into a single `use_ref`.
|
||||
|
||||
```rust
|
||||
struct Todo {
|
||||
contents: String,
|
||||
is_hovered: bool,
|
||||
is_editing: bool,
|
||||
}
|
||||
|
||||
let todos = use_ref(&cx, || vec![Todo::new()]);
|
||||
|
||||
cx.render(rsx!{
|
||||
ul {
|
||||
todos.read().iter().enumerate().map(|(id, todo)| rsx!{
|
||||
li {
|
||||
onhover: move |_| *todos.write()[id].is_hovered = true,
|
||||
h1 { "{todo.contents}" }
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
As shown above, whenever the todo is hovered, we want to set its state:
|
||||
|
||||
```rust
|
||||
todos.write()[0].is_hovered = true;
|
||||
```
|
||||
|
||||
As the amount of interactions goes up, so does the complexity of our state. Should the "hover" state really be baked into our data model?
|
||||
|
||||
Instead, let's refactor our Todo component to handle its own state:
|
||||
|
||||
```rust
|
||||
#[inline_props]
|
||||
fn Todo<'a>(cx: Scope, todo: &'a Todo) -> Element {
|
||||
let is_hovered = use_state(&cx, || false);
|
||||
|
||||
cx.render(rsx!{
|
||||
li {
|
||||
h1 { "{todo.contents}" }
|
||||
onhover: move |_| is_hovered.set(true),
|
||||
}
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
Now, we can simplify our Todo data model to get rid of local UI state:
|
||||
|
||||
```rust
|
||||
struct Todo {
|
||||
contents: String,
|
||||
}
|
||||
```
|
||||
|
||||
This is not only better for encapsulation and abstraction, but it's only more performant! Whenever a Todo is hovered, we won't need to re-render *every* Todo again – only the Todo that's currently being hovered.
|
||||
|
||||
|
||||
Wherever possible, you should try to refactor the "view" layer *out* of your data model.
|
||||
|
||||
## Immutability
|
||||
|
||||
Storing all of your state inside a `use_ref` might be tempting. However, you'll quickly run into an issue where the `Ref` provided by `read()` "does not live long enough." An indeed – you can't return locally-borrowed value into the Dioxus tree.
|
||||
|
||||
In these scenarios consider breaking your `use_ref` into individual `use_state`s.
|
||||
|
||||
You might've started modeling your component with a struct and use_ref
|
||||
|
||||
```rust
|
||||
struct State {
|
||||
count: i32,
|
||||
color: &'static str,
|
||||
names: HashMap<String, String>
|
||||
}
|
||||
|
||||
// in the component
|
||||
let state = use_ref(&cx, State::new)
|
||||
```
|
||||
|
||||
The "better" approach for this particular component would be to break the state apart into different values:
|
||||
|
||||
```rust
|
||||
let count = use_state(&cx, || 0);
|
||||
let color = use_state(&cx, || "red");
|
||||
let names = use_state(&cx, HashMap::new);
|
||||
```
|
||||
|
||||
You might recognize that our "names" value is a HashMap – which is not terribly cheap to clone every time we update its value. To solve this issue, we *highly* suggest using a library like [`im`](https://crates.io/crates/im) which will take advantage of structural sharing to make clones and mutations much cheaper.
|
||||
|
||||
When combined with the `make_mut` method on `use_state`, you can get really succinct updates to collections:
|
||||
|
||||
```rust
|
||||
let todos = use_state(&cx, im_rc::HashMap::default);
|
||||
|
||||
todos.make_mut().insert("new todo", Todo {
|
||||
contents: "go get groceries",
|
||||
});
|
||||
```
|
||||
|
||||
## Moving on
|
||||
|
||||
This particular local patterns are powerful but is not a cure-all for state management problems. Sometimes your state problems are much larger than just staying local to a component.
|
||||
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
|
||||
## Memoization
|
||||
|
||||
Dioxus uses Memoization for a more efficient user interface. Memoization is the process in which we check if a component actually needs to be re-rendered when its props change. If a component's properties change but they wouldn't affect the output, then we don't need to re-render the component, saving time!
|
||||
|
||||
For example, let's say we have a component that has two children:
|
||||
|
||||
```rust
|
||||
fn Demo(cx: Scope) -> Element {
|
||||
// don't worry about these 2, we'll cover them later
|
||||
let name = use_state(&cx, || String::from("bob"));
|
||||
let age = use_state(&cx, || 21);
|
||||
|
||||
cx.render(rsx!{
|
||||
Name { name: name }
|
||||
Age { age: age }
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
If `name` changes but `age` does not, then there is no reason to re-render our `Age` component since the contents of its props did not meaningfully change.
|
||||
|
||||
Dioxus memoizes owned components. It uses `PartialEq` to determine if a component needs rerendering, or if it has stayed the same. This is why you must derive PartialEq!
|
||||
|
||||
> This means you can always rely on props with `PartialEq` or no props at all to act as barriers in your app. This can be extremely useful when building larger apps where properties frequently change. By moving our state into a global state management solution, we can achieve precise, surgical re-renders, improving the performance of our app.
|
||||
|
||||
Borrowed Props cannot be safely memoized. However, this is not a problem – Dioxus relies on the memoization of their parents to determine if they need to be rerendered.
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
|
||||
|
||||
## Using UseRef with "models"
|
||||
|
||||
One option for state management that UseRef enables is the development of a "model" for your components. This particular pattern enables you to model your state with regular structs.
|
||||
|
||||
For instance, our calculator example uses a struct to model the state.
|
||||
|
||||
```rust
|
||||
|
||||
struct Calculator {
|
||||
display_value: String,
|
||||
operator: Option<Operator>,
|
||||
waiting_for_operand: bool,
|
||||
cur_val: f64,
|
||||
}
|
||||
```
|
||||
|
||||
Our component is really simple – we just call `use_ref` to get an initial calculator state.
|
||||
|
||||
```rust
|
||||
fn app(cx: Scope) -> Element {
|
||||
let state = use_ref(&cx, Calculator::new);
|
||||
|
||||
cx.render(rsx!{
|
||||
// the rendering code
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
In our UI, we can then use `read` and a helper method to get data out of the model.
|
||||
|
||||
```rust
|
||||
// Our accessor method
|
||||
impl Calculator {
|
||||
fn formatted_display(&self) -> String {
|
||||
self.display_value
|
||||
.parse::<f64>()
|
||||
.unwrap()
|
||||
.separated_string()
|
||||
}
|
||||
}
|
||||
|
||||
// And then in the UI
|
||||
cx.render(rsx!{
|
||||
div { [state.read().formatted_display()] }
|
||||
})
|
||||
```
|
||||
|
||||
To modify the state, we can setup a helper method and then attach it to a callback.
|
||||
|
||||
```rust
|
||||
// our helper
|
||||
impl Calculator {
|
||||
fn clear_display(&mut self) {
|
||||
self.display_value = "0".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
// our callback
|
||||
cx.render(rsx!{
|
||||
button {
|
||||
onclick: move |_| state.write().clear_display(),
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# Working with Async
|
||||
|
||||
Often, apps need to interact with file systems, network interfaces, hardware, or timers. This chapter provides an overview of using async code in Dioxus.
|
||||
|
||||
## The Runtime
|
||||
|
||||
By default, Dioxus-Desktop ships with the `Tokio` runtime and automatically sets everything up for you. This is currently not configurable, though it would be easy to write an integration for Dioxus desktop that uses a different asynchronous runtime.
|
||||
|
||||
Dioxus is not currently thread-safe, so any async code you write does *not* need to be `Send/Sync`. That means that you can use non-thread-safe structures like `Cell`, `Rc`, and `RefCell`.
|
||||
@@ -0,0 +1,29 @@
|
||||
# Spawning Futures
|
||||
|
||||
The `use_future` and `use_coroutine` hooks are useful if you want to unconditionally spawn the future. Sometimes, though, you'll want to only spawn a future in response to an event, such as a mouse click. For example, suppose you need to send a request when the user clicks a "log in" button. For this, you can use `cx.spawn`:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/spawn.rs:spawn}}
|
||||
```
|
||||
|
||||
> Note: `spawn` will always spawn a *new* future. You most likely don't want to call it on every render.
|
||||
|
||||
The future must be `'static` – so any values captured by the task cannot carry any references to `cx`, such as a `UseState`.
|
||||
|
||||
However, since you'll typically need a way to update the value of a hook, you can use `to_owned` to create a clone of the hook handle. You can then use that clone in the async closure.
|
||||
|
||||
To make this a bit less verbose, Dioxus exports the `to_owned!` macro which will create a binding as shown above, which can be quite helpful when dealing with many values.
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/spawn.rs:to_owned_macro}}
|
||||
```
|
||||
|
||||
Calling `spawn` will give you a `JoinHandle` which lets you cancel or pause the future.
|
||||
|
||||
## Spawning Tokio Tasks
|
||||
|
||||
Sometimes, you might want to spawn a background task that needs multiple threads or talk to hardware that might block your app code. In these cases, we can directly spawn a Tokio task from our future. For Dioxus-Desktop, your task will be spawned onto Tokio's Multithreaded runtime:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/spawn.rs:tokio}}
|
||||
```
|
||||
@@ -0,0 +1,183 @@
|
||||
# Coroutines
|
||||
|
||||
Another good tool to keep in your async toolbox are coroutines. Coroutines are futures that can be manually stopped, started, paused, and resumed.
|
||||
|
||||
Like regular futures, code in a Dioxus coroutine will run until the next `await` point before yielding. This low-level control over asynchronous tasks is quite powerful, allowing for infinitely looping tasks like WebSocket polling, background timers, and other periodic actions.
|
||||
|
||||
## `use_coroutine`
|
||||
|
||||
The basic setup for coroutines is the `use_coroutine` hook. Most coroutines we write will be polling loops using async/await.
|
||||
|
||||
```rust
|
||||
fn app(cx: Scope) -> Element {
|
||||
let ws: &UseCoroutine<()> = use_coroutine(&cx, |rx| async move {
|
||||
// Connect to some sort of service
|
||||
let mut conn = connect_to_ws_server().await;
|
||||
|
||||
// Wait for data on the service
|
||||
while let Some(msg) = conn.next().await {
|
||||
// handle messages
|
||||
}
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
For many services, a simple async loop will handle the majority of use cases.
|
||||
|
||||
However, if we want to temporarily disable the coroutine, we can "pause" it using the `pause` method, and "resume" it using the `resume` method:
|
||||
|
||||
```rust
|
||||
let sync: &UseCoroutine<()> = use_coroutine(&cx, |rx| async move {
|
||||
// code for syncing
|
||||
});
|
||||
|
||||
if sync.is_running() {
|
||||
cx.render(rsx!{
|
||||
button {
|
||||
onclick: move |_| sync.pause(),
|
||||
"Disable syncing"
|
||||
}
|
||||
})
|
||||
} else {
|
||||
cx.render(rsx!{
|
||||
button {
|
||||
onclick: move |_| sync.resume(),
|
||||
"Enable syncing"
|
||||
}
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
This pattern is where coroutines are extremely useful – instead of writing all the complicated logic for pausing our async tasks like we would with JavaScript promises, the Rust model allows us to just not poll our future.
|
||||
|
||||
## Sending Values
|
||||
|
||||
You might've noticed the `use_coroutine` closure takes an argument called `rx`. What is that? Well, a common pattern in complex apps is to handle a bunch of async code at once. With libraries like Redux Toolkit, managing multiple promises at once can be challenging and a common source of bugs.
|
||||
|
||||
With Coroutines, we have the opportunity to centralize our async logic. The `rx` parameter is an Unbounded Channel for code external to the coroutine to send data *into* the coroutine. Instead of looping on an external service, we can loop on the channel itself, processing messages from within our app without needing to spawn a new future. To send data into the coroutine, we would call "send" on the handle.
|
||||
|
||||
|
||||
```rust
|
||||
enum ProfileUpdate {
|
||||
SetUsername(String),
|
||||
SetAge(i32)
|
||||
}
|
||||
|
||||
let profile = use_coroutine(&cx, |mut rx: UnboundedReciver<ProfileUpdate>| async move {
|
||||
let mut server = connect_to_server().await;
|
||||
|
||||
while let Ok(msg) = rx.next().await {
|
||||
match msg {
|
||||
ProfileUpdate::SetUsername(name) => server.update_username(name).await,
|
||||
ProfileUpdate::SetAge(age) => server.update_age(age).await,
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
cx.render(rsx!{
|
||||
button {
|
||||
onclick: move |_| profile.send(ProfileUpdate::SetUsername("Bob".to_string())),
|
||||
"Update username"
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
For sufficiently complex apps, we could build a bunch of different useful "services" that loop on channels to update the app.
|
||||
|
||||
```rust
|
||||
let profile = use_coroutine(&cx, profile_service);
|
||||
let editor = use_coroutine(&cx, editor_service);
|
||||
let sync = use_coroutine(&cx, sync_service);
|
||||
|
||||
async fn profile_service(rx: UnboundedReceiver<ProfileCommand>) {
|
||||
// do stuff
|
||||
}
|
||||
|
||||
async fn sync_service(rx: UnboundedReceiver<SyncCommand>) {
|
||||
// do stuff
|
||||
}
|
||||
|
||||
async fn editor_service(rx: UnboundedReceiver<EditorCommand>) {
|
||||
// do stuff
|
||||
}
|
||||
```
|
||||
|
||||
We can combine coroutines with Fermi to emulate Redux Toolkit's Thunk system with much less headache. This lets us store all of our app's state *within* a task and then simply update the "view" values stored in Atoms. It cannot be understated how powerful this technique is: we get all the perks of native Rust tasks with the optimizations and ergonomics of global state. This means your *actual* state does not need to be tied up in a system like Fermi or Redux – the only Atoms that need to exist are those that are used to drive the display/UI.
|
||||
|
||||
```rust
|
||||
static USERNAME: Atom<String> = |_| "default".to_string();
|
||||
|
||||
fn app(cx: Scope) -> Element {
|
||||
let atoms = use_atom_root(&cx);
|
||||
|
||||
use_coroutine(&cx, |rx| sync_service(rx, atoms.clone()));
|
||||
|
||||
cx.render(rsx!{
|
||||
Banner {}
|
||||
})
|
||||
}
|
||||
|
||||
fn Banner(cx: Scope) -> Element {
|
||||
let username = use_read(&cx, USERNAME);
|
||||
|
||||
cx.render(rsx!{
|
||||
h1 { "Welcome back, {username}" }
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
Now, in our sync service, we can structure our state however we want. We only need to update the view values when ready.
|
||||
|
||||
```rust
|
||||
enum SyncAction {
|
||||
SetUsername(String),
|
||||
}
|
||||
|
||||
async fn sync_service(mut rx: UnboundedReceiver<SyncAction>, atoms: AtomRoot) {
|
||||
let username = atoms.write(USERNAME);
|
||||
let errors = atoms.write(ERRORS);
|
||||
|
||||
while let Ok(msg) = rx.next().await {
|
||||
match msg {
|
||||
SyncAction::SetUsername(name) => {
|
||||
if set_name_on_server(&name).await.is_ok() {
|
||||
username.set(name);
|
||||
} else {
|
||||
errors.make_mut().push("SetUsernameFailed");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Yielding Values
|
||||
|
||||
To yield values from a coroutine, simply bring in a `UseState` handle and set the value whenever your coroutine completes its work.
|
||||
|
||||
|
||||
```rust
|
||||
let sync_status = use_state(&cx, || Status::Launching);
|
||||
let sync_task = use_coroutine(&cx, |rx: UnboundedReceiver<SyncAction>| {
|
||||
to_owned![sync_status];
|
||||
async move {
|
||||
loop {
|
||||
delay_ms(1000).await;
|
||||
sync_status.set(Status::Working);
|
||||
}
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Automatic injection into the Context API
|
||||
|
||||
Coroutine handles are automatically injected through the context API. `use_coroutine_handle` with the message type as a generic can be used to fetch a handle.
|
||||
|
||||
```rust
|
||||
fn Child(cx: Scope) -> Element {
|
||||
let sync_task = use_coroutine_handle::<SyncAction>(&cx);
|
||||
|
||||
sync_task.send(SyncAction::SetUsername);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,33 @@
|
||||
# UseFuture
|
||||
|
||||
[`use_future`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_future.html) lets you run an async closure, and provides you with its result.
|
||||
|
||||
For example, we can make an API request inside `use_future`:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/use_future.rs:use_future}}
|
||||
```
|
||||
|
||||
The code inside `use_future` will be submitted to the Dioxus scheduler once the component has rendered.
|
||||
|
||||
We can use `.value()` to get the result of the future. On the first run, since there's no data ready when the component loads, its value will be `None`. However, once the future is finished, the component will be re-rendered and the value will now be `Some(...)`, containing the return value of the closure.
|
||||
|
||||
We can then render that result:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/use_future.rs:render}}
|
||||
```
|
||||
|
||||
|
||||
## Restarting the Future
|
||||
|
||||
The `UseFuture` handle provides a `restart` method. It can be used to execute the future again, producing a new value.
|
||||
|
||||
## Dependencies
|
||||
|
||||
Often, you will need to run the future again every time some value (e.g. a prop) changes. Rather than `.restart`ing it manually, you can provide a tuple of "dependencies" to the hook. It will automatically re-run the future when any of those dependencies change. Example:
|
||||
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/use_future.rs:dependency}}
|
||||
```
|
||||
@@ -0,0 +1,33 @@
|
||||
# Antipatterns
|
||||
|
||||
This example shows what not to do and provides a reason why a given pattern is considered an "AntiPattern". Most anti-patterns are considered wrong due performance reasons, or for harming code re-usability.
|
||||
|
||||
## Unnecessarily Nested Fragments
|
||||
|
||||
Fragments don't mount a physical element to the DOM immediately, so Dioxus must recurse into its children to find a physical DOM node. This process is called "normalization". This means that deeply nested fragments make Dioxus perform unnecessary work. Prefer one or two levels of fragments / nested components until presenting a true DOM element.
|
||||
|
||||
Only Component and Fragment nodes are susceptible to this issue. Dioxus mitigates this with components by providing an API for registering shared state without the Context Provider pattern.
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/anti_patterns.rs:nested_fragments}}
|
||||
```
|
||||
|
||||
## Incorrect Iterator Keys
|
||||
|
||||
As described in the conditional rendering chapter, list items must have unique keys that are associated with the same items across renders. This helps Dioxus associate state with the contained components, and ensures good diffing performance. Do not omit keys, unless you know that the list is static and will never change.
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/anti_patterns.rs:iter_keys}}
|
||||
```
|
||||
|
||||
## Avoid Interior Mutability in Props
|
||||
|
||||
While it is technically acceptable to have a `Mutex` or a `RwLock` in the props, they will be difficult to use.
|
||||
|
||||
Suppose you have a struct `User` containing the field `username: String`. If you pass a `Mutex<User>` prop to a `UserComponent` component, that component may wish to pass the username as a `&str` prop to a child component. However, it cannot pass that borrowed field down, since it only would live as long as the `Mutex`'s lock, which belongs to the `UserComponent` function. Therefore, the component will be forced to clone the `username` field.
|
||||
|
||||
## Avoid Updating State During Render
|
||||
|
||||
Every time you update the state, Dioxus needs to re-render the component – this is inefficient! Consider refactoring your code to avoid this.
|
||||
|
||||
Also, if you unconditionally update the state during render, it will be re-rendered in an infinite loop.
|
||||
@@ -0,0 +1,158 @@
|
||||
# Error handling
|
||||
|
||||
A selling point of Rust for web development is the reliability of always knowing where errors can occur and being forced to handle them
|
||||
|
||||
However, we haven't talked about error handling at all in this guide! In this chapter, we'll cover some strategies in handling errors to ensure your app never crashes.
|
||||
|
||||
|
||||
|
||||
## The simplest – returning None
|
||||
|
||||
Astute observers might have noticed that `Element` is actually a type alias for `Option<VNode>`. You don't need to know what a `VNode` is, but it's important to recognize that we could actually return nothing at all:
|
||||
|
||||
```rust
|
||||
fn App(cx: Scope) -> Element {
|
||||
None
|
||||
}
|
||||
```
|
||||
|
||||
This lets us add in some syntactic sugar for operations we think *shouldn't* fail, but we're still not confident enough to "unwrap" on.
|
||||
|
||||
> The nature of `Option<VNode>` might change in the future as the `try` trait gets upgraded.
|
||||
|
||||
```rust
|
||||
fn App(cx: Scope) -> Element {
|
||||
// immediately return "None"
|
||||
let name = cx.use_hook(|_| Some("hi"))?;
|
||||
}
|
||||
```
|
||||
|
||||
## Early return on result
|
||||
|
||||
Because Rust can't accept both Options and Results with the existing try infrastructure, you'll need to manually handle Results. This can be done by converting them into Options or by explicitly handling them.
|
||||
|
||||
```rust
|
||||
fn App(cx: Scope) -> Element {
|
||||
// Convert Result to Option
|
||||
let name = cx.use_hook(|_| "1.234").parse().ok()?;
|
||||
|
||||
|
||||
// Early return
|
||||
let count = cx.use_hook(|_| "1.234");
|
||||
let val = match count.parse() {
|
||||
Ok(val) => val
|
||||
Err(err) => return cx.render(rsx!{ "Parsing failed" })
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
Notice that while hooks in Dioxus do not like being called in conditionals or loops, they *are* okay with early returns. Returning an error state early is a completely valid way of handling errors.
|
||||
|
||||
|
||||
## Match results
|
||||
|
||||
The next "best" way of handling errors in Dioxus is to match on the error locally. This is the most robust way of handling errors, though it doesn't scale to architectures beyond a single component.
|
||||
|
||||
To do this, we simply have an error state built into our component:
|
||||
|
||||
```rust
|
||||
let err = use_state(&cx, || None);
|
||||
```
|
||||
|
||||
Whenever we perform an action that generates an error, we'll set that error state. We can then match on the error in a number of ways (early return, return Element, etc).
|
||||
|
||||
|
||||
```rust
|
||||
fn Commandline(cx: Scope) -> Element {
|
||||
let error = use_state(&cx, || None);
|
||||
|
||||
cx.render(match *error {
|
||||
Some(error) => rsx!(
|
||||
h1 { "An error occured" }
|
||||
)
|
||||
None => rsx!(
|
||||
input {
|
||||
oninput: move |_| error.set(Some("bad thing happened!")),
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
## Passing error states through components
|
||||
|
||||
If you're dealing with a handful of components with minimal nesting, you can just pass the error handle into child components.
|
||||
|
||||
```rust
|
||||
fn Commandline(cx: Scope) -> Element {
|
||||
let error = use_state(&cx, || None);
|
||||
|
||||
if let Some(error) = **error {
|
||||
return cx.render(rsx!{ "An error occured" });
|
||||
}
|
||||
|
||||
cx.render(rsx!{
|
||||
Child { error: error.clone() }
|
||||
Child { error: error.clone() }
|
||||
Child { error: error.clone() }
|
||||
Child { error: error.clone() }
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
Much like before, our child components can manually set the error during their own actions. The advantage to this pattern is that we can easily isolate error states to a few components at a time, making our app more predictable and robust.
|
||||
|
||||
## Going global
|
||||
|
||||
A strategy for handling cascaded errors in larger apps is through signaling an error using global state. This particular pattern involves creating an "error" context, and then setting it wherever relevant. This particular method is not as "sophisticated" as React's error boundary, but it is more fitting for Rust.
|
||||
|
||||
To get started, consider using a built-in hook like `use_context` and `use_context_provider` or Fermi. Of course, it's pretty easy to roll your own hook too.
|
||||
|
||||
At the "top" of our architecture, we're going to want to explicitly declare a value that could be an error.
|
||||
|
||||
|
||||
```rust
|
||||
enum InputError {
|
||||
None,
|
||||
TooLong,
|
||||
TooShort,
|
||||
}
|
||||
|
||||
static INPUT_ERROR: Atom<InputError> = |_| InputError::None;
|
||||
```
|
||||
|
||||
Then, in our top level component, we want to explicitly handle the possible error state for this part of the tree.
|
||||
|
||||
```rust
|
||||
fn TopLevel(cx: Scope) -> Element {
|
||||
let error = use_read(&cx, INPUT_ERROR);
|
||||
|
||||
match error {
|
||||
TooLong => return cx.render(rsx!{ "FAILED: Too long!" }),
|
||||
TooShort => return cx.render(rsx!{ "FAILED: Too Short!" }),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Now, whenever a downstream component has an error in its actions, it can simply just set its own error state:
|
||||
|
||||
```rust
|
||||
fn Commandline(cx: Scope) -> Element {
|
||||
let set_error = use_set(&cx, INPUT_ERROR);
|
||||
|
||||
cx.render(rsx!{
|
||||
input {
|
||||
oninput: move |evt| {
|
||||
if evt.value.len() > 20 {
|
||||
set_error(InputError::TooLong);
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
This approach to error handling is best in apps that have "well defined" error states. Consider using a crate like `thiserror` or `anyhow` to simplify the generation of the error types.
|
||||
|
||||
This pattern is widely popular in many contexts and is particularly helpful whenever your code generates a non-recoverable error. You can gracefully capture these "global" error states without panicking or mucking up state.
|
||||
@@ -0,0 +1,29 @@
|
||||
# Best Practices
|
||||
|
||||
## Reusable Components
|
||||
|
||||
As much as possible, break your code down into small, reusable components and hooks, instead of implementing large chunks of the UI in a single component. This will help you keep the code maintainable – it is much easier to e.g. add, remove or re-order parts of the UI if it is organized in components.
|
||||
|
||||
Organize your components in modules to keep the codebase easy to navigate!
|
||||
|
||||
## Minimize State Dependencies
|
||||
|
||||
While it is possible to share state between components, this should only be done when necessary. Any component that is associated with a particular state object needs to be re-rendered when that state changes. For this reason:
|
||||
|
||||
- Keep state local to a component if possible
|
||||
- When sharing state through props, only pass down the specific data necessary
|
||||
|
||||
## Reusable Libraries
|
||||
|
||||
When publishing a library designed to work with Dioxus, we highly advise using only the core feature on the `dioxus` crate. This makes your crate compile faster, makes it more stable, and avoids bringing in incompatible libraries that might make it not compile on unsupported platforms.
|
||||
|
||||
|
||||
❌ Don't include unnecessary dependencies in libraries:
|
||||
```toml
|
||||
dioxus = { version = "...", features = ["web", "desktop", "full"]}
|
||||
```
|
||||
|
||||
✅ Only add the features you need:
|
||||
```toml
|
||||
dioxus = { version = "...", features = "core"}
|
||||
```
|
||||
@@ -0,0 +1,20 @@
|
||||
# Contributing
|
||||
|
||||
Development happens in the [Dioxus GitHub repository](https://github.com/DioxusLabs/dioxus). If you've found a bug or have an idea for a feature, please submit an issue (check if someone hasn't [done it already](https://github.com/DioxusLabs/dioxus/issues) though).
|
||||
|
||||
[GitHub discussions](https://github.com/DioxusLabs/dioxus/discussions) can be used as a place to ask for help or talk about features. You can also join [our Discord channel](https://discord.gg/XgGxMSkvUM) where some development discussion happens.
|
||||
|
||||
## Improving Docs
|
||||
|
||||
If you'd like to improve the docs, PRs are welcome! Both Rust docs ([source](https://github.com/DioxusLabs/dioxus/tree/master/packages)) and this guide ([source](https://github.com/DioxusLabs/dioxus/tree/master/docs/guide)) can be found in the GitHub repo.
|
||||
|
||||
## Working on the Ecosystem
|
||||
|
||||
Part of what makes React great is the rich ecosystem. We'd like the same for Dioxus! So if you have a library in mind that you'd like to write, and that you think many people would benefit from, it will be appreciated. You can [browse npm.js](https://www.npmjs.com/search?q=keywords:react-component) for inspiration.
|
||||
|
||||
## Bugs & Features
|
||||
|
||||
If you've fixed [an issue that's open](https://github.com/DioxusLabs/dioxus/issues), feel free to submit a PR! You can also take a look at [the roadmap](./roadmap.md) and work on something in there. Consider [reaching out](https://discord.gg/XgGxMSkvUM) to the team first to make sure everyone's on the same page, and you don't do useless work!
|
||||
|
||||
All pull requests (including those made by a team member) must be approved by at least one other team member.
|
||||
Larger, more nuanced decisions about design, architecture, breaking changes, trade-offs, etc. are made by team consensus.
|
||||
@@ -0,0 +1,493 @@
|
||||
# Custom Renderer
|
||||
|
||||
Dioxus is an incredibly portable framework for UI development. The lessons, knowledge, hooks, and components you acquire over time can always be used for future projects. However, sometimes those projects cannot leverage a supported renderer or you need to implement your own better renderer.
|
||||
|
||||
Great news: the design of the renderer is entirely up to you! We provide suggestions and inspiration with the 1st party renderers, but only really require processing `DomEdits` and sending `UserEvents`.
|
||||
|
||||
## The specifics:
|
||||
|
||||
Implementing the renderer is fairly straightforward. The renderer needs to:
|
||||
|
||||
1. Handle the stream of edits generated by updates to the virtual DOM
|
||||
2. Register listeners and pass events into the virtual DOM's event system
|
||||
|
||||
Essentially, your renderer needs to implement the `RealDom` trait and generate `EventTrigger` objects to update the VirtualDOM. From there, you'll have everything needed to render the VirtualDOM to the screen.
|
||||
|
||||
Internally, Dioxus handles the tree relationship, diffing, memory management, and the event system, leaving as little as possible required for renderers to implement themselves.
|
||||
|
||||
For reference, check out the javascript interperter or tui renderer as a starting point for your custom renderer.
|
||||
|
||||
## DomEdits
|
||||
|
||||
The "DomEdit" type is a serialized enum that represents an atomic operation occurring on the RealDom. The variants roughly follow this set:
|
||||
|
||||
```rust
|
||||
enum DomEdit {
|
||||
PushRoot,
|
||||
AppendChildren,
|
||||
ReplaceWith,
|
||||
InsertAfter,
|
||||
InsertBefore,
|
||||
Remove,
|
||||
CreateTextNode,
|
||||
CreateElement,
|
||||
CreateElementNs,
|
||||
CreatePlaceholder,
|
||||
NewEventListener,
|
||||
RemoveEventListener,
|
||||
SetText,
|
||||
SetAttribute,
|
||||
RemoveAttribute,
|
||||
PopRoot,
|
||||
}
|
||||
```
|
||||
|
||||
The Dioxus diffing mechanism operates as a [stack machine](https://en.wikipedia.org/wiki/Stack_machine) where the "push_root" method pushes a new "real" DOM node onto the stack and "append_child" and "replace_with" both remove nodes from the stack.
|
||||
|
||||
|
||||
### An example
|
||||
|
||||
For the sake of understanding, lets consider this example – a very simple UI declaration:
|
||||
|
||||
```rust
|
||||
rsx!( h1 {"hello world"} )
|
||||
```
|
||||
|
||||
To get things started, Dioxus must first navigate to the container of this h1 tag. To "navigate" here, the internal diffing algorithm generates the DomEdit `PushRoot` where the ID of the root is the container.
|
||||
|
||||
When the renderer receives this instruction, it pushes the actual Node onto its own stack. The real renderer's stack will look like this:
|
||||
|
||||
```rust
|
||||
instructions: [
|
||||
PushRoot(Container)
|
||||
]
|
||||
stack: [
|
||||
ContainerNode,
|
||||
]
|
||||
```
|
||||
|
||||
Next, Dioxus will encounter the h1 node. The diff algorithm decides that this node needs to be created, so Dioxus will generate the DomEdit `CreateElement`. When the renderer receives this instruction, it will create an unmounted node and push into its own stack:
|
||||
|
||||
```rust
|
||||
instructions: [
|
||||
PushRoot(Container),
|
||||
CreateElement(h1),
|
||||
]
|
||||
stack: [
|
||||
ContainerNode,
|
||||
h1,
|
||||
]
|
||||
```
|
||||
Next, Dioxus sees the text node, and generates the `CreateTextNode` DomEdit:
|
||||
```rust
|
||||
instructions: [
|
||||
PushRoot(Container),
|
||||
CreateElement(h1),
|
||||
CreateTextNode("hello world")
|
||||
]
|
||||
stack: [
|
||||
ContainerNode,
|
||||
h1,
|
||||
"hello world"
|
||||
]
|
||||
```
|
||||
Remember, the text node is not attached to anything (it is unmounted) so Dioxus needs to generate an Edit that connects the text node to the h1 element. It depends on the situation, but in this case we use `AppendChildren`. This pops the text node off the stack, leaving the h1 element as the next element in line.
|
||||
|
||||
```rust
|
||||
instructions: [
|
||||
PushRoot(Container),
|
||||
CreateElement(h1),
|
||||
CreateTextNode("hello world"),
|
||||
AppendChildren(1)
|
||||
]
|
||||
stack: [
|
||||
ContainerNode,
|
||||
h1
|
||||
]
|
||||
```
|
||||
We call `AppendChildren` again, popping off the h1 node and attaching it to the parent:
|
||||
```rust
|
||||
instructions: [
|
||||
PushRoot(Container),
|
||||
CreateElement(h1),
|
||||
CreateTextNode("hello world"),
|
||||
AppendChildren(1),
|
||||
AppendChildren(1)
|
||||
]
|
||||
stack: [
|
||||
ContainerNode,
|
||||
]
|
||||
```
|
||||
Finally, the container is popped since we don't need it anymore.
|
||||
```rust
|
||||
instructions: [
|
||||
PushRoot(Container),
|
||||
CreateElement(h1),
|
||||
CreateTextNode("hello world"),
|
||||
AppendChildren(1),
|
||||
AppendChildren(1),
|
||||
PopRoot
|
||||
]
|
||||
stack: []
|
||||
```
|
||||
Over time, our stack looked like this:
|
||||
```rust
|
||||
[]
|
||||
[Container]
|
||||
[Container, h1]
|
||||
[Container, h1, "hello world"]
|
||||
[Container, h1]
|
||||
[Container]
|
||||
[]
|
||||
```
|
||||
|
||||
Notice how our stack is empty once UI has been mounted. Conveniently, this approach completely separates the VirtualDOM and the Real DOM. Additionally, these edits are serializable, meaning we can even manage UIs across a network connection. This little stack machine and serialized edits makes Dioxus independent of platform specifics.
|
||||
|
||||
Dioxus is also really fast. Because Dioxus splits the diff and patch phase, it's able to make all the edits to the RealDOM in a very short amount of time (less than a single frame) making rendering very snappy. It also allows Dioxus to cancel large diffing operations if higher priority work comes in while it's diffing.
|
||||
|
||||
It's important to note that there _is_ one layer of connectedness between Dioxus and the renderer. Dioxus saves and loads elements (the PushRoot edit) with an ID. Inside the VirtualDOM, this is just tracked as a u64.
|
||||
|
||||
Whenever a `CreateElement` edit is generated during diffing, Dioxus increments its node counter and assigns that new element its current NodeCount. The RealDom is responsible for remembering this ID and pushing the correct node when PushRoot(ID) is generated. Dioxus reclaims IDs of elements when removed. To stay in sync with Dioxus you can use a sparce Vec (Vec<Option<T>>) with possibly unoccupied items. You can use the ids as indexes into the Vec for elements, and grow the Vec when a id does not exist.
|
||||
|
||||
This little demo serves to show exactly how a Renderer would need to process an edit stream to build UIs. A set of serialized DomEditss for various demos is available for you to test your custom renderer against.
|
||||
|
||||
## Event loop
|
||||
|
||||
Like most GUIs, Dioxus relies on an event loop to progress the VirtualDOM. The VirtualDOM itself can produce events as well, so it's important that your custom renderer can handle those too.
|
||||
|
||||
The code for the WebSys implementation is straightforward, so we'll add it here to demonstrate how simple an event loop is:
|
||||
|
||||
```rust
|
||||
pub async fn run(&mut self) -> dioxus_core::error::Result<()> {
|
||||
// Push the body element onto the WebsysDom's stack machine
|
||||
let mut websys_dom = crate::new::WebsysDom::new(prepare_websys_dom());
|
||||
websys_dom.stack.push(root_node);
|
||||
|
||||
// Rebuild or hydrate the virtualdom
|
||||
let mutations = self.internal_dom.rebuild();
|
||||
websys_dom.apply_mutations(mutations);
|
||||
|
||||
// Wait for updates from the real dom and progress the virtual dom
|
||||
loop {
|
||||
let user_input_future = websys_dom.wait_for_event();
|
||||
let internal_event_future = self.internal_dom.wait_for_work();
|
||||
|
||||
match select(user_input_future, internal_event_future).await {
|
||||
Either::Left((_, _)) => {
|
||||
let mutations = self.internal_dom.work_with_deadline(|| false);
|
||||
websys_dom.apply_mutations(mutations);
|
||||
},
|
||||
Either::Right((event, _)) => websys_dom.handle_event(event),
|
||||
}
|
||||
|
||||
// render
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
It's important that you decode the real events from your event system into Dioxus' synthetic event system (synthetic meaning abstracted). This simply means matching your event type and creating a Dioxus `UserEvent` type. Right now, the VirtualEvent system is modeled almost entirely around the HTML spec, but we are interested in slimming it down.
|
||||
|
||||
```rust
|
||||
fn virtual_event_from_websys_event(event: &web_sys::Event) -> VirtualEvent {
|
||||
match event.type_().as_str() {
|
||||
"keydown" => {
|
||||
let event: web_sys::KeyboardEvent = event.clone().dyn_into().unwrap();
|
||||
UserEvent::KeyboardEvent(UserEvent {
|
||||
scope_id: None,
|
||||
priority: EventPriority::Medium,
|
||||
name: "keydown",
|
||||
// This should be whatever element is focused
|
||||
element: Some(ElementId(0)),
|
||||
data: Arc::new(KeyboardData{
|
||||
char_code: event.char_code(),
|
||||
key: event.key(),
|
||||
key_code: event.key_code(),
|
||||
alt_key: event.alt_key(),
|
||||
ctrl_key: event.ctrl_key(),
|
||||
meta_key: event.meta_key(),
|
||||
shift_key: event.shift_key(),
|
||||
location: event.location(),
|
||||
repeat: event.repeat(),
|
||||
which: event.which(),
|
||||
})
|
||||
})
|
||||
}
|
||||
_ => todo!()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Custom raw elements
|
||||
|
||||
If you need to go as far as relying on custom elements for your renderer – you totally can. This still enables you to use Dioxus' reactive nature, component system, shared state, and other features, but will ultimately generate different nodes. All attributes and listeners for the HTML and SVG namespace are shuttled through helper structs that essentially compile away (pose no runtime overhead). You can drop in your own elements any time you want, with little hassle. However, you must be absolutely sure your renderer can handle the new type, or it will crash and burn.
|
||||
|
||||
These custom elements are defined as unit structs with trait implementations.
|
||||
|
||||
For example, the `div` element is (approximately!) defined as such:
|
||||
|
||||
```rust
|
||||
struct div;
|
||||
impl div {
|
||||
/// Some glorious documentation about the class property.
|
||||
const TAG_NAME: &'static str = "div";
|
||||
const NAME_SPACE: Option<&'static str> = None;
|
||||
// define the class attribute
|
||||
pub fn class<'a>(&self, cx: NodeFactory<'a>, val: Arguments) -> Attribute<'a> {
|
||||
cx.attr("class", val, None, false)
|
||||
}
|
||||
// more attributes
|
||||
}
|
||||
```
|
||||
|
||||
You've probably noticed that many elements in the `rsx!` macros support on-hover documentation. The approach we take to custom elements means that the unit struct is created immediately where the element is used in the macro. When the macro is expanded, the doc comments still apply to the unit struct, giving tons of in-editor feedback, even inside a proc macro.
|
||||
|
||||
# Native Core
|
||||
|
||||
If you are creating a renderer in rust, native core provides some utilites to implement a renderer. It provides an abstraction over DomEdits and handles layout for you.
|
||||
|
||||
## RealDom
|
||||
|
||||
The `RealDom` is a higher level abstraction over updating the Dom. It updates with `DomEdits` and provides a way to incrementally update the state of nodes based on what attributes change.
|
||||
|
||||
### Example
|
||||
|
||||
Let's build a toy renderer with borders, size, and text color.
|
||||
Before we start lets take a look at an exaple element we can render:
|
||||
```rust
|
||||
cx.render(rsx!{
|
||||
div{
|
||||
color: "red",
|
||||
p{
|
||||
border: "1px solid black",
|
||||
"hello world"
|
||||
}
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
In this tree the color depends on the parent's color. The size depends on the childrens size, the current text, and a text size. The border depends on only the current node.
|
||||
|
||||
In the following diagram arrows represent dataflow:
|
||||
|
||||
[](https://mermaid-js.github.io/mermaid-live-editor/edit#pako:eNqdVNFqgzAU_RXJXizUUZPJmIM-jO0LukdhpCbO0JhIGteW0n9fNK1Oa0brfUnu9VxyzzkXjyCVhIIYZFzu0hwr7X2-JcIzsa3W3wqXuZdKoele22oddfa1Y0Tnfn31muvMfqeCDNq3GmvaNROmaKqZFO1DPTRhP8MOd1fTWYNDvzlmQbBMJZcq9JtjNgY1mLVUhBqQPQeojl3wGCw5PsjqnIe-zXqEL8GZ2Kz0gVMPmoeU3ND4IcuiaLGY2zRouuKncv_qGKv3VodpJe0JVU6QCQ5kgqMyWQVr8hbk4hm1PBcmsuwmnrCVH94rP7xN_ucp8sOB_EPSfz9drYVrkpc_AmH8_yTjJueUc-ntpOJkgt2os9tKjcYlt-DLUiD3UsB2KZCLcwjv3Aq33-g2v0M0xXA0MBy5DUdXi-gcJZriuLmAOSioKjAj5ld8rMsJ0DktaAJicyVYbRKQiJPBVSUx438QpqUCcYb5ls4BrrRcHUTaFizqnWGzR8W5evoFI-bJdw)
|
||||
|
||||
[//]: # "%% mermaid flow chart"
|
||||
[//]: # "flowchart TB"
|
||||
[//]: # " subgraph context"
|
||||
[//]: # " text_width(text width)"
|
||||
[//]: # " end"
|
||||
[//]: # " subgraph state"
|
||||
[//]: # " direction TB"
|
||||
[//]: # " subgraph div state"
|
||||
[//]: # " direction TB"
|
||||
[//]: # " state1(state)-->color1(color)"
|
||||
[//]: # " state1-->border1(border)"
|
||||
[//]: # " text_width-.->layout_width1(layout width)"
|
||||
[//]: # " linkStyle 2 stroke:#ff5500,stroke-width:4px;"
|
||||
[//]: # " state1-->layout_width1"
|
||||
[//]: # " end"
|
||||
[//]: # " subgraph p state"
|
||||
[//]: # " direction TB"
|
||||
[//]: # " state2(state)-->color2(color)"
|
||||
[//]: # " color1-.->color2"
|
||||
[//]: # " linkStyle 5 stroke:#0000ff,stroke-width:4px;"
|
||||
[//]: # " state2-->border2(border)"
|
||||
[//]: # " text_width-.->layout_width2(layout width)"
|
||||
[//]: # " linkStyle 7 stroke:#ff5500,stroke-width:4px;"
|
||||
[//]: # " state2-->layout_width2"
|
||||
[//]: # " layout_width2-.->layout_width1"
|
||||
[//]: # " linkStyle 9 stroke:#00aa00,stroke-width:4px;"
|
||||
[//]: # " end"
|
||||
[//]: # " subgraph hello world state"
|
||||
[//]: # " direction TB"
|
||||
[//]: # " state3(state)-->border3(border)"
|
||||
[//]: # " state3-->color3(color)"
|
||||
[//]: # " color2-.->color3"
|
||||
[//]: # " linkStyle 12 stroke:#0000ff,stroke-width:4px;"
|
||||
[//]: # " text_width-.->layout_width3(layout width)"
|
||||
[//]: # " linkStyle 13 stroke:#ff5500,stroke-width:4px;"
|
||||
[//]: # " state3-->layout_width3"
|
||||
[//]: # " layout_width3-.->layout_width2"
|
||||
[//]: # " linkStyle 15 stroke:#00aa00,stroke-width:4px;"
|
||||
[//]: # " end"
|
||||
[//]: # " end"
|
||||
|
||||
To help in building a Dom, native core provides four traits: State, ChildDepState, ParentDepState, and NodeDepState and a RealDom struct. The ChildDepState, ParentDepState, and NodeDepState provide a way to discribe how some information in a node relates to that of its relatives. By providing how to build a single node from its relations, native-core will derive a way to update the state of all nodes for you with ```#[derive(State)]```. Once you have a state you can provide it as a generic to RealDom. RealDom provides all of the methods to interact and update your new dom.
|
||||
|
||||
```rust
|
||||
use dioxus_native_core::node_ref::*;
|
||||
use dioxus_native_core::state::{ChildDepState, NodeDepState, ParentDepState, State};
|
||||
use dioxus_native_core_macro::{sorted_str_slice, State};
|
||||
|
||||
#[derive(Default, Copy, Clone)]
|
||||
struct Size(f32, f32);
|
||||
// Size only depends on the current node and its children, so it implements ChildDepState
|
||||
impl ChildDepState for Size {
|
||||
// Size accepts a font size context
|
||||
type Ctx = f32;
|
||||
// Size depends on the Size part of each child
|
||||
type DepState = Self;
|
||||
// Size only cares about the width, height, and text parts of the current node
|
||||
const NODE_MASK: NodeMask =
|
||||
NodeMask::new_with_attrs(AttributeMask::Static(&sorted_str_slice!(["width", "height"]))).with_text();
|
||||
fn reduce<'a>(
|
||||
&mut self,
|
||||
node: NodeView,
|
||||
children: impl Iterator<Item = &'a Self::DepState>,
|
||||
ctx: &Self::Ctx,
|
||||
) -> bool
|
||||
where
|
||||
Self::DepState: 'a,
|
||||
{
|
||||
let mut width;
|
||||
let mut height;
|
||||
if let Some(text) = node.text() {
|
||||
// if the node has text, use the text to size our object
|
||||
width = text.len() as f32 * ctx;
|
||||
height = ctx;
|
||||
} else {
|
||||
// otherwise, the size is the maximum size of the children
|
||||
width = *children
|
||||
.reduce(|accum, item| if accum >= item.0 { accum } else { item.0 })
|
||||
.unwrap_or(0.0));
|
||||
height = *children
|
||||
.reduce(|accum, item| if accum >= item.1 { accum } else { item.1 })
|
||||
.unwrap_or(&0.0);
|
||||
}
|
||||
// if the node contains a width or height attribute it overrides the other size
|
||||
for a in node.attibutes(){
|
||||
match a.name{
|
||||
"width" => width = a.value.parse().unwrap(),
|
||||
"height" => height = a.value.parse().unwrap(),
|
||||
// because Size only depends on the width and height, no other attributes will be passed to the member
|
||||
_ => panic!()
|
||||
}
|
||||
}
|
||||
// to determine what other parts of the dom need to be updated we return a boolean that marks if this member changed
|
||||
let changed = (width != self.0) || (height != self.1);
|
||||
*self = Self(width, height);
|
||||
changed
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Default)]
|
||||
struct TextColor {
|
||||
r: u8,
|
||||
g: u8,
|
||||
b: u8,
|
||||
}
|
||||
// TextColor only depends on the current node and its parent, so it implements ParentDepState
|
||||
impl ParentDepState for TextColor {
|
||||
type Ctx = ();
|
||||
// TextColor depends on the TextColor part of the parent
|
||||
type DepState = Self;
|
||||
// TextColor only cares about the color attribute of the current node
|
||||
const NODE_MASK: NodeMask = NodeMask::new_with_attrs(AttributeMask::Static(&["color"]));
|
||||
fn reduce(
|
||||
&mut self,
|
||||
node: NodeView,
|
||||
parent: Option<&Self::DepState>,
|
||||
_ctx: &Self::Ctx,
|
||||
) -> bool {
|
||||
// TextColor only depends on the color tag, so getting the first tag is equivilent to looking through all tags
|
||||
let new = match node.attributes().next() {
|
||||
// if there is a color tag, translate it
|
||||
Some("red") => TextColor { r: 255, g: 0, b: 0 },
|
||||
Some("green") => TextColor { r: 0, g: 255, b: 0 },
|
||||
Some("blue") => TextColor { r: 0, g: 0, b: 255 },
|
||||
Some(_) => panic!("unknown color"),
|
||||
// otherwise check if the node has a parent and inherit that color
|
||||
None => match parent {
|
||||
Some(parent) => *parent,
|
||||
None => Self::default(),
|
||||
},
|
||||
};
|
||||
// check if the member has changed
|
||||
let changed = new != *self;
|
||||
*self = new;
|
||||
changed
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Default)]
|
||||
struct Border(bool);
|
||||
// TextColor only depends on the current node, so it implements NodeDepState
|
||||
impl NodeDepState for Border {
|
||||
type Ctx = ();
|
||||
// Border does not depended on any other member in the current node
|
||||
type DepState = ();
|
||||
// Border does not depended on any other member in the current node
|
||||
const NODE_MASK: NodeMask =
|
||||
NodeMask::new_with_attrs(AttributeMask::Static(&["border"]));
|
||||
fn reduce(&mut self, node: NodeView, _sibling: &Self::DepState, _ctx: &Self::Ctx) -> bool {
|
||||
// check if the node contians a border attribute
|
||||
let new = Self(node.attributes().next().map(|a| a.name == "border").is_some());
|
||||
// check if the member has changed
|
||||
let changed = new != *self;
|
||||
*self = new;
|
||||
changed
|
||||
}
|
||||
}
|
||||
|
||||
// State provides a derive macro, but anotations on the members are needed in the form #[dep_type(dep_member, CtxType)]
|
||||
#[derive(State, Default, Clone)]
|
||||
struct ToyState {
|
||||
// the color member of it's parent and no context
|
||||
#[parent_dep_state(color)]
|
||||
color: TextColor,
|
||||
// depends on the node, and no context
|
||||
#[node_dep_state()]
|
||||
border: Border,
|
||||
// depends on the layout_width member of children and f32 context (for text size)
|
||||
#[child_dep_state(size, f32)]
|
||||
size: Size,
|
||||
}
|
||||
```
|
||||
|
||||
Now that we have our state, we can put it to use in our dom. Re can update the dom with update_state to update the structure of the dom (adding, removing, and chaning properties of nodes) and then apply_mutations to update the ToyState for each of the nodes that changed.
|
||||
```rust
|
||||
fn main(){
|
||||
fn app(cx: Scope) -> Element {
|
||||
cx.render(rsx!{
|
||||
div{
|
||||
color: "red",
|
||||
"hello world"
|
||||
}
|
||||
})
|
||||
}
|
||||
let vdom = VirtualDom::new(app);
|
||||
let rdom: RealDom<ToyState> = RealDom::new();
|
||||
|
||||
let mutations = dom.rebuild();
|
||||
// update the structure of the real_dom tree
|
||||
let to_update = rdom.apply_mutations(vec![mutations]);
|
||||
let mut ctx = AnyMap::new();
|
||||
// set the font size to 3.3
|
||||
ctx.insert(3.3);
|
||||
// update the ToyState for nodes in the real_dom tree
|
||||
let _to_rerender = rdom.update_state(&dom, to_update, ctx).unwrap();
|
||||
|
||||
// we need to run the vdom in a async runtime
|
||||
tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()?
|
||||
.block_on(async {
|
||||
loop{
|
||||
let wait = vdom.wait_for_work();
|
||||
let mutations = vdom.work_with_deadline(|| false);
|
||||
let to_update = rdom.apply_mutations(mutations);
|
||||
let mut ctx = AnyMap::new();
|
||||
ctx.insert(3.3);
|
||||
let _to_rerender = rdom.update_state(vdom, to_update, ctx).unwrap();
|
||||
|
||||
// render...
|
||||
}
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
## Layout
|
||||
For most platforms the layout of the Elements will stay the same. The layout_attributes module provides a way to apply html attributes to a stretch layout style.
|
||||
|
||||
## Conclusion
|
||||
That should be it! You should have nearly all the knowledge required on how to implement your own renderer. We're super interested in seeing Dioxus apps brought to custom desktop renderers, mobile renderer, video game UI, and even augmented reality! If you're interesting in contributing to any of the these projects, don't be afraid to reach out or join the community.
|
||||
@@ -0,0 +1,31 @@
|
||||
# Component Children
|
||||
|
||||
In some cases, you may wish to create a component that acts as a container for some other content, without the component needing to know what that content is. To achieve this, create a prop of type `Element`:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/component_element_props.rs:Clickable}}
|
||||
```
|
||||
|
||||
Then, when rendering the component, you can pass in the output of `cx.render(rsx!(...))`:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/component_element_props.rs:Clickable_usage}}
|
||||
```
|
||||
|
||||
> Note: Since `Element<'a>` is a borrowed prop, there will be no memoization.
|
||||
|
||||
> Warning: While it may compile, do not include the same `Element` more than once in the RSX. The resulting behavior is unspecified.
|
||||
|
||||
## The `children` field
|
||||
|
||||
Rather than passing the RSX through a regular prop, you may wish to accept children similarly to how elements can have children. The "magic" `children` prop lets you achieve this:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/component_children.rs:Clickable}}
|
||||
```
|
||||
|
||||
This makes using the component much simpler: simply put the RSX inside the `{}` brackets – and there is no need for a `render` call or another macro!
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/component_children.rs:Clickable_usage}}
|
||||
```
|
||||
@@ -0,0 +1,141 @@
|
||||
# Component Props
|
||||
|
||||
Just like you can pass arguments to a function, you can pass props to a component that customize its behavior! The components we've seen so far didn't accept any props – so let's write some components that do.
|
||||
|
||||
## `#[derive(Props)]`
|
||||
|
||||
Component props are a single struct annotated with `#[derive(Props)]`. For a component to accept props, the type of its argument must be `Scope<YourPropsStruct>`. Then, you can access the value of the props using `cx.props`.
|
||||
|
||||
There are 2 flavors of Props structs:
|
||||
- Owned props:
|
||||
- Don't have an associated lifetime
|
||||
- Implement `PartialEq`, allowing for memoization (if the props don't change, Dioxus won't re-render the component)
|
||||
- Borrowed props:
|
||||
- [Borrow](https://doc.rust-lang.org/beta/rust-by-example/scope/borrow.html) from a parent component
|
||||
- Cannot be memoized due to lifetime constraints
|
||||
|
||||
|
||||
### Owned Props
|
||||
|
||||
Owned Props are very simple – they don't borrow anything. Example:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/component_owned_props.rs:Likes}}
|
||||
```
|
||||
|
||||
You can then pass prop values to the component the same way you would pass attributes to an element:
|
||||
```rust
|
||||
{{#include ../../examples/component_owned_props.rs:App}}
|
||||
```
|
||||
|
||||

|
||||
|
||||
### Borrowed Props
|
||||
|
||||
Owning props works well if your props are easy to copy around – like a single number. But what if we need to pass a larger data type, like a String from an `App` Component to a `TitleCard` subcomponent? A naive solution might be to [`.clone()`](https://doc.rust-lang.org/std/clone/trait.Clone.html) the String, creating a copy of it for the subcomponent – but this would be inefficient, especially for larger Strings.
|
||||
|
||||
Rust allows for something more efficient – borrowing the String as a `&str` – this is what Borrowed Props are for!
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/component_borrowed_props.rs:TitleCard}}
|
||||
```
|
||||
|
||||
We can then use the component like this:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/component_borrowed_props.rs:App}}
|
||||
```
|
||||

|
||||
|
||||
|
||||
## Prop Options
|
||||
|
||||
The `#[derive(Props)]` macro has some features that let you customize the behavior of props.
|
||||
|
||||
### Optional Props
|
||||
|
||||
You can create optional fields by using the `Option<…>` type for a field:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/component_props_options.rs:OptionalProps}}
|
||||
```
|
||||
|
||||
Then, you can choose to either provide them or not:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/component_props_options.rs:OptionalProps_usage}}
|
||||
```
|
||||
|
||||
### Explicitly Required `Option`s
|
||||
|
||||
If you want to explicitly require an `Option`, and not an optional prop, you can annotate it with `#[props(!optional)]`:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/component_props_options.rs:ExplicitOption}}
|
||||
```
|
||||
|
||||
Then, you have to explicitly pass either `Some("str")` or `None`:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/component_props_options.rs:ExplicitOption_usage}}
|
||||
```
|
||||
|
||||
### Default Props
|
||||
|
||||
You can use `#[props(default = 42)]` to make a field optional and specify its default value:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/component_props_options.rs:DefaultComponent}}
|
||||
```
|
||||
|
||||
Then, similarly to optional props, you don't have to provide it:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/component_props_options.rs:DefaultComponent_usage}}
|
||||
```
|
||||
|
||||
### Automatic Conversion with `.into`
|
||||
|
||||
It is common for Rust functions to accept `impl Into<SomeType>` rather than just `SomeType` to support a wider range of parameters. If you want similar functionality with props, you can use `#[props(into)]`. For example, you could add it on a `String` prop – and `&str` will also be automatically accepted, as it can be converted into `String`:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/component_props_options.rs:IntoComponent}}
|
||||
```
|
||||
|
||||
Then, you can use it so:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/component_props_options.rs:IntoComponent_usage}}
|
||||
```
|
||||
|
||||
## The `inline_props` macro
|
||||
|
||||
So far, every Component function we've seen had a corresponding ComponentProps struct to pass in props. This was quite verbose... Wouldn't it be nice to have props as simple function arguments? Then we wouldn't need to define a Props struct, and instead of typing `cx.props.whatever`, we could just use `whatever` directly!
|
||||
|
||||
`inline_props` allows you to do just that. Instead of typing the "full" version:
|
||||
|
||||
```rust
|
||||
#[derive(Props, PartialEq)]
|
||||
struct TitleCardProps {
|
||||
title: String,
|
||||
}
|
||||
|
||||
fn TitleCard(cx: Scope<TitleCardProps>) -> Element {
|
||||
cx.render(rsx!{
|
||||
h1 { "{cx.props.title}" }
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
...you can define a function that accepts props as arguments. Then, just annotate it with `#[inline_props]`, and the macro will turn it into a regular Component for you:
|
||||
|
||||
```rust
|
||||
#[inline_props]
|
||||
fn TitleCard(cx: Scope, title: String) -> Element {
|
||||
cx.render(rsx!{
|
||||
h1 { "{title}" }
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
> While the new Component is shorter and easier to read, this macro should not be used by library authors since you have less control over Prop documentation.
|
||||
@@ -0,0 +1,27 @@
|
||||
# Components
|
||||
|
||||
Just like you wouldn't want to write a complex program in a single, long, `main` function, you shouldn't build a complex UI in a single `App` function. Instead, it would be better to break down the functionality of an app in logical parts called components.
|
||||
|
||||
A component is a Rust function, named in UpperCammelCase, that takes a `Scope` parameter and returns an `Element` describing the UI it wants to render. In fact, our `App` function is a component!
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/hello_world_desktop.rs:component}}
|
||||
```
|
||||
|
||||
> You'll probably want to add `#![allow(non_snake_case)]` to the top of your crate to avoid warnings about the function name
|
||||
|
||||
A Component is responsible for some rendering task – typically, rendering an isolated part of the user interface. For example, you could have an `About` component that renders a short description of Dioxus Labs:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/components.rs:About}}
|
||||
```
|
||||
|
||||
Then, you can render your component in another component, similarly to how elements are rendered:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/components.rs:App}}
|
||||
```
|
||||
|
||||

|
||||
|
||||
> At this point, it might seem like components are nothing more than functions. However, as you learn more about the features of Dioxus, you'll see that they are actually more powerful!
|
||||
|
After Width: | Height: | Size: 7.7 KiB |
|
After Width: | Height: | Size: 6.2 KiB |
|
After Width: | Height: | Size: 19 KiB |
@@ -0,0 +1,106 @@
|
||||
# Describing the UI
|
||||
|
||||
Dioxus is a *declarative* framework. This means that instead of telling Dioxus what to do (e.g. to "create an element" or "set color to red") we simply *declare* what we want the UI to look like using RSX.
|
||||
|
||||
You have already seen a simple example or RSX syntax in the "hello world" application:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/hello_world_desktop.rs:component}}
|
||||
```
|
||||
|
||||
Here, we use the `rsx!` macro to *declare* that we want a `div` element, containing the text `"Hello, world!"`. Dioxus takes the RSX and constructs a UI from it.
|
||||
|
||||
## RSX Features
|
||||
|
||||
RSX is very similar to HTML in that it describes elements with attributes and children. Here's an empty `div` element in RSX, as well as the resulting HTML:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/rsx_overview.rs:empty}}
|
||||
```
|
||||
```html
|
||||
<div></div>
|
||||
```
|
||||
|
||||
### Children
|
||||
|
||||
To add children to an element, put them inside the `{}` brackets. They can be either other elements, or text. For example, you could have an `ol` (ordered list) element, containing 3 `li` (list item) elements, each of which contains some text:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/rsx_overview.rs:children}}
|
||||
```
|
||||
```html
|
||||
<ol>
|
||||
<li>First Item</li>
|
||||
<li>Second Item</li>
|
||||
<li>Third Item</li>
|
||||
</ol>
|
||||
```
|
||||
|
||||
### Fragments
|
||||
|
||||
You can also "group" elements by wrapping them in `Fragment {}`. This will not create any additional elements.
|
||||
|
||||
> Note: you can also render multiple elements at the top level of `rsx!` and they will be automatically grouped – no need for an explicit `Fragment {}` there.
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/rsx_overview.rs:fragments}}
|
||||
```
|
||||
|
||||
```html
|
||||
<p>First Item</p>
|
||||
<p>Second Item</p>
|
||||
<span>a group</span>
|
||||
<span>of three</span>
|
||||
<span>items</span>
|
||||
```
|
||||
|
||||
### Attributes
|
||||
|
||||
Attributes are also specified inside the `{}` brackets, using the `name: value` syntax. You can provide the value as a literal in the RSX:
|
||||
```rust
|
||||
{{#include ../../examples/rsx_overview.rs:attributes}}
|
||||
```
|
||||
```html
|
||||
<a href="https://www.youtube.com/watch?v=dQw4w9WgXcQ" class="primary_button" autofocus="true">Log In</a>
|
||||
```
|
||||
|
||||
> Note: All attributes defined in `dioxus-html` follow the snake_case naming convention. They transform their `snake_case` names to HTML's `camelCase` attributes.
|
||||
|
||||
#### Custom Attributes
|
||||
|
||||
Dioxus has a pre-configured set of attributes that you can use. RSX is validated at compile time to make sure you didn't specify an invalid attribute. If you want to override this behavior with a custom attribute name, specify the attribute in quotes:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/rsx_overview.rs:custom_attributes}}
|
||||
```
|
||||
```html
|
||||
<b customAttribute="value">
|
||||
Rust is cool
|
||||
</b>
|
||||
```
|
||||
|
||||
### Interpolation
|
||||
|
||||
Similarly to how you can [format](https://doc.rust-lang.org/rust-by-example/hello/print/fmt.html) Rust strings, you can also interpolate in RSX text. Use `{variable}` to Display the value of a variable in a string, or `{variable:?}` to use the Debug representation:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/rsx_overview.rs:formatting}}
|
||||
```
|
||||
```html
|
||||
|
||||
<div class="country-es">Coordinates: (42, 0)
|
||||
<div>ES</div>
|
||||
<div>42</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
### Expressions
|
||||
|
||||
You can include arbitrary Rust expressions within RSX, but you must escape them in `[]` brackets:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/rsx_overview.rs:expression}}
|
||||
```
|
||||
```html
|
||||
<span>DIOXUS</span>
|
||||
```
|
||||
@@ -0,0 +1,63 @@
|
||||
# Special Attributes
|
||||
|
||||
While most attributes are simply passed on to the HTML, some have special behaviors.
|
||||
|
||||
## The HTML Escape Hatch
|
||||
|
||||
If you're working with pre-rendered assets, output from templates, or output from a JS library, then you might want to pass HTML directly instead of going through Dioxus. In these instances, reach for `dangerous_inner_html`.
|
||||
|
||||
For example, shipping a markdown-to-Dioxus converter might significantly bloat your final application size. Instead, you'll want to pre-render your markdown to HTML and then include the HTML directly in your output. We use this approach for the [Dioxus homepage](https://dioxuslabs.com):
|
||||
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/dangerous_inner_html.rs:dangerous_inner_html}}
|
||||
```
|
||||
|
||||
> Note! This attribute is called "dangerous_inner_html" because it is **dangerous** to pass it data you don't trust. If you're not careful, you can easily expose [cross-site scripting (XSS)](https://en.wikipedia.org/wiki/Cross-site_scripting) attacks to your users.
|
||||
>
|
||||
> If you're handling untrusted input, make sure to sanitize your HTML before passing it into `dangerous_inner_html` – or just pass it to a Text Element to escape any HTML tags.
|
||||
|
||||
|
||||
## Boolean Attributes
|
||||
|
||||
Most attributes, when rendered, will be rendered exactly as the input you provided. However, some attributes are considered "boolean" attributes and just their presence determines whether they affect the output. For these attributes, a provided value of `"false"` will cause them to be removed from the target element.
|
||||
|
||||
So this RSX wouldn't actually render the `hidden` attribute:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/boolean_attribute.rs:boolean_attribute}}
|
||||
```
|
||||
```html
|
||||
<div>hello</div>
|
||||
```
|
||||
|
||||
Not all attributes work like this however. *Only the following attributes* have this behavior:
|
||||
|
||||
- `allowfullscreen`
|
||||
- `allowpaymentrequest`
|
||||
- `async`
|
||||
- `autofocus`
|
||||
- `autoplay`
|
||||
- `checked`
|
||||
- `controls`
|
||||
- `default`
|
||||
- `defer`
|
||||
- `disabled`
|
||||
- `formnovalidate`
|
||||
- `hidden`
|
||||
- `ismap`
|
||||
- `itemscope`
|
||||
- `loop`
|
||||
- `multiple`
|
||||
- `muted`
|
||||
- `nomodule`
|
||||
- `novalidate`
|
||||
- `open`
|
||||
- `playsinline`
|
||||
- `readonly`
|
||||
- `required`
|
||||
- `reversed`
|
||||
- `selected`
|
||||
- `truespeed`
|
||||
|
||||
For any other attributes, a value of `"false"` will be sent directly to the DOM.
|
||||
@@ -0,0 +1,45 @@
|
||||
# Desktop Application
|
||||
|
||||
Build a standalone native desktop app that looks and feels the same across operating systems.
|
||||
|
||||
Apps built with Dioxus are typically <5mb in size and use existing system resources, so they won't hog extreme amounts of RAM or memory.
|
||||
|
||||
Examples:
|
||||
- [File explorer](https://github.com/DioxusLabs/example-projects/blob/master/file-explorer)
|
||||
- [WiFi scanner](https://github.com/DioxusLabs/example-projects/blob/master/wifi-scanner)
|
||||
|
||||
[](https://github.com/DioxusLabs/example-projects/tree/master/file-explorer)
|
||||
|
||||
## Support
|
||||
|
||||
The desktop is a powerful target for Dioxus, but is currently limited in capability when compared to the Web platform. Currently, desktop apps are rendered with the platform's WebView library, but your Rust code is running natively on a native thread. This means that browser APIs are *not* available, so rendering WebGL, Canvas, etc is not as easy as the Web. However, native system APIs *are* accessible, so streaming, WebSockets, filesystem, etc are all viable APIs. In the future, we plan to move to a custom webrenderer-based DOM renderer with WGPU integrations.
|
||||
|
||||
Dioxus Desktop is built off [Tauri](https://tauri.app/). Right now there aren't any Dioxus abstractions over keyboard shortcuts, menubar, handling, etc, so you'll want to leverage Tauri – mostly [Wry](http://github.com/tauri-apps/wry/) and [Tao](http://github.com/tauri-apps/tao)) directly.
|
||||
|
||||
## Creating a Project
|
||||
|
||||
Create a new crate:
|
||||
|
||||
```shell
|
||||
cargo new --bin demo
|
||||
cd demo
|
||||
```
|
||||
|
||||
Add Dioxus with the `desktop` feature (this will edit `Cargo.toml`):
|
||||
|
||||
```shell
|
||||
cargo add dioxus --features desktop
|
||||
```
|
||||
|
||||
> If your system does not provide the `libappindicator3` library, like Debian/bullseye, you can enable the replacement `ayatana` with an additional flag:
|
||||
>
|
||||
>```shell
|
||||
># On Debian/bullseye use:
|
||||
>cargo add dioxus --features desktop --features ayatana
|
||||
>```
|
||||
|
||||
Edit your `main.rs`:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/hello_world_desktop.rs:all}}
|
||||
```
|
||||
@@ -0,0 +1,25 @@
|
||||
# Setting Up Hot Reload
|
||||
|
||||
1. Hot reloading allows much faster iteration times inside of rsx calls by interperting them and streaming the edits.
|
||||
2. It is useful when changing the styling/layout of a program, but will not help with changing the logic of a program.
|
||||
3. Currently the cli only implements hot reloading for the web renderer.
|
||||
|
||||
# Setup
|
||||
Install [dioxus-cli](https://github.com/DioxusLabs/cli).
|
||||
Enable the hot-reload feature on dioxus:
|
||||
```toml
|
||||
dioxus = { version = "*", features = ["web", "hot-reload"] }
|
||||
```
|
||||
|
||||
# Usage
|
||||
1. run:
|
||||
```
|
||||
dioxus serve --hot-reload
|
||||
```
|
||||
2. change some code within a rsx macro
|
||||
3. open your localhost in a browser
|
||||
4. save and watch the style change without recompiling
|
||||
|
||||
# Limitations
|
||||
1. The interperter can only use expressions that existed on the last full recompile. If you introduce a new variable or expression to the rsx call, it will trigger a full recompile to capture the expression.
|
||||
2. Components and Iterators can contain abritary rust code, and will trigger a full recompile when changed.
|
||||
@@ -0,0 +1,74 @@
|
||||
# Getting Started
|
||||
|
||||
This section will help you set up your Dioxus project!
|
||||
|
||||
## Prerequisites
|
||||
|
||||
### An Editor
|
||||
|
||||
Dioxus integrates very well with the [Rust-Analyzer LSP plugin](https://rust-analyzer.github.io) which will provide appropriate syntax highlighting, code navigation, folding, and more.
|
||||
|
||||
### Rust
|
||||
|
||||
Head over to [https://rust-lang.org](http://rust-lang.org) and install the Rust compiler.
|
||||
|
||||
We strongly recommend going through the [official Rust book](https://doc.rust-lang.org/book/ch01-00-getting-started.html) _completely_. However, our hope is that a Dioxus app can serve as a great first Rust project. With Dioxus, you'll learn about:
|
||||
|
||||
- Error handling
|
||||
- Structs, Functions, Enums
|
||||
- Closures
|
||||
- Macros
|
||||
|
||||
We've put a lot of care into making Dioxus syntax familiar and easy to understand, so you won't need deep knowledge on async, lifetimes, or smart pointers until you really start building complex Dioxus apps.
|
||||
|
||||
### Platform-Specific Dependencies
|
||||
|
||||
#### Windows
|
||||
|
||||
Windows Desktop apps depend on WebView2 – a library which should be installed in all modern Windows distributions. If you have Edge installed, then Dioxus will work fine. If you *don't* have Webview2, [then you can install it through Microsoft](https://developer.microsoft.com/en-us/microsoft-edge/webview2/). MS provides 3 options:
|
||||
|
||||
1. A tiny "evergreen" *bootstrapper* which will fetch an installer from Microsoft's CDN
|
||||
2. A tiny *installer* which will fetch Webview2 from Microsoft's CDN
|
||||
3. A statically linked version of Webview2 in your final binary for offline users
|
||||
|
||||
For development purposes, use Option 1.
|
||||
|
||||
#### Linux
|
||||
|
||||
Webview Linux apps require WebkitGtk. When distributing, this can be part of your dependency tree in your `.rpm` or `.deb`. However, it's very likely that your users will already have WebkitGtk.
|
||||
|
||||
```bash
|
||||
sudo apt install libwebkit2gtk-4.0-dev libgtk-3-dev libappindicator3-dev
|
||||
```
|
||||
|
||||
When using Debian/bullseye `libappindicator3-dev` is no longer available but replaced by `libayatana-appindicator3-dev`.
|
||||
|
||||
```bash
|
||||
# on Debian/bullseye use:
|
||||
sudo apt install libwebkit2gtk-4.0-dev libgtk-3-dev libayatana-appindicator3-dev
|
||||
```
|
||||
|
||||
If you run into issues, make sure you have all the basics installed, as outlined in the [Tauri docs](https://tauri.studio/v1/guides/getting-started/prerequisites#setting-up-linux).
|
||||
|
||||
|
||||
#### MacOS
|
||||
|
||||
Currently – everything for macOS is built right in! However, you might run into an issue if you're using nightly Rust due to some permissions issues in our Tao dependency (which have been resolved but not published).
|
||||
|
||||
### Suggested Cargo Extensions
|
||||
|
||||
If you want to keep your traditional `npm install XXX` workflow for adding packages, you might want to install `cargo-edit` and a few other fun `cargo` extensions:
|
||||
|
||||
- [cargo-expand](https://github.com/dtolnay/cargo-expand) for expanding macro calls
|
||||
- [cargo tree](https://doc.rust-lang.org/cargo/commands/cargo-tree.html) – an integrated cargo command that lets you inspect your dependency tree
|
||||
|
||||
|
||||
## Setup Guides
|
||||
|
||||
Dioxus supports multiple platforms. Depending on what you want, the setup is a bit different.
|
||||
|
||||
- [Web](web.md): running in the browser using WASM
|
||||
- [Server Side Rendering](ssr.md): render Dioxus HTML as text
|
||||
- [Desktop](desktop.md): a standalone app using webview
|
||||
- [Mobile](mobile.md)
|
||||
- [Terminal UI](tui.md): terminal text-based graphic interface
|
||||
@@ -0,0 +1,74 @@
|
||||
# Mobile App
|
||||
|
||||
Build a mobile app with Dioxus!
|
||||
|
||||
Example: [Todo App](https://github.com/DioxusLabs/example-projects/blob/master/ios_demo)
|
||||
|
||||
## Support
|
||||
Mobile is currently the least-supported renderer target for Dioxus. Mobile apps are rendered with the platform's WebView, meaning that animations, transparency, and native widgets are not currently achievable.
|
||||
|
||||
In addition, iOS is the only supported Mobile Platform. It is possible to get Dioxus running on Android and rendered with WebView, but the Rust windowing library that Dioxus uses – tao – does not currently support Android.
|
||||
|
||||
Mobile support is currently best suited for CRUD-style apps, ideally for internal teams who need to develop quickly but don't care much about animations or native widgets.
|
||||
|
||||
## Getting Set up
|
||||
|
||||
Getting set up with mobile can be quite challenging. The tooling here isn't great (yet) and might take some hacking around to get things working. macOS M1 is broadly unexplored and might not work for you.
|
||||
|
||||
We're going to be using `cargo-mobile` to build for mobile. First, install it:
|
||||
|
||||
```shell
|
||||
cargo install --git https://github.com/BrainiumLLC/cargo-mobile
|
||||
```
|
||||
|
||||
And then initialize your app for the right platform. Use the `winit` template for now. Right now, there's no "Dioxus" template in cargo-mobile.
|
||||
|
||||
```shell
|
||||
cargo mobile init
|
||||
```
|
||||
|
||||
We're going to completely clear out the `dependencies` it generates for us, swapping out `winit` with `dioxus-mobile`.
|
||||
|
||||
```toml
|
||||
|
||||
[package]
|
||||
name = "dioxus-ios-demo"
|
||||
version = "0.1.0"
|
||||
authors = ["Jonathan Kelley <jkelleyrtp@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
|
||||
# leave the `lib` declaration
|
||||
[lib]
|
||||
crate-type = ["staticlib", "cdylib", "rlib"]
|
||||
|
||||
|
||||
# leave the binary it generates for us
|
||||
[[bin]]
|
||||
name = "dioxus-ios-demo-desktop"
|
||||
path = "gen/bin/desktop.rs"
|
||||
|
||||
# clear all the dependencies
|
||||
[dependencies]
|
||||
mobile-entry-point = "0.1.0"
|
||||
dioxus = { version = "*", features = ["mobile"] }
|
||||
simple_logger = "*"
|
||||
```
|
||||
|
||||
Edit your `lib.rs`:
|
||||
|
||||
```rust
|
||||
use dioxus::prelude::*;
|
||||
|
||||
fn main() {
|
||||
dioxus::mobile::launch(app);
|
||||
}
|
||||
|
||||
fn app(cx: Scope) -> Element {
|
||||
cx.render(rsx!{
|
||||
div {
|
||||
"hello world!"
|
||||
}
|
||||
})
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,109 @@
|
||||
# Server-Side Rendering
|
||||
|
||||
The Dioxus VirtualDom can be rendered server-side.
|
||||
|
||||
[Example: Dioxus DocSite](https://github.com/dioxusLabs/docsite)
|
||||
|
||||
## Multithreaded Support
|
||||
|
||||
The Dioxus VirtualDom, sadly, is not currently `Send`. Internally, we use quite a bit of interior mutability which is not thread-safe. This means you can't easily use Dioxus with most web frameworks like Tide, Rocket, Axum, etc.
|
||||
|
||||
To solve this, you'll want to spawn a VirtualDom on its own thread and communicate with it via channels.
|
||||
|
||||
When working with web frameworks that require `Send`, it is possible to render a VirtualDom immediately to a String – but you cannot hold the VirtualDom across an await point. For retained-state SSR (essentially LiveView), you'll need to create a pool of VirtualDoms.
|
||||
|
||||
|
||||
## Setup
|
||||
|
||||
If you just want to render `rsx!` or a VirtualDom to HTML, check out the API docs. It's pretty simple:
|
||||
|
||||
```rust
|
||||
// We can render VirtualDoms
|
||||
let mut vdom = VirtualDom::new(app);
|
||||
let _ = vdom.rebuild();
|
||||
println!("{}", dioxus::ssr::render_vdom(&vdom));
|
||||
|
||||
// Or we can render rsx! calls directly
|
||||
println!( "{}", dioxus::ssr::render_lazy(rsx! { h1 { "Hello, world!" } } );
|
||||
```
|
||||
|
||||
However, for this guide, we're going to show how to use Dioxus SSR with `Axum`.
|
||||
|
||||
Make sure you have Rust and Cargo installed, and then create a new project:
|
||||
|
||||
```shell
|
||||
cargo new --bin demo
|
||||
cd app
|
||||
```
|
||||
|
||||
Add Dioxus with the `ssr` feature:
|
||||
|
||||
```shell
|
||||
cargo add dioxus --features ssr
|
||||
```
|
||||
|
||||
Next, add all the Axum dependencies. This will be different if you're using a different Web Framework
|
||||
|
||||
```
|
||||
cargo add tokio --features full
|
||||
cargo add axum
|
||||
```
|
||||
|
||||
Your dependencies should look roughly like this:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
axum = "0.4.5"
|
||||
dioxus = { version = "*", features = ["ssr"] }
|
||||
tokio = { version = "1.15.0", features = ["full"] }
|
||||
```
|
||||
|
||||
Now, set up your Axum app to respond on an endpoint.
|
||||
|
||||
```rust
|
||||
use axum::{response::Html, routing::get, Router};
|
||||
use dioxus::prelude::*;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 3000));
|
||||
println!("listening on http://{}", addr);
|
||||
|
||||
axum::Server::bind(&addr)
|
||||
.serve(
|
||||
Router::new()
|
||||
.route("/", get(app_endpoint))
|
||||
.into_make_service(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
```
|
||||
|
||||
And then add our endpoint. We can either render `rsx!` directly:
|
||||
|
||||
```rust
|
||||
async fn app_endpoint() -> Html<String> {
|
||||
Html(dioxus::ssr::render_lazy(rsx! {
|
||||
h1 { "hello world!" }
|
||||
}))
|
||||
}
|
||||
```
|
||||
|
||||
Or we can render VirtualDoms.
|
||||
|
||||
```rust
|
||||
async fn app_endpoint() -> Html<String> {
|
||||
fn app(cx: Scope) -> Element {
|
||||
cx.render(rsx!(h1 { "hello world" }))
|
||||
}
|
||||
let mut app = VirtualDom::new(app);
|
||||
let _ = app.rebuild();
|
||||
|
||||
Html(dioxus::ssr::render_vdom(&app))
|
||||
}
|
||||
```
|
||||
|
||||
And that's it!
|
||||
|
||||
> You might notice that you cannot hold the VirtualDom across an await point. Dioxus is currently not ThreadSafe, so it _must_ remain on the thread it started. We are working on loosening this requirement.
|
||||
@@ -0,0 +1,46 @@
|
||||
# Terminal UI
|
||||
|
||||
You can build a text-based interface that will run in the terminal using Dioxus.
|
||||
|
||||

|
||||
|
||||
> Note: this book was written with HTML-based platforms in mind. You might be able to follow along with TUI, but you'll have to adapt a bit.
|
||||
|
||||
## Support
|
||||
|
||||
TUI support is currently quite experimental. Even the project name will change. But, if you're willing to venture into the realm of the unknown, this guide will get you started.
|
||||
|
||||
## Getting Set up
|
||||
|
||||
|
||||
Start by making a new package and adding our TUI feature.
|
||||
|
||||
```shell
|
||||
cargo new --bin demo
|
||||
cd demo
|
||||
cargo add dioxus --features tui
|
||||
```
|
||||
|
||||
Then, edit your `main.rs` with the basic template.
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/hello_world_tui.rs}}
|
||||
```
|
||||
|
||||
To run our app:
|
||||
|
||||
```shell
|
||||
cargo run
|
||||
```
|
||||
|
||||
Press "ctrl-c" to close the app. To switch from "ctrl-c" to just "q" to quit you can launch the app with a configuration to disable the default quit and use the root TuiContext to quit on your own.
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/hello_world_tui_no_ctrl_c.rs}}
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
- Our TUI package uses flexbox for layout
|
||||
- 1px is one character lineheight. Your regular CSS px does not translate.
|
||||
- If your app panics, your terminal is wrecked. This will be fixed eventually.
|
||||
@@ -0,0 +1,72 @@
|
||||
# Web
|
||||
|
||||
Build single-page applications that run in the browser with Dioxus. To run on the Web, your app must be compiled to WebAssembly and depend on the `dioxus` crate with the `web` feature enabled.
|
||||
|
||||
A build of Dioxus for the web will be roughly equivalent to the size of a React build (70kb vs 65kb), but will load significantly faster due to [WebAssembly's StreamingCompile](https://hacks.mozilla.org/2018/01/making-webassembly-even-faster-firefoxs-new-streaming-and-tiering-compiler/) option.
|
||||
|
||||
Examples:
|
||||
- [TodoMVC](https://github.com/DioxusLabs/example-projects/tree/master/todomvc)
|
||||
- [ECommerce](https://github.com/DioxusLabs/example-projects/tree/master/ecommerce-site)
|
||||
|
||||
[](https://github.com/DioxusLabs/example-projects/blob/master/todomvc)
|
||||
|
||||
> Note: Because of the limitations of Wasm, not every crate will work with your web apps, so you'll need to make sure that your crates work without native system calls (timers, IO, etc).
|
||||
|
||||
## Support
|
||||
|
||||
The Web is the best-supported target platform for Dioxus.
|
||||
|
||||
## Tooling
|
||||
|
||||
To develop your Dioxus app for the web, you'll need a tool to build and serve your assets. We recommend using [trunk](https://trunkrs.dev) which includes a build system, Wasm optimization, a dev server, and support for SASS/CSS:
|
||||
|
||||
```shell
|
||||
cargo install trunk
|
||||
```
|
||||
|
||||
Make sure the `wasm32-unknown-unknown` target is installed:
|
||||
```shell
|
||||
rustup target add wasm32-unknown-unknown
|
||||
```
|
||||
|
||||
## Creating a Project
|
||||
|
||||
Create a new crate:
|
||||
|
||||
```shell
|
||||
cargo new --bin demo
|
||||
cd demo
|
||||
```
|
||||
|
||||
Add Dioxus as a dependency with the `web` feature:
|
||||
|
||||
```bash
|
||||
cargo add dioxus --features web
|
||||
```
|
||||
|
||||
Add an `index.html` for Trunk to use. Make sure your "mount point" element has an ID of "main":
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
</head>
|
||||
<body>
|
||||
<div id="main"> </div>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
Edit your `main.rs`:
|
||||
```rust
|
||||
{{#include ../../examples/hello_world_web.rs}}
|
||||
```
|
||||
|
||||
|
||||
And to serve our app:
|
||||
|
||||
```bash
|
||||
trunk serve
|
||||
```
|
||||
|
After Width: | Height: | Size: 191 KiB |
|
After Width: | Height: | Size: 3.6 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 58 KiB |
|
After Width: | Height: | Size: 121 KiB |
|
After Width: | Height: | Size: 272 KiB |
@@ -0,0 +1,51 @@
|
||||
# Introduction
|
||||
|
||||

|
||||
|
||||
Dioxus is a portable, performant, and ergonomic framework for building cross-platform user interfaces in Rust. This guide will help you get started with writing Dioxus apps for the Web, Desktop, Mobile, and more.
|
||||
|
||||
```rust
|
||||
fn app(cx: Scope) -> Element {
|
||||
let mut count = use_state(&cx, || 0);
|
||||
|
||||
cx.render(rsx!(
|
||||
h1 { "High-Five counter: {count}" }
|
||||
button { onclick: move |_| count += 1, "Up high!" }
|
||||
button { onclick: move |_| count -= 1, "Down low!" }
|
||||
))
|
||||
}
|
||||
```
|
||||
|
||||
Dioxus is heavily inspired by React. If you know React, getting started with Dioxus will be a breeze.
|
||||
|
||||
> This guide assumes you already know some [Rust](https://www.rust-lang.org/)! If not, we recommend reading [*the book*](https://doc.rust-lang.org/book/ch01-00-getting-started.html) to learn Rust first.
|
||||
|
||||
## Features
|
||||
|
||||
- Desktop apps running natively (no Electron!) in less than 10 lines of code.
|
||||
- Incredibly ergonomic and powerful state management.
|
||||
- Comprehensive inline documentation – hover and guides for all HTML elements, listeners, and events.
|
||||
- Extremely memory efficient – 0 global allocations for steady-state components.
|
||||
- Multi-channel asynchronous scheduler for first-class async support.
|
||||
- And more! Read the [full release post](https://dioxuslabs.com/blog/introducing-dioxus/.
|
||||
|
||||
### Multiplatform
|
||||
|
||||
Dioxus is a *portable* toolkit, meaning the Core implementation can run anywhere with no platform-dependent linking. Unlike many other Rust frontend toolkits, Dioxus is not intrinsically linked to WebSys. In fact, every element and event listener can be swapped out at compile time. By default, Dioxus ships with the `html` feature enabled, but this can be disabled depending on your target renderer.
|
||||
|
||||
Right now, we have several 1st-party renderers:
|
||||
- WebSys (for WASM): Great support
|
||||
- Tao/Tokio (for Desktop apps): Good support
|
||||
- Tao/Tokio (for Mobile apps): Poor support
|
||||
- SSR (for generating static markup)
|
||||
- TUI/Rink (for terminal-based apps): Experimental
|
||||
|
||||
## Stability
|
||||
|
||||
Dioxus has not reached a stable release yet.
|
||||
|
||||
Web: Since the web is a fairly mature platform, we expect there to be very little API churn for web-based features.
|
||||
|
||||
Desktop: APIs will likely be in flux as we figure out better patterns than our ElectronJS counterpart.
|
||||
|
||||
SSR: We don't expect the SSR API to change drastically in the future.
|
||||
@@ -0,0 +1,26 @@
|
||||
# Custom Hooks
|
||||
|
||||
Hooks are a great way to encapsulate business logic. If none of the existing hooks work for your problem, you can write your own.
|
||||
|
||||
## Composing Hooks
|
||||
|
||||
To avoid repetition, you can encapsulate business logic based on existing hooks to create a new hook.
|
||||
|
||||
For example, if many components need to access an `AppSettings` struct, you can create a "shortcut" hook:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/hooks_composed.rs:wrap_context}}
|
||||
```
|
||||
|
||||
## Custom Hook Logic
|
||||
|
||||
You can use [`cx.use_hook`](https://docs.rs/dioxus/latest/dioxus/prelude/struct.Scope.html#method.use_hook) to build your own hooks. In fact, this is what all the standard hooks are built on!
|
||||
|
||||
`use_hook` accepts a single closure for initializing the hook. It will be only run the first time the component is rendered. The return value of that closure will be used as the value of the hook – Dioxus will take it, and store it for as long as the component is alive. On every render (not just the first one!), you will get a reference to this value.
|
||||
|
||||
> Note: You can implement [`Drop`](https://doc.rust-lang.org/std/ops/trait.Drop.html) for your hook value – it will be dropped then the component is unmounted (no longer in the UI)
|
||||
|
||||
Inside the initialization closure, you will typically make calls to other `cx` methods. For example:
|
||||
|
||||
- The `use_state` hook tracks state in the hook value, and uses [`cx.schedule_update`](https://docs.rs/dioxus/latest/dioxus/prelude/struct.Scope.html#method.schedule_update) to make Dioxus re-render the component whenever it changes.
|
||||
- The `use_context` hook calls [`cx.consume_context`](https://docs.rs/dioxus/latest/dioxus/prelude/struct.Scope.html#method.consume_context) (which would be expensive to call on every render) to get some context from the scope
|
||||
@@ -0,0 +1,73 @@
|
||||
# Dynamic Rendering
|
||||
|
||||
Sometimes you want to render different things depending on the state/props. With Dioxus, just describe what you want to see using Rust control flow – the framework will take care of making the necessary changes on the fly if the state or props change!
|
||||
|
||||
## Conditional Rendering
|
||||
|
||||
To render different elements based on a condition, you could use an `if-else` statement:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/conditional_rendering.rs:if_else}}
|
||||
```
|
||||
|
||||
> You could also use `match` statements, or any Rust function to conditionally render different things.
|
||||
|
||||
|
||||
### Inspecting `Element` props
|
||||
|
||||
Since `Element` is a `Option<VNode>`, components accepting `Element` as a prop can actually inspect its contents, and render different things based on that. Example:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/component_children_inspect.rs:Clickable}}
|
||||
```
|
||||
|
||||
You can't mutate the `Element`, but if you need a modified version of it, you can construct a new one based on its attributes/children/etc.
|
||||
|
||||
|
||||
## Rendering Nothing
|
||||
|
||||
To render nothing, you can return `None` from a component. This is useful if you want to conditionally hide something:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/conditional_rendering.rs:conditional_none}}
|
||||
```
|
||||
|
||||
This works because the `Element` type is just an alias for `Option<VNode>`
|
||||
|
||||
> Again, you may use a different method to conditionally return `None`. For example the boolean's [`then()`](https://doc.rust-lang.org/std/primitive.bool.html#method.then) function could be used.
|
||||
|
||||
## Rendering Lists
|
||||
|
||||
Often, you'll want to render a collection of components. For example, you might want to render a list of all comments on a post.
|
||||
|
||||
For this, Dioxus accepts iterators that produce `Element`s. So we need to:
|
||||
|
||||
- Get an iterator over all of our items (e.g., if you have a `Vec` of comments, iterate over it with `iter()`)
|
||||
- `.map` the iterator to convert each item into a rendered `Element` using `cx.render(rsx!(...))`
|
||||
- Add a unique `key` attribute to each iterator item
|
||||
- Include this iterator in the final RSX
|
||||
|
||||
Example: suppose you have a list of comments you want to render. Then, you can render them like this:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/rendering_lists.rs:render_list}}
|
||||
```
|
||||
|
||||
### The `key` Attribute
|
||||
|
||||
Every time you re-render your list, Dioxus needs to keep track of which item went where, because the order of items in a list might change – items might be added, removed or swapped. Despite that, Dioxus needs to:
|
||||
|
||||
- Keep track of component state
|
||||
- Efficiently figure out what updates need to be made to the UI
|
||||
|
||||
For example, suppose the `CommentComponent` had some state – e.g. a field where the user typed in a reply. If the order of comments suddenly changes, Dioxus needs to correctly associate that state with the same comment – otherwise, the user will end up replying to a different comment!
|
||||
|
||||
To help Dioxus keep track of list items, we need to associate each item with a unique key. In the example above, we dynamically generated the unique key. In real applications, it's more likely that the key will come from e.g. a database ID. It doesn't really matter where you get the key from, as long as it meets the requirements
|
||||
|
||||
- Keys must be unique in a list
|
||||
- The same item should always get associated with the same key
|
||||
- Keys should be relatively small (i.e. converting the entire Comment structure to a String would be a pretty bad key) so they can be compared efficiently
|
||||
|
||||
You might be tempted to use an item's index in the list as its key. In fact, that’s what Dioxus will use if you don’t specify a key at all. This is only acceptable if you can guarantee that the list is constant – i.e., no re-ordering, additions or deletions.
|
||||
|
||||
> Note that if you pass the key to a component you've made, it won't receive the key as a prop. It’s only used as a hint by Dioxus itself. If your component needs an ID, you have to pass it as a separate prop.
|
||||
@@ -0,0 +1,66 @@
|
||||
# Event Handlers
|
||||
|
||||
Events are interesting things that happen, usually related to something the user has done. For example, some events happen when the user clicks, scrolls, moves the mouse, or types a character. To respond to these actions and make the UI interactive, we need to handle those events.
|
||||
|
||||
Events are associated with elements. For example, we usually don't care about all the clicks that happen within an app, only those on a particular button. To handle events that happen on an element, we must attach the desired event handler to it.
|
||||
|
||||
Event handlers are similar to regular attributes, but their name usually starts with `on`- and they accept closures as values. The closure will be called whenever the event is triggered, and will be passed that event.
|
||||
|
||||
For example, to handle clicks on an element, we can specify an `onclick` handler:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/event_click.rs:rsx}}
|
||||
```
|
||||
|
||||
## The `Event` object
|
||||
|
||||
Event handlers receive an [`UiEvent`](https://docs.rs/dioxus-core/latest/dioxus_core/struct.UiEvent.html) object containing information about the event. Different types of events contain different types of data. For example, mouse-related events contain [`MouseData`](https://docs.rs/dioxus/latest/dioxus/events/struct.MouseData.html), which tells you things like where the mouse was clicked and what mouse buttons were used.
|
||||
|
||||
In the example above, this event data was logged to the terminal:
|
||||
|
||||
```
|
||||
Clicked! Event: UiEvent { data: MouseData { coordinates: Coordinates { screen: (468.0, 109.0), client: (73.0, 25.0), element: (63.0, 15.0), page: (73.0, 25.0) }, modifiers: (empty), held_buttons: EnumSet(), trigger_button: Some(Primary) } }
|
||||
Clicked! Event: UiEvent { data: MouseData { coordinates: Coordinates { screen: (468.0, 109.0), client: (73.0, 25.0), element: (63.0, 15.0), page: (73.0, 25.0) }, modifiers: (empty), held_buttons: EnumSet(), trigger_button: Some(Primary) } }
|
||||
```
|
||||
|
||||
To learn what the different event types provide, read the [events module docs](https://docs.rs/dioxus/latest/dioxus/events/index.html).
|
||||
|
||||
### Stopping propagation
|
||||
|
||||
When you have e.g. a `button` inside a `div`, any click on the `button` is also a click on the `div`. For this reason, Dioxus propagates the click event: first, it is triggered on the target element, then on parent elements. If you want to prevent this behavior, you can call `cancel_bubble()` on the event:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/event_click.rs:rsx}}
|
||||
```
|
||||
|
||||
## Prevent Default
|
||||
|
||||
Some events have a default behavior. For keyboard events, this might be entering the typed character. For mouse events, this might be selecting some text.
|
||||
|
||||
In some instances, might want to avoid this default behavior. For this, you can add the `prevent_default` attribute with the name of the handler whose default behavior you want to stop. This attribute is special: you can attach it multiple times for multiple attributes:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/event_prevent_default.rs:prevent_default}}
|
||||
```
|
||||
|
||||
Any event handlers will still be called.
|
||||
|
||||
> Normally, in React or JavaScript, you'd call "preventDefault" on the event in the callback. Dioxus does *not* currently support this behavior. Note: this means you cannot conditionally prevent default behavior.
|
||||
|
||||
## Handler Props
|
||||
|
||||
Sometimes, you might want to make a component that accepts an event handler. A simple example would be a `FancyButton` component, which accepts an `on_click` handler:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/event_handler_prop.rs:component_with_handler}}
|
||||
```
|
||||
|
||||
Then, you can use it like any other handler:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/event_handler_prop.rs:usage}}
|
||||
```
|
||||
|
||||
> Note: just like any other attribute, you can name the handlers anything you want! Though they must start with `on`, for the prop to be automatically turned into an `EventHandler` at the call site.
|
||||
>
|
||||
> You can also put custom data in the event, rather than e.g. `MouseData`
|
||||
@@ -0,0 +1,83 @@
|
||||
# Hooks and Component State
|
||||
|
||||
So far our components, being Rust functions, had no state – they were always rendering the same thing. However, in a UI component, it is often useful to have stateful functionality to build user interactions. For example, you might want to track whether the user has openend a drop-down, and render different things accordingly.
|
||||
|
||||
For stateful logic, you can use hooks. Hooks are Rust functions that take a reference to `ScopeState` (in a component, you can pass `&cx`), and provide you with functionality and state.
|
||||
|
||||
## `use_state` Hook
|
||||
|
||||
[`use_state`](https://docs.rs/dioxus/latest/dioxus/hooks/fn.use_state.html) is one of the simplest hooks.
|
||||
|
||||
- You provide a closure that determines the initial value
|
||||
- `use_state` gives you the current value, and a way to update it by setting it to something else
|
||||
- When the value updates, `use_state` makes the component re-render, and provides you with the new value
|
||||
|
||||
For example, you might have seen the counter example, in which state (a number) is tracked using the `use_state` hook:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/hooks_counter.rs:component}}
|
||||
```
|
||||

|
||||
|
||||
Every time the component's state changes, it re-renders, and the component function is called, so you can describe what you want the new UI to look like. You don't have to worry about "changing" anything – just describe what you want in terms of the state, and Dioxus will take care of the rest!
|
||||
|
||||
> `use_state` returns your value wrapped in a smart pointer of type [`UseState`](https://docs.rs/dioxus/latest/dioxus/hooks/struct.UseState.html). This is why you can both read the value and update it, even within a handler.
|
||||
|
||||
You can use multiple hooks in the same component if you want:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/hooks_counter_two_state.rs:component}}
|
||||
```
|
||||

|
||||
|
||||
## Rules of Hooks
|
||||
|
||||
The above example might seem a bit magic, since Rust functions are typically not associated with state. Dioxus allows hooks to maintain state across renders through a reference to `ScopeState`, which is why you must pass `&cx` to them.
|
||||
|
||||
But how can Dioxus differentiate between multiple hooks in the same component? As you saw in the second example, both `use_state` functions were called with the same parameters, so how come they can return different things when the counters are different?
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/hooks_counter_two_state.rs:use_state_calls}}
|
||||
```
|
||||
|
||||
This is only possible because the two hooks are always called in the same order, so Dioxus knows which is which. So the order you call hooks matters, which is why you must follow certain rules when using hooks:
|
||||
|
||||
1. Hooks may be only used in components or other hooks (we'll get to that later)
|
||||
2. On every call to the component function
|
||||
1. The same hooks must be called
|
||||
2. In the same order
|
||||
3. Hooks name's must start with `use_` so you don't accidentally confuse them with regular functions
|
||||
|
||||
These rules mean that there are certain things you can't do with hooks:
|
||||
|
||||
### No Hooks in Conditionals
|
||||
```rust
|
||||
{{#include ../../examples/hooks_bad.rs:conditional}}
|
||||
```
|
||||
|
||||
### No Hooks in Closures
|
||||
```rust
|
||||
{{#include ../../examples/hooks_bad.rs:closure}}
|
||||
```
|
||||
|
||||
### No Hooks in Loops
|
||||
```rust
|
||||
{{#include ../../examples/hooks_bad.rs:loop}}
|
||||
```
|
||||
|
||||
## `use_ref` Hook
|
||||
|
||||
`use_state` is great for tracking simple values. However, you may notice in the [`UseState` API](https://docs.rs/dioxus/latest/dioxus/hooks/struct.UseState.html) that the only way to modify its value is to replace it with something else (e.g., by calling `set`, or through one of the `+=`, `-=` operators). This works well when it is cheap to construct a value (such as any primitive). But what if you want to maintain more complex data in the components state?
|
||||
|
||||
For example, suppose we want to maintain a `Vec` of values. If we stored it with `use_state`, the only way to add a new value to the list would be to create a new `Vec` with the additional value, and put it in the state. This is expensive! We want to modify the existing `Vec` instead.
|
||||
|
||||
Thankfully, there is another hook for that, `use_ref`! It is similar to `use_state`, but it lets you get a mutable reference to the contained data.
|
||||
|
||||
Here's a simple example that keeps a list of events in a `use_ref`. We can acquire write access to the state with `.write()`, and then just `.push` a new value to the state:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/hooks_use_ref.rs:component}}
|
||||
```
|
||||
|
||||
> The return values of `use_state` and `use_ref`, (`UseState` and `UseRef`, respectively) are in some ways similar to [`Cell`](https://doc.rust-lang.org/std/cell/) and [`RefCell`](https://doc.rust-lang.org/std/cell/struct.RefCell.html) – they provide interior mutability. However, these Dioxus wrappers also ensure that the component gets re-rendered whenever you change the state.
|
||||
|
||||
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 362 KiB |
@@ -0,0 +1,3 @@
|
||||
# Interactivity
|
||||
|
||||
So far, we've learned how to describe the structure and properties of our user interfaces. However, most interfaces need to be interactive in order to be useful. In this chapter, we describe how to make a Dioxus app that responds to the user.
|
||||
@@ -0,0 +1,86 @@
|
||||
# Router
|
||||
|
||||
In many of your apps, you'll want to have different "scenes". For a webpage, these scenes might be the different webpages with their own content.
|
||||
|
||||
You could write your own scene management solution – quite simply too. However, to save you the effort, Dioxus supports a first-party solution for scene management called Dioxus Router.
|
||||
|
||||
|
||||
## What is it?
|
||||
|
||||
For an app like the Dioxus landing page (https://dioxuslabs.com), we want to have different pages. A quick sketch of an app would be something like:
|
||||
|
||||
- Homepage
|
||||
- Blog
|
||||
- Example showcase
|
||||
|
||||
Each of these scenes is independent – we don't want to render both the homepage and blog at the same time.
|
||||
|
||||
This is where the router crates come in handy. To make sure we're using the router, simply add the `"router"` feature to your dioxus dependency.
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
dioxus = { version = "0.2", features = ["desktop", "router"] }
|
||||
```
|
||||
|
||||
|
||||
## Using the router
|
||||
|
||||
Unlike other routers in the Rust ecosystem, our router is built declaratively. This makes it possible to compose our app layout simply by arranging components.
|
||||
|
||||
```rust
|
||||
rsx!{
|
||||
Router {
|
||||
Route { to: "/home", Home {} }
|
||||
Route { to: "/blog", Blog {} }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Whenever we visit this app, we will get either the Home component or the Blog component rendered depending on which route we enter at. If neither of these routes match the current location, then nothing will render.
|
||||
|
||||
We can fix this one of two ways:
|
||||
|
||||
- A fallback 404 page
|
||||
|
||||
```rust
|
||||
rsx!{
|
||||
Router {
|
||||
Route { to: "/home", Home {} }
|
||||
Route { to: "/blog", Blog {} }
|
||||
Route { to: "", NotFound {} }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
- Redirect 404 to home
|
||||
|
||||
```rust
|
||||
rsx!{
|
||||
Router {
|
||||
Route { to: "/home", Home {} }
|
||||
Route { to: "/blog", Blog {} }
|
||||
Redirect { from: "", to: "/home" }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Links
|
||||
|
||||
For our app to navigate these routes, we can provide clickable elements called Links. These simply wrap `<a>` elements that, when clicked, navigate the app to the given location.
|
||||
|
||||
|
||||
```rust
|
||||
rsx!{
|
||||
Link {
|
||||
to: "/home",
|
||||
"Go home!"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## More reading
|
||||
|
||||
This page is just meant to be a very brief overview of the router to show you that there's a powerful solution already built for a very common problem. For more information about the router, definitely check out its book or check out some of the examples.
|
||||
|
||||
The router has its own documentation! [Available here](https://dioxuslabs.com/router/guide/).
|
||||
@@ -0,0 +1,66 @@
|
||||
# Sharing State
|
||||
|
||||
Often, multiple components need to access the same state. Depending on your needs, there are several ways to implement this.
|
||||
|
||||
## Lifting State
|
||||
|
||||
One approach to share state between components is to "lift" it up to the nearest common ancestor. This means putting the `use_state` hook in a parent component, and passing the needed values down as props.
|
||||
|
||||
For example, suppose we want to build a meme editor. We want to have an input to edit the meme caption, but also a preview of the meme with the caption. Logically, the meme and the input are 2 separate components, but they need access to the same state (the current caption).
|
||||
|
||||
> Of course, in this simple example, we could write everything in one component – but it is better to split everything out in smaller components to make the code more reusable and easier to maintain (this is even more important for larger, complex apps).
|
||||
|
||||
We start with a `Meme` component, responsible for rendering a meme with a given caption:
|
||||
```rust
|
||||
{{#include ../../examples/meme_editor.rs:meme_component}}
|
||||
```
|
||||
|
||||
> Note that the `Meme` component is unaware where the caption is coming from – it could be stored in `use_state`, `use_ref`, or a constant. This ensures that it is very reusable – the same component can be used for a meme gallery without any changes!
|
||||
|
||||
We also create a caption editor, completely decoupled from the meme. The caption editor must not store the caption itself – otherwise, how will we provide it to the `Meme` component? Instead, it should accept the current caption as a prop, as well as an event handler to delegate input events to:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/meme_editor.rs:caption_editor}}
|
||||
```
|
||||
|
||||
Finally, a third component will render the other two as children. It will be responsible for keeping the state and passing down the relevant props.
|
||||
```rust
|
||||
{{#include ../../examples/meme_editor.rs:meme_editor}}
|
||||
```
|
||||

|
||||
|
||||
## Using Context
|
||||
|
||||
Sometimes, some state needs to be shared between multiple components far down the tree, and passing it down through props is very inconvenient.
|
||||
|
||||
Suppose now that we want to implement a dark mode toggle for our app. To achieve this, we will make every component select styling depending on whether dark mode is enabled or not.
|
||||
|
||||
> Note: we're choosing this approach for the sake of an example. There are better ways to implement dark mode (e.g. using CSS variables). Let's pretend CSS variables don't exist – welcome to 2013!
|
||||
|
||||
Now, we could write another `use_state` in the top component, and pass `is_dark_mode` down to every component through props. But think about what will happen as the app grows in complexity – almost every component that renders any CSS is going to need to know if dark mode is enabled or not – so they'll all need the same dark mode prop. And every parent component will need to pass it down to them. Imagine how messy and verbose that would get, especially if we had components several levels deep!
|
||||
|
||||
Dioxus offers a better solution than this "prop drilling" – providing context. The [`use_context_provider`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_context_provider.html) hook is similar to `use_ref`, but it makes it available through [`use_context`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_context.html) for all children components.
|
||||
|
||||
First, we have to create a struct for our dark mode configuration:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/meme_editor_dark_mode.rs:DarkMode_struct}}
|
||||
```
|
||||
|
||||
Now, in a top-level component (like `App`), we can provide the `DarkMode` context to all children components:
|
||||
```rust
|
||||
{{#include ../../examples/meme_editor_dark_mode.rs:context_provider}}
|
||||
```
|
||||
|
||||
As a result, any child component of `App` (direct or not), can access the `DarkMode` context.
|
||||
```rust
|
||||
{{#include ../../examples/meme_editor_dark_mode.rs:use_context}}
|
||||
```
|
||||
|
||||
> `use_context` returns `Option<UseSharedState<DarkMode>>` here. If the context has been provided, the value is `Some(UseSharedState)`, which you can call `.read` or `.write` on, similarly to `UseRef`. Otherwise, the value is `None`.
|
||||
|
||||
For example, here's how we would implement the dark mode toggle, which both reads the context (to determine what color it should render) and writes to it (to toggle dark mode):
|
||||
```rust
|
||||
{{#include ../../examples/meme_editor_dark_mode.rs:toggle}}
|
||||
```
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
# User Input
|
||||
|
||||
Interfaces often need to provide a way to input data: e.g. text, numbers, checkboxes, etc. In Dioxus, there are two ways you can work with user input.
|
||||
|
||||
## Controlled Inputs
|
||||
|
||||
With controlled inputs, you are directly in charge of the state of the input. This gives you a lot of flexibility, and makes it easy to keep things in sync. For example, this is how you would create a controlled text input:
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/input_controlled.rs:component}}
|
||||
```
|
||||
|
||||
Notice the flexibility – you can:
|
||||
- Also display the same contents in another element, and they will be in sync
|
||||
- Transform the input every time it is modified (e.g. to make sure it is upper case)
|
||||
- Validate the input every time it changes
|
||||
- Have custom logic happening when the input changes (e.g. network request for autocompletion)
|
||||
- Programmatically change the value (e.g. a "randomize" button that fills the input with nonsense)
|
||||
|
||||
## Uncontrolled Inputs
|
||||
|
||||
As an alternative to controlled inputs, you can simply let the platform keep track of the input values. If we don't tell a HTML input what content it should have, it be editable anyway (this is built into the webview). This approach can be more performant, but less flexible. For example, it's harder to keep the input in sync with another element.
|
||||
|
||||
Since you don't necessarily have the current value of the uncontrolled input in state, you can access it either by listening to `oninput` events (similarly to controlled components), or, if the input is part of a form, you can access the form data in the form events (e.g. `oninput` or `onsubmit`):
|
||||
|
||||
```rust
|
||||
{{#include ../../examples/input_uncontrolled.rs:component}}
|
||||
```
|
||||
```
|
||||
Submitted! UiEvent { data: FormData { value: "", values: {"age": "very old", "date": "1966", "name": "Fred"} } }
|
||||
```
|
||||
@@ -0,0 +1 @@
|
||||
// empty (we only need this crate for the examples)
|
||||
@@ -0,0 +1,65 @@
|
||||
# Publishing
|
||||
|
||||
Congrats! You've made your first Dioxus app that actually does some pretty cool stuff. This app uses your operating system's WebView library, so it's portable to be distributed for other platforms.
|
||||
|
||||
In this section, we'll cover how to bundle your app for macOS, Windows, and Linux.
|
||||
|
||||
|
||||
|
||||
## Install `cargo-bundle`
|
||||
|
||||
|
||||
The first thing we'll do is install [`cargo-bundle`](https://github.com/burtonageo/cargo-bundle). This extension to cargo will make it very easy to package our app for the various platforms.
|
||||
|
||||
According to the `cargo-bundle` github page,
|
||||
|
||||
|
||||
|
||||
*"cargo-bundle is a tool used to generate installers or app bundles for GUI executables built with cargo. It can create .app bundles for Mac OS X and iOS, .deb packages for Linux, and .msi installers for Windows (note however that iOS and Windows support is still experimental). Support for creating .rpm packages (for Linux) and .apk packages (for Android) is still pending."*
|
||||
|
||||
|
||||
To install, simply run
|
||||
|
||||
|
||||
`cargo install cargo-bundle`
|
||||
|
||||
## Setting up your project
|
||||
|
||||
|
||||
To get a project setup for bundling, we need to add some flags to our `Cargo.toml` file.
|
||||
|
||||
|
||||
```toml
|
||||
[package]
|
||||
name = "example"
|
||||
# ...other fields...
|
||||
|
||||
[package.metadata.bundle]
|
||||
name = "DogSearch"
|
||||
identifier = "com.dogs.dogsearch"
|
||||
version = "1.0.0"
|
||||
copyright = "Copyright (c) Jane Doe 2016. All rights reserved."
|
||||
category = "Developer Tool"
|
||||
short_description = "Easily search for Dog photos"
|
||||
long_description = """
|
||||
This app makes it quick and easy to browse photos of dogs from over 200 bree
|
||||
"""
|
||||
```
|
||||
|
||||
|
||||
## Building
|
||||
|
||||
Following cargo-bundle's instructions, we simply `cargo-bundle --release` to produce a final app with all the optimizations and assets builtin.
|
||||
|
||||
Once you've ran `cargo-bundle --release`, your app should be accessible in
|
||||
|
||||
`target/release/bundle/<platform>/`.
|
||||
|
||||
For example, a macOS app would look like this:
|
||||
|
||||

|
||||
|
||||
Nice! And it's only 4.8 Mb – extremely lean!! Because Dioxus leverages your platform's native WebView, Dioxus apps are extremely memory efficient and won't waste your battery.
|
||||
|
||||
> Note: not all CSS works the same on all platforms. Make sure to view your app's CSS on each platform – or web browser (Firefox, Chrome, Safari) before publishing.
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
# Publishing
|
||||
@@ -0,0 +1,8 @@
|
||||
## Publishing with Github Pages
|
||||
To build our app and publish it to Github:
|
||||
|
||||
- Make sure GitHub Pages is set up for your repo
|
||||
- Build your app with `trunk build --release` (include `--public-url <repo-name>` to update asset prefixes if using a project site)
|
||||
- Move your generated HTML/CSS/JS/Wasm from `dist` into the folder configured for Github Pages
|
||||
- Add and commit with git
|
||||
- Push to GitHub
|
||||
@@ -0,0 +1,132 @@
|
||||
# Roadmap & Feature-set
|
||||
|
||||
This feature set and roadmap can help you decide if what Dioxus can do today works for you.
|
||||
|
||||
If a feature that you need doesn't exist or you want to contribute to projects on the roadmap, feel free to get involved by [joining the discord](https://discord.gg/XgGxMSkvUM).
|
||||
|
||||
Generally, here's the status of each platform:
|
||||
|
||||
- **Web**: Dioxus is a great choice for pure web-apps – especially for CRUD/complex apps. However, it does lack the ecosystem of React, so you might be missing a component library or some useful hook.
|
||||
|
||||
- **SSR**: Dioxus is a great choice for pre-rendering, hydration, and rendering HTML on a web endpoint. Be warned – the VirtualDom is not (currently) `Send + Sync`.
|
||||
|
||||
- **Desktop**: You can build very competent single-window desktop apps right now. However, multi-window apps require support from Dioxus core and are not ready.
|
||||
|
||||
- **Mobile**: Mobile support is very young. You'll be figuring things out as you go and there are not many support crates for peripherals.
|
||||
|
||||
- **LiveView**: LiveView support is very young. You'll be figuring things out as you go. Thankfully, none of it is too hard and any work can be upstreamed into Dioxus.
|
||||
|
||||
## Features
|
||||
---
|
||||
|
||||
| Feature | Status | Description |
|
||||
| ------------------------- | ------ | -------------------------------------------------------------------- |
|
||||
| Conditional Rendering | ✅ | if/then to hide/show component |
|
||||
| Map, Iterator | ✅ | map/filter/reduce to produce rsx! |
|
||||
| Keyed Components | ✅ | advanced diffing with keys |
|
||||
| Web | ✅ | renderer for web browser |
|
||||
| Desktop (webview) | ✅ | renderer for desktop |
|
||||
| Shared State (Context) | ✅ | share state through the tree |
|
||||
| Hooks | ✅ | memory cells in components |
|
||||
| SSR | ✅ | render directly to string |
|
||||
| Component Children | ✅ | cx.children() as a list of nodes |
|
||||
| Headless components | ✅ | components that don't return real elements |
|
||||
| Fragments | ✅ | multiple elements without a real root |
|
||||
| Manual Props | ✅ | Manually pass in props with spread syntax |
|
||||
| Controlled Inputs | ✅ | stateful wrappers around inputs |
|
||||
| CSS/Inline Styles | ✅ | syntax for inline styles/attribute groups |
|
||||
| Custom elements | ✅ | Define new element primitives |
|
||||
| Suspense | ✅ | schedule future render from future/promise |
|
||||
| Integrated error handling | ✅ | Gracefully handle errors with ? syntax |
|
||||
| NodeRef | ✅ | gain direct access to nodes |
|
||||
| Re-hydration | ✅ | Pre-render to HTML to speed up first contentful paint |
|
||||
| Jank-Free Rendering | ✅ | Large diffs are segmented across frames for silky-smooth transitions |
|
||||
| Effects | ✅ | Run effects after a component has been committed to render |
|
||||
| Portals | 🛠 | Render nodes outside of the traditional tree structure |
|
||||
| Cooperative Scheduling | 🛠 | Prioritize important events over non-important events |
|
||||
| Server Components | 🛠 | Hybrid components for SPA and Server |
|
||||
| Bundle Splitting | 👀 | Efficiently and asynchronously load the app |
|
||||
| Lazy Components | 👀 | Dynamically load the new components as the page is loaded |
|
||||
| 1st class global state | ✅ | redux/recoil/mobx on top of context |
|
||||
| Runs natively | ✅ | runs as a portable binary w/o a runtime (Node) |
|
||||
| Subtree Memoization | ✅ | skip diffing static element subtrees |
|
||||
| High-efficiency templates | 🛠 | rsx! calls are translated to templates on the DOM's side |
|
||||
| Compile-time correct | ✅ | Throw errors on invalid template layouts |
|
||||
| Heuristic Engine | ✅ | track component memory usage to minimize future allocations |
|
||||
| Fine-grained reactivity | 👀 | Skip diffing for fine-grain updates |
|
||||
|
||||
- ✅ = implemented and working
|
||||
- 🛠 = actively being worked on
|
||||
- 👀 = not yet implemented or being worked on
|
||||
|
||||
|
||||
## Roadmap
|
||||
These Features are planned for the future of Dioxus:
|
||||
|
||||
### Core
|
||||
- [x] Release of Dioxus Core
|
||||
- [x] Upgrade documentation to include more theory and be more comprehensive
|
||||
- [ ] Support for HTML-side templates for lightning-fast dom manipulation
|
||||
- [ ] Support for multiple renderers for same virtualdom (subtrees)
|
||||
- [ ] Support for ThreadSafe (Send + Sync)
|
||||
- [ ] Support for Portals
|
||||
|
||||
### SSR
|
||||
- [x] SSR Support + Hydration
|
||||
- [ ] Integrated suspense support for SSR
|
||||
|
||||
### Desktop
|
||||
- [ ] Declarative window management
|
||||
- [ ] Templates for building/bundling
|
||||
- [ ] Fully native renderer
|
||||
- [ ] Access to Canvas/WebGL context natively
|
||||
|
||||
### Mobile
|
||||
- [ ] Mobile standard library
|
||||
- [ ] GPS
|
||||
- [ ] Camera
|
||||
- [ ] filesystem
|
||||
- [ ] Biometrics
|
||||
- [ ] WiFi
|
||||
- [ ] Bluetooth
|
||||
- [ ] Notifications
|
||||
- [ ] Clipboard
|
||||
- [ ] Animations
|
||||
- [ ] Native Renderer
|
||||
|
||||
### Bundling (CLI)
|
||||
- [x] Translation from HTML into RSX
|
||||
- [x] Dev server
|
||||
- [x] Live reload
|
||||
- [x] Translation from JSX into RSX
|
||||
- [ ] Hot module replacement
|
||||
- [ ] Code splitting
|
||||
- [ ] Asset macros
|
||||
- [ ] Css pipeline
|
||||
- [ ] Image pipeline
|
||||
|
||||
### Essential hooks
|
||||
- [x] Router
|
||||
- [x] Global state management
|
||||
- [ ] Resize observer
|
||||
|
||||
|
||||
## Work in Progress
|
||||
|
||||
### Build Tool
|
||||
|
||||
We are currently working on our own build tool called [Dioxus CLI](https://github.com/DioxusLabs/cli) which will support:
|
||||
|
||||
- an interactive TUI
|
||||
- on-the-fly reconfiguration
|
||||
- hot CSS reloading
|
||||
- two-way data binding between browser and source code
|
||||
- an interpreter for `rsx!`
|
||||
- ability to publish to github/netlify/vercel
|
||||
- bundling for iOS/Desktop/etc
|
||||
|
||||
### LiveView / Server Component Support
|
||||
|
||||
The internal architecture of Dioxus was designed from day one to support the `LiveView` use-case, where a web server hosts a running app for each connected user. As of today, there is no first-class LiveView support – you'll need to wire this up yourself.
|
||||
|
||||
While not currently fully implemented, the expectation is that LiveView apps can be a hybrid between Wasm and server-rendered where only portions of a page are "live" and the rest of the page is either server-rendered, statically generated, or handled by the host SPA.
|
||||