diff --git a/.github/workflows/cli_release.yml b/.github/workflows/cli_release.yml index c6c2b81e8..4cd33f47e 100644 --- a/.github/workflows/cli_release.yml +++ b/.github/workflows/cli_release.yml @@ -29,7 +29,7 @@ jobs: toolchain: "1.70.0", } steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Install stable uses: dtolnay/rust-toolchain@master with: diff --git a/.github/workflows/docs stable.yml b/.github/workflows/docs stable.yml index 069d4308a..642216f0f 100644 --- a/.github/workflows/docs stable.yml +++ b/.github/workflows/docs stable.yml @@ -23,7 +23,7 @@ jobs: - name: Setup mdBook run: | cargo install mdbook --git https://github.com/Demonthos/mdBook.git --branch master - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Build run: cd docs && diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 3a452e770..88542aea8 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -1,12 +1,13 @@ name: github pages on: - push: - paths: - - docs/** - - .github/workflows/docs.yml - branches: - - master + workflow_dispatch: + # push: + # paths: + # - docs/** + # - .github/workflows/docs.yml + # branches: + # - master concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} @@ -28,7 +29,7 @@ jobs: - name: Setup mdBook run: | cargo install mdbook --git https://github.com/Demonthos/mdBook.git --branch master - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Build run: cd docs && diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 04f367b8e..037525557 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -41,7 +41,7 @@ jobs: - uses: Swatinem/rust-cache@v2 - run: sudo apt-get update - run: sudo apt install libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: cargo check --all --examples --tests test: @@ -56,7 +56,7 @@ jobs: - uses: davidB/rust-cargo-make@v1 - uses: browser-actions/setup-firefox@latest - uses: jetli/wasm-pack-action@v0.4.0 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: cargo make tests fmt: @@ -67,7 +67,7 @@ jobs: - uses: dtolnay/rust-toolchain@stable - uses: Swatinem/rust-cache@v2 - run: rustup component add rustfmt - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: cargo fmt --all -- --check clippy: @@ -80,7 +80,7 @@ jobs: - run: sudo apt-get update - run: sudo apt install libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev - run: rustup component add clippy - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: cargo clippy --workspace --examples --tests -- -D warnings matrix_test: @@ -124,7 +124,7 @@ jobs: } steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: install stable uses: dtolnay/rust-toolchain@master @@ -154,7 +154,7 @@ jobs: # options: --security-opt seccomp=unconfined # steps: # - name: Checkout repository - # uses: actions/checkout@v3 + # uses: actions/checkout@v4 # - name: Generate code coverage # run: | # apt-get update &&\ diff --git a/.github/workflows/miri.yml b/.github/workflows/miri.yml index b1d772512..4a467b9b2 100644 --- a/.github/workflows/miri.yml +++ b/.github/workflows/miri.yml @@ -69,7 +69,7 @@ jobs: if: runner.os == 'Linux' run: echo "MIRIFLAGS=-Zmiri-tag-gc=1" >> $GITHUB_ENV - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Install Rust ${{ env.rust_nightly }} uses: dtolnay/rust-toolchain@master with: diff --git a/.github/workflows/playwright.yml b/.github/workflows/playwright.yml index dba32d257..500d41564 100644 --- a/.github/workflows/playwright.yml +++ b/.github/workflows/playwright.yml @@ -19,7 +19,7 @@ jobs: runs-on: ubuntu-latest steps: # Do our best to cache the toolchain and node install steps - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: actions/setup-node@v3 with: node-version: 16 diff --git a/Cargo.toml b/Cargo.toml index 54c54ebf1..e6b07eb8c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -37,8 +37,6 @@ members = [ "packages/fullstack/examples/salvo-hello-world", "packages/fullstack/examples/warp-hello-world", "packages/fullstack/examples/static-hydrated", - "docs/guide", - "docs/router", # Full project examples "examples/tailwind", "examples/PWA-example", @@ -82,7 +80,8 @@ generational-box = { path = "packages/generational-box" } dioxus-hot-reload = { path = "packages/hot-reload", version = "0.4.0" } dioxus-fullstack = { path = "packages/fullstack", version = "0.4.1" } dioxus_server_macro = { path = "packages/server-macro", version = "0.4.1" } -log = "0.4.19" +tracing = "0.1.37" +tracing-futures = "0.2.5" tokio = "1.28" slab = "0.4.2" futures-channel = "0.3.21" diff --git a/docs/.nojekyll b/docs/.nojekyll deleted file mode 100644 index e69de29bb..000000000 diff --git a/docs/README.md b/docs/README.md deleted file mode 100644 index 766752ecf..000000000 --- a/docs/README.md +++ /dev/null @@ -1,19 +0,0 @@ -# Building the Documentation - -Dioxus uses a fork of MdBook with multilanguage support. To build the documentation, you will need to install the forked version of MdBook. - -```sh -cargo install mdbook --git https://github.com/Demonthos/mdBook.git --branch master -``` - -Then, you can build the documentation by running: - -```sh -cd docs -cd guide -mdbook build -d ../nightly/guide -cd .. -cd router -mdbook build -d ../nightly/router -cd ../../ -``` diff --git a/docs/fermi/.gitignore b/docs/fermi/.gitignore deleted file mode 100644 index 7585238ef..000000000 --- a/docs/fermi/.gitignore +++ /dev/null @@ -1 +0,0 @@ -book diff --git a/docs/fermi/book.toml b/docs/fermi/book.toml deleted file mode 100644 index dd6d2eacb..000000000 --- a/docs/fermi/book.toml +++ /dev/null @@ -1,6 +0,0 @@ -[book] -authors = ["Jonathan Kelley"] -language = "en" -multilingual = false -src = "src" -title = "Fermi Guide" diff --git a/docs/fermi/src/SUMMARY.md b/docs/fermi/src/SUMMARY.md deleted file mode 100644 index 7390c8289..000000000 --- a/docs/fermi/src/SUMMARY.md +++ /dev/null @@ -1,3 +0,0 @@ -# Summary - -- [Chapter 1](./chapter_1.md) diff --git a/docs/fermi/src/chapter_1.md b/docs/fermi/src/chapter_1.md deleted file mode 100644 index b743fda35..000000000 --- a/docs/fermi/src/chapter_1.md +++ /dev/null @@ -1 +0,0 @@ -# Chapter 1 diff --git a/docs/guide/.gitignore b/docs/guide/.gitignore deleted file mode 100644 index 3006b271d..000000000 --- a/docs/guide/.gitignore +++ /dev/null @@ -1 +0,0 @@ -book/ diff --git a/docs/guide/Cargo.toml b/docs/guide/Cargo.toml deleted file mode 100644 index c2527b8b4..000000000 --- a/docs/guide/Cargo.toml +++ /dev/null @@ -1,27 +0,0 @@ -[package] -name = "dioxus-guide" -version = "0.0.1" -edition = "2021" -description = "Dioxus guide, including testable examples" -license = "MIT OR Apache-2.0" -publish = false - -[dev-dependencies] -dioxus = { path = "../../packages/dioxus" } -dioxus-desktop = { path = "../../packages/desktop" } -dioxus-web = { path = "../../packages/web" } -dioxus-ssr = { path = "../../packages/ssr" } -dioxus-native-core = { path = "../../packages/native-core" } -dioxus-native-core-macro = { path = "../../packages/native-core-macro" } -dioxus-router = { path = "../../packages/router" } -dioxus-liveview = { path = "../../packages/liveview", features = ["axum"] } -dioxus-tui = { path = "../../packages/dioxus-tui" } -dioxus-fullstack = { path = "../../packages/fullstack" } -# dioxus = { path = "../../packages/dioxus", features = ["desktop", "web", "ssr", "router", "fermi", "tui"] } -fermi = { path = "../../packages/fermi" } -shipyard = "0.6.2" -serde = { version = "1.0.138", features=["derive"] } -reqwest = { version = "0.11.11", features = ["json"] } -tokio = { version = "1.19.2", features = ["full"] } -axum = { version = "0.6.1", features = ["ws"] } -gloo-storage = "0.2.2" diff --git a/docs/guide/book.toml b/docs/guide/book.toml deleted file mode 100644 index 1f926256e..000000000 --- a/docs/guide/book.toml +++ /dev/null @@ -1,40 +0,0 @@ -[book.en] -title = "Dioxus Documentation" -description = "Get started with Dioxus, a portable, performant, and ergonomic framework for building cross-platform user interfaces in Rust" -authors = ["Jonathan Kelley"] -language = "en" - -[language.en] -name = "English" - -[language.pt-br] -name = "Português Brasileiro" -title = "Documentação do Dioxus" -description = "Introdução ao Dioxus, um framework portátil, de alto desempenho e ergonômico para criar interfaces de usuário multiplataforma em Rust." - -[rust] -edition = "2018" - -[output.html] -mathjax-support = true -site-url = "/mdBook/" -git-repository-url = "https://github.com/DioxusLabs/dioxus/edit/master/docs/guide" -edit-url-template = "https://github.com/DioxusLabs/dioxus/edit/master/docs/guide/{path}" - -[output.html.playground] -editable = true -line-numbers = true -# running examples will not work because dioxus is not a included in the playground -runnable = false - -[output.html.search] -limit-results = 20 -use-boolean-and = true -boost-title = 2 -boost-hierarchy = 2 -boost-paragraph = 1 -expand = true -heading-split-level = 2 - -# [output.html.redirect] -# "/format/config.html" = "configuration/index.html" diff --git a/docs/guide/examples/Readme.md b/docs/guide/examples/Readme.md deleted file mode 100644 index 891fc8fe4..000000000 --- a/docs/guide/examples/Readme.md +++ /dev/null @@ -1 +0,0 @@ -Some of these examples (e.g. web) cannot be run. The code samples are here mostly so that we can easily check that they compile using `cargo test`. \ No newline at end of file diff --git a/docs/guide/examples/anti_patterns.rs b/docs/guide/examples/anti_patterns.rs deleted file mode 100644 index 3911bfa0a..000000000 --- a/docs/guide/examples/anti_patterns.rs +++ /dev/null @@ -1,71 +0,0 @@ -#![allow(non_snake_case, unused)] - -//! This example shows what *not* to do - -use std::collections::HashMap; - -use dioxus::prelude::*; - -fn main() {} - -fn AntipatternNestedFragments(cx: Scope<()>) -> Element { - // ANCHOR: nested_fragments - // ❌ Don't unnecessarily nest fragments - let _ = cx.render(rsx!( - Fragment { - Fragment { - Fragment { - Fragment { - Fragment { - div { "Finally have a real node!" } - } - } - } - } - } - )); - - // ✅ Render shallow structures - cx.render(rsx!( - div { "Finally have a real node!" } - )) - // ANCHOR_END: nested_fragments -} - -#[derive(PartialEq, Props)] -struct NoKeysProps { - data: HashMap, -} - -fn AntipatternNoKeys(cx: Scope) -> Element { - // ANCHOR: iter_keys - let data: &HashMap<_, _> = &cx.props.data; - - // ❌ No keys - cx.render(rsx! { - ul { - data.values().map(|value| rsx!( - li { "List item: {value}" } - )) - } - }); - - // ❌ Using index as keys - cx.render(rsx! { - ul { - cx.props.data.values().enumerate().map(|(index, value)| rsx!( - li { key: "{index}", "List item: {value}" } - )) - } - }); - - // ✅ Using unique IDs as keys: - cx.render(rsx! { - ul { - cx.props.data.iter().map(|(key, value)| rsx!( - li { key: "{key}", "List item: {value}" } - )) - } - }) - // ANCHOR_END: iter_keys -} diff --git a/docs/guide/examples/boolean_attribute.rs b/docs/guide/examples/boolean_attribute.rs deleted file mode 100644 index 685103ccb..000000000 --- a/docs/guide/examples/boolean_attribute.rs +++ /dev/null @@ -1,18 +0,0 @@ -#![allow(non_snake_case)] -use dioxus::prelude::*; - -fn main() { - dioxus_desktop::launch(App); -} - -#[rustfmt::skip] -fn App(cx: Scope) -> Element { - // ANCHOR: boolean_attribute -cx.render(rsx! { - div { - hidden: "false", - "hello" - } -}) - // ANCHOR_END: boolean_attribute -} diff --git a/docs/guide/examples/component_borrowed_props.rs b/docs/guide/examples/component_borrowed_props.rs deleted file mode 100644 index ee78a1824..000000000 --- a/docs/guide/examples/component_borrowed_props.rs +++ /dev/null @@ -1,27 +0,0 @@ -#![allow(non_snake_case)] -use dioxus::prelude::*; - -fn main() { - dioxus_desktop::launch(App); -} - -// ANCHOR: App -fn App(cx: Scope) -> Element { - let hello = "Hello Dioxus!"; - - cx.render(rsx!(TitleCard { title: hello })) -} -// ANCHOR_END: App - -// ANCHOR: TitleCard -#[derive(Props)] -struct TitleCardProps<'a> { - title: &'a str, -} - -fn TitleCard<'a>(cx: Scope<'a, TitleCardProps<'a>>) -> Element { - cx.render(rsx! { - h1 { "{cx.props.title}" } - }) -} -// ANCHOR_END: TitleCard diff --git a/docs/guide/examples/component_children.rs b/docs/guide/examples/component_children.rs deleted file mode 100644 index d13a6480d..000000000 --- a/docs/guide/examples/component_children.rs +++ /dev/null @@ -1,36 +0,0 @@ -// ANCHOR: all -#![allow(non_snake_case)] -use dioxus::prelude::*; - -fn main() { - dioxus_desktop::launch(App); -} - -fn App(cx: Scope) -> Element { - // ANCHOR: Clickable_usage - cx.render(rsx! { - Clickable { - href: "https://www.youtube.com/watch?v=C-M2hs3sXGo", - "How to " i {"not"} " be seen" - } - }) - // ANCHOR_END: Clickable_usage -} - -// ANCHOR: Clickable -#[derive(Props)] -struct ClickableProps<'a> { - href: &'a str, - children: Element<'a>, -} - -fn Clickable<'a>(cx: Scope<'a, ClickableProps<'a>>) -> Element { - cx.render(rsx!( - a { - href: "{cx.props.href}", - class: "fancy-button", - &cx.props.children - } - )) -} -// ANCHOR_END: Clickable diff --git a/docs/guide/examples/component_children_inspect.rs b/docs/guide/examples/component_children_inspect.rs deleted file mode 100644 index a79b068a3..000000000 --- a/docs/guide/examples/component_children_inspect.rs +++ /dev/null @@ -1,37 +0,0 @@ -// ANCHOR: all -#![allow(non_snake_case, unused)] -use dioxus::prelude::*; - -fn main() { - dioxus_desktop::launch(App); -} - -fn App(cx: Scope) -> Element { - // ANCHOR: Clickable_usage - cx.render(rsx! { - Clickable { - href: "https://www.youtube.com/watch?v=C-M2hs3sXGo", - "How to " i {"not"} " be seen" - } - }) - // ANCHOR_END: Clickable_usage -} - -#[derive(Props)] -struct ClickableProps<'a> { - href: &'a str, - children: Element<'a>, -} - -// ANCHOR: Clickable -fn Clickable<'a>(cx: Scope<'a, ClickableProps<'a>>) -> Element { - match cx.props.children { - Some(VNode { dynamic_nodes, .. }) => { - todo!("render some stuff") - } - _ => { - todo!("render some other stuff") - } - } -} -// ANCHOR_END: Clickable diff --git a/docs/guide/examples/component_element_props.rs b/docs/guide/examples/component_element_props.rs deleted file mode 100644 index b8fe98879..000000000 --- a/docs/guide/examples/component_element_props.rs +++ /dev/null @@ -1,36 +0,0 @@ -// ANCHOR: all -#![allow(non_snake_case)] -use dioxus::prelude::*; - -fn main() { - dioxus_desktop::launch(App); -} - -fn App(cx: Scope) -> Element { - // ANCHOR: Clickable_usage - cx.render(rsx! { - Clickable { - href: "https://www.youtube.com/watch?v=C-M2hs3sXGo", - body: cx.render(rsx!("How to " i {"not"} " be seen")), - } - }) - // ANCHOR_END: Clickable_usage -} - -// ANCHOR: Clickable -#[derive(Props)] -struct ClickableProps<'a> { - href: &'a str, - body: Element<'a>, -} - -fn Clickable<'a>(cx: Scope<'a, ClickableProps<'a>>) -> Element { - cx.render(rsx!( - a { - href: "{cx.props.href}", - class: "fancy-button", - &cx.props.body - } - )) -} -// ANCHOR_END: Clickable diff --git a/docs/guide/examples/component_owned_props.rs b/docs/guide/examples/component_owned_props.rs deleted file mode 100644 index 3913f02c8..000000000 --- a/docs/guide/examples/component_owned_props.rs +++ /dev/null @@ -1,34 +0,0 @@ -#![allow(non_snake_case)] -use dioxus::prelude::*; - -fn main() { - dioxus_desktop::launch(App); -} - -// ANCHOR: App -fn App(cx: Scope) -> Element { - cx.render(rsx! { - Likes { - score: 42, - }, - }) -} -// ANCHOR_END: App - -// ANCHOR: Likes -// Remember: Owned props must implement `PartialEq`! -#[derive(PartialEq, Props)] -struct LikesProps { - score: i32, -} - -fn Likes(cx: Scope) -> Element { - cx.render(rsx! { - div { - "This post has ", - b { "{cx.props.score}" }, - " likes" - } - }) -} -// ANCHOR_END: Likes diff --git a/docs/guide/examples/component_props_options.rs b/docs/guide/examples/component_props_options.rs deleted file mode 100644 index df2ebf1db..000000000 --- a/docs/guide/examples/component_props_options.rs +++ /dev/null @@ -1,110 +0,0 @@ -#![allow(non_snake_case)] -use dioxus::prelude::*; - -fn main() { - dioxus_desktop::launch(App); -} - -#[rustfmt::skip] -fn App(cx: Scope) -> Element { - cx.render(rsx! { - // ANCHOR: OptionalProps_usage -Title { - title: "Some Title", -}, -Title { - title: "Some Title", - subtitle: "Some Subtitle", -}, -// Providing an Option explicitly won't compile though: -// Title { -// title: "Some Title", -// subtitle: None, -// }, - // ANCHOR_END: OptionalProps_usage - - // ANCHOR: ExplicitOption_usage -ExplicitOption { - title: "Some Title", - subtitle: None, -}, -ExplicitOption { - title: "Some Title", - subtitle: Some("Some Title"), -}, -// This won't compile: -// ExplicitOption { -// title: "Some Title", -// }, - // ANCHOR_END: ExplicitOption_usage - - // ANCHOR: DefaultComponent_usage -DefaultComponent { - number: 5, -}, -DefaultComponent {}, - // ANCHOR_END: DefaultComponent_usage - - // ANCHOR: IntoComponent_usage -IntoComponent { - string: "some &str", -}, - // ANCHOR_END: IntoComponent_usage - }) -} - -// ANCHOR: OptionalProps -#[derive(Props)] -struct OptionalProps<'a> { - title: &'a str, - subtitle: Option<&'a str>, -} - -fn Title<'a>(cx: Scope<'a, OptionalProps>) -> Element<'a> { - cx.render(rsx!(h1{ - "{cx.props.title}: ", - cx.props.subtitle.unwrap_or("No subtitle provided"), - })) -} -// ANCHOR_END: OptionalProps - -// ANCHOR: ExplicitOption -#[derive(Props)] -struct ExplicitOptionProps<'a> { - title: &'a str, - #[props(!optional)] - subtitle: Option<&'a str>, -} - -fn ExplicitOption<'a>(cx: Scope<'a, ExplicitOptionProps>) -> Element<'a> { - cx.render(rsx!(h1 { - "{cx.props.title}: ", - cx.props.subtitle.unwrap_or("No subtitle provided"), - })) -} -// ANCHOR_END: ExplicitOption - -// ANCHOR: DefaultComponent -#[derive(PartialEq, Props)] -struct DefaultProps { - // default to 42 when not provided - #[props(default = 42)] - number: i64, -} - -fn DefaultComponent(cx: Scope) -> Element { - cx.render(rsx!(h1 { "{cx.props.number}" })) -} -// ANCHOR_END: DefaultComponent - -// ANCHOR: IntoComponent -#[derive(PartialEq, Props)] -struct IntoProps { - #[props(into)] - string: String, -} - -fn IntoComponent(cx: Scope) -> Element { - cx.render(rsx!(h1 { "{cx.props.string}" })) -} -// ANCHOR_END: IntoComponent diff --git a/docs/guide/examples/components.rs b/docs/guide/examples/components.rs deleted file mode 100644 index 85020c79c..000000000 --- a/docs/guide/examples/components.rs +++ /dev/null @@ -1,24 +0,0 @@ -#![allow(non_snake_case)] -use dioxus::prelude::*; - -fn main() { - dioxus_desktop::launch(App); -} - -// ANCHOR: App -fn App(cx: Scope) -> Element { - cx.render(rsx! { - About {}, - About {}, - }) -} -// ANCHOR_END: App - -// ANCHOR: About -pub fn About(cx: Scope) -> Element { - cx.render(rsx!(p { - b {"Dioxus Labs"} - " An Open Source project dedicated to making Rust UI wonderful." - })) -} -// ANCHOR_END: About diff --git a/docs/guide/examples/conditional_rendering.rs b/docs/guide/examples/conditional_rendering.rs deleted file mode 100644 index c6095df98..000000000 --- a/docs/guide/examples/conditional_rendering.rs +++ /dev/null @@ -1,97 +0,0 @@ -#![allow(unused)] -#![allow(non_snake_case)] -use dioxus::prelude::*; - -fn main() { - dioxus_desktop::launch(App); -} - -pub fn App(cx: Scope) -> Element { - let is_logged_in = use_state(cx, || false); - - cx.render(rsx!(LogIn { - is_logged_in: **is_logged_in, - on_log_in: |_| is_logged_in.set(true), - on_log_out: |_| is_logged_in.set(false), - })) -} - -#[inline_props] -#[rustfmt::skip] -fn LogIn<'a>( - cx: Scope<'a>, - is_logged_in: bool, - on_log_in: EventHandler<'a>, - on_log_out: EventHandler<'a>, -) -> Element<'a> { - // ANCHOR: if_else -if *is_logged_in { - cx.render(rsx! { - "Welcome!" - button { - onclick: move |_| on_log_out.call(()), - "Log Out", - } - }) -} else { - cx.render(rsx! { - button { - onclick: move |_| on_log_in.call(()), - "Log In", - } - }) -} - // ANCHOR_END: if_else -} - -#[inline_props] -#[rustfmt::skip] -fn LogInImproved<'a>( - cx: Scope<'a>, - is_logged_in: bool, - on_log_in: EventHandler<'a>, - on_log_out: EventHandler<'a>, -) -> Element<'a> { - // ANCHOR: if_else_improved -cx.render(rsx! { - // We only render the welcome message if we are logged in - // You can use if statements in the middle of a render block to conditionally render elements - if *is_logged_in { - // Notice the body of this if statment is rsx code, not an expression - "Welcome!" - } - button { - // depending on the value of `is_logged_in`, we will call a different event handler - onclick: move |_| if *is_logged_in { - on_log_in.call(()) - } - else{ - on_log_out.call(()) - }, - if *is_logged_in { - // if we are logged in, the button should say "Log Out" - "Log Out" - } else { - // if we are not logged in, the button should say "Log In" - "Log In" - } - } -}) - // ANCHOR_END: if_else_improved -} - -#[inline_props] -#[rustfmt::skip] -fn LogInWarning(cx: Scope, is_logged_in: bool) -> Element { - // ANCHOR: conditional_none -if *is_logged_in { - return None; -} - -cx.render(rsx! { - a { - "You must be logged in to comment" - } -}) - // ANCHOR_END: conditional_none -} diff --git a/docs/guide/examples/custom_renderer.rs b/docs/guide/examples/custom_renderer.rs deleted file mode 100644 index 13993fe7b..000000000 --- a/docs/guide/examples/custom_renderer.rs +++ /dev/null @@ -1,311 +0,0 @@ -use dioxus::html::input_data::keyboard_types::{Code, Key, Modifiers}; -use dioxus::prelude::*; -use dioxus_native_core::exports::shipyard::Component; -use dioxus_native_core::node_ref::*; -use dioxus_native_core::prelude::*; -use dioxus_native_core::utils::cursor::{Cursor, Pos}; -use dioxus_native_core_macro::partial_derive_state; - -// ANCHOR: state_impl -struct FontSize(f64); - -// All states need to derive Component -#[derive(Default, Debug, Copy, Clone, Component)] -struct Size(f64, f64); - -/// Derive some of the boilerplate for the State implementation -#[partial_derive_state] -impl State for Size { - type ParentDependencies = (); - - // The size of the current node depends on the size of its children - type ChildDependencies = (Self,); - - type NodeDependencies = (); - - // Size only cares about the width, height, and text parts of the current node - const NODE_MASK: NodeMaskBuilder<'static> = NodeMaskBuilder::new() - // Get access to the width and height attributes - .with_attrs(AttributeMaskBuilder::Some(&["width", "height"])) - // Get access to the text of the node - .with_text(); - - fn update<'a>( - &mut self, - node_view: NodeView<()>, - _node: ::ElementBorrowed<'a>, - _parent: Option<::ElementBorrowed<'a>>, - children: Vec<::ElementBorrowed<'a>>, - context: &SendAnyMap, - ) -> bool { - let font_size = context.get::().unwrap().0; - let mut width; - let mut height; - if let Some(text) = node_view.text() { - // if the node has text, use the text to size our object - width = text.len() as f64 * font_size; - height = font_size; - } else { - // otherwise, the size is the maximum size of the children - width = children - .iter() - .map(|(item,)| item.0) - .reduce(|accum, item| if accum >= item { accum } else { item }) - .unwrap_or(0.0); - - height = children - .iter() - .map(|(item,)| item.1) - .reduce(|accum, item| if accum >= item { accum } else { item }) - .unwrap_or(0.0); - } - // if the node contains a width or height attribute it overrides the other size - for a in node_view.attributes().into_iter().flatten() { - match &*a.attribute.name { - "width" => width = a.value.as_float().unwrap(), - "height" => height = a.value.as_float().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, Component)] -struct TextColor { - r: u8, - g: u8, - b: u8, -} - -#[partial_derive_state] -impl State for TextColor { - // TextColor depends on the TextColor part of the parent - type ParentDependencies = (Self,); - - type ChildDependencies = (); - - type NodeDependencies = (); - - // TextColor only cares about the color attribute of the current node - const NODE_MASK: NodeMaskBuilder<'static> = - // Get access to the color attribute - NodeMaskBuilder::new().with_attrs(AttributeMaskBuilder::Some(&["color"])); - - fn update<'a>( - &mut self, - node_view: NodeView<()>, - _node: ::ElementBorrowed<'a>, - parent: Option<::ElementBorrowed<'a>>, - _children: Vec<::ElementBorrowed<'a>>, - _context: &SendAnyMap, - ) -> bool { - // TextColor only depends on the color tag, so getting the first tag is equivilent to looking through all tags - let new = match node_view - .attributes() - .and_then(|mut attrs| attrs.next()) - .and_then(|attr| attr.value.as_text()) - { - // 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(color) => panic!("unknown color {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, Copy, PartialEq, Default, Component)] -struct Border(bool); - -#[partial_derive_state] -impl State for Border { - // TextColor depends on the TextColor part of the parent - type ParentDependencies = (Self,); - - type ChildDependencies = (); - - type NodeDependencies = (); - - // Border does not depended on any other member in the current node - const NODE_MASK: NodeMaskBuilder<'static> = - // Get access to the border attribute - NodeMaskBuilder::new().with_attrs(AttributeMaskBuilder::Some(&["border"])); - - fn update<'a>( - &mut self, - node_view: NodeView<()>, - _node: ::ElementBorrowed<'a>, - _parent: Option<::ElementBorrowed<'a>>, - _children: Vec<::ElementBorrowed<'a>>, - _context: &SendAnyMap, - ) -> bool { - // check if the node contians a border attribute - let new = Self( - node_view - .attributes() - .and_then(|mut attrs| attrs.next().map(|a| a.attribute.name == "border")) - .is_some(), - ); - // check if the member has changed - let changed = new != *self; - *self = new; - changed - } -} -// ANCHOR_END: state_impl - -// ANCHOR: rendering -fn main() -> Result<(), Box> { - fn app(cx: Scope) -> Element { - let count = use_state(cx, || 0); - - use_future(cx, (count,), |(count,)| async move { - loop { - tokio::time::sleep(std::time::Duration::from_secs(1)).await; - count.set(*count + 1); - } - }); - - cx.render(rsx! { - div{ - color: "red", - "{count}" - } - }) - } - - // create the vdom, the real_dom, and the binding layer between them - let mut vdom = VirtualDom::new(app); - let mut rdom: RealDom = RealDom::new([ - Border::to_type_erased(), - TextColor::to_type_erased(), - Size::to_type_erased(), - ]); - let mut dioxus_intigration_state = DioxusState::create(&mut rdom); - - let mutations = vdom.rebuild(); - // update the structure of the real_dom tree - dioxus_intigration_state.apply_mutations(&mut rdom, mutations); - let mut ctx = SendAnyMap::new(); - // set the font size to 3.3 - ctx.insert(FontSize(3.3)); - // update the State for nodes in the real_dom tree - let _to_rerender = rdom.update_state(ctx); - - // we need to run the vdom in a async runtime - tokio::runtime::Builder::new_current_thread() - .enable_all() - .build()? - .block_on(async { - loop { - // wait for the vdom to update - vdom.wait_for_work().await; - - // get the mutations from the vdom - let mutations = vdom.render_immediate(); - - // update the structure of the real_dom tree - dioxus_intigration_state.apply_mutations(&mut rdom, mutations); - - // update the state of the real_dom tree - let mut ctx = SendAnyMap::new(); - // set the font size to 3.3 - ctx.insert(FontSize(3.3)); - let _to_rerender = rdom.update_state(ctx); - - // render... - rdom.traverse_depth_first(|node| { - let indent = " ".repeat(node.height() as usize); - let color = *node.get::().unwrap(); - let size = *node.get::().unwrap(); - let border = *node.get::().unwrap(); - let id = node.id(); - let node = node.node_type(); - let node_type = &*node; - println!("{indent}{id:?} {color:?} {size:?} {border:?} {node_type:?}"); - }); - } - }) -} -// ANCHOR_END: rendering - -// ANCHOR: derive_state -// All states must derive Component (https://docs.rs/shipyard/latest/shipyard/derive.Component.html) -// They also must implement Default or provide a custom implementation of create in the State trait -#[derive(Default, Component)] -struct MyState; - -/// Derive some of the boilerplate for the State implementation -#[partial_derive_state] -impl State for MyState { - // The states of the parent nodes this state depends on - type ParentDependencies = (); - - // The states of the child nodes this state depends on - type ChildDependencies = (Self,); - - // The states of the current node this state depends on - type NodeDependencies = (); - - // The parts of the current text, element, or placeholder node in the tree that this state depends on - const NODE_MASK: NodeMaskBuilder<'static> = NodeMaskBuilder::new(); - - // How to update the state of the current node based on the state of the parent nodes, child nodes, and the current node - // Returns true if the node was updated and false if the node was not updated - fn update<'a>( - &mut self, - // The view of the current node limited to the parts this state depends on - _node_view: NodeView<()>, - // The state of the current node that this state depends on - _node: ::ElementBorrowed<'a>, - // The state of the parent nodes that this state depends on - _parent: Option<::ElementBorrowed<'a>>, - // The state of the child nodes that this state depends on - _children: Vec<::ElementBorrowed<'a>>, - // The context of the current node used to pass global state into the tree - _context: &SendAnyMap, - ) -> bool { - todo!() - } - - // partial_derive_state will generate a default implementation of all the other methods -} -// ANCHOR_END: derive_state - -#[allow(unused)] -// ANCHOR: cursor -fn text_editing() { - let mut cursor = Cursor::default(); - let mut text = String::new(); - - // handle keyboard input with a max text length of 10 - cursor.handle_input( - &Code::ArrowRight, - &Key::ArrowRight, - &Modifiers::empty(), - &mut text, - 10, - ); - - // mannually select text between characters 0-5 on the first line (this could be from dragging with a mouse) - cursor.start = Pos::new(0, 0); - cursor.end = Some(Pos::new(5, 0)); - - // delete the selected text and move the cursor to the start of the selection - cursor.delete_selection(&mut text); -} -// ANCHOR_END: cursor diff --git a/docs/guide/examples/dangerous_inner_html.rs b/docs/guide/examples/dangerous_inner_html.rs deleted file mode 100644 index fe8a52663..000000000 --- a/docs/guide/examples/dangerous_inner_html.rs +++ /dev/null @@ -1,20 +0,0 @@ -#![allow(non_snake_case)] -use dioxus::prelude::*; - -fn main() { - dioxus_desktop::launch(App); -} - -#[rustfmt::skip] -fn App(cx: Scope) -> Element { - // ANCHOR: dangerous_inner_html -// this should come from a trusted source -let contents = "live dangerously"; - -cx.render(rsx! { - div { - dangerous_inner_html: "{contents}", - } -}) - // ANCHOR_END: dangerous_inner_html -} diff --git a/docs/guide/examples/event_click.rs b/docs/guide/examples/event_click.rs deleted file mode 100644 index bd25c5f36..000000000 --- a/docs/guide/examples/event_click.rs +++ /dev/null @@ -1,18 +0,0 @@ -#![allow(non_snake_case)] -use dioxus::prelude::*; - -fn main() { - dioxus_desktop::launch(App); -} - -#[rustfmt::skip] -fn App(cx: Scope) -> Element { - // ANCHOR: rsx -cx.render(rsx! { - button { - onclick: move |event| println!("Clicked! Event: {event:?}"), - "click me!" - } -}) - // ANCHOR_END: rsx -} diff --git a/docs/guide/examples/event_handler_prop.rs b/docs/guide/examples/event_handler_prop.rs deleted file mode 100644 index 0ef70c841..000000000 --- a/docs/guide/examples/event_handler_prop.rs +++ /dev/null @@ -1,32 +0,0 @@ -#![allow(non_snake_case)] - -use dioxus::prelude::*; - -fn main() { - dioxus_desktop::launch(App); -} - -fn App(cx: Scope) -> Element { - // ANCHOR: usage - cx.render(rsx! { - FancyButton { - on_click: move |event| println!("Clicked! {event:?}") - } - }) - // ANCHOR_END: usage -} - -// ANCHOR: component_with_handler -#[derive(Props)] -pub struct FancyButtonProps<'a> { - on_click: EventHandler<'a, MouseEvent>, -} - -pub fn FancyButton<'a>(cx: Scope<'a, FancyButtonProps<'a>>) -> Element<'a> { - cx.render(rsx!(button { - class: "fancy-button", - onclick: move |evt| cx.props.on_click.call(evt), - "click me pls." - })) -} -// ANCHOR_END: component_with_handler diff --git a/docs/guide/examples/event_nested.rs b/docs/guide/examples/event_nested.rs deleted file mode 100644 index b31e340f1..000000000 --- a/docs/guide/examples/event_nested.rs +++ /dev/null @@ -1,25 +0,0 @@ -#![allow(non_snake_case)] -use dioxus::prelude::*; - -fn main() { - dioxus_desktop::launch(App); -} - -#[rustfmt::skip] -fn App(cx: Scope) -> Element { - // ANCHOR: rsx -cx.render(rsx! { - div { - onclick: move |_event| {}, - "outer", - button { - onclick: move |event| { - // now, outer won't be triggered - event.stop_propagation(); - }, - "inner" - } - } -}) - // ANCHOR_END: rsx -} diff --git a/docs/guide/examples/event_prevent_default.rs b/docs/guide/examples/event_prevent_default.rs deleted file mode 100644 index 32443d017..000000000 --- a/docs/guide/examples/event_prevent_default.rs +++ /dev/null @@ -1,17 +0,0 @@ -#![allow(non_snake_case)] -use dioxus::prelude::*; - -fn main() { - dioxus_desktop::launch(App); -} - -#[rustfmt::skip] -fn App(cx: Scope) -> Element { - // ANCHOR: prevent_default -cx.render(rsx! { - input { - prevent_default: "oninput onclick", - } -}) - // ANCHOR_END: prevent_default -} diff --git a/docs/guide/examples/hello_world_desktop.rs b/docs/guide/examples/hello_world_desktop.rs deleted file mode 100644 index 9d5a02051..000000000 --- a/docs/guide/examples/hello_world_desktop.rs +++ /dev/null @@ -1,21 +0,0 @@ -// ANCHOR: all -#![allow(non_snake_case)] -// import the prelude to get access to the `rsx!` macro and the `Scope` and `Element` types -use dioxus::prelude::*; - -fn main() { - // launch the dioxus app in a webview - dioxus_desktop::launch(App); -} - -// ANCHOR: component -// define a component that renders a div with the text "Hello, world!" -fn App(cx: Scope) -> Element { - cx.render(rsx! { - div { - "Hello, world!" - } - }) -} -// ANCHOR_END: component -// ANCHOR_END: all diff --git a/docs/guide/examples/hello_world_liveview.rs b/docs/guide/examples/hello_world_liveview.rs deleted file mode 100644 index c88dc2f53..000000000 --- a/docs/guide/examples/hello_world_liveview.rs +++ /dev/null @@ -1,60 +0,0 @@ -// ANCHOR: all -use axum::{extract::ws::WebSocketUpgrade, response::Html, routing::get, Router}; -use dioxus::prelude::*; - -// ANCHOR: glue -#[tokio::main] -async fn main() { - let addr: std::net::SocketAddr = ([127, 0, 0, 1], 3030).into(); - - let view = dioxus_liveview::LiveViewPool::new(); - - let app = Router::new() - // The root route contains the glue code to connect to the WebSocket - .route( - "/", - get(move || async move { - Html(format!( - r#" - - - Dioxus LiveView with Axum -
- {glue} - - "#, - // Create the glue code to connect to the WebSocket on the "/ws" route - glue = dioxus_liveview::interpreter_glue(&format!("ws://{addr}/ws")) - )) - }), - ) - // The WebSocket route is what Dioxus uses to communicate with the browser - .route( - "/ws", - get(move |ws: WebSocketUpgrade| async move { - ws.on_upgrade(move |socket| async move { - // When the WebSocket is upgraded, launch the LiveView with the app component - _ = view.launch(dioxus_liveview::axum_socket(socket), app).await; - }) - }), - ); - - println!("Listening on http://{addr}"); - - axum::Server::bind(&addr.to_string().parse().unwrap()) - .serve(app.into_make_service()) - .await - .unwrap(); -} -// ANCHOR_END: glue - -// ANCHOR: app -fn app(cx: Scope) -> Element { - cx.render(rsx! { - div { - "Hello, world!" - } - }) -} -// ANCHOR_END: app -// ANCHOR_END: all diff --git a/docs/guide/examples/hello_world_ssr.rs b/docs/guide/examples/hello_world_ssr.rs deleted file mode 100644 index 0f8db0b46..000000000 --- a/docs/guide/examples/hello_world_ssr.rs +++ /dev/null @@ -1,63 +0,0 @@ -#![allow(unused)] -#![allow(non_snake_case)] -// ANCHOR: all - -// ANCHOR: main -#![allow(non_snake_case)] -use axum::{response::Html, routing::get, Router}; -// import the prelude to get access to the `rsx!` macro and the `Scope` and `Element` types -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(); -} - -// ANCHOR_END: main - -// ANCHOR: endpoint -async fn app_endpoint() -> Html { - // render the rsx! macro to HTML - Html(dioxus_ssr::render_lazy(rsx! { - div { "hello world!" } - })) -} -// ANCHOR_END: endpoint - -// ANCHOR: second_endpoint -async fn second_app_endpoint() -> Html { - // create a component that renders a div with the text "hello world" - fn app(cx: Scope) -> Element { - cx.render(rsx!(div { "hello world" })) - } - // create a VirtualDom with the app component - let mut app = VirtualDom::new(app); - // rebuild the VirtualDom before rendering - let _ = app.rebuild(); - - // render the VirtualDom to HTML - Html(dioxus_ssr::render(&app)) -} -// ANCHOR_END: second_endpoint - -// ANCHOR: component -// define a component that renders a div with the text "Hello, world!" -fn App(cx: Scope) -> Element { - cx.render(rsx! { - div { - "Hello, world!" - } - }) -} -// ANCHOR_END: component -// ANCHOR_END: all diff --git a/docs/guide/examples/hello_world_tui.rs b/docs/guide/examples/hello_world_tui.rs deleted file mode 100644 index dc4f0ee71..000000000 --- a/docs/guide/examples/hello_world_tui.rs +++ /dev/null @@ -1,17 +0,0 @@ -#![allow(non_snake_case)] -// import the prelude to get access to the `rsx!` macro and the `Scope` and `Element` types -use dioxus::prelude::*; - -fn main() { - // launch the app in the terminal - dioxus_tui::launch(App); -} - -// create a component that renders a div with the text "Hello, world!" -fn App(cx: Scope) -> Element { - cx.render(rsx! { - div { - "Hello, world!" - } - }) -} diff --git a/docs/guide/examples/hello_world_tui_no_ctrl_c.rs b/docs/guide/examples/hello_world_tui_no_ctrl_c.rs deleted file mode 100644 index 6afa21e6c..000000000 --- a/docs/guide/examples/hello_world_tui_no_ctrl_c.rs +++ /dev/null @@ -1,36 +0,0 @@ -// todo remove deprecated -#![allow(non_snake_case, deprecated)] - -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.key_code { - tui_ctx.quit(); - }, - - "Hello world!" - } - }) -} diff --git a/docs/guide/examples/hello_world_web.rs b/docs/guide/examples/hello_world_web.rs deleted file mode 100644 index 7b013bc3d..000000000 --- a/docs/guide/examples/hello_world_web.rs +++ /dev/null @@ -1,17 +0,0 @@ -#![allow(non_snake_case)] -// import the prelude to get access to the `rsx!` macro and the `Scope` and `Element` types -use dioxus::prelude::*; - -fn main() { - // launch the web app - dioxus_web::launch(App); -} - -// create a component that renders a div with the text "Hello, world!" -fn App(cx: Scope) -> Element { - cx.render(rsx! { - div { - "Hello, world!" - } - }) -} diff --git a/docs/guide/examples/hooks_anti_patterns.rs b/docs/guide/examples/hooks_anti_patterns.rs deleted file mode 100644 index 2119b8601..000000000 --- a/docs/guide/examples/hooks_anti_patterns.rs +++ /dev/null @@ -1,38 +0,0 @@ -#![allow(unused)] - -use dioxus::prelude::*; - -fn main() {} - -// ANCHOR: non_clone_state -use std::cell::RefCell; -use std::rc::Rc; -use std::sync::Arc; - -struct UseState<'a, T> { - value: &'a RefCell, - update: Arc, -} - -fn my_use_state(cx: &ScopeState, init: impl FnOnce() -> T) -> UseState { - // The update function will trigger a re-render in the component cx is attached to - let update = cx.schedule_update(); - // Create the initial state - let value = cx.use_hook(|| RefCell::new(init())); - - UseState { value, update } -} - -impl UseState<'_, T> { - fn get(&self) -> T { - self.value.borrow().clone() - } - - fn set(&self, value: T) { - // Update the state - *self.value.borrow_mut() = value; - // Trigger a re-render on the component the state is from - (self.update)(); - } -} -// ANCHOR_END: non_clone_state diff --git a/docs/guide/examples/hooks_bad.rs b/docs/guide/examples/hooks_bad.rs deleted file mode 100644 index cbaa54e90..000000000 --- a/docs/guide/examples/hooks_bad.rs +++ /dev/null @@ -1,68 +0,0 @@ -#![allow(non_snake_case)] - -use dioxus::prelude::*; -use std::collections::HashMap; - -fn main() { - dioxus_desktop::launch(App); -} - -#[rustfmt::skip] -fn App(cx: Scope) -> Element { - let you_are_happy = true; - let you_know_it = false; - - // ANCHOR: conditional -// ❌ don't call hooks in conditionals! -// We must ensure that the same hooks will be called every time -// But `if` statements only run if the conditional is true! -// So we might violate rule 2. -if you_are_happy && you_know_it { - let something = use_state(cx, || "hands"); - println!("clap your {something}") -} - -// ✅ instead, *always* call use_state -// You can put other stuff in the conditional though -let something = use_state(cx, || "hands"); -if you_are_happy && you_know_it { - println!("clap your {something}") -} - // ANCHOR_END: conditional - - // ANCHOR: closure -// ❌ don't call hooks inside closures! -// We can't guarantee that the closure, if used, will be called in the same order every time -let _a = || { - let b = use_state(cx, || 0); - b.get() -}; - -// ✅ instead, move hook `b` outside -let b = use_state(cx, || 0); -let _a = || b.get(); - // ANCHOR_END: closure - - let names: Vec<&str> = vec![]; - - // ANCHOR: loop -// `names` is a Vec<&str> - -// ❌ Do not use hooks in loops! -// In this case, if the length of the Vec changes, we break rule 2 -for _name in &names { - let is_selected = use_state(cx, || false); - println!("selected: {is_selected}"); -} - -// ✅ Instead, use a hashmap with use_ref -let selection_map = use_ref(cx, HashMap::<&str, bool>::new); - -for name in &names { - let is_selected = selection_map.read()[name]; - println!("selected: {is_selected}"); -} - // ANCHOR_END: loop - - cx.render(rsx!(())) -} diff --git a/docs/guide/examples/hooks_composed.rs b/docs/guide/examples/hooks_composed.rs deleted file mode 100644 index 782a19d7d..000000000 --- a/docs/guide/examples/hooks_composed.rs +++ /dev/null @@ -1,67 +0,0 @@ -#![allow(unused)] - -use dioxus::prelude::*; - -fn main() {} - -struct AppSettings {} - -// ANCHOR: wrap_context -fn use_settings(cx: &ScopeState) -> &UseSharedState { - use_shared_state::(cx).expect("App settings not provided") -} -// ANCHOR_END: wrap_context - -// ANCHOR: use_storage -use gloo_storage::{LocalStorage, Storage}; -use serde::{de::DeserializeOwned, Serialize}; - -/// A persistent storage hook that can be used to store data across application reloads. -#[allow(clippy::needless_return)] -pub fn use_persistent( - cx: &ScopeState, - // A unique key for the storage entry - key: impl ToString, - // A function that returns the initial value if the storage entry is empty - init: impl FnOnce() -> T, -) -> &UsePersistent { - // Use the use_ref hook to create a mutable state for the storage entry - let state = use_ref(cx, move || { - // This closure will run when the hook is created - let key = key.to_string(); - let value = LocalStorage::get(key.as_str()).ok().unwrap_or_else(init); - StorageEntry { key, value } - }); - - // Wrap the state in a new struct with a custom API - // Note: We use use_hook here so that this hook is easier to use in closures in the rsx. Any values with the same lifetime as the ScopeState can be used in the closure without cloning. - cx.use_hook(|| UsePersistent { - inner: state.clone(), - }) -} - -struct StorageEntry { - key: String, - value: T, -} - -/// Storage that persists across application reloads -pub struct UsePersistent { - inner: UseRef>, -} - -impl UsePersistent { - /// Returns a reference to the value - pub fn get(&self) -> T { - self.inner.read().value.clone() - } - - /// Sets the value - pub fn set(&self, value: T) { - let mut inner = self.inner.write(); - // Write the new value to local storage - LocalStorage::set(inner.key.as_str(), &value); - inner.value = value; - } -} -// ANCHOR_END: use_storage diff --git a/docs/guide/examples/hooks_counter.rs b/docs/guide/examples/hooks_counter.rs deleted file mode 100644 index 86705f4af..000000000 --- a/docs/guide/examples/hooks_counter.rs +++ /dev/null @@ -1,31 +0,0 @@ -#![allow(non_snake_case)] -use dioxus::prelude::*; - -fn main() { - dioxus_desktop::launch(App); -} - -// ANCHOR: component -fn App(cx: Scope) -> Element { - // count will be initialized to 0 the first time the component is rendered - let mut count = use_state(cx, || 0); - - cx.render(rsx!( - h1 { "High-Five counter: {count}" } - button { - onclick: move |_| { - // changing the count will cause the component to re-render - count += 1 - }, - "Up high!" - } - button { - onclick: move |_| { - // changing the count will cause the component to re-render - count -= 1 - }, - "Down low!" - } - )) -} -// ANCHOR_END: component diff --git a/docs/guide/examples/hooks_counter_two_state.rs b/docs/guide/examples/hooks_counter_two_state.rs deleted file mode 100644 index b2a8f6e77..000000000 --- a/docs/guide/examples/hooks_counter_two_state.rs +++ /dev/null @@ -1,24 +0,0 @@ -#![allow(non_snake_case)] -use dioxus::prelude::*; - -fn main() { - dioxus_desktop::launch(App); -} - -// ANCHOR: component -fn App(cx: Scope) -> Element { - // ANCHOR: use_state_calls - let mut count_a = use_state(cx, || 0); - let mut count_b = use_state(cx, || 0); - // ANCHOR_END: use_state_calls - - cx.render(rsx!( - h1 { "Counter_a: {count_a}" } - button { onclick: move |_| count_a += 1, "a++" } - button { onclick: move |_| count_a -= 1, "a--" } - h1 { "Counter_b: {count_b}" } - button { onclick: move |_| count_b += 1, "b++" } - button { onclick: move |_| count_b -= 1, "b--" } - )) -} -// ANCHOR_END: component diff --git a/docs/guide/examples/hooks_custom_logic.rs b/docs/guide/examples/hooks_custom_logic.rs deleted file mode 100644 index 2323ddb11..000000000 --- a/docs/guide/examples/hooks_custom_logic.rs +++ /dev/null @@ -1,57 +0,0 @@ -#![allow(unused)] - -use dioxus::prelude::*; - -fn main() {} - -// ANCHOR: use_state -use std::cell::RefCell; -use std::rc::Rc; -use std::sync::Arc; - -#[derive(Clone)] -struct UseState { - value: Rc>, - update: Arc, -} - -fn my_use_state(cx: &ScopeState, init: impl FnOnce() -> T) -> &UseState { - cx.use_hook(|| { - // The update function will trigger a re-render in the component cx is attached to - let update = cx.schedule_update(); - // Create the initial state - let value = Rc::new(RefCell::new(init())); - - UseState { value, update } - }) -} - -impl UseState { - fn get(&self) -> T { - self.value.borrow().clone() - } - - fn set(&self, value: T) { - // Update the state - *self.value.borrow_mut() = value; - // Trigger a re-render on the component the state is from - (self.update)(); - } -} -// ANCHOR_END: use_state - -// ANCHOR: use_context -pub fn use_context(cx: &ScopeState) -> Option<&T> { - cx.use_hook(|| cx.consume_context::()).as_ref() -} - -pub fn use_context_provider(cx: &ScopeState, f: impl FnOnce() -> T) -> &T { - cx.use_hook(|| { - let val = f(); - // Provide the context state to the scope - cx.provide_context(val.clone()); - val - }) -} - -// ANCHOR_END: use_context diff --git a/docs/guide/examples/hooks_use_ref.rs b/docs/guide/examples/hooks_use_ref.rs deleted file mode 100644 index 00794fbb7..000000000 --- a/docs/guide/examples/hooks_use_ref.rs +++ /dev/null @@ -1,22 +0,0 @@ -#![allow(non_snake_case)] -use dioxus::prelude::*; - -fn main() { - dioxus_desktop::launch(App); -} - -// ANCHOR: component -fn App(cx: Scope) -> Element { - let list = use_ref(cx, Vec::new); - - cx.render(rsx!( - p { "Current list: {list.read():?}" } - button { - onclick: move |event| { - list.with_mut(|list| list.push(event)); - }, - "Click me!" - } - )) -} -// ANCHOR_END: component diff --git a/docs/guide/examples/hydration.rs b/docs/guide/examples/hydration.rs deleted file mode 100644 index 31574edce..000000000 --- a/docs/guide/examples/hydration.rs +++ /dev/null @@ -1,34 +0,0 @@ -#![allow(non_snake_case, unused)] -use dioxus::prelude::*; - -fn main() { - #[cfg(feature = "web")] - dioxus_web::launch_cfg(app, dioxus_web::Config::new().hydrate(true)); - #[cfg(feature = "ssr")] - { - use dioxus_fullstack::prelude::*; - tokio::runtime::Runtime::new() - .unwrap() - .block_on(async move { - let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 8080)); - axum::Server::bind(&addr) - .serve( - axum::Router::new() - .serve_dioxus_application("", ServeConfigBuilder::new(app, ())) - .into_make_service(), - ) - .await - .unwrap(); - }); - } -} - -fn app(cx: Scope) -> Element { - let mut count = use_state(cx, || 0); - - cx.render(rsx! { - h1 { "High-Five counter: {count}" } - button { onclick: move |_| count += 1, "Up high!" } - button { onclick: move |_| count -= 1, "Down low!" } - }) -} diff --git a/docs/guide/examples/hydration_props.rs b/docs/guide/examples/hydration_props.rs deleted file mode 100644 index 4e6bb1752..000000000 --- a/docs/guide/examples/hydration_props.rs +++ /dev/null @@ -1,74 +0,0 @@ -#![allow(non_snake_case, unused)] -use dioxus::prelude::*; -use dioxus_fullstack::prelude::*; - -fn main() { - #[cfg(feature = "web")] - dioxus_web::launch_with_props( - app, - // Get the root props from the document - get_root_props_from_document().unwrap_or_default(), - dioxus_web::Config::new().hydrate(true), - ); - #[cfg(feature = "ssr")] - { - use axum::extract::Path; - use axum::extract::State; - use axum::routing::get; - tokio::runtime::Runtime::new() - .unwrap() - .block_on(async move { - let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 8080)); - axum::Server::bind(&addr) - .serve( - axum::Router::new() - // Serve the dist folder with the static javascript and WASM files created by the dixous CLI - .serve_static_assets("./dist") - // Register server functions - .register_server_fns("") - // Connect to the hot reload server in debug mode - .connect_hot_reload() - // Render the application. This will serialize the root props (the intial count) into the HTML - .route( - "/", - get(move | State(ssr_state): State| async move { axum::body::Full::from( - ssr_state.render( - &ServeConfigBuilder::new( - app, - 0, - ) - .build(), - ) - )}), - ) - // Render the application with a different intial count - .route( - "/:initial_count", - get(move |Path(intial_count): Path, State(ssr_state): State| async move { axum::body::Full::from( - ssr_state.render( - &ServeConfigBuilder::new( - app, - intial_count, - ) - .build(), - ) - )}), - ) - .with_state(SSRState::default()) - .into_make_service(), - ) - .await - .unwrap(); - }); - } -} - -fn app(cx: Scope) -> Element { - let mut count = use_state(cx, || *cx.props); - - cx.render(rsx! { - h1 { "High-Five counter: {count}" } - button { onclick: move |_| count += 1, "Up high!" } - button { onclick: move |_| count -= 1, "Down low!" } - }) -} diff --git a/docs/guide/examples/input_controlled.rs b/docs/guide/examples/input_controlled.rs deleted file mode 100644 index bf92072a3..000000000 --- a/docs/guide/examples/input_controlled.rs +++ /dev/null @@ -1,21 +0,0 @@ -#![allow(non_snake_case)] -use dioxus::prelude::*; - -fn main() { - dioxus_desktop::launch(App); -} - -// ANCHOR: component -fn App(cx: Scope) -> Element { - let name = use_state(cx, || "bob".to_string()); - - cx.render(rsx! { - input { - // we tell the component what to render - value: "{name}", - // and what to do when the value changes - oninput: move |evt| name.set(evt.value.clone()), - } - }) -} -// ANCHOR_END: component diff --git a/docs/guide/examples/input_uncontrolled.rs b/docs/guide/examples/input_uncontrolled.rs deleted file mode 100644 index 5adc4aaad..000000000 --- a/docs/guide/examples/input_uncontrolled.rs +++ /dev/null @@ -1,22 +0,0 @@ -#![allow(non_snake_case)] -use dioxus::prelude::*; - -fn main() { - dioxus_desktop::launch(App); -} - -// ANCHOR: component -fn App(cx: Scope) -> Element { - cx.render(rsx! { - form { - onsubmit: move |event| { - println!("Submitted! {event:?}") - }, - input { name: "name", }, - input { name: "age", }, - input { name: "date", }, - input { r#type: "submit", }, - } - }) -} -// ANCHOR_END: component diff --git a/docs/guide/examples/meme_editor.rs b/docs/guide/examples/meme_editor.rs deleted file mode 100644 index c5a473da9..000000000 --- a/docs/guide/examples/meme_editor.rs +++ /dev/null @@ -1,104 +0,0 @@ -// ANCHOR: all -#![allow(non_snake_case)] - -use dioxus::prelude::*; - -fn main() { - dioxus_desktop::launch(MemeEditor); -} - -// ANCHOR: meme_editor -fn MemeEditor(cx: Scope) -> Element { - let container_style = r" - display: flex; - flex-direction: column; - gap: 16px; - margin: 0 auto; - width: fit-content; - "; - - let caption = use_state(cx, || "me waiting for my rust code to compile".to_string()); - - cx.render(rsx! { - div { - style: "{container_style}", - h1 { "Meme Editor" }, - Meme { - caption: caption, - }, - CaptionEditor { - caption: caption, - on_input: move |event: FormEvent| {caption.set(event.value.clone());}, - }, - } - }) -} -// ANCHOR_END: meme_editor - -// ANCHOR: meme_component -#[inline_props] -fn Meme<'a>(cx: Scope<'a>, caption: &'a str) -> Element<'a> { - let container_style = r#" - position: relative; - width: fit-content; - "#; - - let caption_container_style = r#" - position: absolute; - bottom: 0; - left: 0; - right: 0; - padding: 16px 8px; - "#; - - let caption_style = r" - font-size: 32px; - margin: 0; - color: white; - text-align: center; - "; - - cx.render(rsx!( - div { - style: "{container_style}", - img { - src: "https://i.imgflip.com/2zh47r.jpg", - height: "500px", - }, - div { - style: "{caption_container_style}", - p { - style: "{caption_style}", - "{caption}" - } - } - } - )) -} -// ANCHOR_END: meme_component - -// ANCHOR: caption_editor -#[inline_props] -fn CaptionEditor<'a>( - cx: Scope<'a>, - caption: &'a str, - on_input: EventHandler<'a, FormEvent>, -) -> Element<'a> { - let input_style = r" - border: none; - background: cornflowerblue; - padding: 8px 16px; - margin: 0; - border-radius: 4px; - color: white; - "; - - cx.render(rsx!(input { - style: "{input_style}", - value: "{caption}", - oninput: move |event| on_input.call(event), - })) -} -// ANCHOR_END: caption_editor - -// ANCHOR_END: all diff --git a/docs/guide/examples/meme_editor_dark_mode.rs b/docs/guide/examples/meme_editor_dark_mode.rs deleted file mode 100644 index e62a64eb7..000000000 --- a/docs/guide/examples/meme_editor_dark_mode.rs +++ /dev/null @@ -1,185 +0,0 @@ -// ANCHOR: all -#![allow(non_snake_case)] - -use dioxus::prelude::*; - -fn main() { - dioxus_desktop::launch(App); -} - -// ANCHOR: DarkMode_struct -struct DarkMode(bool); -// ANCHOR_END: DarkMode_struct - -#[rustfmt::skip] -pub fn App(cx: Scope) -> Element { - // ANCHOR: context_provider -use_shared_state_provider(cx, || DarkMode(false)); - // ANCHOR_END: context_provider - - let is_dark_mode = use_is_dark_mode(cx); - - let wrapper_style = if is_dark_mode { - r" - background: #222; - min-height: 100vh; - " - } else { - r"" - }; - - cx.render(rsx!(div { - style: "{wrapper_style}", - DarkModeToggle {}, - MemeEditor {}, - })) -} - -#[rustfmt::skip] -pub fn use_is_dark_mode(cx: &ScopeState) -> bool { - // ANCHOR: use_context -let dark_mode_context = use_shared_state::(cx); - // ANCHOR_END: use_context - - dark_mode_context - .map(|context| context.read().0) - .unwrap_or(false) -} - -// ANCHOR: toggle -pub fn DarkModeToggle(cx: Scope) -> Element { - let dark_mode = use_shared_state::(cx).unwrap(); - - let style = if dark_mode.read().0 { - "color:white" - } else { - "" - }; - - cx.render(rsx!(label { - style: "{style}", - "Dark Mode", - input { - r#type: "checkbox", - oninput: move |event| { - let is_enabled = event.value == "true"; - dark_mode.write().0 = is_enabled; - }, - }, - })) -} -// ANCHOR_END: toggle - -// ANCHOR: meme_editor -fn MemeEditor(cx: Scope) -> Element { - let is_dark_mode = use_is_dark_mode(cx); - let heading_style = if is_dark_mode { "color: white" } else { "" }; - - let container_style = r" - display: flex; - flex-direction: column; - gap: 16px; - margin: 0 auto; - width: fit-content; - "; - - let caption = use_state(cx, || "me waiting for my rust code to compile".to_string()); - - cx.render(rsx! { - div { - style: "{container_style}", - h1 { - style: "{heading_style}", - "Meme Editor" - }, - Meme { - caption: caption, - }, - CaptionEditor { - caption: caption, - on_input: move |event: FormEvent| {caption.set(event.value.clone());}, - }, - } - }) -} -// ANCHOR_END: meme_editor - -// ANCHOR: meme_component -#[inline_props] -fn Meme<'a>(cx: Scope<'a>, caption: &'a str) -> Element<'a> { - let container_style = r" - position: relative; - width: fit-content; - "; - - let caption_container_style = r" - position: absolute; - bottom: 0; - left: 0; - right: 0; - padding: 16px 8px; - "; - - let caption_style = r" - font-size: 32px; - margin: 0; - color: white; - text-align: center; - "; - - cx.render(rsx!( - div { - style: "{container_style}", - img { - src: "https://i.imgflip.com/2zh47r.jpg", - height: "500px", - }, - div { - style: "{caption_container_style}", - p { - style: "{caption_style}", - "{caption}" - } - } - } - )) -} -// ANCHOR_END: meme_component - -// ANCHOR: caption_editor -#[inline_props] -fn CaptionEditor<'a>( - cx: Scope<'a>, - caption: &'a str, - on_input: EventHandler<'a, FormEvent>, -) -> Element<'a> { - let is_dark_mode = use_is_dark_mode(cx); - - let colors = if is_dark_mode { - r" - background: cornflowerblue; - color: white; - " - } else { - r" - background: #def; - color: black; - " - }; - - let input_style = r" - border: none; - padding: 8px 16px; - margin: 0; - border-radius: 4px; - "; - - cx.render(rsx!(input { - style: "{input_style}{colors}", - value: "{caption}", - oninput: move |event| on_input.call(event), - })) -} -// ANCHOR_END: caption_editor - -// ANCHOR_END: all diff --git a/docs/guide/examples/readme_expanded.rs b/docs/guide/examples/readme_expanded.rs deleted file mode 100644 index 1ec30e57b..000000000 --- a/docs/guide/examples/readme_expanded.rs +++ /dev/null @@ -1,108 +0,0 @@ -use dioxus::prelude::*; - -fn main() { - dioxus_desktop::launch(app); -} - -fn app(cx: Scope) -> Element { - let mut count = use_state(cx, || 0); - - cx.render( - // rsx expands to LazyNodes::new - ::dioxus::core::LazyNodes::new( - move |__cx: &::dioxus::core::ScopeState| -> ::dioxus::core::VNode { - // The template is every static part of the rsx - static TEMPLATE: ::dioxus::core::Template = ::dioxus::core::Template { - // This is the source location of the rsx that generated this template. This is used to make hot rsx reloading work. Hot rsx reloading just replaces the template with a new one generated from the rsx by the CLI. - name: "examples\\readme.rs:14:15:250", - // The root nodes are the top level nodes of the rsx - roots: &[ - // The h1 node - ::dioxus::core::TemplateNode::Element { - // Find the built in h1 tag in the dioxus_elements crate exported by the dioxus html crate - tag: dioxus_elements::h1::TAG_NAME, - namespace: dioxus_elements::h1::NAME_SPACE, - attrs: &[], - // The children of the h1 node - children: &[ - // The dynamic count text node - // Any nodes that are dynamic have a dynamic placeholder with a unique index - ::dioxus::core::TemplateNode::DynamicText { - // This index is used to find what element in `dynamic_nodes` to use instead of the placeholder - id: 0usize, - }, - ], - }, - // The up high button node - ::dioxus::core::TemplateNode::Element { - tag: dioxus_elements::button::TAG_NAME, - namespace: dioxus_elements::button::NAME_SPACE, - attrs: &[ - // The dynamic onclick listener attribute - // Any attributes that are dynamic have a dynamic placeholder with a unique index. - ::dioxus::core::TemplateAttribute::Dynamic { - // Similar to dynamic nodes, dynamic attributes have a unique index used to find the attribute in `dynamic_attrs` to use instead of the placeholder - id: 0usize, - }, - ], - children: &[::dioxus::core::TemplateNode::Text { text: "Up high!" }], - }, - // The down low button node - ::dioxus::core::TemplateNode::Element { - tag: dioxus_elements::button::TAG_NAME, - namespace: dioxus_elements::button::NAME_SPACE, - attrs: &[ - // The dynamic onclick listener attribute - ::dioxus::core::TemplateAttribute::Dynamic { id: 1usize }, - ], - children: &[::dioxus::core::TemplateNode::Text { text: "Down low!" }], - }, - ], - // Node paths is a list of paths to every dynamic node in the rsx - node_paths: &[ - // The first node path is the path to the dynamic node with an id of 0 (the count text node) - &[ - // Go to the index 0 root node - 0u8, - // - // Go to the first child of the root node - 0u8, - ], - ], - // Attr paths is a list of paths to every dynamic attribute in the rsx - attr_paths: &[ - // The first attr path is the path to the dynamic attribute with an id of 0 (the up high button onclick listener) - &[ - // Go to the index 1 root node - 1u8, - ], - // The second attr path is the path to the dynamic attribute with an id of 1 (the down low button onclick listener) - &[ - // Go to the index 2 root node - 2u8, - ], - ], - }; - // The VNode is a reference to the template with the dynamic parts of the rsx - ::dioxus::core::VNode { - parent: None, - key: None, - // The static template this node will use. The template is stored in a Cell so it can be replaced with a new template when hot rsx reloading is enabled - template: std::cell::Cell::new(TEMPLATE), - root_ids: dioxus::core::exports::bumpalo::collections::Vec::new_in(__cx.bump()) - .into(), - dynamic_nodes: __cx.bump().alloc([ - // The dynamic count text node (dynamic node id 0) - __cx.text_node(format_args!("High-Five counter: {0}", count)), - ]), - dynamic_attrs: __cx.bump().alloc([ - // The dynamic up high button onclick listener (dynamic attribute id 0) - dioxus_elements::events::onclick(__cx, move |_| count += 1), - // The dynamic down low button onclick listener (dynamic attribute id 1) - dioxus_elements::events::onclick(__cx, move |_| count -= 1), - ]), - } - }, - ), - ) -} diff --git a/docs/guide/examples/rendering_lists.rs b/docs/guide/examples/rendering_lists.rs deleted file mode 100644 index b95e712dc..000000000 --- a/docs/guide/examples/rendering_lists.rs +++ /dev/null @@ -1,98 +0,0 @@ -#![allow(non_snake_case)] - -use dioxus::prelude::*; - -fn main() { - dioxus_desktop::launch(App); -} - -#[derive(PartialEq, Clone)] -struct Comment { - content: String, - id: usize, -} - -#[rustfmt::skip] -pub fn App(cx: Scope) -> Element { - // ANCHOR: render_list -let comment_field = use_state(cx, String::new); -let mut next_id = use_state(cx, || 0); -let comments = use_ref(cx, Vec::::new); - -let comments_lock = comments.read(); -let comments_rendered = comments_lock.iter().map(|comment| { - rsx!(CommentComponent { - key: "{comment.id}", - comment: comment.clone(), - }) -}); - -cx.render(rsx!( - form { - onsubmit: move |_| { - comments.write().push(Comment { - content: comment_field.get().clone(), - id: *next_id.get(), - }); - next_id += 1; - - comment_field.set(String::new()); - }, - input { - value: "{comment_field}", - oninput: |event| comment_field.set(event.value.clone()), - } - input { - r#type: "submit", - } - }, - comments_rendered, -)) - // ANCHOR_END: render_list -} - -#[rustfmt::skip] -pub fn AppForLoop(cx: Scope) -> Element { - // ANCHOR: render_list_for_loop -let comment_field = use_state(cx, String::new); -let mut next_id = use_state(cx, || 0); -let comments = use_ref(cx, Vec::::new); - -cx.render(rsx!( - form { - onsubmit: move |_| { - comments.write().push(Comment { - content: comment_field.get().clone(), - id: *next_id.get(), - }); - next_id += 1; - - comment_field.set(String::new()); - }, - input { - value: "{comment_field}", - oninput: |event| comment_field.set(event.value.clone()), - } - input { - r#type: "submit", - } - }, - for comment in &*comments.read() { - // Notice the body of this for loop is rsx code, not an expression - CommentComponent { - key: "{comment.id}", - comment: comment.clone(), - } - } -)) - // ANCHOR_END: render_list_for_loop -} - -#[inline_props] -fn CommentComponent(cx: Scope, comment: Comment) -> Element { - cx.render(rsx!(div { - "Comment by anon:", - p { "{comment.content}" } - button { "Reply" }, - })) -} diff --git a/docs/guide/examples/rsx_overview.rs b/docs/guide/examples/rsx_overview.rs deleted file mode 100644 index 93c991d0d..000000000 --- a/docs/guide/examples/rsx_overview.rs +++ /dev/null @@ -1,169 +0,0 @@ -#![allow(non_snake_case)] - -use dioxus::prelude::*; - -fn main() { - dioxus_desktop::launch(App); -} - -pub fn App(cx: Scope) -> Element { - cx.render(rsx!( - Empty {}, - Children {}, - Fragments {}, - Attributes {}, - VariableAttributes {}, - CustomAttributes {}, - Formatting {}, - Expression {}, - )) -} - -#[rustfmt::skip] -pub fn Empty(cx: Scope) -> Element { - // ANCHOR: empty -cx.render(rsx!(div { - // attributes / listeners - // children -})) - // ANCHOR_END: empty -} - -#[rustfmt::skip] -pub fn Children(cx: Scope) -> Element { - // ANCHOR: children -cx.render(rsx!(ol { - li {"First Item"} - li {"Second Item"} - li {"Third Item"} -})) - // ANCHOR_END: children -} - -#[rustfmt::skip] -pub fn Fragments(cx: Scope) -> Element { - // ANCHOR: fragments -cx.render(rsx!( - p {"First Item"}, - p {"Second Item"}, - Fragment { - span { "a group" }, - span { "of three" }, - span { "items" }, - } -)) - // ANCHOR_END: fragments -} - -#[rustfmt::skip] -pub fn ManyRoots(cx: Scope) -> Element { - // ANCHOR: manyroots -cx.render(rsx!( - p {"First Item"}, - p {"Second Item"}, -)) - // ANCHOR_END: manyroots -} - -#[rustfmt::skip] -pub fn Attributes(cx: Scope) -> Element { - // ANCHOR: attributes -cx.render(rsx!(a { - href: "https://www.youtube.com/watch?v=dQw4w9WgXcQ", - class: "primary_button", - color: "red", -})) - // ANCHOR_END: attributes -} - -#[rustfmt::skip] -pub fn VariableAttributes(cx: Scope) -> Element { - // ANCHOR: variable_attributes -let written_in_rust = true; -let button_type = "button"; -cx.render(rsx!(button { - disabled: "{written_in_rust}", - class: "{button_type}", - "Rewrite it in rust" -})) - // ANCHOR_END: variable_attributes -} - -#[rustfmt::skip] -pub fn CustomAttributes(cx: Scope) -> Element { - // ANCHOR: custom_attributes - cx.render(rsx!(b { - "customAttribute": "value", - })) - // ANCHOR_END: custom_attributes -} - -#[rustfmt::skip] -pub fn Formatting(cx: Scope) -> Element { - // ANCHOR: formatting -let coordinates = (42, 0); -let country = "es"; -cx.render(rsx!(div { - class: "country-{country}", - "position": "{coordinates:?}", - // arbitrary expressions are allowed, - // as long as they don't contain `{}` - div { - "{country.to_uppercase()}" - }, - div { - "{7*6}" - }, - // {} can be escaped with {{}} - div { - "{{}}" - }, -})) -// ANCHOR_END: formatting -} - -#[rustfmt::skip] -pub fn Expression(cx: Scope) -> Element { - // ANCHOR: expression -let text = "Dioxus"; -cx.render(rsx!(span { - text.to_uppercase(), - // create a list of text from 0 to 9 - (0..10).map(|i| rsx!{ i.to_string() }) -})) - // ANCHOR_END: expression -} - -#[rustfmt::skip] -pub fn Loops(cx: Scope) -> Element { - // ANCHOR: loops -cx.render(rsx!{ - // use a for loop where the body itself is RSX - div { - // create a list of text from 0 to 9 - for i in 0..3 { - // NOTE: the body of the loop is RSX not a rust statement - div { - "{i}" - } - } - } - // iterator equivalent - div { - (0..3).map(|i| rsx!{ div { "{i}" } }) - } -}) - // ANCHOR_END: loops -} - -#[rustfmt::skip] -pub fn IfStatements(cx: Scope) -> Element { - // ANCHOR: ifstatements -cx.render(rsx!{ - // use if statements without an else - if true { - rsx!(div { "true" }) - } -}) - // ANCHOR_END: ifstatements -} diff --git a/docs/guide/examples/server_basic.rs b/docs/guide/examples/server_basic.rs deleted file mode 100644 index 858fcfd50..000000000 --- a/docs/guide/examples/server_basic.rs +++ /dev/null @@ -1,30 +0,0 @@ -#![allow(non_snake_case, unused)] -use dioxus::prelude::*; - -#[tokio::main] -async fn main() { - #[cfg(feature = "ssr")] - { - use dioxus_fullstack::prelude::*; - - let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 8080)); - axum::Server::bind(&addr) - .serve( - axum::Router::new() - .serve_dioxus_application("", ServeConfigBuilder::new(app, ())) - .into_make_service(), - ) - .await - .unwrap(); - } -} - -fn app(cx: Scope) -> Element { - let mut count = use_state(cx, || 0); - - cx.render(rsx! { - h1 { "High-Five counter: {count}" } - button { onclick: move |_| count += 1, "Up high!" } - button { onclick: move |_| count -= 1, "Down low!" } - }) -} diff --git a/docs/guide/examples/server_context.rs b/docs/guide/examples/server_context.rs deleted file mode 100644 index 172b978e9..000000000 --- a/docs/guide/examples/server_context.rs +++ /dev/null @@ -1,109 +0,0 @@ -#![allow(non_snake_case, unused)] -use dioxus::prelude::*; -use dioxus_fullstack::prelude::*; - -fn main() { - #[cfg(feature = "web")] - dioxus_web::launch_with_props( - app, - // Get the root props from the document - get_root_props_from_document().unwrap_or_default(), - dioxus_web::Config::new().hydrate(true), - ); - #[cfg(feature = "ssr")] - { - use axum::extract::Path; - use axum::extract::State; - use axum::routing::get; - - tokio::runtime::Runtime::new() - .unwrap() - .block_on(async move { - let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 8080)); - axum::Server::bind(&addr) - .serve( - axum::Router::new() - // Serve the dist folder with the static javascript and WASM files created by the dixous CLI - .serve_static_assets("./dist") - // Register server functions - .register_server_fns("") - // Connect to the hot reload server in debug mode - .connect_hot_reload() - // Render the application. This will serialize the root props (the intial count) into the HTML - .route( - "/", - get(move |State(ssr_state): State| async move { axum::body::Full::from( - ssr_state.render( - &ServeConfigBuilder::new( - app, - 0, - ) - .build(), - ) - )}), - ) - // Render the application with a different intial count - .route( - "/:initial_count", - get(move |Path(intial_count): Path, State(ssr_state): State| async move { axum::body::Full::from( - ssr_state.render( - &ServeConfigBuilder::new( - app, - intial_count, - ) - .build(), - ) - )}), - ) - .with_state(SSRState::default()) - .into_make_service(), - ) - .await - .unwrap(); - }); - } -} - -fn app(cx: Scope) -> Element { - let mut count = use_state(cx, || *cx.props); - - cx.render(rsx! { - h1 { "High-Five counter: {count}" } - button { onclick: move |_| count += 1, "Up high!" } - button { onclick: move |_| count -= 1, "Down low!" } - button { - onclick: move |_| { - to_owned![count]; - async move { - // Call the server function just like a local async function - if let Ok(new_count) = double_server(*count.current()).await { - count.set(new_count); - } - } - }, - "Double" - } - }) -} - -// We use the "getcbor" encoding to make caching easier -#[server(DoubleServer, "", "getcbor")] -async fn double_server(number: usize) -> Result { - let cx = server_context(); - // Perform some expensive computation or access a database on the server - tokio::time::sleep(std::time::Duration::from_secs(1)).await; - let result = number * 2; - - println!( - "User Agent {:?}", - cx.request_parts().headers.get("User-Agent") - ); - - // Set the cache control header to 1 hour on the post request - cx.response_headers_mut() - .insert("Cache-Control", "max-age=3600".parse().unwrap()); - - println!("server calculated {result}"); - - Ok(result) -} diff --git a/docs/guide/examples/server_context_state.rs b/docs/guide/examples/server_context_state.rs deleted file mode 100644 index 0f0b541cc..000000000 --- a/docs/guide/examples/server_context_state.rs +++ /dev/null @@ -1,134 +0,0 @@ -#![allow(non_snake_case, unused)] -use dioxus::prelude::*; -use dioxus_fullstack::prelude::*; - -#[cfg(feature = "ssr")] -#[derive(Default, Clone)] -struct ServerFunctionState { - call_count: std::sync::Arc, -} - -fn main() { - #[cfg(feature = "web")] - dioxus_web::launch_with_props( - app, - // Get the root props from the document - get_root_props_from_document().unwrap_or_default(), - dioxus_web::Config::new().hydrate(true), - ); - #[cfg(feature = "ssr")] - { - use axum::body::Body; - use axum::extract::Path; - use axum::extract::State; - use axum::http::Request; - use axum::routing::get; - use std::sync::Arc; - - tokio::runtime::Runtime::new() - .unwrap() - .block_on(async move { - let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 8080)); - axum::Server::bind(&addr) - .serve( - axum::Router::new() - // Serve the dist folder with the static javascript and WASM files created by the dixous CLI - .serve_static_assets("./dist") - // Register server functions - .register_server_fns_with_handler("", |func| { - move |State(server_fn_state): State, req: Request| async move { - let (parts, body) = req.into_parts(); - let parts: Arc = Arc::new(parts.into()); - let mut server_context = DioxusServerContext::new(parts.clone()); - server_context.insert(server_fn_state); - server_fn_handler(server_context, func.clone(), parts, body).await - } - }) - .with_state(ServerFunctionState::default()) - // Connect to the hot reload server in debug mode - .connect_hot_reload() - // Render the application. This will serialize the root props (the intial count) into the HTML - .route( - "/", - get(move |State(ssr_state): State| async move { axum::body::Full::from( - ssr_state.render( - &ServeConfigBuilder::new( - app, - 0, - ) - .build(), - ) - )}), - ) - // Render the application with a different intial count - .route( - "/:initial_count", - get(move |Path(intial_count): Path, State(ssr_state): State| async move { axum::body::Full::from( - ssr_state.render( - &ServeConfigBuilder::new( - app, - intial_count, - ) - .build(), - ) - )}), - ) - .with_state(SSRState::default()) - .into_make_service(), - ) - .await - .unwrap(); - }); - } -} - -fn app(cx: Scope) -> Element { - let mut count = use_state(cx, || *cx.props); - - cx.render(rsx! { - h1 { "High-Five counter: {count}" } - button { onclick: move |_| count += 1, "Up high!" } - button { onclick: move |_| count -= 1, "Down low!" } - button { - onclick: move |_| { - to_owned![count]; - async move { - // Call the server function just like a local async function - if let Ok(new_count) = double_server(*count.current()).await { - count.set(new_count); - } - } - }, - "Double" - } - }) -} - -// We use the "getcbor" encoding to make caching easier -#[server(DoubleServer, "", "getcbor")] -async fn double_server(number: usize) -> Result { - // Perform some expensive computation or access a database on the server - tokio::time::sleep(std::time::Duration::from_secs(1)).await; - let result = number * 2; - let cx = server_context(); - - println!( - "User Agent {:?}", - cx.request_parts().headers.get("User-Agent") - ); - - // Set the cache control header to 1 hour on the post request - cx.response_headers_mut() - .insert("Cache-Control", "max-age=3600".parse().unwrap()); - - // Get the server function state - let server_fn_state = cx.get::().unwrap(); - let call_count = server_fn_state - .call_count - .fetch_add(1, std::sync::atomic::Ordering::SeqCst); - println!("server functions have been called {call_count} times"); - - println!("server calculated {result}"); - - Ok(result) -} diff --git a/docs/guide/examples/server_function.rs b/docs/guide/examples/server_function.rs deleted file mode 100644 index 55f5104f9..000000000 --- a/docs/guide/examples/server_function.rs +++ /dev/null @@ -1,96 +0,0 @@ -#![allow(non_snake_case, unused)] -use dioxus::prelude::*; -use dioxus_fullstack::prelude::*; - -fn main() { - #[cfg(feature = "web")] - dioxus_web::launch_with_props( - app, - // Get the root props from the document - get_root_props_from_document().unwrap_or_default(), - dioxus_web::Config::new().hydrate(true), - ); - #[cfg(feature = "ssr")] - { - use axum::extract::Path; - use axum::extract::State; - use axum::routing::get; - - tokio::runtime::Runtime::new() - .unwrap() - .block_on(async move { - let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 8080)); - axum::Server::bind(&addr) - .serve( - axum::Router::new() - // Serve the dist folder with the static javascript and WASM files created by the dixous CLI - .serve_static_assets("./dist") - // Register server functions - .register_server_fns("") - // Connect to the hot reload server in debug mode - .connect_hot_reload() - // Render the application. This will serialize the root props (the intial count) into the HTML - .route( - "/", - get(move |Path(intial_count): Path, State(ssr_state): State| async move { axum::body::Full::from( - ssr_state.render( - &ServeConfigBuilder::new( - app, - intial_count, - ) - .build(), - ) - )}), - ) - // Render the application with a different intial count - .route( - "/:initial_count", - get(move |Path(intial_count): Path, State(ssr_state): State| async move { axum::body::Full::from( - ssr_state.render( - &ServeConfigBuilder::new( - app, - intial_count, - ) - .build(), - ) - )}), - ) - .with_state(SSRState::default()) - .into_make_service(), - ) - .await - .unwrap(); - }); - } -} - -fn app(cx: Scope) -> Element { - let mut count = use_state(cx, || *cx.props); - - cx.render(rsx! { - h1 { "High-Five counter: {count}" } - button { onclick: move |_| count += 1, "Up high!" } - button { onclick: move |_| count -= 1, "Down low!" } - button { - onclick: move |_| { - to_owned![count]; - async move { - // Call the server function just like a local async function - if let Ok(new_count) = double_server(*count.current()).await { - count.set(new_count); - } - } - }, - "Double" - } - }) -} - -#[server(DoubleServer)] -async fn double_server(number: usize) -> Result { - // Perform some expensive computation or access a database on the server - tokio::time::sleep(std::time::Duration::from_secs(1)).await; - let result = number * 2; - println!("server calculated {result}"); - Ok(result) -} diff --git a/docs/guide/examples/spawn.rs b/docs/guide/examples/spawn.rs deleted file mode 100644 index 90c311200..000000000 --- a/docs/guide/examples/spawn.rs +++ /dev/null @@ -1,84 +0,0 @@ -#![allow(non_snake_case, unused)] - -use dioxus::prelude::*; - -fn main() { - dioxus_desktop::launch(App); -} - -fn App(cx: Scope) -> Element { - // ANCHOR: spawn - let logged_in = use_state(cx, || false); - - let log_in = move |_| { - cx.spawn({ - let logged_in = logged_in.to_owned(); - - async move { - let resp = reqwest::Client::new() - .post("http://example.com/login") - .send() - .await; - - match resp { - Ok(_data) => { - println!("Login successful!"); - logged_in.set(true); - } - Err(_err) => { - println!( - "Login failed - you need a login server running on localhost:8080." - ) - } - } - } - }); - }; - - cx.render(rsx! { - button { - onclick: log_in, - "Login", - } - }) - // ANCHOR_END: spawn -} - -pub fn Tokio(cx: Scope) -> Element { - let _ = || { - // ANCHOR: tokio - cx.spawn(async { - let _ = tokio::spawn(async {}).await; - - let _ = tokio::task::spawn_local(async { - // some !Send work - }) - .await; - }); - // ANCHOR_END: tokio - }; - - cx.render(rsx!(())) -} - -pub fn ToOwnedMacro(cx: Scope) -> Element { - let count = use_state(cx, || 0); - let age = use_state(cx, || 0); - let name = use_state(cx, || 0); - let description = use_state(cx, || 0); - - let _ = || { - // ANCHOR: to_owned_macro - use dioxus::hooks::to_owned; - - cx.spawn({ - to_owned![count, age, name, description]; - async move { - // ... - } - }); - // ANCHOR_END: to_owned_macro - }; - - cx.render(rsx!(())) -} diff --git a/docs/guide/examples/use_future.rs b/docs/guide/examples/use_future.rs deleted file mode 100644 index 01464704a..000000000 --- a/docs/guide/examples/use_future.rs +++ /dev/null @@ -1,62 +0,0 @@ -#![allow(non_snake_case, unused)] - -use dioxus::prelude::*; - -fn main() { - dioxus_desktop::launch(App); -} - -#[derive(serde::Deserialize, Debug)] -struct ApiResponse { - #[serde(rename = "message")] - image_url: String, -} - -#[rustfmt::skip] -fn App(cx: Scope) -> Element { -// ANCHOR: use_future -let future = use_future(cx, (), |_| async move { - reqwest::get("https://dog.ceo/api/breeds/image/random") - .await - .unwrap() - .json::() - .await -}); -// ANCHOR_END: use_future - -// ANCHOR: render -cx.render(match future.value() { - Some(Ok(response)) => rsx! { - button { - onclick: move |_| future.restart(), - "Click to fetch another doggo" - } - div { - img { - max_width: "500px", - max_height: "500px", - src: "{response.image_url}", - } - } - }, - Some(Err(_)) => rsx! { div { "Loading dogs failed" } }, - None => rsx! { div { "Loading dogs..." } }, -}) -// ANCHOR_END: render -} - -#[rustfmt::skip] -#[inline_props] -fn RandomDog(cx: Scope, breed: String) -> Element { -// ANCHOR: dependency -let future = use_future(cx, (breed,), |(breed,)| async move { - reqwest::get(format!("https://dog.ceo/api/breed/{breed}/images/random")) - .await - .unwrap() - .json::() - .await -}); -// ANCHOR_END: dependency - - cx.render(rsx!(())) -} diff --git a/docs/guide/src/en/SUMMARY.md b/docs/guide/src/en/SUMMARY.md deleted file mode 100644 index a44439200..000000000 --- a/docs/guide/src/en/SUMMARY.md +++ /dev/null @@ -1,57 +0,0 @@ -# Summary - -[Introduction](index.md) - -- [Getting Started](getting_started/index.md) - - [Desktop](getting_started/desktop.md) - - [Web](getting_started/web.md) - - [Server-Side Rendering](getting_started/ssr.md) - - [Fullstack](getting_started/fullstack.md) - - [Liveview](getting_started/liveview.md) - - [Terminal UI](getting_started/tui.md) - - [Mobile](getting_started/mobile.md) - - [Hot Reloading](getting_started/hot_reload.md) -- [Describing the UI](describing_ui/index.md) - - [Special Attributes](describing_ui/special_attributes.md) - - [Components](describing_ui/components.md) - - [Props](describing_ui/component_props.md) - - [Component Children](describing_ui/component_children.md) -- [Interactivity](interactivity/index.md) - - [Event Listeners](interactivity/event_handlers.md) - - [Hooks & Component State](interactivity/hooks.md) - - [User Input](interactivity/user_input.md) - - [Sharing State](interactivity/sharing_state.md) - - [Memoization](interactivity/memoization.md) - - [Custom Hooks](interactivity/custom_hooks.md) - - [Dynamic Rendering](interactivity/dynamic_rendering.md) - - [Routing](interactivity/router.md) -- [Async](async/index.md) - - [UseEffect](async/use_effect.md) - - [UseFuture](async/use_future.md) - - [UseCoroutine](async/use_coroutine.md) - - [Spawning Futures](async/spawn.md) -- [Best Practices](best_practices/index.md) - - [Error Handling](best_practices/error_handling.md) - - [Antipatterns](best_practices/antipatterns.md) -- [Publishing](publishing/index.md) - - - [Desktop](publishing/desktop.md) - - [Web](publishing/web.md) - ---- - -- [Fullstack](fullstack/index.md) - - [Getting Started](fullstack/getting_started.md) - - [Communicating with the Server](fullstack/server_functions.md) - ---- - -- [Custom Renderer](custom_renderer/index.md) - ---- - -- [Contributing](contributing/index.md) - - [Project Structure](contributing/project_structure.md) - - [Walkthrough of Internals](contributing/walkthrough_readme.md) - - [Guiding Principles](contributing/guiding_principles.md) - - [Roadmap](contributing/roadmap.md) diff --git a/docs/guide/src/en/__unused/README.md b/docs/guide/src/en/__unused/README.md deleted file mode 100644 index 0a3583ef1..000000000 --- a/docs/guide/src/en/__unused/README.md +++ /dev/null @@ -1,6 +0,0 @@ -This directory includes: - -- Very outdated docs -- Docs for features which haven't been implemented (yet?) -- Information which has already been covered in the guide in a more organized fashion -- A few things yet to be integrated into the guide nicely \ No newline at end of file diff --git a/docs/guide/src/en/__unused/advanced-guides/06-subscription-api.md b/docs/guide/src/en/__unused/advanced-guides/06-subscription-api.md deleted file mode 100644 index 1d53a8d61..000000000 --- a/docs/guide/src/en/__unused/advanced-guides/06-subscription-api.md +++ /dev/null @@ -1,33 +0,0 @@ -# Subscriptions - -Yew subscriptions are used to schedule update for components into the future. The `Context` object can create subscriptions: - -```rust, no_run -fn Component(cx: Component) -> DomTree { - let update = cx.schedule(); - - // Now, when the subscription is called, the component will be re-evaluated - update.consume(); -} -``` - -Whenever a component's subscription is called, the component will then re-evaluated. You can consider the input properties of -a component to be just another form of subscription. By default, the Dioxus component system automatically diffs a component's props -when the parent function is called, and if the props are different, the child component's subscription is called. - -The subscription API exposes this functionality allowing hooks and state management solutions the ability to update components whenever -some state or event occurs outside of the component. For instance, the `use_context` hook uses this to subscribe components that use a -particular context. - -```rust, no_run -fn use_context(cx: Scope) -> I { - -} - - - - - - - -``` diff --git a/docs/guide/src/en/__unused/advanced-guides/10-concurrent-mode.md b/docs/guide/src/en/__unused/advanced-guides/10-concurrent-mode.md deleted file mode 100644 index b92897157..000000000 --- a/docs/guide/src/en/__unused/advanced-guides/10-concurrent-mode.md +++ /dev/null @@ -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, no_run -fn Example(cx: Scope) -> Vnode { - rsx!{
"Hello world!"
} -} -``` - -becomes - -```rust, no_run -async fn Example(cx: Scope) -> Vnode { - rsx!{
"Hello world!"
} -} -``` - -Now, logic in components can be awaited to delay updates of the component and its children. Like so: - -```rust, no_run -async fn Example(cx: Scope) -> Vnode { - let name = fetch_name().await; - rsx!{
"Hello {name}"
} -} - -async fetch_name() -> String { - // ... -} -``` - -This component will only schedule its render once the fetch is complete. However, we _don't_ recommend using async/await directly in your components. - -Async is a notoriously challenging yet rewarding tool for efficient tools. If not careful, locking and unlocking shared aspects of the component's context can lead to data races and panics. If a shared resource is locked while the component is awaiting, then other components can be locked or panic when trying to access the same resource. These rules are especially important when references to shared global state are accessed using the context object's lifetime. If mutable references to data captured immutably by the context are taken, then the component will panic, causing confusion. - -Instead, we suggest using hooks and future combinators that can safely utilize the safeguards of the component's Context when interacting with async tasks. - -As part of our Dioxus hooks crate, we provide a data loader hook which pauses a component until its async dependencies are ready. This caches requests, reruns the fetch if dependencies have changed, and provides the option to render something else while the component is loading. - -```rust, no_run -async fn ExampleLoader(cx: Scope) -> Vnode { - /* - Fetch, pause the component from rendering at all. - - The component is locked while waiting for the request to complete - While waiting, an alternate component is scheduled in its place. - - This API stores the result on the Context object, so the loaded data is taken as reference. - */ - let name: &Result = use_fetch_data("http://example.com/json", ()) - .place_holder(|cx| rsx!{
"loading..."
}) - .delayed_place_holder(1000, |cx| rsx!{
"still loading..."
}) - .await; - - match name { - Ok(name) => rsx! {
"Hello {something}"
}, - Err(e) => rsx! {
"An error occurred :("
} - } -} -``` - -```rust, no_run -async fn Example(cx: Scope) -> DomTree { - // Diff this set between the last set - // Check if we have any outstanding tasks? - // - // Eventually, render the component into the VDOM when the future completes -
- -
- - // Render a div, queue a component - // Render the placeholder first, then when the component is ready, then render the component -
- "Loading"
}}> - - - -} -``` diff --git a/docs/guide/src/en/__unused/advanced-guides/11-arena-memo.md b/docs/guide/src/en/__unused/advanced-guides/11-arena-memo.md deleted file mode 100644 index 49fedda11..000000000 --- a/docs/guide/src/en/__unused/advanced-guides/11-arena-memo.md +++ /dev/null @@ -1,58 +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 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, no_run -fn test() -> DomTree { - html! { - <> - - // same as - - - } -} - -static TestComponent: Component = |cx| html!{
"Hello world"
}; - -static TestComponent: Component = |cx|{ - let g = "BLAH"; - html! { -
"Hello world"
- } -}; - -#[inline_props] -fn test_component(cx: Scope, name: String) -> Element { - render!("Hello, {name}") -} -``` - -## Why this behavior? - -"This is different than React, why differ?". - -Take a component like this: - -```rust, no_run -fn test(cx: Scope) -> DomTree { - let Bundle { alpha, beta, gamma } = use_context::(cx); - html! { -
- - - -
- } -} -``` - -While the contents of the destructured bundle might change, not every child component will need to be re-rendered every time the context changes. diff --git a/docs/guide/src/en/__unused/advanced-guides/12-signals.md b/docs/guide/src/en/__unused/advanced-guides/12-signals.md deleted file mode 100644 index 7fbb56de7..000000000 --- a/docs/guide/src/en/__unused/advanced-guides/12-signals.md +++ /dev/null @@ -1,150 +0,0 @@ -# Signals: Skipping the Diff - -In most cases, the traditional VirtualDOM diffing pattern is plenty fast. Dioxus will compare trees of VNodes, find the differences, and then update the Renderer's DOM with the diffs. However, this can generate a lot of overhead for certain types of components. In apps where reducing visual latency is a top priority, you can opt into the `Signals` api to entirely disable diffing of hot-path components. Dioxus will then automatically construct a state machine for your component, making updates nearly instant. - -Signals build on the same infrastructure that powers asynchronous rendering where in-tree values can be updated outside of the render phase. In async rendering, a future is used as the signal source. With the raw signal API, any value can be used as a signal source. - -By default, Dioxus will only try to diff subtrees of components with dynamic content, automatically skipping diffing static content. - -## What does this look like? - -Your component today might look something like this: - -```rust, no_run -fn Comp(cx: Scope) -> DomTree { - let (title, set_title) = use_state(cx, || "Title".to_string()); - cx.render(rsx!{ - input { - value: title, - onchange: move |new| set_title(new.value()) - } - }) -} -``` - -This component is fairly straightforward – the input updates its own value on every change. However, every call to set_title will re-render the component. If we add a large list, then every time we update the title input, Dioxus will need to diff the entire list, over, and over, and over. This is **a lot** of wasted clock-cycles! - -```rust, no_run -fn Comp(cx: Scope) -> DomTree { - let (title, set_title) = use_state(cx, || "Title".to_string()); - cx.render(rsx!{ - div { - input { - value: title, - onchange: move |new| set_title(new.value()) - } - ul { - {0..10000.map(|f| rsx!{ - li { "{f}" } - })} - } - } - }) -} -``` - -Many experienced React developers will just say "this is bad design" – but we consider it to be a pit of failure, rather than a pit of success! That's why signals exist – to push you in a more performant (and ergonomic) direction. Signals let us directly bind values to their final place in the VirtualDOM. Whenever the signal value is updated, Dioxus will only the DOM nodes where that signal is used. Signals are built into Dioxus, so we can directly bind attributes of elements to their updates. - -We can use signals to generate a two-way binding between data and the input box. Our text input is now just a two-line component! - -```rust, no_run -fn Comp(cx: Scope) -> DomTree { - let mut title = use_signal(cx, || String::from("Title")); - cx.render(rsx!(input { value: title })) -} -``` - -For a slightly more interesting example, this component calculates the sum between two numbers, but totally skips the diffing process. - -```rust, no_run -fn Calculator(cx: Scope) -> DomTree { - let mut a = use_signal(cx, || 0); - let mut b = use_signal(cx, || 0); - let mut c = a + b; - rsx! { - input { value: a } - input { value: b } - p { "a + b = {c}" } - } -} -``` - -Do you notice how we can use built-in operations on signals? Under the hood, we actually create a new derived signal that depends on `a` and `b`. Whenever `a` or `b` update, then `c` will update. If we need to create a new derived signal that's more complex than a basic operation (`std::ops`) we can either chain signals together or combine them: - -```rust, no_run -let mut a = use_signal(cx, || 0); -let mut b = use_signal(cx, || 0); - -// Chain signals together using the `with` method -let c = a.with(b).map(|(a, b)| *a + *b); -``` - -## Deref and DerefMut - -If we ever need to get the value out of a signal, we can simply `deref` it. - -```rust, no_run -let mut a = use_signal(cx, || 0); -let c = *a + *b; -``` - -Calling `deref` or `deref_mut` is actually more complex than it seems. When a value is derefed, you're essentially telling Dioxus that _this_ element _needs_ to be subscribed to the signal. If a signal is derefed outside of an element, the entire component will be subscribed and the advantage of skipping diffing will be lost. Dioxus will throw an error in the console when this happens to tell you that you're using signals wrong, but your component will continue to work. - -## Global Signals - -Sometimes you want a signal to propagate across your app, either through far-away siblings or through deeply-nested components. In these cases, we use Dirac: Dioxus's first-class state management toolkit. Dirac atoms automatically implement the Signal API. This component will bind the input element to the `TITLE` atom. - - -```rust, no_run -const TITLE: Atom = Atom(|| "".to_string()); - -const Provider: Component = |cx|{ - let title = use_signal(cx, &TITLE); - render!(input { value: title }) -}; -``` - -If we use the `TITLE` atom in another component, we can cause updates to flow between components without calling render or diffing either component trees: - -```rust, no_run -const Receiver: Component = |cx|{ - let title = use_signal(cx, &TITLE); - log::info!("This will only be called once!"); - rsx!(cx, - div { - h1 { "{title}" } - div {} - footer {} - } - ) -}; -``` - -Dioxus knows that the receiver's `title` signal is used only in the text node, and skips diffing Receiver entirely, knowing to update _just_ the text node. - -If you build a complex app on top of Dirac, you'll likely notice that many of your components simply won't be diffed at all. For instance, our Receiver component will never be diffed once it has been mounted! - -## Signals and Iterators - -Sometimes you want to use a collection of items. With Signals, you can bypass diffing for collections – a very powerful technique to avoid re-rendering on large collections. - -By default, Dioxus is limited when you use iter/map. With the `For` component, you can provide an iterator and a function for the iterator to map to. - -Dioxus automatically understands how to use your signals when mixed with iterators through `Deref`/`DerefMut`. This lets you efficiently map collections while avoiding the re-rendering of lists. In essence, signals act as a hint to Dioxus on how to avoid un-necessary checks and renders, making your app faster. - -```rust, no_run -const DICT: AtomFamily = AtomFamily(|_| {}); - -const List: Component = |cx|{ - let dict = use_signal(cx, &DICT); - cx.render(rsx!( - ul { - For { each: dict, map: |k, v| rsx!( li { "{v}" }) } - } - )) -}; -``` - -## How does it work? - -Signals internally use Dioxus' asynchronous rendering infrastructure to perform updates out of the tree. diff --git a/docs/guide/src/en/__unused/advanced-guides/13-subtrees.md b/docs/guide/src/en/__unused/advanced-guides/13-subtrees.md deleted file mode 100644 index d7a8ba1d7..000000000 --- a/docs/guide/src/en/__unused/advanced-guides/13-subtrees.md +++ /dev/null @@ -1,52 +0,0 @@ -# Subtrees - -One way of extending the Dioxus VirtualDom is through the use of "Subtrees." Subtrees are chunks of the VirtualDom tree distinct from the rest of the tree. They still participate in event bubbling, diffing, etc, but will have a separate set of edits generated during the diff phase. - -For a VirtualDom that has a root tree with two subtrees, the edits follow a pattern of: - -Root --> Tree 1 --> Tree 2 --> Original root tree - -- Root edits -- Tree 1 Edits -- Tree 2 Edits -- Root Edits - -The goal of this functionality is to enable things like Portals, Windows, and inline alternative renderers without needing to spin up a new VirtualDom. - -With the right renderer plugins, a subtree could be rendered as anything – a 3D scene, SVG, or even as the contents of a new window or modal. This functionality is similar to "Portals" in React, but much more "renderer agnostic." Portals, by nature, are not necessarily cross-platform and rely on renderer functionality, so it makes sense to abstract their purpose into the subtree concept. - -The desktop renderer comes pre-loaded with the window and notification subtree plugins, making it possible to render subtrees into entirely different windows. - -Subtrees also solve the "bridging" issues in React where two different renderers need two different VirtualDoms to work properly. In Dioxus, you only ever need one VirtualDom and the right renderer plugins. - -## API - -Due to their importance in the hierarchy, Components – not nodes – are treated as subtree roots. - -```rust, no_run - -fn Subtree

(cx: Scope

) -> DomTree { - -} - -fn Window() -> DomTree { - Subtree { - onassign: move |e| { - // create window - } - children() - } -} - -fn 3dRenderer -> DomTree { - Subtree { - onassign: move |e| { - // initialize bevy - } - } -} - -``` diff --git a/docs/guide/src/en/__unused/advanced-guides/custom-renderer.md b/docs/guide/src/en/__unused/advanced-guides/custom-renderer.md deleted file mode 100644 index b14243dae..000000000 --- a/docs/guide/src/en/__unused/advanced-guides/custom-renderer.md +++ /dev/null @@ -1,280 +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 implementation of the `RealDom` trait for things to function properly. - -## The specifics: - -Implementing the renderer is fairly straightforward. The renderer needs to: - -1. Handle the stream of edits generated by updates to the virtual DOM -2. Register listeners and pass events into the virtual DOM's event system -3. Progress the virtual DOM with an async executor (or disable the suspense API and use `progress_sync`) - -Essentially, your renderer needs to implement the `RealDom` trait and generate `EventTrigger` objects to update the VirtualDOM. From there, you'll have everything needed to render the VirtualDOM to the screen. - -Internally, Dioxus handles the tree relationship, diffing, memory management, and the event system, leaving as little as possible required for renderers to implement themselves. - -For reference, check out the WebSys renderer as a starting point for your custom renderer. - -## Trait implementation and DomEdits - -The current `RealDom` trait lives in `dioxus-core/diff`. A version of it is provided here (but might not be up-to-date): - -```rust, no_run -pub trait RealDom<'a> { - fn handle_edit(&mut self, edit: DomEdit); - fn request_available_node(&mut self) -> ElementId; - fn raw_node_as_any(&self) -> &mut dyn Any; -} -``` - -For reference, the "DomEdit" type is a serialized enum that represents an atomic operation occurring on the RealDom. The variants roughly follow this set: - -```rust, no_run -enum DomEdit { - PushRoot, - AppendChildren, - ReplaceWith, - CreateTextNode, - CreateElement, - CreateElementNs, - CreatePlaceholder, - NewEventListener, - RemoveEventListener, - SetText, - SetAttribute, - RemoveAttribute, -} -``` - -The Dioxus diffing mechanism operates as a [stack machine](https://en.wikipedia.org/wiki/Stack_machine) where the "push_root" method pushes a new "real" DOM node onto the stack and "append_child" and "replace_with" both remove nodes from the stack. - -### An example - -For the sake of understanding, lets consider this example – a very simple UI declaration: - -```rust, no_run -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, no_run -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, no_run -instructions: [ - PushRoot(Container), - CreateElement(h1), -] -stack: [ - ContainerNode, - h1, -] -``` - -Next, Dioxus sees the text node, and generates the `CreateTextNode` DomEdit: - -```rust, no_run -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, no_run -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, no_run -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, no_run -instructions: [ - PushRoot(Container), - CreateElement(h1), - CreateTextNode("hello world"), - AppendChildren(1), - AppendChildren(1), - Pop(1) -] -stack: [] -``` - -Over time, our stack looked like this: - -```rust, no_run -[] -[Container] -[Container, h1] -[Container, h1, "hello world"] -[Container, h1] -[Container] -[] -``` - -Notice how our stack is empty once UI has been mounted. Conveniently, this approach completely separates the VirtualDOM and the Real DOM. Additionally, these edits are serializable, meaning we can even manage UIs across a network connection. This little stack machine and serialized edits makes Dioxus independent of platform specifics. - -Dioxus is also really fast. Because Dioxus splits the diff and patch phase, it's able to make all the edits to the RealDOM in a very short amount of time (less than a single frame) making rendering very snappy. It also allows Dioxus to cancel large diffing operations if higher priority work comes in while it's diffing. - -It's important to note that there _is_ one layer of connectedness between Dioxus and the renderer. Dioxus saves and loads elements (the PushRoot edit) with an ID. Inside the VirtualDOM, this is just tracked as a u64. - -Whenever a `CreateElement` edit is generated during diffing, Dioxus increments its node counter and assigns that new element its current NodeCount. The RealDom is responsible for remembering this ID and pushing the correct node when PushRoot(ID) is generated. Dioxus doesn't reclaim IDs of elements its removed, but your renderer probably will want to. To do this, we suggest using a `SecondarySlotMap` if implementing the renderer in Rust, or just deferring to a HashMap-type approach. - -This little demo serves to show exactly how a Renderer would need to process an edit stream to build UIs. A set of serialized EditStreams for various demos is available for you to test your custom renderer against. - -## Event loop - -Like most GUIs, Dioxus relies on an event loop to progress the VirtualDOM. The VirtualDOM itself can produce events as well, so it's important that your custom renderer can handle those too. - -The code for the WebSys implementation is straightforward, so we'll add it here to demonstrate how simple an event loop is: - -```rust, 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()); - websys_dom.stack.push(root_node); - - // Rebuild or hydrate the virtualdom - self.internal_dom.rebuild(&mut websys_dom)?; - - // Wait for updates from the real dom and progress the virtual dom - loop { - let user_input_future = websys_dom.wait_for_event(); - let internal_event_future = self.internal_dom.wait_for_event(); - - match select(user_input_future, internal_event_future).await { - Either::Left((trigger, _)) => trigger, - Either::Right((trigger, _)) => trigger, - } - } - - while let Some(trigger) = { - websys_dom.stack.push(body_element.first_child().unwrap()); - self.internal_dom - .progress_with_event(&mut websys_dom, trigger)?; - } -} -``` - -It's important that you decode the real events from your event system into Dioxus' synthetic event system (synthetic meaning abstracted). This simply means matching your event type and creating a Dioxus `VirtualEvent` type. Your custom event must implement the corresponding event trait. Right now, the VirtualEvent system is modeled almost entirely around the HTML spec, but we are interested in slimming it down. - -```rust, no_run -fn virtual_event_from_websys_event(event: &web_sys::Event) -> VirtualEvent { - match event.type_().as_str() { - "keydown" | "keypress" | "keyup" => { - struct CustomKeyboardEvent(web_sys::KeyboardEvent); - impl dioxus::events::KeyboardEvent for CustomKeyboardEvent { - fn char_code(&self) -> usize { self.0.char_code() } - fn ctrl_key(&self) -> bool { self.0.ctrl_key() } - fn key(&self) -> String { self.0.key() } - fn key_code(&self) -> usize { self.0.key_code() } - fn location(&self) -> usize { self.0.location() } - fn meta_key(&self) -> bool { self.0.meta_key() } - fn repeat(&self) -> bool { self.0.repeat() } - fn shift_key(&self) -> bool { self.0.shift_key() } - fn which(&self) -> usize { self.0.which() } - fn get_modifier_state(&self, key_code: usize) -> bool { self.0.get_modifier_state() } - } - VirtualEvent::KeyboardEvent(Rc::new(event.clone().dyn_into().unwrap())) - } - _ => todo!() -``` - -## Custom raw elements - -If you need to go as far as relying on custom elements for your renderer – you totally can. This still enables you to use Dioxus' reactive nature, component system, shared state, and other features, but will ultimately generate different nodes. All attributes and listeners for the HTML and SVG namespace are shuttled through helper structs that essentially compile away (pose no runtime overhead). You can drop in your own elements any time you want, with little hassle. However, you must be absolutely sure your renderer can handle the new type, or it will crash and burn. - -These custom elements are defined as unit structs with trait implementations. - -For example, the `div` element is (approximately!) defined as such: - -```rust, no_run -struct div; -impl div { - /// Some glorious documentation about the class property. - #[inline] - fn class<'a>(&self, cx: NodeFactory<'a>, val: Arguments) -> Attribute<'a> { - cx.attr("class", val, None, false) - } - // more attributes -} -``` - -You've probably noticed that many elements in the `rsx!` and `html!` macros support on-hover documentation. The approach we take to custom elements means that the unit struct is created immediately where the element is used in the macro. When the macro is expanded, the doc comments still apply to the unit struct, giving tons of in-editor feedback, even inside a proc macro. - -## Compatibility - -Forewarning: not every hook and service will work on your platform. Dioxus wraps things that need to be cross-platform in "synthetic" types. However, downcasting to a native type might fail if the types don't match. - -There are three opportunities for platform incompatibilities to break your program: - -1. When downcasting elements via `Ref.downcast_ref()` -2. When downcasting events via `Event.downcast_ref()` -3. Calling platform-specific APIs that don't exist - -The best hooks will properly detect the target platform and still provide functionality, failing gracefully when a platform is not supported. We encourage – and provide – an indication to the user on what platforms a hook supports. For issues 1 and 2, these return a result as to not cause panics on unsupported platforms. When designing your hooks, we recommend propagating this error upwards into user facing code, making it obvious that this particular service is not supported. - -This particular code _will panic_ due to the unwrap on downcast_ref. Try to avoid these types of patterns. - -```rust, no_run -let div_ref = use_node_ref(cx); - -cx.render(rsx!{ - div { ref: div_ref, class: "custom class", - button { "click me to see my parent's class" - onclick: move |_| if let Some(div_ref) = div_ref { - log::info!("Div class is {}", div_ref.downcast_ref::().unwrap().class()) - } - } - } -}) - -``` - -## Conclusion - -That should be it! You should have nearly all the knowledge required on how to implement your own renderer. We're super interested in seeing Dioxus apps brought to custom desktop renderers, mobile renderer, video game UI, and even augmented reality! If you're interesting in contributing to any of the these projects, don't be afraid to reach out or join the community. diff --git a/docs/guide/src/en/__unused/advanced-guides/liveview.md b/docs/guide/src/en/__unused/advanced-guides/liveview.md deleted file mode 100644 index e223c593e..000000000 --- a/docs/guide/src/en/__unused/advanced-guides/liveview.md +++ /dev/null @@ -1,32 +0,0 @@ -# Dioxus Liveview -Liveview is a configuration where a server and a client work together to render a Dioxus app. Liveview monomorphizes a web application, eliminating the need for frontend-specific APIs. - -This is a developer-friendly alternative to the JAM-stack (Javascript + API + Markdown), combining the Wasm-compatibility and async performance of Rust. - -## Why liveview? - -### No APIs necessary! -Because Liveview combines the server and the client, you'll find dedicated APIs unnecessary. You'll still want to implement a data-fetching service for Live-apps, but this can be implemented as a crate and shared between apps. This approach was designed to let you model out your data requirements without needing to maintain a public versioned API. - -You can find more information to data modeling and fetching for LiveApps in the "Book of Dioxus Patterns". - -### Ease of deployment -There is no hassle for deploying Dioxus liveview apps – simply upload the binary to your hosting provider of choice. There simply is no need to deal with intermediate APIs. An app's frontend and backend are tightly coupled to each other, meaning that the backed and frontend are always up to date. - -This is especially powerful for small teams, where fast iteration, versioned unique prototypes, and simple deployments are important. As your app grows, Dioxus will happily grow with you, serving up to 100K RPS (thanks to async Rust performance). - -### Power of server rendering combined with the reactive nature of JavaScript -Liveview apps are backed by a server and enhanced with web-assembly. This completely eliminates the need to write Javascript to add dynamic content to webpages. Apps are written in only **one** language and require essentially 0 knowledge of build systems, transpiling or ECMAScript versions. Minimum browser support is guaranteed to cover 95% of users, and the Dioxus-CLI can be configured to generate polyfills for even more support. - -### Support with LiveHost by Dioxus-Labs -The Dioxus-CLI comes ready for use with premium Dioxus-Labs services, like LiveHost. Simply link up your git repo to the Dioxus LiveHost and start deploying your fullstack Dioxus app today. LiveHost supports: - -- Versioned fronted/backend with unique links -- Builtin CI/CD -- Managed and pluggable storage database backends -- Serverless support for minimal latency -- Site Analytics -- Lighthouse optimization -- On-premise support (see license terms) - -Dioxus LiveHost is a Dioxus LiveApp management service with all supported features in a single binary. For OSS, we permit free usage and deployment of LiveHost to your favorite hosting provider. diff --git a/docs/guide/src/en/__unused/advanced-guides/rsx.md b/docs/guide/src/en/__unused/advanced-guides/rsx.md deleted file mode 100644 index 169a57875..000000000 --- a/docs/guide/src/en/__unused/advanced-guides/rsx.md +++ /dev/null @@ -1,67 +0,0 @@ -# VNodes with RSX, HTML, and NodeFactory - -Many modern frameworks provide a domain-specific-language for declaring user-interfaces. In the case of React, this language extension is called JSX and must be handled through additional dependencies and pre/post processors to transform your source code. With Rust, we can simply provide a procedural macro in the Dioxus dependency itself that mimics the JSX language. - -With Dioxus, we actually ship two different macros – a macro that mimics JSX (the `html!` macro) and a macro that mimics Rust's native nested-struct syntax (the `rsx!` macro). These macros simply transform their inputs into NodeFactory calls. - -For instance, this html! call: - -```rust, no_run -html!(

"hello world"
) -``` - -becomes this NodeFactory call: - -```rust, no_run -|f| f.element( - dioxus_elements::div, // tag - [], // listeners - [], // attributes - [f.static_text("hello world")], // children - None // key -) -``` - -The NodeFactory API is fairly ergonomic, making it a viable option to use directly. The NodeFactory API is also compile-time correct and has incredible syntax highlighting support. We use what Rust calls a "unit type" – the `dioxus_elements::div` and associated methods to ensure that a `div` can only have attributes associated with `div`s. This lets us tack on relevant documentation, autocomplete support, and jump-to-definition for methods and attributes. - -![Compile time correct syntax](../images/compiletimecorrect.png) - -## html! macro - -The html! macro supports a limited subset of the html standard. Rust's macro parsing tools are somewhat limited, so all text between tags _must be quoted_. - -However, writing HTML by hand is a bit tedious – IDE tools for Rust don't support linting/autocomplete/syntax highlighting. We suggest using RSX – it's more natural for Rust programs and _does_ integrate well with Rust IDE tools. - -```rust, no_run -let name = "jane"; -let pending = false; -let count = 10; - -dioxus::ssr::render_lazy(html! { -
-

"Hello, {name}!"

-

"Status: {pending}!"

-

"Count {count}!"

-
-}); -``` - -## rsx! macro - -The rsx! macro is a VNode builder macro designed especially for Rust programs. Writing these should feel very natural, much like assembling a struct. VSCode also supports these with code folding, bracket-tabbing, bracket highlighting, section selecting, inline documentation, GOTO definition, and refactoring support. - -When helpful, the Dioxus VSCode extension provides a way of converting a selection of HTML directly to RSX, so you can import templates from the web directly into your existing app. - -It's also a bit easier on the eyes than HTML. - -```rust, no_run -dioxus::ssr::render_lazy(rsx! { - div { - p {"Hello, {name}!"} - p {"Status: {pending}!"} - p {"Count {count}!"} - } -}); -``` - -In the next section, we'll cover the `rsx!` macro in more depth. diff --git a/docs/guide/src/en/__unused/advanced-guides/testing.md b/docs/guide/src/en/__unused/advanced-guides/testing.md deleted file mode 100644 index 405c929a9..000000000 --- a/docs/guide/src/en/__unused/advanced-guides/testing.md +++ /dev/null @@ -1,29 +0,0 @@ -## Testing - -To test your Rust code, you can annotate any function with the `#[test]` block. In VSCode with RA, this will provide a lens to click and run the test. - -```rust, no_run -#[test] -fn component_runs() { - assert!(true) -} -``` - -This will test your Rust code _without_ going through the browser. This is ideal for squashing logic bugs and ensuring components render appropriately when the browsers's DOM is not needed. If you need to run tests in the browser, you can annotate your blocks with the `#[dioxus::test]` block. - -```rust, no_run -#[dioxus::test] -fn runs_in_browser() { - // ... -} -``` - -Then, when you run - -```console -dx test --chrome -``` - -Dioxus will build and test your code using the Chrome browser as a harness. - -There's a lot more to testing if you dive in, so check out the [Testing]() guide for more information diff --git a/docs/guide/src/en/__unused/attribute_spreading.md b/docs/guide/src/en/__unused/attribute_spreading.md deleted file mode 100644 index 9bbb30698..000000000 --- a/docs/guide/src/en/__unused/attribute_spreading.md +++ /dev/null @@ -1,30 +0,0 @@ -In the cases where you need to pass arbitrary element properties into a component – say to add more functionality to the `` tag, Dioxus will accept any quoted fields. This is similar to adding arbitrary fields to regular elements using quotes. - -```rust, no_run - -rsx!( - Clickable { - "class": "blue-button", - "style": "background: red;" - } -) - -``` - -For a component to accept these attributes, you must add an `attributes` field to your component's properties. We can use the spread syntax to add these attributes to whatever nodes are in our component. - -```rust, no_run -#[derive(Props)] -struct ClickableProps<'a> { - attributes: Attributes<'a> -} - -fn clickable(cx: Scope>) -> Element { - cx.render(rsx!( - a { - ..cx.props.attributes, - "Any link, anywhere" - } - )) -} -``` diff --git a/docs/guide/src/en/__unused/composing.md b/docs/guide/src/en/__unused/composing.md deleted file mode 100644 index 82435d6f3..000000000 --- a/docs/guide/src/en/__unused/composing.md +++ /dev/null @@ -1,244 +0,0 @@ -# Thinking in Reactively - -We've finally reached the point in our tutorial where we can talk about the theory of Reactivity. We've talked about defining a declarative view, but not about the aspects that make our code _reactive_. - -Understanding the theory of reactive programming is essential to making sense of Dioxus and writing effective, performant UIs. - -In this section, we'll talk about: - -- One-way data flow -- Modifying data -- Forcing renders -- How renders propagate - -This section is a bit long, but worth the read. We recommend coffee, tea, and/or snacks. - -## Reactive Programming - -Dioxus is one of a handful of Rust libraries that provide a "Reactive Programming Model". The term "Reactive programming" is a classification of programming paradigm – much like functional or imperative programming. This is a very important distinction since it affects how we _think_ about our code. - -Reactive programming is a programming model concerned with deriving computations from asynchronous data flow. Most reactive programs are comprised of datasources, intermediate computations, and a final result. - -We consider the rendered GUI to be the final result of our Dioxus apps. The datasources for our apps include local and global state. - -For example, the model presented in the figure below is comprised of two data sources: time and a constant. These values are passed through our computation graph to achieve a final result: `g`. - -![Reactive Model](https://upload.wikimedia.org/wikipedia/commons/thumb/e/e9/Reactive_programming_glitches.svg/440px-Reactive_programming_glitches.svg.png) - -Whenever our `seconds` variable changes, we will then reevaluate the computation for `t`. Because `g` relies on `t`, we will also reevaluate its computation too. Notice that we would've reevaluated the computation for `g` even if `t` didn't change because `seconds` is used to calculate `g`. - -However, if we somehow changed our constant from `1` to `2`, then we need to reevaluate `t`. If, for whatever reason, this change did not affect the result of `t`, then we wouldn't try to reevaluate `g`. - -In Reactive Programming, we don't think about whether or not we should reevaluate `t` or `g`; instead, we simply provide functions of computation and let the framework figure out the rest for us. - -In Rust, our reactive app would look something like: - -```rust, no_run -fn compute_g(t: i32, seconds: i32) -> bool { - t > seconds -} - -fn compute_t(constant: i32, seconds: i32) -> i32 { - constant + seconds -} - -fn compute_graph(constant: i32, seconds: i32) -> bool { - let t = compute_t(constant, seconds); - let g = compute_g(t, seconds); - g -} -``` - -## How is Dioxus Reactive? - -The Dioxus VirtualDom provides us a framework for reactive programming. When we build apps with dioxus, we need to provide our own datasources. This can be either initial props or some values fetched from the network. We then pass this data through our app into components through properties. - -If we represented the reactive graph presented above in Dioxus, it would look very similar: - -```rust, no_run -// Declare a component that holds our datasources and calculates `g` -fn RenderGraph(cx: Scope) -> Element { - let seconds = use_datasource(SECONDS); - let constant = use_state(cx, || 1); - - cx.render(rsx!( - RenderG { seconds: seconds } - RenderT { seconds: seconds, constant: constant } - )) -} - -// "calculate" g by rendering `t` and `seconds` -#[inline_props] -fn RenderG(cx: Scope, seconds: i32) -> Element { - cx.render(rsx!{ "There are {seconds} seconds remaining..." }) -} - -// calculate and render `t` in its own component -#[inline_props] -fn RenderT(cx: Scope, seconds: i32, constant: i32) -> Element { - let res = seconds + constant; - cx.render(rsx!{ "{res}" }) -} -``` - -With this app, we've defined three components. Our top-level component provides our datasources (the hooks), computation nodes (child components), and a final value (what's "rendered"). - -Now, whenever the `constant` changes, our `RenderT` component will be re-rendered. However, if `seconds` doesn't change, then we don't need to re-render `RenderG` because the input is the same. If `seconds` _does_ change, then both RenderG and RenderT will be reevaluated. - -Dioxus is "Reactive" because it provides this framework for us. All we need to do is write our own tiny units of computation and Dioxus figures out which components need to be reevaluated automatically. - -These extra checks and algorithms add some overhead, which is why you see projects like [Sycamore](http://sycamore-rs.netlify.app) and [SolidJS](http://solidjs.com) eliminating them altogether. Dioxus is _really_ fast, so we're willing to exchange the added overhead for improved developer experience. - -## How do we update values in our dataflow graph? - -Dioxus will automatically figure out how to regenerate parts of our app when datasources change. But how exactly can we update our data sources? - -In Dioxus there are two datasources: - -1. Local state in `use_hook` and all other hooks -2. Global state through `provide_context`. - -Technically, the root props of the VirtualDom are a third datasource, but since we cannot modify them, they are not worth talking about. - -### Local State - -For local state in hooks, Dioxus gives us the `use_hook` method which returns an `&mut T` without any requirements. This means raw hook values are not tracked by Dioxus. In fact, we could write a component that modifies a hook value directly: - -```rust, no_run -fn app(cx: Scope) -> Element { - let mut count = cx.use_hook(|_| 0); - cx.render(rsx!{ - button { - onclick: move |_| *count += 1, - "Count: {count}" - } - }) -} -``` - -However, when this value is written to, the component does not know to be reevaluated. We must explicitly tell Dioxus that this component is "dirty" and needs to be re-rendered. This is done through the `cx.needs_update` method: - -```rust, no_run -button { - onclick: move |_| { - *count += 1; - cx.needs_update(); - }, - "Count: {count}" -} -``` - -Now, whenever we click the button, the value will change and the component will be re-rendered. - -> Re-rendering is when Dioxus calls your function component _again_. Component functions will be called over and over throughout their lifetime, so they should be mostly side-effect free. - -### Understand this! - -Your component functions will be called ("rendered" in our lingo) for as long as the component is present in the tree. - -A single component will be called multiple times, modifying its own internal state or rendering new nodes with new values from its properties. - -### App-Global State - -With the `provide_context` and `consume_context` methods on `Scope`, we can share values to descendants without having to pass values through component props. This has the side-effect of making our datasources less obvious from a high-level perspective, but it makes our components more modular within the same codebase. - -To make app-global state easier to reason about, Dioxus makes all values provided through `provide_context` immutable. This means any library built on top of `provide_context` needs to use interior mutability to modify shared global state. - -In these cases, App-Global state needs to manually track which components need to be re-generated. - -To regenerate _any_ component in your app, you can get a handle to the Dioxus' internal scheduler through `schedule_update_any`: - -```rust, no_run -let force_render = cx.schedule_update_any(); - -// force a render of the root component -force_render(ScopeId(0)); -``` - -## What does it mean for a component to "re-render"? - -In our guides, we frequently use the phrase "re-render" to describe updates to our app. You'll often hear this paired with "preventing unnecessary re-renders." But what exactly does this mean? - -When we call `dioxus::desktop::launch`, Dioxus will create a new `Scope` object and call the component we gave it. Our `rsx!` calls will create new nodes which we return back to the VirtualDom. Dioxus will then look through these nodes for child components, call their functions, and so on until every component has been "rendered." We consider these nodes "rendered" because they were created because of our explicit actions. - -The tree of UI that dioxus creates will roughly look like the tree of components presented earlier: - -![Tree of UI](../images/component_tree.png) - -But what happens when we call `needs_update` after modifying some important state? Well, if Dioxus called our component's function again, then we would produce new, different nodes. In fact, this is exactly what Dioxus does! - -At this point, we have some old nodes and some new nodes. Again, we call this "rendering" because Dioxus had to create new nodes because of our explicit actions. Any time new nodes get created, our VirtualDom is being "rendered." - -These nodes are stored in an extremely efficient memory allocator called a "bump arena." For example, a div with a handler and attribute would be stored in memory in two locations: the "old" tree and the "new" tree. - -![Bump Arenas](../images/oldnew.png) - -From here, Dioxus computes the difference between these trees and updates the Real DOM to make it look like the new version of what we've declared. - -![Diffing](../images/diffing.png) - -## Suppressing Renders - -So, we know how to make Dioxus render, but how do we _stop_ it? What if we _know_ that our state didn't change and we shouldn't render and diff new nodes because they'll be exactly the same as the last time? - -In these cases, you want to reach for _memoization_. In Dioxus, memoization involves preventing a component from rendering again if its props didn't change since the last time it attempted to render. - -Visually, you can tell that a component will only re-render if the new value is sufficiently different than the old one. - -| props.val | re-render | -| --------- | --------- | -| 10 | true | -| 20 | true | -| 20 | false | -| 20 | false | -| 10 | true | -| 30 | false | - -This is why when you `derive(Props)`, you must also implement the `PartialEq` trait. To override the memoization strategy for a component, you can simply implement your own PartialEq. - -```rust, no_run -struct CustomProps { - val: i32, -} - -impl PartialEq for CustomProps { - fn partial_eq(&self, other: &Self) -> bool { - // we don't render components that have a val less than 5 - if other.val > 5 && self.val > 5{ - self.val == other.val - } - } -} -``` - -However, for components that borrow data, it doesn't make sense to implement PartialEq since the actual references in memory might be different. - -You can technically override this behavior by implementing the `Props` trait manually, though it's unsafe and easy to mess up: - -```rust, no_run -unsafe impl Properties for CustomProps { - fn memoize(&self, other &Self) -> bool { - self != other - } -} -``` - -TLDR: - -- Dioxus checks if props changed between renders -- If props changed according to PartialEq, Dioxus re-renders the component -- Props that have a lifetime (ie `<'a>`) will always be re-rendered - -## Wrapping Up - -Wow, that was a lot of material! - -Let's see if we can recap what was presented: - -- Reactive programming calculates a final value from datasources and computation -- Dioxus is "reactive" since it figures out which computations to check -- `schedule_update` must be called to mark a component as dirty -- dirty components will be re-rendered (called multiple times) to produce a new UI -- Renders can be suppressed with memoization - -This theory is crucial to understand how to compose components and how to control renders in your app. diff --git a/docs/guide/src/en/__unused/event_javascript.rs b/docs/guide/src/en/__unused/event_javascript.rs deleted file mode 100644 index d80501b46..000000000 --- a/docs/guide/src/en/__unused/event_javascript.rs +++ /dev/null @@ -1,26 +0,0 @@ - -## JavaScript Handlers - -Instead of passing a closure, you can also pass a string to event handlers – this lets you use JavaScript (if your renderer can execute JavaScript): - -```rust -{{#include ../../../examples/event_javascript.rs:rsx}} -``` - - -#![allow(non_snake_case)] -use dioxus::prelude::*; - -fn main() { - dioxus::desktop::launch(App); -} - -fn App(cx: Scope) -> Element { - cx.render(rsx! { - // ANCHOR: rsx - div { - onclick: "alert('hello world')", - } - // ANCHOR_END: rsx - }) -} diff --git a/docs/guide/src/en/__unused/fanout.md b/docs/guide/src/en/__unused/fanout.md deleted file mode 100644 index 63b7d3403..000000000 --- a/docs/guide/src/en/__unused/fanout.md +++ /dev/null @@ -1,61 +0,0 @@ -# Fanning Out - -One of the most reliable state management patterns in large Dioxus apps is `fan-out`. The fan-out pattern is the ideal way to structure your app to maximize code reuse, testability, and deterministic rendering. - -## The structure - -With `fan-out`, our individual components at "leaf" position of our VirtualDom are "pure", making them easily reusable, testable, and deterministic. For instance, the "title" bar of our app might be a fairly complicated component. - -```rust, no_run -#[derive(Props, PartialEq)] -struct TitlebarProps { - title: String, - subtitle: String, -} - -fn Titlebar(cx: Scope) -> Element { - cx.render(rsx!{ - div { - class: "titlebar" - h1 { "{cx.props.title}" } - h1 { "{cx.props.subtitle}" } - } - }) -} -``` - -If we used global state like use_context or fermi, we might be tempted to inject our `use_read` directly into the component. - -```rust, no_run -fn Titlebar(cx: Scope) -> Element { - let title = use_read(cx, TITLE); - let subtitle = use_read(cx, SUBTITLE); - - cx.render(rsx!{/* ui */}) -} -``` - -For many apps – this is a fine pattern, especially if the component is a one-off. However, if we want to reuse the component outside of this app, then we'll start to run into issues where our contexts are unavailable. - -## Fanning Out - -To enable our titlebar component to be used across apps, we want to lift our atoms upwards and out of the Titlebar component. We would organize a bunch of other components in this section of the app to share some of the same state. - -```rust, no_run -fn DocsiteTitlesection(cx: Scope) { - let title = use_read(cx, TITLE); - let subtitle = use_read(cx, SUBTITLE); - - let username = use_read(cx, USERNAME); - let points = use_read(cx, POINTS); - - cx.render(rsx!{ - TitleBar { title: title, subtitle: subtitle } - UserBar { username: username, points: points } - }) -} -``` - -This particular wrapper component unfortunately cannot be reused across apps. However, because it simply wraps other real elements, it doesn't have to. We are free to reuse our TitleBar and UserBar components across apps with ease. We also know that this particular component is plenty performant because the wrapper doesn't have any props and is always memoized. The only times this component re-renders is when any of the atoms change. - -This is the beauty of Dioxus – we always know where our components are likely to be re-rendered. Our wrapper components can easily prevent any large re-renders by simply memoizing their components. This system might not be as elegant or precise as signal systems found in libraries like Sycamore or SolidJS, but it is quite ergonomic. diff --git a/docs/guide/src/en/__unused/hello_world.md b/docs/guide/src/en/__unused/hello_world.md deleted file mode 100644 index d49172e47..000000000 --- a/docs/guide/src/en/__unused/hello_world.md +++ /dev/null @@ -1,14 +0,0 @@ -# "Hello, World" desktop app - - - -If you plan to develop extensions for the `Dioxus` ecosystem, please use the `dioxus` crate with the `core` feature to limit the amount of dependencies your project brings in. - - -### What is this `Scope` object? - -Coming from React, the `Scope` object might be confusing. In React, you'll want to store data between renders with hooks. However, hooks rely on global variables which make them difficult to integrate in multi-tenant systems like server-rendering. - -In Dioxus, you are given an explicit `Scope` object to control how the component renders and stores data. The `Scope` object provides a handful of useful APIs for features like suspense, rendering, and more. - -For now, just know that `Scope` lets you store state with hooks and render elements with `cx.render`. diff --git a/docs/guide/src/en/__unused/helpers.md b/docs/guide/src/en/__unused/helpers.md deleted file mode 100644 index 86c76bea8..000000000 --- a/docs/guide/src/en/__unused/helpers.md +++ /dev/null @@ -1,47 +0,0 @@ -# Helper Crates - -Because the Dioxus ecosystem is fairly young, there aren't a ton of third-party libraries designed to "get things done." That's where the Dioxus helper crates come in. These are officially supported crates built on top of existing libraries to solve some of the common barriers to building apps. - -## Router - -Quickly add a cross-platform router to structure your app. - -[Link](https://github.com/DioxusLabs/dioxus/tree/master/packages/router) - -## Fermi - -Global state as easy as `use_state`. - -[Link](https://github.com/DioxusLabs/dioxus/tree/master/packages/fermi) - -## Query - -This crate has yet to be developed! However, we do plan on providing a crate for good fetching and query support. - -## 3rd-party – Toast - -Toast notifications, curtesy of [@mrxiaozhuox](https://github.com/mrxiaozhuox). - -[Link](https://github.com/mrxiaozhuox/dioxus-toast) - -## 3rd-party – HeroIcon - -Collection of helpful hero icons, curtesy of [@autarch](https://github.com/autarch). - - -[Link](https://github.com/houseabsolute/dioxus-heroicons) - -## 3rd-party – Katex - -Draw beautiful equations, curtesy of [@oovm](https://github.com/oovm) - -[Link](https://github.com/oovm/katex-wasm/tree/dev/projects/dioxus-katex) - - -## 3rd-party – PrimsJS - -Highlight your code blocks with ease, curtesy of [@oovm](https://github.com/oovm) - -[Link](https://github.com/oovm/katex-wasm/tree/dev/projects/dioxus-katex) - - diff --git a/docs/guide/src/en/__unused/index.md b/docs/guide/src/en/__unused/index.md deleted file mode 100644 index d1863a465..000000000 --- a/docs/guide/src/en/__unused/index.md +++ /dev/null @@ -1,36 +0,0 @@ -# Managing State - -Every app you'll build with Dioxus will have some sort of state that needs to be maintained and updated as your users interact with it. However, managing state can be particularly challenging at times, and is frequently the source of bugs in many GUI frameworks. - -In this chapter, we'll cover the various ways to manage state, the appropriate terminology, various patterns, and some problems you might run into. - -## The Problem - -Why do people say state management is so difficult? What does it mean? - -Generally, state management is the code you need to write to ensure that your app renders the _correct_ content. If the user inputs a name, then you need to display the appropriate response – like alerts, validation, and disable/enable various elements on the page. Things can quickly become tricky if you need loading screens and cancellable tasks. - -For the simplest of apps, all of your state can enter the app from the root props. This is common in server-side rendering – we can collect all of the required state _before_ rendering the content. - -```rust, no_run -let all_content = get_all_content().await; - -let output = dioxus::ssr::render_lazy(rsx!{ - div { - RenderContent { content: all_content } - } -}); -``` - -With this incredibly simple setup, it is highly unlikely that you'll have rendering bugs. There simply is barely any state to manage. - -However, most of your apps will store state inside of the Dioxus VirtualDom – either through local state or global state. - -## Your options - -To deal with complexity, you have a couple of options: - -- Refactor state out of shared state and into reusable components and hooks. -- Lift state upwards to be spread across multiple components (fan out). -- Use the Context API to share state globally. -- Use a dedicated state management solution like Fermi. diff --git a/docs/guide/src/en/__unused/localstate.md b/docs/guide/src/en/__unused/localstate.md deleted file mode 100644 index fbc04272a..000000000 --- a/docs/guide/src/en/__unused/localstate.md +++ /dev/null @@ -1,107 +0,0 @@ -# Local State - -The first step to dealing with complexity in your app is to refactor your state to be purely local. This encourages good code reuse and prevents leakage of abstractions across component boundaries. - -## What it looks like - -Let's say we're managing the state for a list of Todos. Whenever we edit the todo, we want the list to update. We might've started building our app but putting everything into a single `use_ref`. - -```rust, no_run -struct Todo { - contents: String, - is_hovered: bool, - is_editing: bool, -} - -let todos = use_ref(cx, || vec![Todo::new()]); - -cx.render(rsx!{ - ul { - todos.read().iter().enumerate().map(|(id, todo)| rsx!{ - li { - onhover: move |_| *todos.write()[id].is_hovered = true, - h1 { "{todo.contents}" } - } - }) - } -}) -``` - -As shown above, whenever the todo is hovered, we want to set its state: - -```rust, no_run -todos.write()[0].is_hovered = true; -``` - -As the amount of interactions goes up, so does the complexity of our state. Should the "hover" state really be baked into our data model? - -Instead, let's refactor our Todo component to handle its own state: - -```rust, no_run -#[inline_props] -fn Todo<'a>(cx: Scope, todo: &'a Todo) -> Element { - let is_hovered = use_state(cx, || false); - - cx.render(rsx!{ - li { - h1 { "{todo.contents}" } - onhover: move |_| is_hovered.set(true), - } - }) -} -``` - -Now, we can simplify our Todo data model to get rid of local UI state: - -```rust, no_run -struct Todo { - contents: String, -} -``` - -This is not only better for encapsulation and abstraction, but it's only more performant! Whenever a Todo is hovered, we won't need to re-render _every_ Todo again – only the Todo that's currently being hovered. - -Wherever possible, you should try to refactor the "view" layer _out_ of your data model. - -## Immutability - -Storing all of your state inside a `use_ref` might be tempting. However, you'll quickly run into an issue where the `Ref` provided by `read()` "does not live long enough." An indeed – you can't return locally-borrowed value into the Dioxus tree. - -In these scenarios consider breaking your `use_ref` into individual `use_state`s. - -You might've started modeling your component with a struct and use_ref - -```rust, no_run -struct State { - count: i32, - color: &'static str, - names: HashMap -} - -// in the component -let state = use_ref(cx, State::new) -``` - -The "better" approach for this particular component would be to break the state apart into different values: - -```rust, no_run -let count = use_state(cx, || 0); -let color = use_state(cx, || "red"); -let names = use_state(cx, HashMap::new); -``` - -You might recognize that our "names" value is a HashMap – which is not terribly cheap to clone every time we update its value. To solve this issue, we _highly_ suggest using a library like [`im`](https://crates.io/crates/im) which will take advantage of structural sharing to make clones and mutations much cheaper. - -When combined with the `make_mut` method on `use_state`, you can get really succinct updates to collections: - -```rust, no_run -let todos = use_state(cx, im_rc::HashMap::default); - -todos.make_mut().insert("new todo", Todo { - contents: "go get groceries", -}); -``` - -## Moving on - -This particular local patterns are powerful but is not a cure-all for state management problems. Sometimes your state problems are much larger than just staying local to a component. diff --git a/docs/guide/src/en/__unused/memoization.md b/docs/guide/src/en/__unused/memoization.md deleted file mode 100644 index 4baa73be9..000000000 --- a/docs/guide/src/en/__unused/memoization.md +++ /dev/null @@ -1,26 +0,0 @@ -## Memoization - -Dioxus uses Memoization for a more efficient user interface. Memoization is the process in which we check if a component actually needs to be re-rendered when its props change. If a component's properties change but they wouldn't affect the output, then we don't need to re-render the component, saving time! - -For example, let's say we have a component that has two children: - -```rust, no_run -fn Demo(cx: Scope) -> Element { - // don't worry about these 2, we'll cover them later - let name = use_state(cx, || String::from("bob")); - let age = use_state(cx, || 21); - - cx.render(rsx!{ - Name { name: name } - Age { age: age } - }) -} -``` - -If `name` changes but `age` does not, then there is no reason to re-render our `Age` component since the contents of its props did not meaningfully change. - -Dioxus memoizes owned components. It uses `PartialEq` to determine if a component needs rerendering, or if it has stayed the same. This is why you must derive PartialEq! - -> This means you can always rely on props with `PartialEq` or no props at all to act as barriers in your app. This can be extremely useful when building larger apps where properties frequently change. By moving our state into a global state management solution, we can achieve precise, surgical re-renders, improving the performance of our app. - -Borrowed Props cannot be safely memoized. However, this is not a problem – Dioxus relies on the memoization of their parents to determine if they need to be rerendered. diff --git a/docs/guide/src/en/__unused/model_pattern.md b/docs/guide/src/en/__unused/model_pattern.md deleted file mode 100644 index c9bf9f6b5..000000000 --- a/docs/guide/src/en/__unused/model_pattern.md +++ /dev/null @@ -1,64 +0,0 @@ -## Using UseRef with "models" - -One option for state management that UseRef enables is the development of a "model" for your components. This particular pattern enables you to model your state with regular structs. - -For instance, our calculator example uses a struct to model the state. - -```rust, no_run - -struct Calculator { - display_value: String, - operator: Option, - waiting_for_operand: bool, - cur_val: f64, -} -``` - -Our component is really simple – we just call `use_ref` to get an initial calculator state. - -```rust, no_run -fn app(cx: Scope) -> Element { - let state = use_ref(cx, Calculator::new); - - cx.render(rsx!{ - // the rendering code - }) -} -``` - -In our UI, we can then use `read` and a helper method to get data out of the model. - -```rust, no_run -// Our accessor method -impl Calculator { - fn formatted_display(&self) -> String { - self.display_value - .parse::() - .unwrap() - .separated_string() - } -} - -// And then in the UI -cx.render(rsx!{ - div { [state.read().formatted_display()] } -}) -``` - -To modify the state, we can setup a helper method and then attach it to a callback. - -```rust, no_run -// our helper -impl Calculator { - fn clear_display(&mut self) { - self.display_value = "0".to_string() - } -} - -// our callback -cx.render(rsx!{ - button { - onclick: move |_| state.write().clear_display(), - } -}) -``` diff --git a/docs/guide/src/en/async/index.md b/docs/guide/src/en/async/index.md deleted file mode 100644 index a95671399..000000000 --- a/docs/guide/src/en/async/index.md +++ /dev/null @@ -1,9 +0,0 @@ -# Working with Async - -Often, apps need to interact with file systems, network interfaces, hardware, or timers. This chapter provides an overview of using async code in Dioxus. - -## The Runtime - -By default, Dioxus-Desktop ships with the `Tokio` runtime and automatically sets everything up for you. This is currently not configurable, though it would be easy to write an integration for Dioxus desktop that uses a different asynchronous runtime. - -Dioxus is not currently thread-safe, so any async code you write does *not* need to be `Send/Sync`. That means that you can use non-thread-safe structures like `Cell`, `Rc`, and `RefCell`. diff --git a/docs/guide/src/en/async/spawn.md b/docs/guide/src/en/async/spawn.md deleted file mode 100644 index 2f86ad159..000000000 --- a/docs/guide/src/en/async/spawn.md +++ /dev/null @@ -1,19 +0,0 @@ -# Spawning Futures - -The `use_future` and `use_coroutine` hooks are useful if you want to unconditionally spawn the future. Sometimes, though, you'll want to only spawn a future in response to an event, such as a mouse click. For example, suppose you need to send a request when the user clicks a "log in" button. For this, you can use `cx.spawn`: - -```rust, no_run -{{#include ../../../examples/spawn.rs:spawn}} -``` - -> Note: `spawn` will always spawn a _new_ future. You most likely don't want to call it on every render. - -Calling `spawn` will give you a `JoinHandle` which lets you cancel or pause the future. - -## Spawning Tokio Tasks - -Sometimes, you might want to spawn a background task that needs multiple threads or talk to hardware that might block your app code. In these cases, we can directly spawn a Tokio task from our future. For Dioxus-Desktop, your task will be spawned onto Tokio's Multithreaded runtime: - -```rust, no_run -{{#include ../../../examples/spawn.rs:tokio}} -``` diff --git a/docs/guide/src/en/async/use_coroutine.md b/docs/guide/src/en/async/use_coroutine.md deleted file mode 100644 index d42905be5..000000000 --- a/docs/guide/src/en/async/use_coroutine.md +++ /dev/null @@ -1,204 +0,0 @@ -# Coroutines - -Another tool in your async toolbox are coroutines. Coroutines are futures that can be manually stopped, started, paused, and resumed. - -Like regular futures, code in a coroutine will run until the next `await` point before yielding. This low-level control over asynchronous tasks is quite powerful, allowing for infinitely looping tasks like WebSocket polling, background timers, and other periodic actions. - -## `use_coroutine` - -The `use_coroutine` hook allows you to create a coroutine. Most coroutines we write will be polling loops using async/await. - -```rust, no_run -fn app(cx: Scope) -> Element { - let ws: &UseCoroutine<()> = use_coroutine(cx, |rx| async move { - // Connect to some sort of service - let mut conn = connect_to_ws_server().await; - - // Wait for data on the service - while let Some(msg) = conn.next().await { - // handle messages - } - }); -} -``` - -For many services, a simple async loop will handle the majority of use cases. - -However, if we want to temporarily disable the coroutine, we can "pause" it using the `pause` method, and "resume" it using the `resume` method: - -```rust, no_run -let sync: &UseCoroutine<()> = use_coroutine(cx, |rx| async move { - // code for syncing -}); - -if sync.is_running() { - cx.render(rsx!{ - button { - onclick: move |_| sync.pause(), - "Disable syncing" - } - }) -} else { - cx.render(rsx!{ - button { - onclick: move |_| sync.resume(), - "Enable syncing" - } - }) -} -``` - -This pattern is where coroutines are extremely useful – instead of writing all the complicated logic for pausing our async tasks like we would with JavaScript promises, the Rust model allows us to just not poll our future. - -## Yielding Values - -To yield values from a coroutine, simply bring in a `UseState` handle and set the value whenever your coroutine completes its work. - -The future must be `'static` – so any values captured by the task cannot carry any references to `cx`, such as a `UseState`. - -You can use [to_owned](https://doc.rust-lang.org/std/borrow/trait.ToOwned.html#tymethod.to_owned) to create a clone of the hook handle which can be moved into the async closure. - -```rust, no_run -let sync_status = use_state(cx, || Status::Launching); -let sync_task = use_coroutine(cx, |rx: UnboundedReceiver| { - let sync_status = sync_status.to_owned(); - async move { - loop { - delay_ms(1000).await; - sync_status.set(Status::Working); - } - } -}) -``` - -To make this a bit less verbose, Dioxus exports the `to_owned!` macro which will create a binding as shown above, which can be quite helpful when dealing with many values. - -```rust, no_run -let sync_status = use_state(cx, || Status::Launching); -let load_status = use_state(cx, || Status::Launching); -let sync_task = use_coroutine(cx, |rx: UnboundedReceiver| { - to_owned![sync_status, load_status]; - async move { - // ... - } -}) -``` - -## Sending Values - -You might've noticed the `use_coroutine` closure takes an argument called `rx`. What is that? Well, a common pattern in complex apps is to handle a bunch of async code at once. With libraries like Redux Toolkit, managing multiple promises at once can be challenging and a common source of bugs. - -With Coroutines, we can centralize our async logic. The `rx` parameter is an Channel that allows code external to the coroutine to send data _into_ the coroutine. Instead of looping on an external service, we can loop on the channel itself, processing messages from within our app without needing to spawn a new future. To send data into the coroutine, we would call "send" on the handle. - -```rust, no_run -use futures_util::stream::StreamExt; - -enum ProfileUpdate { - SetUsername(String), - SetAge(i32) -} - -let profile = use_coroutine(cx, |mut rx: UnboundedReciver| async move { - let mut server = connect_to_server().await; - - while let Ok(msg) = rx.next().await { - match msg { - ProfileUpdate::SetUsername(name) => server.update_username(name).await, - ProfileUpdate::SetAge(age) => server.update_age(age).await, - } - } -}); - - -cx.render(rsx!{ - button { - onclick: move |_| profile.send(ProfileUpdate::SetUsername("Bob".to_string())), - "Update username" - } -}) -``` - -> Note: In order to use/run the `rx.next().await` statement you will need to extend the [`Stream`] trait (used by [`UnboundedReceiver`]) by adding 'futures_util' as a dependency to your project and adding the `use futures_util::stream::StreamExt;`. - -For sufficiently complex apps, we could build a bunch of different useful "services" that loop on channels to update the app. - -```rust, no_run -let profile = use_coroutine(cx, profile_service); -let editor = use_coroutine(cx, editor_service); -let sync = use_coroutine(cx, sync_service); - -async fn profile_service(rx: UnboundedReceiver) { - // do stuff -} - -async fn sync_service(rx: UnboundedReceiver) { - // do stuff -} - -async fn editor_service(rx: UnboundedReceiver) { - // do stuff -} -``` - -We can combine coroutines with [Fermi](https://docs.rs/fermi/latest/fermi/index.html) to emulate Redux Toolkit's Thunk system with much less headache. This lets us store all of our app's state _within_ a task and then simply update the "view" values stored in Atoms. It cannot be understated how powerful this technique is: we get all the perks of native Rust tasks with the optimizations and ergonomics of global state. This means your _actual_ state does not need to be tied up in a system like Fermi or Redux – the only Atoms that need to exist are those that are used to drive the display/UI. - -```rust, no_run -static USERNAME: Atom = Atom(|_| "default".to_string()); - -fn app(cx: Scope) -> Element { - let atoms = use_atom_root(cx); - - use_coroutine(cx, |rx| sync_service(rx, atoms.clone())); - - cx.render(rsx!{ - Banner {} - }) -} - -fn Banner(cx: Scope) -> Element { - let username = use_read(cx, &USERNAME); - - cx.render(rsx!{ - h1 { "Welcome back, {username}" } - }) -} -``` - -Now, in our sync service, we can structure our state however we want. We only need to update the view values when ready. - -```rust, no_run -use futures_util::stream::StreamExt; - -enum SyncAction { - SetUsername(String), -} - -async fn sync_service(mut rx: UnboundedReceiver, atoms: AtomRoot) { - let username = atoms.write(&USERNAME); - let errors = atoms.write(&ERRORS); - - while let Ok(msg) = rx.next().await { - match msg { - SyncAction::SetUsername(name) => { - if set_name_on_server(&name).await.is_ok() { - username.set(name); - } else { - errors.make_mut().push("SetUsernameFailed"); - } - } - } - } -} -``` - -## Automatic injection into the Context API - -Coroutine handles are automatically injected through the context API. You can use the `use_coroutine_handle` hook with the message type as a generic to fetch a handle. - -```rust, no_run -fn Child(cx: Scope) -> Element { - let sync_task = use_coroutine_handle::(cx); - - sync_task.send(SyncAction::SetUsername); -} -``` diff --git a/docs/guide/src/en/async/use_effect.md b/docs/guide/src/en/async/use_effect.md deleted file mode 100644 index 7c20e3589..000000000 --- a/docs/guide/src/en/async/use_effect.md +++ /dev/null @@ -1,41 +0,0 @@ -# UseEffect - -[`use_effect`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_effect.html) lets you run a callback that returns a future, which will be re-run when its [dependencies](#dependencies) change. This is useful to syncrhonize with external events. - -## Dependencies - -You can make the callback re-run when some value changes. For example, you might want to fetch a user's data only when the user id changes. You can provide a tuple of "dependencies" to the hook. It will automatically re-run it when any of those dependencies change. - -## Example - -```rust, no_run -#[inline_props] -fn Profile(cx: Scope, id: usize) -> Element { - let name = use_state(cx, || None); - - // Only fetch the user data when the id changes. - use_effect(cx, (id,), |(id,)| { - to_owned![name]; - async move { - let user = fetch_user(id).await; - name.set(user.name); - } - }); - - // Because the dependencies are empty, this will only run once. - // An empty tuple is always equal to an empty tuple. - use_effect(cx, (), |()| async move { - println!("Hello, World!"); - }); - - let name = name.get().clone().unwrap_or("Loading...".to_string()); - - render!( - p { "{name}" } - ) -} - -fn app(cx: Scope) -> Element { - render!(Profile { id: 0 }) -} -``` diff --git a/docs/guide/src/en/async/use_future.md b/docs/guide/src/en/async/use_future.md deleted file mode 100644 index c7b262c61..000000000 --- a/docs/guide/src/en/async/use_future.md +++ /dev/null @@ -1,31 +0,0 @@ -# UseFuture - -[`use_future`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_future.html) lets you run an async closure, and provides you with its result. - -For example, we can make an API request (using [reqwest](https://docs.rs/reqwest/latest/reqwest/index.html)) inside `use_future`: - -```rust, no_run -{{#include ../../../examples/use_future.rs:use_future}} -``` - -The code inside `use_future` will be submitted to the Dioxus scheduler once the component has rendered. - -We can use `.value()` to get the result of the future. On the first run, since there's no data ready when the component loads, its value will be `None`. However, once the future is finished, the component will be re-rendered and the value will now be `Some(...)`, containing the return value of the closure. - -We can then render that result: - -```rust, no_run -{{#include ../../../examples/use_future.rs:render}} -``` - -## Restarting the Future - -The `UseFuture` handle provides a `restart` method. It can be used to execute the future again, producing a new value. - -## Dependencies - -Often, you will need to run the future again every time some value (e.g. a prop) changes. Rather than calling `restart` manually, you can provide a tuple of "dependencies" to the hook. It will automatically re-run the future when any of those dependencies change. Example: - -```rust, no_run -{{#include ../../../examples/use_future.rs:dependency}} -``` diff --git a/docs/guide/src/en/best_practices/antipatterns.md b/docs/guide/src/en/best_practices/antipatterns.md deleted file mode 100644 index 771ffe75f..000000000 --- a/docs/guide/src/en/best_practices/antipatterns.md +++ /dev/null @@ -1,33 +0,0 @@ -# Antipatterns - -This example shows what not to do and provides a reason why a given pattern is considered an "AntiPattern". Most anti-patterns are considered wrong for performance or code re-usability reasons. - -## Unnecessarily Nested Fragments - -Fragments don't mount a physical element to the DOM immediately, so Dioxus must recurse into its children to find a physical DOM node. This process is called "normalization". This means that deeply nested fragments make Dioxus perform unnecessary work. Prefer one or two levels of fragments / nested components until presenting a true DOM element. - -Only Component and Fragment nodes are susceptible to this issue. Dioxus mitigates this with components by providing an API for registering shared state without the Context Provider pattern. - -```rust, no_run -{{#include ../../../examples/anti_patterns.rs:nested_fragments}} -``` - -## Incorrect Iterator Keys - -As described in the [dynamic rendering chapter](../interactivity/dynamic_rendering.md#the-key-attribute), list items must have unique keys that are associated with the same items across renders. This helps Dioxus associate state with the contained components and ensures good diffing performance. Do not omit keys, unless you know that the list will never change. - -```rust, no_run -{{#include ../../../examples/anti_patterns.rs:iter_keys}} -``` - -## Avoid Interior Mutability in Props - -While it is technically acceptable to have a `Mutex` or a `RwLock` in the props, they will be difficult to use. - -Suppose you have a struct `User` containing the field `username: String`. If you pass a `Mutex` prop to a `UserComponent` component, that component may wish to pass the username as a `&str` prop to a child component. However, it cannot pass that borrowed field down, since it only would live as long as the `Mutex`'s lock, which belongs to the `UserComponent` function. Therefore, the component will be forced to clone the `username` field. - -## Avoid Updating State During Render - -Every time you update the state, Dioxus needs to re-render the component – this is inefficient! Consider refactoring your code to avoid this. - -Also, if you unconditionally update the state during render, it will be re-rendered in an infinite loop. diff --git a/docs/guide/src/en/best_practices/error_handling.md b/docs/guide/src/en/best_practices/error_handling.md deleted file mode 100644 index d16d04347..000000000 --- a/docs/guide/src/en/best_practices/error_handling.md +++ /dev/null @@ -1,153 +0,0 @@ -# Error handling - -A selling point of Rust for web development is the reliability of always knowing where errors can occur and being forced to handle them - -However, we haven't talked about error handling at all in this guide! In this chapter, we'll cover some strategies in handling errors to ensure your app never crashes. - -## The simplest – returning None - -Astute observers might have noticed that `Element` is actually a type alias for `Option`. You don't need to know what a `VNode` is, but it's important to recognize that we could actually return nothing at all: - -```rust, no_run -fn App(cx: Scope) -> Element { - None -} -``` - -This lets us add in some syntactic sugar for operations we think _shouldn't_ fail, but we're still not confident enough to "unwrap" on. - -> The nature of `Option` might change in the future as the `try` trait gets upgraded. - -```rust, no_run -fn App(cx: Scope) -> Element { - // immediately return "None" - let name = cx.use_hook(|_| Some("hi"))?; -} -``` - -## Early return on result - -Because Rust can't accept both Options and Results with the existing try infrastructure, you'll need to manually handle Results. This can be done by converting them into Options or by explicitly handling them. - -```rust, no_run -fn App(cx: Scope) -> Element { - // Convert Result to Option - let name = cx.use_hook(|_| "1.234").parse().ok()?; - - - // Early return - let count = cx.use_hook(|_| "1.234"); - let val = match count.parse() { - Ok(val) => val - Err(err) => return cx.render(rsx!{ "Parsing failed" }) - }; -} -``` - -Notice that while hooks in Dioxus do not like being called in conditionals or loops, they _are_ okay with early returns. Returning an error state early is a completely valid way of handling errors. - -## Match results - -The next "best" way of handling errors in Dioxus is to match on the error locally. This is the most robust way of handling errors, though it doesn't scale to architectures beyond a single component. - -To do this, we simply have an error state built into our component: - -```rust, no_run -let err = use_state(cx, || None); -``` - -Whenever we perform an action that generates an error, we'll set that error state. We can then match on the error in a number of ways (early return, return Element, etc). - -```rust, no_run -fn Commandline(cx: Scope) -> Element { - let error = use_state(cx, || None); - - cx.render(match *error { - Some(error) => rsx!( - h1 { "An error occured" } - ) - None => rsx!( - input { - oninput: move |_| error.set(Some("bad thing happened!")), - } - ) - }) -} -``` - -## Passing error states through components - -If you're dealing with a handful of components with minimal nesting, you can just pass the error handle into child components. - -```rust, no_run -fn Commandline(cx: Scope) -> Element { - let error = use_state(cx, || None); - - if let Some(error) = **error { - return cx.render(rsx!{ "An error occured" }); - } - - cx.render(rsx!{ - Child { error: error.clone() } - Child { error: error.clone() } - Child { error: error.clone() } - Child { error: error.clone() } - }) -} -``` - -Much like before, our child components can manually set the error during their own actions. The advantage to this pattern is that we can easily isolate error states to a few components at a time, making our app more predictable and robust. - -## Going global - -A strategy for handling cascaded errors in larger apps is through signaling an error using global state. This particular pattern involves creating an "error" context, and then setting it wherever relevant. This particular method is not as "sophisticated" as React's error boundary, but it is more fitting for Rust. - -To get started, consider using a built-in hook like `use_context` and `use_context_provider` or Fermi. Of course, it's pretty easy to roll your own hook too. - -At the "top" of our architecture, we're going to want to explicitly declare a value that could be an error. - -```rust, no_run -enum InputError { - None, - TooLong, - TooShort, -} - -static INPUT_ERROR: Atom = Atom(|_| InputError::None); -``` - -Then, in our top level component, we want to explicitly handle the possible error state for this part of the tree. - -```rust, no_run -fn TopLevel(cx: Scope) -> Element { - let error = use_read(cx, &INPUT_ERROR); - - match error { - TooLong => return cx.render(rsx!{ "FAILED: Too long!" }), - TooShort => return cx.render(rsx!{ "FAILED: Too Short!" }), - _ => {} - } -} -``` - -Now, whenever a downstream component has an error in its actions, it can simply just set its own error state: - -```rust, no_run -fn Commandline(cx: Scope) -> Element { - let set_error = use_set(cx, &INPUT_ERROR); - - cx.render(rsx!{ - input { - oninput: move |evt| { - if evt.value.len() > 20 { - set_error(InputError::TooLong); - } - } - } - }) -} -``` - -This approach to error handling is best in apps that have "well defined" error states. Consider using a crate like `thiserror` or `anyhow` to simplify the generation of the error types. - -This pattern is widely popular in many contexts and is particularly helpful whenever your code generates a non-recoverable error. You can gracefully capture these "global" error states without panicking or mucking up state. diff --git a/docs/guide/src/en/best_practices/index.md b/docs/guide/src/en/best_practices/index.md deleted file mode 100644 index 6b9f0ed1d..000000000 --- a/docs/guide/src/en/best_practices/index.md +++ /dev/null @@ -1,14 +0,0 @@ -# Best Practices - -## Reusable Components - -As much as possible, break your code down into small, reusable components and hooks, instead of implementing large chunks of the UI in a single component. This will help you keep the code maintainable – it is much easier to e.g. add, remove or re-order parts of the UI if it is organized in components. - -Organize your components in modules to keep the codebase easy to navigate! - -## Minimize State Dependencies - -While it is possible to share state between components, this should only be done when necessary. Any component that is associated with a particular state object needs to be re-rendered when that state changes. For this reason: - -- Keep state local to a component if possible -- When sharing state through props, only pass down the specific data necessary diff --git a/docs/guide/src/en/contributing/guiding_principles.md b/docs/guide/src/en/contributing/guiding_principles.md deleted file mode 100644 index 5c730d622..000000000 --- a/docs/guide/src/en/contributing/guiding_principles.md +++ /dev/null @@ -1,37 +0,0 @@ -# Overall Goals - -This document outlines some of the overall goals for Dioxus. These goals are not set in stone, but they represent general guidelines for the project. - -The goal of Dioxus is to make it easy to build **cross-platform applications that scale**. - -## Cross-Platform - -Dioxus is designed to be cross-platform by default. This means that it should be easy to build applications that run on the web, desktop, and mobile. However, Dioxus should also be flexible enough to allow users to opt into platform-specific features when needed. The `use_eval` is one example of this. By default, Dioxus does not assume that the platform supports JavaScript, but it does provide a hook that allows users to opt into JavaScript when needed. - -## Performance - -As Dioxus applications grow, they should remain relatively performant without the need for manual optimizations. There will be cases where manual optimizations are needed, but Dioxus should try to make these cases as rare as possible. - -One of the benefits of the core architecture of Dioxus is that it delivers reasonable performance even when components are rerendered often. It is based on a Virtual Dom which performs diffing which should prevent unnecessary re-renders even when large parts of the component tree are rerun. On top of this, Dioxus groups static parts of the RSX tree together to skip diffing them entirely. - -## Type Safety - -As teams grow, the Type safety of Rust is a huge advantage. Dioxus should leverage this advantage to make it easy to build applications with large teams. - -To take full advantage of Rust's type system, Dioxus should try to avoid exposing public `Any` types and string-ly typed APIs where possible. - -## Developer Experience - -Dioxus should be easy to learn and ergonomic to use. - -- The API of Dioxus attempts to remain close to React's API where possible. This makes it easier for people to learn Dioxus if they already know React - -- We can avoid the tradeoff between simplicity and flexibility by providing multiple layers of API: One for the very common use case, one for low-level control - - - Hooks: the hooks crate has the most common use cases, but `cx.hook` provides a way to access the underlying persistent reference if needed. - - The builder pattern in platform Configs: The builder pattern is used to default to the most common use case, but users can change the defaults if needed. - -- Documentation: - - All public APIs should have rust documentation - - Examples should be provided for all public features. These examples both serve as documentation and testing. They are checked by CI to ensure that they continue to compile - - The most common workflows should be documented in the guide diff --git a/docs/guide/src/en/contributing/index.md b/docs/guide/src/en/contributing/index.md deleted file mode 100644 index d70dc6f8d..000000000 --- a/docs/guide/src/en/contributing/index.md +++ /dev/null @@ -1,57 +0,0 @@ -# Contributing - -Development happens in the [Dioxus GitHub repository](https://github.com/DioxusLabs/dioxus). If you've found a bug or have an idea for a feature, please submit an issue (but first check if someone hasn't [done it already](https://github.com/DioxusLabs/dioxus/issues)). - -[GitHub discussions](https://github.com/DioxusLabs/dioxus/discussions) can be used as a place to ask for help or talk about features. You can also join [our Discord channel](https://discord.gg/XgGxMSkvUM) where some development discussion happens. - -## Improving Docs - -If you'd like to improve the docs, PRs are welcome! Both Rust docs ([source](https://github.com/DioxusLabs/dioxus/tree/master/packages)) and this guide ([source](https://github.com/DioxusLabs/dioxus/tree/master/docs/guide)) can be found in the GitHub repo. - -## Working on the Ecosystem - -Part of what makes React great is the rich ecosystem. We'd like the same for Dioxus! So if you have a library in mind that you'd like to write and many people would benefit from, it will be appreciated. You can [browse npm.js](https://www.npmjs.com/search?q=keywords:react-component) for inspiration. Once you are done, add your library to the [awesome dioxus](https://github.com/DioxusLabs/awesome-dioxus) list or share it in the `#I-made-a-thing` channel on [Discord](https://discord.gg/XgGxMSkvUM). - -## Bugs & Features - -If you've fixed [an open issue](https://github.com/DioxusLabs/dioxus/issues), feel free to submit a PR! You can also take a look at [the roadmap](./roadmap.md) and work on something in there. Consider [reaching out](https://discord.gg/XgGxMSkvUM) to the team first to make sure everyone's on the same page, and you don't do useless work! - -All pull requests (including those made by a team member) must be approved by at least one other team member. -Larger, more nuanced decisions about design, architecture, breaking changes, trade-offs, etc. are made by team consensus. - -## Tools - -The following tools can be helpful when developing Dioxus. Many of these tools are used in the CI pipeline. Running them locally before submitting a PR instead of waiting for CI can save time. - -- All code is tested with [cargo test](https://doc.rust-lang.org/cargo/commands/cargo-test.html) - -```sh -cargo fmt --all -``` - -- All code is formatted with [rustfmt](https://github.com/rust-lang/rustfmt) - -```sh -cargo check --workspace --examples --tests -``` - -- All code is linted with [Clippy](https://doc.rust-lang.org/clippy/) - -```sh -cargo clippy --workspace --examples --tests -- -D warnings -``` - -- Browser tests are automated with [Playwright](https://playwright.dev/docs/intro#installing-playwright) - -```sh -npx playwright test -``` - -- Crates that use unsafe are checked for undefined behavior with [MIRI](https://github.com/rust-lang/miri). MIRI can be helpful to debug what unsafe code is causing issues. Only code that does not interact with system calls can be checked with MIRI. Currently, this is used for the two MIRI tests in `dioxus-core` and `dioxus-native-core`. - -```sh -cargo miri test --package dioxus-core --test miri_stress -cargo miri test --package dioxus-native-core --test miri_native -``` - -- [Rust analyzer](https://rust-analyzer.github.io/) can be very helpful for quick feedback in your IDE. diff --git a/docs/guide/src/en/contributing/project_structure.md b/docs/guide/src/en/contributing/project_structure.md deleted file mode 100644 index 38b6cbde4..000000000 --- a/docs/guide/src/en/contributing/project_structure.md +++ /dev/null @@ -1,50 +0,0 @@ -# Project Struture - -There are many packages in the Dioxus organization. This document will help you understand the purpose of each package and how they fit together. - -## Renderers - -- [Desktop](https://github.com/DioxusLabs/dioxus/tree/master/packages/desktop): A renderer that runs Dioxus applications natively, but renders them with the system webview. -- [Mobile](https://github.com/DioxusLabs/dioxus/tree/master/packages/mobile): A renderer that runs Dioxus applications natively, but renders them with the system webview. This is currently a copy of the desktop renderer. -- [Web](https://github.com/DioxusLabs/dioxus/tree/master/packages/Web): Renders Dioxus applications in the browser by compiling to WASM and manipulating the DOM. -- [Liveview](https://github.com/DioxusLabs/dioxus/tree/master/packages/liveview): A renderer that runs on the server, and renders using a websocket proxy in the browser. -- [Rink](https://github.com/DioxusLabs/dioxus/tree/master/packages/rink): A renderer that renders a HTML-like tree into a terminal. -- [TUI](https://github.com/DioxusLabs/dioxus/tree/master/packages/dioxus-tui): A renderer that uses Rink to render a Dioxus application in a terminal. -- [Blitz-Core](https://github.com/DioxusLabs/blitz/tree/master/blitz-core): An experimental native renderer that renders a HTML-like tree using WGPU. -- [Blitz](https://github.com/DioxusLabs/blitz): An experimental native renderer that uses Blitz-Core to render a Dioxus application using WGPU. -- [SSR](https://github.com/DioxusLabs/dioxus/tree/master/packages/ssr): A renderer that runs Dioxus applications on the server, and renders them to HTML. - -## State Management/Hooks - -- [Hooks](https://github.com/DioxusLabs/dioxus/tree/master/packages/hooks): A collection of common hooks for Dioxus applications -- [Signals](https://github.com/DioxusLabs/dioxus/tree/master/packages/signals): A experimental state management library for Dioxus applications. This currently contains a `Copy` version of UseRef -- [Dioxus STD](https://github.com/DioxusLabs/dioxus-std): A collection of platform agnostic hooks to interact with system interfaces (The clipboard, camera, etc.). -- [Fermi](https://github.com/DioxusLabs/dioxus/tree/master/packages/fermi): A global state management library for Dioxus applications. - [Router](https://github.com/DioxusLabs/dioxus/tree/master/packages/router): A client-side router for Dioxus applications - -## Core utilities - -- [core](https://github.com/DioxusLabs/dioxus/tree/master/packages/core): The core virtual dom implementation every Dioxus application uses - - You can read more about the archetecture of the core [in this blog post](https://dioxuslabs.com/blog/templates-diffing/) and the [custom renderer section of the guide](../custom_renderer/index.md) -- [RSX](https://github.com/DioxusLabs/dioxus/tree/master/packages/RSX): The core parsing for RSX used for hot reloading, autoformatting, and the macro -- [core-macro](https://github.com/DioxusLabs/dioxus/tree/master/packages/core-macro): The rsx! macro used to write Dioxus applications. (This is a wrapper over the RSX crate) -- [HTML macro](https://github.com/DioxusLabs/dioxus-html-macro): A html-like alternative to the RSX macro - -## Native Renderer Utilities - -- [native-core](https://github.com/DioxusLabs/dioxus/tree/master/packages/native-core): Incrementally computed tree of states (mostly styles) - - You can read more about how native-core can help you build native renderers in the [custom renderer section of the guide](../custom_renderer/index.html#native-core) -- [native-core-macro](https://github.com/DioxusLabs/dioxus/tree/master/packages/native-core-macro): A helper macro for native core -- [Taffy](https://github.com/DioxusLabs/taffy): Layout engine powering Blitz-Core, Rink, and Bevy UI - -## Web renderer tooling - -- [HTML](https://github.com/DioxusLabs/dioxus/tree/master/packages/html): defines html specific elements, events, and attributes -- [Interpreter](https://github.com/DioxusLabs/dioxus/tree/master/packages/interpreter): defines browser bindings used by the web and desktop renderers - -## Developer tooling - -- [hot-reload](https://github.com/DioxusLabs/dioxus/tree/master/packages/hot-reload): Macro that uses the RSX crate to hot reload static parts of any rsx! macro. This macro works with any non-web renderer with an [integration](https://crates.io/crates/dioxus-hot-reload) -- [autofmt](https://github.com/DioxusLabs/dioxus/tree/master/packages/autofmt): Formats RSX code -- [rsx-rosetta](https://github.com/DioxusLabs/dioxus/tree/master/packages/RSX-rosetta): Handles conversion between HTML and RSX -- [CLI](https://github.com/DioxusLabs/cli): A Command Line Interface and VSCode extension to assist with Dioxus usage diff --git a/docs/guide/src/en/contributing/roadmap.md b/docs/guide/src/en/contributing/roadmap.md deleted file mode 100644 index fba5913db..000000000 --- a/docs/guide/src/en/contributing/roadmap.md +++ /dev/null @@ -1,138 +0,0 @@ -# Roadmap & Feature-set - -This feature set and roadmap can help you decide if what Dioxus can do today works for you. - -If a feature that you need doesn't exist or you want to contribute to projects on the roadmap, feel free to get involved by [joining the discord](https://discord.gg/XgGxMSkvUM). - -Generally, here's the status of each platform: - -- **Web**: Dioxus is a great choice for pure web-apps – especially for CRUD/complex apps. However, it does lack the ecosystem of React, so you might be missing a component library or some useful hook. - -- **SSR**: Dioxus is a great choice for pre-rendering, hydration, and rendering HTML on a web endpoint. Be warned – the VirtualDom is not (currently) `Send + Sync`. - -- **Desktop**: You can build very competent single-window desktop apps right now. However, multi-window apps require support from Dioxus core and are not ready. - -- **Mobile**: Mobile support is very young. You'll be figuring things out as you go and there are not many support crates for peripherals. - -- **LiveView**: LiveView support is very young. You'll be figuring things out as you go. Thankfully, none of it is too hard and any work can be upstreamed into Dioxus. - -## Features - ---- - -| Feature | Status | Description | -| ------------------------- | ------ | -------------------------------------------------------------------- | -| Conditional Rendering | ✅ | if/then to hide/show component | -| Map, Iterator | ✅ | map/filter/reduce to produce rsx! | -| Keyed Components | ✅ | advanced diffing with keys | -| Web | ✅ | renderer for web browser | -| Desktop (webview) | ✅ | renderer for desktop | -| Shared State (Context) | ✅ | share state through the tree | -| Hooks | ✅ | memory cells in components | -| SSR | ✅ | render directly to string | -| Component Children | ✅ | cx.children() as a list of nodes | -| Headless components | ✅ | components that don't return real elements | -| Fragments | ✅ | multiple elements without a real root | -| Manual Props | ✅ | Manually pass in props with spread syntax | -| Controlled Inputs | ✅ | stateful wrappers around inputs | -| CSS/Inline Styles | ✅ | syntax for inline styles/attribute groups | -| Custom elements | ✅ | Define new element primitives | -| Suspense | ✅ | schedule future render from future/promise | -| Integrated error handling | ✅ | Gracefully handle errors with ? syntax | -| NodeRef | ✅ | gain direct access to nodes | -| Re-hydration | ✅ | Pre-render to HTML to speed up first contentful paint | -| Jank-Free Rendering | ✅ | Large diffs are segmented across frames for silky-smooth transitions | -| Effects | ✅ | Run effects after a component has been committed to render | -| Portals | 🛠 | Render nodes outside of the traditional tree structure | -| Cooperative Scheduling | 🛠 | Prioritize important events over non-important events | -| Server Components | 🛠 | Hybrid components for SPA and Server | -| Bundle Splitting | 👀 | Efficiently and asynchronously load the app | -| Lazy Components | 👀 | Dynamically load the new components as the page is loaded | -| 1st class global state | ✅ | redux/recoil/mobx on top of context | -| Runs natively | ✅ | runs as a portable binary w/o a runtime (Node) | -| Subtree Memoization | ✅ | skip diffing static element subtrees | -| High-efficiency templates | ✅ | rsx! calls are translated to templates on the DOM's side | -| Compile-time correct | ✅ | Throw errors on invalid template layouts | -| Heuristic Engine | ✅ | track component memory usage to minimize future allocations | -| Fine-grained reactivity | 👀 | Skip diffing for fine-grain updates | - -- ✅ = implemented and working -- 🛠 = actively being worked on -- 👀 = not yet implemented or being worked on - -## Roadmap - -These Features are planned for the future of Dioxus: - -### Core - -- [x] Release of Dioxus Core -- [x] Upgrade documentation to include more theory and be more comprehensive -- [x] Support for HTML-side templates for lightning-fast dom manipulation -- [ ] Support for multiple renderers for same virtualdom (subtrees) -- [ ] Support for ThreadSafe (Send + Sync) -- [ ] Support for Portals - -### SSR - -- [x] SSR Support + Hydration -- [ ] Integrated suspense support for SSR - -### Desktop - -- [ ] Declarative window management -- [ ] Templates for building/bundling -- [ ] Access to Canvas/WebGL context natively - -### Mobile - -- [ ] Mobile standard library - - [ ] GPS - - [ ] Camera - - [ ] filesystem - - [ ] Biometrics - - [ ] WiFi - - [ ] Bluetooth - - [ ] Notifications - - [ ] Clipboard -- [ ] Animations - -### Bundling (CLI) - -- [x] Translation from HTML into RSX -- [x] Dev server -- [x] Live reload -- [x] Translation from JSX into RSX -- [ ] Hot module replacement -- [ ] Code splitting -- [ ] Asset macros -- [ ] Css pipeline -- [ ] Image pipeline - -### Essential hooks - -- [x] Router -- [x] Global state management -- [ ] Resize observer - -## Work in Progress - -### Build Tool - -We are currently working on our own build tool called [Dioxus CLI](https://github.com/DioxusLabs/cli) which will support: - -- an interactive TUI -- on-the-fly reconfiguration -- hot CSS reloading -- two-way data binding between browser and source code -- an interpreter for `rsx!` -- ability to publish to github/netlify/vercel -- bundling for iOS/Desktop/etc - -### Server Component Support - -While not currently fully implemented, the expectation is that LiveView apps can be a hybrid between Wasm and server-rendered where only portions of a page are "live" and the rest of the page is either server-rendered, statically generated, or handled by the host SPA. - -### Native rendering - -We are currently working on a native renderer for Dioxus using WGPU called [Blitz](https://github.com/DioxusLabs/blitz/). This will allow you to build apps that are rendered natively for iOS, Android, and Desktop. diff --git a/docs/guide/src/en/contributing/walkthrough_readme.md b/docs/guide/src/en/contributing/walkthrough_readme.md deleted file mode 100644 index 5be9d4b5a..000000000 --- a/docs/guide/src/en/contributing/walkthrough_readme.md +++ /dev/null @@ -1,136 +0,0 @@ -# Walkthrough of the Hello World Example Internals - -This walkthrough will take you through the internals of the Hello World example program. It will explain how major parts of Dioxus internals interact with each other to take the readme example from a source file to a running application. This guide should serve as a high-level overview of the internals of Dioxus. It is not meant to be a comprehensive guide. - -## The Source File - -We start will a hello world program. This program renders a desktop app with the text "Hello World" in a webview. - -```rust, no_run -{{#include ../../../../../examples/readme.rs}} -``` - -[![](https://mermaid.ink/img/pako:eNqNkT1vwyAQhv8KvSlR48HphtQtqjK0S6tuSBGBS0CxwcJHk8rxfy_YVqxKVdR3ug_u4YXrQHmNwOFQ-bMyMhB7fReOJbVxfwyyMSy0l7GSpW1ARda727ksUy5MuSyKgvBC5ULA1h5N8WK_kCkfHWHgrBuiXsBynrvdsY9E3u1iM_eyvFOVVadMnELOap-o1911JLPHZ1b-YqLTc3LjTt7WifTZMJPsPdx1ov3Z_ellfcdL8R8vmTy5eUqsTUpZ-vzZzjAEK6gx1NLqtJwuNwSQwRoF8BRqGU4ChOvTORnJf3w7BZxCxBXERkvCjZXpQTXwg6zaVEVtyYe3cdvD0vsf4bucgw?type=png)](https://mermaid.live/edit#pako:eNqNkT1vwyAQhv8KvSlR48HphtQtqjK0S6tuSBGBS0CxwcJHk8rxfy_YVqxKVdR3ug_u4YXrQHmNwOFQ-bMyMhB7fReOJbVxfwyyMSy0l7GSpW1ARda727ksUy5MuSyKgvBC5ULA1h5N8WK_kCkfHWHgrBuiXsBynrvdsY9E3u1iM_eyvFOVVadMnELOap-o1911JLPHZ1b-YqLTc3LjTt7WifTZMJPsPdx1ov3Z_ellfcdL8R8vmTy5eUqsTUpZ-vzZzjAEK6gx1NLqtJwuNwSQwRoF8BRqGU4ChOvTORnJf3w7BZxCxBXERkvCjZXpQTXwg6zaVEVtyYe3cdvD0vsf4bucgw) - -## The rsx! Macro - -Before the Rust compiler runs the program, it will expand all [macros](https://doc.rust-lang.org/reference/procedural-macros.html). Here is what the hello world example looks like expanded: - -```rust, no_run -{{#include ../../../examples/readme_expanded.rs}} -``` - -The rsx macro separates the static parts of the rsx (the template) and the dynamic parts (the [dynamic_nodes](https://docs.rs/dioxus-core/0.3.2/dioxus_core/prelude/struct.VNode.html#structfield.dynamic_nodes) and [dynamic_attributes](https://docs.rs/dioxus-core/0.3.2/dioxus_core/prelude/struct.VNode.html#structfield.dynamic_attrs)). - -The static template only contains the parts of the rsx that cannot change at runtime with holes for the dynamic parts: - -[![](https://mermaid.ink/img/pako:eNqdksFuwjAMhl8l8wkkKtFx65njdtm0E0GVSQKJoEmVOgKEeHecUrXStO0wn5Lf9u8vcm6ggjZQwf4UzspiJPH2Ib3g6NLuELG1oiMkp0TsLs9EDu2iUeSCH8tz2HJmy3lRFPrqsXGq9mxeLzcbCU6LZSUGXWRdwnY7tY7Tdoko-Dq1U64fODgiUfzJMeuOe7_ZGq-ny2jNhGQu9DqT8NUK6w72RcL8dxgdzv4PnHLAKf-Fk80HoBUDrfkqeBkTUd8EC2hMbNBpXtYtJySQNQ0PqPioMR4lSH_nOkwUPq9eQUUxmQWkViOZtUN-UwPVHk8dq0Y7CvH9uf3-E9wfrmuk1A?type=png)](https://mermaid.live/edit#pako:eNqdksFuwjAMhl8l8wkkKtFx65njdtm0E0GVSQKJoEmVOgKEeHecUrXStO0wn5Lf9u8vcm6ggjZQwf4UzspiJPH2Ib3g6NLuELG1oiMkp0TsLs9EDu2iUeSCH8tz2HJmy3lRFPrqsXGq9mxeLzcbCU6LZSUGXWRdwnY7tY7Tdoko-Dq1U64fODgiUfzJMeuOe7_ZGq-ny2jNhGQu9DqT8NUK6w72RcL8dxgdzv4PnHLAKf-Fk80HoBUDrfkqeBkTUd8EC2hMbNBpXtYtJySQNQ0PqPioMR4lSH_nOkwUPq9eQUUxmQWkViOZtUN-UwPVHk8dq0Y7CvH9uf3-E9wfrmuk1A) - -The dynamic_nodes and dynamic_attributes are the parts of the rsx that can change at runtime: - -[![](https://mermaid.ink/img/pako:eNp1UcFOwzAM_RXLVzZpvUbighDiABfgtkxTlnirtSaZUgc0df130hZEEcwny35-79nu0EZHqHDfxA9bmyTw9KIDlGjz7pDMqQZ3DsazhVCQ7dQbwnEiKxwDvN3NqhN4O4C3q_VaIztYKXjkQ7184HcCG3MQSgq6Mes1bjbTPAV3RdqIJN5l-V__2_Fcf5iY68dgG7ZHBT4WD5ftZfIBN7dQ_Tj4w1B9MVTXGZa_GMYdcIGekjfsymW7oaFRavKkUZXUmXTUqENfcCZLfD0Hi0pSpgXmkzNC92zKATyqvWnaUiXHEtPz9KrxY_0nzYOPmA?type=png)](https://mermaid.live/edit#pako:eNp1UcFOwzAM_RXLVzZpvUbighDiABfgtkxTlnirtSaZUgc0df130hZEEcwny35-79nu0EZHqHDfxA9bmyTw9KIDlGjz7pDMqQZ3DsazhVCQ7dQbwnEiKxwDvN3NqhN4O4C3q_VaIztYKXjkQ7184HcCG3MQSgq6Mes1bjbTPAV3RdqIJN5l-V__2_Fcf5iY68dgG7ZHBT4WD5ftZfIBN7dQ_Tj4w1B9MVTXGZa_GMYdcIGekjfsymW7oaFRavKkUZXUmXTUqENfcCZLfD0Hi0pSpgXmkzNC92zKATyqvWnaUiXHEtPz9KrxY_0nzYOPmA) - -## Launching the App - -The app is launched by calling the `launch` function with the root component. Internally, this function will create a new web view using [wry](https://docs.rs/wry/latest/wry/) and create a virtual dom with the root component (`fn app()` in the readme example). This guide will not explain the renderer in-depth, but you can read more about it in the [custom renderer](/guide/custom-renderer) section. - -## The Virtual DOM - -Before we dive into the initial render in the virtual DOM, we need to discuss what the virtual DOM is. The virtual DOM is a representation of the DOM that is used to diff the current DOM from the new DOM. This diff is then used to create a list of mutations that need to be applied to the DOM to bring it into sync with the virtual DOM. - -The Virtual DOM roughly looks like this: - -```rust, no_run -pub struct VirtualDom { - // All the templates that have been created or set during hot reloading - pub(crate) templates: FxHashMap>>, - - // A slab of all the scopes that have been created - pub(crate) scopes: ScopeSlab, - - // All scopes that have been marked as dirty - pub(crate) dirty_scopes: BTreeSet, - - // Every element is actually a dual reference - one to the template and the other to the dynamic node in that template - pub(crate) elements: Slab, - - // This receiver is used to receive messages from hooks about what scopes need to be marked as dirty - pub(crate) rx: futures_channel::mpsc::UnboundedReceiver, - - // The changes queued up to be sent to the renderer - pub(crate) mutations: Mutations<'static>, -} -``` - -> What is a [slab](https://docs.rs/slab/latest/slab/)? -> -> A slab acts like a hashmap with integer keys if you don't care about the value of the keys. It is internally backed by a dense vector which makes it more efficient than a hashmap. When you insert a value into a slab, it returns an integer key that you can use to retrieve the value later. - -> How does Dioxus use slabs? -> -> Dioxus uses "synchronized slabs" to communicate between the renderer and the VDOM. When a node is created in the Virtual DOM, an (elementId, mutation) pair is passed to the renderer to identify that node, which the renderer will then render in actual DOM. These ids are also used by the Virtual Dom to reference that node in future mutations, like setting an attribute on a node or removing a node. When the renderer sends an event to the Virtual Dom, it sends the ElementId of the node that the event was triggered on. The Virtual DOM uses this id to find that node in the slab and then run the necessary event handlers. - -The virtual DOM is a tree of scopes. A new `Scope` is created for every component when it is first rendered and recycled when the component is unmounted. - -Scopes serve three main purposes: - -1. They store the state of hooks used by the component -2. They store the state for the context API (for example: using - [use_shared_state_provider](https://docs.rs/dioxus/latest/dioxus/prelude/fn.use_shared_state_provider.html)). -3. They store the current and previous versions of the `VNode` that was rendered, so they can be - diffed to generate the set of mutations needed to re-render it. - -### The Initial Render - -The root scope is created and rebuilt: - -1. The root component is run -2. The root component returns a `VNode` -3. Mutations for this `VNode` are created and added to the mutation list (this may involve creating new child components) -4. The `VNode` is stored in the root's `Scope`. - -After the root's `Scope` is built, all generated mutations are sent to the renderer, which applies them to the DOM. - -After the initial render, the root `Scope` looks like this: - -[![](https://mermaid.ink/img/pako:eNqtVE1P4zAQ_SuzPrWikRpWXCLtBRDisItWsOxhCaqM7RKricdyJrQV8N93QtvQNCkfEnOynydv3nxkHoVCbUQipjnOVSYDwc_L1AFbWd3dB-kzuEQkuFLoDUwDFkCZAek9nGDh0RlHK__atA1GkUUHf45f0YbppAqB_aOzIAvz-t7-chN_Y-1bw1WSJKsglIu2w9tktWXxIIuHURT5XCqTYa5NmDguw2R8c5MKq2GcgF46WTB_jafi9rZL0yi5q4jQTSrf9altO4okCn1Ratwyz55Qxuku2ITlTMgs6HCQimsPmb3PvqVi-L5gjXP3QcnxWnL8JZLrwGvR31n0KV-Bx6-r-oVkT_-3G1S-NQLbk9i8rj7udP2cixed2QcDCitHJiQw7ub3EVlNecrPjudG2-6soFO5VbMECmR9T5OnlUY4-AFxfw9aTFst3McU9TK1Otm6NEn_DubBYlX2_dglLXOz48FgwJmJ5lZTlhz6xWgNaFnyDgpymcARHO0W2a9J_l5w2wYXvHuGPcqaQ-rESBQmFNJq3nCPNZoK3l4sUSR81DLMUpG6Z_aTFeHV0imRUKjMSFReSzKnVnKGhUimMi8ZNdoShl-rlfmyOUfCS_cPcePz_B_Wl4pc?type=png)](https://mermaid.live/edit#pako:eNqtVE1P4zAQ_SuzPrWikRpWXCLtBRDisItWsOxhCaqM7RKricdyJrQV8N93QtvQNCkfEnOynydv3nxkHoVCbUQipjnOVSYDwc_L1AFbWd3dB-kzuEQkuFLoDUwDFkCZAek9nGDh0RlHK__atA1GkUUHf45f0YbppAqB_aOzIAvz-t7-chN_Y-1bw1WSJKsglIu2w9tktWXxIIuHURT5XCqTYa5NmDguw2R8c5MKq2GcgF46WTB_jafi9rZL0yi5q4jQTSrf9altO4okCn1Ratwyz55Qxuku2ITlTMgs6HCQimsPmb3PvqVi-L5gjXP3QcnxWnL8JZLrwGvR31n0KV-Bx6-r-oVkT_-3G1S-NQLbk9i8rj7udP2cixed2QcDCitHJiQw7ub3EVlNecrPjudG2-6soFO5VbMECmR9T5OnlUY4-AFxfw9aTFst3McU9TK1Otm6NEn_DubBYlX2_dglLXOz48FgwJmJ5lZTlhz6xWgNaFnyDgpymcARHO0W2a9J_l5w2wYXvHuGPcqaQ-rESBQmFNJq3nCPNZoK3l4sUSR81DLMUpG6Z_aTFeHV0imRUKjMSFReSzKnVnKGhUimMi8ZNdoShl-rlfmyOUfCS_cPcePz_B_Wl4pc) - -### Waiting for Events - -The Virtual DOM will only ever re-render a `Scope` if it is marked as dirty. Each hook is responsible for marking the `Scope` as dirty if the state has changed. Hooks can mark a scope as dirty by sending a message to the Virtual Dom's channel. You can see the [implementations](https://github.com/DioxusLabs/dioxus/tree/master/packages/hooks) for the hooks dioxus includes by default on how this is done. Calling `needs_update()` on a hook will also cause it to mark its scope as dirty. - -There are generally two ways a scope is marked as dirty: - -1. The renderer triggers an event: An event listener on this event may be called, which may mark a - component as dirty, if processing the event resulted in any generated any mutations. -2. The renderer calls - [`wait_for_work`](https://docs.rs/dioxus/latest/dioxus/prelude/struct.VirtualDom.html#method.wait_for_work): - This polls dioxus internal future queue. One of these futures may mark a component as dirty. - -Once at least one `Scope` is marked as dirty, the renderer can call [`render_with_deadline`](https://docs.rs/dioxus/latest/dioxus/prelude/struct.VirtualDom.html#method.render_with_deadline) to diff the dirty scopes. - -### Diffing Scopes - -When a user clicks the "up high" button, the root `Scope` will be marked as dirty by the `use_state` hook. The desktop renderer will then call `render_with_deadline`, which will diff the root `Scope`. - -To start the diffing process, the component function is run. After the root component is run it, the root `Scope` will look like this: - -[![](https://mermaid.ink/img/pako:eNrFVlFP2zAQ_iuen0BrpCaIl0i8AEJ72KQJtpcRFBnbJVYTn-U4tBXw33dpG5M2CetoBfdkny_ffb67fPIT5SAkjekkhxnPmHXk-3WiCVpZ3T9YZjJyDeDIDQcjycRCQVwmCTOGXEBhQEvtVvG1CWUldwo0-XX-6vVIF5W1GB9cWVbI1_PNL5v8jW3uPFbpmFOc2HK-GfA2WG1ZeJSFx0EQmJxxmUEupE01liEd394mVAkyjolYaFYgfu1P6N1dF8Yzua-cA51WphtTWzsLc872Zan9CnEGUkktuk6fFm_i5NxFRwn9bUimHrIvCT3-N2EBM70j5XBNOTwI5TrxmvQJkr7ELcHx67Jeggz0v92g8q0RaE-iP1193On6NyxecKUeJeFQaSdtTMLu_Xah5ctT_u94Nty2ZwU0zxWfxqQA5PecPq84kq9nfRw7SK0WDiEFZ4O37d34S_-08lFBVfb92KVb5HIrAp0WpjKYKeGyODLz0dohWIkaZNkiJqfkdLvIH6oRaTSoEmm0n06k0a5K0ZdpL61Io0Yt0nfpxc7UQ0_9cJrhyZ8syX-6brS706Mc489Vjja7fbWj3cxDqIdfJJqOaCFtwZTAV8hT7U0ovjBQRmiMS8HsNKGJfsE4Vjm4WWhOY2crOaKVEczJS8WwgAWNJywv0SuFcmB_rJ41y9fNiBqm_wA0MS9_AUuAiy0?type=png)](https://mermaid.live/edit#pako:eNrFVlFP2zAQ_iuen0BrpCaIl0i8AEJ72KQJtpcRFBnbJVYTn-U4tBXw33dpG5M2CetoBfdkny_ffb67fPIT5SAkjekkhxnPmHXk-3WiCVpZ3T9YZjJyDeDIDQcjycRCQVwmCTOGXEBhQEvtVvG1CWUldwo0-XX-6vVIF5W1GB9cWVbI1_PNL5v8jW3uPFbpmFOc2HK-GfA2WG1ZeJSFx0EQmJxxmUEupE01liEd394mVAkyjolYaFYgfu1P6N1dF8Yzua-cA51WphtTWzsLc872Zan9CnEGUkktuk6fFm_i5NxFRwn9bUimHrIvCT3-N2EBM70j5XBNOTwI5TrxmvQJkr7ELcHx67Jeggz0v92g8q0RaE-iP1193On6NyxecKUeJeFQaSdtTMLu_Xah5ctT_u94Nty2ZwU0zxWfxqQA5PecPq84kq9nfRw7SK0WDiEFZ4O37d34S_-08lFBVfb92KVb5HIrAp0WpjKYKeGyODLz0dohWIkaZNkiJqfkdLvIH6oRaTSoEmm0n06k0a5K0ZdpL61Io0Yt0nfpxc7UQ0_9cJrhyZ8syX-6brS706Mc489Vjja7fbWj3cxDqIdfJJqOaCFtwZTAV8hT7U0ovjBQRmiMS8HsNKGJfsE4Vjm4WWhOY2crOaKVEczJS8WwgAWNJywv0SuFcmB_rJ41y9fNiBqm_wA0MS9_AUuAiy0) - -Next, the Virtual DOM will compare the new VNode with the previous VNode and only update the parts of the tree that have changed. Because of this approach, when a component is re-rendered only the parts of the tree that have changed will be updated in the DOM by the renderer. - -The diffing algorithm goes through the list of dynamic attributes and nodes and compares them to the previous VNode. If the attribute or node has changed, a mutation that describes the change is added to the mutation list. - -Here is what the diffing algorithm looks like for the root `Scope` (red lines indicate that a mutation was generated, and green lines indicate that no mutation was generated) - -[![](https://mermaid.ink/img/pako:eNrFlFFPwjAQx7_KpT7Kko2Elya8qCE-aGLAJ5khpe1Yw9Zbug4k4He3OJjbGPig0T5t17tf_nf777aEo5CEkijBNY-ZsfAwDjW4kxfzhWFZDGNECxOOmYTIYAo2lsCyDG4xzVBLbcv8_RHKSG4V6orSIN0Wxrh8b2RYKr_uTyubd1W92GiWKg7aac6bOU3G803HbVk82xfP_Ok0JEqAT-FeLWJvpFYSOBbaSkMhCMnra5MgtfhWFrPWqHlhL2urT6atbU-oa0PNE8WXFFJ0-nazXakRroddGk9IwYEUnCd5w7Pddr5UTT8ZuVJY5F0fM7ebRLYyXNDgUnprJWxM-9lb7xAQLHe-M2xDYQCD9pD_2hez_kVn-P_rjLq6n3qjYv2iO5qz9DyvPdyv1ETp5eTTJ_7BGvQq8v1TVtl5jXUcRRcrqFh-dI4VtFlBN6t_ynLNkh5JpUmZEm5rbvfhkLiN6H4BQt2jYGYZklC_uzxWWJxsNCfUmkL2SJEJZuWdYs4cKaERS3IXlUJZNI_lGv7cxj2SMf2CeMx5_wBcbK19?type=png)](https://mermaid.live/edit#pako:eNrFlFFPwjAQx7_KpT7Kko2Elya8qCE-aGLAJ5khpe1Yw9Zbug4k4He3OJjbGPig0T5t17tf_nf777aEo5CEkijBNY-ZsfAwDjW4kxfzhWFZDGNECxOOmYTIYAo2lsCyDG4xzVBLbcv8_RHKSG4V6orSIN0Wxrh8b2RYKr_uTyubd1W92GiWKg7aac6bOU3G803HbVk82xfP_Ok0JEqAT-FeLWJvpFYSOBbaSkMhCMnra5MgtfhWFrPWqHlhL2urT6atbU-oa0PNE8WXFFJ0-nazXakRroddGk9IwYEUnCd5w7Pddr5UTT8ZuVJY5F0fM7ebRLYyXNDgUnprJWxM-9lb7xAQLHe-M2xDYQCD9pD_2hez_kVn-P_rjLq6n3qjYv2iO5qz9DyvPdyv1ETp5eTTJ_7BGvQq8v1TVtl5jXUcRRcrqFh-dI4VtFlBN6t_ynLNkh5JpUmZEm5rbvfhkLiN6H4BQt2jYGYZklC_uzxWWJxsNCfUmkL2SJEJZuWdYs4cKaERS3IXlUJZNI_lGv7cxj2SMf2CeMx5_wBcbK19) - -## Conclusion - -This is only a brief overview of how the Virtual Dom works. There are several aspects not yet covered in this guide including: - - * How the Virtual DOM handles async-components - * Keyed diffing - * Using [bump allocation](https://github.com/fitzgen/bumpalo) to efficiently allocate VNodes. - -If you need more information about the Virtual Dom, you can read the code of the [core](https://github.com/DioxusLabs/dioxus/tree/master/packages/core) crate or reach out to us on [Discord](https://discord.gg/XgGxMSkvUM). \ No newline at end of file diff --git a/docs/guide/src/en/custom_renderer/index.md b/docs/guide/src/en/custom_renderer/index.md deleted file mode 100644 index 3b6888b0d..000000000 --- a/docs/guide/src/en/custom_renderer/index.md +++ /dev/null @@ -1,413 +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 `Mutations` 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 process edits and generate events 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 interpreter](https://github.com/DioxusLabs/dioxus/tree/master/packages/interpreter) or [tui renderer](https://github.com/DioxusLabs/dioxus/tree/master/packages/dioxus-tui) as a starting point for your custom renderer. - -## Templates - -Dioxus is built around the concept of [Templates](https://docs.rs/dioxus-core/latest/dioxus_core/prelude/struct.Template.html). Templates describe a UI tree known at compile time with dynamic parts filled at runtime. This is useful internally to make skip diffing static nodes, but it is also useful for the renderer to reuse parts of the UI tree. This can be useful for things like a list of items. Each item could contain some static parts and some dynamic parts. The renderer can use the template to create a static part of the UI once, clone it for each element in the list, and then fill in the dynamic parts. - -## Mutations - -The `Mutation` type is a serialized enum that represents an operation that should be applied to update the UI. The variants roughly follow this set: - -```rust, no_run -enum Mutation { - AppendChildren, - AssignId, - CreatePlaceholder, - CreateTextNode, - HydrateText, - LoadTemplate, - ReplaceWith, - ReplacePlaceholder, - InsertAfter, - InsertBefore, - SetAttribute, - SetText, - NewEventListener, - RemoveEventListener, - Remove, - PushRoot, -} -``` - -The Dioxus diffing mechanism operates as a [stack machine](https://en.wikipedia.org/wiki/Stack_machine) where the [LoadTemplate](https://docs.rs/dioxus-core/latest/dioxus_core/enum.Mutation.html#variant.LoadTemplate), [CreatePlaceholder](https://docs.rs/dioxus-core/latest/dioxus_core/enum.Mutation.html#variant.CreatePlaceholder), and [CreateTextNode](https://docs.rs/dioxus-core/latest/dioxus_core/enum.Mutation.html#variant.CreateTextNode) mutations pushes a new "real" DOM node onto the stack and [AppendChildren](https://docs.rs/dioxus-core/latest/dioxus_core/enum.Mutation.html#variant.AppendChildren), [InsertAfter](https://docs.rs/dioxus-core/latest/dioxus_core/enum.Mutation.html#variant.InsertAfter), [InsertBefore](https://docs.rs/dioxus-core/latest/dioxus_core/enum.Mutation.html#variant.InsertBefore), [ReplacePlaceholder](https://docs.rs/dioxus-core/latest/dioxus_core/enum.Mutation.html#variant.ReplacePlaceholder), and [ReplaceWith](https://docs.rs/dioxus-core/latest/dioxus_core/enum.Mutation.html#variant.ReplaceWith) all remove nodes from the stack. - -## Node storage - -Dioxus saves and loads elements with IDs. Inside the VirtualDOM, this is just tracked as 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 id is used in a mutation. Dioxus reclaims the IDs of elements when removed. To stay in sync with Dioxus you can use a sparse Vec (Vec>) with possibly unoccupied items. You can use the ids as indexes into the Vec for elements, and grow the Vec when an id does not exist. - -### An Example - -For the sake of understanding, let's consider this example – a very simple UI declaration: - -```rust, no_run -rsx!( h1 {"count: {x}"} ) -``` - -#### Building Templates - -The above rsx will create a template that contains one static h1 tag and a placeholder for a dynamic text node. The template contains the static parts of the UI, and ids for the dynamic parts along with the paths to access them. - -The template will look something like this: - -```rust, no_run -Template { - // Some id that is unique for the entire project - name: "main.rs:1:1:0", - // The root nodes of the template - roots: &[ - TemplateNode::Element { - tag: "h1", - namespace: None, - attrs: &[], - children: &[ - TemplateNode::DynamicText { - id: 0 - }, - ], - } - ], - // the path to each of the dynamic nodes - node_paths: &[ - // the path to dynamic node with a id of 0 - &[ - // on the first root node - 0, - // the first child of the root node - 0, - ] - ], - // the path to each of the dynamic attributes - attr_paths: &'a [&'a [u8]], -} -``` - -> For more detailed docs about the struture of templates see the [Template api docs](https://docs.rs/dioxus-core/latest/dioxus_core/prelude/struct.Template.html) - -This template will be sent to the renderer in the [list of templates](https://docs.rs/dioxus-core/latest/dioxus_core/struct.Mutations.html#structfield.templates) supplied with the mutations the first time it is used. Any time the renderer encounters a [LoadTemplate](https://docs.rs/dioxus-core/latest/dioxus_core/enum.Mutation.html#variant.LoadTemplate) mutation after this, it should clone the template and store it in the given id. - -For dynamic nodes and dynamic text nodes, a placeholder node should be created and inserted into the UI so that the node can be modified later. - -In HTML renderers, this template could look like this: - -```html -

""

-``` - -#### Applying Mutations - -After the renderer has created all of the new templates, it can begin to process the mutations. - -When the renderer starts, it should contain the Root node on the stack and store the Root node with an id of 0. The Root node is the top-level node of the UI. In HTML, this is the `
` element. - -```rust, no_run -instructions: [] -stack: [ - RootNode, -] -nodes: [ - RootNode, -] -``` - -The first mutation is a `LoadTemplate` mutation. This tells the renderer to load a root from the template with the given id. The renderer will then push the root node of the template onto the stack and store it with an id for later. In this case, the root node is an h1 element. - -```rust, no_run -instructions: [ - LoadTemplate { - // the id of the template - name: "main.rs:1:1:0", - // the index of the root node in the template - index: 0, - // the id to store - id: ElementId(1), - } -] -stack: [ - RootNode, -

""

, -] -nodes: [ - RootNode, -

""

, -] -``` - -Next, Dioxus will create the dynamic text node. The diff algorithm decides that this node needs to be created, so Dioxus will generate the Mutation `HydrateText`. When the renderer receives this instruction, it will navigate to the placeholder text node in the template and replace it with the new text. - -```rust, no_run -instructions: [ - LoadTemplate { - name: "main.rs:1:1:0", - index: 0, - id: ElementId(1), - }, - HydrateText { - // the id to store the text node - id: ElementId(2), - // the text to set - text: "count: 0", - } -] -stack: [ - RootNode, -

"count: 0"

, -] -nodes: [ - RootNode, -

"count: 0"

, - "count: 0", -] -``` - -Remember, the h1 node is not attached to anything (it is unmounted) so Dioxus needs to generate an Edit that connects the h1 node to the Root. It depends on the situation, but in this case, we use `AppendChildren`. This pops the text node off the stack, leaving the Root element as the next element on the stack. - -```rust, no_run -instructions: [ - LoadTemplate { - name: "main.rs:1:1:0", - index: 0, - id: ElementId(1), - }, - HydrateText { - id: ElementId(2), - text: "count: 0", - }, - AppendChildren { - // the id of the parent node - id: ElementId(0), - // the number of nodes to pop off the stack and append - m: 1 - } -] -stack: [ - RootNode, -] -nodes: [ - RootNode, -

"count: 0"

, - "count: 0", -] -``` - -Over time, our stack looked like this: - -```rust, no_run -[Root] -[Root,

""

] -[Root,

"count: 0"

] -[Root] -``` - -Conveniently, this approach completely separates the Virtual DOM 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 make 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. - -This little demo serves to show exactly how a Renderer would need to process a mutation stream to build UIs. - -## 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 for 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, no_run, ignore -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 to decode what the real events are for 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 virtual event system is modeled almost entirely around the HTML spec, but we are interested in slimming it down. - -```rust, no_run, ignore -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/attributes 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. You can drop in your elements any time you want, with little hassle. However, you must be sure your renderer can handle the new namespace. - -For more examples and information on how to create custom namespaces, see the [`dioxus_html` crate](https://github.com/DioxusLabs/dioxus/blob/master/packages/html/README.md#how-to-extend-it). - -# Native Core - -If you are creating a renderer in rust, the [native-core](https://github.com/DioxusLabs/dioxus/tree/master/packages/native-core) crate provides some utilities to implement a renderer. It provides an abstraction over Mutations and Templates and contains helpers that can handle the layout and text editing for you. - -## The RealDom - -The `RealDom` is a higher-level abstraction over updating the Dom. It uses an entity component system to manage the state of nodes. This system allows you to modify insert and modify arbitrary components on nodes. On top of this, the RealDom provides a way to manage a tree of nodes, and the State trait provides a way to automatically add and update these components when the tree is modified. It also provides a way to apply `Mutations` to the RealDom. - -### Example - -Let's build a toy renderer with borders, size, and text color. -Before we start let's take a look at an example element we can render: - -```rust, no_run -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 layout depends on the children's layout, the current text, and the text size. The border depends on only the current node. - -In the following diagram arrows represent dataflow: - -[![](https://mermaid.ink/img/pako:eNqllV1vgjAUhv8K6W4wkQVa2QdLdrHsdlfukmSptEhjoaSWqTH-9xVwONAKst70g5739JzzlO5BJAgFAYi52EQJlsr6fAszS7d1sVhKnCdWJDJFt6peLVs5-9owohK7HFrVcFJ_pxnpmK8VVvRkTJikkWIiaxy1dhP23bUwW1WW5WbPrrqJ4ziR4EJ6dtVN2ls5y1ZztePUcrWZFCvqVEcPPDffvlyS1XoLIQnVgnVvVPR6FU9Zc-6dV453ojjOPbuetRJ57gIeXQR3cez7rjtteZyZQ2j5MqmjqwE0ZW0VKx9RKtgpFewp1aw3sXXFy6TWgiYlv8mfq1scD8ofbBCAfQg8_AMBOAyBxzEIwA4CxgQ99QbQkjnD2KT7_CfxGF8_9WXQEsq5sDZCcjICOXRCri4h6r3NA38Q6Jdi1EOx5w3DGDYYI6MUvJFjM3VoGHUeGoMd6mBnDmh2E3fo7O4Yhf0x4OkBmIKUyhQzol_GfbkcApXQlIYg0EOC5SoEYXbQ-3ChxHyXRSBQsqBTUOREx_7OsAY3BUGM-VqvUsKUkB_1U6vf05gtweEHTk4_HQ?type=png)](https://mermaid.live/edit#pako:eNqllV1vgjAUhv8K6W4wkQVa2QdLdrHsdlfukmSptEhjoaSWqTH-9xVwONAKst70g5739JzzlO5BJAgFAYi52EQJlsr6fAszS7d1sVhKnCdWJDJFt6peLVs5-9owohK7HFrVcFJ_pxnpmK8VVvRkTJikkWIiaxy1dhP23bUwW1WW5WbPrrqJ4ziR4EJ6dtVN2ls5y1ZztePUcrWZFCvqVEcPPDffvlyS1XoLIQnVgnVvVPR6FU9Zc-6dV453ojjOPbuetRJ57gIeXQR3cez7rjtteZyZQ2j5MqmjqwE0ZW0VKx9RKtgpFewp1aw3sXXFy6TWgiYlv8mfq1scD8ofbBCAfQg8_AMBOAyBxzEIwA4CxgQ99QbQkjnD2KT7_CfxGF8_9WXQEsq5sDZCcjICOXRCri4h6r3NA38Q6Jdi1EOx5w3DGDYYI6MUvJFjM3VoGHUeGoMd6mBnDmh2E3fo7O4Yhf0x4OkBmIKUyhQzol_GfbkcApXQlIYg0EOC5SoEYXbQ-3ChxHyXRSBQsqBTUOREx_7OsAY3BUGM-VqvUsKUkB_1U6vf05gtweEHTk4_HQ) - -[//]: # "%% 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)" -[//]: # " linkStyle 0 stroke-width:10px;" -[//]: # " state1---border1(border)" -[//]: # " linkStyle 1 stroke-width:10px;" -[//]: # " text_width-.->layout_width1(layout width)" -[//]: # " linkStyle 2 stroke:#ff5500,stroke-width:4px;" -[//]: # " state1---layout_width1" -[//]: # " linkStyle 3 stroke-width:10px;" -[//]: # " end" -[//]: # " subgraph p state" -[//]: # " direction TB" -[//]: # " state2(state)---color2(color)" -[//]: # " linkStyle 4 stroke-width:10px;" -[//]: # " color1-.->color2" -[//]: # " linkStyle 5 stroke:#0000ff,stroke-width:4px;" -[//]: # " state2---border2(border)" -[//]: # " linkStyle 6 stroke-width:10px;" -[//]: # " text_width-.->layout_width2(layout width)" -[//]: # " linkStyle 7 stroke:#ff5500,stroke-width:4px;" -[//]: # " state2---layout_width2" -[//]: # " linkStyle 8 stroke-width:10px;" -[//]: # " layout_width2-.->layout_width1" -[//]: # " linkStyle 9 stroke:#00aa00,stroke-width:4px;" -[//]: # " end" -[//]: # " subgraph hello world state" -[//]: # " direction TB" -[//]: # " state3(state)---border3(border)" -[//]: # " linkStyle 10 stroke-width:10px;" -[//]: # " state3---color3(color)" -[//]: # " linkStyle 11 stroke-width:10px;" -[//]: # " 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" -[//]: # " linkStyle 14 stroke-width:10px;" -[//]: # " layout_width3-.->layout_width2" -[//]: # " linkStyle 15 stroke:#00aa00,stroke-width:4px;" -[//]: # " end" -[//]: # " end" - -To help in building a Dom, native-core provides the State trait and a RealDom struct. The State trait provides a way to describe how states in a node depend on other states in its relatives. By describing how to update a single node from its relations, native-core will derive a way to update the states of all nodes for you. 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. - -Native Core cannot create all of the required methods for the State trait, but it can derive some of them. To implement the State trait, you must implement the following methods and let the `#[partial_derive_state]` macro handle the rest: - -```rust, no_run, ignore -{{#include ../../../examples/custom_renderer.rs:derive_state}} -``` - -Lets take a look at how to implement the State trait for a simple renderer. - -```rust, no_run -{{#include ../../../examples/custom_renderer.rs:state_impl}} -``` - -Now that we have our state, we can put it to use in our RealDom. We can update the RealDom with apply_mutations to update the structure of the dom (adding, removing, and changing properties of nodes) and then update_state to update the States for each of the nodes that changed. - -```rust, no_run -{{#include ../../../examples/custom_renderer.rs:rendering}} -``` - -## Layout - -For most platforms, the layout of the Elements will stay the same. The [layout_attributes](https://docs.rs/dioxus-native-core/latest/dioxus_native_core/layout_attributes/index.html) module provides a way to apply HTML attributes a [Taffy](https://docs.rs/taffy/latest/taffy/index.html) layout style. - -## Text Editing - -To make it easier to implement text editing in rust renderers, `native-core` also contains a renderer-agnostic cursor system. The cursor can handle text editing, selection, and movement with common keyboard shortcuts integrated. - -```rust, no_run -{{#include ../../../examples/custom_renderer.rs:cursor}} -``` - -## Conclusion - -That should be it! You should have nearly all the knowledge required on how to implement your renderer. We're super interested in seeing Dioxus apps brought to custom desktop renderers, mobile renderers, video game UI, and even augmented reality! If you're interested in contributing to any of these projects, don't be afraid to reach out or join the [community](https://discord.gg/XgGxMSkvUM). diff --git a/docs/guide/src/en/describing_ui/component_children.md b/docs/guide/src/en/describing_ui/component_children.md deleted file mode 100644 index 7e329abbc..000000000 --- a/docs/guide/src/en/describing_ui/component_children.md +++ /dev/null @@ -1,31 +0,0 @@ -# Component Children - -In some cases, you may wish to create a component that acts as a container for some other content, without the component needing to know what that content is. To achieve this, create a prop of type `Element`: - -```rust, no_run -{{#include ../../../examples/component_element_props.rs:Clickable}} -``` - -Then, when rendering the component, you can pass in the output of `cx.render(rsx!(...))`: - -```rust, no_run -{{#include ../../../examples/component_element_props.rs:Clickable_usage}} -``` - -> Note: Since `Element<'a>` is a borrowed prop, there will be no memoization. - -> Warning: While it may compile, do not include the same `Element` more than once in the RSX. The resulting behavior is unspecified. - -## The `children` field - -Rather than passing the RSX through a regular prop, you may wish to accept children similarly to how elements can have children. The "magic" `children` prop lets you achieve this: - -```rust, no_run -{{#include ../../../examples/component_children.rs:Clickable}} -``` - -This makes using the component much simpler: simply put the RSX inside the `{}` brackets – and there is no need for a `render` call or another macro! - -```rust, no_run -{{#include ../../../examples/component_children.rs:Clickable_usage}} -``` diff --git a/docs/guide/src/en/describing_ui/component_props.md b/docs/guide/src/en/describing_ui/component_props.md deleted file mode 100644 index 947ec5f70..000000000 --- a/docs/guide/src/en/describing_ui/component_props.md +++ /dev/null @@ -1,144 +0,0 @@ -# Component Props - -Just like you can pass arguments to a function, you can pass props to a component that customize its behavior! The components we've seen so far didn't accept any props – so let's write some components that do. - -## `#[derive(Props)]` - -Component props are a single struct annotated with `#[derive(Props)]`. For a component to accept props, the type of its argument must be `Scope`. Then, you can access the value of the props using `cx.props`. - -There are 2 flavors of Props structs: - -- Owned props: - - Don't have an associated lifetime - - Implement `PartialEq`, allow for memoization (if the props don't change, Dioxus won't re-render the component) -- Borrowed props: - - [Borrow](https://doc.rust-lang.org/beta/rust-by-example/scope/borrow.html) from a parent component - - Cannot be memoized due to lifetime constraints - -### Owned Props - -Owned Props are very simple – they don't borrow anything. Example: - -```rust, no_run -{{#include ../../../examples/component_owned_props.rs:Likes}} -``` - -You can then pass prop values to the component the same way you would pass attributes to an element: - -```rust, no_run -{{#include ../../../examples/component_owned_props.rs:App}} -``` - -![Screenshot: Likes component](./images/component_owned_props_screenshot.png) - -### Borrowed Props - -Owned props work well if your props are easy to copy around – like a single number. But what if we need to pass a larger data type, like a String from an `App` Component to a `TitleCard` subcomponent? A naive solution might be to [`.clone()`](https://doc.rust-lang.org/std/clone/trait.Clone.html) the String, creating a copy of it for the subcomponent – but this would be inefficient, especially for larger Strings. - -Rust allows for something more efficient – borrowing the String as a `&str` – this is what Borrowed Props are for! - -```rust, no_run -{{#include ../../../examples/component_borrowed_props.rs:TitleCard}} -``` - -We can then use the component like this: - -```rust, no_run -{{#include ../../../examples/component_borrowed_props.rs:App}} -``` - -![Screenshot: TitleCard component](./images/component_borrowed_props_screenshot.png) - -Borrowed props can be very useful, but they do not allow for memorization so they will _always_ rerun when the parent scope is rerendered. Because of this Borrowed Props should be reserved for components that are cheap to rerun or places where cloning data is an issue. Using Borrowed Props everywhere will result in large parts of your app rerunning every interaction. - -## Prop Options - -The `#[derive(Props)]` macro has some features that let you customize the behavior of props. - -### Optional Props - -You can create optional fields by using the `Option<…>` type for a field: - -```rust, no_run -{{#include ../../../examples/component_props_options.rs:OptionalProps}} -``` - -Then, you can choose to either provide them or not: - -```rust, no_run -{{#include ../../../examples/component_props_options.rs:OptionalProps_usage}} -``` - -### Explicitly Required `Option`s - -If you want to explicitly require an `Option`, and not an optional prop, you can annotate it with `#[props(!optional)]`: - -```rust, no_run -{{#include ../../../examples/component_props_options.rs:ExplicitOption}} -``` - -Then, you have to explicitly pass either `Some("str")` or `None`: - -```rust, no_run -{{#include ../../../examples/component_props_options.rs:ExplicitOption_usage}} -``` - -### Default Props - -You can use `#[props(default = 42)]` to make a field optional and specify its default value: - -```rust, no_run -{{#include ../../../examples/component_props_options.rs:DefaultComponent}} -``` - -Then, similarly to optional props, you don't have to provide it: - -```rust, no_run -{{#include ../../../examples/component_props_options.rs:DefaultComponent_usage}} -``` - -### Automatic Conversion with `.into` - -It is common for Rust functions to accept `impl Into` rather than just `SomeType` to support a wider range of parameters. If you want similar functionality with props, you can use `#[props(into)]`. For example, you could add it on a `String` prop – and `&str` will also be automatically accepted, as it can be converted into `String`: - -```rust, no_run -{{#include ../../../examples/component_props_options.rs:IntoComponent}} -``` - -Then, you can use it so: - -```rust, no_run -{{#include ../../../examples/component_props_options.rs:IntoComponent_usage}} -``` - -## The `inline_props` macro - -So far, every Component function we've seen had a corresponding ComponentProps struct to pass in props. This was quite verbose... Wouldn't it be nice to have props as simple function arguments? Then we wouldn't need to define a Props struct, and instead of typing `cx.props.whatever`, we could just use `whatever` directly! - -`inline_props` allows you to do just that. Instead of typing the "full" version: - -```rust, no_run -#[derive(Props, PartialEq)] -struct TitleCardProps { - title: String, -} - -fn TitleCard(cx: Scope) -> Element { - cx.render(rsx!{ - h1 { "{cx.props.title}" } - }) -} -``` - -...you can define a function that accepts props as arguments. Then, just annotate it with `#[inline_props]`, and the macro will turn it into a regular Component for you: - -```rust, no_run -#[inline_props] -fn TitleCard(cx: Scope, title: String) -> Element { - cx.render(rsx!{ - h1 { "{title}" } - }) -} -``` - -> While the new Component is shorter and easier to read, this macro should not be used by library authors since you have less control over Prop documentation. diff --git a/docs/guide/src/en/describing_ui/components.md b/docs/guide/src/en/describing_ui/components.md deleted file mode 100644 index 2b72fcaf2..000000000 --- a/docs/guide/src/en/describing_ui/components.md +++ /dev/null @@ -1,27 +0,0 @@ -# Components - -Just like you wouldn't want to write a complex program in a single, long, `main` function, you shouldn't build a complex UI in a single `App` function. Instead, you should break down the functionality of an app in logical parts called components. - -A component is a Rust function, named in UpperCammelCase, that takes a `Scope` parameter and returns an `Element` describing the UI it wants to render. In fact, our `App` function is a component! - -```rust, no_run -{{#include ../../../examples/hello_world_desktop.rs:component}} -``` - -> You'll probably want to add `#![allow(non_snake_case)]` to the top of your crate to avoid warnings about UpperCammelCase component names - -A Component is responsible for some rendering task – typically, rendering an isolated part of the user interface. For example, you could have an `About` component that renders a short description of Dioxus Labs: - -```rust, no_run -{{#include ../../../examples/components.rs:About}} -``` - -Then, you can render your component in another component, similarly to how elements are rendered: - -```rust, no_run -{{#include ../../../examples/components.rs:App}} -``` - -![Screenshot containing the About component twice](./images/screenshot_about_component.png) - -> At this point, it might seem like components are nothing more than functions. However, as you learn more about the features of Dioxus, you'll see that they are actually more powerful! diff --git a/docs/guide/src/en/describing_ui/images/component_borrowed_props_screenshot.png b/docs/guide/src/en/describing_ui/images/component_borrowed_props_screenshot.png deleted file mode 100644 index 6f1864662..000000000 Binary files a/docs/guide/src/en/describing_ui/images/component_borrowed_props_screenshot.png and /dev/null differ diff --git a/docs/guide/src/en/describing_ui/images/component_owned_props_screenshot.png b/docs/guide/src/en/describing_ui/images/component_owned_props_screenshot.png deleted file mode 100644 index 2a1146cd1..000000000 Binary files a/docs/guide/src/en/describing_ui/images/component_owned_props_screenshot.png and /dev/null differ diff --git a/docs/guide/src/en/describing_ui/images/screenshot_about_component.png b/docs/guide/src/en/describing_ui/images/screenshot_about_component.png deleted file mode 100644 index 36f7250a1..000000000 Binary files a/docs/guide/src/en/describing_ui/images/screenshot_about_component.png and /dev/null differ diff --git a/docs/guide/src/en/describing_ui/index.md b/docs/guide/src/en/describing_ui/index.md deleted file mode 100644 index 8e5b3fe8f..000000000 --- a/docs/guide/src/en/describing_ui/index.md +++ /dev/null @@ -1,142 +0,0 @@ -# Describing the UI - -Dioxus is a _declarative_ framework. This means that instead of telling Dioxus what to do (e.g. to "create an element" or "set the color to red") we simply _declare_ what we want the UI to look like using RSX. - -You have already seen a simple example of RSX syntax in the "hello world" application: - -```rust, no_run -{{#include ../../../examples/hello_world_desktop.rs:component}} -``` - -Here, we use the `rsx!` macro to _declare_ that we want a `div` element, containing the text `"Hello, world!"`. Dioxus takes the RSX and constructs a UI from it. - -## RSX Features - -RSX is very similar to HTML in that it describes elements with attributes and children. Here's an empty `div` element in RSX, as well as the resulting HTML: - -```rust, no_run -{{#include ../../../examples/rsx_overview.rs:empty}} -``` - -```html -
-``` - -### Attributes - -Attributes (and [listeners](../interactivity/index.md)) modify the behavior or appearance of the element they are attached to. They are specified inside the `{}` brackets, using the `name: value` syntax. You can provide the value as a literal in the RSX: - -```rust, no_run -{{#include ../../../examples/rsx_overview.rs:attributes}} -``` - -```html -
-``` - -> Note: All attributes defined in `dioxus-html` follow the snake_case naming convention. They transform their `snake_case` names to HTML's `camelCase` attributes. - -> Note: Styles can be used directly outside of the `style:` attribute. In the above example, `color: "red"` is turned into `style="color: red"`. - -#### Custom Attributes - -Dioxus has a pre-configured set of attributes that you can use. RSX is validated at compile time to make sure you didn't specify an invalid attribute. If you want to override this behavior with a custom attribute name, specify the attribute in quotes: - -```rust, no_run -{{#include ../../../examples/rsx_overview.rs:custom_attributes}} -``` - -```html - -``` - -### Interpolation - -Similarly to how you can [format](https://doc.rust-lang.org/rust-by-example/hello/print/fmt.html) Rust strings, you can also interpolate in RSX text. Use `{variable}` to Display the value of a variable in a string, or `{variable:?}` to use the Debug representation: - -```rust, no_run -{{#include ../../../examples/rsx_overview.rs:formatting}} -``` - -```html -
-
ES
-
42
-
{}
-
-``` - -### Children - -To add children to an element, put them inside the `{}` brackets after all attributes and listeners in the element. They can be other elements, text, or [components](components.md). For example, you could have an `ol` (ordered list) element, containing 3 `li` (list item) elements, each of which contains some text: - -```rust, no_run -{{#include ../../../examples/rsx_overview.rs:children}} -``` - -```html -
    -
  1. First Item
  2. -
  3. Second Item
  4. -
  5. Third Item
  6. -
-``` - -### Fragments - -You can render multiple elements at the top level of `rsx!` and they will be automatically grouped. - -```rust, no_run -{{#include ../../../examples/rsx_overview.rs:manyroots}} -``` - -```html -

First Item

-

Second Item

-``` - -### Expressions - -You can include arbitrary Rust expressions as children within RSX that implements [IntoDynNode](https://docs.rs/dioxus-core/0.3/dioxus_core/trait.IntoDynNode.html). This is useful for displaying data from an [iterator](https://doc.rust-lang.org/stable/book/ch13-02-iterators.html#processing-a-series-of-items-with-iterators): - -```rust, no_run -{{#include ../../../examples/rsx_overview.rs:expression}} -``` - -```html -DIOXUS0123456789 -``` - -### Loops - -In addition to iterators you can also use for loops directly within RSX: - -```rust, no_run -{{#include ../../../examples/rsx_overview.rs:loops}} -``` - -```html -
0
-
1
-
2
-
0
-
1
-
2
-``` - -### If statements - -You can also use if statements without an else branch within RSX: - -```rust, no_run -{{#include ../../../examples/rsx_overview.rs:ifstatements}} -``` - -```html -
true
-``` diff --git a/docs/guide/src/en/describing_ui/special_attributes.md b/docs/guide/src/en/describing_ui/special_attributes.md deleted file mode 100644 index 4ba7a40f1..000000000 --- a/docs/guide/src/en/describing_ui/special_attributes.md +++ /dev/null @@ -1,62 +0,0 @@ -# Special Attributes - -While most attributes are simply passed on to the HTML, some have special behaviors. - -## The HTML Escape Hatch - -If you're working with pre-rendered assets, output from templates, or output from a JS library, then you might want to pass HTML directly instead of going through Dioxus. In these instances, reach for `dangerous_inner_html`. - -For example, shipping a markdown-to-Dioxus converter might significantly bloat your final application size. Instead, you'll want to pre-render your markdown to HTML and then include the HTML directly in your output. We use this approach for the [Dioxus homepage](https://dioxuslabs.com): - -```rust, no_run -{{#include ../../../examples/dangerous_inner_html.rs:dangerous_inner_html}} -``` - -> Note! This attribute is called "dangerous_inner_html" because it is **dangerous** to pass it data you don't trust. If you're not careful, you can easily expose [cross-site scripting (XSS)](https://en.wikipedia.org/wiki/Cross-site_scripting) attacks to your users. -> -> If you're handling untrusted input, make sure to sanitize your HTML before passing it into `dangerous_inner_html` – or just pass it to a Text Element to escape any HTML tags. - -## Boolean Attributes - -Most attributes, when rendered, will be rendered exactly as the input you provided. However, some attributes are considered "boolean" attributes and just their presence determines whether they affect the output. For these attributes, a provided value of `"false"` will cause them to be removed from the target element. - -So this RSX wouldn't actually render the `hidden` attribute: - -```rust, no_run -{{#include ../../../examples/boolean_attribute.rs:boolean_attribute}} -``` - -```html -
hello
-``` - -Not all attributes work like this however. _Only the following attributes_ have this behavior: - -- `allowfullscreen` -- `allowpaymentrequest` -- `async` -- `autofocus` -- `autoplay` -- `checked` -- `controls` -- `default` -- `defer` -- `disabled` -- `formnovalidate` -- `hidden` -- `ismap` -- `itemscope` -- `loop` -- `multiple` -- `muted` -- `nomodule` -- `novalidate` -- `open` -- `playsinline` -- `readonly` -- `required` -- `reversed` -- `selected` -- `truespeed` - -For any other attributes, a value of `"false"` will be sent directly to the DOM. diff --git a/docs/guide/src/en/fullstack/getting_started.md b/docs/guide/src/en/fullstack/getting_started.md deleted file mode 100644 index 401af1d43..000000000 --- a/docs/guide/src/en/fullstack/getting_started.md +++ /dev/null @@ -1,102 +0,0 @@ -> This guide assumes you read the [Web](web.md) guide and installed the [Dioxus-cli](https://github.com/DioxusLabs/cli) - -# Getting Started - -## Setup - -For this guide, we're going to show how to use Dioxus with [Axum](https://docs.rs/axum/latest/axum/), but `dioxus-fullstack` also integrates with the [Warp](https://docs.rs/warp/latest/warp/) and [Salvo](https://docs.rs/salvo/latest/salvo/) web frameworks. - -Make sure you have Rust and Cargo installed, and then create a new project: - -```shell -cargo new --bin demo -cd demo -``` - -Add `dioxus` and `dioxus-fullstack` as dependencies: - -```shell -cargo add dioxus -cargo add dioxus-fullstack --features axum, ssr -``` - -Next, add all the Axum dependencies. This will be different if you're using a different Web Framework - -```shell -cargo add tokio --features full -cargo add axum -``` - -Your dependencies should look roughly like this: - -```toml -[dependencies] -axum = "*" -dioxus = { version = "*" } -dioxus-fullstack = { version = "*", features = ["axum", "ssr"] } -tokio = { version = "*", features = ["full"] } -``` - -Now, set up your Axum app to serve the Dioxus app. - -```rust, no_run -{{#include ../../../examples/server_basic.rs}} -``` - -Now, run your app with `cargo run` and open `http://localhost:8080` in your browser. You should see a server-side rendered page with a counter. - -## Hydration - -Right now, the page is static. We can't interact with the buttons. To fix this, we can hydrate the page with `dioxus-web`. - -First, modify your `Cargo.toml` to include two features, one for the server called `ssr`, and one for the client called `web`. - -```toml -[dependencies] -# Common dependancies -dioxus = { version = "*" } -dioxus-fullstack = { version = "*" } - -# Web dependancies -dioxus-web = { version = "*", features=["hydrate"], optional = true } - -# Server dependancies -axum = { version = "0.6.12", optional = true } -tokio = { version = "1.27.0", features = ["full"], optional = true } - -[features] -default = [] -ssr = ["axum", "tokio", "dioxus-fullstack/axum"] -web = ["dioxus-web"] -``` - -Next, we need to modify our `main.rs` to use either hydrate on the client or render on the server depending on the active features. - -```rust, no_run -{{#include ../../../examples/hydration.rs}} -``` - -Now, build your client-side bundle with `dx build --features web` and run your server with `cargo run --features ssr`. You should see the same page as before, but now you can interact with the buttons! - -## Sycronizing props between the server and client - -Let's make the initial count of the counter dynamic based on the current page. - -### Modifying the server - -To do this, we must remove the serve_dioxus_application and replace it with a custom implementation of its four key functions: - -- Serve static WASM and JS files with serve_static_assets -- Register server functions with register_server_fns (more information on server functions later) -- Connect to the hot reload server with connect_hot_reload -- A custom route that uses SSRState to server-side render the application - -### Modifying the client - -The only thing we need to change on the client is the props. `dioxus-fullstack` will automatically serialize the props it uses to server render the app and send them to the client. In the client section of `main.rs`, we need to add `get_root_props_from_document` to deserialize the props before we hydrate the app. - -```rust, no_run -{{#include ../../../examples/hydration_props.rs}} -``` - -Now, build your client-side bundle with `dx build --features web` and run your server with `cargo run --features ssr`. Navigate to `http://localhost:8080/1` and you should see the counter start at 1. Navigate to `http://localhost:8080/2` and you should see the counter start at 2. diff --git a/docs/guide/src/en/fullstack/index.md b/docs/guide/src/en/fullstack/index.md deleted file mode 100644 index a9b39c8f1..000000000 --- a/docs/guide/src/en/fullstack/index.md +++ /dev/null @@ -1,59 +0,0 @@ -# Fullstack development - -So far you have learned about three different approaches to target the web with Dioxus: - -- [Client-side rendering with dioxus-web](../getting_started/web.md) -- [Server-side rendering with dioxus-liveview](../getting_started/liveview.md) -- [Server-side static HTML generation with dioxus-ssr](../getting_started/ssr.md) - -## Summary of Existing Approaches - -Each approach has its tradeoffs: - -### Client-side rendering - -- With Client side rendering, you send the entire content of your application to the client, and then the client generates all of the HTML of the page dynamically. - -- This means that the page will be blank until the JavaScript bundle has loaded and the application has initialized. This can result in **slower first render times and makes the page less SEO-friendly**. - -> SEO stands for Search Engine Optimization. It refers to the practice of making your website more likely to appear in search engine results. Search engines like Google and Bing use web crawlers to index the content of websites. Most of these crawlers are not able to run JavaScript, so they will not be able to index the content of your page if it is rendered client-side. - -- Client-side rendered applications need to use **weakly typed requests to communicate with the server** - -> Client-side rendering is a good starting point for most applications. It is well supported and makes it easy to communicate with the client/browser APIs - -### Liveview - -- Liveview rendering communicates with the server over a WebSocket connection. It essentially moves all of the work that Client-side rendering does to the server. - -- This makes it **easy to communicate with the server, but more difficult to communicate with the client/browser APIS**. - -- Each interaction also requires a message to be sent to the server and back which can cause **issues with latency**. - -- Because Liveview uses a websocket to render, the page will be blank until the WebSocket connection has been established and the first renderer has been sent form the websocket. Just like with client side rendering, this can make the page **less SEO-friendly**. - -- Because the page is rendered on the server and the page is sent to the client piece by piece, you never need to send the entire application to the client. The initial load time can be faster than client-side rendering with large applications because Liveview only needs to send a constant small websocket script regardless of the size of the application. - -> Liveview is a good fit for applications that already need to communicate with the server frequently (like real time collaborative apps), but don't need to communicate with as many client/browser APIs - -### Server-side rendering - -- Server-side rendering generates all of the HTML of the page on the server before the page is sent to the client. This means that the page will be fully rendered when it is sent to the client. This results in a faster first render time and makes the page more SEO-friendly. However, it **only works for static pages**. - -> Server-side rendering is not a good fit for purely static sites like a blog - -## A New Approach - -Each of these approaches has its tradeoffs. What if we could combine the best parts of each approach? - -- **Fast initial render** time like SSR -- **Works well with SEO** like SSR -- **Type safe easy communication with the server** like Liveview -- **Access to the client/browser APIs** like Client-side rendering -- **Fast interactivity** like Client-side rendering - -We can achieve this by rendering the initial page on the server (SSR) and then taking over rendering on the client (Client-side rendering). Taking over rendering on the client is called **hydration**. - -Finally, we can use [server functions](server_functions.md) to communicate with the server in a type-safe way. - -This approach uses both the dioxus-web and dioxus-ssr crates. To integrate those two packages and `axum`, `warp`, or `salvo`, Dioxus provides the `dioxus-fullstack` crate. diff --git a/docs/guide/src/en/fullstack/server_functions.md b/docs/guide/src/en/fullstack/server_functions.md deleted file mode 100644 index 581aa382a..000000000 --- a/docs/guide/src/en/fullstack/server_functions.md +++ /dev/null @@ -1,31 +0,0 @@ -# Communicating with the server - -`dixous-server` provides server functions that allow you to call an automatically generated API on the server from the client as if it were a local function. - -To make a server function, simply add the `#[server(YourUniqueType)]` attribute to a function. The function must: - -- Be an async function -- Have arguments and a return type that both implement serialize and deserialize (with [serde](https://serde.rs/)). -- Return a `Result` with an error type of ServerFnError - -You must call `register` on the type you passed into the server macro in your main function before starting your server to tell Dioxus about the server function. - -Let's continue building on the app we made in the [getting started](./getting_started.md) guide. We will add a server function to our app that allows us to double the count on the server. - -First, add serde as a dependency: - -```shell -cargo add serde -``` - -Next, add the server function to your `main.rs`: - -```rust, no_run -{{#include ../../../examples/server_function.rs}} -``` - -Now, build your client-side bundle with `dx build --features web` and run your server with `cargo run --features ssr`. You should see a new button that multiplies the count by 2. - -## Conclusion - -That's it! You've created a full-stack Dioxus app. You can find more examples of full-stack apps and information about how to integrate with other frameworks and desktop renderers in the [dioxus-fullstack examples directory](https://github.com/DioxusLabs/dioxus/tree/master/packages/server/examples). diff --git a/docs/guide/src/en/getting_started/desktop.md b/docs/guide/src/en/getting_started/desktop.md deleted file mode 100644 index 42fe5c1a2..000000000 --- a/docs/guide/src/en/getting_started/desktop.md +++ /dev/null @@ -1,77 +0,0 @@ -# Desktop Overview - -Build a standalone native desktop app that looks and feels the same across operating systems. - -Apps built with Dioxus are typically <5mb in size and use existing system resources, so they won't hog extreme amounts of RAM or memory. - -Examples: - -- [File Explorer](https://github.com/DioxusLabs/example-projects/blob/master/file-explorer) -- [WiFi Scanner](https://github.com/DioxusLabs/example-projects/blob/master/wifi-scanner) - -[![File ExplorerExample](https://raw.githubusercontent.com/DioxusLabs/example-projects/master/file-explorer/image.png)](https://github.com/DioxusLabs/example-projects/tree/master/file-explorer) - -## Support - -The desktop is a powerful target for Dioxus but is currently limited in capability when compared to the Web platform. Currently, desktop apps are rendered with the platform's WebView library, but your Rust code is running natively on a native thread. This means that browser APIs are _not_ available, so rendering WebGL, Canvas, etc is not as easy as the Web. However, native system APIs _are_ accessible, so streaming, WebSockets, filesystem, etc are all viable APIs. In the future, we plan to move to a custom web renderer-based DOM renderer with WGPU integrations. - -Dioxus Desktop is built off [Tauri](https://tauri.app/). Right now there aren't any Dioxus abstractions over the 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. - -# Getting started - -## Platform-Specific Dependencies - -Dioxus desktop renders through a web view. Depending on your platform, you might need to install some dependancies. - -### Windows - -Windows Desktop apps depend on WebView2 – a library that should be installed in all modern Windows distributions. If you have Edge installed, then Dioxus will work fine. If you _don't_ have Webview2, [then you can install it through Microsoft](https://developer.microsoft.com/en-us/microsoft-edge/webview2/). MS provides 3 options: - -1. A tiny "evergreen" _bootstrapper_ that fetches an installer from Microsoft's CDN -2. A tiny _installer_ that fetches Webview2 from Microsoft's CDN -3. A statically linked version of Webview2 in your final binary for offline users - -For development purposes, use Option 1. - -### Linux - -Webview Linux apps require WebkitGtk. When distributing, this can be part of your dependency tree in your `.rpm` or `.deb`. However, likely, your users will already have WebkitGtk. - -```bash -sudo apt install libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev -``` - -When using Debian/bullseye `libappindicator3-dev` is no longer available but replaced by `libayatana-appindicator3-dev`. - -```bash -# on Debian/bullseye use: -sudo apt install libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev -``` - -If you run into issues, make sure you have all the basics installed, as outlined in the [Tauri docs](https://tauri.studio/v1/guides/getting-started/prerequisites#setting-up-linux). - -### MacOS - -Currently – everything for macOS is built right in! However, you might run into an issue if you're using nightly Rust due to some permissions issues in our Tao dependency (which have been resolved but not published). - -## Creating a Project - -Create a new crate: - -```shell -cargo new --bin demo -cd demo -``` - -Add Dioxus and the desktop renderer as dependencies (this will edit your `Cargo.toml`): - -```shell -cargo add dioxus -cargo add dioxus-desktop -``` - -Edit your `main.rs`: - -```rust, no_run -{{#include ../../../examples/hello_world_desktop.rs:all}} -``` diff --git a/docs/guide/src/en/getting_started/fullstack.md b/docs/guide/src/en/getting_started/fullstack.md deleted file mode 100644 index fa3ba67c2..000000000 --- a/docs/guide/src/en/getting_started/fullstack.md +++ /dev/null @@ -1 +0,0 @@ -# Fullstack diff --git a/docs/guide/src/en/getting_started/hot_reload.md b/docs/guide/src/en/getting_started/hot_reload.md deleted file mode 100644 index d207f361a..000000000 --- a/docs/guide/src/en/getting_started/hot_reload.md +++ /dev/null @@ -1,60 +0,0 @@ -# Setting Up Hot Reload - -1. Hot reloading allows much faster iteration times inside of rsx calls by interpreting 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. For TUI, desktop, and LiveView you can use the hot reload macro instead. - -# Web - -For the web renderer, you can use the dioxus cli to serve your application with hot reloading enabled. - -## Setup - -Install [dioxus-cli](https://github.com/DioxusLabs/cli). -Hot reloading is automatically enabled when using the web renderer on debug builds. - -## Usage - -1. Run: - -```bash -dx serve --hot-reload -``` - -2. Change some code within a rsx or render macro -3. Open your localhost in a browser -4. Save and watch the style change without recompiling - -# Desktop/Liveview/TUI/Server - -For desktop, LiveView, and tui, you can place the hot reload macro at the top of your main function to enable hot reloading. -Hot reloading is automatically enabled on debug builds. - -For more information about hot reloading on native platforms and configuration options see the [dioxus-hot-reload](https://crates.io/crates/dioxus-hot-reload) crate. - -## Setup - -Add the following to your main function: - -```rust, no_run -fn main() { - hot_reload_init!(); - // launch your application -} -``` - -## Usage - -1. Run: - -```bash -cargo run -``` - -2. Change some code within a rsx or render macro -3. Save and watch the style change without recompiling - -# Limitations - -1. The interpreter 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 require a full recompile to capture the expression. -2. Components, Iterators, and some attributes can contain arbitrary rust code and will trigger a full recompile when changed. diff --git a/docs/guide/src/en/getting_started/index.md b/docs/guide/src/en/getting_started/index.md deleted file mode 100644 index fbf0b2d05..000000000 --- a/docs/guide/src/en/getting_started/index.md +++ /dev/null @@ -1,34 +0,0 @@ -# Getting Started - -This section will help you set up your Dioxus project! - -## Prerequisites - -### An Editor - -Dioxus integrates very well with the [Rust-Analyzer LSP plugin](https://rust-analyzer.github.io) which will provide appropriate syntax highlighting, code navigation, folding, and more. - -### Rust - -Head over to [https://rust-lang.org](http://rust-lang.org) and install the Rust compiler. - -We strongly recommend going through the [official Rust book](https://doc.rust-lang.org/book/ch01-00-getting-started.html) _completely_. However, we hope that a Dioxus app can serve as a great first Rust project. With Dioxus, you'll learn about: - -- Error handling -- Structs, Functions, Enums -- Closures -- Macros - -We've put a lot of care into making Dioxus syntax familiar and easy to understand, so you won't need deep knowledge of async, lifetimes, or smart pointers until you start building complex Dioxus apps. - - -## Setup Guides - -Dioxus supports multiple platforms. Choose the platform you want to target below to get platform-specific setup instructions: - -- [Web](web.md): runs in the browser through WebAssembly -- [Server Side Rendering](ssr.md): renders to HTML text on the server -- [Liveview](liveview.md): runs on the server, renders in the browser using WebSockets -- [Desktop](desktop.md): runs in a web view on desktop -- [Mobile](mobile.md): runs in a web view on mobile -- [Terminal UI](tui.md): renders text-based graphics in the terminal \ No newline at end of file diff --git a/docs/guide/src/en/getting_started/liveview.md b/docs/guide/src/en/getting_started/liveview.md deleted file mode 100644 index 56847cab5..000000000 --- a/docs/guide/src/en/getting_started/liveview.md +++ /dev/null @@ -1,62 +0,0 @@ -# Liveview - -Liveview allows apps to _run_ on the server and _render_ in the browser. It uses WebSockets to communicate between the server and the browser. - -Examples: - -- [Axum Example](https://github.com/DioxusLabs/dioxus/tree/master/packages/liveview/examples/axum.rs) -- [Salvo Example](https://github.com/DioxusLabs/dioxus/tree/master/packages/liveview/examples/salvo.rs) -- [Warp Example](https://github.com/DioxusLabs/dioxus/tree/master/packages/liveview/examples/warp.rs) - -## Support - -Liveview is currently limited in capability when compared to the Web platform. Liveview apps run on the server in a native thread. This means that browser APIs are not available, so rendering WebGL, Canvas, etc is not as easy as the Web. However, native system APIs are accessible, so streaming, WebSockets, filesystem, etc are all viable APIs. - -## Setup - -For this guide, we're going to show how to use Dioxus Liveview with [Axum](https://docs.rs/axum/latest/axum/). - -Make sure you have Rust and Cargo installed, and then create a new project: - -```shell -cargo new --bin demo -cd app -``` - -Add Dioxus and the liveview renderer with the Axum feature as dependencies: - -```shell -cargo add dioxus -cargo add dioxus-liveview --features axum -``` - -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 = "*" } -dioxus-liveview = { version = "*", features = ["axum"] } -tokio = { version = "1.15.0", features = ["full"] } -``` - -Now, set up your Axum app to respond on an endpoint. - -```rust, no_run -{{#include ../../../examples/hello_world_liveview.rs:glue}} -``` - -And then add our app component: - -```rust, no_run -{{#include ../../../examples/hello_world_liveview.rs:app}} -``` - -And that's it! diff --git a/docs/guide/src/en/getting_started/mobile.md b/docs/guide/src/en/getting_started/mobile.md deleted file mode 100644 index 72d597f51..000000000 --- a/docs/guide/src/en/getting_started/mobile.md +++ /dev/null @@ -1,76 +0,0 @@ -# Mobile App - -Build a mobile app with Dioxus! - -Example: [Todo App](https://github.com/DioxusLabs/example-projects/blob/master/ios_demo) - -## Support - -Mobile is currently the least-supported renderer target for Dioxus. Mobile apps are rendered with either the platform's WebView or experimentally through [WGPU](https://github.com/DioxusLabs/blitz). WebView doesn't support animations, transparency, and native widgets. - -Mobile support is currently best suited for CRUD-style apps, ideally for internal teams who need to develop quickly but don't care much about animations or native widgets. - -This guide is primarily targeted at iOS apps, however, you can follow it while using the `android` guide in `cargo-mobile`. - -## 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 = [] -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 = "*"} -dioxus-desktop = { version = "*" } -simple_logger = "*" -``` - -Edit your `lib.rs`: - -```rust, no_run -use dioxus::prelude::*; - -fn main() { - dioxus_desktop::launch(app); -} - -fn app(cx: Scope) -> Element { - cx.render(rsx!{ - div { - "hello world!" - } - }) -} -``` diff --git a/docs/guide/src/en/getting_started/ssr.md b/docs/guide/src/en/getting_started/ssr.md deleted file mode 100644 index 080efbb6d..000000000 --- a/docs/guide/src/en/getting_started/ssr.md +++ /dev/null @@ -1,71 +0,0 @@ -# Server-Side Rendering - -For lower-level control over the rendering process, you can use the `dioxus-ssr` crate directly. This can be useful when integrating with a web framework that `dioxus-server` does not support, or pre-rendering pages. - -## Setup - -For this guide, we're going to show how to use Dioxus SSR with [Axum](https://docs.rs/axum/latest/axum/). - -Make sure you have Rust and Cargo installed, and then create a new project: - -```shell -cargo new --bin demo -cd demo -``` - -Add Dioxus and the ssr renderer as dependencies: - -```shell -cargo add dioxus -cargo add dioxus-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 = "*" } -dioxus-ssr = { version = "*" } -tokio = { version = "1.15.0", features = ["full"] } -``` - -Now, set up your Axum app to respond on an endpoint. - -```rust, no_run -{{#include ../../../examples/hello_world_ssr.rs:main}} -``` - -And then add our endpoint. We can either render `rsx!` directly: - -```rust, no_run -{{#include ../../../examples/hello_world_ssr.rs:endpoint}} -``` - -Or we can render VirtualDoms. - -```rust, no_run -{{#include ../../../examples/hello_world_ssr.rs:second_endpoint}} -``` - -And then add our app component: - -```rust -{{#include ../../../examples/hello_world_ssr.rs:component}} -``` - -And that's it! - - -## Multithreaded Support - -The Dioxus VirtualDom, sadly, is not currently `Send`. Internally, we use quite a bit of interior mutability which is not thread-safe. -When working with web frameworks that require `Send`, it is possible to render a VirtualDom immediately to a String – but you cannot hold the VirtualDom across an await point. For retained-state SSR (essentially LiveView), you'll need to spawn a VirtualDom on its own thread and communicate with it via channels or create a pool of VirtualDoms. -You might notice that you cannot hold the VirtualDom across an await point. Because Dioxus is currently not ThreadSafe, it _must_ remain on the thread it started. We are working on loosening this requirement. diff --git a/docs/guide/src/en/getting_started/tui.md b/docs/guide/src/en/getting_started/tui.md deleted file mode 100644 index 504c01212..000000000 --- a/docs/guide/src/en/getting_started/tui.md +++ /dev/null @@ -1,46 +0,0 @@ -# Terminal UI - -You can build a text-based interface that will run in the terminal using Dioxus. - -![Hello World screenshot](https://github.com/DioxusLabs/rink/raw/master/examples/example.png) - -> Note: this book was written with HTML-based platforms in mind. You might be able to follow along with TUI, but you'll have to adapt a bit. - -## Support - -TUI support is currently quite experimental. But, if you're willing to venture into the realm of the unknown, this guide will get you started. - -- It uses flexbox for the layout -- It only supports a subset of the attributes and elements -- Regular widgets will not work in the tui render, but the tui renderer has its own widget components that start with a capital letter. See the [widgets example](https://github.com/DioxusLabs/dioxus/blob/master/packages/dioxus-tui/examples/widgets.rs) -- 1px is one character line height. Your regular CSS px does not translate -- If your app panics, your terminal is wrecked. This will be fixed eventually - -## Getting Set up - -Start by making a new package and adding Dioxus and the TUI renderer as dependancies. - -```shell -cargo new --bin demo -cd demo -cargo add dioxus -cargo add dioxus-tui -``` - -Then, edit your `main.rs` with the basic template. - -```rust, no_run -{{#include ../../../examples/hello_world_tui.rs}} -``` - -To run our app: - -```shell -cargo run -``` - -Press "ctrl-c" to close the app. To switch from "ctrl-c" to just "q" to quit you can launch the app with a configuration to disable the default quit and use the root TuiContext to quit on your own. - -```rust, no_run -{{#include ../../../examples/hello_world_tui_no_ctrl_c.rs}} -``` diff --git a/docs/guide/src/en/getting_started/web.md b/docs/guide/src/en/getting_started/web.md deleted file mode 100644 index 07139cce6..000000000 --- a/docs/guide/src/en/getting_started/web.md +++ /dev/null @@ -1,63 +0,0 @@ -# Web - -Build single-page applications that run in the browser with Dioxus. To run on the Web, your app must be compiled to WebAssembly and depend on the `dioxus` and `dioxus-web` crates. - -A build of Dioxus for the web will be roughly equivalent to the size of a React build (70kb vs 65kb) but it will load significantly faster because [WebAssembly can be compiled as it is streamed](https://hacks.mozilla.org/2018/01/making-webassembly-even-faster-firefoxs-new-streaming-and-tiering-compiler/). - -Examples: - -- [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) - -> Note: Because of the limitations of Wasm, [not every crate will work](https://rustwasm.github.io/docs/book/reference/which-crates-work-with-wasm.html) with your web apps, so you'll need to make sure that your crates work without native system calls (timers, IO, etc). - -## Support - -The Web is the best-supported target platform for Dioxus. - -- Because your app will be compiled to WASM you have access to browser APIs through [wasm-bindgen](https://rustwasm.github.io/docs/wasm-bindgen/introduction.html). -- Dioxus provides hydration to resume apps that are rendered on the server. See the [fullstack](fullstack.md) getting started guide for more information. - -## Tooling - -To develop your Dioxus app for the web, you'll need a tool to build and serve your assets. We recommend using [dioxus-cli](https://github.com/DioxusLabs/dioxus/tree/master/packages/cli) which includes a build system, Wasm optimization, a dev server, and support hot reloading: - -```shell -cargo install dioxus-cli --locked -``` - -Make sure the `wasm32-unknown-unknown` target for rust is installed: - -```shell -rustup target add wasm32-unknown-unknown -``` - -## Creating a Project - -Create a new crate: - -```shell -cargo new --bin demo -cd demo -``` - -Add Dioxus and the web renderer as dependencies (this will edit your `Cargo.toml`): - -```bash -cargo add dioxus -cargo add dioxus-web -``` - -Edit your `main.rs`: - -```rust, no_run -{{#include ../../../examples/hello_world_web.rs}} -``` - -And to serve our app: - -```bash -dx serve -``` diff --git a/docs/guide/src/en/images/compiletimecorrect.png b/docs/guide/src/en/images/compiletimecorrect.png deleted file mode 100644 index 8fab7509f..000000000 Binary files a/docs/guide/src/en/images/compiletimecorrect.png and /dev/null differ diff --git a/docs/guide/src/en/images/component_tree.png b/docs/guide/src/en/images/component_tree.png deleted file mode 100644 index d96924073..000000000 Binary files a/docs/guide/src/en/images/component_tree.png and /dev/null differ diff --git a/docs/guide/src/en/images/diffing.png b/docs/guide/src/en/images/diffing.png deleted file mode 100644 index 4c243bc75..000000000 Binary files a/docs/guide/src/en/images/diffing.png and /dev/null differ diff --git a/docs/guide/src/en/images/dioxuslogo_full.png b/docs/guide/src/en/images/dioxuslogo_full.png deleted file mode 100644 index 7d08f2af8..000000000 Binary files a/docs/guide/src/en/images/dioxuslogo_full.png and /dev/null differ diff --git a/docs/guide/src/en/images/oldnew.png b/docs/guide/src/en/images/oldnew.png deleted file mode 100644 index 5aca37e40..000000000 Binary files a/docs/guide/src/en/images/oldnew.png and /dev/null differ diff --git a/docs/guide/src/en/images/publish.png b/docs/guide/src/en/images/publish.png deleted file mode 100644 index b17d3bb06..000000000 Binary files a/docs/guide/src/en/images/publish.png and /dev/null differ diff --git a/docs/guide/src/en/index.md b/docs/guide/src/en/index.md deleted file mode 100644 index bbebb0bc9..000000000 --- a/docs/guide/src/en/index.md +++ /dev/null @@ -1,52 +0,0 @@ -# Introduction - -![dioxuslogo](./images/dioxuslogo_full.png) - -Dioxus is a portable, performant, and ergonomic framework for building cross-platform user interfaces in Rust. This guide will help you get started with writing Dioxus apps for the Web, Desktop, Mobile, and more. - -```rust, no_run -fn app(cx: Scope) -> Element { - let mut count = use_state(cx, || 0); - - cx.render(rsx!( - h1 { "High-Five counter: {count}" } - button { onclick: move |_| count += 1, "Up high!" } - button { onclick: move |_| count -= 1, "Down low!" } - )) -} -``` - -Dioxus is heavily inspired by React. If you know React, getting started with Dioxus will be a breeze. - -> This guide assumes you already know some [Rust](https://www.rust-lang.org/)! If not, we recommend reading [_the book_](https://doc.rust-lang.org/book/ch01-00-getting-started.html) to learn Rust first. - -## Features - -- Desktop apps running natively (no Electron!) in less than 10 lines of code. -- Incredibly ergonomic and powerful state management. -- Comprehensive inline documentation – hover and guides for all HTML elements, listeners, and events. -- Extremely memory efficient – 0 global allocations for steady-state components. -- Multi-channel asynchronous scheduler for first-class async support. -- And more! Read the [full release post](https://dioxuslabs.com/blog/introducing-dioxus/). - -### Multiplatform - -Dioxus is a _portable_ toolkit, meaning the Core implementation can run anywhere with no platform-dependent linking. Unlike many other Rust frontend toolkits, Dioxus is not intrinsically linked to WebSys. In fact, every element and event listener can be swapped out at compile time. By default, Dioxus ships with the `html` feature enabled, but this can be disabled depending on your target renderer. - -Right now, we have several 1st-party renderers: - -- WebSys (for WASM): Great support -- Tao/Tokio (for Desktop apps): Good support -- Tao/Tokio (for Mobile apps): Poor support -- SSR (for generating static markup) -- TUI/Rink (for terminal-based apps): Experimental - -## Stability - -Dioxus has not reached a stable release yet. - -Web: Since the web is a fairly mature platform, we expect there to be very little API churn for web-based features. - -Desktop: APIs will likely be in flux as we figure out better patterns than our ElectronJS counterpart. - -SSR: We don't expect the SSR API to change drastically in the future. diff --git a/docs/guide/src/en/interactivity/custom_hooks.md b/docs/guide/src/en/interactivity/custom_hooks.md deleted file mode 100644 index d075bb632..000000000 --- a/docs/guide/src/en/interactivity/custom_hooks.md +++ /dev/null @@ -1,91 +0,0 @@ -# Custom Hooks - -Hooks are a great way to encapsulate business logic. If none of the existing hooks work for your problem, you can write your own. - -When writing your hook, you can make a function that accepts `cx: &ScopeState` as a parameter to accept a scope with any Props. - -## Composing Hooks - -To avoid repetition, you can encapsulate business logic based on existing hooks to create a new hook. - -For example, if many components need to access an `AppSettings` struct, you can create a "shortcut" hook: - -```rust, no_run -{{#include ../../../examples/hooks_composed.rs:wrap_context}} -``` - -Or if you want to wrap a hook that persists reloads with the storage API, you can build on top of the use_ref hook to work with mutable state: - -```rust, no_run -{{#include ../../../examples/hooks_composed.rs:use_storage}} -``` - -## Custom Hook Logic - -You can use [`cx.use_hook`](https://docs.rs/dioxus/latest/dioxus/prelude/struct.ScopeState.html#method.use_hook) to build your own hooks. In fact, this is what all the standard hooks are built on! - -`use_hook` accepts a single closure for initializing the hook. It will be only run the first time the component is rendered. The return value of that closure will be used as the value of the hook – Dioxus will take it, and store it for as long as the component is alive. On every render (not just the first one!), you will get a reference to this value. - -> Note: You can implement [`Drop`](https://doc.rust-lang.org/std/ops/trait.Drop.html) for your hook value – it will be dropped then the component is unmounted (no longer in the UI) - -Inside the initialization closure, you will typically make calls to other `cx` methods. For example: - -- The `use_state` hook tracks state in the hook value, and uses [`cx.schedule_update`](https://docs.rs/dioxus/latest/dioxus/prelude/struct.ScopeState.html#method.schedule_update) to make Dioxus re-render the component whenever it changes. - -Here is a simplified implementation of the `use_state` hook: - -```rust, no_run -{{#include ../../../examples/hooks_custom_logic.rs:use_state}} -``` - -- The `use_context` hook calls [`cx.consume_context`](https://docs.rs/dioxus/latest/dioxus/prelude/struct.ScopeState.html#method.consume_context) (which would be expensive to call on every render) to get some context from the scope - -Here is an implementation of the `use_context` and `use_context_provider` hooks: - -```rust, no_run -{{#include ../../../examples/hooks_custom_logic.rs:use_context}} -``` - -## Hook Anti-Patterns - -When writing a custom hook, you should avoid the following anti-patterns: - -- !Clone Hooks: To allow hooks to be used within async blocks, the hooks must be Clone. To make a hook clone, you can wrap data in Rc or Arc and avoid lifetimes in hooks. - -This version of use_state may seem more efficient, but it is not cloneable: - -```rust, no_run -{{#include ../../../examples/hooks_anti_patterns.rs:non_clone_state}} -``` - -If we try to use this hook in an async block, we will get a compile error: - -```rust, no_run -fn FutureComponent(cx: &ScopeState) -> Element { - let my_state = my_use_state(cx, || 0); - cx.spawn({ - to_owned![my_state]; - async move { - my_state.set(1); - } - }); - - todo!() -} -``` - -But with the original version, we can use it in an async block: - -```rust, no_run -fn FutureComponent(cx: &ScopeState) -> Element { - let my_state = use_state(cx, || 0); - cx.spawn({ - to_owned![my_state]; - async move { - my_state.set(1); - } - }); - - todo!() -} -``` diff --git a/docs/guide/src/en/interactivity/dynamic_rendering.md b/docs/guide/src/en/interactivity/dynamic_rendering.md deleted file mode 100644 index 8d91650c3..000000000 --- a/docs/guide/src/en/interactivity/dynamic_rendering.md +++ /dev/null @@ -1,86 +0,0 @@ -# Dynamic Rendering - -Sometimes you want to render different things depending on the state/props. With Dioxus, just describe what you want to see using Rust control flow – the framework will take care of making the necessary changes on the fly if the state or props change! - -## Conditional Rendering - -To render different elements based on a condition, you could use an `if-else` statement: - -```rust, no_run -{{#include ../../../examples/conditional_rendering.rs:if_else}} -``` - -> You could also use `match` statements, or any Rust function to conditionally render different things. - -### Improving the `if-else` Example - -You may have noticed some repeated code in the `if-else` example above. Repeating code like this is both bad for maintainability and performance. Dioxus will skip diffing static elements like the button, but when switching between multiple `rsx` calls it cannot perform this optimization. For this example either approach is fine, but for components with large parts that are reused between conditionals, it can be more of an issue. - -We can improve this example by splitting up the dynamic parts and inserting them where they are needed. - -```rust, no_run -{{#include ../../../examples/conditional_rendering.rs:if_else_improved}} -``` - -### Inspecting `Element` props - -Since `Element` is a `Option`, components accepting `Element` as a prop can inspect its contents, and render different things based on that. Example: - -```rust, no_run -{{#include ../../../examples/component_children_inspect.rs:Clickable}} -``` - -You can't mutate the `Element`, but if you need a modified version of it, you can construct a new one based on its attributes/children/etc. - -## Rendering Nothing - -To render nothing, you can return `None` from a component. This is useful if you want to conditionally hide something: - -```rust, no_run -{{#include ../../../examples/conditional_rendering.rs:conditional_none}} -``` - -This works because the `Element` type is just an alias for `Option` - -> Again, you may use a different method to conditionally return `None`. For example the boolean's [`then()`](https://doc.rust-lang.org/std/primitive.bool.html#method.then) function could be used. - -## Rendering Lists - -Often, you'll want to render a collection of components. For example, you might want to render a list of all comments on a post. - -For this, Dioxus accepts iterators that produce `Element`s. So we need to: - -- Get an iterator over all of our items (e.g., if you have a `Vec` of comments, iterate over it with `iter()`) -- `.map` the iterator to convert each item into a `LazyNode` using `rsx!(...)` - - Add a unique `key` attribute to each iterator item -- Include this iterator in the final RSX (or use it inline) - -Example: suppose you have a list of comments you want to render. Then, you can render them like this: - -```rust, no_run -{{#include ../../../examples/rendering_lists.rs:render_list}} -``` - -### Inline for loops - -Because of how common it is to render a list of items, Dioxus provides a shorthand for this. Instead of using `.iter`, `.map`, and `rsx`, you can use a `for` loop with a body of rsx code: - -```rust, no_run -{{#include ../../../examples/rendering_lists.rs:render_list_for_loop}} -``` - -### The `key` Attribute - -Every time you re-render your list, Dioxus needs to keep track of which items go where to determine what updates need to be made to the UI. - -For example, suppose the `CommentComponent` had some state – e.g. a field where the user typed in a reply. If the order of comments suddenly changes, Dioxus needs to correctly associate that state with the same comment – otherwise, the user will end up replying to a different comment! - -To help Dioxus keep track of list items, we need to associate each item with a unique key. In the example above, we dynamically generated the unique key. In real applications, it's more likely that the key will come from e.g. a database ID. It doesn't matter where you get the key from, as long as it meets the requirements: - -- Keys must be unique in a list -- The same item should always get associated with the same key -- Keys should be relatively small (i.e. converting the entire Comment structure to a String would be a pretty bad key) so they can be compared efficiently - -You might be tempted to use an item's index in the list as its key. That’s what Dioxus will use if you don’t specify a key at all. This is only acceptable if you can guarantee that the list is constant – i.e., no re-ordering, additions, or deletions. - -> Note that if you pass the key to a component you've made, it won't receive the key as a prop. It’s only used as a hint by Dioxus itself. If your component needs an ID, you have to pass it as a separate prop. diff --git a/docs/guide/src/en/interactivity/event_handlers.md b/docs/guide/src/en/interactivity/event_handlers.md deleted file mode 100644 index 4e332adf9..000000000 --- a/docs/guide/src/en/interactivity/event_handlers.md +++ /dev/null @@ -1,72 +0,0 @@ -# Event Handlers - -Event handlers are used to respond to user actions. For example, an event handler could be triggered when the user clicks, scrolls, moves the mouse, or types a character. - -Event handlers are attached to elements. For example, we usually don't care about all the clicks that happen within an app, only those on a particular button. - -Event handlers are similar to regular attributes, but their name usually starts with `on`- and they accept closures as values. The closure will be called whenever the event it listens for is triggered and will be passed that event. - -For example, to handle clicks on an element, we can specify an `onclick` handler: - -```rust, no_run -{{#include ../../../examples/event_click.rs:rsx}} -``` - -## The `Event` object - -Event handlers receive an [`Event`](https://docs.rs/dioxus-core/latest/dioxus_core/struct.Event.html) object containing information about the event. Different types of events contain different types of data. For example, mouse-related events contain [`MouseData`](https://docs.rs/dioxus/latest/dioxus/events/struct.MouseData.html), which tells you things like where the mouse was clicked and what mouse buttons were used. - -In the example above, this event data was logged to the terminal: - -``` -Clicked! Event: UiEvent { bubble_state: Cell { value: true }, data: MouseData { coordinates: Coordinates { screen: (242.0, 256.0), client: (26.0, 17.0), element: (16.0, 7.0), page: (26.0, 17.0) }, modifiers: (empty), held_buttons: EnumSet(), trigger_button: Some(Primary) } } -Clicked! Event: UiEvent { bubble_state: Cell { value: true }, data: MouseData { coordinates: Coordinates { screen: (242.0, 256.0), client: (26.0, 17.0), element: (16.0, 7.0), page: (26.0, 17.0) }, modifiers: (empty), held_buttons: EnumSet(), trigger_button: Some(Primary) } } -``` - -To learn what the different event types for HTML provide, read the [events module docs](https://docs.rs/dioxus-html/latest/dioxus_html/events/index.html). - -### Event propagation - -Some events will trigger first on the element the event originated at upward. For example, a click event on a `button` inside a `div` would first trigger the button's event listener and then the div's event listener. - -> For more information about event propagation see [the mdn docs on event bubbling](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_bubbling) - -If you want to prevent this behavior, you can call `stop_propagation()` on the event: - -```rust, no_run -{{#include ../../../examples/event_nested.rs:rsx}} -``` - -## Prevent Default - -Some events have a default behavior. For keyboard events, this might be entering the typed character. For mouse events, this might be selecting some text. - -In some instances, might want to avoid this default behavior. For this, you can add the `prevent_default` attribute with the name of the handler whose default behavior you want to stop. This attribute can be used for multiple handlers using their name separated by spaces: - -```rust, no_run -{{#include ../../../examples/event_prevent_default.rs:prevent_default}} -``` - -Any event handlers will still be called. - -> Normally, in React or JavaScript, you'd call "preventDefault" on the event in the callback. Dioxus does _not_ currently support this behavior. Note: this means you cannot conditionally prevent default behavior based on the data in the event. - -> Note about forms: if an event handler is attached to the `onsubmit` event of a form, default behavior is to **not submit it**, meaning having `prevent_default: "onsubmit"` will submit it in this case. - -## Handler Props - -Sometimes, you might want to make a component that accepts an event handler. A simple example would be a `FancyButton` component, which accepts an `on_click` handler: - -```rust, no_run -{{#include ../../../examples/event_handler_prop.rs:component_with_handler}} -``` - -Then, you can use it like any other handler: - -```rust, no_run -{{#include ../../../examples/event_handler_prop.rs:usage}} -``` - -> Note: just like any other attribute, you can name the handlers anything you want! Though they must start with `on`, for the prop to be automatically turned into an `EventHandler` at the call site. -> -> You can also put custom data in the event, rather than e.g. `MouseData` diff --git a/docs/guide/src/en/interactivity/hooks.md b/docs/guide/src/en/interactivity/hooks.md deleted file mode 100644 index 8b571dacd..000000000 --- a/docs/guide/src/en/interactivity/hooks.md +++ /dev/null @@ -1,106 +0,0 @@ -# Hooks and Component State - -So far our components have had no state like a normal rust functions. However, in a UI component, it is often useful to have stateful functionality to build user interactions. For example, you might want to track whether the user has opened a drop-down, and render different things accordingly. - -Hooks allow us to create state in our components. Hooks are Rust functions that take a reference to [`ScopeState`](https://docs.rs/dioxus/latest/dioxus/prelude/struct.ScopeState.html) (in a component, you can pass `cx`), and provide you with functionality and state. - -## `use_state` Hook - -[`use_state`](https://docs.rs/dioxus/latest/dioxus/prelude/fn.use_state.html) is one of the simplest hooks. - -- You provide a closure that determines the initial value: `let mut count = use_state(cx, || 0);` -- `use_state` gives you the current value, and a way to update it by setting it to something else -- When the value updates, `use_state` makes the component re-render (along with any other component - that references it), and then provides you with the new value. - -For example, you might have seen the counter example, in which state (a number) is tracked using the `use_state` hook: - -```rust, no_run -{{#include ../../../examples/hooks_counter.rs:component}} -``` - -![Screenshot: counter app](./images/counter.png) - -Every time the component's state changes, it re-renders, and the component function is called, so you can describe what you want the new UI to look like. You don't have to worry about "changing" anything – just describe what you want in terms of the state, and Dioxus will take care of the rest! - -> `use_state` returns your value wrapped in a smart pointer of type [`UseState`](https://docs.rs/dioxus/latest/dioxus/prelude/struct.UseState.html). This is why you can both read the value and update it, even within an event handler. - -You can use multiple hooks in the same component if you want: - -```rust, no_run -{{#include ../../../examples/hooks_counter_two_state.rs:component}} -``` - -![Screenshot: app with two counters](./images/counter_two_state.png) - -## Rules of Hooks - -The above example might seem a bit magic, since Rust functions are typically not associated with state. Dioxus allows hooks to maintain state across renders through a reference to `ScopeState`, which is why you must pass `&cx` to them. - -But how can Dioxus differentiate between multiple hooks in the same component? As you saw in the second example, both `use_state` functions were called with the same parameters, so how come they can return different things when the counters are different? - -```rust, no_run -{{#include ../../../examples/hooks_counter_two_state.rs:use_state_calls}} -``` - -This is only possible because the two hooks are always called in the same order, so Dioxus knows which is which. Because the order you call hooks matters, you must follow certain rules when using hooks: - -1. Hooks may be only used in components or other hooks (we'll get to that later) -2. On every call to a component function - 1. The same hooks must be called (except in the case of early returns, as explained later in the [Error Handling chapter](../best_practices/error_handling.md)) - 2. In the same order -3. Hook names should start with `use_` so you don't accidentally confuse them with regular - functions (`use_state()`, `use_ref()`, `use_future()`, etc...) - -These rules mean that there are certain things you can't do with hooks: - -### No Hooks in Conditionals - -```rust, no_run -{{#include ../../../examples/hooks_bad.rs:conditional}} -``` - -### No Hooks in Closures - -```rust, no_run -{{#include ../../../examples/hooks_bad.rs:closure}} -``` - -### No Hooks in Loops - -```rust, no_run -{{#include ../../../examples/hooks_bad.rs:loop}} -``` - -## `use_ref` Hook - -`use_state` is great for tracking simple values. However, you may notice in the [`UseState` API](https://docs.rs/dioxus/latest/dioxus/hooks/struct.UseState.html) that the only way to modify its value is to replace it with something else (e.g., by calling `set`, or through one of the `+=`, `-=` operators). This works well when it is cheap to construct a value (such as any primitive). But what if you want to maintain more complex data in the components state? - -For example, suppose we want to maintain a `Vec` of values. If we stored it with `use_state`, the -only way to add a new value to the list would be to copy the existing `Vec`, add our value to it, -and then replace the existing `Vec` in the state with it. This is expensive! We want to modify the -existing `Vec` instead. - -Thankfully, there is another hook for that, `use_ref`! It **is** similar to `use_state`, but it lets you get a mutable reference to the contained data. - -Here's a simple example that keeps a list of events in a `use_ref`. We can acquire write access to the state with `.with_mut()`, and then just `.push` a new value to the state: - -```rust, no_run -{{#include ../../../examples/hooks_use_ref.rs:component}} -``` - -> The return values of `use_state` and `use_ref` ( -> [`UseState`](https://docs.rs/dioxus/latest/dioxus/prelude/struct.UseState.html) and -> [`UseRef`](https://docs.rs/dioxus/latest/dioxus/prelude/struct.UseRef.html), respectively) are in -> some ways similar to [`Cell`](https://doc.rust-lang.org/std/cell/) and -> [`RefCell`](https://doc.rust-lang.org/std/cell/struct.RefCell.html) – they provide interior -> mutability. However, these Dioxus wrappers also ensure that the component gets re-rendered -> whenever you change the state. - - -## Additional Resources - -- [**dioxus_hooks** ](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/) rustdoc - - Documents all hook types included with dioxus by default Most of these are also covered in - later chapters of this guide. -- [Hooks Package](https://github.com/DioxusLabs/dioxus/tree/master/packages/hooks) diff --git a/docs/guide/src/en/interactivity/images/counter.png b/docs/guide/src/en/interactivity/images/counter.png deleted file mode 100644 index dd89cadef..000000000 Binary files a/docs/guide/src/en/interactivity/images/counter.png and /dev/null differ diff --git a/docs/guide/src/en/interactivity/images/counter_two_state.png b/docs/guide/src/en/interactivity/images/counter_two_state.png deleted file mode 100644 index 4f77942a2..000000000 Binary files a/docs/guide/src/en/interactivity/images/counter_two_state.png and /dev/null differ diff --git a/docs/guide/src/en/interactivity/images/meme_editor_screenshot.png b/docs/guide/src/en/interactivity/images/meme_editor_screenshot.png deleted file mode 100644 index 3f7c807fb..000000000 Binary files a/docs/guide/src/en/interactivity/images/meme_editor_screenshot.png and /dev/null differ diff --git a/docs/guide/src/en/interactivity/index.md b/docs/guide/src/en/interactivity/index.md deleted file mode 100644 index fa24aaa31..000000000 --- a/docs/guide/src/en/interactivity/index.md +++ /dev/null @@ -1,3 +0,0 @@ -# Interactivity - -So far, we've learned how to describe the structure and properties of our user interfaces. However, most interfaces need to be interactive in order to be useful. In this chapter, we describe how to make a Dioxus app that responds to the user. diff --git a/docs/guide/src/en/interactivity/memoization.md b/docs/guide/src/en/interactivity/memoization.md deleted file mode 100644 index 32ec37ce5..000000000 --- a/docs/guide/src/en/interactivity/memoization.md +++ /dev/null @@ -1,19 +0,0 @@ -# Memoization - -[`use_memo`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_memo.html) let's you memorize values and thus save computation time. This is useful for expensive calculations. - -```rust, no_run -#[inline_props] -fn Calculator(cx: Scope, number: usize) -> Element { - let bigger_number = use_memo(cx, (number,), |(number,)| { - // This will only be calculated when `number` has changed. - number * 100 - }); - render!( - p { "{bigger_number}" } - ) -} -fn app(cx: Scope) -> Element { - render!(Calculator { number: 0 }) -} -``` diff --git a/docs/guide/src/en/interactivity/router.md b/docs/guide/src/en/interactivity/router.md deleted file mode 100644 index b4f20eb78..000000000 --- a/docs/guide/src/en/interactivity/router.md +++ /dev/null @@ -1,83 +0,0 @@ -# Router - -In many of your apps, you'll want to have different "scenes". For a webpage, these scenes might be the different webpages with their own content. For a desktop app, these scenes might be different views in your app. - -To unify these platforms, Dioxus provides a first-party solution for scene management called Dioxus Router. - -## What is it? - -For an app like the Dioxus landing page (https://dioxuslabs.com), we want to have several different scenes: - -- Homepage -- Blog - -Each of these scenes is independent – we don't want to render both the homepage and blog at the same time. - -The Dioxus router makes it easy to create these scenes. To make sure we're using the router, add the `dioxus-router` package to your `Cargo.toml`. - -```shell -cargo add dioxus-router -``` - -## Using the router - -Unlike other routers in the Rust ecosystem, our router is built declaratively. This makes it possible to compose our app layout simply by arranging components. - -```rust, no_run -rsx!{ - // All of our routes will be rendered inside this Router component - Router:: { - // if the current location is "/home", render the Home component - Route { to: "/home", Home {} } - // if the current location is "/blog", render the Blog component - Route { to: "/blog", Blog {} } - } -} -``` - -Whenever we visit this app, we will get either the Home component or the Blog component rendered depending on which route we enter at. If neither of these routes match the current location, then nothing will render. - -We can fix this one of two ways: - -- A fallback 404 page - -```rust, no_run -rsx!{ - Router:: { - Route { to: "/home", Home {} } - Route { to: "/blog", Blog {} } - // if the current location doesn't match any of the above routes, render the NotFound component - Route { to: "", NotFound {} } - } -} -``` - -- Redirect 404 to home - -```rust, no_run -rsx!{ - Router:: { - Route { to: "/home", Home {} } - Route { to: "/blog", Blog {} } - // if the current location doesn't match any of the above routes, redirect to "/home" - Redirect { from: "", to: "/home" } - } -} -``` - -## Links - -For our app to navigate these routes, we can provide clickable elements called Links. These simply wrap `` elements that, when clicked, navigate the app to the given location. - -```rust, no_run -rsx!{ - Link { - to: "/home", - "Go home!" - } -} -``` - -## More reading - -This page is just a very brief overview of the router. For more information, check out [the router book](https://dioxuslabs.com/docs/0.3/router/) or some of [the router examples](https://github.com/DioxusLabs/dioxus/blob/master/examples/router.rs). diff --git a/docs/guide/src/en/interactivity/sharing_state.md b/docs/guide/src/en/interactivity/sharing_state.md deleted file mode 100644 index d71fbdec0..000000000 --- a/docs/guide/src/en/interactivity/sharing_state.md +++ /dev/null @@ -1,71 +0,0 @@ -# Sharing State - -Often, multiple components need to access the same state. Depending on your needs, there are several ways to implement this. - -## Lifting State - -One approach to share state between components is to "lift" it up to the nearest common ancestor. This means putting the `use_state` hook in a parent component, and passing the needed values down as props. - -Suppose we want to build a meme editor. We want to have an input to edit the meme caption, but also a preview of the meme with the caption. Logically, the meme and the input are 2 separate components, but they need access to the same state (the current caption). - -> Of course, in this simple example, we could write everything in one component – but it is better to split everything out in smaller components to make the code more reusable, maintainable, and performant (this is even more important for larger, complex apps). - -We start with a `Meme` component, responsible for rendering a meme with a given caption: - -```rust, no_run -{{#include ../../../examples/meme_editor.rs:meme_component}} -``` - -> Note that the `Meme` component is unaware where the caption is coming from – it could be stored in `use_state`, `use_ref`, or a constant. This ensures that it is very reusable – the same component can be used for a meme gallery without any changes! - -We also create a caption editor, completely decoupled from the meme. The caption editor must not store the caption itself – otherwise, how will we provide it to the `Meme` component? Instead, it should accept the current caption as a prop, as well as an event handler to delegate input events to: - -```rust, no_run -{{#include ../../../examples/meme_editor.rs:caption_editor}} -``` - -Finally, a third component will render the other two as children. It will be responsible for keeping the state and passing down the relevant props. - -```rust, no_run -{{#include ../../../examples/meme_editor.rs:meme_editor}} -``` - -![Meme Editor Screenshot: An old plastic skeleton sitting on a park bench. Caption: "me waiting for a language feature"](./images/meme_editor_screenshot.png) - -## Using Shared State - -Sometimes, some state needs to be shared between multiple components far down the tree, and passing it down through props is very inconvenient. - -Suppose now that we want to implement a dark mode toggle for our app. To achieve this, we will make every component select styling depending on whether dark mode is enabled or not. - -> Note: we're choosing this approach for the sake of an example. There are better ways to implement dark mode (e.g. using CSS variables). Let's pretend CSS variables don't exist – welcome to 2013! - -Now, we could write another `use_state` in the top component, and pass `is_dark_mode` down to every component through props. But think about what will happen as the app grows in complexity – almost every component that renders any CSS is going to need to know if dark mode is enabled or not – so they'll all need the same dark mode prop. And every parent component will need to pass it down to them. Imagine how messy and verbose that would get, especially if we had components several levels deep! - -Dioxus offers a better solution than this "prop drilling" – providing context. The [`use_shared_state_provider`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_shared_state_provider.html) hook is similar to `use_ref`, but it makes it available through [`use_shared_state`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_shared_state.html) for all children components. - -First, we have to create a struct for our dark mode configuration: - -```rust, no_run -{{#include ../../../examples/meme_editor_dark_mode.rs:DarkMode_struct}} -``` - -Now, in a top-level component (like `App`), we can provide the `DarkMode` context to all children components: - -```rust, no_run -{{#include ../../../examples/meme_editor_dark_mode.rs:context_provider}} -``` - -As a result, any child component of `App` (direct or not), can access the `DarkMode` context. - -```rust, no_run -{{#include ../../../examples/meme_editor_dark_mode.rs:use_context}} -``` - -> `use_shared_state` returns `Option>` here. If the context has been provided, the value is `Some(UseSharedState)`, which you can call `.read` or `.write` on, similarly to `UseRef`. Otherwise, the value is `None`. - -For example, here's how we would implement the dark mode toggle, which both reads the context (to determine what color it should render) and writes to it (to toggle dark mode): - -```rust, no_run -{{#include ../../../examples/meme_editor_dark_mode.rs:toggle}} -``` diff --git a/docs/guide/src/en/interactivity/user_input.md b/docs/guide/src/en/interactivity/user_input.md deleted file mode 100644 index 6470588e5..000000000 --- a/docs/guide/src/en/interactivity/user_input.md +++ /dev/null @@ -1,33 +0,0 @@ -# User Input - -Interfaces often need to provide a way to input data: e.g. text, numbers, checkboxes, etc. In Dioxus, there are two ways you can work with user input. - -## Controlled Inputs - -With controlled inputs, you are directly in charge of the state of the input. This gives you a lot of flexibility, and makes it easy to keep things in sync. For example, this is how you would create a controlled text input: - -```rust, no_run -{{#include ../../../examples/input_controlled.rs:component}} -``` - -Notice the flexibility – you can: - -- Also display the same contents in another element, and they will be in sync -- Transform the input every time it is modified (e.g. to make sure it is upper case) -- Validate the input every time it changes -- Have custom logic happening when the input changes (e.g. network request for autocompletion) -- Programmatically change the value (e.g. a "randomize" button that fills the input with nonsense) - -## Uncontrolled Inputs - -As an alternative to controlled inputs, you can simply let the platform keep track of the input values. If we don't tell a HTML input what content it should have, it will be editable anyway (this is built into the browser). This approach can be more performant, but less flexible. For example, it's harder to keep the input in sync with another element. - -Since you don't necessarily have the current value of the uncontrolled input in state, you can access it either by listening to `oninput` events (similarly to controlled components), or, if the input is part of a form, you can access the form data in the form events (e.g. `oninput` or `onsubmit`): - -```rust, no_run -{{#include ../../../examples/input_uncontrolled.rs:component}} -``` - -``` -Submitted! UiEvent { data: FormData { value: "", values: {"age": "very old", "date": "1966", "name": "Fred"} } } -``` diff --git a/docs/guide/src/en/lib.rs b/docs/guide/src/en/lib.rs deleted file mode 100644 index 97cda56a8..000000000 --- a/docs/guide/src/en/lib.rs +++ /dev/null @@ -1 +0,0 @@ -// empty (we only need this crate for the examples) diff --git a/docs/guide/src/en/publishing/desktop.md b/docs/guide/src/en/publishing/desktop.md deleted file mode 100644 index f30b0b26d..000000000 --- a/docs/guide/src/en/publishing/desktop.md +++ /dev/null @@ -1,65 +0,0 @@ -# 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//`. - -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. - diff --git a/docs/guide/src/en/publishing/index.md b/docs/guide/src/en/publishing/index.md deleted file mode 100644 index 96670f1c8..000000000 --- a/docs/guide/src/en/publishing/index.md +++ /dev/null @@ -1 +0,0 @@ -# Publishing diff --git a/docs/guide/src/en/publishing/web.md b/docs/guide/src/en/publishing/web.md deleted file mode 100644 index 9c285a104..000000000 --- a/docs/guide/src/en/publishing/web.md +++ /dev/null @@ -1,8 +0,0 @@ -## Publishing with Github Pages -To build our app and publish it to Github: - -- Make sure GitHub Pages is set up for your repo -- Build your app with `trunk build --release` (include `--public-url ` 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 diff --git a/docs/guide/src/pt-br/SUMMARY.md b/docs/guide/src/pt-br/SUMMARY.md deleted file mode 100644 index 45cc4912f..000000000 --- a/docs/guide/src/pt-br/SUMMARY.md +++ /dev/null @@ -1,43 +0,0 @@ -# Sumário - -[Introdução](index.md) - -- [Introdução Rápida as Plataformas](getting_started/index.md) - - [Desktop](getting_started/desktop.md) - - [Web](getting_started/web.md) - - [Hot Reload](getting_started/hot_reload.md) - - [Renderização por Servidor](getting_started/ssr.md) - - [Interface do Terminal](getting_started/tui.md) - - [Móvel](getting_started/mobile.md) -- [Descrevendo a Interface do Usuário](describing_ui/index.md) - - [Atributos Especiais](describing_ui/special_attributes.md) - - [Componentes](describing_ui/components.md) - - [Props](describing_ui/component_props.md) - - [Componente Filho](describing_ui/component_children.md) -- [Interatividade](interactivity/index.md) - - [Manipuladores de Eventos](interactivity/event_handlers.md) - - [Hooks & Estado de Componentes](interactivity/hooks.md) - - [Entradas do Usuário](interactivity/user_input.md) - - [Estado Compartilhado](interactivity/sharing_state.md) - - [Hooks Personalizados](interactivity/custom_hooks.md) - - [Renderização Dinâmica](interactivity/dynamic_rendering.md) - - [Roteamento](interactivity/roteador.md) -- [Assincronia](async/index.md) - - [UseFuture](async/use_future.md) - - [UseCoroutine](async/use_coroutine.md) - - [Gerando Futures](async/spawn.md) -- [Práticas Recomendadas](best_practices/index.md) - - [Tratamento de erros](best_practices/error_handling.md) - - [Antipadrões](best_practices/antipatterns.md) -- [Publicação](publishing/index.md) - - [Desktop](publishing/desktop.md) - - [Web](publishing/web.md) - ---- - -- [Renderizador Personalizado](custom_renderer/index.md) - ---- - -[Roteiro](roadmap.md) -[Contribuindo](contributing.md) diff --git a/docs/guide/src/pt-br/async/index.md b/docs/guide/src/pt-br/async/index.md deleted file mode 100644 index ea3cae827..000000000 --- a/docs/guide/src/pt-br/async/index.md +++ /dev/null @@ -1,9 +0,0 @@ -# Trabalhando em Assincronia - -Muitas vezes, os aplicativos precisam interagir com sistemas de arquivos, interfaces de rede, hardware ou temporizadores. Este capítulo fornece uma visão geral do uso de código assíncrono no Dioxus. - -## O Tempo de Execução (runtime) - -Por padrão, o Dioxus-Desktop vem com o runtime `Tokio` e configura tudo automaticamente para você. No momento, isso não é configurável, embora seja fácil escrever uma integração para o desktop Dioxus que use um tempo de execução assíncrono diferente. - -Dioxus atualmente não é `thread-safe`, então qualquer código assíncrono que você escreve _não_ precisa ser `Send/Sync`. Isso significa que você pode usar estruturas não `thread-safe` como `Cell`, `Rc` e `RefCell`. diff --git a/docs/guide/src/pt-br/async/spawn.md b/docs/guide/src/pt-br/async/spawn.md deleted file mode 100644 index 3c00934cf..000000000 --- a/docs/guide/src/pt-br/async/spawn.md +++ /dev/null @@ -1,29 +0,0 @@ -# Gerando Futures - -Os **"hooks"** `use_future` e `use_coroutine` são úteis se você quiser gerar incondicionalmente o `Future`. Às vezes, porém, você desejará apenas gerar um `Future` em resposta a um evento, como um clique do mouse. Por exemplo, suponha que você precise enviar uma solicitação quando o usuário clicar em um botão "log in". Para isso, você pode usar `cx.spawn`: - -```rust, no_run -{{#include ../../../examples/spawn.rs:spawn}} -``` - -> Nota: `spawn` sempre gerará um _novo_ `Future`. Você provavelmente não quer chamá-lo em cada renderização. - -O `Future` deve ser `'static` – então quaisquer valores capturados pela tarefa não podem carregar nenhuma referência a `cx`, como um `UseState`. - -No entanto, como você normalmente precisa de uma maneira de atualizar o valor de um gancho, você pode usar `to_owned` para criar um clone do _handle_ do _hook_. Você pode então usar esse clone no encerramento assíncrono. - -Para tornar isso um pouco menos detalhado, o Dioxus exporta a macro `to_owned!` que criará uma ligação como mostrado acima, o que pode ser bastante útil ao lidar com muitos valores. - -```rust, no_run -{{#include ../../../examples/spawn.rs:to_owned_macro}} -``` - -Calling `spawn` will give you a `JoinHandle` which lets you cancel or pause the future. - -## Gerando Tarefas do Tokio - -Às vezes, você pode querer gerar uma tarefa em segundo plano que precise de vários _threads_ ou conversar com o hardware que pode bloquear o código do seu aplicativo. Nesses casos, podemos gerar diretamente uma tarefa Tokio do nosso `Future`. Para Dioxus-Desktop, sua tarefa será gerada no tempo de execução Multi-Tarefado do Tokio: - -```rust, no_run -{{#include ../../../examples/spawn.rs:tokio}} -``` diff --git a/docs/guide/src/pt-br/async/use_coroutine.md b/docs/guide/src/pt-br/async/use_coroutine.md deleted file mode 100644 index cb9eda3a0..000000000 --- a/docs/guide/src/pt-br/async/use_coroutine.md +++ /dev/null @@ -1,181 +0,0 @@ -# Corrotinas - -Outra boa ferramenta para manter em sua caixa de ferramentas assíncrona são as corrotinas. Corrotinas são `Futures` que podem ser interrompidos, iniciados, pausados e retomados manualmente. - -Assim como os `Futures` regulares, o código em uma corrotina Dioxus será executado até o próximo ponto `await` antes do _render_. Esse controle de baixo nível sobre tarefas assíncronas é bastante poderoso, permitindo tarefas em _loop_ infinito, como pesquisa de WebSocket, temporizadores em segundo plano e outras ações periódicas. - -## `use_coroutine` - -A configuração básica para corrotinas é o _hook_ `use_coroutine`. A maioria das corrotinas que escrevemos serão _loops_ de pesquisa usando `async`/`await`. - -```rust, no_run -fn app(cx: Scope) -> Element { - let ws: &UseCoroutine<()> = use_coroutine(cx, |rx| async move { - // Connect to some sort of service - let mut conn = connect_to_ws_server().await; - - // Wait for data on the service - while let Some(msg) = conn.next().await { - // handle messages - } - }); -} -``` - -Para muitos serviços, um _loop_ assíncrono simples lidará com a maioria dos casos de uso. - -No entanto, se quisermos desabilitar temporariamente a corrotina, podemos "pausá-la" usando o método `pause` e "retomá-la" usando o método `resume`: - -```rust, no_run -let sync: &UseCoroutine<()> = use_coroutine(cx, |rx| async move { - // code for syncing -}); - -if sync.is_running() { - cx.render(rsx!{ - button { - onclick: move |_| sync.pause(), - "Disable syncing" - } - }) -} else { - cx.render(rsx!{ - button { - onclick: move |_| sync.resume(), - "Enable syncing" - } - }) -} -``` - -Esse padrão é onde as corrotinas são extremamente úteis – em vez de escrever toda a lógica complicada para pausar nossas tarefas assíncronas como faríamos com `Promises` de JavaScript, o modelo do Rust nos permite simplesmente não pesquisar nosso `Future`. - -## Enviando valores - -Você deve ter notado que o encerramento `use_coroutine` recebe um argumento chamado `rx`. O que é aquilo? Bem, um padrão comum em aplicativos complexos é lidar com vários códigos assíncronos de uma só vez. Com bibliotecas como o Redux Toolkit, gerenciar várias promessas ao mesmo tempo pode ser um desafio e uma fonte comum de _bugs_. - -Usando corrotinas, temos a oportunidade de centralizar nossa lógica assíncrona. O parâmetro `rx` é um canal ilimitado para código externo à corrotina para enviar dados _para_ a corrotina. Em vez de fazer um _loop_ em um serviço externo, podemos fazer um _loop_ no próprio canal, processando mensagens de dentro de nosso aplicativo sem precisar gerar um novo `Future`. Para enviar dados para a corrotina, chamaríamos "send" no _handle_. - -```rust, no_run -enum ProfileUpdate { - SetUsername(String), - SetAge(i32) -} - -let profile = use_coroutine(cx, |mut rx: UnboundedReciver| async move { - let mut server = connect_to_server().await; - - while let Ok(msg) = rx.next().await { - match msg { - ProfileUpdate::SetUsername(name) => server.update_username(name).await, - ProfileUpdate::SetAge(age) => server.update_age(age).await, - } - } -}); - - -cx.render(rsx!{ - button { - onclick: move |_| profile.send(ProfileUpdate::SetUsername("Bob".to_string())), - "Update username" - } -}) -``` - -Para aplicativos suficientemente complexos, poderíamos criar vários "serviços" úteis diferentes que fazem um _loop_ nos canais para atualizar o aplicativo. - -```rust, no_run -let profile = use_coroutine(cx, profile_service); -let editor = use_coroutine(cx, editor_service); -let sync = use_coroutine(cx, sync_service); - -async fn profile_service(rx: UnboundedReceiver) { - // do stuff -} - -async fn sync_service(rx: UnboundedReceiver) { - // do stuff -} - -async fn editor_service(rx: UnboundedReceiver) { - // do stuff -} -``` - -Podemos combinar corrotinas com `Fermi` para emular o sistema `Thunk` do **Redux Toolkit** com muito menos dor de cabeça. Isso nos permite armazenar todo o estado do nosso aplicativo _dentro_ de uma tarefa e, em seguida, simplesmente atualizar os valores de "visualização" armazenados em `Atoms`. Não pode ser subestimado o quão poderosa é essa técnica: temos todas as vantagens das tarefas nativas do Rust com as otimizações e ergonomia do estado global. Isso significa que seu estado _real_ não precisa estar vinculado a um sistema como `Fermi` ou `Redux` – os únicos `Atoms` que precisam existir são aqueles que são usados para controlar a interface. - -```rust, no_run -static USERNAME: Atom = Atom(|_| "default".to_string()); - -fn app(cx: Scope) -> Element { - let atoms = use_atom_root(cx); - - use_coroutine(cx, |rx| sync_service(rx, atoms.clone())); - - cx.render(rsx!{ - Banner {} - }) -} - -fn Banner(cx: Scope) -> Element { - let username = use_read(cx, &USERNAME); - - cx.render(rsx!{ - h1 { "Welcome back, {username}" } - }) -} -``` - -Agora, em nosso serviço de sincronização, podemos estruturar nosso estado como quisermos. Só precisamos atualizar os valores da _view_ quando estiver pronto. - -```rust, no_run -enum SyncAction { - SetUsername(String), -} - -async fn sync_service(mut rx: UnboundedReceiver, atoms: AtomRoot) { - let username = atoms.write(&USERNAME); - let errors = atoms.write(&ERRORS); - - while let Ok(msg) = rx.next().await { - match msg { - SyncAction::SetUsername(name) => { - if set_name_on_server(&name).await.is_ok() { - username.set(name); - } else { - errors.make_mut().push("SetUsernameFailed"); - } - } - } - } -} -``` - -## Valores de Rendimento - -Para obter valores de uma corrotina, basta usar um identificador `UseState` e definir o valor sempre que sua corrotina concluir seu trabalho. - -```rust, no_run -let sync_status = use_state(cx, || Status::Launching); -let sync_task = use_coroutine(cx, |rx: UnboundedReceiver| { - to_owned![sync_status]; - async move { - loop { - delay_ms(1000).await; - sync_status.set(Status::Working); - } - } -}) -``` - -## Injeção Automática na API de Contexto - -Os identificadores de corrotina são injetados automaticamente por meio da API de contexto. `use_coroutine_handle` com o tipo de mensagem como genérico pode ser usado para buscar um _handle_. - -```rust, no_run -fn Child(cx: Scope) -> Element { - let sync_task = use_coroutine_handle::(cx); - - sync_task.send(SyncAction::SetUsername); -} -``` diff --git a/docs/guide/src/pt-br/async/use_future.md b/docs/guide/src/pt-br/async/use_future.md deleted file mode 100644 index 1e7030ddf..000000000 --- a/docs/guide/src/pt-br/async/use_future.md +++ /dev/null @@ -1,31 +0,0 @@ -# `UseFuture` - -[`use_future`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_future.html) permite executar um encerramento assíncrono e fornece seu resultado. - -Por exemplo, podemos fazer uma solicitação de API dentro de `use_future`: - -```rust, no_run -{{#include ../../../examples/use_future.rs:use_future}} -``` - -O código dentro de `use_future` será enviado ao agendador do Dioxus assim que o componente for renderizado. - -Podemos usar `.value()` para obter o resultado do `Future`. Na primeira execução, como não há dados prontos quando o componente é carregado, seu valor será `None`. No entanto, uma vez finalizado o `Future`, o componente será renderizado novamente e o valor agora será `Some(...)`, contendo o valor de retorno do encerramento. - -Podemos então renderizar esse resultado: - -```rust, no_run -{{#include ../../../examples/use_future.rs:render}} -``` - -## Reiniciando o `Future` - -O identificador `UseFuture` fornece um método `restart`. Ele pode ser usado para executar o `Future` novamente, produzindo um novo valor. - -## Dependências - -Muitas vezes, você precisará executar o `Future` novamente toda vez que algum valor (por exemplo, uma prop) mudar. Ao invés de `.restart` manualmente, você pode fornecer uma tupla de "dependências" para o gancho. Ele executará automaticamente o `Future` quando qualquer uma dessas dependências for alterada. Exemplo: - -```rust, no_run -{{#include ../../../examples/use_future.rs:dependency}} -``` diff --git a/docs/guide/src/pt-br/best_practices/antipatterns.md b/docs/guide/src/pt-br/best_practices/antipatterns.md deleted file mode 100644 index fa57ba125..000000000 --- a/docs/guide/src/pt-br/best_practices/antipatterns.md +++ /dev/null @@ -1,33 +0,0 @@ -# Antipadrões - -Este exemplo mostra o que não fazer e fornece uma razão pela qual um determinado padrão é considerado um "AntiPattern". A maioria dos antipadrões são considerados errados por motivos de desempenho ou por prejudicar a reutilização do código. - -## Fragmentos Aninhados Desnecessariamente - -Os fragmentos não montam um elemento físico no DOM imediatamente, então o Dioxus deve recorrer a seus filhos para encontrar um nó DOM físico. Este processo é chamado de "normalização". Isso significa que fragmentos profundamente aninhados fazem o Dioxus realizar um trabalho desnecessário. Prefira um ou dois níveis de fragmentos/componentes aninhados até apresentar um elemento DOM verdadeiro. - -Apenas os nós Componente e Fragmento são suscetíveis a esse problema. O Dioxus atenua isso com componentes fornecendo uma API para registrar o estado compartilhado sem o padrão _Context Provider_. - -```rust, no_run -{{#include ../../../examples/anti_patterns.rs:nested_fragments}} -``` - -## Chaves do Iterador Incorretas - -Conforme descrito no capítulo de renderização condicional, os itens da lista devem ter _keys_ exclusivas associadas aos mesmos itens nas renderizações. Isso ajuda o Dioxus a associar o estado aos componentes contidos e garante um bom desempenho de diferenciação. Não omita as _keys_, a menos que você saiba que a lista é estática e nunca será alterada. - -```rust, no_run -{{#include ../../../examples/anti_patterns.rs:iter_keys}} -``` - -## Evite Mutabilidade Interior em `Props` - -Embora seja tecnicamente aceitável ter um `Mutex` ou um `RwLock` nos _props_, eles serão difíceis de usar. - -Suponha que você tenha um _struct_ `User` contendo o campo `username: String`. Se você passar uma _prop_ `Mutex` para um componente `UserComponent`, esse componente pode querer passar o nome de usuário como uma _prop_ `&str` para um componente filho. No entanto, ele não pode passar esse campo emprestado, pois ele só viveria enquanto o bloqueio do `Mutex`, que pertence à função `UserComponent`. Portanto, o componente será forçado a clonar o campo `username`. - -## Evite Atualizar o Estado Durante a Renderização - -Toda vez que você atualiza o estado, o Dioxus precisa renderizar novamente o componente – isso é ineficiente! Considere refatorar seu código para evitar isso. - -Além disso, se você atualizar incondicionalmente o estado durante a renderização, ele será renderizado novamente em um _loop_ infinito. diff --git a/docs/guide/src/pt-br/best_practices/error_handling.md b/docs/guide/src/pt-br/best_practices/error_handling.md deleted file mode 100644 index 2fec8d88d..000000000 --- a/docs/guide/src/pt-br/best_practices/error_handling.md +++ /dev/null @@ -1,153 +0,0 @@ -# Manipulação de Erros - -Um ponto forte do Rust para desenvolvimento Web é a confiabilidade de sempre saber onde os erros podem ocorrer e ser forçado a lidar com eles - -No entanto, não falamos sobre tratamento de erros neste guia! Neste capítulo, abordaremos algumas estratégias para lidar com erros para garantir que seu aplicativo nunca falhe. - -## O mais simples – retornando None - -Observadores astutos podem ter notado que `Element` é na verdade um alias de tipo para `Option`. Você não precisa saber o que é um `VNode`, mas é importante reconhecer que não poderíamos retornar nada: - -```rust, no_run -fn App(cx: Scope) -> Element { - None -} -``` - -Isso nos permite adicionar um pouco de açúcar sintático para operações que achamos que _não devem_ falhar, mas ainda não estamos confiantes o suficiente para "desempacotar". - -> A natureza de `Option` pode mudar no futuro à medida que a característica `try` for atualizada. - -```rust, no_run -fn App(cx: Scope) -> Element { - // immediately return "None" - let name = cx.use_hook(|_| Some("hi"))?; -} -``` - -## Retorno Antecipado do Resultado - -Como o Rust não pode aceitar opções e resultados com a infraestrutura _try_ existente, você precisará manipular os resultados manualmente. Isso pode ser feito convertendo-os em `Option` ou manipulando-os explicitamente. - -```rust, no_run -fn App(cx: Scope) -> Element { - // Convert Result to Option - let name = cx.use_hook(|_| "1.234").parse().ok()?; - - - // Early return - let count = cx.use_hook(|_| "1.234"); - let val = match count.parse() { - Ok(val) => val - Err(err) => return cx.render(rsx!{ "Parsing failed" }) - }; -} -``` - -Observe que enquanto os ganchos no Dioxus não gostam de ser chamados em condicionais ou loops, eles _estão_ bem com retornos antecipados. Retornar um estado de erro antecipadamente é uma maneira completamente válida de lidar com erros. - -## Resultados usando `match` - -A próxima "melhor" maneira de lidar com erros no Dioxus é combinar (`match`) o erro localmente. Essa é a maneira mais robusta de lidar com erros, embora não seja dimensionada para arquiteturas além de um único componente. - -Para fazer isso, simplesmente temos um estado de erro embutido em nosso componente: - -```rust, no_run -let err = use_state(cx, || None); -``` - -Sempre que realizarmos uma ação que gere um erro, definiremos esse estado de erro. Podemos então combinar o erro de várias maneiras (retorno antecipado, elemento de retorno etc.). - -```rust, no_run -fn Commandline(cx: Scope) -> Element { - let error = use_state(cx, || None); - - cx.render(match *error { - Some(error) => rsx!( - h1 { "An error occured" } - ) - None => rsx!( - input { - oninput: move |_| error.set(Some("bad thing happened!")), - } - ) - }) -} -``` - -## Passando Estados de Erro Através de Componentes - -Se você estiver lidando com alguns componentes com um mínimo de aninhamento, basta passar o identificador de erro para componentes filhos. - -```rust, no_run -fn Commandline(cx: Scope) -> Element { - let error = use_state(cx, || None); - - if let Some(error) = **error { - return cx.render(rsx!{ "An error occured" }); - } - - cx.render(rsx!{ - Child { error: error.clone() } - Child { error: error.clone() } - Child { error: error.clone() } - Child { error: error.clone() } - }) -} -``` - -Assim como antes, nossos componentes filhos podem definir manualmente o erro durante suas próprias ações. A vantagem desse padrão é que podemos isolar facilmente os estados de erro para alguns componentes por vez, tornando nosso aplicativo mais previsível e robusto. - -## Tornando Global - -Uma estratégia para lidar com erros em cascata em aplicativos maiores é sinalizar um erro usando o estado global. Esse padrão específico envolve a criação de um contexto de "erro" e, em seguida, defini-lo sempre que relevante. Este método em particular não é tão "sofisticado" quanto o controle de erros do React, mas é mais adequado para Rust. - -Para começar, considere usar um _hook_ embutido como `use_context` e `use_context_provider` ou `Fermi`. Claro, é muito fácil criar seu próprio _hook_ também. - -No "topo" de nossa arquitetura, queremos declarar explicitamente um valor que pode ser um erro. - -```rust, no_run -enum InputError { - None, - TooLong, - TooShort, -} - -static INPUT_ERROR: Atom = Atom(|_| InputError::None); -``` - -Então, em nosso componente de nível superior, queremos tratar explicitamente o possível estado de erro para esta parte da árvore. - -```rust, no_run -fn TopLevel(cx: Scope) -> Element { - let error = use_read(cx, &INPUT_ERROR); - - match error { - TooLong => return cx.render(rsx!{ "FAILED: Too long!" }), - TooShort => return cx.render(rsx!{ "FAILED: Too Short!" }), - _ => {} - } -} -``` - -Agora, sempre que um componente _downstream_ tiver um erro em suas ações, ele pode simplesmente definir seu próprio estado de erro: - -```rust, no_run -fn Commandline(cx: Scope) -> Element { - let set_error = use_set(cx, &INPUT_ERROR); - - cx.render(rsx!{ - input { - oninput: move |evt| { - if evt.value.len() > 20 { - set_error(InputError::TooLong); - } - } - } - }) -} -``` - -Essa abordagem de tratamento de erros é melhor em aplicativos que têm estados de erro "bem definidos". Considere usar uma `crate` como `thiserror` ou `anyhow` para simplificar a geração dos tipos de erro. - -Esse padrão é amplamente popular em muitos contextos e é particularmente útil sempre que seu código gera um erro irrecuperável. Você pode capturar esses estados de erro "globais" resultar em `panic!` ou estragar o estado. diff --git a/docs/guide/src/pt-br/best_practices/index.md b/docs/guide/src/pt-br/best_practices/index.md deleted file mode 100644 index ee8506241..000000000 --- a/docs/guide/src/pt-br/best_practices/index.md +++ /dev/null @@ -1,14 +0,0 @@ -# Práticas Recomendadas - -## Componentes Reutilizáveis - -Tanto quanto possível, divida seu código em pequenos componentes e _hooks_ reutilizáveis, em vez de implementar grandes partes da interface do usuário em um único componente. Isso ajudará você a manter o código sustentável – é muito mais fácil, por exemplo, adicionar, remover ou reordenar partes da interface do usuário se ela estiver organizada em componentes. - -Organize seus componentes em módulos para manter a base de código fácil de navegar! - -## Minimize as Dependências do Estado - -Embora seja possível compartilhar o estado entre os componentes, isso só deve ser feito quando necessário. Qualquer componente associado a um objeto de estado específico precisa ser renderizado novamente quando esse estado for alterado. Por esta razão: - -- Mantenha o estado local para um componente, se possível -- Ao compartilhar o estado por meio de adereços, passe apenas os dados específicos necessários diff --git a/docs/guide/src/pt-br/contributing.md b/docs/guide/src/pt-br/contributing.md deleted file mode 100644 index 404a174db..000000000 --- a/docs/guide/src/pt-br/contributing.md +++ /dev/null @@ -1,20 +0,0 @@ -# Contribuindo - -O desenvolvimento acontece no [repositório do Dioxus no GitHub](https://github.com/DioxusLabs/dioxus). Se você encontrou um bug ou tem uma ideia para um recurso, envie um _issue_ (verifique se alguém ainda não o fez (https://github.com/DioxusLabs/dioxus/issues)). - -[Discussões do GitHub](https://github.com/DioxusLabs/dioxus/discussions) podem ser usadas como um lugar para pedir ajuda ou falar sobre recursos. Você também pode participar do [nosso canal Discord](https://discord.gg/XgGxMSkvUM) onde algumas discussões de desenvolvimento acontecem. - -## Como melhorar os documentos - -Se você quiser melhorar os documentos, os PRs são bem-vindos! Ambos os documentos do Rust ([source](https://github.com/DioxusLabs/dioxus/tree/master/packages)) e este guia ([source](https://github.com/DioxusLabs/dioxus/tree/master /docs/guide)) pode ser encontrado no repositório do GitHub. - -## Trabalhando no Ecossistema - -Parte do que torna o React ótimo é o rico ecossistema. Gostaríamos do mesmo para Dioxus! Portanto, se você tem uma biblioteca em mente que gostaria de escrever e da qual acha que muitas pessoas se beneficiariam, ela será apreciada. Você pode [navegar no npm.js](https://www.npmjs.com/search?q=keywords:react-component) para se inspirar. - -## Bugs e recursos - -Se você corrigiu [um problema aberto](https://github.com/DioxusLabs/dioxus/issues), sinta-se à vontade para enviar um PR! Você também pode dar uma olhada no [roteiro](./roadmap.md) e trabalhar em algo lá. Considere [entre em contato](https://discord.gg/XgGxMSkvUM) com a equipe primeiro para garantir que todos estejam na mesma página e que você não faça um trabalho inútil! - -Todas as solicitações de PR (incluindo aquelas feitas por um membro da equipe) devem ser aprovadas por pelo menos um outro membro da equipe. -Decisões maiores e mais sutis sobre design, arquitetura, mudanças de última hora, trade-offs, etc. são feitas por consenso da equipe. diff --git a/docs/guide/src/pt-br/custom_renderer/index.md b/docs/guide/src/pt-br/custom_renderer/index.md deleted file mode 100644 index 195f9d6ca..000000000 --- a/docs/guide/src/pt-br/custom_renderer/index.md +++ /dev/null @@ -1,505 +0,0 @@ -# Renderizador Personalizado - -Dioxus é uma estrutura incrivelmente portátil para desenvolvimento de interface do usuário. As lições, conhecimentos, _hooks_ e componentes que você adquire ao longo do tempo sempre podem ser usados ​​para projetos futuros. No entanto, às vezes, esses projetos não podem aproveitar um renderizador compatível ou você precisa implementar seu próprio renderizador melhor. - -Ótimas notícias: o design do renderizador depende inteiramente de você! Nós fornecemos sugestões e inspiração com os renderizadores originais, mas só realmente precisamos processar `DomEdits` e enviar `UserEvents`. - -## Detalhes - -A implementação do renderizador é bastante simples. O renderizador precisa: - -1. Lidar com o fluxo de edições gerado por atualizações no DOM virtual -2. Registrar ouvintes e passar eventos para o sistema de eventos do DOM virtual - -Essencialmente, seu renderizador precisa implementar a `trait` `RealDom` e gerar objetos `EventTrigger` para atualizar o `VirtualDOM`. A partir daí, você terá tudo o que precisa para renderizar o `VirtualDOM` na tela. - -Internamente, o Dioxus lida com o relacionamento da árvore, `diffing`, gerenciamento de memória e o sistema de eventos, deixando o mínimo necessário para que os renderizadores se implementem. - -Como referência, confira o interpretador `javascript` ou o renderizador `tui` como ponto de partida para seu renderizador personalizado. - -## DomEdit - -O tipo "DomEdit" é uma `enum` serializada que representa uma operação atômica que ocorre no `RealDom`. As variantes seguem aproximadamente este conjunto: - -```rust, no_run -enum DomEdit { - PushRoot, - AppendChildren, - ReplaceWith, - InsertAfter, - InsertBefore, - Remove, - CreateTextNode, - CreateElement, - CreateElementNs, - CreatePlaceholder, - NewEventListener, - RemoveEventListener, - SetText, - SetAttribute, - RemoveAttribute, - PopRoot, -} -``` - -O mecanismo de diferenciação Dioxus opera como uma [máquina de pilha] (https://en.wikipedia.org/wiki/Stack_machine) onde o método "push_root" empurra um novo nó DOM "real" para a pilha e "append_child" e "replace_with" " ambos removem nós da pilha. - -### Exemplo - -Para fins de compreensão, vamos considerar este exemplo – uma declaração de interface do usuário muito simples: - -```rust, no_run -rsx!( h1 {"hello world"} ) -``` - -Para começar, o Dioxus deve primeiro navegar até o contêiner dessa tag h1. Para "navegar" aqui, o algoritmo de diferenciação interna gera o `DomEdit` `PushRoot` onde o ID da raiz é o contêiner. - -Quando o renderizador recebe essa instrução, ele empurra o `Node` real para sua própria pilha. A pilha do renderizador real ficará assim: - -```rust, no_run -instructions: [ - PushRoot(Container) -] -stack: [ - ContainerNode, -] -``` - -Em seguida, o Dioxus encontrará o nó `h1`. O algoritmo `diff` decide que este nó precisa ser criado, então o Dioxus irá gerar o DomEdit `CreateElement`. Quando o renderizador receber esta instrução, ele criará um nó desmontado e o enviará para sua própria pilha (_stack_): - -```rust, no_run -instructions: [ - PushRoot(Container), - CreateElement(h1), -] -stack: [ - ContainerNode, - h1, -] -``` - -Em seguida, Dioxus vê o nó de texto e gera o DomEdit `CreateTextNode`: - -```rust, no_run -instructions: [ - PushRoot(Container), - CreateElement(h1), - CreateTextNode("hello world") -] -stack: [ - ContainerNode, - h1, - "hello world" -] -``` - -Lembre-se, o nó de texto não está anexado a nada (ele está desmontado), então o Dioxus precisa gerar um _Edit_ que conecte o nó de texto ao elemento `h1`. Depende da situação, mas neste caso usamos `AppendChildren`. Isso remove o nó de texto da _stack_, deixando o elemento `h1` como o próximo elemento na linha. - -```rust, no_run -instructions: [ - PushRoot(Container), - CreateElement(h1), - CreateTextNode("hello world"), - AppendChildren(1) -] -stack: [ - ContainerNode, - h1 -] -``` - -Chamamos `AppendChildren` novamente, retirando o nó `h1` e anexando-o ao pai: - -```rust, no_run -instructions: [ - PushRoot(Container), - CreateElement(h1), - CreateTextNode("hello world"), - AppendChildren(1), - AppendChildren(1) -] -stack: [ - ContainerNode, -] -``` - -Finalmente, o contêiner é aberto, pois não precisamos mais dele. - -```rust, no_run -instructions: [ - PushRoot(Container), - CreateElement(h1), - CreateTextNode("hello world"), - AppendChildren(1), - AppendChildren(1), - PopRoot -] -stack: [] -``` - -Com o tempo, nossa _stack_ ficou assim: - -```rust, no_run -[] -[Container] -[Container, h1] -[Container, h1, "hello world"] -[Container, h1] -[Container] -[] -``` - -Observe como nossa _stack_ fica vazia depois que a interface do usuário é montada. Convenientemente, essa abordagem separa completamente o `VirtualDOM` e o `RealDOM`. Além disso, essas edições são serializáveis, o que significa que podemos até gerenciar UIs em uma conexão de rede. Esta pequena _stack_ e edições serializadas tornam o Dioxus independente das especificidades da plataforma. - -Dioxus também é muito rápido. Como o Dioxus divide a fase de `diff` e `patch`, ele é capaz de fazer todas as edições no `RealDOM` em um período de tempo muito curto (menos de um único quadro), tornando a renderização muito rápida. Ele também permite que o Dioxus cancele grandes operações de diferenciação se ocorrer um trabalho de prioridade mais alta durante a diferenciação. - -É importante notar que há uma camada de conexão entre o Dioxus e o renderizador. Dioxus salva e carrega elementos (a edição `PushRoot`) com um ID. Dentro do `VirtualDOM`, isso é rastreado apenas como um `u64`. - -Sempre que uma edição `CreateElement` é gerada durante a comparação, o Dioxus incrementa seu contador de nós e atribui a esse novo elemento seu `NodeCount` atual. O `RealDom` é responsável por lembrar este ID e enviar o nó correto quando `PushRoot(ID)` é gerado. Dioxus recupera IDs de elementos quando removidos. Para ficar em sincronia com Dioxus, você pode usar um `Sparce Vec` (`Vec>`) com itens possivelmente desocupados. Você pode usar os ids como índices no `Vec` para elementos e aumentar o `Vec` quando um id não existir. - -Esta pequena demonstração serve para mostrar exatamente como um Renderer precisaria processar um stream de edição para construir UIs. Um conjunto de `DomEdits` serializados para várias demos está disponível para você testar seu renderizador personalizado. - -## Ciclo de Eventos - -Como a maioria das GUIs, o Dioxus conta com um _loop_ de eventos para progredir no `VirtualDOM`. O próprio `VirtualDOM` também pode produzir eventos, por isso é importante que seu renderizador personalizado também possa lidar com eles. - -O código para a implementação do `WebSys` é direto, então vamos adicioná-lo aqui para demonstrar como um `loop` de eventos é simples: - -```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()); - 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 - } -} -``` - -É importante que você decodifique os eventos reais do seu sistema de eventos no sistema de eventos sintético do Dioxus (entenda sintético como abstraído). Isso significa simplesmente combinar seu tipo de evento e criar um tipo Dioxus `UserEvent`. No momento, o sistema `VirtualEvent` é modelado quase inteiramente em torno da especificação HTML, mas estamos interessados em reduzi-lo. - -```rust, no_run -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!() - } -} -``` - -## Elementos brutos personalizados - -Se você precisa ir tão longe a ponto de confiar em elementos personalizados para o seu renderizador – você pode. Isso ainda permite que você use a natureza reativa do Dioxus, sistema de componentes, estado compartilhado e outros recursos, mas acabará gerando nós diferentes. Todos os atributos e ouvintes para o namespace HTML e SVG são transportados por meio de estruturas auxiliares que essencialmente compilam (não representam sobrecarga de tempo de execução). Você pode colocar seus próprios elementos a qualquer hora, sem problemas. No entanto, você deve ter certeza absoluta de que seu renderizador pode lidar com o novo tipo, ou ele irá "bater e queimar". - -Esses elementos personalizados são definidos como estruturas de unidade com implementações de características. - -Por exemplo, o elemento `div` é (aproximadamente!) definido assim: - -```rust, no_run -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 -} -``` - -Você provavelmente notou que muitos elementos nas macros `rsx!` suportam documentação em foco. A abordagem que adotamos para elementos personalizados significa que a estrutura da unidade é criada imediatamente onde o elemento é usado na macro. Quando a macro é expandida, os comentários doc ainda se aplicam à estrutura da unidade, dando toneladas de feedback no editor, mesmo dentro de uma `macro proc`. - -# Núcleo Nativo - -Se você estiver criando um renderizador em Rust, o núcleo nativo fornece alguns utilitários para implementar um renderizador. Ele fornece uma abstração sobre `DomEdits` e manipula o layout para você. - -## RealDom - -O `RealDom` é uma abstração de nível superior sobre a atualização do Dom. Ele atualiza com `DomEdits` e fornece uma maneira de atualizar incrementalmente o estado dos nós com base em quais atributos mudam. - -### Exemplo - -Vamos construir um renderizador de exemplo com bordas, tamanho e cor do texto. -Antes de começarmos, vamos dar uma olhada em um elemento de exemplo que podemos renderizar: - -```rust, no_run -cx.render(rsx!{ - div{ - color: "red", - p{ - border: "1px solid black", - "hello world" - } - } -}) -``` - -Nesta árvore a cor depende da cor do pai. O tamanho depende do tamanho das _children_, do texto atual e do tamanho do texto. A borda depende apenas do nó atual. - -No diagrama a seguir, as setas representam o fluxo de dados: - -[![](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" - -Para ajudar na construção de um DOM, o núcleo nativo fornece quatro `traits`: `State`, `ChildDepState`, `ParentDepState` e `NodeDepState` e uma estrutura `RealDom`. O `ChildDepState`, `ParentDepState` e `NodeDepState` fornecem uma maneira de descrever como algumas informações em um nó se relacionam com as de seus parentes. Ao fornecer como construir um único nó a partir de suas relações, o native-core derivará uma maneira de atualizar o estado de todos os nós para você com `#[derive(State)]`. Depois de ter um estado, você pode fornecê-lo como genérico ao `RealDom`. `RealDom` fornece todos os métodos para interagir e atualizar seu novo dom. - -```rust, no_run -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, - 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, -} -``` - -Agora que temos nosso estado, podemos colocá-lo em uso em nosso DOM. Você pode atualizar o DOM com `update_state` para atualizar a estrutura do dom (adicionando, removendo e alterando as propriedades dos nós) e então `apply_mutations` para atualizar o `ToyState` para cada um dos nós que foram alterados. - -```rust, no_run -fn main(){ - fn app(cx: Scope) -> Element { - cx.render(rsx!{ - div{ - color: "red", - "hello world" - } - }) - } - let vdom = VirtualDom::new(app); - let rdom: RealDom = 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 - -Para a maioria das plataformas, o _layout_ dos `Elementos` permanecerá o mesmo. O módulo `layout_attributes` fornece uma maneira de aplicar atributos html a um estilo de _layout_ estendido. - -## Conclusão - -Pronto! Você deve ter quase todo o conhecimento necessário sobre como implementar seu próprio renderizador. Estamos super interessados em ver os aplicativos Dioxus trazidos para renderizadores de desktop personalizados, renderizador para dispositivos móveis, interface do usuário de videogame e até realidade aumentada! Se você estiver interessado em contribuir para qualquer um desses projetos, não tenha medo de entrar em contato ou se juntar à comunidade. diff --git a/docs/guide/src/pt-br/describing_ui/component_children.md b/docs/guide/src/pt-br/describing_ui/component_children.md deleted file mode 100644 index 9663dca19..000000000 --- a/docs/guide/src/pt-br/describing_ui/component_children.md +++ /dev/null @@ -1,31 +0,0 @@ -# Componente Filhos - -Em alguns casos, você pode desejar criar um componente que atue como um contêiner para algum outro conteúdo, sem que o componente precise saber qual é esse conteúdo. Para conseguir isso, crie uma _prop_ do tipo `Element`: - -```rust, no_run -{{#include ../../../examples/component_element_props.rs:Clickable}} -``` - -Então, ao renderizar o componente, você pode passar a saída de `cx.render(rsx!(...))`: - -```rust, no_run -{{#include ../../../examples/component_element_props.rs:Clickable_usage}} -``` - -> Nota: Como `Element<'a>` é uma _prop_ emprestado, não haverá memoização. - -> Atenção: Embora possa compilar, não inclua o mesmo `Element` mais de uma vez no RSX. O comportamento resultante não é especificado. - -## O Campo `children` - -Em vez de passar o `RSX` através de uma _prop_ regular, você pode querer aceitar filhos da mesma forma que os elementos podem ter filhos. O prop "mágico" `children` permite que você consiga isso: - -```rust, no_run -{{#include ../../../examples/component_children.rs:Clickable}} -``` - -Isso torna o uso do componente muito mais simples: basta colocar o `RSX` dentro dos colchetes `{}` – e não há necessidade de uma chamada `render` ou outra macro! - -```rust, no_run -{{#include ../../../examples/component_children.rs:Clickable_usage}} -``` diff --git a/docs/guide/src/pt-br/describing_ui/component_props.md b/docs/guide/src/pt-br/describing_ui/component_props.md deleted file mode 100644 index 4cb5a50ca..000000000 --- a/docs/guide/src/pt-br/describing_ui/component_props.md +++ /dev/null @@ -1,142 +0,0 @@ -# Props de Componentes - -Assim como você pode passar argumentos para uma função, você pode passar _props_ para um componente que personaliza seu comportamento! Os componentes que vimos até agora não aceitam _props_ – então vamos escrever alguns componentes que aceitam. - -## `#[derive(Props)]` - -_Props_ de componente são uma única estrutura anotada com `#[derive(Props)]`. Para um componente aceitar _props_, o tipo de seu argumento deve ser `Scope`. Então, você pode acessar o valor das _props_ usando `cx.props`. - -Existem 2 tipos de estruturas Props: - -- `props` próprios: - - Não tem uma vida útil associada - - Implementam `PartialEq`, permitindo a memoização (se os _props_ não mudarem, o Dioxus não renderizará novamente o componente) -- `props` emprestados: - - [Emprestado](https://doc.rust-lang.org/beta/rust-by-example/scope/borrow.html) de um componente pai - - Não pode ser memoizado devido a restrições de tempo de vida (Rust's lifetime) - -### Props Próprios - -_Props_ próprios são muito simples – eles não emprestam nada. Exemplo: - -```rust, no_run -{{#include ../../../examples/component_owned_props.rs:Likes}} -``` - -Você pode então passar valores de _prop_ para o componente da mesma forma que você passaria atributos para um elemento: - -```rust, no_run -{{#include ../../../examples/component_owned_props.rs:App}} -``` - -![Screenshot: Likes component](./images/component_owned_props_screenshot.png) - -### Props Emprestados - -Possuir _props_ funciona bem se seus _props_ forem fáceis de copiar – como um único número. Mas e se precisarmos passar um tipo de dados maior, como uma `String` de um componente `App` para um subcomponente `TitleCard`? Uma solução ingênua pode ser [`.clone()`](https://doc.rust-lang.org/std/clone/trait.Clone.html) a `String`, criando uma cópia dela para o subcomponente – mas isso seria ineficiente, especialmente para `Strings` maiores. - -Rust permite algo mais eficiente – emprestar a `String` como um `&str` – é para isso que servem as _props emprestadas_! - -```rust, no_run -{{#include ../../../examples/component_borrowed_props.rs:TitleCard}} -``` - -Podemos então usar o componente assim: - -```rust, no_run -{{#include ../../../examples/component_borrowed_props.rs:App}} -``` - -![Screenshot: TitleCard component](./images/component_borrowed_props_screenshot.png) - -## Props de Option - -A macro `#[derive(Props)]` tem alguns recursos que permitem personalizar o comportamento dos adereços. - -### Props Opcionais - -Você pode criar campos opcionais usando o tipo `Option<…>` para um campo: - -```rust, no_run -{{#include ../../../examples/component_props_options.rs:OptionalProps}} -``` - -Em seguida, você pode optar por fornecê-los ou não: - -```rust, no_run -{{#include ../../../examples/component_props_options.rs:OptionalProps_usage}} -``` - -### `Option` Explicitamente Obrigatórias - -Se você quiser exigir explicitamente uma `Option`, e não uma _prop_ opcional, você pode anotá-la com `#[props(!optional)]`: - -```rust, no_run -{{#include ../../../examples/component_props_options.rs:ExplicitOption}} -``` - -Então, você tem que passar explicitamente `Some("str")` ou `None`: - -```rust, no_run -{{#include ../../../examples/component_props_options.rs:ExplicitOption_usage}} -``` - -### Props Padrão - -Você pode usar `#[props(default = 42)]` para tornar um campo opcional e especificar seu valor padrão: - -```rust, no_run -{{#include ../../../examples/component_props_options.rs:DefaultComponent}} -``` - -Então, da mesma forma que _props_ opcionais, você não precisa fornecê-lo: - -```rust, no_run -{{#include ../../../examples/component_props_options.rs:DefaultComponent_usage}} -``` - -### Conversão Automática com `.into` - -É comum que as funções Rust aceitem `impl Into` em vez de apenas `SomeType` para suportar uma ampla gama de parâmetros. Se você quiser uma funcionalidade semelhante com _props_, você pode usar `#[props(into)]`. Por exemplo, você pode adicioná-lo em uma prop `String` – e `&str` também será aceito automaticamente, pois pode ser convertido em `String`: - -```rust, no_run -{{#include ../../../examples/component_props_options.rs:IntoComponent}} -``` - -Então, você pode usá-lo assim: - -```rust, no_run -{{#include ../../../examples/component_props_options.rs:IntoComponent_usage}} -``` - -## A macro `inline_props` - -Até agora, todas as funções `Component` que vimos tinham uma _struct_ `ComponentProps` correspondente para passar em _props_. Isso foi bastante verboso... Não seria legal ter _props_ como argumentos de função simples? Então não precisaríamos definir uma estrutura Props, e ao invés de digitar `cx.props.whatever`, poderíamos usar `whatever` diretamente! - -`inline_props` permite que você faça exatamente isso. Em vez de digitar a versão "completa": - -```rust, no_run -#[derive(Props, PartialEq)] -struct TitleCardProps { - title: String, -} - -fn TitleCard(cx: Scope) -> Element { - cx.render(rsx!{ - h1 { "{cx.props.title}" } - }) -} -``` - -...você pode definir uma função que aceita _props_ como argumentos. Então, basta anotá-lo com `#[inline_props]`, e a macro irá transformá-lo em um componente regular para você: - -```rust, no_run -#[inline_props] -fn TitleCard(cx: Scope, title: String) -> Element { - cx.render(rsx!{ - h1 { "{title}" } - }) -} -``` - -> Embora o novo Componente seja mais curto e fácil de ler, essa macro não deve ser usada por autores de bibliotecas, pois você tem menos controle sobre a documentação do Prop. diff --git a/docs/guide/src/pt-br/describing_ui/components.md b/docs/guide/src/pt-br/describing_ui/components.md deleted file mode 100644 index 91123b5f8..000000000 --- a/docs/guide/src/pt-br/describing_ui/components.md +++ /dev/null @@ -1,27 +0,0 @@ -# Componentes - -Assim como você não gostaria de escrever um programa complexo em uma única e longa função `main`, você não deve construir uma interface complexa em uma única função `App`. Em vez disso, seria melhor dividir a funcionalidade de um aplicativo em partes lógicas chamadas componentes. - -Um componente é uma função Rust, nomeada em _UpperCammelCase_, que recebe um parâmetro `Scope` e retorna um `Element` descrevendo a interface do usuário que deseja renderizar. Na verdade, nossa função `App` é um componente! - -```rust, no_run -{{#include ../../../examples/hello_world_desktop.rs:component}} -``` - -> Você provavelmente desejará adicionar `#![allow(non_snake_case)]` no topo de sua caixa para evitar avisos sobre o nome da função - -Um Componente é responsável por alguma tarefa de renderização – normalmente, renderizando uma parte isolada da interface do usuário. Por exemplo, você pode ter um componente `About` que renderiza uma breve descrição do Dioxus Labs: - -```rust, no_run -{{#include ../../../examples/components.rs:About}} -``` - -Em seguida, você pode renderizar seu componente em outro componente, da mesma forma que os elementos são renderizados: - -```rust, no_run -{{#include ../../../examples/components.rs:App}} -``` - -![Captura de tela contendo o componente Sobre duas vezes](./images/screenshot_about_component.png) - -> Neste ponto, pode parecer que os componentes nada mais são do que funções. No entanto, à medida que você aprende mais sobre os recursos do Dioxus, verá que eles são realmente mais poderosos! diff --git a/docs/guide/src/pt-br/describing_ui/images/component_borrowed_props_screenshot.png b/docs/guide/src/pt-br/describing_ui/images/component_borrowed_props_screenshot.png deleted file mode 100644 index 6f1864662..000000000 Binary files a/docs/guide/src/pt-br/describing_ui/images/component_borrowed_props_screenshot.png and /dev/null differ diff --git a/docs/guide/src/pt-br/describing_ui/images/component_owned_props_screenshot.png b/docs/guide/src/pt-br/describing_ui/images/component_owned_props_screenshot.png deleted file mode 100644 index 2a1146cd1..000000000 Binary files a/docs/guide/src/pt-br/describing_ui/images/component_owned_props_screenshot.png and /dev/null differ diff --git a/docs/guide/src/pt-br/describing_ui/images/screenshot_about_component.png b/docs/guide/src/pt-br/describing_ui/images/screenshot_about_component.png deleted file mode 100644 index 36f7250a1..000000000 Binary files a/docs/guide/src/pt-br/describing_ui/images/screenshot_about_component.png and /dev/null differ diff --git a/docs/guide/src/pt-br/describing_ui/index.md b/docs/guide/src/pt-br/describing_ui/index.md deleted file mode 100644 index 212e67921..000000000 --- a/docs/guide/src/pt-br/describing_ui/index.md +++ /dev/null @@ -1,116 +0,0 @@ -# Descrevendo a Interface do Usuário - -Dioxus é uma estrutura _declarativa_. Isso significa que, em vez de dizer ao Dioxus o que fazer (por exemplo, "criar um elemento" ou "definir a cor para vermelho"), simplesmente _declaramos_ como queremos que a interface do usuário se pareça usando o RSX. - -Você já viu um exemplo simples ou sintaxe `RSX` no aplicativo "hello world": - -```rust, no_run -{{#include ../../../examples/hello_world_desktop.rs:component}} -``` - -Aqui, usamos a macro `rsx!` para _declarar_ que queremos um elemento `div`, contendo o texto `"Hello, world!"`. Dioxus pega o RSX e constrói uma interface do usuário a partir dele. - -## Recursos do RSX - -O RSX é muito semelhante ao HTML, pois descreve elementos com atributos e filhos. Aqui está um elemento `div` vazio no RSX, bem como o HTML resultante: - -```rust, no_run -{{#include ../../../examples/rsx_overview.rs:empty}} -``` - -```html -
-``` - -### Filhos - -Para adicionar filhos a um elemento, coloque-os dentro dos colchetes `{}`. Eles podem ser outros elementos ou texto. Por exemplo, você pode ter um elemento `ol` (lista ordenada), contendo 3 elementos `li` (item da lista), cada um dos quais contém algum texto: - -```rust, no_run -{{#include ../../../examples/rsx_overview.rs:children}} -``` - -```html -
    -
  1. First Item
  2. -
  3. Second Item
  4. -
  5. Third Item
  6. -
-``` - -### Fragmentos - -Você também pode "agrupar" elementos envolvendo-os em `Fragment {}`. Isso não criará nenhum elemento adicional. - -> Nota: você também pode renderizar vários elementos no nível superior de `rsx!` e eles serão agrupados automaticamente – não há necessidade de um `Fragment {}` explícito lá. - -```rust, no_run -{{#include ../../../examples/rsx_overview.rs:fragments}} -``` - -```html -

First Item

-

Second Item

-a group -of three -items -``` - -### Atributos - -Os atributos também são especificados dentro dos colchetes `{}`, usando a sintaxe `name: value`. Você pode fornecer o valor como um literal no RSX: - -```rust, no_run -{{#include ../../../examples/rsx_overview.rs:attributes}} -``` - -```html -
Log In -``` - -> Nota: Todos os atributos definidos em `dioxus-html` seguem a convenção de nomenclatura snake_case. Eles transformam seus nomes `snake_case` em atributos `camelCase` do HTML. - -#### Atributos Personalizados - -Dioxus tem um conjunto pré-configurado de atributos que você pode usar. O RSX é validado em tempo de compilação para garantir que você não especificou um atributo inválido. Se você quiser substituir esse comportamento por um nome de atributo personalizado, especifique o atributo entre aspas: - -```rust, no_run -{{#include ../../../examples/rsx_overview.rs:custom_attributes}} -``` - -```html - Rust is cool -``` - -### Interpolação - -Da mesma forma que você pode [formatar](https://doc.rust-lang.org/rust-by-example/hello/print/fmt.html) Rust _strings_, você também pode interpolar no texto RSX. Use `{variable}` para exibir o valor de uma variável em uma _string_, ou `{variable:?}` para usar a representação `Debug`: - -```rust, no_run -{{#include ../../../examples/rsx_overview.rs:formatting}} -``` - -```html -
- Coordinates: (42, 0) -
ES
-
42
-
-``` - -### Expressões - -Você pode incluir expressões Rust arbitrárias dentro do RSX, mas deve escapá-las entre colchetes `[]`: - -```rust, no_run -{{#include ../../../examples/rsx_overview.rs:expression}} -``` - -```html -DIOXUS -``` diff --git a/docs/guide/src/pt-br/describing_ui/special_attributes.md b/docs/guide/src/pt-br/describing_ui/special_attributes.md deleted file mode 100644 index 01bfe9b25..000000000 --- a/docs/guide/src/pt-br/describing_ui/special_attributes.md +++ /dev/null @@ -1,62 +0,0 @@ -# Atributos Especiais - -Enquanto a maioria dos atributos são simplesmente passados para o HTML, alguns têm comportamentos especiais. - -## A Escotilha de Escape do HTML - -Se você estiver trabalhando com itens pré-renderizados, modelos ou uma biblioteca JS, convém passar o HTML diretamente em vez de passar pelo Dioxus. Nesses casos, use `dangerous_inner_html`. - -Por exemplo, enviar um conversor de markdown para Dioxus pode aumentar significativamente o tamanho final do aplicativo. Em vez disso, você desejará pré-renderizar sua remarcação para HTML e, em seguida, incluir o HTML diretamente em sua saída. Usamos essa abordagem para a [página inicial do Dioxus](https://dioxuslabs.com): - -```rust, no_run -{{#include ../../../examples/dangerous_inner_html.rs:dangerous_inner_html}} -``` - -> Nota! Esse atributo é chamado de "dangerous_inner_html" porque é **perigoso** passar dados que você não confia. Se você não for cuidadoso, poderá facilmente expor ataques de [cross-site scripting (XSS)](https://en.wikipedia.org/wiki/Cross-site_scripting) aos seus usuários. -> -> Se você estiver lidando com entradas não confiáveis, certifique-se de higienizar seu HTML antes de passá-lo para `dangerous_inner_html` – ou apenas passe-o para um elemento de texto para escapar de qualquer tag HTML. - -## Atributos Booleanos - -A maioria dos atributos, quando renderizados, serão renderizados exatamente como a entrada que você forneceu. No entanto, alguns atributos são considerados atributos "booleanos" e apenas sua presença determina se eles afetam a saída. Para esses atributos, um valor fornecido de `"false"` fará com que eles sejam removidos do elemento de destino. - -Portanto, este RSX não renderizaria o atributo `hidden`: - -```rust, no_run -{{#include ../../../examples/boolean_attribute.rs:boolean_attribute}} -``` - -```html -
hello
-``` - -No entanto, nem todos os atributos funcionam assim. _Apenas os seguintes atributos_ têm este comportamento: - -- `allowfullscreen` -- `allowpaymentrequest` -- `async` -- `autofocus` -- `autoplay` -- `checked` -- `controls` -- `default` -- `defer` -- `disabled` -- `formnovalidate` -- `hidden` -- `ismap` -- `itemscope` -- `loop` -- `multiple` -- `muted` -- `nomodule` -- `novalidate` -- `open` -- `playsinline` -- `readonly` -- `required` -- `reversed` -- `selected` -- `truespeed` - -Para quaisquer outros atributos, um valor de `"false"` será enviado diretamente para o DOM. diff --git a/docs/guide/src/pt-br/getting_started/desktop.md b/docs/guide/src/pt-br/getting_started/desktop.md deleted file mode 100644 index 70f71aa1a..000000000 --- a/docs/guide/src/pt-br/getting_started/desktop.md +++ /dev/null @@ -1,40 +0,0 @@ -# Aplicativo de área de trabalho - -Crie um aplicativo de desktop nativo autônomo que tenha a mesma aparência em todos os sistemas operacionais. - -Os aplicativos criados com o Dioxus geralmente têm menos de 5 MB de tamanho e usam os recursos existentes do sistema, para que não consumam quantidades extremas de RAM ou memória. - -Exemplos: - -- [Explorador de arquivos](https://github.com/DioxusLabs/example-projects/blob/master/file-explorer) -- [Scanner WiFi](https://github.com/DioxusLabs/example-projects/blob/master/wifi-scanner) - -[![Exemplo do Explorador de Arquivos](https://raw.githubusercontent.com/DioxusLabs/example-projects/master/file-explorer/image.png)](https://github.com/DioxusLabs/example-projects/tree /master/file-explorer) - -## Suporte - -O desktop é uma plataforma poderosa para o Dioxus, mas atualmente é limitado em capacidade quando comparado à plataforma Web. Atualmente, os aplicativos de desktop são renderizados com a biblioteca WebView da própria plataforma, mas seu código Rust está sendo executado nativamente em um _thread_ nativo. Isso significa que as APIs do navegador _não_ estão disponíveis, portanto, renderizar WebGL, Canvas, etc. não é tão fácil quanto a Web. No entanto, as APIs do sistema nativo _são_ acessíveis, portanto, streaming, WebSockets, sistema de arquivos, etc., são todas APIs viáveis. No futuro, planejamos migrar para um renderizador DOM personalizado baseado em webrenderer com integrações WGPU. - -O Dioxus Desktop é construído a partir do [Tauri](https://tauri.app/). No momento, não há abstrações do Dioxus sobre atalhos de teclado, barra de menus, manuseio, etc., então você deve aproveitar o Tauri - principalmente [Wry](http://github.com/tauri-apps/wry/) e [ Tao](http://github.com/tauri-apps/tao)) diretamente. - -## Criando um projeto - -Crie uma nova caixa: - -```shell -cargo new --bin demo -cd demo -``` - -Adicione o Dioxus com o recurso `desktop` (isso irá editar o `Cargo.toml`): - -```shell -cargo add dioxus -cargo add dioxus-desktop -``` - -Edite seu `main.rs`: - -```rust, no_run -{{#include ../../../examples/hello_world_desktop.rs:all}} -``` diff --git a/docs/guide/src/pt-br/getting_started/hot_reload.md b/docs/guide/src/pt-br/getting_started/hot_reload.md deleted file mode 100644 index 447169055..000000000 --- a/docs/guide/src/pt-br/getting_started/hot_reload.md +++ /dev/null @@ -1,31 +0,0 @@ -# Configurando o Hot Reload - -1. O recarregamento em tempo-real (_hot reload_) permite tempos de iteração muito mais rápidos dentro de chamadas 'rsx', interpretando-as e transmitindo as edições. -2. É útil para alterar o estilo/layout de um programa, mas não ajudará na alteração da lógica de um programa. -3. Atualmente, o cli implementa apenas o _hot-reload_ para o renderizador da web. - -# Configurar - -Instale o [dioxus-cli](https://github.com/DioxusLabs/cli). -Habilite o recurso de _hot-reload_ no dioxus: - -```toml -dioxus = { version = "*", features = ["hot-reload"] } -``` - -# Usage - -1. Execute: - -``` -dx serve --hot-reload -``` - -2. alterar algum código dentro de uma macro `rsx` -3. abra seu `localhost` em um navegador -4. salve e observe a mudança de estilo sem recompilar - -# Limitações - -1. O interpretador só pode usar expressões que existiam na última recompilação completa. Se você introduzir uma nova variável ou expressão na chamada `rsx`, ela acionará uma recompilação completa para capturar a expressão. -2. Componentes e Iteradores podem conter código de Rust arbitrário e acionarão uma recompilação completa quando alterados. diff --git a/docs/guide/src/pt-br/getting_started/index.md b/docs/guide/src/pt-br/getting_started/index.md deleted file mode 100644 index 2ee8fe89f..000000000 --- a/docs/guide/src/pt-br/getting_started/index.md +++ /dev/null @@ -1,72 +0,0 @@ -# Introdução - -Esta seção irá ajudá-lo a configurar seu projeto Dioxus! - -## Pré-requisitos - -### Editor - -O Dioxus se integra muito bem com o [plugin Rust-Analyzer LSP](https://rust-analyzer.github.io) que fornecerá realce de sintaxe apropriado, navegação de código, _folding_ e muito mais. - -### Rust - -Vá para [https://rust-lang.org](http://rust-lang.org) e instale o compilador Rust. - -É altamente recomendável ler o [livro oficial do Rust](https://doc.rust-lang.org/book/ch01-00-getting-started.html) _completamente_. No entanto, nossa esperança é que um aplicativo Dioxus possa servir como um ótimo primeiro projeto Rust. Com Dioxus, você aprenderá sobre: - -- Manipulação de erros -- Estruturas, Funções, Enums -- Closures -- Macros - -Nós empenhamos muito cuidado para tornar a sintaxe do Dioxus familiar e fácil de entender, para que você não precise de conhecimento profundo sobre _async_, _lifetime_ ou _smart pointers_ até que você realmente comece a criar aplicativos Dioxus complexos. - -### Dependências Específicas da Plataforma - -#### Windows - -Os aplicativos da área de trabalho do Windows dependem do WebView2 – uma biblioteca que deve ser instalada em todas as distribuições modernas do Windows. Se você tiver o Edge instalado, o Dioxus funcionará bem. Se você _não_ tiver o Webview2, [você poderá instalá-lo pela Microsoft](https://developer.microsoft.com/en-us/microsoft-edge/webview2/). MS oferece 3 opções: - -1. Um pequeno _bootstrapper_ "evergreen" que buscará um instalador do CDN da Microsoft -2. Um pequeno _instalador_ que buscará o Webview2 do CDN da Microsoft -3. Uma versão vinculada estaticamente do Webview2 em seu binário final para usuários offline - -Para fins de desenvolvimento, use a Opção 1. - -#### Linux - -Os aplicativos Webview Linux requerem WebkitGtk. Ao distribuir, isso pode ser parte de sua árvore de dependência em seu `.rpm` ou `.deb`. No entanto, é muito provável que seus usuários já tenham o WebkitGtk. - -```bash -sudo apt install libwebkit2gtk-4.0-dev libgtk-3-dev libappindicator3-dev -``` - -Ao usar o Debian/bullseye, o `libappindicator3-dev` não está mais disponível, pois foi substituído por `libayatana-appindicator3-dev`. - -```bash -# on Debian/bullseye use: -sudo apt install libwebkit2gtk-4.0-dev libgtk-3-dev libayatana-appindicator3-dev -``` - -Se você tiver problemas, certifique-se de ter todo o básico instalado, conforme descrito nos [documentos do Tauri](https://tauri.studio/v1/guides/getting-started/prerequisites#setting-up-linux). - -#### Mac OS - -Atualmente – tudo para macOS está integrado! No entanto, você pode encontrar um problema se estiver usando o Rust **nightly** devido a alguns problemas de permissão em nossa dependência do `Tao` (que foram resolvidos, mas não publicados). - -### Extensões do Cargo Sugeridas - -Se você quiser manter seu fluxo de trabalho tradicional como `npm install XXX` para adicionar pacotes, você pode querer instalar o `cargo-edit` e algumas outras extensões `cargo` interessantes: - -- [cargo-expand](https://github.com/dtolnay/cargo-expand) para expandir chamadas de macro -- [árvore de carga](https://doc.rust-lang.org/cargo/commands/cargo-tree.html) – um comando de carga integrado que permite inspecionar sua árvore de dependência - -## Guias de configuração - -Dioxus suporta múltiplas plataformas. Dependendo do que você quer, a configuração é um pouco diferente. - -- [Web](web.md): rodando no navegador usando WASM -- [Server Side Rendering](ssr.md): renderiza Dioxus HTML como texto -- [Desktop](desktop.md): um aplicativo autônomo usando o webview -- [Celular](mobile.md) -- [Terminal UI](tui.md): interface gráfica baseada em texto do terminal diff --git a/docs/guide/src/pt-br/getting_started/mobile.md b/docs/guide/src/pt-br/getting_started/mobile.md deleted file mode 100644 index 66a17272b..000000000 --- a/docs/guide/src/pt-br/getting_started/mobile.md +++ /dev/null @@ -1,76 +0,0 @@ -# Aplicativo móvel - -Crie um aplicativo móvel com Dioxus! - -Exemplo: [Aplicativo Todo](https://github.com/DioxusLabs/example-projects/blob/master/ios_demo) - -## Suporte - -Atualmente, a plataforma móvel é o destino de renderizador menos suportado para o Dioxus. Os aplicativos móveis são renderizados com o WebView da plataforma, o que significa que animações, transparência e widgets nativos não estão disponíveis no momento. - -Além disso, o iOS é a única plataforma móvel compatível. É possível obter o Dioxus rodando no Android e renderizado com WebView, mas a biblioteca de janelas do Rust que o Dioxus usa – tao – atualmente não suporta Android. - -Atualmente, o suporte móvel é mais adequado para aplicativos no estilo CRUD, idealmente para equipes internas que precisam desenvolver rapidamente, mas não se importam muito com animações ou widgets nativos. - -## Configurando - -A configuração com dispositivos móveis pode ser bastante desafiadora. As ferramentas aqui não são ótimas (ainda) e podem precisar de alguns _hacks_ para fazer as coisas funcionarem. O macOS M1 é amplamente inexplorado e pode não funcionar para você. - -Vamos usar `cargo-mobile` para construir para dispositivos móveis. Primeiro, instale-o: - -```shell -cargo install --git https://github.com/BrainiumLLC/cargo-mobile -``` - -E, em seguida, inicialize seu aplicativo para a plataforma certa. Use o modelo `winit` por enquanto. No momento, não há modelo "Dioxus" no cargo-mobile. - -```shell -cargo mobile init -``` - -Nós vamos limpar completamente as `dependências` que ele gera para nós, trocando `winit` por `dioxus-mobile`. - -```toml - -[package] -name = "dioxus-ios-demo" -version = "0.1.0" -authors = ["Jonathan Kelley "] -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 = "*" } -dioxus-desktop = { version = "*" } -simple_logger = "*" -``` - -Edite seu `lib.rs`: - -```rust, no_run -use dioxus::prelude::*; - -fn main() { - dioxus_desktop::launch(app); -} - -fn app(cx: Scope) -> Element { - cx.render(rsx!{ - div { - "hello world!" - } - }) -} -``` diff --git a/docs/guide/src/pt-br/getting_started/ssr.md b/docs/guide/src/pt-br/getting_started/ssr.md deleted file mode 100644 index ebf478163..000000000 --- a/docs/guide/src/pt-br/getting_started/ssr.md +++ /dev/null @@ -1,110 +0,0 @@ -# Renderização por Servidor - -O Dioxus 'VirtualDom' pode ser renderizado por servidor. - -[Exemplo: Dioxus DocSite](https://github.com/dioxusLabs/docsite) - -## Suporte a Multitarefas - -O Dioxus `VirtualDom`, infelizmente, atualmente não é `Send`. Internamente, usamos um pouco de mutabilidade interior que não é _thread-safe_. Isso significa que você não pode usar Dioxus facilmente com a maioria dos frameworks da web como Tide, Rocket, Axum, etc. - -Para resolver isso, você deve gerar um `VirtualDom` em seu próprio thread e se comunicar com ele por meio de canais. - -Ao trabalhar com frameworks web que requerem `Send`, é possível renderizar um `VirtualDom` imediatamente para uma `String` – mas você não pode manter o `VirtualDom` em um ponto de espera. Para SSR de estado retido (essencialmente LiveView), você precisará criar um _pool_ de `VirtualDoms`. - -## Configurar - -Se você quer apenas renderizar `rsx!` ou um VirtualDom para HTML, confira os documentos da API. É bem simples: - -```rust, no_run -// 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!" } } ); -``` - -No entanto, para este guia, vamos mostrar como usar Dioxus SSR com `Axum`. - -Certifique-se de ter o Rust and Cargo instalado e, em seguida, crie um novo projeto: - -```shell -cargo new --bin demo -cd app -``` - -Adicione o Dioxus com o recurso `ssr`: - -```shell -cargo add dioxus -cargo add dioxus-ssr -``` - -Em seguida, adicione todas as dependências do Axum. Isso será diferente se você estiver usando um Web Framework diferente - -``` -cargo add tokio --features full -cargo add axum -``` - -Suas dependências devem ficar mais ou menos assim: - -```toml -[dependencies] -axum = "0.4.5" -dioxus = { version = "*" } -dioxus-ssr = { version = "*" } -tokio = { version = "1.15.0", features = ["full"] } -``` - -Agora, configure seu aplicativo Axum para responder em um _endpoint_. - -```rust, no_run -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(); -} -``` - -E, em seguida, adicione nosso _endpoint_. Podemos renderizar `rsx!` diretamente: - -```rust, no_run -async fn app_endpoint() -> Html { - Html(dioxus_ssr::render_lazy(rsx! { - h1 { "hello world!" } - })) -} -``` - -Ou podemos renderizar `VirtualDoms`. - -```rust, no_run -async fn app_endpoint() -> Html { - 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)) -} -``` - -E é isso! - -> Você pode notar que não pode manter o VirtualDom em um ponto de espera. Dioxus atualmente não é ThreadSafe, então _deve_ permanecer no _thread_ que iniciou. Estamos trabalhando para flexibilizar essa exigência. diff --git a/docs/guide/src/pt-br/getting_started/tui.md b/docs/guide/src/pt-br/getting_started/tui.md deleted file mode 100644 index ba4e2ecda..000000000 --- a/docs/guide/src/pt-br/getting_started/tui.md +++ /dev/null @@ -1,46 +0,0 @@ -# IU do terminal - -Você pode construir uma interface baseada em texto que será executada no terminal usando o Dioxus. - -![Hello World screenshot](https://github.com/DioxusLabs/rink/raw/master/examples/example.png) - -> Nota: este livro foi escrito tendo em mente plataformas baseadas em HTML. Você pode acompanhar a TUI, mas terá que se adaptar um pouco. - -## Suporte - -O suporte à TUI é atualmente bastante experimental. Até o nome do projeto mudará. Mas, se você estiver disposto a se aventurar no reino do desconhecido, este guia o ajudará a começar. - -## Configurando - -Comece criando um novo pacote e adicionando nosso recurso TUI. - -```shell -cargo new --bin demo -cd demo -cargo add dioxus -cargo add dioxus-tui -``` - -Em seguida, edite seu `main.rs` com o modelo básico. - -```rust, no_run -{{#include ../../../examples/hello_world_tui.rs}} -``` - -Para executar nosso aplicativo: - -```shell -cargo run -``` - -Pressione "ctrl-c" para fechar o aplicativo. Para mudar de "ctrl-c" para apenas "q" para sair, você pode iniciar o aplicativo com uma configuração para desativar o sair padrão e usar a raiz TuiContext para sair por conta própria. - -```rust, no_run -{{#include ../../../examples/hello_world_tui_no_ctrl_c.rs}} -``` - -## Notas - -- Nosso pacote TUI usa flexbox para layout -- 1px é a altura da linha de um caractere. Seu px CSS regular não traduz. -- Se seu aplicativo entrar em pânico, seu terminal será destruído. Isso será corrigido eventualmente. diff --git a/docs/guide/src/pt-br/getting_started/web.md b/docs/guide/src/pt-br/getting_started/web.md deleted file mode 100644 index 47991b595..000000000 --- a/docs/guide/src/pt-br/getting_started/web.md +++ /dev/null @@ -1,75 +0,0 @@ -# Web - -Crie aplicativos de página única (SPA) que são executados no navegador com o Dioxus. Para rodar na Web, seu aplicativo deve ser compilado para WebAssembly e utilizar a `crate` `dioxus` com o recurso `web` ativado. - -Uma compilação do Dioxus para a web será aproximadamente equivalente ao tamanho de uma compilação do React (70kb vs 65kb), mas carregará significativamente mais rápido devido ao [StreamingCompile do WebAssembly](https://hacks.mozilla.org/2018/01/making-webassembly-even-faster-firefoxs-new-streaming-and-tiering-compiler/). - -Exemplos: - -- [TodoMVC](https://github.com/DioxusLabs/example-projects/tree/master/todomvc) -- [ECommerce](https://github.com/DioxusLabs/example-projects/tree/master/ecommerce-site) - -[![Exemplo de TodoMVC](https://github.com/DioxusLabs/example-projects/raw/master/todomvc/example.png)](https://github.com/DioxusLabs/example-projects/blob/master /todomvc) - -> Nota: Devido às limitações do Wasm, nem todos as `crates` funcionarão com seus aplicativos da web, portanto, você precisará certificar-se de que suas `crates` funcionem sem chamadas de sistema nativas (temporizadores, IO, etc.). - -## Suporte - -A Web é a plataforma de destino com melhor suporte para Dioxus. - -## Ferramentas - -Para desenvolver seu aplicativo Dioxus para a web, você precisará de uma ferramenta para construir e servir seus itens. Recomendamos usar [trunk](https://trunkrs.dev) que inclui um sistema de compilação, otimização Wasm, um servidor dev e suporte para SASS/CSS: - -```shell -cargo install trunk -``` - -Certifique-se de que o destino `wasm32-unknown-unknown` esteja instalado: - -```shell -rustup target add wasm32-unknown-unknown -``` - -## Criando um Projeto - -Crie uma nova caixa: - -```shell -cargo new --bin demo -cd demo -``` - -Adicione o Dioxus como uma dependência com o recurso `web`: - -```bash -cargo add dioxus -cargo add dioxus-web -``` - -Adicione um `index.html` para o `Trunk` usar. Certifique-se de que seu elemento "mount point" tenha um ID de "main": - -```html - - - - - - - -
- - -``` - -Edite seu `main.rs`: - -```rust, no_run -{{#include ../../../examples/hello_world_web.rs}} -``` - -E para servir nosso aplicativo: - -```bash -trunk serve -``` diff --git a/docs/guide/src/pt-br/images/compiletimecorrect.png b/docs/guide/src/pt-br/images/compiletimecorrect.png deleted file mode 100644 index 8fab7509f..000000000 Binary files a/docs/guide/src/pt-br/images/compiletimecorrect.png and /dev/null differ diff --git a/docs/guide/src/pt-br/images/component_tree.png b/docs/guide/src/pt-br/images/component_tree.png deleted file mode 100644 index d96924073..000000000 Binary files a/docs/guide/src/pt-br/images/component_tree.png and /dev/null differ diff --git a/docs/guide/src/pt-br/images/diffing.png b/docs/guide/src/pt-br/images/diffing.png deleted file mode 100644 index 4c243bc75..000000000 Binary files a/docs/guide/src/pt-br/images/diffing.png and /dev/null differ diff --git a/docs/guide/src/pt-br/images/dioxuslogo_full.png b/docs/guide/src/pt-br/images/dioxuslogo_full.png deleted file mode 100644 index 7d08f2af8..000000000 Binary files a/docs/guide/src/pt-br/images/dioxuslogo_full.png and /dev/null differ diff --git a/docs/guide/src/pt-br/images/oldnew.png b/docs/guide/src/pt-br/images/oldnew.png deleted file mode 100644 index 5aca37e40..000000000 Binary files a/docs/guide/src/pt-br/images/oldnew.png and /dev/null differ diff --git a/docs/guide/src/pt-br/images/publish.png b/docs/guide/src/pt-br/images/publish.png deleted file mode 100644 index b17d3bb06..000000000 Binary files a/docs/guide/src/pt-br/images/publish.png and /dev/null differ diff --git a/docs/guide/src/pt-br/index.md b/docs/guide/src/pt-br/index.md deleted file mode 100644 index e3d32ebc2..000000000 --- a/docs/guide/src/pt-br/index.md +++ /dev/null @@ -1,52 +0,0 @@ -# Introdução - -![dioxuslogo](./images/dioxuslogo_full.png) - -Dioxus é uma estrutura portátil, de alto desempenho e ergonômica para a construção de interfaces de usuário multiplataforma no Rust. Este guia irá ajudá-lo a começar a escrever aplicativos Dioxus para a Web, Desktop, Mobile e muito mais. - -```rust, no_run -fn app(cx: Scope) -> Element { - let mut count = use_state(cx, || 0); - - cx.render(rsx!( - h1 { "High-Five counter: {count}" } - button { onclick: move |_| count += 1, "Up high!" } - button { onclick: move |_| count -= 1, "Down low!" } - )) -} -``` - -Dioxus é fortemente inspirado pelo React. Se você conhece o React, começar com o Dioxus será muito fácil. - -> Este guia pressupõe que você já conhece um pouco de [Rust](https://www.rust-lang.org/)! Caso contrário, recomendamos ler [_the book_](https://doc.rust-lang.org/book/ch01-00-getting-started.html) para aprender Rust primeiro. - -## Recursos - -- Aplicativos de desktop rodando nativamente (sem Electron!) em menos de 10 linhas de código. -- Gerenciamento de estado incrivelmente ergonômico e poderoso. -- Documentação em linha abrangente - documentação sob o mouse e guias para todos os elementos HTML e manipuladores de eventos. -- Extremamente eficiente de memória – 0 alocações globais para componentes de estado estacionário. -- Agendador assíncrono multicanal para suporte assíncrono de primeira classe. -- E mais! Leia as [notas de lançamento completa](https://dioxuslabs.com/blog/introducing-dioxus/. - -### Multi Plataforma - -Dioxus é um kit de ferramentas _portátil_, o que significa que a implementação do núcleo pode ser executada em qualquer lugar sem independente da plataforma. Ao contrário de muitos outros kits de ferramentas de frontend Rust, o Dioxus não está intrinsecamente vinculado ao WebSys. Na verdade, todos os elementos e ouvintes de eventos podem ser trocados em tempo de compilação. Por padrão, o Dioxus vem com o recurso `html` habilitado, mas isso pode ser desabilitado dependendo do seu renderizador de destino. - -No momento, temos vários renderizadores de terceiros: - -- WebSys (para WASM): Ótimo suporte -- Tao/Tokio (para aplicativos de desktop): Bom suporte -- Tao/Tokio (para aplicativos móveis): Suporte ruim -- SSR (para gerar marcação estática) -- TUI/Rink (para aplicativos baseados em terminal): Experimental - -## Estabilidade - -Dioxus ainda não chegou a uma versão estável. - -Web: como a Web é uma plataforma bastante madura, esperamos que haja muito pouca rotatividade de API para recursos baseados na Web. - -Desktop: APIs provavelmente estarão em fluxo à medida que descobrimos padrões melhores do que nossa contraparte, ElectronJS. - -SSR: Não esperamos que a API SSR mude drasticamente no futuro. diff --git a/docs/guide/src/pt-br/interactivity/custom_hooks.md b/docs/guide/src/pt-br/interactivity/custom_hooks.md deleted file mode 100644 index c2ac570c4..000000000 --- a/docs/guide/src/pt-br/interactivity/custom_hooks.md +++ /dev/null @@ -1,26 +0,0 @@ -# Hooks Personalizados - -_Hooks_ são uma ótima maneira de encapsular a lógica de negócio. Se nenhum dos _hooks_ existentes funcionar para o seu problema, você pode escrever o seu próprio. - -## Hooks de Composição - -Para evitar a repetição, você pode encapsular a lógica de negócios com base em _hooks_ existentes para criar um novo gancho. - -Por exemplo, se muitos componentes precisam acessar uma _struct_ `AppSettings`, você pode criar um gancho de "atalho": - -```rust, no_run -{{#include ../../../examples/hooks_composed.rs:wrap_context}} -``` - -## Lógica de Hook Personalizada - -Você pode usar [`cx.use_hook`](https://docs.rs/dioxus/latest/dioxus/prelude/struct.Scope.html#method.use_hook) para construir seus próprios _hooks_. Na verdade, é nisso que todos os _hooks_ padrão são construídos! - -`use_hook` aceita um único encerramento para inicializar o _hook_. Ele será executado apenas na primeira vez que o componente for renderizado. O valor de retorno desse encerramento será usado como o valor do _hook_ – o Dioxus o pegará e o armazenará enquanto o componente estiver vivo. Em cada renderização (não apenas na primeira!), você receberá uma referência a esse valor. - -> Nota: Você pode implementar [`Drop`](https://doc.rust-lang.org/std/ops/trait.Drop.html) para o valor do seu _hook_ – ele será descartado e o componente será desmontado (não mais na interface do usuário) - -Dentro do encerramento de inicialização, você normalmente fará chamadas para outros métodos `cx`. Por exemplo: - -- O _hook_ `use_state` rastreia o estado no valor do _hook_ e usa [`cx.schedule_update`](https://docs.rs/dioxus/latest/dioxus/prelude/struct.Scope.html#method.schedule_update) para o Dioxus renderizar novamente o componente sempre que ele for alterado. -- O _hook_ `use_context` chama [`cx.consume_context`](https://docs.rs/dioxus/latest/dioxus/prelude/struct.Scope.html#method.consume_context) (que seria custoso chamar em cada render) para obter algum contexto do escopo diff --git a/docs/guide/src/pt-br/interactivity/dynamic_rendering.md b/docs/guide/src/pt-br/interactivity/dynamic_rendering.md deleted file mode 100644 index 58c120926..000000000 --- a/docs/guide/src/pt-br/interactivity/dynamic_rendering.md +++ /dev/null @@ -1,71 +0,0 @@ -# Renderização Dinâmica - -Às vezes você quer renderizar coisas diferentes dependendo do estado/_props_. Com o Dioxus, apenas descreva o que você quer ver usando o fluxo de controle do Rust – o _framework_ se encarregará de fazer as mudanças necessárias em tempo real se o estado ou _props_ mudarem! - -## Renderização Condicional - -Para renderizar diferentes elementos com base em uma condição, você pode usar uma instrução `if-else`: - -```rust, no_run -{{#include ../../../examples/conditional_rendering.rs:if_else}} -``` - -> Você também pode usar instruções `match`, ou qualquer função Rust para renderizar condicionalmente coisas diferentes. - -### Inspecionando _props_ `Element` - -Como `Element` é uma `Option`, os componentes que aceitam `Element` como _prop_ podem realmente inspecionar seu conteúdo e renderizar coisas diferentes com base nisso. Exemplo: - -```rust, no_run -{{#include ../../../examples/component_children_inspect.rs:Clickable}} -``` - -Você não pode modificar o `Element`, mas se precisar de uma versão modificada dele, você pode construir um novo baseado em seus atributos/filhos/etc. - -## Renderizando Nada - -Para renderizar nada, você pode retornar `None` de um componente. Isso é útil se você deseja ocultar algo condicionalmente: - -```rust, no_run -{{#include ../../../examples/conditional_rendering.rs:conditional_none}} -``` - -Isso funciona porque o tipo `Element` é apenas um alias para `Option` - -> Novamente, você pode usar um método diferente para retornar condicionalmente `None`. Por exemplo, a função _booleana_ [`then()`](https://doc.rust-lang.org/std/primitive.bool.html#method.then) pode ser usada. - -## Listas de renderização - -Frequentemente, você desejará renderizar uma coleção de componentes. Por exemplo, você pode querer renderizar uma lista de todos os comentários em uma postagem. - -Para isso, o Dioxus aceita iteradores que produzem `Element`s. Então precisamos: - -- Obter um iterador sobre todos os nossos itens (por exemplo, se você tiver um `Vec` de comentários, itere sobre ele com `iter()`) -- `.map` o iterador para converter cada item em um `Element` renderizado usando `cx.render(rsx!(...))` - - Adicione um atributo `key` exclusivo a cada item do iterador -- Incluir este iterador no RSX final - -Exemplo: suponha que você tenha uma lista de comentários que deseja renderizar. Então, você pode renderizá-los assim: - -```rust, no_run -{{#include ../../../examples/rendering_lists.rs:render_list}} -``` - -### O Atributo `key` - -Toda vez que você renderiza novamente sua lista, o Dioxus precisa acompanhar qual item foi para onde, porque a ordem dos itens em uma lista pode mudar – itens podem ser adicionados, removidos ou trocados. Apesar disso, Dioxus precisa: - -- Acompanhar o estado do componente -- Descobrir com eficiência quais atualizações precisam ser feitas na interface do usuário - -Por exemplo, suponha que o `CommentComponent` tenha algum estado – ex. um campo onde o usuário digitou uma resposta. Se a ordem dos comentários mudar repentinamente, o Dioxus precisa associar corretamente esse estado ao mesmo comentário – caso contrário, o usuário acabará respondendo a um comentário diferente! - -Para ajudar o Dioxus a acompanhar os itens da lista, precisamos associar cada item a uma chave exclusiva. No exemplo acima, geramos dinamicamente a chave exclusiva. Em aplicações reais, é mais provável que a chave venha de, por exemplo, um ID de banco de dados. Realmente não importa de onde você obtém a chave, desde que atenda aos requisitos - -- As chaves devem ser únicas em uma lista -- O mesmo item deve sempre ser associado à mesma chave -- As chaves devem ser relativamente pequenas (ou seja, converter toda a estrutura Comment em uma String seria uma chave muito ruim) para que possam ser comparadas com eficiência - -Você pode ficar tentado a usar o índice de um item na lista como sua chave. Na verdade, é isso que o Dioxus usará se você não especificar uma chave. Isso só é aceitável se você puder garantir que a lista seja constante – ou seja, sem reordenação, adições ou exclusões. - -> Observe que se você passar a chave para um componente que você criou, ele não receberá a chave como _prop_. É usado apenas como uma dica pelo próprio Dioxus. Se o seu componente precisar de um ID, você deve passá-lo como um _prop_ separado. diff --git a/docs/guide/src/pt-br/interactivity/event_handlers.md b/docs/guide/src/pt-br/interactivity/event_handlers.md deleted file mode 100644 index 8b3d757ef..000000000 --- a/docs/guide/src/pt-br/interactivity/event_handlers.md +++ /dev/null @@ -1,68 +0,0 @@ -# Manipuladores de eventos - -Eventos são ações interessantes que acontecem, geralmente relacionadas a algo que o usuário fez. Por exemplo, alguns eventos acontecem quando o usuário clica, rola, move o mouse ou digita um caractere. Para responder a essas ações e tornar a interface do usuário interativa, precisamos lidar com esses eventos. - -Os eventos estão associados a elementos. Por exemplo, geralmente não nos importamos com todos os cliques que acontecem em um aplicativo, apenas aqueles em um botão específico. Para lidar com eventos que acontecem em um elemento, devemos anexar o manipulador de eventos desejado a ele. - -Os manipuladores de eventos são semelhantes aos atributos regulares, mas seus nomes geralmente começam com `on` - e aceitam encerramentos como valores. O encerramento será chamado sempre que o evento for acionado e será passado esse evento. - -Por exemplo, para manipular cliques em um elemento, podemos especificar um manipulador `onclick`: - -```rust, no_run -{{#include ../../../examples/event_click.rs:rsx}} -``` - -## O Objeto `Evento` - -Os manipuladores de eventos recebem um objeto [`UiEvent`](https://docs.rs/dioxus-core/latest/dioxus_core/struct.UiEvent.html) contendo informações sobre o evento. Diferentes tipos de eventos contêm diferentes tipos de dados. Por exemplo, eventos relacionados ao mouse contêm [`MouseData`](https://docs.rs/dioxus/latest/dioxus/events/struct.MouseData.html), que informa coisas como onde o mouse foi clicado e quais botões do mouse foram usados. - -No exemplo acima, esses dados de evento foram registrados no terminal: - -``` -Clicked! Event: UiEvent { data: MouseData { coordinates: Coordinates { screen: (468.0, 109.0), client: (73.0, 25.0), element: (63.0, 15.0), page: (73.0, 25.0) }, modifiers: (empty), held_buttons: EnumSet(), trigger_button: Some(Primary) } } -Clicked! Event: UiEvent { data: MouseData { coordinates: Coordinates { screen: (468.0, 109.0), client: (73.0, 25.0), element: (63.0, 15.0), page: (73.0, 25.0) }, modifiers: (empty), held_buttons: EnumSet(), trigger_button: Some(Primary) } } -``` - -Para saber o que os diferentes tipos de eventos fornecem, leia os [documentos do módulo de eventos](https://docs.rs/dioxus/latest/dioxus/events/index.html). - -### Parando a propagação - -Quando você tem, por exemplo um `button` dentro de um `div`, qualquer clique no `button` também é um clique no `div`. Por esta razão, Dioxus propaga o evento click: primeiro, ele é acionado no elemento alvo, depois nos elementos pai. Se você quiser evitar esse comportamento, você pode chamar `cancel_bubble()` no evento: - -```rust, no_run -{{#include ../../../examples/event_click.rs:rsx}} -``` - -## Prevenir o Padrão - -Alguns eventos têm um comportamento padrão. Para eventos de teclado, isso pode ser inserir o caractere digitado. Para eventos de mouse, isso pode estar selecionando algum texto. - -Em alguns casos, você pode querer evitar esse comportamento padrão. Para isso, você pode adicionar o atributo `prevent_default` com o nome do manipulador cujo comportamento padrão você deseja interromper. Este atributo é especial: você pode anexá-lo várias vezes para vários atributos: - -```rust, no_run -{{#include ../../../examples/event_prevent_default.rs:prevent_default}} -``` - -Quaisquer manipuladores de eventos ainda serão chamados. - -> Normalmente, em React ou JavaScript, você chamaria "preventDefault" no evento no retorno de chamada. Dioxus atualmente _não_ suporta este comportamento. Observação: isso significa que você não pode impedir condicionalmente o comportamento padrão. - -## Manipulador de Props - -Às vezes, você pode querer criar um componente que aceite um manipulador de eventos. Um exemplo simples seria um componente `FancyButton`, que aceita um manipulador `on_click`: - -```rust, no_run -{{#include ../../../examples/event_handler_prop.rs:component_with_handler}} -``` - -Então, você pode usá-lo como qualquer outro manipulador: - -```rust, no_run -{{#include ../../../examples/event_handler_prop.rs:usage}} -``` - -> Nota: assim como qualquer outro atributo, você pode nomear os manipuladores como quiser! Embora eles devam começar com `on`, para que o prop seja automaticamente transformado em um `EventHandler` no local da chamada. -> -> Você também pode colocar dados personalizados no evento, em vez de, por exemplo, `MouseData` - -> Nota sobre formulários: se um manipulador de evento está anexado ao evento `onsubmit` em um formulário, o comportamento padrão é de **não submetê-lo**. Portanto, especificar `prevent_default: "onsubmit"` irá submetê-lo. \ No newline at end of file diff --git a/docs/guide/src/pt-br/interactivity/hooks.md b/docs/guide/src/pt-br/interactivity/hooks.md deleted file mode 100644 index c5dd85d41..000000000 --- a/docs/guide/src/pt-br/interactivity/hooks.md +++ /dev/null @@ -1,87 +0,0 @@ -# Hooks e Estado do Componente - -Até agora nossos componentes, sendo funções Rust, não tinham estado – eles estavam sempre renderizando a mesma coisa. No entanto, em um componente de interface do usuário, geralmente é útil ter uma funcionalidade com estado para criar interações do usuário. Por exemplo, você pode querer rastrear se o usuário abriu uma lista suspensa e renderizar coisas diferentes de acordo. - -Para lógica com estado, você pode usar _hooks_. _Hooks_ são funções Rust que fazem referência a `ScopeState` (em um componente, você pode passar `&cx`), e fornecem funcionalidade e estado. - -## Hook `use_state` - -[`use_state`](https://docs.rs/dioxus/latest/dioxus/hooks/fn.use_state.html) é um dos _hooks_ mais simples. - -- Você fornece um fechamento que determina o valor inicial -- `use_state` fornece o valor atual e uma maneira de atualizá-lo, definindo-o para outra coisa -- Quando o valor é atualizado, `use_state` faz o componente renderizar novamente e fornece o novo valor - -Por exemplo, você pode ter visto o exemplo do contador, no qual o estado (um número) é rastreado usando o _hook_ `use_state`: - -```rust, no_run -{{#include ../../../examples/hooks_counter.rs:component}} -``` - -![Screenshot: counter app](./images/counter.png) - -Toda vez que o estado do componente muda, ele é renderizado novamente e a função do componente é chamada, para que você possa descrever como deseja que a nova interface do usuário se pareça. Você não precisa se preocupar em "mudar" nada - apenas descreva o que você quer em termos de estado, e Dioxus cuidará do resto! - -> `use_state` retorna seu valor envolto em uma _smart pointer_ do tipo [`UseState`](https://docs.rs/dioxus/latest/dioxus/hooks/struct.UseState.html). É por isso que você pode ler o valor e atualizá-lo, mesmo dentro de um manipulador. - -Você pode usar vários _hooks_ no mesmo componente se quiser: - -```rust, no_run -{{#include ../../../examples/hooks_counter_two_state.rs:component}} -``` - -![Screenshot: app with two counters](./images/counter_two_state.png) - -## Regras dos Hooks - -O exemplo acima pode parecer um pouco mágico, já que as funções Rust normalmente não estão associadas ao estado. O Dioxus permite que os _hooks_ mantenham o estado entre as renderizações através de uma referência a `ScopeState`, e é por isso que você deve passar `&cx` para eles. - -Mas como Dioxus pode diferenciar entre vários _hooks_ no mesmo componente? Como você viu no segundo exemplo, ambas as funções `use_state` foram chamadas com os mesmos parâmetros, então como elas podem retornar coisas diferentes quando os contadores são diferentes? - -```rust, no_run -{{#include ../../../examples/hooks_counter_two_state.rs:use_state_calls}} -``` - -Isso só é possível porque os dois _hooks_ são sempre chamados na mesma ordem, então Dioxus sabe qual é qual. Portanto, a ordem em que você chama os _hooks_ é importante, e é por isso que você deve seguir certas regras ao usar os _hooks_: - -1. _Hooks_ só podem ser usados em componentes ou outros _hooks_ (falaremos disso mais tarde) -2. Em cada chamada para a função componente - 1. Os mesmos _hooks_ devem ser chamados - 2. Na mesma ordem -3. Os nomes dos _hooks_ devem começar com `use_` para que você não os confunda acidentalmente com funções normais - -Essas regras significam que há certas coisas que você não pode fazer com _hooks_: - -### Sem Hooks em Condicionais - -```rust, no_run -{{#include ../../../examples/hooks_bad.rs:conditional}} -``` - -### Sem Hooks em Closures - -```rust, no_run -{{#include ../../../examples/hooks_bad.rs:closure}} -``` - -### Sem Hooks em Loops - -```rust, no_run -{{#include ../../../examples/hooks_bad.rs:loop}} -``` - -## Gancho `use_ref` - -`use_state` é ótimo para rastrear valores simples. No entanto, você pode notar na [`UseState` API](https://docs.rs/dioxus/latest/dioxus/hooks/struct.UseState.html) que a única maneira de modificar seu valor é substituí-lo por algo else (por exemplo, chamando `set`, ou através de um dos operadores `+=`, `-=`). Isso funciona bem quando é barato construir um valor (como qualquer primitivo). Mas e se você quiser manter dados mais complexos no estado dos componentes? - -Por exemplo, suponha que queremos manter um `Vec` de valores. Se o armazenamos com `use_state`, a única maneira de adicionar um novo valor à lista seria criar um novo `Vec` com o valor adicional e colocá-lo no estado. Isto é custoso! Queremos modificar o `Vec` existente. - -Felizmente, existe outro _hook_ para isso, `use_ref`! É semelhante ao `use_state`, mas permite obter uma referência mutável aos dados contidos. - -Aqui está um exemplo simples que mantém uma lista de eventos em um `use_ref`. Podemos adquirir acesso de escrita ao estado com `.write()`, e então apenas `.push` um novo valor para o estado: - -```rust, no_run -{{#include ../../../examples/hooks_use_ref.rs:component}} -``` - -> Os valores de retorno de `use_state` e `use_ref`, (`UseState` e `UseRef`, respectivamente) são de alguma forma semelhantes a [`Cell`](https://doc.rust-lang.org/std/ cell/) e [`RefCell`](https://doc.rust-lang.org/std/cell/struct.RefCell.html) – eles fornecem mutabilidade interior. No entanto, esses _wrappers_ do Dioxus também garantem que o componente seja renderizado novamente sempre que você alterar o estado. diff --git a/docs/guide/src/pt-br/interactivity/images/counter.png b/docs/guide/src/pt-br/interactivity/images/counter.png deleted file mode 100644 index dd89cadef..000000000 Binary files a/docs/guide/src/pt-br/interactivity/images/counter.png and /dev/null differ diff --git a/docs/guide/src/pt-br/interactivity/images/counter_two_state.png b/docs/guide/src/pt-br/interactivity/images/counter_two_state.png deleted file mode 100644 index 4f77942a2..000000000 Binary files a/docs/guide/src/pt-br/interactivity/images/counter_two_state.png and /dev/null differ diff --git a/docs/guide/src/pt-br/interactivity/images/meme_editor_screenshot.png b/docs/guide/src/pt-br/interactivity/images/meme_editor_screenshot.png deleted file mode 100644 index 3f7c807fb..000000000 Binary files a/docs/guide/src/pt-br/interactivity/images/meme_editor_screenshot.png and /dev/null differ diff --git a/docs/guide/src/pt-br/interactivity/index.md b/docs/guide/src/pt-br/interactivity/index.md deleted file mode 100644 index 0dbdb2727..000000000 --- a/docs/guide/src/pt-br/interactivity/index.md +++ /dev/null @@ -1,3 +0,0 @@ -# Interatividade - -Até agora, aprendemos como descrever a estrutura e as propriedades de nossas interfaces de usuário. No entanto, a maioria das interfaces precisa ser interativa para ser útil. Neste capítulo, descrevemos como fazer um aplicativo Dioxus que responde ao usuário. diff --git a/docs/guide/src/pt-br/interactivity/roteador.md b/docs/guide/src/pt-br/interactivity/roteador.md deleted file mode 100644 index 564445de5..000000000 --- a/docs/guide/src/pt-br/interactivity/roteador.md +++ /dev/null @@ -1 +0,0 @@ -# Roteamento diff --git a/docs/guide/src/pt-br/interactivity/router.md b/docs/guide/src/pt-br/interactivity/router.md deleted file mode 100644 index 282508df9..000000000 --- a/docs/guide/src/pt-br/interactivity/router.md +++ /dev/null @@ -1,83 +0,0 @@ -# Roteador - -Em muitos de seus aplicativos, você desejará ter diferentes "cenas". Para uma página da Web, essas cenas podem ser as diferentes páginas da Web com seu próprio conteúdo. - -Você pode escrever sua própria solução de gerenciamento de cena também. No entanto, para poupar o seu esforço, o Dioxus oferece suporte a uma solução de primeira linha para gerenciamento de cena chamada Dioxus Router. - -## O que é isso? - -Para um aplicativo como a página de destino do Dioxus (https://dioxuslabs.com), queremos ter páginas diferentes. Um esboço rápido de um aplicativo seria algo como: - -- Pagina inicial -- Blogue -- Exemplo de vitrine - -Cada uma dessas cenas é independente – não queremos renderizar a página inicial e o blog ao mesmo tempo. - -É aqui que a `crates` do roteador são úteis. Para ter certeza de que estamos usando o roteador, basta adicionar o recurso `router` à sua dependência do Dioxus. - -```toml -[dependencies] -dioxus = { version = "*" } -dioxus-router = { version = "*" } -``` - -## Usando o Roteador - -Ao contrário de outros roteadores no ecossistema Rust, nosso roteador é construído de forma declarativa. Isso torna possível compor o layout do nosso aplicativo simplesmente organizando os componentes. - -```rust, no_run -rsx!{ - Router:: { - Route { to: "/home", Home {} } - Route { to: "/blog", Blog {} } - } -} -``` - -Sempre que visitamos este aplicativo, obteremos o componente Home ou o componente Blog renderizado, dependendo de qual rota entrarmos. Se nenhuma dessas rotas corresponder à localização atual, nada será renderizado. - -Podemos corrigir isso de duas maneiras: - -- Uma página 404 de _fallback_ - -```rust, no_run -rsx!{ - Router:: { - Route { to: "/home", Home {} } - Route { to: "/blog", Blog {} } - Route { to: "", NotFound {} } - } -} -``` - -- Redirecionar 404 para _Home_ - -```rust, no_run -rsx!{ - Router:: { - Route { to: "/home", Home {} } - Route { to: "/blog", Blog {} } - Redirect { from: "", to: "/home" } - } -} -``` - -## Links - -Para que nosso aplicativo navegue nessas rotas, podemos fornecer elementos clicáveis chamados Links. Eles simplesmente envolvem elementos `` que, quando clicados, navegam no aplicativo para o local determinado. - -```rust, no_run -rsx!{ - Link { - to: "/home", - "Go home!" - } -} -``` - -## Mais leitura - -Esta página é apenas uma breve visão geral do roteador para mostrar que existe uma solução poderosa já construída para um problema muito comum. Para obter mais informações sobre o roteador, confira seu livro ou confira alguns dos exemplos. - -O roteador tem sua própria documentação! [Disponível aqui](https://dioxuslabs.com/docs/0.3/router/). diff --git a/docs/guide/src/pt-br/interactivity/sharing_state.md b/docs/guide/src/pt-br/interactivity/sharing_state.md deleted file mode 100644 index b9b829c0c..000000000 --- a/docs/guide/src/pt-br/interactivity/sharing_state.md +++ /dev/null @@ -1,71 +0,0 @@ -# Estado de compartilhamento - -Muitas vezes, vários componentes precisam acessar o mesmo estado. Dependendo de suas necessidades, existem várias maneiras de implementar isso. - -## Elevenado o Estado - -Uma abordagem para compartilhar o estado entre os componentes é "elevá-lo" até o ancestral comum mais próximo. Isso significa colocar o _hook_ `use_state` em um componente pai e passar os valores necessários como _props_. - -Por exemplo, suponha que queremos construir um editor de memes. Queremos ter uma entrada para editar a legenda do meme, mas também uma visualização do meme com a legenda. Logicamente, o meme e a entrada são 2 componentes separados, mas precisam acessar o mesmo estado (a legenda atual). - -> Claro, neste exemplo simples, poderíamos escrever tudo em um componente - mas é melhor dividir tudo em componentes menores para tornar o código mais reutilizável e fácil de manter (isso é ainda mais importante para aplicativos maiores e complexos) . - -Começamos com um componente `Meme`, responsável por renderizar um meme com uma determinada legenda: - -```rust, no_run -{{#include ../../../examples/meme_editor.rs:meme_component}} -``` - -> Observe que o componente `Meme` não sabe de onde vem a legenda – ela pode ser armazenada em `use_state`, `use_ref` ou uma constante. Isso garante que seja muito reutilizável - o mesmo componente pode ser usado para uma galeria de memes sem nenhuma alteração! - -Também criamos um editor de legendas, totalmente desacoplado do meme. O editor de legendas não deve armazenar a legenda em si – caso contrário, como iremos fornecê-la ao componente `Meme`? Em vez disso, ele deve aceitar a legenda atual como um suporte, bem como um manipulador de eventos para delegar eventos de entrada para: - -```rust, no_run -{{#include ../../../examples/meme_editor.rs:caption_editor}} -``` - -Finalmente, um terceiro componente renderizará os outros dois como filhos. Ele será responsável por manter o estado e passar os _props_ relevantes. - -```rust, no_run -{{#include ../../../examples/meme_editor.rs:meme_editor}} -``` - -![Captura de tela do editor de memes: Um velho esqueleto de plástico sentado em um banco de parque. Legenda: "eu esperando por um recurso de idioma"](./images/meme_editor_screenshot.png) - -## Usando o contexto - -Às vezes, algum estado precisa ser compartilhado entre vários componentes na árvore, e passá-lo pelos _props_ é muito inconveniente. - -Suponha agora que queremos implementar uma alternância de modo escuro para nosso aplicativo. Para conseguir isso, faremos com que cada componente selecione o estilo dependendo se o modo escuro está ativado ou não. - -> Nota: estamos escolhendo esta abordagem como exemplo. Existem maneiras melhores de implementar o modo escuro (por exemplo, usando variáveis ​​CSS). Vamos fingir que as variáveis ​​CSS não existem – bem-vindo a 2013! - -Agora, poderíamos escrever outro `use_state` no componente superior e passar `is_dark_mode` para cada componente através de _props_. Mas pense no que acontecerá à medida que o aplicativo crescer em complexidade – quase todos os componentes que renderizam qualquer CSS precisarão saber se o modo escuro está ativado ou não – para que todos precisem do mesmo suporte do modo escuro. E cada componente pai precisará passá-lo para eles. Imagine como isso ficaria confuso e verboso, especialmente se tivéssemos componentes com vários níveis de profundidade! - -A Dioxus oferece uma solução melhor do que esta "perfuração com hélice" – fornecendo contexto. O _hook_ [`use_context_provider`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_context_provider.html) é semelhante ao `use_ref`, mas o torna disponível através do [`use_context`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_context.html) para todos os componentes filhos. - -Primeiro, temos que criar um _struct_ para nossa configuração de modo escuro: - -```rust, no_run -{{#include ../../../examples/meme_editor_dark_mode.rs:DarkMode_struct}} -``` - -Agora, em um componente de nível superior (como `App`), podemos fornecer o contexto `DarkMode` para todos os componentes filhos: - -```rust, no_run -{{#include ../../../examples/meme_editor_dark_mode.rs:context_provider}} -``` - -Como resultado, qualquer componente filho de `App` (direto ou não), pode acessar o contexto `DarkMode`. - -```rust, no_run -{{#include ../../../examples/meme_editor_dark_mode.rs:use_context}} -``` - -> `use_context` retorna `Option>` aqui. Se o contexto foi fornecido, o valor é `Some(UseSharedState)`, que você pode chamar `.read` ou `.write`, similarmente a `UseRef`. Caso contrário, o valor é `None`. - -Por exemplo, aqui está como implementaríamos a alternância do modo escuro, que lê o contexto (para determinar a cor que deve renderizar) e grava nele (para alternar o modo escuro): - -```rust, no_run -{{#include ../../../examples/meme_editor_dark_mode.rs:toggle}} -``` diff --git a/docs/guide/src/pt-br/interactivity/user_input.md b/docs/guide/src/pt-br/interactivity/user_input.md deleted file mode 100644 index 94a091e38..000000000 --- a/docs/guide/src/pt-br/interactivity/user_input.md +++ /dev/null @@ -1,33 +0,0 @@ -# Entradas do Usuário - -As interfaces geralmente precisam fornecer uma maneira de inserir dados: por exemplo, texto, números, caixas de seleção, etc. No Dioxus, há duas maneiras de trabalhar com a entrada do usuário. - -## Entradas Controladas - -Com entradas controladas, você fica diretamente responsável pelo estado da entrada. Isso lhe dá muita flexibilidade e facilita manter as coisas em sincronia. Por exemplo, é assim que você criaria uma entrada de texto controlada: - -```rust, no_run -{{#include ../../../examples/input_controlled.rs:component}} -``` - -Observe a flexibilidade - você pode: - -- Exibir o mesmo conteúdo em outro elemento, e eles estarão em sincronia -- Transformar a entrada toda vez que for modificada (por exemplo, para garantir que seja maiúscula) -- Validar a entrada toda vez que ela mudar -- Ter uma lógica personalizada acontecendo quando a entrada for alterada (por exemplo, solicitação de rede para preenchimento automático) -- Alterar programaticamente o valor (por exemplo, um botão "randomize" que preenche a entrada com absurdos) - -## Entradas não Controladas - -Como alternativa às entradas controladas, você pode simplesmente deixar a plataforma acompanhar os valores de entrada. Se não dissermos a uma entrada HTML qual conteúdo ela deve ter, ela poderá ser editada de qualquer maneira (isso está embutido na visualização da web). Essa abordagem pode ser mais eficiente, mas menos flexível. Por exemplo, é mais difícil manter a entrada sincronizada com outro elemento. - -Como você não tem necessariamente o valor atual da entrada não controlada no estado, você pode acessá-lo ouvindo os eventos `oninput` (de maneira semelhante aos componentes controlados) ou, se a entrada for parte de um formulário, você pode acessar os dados do formulário nos eventos do formulário (por exemplo, `oninput` ou `onsubmit`): - -```rust, no_run -{{#include ../../../examples/input_uncontrolled.rs:component}} -``` - -``` -Submitted! UiEvent { data: FormData { value: "", values: {"age": "very old", "date": "1966", "name": "Fred"} } } -``` diff --git a/docs/guide/src/pt-br/lib.rs b/docs/guide/src/pt-br/lib.rs deleted file mode 100644 index 97cda56a8..000000000 --- a/docs/guide/src/pt-br/lib.rs +++ /dev/null @@ -1 +0,0 @@ -// empty (we only need this crate for the examples) diff --git a/docs/guide/src/pt-br/publishing/desktop.md b/docs/guide/src/pt-br/publishing/desktop.md deleted file mode 100644 index ab9427b32..000000000 --- a/docs/guide/src/pt-br/publishing/desktop.md +++ /dev/null @@ -1,54 +0,0 @@ -# Publicação - -Parabéns! Você fez seu primeiro aplicativo Dioxus que realmente faz coisas muito legais. Este aplicativo usa a biblioteca WebView do seu sistema operacional, portanto, é portátil para ser distribuído para outras plataformas. - -Nesta seção, abordaremos como agrupar seu aplicativo para macOS, Windows e Linux. - -## Instale o `cargo-bundle` - -A primeira coisa que faremos é instalar o [`cargo-bundle`](https://github.com/burtonageo/cargo-bundle). Essa extensão para carga facilitará muito o empacotamento do nosso aplicativo para as várias plataformas. - -De acordo com a página do github `cargo-bundle`, - -_"cargo-bundle é uma ferramenta usada para gerar instaladores ou pacotes de aplicativos para executáveis ​​GUI criados com o cargo. Ele pode criar pacotes .app para Mac OS X e iOS, pacotes .deb para Linux e instaladores .msi para Windows (observe no entanto que o suporte para iOS e Windows ainda é experimental). O suporte para a criação de pacotes .rpm (para Linux) e pacotes .apk (para Android) ainda está pendente."_ - -Para instalar, basta executar - -`cargo install ` - -## Configurando seu Projeto - -Para obter uma configuração de projeto para empacotamento, precisamos adicionar algumas _flags_ ao nosso arquivo `Cargo.toml`. - -```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 -""" -``` - -## Empacotando - -Seguindo as instruções do cargo-bundle, simplesmente `cargo-bundle --release` para produzir um aplicativo final com todas as otimizações e recursos integrados. - -Depois de executar `cargo-bundle --release`, seu aplicativo deve estar acessível em - -`target/release/bundle//`. - -Por exemplo, um aplicativo macOS ficaria assim: - -![Aplicativo publicado](../images/publish.png) - -Ótimo! E são apenas 4,8 Mb – extremamente enxutos! Como o Dioxus aproveita o WebView nativo da sua plataforma, os aplicativos Dioxus são extremamente eficientes em termos de memória e não desperdiçam sua bateria. - -> Nota: nem todo CSS funciona da mesma forma em todas as plataformas. Certifique-se de visualizar o CSS do seu aplicativo em cada plataforma – ou navegador da web (Firefox, Chrome, Safari) antes de publicar. diff --git a/docs/guide/src/pt-br/publishing/index.md b/docs/guide/src/pt-br/publishing/index.md deleted file mode 100644 index 06b7aaf7b..000000000 --- a/docs/guide/src/pt-br/publishing/index.md +++ /dev/null @@ -1 +0,0 @@ -# Publicando diff --git a/docs/guide/src/pt-br/publishing/web.md b/docs/guide/src/pt-br/publishing/web.md deleted file mode 100644 index 2ecc49699..000000000 --- a/docs/guide/src/pt-br/publishing/web.md +++ /dev/null @@ -1,9 +0,0 @@ -## Publicando com o Github Pages - -Para construir nosso aplicativo e publicá-lo no Github: - -- Verifique se o GitHub Pages está configurado para seu repositório -- Crie seu aplicativo com `trunk build --release` (inclua `--public-url ` para atualizar os prefixos de ativos se estiver usando um site de projeto) -- Mova seu HTML/CSS/JS/Wasm gerado de `dist` para a pasta configurada para Github Pages -- Adicione e confirme com `git` -- `git push` para o GitHub diff --git a/docs/guide/src/pt-br/roadmap.md b/docs/guide/src/pt-br/roadmap.md deleted file mode 100644 index d16a09770..000000000 --- a/docs/guide/src/pt-br/roadmap.md +++ /dev/null @@ -1,138 +0,0 @@ -# Roteiro e Conjunto de Recursos - -Este conjunto de recursos e roteiro podem ajudá-lo a decidir se o que a Dioxus pode fazer hoje funciona para você. - -Se um recurso que você precisa não existe ou você deseja contribuir com projetos no roteiro, sinta-se à vontade para se envolver [juntando-se ao discord](https://discord.gg/XgGxMSkvUM). - -Em geral, aqui está o status de cada plataforma: - -- **Web**: Dioxus é uma ótima opção para aplicativos da web puros - especialmente para aplicativos CRUD/complexos. No entanto, ele não possui o ecossistema do React, então você pode estar perdendo uma biblioteca de componentes ou algum _hook_ útil. - -- **SSR**: Dioxus é uma ótima opção para pré-renderização, hidratação e renderização de HTML em um endpoint da web. Esteja ciente: o `VirtualDom` não é (atualmente) `Send + Sync`. - -- **Desktop**: você pode criar aplicativos de desktop de janela única muito competentes agora mesmo. No entanto, os aplicativos de várias janelas exigem suporte do núcleo do Dioxus que não estão prontos. - -- **Celular**: o suporte móvel é muito recente. Você descobrirá as coisas à medida que avança e não há muitas `crates` de suporte para periféricos. - -- **LiveView**: o suporte ao LiveView é muito recente. Você descobrirá as coisas à medida que avança. Felizmente, nada disso é muito difícil e qualquer trabalho poderá ser enviado `upstream` no Dioxus. - -## Recursos - ---- - -| Recurso | Situação | Descrição | -| ----------------------------------- | -------- | ------------------------------------------------------------------------------------------------ | -| Renderização Condicional | ✅ | `if/then` para esconder/mostrar componente | -| Map, Iterador | ✅ | `map/filter/reduce` para produzir `rsx!` | -| Componentes Chaveados | ✅ | comparação em `diff` com chaves | -| Web | ✅ | renderizador para navegadores Web | -| Desktop (WebView) | ✅ | renderizador para Desktop | -| Estado Compartilhado (Context) | ✅ | compartilha estados através de árvores | -| Hooks | ✅ | células de memoria nos componentes | -| SSR | ✅ | renderiza diretamente para `string` | -| Componente Filho | ✅ | `cx.children()` como lista de nós | -| Componentes Sem Elementos | ✅ | componentes que não renderizam elementos reais na DOM | -| Fragmentos | ✅ | elementos múltiplos sem uma raiz real | -| Propriedades Manuais | ✅ | passa manualmente `props` com a sintaxe de propagação (`spread syntax`) | -| Entradas Controladas | ✅ | encapsulamento com estado em sobre entradas | -| Estilos CSS/Inline | ✅ | sintaxe para grupos de estilo/atributos em linha | -| Elementos Personalizados | ✅ | define novos elementos primitivos | -| Suspensão | ✅ | programa futuras renderizações usando `future`/`Promise` | -| Tratamento Integrado de Erros | ✅ | trata erros graciosamente com a sintaxe `?` | -| NodeRef | ✅ | ganha acesso direto aos nós | -| Re-hidratação | ✅ | pre-renderiza HTML para acelerar a primeira impressão na tela | -| Renderização Livre de Gargalos | ✅ | `diffs` grandes são segmentados sobre quadros para uma transição suave como seda | -| Efeitos | ✅ | executa efeitos após um componente ser enviado para a fila de renderização | -| Portais | 🛠 | renderiza nós fora da árvore tradicional de elementos (DOM) | -| Agendamento Cooperativo | 🛠 | prioriza eventos com mais importância sobre eventos menos importantes | -| Componentes de Servidor | 🛠 | componentes híbridos para aplicativos de única página (SPA) e servidores | -| Divisão de Pacotes | 👀 | carrega o aplicativo assincronamente e eficientemente | -| Componentes Tardios | 👀 | dinamicamente carrega os novos componentes assim que estiverem prontos enquanto a página carrega | -| Estado Global de 1ª Classe | ✅ | `redux/recoil/mobx` sobre o `context` | -| Execução Nativa | ✅ | execução como um binário portátil sem um `runtime` (Node) | -| Sub-Árvore de Memoization | ✅ | pula o `diffing` em sub-árvores de elementos estáticos | -| Modelos de Alta Eficiência | 🛠 | chamadas `rsx!` são traduzidas para modelos sobre a `DOM` | -| Garantia de Correção por Compilador | ✅ | avisa sobre erros em esquemas de modelos inválidos antes do final da compilação | -| Motor de Heurística | ✅ | rastreia componentes na memória para minimizar alocações futures | -| Controle Preciso de Reatividade | 👀 | pula o `diffing` para ter controle preciso das atualizações de tela | - -- ✅ = implementado e funcionando -- 🛠 = sendo trabalhado ativamente -- 👀 = ainda não implementado ou sendo trabalhado - -## Roteiro - -Esses recursos estão planejados para o futuro do Dioxus: - -### Essencial - -- [x] Liberação do Núcleo Dioxus -- [x] Atualizar a documentação para incluir mais teoria e ser mais abrangente -- [ ] Suporte para modelos HTML para manipulação de DOM ultrarrápida -- [ ] Suporte para vários renderizadores para o mesmo `virtualdom` (subárvores) -- [ ] Suporte para `ThreadSafe` (`Send` + `Sync`) -- [ ] Suporte para `Portals` - -### SSR - -- [x] Suporte SSR + Hidratação -- [ ] Suporte integrado de suspensão para SSR - -### Desktop - -- [ ] Gerenciamento de janela declarativa -- [ ] Modelos para construção/agregação -- [ ] Renderizador totalmente nativo -- [ ] Acesso ao contexto Canvas/WebGL nativamente - -### Móvel - -- [ ] Biblioteca padrão móvel - - [ ] GPS - - [ ] Câmera - - [ ] Sistema de Arquivo - - [ ] Biometria - - [ ] Wi-fi - - [ ] Bluetooth - - [ ] Notificações - - [ ] Prancheta (_Clipboard_) -- [ ] Animações -- [ ] Renderizador nativo - -### Empacotamento (CLI) - -- [x] Tradução de HTML para RSX -- [x] Servidor de desenvolvimento -- [x] Recarregamento em tempo-real (_hot-reload_) -- [x] Tradução de JSX para RSX -- [ ] Substituição de módulos em tempo-real (_hot-modules_) -- [ ] Divisão de código -- [ ] Acervo de macros -- [ ] _Pipeline_ CSS -- [ ] _Pipeline_ de imagens - -### Hooks Essenciais - -- [x] Roteador -- [x] Gerenciamento de estado global -- [ ] Redimensionar o observador - -## Trabalho em Progresso - -### Ferramenta de Construção - -Atualmente, estamos trabalhando em nossa própria ferramenta de compilação chamada [Dioxus CLI](https://github.com/DioxusLabs/cli) que suportará: - -- uma TUI interativa -- reconfiguração em tempo real -- recarga de CSS em tempo-real -- ligação de dados bidirecional entre o navegador e o código-fonte -- um interpretador para `rsx!` -- capacidade de publicar no github/netlify/vercel -- pacote para iOS/Desktop/etc - -### Suporte ao LiveView / Componente do Servidor - -A arquitetura interna do Dioxus foi projetada desde o primeiro dia para suportar o caso de uso `LiveView`, onde um servidor Web hospeda um aplicativo em execução para cada usuário conectado. A partir de hoje, não há suporte LiveView de primeira classe – você precisará conectar isso sozinho. - -Embora não esteja totalmente implementado, a expectativa é que os aplicativos LiveView possam ser um híbrido entre Wasm e renderizado pelo servidor, onde apenas partes de uma página são "ao vivo" e o restante da página é renderizado pelo servidor, gerado estaticamente ou manipulado pelo SPA anfitrião. diff --git a/docs/posts/release-0-2-0.md b/docs/posts/release-0-2-0.md deleted file mode 100644 index 82d87a730..000000000 --- a/docs/posts/release-0-2-0.md +++ /dev/null @@ -1,361 +0,0 @@ -# Dioxus v0.2 Release: TUI, Router, Fermi, and Tooling - -> March 9, 2022 - -Thanks to these amazing folks for their financial support on OpenCollective: - -- [@t1m0t](https://github.com/t1m0t) -- [@alexkirsz](https://github.com/t1m0t) -- [@freopen](https://github.com/freopen) -- [@DannyMichaels](https://github.com/DannyMichaels) -- [@SweetLittleMUV](https://github.com/Fatcat560) - -Thanks to these amazing folks for their code contributions: - -- [@mrxiaozhuox](https://github.com/mrxiaozhuox) -- [@autarch](https://github.com/autarch) -- [@FruitieX](https://github.com/FruitieX) -- [@t1m0t](https://github.com/t1m0t) -- [@Demonthos](https://github.com/Demonthos) -- [@oovm](https://github.com/oovm) -- [@6asaaki](https://github.com/6asaaki) - -Just over two months in, and we already a ton of awesome changes to Dioxus! - -Dioxus is a recently-released library for building interactive user interfaces (GUI) with Rust. It is built around a Virtual DOM, making it portable for the web, desktop, server, mobile, and more. Dioxus looks and feels just like React, so if you know React, then you'll feel right at home. - -```rust, no_run -fn app(cx: Scope) -> Element { - let mut count = use_state(cx, || 0); - - cx.render(rsx! { - h1 { "Count: {count}" } - button { onclick: move |_| count += 1, "+" } - button { onclick: move |_| count -= 1, "-" } - }) -} -``` - -# What's new? - -A _ton_ of stuff happened in this release; 550+ commits, 23 contributors, 2 minor releases, and 6 backers on Open Collective. - -Some of the major new features include: - -- We now can render into the terminal, similar to Ink.JS - a huge thanks to [@Demonthos](https://github.com/Demonthos) -- We have a new router in the spirit of React-Router [@autarch](https://github.com/autarch) -- We now have Fermi for global state management in the spirit of [Recoil.JS](https://recoiljs.org) -- Our desktop platform got major upgrades, getting closer to parity with Electron [@mrxiaozhuox](https://github.com/mrxiaozhuox) -- Our CLI tools now support HTML-to-RSX translation for converting 3rd party HTML into Dioxus [@mrxiaozhuox](https://github.com/mrxiaozhuox) -- Dioxus-Web is sped up by 2.5x with JS-based DOM manipulation (3x faster than React) - -We also fixed and improved a bunch of stuff - check out the full list down below. - -## A New Renderer: Your terminal! - -When Dioxus was initially released, we had very simple support for logging Dioxus elements out as TUI elements. In the past month or so, [@Demonthos](https://github.com/Demonthos) really stepped up and made the new crate a reality. - -![Imgur](https://i.imgur.com/GL7uu3r.png) - -The new TUI renderer even supports mouse movements, keyboard input, async tasks, borders, and a ton more. - -` tag. It takes a target and children. - -Unlike a regular `` tag, we can pass in our Route enum as the target. Because we annotated our routes with the [`route(path)`] attribute, the [`Link`] will know how to generate the correct URL. If we use the Route enum, the rust compiler will prevent us from linking to a page that doesn't exist. - -Let's add our links: - -```rust, no_run -{{#include ../../examples/links.rs:nav}} -``` - -> Using this method, the [`Link`] component only works for links within our -> application. To learn more about navigation targets see -> [here](./navigation-targets.md). - -Now you should see a list of links near the top of your page. Click on one and -you should seamlessly travel between pages. - -## URL Parameters and Nested Routes - -Many websites such as GitHub put parameters in their URL. For example, -`https://github.com/DioxusLabs` utilizes the text after the domain to -dynamically search and display content about an organization. - -We want to store our blogs in a database and load them as needed. We also -want our users to be able to send people a link to a specific blog post. -Instead of listing all of the blog titles at compile time, we can make a dynamic route. - -We could utilize a search page that loads a blog when clicked but then our users -won't be able to share our blogs easily. This is where URL parameters come in. - -The path to our blog will look like `/blog/myBlogPage`, `myBlogPage` being the -URL parameter. - -First, let's create a layout component (similar to the navbar) that wraps the blog content. This allows us to add a heading that tells the user they are on the blog. - -```rust, no_run -{{#include ../../examples/dynamic_route.rs:blog}} -``` - -Now we'll create another index component, that'll be displayed when no blog post -is selected: - -```rust, no_run -{{#include ../../examples/dynamic_route.rs:blog_list}} -``` - -We also need to create a component that displays an actual blog post. This component will accept the URL parameters as props: - -```rust, no_run -{{#include ../../examples/dynamic_route.rs:blog_post}} -``` - -Finally, let's tell our router about those components: - -```rust, no_run -{{#include ../../examples/dynamic_route.rs:router}} -``` - -That's it! If you head to `/blog/1` you should see our sample post. - -## Conclusion - -In this chapter, we utilized Dioxus Router's Link, and Route Parameter -functionality to build the blog portion of our application. In the next chapter, -we will go over how navigation targets (like the one we passed to our links) -work. - -[`Link`]: https://docs.rs/dioxus-router/latest/dioxus_router/prelude/fn.GenericLink.html diff --git a/docs/router/src/example/first-route.md b/docs/router/src/example/first-route.md deleted file mode 100644 index 5135f6a8f..000000000 --- a/docs/router/src/example/first-route.md +++ /dev/null @@ -1,62 +0,0 @@ -# Creating Our First Route - -In this chapter, we will start utilizing Dioxus Router and add a homepage and a -404 page to our project. - -## Fundamentals - -The core of the Dioxus Router is the [`Routable`] macro and the [`Router`] component. - -First, we need an actual page to route to! Let's add a homepage component: - -```rust, no_run -{{#include ../../examples/first_route.rs:home}} -``` - -## Creating Routes - -We want to use Dioxus Router to separate our application into different "pages". -Dioxus Router will then determine which page to render based on the URL path. - -To start using Dioxus Router, we need to use the [`Routable`] macro. - -The [`Routable`] macro takes an enum with all of the possible routes in our application. Each variant of the enum represents a route and must be annotated with the [`route(path)`] attribute. - -```rust, no_run -{{#include ../../examples/first_route.rs:router}} -``` - -All other hooks and components the router provides can only be used as a descendant of a [`Router`] component. - -If you head to your application's browser tab, you should now see the text -`Welcome to Dioxus Blog!` when on the root URL (`http://localhost:8080/`). If -you enter a different path for the URL, nothing should be displayed. - -This is because we told Dioxus Router to render the `Home` component only when -the URL path is `/`. - -## Fallback Route - -In our example, when a route doesn't exist Dioxus Router doesn't render anything. Many sites also have a "404" page when a path does not exist. Let's add one to our site. - -First, we create a new `PageNotFound` component. - -```rust, no_run -{{#include ../../examples/catch_all.rs:fallback}} -``` - -Next, register the route in the Route enum to match if all other routes fail. - -```rust, no_run -{{#include ../../examples/catch_all.rs:router}} -``` - -Now when you go to a route that doesn't exist, you should see the page not found -text. - -## Conclusion - -In this chapter, we learned how to create a route and tell Dioxus Router what -component to render when the URL path is `/`. We also created a 404 page to -handle when a route doesn't exist. Next, we'll create the blog portion of our -site. We will utilize nested routes and URL parameters. diff --git a/docs/router/src/example/full-code.md b/docs/router/src/example/full-code.md deleted file mode 100644 index ca97812a5..000000000 --- a/docs/router/src/example/full-code.md +++ /dev/null @@ -1,5 +0,0 @@ -# Full Code - -```rust, no_run -{{#include ../../examples/full_example.rs}} -``` diff --git a/docs/router/src/example/index.md b/docs/router/src/example/index.md deleted file mode 100644 index 064c9ac68..000000000 --- a/docs/router/src/example/index.md +++ /dev/null @@ -1,29 +0,0 @@ -# Overview - -In this guide, you'll learn to effectively use Dioxus Router whether you're -building a small todo app or the next FAANG company. We will create a small -website with a blog, homepage, and more! - -> To follow along with the router example, you'll need a working Dioxus app. -> Check out the [Dioxus book](https://dioxuslabs.com/docs/0.3/guide/en/) to get started. - -> Make sure to add Dioxus Router as a dependency, as explained in the -> [introduction](../index.md). - -## You'll learn how to - -- Create routes and render "pages". -- Utilize nested routes, create a navigation bar, and render content for a - set of routes. -- Parse URL parameters to dynamically display content. -- Redirect visitors to different routes. - -> **Disclaimer** -> -> The example will only display the features of Dioxus Router. It will not -> include any actual functionality. To keep things simple we will only be using -> a single file, this is not the recommended way of doing things with a real -> application. - -You can find the complete application in the [full code](./full-code.md) -chapter. diff --git a/docs/router/src/example/navigation-targets.md b/docs/router/src/example/navigation-targets.md deleted file mode 100644 index fb12f913f..000000000 --- a/docs/router/src/example/navigation-targets.md +++ /dev/null @@ -1,27 +0,0 @@ -# Navigation Targets - -In the previous chapter, we learned how to create links to pages within our app. -We told them where to go using the `target` property. This property takes something that can be converted to a [`NavigationTarget`]. - -## What is a navigation target? - -A [`NavigationTarget`] is similar to the `href` of an HTML anchor element. It -tells the router where to navigate to. The Dioxus Router knows two kinds of -navigation targets: - -- [`Internal`]: We used internal links in the previous chapter. It's a link to a page within our - app represented as a Route enum. -- [`External`]: This works exactly like an HTML anchors' `href`. Don't use this for in-app - navigation as it will trigger a page reload by the browser. - -## External navigation - -If we need a link to an external page we can do it like this: - -```rust, no_run -{{#include ../../examples/external_link.rs:component}} -``` - -[`External`]: https://docs.rs/dioxus-router-core/latest/dioxus_router/navigation/enum.NavigationTarget.html#variant.External -[`Internal`]: https://docs.rs/dioxus-router-core/latest/dioxus_router/navigation/enum.NavigationTarget.html#variant.Internal -[`NavigationTarget`]: https://docs.rs/dioxus-router-core/latest/dioxus_router/navigation/enum.NavigationTarget.html diff --git a/docs/router/src/example/redirection-perfection.md b/docs/router/src/example/redirection-perfection.md deleted file mode 100644 index 1ad4950ae..000000000 --- a/docs/router/src/example/redirection-perfection.md +++ /dev/null @@ -1,41 +0,0 @@ -# Redirection Perfection - -You're well on your way to becoming a routing master! - -In this chapter, we will cover creating redirects - -## Creating Redirects - -A redirect is very simple. When dioxus encounters a redirect while finding out -what components to render, it will redirect the user to the target of the -redirect. - -As a simple example, let's say you want user to still land on your blog, even -if they used the path `/myblog` or `/myblog/:name`. - -Redirects are special attributes in the router enum that accept a route and a closure -with the route parameters. The closure should return a route to redirect to. - -Let's add a redirect to our router enum: - -```rust, no_run -{{#include ../../examples/full_example.rs:router}} -``` - -That's it! Now your users will be redirected to the blog. - -### Conclusion - -Well done! You've completed the Dioxus Router guide. You've built a small -application and learned about the many things you can do with Dioxus Router. -To continue your journey, you attempt a challenge listed below, look at the [router examples](https://github.com/DioxusLabs/dioxus/tree/master/packages/router/examples), or -can check out the [API reference](https://docs.rs/dioxus-router/). - -### Challenges - -- Organize your components into separate files for better maintainability. -- Give your app some style if you haven't already. -- Build an about page so your visitors know who you are. -- Add a user system that uses URL parameters. -- Create a simple admin system to create, delete, and edit blogs. -- If you want to go to the max, hook up your application to a rest API and database. diff --git a/docs/router/src/index.md b/docs/router/src/index.md deleted file mode 100644 index 56a7d5deb..000000000 --- a/docs/router/src/index.md +++ /dev/null @@ -1,27 +0,0 @@ -# Introduction - -> If you are not familiar with Dioxus itself, check out the [Dioxus book](https://dioxuslabs.com/docs/0.3/guide/en/) first. - -Whether you are building a website, desktop app, or mobile app, -splitting your app's views into "pages" can be an effective method for -organization and maintainability. - -For this purpose, Dioxus provides a router. Use the `cargo add` command to add the dependency: - -```sh -cargo add dioxus-router -``` - -This book is intended to get you up to speed with Dioxus Router. It is split -into two sections: - -1. The [reference](./reference/index.md) section explains individual features in - depth. You can read it from start to finish, or you can read individual chapters - in whatever order you want. -2. If you prefer a learning-by-doing approach, you can check out the - _[example project](./example/index.md)_. It guides you through - creating a dioxus app, setting up the router, and using some of its - functionality. - -> Please note that this is not the only documentation for the Dioxus Router. You -> can also check out the [API Docs](https://docs.rs/dioxus-router/). diff --git a/docs/router/src/lib.rs b/docs/router/src/lib.rs deleted file mode 100644 index 97cda56a8..000000000 --- a/docs/router/src/lib.rs +++ /dev/null @@ -1 +0,0 @@ -// empty (we only need this crate for the examples) diff --git a/docs/router/src/reference/history-buttons.md b/docs/router/src/reference/history-buttons.md deleted file mode 100644 index ad3ffbe22..000000000 --- a/docs/router/src/reference/history-buttons.md +++ /dev/null @@ -1,32 +0,0 @@ -# History Buttons - -Some platforms, like web browsers, provide users with an easy way to navigate -through an app's history. They have UI elements or integrate with the OS. - -However, native platforms usually don't provide such amenities, which means that -apps wanting users to have access to them, need to implement them. For this -reason, the router comes with two components, which emulate a browser's back and -forward buttons: - -- [`GoBackButton`](https://docs.rs/dioxus-router/latest/dioxus_router/components/fn.GoBackButton.html) -- [`GoForwardButton`](https://docs.rs/dioxus-router/latest/dioxus_router/components/fn.GoForwardButton.html) - -> If you want to navigate through the history programmatically, take a look at -> [`programmatic navigation`](./navigation/programmatic.md). - -```rust, no_run -{{#include ../../examples/history_buttons.rs:history_buttons}} -``` - -As you might know, browsers usually disable the back and forward buttons if -there is no history to navigate to. The router's history buttons try to do that -too, but depending on the [history provider] that might not be possible. - -Importantly, neither [`WebHistory`] supports that feature. -This is due to limitations of the browser History API. - -However, in both cases, the router will just ignore button presses, if there is -no history to navigate to. - -Also, when using [`WebHistory`], the history buttons might -navigate a user to a history entry outside your app. diff --git a/docs/router/src/reference/history-providers.md b/docs/router/src/reference/history-providers.md deleted file mode 100644 index 6ee11b20f..000000000 --- a/docs/router/src/reference/history-providers.md +++ /dev/null @@ -1,20 +0,0 @@ -# History Providers - -[`HistoryProvider`]s are used by the router to keep track of the navigation history -and update any external state (e.g. the browser's URL). - -The router provides two [`HistoryProvider`]s, but you can also create your own. -The two default implementations are: - -- The [`MemoryHistory`] is a custom implementation that works in memory. -- The [`WebHistory`] integrates with the browser's URL. - -By default, the router uses the [`MemoryHistory`]. It might be changed to use -[`WebHistory`] when the `web` feature is active, but that is not guaranteed. - -You can override the default history: - -```rust, no_run -{{#include ../../examples/history_provider.rs:app}} -``` - diff --git a/docs/router/src/reference/index.md b/docs/router/src/reference/index.md deleted file mode 100644 index add681671..000000000 --- a/docs/router/src/reference/index.md +++ /dev/null @@ -1,23 +0,0 @@ -# Adding the Router to Your Application - -In this chapter, we will learn how to add the router to our app. By itself, this -is not very useful. However, it is a prerequisite for all the functionality -described in the other chapters. - -> Make sure you added the `dioxus-router` dependency as explained in the -> [introduction](../index.md). - -In most cases, we want to add the router to the root component of our app. This -way, we can ensure that we have access to all its functionality everywhere. - -First, we define the router with the router macro: - -```rust, no_run -{{#include ../../examples/first_route.rs:router}} -``` - -Then we render the router with the [`Router`] component. - -```rust, no_run -{{#include ../../examples/first_route.rs:app}} -``` diff --git a/docs/router/src/reference/layouts.md b/docs/router/src/reference/layouts.md deleted file mode 100644 index 525838fb0..000000000 --- a/docs/router/src/reference/layouts.md +++ /dev/null @@ -1,19 +0,0 @@ -# Layouts - -Layouts allow you to wrap all child routes in a component. This can be useful when creating something like a header that will be used in many different routes. - -[`Outlet`] tells the router where to render content in layouts. In the following example, -the Index will be rendered within the [`Outlet`]. - -```rust, no_run -{{#include ../../examples/outlet.rs:outlet}} -``` - -The example above will output the following HTML (line breaks added for -readability): - -```html -
header
-

Index

-
footer
-``` diff --git a/docs/router/src/reference/navigation/index.md b/docs/router/src/reference/navigation/index.md deleted file mode 100644 index 2abf8477e..000000000 --- a/docs/router/src/reference/navigation/index.md +++ /dev/null @@ -1,39 +0,0 @@ -# Links & Navigation - -When we split our app into pages, we need to provide our users with a way to -navigate between them. On regular web pages, we'd use an anchor element for that, -like this: - -```html -
Link to an other page -``` - -However, we cannot do that when using the router for three reasons: - -1. Anchor tags make the browser load a new page from the server. This takes a - lot of time, and it is much faster to let the router handle the navigation - client-side. -2. Navigation using anchor tags only works when the app is running inside a - browser. This means we cannot use them inside apps using Dioxus Desktop. -3. Anchor tags cannot check if the target page exists. This means we cannot - prevent accidentally linking to non-existent pages. - -To solve these problems, the router provides us with a [`Link`] component we can -use like this: - -```rust, no_run -{{#include ../../../examples/links.rs:nav}} -``` - -The `target` in the example above is similar to the `href` of a regular anchor -element. However, it tells the router more about what kind of navigation it -should perform. It accepts something that can be converted into a -[`NavigationTarget`]: - -- The example uses a Internal route. This is the most common type of navigation. - It tells the router to navigate to a page within our app by passing a variant of a [`Routable`] enum. This type of navigation can never fail if the link component is used inside a router component. -- [`External`] allows us to navigate to URLs outside of our app. This is useful - for links to external websites. NavigationTarget::External accepts an URL to navigate to. This type of navigation can fail if the URL is invalid. - -> The [`Link`] accepts several props that modify its behavior. See the API docs -> for more details. diff --git a/docs/router/src/reference/navigation/programmatic.md b/docs/router/src/reference/navigation/programmatic.md deleted file mode 100644 index 894dd968e..000000000 --- a/docs/router/src/reference/navigation/programmatic.md +++ /dev/null @@ -1,32 +0,0 @@ -# Programmatic Navigation - -Sometimes we want our application to navigate to another page without having the -user click on a link. This is called programmatic navigation. - -## Using a Navigator - -We can get a navigator with the [`use_navigator`] hook. This hook returns a [`Navigator`]. - -We can use the [`Navigator`] to trigger four different kinds of navigation: - -- `push` will navigate to the target. It works like a regular anchor tag. -- `replace` works like `push`, except that it replaces the current history entry - instead of adding a new one. This means the prior page cannot be restored with the browser's back button. -- `Go back` works like the browser's back button. -- `Go forward` works like the browser's forward button. - -```rust, no_run -{{#include ../../../examples/navigator.rs:nav}} -``` - -You might have noticed that, like [`Link`], the [`Navigator`]s `push` and -`replace` functions take a [`NavigationTarget`]. This means we can use either -[`Internal`], or [`External`] targets. - -## External Navigation Targets - -Unlike a [`Link`], the [`Navigator`] cannot rely on the browser (or webview) to -handle navigation to external targets via a generated anchor element. - -This means, that under certain conditions, navigation to external targets can -fail. diff --git a/docs/router/src/reference/redirects.md b/docs/router/src/reference/redirects.md deleted file mode 100644 index 70ea4d7cd..000000000 --- a/docs/router/src/reference/redirects.md +++ /dev/null @@ -1,13 +0,0 @@ -# Redirects - -In some cases, we may want to redirect our users to another page whenever they -open a specific path. We can tell the router to do this with the `#[redirect]` -attribute. - -The `#[redirect]` attribute accepts a route and a closure with all of the parameters defined in the route. The closure must return a [`NavigationTarget`]. - -In the following example, we will redirect everybody from `/myblog` and `/myblog/:id` to `/blog` and `/blog/:id` respectively - -```rust, no_run -{{#include ../../examples/full_example.rs:router}} -``` diff --git a/docs/router/src/reference/routes/index.md b/docs/router/src/reference/routes/index.md deleted file mode 100644 index 7cd0fe9e5..000000000 --- a/docs/router/src/reference/routes/index.md +++ /dev/null @@ -1,65 +0,0 @@ -# Defining Routes - -When creating a [`Routable`] enum, we can define routes for our application using the `route("path")` attribute. - -## Route Segments - -Each route is made up of segments. Most segments are separated by `/` characters in the path. - -There are four fundamental types of segments: - -1. [Static segments](#static-segments) are fixed strings that must be present in the path. -2. [Dynamic segments](#dynamic-segments) are types that can be parsed from a segment. -3. [Catch-all segments](#catch-all-segments) are types that can be parsed from multiple segments. -4. [Query segments](#query-segments) are types that can be parsed from the query string. - -Routes are matched: - -- First, from most specific to least specific (Static then Dynamic then Catch All) (Query is always matched) -- Then, if multiple routes match the same path, the order in which they are defined in the enum is followed. - -## Static segments - -Fixed routes match a specific path. For example, the route `#[route("/about")]` will match the path `/about`. - -```rust, no_run -{{#include ../../../examples/static_segments.rs:route}} -``` - -## Dynamic Segments - -Dynamic segments are in the form of `:name` where `name` is -the name of the field in the route variant. If the segment is parsed -successfully then the route matches, otherwise the matching continues. - -The segment can be of any type that implements `FromStr`. - -```rust, no_run -{{#include ../../../examples/dynamic_segments.rs:route}} -``` - -## Catch All Segments - -Catch All segments are in the form of `:...name` where `name` is the name of the field in the route variant. If the segments are parsed successfully then the route matches, otherwise the matching continues. - -The segment can be of any type that implements `FromSegments`. (Vec implements this by default) - -Catch All segments must be the _last route segment_ in the path (query segments are not counted) and cannot be included in nests. - -```rust, no_run -{{#include ../../../examples/catch_all_segments.rs:route}} -``` - -## Query Segments - -Query segments are in the form of `?:name` where `name` is the name of the field in the route variant. - -Unlike [Dynamic Segments](#dynamic-segments) and [Catch All Segments](#catch-all-segments), parsing a Query segment must not fail. - -The segment can be of any type that implements `FromQuery`. - -Query segments must be the _after all route segments_ and cannot be included in nests. - -```rust, no_run -{{#include ../../../examples/query_segments.rs:route}} -``` diff --git a/docs/router/src/reference/routes/nested.md b/docs/router/src/reference/routes/nested.md deleted file mode 100644 index 4860fbb0d..000000000 --- a/docs/router/src/reference/routes/nested.md +++ /dev/null @@ -1,39 +0,0 @@ -# Nested Routes - -When developing bigger applications we often want to nest routes within each -other. As an example, we might want to organize a settings menu using this -pattern: - -```plain -└ Settings - ├ General Settings (displayed when opening the settings) - ├ Change Password - └ Privacy Settings -``` - -We might want to map this structure to these paths and components: - -```plain -/settings -> Settings { GeneralSettings } -/settings/password -> Settings { PWSettings } -/settings/privacy -> Settings { PrivacySettings } -``` - -Nested routes allow us to do this without repeating /settings in every route. - -## Nesting - -To nest routes, we use the `#[nest("path")]` and `#[end_nest]` attributes. - -The path in nest must not: - -1. Contain a [Catch All Segment](index.md#catch-all-segments) -2. Contain a [Query Segment](index.md#query-segments) - -If you define a dynamic segment in a nest, it will be available to all child routes and layouts. - -To finish a nest, we use the `#[end_nest]` attribute or the end of the enum. - -```rust, no_run -{{#include ../../../examples/nest.rs:route}} -``` diff --git a/docs/router/src/reference/routing-update-callback.md b/docs/router/src/reference/routing-update-callback.md deleted file mode 100644 index f4fdb9a99..000000000 --- a/docs/router/src/reference/routing-update-callback.md +++ /dev/null @@ -1,25 +0,0 @@ -# Routing Update Callback - -In some cases, we might want to run custom code when the current route changes. -For this reason, the [`RouterConfig`] exposes an `on_update` field. - -## How does the callback behave? - -The `on_update` is called whenever the current routing information changes. It -is called after the router updated its internal state, but before dependent components and hooks are updated. - -If the callback returns a [`NavigationTarget`], the router will replace the -current location with the specified target. It will not call the -`on_update` again. - -If at any point the router encounters a -[navigation failure](./failures/index.md), it will go to the appropriate state -without calling the `on_update`. It doesn't matter if the invalid target -initiated the navigation, was found as a redirect target, or was returned by the -`on_update` itself. - -## Code Example - -```rust, no_run -{{#include ../../examples/routing_update.rs:router}} -``` diff --git a/docs/router/src/reference/static-generation.md b/docs/router/src/reference/static-generation.md deleted file mode 100644 index c43f9fe4b..000000000 --- a/docs/router/src/reference/static-generation.md +++ /dev/null @@ -1,15 +0,0 @@ -# Static Generation - -## Getting the Sitemap - -The [`Routable`] trait includes an associated [`SITE_MAP`] constant that contains the map of all of the routes in the enum. - -By default, the sitemap is a tree of (static or dynamic) RouteTypes, but it can be flattened into a list of individual routes with the `.flatten()` method. - -## Generating a Sitemap - -To statically render pages, we need to flatten the route tree and generate a file for each route that contains only static segments: - -```rust, no_run -{{#include ../../../../packages/router/examples/static_generation.rs}} -``` diff --git a/examples/crm.rs b/examples/crm.rs index f3da8ab7a..d2cd98118 100644 --- a/examples/crm.rs +++ b/examples/crm.rs @@ -1,5 +1,4 @@ //! Tiny CRM: A port of the Yew CRM example to Dioxus. -#![allow(non_snake_case)] use dioxus::prelude::*; use dioxus_router::prelude::*; @@ -27,6 +26,7 @@ pub struct Client { type ClientContext = Vec; +#[component] fn App(cx: Scope) -> Element { use_shared_state_provider::(cx, Default::default); @@ -50,7 +50,7 @@ fn App(cx: Scope) -> Element { } } -#[inline_props] +#[component] fn ClientList(cx: Scope) -> Element { let clients = use_shared_state::(cx).unwrap(); @@ -80,7 +80,7 @@ fn ClientList(cx: Scope) -> Element { }) } -#[inline_props] +#[component] fn ClientAdd(cx: Scope) -> Element { let clients = use_shared_state::(cx).unwrap(); let first_name = use_state(cx, String::new); @@ -173,7 +173,7 @@ fn ClientAdd(cx: Scope) -> Element { }) } -#[inline_props] +#[component] fn Settings(cx: Scope) -> Element { let clients = use_shared_state::(cx).unwrap(); diff --git a/examples/dog_app.rs b/examples/dog_app.rs index 243e4bbca..66a3c615c 100644 --- a/examples/dog_app.rs +++ b/examples/dog_app.rs @@ -2,7 +2,7 @@ use dioxus::prelude::*; use std::collections::HashMap; fn main() { - dioxus_desktop::launch(|cx| render!(app_root {})); + dioxus_desktop::launch(|cx| render!(AppRoot {})); } #[derive(Debug, Clone, PartialEq, serde::Deserialize)] @@ -10,7 +10,8 @@ struct ListBreeds { message: HashMap>, } -fn app_root(cx: Scope<'_>) -> Element { +#[component] +fn AppRoot(cx: Scope<'_>) -> Element { let breed = use_state(cx, || "deerhound".to_string()); let breeds = use_future!(cx, || async move { @@ -36,7 +37,7 @@ fn app_root(cx: Scope<'_>) -> Element { } } } - div { flex: "50%", breed_pic { breed: breed.to_string() } } + div { flex: "50%", BreedPic { breed: breed.to_string() } } } } }), @@ -49,8 +50,8 @@ struct DogApi { message: String, } -#[inline_props] -fn breed_pic(cx: Scope, breed: String) -> Element { +#[component] +fn BreedPic(cx: Scope, breed: String) -> Element { let fut = use_future!(cx, |breed| async move { reqwest::get(format!("https://dog.ceo/api/breed/{breed}/images/random")) .await diff --git a/examples/error_handle.rs b/examples/error_handle.rs index b4a6dbb05..d1fb57933 100644 --- a/examples/error_handle.rs +++ b/examples/error_handle.rs @@ -1,10 +1,11 @@ use dioxus::prelude::*; fn main() { - dioxus_desktop::launch(app); + dioxus_desktop::launch(App); } -fn app(cx: Scope) -> Element { +#[component] +fn App(cx: Scope) -> Element { let val = use_state(cx, || "0.0001"); let num = match val.parse::() { @@ -19,13 +20,13 @@ fn app(cx: Scope) -> Element { "Set an invalid number" } (0..5).map(|i| rsx! { - demo_c { x: i } + DemoC { x: i } }) }) } -#[inline_props] -fn demo_c(cx: Scope, x: i32) -> Element { +#[component] +fn DemoC(cx: Scope, x: i32) -> Element { cx.render(rsx! { h1 { "asdasdasdasd {x}" diff --git a/examples/flat_router.rs b/examples/flat_router.rs index b8e3d6425..ec6e2f417 100644 --- a/examples/flat_router.rs +++ b/examples/flat_router.rs @@ -1,5 +1,3 @@ -#![allow(non_snake_case)] - use dioxus::prelude::*; use dioxus_desktop::{tao::dpi::LogicalSize, Config, WindowBuilder}; use dioxus_router::prelude::*; @@ -13,10 +11,11 @@ fn main() { .with_resizable(false), ); - dioxus_desktop::launch_cfg(app, cfg) + dioxus_desktop::launch_cfg(App, cfg) } -fn app(cx: Scope) -> Element { +#[component] +fn App(cx: Scope) -> Element { render! { Router:: {} } @@ -36,7 +35,7 @@ enum Route { Settings {}, } -#[inline_props] +#[component] fn Footer(cx: Scope) -> Element { render! { div { @@ -58,22 +57,22 @@ fn Footer(cx: Scope) -> Element { } } -#[inline_props] +#[component] fn Home(cx: Scope) -> Element { render!("Home") } -#[inline_props] +#[component] fn Games(cx: Scope) -> Element { render!("Games") } -#[inline_props] +#[component] fn Play(cx: Scope) -> Element { render!("Play") } -#[inline_props] +#[component] fn Settings(cx: Scope) -> Element { render!("Settings") } diff --git a/examples/inlineprops.rs b/examples/inlineprops.rs index 8c626d346..6d5534064 100644 --- a/examples/inlineprops.rs +++ b/examples/inlineprops.rs @@ -1,33 +1,35 @@ -//! Run with `cargo-expand` to see what each one expands to -#![allow(non_snake_case)] - +//! Run with `cargo-expand` to see what each one expands to. +//! This file is named `inlineprops.rs`, because there used to be a `#[inline_props]` macro to +//! do this. However, it's now deprecated (and will likely be removed in a future major version), +//! so please use `#[component]` instead! use dioxus::prelude::*; -#[inline_props] +#[component] fn Thing1(cx: Scope, _a: T) -> Element { cx.render(rsx! { "" }) } -#[inline_props] +#[component] fn Thing2(cx: Scope, _a: u32) -> Element<'a> { cx.render(rsx! { "" }) } -#[inline_props] +#[component] fn Thing3<'a, T>(cx: Scope<'a>, _a: &'a T) -> Element<'a> { cx.render(rsx! { "" }) } -#[inline_props] +#[component] fn Thing4<'a>(cx: Scope<'a>, _a: &'a u32) -> Element<'a> { cx.render(rsx! { "" }) } fn main() { - dioxus_desktop::launch(app); + dioxus_desktop::launch(App); } -fn app(cx: Scope) -> Element { +#[component] +fn App(cx: Scope) -> Element { let state = use_state(cx, || 1); cx.render(rsx! { diff --git a/examples/link.rs b/examples/link.rs index c66b1abd1..726fe3d79 100644 --- a/examples/link.rs +++ b/examples/link.rs @@ -1,13 +1,12 @@ -#![allow(non_snake_case)] - use dioxus::prelude::*; use dioxus_router::prelude::*; fn main() { - dioxus_desktop::launch(app); + dioxus_desktop::launch(App); } -fn app(cx: Scope) -> Element { +#[component] +fn App(cx: Scope) -> Element { cx.render(rsx! ( div { p { @@ -38,7 +37,7 @@ enum Route { Settings {}, } -#[inline_props] +#[component] fn Header(cx: Scope) -> Element { render! { h1 { "Your app here" } @@ -50,12 +49,12 @@ fn Header(cx: Scope) -> Element { } } -#[inline_props] +#[component] fn Home(cx: Scope) -> Element { render!(h1 { "Home" }) } -#[inline_props] +#[component] fn Settings(cx: Scope) -> Element { render!(h1 { "Settings" }) } diff --git a/examples/query_segments_demo/src/main.rs b/examples/query_segments_demo/src/main.rs index 2348f1fe5..d9f5f83ef 100644 --- a/examples/query_segments_demo/src/main.rs +++ b/examples/query_segments_demo/src/main.rs @@ -1,4 +1,4 @@ -#![allow(non_snake_case, unused)] +#![allow(unused)] //! Example: Url query segments usage //! ------------------------------------ //! @@ -56,7 +56,7 @@ impl FromQuery for BlogQuerySegments { } } -#[inline_props] +#[component] fn BlogPost(cx: Scope, query_params: BlogQuerySegments) -> Element { render! { div{"This is your blogpost with a query segment:"} @@ -64,6 +64,7 @@ fn BlogPost(cx: Scope, query_params: BlogQuerySegments) -> Element { } } +#[component] fn App(cx: Scope) -> Element { render! { Router::{} } } diff --git a/examples/router.rs b/examples/router.rs index ed7fbefa4..d00c747b9 100644 --- a/examples/router.rs +++ b/examples/router.rs @@ -1,5 +1,3 @@ -#![allow(non_snake_case)] - use dioxus::prelude::*; use dioxus_router::prelude::*; @@ -37,12 +35,14 @@ enum Route { } // ANCHOR_END: router +#[component] fn App(cx: Scope) -> Element { render! { Router:: {} } } +#[component] fn NavBar(cx: Scope) -> Element { render! { nav { @@ -55,12 +55,14 @@ fn NavBar(cx: Scope) -> Element { } } +#[component] fn Home(cx: Scope) -> Element { render! { h1 { "Welcome to the Dioxus Blog!" } } } +#[component] fn Blog(cx: Scope) -> Element { render! { h1 { "Blog" } @@ -68,6 +70,7 @@ fn Blog(cx: Scope) -> Element { } } +#[component] fn BlogList(cx: Scope) -> Element { render! { h2 { "Choose a post" } @@ -88,14 +91,14 @@ fn BlogList(cx: Scope) -> Element { } } -#[inline_props] +#[component] fn BlogPost(cx: Scope, name: String) -> Element { render! { h2 { "Blog Post: {name}"} } } -#[inline_props] +#[component] fn PageNotFound(cx: Scope, route: Vec) -> Element { render! { h1 { "Page not found" } diff --git a/examples/rsx_usage.rs b/examples/rsx_usage.rs index d5e2fcdb3..f9ecb4939 100644 --- a/examples/rsx_usage.rs +++ b/examples/rsx_usage.rs @@ -1,4 +1,3 @@ -#![allow(non_snake_case)] //! A tour of the rsx! macro //! ------------------------ //! @@ -40,7 +39,7 @@ //! - Allow top-level fragments fn main() { - dioxus_desktop::launch(app); + dioxus_desktop::launch(App); } use core::{fmt, str::FromStr}; @@ -49,7 +48,8 @@ use std::fmt::Display; use baller::Baller; use dioxus::prelude::*; -fn app(cx: Scope) -> Element { +#[component] +fn App(cx: Scope) -> Element { let formatting = "formatting!"; let formatting_tuple = ("a", "b"); let lazy_fmt = format_args!("lazily formatted text"); @@ -217,12 +217,16 @@ fn format_dollars(dollars: u32, cents: u32) -> String { format!("${dollars}.{cents:02}") } -fn helper<'a>(cx: &'a ScopeState, text: &str) -> Element<'a> { +fn helper<'a>(cx: &'a ScopeState, text: &'a str) -> Element<'a> { cx.render(rsx! { p { "{text}" } }) } +// no_case_check disables PascalCase checking if you *really* want a snake_case component. +// This will likely be deprecated/removed in a future update that will introduce a more polished linting system, +// something like Clippy. +#[component(no_case_check)] fn lowercase_helper(cx: Scope) -> Element { cx.render(rsx! { "asd" @@ -234,12 +238,16 @@ mod baller { #[derive(Props, PartialEq, Eq)] pub struct BallerProps {} - #[allow(non_snake_case)] + #[component] /// This component totally balls - pub fn Baller(_: Scope) -> Element { + pub fn Baller(_cx: Scope) -> Element { todo!() } + // no_case_check disables PascalCase checking if you *really* want a snake_case component. + // This will likely be deprecated/removed in a future update that will introduce a more polished linting system, + // something like Clippy. + #[component(no_case_check)] pub fn lowercase_component(cx: Scope) -> Element { cx.render(rsx! { "look ma, no uppercase" }) } @@ -253,7 +261,7 @@ pub struct TallerProps<'a> { } /// Documention for this component is visible within the rsx macro -#[allow(non_snake_case)] +#[component] pub fn Taller<'a>(cx: Scope<'a, TallerProps<'a>>) -> Element { cx.render(rsx! { &cx.props.children @@ -275,15 +283,14 @@ where todo!() } -#[inline_props] +#[component] fn WithInline<'a>(cx: Scope<'a>, text: &'a str) -> Element { cx.render(rsx! { p { "{text}" } }) } -// generic component with inline_props too -#[inline_props] +#[component] fn Label(cx: Scope, text: T) -> Element where T: Display, diff --git a/examples/shared_state.rs b/examples/shared_state.rs index d129f75d1..37271f160 100644 --- a/examples/shared_state.rs +++ b/examples/shared_state.rs @@ -1,5 +1,3 @@ -#![allow(non_snake_case)] - use std::collections::HashMap; use dioxus::prelude::*; @@ -27,6 +25,7 @@ impl CoolData { } } +#[component] #[rustfmt::skip] pub fn App(cx: Scope) -> Element { use_shared_state_provider(cx, || CoolData::new(HashMap::from([ @@ -50,7 +49,7 @@ pub fn App(cx: Scope) -> Element { ) } -#[inline_props] +#[component] fn DataEditor(cx: Scope, id: usize) -> Element { let cool_data = use_shared_state::(cx).unwrap().read(); @@ -61,7 +60,7 @@ fn DataEditor(cx: Scope, id: usize) -> Element { }) } -#[inline_props] +#[component] fn DataView(cx: Scope, id: usize) -> Element { let cool_data = use_shared_state::(cx).unwrap(); diff --git a/examples/simple_desktop.rs b/examples/simple_desktop.rs index 374b58a4e..4eac5e3a9 100644 --- a/examples/simple_desktop.rs +++ b/examples/simple_desktop.rs @@ -9,10 +9,11 @@ fn main() { .with_module_level("dioxus", log::LevelFilter::Trace) .init() .unwrap(); - dioxus_desktop::launch(app); + dioxus_desktop::launch(App); } -fn app(cx: Scope) -> Element { +#[component] +fn App(cx: Scope) -> Element { render! { Router:: {} } @@ -36,7 +37,7 @@ enum Route { Oranges {}, } -#[inline_props] +#[component] fn NavBar(cx: Scope) -> Element { render! { h1 { "Your app here" } @@ -51,19 +52,19 @@ fn NavBar(cx: Scope) -> Element { } } -#[inline_props] +#[component] fn Home(cx: Scope) -> Element { log::debug!("rendering home {:?}", cx.scope_id()); render! { h1 { "Home" } } } -#[inline_props] +#[component] fn BlogList(cx: Scope) -> Element { log::debug!("rendering blog list {:?}", cx.scope_id()); render! { div { "Blog List" } } } -#[inline_props] +#[component] fn BlogPost(cx: Scope, post: String) -> Element { log::debug!("rendering blog post {}", post); @@ -75,7 +76,7 @@ fn BlogPost(cx: Scope, post: String) -> Element { } } -#[inline_props] +#[component] fn Oranges(cx: Scope) -> Element { render!("Oranges are not apples!") } diff --git a/examples/simple_router.rs b/examples/simple_router.rs index 0604558a1..7ed55885e 100644 --- a/examples/simple_router.rs +++ b/examples/simple_router.rs @@ -12,12 +12,12 @@ enum Route { Blog { id: String }, } -#[inline_props] +#[component] fn Homepage(cx: Scope) -> Element { render! { h1 { "Welcome home" } } } -#[inline_props] +#[component] fn Blog(cx: Scope, id: String) -> Element { render! { h1 { "How to make: " } @@ -25,7 +25,7 @@ fn Blog(cx: Scope, id: String) -> Element { } } -#[inline_props] +#[component] fn Nav(cx: Scope) -> Element { render! { nav { diff --git a/packages/autofmt/README.md b/packages/autofmt/README.md index bd934f2c7..0b13dc7a9 100644 --- a/packages/autofmt/README.md +++ b/packages/autofmt/README.md @@ -1,6 +1,5 @@ # dioxus-autofmt - [![Crates.io][crates-badge]][crates-url] [![MIT licensed][mit-badge]][mit-url] [![Build Status][actions-badge]][actions-url] @@ -8,38 +7,33 @@ [crates-badge]: https://img.shields.io/crates/v/dioxus-autofmt.svg [crates-url]: https://crates.io/crates/dioxus-autofmt - [mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg [mit-url]: https://github.com/dioxuslabs/dioxus/blob/master/LICENSE - [actions-badge]: https://github.com/dioxuslabs/dioxus/actions/workflows/main.yml/badge.svg [actions-url]: https://github.com/dioxuslabs/dioxus/actions?query=workflow%3ACI+branch%3Amaster - [discord-badge]: https://img.shields.io/discord/899851952891002890.svg?logo=discord&style=flat-square [discord-url]: https://discord.gg/XgGxMSkvUM [Website](https://dioxuslabs.com) | -[Guides](https://dioxuslabs.com/docs/0.3/guide/en/) | +[Guides](https://dioxuslabs.com/learn/0.4/) | [API Docs](https://docs.rs/dioxus-autofmt/latest/dioxus_autofmt) | [Chat](https://discord.gg/XgGxMSkvUM) - ## Overview `dioxus-autofmt` provides a pretty printer for the `rsx` syntax tree. - This is done manually with a via set of formatting rules. The output is not guaranteed to be stable between minor versions of the crate as we might tweak the output. `dioxus-autofmt` provides an API to perform precision edits as well as just spit out a block of formatted RSX from any RSX syntax tree. This is used by the `rsx-rosetta` crate which can accept various input languages and output valid RSX. - ## Contributing - Report issues on our [issue tracker](https://github.com/dioxuslabs/dioxus/issues). - Join the discord and ask questions! ## License + This project is licensed under the [MIT license]. [mit license]: https://github.com/DioxusLabs/dioxus/blob/master/LICENSE-MIT diff --git a/packages/autofmt/tests/samples/long.rsx b/packages/autofmt/tests/samples/long.rsx index c5ace9cc3..1bda8a006 100644 --- a/packages/autofmt/tests/samples/long.rsx +++ b/packages/autofmt/tests/samples/long.rsx @@ -1,6 +1,6 @@ use dioxus::prelude::*; -#[inline_props] +#[component] pub fn Explainer<'a>( cx: Scope<'a>, invert: bool, diff --git a/packages/check/README.md b/packages/check/README.md index 512eb579a..0bb6ce0a4 100644 --- a/packages/check/README.md +++ b/packages/check/README.md @@ -1,6 +1,5 @@ # dioxus-check - [![Crates.io][crates-badge]][crates-url] [![MIT licensed][mit-badge]][mit-url] [![Build Status][actions-badge]][actions-url] @@ -8,25 +7,21 @@ [crates-badge]: https://img.shields.io/crates/v/dioxus-autofmt.svg [crates-url]: https://crates.io/crates/dioxus-autofmt - [mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg [mit-url]: https://github.com/dioxuslabs/dioxus/blob/master/LICENSE - [actions-badge]: https://github.com/dioxuslabs/dioxus/actions/workflows/main.yml/badge.svg [actions-url]: https://github.com/dioxuslabs/dioxus/actions?query=workflow%3ACI+branch%3Amaster - [discord-badge]: https://img.shields.io/discord/899851952891002890.svg?logo=discord&style=flat-square [discord-url]: https://discord.gg/XgGxMSkvUM [Website](https://dioxuslabs.com) | -[Guides](https://dioxuslabs.com/docs/0.3/guide/en/) | +[Guides](https://dioxuslabs.com/learn/0.4/) | [API Docs](https://docs.rs/dioxus-autofmt/latest/dioxus_autofmt) | [Chat](https://discord.gg/XgGxMSkvUM) - ## Overview -`dioxus-check` analyzes Dioxus source code and reports errors and warnings. Primarily, it enforces the [Rules of Hooks](https://dioxuslabs.com/docs/0.3/guide/en/interactivity/hooks.html#no-hooks-in-conditionals). +`dioxus-check` analyzes Dioxus source code and reports errors and warnings. Primarily, it enforces the [Rules of Hooks](https://dioxuslabs.com/learn/0.4/reference/hooks#rules-of-hooks). ## Contributing @@ -34,6 +29,7 @@ - Join the discord and ask questions! ## License + This project is licensed under the [MIT license]. [mit license]: https://github.com/DioxusLabs/dioxus/blob/master/LICENSE-MIT diff --git a/packages/check/src/issues.rs b/packages/check/src/issues.rs index 9893cde25..34d20eaef 100644 --- a/packages/check/src/issues.rs +++ b/packages/check/src/issues.rs @@ -158,11 +158,11 @@ impl Display for IssueReport { #[allow(clippy::enum_variant_names)] // we'll add non-hook ones in the future /// Issues that might be found via static analysis of a Dioxus file. pub enum Issue { - /// https://dioxuslabs.com/docs/0.3/guide/en/interactivity/hooks.html#no-hooks-in-conditionals + /// https://dioxuslabs.com/learn/0.4/reference/hooks#no-hooks-in-conditionals HookInsideConditional(HookInfo, ConditionalInfo), - /// https://dioxuslabs.com/docs/0.3/guide/en/interactivity/hooks.html#no-hooks-in-loops + /// https://dioxuslabs.com/learn/0.4/reference/hooks#no-hooks-in-loops HookInsideLoop(HookInfo, AnyLoopInfo), - /// https://dioxuslabs.com/docs/0.3/guide/en/interactivity/hooks.html#no-hooks-in-closures + /// https://dioxuslabs.com/learn/0.4/reference/hooks#no-hooks-in-closures HookInsideClosure(HookInfo, ClosureInfo), HookOutsideComponent(HookInfo), } diff --git a/packages/cli/src/server/desktop/mod.rs b/packages/cli/src/server/desktop/mod.rs index 7c38fd674..e6ad8c7ff 100644 --- a/packages/cli/src/server/desktop/mod.rs +++ b/packages/cli/src/server/desktop/mod.rs @@ -1,12 +1,12 @@ +use crate::server::Platform; use crate::{ cfg::ConfigOptsServe, server::{ output::{print_console_info, PrettierOptions}, - setup_file_watcher, setup_file_watcher_hot_reload, + setup_file_watcher, }, BuildResult, CrateConfig, Result, }; - use dioxus_hot_reload::HotReloadMsg; use dioxus_html::HtmlCtx; use dioxus_rsx::hot_reload::*; @@ -20,7 +20,7 @@ use tokio::sync::broadcast::{self}; #[cfg(feature = "plugin")] use plugin::PluginManager; -use super::Platform; +use super::HotReloadState; pub async fn startup(config: CrateConfig, serve: &ConfigOptsServe) -> Result<()> { startup_with_platform::(config, serve).await @@ -28,7 +28,7 @@ pub async fn startup(config: CrateConfig, serve: &ConfigOptsServe) -> Result<()> pub(crate) async fn startup_with_platform( config: CrateConfig, - serve: &ConfigOptsServe, + serve_cfg: &ConfigOptsServe, ) -> Result<()> { // ctrl-c shutdown checker let _crate_config = config.clone(); @@ -38,18 +38,39 @@ pub(crate) async fn startup_with_platform( std::process::exit(0); }); - match config.hot_reload { - true => serve_hot_reload::

(config, serve).await?, - false => serve_default::

(config, serve).await?, - } + let hot_reload_state = match config.hot_reload { + true => { + let FileMapBuildResult { map, errors } = + FileMap::::create(config.crate_dir.clone()).unwrap(); + + for err in errors { + log::error!("{}", err); + } + + let file_map = Arc::new(Mutex::new(map)); + + let hot_reload_tx = broadcast::channel(100).0; + + clear_paths(); + + Some(HotReloadState { + messages: hot_reload_tx.clone(), + file_map: file_map.clone(), + }) + } + false => None, + }; + + serve::

(config, serve_cfg, hot_reload_state).await?; Ok(()) } /// Start the server without hot reload -async fn serve_default( +async fn serve( config: CrateConfig, serve: &ConfigOptsServe, + hot_reload_state: Option, ) -> Result<()> { let platform = RwLock::new(P::start(&config, serve)?); @@ -65,68 +86,34 @@ async fn serve_default( }, &config, None, + hot_reload_state.clone(), ) .await?; - std::future::pending::<()>().await; + match &hot_reload_state { + Some(hot_reload_state) => { + // The open interprocess sockets + start_desktop_hot_reload(hot_reload_state).await?; + } + None => { + std::future::pending::<()>().await; + } + } Ok(()) } -/// Start dx serve with hot reload -async fn serve_hot_reload( - config: CrateConfig, - serve: &ConfigOptsServe, -) -> Result<()> { - let platform = RwLock::new(P::start(&config, serve)?); - - // Setup hot reload - let FileMapBuildResult { map, errors } = - FileMap::::create(config.crate_dir.clone()).unwrap(); - - for err in errors { - log::error!("{}", err); - } - - let file_map = Arc::new(Mutex::new(map)); - - let (hot_reload_tx, mut hot_reload_rx) = broadcast::channel(100); - - // States - // The open interprocess sockets - let channels = Arc::new(Mutex::new(Vec::new())); - - // Setup file watcher - // We got to own watcher so that it exists for the duration of serve - // Otherwise hot reload won't work. - let _watcher = setup_file_watcher_hot_reload( - &config, - hot_reload_tx, - file_map.clone(), - { - let config = config.clone(); - - let channels = channels.clone(); - move || { - for channel in &mut *channels.lock().unwrap() { - send_msg(HotReloadMsg::Shutdown, channel); - } - platform.write().unwrap().rebuild(&config) - } - }, - None, - ) - .await?; - - clear_paths(); - +async fn start_desktop_hot_reload(hot_reload_state: &HotReloadState) -> Result<()> { match LocalSocketListener::bind("@dioxusin") { Ok(local_socket_stream) => { let aborted = Arc::new(Mutex::new(false)); + // States + // The open interprocess sockets + let channels = Arc::new(Mutex::new(Vec::new())); // listen for connections std::thread::spawn({ - let file_map = file_map.clone(); + let file_map = hot_reload_state.file_map.clone(); let channels = channels.clone(); let aborted = aborted.clone(); let _ = local_socket_stream.set_nonblocking(true); @@ -161,6 +148,8 @@ async fn serve_hot_reload( } }); + let mut hot_reload_rx = hot_reload_state.messages.subscribe(); + while let Ok(template) = hot_reload_rx.recv().await { let channels = &mut *channels.lock().unwrap(); let mut i = 0; diff --git a/packages/cli/src/server/mod.rs b/packages/cli/src/server/mod.rs index 1571a198e..8badab929 100644 --- a/packages/cli/src/server/mod.rs +++ b/packages/cli/src/server/mod.rs @@ -9,7 +9,7 @@ use std::{ path::PathBuf, sync::{Arc, Mutex}, }; -use tokio::sync::broadcast::Sender; +use tokio::sync::broadcast::{self}; mod output; use output::*; @@ -22,6 +22,7 @@ async fn setup_file_watcher Result + Send + 'static>( build_with: F, config: &CrateConfig, web_info: Option, + hot_reload: Option, ) -> Result { let mut last_update_time = chrono::Local::now().timestamp(); @@ -39,28 +40,81 @@ async fn setup_file_watcher Result + Send + 'static>( let config = watcher_config.clone(); if let Ok(e) = info { if chrono::Local::now().timestamp() > last_update_time { - match build_with() { - Ok(res) => { - last_update_time = chrono::Local::now().timestamp(); + let mut needs_full_rebuild; + if let Some(hot_reload) = &hot_reload { + // find changes to the rsx in the file + let mut rsx_file_map = hot_reload.file_map.lock().unwrap(); + let mut messages: Vec> = Vec::new(); - #[allow(clippy::redundant_clone)] - print_console_info( - &config, - PrettierOptions { - changed: e.paths.clone(), - warnings: res.warnings, - elapsed_time: res.elapsed_time, - }, - web_info.clone(), - ); + // In hot reload mode, we only need to rebuild if non-rsx code is changed + needs_full_rebuild = false; - #[cfg(feature = "plugin")] - let _ = PluginManager::on_serve_rebuild( - chrono::Local::now().timestamp(), - e.paths, - ); + for path in &e.paths { + // if this is not a rust file, rebuild the whole project + if path.extension().and_then(|p| p.to_str()) != Some("rs") { + needs_full_rebuild = true; + break; + } + + match rsx_file_map.update_rsx(path, &config.crate_dir) { + Ok(UpdateResult::UpdatedRsx(msgs)) => { + messages.extend(msgs); + needs_full_rebuild = false; + } + Ok(UpdateResult::NeedsRebuild) => { + needs_full_rebuild = true; + } + Err(err) => { + log::error!("{}", err); + } + } + } + + if needs_full_rebuild { + // Reset the file map to the new state of the project + let FileMapBuildResult { + map: new_file_map, + errors, + } = FileMap::::create(config.crate_dir.clone()).unwrap(); + + for err in errors { + log::error!("{}", err); + } + + *rsx_file_map = new_file_map; + } else { + for msg in messages { + let _ = hot_reload.messages.send(msg); + } + } + } else { + needs_full_rebuild = true; + } + + if needs_full_rebuild { + match build_with() { + Ok(res) => { + last_update_time = chrono::Local::now().timestamp(); + + #[allow(clippy::redundant_clone)] + print_console_info( + &config, + PrettierOptions { + changed: e.paths.clone(), + warnings: res.warnings, + elapsed_time: res.elapsed_time, + }, + web_info.clone(), + ); + + #[cfg(feature = "plugin")] + let _ = PluginManager::on_serve_rebuild( + chrono::Local::now().timestamp(), + e.paths, + ); + } + Err(e) => log::error!("{}", e), } - Err(e) => log::error!("{}", e), } } } @@ -78,113 +132,15 @@ async fn setup_file_watcher Result + Send + 'static>( Ok(watcher) } -// Todo: reduce duplication and merge with setup_file_watcher() -/// Sets up a file watcher with hot reload -async fn setup_file_watcher_hot_reload Result + Send + 'static>( - config: &CrateConfig, - hot_reload_tx: Sender>, - file_map: Arc>>, - build_with: F, - web_info: Option, -) -> Result { - // file watcher: check file change - let allow_watch_path = config - .dioxus_config - .web - .watcher - .watch_path - .clone() - .unwrap_or_else(|| vec![PathBuf::from("src")]); - - let watcher_config = config.clone(); - let mut last_update_time = chrono::Local::now().timestamp(); - - let mut watcher = RecommendedWatcher::new( - move |evt: notify::Result| { - let config = watcher_config.clone(); - // Give time for the change to take effect before reading the file - std::thread::sleep(std::time::Duration::from_millis(100)); - if chrono::Local::now().timestamp() > last_update_time { - if let Ok(evt) = evt { - let mut messages: Vec> = Vec::new(); - for path in evt.paths.clone() { - // if this is not a rust file, rebuild the whole project - if path.extension().and_then(|p| p.to_str()) != Some("rs") { - match build_with() { - Ok(res) => { - print_console_info( - &config, - PrettierOptions { - changed: evt.paths, - warnings: res.warnings, - elapsed_time: res.elapsed_time, - }, - web_info.clone(), - ); - } - Err(err) => { - log::error!("{}", err); - } - } - return; - } - // find changes to the rsx in the file - let mut map = file_map.lock().unwrap(); - - match map.update_rsx(&path, &config.crate_dir) { - Ok(UpdateResult::UpdatedRsx(msgs)) => { - messages.extend(msgs); - } - Ok(UpdateResult::NeedsRebuild) => { - match build_with() { - Ok(res) => { - print_console_info( - &config, - PrettierOptions { - changed: evt.paths, - warnings: res.warnings, - elapsed_time: res.elapsed_time, - }, - web_info.clone(), - ); - } - Err(err) => { - log::error!("{}", err); - } - } - return; - } - Err(err) => { - log::error!("{}", err); - } - } - } - for msg in messages { - let _ = hot_reload_tx.send(msg); - } - } - last_update_time = chrono::Local::now().timestamp(); - } - }, - notify::Config::default(), - ) - .unwrap(); - - for sub_path in allow_watch_path { - if let Err(err) = watcher.watch( - &config.crate_dir.join(&sub_path), - notify::RecursiveMode::Recursive, - ) { - log::error!("error watching {sub_path:?}: \n{}", err); - } - } - - Ok(watcher) -} - pub(crate) trait Platform { fn start(config: &CrateConfig, serve: &ConfigOptsServe) -> Result where Self: Sized; fn rebuild(&mut self, config: &CrateConfig) -> Result; } + +#[derive(Clone)] +pub struct HotReloadState { + pub messages: broadcast::Sender>, + pub file_map: Arc>>, +} diff --git a/packages/cli/src/server/web/hot_reload.rs b/packages/cli/src/server/web/hot_reload.rs index 49cce38d4..7b47dca4c 100644 --- a/packages/cli/src/server/web/hot_reload.rs +++ b/packages/cli/src/server/web/hot_reload.rs @@ -1,27 +1,15 @@ -use std::sync::{Arc, Mutex}; - use axum::{ extract::{ws::Message, WebSocketUpgrade}, response::IntoResponse, Extension, TypedHeader, }; -use dioxus_core::Template; -use dioxus_html::HtmlCtx; -use dioxus_rsx::hot_reload::FileMap; -use tokio::sync::broadcast; -use crate::CrateConfig; - -pub struct HotReloadState { - pub messages: broadcast::Sender>, - pub file_map: Arc>>, - pub watcher_config: CrateConfig, -} +use crate::server::HotReloadState; pub async fn hot_reload_handler( ws: WebSocketUpgrade, _: Option>, - Extension(state): Extension>, + Extension(state): Extension, ) -> impl IntoResponse { ws.on_upgrade(|mut socket| async move { log::info!("🔥 Hot Reload WebSocket connected"); diff --git a/packages/cli/src/server/web/mod.rs b/packages/cli/src/server/web/mod.rs index 297e252fa..1ed57fb96 100644 --- a/packages/cli/src/server/web/mod.rs +++ b/packages/cli/src/server/web/mod.rs @@ -3,7 +3,7 @@ use crate::{ serve::Serve, server::{ output::{print_console_info, PrettierOptions, WebServerInfo}, - setup_file_watcher, setup_file_watcher_hot_reload, + setup_file_watcher, HotReloadState, }, BuildResult, CrateConfig, Result, WebHttpsConfig, }; @@ -63,21 +63,48 @@ pub async fn startup( let ip = get_ip().unwrap_or(String::from("0.0.0.0")); - match config.hot_reload { - true => serve_hot_reload(ip, port, config, start_browser, skip_assets).await?, - false => serve_default(ip, port, config, start_browser, skip_assets).await?, - } + let hot_reload_state = match config.hot_reload { + true => { + let FileMapBuildResult { map, errors } = + FileMap::::create(config.crate_dir.clone()).unwrap(); + + for err in errors { + log::error!("{}", err); + } + + let file_map = Arc::new(Mutex::new(map)); + + let hot_reload_tx = broadcast::channel(100).0; + + Some(HotReloadState { + messages: hot_reload_tx.clone(), + file_map: file_map.clone(), + }) + } + false => None, + }; + + serve( + ip, + port, + config, + start_browser, + skip_assets, + hot_reload_state, + ) + .await?; Ok(()) } /// Start the server without hot reload -async fn serve_default( +pub async fn serve( ip: String, port: u16, config: CrateConfig, start_browser: bool, skip_assets: bool, + hot_reload_state: Option, ) -> Result<()> { let first_build_result = crate::builder::build(&config, false, skip_assets)?; @@ -99,6 +126,7 @@ async fn serve_default( ip: ip.clone(), port, }), + hot_reload_state.clone(), ) .await?; @@ -125,89 +153,7 @@ async fn serve_default( ); // Router - let router = setup_router(config, ws_reload_state, None).await?; - - // Start server - start_server(port, router, start_browser, rustls_config).await?; - - Ok(()) -} - -/// Start dx serve with hot reload -async fn serve_hot_reload( - ip: String, - port: u16, - config: CrateConfig, - start_browser: bool, - skip_assets: bool, -) -> Result<()> { - let first_build_result = crate::builder::build(&config, false, skip_assets)?; - - log::info!("🚀 Starting development server..."); - - // Setup hot reload - let (reload_tx, _) = broadcast::channel(100); - let FileMapBuildResult { map, errors } = - FileMap::::create(config.crate_dir.clone()).unwrap(); - - for err in errors { - log::error!("{}", err); - } - - let file_map = Arc::new(Mutex::new(map)); - - let hot_reload_tx = broadcast::channel(100).0; - - // States - let hot_reload_state = Arc::new(HotReloadState { - messages: hot_reload_tx.clone(), - file_map: file_map.clone(), - watcher_config: config.clone(), - }); - - let ws_reload_state = Arc::new(WsReloadState { - update: reload_tx.clone(), - }); - - // Setup file watcher - // We got to own watcher so that it exists for the duration of serve - // Otherwise hot reload won't work. - let _watcher = setup_file_watcher_hot_reload( - &config, - hot_reload_tx, - file_map, - { - let config = config.clone(); - let reload_tx = reload_tx.clone(); - move || build(&config, &reload_tx, skip_assets) - }, - Some(WebServerInfo { - ip: ip.clone(), - port, - }), - ) - .await?; - - // HTTPS - // Before console info so it can stop if mkcert isn't installed or fails - let rustls_config = get_rustls(&config).await?; - - // Print serve info - print_console_info( - &config, - PrettierOptions { - changed: vec![], - warnings: first_build_result.warnings, - elapsed_time: first_build_result.elapsed_time, - }, - Some(WebServerInfo { - ip: ip.clone(), - port, - }), - ); - - // Router - let router = setup_router(config, ws_reload_state, Some(hot_reload_state)).await?; + let router = setup_router(config, ws_reload_state, hot_reload_state).await?; // Start server start_server(port, router, start_browser, rustls_config).await?; @@ -298,7 +244,7 @@ fn get_rustls_without_mkcert(web_config: &WebHttpsConfig) -> Result<(String, Str async fn setup_router( config: CrateConfig, ws_reload: Arc, - hot_reload: Option>, + hot_reload: Option, ) -> Result { // Setup cors let cors = CorsLayer::new() diff --git a/packages/core-macro/Cargo.toml b/packages/core-macro/Cargo.toml index f3d6f6b3b..d928d5fec 100644 --- a/packages/core-macro/Cargo.toml +++ b/packages/core-macro/Cargo.toml @@ -17,6 +17,8 @@ proc-macro2 = { version = "1.0" } quote = "1.0" syn = { version = "2.0", features = ["full", "extra-traits"] } dioxus-rsx = { workspace = true } +dioxus-core = { workspace = true } +constcat = "0.3.0" # testing [dev-dependencies] diff --git a/packages/core-macro/README.md b/packages/core-macro/README.md index bcf1572cf..31b0cca90 100644 --- a/packages/core-macro/README.md +++ b/packages/core-macro/README.md @@ -1,6 +1,5 @@ # dioxus-core-macro - [![Crates.io][crates-badge]][crates-url] [![MIT licensed][mit-badge]][mit-url] [![Build Status][actions-badge]][actions-url] @@ -8,22 +7,18 @@ [crates-badge]: https://img.shields.io/crates/v/dioxus-core-macro.svg [crates-url]: https://crates.io/crates/dioxus-core-macro - [mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg [mit-url]: https://github.com/dioxuslabs/dioxus/blob/master/LICENSE - [actions-badge]: https://github.com/dioxuslabs/dioxus/actions/workflows/main.yml/badge.svg [actions-url]: https://github.com/dioxuslabs/dioxus/actions?query=workflow%3ACI+branch%3Amaster - [discord-badge]: https://img.shields.io/discord/899851952891002890.svg?logo=discord&style=flat-square [discord-url]: https://discord.gg/XgGxMSkvUM [Website](https://dioxuslabs.com) | -[Guides](https://dioxuslabs.com/docs/0.3/guide/en/) | +[Guides](https://dioxuslabs.com/learn/0.4/) | [API Docs](https://docs.rs/dioxus-core-macro/latest/dioxus_core_macro) | [Chat](https://discord.gg/XgGxMSkvUM) - ## Overview `dioxus-core-macro` provides a handful of helpful macros used by the `dioxus` crate. These include: @@ -32,13 +27,13 @@ - The `inline_props` macro transforms function arguments into an auto-derived struct - The `format_args_f` macro which allows f-string formatting with support for expressions - ## Contributing - Report issues on our [issue tracker](https://github.com/dioxuslabs/dioxus/issues). - Join the discord and ask questions! ## License + This project is licensed under the [MIT license]. [mit license]: https://github.com/DioxusLabs/dioxus/blob/master/LICENSE-MIT diff --git a/packages/core-macro/src/component_body/mod.rs b/packages/core-macro/src/component_body/mod.rs new file mode 100644 index 000000000..91e66c42c --- /dev/null +++ b/packages/core-macro/src/component_body/mod.rs @@ -0,0 +1,237 @@ +//! This module is used for parsing a component function into a struct that is subsequently +//! deserialized into something useful using deserializer arguments. +//! +//! Let's break that down with a term glossary and examples which show usage and implementing. +//! +//! # Glossary +//! * `component body` - The [`ComponentBody`] struct. It's used to parse a component function [`proc_macro::TokenStream`] +//! to a reusable struct that deserializers use to modify the token stream. +//! * `deserializer` - A struct that deserializes the [`ComponentBody`] into a [`DeserializerOutput`]. +//! It implements the [`DeserializerArgs`] trait, but as you can see, it's called "DeserializerArgs", +//! not "Deserializer". Why? +//! Because "args" makes more sense to the caller of [`ComponentBody::deserialize`], which +//! takes an [`DeserializerArgs`] argument. However, you can think of "DeserializerArgs" as the deserializer. +//! * `deserializer output` - A struct that implements the [`DeserializerOutput`] trait. +//! This struct is what enables deserializers to use each other, since it contains the fields that +//! a deserializer needs to turn a token stream to a different token stream. +//! This means a deserializer can get the output of another deserializer, and use that output, +//! thereby using the functionality of a different deserializer. +//! This struct also implements [`ToTokens`], which means that this is the final stage of the whole process. +//! +//! # Examples +//! *Not all imports might be included.* +//! +//! ## Usage in a procedural macro attribute +//! ```rs,ignore +//! use proc_macro::TokenStream; +//! +//! // Some documentation. You can reuse this in your deserializer structs. +//! /// This attribute changes the name of a component function to whatever the first argument is. +//! #[proc_macro_attribute] +//! pub fn name_changer(args: TokenStream, input: TokenStream) -> TokenStream { +//! // Parse the component body. +//! let component_body = parse_macro_input!(input as ComponentBody); +//! +//! // Parse the first argument, which is going to be the components new name. +//! let new_name: String = match Punctuated::::parse_terminated.parse(args) { +//! Err(e) => return e.to_compile_error().into(), // Convert to a compile error and return +//! Ok(args) => { +//! // If the argument exists, then convert it to a string +//! if let Some(first) = args.first() { +//! first.to_token_stream().to_string() +//! } else { +//! // If the argument doesn't exist, return an error with the appropriate message. +//! // The "span" is the location of some code. +//! // The error occurred in the "args" token stream, so point the error there. +//! return Error::new(args.span(), "No new name provided").to_compile_error().into(); +//! } +//! } +//! }; +//! +//! let new_name = &*new_name; +//! +//! // Deserialize the component body to an output with the given args. +//! let output = component_body.deserialize(NameChangerDeserializerArgs { new_name }); +//! +//! // Error handling like before, except now you're ready to return the final value. +//! match output { +//! Err(e) => e.to_compile_error().into(), +//! Ok(output) => output.to_token_stream().into(), +//! } +//! } +//! ``` +//! ## Using the macro in Dioxus code: +//! ```rs +//! use your_proc_macro_library::name_changer; +//! use dioxus::prelude::*; +//! +//! #[name_changer(CoolName)] +//! pub fn LameName(cx: Scope) -> Element { +//! render! { "I want a cool name!" } +//! } +//! +//! pub fn App(cx: Scope) -> Element { +//! render! { CoolName {} } // Renders: "I want a cool name!" +//! } +//! ``` +//! ## Implementing a component body deserializer +//! ```rs +//! use syn::{Result, ItemFn, Signature, Ident}; +//! use quote::quote; +//! +//! // Create a list of arguments. +//! // If there was no args, just make it empty. The "args" struct is also the deserializer struct. +//! // For the docs, you can basically copy paste this text and replace "name_changer" with your macro path. +//! // Although unfortunately, the link does not work +//! // Just make sure that your macro is well documented. +//! /// The args and deserializing implementation for the [`name_changer`] macro. +//! #[derive(Clone)] +//! pub struct NameChangerDeserializerArgs<'a> { +//! pub new_name: &'a str, +//! } +//! +//! // Create an output struct. +//! // The ItemFn represents a modified component function. +//! // To read what fields should be here, check out the `DeserializerOutput` struct docs. +//! // For the docs, you can basically copy paste this text and replace "name_changer" with your macro path. +//! // Just make sure that your macro is well documented. +//! /// The output fields and [`ToTokens`] implementation for the [`name_changer`] macro. +//! #[derive(Clone)] +//! pub struct NameChangerDeserializerOutput { +//! pub comp_fn: ItemFn, +//! } +//! +//! // Implement `ToTokens`, which is forced by `DeserializerOutput`. +//! // This will usually be very simple like this, even for complex deserializers. +//! // That's because of the way the `DeserializerOutput` is designed. +//! impl ToTokens for NameChangerDeserializerOutput { +//! fn to_tokens(&self, tokens: &mut TokenStream) { +//! let comp_fn = &self.comp_fn; +//! +//! tokens.append_all(quote! { +//! #comp_fn +//! }); +//! } +//! } +//! +//! impl DeserializerOutput for NameChangerDeserializerOutput {} +//! +//! // Implement `DeserializerArgs`. This is the core part of deserializers. +//! impl<'a> DeserializerArgs for NameChangerDeserializerArgs<'a> { +//! fn to_output(&self, component_body: &ComponentBody) -> Result { +//! let old_fn = &component_body.item_fn; +//! let old_sig = &old_fn.sig; +//! +//! // For more complex uses, you will probably use `quote::parse_quote!` in combination with +//! // creating the structs manually. +//! // However, create the structs manually if you can. +//! // It's more reliable, because you only modify a certain struct field +//! // and set the others to be the clone of the original component body. +//! // That ensures that no information will be accidentally removed. +//! let new_sig = Signature { +//! ident: Ident::new(self.new_name, old_sig.ident.span()), +//! ..old_sig.clone() +//! }; +//! let new_fn = ItemFn { +//! sig: new_sig, +//! ..old_fn.clone() +//! }; +//! +//! Ok(NameChangerDeserializerOutput { +//! comp_fn: new_fn +//! }) +//! } +//! ``` + +pub mod utils; + +pub use utils::DeserializerArgs; +pub use utils::DeserializerOutput; +pub use utils::TypeHelper; + +use dioxus_core::{Element, Scope}; +use syn::parse::{Parse, ParseStream}; +use syn::spanned::Spanned; +use syn::*; + +/// General struct for parsing a component body. +/// However, because it's ambiguous, it does not implement [`ToTokens`](quote::to_tokens::ToTokens). +/// +/// Refer to the [module documentation](crate::component_body) for more. +pub struct ComponentBody { + /// The component function definition. You can parse this back into a [`ComponentBody`]. + /// For example, you might modify it, parse it into a [`ComponentBody`], and deserialize that + /// using some deserializer. This is how deserializers use other deserializers. + /// + /// **`item_fn.sig.inputs` includes the context argument!** + /// Keep this in mind when creating deserializers, because you often might want to ignore it. + /// That might be annoying, but it would be bad design for this kind of struct to not be parsable from itself. + pub item_fn: ItemFn, + /// Parsing tries to ensure that this argument will be a [`Scope`]. + /// **However, macros have limitations that prevent this from always working, + /// so don't take this for granted!** + pub cx_arg: FnArg, + /// The pattern (name) and type of the context argument. + pub cx_pat_type: PatType, + /// If the function has any arguments other than the context. + pub has_extra_args: bool, +} + +impl ComponentBody { + /// Deserializes the body into the [`TOutput`] with the specific [`TArgs`]. + /// Even if the args are empty, the [`TArg`] type still determines what [`TOutput`] will be generated. + pub fn deserialize(&self, args: TArgs) -> Result + where + TOutput: DeserializerOutput, + TArgs: DeserializerArgs, + { + args.to_output(self) + } +} + +impl Parse for ComponentBody { + fn parse(input: ParseStream) -> Result { + let item_fn: ItemFn = input.parse()?; + let scope_type_path = Scope::get_path_string(); + + let (cx_arg, cx_pat_type) = if let Some(first_arg) = item_fn.sig.inputs.first() { + let incorrect_first_arg_err = Err(Error::new( + first_arg.span(), + format!("First argument must be a <{}>", scope_type_path), + )); + + match first_arg.to_owned() { + FnArg::Receiver(_) => { + return incorrect_first_arg_err; + } + FnArg::Typed(f) => (first_arg.to_owned(), f), + } + } else { + return Err(Error::new( + item_fn.sig.ident.span(), // Or maybe just item_f.sig.span()? + format!( + "Must have at least one argument that's a <{}>", + scope_type_path + ), + )); + }; + + let element_type_path = Element::get_path_string(); + + if item_fn.sig.output == ReturnType::Default { + return Err(Error::new( + item_fn.sig.output.span(), + format!("Must return a <{}>", element_type_path), + )); + } + + let has_extra_args = item_fn.sig.inputs.len() > 1; + + Ok(Self { + item_fn, + cx_arg, + cx_pat_type, + has_extra_args, + }) + } +} diff --git a/packages/core-macro/src/component_body/utils.rs b/packages/core-macro/src/component_body/utils.rs new file mode 100644 index 000000000..05a2869d7 --- /dev/null +++ b/packages/core-macro/src/component_body/utils.rs @@ -0,0 +1,57 @@ +use crate::component_body::ComponentBody; +use dioxus_core::{Element, Scope}; +use quote::ToTokens; +use syn::{parse_quote, Path}; + +/// The output produced by a deserializer. +/// +/// # For implementors +/// Struct field guidelines: +/// * Must be public, so that other deserializers can utilize them. +/// * Should usually be [`Item`]s that you then simply combine in a [`quote!`] +/// in the [`ComponentBodyDeserializer::output_to_token_stream2`] function. +/// * If an [`Item`] might not be included, wrap it in an [`Option`]. +/// * Must be at the component function "level"/"context". +/// For example, the [`InlinePropsDeserializer`](crate::component_body_deserializers::inline_props::InlinePropsDeserializer) +/// produces two [`Item`]s; the function but with arguments turned into props, and the props struct. +/// It does not return any [`Item`]s inside the struct or function. +pub trait DeserializerOutput: ToTokens {} + +impl DeserializerOutput for T {} + +/// The args passed to a [`ComponentBody`] when deserializing it. +/// +/// It's also the struct that does the deserializing. +/// It's called "DeserializerArgs", not "Deserializer". Why? +/// Because "args" makes more sense to the caller of [`ComponentBody::deserialize`], which +/// takes an [`DeserializerArgs`] argument. However, you can think of "DeserializerArgs" as the deserializer. +pub trait DeserializerArgs: Clone +where + TOutput: ToTokens, +{ + // There's a lot of Results out there... let's make sure that this is a syn::Result. + // Let's also make sure there's not a warning. + /// Creates a [`ToTokens`] struct from the `self` args and a [`ComponentBody`]. + /// The [`ComponentBody::deserialize`] provides a cleaner way of calling this function. + #[allow(unused_qualifications)] + fn to_output(&self, component_body: &ComponentBody) -> syn::Result; +} + +pub trait TypeHelper { + fn get_path() -> Path; + fn get_path_string() -> String { + Self::get_path().to_token_stream().to_string() + } +} + +impl<'a> TypeHelper for Scope<'a> { + fn get_path() -> Path { + parse_quote!(::dioxus::core::Scope) + } +} + +impl<'a> TypeHelper for Element<'a> { + fn get_path() -> Path { + parse_quote!(::dioxus::core::Element) + } +} diff --git a/packages/core-macro/src/component_body_deserializers/component.rs b/packages/core-macro/src/component_body_deserializers/component.rs new file mode 100644 index 000000000..e43b1819f --- /dev/null +++ b/packages/core-macro/src/component_body_deserializers/component.rs @@ -0,0 +1,152 @@ +use crate::component_body::{ComponentBody, DeserializerArgs}; +use crate::component_body_deserializers::inline_props::InlinePropsDeserializerArgs; +use constcat::concat; +use proc_macro2::TokenStream as TokenStream2; +use quote::{quote, ToTokens, TokenStreamExt}; +use syn::*; + +pub(crate) const COMPONENT_ARG_CASE_CHECK_ERROR: &str = concat!( + "This component does not use PascalCase. \ +To ignore this check, pass the \"", + crate::COMPONENT_ARG_CASE_CHECK_OFF, + "\" argument, like so: #[component(", + crate::COMPONENT_ARG_CASE_CHECK_OFF, + ")]" +); + +const INNER_FN_NAME: &str = "__dx_inner_comp"; + +fn get_out_comp_fn(orig_comp_fn: &ItemFn, cx_pat: &Pat) -> ItemFn { + let inner_comp_ident = Ident::new(INNER_FN_NAME, orig_comp_fn.sig.ident.span()); + + let inner_comp_fn = ItemFn { + sig: Signature { + ident: inner_comp_ident.clone(), + ..orig_comp_fn.sig.clone() + }, + ..orig_comp_fn.clone() + }; + + ItemFn { + block: parse_quote! { + { + #[warn(non_snake_case)] + #[inline(always)] + #inner_comp_fn + #inner_comp_ident (#cx_pat) + } + }, + ..orig_comp_fn.clone() + } +} + +/// The args and deserializing implementation for the [`crate::component`] macro. +#[derive(Clone)] +pub struct ComponentDeserializerArgs { + pub case_check: bool, +} + +/// The output fields and [`ToTokens`] implementation for the [`crate::component`] macro. +#[derive(Clone)] +pub struct ComponentDeserializerOutput { + pub comp_fn: ItemFn, + pub props_struct: Option, +} + +impl ToTokens for ComponentDeserializerOutput { + fn to_tokens(&self, tokens: &mut TokenStream2) { + let comp_fn = &self.comp_fn; + let props_struct = &self.props_struct; + + tokens.append_all(quote! { + #props_struct + #[allow(non_snake_case)] + #comp_fn + }); + } +} + +impl DeserializerArgs for ComponentDeserializerArgs { + fn to_output(&self, component_body: &ComponentBody) -> Result { + let Signature { ident, .. } = &component_body.item_fn.sig; + + if self.case_check && !is_pascal_case(&ident.to_string()) { + return Err(Error::new(ident.span(), COMPONENT_ARG_CASE_CHECK_ERROR)); + } + + if component_body.has_extra_args { + Self::deserialize_with_props(component_body) + } else { + Ok(Self::deserialize_no_props(component_body)) + } + } +} + +impl ComponentDeserializerArgs { + fn deserialize_no_props(component_body: &ComponentBody) -> ComponentDeserializerOutput { + let ComponentBody { + item_fn, + cx_pat_type, + .. + } = component_body; + let cx_pat = &cx_pat_type.pat; + + let comp_fn = get_out_comp_fn(item_fn, cx_pat); + + ComponentDeserializerOutput { + comp_fn, + props_struct: None, + } + } + + fn deserialize_with_props( + component_body: &ComponentBody, + ) -> Result { + let ComponentBody { + item_fn, + cx_pat_type, + .. + } = component_body; + let cx_pat = &cx_pat_type.pat; + + let comp_parsed = match parse2::(quote!(#item_fn)) { + Ok(comp_body) => comp_body, + Err(e) => { + return Err(Error::new( + e.span(), + format!( + "This is probably a bug in our code, please report it! Error: {}", + e + ), + )) + } + }; + + let inlined_props_output = comp_parsed.deserialize(InlinePropsDeserializerArgs {})?; + let props_struct = inlined_props_output.props_struct; + let props_fn = inlined_props_output.comp_fn; + + let comp_fn = get_out_comp_fn(&props_fn, cx_pat); + + Ok(ComponentDeserializerOutput { + comp_fn, + props_struct: Some(props_struct), + }) + } +} + +fn is_pascal_case(input: &str) -> bool { + let mut is_next_lowercase = false; + + for c in input.chars() { + let is_upper = c.is_ascii_uppercase(); + + if (c == '_') || (is_upper && is_next_lowercase) { + return false; + } + + is_next_lowercase = is_upper; + } + + true +} diff --git a/packages/core-macro/src/component_body_deserializers/inline_props.rs b/packages/core-macro/src/component_body_deserializers/inline_props.rs new file mode 100644 index 000000000..8e4581c19 --- /dev/null +++ b/packages/core-macro/src/component_body_deserializers/inline_props.rs @@ -0,0 +1,195 @@ +use crate::component_body::{ComponentBody, DeserializerArgs}; +use proc_macro2::TokenStream as TokenStream2; +use quote::{quote, ToTokens, TokenStreamExt}; +use syn::token::Comma; +use syn::{punctuated::Punctuated, *}; + +/// The args and deserializing implementation for the [`crate::inline_props`] macro. +#[derive(Clone)] +pub struct InlinePropsDeserializerArgs; + +/// The output fields and [`ToTokens`] implementation for the [`crate::inline_props`] macro. +#[derive(Clone)] +pub struct InlinePropsDeserializerOutput { + pub comp_fn: ItemFn, + pub props_struct: ItemStruct, +} + +impl ToTokens for InlinePropsDeserializerOutput { + fn to_tokens(&self, tokens: &mut TokenStream2) { + let function = &self.comp_fn; + let props_struct = &self.props_struct; + + tokens.append_all(quote! { + #function + #props_struct + }); + } +} + +impl DeserializerArgs for InlinePropsDeserializerArgs { + fn to_output(&self, component_body: &ComponentBody) -> Result { + Ok(InlinePropsDeserializerOutput { + comp_fn: Self::get_function(component_body), + props_struct: Self::get_props_struct(component_body), + }) + } +} + +impl InlinePropsDeserializerArgs { + fn get_props_struct(component_body: &ComponentBody) -> ItemStruct { + let ComponentBody { item_fn, .. } = component_body; + let ItemFn { vis, sig, .. } = item_fn; + let Signature { + inputs, + ident: fn_ident, + generics, + .. + } = sig; + + // Skip first arg since that's the context + let struct_fields = inputs.iter().skip(1).map(move |f| { + match f { + FnArg::Receiver(_) => unreachable!(), // Unreachable because of ComponentBody parsing + FnArg::Typed(pt) => { + let arg_pat = &pt.pat; // Pattern (identifier) + let arg_colon = &pt.colon_token; + let arg_ty = &pt.ty; // Type + let arg_attrs = &pt.attrs; // Attributes + + quote! { + #(#arg_attrs) + * + #vis #arg_pat #arg_colon #arg_ty + } + } + } + }); + + let struct_ident = Ident::new(&format!("{fn_ident}Props"), fn_ident.span()); + + let first_lifetime = if let Some(GenericParam::Lifetime(lt)) = generics.params.first() { + Some(lt) + } else { + None + }; + + let struct_attrs = if first_lifetime.is_some() { + quote! { #[derive(Props)] } + } else { + quote! { #[derive(Props, PartialEq)] } + }; + + let struct_generics = if first_lifetime.is_some() { + let struct_generics: Punctuated = component_body + .item_fn + .sig + .generics + .params + .iter() + .map(|it| match it { + GenericParam::Type(tp) => { + let mut tp = tp.clone(); + tp.bounds.push(parse_quote!( 'a )); + + GenericParam::Type(tp) + } + _ => it.clone(), + }) + .collect(); + + quote! { <#struct_generics> } + } else { + quote! { #generics } + }; + + parse_quote! { + #struct_attrs + #[allow(non_camel_case_types)] + #vis struct #struct_ident #struct_generics + { + #(#struct_fields),* + } + } + } + + fn get_function(component_body: &ComponentBody) -> ItemFn { + let ComponentBody { + item_fn, + cx_pat_type, + .. + } = component_body; + let ItemFn { + attrs: fn_attrs, + vis, + sig, + block: fn_block, + } = item_fn; + let Signature { + inputs, + ident: fn_ident, + generics, + output: fn_output, + asyncness, + .. + } = sig; + let Generics { where_clause, .. } = generics; + + let cx_pat = &cx_pat_type.pat; + let struct_ident = Ident::new(&format!("{fn_ident}Props"), fn_ident.span()); + + // Skip first arg since that's the context + let struct_field_names = inputs.iter().skip(1).filter_map(|f| match f { + FnArg::Receiver(_) => unreachable!(), // ComponentBody prohibits receiver parameters. + FnArg::Typed(t) => Some(&t.pat), + }); + + let first_lifetime = if let Some(GenericParam::Lifetime(lt)) = generics.params.first() { + Some(lt) + } else { + None + }; + + let (scope_lifetime, fn_generics) = if let Some(lt) = first_lifetime { + (quote! { #lt, }, generics.clone()) + } else { + let lifetime: LifetimeParam = parse_quote! { 'a }; + + let mut fn_generics = generics.clone(); + fn_generics + .params + .insert(0, GenericParam::Lifetime(lifetime.clone())); + + (quote! { #lifetime, }, fn_generics) + }; + + let generics_no_bounds = { + let mut generics = generics.clone(); + generics.params = generics + .params + .iter() + .map(|it| match it { + GenericParam::Type(tp) => { + let mut tp = tp.clone(); + tp.bounds.clear(); + + GenericParam::Type(tp) + } + _ => it.clone(), + }) + .collect(); + + generics + }; + + parse_quote! { + #(#fn_attrs)* + #asyncness #vis fn #fn_ident #fn_generics (#cx_pat: Scope<#scope_lifetime #struct_ident #generics_no_bounds>) #fn_output + #where_clause + { + let #struct_ident { #(#struct_field_names),* } = &#cx_pat.props; + #fn_block + } + } + } +} diff --git a/packages/core-macro/src/component_body_deserializers/mod.rs b/packages/core-macro/src/component_body_deserializers/mod.rs new file mode 100644 index 000000000..a3027796d --- /dev/null +++ b/packages/core-macro/src/component_body_deserializers/mod.rs @@ -0,0 +1,4 @@ +//! This module contains all [`ComponentBody`](crate::component_body::ComponentBody) deserializers. + +pub mod component; +pub mod inline_props; diff --git a/packages/core-macro/src/inlineprops.rs b/packages/core-macro/src/inlineprops.rs deleted file mode 100644 index ccc00f4f9..000000000 --- a/packages/core-macro/src/inlineprops.rs +++ /dev/null @@ -1,185 +0,0 @@ -use proc_macro2::{Span, TokenStream as TokenStream2}; -use quote::{quote, ToTokens, TokenStreamExt}; -use syn::{ - parse::{Parse, ParseStream}, - punctuated::Punctuated, - *, -}; - -pub struct InlinePropsBody { - pub attrs: Vec, - pub vis: syn::Visibility, - pub maybe_async: Option, - pub fn_token: Token![fn], - pub ident: Ident, - pub cx_token: Box, - pub generics: Generics, - pub paren_token: token::Paren, - pub inputs: Punctuated, - // pub fields: FieldsNamed, - pub output: ReturnType, - pub where_clause: Option, - pub block: Box, -} - -/// The custom rusty variant of parsing rsx! -impl Parse for InlinePropsBody { - fn parse(input: ParseStream) -> Result { - let attrs: Vec = input.call(Attribute::parse_outer)?; - let maybe_async: Option = input.parse().ok(); - let vis: Visibility = input.parse()?; - - let fn_token = input.parse()?; - let ident = input.parse()?; - let generics: Generics = input.parse()?; - - let content; - let paren_token = syn::parenthesized!(content in input); - - let first_arg: FnArg = content.parse()?; - let cx_token = { - match first_arg { - FnArg::Receiver(_) => panic!("first argument must not be a receiver argument"), - FnArg::Typed(f) => f.pat, - } - }; - - let _: Result = content.parse(); - - let inputs = syn::punctuated::Punctuated::parse_terminated(&content)?; - - let output = input.parse()?; - - let where_clause = input - .peek(syn::token::Where) - .then(|| input.parse()) - .transpose()?; - - let block = input.parse()?; - - Ok(Self { - vis, - maybe_async, - fn_token, - ident, - generics, - paren_token, - inputs, - output, - where_clause, - block, - cx_token, - attrs, - }) - } -} - -/// Serialize the same way, regardless of flavor -impl ToTokens for InlinePropsBody { - fn to_tokens(&self, out_tokens: &mut TokenStream2) { - let Self { - vis, - ident, - generics, - inputs, - output, - where_clause, - block, - cx_token, - attrs, - maybe_async, - .. - } = self; - - let fields = inputs.iter().map(|f| { - quote! { #vis #f } - }); - - let struct_name = Ident::new(&format!("{ident}Props"), Span::call_site()); - - let field_names = inputs.iter().filter_map(|f| match f { - FnArg::Receiver(_) => todo!(), - FnArg::Typed(t) => Some(&t.pat), - }); - - let first_lifetime = if let Some(GenericParam::Lifetime(lt)) = generics.params.first() { - Some(lt) - } else { - None - }; - - let modifiers = if first_lifetime.is_some() { - quote! { #[derive(Props)] } - } else { - quote! { #[derive(Props, PartialEq)] } - }; - - let (scope_lifetime, fn_generics, struct_generics) = if let Some(lt) = first_lifetime { - let struct_generics: Punctuated<_, token::Comma> = generics - .params - .iter() - .map(|it| match it { - GenericParam::Type(tp) => { - let mut tp = tp.clone(); - tp.bounds.push(parse_quote!( 'a )); - - GenericParam::Type(tp) - } - _ => it.clone(), - }) - .collect(); - - ( - quote! { #lt, }, - generics.clone(), - quote! { <#struct_generics> }, - ) - } else { - let lifetime: LifetimeParam = parse_quote! { 'a }; - - let mut fn_generics = generics.clone(); - fn_generics - .params - .insert(0, GenericParam::Lifetime(lifetime.clone())); - - (quote! { #lifetime, }, fn_generics, quote! { #generics }) - }; - - let generics_no_bounds = { - let mut generics = generics.clone(); - generics.params = generics - .params - .iter() - .map(|it| match it { - GenericParam::Type(tp) => { - let mut tp = tp.clone(); - tp.bounds.clear(); - - GenericParam::Type(tp) - } - _ => it.clone(), - }) - .collect(); - - generics - }; - - out_tokens.append_all(quote! { - #modifiers - #[allow(non_camel_case_types)] - #vis struct #struct_name #struct_generics - #where_clause - { - #(#fields),* - } - - #(#attrs)* - #maybe_async #vis fn #ident #fn_generics (#cx_token: Scope<#scope_lifetime #struct_name #generics_no_bounds>) #output - #where_clause - { - let #struct_name { #(#field_names),* } = &#cx_token.props; - #block - } - }); - } -} diff --git a/packages/core-macro/src/lib.rs b/packages/core-macro/src/lib.rs index 501c38e7b..d91c72e39 100644 --- a/packages/core-macro/src/lib.rs +++ b/packages/core-macro/src/lib.rs @@ -1,12 +1,18 @@ use proc_macro::TokenStream; use quote::ToTokens; use rsx::RenderCallBody; -use syn::parse_macro_input; +use syn::parse::Parser; +use syn::punctuated::Punctuated; +use syn::{parse_macro_input, Path, Token}; -mod inlineprops; +mod component_body; +mod component_body_deserializers; mod props; // mod rsx; +use crate::component_body::ComponentBody; +use crate::component_body_deserializers::component::ComponentDeserializerArgs; +use crate::component_body_deserializers::inline_props::InlinePropsDeserializerArgs; use dioxus_rsx as rsx; #[proc_macro] @@ -18,7 +24,7 @@ pub fn format_args_f(input: TokenStream) -> TokenStream { } #[proc_macro_derive(Props, attributes(props))] -pub fn derive_typed_builder(input: proc_macro::TokenStream) -> proc_macro::TokenStream { +pub fn derive_typed_builder(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as syn::DeriveInput); match props::impl_my_derive(&input) { Ok(output) => output.into(), @@ -37,7 +43,7 @@ pub fn rsx(s: TokenStream) -> TokenStream { /// The render! macro makes it easy for developers to write jsx-style markup in their components. /// -/// The render macro automatically renders rsx - making it unhygenic. +/// The render macro automatically renders rsx - making it unhygienic. #[proc_macro] pub fn render(s: TokenStream) -> TokenStream { match syn::parse::(s) { @@ -55,7 +61,7 @@ pub fn render(s: TokenStream) -> TokenStream { /// you would be repeating a lot of the usual Rust boilerplate. /// /// # Example -/// ```ignore +/// ```rust,ignore /// #[inline_props] /// fn app(cx: Scope, bob: String) -> Element { /// cx.render(rsx!("hello, {bob}")) @@ -73,9 +79,118 @@ pub fn render(s: TokenStream) -> TokenStream { /// } /// ``` #[proc_macro_attribute] -pub fn inline_props(_args: proc_macro::TokenStream, s: TokenStream) -> TokenStream { - match syn::parse::(s) { +#[deprecated(note = "Use `#[component]` instead.")] +pub fn inline_props(_args: TokenStream, s: TokenStream) -> TokenStream { + let comp_body = parse_macro_input!(s as ComponentBody); + + match comp_body.deserialize(InlinePropsDeserializerArgs {}) { Err(e) => e.to_compile_error().into(), - Ok(s) => s.to_token_stream().into(), + Ok(output) => output.to_token_stream().into(), + } +} + +pub(crate) const COMPONENT_ARG_CASE_CHECK_OFF: &str = "no_case_check"; + +/// Streamlines component creation. +/// This is the recommended way of creating components, +/// though you might want lower-level control with more advanced uses. +/// +/// # Arguments +/// * `no_case_check` - Doesn't enforce `PascalCase` on your component names. +/// **This will be removed/deprecated in a future update in favor of a more complete Clippy-backed linting system.** +/// The reasoning behind this is that Clippy allows more robust and powerful lints, whereas +/// macros are extremely limited. +/// +/// # Features +/// This attribute: +/// * Enforces that your component uses `PascalCase`. +/// No warnings are generated for the `PascalCase` +/// function name, but everything else will still raise a warning if it's incorrectly `PascalCase`. +/// Does not disable warnings anywhere else, so if you, for example, +/// accidentally don't use `snake_case` +/// for a variable name in the function, the compiler will still warn you. +/// * Automatically uses `#[inline_props]` if there's more than 1 parameter in the function. +/// * Verifies the validity of your component. +/// E.g. if it has a [`Scope`](dioxus_core::Scope) argument. +/// Notes: +/// * This doesn't work 100% of the time, because of macro limitations. +/// * Provides helpful messages if your component is not correct. +/// Possible bugs (please, report these!): +/// * There might be bugs where it incorrectly *denies* validity. +/// This is bad as it means that you can't use the attribute or you have to change the component. +/// * There might be bugs where it incorrectly *confirms* validity. +/// You will still know if the component is invalid once you use it, +/// but the error might be less helpful. +/// +/// # Examples +/// * Without props: +/// ```rust,ignore +/// #[component] +/// fn GreetBob(cx: Scope) -> Element { +/// render! { "hello, bob" } +/// } +/// +/// // is equivalent to +/// +/// #[allow(non_snake_case)] +/// fn GreetBob(cx: Scope) -> Element { +/// #[warn(non_snake_case)] +/// #[inline(always)] +/// fn __dx_inner_comp(cx: Scope) -> Element { +/// render! { "hello, bob" } +/// } +/// // There's no function call overhead since __dx_inner_comp has the #[inline(always)] attribute, +/// // so don't worry about performance. +/// __dx_inner_comp(cx) +/// } +/// ``` +/// * With props: +/// ```rust,ignore +/// #[component(no_case_check)] +/// fn GreetPerson(cx: Scope, person: String) -> Element { +/// render! { "hello, {person}" } +/// } +/// +/// // is equivalent to +/// +/// #[derive(Props, PartialEq)] +/// #[allow(non_camel_case_types)] +/// struct GreetPersonProps { +/// person: String, +/// } +/// +/// #[allow(non_snake_case)] +/// fn GreetPerson<'a>(cx: Scope<'a, GreetPersonProps>) -> Element { +/// #[warn(non_snake_case)] +/// #[inline(always)] +/// fn __dx_inner_comp<'a>(cx: Scope<'a, GreetPersonProps>e) -> Element { +/// let GreetPersonProps { person } = &cx.props; +/// { +/// render! { "hello, {person}" } +/// } +/// } +/// +/// __dx_inner_comp(cx) +/// } +/// ``` +// TODO: Maybe add an option to input a custom component name through the args. +// I think that's unnecessary, but there might be some scenario where it could be useful. +#[proc_macro_attribute] +pub fn component(args: TokenStream, input: TokenStream) -> TokenStream { + let component_body = parse_macro_input!(input as ComponentBody); + let case_check = match Punctuated::::parse_terminated.parse(args) { + Err(e) => return e.to_compile_error().into(), + Ok(args) => { + if let Some(first) = args.first() { + !first.is_ident(COMPONENT_ARG_CASE_CHECK_OFF) + } else { + true + } + } + }; + + match component_body.deserialize(ComponentDeserializerArgs { case_check }) { + Err(e) => e.to_compile_error().into(), + Ok(output) => output.to_token_stream().into(), } } diff --git a/packages/core-macro/src/props/mod.rs b/packages/core-macro/src/props/mod.rs index 6a0d24a95..c1931e497 100644 --- a/packages/core-macro/src/props/mod.rs +++ b/packages/core-macro/src/props/mod.rs @@ -2,9 +2,9 @@ //! //! However, it has been adopted to fit the Dioxus Props builder pattern. //! -//! For dioxus, we make a few changes: -//! - [ ] automatically implement Into

, props: P, cfg: Config) if temp.contains_key("href") { let open = webbrowser::open(temp["href"].as_str().unwrap()); if let Err(e) = open { - log::error!("Open Browser error: {:?}", e); + tracing::error!("Open Browser error: {:?}", e); } } } diff --git a/packages/desktop/src/protocol.rs b/packages/desktop/src/protocol.rs index 7a9e0b8e7..1f407561c 100644 --- a/packages/desktop/src/protocol.rs +++ b/packages/desktop/src/protocol.rs @@ -149,7 +149,7 @@ pub(super) fn desktop_handler( .map_err(From::from); } - log::error!( + tracing::error!( "Failed to find {} (as path {})", request.uri().path(), asset.display() diff --git a/packages/desktop/src/query.rs b/packages/desktop/src/query.rs index 247f333e8..d38478c61 100644 --- a/packages/desktop/src/query.rs +++ b/packages/desktop/src/query.rs @@ -123,7 +123,7 @@ impl QueryEngine { }}) }})();"# )) { - log::warn!("Query error: {err}"); + tracing::warn!("Query error: {err}"); } Query { diff --git a/packages/desktop/src/readme.md b/packages/desktop/src/readme.md index cd4dbe41a..ac2205b4c 100644 --- a/packages/desktop/src/readme.md +++ b/packages/desktop/src/readme.md @@ -8,7 +8,6 @@ One of Dioxus' flagship features is the ability to quickly build a native deskto Dioxus Desktop is built off Tauri. Right now there aren't any Dioxus abstractions over the 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. An upcoming 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: @@ -44,9 +43,8 @@ fn app(cx: Scope) -> Element { } ``` - 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/docs/0.3/guide/en) if you already haven't! +Make sure to read the [Dioxus Guide](https://dioxuslabs.com/learn/0.4/) if you already haven't! diff --git a/packages/dioxus-tui/Cargo.toml b/packages/dioxus-tui/Cargo.toml index 1286ca010..0d0bb59f4 100644 --- a/packages/dioxus-tui/Cargo.toml +++ b/packages/dioxus-tui/Cargo.toml @@ -5,7 +5,7 @@ authors = ["Jonathan Kelley, Evan Almloff"] edition = "2021" description = "TUI-based renderer for Dioxus" repository = "https://github.com/DioxusLabs/dioxus/" -homepage = "https://dioxuslabs.com/docs/0.3/guide/en/getting_started/tui.html" +homepage = "https://dioxuslabs.com/learn/0.4/getting_started/tui" keywords = ["dom", "ui", "gui", "react", "terminal"] license = "MIT OR Apache-2.0" diff --git a/packages/dioxus/Cargo.toml b/packages/dioxus/Cargo.toml index ea052230b..2c284bf1a 100644 --- a/packages/dioxus/Cargo.toml +++ b/packages/dioxus/Cargo.toml @@ -6,7 +6,7 @@ edition = "2021" description = "Portable, performant, and ergonomic framework for building cross-platform user interfaces in Rust" license = "MIT OR Apache-2.0" repository = "https://github.com/DioxusLabs/dioxus/" -homepage = "https://dioxuslabs.com/docs/0.3/guide/en/index.html" +homepage = "https://dioxuslabs.com/learn/0.4/" keywords = ["dom", "ui", "gui", "react", "wasm"] rust-version = "1.65.0" @@ -30,7 +30,7 @@ hot-reload = ["dioxus-hot-reload"] [dev-dependencies] futures-util = { workspace = true } -log = { workspace = true } +tracing = { workspace = true } rand = { version = "0.8.4", features = ["small_rng"] } criterion = "0.3.5" thiserror = { workspace = true } diff --git a/packages/dioxus/README.md b/packages/dioxus/README.md index 31fff88fa..5bbb37aa0 100644 --- a/packages/dioxus/README.md +++ b/packages/dioxus/README.md @@ -1,4 +1,4 @@ -

+

🌗🚀 Dioxus

A concurrent, functional, virtual DOM for Rust @@ -9,8 +9,8 @@ This overview provides a brief introduction to Dioxus. For a more in-depth guide, make sure to check out: -- [Getting Started](https://dioxuslabs.com/docs/0.3/guide/en/getting_started/index.html) -- [Book](https://dioxuslabs.com/docs/0.3/guide/en/) +- [Getting Started](https://dioxuslabs.com/learn/0.4/getting_started) +- [Book (0.4)](https://dioxuslabs.com/learn/0.4/) - [Examples](https://github.com/DioxusLabs/example-projects) # Overview and Goals @@ -27,15 +27,15 @@ Dioxus is heavily inspired by React, supporting many of the same concepts: If you know React, then you know Dioxus. -Dioxus is *substantially* more performant than many of the other Rust UI libraries (Yew/Percy) and is *significantly* more performant -than React - roughly competitive with InfernoJS. +Dioxus is _substantially_ more performant than many of the other Rust UI libraries (Yew/Percy) and is _significantly_ more performant +than React—roughly competitive with InfernoJS. -Remember: Dioxus is a library for declaring interactive user interfaces - it is not a dedicated renderer. Most 1st party renderers for Dioxus currently only support web technologies. +Remember: Dioxus is a library for declaring interactive user interfaces—it is not a dedicated renderer. Most 1st party renderers for Dioxus currently only support web technologies. ## Brief Overview All Dioxus apps are built by composing functions that take in a `Scope` which is generic over some `Properties` and return an `Element`. -A `Scope` holds relevant state data for the currently-rendered component. +A `Scope` holds relevant state data for the currently rendered component. To launch an app, we use the `launch` method for the specific renderer we want to use. In the launch function, we pass the app's `Component`. @@ -43,10 +43,13 @@ To launch an app, we use the `launch` method for the specific renderer we want t use dioxus::prelude::*; fn main() { - dioxus_desktop::launch(app); + dioxus_desktop::launch(App); } -fn app(cx: Scope) -> Element { +// The #[component] attribute streamlines component creation. +// It's not required, but highly recommended. For example, UpperCamelCase components will not generate a warning. +#[component] +fn App(cx: Scope) -> Element { cx.render(rsx!("hello world!")) } ``` @@ -59,7 +62,7 @@ macro or the NodeFactory API. For the most part, you want to use the `rsx!` macro. Any element in `rsx!` can have attributes, listeners, and children. For -consistency, we force all attributes and listeners to be listed *before* +consistency, we force all attributes and listeners to be listed _before_ children. ```rust, ignore @@ -84,7 +87,6 @@ rsx!( (0..10).map(|_| rsx!(span { "hello world" })) } ) - ``` Used within components, the `rsx!` macro must be rendered into an `Element` with @@ -95,7 +97,8 @@ If we want to omit the boilerplate of `cx.render`, we can simply pass in render nodes in match statements. ```rust, ignore -fn example(cx: Scope) -> Element { +#[component[ +fn Example(cx: Scope) -> Element { // both of these are equivalent cx.render(rsx!("hello world")) @@ -108,7 +111,8 @@ Putting everything together, we can write a simple component that renders a list elements: ```rust, ignore -fn app(cx: Scope) -> Element { +#[component] +fn App(cx: Scope) -> Element { let name = "dave"; cx.render(rsx!( h1 { "Hello, {name}!" } @@ -136,6 +140,7 @@ properties, we can use the `()` type or simply omit the type altogether. In Dioxus, all properties are memoized by default! ```rust, ignore +#[component] fn App(cx: Scope) -> Element { cx.render(rsx!( Header { @@ -157,6 +162,7 @@ struct HeaderProps { color: String, } +#[component] fn Header(cx: Scope) -> Element { cx.render(rsx!( div { @@ -167,11 +173,11 @@ fn Header(cx: Scope) -> Element { } ``` -Components may use the `inline_props` macro to completely inline the props -definition into the function arguments. +The `#[component]` macro also allows you to derive the props +struct from function arguments: ```rust, ignore -#[inline_props] +#[component] fn Header(cx: Scope, title: String, color: String) -> Element { cx.render(rsx!( div { @@ -184,6 +190,7 @@ fn Header(cx: Scope, title: String, color: String) -> Element { Components may also borrow data from their parent component. We just need to attach some lifetimes to the props struct. + > Note: we don't need to derive `PartialEq` for borrowed props since they cannot be memoized. ```rust, ignore @@ -193,6 +200,7 @@ struct HeaderProps<'a> { color: &'a str, } +#[component] fn Header<'a>(cx: Scope<'a, HeaderProps<'a>>) -> Element { cx.render(rsx!( div { @@ -221,6 +229,9 @@ rsx!( ) ``` +However, the convention is to use UpperCamelCase. The `#[component]` attribute will enforce this, +but you can turn it off if you wish. + ## Hooks While components are reusable forms of UI elements, hooks are reusable forms @@ -231,7 +242,8 @@ By convention, all hooks are functions that should start with `use_`. We can use hooks to define the state and modify it from within listeners. ```rust, ignore -fn app(cx: Scope) -> Element { +#[component] +fn App(cx: Scope) -> Element { let name = use_state(cx, || "world"); render!("hello {name}!") @@ -239,10 +251,11 @@ fn app(cx: Scope) -> Element { ``` Hooks are sensitive to how they are used. To use hooks, you must abide by the -["rules of hooks" (borrowed from react)](https://reactjs.org/docs/hooks-rules.html): -- Functions with "use_" should not be called in callbacks -- Functions with "use_" should not be called out of order -- Functions with "use_" should not be called in loops or conditionals +["rules of hooks" (borrowed from React)](https://reactjs.org/docs/hooks-rules.html): + +- Functions with "use\_" should not be called in callbacks +- Functions with "use\_" should not be called out of order +- Functions with "use\_" should not be called in loops or conditionals In a sense, hooks let us add a field of state to our component without declaring an explicit state struct. However, this means we need to "load" the struct in the right @@ -278,6 +291,7 @@ fn main() { dioxus_desktop::launch(App); } +#[component] fn App(cx: Scope) -> Element { let count = use_state(cx, || 0); @@ -295,6 +309,7 @@ This overview doesn't cover everything. Make sure to check out the tutorial and website for more details. Beyond this overview, Dioxus supports: + - Server-side rendering - Concurrent rendering (with async support) - Web/Desktop/Mobile support @@ -311,14 +326,16 @@ Good luck! ## Inspiration, Resources, Alternatives, and Credits Dioxus is inspired by: + - React: for its hooks, concurrency, suspense - Dodrio: for its research in bump allocation, double buffering, and diffing architecture Alternatives to Dioxus include: + - Yew: supports function components and web, but no SSR, borrowed data, or bump allocation. Rather slow at times. - Percy: supports function components, web, ssr, but lacks state management - Sycamore: supports function components, web, ssr, but is closer to SolidJS than React -- MoonZoom/Seed: opinionated frameworks based on the Elm model (message, update) - no hooks +- MoonZoom/Seed: opinionated frameworks based on the Elm model (message, update)—no hooks -We've put a lot of work into making Dioxus ergonomic and *familiar*. -Our target audience is TypeScript developers looking to switch to Rust for the web - so we need to be comparable to React. +We've put a lot of work into making Dioxus ergonomic and _familiar_. +Our target audience is TypeScript developers looking to switch to Rust for the web—so we need to be comparable to React. diff --git a/packages/dioxus/src/lib.rs b/packages/dioxus/src/lib.rs index 5d1371f27..bc2cd76e6 100644 --- a/packages/dioxus/src/lib.rs +++ b/packages/dioxus/src/lib.rs @@ -24,7 +24,8 @@ pub mod prelude { pub use dioxus_core::prelude::*; #[cfg(feature = "macro")] - pub use dioxus_core_macro::{format_args_f, inline_props, render, rsx, Props}; + #[allow(deprecated)] + pub use dioxus_core_macro::{component, format_args_f, inline_props, render, rsx, Props}; #[cfg(feature = "html")] pub use dioxus_html as dioxus_elements; diff --git a/packages/fermi/Cargo.toml b/packages/fermi/Cargo.toml index a50a06852..92a0ede71 100644 --- a/packages/fermi/Cargo.toml +++ b/packages/fermi/Cargo.toml @@ -14,7 +14,7 @@ keywords = ["dom", "ui", "gui", "react", "state-management"] [dependencies] dioxus-core = { workspace = true } im-rc = { version = "15.0.0", features = ["serde"] } -log = { workspace = true } +tracing = { workspace = true } [dev-dependencies] closure = "0.3.0" diff --git a/packages/fermi/src/root.rs b/packages/fermi/src/root.rs index f77930c75..67f6514c7 100644 --- a/packages/fermi/src/root.rs +++ b/packages/fermi/src/root.rs @@ -66,14 +66,14 @@ impl AtomRoot { if let Some(slot) = atoms.get_mut(&ptr) { slot.value = Rc::new(value); - log::trace!("found item with subscribers {:?}", slot.subscribers); + tracing::trace!("found item with subscribers {:?}", slot.subscribers); for scope in &slot.subscribers { - log::trace!("updating subcsriber"); + tracing::trace!("updating subcsriber"); (self.update_any)(*scope); } } else { - log::trace!("no atoms found for {:?}", ptr); + tracing::trace!("no atoms found for {:?}", ptr); atoms.insert( ptr, Slot { @@ -96,7 +96,7 @@ impl AtomRoot { pub fn force_update(&self, ptr: AtomId) { if let Some(slot) = self.atoms.borrow_mut().get(&ptr) { for scope in slot.subscribers.iter() { - log::trace!("updating subcsriber"); + tracing::trace!("updating subcsriber"); (self.update_any)(*scope); } } diff --git a/packages/fullstack/Cargo.toml b/packages/fullstack/Cargo.toml index 82ed7c8d7..8ab213e78 100644 --- a/packages/fullstack/Cargo.toml +++ b/packages/fullstack/Cargo.toml @@ -44,7 +44,8 @@ dioxus-desktop = { workspace = true, optional = true } # Router Integration dioxus-router = { workspace = true, optional = true } -log = { workspace = true } +tracing = { workspace = true } +tracing-futures = { workspace = true } once_cell = "1.17.1" thiserror = { workspace = true } tokio = { workspace = true, features = ["full"], optional = true } diff --git a/packages/fullstack/README.md b/packages/fullstack/README.md index ecd003ee8..3128c3598 100644 --- a/packages/fullstack/README.md +++ b/packages/fullstack/README.md @@ -15,7 +15,7 @@ [discord-url]: https://discord.gg/XgGxMSkvUM [Website](https://dioxuslabs.com) | -[Guides](https://dioxuslabs.com/docs/0.3/guide/en/) | +[Guides](https://dioxuslabs.com/learn/0.4/) | [API Docs](https://docs.rs/dioxus-fullstack/latest/dioxus_sever) | [Chat](https://discord.gg/XgGxMSkvUM) diff --git a/packages/fullstack/examples/axum-hello-world/Cargo.toml b/packages/fullstack/examples/axum-hello-world/Cargo.toml index 2073e4655..a3b68b05a 100644 --- a/packages/fullstack/examples/axum-hello-world/Cargo.toml +++ b/packages/fullstack/examples/axum-hello-world/Cargo.toml @@ -12,8 +12,9 @@ dioxus-fullstack = { workspace = true } axum = { version = "0.6.12", optional = true } serde = "1.0.159" simple_logger = "4.2.0" -wasm-logger = "0.2.0" -log.workspace = true +tracing-wasm = "0.2.1" +tracing.workspace = true +tracing-subscriber = "0.3.17" reqwest = "0.11.18" [features] diff --git a/packages/fullstack/examples/axum-hello-world/src/main.rs b/packages/fullstack/examples/axum-hello-world/src/main.rs index 985a5a717..8f1d3c8c6 100644 --- a/packages/fullstack/examples/axum-hello-world/src/main.rs +++ b/packages/fullstack/examples/axum-hello-world/src/main.rs @@ -12,7 +12,6 @@ use dioxus_fullstack::{ prelude::*, }; use serde::{Deserialize, Serialize}; -use wasm_logger::Config; #[derive(Props, PartialEq, Debug, Default, Serialize, Deserialize, Clone)] struct AppProps { @@ -66,9 +65,9 @@ async fn get_server_data() -> Result { fn main() { #[cfg(feature = "web")] - wasm_logger::init(wasm_logger::Config::new(log::Level::Trace)); + tracing_wasm::set_as_global_default(); #[cfg(feature = "ssr")] - simple_logger::SimpleLogger::new().init().unwrap(); + tracing_subscriber::fmt::init(); LaunchBuilder::new_with_props(app, AppProps { count: 0 }).launch() } diff --git a/packages/fullstack/examples/axum-router/src/main.rs b/packages/fullstack/examples/axum-router/src/main.rs index 6780aec6f..176bf3361 100644 --- a/packages/fullstack/examples/axum-router/src/main.rs +++ b/packages/fullstack/examples/axum-router/src/main.rs @@ -5,8 +5,6 @@ //! cargo run --features ssr --release //! ``` -#![allow(non_snake_case)] - use dioxus::prelude::*; use dioxus_fullstack::prelude::*; use dioxus_router::prelude::*; @@ -33,7 +31,7 @@ enum Route { Blog { id: i32 }, } -#[inline_props] +#[component] fn Blog(cx: Scope, id: i32) -> Element { render! { Link { to: Route::Home {}, "Go to counter" } @@ -51,7 +49,7 @@ fn Blog(cx: Scope, id: i32) -> Element { } } -#[inline_props] +#[component] fn Home(cx: Scope) -> Element { let mut count = use_state(cx, || 0); let text = use_state(cx, || "...".to_string()); diff --git a/packages/fullstack/examples/salvo-hello-world/Cargo.toml b/packages/fullstack/examples/salvo-hello-world/Cargo.toml index 977ad7843..ca0d85ecf 100644 --- a/packages/fullstack/examples/salvo-hello-world/Cargo.toml +++ b/packages/fullstack/examples/salvo-hello-world/Cargo.toml @@ -16,8 +16,9 @@ salvo = { version = "0.37.9", optional = true } execute = "0.2.12" reqwest = "0.11.18" simple_logger = "4.2.0" -log.workspace = true -wasm-logger = "0.2.0" +tracing-wasm = "0.2.1" +tracing.workspace = true +tracing-subscriber = "0.3.17" [features] default = [] diff --git a/packages/fullstack/examples/salvo-hello-world/src/main.rs b/packages/fullstack/examples/salvo-hello-world/src/main.rs index df119b4dd..838ee6f2c 100644 --- a/packages/fullstack/examples/salvo-hello-world/src/main.rs +++ b/packages/fullstack/examples/salvo-hello-world/src/main.rs @@ -60,9 +60,9 @@ async fn get_server_data() -> Result { fn main() { #[cfg(feature = "web")] - wasm_logger::init(wasm_logger::Config::new(log::Level::Trace)); + tracing_wasm::set_as_global_default(); #[cfg(feature = "ssr")] - simple_logger::SimpleLogger::new().init().unwrap(); + tracing_subscriber::fmt::init(); LaunchBuilder::new_with_props(app, AppProps { count: 0 }).launch() } diff --git a/packages/fullstack/examples/static-hydrated/src/main.rs b/packages/fullstack/examples/static-hydrated/src/main.rs index 78963be7e..2539d0deb 100644 --- a/packages/fullstack/examples/static-hydrated/src/main.rs +++ b/packages/fullstack/examples/static-hydrated/src/main.rs @@ -5,7 +5,7 @@ //! cargo run --features ssr //! ``` -#![allow(non_snake_case, unused)] +#![allow(unused)] use dioxus::prelude::*; use dioxus_fullstack::{launch, prelude::*}; use dioxus_router::prelude::*; @@ -49,7 +49,7 @@ enum Route { Blog, } -#[inline_props] +#[component] fn Blog(cx: Scope) -> Element { render! { Link { to: Route::Home {}, "Go to counter" } @@ -67,7 +67,7 @@ fn Blog(cx: Scope) -> Element { } } -#[inline_props] +#[component] fn Home(cx: Scope) -> Element { let mut count = use_state(cx, || 0); let text = use_state(cx, || "...".to_string()); diff --git a/packages/fullstack/examples/warp-hello-world/Cargo.toml b/packages/fullstack/examples/warp-hello-world/Cargo.toml index d9e82b4c4..1474facf3 100644 --- a/packages/fullstack/examples/warp-hello-world/Cargo.toml +++ b/packages/fullstack/examples/warp-hello-world/Cargo.toml @@ -16,8 +16,9 @@ warp = { version = "0.3.3", optional = true } execute = "0.2.12" reqwest = "0.11.18" simple_logger = "4.2.0" -log.workspace = true -wasm-logger = "0.2.0" +tracing-wasm = "0.2.1" +tracing.workspace = true +tracing-subscriber = "0.3.17" [features] default = [] diff --git a/packages/fullstack/examples/warp-hello-world/src/main.rs b/packages/fullstack/examples/warp-hello-world/src/main.rs index df119b4dd..838ee6f2c 100644 --- a/packages/fullstack/examples/warp-hello-world/src/main.rs +++ b/packages/fullstack/examples/warp-hello-world/src/main.rs @@ -60,9 +60,9 @@ async fn get_server_data() -> Result { fn main() { #[cfg(feature = "web")] - wasm_logger::init(wasm_logger::Config::new(log::Level::Trace)); + tracing_wasm::set_as_global_default(); #[cfg(feature = "ssr")] - simple_logger::SimpleLogger::new().init().unwrap(); + tracing_subscriber::fmt::init(); LaunchBuilder::new_with_props(app, AppProps { count: 0 }).launch() } diff --git a/packages/fullstack/src/adapters/axum_adapter.rs b/packages/fullstack/src/adapters/axum_adapter.rs index 330d15bc3..95d9ee6cd 100644 --- a/packages/fullstack/src/adapters/axum_adapter.rs +++ b/packages/fullstack/src/adapters/axum_adapter.rs @@ -263,8 +263,8 @@ where let res = service.run(req); match res.await { Ok(res) => Ok::<_, std::convert::Infallible>(res.map(|b| b.into())), - Err(_e) => { - let mut res = Response::new(Body::empty()); + Err(e) => { + let mut res = Response::new(Body::from(e.to_string())); *res.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; Ok(res) } @@ -389,7 +389,7 @@ pub async fn render_handler response } Err(e) => { - log::error!("Failed to render page: {}", e); + tracing::error!("Failed to render page: {}", e); report_err(e).into_response() } } diff --git a/packages/fullstack/src/adapters/salvo_adapter.rs b/packages/fullstack/src/adapters/salvo_adapter.rs index 671128b65..674722665 100644 --- a/packages/fullstack/src/adapters/salvo_adapter.rs +++ b/packages/fullstack/src/adapters/salvo_adapter.rs @@ -423,7 +423,7 @@ impl Handler for SSRHandler freshness.write(res.headers_mut()); } Err(err) => { - log::error!("Error rendering SSR: {}", err); + tracing::error!("Error rendering SSR: {}", err); res.write_body("Error rendering SSR").unwrap(); } }; diff --git a/packages/fullstack/src/adapters/warp_adapter.rs b/packages/fullstack/src/adapters/warp_adapter.rs index 723314ca3..316d70e56 100644 --- a/packages/fullstack/src/adapters/warp_adapter.rs +++ b/packages/fullstack/src/adapters/warp_adapter.rs @@ -84,7 +84,7 @@ use warp::{ /// async move { /// let req = warp::hyper::Request::from_parts(parts, bytes.into()); /// service.run(req).await.map_err(|err| { -/// log::error!("Server function error: {}", err); +/// tracing::error!("Server function error: {}", err); /// warp::reject::reject() /// }) /// } @@ -142,8 +142,18 @@ pub fn register_server_fns(server_fn_route: &'static str) -> BoxedFilter<(impl R async move { let req = warp::hyper::Request::from_parts(parts, bytes.into()); service.run(req).await.map_err(|err| { - log::error!("Server function error: {}", err); - warp::reject::reject() + tracing::error!("Server function error: {}", err); + + struct WarpServerFnError(String); + impl std::fmt::Debug for WarpServerFnError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.0) + } + } + + impl warp::reject::Reject for WarpServerFnError {} + + warp::reject::custom(WarpServerFnError(err.to_string())) }) } }) @@ -222,7 +232,7 @@ pub fn render_ssr( res } Err(err) => { - log::error!("Failed to render ssr: {}", err); + tracing::error!("Failed to render ssr: {}", err); Response::builder() .status(500) .body("Failed to render ssr".into()) diff --git a/packages/fullstack/src/hooks/server_cached.rs b/packages/fullstack/src/hooks/server_cached.rs index 80bb93008..519f70dae 100644 --- a/packages/fullstack/src/hooks/server_cached.rs +++ b/packages/fullstack/src/hooks/server_cached.rs @@ -23,7 +23,7 @@ pub fn server_cached(server_fn: impl let data = server_fn(); let sc = crate::prelude::server_context(); if let Err(err) = sc.push_html_data(&data) { - log::error!("Failed to push HTML data: {}", err); + tracing::error!("Failed to push HTML data: {}", err); } data } diff --git a/packages/fullstack/src/hooks/server_future.rs b/packages/fullstack/src/hooks/server_future.rs index 9a13df235..e4d89480e 100644 --- a/packages/fullstack/src/hooks/server_future.rs +++ b/packages/fullstack/src/hooks/server_future.rs @@ -47,13 +47,13 @@ where if first_run { match crate::html_storage::deserialize::take_server_data() { Some(data) => { - log::trace!("Loaded {data:?} from server"); + tracing::trace!("Loaded {data:?} from server"); *state.value.borrow_mut() = Some(Box::new(data)); state.needs_regen.set(false); return Some(state); } None => { - log::trace!("Failed to load from server... running future"); + tracing::trace!("Failed to load from server... running future"); } }; } @@ -82,7 +82,7 @@ where data = fut.await; if first_run { if let Err(err) = crate::prelude::server_context().push_html_data(&data) { - log::error!("Failed to push HTML data: {}", err); + tracing::error!("Failed to push HTML data: {}", err); }; } } @@ -99,7 +99,7 @@ where if first_run { #[cfg(feature = "ssr")] { - log::trace!("Suspending first run of use_server_future"); + tracing::trace!("Suspending first run of use_server_future"); cx.suspend(); } None diff --git a/packages/fullstack/src/hot_reload.rs b/packages/fullstack/src/hot_reload.rs index b94df4811..87f219df8 100644 --- a/packages/fullstack/src/hot_reload.rs +++ b/packages/fullstack/src/hot_reload.rs @@ -30,7 +30,7 @@ impl Default for HotReloadState { } if let Err(err) = tx.send(Some(template)) { - log::error!("Failed to send hot reload message: {}", err); + tracing::error!("Failed to send hot reload message: {}", err); } } dioxus_hot_reload::HotReloadMsg::Shutdown => { diff --git a/packages/fullstack/src/html_storage/deserialize.rs b/packages/fullstack/src/html_storage/deserialize.rs index 822b45076..7fc70ba6c 100644 --- a/packages/fullstack/src/html_storage/deserialize.rs +++ b/packages/fullstack/src/html_storage/deserialize.rs @@ -10,7 +10,7 @@ pub(crate) fn serde_from_bytes(string: &[u8]) -> Option let decompressed = match STANDARD.decode(string) { Ok(bytes) => bytes, Err(err) => { - log::error!("Failed to decode base64: {}", err); + tracing::error!("Failed to decode base64: {}", err); return None; } }; @@ -18,7 +18,7 @@ pub(crate) fn serde_from_bytes(string: &[u8]) -> Option match postcard::from_bytes(&decompressed) { Ok(data) => Some(data), Err(err) => { - log::error!("Failed to deserialize: {}", err); + tracing::error!("Failed to deserialize: {}", err); None } } @@ -32,14 +32,14 @@ static SERVER_DATA: once_cell::sync::Lazy> = let element = match window.get_element_by_id("dioxus-storage-data") { Some(element) => element, None => { - log::error!("Failed to get element by id: dioxus-storage-data"); + tracing::error!("Failed to get element by id: dioxus-storage-data"); return None; } }; let attribute = match element.get_attribute("data-serialized") { Some(attribute) => attribute, None => { - log::error!("Failed to get attribute: data-serialized"); + tracing::error!("Failed to get attribute: data-serialized"); return None; } }; diff --git a/packages/fullstack/src/html_storage/mod.rs b/packages/fullstack/src/html_storage/mod.rs index 2d64953ae..5b4d2804f 100644 --- a/packages/fullstack/src/html_storage/mod.rs +++ b/packages/fullstack/src/html_storage/mod.rs @@ -36,7 +36,7 @@ impl HTMLDataCursor { pub fn take(&self) -> Option { let current = self.index.load(std::sync::atomic::Ordering::SeqCst); if current >= self.data.len() { - log::error!( + tracing::error!( "Tried to take more data than was available, len: {}, index: {}", self.data.len(), current @@ -48,7 +48,7 @@ impl HTMLDataCursor { match postcard::from_bytes(cursor) { Ok(x) => Some(x), Err(e) => { - log::error!("Error deserializing data: {:?}", e); + tracing::error!("Error deserializing data: {:?}", e); None } } diff --git a/packages/fullstack/src/layer.rs b/packages/fullstack/src/layer.rs index cf5633db2..10e67b3f5 100644 --- a/packages/fullstack/src/layer.rs +++ b/packages/fullstack/src/layer.rs @@ -1,4 +1,5 @@ use std::pin::Pin; +use tracing_futures::Instrument; use http::{Request, Response}; @@ -45,7 +46,11 @@ where > + Send, >, > { - let fut = self.call(req); + let fut = self.call(req).instrument(tracing::trace_span!( + "service", + "{}", + std::any::type_name::() + )); Box::pin(async move { fut.await.map_err(|err| err.into()) }) } } diff --git a/packages/fullstack/src/render.rs b/packages/fullstack/src/render.rs index d389fa54e..cda41f82c 100644 --- a/packages/fullstack/src/render.rs +++ b/packages/fullstack/src/render.rs @@ -50,10 +50,10 @@ impl SsrRendererPool { let prev_context = SERVER_CONTEXT.with(|ctx| ctx.replace(server_context)); // poll the future, which may call server_context() - log::info!("Rebuilding vdom"); + tracing::info!("Rebuilding vdom"); let _ = vdom.rebuild(); vdom.wait_for_suspense().await; - log::info!("Suspense resolved"); + tracing::info!("Suspense resolved"); // after polling the future, we need to restore the context SERVER_CONTEXT.with(|ctx| ctx.replace(prev_context)); @@ -116,10 +116,10 @@ impl SsrRendererPool { let prev_context = SERVER_CONTEXT .with(|ctx| ctx.replace(Box::new(server_context))); // poll the future, which may call server_context() - log::info!("Rebuilding vdom"); + tracing::info!("Rebuilding vdom"); let _ = vdom.rebuild(); vdom.wait_for_suspense().await; - log::info!("Suspense resolved"); + tracing::info!("Suspense resolved"); // after polling the future, we need to restore the context SERVER_CONTEXT.with(|ctx| ctx.replace(prev_context)); }) diff --git a/packages/fullstack/src/router.rs b/packages/fullstack/src/router.rs index eee282c01..b556aa000 100644 --- a/packages/fullstack/src/router.rs +++ b/packages/fullstack/src/router.rs @@ -29,7 +29,7 @@ where .to_string() .parse() .unwrap_or_else(|err| { - log::error!("Failed to parse uri: {}", err); + tracing::error!("Failed to parse uri: {}", err); "/" .parse() .unwrap_or_else(|err| { diff --git a/packages/hooks/Cargo.toml b/packages/hooks/Cargo.toml index caa25cb1e..bf07389ff 100644 --- a/packages/hooks/Cargo.toml +++ b/packages/hooks/Cargo.toml @@ -16,7 +16,7 @@ nightly-features = [] [dependencies] dioxus-core = { workspace = true } futures-channel = { workspace = true } -log = { workspace = true } +tracing = { workspace = true } thiserror = { workspace = true } slab = { workspace = true } dioxus-debug-cell = "0.1.1" diff --git a/packages/hooks/README.md b/packages/hooks/README.md index 6c77867de..932847b53 100644 --- a/packages/hooks/README.md +++ b/packages/hooks/README.md @@ -1,6 +1,5 @@ # Dioxus Hooks - [![Crates.io][crates-badge]][crates-url] [![MIT licensed][mit-badge]][mit-url] [![Build Status][actions-badge]][actions-url] @@ -8,22 +7,18 @@ [crates-badge]: https://img.shields.io/crates/v/dioxus-hooks.svg [crates-url]: https://crates.io/crates/dioxus-hooks - [mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg [mit-url]: https://github.com/dioxuslabs/dioxus/blob/master/LICENSE - [actions-badge]: https://github.com/dioxuslabs/dioxus/actions/workflows/main.yml/badge.svg [actions-url]: https://github.com/dioxuslabs/dioxus/actions?query=workflow%3ACI+branch%3Amaster - [discord-badge]: https://img.shields.io/discord/899851952891002890.svg?logo=discord&style=flat-square [discord-url]: https://discord.gg/XgGxMSkvUM [Website](https://dioxuslabs.com) | -[Guides](https://dioxuslabs.com/docs/0.3/guide/en/) | +[Guides](https://dioxuslabs.com/learn/0.4/) | [API Docs](https://docs.rs/dioxus-hooks/latest/dioxus_hooks) | [Chat](https://discord.gg/XgGxMSkvUM) - ## Overview `dioxus-hooks` includes some basic useful hooks for dioxus: @@ -42,13 +37,13 @@ This crate also provides a few helpful macros to get around some Rust lifetime m - `use_future!()` - `use_callback!()` - ## Contributing - Report issues on our [issue tracker](https://github.com/dioxuslabs/dioxus/issues). - Join the discord and ask questions! ## License + This project is licensed under the [MIT license]. [mit license]: https://github.com/DioxusLabs/dioxus/blob/master/LICENSE-MIT diff --git a/packages/hooks/src/computed.rs b/packages/hooks/src/computed.rs index 1fcad8bb0..3369d6832 100644 --- a/packages/hooks/src/computed.rs +++ b/packages/hooks/src/computed.rs @@ -17,6 +17,7 @@ use std::{ /// ```rust /// use dioxus::prelude::*; /// +/// #[component] /// fn Parent(cx: Scope) -> Element { /// let count = use_tracked_state(cx, || 0); /// @@ -27,7 +28,7 @@ use std::{ /// } /// } /// -/// #[inline_props] +/// #[component] /// fn Child(cx: Scope, count: Tracked) -> Element { /// let less_than_five = use_selector(cx, count, |count| *count < 5); /// diff --git a/packages/hooks/src/use_shared_state.rs b/packages/hooks/src/use_shared_state.rs index b900b9dc6..18ce1e5f1 100644 --- a/packages/hooks/src/use_shared_state.rs +++ b/packages/hooks/src/use_shared_state.rs @@ -81,10 +81,12 @@ pub(crate) struct ProvidedStateInner { value: T, notify_any: Arc, consumers: HashSet, + gen: usize, } impl ProvidedStateInner { pub(crate) fn notify_consumers(&mut self) { + self.gen += 1; for consumer in self.consumers.iter() { (self.notify_any)(*consumer); } @@ -157,7 +159,7 @@ impl ProvidedStateInner { /// /// Right now, there is not a distinction between read-only and write-only, so every consumer will be notified. pub fn use_shared_state(cx: &ScopeState) -> Option<&UseSharedState> { - let state: &Option> = &*cx.use_hook(move || { + let state_owner: &mut Option> = &mut *cx.use_hook(move || { let scope_id = cx.scope_id(); let root = cx.consume_context::>()?; @@ -167,7 +169,10 @@ pub fn use_shared_state(cx: &ScopeState) -> Option<&UseSharedState Drop for UseSharedStateOwner { /// State that is shared between components through the context system pub struct UseSharedState { pub(crate) inner: Rc>>, + gen: usize, } impl UseSharedState { fn new(inner: Rc>>) -> Self { - Self { inner } + let gen = inner.borrow().gen; + Self { inner, gen } } /// Notify all consumers of the state that it has changed. (This is called automatically when you call "write") @@ -302,15 +309,14 @@ impl Clone for UseSharedState { fn clone(&self) -> Self { Self { inner: self.inner.clone(), + gen: self.gen, } } } -impl PartialEq for UseSharedState { +impl PartialEq for UseSharedState { fn eq(&self, other: &Self) -> bool { - let first = self.inner.borrow(); - let second = other.inner.borrow(); - first.value == second.value + self.gen == other.gen } } @@ -360,6 +366,7 @@ pub fn use_shared_state_provider(cx: &ScopeState, f: impl FnOnce() - value: f(), notify_any: cx.schedule_update_any(), consumers: HashSet::new(), + gen: 0, })); cx.provide_context(state); diff --git a/packages/hooks/src/useeffect.rs b/packages/hooks/src/useeffect.rs index aec1f9c9a..76a3f5245 100644 --- a/packages/hooks/src/useeffect.rs +++ b/packages/hooks/src/useeffect.rs @@ -14,7 +14,8 @@ use crate::UseFutureDep; /// ## Examples /// /// ```rust, no_run -/// #[inline_props] +/// # use dioxus::prelude::*; +/// #[component] /// fn Profile(cx: Scope, id: usize) -> Element { /// let name = use_state(cx, || None); /// @@ -34,7 +35,8 @@ use crate::UseFutureDep; /// ) /// } /// -/// fn app(cx: Scope) -> Element { +/// #[component] +/// fn App(cx: Scope) -> Element { /// render!(Profile { id: 0 }) /// } /// ``` diff --git a/packages/hooks/src/usefuture.rs b/packages/hooks/src/usefuture.rs index 6692e2d3b..67bcdc74e 100644 --- a/packages/hooks/src/usefuture.rs +++ b/packages/hooks/src/usefuture.rs @@ -14,7 +14,7 @@ use crate::{use_state, UseState}; /// /// Whenever the hooks dependencies change, the future will be re-evaluated. /// If a future is pending when the dependencies change, the previous future -/// will be allowed to continue +/// will be canceled before the new one is started. /// /// - dependencies: a tuple of references to values that are PartialEq + Clone pub fn use_future( diff --git a/packages/hooks/src/usememo.rs b/packages/hooks/src/usememo.rs index d3d991ccc..3181d57b8 100644 --- a/packages/hooks/src/usememo.rs +++ b/packages/hooks/src/usememo.rs @@ -10,8 +10,9 @@ use crate::UseFutureDep; /// ## Examples /// /// ```rust, no_run +/// # use dioxus::prelude::*; /// -/// #[inline_props] +/// #[component] /// fn Calculator(cx: Scope, number: usize) -> Element { /// let bigger_number = use_memo(cx, (number,), |(number,)| { /// // This will only be calculated when `number` has changed. @@ -21,7 +22,9 @@ use crate::UseFutureDep; /// p { "{bigger_number}" } /// ) /// } -/// fn app(cx: Scope) -> Element { +/// +/// #[component] +/// fn App(cx: Scope) -> Element { /// render!(Calculator { number: 0 }) /// } /// ``` diff --git a/packages/hot-reload/Cargo.toml b/packages/hot-reload/Cargo.toml index 38eecc8bd..b724ad685 100644 --- a/packages/hot-reload/Cargo.toml +++ b/packages/hot-reload/Cargo.toml @@ -5,7 +5,7 @@ version = { workspace = true } edition = "2021" license = "MIT OR Apache-2.0" repository = "https://github.com/DioxusLabs/dioxus/" -homepage = "https://dioxuslabs.com/docs/0.3/guide/en/getting_started/hot_reload.html" +homepage = "https://dioxuslabs.com/learn/0.4/migration/hot_reload" description = "Hot reloading utilities for Dioxus" keywords = ["dom", "ui", "gui", "react", "hot-reloading"] diff --git a/packages/hot-reload/README.md b/packages/hot-reload/README.md index 60b7b9c87..d7418d4b1 100644 --- a/packages/hot-reload/README.md +++ b/packages/hot-reload/README.md @@ -1,6 +1,5 @@ # `dioxus-hot-reload`: Hot Reloading Utilites for Dioxus - [![Crates.io][crates-badge]][crates-url] [![MIT licensed][mit-badge]][mit-url] [![Build Status][actions-badge]][actions-url] @@ -8,28 +7,24 @@ [crates-badge]: https://img.shields.io/crates/v/dioxus-hot-reload.svg [crates-url]: https://crates.io/crates/dioxus-hot-reload - [mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg [mit-url]: https://github.com/dioxuslabs/dioxus/blob/master/LICENSE - [actions-badge]: https://github.com/dioxuslabs/dioxus/actions/workflows/main.yml/badge.svg [actions-url]: https://github.com/dioxuslabs/dioxus/actions?query=workflow%3ACI+branch%3Amaster - [discord-badge]: https://img.shields.io/discord/899851952891002890.svg?logo=discord&style=flat-square [discord-url]: https://discord.gg/XgGxMSkvUM [Website](https://dioxuslabs.com) | -[Guides](https://dioxuslabs.com/docs/0.3/guide/en) | +[Guides](https://dioxuslabs.com/learn/0.4/) | [API Docs](https://docs.rs/dioxus-hot-reload/latest/dioxus_hot_reload) | [Chat](https://discord.gg/XgGxMSkvUM) - ## Overview Dioxus supports hot reloading for static parts of rsx macros. This enables changing the styling of your application without recompiling the rust code. This is useful for rapid iteration on the styling of your application. - Hot reloading could update the following change without recompiling: + ```rust rsx! { div { @@ -37,7 +32,9 @@ rsx! { } } ``` + => + ```rust rsx! { div { @@ -49,6 +46,7 @@ rsx! { ``` But it could not update the following change: + ```rust rsx! { div { @@ -56,7 +54,9 @@ rsx! { } } ``` + => + ```rust rsx! { div { @@ -161,6 +161,7 @@ async fn launch(app: Component) { - Join the discord and ask questions! ## License + This project is licensed under the [MIT license]. [mit license]: https://github.com/DioxusLabs/dioxus/blob/master/LICENSE-MIT diff --git a/packages/html/README.md b/packages/html/README.md index 59ec2f9ff..93733116c 100644 --- a/packages/html/README.md +++ b/packages/html/README.md @@ -1,6 +1,5 @@ # `dioxus-html`: Html (and SVG) Namespace for Dioxus - [![Crates.io][crates-badge]][crates-url] [![MIT licensed][mit-badge]][mit-url] [![Build Status][actions-badge]][actions-url] @@ -8,22 +7,18 @@ [crates-badge]: https://img.shields.io/crates/v/dioxus-html.svg [crates-url]: https://crates.io/crates/dioxus-html - [mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg [mit-url]: https://github.com/dioxuslabs/dioxus/blob/master/LICENSE - [actions-badge]: https://github.com/dioxuslabs/dioxus/actions/workflows/main.yml/badge.svg [actions-url]: https://github.com/dioxuslabs/dioxus/actions?query=workflow%3ACI+branch%3Amaster - [discord-badge]: https://img.shields.io/discord/899851952891002890.svg?logo=discord&style=flat-square [discord-url]: https://discord.gg/XgGxMSkvUM [Website](https://dioxuslabs.com) | -[Guides](https://dioxuslabs.com/docs/0.3/guide/en/) | +[Guides](https://dioxuslabs.com/learn/0.4/) | [API Docs](https://docs.rs/dioxus-html/latest/dioxus_html) | [Chat](https://discord.gg/XgGxMSkvUM) - ## Overview The Dioxus `rsx!` and `html!` macros can accept any compile-time correct namespace on top of NodeFactory. This crate provides the HTML (and SVG) namespaces which get imported in the Dioxus prelude. @@ -64,6 +59,7 @@ All elements should be defined as a zero-sized-struct (also known as unit struct Attributes would then be implemented as constants on these unit structs. The HTML namespace is defined mostly with macros. However, the expanded form would look something like this: + ```rust struct base; impl DioxusElement for base { @@ -75,8 +71,8 @@ impl base { const target: (&'static str, Option<'static str>, bool) = ("target", None, false); } ``` -Because attributes are defined as methods on the unit struct, they guard the attribute creation behind a compile-time correct interface. +Because attributes are defined as methods on the unit struct, they guard the attribute creation behind a compile-time correct interface. ## How to extend it: @@ -93,16 +89,13 @@ mod dioxus_elements { } ``` - - - - ## Contributing - Report issues on our [issue tracker](https://github.com/dioxuslabs/dioxus/issues). - Join the discord and ask questions! ## License + This project is licensed under the [MIT license]. [mit license]: https://github.com/DioxusLabs/dioxus/blob/master/LICENSE-MIT diff --git a/packages/html/src/elements.rs b/packages/html/src/elements.rs index 7e5bed124..7800369a9 100644 --- a/packages/html/src/elements.rs +++ b/packages/html/src/elements.rs @@ -1258,6 +1258,8 @@ builder_constructors! { spellcheck: BoolOrDefault DEFAULT, wrap: Wrap DEFAULT, value: String volatile, + + initial_value: String DEFAULT, }; diff --git a/packages/html/src/events/mouse.rs b/packages/html/src/events/mouse.rs index 7899393ff..55d081900 100644 --- a/packages/html/src/events/mouse.rs +++ b/packages/html/src/events/mouse.rs @@ -108,7 +108,7 @@ impl_event! { /// /// ## Example /// ```rust, ignore - /// rsx!( button { "click me", onclick: move |_| log::info!("Clicked!`") } ) + /// rsx!( button { "click me", onclick: move |_| tracing::info!("Clicked!`") } ) /// ``` /// /// ## Reference diff --git a/packages/interpreter/README.md b/packages/interpreter/README.md index 90e390f56..0c195d681 100644 --- a/packages/interpreter/README.md +++ b/packages/interpreter/README.md @@ -1,6 +1,5 @@ # `dioxus-interpreter-js` - [![Crates.io][crates-badge]][crates-url] [![MIT licensed][mit-badge]][mit-url] [![Build Status][actions-badge]][actions-url] @@ -8,35 +7,31 @@ [crates-badge]: https://img.shields.io/crates/v/dioxus-interpreter-js.svg [crates-url]: https://crates.io/crates/dioxus-interpreter-js - [mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg [mit-url]: https://github.com/dioxuslabs/dioxus/blob/master/LICENSE - [actions-badge]: https://github.com/dioxuslabs/dioxus/actions/workflows/main.yml/badge.svg [actions-url]: https://github.com/dioxuslabs/dioxus/actions?query=workflow%3ACI+branch%3Amaster - [discord-badge]: https://img.shields.io/discord/899851952891002890.svg?logo=discord&style=flat-square [discord-url]: https://discord.gg/XgGxMSkvUM [Website](https://dioxuslabs.com) | -[Guides](https://dioxuslabs.com/docs/0.3/guide/en/) | +[Guides](https://dioxuslabs.com/learn/0.4/) | [API Docs](https://docs.rs/dioxus-interpreter-js/latest/dioxus_interpreter_js) | [Chat](https://discord.gg/XgGxMSkvUM) - ## Overview `dioxus-interpreter-js` provides the high-performance JavaScript glue that interprets the stream of edits produced by the Dioxus VirtualDom and converts them into mutations on the actual web DOM. This crate features bindings for the web and sledgehammer for increased performance. - ## Contributing - Report issues on our [issue tracker](https://github.com/dioxuslabs/dioxus/issues). - Join the discord and ask questions! ## License + This project is licensed under the [MIT license]. [mit license]: https://github.com/DioxusLabs/dioxus/blob/master/LICENSE-MIT diff --git a/packages/interpreter/src/interpreter.js b/packages/interpreter/src/interpreter.js index 0a041df27..a03983ffa 100644 --- a/packages/interpreter/src/interpreter.js +++ b/packages/interpreter/src/interpreter.js @@ -390,7 +390,11 @@ class Interpreter { function handler(event, name, bubbles, config) { let target = event.target; if (target != null) { - let preventDefaultRequests = target.getAttribute(`dioxus-prevent-default`); + let preventDefaultRequests = null; + // Some events can be triggered on text nodes, which don't have attributes + if (target instanceof Element) { + preventDefaultRequests = target.getAttribute(`dioxus-prevent-default`); + } if (event.type === "click") { // todo call prevent default if it's the right type of event @@ -446,15 +450,24 @@ function handler(event, name, bubbles, config) { target.tagName === "FORM" && (event.type === "submit" || event.type === "input") ) { - if ( - target.tagName === "FORM" && - (event.type === "submit" || event.type === "input") - ) { - const formData = new FormData(target); + const formData = new FormData(target); - for (let name of formData.keys()) { - let value = formData.getAll(name); - contents.values[name] = value; + for (let name of formData.keys()) { + let value = formData.getAll(name); + contents.values[name] = value; + } + } + + if ( + target.tagName === "SELECT" && + event.type === "input" + ) { + const selectData = target.options; + contents.values["options"] = []; + for (let i = 0; i < selectData.length; i++) { + let option = selectData[i]; + if (option.selected) { + contents.values["options"].push(option.value.toString()); } } } @@ -474,7 +487,10 @@ function handler(event, name, bubbles, config) { } function find_real_id(target) { - let realId = target.getAttribute(`data-dioxus-id`); + let realId = null; + if (target instanceof Element) { + realId = target.getAttribute(`data-dioxus-id`); + } // walk the tree to find the real element while (realId == null) { // we've reached the root we don't want to send an event @@ -483,7 +499,9 @@ function find_real_id(target) { } target = target.parentElement; - realId = target.getAttribute(`data-dioxus-id`); + if (target instanceof Element) { + realId = target.getAttribute(`data-dioxus-id`); + } } return realId; } diff --git a/packages/liveview/Cargo.toml b/packages/liveview/Cargo.toml index 3dfce5bf4..cbd7b75f5 100644 --- a/packages/liveview/Cargo.toml +++ b/packages/liveview/Cargo.toml @@ -3,7 +3,7 @@ name = "dioxus-liveview" version = { workspace = true } edition = "2021" repository = "https://github.com/DioxusLabs/dioxus/" -homepage = "https://dioxuslabs.com/docs/0.3/guide/en/getting_started/liveview.html" +homepage = "https://dioxuslabs.com/learn/0.4/getting_started/liveview" keywords = ["dom", "ui", "gui", "react", "liveview"] description = "Build server-side apps with Dioxus" authors = ["Jonathan Kelley", "Evan Almloff"] @@ -11,7 +11,7 @@ license = "MIT OR Apache-2.0" [dependencies] thiserror = { workspace = true } -log = { workspace = true } +tracing = { workspace = true } slab = { workspace = true } futures-util = { workspace = true, default-features = false, features = [ "sink", diff --git a/packages/liveview/README.md b/packages/liveview/README.md index 0a0e7de3a..cbae3c53a 100644 --- a/packages/liveview/README.md +++ b/packages/liveview/README.md @@ -1,6 +1,5 @@ # Dioxus Liveview - [![Crates.io][crates-badge]][crates-url] [![MIT licensed][mit-badge]][mit-url] [![Build Status][actions-badge]][actions-url] @@ -8,22 +7,18 @@ [crates-badge]: https://img.shields.io/crates/v/dioxus-liveview.svg [crates-url]: https://crates.io/crates/dioxus-liveview - [mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg [mit-url]: https://github.com/dioxuslabs/dioxus/blob/master/LICENSE - [actions-badge]: https://github.com/dioxuslabs/dioxus/actions/workflows/main.yml/badge.svg [actions-url]: https://github.com/dioxuslabs/dioxus/actions?query=workflow%3ACI+branch%3Amaster - [discord-badge]: https://img.shields.io/discord/899851952891002890.svg?logo=discord&style=flat-square [discord-url]: https://discord.gg/XgGxMSkvUM [Website](https://dioxuslabs.com) | -[Guides](https://dioxuslabs.com/docs/0.3/guide/en/) | +[Guides](https://dioxuslabs.com/learn/0.4/) | [API Docs](https://docs.rs/dioxus-liveview/latest/dioxus_liveview) | [Chat](https://discord.gg/XgGxMSkvUM) - ## Overview `dioxus-liveview` provides adapters for running the Dioxus VirtualDom over a WebSocket connection. @@ -46,6 +41,7 @@ Dioxus-LiveView exports some primitives to wire up an app into an existing backe - Join the discord and ask questions! ## License + This project is licensed under the [MIT license]. [mit license]: https://github.com/DioxusLabs/dioxus/blob/master/LICENSE-MIT diff --git a/packages/liveview/src/query.rs b/packages/liveview/src/query.rs index 8052c2afa..a638625c1 100644 --- a/packages/liveview/src/query.rs +++ b/packages/liveview/src/query.rs @@ -126,7 +126,7 @@ impl QueryEngine { }}) }})();"# )) { - log::warn!("Query error: {err}"); + tracing::warn!("Query error: {err}"); } Query { diff --git a/packages/mobile/Cargo.toml b/packages/mobile/Cargo.toml index 9c6d51270..c0d84c8d4 100644 --- a/packages/mobile/Cargo.toml +++ b/packages/mobile/Cargo.toml @@ -5,7 +5,7 @@ authors = ["Jonathan Kelley"] edition = "2018" description = "Mobile-compatible renderer for Dioxus" repository = "https://github.com/DioxusLabs/dioxus/" -homepage = "https://dioxuslabs.com/docs/0.3/guide/en/getting_started/mobile.html" +homepage = "https://dioxuslabs.com/learn/0.4/getting_started/mobile" keywords = ["dom", "ui", "gui", "react"] license = "MIT OR Apache-2.0" diff --git a/packages/mobile/README.md b/packages/mobile/README.md index 46da9061a..611348da5 100644 --- a/packages/mobile/README.md +++ b/packages/mobile/README.md @@ -7,29 +7,24 @@ [crates-badge]: https://img.shields.io/crates/v/dioxus-mobile.svg [crates-url]: https://crates.io/crates/dioxus-mobile - [mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg [mit-url]: https://github.com/dioxuslabs/dioxus/blob/master/LICENSE - [actions-badge]: https://github.com/dioxuslabs/dioxus/actions/workflows/main.yml/badge.svg [actions-url]: https://github.com/dioxuslabs/dioxus/actions?query=workflow%3ACI+branch%3Amaster - [discord-badge]: https://img.shields.io/discord/899851952891002890.svg?logo=discord&style=flat-square [discord-url]: https://discord.gg/XgGxMSkvUM [Website](https://dioxuslabs.com) | -[Guides](https://dioxuslabs.com/docs/0.3/guide/en/) | +[Guides](https://dioxuslabs.com/learn/0.4/) | [API Docs](https://docs.rs/dioxus-mobile/latest/dioxus_mobile) | [Chat](https://discord.gg/XgGxMSkvUM) - ## Overview `dioxus-mobile` is a re-export of `dioxus-desktop` with some minor tweaks and documentation changes. As this crate evolves, it will provide some more unique features to mobile, but for now, it's very similar to the desktop crate. Dioxus Mobile supports both iOS and Android. However, Android support is still quite experimental and requires a lot of configuration. A good area to contribute here would be to improve the CLI tool to include bundling and mobile configuration. - ## Getting Set up Getting set up with mobile can but 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. @@ -40,7 +35,6 @@ We're going to be using `cargo-mobile` to build for mobile. First, install it: $ 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 @@ -98,9 +92,7 @@ To configure the web view, menubar, and other important desktop-specific feature ## Future Steps -Make sure to read the [Dioxus Guide](https://dioxuslabs.com/docs/0.3/guide/en) if you already haven't! - - +Make sure to read the [Dioxus Guide](https://dioxuslabs.com/learn/0.4/) if you already haven't! ## Contributing @@ -108,6 +100,7 @@ Make sure to read the [Dioxus Guide](https://dioxuslabs.com/docs/0.3/guide/en) i - Join the discord and ask questions! ## License + This project is licensed under the [MIT license]. [mit license]: https://github.com/DioxusLabs/dioxus/blob/master/LICENSE-MIT diff --git a/packages/native-core-macro/README.md b/packages/native-core-macro/README.md index 6b8c13590..4cf19cece 100644 --- a/packages/native-core-macro/README.md +++ b/packages/native-core-macro/README.md @@ -7,33 +7,29 @@ [crates-badge]: https://img.shields.io/crates/v/dioxus-native-core-macro.svg [crates-url]: https://crates.io/crates/dioxus-native-core-macro - [mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg [mit-url]: https://github.com/dioxuslabs/dioxus/blob/master/LICENSE - [actions-badge]: https://github.com/dioxuslabs/dioxus/actions/workflows/main.yml/badge.svg [actions-url]: https://github.com/dioxuslabs/dioxus/actions?query=workflow%3ACI+branch%3Amaster - [discord-badge]: https://img.shields.io/discord/899851952891002890.svg?logo=discord&style=flat-square [discord-url]: https://discord.gg/XgGxMSkvUM [Website](https://dioxuslabs.com) | -[Guides](https://dioxuslabs.com/docs/0.3/guide/en/) | +[Guides](https://dioxuslabs.com/learn/0.4/) | [API Docs](https://docs.rs/dioxus-native-core-macro/latest/dioxus_native_core_macro) | [Chat](https://discord.gg/XgGxMSkvUM) - ## Overview `dioxus-native-core-macro` provides a handful of macros used by native-core for native renderers like TUI, Blitz, and Freya to derive their state. - ## Contributing - Report issues on our [issue tracker](https://github.com/dioxuslabs/dioxus/issues). - Join the discord and ask questions! ## License + This project is licensed under the [MIT license]. [mit license]: https://github.com/DioxusLabs/dioxus/blob/master/LICENSE-MIT diff --git a/packages/router-macro/src/lib.rs b/packages/router-macro/src/lib.rs index c949cf2f4..b1ff7b0fe 100644 --- a/packages/router-macro/src/lib.rs +++ b/packages/router-macro/src/lib.rs @@ -210,7 +210,7 @@ pub fn routable(input: TokenStream) -> TokenStream { let display_impl = route_enum.impl_display(); let routable_impl = route_enum.routable_impl(); - quote! { + (quote! { #error_type #display_impl @@ -218,7 +218,7 @@ pub fn routable(input: TokenStream) -> TokenStream { #routable_impl #parse_impl - } + }) .into() } @@ -482,7 +482,8 @@ impl RouteEnum { let route = s; let (route, _hash) = route.split_once('#').unwrap_or((route, "")); let (route, query) = route.split_once('?').unwrap_or((route, "")); - let mut segments = route.split('/'); + let query = dioxus_router::exports::urlencoding::decode(query).unwrap_or(query.into()); + let mut segments = route.split('/').map(|s| dioxus_router::exports::urlencoding::decode(s).unwrap_or(s.into())); // skip the first empty segment if s.starts_with('/') { let _ = segments.next(); @@ -677,9 +678,9 @@ impl ToTokens for SegmentType { impl<'a> From<&'a RouteSegment> for SegmentType { fn from(value: &'a RouteSegment) -> Self { match value { - segment::RouteSegment::Static(s) => SegmentType::Static(s.to_string()), - segment::RouteSegment::Dynamic(s, _) => SegmentType::Dynamic(s.to_string()), - segment::RouteSegment::CatchAll(s, _) => SegmentType::CatchAll(s.to_string()), + RouteSegment::Static(s) => SegmentType::Static(s.to_string()), + RouteSegment::Dynamic(s, _) => SegmentType::Dynamic(s.to_string()), + RouteSegment::CatchAll(s, _) => SegmentType::CatchAll(s.to_string()), } } } diff --git a/packages/router-macro/src/query.rs b/packages/router-macro/src/query.rs index 8b9db9e51..c97d3be29 100644 --- a/packages/router-macro/src/query.rs +++ b/packages/router-macro/src/query.rs @@ -14,7 +14,7 @@ impl QuerySegment { let ident = &self.ident; let ty = &self.ty; quote! { - let #ident = <#ty as dioxus_router::routable::FromQuery>::from_query(query); + let #ident = <#ty as dioxus_router::routable::FromQuery>::from_query(&*query); } } diff --git a/packages/router-macro/src/route.rs b/packages/router-macro/src/route.rs index b070c2013..26665e575 100644 --- a/packages/router-macro/src/route.rs +++ b/packages/router-macro/src/route.rs @@ -277,10 +277,8 @@ impl Route { } } for segment in &self.segments { - if let RouteSegment::Dynamic(other, ..) = segment { - if other == name { - from_route = true - } + if segment.name().as_ref() == Some(name) { + from_route = true } } if let Some(query) = &self.query { diff --git a/packages/router-macro/src/route_tree.rs b/packages/router-macro/src/route_tree.rs index 399d20e5e..6b89c80ab 100644 --- a/packages/router-macro/src/route_tree.rs +++ b/packages/router-macro/src/route_tree.rs @@ -312,7 +312,8 @@ impl<'a> RouteTreeSegmentData<'a> { quote! { { let mut segments = segments.clone(); - if let Some(segment) = segments.next() { + let segment = segments.next(); + if let Some(segment) = segment.as_deref() { if #segment == segment { #(#children)* } @@ -369,7 +370,7 @@ impl<'a> RouteTreeSegmentData<'a> { quote! { let mut trailing = String::from("/"); for seg in segments.clone() { - trailing += seg; + trailing += &*seg; trailing += "/"; } trailing.pop(); @@ -506,7 +507,9 @@ fn return_constructed( let remaining_segments = segments.clone(); let mut segments_clone = segments.clone(); let next_segment = segments_clone.next(); + let next_segment = next_segment.as_deref(); let segment_after_next = segments_clone.next(); + let segment_after_next = segment_after_next.as_deref(); match (next_segment, segment_after_next) { // This is the last segment, return the parsed route (None, _) | (Some(""), None) => { @@ -516,7 +519,7 @@ fn return_constructed( _ => { let mut trailing = String::new(); for seg in remaining_segments { - trailing += seg; + trailing += &*seg; trailing += "/"; } trailing.pop(); diff --git a/packages/router-macro/src/segment.rs b/packages/router-macro/src/segment.rs index 62dea59a7..7e4e40662 100644 --- a/packages/router-macro/src/segment.rs +++ b/packages/router-macro/src/segment.rs @@ -25,7 +25,7 @@ impl RouteSegment { match self { Self::Static(segment) => quote! { write!(f, "/{}", #segment)?; }, Self::Dynamic(ident, _) => quote! { write!(f, "/{}", #ident)?; }, - Self::CatchAll(ident, _) => quote! { #ident.display_route_segements(f)?; }, + Self::CatchAll(ident, _) => quote! { #ident.display_route_segments(f)?; }, } } @@ -59,6 +59,7 @@ impl RouteSegment { { let mut segments = segments.clone(); let segment = segments.next(); + let segment = segment.as_deref(); let parsed = if let Some(#segment) = segment { Ok(()) } else { @@ -80,7 +81,8 @@ impl RouteSegment { quote! { { let mut segments = segments.clone(); - let parsed = if let Some(segment) = segments.next() { + let segment = segments.next(); + let parsed = if let Some(segment) = segment.as_deref() { <#ty as dioxus_router::routable::FromRouteSegment>::from_route_segment(segment).map_err(|err| #error_enum_name::#error_enum_varient(#inner_parse_enum::#error_name(err))) } else { Err(#error_enum_name::#error_enum_varient(#inner_parse_enum::#missing_error_name)) @@ -100,9 +102,12 @@ impl RouteSegment { quote! { { let parsed = { - let mut segments = segments.clone(); - let segments: Vec<_> = segments.collect(); - <#ty as dioxus_router::routable::FromRouteSegments>::from_route_segments(&segments).map_err(|err| #error_enum_name::#error_enum_varient(#inner_parse_enum::#error_name(err))) + let remaining_segments: Vec<_> = segments.collect(); + let mut new_segments: Vec<&str> = Vec::new(); + for segment in &remaining_segments { + new_segments.push(&*segment); + } + <#ty as dioxus_router::routable::FromRouteSegments>::from_route_segments(&new_segments).map_err(|err| #error_enum_name::#error_enum_varient(#inner_parse_enum::#error_name(err))) }; match parsed { Ok(#name) => { diff --git a/packages/router/Cargo.toml b/packages/router/Cargo.toml index 46d7536b6..80923d539 100644 --- a/packages/router/Cargo.toml +++ b/packages/router/Cargo.toml @@ -14,10 +14,10 @@ anyhow = "1.0.66" dioxus = { workspace = true } dioxus-router-macro = { workspace = true } gloo = { version = "0.8.0", optional = true } -log = { workspace = true } +tracing = { workspace = true } thiserror = { workspace = true } futures-util = { workspace = true } -serde_urlencoded = { version = "0.7.1", optional = true } +urlencoding = "2.1.3" serde = { version = "1", features = ["derive"], optional = true } url = "2.3.1" wasm-bindgen = { workspace = true, optional = true } diff --git a/packages/router/README.md b/packages/router/README.md index db6cfdf4f..f83fa63cf 100644 --- a/packages/router/README.md +++ b/packages/router/README.md @@ -15,7 +15,7 @@ [discord-url]: https://discord.gg/XgGxMSkvUM [Website](https://dioxuslabs.com) | -[Guides](https://dioxuslabs.com/docs/0.3/router/) | +[Guides](https://dioxuslabs.com/learn/0.4/router/) | [API Docs](https://docs.rs/dioxus-router/latest/dioxus_router) | [Chat](https://discord.gg/XgGxMSkvUM) @@ -26,8 +26,6 @@ interface similar to React Router, but takes advantage of types for more expressiveness. ```rust, no_run -#![allow(non_snake_case)] - use dioxus::prelude::*; use dioxus_router::prelude::*; use std::str::FromStr; @@ -48,14 +46,14 @@ enum Route { Index {}, } - +#[component] fn App(cx: Scope) -> Element { render! { Router:: { } } } -#[inline_props] +#[component] fn Index(cx: Scope) -> Element { render! { h1 { "Index" } @@ -66,7 +64,7 @@ fn Index(cx: Scope) -> Element { } } -#[inline_props] +#[component] fn Blog(cx: Scope) -> Element { render! { h1 { "Blog" } @@ -74,7 +72,7 @@ fn Blog(cx: Scope) -> Element { } } -#[inline_props] +#[component] fn BlogList(cx: Scope) -> Element { render! { h2 { "List of blog posts" } @@ -89,7 +87,7 @@ fn BlogList(cx: Scope) -> Element { } } -#[inline_props] +#[component] fn BlogPost(cx: Scope, blog_id: usize) -> Element { render! { h2 { "Blog Post" } diff --git a/packages/router/benches/incremental.rs b/packages/router/benches/incremental.rs index 0c2697a80..2c4e9d548 100644 --- a/packages/router/benches/incremental.rs +++ b/packages/router/benches/incremental.rs @@ -1,4 +1,4 @@ -#![allow(unused, non_snake_case)] +#![allow(unused)] use std::time::Duration; @@ -134,7 +134,7 @@ pub fn criterion_benchmark(c: &mut Criterion) { criterion_group!(benches, criterion_benchmark); criterion_main!(benches); -#[inline_props] +#[component] fn Blog(cx: Scope) -> Element { render! { div { @@ -143,7 +143,7 @@ fn Blog(cx: Scope) -> Element { } } -#[inline_props] +#[component] fn Post(cx: Scope, id: usize) -> Element { render! { for _ in 0..*id { @@ -154,7 +154,7 @@ fn Post(cx: Scope, id: usize) -> Element { } } -#[inline_props] +#[component] fn PostHome(cx: Scope) -> Element { render! { div { @@ -163,7 +163,7 @@ fn PostHome(cx: Scope) -> Element { } } -#[inline_props] +#[component] fn Home(cx: Scope) -> Element { render! { div { @@ -189,7 +189,7 @@ enum Route { Home {}, } -#[inline_props] +#[component] fn RenderPath(cx: Scope, path: Route) -> Element { let path = path.clone(); render! { diff --git a/packages/router/examples/simple_routes.rs b/packages/router/examples/simple_routes.rs index 673658870..3634f7df3 100644 --- a/packages/router/examples/simple_routes.rs +++ b/packages/router/examples/simple_routes.rs @@ -1,24 +1,23 @@ -#![allow(non_snake_case)] - use dioxus::prelude::*; use dioxus_router::prelude::*; use std::str::FromStr; fn main() { #[cfg(not(target_arch = "wasm32"))] - dioxus_desktop::launch(root); + dioxus_desktop::launch(Root); #[cfg(target_arch = "wasm32")] dioxus_web::launch(root); } -fn root(cx: Scope) -> Element { +#[component] +fn Root(cx: Scope) -> Element { render! { Router:: {} } } -#[inline_props] +#[component] fn UserFrame(cx: Scope, user_id: usize) -> Element { render! { pre { @@ -32,7 +31,7 @@ fn UserFrame(cx: Scope, user_id: usize) -> Element { } } -#[inline_props] +#[component] fn Route1(cx: Scope, user_id: usize, dynamic: usize, query: String, extra: String) -> Element { render! { pre { @@ -50,7 +49,7 @@ fn Route1(cx: Scope, user_id: usize, dynamic: usize, query: String, extra: Strin } } -#[inline_props] +#[component] fn Route2(cx: Scope, user_id: usize) -> Element { render! { pre { @@ -65,7 +64,7 @@ fn Route2(cx: Scope, user_id: usize) -> Element { } } -#[inline_props] +#[component] fn Route3(cx: Scope, dynamic: String) -> Element { let navigator = use_navigator(cx); let current_route = use_route(cx)?; diff --git a/packages/router/examples/static_generation.rs b/packages/router/examples/static_generation.rs index 19e7c7341..e3b6db19f 100644 --- a/packages/router/examples/static_generation.rs +++ b/packages/router/examples/static_generation.rs @@ -1,5 +1,3 @@ -#![allow(non_snake_case)] - use std::time::Duration; use dioxus::prelude::*; @@ -54,7 +52,7 @@ async fn main() { .unwrap(); } -#[inline_props] +#[component] fn Blog(cx: Scope) -> Element { render! { div { @@ -63,7 +61,7 @@ fn Blog(cx: Scope) -> Element { } } -#[inline_props] +#[component] fn Post(cx: Scope, id: usize) -> Element { render! { div { @@ -72,7 +70,7 @@ fn Post(cx: Scope, id: usize) -> Element { } } -#[inline_props] +#[component] fn PostHome(cx: Scope) -> Element { render! { div { @@ -81,7 +79,7 @@ fn PostHome(cx: Scope) -> Element { } } -#[inline_props] +#[component] fn Home(cx: Scope) -> Element { render! { div { diff --git a/packages/router/src/components/history_buttons.rs b/packages/router/src/components/history_buttons.rs index 6bd23d860..eb62e9285 100644 --- a/packages/router/src/components/history_buttons.rs +++ b/packages/router/src/components/history_buttons.rs @@ -1,5 +1,5 @@ use dioxus::prelude::*; -use log::error; +use tracing::error; use crate::utils::use_router_internal::use_router_internal; @@ -30,13 +30,14 @@ pub struct HistoryButtonProps<'a> { /// Index {}, /// } /// +/// #[component] /// fn App(cx: Scope) -> Element { /// render! { /// Router:: {} /// } /// } /// -/// #[inline_props] +/// #[component] /// fn Index(cx: Scope) -> Element { /// render! { /// GoBackButton { @@ -52,7 +53,7 @@ pub struct HistoryButtonProps<'a> { /// # r#""# /// # ); /// ``` -#[allow(non_snake_case)] +#[component] pub fn GoBackButton<'a>(cx: Scope<'a, HistoryButtonProps<'a>>) -> Element { let HistoryButtonProps { children } = cx.props; @@ -101,13 +102,14 @@ pub fn GoBackButton<'a>(cx: Scope<'a, HistoryButtonProps<'a>>) -> Element { /// Index {}, /// } /// +/// #[component] /// fn App(cx: Scope) -> Element { /// render! { /// Router:: {} /// } /// } /// -/// #[inline_props] +/// #[component] /// fn Index(cx: Scope) -> Element { /// render! { /// GoForwardButton { @@ -123,7 +125,7 @@ pub fn GoBackButton<'a>(cx: Scope<'a, HistoryButtonProps<'a>>) -> Element { /// # r#""# /// # ); /// ``` -#[allow(non_snake_case)] +#[component] pub fn GoForwardButton<'a>(cx: Scope<'a, HistoryButtonProps<'a>>) -> Element { let HistoryButtonProps { children } = cx.props; diff --git a/packages/router/src/components/link.rs b/packages/router/src/components/link.rs index bc55fec8c..787f9cdc9 100644 --- a/packages/router/src/components/link.rs +++ b/packages/router/src/components/link.rs @@ -1,9 +1,11 @@ +#![allow(clippy::type_complexity)] + use std::any::Any; use std::fmt::Debug; use std::rc::Rc; use dioxus::prelude::*; -use log::error; +use tracing::error; use crate::navigation::NavigationTarget; use crate::prelude::Routable; @@ -133,13 +135,14 @@ impl Debug for LinkProps<'_> { /// Index {}, /// } /// +/// #[component] /// fn App(cx: Scope) -> Element { /// render! { /// Router:: {} /// } /// } /// -/// #[inline_props] +/// #[component] /// fn Index(cx: Scope) -> Element { /// render! { /// render! { diff --git a/packages/router/src/components/outlet.rs b/packages/router/src/components/outlet.rs index 133a23543..663f54e64 100644 --- a/packages/router/src/components/outlet.rs +++ b/packages/router/src/components/outlet.rs @@ -29,7 +29,7 @@ use dioxus::prelude::*; /// Index {}, /// } /// -/// #[inline_props] +/// #[component] /// fn Index(cx: Scope) -> Element { /// render! { /// div { @@ -38,7 +38,7 @@ use dioxus::prelude::*; /// } /// } /// -/// #[inline_props] +/// #[component] /// fn Wrapper(cx: Scope) -> Element { /// render! { /// h1 { "App" } @@ -46,7 +46,7 @@ use dioxus::prelude::*; /// } /// } /// -/// #[inline_props] +/// #[component] /// fn Child(cx: Scope) -> Element { /// render! { /// p { @@ -55,6 +55,7 @@ use dioxus::prelude::*; /// } /// } /// +/// # #[component] /// # fn App(cx: Scope) -> Element { /// # render! { /// # Router:: { diff --git a/packages/router/src/history/memory.rs b/packages/router/src/history/memory.rs index ba511bb97..373920be2 100644 --- a/packages/router/src/history/memory.rs +++ b/packages/router/src/history/memory.rs @@ -20,9 +20,9 @@ where /// ```rust /// # use dioxus_router::prelude::*; /// # use dioxus::prelude::*; - /// # #[inline_props] + /// # #[component] /// # fn Index(cx: Scope) -> Element { todo!() } - /// # #[inline_props] + /// # #[component] /// # fn OtherPage(cx: Scope) -> Element { todo!() } /// #[derive(Clone, Routable, Debug, PartialEq)] /// enum Route { diff --git a/packages/router/src/history/mod.rs b/packages/router/src/history/mod.rs index fda386075..e9668b979 100644 --- a/packages/router/src/history/mod.rs +++ b/packages/router/src/history/mod.rs @@ -48,9 +48,9 @@ pub trait HistoryProvider { /// ```rust /// # use dioxus_router::prelude::*; /// # use dioxus::prelude::*; - /// # #[inline_props] + /// # #[component] /// # fn Index(cx: Scope) -> Element { todo!() } - /// # #[inline_props] + /// # #[component] /// # fn OtherPage(cx: Scope) -> Element { todo!() } /// #[derive(Clone, Routable, Debug, PartialEq)] /// enum Route { @@ -86,17 +86,20 @@ pub trait HistoryProvider { /// ```rust /// # use dioxus_router::prelude::*; /// # use dioxus::prelude::*; - /// # #[inline_props] + /// # #[component] /// # fn Index(cx: Scope) -> Element { todo!() } + /// # fn Other(cx: Scope) -> Element { todo!() } /// #[derive(Clone, Routable, Debug, PartialEq)] /// enum Route { /// #[route("/")] /// Index {}, + /// #[route("/other")] + /// Other {}, /// } /// let mut history = MemoryHistory::::default(); /// assert_eq!(history.can_go_back(), false); /// - /// history.push(Route::Index {}); + /// history.push(Route::Other {}); /// assert_eq!(history.can_go_back(), true); /// ``` #[must_use] @@ -112,9 +115,9 @@ pub trait HistoryProvider { /// ```rust /// # use dioxus_router::prelude::*; /// # use dioxus::prelude::*; - /// # #[inline_props] + /// # #[component] /// # fn Index(cx: Scope) -> Element { todo!() } - /// # #[inline_props] + /// # #[component] /// # fn OtherPage(cx: Scope) -> Element { todo!() } /// #[derive(Clone, Routable, Debug, PartialEq)] /// enum Route { @@ -144,9 +147,9 @@ pub trait HistoryProvider { /// ```rust /// # use dioxus_router::prelude::*; /// # use dioxus::prelude::*; - /// # #[inline_props] + /// # #[component] /// # fn Index(cx: Scope) -> Element { todo!() } - /// # #[inline_props] + /// # #[component] /// # fn OtherPage(cx: Scope) -> Element { todo!() } /// #[derive(Clone, Routable, Debug, PartialEq)] /// enum Route { @@ -177,9 +180,9 @@ pub trait HistoryProvider { /// ```rust /// # use dioxus_router::prelude::*; /// # use dioxus::prelude::*; - /// # #[inline_props] + /// # #[component] /// # fn Index(cx: Scope) -> Element { todo!() } - /// # #[inline_props] + /// # #[component] /// # fn OtherPage(cx: Scope) -> Element { todo!() } /// #[derive(Clone, Routable, Debug, PartialEq)] /// enum Route { @@ -210,9 +213,9 @@ pub trait HistoryProvider { /// ```rust /// # use dioxus_router::prelude::*; /// # use dioxus::prelude::*; - /// # #[inline_props] + /// # #[component] /// # fn Index(cx: Scope) -> Element { todo!() } - /// # #[inline_props] + /// # #[component] /// # fn OtherPage(cx: Scope) -> Element { todo!() } /// #[derive(Clone, Routable, Debug, PartialEq)] /// enum Route { @@ -239,9 +242,9 @@ pub trait HistoryProvider { /// ```rust /// # use dioxus_router::prelude::*; /// # use dioxus::prelude::*; - /// # #[inline_props] + /// # #[component] /// # fn Index(cx: Scope) -> Element { todo!() } - /// # #[inline_props] + /// # #[component] /// # fn OtherPage(cx: Scope) -> Element { todo!() } /// #[derive(Clone, Routable, Debug, PartialEq)] /// enum Route { diff --git a/packages/router/src/history/web.rs b/packages/router/src/history/web.rs index 8b6089b20..789eed76e 100644 --- a/packages/router/src/history/web.rs +++ b/packages/router/src/history/web.rs @@ -139,7 +139,7 @@ impl WebHistory { ); let current_route = myself.current_route(); - log::trace!("initial route: {:?}", current_route); + tracing::trace!("initial route: {:?}", current_route); let current_url = current_route.to_string(); let state = myself.create_state(current_route); let _ = replace_state_with_url(&myself.history, &state, Some(¤t_url)); @@ -195,14 +195,10 @@ where ::Err: std::fmt::Display, { fn route_from_location(&self) -> R { - R::from_str( - &self - .window - .location() - .pathname() - .unwrap_or_else(|_| String::from("/")), - ) - .unwrap_or_else(|err| panic!("{}", err)) + let location = self.window.location(); + let path = location.pathname().unwrap_or_else(|_| "/".into()) + + &location.search().unwrap_or("".into()); + R::from_str(&path).unwrap_or_else(|err| panic!("{}", err)) } fn full_path(&self, state: &R) -> String { diff --git a/packages/router/src/history/web_hash.rs b/packages/router/src/history/web_hash.rs index c910b1c97..c23bca237 100644 --- a/packages/router/src/history/web_hash.rs +++ b/packages/router/src/history/web_hash.rs @@ -1,8 +1,8 @@ use std::sync::{Arc, Mutex}; use gloo::{events::EventListener, render::AnimationFrame, utils::window}; -use log::error; use serde::{de::DeserializeOwned, Serialize}; +use tracing::error; use url::Url; use web_sys::{History, ScrollRestoration, Window}; diff --git a/packages/router/src/hooks/use_navigator.rs b/packages/router/src/hooks/use_navigator.rs index b435e7f9e..c1c21ee63 100644 --- a/packages/router/src/hooks/use_navigator.rs +++ b/packages/router/src/hooks/use_navigator.rs @@ -17,13 +17,14 @@ use crate::prelude::{Navigator, RouterContext}; /// Dynamic { id: usize }, /// } /// +/// #[component] /// fn App(cx: Scope) -> Element { /// render! { /// Router:: {} /// } /// } /// -/// #[inline_props] +/// #[component] /// fn Index(cx: Scope) -> Element { /// let navigator = use_navigator(&cx); /// @@ -35,7 +36,7 @@ use crate::prelude::{Navigator, RouterContext}; /// } /// } /// -/// #[inline_props] +/// #[component] /// fn Dynamic(cx: Scope, id: usize) -> Element { /// render! { /// p { diff --git a/packages/router/src/hooks/use_route.rs b/packages/router/src/hooks/use_route.rs index e6aa906d5..42cca27fb 100644 --- a/packages/router/src/hooks/use_route.rs +++ b/packages/router/src/hooks/use_route.rs @@ -12,7 +12,7 @@ use crate::utils::use_router_internal::use_router_internal; /// - Otherwise the current route. /// /// # Panic -/// - When the calling component is not nested within a [`Link`] component durring a debug build. +/// - When the calling component is not nested within a [`Link`] component during a debug build. /// /// # Example /// ```rust @@ -25,6 +25,7 @@ use crate::utils::use_router_internal::use_router_internal; /// Index {}, /// } /// +/// #[component] /// fn App(cx: Scope) -> Element { /// render! { /// h1 { "App" } @@ -32,9 +33,9 @@ use crate::utils::use_router_internal::use_router_internal; /// } /// } /// -/// #[inline_props] +/// #[component] /// fn Index(cx: Scope) -> Element { -/// let path = use_route(&cx).unwrap(); +/// let path: Route = use_route(&cx).unwrap(); /// render! { /// h2 { "Current Path" } /// p { "{path}" } diff --git a/packages/router/src/incremental.rs b/packages/router/src/incremental.rs index 79f4e24bf..e1c74c5fb 100644 --- a/packages/router/src/incremental.rs +++ b/packages/router/src/incremental.rs @@ -1,4 +1,4 @@ -//! Exentsions to the incremental renderer to support pre-caching static routes. +//! Extensions to the incremental renderer to support pre-caching static routes. use core::pin::Pin; use std::future::Future; use std::str::FromStr; @@ -59,8 +59,8 @@ where .await?; } Err(e) => { - log::info!("@ route: {}", full_path); - log::error!("Error pre-caching static route: {}", e); + tracing::info!("@ route: {}", full_path); + tracing::error!("Error pre-caching static route: {}", e); } } } @@ -87,7 +87,7 @@ where ::Err: std::fmt::Display, W: tokio::io::AsyncWrite + Unpin + Send, { - #[inline_props] + #[component] fn RenderPath(cx: Scope, path: R) -> Element where R: Routable, diff --git a/packages/router/src/lib.rs b/packages/router/src/lib.rs index 49b7ffc42..a92394513 100644 --- a/packages/router/src/lib.rs +++ b/packages/router/src/lib.rs @@ -82,3 +82,8 @@ pub mod prelude { mod utils { pub(crate) mod use_router_internal; } + +#[doc(hidden)] +pub mod exports { + pub use urlencoding; +} diff --git a/packages/router/src/navigation.rs b/packages/router/src/navigation.rs index c0a85fe67..2d7a3f90f 100644 --- a/packages/router/src/navigation.rs +++ b/packages/router/src/navigation.rs @@ -18,7 +18,7 @@ pub enum NavigationTarget { /// # use dioxus::prelude::*; /// # use dioxus_router::prelude::*; /// # use dioxus_router::navigation::NavigationTarget; - /// # #[inline_props] + /// # #[component] /// # fn Index(cx: Scope) -> Element { /// # todo!() /// # } @@ -38,7 +38,7 @@ pub enum NavigationTarget { /// # use dioxus::prelude::*; /// # use dioxus_router::prelude::*; /// # use dioxus_router::navigation::NavigationTarget; - /// # #[inline_props] + /// # #[component] /// # fn Index(cx: Scope) -> Element { /// # todo!() /// # } diff --git a/packages/router/src/routable.rs b/packages/router/src/routable.rs index d9f5b2346..b1bb6d915 100644 --- a/packages/router/src/routable.rs +++ b/packages/router/src/routable.rs @@ -3,16 +3,18 @@ #![allow(non_snake_case)] use dioxus::prelude::*; +use std::iter::FlatMap; +use std::slice::Iter; use std::{fmt::Display, str::FromStr}; -/// An error that occurs when parsing a route +/// An error that occurs when parsing a route. #[derive(Debug, PartialEq)] -pub struct RouteParseError { - /// The attempted routes that failed to match +pub struct RouteParseError { + /// The attempted routes that failed to match. pub attempted_routes: Vec, } -impl std::fmt::Display for RouteParseError { +impl Display for RouteParseError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "Route did not match:\nAttempted Matches:\n")?; for (i, route) in self.attempted_routes.iter().enumerate() { @@ -26,63 +28,96 @@ impl std::fmt::Display for RouteParseError { /// /// This trait needs to be implemented if you want to turn a query string into a struct. /// -/// A working example can be found in the `examples` folder in the root package under `query_segments_demo` +/// A working example can be found in the `examples` folder in the root package under `query_segments_demo`. pub trait FromQuery { - /// Create an instance of `Self` from a query string + /// Create an instance of `Self` from a query string. fn from_query(query: &str) -> Self; } impl From<&'a str>> FromQuery for T { fn from_query(query: &str) -> Self { - T::from(query) + T::from(&*urlencoding::decode(query).expect("Failed to decode url encoding")) } } -/// Something that can be created from a route segment +/// Something that can be created from a route segment. pub trait FromRouteSegment: Sized { - /// The error that can occur when parsing a route segment + /// The error that can occur when parsing a route segment. type Err; - /// Create an instance of `Self` from a route segment + /// Create an instance of `Self` from a route segment. fn from_route_segment(route: &str) -> Result; } impl FromRouteSegment for T where - ::Err: std::fmt::Display, + ::Err: Display, { type Err = ::Err; fn from_route_segment(route: &str) -> Result { - T::from_str(route) + match urlencoding::decode(route) { + Ok(segment) => T::from_str(&segment), + Err(err) => { + tracing::error!("Failed to decode url encoding: {}", err); + T::from_str(route) + } + } } } -/// Something that can be converted to route segments -pub trait ToRouteSegments { - /// Display the route segments - fn display_route_segements(self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result; +#[test] +fn full_circle() { + let route = "testing 1234 hello world"; + assert_eq!(String::from_route_segment(route).unwrap(), route); } -impl ToRouteSegments for I +/// Something that can be converted to route segments. +pub trait ToRouteSegments { + /// Display the route segments. + fn display_route_segments(self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result; +} + +impl ToRouteSegments for I where I: IntoIterator, { - fn display_route_segements(self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn display_route_segments(self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { for segment in self { write!(f, "/")?; - write!(f, "{}", segment)?; + let segment = segment.to_string(); + match urlencoding::decode(&segment) { + Ok(segment) => write!(f, "{}", segment)?, + Err(err) => { + tracing::error!("Failed to decode url encoding: {}", err); + write!(f, "{}", segment)? + } + } } Ok(()) } } -/// Something that can be created from route segments +#[test] +fn to_route_segments() { + struct DisplaysRoute; + + impl Display for DisplaysRoute { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let segments = vec!["hello", "world"]; + segments.display_route_segments(f) + } + } + + assert_eq!(DisplaysRoute.to_string(), "/hello/world"); +} + +/// Something that can be created from route segments. pub trait FromRouteSegments: Sized { - /// The error that can occur when parsing route segments + /// The error that can occur when parsing route segments. type Err; - /// Create an instance of `Self` from route segments + /// Create an instance of `Self` from route segments. fn from_route_segments(segments: &[&str]) -> Result; } @@ -97,29 +132,54 @@ impl> FromRouteSegments for I { } } +/// A flattened version of [`Routable::SITE_MAP`]. +/// This essentially represents a `Vec>`, which you can collect it into. +type SiteMapFlattened<'a> = FlatMap< + Iter<'a, SiteMapSegment>, + Vec>, + fn(&SiteMapSegment) -> Vec>, +>; + +fn seg_strs_to_route(segs_maybe: &Option>) -> Option +where + T: Routable, +{ + if let Some(str) = seg_strs_to_str(segs_maybe) { + T::from_str(&str).ok() + } else { + None + } +} + +fn seg_strs_to_str(segs_maybe: &Option>) -> Option { + segs_maybe + .as_ref() + .map(|segs| String::from('/') + &segs.join("/")) +} + /// Something that can be: -/// 1. Converted from a route -/// 2. Converted to a route -/// 3. Rendered as a component +/// 1. Converted from a route. +/// 2. Converted to a route. +/// 3. Rendered as a component. /// -/// This trait can be derived using the `#[derive(Routable)]` macro -pub trait Routable: std::fmt::Display + std::str::FromStr + Clone + 'static { - /// The error that can occur when parsing a route +/// This trait can be derived using the `#[derive(Routable)]` macro. +pub trait Routable: FromStr + Display + Clone + 'static { + /// The error that can occur when parsing a route. const SITE_MAP: &'static [SiteMapSegment]; /// Render the route at the given level fn render<'a>(&self, cx: &'a ScopeState, level: usize) -> Element<'a>; - /// Checks if this route is a child of the given route + /// Checks if this route is a child of the given route. /// /// # Example /// ```rust /// use dioxus_router::prelude::*; /// use dioxus::prelude::*; /// - /// #[inline_props] + /// #[component] /// fn Home(cx: Scope) -> Element { todo!() } - /// #[inline_props] + /// #[component] /// fn About(cx: Scope) -> Element { todo!() } /// /// #[derive(Routable, Clone, PartialEq, Debug)] @@ -152,23 +212,23 @@ pub trait Routable: std::fmt::Display + std::str::FromStr + Clone + 'static { true } - /// Get the parent route of this route + /// Get the parent route of this route. /// /// # Example /// ```rust /// use dioxus_router::prelude::*; /// use dioxus::prelude::*; /// - /// #[inline_props] + /// #[component] /// fn Home(cx: Scope) -> Element { todo!() } - /// #[inline_props] + /// #[component] /// fn About(cx: Scope) -> Element { todo!() } /// /// #[derive(Routable, Clone, PartialEq, Debug)] /// enum Route { - /// #[route("/")] + /// #[route("/home")] /// Home {}, - /// #[route("/about")] + /// #[route("/home/about")] /// About {}, /// } /// @@ -192,72 +252,67 @@ pub trait Routable: std::fmt::Display + std::str::FromStr + Clone + 'static { Self::from_str(&new_route).ok() } - /// Gets a list of all static routes + /// Returns a flattened version of [`Self::SITE_MAP`]. + fn flatten_site_map<'a>() -> SiteMapFlattened<'a> { + Self::SITE_MAP.iter().flat_map(SiteMapSegment::flatten) + } + + /// Gets a list of all the static routes. + /// Example static route: `#[route("/static/route")]` fn static_routes() -> Vec { - Self::SITE_MAP - .iter() - .flat_map(|segment| segment.flatten()) + Self::flatten_site_map() .filter_map(|route| { - if route + let route_if_static = &route .iter() - .all(|segment| matches!(segment, SegmentType::Static(_))) - { - Self::from_str( - &route - .iter() - .map(|segment| match segment { - SegmentType::Static(s) => s.to_string(), - _ => unreachable!(), - }) - .collect::>() - .join("/"), - ) - .ok() - } else { - None - } + .map(|segment| match segment { + SegmentType::Static(s) => Some(*s), + _ => None, + }) + .collect::>>(); + + seg_strs_to_route(route_if_static) }) .collect() } } trait RoutableFactory { - type Err: std::fmt::Display; + type Err: Display; type Routable: Routable + FromStr; } impl RoutableFactory for R where - ::Err: std::fmt::Display, + ::Err: Display, { type Err = ::Err; type Routable = R; } -trait RouteRenderable: std::fmt::Display + 'static { +trait RouteRenderable: Display + 'static { fn render<'a>(&self, cx: &'a ScopeState, level: usize) -> Element<'a>; } impl RouteRenderable for R where - ::Err: std::fmt::Display, + ::Err: Display, { fn render<'a>(&self, cx: &'a ScopeState, level: usize) -> Element<'a> { self.render(cx, level) } } -/// A type erased map of the site structurens +/// A type erased map of the site structure. #[derive(Debug, Clone, PartialEq)] pub struct SiteMapSegment { - /// The type of the route segment + /// The type of the route segment. pub segment_type: SegmentType, - /// The children of the route segment + /// The children of the route segment. pub children: &'static [SiteMapSegment], } impl SiteMapSegment { - /// Take a map of the site structure and flatten it into a vector of routes + /// Take a map of the site structure and flatten it into a vector of routes. pub fn flatten(&self) -> Vec> { let mut routes = Vec::new(); self.flatten_inner(&mut routes, Vec::new()); @@ -277,16 +332,16 @@ impl SiteMapSegment { } } -/// The type of a route segment +/// The type of a route segment. #[derive(Debug, Clone, PartialEq)] pub enum SegmentType { - /// A static route segment + /// A static route segment. Static(&'static str), - /// A dynamic route segment + /// A dynamic route segment. Dynamic(&'static str), - /// A catch all route segment + /// A catch all route segment. CatchAll(&'static str), - /// A child router + /// A child router. Child, } @@ -296,7 +351,7 @@ impl Display for SegmentType { SegmentType::Static(s) => write!(f, "/{}", s), SegmentType::Child => Ok(()), SegmentType::Dynamic(s) => write!(f, "/:{}", s), - SegmentType::CatchAll(s) => write!(f, "/:...{}", s), + SegmentType::CatchAll(s) => write!(f, "/:..{}", s), } } } diff --git a/packages/router/src/router_cfg.rs b/packages/router/src/router_cfg.rs index 764d70461..dd379e493 100644 --- a/packages/router/src/router_cfg.rs +++ b/packages/router/src/router_cfg.rs @@ -13,7 +13,7 @@ use crate::prelude::*; /// ```rust,no_run /// # use dioxus_router::prelude::*; /// # use dioxus::prelude::*; -/// # #[inline_props] +/// # #[component] /// # fn Index(cx: Scope) -> Element { /// # todo!() /// # } diff --git a/packages/router/tests/via_ssr/link.rs b/packages/router/tests/via_ssr/link.rs index 3fe899128..6f330cb83 100644 --- a/packages/router/tests/via_ssr/link.rs +++ b/packages/router/tests/via_ssr/link.rs @@ -1,4 +1,3 @@ -#![allow(non_snake_case)] use dioxus::prelude::*; use dioxus_router::prelude::*; use std::str::FromStr; @@ -27,6 +26,7 @@ where } } + #[component] fn App(cx: Scope>) -> Element where ::Err: std::fmt::Display, @@ -50,12 +50,12 @@ fn href_internal() { Test {}, } - #[inline_props] - fn Test(cx: Scope) -> Element { + #[component] + fn Test(_cx: Scope) -> Element { todo!() } - #[inline_props] + #[component] fn Root(cx: Scope) -> Element { render! { Link { @@ -88,12 +88,12 @@ fn href_external() { Test {}, } - #[inline_props] - fn Test(cx: Scope) -> Element { + #[component] + fn Test(_cx: Scope) -> Element { todo!() } - #[inline_props] + #[component] fn Root(cx: Scope) -> Element { render! { Link { @@ -126,12 +126,12 @@ fn with_class() { Test {}, } - #[inline_props] - fn Test(cx: Scope) -> Element { + #[component] + fn Test(_cx: Scope) -> Element { todo!() } - #[inline_props] + #[component] fn Root(cx: Scope) -> Element { render! { Link { @@ -163,7 +163,7 @@ fn with_active_class_active() { Root {}, } - #[inline_props] + #[component] fn Root(cx: Scope) -> Element { render! { Link { @@ -198,12 +198,12 @@ fn with_active_class_inactive() { Test {}, } - #[inline_props] - fn Test(cx: Scope) -> Element { + #[component] + fn Test(_cx: Scope) -> Element { todo!() } - #[inline_props] + #[component] fn Root(cx: Scope) -> Element { render! { Link { @@ -238,12 +238,12 @@ fn with_id() { Test {}, } - #[inline_props] - fn Test(cx: Scope) -> Element { + #[component] + fn Test(_cx: Scope) -> Element { todo!() } - #[inline_props] + #[component] fn Root(cx: Scope) -> Element { render! { Link { @@ -277,12 +277,12 @@ fn with_new_tab() { Test {}, } - #[inline_props] - fn Test(cx: Scope) -> Element { + #[component] + fn Test(_cx: Scope) -> Element { todo!() } - #[inline_props] + #[component] fn Root(cx: Scope) -> Element { render! { Link { @@ -314,7 +314,7 @@ fn with_new_tab_external() { Root {}, } - #[inline_props] + #[component] fn Root(cx: Scope) -> Element { render! { Link { @@ -348,12 +348,12 @@ fn with_rel() { Test {}, } - #[inline_props] - fn Test(cx: Scope) -> Element { + #[component] + fn Test(_cx: Scope) -> Element { todo!() } - #[inline_props] + #[component] fn Root(cx: Scope) -> Element { render! { Link { diff --git a/packages/router/tests/via_ssr/outlet.rs b/packages/router/tests/via_ssr/outlet.rs index d48b355d0..216384559 100644 --- a/packages/router/tests/via_ssr/outlet.rs +++ b/packages/router/tests/via_ssr/outlet.rs @@ -1,4 +1,4 @@ -#![allow(non_snake_case, unused)] +#![allow(unused)] use dioxus::prelude::*; use dioxus_router::prelude::*; @@ -34,6 +34,7 @@ fn prepare(path: impl Into) -> VirtualDom { path: String, } + #[component] fn App(cx: Scope) -> Element { render! { h1 { "App" } @@ -46,14 +47,14 @@ fn prepare(path: impl Into) -> VirtualDom { } } - #[inline_props] + #[component] fn RootIndex(cx: Scope) -> Element { render! { h2 { "Root Index" } } } - #[inline_props] + #[component] fn Fixed(cx: Scope) -> Element { render! { h2 { "Fixed" } @@ -61,21 +62,21 @@ fn prepare(path: impl Into) -> VirtualDom { } } - #[inline_props] + #[component] fn FixedIndex(cx: Scope) -> Element { render! { h3 { "Fixed - Index" } } } - #[inline_props] + #[component] fn FixedFixed(cx: Scope) -> Element { render! { h3 { "Fixed - Fixed"} } } - #[inline_props] + #[component] fn Parameter(cx: Scope, id: u8) -> Element { render! { h2 { "Parameter {id}" } @@ -83,14 +84,14 @@ fn prepare(path: impl Into) -> VirtualDom { } } - #[inline_props] + #[component] fn ParameterIndex(cx: Scope, id: u8) -> Element { render! { h3 { "Parameter - Index" } } } - #[inline_props] + #[component] fn ParameterFixed(cx: Scope, id: u8) -> Element { render! { h3 { "Parameter - Fixed" } diff --git a/packages/rsx-rosetta/README.md b/packages/rsx-rosetta/README.md index da3049d3c..f046838c4 100644 --- a/packages/rsx-rosetta/README.md +++ b/packages/rsx-rosetta/README.md @@ -1,5 +1,3 @@ - - # `rsx-rosetta` [![Crates.io][crates-badge]][crates-url] @@ -9,18 +7,15 @@ [crates-badge]: https://img.shields.io/crates/v/rsx-rosetta.svg [crates-url]: https://crates.io/crates/rsx-rosetta - [mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg [mit-url]: https://github.com/dioxuslabs/dioxus/blob/master/LICENSE - [actions-badge]: https://github.com/dioxuslabs/dioxus/actions/workflows/main.yml/badge.svg [actions-url]: https://github.com/dioxuslabs/dioxus/actions?query=workflow%3ACI+branch%3Amaster - [discord-badge]: https://img.shields.io/discord/899851952891002890.svg?logo=discord&style=flat-square [discord-url]: https://discord.gg/XgGxMSkvUM [Website](https://dioxuslabs.com) | -[Guides](https://dioxuslabs.com/docs/0.3/guide/en/) | +[Guides](https://dioxuslabs.com/learn/0.4/) | [API Docs](https://docs.rs/rsx-rosetta/latest/rsx-rosetta) | [Chat](https://discord.gg/XgGxMSkvUM) @@ -49,6 +44,7 @@ From there, you can convert directly to a string or into some other AST. - Join the discord and ask questions! ## License + This project is licensed under the [MIT license]. [mit license]: https://github.com/DioxusLabs/dioxus/blob/master/LICENSE-MIT @@ -56,4 +52,3 @@ This project is licensed under the [MIT license]. Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in Dioxus by you, shall be licensed as MIT, without any additional terms or conditions. - diff --git a/packages/rsx/README.md b/packages/rsx/README.md index c20737167..61502fb17 100644 --- a/packages/rsx/README.md +++ b/packages/rsx/README.md @@ -7,22 +7,18 @@ [crates-badge]: https://img.shields.io/crates/v/dioxus-rsx.svg [crates-url]: https://crates.io/crates/dioxus-rsx - [mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg [mit-url]: https://github.com/dioxuslabs/dioxus/blob/master/LICENSE - [actions-badge]: https://github.com/dioxuslabs/dioxus/actions/workflows/main.yml/badge.svg [actions-url]: https://github.com/dioxuslabs/dioxus/actions?query=workflow%3ACI+branch%3Amaster - [discord-badge]: https://img.shields.io/discord/899851952891002890.svg?logo=discord&style=flat-square [discord-url]: https://discord.gg/XgGxMSkvUM [Website](https://dioxuslabs.com) | -[Guides](https://dioxuslabs.com/docs/0.3/guide/en/) | +[Guides](https://dioxuslabs.com/learn/0.4/) | [API Docs](https://docs.rs/dioxus-rsx/latest/dioxus_rsx) | [Chat](https://discord.gg/XgGxMSkvUM) - ## Overview This crate provides the actual DSL that Dioxus uses in the `rsx!` macro. This crate is separate from the macro crate to enable tooling like autoformat, translation, and AST manipulation (extract to component). @@ -33,6 +29,7 @@ This crate provides the actual DSL that Dioxus uses in the `rsx!` macro. This cr - Join the discord and ask questions! ## License + This project is licensed under the [MIT license]. [mit license]: https://github.com/DioxusLabs/dioxus/blob/master/LICENSE-MIT @@ -40,4 +37,3 @@ This project is licensed under the [MIT license]. Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in Dioxus by you shall be licensed as MIT, without any additional terms or conditions. - diff --git a/packages/signals/Cargo.toml b/packages/signals/Cargo.toml index 0017a1545..56e19bbd8 100644 --- a/packages/signals/Cargo.toml +++ b/packages/signals/Cargo.toml @@ -9,7 +9,7 @@ edition = "2018" [dependencies] dioxus-core = { workspace = true } generational-box = { workspace = true } -log.workspace = true +tracing = { workspace = true } simple_logger = "4.2.0" serde = { version = "1", features = ["derive"], optional = true } diff --git a/packages/signals/README.md b/packages/signals/README.md index 020edc18f..d1e772445 100644 --- a/packages/signals/README.md +++ b/packages/signals/README.md @@ -10,7 +10,8 @@ All signals implement Copy, even if the inner value does not implement copy. Thi use dioxus::prelude::*; use dioxus_signals::*; -fn app(cx: Scope) -> Element { +#[component] +fn App(cx: Scope) -> Element { let signal = use_signal(cx, || "hello world".to_string()); spawn(async move { @@ -32,7 +33,8 @@ Signals will only subscribe to components when you read from the signal in that use dioxus::prelude::*; use dioxus_signals::*; -fn app(cx: Scope) -> Element { +#[component] +fn App(cx: Scope) -> Element { // Because signal is never read in this component, this component will not rerun when the signal changes let signal = use_signal(cx, || 0); @@ -56,6 +58,7 @@ struct ChildProps { signal: Signal, } +#[component] fn Child(cx: Scope) -> Element { // This component does read from the signal, so when the signal changes it will rerun render! { @@ -70,15 +73,17 @@ Because subscriptions happen when you read from (not create) the data, you can p use dioxus::prelude::*; use dioxus_signals::*; -fn app(cx: Scope) -> Element { +#[component] +fn App(cx: Scope) -> Element { // Because signal is never read in this component, this component will not rerun when the signal changes use_context_provider(cx, || Signal::new(0)); - + render! { Child {} } } +#[component] fn Child(cx: Scope) -> Element { let signal: Signal = *use_context(cx).unwrap(); // This component does read from the signal, so when the signal changes it will rerun @@ -92,13 +97,14 @@ fn Child(cx: Scope) -> Element { In addition to local subscriptions in components, `dioxus-signals` provides a way to derive data with local subscriptions. -The use_selector hook will only rerun when any signals inside of the hook change: +The use_selector hook will only rerun when any signals inside the hook change: ```rust use dioxus::prelude::*; use dioxus_signals::*; -fn app(cx: Scope) -> Element { +#[component] +fn App(cx: Scope) -> Element { let signal = use_signal(cx, || 0); let doubled = use_selector(cx, || signal * 2); @@ -113,7 +119,7 @@ fn app(cx: Scope) -> Element { } } -#[inline_props] +#[component] fn Child(cx: Scope, signal: ReadOnlySignal) -> Element { render! { "{signal}" diff --git a/packages/signals/examples/selector.rs b/packages/signals/examples/selector.rs index 85d93ae7f..e7a482cd6 100644 --- a/packages/signals/examples/selector.rs +++ b/packages/signals/examples/selector.rs @@ -1,13 +1,12 @@ -#![allow(non_snake_case)] - use dioxus::prelude::*; use dioxus_signals::*; fn main() { - dioxus_desktop::launch(app); + dioxus_desktop::launch(App); } -fn app(cx: Scope) -> Element { +#[component] +fn App(cx: Scope) -> Element { let signal = use_signal(cx, || 0); let doubled = use_selector(cx, move || signal * 2); @@ -22,7 +21,7 @@ fn app(cx: Scope) -> Element { } } -#[inline_props] +#[component] fn Child(cx: Scope, signal: ReadOnlySignal) -> Element { render! { "{signal}" diff --git a/packages/signals/src/effect.rs b/packages/signals/src/effect.rs index 0685938a0..9a54188d9 100644 --- a/packages/signals/src/effect.rs +++ b/packages/signals/src/effect.rs @@ -18,7 +18,8 @@ pub(crate) fn get_effect_stack() -> EffectStack { Some(rt) => rt, None => { let store = EffectStack::default(); - provide_root_context(store).expect("in a virtual dom") + provide_root_context(store.clone()); + store } } } @@ -54,6 +55,7 @@ pub fn use_effect_with_dependencies( /// Effects allow you to run code when a signal changes. Effects are run immediately and whenever any signal it reads changes. #[derive(Copy, Clone, PartialEq)] pub struct Effect { + pub(crate) source: ScopeId, pub(crate) callback: CopyValue>, } @@ -73,6 +75,7 @@ impl Effect { /// The signal will be owned by the current component and will be dropped when the component is dropped. pub fn new(callback: impl FnMut() + 'static) -> Self { let myself = Self { + source: current_scope_id().expect("in a virtual dom"), callback: CopyValue::new(Box::new(callback)), }; diff --git a/packages/signals/src/rt.rs b/packages/signals/src/rt.rs index 7322d43b4..113fe9b30 100644 --- a/packages/signals/src/rt.rs +++ b/packages/signals/src/rt.rs @@ -2,14 +2,13 @@ use std::cell::{Ref, RefMut}; use std::rc::Rc; -use dioxus_core::prelude::{ - consume_context, consume_context_from_scope, current_scope_id, provide_context, - provide_context_to_scope, provide_root_context, -}; +use dioxus_core::prelude::*; use dioxus_core::ScopeId; use generational_box::{GenerationalBox, Owner, Store}; +use crate::Effect; + fn current_store() -> Store { match consume_context() { Some(rt) => rt, @@ -21,12 +20,20 @@ fn current_store() -> Store { } fn current_owner() -> Rc { - match consume_context() { - Some(rt) => rt, - None => { - let owner = Rc::new(current_store().owner()); - provide_context(owner).expect("in a virtual dom") + match Effect::current() { + // If we are inside of an effect, we should use the owner of the effect as the owner of the value. + Some(effect) => { + let scope_id = effect.source; + owner_in_scope(scope_id) } + // Otherwise either get an owner from the current scope or create a new one. + None => match has_context() { + Some(rt) => rt, + None => { + let owner = Rc::new(current_store().owner()); + provide_context(owner).expect("in a virtual dom") + } + }, } } diff --git a/packages/signals/src/selector.rs b/packages/signals/src/selector.rs index 5eb3fa3c9..346506ff7 100644 --- a/packages/signals/src/selector.rs +++ b/packages/signals/src/selector.rs @@ -74,6 +74,7 @@ pub fn selector(mut f: impl FnMut() -> R + 'static) -> ReadOnlySig inner: CopyValue::invalid(), }; let effect = Effect { + source: current_scope_id().expect("in a virtual dom"), callback: CopyValue::invalid(), }; diff --git a/packages/signals/src/signal.rs b/packages/signals/src/signal.rs index f41624f96..c1ae076d9 100644 --- a/packages/signals/src/signal.rs +++ b/packages/signals/src/signal.rs @@ -26,7 +26,7 @@ use crate::{CopyValue, Effect}; /// render! { Child { state: count } } /// } /// -/// #[inline_props] +/// #[component] /// fn Child(cx: Scope, state: Signal) -> Element { /// let state = *state; /// @@ -89,6 +89,7 @@ pub(crate) struct SignalData { /// use dioxus::prelude::*; /// use dioxus_signals::*; /// +/// #[component] /// fn App(cx: Scope) -> Element { /// let mut count = use_signal(cx, || 0); /// @@ -97,7 +98,7 @@ pub(crate) struct SignalData { /// render! { Child { state: count } } /// } /// -/// #[inline_props] +/// #[component] /// fn Child(cx: Scope, state: Signal) -> Element { /// let state = *state; /// @@ -177,7 +178,7 @@ impl Signal { } else if let Some(current_scope_id) = current_scope_id() { // only subscribe if the vdom is rendering if dioxus_core::vdom_is_rendering() { - log::trace!( + tracing::trace!( "{:?} subscribed to {:?}", self.inner.value, current_scope_id @@ -209,7 +210,7 @@ impl Signal { { let inner = self.inner.read(); for &scope_id in &*inner.subscribers.borrow() { - log::trace!( + tracing::trace!( "Write on {:?} triggered update on {:?}", self.inner.value, scope_id @@ -224,7 +225,7 @@ impl Signal { std::mem::take(&mut *effects) }; for effect in subscribers { - log::trace!( + tracing::trace!( "Write on {:?} triggered effect {:?}", self.inner.value, effect diff --git a/packages/ssr/Cargo.toml b/packages/ssr/Cargo.toml index 1450bd46e..f6376452d 100644 --- a/packages/ssr/Cargo.toml +++ b/packages/ssr/Cargo.toml @@ -6,7 +6,6 @@ edition = "2018" description = "Dioxus render-to-string" license = "MIT OR Apache-2.0" repository = "https://github.com/DioxusLabs/dioxus/" -homepage = "https://dioxuslabs.com/docs/0.3/guide/en/getting_started/ssr.html" keywords = ["dom", "ui", "gui", "react", "ssr"] [dependencies] @@ -15,14 +14,14 @@ askama_escape = "0.10.3" thiserror = "1.0.23" rustc-hash = "1.1.0" lru = "0.10.0" -log = "0.4.13" +tracing = { workspace = true } http = "0.2.9" tokio = { version = "1.28", features = ["full"], optional = true } [dev-dependencies] dioxus = { workspace = true } thiserror = { workspace = true } -log = { workspace = true } +tracing = { workspace = true } fern = { version = "0.6.0", features = ["colored"] } anyhow = "1.0" argh = "0.1.4" diff --git a/packages/ssr/README.md b/packages/ssr/README.md index c5b91b7b8..59dbfbacf 100644 --- a/packages/ssr/README.md +++ b/packages/ssr/README.md @@ -6,10 +6,11 @@

## Resources + This crate is a part of the broader Dioxus ecosystem. For more resources about Dioxus, check out: -- [Getting Started](https://dioxuslabs.com/docs/0.3/guide/en/getting_started/index.html) -- [Book](https://dioxuslabs.com/docs/0.3/guide/en/) +- [Getting Started](https://dioxuslabs.com/learn/0.4/getting_started) +- [Book](https://dioxuslabs.com/learn/0.4/) - [Examples](https://github.com/DioxusLabs/example-projects) ## Overview @@ -26,7 +27,6 @@ let text = dioxus_ssr::render(&vdom); assert_eq!(text, "
hello world!
") ``` - ## Basic Usage The simplest example is to simply render some `rsx!` nodes to HTML. This can be done with the [`render_lazy`] API. @@ -50,15 +50,11 @@ let _ = vdom.rebuild(); let content = dioxus_ssr::render(&vdom); ``` - - - - ## Usage in pre-rendering This crate is particularly useful in pre-generating pages server-side and then selectively loading Dioxus client-side to pick up the reactive elements. -This crate supports hydration out of the box. However, both the client and server must generate the *exact* same VirtualDOMs - the client picks up its VirtualDOM assuming that the pre-rendered page output is the same. To do this, you need to make sure that your VirtualDOM implementation is deterministic! This could involve either serializing our app state and sending it to the client, hydrating only parts of the page, or building tests to ensure what's rendered on the server is the same as the client. +This crate supports hydration out of the box. However, both the client and server must generate the _exact_ same VirtualDOMs - the client picks up its VirtualDOM assuming that the pre-rendered page output is the same. To do this, you need to make sure that your VirtualDOM implementation is deterministic! This could involve either serializing our app state and sending it to the client, hydrating only parts of the page, or building tests to ensure what's rendered on the server is the same as the client. With pre-rendering enabled, this crate will generate element nodes with Element IDs pre-associated. During hydration, the Dioxus-WebSys renderer will attach the Virtual nodes to these real nodes after a page query. @@ -107,5 +103,4 @@ let text = render_lazy!(rsx!( div { "hello world" } )); Dioxus SSR is a powerful tool to generate static sites. Using Dioxus for static site generation _is_ a bit overkill, however. The new documentation generation library, Doxie, is essentially Dioxus SSR on steroids designed for static site generation with client-side hydration. - Again, simply render the VirtualDOM to a string using `render` or any of the other render methods. diff --git a/packages/ssr/src/cache.rs b/packages/ssr/src/cache.rs index a67fd5f22..bcd6ba71f 100644 --- a/packages/ssr/src/cache.rs +++ b/packages/ssr/src/cache.rs @@ -1,6 +1,8 @@ use dioxus_core::prelude::*; use std::fmt::Write; +use crate::renderer::{str_truthy, BOOL_ATTRS}; + #[derive(Debug)] pub struct StringCache { pub segments: Vec, @@ -86,6 +88,10 @@ impl StringCache { inner_html = Some(value); } else if let Some("style") = namespace { styles.push((name, value)); + } else if BOOL_ATTRS.contains(name) { + if str_truthy(value) { + write!(chain, " {name}=\"{value}\"",)?; + } } else { write!(chain, " {name}=\"{value}\"")?; } diff --git a/packages/ssr/src/incremental.rs b/packages/ssr/src/incremental.rs index 9647124de..c3bb25314 100644 --- a/packages/ssr/src/incremental.rs +++ b/packages/ssr/src/incremental.rs @@ -139,13 +139,13 @@ impl IncrementalRenderer { let age = elapsed.as_secs(); if let Some(invalidate_after) = self.invalidate_after { if elapsed < invalidate_after { - log::trace!("memory cache hit {:?}", route); + tracing::trace!("memory cache hit {:?}", route); output.write_all(cache_hit).await?; let max_age = invalidate_after.as_secs(); return Ok(Some(RenderFreshness::new(age, max_age))); } } else { - log::trace!("memory cache hit {:?}", route); + tracing::trace!("memory cache hit {:?}", route); output.write_all(cache_hit).await?; return Ok(Some(RenderFreshness::new_age(age))); } @@ -157,7 +157,7 @@ impl IncrementalRenderer { if let Ok(file) = tokio::fs::File::open(file_path.full_path).await { let mut file = BufReader::new(file); tokio::io::copy_buf(&mut file, output).await?; - log::trace!("file cache hit {:?}", route); + tracing::trace!("file cache hit {:?}", route); self.promote_memory_cache(&route); return Ok(Some(freshness)); } @@ -184,7 +184,7 @@ impl IncrementalRenderer { let freshness = self .render_and_cache(route, component, props, output, rebuild_with, renderer) .await?; - log::trace!("cache miss"); + tracing::trace!("cache miss"); Ok(freshness) } } @@ -206,7 +206,7 @@ impl IncrementalRenderer { } // if the timestamp is invalid or passed, delete the file if let Err(err) = std::fs::remove_file(entry.path()) { - log::error!("Failed to remove file: {}", err); + tracing::error!("Failed to remove file: {}", err); } } } diff --git a/packages/ssr/src/renderer.rs b/packages/ssr/src/renderer.rs index 154fad641..98afef8b7 100644 --- a/packages/ssr/src/renderer.rs +++ b/packages/ssr/src/renderer.rs @@ -1,5 +1,7 @@ use super::cache::Segment; use crate::cache::StringCache; + +use dioxus_core::Attribute; use dioxus_core::{prelude::*, AttributeValue, DynamicNode, RenderReturn}; use std::collections::HashMap; use std::fmt::Write; @@ -83,18 +85,13 @@ impl Renderer { inner_html = Some(attr); } else if attr.namespace == Some("style") { accumulated_dynamic_styles.push(attr); + } else if BOOL_ATTRS.contains(&attr.name) { + if truthy(&attr.value) { + write!(buf, " {}=", attr.name)?; + write_value(buf, &attr.value)?; + } } else { - match attr.value { - AttributeValue::Text(value) => { - write!(buf, " {}=\"{}\"", attr.name, value)? - } - AttributeValue::Bool(value) => write!(buf, " {}={}", attr.name, value)?, - AttributeValue::Int(value) => write!(buf, " {}={}", attr.name, value)?, - AttributeValue::Float(value) => { - write!(buf, " {}={}", attr.name, value)? - } - _ => {} - }; + write_attribute(buf, attr)?; } } Segment::Node(idx) => match &template.dynamic_nodes[*idx] { @@ -153,17 +150,9 @@ impl Renderer { write!(buf, " style=\"")?; } for attr in &accumulated_dynamic_styles { - match attr.value { - AttributeValue::Text(value) => { - write!(buf, "{}:{};", attr.name, value)? - } - AttributeValue::Bool(value) => { - write!(buf, "{}:{};", attr.name, value)? - } - AttributeValue::Float(f) => write!(buf, "{}:{};", attr.name, f)?, - AttributeValue::Int(i) => write!(buf, "{}:{};", attr.name, i)?, - _ => {} - }; + write!(buf, "{}:", attr.name)?; + write_value_unquoted(buf, &attr.value)?; + write!(buf, ";")?; } if !*inside_style_tag { write!(buf, "\"")?; @@ -248,3 +237,81 @@ fn to_string_works() { assert_eq!(out, "
Hello world 1 -->123<-- Hello world 2
nest 1
nest 2
</diiiiiiiiv>
finalize 0
finalize 1
finalize 2
finalize 3
finalize 4
"); } + +pub(crate) const BOOL_ATTRS: &[&str] = &[ + "allowfullscreen", + "allowpaymentrequest", + "async", + "autofocus", + "autoplay", + "checked", + "controls", + "default", + "defer", + "disabled", + "formnovalidate", + "hidden", + "ismap", + "itemscope", + "loop", + "multiple", + "muted", + "nomodule", + "novalidate", + "open", + "playsinline", + "readonly", + "required", + "reversed", + "selected", + "truespeed", + "webkitdirectory", +]; + +pub(crate) fn str_truthy(value: &str) -> bool { + !value.is_empty() && value != "0" && value.to_lowercase() != "false" +} + +pub(crate) fn truthy(value: &AttributeValue) -> bool { + match value { + AttributeValue::Text(value) => str_truthy(value), + AttributeValue::Bool(value) => *value, + AttributeValue::Int(value) => *value != 0, + AttributeValue::Float(value) => *value != 0.0, + _ => false, + } +} + +pub(crate) fn write_attribute(buf: &mut impl Write, attr: &Attribute) -> std::fmt::Result { + let name = &attr.name; + match attr.value { + AttributeValue::Text(value) => write!(buf, " {name}=\"{value}\""), + AttributeValue::Bool(value) => write!(buf, " {name}={value}"), + AttributeValue::Int(value) => write!(buf, " {name}={value}"), + AttributeValue::Float(value) => write!(buf, " {name}={value}"), + _ => Ok(()), + } +} + +pub(crate) fn write_value(buf: &mut impl Write, value: &AttributeValue) -> std::fmt::Result { + match value { + AttributeValue::Text(value) => write!(buf, "\"{}\"", value), + AttributeValue::Bool(value) => write!(buf, "{}", value), + AttributeValue::Int(value) => write!(buf, "{}", value), + AttributeValue::Float(value) => write!(buf, "{}", value), + _ => Ok(()), + } +} + +pub(crate) fn write_value_unquoted( + buf: &mut impl Write, + value: &AttributeValue, +) -> std::fmt::Result { + match value { + AttributeValue::Text(value) => write!(buf, "{}", value), + AttributeValue::Bool(value) => write!(buf, "{}", value), + AttributeValue::Int(value) => write!(buf, "{}", value), + AttributeValue::Float(value) => write!(buf, "{}", value), + _ => Ok(()), + } +} diff --git a/packages/ssr/tests/bool_attr.rs b/packages/ssr/tests/bool_attr.rs new file mode 100644 index 000000000..778e90dcc --- /dev/null +++ b/packages/ssr/tests/bool_attr.rs @@ -0,0 +1,37 @@ +use dioxus::prelude::*; + +#[test] +fn static_boolean_attributs() { + fn app(cx: Scope) -> Element { + render! { + div { hidden: "false" } + div { hidden: "true" } + } + } + + let mut dom = VirtualDom::new(app); + _ = dom.rebuild(); + + assert_eq!( + dioxus_ssr::render(&dom), + r#"
"# + ); +} + +#[test] +fn dynamic_boolean_attributs() { + fn app(cx: Scope) -> Element { + render! { + div { hidden: false } + div { hidden: true } + } + } + + let mut dom = VirtualDom::new(app); + _ = dom.rebuild(); + + assert_eq!( + dioxus_ssr::render(&dom), + r#"
"# + ); +} diff --git a/packages/ssr/tests/simple.rs b/packages/ssr/tests/simple.rs index 395f801e1..cdf186a80 100644 --- a/packages/ssr/tests/simple.rs +++ b/packages/ssr/tests/simple.rs @@ -2,11 +2,12 @@ use dioxus::prelude::*; #[test] fn simple() { - fn app(cx: Scope) -> Element { + #[component] + fn App(cx: Scope) -> Element { render! { div { "hello!" } } } - let mut dom = VirtualDom::new(app); + let mut dom = VirtualDom::new(App); _ = dom.rebuild(); assert_eq!(dioxus_ssr::render(&dom), "
hello!
"); @@ -44,8 +45,8 @@ fn dynamic() { #[test] fn components() { - #[inline_props] - fn my_component(cx: Scope, name: i32) -> Element { + #[component] + fn MyComponent(cx: Scope, name: i32) -> Element { render! { div { "component {name}" } } @@ -55,7 +56,7 @@ fn components() { dioxus_ssr::render_lazy(rsx! { div { (0..5).map(|name| rsx! { - my_component { name: name } + MyComponent { name: name } }) } }), diff --git a/packages/web/Cargo.toml b/packages/web/Cargo.toml index 8de282869..35eb9c5f1 100644 --- a/packages/web/Cargo.toml +++ b/packages/web/Cargo.toml @@ -6,7 +6,7 @@ edition = "2018" description = "Web renderer for Dioxus using websys" license = "MIT OR Apache-2.0" repository = "https://github.com/DioxusLabs/dioxus/" -homepage = "https://dioxuslabs.com/docs/0.3/guide/en/getting_started/web.html" +homepage = "https://dioxuslabs.com/learn/0.4/getting_started/wasm" keywords = ["dom", "ui", "gui", "react", "wasm"] [dependencies] @@ -20,7 +20,7 @@ dioxus-interpreter-js = { workspace = true, features = [ js-sys = "0.3.56" wasm-bindgen = { workspace = true, features = ["enable-interning"] } wasm-bindgen-futures = "0.4.29" -log = { workspace = true } +tracing = { workspace = true } rustc-hash = { workspace = true } console_error_panic_hook = { version = "0.1.7", optional = true } futures-util = { workspace = true, features = ["std", "async-await", "async-await-macro"] } @@ -75,3 +75,4 @@ wasm-logger = "0.2.0" gloo-timers = "0.2.3" gloo-dialogs = "0.1.1" dioxus-web = { path = ".", features = ["hydrate"] } +tracing-wasm = "0.2.1" diff --git a/packages/web/README.md b/packages/web/README.md index 87265c926..561da808c 100644 --- a/packages/web/README.md +++ b/packages/web/README.md @@ -7,18 +7,15 @@ [crates-badge]: https://img.shields.io/crates/v/dioxus-web.svg [crates-url]: https://crates.io/crates/dioxus-web - [mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg [mit-url]: https://github.com/dioxuslabs/dioxus/blob/master/LICENSE - [actions-badge]: https://github.com/dioxuslabs/dioxus/actions/workflows/main.yml/badge.svg [actions-url]: https://github.com/dioxuslabs/dioxus/actions?query=workflow%3ACI+branch%3Amaster - [discord-badge]: https://img.shields.io/discord/899851952891002890.svg?logo=discord&style=flat-square [discord-url]: https://discord.gg/XgGxMSkvUM [Website](https://dioxuslabs.com) | -[Guides](https://dioxuslabs.com/docs/0.3/guide/en/) | +[Guides](https://dioxuslabs.com/learn/0.4/) | [API Docs](https://docs.rs/dioxus-web/latest/dioxus_web) | [Chat](https://discord.gg/XgGxMSkvUM) @@ -36,6 +33,7 @@ Run Dioxus in the browser using WebAssembly. - Join the discord and ask questions! ## License + This project is licensed under the [MIT license]. [mit license]: https://github.com/DioxusLabs/dioxus/blob/master/LICENSE-MIT @@ -43,4 +41,3 @@ This project is licensed under the [MIT license]. Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in Dioxus by you shall be licensed as MIT without any additional terms or conditions. - diff --git a/packages/web/examples/hydrate.rs b/packages/web/examples/hydrate.rs index 3491bba81..08c0f95cd 100644 --- a/packages/web/examples/hydrate.rs +++ b/packages/web/examples/hydrate.rs @@ -43,13 +43,13 @@ fn Bapp(cx: Scope) -> Element { fn main() { console_error_panic_hook::set_once(); - wasm_logger::init(wasm_logger::Config::new(log::Level::Trace)); + tracing_wasm::set_as_global_default(); let mut dom = VirtualDom::new(app); let _ = dom.rebuild(); let pre = dioxus_ssr::pre_render(&dom); - log::trace!("{}", pre); + tracing::trace!("{}", pre); // set the inner content of main to the pre-rendered content window() diff --git a/packages/web/src/dom.rs b/packages/web/src/dom.rs index 52f2ab1a9..4fa5c9444 100644 --- a/packages/web/src/dom.rs +++ b/packages/web/src/dom.rs @@ -249,7 +249,6 @@ impl WebsysDom { for id in to_mount { let node = get_node(id.0 as u32); if let Some(element) = node.dyn_ref::() { - log::info!("mounted event fired: {}", id.0); let data: MountedData = element.into(); let data = Rc::new(data); let _ = self.event_channel.unbounded_send(UiEvent { diff --git a/packages/web/src/eval.rs b/packages/web/src/eval.rs index 954bb1b54..eefece50e 100644 --- a/packages/web/src/eval.rs +++ b/packages/web/src/eval.rs @@ -46,7 +46,7 @@ impl WebEvaluator { Ok(data) => _ = channel_sender.send_blocking(data), Err(e) => { // Can't really do much here. - log::error!("failed to serialize JsValue to serde_json::Value (eval communication) - {}", e); + tracing::error!("failed to serialize JsValue to serde_json::Value (eval communication) - {}", e); } } }); diff --git a/packages/web/src/lib.rs b/packages/web/src/lib.rs index 261232607..60f84de37 100644 --- a/packages/web/src/lib.rs +++ b/packages/web/src/lib.rs @@ -170,7 +170,7 @@ pub fn launch_with_props( /// } /// ``` pub async fn run_with_props(root: fn(Scope) -> Element, root_props: T, cfg: Config) { - log::info!("Starting up"); + tracing::info!("Starting up"); let mut dom = VirtualDom::new_with_props(root, root_props); @@ -205,7 +205,7 @@ pub async fn run_with_props(root: fn(Scope) -> Element, root_prop let mut websys_dom = dom::WebsysDom::new(cfg, tx); - log::info!("rebuilding app"); + tracing::info!("rebuilding app"); if should_hydrate { #[cfg(feature = "hydrate")] @@ -217,7 +217,7 @@ pub async fn run_with_props(root: fn(Scope) -> Element, root_prop websys_dom.load_templates(&templates); if let Err(err) = websys_dom.rehydrate(&dom) { - log::error!( + tracing::error!( "Rehydration failed {:?}. Rebuild DOM into element from scratch", &err ); @@ -240,7 +240,7 @@ pub async fn run_with_props(root: fn(Scope) -> Element, root_prop websys_dom.mount(); loop { - log::trace!("waiting for work"); + tracing::trace!("waiting for work"); // if virtualdom has nothing, wait for it to have something before requesting idle time // if there is work then this future resolves immediately. diff --git a/packages/web/src/rehydrate.rs b/packages/web/src/rehydrate.rs index c7ea6d87d..4415ceb37 100644 --- a/packages/web/src/rehydrate.rs +++ b/packages/web/src/rehydrate.rs @@ -114,9 +114,9 @@ impl WebsysDom { node: &TemplateNode, last_node_was_static_text: &mut bool, ) -> Result<(), RehydrationError> { - log::trace!("rehydrate template node: {:?}", node); + tracing::trace!("rehydrate template node: {:?}", node); if let Ok(current_child) = current_child { - if log::log_enabled!(log::Level::Trace) { + if tracing::event_enabled!(tracing::Level::TRACE) { web_sys::console::log_1(¤t_child.clone().into()); } } @@ -203,9 +203,9 @@ impl WebsysDom { dynamic: &DynamicNode, last_node_was_static_text: &mut bool, ) -> Result<(), RehydrationError> { - log::trace!("rehydrate dynamic node: {:?}", dynamic); + tracing::trace!("rehydrate dynamic node: {:?}", dynamic); if let Ok(current_child) = current_child { - if log::log_enabled!(log::Level::Trace) { + if tracing::event_enabled!(tracing::Level::TRACE) { web_sys::console::log_1(¤t_child.clone().into()); } } diff --git a/translations/ja-jp/README.md b/translations/ja-jp/README.md index 342a99cdb..b678eb989 100644 --- a/translations/ja-jp/README.md +++ b/translations/ja-jp/README.md @@ -40,7 +40,7 @@ | 例 | - ガイド + ガイド | 中文 |