Merge branch 'master' into intigrate-collect-assets

This commit is contained in:
Evan Almloff committed 2023-09-17 19:40:14 -05:00
1 parent ffb5de91d1
commit f976e08f71
379 files changed
+1962 -13517

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
+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),
}
+47 -58
View File
@@ -1,12 +1,12 @@
use crate::server::Platform;
use crate::{
cfg::ConfigOptsServe,
server::{
output::{print_console_info, PrettierOptions},
setup_file_watcher, setup_file_watcher_hot_reload,
setup_file_watcher,
},
BuildResult, CrateConfig, Result,
};
use dioxus_hot_reload::HotReloadMsg;
use dioxus_html::HtmlCtx;
use dioxus_rsx::hot_reload::*;
@@ -20,7 +20,7 @@ use tokio::sync::broadcast::{self};
#[cfg(feature = "plugin")]
use plugin::PluginManager;
use super::Platform;
use super::HotReloadState;
pub async fn startup(config: CrateConfig, serve: &ConfigOptsServe) -> Result<()> {
startup_with_platform::<DesktopPlatform>(config, serve).await
@@ -28,7 +28,7 @@ pub async fn startup(config: CrateConfig, serve: &ConfigOptsServe) -> Result<()>
pub(crate) async fn startup_with_platform<P: Platform + Send + 'static>(
config: CrateConfig,
serve: &ConfigOptsServe,
serve_cfg: &ConfigOptsServe,
) -> Result<()> {
// ctrl-c shutdown checker
let _crate_config = config.clone();
@@ -38,18 +38,39 @@ pub(crate) async fn startup_with_platform<P: Platform + Send + 'static>(
std::process::exit(0);
});
match config.hot_reload {
true => serve_hot_reload::<P>(config, serve).await?,
false => serve_default::<P>(config, serve).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::<P>(config, serve_cfg, hot_reload_state).await?;
Ok(())
}
/// Start the server without hot reload
async fn serve_default<P: Platform + Send + 'static>(
async fn serve<P: Platform + Send + 'static>(
config: CrateConfig,
serve: &ConfigOptsServe,
hot_reload_state: Option<HotReloadState>,
) -> Result<()> {
let platform = RwLock::new(P::start(&config, serve)?);
@@ -65,68 +86,34 @@ async fn serve_default<P: Platform + Send + 'static>(
},
&config,
None,
hot_reload_state.clone(),
)
.await?;
std::future::pending::<()>().await;
match &hot_reload_state {
Some(hot_reload_state) => {
// The open interprocess sockets
start_desktop_hot_reload(hot_reload_state).await?;
}
None => {
std::future::pending::<()>().await;
}
}
Ok(())
}
/// Start dx serve with hot reload
async fn serve_hot_reload<P: Platform + Send + 'static>(
config: CrateConfig,
serve: &ConfigOptsServe,
) -> Result<()> {
let platform = RwLock::new(P::start(&config, serve)?);
// Setup hot reload
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, mut hot_reload_rx) = broadcast::channel(100);
// States
// The open interprocess sockets
let channels = Arc::new(Mutex::new(Vec::new()));
// Setup file watcher
// We got to own watcher so that it exists for the duration of serve
// Otherwise hot reload won't work.
let _watcher = setup_file_watcher_hot_reload(
&config,
hot_reload_tx,
file_map.clone(),
{
let config = config.clone();
let channels = channels.clone();
move || {
for channel in &mut *channels.lock().unwrap() {
send_msg(HotReloadMsg::Shutdown, channel);
}
platform.write().unwrap().rebuild(&config)
}
},
None,
)
.await?;
clear_paths();
async fn start_desktop_hot_reload(hot_reload_state: &HotReloadState) -> Result<()> {
match LocalSocketListener::bind("@dioxusin") {
Ok(local_socket_stream) => {
let aborted = Arc::new(Mutex::new(false));
// States
// The open interprocess sockets
let channels = Arc::new(Mutex::new(Vec::new()));
// listen for connections
std::thread::spawn({
let file_map = file_map.clone();
let file_map = hot_reload_state.file_map.clone();
let channels = channels.clone();
let aborted = aborted.clone();
let _ = local_socket_stream.set_nonblocking(true);
@@ -161,6 +148,8 @@ async fn serve_hot_reload<P: Platform + Send + 'static>(
}
});
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;
+80 -124
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::*;
@@ -22,6 +22,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();
@@ -39,28 +40,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),
}
}
}
@@ -78,113 +132,15 @@ 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)
}
pub(crate) trait Platform {
fn start(config: &CrateConfig, serve: &ConfigOptsServe) -> Result<Self>
where
Self: Sized;
fn rebuild(&mut self, config: &CrateConfig) -> Result<BuildResult>;
}
#[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");
+36 -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,
};
@@ -63,21 +63,48 @@ pub async fn startup(
let ip = get_ip().unwrap_or(String::from("0.0.0.0"));
match config.hot_reload {
true => serve_hot_reload(ip, port, config, start_browser, skip_assets).await?,
false => serve_default(ip, port, config, start_browser, skip_assets).await?,
}
let hot_reload_state = match config.hot_reload {
true => {
let FileMapBuildResult { map, errors } =
FileMap::<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,
skip_assets,
hot_reload_state,
)
.await?;
Ok(())
}
/// Start the server without hot reload
async fn serve_default(
pub async fn serve(
ip: String,
port: u16,
config: CrateConfig,
start_browser: bool,
skip_assets: bool,
hot_reload_state: Option<HotReloadState>,
) -> Result<()> {
let first_build_result = crate::builder::build(&config, false, skip_assets)?;
@@ -99,6 +126,7 @@ async fn serve_default(
ip: ip.clone(),
port,
}),
hot_reload_state.clone(),
)
.await?;
@@ -125,89 +153,7 @@ async fn serve_default(
);
// Router
let router = setup_router(config, ws_reload_state, None).await?;
// Start server
start_server(port, router, start_browser, rustls_config).await?;
Ok(())
}
/// Start dx serve with hot reload
async fn serve_hot_reload(
ip: String,
port: u16,
config: CrateConfig,
start_browser: bool,
skip_assets: bool,
) -> Result<()> {
let first_build_result = crate::builder::build(&config, false, skip_assets)?;
log::info!("🚀 Starting development server...");
// Setup hot reload
let (reload_tx, _) = broadcast::channel(100);
let FileMapBuildResult { map, errors } =
FileMap::<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, skip_assets)
},
Some(WebServerInfo {
ip: ip.clone(),
port,
}),
)
.await?;
// HTTPS
// Before console info so it can stop if mkcert isn't installed or fails
let rustls_config = get_rustls(&config).await?;
// Print serve info
print_console_info(
&config,
PrettierOptions {
changed: vec![],
warnings: first_build_result.warnings,
elapsed_time: first_build_result.elapsed_time,
},
Some(WebServerInfo {
ip: ip.clone(),
port,
}),
);
// Router
let router = setup_router(config, ws_reload_state, Some(hot_reload_state)).await?;
let router = setup_router(config, ws_reload_state, hot_reload_state).await?;
// Start server
start_server(port, router, start_browser, rustls_config).await?;
@@ -298,7 +244,7 @@ fn get_rustls_without_mkcert(web_config: &WebHttpsConfig) -> Result<(String, Str
async fn setup_router(
config: CrateConfig,
ws_reload: Arc<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 }
+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()
}
}
+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! {
+1 -1
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)]
+6 -5
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::{in_runtime, override_runtime, Runtime};
pub use crate::scheduler::*;
pub use crate::scope_context::*;
pub use crate::scopes::*;
@@ -86,11 +87,11 @@ pub use crate::innerlude::{
pub mod prelude {
pub use crate::innerlude::{
consume_context, consume_context_from_scope, current_scope_id, fc_to_builder, has_context,
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,
in_runtime, override_runtime, 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, Runtime, Scope, ScopeId, ScopeState, Scoped,
TaskId, Template, TemplateAttribute, TemplateNode, Throw, VNode, VirtualDom,
};
}
+54 -3
View File
@@ -7,6 +7,51 @@ thread_local! {
static RUNTIMES: RefCell<Vec<Rc<Runtime>>> = RefCell::new(vec![]);
}
/// Run some code within a runtime
pub fn in_runtime<R>(runtime: Rc<Runtime>, f: impl FnOnce() -> R) -> R {
let _guard = RuntimeGuard::new(runtime);
f()
}
/// Override the current 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(|| override_runtime(cx.props.runtime.clone()));
///
/// render! { div {} }
/// }
/// ```
pub fn override_runtime(runtime: Rc<Runtime>) {
RUNTIMES.with(|stack| {
let mut stack = stack.borrow_mut();
stack.pop();
stack.push(runtime);
});
}
/// Pushes a new scope onto the stack
pub(crate) fn push_runtime(runtime: Rc<Runtime>) {
RUNTIMES.with(|stack| stack.borrow_mut().push(runtime));
@@ -41,7 +86,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 +109,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 +128,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())
})
+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()
};
+34 -7
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
+14 -5
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());
///
@@ -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 });
}
}
@@ -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,6 +662,11 @@ 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 {
+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
+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),
+24 -18
View File
@@ -2,13 +2,14 @@ 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::ROOT);
@@ -17,7 +18,8 @@ fn app_drops() {
#[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,7 +30,7 @@ fn hooks_drop() {
})
}
let mut dom = VirtualDom::new(app);
let mut dom = VirtualDom::new(App);
_ = dom.rebuild();
dom.mark_dirty(ScopeId::ROOT);
@@ -37,17 +39,19 @@ fn hooks_drop() {
#[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,7 +59,7 @@ fn contexts_drop() {
})
}
let mut dom = VirtualDom::new(app);
let mut dom = VirtualDom::new(App);
_ = dom.rebuild();
dom.mark_dirty(ScopeId::ROOT);
@@ -64,7 +68,8 @@ fn contexts_drop() {
#[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,7 +79,7 @@ fn tasks_drop() {
})
}
let mut dom = VirtualDom::new(app);
let mut dom = VirtualDom::new(App);
_ = dom.rebuild();
dom.mark_dirty(ScopeId::ROOT);
@@ -97,29 +102,30 @@ fn root_props_drop() {
#[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::ROOT);
+8 -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",
@@ -52,7 +52,7 @@ 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"]
@@ -60,6 +60,10 @@ devtools = ["wry/devtools"]
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
@@ -334,7 +334,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
@@ -149,7 +149,7 @@ pub(super) fn desktop_handler(
.map_err(From::from);
}
log::error!(
tracing::error!(
"Failed to find {} (as path {})",
request.uri().path(),
asset.display()
+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())
@@ -23,7 +23,7 @@ pub fn server_cached<O: 'static + Serialize + DeserializeOwned>(server_fn: impl
let data = server_fn();
let sc = crate::prelude::server_context();
if let Err(err) = sc.push_html_data(&data) {
log::error!("Failed to push HTML data: {}", err);
tracing::error!("Failed to push HTML data: {}", err);
}
data
}
@@ -47,13 +47,13 @@ where
if first_run {
match crate::html_storage::deserialize::take_server_data() {
Some(data) => {
log::trace!("Loaded {data:?} from server");
tracing::trace!("Loaded {data:?} from server");
*state.value.borrow_mut() = Some(Box::new(data));
state.needs_regen.set(false);
return Some(state);
}
None => {
log::trace!("Failed to load from server... running future");
tracing::trace!("Failed to load from server... running future");
}
};
}
@@ -82,7 +82,7 @@ where
data = fut.await;
if first_run {
if let Err(err) = crate::prelude::server_context().push_html_data(&data) {
log::error!("Failed to push HTML data: {}", err);
tracing::error!("Failed to push HTML data: {}", err);
};
}
}
@@ -99,7 +99,7 @@ where
if first_run {
#[cfg(feature = "ssr")]
{
log::trace!("Suspending first run of use_server_future");
tracing::trace!("Suspending first run of use_server_future");
cx.suspend();
}
None
+1 -1
View File
@@ -30,7 +30,7 @@ impl Default for HotReloadState {
}
if let Err(err) = tx.send(Some(template)) {
log::error!("Failed to send hot reload message: {}", err);
tracing::error!("Failed to send hot reload message: {}", err);
}
}
dioxus_hot_reload::HotReloadMsg::Shutdown => {
@@ -10,7 +10,7 @@ pub(crate) fn serde_from_bytes<T: DeserializeOwned>(string: &[u8]) -> Option<T>
let decompressed = match STANDARD.decode(string) {
Ok(bytes) => bytes,
Err(err) => {
log::error!("Failed to decode base64: {}", err);
tracing::error!("Failed to decode base64: {}", err);
return None;
}
};
@@ -18,7 +18,7 @@ pub(crate) fn serde_from_bytes<T: DeserializeOwned>(string: &[u8]) -> Option<T>
match postcard::from_bytes(&decompressed) {
Ok(data) => Some(data),
Err(err) => {
log::error!("Failed to deserialize: {}", err);
tracing::error!("Failed to deserialize: {}", err);
None
}
}
@@ -32,14 +32,14 @@ static SERVER_DATA: once_cell::sync::Lazy<Option<HTMLDataCursor>> =
let element = match window.get_element_by_id("dioxus-storage-data") {
Some(element) => element,
None => {
log::error!("Failed to get element by id: dioxus-storage-data");
tracing::error!("Failed to get element by id: dioxus-storage-data");
return None;
}
};
let attribute = match element.get_attribute("data-serialized") {
Some(attribute) => attribute,
None => {
log::error!("Failed to get attribute: data-serialized");
tracing::error!("Failed to get attribute: data-serialized");
return None;
}
};
+2 -2
View File
@@ -36,7 +36,7 @@ impl HTMLDataCursor {
pub fn take<T: DeserializeOwned>(&self) -> Option<T> {
let current = self.index.load(std::sync::atomic::Ordering::SeqCst);
if current >= self.data.len() {
log::error!(
tracing::error!(
"Tried to take more data than was available, len: {}, index: {}",
self.data.len(),
current
@@ -48,7 +48,7 @@ impl HTMLDataCursor {
match postcard::from_bytes(cursor) {
Ok(x) => Some(x),
Err(e) => {
log::error!("Error deserializing data: {:?}", e);
tracing::error!("Error deserializing data: {:?}", e);
None
}
}
+6 -1
View File
@@ -1,4 +1,5 @@
use std::pin::Pin;
use tracing_futures::Instrument;
use http::{Request, Response};
@@ -45,7 +46,11 @@ where
> + Send,
>,
> {
let fut = self.call(req);
let fut = self.call(req).instrument(tracing::trace_span!(
"service",
"{}",
std::any::type_name::<S>()
));
Box::pin(async move { fut.await.map_err(|err| err.into()) })
}
}
+4 -4
View File
@@ -50,10 +50,10 @@ impl SsrRendererPool {
let prev_context =
SERVER_CONTEXT.with(|ctx| ctx.replace(server_context));
// poll the future, which may call server_context()
log::info!("Rebuilding vdom");
tracing::info!("Rebuilding vdom");
let _ = vdom.rebuild();
vdom.wait_for_suspense().await;
log::info!("Suspense resolved");
tracing::info!("Suspense resolved");
// after polling the future, we need to restore the context
SERVER_CONTEXT.with(|ctx| ctx.replace(prev_context));
@@ -116,10 +116,10 @@ impl SsrRendererPool {
let prev_context = SERVER_CONTEXT
.with(|ctx| ctx.replace(Box::new(server_context)));
// poll the future, which may call server_context()
log::info!("Rebuilding vdom");
tracing::info!("Rebuilding vdom");
let _ = vdom.rebuild();
vdom.wait_for_suspense().await;
log::info!("Suspense resolved");
tracing::info!("Suspense resolved");
// after polling the future, we need to restore the context
SERVER_CONTEXT.with(|ctx| ctx.replace(prev_context));
})
+1 -1
View File
@@ -29,7 +29,7 @@ where
.to_string()
.parse()
.unwrap_or_else(|err| {
log::error!("Failed to parse uri: {}", err);
tracing::error!("Failed to parse uri: {}", err);
"/"
.parse()
.unwrap_or_else(|err| {
+1 -1
View File
@@ -16,7 +16,7 @@ nightly-features = []
[dependencies]
dioxus-core = { workspace = true }
futures-channel = { workspace = true }
log = { workspace = true }
tracing = { workspace = true }
thiserror = { workspace = true }
slab = { workspace = true }
dioxus-debug-cell = "0.1.1"
+2 -7
View File
@@ -1,6 +1,5 @@
# Dioxus Hooks
[![Crates.io][crates-badge]][crates-url]
[![MIT licensed][mit-badge]][mit-url]
[![Build Status][actions-badge]][actions-url]
@@ -8,22 +7,18 @@
[crates-badge]: https://img.shields.io/crates/v/dioxus-hooks.svg
[crates-url]: https://crates.io/crates/dioxus-hooks
[mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg
[mit-url]: https://github.com/dioxuslabs/dioxus/blob/master/LICENSE
[actions-badge]: https://github.com/dioxuslabs/dioxus/actions/workflows/main.yml/badge.svg
[actions-url]: https://github.com/dioxuslabs/dioxus/actions?query=workflow%3ACI+branch%3Amaster
[discord-badge]: https://img.shields.io/discord/899851952891002890.svg?logo=discord&style=flat-square
[discord-url]: https://discord.gg/XgGxMSkvUM
[Website](https://dioxuslabs.com) |
[Guides](https://dioxuslabs.com/docs/0.3/guide/en/) |
[Guides](https://dioxuslabs.com/learn/0.4/) |
[API Docs](https://docs.rs/dioxus-hooks/latest/dioxus_hooks) |
[Chat](https://discord.gg/XgGxMSkvUM)
## Overview
`dioxus-hooks` includes some basic useful hooks for dioxus:
@@ -42,13 +37,13 @@ This crate also provides a few helpful macros to get around some Rust lifetime m
- `use_future!()`
- `use_callback!()`
## Contributing
- Report issues on our [issue tracker](https://github.com/dioxuslabs/dioxus/issues).
- Join the discord and ask questions!
## License
This project is licensed under the [MIT license].
[mit license]: https://github.com/DioxusLabs/dioxus/blob/master/LICENSE-MIT
+2 -1
View File
@@ -17,6 +17,7 @@ use std::{
/// ```rust
/// use dioxus::prelude::*;
///
/// #[component]
/// fn Parent(cx: Scope) -> Element {
/// let count = use_tracked_state(cx, || 0);
///
@@ -27,7 +28,7 @@ use std::{
/// }
/// }
///
/// #[inline_props]
/// #[component]
/// fn Child(cx: Scope, count: Tracked<usize>) -> Element {
/// let less_than_five = use_selector(cx, count, |count| *count < 5);
///
+14 -7
View File
@@ -81,10 +81,12 @@ pub(crate) struct ProvidedStateInner<T> {
value: T,
notify_any: Arc<dyn Fn(ScopeId)>,
consumers: HashSet<ScopeId>,
gen: usize,
}
impl<T> ProvidedStateInner<T> {
pub(crate) fn notify_consumers(&mut self) {
self.gen += 1;
for consumer in self.consumers.iter() {
(self.notify_any)(*consumer);
}
@@ -157,7 +159,7 @@ impl<T> ProvidedStateInner<T> {
///
/// Right now, there is not a distinction between read-only and write-only, so every consumer will be notified.
pub fn use_shared_state<T: 'static>(cx: &ScopeState) -> Option<&UseSharedState<T>> {
let state: &Option<UseSharedStateOwner<T>> = &*cx.use_hook(move || {
let state_owner: &mut Option<UseSharedStateOwner<T>> = &mut *cx.use_hook(move || {
let scope_id = cx.scope_id();
let root = cx.consume_context::<ProvidedState<T>>()?;
@@ -167,7 +169,10 @@ pub fn use_shared_state<T: 'static>(cx: &ScopeState) -> Option<&UseSharedState<T
let owner = UseSharedStateOwner { state, scope_id };
Some(owner)
});
state.as_ref().map(|s| &s.state)
state_owner.as_mut().map(|s| {
s.state.gen = s.state.inner.borrow().gen;
&s.state
})
}
/// This wrapper detects when the hook is dropped and will unsubscribe when the component is unmounted
@@ -187,11 +192,13 @@ impl<T> Drop for UseSharedStateOwner<T> {
/// State that is shared between components through the context system
pub struct UseSharedState<T> {
pub(crate) inner: Rc<RefCell<ProvidedStateInner<T>>>,
gen: usize,
}
impl<T> UseSharedState<T> {
fn new(inner: Rc<RefCell<ProvidedStateInner<T>>>) -> Self {
Self { inner }
let gen = inner.borrow().gen;
Self { inner, gen }
}
/// Notify all consumers of the state that it has changed. (This is called automatically when you call "write")
@@ -302,15 +309,14 @@ impl<T> Clone for UseSharedState<T> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
gen: self.gen,
}
}
}
impl<T: PartialEq> PartialEq for UseSharedState<T> {
impl<T> PartialEq for UseSharedState<T> {
fn eq(&self, other: &Self) -> bool {
let first = self.inner.borrow();
let second = other.inner.borrow();
first.value == second.value
self.gen == other.gen
}
}
@@ -360,6 +366,7 @@ pub fn use_shared_state_provider<T: 'static>(cx: &ScopeState, f: impl FnOnce() -
value: f(),
notify_any: cx.schedule_update_any(),
consumers: HashSet::new(),
gen: 0,
}));
cx.provide_context(state);
+4 -2
View File
@@ -14,7 +14,8 @@ use crate::UseFutureDep;
/// ## Examples
///
/// ```rust, no_run
/// #[inline_props]
/// # use dioxus::prelude::*;
/// #[component]
/// fn Profile(cx: Scope, id: usize) -> Element {
/// let name = use_state(cx, || None);
///
@@ -34,7 +35,8 @@ use crate::UseFutureDep;
/// )
/// }
///
/// fn app(cx: Scope) -> Element {
/// #[component]
/// fn App(cx: Scope) -> Element {
/// render!(Profile { id: 0 })
/// }
/// ```
+1 -1
View File
@@ -14,7 +14,7 @@ use crate::{use_state, UseState};
///
/// Whenever the hooks dependencies change, the future will be re-evaluated.
/// If a future is pending when the dependencies change, the previous future
/// will be allowed to continue
/// will be canceled before the new one is started.
///
/// - dependencies: a tuple of references to values that are PartialEq + Clone
pub fn use_future<T, F, D>(
+5 -2
View File
@@ -10,8 +10,9 @@ use crate::UseFutureDep;
/// ## Examples
///
/// ```rust, no_run
/// # use dioxus::prelude::*;
///
/// #[inline_props]
/// #[component]
/// fn Calculator(cx: Scope, number: usize) -> Element {
/// let bigger_number = use_memo(cx, (number,), |(number,)| {
/// // This will only be calculated when `number` has changed.
@@ -21,7 +22,9 @@ use crate::UseFutureDep;
/// p { "{bigger_number}" }
/// )
/// }
/// fn app(cx: Scope) -> Element {
///
/// #[component]
/// fn App(cx: Scope) -> Element {
/// render!(Calculator { number: 0 })
/// }
/// ```
+1 -1
View File
@@ -5,7 +5,7 @@ version = { workspace = true }
edition = "2021"
license = "MIT OR Apache-2.0"
repository = "https://github.com/DioxusLabs/dioxus/"
homepage = "https://dioxuslabs.com/docs/0.3/guide/en/getting_started/hot_reload.html"
homepage = "https://dioxuslabs.com/learn/0.4/migration/hot_reload"
description = "Hot reloading utilities for Dioxus"
keywords = ["dom", "ui", "gui", "react", "hot-reloading"]
+8 -7
View File
@@ -1,6 +1,5 @@
# `dioxus-hot-reload`: Hot Reloading Utilites for Dioxus
[![Crates.io][crates-badge]][crates-url]
[![MIT licensed][mit-badge]][mit-url]
[![Build Status][actions-badge]][actions-url]
@@ -8,28 +7,24 @@
[crates-badge]: https://img.shields.io/crates/v/dioxus-hot-reload.svg
[crates-url]: https://crates.io/crates/dioxus-hot-reload
[mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg
[mit-url]: https://github.com/dioxuslabs/dioxus/blob/master/LICENSE
[actions-badge]: https://github.com/dioxuslabs/dioxus/actions/workflows/main.yml/badge.svg
[actions-url]: https://github.com/dioxuslabs/dioxus/actions?query=workflow%3ACI+branch%3Amaster
[discord-badge]: https://img.shields.io/discord/899851952891002890.svg?logo=discord&style=flat-square
[discord-url]: https://discord.gg/XgGxMSkvUM
[Website](https://dioxuslabs.com) |
[Guides](https://dioxuslabs.com/docs/0.3/guide/en) |
[Guides](https://dioxuslabs.com/learn/0.4/) |
[API Docs](https://docs.rs/dioxus-hot-reload/latest/dioxus_hot_reload) |
[Chat](https://discord.gg/XgGxMSkvUM)
## Overview
Dioxus supports hot reloading for static parts of rsx macros. This enables changing the styling of your application without recompiling the rust code. This is useful for rapid iteration on the styling of your application.
Hot reloading could update the following change without recompiling:
```rust
rsx! {
div {
@@ -37,7 +32,9 @@ rsx! {
}
}
```
=>
```rust
rsx! {
div {
@@ -49,6 +46,7 @@ rsx! {
```
But it could not update the following change:
```rust
rsx! {
div {
@@ -56,7 +54,9 @@ rsx! {
}
}
```
=>
```rust
rsx! {
div {
@@ -161,6 +161,7 @@ async fn launch(app: Component) {
- Join the discord and ask questions!
## License
This project is licensed under the [MIT license].
[mit license]: https://github.com/DioxusLabs/dioxus/blob/master/LICENSE-MIT
+4 -11
View File
@@ -1,6 +1,5 @@
# `dioxus-html`: Html (and SVG) Namespace for Dioxus
[![Crates.io][crates-badge]][crates-url]
[![MIT licensed][mit-badge]][mit-url]
[![Build Status][actions-badge]][actions-url]
@@ -8,22 +7,18 @@
[crates-badge]: https://img.shields.io/crates/v/dioxus-html.svg
[crates-url]: https://crates.io/crates/dioxus-html
[mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg
[mit-url]: https://github.com/dioxuslabs/dioxus/blob/master/LICENSE
[actions-badge]: https://github.com/dioxuslabs/dioxus/actions/workflows/main.yml/badge.svg
[actions-url]: https://github.com/dioxuslabs/dioxus/actions?query=workflow%3ACI+branch%3Amaster
[discord-badge]: https://img.shields.io/discord/899851952891002890.svg?logo=discord&style=flat-square
[discord-url]: https://discord.gg/XgGxMSkvUM
[Website](https://dioxuslabs.com) |
[Guides](https://dioxuslabs.com/docs/0.3/guide/en/) |
[Guides](https://dioxuslabs.com/learn/0.4/) |
[API Docs](https://docs.rs/dioxus-html/latest/dioxus_html) |
[Chat](https://discord.gg/XgGxMSkvUM)
## Overview
The Dioxus `rsx!` and `html!` macros can accept any compile-time correct namespace on top of NodeFactory. This crate provides the HTML (and SVG) namespaces which get imported in the Dioxus prelude.
@@ -64,6 +59,7 @@ All elements should be defined as a zero-sized-struct (also known as unit struct
Attributes would then be implemented as constants on these unit structs.
The HTML namespace is defined mostly with macros. However, the expanded form would look something like this:
```rust
struct base;
impl DioxusElement for base {
@@ -75,8 +71,8 @@ impl base {
const target: (&'static str, Option<'static str>, bool) = ("target", None, false);
}
```
Because attributes are defined as methods on the unit struct, they guard the attribute creation behind a compile-time correct interface.
Because attributes are defined as methods on the unit struct, they guard the attribute creation behind a compile-time correct interface.
## How to extend it:
@@ -93,16 +89,13 @@ mod dioxus_elements {
}
```
## Contributing
- Report issues on our [issue tracker](https://github.com/dioxuslabs/dioxus/issues).
- Join the discord and ask questions!
## License
This project is licensed under the [MIT license].
[mit license]: https://github.com/DioxusLabs/dioxus/blob/master/LICENSE-MIT
+2
View File
@@ -1258,6 +1258,8 @@ builder_constructors! {
spellcheck: BoolOrDefault DEFAULT,
wrap: Wrap DEFAULT,
value: String volatile,
initial_value: String DEFAULT,
};
+1 -1
View File
@@ -108,7 +108,7 @@ impl_event! {
///
/// ## Example
/// ```rust, ignore
/// rsx!( button { "click me", onclick: move |_| log::info!("Clicked!`") } )
/// rsx!( button { "click me", onclick: move |_| tracing::info!("Clicked!`") } )
/// ```
///
/// ## Reference
+2 -7
View File
@@ -1,6 +1,5 @@
# `dioxus-interpreter-js`
[![Crates.io][crates-badge]][crates-url]
[![MIT licensed][mit-badge]][mit-url]
[![Build Status][actions-badge]][actions-url]
@@ -8,35 +7,31 @@
[crates-badge]: https://img.shields.io/crates/v/dioxus-interpreter-js.svg
[crates-url]: https://crates.io/crates/dioxus-interpreter-js
[mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg
[mit-url]: https://github.com/dioxuslabs/dioxus/blob/master/LICENSE
[actions-badge]: https://github.com/dioxuslabs/dioxus/actions/workflows/main.yml/badge.svg
[actions-url]: https://github.com/dioxuslabs/dioxus/actions?query=workflow%3ACI+branch%3Amaster
[discord-badge]: https://img.shields.io/discord/899851952891002890.svg?logo=discord&style=flat-square
[discord-url]: https://discord.gg/XgGxMSkvUM
[Website](https://dioxuslabs.com) |
[Guides](https://dioxuslabs.com/docs/0.3/guide/en/) |
[Guides](https://dioxuslabs.com/learn/0.4/) |
[API Docs](https://docs.rs/dioxus-interpreter-js/latest/dioxus_interpreter_js) |
[Chat](https://discord.gg/XgGxMSkvUM)
## Overview
`dioxus-interpreter-js` provides the high-performance JavaScript glue that interprets the stream of edits produced by the Dioxus VirtualDom and converts them into mutations on the actual web DOM.
This crate features bindings for the web and sledgehammer for increased performance.
## Contributing
- Report issues on our [issue tracker](https://github.com/dioxuslabs/dioxus/issues).
- Join the discord and ask questions!
## License
This project is licensed under the [MIT license].
[mit license]: https://github.com/DioxusLabs/dioxus/blob/master/LICENSE-MIT
+29 -11
View File
@@ -390,7 +390,11 @@ class Interpreter {
function handler(event, name, bubbles, config) {
let target = event.target;
if (target != null) {
let preventDefaultRequests = target.getAttribute(`dioxus-prevent-default`);
let preventDefaultRequests = null;
// Some events can be triggered on text nodes, which don't have attributes
if (target instanceof Element) {
preventDefaultRequests = target.getAttribute(`dioxus-prevent-default`);
}
if (event.type === "click") {
// todo call prevent default if it's the right type of event
@@ -446,15 +450,24 @@ function handler(event, name, bubbles, config) {
target.tagName === "FORM" &&
(event.type === "submit" || event.type === "input")
) {
if (
target.tagName === "FORM" &&
(event.type === "submit" || event.type === "input")
) {
const formData = new FormData(target);
const formData = new FormData(target);
for (let name of formData.keys()) {
let value = formData.getAll(name);
contents.values[name] = value;
for (let name of formData.keys()) {
let value = formData.getAll(name);
contents.values[name] = value;
}
}
if (
target.tagName === "SELECT" &&
event.type === "input"
) {
const selectData = target.options;
contents.values["options"] = [];
for (let i = 0; i < selectData.length; i++) {
let option = selectData[i];
if (option.selected) {
contents.values["options"].push(option.value.toString());
}
}
}
@@ -474,7 +487,10 @@ function handler(event, name, bubbles, config) {
}
function find_real_id(target) {
let realId = target.getAttribute(`data-dioxus-id`);
let realId = null;
if (target instanceof Element) {
realId = target.getAttribute(`data-dioxus-id`);
}
// walk the tree to find the real element
while (realId == null) {
// we've reached the root we don't want to send an event
@@ -483,7 +499,9 @@ function find_real_id(target) {
}
target = target.parentElement;
realId = target.getAttribute(`data-dioxus-id`);
if (target instanceof Element) {
realId = target.getAttribute(`data-dioxus-id`);
}
}
return realId;
}
+2 -2
View File
@@ -3,7 +3,7 @@ name = "dioxus-liveview"
version = { workspace = true }
edition = "2021"
repository = "https://github.com/DioxusLabs/dioxus/"
homepage = "https://dioxuslabs.com/docs/0.3/guide/en/getting_started/liveview.html"
homepage = "https://dioxuslabs.com/learn/0.4/getting_started/liveview"
keywords = ["dom", "ui", "gui", "react", "liveview"]
description = "Build server-side apps with Dioxus"
authors = ["Jonathan Kelley", "Evan Almloff"]
@@ -11,7 +11,7 @@ license = "MIT OR Apache-2.0"
[dependencies]
thiserror = { workspace = true }
log = { workspace = true }
tracing = { workspace = true }
slab = { workspace = true }
futures-util = { workspace = true, default-features = false, features = [
"sink",
+2 -6
View File
@@ -1,6 +1,5 @@
# Dioxus Liveview
[![Crates.io][crates-badge]][crates-url]
[![MIT licensed][mit-badge]][mit-url]
[![Build Status][actions-badge]][actions-url]
@@ -8,22 +7,18 @@
[crates-badge]: https://img.shields.io/crates/v/dioxus-liveview.svg
[crates-url]: https://crates.io/crates/dioxus-liveview
[mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg
[mit-url]: https://github.com/dioxuslabs/dioxus/blob/master/LICENSE
[actions-badge]: https://github.com/dioxuslabs/dioxus/actions/workflows/main.yml/badge.svg
[actions-url]: https://github.com/dioxuslabs/dioxus/actions?query=workflow%3ACI+branch%3Amaster
[discord-badge]: https://img.shields.io/discord/899851952891002890.svg?logo=discord&style=flat-square
[discord-url]: https://discord.gg/XgGxMSkvUM
[Website](https://dioxuslabs.com) |
[Guides](https://dioxuslabs.com/docs/0.3/guide/en/) |
[Guides](https://dioxuslabs.com/learn/0.4/) |
[API Docs](https://docs.rs/dioxus-liveview/latest/dioxus_liveview) |
[Chat](https://discord.gg/XgGxMSkvUM)
## Overview
`dioxus-liveview` provides adapters for running the Dioxus VirtualDom over a WebSocket connection.
@@ -46,6 +41,7 @@ Dioxus-LiveView exports some primitives to wire up an app into an existing backe
- Join the discord and ask questions!
## License
This project is licensed under the [MIT license].
[mit license]: https://github.com/DioxusLabs/dioxus/blob/master/LICENSE-MIT
+1 -1
View File
@@ -126,7 +126,7 @@ impl QueryEngine {
}})
}})();"#
)) {
log::warn!("Query error: {err}");
tracing::warn!("Query error: {err}");
}
Query {
+1 -1
View File
@@ -5,7 +5,7 @@ authors = ["Jonathan Kelley"]
edition = "2018"
description = "Mobile-compatible renderer for Dioxus"
repository = "https://github.com/DioxusLabs/dioxus/"
homepage = "https://dioxuslabs.com/docs/0.3/guide/en/getting_started/mobile.html"
homepage = "https://dioxuslabs.com/learn/0.4/getting_started/mobile"
keywords = ["dom", "ui", "gui", "react"]
license = "MIT OR Apache-2.0"
+3 -10
View File
@@ -7,29 +7,24 @@
[crates-badge]: https://img.shields.io/crates/v/dioxus-mobile.svg
[crates-url]: https://crates.io/crates/dioxus-mobile
[mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg
[mit-url]: https://github.com/dioxuslabs/dioxus/blob/master/LICENSE
[actions-badge]: https://github.com/dioxuslabs/dioxus/actions/workflows/main.yml/badge.svg
[actions-url]: https://github.com/dioxuslabs/dioxus/actions?query=workflow%3ACI+branch%3Amaster
[discord-badge]: https://img.shields.io/discord/899851952891002890.svg?logo=discord&style=flat-square
[discord-url]: https://discord.gg/XgGxMSkvUM
[Website](https://dioxuslabs.com) |
[Guides](https://dioxuslabs.com/docs/0.3/guide/en/) |
[Guides](https://dioxuslabs.com/learn/0.4/) |
[API Docs](https://docs.rs/dioxus-mobile/latest/dioxus_mobile) |
[Chat](https://discord.gg/XgGxMSkvUM)
## Overview
`dioxus-mobile` is a re-export of `dioxus-desktop` with some minor tweaks and documentation changes. As this crate evolves, it will provide some more unique features to mobile, but for now, it's very similar to the desktop crate.
Dioxus Mobile supports both iOS and Android. However, Android support is still quite experimental and requires a lot of configuration. A good area to contribute here would be to improve the CLI tool to include bundling and mobile configuration.
## Getting Set up
Getting set up with mobile can but quite challenging. The tooling here isn't great (yet) and might take some hacking around to get things working. macOS M1 is broadly unexplored and might not work for you.
@@ -40,7 +35,6 @@ We're going to be using `cargo-mobile` to build for mobile. First, install it:
$ cargo install --git https://github.com/BrainiumLLC/cargo-mobile
```
And then initialize your app for the right platform. Use the `winit` template for now. Right now, there's no "Dioxus" template in cargo-mobile.
```shell
@@ -98,9 +92,7 @@ To configure the web view, menubar, and other important desktop-specific feature
## Future Steps
Make sure to read the [Dioxus Guide](https://dioxuslabs.com/docs/0.3/guide/en) if you already haven't!
Make sure to read the [Dioxus Guide](https://dioxuslabs.com/learn/0.4/) if you already haven't!
## Contributing
@@ -108,6 +100,7 @@ Make sure to read the [Dioxus Guide](https://dioxuslabs.com/docs/0.3/guide/en) i
- Join the discord and ask questions!
## License
This project is licensed under the [MIT license].
[mit license]: https://github.com/DioxusLabs/dioxus/blob/master/LICENSE-MIT
+2 -6
View File
@@ -7,33 +7,29 @@
[crates-badge]: https://img.shields.io/crates/v/dioxus-native-core-macro.svg
[crates-url]: https://crates.io/crates/dioxus-native-core-macro
[mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg
[mit-url]: https://github.com/dioxuslabs/dioxus/blob/master/LICENSE
[actions-badge]: https://github.com/dioxuslabs/dioxus/actions/workflows/main.yml/badge.svg
[actions-url]: https://github.com/dioxuslabs/dioxus/actions?query=workflow%3ACI+branch%3Amaster
[discord-badge]: https://img.shields.io/discord/899851952891002890.svg?logo=discord&style=flat-square
[discord-url]: https://discord.gg/XgGxMSkvUM
[Website](https://dioxuslabs.com) |
[Guides](https://dioxuslabs.com/docs/0.3/guide/en/) |
[Guides](https://dioxuslabs.com/learn/0.4/) |
[API Docs](https://docs.rs/dioxus-native-core-macro/latest/dioxus_native_core_macro) |
[Chat](https://discord.gg/XgGxMSkvUM)
## Overview
`dioxus-native-core-macro` provides a handful of macros used by native-core for native renderers like TUI, Blitz, and Freya to derive their state.
## Contributing
- Report issues on our [issue tracker](https://github.com/dioxuslabs/dioxus/issues).
- Join the discord and ask questions!
## License
This project is licensed under the [MIT license].
[mit license]: https://github.com/DioxusLabs/dioxus/blob/master/LICENSE-MIT
+7 -6
View File
@@ -210,7 +210,7 @@ pub fn routable(input: TokenStream) -> TokenStream {
let display_impl = route_enum.impl_display();
let routable_impl = route_enum.routable_impl();
quote! {
(quote! {
#error_type
#display_impl
@@ -218,7 +218,7 @@ pub fn routable(input: TokenStream) -> TokenStream {
#routable_impl
#parse_impl
}
})
.into()
}
@@ -482,7 +482,8 @@ impl RouteEnum {
let route = s;
let (route, _hash) = route.split_once('#').unwrap_or((route, ""));
let (route, query) = route.split_once('?').unwrap_or((route, ""));
let mut segments = route.split('/');
let query = dioxus_router::exports::urlencoding::decode(query).unwrap_or(query.into());
let mut segments = route.split('/').map(|s| dioxus_router::exports::urlencoding::decode(s).unwrap_or(s.into()));
// skip the first empty segment
if s.starts_with('/') {
let _ = segments.next();
@@ -677,9 +678,9 @@ impl ToTokens for SegmentType {
impl<'a> From<&'a RouteSegment> for SegmentType {
fn from(value: &'a RouteSegment) -> Self {
match value {
segment::RouteSegment::Static(s) => SegmentType::Static(s.to_string()),
segment::RouteSegment::Dynamic(s, _) => SegmentType::Dynamic(s.to_string()),
segment::RouteSegment::CatchAll(s, _) => SegmentType::CatchAll(s.to_string()),
RouteSegment::Static(s) => SegmentType::Static(s.to_string()),
RouteSegment::Dynamic(s, _) => SegmentType::Dynamic(s.to_string()),
RouteSegment::CatchAll(s, _) => SegmentType::CatchAll(s.to_string()),
}
}
}
+1 -1
View File
@@ -14,7 +14,7 @@ impl QuerySegment {
let ident = &self.ident;
let ty = &self.ty;
quote! {
let #ident = <#ty as dioxus_router::routable::FromQuery>::from_query(query);
let #ident = <#ty as dioxus_router::routable::FromQuery>::from_query(&*query);
}
}
+2 -4
View File
@@ -277,10 +277,8 @@ impl Route {
}
}
for segment in &self.segments {
if let RouteSegment::Dynamic(other, ..) = segment {
if other == name {
from_route = true
}
if segment.name().as_ref() == Some(name) {
from_route = true
}
}
if let Some(query) = &self.query {
+6 -3
View File
@@ -312,7 +312,8 @@ impl<'a> RouteTreeSegmentData<'a> {
quote! {
{
let mut segments = segments.clone();
if let Some(segment) = segments.next() {
let segment = segments.next();
if let Some(segment) = segment.as_deref() {
if #segment == segment {
#(#children)*
}
@@ -369,7 +370,7 @@ impl<'a> RouteTreeSegmentData<'a> {
quote! {
let mut trailing = String::from("/");
for seg in segments.clone() {
trailing += seg;
trailing += &*seg;
trailing += "/";
}
trailing.pop();
@@ -506,7 +507,9 @@ fn return_constructed(
let remaining_segments = segments.clone();
let mut segments_clone = segments.clone();
let next_segment = segments_clone.next();
let next_segment = next_segment.as_deref();
let segment_after_next = segments_clone.next();
let segment_after_next = segment_after_next.as_deref();
match (next_segment, segment_after_next) {
// This is the last segment, return the parsed route
(None, _) | (Some(""), None) => {
@@ -516,7 +519,7 @@ fn return_constructed(
_ => {
let mut trailing = String::new();
for seg in remaining_segments {
trailing += seg;
trailing += &*seg;
trailing += "/";
}
trailing.pop();
+10 -5
View File
@@ -25,7 +25,7 @@ impl RouteSegment {
match self {
Self::Static(segment) => quote! { write!(f, "/{}", #segment)?; },
Self::Dynamic(ident, _) => quote! { write!(f, "/{}", #ident)?; },
Self::CatchAll(ident, _) => quote! { #ident.display_route_segements(f)?; },
Self::CatchAll(ident, _) => quote! { #ident.display_route_segments(f)?; },
}
}
@@ -59,6 +59,7 @@ impl RouteSegment {
{
let mut segments = segments.clone();
let segment = segments.next();
let segment = segment.as_deref();
let parsed = if let Some(#segment) = segment {
Ok(())
} else {
@@ -80,7 +81,8 @@ impl RouteSegment {
quote! {
{
let mut segments = segments.clone();
let parsed = if let Some(segment) = segments.next() {
let segment = segments.next();
let parsed = if let Some(segment) = segment.as_deref() {
<#ty as dioxus_router::routable::FromRouteSegment>::from_route_segment(segment).map_err(|err| #error_enum_name::#error_enum_varient(#inner_parse_enum::#error_name(err)))
} else {
Err(#error_enum_name::#error_enum_varient(#inner_parse_enum::#missing_error_name))
@@ -100,9 +102,12 @@ impl RouteSegment {
quote! {
{
let parsed = {
let mut segments = segments.clone();
let segments: Vec<_> = segments.collect();
<#ty as dioxus_router::routable::FromRouteSegments>::from_route_segments(&segments).map_err(|err| #error_enum_name::#error_enum_varient(#inner_parse_enum::#error_name(err)))
let remaining_segments: Vec<_> = segments.collect();
let mut new_segments: Vec<&str> = Vec::new();
for segment in &remaining_segments {
new_segments.push(&*segment);
}
<#ty as dioxus_router::routable::FromRouteSegments>::from_route_segments(&new_segments).map_err(|err| #error_enum_name::#error_enum_varient(#inner_parse_enum::#error_name(err)))
};
match parsed {
Ok(#name) => {
+2 -2
View File
@@ -14,10 +14,10 @@ anyhow = "1.0.66"
dioxus = { workspace = true }
dioxus-router-macro = { workspace = true }
gloo = { version = "0.8.0", optional = true }
log = { workspace = true }
tracing = { workspace = true }
thiserror = { workspace = true }
futures-util = { workspace = true }
serde_urlencoded = { version = "0.7.1", optional = true }
urlencoding = "2.1.3"
serde = { version = "1", features = ["derive"], optional = true }
url = "2.3.1"
wasm-bindgen = { workspace = true, optional = true }
+6 -8
View File
@@ -15,7 +15,7 @@
[discord-url]: https://discord.gg/XgGxMSkvUM
[Website](https://dioxuslabs.com) |
[Guides](https://dioxuslabs.com/docs/0.3/router/) |
[Guides](https://dioxuslabs.com/learn/0.4/router/) |
[API Docs](https://docs.rs/dioxus-router/latest/dioxus_router) |
[Chat](https://discord.gg/XgGxMSkvUM)
@@ -26,8 +26,6 @@ interface similar to React Router, but takes advantage of types for more
expressiveness.
```rust, no_run
#![allow(non_snake_case)]
use dioxus::prelude::*;
use dioxus_router::prelude::*;
use std::str::FromStr;
@@ -48,14 +46,14 @@ enum Route {
Index {},
}
#[component]
fn App(cx: Scope) -> Element {
render! {
Router::<Route> { }
}
}
#[inline_props]
#[component]
fn Index(cx: Scope) -> Element {
render! {
h1 { "Index" }
@@ -66,7 +64,7 @@ fn Index(cx: Scope) -> Element {
}
}
#[inline_props]
#[component]
fn Blog(cx: Scope) -> Element {
render! {
h1 { "Blog" }
@@ -74,7 +72,7 @@ fn Blog(cx: Scope) -> Element {
}
}
#[inline_props]
#[component]
fn BlogList(cx: Scope) -> Element {
render! {
h2 { "List of blog posts" }
@@ -89,7 +87,7 @@ fn BlogList(cx: Scope) -> Element {
}
}
#[inline_props]
#[component]
fn BlogPost(cx: Scope, blog_id: usize) -> Element {
render! {
h2 { "Blog Post" }
+6 -6
View File
@@ -1,4 +1,4 @@
#![allow(unused, non_snake_case)]
#![allow(unused)]
use std::time::Duration;
@@ -134,7 +134,7 @@ pub fn criterion_benchmark(c: &mut Criterion) {
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
#[inline_props]
#[component]
fn Blog(cx: Scope) -> Element {
render! {
div {
@@ -143,7 +143,7 @@ fn Blog(cx: Scope) -> Element {
}
}
#[inline_props]
#[component]
fn Post(cx: Scope, id: usize) -> Element {
render! {
for _ in 0..*id {
@@ -154,7 +154,7 @@ fn Post(cx: Scope, id: usize) -> Element {
}
}
#[inline_props]
#[component]
fn PostHome(cx: Scope) -> Element {
render! {
div {
@@ -163,7 +163,7 @@ fn PostHome(cx: Scope) -> Element {
}
}
#[inline_props]
#[component]
fn Home(cx: Scope) -> Element {
render! {
div {
@@ -189,7 +189,7 @@ enum Route {
Home {},
}
#[inline_props]
#[component]
fn RenderPath(cx: Scope, path: Route) -> Element {
let path = path.clone();
render! {
+7 -8
View File
@@ -1,24 +1,23 @@
#![allow(non_snake_case)]
use dioxus::prelude::*;
use dioxus_router::prelude::*;
use std::str::FromStr;
fn main() {
#[cfg(not(target_arch = "wasm32"))]
dioxus_desktop::launch(root);
dioxus_desktop::launch(Root);
#[cfg(target_arch = "wasm32")]
dioxus_web::launch(root);
}
fn root(cx: Scope) -> Element {
#[component]
fn Root(cx: Scope) -> Element {
render! {
Router::<Route> {}
}
}
#[inline_props]
#[component]
fn UserFrame(cx: Scope, user_id: usize) -> Element {
render! {
pre {
@@ -32,7 +31,7 @@ fn UserFrame(cx: Scope, user_id: usize) -> Element {
}
}
#[inline_props]
#[component]
fn Route1(cx: Scope, user_id: usize, dynamic: usize, query: String, extra: String) -> Element {
render! {
pre {
@@ -50,7 +49,7 @@ fn Route1(cx: Scope, user_id: usize, dynamic: usize, query: String, extra: Strin
}
}
#[inline_props]
#[component]
fn Route2(cx: Scope, user_id: usize) -> Element {
render! {
pre {
@@ -65,7 +64,7 @@ fn Route2(cx: Scope, user_id: usize) -> Element {
}
}
#[inline_props]
#[component]
fn Route3(cx: Scope, dynamic: String) -> Element {
let navigator = use_navigator(cx);
let current_route = use_route(cx)?;
@@ -1,5 +1,3 @@
#![allow(non_snake_case)]
use std::time::Duration;
use dioxus::prelude::*;
@@ -54,7 +52,7 @@ async fn main() {
.unwrap();
}
#[inline_props]
#[component]
fn Blog(cx: Scope) -> Element {
render! {
div {
@@ -63,7 +61,7 @@ fn Blog(cx: Scope) -> Element {
}
}
#[inline_props]
#[component]
fn Post(cx: Scope, id: usize) -> Element {
render! {
div {
@@ -72,7 +70,7 @@ fn Post(cx: Scope, id: usize) -> Element {
}
}
#[inline_props]
#[component]
fn PostHome(cx: Scope) -> Element {
render! {
div {
@@ -81,7 +79,7 @@ fn PostHome(cx: Scope) -> Element {
}
}
#[inline_props]
#[component]
fn Home(cx: Scope) -> Element {
render! {
div {
@@ -1,5 +1,5 @@
use dioxus::prelude::*;
use log::error;
use tracing::error;
use crate::utils::use_router_internal::use_router_internal;
@@ -30,13 +30,14 @@ pub struct HistoryButtonProps<'a> {
/// Index {},
/// }
///
/// #[component]
/// fn App(cx: Scope) -> Element {
/// render! {
/// Router::<Route> {}
/// }
/// }
///
/// #[inline_props]
/// #[component]
/// fn Index(cx: Scope) -> Element {
/// render! {
/// GoBackButton {
@@ -52,7 +53,7 @@ pub struct HistoryButtonProps<'a> {
/// # r#"<button disabled="true" dioxus-prevent-default="onclick">go back</button>"#
/// # );
/// ```
#[allow(non_snake_case)]
#[component]
pub fn GoBackButton<'a>(cx: Scope<'a, HistoryButtonProps<'a>>) -> Element {
let HistoryButtonProps { children } = cx.props;
@@ -101,13 +102,14 @@ pub fn GoBackButton<'a>(cx: Scope<'a, HistoryButtonProps<'a>>) -> Element {
/// Index {},
/// }
///
/// #[component]
/// fn App(cx: Scope) -> Element {
/// render! {
/// Router::<Route> {}
/// }
/// }
///
/// #[inline_props]
/// #[component]
/// fn Index(cx: Scope) -> Element {
/// render! {
/// GoForwardButton {
@@ -123,7 +125,7 @@ pub fn GoBackButton<'a>(cx: Scope<'a, HistoryButtonProps<'a>>) -> Element {
/// # r#"<button disabled="true" dioxus-prevent-default="onclick">go forward</button>"#
/// # );
/// ```
#[allow(non_snake_case)]
#[component]
pub fn GoForwardButton<'a>(cx: Scope<'a, HistoryButtonProps<'a>>) -> Element {
let HistoryButtonProps { children } = cx.props;
+5 -2
View File
@@ -1,9 +1,11 @@
#![allow(clippy::type_complexity)]
use std::any::Any;
use std::fmt::Debug;
use std::rc::Rc;
use dioxus::prelude::*;
use log::error;
use tracing::error;
use crate::navigation::NavigationTarget;
use crate::prelude::Routable;
@@ -133,13 +135,14 @@ impl Debug for LinkProps<'_> {
/// Index {},
/// }
///
/// #[component]
/// fn App(cx: Scope) -> Element {
/// render! {
/// Router::<Route> {}
/// }
/// }
///
/// #[inline_props]
/// #[component]
/// fn Index(cx: Scope) -> Element {
/// render! {
/// render! {
+4 -3
View File
@@ -29,7 +29,7 @@ use dioxus::prelude::*;
/// Index {},
/// }
///
/// #[inline_props]
/// #[component]
/// fn Index(cx: Scope) -> Element {
/// render! {
/// div {
@@ -38,7 +38,7 @@ use dioxus::prelude::*;
/// }
/// }
///
/// #[inline_props]
/// #[component]
/// fn Wrapper(cx: Scope) -> Element {
/// render! {
/// h1 { "App" }
@@ -46,7 +46,7 @@ use dioxus::prelude::*;
/// }
/// }
///
/// #[inline_props]
/// #[component]
/// fn Child(cx: Scope) -> Element {
/// render! {
/// p {
@@ -55,6 +55,7 @@ use dioxus::prelude::*;
/// }
/// }
///
/// # #[component]
/// # fn App(cx: Scope) -> Element {
/// # render! {
/// # Router::<Route> {
+2 -2
View File
@@ -20,9 +20,9 @@ where
/// ```rust
/// # use dioxus_router::prelude::*;
/// # use dioxus::prelude::*;
/// # #[inline_props]
/// # #[component]
/// # fn Index(cx: Scope) -> Element { todo!() }
/// # #[inline_props]
/// # #[component]
/// # fn OtherPage(cx: Scope) -> Element { todo!() }
/// #[derive(Clone, Routable, Debug, PartialEq)]
/// enum Route {
+17 -14
View File
@@ -48,9 +48,9 @@ pub trait HistoryProvider<R: Routable> {
/// ```rust
/// # use dioxus_router::prelude::*;
/// # use dioxus::prelude::*;
/// # #[inline_props]
/// # #[component]
/// # fn Index(cx: Scope) -> Element { todo!() }
/// # #[inline_props]
/// # #[component]
/// # fn OtherPage(cx: Scope) -> Element { todo!() }
/// #[derive(Clone, Routable, Debug, PartialEq)]
/// enum Route {
@@ -86,17 +86,20 @@ pub trait HistoryProvider<R: Routable> {
/// ```rust
/// # use dioxus_router::prelude::*;
/// # use dioxus::prelude::*;
/// # #[inline_props]
/// # #[component]
/// # fn Index(cx: Scope) -> Element { todo!() }
/// # fn Other(cx: Scope) -> Element { todo!() }
/// #[derive(Clone, Routable, Debug, PartialEq)]
/// enum Route {
/// #[route("/")]
/// Index {},
/// #[route("/other")]
/// Other {},
/// }
/// let mut history = MemoryHistory::<Route>::default();
/// assert_eq!(history.can_go_back(), false);
///
/// history.push(Route::Index {});
/// history.push(Route::Other {});
/// assert_eq!(history.can_go_back(), true);
/// ```
#[must_use]
@@ -112,9 +115,9 @@ pub trait HistoryProvider<R: Routable> {
/// ```rust
/// # use dioxus_router::prelude::*;
/// # use dioxus::prelude::*;
/// # #[inline_props]
/// # #[component]
/// # fn Index(cx: Scope) -> Element { todo!() }
/// # #[inline_props]
/// # #[component]
/// # fn OtherPage(cx: Scope) -> Element { todo!() }
/// #[derive(Clone, Routable, Debug, PartialEq)]
/// enum Route {
@@ -144,9 +147,9 @@ pub trait HistoryProvider<R: Routable> {
/// ```rust
/// # use dioxus_router::prelude::*;
/// # use dioxus::prelude::*;
/// # #[inline_props]
/// # #[component]
/// # fn Index(cx: Scope) -> Element { todo!() }
/// # #[inline_props]
/// # #[component]
/// # fn OtherPage(cx: Scope) -> Element { todo!() }
/// #[derive(Clone, Routable, Debug, PartialEq)]
/// enum Route {
@@ -177,9 +180,9 @@ pub trait HistoryProvider<R: Routable> {
/// ```rust
/// # use dioxus_router::prelude::*;
/// # use dioxus::prelude::*;
/// # #[inline_props]
/// # #[component]
/// # fn Index(cx: Scope) -> Element { todo!() }
/// # #[inline_props]
/// # #[component]
/// # fn OtherPage(cx: Scope) -> Element { todo!() }
/// #[derive(Clone, Routable, Debug, PartialEq)]
/// enum Route {
@@ -210,9 +213,9 @@ pub trait HistoryProvider<R: Routable> {
/// ```rust
/// # use dioxus_router::prelude::*;
/// # use dioxus::prelude::*;
/// # #[inline_props]
/// # #[component]
/// # fn Index(cx: Scope) -> Element { todo!() }
/// # #[inline_props]
/// # #[component]
/// # fn OtherPage(cx: Scope) -> Element { todo!() }
/// #[derive(Clone, Routable, Debug, PartialEq)]
/// enum Route {
@@ -239,9 +242,9 @@ pub trait HistoryProvider<R: Routable> {
/// ```rust
/// # use dioxus_router::prelude::*;
/// # use dioxus::prelude::*;
/// # #[inline_props]
/// # #[component]
/// # fn Index(cx: Scope) -> Element { todo!() }
/// # #[inline_props]
/// # #[component]
/// # fn OtherPage(cx: Scope) -> Element { todo!() }
/// #[derive(Clone, Routable, Debug, PartialEq)]
/// enum Route {
Loaded 100 of 379 files, more files were not shown because too many files have changed in this diff. Show more