wip: remove runner on hook and then update docs

This commit is contained in:
Jonathan Kelley committed 2022-01-02 02:15:04 -05:00
1 parent 7d41a16208
commit d1560450ba
95 files changed
+1339 -675

No files matched your search

+9 -12
View File
@@ -18,7 +18,7 @@ fn App(cx: Scope) -> Element {
In general, Dioxus and React share many functional similarities. If this guide is lacking in any general concept or an error message is confusing, React's documentation might be more helpful. We are dedicated to providing a *familiar* toolkit for UI in Rust, so we've chosen to follow in the footsteps of popular UI frameworks (React, Redux, etc). If you know React, then you already know Dioxus. If you don't know either, this guide will still help you!
> This is introduction book! For advanced topics, check out the [Reference](https://dioxuslabs.com/reference) instead.
> This is an introduction book! For advanced topics, check out the [Reference](https://dioxuslabs.com/reference) instead.
## Multiplatform
@@ -29,6 +29,7 @@ Right now, we have several 1st-party renderers:
- Tao/Tokio (for Desktop apps)
- Tao/Tokio (for Mobile apps)
- SSR (for generating static markup)
- TUI/Rink (for terminal-based apps)
### Web Support
---
@@ -40,12 +41,10 @@ Because the web is a fairly mature platform, we expect there to be very little A
[Jump to the getting started guide for the web.]()
Examples:
- [TodoMVC](https://github.com/dioxusLabs/todomvc/)
- [ECommerce]()
- [Photo Editor]()
[![TODOMVC](https://github.com/DioxusLabs/todomvc/raw/master/example.png)](https://github.com/dioxusLabs/todomvc/)
- [TodoMVC](https://github.com/DioxusLabs/example-projects/tree/master/todomvc)
- [ECommerce](https://github.com/DioxusLabs/example-projects/tree/master/ecommerce-site)
[![TodoMVC example](https://github.com/DioxusLabs/example-projects/raw/master/todomvc/example.png)](https://github.com/DioxusLabs/example-projects/blob/master/todomvc)
### SSR Support
---
Dioxus supports server-side rendering!
@@ -59,7 +58,7 @@ let contents = dioxus::ssr::render_vdom(&dom);
[Jump to the getting started guide for SSR.]()
Examples:
- [Example DocSite]()
- [Example DocSite](https://github.com/dioxusLabs/docsite)
- [Tide WebServer]()
- [Markdown to fancy HTML generator]()
@@ -72,9 +71,8 @@ Desktop APIs will likely be in flux as we figure out better patterns than our El
[Jump to the getting started guide for Desktop.]()
Examples:
- [File explorer]()
- [Bluetooth scanner]()
- [Device Viewer]()
- [File explorer](https://github.com/dioxusLabs/file-explorer/)
- [WiFi scanner](https://github.com/DioxusLabs/example-projects/blob/master/wifi-scanner)
[![File ExplorerExample](https://github.com/DioxusLabs/file-explorer-example/raw/master/image.png)](https://github.com/dioxusLabs/file-explorer/)
@@ -87,8 +85,7 @@ Mobile support is currently best suited for CRUD-style apps, ideally for interna
[Jump to the getting started guide for Mobile.]()
Examples:
- [Todo App]()
- [Chat App]()
- [Todo App](https://github.com/DioxusLabs/example-projects/blob/master/ios_demo)
### LiveView / Server Component Support
---
+27 -84
View File
@@ -3,96 +3,39 @@
- [Introduction](README.md)
- [Getting Setup](setup.md)
- [Hello, World!](hello_world.md)
- [Describing the UI](concepts/00-index.md)
- [Intro to Elements](concepts/vnodes.md)
- [Intro to Components](concepts/components.md)
- [Reusing, Importing, and Exporting Components](concepts/exporting_components.md)
- [Passing children and attributes](concepts/component_children.md)
- [Conditional Rendering](concepts/conditional_rendering.md)
- [Lists](concepts/lists.md)
- [Adding Interactivity](concepts/interactivity.md)
- [Hooks and Internal State](concepts/hooks.md)
- [Event handlers](concepts/event_handlers.md)
- [User Input and Controlled Components](concepts/user_input.md)
- [Lifecycle, updates, and effects](concepts/lifecycles.md)
<!-- Responding to Events
State: A Component's Memory
Render and Commit
State as a Snapshot
Queueing a Series of State Updates
Updating Objects in State
Updating Arrays in State -->
<!-- Reacting to Input with State
Choosing the State Structure
Sharing State Between Components
Preserving and Resetting State
Extracting State Logic into a Reducer
Passing Data Deeply with Context
Scaling Up with Reducer and Context -->
- [Managing State](concepts/managing_state.md)
- [Global State](concepts/sharedstate.md)
- [Error handling](concepts/errorhandling.md)
- [Effects](concepts/effects.md)
- [Working with Async](concepts/async.md)
- [Tasks](concepts/asynctasks.md)
- [Suspense](concepts/suspense.md)
- [Async Callbacks](concepts/asynccallbacks.md)
- [Putting it all together](tutorial/index.md)
- [Describing the UI](elements/index.md)
- [Intro to Elements](elements/vnodes.md)
- [Intro to Components](elements/components.md)
- [Reusing, Importing, and Exporting Components](elements/exporting_components.md)
- [Passing children and attributes](elements/component_children.md)
- [Conditional Rendering](elements/conditional_rendering.md)
- [Lists](elements/lists.md)
- [Adding Interactivity](interactivity/index.md)
- [Hooks and Internal State](interactivity/hooks.md)
- [Event handlers](interactivity/event_handlers.md)
- [User Input and Controlled Components](interactivity/user_input.md)
- [Lifecycle, updates, and effects](interactivity/lifecycles.md)
- [Managing State](state/index.md)
- [Local State](state/localstate.md)
- [Lifting State](state/liftingstate.md)
- [Global State](state/sharedstate.md)
- [Error handling](state/errorhandling.md)
- [Working with Async](async/index.md)
- [Tasks](async/asynctasks.md)
- [Putting it all together: Dog Search Engine](tutorial/index.md)
- [New app](tutorial/new_app.md)
- [Structuring our app](tutorial/structure.md)
- [Defining State](tutorial/state.md)
- [Defining Components](tutorial/components.md)
- [Styling](tutorial/styling.md)
- [Publishing](tutorial/publishing.md)
- [Next Steps and Advanced Topics](final/index.md)
<!-- - [Topics in Depth](depth/topics.md)
- [RSX](depth/rsx.md)
- [Components](depth/components.md)
- [Props](depth/props.md)
- [Memoization](depth/memoization.md)
- [Performance](depth/performance.md)
- [Testing](depth/testing.md)
- [Advanced Guides](tutorial/advanced_guides.md)
- [Memoization](concepts/memoization.md)
- [RSX in Depth](concepts/rsx_in_depth.md)
- [Building Elements with NodeFactory](concepts/rsx.md)
- [Custom Elements](concepts/custom_elements.md)
- [Custom Renderer](concepts/custom_renderer.md)
- [Server-side components](concepts/server_side_components.md)
- [Bundling and Distributing](concepts/bundline.md)
- [Web]()
- [Getting Started]()
- [Down-casting Nodes]()
- [Wrapping Web APIs]()
- [SSR]()
- [Wrapping Web APIs]()
- [Desktop]()
- [Wrapping Web APIs]()
- [Mobile]()
- [Wrapping Web APIs]()
- [Reference Guide]()
- [Anti-patterns]()
- [Children]()
- [Conditional Rendering]()
- [Controlled Inputs]()
- [Custom Elements]()
- [Empty Components]()
- [Error Handling]()
- [Fragments]()
- [Global CSS]()
- [Inline Styles]()
- [Iterators]()
- [Listeners]()
- [Memoization]()
- [Node Refs]()
- [Spread Pattern]()
- [State Management]()
- [Suspense]()
- [task]()
- [Testing]() -->
- [Bundling](tutorial/publishing.md)
- [Next Steps and Advanced Topics](final.md)
-----------
[Contributors](misc/contributors.md)
<!-- - [Suspense](concepts/suspense.md) -->
<!-- - [Async Callbacks](concepts/asynccallbacks.md) -->
File renamed without changes.
@@ -20,7 +20,7 @@ fn runs_in_browser() {
Then, when you run
```
```console
$ dioxus test --chrome
```
+90
View File
@@ -0,0 +1,90 @@
# Tasks
All async code in Dioxus must be explicit and handled through Dioxus' task system.
In this chapter, we'll learn how to spawn new tasks through our `Scope`.
## Spawning a task
You can push any `'static` future into the Dioxus future queue by simply calling `cx.spawn` to spawn a task. Pushing a future returns a `TaskId` which can then be used to cancel the
```rust
fn App(cx: Scope) -> Element {
cx.spawn(async {
let mut count = 0;
loop {
tokio::time::delay(std::instant::Duration::from_millis(500)).await;
count += 1;
println!("Current count is {}", count);
}
});
None
}
```
The future must be `'static` - so any values captured by the task must not carry any references to `cx`. All the Dioxus hooks have a method called `for_async` which will create a slightly more limited handle to the hook for you to use in your async code.
```rust
fn App(cx: Scope) -> Element {
let mut count = use_state(&cx, || 0);
let taskid = cx.spawn({
let mut count = count.for_async();
async {
loop {
tokio::time::delay(std::instant::Duration::from_millis(500)).await;
count += 1;
println!("Current count is {}", count);
}
}
});
}
```
The task will run in the background until it is completed.
> Note: `spawn` will always spawn a *new* future. You probably want to call it from a hook initializer instead of the main body of your component.
When bringing lots of values into your task, we provide the `for_async!` macro which will can `for_async` on all values passed in. For types that implement `ToOwned`, `for_async!` will simply call `ToOwned` for that value.
```rust
fn App(cx: Scope) -> Element {
let mut age = use_state(&cx, || 0);
let mut name = use_state(&cx, || "Bob");
let mut description = use_state(&cx, || "asd".to_string());
let taskid = cx.spawn({
for_async![count, name, description]
async { /* code that uses count/name/description */ }
});
}
```
## Details of Tasks
Calling `spawn` is *not* a hook and will *always* generate a new task. Make sure to only spawn tasks when you want to. You should *probably* not call `spawn` in the main body of your component, since a new task will be spawned on every render.
## Spawning Tokio Tasks (for multithreaded use cases)
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 can directly spawn a `tokio task` from our future. For Dioxus-Desktop, your task will be spawned onto Tokio's Multithreaded runtime:
```rust
cx.spawn({
tokio::spawn(async {
// some multithreaded work
}).await;
tokio::spawn_blocking(|| {
// some extremely blocking work
}).await;
tokio::spawn_local(|| {
// some !Send work
}).await;
})
```
> Note: Tokio tasks must be `Send`. Most hooks are `Send` compatible, but if they aren't, then you can use `spawn_local` to spawn onto Dioxus-Desktop's `localset`.
+19
View File
@@ -0,0 +1,19 @@
# Working with Async
Not all apps you'll build can be self-contained with synchronous code. You'll often need to interact with file systems, network interfaces, hardware, or timers.
So far, we've only talked about building apps with synchronous code, so this chapter will focus integrating asynchronous code into your app.
## The Runtime
By default, Dioxus-Desktop ships with the `Tokio` runtime and automatically sets everything up for you.
## Send/Sync
Writing apps that deal with Send/Sync can be frustrating at times. Under the hood, Dioxus is not currently thread-safe, so any async code you write does *not* need to be `Send/Sync`. That means Cell/Rc/RefCell are all fair game.
All async code in your app is polled on a `LocalSet`, so any async code we w
-1
View File
@@ -1 +0,0 @@
# Working with Async
@@ -1 +0,0 @@
# Async Callbacks
-1
View File
@@ -1 +0,0 @@
# Tasks
-1
View File
@@ -1 +0,0 @@
# Bundling and Distributing
@@ -1 +0,0 @@
# Custom Elements
@@ -1 +0,0 @@
# Custom Renderer
-1
View File
@@ -1 +0,0 @@
# Effects
-11
View File
@@ -1,11 +0,0 @@
# Handling Events
In the overview for this section, we mentioned how we can modify the state of our component by responding to user-generated events inside of event listeners.
In this section, we'll talk more about event listeners:
- What events are available
- Handling event data
- Mutability in event listeners
## Event Listeners
@@ -1 +0,0 @@
# Managing State
-1
View File
@@ -1 +0,0 @@
# Memoization
@@ -1 +0,0 @@
# Server-side components
-54
View File
@@ -1,54 +0,0 @@
# Suspense
Suspense in Dioxus is enabled through placeholder nodes.
just a component that renders nodes into the placeholder after the future is finished?
in react, suspense is just completely pausing diffing while a
```rust
let n = use_suspense(cx || {
cx.render(rsx!{
Suspense {
prom: fut,
callback: || {}
}
})
})
suspense () {
let value = use_state();
if first_render {
push_task({
value.set(fut.await);
});
} else {
callback(value)
}
}
let name = fetch_name().await;
function ProfileDetails() {
// Try to read user info, although it might not have loaded yet
const user = resource.read();
return <h1>{user.name}</h1>;
}
fn ProfileDteails() {
let user = resource.suspend(cx, |l| rsx!("{l}"));
// waits for the resource to be ready and updates the placeholder with the tree
let name = resource.suspend_with(cx, |val| rsx!( div { "hello" "{user}" } ));
cx.render(rsx!(
div {
{user}
{name}
}
))
}
```
-1
View File
@@ -1 +0,0 @@
# Fundamental Hooks and use_hook
@@ -30,7 +30,7 @@ struct ClickableProps<'a> {
title: &'a str
}
fn clickable(cx: Scope<ClickableProps>) -> Element {
fn Clickable(cx: Scope<ClickableProps>) -> Element {
cx.render(rsx!(
a {
href: "{cx.props.href}"
@@ -44,10 +44,10 @@ And then use it in our code like so:
```rust
rsx!(
clickable(
Clickable {
href: "https://google.com"
title: "Link to Google"
)
}
)
```
@@ -64,11 +64,11 @@ struct ClickableProps<'a> {
body: Element<'a>
}
fn clickable(cx: Scope<ClickableProps>) -> Element {
fn Clickable(cx: Scope<ClickableProps>) -> Element {
cx.render(rsx!(
a {
href: "{cx.props.href}"
{&cx.props.body}
href: "{cx.props.href}",
&cx.props.body
}
))
}
@@ -78,15 +78,17 @@ Then, at the call site, we can render some nodes and pass them in:
```rust
rsx!(
clickable(
Clickable {
href: "https://google.com"
body: cx.render(rsx!(
img { src: "https://www.google.com/logos/doodles/2021/seasonal-holidays-2021-6753651837109324-6752733080595603-cst.gif" }
img { src: "https://www.google.com/logos/doodles/..." }
))
)
}
)
```
## Auto Conversion of the `Children` field
This pattern can become tedious in some instances, so Dioxus actually performs an implicit conversion of any `rsx` calls inside components into `Elements` at the `children` field. This means you must explicitly declare if a component can take children.
```rust
@@ -99,26 +101,26 @@ struct ClickableProps<'a> {
fn clickable(cx: Scope<ClickableProps>) -> Element {
cx.render(rsx!(
a {
href: "{cx.props.href}"
{&cx.props.children}
href: "{cx.props.href}",
&cx.props.children
}
))
}
```
And to call `clickable`:
Now, whenever we use `Clickable` in another component, we don't need to call `render` on child nodes - it will happen automatically!
```rust
rsx!(
clickable(
Clickable {
href: "https://google.com"
img { src: "https://www.google.com/logos/doodles/2021/seasonal-holidays-2021-6753651837109324-6752733080595603-cst.gif" }
)
img { src: "https://www.google.com/logos/doodles/...." }
}
)
```
> Note: Passing children into components will break any memoization due to the associated lifetime.
While technically allowed, it's an antipattern to pass children more than once in a component and will probably break your app significantly.
While technically allowed, it's an antipattern to pass children more than once in a component and will probably cause your app to crash.
However, because the `Element` is transparently a `VNode`, we can actually match on it to extract the nodes themselves, in case we are expecting a specific format:
@@ -142,10 +144,10 @@ In the cases where you need to pass arbitrary element properties into a componen
```rust
rsx!(
clickable(
Clickable {
"class": "blue-button",
"style": "background: red;"
)
}
)
```
@@ -161,7 +163,7 @@ struct ClickableProps<'a> {
fn clickable(cx: Scope<ClickableProps>) -> Element {
cx.render(rsx!(
a {
..{cx.props.attributes},
..cx.props.attributes,
"Any link, anywhere"
}
))
@@ -195,9 +197,9 @@ Then, we can attach a listener at the call site:
```rust
rsx!(
clickable(
Clickable {
onclick: move |_| log::info!("Clicked"),
)
}
)
```
@@ -110,7 +110,7 @@ When declaring a component in `rsx!`, we can pass in properties using the tradit
Let's take a look at the `VoteButton` component. For now, we won't include any interactivity - just the rendering the score and buttons to the screen.
Most of your Components will look exactly like this: a Props struct and a render function. Every component must take a tuple of `Scope` and `&Props` and return an `Element`.
Most of your Components will look exactly like this: a Props struct and a render function. Every component must take a `Scope` generic over some `Props` and return an `Element`.
As covered before, we'll build our User Interface with the `rsx!` macro and HTML tags. However, with components, we must actually "render" our HTML markup. Calling `cx.render` converts our "lazy" `rsx!` structure into an `Element`.
@@ -145,7 +145,7 @@ struct TitleCardProps<'a> {
title: &'a str,
}
fn TitleCard(cx: Scope<TitleCardProps>) -> Element {
fn TitleCard<'a>(cx: Scope<'a, TitleCardProps<'a>>) -> Element {
cx.render(rsx!{
h1 { "{cx.props.title}" }
})
@@ -156,6 +156,42 @@ For users of React: Dioxus knows *not* to memoize components that borrow propert
This means that during the render process, a newer version of `TitleCardProps` will never be compared with a previous version, saving some clock cycles.
## The inline_props macro
Yes - *another* macro! However, this one is entirely optional.
For internal components, we provide the `inline_props` macro, which will let you embed your `Props` definition right into the function arguments of your component.
Our title card above would be transformed from:
```rust
#[derive(Props, PartialEq)]
struct TitleCardProps {
title: String,
}
fn TitleCard(cx: Scope<TitleCardProps>) -> Element {
cx.render(rsx!{
h1 { "{cx.props.title}" }
})
}
```
to:
```rust
#[inline_props]
fn TitleCard(cx: Scope, title: String) -> Element {
cx.render(rsx!{
h1 { "{title}" }
})
}
```
Again, this macro is optional and should not be used by library authors since you have less fine-grained control over documentation and optionality.
However, it's great for quickly throwing together an app without dealing with *any* extra boilerplate.
## The `Scope` object
Though very similar to React, Dioxus is different in a few ways. Most notably, React components will not have a `Scope` parameter in the component declaration.
@@ -101,14 +101,14 @@ fn App(cx: Scope)-> Element {
## Nesting RSX
By looking at other examples, you might have noticed that it's possible to include `rsx!` calls inside other `rsx!` calls. With the curly-brace syntax, we can include anything in our `rsx!` that implements `IntoVnodeList`: a marker trait for iterators that produce Elements. `rsx!` itself implements this trait, so we can include it directly:
By looking at other examples, you might have noticed that it's possible to include `rsx!` calls inside other `rsx!` calls. We can include anything in our `rsx!` that implements `IntoVnodeList`: a marker trait for iterators that produce Elements. `rsx!` itself implements this trait, so we can include it directly:
```rust
rsx!(
div {
{rsx!(
rsx!(
"more rsx!"
)}
)
}
)
```
@@ -120,7 +120,7 @@ let title = rsx!( "more rsx!" );
rsx!(
div {
{title}
title
}
)
```
@@ -136,7 +136,7 @@ let screen = match logged_in {
cx.render(rsx!{
Navbar {}
{screen}
screen,
Footer {}
})
```
@@ -152,9 +152,9 @@ By default, Rust lets you convert any `boolean` into any other type by calling `
let show_title = true;
rsx!(
div {
{show_title.and_then(|| rsx!{
show_title.and_then(|| rsx!{
"This is the title"
})}
})
}
)
```
@@ -164,20 +164,23 @@ We can use this pattern for many things, including options:
let user_name = Some("bob");
rsx!(
div {
{user_name.map(|name| rsx!("Hello {name}"))}
user_name.map(|name| rsx!("Hello {name}"))
}
)
```
## Rendering Nothing
Sometimes, you don't want your component to return anything at all. In these cases, we can pass "None" into our bracket. However, Rust is not able to infer that our `None` corresponds to `Element` so we need to cast it appropriately:
Sometimes, you don't want your component to return anything at all. Under the hood, the `Element` type is just an alias for `Option<VNode>`, so you can simply return `None`.
This can be helpful in certain patterns where you need to perform some logical side-effects but don't want to render anything.
```rust
rsx!(cx, {None as Element} )
fn demo(cx: Scope) -> Element {
None
}
```
## Moving Forward:
In this chapter, we learned how to render different Elements from a Component depending on a condition. This is a very powerful building block to assemble complex User Interfaces!
@@ -25,27 +25,27 @@ fn main() {
dioxus::desktop::launch(App);
}
fn App((cx, props): Component) -> Element {}
fn App(Scope) -> Element {}
#[derive(PartialEq, Props)]
struct PostProps{}
fn Post((cx, props): Component<PostProps>) -> Element {}
fn Post(Scope<PostProps>) -> Element {}
#[derive(PartialEq, Props)]
struct VoteButtonsProps {}
fn VoteButtons((cx, props): Component<VoteButtonsProps>) -> Element {}
fn VoteButtons(Scope<VoteButtonsProps>) -> Element {}
#[derive(PartialEq, Props)]
struct TitleCardProps {}
fn TitleCard((cx, props): Component<TitleCardProps>) -> Element {}
fn TitleCard(Scope<TitleCardProps>) -> Element {}
#[derive(PartialEq, Props)]
struct MetaCardProps {}
fn MetaCard((cx, props): Component<MetaCardProps>) -> Element {}
fn MetaCard(Scope<MetaCardProps>) -> Element {}
#[derive(PartialEq, Props)]
struct ActionCardProps {}
fn ActionCard((cx, props): Component<ActionCardProps>) -> Element {}
fn ActionCard(Scope<ActionCardProps>) -> Element {}
```
That's a lot of components for one file! We've successfully refactored our app into components, but we should probably start breaking it up into a file for each component.
@@ -61,7 +61,7 @@ use dioxus::prelude::*;
#[derive(PartialEq, Props)]
struct ActionCardProps {}
fn ActionCard((cx, props): Component<ActionCardProps>) -> Element {}
fn ActionCard(Scope<ActionCardProps>) -> Element {}
```
We should also create a `mod.rs` file in the `post` folder so we can use it from our `main.rs`. Our `Post` component and its props will go into this file.
@@ -92,7 +92,7 @@ fn main() {
mod post;
fn App((cx, props): Component) -> Element {
fn App(Scope) -> Element {
cx.render(rsx!{
post::Post {
id: Uuid::new_v4(),
@@ -116,7 +116,7 @@ use dioxus::prelude::*;
#[derive(PartialEq, Props)]
pub struct PostProps {}
pub fn Post((cx, props): Component<PostProps>) -> Element {}
pub fn Post(Scope<PostProps>) -> Element {}
```
While we're here, we also need to make sure each of our subcomponents are included as modules and exported.
@@ -142,7 +142,7 @@ pub struct PostProps {
original_poster: String
}
pub fn Post((cx, props): Component<PostProps>) -> Element {
pub fn Post(Scope<PostProps>) -> Element {
cx.render(rsx!{
div { class: "post-container"
vote::VoteButtons {
@@ -191,7 +191,7 @@ fn main() {
mod post;
fn App((cx, props): Component) -> Element {
fn App(Scope) -> Element {
cx.render(rsx!{
post::Post {
id: Uuid::new_v4(),
@@ -227,7 +227,7 @@ pub struct PostProps {
original_poster: String
}
pub fn Post((cx, props): Component<PostProps>) -> Element {
pub fn Post(Scope<PostProps>) -> Element {
cx.render(rsx!{
div { class: "post-container"
vote::VoteButtons {
@@ -255,7 +255,7 @@ use dioxus::prelude::*;
#[derive(PartialEq, Props)]
pub struct VoteButtonsProps {}
pub fn VoteButtons((cx, props): Component<VoteButtonsProps>) -> Element {}
pub fn VoteButtons(Scope<VoteButtonsProps>) -> Element {}
```
```rust
@@ -264,7 +264,7 @@ use dioxus::prelude::*;
#[derive(PartialEq, Props)]
pub struct TitleCardProps {}
pub fn TitleCard((cx, props): Component<TitleCardProps>) -> Element {}
pub fn TitleCard(Scope<TitleCardProps>) -> Element {}
```
```rust
@@ -273,7 +273,7 @@ use dioxus::prelude::*;
#[derive(PartialEq, Props)]
pub struct MetaCardProps {}
pub fn MetaCard((cx, props): Component<MetaCardProps>) -> Element {}
pub fn MetaCard(Scope<MetaCardProps>) -> Element {}
```
```rust
@@ -282,7 +282,7 @@ use dioxus::prelude::*;
#[derive(PartialEq, Props)]
pub struct ActionCardProps {}
pub fn ActionCard((cx, props): Component<ActionCardProps>) -> Element {}
pub fn ActionCard(Scope<ActionCardProps>) -> Element {}
```
## Moving forward
+73
View File
@@ -0,0 +1,73 @@
# Core Topics
In this chapter, we'll cover some core topics on how Dioxus works and how to best leverage the features to build a beautiful, reactive app.
At a very high level, Dioxus is simply a Rust framework for _declaring_ user interfaces and _reacting_ to changes.
1) We declare what we want our user interface to look like given a state using Rust-based logic and control flow.
2) We declare how we want our state to change when the user triggers an event.
## Declarative UI
Dioxus is a *declarative* framework. This means that instead of manually writing calls to "create element" and "set element background to red," we simply *declare* what we want the element to look like and let Dioxus handle the differences.
Let's pretend that we have a stoplight we need to control - it has a color state with red, yellow, and green as options.
Using an imperative approach, we would have to manually declare each element and then handlers for advancing the stoplight.
```rust
let container = Container::new();
let green_light = Light::new().color("green").enabled(true);
let yellow_light = Light::new().color("yellow").enabled(false);
let red_light = Light::new().color("red").enabled(false);
container.push(green_light);
container.push(yellow_light);
container.push(red_light);
container.set_onclick(move |_| {
if red_light.enabled() {
red_light.set_enabled(false);
green_light.set_enabled(true);
} else if yellow_light.enabled() {
yellow_light.set_enabled(false);
red_light.set_enabled(true);
} else if green_light.enabled() {
green_light.set_enabled(false);
yellow_light.set_enabled(true);
}
});
```
As the UI grows in scale, our logic to keep each element in the proper state would grow exponentially. This can become very unwieldy and lead to out-of-sync UIs that harm user experience.
Instead, with Dioxus, we *declare* what we want our UI to look like:
```rust
let mut state = use_state(&cx, || "red");
cx.render(rsx!(
Container {
Light { color: "red", enabled: state == "red", }
Light { color: "yellow", enabled: state == "yellow", }
Light { color: "green", enabled: state == "green", }
onclick: move |_| {
state.set(match *state {
"green" => "yellow",
"yellow" => "red",
"red" => "green",
})
}
}
))
```
Remember: this concept is not new! Many frameworks are declarative - with React being the most popular. Declarative frameworks tend to be much more enjoyable to work with than imperative frameworks.
Here's some reading about declaring UI in React:
- [https://stackoverflow.com/questions/33655534/difference-between-declarative-and-imperative-in-react-js](https://stackoverflow.com/questions/33655534/difference-between-declarative-and-imperative-in-react-js)
- [https://medium.com/@myung.kim287/declarative-vs-imperative-251ce99c6c44](https://medium.com/@myung.kim287/declarative-vs-imperative-251ce99c6c44)
File renamed without changes.
@@ -87,9 +87,15 @@ Unfortunately, you cannot drop in arbitrary expressions directly into the string
rsx!( {[format_args!("Hello {}", if enabled { "Jack" } else { "Bob" } )]} )
```
Alternatively, `&str` can be included directly, though it must be inside of an array:
```rust
rsx!( "Hello ", [if enabled { "Jack" } else { "Bob" }] )
```
This is different from React's way of generating arbitrary markup but fits within idiomatic Rust.
Typically, with Dioxus, you'll just want to compute your substrings outside of the `rsx!` call:
Typically, with Dioxus, you'll just want to compute your substrings outside of the `rsx!` call and leverage the f-string formatting:
```rust
let name = if enabled { "Jack" } else { "Bob" };
@@ -100,7 +106,7 @@ rsx! ( "hello {name}" )
Every Element in your User Interface will have some sort of properties that the renderer will use when drawing to the screen. These might inform the renderer if the component should be hidden, what its background color should be, or to give it a specific name or ID.
To do this, we use the familiar struct-style syntax that Rust provides. Commas are optional:
To do this, we use the familiar struct-style syntax that Rust provides:
```rust
rsx!(
@@ -127,19 +133,29 @@ rsx!(
)
```
Note: the name of the custom attribute must match exactly what you want the renderer to output. All attributes defined as methods in `dioxus-html` follow the snake_case naming convention. However, they internally translate their snake_case convention to HTML's camelCase convention. When using custom attributes, make sure the name of the attribute exactly matches what the renderer is expecting.
> Note: the name of the custom attribute must match exactly what you want the renderer to output. All attributes defined as methods in `dioxus-html` follow the snake_case naming convention. However, they internally translate their snake_case convention to HTML's camelCase convention. When using custom attributes, make sure the name of the attribute **exactly** matches what the renderer is expecting.
All element attributes must occur *before* child elements. The `rsx!` macro will throw an error if your child elements come before any of your attributes. If you don't see the error, try editing your Rust-Analyzer IDE setting to ignore macro-errors. This is a temporary workaround because Rust-Analyzer currently throws *two* errors instead of just the one we care about.
```rust
// settings.json
{
"rust-analyzer.diagnostics.disabled": [
"macro-error"
],
}
```
## Listeners
Listeners are a special type of Attribute that only accept functions. Listeners let us attach functionality to our Elements by running a provided closure whenever the specified Listener is triggered.
We'll cover listeners in more depth in the Listeners chapter, but for now, just know that every listener must start with the `on` keyword and can accept either a closure or an expression wrapped in curly braces.
We'll cover listeners in more depth in the Listeners chapter, but for now, just know that every listener must start with the `on` keyword and accepts closures.
```rust
rsx!(
div {
onclick: move |_| {}
onmouseover: {handler},
onclick: move |_| log::debug!("div clicked!"),
}
)
```
+49
View File
@@ -0,0 +1,49 @@
# Congrats!
Congrats! You've made it through the `learning Dioxus` book. Throughout this tutorial, you've learned a ton:
- How to build User Interfaces with Elements
- How to compose Element groups together as Components
- How to handle user input with event listeners
- How to manage local and global state
- How to work with async using tasks, coroutines, and suspense
- How to build custom hooks and handlers
With any luck, you followed through the "Putting it All Together" mini guide and have your very own dog search engine app!
# Next Steps and Advanced Topics
Continuing on your journey with Dioxus, you can try a number of things:
- Build a simple TUI app
- Publish your search engine app
- Deploy a WASM app to GitHub
- Design a custom hook
- Contribute to the ecosystem!
There are a number of advanced topics we glossed over:
- The underlying NodeFactory API
- Static elements and templates
- Anti-patterns
- Bundling/distribution
- Working with wasm apps
# Contributing to the ecosystem
Dioxus is still quite young and could use your help!
The core team is actively working on:
- Declarative window management (via Tauri) for Desktop apps
- Portals for Dioxus Core
- Mobile support
- Integration with 3D renderers
- Better async story (suspense, error handling)
- Global state management
- Web development server
- LiveView
- Broader platform support (iOS/Android/TV/embedded)
If there's something specifically interesting to you, don't be afraid to jump in!
-10
View File
@@ -1,10 +0,0 @@
# Next Steps and Advanced Topics
Congrats! You've made it through the `learning Dioxus` book. Throughout this tutorial, you've learned a ton:
- How to build User Interfaces with Elements
- How to compose Element groups together as Components
- How to handle user input with event listeners
- How to manage global and local state
- How to work with async using tasks, coroutines, and suspense
+6 -4
View File
@@ -1,4 +1,4 @@
# Hello, World desktop app
# "Hello, World" desktop app
Let's put together a simple "hello world" desktop application to get acquainted with Dioxus.
@@ -138,11 +138,13 @@ Writing `fn App(cx: Scope) -> Element {` might become tedious. Rust will also le
static App: Component = |cx| cx.render(rsx!(div { "Hello, world!" }));
```
### What is this `Context` object?
### What is this `Scope` object?
Coming from React, the `Context` 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.
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 `Context` object to control how the component renders and stores data. The `Context` object provides a handful of useful APIs for features like suspense, rendering, and more.
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`.
## Moving on
Binary file not shown.

After

Width:  |  Height:  |  Size: 272 KiB

@@ -0,0 +1 @@
# Event handlers
@@ -19,16 +19,16 @@ Broadly, there are two types of GUI structures:
Typically, immediate-mode GUIs are simpler to write but can slow down as more features, like styling, are added.
Many GUIs today - including Dioxus - are written in *Retained mode* - your code changes the data of the user interface but the renderer is responsible for actually drawing to the screen. In these cases, our GUI's state sticks around as the UI is rendered.
Many GUIs today are written in *Retained mode* - your code changes the data of the user interface but the renderer is responsible for actually drawing to the screen. In these cases, our GUI's state sticks around as the UI is rendered. To help accommodate retained mode GUIs, like the web browser, Dioxus provides a mechanism to keep state around.
Dioxus, following in the footsteps of React, provides a "Reactive" model for you to design your UI. This model emphasizes one-way data flow and encapsulation. Essentially, your UI code should be as predictable as possible.
> Note: Even though hooks are accessible, you should still prefer to one-way data flow and encapsulation. Your UI code should be as predictable as possible. Dioxus is plenty fast, even for the largest apps.
## Mechanics of Hooks
In order to have state stick around between renders, Dioxus provides the `hook` through the `use_hook` API. This gives us a mutable reference to data returned from the initialization function.
```rust
fn example(cx: Scope) -> Element {
let name: &mut String = cx.use_hook(|| "John Doe".to_string(), |hook| hook);
let name: &mut String = cx.use_hook(|| "John Doe".to_string());
//
}
@@ -38,7 +38,7 @@ We can even modify this value directly from an event handler:
```rust
fn example(cx: Scope) -> Element {
let name: &mut String = cx.use_hook(|| "John Doe".to_string(), |hook| hook);
let name: &mut String = cx.use_hook(|| "John Doe".to_string());
cx.render(rsx!(
button {
@@ -52,9 +52,9 @@ Mechanically, each call to `use_hook` provides us with `&mut T` for a new value.
```rust
fn example(cx: Scope) -> Element {
let name: &mut String = cx.use_hook(|| "John Doe".to_string(), |hook| hook);
let age: &mut u32 = cx.use_hook(|| 10, |hook| hook);
let friends: &mut Vec<String> = cx.use_hook(|| vec!["Jane Doe".to_string()], |hook| hook);
let name: &mut String = cx.use_hook(|| "John Doe".to_string());
let age: &mut u32 = cx.use_hook(|| 10);
let friends: &mut Vec<String> = cx.use_hook(|| vec!["Jane Doe".to_string()]);
//
}
@@ -84,7 +84,7 @@ Consider when we try to pass our `&mut String` into two different handlers:
```rust
fn example(cx: Scope) -> Element {
let name: &mut String = cx.use_hook(|| "John Doe".to_string(), |hook| hook);
let name: &mut String = cx.use_hook(|| "John Doe".to_string());
cx.render(rsx!(
button { onclick: move |_| name.push_str("yes"), }
@@ -112,7 +112,7 @@ This example uses the `Cell` type to let us replace the value through interior m
```rust
fn example(cx: Scope) -> Element {
let name: &Cell<&'static str> = cx.use_hook(|| "John Doe", |hook| hook);
let name: &Cell<&'static str> = cx.use_hook(|| Cell::new("John Doe"));
cx.render(rsx!(
button { onclick: move |_| name.set("John"), }
@@ -180,6 +180,8 @@ By default, we bundle a handful of hooks in the Dioxus-Hooks package. Feel free
- [use_callback](https://docs.rs/dioxus_hooks/use_callback) - store a callback that implements PartialEq for memoization
- [use_provide_context](https://docs.rs/dioxus_hooks/use_provide_context) - expose state to descendent components
- [use_context](https://docs.rs/dioxus_hooks/use_context) - consume state provided by `use_provide_context`
For a more in-depth guide to building new hooks, checkout out the advanced hook building guide in the reference.
## Wrapping up
@@ -139,7 +139,7 @@ fn App(cx: Scope)-> Element {
let mut sec_elapsed = use_state(&cx, || 0);
use_future(&cx, || {
let mut sec_elapsed = sec_elapsed.to_owned();
let mut sec_elapsed = sec_elapsed.for_async();
async move {
loop {
TimeoutFuture::from_ms(1000).await;
+1 -1
View File
@@ -58,7 +58,7 @@ That's it! We won't need to touch NPM/WebPack/Babel/Parcel, etc. However, you _c
## Rust Knowledge
With Rust, things like benchmarking, testing, and documentation are included in the language. We strongly recommend going through the official Rust book _completely_. However, our hope is that a Dioxus app can serve as a great first project. With Dioxus you'll learn about:
With Rust, things like benchmarking, testing, and documentation are included in the language. We strongly recommend going through the official Rust book _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
+8
View File
@@ -0,0 +1,8 @@
# 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 particular 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 then take an overview
## Terminology
+1
View File
@@ -0,0 +1 @@
# Lifting State
+1
View File
@@ -0,0 +1 @@
# Local State
File renamed without changes.
+64
View File
@@ -1 +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:
![Published App](../images/publish.png)
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.