Merge branch 'master' into master

This commit is contained in:
Jonathan Kelley authored and GitHub committed 2023-07-14 15:36:28 -07:00
commit af49cb4ec6
313 files changed
+23988 -2334

No files matched your search

@@ -2,7 +2,7 @@
Yew subscriptions are used to schedule update for components into the future. The `Context` object can create subscriptions:
```rust
```rust, no_run
fn Component(cx: Component) -> DomTree {
let update = cx.schedule();
@@ -19,7 +19,7 @@ The subscription API exposes this functionality allowing hooks and state managem
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
```rust, no_run
fn use_context<I>(cx: Scope<T>) -> I {
}
@@ -4,7 +4,7 @@ Concurrent mode provides a mechanism for building efficient asynchronous compone
To make a component asynchronous, simply change its function signature to async.
```rust
```rust, no_run
fn Example(cx: Scope) -> Vnode {
rsx!{ <div> "Hello world!" </div> }
}
@@ -12,7 +12,7 @@ fn Example(cx: Scope) -> Vnode {
becomes
```rust
```rust, no_run
async fn Example(cx: Scope) -> Vnode {
rsx!{ <div> "Hello world!" </div> }
}
@@ -20,7 +20,7 @@ async fn Example(cx: Scope) -> Vnode {
Now, logic in components can be awaited to delay updates of the component and its children. Like so:
```rust
```rust, no_run
async fn Example(cx: Scope) -> Vnode {
let name = fetch_name().await;
rsx!{ <div> "Hello {name}" </div> }
@@ -39,7 +39,7 @@ Instead, we suggest using hooks and future combinators that can safely utilize t
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
```rust, no_run
async fn ExampleLoader(cx: Scope) -> Vnode {
/*
Fetch, pause the component from rendering at all.
@@ -61,7 +61,7 @@ async fn ExampleLoader(cx: Scope) -> Vnode {
}
```
```rust
```rust, no_run
async fn Example(cx: Scope) -> DomTree {
// Diff this set between the last set
// Check if we have any outstanding tasks?
@@ -10,7 +10,7 @@ https://dmitripavlutin.com/use-react-memo-wisely/
This behavior is defined as an attribute implicit to user components. When in React land you might wrap a component with `react.memo`, Dioxus components are automatically memoized via an implicit attribute. You can manually configure this behavior on any component with "nomemo" to disable memoization.
```rust
```rust, no_run
fn test() -> DomTree {
html! {
<>
@@ -42,7 +42,7 @@ fn test_component(cx: Scope, name: String) -> Element {
Take a component like this:
```rust
```rust, no_run
fn test(cx: Scope) -> DomTree {
let Bundle { alpha, beta, gamma } = use_context::<SomeContext>(cx);
html! {
@@ -10,7 +10,7 @@ By default, Dioxus will only try to diff subtrees of components with dynamic con
Your component today might look something like this:
```rust
```rust, no_run
fn Comp(cx: Scope) -> DomTree {
let (title, set_title) = use_state(cx, || "Title".to_string());
cx.render(rsx!{
@@ -24,7 +24,7 @@ fn Comp(cx: Scope) -> DomTree {
This component is fairly straightforward – the input updates its own value on every change. However, every call to set_title will re-render the component. If we add a large list, then every time we update the title input, Dioxus will need to diff the entire list, over, and over, and over. This is **a lot** of wasted clock-cycles!
```rust
```rust, no_run
fn Comp(cx: Scope) -> DomTree {
let (title, set_title) = use_state(cx, || "Title".to_string());
cx.render(rsx!{
@@ -47,7 +47,7 @@ Many experienced React developers will just say "this is bad design" – but we
We can use signals to generate a two-way binding between data and the input box. Our text input is now just a two-line component!
```rust
```rust, no_run
fn Comp(cx: Scope) -> DomTree {
let mut title = use_signal(cx, || String::from("Title"));
cx.render(rsx!(input { value: title }))
@@ -56,7 +56,7 @@ fn Comp(cx: Scope) -> DomTree {
For a slightly more interesting example, this component calculates the sum between two numbers, but totally skips the diffing process.
```rust
```rust, no_run
fn Calculator(cx: Scope) -> DomTree {
let mut a = use_signal(cx, || 0);
let mut b = use_signal(cx, || 0);
@@ -71,7 +71,7 @@ fn Calculator(cx: Scope) -> DomTree {
Do you notice how we can use built-in operations on signals? Under the hood, we actually create a new derived signal that depends on `a` and `b`. Whenever `a` or `b` update, then `c` will update. If we need to create a new derived signal that's more complex than a basic operation (`std::ops`) we can either chain signals together or combine them:
```rust
```rust, no_run
let mut a = use_signal(cx, || 0);
let mut b = use_signal(cx, || 0);
@@ -83,7 +83,7 @@ let c = a.with(b).map(|(a, b)| *a + *b);
If we ever need to get the value out of a signal, we can simply `deref` it.
```rust
```rust, no_run
let mut a = use_signal(cx, || 0);
let c = *a + *b;
```
@@ -94,8 +94,10 @@ Calling `deref` or `deref_mut` is actually more complex than it seems. When a va
Sometimes you want a signal to propagate across your app, either through far-away siblings or through deeply-nested components. In these cases, we use Dirac: Dioxus's first-class state management toolkit. Dirac atoms automatically implement the Signal API. This component will bind the input element to the `TITLE` atom.
```rust
```rust, no_run
const TITLE: Atom<String> = Atom(|| "".to_string());
const Provider: Component = |cx|{
let title = use_signal(cx, &TITLE);
render!(input { value: title })
@@ -104,7 +106,7 @@ const Provider: Component = |cx|{
If we use the `TITLE` atom in another component, we can cause updates to flow between components without calling render or diffing either component trees:
```rust
```rust, no_run
const Receiver: Component = |cx|{
let title = use_signal(cx, &TITLE);
log::info!("This will only be called once!");
@@ -130,8 +132,9 @@ By default, Dioxus is limited when you use iter/map. With the `For` component, y
Dioxus automatically understands how to use your signals when mixed with iterators through `Deref`/`DerefMut`. This lets you efficiently map collections while avoiding the re-rendering of lists. In essence, signals act as a hint to Dioxus on how to avoid un-necessary checks and renders, making your app faster.
```rust
```rust, no_run
const DICT: AtomFamily<String, String> = AtomFamily(|_| {});
const List: Component = |cx|{
let dict = use_signal(cx, &DICT);
cx.render(rsx!(
@@ -142,14 +145,6 @@ const List: Component = |cx|{
};
```
## Remote Signals
Apps that use signals will enjoy a pleasant hybrid of server-side and client-side rendering.
```rust
```
## How does it work?
Signals internally use Dioxus' asynchronous rendering infrastructure to perform updates out of the tree.
@@ -22,13 +22,11 @@ The desktop renderer comes pre-loaded with the window and notification subtree p
Subtrees also solve the "bridging" issues in React where two different renderers need two different VirtualDoms to work properly. In Dioxus, you only ever need one VirtualDom and the right renderer plugins.
## API
Due to their importance in the hierarchy, Components – not nodes – are treated as subtree roots.
```rust
```rust, no_run
fn Subtree<P>(cx: Scope<P>) -> DomTree {
@@ -22,7 +22,7 @@ For reference, check out the WebSys renderer as a starting point for your custom
The current `RealDom` trait lives in `dioxus-core/diff`. A version of it is provided here (but might not be up-to-date):
```rust
```rust, no_run
pub trait RealDom<'a> {
fn handle_edit(&mut self, edit: DomEdit);
fn request_available_node(&mut self) -> ElementId;
@@ -32,7 +32,7 @@ pub trait RealDom<'a> {
For reference, the "DomEdit" type is a serialized enum that represents an atomic operation occurring on the RealDom. The variants roughly follow this set:
```rust
```rust, no_run
enum DomEdit {
PushRoot,
AppendChildren,
@@ -51,12 +51,11 @@ enum DomEdit {
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
```rust, no_run
rsx!( h1 {"hello world"} )
```
@@ -64,7 +63,7 @@ To get things started, Dioxus must first navigate to the container of this h1 ta
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
```rust, no_run
instructions: [
PushRoot(Container)
]
@@ -75,7 +74,7 @@ stack: [
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
```rust, no_run
instructions: [
PushRoot(Container),
CreateElement(h1),
@@ -85,8 +84,10 @@ stack: [
h1,
]
```
Next, Dioxus sees the text node, and generates the `CreateTextNode` DomEdit:
```rust
```rust, no_run
instructions: [
PushRoot(Container),
CreateElement(h1),
@@ -98,9 +99,10 @@ stack: [
"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
```rust, no_run
instructions: [
PushRoot(Container),
CreateElement(h1),
@@ -112,8 +114,10 @@ stack: [
h1
]
```
We call `AppendChildren` again, popping off the h1 node and attaching it to the parent:
```rust
```rust, no_run
instructions: [
PushRoot(Container),
CreateElement(h1),
@@ -125,8 +129,10 @@ stack: [
ContainerNode,
]
```
Finally, the container is popped since we don't need it anymore.
```rust
```rust, no_run
instructions: [
PushRoot(Container),
CreateElement(h1),
@@ -137,8 +143,10 @@ instructions: [
]
stack: []
```
Over time, our stack looked like this:
```rust
```rust, no_run
[]
[Container]
[Container, h1]
@@ -164,7 +172,7 @@ Like most GUIs, Dioxus relies on an event loop to progress the VirtualDOM. The V
The code for the WebSys implementation is straightforward, so we'll add it here to demonstrate how simple an event loop is:
```rust
```rust, no_run
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());
@@ -194,7 +202,7 @@ pub async fn run(&mut self) -> dioxus_core::error::Result<()> {
It's important that you decode the real events from your event system into Dioxus' synthetic event system (synthetic meaning abstracted). This simply means matching your event type and creating a Dioxus `VirtualEvent` type. Your custom event must implement the corresponding event trait. Right now, the VirtualEvent system is modeled almost entirely around the HTML spec, but we are interested in slimming it down.
```rust
```rust, no_run
fn virtual_event_from_websys_event(event: &web_sys::Event) -> VirtualEvent {
match event.type_().as_str() {
"keydown" | "keypress" | "keyup" => {
@@ -224,7 +232,7 @@ These custom elements are defined as unit structs with trait implementations.
For example, the `div` element is (approximately!) defined as such:
```rust
```rust, no_run
struct div;
impl div {
/// Some glorious documentation about the class property.
@@ -235,8 +243,8 @@ impl div {
// more attributes
}
```
You've probably noticed that many elements in the `rsx!` and `html!` macros support on-hover documentation. The approach we take to custom elements means that the unit struct is created immediately where the element is used in the macro. When the macro is expanded, the doc comments still apply to the unit struct, giving tons of in-editor feedback, even inside a proc macro.
You've probably noticed that many elements in the `rsx!` and `html!` macros support on-hover documentation. The approach we take to custom elements means that the unit struct is created immediately where the element is used in the macro. When the macro is expanded, the doc comments still apply to the unit struct, giving tons of in-editor feedback, even inside a proc macro.
## Compatibility
@@ -252,7 +260,7 @@ The best hooks will properly detect the target platform and still provide functi
This particular code _will panic_ due to the unwrap on downcast_ref. Try to avoid these types of patterns.
```rust
```rust, no_run
let div_ref = use_node_ref(cx);
cx.render(rsx!{
@@ -5,11 +5,14 @@ Many modern frameworks provide a domain-specific-language for declaring user-int
With Dioxus, we actually ship two different macros – a macro that mimics JSX (the `html!` macro) and a macro that mimics Rust's native nested-struct syntax (the `rsx!` macro). These macros simply transform their inputs into NodeFactory calls.
For instance, this html! call:
```rust
```rust, no_run
html!(<div> "hello world" </div>)
```
becomes this NodeFactory call:
```rust
```rust, no_run
|f| f.element(
dioxus_elements::div, // tag
[], // listeners
@@ -18,6 +21,7 @@ becomes this NodeFactory call:
None // key
)
```
The NodeFactory API is fairly ergonomic, making it a viable option to use directly. The NodeFactory API is also compile-time correct and has incredible syntax highlighting support. We use what Rust calls a "unit type" – the `dioxus_elements::div` and associated methods to ensure that a `div` can only have attributes associated with `div`s. This lets us tack on relevant documentation, autocomplete support, and jump-to-definition for methods and attributes.
![Compile time correct syntax](../images/compiletimecorrect.png)
@@ -28,7 +32,7 @@ The html! macro supports a limited subset of the html standard. Rust's macro par
However, writing HTML by hand is a bit tedious – IDE tools for Rust don't support linting/autocomplete/syntax highlighting. We suggest using RSX – it's more natural for Rust programs and _does_ integrate well with Rust IDE tools.
```rust
```rust, no_run
let name = "jane";
let pending = false;
let count = 10;
@@ -50,7 +54,7 @@ When helpful, the Dioxus VSCode extension provides a way of converting a selecti
It's also a bit easier on the eyes than HTML.
```rust
```rust, no_run
dioxus::ssr::render_lazy(rsx! {
div {
p {"Hello, {name}!"}
@@ -2,7 +2,7 @@
To test your Rust code, you can annotate any function with the `#[test]` block. In VSCode with RA, this will provide a lens to click and run the test.
```rust
```rust, no_run
#[test]
fn component_runs() {
assert!(true)
@@ -11,7 +11,7 @@ fn component_runs() {
This will test your Rust code _without_ going through the browser. This is ideal for squashing logic bugs and ensuring components render appropriately when the browsers's DOM is not needed. If you need to run tests in the browser, you can annotate your blocks with the `#[dioxus::test]` block.
```rust
```rust, no_run
#[dioxus::test]
fn runs_in_browser() {
// ...