docs: more docs
This commit is contained in:
1 parent
0f0fc3e4b8
commit
0826fdfee1
14 files changed
+59
-270
No files matched your search
@@ -1,37 +0,0 @@
|
||||
# Dioxus Chapter 0 - Intro + Index
|
||||
|
||||
|
||||
|
||||
## Guides
|
||||
------------------
|
||||
| Chapter | Description |
|
||||
| ------------------ | ------------------------------------------ |
|
||||
| 1-hello-world | Intro to Dioxus |
|
||||
| 2-utilities | Tools to make writing apps easier |
|
||||
| 3-vnode-macros | VNodes and the html! macro |
|
||||
| 4-hooks | Renderer + event integration using web_sys |
|
||||
| 5-context-api | Virtual DOM, patching/diffing |
|
||||
| 6-subscription API | Standard bundle of useful hooks |
|
||||
| 7-hello-world | Html + functional_component macro |
|
||||
| 8-hello-world | Blessed state management solutions |
|
||||
| 9-hello-world | Renderer + event integration using web_sys |
|
||||
| 10-hello-world | Renderer + event integration using web_sys |
|
||||
|
||||
## Development
|
||||
------------------
|
||||
| Package | Use |
|
||||
| ------- | ------------------------------------------------ |
|
||||
| full | Batteries-included entrypoint with feature flags |
|
||||
| core | Virtual DOM, diffing, patching, and events |
|
||||
| hooks | Standard hooks |
|
||||
| macro | Html + functional_component macro |
|
||||
| web | Renderer + event integration using web_sys |
|
||||
| live | Dedicated isomorphic framework |
|
||||
| recoil | Data-flow-graph state management |
|
||||
| redux | Reducer-style state management |
|
||||
| bearly | Simple and idiomatic state management |
|
||||
|
||||
## Books
|
||||
---------------
|
||||
Book of patterns
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
# Hello, World!
|
||||
|
||||
Dioxus should look and feel just like writing functional React components. In Dioxus, there are no class components with lifecycles. All state management is done via hooks. This encourages logic reusability and lessens the burden on Dioxus to maintain a non-breaking lifecycle API.
|
||||
|
||||
```rust
|
||||
#[derive(Properties, PartialEq)]
|
||||
struct MyProps {
|
||||
name: String
|
||||
}
|
||||
|
||||
fn Example(cx: Context<MyProps>) -> VNode {
|
||||
cx.render(html! {
|
||||
<div> "Hello {cx.name}!" </div>
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
For functions to be valid components, they must take the `Context` object which is generic over some properties. The properties parameter must implement the `Properties` trait, which can be automatically derived. Whenever the input properties of a component changes, the function component will be re-ran and a new set of VNodes will be generated.
|
||||
@@ -1,52 +0,0 @@
|
||||
# Utilities
|
||||
|
||||
There are a few macros and utility functions that make life easier when writing Dioxus components.
|
||||
|
||||
## The `functional_component` procedural macro
|
||||
|
||||
The `functional_component` proc macro allows you to inline props into the generic parameter of the component's context. This is useful When writing "pure" components, or when you don't want the extra clutter of structs, derives, and burden of naming things.
|
||||
|
||||
This macro allows allows a classic struct definition to be embedded directly into the function arguments. The props are automatically pulled from the context and destructured into the function's body, saving an extra step.
|
||||
|
||||
```rust
|
||||
// Inlines and destructure props *automatically*
|
||||
#[functional_component]
|
||||
fn Example(cx: Context, name: &str, pending: bool, count: i32 ) -> VNode {
|
||||
html! {
|
||||
<div>
|
||||
<p> "Hello, {name}!" </p>
|
||||
<p> "Status: {pending}!" </p>
|
||||
<p> "Count {count}!" </p>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
becomes this:
|
||||
|
||||
```rust
|
||||
#[derive(Debug, Properties, PartialEq)]
|
||||
struct ExampleProps {
|
||||
name: String
|
||||
pending: bool
|
||||
count: i32
|
||||
};
|
||||
|
||||
fn Example(cx: &mut Context<ExampleProps>) -> VNode {
|
||||
let ExampleProps {
|
||||
name, pending, count
|
||||
} = cx.props;
|
||||
|
||||
rsx! {
|
||||
<div>
|
||||
<p> "Hello, {name}!" </p>
|
||||
<p> "Status: {pending}!" </p>
|
||||
<p> "Count {count}!" </p>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## The rsx! macro
|
||||
|
||||
The rsx! macacro is similar to the html! macro in other libraries, but with a few add-ons to make it fun and easy to work with. We'll cover the rsx macro more in depth in the [vnode-macro](3-vnode-macros.md) chapter.
|
||||
@@ -1,145 +0,0 @@
|
||||
# VNode Macros
|
||||
|
||||
Dioxus comes preloaded with two macros for creating VNodes.
|
||||
|
||||
## html! macro
|
||||
|
||||
The html! macro supports a limited subset of the html standard. This macro will happily accept a copy-paste from something like tailwind builder. However, writing HTML by hand is a bit tedious - IDE tools for Rust don't support linting/autocomplete/syntax highlighting. RSX is much more natural for Rust programs and _does_ integrate well with Rust IDE tools.
|
||||
|
||||
There is also limited support for dynamic handlers, but it will function similarly to JSX.
|
||||
|
||||
You'll want to write RSX where you can, and in a future release we'll have a tool that automatically converts HTML to RSX.
|
||||
|
||||
```rust
|
||||
#[fc]
|
||||
fn Example(cx: Context, name: &str, pending: bool, count: i32 ) -> VNode {
|
||||
cx.render(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, and section selecting.
|
||||
|
||||
The Dioxus VSCode extension will eventually provide a macro to convert a selection of html! template and turn it into rsx!, so you'll never need to transcribe templates by hand.
|
||||
|
||||
It's also a bit easier on the eyes 🙂.
|
||||
|
||||
```rust
|
||||
#[fc]
|
||||
fn Example(cx: Context, name: &str, pending: bool, count: i32 ) -> VNode {
|
||||
cx.render(rsx! {
|
||||
div {
|
||||
p {"Hello, {name}!"}
|
||||
p {"Status: {pending}!"}
|
||||
p {"Count {count}!"}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Each element takes a comma-separated list of expressions to build the node. Roughly, here's how they work:
|
||||
|
||||
- `name: value` sets the 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 IntoCtx<Vnode> 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.
|
||||
|
||||
```rust
|
||||
static Example: FC<()> = |cx| {
|
||||
|
||||
let text = "example";
|
||||
|
||||
cx.render(rsx!{
|
||||
div {
|
||||
h1 { "Example" },
|
||||
|
||||
// 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}",
|
||||
|
||||
// bool-based classnames
|
||||
classes: [("big", true), ("small", false)]
|
||||
|
||||
// Bool-based props
|
||||
// *must* be in the tuple form, cannot enter as a variable
|
||||
tag: ("type", false)
|
||||
|
||||
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!(in cx, h1 { "big" })
|
||||
2 => rsx!(in cx, h2 { "medium" })
|
||||
_ => rsx!(in cx, h3 { "small" })
|
||||
}}
|
||||
|
||||
// Optionals
|
||||
{true.and_then(|f| rsx!{ h1 {"Conditional Rendering"} })}
|
||||
|
||||
// Bool options
|
||||
{(rsx!{ h1 {"Conditional Rendering"}, true)}
|
||||
|
||||
// Child nodes
|
||||
// Returns &[VNode]
|
||||
{cx.children()}
|
||||
|
||||
// Duplicating nodes
|
||||
// Clones the nodes by reference, so they are literally identical
|
||||
{{
|
||||
let node = rsx!(in cx, h1{ "TopNode" });
|
||||
(0..10).map(|_| node.clone())
|
||||
}}
|
||||
|
||||
// Any expression that is `IntoVNode`
|
||||
{expr}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
```
|
||||
@@ -1,16 +0,0 @@
|
||||
```rust
|
||||
fn Example(cx: &mut Context<()>) -> VNode {
|
||||
let service = use_combubulator(cx);
|
||||
let Status { name, pending, count } = service.info();
|
||||
html! {
|
||||
<div>
|
||||
<p> "Hello, {name}!" </p>
|
||||
<p> "Status: {pending}!" </p>
|
||||
<p> "Count {count}!" </p>
|
||||
<button onclick=|_| service.update()>
|
||||
"Refresh services"
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -1,45 +0,0 @@
|
||||
# Context API
|
||||
|
||||
```rust
|
||||
// Create contexts available to children
|
||||
// Only one context can be associated with any given component
|
||||
// This is known as "exposed state". Children can access this context,
|
||||
// but will not be automatically subscribed.
|
||||
fn ContextCreate(cx: &mut Context<()>) -> VNode {
|
||||
let context = cx.set_context(|| CustomContext::new());
|
||||
html! { <> {cx.children()} </> }
|
||||
}
|
||||
|
||||
fn ContextRead(cx: &mut Context<()>) -> VNode {
|
||||
// Panics if context is not available
|
||||
let some_cx = cx.get_context::<CustomContext>();
|
||||
let text = some_cx.select("some_selector");
|
||||
html! { <div> "{text}" </div> }
|
||||
}
|
||||
|
||||
fn Subscription(cx: &mut Context<()>) -> VNode {
|
||||
// Open a "port" on the component for actions to trigger a re-evaluation
|
||||
let subscription = cx.new_subscription();
|
||||
|
||||
// A looping timer - the effect is re-called on every re-evaluation
|
||||
use_async_effect(cx, move || async {
|
||||
timer::new(2000).await;
|
||||
subscription.call();
|
||||
}, None);
|
||||
|
||||
// A one-shot timer, the deps don't change so the effect only happens once
|
||||
use_async_effect_deps(cx, move || async {
|
||||
timer::new(2000).await;
|
||||
subscription.call();
|
||||
}, ());
|
||||
}
|
||||
|
||||
// Mix subscriptions and context to make a simple Redux
|
||||
fn use_global_state<T: UserContextTrait>(cx: &mut Context<()>) -> T {
|
||||
let some_cx = cx.get_context::<T>();
|
||||
let component_subscription = cx.new_subscription();
|
||||
some_cx.subscribe_component(component_subscription);
|
||||
some_cx
|
||||
}
|
||||
|
||||
```
|
||||
@@ -1,33 +0,0 @@
|
||||
# Subscriptions
|
||||
|
||||
Yew subscriptions are used to schedule update for components into the future. The `Context` object can create subscriptions:
|
||||
|
||||
```rust
|
||||
fn Component(cx: Component<()>) -> VNode {
|
||||
let update = cx.schedule();
|
||||
|
||||
// Now, when the subscription is called, the component will be re-evaluted
|
||||
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: Context<T>) -> I {
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
```
|
||||
Whitespace-only changes.
Whitespace-only changes.
@@ -1,82 +0,0 @@
|
||||
# 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: Context<()>) -> Vnode {
|
||||
rsx!{ <div> "Hello world!" </div> }
|
||||
}
|
||||
```
|
||||
|
||||
becomes
|
||||
|
||||
```rust
|
||||
async fn Example(cx: Context<()>) -> 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: Context<()>) -> 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, and cause confusion.
|
||||
|
||||
Instead, we suggest using hooks and future combinators that can safely utilize the safe guards 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: Context<()>) -> 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 occured :(" </div>}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```rust
|
||||
async fn Example(cx: Context<()>) -> VNode {
|
||||
// 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>
|
||||
}
|
||||
```
|
||||
@@ -1,56 +0,0 @@
|
||||
# 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 implicit attribute to user components. When in React land you might wrap a component is `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() -> VNode {
|
||||
html! {
|
||||
<>
|
||||
<SomeComponent nomemo />
|
||||
// same as
|
||||
<SomeComponent nomemo=true />
|
||||
</>
|
||||
}
|
||||
}
|
||||
|
||||
static TestComponent: FC<()> = |cx| html!{<div>"Hello world"</div>};
|
||||
|
||||
static TestComponent: FC<()> = |cx| {
|
||||
let g = "BLAH";
|
||||
html! {
|
||||
<div> "Hello world" </div>
|
||||
}
|
||||
};
|
||||
|
||||
#[functional_component]
|
||||
static TestComponent: FC<{ name: String }> = |cx| html! { <div> "Hello {name}" </div> };
|
||||
```
|
||||
|
||||
## Why this behavior?
|
||||
|
||||
"This is different than React, why differ?".
|
||||
|
||||
Take a component likes this:
|
||||
|
||||
```rust
|
||||
fn test(cx: Context<()>) -> VNode {
|
||||
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 destructued bundle might change, not every child component will need to be re-rendered.
|
||||
Reference in new issue
Block a user