diff --git a/.docker/Dockerfile_base_test_image b/.docker/Dockerfile_base_test_image new file mode 100644 index 000000000..a29eac927 --- /dev/null +++ b/.docker/Dockerfile_base_test_image @@ -0,0 +1,14 @@ +FROM rust:1.58-buster + +RUN apt update +RUN apt install -y \ + libglib2.0-dev \ + libgtk-3-dev \ + libsoup2.4-dev \ + libappindicator3-dev \ + libwebkit2gtk-4.0-dev \ + firefox-esr \ + # for Tarpaulin code coverage + liblzma-dev binutils-dev libcurl4-openssl-dev libdw-dev libelf-dev + +CMD ["exit"] diff --git a/.docker/Dockerfile_code_coverage b/.docker/Dockerfile_code_coverage new file mode 100644 index 000000000..abcccb56d --- /dev/null +++ b/.docker/Dockerfile_code_coverage @@ -0,0 +1,7 @@ +FROM dioxus-test-image + +WORKDIR /run_test +RUN cargo install cargo-tarpaulin +RUN cargo cache -a + +ENTRYPOINT [ "bash" ] diff --git a/.docker/Dockerfile_pre_test b/.docker/Dockerfile_pre_test index 380bb5773..cc6f8810e 100644 --- a/.docker/Dockerfile_pre_test +++ b/.docker/Dockerfile_pre_test @@ -1,20 +1,8 @@ -FROM rust:1.58-buster +FROM dioxus-base-test-image -RUN apt update -RUN apt install -y \ - libglib2.0-dev \ - libgtk-3-dev \ - libsoup2.4-dev \ - libappindicator3-dev \ - libwebkit2gtk-4.0-dev \ - firefox-esr -# for kcov and Tarpaulin -#liblzma-dev binutils-dev libcurl4-openssl-dev libdw-dev libelf-dev - -RUN cargo install cargo-make --debug -# for test coverage -#RUN cargo install cargo-tarpaulin -# clean up a bit +RUN cargo install cargo-binstall +RUN cargo install cargo-make +RUN cargo install wasm-pack RUN cargo install cargo-cache && cargo cache -a CMD ["exit"] diff --git a/.docker/Dockerfile_test b/.docker/Dockerfile_test index f6265c2bb..4cd644051 100644 --- a/.docker/Dockerfile_test +++ b/.docker/Dockerfile_test @@ -1,8 +1,9 @@ -FROM dioxus-base-test-image +FROM dioxus-pre-test RUN mkdir run_test COPY tmp /run_test WORKDIR /run_test RUN cargo make tests +RUN cargo cache -a CMD ["exit"] diff --git a/.docker/run_local_tests.sh b/.docker/run_local_tests.sh index 4684625d4..b6da68541 100644 --- a/.docker/run_local_tests.sh +++ b/.docker/run_local_tests.sh @@ -12,9 +12,16 @@ function run_script { rsync -a --progress ../ tmp --exclude target --exclude docker # build base image - docker build -f Dockerfile_pre_test -t dioxus-base-test-image . + docker build -f Dockerfile_base_test_image -t dioxus-base-test-image . + docker build -f Dockerfile_pre_test -t dioxus-pre-test . # run test docker build -f Dockerfile_test -t dioxus-test-image . + # code coverage + docker build -f Dockerfile_code_coverage -t dioxus-code-coverage . + + # exec test coverage + cd .. && \ + echo "rustup default nightly && cargo +nightly tarpaulin --verbose --all-features --tests --workspace --exclude core-macro --timeout 120 --out Html" | docker run -i --rm --security-opt seccomp=unconfined -v "/home/elios/project/prs/dioxus/:/run_test" dioxus-code-coverage # clean up rm -rf tmp diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 000000000..0e19ecaec --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,37 @@ +name: github pages + +on: + push: + paths: + - docs/** + - .github/workflows/docs.yml + branches: + - master + +jobs: + build-deploy: + runs-on: ubuntu-latest + environment: docs + steps: + - uses: actions/checkout@v2 + + - name: Setup mdBook + uses: peaceiris/actions-mdbook@v1 + with: + mdbook-version: "0.4.10" + + - name: Build + run: cd docs && + cd guide && mdbook build -d ../nightly/guide && cd .. && + cd reference && mdbook build -d ../nightly/reference && cd .. && + cd router && mdbook build -d ../nightly/router && cd .. + + - name: Deploy 🚀 + uses: JamesIves/github-pages-deploy-action@v4.2.3 + with: + branch: gh-pages # The branch the action should deploy to. + folder: docs/nightly # The folder the action should deploy. + target-folder: docs/nightly + repository-name: dioxuslabs/docsite + clean: false + token: ${{ secrets.DEPLOY_KEY }} # let's pretend I don't need it for now diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml index 57b408a23..6ff2b1e9c 100644 --- a/.github/workflows/macos.yml +++ b/.github/workflows/macos.yml @@ -1,9 +1,32 @@ -on: [push, pull_request] - name: macOS tests +on: + push: + branches: + - master + paths: + - packages/** + - examples/** + - src/** + - .github/** + - lib.rs + - Cargo.toml + + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + branches: + - master + paths: + - packages/** + - examples/** + - src/** + - .github/** + - lib.rs + - Cargo.toml + jobs: test: + if: github.event.pull_request.draft == false name: Test Suite runs-on: macos-latest steps: diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 244313ef9..27116f17d 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -1,9 +1,32 @@ -on: [push, pull_request] - name: Rust CI +on: + push: + branches: + - master + paths: + - packages/** + - examples/** + - src/** + - .github/** + - lib.rs + - Cargo.toml + + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + branches: + - master + paths: + - packages/** + - examples/** + - src/** + - .github/** + - lib.rs + - Cargo.toml + jobs: check: + if: github.event.pull_request.draft == false name: Check runs-on: ubuntu-latest steps: @@ -21,6 +44,7 @@ jobs: command: check test: + if: github.event.pull_request.draft == false name: Test Suite runs-on: ubuntu-latest steps: @@ -42,6 +66,7 @@ jobs: args: tests fmt: + if: github.event.pull_request.draft == false name: Rustfmt runs-on: ubuntu-latest steps: @@ -59,6 +84,7 @@ jobs: args: --all -- --check clippy: + if: github.event.pull_request.draft == false name: Clippy runs-on: ubuntu-latest steps: @@ -76,3 +102,24 @@ jobs: with: command: clippy args: -- -D warnings + + # Coverage is disabled until we can fix it + # coverage: + # name: Coverage + # runs-on: ubuntu-latest + # container: + # image: xd009642/tarpaulin:develop-nightly + # options: --security-opt seccomp=unconfined + # steps: + # - name: Checkout repository + # uses: actions/checkout@v2 + # - name: Generate code coverage + # run: | + # apt-get update &&\ + # apt-get install build-essential &&\ + # apt install libwebkit2gtk-4.0-dev libappindicator3-dev libgtk-3-dev -y &&\ + # cargo +nightly tarpaulin --verbose --all-features --workspace --timeout 120 --out Xml + # - name: Upload to codecov.io + # uses: codecov/codecov-action@v2 + # with: + # fail_ci_if_error: false diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 2b6ea5c23..961adee97 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -1,12 +1,32 @@ name: windows + on: push: branches: - master + paths: + - packages/** + - examples/** + - src/** + - .github/** + - lib.rs + - Cargo.toml + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + branches: + - master + paths: + - packages/** + - examples/** + - src/** + - .github/** + - lib.rs + - Cargo.toml jobs: test: + if: github.event.pull_request.draft == false runs-on: windows-latest name: (${{ matrix.target }}, ${{ matrix.cfg_release_channel }}) env: @@ -50,7 +70,7 @@ jobs: run: | rustc -Vv cargo -V - set RUST_BACKTRACE=1 + set RUST_BACKTRACE=1 cargo build --features "desktop, ssr, router" cargo test --features "desktop, ssr, router" shell: cmd diff --git a/.gitignore b/.gitignore index 9df7e9f93..854f5cb26 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,4 @@ Cargo.lock !.vscode/tasks.json !.vscode/launch.json !.vscode/extensions.json +tarpaulin-report.html \ No newline at end of file diff --git a/.vscode/spellright.dict b/.vscode/spellright.dict index bdaf7abb8..06845ebf9 100644 --- a/.vscode/spellright.dict +++ b/.vscode/spellright.dict @@ -69,3 +69,13 @@ Jank noderef reborrow VirtualDoms +bootstrapper +WebkitGtk +laymans +iter +cloneable +fudamental +clonable +oninput +Webview +idanarye diff --git a/Cargo.toml b/Cargo.toml index 5e3a0a032..26ced24cb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,19 +2,22 @@ name = "dioxus" version = "0.1.8" authors = ["Jonathan Kelley"] -edition = "2018" +edition = "2021" description = "Core functionality for Dioxus - a concurrent renderer-agnostic Virtual DOM for interactive user experiences" license = "MIT OR Apache-2.0" repository = "https://github.com/DioxusLabs/dioxus/" homepage = "https://dioxuslabs.com" documentation = "https://dioxuslabs.com" keywords = ["dom", "ui", "gui", "react", "wasm"] +rust-version = "1.56.0" [dependencies] dioxus-core = { path = "./packages/core", version = "^0.1.9" } dioxus-html = { path = "./packages/html", version = "^0.1.6", optional = true } dioxus-core-macro = { path = "./packages/core-macro", version = "^0.1.7", optional = true } dioxus-hooks = { path = "./packages/hooks", version = "^0.1.7", optional = true } +fermi = { path = "./packages/fermi", version = "^0.1.0", optional = true } +# dioxus-rsx = { path = "./packages/rsx", optional = true } dioxus-web = { path = "./packages/web", version = "^0.0.5", optional = true } dioxus-desktop = { path = "./packages/desktop", version = "^0.1.6", optional = true } @@ -29,24 +32,20 @@ dioxus-interpreter-js = { path = "./packages/interpreter", version = "^0.0.0", o default = ["macro", "hooks", "html"] macro = ["dioxus-core-macro"] +# macro = ["dioxus-core-macro", "dioxus-rsx"] hooks = ["dioxus-hooks"] html = ["dioxus-html"] ssr = ["dioxus-ssr"] web = ["dioxus-web"] desktop = ["dioxus-desktop"] +ayatana = ["dioxus-desktop/ayatana"] router = ["dioxus-router"] -# "dioxus-router/web" -# "dioxus-router/desktop" -# desktop = ["dioxus-desktop", "dioxus-router/desktop"] -# mobile = ["dioxus-mobile"] -# liveview = ["dioxus-liveview"] - - [workspace] members = [ "packages/core", "packages/core-macro", + "packages/rsx", "packages/html", "packages/hooks", "packages/web", @@ -54,18 +53,19 @@ members = [ "packages/desktop", "packages/mobile", "packages/interpreter", + "packages/fermi", ] [dev-dependencies] -futures-util = "0.3.17" +futures-util = "0.3.21" log = "0.4.14" num-format = "0.4.0" separator = "0.4.1" -serde = { version = "1.0.131", features = ["derive"] } +serde = { version = "1.0.136", features = ["derive"] } im-rc = "15.0.0" -anyhow = "1.0.51" -serde_json = "1.0.73" +anyhow = "1.0.53" +serde_json = "1.0.79" rand = { version = "0.8.4", features = ["small_rng"] } -tokio = { version = "1.14.0", features = ["full"] } -reqwest = { version = "0.11.8", features = ["json"] } -dioxus = { path = ".", features = ["desktop", "ssr", "router"] } +tokio = { version = "1.16.1", features = ["full"] } +reqwest = { version = "0.11.9", features = ["json"] } +dioxus = { path = ".", features = ["desktop", "ssr", "router", "fermi"] } diff --git a/README.md b/README.md index 52493b119..40a83dd41 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,5 @@
-

🌗🚀 Dioxus

-

- Frontend that scales. -

+

Dioxus

@@ -26,9 +23,7 @@ CI status -
-
Awesome Page @@ -45,9 +40,11 @@

Website | - Guide - | Examples + | + Guide (0.1.8) + | + Guide (Nightly)

@@ -101,10 +98,10 @@ cargo run --example EXAMPLE - - - - + + + +
TutorialWebDesktopSSRMobileWebDesktopSSRMobile State
@@ -160,9 +157,9 @@ You shouldn't use Dioxus if: ## Comparison with other Rust UI frameworks Dioxus primarily emphasizes **developer experience** and **familiarity with React principles**. -- [Yew](https://github.com/yewstack/yew): prefers the elm pattern instead of React-hooks, no borrowed props, supports SSR (no hydration). +- [Yew](https://github.com/yewstack/yew): prefers the elm pattern instead, no borrowed props, supports SSR (no hydration), no direct desktop/mobile support. - [Percy](https://github.com/chinedufn/percy): Supports SSR but with less emphasis on state management and event handling. -- [Sycamore](https://github.com/sycamore-rs/sycamore): VDOM-less using fine-grained reactivity, but lacking in ergonomics. +- [Sycamore](https://github.com/sycamore-rs/sycamore): VDOM-less using fine-grained reactivity, but no direct support for desktop/mobile. - [Dominator](https://github.com/Pauan/rust-dominator): Signal-based zero-cost alternative, less emphasis on community and docs. - [Azul](https://azul.rs): Fully native HTML/CSS renderer for desktop applications, no support for web/ssr diff --git a/codecov.yml b/codecov.yml new file mode 100644 index 000000000..325c05ec8 --- /dev/null +++ b/codecov.yml @@ -0,0 +1,2 @@ +comment: false +fail_ci_if_error: false diff --git a/docs/cli/.gitignore b/docs/cli/.gitignore new file mode 100644 index 000000000..7585238ef --- /dev/null +++ b/docs/cli/.gitignore @@ -0,0 +1 @@ +book diff --git a/docs/cli/book.toml b/docs/cli/book.toml new file mode 100644 index 000000000..c5c216fe4 --- /dev/null +++ b/docs/cli/book.toml @@ -0,0 +1,6 @@ +[book] +authors = ["YuKun Liu"] +language = "en" +multilingual = false +src = "src" +title = "Dioxus Cli" diff --git a/docs/cli/src/SUMMARY.md b/docs/cli/src/SUMMARY.md new file mode 100644 index 000000000..ed7bcbfaf --- /dev/null +++ b/docs/cli/src/SUMMARY.md @@ -0,0 +1,11 @@ +# Summary + +- [Introduction](./introduction.md) +- [Installation](./installation.md) +- [Create a Project](./creating.md) +- [Configure Project](./configure.md) +- [Commands](./cmd/README.md) + - [Build](./cmd/build.md) + - [Serve](./cmd/serve.md) + - [Clean](./cmd/clean.md) + - [Translate](./cmd/translate.md) \ No newline at end of file diff --git a/docs/cli/src/cmd/README.md b/docs/cli/src/cmd/README.md new file mode 100644 index 000000000..c642b475f --- /dev/null +++ b/docs/cli/src/cmd/README.md @@ -0,0 +1,26 @@ +# Commands + +In this chapter we will introduce all `dioxus-cli` commands. + +> you can also use `dioxus --help` to get cli help info. + +``` +dioxus +Build, bundle, & ship your Dioxus app + +USAGE: + dioxus [OPTIONS] + +OPTIONS: + -h, --help Print help information + -v Enable verbose logging + +SUBCOMMANDS: + build Build the Rust WASM app and all of its assets + clean Clean output artifacts + config Dioxus config file controls + create Init a new project for Dioxus + help Print this message or the help of the given subcommand(s) + serve Build, watch & serve the Rust WASM app and all of its assets + translate Translate some source file into Dioxus code +``` \ No newline at end of file diff --git a/docs/cli/src/cmd/build.md b/docs/cli/src/cmd/build.md new file mode 100644 index 000000000..e81973f2d --- /dev/null +++ b/docs/cli/src/cmd/build.md @@ -0,0 +1,47 @@ +# Build + +The `dioxus build` command can help you `pack & build` a dioxus project. + +``` +dioxus-build +Build the Rust WASM app and all of its assets + +USAGE: + dioxus build [OPTIONS] + +OPTIONS: + --example [default: ""] + --platform [default: "default_platform"] + --release [default: false] +``` + +You can use this command to build project to `out_dir` : + +``` +dioxus build --release +``` + +## Target platform + +Use option `platform` choose build target platform: + +``` +# for desktop project +dioxus build --platform desktop +``` + +`platform` only supports `desktop` & `web`. + +``` +# for web project +dioxus build --platform web +``` + +## Build Example + +You can use `--example {name}` to build a example code. + +``` +# build `example/test` code +dioxus build --exmaple test +``` \ No newline at end of file diff --git a/docs/cli/src/cmd/clean.md b/docs/cli/src/cmd/clean.md new file mode 100644 index 000000000..2f889c1a8 --- /dev/null +++ b/docs/cli/src/cmd/clean.md @@ -0,0 +1,18 @@ +# Clean + +`dioxus clean` will call `target clean` and remove `out_dir` directory. + +``` +dioxus-clean +Clean output artifacts + +USAGE: + dioxus clean +``` + +you can use this command to clean all build cache and the `out_dir` content. + +``` +dioxus clean +``` + diff --git a/docs/cli/src/cmd/serve.md b/docs/cli/src/cmd/serve.md new file mode 100644 index 000000000..e5c10a902 --- /dev/null +++ b/docs/cli/src/cmd/serve.md @@ -0,0 +1,49 @@ +# Serve + +The `dioxus serve` can start a dev server (include hot-reload tool) to run the project. + +``` +dioxus-serve +Build, watch & serve the Rust WASM app and all of its assets + +USAGE: + dioxus serve [OPTIONS] + +OPTIONS: + --example [default: ""] + --platform [default: "default_platform"] + --release [default: false] +``` + +You can use this command to build project and start a `dev server` : + +``` +dioxus serve +``` + +## Target platform + +Use option `platform` choose build target platform: + +``` +# for desktop project +dioxus serve --platform desktop +``` + +`platform` only supports `desktop` & `web`. + +`dev-server` only for `web` project. + +``` +# for web project +dioxus serve --platform web +``` + +## Serve Example + +You can use `--example {name}` to start a example code. + +``` +# build `example/test` code +dioxus serve --exmaple test +``` \ No newline at end of file diff --git a/docs/cli/src/cmd/translate.md b/docs/cli/src/cmd/translate.md new file mode 100644 index 000000000..415a88fba --- /dev/null +++ b/docs/cli/src/cmd/translate.md @@ -0,0 +1,57 @@ +# Translate + +`dioxus translate` can translate some source file into Dioxus code. + +``` +dioxus-translate +Translate some source file into Dioxus code + +USAGE: + dioxus translate [OPTIONS] [OUTPUT] + +ARGS: + Output file, stdout if not present + +OPTIONS: + -c, --component Activate debug mode + -f, --file Input file +``` + +## Translate HTML to stdout + +``` +dioxus transtale --file ./index.html +``` + +## Output in a file + +``` +dioxus translate --component --file ./index.html component.rsx +``` + +set `component` flag will wrap `dioxus rsx` code in a component function. + +## Example + +```html +
+

Hello World

+ Link +
+``` + +Translate HTML to Dioxus component code. + +```rust +fn component(cx: Scope) -> Element { + cx.render(rsx! { + div { + h1 { "Hello World" }, + a { + href: "https://dioxuslabs.com/", + "Link" + } + } + }) +} +``` \ No newline at end of file diff --git a/docs/cli/src/configure.md b/docs/cli/src/configure.md new file mode 100644 index 000000000..f274ce70d --- /dev/null +++ b/docs/cli/src/configure.md @@ -0,0 +1,147 @@ +# Configure Project + +This chapter will introduce `Dioxus.toml` and anatomy the config file. + +## Structure + +We use `toml` to define some info for `dioxus` project. + +### Application + +1. ***name*** - project name & title +2. ***default_platform*** - which platform target for this project. + ``` + # current support: web, desktop + # default: web + default_platform = "web" + ``` + change this to `desktop`, the `dioxus build & serve` will default build desktop app. +3. ***out_dir*** - which directory to put the output file; use `dioxus build & service`, the output will put at this directory, and the `assets` will be also copy to here. + ``` + out_dir = "dist" + ``` +4. ***asset_dir*** - which direcotry to put your `static, assets` file, cli will automatic copy all file to `out_dir`, so you can put some resource file in there, like `CSS, JS, Image` file. + ``` + asset_dir = "public" + ``` + +### Web.App + +Web platform application config: + +1. ***title*** - this value will display on the web page title. like `` tag. + ``` + # HTML title tag content + title = "dioxus app | ⛺" + ``` + +### Web.Watcher + +Web platform `dev-server` watcher config: + +1. ***reload_html*** - a boolean value; when watcher trigger, regenerate `index.html` file. + ``` + # when watcher trigger, regenerate the `index.html` + reload_html = true + ``` +2. ***watch_path*** - which files & directories will be watcher monitoring. + ``` + watch_path = ["src", "public"] + ``` + +### Web.Resource + +Include some `CSS Javascript` resources into html file. + +1. ***style*** - include some style(CSS) file into html. + ``` + style = [ + # include from public_dir. + "./assets/style.css", + # or some asset from online cdn. + "https://cdn.jsdelivr.net/npm/bootstrap/dist/css/bootstrap.css" + ] + ``` +2. ***script*** - include some script(JS) file into html. + ``` + style = [ + # include from public_dir. + "./assets/index.js", + # or some asset from online cdn. + "https://cdn.jsdelivr.net/npm/bootstrap/dist/js/bootstrap.js" + ] + ``` + +### Web.Resource.Dev + +Only include resources at `Dev` mode. + +1. ***style*** - include some style(CSS) file into html. + ``` + style = [ + # include from public_dir. + "./assets/style.css", + # or some asset from online cdn. + "https://cdn.jsdelivr.net/npm/bootstrap/dist/css/bootstrap.css" + ] + ``` +2. ***script*** - include some script(JS) file into html. + ``` + style = [ + # include from public_dir. + "./assets/index.js", + # or some asset from online cdn. + "https://cdn.jsdelivr.net/npm/bootstrap/dist/js/bootstrap.js" + ] + ``` + +## Config example + +```toml +[application] + +# App (Project) Name +name = "{{project-name}}" + +# Dioxus App Default Platform +# desktop, web, mobile, ssr +default_platform = "web" + +# `build` & `serve` dist path +out_dir = "dist" + +# resource (public) file folder +asset_dir = "public" + +[web.app] + +# HTML title tag content +title = "dioxus | ⛺" + +[web.watcher] + +# when watcher trigger, regenerate the `index.html` +reload_html = true + +# which files or dirs will be watcher monitoring +watch_path = ["src", "public"] + +# include `assets` in web platform +[web.resource] + +# CSS style file +style = [] + +# Javascript code file +script = [] + +[web.resource.dev] + +# serve: [dev-server] only + +# CSS style file +style = [] + +# Javascript code file +script = [] +``` \ No newline at end of file diff --git a/docs/cli/src/creating.md b/docs/cli/src/creating.md new file mode 100644 index 000000000..fa725a4f7 --- /dev/null +++ b/docs/cli/src/creating.md @@ -0,0 +1,38 @@ +# Create a Project + +Once you have the Dioxus CLI tool installed, you can use it to create dioxus project. + +## Initializing a default project + +The `dioxus create` command will create a new directory containing a project template. +``` +dioxus create hello-dioxus +``` + +It will clone a default template from github template: [DioxusLabs/dioxus-template](https://github.com/DioxusLabs/dioxus-template) + +> This default template is use for `web` platform application. + +then you can change the current directory in to the project: + +``` +cd hello-dioxus +``` + +> Make sure `wasm32 target` is installed before running the Web project. + +now we can create a `dev server` to display the project: + +``` +dioxus serve +``` + +by default, the dioxus dev server will running at: [`http://127.0.0.1:8080/`](http://127.0.0.1:8080/) + +## Initalizing from other repository + +you can assign which repository you want to create: + +``` +dioxus init hello-dioxus --template=gh:dioxuslabs/dioxus-template +``` \ No newline at end of file diff --git a/docs/cli/src/installation.md b/docs/cli/src/installation.md new file mode 100644 index 000000000..7151de1ff --- /dev/null +++ b/docs/cli/src/installation.md @@ -0,0 +1,24 @@ +# Installation + +There are multiple ways to install the Dioxus CLI tool. Choose any one of the methods below that best suit your needs. + +## Install from latest master version + +We suggest you use `github master` version to install it now. + +We have not yet released the latest version to `crates.io` + +``` +cargo install --git https://github.com/Dioxuslabs/cli +``` + +This will automatically download `Dioxus-CLI` source from github master branch, +and install it in Cargo's global binary directory (`~/.cargo/bin/` by default). + +## Install from `crates.io` version + +``` +cargo install dioxus-cli +``` + +Make sure to add the Cargo bin directory to your `PATH`. \ No newline at end of file diff --git a/docs/cli/src/introduction.md b/docs/cli/src/introduction.md new file mode 100644 index 000000000..2f857a2a5 --- /dev/null +++ b/docs/cli/src/introduction.md @@ -0,0 +1,21 @@ +# Introduction + +📦✨ **Dioxus-Cli** is a tool to help get dioxus projects off the ground. + +![dioxus-logo](https://dioxuslabs.com/guide/images/dioxuslogo_full.png) + +It includes `dev server`, `hot reload` and some `quick command` to help you use dioxus. + +## Features + +- [x] `html` to `rsx` conversion tool +- [x] hot reload for `web` platform +- [x] create dioxus project from `git` repo +- [x] build & pack dioxus project +- [ ] autoformat dioxus `rsx` code + +## Contributors + +Contributors to this guide: + +- [mrxiaozhuox](https://github.com/mrxiaozhuox) \ No newline at end of file diff --git a/docs/fermi/.gitignore b/docs/fermi/.gitignore new file mode 100644 index 000000000..7585238ef --- /dev/null +++ b/docs/fermi/.gitignore @@ -0,0 +1 @@ +book diff --git a/docs/fermi/book.toml b/docs/fermi/book.toml new file mode 100644 index 000000000..dd6d2eacb --- /dev/null +++ b/docs/fermi/book.toml @@ -0,0 +1,6 @@ +[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 new file mode 100644 index 000000000..7390c8289 --- /dev/null +++ b/docs/fermi/src/SUMMARY.md @@ -0,0 +1,3 @@ +# Summary + +- [Chapter 1](./chapter_1.md) diff --git a/docs/fermi/src/chapter_1.md b/docs/fermi/src/chapter_1.md new file mode 100644 index 000000000..b743fda35 --- /dev/null +++ b/docs/fermi/src/chapter_1.md @@ -0,0 +1 @@ +# Chapter 1 diff --git a/docs/guide/src/README.md b/docs/guide/src/README.md index c00dcd274..da6c0156f 100644 --- a/docs/guide/src/README.md +++ b/docs/guide/src/README.md @@ -5,24 +5,24 @@ **Dioxus** is a framework and ecosystem for building fast, scalable, and robust user interfaces with the Rust programming language. This guide will help you get started with Dioxus running on the Web, Desktop, Mobile, and more. ```rust -fn App(cx: Scope) -> Element { - let mut count = use_state(&cx, || 0); +fn app(cx: Scope) -> Element { + let (count, set_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!" } + button { onclick: move |_| set_count(count + 1), "Up high!" } + button { onclick: move |_| set_count(count - 1), "Down low!" } )) }; ``` In general, Dioxus and React share many functional similarities. If this guide is lacking in any general concept or an error message is confusing, React's documentation might be more helpful. We are dedicated to providing a *familiar* toolkit for UI in Rust, so we've chosen to follow in the footsteps of popular UI frameworks (React, Redux, etc). If you know React, then you already know Dioxus. If you don't know either, this guide will still help you! -> This is an introduction book! For advanced topics, check out the [Reference](https://dioxuslabs.com/reference) instead. +> This is an introduction book! For advanced topics, check out the [Reference](/reference) instead. ## 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 Web-Sys. 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. +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) @@ -37,7 +37,7 @@ The Web is the best-supported target platform for Dioxus. To run on the Web, you Because the web is a fairly mature platform, we expect there to be very little API churn for web-based features. -[Jump to the getting started guide for the web.]() +[Jump to the getting started guide for the web.](/reference/platforms/web) Examples: - [TodoMVC](https://github.com/DioxusLabs/example-projects/tree/master/todomvc) @@ -55,7 +55,7 @@ For rendering statically to an `.html` file or from a WebServer, then you'll wan let contents = dioxus::ssr::render_vdom(&dom); ``` -[Jump to the getting started guide for SSR.]() +[Jump to the getting started guide for SSR.](/reference/platforms/ssr) Examples: - [Example DocSite](https://github.com/dioxusLabs/docsite) @@ -68,13 +68,13 @@ The desktop is a powerful target for Dioxus, but is currently limited in capabil Desktop APIs will likely be in flux as we figure out better patterns than our ElectronJS counterpart. -[Jump to the getting started guide for Desktop.]() +[Jump to the getting started guide for Desktop.](/reference/platforms/desktop) Examples: - [File explorer](https://github.com/dioxusLabs/file-explorer/) - [WiFi scanner](https://github.com/DioxusLabs/example-projects/blob/master/wifi-scanner) -[![File ExplorerExample](https://github.com/DioxusLabs/file-explorer-example/raw/master/image.png)](https://github.com/dioxusLabs/file-explorer/) +[![File ExplorerExample](https://raw.githubusercontent.com/DioxusLabs/example-projects/master/file-explorer/image.png)](https://github.com/DioxusLabs/example-projects/tree/master/file-explorer) ### Mobile Support --- @@ -82,7 +82,7 @@ Mobile is currently the least-supported renderer target for Dioxus. Mobile apps 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. -[Jump to the getting started guide for Mobile.]() +[Jump to the getting started guide for Mobile.](/reference/platforms/mobile) Examples: - [Todo App](https://github.com/DioxusLabs/example-projects/blob/master/ios_demo) diff --git a/docs/guide/src/ROADMAP.md b/docs/guide/src/ROADMAP.md new file mode 100644 index 000000000..4f78e6043 --- /dev/null +++ b/docs/guide/src/ROADMAP.md @@ -0,0 +1,114 @@ +# Roadmap & Feature-set + +Before we dive into Dioxus, feel free to take a look at our feature set and roadmap to see 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 +- ❓ = not sure if will or can implement + + +## Roadmap +--- + + +Core: +- [x] Release of Dioxus Core +- [x] Upgrade documentation to include more theory and be more comprehensive +- [ ] 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 +- [ ] Fully native renderer +- [ ] Access to Canvas/WebGL context natively + +Mobile +- [ ] Mobile standard library + - [ ] GPS + - [ ] Camera + - [ ] filesystem + - [ ] Biometrics + - [ ] WiFi + - [ ] Bluetooth + - [ ] Notifications + - [ ] Clipboard + - [ ] + +Bundling (CLI) +- [x] translation from HTML into RSX +- [ ] dev server +- [ ] live reload +- [ ] translation from JSX into RSX +- [ ] hot module replacement +- [ ] code splitting +- [ ] asset macros +- [ ] css pipeline +- [ ] image pipeline + +Essential hooks +- [ ] Router +- [ ] Global state management +- [ ] Resize observer + + diff --git a/docs/guide/src/SUMMARY.md b/docs/guide/src/SUMMARY.md index 2fa29f39e..fff21fd02 100644 --- a/docs/guide/src/SUMMARY.md +++ b/docs/guide/src/SUMMARY.md @@ -1,19 +1,23 @@ # Summary - [Introduction](README.md) +- [Roadmap](ROADMAP.md) - [Getting Set Up](setup.md) - [Hello, World!](hello_world.md) - [Describing the UI](elements/index.md) - [Intro to Elements](elements/vnodes.md) - - [Intro to Components](elements/components.md) - - [The Props Macro](elements/propsmacro.md) - - [Reusing, Importing, and Exporting Components](elements/exporting_components.md) - - [Passing children and attributes](elements/component_children.md) - [Conditional Rendering](elements/conditional_rendering.md) - [Lists](elements/lists.md) + - [Special Attributes](elements/special_attributes.md) +- [Components](components/index.md) + - [Properties](components/propsmacro.md) + - [Reusing, Importing, and Exporting](components/exporting_components.md) + - [Children and Attributes](components/component_children.md) + - [How Data Flows](components/composing.md) - [Adding Interactivity](interactivity/index.md) - [Hooks and Internal State](interactivity/hooks.md) - - [Event handlers](interactivity/event_handlers.md) + - [UseState and UseRef](interactivity/importanthooks.md) + - [Event Listeners](interactivity/event_handlers.md) - [User Input and Controlled Components](interactivity/user_input.md) - [Lifecycle, updates, and effects](interactivity/lifecycles.md) - [Managing State](state/index.md) @@ -41,3 +45,4 @@ + diff --git a/docs/guide/src/async/fetching.md b/docs/guide/src/async/fetching.md index 99e726c7a..b31c3d03b 100644 --- a/docs/guide/src/async/fetching.md +++ b/docs/guide/src/async/fetching.md @@ -1 +1,4 @@ # Fetching + + +This section is currently under construction! 🏗 diff --git a/docs/guide/src/async/index.md b/docs/guide/src/async/index.md index 47b84e81a..0ec02e57d 100644 --- a/docs/guide/src/async/index.md +++ b/docs/guide/src/async/index.md @@ -17,3 +17,6 @@ Writing apps that deal with Send/Sync can be frustrating at times. Under the hoo All async code in your app is polled on a `LocalSet`, so any async code we w + + +> This section is currently under construction! 🏗 diff --git a/docs/guide/src/elements/component_children.md b/docs/guide/src/components/component_children.md similarity index 92% rename from docs/guide/src/elements/component_children.md rename to docs/guide/src/components/component_children.md index d99273394..1259422af 100644 --- a/docs/guide/src/elements/component_children.md +++ b/docs/guide/src/components/component_children.md @@ -30,7 +30,7 @@ struct ClickableProps<'a> { title: &'a str } -fn Clickable(cx: Scope) -> Element { +fn Clickable<'a>(cx: Scope<'a, ClickableProps<'a>>) -> Element { cx.render(rsx!( a { href: "{cx.props.href}" @@ -64,7 +64,7 @@ struct ClickableProps<'a> { body: Element<'a> } -fn Clickable(cx: Scope) -> Element { +fn Clickable<'a>(cx: Scope<'a, ClickableProps<'a>>) -> Element { cx.render(rsx!( a { href: "{cx.props.href}", @@ -98,7 +98,7 @@ struct ClickableProps<'a> { children: Element<'a> } -fn Clickable(cx: Scope) -> Element { +fn Clickable<'a>(cx: Scope<'a, ClickableProps<'a>>) -> Element { cx.render(rsx!( a { href: "{cx.props.href}", @@ -125,7 +125,7 @@ While technically allowed, it's an antipattern to pass children more than once i However, because the `Element` is transparently a `VNode`, we can actually match on it to extract the nodes themselves, in case we are expecting a specific format: ```rust -fn clickable(cx: Scope) -> Element { +fn clickable<'a>(cx: Scope<'a, ClickableProps<'a>>) -> Element { match cx.props.children { Some(VNode::Text(text)) => { // ... @@ -137,7 +137,7 @@ fn clickable(cx: Scope) -> Element { } ``` -## Passing attributes + ## Passing handlers @@ -184,7 +184,7 @@ struct ClickableProps<'a> { onclick: EventHandler<'a, MouseEvent> } -fn clickable(cx: Scope) -> Element { +fn clickable<'a>(cx: Scope<'a, ClickableProps<'a>>) -> Element { cx.render(rsx!( a { onclick: move |evt| cx.props.onclick.call(evt) @@ -215,5 +215,3 @@ In this chapter, we learned: - How to convert `listeners` into `EventHandlers` for components - How to extend any node with custom attributes and children -Next chapter, we'll talk about conditionally rendering parts of your user interface. - diff --git a/docs/guide/src/components/component_example_title.png b/docs/guide/src/components/component_example_title.png new file mode 100644 index 000000000..60a5a329e Binary files /dev/null and b/docs/guide/src/components/component_example_title.png differ diff --git a/docs/guide/src/components/component_example_votes.png b/docs/guide/src/components/component_example_votes.png new file mode 100644 index 000000000..b46739b24 Binary files /dev/null and b/docs/guide/src/components/component_example_votes.png differ diff --git a/docs/guide/src/components/composing.md b/docs/guide/src/components/composing.md new file mode 100644 index 000000000..785387e1b --- /dev/null +++ b/docs/guide/src/components/composing.md @@ -0,0 +1,243 @@ +# Thinking in React + +We've finally reached the point in our tutorial where we can talk about the theory of Reactive interfaces. 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 the very few 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 +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 +// 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 +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 +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 +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 +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 +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/elements/exporting_components.md b/docs/guide/src/components/exporting_components.md similarity index 96% rename from docs/guide/src/elements/exporting_components.md rename to docs/guide/src/components/exporting_components.md index 117249db8..727e5b6b6 100644 --- a/docs/guide/src/elements/exporting_components.md +++ b/docs/guide/src/components/exporting_components.md @@ -1,4 +1,3 @@ - # Reusing, Importing, and Exporting Components As your application grows in size, you'll want to start breaking your UI into components and, eventually, different files. This is a great idea to encapsulate functionality of your UI and scale your team. @@ -66,6 +65,16 @@ fn ActionCard(Scope) -> Element {} We should also create a `mod.rs` file in the `post` folder so we can use it from our `main.rs`. Our `Post` component and its props will go into this file. +```rust +// src/post/mod.rs + +use dioxus::prelude::*; + +#[derive(PartialEq, Props)] +struct PostProps {} +fn Post(Scope) -> Element {} +``` + ```shell ├── Cargo.toml └── src @@ -78,8 +87,6 @@ We should also create a `mod.rs` file in the `post` folder so we can use it from └── mod.rs ``` - - In our `main.rs`, we'll want to declare the `post` module so we can access our `Post` component. ```rust @@ -164,7 +171,6 @@ pub fn Post(Scope) -> Element { } ``` - Ultimately, including and exporting components is governed by Rust's module system. [The Rust book is a great resource to learn about these concepts in greater detail.](https://doc.rust-lang.org/book/ch07-00-managing-growing-projects-with-packages-crates-and-modules.html) ## Final structure: @@ -284,14 +290,3 @@ use dioxus::prelude::*; pub struct ActionCardProps {} pub fn ActionCard(Scope) -> Element {} ``` - -## Moving forward - -Next chapter, we'll start to add use code to hide and show Elements with conditional rendering. - -For more reading on components: - -- [Components in depth]() -- [Lifecycles]() -- [The Context object]() -- [Optional Prop fields]() diff --git a/docs/guide/src/components/index.md b/docs/guide/src/components/index.md new file mode 100644 index 000000000..ff4811a33 --- /dev/null +++ b/docs/guide/src/components/index.md @@ -0,0 +1,42 @@ +# Introduction to Components + +In the previous chapter, we learned about Elements and how they can be composed to create a basic user interface. Now, we'll learn how to group Elements together to form Components. We'll cover: + +- What makes a Component +- How to model a component and its properties in Dioxus +- How to "think declaratively" + +## What is a component? + +In short, a component is a special function that takes input properties and outputs an Element. Much like a function encapsulates some specific computation task, a Component encapsulates some specific rendering task – typically, rendering an isolated part of the user interface. + +### Real-world example + +Let's use a Reddit post as an example: + +![Reddit Post](../images/reddit_post.png) + +If we look at the layout of the component, we notice quite a few buttons and pieces of functionality: + +- Upvote/Downvote +- View comments +- Share +- Save +- Hide +- Give award +- Report +- Crosspost +- Filter by site +- View article +- Visit user + +If we included all this functionality in one `rsx!` call it would be huge! Instead, let's break the post down into Components: + +![Post as Component](../images/reddit_post_components.png) + +- **VoteButton**: Upvote/Downvote +- **TitleCard**: Title, Filter-By-Url +- **MetaCard**: Original Poster, Time Submitted +- **ActionCard**: View comments, Share, Save, Hide, Give award, Report, Crosspost + +In this chapter, we'll learn how to define these components. diff --git a/docs/guide/src/components/propsmacro.md b/docs/guide/src/components/propsmacro.md new file mode 100644 index 000000000..83b01a3ea --- /dev/null +++ b/docs/guide/src/components/propsmacro.md @@ -0,0 +1,200 @@ +# Component Properties +Dioxus components are functions that accept Props as input and output an Element. In fact, the `App` function you saw in the previous chapter was a component with no Props! Most components, however, will need to take some Props to render something useful – so, in this section, we'll learn about props: + +- Deriving the Props trait +- Memoization through PartialEq +- Optional fields on props +- The inline_props macro + +## Props +The input of your Component must be passed in a single struct, which must implement the `Props` trait. We can derive this trait automatically with `#[derive(Props)]`. + +> Dioxus `Props` is very similar to [@idanarye](https://github.com/idanarye)'s [TypedBuilder crate](https://github.com/idanarye/rust-typed-builder) and supports many of the same parameters. + +There are 2 flavors of Props: owned and borrowed. + +- All Owned Props must implement `PartialEq` +- Borrowed props [borrow](https://doc.rust-lang.org/beta/rust-by-example/scope/borrow.html) values from the parent Component + +### Owned Props + +Owned Props are very simple – they don't borrow anything. Example: +```rust +// Remember: owned props must implement PartialEq! +#[derive(PartialEq, Props)] +struct VoteButtonProps { + score: i32 +} + +fn VoteButton(cx: Scope) -> Element { + cx.render(rsx!{ + div { + div { "+" } + div { "{cx.props.score}"} + div { "-" } + } + }) +} +``` + +Now, we can use the VoteButton Component like we would use a regular HTML element: + +```rust +fn main() { + dioxus::desktop::launch(App); +} + +fn App(cx: Scope) -> Element { + cx.render(rsx! ( + VoteButton { score: 42 } + )) +} +``` + +And we can see that the Component indeed gets rendered: + +![Screenshot of running app. Text: "+ \ 42 \ -"](component_example_votes.png) + +> The simplest Owned Props you can have is `()` - or no value at all. This is what the `App` Component takes as props. `Scope` accepts a generic for the Props which defaults to `()`. +> +> ```rust +>// this scope +>Scope<()> +> +>// is the same as this scope +>Scope +>``` + +### Borrowed Props + +Owning props works 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`. Instead of creating a copy, this will give us a reference to the original String – this is what Borrowed Props are for! + +However, if we create a reference a String, Rust will require us to show that the String will not go away while we're using the reference. Otherwise, if we referenced something that doesn't exist, Bad Things could happen. To prevent this, Rust asks us to define a lifetime for the reference: + +```rust +#[derive(Props)] +struct TitleCardProps<'a> { + title: &'a str, +} + +fn TitleCard<'a>(cx: Scope<'a, TitleCardProps<'a>>) -> Element { + cx.render(rsx!{ + h1 { "{cx.props.title}" } + }) +} +``` + +This lifetime `'a` tells the compiler that as long as `title` exists, the String it was created from must also exist. Dioxus will happily accept such a component – we can now render it alongside our VoteButton! + +```rust +fn App(cx: Scope) -> Element { + // For the sake of an example, we create the &str here. + // But you might as well borrow it from an owned String type. + let hello = "Hello Dioxus!"; + + cx.render(rsx! ( + VoteButton { score: 42 }, + TitleCard { title: hello } + )) +} +``` +![New screenshot of running app, now including a "Hello Dioxus!" heading.](component_example_title.png) + +## 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 +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. + +## Optional Props + +You can easily create optional fields by attaching the `optional` modifier to a field: + +```rust +#[derive(Props, PartialEq)] +struct MyProps { + name: String, + + #[props(optional)] + description: Option +} + +fn Demo(cx: MyProps) -> Element { + todo!() +} +``` + +Then, we can completely omit the description field when calling the component: + +```rust +rsx!{ + Demo { + name: "Thing".to_string(), + // description is omitted + } +} +``` + +The `optional` modifier is a combination of two separate modifiers: `default` and `strip_option`. The full list of modifiers includes: + +- `default` - automatically add the field using its `Default` implementation +- `strip_option` - automatically wrap values at the call site in `Some` +- `optional` - alias for `default` and `strip_option` +- `into` - automatically call `into` on the value at the callsite + +For more information on how tags work, check out the [TypedBuilder](https://github.com/idanarye/rust-typed-builder) crate. However, all attributes for props in Dioxus are flattened (no need for `setter` syntax) and the `optional` field is new. + +## 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 +#[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 +#[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/elements/components.md b/docs/guide/src/elements/components.md deleted file mode 100644 index ea43034d9..000000000 --- a/docs/guide/src/elements/components.md +++ /dev/null @@ -1,227 +0,0 @@ -# Introduction to Components - -In the previous chapter, we learned about Elements and how they can be composed to create a basic User Interface. In this chapter, we'll learn how to group Elements together to form Components. - -In this chapter, we'll learn: -- What makes a Component -- How to model a component and its properties in Dioxus -- How to "think declaratively" - -## What is a component? - -In short, a component is a special function that takes input properties and outputs an Element. Typically, Components serve a single purpose: group functionality of a User Interface. Much like a function encapsulates some specific computation task, a Component encapsulates some specific rendering task. - -### Learning through prior art - -Let's take a look at a post on r/rust and see if we can sketch out a component representation. - -![Reddit Post](../images/reddit_post.png) - -This component has a bunch of important information: - -- The score -- The number of comments -- How long ago it was posted -- The url short address -- The title -- The username of the original poster - -If we wanted to sketch out these requirements in Rust, we would start with a struct: - -```rust -struct PostData { - score: i32, - comment_count: u32, - post_time: Instant, - url: String, - title: String, - original_poster_name: String -} -``` - -If we look at the layout of the component, we notice quite a few buttons and pieces of functionality: - -- Upvote/Downvote -- View comments -- Share -- Save -- Hide -- Give award -- Report -- Crosspost -- Filter by site -- View article -- Visit user - -If we included all this functionality in one `rsx!` call it would be huge! Instead, let's break the post down into some core pieces: - -![Post as Component](../images/reddit_post_components.png) - -- **VoteButton**: Upvote/Downvote -- **TitleCard**: Title, Filter-By-Url -- **MetaCard**: Original Poster, Time Submitted -- **ActionCard**: View comments, Share, Save, Hide, Give award, Report, Crosspost - -### Modeling with Dioxus - -We can start by sketching out the Element hierarchy using Dioxus. In general, our "Post" component will be comprised of the four sub-components listed above. First, let's define our `Post` component. - -Unlike normal functions, Dioxus components must explicitly define a single struct to contain all the inputs. These are commonly called "Properties" (props). Our component will be a combination of these properties and a function to render them. - -Our props must implement the `Props` trait and - if the component does not borrow any data - `PartialEq`. Both of these can be done automatically through derive macros: -```rust -#[derive(Props, PartialEq)] -struct PostProps { - id: Uuid, - score: i32, - comment_count: u32, - post_time: Instant, - url: String, - title: String, - original_poster: String -} -``` - -And our render function: -```rust -fn Post(cx: Scope) -> Element { - cx.render(rsx!{ - div { class: "post-container" - VoteButton { - score: cx.props.score, - } - TitleCard { - title: cx.props.title, - url: cx.props.url, - } - MetaCard { - original_poster: cx.props.original_poster, - post_time: cx.props.post_time, - } - ActionCard { - post_id: cx.props.id - } - } - }) -} -``` - -When declaring a component in `rsx!`, we can pass in properties using the traditional Rust struct syntax. Dioxus will automatically call "into" on the property fields, cloning when necessary. Our `Post` component is simply a collection of smaller components wrapped together in a single container. - -Let's take a look at the `VoteButton` component. For now, we won't include any interactivity - just the rendering the score and buttons to the screen. - -Most of your Components will look exactly like this: a Props struct and a render function. Every component must take a `Scope` generic over some `Props` and return an `Element`. - -As covered before, we'll build our User Interface with the `rsx!` macro and HTML tags. However, with components, we must actually "render" our HTML markup. Calling `cx.render` converts our "lazy" `rsx!` structure into an `Element`. - -```rust -#[derive(PartialEq, Props)] -struct VoteButtonProps { - score: i32 -} - -fn VoteButton(cx: Scope) -> Element { - cx.render(rsx!{ - div { class: "votebutton" - div { class: "arrow up" } - div { class: "score", "{cx.props.score}"} - div { class: "arrow down" } - } - }) -} -``` - -## Borrowing - -You can avoid clones by using borrowed component syntax. For example, let's say we passed the `TitleCard` title as an `&str` instead of `String`. In JavaScript, the string would be copied by reference - none of the contents would be copied, but rather the reference to the string's contents are copied. In Rust, this would be similar to calling `clone` on `Rc`. - -Because we're working in Rust, we can choose to either use `Rc`, clone `Title` on every re-render of `Post`, or simply borrow it. In most cases, you'll just want to let `Title` be cloned. - -To enable borrowed values for your component, we need to add a lifetime to let the Rust compiler know that the output `Element` borrows from the component's props. - -```rust -#[derive(Props)] -struct TitleCardProps<'a> { - title: &'a str, -} - -fn TitleCard<'a>(cx: Scope<'a, TitleCardProps<'a>>) -> Element { - cx.render(rsx!{ - h1 { "{cx.props.title}" } - }) -} -``` - -For users of React: Dioxus knows *not* to memoize components that borrow property fields. By default, every component in Dioxus is memoized. This can be disabled by the presence of a non-`'static` borrow. - -This means that during the render process, a newer version of `TitleCardProps` will never be compared with a previous version, saving some clock cycles. - -## The inline_props macro - -Yes - *another* macro! However, this one is entirely optional. - -For internal components, we provide the `inline_props` macro, which will let you embed your `Props` definition right into the function arguments of your component. - -Our title card above would be transformed from: - -```rust -#[derive(Props, PartialEq)] -struct TitleCardProps { - title: String, -} - -fn TitleCard(cx: Scope) -> Element { - cx.render(rsx!{ - h1 { "{cx.props.title}" } - }) -} -``` - -to: - -```rust -#[inline_props] -fn TitleCard(cx: Scope, title: String) -> Element { - cx.render(rsx!{ - h1 { "{title}" } - }) -} -``` - -Again, this macro is optional and should not be used by library authors since you have less fine-grained control over documentation and optionality. - -However, it's great for quickly throwing together an app without dealing with *any* extra boilerplate. - -## The `Scope` object - -Though very similar to React, Dioxus is different in a few ways. Most notably, React components will not have a `Scope` parameter in the component declaration. - -Have you ever wondered how the `useState()` call works in React without a `this` object to actually store the state? - -React uses global variables to store this information. Global mutable variables must be carefully managed and are broadly discouraged in Rust programs. - -```javascript -function Component(props) { - let [state, set_state] = useState(10); -} -``` - - -Because Dioxus needs to work with the rules of Rust it uses the `Scope` object to maintain some internal bookkeeping. That's what the `Scope` object is: a place for the component to store state, manage listeners, and allocate elements. Advanced users of Dioxus will want to learn how to properly leverage the `Scope` object to build robust and performant extensions for Dioxus. - -```rust -fn Post(cx: Scope) -> Element { - cx.render(rsx!("hello")) -} -``` -## Moving forward - -Next chapter, we'll talk about composing Elements and Components across files to build a larger Dioxus App. - -For more references on components, make sure to check out: - -- [Components in depth]() -- [Lifecycles]() -- [The Scope object]() -- [Optional Prop fields]() - diff --git a/docs/guide/src/elements/conditional_rendering.md b/docs/guide/src/elements/conditional_rendering.md index c13263cf6..5c19de237 100644 --- a/docs/guide/src/elements/conditional_rendering.md +++ b/docs/guide/src/elements/conditional_rendering.md @@ -67,7 +67,7 @@ fn App(cx: Scope)-> Element { } ``` -Do note: the `rsx!` macro returns a `Closure`, an anonymous function that has a unique type. To turn our `rsx!` into Elements, we need to call `cx.render`. +Do note: the `rsx!` macro does not return an Element, but rather a wrapper struct for a `Closure` (an anonymous function). To turn our `rsx!` into an Element, we need to call `cx.render`. To make patterns like these less verbose, the `rsx!` macro accepts an optional first argument on which it will call `render`. Our previous component can be shortened with this alternative syntax: @@ -136,34 +136,6 @@ cx.render(rsx!{ }) ``` - -## Boolean Mapping - -In the spirit of highly-functional apps, we suggest using the "boolean mapping" pattern when trying to conditionally hide/show an Element. - -By default, Rust lets you convert any `boolean` into any other type by calling `and_then()`. We can exploit this functionality in components by mapping to some Element. - -```rust -let show_title = true; -rsx!( - div { - show_title.and_then(|| rsx!{ - "This is the title" - }) - } -) -``` - -We can use this pattern for many things, including options: -```rust -let user_name = Some("bob"); -rsx!( - div { - user_name.map(|name| rsx!("Hello {name}")) - } -) -``` - ## Rendering Nothing Sometimes, you don't want your component to return anything at all. Under the hood, the `Element` type is just an alias for `Option`, so you can simply return `None`. @@ -176,11 +148,37 @@ fn demo(cx: Scope) -> Element { } ``` +## Boolean Mapping + +In the spirit of highly-functional apps, we suggest using the "boolean mapping" pattern when trying to conditionally hide/show an Element. + +By default, Rust lets you convert any `boolean` into an Option of any other type with [`then()`](https://doc.rust-lang.org/std/primitive.bool.html#method.then). We can use this in Components by mapping to some Element. + +```rust +let show_title = true; +rsx!( + div { + // Renders nothing by returning None when show_title is false + show_title.then(|| rsx!{ + "This is the title" + }) + } +) +``` + +We can use this pattern for many things, including options: +```rust +let user_name = Some("bob"); +rsx!( + div { + // Renders nothing if user_name is None + user_name.map(|name| rsx!("Hello {name}")) + } +) +``` + ## Moving Forward: -In this chapter, we learned how to render different Elements from a Component depending on a condition. This is a very powerful building block to assemble complex User Interfaces! +In this chapter, we learned how to render different Elements from a Component depending on a condition. This is a very powerful building block to assemble complex user interfaces! In the next chapter, we'll cover how to renderer lists inside your `rsx!`. - -Related Reading: -- [RSX in Depth]() diff --git a/docs/guide/src/elements/index.md b/docs/guide/src/elements/index.md index aedc39e34..c814945d1 100644 --- a/docs/guide/src/elements/index.md +++ b/docs/guide/src/elements/index.md @@ -68,6 +68,6 @@ Remember: this concept is not new! Many frameworks are declarative - with React Here's some reading about declaring UI in React: -- [https://stackoverflow.com/questions/33655534/difference-between-declarative-and-imperative-in-react-js](https://stackoverflow.com/questions/33655534/difference-between-declarative-and-imperative-in-react-js) +- [Difference between declarative and imperative in React.js](https://stackoverflow.com/questions/33655534/difference-between-declarative-and-imperative-in-react-js), a StackOverflow thread -- [https://medium.com/@myung.kim287/declarative-vs-imperative-251ce99c6c44](https://medium.com/@myung.kim287/declarative-vs-imperative-251ce99c6c44) +- [Declarative vs Imperative](https://medium.com/@myung.kim287/declarative-vs-imperative-251ce99c6c44), a blog post by Myung Kim diff --git a/docs/guide/src/elements/lists.md b/docs/guide/src/elements/lists.md index 37e87b7da..8cd58c841 100644 --- a/docs/guide/src/elements/lists.md +++ b/docs/guide/src/elements/lists.md @@ -10,14 +10,24 @@ In this chapter, you will learn: ## Rendering data from lists -Thinking back to our analysis of the `r/reddit` page, we notice a list of data that needs to be rendered: the list of posts. This list of posts is always changing, so we cannot just hardcode the lists into our app like: +If we wanted to build the Reddit app, then we need to implement a list of data that needs to be rendered: the list of posts. This list of posts is always changing, so we cannot just hardcode the lists into our app directly, like so: ```rust +// we shouldn't ship our app with posts that don't update! rsx!( div { - Post {/* some properties */} - Post {/* some properties */} - Post {/* some properties */} + Post { + title: "Post A", + votes: 120, + } + Post { + title: "Post B", + votes: 14, + } + Post { + title: "Post C", + votes: 999, + } } ) ``` @@ -32,7 +42,7 @@ As a simple example, let's render a list of names. First, start with our input d let names = ["jim", "bob", "jane", "doe"]; ``` -Then, we create a new iterator by calling `iter` and then `map`. In our `map` function, we'll place render our template. +Then, we create a new iterator by calling `iter` and then [`map`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.map). In our `map` function, we'll render our template. ```rust let name_list = names.iter().map(|name| rsx!( @@ -40,16 +50,28 @@ let name_list = names.iter().map(|name| rsx!( )); ``` -Finally, we can include this list in the final structure: +We can include this list in the final Element: ```rust rsx!( ul { - {name_list} + name_list } ) ``` -The HTML-rendered version of this list would follow what you would expect: + +Rather than storing `name_list` in a temporary variable, we could also include the iterator inline: +```rust +rsx!( + ul { + names.iter().map(|name| rsx!( + li { "{name}" } + )) + } +) +``` + +The rendered HTML list is what you would expect: ```html
  • jim
  • @@ -59,54 +81,13 @@ The HTML-rendered version of this list would follow what you would expect:
``` -### Rendering our posts with a PostList component - -Let's start by modeling this problem with a component and some properties. - -For this example, we're going to use the borrowed component syntax since we probably have a large list of posts that we don't want to clone every time we render the Post List. - -```rust -#[derive(Props, PartialEq)] -struct PostListProps<'a> { - posts: &'a [PostData] -} -``` -Next, we're going to define our component: - -```rust -fn App(cx: Scope) -> Element { - // First, we create a new iterator by mapping the post array - let posts = cx.props.posts.iter().map(|post| rsx!{ - Post { - title: post.title, - age: post.age, - original_poster: post.original_poster - } - }); - - // Finally, we render the post list inside of a container - cx.render(rsx!{ - ul { class: "post-list" - {posts} - } - }) -} -``` - - ## Filtering Iterators Rust's iterators are extremely powerful, especially when used for filtering tasks. When building user interfaces, you might want to display a list of items filtered by some arbitrary check. -As a very simple example, let's set up a filter where we only list names that begin with the letter "J". +As a very simple example, let's set up a filter where we only list names that begin with the letter "j". -Let's make our list of names: - -```rust -let names = ["jim", "bob", "jane", "doe"]; -``` - -Then, we create a new iterator by calling `iter`, then `filter`, then `map`. In our `filter` function, we'll only allow "j" names, and in our `map` function, we'll render our template. +Using the list from above, let's create a new iterator. Before we render the list with `map` as in the previous example, we'll [`filter`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.filter) the names to only allow those that start with "j". ```rust let name_list = names @@ -115,53 +96,43 @@ let name_list = names .map(|name| rsx!( li { "{name}" })); ``` -Rust's iterators provide us tons of functionality and are significantly easier to work with than JavaScript's map/filter/reduce. +Rust's Iterators are very versatile – check out [their documentation](https://doc.rust-lang.org/std/iter/trait.Iterator.html) for more things you can do with them! -For keen Rustaceans: notice how we don't actually call `collect` on the name list. If we `collected` our filtered list into new Vec, then we would need to make an allocation to store these new elements. Instead, we create an entirely new _lazy_ iterator which will then be consumed by Dioxus in the `render` call. +For keen Rustaceans: notice how we don't actually call `collect` on the name list. If we `collect`ed our filtered list into new Vec, we would need to make an allocation to store these new elements, which slows down rendering. Instead, we create an entirely new _lazy_ iterator which Dioxus will consume in the `render` call. The `render` method is extraordinarily efficient, so it's best practice to let it do most of the allocations for us. -The `render` method is extraordinarily efficient, so it's best practice to let it do most of the allocations for us. +## Keeping list items in order with `key` -## Keeping list items in order with key +The examples above demonstrate the power of iterators in `rsx!` but all share the same issue: if your array items move (e.g. due to sorting), get inserted, or get deleted, Dioxus has no way of knowing what happened. This can cause Elements to be unnecessarily removed, changed and rebuilt when all that was needed was to change their position – this is inneficient. - -The examples above demonstrate the power of iterators in `rsx!` but all share the same issue: a lack of "keys". Whenever you render a list of elements, each item in the list must be **uniquely identifiable**. To make each item unique, you need to give it a "key". - -In Dioxus, keys are strings that uniquely identifies it among other items in that array: +To solve this problem, each item in the list must be **uniquely identifiable**. You can achieve this by giving it a unique, fixed "key". In Dioxus, a key is a string that identifies an item among others in the list. ```rust rsx!( li { key: "a" } ) ``` -Keys tell Dioxus which array item each component corresponds to, so that it can match them up later. This becomes important if your array items can move (e.g. due to sorting), get inserted, or get deleted. A well-chosen key helps Dioxus infer what exactly has happened, and make the correct updates to the screen - +Now, if an item has already been rendered once, Dioxus can use the key to match it up later to make the correct updates – and avoid unnecessary work. NB: the language from this section is strongly borrowed from [React's guide on keys](https://reactjs.org/docs/lists-and-keys.html). + ### Where to get your key Different sources of data provide different sources of keys: - _Data from a database_: If your data is coming from a database, you can use the database keys/IDs, which are unique by nature. -- _Locally generated data_: If your data is generated and persisted locally (e.g. notes in a note-taking app), use an incrementing counter or a package like `uuid` when creating items. +- _Locally generated data_: If your data is generated and persisted locally (e.g. notes in a note-taking app), keep track of keys along with your data. You can use an incrementing counter or a package like `uuid` to generate keys for new items – but make sure they stay the same for the item's lifetime. + +Remember: keys let Dioxus uniquely identify an item among its siblings. A well-chosen key provides more information than the position within the array. Even if the position changes due to reordering, the key lets Dioxus identify the item throughout its lifetime. ### Rules of keys - Keys must be unique among siblings. However, it’s okay to use the same keys for Elements in different arrays. -- Keys must not change or that defeats their purpose! Don’t generate them while rendering. +- An item's key must not change – **don’t generate them on the fly** while rendering. Otherwise, Dioxus will be unable to keep track of which item is which, and we're back to square one. -### Why does Dioxus need keys? +You might be tempted to use an item's index in the array as its key. In fact, 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. In all other cases, do not use the index for the key – it will lead to the performance problems described above. -Imagine that files on your desktop didn’t have names. Instead, you’d refer to them by their order — the first file, the second file, and so on. You could get used to it, but once you delete a file, it would get confusing. The second file would become the first file, the third file would be the second file, and so on. - -File names in a folder and Element keys in an array serve a similar purpose. They let us uniquely identify an item between its siblings. A well-chosen key provides more information than the position within the array. Even if the position changes due to reordering, the key lets Dioxus identify the item throughout its lifetime. - -### Gotcha -You might be tempted to use an item’s index in the array as its key. In fact, that’s what Dioxus will use if you don’t specify a key at all. But the order in which you render items will change over time if an item is inserted, deleted, or if the array gets reordered. Index as a key often leads to subtle and confusing bugs. - -Similarly, do not generate keys on the fly, `gen_random`. This will cause keys to never match up between renders, leading to all your components and DOM being recreated every time. Not only is this slow, but it will also lose any user input inside the list items. Instead, use a stable ID based on the data. - -Note that your components won’t receive 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: +Note that if you pass the key to a [custom component](../components/index.md) 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: ```rust -Post { key: "{key}", id: "{id}" } +Post { key: "{key}", id: "{key}" } ``` ## Moving on @@ -171,4 +142,4 @@ In this section, we learned: - How to use iterator tools to filter and transform data - How to use keys to render lists efficiently -Moving forward, we'll finally cover user input and interactivity. +Moving forward, we'll learn more about attributes. diff --git a/docs/guide/src/elements/propsmacro.md b/docs/guide/src/elements/propsmacro.md deleted file mode 100644 index 7426a73bf..000000000 --- a/docs/guide/src/elements/propsmacro.md +++ /dev/null @@ -1 +0,0 @@ -# The Props Macro diff --git a/docs/guide/src/elements/special_attributes.md b/docs/guide/src/elements/special_attributes.md new file mode 100644 index 000000000..a09ce0bf7 --- /dev/null +++ b/docs/guide/src/elements/special_attributes.md @@ -0,0 +1,192 @@ +# Special Attributes + +Dioxus tries its hardest to stay close to React, but there are some divergences and "special behavior" that you should review before moving on. + +In this section, we'll cover special attributes built into Dioxus: + +- `dangerous_inner_html` +- Boolean attributes +- `prevent_default` + +- event handlers as string attributes +- `value`, `checked`, and `selected` + +## The HTML escape hatch: `dangerous_inner_html` + +One thing you might've missed from React is the ability to render raw HTML directly to the DOM. 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 +fn BlogPost(cx: Scope) -> Element { + let contents = include_str!("../post.html"); + cx.render(rsx!{ + div { + class: "markdown", + dangerous_inner_html: "{contents}", + } + }) +} +``` + +> 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) 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 or not 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: + +```rust +rsx!{ + div { + hidden: "false", + "hello" + } +} +``` +wouldn't actually render the `hidden` 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. + +## Stopping form input and navigation with `prevent_default` + +Currently, calling `prevent_default` on events in EventHandlers is not possible from Desktop/Mobile. Until this is supported, it's possible to prevent default using the `prevent_default` attribute. + +> Note: you cannot conditionally prevent default with this approach. This is a limitation until synchronous event handling is available across the Webview boundary + +To use `prevent_default`, simply attach the `prevent_default` attribute to a given element and set it to the name of the event handler you want to prevent default on. We can attach this attribute multiple times for multiple attributes. + +```rust +rsx!{ + input { + oninput: move |_| {}, + prevent_default: "oninput", + + onclick: move |_| {}, + prevent_default: "onclick", + } +} +``` + + +## Controlled inputs and `value`, `checked`, and `selected` + +In Dioxus, there is a distinction between controlled and uncontrolled inputs. Most inputs you'll use are controlled, meaning we both drive the `value` of the input and react to the `oninput`. + +Controlled components: +```rust +let value = use_state(&cx, || String::from("hello world")); + +rsx! { + input { + oninput: move |evt| value.set(evt.value.clone()), + value: "{value}", + } +} +``` + +With uncontrolled inputs, we won't actually drive the value from the component. This has its advantages when we don't want to re-render the component when the user inputs a value. We could either select the element directly - something Dioxus doesn't support across platforms - or we could handle `oninput` and modify a value without causing an update: + +```rust +let value = use_ref(&cx, || String::from("hello world")); + +rsx! { + input { + oninput: move |evt| *value.write_silent() = evt.value.clone(), + // no "value" is driven here – the input keeps track of its own value, and you can't change it + } +} +``` + +## Strings for handlers like `onclick` + +For element fields that take a handler like `onclick` or `oninput`, Dioxus will let you attach a closure. Alternatively, you can also pass a string using normal attribute syntax and assign this attribute on the DOM. + +This lets you use JavaScript (only if your renderer can execute JavaScript). + +```rust +rsx!{ + div { + // handle oninput with rust + oninput: move |_| {}, + + // or handle oninput with javascript + oninput: "alert('hello world')", + } +} + +``` + +## Wrapping up + +In this chapter, we learned: +- How to declare elements +- How to conditionally render parts of your UI +- How to render lists +- Which attributes are "special" + + diff --git a/docs/guide/src/elements/vnodes.md b/docs/guide/src/elements/vnodes.md index d441693d7..4adbf962d 100644 --- a/docs/guide/src/elements/vnodes.md +++ b/docs/guide/src/elements/vnodes.md @@ -56,7 +56,7 @@ With the default configuration, any Element defined within the `dioxus-html` cra ## Text Elements -Dioxus also supports a special type of Element: Text. Text Elements do not accept children, but rather just string literals denoted with double quotes. +Dioxus also supports a special type of Element: Text. Text Elements do not accept children, just a string literal denoted by double quotes. ```rust rsx! ( @@ -74,20 +74,20 @@ rsx! ( ) ``` -Text can also be formatted with any value that implements `Display`. We use [f-string formatting](https://docs.rs/fstrings/0.2.3/fstrings/) - a "coming soon" feature for stable Rust that is familiar for Python and JavaScript users: +Text can also be formatted with any value that implements `Display`. We use the same syntax as Rust [format strings](https://www.rustnote.com/blog/format_strings.html) – which will already be familiar for Python and JavaScript users: ```rust let name = "Bob"; rsx! ( "hello {name}" ) ``` -Unfortunately, you cannot drop in arbitrary expressions directly into the string literal. In the cases where we need to compute a complex value, we'll want to use `format_args!` directly. Due to specifics of how the `rsx!` macro (we'll cover later), our call to `format_args` must be contained within curly braces *and* square braces. +Unfortunately, you cannot drop in arbitrary expressions directly into the string literal. In the cases where we need to compute a complex value, we'll want to use `format_args!` directly. Due to specifics of the `rsx!` macro (which we'll cover later), our call to `format_args` must be contained within square braces. ```rust -rsx!( {[format_args!("Hello {}", if enabled { "Jack" } else { "Bob" } )]} ) +rsx!( [format_args!("Hello {}", if enabled { "Jack" } else { "Bob" } )] ) ``` -Alternatively, `&str` can be included directly, though it must be inside of an array: +Alternatively, `&str` can be included directly, though it must also be inside square braces: ```rust rsx!( "Hello ", [if enabled { "Jack" } else { "Bob" }] ) @@ -104,7 +104,7 @@ rsx! ( "hello {name}" ) ## Attributes -Every Element in your User Interface will have some sort of properties that the renderer will use when drawing to the screen. These might inform the renderer if the component should be hidden, what its background color should be, or to give it a specific name or ID. +Every Element in your user interface will have some sort of properties that the renderer will use when drawing to the screen. These might inform the renderer if the component should be hidden, what its background color should be, or to give it a specific name or ID. To do this, we use the familiar struct-style syntax that Rust provides: @@ -123,7 +123,7 @@ Each field is defined as a method on the element in the `dioxus-html` crate. Thi 1) file an issue if the attribute _should_ be enabled 2) add a custom attribute on-the-fly -To use custom attributes, simply put the attribute name in quotes followed by a colon: +To use custom attributes, simply put the attribute name in quotes: ```rust rsx!( @@ -170,4 +170,4 @@ We learned: - Elements can either be a named container or text - Some Elements have properties that the renderer can use to draw the UI to the screen -Next, we'll compose Elements together to form components. +Next, we'll compose Elements together using Rust-based logic. diff --git a/docs/guide/src/hello_world.md b/docs/guide/src/hello_world.md index e1d4777d9..6bcc77e30 100644 --- a/docs/guide/src/hello_world.md +++ b/docs/guide/src/hello_world.md @@ -63,7 +63,7 @@ $ cat Cargo.toml [package] name = "hello-dioxus" version = "0.1.0" -edition = "2018" +edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html @@ -81,6 +81,13 @@ $ cargo add dioxus --features desktop It's very important to add `dioxus` with the `desktop` feature for this example. The `dioxus` crate is a batteries-include crate that combines a bunch of utility crates together, ensuring compatibility of the most important parts of the ecosystem. Under the hood, the `dioxus` crate configures various renderers, hooks, debug tooling, and more. The `desktop` feature ensures the we only depend on the smallest set of required crates to compile and render. +If you system does not provide the `libappindicator3` library, like Debian/bullseye, you can enable the replacement `ayatana` with an additional flag: + +```shell +$ # On Debian/bullseye use: +$ cargo add dioxus --features desktop --features ayatana +``` + 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. ### Our first app @@ -92,10 +99,10 @@ use dioxus::prelude::*; fn main() { - dioxus::desktop::launch(App); + dioxus::desktop::launch(app); } -fn App(cx: Scope) -> Element { +fn app(cx: Scope) -> Element { cx.render(rsx! ( div { "Hello, world!" } )) @@ -118,14 +125,14 @@ This initialization code launches a Tokio runtime on a helper thread where your ```rust fn main() { - dioxus::desktop::launch(App); + dioxus::desktop::launch(app); } ``` Finally, our app. Every component in Dioxus is a function that takes in `Context` and `Props` and returns an `Element`. ```rust -fn App(cx: Scope) -> Element { +fn app(cx: Scope) -> Element { cx.render(rsx! { div { "Hello, world!" } }) @@ -143,5 +150,3 @@ For now, just know that `Scope` lets you store state with hooks and render eleme ## Moving on Congrats! You've built your first desktop application with Dioxus. Next, we're going to learn about the basics of building interactive user interfaces. - - diff --git a/docs/guide/src/images/oldnew.png b/docs/guide/src/images/oldnew.png new file mode 100644 index 000000000..5aca37e40 Binary files /dev/null and b/docs/guide/src/images/oldnew.png differ diff --git a/docs/guide/src/interactivity/event_handlers.md b/docs/guide/src/interactivity/event_handlers.md index ee4560b1e..8fcfe6edb 100644 --- a/docs/guide/src/interactivity/event_handlers.md +++ b/docs/guide/src/interactivity/event_handlers.md @@ -1 +1,3 @@ # Event handlers + +> This section is currently under construction! 🏗 diff --git a/docs/guide/src/interactivity/hooks.md b/docs/guide/src/interactivity/hooks.md index adf43c6ef..a84a0b129 100644 --- a/docs/guide/src/interactivity/hooks.md +++ b/docs/guide/src/interactivity/hooks.md @@ -76,6 +76,78 @@ This is why hooks called out of order will fail - if we try to downcast a `Hook< This pattern might seem strange at first, but it can be a significant upgrade over structs as blobs of state, which tend to be difficult to use in [Rust given the ownership system](https://rust-lang.github.io/rfcs/2229-capture-disjoint-fields.html). + +## Rules of hooks + +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 + +Examples of "no-nos" include: + +### ❌ Nested uses + +```rust +// ❌ don't call use_hook or any `use_` function *inside* use_hook! +cx.use_hook(|_| { + let name = cx.use_hook(|_| "ads"); +}) + +// ✅ instead, move the first hook above +let name = cx.use_hook(|_| "ads"); +cx.use_hook(|_| { + // do something with name here +}) +``` + +### ❌ Uses in conditionals +```rust +// ❌ don't call use_ in conditionals! +if do_thing { + let name = use_state(&cx, || 0); +} + +// ✅ instead, *always* call use_state but leave your logic +let name = use_state(&cx, || 0); +if do_thing { + // do thing with name here +} +``` + +### ❌ Uses in loops + + +```rust +// ❌ Do not use hooks in loops! +let mut nodes = vec![]; + +for name in names { + let age = use_state(&cx, |_| 0); + nodes.push(cx.render(rsx!{ + div { "{age}" } + })) +} + +// ✅ Instead, consider refactoring your usecase into components +#[inline_props] +fn Child(cx: Scope, name: String) -> Element { + let age = use_state(&cx, |_| 0); + cx.render(rsx!{ div { "{age}" } }) +} + +// ✅ Or, use a hashmap with use_ref +```rust +let ages = use_ref(&cx, || HashMap::new()); + +names.iter().map(|name| { + let age = ages.get(name).unwrap(); + cx.render(rsx!{ div { "{age}" } }) +}) +``` + ## Building new Hooks However, most hooks you'll interact with *don't* return an `&mut T` since this is not very useful in a real-world situation. @@ -168,23 +240,15 @@ fn example(cx: Scope) -> Element { ``` + ## Hooks provided by the `Dioxus-Hooks` package By default, we bundle a handful of hooks in the Dioxus-Hooks package. Feel free to click on each hook to view its definition and associated documentation. -- [use_state](https://docs.rs/dioxus_hooks/use_state) - store state with ergonomic updates -- [use_ref](https://docs.rs/dioxus_hooks/use_ref) - store non-clone state with a refcell -- [use_future](https://docs.rs/dioxus_hooks/use_future) - store a future to be polled after initialization -- [use_coroutine](https://docs.rs/dioxus_hooks/use_coroutine) - store a future that can be stopped/started/communicated with -- [use_noderef](https://docs.rs/dioxus_hooks/use_noderef) - store a handle to the native element -- [use_callback](https://docs.rs/dioxus_hooks/use_callback) - store a callback that implements PartialEq for memoization -- [use_provide_context](https://docs.rs/dioxus_hooks/use_provide_context) - expose state to descendent components -- [use_context](https://docs.rs/dioxus_hooks/use_context) - consume state provided by `use_provide_context` - -For a more in-depth guide to building new hooks, checkout out the advanced hook building guide in the reference. - -## Wrapping up - -In this chapter, we learned about the mechanics and intricacies of storing state inside a component. - -In the next chapter, we'll cover event listeners in similar depth, and how to combine the two to build interactive components. +- [use_state](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_state.html) - store state with ergonomic updates +- [use_ref](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_ref.html) - store non-clone state with a refcell +- [use_future](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_future.html) - store a future to be polled after initialization +- [use_coroutine](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_coroutine.html) - store a future that can be stopped/started/communicated with +- [use_context_provider](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_context_provider.html) - expose state to descendent components +- [use_context](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_context.html) - consume state provided by `use_provide_context` +- [use_suspense](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_suspense.html) diff --git a/docs/guide/src/interactivity/importanthooks.md b/docs/guide/src/interactivity/importanthooks.md new file mode 100644 index 000000000..161c5becf --- /dev/null +++ b/docs/guide/src/interactivity/importanthooks.md @@ -0,0 +1,127 @@ +# `use_state` and `use_ref` + +Most components you will write in Dioxus will need to store state somehow. For local state, we provide two very convenient hooks: + +- [use_state](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_state.html) +- [use_ref](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_ref.html) + +Both of these hooks are extremely powerful and flexible, so we've dedicated this section to understanding them properly. + +> These two hooks are not the only way to store state. You can always build your own hooks! + +## `use_state` + +The `use_state` hook is very similar to its React counterpart. When we use it, we get two values: + +- The value itself as an `&T` +- A handle to set the value `&UseState` + +```rust +let (count, set_count) = use_state(&cx, || 0); + +// then to set the count +set_count(count + 1) +``` + +However, the `set_count` object is more powerful than it looks. You can use it as a closure, but you can also call methods on it to do more powerful operations. + +For instance, we can get a handle to the current value at any time: + +```rust +let current: Rc = set_count.current(); +``` + +Or, we can get the inner handle to set the value + +```rust +let setter: Rc = set_count.setter(); +``` + +Or, we can set a new value using the current value as a reference: + +```rust +set_count.modify(|i| i + 1); +``` + +If the value is cheaply cloneable, then we can call `with_mut` to get a mutable reference to the value: + +```rust +set_count.with_mut(|i| *i += 1); +``` + +Alternatively, we can call `make_mut` which gives us a `RefMut` to the underlying value: + +```rust +*set_count.make_mut() += 1; +``` + +Plus, the `set_count` handle is cloneable into async contexts, so we can use it in futures. + +```rust +// count up infinitely +cx.spawn({ + to_owned![set_count]; + async move { + loop { + wait_ms(100).await; + set_count.modify(|i| i + 1); + } + } +}) +``` + +## `use_ref` + +You might've noticed a fundamental limitation to `use_state`: to modify the value in-place, it must be cheaply cloneable. But what if your type is not cheap to clone? + +In these cases, you should reach for `use_ref` which is essentially just a glorified `Rc>` (Rust [smart pointers](https://doc.rust-lang.org/book/ch15-04-rc.html)). + +This provides us some runtime locks around our data, trading reliability for performance. For most cases though, you will find it hard to make `use_ref` crash. + +> Note: this is *not* exactly like its React counterpart since calling `write` will cause a re-render. For more React parity, use the `write_silent` method. + +To use the hook: + +```rust +let names = use_ref(&cx, || vec!["susie", "calvin"]); +``` + +To read the hook values, use the `read()` method: + +```rust +cx.render(rsx!{ + ul { + names.read().iter().map(|name| { + rsx!{ "{name}" } + }) + } +}) +``` + +And then to write into the hook value, use the `write` method: + +```rust +names.write().push("Tiger"); +``` + +If you don't want to re-render the component when names is updated, then we can use the `write_silent` method: + +```rust +names.write_silent().push("Transmogrifier"); +``` + +Again, like `UseState`, the `UseRef` handle is clonable into async contexts: + + +```rust +// infinitely push calvin into the list +cx.spawn({ + to_owned![names]; + async move { + loop { + wait_ms(100).await; + names.write().push("Calvin"); + } + } +}) +``` diff --git a/docs/guide/src/interactivity/index.md b/docs/guide/src/interactivity/index.md index 0e1a61252..6075a4a5a 100644 --- a/docs/guide/src/interactivity/index.md +++ b/docs/guide/src/interactivity/index.md @@ -1,6 +1,6 @@ # Adding Interactivity -So far, we've learned how to describe the structure and properties of our user interfaces. Unfortunately, they're static and quite a bit uninteresting. In this chapter, we're going to learn how to add interactivity through events, state, and tasks. +So far, we've learned how to describe the structure and properties of our user interfaces. Unfortunately, they're static and quite uninteresting. In this chapter, we're going to learn how to add interactivity through events, state, and tasks. ## Primer on interactivity @@ -44,9 +44,9 @@ fn App(cx: Scope) -> Element { } ``` -State in Dioxus follows a pattern called "one-way-data-flow." As your components create new components as their children, your app's structure will eventually grow into a tree where state gets passed down from the root component into "leaves" of the tree. +State in Dioxus follows a pattern called "one-way data-flow." As your components create new components as their children, your app's structure will eventually grow into a tree where state gets passed down from the root component into "leaves" of the tree. -You've probably seen the tree of UI components represented using an directed-acyclic-graph: +You've probably seen the tree of UI components represented using a directed acyclic graph: ![image](../images/component_tree.png) @@ -64,7 +64,7 @@ The most common hook you'll use for storing state is `use_state`. `use_state` pr ```rust fn App(cx: Scope)-> Element { - let post = use_state(&cx, || { + let (post, set_post) = use_state(&cx, || { PostData { id: Uuid::new_v4(), score: 10, @@ -84,10 +84,10 @@ fn App(cx: Scope)-> Element { } ``` -Whenever we have a new post that we want to render, we can call `set` on `post` and provide a new value: +Whenever we have a new post that we want to render, we can call `set_post` and provide a new value: ```rust -post.set(PostData { +set_post(PostData { id: Uuid::new_v4(), score: 20, comment_count: 0, @@ -112,11 +112,11 @@ For example, let's say we provide a button to generate a new post. Whenever the ```rust fn App(cx: Scope)-> Element { - let post = use_state(&cx, || PostData::new()); + let (post, set_post) = use_state(&cx, || PostData::new()); cx.render(rsx!{ button { - on_click: move |_| post.set(PostData::random()) + on_click: move |_| set_post(PostData::random()) "Generate a random post" } Post { props: &post } @@ -128,7 +128,12 @@ We'll dive much deeper into event listeners later. ### Updating state asynchronously -We can also update our state outside of event listeners with `coroutines`. `Coroutines` are asynchronous blocks of our component that have the ability to cleanly interact with values, hooks, and other data in the component. Since coroutines stick around between renders, the data in them must be valid for the `'static` lifetime. We must explicitly declare which values our task will rely on to avoid the `stale props` problem common in React. +We can also update our state outside of event listeners with `futures` and `coroutines`. + +- `Futures` are Rust's version of promises that can execute asynchronous work by an efficient polling system. We can submit new futures to Dioxus either through `push_future` which returns a `TaskId` or with `spawn`. +- `Coroutines` are asynchronous blocks of our component that have the ability to cleanly interact with values, hooks, and other data in the component. + +Since coroutines and Futures stick around between renders, the data in them must be valid for the `'static` lifetime. We must explicitly declare which values our task will rely on to avoid the `stale props` problem common in React. We can use tasks in our components to build a tiny stopwatch that ticks every second. @@ -136,14 +141,14 @@ We can use tasks in our components to build a tiny stopwatch that ticks every se ```rust fn App(cx: Scope)-> Element { - let mut sec_elapsed = use_state(&cx, || 0); + let (elapsed, set_elapsed) = use_state(&cx, || 0); use_future(&cx, || { - let mut sec_elapsed = sec_elapsed.for_async(); + to_owned![set_elapsed]; // explicitly capture this hook for use in async async move { loop { TimeoutFuture::from_ms(1000).await; - sec_elapsed += 1; + set_elapsed.modify(|i| i + 1) } } }); @@ -152,12 +157,10 @@ fn App(cx: Scope)-> Element { } ``` -Using asynchronous code can be difficult! This is just scratching the surface of what's possible. We have an entire chapter on using async properly in your Dioxus Apps. +Using asynchronous code can be difficult! This is just scratching the surface of what's possible. We have an entire chapter on using async properly in your Dioxus Apps. We have an entire section dedicated to using `async` properly later in this book. ### How do I tell Dioxus that my state changed? -So far, we've only updated our state with `.set`. However, you might've noticed that we used `AddAssign` to increment the `sec_elapsed` value in our stopwatch example *without* calling set. This is because the `AddAssign` trait is implemented for `UseState` (the wrapper around our value returned from `use_state`). Under the hood, whenever you try to mutate our value through `UseState`, you're actually calling `.set` which informs Dioxus that _this_ component needs to be updated on the screen. - Whenever you inform Dioxus that the component needs to be updated, it will "render" your component again, storing the previous and current Elements in memory. Dioxus will automatically figure out the differences between the old and the new and generate a list of edits that the renderer needs to apply to change what's on the screen. This process is called "diffing": ![Diffing](../images/diffing.png) @@ -170,11 +173,37 @@ With these building blocks, we can craft new hooks similar to `use_state` that l In general, Dioxus should be plenty fast for most use cases. However, there are some rules you should consider following to ensure your apps are quick. -- 1) **Don't call set—state _while rendering_**. This will cause Dioxus to unnecessarily re-check the component for updates. +- 1) **Don't call set_state _while rendering_**. This will cause Dioxus to unnecessarily re-check the component for updates or enter an infinite loop. - 2) **Break your state apart into smaller sections.** Hooks are explicitly designed to "unshackle" your state from the typical model-view-controller paradigm, making it easy to reuse useful bits of code with a single function. - 3) **Move local state down**. Dioxus will need to re-check child components of your app if the root component is constantly being updated. You'll get best results if rapidly-changing state does not cause major re-renders. + + +## The `Scope` object + +Though very similar to React, Dioxus is different in a few ways. Most notably, React components will not have a `Scope` parameter in the component declaration. + +Have you ever wondered how the `useState()` call works in React without a `this` object to actually store the state? + +```javascript +// in React: +function Component(props) { + // This state persists between component renders, but where does it live? + let [state, set_state] = useState(10); +} +``` + +React uses global variables to store this information. However, global mutable variables must be carefully managed and are broadly discouraged in Rust programs. Because Dioxus needs to work with the rules of Rust it uses the `Scope` rather than a global state object to maintain some internal bookkeeping. + +That's what the `Scope` object is: a place for the Component to store state, manage listeners, and allocate elements. Advanced users of Dioxus will want to learn how to properly leverage the `Scope` object to build robust and performant extensions for Dioxus. + +```rust +fn Post(cx: Scope) -> Element { + cx.render(rsx!("hello")) +} +``` ## Moving On diff --git a/docs/guide/src/interactivity/lifecycles.md b/docs/guide/src/interactivity/lifecycles.md index 07a02f4ea..fdaa5b5e3 100644 --- a/docs/guide/src/interactivity/lifecycles.md +++ b/docs/guide/src/interactivity/lifecycles.md @@ -1 +1,3 @@ # Lifecycle, updates, and effects + +> This section is currently under construction! 🏗 diff --git a/docs/guide/src/interactivity/user_input.md b/docs/guide/src/interactivity/user_input.md index 2424e7f14..1e7ebbcbd 100644 --- a/docs/guide/src/interactivity/user_input.md +++ b/docs/guide/src/interactivity/user_input.md @@ -1 +1,6 @@ # User Input and Controlled Components + +Handling user input is one of the most common things your app will do, but it can be tricky + + +> This section is currently under construction! 🏗 diff --git a/docs/guide/src/setup.md b/docs/guide/src/setup.md index de634dc0a..1bbcec213 100644 --- a/docs/guide/src/setup.md +++ b/docs/guide/src/setup.md @@ -8,7 +8,7 @@ We'll learn about: - Suggested cargo extensions -For platform-specific guides, check out the [Platform Specific Guides](../platforms/00-index.md). +For platform-specific guides, check out the [Platform Specific Guides](/reference/platforms/index.md). # Setting up Dioxus @@ -19,7 +19,7 @@ Dioxus requires a few main things to get up and running: Dioxus integrates very well with the Rust-Analyzer IDE plugin which will provide appropriate syntax highlighting, code navigation, folding, and more. -### Installing Rust +## Installing Rust Head over to [https://rust-lang.org](http://rust-lang.org) and install the Rust compiler. @@ -29,24 +29,45 @@ Once installed, make sure to install wasm32-unknown-unknown as a target if you'r rustup target add wasm32-unknown-unknown ``` -### Platform-Specific Dependencies +## Platform-Specific Dependencies If you are running a modern, mainstream operating system, you should need no additional setup to build WebView-based Desktop apps. However, if you are running an older version of Windows or a flavor of Linux with no default web rendering engine, you might need to install some additional dependencies. -For windows users: download the [bootstrapper for Webview2 from Microsoft](https://developer.microsoft.com/en-us/microsoft-edge/webview2/) -For linux users, we need the development libraries for libgtk. +### Windows + +Windows Desktop apps depend on WebView2 - a library which 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* which will fetch an installer from Microsoft's CDN +2. A tiny *installer* which will fetch 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, it's very likely that your users will already have WebkitGtk. ``` sudo apt install libwebkit2gtk-4.0-dev libgtk-3-dev libappindicator3-dev ``` -When distributing onto older Windows platforms or less-mainstream +When using Debian/bullseye `libappindicator3-dev` is no longer available but replaced by `libayatana-appindicator3-dev`. + +``` +# on Debian/bullseye use: +sudo apt install libwebkit2gtk-4.0-dev libgtk-3-dev libayatanta-appindicator3-dev +``` + +If you run into issues, make sure you have all the basics installed, as outlined in the [Tauri docs](https://tauri.studio/en/docs/get-started/setup-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). -### Dioxus-CLI for dev server, bundling, etc. +## Dioxus-CLI for dev server, bundling, etc. We also recommend installing the Dioxus CLI. The Dioxus CLI automates building and packaging for various targets and integrates with simulators, development servers, and app deployment. To install the CLI, you'll need cargo (which should be automatically installed with Rust): @@ -62,7 +83,7 @@ $ cargo install --force dioxus-cli We provide this 1st-party tool to save you from having to run potentially untrusted code every time you add a crate to your project - as is standard in the NPM ecosystem. -### Suggested extensions +## Suggested extensions If you want to keep your traditional `npm install XXX` workflow for adding packages, you might want to install `cargo-edit` and a few other fun `cargo` extensions: diff --git a/docs/guide/src/state/errorhandling.md b/docs/guide/src/state/errorhandling.md index 40436521f..767a314b0 100644 --- a/docs/guide/src/state/errorhandling.md +++ b/docs/guide/src/state/errorhandling.md @@ -9,3 +9,4 @@ fn App((cx, props): Component) -> Element { } ``` +> This section is currently under construction! 🏗 diff --git a/docs/guide/src/state/index.md b/docs/guide/src/state/index.md index 1874dd73e..07584124c 100644 --- a/docs/guide/src/state/index.md +++ b/docs/guide/src/state/index.md @@ -4,5 +4,25 @@ Every app you'll build with Dioxus will have some sort of state that needs to be In this chapter, we'll cover the various ways to manage state, the appropriate terminology, various patterns, and then take an overview +## Terminology + + +> This section is currently under construction! 🏗 + + + + +## Important hook: `use_state` + + + + + +## Important hook: `use_ref` + + + + +## `provide_context` and `consume_context` ## Terminology diff --git a/docs/guide/src/state/liftingstate.md b/docs/guide/src/state/liftingstate.md index 3e906a0ca..fec62d2c7 100644 --- a/docs/guide/src/state/liftingstate.md +++ b/docs/guide/src/state/liftingstate.md @@ -1 +1,4 @@ # Lifting State + + +> This section is currently under construction! 🏗 diff --git a/docs/guide/src/state/localstate.md b/docs/guide/src/state/localstate.md index 29085ac45..e54c1e45f 100644 --- a/docs/guide/src/state/localstate.md +++ b/docs/guide/src/state/localstate.md @@ -1 +1,4 @@ # Local State + + +> This section is currently under construction! 🏗 diff --git a/docs/guide/src/state/sharedstate.md b/docs/guide/src/state/sharedstate.md index ec1ede1d1..148b6eb66 100644 --- a/docs/guide/src/state/sharedstate.md +++ b/docs/guide/src/state/sharedstate.md @@ -1 +1,7 @@ # Global State + + +cx.provide_context() +cx.consume_context() + +> This section is currently under construction! 🏗 diff --git a/docs/guide/src/tutorial/components.md b/docs/guide/src/tutorial/components.md index bfbb760b3..82bae6cd7 100644 --- a/docs/guide/src/tutorial/components.md +++ b/docs/guide/src/tutorial/components.md @@ -1 +1,3 @@ # Defining Components + +This section is currently under construction! 🏗 diff --git a/docs/guide/src/tutorial/state.md b/docs/guide/src/tutorial/state.md index 35df690d6..6026c7546 100644 --- a/docs/guide/src/tutorial/state.md +++ b/docs/guide/src/tutorial/state.md @@ -1 +1,3 @@ # Defining State + +This section is currently under construction! 🏗 diff --git a/docs/guide/src/tutorial/structure.md b/docs/guide/src/tutorial/structure.md index 1cbb47579..eaf8afe43 100644 --- a/docs/guide/src/tutorial/structure.md +++ b/docs/guide/src/tutorial/structure.md @@ -1 +1,4 @@ # Structuring our app + + +This section is currently under construction! 🏗 diff --git a/docs/guide/src/tutorial/styling.md b/docs/guide/src/tutorial/styling.md index 3e90761b5..b25db14d2 100644 --- a/docs/guide/src/tutorial/styling.md +++ b/docs/guide/src/tutorial/styling.md @@ -1 +1,4 @@ # Styling + + +This section is currently under construction! 🏗 diff --git a/docs/nightly/readme.md b/docs/nightly/readme.md new file mode 100644 index 000000000..99f706e81 --- /dev/null +++ b/docs/nightly/readme.md @@ -0,0 +1 @@ +this directory is for deploying into diff --git a/docs/reference/src/SUMMARY.md b/docs/reference/src/SUMMARY.md index 3feb9fe36..18f351bfa 100644 --- a/docs/reference/src/SUMMARY.md +++ b/docs/reference/src/SUMMARY.md @@ -2,11 +2,12 @@ - [Introduction](README.md) -- [Web](web/index.md) -- [Desktop](desktop/index.md) -- [Mobile](mobile/index.md) -- [SSR](ssr/index.md) -- [TUI](tui/index.md) +- [Platforms](platforms/index.md) + - [Web](platforms/web.md) + - [Server Side Rendering](platforms/ssr.md) + - [Desktop](platforms/desktop.md) + - [Mobile](platforms/mobile.md) + - [TUI](platforms/tui.md) - [Advanced Guides](guide/index.md) - [RSX in Depth](guide/rsx_in_depth.md) diff --git a/docs/reference/src/desktop/index.md b/docs/reference/src/platforms/desktop.md similarity index 98% rename from docs/reference/src/desktop/index.md rename to docs/reference/src/platforms/desktop.md index 8011f1eed..18393f132 100644 --- a/docs/reference/src/desktop/index.md +++ b/docs/reference/src/platforms/desktop.md @@ -1,4 +1,4 @@ -# Desktop +# Getting Started: Desktop One of Dioxus' killer features is the ability to quickly build a native desktop app that looks and feels the same across platforms. Apps built with Dioxus are typically <5mb in size and use existing system resources, so they won't hog extreme amounts of RAM or memory. diff --git a/docs/reference/src/platforms/index.md b/docs/reference/src/platforms/index.md new file mode 100644 index 000000000..fbbabd35d --- /dev/null +++ b/docs/reference/src/platforms/index.md @@ -0,0 +1,10 @@ +# Platforms + +Dioxus supports many different platforms. Below are a list of guides that walk you through setting up Dioxus for a specific platform. + +### Setup Guides +- [Web](web.md) +- [Server Side Rendering](ssr.md) +- [Desktop](desktop.md) +- [Mobile](mobile.md) +- [TUI](tui.md) \ No newline at end of file diff --git a/docs/reference/src/mobile/index.md b/docs/reference/src/platforms/mobile.md similarity index 99% rename from docs/reference/src/mobile/index.md rename to docs/reference/src/platforms/mobile.md index 2e8344ed1..5a41ffe60 100644 --- a/docs/reference/src/mobile/index.md +++ b/docs/reference/src/platforms/mobile.md @@ -21,7 +21,7 @@ $ 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 moble init +$ cargo mobile init ``` We're going to completely clear out the `dependencies` it generates for us, swapping out `winit` with `dioxus-mobile`. diff --git a/docs/reference/src/ssr/index.md b/docs/reference/src/platforms/ssr.md similarity index 88% rename from docs/reference/src/ssr/index.md rename to docs/reference/src/platforms/ssr.md index aef223dfd..09e32ba43 100644 --- a/docs/reference/src/ssr/index.md +++ b/docs/reference/src/platforms/ssr.md @@ -2,11 +2,8 @@ The Dioxus VirtualDom can be rendered to a string by traversing the Element Tree. This is implemented in the `ssr` crate where your Dioxus app can be directly rendered to HTML to be served by a web server. - - ## Setup - If you just want to render `rsx!` or a VirtualDom to HTML, check out the API docs. It's pretty simple: ```rust @@ -19,8 +16,7 @@ println!("{}", dioxus::ssr::render_vdom(&vdom)); println!( "{}", dioxus::ssr::render_lazy(rsx! { h1 { "Hello, world!" } } ); ``` - -However, for this guide, we're going to show how to use Dioxus SSR with `Axum`. +However, for this guide, we're going to show how to use Dioxus SSR with `Axum`. Make sure you have Rust and Cargo installed, and then create a new project: @@ -29,15 +25,16 @@ $ cargo new --bin demo $ cd app ``` -Add Dioxus with the `desktop` feature: +Add Dioxus with the `ssr` feature: ```shell $ cargo add dioxus --features ssr ``` Next, add all the Axum dependencies. This will be different if you're using a different Web Framework + ``` -$ cargo add dioxus tokio --features full +$ cargo add tokio --features full $ cargo add axum ``` @@ -45,12 +42,11 @@ Your dependencies should look roughly like this: ```toml [dependencies] -axum = "0.4.3" +axum = "0.4.5" dioxus = { version = "*", features = ["ssr"] } tokio = { version = "1.15.0", features = ["full"] } ``` - Now, setup your Axum app to respond on an endpoint. ```rust @@ -63,7 +59,11 @@ async fn main() { println!("listening on http://{}", addr); axum::Server::bind(&addr) - .serve(Router::new().route("/", get(app_endpoint))) + .serve( + Router::new() + .route("/", get(app_endpoint)) + .into_make_service(), + ) .await .unwrap(); } @@ -88,14 +88,14 @@ async fn app_endpoint() -> Html { } let mut app = VirtualDom::new(app); let _ = app.rebuild(); - + Html(dioxus::ssr::render_vdom(&app)) } ``` And that's it! -> You might notice that you cannot hold the VirtualDom across an await point. Dioxus is currently not ThreadSafe, so it *must* remain on the thread it started. We are working on loosening this requirement. +> You might notice that you cannot hold the VirtualDom across an await point. Dioxus is currently not ThreadSafe, so it _must_ remain on the thread it started. We are working on loosening this requirement. ## Future Steps diff --git a/docs/reference/src/tui/index.md b/docs/reference/src/platforms/tui.md similarity index 98% rename from docs/reference/src/tui/index.md rename to docs/reference/src/platforms/tui.md index 3947883d4..e646bd4ba 100644 --- a/docs/reference/src/tui/index.md +++ b/docs/reference/src/platforms/tui.md @@ -1,4 +1,4 @@ -# TUI +# Getting Started: TUI TUI support is currently quite experimental. Even the project name will change. But, if you're willing to venture into the realm of the unknown, this guide will get you started. diff --git a/docs/reference/src/web/index.md b/docs/reference/src/platforms/web.md similarity index 98% rename from docs/reference/src/web/index.md rename to docs/reference/src/platforms/web.md index 062cba177..2ff5f621e 100644 --- a/docs/reference/src/web/index.md +++ b/docs/reference/src/platforms/web.md @@ -1,4 +1,4 @@ -# Getting Started: Dioxus for Web +# Getting Started: Web [*"Pack your things, we're going on an adventure!"*](https://trunkrs.dev) diff --git a/docs/router/.gitignore b/docs/router/.gitignore new file mode 100644 index 000000000..7585238ef --- /dev/null +++ b/docs/router/.gitignore @@ -0,0 +1 @@ +book diff --git a/docs/router/book.toml b/docs/router/book.toml new file mode 100644 index 000000000..216bc555e --- /dev/null +++ b/docs/router/book.toml @@ -0,0 +1,6 @@ +[book] +authors = ["Jonathan Kelley"] +language = "en" +multilingual = false +src = "src" +title = "Dioxus Router" diff --git a/docs/router/src/SUMMARY.md b/docs/router/src/SUMMARY.md new file mode 100644 index 000000000..7390c8289 --- /dev/null +++ b/docs/router/src/SUMMARY.md @@ -0,0 +1,3 @@ +# Summary + +- [Chapter 1](./chapter_1.md) diff --git a/docs/router/src/chapter_1.md b/docs/router/src/chapter_1.md new file mode 100644 index 000000000..d4a45381b --- /dev/null +++ b/docs/router/src/chapter_1.md @@ -0,0 +1,3 @@ +# Chapter 1 + +The Dioxus Router is very important!! diff --git a/examples/all_css.rs b/examples/all_css.rs new file mode 100644 index 000000000..baf6294a4 --- /dev/null +++ b/examples/all_css.rs @@ -0,0 +1,411 @@ +use dioxus::prelude::*; + +fn main() { + dioxus::desktop::launch(app); +} + +fn app(cx: Scope) -> Element { + cx.render(rsx! { + div { + align_content: "a", + align_items: "a", + align_self: "a", + alignment_adjust: "a", + alignment_baseline: "a", + all: "a", + alt: "a", + animation: "a", + animation_delay: "a", + animation_direction: "a", + animation_duration: "a", + animation_fill_mode: "a", + animation_iteration_count: "a", + animation_name: "a", + animation_play_state: "a", + animation_timing_function: "a", + azimuth: "a", + backface_visibility: "a", + background: "a", + background_attachment: "a", + background_clip: "a", + background_color: "a", + background_image: "a", + background_origin: "a", + background_position: "a", + background_repeat: "a", + background_size: "a", + background_blend_mode: "a", + baseline_shift: "a", + bleed: "a", + bookmark_label: "a", + bookmark_level: "a", + bookmark_state: "a", + border: "a", + border_color: "a", + border_style: "a", + border_width: "a", + border_bottom: "a", + border_bottom_color: "a", + border_bottom_style: "a", + border_bottom_width: "a", + border_left: "a", + border_left_color: "a", + border_left_style: "a", + border_left_width: "a", + border_right: "a", + border_right_color: "a", + border_right_style: "a", + border_right_width: "a", + border_top: "a", + border_top_color: "a", + border_top_style: "a", + border_top_width: "a", + border_collapse: "a", + border_image: "a", + border_image_outset: "a", + border_image_repeat: "a", + border_image_slice: "a", + border_image_source: "a", + border_image_width: "a", + border_radius: "a", + border_bottom_left_radius: "a", + border_bottom_right_radius: "a", + border_top_left_radius: "a", + border_top_right_radius: "a", + border_spacing: "a", + bottom: "a", + box_decoration_break: "a", + box_shadow: "a", + box_sizing: "a", + box_snap: "a", + break_after: "a", + break_before: "a", + break_inside: "a", + buffered_rendering: "a", + caption_side: "a", + clear: "a", + clear_side: "a", + clip: "a", + clip_path: "a", + clip_rule: "a", + color: "a", + color_adjust: "a", + color_correction: "a", + color_interpolation: "a", + color_interpolation_filters: "a", + color_profile: "a", + color_rendering: "a", + column_fill: "a", + column_gap: "a", + column_rule: "a", + column_rule_color: "a", + column_rule_style: "a", + column_rule_width: "a", + column_span: "a", + columns: "a", + column_count: "a", + column_width: "a", + contain: "a", + content: "a", + counter_increment: "a", + counter_reset: "a", + counter_set: "a", + cue: "a", + cue_after: "a", + cue_before: "a", + cursor: "a", + direction: "a", + display: "a", + display_inside: "a", + display_outside: "a", + display_extras: "a", + display_box: "a", + dominant_baseline: "a", + elevation: "a", + empty_cells: "a", + enable_background: "a", + fill: "a", + fill_opacity: "a", + fill_rule: "a", + filter: "a", + float: "a", + float_defer_column: "a", + float_defer_page: "a", + float_offset: "a", + float_wrap: "a", + flow_into: "a", + flow_from: "a", + flex: "a", + flex_basis: "a", + flex_grow: "a", + flex_shrink: "a", + flex_flow: "a", + flex_direction: "a", + flex_wrap: "a", + flood_color: "a", + flood_opacity: "a", + font: "a", + font_family: "a", + font_size: "a", + font_stretch: "a", + font_style: "a", + font_weight: "a", + font_feature_settings: "a", + font_kerning: "a", + font_language_override: "a", + font_size_adjust: "a", + font_synthesis: "a", + font_variant: "a", + font_variant_alternates: "a", + font_variant_caps: "a", + font_variant_east_asian: "a", + font_variant_ligatures: "a", + font_variant_numeric: "a", + font_variant_position: "a", + footnote_policy: "a", + glyph_orientation_horizontal: "a", + glyph_orientation_vertical: "a", + grid: "a", + grid_auto_flow: "a", + grid_auto_columns: "a", + grid_auto_rows: "a", + grid_template: "a", + grid_template_areas: "a", + grid_template_columns: "a", + grid_template_rows: "a", + grid_area: "a", + grid_column: "a", + grid_column_start: "a", + grid_column_end: "a", + grid_row: "a", + grid_row_start: "a", + grid_row_end: "a", + hanging_punctuation: "a", + height: "a", + hyphenate_character: "a", + hyphenate_limit_chars: "a", + hyphenate_limit_last: "a", + hyphenate_limit_lines: "a", + hyphenate_limit_zone: "a", + hyphens: "a", + icon: "a", + image_orientation: "a", + image_resolution: "a", + image_rendering: "a", + ime: "a", + ime_align: "a", + ime_mode: "a", + ime_offset: "a", + ime_width: "a", + initial_letters: "a", + inline_box_align: "a", + isolation: "a", + justify_content: "a", + justify_items: "a", + justify_self: "a", + kerning: "a", + left: "a", + letter_spacing: "a", + lighting_color: "a", + line_box_contain: "a", + line_break: "a", + line_grid: "a", + line_height: "a", + line_slack: "a", + line_snap: "a", + list_style: "a", + list_style_image: "a", + list_style_position: "a", + list_style_type: "a", + margin: "a", + margin_bottom: "a", + margin_left: "a", + margin_right: "a", + margin_top: "a", + marker: "a", + marker_end: "a", + marker_mid: "a", + marker_pattern: "a", + marker_segment: "a", + marker_start: "a", + marker_knockout_left: "a", + marker_knockout_right: "a", + marker_side: "a", + marks: "a", + marquee_direction: "a", + marquee_play_count: "a", + marquee_speed: "a", + marquee_style: "a", + mask: "a", + mask_image: "a", + mask_repeat: "a", + mask_position: "a", + mask_clip: "a", + mask_origin: "a", + mask_size: "a", + mask_box: "a", + mask_box_outset: "a", + mask_box_repeat: "a", + mask_box_slice: "a", + mask_box_source: "a", + mask_box_width: "a", + mask_type: "a", + max_height: "a", + max_lines: "a", + max_width: "a", + min_height: "a", + min_width: "a", + mix_blend_mode: "a", + nav_down: "a", + nav_index: "a", + nav_left: "a", + nav_right: "a", + nav_up: "a", + object_fit: "a", + object_position: "a", + offset_after: "a", + offset_before: "a", + offset_end: "a", + offset_start: "a", + opacity: "a", + order: "a", + orphans: "a", + outline: "a", + outline_color: "a", + outline_style: "a", + outline_width: "a", + outline_offset: "a", + overflow: "a", + overflow_x: "a", + overflow_y: "a", + overflow_style: "a", + overflow_wrap: "a", + padding: "a", + padding_bottom: "a", + padding_left: "a", + padding_right: "a", + padding_top: "a", + page: "a", + page_break_after: "a", + page_break_before: "a", + page_break_inside: "a", + paint_order: "a", + pause: "a", + pause_after: "a", + pause_before: "a", + perspective: "a", + perspective_origin: "a", + pitch: "a", + pitch_range: "a", + play_during: "a", + pointer_events: "a", + position: "a", + quotes: "a", + region_fragment: "a", + resize: "a", + rest: "a", + rest_after: "a", + rest_before: "a", + richness: "a", + right: "a", + ruby_align: "a", + ruby_merge: "a", + ruby_position: "a", + scroll_behavior: "a", + scroll_snap_coordinate: "a", + scroll_snap_destination: "a", + scroll_snap_points_x: "a", + scroll_snap_points_y: "a", + scroll_snap_type: "a", + shape_image_threshold: "a", + shape_inside: "a", + shape_margin: "a", + shape_outside: "a", + shape_padding: "a", + shape_rendering: "a", + size: "a", + speak: "a", + speak_as: "a", + speak_header: "a", + speak_numeral: "a", + speak_punctuation: "a", + speech_rate: "a", + stop_color: "a", + stop_opacity: "a", + stress: "a", + string_set: "a", + stroke: "a", + stroke_dasharray: "a", + stroke_dashoffset: "a", + stroke_linecap: "a", + stroke_linejoin: "a", + stroke_miterlimit: "a", + stroke_opacity: "a", + stroke_width: "a", + tab_size: "a", + table_layout: "a", + text_align: "a", + text_align_all: "a", + text_align_last: "a", + text_anchor: "a", + text_combine_upright: "a", + text_decoration: "a", + text_decoration_color: "a", + text_decoration_line: "a", + text_decoration_style: "a", + text_decoration_skip: "a", + text_emphasis: "a", + text_emphasis_color: "a", + text_emphasis_style: "a", + text_emphasis_position: "a", + text_emphasis_skip: "a", + text_height: "a", + text_indent: "a", + text_justify: "a", + text_orientation: "a", + text_overflow: "a", + text_rendering: "a", + text_shadow: "a", + text_size_adjust: "a", + text_space_collapse: "a", + text_spacing: "a", + text_transform: "a", + text_underline_position: "a", + text_wrap: "a", + top: "a", + touch_action: "a", + transform: "a", + transform_box: "a", + transform_origin: "a", + transform_style: "a", + transition: "a", + transition_delay: "a", + transition_duration: "a", + transition_property: "a", + unicode_bidi: "a", + vector_effect: "a", + vertical_align: "a", + visibility: "a", + voice_balance: "a", + voice_duration: "a", + voice_family: "a", + voice_pitch: "a", + voice_range: "a", + voice_rate: "a", + voice_stress: "a", + voice_volumn: "a", + volume: "a", + white_space: "a", + widows: "a", + width: "a", + will_change: "a", + word_break: "a", + word_spacing: "a", + word_wrap: "a", + wrap_flow: "a", + wrap_through: "a", + writing_mode: "a", + z_index: "a", + } + }) +} diff --git a/examples/borderless.rs b/examples/borderless.rs deleted file mode 100644 index d52e9fb5a..000000000 --- a/examples/borderless.rs +++ /dev/null @@ -1,38 +0,0 @@ -use dioxus::prelude::*; - -fn main() { - dioxus::desktop::launch_cfg(app, |cfg| { - cfg.with_window(|w| w.with_title("BorderLess Demo").with_decorations(false)) - }); -} - -fn app(cx: Scope) -> Element { - let window = dioxus::desktop::use_window(&cx); - - cx.render(rsx!( - link { href:"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css", rel:"stylesheet" } - header { - class: "text-gray-400 bg-gray-900 body-font", - onmousedown: move |_| window.drag(), - div { - class: "container mx-auto flex flex-wrap p-5 flex-col md:flex-row items-center", - a { class: "flex title-font font-medium items-center text-white mb-4 md:mb-0", - span { class: "ml-3 text-xl", "Dioxus"} - } - nav { class: "md:ml-auto flex flex-wrap items-center text-base justify-center" } - button { - class: "inline-flex items-center bg-gray-800 border-0 py-1 px-3 focus:outline-none hover:bg-gray-700 rounded text-base mt-4 md:mt-0", - onmousedown: |evt| evt.cancel_bubble(), - onclick: move |_| window.minimize(true), - "Minimize" - } - button { - class: "inline-flex items-center bg-gray-800 border-0 py-1 px-3 focus:outline-none hover:bg-gray-700 rounded text-base mt-4 md:mt-0", - onmousedown: |evt| evt.cancel_bubble(), - onclick: move |_| window.close(), - "Close" - } - } - } - )) -} diff --git a/examples/dog_app.rs b/examples/dog_app.rs index a30f3e5e8..ad983035e 100644 --- a/examples/dog_app.rs +++ b/examples/dog_app.rs @@ -16,7 +16,9 @@ struct ListBreeds { } fn app(cx: Scope) -> Element { - let breeds = use_future(&cx, || async move { + let (breed, set_breed) = use_state(&cx, || None); + + let breeds = use_future(&cx, (), |_| async move { reqwest::get("https://dog.ceo/api/breeds/list/all") .await .unwrap() @@ -24,13 +26,10 @@ fn app(cx: Scope) -> Element { .await }); - let (breed, set_breed) = use_state(&cx, || None); - match breeds.value() { Some(Ok(breeds)) => cx.render(rsx! { div { - h1 {"Select a dog breed!"} - + h1 { "Select a dog breed!" } div { display: "flex", ul { flex: "50%", breeds.message.keys().map(|breed| rsx!( @@ -51,34 +50,23 @@ fn app(cx: Scope) -> Element { } } }), - Some(Err(_e)) => cx.render(rsx! { - div { "Error fetching breeds" } - }), - None => cx.render(rsx! { - div { "Loading dogs..." } - }), + Some(Err(_e)) => cx.render(rsx! { div { "Error fetching breeds" } }), + None => cx.render(rsx! { div { "Loading dogs..." } }), } } +#[derive(serde::Deserialize, Debug)] +struct DogApi { + message: String, +} + #[inline_props] fn Breed(cx: Scope, breed: String) -> Element { - #[derive(serde::Deserialize, Debug)] - struct DogApi { - message: String, - } - - let endpoint = format!("https://dog.ceo/api/breed/{}/images/random", breed); - - let fut = use_future(&cx, || async move { + let fut = use_future(&cx, (breed,), |(breed,)| async move { + let endpoint = format!("https://dog.ceo/api/breed/{}/images/random", breed); reqwest::get(endpoint).await.unwrap().json::().await }); - let (name, set_name) = use_state(&cx, || breed.clone()); - if name != breed { - set_name(breed.clone()); - fut.restart(); - } - cx.render(match fut.value() { Some(Ok(resp)) => rsx! { button { diff --git a/examples/fermi.rs b/examples/fermi.rs new file mode 100644 index 000000000..2be01d019 --- /dev/null +++ b/examples/fermi.rs @@ -0,0 +1,30 @@ +#![allow(non_snake_case)] + +use dioxus::prelude::*; +use fermi::prelude::*; + +fn main() { + dioxus::desktop::launch(app) +} + +static NAME: Atom = |_| "world".to_string(); + +fn app(cx: Scope) -> Element { + let name = use_read(&cx, NAME); + + cx.render(rsx! { + div { "hello {name}!" } + Child {} + }) +} + +fn Child(cx: Scope) -> Element { + let set_name = use_set(&cx, NAME); + + cx.render(rsx! { + button { + onclick: move |_| set_name("dioxus".to_string()), + "reset name" + } + }) +} diff --git a/examples/form.rs b/examples/form.rs new file mode 100644 index 000000000..5f0c992f5 --- /dev/null +++ b/examples/form.rs @@ -0,0 +1,26 @@ +//! Forms +//! +//! Dioxus forms deviate slightly from html, automatically returning all named inputs +//! in the "values" field + +use dioxus::prelude::*; + +fn main() { + dioxus::desktop::launch(app); +} + +fn app(cx: Scope) -> Element { + cx.render(rsx! { + div { + h1 { "Form" } + form { + onsubmit: move |ev| println!("Submitted {:?}", ev.values), + oninput: move |ev| println!("Input {:?}", ev.values), + input { r#type: "text", name: "username" } + input { r#type: "text", name: "full-name" } + input { r#type: "password", name: "password" } + button { "Submit the form" } + } + } + }) +} diff --git a/examples/heavy_compute.rs b/examples/heavy_compute.rs new file mode 100644 index 000000000..6e10a2f1f --- /dev/null +++ b/examples/heavy_compute.rs @@ -0,0 +1,28 @@ +//! This example shows that you can place heavy work on the main thread, and then +//! +//! You *should* be using `tokio::spawn_blocking` instead. +//! +//! Your app runs in an async runtime (Tokio), so you should avoid blocking +//! the rendering of the VirtualDom. +//! +//! + +use dioxus::prelude::*; + +fn main() { + dioxus::desktop::launch(app); +} + +fn app(cx: Scope) -> Element { + // This is discouraged + std::thread::sleep(std::time::Duration::from_millis(2_000)); + + // This is suggested + tokio::task::spawn_blocking(move || { + std::thread::sleep(std::time::Duration::from_millis(2_000)); + }); + + cx.render(rsx! { + div { "Hello, world!" } + }) +} diff --git a/examples/login_form.rs b/examples/login_form.rs new file mode 100644 index 000000000..0a0c77e87 --- /dev/null +++ b/examples/login_form.rs @@ -0,0 +1,50 @@ +//! This example demonstrates the following: +//! Futures in a callback, Router, and Forms + +use dioxus::events::*; +use dioxus::prelude::*; + +fn main() { + dioxus::desktop::launch(app); +} + +fn app(cx: Scope) -> Element { + let onsubmit = move |evt: FormEvent| { + cx.spawn(async move { + let resp = reqwest::Client::new() + .post("http://localhost:8080/login") + .form(&[ + ("username", &evt.values["username"]), + ("password", &evt.values["password"]), + ]) + .send() + .await; + + match resp { + // Parse data from here, such as storing a response token + Ok(_data) => println!("Login successful!"), + + //Handle any errors from the fetch here + Err(_err) => { + println!("Login failed - you need a login server running on localhost:8080.") + } + } + }); + }; + + cx.render(rsx! { + h1 { "Login" } + form { + onsubmit: onsubmit, + prevent_default: "onsubmit", // Prevent the default behavior of
to post + + input { "type": "text", id: "username", name: "username" } + label { "Username" } + br {} + input { "type": "password", id: "password", name: "password" } + label { "Password" } + br {} + button { "Login" } + } + }) +} diff --git a/examples/suspense.rs b/examples/suspense.rs index 5a9bf4fd8..ace5954f2 100644 --- a/examples/suspense.rs +++ b/examples/suspense.rs @@ -35,8 +35,8 @@ fn app(cx: Scope) -> Element { div { h1 {"Dogs are very important"} p { - "The dog or domestic dog (Canis familiaris[4][5] or Canis lupus familiaris[5])" - "is a domesticated descendant of the wolf which is characterized by an upturning tail." + "The dog or domestic dog (Canis familiaris[4][5] or Canis lupus familiaris[5])" + "is a domesticated descendant of the wolf which is characterized by an upturning tail." "The dog derived from an ancient, extinct wolf,[6][7] and the modern grey wolf is the" "dog's nearest living relative.[8] The dog was the first species to be domesticated,[9][8]" "by hunter–gatherers over 15,000 years ago,[7] before the development of agriculture.[1]" @@ -52,7 +52,7 @@ fn app(cx: Scope) -> Element { /// Suspense is achieved my moving the future into only the component that /// actually renders the data. fn Doggo(cx: Scope) -> Element { - let fut = use_future(&cx, || async move { + let fut = use_future(&cx, (), |_| async move { reqwest::get("https://dog.ceo/api/breeds/image/random/") .await .unwrap() diff --git a/examples/tasks.rs b/examples/tasks.rs index 3c4d4cba3..22b61eab8 100644 --- a/examples/tasks.rs +++ b/examples/tasks.rs @@ -12,8 +12,8 @@ fn main() { fn app(cx: Scope) -> Element { let (count, set_count) = use_state(&cx, || 0); - use_future(&cx, move || { - let set_count = set_count.to_owned(); + use_future(&cx, (), move |_| { + let set_count = set_count.clone(); async move { loop { tokio::time::sleep(Duration::from_millis(1000)).await; diff --git a/examples/textarea.rs b/examples/textarea.rs new file mode 100644 index 000000000..5988149ba --- /dev/null +++ b/examples/textarea.rs @@ -0,0 +1,23 @@ +// How to use textareas + +use dioxus::prelude::*; + +fn main() { + dioxus::desktop::launch(app); +} + +fn app(cx: Scope) -> Element { + let (model, set_model) = use_state(&cx, || String::from("asd")); + + println!("{}", model); + + cx.render(rsx! { + textarea { + class: "border", + rows: "10", + cols: "80", + value: "{model}", + oninput: move |e| set_model(e.value.clone()), + } + }) +} diff --git a/examples/todomvc.rs b/examples/todomvc.rs index 937d6992c..f0109eb4b 100644 --- a/examples/todomvc.rs +++ b/examples/todomvc.rs @@ -129,7 +129,6 @@ pub fn todo_entry<'a>(cx: Scope<'a, TodoEntryProps<'a>>) -> Element { label { r#for: "cbg-{todo.id}", onclick: move |_| set_is_editing(true), - onfocusout: move |_| set_is_editing(false), "{todo.contents}" } } @@ -139,6 +138,7 @@ pub fn todo_entry<'a>(cx: Scope<'a, TodoEntryProps<'a>>) -> Element { value: "{todo.contents}", oninput: move |evt| cx.props.set_todos.make_mut()[&cx.props.id].contents = evt.value.clone(), autofocus: "true", + onfocusout: move |_| set_is_editing(false), onkeydown: move |evt| { match evt.key.as_str() { "Enter" | "Escape" | "Tab" => set_is_editing(false), diff --git a/examples/window_event.rs b/examples/window_event.rs new file mode 100644 index 000000000..cb578829f --- /dev/null +++ b/examples/window_event.rs @@ -0,0 +1,97 @@ +use dioxus::prelude::*; + +fn main() { + dioxus::desktop::launch_cfg(app, |cfg| { + cfg.with_window(|w| w.with_title("BorderLess Demo").with_decorations(false)) + }); +} + +fn app(cx: Scope) -> Element { + let window = dioxus::desktop::use_window(&cx); + + // if you want to make window fullscreen, you need close the resizable. + // window.set_fullscreen(true); + // window.set_resizable(false); + + let (fullscreen, set_fullscreen) = use_state(&cx, || false); + let (always_on_top, set_always_on_top) = use_state(&cx, || false); + let (decorations, set_decorations) = use_state(&cx, || false); + + cx.render(rsx!( + link { href:"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css", rel:"stylesheet" } + header { + class: "text-gray-400 bg-gray-900 body-font", + onmousedown: move |_| window.drag(), + div { + class: "container mx-auto flex flex-wrap p-5 flex-col md:flex-row items-center", + a { class: "flex title-font font-medium items-center text-white mb-4 md:mb-0", + span { class: "ml-3 text-xl", "Dioxus"} + } + nav { class: "md:ml-auto flex flex-wrap items-center text-base justify-center" } + button { + class: "inline-flex items-center bg-gray-800 border-0 py-1 px-3 focus:outline-none hover:bg-gray-700 rounded text-base mt-4 md:mt-0", + onmousedown: |evt| evt.cancel_bubble(), + onclick: move |_| window.set_minimized(true), + "Minimize" + } + button { + class: "inline-flex items-center bg-gray-800 border-0 py-1 px-3 focus:outline-none hover:bg-gray-700 rounded text-base mt-4 md:mt-0", + onmousedown: |evt| evt.cancel_bubble(), + onclick: move |_| { + + window.set_fullscreen(!fullscreen); + window.set_resizable(*fullscreen); + + set_fullscreen(!fullscreen); + }, + "Fullscreen" + } + button { + class: "inline-flex items-center bg-gray-800 border-0 py-1 px-3 focus:outline-none hover:bg-gray-700 rounded text-base mt-4 md:mt-0", + onmousedown: |evt| evt.cancel_bubble(), + onclick: move |_| window.close(), + "Close" + } + } + } + br {} + div { + class: "container mx-auto", + div { + class: "grid grid-cols-5", + div { + button { + class: "inline-flex items-center text-white bg-green-500 border-0 py-1 px-3 hover:bg-green-700 rounded", + onmousedown: |evt| evt.cancel_bubble(), + onclick: move |_| { + window.set_always_on_top(!always_on_top); + set_always_on_top(!always_on_top); + }, + "Always On Top" + } + } + div { + button { + class: "inline-flex items-center text-white bg-blue-500 border-0 py-1 px-3 hover:bg-green-700 rounded", + onmousedown: |evt| evt.cancel_bubble(), + onclick: move |_| { + window.set_decorations(!decorations); + set_decorations(!decorations); + }, + "Set Decorations" + } + } + div { + button { + class: "inline-flex items-center text-white bg-blue-500 border-0 py-1 px-3 hover:bg-green-700 rounded", + onmousedown: |evt| evt.cancel_bubble(), + onclick: move |_| { + window.set_title("Dioxus Application"); + }, + "Change Title" + } + } + } + } + )) +} diff --git a/notes/README/ZH_CN.md b/notes/README/ZH_CN.md index 28bd07ed0..79f2b51aa 100644 --- a/notes/README/ZH_CN.md +++ b/notes/README/ZH_CN.md @@ -44,7 +44,7 @@

官网 | - 手册 + 手册 | 示例

@@ -65,12 +65,12 @@ Dioxus 是一个可移植、高性能的框架,用于在 Rust 中构建跨平 ```rust fn app(cx: Scope) -> Element { - let mut count = use_state(&cx, || 0); + let (count, set_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!" } + button { onclick: move |_| set_count(count + 1), "Up high!" } + button { onclick: move |_| set_count(count - 1), "Down low!" } )) } ``` @@ -160,6 +160,15 @@ Dioxus 使 Rust 应用程序的编写速度和 React 应用程序一样快,但 - 您希望应用运行在 `不支持 Wasm 或 asm.js` 的浏览器。 - 您需要一个 `Send + Sync` UI 解决方案(目前不支持)。 +### 项目生态 + +想要加入我们一起为 Dioxus 生态努力吗?有很多项目都能在您的帮助下获得改变: + +- [TUI 渲染器](https://github.com/dioxusLabs/rink) +- [CLI 开发工具](https://github.com/dioxusLabs/cli) +- [官网及文档](https://github.com/dioxusLabs/docsite) +- 动态网站 及 Web 服务器 +- 资源系统 ## 协议 diff --git a/packages/core-macro/Cargo.toml b/packages/core-macro/Cargo.toml index eb8210923..e6ff29a22 100644 --- a/packages/core-macro/Cargo.toml +++ b/packages/core-macro/Cargo.toml @@ -15,8 +15,8 @@ keywords = ["dom", "ui", "gui", "react", "wasm"] proc-macro = true [dependencies] -once_cell = "1.8" -proc-macro-error = "1.0.4" +# dioxus-rsx = { path = "../rsx" } +proc-macro-error = "1" proc-macro2 = { version = "1.0.6" } quote = "1.0" syn = { version = "1.0.11", features = ["full", "extra-traits"] } diff --git a/packages/core-macro/examples/html_test.rs b/packages/core-macro/examples/html_test.rs deleted file mode 100644 index c8e33ef8b..000000000 --- a/packages/core-macro/examples/html_test.rs +++ /dev/null @@ -1,8 +0,0 @@ -fn main() { - // use dioxus_core_macro::*; - // let r = html! { - //
- // "hello world" - //
- // }; -} diff --git a/packages/core-macro/examples/inline_props.rs b/packages/core-macro/examples/inline_props.rs deleted file mode 100644 index 28602ac30..000000000 --- a/packages/core-macro/examples/inline_props.rs +++ /dev/null @@ -1,22 +0,0 @@ -use dioxus_core_macro::{inline_props, Props}; - -fn main() {} - -type Element<'a> = (); - -pub struct Scope<'a, T = ()> { - props: &'a T, -} - -// #[inline_props] -pub fn component<'a>( - cx: Scope<'a>, - chkk: String, - chkk2: String, - r: u32, - cat: &'a str, - drd: String, - e: String, -) -> Element<'a> { - let r = chkk.len(); -} diff --git a/packages/core-macro/examples/prop_test.rs b/packages/core-macro/examples/prop_test.rs deleted file mode 100644 index 525b3c8b0..000000000 --- a/packages/core-macro/examples/prop_test.rs +++ /dev/null @@ -1,24 +0,0 @@ -fn main() {} - -pub mod dioxus { - pub mod prelude { - pub trait Properties { - type Builder; - const IS_STATIC: bool; - fn builder() -> Self::Builder; - unsafe fn memoize(&self, other: &Self) -> bool; - } - } -} - -/// This implementation should require a "PartialEq" because it memoizes (no external references) -#[derive(PartialEq, dioxus_core_macro::Props)] -struct SomeProps { - a: String, -} - -/// This implementation does not require a "PartialEq" because it does not memoize -#[derive(dioxus_core_macro::Props)] -struct SomePropsTwo<'a> { - _a: &'a str, -} diff --git a/packages/core-macro/src/htm.rs b/packages/core-macro/src/htm.rs deleted file mode 100644 index ca53096f6..000000000 --- a/packages/core-macro/src/htm.rs +++ /dev/null @@ -1,443 +0,0 @@ -//! -//! TODO: -//! - [ ] Support for VComponents -//! - [ ] Support for inline format in text -//! - [ ] Support for expressions in attribute positions -//! - [ ] Support for iterators -//! - [ ] support for inline html! -//! -//! -//! -//! -//! -//! -//! - -use { - proc_macro2::TokenStream as TokenStream2, - quote::{quote, ToTokens, TokenStreamExt}, - syn::{ - ext::IdentExt, - parse::{Parse, ParseStream}, - token, Error, Expr, ExprClosure, Ident, LitStr, Result, Token, - }, -}; - -// ============================================== -// Parse any stream coming from the html! macro -// ============================================== -pub struct HtmlRender { - kind: NodeOrList, -} - -impl Parse for HtmlRender { - fn parse(input: ParseStream) -> Result { - if input.peek(LitStr) { - return input.parse::()?.parse::(); - } - - // let __cx: Ident = s.parse()?; - // s.parse::()?; - // if elements are in an array, return a bumpalo::collections::Vec rather than a Node. - let kind = if input.peek(token::Bracket) { - let nodes_toks; - syn::bracketed!(nodes_toks in input); - let mut nodes: Vec> = vec![nodes_toks.parse()?]; - while nodes_toks.peek(Token![,]) { - nodes_toks.parse::()?; - nodes.push(nodes_toks.parse()?); - } - NodeOrList::List(NodeList(nodes)) - } else { - NodeOrList::Node(input.parse()?) - }; - Ok(HtmlRender { kind }) - } -} - -impl ToTokens for HtmlRender { - fn to_tokens(&self, out_tokens: &mut TokenStream2) { - let new_toks = ToToksCtx::new(&self.kind).to_token_stream(); - - // create a lazy tree that accepts a bump allocator - let final_tokens = quote! { - dioxus::prelude::LazyNodes::new(move |__cx| { - let bump = __cx.bump(); - - #new_toks - }) - }; - - final_tokens.to_tokens(out_tokens); - } -} - -/// ============================================= -/// Parse any child as a node or list of nodes -/// ============================================= -/// - [ ] Allow iterators -/// -/// -enum NodeOrList { - Node(Node), - List(NodeList), -} - -impl ToTokens for ToToksCtx<&NodeOrList> { - fn to_tokens(&self, tokens: &mut TokenStream2) { - match self.inner { - NodeOrList::Node(node) => self.recurse(node).to_tokens(tokens), - NodeOrList::List(list) => self.recurse(list).to_tokens(tokens), - } - } -} - -struct NodeList(Vec>); - -impl ToTokens for ToToksCtx<&NodeList> { - fn to_tokens(&self, tokens: &mut TokenStream2) { - let nodes = self.inner.0.iter().map(|node| self.recurse(node)); - tokens.append_all(quote! { - dioxus::bumpalo::vec![in bump; - #(#nodes),* - ] - }); - } -} - -enum Node { - Element(Element), - Text(TextNode), -} - -impl ToTokens for ToToksCtx<&Node> { - fn to_tokens(&self, tokens: &mut TokenStream2) { - match &self.inner { - Node::Element(el) => self.recurse(el).to_tokens(tokens), - Node::Text(txt) => self.recurse(txt).to_tokens(tokens), - } - } -} - -impl Node { - fn _peek(s: ParseStream) -> bool { - (s.peek(Token![<]) && !s.peek2(Token![/])) || s.peek(token::Brace) || s.peek(LitStr) - } -} - -impl Parse for Node { - fn parse(s: ParseStream) -> Result { - Ok(if s.peek(Token![<]) { - Node::Element(s.parse()?) - } else { - Node::Text(s.parse()?) - }) - } -} - -/// ======================================= -/// Parse the VNode::Element type -/// ======================================= -/// - [ ] Allow VComponent -/// -/// -struct Element { - name: Ident, - attrs: Vec, - children: MaybeExpr>, -} - -impl ToTokens for ToToksCtx<&Element> { - fn to_tokens(&self, tokens: &mut TokenStream2) { - // let __cx = self.__cx; - let name = &self.inner.name; - // let name = &self.inner.name.to_string(); - tokens.append_all(quote! { - __cx.element(dioxus_elements::#name) - // dioxus::builder::ElementBuilder::new( #name) - }); - for attr in self.inner.attrs.iter() { - self.recurse(attr).to_tokens(tokens); - } - - // if is_valid_svg_tag(&name.to_string()) { - // tokens.append_all(quote! { - // .namespace(Some("http://www.w3.org/2000/svg")) - // }); - // } - - match &self.inner.children { - MaybeExpr::Expr(expr) => tokens.append_all(quote! { - .children(#expr) - }), - MaybeExpr::Literal(nodes) => { - let mut children = nodes.iter(); - if let Some(child) = children.next() { - let mut inner_toks = TokenStream2::new(); - self.recurse(child).to_tokens(&mut inner_toks); - for child in children { - quote!(,).to_tokens(&mut inner_toks); - self.recurse(child).to_tokens(&mut inner_toks); - } - tokens.append_all(quote! { - .children([#inner_toks]) - }); - } - } - } - tokens.append_all(quote! { - .finish() - }); - } -} - -impl Parse for Element { - fn parse(s: ParseStream) -> Result { - s.parse::()?; - let name = Ident::parse_any(s)?; - let mut attrs = vec![]; - let _children: Vec = vec![]; - - // keep looking for attributes - while !s.peek(Token![>]) { - // self-closing - if s.peek(Token![/]) { - s.parse::()?; - s.parse::]>()?; - return Ok(Self { - name, - attrs, - children: MaybeExpr::Literal(vec![]), - }); - } - attrs.push(s.parse()?); - } - s.parse::]>()?; - - // Contents of an element can either be a brace (in which case we just copy verbatim), or a - // sequence of nodes. - let children = if s.peek(token::Brace) { - // expr - let content; - syn::braced!(content in s); - MaybeExpr::Expr(content.parse()?) - } else { - // nodes - let mut children = vec![]; - while !(s.peek(Token![<]) && s.peek2(Token![/])) { - children.push(s.parse()?); - } - MaybeExpr::Literal(children) - }; - - // closing element - s.parse::()?; - s.parse::()?; - let close = Ident::parse_any(s)?; - if close != name { - return Err(Error::new_spanned( - close, - "closing element does not match opening", - )); - } - s.parse::]>()?; - - Ok(Self { - name, - attrs, - children, - }) - } -} - -/// ======================================= -/// Parse a VElement's Attributes -/// ======================================= -/// - [ ] Allow expressions as attribute -/// -/// -struct Attr { - name: Ident, - ty: AttrType, -} - -impl Parse for Attr { - fn parse(s: ParseStream) -> Result { - let mut name = Ident::parse_any(s)?; - let name_str = name.to_string(); - s.parse::()?; - - // Check if this is an event handler - // If so, parse into literal tokens - let ty = if name_str.starts_with("on") { - // remove the "on" bit - name = Ident::new(name_str.trim_start_matches("on"), name.span()); - let content; - syn::braced!(content in s); - // AttrType::Value(content.parse()?) - AttrType::Event(content.parse()?) - // AttrType::Event(content.parse()?) - } else { - let lit_str = if name_str == "style" && s.peek(token::Brace) { - // special-case to deal with literal styles. - let outer; - syn::braced!(outer in s); - // double brace for inline style. - // todo!("Style support not ready yet"); - - // if outer.peek(token::Brace) { - // let inner; - // syn::braced!(inner in outer); - // let styles: Styles = inner.parse()?; - // MaybeExpr::Literal(LitStr::new(&styles.to_string(), Span::call_site())) - // } else { - // just parse as an expression - MaybeExpr::Expr(outer.parse()?) - // } - } else { - s.parse()? - }; - AttrType::Value(lit_str) - }; - Ok(Attr { name, ty }) - } -} - -impl ToTokens for ToToksCtx<&Attr> { - fn to_tokens(&self, tokens: &mut TokenStream2) { - let name = self.inner.name.to_string(); - let _attr_stream = TokenStream2::new(); - match &self.inner.ty { - AttrType::Value(value) => { - let value = self.recurse(value); - if name == "xmlns" { - tokens.append_all(quote! { - .namespace(Some(#value)) - }); - } else { - tokens.append_all(quote! { - .attr(#name, format_args_f!(#value)) - }); - } - } - AttrType::Event(event) => { - tokens.append_all(quote! { - .on(#name, #event) - }); - } - } - } -} - -enum AttrType { - Value(MaybeExpr), - Event(ExprClosure), - // todo Bool(MaybeExpr) -} - -/// ======================================= -/// Parse just plain text -/// ======================================= -/// - [ ] Perform formatting automatically -/// -/// -struct TextNode(MaybeExpr); - -impl Parse for TextNode { - fn parse(s: ParseStream) -> Result { - Ok(Self(s.parse()?)) - } -} - -impl ToTokens for ToToksCtx<&TextNode> { - fn to_tokens(&self, tokens: &mut TokenStream2) { - let mut token_stream = TokenStream2::new(); - self.recurse(&self.inner.0).to_tokens(&mut token_stream); - tokens.append_all(quote! { - __cx.text(format_args_f!(#token_stream)) - }); - } -} - -#[allow(clippy::large_enum_variant)] -enum MaybeExpr { - Literal(T), - Expr(Expr), -} - -impl Parse for MaybeExpr { - fn parse(s: ParseStream) -> Result { - if s.peek(token::Brace) { - let content; - syn::braced!(content in s); - Ok(MaybeExpr::Expr(content.parse()?)) - } else { - Ok(MaybeExpr::Literal(s.parse()?)) - } - } -} - -impl<'a, T> ToTokens for ToToksCtx<&'a MaybeExpr> -where - T: 'a, - ToToksCtx<&'a T>: ToTokens, -{ - fn to_tokens(&self, tokens: &mut TokenStream2) { - match &self.inner { - MaybeExpr::Literal(v) => self.recurse(v).to_tokens(tokens), - MaybeExpr::Expr(expr) => expr.to_tokens(tokens), - } - } -} - -/// ToTokens context -struct ToToksCtx { - inner: T, -} - -impl<'a, T> ToToksCtx { - fn new(inner: T) -> Self { - ToToksCtx { inner } - } - - fn recurse(&self, inner: U) -> ToToksCtx { - ToToksCtx { inner } - } -} - -impl ToTokens for ToToksCtx<&LitStr> { - fn to_tokens(&self, tokens: &mut TokenStream2) { - self.inner.to_tokens(tokens) - } -} - -#[cfg(test)] -mod test { - fn parse(input: &str) -> super::Result { - syn::parse_str(input) - } - - #[test] - fn div() { - parse("bump,
").unwrap(); - } - - #[test] - fn nested() { - parse("bump,
\"text\"
").unwrap(); - } - - #[test] - fn complex() { - parse( - "bump, -
{contact_details}
- ", - ) - .unwrap(); - } -} diff --git a/packages/core-macro/src/lib.rs b/packages/core-macro/src/lib.rs index 7099311ce..931933386 100644 --- a/packages/core-macro/src/lib.rs +++ b/packages/core-macro/src/lib.rs @@ -2,11 +2,10 @@ use proc_macro::TokenStream; use quote::ToTokens; use syn::parse_macro_input; -pub(crate) mod ifmt; -pub(crate) mod inlineprops; -pub(crate) mod props; -pub(crate) mod router; -pub(crate) mod rsx; +mod ifmt; +mod inlineprops; +mod props; +mod rsx; #[proc_macro] pub fn format_args_f(input: TokenStream) -> TokenStream { @@ -186,36 +185,6 @@ pub fn rsx(s: TokenStream) -> TokenStream { } } -/// Derive macro used to mark an enum as Routable. -/// -/// This macro can only be used on enums. Every varient of the macro needs to be marked -/// with the `at` attribute to specify the URL of the route. It generates an implementation of -/// `yew_router::Routable` trait and `const`s for the routes passed which are used with `Route` -/// component. -/// -/// # Example -/// -/// ``` -/// # use yew_router::Routable; -/// #[derive(Debug, Clone, Copy, PartialEq, Routable)] -/// enum Routes { -/// #[at("/")] -/// Home, -/// #[at("/secure")] -/// Secure, -/// #[at("/profile/{id}")] -/// Profile(u32), -/// #[at("/404")] -/// NotFound, -/// } -/// ``` -#[proc_macro_derive(Routable, attributes(at, not_found))] -pub fn routable_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { - use router::{routable_derive_impl, Routable}; - let input = parse_macro_input!(input as Routable); - routable_derive_impl(input).into() -} - /// Derive props for a component within the component definition. /// /// This macro provides a simple transformation from `Scope<{}>` to `Scope

`, diff --git a/packages/core-macro/src/router.rs b/packages/core-macro/src/router.rs deleted file mode 100644 index 3edad75e3..000000000 --- a/packages/core-macro/src/router.rs +++ /dev/null @@ -1,214 +0,0 @@ -#![allow(dead_code)] - -use proc_macro2::TokenStream; -use quote::quote; -use syn::parse::{Parse, ParseStream}; -use syn::punctuated::Punctuated; -use syn::spanned::Spanned; -use syn::{Data, DeriveInput, Fields, Ident, LitStr, Variant}; - -const AT_ATTR_IDENT: &str = "at"; -const NOT_FOUND_ATTR_IDENT: &str = "not_found"; - -pub struct Routable { - ident: Ident, - ats: Vec, - variants: Punctuated, - not_found_route: Option, -} - -impl Parse for Routable { - fn parse(input: ParseStream) -> syn::Result { - let DeriveInput { ident, data, .. } = input.parse()?; - - let data = match data { - Data::Enum(data) => data, - Data::Struct(s) => { - return Err(syn::Error::new( - s.struct_token.span(), - "expected enum, found struct", - )) - } - Data::Union(u) => { - return Err(syn::Error::new( - u.union_token.span(), - "expected enum, found union", - )) - } - }; - - let (not_found_route, ats) = parse_variants_attributes(&data.variants)?; - - Ok(Self { - ident, - variants: data.variants, - ats, - not_found_route, - }) - } -} - -fn parse_variants_attributes( - variants: &Punctuated, -) -> syn::Result<(Option, Vec)> { - let mut not_founds = vec![]; - let mut ats: Vec = vec![]; - - let mut not_found_attrs = vec![]; - - for variant in variants.iter() { - if let Fields::Unnamed(ref field) = variant.fields { - return Err(syn::Error::new( - field.span(), - "only named fields are supported", - )); - } - - let attrs = &variant.attrs; - let at_attrs = attrs - .iter() - .filter(|attr| attr.path.is_ident(AT_ATTR_IDENT)) - .collect::>(); - - let attr = match at_attrs.len() { - 1 => *at_attrs.first().unwrap(), - 0 => { - return Err(syn::Error::new( - variant.span(), - format!( - "{} attribute must be present on every variant", - AT_ATTR_IDENT - ), - )) - } - _ => { - return Err(syn::Error::new_spanned( - quote! { #(#at_attrs)* }, - format!("only one {} attribute must be present", AT_ATTR_IDENT), - )) - } - }; - - let lit = attr.parse_args::()?; - ats.push(lit); - - for attr in attrs.iter() { - if attr.path.is_ident(NOT_FOUND_ATTR_IDENT) { - not_found_attrs.push(attr); - not_founds.push(variant.ident.clone()) - } - } - } - - if not_founds.len() > 1 { - return Err(syn::Error::new_spanned( - quote! { #(#not_found_attrs)* }, - format!("there can only be one {}", NOT_FOUND_ATTR_IDENT), - )); - } - - Ok((not_founds.into_iter().next(), ats)) -} - -impl Routable { - // fn build_from_path(&self) -> TokenStream { - // let from_path_matches = self.variants.iter().enumerate().map(|(i, variant)| { - // let ident = &variant.ident; - // let right = match &variant.fields { - // Fields::Unit => quote! { Self::#ident }, - // Fields::Named(field) => { - // let fields = field.named.iter().map(|it| { - // //named fields have idents - // it.ident.as_ref().unwrap() - // }); - // quote! { Self::#ident { #(#fields: params.get(stringify!(#fields))?.parse().ok()?,)* } } - // } - // Fields::Unnamed(_) => unreachable!(), // already checked - // }; - - // let left = self.ats.get(i).unwrap(); - // quote! { - // #left => ::std::option::Option::Some(#right) - // } - // }); - - // quote! { - // fn from_path(path: &str, params: &::std::collections::HashMap<&str, &str>) -> ::std::option::Option { - // match path { - // #(#from_path_matches),*, - // _ => ::std::option::Option::None, - // } - // } - // } - // } - - // fn build_to_path(&self) -> TokenStream { - // let to_path_matches = self.variants.iter().enumerate().map(|(i, variant)| { - // let ident = &variant.ident; - // let mut right = self.ats.get(i).unwrap().value(); - - // match &variant.fields { - // Fields::Unit => quote! { Self::#ident => ::std::string::ToString::to_string(#right) }, - // Fields::Named(field) => { - // let fields = field - // .named - // .iter() - // .map(|it| it.ident.as_ref().unwrap()) - // .collect::>(); - - // for field in fields.iter() { - // // :param -> {param} - // // so we can pass it to `format!("...", param)` - // right = right.replace(&format!(":{}", field), &format!("{{{}}}", field)) - // } - - // quote! { - // Self::#ident { #(#fields),* } => ::std::format!(#right, #(#fields = #fields),*) - // } - // } - // Fields::Unnamed(_) => unreachable!(), // already checked - // } - // }); - - // quote! { - // fn to_path(&self) -> ::std::string::String { - // match self { - // #(#to_path_matches),*, - // } - // } - // } - // } -} - -pub fn routable_derive_impl(input: Routable) -> TokenStream { - let Routable { - // ats, - // not_found_route, - // ident, - .. - } = &input; - - // let from_path = input.build_from_path(); - // let to_path = input.build_to_path(); - - quote! { - // #[automatically_derived] - // impl ::dioxus::router::Routable for #ident { - - // fn recognize(pathname: &str) -> ::std::option::Option { - // todo!() - // // ::std::thread_local! { - // // static ROUTER: ::dioxus::router::__macro::Router = ::dioxus::router::__macro::build_router::<#ident>(); - // // } - // // let route = ROUTER.with(|router| ::dioxus::router::__macro::recognize_with_router(router, pathname)); - // // { - // // let route = ::std::clone::Clone::clone(&route); - // // #cache_thread_local_ident.with(move |val| { - // // *val.borrow_mut() = route; - // // }); - // // } - // // route - // } - // } - } -} diff --git a/packages/core-macro/src/rsx/component.rs b/packages/core-macro/src/rsx/component.rs index 4e9d449cf..17006e6ac 100644 --- a/packages/core-macro/src/rsx/component.rs +++ b/packages/core-macro/src/rsx/component.rs @@ -23,10 +23,10 @@ use syn::{ }; pub struct Component { - name: syn::Path, - body: Vec, - children: Vec, - manual_props: Option, + pub name: syn::Path, + pub body: Vec, + pub children: Vec, + pub manual_props: Option, } impl Parse for Component { diff --git a/packages/core-macro/src/rsx/element.rs b/packages/core-macro/src/rsx/element.rs index ebc401b6e..fa8fc9f51 100644 --- a/packages/core-macro/src/rsx/element.rs +++ b/packages/core-macro/src/rsx/element.rs @@ -11,12 +11,11 @@ use syn::{ // Parse the VNode::Element type // ======================================= pub struct Element { - name: Ident, - key: Option, - attributes: Vec, - listeners: Vec, - children: Vec, - _is_static: bool, + pub name: Ident, + pub key: Option, + pub attributes: Vec, + pub children: Vec, + pub _is_static: bool, } impl Parse for Element { @@ -28,7 +27,6 @@ impl Parse for Element { syn::braced!(content in stream); let mut attributes: Vec = vec![]; - let mut listeners: Vec = vec![]; let mut children: Vec = vec![]; let mut key = None; let mut _el_ref = None; @@ -54,6 +52,7 @@ impl Parse for Element { }); } else { let value = content.parse::()?; + attributes.push(ElementAttrNamed { el_name: el_name.clone(), attr: ElementAttr::CustomAttrExpression { name, value }, @@ -82,7 +81,7 @@ impl Parse for Element { content.parse::()?; if name_str.starts_with("on") { - listeners.push(ElementAttrNamed { + attributes.push(ElementAttrNamed { el_name: el_name.clone(), attr: ElementAttr::EventTokens { name, @@ -182,7 +181,6 @@ impl Parse for Element { name: el_name, attributes, children, - listeners, _is_static: false, }) } @@ -193,14 +191,21 @@ impl ToTokens for Element { let name = &self.name; let children = &self.children; - let listeners = &self.listeners; - let attr = &self.attributes; - let key = match &self.key { Some(ty) => quote! { Some(format_args_f!(#ty)) }, None => quote! { None }, }; + let listeners = self + .attributes + .iter() + .filter(|f| matches!(f.attr, ElementAttr::EventTokens { .. })); + + let attr = self + .attributes + .iter() + .filter(|f| !matches!(f.attr, ElementAttr::EventTokens { .. })); + tokens.append_all(quote! { __cx.element( dioxus_elements::#name, @@ -213,29 +218,28 @@ impl ToTokens for Element { } } -enum ElementAttr { - // attribute: "valuee {}" +pub enum ElementAttr { + /// attribute: "valuee {}" AttrText { name: Ident, value: LitStr }, - // attribute: true, + /// attribute: true, AttrExpression { name: Ident, value: Expr }, - // "attribute": "value {}" + /// "attribute": "value {}" CustomAttrText { name: LitStr, value: LitStr }, - // "attribute": true, + /// "attribute": true, CustomAttrExpression { name: LitStr, value: Expr }, - // // onclick: move |_| {} + // /// onclick: move |_| {} // EventClosure { name: Ident, closure: ExprClosure }, - - // onclick: {} + /// onclick: {} EventTokens { name: Ident, tokens: Expr }, } -struct ElementAttrNamed { - el_name: Ident, - attr: ElementAttr, +pub struct ElementAttrNamed { + pub el_name: Ident, + pub attr: ElementAttr, } impl ToTokens for ElementAttrNamed { diff --git a/packages/core-macro/src/rsx/mod.rs b/packages/core-macro/src/rsx/mod.rs index 5ff5d85f7..858f07c5c 100644 --- a/packages/core-macro/src/rsx/mod.rs +++ b/packages/core-macro/src/rsx/mod.rs @@ -15,6 +15,8 @@ mod component; mod element; mod node; +pub mod pretty; + // Re-export the namespaces into each other pub use component::*; pub use element::*; @@ -29,8 +31,8 @@ use syn::{ }; pub struct CallBody { - custom_context: Option, - roots: Vec, + pub custom_context: Option, + pub roots: Vec, } impl Parse for CallBody { @@ -77,7 +79,7 @@ impl ToTokens for CallBody { match &self.custom_context { // The `in cx` pattern allows directly rendering Some(ident) => out_tokens.append_all(quote! { - #ident.render(LazyNodes::new_some(move |__cx: NodeFactory| -> VNode { + #ident.render(LazyNodes::new(move |__cx: NodeFactory| -> VNode { use dioxus_elements::{GlobalAttributes, SvgAttributes}; #inner })) @@ -85,7 +87,7 @@ impl ToTokens for CallBody { // Otherwise we just build the LazyNode wrapper None => out_tokens.append_all(quote! { - LazyNodes::new_some(move |__cx: NodeFactory| -> VNode { + LazyNodes::new(move |__cx: NodeFactory| -> VNode { use dioxus_elements::{GlobalAttributes, SvgAttributes}; #inner }) diff --git a/packages/core-macro/src/rsx/pretty.rs b/packages/core-macro/src/rsx/pretty.rs new file mode 100644 index 000000000..26ad54006 --- /dev/null +++ b/packages/core-macro/src/rsx/pretty.rs @@ -0,0 +1 @@ +//! pretty printer for rsx! diff --git a/packages/core-macro/src/rsxtemplate.rs b/packages/core-macro/src/rsxtemplate.rs deleted file mode 100644 index 9222d7117..000000000 --- a/packages/core-macro/src/rsxtemplate.rs +++ /dev/null @@ -1,84 +0,0 @@ -use crate::{rsx::RsxBody, util::is_valid_svg_tag}; - -use { - proc_macro::TokenStream, - proc_macro2::{Span, TokenStream as TokenStream2}, - quote::{quote, ToTokens, TokenStreamExt}, - syn::{ - ext::IdentExt, - parse::{Parse, ParseStream}, - token, Error, Expr, ExprClosure, Ident, LitBool, LitStr, Path, Result, Token, - }, -}; - -// ============================================== -// Parse any stream coming from the html! macro -// ============================================== -pub struct RsxTemplate { - inner: RsxBody, -} - -impl Parse for RsxTemplate { - fn parse(s: ParseStream) -> Result { - if s.peek(LitStr) { - use std::str::FromStr; - - let lit = s.parse::()?; - let g = lit.span(); - let mut value = lit.value(); - if value.ends_with('\n') { - value.pop(); - if value.ends_with('\r') { - value.pop(); - } - } - let lit = LitStr::new(&value, lit.span()); - - // panic!("{:#?}", lit); - match lit.parse::() { - Ok(r) => Ok(Self { inner: r }), - Err(e) => Err(e), - } - } else { - panic!("Not a str lit") - } - // let t = s.parse::()?; - - // let new_stream = TokenStream::from(t.to_s) - - // let cx: Ident = s.parse()?; - // s.parse::()?; - // if elements are in an array, return a bumpalo::collections::Vec rather than a Node. - // let kind = if s.peek(token::Bracket) { - // let nodes_toks; - // syn::bracketed!(nodes_toks in s); - // let mut nodes: Vec> = vec![nodes_toks.parse()?]; - // while nodes_toks.peek(Token![,]) { - // nodes_toks.parse::()?; - // nodes.push(nodes_toks.parse()?); - // } - // NodeOrList::List(NodeList(nodes)) - // } else { - // NodeOrList::Node(s.parse()?) - // }; - // Ok(HtmlRender { kind }) - } -} - -impl ToTokens for RsxTemplate { - fn to_tokens(&self, out_tokens: &mut TokenStream2) { - self.inner.to_tokens(out_tokens); - // let new_toks = ToToksCtx::new(&self.kind).to_token_stream(); - - // // create a lazy tree that accepts a bump allocator - // let final_tokens = quote! { - // dioxus::prelude::LazyNodes::new(move |cx| { - // let bump = &cx.bump(); - - // #new_toks - // }) - // }; - - // final_tokens.to_tokens(out_tokens); - } -} diff --git a/packages/core/Cargo.toml b/packages/core/Cargo.toml index 03b378e88..4126eb47f 100644 --- a/packages/core/Cargo.toml +++ b/packages/core/Cargo.toml @@ -32,7 +32,7 @@ smallvec = "1.6" slab = "0.4" -futures-channel = "0.3" +futures-channel = "0.3.21" # used for noderefs once_cell = "1.8" diff --git a/packages/core/examples/borrowed.rs b/packages/core/examples/borrowed.rs deleted file mode 100644 index b7a9f513c..000000000 --- a/packages/core/examples/borrowed.rs +++ /dev/null @@ -1,33 +0,0 @@ -use dioxus::prelude::*; -use dioxus_core as dioxus; -use dioxus_core_macro::*; -use dioxus_html as dioxus_elements; - -fn main() {} - -fn app(cx: Scope) -> Element { - cx.render(rsx!(div { - app2( - p: "asd" - ) - })) -} - -#[derive(Props)] -struct Borrowed<'a> { - p: &'a str, -} - -fn app2<'a>(cx: Scope<'a, Borrowed<'a>>) -> Element { - let g = eat2(&cx); - rsx!(cx, "") -} - -fn eat2(s: &ScopeState) {} - -fn eat(f: &str) {} - -fn bleat() { - let blah = String::from("asd"); - eat(&blah); -} diff --git a/packages/core/examples/component_children.rs b/packages/core/examples/component_children.rs deleted file mode 100644 index ac76740b8..000000000 --- a/packages/core/examples/component_children.rs +++ /dev/null @@ -1,40 +0,0 @@ -#![allow(non_snake_case)] - -use dioxus::prelude::*; -use dioxus_core as dioxus; -use dioxus_core_macro::*; -use dioxus_html as dioxus_elements; - -fn main() { - let mut dom = VirtualDom::new(parent); - let edits = dom.rebuild(); - dbg!(edits); -} - -fn parent(cx: Scope) -> Element { - let value = cx.use_hook(|_| String::new()); - - cx.render(rsx! { - div { - child( - name: value, - h1 {"hi"} - ) - } - }) -} - -#[derive(Props)] -struct ChildProps<'a> { - name: &'a str, - children: Element<'a>, -} - -fn child<'a>(cx: Scope<'a, ChildProps<'a>>) -> Element { - cx.render(rsx! { - div { - "it's nested {cx.props.name}", - &cx.props.children - } - }) -} diff --git a/packages/core/examples/simple_hello.rs b/packages/core/examples/simple_hello.rs deleted file mode 100644 index 94a897e7c..000000000 --- a/packages/core/examples/simple_hello.rs +++ /dev/null @@ -1,9 +0,0 @@ -use dioxus::prelude::*; -use dioxus_core as dioxus; -use dioxus_core_macro::*; -use dioxus_html as dioxus_elements; - -// very tiny hello world -fn main() { - dioxus::VirtualDom::new(|cx| rsx!(cx, "hello world")); -} diff --git a/packages/core/examples/works.rs b/packages/core/examples/works.rs deleted file mode 100644 index 0de94b5c3..000000000 --- a/packages/core/examples/works.rs +++ /dev/null @@ -1,54 +0,0 @@ -#![allow(non_snake_case)] - -use dioxus::prelude::*; -use dioxus_core as dioxus; -use dioxus_core_macro::*; -use dioxus_html as dioxus_elements; - -fn main() { - let _ = VirtualDom::new(parent); -} - -fn parent(cx: Scope) -> Element { - let value = cx.use_hook(|_| String::new()); - - cx.render(rsx! { - div { - child( name: value ) - } - }) -} - -#[derive(Props)] -struct ChildProps<'a> { - name: &'a str, -} - -fn child<'a>(cx: Scope<'a, ChildProps<'a>>) -> Element { - cx.render(rsx! { - div { - h1 { "it's nested" } - grandchild( name: cx.props.name ) - } - }) -} - -#[derive(Props)] -struct Grandchild<'a> { - name: &'a str, -} - -fn grandchild<'a>(cx: Scope<'a, Grandchild>) -> Element<'a> { - cx.render(rsx! { - div { "Hello {cx.props.name}!" } - great_grandchild( name: cx.props.name ) - }) -} - -fn great_grandchild<'a>(cx: Scope<'a, Grandchild>) -> Element<'a> { - cx.render(rsx! { - div { - h1 { "it's nested" } - } - }) -} diff --git a/packages/core/src/diff.rs b/packages/core/src/diff.rs index d7189a710..4e9a11c34 100644 --- a/packages/core/src/diff.rs +++ b/packages/core/src/diff.rs @@ -257,11 +257,10 @@ impl<'b> DiffState<'b> { vcomponent.scope.set(Some(new_idx)); log::trace!( - "created component \"{}\", id: {:?} parent {:?} orig: {:?}", + "created component \"{}\", id: {:?} parent {:?}", vcomponent.fn_name, new_idx, parent_idx, - vcomponent.originator ); // if vcomponent.can_memoize { @@ -853,7 +852,7 @@ impl<'b> DiffState<'b> { nodes_created += self.create_node(new_node); } else { self.diff_node(&old[old_index], new_node); - nodes_created += self.push_all_nodes(new_node); + nodes_created += self.push_all_real_nodes(new_node); } } @@ -876,7 +875,7 @@ impl<'b> DiffState<'b> { nodes_created += self.create_node(new_node); } else { self.diff_node(&old[old_index], new_node); - nodes_created += self.push_all_nodes(new_node); + nodes_created += self.push_all_real_nodes(new_node); } } @@ -899,7 +898,7 @@ impl<'b> DiffState<'b> { nodes_created += self.create_node(new_node); } else { self.diff_node(&old[old_index], new_node); - nodes_created += self.push_all_nodes(new_node); + nodes_created += self.push_all_real_nodes(new_node); } } @@ -957,13 +956,6 @@ impl<'b> DiffState<'b> { let props = scope.props.take().unwrap(); c.props.borrow_mut().replace(props); self.scopes.try_remove(scope_id).unwrap(); - - // // we can only remove components if they are actively being diffed - // if self.scope_stack.contains(&c.originator) { - // log::trace!("Removing component {:?}", old); - - // self.scopes.try_remove(scope_id).unwrap(); - // } } self.leave_scope(); } @@ -1100,9 +1092,9 @@ impl<'b> DiffState<'b> { } // recursively push all the nodes of a tree onto the stack and return how many are there - fn push_all_nodes(&mut self, node: &'b VNode<'b>) -> usize { + fn push_all_real_nodes(&mut self, node: &'b VNode<'b>) -> usize { match node { - VNode::Text(_) | VNode::Placeholder(_) => { + VNode::Text(_) | VNode::Placeholder(_) | VNode::Element(_) => { self.mutations.push_root(node.mounted_id()); 1 } @@ -1110,7 +1102,7 @@ impl<'b> DiffState<'b> { VNode::Fragment(frag) => { let mut added = 0; for child in frag.children { - added += self.push_all_nodes(child); + added += self.push_all_real_nodes(child); } added } @@ -1118,16 +1110,7 @@ impl<'b> DiffState<'b> { VNode::Component(c) => { let scope_id = c.scope.get().unwrap(); let root = self.scopes.root_node(scope_id); - self.push_all_nodes(root) - } - - VNode::Element(el) => { - let mut num_on_stack = 0; - for child in el.children.iter() { - num_on_stack += self.push_all_nodes(child); - } - self.mutations.push_root(el.id.get().unwrap()); - num_on_stack + 1 + self.push_all_real_nodes(root) } } } diff --git a/packages/core/src/events.rs b/packages/core/src/events.rs index 8386cedd8..1a9899e4a 100644 --- a/packages/core/src/events.rs +++ b/packages/core/src/events.rs @@ -119,24 +119,41 @@ pub enum EventPriority { Low = 0, } +/// The internal Dioxus type that carries any event data to the relevant handler. +/// +/// +/// +/// +/// pub struct AnyEvent { pub(crate) bubble_state: Rc, pub(crate) data: Arc, } impl AnyEvent { + /// Convert this AnyEvent into a specific UiEvent with EventData. + /// + /// ```rust, ignore + /// let evt: FormEvent = evvt.downcast().unwrap(); + /// ``` pub fn downcast(self) -> Option> { let AnyEvent { data, bubble_state } = self; - if let Ok(data) = data.downcast::() { - Some(UiEvent { bubble_state, data }) - } else { - None - } + data.downcast::() + .ok() + .map(|data| UiEvent { bubble_state, data }) } } +/// A UiEvent is a type that wraps various EventData. +/// +/// You should prefer to use the name of the event directly, rather than +/// the UiEvent generic type. +/// +/// For the HTML crate, this would include [`MouseEvent`], [`FormEvent`] etc. pub struct UiEvent { + /// The internal data of the event + /// This is wrapped in an Arc so that it can be sent across threads pub data: Arc, #[allow(unused)] diff --git a/packages/core/src/lazynodes.rs b/packages/core/src/lazynodes.rs index 1340c916c..5fac7b194 100644 --- a/packages/core/src/lazynodes.rs +++ b/packages/core/src/lazynodes.rs @@ -35,14 +35,32 @@ enum StackNodeStorage<'a, 'b> { } impl<'a, 'b> LazyNodes<'a, 'b> { - pub fn new_some(_val: F) -> Self - where - F: FnOnce(NodeFactory<'a>) -> VNode<'a> + 'b, - { - Self::new(_val) + /// Create a new LazyNodes closure, optimistically placing it onto the stack. + /// + /// If the closure cannot fit into the stack allocation (16 bytes), then it + /// is placed on the heap. Most closures will fit into the stack, and is + /// the most optimal way to use the creation function. + pub fn new(val: impl FnOnce(NodeFactory<'a>) -> VNode<'a> + 'b) -> Self { + // there's no way to call FnOnce without a box, so we need to store it in a slot and use static dispatch + let mut slot = Some(val); + + let val = move |fac: Option>| { + let inner = slot.take().unwrap(); + fac.map(inner) + }; + + // miri does not know how to work with mucking directly into bytes + // just use a heap allocated type when miri is running + if cfg!(miri) { + Self { + inner: StackNodeStorage::Heap(Box::new(val)), + } + } else { + unsafe { LazyNodes::new_inner(val) } + } } - /// force this call onto the stack + /// Create a new LazyNodes closure, but force it onto the heap. pub fn new_boxed(_val: F) -> Self where F: FnOnce(NodeFactory<'a>) -> VNode<'a> + 'b, @@ -60,25 +78,6 @@ impl<'a, 'b> LazyNodes<'a, 'b> { } } - pub fn new(_val: impl FnOnce(NodeFactory<'a>) -> VNode<'a> + 'b) -> Self { - // there's no way to call FnOnce without a box, so we need to store it in a slot and use static dispatch - let mut slot = Some(_val); - - let val = move |fac: Option>| { - let inner = slot.take().unwrap(); - fac.map(inner) - }; - - // miri does not know how to work with mucking directly into bytes - if cfg!(miri) { - Self { - inner: StackNodeStorage::Heap(Box::new(val)), - } - } else { - unsafe { LazyNodes::new_inner(val) } - } - } - unsafe fn new_inner(val: F) -> Self where F: FnMut(Option>) -> Option> + 'b, @@ -153,6 +152,15 @@ impl<'a, 'b> LazyNodes<'a, 'b> { } } + /// Call the closure with the given factory to produce real VNodes. + /// + /// ```rust, ignore + /// let f = LazyNodes::new(move |f| f.element("div", [], [], [] None)); + /// + /// let fac = NodeFactory::new(&cx); + /// + /// let node = f.call(cac); + /// ``` pub fn call(self, f: NodeFactory<'a>) -> VNode<'a> { match self.inner { StackNodeStorage::Heap(mut lazy) => lazy(Some(f)).unwrap(), @@ -245,9 +253,7 @@ mod tests { #[test] fn it_works() { fn app(cx: Scope<()>) -> Element { - cx.render(LazyNodes::new_some(|f| { - f.text(format_args!("hello world!")) - })) + cx.render(LazyNodes::new(|f| f.text(format_args!("hello world!")))) } let mut dom = VirtualDom::new(app); @@ -280,7 +286,7 @@ mod tests { .map(|i| { let val = cx.props.inner.clone(); - LazyNodes::new_some(move |f| { + LazyNodes::new(move |f| { log::debug!("hell closure"); let inner = DropInner { id: i }; f.text(format_args!("hello world {:?}, {:?}", inner.id, val)) @@ -288,7 +294,7 @@ mod tests { }) .collect::>(); - LazyNodes::new_some(|f| { + LazyNodes::new(|f| { log::debug!("main closure"); f.fragment_from_iter(it) }) diff --git a/packages/core/src/lib.rs b/packages/core/src/lib.rs index e81ddca87..07fb5ce79 100644 --- a/packages/core/src/lib.rs +++ b/packages/core/src/lib.rs @@ -1,5 +1,6 @@ #![allow(non_snake_case)] #![doc = include_str!("../README.md")] +#![deny(missing_docs)] pub(crate) mod diff; pub(crate) mod events; @@ -76,6 +77,9 @@ pub use crate::innerlude::{ VElement, VFragment, VNode, VPlaceholder, VText, VirtualDom, }; +/// The purpose of this module is to alleviate imports of many common types +/// +/// This includes types like [`Scope`], [`Element`], and [`Component`]. pub mod prelude { pub use crate::innerlude::{ fc_to_builder, Attributes, Component, DioxusElement, Element, EventHandler, Fragment, diff --git a/packages/core/src/mutations.rs b/packages/core/src/mutations.rs index bd94d0b71..2d3a4505f 100644 --- a/packages/core/src/mutations.rs +++ b/packages/core/src/mutations.rs @@ -16,8 +16,13 @@ use std::{any::Any, fmt::Debug}; /// /// Mutations are the only link between the RealDOM and the VirtualDOM. pub struct Mutations<'a> { + /// The list of edits that need to be applied for the RealDOM to match the VirtualDOM. pub edits: Vec>, + + /// The list of Scopes that were diffed, created, and removed during the Diff process. pub dirty_scopes: FxHashSet, + + /// The list of nodes to connect to the RealDOM. pub refs: Vec>, } @@ -39,74 +44,146 @@ impl Debug for Mutations<'_> { serde(tag = "type") )] pub enum DomEdit<'bump> { + /// Push the given root node onto our stack. PushRoot { + /// The ID of the root node to push. root: u64, }, + /// Pop the topmost node from our stack and append them to the node + /// at the top of the stack. AppendChildren { + /// How many nodes should be popped from the stack. + /// The node remaining on the stack will be the target for the append. many: u32, }, - // // save a possibly-fragment node as a template - // SaveAsTemplate { - // many: u32, - // }, - - // "Root" refers to the item directly - // it's a waste of an instruction to push the root directly + /// Replace a given (single) node with a handful of nodes currently on the stack. ReplaceWith { + /// The ID of the node to be replaced. root: u64, + + /// How many nodes should be popped from the stack to replace the target node. m: u32, }, + + /// Insert a number of nodes after a given node. InsertAfter { + /// The ID of the node to insert after. root: u64, + + /// How many nodes should be popped from the stack to insert after the target node. n: u32, }, + + /// Insert a number of nodes before a given node. InsertBefore { + /// The ID of the node to insert before. root: u64, + + /// How many nodes should be popped from the stack to insert before the target node. n: u32, }, + + /// Remove a particular node from the DOM Remove { + /// The ID of the node to remove. root: u64, }, + + /// Create a new purely-text node CreateTextNode { + /// The ID the new node should have. + root: u64, + + /// The textcontent of the node text: &'bump str, - root: u64, }, + + /// Create a new purely-element node CreateElement { - tag: &'bump str, + /// The ID the new node should have. root: u64, + + /// The tagname of the node + tag: &'bump str, }, + + /// Create a new purely-comment node with a given namespace CreateElementNs { - tag: &'bump str, + /// The ID the new node should have. root: u64, + + /// The namespace of the node + tag: &'bump str, + + /// The namespace of the node (like `SVG`) ns: &'static str, }, + + /// Create a new placeholder node. + /// In most implementations, this will either be a hidden div or a comment node. CreatePlaceholder { + /// The ID the new node should have. root: u64, }, + + /// Create a new Event Listener. NewEventListener { + /// The name of the event to listen for. event_name: &'static str, + + /// The ID of the node to attach the listener to. scope: ScopeId, + + /// The ID of the node to attach the listener to. root: u64, }, + + /// Remove an existing Event Listener. RemoveEventListener { + /// The ID of the node to remove. root: u64, + + /// The name of the event to remove. event: &'static str, }, + + /// Set the textcontent of a node. SetText { + /// The ID of the node to set the textcontent of. root: u64, + + /// The textcontent of the node text: &'bump str, }, + + /// Set the value of a node's attribute. SetAttribute { + /// The ID of the node to set the attribute of. root: u64, + + /// The name of the attribute to set. field: &'static str, + + /// The value of the attribute. value: &'bump str, + + /// The (optional) namespace of the attribute. + /// For instance, "style" is in the "style" namespace. ns: Option<&'bump str>, }, + + /// Remove an attribute from a node. RemoveAttribute { + /// The ID of the node to remove. root: u64, + + /// The name of the attribute to remove. name: &'static str, + + /// The namespace of the attribute. + ns: Option<&'bump str>, }, } @@ -218,8 +295,15 @@ impl<'a> Mutations<'a> { } pub(crate) fn remove_attribute(&mut self, attribute: &Attribute, root: u64) { - let name = attribute.name; - self.edits.push(RemoveAttribute { name, root }); + let Attribute { + name, namespace, .. + } = attribute; + + self.edits.push(RemoveAttribute { + name, + ns: *namespace, + root, + }); } pub(crate) fn mark_dirty_scope(&mut self, scope: ScopeId) { diff --git a/packages/core/src/nodes.rs b/packages/core/src/nodes.rs index 7a36f58ce..094af2281 100644 --- a/packages/core/src/nodes.rs +++ b/packages/core/src/nodes.rs @@ -148,7 +148,7 @@ impl<'src> VNode<'src> { } // Create an "owned" version of the vnode. - pub fn decouple(&self) -> VNode<'src> { + pub(crate) fn decouple(&self) -> VNode<'src> { match *self { VNode::Text(t) => VNode::Text(t), VNode::Element(e) => VNode::Element(e), @@ -181,7 +181,6 @@ impl Debug for VNode<'_> { .field("fnptr", &comp.user_fc) .field("key", &comp.key) .field("scope", &comp.scope) - .field("originator", &comp.originator) .finish(), } } @@ -200,6 +199,7 @@ impl std::fmt::Display for ElementId { } impl ElementId { + /// Convertt the ElementId to a `u64`. pub fn as_u64(self) -> u64 { self.0 as u64 } @@ -211,18 +211,26 @@ fn empty_cell() -> Cell> { /// A placeholder node only generated when Fragments don't have any children. pub struct VPlaceholder { + /// The [`ElementId`] of the placeholder. pub id: Cell>, } /// A bump-allocated string slice and metadata. pub struct VText<'src> { - pub text: &'src str, + /// The [`ElementId`] of the VText. pub id: Cell>, + + /// The text of the VText. + pub text: &'src str, + + /// An indiciation if this VText can be ignored during diffing + /// Is usually only when there are no strings to be formatted (so the text is &'static str) pub is_static: bool, } /// A list of VNodes with no single root. pub struct VFragment<'src> { + /// The key of the fragment to be used during keyed diffing. pub key: Option<&'src str>, /// Fragments can never have zero children. Enforced by NodeFactory. @@ -233,13 +241,34 @@ pub struct VFragment<'src> { /// An element like a "div" with children, listeners, and attributes. pub struct VElement<'a> { - pub tag: &'static str, - pub namespace: Option<&'static str>, - pub key: Option<&'a str>, + /// The [`ElementId`] of the VText. pub id: Cell>, + + /// The key of the element to be used during keyed diffing. + pub key: Option<&'a str>, + + /// The tag name of the element. + /// + /// IE "div" + pub tag: &'static str, + + /// The namespace of the VElement + /// + /// IE "svg" + pub namespace: Option<&'static str>, + + /// The parent of the Element (if any). + /// + /// Used when bubbling events pub parent: Cell>, + + /// The Listeners of the VElement. pub listeners: &'a [Listener<'a>], + + /// The attributes of the VElement. pub attributes: &'a [Attribute<'a>], + + /// The children of the VElement. pub children: &'a [VNode<'a>], } @@ -275,12 +304,19 @@ impl Debug for VElement<'_> { /// }; /// ``` pub trait DioxusElement { + /// The tag name of the element. const TAG_NAME: &'static str; + + /// The namespace of the element. const NAME_SPACE: Option<&'static str>; + + /// The tag name of the element. #[inline] fn tag_name(&self) -> &'static str { Self::TAG_NAME } + + /// The namespace of the element. #[inline] fn namespace(&self) -> Option<&'static str> { Self::NAME_SPACE @@ -291,16 +327,25 @@ pub trait DioxusElement { /// `href="https://example.com"`. #[derive(Clone, Debug)] pub struct Attribute<'a> { + /// The name of the attribute. pub name: &'static str, + /// The value of the attribute. pub value: &'a str, + /// An indication if this attribute can be ignored during diffing + /// + /// Usually only when there are no strings to be formatted (so the value is &'static str) pub is_static: bool, + /// An indication of we should always try and set the attribute. + /// Used in controlled components to ensure changes are propagated. pub is_volatile: bool, - // Doesn't exist in the html spec. - // Used in Dioxus to denote "style" tags. + /// The namespace of the attribute. + /// + /// Doesn't exist in the html spec. + /// Used in Dioxus to denote "style" tags and other attribute groups. pub namespace: Option<&'static str>, } @@ -353,6 +398,8 @@ type ExternalListenerCallback<'bump, T> = BumpBox<'bump, dyn FnMut(T) + 'bump>; /// /// ``` pub struct EventHandler<'bump, T = ()> { + /// The (optional) callback that the user specified + /// Uses a `RefCell` to allow for interior mutability, and FnMut closures. pub callback: RefCell>>, } @@ -381,12 +428,23 @@ impl EventHandler<'_, T> { /// Virtual Components for custom user-defined components /// Only supports the functional syntax pub struct VComponent<'src> { + /// The key of the component to be used during keyed diffing. pub key: Option<&'src str>, - pub originator: ScopeId, + + /// The ID of the component. + /// Will not be assigned until after the component has been initialized. pub scope: Cell>, + + /// An indication if the component is static (can be memozied) pub can_memoize: bool, + + /// The function pointer to the component's render function. pub user_fc: ComponentPtr, + + /// The actual name of the component. pub fn_name: &'static str, + + /// The props of the component. pub props: RefCell>>, } @@ -434,6 +492,7 @@ pub struct NodeFactory<'a> { } impl<'a> NodeFactory<'a> { + /// Create a new [`NodeFactory`] from a [`Scope`] or [`ScopeState`] pub fn new(scope: &'a ScopeState) -> NodeFactory<'a> { NodeFactory { scope, @@ -441,6 +500,7 @@ impl<'a> NodeFactory<'a> { } } + /// Get the custom alloactor for this component #[inline] pub fn bump(&self) -> &'a bumpalo::Bump { self.bump @@ -482,6 +542,7 @@ impl<'a> NodeFactory<'a> { })) } + /// Create a new [`VNode::VElement`] pub fn element( &self, el: impl DioxusElement, @@ -500,6 +561,9 @@ impl<'a> NodeFactory<'a> { ) } + /// Create a new [`VNode::VElement`] without the trait bound + /// + /// IE pass in "div" instead of `div` pub fn raw_element( &self, tag_name: &'static str, @@ -529,6 +593,7 @@ impl<'a> NodeFactory<'a> { })) } + /// Create a new [`Attribute`] pub fn attr( &self, name: &'static str, @@ -546,6 +611,7 @@ impl<'a> NodeFactory<'a> { } } + /// Create a new [`VNode::VComponent`] pub fn component

( &self, component: fn(Scope<'a, P>) -> Element, @@ -561,11 +627,8 @@ impl<'a> NodeFactory<'a> { scope: Default::default(), can_memoize: P::IS_STATIC, user_fc: component as ComponentPtr, - originator: self.scope.scope_id(), fn_name, props: RefCell::new(Some(Box::new(VComponentProps { - // local_props: RefCell::new(Some(props)), - // heap_props: RefCell::new(None), props, memo: P::memoize, // smuggle the memoization function across borders @@ -586,6 +649,7 @@ impl<'a> NodeFactory<'a> { VNode::Component(vcomp) } + /// Create a new [`Listener`] pub fn listener(self, event: &'static str, callback: InternalHandler<'a>) -> Listener<'a> { Listener { event, @@ -594,6 +658,7 @@ impl<'a> NodeFactory<'a> { } } + /// Create a new [`VNode::VFragment`] from a root of the rsx! call pub fn fragment_root<'b, 'c>( self, node_iter: impl IntoIterator + 'c> + 'b, @@ -614,6 +679,7 @@ impl<'a> NodeFactory<'a> { } } + /// Create a new [`VNode::VFragment`] from any iterator pub fn fragment_from_iter<'b, 'c>( self, node_iter: impl IntoIterator + 'c> + 'b, @@ -653,8 +719,7 @@ impl<'a> NodeFactory<'a> { } } - // this isn't quite feasible yet - // I think we need some form of interior mutability or state on nodefactory that stores which subtree was created + /// Create a new [`VNode`] from any iterator of children pub fn create_children( self, node_iter: impl IntoIterator>, @@ -679,6 +744,7 @@ impl<'a> NodeFactory<'a> { } } + /// Create a new [`EventHandler`] from an [`FnMut`] pub fn event_handler(self, f: impl FnMut(T) + 'a) -> EventHandler<'a, T> { let handler: &mut dyn FnMut(T) = self.bump.alloc(f); let caller = unsafe { BumpBox::from_raw(handler as *mut dyn FnMut(T)) }; @@ -709,6 +775,7 @@ impl Debug for NodeFactory<'_> { /// As such, all node creation must go through the factory, which is only available in the component context. /// These strict requirements make it possible to manage lifetimes and state. pub trait IntoVNode<'a> { + /// Convert this into a [`VNode`], using the [`NodeFactory`] as a source of allocation fn into_vnode(self, cx: NodeFactory<'a>) -> VNode<'a>; } diff --git a/packages/core/src/properties.rs b/packages/core/src/properties.rs index f42bc36ba..e81fc52a2 100644 --- a/packages/core/src/properties.rs +++ b/packages/core/src/properties.rs @@ -128,8 +128,14 @@ pub fn Fragment<'a>(cx: Scope<'a, FragmentProps<'a>>) -> Element { /// } /// ``` pub trait Properties: Sized { + /// The type of the builder for this component. + /// Used to create "in-progress" versions of the props. type Builder; + + /// An indication if these props are can be memoized automatically. const IS_STATIC: bool; + + /// Create a builder for this component. fn builder() -> Self::Builder; /// Memoization can only happen if the props are valid for the 'static lifetime diff --git a/packages/core/src/scopes.rs b/packages/core/src/scopes.rs index 1e58dcfd2..65725ad4f 100644 --- a/packages/core/src/scopes.rs +++ b/packages/core/src/scopes.rs @@ -11,6 +11,7 @@ use std::{ future::Future, pin::Pin, rc::Rc, + sync::Arc, }; /// for traceability, we use the raw fn pointer to identify the function @@ -96,11 +97,10 @@ impl ScopeArena { // Get the height of the scope let height = parent_scope - .map(|id| self.get_scope(id).map(|scope| scope.height + 1)) - .flatten() + .and_then(|id| self.get_scope(id).map(|scope| scope.height + 1)) .unwrap_or_default(); - let parent_scope = parent_scope.map(|f| self.get_scope_raw(f)).flatten(); + let parent_scope = parent_scope.and_then(|f| self.get_scope_raw(f)); /* This scopearena aggressively reuses old scopes when possible. @@ -399,7 +399,10 @@ impl ScopeArena { /// } /// ``` pub struct Scope<'a, P = ()> { + /// The internal ScopeState for this component pub scope: &'a ScopeState, + + /// The props for this component pub props: &'a P, } @@ -582,12 +585,17 @@ impl ScopeState { self.our_arena_idx } + /// Get a handle to the raw update scheduler channel + pub fn scheduler_channel(&self) -> UnboundedSender { + self.tasks.sender.clone() + } + /// Create a subscription that schedules a future render for the reference component /// /// ## Notice: you should prefer using prepare_update and get_scope_id - pub fn schedule_update(&self) -> Rc { + pub fn schedule_update(&self) -> Arc { let (chan, id) = (self.tasks.sender.clone(), self.scope_id()); - Rc::new(move || { + Arc::new(move || { let _ = chan.unbounded_send(SchedulerMsg::Immediate(id)); }) } @@ -597,9 +605,9 @@ impl ScopeState { /// A component's ScopeId can be obtained from `use_hook` or the [`ScopeState::scope_id`] method. /// /// This method should be used when you want to schedule an update for a component - pub fn schedule_update_any(&self) -> Rc { + pub fn schedule_update_any(&self) -> Arc { let chan = self.tasks.sender.clone(); - Rc::new(move |id| { + Arc::new(move |id| { let _ = chan.unbounded_send(SchedulerMsg::Immediate(id)); }) } @@ -656,8 +664,7 @@ impl ScopeState { self.shared_contexts .borrow_mut() .insert(TypeId::of::(), value.clone()) - .map(|f| f.downcast::().ok()) - .flatten(); + .and_then(|f| f.downcast::().ok()); value } @@ -687,8 +694,7 @@ impl ScopeState { self.shared_contexts .borrow_mut() .insert(TypeId::of::(), value.clone()) - .map(|f| f.downcast::().ok()) - .flatten(); + .and_then(|f| f.downcast::().ok()); return value; } @@ -750,7 +756,8 @@ impl ScopeState { self.push_future(fut); } - // todo: attach some state to the future to know if we should poll it + /// Informs the scheduler that this task is no longer needed and should be removed + /// on next poll. pub fn remove_future(&self, id: TaskId) { self.tasks.remove_fut(id); } diff --git a/packages/core/src/util.rs b/packages/core/src/util.rs index b9640792d..a6a524e27 100644 --- a/packages/core/src/util.rs +++ b/packages/core/src/util.rs @@ -1,5 +1,7 @@ use crate::innerlude::*; +/// An iterator that only yields "real" [`Element`]s. IE only Elements that are +/// not [`VNode::VComponent`] or [`VNode::VFragment`], . pub struct ElementIdIterator<'a> { vdom: &'a VirtualDom, @@ -9,6 +11,9 @@ pub struct ElementIdIterator<'a> { } impl<'a> ElementIdIterator<'a> { + /// Create a new iterator from the given [`VirtualDom`] and [`VNode`] + /// + /// This will allow you to iterate through all the real childrne of the [`VNode`]. pub fn new(vdom: &'a VirtualDom, node: &'a VNode<'a>) -> Self { Self { vdom, diff --git a/packages/core/src/virtual_dom.rs b/packages/core/src/virtual_dom.rs index a7092104c..6d1678773 100644 --- a/packages/core/src/virtual_dom.rs +++ b/packages/core/src/virtual_dom.rs @@ -114,15 +114,18 @@ pub struct VirtualDom { ), } +/// The type of message that can be sent to the scheduler. +/// +/// These messages control how the scheduler will process updates to the UI. #[derive(Debug)] pub enum SchedulerMsg { - // events from the host + /// Events from the Renderer Event(UserEvent), - // setstate + /// Immediate updates from Components that mark them as dirty Immediate(ScopeId), - // an async task pushed from an event handler (or just spawned) + /// New tasks from components that should be polled when the next poll is ready NewTask(ScopeId), } @@ -388,6 +391,9 @@ impl VirtualDom { } } + /// Handle an individual message for the scheduler. + /// + /// This will either call an event listener or mark a component as dirty. pub fn process_message(&mut self, msg: SchedulerMsg) { match msg { SchedulerMsg::NewTask(_id) => { diff --git a/packages/core/tests/lifecycle.rs b/packages/core/tests/lifecycle.rs index f977ba96e..35058d418 100644 --- a/packages/core/tests/lifecycle.rs +++ b/packages/core/tests/lifecycle.rs @@ -1,4 +1,5 @@ #![allow(unused, non_upper_case_globals)] +#![allow(non_snake_case)] //! Tests for the lifecycle of components. use dioxus::prelude::*; diff --git a/packages/core/tests/miri_stress.rs b/packages/core/tests/miri_stress.rs index 8ce030147..fe98c83ae 100644 --- a/packages/core/tests/miri_stress.rs +++ b/packages/core/tests/miri_stress.rs @@ -1,3 +1,4 @@ +#![allow(non_snake_case)] /* Stress Miri as much as possible. @@ -311,22 +312,11 @@ fn leak_thru_children() { #[test] fn test_pass_thru() { - #[inline_props] - fn Router<'a>(cx: Scope, children: Element<'a>) -> Element { - cx.render(rsx! { - div { - &cx.props.children - } - }) - } - #[inline_props] fn NavContainer<'a>(cx: Scope, children: Element<'a>) -> Element { cx.render(rsx! { header { - nav { - &cx.props.children - } + nav { children } } }) } @@ -365,9 +355,9 @@ fn test_pass_thru() { class: "columns is-mobile", div { class: "column is-full", - &cx.props.nav, - &cx.props.body, - &cx.props.footer, + nav, + body, + footer, } } }) @@ -398,7 +388,7 @@ fn test_pass_thru() { let mut dom = new_dom(app, ()); let _ = dom.rebuild(); - for x in 0..40 { + for _ in 0..40 { dom.handle_message(SchedulerMsg::Immediate(ScopeId(0))); dom.work_with_deadline(|| false); dom.handle_message(SchedulerMsg::Immediate(ScopeId(0))); diff --git a/packages/core/tests/passthru.rs b/packages/core/tests/passthru.rs index e00aa545c..948de8b67 100644 --- a/packages/core/tests/passthru.rs +++ b/packages/core/tests/passthru.rs @@ -1,4 +1,5 @@ #![allow(unused, non_upper_case_globals)] +#![allow(non_snake_case)] //! Diffing Tests //! @@ -40,9 +41,7 @@ fn nested_passthru_creates() { #[inline_props] fn Child<'a>(cx: Scope, children: Element<'a>) -> Element { - cx.render(rsx! { - children - }) + cx.render(rsx! { children }) }; let mut dom = VirtualDom::new(app); diff --git a/packages/core/tests/sharedstate.rs b/packages/core/tests/sharedstate.rs index 70e823569..18d569914 100644 --- a/packages/core/tests/sharedstate.rs +++ b/packages/core/tests/sharedstate.rs @@ -1,4 +1,4 @@ -#![allow(unused, non_upper_case_globals)] +#![allow(unused, non_upper_case_globals, non_snake_case)] use dioxus::{prelude::*, DomEdit, Mutations, SchedulerMsg, ScopeId}; use dioxus_core as dioxus; diff --git a/packages/desktop/Cargo.toml b/packages/desktop/Cargo.toml index fa1bc88dc..017d399c1 100644 --- a/packages/desktop/Cargo.toml +++ b/packages/desktop/Cargo.toml @@ -13,31 +13,39 @@ keywords = ["dom", "ui", "gui", "react", "wasm"] [dependencies] dioxus-core = { path = "../core", version = "^0.1.9", features = ["serialize"] } -argh = "0.1.4" -serde = "1.0.120" -serde_json = "1.0.61" -thiserror = "1.0.23" -log = "0.4.13" -html-escape = "0.2.9" -wry = "0.12.2" -futures-channel = "0.3" -tokio = { version = "1.12.0", features = [ +serde = "1.0.136" +serde_json = "1.0.79" +thiserror = "1.0.30" +log = "0.4.14" +wry = { version = "0.13.1" } +futures-channel = "0.3.21" +tokio = { version = "1.16.1", features = [ "sync", "rt-multi-thread", "rt", "time", ], optional = true, default-features = false } -dioxus-core-macro = { path = "../core-macro", version = "^0.1.7" } dioxus-html = { path = "../html", features = ["serialize"], version = "^0.1.6" } webbrowser = "0.5.5" mime_guess = "2.0.3" dioxus-interpreter-js = { path = "../interpreter", version = "^0.0.0" } - +dunce = "1.0.2" +[target.'cfg(target_os = "macos")'.dependencies] +core-foundation = "0.9.3" [features] default = ["tokio_runtime"] tokio_runtime = ["tokio"] +devtool = ["wry/devtool"] +fullscreen = ["wry/fullscreen"] +transparent = ["wry/transparent"] + +tray = ["wry/tray"] +ayatana = ["wry/ayatana"] + [dev-dependencies] +dioxus-core-macro = { path = "../core-macro", version = "^0.1.7" } dioxus-hooks = { path = "../hooks" } +# image = "0.24.0" # enable this when generating a new desktop image diff --git a/packages/desktop/src/assets/default_icon.bin b/packages/desktop/src/assets/default_icon.bin new file mode 100644 index 000000000..2d4898f0c Binary files /dev/null and b/packages/desktop/src/assets/default_icon.bin differ diff --git a/packages/desktop/src/assets/default_icon.png b/packages/desktop/src/assets/default_icon.png new file mode 100644 index 000000000..d0742ea8a Binary files /dev/null and b/packages/desktop/src/assets/default_icon.png differ diff --git a/packages/desktop/src/cfg.rs b/packages/desktop/src/cfg.rs index 5baa46f5d..6028706bc 100644 --- a/packages/desktop/src/cfg.rs +++ b/packages/desktop/src/cfg.rs @@ -1,3 +1,6 @@ +use std::path::PathBuf; + +use wry::application::window::Icon; use wry::{ application::{ event_loop::EventLoop, @@ -11,14 +14,16 @@ use wry::{ pub(crate) type DynEventHandlerFn = dyn Fn(&mut EventLoop<()>, &mut WebView); pub struct DesktopConfig { - pub window: WindowBuilder, - pub file_drop_handler: Option bool>>, - pub protocos: Vec, + pub(crate) window: WindowBuilder, + pub(crate) file_drop_handler: Option bool>>, + pub(crate) protocols: Vec, pub(crate) pre_rendered: Option, pub(crate) event_handler: Option>, + pub(crate) disable_context_menu: bool, + pub(crate) resource_dir: Option, } -pub type WryProtocl = ( +pub(crate) type WryProtocol = ( String, Box WryResult + 'static>, ); @@ -28,15 +33,31 @@ impl DesktopConfig { #[inline] pub fn new() -> Self { let window = WindowBuilder::new().with_title("Dioxus app"); + Self { event_handler: None, window, - protocos: Vec::new(), + protocols: Vec::new(), file_drop_handler: None, pre_rendered: None, + disable_context_menu: !cfg!(debug_assertions), + resource_dir: None, } } + /// set the directory from which assets will be searched in release mode + pub fn with_resource_directory(mut self, path: impl Into) -> Self { + self.resource_dir = Some(path.into()); + self + } + + /// Set whether or not the right-click context menu should be disabled. + pub fn with_disable_context_menu(&mut self, disable: bool) -> &mut Self { + self.disable_context_menu = disable; + self + } + + /// With pre-rendered HTML content pub fn with_prerendered(&mut self, content: String) -> &mut Self { self.pre_rendered = Some(content); self @@ -75,7 +96,21 @@ impl DesktopConfig { where F: Fn(&HttpRequest) -> WryResult + 'static, { - self.protocos.push((name, Box::new(handler))); + self.protocols.push((name, Box::new(handler))); + self + } + + pub fn with_icon(&mut self, icon: Icon) -> &mut Self { + self.window.window.window_icon = Some(icon); + self + } +} + +impl DesktopConfig { + pub(crate) fn with_default_icon(mut self) -> Self { + let bin: &[u8] = include_bytes!("./assets/default_icon.bin"); + let rgba = Icon::from_rgba(bin.to_owned(), 460, 460).expect("image parse failed"); + self.window.window.window_icon = Some(rgba); self } } @@ -85,3 +120,31 @@ impl Default for DesktopConfig { Self::new() } } + +// dirty trick, avoid introducing `image` at runtime +// TODO: use serde when `Icon` impl serde +// +// This function should only be enabled when generating new icons. +// +// #[test] +// #[ignore] +// fn prepare_default_icon() { +// use image::io::Reader as ImageReader; +// use image::ImageFormat; +// use std::fs::File; +// use std::io::Cursor; +// use std::io::Write; +// use std::path::PathBuf; +// let png: &[u8] = include_bytes!("default_icon.png"); +// let mut reader = ImageReader::new(Cursor::new(png)); +// reader.set_format(ImageFormat::Png); +// let icon = reader.decode().unwrap(); +// let bin = PathBuf::from(file!()) +// .parent() +// .unwrap() +// .join("default_icon.bin"); +// println!("{:?}", bin); +// let mut file = File::create(bin).unwrap(); +// file.write_all(icon.as_bytes()).unwrap(); +// println!("({}, {})", icon.width(), icon.height()) +// } diff --git a/packages/desktop/src/controller.rs b/packages/desktop/src/controller.rs new file mode 100644 index 000000000..ef2ecf5c1 --- /dev/null +++ b/packages/desktop/src/controller.rs @@ -0,0 +1,106 @@ +use crate::desktop_context::{DesktopContext, UserWindowEvent}; +use dioxus_core::*; +use std::{ + collections::{HashMap, VecDeque}, + sync::atomic::AtomicBool, + sync::{Arc, RwLock}, +}; +use wry::{ + self, + application::{event_loop::ControlFlow, event_loop::EventLoopProxy, window::WindowId}, + webview::WebView, +}; + +pub(super) struct DesktopController { + pub(super) webviews: HashMap, + pub(super) sender: futures_channel::mpsc::UnboundedSender, + pub(super) pending_edits: Arc>>, + pub(super) quit_app_on_close: bool, + pub(super) is_ready: Arc, +} + +impl DesktopController { + // Launch the virtualdom on its own thread managed by tokio + // returns the desktop state + pub(super) fn new_on_tokio( + root: Component

, + props: P, + proxy: EventLoopProxy, + ) -> Self { + let edit_queue = Arc::new(RwLock::new(VecDeque::new())); + let pending_edits = edit_queue.clone(); + + let (sender, receiver) = futures_channel::mpsc::unbounded::(); + let return_sender = sender.clone(); + + let desktop_context_proxy = proxy.clone(); + std::thread::spawn(move || { + // We create the runtime as multithreaded, so you can still "spawn" onto multiple threads + let runtime = tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .unwrap(); + + runtime.block_on(async move { + let mut dom = + VirtualDom::new_with_props_and_scheduler(root, props, (sender, receiver)); + + let window_context = DesktopContext::new(desktop_context_proxy); + + dom.base_scope().provide_context(window_context); + + let edits = dom.rebuild(); + + edit_queue + .write() + .unwrap() + .push_front(serde_json::to_string(&edits.edits).unwrap()); + + // Make sure the window is ready for any new updates + proxy.send_event(UserWindowEvent::Update).unwrap(); + + loop { + dom.wait_for_work().await; + let mut muts = dom.work_with_deadline(|| false); + + while let Some(edit) = muts.pop() { + edit_queue + .write() + .unwrap() + .push_front(serde_json::to_string(&edit.edits).unwrap()); + } + + let _ = proxy.send_event(UserWindowEvent::Update); + } + }) + }); + + Self { + pending_edits, + sender: return_sender, + webviews: HashMap::new(), + is_ready: Arc::new(AtomicBool::new(false)), + quit_app_on_close: true, + } + } + + pub(super) fn close_window(&mut self, window_id: WindowId, control_flow: &mut ControlFlow) { + self.webviews.remove(&window_id); + + if self.webviews.is_empty() && self.quit_app_on_close { + *control_flow = ControlFlow::Exit; + } + } + + pub(super) fn try_load_ready_webviews(&mut self) { + if self.is_ready.load(std::sync::atomic::Ordering::Relaxed) { + let mut queue = self.pending_edits.write().unwrap(); + let (_id, view) = self.webviews.iter_mut().next().unwrap(); + + while let Some(edit) = queue.pop_back() { + view.evaluate_script(&format!("window.interpreter.handleEdits({})", edit)) + .unwrap(); + } + } + } +} diff --git a/packages/desktop/src/desktop_context.rs b/packages/desktop/src/desktop_context.rs index 9c0404477..eaff13750 100644 --- a/packages/desktop/src/desktop_context.rs +++ b/packages/desktop/src/desktop_context.rs @@ -3,13 +3,23 @@ use std::rc::Rc; use dioxus_core::ScopeState; use wry::application::event_loop::EventLoopProxy; -use crate::UserWindowEvent; +use UserWindowEvent::*; -type ProxyType = EventLoopProxy; +pub type ProxyType = EventLoopProxy; -/// Desktop-Window handle api context +/// Get an imperative handle to the current window +pub fn use_window(cx: &ScopeState) -> &Rc { + cx.use_hook(|_| cx.consume_context::()) + .as_ref() + .unwrap() +} + +/// An imperative interface to the current window. /// -/// you can use this context control some window event +/// To get a handle to the current window, use the [`use_window`] hook. +/// +/// +/// # Example /// /// you can use `cx.consume_context::` to get this context /// @@ -18,7 +28,8 @@ type ProxyType = EventLoopProxy; /// ``` #[derive(Clone)] pub struct DesktopContext { - proxy: ProxyType, + /// The wry/tao proxy to the current window + pub proxy: ProxyType, } impl DesktopContext { @@ -35,33 +46,148 @@ impl DesktopContext { /// onmousedown: move |_| { desktop.drag_window(); } /// ``` pub fn drag(&self) { - let _ = self.proxy.send_event(UserWindowEvent::DragWindow); + let _ = self.proxy.send_event(DragWindow); } /// set window minimize state - pub fn minimize(&self, minimized: bool) { - let _ = self.proxy.send_event(UserWindowEvent::Minimize(minimized)); + pub fn set_minimized(&self, minimized: bool) { + let _ = self.proxy.send_event(Minimize(minimized)); } /// set window maximize state - pub fn maximize(&self, maximized: bool) { - let _ = self.proxy.send_event(UserWindowEvent::Maximize(maximized)); + pub fn set_maximized(&self, maximized: bool) { + let _ = self.proxy.send_event(Maximize(maximized)); + } + + /// toggle window maximize state + pub fn toggle_maximized(&self) { + let _ = self.proxy.send_event(MaximizeToggle); + } + + /// set window visible or not + pub fn set_visible(&self, visible: bool) { + let _ = self.proxy.send_event(Visible(visible)); } /// close window pub fn close(&self) { - let _ = self.proxy.send_event(UserWindowEvent::CloseWindow); + let _ = self.proxy.send_event(CloseWindow); } /// set window to focus pub fn focus(&self) { - let _ = self.proxy.send_event(UserWindowEvent::FocusWindow); + let _ = self.proxy.send_event(FocusWindow); + } + + /// change window to fullscreen + pub fn set_fullscreen(&self, fullscreen: bool) { + let _ = self.proxy.send_event(Fullscreen(fullscreen)); + } + + /// set resizable state + pub fn set_resizable(&self, resizable: bool) { + let _ = self.proxy.send_event(Resizable(resizable)); + } + + /// set the window always on top + pub fn set_always_on_top(&self, top: bool) { + let _ = self.proxy.send_event(AlwaysOnTop(top)); + } + + /// set cursor visible or not + pub fn set_cursor_visible(&self, visible: bool) { + let _ = self.proxy.send_event(CursorVisible(visible)); + } + + /// set cursor grab + pub fn set_cursor_grab(&self, grab: bool) { + let _ = self.proxy.send_event(CursorGrab(grab)); + } + + /// set window title + pub fn set_title(&self, title: &str) { + let _ = self.proxy.send_event(SetTitle(String::from(title))); + } + + /// change window to borderless + pub fn set_decorations(&self, decoration: bool) { + let _ = self.proxy.send_event(SetDecorations(decoration)); + } + + /// opens DevTool window + pub fn devtool(&self) { + let _ = self.proxy.send_event(DevTool); } } -/// use this function can get the `DesktopContext` context. -pub fn use_window(cx: &ScopeState) -> &Rc { - cx.use_hook(|_| cx.consume_context::()) - .as_ref() - .unwrap() +use wry::application::event_loop::ControlFlow; +use wry::application::window::Fullscreen as WryFullscreen; + +use crate::controller::DesktopController; + +#[derive(Debug)] +pub enum UserWindowEvent { + Update, + + CloseWindow, + DragWindow, + FocusWindow, + + Visible(bool), + Minimize(bool), + Maximize(bool), + MaximizeToggle, + Resizable(bool), + AlwaysOnTop(bool), + Fullscreen(bool), + + CursorVisible(bool), + CursorGrab(bool), + + SetTitle(String), + SetDecorations(bool), + + DevTool, +} + +pub(super) fn handler( + user_event: UserWindowEvent, + desktop: &mut DesktopController, + control_flow: &mut ControlFlow, +) { + // currently dioxus-desktop supports a single window only, + // so we can grab the only webview from the map; + let webview = desktop.webviews.values().next().unwrap(); + let window = webview.window(); + + match user_event { + Update => desktop.try_load_ready_webviews(), + CloseWindow => *control_flow = ControlFlow::Exit, + DragWindow => { + // if the drag_window has any errors, we don't do anything + window.fullscreen().is_none().then(|| window.drag_window()); + } + Visible(state) => window.set_visible(state), + Minimize(state) => window.set_minimized(state), + Maximize(state) => window.set_maximized(state), + MaximizeToggle => window.set_maximized(!window.is_maximized()), + Fullscreen(state) => { + if let Some(handle) = window.current_monitor() { + window.set_fullscreen(state.then(|| WryFullscreen::Borderless(Some(handle)))); + } + } + FocusWindow => window.set_focus(), + Resizable(state) => window.set_resizable(state), + AlwaysOnTop(state) => window.set_always_on_top(state), + + CursorVisible(state) => window.set_cursor_visible(state), + CursorGrab(state) => { + let _ = window.set_cursor_grab(state); + } + + SetTitle(content) => window.set_title(&content), + SetDecorations(state) => window.set_decorations(state), + + DevTool => webview.devtool(), + } } diff --git a/packages/desktop/src/events.rs b/packages/desktop/src/events.rs index 760bf7662..44126dd63 100644 --- a/packages/desktop/src/events.rs +++ b/packages/desktop/src/events.rs @@ -1,5 +1,4 @@ -//! Convert a serialized event to an event Trigger -//! +//! Convert a serialized event to an event trigger use std::any::Any; use std::sync::Arc; @@ -7,27 +6,49 @@ use std::sync::Arc; use dioxus_core::{ElementId, EventPriority, UserEvent}; use dioxus_html::on::*; +#[derive(serde::Serialize, serde::Deserialize)] +pub(crate) struct IpcMessage { + method: String, + params: serde_json::Value, +} + +impl IpcMessage { + pub(crate) fn method(&self) -> &str { + self.method.as_str() + } + + pub(crate) fn params(self) -> serde_json::Value { + self.params + } +} + +pub(crate) fn parse_ipc_message(payload: &str) -> Option { + match serde_json::from_str(payload) { + Ok(message) => Some(message), + Err(e) => { + log::error!("could not parse IPC message, error: {}", e); + None + } + } +} + #[derive(serde::Serialize, serde::Deserialize)] struct ImEvent { event: String, mounted_dom_id: u64, - // scope: u64, contents: serde_json::Value, } pub fn trigger_from_serialized(val: serde_json::Value) -> UserEvent { - let ims: Vec = serde_json::from_value(val).unwrap(); - let ImEvent { event, mounted_dom_id, contents, - } = ims.into_iter().next().unwrap(); + } = serde_json::from_value(val).unwrap(); - // let scope_id = ScopeId(scope as usize); let mounted_dom_id = Some(ElementId(mounted_dom_id as usize)); - let name = event_name_from_typ(&event); + let name = event_name_from_type(&event); let event = make_synthetic_event(&event, contents); UserEvent { @@ -105,7 +126,7 @@ fn make_synthetic_event(name: &str, val: serde_json::Value) -> Arc &'static str { +fn event_name_from_type(typ: &str) -> &'static str { match typ { "copy" => "copy", "cut" => "cut", diff --git a/packages/desktop/src/index.html b/packages/desktop/src/index.html index 88fcba12a..292a1ae6a 100644 --- a/packages/desktop/src/index.html +++ b/packages/desktop/src/index.html @@ -1,22 +1,15 @@ - - - - - - - - - -

-
- - - - + }); + + diff --git a/packages/desktop/src/lib.rs b/packages/desktop/src/lib.rs index 9181d04dc..4b2615d54 100644 --- a/packages/desktop/src/lib.rs +++ b/packages/desktop/src/lib.rs @@ -1,81 +1,31 @@ -//! Dioxus Desktop Renderer -//! -//! Render the Dioxus VirtualDom using the platform's native WebView implementation. -//! -//! # Desktop -//! -//! One of Dioxus' killer features is the ability to quickly build a native desktop app that looks and feels the same across platforms. Apps built with Dioxus are typically <5mb in size and use existing system resources, so they won't hog extreme amounts of RAM or memory. -//! -//! Dioxus Desktop is built off Tauri. Right now there aren't any Dioxus abstractions over keyboard shortcuts, menubar, handling, etc, so you'll want to leverage Tauri - mostly [Wry](http://github.com/tauri-apps/wry/) and [Tao](http://github.com/tauri-apps/tao)) directly. The next major release of Dioxus-Desktop will include components and hooks for notifications, global shortcuts, menubar, etc. -//! -//! -//! ## Getting Set up -//! -//! Getting Set up with Dioxus-Desktop is quite easy. Make sure you have Rust and Cargo installed, and then create a new project: -//! -//! ```shell -//! $ cargo new --bin demo -//! $ cd app -//! ``` -//! -//! Add Dioxus with the `desktop` feature: -//! -//! ```shell -//! $ cargo add dioxus --features desktop -//! ``` -//! -//! Edit your `main.rs`: -//! -//! ```rust -//! // main.rs -//! use dioxus::prelude::*; -//! -//! fn main() { -//! dioxus::desktop::launch(app); -//! } -//! -//! fn app(cx: Scope) -> Element { -//! cx.render(rsx!{ -//! div { -//! "hello world!" -//! } -//! }) -//! } -//! ``` -//! -//! -//! To configure the webview, menubar, and other important desktop-specific features, checkout out some of the launch configuration in the [API reference](https://docs.rs/dioxus-desktop/). -//! -//! ## Future Steps -//! -//! Make sure to read the [Dioxus Guide](https://dioxuslabs.com/guide) if you already haven't! +#![doc = include_str!("readme.md")] +#![doc(html_logo_url = "https://avatars.githubusercontent.com/u/79236386")] +#![doc(html_favicon_url = "https://avatars.githubusercontent.com/u/79236386")] +#![deny(missing_docs)] -pub mod cfg; -pub mod desktop_context; -pub mod escape; -pub mod events; +mod cfg; +mod controller; +mod desktop_context; +mod escape; +mod events; +mod protocol; +use desktop_context::UserWindowEvent; +pub use desktop_context::{use_window, DesktopContext}; +pub use wry; +pub use wry::application as tao; + +use crate::events::trigger_from_serialized; use cfg::DesktopConfig; -pub use desktop_context::use_window; -use desktop_context::DesktopContext; +use controller::DesktopController; use dioxus_core::*; -use std::{ - collections::{HashMap, VecDeque}, - sync::atomic::AtomicBool, - sync::{Arc, RwLock}, -}; +use events::parse_ipc_message; use tao::{ event::{Event, StartCause, WindowEvent}, event_loop::{ControlFlow, EventLoop}, - window::{Window, WindowId}, -}; -pub use wry; -pub use wry::application as tao; -use wry::{ - application::event_loop::EventLoopProxy, - webview::RpcRequest, - webview::{WebView, WebViewBuilder}, + window::Window, }; +use wry::webview::WebViewBuilder; /// Launch the WebView and run the event loop. /// @@ -152,7 +102,7 @@ pub fn launch_with_props( props: P, builder: impl FnOnce(&mut DesktopConfig) -> &mut DesktopConfig, ) { - let mut cfg = DesktopConfig::default(); + let mut cfg = DesktopConfig::default().with_default_icon(); builder(&mut cfg); let event_loop = EventLoop::with_user_event(); @@ -173,29 +123,32 @@ pub fn launch_with_props( let (is_ready, sender) = (desktop.is_ready.clone(), desktop.sender.clone()); let proxy = proxy.clone(); + let file_handler = cfg.file_drop_handler.take(); + let resource_dir = cfg.resource_dir.clone(); + let mut webview = WebViewBuilder::new(window) .unwrap() + .with_transparent(cfg.window.window.transparent) .with_url("dioxus://index.html/") .unwrap() - .with_rpc_handler(move |_window: &Window, req: RpcRequest| { - match req.method.as_str() { - "user_event" => { - let event = events::trigger_from_serialized(req.params.unwrap()); - log::trace!("User event: {:?}", event); - sender.unbounded_send(SchedulerMsg::Event(event)).unwrap(); - } - "initialize" => { - is_ready.store(true, std::sync::atomic::Ordering::Relaxed); - let _ = proxy.send_event(UserWindowEvent::Update); - } - "browser_open" => { - println!("browser_open"); - let data = req.params.unwrap(); - log::trace!("Open browser: {:?}", data); - if let Some(arr) = data.as_array() { - if let Some(temp) = arr[0].as_object() { + .with_ipc_handler(move |_window: &Window, payload: String| { + parse_ipc_message(&payload) + .map(|message| match message.method() { + "user_event" => { + let event = trigger_from_serialized(message.params()); + log::trace!("User event: {:?}", event); + sender.unbounded_send(SchedulerMsg::Event(event)).unwrap(); + } + "initialize" => { + is_ready.store(true, std::sync::atomic::Ordering::Relaxed); + let _ = proxy.send_event(UserWindowEvent::Update); + } + "browser_open" => { + let data = message.params(); + log::trace!("Open browser: {:?}", data); + if let Some(temp) = data.as_object() { if temp.contains_key("href") { let url = temp.get("href").unwrap().as_str().unwrap(); if let Err(e) = webbrowser::open(url) { @@ -204,54 +157,14 @@ pub fn launch_with_props( } } } - } - _ => {} - } - None + _ => (), + }) + .unwrap_or_else(|| { + log::warn!("invalid IPC message received"); + }); }) - .with_custom_protocol(String::from("dioxus"), move |request| { - // Any content that that uses the `dioxus://` scheme will be shuttled through this handler as a "special case" - // For now, we only serve two pieces of content which get included as bytes into the final binary. - let path = request.uri().replace("dioxus://", ""); - - // all assets shouldbe called from index.html - let trimmed = path.trim_start_matches("index.html/"); - - if trimmed.is_empty() { - wry::http::ResponseBuilder::new() - .mimetype("text/html") - .body(include_bytes!("./index.html").to_vec()) - } else if trimmed == "index.js" { - wry::http::ResponseBuilder::new() - .mimetype("text/javascript") - .body(dioxus_interpreter_js::INTERPRTER_JS.as_bytes().to_vec()) - } else { - // Read the file content from file path - use std::fs::read; - - let path_buf = std::path::Path::new(trimmed).canonicalize()?; - let cur_path = std::path::Path::new(".").canonicalize()?; - - if !path_buf.starts_with(cur_path) { - return wry::http::ResponseBuilder::new() - .status(wry::http::status::StatusCode::FORBIDDEN) - .body(String::from("Forbidden").into_bytes()); - } - - if !path_buf.exists() { - return wry::http::ResponseBuilder::new() - .status(wry::http::status::StatusCode::NOT_FOUND) - .body(String::from("Not Found").into_bytes()); - } - - let mime = mime_guess::from_path(&path_buf).first_or_octet_stream(); - - // do not let path searching to go two layers beyond the caller level - let data = read(path_buf)?; - let meta = format!("{}", mime); - - wry::http::ResponseBuilder::new().mimetype(&meta).body(data) - } + .with_custom_protocol(String::from("dioxus"), move |r| { + protocol::desktop_handler(r, resource_dir.clone()) }) .with_file_drop_handler(move |window, evet| { file_handler @@ -260,10 +173,32 @@ pub fn launch_with_props( .unwrap_or_default() }); - for (name, handler) in cfg.protocos.drain(..) { + for (name, handler) in cfg.protocols.drain(..) { webview = webview.with_custom_protocol(name, handler) } + if cfg.disable_context_menu { + // in release mode, we don't want to show the dev tool or reload menus + webview = webview.with_initialization_script( + r#" + if (document.addEventListener) { + document.addEventListener('contextmenu', function(e) { + alert("You've tried to open context menu"); + e.preventDefault(); + }, false); + } else { + document.attachEvent('oncontextmenu', function() { + alert("You've tried to open context menu"); + window.event.returnValue = false; + }); + } + "#, + ) + } else { + // in debug, we are okay with the reload menu showing and dev tool + webview = webview.with_dev_tool(true); + } + desktop.webviews.insert(window_id, webview.build().unwrap()); } @@ -282,46 +217,8 @@ pub fn launch_with_props( _ => {} }, - Event::UserEvent(_evt) => { - // - match _evt { - UserWindowEvent::Update => desktop.try_load_ready_webviews(), - UserWindowEvent::DragWindow => { - // this loop just run once, because dioxus-desktop is unsupport multi-window. - for webview in desktop.webviews.values() { - let window = webview.window(); - // start to drag the window. - // if the drag_window have any err. we don't do anything. - let _ = window.drag_window(); - } - } - UserWindowEvent::CloseWindow => { - // close window - *control_flow = ControlFlow::Exit; - } - UserWindowEvent::Minimize(state) => { - // this loop just run once, because dioxus-desktop is unsupport multi-window. - for webview in desktop.webviews.values() { - let window = webview.window(); - // change window minimized state. - window.set_minimized(state); - } - } - UserWindowEvent::Maximize(state) => { - // this loop just run once, because dioxus-desktop is unsupport multi-window. - for webview in desktop.webviews.values() { - let window = webview.window(); - // change window maximized state. - window.set_maximized(state); - } - } - UserWindowEvent::FocusWindow => { - for webview in desktop.webviews.values() { - let window = webview.window(); - window.set_focus(); - } - } - } + Event::UserEvent(user_event) => { + desktop_context::handler(user_event, &mut desktop, control_flow) } Event::MainEventsCleared => {} Event::Resumed => {} @@ -332,108 +229,3 @@ pub fn launch_with_props( } }) } - -pub enum UserWindowEvent { - Update, - DragWindow, - CloseWindow, - FocusWindow, - Minimize(bool), - Maximize(bool), -} - -pub struct DesktopController { - pub proxy: EventLoopProxy, - pub webviews: HashMap, - pub sender: futures_channel::mpsc::UnboundedSender, - pub pending_edits: Arc>>, - pub quit_app_on_close: bool, - pub is_ready: Arc, -} - -impl DesktopController { - // Launch the virtualdom on its own thread managed by tokio - // returns the desktop state - pub fn new_on_tokio( - root: Component

, - props: P, - evt: EventLoopProxy, - ) -> Self { - let edit_queue = Arc::new(RwLock::new(VecDeque::new())); - let pending_edits = edit_queue.clone(); - - let (sender, receiver) = futures_channel::mpsc::unbounded::(); - let return_sender = sender.clone(); - let proxy = evt.clone(); - - let desktop_context_proxy = proxy.clone(); - std::thread::spawn(move || { - // We create the runtime as multithreaded, so you can still "spawn" onto multiple threads - let runtime = tokio::runtime::Builder::new_multi_thread() - .enable_all() - .build() - .unwrap(); - - runtime.block_on(async move { - let mut dom = - VirtualDom::new_with_props_and_scheduler(root, props, (sender, receiver)); - - let window_context = DesktopContext::new(desktop_context_proxy); - - dom.base_scope().provide_context(window_context); - - let edits = dom.rebuild(); - - edit_queue - .write() - .unwrap() - .push_front(serde_json::to_string(&edits.edits).unwrap()); - - loop { - dom.wait_for_work().await; - let mut muts = dom.work_with_deadline(|| false); - - while let Some(edit) = muts.pop() { - edit_queue - .write() - .unwrap() - .push_front(serde_json::to_string(&edit.edits).unwrap()); - } - - let _ = evt.send_event(UserWindowEvent::Update); - } - }) - }); - - Self { - pending_edits, - sender: return_sender, - proxy, - webviews: HashMap::new(), - is_ready: Arc::new(AtomicBool::new(false)), - quit_app_on_close: true, - } - } - - pub fn close_window(&mut self, window_id: WindowId, control_flow: &mut ControlFlow) { - self.webviews.remove(&window_id); - - if self.webviews.is_empty() && self.quit_app_on_close { - *control_flow = ControlFlow::Exit; - } - } - - pub fn try_load_ready_webviews(&mut self) { - if self.is_ready.load(std::sync::atomic::Ordering::Relaxed) { - let mut queue = self.pending_edits.write().unwrap(); - let (_id, view) = self.webviews.iter_mut().next().unwrap(); - - while let Some(edit) = queue.pop_back() { - view.evaluate_script(&format!("window.interpreter.handleEdits({})", edit)) - .unwrap(); - } - } else { - println!("waiting for ready"); - } - } -} diff --git a/packages/desktop/src/protocol.rs b/packages/desktop/src/protocol.rs new file mode 100644 index 000000000..bd8bb3d84 --- /dev/null +++ b/packages/desktop/src/protocol.rs @@ -0,0 +1,83 @@ +use std::path::{Path, PathBuf}; +use wry::{ + http::{status::StatusCode, Request, Response, ResponseBuilder}, + Result, +}; + +pub(super) fn desktop_handler(request: &Request, asset_root: Option) -> Result { + // Any content that uses the `dioxus://` scheme will be shuttled through this handler as a "special case". + // For now, we only serve two pieces of content which get included as bytes into the final binary. + let path = request.uri().replace("dioxus://", ""); + + // all assets should be called from index.html + let trimmed = path.trim_start_matches("index.html/"); + + if trimmed.is_empty() { + ResponseBuilder::new() + .mimetype("text/html") + .body(include_bytes!("./index.html").to_vec()) + } else if trimmed == "index.js" { + ResponseBuilder::new() + .mimetype("text/javascript") + .body(dioxus_interpreter_js::INTERPRETER_JS.as_bytes().to_vec()) + } else { + let asset_root = asset_root + .unwrap_or_else(|| get_asset_root().unwrap_or_else(|| Path::new(".").to_path_buf())) + .canonicalize()?; + + let asset = asset_root.join(trimmed).canonicalize()?; + + if !asset.starts_with(asset_root) { + return ResponseBuilder::new() + .status(StatusCode::FORBIDDEN) + .body(String::from("Forbidden").into_bytes()); + } + + if !asset.exists() { + return ResponseBuilder::new() + .status(StatusCode::NOT_FOUND) + .body(String::from("Not Found").into_bytes()); + } + + let mime = mime_guess::from_path(&asset).first_or_octet_stream(); + + // do not let path searching to go two layers beyond the caller level + let data = std::fs::read(asset)?; + let meta = format!("{}", mime); + + ResponseBuilder::new().mimetype(&meta).body(data) + } +} + +#[allow(unreachable_code)] +fn get_asset_root() -> Option { + /* + We're matching exactly how cargo-bundle works. + + - [x] macOS + - [ ] Windows + - [ ] Linux (rpm) + - [ ] Linux (deb) + - [ ] iOS + - [ ] Android + + */ + + if std::env::var_os("CARGO").is_some() { + return None; + } + + // TODO: support for other platforms + #[cfg(target_os = "macos")] + { + let bundle = core_foundation::bundle::CFBundle::main_bundle(); + let bundle_path = dbg!(bundle.path()?); + let resources_path = dbg!(bundle.resources_path()?); + let absolute_resources_root = dbg!(bundle_path.join(resources_path)); + let canonical_resources_root = dbg!(dunce::canonicalize(absolute_resources_root).ok()?); + + return Some(canonical_resources_root); + } + + None +} diff --git a/packages/desktop/src/readme.md b/packages/desktop/src/readme.md new file mode 100644 index 000000000..dc034fe67 --- /dev/null +++ b/packages/desktop/src/readme.md @@ -0,0 +1,51 @@ +Dioxus Desktop Renderer + +Render the Dioxus VirtualDom using the platform's native WebView implementation. + +# Desktop + +One of Dioxus' killer features is the ability to quickly build a native desktop app that looks and feels the same across platforms. Apps built with Dioxus are typically <5mb in size and use existing system resources, so they won't hog extreme amounts of RAM or memory. + +Dioxus Desktop is built off Tauri. Right now there aren't any Dioxus abstractions over keyboard shortcuts, menubar, handling, etc, so you'll want to leverage Tauri - mostly [Wry](http://github.com/tauri-apps/wry/) and [Tao](http://github.com/tauri-apps/tao)) directly. The next major release of Dioxus-Desktop will include components and hooks for notifications, global shortcuts, menubar, etc. + + +## Getting Set up + +Getting Set up with Dioxus-Desktop is quite easy. Make sure you have Rust and Cargo installed, and then create a new project: + +```shell +$ cargo new --bin demo +$ cd app +``` + +Add Dioxus with the `desktop` feature: + +```shell +$ cargo add dioxus --features desktop +``` + +Edit your `main.rs`: + +```rust +// main.rs +use dioxus::prelude::*; + +fn main() { + dioxus::desktop::launch(app); +} + +fn app(cx: Scope) -> Element { + cx.render(rsx!{ + div { + "hello world!" + } + }) +} +``` + + +To configure the webview, menubar, and other important desktop-specific features, checkout out some of the launch configuration in the [API reference](https://docs.rs/dioxus-desktop/). + +## Future Steps + +Make sure to read the [Dioxus Guide](https://dioxuslabs.com/guide) if you already haven't! \ No newline at end of file diff --git a/packages/fermi/Cargo.toml b/packages/fermi/Cargo.toml new file mode 100644 index 000000000..48fe377c7 --- /dev/null +++ b/packages/fermi/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "fermi" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +dioxus-core = { path = "../core" } +im-rc = { version = "15.0.0", features = ["serde"] } +log = "0.4.14" + +[dev-dependencies] +closure = "0.3.0" diff --git a/packages/fermi/README.md b/packages/fermi/README.md new file mode 100644 index 000000000..0923aa6f6 --- /dev/null +++ b/packages/fermi/README.md @@ -0,0 +1,92 @@ + +

+

Fermi ⚛

+

+ Atom-based global state management solution for Dioxus +

+
+ + +
+ + + Crates.io version + + + + Download + + + + docs.rs docs + + + + CI status + +
+ +----- + +Fermi is a global state management solution for Dioxus that's as easy as `use_state`. + +Inspired by atom-based state management solutions, all state in Fermi starts as an `atom`: + +```rust +static NAME: Atom<&str> = |_| "Dioxus"; +``` + +From anywhere in our app, we can read our the value of our atom: + +```rust +fn NameCard(cx: Scope) -> Element { + let name = use_read(&cx, NAME); + cx.render(rsx!{ h1 { "Hello, {name}"} }) +} +``` + +We can also set the value of our atom, also from anywhere in our app: + +```rust +fn NameCard(cx: Scope) -> Element { + let set_name = use_set(&cx, NAME); + cx.render(rsx!{ + button { + onclick: move |_| set_name("Fermi"), + "Set name to fermi" + } + }) +} +``` + +It's that simple! + +## Installation +Fermi is currently under construction, so you have to use the `master` branch to get started. + +```rust +[depdencies] +fermi = { git = "https://github.com/dioxuslabs/fermi" } +``` + + +## Running examples + +The examples here use Dioxus Desktop to showcase their functionality. To run an example, use +``` +$ cargo run --example EXAMPLE +``` + +## Features + +Broadly our feature set to required to be released includes: +- [x] Support for Atoms +- [x] Support for AtomRef (for values that aren't clone) +- [ ] Support for Atom Families +- [ ] Support for memoized Selectors +- [ ] Support for memoized SelectorFamilies +- [ ] Support for UseFermiCallback for access to fermi from async diff --git a/packages/fermi/src/atoms/atom.rs b/packages/fermi/src/atoms/atom.rs new file mode 100644 index 000000000..2b99174b5 --- /dev/null +++ b/packages/fermi/src/atoms/atom.rs @@ -0,0 +1,28 @@ +use crate::{AtomId, AtomRoot, Readable, Writable}; + +pub type Atom = fn(AtomBuilder) -> T; +pub struct AtomBuilder; + +impl Readable for Atom { + fn read(&self, _root: AtomRoot) -> Option { + todo!() + } + fn init(&self) -> V { + (*self)(AtomBuilder) + } + fn unique_id(&self) -> AtomId { + *self as *const () + } +} + +impl Writable for Atom { + fn write(&self, _root: AtomRoot, _value: V) { + todo!() + } +} + +#[test] +fn atom_compiles() { + static TEST_ATOM: Atom<&str> = |_| "hello"; + dbg!(TEST_ATOM.init()); +} diff --git a/packages/fermi/src/atoms/atomfamily.rs b/packages/fermi/src/atoms/atomfamily.rs new file mode 100644 index 000000000..60fc22bcb --- /dev/null +++ b/packages/fermi/src/atoms/atomfamily.rs @@ -0,0 +1,25 @@ +use crate::{AtomId, AtomRoot, Readable, Writable}; +use im_rc::HashMap as ImMap; + +pub struct AtomFamilyBuilder; +pub type AtomFamily = fn(AtomFamilyBuilder) -> ImMap; + +impl Readable> for AtomFamily { + fn read(&self, _root: AtomRoot) -> Option> { + todo!() + } + + fn init(&self) -> ImMap { + (*self)(AtomFamilyBuilder) + } + + fn unique_id(&self) -> AtomId { + *self as *const () + } +} + +impl Writable> for AtomFamily { + fn write(&self, _root: AtomRoot, _value: ImMap) { + todo!() + } +} diff --git a/packages/fermi/src/atoms/atomref.rs b/packages/fermi/src/atoms/atomref.rs new file mode 100644 index 000000000..59e412031 --- /dev/null +++ b/packages/fermi/src/atoms/atomref.rs @@ -0,0 +1,25 @@ +use crate::{AtomId, AtomRoot, Readable}; +use std::cell::RefCell; + +pub struct AtomRefBuilder; +pub type AtomRef = fn(AtomRefBuilder) -> T; + +impl Readable> for AtomRef { + fn read(&self, _root: AtomRoot) -> Option> { + todo!() + } + + fn init(&self) -> RefCell { + RefCell::new((*self)(AtomRefBuilder)) + } + + fn unique_id(&self) -> AtomId { + *self as *const () + } +} + +#[test] +fn atom_compiles() { + static TEST_ATOM: AtomRef> = |_| vec![]; + dbg!(TEST_ATOM.init()); +} diff --git a/packages/fermi/src/atoms/selector.rs b/packages/fermi/src/atoms/selector.rs new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/packages/fermi/src/atoms/selector.rs @@ -0,0 +1 @@ + diff --git a/packages/fermi/src/atoms/selectorfamily.rs b/packages/fermi/src/atoms/selectorfamily.rs new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/packages/fermi/src/atoms/selectorfamily.rs @@ -0,0 +1 @@ + diff --git a/packages/fermi/src/callback.rs b/packages/fermi/src/callback.rs new file mode 100644 index 000000000..a7ca9155f --- /dev/null +++ b/packages/fermi/src/callback.rs @@ -0,0 +1,53 @@ +#![allow(clippy::all, unused)] + +use std::rc::Rc; + +use dioxus_core::prelude::*; + +use crate::{AtomRoot, Readable, Writable}; + +#[derive(Clone)] +pub struct CallbackApi { + root: Rc, +} + +impl CallbackApi { + // get the current value of the atom + pub fn get(&self, atom: impl Readable) -> &V { + todo!() + } + + // get the current value of the atom in its RC container + pub fn get_rc(&self, atom: impl Readable) -> &Rc { + todo!() + } + + // set the current value of the atom + pub fn set(&self, atom: impl Writable, value: V) { + todo!() + } +} + +pub fn use_atom_context(cx: &ScopeState) -> &CallbackApi { + todo!() +} + +macro_rules! use_callback { + (&$cx:ident, [$($cap:ident),*], move || $body:expr) => { + move || { + $( + #[allow(unused_mut)] + let mut $cap = $cap.to_owned(); + )* + $cx.spawn($body); + } + }; +} + +#[macro_export] +macro_rules! to_owned { + ($($es:ident),+) => {$( + #[allow(unused_mut)] + let mut $es = $es.to_owned(); + )*} +} diff --git a/packages/fermi/src/hooks/atom_ref.rs b/packages/fermi/src/hooks/atom_ref.rs new file mode 100644 index 000000000..da9ad9367 --- /dev/null +++ b/packages/fermi/src/hooks/atom_ref.rs @@ -0,0 +1,62 @@ +use crate::{use_atom_root, AtomId, AtomRef, AtomRoot, Readable}; +use dioxus_core::{ScopeId, ScopeState}; +use std::{ + cell::{Ref, RefCell, RefMut}, + rc::Rc, +}; + +/// +/// +/// +/// +/// +/// +/// +/// +pub fn use_atom_ref(cx: &ScopeState, atom: AtomRef) -> &UseAtomRef { + let root = use_atom_root(cx); + + cx.use_hook(|_| { + root.initialize(atom); + UseAtomRef { + ptr: atom.unique_id(), + root: root.clone(), + scope_id: cx.scope_id(), + value: root.register(atom, cx.scope_id()), + } + }) +} + +pub struct UseAtomRef { + ptr: AtomId, + value: Rc>, + root: Rc, + scope_id: ScopeId, +} + +impl UseAtomRef { + pub fn read(&self) -> Ref { + self.value.borrow() + } + + pub fn write(&self) -> RefMut { + self.root.force_update(self.ptr); + self.value.borrow_mut() + } + + pub fn write_silent(&self) -> RefMut { + self.root.force_update(self.ptr); + self.value.borrow_mut() + } + + pub fn set(&self, new: T) { + self.root.force_update(self.ptr); + self.root.set(self.ptr, new); + } +} + +impl Drop for UseAtomRef { + fn drop(&mut self) { + self.root.unsubscribe(self.ptr, self.scope_id) + } +} diff --git a/packages/fermi/src/hooks/atom_root.rs b/packages/fermi/src/hooks/atom_root.rs new file mode 100644 index 000000000..d2945025b --- /dev/null +++ b/packages/fermi/src/hooks/atom_root.rs @@ -0,0 +1,11 @@ +use crate::AtomRoot; +use dioxus_core::ScopeState; +use std::rc::Rc; + +// Returns the atom root, initiaizing it at the root of the app if it does not exist. +pub fn use_atom_root(cx: &ScopeState) -> &Rc { + cx.use_hook(|_| match cx.consume_context::() { + Some(root) => root, + None => cx.provide_root_context(AtomRoot::new(cx.schedule_update_any())), + }) +} diff --git a/packages/fermi/src/hooks/init_atom_root.rs b/packages/fermi/src/hooks/init_atom_root.rs new file mode 100644 index 000000000..edb8aafb8 --- /dev/null +++ b/packages/fermi/src/hooks/init_atom_root.rs @@ -0,0 +1,11 @@ +use crate::AtomRoot; +use dioxus_core::ScopeState; +use std::rc::Rc; + +// Initializes the atom root and retuns it; +pub fn use_init_atom_root(cx: &ScopeState) -> &Rc { + cx.use_hook(|_| match cx.consume_context::() { + Some(ctx) => ctx, + None => cx.provide_context(AtomRoot::new(cx.schedule_update_any())), + }) +} diff --git a/packages/fermi/src/hooks/read.rs b/packages/fermi/src/hooks/read.rs new file mode 100644 index 000000000..b231c74d3 --- /dev/null +++ b/packages/fermi/src/hooks/read.rs @@ -0,0 +1,36 @@ +use crate::{use_atom_root, AtomId, AtomRoot, Readable}; +use dioxus_core::{ScopeId, ScopeState}; +use std::rc::Rc; + +pub fn use_read<'a, V: 'static>(cx: &'a ScopeState, f: impl Readable) -> &'a V { + use_read_rc(cx, f).as_ref() +} + +pub fn use_read_rc<'a, V: 'static>(cx: &'a ScopeState, f: impl Readable) -> &'a Rc { + let root = use_atom_root(cx); + + struct UseReadInner { + root: Rc, + id: AtomId, + scope_id: ScopeId, + value: Option>, + } + + impl Drop for UseReadInner { + fn drop(&mut self) { + self.root.unsubscribe(self.id, self.scope_id) + } + } + + let inner = cx.use_hook(|_| UseReadInner { + value: None, + root: root.clone(), + scope_id: cx.scope_id(), + id: f.unique_id(), + }); + + let value = inner.root.register(f, cx.scope_id()); + + inner.value = Some(value); + inner.value.as_ref().unwrap() +} diff --git a/packages/fermi/src/hooks/set.rs b/packages/fermi/src/hooks/set.rs new file mode 100644 index 000000000..6d77fbf8c --- /dev/null +++ b/packages/fermi/src/hooks/set.rs @@ -0,0 +1,13 @@ +use crate::{use_atom_root, Writable}; +use dioxus_core::ScopeState; +use std::rc::Rc; + +pub fn use_set<'a, T: 'static>(cx: &'a ScopeState, f: impl Writable) -> &'a Rc { + let root = use_atom_root(cx); + cx.use_hook(|_| { + let id = f.unique_id(); + let root = root.clone(); + root.initialize(f); + Rc::new(move |new| root.set(id, new)) as Rc + }) +} diff --git a/packages/fermi/src/lib.rs b/packages/fermi/src/lib.rs new file mode 100644 index 000000000..8ac4f1ccf --- /dev/null +++ b/packages/fermi/src/lib.rs @@ -0,0 +1,58 @@ +#![doc = include_str!("../README.md")] + +pub mod prelude { + pub use crate::*; +} + +mod callback; +mod root; + +pub use atoms::*; +pub use callback::*; +pub use hooks::*; +pub use root::*; + +mod atoms { + mod atom; + mod atomfamily; + mod atomref; + mod selector; + mod selectorfamily; + + pub use atom::*; + pub use atomfamily::*; + pub use atomref::*; + pub use selector::*; + pub use selectorfamily::*; +} + +pub mod hooks { + mod atom_ref; + mod atom_root; + mod init_atom_root; + mod read; + mod set; + pub use atom_ref::*; + pub use atom_root::*; + pub use init_atom_root::*; + pub use read::*; + pub use set::*; +} + +/// All Atoms are `Readable` - they support reading their value. +/// +/// This trait lets Dioxus abstract over Atoms, AtomFamilies, AtomRefs, and Selectors. +/// It is not very useful for your own code, but could be used to build new Atom primitives. +pub trait Readable { + fn read(&self, root: AtomRoot) -> Option; + fn init(&self) -> V; + fn unique_id(&self) -> AtomId; +} + +/// All Atoms are `Writable` - they support writing their value. +/// +/// This trait lets Dioxus abstract over Atoms, AtomFamilies, AtomRefs, and Selectors. +/// This trait lets Dioxus abstract over Atoms, AtomFamilies, AtomRefs, and Selectors +pub trait Writable: Readable { + fn write(&self, root: AtomRoot, value: V); +} diff --git a/packages/fermi/src/root.rs b/packages/fermi/src/root.rs new file mode 100644 index 000000000..d80b176dc --- /dev/null +++ b/packages/fermi/src/root.rs @@ -0,0 +1,103 @@ +use std::{any::Any, cell::RefCell, collections::HashMap, rc::Rc, sync::Arc}; + +use dioxus_core::ScopeId; +use im_rc::HashSet; + +use crate::Readable; + +pub type AtomId = *const (); + +pub struct AtomRoot { + pub atoms: RefCell>, + pub update_any: Arc, +} + +pub struct Slot { + pub value: Rc, + pub subscribers: HashSet, +} + +impl AtomRoot { + pub fn new(update_any: Arc) -> Self { + Self { + update_any, + atoms: RefCell::new(HashMap::new()), + } + } + + pub fn initialize(&self, f: impl Readable) { + let id = f.unique_id(); + if self.atoms.borrow().get(&id).is_none() { + self.atoms.borrow_mut().insert( + id, + Slot { + value: Rc::new(f.init()), + subscribers: HashSet::new(), + }, + ); + } + } + + pub fn register(&self, f: impl Readable, scope: ScopeId) -> Rc { + log::trace!("registering atom {:?}", f.unique_id()); + + let mut atoms = self.atoms.borrow_mut(); + + // initialize the value if it's not already initialized + if let Some(slot) = atoms.get_mut(&f.unique_id()) { + slot.subscribers.insert(scope); + slot.value.clone().downcast().unwrap() + } else { + let value = Rc::new(f.init()); + let mut subscribers = HashSet::new(); + subscribers.insert(scope); + + atoms.insert( + f.unique_id(), + Slot { + value: value.clone(), + subscribers, + }, + ); + value + } + } + + pub fn set(&self, ptr: AtomId, value: V) { + let mut atoms = self.atoms.borrow_mut(); + + if let Some(slot) = atoms.get_mut(&ptr) { + slot.value = Rc::new(value); + log::trace!("found item with subscribers {:?}", slot.subscribers); + + for scope in &slot.subscribers { + log::trace!("updating subcsriber"); + (self.update_any)(*scope); + } + } else { + log::trace!("no atoms found for {:?}", ptr); + } + } + + pub fn unsubscribe(&self, ptr: AtomId, scope: ScopeId) { + let mut atoms = self.atoms.borrow_mut(); + + if let Some(slot) = atoms.get_mut(&ptr) { + slot.subscribers.remove(&scope); + } + } + + // force update of all subscribers + 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"); + (self.update_any)(*scope); + } + } + } + + pub fn read(&self, _f: impl Readable) -> &V { + todo!() + } +} diff --git a/packages/hooks/Cargo.toml b/packages/hooks/Cargo.toml index 7d8e4d26a..e97885743 100644 --- a/packages/hooks/Cargo.toml +++ b/packages/hooks/Cargo.toml @@ -13,3 +13,10 @@ keywords = ["dom", "ui", "gui", "react", "wasm"] [dependencies] dioxus-core = { path = "../../packages/core", version = "^0.1.9" } +futures-channel = "0.3.21" +log = { version = "0.4", features = ["release_max_level_off"] } + + +[dev-dependencies] +futures-util = { version = "0.3", default-features = false } +dioxus-core = { path = "../../packages/core", version = "^0.1.9" } diff --git a/packages/hooks/src/lib.rs b/packages/hooks/src/lib.rs index cb4afd297..2824c1069 100644 --- a/packages/hooks/src/lib.rs +++ b/packages/hooks/src/lib.rs @@ -1,3 +1,6 @@ +// #![deny(missing_docs)] +//! Useful foundational hooks for Dioxus + mod usestate; pub use usestate::{use_state, UseState}; @@ -13,8 +16,8 @@ pub use usecoroutine::*; mod usefuture; pub use usefuture::*; -mod usesuspense; -pub use usesuspense::*; +mod useeffect; +pub use useeffect::*; #[macro_export] /// A helper macro for using hooks in async environements. diff --git a/packages/hooks/src/use_shared_state.rs b/packages/hooks/src/use_shared_state.rs index a05e99d7d..3672302e9 100644 --- a/packages/hooks/src/use_shared_state.rs +++ b/packages/hooks/src/use_shared_state.rs @@ -3,6 +3,7 @@ use std::{ cell::{Cell, Ref, RefCell, RefMut}, collections::HashSet, rc::Rc, + sync::Arc, }; type ProvidedState = RefCell>; @@ -10,7 +11,7 @@ type ProvidedState = RefCell>; // Tracks all the subscribers to a shared State pub struct ProvidedStateInner { value: Rc>, - notify_any: Rc, + notify_any: Arc, consumers: HashSet, } diff --git a/packages/hooks/src/usecoroutine.rs b/packages/hooks/src/usecoroutine.rs index 7faf507ed..b4b2907ff 100644 --- a/packages/hooks/src/usecoroutine.rs +++ b/packages/hooks/src/usecoroutine.rs @@ -1,122 +1,144 @@ use dioxus_core::{ScopeState, TaskId}; +pub use futures_channel::mpsc::{UnboundedReceiver, UnboundedSender}; use std::future::Future; -use std::{cell::Cell, rc::Rc}; -/* +use std::rc::Rc; - - -let g = use_coroutine(&cx, || { - // clone the items in - async move { - - } -}) - - - -*/ -pub fn use_coroutine(cx: &ScopeState, create_future: impl FnOnce() -> F) -> CoroutineHandle<'_> +/// Maintain a handle over a future that can be paused, resumed, and canceled. +/// +/// This is an upgraded form of [`use_future`] with an integrated channel system. +/// Specifically, the coroutine generated here comes with an [`UnboundedChannel`] +/// built into it - saving you the hassle of building your own. +/// +/// Addititionally, coroutines are automatically injected as shared contexts, so +/// downstream components can tap into a coroutine's channel and send messages +/// into a singular async event loop. +/// +/// This makes it effective for apps that need to interact with an event loop or +/// some asynchronous code without thinking too hard about state. +/// +/// ## Global State +/// +/// Typically, writing apps that handle concurrency properly can be difficult, +/// so the intention of this hook is to make it easy to join and poll async tasks +/// concurrently in a centralized place. You'll find that you can have much better +/// control over your app's state if you centralize your async actions, even under +/// the same concurrent context. This makes it easier to prevent undeseriable +/// states in your UI while various async tasks are already running. +/// +/// This hook is especially powerful when combined with Fermi. We can store important +/// global data in a coroutine, and then access display-level values from the rest +/// of our app through atoms. +/// +/// ## UseCallback instead +/// +/// However, you must plan out your own concurrency and synchronization. If you +/// don't care about actions in your app being synchronized, you can use [`use_callback`] +/// hook to spawn multiple tasks and run them concurrently. +/// +/// ## Example +/// +/// ```rust, ignore +/// enum Action { +/// Start, +/// Stop, +/// } +/// +/// let chat_client = use_coroutine(&cx, |rx: UnboundedReceiver| async move { +/// while let Some(action) = rx.next().await { +/// match action { +/// Action::Start => {} +/// Action::Stop => {}, +/// } +/// } +/// }); +/// +/// +/// cx.render(rsx!{ +/// button { +/// onclick: move |_| chat_client.send(Action::Start), +/// "Start Chat Service" +/// } +/// }) +/// ``` +pub fn use_coroutine(cx: &ScopeState, init: G) -> &CoroutineHandle where + M: 'static, + G: FnOnce(UnboundedReceiver) -> F, F: Future + 'static, { - let state = cx.use_hook(move |_| { - let f = create_future(); - let id = cx.push_future(f); - State { - running: Default::default(), - _id: id - // pending_fut: Default::default(), - // running_fut: Default::default(), + cx.use_hook(|_| { + let (tx, rx) = futures_channel::mpsc::unbounded(); + let task = cx.push_future(init(rx)); + cx.provide_context(CoroutineHandle { tx, task }) + }) +} + +/// Get a handle to a coroutine higher in the tree +/// +/// See the docs for [`use_coroutine`] for more details. +pub fn use_coroutine_handle(cx: &ScopeState) -> Option<&Rc>> { + cx.use_hook(|_| cx.consume_context::>()) + .as_ref() +} + +pub struct CoroutineHandle { + tx: UnboundedSender, + task: TaskId, +} + +impl CoroutineHandle { + /// Get the ID of this coroutine + #[must_use] + pub fn task_id(&self) -> TaskId { + self.task + } + + /// Send a message to the coroutine + pub fn send(&self, msg: T) { + let _ = self.tx.unbounded_send(msg); + } +} + +#[cfg(test)] +mod tests { + #![allow(unused)] + + use super::*; + use dioxus_core::exports::futures_channel::mpsc::unbounded; + use dioxus_core::prelude::*; + use futures_util::StreamExt; + + fn app(cx: Scope, name: String) -> Element { + let task = use_coroutine(&cx, |mut rx: UnboundedReceiver| async move { + while let Some(msg) = rx.next().await { + println!("got message: {}", msg); } - }); + }); - // state.pending_fut.set(Some(Box::pin(f))); + let task2 = use_coroutine(&cx, view_task); - // if let Some(fut) = state.running_fut.as_mut() { - // cx.push_future(fut); - // } + let task3 = use_coroutine(&cx, |rx| complex_task(rx, 10)); - // if let Some(fut) = state.running_fut.take() { - // state.running.set(true); - // fut.resume(); - // } + None + } - // let submit: Box = Box::new(move || { - // let g = async move { - // running.set(true); - // create_future().await; - // running.set(false); - // }; - // let p: Pin>> = Box::pin(g); - // fut_slot - // .borrow_mut() - // .replace(unsafe { std::mem::transmute(p) }); - // }); + async fn view_task(mut rx: UnboundedReceiver) { + while let Some(msg) = rx.next().await { + println!("got message: {}", msg); + } + } - // let submit = unsafe { std::mem::transmute(submit) }; - // state.submit.get_mut().replace(submit); + enum Actions { + CloseAll, + OpenAll, + } - // if state.running.get() { - // // let mut fut = state.fut.borrow_mut(); - // // cx.push_task(|| fut.as_mut().unwrap().as_mut()); - // } else { - // // make sure to drop the old future - // if let Some(fut) = state.fut.borrow_mut().take() { - // drop(fut); - // } - // } - CoroutineHandle { cx, inner: state } -} - -struct State { - running: Rc>, - _id: TaskId, - // the way this is structure, you can toggle the coroutine without re-rendering the comppnent - // this means every render *generates* the future, which is a bit of a waste - // todo: allocate pending futures in the bump allocator and then have a true promotion - // pending_fut: Cell + 'static>>>>, - // running_fut: Option + 'static>>>, - // running_fut: Rc + 'static>>>>> -} - -pub struct CoroutineHandle<'a> { - cx: &'a ScopeState, - inner: &'a State, -} - -impl Clone for CoroutineHandle<'_> { - fn clone(&self) -> Self { - CoroutineHandle { - cx: self.cx, - inner: self.inner, + async fn complex_task(mut rx: UnboundedReceiver, name: i32) { + while let Some(msg) = rx.next().await { + match msg { + Actions::CloseAll => todo!(), + Actions::OpenAll => todo!(), + } } } } -impl Copy for CoroutineHandle<'_> {} - -impl<'a> CoroutineHandle<'a> { - #[allow(clippy::needless_return)] - pub fn start(&self) { - if self.is_running() { - return; - } - - // if let Some(submit) = self.inner.pending_fut.take() { - // submit(); - // let inner = self.inner; - // self.cx.push_task(submit()); - // } - } - - pub fn is_running(&self) -> bool { - self.inner.running.get() - } - - pub fn resume(&self) { - // self.cx.push_task(fut) - } - - pub fn stop(&self) {} - - pub fn restart(&self) {} -} diff --git a/packages/hooks/src/useeffect.rs b/packages/hooks/src/useeffect.rs new file mode 100644 index 000000000..09366fc35 --- /dev/null +++ b/packages/hooks/src/useeffect.rs @@ -0,0 +1,92 @@ +use dioxus_core::{ScopeState, TaskId}; +use std::{any::Any, cell::Cell, future::Future}; + +use crate::UseFutureDep; + +/// A hook that provides a future that executes after the hooks have been applied +/// +/// 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 +/// +/// - dependencies: a tuple of references to values that are PartialEq + Clone +/// +/// ## Examples +/// +/// ```rust, ignore +/// +/// #[inline_props] +/// fn app(cx: Scope, name: &str) -> Element { +/// use_effect(&cx, (name,), |(name,)| async move { +/// set_title(name); +/// })) +/// } +/// ``` +pub fn use_effect(cx: &ScopeState, dependencies: D, future: impl FnOnce(D::Out) -> F) +where + T: 'static, + F: Future + 'static, + D: UseFutureDep, +{ + struct UseEffect { + needs_regen: bool, + task: Cell>, + dependencies: Vec>, + } + + let state = cx.use_hook(move |_| UseEffect { + needs_regen: true, + task: Cell::new(None), + dependencies: Vec::new(), + }); + + if dependencies.clone().apply(&mut state.dependencies) || state.needs_regen { + // We don't need regen anymore + state.needs_regen = false; + + // Create the new future + let fut = future(dependencies.out()); + + state.task.set(Some(cx.push_future(async move { + fut.await; + }))); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[allow(unused)] + #[test] + fn test_use_future() { + use dioxus_core::prelude::*; + + struct MyProps { + a: String, + b: i32, + c: i32, + d: i32, + e: i32, + } + + fn app(cx: Scope) -> Element { + // should only ever run once + use_effect(&cx, (), |_| async move { + // + }); + + // runs when a is changed + use_effect(&cx, (&cx.props.a,), |(a,)| async move { + // + }); + + // runs when a or b is changed + use_effect(&cx, (&cx.props.a, &cx.props.b), |(a, b)| async move { + // + }); + + None + } + } +} diff --git a/packages/hooks/src/usefuture.rs b/packages/hooks/src/usefuture.rs index 58f350124..d018d1b98 100644 --- a/packages/hooks/src/usefuture.rs +++ b/packages/hooks/src/usefuture.rs @@ -1,61 +1,108 @@ +#![allow(missing_docs)] use dioxus_core::{ScopeState, TaskId}; -use std::{cell::Cell, future::Future, rc::Rc}; +use std::{any::Any, cell::Cell, future::Future, rc::Rc, sync::Arc}; -pub fn use_future<'a, T: 'static, F: Future + 'static>( - cx: &'a ScopeState, - new_fut: impl FnOnce() -> F, -) -> &'a UseFuture { - let state = cx.use_hook(move |_| { - // - UseFuture { - update: cx.schedule_update(), - needs_regen: Cell::new(true), - slot: Rc::new(Cell::new(None)), - value: None, - task: None, - } +/// A future that resolves to a value. +/// +/// This runs the future only once - though the future may be regenerated +/// through the [`UseFuture::restart`] method. +/// +/// This is commonly used for components that cannot be rendered until some +/// asynchronous operation has completed. +/// +/// 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 +/// +/// - dependencies: a tuple of references to values that are PartialEq + Clone +pub fn use_future( + cx: &ScopeState, + dependencies: D, + future: impl FnOnce(D::Out) -> F, +) -> &UseFuture +where + T: 'static, + F: Future + 'static, + D: UseFutureDep, +{ + let state = cx.use_hook(move |_| UseFuture { + update: cx.schedule_update(), + needs_regen: Cell::new(true), + slot: Rc::new(Cell::new(None)), + value: None, + task: Cell::new(None), + dependencies: Vec::new(), }); if let Some(value) = state.slot.take() { state.value = Some(value); - state.task = None; + state.task.set(None); } - if state.needs_regen.get() { + if dependencies.clone().apply(&mut state.dependencies) || state.needs_regen.get() { // We don't need regen anymore state.needs_regen.set(false); // Create the new future - let fut = new_fut(); + let fut = future(dependencies.out()); // Clone in our cells let slot = state.slot.clone(); - let updater = state.update.clone(); + let schedule_update = state.update.clone(); - state.task = Some(cx.push_future(async move { + // Cancel the current future + if let Some(current) = state.task.take() { + cx.remove_future(current); + } + + state.task.set(Some(cx.push_future(async move { let res = fut.await; slot.set(Some(res)); - updater(); - })); + schedule_update(); + }))); } state } +pub enum FutureState<'a, T> { + Pending, + Complete(&'a T), + Regenerating(&'a T), // the old value +} + pub struct UseFuture { - update: Rc, + update: Arc, needs_regen: Cell, value: Option, slot: Rc>>, - task: Option, + task: Cell>, + dependencies: Vec>, +} + +pub enum UseFutureState<'a, T> { + Pending, + Complete(&'a T), + Reloading(&'a T), } impl UseFuture { + /// Restart the future with new dependencies. + /// + /// Will not cancel the previous future, but will ignore any values that it + /// generates. pub fn restart(&self) { self.needs_regen.set(true); (self.update)(); } + /// Forcefully cancel a future + pub fn cancel(&self, cx: &ScopeState) { + if let Some(task) = self.task.take() { + cx.remove_future(task); + } + } + // clears the value in the future slot without starting the future over pub fn clear(&self) -> Option { (self.update)(); @@ -69,7 +116,163 @@ impl UseFuture { (self.update)(); } + /// Return any value, even old values if the future has not yet resolved. + /// + /// If the future has never completed, the returned value will be `None`. pub fn value(&self) -> Option<&T> { self.value.as_ref() } + + /// Get the ID of the future in Dioxus' internal scheduler + pub fn task(&self) -> Option { + self.task.get() + } + + /// Get the current stateof the future. + pub fn state(&self) -> UseFutureState { + match (&self.task.get(), &self.value) { + // If we have a task and an existing value, we're reloading + (Some(_), Some(val)) => UseFutureState::Reloading(val), + + // no task, but value - we're done + (None, Some(val)) => UseFutureState::Complete(val), + + // no task, no value - something's wrong? return pending + (None, None) => UseFutureState::Pending, + + // Task, no value - we're still pending + (Some(_), None) => UseFutureState::Pending, + } + } +} + +pub trait UseFutureDep: Sized + Clone { + type Out; + fn out(&self) -> Self::Out; + fn apply(self, state: &mut Vec>) -> bool; +} + +impl UseFutureDep for () { + type Out = (); + fn out(&self) -> Self::Out {} + fn apply(self, _state: &mut Vec>) -> bool { + false + } +} + +pub trait Dep: 'static + PartialEq + Clone {} +impl Dep for T where T: 'static + PartialEq + Clone {} + +impl UseFutureDep for &A { + type Out = A; + fn out(&self) -> Self::Out { + (*self).clone() + } + fn apply(self, state: &mut Vec>) -> bool { + match state.get_mut(0).and_then(|f| f.downcast_mut::()) { + Some(val) => { + if *val != *self { + *val = self.clone(); + return true; + } + } + None => { + state.push(Box::new(self.clone())); + return true; + } + } + false + } +} + +macro_rules! impl_dep { + ( + $($el:ident=$name:ident,)* + ) => { + impl< $($el),* > UseFutureDep for ($(&$el,)*) + where + $( + $el: Dep + ),* + { + type Out = ($($el,)*); + + fn out(&self) -> Self::Out { + let ($($name,)*) = self; + ($((*$name).clone(),)*) + } + + #[allow(unused)] + fn apply(self, state: &mut Vec>) -> bool { + let ($($name,)*) = self; + let mut idx = 0; + let mut needs_regen = false; + + $( + match state.get_mut(idx).map(|f| f.downcast_mut::<$el>()).flatten() { + Some(val) => { + if *val != *$name { + *val = $name.clone(); + needs_regen = true; + } + } + None => { + state.push(Box::new($name.clone())); + needs_regen = true; + } + } + idx += 1; + )* + + needs_regen + } + } + }; +} + +impl_dep!(A = a,); +impl_dep!(A = a, B = b,); +impl_dep!(A = a, B = b, C = c,); +impl_dep!(A = a, B = b, C = c, D = d,); +impl_dep!(A = a, B = b, C = c, D = d, E = e,); +impl_dep!(A = a, B = b, C = c, D = d, E = e, F = f,); +impl_dep!(A = a, B = b, C = c, D = d, E = e, F = f, G = g,); +impl_dep!(A = a, B = b, C = c, D = d, E = e, F = f, G = g, H = h,); + +#[cfg(test)] +mod tests { + use super::*; + + #[allow(unused)] + #[test] + fn test_use_future() { + use dioxus_core::prelude::*; + + struct MyProps { + a: String, + b: i32, + c: i32, + d: i32, + e: i32, + } + + fn app(cx: Scope) -> Element { + // should only ever run once + let fut = use_future(&cx, (), |_| async move { + // + }); + + // runs when a is changed + let fut = use_future(&cx, (&cx.props.a,), |(a,)| async move { + // + }); + + // runs when a or b is changed + let fut = use_future(&cx, (&cx.props.a, &cx.props.b), |(a, b)| async move { + // + }); + + None + } + } } diff --git a/packages/hooks/src/useref.rs b/packages/hooks/src/useref.rs index 3ddf86e8c..6ab25cbd4 100644 --- a/packages/hooks/src/useref.rs +++ b/packages/hooks/src/useref.rs @@ -1,57 +1,228 @@ +use dioxus_core::ScopeState; use std::{ cell::{Ref, RefCell, RefMut}, rc::Rc, + sync::Arc, }; -use dioxus_core::ScopeState; - -pub fn use_ref<'a, T: 'static>(cx: &'a ScopeState, f: impl FnOnce() -> T) -> &'a UseRef { +/// `use_ref` is a key foundational hook for storing state in Dioxus. +/// +/// It is different that `use_state` in that the value stored is not "immutable". +/// Instead, UseRef is designed to store larger values that will be mutated at will. +/// +/// ## Writing Values +/// +/// Generally, `use_ref` is just a wrapper around a RefCell that tracks mutable +/// writes through the `write` method. Whenever `write` is called, the component +/// that initialized the hook will be marked as "dirty". +/// +/// ```rust +/// let val = use_ref(|| HashMap::::new()); +/// +/// // using `write` will give us a `RefMut` to the inner value, which we can call methods on +/// // This marks the component as "dirty" +/// val.write().insert(1, "hello".to_string()); +/// ``` +/// +/// You can avoid this defualt behavior with `write_silent` +/// +/// ``` +/// // with `write_silent`, the component will not be re-rendered +/// val.write_silent().insert(2, "goodbye".to_string()); +/// ``` +/// +/// ## Reading Values +/// +/// To read values out of the refcell, you can use the `read` method which will retrun a `Ref`. +/// +/// ```rust +/// let map: Ref<_> = val.read(); +/// +/// let item = map.get(&1); +/// ``` +/// +/// To get an &T out of the RefCell, you need to "reborrow" through the Ref: +/// +/// ```rust +/// let read = val.read(); +/// let map = &*read; +/// ``` +/// +/// ## Collections and iteration +/// +/// A common usecase for `use_ref` is to store a large amount of data in a component. +/// Typically this will be a collection like a HashMap or a Vec. To create new +/// elements from the collection, we can use `read()` directly in our rsx!. +/// +/// ```rust +/// rsx!{ +/// val.read().iter().map(|(k, v)| { +/// rsx!{ key: "{k}", value: "{v}" } +/// }) +/// } +/// ``` +/// +/// If you are generating elements outside of `rsx!` then you might need to call +/// "render" inside the iterator. For some cases you might need to collect into +/// a temporary Vec. +/// +/// ```rust +/// let items = val.read().iter().map(|(k, v)| { +/// cx.render(rsx!{ key: "{k}", value: "{v}" }) +/// }); +/// +/// // collect into a Vec +/// +/// let items: Vec = items.collect(); +/// ``` +/// +/// ## Use in Async +/// +/// To access values from a `UseRef` in an async context, you need to detach it +/// from the current scope's lifetime, making it a `'static` value. This is done +/// by simply calling `ToOnwed` or `Clone`. +/// +/// ```rust +/// let val = use_ref(|| HashMap::::new()); +/// +/// cx.spawn({ +/// let val = val.clone(); +/// async move { +/// some_work().await; +/// val.write().insert(1, "hello".to_string()); +/// } +/// }) +/// ``` +/// +/// If you're working with lots of values like UseState and UseRef, you can use the +/// `clone!` macro to make it easier to write the above code. +/// +/// ```rust +/// let val1 = use_ref(|| HashMap::::new()); +/// let val2 = use_ref(|| HashMap::::new()); +/// let val3 = use_ref(|| HashMap::::new()); +/// +/// cx.spawn({ +/// clone![val1, val2, val3]; +/// async move { +/// some_work().await; +/// val.write().insert(1, "hello".to_string()); +/// } +/// }) +/// ``` +pub fn use_ref<'a, T: 'static>( + cx: &'a ScopeState, + initialize_refcell: impl FnOnce() -> T, +) -> &'a UseRef { cx.use_hook(|_| UseRef { - update_callback: cx.schedule_update(), - value: Rc::new(RefCell::new(f())), + update: cx.schedule_update(), + value: Rc::new(RefCell::new(initialize_refcell())), }) } +/// A type created by the [`use_ref`] hook. See its documentation for more details. pub struct UseRef { - update_callback: Rc, + update: Arc, value: Rc>, } -impl UseRef { - pub fn read(&self) -> Ref<'_, T> { - self.value.borrow() - } - - pub fn set(&self, new: T) { - *self.value.borrow_mut() = new; - self.needs_update(); - } - - pub fn read_write(&self) -> (Ref<'_, T>, &Self) { - (self.read(), self) - } - - /// Calling "write" will force the component to re-render - pub fn write(&self) -> RefMut<'_, T> { - self.needs_update(); - self.value.borrow_mut() - } - - /// Allows the ability to write the value without forcing a re-render - pub fn write_silent(&self) -> RefMut<'_, T> { - self.value.borrow_mut() - } - - pub fn needs_update(&self) { - (self.update_callback)(); - } -} - impl Clone for UseRef { fn clone(&self) -> Self { Self { - update_callback: self.update_callback.clone(), + update: self.update.clone(), value: self.value.clone(), } } } + +impl UseRef { + /// Read the value in the RefCell into a `Ref`. If this method is called + /// while other values are still being `read` or `write`, then your app will crash. + /// + /// Be very careful when working with this method. If you can, consider using + /// the `with` and `with_mut` methods instead, choosing to render Elements + /// during the read calls. + pub fn read(&self) -> Ref<'_, T> { + self.value.borrow() + } + + /// Set the curernt value to `new_value`. This will mark the component as "dirty" + /// + /// This change will propogate immediately, so any other contexts that are + /// using this RefCell will also be affected. If called during an async context, + /// the component will not be re-rendered until the next `.await` call. + pub fn set(&self, new: T) { + *self.value.borrow_mut() = new; + self.needs_update(); + } + + /// Mutably unlock the value in the RefCell. This will mark the component as "dirty" + /// + /// Uses to `write` should be as short as possible. + /// + /// Be very careful when working with this method. If you can, consider using + /// the `with` and `with_mut` methods instead, choosing to render Elements + /// during the read and write calls. + pub fn write(&self) -> RefMut<'_, T> { + self.needs_update(); + self.value.borrow_mut() + } + + /// Mutably unlock the value in the RefCell. This will not mark the component as dirty. + /// This is useful if you want to do some work without causing the component to re-render. + /// + /// Uses to `write` should be as short as possible. + /// + /// Be very careful when working with this method. If you can, consider using + /// the `with` and `with_mut` methods instead, choosing to render Elements + pub fn write_silent(&self) -> RefMut<'_, T> { + self.value.borrow_mut() + } + + /// Take a reference to the inner value termporarily and produce a new value + /// + /// Note: You can always "reborrow" the value through the RefCell. + /// This method just does it for you automatically. + /// + /// ```rust + /// let val = use_ref(|| HashMap::::new()); + /// + /// + /// // use reborrowing + /// let inner = &*val.read(); + /// + /// // or, be safer and use `with` + /// val.with(|i| println!("{:?}", i)); + /// ``` + pub fn with(&self, immutable_callback: impl FnOnce(&T) -> O) -> O { + immutable_callback(&*self.read()) + } + + /// Take a reference to the inner value termporarily and produce a new value, + /// modifying the original in place. + /// + /// Note: You can always "reborrow" the value through the RefCell. + /// This method just does it for you automatically. + /// + /// ```rust + /// let val = use_ref(|| HashMap::::new()); + /// + /// + /// // use reborrowing + /// let inner = &mut *val.write(); + /// + /// // or, be safer and use `with` + /// val.with_mut(|i| i.insert(1, "hi")); + /// ``` + pub fn with_mut(&self, mutable_callback: impl FnOnce(&mut T) -> O) -> O { + mutable_callback(&mut *self.write()) + } + + /// Call the inner callback to mark the originator component as dirty. + /// + /// This will cause the component to be re-rendered after the current scope + /// has ended or the current async task has been yielded through await. + pub fn needs_update(&self) { + (self.update)(); + } +} diff --git a/packages/hooks/src/usestate.rs b/packages/hooks/src/usestate.rs index 7e8892be9..7dd6bfea4 100644 --- a/packages/hooks/src/usestate.rs +++ b/packages/hooks/src/usestate.rs @@ -5,6 +5,7 @@ use std::{ cell::{RefCell, RefMut}, fmt::{Debug, Display}, rc::Rc, + sync::Arc, }; /// Store state between component renders. @@ -69,7 +70,7 @@ pub fn use_state<'a, T: 'static>( pub struct UseState { pub(crate) current_val: Rc, - pub(crate) update_callback: Rc, + pub(crate) update_callback: Arc, pub(crate) setter: Rc, pub(crate) slot: Rc>>, } diff --git a/packages/html/src/events.rs b/packages/html/src/events.rs index b9bcecd4f..8067e6314 100644 --- a/packages/html/src/events.rs +++ b/packages/html/src/events.rs @@ -3,6 +3,8 @@ use dioxus_core::exports::bumpalo; use dioxus_core::*; pub mod on { + use std::collections::HashMap; + use super::*; macro_rules! event_directory { ( $( @@ -484,6 +486,7 @@ pub mod on { #[derive(Debug)] pub struct FormData { pub value: String, + pub values: HashMap, /* DOMEvent: Send + SyncTarget relatedTarget */ } diff --git a/packages/html/src/global_attributes.rs b/packages/html/src/global_attributes.rs index 151a1539b..199cd0b86 100644 --- a/packages/html/src/global_attributes.rs +++ b/packages/html/src/global_attributes.rs @@ -118,524 +118,411 @@ pub trait GlobalAttributes { // // This roughly follows the html spec style_trait_methods! { - /// Specifies the alignment of flexible container's items within the flex container. align_content: "align-content", - - /// Specifies the default alignment for items within the flex container. align_items: "align-items", - - /// Specifies the alignment for selected items within the flex container. align_self: "align-self", - - /// Specifies the keyframe_based animations. + alignment_adjust: "alignment-adjust", + alignment_baseline: "alignment-baseline", + all: "all", + alt: "alt", animation: "animation", - - /// Specifies when the animation will start. animation_delay: "animation-delay", - - /// Specifies whether the animation should play in reverse on alternate cycles or not. animation_direction: "animation-direction", - - /// Specifies the number of seconds or milliseconds an animation should take to complete one cycle animation_duration: "animation-duration", - - /// Specifies how a CSS animation should apply styles to its target before and after it is executing animation_fill_mode: "animation-fill-mode", - - /// Specifies the number of times an animation cycle should be played before stopping. animation_iteration_count: "animation-iteration-count", - - /// Specifies the name of @keyframes defined animations that should be applied to the selected element animation_name: "animation-name", - - /// Specifies whether the animation is running or paused. animation_play_state: "animation-play-state", - - /// Specifies how a CSS animation should progress over the duration of each cycle. animation_timing_function: "animation-timing-function", - - /// Specifies whether or not the "back" side of a transformed element is visible when facing the user. + azimuth: "azimuth", backface_visibility: "backface-visibility", - - /// Defines a variety of background properties within one declaration. background: "background", - - /// Specify whether the background image is fixed in the viewport or scrolls. background_attachment: "background-attachment", - - /// Specifies the painting area of the background. background_clip: "background-clip", - - /// Defines an element's background color. background_color: "background-color", - - /// Defines an element's background image. background_image: "background-image", - - /// Specifies the positioning area of the background images. background_origin: "background-origin", - - /// Defines the origin of a background image. background_position: "background-position", - - /// Specify whether/how the background image is tiled. background_repeat: "background-repeat", - - /// Specifies the size of the background images. background_size: "background-size", - - /// Sets the width, style, and color for all four sides of an element's border. + background_blend_mode: "background-blend-mode", + baseline_shift: "baseline-shift", + bleed: "bleed", + bookmark_label: "bookmark-label", + bookmark_level: "bookmark-level", + bookmark_state: "bookmark-state", border: "border", - - /// Sets the width, style, and color of the bottom border of an element. - border_bottom: "border-bottom", - - /// Sets the color of the bottom border of an element. - border_bottom_color: "border-bottom-color", - - /// Defines the shape of the bottom_left border corner of an element. - border_bottom_left_radius: "border-bottom-left-radius", - - /// Defines the shape of the bottom_right border corner of an element. - border_bottom_right_radius: "border-bottom-right-radius", - - /// Sets the style of the bottom border of an element. - border_bottom_style: "border-bottom-style", - - /// Sets the width of the bottom border of an element. - border_bottom_width: "border-bottom-width", - - /// Specifies whether table cell borders are connected or separated. - border_collapse: "border-collapse", - - /// Sets the color of the border on all the four sides of an element. border_color: "border-color", - - /// Specifies how an image is to be used in place of the border styles. - border_image: "border-image", - - /// Specifies the amount by which the border image area extends beyond the border box. - border_image_outset: "border-image-outset", - - /// Specifies whether the image_border should be repeated, rounded or stretched. - border_image_repeat: "border-image-repeat", - - /// Specifies the inward offsets of the image_border. - border_image_slice: "border-image-slice", - - /// Specifies the location of the image to be used as a border. - border_image_source: "border-image-source", - - /// Specifies the width of the image_border. - border_image_width: "border-image-width", - - /// Sets the width, style, and color of the left border of an element. - border_left: "border-left", - - /// Sets the color of the left border of an element. - border_left_color: "border-left-color", - - /// Sets the style of the left border of an element. - border_left_style: "border-left-style", - - /// Sets the width of the left border of an element. - border_left_width: "border-left-width", - - /// Defines the shape of the border corners of an element. - border_radius: "border-radius", - - /// Sets the width, style, and color of the right border of an element. - border_right: "border-right", - - /// Sets the color of the right border of an element. - border_right_color: "border-right-color", - - /// Sets the style of the right border of an element. - border_right_style: "border-right-style", - - /// Sets the width of the right border of an element. - border_right_width: "border-right-width", - - /// Sets the spacing between the borders of adjacent table cells. - border_spacing: "border-spacing", - - /// Sets the style of the border on all the four sides of an element. border_style: "border-style", - - /// Sets the width, style, and color of the top border of an element. - border_top: "border-top", - - /// Sets the color of the top border of an element. - border_top_color: "border-top-color", - - /// Defines the shape of the top_left border corner of an element. - border_top_left_radius: "border-top-left-radius", - - /// Defines the shape of the top_right border corner of an element. - border_top_right_radius: "border-top-right-radius", - - /// Sets the style of the top border of an element. - border_top_style: "border-top-style", - - /// Sets the width of the top border of an element. - border_top_width: "border-top-width", - - /// Sets the width of the border on all the four sides of an element. border_width: "border-width", - - /// Specify the location of the bottom edge of the positioned element. + border_bottom: "border-bottom", + border_bottom_color: "border-bottom-color", + border_bottom_style: "border-bottom-style", + border_bottom_width: "border-bottom-width", + border_left: "border-left", + border_left_color: "border-left-color", + border_left_style: "border-left-style", + border_left_width: "border-left-width", + border_right: "border-right", + border_right_color: "border-right-color", + border_right_style: "border-right-style", + border_right_width: "border-right-width", + border_top: "border-top", + border_top_color: "border-top-color", + border_top_style: "border-top-style", + border_top_width: "border-top-width", + border_collapse: "border-collapse", + border_image: "border-image", + border_image_outset: "border-image-outset", + border_image_repeat: "border-image-repeat", + border_image_slice: "border-image-slice", + border_image_source: "border-image-source", + border_image_width: "border-image-width", + border_radius: "border-radius", + border_bottom_left_radius: "border-bottom-left-radius", + border_bottom_right_radius: "border-bottom-right-radius", + border_top_left_radius: "border-top-left-radius", + border_top_right_radius: "border-top-right-radius", + border_spacing: "border-spacing", bottom: "bottom", - - /// Applies one or more drop_shadows to the element's box. + box_decoration_break: "box-decoration-break", box_shadow: "box-shadow", - - /// Alter the default CSS box model. box_sizing: "box-sizing", - - /// Specify the position of table's caption. + box_snap: "box-snap", + break_after: "break-after", + break_before: "break-before", + break_inside: "break-inside", + buffered_rendering: "buffered-rendering", caption_side: "caption-side", - - /// Specifies the placement of an element in relation to floating elements. clear: "clear", - - /// Defines the clipping region. + clear_side: "clear-side", clip: "clip", - - /// Specify the color of the text of an element. + clip_path: "clip-path", + clip_rule: "clip-rule", color: "color", - - /// Specifies the number of columns in a multi_column element. - column_count: "column-count", - - /// Specifies how columns will be filled. + color_adjust: "color-adjust", + color_correction: "color-correction", + color_interpolation: "color-interpolation", + color_interpolation_filters: "color-interpolation-filters", + color_profile: "color-profile", + color_rendering: "color-rendering", column_fill: "column-fill", - - /// Specifies the gap between the columns in a multi_column element. column_gap: "column-gap", - - /// Specifies a straight line, or "rule", to be drawn between each column in a multi_column element. column_rule: "column-rule", - - /// Specifies the color of the rules drawn between columns in a multi_column layout. column_rule_color: "column-rule-color", - - /// Specifies the style of the rule drawn between the columns in a multi_column layout. column_rule_style: "column-rule-style", - - /// Specifies the width of the rule drawn between the columns in a multi_column layout. column_rule_width: "column-rule-width", - - /// Specifies how many columns an element spans across in a multi_column layout. column_span: "column-span", - - /// Specifies the optimal width of the columns in a multi_column element. - column_width: "column-width", - - /// A shorthand property for setting column_width and column_count properties. columns: "columns", - - /// Inserts generated content. + column_count: "column-count", + column_width: "column-width", + contain: "contain", content: "content", - - /// Increments one or more counter values. counter_increment: "counter-increment", - - /// Creates or resets one or more counters. counter_reset: "counter-reset", - - /// Specify the type of cursor. + counter_set: "counter-set", + cue: "cue", + cue_after: "cue-after", + cue_before: "cue-before", cursor: "cursor", - - /// Define the text direction/writing direction. direction: "direction", - - /// Specifies how an element is displayed onscreen. display: "display", - - /// Show or hide borders and backgrounds of empty table cells. + display_inside: "display-inside", + display_outside: "display-outside", + display_extras: "display-extras", + display_box: "display-box", + dominant_baseline: "dominant-baseline", + elevation: "elevation", empty_cells: "empty-cells", - - /// Specifies the components of a flexible length. - flex: "flex", - - /// Specifies the initial main size of the flex item. - flex_basis: "flex-basis", - - /// Specifies the direction of the flexible items. - flex_direction: "flex-direction", - - /// A shorthand property for the flex_direction and the flex_wrap properties. - flex_flow: "flex-flow", - - /// Specifies how the flex item will grow relative to the other items inside the flex container. - flex_grow: "flex-grow", - - /// Specifies how the flex item will shrink relative to the other items inside the flex container - flex_shrink: "flex-shrink", - - /// Specifies whether the flexible items should wrap or not. - flex_wrap: "flex-wrap", - - /// Specifies whether or not a box should float. + enable_background: "enable-background", + fill: "fill", + fill_opacity: "fill-opacity", + fill_rule: "fill-rule", + filter: "filter", float: "float", - - /// Defines a variety of font properties within one declaration. + float_defer_column: "float-defer-column", + float_defer_page: "float-defer-page", + float_offset: "float-offset", + float_wrap: "float-wrap", + flow_into: "flow-into", + flow_from: "flow-from", + flex: "flex", + flex_basis: "flex-basis", + flex_grow: "flex-grow", + flex_shrink: "flex-shrink", + flex_flow: "flex-flow", + flex_direction: "flex-direction", + flex_wrap: "flex-wrap", + flood_color: "flood-color", + flood_opacity: "flood-opacity", font: "font", - - /// Defines a list of fonts for element. font_family: "font-family", - - /// Defines the font size for the text. font_size: "font-size", - - /// Preserves the readability of text when font fallback occurs. - font_size_adjust: "font-size-adjust", - - /// Selects a normal, condensed, or expanded face from a font. font_stretch: "font-stretch", - - /// Defines the font style for the text. font_style: "font-style", - - /// Specify the font variant. - font_variant: "font-variant", - - /// Specify the font weight of the text. font_weight: "font-weight", - - /// Sets gaps (gutters) between rows and columns. Shorthand for row_gap and column_gap. - gap: "gap", - - /// Specify the height of an element. + font_feature_settings: "font-feature-settings", + font_kerning: "font-kerning", + font_language_override: "font-language-override", + font_size_adjust: "font-size-adjust", + font_synthesis: "font-synthesis", + font_variant: "font-variant", + font_variant_alternates: "font-variant-alternates", + font_variant_caps: "font-variant-caps", + font_variant_east_asian: "font-variant-east-asian", + font_variant_ligatures: "font-variant-ligatures", + font_variant_numeric: "font-variant-numeric", + font_variant_position: "font-variant-position", + footnote_policy: "footnote-policy", + glyph_orientation_horizontal: "glyph-orientation-horizontal", + glyph_orientation_vertical: "glyph-orientation-vertical", + grid: "grid", + grid_auto_flow: "grid-auto-flow", + grid_auto_columns: "grid-auto-columns", + grid_auto_rows: "grid-auto-rows", + grid_template: "grid-template", + grid_template_areas: "grid-template-areas", + grid_template_columns: "grid-template-columns", + grid_template_rows: "grid-template-rows", + grid_area: "grid-area", + grid_column: "grid-column", + grid_column_start: "grid-column-start", + grid_column_end: "grid-column-end", + grid_row: "grid-row", + grid_row_start: "grid-row-start", + grid_row_end: "grid-row-end", + hanging_punctuation: "hanging-punctuation", height: "height", - - /// Specifies how flex items are aligned along the main axis of the flex container after any flexible lengths and auto margins have been resolved. + hyphenate_character: "hyphenate-character", + hyphenate_limit_chars: "hyphenate-limit-chars", + hyphenate_limit_last: "hyphenate-limit-last", + hyphenate_limit_lines: "hyphenate-limit-lines", + hyphenate_limit_zone: "hyphenate-limit-zone", + hyphens: "hyphens", + icon: "icon", + image_orientation: "image-orientation", + image_resolution: "image-resolution", + image_rendering: "image-rendering", + ime: "ime", + ime_align: "ime-align", + ime_mode: "ime-mode", + ime_offset: "ime-offset", + ime_width: "ime-width", + initial_letters: "initial-letters", + inline_box_align: "inline-box-align", + isolation: "isolation", justify_content: "justify-content", - - /// Specify the location of the left edge of the positioned element. + justify_items: "justify-items", + justify_self: "justify-self", + kerning: "kerning", left: "left", - - /// Sets the extra spacing between letters. letter_spacing: "letter-spacing", - - /// Sets the height between lines of text. + lighting_color: "lighting-color", + line_box_contain: "line-box-contain", + line_break: "line-break", + line_grid: "line-grid", line_height: "line-height", - - /// Defines the display style for a list and list elements. + line_slack: "line-slack", + line_snap: "line-snap", list_style: "list-style", - - /// Specifies the image to be used as a list_item marker. list_style_image: "list-style-image", - - /// Specifies the position of the list_item marker. list_style_position: "list-style-position", - - /// Specifies the marker style for a list_item. - list_styler_type: "list-style-type", - - /// Sets the margin on all four sides of the element. + list_style_type: "list-style-type", margin: "margin", - - /// Sets the bottom margin of the element. margin_bottom: "margin-bottom", - - /// Sets the left margin of the element. margin_left: "margin-left", - - /// Sets the right margin of the element. margin_right: "margin-right", - - /// Sets the top margin of the element. margin_top: "margin-top", - - /// Specify the maximum height of an element. + marker: "marker", + marker_end: "marker-end", + marker_mid: "marker-mid", + marker_pattern: "marker-pattern", + marker_segment: "marker-segment", + marker_start: "marker-start", + marker_knockout_left: "marker-knockout-left", + marker_knockout_right: "marker-knockout-right", + marker_side: "marker-side", + marks: "marks", + marquee_direction: "marquee-direction", + marquee_play_count: "marquee-play-count", + marquee_speed: "marquee-speed", + marquee_style: "marquee-style", + mask: "mask", + mask_image: "mask-image", + mask_repeat: "mask-repeat", + mask_position: "mask-position", + mask_clip: "mask-clip", + mask_origin: "mask-origin", + mask_size: "mask-size", + mask_box: "mask-box", + mask_box_outset: "mask-box-outset", + mask_box_repeat: "mask-box-repeat", + mask_box_slice: "mask-box-slice", + mask_box_source: "mask-box-source", + mask_box_width: "mask-box-width", + mask_type: "mask-type", max_height: "max-height", - - /// Specify the maximum width of an element. + max_lines: "max-lines", max_width: "max-width", - - /// Specify the minimum height of an element. min_height: "min-height", - - /// Specify the minimum width of an element. min_width: "min-width", - - /// Specifies the transparency of an element. + mix_blend_mode: "mix-blend-mode", + nav_down: "nav-down", + nav_index: "nav-index", + nav_left: "nav-left", + nav_right: "nav-right", + nav_up: "nav-up", + object_fit: "object-fit", + object_position: "object-position", + offset_after: "offset-after", + offset_before: "offset-before", + offset_end: "offset-end", + offset_start: "offset-start", opacity: "opacity", - - /// Specifies the order in which a flex items are displayed and laid out within a flex container. order: "order", - - /// Sets the width, style, and color for all four sides of an element's outline. + orphans: "orphans", outline: "outline", - - /// Sets the color of the outline. outline_color: "outline-color", - - /// Set the space between an outline and the border edge of an element. - outline_offset: "outline-offset", - - /// Sets a style for an outline. outline_style: "outline-style", - - /// Sets the width of the outline. outline_width: "outline-width", - - /// Specifies the treatment of content that overflows the element's box. + outline_offset: "outline-offset", overflow: "overflow", - - /// Specifies the treatment of content that overflows the element's box horizontally. overflow_x: "overflow-x", - - /// Specifies the treatment of content that overflows the element's box vertically. overflow_y: "overflow-y", - - /// Sets the padding on all four sides of the element. + overflow_style: "overflow-style", + overflow_wrap: "overflow-wrap", padding: "padding", - - /// Sets the padding to the bottom side of an element. padding_bottom: "padding-bottom", - - /// Sets the padding to the left side of an element. padding_left: "padding-left", - - /// Sets the padding to the right side of an element. padding_right: "padding-right", - - /// Sets the padding to the top side of an element. padding_top: "padding-top", - - /// Insert a page breaks after an element. + page: "page", page_break_after: "page-break-after", - - /// Insert a page breaks before an element. page_break_before: "page-break-before", - - /// Insert a page breaks inside an element. page_break_inside: "page-break-inside", - - /// Defines the perspective from which all child elements of the object are viewed. + paint_order: "paint-order", + pause: "pause", + pause_after: "pause-after", + pause_before: "pause-before", perspective: "perspective", - - /// Defines the origin (the vanishing point for the 3D space) for the perspective property. perspective_origin: "perspective-origin", - - /// Specifies how an element is positioned. - position: "position", - - /// The pointer-events CSS property sets under what circumstances (if any) a particular graphic element can - /// become the target of pointer events. - /// - /// MDN: [`pointer_events`](https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events) + pitch: "pitch", + pitch_range: "pitch-range", + play_during: "play-during", pointer_events: "pointer-events", - - /// Specifies quotation marks for embedded quotations. + position: "position", quotes: "quotes", - - /// Specifies whether or not an element is resizable by the user. + region_fragment: "region-fragment", resize: "resize", - - /// Specify the location of the right edge of the positioned element. + rest: "rest", + rest_after: "rest-after", + rest_before: "rest-before", + richness: "richness", right: "right", - - /// Specifies the gap between the rows in a multi_column element. - row_gap: "row-gap", - - /// Specifies the length of the tab character. + ruby_align: "ruby-align", + ruby_merge: "ruby-merge", + ruby_position: "ruby-position", + scroll_behavior: "scroll-behavior", + scroll_snap_coordinate: "scroll-snap-coordinate", + scroll_snap_destination: "scroll-snap-destination", + scroll_snap_points_x: "scroll-snap-points-x", + scroll_snap_points_y: "scroll-snap-points-y", + scroll_snap_type: "scroll-snap-type", + shape_image_threshold: "shape-image-threshold", + shape_inside: "shape-inside", + shape_margin: "shape-margin", + shape_outside: "shape-outside", + shape_padding: "shape-padding", + shape_rendering: "shape-rendering", + size: "size", + speak: "speak", + speak_as: "speak-as", + speak_header: "speak-header", + speak_numeral: "speak-numeral", + speak_punctuation: "speak-punctuation", + speech_rate: "speech-rate", + stop_color: "stop-color", + stop_opacity: "stop-opacity", + stress: "stress", + string_set: "string-set", + stroke: "stroke", + stroke_dasharray: "stroke-dasharray", + stroke_dashoffset: "stroke-dashoffset", + stroke_linecap: "stroke-linecap", + stroke_linejoin: "stroke-linejoin", + stroke_miterlimit: "stroke-miterlimit", + stroke_opacity: "stroke-opacity", + stroke_width: "stroke-width", tab_size: "tab-size", - - /// Specifies a table layout algorithm. table_layout: "table-layout", - - /// Sets the horizontal alignment of inline content. text_align: "text-align", - - /// Specifies how the last line of a block or a line right before a forced line break is aligned when is justify.", + text_align_all: "text-align-all", text_align_last: "text-align-last", - - /// Specifies the decoration added to text. + text_anchor: "text-anchor", + text_combine_upright: "text-combine-upright", text_decoration: "text-decoration", - - /// Specifies the color of the text_decoration_line. text_decoration_color: "text-decoration-color", - - /// Specifies what kind of line decorations are added to the element. text_decoration_line: "text-decoration-line", - - /// Specifies the style of the lines specified by the text_decoration_line property text_decoration_style: "text-decoration-style", - - /// Indent the first line of text. + text_decoration_skip: "text-decoration-skip", + text_emphasis: "text-emphasis", + text_emphasis_color: "text-emphasis-color", + text_emphasis_style: "text-emphasis-style", + text_emphasis_position: "text-emphasis-position", + text_emphasis_skip: "text-emphasis-skip", + text_height: "text-height", text_indent: "text-indent", - - /// Specifies the justification method to use when the text_align property is set to justify. text_justify: "text-justify", - - /// Specifies how the text content will be displayed, when it overflows the block containers. + text_orientation: "text-orientation", text_overflow: "text-overflow", - - /// Applies one or more shadows to the text content of an element. + text_rendering: "text-rendering", text_shadow: "text-shadow", - - /// Transforms the case of the text. + text_size_adjust: "text-size-adjust", + text_space_collapse: "text-space-collapse", + text_spacing: "text-spacing", text_transform: "text-transform", - - /// Specify the location of the top edge of the positioned element. + text_underline_position: "text-underline-position", + text_wrap: "text-wrap", top: "top", - - /// Applies a 2D or 3D transformation to an element. + touch_action: "touch-action", transform: "transform", - - /// Defines the origin of transformation for an element. + transform_box: "transform-box", transform_origin: "transform-origin", - - /// Specifies how nested elements are rendered in 3D space. transform_style: "transform-style", - - /// Defines the transition between two states of an element. transition: "transition", - - /// Specifies when the transition effect will start. transition_delay: "transition-delay", - - /// Specifies the number of seconds or milliseconds a transition effect should take to complete. transition_duration: "transition-duration", - - /// Specifies the names of the CSS properties to which a transition effect should be applied. transition_property: "transition-property", - - /// Specifies the speed curve of the transition effect. + unicode_bidi: "unicode-bidi", + vector_effect: "vector-effect", + vertical_align: "vertical-align", + visibility: "visibility", + voice_balance: "voice-balance", + voice_duration: "voice-duration", + voice_family: "voice-family", + voice_pitch: "voice-pitch", + voice_range: "voice-range", + voice_rate: "voice-rate", + voice_stress: "voice-stress", + voice_volumn: "voice-volumn", + volume: "volume", + white_space: "white-space", + widows: "widows", + width: "width", + will_change: "will-change", + word_break: "word-break", + word_spacing: "word-spacing", + word_wrap: "word-wrap", + wrap_flow: "wrap-flow", + wrap_through: "wrap-through", + writing_mode: "writing-mode", + gap: "gap", + list_styler_type: "list-style-type", + row_gap: "row-gap", transition_timing_function: "transition-timing-function", - - /// The user-select CSS property controls whether the user can select text. - /// This doesn't have any effect on content loaded as part of a browser's user interface (its chrome), except in textboxes. user_select: "user-select", webkit_user_select: "-webkit-user-select", - - /// Sets the vertical positioning of an element relative to the current text baseline. - vertical_align: "vertical-align", - - /// Specifies whether or not an element is visible. - visibility: "visibility", - - /// Specifies how white space inside the element is handled. - white_space: "white-space", - - /// Specify the width of an element. - width: "width", - - /// Specifies how to break lines within words. - word_break: "word-break", - - /// Sets the spacing between words. - word_spacing: "word-spacing", - - /// Specifies whether to break words when the content overflows the boundaries of its container. - word_wrap: "word-wrap", - - /// Specifies a layering or stacking order for positioned elements. - z_index : "z-index", - + z_index : "z-index", } aria_trait_methods! { aria_current: "aria-current", diff --git a/packages/interpreter/src/bindings.rs b/packages/interpreter/src/bindings.rs index fa96e3230..aa937728b 100644 --- a/packages/interpreter/src/bindings.rs +++ b/packages/interpreter/src/bindings.rs @@ -1,3 +1,5 @@ +#![allow(clippy::unused_unit, non_upper_case_globals)] + use js_sys::Function; use wasm_bindgen::prelude::*; use web_sys::{Element, Node}; @@ -31,7 +33,7 @@ extern "C" { pub fn Remove(this: &Interpreter, root: u64); #[wasm_bindgen(method)] - pub fn CreateTextNode(this: &Interpreter, text: &str, root: u64); + pub fn CreateTextNode(this: &Interpreter, text: JsValue, root: u64); #[wasm_bindgen(method)] pub fn CreateElement(this: &Interpreter, tag: &str, root: u64); @@ -49,11 +51,17 @@ extern "C" { pub fn RemoveEventListener(this: &Interpreter, root: u64, name: &str); #[wasm_bindgen(method)] - pub fn SetText(this: &Interpreter, root: u64, text: &str); + pub fn SetText(this: &Interpreter, root: u64, text: JsValue); #[wasm_bindgen(method)] - pub fn SetAttribute(this: &Interpreter, root: u64, field: &str, value: &str, ns: Option<&str>); + pub fn SetAttribute( + this: &Interpreter, + root: u64, + field: &str, + value: JsValue, + ns: Option<&str>, + ); #[wasm_bindgen(method)] - pub fn RemoveAttribute(this: &Interpreter, root: u64, field: &str); + pub fn RemoveAttribute(this: &Interpreter, root: u64, field: &str, ns: Option<&str>); } diff --git a/packages/interpreter/src/interpreter.js b/packages/interpreter/src/interpreter.js index dbcb73a96..fd4170351 100644 --- a/packages/interpreter/src/interpreter.js +++ b/packages/interpreter/src/interpreter.js @@ -2,16 +2,10 @@ export function main() { let root = window.document.getElementById("main"); if (root != null) { window.interpreter = new Interpreter(root); - window.rpc.call("initialize"); + window.ipc.postMessage(serializeIpcMessage("initialize")); } } export class Interpreter { - root; - stack; - listeners; - handlers; - lastNodeWasText; - nodes; constructor(root) { this.root = root; this.stack = [root]; @@ -59,14 +53,12 @@ export class Interpreter { } } CreateTextNode(text, root) { - // todo: make it so the types are okay const node = document.createTextNode(text); this.nodes[root] = node; this.stack.push(node); } CreateElement(tag, root) { const el = document.createElement(tag); - // el.setAttribute("data-dioxus-id", `${root}`); this.nodes[root] = el; this.stack.push(el); } @@ -108,15 +100,15 @@ export class Interpreter { SetAttribute(root, field, value, ns) { const name = field; const node = this.nodes[root]; - if (ns == "style") { + if (ns === "style") { // @ts-ignore node.style[name] = value; - } else if (ns != null || ns != undefined) { + } else if (ns !== null || ns !== undefined) { node.setAttributeNS(ns, name, value); } else { switch (name) { case "value": - if (value != node.value) { + if (value !== node.value) { node.value = value; } break; @@ -131,7 +123,7 @@ export class Interpreter { break; default: // https://github.com/facebook/react/blob/8b88ac2592c5f555f315f9440cbb665dd1e7457a/packages/react-dom/src/shared/DOMProperty.js#L352-L364 - if (value == "false" && bool_attrs.hasOwnProperty(name)) { + if (value === "false" && bool_attrs.hasOwnProperty(name)) { node.removeAttribute(name); } else { node.setAttribute(name, value); @@ -139,17 +131,21 @@ export class Interpreter { } } } - RemoveAttribute(root, name) { + RemoveAttribute(root, field, ns) { + const name = field; const node = this.nodes[root]; - node.removeAttribute(name); - if (name === "value") { + if (ns !== null || ns !== undefined) { + node.removeAttributeNS(ns, name); + } else if (name === "value") { node.value = ""; - } - if (name === "checked") { + } else if (name === "checked") { node.checked = false; - } - if (name === "selected") { + } else if (name === "selected") { node.selected = false; + } else if (name === "dangerous_inner_html") { + node.innerHTML = ""; + } else { + node.removeAttribute(name); } } handleEdits(edits) { @@ -204,19 +200,32 @@ export class Interpreter { `dioxus-prevent-default` ); - if (event.type == "click") { + if (event.type === "click") { // todo call prevent default if it's the right type of event if (shouldPreventDefault !== `onclick`) { - if (target.tagName == "A") { + if (target.tagName === "A") { + event.preventDefault(); const href = target.getAttribute("href"); if (href !== "" && href !== null && href !== undefined) { - window.rpc.call("browser_open", { href }); + window.ipc.postMessage( + serializeIpcMessage("browser_open", { href }) + ); } } } + + // also prevent buttons from submitting + if (target.tagName === "BUTTON") { + event.preventDefault(); + } } // walk the tree to find the real element - while (realId == null && target.parentElement != null) { + while (realId == null) { + // we've reached the root we don't want to send an event + if (target.parentElement === null) { + return; + } + target = target.parentElement; realId = target.getAttribute(`data-dioxus-id`); } @@ -224,21 +233,43 @@ export class Interpreter { shouldPreventDefault = target.getAttribute( `dioxus-prevent-default` ); + let contents = serialize_event(event); + if (shouldPreventDefault === `on${event.type}`) { - // event.preventDefault(); + event.preventDefault(); } - if (event.type == "submit") { - // event.preventDefault(); + if (event.type === "submit") { + event.preventDefault(); } - if (realId == null) { + + if (target.tagName === "FORM") { + for (let x = 0; x < target.elements.length; x++) { + let element = target.elements[x]; + let name = element.getAttribute("name"); + if (name != null) { + if (element.getAttribute("type") === "checkbox") { + // @ts-ignore + contents.values[name] = element.checked ? "true" : "false"; + } else { + // @ts-ignore + contents.values[name] = + element.value ?? element.textContent; + } + } + } + } + + if (realId === null) { return; } - window.rpc.call("user_event", { - event: edit.event_name, - mounted_dom_id: parseInt(realId), - contents: contents, - }); + window.ipc.postMessage( + serializeIpcMessage("user_event", { + event: edit.event_name, + mounted_dom_id: parseInt(realId), + contents: contents, + }) + ); } }; this.NewEventListener(edit.event_name, edit.root, handler); @@ -250,12 +281,13 @@ export class Interpreter { this.SetAttribute(edit.root, edit.field, edit.value, edit.ns); break; case "RemoveAttribute": - this.RemoveAttribute(edit.root, edit.name); + this.RemoveAttribute(edit.root, edit.name, edit.ns); break; } } } -function serialize_event(event) { + +export function serialize_event(event) { switch (event.type) { case "copy": case "cut": @@ -313,6 +345,7 @@ function serialize_event(event) { } return { value: value, + values: {}, }; } case "input": @@ -321,11 +354,12 @@ function serialize_event(event) { case "submit": { let target = event.target; let value = target.value ?? target.textContent; - if (target.type == "checkbox") { + if (target.type === "checkbox") { value = target.checked ? "true" : "false"; } return { value: value, + values: {}, }; } case "click": @@ -515,6 +549,9 @@ function serialize_event(event) { } } } +function serializeIpcMessage(method, params = {}) { + return JSON.stringify({ method, params }); +} const bool_attrs = { allowfullscreen: true, allowpaymentrequest: true, diff --git a/packages/interpreter/src/lib.rs b/packages/interpreter/src/lib.rs index ebca3cbf4..076a89197 100644 --- a/packages/interpreter/src/lib.rs +++ b/packages/interpreter/src/lib.rs @@ -1,4 +1,4 @@ -pub static INTERPRTER_JS: &str = include_str!("./interpreter.js"); +pub static INTERPRETER_JS: &str = include_str!("./interpreter.js"); #[cfg(feature = "web")] mod bindings; diff --git a/packages/router/Cargo.toml b/packages/router/Cargo.toml index 239a3c5d8..221372b50 100644 --- a/packages/router/Cargo.toml +++ b/packages/router/Cargo.toml @@ -16,8 +16,8 @@ dioxus-html = { path = "../html", version = "^0.1.6", default-features = false } dioxus-core-macro = { path = "../core-macro", version = "^0.1.7" } serde = "1" -url = "2.2.2" serde_urlencoded = "0.7" +# url = "2.2.2" # for wasm web-sys = { version = "0.3", features = [ diff --git a/packages/router/examples/simple.rs b/packages/router/examples/simple.rs index 4aebafb84..4afb122ae 100644 --- a/packages/router/examples/simple.rs +++ b/packages/router/examples/simple.rs @@ -1,8 +1,9 @@ +#![allow(non_snake_case)] + use dioxus_core::prelude::*; use dioxus_core_macro::*; use dioxus_html as dioxus_elements; use dioxus_router::*; -use serde::{Deserialize, Serialize}; fn main() { console_error_panic_hook::set_once(); @@ -25,26 +26,17 @@ static APP: Component = |cx| { fn Home(cx: Scope) -> Element { cx.render(rsx! { - div { - h1 { "Home" } - } + h1 { "Home" } }) } fn BlogList(cx: Scope) -> Element { cx.render(rsx! { - div { - - } + div { "Blog List" } }) } fn BlogPost(cx: Scope) -> Element { let id = use_route(&cx).segment::("id")?; - - cx.render(rsx! { - div { - - } - }) + cx.render(rsx! { div { "{id:?}" } }) } diff --git a/packages/router/src/components/link.rs b/packages/router/src/components/link.rs index 18e9fd92e..b2b69108f 100644 --- a/packages/router/src/components/link.rs +++ b/packages/router/src/components/link.rs @@ -34,6 +34,17 @@ pub struct LinkProps<'a> { #[props(default, strip_option)] title: Option<&'a str>, + #[props(default = true)] + autodetect: bool, + + /// Is this link an external link? + #[props(default = false)] + external: bool, + + /// New tab? + #[props(default = false)] + new_tab: bool, + children: Element<'a>, #[props(default)] @@ -41,17 +52,38 @@ pub struct LinkProps<'a> { } pub fn Link<'a>(cx: Scope<'a, LinkProps<'a>>) -> Element { - // log::trace!("render Link to {}", cx.props.to); if let Some(service) = cx.consume_context::() { + let LinkProps { + to, + href, + class, + id, + title, + autodetect, + external, + new_tab, + children, + .. + } = cx.props; + + let is_http = to.starts_with("http") || to.starts_with("https"); + let outerlink = (*autodetect && is_http) || *external; + + let prevent_default = if outerlink { "" } else { "onclick" }; + return cx.render(rsx! { a { - href: "{cx.props.to}", - class: format_args!("{}", cx.props.class.unwrap_or("")), - id: format_args!("{}", cx.props.id.unwrap_or("")), - title: format_args!("{}", cx.props.title.unwrap_or("")), - - prevent_default: "onclick", - onclick: move |_| service.push_route(cx.props.to), + href: "{to}", + class: format_args!("{}", class.unwrap_or("")), + id: format_args!("{}", id.unwrap_or("")), + title: format_args!("{}", title.unwrap_or("")), + prevent_default: "{prevent_default}", + target: format_args!("{}", if *new_tab { "_blank" } else { "" }), + onclick: move |_| { + if !outerlink { + service.push_route(to); + } + }, &cx.props.children } diff --git a/packages/router/src/components/router.rs b/packages/router/src/components/router.rs index bf23645f5..c117c6650 100644 --- a/packages/router/src/components/router.rs +++ b/packages/router/src/components/router.rs @@ -32,7 +32,5 @@ pub fn Router<'a>(cx: Scope<'a, RouterProps<'a>>) -> Element { cx.props.onchange.call(path.to_string()); } - cx.render(rsx!( - div { &cx.props.children } - )) + cx.render(rsx!(&cx.props.children)) } diff --git a/packages/router/src/hooks/use_route.rs b/packages/router/src/hooks/use_route.rs index 31a157a8f..4de6dff12 100644 --- a/packages/router/src/hooks/use_route.rs +++ b/packages/router/src/hooks/use_route.rs @@ -106,7 +106,7 @@ impl Drop for UseRouteListener { } /// This hook provides access to the `RouterService` for the app. -pub fn use_router(cx: &ScopeState) -> &RouterService { +pub fn use_router(cx: &ScopeState) -> &Rc { cx.use_hook(|_| { cx.consume_context::() .expect("Cannot call use_route outside the scope of a Router component") diff --git a/packages/router/src/service.rs b/packages/router/src/service.rs index a4ab4dc0d..ad45083ed 100644 --- a/packages/router/src/service.rs +++ b/packages/router/src/service.rs @@ -3,6 +3,7 @@ use std::{ cell::{Cell, Ref, RefCell}, collections::{HashMap, HashSet}, rc::Rc, + sync::Arc, }; use dioxus_core::ScopeId; @@ -10,7 +11,7 @@ use dioxus_core::ScopeId; use crate::platform::RouterProvider; pub struct RouterService { - pub(crate) regen_route: Rc, + pub(crate) regen_route: Arc, pub(crate) pending_events: Rc>>, slots: Rc>>, onchange_listeners: Rc>>, @@ -42,7 +43,7 @@ enum RouteSlot { } impl RouterService { - pub fn new(regen_route: Rc, root_scope: ScopeId) -> Self { + pub fn new(regen_route: Arc, root_scope: ScopeId) -> Self { let history = BrowserHistory::default(); let location = history.location(); let path = location.path(); diff --git a/packages/rsx/Cargo.toml b/packages/rsx/Cargo.toml new file mode 100644 index 000000000..0d84ba250 --- /dev/null +++ b/packages/rsx/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "dioxus-rsx" +version = "0.1.0" +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +proc-macro-error = "1" +proc-macro2 = { version = "1.0.6" } +quote = "1.0" +syn = { version = "1.0.11", features = ["full", "extra-traits"] } diff --git a/packages/rsx/src/component.rs b/packages/rsx/src/component.rs new file mode 100644 index 000000000..17006e6ac --- /dev/null +++ b/packages/rsx/src/component.rs @@ -0,0 +1,234 @@ +//! Parse components into the VComponent VNode +//! ========================================== +//! +//! This parsing path emerges from [`AmbiguousElement`] which supports validation of the vcomponent format. +//! We can be reasonably sure that whatever enters this parsing path is in the right format. +//! This feature must support +//! - [x] Namespaced components +//! - [x] Fields +//! - [x] Componentbuilder synax +//! - [x] Optional commas +//! - [ ] Children +//! - [ ] Keys +//! - [ ] Properties spreading with with `..` syntax + +use super::*; + +use proc_macro2::TokenStream as TokenStream2; +use quote::{quote, ToTokens, TokenStreamExt}; +use syn::{ + ext::IdentExt, + parse::{Parse, ParseBuffer, ParseStream}, + token, Expr, Ident, LitStr, Result, Token, +}; + +pub struct Component { + pub name: syn::Path, + pub body: Vec, + pub children: Vec, + pub manual_props: Option, +} + +impl Parse for Component { + fn parse(stream: ParseStream) -> Result { + let name = syn::Path::parse_mod_style(stream)?; + + let content: ParseBuffer; + + // if we see a `{` then we have a block + // else parse as a function-like call + if stream.peek(token::Brace) { + syn::braced!(content in stream); + } else { + syn::parenthesized!(content in stream); + } + + let mut body = Vec::new(); + let mut children = Vec::new(); + let mut manual_props = None; + + while !content.is_empty() { + // if we splat into a component then we're merging properties + if content.peek(Token![..]) { + content.parse::()?; + manual_props = Some(content.parse::()?); + } else if content.peek(Ident) && content.peek2(Token![:]) && !content.peek3(Token![:]) { + body.push(content.parse::()?); + } else { + children.push(content.parse::()?); + } + + if content.peek(Token![,]) { + let _ = content.parse::(); + } + } + + Ok(Self { + name, + body, + children, + manual_props, + }) + } +} + +impl ToTokens for Component { + fn to_tokens(&self, tokens: &mut TokenStream2) { + let name = &self.name; + + let mut has_key = None; + + let builder = match &self.manual_props { + Some(manual_props) => { + let mut toks = quote! { + let mut __manual_props = #manual_props; + }; + for field in &self.body { + if field.name == "key" { + has_key = Some(field); + } else { + let name = &field.name; + let val = &field.content; + toks.append_all(quote! { + __manual_props.#name = #val; + }); + } + } + toks.append_all(quote! { + __manual_props + }); + quote! {{ + #toks + }} + } + None => { + let mut toks = quote! { fc_to_builder(#name) }; + for field in &self.body { + match field.name.to_string().as_str() { + "key" => { + // + has_key = Some(field); + } + _ => toks.append_all(quote! {#field}), + } + } + + if !self.children.is_empty() { + let childs = &self.children; + toks.append_all(quote! { + .children(__cx.create_children([ #( #childs ),* ])) + }); + } + + toks.append_all(quote! { + .build() + }); + toks + } + }; + + let key_token = match has_key { + Some(field) => { + let inners = &field.content; + quote! { Some(format_args_f!(#inners)) } + } + None => quote! { None }, + }; + + let fn_name = self.name.segments.last().unwrap().ident.to_string(); + + tokens.append_all(quote! { + __cx.component( + #name, + #builder, + #key_token, + #fn_name + ) + }) + } +} + +// the struct's fields info +pub struct ComponentField { + name: Ident, + content: ContentField, +} + +enum ContentField { + ManExpr(Expr), + Formatted(LitStr), + OnHandlerRaw(Expr), +} + +impl ToTokens for ContentField { + fn to_tokens(&self, tokens: &mut TokenStream2) { + match self { + ContentField::ManExpr(e) => e.to_tokens(tokens), + ContentField::Formatted(s) => tokens.append_all(quote! { + __cx.raw_text(format_args_f!(#s)).0 + }), + ContentField::OnHandlerRaw(e) => tokens.append_all(quote! { + __cx.event_handler(#e) + }), + } + } +} + +impl Parse for ComponentField { + fn parse(input: ParseStream) -> Result { + let name = Ident::parse_any(input)?; + input.parse::()?; + + if name.to_string().starts_with("on") { + let content = ContentField::OnHandlerRaw(input.parse()?); + return Ok(Self { name, content }); + } + + if name == "key" { + let content = ContentField::ManExpr(input.parse()?); + return Ok(Self { name, content }); + } + + if input.peek(LitStr) && input.peek2(Token![,]) { + let t: LitStr = input.fork().parse()?; + + if is_literal_foramtted(&t) { + let content = ContentField::Formatted(input.parse()?); + return Ok(Self { name, content }); + } + } + + if input.peek(LitStr) && input.peek2(LitStr) { + let item = input.parse::().unwrap(); + proc_macro_error::emit_error!(item, "This attribute is missing a trailing comma") + } + + let content = ContentField::ManExpr(input.parse()?); + Ok(Self { name, content }) + } +} + +impl ToTokens for ComponentField { + fn to_tokens(&self, tokens: &mut TokenStream2) { + let ComponentField { name, content, .. } = self; + tokens.append_all(quote! { + .#name(#content) + }) + } +} + +fn is_literal_foramtted(lit: &LitStr) -> bool { + let s = lit.value(); + let mut chars = s.chars(); + + while let Some(next) = chars.next() { + if next == '{' { + let nen = chars.next(); + if nen != Some('{') { + return true; + } + } + } + + false +} diff --git a/packages/rsx/src/element.rs b/packages/rsx/src/element.rs new file mode 100644 index 000000000..fa8fc9f51 --- /dev/null +++ b/packages/rsx/src/element.rs @@ -0,0 +1,282 @@ +use super::*; + +use proc_macro2::TokenStream as TokenStream2; +use quote::{quote, ToTokens, TokenStreamExt}; +use syn::{ + parse::{Parse, ParseBuffer, ParseStream}, + Expr, Ident, LitStr, Result, Token, +}; + +// ======================================= +// Parse the VNode::Element type +// ======================================= +pub struct Element { + pub name: Ident, + pub key: Option, + pub attributes: Vec, + pub children: Vec, + pub _is_static: bool, +} + +impl Parse for Element { + fn parse(stream: ParseStream) -> Result { + let el_name = Ident::parse(stream)?; + + // parse the guts + let content: ParseBuffer; + syn::braced!(content in stream); + + let mut attributes: Vec = vec![]; + let mut children: Vec = vec![]; + let mut key = None; + let mut _el_ref = None; + + // parse fields with commas + // break when we don't get this pattern anymore + // start parsing bodynodes + // "def": 456, + // abc: 123, + loop { + // Parse the raw literal fields + if content.peek(LitStr) && content.peek2(Token![:]) && !content.peek3(Token![:]) { + let name = content.parse::()?; + let ident = name.clone(); + + content.parse::()?; + + if content.peek(LitStr) && content.peek2(Token![,]) { + let value = content.parse::()?; + attributes.push(ElementAttrNamed { + el_name: el_name.clone(), + attr: ElementAttr::CustomAttrText { name, value }, + }); + } else { + let value = content.parse::()?; + + attributes.push(ElementAttrNamed { + el_name: el_name.clone(), + attr: ElementAttr::CustomAttrExpression { name, value }, + }); + } + + if content.is_empty() { + break; + } + + // todo: add a message saying you need to include commas between fields + if content.parse::().is_err() { + proc_macro_error::emit_error!( + ident, + "This attribute is missing a trailing comma" + ) + } + continue; + } + + if content.peek(Ident) && content.peek2(Token![:]) && !content.peek3(Token![:]) { + let name = content.parse::()?; + let ident = name.clone(); + + let name_str = name.to_string(); + content.parse::()?; + + if name_str.starts_with("on") { + attributes.push(ElementAttrNamed { + el_name: el_name.clone(), + attr: ElementAttr::EventTokens { + name, + tokens: content.parse()?, + }, + }); + } else { + match name_str.as_str() { + "key" => { + key = Some(content.parse()?); + } + "classes" => todo!("custom class list not supported yet"), + // "namespace" => todo!("custom namespace not supported yet"), + "node_ref" => { + _el_ref = Some(content.parse::()?); + } + _ => { + if content.peek(LitStr) { + attributes.push(ElementAttrNamed { + el_name: el_name.clone(), + attr: ElementAttr::AttrText { + name, + value: content.parse()?, + }, + }); + } else { + attributes.push(ElementAttrNamed { + el_name: el_name.clone(), + attr: ElementAttr::AttrExpression { + name, + value: content.parse()?, + }, + }); + } + } + } + } + + if content.is_empty() { + break; + } + + // todo: add a message saying you need to include commas between fields + if content.parse::().is_err() { + proc_macro_error::emit_error!( + ident, + "This attribute is missing a trailing comma" + ) + } + continue; + } + + break; + } + + while !content.is_empty() { + if (content.peek(LitStr) && content.peek2(Token![:])) && !content.peek3(Token![:]) { + let ident = content.parse::().unwrap(); + let name = ident.value(); + proc_macro_error::emit_error!( + ident, "This attribute `{}` is in the wrong place.", name; + help = +"All attribute fields must be placed above children elements. + + div { + attr: \"...\", <---- attribute is above children + div { } <---- children are below attributes + }"; + ) + } + + if (content.peek(Ident) && content.peek2(Token![:])) && !content.peek3(Token![:]) { + let ident = content.parse::().unwrap(); + let name = ident.to_string(); + proc_macro_error::emit_error!( + ident, "This attribute `{}` is in the wrong place.", name; + help = +"All attribute fields must be placed above children elements. + + div { + attr: \"...\", <---- attribute is above children + div { } <---- children are below attributes + }"; + ) + } + + children.push(content.parse::()?); + // consume comma if it exists + // we don't actually care if there *are* commas after elements/text + if content.peek(Token![,]) { + let _ = content.parse::(); + } + } + + Ok(Self { + key, + name: el_name, + attributes, + children, + _is_static: false, + }) + } +} + +impl ToTokens for Element { + fn to_tokens(&self, tokens: &mut TokenStream2) { + let name = &self.name; + let children = &self.children; + + let key = match &self.key { + Some(ty) => quote! { Some(format_args_f!(#ty)) }, + None => quote! { None }, + }; + + let listeners = self + .attributes + .iter() + .filter(|f| matches!(f.attr, ElementAttr::EventTokens { .. })); + + let attr = self + .attributes + .iter() + .filter(|f| !matches!(f.attr, ElementAttr::EventTokens { .. })); + + tokens.append_all(quote! { + __cx.element( + dioxus_elements::#name, + __cx.bump().alloc([ #(#listeners),* ]), + __cx.bump().alloc([ #(#attr),* ]), + __cx.bump().alloc([ #(#children),* ]), + #key, + ) + }); + } +} + +pub enum ElementAttr { + /// attribute: "valuee {}" + AttrText { name: Ident, value: LitStr }, + + /// attribute: true, + AttrExpression { name: Ident, value: Expr }, + + /// "attribute": "value {}" + CustomAttrText { name: LitStr, value: LitStr }, + + /// "attribute": true, + CustomAttrExpression { name: LitStr, value: Expr }, + + // /// onclick: move |_| {} + // EventClosure { name: Ident, closure: ExprClosure }, + /// onclick: {} + EventTokens { name: Ident, tokens: Expr }, +} + +pub struct ElementAttrNamed { + pub el_name: Ident, + pub attr: ElementAttr, +} + +impl ToTokens for ElementAttrNamed { + fn to_tokens(&self, tokens: &mut TokenStream2) { + let ElementAttrNamed { el_name, attr } = self; + + tokens.append_all(match attr { + ElementAttr::AttrText { name, value } => { + quote! { + dioxus_elements::#el_name.#name(__cx, format_args_f!(#value)) + } + } + ElementAttr::AttrExpression { name, value } => { + quote! { + dioxus_elements::#el_name.#name(__cx, #value) + } + } + ElementAttr::CustomAttrText { name, value } => { + quote! { + __cx.attr( #name, format_args_f!(#value), None, false ) + } + } + ElementAttr::CustomAttrExpression { name, value } => { + quote! { + __cx.attr( #name, format_args_f!(#value), None, false ) + } + } + // ElementAttr::EventClosure { name, closure } => { + // quote! { + // dioxus_elements::on::#name(__cx, #closure) + // } + // } + ElementAttr::EventTokens { name, tokens } => { + quote! { + dioxus_elements::on::#name(__cx, #tokens) + } + } + }); + } +} diff --git a/packages/rsx/src/lib.rs b/packages/rsx/src/lib.rs new file mode 100644 index 000000000..858f07c5c --- /dev/null +++ b/packages/rsx/src/lib.rs @@ -0,0 +1,97 @@ +//! Parse the root tokens in the rsx!{} macro +//! ========================================= +//! +//! This parsing path emerges directly from the macro call, with `RsxRender` being the primary entrance into parsing. +//! This feature must support: +//! - [x] Optionally rendering if the `in XYZ` pattern is present +//! - [x] Fragments as top-level element (through ambiguous) +//! - [x] Components as top-level element (through ambiguous) +//! - [x] Tags as top-level elements (through ambiguous) +//! - [x] Good errors if parsing fails +//! +//! Any errors in using rsx! will likely occur when people start using it, so the first errors must be really helpful. + +mod component; +mod element; +mod node; + +pub mod pretty; + +// Re-export the namespaces into each other +pub use component::*; +pub use element::*; +pub use node::*; + +// imports +use proc_macro2::TokenStream as TokenStream2; +use quote::{quote, ToTokens, TokenStreamExt}; +use syn::{ + parse::{Parse, ParseStream}, + Ident, Result, Token, +}; + +pub struct CallBody { + pub custom_context: Option, + pub roots: Vec, +} + +impl Parse for CallBody { + fn parse(input: ParseStream) -> Result { + let custom_context = if input.peek(Ident) && input.peek2(Token![,]) { + let name = input.parse::()?; + input.parse::()?; + + Some(name) + } else { + None + }; + + let mut roots = Vec::new(); + + while !input.is_empty() { + let node = input.parse::()?; + + if input.peek(Token![,]) { + let _ = input.parse::(); + } + + roots.push(node); + } + + Ok(Self { + custom_context, + roots, + }) + } +} + +/// Serialize the same way, regardless of flavor +impl ToTokens for CallBody { + fn to_tokens(&self, out_tokens: &mut TokenStream2) { + let inner = if self.roots.len() == 1 { + let inner = &self.roots[0]; + quote! { #inner } + } else { + let childs = &self.roots; + quote! { __cx.fragment_root([ #(#childs),* ]) } + }; + + match &self.custom_context { + // The `in cx` pattern allows directly rendering + Some(ident) => out_tokens.append_all(quote! { + #ident.render(LazyNodes::new(move |__cx: NodeFactory| -> VNode { + use dioxus_elements::{GlobalAttributes, SvgAttributes}; + #inner + })) + }), + + // Otherwise we just build the LazyNode wrapper + None => out_tokens.append_all(quote! { + LazyNodes::new(move |__cx: NodeFactory| -> VNode { + use dioxus_elements::{GlobalAttributes, SvgAttributes}; + #inner + }) + }), + }; + } +} diff --git a/packages/rsx/src/node.rs b/packages/rsx/src/node.rs new file mode 100644 index 000000000..eeee421b0 --- /dev/null +++ b/packages/rsx/src/node.rs @@ -0,0 +1,86 @@ +use super::*; + +use proc_macro2::TokenStream as TokenStream2; +use quote::{quote, ToTokens, TokenStreamExt}; +use syn::{ + parse::{Parse, ParseStream}, + token, Attribute, Expr, LitStr, Result, Token, +}; + +/* +Parse +-> div {} +-> Component {} +-> component() +-> "text {with_args}" +-> (0..10).map(|f| rsx!("asd")), // <--- notice the comma - must be a complete expr +*/ +pub enum BodyNode { + Element(Element), + Component(Component), + Text(LitStr), + RawExpr(Expr), + Meta(Attribute), +} + +impl Parse for BodyNode { + fn parse(stream: ParseStream) -> Result { + if stream.peek(LitStr) { + return Ok(BodyNode::Text(stream.parse()?)); + } + + // div {} -> el + // Div {} -> comp + if stream.peek(syn::Ident) && stream.peek2(token::Brace) { + if stream + .fork() + .parse::()? + .to_string() + .chars() + .next() + .unwrap() + .is_ascii_uppercase() + { + return Ok(BodyNode::Component(stream.parse()?)); + } else { + return Ok(BodyNode::Element(stream.parse::()?)); + } + } + + // component() -> comp + // ::component {} -> comp + // ::component () -> comp + if (stream.peek(syn::Ident) && stream.peek2(token::Paren)) + || (stream.peek(Token![::])) + || (stream.peek(Token![:]) && stream.peek2(Token![:])) + { + return Ok(BodyNode::Component(stream.parse::()?)); + } + + // crate::component{} -> comp + // crate::component() -> comp + if let Ok(pat) = stream.fork().parse::() { + if pat.segments.len() > 1 { + return Ok(BodyNode::Component(stream.parse::()?)); + } + } + + Ok(BodyNode::RawExpr(stream.parse::()?)) + } +} + +impl ToTokens for BodyNode { + fn to_tokens(&self, tokens: &mut TokenStream2) { + match &self { + BodyNode::Element(el) => el.to_tokens(tokens), + BodyNode::Component(comp) => comp.to_tokens(tokens), + BodyNode::Text(txt) => tokens.append_all(quote! { + __cx.text(format_args_f!(#txt)) + }), + BodyNode::RawExpr(exp) => tokens.append_all(quote! { + __cx.fragment_from_iter(#exp) + }), + BodyNode::Meta(_) => {} + } + } +} diff --git a/packages/rsx/src/pretty.rs b/packages/rsx/src/pretty.rs new file mode 100644 index 000000000..26ad54006 --- /dev/null +++ b/packages/rsx/src/pretty.rs @@ -0,0 +1 @@ +//! pretty printer for rsx! diff --git a/packages/web/Cargo.toml b/packages/web/Cargo.toml index 9145fed8b..333838398 100644 --- a/packages/web/Cargo.toml +++ b/packages/web/Cargo.toml @@ -15,20 +15,18 @@ dioxus-core = { path = "../core", version = "^0.1.9" } dioxus-html = { path = "../html", version = "^0.1.6" } js-sys = "0.3.56" wasm-bindgen = { version = "0.2.79", features = ["enable-interning"] } -lazy_static = "1.4.0" wasm-bindgen-futures = "0.4.29" log = { version = "0.4.14", features = ["release_max_level_off"] } fxhash = "0.2.1" -wasm-logger = "0.2.0" console_error_panic_hook = { version = "0.1.7", optional = true } -wasm-bindgen-test = "0.3.29" once_cell = "1.9.0" -async-channel = "1.6.1" anyhow = "1.0.53" gloo-timers = { version = "0.2.3", features = ["futures"] } futures-util = "0.3.19" smallstr = "0.2.0" dioxus-interpreter-js = { path = "../interpreter", version = "^0.0.0", features = ["web"] } +serde-wasm-bindgen = "0.4.2" +futures-channel = "0.3.21" [dependencies.web-sys] version = "0.3.56" @@ -42,6 +40,7 @@ features = [ "HtmlInputElement", "HtmlSelectElement", "HtmlTextAreaElement", + "HtmlFormElement", "EventTarget", "HtmlCollection", "Node", @@ -78,3 +77,5 @@ panic_hook = ["console_error_panic_hook"] dioxus-core-macro = { path = "../core-macro" } wasm-bindgen-test = "0.3.29" dioxus-ssr = { path = "../ssr" } +wasm-logger = "0.2.0" + diff --git a/packages/web/examples/hydrate.rs b/packages/web/examples/hydrate.rs index c78f4036a..3097db2e7 100644 --- a/packages/web/examples/hydrate.rs +++ b/packages/web/examples/hydrate.rs @@ -1,8 +1,6 @@ -use dioxus_core as dioxus; use dioxus_core::prelude::*; use dioxus_core_macro::*; use dioxus_html as dioxus_elements; -use wasm_bindgen_test::wasm_bindgen_test; use web_sys::window; fn app(cx: Scope) -> Element { diff --git a/packages/web/src/dom.rs b/packages/web/src/dom.rs index 6ca689d28..3ecfe9913 100644 --- a/packages/web/src/dom.rs +++ b/packages/web/src/dom.rs @@ -41,7 +41,7 @@ impl WebsysDom { Some(Ok(id)) => { break Ok(UserEvent { name: event_name_from_typ(&typ), - data: virtual_event_from_websys_event(event.clone()), + data: virtual_event_from_websys_event(event.clone(), target.clone()), element: Some(ElementId(id)), scope_id: None, priority: dioxus_core::EventPriority::Medium, @@ -57,7 +57,10 @@ impl WebsysDom { } else { break Ok(UserEvent { name: event_name_from_typ(&typ), - data: virtual_event_from_websys_event(event.clone()), + data: virtual_event_from_websys_event( + event.clone(), + target.clone(), + ), element: None, scope_id: None, priority: dioxus_core::EventPriority::Low, @@ -84,7 +87,12 @@ impl WebsysDom { } }); - let root = load_document().get_element_by_id(&cfg.rootname).unwrap(); + // a match here in order to avoid some error during runtime browser test + let document = load_document(); + let root = match document.get_element_by_id(&cfg.rootname) { + Some(root) => root, + None => document.create_element("body").ok().unwrap(), + }; Self { interpreter: Interpreter::new(root.clone()), @@ -102,9 +110,7 @@ impl WebsysDom { DomEdit::InsertAfter { root, n } => self.interpreter.InsertAfter(root, n), DomEdit::InsertBefore { root, n } => self.interpreter.InsertBefore(root, n), DomEdit::Remove { root } => self.interpreter.Remove(root), - DomEdit::CreateTextNode { text, root } => { - self.interpreter.CreateTextNode(text, root) - } + DomEdit::CreateElement { tag, root } => self.interpreter.CreateElement(tag, root), DomEdit::CreateElementNs { tag, root, ns } => { self.interpreter.CreateElementNs(tag, root, ns) @@ -120,15 +126,27 @@ impl WebsysDom { DomEdit::RemoveEventListener { root, event } => { self.interpreter.RemoveEventListener(root, event) } - DomEdit::SetText { root, text } => self.interpreter.SetText(root, text), + + DomEdit::RemoveAttribute { root, name, ns } => { + self.interpreter.RemoveAttribute(root, name, ns) + } + + DomEdit::CreateTextNode { text, root } => { + let text = serde_wasm_bindgen::to_value(text).unwrap(); + self.interpreter.CreateTextNode(text, root) + } + DomEdit::SetText { root, text } => { + let text = serde_wasm_bindgen::to_value(text).unwrap(); + self.interpreter.SetText(root, text) + } DomEdit::SetAttribute { root, field, value, ns, - } => self.interpreter.SetAttribute(root, field, value, ns), - DomEdit::RemoveAttribute { root, name } => { - self.interpreter.RemoveAttribute(root, name) + } => { + let value = serde_wasm_bindgen::to_value(value).unwrap(); + self.interpreter.SetAttribute(root, field, value, ns) } } } @@ -144,7 +162,10 @@ unsafe impl Sync for DioxusWebsysEvent {} // todo: some of these events are being casted to the wrong event type. // We need tests that simulate clicks/etc and make sure every event type works. -fn virtual_event_from_websys_event(event: web_sys::Event) -> Arc { +fn virtual_event_from_websys_event( + event: web_sys::Event, + target: Element, +) -> Arc { use dioxus_html::on::*; use dioxus_html::KeyCode; @@ -177,9 +198,6 @@ fn virtual_event_from_websys_event(event: web_sys::Event) -> Arc { - let evt: &web_sys::Event = event.dyn_ref().unwrap(); - - let target: web_sys::EventTarget = evt.target().unwrap(); let value: String = (&target) .dyn_ref() .map(|input: &web_sys::HtmlInputElement| { @@ -215,7 +233,38 @@ fn virtual_event_from_websys_event(event: web_sys::Event) -> Arc() { + let elements = form.elements(); + for x in 0..elements.length() { + let element = elements.item(x).unwrap(); + if let Some(name) = element.get_attribute("name") { + let value: String = (&element) + .dyn_ref() + .map(|input: &web_sys::HtmlInputElement| { + match input.type_().as_str() { + "checkbox" => { + match input.checked() { + true => "true".to_string(), + false => "false".to_string(), + } + }, + _ => input.value() + } + }) + .or_else(|| target.dyn_ref().map(|input: &web_sys::HtmlTextAreaElement| input.value())) + .or_else(|| target.dyn_ref().map(|input: &web_sys::HtmlSelectElement| input.value())) + .or_else(|| target.dyn_ref::().unwrap().text_content()) + .expect("only an InputElement or TextAreaElement or an element with contenteditable=true can have an oninput event listener"); + + values.insert(name, value); + } + } + } + + Arc::new(FormData { value, values }) } "click" | "contextmenu" | "doubleclick" | "drag" | "dragend" | "dragenter" | "dragexit" | "dragleave" | "dragover" | "dragstart" | "drop" | "mousedown" | "mouseenter" @@ -307,6 +356,7 @@ fn virtual_event_from_websys_event(event: web_sys::Event) -> Arc Arc::new(MediaData {}), "toggle" => Arc::new(ToggleData {}), + _ => Arc::new(()), } } diff --git a/packages/web/src/lib.rs b/packages/web/src/lib.rs index cef1bc14c..c82dc4975 100644 --- a/packages/web/src/lib.rs +++ b/packages/web/src/lib.rs @@ -1,3 +1,5 @@ +#![deny(missing_docs)] + //! Dioxus WebSys //! //! ## Overview @@ -211,7 +213,7 @@ pub async fn run_with_props(root: Component, root_props: T websys_dom.apply_edits(edits.edits); } - let work_loop = ric_raf::RafLoop::new(); + let mut work_loop = ric_raf::RafLoop::new(); loop { log::trace!("waiting for work"); diff --git a/packages/web/src/ric_raf.rs b/packages/web/src/ric_raf.rs index 2ac0668b9..89819fff0 100644 --- a/packages/web/src/ric_raf.rs +++ b/packages/web/src/ric_raf.rs @@ -7,6 +7,7 @@ //! Because RIC doesn't work on Safari, we polyfill using the "ricpolyfill.js" file and use some basic detection to see //! if RIC is available. +use futures_util::StreamExt; use gloo_timers::future::TimeoutFuture; use js_sys::Function; use wasm_bindgen::{prelude::Closure, JsCast, JsValue}; @@ -14,21 +15,21 @@ use web_sys::{window, Window}; pub(crate) struct RafLoop { window: Window, - ric_receiver: async_channel::Receiver, - raf_receiver: async_channel::Receiver<()>, + ric_receiver: futures_channel::mpsc::UnboundedReceiver, + raf_receiver: futures_channel::mpsc::UnboundedReceiver<()>, ric_closure: Closure, raf_closure: Closure, } impl RafLoop { pub fn new() -> Self { - let (raf_sender, raf_receiver) = async_channel::unbounded(); + let (raf_sender, raf_receiver) = futures_channel::mpsc::unbounded(); let raf_closure: Closure = Closure::wrap(Box::new(move |_v: JsValue| { - raf_sender.try_send(()).unwrap() + raf_sender.unbounded_send(()).unwrap() })); - let (ric_sender, ric_receiver) = async_channel::unbounded(); + let (ric_sender, ric_receiver) = futures_channel::mpsc::unbounded(); let has_idle_callback = { let bo = window().unwrap().dyn_into::().unwrap(); @@ -45,7 +46,7 @@ impl RafLoop { 10 }; - ric_sender.try_send(time_remaining).unwrap() + ric_sender.unbounded_send(time_remaining).unwrap() })); // execute the polyfill for safari @@ -64,16 +65,16 @@ impl RafLoop { } } /// waits for some idle time and returns a timeout future that expires after the idle time has passed - pub async fn wait_for_idle_time(&self) -> TimeoutFuture { + pub async fn wait_for_idle_time(&mut self) -> TimeoutFuture { let ric_fn = self.ric_closure.as_ref().dyn_ref::().unwrap(); let _cb_id: u32 = self.window.request_idle_callback(ric_fn).unwrap(); - let deadline = self.ric_receiver.recv().await.unwrap(); + let deadline = self.ric_receiver.next().await.unwrap(); TimeoutFuture::new(deadline) } - pub async fn wait_for_raf(&self) { + pub async fn wait_for_raf(&mut self) { let raf_fn = self.raf_closure.as_ref().dyn_ref::().unwrap(); let _id: i32 = self.window.request_animation_frame(raf_fn).unwrap(); - self.raf_receiver.recv().await.unwrap(); + self.raf_receiver.next().await.unwrap(); } } diff --git a/packages/web/tests/hydrate.rs b/packages/web/tests/hydrate.rs index b0ecc6c51..b8a034a5b 100644 --- a/packages/web/tests/hydrate.rs +++ b/packages/web/tests/hydrate.rs @@ -1,4 +1,3 @@ -use dioxus_core as dioxus; use dioxus_core::prelude::*; use dioxus_core_macro::*; use dioxus_html as dioxus_elements; diff --git a/src/lib.rs b/src/lib.rs index d7b479a07..488b1ee9b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -340,6 +340,9 @@ pub use dioxus_web as web; #[cfg(feature = "desktop")] pub use dioxus_desktop as desktop; +#[cfg(feature = "fermi")] +pub use fermi; + // #[cfg(feature = "mobile")] // pub use dioxus_mobile as mobile; @@ -350,7 +353,7 @@ pub mod events { pub mod prelude { pub use dioxus_core::prelude::*; - pub use dioxus_core_macro::{format_args_f, inline_props, rsx, Props, Routable}; + pub use dioxus_core_macro::{format_args_f, inline_props, rsx, Props}; pub use dioxus_elements::{GlobalAttributes, SvgAttributes}; pub use dioxus_hooks::*; pub use dioxus_html as dioxus_elements; diff --git a/tests/fermi.rs b/tests/fermi.rs new file mode 100644 index 000000000..1149539f0 --- /dev/null +++ b/tests/fermi.rs @@ -0,0 +1,46 @@ +#![allow(non_snake_case)] + +use dioxus::prelude::*; +use fermi::*; + +#[test] +fn test_fermi() { + let mut app = VirtualDom::new(App); + app.rebuild(); +} + +static TITLE: Atom = |_| "".to_string(); +static USERS: AtomFamily = |_| Default::default(); + +fn App(cx: Scope) -> Element { + cx.render(rsx!( + Leaf { id: 0 } + Leaf { id: 1 } + Leaf { id: 2 } + )) +} + +#[derive(Debug, PartialEq, Props)] +struct LeafProps { + id: u32, +} + +fn Leaf(cx: Scope) -> Element { + let _user = use_read(&cx, TITLE); + let _user = use_read(&cx, USERS); + + rsx!(cx, div { + button { + onclick: move |_| {}, + "Start" + } + button { + onclick: move |_| {}, + "Stop" + } + button { + onclick: move |_| {}, + "Reverse" + } + }) +}