Merge branch 'master' into debug-signals

This commit is contained in:
Evan Almloff committed 2023-09-22 07:59:47 -05:00
commit 78860da006
434 files changed
+2673 -14238

No files matched your search

+2 -8
View File
@@ -1,6 +1,5 @@
# dioxus-autofmt
[![Crates.io][crates-badge]][crates-url]
[![MIT licensed][mit-badge]][mit-url]
[![Build Status][actions-badge]][actions-url]
@@ -8,38 +7,33 @@
[crates-badge]: https://img.shields.io/crates/v/dioxus-autofmt.svg
[crates-url]: https://crates.io/crates/dioxus-autofmt
[mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg
[mit-url]: https://github.com/dioxuslabs/dioxus/blob/master/LICENSE
[actions-badge]: https://github.com/dioxuslabs/dioxus/actions/workflows/main.yml/badge.svg
[actions-url]: https://github.com/dioxuslabs/dioxus/actions?query=workflow%3ACI+branch%3Amaster
[discord-badge]: https://img.shields.io/discord/899851952891002890.svg?logo=discord&style=flat-square
[discord-url]: https://discord.gg/XgGxMSkvUM
[Website](https://dioxuslabs.com) |
[Guides](https://dioxuslabs.com/docs/0.3/guide/en/) |
[Guides](https://dioxuslabs.com/learn/0.4/) |
[API Docs](https://docs.rs/dioxus-autofmt/latest/dioxus_autofmt) |
[Chat](https://discord.gg/XgGxMSkvUM)
## Overview
`dioxus-autofmt` provides a pretty printer for the `rsx` syntax tree.
This is done manually with a via set of formatting rules. The output is not guaranteed to be stable between minor versions of the crate as we might tweak the output.
`dioxus-autofmt` provides an API to perform precision edits as well as just spit out a block of formatted RSX from any RSX syntax tree. This is used by the `rsx-rosetta` crate which can accept various input languages and output valid RSX.
## Contributing
- Report issues on our [issue tracker](https://github.com/dioxuslabs/dioxus/issues).
- Join the discord and ask questions!
## License
This project is licensed under the [MIT license].
[mit license]: https://github.com/DioxusLabs/dioxus/blob/master/LICENSE-MIT
+9 -1
View File
@@ -17,7 +17,15 @@ struct MacroCollector<'a, 'b> {
impl<'a, 'b> Visit<'b> for MacroCollector<'a, 'b> {
fn visit_macro(&mut self, i: &'b Macro) {
self.macros.push(i);
if let Some("rsx" | "render") = i
.path
.segments
.last()
.map(|i| i.ident.to_string())
.as_deref()
{
self.macros.push(i)
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
use dioxus::prelude::*;
#[inline_props]
#[component]
pub fn Explainer<'a>(
cx: Scope<'a>,
invert: bool,
+3 -7
View File
@@ -1,6 +1,5 @@
# dioxus-check
[![Crates.io][crates-badge]][crates-url]
[![MIT licensed][mit-badge]][mit-url]
[![Build Status][actions-badge]][actions-url]
@@ -8,25 +7,21 @@
[crates-badge]: https://img.shields.io/crates/v/dioxus-autofmt.svg
[crates-url]: https://crates.io/crates/dioxus-autofmt
[mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg
[mit-url]: https://github.com/dioxuslabs/dioxus/blob/master/LICENSE
[actions-badge]: https://github.com/dioxuslabs/dioxus/actions/workflows/main.yml/badge.svg
[actions-url]: https://github.com/dioxuslabs/dioxus/actions?query=workflow%3ACI+branch%3Amaster
[discord-badge]: https://img.shields.io/discord/899851952891002890.svg?logo=discord&style=flat-square
[discord-url]: https://discord.gg/XgGxMSkvUM
[Website](https://dioxuslabs.com) |
[Guides](https://dioxuslabs.com/docs/0.3/guide/en/) |
[Guides](https://dioxuslabs.com/learn/0.4/) |
[API Docs](https://docs.rs/dioxus-autofmt/latest/dioxus_autofmt) |
[Chat](https://discord.gg/XgGxMSkvUM)
## Overview
`dioxus-check` analyzes Dioxus source code and reports errors and warnings. Primarily, it enforces the [Rules of Hooks](https://dioxuslabs.com/docs/0.3/guide/en/interactivity/hooks.html#no-hooks-in-conditionals).
`dioxus-check` analyzes Dioxus source code and reports errors and warnings. Primarily, it enforces the [Rules of Hooks](https://dioxuslabs.com/learn/0.4/reference/hooks#rules-of-hooks).
## Contributing
@@ -34,6 +29,7 @@
- Join the discord and ask questions!
## License
This project is licensed under the [MIT license].
[mit license]: https://github.com/DioxusLabs/dioxus/blob/master/LICENSE-MIT
+3 -3
View File
@@ -158,11 +158,11 @@ impl Display for IssueReport {
#[allow(clippy::enum_variant_names)] // we'll add non-hook ones in the future
/// Issues that might be found via static analysis of a Dioxus file.
pub enum Issue {
/// https://dioxuslabs.com/docs/0.3/guide/en/interactivity/hooks.html#no-hooks-in-conditionals
/// https://dioxuslabs.com/learn/0.4/reference/hooks#no-hooks-in-conditionals
HookInsideConditional(HookInfo, ConditionalInfo),
/// https://dioxuslabs.com/docs/0.3/guide/en/interactivity/hooks.html#no-hooks-in-loops
/// https://dioxuslabs.com/learn/0.4/reference/hooks#no-hooks-in-loops
HookInsideLoop(HookInfo, AnyLoopInfo),
/// https://dioxuslabs.com/docs/0.3/guide/en/interactivity/hooks.html#no-hooks-in-closures
/// https://dioxuslabs.com/learn/0.4/reference/hooks#no-hooks-in-closures
HookInsideClosure(HookInfo, ClosureInfo),
HookOutsideComponent(HookInfo),
}
+9 -25
View File
@@ -8,47 +8,31 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: stable
override: true
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v1
- uses: actions-rs/cargo@v1
with:
command: check
- run: cargo check
test:
name: Test Suite
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: stable
override: true
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v1
- uses: actions-rs/cargo@v1
with:
command: test
- run: cargo test
fmt:
name: Rustfmt
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: stable
override: true
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v1
- run: rustup component add rustfmt
- uses: actions-rs/cargo@v1
with:
command: fmt
args: --all -- --check
- run: cargo fmt --all -- --check
# clippy:
# name: Clippy
+5 -6
View File
@@ -1,6 +1,6 @@
[package]
name = "dioxus-cli"
version = { workspace = true }
version = "0.4.1"
authors = ["Jonathan Kelley"]
edition = "2021"
description = "CLI tool for developing, testing, and publishing Dioxus apps"
@@ -22,7 +22,7 @@ serde = { version = "1.0.136", features = ["derive"] }
serde_json = "1.0.79"
toml = "0.5.8"
fs_extra = "1.2.0"
cargo_toml = "0.11.4"
cargo_toml = "0.16.0"
futures = "0.3.21"
notify = { version = "5.0.0-pre.16", features = ["serde"] }
html_parser = { workspace = true }
@@ -36,7 +36,7 @@ chrono = "0.4.19"
anyhow = "1.0.53"
hyper = "0.14.17"
hyper-rustls = "0.23.2"
indicatif = "0.17.0-rc.11"
indicatif = "0.17.5"
subprocess = "0.2.9"
axum = { version = "0.5.1", features = ["ws", "headers"] }
@@ -75,11 +75,10 @@ gitignore = "1.0.7"
open = "4.1.0"
cargo-generate = "0.18"
toml_edit = "0.19.11"
# dioxus-rsx = "0.0.1"
# bundling
tauri-bundler = { version = "1.2", features = ["native-tls-vendored"] }
tauri-utils = "1.3"
tauri-bundler = { version = "=1.3.0", features = ["native-tls-vendored"] }
tauri-utils = "=1.4.*"
dioxus-autofmt = { workspace = true }
dioxus-check = { workspace = true }
+21 -18
View File
@@ -1,29 +1,31 @@
[application]
# dioxus project name
name = "dioxus-cli"
# App name
name = "project_name"
# default platfrom
# you can also use `dx serve/build --platform XXX` to use other platform
# value: web | desktop
default_platform = "desktop"
# The Dioxus platform to default to
default_platform = "web"
# Web `build` & `serve` dist path
# `build` & `serve` output path
out_dir = "dist"
# resource (static) file folder
# The static resource path
asset_dir = "public"
[web.app]
# HTML title tag content
title = "dioxus | ⛺"
title = "project_name"
[web.watcher]
watch_path = ["src"]
# When watcher is triggered, regenerate the `index.html`
reload_html = true
# include `assets` in web platform
# Which files or dirs will be monitored
watch_path = ["src", "public"]
# Include style or script assets
[web.resource]
# CSS style file
@@ -34,12 +36,13 @@ script = []
[web.resource.dev]
# Javascript code file
# serve: [dev-server] only
# Same as [web.resource], but for development servers
# CSS style file
style = []
# JavaScript files
script = []
[application.tools]
# use binaryen.wasm-opt for output Wasm file
# binaryen just will trigger in `web` platform
binaryen = { wasm_opt = true }
[[web.proxy]]
backend = "http://localhost:8000/api/"
+44 -16
View File
@@ -1,43 +1,71 @@
<div align="center">
<h1>📦✨ Dioxus CLI </h1>
<div style="text-align: center">
<h1>📦✨ Dioxus CLI</h1>
<p><strong>Tooling to supercharge Dioxus projects</strong></p>
</div>
**dioxus-cli** (inspired by wasm-pack and webpack) is a tool for getting Dioxus projects up and running.
It handles all build, bundling, development and publishing to simplify web development.
The **dioxus-cli** (inspired by wasm-pack and webpack) is a tool for getting Dioxus projects up and running.
It handles all building, bundling, development and publishing to simplify development.
## Installation
### Install stable version
### Install the stable version (recommended)
```
cargo install dioxus-cli
cargo install dioxus-cli --locked
```
### Install from git repository
### Install the latest development build through git
To get the latest bug fixes and features, you can install the development version from git.
However, this is not fully tested.
That means you're probably going to have more bugs despite having the latest bug fixes.
```
cargo install --git https://github.com/DioxusLabs/dioxus dioxus-cli
```
This will download the CLI from the master branch,
and install it in Cargo's global binary directory (`~/.cargo/bin/` by default).
### Install from local folder
```
cargo install --path . --debug
```
## Get started
## Get Started
Use `dx create project-name` to initialize a new Dioxus project. <br>
Use `dx create project-name` to initialize a new Dioxus project.
It will be cloned from the [dioxus-template](https://github.com/DioxusLabs/dioxus-template) repository.
<br>
Alternatively, you can specify the template path:
```
dx create hello --template gh:dioxuslabs/dioxus-template
```
## Dioxus Config File
Run `dx --help` for a list of all the available commands.
Furthermore, you can run `dx <command> --help` to get help with a specific command.
Dioxus CLI will use `Dioxus.toml` file to Identify some project info and switch some cli feature.
## Dioxus config file
You can get more configure information from [Dioxus CLI Document](https://dioxuslabs.com/cli/configure.html).
You can use the `Dioxus.toml` file for further configuration.
Some fields are mandatory, but the CLI tool will tell you which ones are missing.
You can create a `Dioxus.toml` with all fields already set using `dx config init project-name`,
or you can use this bare-bones template (only mandatory fields) to get started:
```toml
[application]
name = "project-name"
# Currently supported platforms: web, desktop
default_platform = "web"
[web.app]
title = "Hello"
[web.watcher]
[web.resource.dev]
```
The full anatomy of `Dioxus.toml` is shown on the [Dioxus website](https://dioxuslabs.com/learn/0.4/CLI/configure).
+1 -1
View File
@@ -3,4 +3,4 @@ authors = ["YuKun Liu"]
language = "en"
multilingual = false
src = "src"
title = "Dioxus Cli"
title = "Dioxus CLI"
+9 -14
View File
@@ -2,17 +2,12 @@
- [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)
- [Plugin Development](./plugin/README.md)
- [API.Log](./plugin/interface/log.md)
- [API.Command](./plugin/interface/command.md)
- [API.OS](./plugin/interface/os.md)
- [API.Directories](./plugin/interface/dirs.md)
- [API.Network](./plugin/interface/network.md)
- [API.Path](./plugin/interface/path.md)
- [Create a project](./creating.md)
- [Configure a project](./configure.md)
- [Plugin development](./plugin/README.md)
- [API.Log](plugin/interface/log.md)
- [API.Command](plugin/interface/command.md)
- [API.OS](plugin/interface/os.md)
- [API.Directories](plugin/interface/dirs.md)
- [API.Network](plugin/interface/network.md)
- [API.Path](plugin/interface/path.md)
-30
View File
@@ -1,30 +0,0 @@
# Commands
In this chapter we will introduce all `dioxus-cli` commands.
> You can also use `dx --help` to get cli help info.
```
Build, Bundle & Ship Dioxus Apps
Usage: dx [OPTIONS] <COMMAND>
Commands:
build Build the Rust WASM app and all of its assets
translate Translate some source file into Dioxus code
serve Build, watch & serve the Rust WASM app and all of its assets
create Init a new project for Dioxus
clean Clean output artifacts
bundle Bundle the Rust desktop app and all of its assets
version Print the version of this extension
fmt Format some rsx
check Check the Rust files in the project for issues
config Dioxus config file controls
help Print this message or the help of the given subcommand(s)
Options:
-v Enable verbose logging
--bin <BIN> Specify bin target
-h, --help Print help
-V, --version Print version
```
-56
View File
@@ -1,56 +0,0 @@
# Build
The `dx build` command can help you `pack & build` a dioxus project.
```
dioxus-build
Build the Rust WASM app and all of its assets
USAGE:
dx build [OPTIONS]
OPTIONS:
--example <EXAMPLE> [default: ""]
--platform <PLATFORM> [default: "default_platform"]
--release [default: false]
--bin [default: None]
```
You can use this command to build a project:
```
dx build --release
```
## Target platform
Use the `platform` option to choose your target platform:
```
# for desktop project
dx build --platform desktop
```
`platform` currently only supports `desktop` & `web`.
```
# for web project
dx build --platform web
```
## Specify workspace bin
You can add the `--bin` option to select which crate you want Dioxus to build:
```
dx build --bin app
```
## Build Example
You can use the `example` option to select a example to build:
```
# build the `test` example
dx build --exmaple test
```
-27
View File
@@ -1,27 +0,0 @@
# Clean
`dx clean` will clear the build artifacts (the out_dir and the cargo cache)
```
dioxus-clean
Clean build artifacts
USAGE:
dx clean [OPTIONS]
OPTIONS:
--bin [default: None]
```
# Example
```
dx clean
```
# Specify workspace bin
You can add the `--bin` option to select which crate you want Dioxus to clean artifacts from:
```
dx clean --bin app
```
-70
View File
@@ -1,70 +0,0 @@
# Serve
The `dx serve` can start a dev server with hot-reloading
```
dioxus-serve
Build, watch & serve the Rust WASM app and all of its assets
USAGE:
dx serve [OPTIONS]
OPTIONS:
--example <EXAMPLE> [default: ""]
--platform <PLATFORM> [default: "default_platform"]
--release [default: false]
--hot-reload [default: false]
--bin [default: None]
```
You can use this command to build project and start a dev server:
```
dx serve
```
## Serve Example
You can use the `example` option to serve a example:
```
# serve the `test` example
dx serve --exmaple test
```
## Specify workspace bin
You can add the `--bin` option to select which crate you want Dioxus to build and serve:
```
dx serve --bin app
```
## Open Browser
You can add the `--open` option to open system default browser when server startup:
```
dx serve --open
```
## RSX Hot Reloading
You can add the `--hot-reload` flag to enable [rsx hot reloading](https://dioxuslabs.com/docs/0.3/guide/en/getting_started/hot_reload.html). This will allow you to reload some rsx changes without a full recompile:
```
dx serve --open
```
## Cross Origin Policy
You can add the `cross-origin-policy` option to change cross-origin header to:
```
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
```
```
dx serve --corss-origin-policy
```
-68
View File
@@ -1,68 +0,0 @@
# Translate
`dx translate` can translate some `html` file into a Dioxus compoent
```
dioxus-translate
Translate some source file into a Dioxus component
USAGE:
dx translate [OPTIONS] [OUTPUT]
ARGS:
<OUTPUT> Output file, defaults to stdout if not present
OPTIONS:
-c, --component Activate debug mode
-f, --file <FILE> Input file
```
## Translate HTML to stdout
You can use the `file` option to set path to the `html` file to translate:
```
dx transtale --file ./index.html
```
## Output rsx to a file
You can pass a file to the traslate command to set the path to write the output of the command to:
```
dx translate --file ./index.html component.rsx
```
## Output rsx to a file
Setting the `component` option will create a compoent from the HTML:
```
dx translate --file ./index.html --component
```
## Example
This HTML:
```html
<div>
<h1> Hello World </h1>
<a href="https://dioxuslabs.com/">Link</a>
</div>
```
Translates into this Dioxus component:
```rust
fn component(cx: Scope) -> Element {
cx.render(rsx! {
div {
h1 { "Hello World" },
a {
href: "https://dioxuslabs.com/",
"Link"
}
}
})
}
```
+85 -96
View File
@@ -1,166 +1,155 @@
# Configure Project
This chapter will teach you how to configure the CLI with the `Dioxus.toml` file.
There's an [example](#config-example) which has comments to describe individual keys.
You can copy that or view this documentation for a more complete learning experience.
This chapter will introduce you to how to configure the CLI with your `Dioxus.toml` file
Be aware that if the config file is present in the folder, some fields must be filled out, or the CLI tool will abort. The mandatory [table headers](https://toml.io/en/v1.0.0#table) and keys will have a '✍' sign beside it.
"🔒" indicates a mandatory item. Some headers are mandatory, but none of the keys inside them are. It might look weird, but it's normal. Simply don't include any keys.
## Structure
The CLI uses a `Dioxus.toml` file in the root of your crate to define some configuration for your `dioxus` project.
Each header has it's TOML form directly under it.
### Application ✍
### Application 🔒
General application confiration:
```
```toml
[application]
# configuration
```
1. ***name*** ✍ - project name & title
2. ***default_platform*** ✍ - which platform target for this project.
Application-wide configuration. Applies to both web and desktop.
1. **name** 🔒 - Project name & title.
```toml
name = "my_project"
```
name = "my-project"
```
2. ***default_platform*** - The platform this project targets
```ß
# current supported platforms: web, desktop
# default: web
2. **default_platform** 🔒 - The platform this project targets
```toml
# Currently supported platforms: web, desktop
default_platform = "web"
```
if you change this to `desktop`, the `dx build` will default building a desktop app
3. ***out_dir*** - The directory to place the build artifacts from `dx build` or `dx service` into. This is also where the `assets` directory will be copied to
```
3. **out_dir** - The directory to place the build artifacts from `dx build` or `dx serve` into. This is also where the `assets` directory will be copied into.
```toml
out_dir = "dist"
```
4. ***asset_dir*** - The directory with your static assets. The CLI will automatically copy these assets into the ***out_dir*** after a build/serve.
```
4. **asset_dir** - The directory with your static assets. The CLI will automatically copy these assets into the **out_dir** after a build/serve.
```toml
asset_dir = "public"
```
5. ***sub_package*** - The sub package in the workspace to build by default
```
5. **sub_package** - The sub package in the workspace to build by default.
```toml
sub_package = "my-crate"
```
### Web.App ✍
### Web.App 🔒
Configeration specific to web applications:
```
```toml
[web.app]
# configuration
```
1. ***title*** - The title of the web page
```
Web-specific configuration.
1. **title** - The title of the web page.
```toml
# HTML title tag content
title = "dioxus app | ⛺"
```
2. ***base_path*** - The base path to build the appliation for serving at. This can be useful when serving your application in a subdirectory under a domain. For example when building a site to be served on github pages.
title = "project_name"
```
2. **base_path** - The base path to build the application for serving at. This can be useful when serving your application in a subdirectory under a domain. For example when building a site to be served on GitHub Pages.
```toml
# The application will be served at domain.com/my_application/, so we need to modify the base_path to the path where the application will be served
base_path = "my_application"
```
### Web.Watcher ✍
Configeration related to the development server:
```
```toml
[web.watcher]
# configuration
```
1. ***reload_html*** - If this is true, the cli will rebuild the index.html file every time the application is rebuilt
```
Development server configuration.
1. **reload_html** - If this is true, the cli will rebuild the index.html file every time the application is rebuilt
```toml
reload_html = true
```
2. ***watch_path*** - The files & directories to moniter for changes
```
2. **watch_path** - The files & directories to monitor for changes
```toml
watch_path = ["src", "public"]
```
3. ***index_on_404*** - If enabled, Dioxus CLI will serve the root page when a route is not found. *This is needed when serving an application that uses the router*
```
3. **index_on_404** - If enabled, Dioxus will serve the root page when a route is not found.
*This is needed when serving an application that uses the router*.
However, when serving your app using something else than Dioxus (e.g. GitHub Pages), you will have to check how to configure it on that platform.
In GitHub Pages, you can make a copy of `index.html` named `404.html` in the same directory.
```toml
index_on_404 = true
```
### Web.Resource ✍
### Web.Resource 🔒
Configeration related to static resources your application uses:
```
```toml
[web.resource]
# configuration
```
1. ***style*** - The styles (`.css` files) to include in your application
```
Static resource configuration.
1. **style** - CSS files to include in your application.
```toml
style = [
# include from public_dir.
# Include from public_dir.
"./assets/style.css",
# or some asset from online cdn.
# Or some asset from online cdn.
"https://cdn.jsdelivr.net/npm/bootstrap/dist/css/bootstrap.css"
]
```
2. ***script*** - The additional scripts (`.js` files) to include in your application
```
style = [
# include from public_dir.
"./assets/index.js",
# or some asset from online cdn.
2. **script** - JavaScript files to include in your application.
```toml
script = [
# Include from asset_dir.
"./public/index.js",
# Or from an online CDN.
"https://cdn.jsdelivr.net/npm/bootstrap/dist/js/bootstrap.js"
]
```
### Web.Resource.Dev ✍
### Web.Resource.Dev 🔒
Configeration related to static resources your application uses in development:
```
```toml
[web.resource.dev]
# configuration
```
1. ***style*** - The styles (`.css` files) to include in your application
```
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*** - The additional scripts (`.js` files) to include in your application
```
style = [
# include from public_dir.
"./assets/index.js",
# or some asset from online cdn.
"https://cdn.jsdelivr.net/npm/bootstrap/dist/js/bootstrap.js"
]
```
This is the same as [`[web.resource]`](#webresource-), but it only works in development servers.
For example, if you want to include a file in a `dx serve` server, but not a `dx serve --release` server, put it here.
### Web.Proxy
Configeration related to any proxies your application requires durring development. Proxies will forward requests to a new service
```
```toml
[[web.proxy]]
# configuration
```
1. ***backend*** - The URL to the server to proxy. The CLI will forward any requests under the backend relative route to the backend instead of returning 404
```
Configuration related to any proxies your application requires during development. Proxies will forward requests to a new service.
1. **backend** - The URL to the server to proxy. The CLI will forward any requests under the backend relative route to the backend instead of returning 404
```toml
backend = "http://localhost:8000/api/"
```
This will cause any requests made to the dev server with prefix /api/ to be redirected to the backend server at http://localhost:8000. The path and query parameters will be passed on as-is (path rewriting is not currently supported).
This will cause any requests made to the dev server with prefix /api/ to be redirected to the backend server at http://localhost:8000. The path and query parameters will be passed on as-is (path rewriting is currently not supported).
## Config example
This includes all fields, mandatory or not.
```toml
[application]
# App (Project) Name
name = "{{project-name}}"
# App name
name = "project_name"
# The Dioxus platform to default to
default_platform = "web"
@@ -168,23 +157,23 @@ default_platform = "web"
# `build` & `serve` output path
out_dir = "dist"
# the static resource path
# The static resource path
asset_dir = "public"
[web.app]
# HTML title tag content
title = "dioxus | ⛺"
title = "project_name"
[web.watcher]
# when watcher is triggered, regenerate the `index.html`
# When watcher is triggered, regenerate the `index.html`
reload_html = true
# which files or dirs will be monitored
# Which files or dirs will be monitored
watch_path = ["src", "public"]
# include `assets` in web platform
# Include style or script assets
[web.resource]
# CSS style file
@@ -195,12 +184,12 @@ script = []
[web.resource.dev]
# serve: [dev-server] only
# Same as [web.resource], but for development servers
# CSS style file
style = []
# Javascript code file
# JavaScript files
script = []
[[web.proxy]]
+9 -11
View File
@@ -1,39 +1,37 @@
# Create a Project
Once you have the Dioxus CLI tool installed, you can use it to create dioxus project.
Once you have the Dioxus CLI installed, you can use it to create your own project!
## Initializing a default project
First, run the `dx create` command to create a new project ready to be used with Dioxus and the Dioxus CLI:
First, run the `dx create` command to create a new project:
```
dx 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.
> It will clone this [template](https://github.com/DioxusLabs/dioxus-template).
> This default template is used for `web` platform application.
>
> You can choose to create your project from a different template by passing the `template` argument:
> ```
> dx init hello-dioxus --template=gh:dioxuslabs/dioxus-template
> ```
Next, move the current directory into your new project:
Next, navigate into your new project:
```
cd hello-dioxus
```
> Make sure `wasm32 target` is installed before running the Web project.
> You can install the wasm target for rust using rustup:
> Make sure the WASM target is installed before running the projects.
> You can install the WASM target for rust using rustup:
> ```
> rustup target add wasm32-unknown-unknown
> ```
Finally, create serve your project with the Dioxus CLI:
Finally, serve your project:
```
dx serve
```
By default, the CLI serve your site at: [`http://127.0.0.1:8080/`](http://127.0.0.1:8080/)
By default, the CLI serves your website at [`http://127.0.0.1:8080/`](http://127.0.0.1:8080/).
+9 -8
View File
@@ -1,22 +1,23 @@
# Installation
Choose any one of the methods below to install the Dioxus CLI:
## Install the latest development build through git
## Install from latest git version
To get the most up to date bug fixes and features of the Dioxus CLI, you can install the development version from git.
To get the latest bug fixes and features, you can install the development version from git.
```
cargo install --git https://github.com/Dioxuslabs/cli
```
This will automatically download `Dioxus-CLI` source from github master branch,
This will 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
## Install stable through `crates.io`
The published version of the Dioxus CLI is updated less often, but should be more stable than the git version of the Dioxus CLI.
The published version of the Dioxus CLI is updated less often, but is more stable than the git version.
```
cargo install dioxus-cli
cargo install dioxus-cli --locked
```
Run `dx --help` for a list of all the available commands.
Furthermore, you can run `dx <COMMAND> --help` to get help with a specific command.
+12 -15
View File
@@ -1,21 +1,18 @@
# 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.
The 📦✨ **Dioxus CLI** is a tool to help get Dioxus projects off the ground.
## Features
* Build and pack a Dioxus project
* `html` to `rsx` conversion tool
* Hot Reload for `web` platform
* Create a Dioxus project from `git` repo
* And more!
<!-- Checkmarks don't render on the website, so I've just made a normal list. You can uncomment this if the website rendering is fixed.
- [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)
- [x] Hot Reload for `web` platform
- [x] Create a Dioxus project from `git` repo
- [x] Build & pack Dioxus project
- [ ] Automatically format Dioxus `rsx` code
-->
+74 -13
View File
@@ -1,24 +1,85 @@
# CLI Plugin Development
# CLI Plugin development
> For Cli 0.2.0 we will add `plugin-develop` support.
**IMPORTANT: Ignore this documentation. Plugins are yet to be released and chances are it won't work for you. This is just what plugins *could* look like.**
Before the 0.2.0 we use `dx tool` to use & install some plugin, but we think that is not good for extend cli program, some people want tailwind support, some people want sass support, we can't add all this thing in to the cli source code and we don't have time to maintain a lot of tools that user request, so maybe user make plugin by themself is a good choice.
In the past we used `dx tool` to use and install tools, but it was a flawed system.
Tools were hard-coded by us, but people want more tools than we could code, so this plugin system was made to let
anyone develop plugins and use them in Dioxus projects.
### Why Lua ?
Plugin resources:
* [Source code](https://github.com/DioxusLabs/dioxus/tree/master/packages/cli/src/plugin)
* [Unofficial Dioxus plugin community](https://github.com/DioxusPluginCommunity). Contains certain plugins you can use right now.
We choose `Lua: 5.4` to be the plugin develop language, because cli plugin is not complex, just like a workflow, and user & developer can write some easy code for their plugin. We have **vendored** lua in cli program, and user don't need install lua runtime in their computer, and the lua parser & runtime doesn't take up much disk memory.
### Why Lua?
### Event Management
We chose Lua `5.4` to be the plugin developing language,
because it's extremely lightweight, embeddable and easy to learn.
We installed Lua into the CLI, so you don't need to do it yourself.
The plugin library have pre-define some important event you can control:
Lua resources:
* [Official website](https://www.lua.org/). You can basically find everything here.
* [Awesome Lua](https://github.com/LewisJEllis/awesome-lua). Additional resources (such as Lua plugins for your favorite IDE), and other *awesome* tools!
- `build.on_start`
- `build.on_finished`
- `serve.on_start`
- `serve.on_rebuild`
- `serve.on_shutdown`
### Plugin Template
## Creating a plugin
A plugin is just an `init.lua` file.
You can include other files using `dofile(path)`.
You need to have a plugin and a manager instance, which you can get using `require`:
```lua
local plugin = require("plugin")
local manager = require("manager")
```
You need to set some `manager` fields and then initialize the plugin:
```lua
manager.name = "My first plugin"
manager.repository = "https://github.com/john-doe/my-first-plugin" -- The repository URL.
manager.author = "John Doe <john.doe@example.com>"
manager.version = "0.1.0"
plugin.init(manager)
```
You also need to return the `manager`, which basically represents your plugin:
```lua
-- Your code here.
-- End of file.
manager.serve.interval = 1000
return manager
```
And you're ready to go. Now, go and have a look at the stuff below and the API documentation.
### Plugin info
You will encounter this type in the events below. The keys are as follows:
* `name: string` - The name of the plugin.
* `repository: string` - The plugin repository URL.
* `author: string` - The author of the plugin.
* `version: string` - The plugin version.
### Event management
The plugin library has certain events that you can subscribe to.
* `manager.on_init` - Triggers the first time the plugin is loaded.
* `manager.build.on_start(info)` - Triggers before the build process. E.g., before `dx build`.
* `manager.build.on_finish(info)` - Triggers after the build process. E.g., after `dx build`.
* `manager.serve.on_start(info)` - Triggers before the serving process. E.g., before `dx serve`.
* `manager.serve.on_rebuild_start(info)` - Triggers before the server rebuilds the web with hot reload.
* `manager.serve.on_rebuild_end(info)` - Triggers after the server rebuilds the web with hot reload.
* `manager.serve.on_shutdown` - Triggers when the server is shutdown. E.g., when the `dx serve` process is terminated.
To subscribe to an event, you simply need to assign it to a function:
```lua
manager.build.on_start = function (info)
log.info("[plugin] Build starting: " .. info.name)
end
```
### Plugin template
```lua
package.path = library_dir .. "/?.lua"
@@ -1,15 +1,15 @@
# Command Functions
> you can use command functions to execute some code & script
You can use command functions to execute code and scripts.
Type Define:
Type definition:
```
Stdio: "Inherit" | "Piped" | "Null"
```
### `exec(commands: [string], stdout: Stdio, stderr: Stdio)`
you can use this function to run some command on the current system.
You can use this function to run some commands on the current system.
```lua
local cmd = plugin.command
@@ -18,4 +18,4 @@ manager.test = function ()
cmd.exec({"git", "clone", "https://github.com/DioxusLabs/cli-plugin-library"})
end
```
> Warning: This function don't have exception catch.
> Warning: This function doesn't catch exceptions.
+7 -12
View File
@@ -1,33 +1,28 @@
# Dirs Functions
> you can use Dirs functions to get some directory path
Dirs functions are for getting various directory paths. Not to be confused with `plugin.path`.
### `plugin_dir() -> string`
### plugin_dir() -> string
You can get current plugin **root** directory path
Get the plugin's root directory path.
```lua
local path = plugin.dirs.plugin_dir()
-- example: ~/Development/DioxusCli/plugin/test-plugin/
```
### bin_dir() -> string
### `bin_dir() -> string`
You can get plugin **bin** direcotry path
Sometime you need install some binary file like `tailwind-cli` & `sass-cli` to help your plugin work, then you should put binary file in this directory.
Get the plugin's binary directory path. Put binary files like `tailwind-cli` or `sass-cli` in this directory.
```lua
local path = plugin.dirs.bin_dir()
-- example: ~/Development/DioxusCli/plugin/test-plugin/bin/
```
### temp_dir() -> string
### `temp_dir() -> string`
You can get plugin **temp** direcotry path
Just put some temporary file in this directory.
Get the plugin's temporary directory path. Put any temporary files here.
```lua
local path = plugin.dirs.bin_dir()
+11 -11
View File
@@ -1,46 +1,46 @@
# Log Functions
> You can use log function to print some useful log info
You can use log functions to print various logging information.
### Trace(info: string)
### `trace(info: string)`
Print trace log info
Print trace log info.
```lua
local log = plugin.log
log.trace("trace information")
```
### Debug(info: string)
### `debug(info: string)`
Print debug log info
Print debug log info.
```lua
local log = plugin.log
log.debug("debug information")
```
### Info(info: string)
### `info(info: string)`
Print info log info
Print info log info.
```lua
local log = plugin.log
log.info("info information")
```
### Warn(info: string)
### `warn(info: string)`
Print warning log info
Print warning log info.
```lua
local log = plugin.log
log.warn("warn information")
```
### Error(info: string)
### `error(info: string)`
Print error log info
Print error log info.
```lua
local log = plugin.log
@@ -1,12 +1,13 @@
# Network Functions
> you can use Network functions to download & read some data from internet
You can use Network functions to download & read some data from the internet.
### download_file(url: string, path: string) -> boolean
### `download_file(url: string, path: string) -> boolean`
This function can help you download some file from url, and it will return a *boolean* value to check the download status. (true: success | false: fail)
Downloads a file from the specified URL,
and returns a `boolean` that represents the download status (true: success, false: failure).
You need pass a target url and a local path (where you want to save this file)
You need to pass a target URL and a local path (where you want to save this file).
```lua
-- this file will download to plugin temp directory
@@ -19,9 +20,11 @@ if status != true then
end
```
### clone_repo(url: string, path: string) -> boolean
### `clone_repo(url: string, path: string) -> boolean`
This function can help you use `git clone` command (this system must have been installed git)
Clone a repository from the given URL into the given path.
Returns a `boolean` that represents the clone status (true: success, false: failure).
The system executing this function must have git installed.
```lua
local status = plugin.network.clone_repo(
+3 -3
View File
@@ -1,10 +1,10 @@
# OS Functions
> you can use OS functions to get some system information
OS functions are for getting system information.
### current_platform() -> string ("windows" | "macos" | "linux")
### `current_platform() -> string ("windows" | "macos" | "linux")`
This function can help you get system & platform type:
Get the current OS platform.
```lua
local platform = plugin.os.current_platform()
+14 -11
View File
@@ -1,10 +1,13 @@
# Path Functions
> you can use path functions to operate valid path string
You can use path functions to perform operations on valid path strings.
### join(path: string, extra: string) -> string
### `join(path: string, extra: string) -> string`
This function can help you extend a path, you can extend any path, dirname or filename.
<!-- TODO: Add specifics.
From the example given, it seems like it just creates a subdirectory path.
What would it do when "extending" file paths? -->
Extend a path; you can extend both directory and file paths.
```lua
local current_path = "~/hello/dioxus"
@@ -12,9 +15,9 @@ local new_path = plugin.path.join(current_path, "world")
-- new_path = "~/hello/dioxus/world"
```
### parent(path: string) -> string
### `parent(path: string) -> string`
This function will return `path` parent-path string, back to the parent.
Return the parent path of the specified path. The parent path is always a directory.
```lua
local current_path = "~/hello/dioxus"
@@ -22,14 +25,14 @@ local new_path = plugin.path.parent(current_path)
-- new_path = "~/hello/"
```
### exists(path: string) -> boolean
### `exists(path: string) -> boolean`
This function can check some path (dir & file) is exists.
Check if the specified path exists, as either a file or a directory.
### is_file(path: string) -> boolean
### `is_file(path: string) -> boolean`
This function can check some path is a exist file.
Check if the specified path is a file.
### is_dir(path: string) -> boolean
### `is_dir(path: string) -> boolean`
This function can check some path is a exist dir.
Check if the specified path is a directory.
+5 -6
View File
@@ -22,6 +22,7 @@ pub struct BuildResult {
pub elapsed_time: u128,
}
#[allow(unused)]
pub fn build(config: &CrateConfig, quiet: bool) -> Result<BuildResult> {
// [1] Build the project with cargo, generating a wasm32-unknown-unknown target (is there a more specific, better target to leverage?)
// [2] Generate the appropriate build folders
@@ -53,7 +54,8 @@ pub fn build(config: &CrateConfig, quiet: bool) -> Result<BuildResult> {
.arg("build")
.arg("--target")
.arg("wasm32-unknown-unknown")
.arg("--message-format=json");
.arg("--message-format=json")
.arg("--quiet");
let cmd = if config.release {
cmd.arg("--release")
@@ -66,8 +68,6 @@ pub fn build(config: &CrateConfig, quiet: bool) -> Result<BuildResult> {
cmd
};
let cmd = if quiet { cmd.arg("--quiet") } else { cmd };
let cmd = if config.custom_profile.is_some() {
let custom_profile = config.custom_profile.as_ref().unwrap();
cmd.arg("--profile").arg(custom_profile)
@@ -386,10 +386,9 @@ fn prettier_build(cmd: subprocess::Exec) -> anyhow::Result<Vec<Diagnostic>> {
}
}
StopSpinOnDrop(pb.clone());
let stdout = cmd.detached().stream_stdout()?;
let reader = std::io::BufReader::new(stdout);
for message in cargo_metadata::Message::parse_stream(reader) {
match message.unwrap() {
Message::CompilerMessage(msg) => {
@@ -409,7 +408,7 @@ fn prettier_build(cmd: subprocess::Exec) -> anyhow::Result<Vec<Diagnostic>> {
}
}
Message::CompilerArtifact(artifact) => {
pb.set_message(format!("Compiling {} ", artifact.package_id));
pb.set_message(format!("⚙️ Compiling {} ", artifact.package_id));
pb.tick();
}
Message::BuildScriptExecuted(script) => {
+1 -1
View File
@@ -42,7 +42,7 @@ impl Build {
match platform {
Platform::Web => {
crate::builder::build(&crate_config, false)?;
crate::builder::build(&crate_config, true)?;
}
Platform::Desktop => {
crate::builder::build_desktop(&crate_config, false)?;
+4 -4
View File
@@ -132,10 +132,10 @@ impl Bundle {
.project_out_directory(crate_config.out_dir)
.package_settings(PackageSettings {
product_name: crate_config.dioxus_config.application.name.clone(),
version: package.version,
description: package.description.unwrap_or_default(),
homepage: package.homepage,
authors: Some(package.authors),
version: package.version().to_string(),
description: package.description().unwrap_or_default().to_string(),
homepage: Some(package.homepage().unwrap_or_default().to_string()),
authors: Some(Vec::from(package.authors())),
default_run: Some(crate_config.dioxus_config.application.name.clone()),
})
.binaries(binaries)
+3
View File
@@ -381,6 +381,7 @@ impl From<DebianSettings> for tauri_bundler::DebianSettings {
tauri_bundler::DebianSettings {
depends: val.depends,
files: val.files,
desktop_template: None,
}
}
}
@@ -522,6 +523,8 @@ impl From<NsisSettings> for tauri_bundler::NsisSettings {
install_mode: val.install_mode.into(),
languages: val.languages,
display_language_selector: val.display_language_selector,
custom_language_files: None,
template: None,
}
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
pub const DIOXUS_CLI_VERSION: &str = "0.1.5";
pub const DIOXUS_CLI_VERSION: &str = "0.4.1";
pub mod builder;
pub mod server;
+44 -69
View File
@@ -1,7 +1,7 @@
use crate::{
server::{
output::{print_console_info, PrettierOptions},
setup_file_watcher, setup_file_watcher_hot_reload,
setup_file_watcher,
},
BuildResult, CrateConfig, Result,
};
@@ -19,6 +19,8 @@ use tokio::sync::broadcast::{self};
#[cfg(feature = "plugin")]
use plugin::PluginManager;
use super::HotReloadState;
pub async fn startup(config: CrateConfig) -> Result<()> {
// ctrl-c shutdown checker
let _crate_config = config.clone();
@@ -28,16 +30,36 @@ pub async fn startup(config: CrateConfig) -> Result<()> {
std::process::exit(0);
});
match config.hot_reload {
true => serve_hot_reload(config).await?,
false => serve_default(config).await?,
}
let hot_reload_state = match config.hot_reload {
true => {
let FileMapBuildResult { map, errors } =
FileMap::<HtmlCtx>::create(config.crate_dir.clone()).unwrap();
for err in errors {
log::error!("{}", err);
}
let file_map = Arc::new(Mutex::new(map));
let hot_reload_tx = broadcast::channel(100).0;
clear_paths();
Some(HotReloadState {
messages: hot_reload_tx.clone(),
file_map: file_map.clone(),
})
}
false => None,
};
serve(config, hot_reload_state).await?;
Ok(())
}
/// Start the server without hot reload
pub async fn serve_default(config: CrateConfig) -> Result<()> {
pub async fn serve(config: CrateConfig, hot_reload_state: Option<HotReloadState>) -> Result<()> {
let (child, first_build_result) = start_desktop(&config)?;
let currently_running_child: RwLock<Child> = RwLock::new(child);
@@ -59,6 +81,7 @@ pub async fn serve_default(config: CrateConfig) -> Result<()> {
},
&config,
None,
hot_reload_state.clone(),
)
.await?;
@@ -73,79 +96,29 @@ pub async fn serve_default(config: CrateConfig) -> Result<()> {
None,
);
std::future::pending::<()>().await;
match hot_reload_state {
Some(hot_reload_state) => {
start_desktop_hot_reload(hot_reload_state).await?;
}
None => {
std::future::pending::<()>().await;
}
}
Ok(())
}
/// Start the server without hot reload
/// Start dx serve with hot reload
pub async fn serve_hot_reload(config: CrateConfig) -> Result<()> {
let (_, first_build_result) = start_desktop(&config)?;
println!("🚀 Starting development server...");
// Setup hot reload
let FileMapBuildResult { map, errors } =
FileMap::<HtmlCtx>::create(config.crate_dir.clone()).unwrap();
println!("🚀 Starting development server...");
for err in errors {
log::error!("{}", err);
}
let file_map = Arc::new(Mutex::new(map));
let (hot_reload_tx, mut hot_reload_rx) = broadcast::channel(100);
// States
// The open interprocess sockets
let channels = Arc::new(Mutex::new(Vec::new()));
// Setup file watcher
// We got to own watcher so that it exists for the duration of serve
// Otherwise hot reload won't work.
let _watcher = setup_file_watcher_hot_reload(
&config,
hot_reload_tx,
file_map.clone(),
{
let config = config.clone();
let channels = channels.clone();
move || {
for channel in &mut *channels.lock().unwrap() {
send_msg(HotReloadMsg::Shutdown, channel);
}
Ok(start_desktop(&config)?.1)
}
},
None,
)
.await?;
// Print serve info
print_console_info(
&config,
PrettierOptions {
changed: vec![],
warnings: first_build_result.warnings,
elapsed_time: first_build_result.elapsed_time,
},
None,
);
clear_paths();
async fn start_desktop_hot_reload(hot_reload_state: HotReloadState) -> Result<()> {
match LocalSocketListener::bind("@dioxusin") {
Ok(local_socket_stream) => {
let aborted = Arc::new(Mutex::new(false));
// States
// The open interprocess sockets
let channels = Arc::new(Mutex::new(Vec::new()));
// listen for connections
std::thread::spawn({
let file_map = file_map.clone();
let file_map = hot_reload_state.file_map.clone();
let channels = channels.clone();
let aborted = aborted.clone();
let _ = local_socket_stream.set_nonblocking(true);
@@ -180,6 +153,8 @@ pub async fn serve_hot_reload(config: CrateConfig) -> Result<()> {
}
});
let mut hot_reload_rx = hot_reload_state.messages.subscribe();
while let Ok(template) = hot_reload_rx.recv().await {
let channels = &mut *channels.lock().unwrap();
let mut i = 0;
+78 -122
View File
@@ -9,7 +9,7 @@ use std::{
path::PathBuf,
sync::{Arc, Mutex},
};
use tokio::sync::broadcast::Sender;
use tokio::sync::broadcast::{self};
mod output;
use output::*;
@@ -21,6 +21,7 @@ async fn setup_file_watcher<F: Fn() -> Result<BuildResult> + Send + 'static>(
build_with: F,
config: &CrateConfig,
web_info: Option<WebServerInfo>,
hot_reload: Option<HotReloadState>,
) -> Result<RecommendedWatcher> {
let mut last_update_time = chrono::Local::now().timestamp();
@@ -38,28 +39,81 @@ async fn setup_file_watcher<F: Fn() -> Result<BuildResult> + Send + 'static>(
let config = watcher_config.clone();
if let Ok(e) = info {
if chrono::Local::now().timestamp() > last_update_time {
match build_with() {
Ok(res) => {
last_update_time = chrono::Local::now().timestamp();
let mut needs_full_rebuild;
if let Some(hot_reload) = &hot_reload {
// find changes to the rsx in the file
let mut rsx_file_map = hot_reload.file_map.lock().unwrap();
let mut messages: Vec<Template<'static>> = Vec::new();
#[allow(clippy::redundant_clone)]
print_console_info(
&config,
PrettierOptions {
changed: e.paths.clone(),
warnings: res.warnings,
elapsed_time: res.elapsed_time,
},
web_info.clone(),
);
// In hot reload mode, we only need to rebuild if non-rsx code is changed
needs_full_rebuild = false;
#[cfg(feature = "plugin")]
let _ = PluginManager::on_serve_rebuild(
chrono::Local::now().timestamp(),
e.paths,
);
for path in &e.paths {
// if this is not a rust file, rebuild the whole project
if path.extension().and_then(|p| p.to_str()) != Some("rs") {
needs_full_rebuild = true;
break;
}
match rsx_file_map.update_rsx(path, &config.crate_dir) {
Ok(UpdateResult::UpdatedRsx(msgs)) => {
messages.extend(msgs);
needs_full_rebuild = false;
}
Ok(UpdateResult::NeedsRebuild) => {
needs_full_rebuild = true;
}
Err(err) => {
log::error!("{}", err);
}
}
}
if needs_full_rebuild {
// Reset the file map to the new state of the project
let FileMapBuildResult {
map: new_file_map,
errors,
} = FileMap::<HtmlCtx>::create(config.crate_dir.clone()).unwrap();
for err in errors {
log::error!("{}", err);
}
*rsx_file_map = new_file_map;
} else {
for msg in messages {
let _ = hot_reload.messages.send(msg);
}
}
} else {
needs_full_rebuild = true;
}
if needs_full_rebuild {
match build_with() {
Ok(res) => {
last_update_time = chrono::Local::now().timestamp();
#[allow(clippy::redundant_clone)]
print_console_info(
&config,
PrettierOptions {
changed: e.paths.clone(),
warnings: res.warnings,
elapsed_time: res.elapsed_time,
},
web_info.clone(),
);
#[cfg(feature = "plugin")]
let _ = PluginManager::on_serve_rebuild(
chrono::Local::now().timestamp(),
e.paths,
);
}
Err(e) => log::error!("{}", e),
}
Err(e) => log::error!("{}", e),
}
}
}
@@ -77,106 +131,8 @@ async fn setup_file_watcher<F: Fn() -> Result<BuildResult> + Send + 'static>(
Ok(watcher)
}
// Todo: reduce duplication and merge with setup_file_watcher()
/// Sets up a file watcher with hot reload
async fn setup_file_watcher_hot_reload<F: Fn() -> Result<BuildResult> + Send + 'static>(
config: &CrateConfig,
hot_reload_tx: Sender<Template<'static>>,
file_map: Arc<Mutex<FileMap<HtmlCtx>>>,
build_with: F,
web_info: Option<WebServerInfo>,
) -> Result<RecommendedWatcher> {
// file watcher: check file change
let allow_watch_path = config
.dioxus_config
.web
.watcher
.watch_path
.clone()
.unwrap_or_else(|| vec![PathBuf::from("src")]);
let watcher_config = config.clone();
let mut last_update_time = chrono::Local::now().timestamp();
let mut watcher = RecommendedWatcher::new(
move |evt: notify::Result<notify::Event>| {
let config = watcher_config.clone();
// Give time for the change to take effect before reading the file
std::thread::sleep(std::time::Duration::from_millis(100));
if chrono::Local::now().timestamp() > last_update_time {
if let Ok(evt) = evt {
let mut messages: Vec<Template<'static>> = Vec::new();
for path in evt.paths.clone() {
// if this is not a rust file, rebuild the whole project
if path.extension().and_then(|p| p.to_str()) != Some("rs") {
match build_with() {
Ok(res) => {
print_console_info(
&config,
PrettierOptions {
changed: evt.paths,
warnings: res.warnings,
elapsed_time: res.elapsed_time,
},
web_info.clone(),
);
}
Err(err) => {
log::error!("{}", err);
}
}
return;
}
// find changes to the rsx in the file
let mut map = file_map.lock().unwrap();
match map.update_rsx(&path, &config.crate_dir) {
Ok(UpdateResult::UpdatedRsx(msgs)) => {
messages.extend(msgs);
}
Ok(UpdateResult::NeedsRebuild) => {
match build_with() {
Ok(res) => {
print_console_info(
&config,
PrettierOptions {
changed: evt.paths,
warnings: res.warnings,
elapsed_time: res.elapsed_time,
},
web_info.clone(),
);
}
Err(err) => {
log::error!("{}", err);
}
}
return;
}
Err(err) => {
log::error!("{}", err);
}
}
}
for msg in messages {
let _ = hot_reload_tx.send(msg);
}
}
last_update_time = chrono::Local::now().timestamp();
}
},
notify::Config::default(),
)
.unwrap();
for sub_path in allow_watch_path {
if let Err(err) = watcher.watch(
&config.crate_dir.join(&sub_path),
notify::RecursiveMode::Recursive,
) {
log::error!("error watching {sub_path:?}: \n{}", err);
}
}
Ok(watcher)
#[derive(Clone)]
pub struct HotReloadState {
pub messages: broadcast::Sender<Template<'static>>,
pub file_map: Arc<Mutex<FileMap<HtmlCtx>>>,
}
+2 -14
View File
@@ -1,27 +1,15 @@
use std::sync::{Arc, Mutex};
use axum::{
extract::{ws::Message, WebSocketUpgrade},
response::IntoResponse,
Extension, TypedHeader,
};
use dioxus_core::Template;
use dioxus_html::HtmlCtx;
use dioxus_rsx::hot_reload::FileMap;
use tokio::sync::broadcast;
use crate::CrateConfig;
pub struct HotReloadState {
pub messages: broadcast::Sender<Template<'static>>,
pub file_map: Arc<Mutex<FileMap<HtmlCtx>>>,
pub watcher_config: CrateConfig,
}
use crate::server::HotReloadState;
pub async fn hot_reload_handler(
ws: WebSocketUpgrade,
_: Option<TypedHeader<headers::UserAgent>>,
Extension(state): Extension<Arc<HotReloadState>>,
Extension(state): Extension<HotReloadState>,
) -> impl IntoResponse {
ws.on_upgrade(|mut socket| async move {
log::info!("🔥 Hot Reload WebSocket connected");
+29 -90
View File
@@ -3,7 +3,7 @@ use crate::{
serve::Serve,
server::{
output::{print_console_info, PrettierOptions, WebServerInfo},
setup_file_watcher, setup_file_watcher_hot_reload,
setup_file_watcher, HotReloadState,
},
BuildResult, CrateConfig, Result, WebHttpsConfig,
};
@@ -58,22 +58,41 @@ pub async fn startup(port: u16, config: CrateConfig, start_browser: bool) -> Res
let ip = get_ip().unwrap_or(String::from("0.0.0.0"));
match config.hot_reload {
true => serve_hot_reload(ip, port, config, start_browser).await?,
false => serve_default(ip, port, config, start_browser).await?,
}
let hot_reload_state = match config.hot_reload {
true => {
let FileMapBuildResult { map, errors } =
FileMap::<HtmlCtx>::create(config.crate_dir.clone()).unwrap();
for err in errors {
log::error!("{}", err);
}
let file_map = Arc::new(Mutex::new(map));
let hot_reload_tx = broadcast::channel(100).0;
Some(HotReloadState {
messages: hot_reload_tx.clone(),
file_map: file_map.clone(),
})
}
false => None,
};
serve(ip, port, config, start_browser, hot_reload_state).await?;
Ok(())
}
/// Start the server without hot reload
pub async fn serve_default(
pub async fn serve(
ip: String,
port: u16,
config: CrateConfig,
start_browser: bool,
hot_reload_state: Option<HotReloadState>,
) -> Result<()> {
let first_build_result = crate::builder::build(&config, false)?;
let first_build_result = crate::builder::build(&config, true)?;
log::info!("🚀 Starting development server...");
@@ -93,6 +112,7 @@ pub async fn serve_default(
ip: ip.clone(),
port,
}),
hot_reload_state.clone(),
)
.await?;
@@ -119,88 +139,7 @@ pub async fn serve_default(
);
// Router
let router = setup_router(config, ws_reload_state, None).await?;
// Start server
start_server(port, router, start_browser, rustls_config).await?;
Ok(())
}
/// Start dx serve with hot reload
pub async fn serve_hot_reload(
ip: String,
port: u16,
config: CrateConfig,
start_browser: bool,
) -> Result<()> {
let first_build_result = crate::builder::build(&config, false)?;
log::info!("🚀 Starting development server...");
// Setup hot reload
let (reload_tx, _) = broadcast::channel(100);
let FileMapBuildResult { map, errors } =
FileMap::<HtmlCtx>::create(config.crate_dir.clone()).unwrap();
for err in errors {
log::error!("{}", err);
}
let file_map = Arc::new(Mutex::new(map));
let hot_reload_tx = broadcast::channel(100).0;
// States
let hot_reload_state = Arc::new(HotReloadState {
messages: hot_reload_tx.clone(),
file_map: file_map.clone(),
watcher_config: config.clone(),
});
let ws_reload_state = Arc::new(WsReloadState {
update: reload_tx.clone(),
});
// Setup file watcher
// We got to own watcher so that it exists for the duration of serve
// Otherwise hot reload won't work.
let _watcher = setup_file_watcher_hot_reload(
&config,
hot_reload_tx,
file_map,
{
let config = config.clone();
let reload_tx = reload_tx.clone();
move || build(&config, &reload_tx)
},
Some(WebServerInfo {
ip: ip.clone(),
port,
}),
)
.await?;
// HTTPS
// Before console info so it can stop if mkcert isn't installed or fails
let rustls_config = get_rustls(&config).await?;
// Print serve info
print_console_info(
&config,
PrettierOptions {
changed: vec![],
warnings: first_build_result.warnings,
elapsed_time: first_build_result.elapsed_time,
},
Some(WebServerInfo {
ip: ip.clone(),
port,
}),
);
// Router
let router = setup_router(config, ws_reload_state, Some(hot_reload_state)).await?;
let router = setup_router(config, ws_reload_state, hot_reload_state).await?;
// Start server
start_server(port, router, start_browser, rustls_config).await?;
@@ -291,7 +230,7 @@ fn get_rustls_without_mkcert(web_config: &WebHttpsConfig) -> Result<(String, Str
async fn setup_router(
config: CrateConfig,
ws_reload: Arc<WsReloadState>,
hot_reload: Option<Arc<HotReloadState>>,
hot_reload: Option<HotReloadState>,
) -> Result<Router> {
// Setup cors
let cors = CorsLayer::new()
+2
View File
@@ -17,6 +17,8 @@ proc-macro2 = { version = "1.0" }
quote = "1.0"
syn = { version = "2.0", features = ["full", "extra-traits"] }
dioxus-rsx = { workspace = true }
dioxus-core = { workspace = true }
constcat = "0.3.0"
# testing
[dev-dependencies]
+2 -7
View File
@@ -1,6 +1,5 @@
# dioxus-core-macro
[![Crates.io][crates-badge]][crates-url]
[![MIT licensed][mit-badge]][mit-url]
[![Build Status][actions-badge]][actions-url]
@@ -8,22 +7,18 @@
[crates-badge]: https://img.shields.io/crates/v/dioxus-core-macro.svg
[crates-url]: https://crates.io/crates/dioxus-core-macro
[mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg
[mit-url]: https://github.com/dioxuslabs/dioxus/blob/master/LICENSE
[actions-badge]: https://github.com/dioxuslabs/dioxus/actions/workflows/main.yml/badge.svg
[actions-url]: https://github.com/dioxuslabs/dioxus/actions?query=workflow%3ACI+branch%3Amaster
[discord-badge]: https://img.shields.io/discord/899851952891002890.svg?logo=discord&style=flat-square
[discord-url]: https://discord.gg/XgGxMSkvUM
[Website](https://dioxuslabs.com) |
[Guides](https://dioxuslabs.com/docs/0.3/guide/en/) |
[Guides](https://dioxuslabs.com/learn/0.4/) |
[API Docs](https://docs.rs/dioxus-core-macro/latest/dioxus_core_macro) |
[Chat](https://discord.gg/XgGxMSkvUM)
## Overview
`dioxus-core-macro` provides a handful of helpful macros used by the `dioxus` crate. These include:
@@ -32,13 +27,13 @@
- The `inline_props` macro transforms function arguments into an auto-derived struct
- The `format_args_f` macro which allows f-string formatting with support for expressions
## Contributing
- Report issues on our [issue tracker](https://github.com/dioxuslabs/dioxus/issues).
- Join the discord and ask questions!
## License
This project is licensed under the [MIT license].
[mit license]: https://github.com/DioxusLabs/dioxus/blob/master/LICENSE-MIT
@@ -0,0 +1,237 @@
//! This module is used for parsing a component function into a struct that is subsequently
//! deserialized into something useful using deserializer arguments.
//!
//! Let's break that down with a term glossary and examples which show usage and implementing.
//!
//! # Glossary
//! * `component body` - The [`ComponentBody`] struct. It's used to parse a component function [`proc_macro::TokenStream`]
//! to a reusable struct that deserializers use to modify the token stream.
//! * `deserializer` - A struct that deserializes the [`ComponentBody`] into a [`DeserializerOutput`].
//! It implements the [`DeserializerArgs`] trait, but as you can see, it's called "DeserializerArgs",
//! not "Deserializer". Why?
//! Because "args" makes more sense to the caller of [`ComponentBody::deserialize`], which
//! takes an [`DeserializerArgs`] argument. However, you can think of "DeserializerArgs" as the deserializer.
//! * `deserializer output` - A struct that implements the [`DeserializerOutput`] trait.
//! This struct is what enables deserializers to use each other, since it contains the fields that
//! a deserializer needs to turn a token stream to a different token stream.
//! This means a deserializer can get the output of another deserializer, and use that output,
//! thereby using the functionality of a different deserializer.
//! This struct also implements [`ToTokens`], which means that this is the final stage of the whole process.
//!
//! # Examples
//! *Not all imports might be included.*
//!
//! ## Usage in a procedural macro attribute
//! ```rs,ignore
//! use proc_macro::TokenStream;
//!
//! // Some documentation. You can reuse this in your deserializer structs.
//! /// This attribute changes the name of a component function to whatever the first argument is.
//! #[proc_macro_attribute]
//! pub fn name_changer(args: TokenStream, input: TokenStream) -> TokenStream {
//! // Parse the component body.
//! let component_body = parse_macro_input!(input as ComponentBody);
//!
//! // Parse the first argument, which is going to be the components new name.
//! let new_name: String = match Punctuated::<Path, Token![,]>::parse_terminated.parse(args) {
//! Err(e) => return e.to_compile_error().into(), // Convert to a compile error and return
//! Ok(args) => {
//! // If the argument exists, then convert it to a string
//! if let Some(first) = args.first() {
//! first.to_token_stream().to_string()
//! } else {
//! // If the argument doesn't exist, return an error with the appropriate message.
//! // The "span" is the location of some code.
//! // The error occurred in the "args" token stream, so point the error there.
//! return Error::new(args.span(), "No new name provided").to_compile_error().into();
//! }
//! }
//! };
//!
//! let new_name = &*new_name;
//!
//! // Deserialize the component body to an output with the given args.
//! let output = component_body.deserialize(NameChangerDeserializerArgs { new_name });
//!
//! // Error handling like before, except now you're ready to return the final value.
//! match output {
//! Err(e) => e.to_compile_error().into(),
//! Ok(output) => output.to_token_stream().into(),
//! }
//! }
//! ```
//! ## Using the macro in Dioxus code:
//! ```rs
//! use your_proc_macro_library::name_changer;
//! use dioxus::prelude::*;
//!
//! #[name_changer(CoolName)]
//! pub fn LameName(cx: Scope) -> Element {
//! render! { "I want a cool name!" }
//! }
//!
//! pub fn App(cx: Scope) -> Element {
//! render! { CoolName {} } // Renders: "I want a cool name!"
//! }
//! ```
//! ## Implementing a component body deserializer
//! ```rs
//! use syn::{Result, ItemFn, Signature, Ident};
//! use quote::quote;
//!
//! // Create a list of arguments.
//! // If there was no args, just make it empty. The "args" struct is also the deserializer struct.
//! // For the docs, you can basically copy paste this text and replace "name_changer" with your macro path.
//! // Although unfortunately, the link does not work
//! // Just make sure that your macro is well documented.
//! /// The args and deserializing implementation for the [`name_changer`] macro.
//! #[derive(Clone)]
//! pub struct NameChangerDeserializerArgs<'a> {
//! pub new_name: &'a str,
//! }
//!
//! // Create an output struct.
//! // The ItemFn represents a modified component function.
//! // To read what fields should be here, check out the `DeserializerOutput` struct docs.
//! // For the docs, you can basically copy paste this text and replace "name_changer" with your macro path.
//! // Just make sure that your macro is well documented.
//! /// The output fields and [`ToTokens`] implementation for the [`name_changer`] macro.
//! #[derive(Clone)]
//! pub struct NameChangerDeserializerOutput {
//! pub comp_fn: ItemFn,
//! }
//!
//! // Implement `ToTokens`, which is forced by `DeserializerOutput`.
//! // This will usually be very simple like this, even for complex deserializers.
//! // That's because of the way the `DeserializerOutput` is designed.
//! impl ToTokens for NameChangerDeserializerOutput {
//! fn to_tokens(&self, tokens: &mut TokenStream) {
//! let comp_fn = &self.comp_fn;
//!
//! tokens.append_all(quote! {
//! #comp_fn
//! });
//! }
//! }
//!
//! impl DeserializerOutput for NameChangerDeserializerOutput {}
//!
//! // Implement `DeserializerArgs`. This is the core part of deserializers.
//! impl<'a> DeserializerArgs<NameChangerDeserializerOutput> for NameChangerDeserializerArgs<'a> {
//! fn to_output(&self, component_body: &ComponentBody) -> Result<NameChangerDeserializerOutput> {
//! let old_fn = &component_body.item_fn;
//! let old_sig = &old_fn.sig;
//!
//! // For more complex uses, you will probably use `quote::parse_quote!` in combination with
//! // creating the structs manually.
//! // However, create the structs manually if you can.
//! // It's more reliable, because you only modify a certain struct field
//! // and set the others to be the clone of the original component body.
//! // That ensures that no information will be accidentally removed.
//! let new_sig = Signature {
//! ident: Ident::new(self.new_name, old_sig.ident.span()),
//! ..old_sig.clone()
//! };
//! let new_fn = ItemFn {
//! sig: new_sig,
//! ..old_fn.clone()
//! };
//!
//! Ok(NameChangerDeserializerOutput {
//! comp_fn: new_fn
//! })
//! }
//! ```
pub mod utils;
pub use utils::DeserializerArgs;
pub use utils::DeserializerOutput;
pub use utils::TypeHelper;
use dioxus_core::{Element, Scope};
use syn::parse::{Parse, ParseStream};
use syn::spanned::Spanned;
use syn::*;
/// General struct for parsing a component body.
/// However, because it's ambiguous, it does not implement [`ToTokens`](quote::to_tokens::ToTokens).
///
/// Refer to the [module documentation](crate::component_body) for more.
pub struct ComponentBody {
/// The component function definition. You can parse this back into a [`ComponentBody`].
/// For example, you might modify it, parse it into a [`ComponentBody`], and deserialize that
/// using some deserializer. This is how deserializers use other deserializers.
///
/// **`item_fn.sig.inputs` includes the context argument!**
/// Keep this in mind when creating deserializers, because you often might want to ignore it.
/// That might be annoying, but it would be bad design for this kind of struct to not be parsable from itself.
pub item_fn: ItemFn,
/// Parsing tries to ensure that this argument will be a [`Scope`].
/// **However, macros have limitations that prevent this from always working,
/// so don't take this for granted!**
pub cx_arg: FnArg,
/// The pattern (name) and type of the context argument.
pub cx_pat_type: PatType,
/// If the function has any arguments other than the context.
pub has_extra_args: bool,
}
impl ComponentBody {
/// Deserializes the body into the [`TOutput`] with the specific [`TArgs`].
/// Even if the args are empty, the [`TArg`] type still determines what [`TOutput`] will be generated.
pub fn deserialize<TOutput, TArgs>(&self, args: TArgs) -> Result<TOutput>
where
TOutput: DeserializerOutput,
TArgs: DeserializerArgs<TOutput>,
{
args.to_output(self)
}
}
impl Parse for ComponentBody {
fn parse(input: ParseStream) -> Result<Self> {
let item_fn: ItemFn = input.parse()?;
let scope_type_path = Scope::get_path_string();
let (cx_arg, cx_pat_type) = if let Some(first_arg) = item_fn.sig.inputs.first() {
let incorrect_first_arg_err = Err(Error::new(
first_arg.span(),
format!("First argument must be a <{}>", scope_type_path),
));
match first_arg.to_owned() {
FnArg::Receiver(_) => {
return incorrect_first_arg_err;
}
FnArg::Typed(f) => (first_arg.to_owned(), f),
}
} else {
return Err(Error::new(
item_fn.sig.ident.span(), // Or maybe just item_f.sig.span()?
format!(
"Must have at least one argument that's a <{}>",
scope_type_path
),
));
};
let element_type_path = Element::get_path_string();
if item_fn.sig.output == ReturnType::Default {
return Err(Error::new(
item_fn.sig.output.span(),
format!("Must return a <{}>", element_type_path),
));
}
let has_extra_args = item_fn.sig.inputs.len() > 1;
Ok(Self {
item_fn,
cx_arg,
cx_pat_type,
has_extra_args,
})
}
}
@@ -0,0 +1,57 @@
use crate::component_body::ComponentBody;
use dioxus_core::{Element, Scope};
use quote::ToTokens;
use syn::{parse_quote, Path};
/// The output produced by a deserializer.
///
/// # For implementors
/// Struct field guidelines:
/// * Must be public, so that other deserializers can utilize them.
/// * Should usually be [`Item`]s that you then simply combine in a [`quote!`]
/// in the [`ComponentBodyDeserializer::output_to_token_stream2`] function.
/// * If an [`Item`] might not be included, wrap it in an [`Option`].
/// * Must be at the component function "level"/"context".
/// For example, the [`InlinePropsDeserializer`](crate::component_body_deserializers::inline_props::InlinePropsDeserializer)
/// produces two [`Item`]s; the function but with arguments turned into props, and the props struct.
/// It does not return any [`Item`]s inside the struct or function.
pub trait DeserializerOutput: ToTokens {}
impl<T: ToTokens> DeserializerOutput for T {}
/// The args passed to a [`ComponentBody`] when deserializing it.
///
/// It's also the struct that does the deserializing.
/// It's called "DeserializerArgs", not "Deserializer". Why?
/// Because "args" makes more sense to the caller of [`ComponentBody::deserialize`], which
/// takes an [`DeserializerArgs`] argument. However, you can think of "DeserializerArgs" as the deserializer.
pub trait DeserializerArgs<TOutput>: Clone
where
TOutput: ToTokens,
{
// There's a lot of Results out there... let's make sure that this is a syn::Result.
// Let's also make sure there's not a warning.
/// Creates a [`ToTokens`] struct from the `self` args and a [`ComponentBody`].
/// The [`ComponentBody::deserialize`] provides a cleaner way of calling this function.
#[allow(unused_qualifications)]
fn to_output(&self, component_body: &ComponentBody) -> syn::Result<TOutput>;
}
pub trait TypeHelper {
fn get_path() -> Path;
fn get_path_string() -> String {
Self::get_path().to_token_stream().to_string()
}
}
impl<'a> TypeHelper for Scope<'a> {
fn get_path() -> Path {
parse_quote!(::dioxus::core::Scope)
}
}
impl<'a> TypeHelper for Element<'a> {
fn get_path() -> Path {
parse_quote!(::dioxus::core::Element)
}
}
@@ -0,0 +1,152 @@
use crate::component_body::{ComponentBody, DeserializerArgs};
use crate::component_body_deserializers::inline_props::InlinePropsDeserializerArgs;
use constcat::concat;
use proc_macro2::TokenStream as TokenStream2;
use quote::{quote, ToTokens, TokenStreamExt};
use syn::*;
pub(crate) const COMPONENT_ARG_CASE_CHECK_ERROR: &str = concat!(
"This component does not use PascalCase. \
To ignore this check, pass the \"",
crate::COMPONENT_ARG_CASE_CHECK_OFF,
"\" argument, like so: #[component(",
crate::COMPONENT_ARG_CASE_CHECK_OFF,
")]"
);
const INNER_FN_NAME: &str = "__dx_inner_comp";
fn get_out_comp_fn(orig_comp_fn: &ItemFn, cx_pat: &Pat) -> ItemFn {
let inner_comp_ident = Ident::new(INNER_FN_NAME, orig_comp_fn.sig.ident.span());
let inner_comp_fn = ItemFn {
sig: Signature {
ident: inner_comp_ident.clone(),
..orig_comp_fn.sig.clone()
},
..orig_comp_fn.clone()
};
ItemFn {
block: parse_quote! {
{
#[warn(non_snake_case)]
#[inline(always)]
#inner_comp_fn
#inner_comp_ident (#cx_pat)
}
},
..orig_comp_fn.clone()
}
}
/// The args and deserializing implementation for the [`crate::component`] macro.
#[derive(Clone)]
pub struct ComponentDeserializerArgs {
pub case_check: bool,
}
/// The output fields and [`ToTokens`] implementation for the [`crate::component`] macro.
#[derive(Clone)]
pub struct ComponentDeserializerOutput {
pub comp_fn: ItemFn,
pub props_struct: Option<ItemStruct>,
}
impl ToTokens for ComponentDeserializerOutput {
fn to_tokens(&self, tokens: &mut TokenStream2) {
let comp_fn = &self.comp_fn;
let props_struct = &self.props_struct;
tokens.append_all(quote! {
#props_struct
#[allow(non_snake_case)]
#comp_fn
});
}
}
impl DeserializerArgs<ComponentDeserializerOutput> for ComponentDeserializerArgs {
fn to_output(&self, component_body: &ComponentBody) -> Result<ComponentDeserializerOutput> {
let Signature { ident, .. } = &component_body.item_fn.sig;
if self.case_check && !is_pascal_case(&ident.to_string()) {
return Err(Error::new(ident.span(), COMPONENT_ARG_CASE_CHECK_ERROR));
}
if component_body.has_extra_args {
Self::deserialize_with_props(component_body)
} else {
Ok(Self::deserialize_no_props(component_body))
}
}
}
impl ComponentDeserializerArgs {
fn deserialize_no_props(component_body: &ComponentBody) -> ComponentDeserializerOutput {
let ComponentBody {
item_fn,
cx_pat_type,
..
} = component_body;
let cx_pat = &cx_pat_type.pat;
let comp_fn = get_out_comp_fn(item_fn, cx_pat);
ComponentDeserializerOutput {
comp_fn,
props_struct: None,
}
}
fn deserialize_with_props(
component_body: &ComponentBody,
) -> Result<ComponentDeserializerOutput> {
let ComponentBody {
item_fn,
cx_pat_type,
..
} = component_body;
let cx_pat = &cx_pat_type.pat;
let comp_parsed = match parse2::<ComponentBody>(quote!(#item_fn)) {
Ok(comp_body) => comp_body,
Err(e) => {
return Err(Error::new(
e.span(),
format!(
"This is probably a bug in our code, please report it! Error: {}",
e
),
))
}
};
let inlined_props_output = comp_parsed.deserialize(InlinePropsDeserializerArgs {})?;
let props_struct = inlined_props_output.props_struct;
let props_fn = inlined_props_output.comp_fn;
let comp_fn = get_out_comp_fn(&props_fn, cx_pat);
Ok(ComponentDeserializerOutput {
comp_fn,
props_struct: Some(props_struct),
})
}
}
fn is_pascal_case(input: &str) -> bool {
let mut is_next_lowercase = false;
for c in input.chars() {
let is_upper = c.is_ascii_uppercase();
if (c == '_') || (is_upper && is_next_lowercase) {
return false;
}
is_next_lowercase = is_upper;
}
true
}
@@ -0,0 +1,195 @@
use crate::component_body::{ComponentBody, DeserializerArgs};
use proc_macro2::TokenStream as TokenStream2;
use quote::{quote, ToTokens, TokenStreamExt};
use syn::token::Comma;
use syn::{punctuated::Punctuated, *};
/// The args and deserializing implementation for the [`crate::inline_props`] macro.
#[derive(Clone)]
pub struct InlinePropsDeserializerArgs;
/// The output fields and [`ToTokens`] implementation for the [`crate::inline_props`] macro.
#[derive(Clone)]
pub struct InlinePropsDeserializerOutput {
pub comp_fn: ItemFn,
pub props_struct: ItemStruct,
}
impl ToTokens for InlinePropsDeserializerOutput {
fn to_tokens(&self, tokens: &mut TokenStream2) {
let function = &self.comp_fn;
let props_struct = &self.props_struct;
tokens.append_all(quote! {
#function
#props_struct
});
}
}
impl DeserializerArgs<InlinePropsDeserializerOutput> for InlinePropsDeserializerArgs {
fn to_output(&self, component_body: &ComponentBody) -> Result<InlinePropsDeserializerOutput> {
Ok(InlinePropsDeserializerOutput {
comp_fn: Self::get_function(component_body),
props_struct: Self::get_props_struct(component_body),
})
}
}
impl InlinePropsDeserializerArgs {
fn get_props_struct(component_body: &ComponentBody) -> ItemStruct {
let ComponentBody { item_fn, .. } = component_body;
let ItemFn { vis, sig, .. } = item_fn;
let Signature {
inputs,
ident: fn_ident,
generics,
..
} = sig;
// Skip first arg since that's the context
let struct_fields = inputs.iter().skip(1).map(move |f| {
match f {
FnArg::Receiver(_) => unreachable!(), // Unreachable because of ComponentBody parsing
FnArg::Typed(pt) => {
let arg_pat = &pt.pat; // Pattern (identifier)
let arg_colon = &pt.colon_token;
let arg_ty = &pt.ty; // Type
let arg_attrs = &pt.attrs; // Attributes
quote! {
#(#arg_attrs)
*
#vis #arg_pat #arg_colon #arg_ty
}
}
}
});
let struct_ident = Ident::new(&format!("{fn_ident}Props"), fn_ident.span());
let first_lifetime = if let Some(GenericParam::Lifetime(lt)) = generics.params.first() {
Some(lt)
} else {
None
};
let struct_attrs = if first_lifetime.is_some() {
quote! { #[derive(Props)] }
} else {
quote! { #[derive(Props, PartialEq)] }
};
let struct_generics = if first_lifetime.is_some() {
let struct_generics: Punctuated<GenericParam, Comma> = component_body
.item_fn
.sig
.generics
.params
.iter()
.map(|it| match it {
GenericParam::Type(tp) => {
let mut tp = tp.clone();
tp.bounds.push(parse_quote!( 'a ));
GenericParam::Type(tp)
}
_ => it.clone(),
})
.collect();
quote! { <#struct_generics> }
} else {
quote! { #generics }
};
parse_quote! {
#struct_attrs
#[allow(non_camel_case_types)]
#vis struct #struct_ident #struct_generics
{
#(#struct_fields),*
}
}
}
fn get_function(component_body: &ComponentBody) -> ItemFn {
let ComponentBody {
item_fn,
cx_pat_type,
..
} = component_body;
let ItemFn {
attrs: fn_attrs,
vis,
sig,
block: fn_block,
} = item_fn;
let Signature {
inputs,
ident: fn_ident,
generics,
output: fn_output,
asyncness,
..
} = sig;
let Generics { where_clause, .. } = generics;
let cx_pat = &cx_pat_type.pat;
let struct_ident = Ident::new(&format!("{fn_ident}Props"), fn_ident.span());
// Skip first arg since that's the context
let struct_field_names = inputs.iter().skip(1).filter_map(|f| match f {
FnArg::Receiver(_) => unreachable!(), // ComponentBody prohibits receiver parameters.
FnArg::Typed(t) => Some(&t.pat),
});
let first_lifetime = if let Some(GenericParam::Lifetime(lt)) = generics.params.first() {
Some(lt)
} else {
None
};
let (scope_lifetime, fn_generics) = if let Some(lt) = first_lifetime {
(quote! { #lt, }, generics.clone())
} else {
let lifetime: LifetimeParam = parse_quote! { 'a };
let mut fn_generics = generics.clone();
fn_generics
.params
.insert(0, GenericParam::Lifetime(lifetime.clone()));
(quote! { #lifetime, }, fn_generics)
};
let generics_no_bounds = {
let mut generics = generics.clone();
generics.params = generics
.params
.iter()
.map(|it| match it {
GenericParam::Type(tp) => {
let mut tp = tp.clone();
tp.bounds.clear();
GenericParam::Type(tp)
}
_ => it.clone(),
})
.collect();
generics
};
parse_quote! {
#(#fn_attrs)*
#asyncness #vis fn #fn_ident #fn_generics (#cx_pat: Scope<#scope_lifetime #struct_ident #generics_no_bounds>) #fn_output
#where_clause
{
let #struct_ident { #(#struct_field_names),* } = &#cx_pat.props;
#fn_block
}
}
}
}
@@ -0,0 +1,4 @@
//! This module contains all [`ComponentBody`](crate::component_body::ComponentBody) deserializers.
pub mod component;
pub mod inline_props;
-185
View File
@@ -1,185 +0,0 @@
use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::{quote, ToTokens, TokenStreamExt};
use syn::{
parse::{Parse, ParseStream},
punctuated::Punctuated,
*,
};
pub struct InlinePropsBody {
pub attrs: Vec<Attribute>,
pub vis: syn::Visibility,
pub maybe_async: Option<Token![async]>,
pub fn_token: Token![fn],
pub ident: Ident,
pub cx_token: Box<Pat>,
pub generics: Generics,
pub paren_token: token::Paren,
pub inputs: Punctuated<FnArg, Token![,]>,
// pub fields: FieldsNamed,
pub output: ReturnType,
pub where_clause: Option<WhereClause>,
pub block: Box<Block>,
}
/// The custom rusty variant of parsing rsx!
impl Parse for InlinePropsBody {
fn parse(input: ParseStream) -> Result<Self> {
let attrs: Vec<Attribute> = input.call(Attribute::parse_outer)?;
let maybe_async: Option<Token![async]> = input.parse().ok();
let vis: Visibility = input.parse()?;
let fn_token = input.parse()?;
let ident = input.parse()?;
let generics: Generics = input.parse()?;
let content;
let paren_token = syn::parenthesized!(content in input);
let first_arg: FnArg = content.parse()?;
let cx_token = {
match first_arg {
FnArg::Receiver(_) => panic!("first argument must not be a receiver argument"),
FnArg::Typed(f) => f.pat,
}
};
let _: Result<Token![,]> = content.parse();
let inputs = syn::punctuated::Punctuated::parse_terminated(&content)?;
let output = input.parse()?;
let where_clause = input
.peek(syn::token::Where)
.then(|| input.parse())
.transpose()?;
let block = input.parse()?;
Ok(Self {
vis,
maybe_async,
fn_token,
ident,
generics,
paren_token,
inputs,
output,
where_clause,
block,
cx_token,
attrs,
})
}
}
/// Serialize the same way, regardless of flavor
impl ToTokens for InlinePropsBody {
fn to_tokens(&self, out_tokens: &mut TokenStream2) {
let Self {
vis,
ident,
generics,
inputs,
output,
where_clause,
block,
cx_token,
attrs,
maybe_async,
..
} = self;
let fields = inputs.iter().map(|f| {
quote! { #vis #f }
});
let struct_name = Ident::new(&format!("{ident}Props"), Span::call_site());
let field_names = inputs.iter().filter_map(|f| match f {
FnArg::Receiver(_) => todo!(),
FnArg::Typed(t) => Some(&t.pat),
});
let first_lifetime = if let Some(GenericParam::Lifetime(lt)) = generics.params.first() {
Some(lt)
} else {
None
};
let modifiers = if first_lifetime.is_some() {
quote! { #[derive(Props)] }
} else {
quote! { #[derive(Props, PartialEq)] }
};
let (scope_lifetime, fn_generics, struct_generics) = if let Some(lt) = first_lifetime {
let struct_generics: Punctuated<_, token::Comma> = generics
.params
.iter()
.map(|it| match it {
GenericParam::Type(tp) => {
let mut tp = tp.clone();
tp.bounds.push(parse_quote!( 'a ));
GenericParam::Type(tp)
}
_ => it.clone(),
})
.collect();
(
quote! { #lt, },
generics.clone(),
quote! { <#struct_generics> },
)
} else {
let lifetime: LifetimeParam = parse_quote! { 'a };
let mut fn_generics = generics.clone();
fn_generics
.params
.insert(0, GenericParam::Lifetime(lifetime.clone()));
(quote! { #lifetime, }, fn_generics, quote! { #generics })
};
let generics_no_bounds = {
let mut generics = generics.clone();
generics.params = generics
.params
.iter()
.map(|it| match it {
GenericParam::Type(tp) => {
let mut tp = tp.clone();
tp.bounds.clear();
GenericParam::Type(tp)
}
_ => it.clone(),
})
.collect();
generics
};
out_tokens.append_all(quote! {
#modifiers
#[allow(non_camel_case_types)]
#vis struct #struct_name #struct_generics
#where_clause
{
#(#fields),*
}
#(#attrs)*
#maybe_async #vis fn #ident #fn_generics (#cx_token: Scope<#scope_lifetime #struct_name #generics_no_bounds>) #output
#where_clause
{
let #struct_name { #(#field_names),* } = &#cx_token.props;
#block
}
});
}
}
+123 -8
View File
@@ -1,12 +1,18 @@
use proc_macro::TokenStream;
use quote::ToTokens;
use rsx::RenderCallBody;
use syn::parse_macro_input;
use syn::parse::Parser;
use syn::punctuated::Punctuated;
use syn::{parse_macro_input, Path, Token};
mod inlineprops;
mod component_body;
mod component_body_deserializers;
mod props;
// mod rsx;
use crate::component_body::ComponentBody;
use crate::component_body_deserializers::component::ComponentDeserializerArgs;
use crate::component_body_deserializers::inline_props::InlinePropsDeserializerArgs;
use dioxus_rsx as rsx;
#[proc_macro]
@@ -18,7 +24,7 @@ pub fn format_args_f(input: TokenStream) -> TokenStream {
}
#[proc_macro_derive(Props, attributes(props))]
pub fn derive_typed_builder(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
pub fn derive_typed_builder(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as syn::DeriveInput);
match props::impl_my_derive(&input) {
Ok(output) => output.into(),
@@ -37,7 +43,7 @@ pub fn rsx(s: TokenStream) -> TokenStream {
/// The render! macro makes it easy for developers to write jsx-style markup in their components.
///
/// The render macro automatically renders rsx - making it unhygenic.
/// The render macro automatically renders rsx - making it unhygienic.
#[proc_macro]
pub fn render(s: TokenStream) -> TokenStream {
match syn::parse::<rsx::CallBody>(s) {
@@ -55,7 +61,7 @@ pub fn render(s: TokenStream) -> TokenStream {
/// you would be repeating a lot of the usual Rust boilerplate.
///
/// # Example
/// ```ignore
/// ```rust,ignore
/// #[inline_props]
/// fn app(cx: Scope, bob: String) -> Element {
/// cx.render(rsx!("hello, {bob}"))
@@ -73,9 +79,118 @@ pub fn render(s: TokenStream) -> TokenStream {
/// }
/// ```
#[proc_macro_attribute]
pub fn inline_props(_args: proc_macro::TokenStream, s: TokenStream) -> TokenStream {
match syn::parse::<inlineprops::InlinePropsBody>(s) {
#[deprecated(note = "Use `#[component]` instead.")]
pub fn inline_props(_args: TokenStream, s: TokenStream) -> TokenStream {
let comp_body = parse_macro_input!(s as ComponentBody);
match comp_body.deserialize(InlinePropsDeserializerArgs {}) {
Err(e) => e.to_compile_error().into(),
Ok(s) => s.to_token_stream().into(),
Ok(output) => output.to_token_stream().into(),
}
}
pub(crate) const COMPONENT_ARG_CASE_CHECK_OFF: &str = "no_case_check";
/// Streamlines component creation.
/// This is the recommended way of creating components,
/// though you might want lower-level control with more advanced uses.
///
/// # Arguments
/// * `no_case_check` - Doesn't enforce `PascalCase` on your component names.
/// **This will be removed/deprecated in a future update in favor of a more complete Clippy-backed linting system.**
/// The reasoning behind this is that Clippy allows more robust and powerful lints, whereas
/// macros are extremely limited.
///
/// # Features
/// This attribute:
/// * Enforces that your component uses `PascalCase`.
/// No warnings are generated for the `PascalCase`
/// function name, but everything else will still raise a warning if it's incorrectly `PascalCase`.
/// Does not disable warnings anywhere else, so if you, for example,
/// accidentally don't use `snake_case`
/// for a variable name in the function, the compiler will still warn you.
/// * Automatically uses `#[inline_props]` if there's more than 1 parameter in the function.
/// * Verifies the validity of your component.
/// E.g. if it has a [`Scope`](dioxus_core::Scope) argument.
/// Notes:
/// * This doesn't work 100% of the time, because of macro limitations.
/// * Provides helpful messages if your component is not correct.
/// Possible bugs (please, report these!):
/// * There might be bugs where it incorrectly *denies* validity.
/// This is bad as it means that you can't use the attribute or you have to change the component.
/// * There might be bugs where it incorrectly *confirms* validity.
/// You will still know if the component is invalid once you use it,
/// but the error might be less helpful.
///
/// # Examples
/// * Without props:
/// ```rust,ignore
/// #[component]
/// fn GreetBob(cx: Scope) -> Element {
/// render! { "hello, bob" }
/// }
///
/// // is equivalent to
///
/// #[allow(non_snake_case)]
/// fn GreetBob(cx: Scope) -> Element {
/// #[warn(non_snake_case)]
/// #[inline(always)]
/// fn __dx_inner_comp(cx: Scope) -> Element {
/// render! { "hello, bob" }
/// }
/// // There's no function call overhead since __dx_inner_comp has the #[inline(always)] attribute,
/// // so don't worry about performance.
/// __dx_inner_comp(cx)
/// }
/// ```
/// * With props:
/// ```rust,ignore
/// #[component(no_case_check)]
/// fn GreetPerson(cx: Scope, person: String) -> Element {
/// render! { "hello, {person}" }
/// }
///
/// // is equivalent to
///
/// #[derive(Props, PartialEq)]
/// #[allow(non_camel_case_types)]
/// struct GreetPersonProps {
/// person: String,
/// }
///
/// #[allow(non_snake_case)]
/// fn GreetPerson<'a>(cx: Scope<'a, GreetPersonProps>) -> Element {
/// #[warn(non_snake_case)]
/// #[inline(always)]
/// fn __dx_inner_comp<'a>(cx: Scope<'a, GreetPersonProps>e) -> Element {
/// let GreetPersonProps { person } = &cx.props;
/// {
/// render! { "hello, {person}" }
/// }
/// }
///
/// __dx_inner_comp(cx)
/// }
/// ```
// TODO: Maybe add an option to input a custom component name through the args.
// I think that's unnecessary, but there might be some scenario where it could be useful.
#[proc_macro_attribute]
pub fn component(args: TokenStream, input: TokenStream) -> TokenStream {
let component_body = parse_macro_input!(input as ComponentBody);
let case_check = match Punctuated::<Path, Token![,]>::parse_terminated.parse(args) {
Err(e) => return e.to_compile_error().into(),
Ok(args) => {
if let Some(first) = args.first() {
!first.is_ident(COMPONENT_ARG_CASE_CHECK_OFF)
} else {
true
}
}
};
match component_body.deserialize(ComponentDeserializerArgs { case_check }) {
Err(e) => e.to_compile_error().into(),
Ok(output) => output.to_token_stream().into(),
}
}
+29 -26
View File
@@ -2,9 +2,9 @@
//!
//! However, it has been adopted to fit the Dioxus Props builder pattern.
//!
//! For dioxus, we make a few changes:
//! - [ ] automatically implement Into<Option> on the setters (IE the strip setter option)
//! - [ ] automatically implement a default of none for optional fields (those explicitly wrapped with Option<T>)
//! For Dioxus, we make a few changes:
//! - [ ] Automatically implement Into<Option> on the setters (IE the strip setter option)
//! - [ ] Automatically implement a default of none for optional fields (those explicitly wrapped with Option<T>)
use proc_macro2::TokenStream;
@@ -194,8 +194,9 @@ mod field_info {
// children field is automatically defaulted to None
if name == "children" {
builder_attr.default =
Some(syn::parse(quote!(Default::default()).into()).unwrap());
builder_attr.default = Some(
syn::parse(quote!(::core::default::Default::default()).into()).unwrap(),
);
}
// auto detect optional
@@ -204,8 +205,9 @@ mod field_info {
&& type_from_inside_option(&field.ty, true).is_some();
if !builder_attr.strip_option && strip_option_auto {
builder_attr.strip_option = true;
builder_attr.default =
Some(syn::parse(quote!(Default::default()).into()).unwrap());
builder_attr.default = Some(
syn::parse(quote!(::core::default::Default::default()).into()).unwrap(),
);
}
Ok(FieldInfo {
@@ -213,7 +215,7 @@ mod field_info {
name,
generic_ident: syn::Ident::new(
&format!("__{}", strip_raw_ident_prefix(name.to_string())),
proc_macro2::Span::call_site(),
name.span(),
),
ty: &field.ty,
builder_attr,
@@ -345,14 +347,18 @@ mod field_info {
.ok_or_else(|| Error::new_spanned(&path, "Expected identifier"))?;
match name.as_str() {
"default" => {
self.default =
Some(syn::parse(quote!(Default::default()).into()).unwrap());
self.default = Some(
syn::parse(quote!(::core::default::Default::default()).into())
.unwrap(),
);
Ok(())
}
"optional" => {
self.default =
Some(syn::parse(quote!(Default::default()).into()).unwrap());
self.default = Some(
syn::parse(quote!(::core::default::Default::default()).into())
.unwrap(),
);
self.strip_option = true;
Ok(())
}
@@ -505,15 +511,12 @@ mod struct_info {
.map(|(i, f)| FieldInfo::new(i, f, builder_attr.field_defaults.clone()))
.collect::<Result<_, _>>()?,
builder_attr,
builder_name: syn::Ident::new(&builder_name, proc_macro2::Span::call_site()),
builder_name: syn::Ident::new(&builder_name, ast.ident.span()),
conversion_helper_trait_name: syn::Ident::new(
&format!("{builder_name}_Optional"),
proc_macro2::Span::call_site(),
),
core: syn::Ident::new(
&format!("{builder_name}_core"),
proc_macro2::Span::call_site(),
ast.ident.span(),
),
core: syn::Ident::new(&format!("{builder_name}_core"), ast.ident.span()),
})
}
@@ -551,11 +554,11 @@ mod struct_info {
let phantom_generics = self.generics.params.iter().map(|param| match param {
syn::GenericParam::Lifetime(lifetime) => {
let lifetime = &lifetime.lifetime;
quote!(core::marker::PhantomData<&#lifetime ()>)
quote!(::core::marker::PhantomData<&#lifetime ()>)
}
syn::GenericParam::Type(ty) => {
let ty = &ty.ident;
quote!(core::marker::PhantomData<#ty>)
quote!(::core::marker::PhantomData<#ty>)
}
syn::GenericParam::Const(_cnst) => {
quote!()
@@ -634,7 +637,7 @@ Finally, call `.build()` to create the instance of `{name}`.
#vis fn builder() -> #builder_name #generics_with_empty {
#builder_name {
fields: #empties_tuple,
_phantom: core::default::Default::default(),
_phantom: ::core::default::Default::default(),
}
}
}
@@ -651,12 +654,12 @@ Finally, call `.build()` to create the instance of `{name}`.
fn clone(&self) -> Self {
Self {
fields: self.fields.clone(),
_phantom: Default::default(),
_phantom: ::core::default::Default::default(),
}
}
}
impl #impl_generics dioxus::prelude::Properties for #name #ty_generics
impl #impl_generics ::dioxus::prelude::Properties for #name #ty_generics
#b_generics_where_extras_predicates
{
type Builder = #builder_name #generics_with_empty;
@@ -793,7 +796,7 @@ Finally, call `.build()` to create the instance of `{name}`.
};
let (arg_type, arg_expr) = if field.builder_attr.auto_into {
(
quote!(impl core::convert::Into<#arg_type>),
quote!(impl ::core::convert::Into<#arg_type>),
quote!(#field_name.into()),
)
} else {
@@ -811,7 +814,7 @@ Finally, call `.build()` to create the instance of `{name}`.
builder_name,
strip_raw_ident_prefix(field_name.to_string())
),
proc_macro2::Span::call_site(),
builder_name.span(),
);
let repeated_fields_error_message = format!("Repeated field {field_name}");
@@ -930,7 +933,7 @@ Finally, call `.build()` to create the instance of `{name}`.
builder_name,
strip_raw_ident_prefix(field_name.to_string())
),
proc_macro2::Span::call_site(),
builder_name.span(),
);
let early_build_error_message = format!("Missing required field {field_name}");
+1 -1
View File
@@ -28,7 +28,7 @@ slab = { workspace = true }
futures-channel = { workspace = true }
smallbox = "0.8.1"
log = { workspace = true }
tracing = { workspace = true }
# Serialize the Edits for use in Webview/Liveview instances
serde = { version = "1", features = ["derive"], optional = true }
@@ -0,0 +1,24 @@
use dioxus::prelude::*;
fn main() {}
fn app(cx: Scope) -> Element {
let count = vec![1, 2, 3];
render! {
unsafe_child_component {
borrowed: &count
}
}
}
#[derive(Props)]
struct Testing<'a> {
borrowed: &'a Vec<u32>,
}
fn unsafe_child_component<'a>(cx: Scope<'a, Testing<'a>>) -> Element<'a> {
cx.render(rsx! {
div { "{cx.props.borrowed:?}" }
})
}
@@ -0,0 +1,12 @@
error[E0515]: cannot return value referencing local variable `count`
--> compile_tests/props_safety_temporary_values.rs:8:5
|
8 | / render! {
9 | | unsafe_child_component {
10 | | borrowed: &count
| | ------ `count` is borrowed here
11 | | }
12 | | }
| |_____^ returns a value referencing data owned by the current function
|
= note: this error originates in the macro `render` (in Nightly builds, run with -Z macro-backtrace for more info)
+1 -1
View File
@@ -68,7 +68,7 @@ unsafe impl<'a, P> AnyProps<'a> for VProps<'a, P> {
Ok(None) => RenderReturn::default(),
Err(err) => {
let component_name = cx.name();
log::error!("Error while rendering component `{component_name}`: {err:?}");
tracing::error!("Error while rendering component `{component_name}`: {err:?}");
RenderReturn::default()
}
}
+2 -2
View File
@@ -35,7 +35,7 @@ impl ElementRef {
Self {
template: None,
path: ElementPath::Root(0),
scope: ScopeId(0),
scope: ScopeId::ROOT,
}
}
}
@@ -60,7 +60,7 @@ impl VirtualDom {
fn next_reference(&mut self, template: &VNode, path: ElementPath) -> ElementId {
let entry = self.elements.vacant_entry();
let id = entry.key();
let scope = self.runtime.current_scope_id().unwrap_or(ScopeId(0));
let scope = self.runtime.current_scope_id().unwrap_or(ScopeId::ROOT);
entry.insert(ElementRef {
// We know this is non-null because it comes from a reference
+8 -3
View File
@@ -196,7 +196,8 @@ impl<'b> VirtualDom {
right.scope.set(Some(scope_id));
// copy out the box for both
let old = self.scopes[scope_id.0].props.as_ref();
let old_scope = &self.scopes[scope_id.0];
let old = old_scope.props.as_ref();
let new: Box<dyn AnyProps> = right.props.take().unwrap();
let new: Box<dyn AnyProps> = unsafe { std::mem::transmute(new) };
@@ -204,6 +205,11 @@ impl<'b> VirtualDom {
// The target scopestate still has the reference to the old props, so there's no need to update anything
// This also implicitly drops the new props since they're not used
if left.static_props && unsafe { old.as_ref().unwrap().memoize(new.as_ref()) } {
tracing::trace!(
"Memoized props for component {:#?} ({})",
scope_id,
old_scope.context().name
);
return;
}
@@ -577,8 +583,7 @@ impl<'b> VirtualDom {
}
// 4. Compute the LIS of this list
let mut lis_sequence = Vec::default();
lis_sequence.reserve(new_index_to_old_index.len());
let mut lis_sequence = Vec::with_capacity(new_index_to_old_index.len());
let mut predecessors = vec![0; new_index_to_old_index.len()];
let mut starts = vec![0; new_index_to_old_index.len()];
+12 -15
View File
@@ -49,17 +49,16 @@ impl ErrorBoundary {
/// A trait to allow results to be thrown upwards to the nearest Error Boundary
///
/// The canonical way of using this trait is to throw results from hooks, aborting rendering
/// through question mark synax. The throw method returns an option that evalutes to None
/// through question mark syntax. The throw method returns an option that evaluates to None
/// if there is an error, injecting the error to the nearest error boundary.
///
/// If the value is `Ok`, then throw returns the value, not aborting the rendering preocess.
/// If the value is `Ok`, then throw returns the value, not aborting the rendering process.
///
/// The call stack is saved for this component and provided to the error boundary
///
/// ```rust, ignore
///
/// #[inline_props]
/// fn app(cx: Scope, count: String) -> Element {
/// #[component]
/// fn App(cx: Scope, count: String) -> Element {
/// let id: i32 = count.parse().throw(cx)?;
///
/// cx.render(rsx! {
@@ -71,9 +70,9 @@ pub trait Throw<S = ()>: Sized {
/// The value that will be returned in if the given value is `Ok`.
type Out;
/// Returns an option that evalutes to None if there is an error, injecting the error to the nearest error boundary.
/// Returns an option that evaluates to None if there is an error, injecting the error to the nearest error boundary.
///
/// If the value is `Ok`, then throw returns the value, not aborting the rendering preocess.
/// If the value is `Ok`, then throw returns the value, not aborting the rendering process.
///
/// The call stack is saved for this component and provided to the error boundary
///
@@ -83,9 +82,8 @@ pub trait Throw<S = ()>: Sized {
///
///
/// ```rust, ignore
///
/// #[inline_props]
/// fn app(cx: Scope, count: String) -> Element {
/// #[component]
/// fn App(cx: Scope, count: String) -> Element {
/// let id: i32 = count.parse().throw(cx)?;
///
/// cx.render(rsx! {
@@ -95,9 +93,9 @@ pub trait Throw<S = ()>: Sized {
/// ```
fn throw(self, cx: &ScopeState) -> Option<Self::Out>;
/// Returns an option that evalutes to None if there is an error, injecting the error to the nearest error boundary.
/// Returns an option that evaluates to None if there is an error, injecting the error to the nearest error boundary.
///
/// If the value is `Ok`, then throw returns the value, not aborting the rendering preocess.
/// If the value is `Ok`, then throw returns the value, not aborting the rendering process.
///
/// The call stack is saved for this component and provided to the error boundary
///
@@ -107,9 +105,8 @@ pub trait Throw<S = ()>: Sized {
///
///
/// ```rust, ignore
///
/// #[inline_props]
/// fn app(cx: Scope, count: String) -> Element {
/// #[component]
/// fn App(cx: Scope, count: String) -> Element {
/// let id: i32 = count.parse().throw(cx)?;
///
/// cx.render(rsx! {
+2 -2
View File
@@ -118,7 +118,7 @@ impl<T: std::fmt::Debug> std::fmt::Debug for Event<T> {
///
/// ```rust, ignore
/// rsx!{
/// MyComponent { onclick: move |evt| log::info!("clicked") }
/// MyComponent { onclick: move |evt| tracing::debug!("clicked") }
/// }
///
/// #[derive(Props)]
@@ -143,7 +143,7 @@ pub struct EventHandler<'bump, T = ()> {
impl<T> Default for EventHandler<'_, T> {
fn default() -> Self {
Self {
origin: ScopeId(0),
origin: ScopeId::ROOT,
callback: Default::default(),
}
}
+3 -2
View File
@@ -32,6 +32,7 @@ pub(crate) mod innerlude {
pub use crate::nodes::RenderReturn;
pub use crate::nodes::*;
pub use crate::properties::*;
pub use crate::runtime::{Runtime, RuntimeGuard};
pub use crate::scheduler::*;
pub use crate::scope_context::*;
pub use crate::scopes::*;
@@ -89,8 +90,8 @@ pub mod prelude {
provide_context, provide_context_to_scope, provide_root_context, push_future,
remove_future, schedule_update_any, spawn, spawn_forever, suspend, throw, AnyValue,
Component, Element, Event, EventHandler, Fragment, IntoAttributeValue, LazyNodes,
Properties, Scope, ScopeId, ScopeState, Scoped, TaskId, Template, TemplateAttribute,
TemplateNode, Throw, VNode, VirtualDom,
Properties, Runtime, RuntimeGuard, Scope, ScopeId, ScopeState, Scoped, TaskId, Template,
TemplateAttribute, TemplateNode, Throw, VNode, VirtualDom,
};
}
+2 -2
View File
@@ -691,7 +691,7 @@ impl<'a> IntoDynNode<'a> for &Element<'a> {
impl<'a, 'b> IntoDynNode<'a> for LazyNodes<'a, 'b> {
fn into_vnode(self, cx: &'a ScopeState) -> DynamicNode<'a> {
DynamicNode::Fragment(cx.bump().alloc([self.call(cx)]))
DynamicNode::Fragment(cx.bump().alloc([cx.render(self).unwrap()]))
}
}
@@ -750,7 +750,7 @@ impl<'a> IntoTemplate<'a> for Element<'a> {
}
impl<'a, 'b> IntoTemplate<'a> for LazyNodes<'a, 'b> {
fn into_template(self, cx: &'a ScopeState) -> VNode<'a> {
self.call(cx)
cx.render(self).unwrap()
}
}
+1
View File
@@ -79,4 +79,5 @@ pub fn fc_to_builder<'a, T: Properties + 'a>(_: fn(Scope<'a, T>) -> Element<'a>)
fn unsafe_props_fail() {
let t = trybuild::TestCases::new();
t.compile_fail("compile_tests/props_safety.rs");
t.compile_fail("compile_tests/props_safety_temporary_values.rs");
}
+43 -5
View File
@@ -41,7 +41,8 @@ where
.flatten()
}
pub(crate) struct Runtime {
/// A global runtime that is shared across all scopes that provides the async runtime and context API
pub struct Runtime {
pub(crate) scope_contexts: RefCell<Vec<Option<ScopeContext>>>,
pub(crate) scheduler: Rc<Scheduler>,
@@ -63,6 +64,11 @@ impl Runtime {
})
}
/// Get the current runtime
pub fn current() -> Option<Rc<Self>> {
RUNTIMES.with(|stack| stack.borrow().last().cloned())
}
/// Create a scope context. This slab is synchronized with the scope slab.
pub(crate) fn create_context_at(&self, id: ScopeId, context: ScopeContext) {
let mut contexts = self.scope_contexts.borrow_mut();
@@ -77,14 +83,14 @@ impl Runtime {
}
/// Get the current scope id
pub fn current_scope_id(&self) -> Option<ScopeId> {
pub(crate) fn current_scope_id(&self) -> Option<ScopeId> {
self.scope_stack.borrow().last().copied()
}
/// Get the context for any scope given its ID
///
/// This is useful for inserting or removing contexts from a scope, or rendering out its root node
pub fn get_context(&self, id: ScopeId) -> Option<Ref<'_, ScopeContext>> {
pub(crate) fn get_context(&self, id: ScopeId) -> Option<Ref<'_, ScopeContext>> {
Ref::filter_map(self.scope_contexts.borrow(), |contexts| {
contexts.get(id.0).and_then(|f| f.as_ref())
})
@@ -92,10 +98,42 @@ impl Runtime {
}
}
pub(crate) struct RuntimeGuard(Rc<Runtime>);
/// A gaurd for a new runtime. This must be used to override the current runtime when importing components from a dynamic library that has it's own runtime.
///
/// ```rust
/// use dioxus::prelude::*;
///
/// fn main() {
/// let virtual_dom = VirtualDom::new(app);
/// }
///
/// fn app(cx: Scope) -> Element {
/// render!{ Component { runtime: Runtime::current().unwrap() } }
/// }
///
/// // In a dynamic library
/// #[derive(Props)]
/// struct ComponentProps {
/// runtime: std::rc::Rc<Runtime>,
/// }
///
/// impl PartialEq for ComponentProps {
/// fn eq(&self, _other: &Self) -> bool {
/// true
/// }
/// }
///
/// fn Component(cx: Scope<ComponentProps>) -> Element {
/// cx.use_hook(|| RuntimeGuard::new(cx.props.runtime.clone()));
///
/// render! { div {} }
/// }
/// ```
pub struct RuntimeGuard(Rc<Runtime>);
impl RuntimeGuard {
pub(crate) fn new(runtime: Rc<Runtime>) -> Self {
/// Create a new runtime guard that sets the current Dioxus runtime. The runtime will be reset when the guard is dropped
pub fn new(runtime: Rc<Runtime>) -> Self {
push_runtime(runtime.clone());
Self(runtime)
}
+1
View File
@@ -64,6 +64,7 @@ impl VirtualDom {
let props: &dyn AnyProps = scope.props.as_ref().unwrap().as_ref();
let props: &dyn AnyProps = std::mem::transmute(props);
let _span = tracing::trace_span!("render", scope = %scope.context().name);
props.render(scope).extend_lifetime()
};
+36 -9
View File
@@ -107,20 +107,30 @@ impl ScopeContext {
///
/// Clones the state if it exists.
pub fn consume_context<T: 'static + Clone>(&self) -> Option<T> {
tracing::trace!(
"looking for context {} ({:?}) in {}",
std::any::type_name::<T>(),
std::any::TypeId::of::<T>(),
self.name
);
if let Some(this_ctx) = self.has_context() {
return Some(this_ctx);
}
let mut search_parent = self.parent_id;
with_runtime(|runtime| {
match with_runtime(|runtime: &crate::runtime::Runtime| {
while let Some(parent_id) = search_parent {
let parent = runtime.get_context(parent_id).unwrap();
if let Some(shared) = parent
.shared_contexts
.borrow()
.iter()
.find_map(|any| any.downcast_ref::<T>())
{
tracing::trace!(
"looking for context {} ({:?}) in {}",
std::any::type_name::<T>(),
std::any::TypeId::of::<T>(),
parent.name
);
if let Some(shared) = parent.shared_contexts.borrow().iter().find_map(|any| {
tracing::trace!("found context {:?}", any.type_id());
any.downcast_ref::<T>()
}) {
return Some(shared.clone());
}
search_parent = parent.parent_id;
@@ -128,6 +138,17 @@ impl ScopeContext {
None
})
.flatten()
{
Some(ctx) => Some(ctx),
None => {
tracing::trace!(
"context {} ({:?}) not found",
std::any::type_name::<T>(),
std::any::TypeId::of::<T>()
);
None
}
}
}
/// Expose state to children further down the [`crate::VirtualDom`] Tree. Requires `Clone` on the context to allow getting values down the tree.
@@ -152,6 +173,12 @@ impl ScopeContext {
/// }
/// ```
pub fn provide_context<T: 'static + Clone>(&self, value: T) -> T {
tracing::trace!(
"providing context {} ({:?}) in {}",
std::any::type_name::<T>(),
std::any::TypeId::of::<T>(),
self.name
);
let mut contexts = self.shared_contexts.borrow_mut();
// If the context exists, swap it out for the new value
@@ -179,7 +206,7 @@ impl ScopeContext {
pub fn provide_root_context<T: 'static + Clone>(&self, context: T) -> T {
with_runtime(|runtime| {
runtime
.get_context(ScopeId(0))
.get_context(ScopeId::ROOT)
.unwrap()
.provide_context(context)
})
@@ -203,7 +230,7 @@ impl ScopeContext {
/// This is good for tasks that need to be run after the component has been dropped.
pub fn spawn_forever(&self, fut: impl Future<Output = ()> + 'static) -> TaskId {
// The root scope will never be unmounted so we can just add the task at the top of the app
let id = self.tasks.spawn(ScopeId(0), fut);
let id = self.tasks.spawn(ScopeId::ROOT, fut);
// wake up the scheduler if it is sleeping
self.tasks
+18 -1
View File
@@ -63,6 +63,21 @@ impl<'a, T> std::ops::Deref for Scoped<'a, T> {
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
pub struct ScopeId(pub usize);
impl ScopeId {
/// The root ScopeId.
///
/// This scope will last for the entire duration of your app, making it convenient for long-lived state
/// that is created dynamically somewhere down the component tree.
///
/// # Example
///
/// ```rust, ignore
/// use dioxus_signals::*;
/// let my_persistent_state = Signal::new_in_scope(ScopeId::ROOT, String::new());
/// ```
pub const ROOT: ScopeId = ScopeId(0);
}
/// A component's state separate from its props.
///
/// This struct exists to provide a common interface for all scopes without relying on generics.
@@ -424,7 +439,9 @@ impl<'src> ScopeState {
fn_name: &'static str,
) -> DynamicNode<'src>
where
P: Properties + 'child,
// The properties must be valid until the next bump frame
P: Properties + 'src,
// The current bump allocator frame must outlive the child's borrowed props
'src: 'child,
{
let vcomp = VProps::new(component, P::memoize, props);
+19 -10
View File
@@ -52,6 +52,7 @@ use std::{any::Any, cell::Cell, collections::BTreeSet, future::Future, rc::Rc};
///
/// static ROUTES: &str = "";
///
/// #[component]
/// fn App(cx: Scope<AppProps>) -> Element {
/// cx.render(rsx!(
/// NavBar { routes: ROUTES }
@@ -60,18 +61,19 @@ use std::{any::Any, cell::Cell, collections::BTreeSet, future::Future, rc::Rc};
/// ))
/// }
///
/// #[inline_props]
/// #[component]
/// fn NavBar(cx: Scope, routes: &'static str) -> Element {
/// cx.render(rsx! {
/// div { "Routes: {routes}" }
/// })
/// }
///
/// #[component]
/// fn Footer(cx: Scope) -> Element {
/// cx.render(rsx! { div { "Footer" } })
/// }
///
/// #[inline_props]
/// #[component]
/// fn Title<'a>(cx: Scope<'a>, children: Element<'a>) -> Element {
/// cx.render(rsx! {
/// div { id: "title", children }
@@ -122,13 +124,14 @@ use std::{any::Any, cell::Cell, collections::BTreeSet, future::Future, rc::Rc};
///
/// Putting everything together, you can build an event loop around Dioxus by using the methods outlined above.
/// ```rust, ignore
/// fn app(cx: Scope) -> Element {
/// #[component]
/// fn App(cx: Scope) -> Element {
/// cx.render(rsx! {
/// div { "Hello World" }
/// })
/// }
///
/// let dom = VirtualDom::new(app);
/// let dom = VirtualDom::new(App);
///
/// real_dom.apply(dom.rebuild());
///
@@ -270,7 +273,7 @@ impl VirtualDom {
);
// Unlike react, we provide a default error boundary that just renders the error as a string
root.provide_context(Rc::new(ErrorBoundary::new(ScopeId(0))));
root.provide_context(Rc::new(ErrorBoundary::new(ScopeId::ROOT)));
// the root element is always given element ID 0 since it's the container for the entire tree
dom.elements.insert(ElementRef::none());
@@ -289,7 +292,7 @@ impl VirtualDom {
///
/// This scope has a ScopeId of 0 and is the root of the tree
pub fn base_scope(&self) -> &ScopeState {
self.get_scope(ScopeId(0)).unwrap()
self.get_scope(ScopeId::ROOT).unwrap()
}
/// Build the virtualdom with a global context inserted into the base scope
@@ -306,6 +309,7 @@ impl VirtualDom {
pub fn mark_dirty(&mut self, id: ScopeId) {
if let Some(scope) = self.get_scope(id) {
let height = scope.height();
tracing::trace!("Marking scope {:?} ({}) as dirty", id, scope.context().name);
self.dirty_scopes.insert(DirtyScope { height, id });
}
}
@@ -547,10 +551,10 @@ impl VirtualDom {
/// ```
pub fn rebuild(&mut self) -> Mutations {
let _runtime = RuntimeGuard::new(self.runtime.clone());
match unsafe { self.run_scope(ScopeId(0)).extend_lifetime_ref() } {
match unsafe { self.run_scope(ScopeId::ROOT).extend_lifetime_ref() } {
// Rebuilding implies we append the created elements to the root
RenderReturn::Ready(node) => {
let m = self.create_scope(ScopeId(0), node);
let m = self.create_scope(ScopeId::ROOT, node);
self.mutations.edits.push(Mutation::AppendChildren {
id: ElementId(0),
m,
@@ -558,7 +562,7 @@ impl VirtualDom {
}
// If an error occurs, we should try to render the default error component and context where the error occured
RenderReturn::Aborted(placeholder) => {
log::info!("Ran into suspended or aborted scope during rebuild");
tracing::debug!("Ran into suspended or aborted scope during rebuild");
let id = self.next_null();
placeholder.id.set(Some(id));
self.mutations.push(Mutation::CreatePlaceholder { id });
@@ -658,11 +662,16 @@ impl VirtualDom {
fn finalize(&mut self) -> Mutations {
std::mem::take(&mut self.mutations)
}
/// Get the current runtime
pub fn runtime(&self) -> Rc<Runtime> {
self.runtime.clone()
}
}
impl Drop for VirtualDom {
fn drop(&mut self) {
// Simply drop this scope which drops all of its children
self.drop_scope(ScopeId(0), true);
self.drop_scope(ScopeId::ROOT, true);
}
}
+4 -4
View File
@@ -34,7 +34,7 @@ fn attrs_cycle() {
]
);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -56,7 +56,7 @@ fn attrs_cycle() {
]
);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -65,7 +65,7 @@ fn attrs_cycle() {
]
);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -88,7 +88,7 @@ fn attrs_cycle() {
);
// we take the node taken by attributes since we reused it
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
+1 -1
View File
@@ -24,7 +24,7 @@ fn bubbles_error() {
let _edits = dom.rebuild().santize();
}
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
_ = dom.render_immediate();
}
+3 -3
View File
@@ -27,11 +27,11 @@ fn state_shares() {
]
);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
_ = dom.render_immediate();
assert_eq!(dom.base_scope().consume_context::<i32>().unwrap(), 1);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
_ = dom.render_immediate();
assert_eq!(dom.base_scope().consume_context::<i32>().unwrap(), 2);
@@ -41,7 +41,7 @@ fn state_shares() {
[SetText { value: "Value is 2", id: ElementId(1,) },]
);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
dom.mark_dirty(ScopeId(2));
let edits = dom.render_immediate();
assert_eq!(
+19 -16
View File
@@ -5,11 +5,12 @@ use dioxus_core::ElementId;
/// Should push the text node onto the stack and modify it
#[test]
fn nested_passthru_creates() {
fn app(cx: Scope) -> Element {
#[component]
fn App(cx: Scope) -> Element {
cx.render(rsx! {
pass_thru {
pass_thru {
pass_thru {
PassThru {
PassThru {
PassThru {
div { "hi" }
}
}
@@ -17,12 +18,12 @@ fn nested_passthru_creates() {
})
}
#[inline_props]
fn pass_thru<'a>(cx: Scope<'a>, children: Element<'a>) -> Element {
#[component]
fn PassThru<'a>(cx: Scope<'a>, children: Element<'a>) -> Element {
cx.render(rsx!(children))
}
let mut dom = VirtualDom::new(app);
let mut dom = VirtualDom::new(App);
let edits = dom.rebuild().santize();
assert_eq!(
@@ -39,13 +40,14 @@ fn nested_passthru_creates() {
/// Take note on how we don't spit out the template for child_comp since it's entirely dynamic
#[test]
fn nested_passthru_creates_add() {
fn app(cx: Scope) -> Element {
#[component]
fn App(cx: Scope) -> Element {
cx.render(rsx! {
child_comp {
ChildComp {
"1"
child_comp {
ChildComp {
"2"
child_comp {
ChildComp {
"3"
div {
"hi"
@@ -56,12 +58,12 @@ fn nested_passthru_creates_add() {
})
}
#[inline_props]
fn child_comp<'a>(cx: Scope, children: Element<'a>) -> Element {
#[component]
fn ChildComp<'a>(cx: Scope, children: Element<'a>) -> Element {
cx.render(rsx! { children })
}
let mut dom = VirtualDom::new(app);
let mut dom = VirtualDom::new(App);
assert_eq!(
dom.rebuild().santize().edits,
@@ -82,13 +84,14 @@ fn nested_passthru_creates_add() {
/// note that the template is all dynamic roots - so it doesn't actually get cached as a template
#[test]
fn dynamic_node_as_root() {
fn app(cx: Scope) -> Element {
#[component]
fn App(cx: Scope) -> Element {
let a = 123;
let b = 456;
cx.render(rsx! { "{a}" "{b}" })
}
let mut dom = VirtualDom::new(app);
let mut dom = VirtualDom::new(App);
let edits = dom.rebuild().santize();
// Since the roots were all dynamic, they should not cause any template muations
+3 -3
View File
@@ -23,7 +23,7 @@ fn cycling_elements() {
);
}
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -33,7 +33,7 @@ fn cycling_elements() {
);
// notice that the IDs cycle back to ElementId(1), preserving a minimal memory footprint
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -42,7 +42,7 @@ fn cycling_elements() {
]
);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
+3 -3
View File
@@ -75,7 +75,7 @@ fn component_swap() {
);
}
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -84,7 +84,7 @@ fn component_swap() {
]
);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -93,7 +93,7 @@ fn component_swap() {
]
);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
+7 -7
View File
@@ -12,19 +12,19 @@ fn text_diff() {
let mut vdom = VirtualDom::new(app);
_ = vdom.rebuild();
vdom.mark_dirty(ScopeId(0));
vdom.mark_dirty(ScopeId::ROOT);
assert_eq!(
vdom.render_immediate().edits,
[SetText { value: "hello 1", id: ElementId(2) }]
);
vdom.mark_dirty(ScopeId(0));
vdom.mark_dirty(ScopeId::ROOT);
assert_eq!(
vdom.render_immediate().edits,
[SetText { value: "hello 2", id: ElementId(2) }]
);
vdom.mark_dirty(ScopeId(0));
vdom.mark_dirty(ScopeId::ROOT);
assert_eq!(
vdom.render_immediate().edits,
[SetText { value: "hello 3", id: ElementId(2) }]
@@ -46,7 +46,7 @@ fn element_swap() {
let mut vdom = VirtualDom::new(app);
_ = vdom.rebuild();
vdom.mark_dirty(ScopeId(0));
vdom.mark_dirty(ScopeId::ROOT);
assert_eq!(
vdom.render_immediate().santize().edits,
[
@@ -55,7 +55,7 @@ fn element_swap() {
]
);
vdom.mark_dirty(ScopeId(0));
vdom.mark_dirty(ScopeId::ROOT);
assert_eq!(
vdom.render_immediate().santize().edits,
[
@@ -64,7 +64,7 @@ fn element_swap() {
]
);
vdom.mark_dirty(ScopeId(0));
vdom.mark_dirty(ScopeId::ROOT);
assert_eq!(
vdom.render_immediate().santize().edits,
[
@@ -73,7 +73,7 @@ fn element_swap() {
]
);
vdom.mark_dirty(ScopeId(0));
vdom.mark_dirty(ScopeId::ROOT);
assert_eq!(
vdom.render_immediate().santize().edits,
[
+12 -12
View File
@@ -39,7 +39,7 @@ fn keyed_diffing_out_of_order() {
);
}
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().edits,
[
@@ -64,7 +64,7 @@ fn keyed_diffing_out_of_order_adds() {
_ = dom.rebuild();
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().edits,
[
@@ -90,7 +90,7 @@ fn keyed_diffing_out_of_order_adds_3() {
_ = dom.rebuild();
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().edits,
[
@@ -116,7 +116,7 @@ fn keyed_diffing_out_of_order_adds_4() {
_ = dom.rebuild();
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().edits,
[
@@ -142,7 +142,7 @@ fn keyed_diffing_out_of_order_adds_5() {
_ = dom.rebuild();
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().edits,
[
@@ -167,7 +167,7 @@ fn keyed_diffing_additions() {
_ = dom.rebuild();
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -192,7 +192,7 @@ fn keyed_diffing_additions_and_moves_on_ends() {
_ = dom.rebuild();
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -222,7 +222,7 @@ fn keyed_diffing_additions_and_moves_in_middle() {
_ = dom.rebuild();
// LIS: 4, 5, 6
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -256,7 +256,7 @@ fn controlled_keyed_diffing_out_of_order() {
_ = dom.rebuild();
// LIS: 5, 6
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -289,7 +289,7 @@ fn controlled_keyed_diffing_out_of_order_max_test() {
_ = dom.rebuild();
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -318,7 +318,7 @@ fn remove_list() {
_ = dom.rebuild();
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -343,7 +343,7 @@ fn no_common_keys() {
_ = dom.rebuild();
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
+18 -18
View File
@@ -27,7 +27,7 @@ fn list_creates_one_by_one() {
);
// Rendering the first item should replace the placeholder with an element
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -38,7 +38,7 @@ fn list_creates_one_by_one() {
);
// Rendering the next item should insert after the previous
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -49,7 +49,7 @@ fn list_creates_one_by_one() {
);
// ... and again!
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -60,7 +60,7 @@ fn list_creates_one_by_one() {
);
// once more
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -107,14 +107,14 @@ fn removes_one_by_one() {
// Remove div(3)
// Rendering the first item should replace the placeholder with an element
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[Remove { id: ElementId(6) }]
);
// Remove div(2)
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[Remove { id: ElementId(4) }]
@@ -122,7 +122,7 @@ fn removes_one_by_one() {
// Remove div(1) and replace with a placeholder
// todo: this should just be a remove with no placeholder
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -133,7 +133,7 @@ fn removes_one_by_one() {
// load the 3 and replace the placeholder
// todo: this should actually be append to, but replace placeholder is fine for now
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -170,7 +170,7 @@ fn list_shrink_multiroot() {
]
);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -182,7 +182,7 @@ fn list_shrink_multiroot() {
]
);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -194,7 +194,7 @@ fn list_shrink_multiroot() {
]
);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -249,19 +249,19 @@ fn removes_one_by_one_multiroot() {
]
);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[Remove { id: ElementId(10) }, Remove { id: ElementId(12) }]
);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[Remove { id: ElementId(6) }, Remove { id: ElementId(8) }]
);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
assert_eq!(
dom.render_immediate().santize().edits,
[
@@ -328,7 +328,7 @@ fn remove_many() {
}
{
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
let edits = dom.render_immediate().santize();
assert_eq!(
edits.edits,
@@ -341,7 +341,7 @@ fn remove_many() {
}
{
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
let edits = dom.render_immediate().santize();
assert_eq!(
edits.edits,
@@ -360,7 +360,7 @@ fn remove_many() {
}
{
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
let edits = dom.render_immediate().santize();
assert_eq!(
edits.edits,
@@ -376,7 +376,7 @@ fn remove_many() {
}
{
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
let edits = dom.render_immediate().santize();
assert_eq!(
edits.edits,
+8 -8
View File
@@ -58,7 +58,7 @@ fn events_generate() {
dom.handle_event("click", Rc::new(MouseData::default()), ElementId(1), true);
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
let edits = dom.render_immediate();
assert_eq!(
@@ -107,7 +107,7 @@ fn events_generate() {
// );
// assert_eq!(
// dom.hard_diff(ScopeId(0)).edits,
// dom.hard_diff(ScopeId::ROOT).edits,
// [
// CreateElement { root: Some(2), tag: "div", children: 0 },
// ReplaceWith { root: Some(1), nodes: vec![2] }
@@ -115,7 +115,7 @@ fn events_generate() {
// );
// assert_eq!(
// dom.hard_diff(ScopeId(0)).edits,
// dom.hard_diff(ScopeId::ROOT).edits,
// [
// CreateTextNode { root: Some(1), text: "Text2" },
// ReplaceWith { root: Some(2), nodes: vec![1] }
@@ -124,7 +124,7 @@ fn events_generate() {
// // child {}
// assert_eq!(
// dom.hard_diff(ScopeId(0)).edits,
// dom.hard_diff(ScopeId::ROOT).edits,
// [
// CreateElement { root: Some(2), tag: "h1", children: 0 },
// ReplaceWith { root: Some(1), nodes: vec![2] }
@@ -133,7 +133,7 @@ fn events_generate() {
// // placeholder
// assert_eq!(
// dom.hard_diff(ScopeId(0)).edits,
// dom.hard_diff(ScopeId::ROOT).edits,
// [
// CreatePlaceholder { root: Some(1) },
// ReplaceWith { root: Some(2), nodes: vec![1] }
@@ -141,7 +141,7 @@ fn events_generate() {
// );
// assert_eq!(
// dom.hard_diff(ScopeId(0)).edits,
// dom.hard_diff(ScopeId::ROOT).edits,
// [
// CreateTextNode { root: Some(2), text: "text 3" },
// ReplaceWith { root: Some(1), nodes: vec![2] }
@@ -149,7 +149,7 @@ fn events_generate() {
// );
// assert_eq!(
// dom.hard_diff(ScopeId(0)).edits,
// dom.hard_diff(ScopeId::ROOT).edits,
// [
// CreateTextNode { text: "text 0", root: Some(1) },
// CreateTextNode { text: "text 1", root: Some(3) },
@@ -158,7 +158,7 @@ fn events_generate() {
// );
// assert_eq!(
// dom.hard_diff(ScopeId(0)).edits,
// dom.hard_diff(ScopeId::ROOT).edits,
// [
// CreateElement { tag: "h1", root: Some(2), children: 0 },
// ReplaceWith { root: Some(1), nodes: vec![2] },
+6 -5
View File
@@ -4,7 +4,7 @@ use std::rc::Rc;
#[test]
fn miri_rollover() {
let mut dom = VirtualDom::new(app);
let mut dom = VirtualDom::new(App);
_ = dom.rebuild();
@@ -15,7 +15,8 @@ fn miri_rollover() {
}
}
fn app(cx: Scope) -> Element {
#[component]
fn App(cx: Scope) -> Element {
let mut idx = use_state(cx, || 0);
let onhover = |_| println!("go!");
@@ -31,15 +32,15 @@ fn app(cx: Scope) -> Element {
button { onclick: move |_| idx -= 1, "-" }
ul {
(0..**idx).map(|i| rsx! {
child_example { i: i, onhover: onhover }
ChildExample { i: i, onhover: onhover }
})
}
}
})
}
#[inline_props]
fn child_example<'a>(cx: Scope<'a>, i: i32, onhover: EventHandler<'a, MouseEvent>) -> Element {
#[component]
fn ChildExample<'a>(cx: Scope<'a>, i: i32, onhover: EventHandler<'a, MouseEvent>) -> Element {
cx.render(rsx! {
li {
onmouseover: move |e| onhover.call(e),
+30 -24
View File
@@ -2,22 +2,24 @@ use dioxus::prelude::*;
#[test]
fn app_drops() {
fn app(cx: Scope) -> Element {
#[component]
fn App(cx: Scope) -> Element {
cx.render(rsx! {
div {}
})
}
let mut dom = VirtualDom::new(app);
let mut dom = VirtualDom::new(App);
_ = dom.rebuild();
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
_ = dom.render_immediate();
}
#[test]
fn hooks_drop() {
fn app(cx: Scope) -> Element {
#[component]
fn App(cx: Scope) -> Element {
cx.use_hook(|| String::from("asd"));
cx.use_hook(|| String::from("asd"));
cx.use_hook(|| String::from("asd"));
@@ -28,26 +30,28 @@ fn hooks_drop() {
})
}
let mut dom = VirtualDom::new(app);
let mut dom = VirtualDom::new(App);
_ = dom.rebuild();
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
_ = dom.render_immediate();
}
#[test]
fn contexts_drop() {
fn app(cx: Scope) -> Element {
#[component]
fn App(cx: Scope) -> Element {
cx.provide_context(String::from("asd"));
cx.render(rsx! {
div {
child_comp {}
ChildComp {}
}
})
}
fn child_comp(cx: Scope) -> Element {
#[component]
fn ChildComp(cx: Scope) -> Element {
let el = cx.consume_context::<String>().unwrap();
cx.render(rsx! {
@@ -55,16 +59,17 @@ fn contexts_drop() {
})
}
let mut dom = VirtualDom::new(app);
let mut dom = VirtualDom::new(App);
_ = dom.rebuild();
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
_ = dom.render_immediate();
}
#[test]
fn tasks_drop() {
fn app(cx: Scope) -> Element {
#[component]
fn App(cx: Scope) -> Element {
cx.spawn(async {
// tokio::time::sleep(std::time::Duration::from_millis(100000)).await;
});
@@ -74,10 +79,10 @@ fn tasks_drop() {
})
}
let mut dom = VirtualDom::new(app);
let mut dom = VirtualDom::new(App);
_ = dom.rebuild();
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
_ = dom.render_immediate();
}
@@ -91,37 +96,38 @@ fn root_props_drop() {
);
_ = dom.rebuild();
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
_ = dom.render_immediate();
}
#[test]
fn diffing_drops_old() {
fn app(cx: Scope) -> Element {
#[component]
fn App(cx: Scope) -> Element {
cx.render(rsx! {
div {
match cx.generation() % 2 {
0 => rsx!( child_comp1 { name: "asdasd".to_string() }),
1 => rsx!( child_comp2 { name: "asdasd".to_string() }),
0 => rsx!( ChildComp1 { name: "asdasd".to_string() }),
1 => rsx!( ChildComp2 { name: "asdasd".to_string() }),
_ => todo!()
}
}
})
}
#[inline_props]
fn child_comp1(cx: Scope, name: String) -> Element {
#[component]
fn ChildComp1(cx: Scope, name: String) -> Element {
cx.render(rsx! { "Hello {name}" })
}
#[inline_props]
fn child_comp2(cx: Scope, name: String) -> Element {
#[component]
fn ChildComp2(cx: Scope, name: String) -> Element {
cx.render(rsx! { "Goodbye {name}" })
}
let mut dom = VirtualDom::new(app);
let mut dom = VirtualDom::new(App);
_ = dom.rebuild();
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
_ = dom.render_immediate();
}
+8 -8
View File
@@ -62,7 +62,7 @@ fn test_memory_leak() {
_ = dom.rebuild();
for _ in 0..5 {
dom.mark_dirty(ScopeId(0));
dom.mark_dirty(ScopeId::ROOT);
_ = dom.render_immediate();
}
}
@@ -97,13 +97,13 @@ fn memo_works_properly() {
_ = dom.rebuild();
// todo!()
// dom.hard_diff(ScopeId(0));
// dom.hard_diff(ScopeId(0));
// dom.hard_diff(ScopeId(0));
// dom.hard_diff(ScopeId(0));
// dom.hard_diff(ScopeId(0));
// dom.hard_diff(ScopeId(0));
// dom.hard_diff(ScopeId(0));
// dom.hard_diff(ScopeId::ROOT);
// dom.hard_diff(ScopeId::ROOT);
// dom.hard_diff(ScopeId::ROOT);
// dom.hard_diff(ScopeId::ROOT);
// dom.hard_diff(ScopeId::ROOT);
// dom.hard_diff(ScopeId::ROOT);
// dom.hard_diff(ScopeId::ROOT);
}
#[test]
+10 -4
View File
@@ -6,7 +6,7 @@ edition = "2018"
description = "WebView renderer for Dioxus"
license = "MIT OR Apache-2.0"
repository = "https://github.com/DioxusLabs/dioxus/"
homepage = "https://dioxuslabs.com/docs/0.3/guide/en/getting_started/desktop.html"
homepage = "https://dioxuslabs.com/learn/0.4/getting_started/desktop"
keywords = ["dom", "ui", "gui", "react"]
[dependencies]
@@ -18,8 +18,8 @@ dioxus-hot-reload = { workspace = true, optional = true }
serde = "1.0.136"
serde_json = "1.0.79"
thiserror = { workspace = true }
log = { workspace = true }
wry = { version = "0.28.0" }
wry = { version = "0.28.0", default-features = false, features = ["protocol", "file-drop"] }
tracing = { workspace = true }
futures-channel = { workspace = true }
tokio = { workspace = true, features = [
"sync",
@@ -51,13 +51,19 @@ core-foundation = "0.9.3"
objc = "0.2.7"
[features]
default = ["tokio_runtime", "hot-reload"]
default = ["tokio_runtime", "hot-reload", "wry/objc-exception"]
tokio_runtime = ["tokio"]
fullscreen = ["wry/fullscreen"]
transparent = ["wry/transparent"]
devtools = ["wry/devtools"]
tray = ["wry/tray"]
dox = ["wry/dox"]
hot-reload = ["dioxus-hot-reload"]
[package.metadata.docs.rs]
default-features = false
features = [ "dox", "tokio_runtime", "hot-reload" ]
[dev-dependencies]
dioxus-core-macro = { workspace = true }
dioxus-hooks = { workspace = true }
+3 -9
View File
@@ -1,6 +1,5 @@
# Dioxus Desktop (webview)
[![Crates.io][crates-badge]][crates-url]
[![MIT licensed][mit-badge]][mit-url]
[![Build Status][actions-badge]][actions-url]
@@ -8,31 +7,25 @@
[crates-badge]: https://img.shields.io/crates/v/dioxus-desktop.svg
[crates-url]: https://crates.io/crates/dioxus-desktop
[mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg
[mit-url]: https://github.com/dioxuslabs/dioxus/blob/master/LICENSE
[actions-badge]: https://github.com/dioxuslabs/dioxus/actions/workflows/main.yml/badge.svg
[actions-url]: https://github.com/dioxuslabs/dioxus/actions?query=workflow%3ACI+branch%3Amaster
[discord-badge]: https://img.shields.io/discord/899851952891002890.svg?logo=discord&style=flat-square
[discord-url]: https://discord.gg/XgGxMSkvUM
[Website](https://dioxuslabs.com) |
[Guides](https://dioxuslabs.com/docs/0.3/guide/en/) |
[Guides](https://dioxuslabs.com/learn/0.4/) |
[API Docs](https://docs.rs/dioxus-desktop/latest/dioxus_desktop) |
[Chat](https://discord.gg/XgGxMSkvUM)
## Overview
`dioxus-desktop` provides a webview-based desktop renderer for the Dioxus VirtualDom.
This requires that webview is installed on the target system. WebView is installed by default on macOS and iOS devices, but might not come preinstalled on Windows or Linux devices. To fix these issues, follow the [instructions in the guide](guide-url).
[guide-url]: https://dioxuslabs.com/docs/0.3/guide/en/getting_started/desktop.html
[guide-url]: https://dioxuslabs.com/learn/0.4/getting_started/desktop
## Features
@@ -48,6 +41,7 @@ This requires that webview is installed on the target system. WebView is install
- Join the discord and ask questions!
## License
This project is licensed under the [MIT license].
[mit license]: https://github.com/DioxusLabs/dioxus/blob/master/LICENSE-MIT
+2 -2
View File
@@ -194,7 +194,7 @@ impl DesktopService {
/// launch print modal
pub fn print(&self) {
if let Err(e) = self.webview.print() {
log::warn!("Open print modal failed: {e}");
tracing::warn!("Open print modal failed: {e}");
}
}
@@ -209,7 +209,7 @@ impl DesktopService {
self.webview.open_devtools();
#[cfg(not(debug_assertions))]
log::warn!("Devtools are disabled in release builds");
tracing::warn!("Devtools are disabled in release builds");
}
/// Create a wry event handler that listens for wry events.
+1 -1
View File
@@ -330,7 +330,7 @@ pub fn launch_with_props<P: 'static>(root: Component<P>, props: P, cfg: Config)
if temp.contains_key("href") {
let open = webbrowser::open(temp["href"].as_str().unwrap());
if let Err(e) = open {
log::error!("Open Browser error: {:?}", e);
tracing::error!("Open Browser error: {:?}", e);
}
}
}
+1 -1
View File
@@ -123,7 +123,7 @@ impl QueryEngine {
}})
}})();"#
)) {
log::warn!("Query error: {err}");
tracing::warn!("Query error: {err}");
}
Query {
+1 -3
View File
@@ -8,7 +8,6 @@ One of Dioxus' flagship features is the ability to quickly build a native deskto
Dioxus Desktop is built off Tauri. Right now there aren't any Dioxus abstractions over the menubar, handling, etc, so you'll want to leverage Tauri - mostly [Wry](http://github.com/tauri-apps/wry/) and [Tao](http://github.com/tauri-apps/tao) directly. An upcoming release of Dioxus-Desktop will include components and hooks for notifications, global shortcuts, menubar, etc.
## Getting Set up
Getting Set up with Dioxus-Desktop is quite easy. Make sure you have Rust and Cargo installed, and then create a new project:
@@ -44,9 +43,8 @@ fn app(cx: Scope) -> Element {
}
```
To configure the webview, menubar, and other important desktop-specific features, checkout out some of the launch configuration in the [API reference](https://docs.rs/dioxus-desktop/).
## Future Steps
Make sure to read the [Dioxus Guide](https://dioxuslabs.com/docs/0.3/guide/en) if you already haven't!
Make sure to read the [Dioxus Guide](https://dioxuslabs.com/learn/0.4/) if you already haven't!
+1 -1
View File
@@ -5,7 +5,7 @@ authors = ["Jonathan Kelley, Evan Almloff"]
edition = "2021"
description = "TUI-based renderer for Dioxus"
repository = "https://github.com/DioxusLabs/dioxus/"
homepage = "https://dioxuslabs.com/docs/0.3/guide/en/getting_started/tui.html"
homepage = "https://dioxuslabs.com/learn/0.4/getting_started/tui"
keywords = ["dom", "ui", "gui", "react", "terminal"]
license = "MIT OR Apache-2.0"
+2 -2
View File
@@ -6,7 +6,7 @@ edition = "2021"
description = "Portable, performant, and ergonomic framework for building cross-platform user interfaces in Rust"
license = "MIT OR Apache-2.0"
repository = "https://github.com/DioxusLabs/dioxus/"
homepage = "https://dioxuslabs.com/docs/0.3/guide/en/index.html"
homepage = "https://dioxuslabs.com/learn/0.4/"
keywords = ["dom", "ui", "gui", "react", "wasm"]
rust-version = "1.65.0"
@@ -30,7 +30,7 @@ hot-reload = ["dioxus-hot-reload"]
[dev-dependencies]
futures-util = { workspace = true }
log = { workspace = true }
tracing = { workspace = true }
rand = { version = "0.8.4", features = ["small_rng"] }
criterion = "0.3.5"
thiserror = { workspace = true }
+41 -24
View File
@@ -1,4 +1,4 @@
<div align="center">
<div style="text-align: center">
<h1>🌗🚀 Dioxus</h1>
<p>
<strong>A concurrent, functional, virtual DOM for Rust</strong>
@@ -9,8 +9,8 @@
This overview provides a brief introduction to Dioxus. For a more in-depth guide, make sure to check out:
- [Getting Started](https://dioxuslabs.com/docs/0.3/guide/en/getting_started/index.html)
- [Book](https://dioxuslabs.com/docs/0.3/guide/en/)
- [Getting Started](https://dioxuslabs.com/learn/0.4/getting_started)
- [Book (0.4)](https://dioxuslabs.com/learn/0.4/)
- [Examples](https://github.com/DioxusLabs/example-projects)
# Overview and Goals
@@ -27,15 +27,15 @@ Dioxus is heavily inspired by React, supporting many of the same concepts:
If you know React, then you know Dioxus.
Dioxus is *substantially* more performant than many of the other Rust UI libraries (Yew/Percy) and is *significantly* more performant
than React - roughly competitive with InfernoJS.
Dioxus is _substantially_ more performant than many of the other Rust UI libraries (Yew/Percy) and is _significantly_ more performant
than React—roughly competitive with InfernoJS.
Remember: Dioxus is a library for declaring interactive user interfaces - it is not a dedicated renderer. Most 1st party renderers for Dioxus currently only support web technologies.
Remember: Dioxus is a library for declaring interactive user interfaces—it is not a dedicated renderer. Most 1st party renderers for Dioxus currently only support web technologies.
## Brief Overview
All Dioxus apps are built by composing functions that take in a `Scope` which is generic over some `Properties` and return an `Element`.
A `Scope` holds relevant state data for the currently-rendered component.
A `Scope` holds relevant state data for the currently rendered component.
To launch an app, we use the `launch` method for the specific renderer we want to use. In the launch function, we pass the app's `Component`.
@@ -43,10 +43,13 @@ To launch an app, we use the `launch` method for the specific renderer we want t
use dioxus::prelude::*;
fn main() {
dioxus_desktop::launch(app);
dioxus_desktop::launch(App);
}
fn app(cx: Scope) -> Element {
// The #[component] attribute streamlines component creation.
// It's not required, but highly recommended. For example, UpperCamelCase components will not generate a warning.
#[component]
fn App(cx: Scope) -> Element {
cx.render(rsx!("hello world!"))
}
```
@@ -59,7 +62,7 @@ macro or the NodeFactory API. For the most part, you want to use the `rsx!`
macro.
Any element in `rsx!` can have attributes, listeners, and children. For
consistency, we force all attributes and listeners to be listed *before*
consistency, we force all attributes and listeners to be listed _before_
children.
```rust, ignore
@@ -84,7 +87,6 @@ rsx!(
(0..10).map(|_| rsx!(span { "hello world" }))
}
)
```
Used within components, the `rsx!` macro must be rendered into an `Element` with
@@ -95,7 +97,8 @@ If we want to omit the boilerplate of `cx.render`, we can simply pass in
render nodes in match statements.
```rust, ignore
fn example(cx: Scope) -> Element {
#[component[
fn Example(cx: Scope) -> Element {
// both of these are equivalent
cx.render(rsx!("hello world"))
@@ -108,7 +111,8 @@ Putting everything together, we can write a simple component that renders a list
elements:
```rust, ignore
fn app(cx: Scope) -> Element {
#[component]
fn App(cx: Scope) -> Element {
let name = "dave";
cx.render(rsx!(
h1 { "Hello, {name}!" }
@@ -136,6 +140,7 @@ properties, we can use the `()` type or simply omit the type altogether.
In Dioxus, all properties are memoized by default!
```rust, ignore
#[component]
fn App(cx: Scope) -> Element {
cx.render(rsx!(
Header {
@@ -157,6 +162,7 @@ struct HeaderProps {
color: String,
}
#[component]
fn Header(cx: Scope<HeaderProps>) -> Element {
cx.render(rsx!(
div {
@@ -167,11 +173,11 @@ fn Header(cx: Scope<HeaderProps>) -> Element {
}
```
Components may use the `inline_props` macro to completely inline the props
definition into the function arguments.
The `#[component]` macro also allows you to derive the props
struct from function arguments:
```rust, ignore
#[inline_props]
#[component]
fn Header(cx: Scope, title: String, color: String) -> Element {
cx.render(rsx!(
div {
@@ -184,6 +190,7 @@ fn Header(cx: Scope, title: String, color: String) -> Element {
Components may also borrow data from their parent component. We just need to
attach some lifetimes to the props struct.
> Note: we don't need to derive `PartialEq` for borrowed props since they cannot be memoized.
```rust, ignore
@@ -193,6 +200,7 @@ struct HeaderProps<'a> {
color: &'a str,
}
#[component]
fn Header<'a>(cx: Scope<'a, HeaderProps<'a>>) -> Element {
cx.render(rsx!(
div {
@@ -221,6 +229,9 @@ rsx!(
)
```
However, the convention is to use UpperCamelCase. The `#[component]` attribute will enforce this,
but you can turn it off if you wish.
## Hooks
While components are reusable forms of UI elements, hooks are reusable forms
@@ -231,7 +242,8 @@ By convention, all hooks are functions that should start with `use_`. We can
use hooks to define the state and modify it from within listeners.
```rust, ignore
fn app(cx: Scope) -> Element {
#[component]
fn App(cx: Scope) -> Element {
let name = use_state(cx, || "world");
render!("hello {name}!")
@@ -239,10 +251,11 @@ fn app(cx: Scope) -> Element {
```
Hooks are sensitive to how they are used. To use hooks, you must abide by the
["rules of hooks" (borrowed from react)](https://reactjs.org/docs/hooks-rules.html):
- Functions with "use_" should not be called in callbacks
- Functions with "use_" should not be called out of order
- Functions with "use_" should not be called in loops or conditionals
["rules of hooks" (borrowed from React)](https://reactjs.org/docs/hooks-rules.html):
- Functions with "use\_" should not be called in callbacks
- Functions with "use\_" should not be called out of order
- Functions with "use\_" should not be called in loops or conditionals
In a sense, hooks let us add a field of state to our component without declaring
an explicit state struct. However, this means we need to "load" the struct in the right
@@ -278,6 +291,7 @@ fn main() {
dioxus_desktop::launch(App);
}
#[component]
fn App(cx: Scope) -> Element {
let count = use_state(cx, || 0);
@@ -295,6 +309,7 @@ This overview doesn't cover everything. Make sure to check out the tutorial and
website for more details.
Beyond this overview, Dioxus supports:
- Server-side rendering
- Concurrent rendering (with async support)
- Web/Desktop/Mobile support
@@ -311,14 +326,16 @@ Good luck!
## Inspiration, Resources, Alternatives, and Credits
Dioxus is inspired by:
- React: for its hooks, concurrency, suspense
- Dodrio: for its research in bump allocation, double buffering, and diffing architecture
Alternatives to Dioxus include:
- Yew: supports function components and web, but no SSR, borrowed data, or bump allocation. Rather slow at times.
- Percy: supports function components, web, ssr, but lacks state management
- Sycamore: supports function components, web, ssr, but is closer to SolidJS than React
- MoonZoom/Seed: opinionated frameworks based on the Elm model (message, update) - no hooks
- MoonZoom/Seed: opinionated frameworks based on the Elm model (message, update)—no hooks
We've put a lot of work into making Dioxus ergonomic and *familiar*.
Our target audience is TypeScript developers looking to switch to Rust for the web - so we need to be comparable to React.
We've put a lot of work into making Dioxus ergonomic and _familiar_.
Our target audience is TypeScript developers looking to switch to Rust for the web—so we need to be comparable to React.
+2 -1
View File
@@ -24,7 +24,8 @@ pub mod prelude {
pub use dioxus_core::prelude::*;
#[cfg(feature = "macro")]
pub use dioxus_core_macro::{format_args_f, inline_props, render, rsx, Props};
#[allow(deprecated)]
pub use dioxus_core_macro::{component, format_args_f, inline_props, render, rsx, Props};
#[cfg(feature = "html")]
pub use dioxus_html as dioxus_elements;
+1 -1
View File
@@ -14,7 +14,7 @@ keywords = ["dom", "ui", "gui", "react", "state-management"]
[dependencies]
dioxus-core = { workspace = true }
im-rc = { version = "15.0.0", features = ["serde"] }
log = { workspace = true }
tracing = { workspace = true }
[dev-dependencies]
closure = "0.3.0"
+4 -4
View File
@@ -66,14 +66,14 @@ impl AtomRoot {
if let Some(slot) = atoms.get_mut(&ptr) {
slot.value = Rc::new(value);
log::trace!("found item with subscribers {:?}", slot.subscribers);
tracing::trace!("found item with subscribers {:?}", slot.subscribers);
for scope in &slot.subscribers {
log::trace!("updating subcsriber");
tracing::trace!("updating subcsriber");
(self.update_any)(*scope);
}
} else {
log::trace!("no atoms found for {:?}", ptr);
tracing::trace!("no atoms found for {:?}", ptr);
atoms.insert(
ptr,
Slot {
@@ -96,7 +96,7 @@ impl AtomRoot {
pub fn force_update(&self, ptr: AtomId) {
if let Some(slot) = self.atoms.borrow_mut().get(&ptr) {
for scope in slot.subscribers.iter() {
log::trace!("updating subcsriber");
tracing::trace!("updating subcsriber");
(self.update_any)(*scope);
}
}
+2 -1
View File
@@ -44,7 +44,8 @@ dioxus-desktop = { workspace = true, optional = true }
# Router Integration
dioxus-router = { workspace = true, optional = true }
log = { workspace = true }
tracing = { workspace = true }
tracing-futures = { workspace = true }
once_cell = "1.17.1"
thiserror = { workspace = true }
tokio = { workspace = true, features = ["full"], optional = true }
+1 -1
View File
@@ -15,7 +15,7 @@
[discord-url]: https://discord.gg/XgGxMSkvUM
[Website](https://dioxuslabs.com) |
[Guides](https://dioxuslabs.com/docs/0.3/guide/en/) |
[Guides](https://dioxuslabs.com/learn/0.4/) |
[API Docs](https://docs.rs/dioxus-fullstack/latest/dioxus_sever) |
[Chat](https://discord.gg/XgGxMSkvUM)
@@ -12,8 +12,9 @@ dioxus-fullstack = { workspace = true }
axum = { version = "0.6.12", optional = true }
serde = "1.0.159"
simple_logger = "4.2.0"
wasm-logger = "0.2.0"
log.workspace = true
tracing-wasm = "0.2.1"
tracing.workspace = true
tracing-subscriber = "0.3.17"
reqwest = "0.11.18"
[features]
@@ -12,7 +12,6 @@ use dioxus_fullstack::{
prelude::*,
};
use serde::{Deserialize, Serialize};
use wasm_logger::Config;
#[derive(Props, PartialEq, Debug, Default, Serialize, Deserialize, Clone)]
struct AppProps {
@@ -66,9 +65,9 @@ async fn get_server_data() -> Result<String, ServerFnError> {
fn main() {
#[cfg(feature = "web")]
wasm_logger::init(wasm_logger::Config::new(log::Level::Trace));
tracing_wasm::set_as_global_default();
#[cfg(feature = "ssr")]
simple_logger::SimpleLogger::new().init().unwrap();
tracing_subscriber::fmt::init();
LaunchBuilder::new_with_props(app, AppProps { count: 0 }).launch()
}
@@ -5,8 +5,6 @@
//! cargo run --features ssr --release
//! ```
#![allow(non_snake_case)]
use dioxus::prelude::*;
use dioxus_fullstack::prelude::*;
use dioxus_router::prelude::*;
@@ -33,7 +31,7 @@ enum Route {
Blog { id: i32 },
}
#[inline_props]
#[component]
fn Blog(cx: Scope, id: i32) -> Element {
render! {
Link { to: Route::Home {}, "Go to counter" }
@@ -51,7 +49,7 @@ fn Blog(cx: Scope, id: i32) -> Element {
}
}
#[inline_props]
#[component]
fn Home(cx: Scope) -> Element {
let mut count = use_state(cx, || 0);
let text = use_state(cx, || "...".to_string());
@@ -16,8 +16,9 @@ salvo = { version = "0.37.9", optional = true }
execute = "0.2.12"
reqwest = "0.11.18"
simple_logger = "4.2.0"
log.workspace = true
wasm-logger = "0.2.0"
tracing-wasm = "0.2.1"
tracing.workspace = true
tracing-subscriber = "0.3.17"
[features]
default = []
@@ -60,9 +60,9 @@ async fn get_server_data() -> Result<String, ServerFnError> {
fn main() {
#[cfg(feature = "web")]
wasm_logger::init(wasm_logger::Config::new(log::Level::Trace));
tracing_wasm::set_as_global_default();
#[cfg(feature = "ssr")]
simple_logger::SimpleLogger::new().init().unwrap();
tracing_subscriber::fmt::init();
LaunchBuilder::new_with_props(app, AppProps { count: 0 }).launch()
}
@@ -5,7 +5,7 @@
//! cargo run --features ssr
//! ```
#![allow(non_snake_case, unused)]
#![allow(unused)]
use dioxus::prelude::*;
use dioxus_fullstack::{launch, prelude::*};
use dioxus_router::prelude::*;
@@ -49,7 +49,7 @@ enum Route {
Blog,
}
#[inline_props]
#[component]
fn Blog(cx: Scope) -> Element {
render! {
Link { to: Route::Home {}, "Go to counter" }
@@ -67,7 +67,7 @@ fn Blog(cx: Scope) -> Element {
}
}
#[inline_props]
#[component]
fn Home(cx: Scope) -> Element {
let mut count = use_state(cx, || 0);
let text = use_state(cx, || "...".to_string());
@@ -16,8 +16,9 @@ warp = { version = "0.3.3", optional = true }
execute = "0.2.12"
reqwest = "0.11.18"
simple_logger = "4.2.0"
log.workspace = true
wasm-logger = "0.2.0"
tracing-wasm = "0.2.1"
tracing.workspace = true
tracing-subscriber = "0.3.17"
[features]
default = []
@@ -60,9 +60,9 @@ async fn get_server_data() -> Result<String, ServerFnError> {
fn main() {
#[cfg(feature = "web")]
wasm_logger::init(wasm_logger::Config::new(log::Level::Trace));
tracing_wasm::set_as_global_default();
#[cfg(feature = "ssr")]
simple_logger::SimpleLogger::new().init().unwrap();
tracing_subscriber::fmt::init();
LaunchBuilder::new_with_props(app, AppProps { count: 0 }).launch()
}
@@ -263,8 +263,8 @@ where
let res = service.run(req);
match res.await {
Ok(res) => Ok::<_, std::convert::Infallible>(res.map(|b| b.into())),
Err(_e) => {
let mut res = Response::new(Body::empty());
Err(e) => {
let mut res = Response::new(Body::from(e.to_string()));
*res.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
Ok(res)
}
@@ -389,7 +389,7 @@ pub async fn render_handler<P: Clone + serde::Serialize + Send + Sync + 'static>
response
}
Err(e) => {
log::error!("Failed to render page: {}", e);
tracing::error!("Failed to render page: {}", e);
report_err(e).into_response()
}
}
@@ -423,7 +423,7 @@ impl<P: Clone + serde::Serialize + Send + Sync + 'static> Handler for SSRHandler
freshness.write(res.headers_mut());
}
Err(err) => {
log::error!("Error rendering SSR: {}", err);
tracing::error!("Error rendering SSR: {}", err);
res.write_body("Error rendering SSR").unwrap();
}
};
@@ -84,7 +84,7 @@ use warp::{
/// async move {
/// let req = warp::hyper::Request::from_parts(parts, bytes.into());
/// service.run(req).await.map_err(|err| {
/// log::error!("Server function error: {}", err);
/// tracing::error!("Server function error: {}", err);
/// warp::reject::reject()
/// })
/// }
@@ -142,8 +142,18 @@ pub fn register_server_fns(server_fn_route: &'static str) -> BoxedFilter<(impl R
async move {
let req = warp::hyper::Request::from_parts(parts, bytes.into());
service.run(req).await.map_err(|err| {
log::error!("Server function error: {}", err);
warp::reject::reject()
tracing::error!("Server function error: {}", err);
struct WarpServerFnError(String);
impl std::fmt::Debug for WarpServerFnError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl warp::reject::Reject for WarpServerFnError {}
warp::reject::custom(WarpServerFnError(err.to_string()))
})
}
})
@@ -222,7 +232,7 @@ pub fn render_ssr<P: Clone + serde::Serialize + Send + Sync + 'static>(
res
}
Err(err) => {
log::error!("Failed to render ssr: {}", err);
tracing::error!("Failed to render ssr: {}", err);
Response::builder()
.status(500)
.body("Failed to render ssr".into())
Loaded 100 of 434 files, more files were not shown because too many files have changed in this diff. Show more