Rework Guide (#486)

* Move getting started to Guide

* Clean up summary and getting started

* Shorten intro by moving stuff to individual platform docs

* Make intro even shorter, summarize features

* Further cleanup; move development-related docs to separate section

* Make `guide` a crate. Turn code samples into examples so that we can check if they compile

* Rewrite "Describing the UI":

* Focus on RSX syntax (interactivity covered in later chapters); make sure samples are tested; concise language

* Move some "special attribute" samples to the `examples` directory

* Simplify introduction to components

* Simplify introduction to component props

* Document Prop features; add code samples

* Simplify component children docs

* Interactivity: better introduction to events

* Hooks: better introduction

* Remove outdated doc

* Introducs use_ref

* Simplify User Input chapter

* Document event handler props

* Meme editor example

* Meme editor walkthrough

* Add dark mode example

* Guide for context; dark mode example

* Guide: custom hooks

* Guide: conditional rendering

* Guide: rendering lists

* Guide: rendering lists + keys

* Move remaining infor from Reference to guide

* Delete reference book
This commit is contained in:
Reinis Mazeiks authored and GitHub committed 2022-07-07 08:50:36 +00:00
1 parent 92a8b7c75f
commit 6c323e9fc5
152 files changed
+2827 -5052

No files matched your search

-1
View File
@@ -1 +0,0 @@
reference
View File
Whitespace-only changes.
-27
View File
@@ -1,27 +0,0 @@
# Dioxus: Reference and Advanced Guides
![dioxuslogo](./images/dioxuslogo_full.png)
**Dioxus** is a framework and ecosystem for building fast, scalable, and robust user interfaces with the Rust programming language. This guide will help you get started with Dioxus running on the Web, Desktop, Mobile, and more.
> This book is the reference and Advanced Guides for the Dioxus framework. For a tutorial on how to actually *use* Dioxus, make sure to check out the [official guide](https://dioxuslabs.com/guide/).
## Reference and Guides
With the reference, we aim to maintain documentation of functionality that might not be mentioned in the official guide to keep the information load to a minimum. Some topics not included by the guide but discussed in the reference include:
- ThreadSafety of the VirtualDom
- Full usage of `rsx!` and included features
- Spread pattern for component properties
- Testing
- Memoization in Depth
- Custom Elements
- Custom Renderers
## Contributing
If this doc is lacking in any way, is confusing, has a typo, or you'd just like to help improve things, feel free to make a PR against the [Dioxus repo](https://github.com/DioxusLabs/dioxus/tree/master/docs/reference).
All contributions will be licensed under MIT/Apache2.
-15
View File
@@ -1,15 +0,0 @@
# Summary
- [Introduction](README.md)
- [Platforms](platforms/index.md)
- [Web](platforms/web.md)
- [Server Side Rendering](platforms/ssr.md)
- [Desktop](platforms/desktop.md)
- [Mobile](platforms/mobile.md)
- [TUI](platforms/tui.md)
- [Advanced Guides](guide/index.md)
- [RSX in Depth](guide/rsx_in_depth.md)
- [Custom Renderer](guide/custom_renderer.md)
- [Hot Reloading Rsx](guide/hot_reloading.md)
-493
View File
@@ -1,493 +0,0 @@
# 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.ink/img/pako:eNqdVNFqgzAU_RXJXizUUZPJmIM-jO0LukdhpCbO0JhIGteW0n9fNK1Oa0brfUnu9VxyzzkXjyCVhIIYZFzu0hwr7X2-JcIzsa3W3wqXuZdKoele22oddfa1Y0Tnfn31muvMfqeCDNq3GmvaNROmaKqZFO1DPTRhP8MOd1fTWYNDvzlmQbBMJZcq9JtjNgY1mLVUhBqQPQeojl3wGCw5PsjqnIe-zXqEL8GZ2Kz0gVMPmoeU3ND4IcuiaLGY2zRouuKncv_qGKv3VodpJe0JVU6QCQ5kgqMyWQVr8hbk4hm1PBcmsuwmnrCVH94rP7xN_ucp8sOB_EPSfz9drYVrkpc_AmH8_yTjJueUc-ntpOJkgt2os9tKjcYlt-DLUiD3UsB2KZCLcwjv3Aq33-g2v0M0xXA0MBy5DUdXi-gcJZriuLmAOSioKjAj5ld8rMsJ0DktaAJicyVYbRKQiJPBVSUx438QpqUCcYb5ls4BrrRcHUTaFizqnWGzR8W5evoFI-bJdw)](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.
-24
View File
@@ -1,24 +0,0 @@
# Hot Reloading
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.
-1
View File
@@ -1 +0,0 @@
# Advanced Guides
-231
View File
@@ -1,231 +0,0 @@
# RSX in Depth
The RSX macro makes it very easy to assemble complex UIs with a very natural Rust syntax:
```rust
rsx!(
div {
button {
onclick: move |e| todos.write().new_todo(),
"Add todo"
}
ul {
class: "todo-list",
todos.iter().map(|(key, todo)| rsx!(
li {
class: "beautiful-todo"
key: "f"
h3 { "{todo.title}" }
p { "{todo.contents}"}
}
))
}
}
)
```
In this section, we'll cover the `rsx!` macro in depth. If you prefer to learn through examples, the `code reference` guide has plenty of examples on how to use `rsx!` effectively.
### Element structure
Attributes must come before child elements
```rust
div {
hidden: "false",
"some text"
child {}
Component {} // uppercase
component() // lowercase is treated like a function call
(0..10).map(|f| rsx!{ "hi {f}" }) // arbitrary rust expressions
}
```
Each element takes a comma-separated list of expressions to build the node. Roughly, here's how they work:
- `name: value` sets a property on this element.
- `"text"` adds a new text element
- `tag {}` adds a new child element
- `CustomTag {}` adds a new child component
- `{expr}` pastes the `expr` tokens literally. They must be `IntoIterator<T> where T: IntoVnode` to work properly
Commas are entirely optional, but might be useful to delineate between elements and attributes.
The `render` function provides an **extremely efficient** allocator for VNodes and text, so try not to use the `format!` macro in your components. Rust's default `ToString` methods pass through the global allocator, but all text in components is allocated inside a manually-managed Bump arena. To push you in the right direction, all text-based attributes take `std::fmt::Arguments` directly, so you'll want to reach for `format_args!` when the built-in `f-string` interpolation just doesn't cut it.
### Ignoring `cx.render` with `rsx!(cx, ...)`
Sometimes, writing `cx.render` is a hassle. The `rsx! macro will accept any token followed by a comma as the target to call "render" on:
```rust
cx.render(rsx!( div {} ))
// becomes
rsx!(cx, div {})
```
### Conditional Rendering
Sometimes, you might not want to render an element given a condition. The rsx! macro will accept any tokens directly contained with curly braces, provided they resolve to a type that implements `IntoIterator<VNode>`. This lets us write any Rust expression that resolves to a VNode:
```rust
rsx!({
if enabled {
rsx!(cx, div {"enabled"})
} else {
rsx!(cx, li {"disabled"})
}
})
```
A convenient way of hiding/showing an element is returning an `Option<VNode>`. When combined with `and_then`, we can succinctly control the display state given some boolean:
```rust
rsx!({
a.and_then(rsx!(div {"enabled"}))
})
```
It's important to note that the expression `rsx!()` is typically lazy - this expression must be _rendered_ to produce a VNode. When using match statements, we must render every arm as to avoid the `no two closures are identical` rule that Rust imposes:
```rust
// this will not compile!
match case {
true => rsx!(div {}),
false => rsx!(div {})
}
// the nodes must be rendered first
match case {
true => rsx!(cx, div {}),
false => rsx!(cx, div {})
}
```
### Lists
Again, because anything that implements `IntoIterator<VNode>` is valid, we can use lists directly in our `rsx!`:
```rust
let items = vec!["a", "b", "c"];
cx.render(rsx!{
ul {
{items.iter().map(|f| rsx!(li { "a" }))}
}
})
```
Sometimes, it makes sense to render VNodes into a list:
```rust
let mut items = vec![];
for _ in 0..5 {
items.push(rsx!(cx, li {} ))
}
rsx!(cx, {items} )
```
#### Lists and Keys
When rendering the VirtualDom to the screen, Dioxus needs to know which elements have been added and which have been removed. These changes are determined through a process called "diffing" - an old set of elements is compared to a new set of elements. If an element is removed, then it won't show up in the new elements, and Dioxus knows to remove it.
However, with lists, Dioxus does not exactly know how to determine which elements have been added or removed if the order changes or if an element is added or removed from the middle of the list.
In these cases, it is vitally important to specify a "key" alongside the element. Keys should be persistent between renders.
```rust
fn render_list(cx: Scope, items: HashMap<String, Todo>) -> DomTree {
rsx!(cx, ul {
{items.iter().map(|key, item| {
li {
key: key,
h2 { "{todo.title}" }
p { "{todo.contents}" }
}
})}
})
}
```
There have been many guides made for keys in React, so we recommend reading up to understand their importance:
- [React guide on keys](https://reactjs.org/docs/lists-and-keys.html)
- [Importance of keys (Medium)](https://kentcdodds.com/blog/understanding-reacts-key-prop)
### Complete Reference
```rust
let text = "example";
cx.render(rsx!{
div {
h1 { "Example" },
{title}
// fstring interpolation
"{text}"
p {
// Attributes
tag: "type",
// Anything that implements display can be an attribute
abc: 123,
enabled: true,
// attributes also supports interpolation
// `class` is not a restricted keyword unlike JS and ClassName
class: "big small wide short {text}",
class: format_args!("attributes take fmt::Arguments. {}", 99),
tag: {"these tokens are placed directly"}
// Children
a { "abcder" },
// Children with attributes
h2 { "hello", class: "abc-123" },
// Child components
CustomComponent { a: 123, b: 456, key: "1" },
// Child components with paths
crate::components::CustomComponent { a: 123, b: 456, key: "1" },
// Iterators
{ (0..3).map(|i| rsx!( h1 {"{:i}"} )) },
// More rsx!, or even html!
{ rsx! { div { } } },
{ html! { <div> </div> } },
// Matching
// Requires rendering the nodes first.
// rsx! is lazy, and the underlying closures cannot have the same type
// Rendering produces the VNode type
{match rand::gen_range::<i32>(1..3) {
1 => rsx!(cx, h1 { "big" })
2 => rsx!(cx, h2 { "medium" })
_ => rsx!(cx, h3 { "small" })
}}
// Optionals
{true.and_then(|f| rsx!( h1 {"Conditional Rendering"} ))}
// Child nodes
{cx.props.children}
// Any expression that is `IntoVNode`
{expr}
}
}
})
```
Binary file not shown.

Before

Width:  |  Height:  |  Size: 58 KiB

-47
View File
@@ -1,47 +0,0 @@
# Getting Started: Desktop
One of Dioxus' killer features is the ability to quickly build a native desktop app that looks and feels the same across platforms. 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.
Dioxus Desktop is built off Tauri. 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. The next major release of Dioxus-Desktop will include components and hooks for notifications, global shortcuts, menubar, etc.
## Getting Set up
Getting Set up with Dioxus-Desktop is quite easy. Make sure you have Rust and Cargo installed, and then create a new project:
```shell
$ cargo new --bin demo
$ cd demo
```
Add Dioxus with the `desktop` feature:
```shell
$ cargo add dioxus --features desktop
```
Edit your `main.rs`:
```rust
// main.rs
use dioxus::prelude::*;
fn main() {
dioxus::desktop::launch(app);
}
fn app(cx: Scope) -> Element {
cx.render(rsx!{
div {
"hello world!"
}
})
}
```
To configure the webview, menubar, and other important desktop-specific features, checkout out some of the launch configuration in the [API reference](https://docs.rs/dioxus-desktop/).
## Future Steps
Make sure to read the [Dioxus Guide](https://dioxuslabs.com/guide) if you already haven't!
-10
View File
@@ -1,10 +0,0 @@
# Platforms
Dioxus supports many different platforms. Below are a list of guides that walk you through setting up Dioxus for a specific platform.
### Setup Guides
- [Web](web.md)
- [Server Side Rendering](ssr.md)
- [Desktop](desktop.md)
- [Mobile](mobile.md)
- [TUI](tui.md)
-78
View File
@@ -1,78 +0,0 @@
# Getting started: mobile
Dioxus is unique in that it actually supports mobile. However, support is very young and you might need to dip down into some of the primitives until better support is ready.
Currently, only iOS is supported through us, however you *can* add android support by following the same instructions below by using the `android` guide in `cargo-mobile`.
Also, Dioxus Desktop and Dioxus Mobile share the same codebase, and dioxus-mobile currently just re-exports dioxus-desktop.
## 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
// main.rs
use dioxus::prelude::*;
fn main() {
dioxus::mobile::launch(app);
}
fn app(cx: Scope) -> Element {
cx.render(rsx!{
div {
"hello world!"
}
})
}
```
To configure the webview, menubar, and other important desktop-specific features, checkout out some of the launch configuration in the [API reference](https://docs.rs/dioxus-mobile/).
## Future Steps
Make sure to read the [Dioxus Guide](https://dioxuslabs.com/guide) if you already haven't!
-102
View File
@@ -1,102 +0,0 @@
# Getting Started: Server-Side-Rendering
The Dioxus VirtualDom can be rendered to a string by traversing the Element Tree. This is implemented in the `ssr` crate where your Dioxus app can be directly rendered to HTML to be served by a web server.
## 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, setup 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.
## Future Steps
Make sure to read the [Dioxus Guide](https://dioxuslabs.com/guide) if you already haven't!
-98
View File
@@ -1,98 +0,0 @@
# Getting Started: TUI
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.
[TUI Support](https://github.com/DioxusLabs/rink/raw/master/examples/example.png)
## Getting Set up
To tinker with TUI support, 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
// main
use dioxus::prelude::*;
fn main() {
dioxus::tui::launch(app);
}
fn app(cx: Scope) -> Element {
cx.render(rsx! {
div {
width: "100%",
height: "10px",
background_color: "red",
justify_content: "center",
align_items: "center",
"Hello world!"
}
})
}
```
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
use dioxus::events::{KeyCode, KeyboardEvent};
use dioxus::prelude::*;
use dioxus::tui::TuiContext;
fn main() {
dioxus::tui::launch_cfg(
app,
dioxus::tui::Config::new()
.without_ctrl_c_quit()
// Some older terminals only support 16 colors or ANSI colors if your terminal is one of these change this to BaseColors or ANSI
.with_rendering_mode(dioxus::tui::RenderingMode::Rgb),
);
}
fn app(cx: Scope) -> Element {
let tui_ctx: TuiContext = cx.consume_context().unwrap();
cx.render(rsx! {
div {
width: "100%",
height: "10px",
background_color: "red",
justify_content: "center",
align_items: "center",
onkeydown: move |k: KeyboardEvent| if let KeyCode::Q = k.data.key_code {
tui_ctx.quit();
},
"Hello world!"
}
})
}
```
## 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.
## Future Steps
Make sure to read the [Dioxus Guide](https://dioxuslabs.com/guide) if you already haven't!
-111
View File
@@ -1,111 +0,0 @@
# Getting Started: Web
[*"Pack your things, we're going on an adventure!"*](https://trunkrs.dev)
Dioxus is well supported for the web through WebAssembly. 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.
Building Dioxus apps for the web requires much less configuration than our JavaScript counterparts.
## 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.
Currently, trunk projects can only build the root binary (ie the `main.rs`). To build a new Dioxus compatible project, this should get you up and running.
First, [install trunk](https://trunkrs.dev/#install):
```shell
$ cargo install trunk
```
Make sure the `wasm32-unknown-unknown` target is installed:
```shell
$ rustup target add wasm32-unknown-unknown
```
Create a new project:
```shell
$ cargo new --bin demo
$ cd demo
```
Add Dioxus with the `web` features:
```
$ cargo add dioxus --features web
```
Add an `index.html` for Trunk to use. Make sure your "mount point" element has an ID of "main" (this can be configured later):
```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
// main.rs
use dioxus::prelude::*;
fn main() {
dioxus::web::launch(app);
}
fn app(cx: Scope) -> Element {
cx.render(rsx!{
div { "hello, wasm!" }
})
}
```
And to serve our app:
```shell
trunk serve
```
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
That's it!
## Future Build Tool
We are currently working on our own build tool called [Dioxus Studio](http://github.com/dioxusLabs/studio) 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
## Features
Currently, the web supports:
- Pre-rendering/Hydration
## Events
The regular events in the `html` crate work just fine in the web.
## Future Steps
Make sure to read the [Dioxus Guide](https://dioxuslabs.com/guide) if you already haven't!