Merge branch 'master' into jk/examples-overhaul
This commit is contained in:
49 files changed
+837
-1008
No files matched your search
+26
-37
@@ -1,49 +1,38 @@
|
|||||||
name: github pages
|
name: Deploy Nightly Docs
|
||||||
|
|
||||||
on:
|
on:
|
||||||
workflow_dispatch:
|
push:
|
||||||
# push:
|
branches:
|
||||||
# paths:
|
- master
|
||||||
# - docs/**
|
|
||||||
# - .github/workflows/docs.yml
|
|
||||||
# branches:
|
|
||||||
# - master
|
|
||||||
|
|
||||||
concurrency:
|
|
||||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
|
|
||||||
cancel-in-progress: true
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build-deploy:
|
deploy:
|
||||||
|
name: Build & Deploy
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
environment: docs
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
|
|
||||||
# NOTE: Comment out when https://github.com/rust-lang/mdBook/pull/1306 is merged and released
|
|
||||||
# - name: Setup mdBook
|
|
||||||
# uses: peaceiris/actions-mdbook@v1
|
|
||||||
# with:
|
|
||||||
# mdbook-version: "0.4.10"
|
|
||||||
|
|
||||||
# NOTE: Delete when the previous one is enabled
|
|
||||||
- name: Setup mdBook
|
|
||||||
run: |
|
|
||||||
cargo install mdbook --git https://github.com/Demonthos/mdBook.git --branch master
|
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
|
- run: sudo apt-get update
|
||||||
|
- run: sudo apt install libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev libxdo-dev
|
||||||
|
- uses: dtolnay/rust-toolchain@nightly
|
||||||
|
with:
|
||||||
|
toolchain: nightly-2024-02-01
|
||||||
|
- uses: Swatinem/rust-cache@v2
|
||||||
|
with:
|
||||||
|
cache-all-crates: "true"
|
||||||
|
save-if: ${{ github.ref == 'refs/heads/master' }}
|
||||||
|
- uses: ilammy/setup-nasm@v1
|
||||||
|
|
||||||
- name: Build
|
- name: cargo doc
|
||||||
run: cd docs &&
|
run: cargo doc --no-deps --workspace --all-features
|
||||||
cd guide && mdbook build -d ../nightly/guide && cd .. &&
|
|
||||||
cd router && mdbook build -d ../nightly/router && cd ..
|
|
||||||
# cd reference && mdbook build -d ../nightly/reference && cd .. &&
|
|
||||||
# cd fermi && mdbook build -d ../nightly/fermi && cd ..
|
|
||||||
|
|
||||||
- name: Deploy 🚀
|
- name: Deploy
|
||||||
uses: JamesIves/github-pages-deploy-action@v4.5.0
|
uses: JamesIves/github-pages-deploy-action@v4.5.0
|
||||||
with:
|
with:
|
||||||
branch: gh-pages # The branch the action should deploy to.
|
branch: gh-pages
|
||||||
folder: docs/nightly # The folder the action should deploy.
|
folder: target/doc
|
||||||
target-folder: docs/nightly
|
target-folder: api-docs/nightly
|
||||||
repository-name: dioxuslabs/docsite
|
repository-name: dioxuslabs/docsite
|
||||||
clean: false
|
clean: false
|
||||||
token: ${{ secrets.DEPLOY_KEY }} # let's pretend I don't need it for now
|
token: ${{ secrets.DEPLOY_KEY }}
|
||||||
Generated
+246
-196
File diff suppressed because it is too large.
Load diff
@@ -36,6 +36,7 @@ hyper = "0.14.17"
|
|||||||
hyper-rustls = "0.23.2"
|
hyper-rustls = "0.23.2"
|
||||||
indicatif = "0.17.5"
|
indicatif = "0.17.5"
|
||||||
subprocess = "0.2.9"
|
subprocess = "0.2.9"
|
||||||
|
rayon = "1.8.0"
|
||||||
|
|
||||||
axum = { version = "0.5.1", features = ["ws", "headers"] }
|
axum = { version = "0.5.1", features = ["ws", "headers"] }
|
||||||
axum-server = { version = "0.5.1", features = ["tls-rustls"] }
|
axum-server = { version = "0.5.1", features = ["tls-rustls"] }
|
||||||
@@ -74,6 +75,10 @@ toml_edit = "0.21.0"
|
|||||||
# bundling
|
# bundling
|
||||||
tauri-bundler = { version = "=1.4.*", features = ["native-tls-vendored"] }
|
tauri-bundler = { version = "=1.4.*", features = ["native-tls-vendored"] }
|
||||||
|
|
||||||
|
# formatting
|
||||||
|
syn = { version = "2.0" }
|
||||||
|
prettyplease = { workspace = true }
|
||||||
|
|
||||||
manganis-cli-support = { workspace = true, features = ["webp", "html"] }
|
manganis-cli-support = { workspace = true, features = ["webp", "html"] }
|
||||||
|
|
||||||
dioxus-autofmt = { workspace = true }
|
dioxus-autofmt = { workspace = true }
|
||||||
@@ -84,7 +89,7 @@ dioxus-html = { workspace = true, features = ["hot-reload-context"] }
|
|||||||
dioxus-core = { workspace = true, features = ["serialize"] }
|
dioxus-core = { workspace = true, features = ["serialize"] }
|
||||||
dioxus-hot-reload = { workspace = true }
|
dioxus-hot-reload = { workspace = true }
|
||||||
interprocess-docfix = { version = "1.2.2" }
|
interprocess-docfix = { version = "1.2.2" }
|
||||||
gitignore = "1.0.8"
|
ignore = "0.4.22"
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = []
|
default = []
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use dioxus_autofmt::{IndentOptions, IndentType};
|
use dioxus_autofmt::{IndentOptions, IndentType};
|
||||||
use futures_util::{stream::FuturesUnordered, StreamExt};
|
use rayon::prelude::*;
|
||||||
use std::{fs, path::Path, process::exit};
|
use std::{fs, path::Path, process::exit};
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -10,6 +10,10 @@ use super::*;
|
|||||||
/// Format some rsx
|
/// Format some rsx
|
||||||
#[derive(Clone, Debug, Parser)]
|
#[derive(Clone, Debug, Parser)]
|
||||||
pub struct Autoformat {
|
pub struct Autoformat {
|
||||||
|
/// Format rust code before the formatting the rsx macros
|
||||||
|
#[clap(long)]
|
||||||
|
pub all_code: bool,
|
||||||
|
|
||||||
/// Run in 'check' mode. Exits with 0 if input is formatted correctly. Exits
|
/// Run in 'check' mode. Exits with 0 if input is formatted correctly. Exits
|
||||||
/// with 1 and prints a diff if formatting is required.
|
/// with 1 and prints a diff if formatting is required.
|
||||||
#[clap(short, long)]
|
#[clap(short, long)]
|
||||||
@@ -29,19 +33,19 @@ pub struct Autoformat {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Autoformat {
|
impl Autoformat {
|
||||||
// Todo: autoformat the entire crate
|
pub fn autoformat(self) -> Result<()> {
|
||||||
pub async fn autoformat(self) -> Result<()> {
|
|
||||||
let Autoformat {
|
let Autoformat {
|
||||||
check,
|
check,
|
||||||
raw,
|
raw,
|
||||||
file,
|
file,
|
||||||
split_line_attributes,
|
split_line_attributes,
|
||||||
|
all_code: format_rust_code,
|
||||||
..
|
..
|
||||||
} = self;
|
} = self;
|
||||||
|
|
||||||
// Default to formatting the project
|
// Default to formatting the project
|
||||||
if raw.is_none() && file.is_none() {
|
if raw.is_none() && file.is_none() {
|
||||||
if let Err(e) = autoformat_project(check, split_line_attributes).await {
|
if let Err(e) = autoformat_project(check, split_line_attributes, format_rust_code) {
|
||||||
eprintln!("error formatting project: {}", e);
|
eprintln!("error formatting project: {}", e);
|
||||||
exit(1);
|
exit(1);
|
||||||
}
|
}
|
||||||
@@ -60,14 +64,18 @@ impl Autoformat {
|
|||||||
|
|
||||||
// Format single file
|
// Format single file
|
||||||
if let Some(file) = file {
|
if let Some(file) = file {
|
||||||
refactor_file(file, split_line_attributes)?;
|
refactor_file(file, split_line_attributes, format_rust_code)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn refactor_file(file: String, split_line_attributes: bool) -> Result<(), Error> {
|
fn refactor_file(
|
||||||
|
file: String,
|
||||||
|
split_line_attributes: bool,
|
||||||
|
format_rust_code: bool,
|
||||||
|
) -> Result<(), Error> {
|
||||||
let indent = indentation_for(".", split_line_attributes)?;
|
let indent = indentation_for(".", split_line_attributes)?;
|
||||||
let file_content = if file == "-" {
|
let file_content = if file == "-" {
|
||||||
let mut contents = String::new();
|
let mut contents = String::new();
|
||||||
@@ -76,10 +84,15 @@ fn refactor_file(file: String, split_line_attributes: bool) -> Result<(), Error>
|
|||||||
} else {
|
} else {
|
||||||
fs::read_to_string(&file)
|
fs::read_to_string(&file)
|
||||||
};
|
};
|
||||||
let Ok(s) = file_content else {
|
let Ok(mut s) = file_content else {
|
||||||
eprintln!("failed to open file: {}", file_content.unwrap_err());
|
eprintln!("failed to open file: {}", file_content.unwrap_err());
|
||||||
exit(1);
|
exit(1);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if format_rust_code {
|
||||||
|
s = format_rust(&s)?;
|
||||||
|
}
|
||||||
|
|
||||||
let edits = dioxus_autofmt::fmt_file(&s, indent);
|
let edits = dioxus_autofmt::fmt_file(&s, indent);
|
||||||
let out = dioxus_autofmt::apply_formats(&s, edits);
|
let out = dioxus_autofmt::apply_formats(&s, edits);
|
||||||
|
|
||||||
@@ -94,50 +107,46 @@ fn refactor_file(file: String, split_line_attributes: bool) -> Result<(), Error>
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_project_files(config: &CrateConfig) -> Vec<PathBuf> {
|
use std::ffi::OsStr;
|
||||||
let mut files = vec![];
|
fn get_project_files() -> Vec<PathBuf> {
|
||||||
|
let mut files = Vec::new();
|
||||||
let gitignore_path = config.crate_dir.join(".gitignore");
|
for result in ignore::Walk::new("./") {
|
||||||
if gitignore_path.is_file() {
|
let path = result.unwrap().into_path();
|
||||||
let gitigno = gitignore::File::new(gitignore_path.as_path()).unwrap();
|
if let Some(ext) = path.extension() {
|
||||||
if let Ok(git_files) = gitigno.included_files() {
|
if ext == OsStr::new("rs") {
|
||||||
let git_files = git_files
|
files.push(path);
|
||||||
.into_iter()
|
}
|
||||||
.filter(|f| f.ends_with(".rs") && !is_target_dir(f));
|
}
|
||||||
files.extend(git_files)
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
collect_rs_files(&config.crate_dir, &mut files);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
files
|
files
|
||||||
}
|
}
|
||||||
|
|
||||||
fn is_target_dir(file: &Path) -> bool {
|
fn format_file(
|
||||||
let stripped = if let Ok(cwd) = std::env::current_dir() {
|
|
||||||
file.strip_prefix(cwd).unwrap_or(file)
|
|
||||||
} else {
|
|
||||||
file
|
|
||||||
};
|
|
||||||
if let Some(first) = stripped.components().next() {
|
|
||||||
first.as_os_str() == "target"
|
|
||||||
} else {
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn format_file(
|
|
||||||
path: impl AsRef<Path>,
|
path: impl AsRef<Path>,
|
||||||
indent: IndentOptions,
|
indent: IndentOptions,
|
||||||
) -> Result<usize, tokio::io::Error> {
|
format_rust_code: bool,
|
||||||
let contents = tokio::fs::read_to_string(&path).await?;
|
) -> Result<usize> {
|
||||||
|
let mut contents = fs::read_to_string(&path)?;
|
||||||
|
let mut if_write = false;
|
||||||
|
if format_rust_code {
|
||||||
|
let formatted = format_rust(&contents)
|
||||||
|
.map_err(|err| Error::ParseError(format!("Syntax Error:\n{}", err)))?;
|
||||||
|
if contents != formatted {
|
||||||
|
if_write = true;
|
||||||
|
contents = formatted;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let edits = dioxus_autofmt::fmt_file(&contents, indent);
|
let edits = dioxus_autofmt::fmt_file(&contents, indent);
|
||||||
let len = edits.len();
|
let len = edits.len();
|
||||||
|
|
||||||
if !edits.is_empty() {
|
if !edits.is_empty() {
|
||||||
|
if_write = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if if_write {
|
||||||
let out = dioxus_autofmt::apply_formats(&contents, edits);
|
let out = dioxus_autofmt::apply_formats(&contents, edits);
|
||||||
tokio::fs::write(path, out).await?;
|
fs::write(path, out)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(len)
|
Ok(len)
|
||||||
@@ -145,13 +154,15 @@ async fn format_file(
|
|||||||
|
|
||||||
/// Read every .rs file accessible when considering the .gitignore and try to format it
|
/// Read every .rs file accessible when considering the .gitignore and try to format it
|
||||||
///
|
///
|
||||||
/// Runs using Tokio for multithreading, so it should be really really fast
|
/// Runs using rayon for multithreading, so it should be really really fast
|
||||||
///
|
///
|
||||||
/// Doesn't do mod-descending, so it will still try to format unreachable files. TODO.
|
/// Doesn't do mod-descending, so it will still try to format unreachable files. TODO.
|
||||||
async fn autoformat_project(check: bool, split_line_attributes: bool) -> Result<()> {
|
fn autoformat_project(
|
||||||
let crate_config = dioxus_cli_config::CrateConfig::new(None)?;
|
check: bool,
|
||||||
|
split_line_attributes: bool,
|
||||||
let files_to_format = get_project_files(&crate_config);
|
format_rust_code: bool,
|
||||||
|
) -> Result<()> {
|
||||||
|
let files_to_format = get_project_files();
|
||||||
|
|
||||||
if files_to_format.is_empty() {
|
if files_to_format.is_empty() {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
@@ -164,26 +175,18 @@ async fn autoformat_project(check: bool, split_line_attributes: bool) -> Result<
|
|||||||
let indent = indentation_for(&files_to_format[0], split_line_attributes)?;
|
let indent = indentation_for(&files_to_format[0], split_line_attributes)?;
|
||||||
|
|
||||||
let counts = files_to_format
|
let counts = files_to_format
|
||||||
.into_iter()
|
.into_par_iter()
|
||||||
.map(|path| async {
|
.map(|path| {
|
||||||
let path_clone = path.clone();
|
let res = format_file(&path, indent.clone(), format_rust_code);
|
||||||
let res = tokio::spawn(format_file(path, indent.clone())).await;
|
|
||||||
|
|
||||||
match res {
|
match res {
|
||||||
|
Ok(cnt) => Some(cnt),
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
eprintln!("error formatting file: {}\n{err}", path_clone.display());
|
eprintln!("error formatting file : {}\n{:#?}", path.display(), err);
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
Ok(Err(err)) => {
|
|
||||||
eprintln!("error formatting file: {}\n{err}", path_clone.display());
|
|
||||||
None
|
|
||||||
}
|
|
||||||
Ok(Ok(res)) => Some(res),
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.collect::<FuturesUnordered<_>>()
|
.collect::<Vec<_>>();
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.await;
|
|
||||||
|
|
||||||
let files_formatted: usize = counts.into_iter().flatten().sum();
|
let files_formatted: usize = counts.into_iter().flatten().sum();
|
||||||
|
|
||||||
@@ -242,28 +245,21 @@ fn indentation_for(
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn collect_rs_files(folder: &impl AsRef<Path>, files: &mut Vec<PathBuf>) {
|
/// Format rust code using prettyplease
|
||||||
if is_target_dir(folder.as_ref()) {
|
fn format_rust(input: &str) -> Result<String> {
|
||||||
return;
|
let syntax_tree = syn::parse_file(input).map_err(format_syn_error)?;
|
||||||
}
|
let output = prettyplease::unparse(&syntax_tree);
|
||||||
let Ok(folder) = folder.as_ref().read_dir() else {
|
Ok(output)
|
||||||
return;
|
|
||||||
};
|
|
||||||
// load the gitignore
|
|
||||||
for entry in folder {
|
|
||||||
let Ok(entry) = entry else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
let path = entry.path();
|
|
||||||
if path.is_dir() {
|
|
||||||
collect_rs_files(&path, files);
|
|
||||||
}
|
|
||||||
if let Some(ext) = path.extension() {
|
|
||||||
if ext == "rs" && !is_target_dir(&path) {
|
|
||||||
files.push(path);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn format_syn_error(err: syn::Error) -> Error {
|
||||||
|
let start = err.span().start();
|
||||||
|
let line = start.line;
|
||||||
|
let column = start.column;
|
||||||
|
Error::ParseError(format!(
|
||||||
|
"Syntax Error in line {} column {}:\n{}",
|
||||||
|
line, column, err
|
||||||
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
@@ -284,13 +280,14 @@ async fn test_auto_fmt() {
|
|||||||
.to_string();
|
.to_string();
|
||||||
|
|
||||||
let fmt = Autoformat {
|
let fmt = Autoformat {
|
||||||
|
all_code: false,
|
||||||
check: false,
|
check: false,
|
||||||
raw: Some(test_rsx),
|
raw: Some(test_rsx),
|
||||||
file: None,
|
file: None,
|
||||||
split_line_attributes: false,
|
split_line_attributes: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
fmt.autoformat().await.unwrap();
|
fmt.autoformat().unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
/*#[test]
|
/*#[test]
|
||||||
|
|||||||
@@ -70,7 +70,6 @@ async fn main() -> anyhow::Result<()> {
|
|||||||
|
|
||||||
Autoformat(opts) => opts
|
Autoformat(opts) => opts
|
||||||
.autoformat()
|
.autoformat()
|
||||||
.await
|
|
||||||
.context(error_wrapper("Error autoformatting RSX")),
|
.context(error_wrapper("Error autoformatting RSX")),
|
||||||
|
|
||||||
Check(opts) => opts
|
Check(opts) => opts
|
||||||
|
|||||||
@@ -112,12 +112,6 @@ async fn setup_file_watcher<F: Fn() -> Result<BuildResult> + Send + 'static>(
|
|||||||
},
|
},
|
||||||
web_info.clone(),
|
web_info.clone(),
|
||||||
);
|
);
|
||||||
|
|
||||||
#[cfg(feature = "plugin")]
|
|
||||||
let _ = PluginManager::on_serve_rebuild(
|
|
||||||
chrono::Local::now().timestamp(),
|
|
||||||
e.paths,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
last_update_time = chrono::Local::now().timestamp();
|
last_update_time = chrono::Local::now().timestamp();
|
||||||
|
|||||||
@@ -145,7 +145,7 @@ impl ErrorBoundary {
|
|||||||
///
|
///
|
||||||
/// rsx! {
|
/// rsx! {
|
||||||
/// div { "Count {}" }
|
/// div { "Count {}" }
|
||||||
/// })
|
/// }
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
pub trait Throw<S = ()>: Sized {
|
pub trait Throw<S = ()>: Sized {
|
||||||
@@ -170,7 +170,7 @@ pub trait Throw<S = ()>: Sized {
|
|||||||
///
|
///
|
||||||
/// rsx! {
|
/// rsx! {
|
||||||
/// div { "Count {}" }
|
/// div { "Count {}" }
|
||||||
/// })
|
/// }
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
fn throw(self) -> Option<Self::Out>;
|
fn throw(self) -> Option<Self::Out>;
|
||||||
@@ -193,7 +193,7 @@ pub trait Throw<S = ()>: Sized {
|
|||||||
///
|
///
|
||||||
/// rsx! {
|
/// rsx! {
|
||||||
/// div { "Count {}" }
|
/// div { "Count {}" }
|
||||||
/// })
|
/// }
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
fn throw_with<D: Debug + 'static>(self, e: impl FnOnce() -> D) -> Option<Self::Out> {
|
fn throw_with<D: Debug + 'static>(self, e: impl FnOnce() -> D) -> Option<Self::Out> {
|
||||||
|
|||||||
@@ -159,7 +159,7 @@ impl<T: std::fmt::Debug> std::fmt::Debug for Event<T> {
|
|||||||
/// button {
|
/// button {
|
||||||
/// onclick: move |evt| cx.onclick.call(evt),
|
/// onclick: move |evt| cx.onclick.call(evt),
|
||||||
/// }
|
/// }
|
||||||
/// })
|
/// }
|
||||||
/// }
|
/// }
|
||||||
///
|
///
|
||||||
/// ```
|
/// ```
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ pub(crate) mod innerlude {
|
|||||||
/// An Errored [`Element`] will propagate the error to the nearest error boundary.
|
/// An Errored [`Element`] will propagate the error to the nearest error boundary.
|
||||||
pub type Element = Option<VNode>;
|
pub type Element = Option<VNode>;
|
||||||
|
|
||||||
/// A [`Component`] is a function that takes a [`Scope`] and returns an [`Element`].
|
/// A [`Component`] is a function that takes [`Properties`] and returns an [`Element`].
|
||||||
///
|
///
|
||||||
/// Components can be used in other components with two syntax options:
|
/// Components can be used in other components with two syntax options:
|
||||||
/// - lowercase as a function call with named arguments (rust style)
|
/// - lowercase as a function call with named arguments (rust style)
|
||||||
@@ -84,7 +84,7 @@ pub use crate::innerlude::{
|
|||||||
|
|
||||||
/// The purpose of this module is to alleviate imports of many common types
|
/// The purpose of this module is to alleviate imports of many common types
|
||||||
///
|
///
|
||||||
/// This includes types like [`Scope`], [`Element`], and [`Component`].
|
/// This includes types like [`Element`], and [`Component`].
|
||||||
pub mod prelude {
|
pub mod prelude {
|
||||||
pub use crate::innerlude::{
|
pub use crate::innerlude::{
|
||||||
consume_context, consume_context_from_scope, current_scope_id, fc_to_builder, flush_sync,
|
consume_context, consume_context_from_scope, current_scope_id, fc_to_builder, flush_sync,
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ use std::{any::Any, collections::BTreeSet, rc::Rc};
|
|||||||
///
|
///
|
||||||
/// ## Guide
|
/// ## Guide
|
||||||
///
|
///
|
||||||
/// Components are defined as simple functions that take [`Scope`] and return an [`Element`].
|
/// Components are defined as simple functions that take [`crate::properties::Properties`] and return an [`Element`].
|
||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// # use dioxus::prelude::*;
|
/// # use dioxus::prelude::*;
|
||||||
@@ -218,7 +218,7 @@ impl VirtualDom {
|
|||||||
/// # Example
|
/// # Example
|
||||||
/// ```rust, ignore
|
/// ```rust, ignore
|
||||||
/// fn Example() -> Element {
|
/// fn Example() -> Element {
|
||||||
/// rsx!( div { "hello world" } ))
|
/// rsx!( div { "hello world" } )
|
||||||
/// }
|
/// }
|
||||||
///
|
///
|
||||||
/// let dom = VirtualDom::new(Example);
|
/// let dom = VirtualDom::new(Example);
|
||||||
@@ -439,7 +439,7 @@ impl VirtualDom {
|
|||||||
self.process_events();
|
self.process_events();
|
||||||
|
|
||||||
// Now that we have collected all queued work, we should check if we have any dirty scopes. If there are not, then we can poll any queued futures
|
// Now that we have collected all queued work, we should check if we have any dirty scopes. If there are not, then we can poll any queued futures
|
||||||
if !self.dirty_scopes.is_empty() || !self.suspended_scopes.is_empty() {
|
if !self.dirty_scopes.is_empty() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -526,7 +526,7 @@ impl VirtualDom {
|
|||||||
///
|
///
|
||||||
/// # Example
|
/// # Example
|
||||||
/// ```rust, ignore
|
/// ```rust, ignore
|
||||||
/// static app: Component = |cx| rsx!{ "hello world" });
|
/// static app: Component = |cx| rsx!{ "hello world" };
|
||||||
///
|
///
|
||||||
/// let mut dom = VirtualDom::new();
|
/// let mut dom = VirtualDom::new();
|
||||||
/// let edits = dom.rebuild();
|
/// let edits = dom.rebuild();
|
||||||
|
|||||||
@@ -55,6 +55,9 @@ warp = ["dioxus-fullstack?/warp", "ssr", "dioxus-liveview?/warp"]
|
|||||||
rocket = ["dioxus-liveview?/rocket"]
|
rocket = ["dioxus-liveview?/rocket"]
|
||||||
tui = ["dioxus-tui", "dioxus-config-macro/tui"]
|
tui = ["dioxus-tui", "dioxus-config-macro/tui"]
|
||||||
|
|
||||||
|
# This feature enables some nightly flags that make it more clear what structs/methods are available in each feature
|
||||||
|
nightly-doc = []
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
futures-util = { workspace = true }
|
futures-util = { workspace = true }
|
||||||
tracing = { workspace = true }
|
tracing = { workspace = true }
|
||||||
|
|||||||
+11
-12
@@ -50,7 +50,7 @@ fn main() {
|
|||||||
// It's not required, but highly recommended. For example, UpperCamelCase components will not generate a warning.
|
// It's not required, but highly recommended. For example, UpperCamelCase components will not generate a warning.
|
||||||
#[component]
|
#[component]
|
||||||
fn App() -> Element {
|
fn App() -> Element {
|
||||||
rsx!("hello world!"))
|
rsx!("hello world!")
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -97,13 +97,12 @@ If we want to omit the boilerplate of `cx.render`, we can simply pass in
|
|||||||
render nodes in match statements.
|
render nodes in match statements.
|
||||||
|
|
||||||
```rust, ignore
|
```rust, ignore
|
||||||
#[component[
|
#[component]
|
||||||
fn Example() -> Element {
|
fn Example() -> Element {
|
||||||
|
|
||||||
// both of these are equivalent
|
// both of these are equivalent
|
||||||
rsx!("hello world"))
|
rsx!("hello world");
|
||||||
|
|
||||||
rsx!("hello world!")
|
rsx!("hello world!");
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -127,7 +126,7 @@ fn App() -> Element {
|
|||||||
))
|
))
|
||||||
|
|
||||||
}
|
}
|
||||||
))
|
)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -147,7 +146,7 @@ fn App() -> Element {
|
|||||||
title: "My App",
|
title: "My App",
|
||||||
color: "red",
|
color: "red",
|
||||||
}
|
}
|
||||||
))
|
)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -169,7 +168,7 @@ fn Header(cx: Scope<HeaderProps>) -> Element {
|
|||||||
background_color: "{cx.props.color}"
|
background_color: "{cx.props.color}"
|
||||||
h1 { "{cx.props.title}" }
|
h1 { "{cx.props.title}" }
|
||||||
}
|
}
|
||||||
))
|
)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -184,7 +183,7 @@ fn Header(title: String, color: String) -> Element {
|
|||||||
background_color: "{color}"
|
background_color: "{color}"
|
||||||
h1 { "{title}" }
|
h1 { "{title}" }
|
||||||
}
|
}
|
||||||
))
|
)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -201,13 +200,13 @@ struct HeaderProps<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[component]
|
#[component]
|
||||||
fn Header(props: HeaderProps -> Element {
|
fn Header(props: HeaderProps) -> Element {
|
||||||
rsx!(
|
rsx!(
|
||||||
div {
|
div {
|
||||||
background_color: "{cx.props.color}"
|
background_color: "{cx.props.color}"
|
||||||
h1 { "{cx.props.title}" }
|
h1 { "{cx.props.title}" }
|
||||||
}
|
}
|
||||||
))
|
)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -299,7 +298,7 @@ fn App() -> Element {
|
|||||||
div { "Count: {count}" }
|
div { "Count: {count}" }
|
||||||
button { onclick: move |_| count.set(count + 1), "Increment" }
|
button { onclick: move |_| count.set(count + 1), "Increment" }
|
||||||
button { onclick: move |_| count.set(count - 1), "Decrement" }
|
button { onclick: move |_| count.set(count - 1), "Decrement" }
|
||||||
))
|
)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ impl LaunchBuilder {
|
|||||||
|
|
||||||
/// Launch your web application.
|
/// Launch your web application.
|
||||||
#[cfg(feature = "web")]
|
#[cfg(feature = "web")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "web")))]
|
||||||
pub fn web() -> LaunchBuilder<dioxus_web::Config, UnsendContext> {
|
pub fn web() -> LaunchBuilder<dioxus_web::Config, UnsendContext> {
|
||||||
LaunchBuilder {
|
LaunchBuilder {
|
||||||
launch_fn: dioxus_web::launch::launch,
|
launch_fn: dioxus_web::launch::launch,
|
||||||
@@ -48,6 +49,7 @@ impl LaunchBuilder {
|
|||||||
|
|
||||||
/// Launch your desktop application.
|
/// Launch your desktop application.
|
||||||
#[cfg(feature = "desktop")]
|
#[cfg(feature = "desktop")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "desktop")))]
|
||||||
pub fn desktop() -> LaunchBuilder<dioxus_desktop::Config, UnsendContext> {
|
pub fn desktop() -> LaunchBuilder<dioxus_desktop::Config, UnsendContext> {
|
||||||
LaunchBuilder {
|
LaunchBuilder {
|
||||||
launch_fn: dioxus_desktop::launch::launch,
|
launch_fn: dioxus_desktop::launch::launch,
|
||||||
@@ -58,6 +60,7 @@ impl LaunchBuilder {
|
|||||||
|
|
||||||
/// Launch your fullstack application.
|
/// Launch your fullstack application.
|
||||||
#[cfg(feature = "fullstack")]
|
#[cfg(feature = "fullstack")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "fullstack")))]
|
||||||
pub fn fullstack() -> LaunchBuilder<dioxus_fullstack::Config, SendContext> {
|
pub fn fullstack() -> LaunchBuilder<dioxus_fullstack::Config, SendContext> {
|
||||||
LaunchBuilder {
|
LaunchBuilder {
|
||||||
launch_fn: dioxus_fullstack::launch::launch,
|
launch_fn: dioxus_fullstack::launch::launch,
|
||||||
@@ -68,6 +71,7 @@ impl LaunchBuilder {
|
|||||||
|
|
||||||
/// Launch your fullstack application.
|
/// Launch your fullstack application.
|
||||||
#[cfg(feature = "mobile")]
|
#[cfg(feature = "mobile")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "mobile")))]
|
||||||
pub fn mobile() -> LaunchBuilder<dioxus_mobile::Config, UnsendContext> {
|
pub fn mobile() -> LaunchBuilder<dioxus_mobile::Config, UnsendContext> {
|
||||||
LaunchBuilder {
|
LaunchBuilder {
|
||||||
launch_fn: dioxus_mobile::launch::launch,
|
launch_fn: dioxus_mobile::launch::launch,
|
||||||
@@ -77,6 +81,7 @@ impl LaunchBuilder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "tui")]
|
#[cfg(feature = "tui")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "tui")))]
|
||||||
/// Launch your tui application
|
/// Launch your tui application
|
||||||
pub fn tui() -> LaunchBuilder<dioxus_tui::Config, UnsendContext> {
|
pub fn tui() -> LaunchBuilder<dioxus_tui::Config, UnsendContext> {
|
||||||
LaunchBuilder {
|
LaunchBuilder {
|
||||||
@@ -209,24 +214,28 @@ pub fn launch(app: fn() -> Element) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "web")]
|
#[cfg(feature = "web")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "web")))]
|
||||||
/// Launch your web application without any additional configuration. See [`LaunchBuilder`] for more options.
|
/// Launch your web application without any additional configuration. See [`LaunchBuilder`] for more options.
|
||||||
pub fn launch_web(app: fn() -> Element) {
|
pub fn launch_web(app: fn() -> Element) {
|
||||||
LaunchBuilder::web().launch(app)
|
LaunchBuilder::web().launch(app)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "desktop")]
|
#[cfg(feature = "desktop")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "desktop")))]
|
||||||
/// Launch your desktop application without any additional configuration. See [`LaunchBuilder`] for more options.
|
/// Launch your desktop application without any additional configuration. See [`LaunchBuilder`] for more options.
|
||||||
pub fn launch_desktop(app: fn() -> Element) {
|
pub fn launch_desktop(app: fn() -> Element) {
|
||||||
LaunchBuilder::desktop().launch(app)
|
LaunchBuilder::desktop().launch(app)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "fullstack")]
|
#[cfg(feature = "fullstack")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "fullstack")))]
|
||||||
/// Launch your fullstack application without any additional configuration. See [`LaunchBuilder`] for more options.
|
/// Launch your fullstack application without any additional configuration. See [`LaunchBuilder`] for more options.
|
||||||
pub fn launch_fullstack(app: fn() -> Element) {
|
pub fn launch_fullstack(app: fn() -> Element) {
|
||||||
LaunchBuilder::fullstack().launch(app)
|
LaunchBuilder::fullstack().launch(app)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "tui")]
|
#[cfg(feature = "tui")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "tui")))]
|
||||||
/// Launch your tui application without any additional configuration. See [`LaunchBuilder`] for more options.
|
/// Launch your tui application without any additional configuration. See [`LaunchBuilder`] for more options.
|
||||||
pub fn launch_tui(app: fn() -> Element) {
|
pub fn launch_tui(app: fn() -> Element) {
|
||||||
LaunchBuilder::tui().launch(app)
|
LaunchBuilder::tui().launch(app)
|
||||||
|
|||||||
@@ -1,88 +1,114 @@
|
|||||||
#![doc = include_str!("../README.md")]
|
#![doc = include_str!("../README.md")]
|
||||||
#![doc(html_logo_url = "https://avatars.githubusercontent.com/u/79236386")]
|
#![doc(html_logo_url = "https://avatars.githubusercontent.com/u/79236386")]
|
||||||
#![doc(html_favicon_url = "https://avatars.githubusercontent.com/u/79236386")]
|
#![doc(html_favicon_url = "https://avatars.githubusercontent.com/u/79236386")]
|
||||||
|
#![cfg_attr(any(docsrs, feature = "nightly-doc"), feature(doc_cfg))]
|
||||||
|
|
||||||
pub use dioxus_core;
|
pub use dioxus_core;
|
||||||
|
|
||||||
#[cfg(feature = "launch")]
|
#[cfg(feature = "launch")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "launch")))]
|
||||||
mod launch;
|
mod launch;
|
||||||
|
|
||||||
#[cfg(feature = "hooks")]
|
#[cfg(feature = "hooks")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "hooks")))]
|
||||||
pub use dioxus_hooks as hooks;
|
pub use dioxus_hooks as hooks;
|
||||||
|
|
||||||
#[cfg(feature = "signals")]
|
#[cfg(feature = "signals")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "signals")))]
|
||||||
pub use dioxus_signals as signals;
|
pub use dioxus_signals as signals;
|
||||||
|
|
||||||
pub mod events {
|
pub mod events {
|
||||||
#[cfg(feature = "html")]
|
#[cfg(feature = "html")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "html")))]
|
||||||
pub use dioxus_html::prelude::*;
|
pub use dioxus_html::prelude::*;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "html")]
|
#[cfg(feature = "html")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "html")))]
|
||||||
pub use dioxus_html as html;
|
pub use dioxus_html as html;
|
||||||
|
|
||||||
#[cfg(feature = "macro")]
|
#[cfg(feature = "macro")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "macro")))]
|
||||||
pub use dioxus_core_macro as core_macro;
|
pub use dioxus_core_macro as core_macro;
|
||||||
|
|
||||||
pub mod prelude {
|
pub mod prelude {
|
||||||
#[cfg(feature = "launch")]
|
#[cfg(feature = "launch")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "launch")))]
|
||||||
pub use crate::launch::*;
|
pub use crate::launch::*;
|
||||||
|
|
||||||
#[cfg(feature = "hooks")]
|
#[cfg(feature = "hooks")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "hooks")))]
|
||||||
pub use crate::hooks::*;
|
pub use crate::hooks::*;
|
||||||
|
|
||||||
#[cfg(feature = "signals")]
|
#[cfg(feature = "signals")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "signals")))]
|
||||||
pub use dioxus_signals::*;
|
pub use dioxus_signals::*;
|
||||||
|
|
||||||
pub use dioxus_core::prelude::*;
|
pub use dioxus_core::prelude::*;
|
||||||
|
|
||||||
#[cfg(feature = "macro")]
|
#[cfg(feature = "macro")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "macro")))]
|
||||||
#[allow(deprecated)]
|
#[allow(deprecated)]
|
||||||
pub use dioxus_core_macro::{component, format_args_f, inline_props, render, rsx, Props};
|
pub use dioxus_core_macro::{component, format_args_f, inline_props, render, rsx, Props};
|
||||||
|
|
||||||
#[cfg(feature = "launch")]
|
#[cfg(feature = "launch")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "launch")))]
|
||||||
pub use dioxus_config_macro::*;
|
pub use dioxus_config_macro::*;
|
||||||
|
|
||||||
#[cfg(feature = "html")]
|
#[cfg(feature = "html")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "html")))]
|
||||||
pub use dioxus_html as dioxus_elements;
|
pub use dioxus_html as dioxus_elements;
|
||||||
|
|
||||||
#[cfg(feature = "html")]
|
#[cfg(feature = "html")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "html")))]
|
||||||
pub use dioxus_elements::{prelude::*, GlobalAttributes, SvgAttributes};
|
pub use dioxus_elements::{prelude::*, GlobalAttributes, SvgAttributes};
|
||||||
|
|
||||||
#[cfg(all(not(target_arch = "wasm32"), feature = "hot-reload"))]
|
#[cfg(all(not(target_arch = "wasm32"), feature = "hot-reload"))]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "hot-reload")))]
|
||||||
pub use dioxus_hot_reload::{self, hot_reload_init};
|
pub use dioxus_hot_reload::{self, hot_reload_init};
|
||||||
|
|
||||||
pub use dioxus_core;
|
pub use dioxus_core;
|
||||||
|
|
||||||
#[cfg(feature = "fullstack")]
|
#[cfg(feature = "fullstack")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "fullstack")))]
|
||||||
pub use dioxus_fullstack::prelude::*;
|
pub use dioxus_fullstack::prelude::*;
|
||||||
|
|
||||||
#[cfg(feature = "router")]
|
#[cfg(feature = "router")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "router")))]
|
||||||
pub use dioxus_router;
|
pub use dioxus_router;
|
||||||
#[cfg(feature = "router")]
|
#[cfg(feature = "router")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "router")))]
|
||||||
pub use dioxus_router::prelude::*;
|
pub use dioxus_router::prelude::*;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "web")]
|
#[cfg(feature = "web")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "web")))]
|
||||||
pub use dioxus_web as web;
|
pub use dioxus_web as web;
|
||||||
|
|
||||||
#[cfg(feature = "router")]
|
#[cfg(feature = "router")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "router")))]
|
||||||
pub use dioxus_router as router;
|
pub use dioxus_router as router;
|
||||||
|
|
||||||
#[cfg(feature = "fullstack")]
|
#[cfg(feature = "fullstack")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "fullstack")))]
|
||||||
pub use dioxus_fullstack as fullstack;
|
pub use dioxus_fullstack as fullstack;
|
||||||
|
|
||||||
#[cfg(feature = "desktop")]
|
#[cfg(feature = "desktop")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "desktop")))]
|
||||||
pub use dioxus_desktop as desktop;
|
pub use dioxus_desktop as desktop;
|
||||||
|
|
||||||
#[cfg(feature = "mobile")]
|
#[cfg(feature = "mobile")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "mobile")))]
|
||||||
pub use dioxus_desktop as mobile;
|
pub use dioxus_desktop as mobile;
|
||||||
|
|
||||||
#[cfg(feature = "liveview")]
|
#[cfg(feature = "liveview")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "liveview")))]
|
||||||
pub use dioxus_liveview as liveview;
|
pub use dioxus_liveview as liveview;
|
||||||
|
|
||||||
#[cfg(feature = "tui")]
|
#[cfg(feature = "tui")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "tui")))]
|
||||||
pub use dioxus_tui as tui;
|
pub use dioxus_tui as tui;
|
||||||
|
|
||||||
#[cfg(feature = "ssr")]
|
#[cfg(feature = "ssr")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "ssr")))]
|
||||||
pub use dioxus_ssr as ssr;
|
pub use dioxus_ssr as ssr;
|
||||||
@@ -81,3 +81,5 @@ salvo = ["dep:salvo", "server", "http-body-util"]
|
|||||||
server = ["server_fn/ssr", "dioxus_server_macro/server", "tokio", "tokio-util", "tokio-stream", "dioxus-ssr", "dioxus-ssr/incremental", "tower", "hyper", "http", "tower-layer", "anymap", "tracing-futures", "pin-project", "thiserror", "dioxus-cli-config"]
|
server = ["server_fn/ssr", "dioxus_server_macro/server", "tokio", "tokio-util", "tokio-stream", "dioxus-ssr", "dioxus-ssr/incremental", "tower", "hyper", "http", "tower-layer", "anymap", "tracing-futures", "pin-project", "thiserror", "dioxus-cli-config"]
|
||||||
default-tls = ["server_fn/default-tls"]
|
default-tls = ["server_fn/default-tls"]
|
||||||
rustls = ["server_fn/rustls"]
|
rustls = ["server_fn/rustls"]
|
||||||
|
# This feature enables some nightly flags that make it more clear what structs/methods are available in each feature
|
||||||
|
nightly-doc = []
|
||||||
@@ -4,10 +4,10 @@
|
|||||||
// ```
|
// ```
|
||||||
|
|
||||||
use axum_desktop::*;
|
use axum_desktop::*;
|
||||||
use dioxus_fullstack::prelude::server_fn::set_server_url;
|
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
// Set the url of the server where server functions are hosted.
|
// Set the url of the server where server functions are hosted.
|
||||||
set_server_url("http://127.0.0.1:8080");
|
#[cfg(not(feature = "server"))]
|
||||||
|
dioxus::fullstack::prelude::server_fn::set_server_url("http://127.0.0.1:8080");
|
||||||
dioxus::desktop::launch(app)
|
dioxus::desktop::launch(app)
|
||||||
}
|
}
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
// ```
|
// ```
|
||||||
|
|
||||||
use axum_desktop::*;
|
use axum_desktop::*;
|
||||||
use dioxus_fullstack::prelude::*;
|
use dioxus::prelude::*;
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() {
|
async fn main() {
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ async fn main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Hydrate the page
|
// Hydrate the page
|
||||||
#[cfg(feature = "web")]
|
#[cfg(all(feature = "web", not(feature = "server")))]
|
||||||
fn main() {
|
fn main() {
|
||||||
dioxus_web::launch_with_props(
|
dioxus_web::launch_with_props(
|
||||||
dioxus_fullstack::router::RouteWithCfg::<Route>,
|
dioxus_fullstack::router::RouteWithCfg::<Route>,
|
||||||
|
|||||||
@@ -332,7 +332,7 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn connect_hot_reload(self) -> Self {
|
fn connect_hot_reload(self) -> Self {
|
||||||
#[cfg(all(debug_assertions, feature = "hot-reload", feature = "server"))]
|
#[cfg(all(debug_assertions, feature = "hot-reload"))]
|
||||||
{
|
{
|
||||||
self.nest(
|
self.nest(
|
||||||
"/_dioxus",
|
"/_dioxus",
|
||||||
@@ -354,7 +354,7 @@ where
|
|||||||
.route("/hot_reload", get(hot_reload_handler)),
|
.route("/hot_reload", get(hot_reload_handler)),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
#[cfg(not(all(debug_assertions, feature = "hot-reload", feature = "server")))]
|
#[cfg(not(all(debug_assertions, feature = "hot-reload")))]
|
||||||
{
|
{
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
@@ -476,7 +476,7 @@ fn report_err<E: std::fmt::Display>(e: E) -> Response<BoxBody> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A handler for Dioxus web hot reload websocket. This will send the updated static parts of the RSX to the client when they change.
|
/// A handler for Dioxus web hot reload websocket. This will send the updated static parts of the RSX to the client when they change.
|
||||||
#[cfg(all(debug_assertions, feature = "hot-reload", feature = "server"))]
|
#[cfg(all(debug_assertions, feature = "hot-reload"))]
|
||||||
pub async fn hot_reload_handler(ws: axum::extract::WebSocketUpgrade) -> impl IntoResponse {
|
pub async fn hot_reload_handler(ws: axum::extract::WebSocketUpgrade) -> impl IntoResponse {
|
||||||
use axum::extract::ws::Message;
|
use axum::extract::ws::Message;
|
||||||
use futures_util::StreamExt;
|
use futures_util::StreamExt;
|
||||||
|
|||||||
@@ -12,8 +12,8 @@
|
|||||||
|
|
||||||
#[cfg(feature = "axum")]
|
#[cfg(feature = "axum")]
|
||||||
pub mod axum_adapter;
|
pub mod axum_adapter;
|
||||||
#[cfg(feature = "salvo")]
|
// #[cfg(feature = "salvo")]
|
||||||
pub mod salvo_adapter;
|
// pub mod salvo_adapter;
|
||||||
#[cfg(feature = "warp")]
|
#[cfg(feature = "warp")]
|
||||||
pub mod warp_adapter;
|
pub mod warp_adapter;
|
||||||
|
|
||||||
|
|||||||
@@ -291,17 +291,20 @@ impl DioxusRouterExt for Router {
|
|||||||
) -> Self {
|
) -> Self {
|
||||||
let cfg = cfg.into();
|
let cfg = cfg.into();
|
||||||
|
|
||||||
self.serve_static_assets(cfg.assets_path)
|
self.serve_static_assets(cfg.assets_path.clone())
|
||||||
.connect_hot_reload()
|
.connect_hot_reload()
|
||||||
.register_server_fns(server_fn_path)
|
.register_server_fns(server_fn_path)
|
||||||
.push(Router::with_path("/<**any_path>").get(SSRHandler { cfg }))
|
.push(Router::with_path("/<**any_path>").get(SSRHandler {
|
||||||
|
config: cfg,
|
||||||
|
virtual_dom: virtual_dom_factory,
|
||||||
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn connect_hot_reload(self) -> Self {
|
fn connect_hot_reload(self) -> Self {
|
||||||
let mut _dioxus_router = Router::with_path("_dioxus");
|
let mut _dioxus_router = Router::with_path("_dioxus");
|
||||||
_dioxus_router =
|
_dioxus_router =
|
||||||
_dioxus_router.push(Router::with_path("hot_reload").handle(HotReloadHandler));
|
_dioxus_router.push(Router::with_path("hot_reload").handle(HotReloadHandler));
|
||||||
#[cfg(all(debug_assertions, feature = "hot-reload", feature = "server"))]
|
#[cfg(all(debug_assertions, feature = "hot-reload"))]
|
||||||
{
|
{
|
||||||
_dioxus_router = _dioxus_router.push(Router::with_path("disconnect").handle(ignore_ws));
|
_dioxus_router = _dioxus_router.push(Router::with_path("disconnect").handle(ignore_ws));
|
||||||
}
|
}
|
||||||
@@ -485,11 +488,11 @@ fn handle_error(error: impl Error + Send + Sync, res: &mut Response) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A handler for Dioxus web hot reload websocket. This will send the updated static parts of the RSX to the client when they change.
|
/// A handler for Dioxus web hot reload websocket. This will send the updated static parts of the RSX to the client when they change.
|
||||||
#[cfg(not(all(debug_assertions, feature = "hot-reload", feature = "server")))]
|
#[cfg(not(all(debug_assertions, feature = "hot-reload")))]
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct HotReloadHandler;
|
pub struct HotReloadHandler;
|
||||||
|
|
||||||
#[cfg(not(all(debug_assertions, feature = "hot-reload", feature = "server")))]
|
#[cfg(not(all(debug_assertions, feature = "hot-reload")))]
|
||||||
#[handler]
|
#[handler]
|
||||||
impl HotReloadHandler {
|
impl HotReloadHandler {
|
||||||
async fn handle(
|
async fn handle(
|
||||||
@@ -503,11 +506,11 @@ impl HotReloadHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A handler for Dioxus web hot reload websocket. This will send the updated static parts of the RSX to the client when they change.
|
/// A handler for Dioxus web hot reload websocket. This will send the updated static parts of the RSX to the client when they change.
|
||||||
#[cfg(all(debug_assertions, feature = "hot-reload", feature = "server"))]
|
#[cfg(all(debug_assertions, feature = "hot-reload"))]
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct HotReloadHandler;
|
pub struct HotReloadHandler;
|
||||||
|
|
||||||
#[cfg(all(debug_assertions, feature = "hot-reload", feature = "server"))]
|
#[cfg(all(debug_assertions, feature = "hot-reload"))]
|
||||||
#[handler]
|
#[handler]
|
||||||
impl HotReloadHandler {
|
impl HotReloadHandler {
|
||||||
async fn handle(
|
async fn handle(
|
||||||
@@ -561,7 +564,7 @@ impl HotReloadHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(all(debug_assertions, feature = "hot-reload", feature = "server"))]
|
#[cfg(all(debug_assertions, feature = "hot-reload"))]
|
||||||
#[handler]
|
#[handler]
|
||||||
async fn ignore_ws(req: &mut Request, res: &mut Response) -> Result<(), salvo::http::StatusError> {
|
async fn ignore_ws(req: &mut Request, res: &mut Response) -> Result<(), salvo::http::StatusError> {
|
||||||
use salvo::websocket::WebSocketUpgrade;
|
use salvo::websocket::WebSocketUpgrade;
|
||||||
|
|||||||
@@ -187,7 +187,7 @@ pub fn serve_dioxus_application(
|
|||||||
) -> BoxedFilter<(impl Reply,)> {
|
) -> BoxedFilter<(impl Reply,)> {
|
||||||
let cfg = cfg.into();
|
let cfg = cfg.into();
|
||||||
// Serve the dist folder and the index.html file
|
// Serve the dist folder and the index.html file
|
||||||
let serve_dir = warp::fs::dir(cfg.assets_path);
|
let serve_dir = warp::fs::dir(cfg.assets_path.clone());
|
||||||
|
|
||||||
let virtual_dom_factory =
|
let virtual_dom_factory =
|
||||||
Arc::new(virtual_dom_factory) as Arc<dyn Fn() -> VirtualDom + Send + Sync + 'static>;
|
Arc::new(virtual_dom_factory) as Arc<dyn Fn() -> VirtualDom + Send + Sync + 'static>;
|
||||||
@@ -332,13 +332,13 @@ impl warp::reject::Reject for RecieveFailed {}
|
|||||||
/// ```
|
/// ```
|
||||||
pub fn connect_hot_reload() -> impl Filter<Extract = (impl Reply,), Error = warp::Rejection> + Clone
|
pub fn connect_hot_reload() -> impl Filter<Extract = (impl Reply,), Error = warp::Rejection> + Clone
|
||||||
{
|
{
|
||||||
#[cfg(not(all(debug_assertions, feature = "hot-reload", feature = "server")))]
|
#[cfg(not(all(debug_assertions, feature = "hot-reload")))]
|
||||||
{
|
{
|
||||||
warp::path!("_dioxus" / "hot_reload")
|
warp::path!("_dioxus" / "hot_reload")
|
||||||
.map(warp::reply)
|
.map(warp::reply)
|
||||||
.map(|reply| warp::reply::with_status(reply, warp::http::StatusCode::NOT_FOUND))
|
.map(|reply| warp::reply::with_status(reply, warp::http::StatusCode::NOT_FOUND))
|
||||||
}
|
}
|
||||||
#[cfg(all(debug_assertions, feature = "hot-reload", feature = "server"))]
|
#[cfg(all(debug_assertions, feature = "hot-reload"))]
|
||||||
{
|
{
|
||||||
use crate::hot_reload::HotReloadState;
|
use crate::hot_reload::HotReloadState;
|
||||||
use futures_util::sink::SinkExt;
|
use futures_util::sink::SinkExt;
|
||||||
@@ -349,7 +349,7 @@ pub fn connect_hot_reload() -> impl Filter<Extract = (impl Reply,), Error = warp
|
|||||||
.and(warp::any().then(crate::hot_reload::spawn_hot_reload))
|
.and(warp::any().then(crate::hot_reload::spawn_hot_reload))
|
||||||
.and(warp::ws())
|
.and(warp::ws())
|
||||||
.map(move |state: &'static HotReloadState, ws: warp::ws::Ws| {
|
.map(move |state: &'static HotReloadState, ws: warp::ws::Ws| {
|
||||||
#[cfg(all(debug_assertions, feature = "hot-reload", feature = "server"))]
|
// #[cfg(all(debug_assertions, feature = "hot-reload"))]
|
||||||
ws.on_upgrade(move |mut websocket| {
|
ws.on_upgrade(move |mut websocket| {
|
||||||
async move {
|
async move {
|
||||||
println!("🔥 Hot Reload WebSocket connected");
|
println!("🔥 Hot Reload WebSocket connected");
|
||||||
@@ -393,7 +393,7 @@ pub fn connect_hot_reload() -> impl Filter<Extract = (impl Reply,), Error = warp
|
|||||||
.and(warp::ws())
|
.and(warp::ws())
|
||||||
.map(move |ws: warp::ws::Ws| {
|
.map(move |ws: warp::ws::Ws| {
|
||||||
println!("disconnect");
|
println!("disconnect");
|
||||||
#[cfg(all(debug_assertions, feature = "hot-reload", feature = "server"))]
|
#[cfg(all(debug_assertions, feature = "hot-reload",))]
|
||||||
ws.on_upgrade(move |mut websocket| async move {
|
ws.on_upgrade(move |mut websocket| async move {
|
||||||
struct DisconnectOnDrop(Option<warp::ws::WebSocket>);
|
struct DisconnectOnDrop(Option<warp::ws::WebSocket>);
|
||||||
impl Drop for DisconnectOnDrop {
|
impl Drop for DisconnectOnDrop {
|
||||||
|
|||||||
@@ -53,6 +53,7 @@ impl Config {
|
|||||||
|
|
||||||
/// Set the address to serve the app on.
|
/// Set the address to serve the app on.
|
||||||
#[cfg(feature = "server")]
|
#[cfg(feature = "server")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "server")))]
|
||||||
pub fn addr(self, addr: impl Into<std::net::SocketAddr>) -> Self {
|
pub fn addr(self, addr: impl Into<std::net::SocketAddr>) -> Self {
|
||||||
let addr = addr.into();
|
let addr = addr.into();
|
||||||
Self { addr, ..self }
|
Self { addr, ..self }
|
||||||
@@ -60,6 +61,7 @@ impl Config {
|
|||||||
|
|
||||||
/// Set the route to the server functions.
|
/// Set the route to the server functions.
|
||||||
#[cfg(feature = "server")]
|
#[cfg(feature = "server")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "server")))]
|
||||||
pub fn server_fn_route(self, server_fn_route: &'static str) -> Self {
|
pub fn server_fn_route(self, server_fn_route: &'static str) -> Self {
|
||||||
Self {
|
Self {
|
||||||
server_fn_route,
|
server_fn_route,
|
||||||
@@ -69,6 +71,7 @@ impl Config {
|
|||||||
|
|
||||||
/// Set the incremental renderer config.
|
/// Set the incremental renderer config.
|
||||||
#[cfg(feature = "server")]
|
#[cfg(feature = "server")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "server")))]
|
||||||
pub fn incremental(self, cfg: IncrementalRendererConfig) -> Self {
|
pub fn incremental(self, cfg: IncrementalRendererConfig) -> Self {
|
||||||
Self {
|
Self {
|
||||||
server_cfg: self.server_cfg.incremental(cfg),
|
server_cfg: self.server_cfg.incremental(cfg),
|
||||||
@@ -78,18 +81,21 @@ impl Config {
|
|||||||
|
|
||||||
/// Set the server config.
|
/// Set the server config.
|
||||||
#[cfg(feature = "server")]
|
#[cfg(feature = "server")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "server")))]
|
||||||
pub fn server_cfg(self, server_cfg: ServeConfigBuilder) -> Self {
|
pub fn server_cfg(self, server_cfg: ServeConfigBuilder) -> Self {
|
||||||
Self { server_cfg, ..self }
|
Self { server_cfg, ..self }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set the web config.
|
/// Set the web config.
|
||||||
#[cfg(feature = "web")]
|
#[cfg(feature = "web")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "web")))]
|
||||||
pub fn web_cfg(self, web_cfg: dioxus_web::Config) -> Self {
|
pub fn web_cfg(self, web_cfg: dioxus_web::Config) -> Self {
|
||||||
Self { web_cfg, ..self }
|
Self { web_cfg, ..self }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set the desktop config.
|
/// Set the desktop config.
|
||||||
#[cfg(feature = "desktop")]
|
#[cfg(feature = "desktop")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "desktop")))]
|
||||||
pub fn desktop_cfg(self, desktop_cfg: dioxus_desktop::Config) -> Self {
|
pub fn desktop_cfg(self, desktop_cfg: dioxus_desktop::Config) -> Self {
|
||||||
Self {
|
Self {
|
||||||
desktop_cfg,
|
desktop_cfg,
|
||||||
@@ -99,11 +105,13 @@ impl Config {
|
|||||||
|
|
||||||
/// Set the mobile config.
|
/// Set the mobile config.
|
||||||
#[cfg(feature = "mobile")]
|
#[cfg(feature = "mobile")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "mobile")))]
|
||||||
pub fn mobile_cfg(self, mobile_cfg: dioxus_mobile::Config) -> Self {
|
pub fn mobile_cfg(self, mobile_cfg: dioxus_mobile::Config) -> Self {
|
||||||
Self { mobile_cfg, ..self }
|
Self { mobile_cfg, ..self }
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "server")]
|
#[cfg(feature = "server")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "server")))]
|
||||||
/// Launch a server application
|
/// Launch a server application
|
||||||
pub async fn launch_server(
|
pub async fn launch_server(
|
||||||
self,
|
self,
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
#![doc(html_logo_url = "https://avatars.githubusercontent.com/u/79236386")]
|
#![doc(html_logo_url = "https://avatars.githubusercontent.com/u/79236386")]
|
||||||
#![doc(html_favicon_url = "https://avatars.githubusercontent.com/u/79236386")]
|
#![doc(html_favicon_url = "https://avatars.githubusercontent.com/u/79236386")]
|
||||||
#![deny(missing_docs)]
|
#![deny(missing_docs)]
|
||||||
|
#![cfg_attr(any(docsrs, feature = "nightly-doc"), feature(doc_cfg))]
|
||||||
|
|
||||||
pub use once_cell;
|
pub use once_cell;
|
||||||
|
|
||||||
@@ -9,8 +10,20 @@ mod html_storage;
|
|||||||
|
|
||||||
#[cfg(feature = "server")]
|
#[cfg(feature = "server")]
|
||||||
mod adapters;
|
mod adapters;
|
||||||
|
// Splitting up the glob export lets us document features required for each adapter
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "axum")))]
|
||||||
|
#[cfg(feature = "axum")]
|
||||||
|
pub use adapters::axum_adapter;
|
||||||
|
// TODO: Compilation seems to be broken with the salvo feature enabled. Fix and add more features to checks in CI
|
||||||
|
// #[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "salvo")))]
|
||||||
|
// #[cfg(feature = "salvo")]
|
||||||
|
// pub use adapters::salvo_adapter;
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "warp")))]
|
||||||
|
#[cfg(feature = "warp")]
|
||||||
|
pub use adapters::warp_adapter;
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "server")))]
|
||||||
#[cfg(feature = "server")]
|
#[cfg(feature = "server")]
|
||||||
pub use adapters::*;
|
pub use adapters::{server_fn_service, ServerFnHandler};
|
||||||
mod config;
|
mod config;
|
||||||
mod hooks;
|
mod hooks;
|
||||||
#[cfg(all(debug_assertions, feature = "hot-reload", feature = "server"))]
|
#[cfg(all(debug_assertions, feature = "hot-reload", feature = "server"))]
|
||||||
@@ -30,35 +43,57 @@ mod server_fn;
|
|||||||
/// A prelude of commonly used items in dioxus-fullstack.
|
/// A prelude of commonly used items in dioxus-fullstack.
|
||||||
pub mod prelude {
|
pub mod prelude {
|
||||||
#[cfg(feature = "axum")]
|
#[cfg(feature = "axum")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "axum")))]
|
||||||
pub use crate::adapters::axum_adapter::*;
|
pub use crate::adapters::axum_adapter::*;
|
||||||
#[cfg(feature = "salvo")]
|
// #[cfg(feature = "salvo")]
|
||||||
pub use crate::adapters::salvo_adapter::*;
|
// #[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "salvo")))]
|
||||||
|
// pub use crate::adapters::salvo_adapter::*;
|
||||||
#[cfg(feature = "warp")]
|
#[cfg(feature = "warp")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "warp")))]
|
||||||
pub use crate::adapters::warp_adapter::*;
|
pub use crate::adapters::warp_adapter::*;
|
||||||
use crate::hooks;
|
use crate::hooks;
|
||||||
#[cfg(not(feature = "server"))]
|
#[cfg(not(feature = "server"))]
|
||||||
|
#[cfg_attr(
|
||||||
|
any(docsrs, feature = "nightly-doc"),
|
||||||
|
doc(cfg(not(feature = "server")))
|
||||||
|
)]
|
||||||
pub use crate::html_storage::deserialize::get_root_props_from_document;
|
pub use crate::html_storage::deserialize::get_root_props_from_document;
|
||||||
#[cfg(feature = "server")]
|
#[cfg(feature = "server")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "server")))]
|
||||||
pub use crate::layer::{Layer, Service};
|
pub use crate::layer::{Layer, Service};
|
||||||
#[cfg(all(feature = "server", feature = "router"))]
|
#[cfg(all(feature = "server", feature = "router"))]
|
||||||
|
#[cfg_attr(
|
||||||
|
any(docsrs, feature = "nightly-doc"),
|
||||||
|
doc(cfg(all(feature = "server", feature = "router")))
|
||||||
|
)]
|
||||||
pub use crate::render::pre_cache_static_routes_with_props;
|
pub use crate::render::pre_cache_static_routes_with_props;
|
||||||
#[cfg(feature = "server")]
|
#[cfg(feature = "server")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "server")))]
|
||||||
pub use crate::render::SSRState;
|
pub use crate::render::SSRState;
|
||||||
#[cfg(feature = "router")]
|
#[cfg(feature = "router")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "router")))]
|
||||||
pub use crate::router::FullstackRouterConfig;
|
pub use crate::router::FullstackRouterConfig;
|
||||||
#[cfg(feature = "server")]
|
#[cfg(feature = "server")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "server")))]
|
||||||
pub use crate::serve_config::{ServeConfig, ServeConfigBuilder};
|
pub use crate::serve_config::{ServeConfig, ServeConfigBuilder};
|
||||||
#[cfg(all(feature = "server", feature = "axum"))]
|
#[cfg(all(feature = "server", feature = "axum"))]
|
||||||
|
#[cfg_attr(
|
||||||
|
any(docsrs, feature = "nightly-doc"),
|
||||||
|
doc(cfg(all(feature = "server", feature = "axum")))
|
||||||
|
)]
|
||||||
pub use crate::server_context::Axum;
|
pub use crate::server_context::Axum;
|
||||||
#[cfg(feature = "server")]
|
#[cfg(feature = "server")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "server")))]
|
||||||
pub use crate::server_context::{
|
pub use crate::server_context::{
|
||||||
extract, server_context, DioxusServerContext, FromServerContext, ProvideServerContext,
|
extract, server_context, DioxusServerContext, FromServerContext, ProvideServerContext,
|
||||||
};
|
};
|
||||||
pub use crate::server_fn::DioxusServerFn;
|
pub use crate::server_fn::DioxusServerFn;
|
||||||
#[cfg(feature = "server")]
|
#[cfg(feature = "server")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "server")))]
|
||||||
pub use crate::server_fn::{ServerFnMiddleware, ServerFnTraitObj, ServerFunction};
|
pub use crate::server_fn::{ServerFnMiddleware, ServerFnTraitObj, ServerFunction};
|
||||||
pub use dioxus_server_macro::*;
|
pub use dioxus_server_macro::*;
|
||||||
#[cfg(feature = "server")]
|
#[cfg(feature = "server")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "server")))]
|
||||||
pub use dioxus_ssr::incremental::IncrementalRendererConfig;
|
pub use dioxus_ssr::incremental::IncrementalRendererConfig;
|
||||||
pub use server_fn::{self, ServerFn as _, ServerFnError};
|
pub use server_fn::{self, ServerFn as _, ServerFnError};
|
||||||
|
|
||||||
@@ -66,11 +101,26 @@ pub mod prelude {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Warn users about overlapping features
|
// Warn users about overlapping features
|
||||||
#[cfg(all(feature = "server", feature = "web", not(doc)))]
|
#[cfg(all(
|
||||||
|
feature = "server",
|
||||||
|
feature = "web",
|
||||||
|
not(doc),
|
||||||
|
not(feature = "nightly-doc")
|
||||||
|
))]
|
||||||
compile_error!("The `ssr` feature (enabled by `warp`, `axum`, or `salvo`) and `web` feature are overlapping. Please choose one or the other.");
|
compile_error!("The `ssr` feature (enabled by `warp`, `axum`, or `salvo`) and `web` feature are overlapping. Please choose one or the other.");
|
||||||
|
|
||||||
#[cfg(all(feature = "server", feature = "desktop", not(doc)))]
|
#[cfg(all(
|
||||||
|
feature = "server",
|
||||||
|
feature = "desktop",
|
||||||
|
not(doc),
|
||||||
|
not(feature = "nightly-doc")
|
||||||
|
))]
|
||||||
compile_error!("The `ssr` feature (enabled by `warp`, `axum`, or `salvo`) and `desktop` feature are overlapping. Please choose one or the other.");
|
compile_error!("The `ssr` feature (enabled by `warp`, `axum`, or `salvo`) and `desktop` feature are overlapping. Please choose one or the other.");
|
||||||
|
|
||||||
#[cfg(all(feature = "server", feature = "mobile", not(doc)))]
|
#[cfg(all(
|
||||||
|
feature = "server",
|
||||||
|
feature = "mobile",
|
||||||
|
not(doc),
|
||||||
|
not(feature = "nightly-doc")
|
||||||
|
))]
|
||||||
compile_error!("The `ssr` feature (enabled by `warp`, `axum`, or `salvo`) and `mobile` feature are overlapping. Please choose one or the other.");
|
compile_error!("The `ssr` feature (enabled by `warp`, `axum`, or `salvo`) and `mobile` feature are overlapping. Please choose one or the other.");
|
||||||
@@ -228,6 +228,7 @@ impl<T: Send + Sync + Clone + 'static> FromServerContext for FromContext<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "axum")]
|
#[cfg(feature = "axum")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "axum")))]
|
||||||
/// An adapter for axum extractors for the server context
|
/// An adapter for axum extractors for the server context
|
||||||
pub struct Axum;
|
pub struct Axum;
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
#[cfg(any(feature = "server", doc))]
|
#[cfg(feature = "server")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "server")))]
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
/// A trait object for a function that be called on serializable arguments and returns a serializable result.
|
/// A trait object for a function that be called on serializable arguments and returns a serializable result.
|
||||||
pub struct ServerFnTraitObj(server_fn::ServerFnTraitObj<()>);
|
pub struct ServerFnTraitObj(server_fn::ServerFnTraitObj<()>);
|
||||||
|
|
||||||
#[cfg(any(feature = "server", doc))]
|
#[cfg(feature = "server")]
|
||||||
impl std::ops::Deref for ServerFnTraitObj {
|
impl std::ops::Deref for ServerFnTraitObj {
|
||||||
type Target = server_fn::ServerFnTraitObj<()>;
|
type Target = server_fn::ServerFnTraitObj<()>;
|
||||||
|
|
||||||
@@ -12,14 +13,14 @@ impl std::ops::Deref for ServerFnTraitObj {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(any(feature = "server", doc))]
|
#[cfg(feature = "server")]
|
||||||
impl std::ops::DerefMut for ServerFnTraitObj {
|
impl std::ops::DerefMut for ServerFnTraitObj {
|
||||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||||
&mut self.0
|
&mut self.0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(any(feature = "server", doc))]
|
#[cfg(feature = "server")]
|
||||||
impl ServerFnTraitObj {
|
impl ServerFnTraitObj {
|
||||||
fn new(
|
fn new(
|
||||||
prefix: &'static str,
|
prefix: &'static str,
|
||||||
@@ -40,6 +41,7 @@ impl ServerFnTraitObj {
|
|||||||
server_fn::inventory::collect!(ServerFnTraitObj);
|
server_fn::inventory::collect!(ServerFnTraitObj);
|
||||||
|
|
||||||
#[cfg(feature = "server")]
|
#[cfg(feature = "server")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "server")))]
|
||||||
/// Middleware for a server function
|
/// Middleware for a server function
|
||||||
pub struct ServerFnMiddleware {
|
pub struct ServerFnMiddleware {
|
||||||
/// The prefix of the server function.
|
/// The prefix of the server function.
|
||||||
@@ -72,7 +74,8 @@ pub(crate) static MIDDLEWARE: once_cell::sync::Lazy<
|
|||||||
#[cfg(feature = "server")]
|
#[cfg(feature = "server")]
|
||||||
server_fn::inventory::collect!(ServerFnMiddleware);
|
server_fn::inventory::collect!(ServerFnMiddleware);
|
||||||
|
|
||||||
#[cfg(any(feature = "server", doc))]
|
#[cfg(feature = "server")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "server")))]
|
||||||
/// A server function that can be called on serializable arguments and returns a serializable result.
|
/// A server function that can be called on serializable arguments and returns a serializable result.
|
||||||
pub type ServerFunction = server_fn::SerializedFnTraitObj<()>;
|
pub type ServerFunction = server_fn::SerializedFnTraitObj<()>;
|
||||||
|
|
||||||
@@ -88,7 +91,8 @@ static REGISTERED_SERVER_FUNCTIONS: once_cell::sync::Lazy<
|
|||||||
std::sync::Arc::new(std::sync::RwLock::new(map))
|
std::sync::Arc::new(std::sync::RwLock::new(map))
|
||||||
});
|
});
|
||||||
|
|
||||||
#[cfg(any(feature = "server", doc))]
|
#[cfg(feature = "server")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "server")))]
|
||||||
/// The registry of all Dioxus server functions.
|
/// The registry of all Dioxus server functions.
|
||||||
pub struct DioxusServerFnRegistry;
|
pub struct DioxusServerFnRegistry;
|
||||||
|
|
||||||
@@ -155,7 +159,8 @@ impl server_fn::ServerFunctionRegistry<()> for DioxusServerFnRegistry {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(any(feature = "server", doc))]
|
#[cfg(feature = "server")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "server")))]
|
||||||
/// Errors that can occur when registering a server function.
|
/// Errors that can occur when registering a server function.
|
||||||
#[derive(thiserror::Error, Debug, Clone, serde::Serialize, serde::Deserialize)]
|
#[derive(thiserror::Error, Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
pub enum ServerRegistrationFnError {
|
pub enum ServerRegistrationFnError {
|
||||||
@@ -178,7 +183,8 @@ pub enum ServerRegistrationFnError {
|
|||||||
/// Technically, the trait is implemented on a type that describes the server function's arguments, not the function itself.
|
/// Technically, the trait is implemented on a type that describes the server function's arguments, not the function itself.
|
||||||
pub trait DioxusServerFn: server_fn::ServerFn<()> {
|
pub trait DioxusServerFn: server_fn::ServerFn<()> {
|
||||||
/// Registers the server function, allowing the client to query it by URL.
|
/// Registers the server function, allowing the client to query it by URL.
|
||||||
#[cfg(any(feature = "server", doc))]
|
#[cfg(feature = "server")]
|
||||||
|
#[cfg_attr(any(docsrs, feature = "nightly-doc"), doc(cfg(feature = "server")))]
|
||||||
fn register_explicit() -> Result<(), server_fn::ServerFnError> {
|
fn register_explicit() -> Result<(), server_fn::ServerFnError> {
|
||||||
Self::register_in_explicit::<DioxusServerFnRegistry>()
|
Self::register_in_explicit::<DioxusServerFnRegistry>()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -228,9 +228,9 @@ pub trait Storage<Data = ()>: AnyStorage + 'static {
|
|||||||
/// A trait for any storage backing type.
|
/// A trait for any storage backing type.
|
||||||
pub trait AnyStorage: Default {
|
pub trait AnyStorage: Default {
|
||||||
/// The reference this storage type returns.
|
/// The reference this storage type returns.
|
||||||
type Ref<T: ?Sized + 'static>: Deref<Target = T>;
|
type Ref<T: ?Sized + 'static>: Deref<Target = T> + 'static;
|
||||||
/// The mutable reference this storage type returns.
|
/// The mutable reference this storage type returns.
|
||||||
type Mut<T: ?Sized + 'static>: DerefMut<Target = T>;
|
type Mut<T: ?Sized + 'static>: DerefMut<Target = T> + 'static;
|
||||||
|
|
||||||
/// Try to map the mutable ref.
|
/// Try to map the mutable ref.
|
||||||
fn try_map_mut<T: ?Sized, U: ?Sized + 'static>(
|
fn try_map_mut<T: ?Sized, U: ?Sized + 'static>(
|
||||||
@@ -247,13 +247,16 @@ pub trait AnyStorage: Default {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Try to map the ref.
|
/// Try to map the ref.
|
||||||
fn try_map<T, U: ?Sized + 'static>(
|
fn try_map<T: ?Sized, U: ?Sized + 'static>(
|
||||||
ref_: Self::Ref<T>,
|
ref_: Self::Ref<T>,
|
||||||
f: impl FnOnce(&T) -> Option<&U>,
|
f: impl FnOnce(&T) -> Option<&U>,
|
||||||
) -> Option<Self::Ref<U>>;
|
) -> Option<Self::Ref<U>>;
|
||||||
|
|
||||||
/// Map the ref.
|
/// Map the ref.
|
||||||
fn map<T, U: ?Sized + 'static>(ref_: Self::Ref<T>, f: impl FnOnce(&T) -> &U) -> Self::Ref<U> {
|
fn map<T: ?Sized, U: ?Sized + 'static>(
|
||||||
|
ref_: Self::Ref<T>,
|
||||||
|
f: impl FnOnce(&T) -> &U,
|
||||||
|
) -> Self::Ref<U> {
|
||||||
Self::try_map(ref_, |v| Some(f(v))).unwrap()
|
Self::try_map(ref_, |v| Some(f(v))).unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ impl AnyStorage for SyncStorage {
|
|||||||
type Ref<R: ?Sized + 'static> = GenerationalRef<MappedRwLockReadGuard<'static, R>>;
|
type Ref<R: ?Sized + 'static> = GenerationalRef<MappedRwLockReadGuard<'static, R>>;
|
||||||
type Mut<W: ?Sized + 'static> = GenerationalRefMut<MappedRwLockWriteGuard<'static, W>>;
|
type Mut<W: ?Sized + 'static> = GenerationalRefMut<MappedRwLockWriteGuard<'static, W>>;
|
||||||
|
|
||||||
fn try_map<I, U: ?Sized + 'static>(
|
fn try_map<I: ?Sized, U: ?Sized + 'static>(
|
||||||
ref_: Self::Ref<I>,
|
ref_: Self::Ref<I>,
|
||||||
f: impl FnOnce(&I) -> Option<&U>,
|
f: impl FnOnce(&I) -> Option<&U>,
|
||||||
) -> Option<Self::Ref<U>> {
|
) -> Option<Self::Ref<U>> {
|
||||||
|
|||||||
@@ -92,7 +92,7 @@ impl AnyStorage for UnsyncStorage {
|
|||||||
type Ref<R: ?Sized + 'static> = GenerationalRef<Ref<'static, R>>;
|
type Ref<R: ?Sized + 'static> = GenerationalRef<Ref<'static, R>>;
|
||||||
type Mut<W: ?Sized + 'static> = GenerationalRefMut<RefMut<'static, W>>;
|
type Mut<W: ?Sized + 'static> = GenerationalRefMut<RefMut<'static, W>>;
|
||||||
|
|
||||||
fn try_map<I, U: ?Sized + 'static>(
|
fn try_map<I: ?Sized, U: ?Sized + 'static>(
|
||||||
_self: Self::Ref<I>,
|
_self: Self::Ref<I>,
|
||||||
f: impl FnOnce(&I) -> Option<&U>,
|
f: impl FnOnce(&I) -> Option<&U>,
|
||||||
) -> Option<Self::Ref<U>> {
|
) -> Option<Self::Ref<U>> {
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
#![doc = include_str!("../README.md")]
|
#![doc = include_str!("../README.md")]
|
||||||
#![doc(html_logo_url = "https://avatars.githubusercontent.com/u/79236386")]
|
#![doc(html_logo_url = "https://avatars.githubusercontent.com/u/79236386")]
|
||||||
#![doc(html_favicon_url = "https://avatars.githubusercontent.com/u/79236386")]
|
#![doc(html_favicon_url = "https://avatars.githubusercontent.com/u/79236386")]
|
||||||
#![cfg_attr(feature = "nightly-features", feature(debug_refcell))]
|
|
||||||
|
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
/// A helper macro for using hooks and properties in async environments.
|
/// A helper macro for using hooks and properties in async environments.
|
||||||
|
|||||||
@@ -3,9 +3,9 @@ use std::any::Any;
|
|||||||
|
|
||||||
#[cfg(feature = "axum")]
|
#[cfg(feature = "axum")]
|
||||||
pub type Config = crate::Config<axum::Router>;
|
pub type Config = crate::Config<axum::Router>;
|
||||||
#[cfg(feature = "salvo")]
|
#[cfg(all(feature = "salvo", not(feature = "axum")))]
|
||||||
pub type Config = crate::Config<salvo::Router>;
|
pub type Config = crate::Config<salvo::Router>;
|
||||||
#[cfg(feature = "rocket")]
|
#[cfg(all(feature = "rocket", not(any(feature = "axum", feature = "salvo"))))]
|
||||||
pub type Config = crate::Config<rocket::Rocket<rocket::Build>>;
|
pub type Config = crate::Config<rocket::Rocket<rocket::Build>>;
|
||||||
|
|
||||||
/// Launches the WebView and runs the event loop, with configuration and root props.
|
/// Launches the WebView and runs the event loop, with configuration and root props.
|
||||||
|
|||||||
@@ -35,7 +35,6 @@ default = []
|
|||||||
ssr = ["dioxus-ssr/incremental", "tokio", "dioxus-fullstack?/server"]
|
ssr = ["dioxus-ssr/incremental", "tokio", "dioxus-fullstack?/server"]
|
||||||
liveview = ["dioxus-liveview", "tokio", "dep:serde", "serde_json"]
|
liveview = ["dioxus-liveview", "tokio", "dep:serde", "serde_json"]
|
||||||
wasm_test = []
|
wasm_test = []
|
||||||
serde = ["dep:serde", "gloo-utils?/serde"]
|
|
||||||
web = ["gloo", "web-sys", "wasm-bindgen", "gloo-utils", "js-sys"]
|
web = ["gloo", "web-sys", "wasm-bindgen", "gloo-utils", "js-sys"]
|
||||||
fullstack = ["dioxus-fullstack"]
|
fullstack = ["dioxus-fullstack"]
|
||||||
|
|
||||||
|
|||||||
@@ -11,18 +11,6 @@ pub struct RouterConfigFactory<R: Routable> {
|
|||||||
config: Rc<RefCell<Option<Box<dyn FnOnce() -> RouterConfig<R>>>>>,
|
config: Rc<RefCell<Option<Box<dyn FnOnce() -> RouterConfig<R>>>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
impl<R: Routable> Default for RouterConfigFactory<R>
|
|
||||||
where
|
|
||||||
<R as FromStr>::Err: std::fmt::Display,
|
|
||||||
R: serde::Serialize + serde::de::DeserializeOwned,
|
|
||||||
{
|
|
||||||
fn default() -> Self {
|
|
||||||
Self::from(RouterConfig::default)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(feature = "serde"))]
|
|
||||||
impl<R: Routable> Default for RouterConfigFactory<R>
|
impl<R: Routable> Default for RouterConfigFactory<R>
|
||||||
where
|
where
|
||||||
<R as FromStr>::Err: std::fmt::Display,
|
<R as FromStr>::Err: std::fmt::Display,
|
||||||
@@ -40,19 +28,6 @@ impl<R: Routable, F: FnOnce() -> RouterConfig<R> + 'static> From<F> for RouterCo
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
/// The props for [`Router`].
|
|
||||||
#[derive(Props)]
|
|
||||||
pub struct RouterProps<R: Routable>
|
|
||||||
where
|
|
||||||
<R as FromStr>::Err: std::fmt::Display,
|
|
||||||
R: serde::Serialize + serde::de::DeserializeOwned,
|
|
||||||
{
|
|
||||||
#[props(default, into)]
|
|
||||||
config: RouterConfigFactory<R>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(feature = "serde"))]
|
|
||||||
/// The props for [`Router`].
|
/// The props for [`Router`].
|
||||||
#[derive(Props)]
|
#[derive(Props)]
|
||||||
pub struct RouterProps<R: Routable>
|
pub struct RouterProps<R: Routable>
|
||||||
@@ -74,7 +49,6 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(feature = "serde"))]
|
|
||||||
impl<R: Routable> Default for RouterProps<R>
|
impl<R: Routable> Default for RouterProps<R>
|
||||||
where
|
where
|
||||||
<R as FromStr>::Err: std::fmt::Display,
|
<R as FromStr>::Err: std::fmt::Display,
|
||||||
@@ -86,20 +60,6 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
impl<R: Routable> Default for RouterProps<R>
|
|
||||||
where
|
|
||||||
<R as FromStr>::Err: std::fmt::Display,
|
|
||||||
R: serde::Serialize + serde::de::DeserializeOwned,
|
|
||||||
{
|
|
||||||
fn default() -> Self {
|
|
||||||
Self {
|
|
||||||
config: RouterConfigFactory::default(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(feature = "serde"))]
|
|
||||||
impl<R: Routable> PartialEq for RouterProps<R>
|
impl<R: Routable> PartialEq for RouterProps<R>
|
||||||
where
|
where
|
||||||
<R as FromStr>::Err: std::fmt::Display,
|
<R as FromStr>::Err: std::fmt::Display,
|
||||||
@@ -110,19 +70,6 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
impl<R: Routable> PartialEq for RouterProps<R>
|
|
||||||
where
|
|
||||||
<R as FromStr>::Err: std::fmt::Display,
|
|
||||||
R: serde::Serialize + serde::de::DeserializeOwned,
|
|
||||||
{
|
|
||||||
fn eq(&self, _: &Self) -> bool {
|
|
||||||
// prevent the router from re-rendering when the initial url or config changes
|
|
||||||
true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(feature = "serde"))]
|
|
||||||
/// A component that renders the current route.
|
/// A component that renders the current route.
|
||||||
pub fn Router<R: Routable + Clone>(props: RouterProps<R>) -> Element
|
pub fn Router<R: Routable + Clone>(props: RouterProps<R>) -> Element
|
||||||
where
|
where
|
||||||
@@ -148,28 +95,3 @@ where
|
|||||||
|
|
||||||
rsx! { Outlet::<R> {} }
|
rsx! { Outlet::<R> {} }
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
/// A component that renders the current route.
|
|
||||||
pub fn Router<R: Routable + Clone>(cx: ScopeState<RouterProps<R>>) -> Element
|
|
||||||
where
|
|
||||||
<R as FromStr>::Err: std::fmt::Display,
|
|
||||||
R: serde::Serialize + serde::de::DeserializeOwned,
|
|
||||||
{
|
|
||||||
use_context_provider(|| {
|
|
||||||
RouterContext::new(
|
|
||||||
(cx.props
|
|
||||||
.config
|
|
||||||
.config
|
|
||||||
.take()
|
|
||||||
.expect("use_context_provider ran twice"))(),
|
|
||||||
cx.schedule_update_any(),
|
|
||||||
)
|
|
||||||
});
|
|
||||||
use_context_provider(|| OutletContext::<R> {
|
|
||||||
current_level: 0,
|
|
||||||
_marker: std::marker::PhantomData,
|
|
||||||
});
|
|
||||||
|
|
||||||
rsx! { Outlet::<R> {} }
|
|
||||||
}
|
|
||||||
@@ -23,7 +23,6 @@ fn base_path() -> Option<&'static str> {
|
|||||||
base_path
|
base_path
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(feature = "serde"))]
|
|
||||||
#[allow(clippy::extra_unused_type_parameters)]
|
#[allow(clippy::extra_unused_type_parameters)]
|
||||||
fn update_scroll<R>(window: &Window, history: &History) {
|
fn update_scroll<R>(window: &Window, history: &History) {
|
||||||
let scroll = ScrollPosition::of_window(window);
|
let scroll = ScrollPosition::of_window(window);
|
||||||
@@ -32,27 +31,6 @@ fn update_scroll<R>(window: &Window, history: &History) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
fn update_scroll<R: serde::Serialize + serde::de::DeserializeOwned + Routable>(
|
|
||||||
window: &Window,
|
|
||||||
history: &History,
|
|
||||||
) {
|
|
||||||
if let Some(WebHistoryState { state, .. }) = get_current::<WebHistoryState<R>>(history) {
|
|
||||||
let scroll = ScrollPosition::of_window(window);
|
|
||||||
let state = WebHistoryState { state, scroll };
|
|
||||||
if let Err(err) = replace_state_with_url(history, &state, None) {
|
|
||||||
error!(err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
#[derive(serde::Deserialize, serde::Serialize)]
|
|
||||||
struct WebHistoryState<R> {
|
|
||||||
state: R,
|
|
||||||
scroll: ScrollPosition,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A [`HistoryProvider`] that integrates with a browser via the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API).
|
/// A [`HistoryProvider`] that integrates with a browser via the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API).
|
||||||
///
|
///
|
||||||
/// # Prefix
|
/// # Prefix
|
||||||
@@ -75,7 +53,6 @@ pub struct WebHistory<R: Routable> {
|
|||||||
phantom: std::marker::PhantomData<R>,
|
phantom: std::marker::PhantomData<R>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(feature = "serde"))]
|
|
||||||
impl<R: Routable> Default for WebHistory<R>
|
impl<R: Routable> Default for WebHistory<R>
|
||||||
where
|
where
|
||||||
<R as std::str::FromStr>::Err: std::fmt::Display,
|
<R as std::str::FromStr>::Err: std::fmt::Display,
|
||||||
@@ -85,19 +62,7 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
impl<R: Routable> Default for WebHistory<R>
|
|
||||||
where
|
|
||||||
<R as std::str::FromStr>::Err: std::fmt::Display,
|
|
||||||
R: serde::Serialize + serde::de::DeserializeOwned,
|
|
||||||
{
|
|
||||||
fn default() -> Self {
|
|
||||||
Self::new(None, true)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<R: Routable> WebHistory<R> {
|
impl<R: Routable> WebHistory<R> {
|
||||||
#[cfg(not(feature = "serde"))]
|
|
||||||
/// Create a new [`WebHistory`].
|
/// Create a new [`WebHistory`].
|
||||||
///
|
///
|
||||||
/// If `do_scroll_restoration` is [`true`], [`WebHistory`] will take control of the history
|
/// If `do_scroll_restoration` is [`true`], [`WebHistory`] will take control of the history
|
||||||
@@ -116,47 +81,6 @@ impl<R: Routable> WebHistory<R> {
|
|||||||
myself
|
myself
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
/// Create a new [`WebHistory`].
|
|
||||||
///
|
|
||||||
/// If `do_scroll_restoration` is [`true`], [`WebHistory`] will take control of the history
|
|
||||||
/// state. It'll also set the browsers scroll restoration to `manual`.
|
|
||||||
pub fn new(prefix: Option<String>, do_scroll_restoration: bool) -> Self
|
|
||||||
where
|
|
||||||
<R as std::str::FromStr>::Err: std::fmt::Display,
|
|
||||||
R: serde::Serialize + serde::de::DeserializeOwned,
|
|
||||||
{
|
|
||||||
let w = window().expect("access to `window`");
|
|
||||||
let h = w.history().expect("`window` has access to `history`");
|
|
||||||
let document = w.document().expect("`window` has access to `document`");
|
|
||||||
|
|
||||||
let myself = Self::new_inner(
|
|
||||||
prefix,
|
|
||||||
do_scroll_restoration,
|
|
||||||
EventListener::new(&document, "scroll", {
|
|
||||||
let mut last_updated = 0.0;
|
|
||||||
move |evt| {
|
|
||||||
// the time stamp in milliseconds
|
|
||||||
let time_stamp = evt.time_stamp();
|
|
||||||
// throttle the scroll event to 100ms
|
|
||||||
if (time_stamp - last_updated) < 100.0 {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
update_scroll::<R>(&w, &h);
|
|
||||||
last_updated = time_stamp;
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
let current_route = myself.current_route();
|
|
||||||
tracing::trace!("initial route: {:?}", current_route);
|
|
||||||
let current_url = current_route.to_string();
|
|
||||||
let state = myself.create_state(current_route);
|
|
||||||
let _ = replace_state_with_url(&myself.history, &state, Some(¤t_url));
|
|
||||||
|
|
||||||
myself
|
|
||||||
}
|
|
||||||
|
|
||||||
fn new_inner(prefix: Option<String>, do_scroll_restoration: bool) -> Self
|
fn new_inner(prefix: Option<String>, do_scroll_restoration: bool) -> Self
|
||||||
where
|
where
|
||||||
<R as std::str::FromStr>::Err: std::fmt::Display,
|
<R as std::str::FromStr>::Err: std::fmt::Display,
|
||||||
@@ -191,17 +115,10 @@ impl<R: Routable> WebHistory<R> {
|
|||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(feature = "serde"))]
|
|
||||||
fn create_state(&self, _state: R) -> [f64; 2] {
|
fn create_state(&self, _state: R) -> [f64; 2] {
|
||||||
let scroll = self.scroll_pos();
|
let scroll = self.scroll_pos();
|
||||||
[scroll.x, scroll.y]
|
[scroll.x, scroll.y]
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
fn create_state(&self, state: R) -> WebHistoryState<R> {
|
|
||||||
let scroll = self.scroll_pos();
|
|
||||||
WebHistoryState { state, scroll }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<R: Routable> WebHistory<R>
|
impl<R: Routable> WebHistory<R>
|
||||||
@@ -254,91 +171,6 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
impl<R: serde::Serialize + serde::de::DeserializeOwned + Routable> HistoryProvider<R>
|
|
||||||
for WebHistory<R>
|
|
||||||
where
|
|
||||||
<R as std::str::FromStr>::Err: std::fmt::Display,
|
|
||||||
{
|
|
||||||
fn current_route(&self) -> R {
|
|
||||||
match get_current::<WebHistoryState<_>>(&self.history) {
|
|
||||||
// Try to get the route from the history state
|
|
||||||
Some(route) => route.state,
|
|
||||||
// If that fails, get the route from the current URL
|
|
||||||
None => self.route_from_location(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn current_prefix(&self) -> Option<String> {
|
|
||||||
self.prefix.clone()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn go_back(&mut self) {
|
|
||||||
if let Err(e) = self.history.back() {
|
|
||||||
error!("failed to go back: ", e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn go_forward(&mut self) {
|
|
||||||
if let Err(e) = self.history.forward() {
|
|
||||||
error!("failed to go forward: ", e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn push(&mut self, state: R) {
|
|
||||||
use gloo_utils::format::JsValueSerdeExt;
|
|
||||||
if JsValue::from_serde(&state) != JsValue::from_serde(&self.current_route()) {
|
|
||||||
// don't push the same state twice
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let w = window().expect("access to `window`");
|
|
||||||
let h = w.history().expect("`window` has access to `history`");
|
|
||||||
|
|
||||||
// update the scroll position before pushing the new state
|
|
||||||
update_scroll::<R>(&w, &h);
|
|
||||||
|
|
||||||
let path = self.full_path(&state);
|
|
||||||
|
|
||||||
let state = self.create_state(state);
|
|
||||||
|
|
||||||
self.handle_nav(push_state_and_url(&self.history, &state, path));
|
|
||||||
}
|
|
||||||
|
|
||||||
fn replace(&mut self, state: R) {
|
|
||||||
let path = match &self.prefix {
|
|
||||||
None => format!("{state}"),
|
|
||||||
Some(prefix) => format!("{prefix}{state}"),
|
|
||||||
};
|
|
||||||
|
|
||||||
let state = self.create_state(state);
|
|
||||||
|
|
||||||
self.handle_nav(replace_state_with_url(&self.history, &state, Some(&path)));
|
|
||||||
}
|
|
||||||
|
|
||||||
fn external(&mut self, url: String) -> bool {
|
|
||||||
self.navigate_external(url)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn updater(&mut self, callback: std::sync::Arc<dyn Fn() + Send + Sync>) {
|
|
||||||
let w = self.window.clone();
|
|
||||||
let h = self.history.clone();
|
|
||||||
let s = self.listener_animation_frame.clone();
|
|
||||||
let d = self.do_scroll_restoration;
|
|
||||||
|
|
||||||
self.listener_navigation = Some(EventListener::new(&self.window, "popstate", move |_| {
|
|
||||||
(*callback)();
|
|
||||||
if d {
|
|
||||||
let mut s = s.lock().expect("unpoisoned scroll mutex");
|
|
||||||
if let Some(current_state) = get_current::<WebHistoryState<R>>(&h) {
|
|
||||||
*s = Some(current_state.scroll.scroll_to(w.clone()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(feature = "serde"))]
|
|
||||||
impl<R: Routable> HistoryProvider<R> for WebHistory<R>
|
impl<R: Routable> HistoryProvider<R> for WebHistory<R>
|
||||||
where
|
where
|
||||||
<R as std::str::FromStr>::Err: std::fmt::Display,
|
<R as std::str::FromStr>::Err: std::fmt::Display,
|
||||||
|
|||||||
@@ -1,10 +1,7 @@
|
|||||||
use gloo::console::error;
|
use gloo::console::error;
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
use gloo_utils::format::JsValueSerdeExt;
|
|
||||||
use wasm_bindgen::JsValue;
|
use wasm_bindgen::JsValue;
|
||||||
use web_sys::History;
|
use web_sys::History;
|
||||||
|
|
||||||
#[cfg(not(feature = "serde"))]
|
|
||||||
pub(crate) fn replace_state_with_url(
|
pub(crate) fn replace_state_with_url(
|
||||||
history: &History,
|
history: &History,
|
||||||
value: &[f64; 2],
|
value: &[f64; 2],
|
||||||
@@ -17,18 +14,6 @@ pub(crate) fn replace_state_with_url(
|
|||||||
history.replace_state_with_url(&position, "", url)
|
history.replace_state_with_url(&position, "", url)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
pub(crate) fn replace_state_with_url<V: serde::Serialize>(
|
|
||||||
history: &History,
|
|
||||||
value: &V,
|
|
||||||
url: Option<&str>,
|
|
||||||
) -> Result<(), JsValue> {
|
|
||||||
let position = JsValue::from_serde(value).unwrap();
|
|
||||||
|
|
||||||
history.replace_state_with_url(&position, "", url)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(feature = "serde"))]
|
|
||||||
pub(crate) fn push_state_and_url(
|
pub(crate) fn push_state_and_url(
|
||||||
history: &History,
|
history: &History,
|
||||||
value: &[f64; 2],
|
value: &[f64; 2],
|
||||||
@@ -41,33 +26,6 @@ pub(crate) fn push_state_and_url(
|
|||||||
history.push_state_with_url(&position, "", Some(&url))
|
history.push_state_with_url(&position, "", Some(&url))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
pub(crate) fn push_state_and_url<V: serde::Serialize>(
|
|
||||||
history: &History,
|
|
||||||
value: &V,
|
|
||||||
url: String,
|
|
||||||
) -> Result<(), JsValue> {
|
|
||||||
let position = JsValue::from_serde(value).unwrap();
|
|
||||||
|
|
||||||
history.push_state_with_url(&position, "", Some(&url))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
pub(crate) fn get_current<V: serde::de::DeserializeOwned>(history: &History) -> Option<V> {
|
|
||||||
let state = history.state();
|
|
||||||
if let Err(err) = &state {
|
|
||||||
error!(err);
|
|
||||||
}
|
|
||||||
state.ok().and_then(|state| {
|
|
||||||
let deserialized = state.into_serde();
|
|
||||||
if let Err(err) = &deserialized {
|
|
||||||
error!(format!("{}", err));
|
|
||||||
}
|
|
||||||
deserialized.ok()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(feature = "serde"))]
|
|
||||||
pub(crate) fn get_current(history: &History) -> Option<[f64; 2]> {
|
pub(crate) fn get_current(history: &History) -> Option<[f64; 2]> {
|
||||||
use wasm_bindgen::JsCast;
|
use wasm_bindgen::JsCast;
|
||||||
|
|
||||||
|
|||||||
@@ -31,21 +31,6 @@ pub struct RouterConfig<R: Routable> {
|
|||||||
pub(crate) initial_route: Option<R>,
|
pub(crate) initial_route: Option<R>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
impl<R: Routable + Clone> Default for RouterConfig<R>
|
|
||||||
where
|
|
||||||
<R as std::str::FromStr>::Err: std::fmt::Display,
|
|
||||||
R: serde::Serialize + serde::de::DeserializeOwned,
|
|
||||||
{
|
|
||||||
fn default() -> Self {
|
|
||||||
Self {
|
|
||||||
failure_external_navigation: FailureExternalNavigation::<R>,
|
|
||||||
history: None,
|
|
||||||
on_update: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
macro_rules! default_history {
|
macro_rules! default_history {
|
||||||
($initial_route:ident) => {
|
($initial_route:ident) => {
|
||||||
{
|
{
|
||||||
@@ -83,24 +68,6 @@ macro_rules! default_history {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
impl<R: Routable + Clone> RouterConfig<R>
|
|
||||||
where
|
|
||||||
<R as std::str::FromStr>::Err: std::fmt::Display,
|
|
||||||
R: serde::Serialize + serde::de::DeserializeOwned,
|
|
||||||
{
|
|
||||||
pub(crate) fn get_history(self) -> Box<dyn HistoryProvider<R>> {
|
|
||||||
#[allow(unused)]
|
|
||||||
let initial_route = self.initial_route.clone().unwrap_or("/".parse().unwrap_or_else(|err|
|
|
||||||
panic!("index route does not exist:\n{}\n use MemoryHistory::with_initial_path or RouterConfig::initial_route to set a custom path", err)
|
|
||||||
));
|
|
||||||
self.history
|
|
||||||
.take()
|
|
||||||
.unwrap_or_else(|| default_history!(initial_route))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(feature = "serde"))]
|
|
||||||
impl<R: Routable + Clone> Default for RouterConfig<R>
|
impl<R: Routable + Clone> Default for RouterConfig<R>
|
||||||
where
|
where
|
||||||
<R as std::str::FromStr>::Err: std::fmt::Display,
|
<R as std::str::FromStr>::Err: std::fmt::Display,
|
||||||
|
|||||||
@@ -26,7 +26,6 @@ flume = { version = "0.11.0", default-features = false, features = ["async"] }
|
|||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
dioxus = { workspace = true }
|
dioxus = { workspace = true }
|
||||||
# dioxus-desktop = { workspace = true }
|
|
||||||
tokio = { version = "1", features = ["full"] }
|
tokio = { version = "1", features = ["full"] }
|
||||||
tracing-subscriber = "0.3.17"
|
tracing-subscriber = "0.3.17"
|
||||||
simple_logger = "4.2.0"
|
simple_logger = "4.2.0"
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
#![allow(non_snake_case)]
|
||||||
|
|
||||||
|
use dioxus::prelude::*;
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
launch(app);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn app() -> Element {
|
||||||
|
let mut vec = use_signal(|| vec![0]);
|
||||||
|
|
||||||
|
rsx! {
|
||||||
|
button {
|
||||||
|
onclick: move |_| {
|
||||||
|
let mut write = vec.write();
|
||||||
|
let len = write.len() as i32;
|
||||||
|
write.push(len);
|
||||||
|
},
|
||||||
|
"Create"
|
||||||
|
}
|
||||||
|
|
||||||
|
button {
|
||||||
|
onclick: move |_| {
|
||||||
|
vec.write().pop();
|
||||||
|
},
|
||||||
|
"Destroy"
|
||||||
|
}
|
||||||
|
|
||||||
|
for i in 0..vec.len() {
|
||||||
|
Child { count: vec.map(move |v| &v[i]) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[component]
|
||||||
|
fn Child(count: MappedSignal<i32>) -> Element {
|
||||||
|
use_memo({
|
||||||
|
to_owned![count];
|
||||||
|
move || {
|
||||||
|
let value = count.read();
|
||||||
|
println!("Child value: {value}");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
rsx! {
|
||||||
|
div {
|
||||||
|
"Child: {count}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,6 +13,7 @@ use dioxus_core::ScopeId;
|
|||||||
|
|
||||||
use generational_box::{GenerationalBox, Owner, Storage};
|
use generational_box::{GenerationalBox, Owner, Storage};
|
||||||
|
|
||||||
|
use crate::ReadableRef;
|
||||||
use crate::Writable;
|
use crate::Writable;
|
||||||
use crate::{ReactiveContext, Readable};
|
use crate::{ReactiveContext, Readable};
|
||||||
|
|
||||||
@@ -204,40 +205,30 @@ impl<T: 'static, S: Storage<T>> CopyValue<T, S> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: 'static, S: Storage<T>> Readable<T> for CopyValue<T, S> {
|
impl<T: 'static, S: Storage<T>> Readable for CopyValue<T, S> {
|
||||||
type Ref<R: ?Sized + 'static> = S::Ref<R>;
|
type Target = T;
|
||||||
|
type Storage = S;
|
||||||
|
|
||||||
fn map_ref<I, U: ?Sized, F: FnOnce(&I) -> &U>(ref_: Self::Ref<I>, f: F) -> Self::Ref<U> {
|
fn try_read(&self) -> Result<ReadableRef<Self>, generational_box::BorrowError> {
|
||||||
S::map(ref_, f)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn try_map_ref<I, U: ?Sized, F: FnOnce(&I) -> Option<&U>>(
|
|
||||||
ref_: Self::Ref<I>,
|
|
||||||
f: F,
|
|
||||||
) -> Option<Self::Ref<U>> {
|
|
||||||
S::try_map(ref_, f)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn try_read(&self) -> Result<S::Ref<T>, generational_box::BorrowError> {
|
|
||||||
self.value.try_read()
|
self.value.try_read()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn peek(&self) -> Self::Ref<T> {
|
fn peek(&self) -> ReadableRef<Self> {
|
||||||
self.value.read()
|
self.value.read()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: 'static, S: Storage<T>> Writable<T> for CopyValue<T, S> {
|
impl<T: 'static, S: Storage<T>> Writable for CopyValue<T, S> {
|
||||||
type Mut<R: ?Sized + 'static> = S::Mut<R>;
|
type Mut<R: ?Sized + 'static> = S::Mut<R>;
|
||||||
|
|
||||||
fn map_mut<I, U: ?Sized, F: FnOnce(&mut I) -> &mut U>(
|
fn map_mut<I: ?Sized, U: ?Sized, F: FnOnce(&mut I) -> &mut U>(
|
||||||
mut_: Self::Mut<I>,
|
mut_: Self::Mut<I>,
|
||||||
f: F,
|
f: F,
|
||||||
) -> Self::Mut<U> {
|
) -> Self::Mut<U> {
|
||||||
S::map_mut(mut_, f)
|
S::map_mut(mut_, f)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn try_map_mut<I, U: ?Sized, F: FnOnce(&mut I) -> Option<&mut U>>(
|
fn try_map_mut<I: ?Sized, U: ?Sized, F: FnOnce(&mut I) -> Option<&mut U>>(
|
||||||
mut_: Self::Mut<I>,
|
mut_: Self::Mut<I>,
|
||||||
f: F,
|
f: F,
|
||||||
) -> Option<Self::Mut<U>> {
|
) -> Option<Self::Mut<U>> {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use crate::read::Readable;
|
use crate::{read::Readable, ReadableRef};
|
||||||
use dioxus_core::prelude::{IntoAttributeValue, ScopeId};
|
use dioxus_core::prelude::{IntoAttributeValue, ScopeId};
|
||||||
use generational_box::{AnyStorage, UnsyncStorage};
|
use generational_box::UnsyncStorage;
|
||||||
use std::{mem::MaybeUninit, ops::Deref};
|
use std::{mem::MaybeUninit, ops::Deref};
|
||||||
|
|
||||||
use crate::{ReadOnlySignal, Signal};
|
use crate::{ReadOnlySignal, Signal};
|
||||||
@@ -51,27 +51,17 @@ impl<T: PartialEq + 'static> GlobalMemo<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: PartialEq + 'static> Readable<T> for GlobalMemo<T> {
|
impl<T: PartialEq + 'static> Readable for GlobalMemo<T> {
|
||||||
type Ref<R: ?Sized + 'static> = generational_box::GenerationalRef<std::cell::Ref<'static, R>>;
|
type Target = T;
|
||||||
|
type Storage = UnsyncStorage;
|
||||||
fn map_ref<I, U: ?Sized, F: FnOnce(&I) -> &U>(ref_: Self::Ref<I>, f: F) -> Self::Ref<U> {
|
|
||||||
<UnsyncStorage as AnyStorage>::map(ref_, f)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn try_map_ref<I, U: ?Sized, F: FnOnce(&I) -> Option<&U>>(
|
|
||||||
ref_: Self::Ref<I>,
|
|
||||||
f: F,
|
|
||||||
) -> Option<Self::Ref<U>> {
|
|
||||||
<UnsyncStorage as AnyStorage>::try_map(ref_, f)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[track_caller]
|
#[track_caller]
|
||||||
fn try_read(&self) -> Result<Self::Ref<T>, generational_box::BorrowError> {
|
fn try_read(&self) -> Result<ReadableRef<Self>, generational_box::BorrowError> {
|
||||||
self.signal().try_read()
|
self.signal().try_read()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[track_caller]
|
#[track_caller]
|
||||||
fn peek(&self) -> Self::Ref<T> {
|
fn peek(&self) -> ReadableRef<Self> {
|
||||||
self.signal().peek()
|
self.signal().peek()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
use crate::read::Readable;
|
|
||||||
use crate::write::Writable;
|
use crate::write::Writable;
|
||||||
use crate::Write;
|
use crate::Write;
|
||||||
|
use crate::{read::Readable, ReadableRef};
|
||||||
use dioxus_core::prelude::{IntoAttributeValue, ScopeId};
|
use dioxus_core::prelude::{IntoAttributeValue, ScopeId};
|
||||||
use generational_box::{AnyStorage, GenerationalRef, UnsyncStorage};
|
use generational_box::UnsyncStorage;
|
||||||
use std::{cell::Ref, mem::MaybeUninit, ops::Deref};
|
use std::{mem::MaybeUninit, ops::Deref};
|
||||||
|
|
||||||
use super::get_global_context;
|
use super::get_global_context;
|
||||||
use crate::{MappedSignal, Signal};
|
use crate::Signal;
|
||||||
|
|
||||||
/// A signal that can be accessed from anywhere in the application and created in a static
|
/// A signal that can be accessed from anywhere in the application and created in a static
|
||||||
pub struct GlobalSignal<T> {
|
pub struct GlobalSignal<T> {
|
||||||
@@ -60,56 +60,42 @@ impl<T: 'static> GlobalSignal<T> {
|
|||||||
self.signal().with_mut(f)
|
self.signal().with_mut(f)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Map the signal to a new type.
|
|
||||||
pub fn map<O>(
|
|
||||||
&self,
|
|
||||||
f: impl Fn(&T) -> &O + 'static,
|
|
||||||
) -> MappedSignal<GenerationalRef<Ref<'static, O>>> {
|
|
||||||
MappedSignal::new(self.signal(), f)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get the generational id of the signal.
|
/// Get the generational id of the signal.
|
||||||
pub fn id(&self) -> generational_box::GenerationalBoxId {
|
pub fn id(&self) -> generational_box::GenerationalBoxId {
|
||||||
self.signal().id()
|
self.signal().id()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: 'static> Readable<T> for GlobalSignal<T> {
|
impl<T: 'static> Readable for GlobalSignal<T> {
|
||||||
type Ref<R: ?Sized + 'static> = generational_box::GenerationalRef<std::cell::Ref<'static, R>>;
|
type Target = T;
|
||||||
|
type Storage = UnsyncStorage;
|
||||||
fn map_ref<I, U: ?Sized, F: FnOnce(&I) -> &U>(ref_: Self::Ref<I>, f: F) -> Self::Ref<U> {
|
|
||||||
<UnsyncStorage as AnyStorage>::map(ref_, f)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn try_map_ref<I, U: ?Sized, F: FnOnce(&I) -> Option<&U>>(
|
|
||||||
ref_: Self::Ref<I>,
|
|
||||||
f: F,
|
|
||||||
) -> Option<Self::Ref<U>> {
|
|
||||||
<UnsyncStorage as AnyStorage>::try_map(ref_, f)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[track_caller]
|
#[track_caller]
|
||||||
fn try_read(&self) -> Result<Self::Ref<T>, generational_box::BorrowError> {
|
fn try_read(&self) -> Result<ReadableRef<Self>, generational_box::BorrowError> {
|
||||||
self.signal().try_read()
|
self.signal().try_read()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[track_caller]
|
#[track_caller]
|
||||||
fn peek(&self) -> Self::Ref<T> {
|
fn peek(&self) -> ReadableRef<Self> {
|
||||||
self.signal().peek()
|
self.signal().peek()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: 'static> Writable<T> for GlobalSignal<T> {
|
impl<T: 'static> Writable for GlobalSignal<T> {
|
||||||
type Mut<R: ?Sized + 'static> = Write<R, UnsyncStorage>;
|
type Mut<R: ?Sized + 'static> = Write<R, UnsyncStorage>;
|
||||||
|
|
||||||
fn map_mut<I, U: ?Sized + 'static, F: FnOnce(&mut I) -> &mut U>(
|
fn map_mut<I: ?Sized, U: ?Sized + 'static, F: FnOnce(&mut I) -> &mut U>(
|
||||||
ref_: Self::Mut<I>,
|
ref_: Self::Mut<I>,
|
||||||
f: F,
|
f: F,
|
||||||
) -> Self::Mut<U> {
|
) -> Self::Mut<U> {
|
||||||
Write::map(ref_, f)
|
Write::map(ref_, f)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn try_map_mut<I: 'static, U: ?Sized + 'static, F: FnOnce(&mut I) -> Option<&mut U>>(
|
fn try_map_mut<
|
||||||
|
I: ?Sized + 'static,
|
||||||
|
U: ?Sized + 'static,
|
||||||
|
F: FnOnce(&mut I) -> Option<&mut U>,
|
||||||
|
>(
|
||||||
ref_: Self::Mut<I>,
|
ref_: Self::Mut<I>,
|
||||||
f: F,
|
f: F,
|
||||||
) -> Option<Self::Mut<U>> {
|
) -> Option<Self::Mut<U>> {
|
||||||
@@ -151,7 +137,7 @@ impl<T: Clone + 'static> Deref for GlobalSignal<T> {
|
|||||||
|
|
||||||
// Then move that value into the closure. We assume that the closure now has a in memory layout of Self.
|
// Then move that value into the closure. We assume that the closure now has a in memory layout of Self.
|
||||||
let uninit_closure = move || {
|
let uninit_closure = move || {
|
||||||
<GlobalSignal<T> as Readable<T>>::read(unsafe { &*uninit_callable.as_ptr() }).clone()
|
<GlobalSignal<T> as Readable>::read(unsafe { &*uninit_callable.as_ptr() }).clone()
|
||||||
};
|
};
|
||||||
|
|
||||||
// Check that the size of the closure is the same as the size of Self in case the compiler changed the layout of the closure.
|
// Check that the size of the closure is the same as the size of Self in case the compiler changed the layout of the closure.
|
||||||
|
|||||||
@@ -2,15 +2,15 @@ use crate::copy_value::CopyValue;
|
|||||||
use crate::read::Readable;
|
use crate::read::Readable;
|
||||||
use crate::signal::Signal;
|
use crate::signal::Signal;
|
||||||
use crate::write::Writable;
|
use crate::write::Writable;
|
||||||
use crate::{GlobalMemo, GlobalSignal, ReadOnlySignal, SignalData};
|
use crate::{GlobalMemo, GlobalSignal, MappedSignal, ReadOnlySignal, SignalData};
|
||||||
use generational_box::Storage;
|
use generational_box::{AnyStorage, Storage};
|
||||||
|
|
||||||
use std::{
|
use std::{
|
||||||
fmt::{Debug, Display},
|
fmt::{Debug, Display},
|
||||||
ops::{Add, Div, Mul, Sub},
|
ops::{Add, Div, Mul, Sub},
|
||||||
};
|
};
|
||||||
|
|
||||||
macro_rules! read_impls {
|
macro_rules! default_impl {
|
||||||
($ty:ident $(: $extra_bounds:path)? $(, $bound_ty:ident : $bound:path, $vec_bound_ty:ident : $vec_bound:path)?) => {
|
($ty:ident $(: $extra_bounds:path)? $(, $bound_ty:ident : $bound:path, $vec_bound_ty:ident : $vec_bound:path)?) => {
|
||||||
$(
|
$(
|
||||||
impl<T: Default + 'static, $bound_ty: $bound> Default for $ty<T, $bound_ty> {
|
impl<T: Default + 'static, $bound_ty: $bound> Default for $ty<T, $bound_ty> {
|
||||||
@@ -20,7 +20,11 @@ macro_rules! read_impls {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
)?
|
)?
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! read_impls {
|
||||||
|
($ty:ident $(: $extra_bounds:path)? $(, $bound_ty:ident : $bound:path, $vec_bound_ty:ident : $vec_bound:path)?) => {
|
||||||
impl<T: $($extra_bounds + )? Display + 'static $(,$bound_ty: $bound)?> Display for $ty<T $(, $bound_ty)?> {
|
impl<T: $($extra_bounds + )? Display + 'static $(,$bound_ty: $bound)?> Display for $ty<T $(, $bound_ty)?> {
|
||||||
#[track_caller]
|
#[track_caller]
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
@@ -113,6 +117,7 @@ macro_rules! write_impls {
|
|||||||
}
|
}
|
||||||
|
|
||||||
read_impls!(CopyValue, S: Storage<T>, S: Storage<Vec<T>>);
|
read_impls!(CopyValue, S: Storage<T>, S: Storage<Vec<T>>);
|
||||||
|
default_impl!(CopyValue, S: Storage<T>, S: Storage<Vec<T>>);
|
||||||
write_impls!(CopyValue, Storage<T>, Storage<Vec<T>>);
|
write_impls!(CopyValue, Storage<T>, Storage<Vec<T>>);
|
||||||
|
|
||||||
impl<T: 'static, S: Storage<T>> Clone for CopyValue<T, S> {
|
impl<T: 'static, S: Storage<T>> Clone for CopyValue<T, S> {
|
||||||
@@ -124,6 +129,7 @@ impl<T: 'static, S: Storage<T>> Clone for CopyValue<T, S> {
|
|||||||
impl<T: 'static, S: Storage<T>> Copy for CopyValue<T, S> {}
|
impl<T: 'static, S: Storage<T>> Copy for CopyValue<T, S> {}
|
||||||
|
|
||||||
read_impls!(Signal, S: Storage<SignalData<T>>, S: Storage<SignalData<Vec<T>>>);
|
read_impls!(Signal, S: Storage<SignalData<T>>, S: Storage<SignalData<Vec<T>>>);
|
||||||
|
default_impl!(Signal, S: Storage<SignalData<T>>, S: Storage<SignalData<Vec<T>>>);
|
||||||
write_impls!(Signal, Storage<SignalData<T>>, Storage<SignalData<Vec<T>>>);
|
write_impls!(Signal, Storage<SignalData<T>>, Storage<SignalData<Vec<T>>>);
|
||||||
|
|
||||||
impl<T: 'static, S: Storage<SignalData<T>>> Clone for Signal<T, S> {
|
impl<T: 'static, S: Storage<SignalData<T>>> Clone for Signal<T, S> {
|
||||||
@@ -139,6 +145,11 @@ read_impls!(
|
|||||||
S: Storage<SignalData<T>>,
|
S: Storage<SignalData<T>>,
|
||||||
S: Storage<SignalData<Vec<T>>>
|
S: Storage<SignalData<Vec<T>>>
|
||||||
);
|
);
|
||||||
|
default_impl!(
|
||||||
|
ReadOnlySignal,
|
||||||
|
S: Storage<SignalData<T>>,
|
||||||
|
S: Storage<SignalData<Vec<T>>>
|
||||||
|
);
|
||||||
|
|
||||||
impl<T: 'static, S: Storage<SignalData<T>>> Clone for ReadOnlySignal<T, S> {
|
impl<T: 'static, S: Storage<SignalData<T>>> Clone for ReadOnlySignal<T, S> {
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
@@ -149,5 +160,8 @@ impl<T: 'static, S: Storage<SignalData<T>>> Clone for ReadOnlySignal<T, S> {
|
|||||||
impl<T: 'static, S: Storage<SignalData<T>>> Copy for ReadOnlySignal<T, S> {}
|
impl<T: 'static, S: Storage<SignalData<T>>> Copy for ReadOnlySignal<T, S> {}
|
||||||
|
|
||||||
read_impls!(GlobalSignal);
|
read_impls!(GlobalSignal);
|
||||||
|
default_impl!(GlobalSignal);
|
||||||
|
|
||||||
read_impls!(GlobalMemo: PartialEq);
|
read_impls!(GlobalMemo: PartialEq);
|
||||||
|
|
||||||
|
read_impls!(MappedSignal, S: AnyStorage, S: AnyStorage);
|
||||||
+68
-96
@@ -1,114 +1,86 @@
|
|||||||
use crate::read::Readable;
|
use std::{ops::Deref, rc::Rc};
|
||||||
use crate::CopyValue;
|
|
||||||
use crate::Signal;
|
use crate::{read::Readable, ReadableRef};
|
||||||
use crate::SignalData;
|
use dioxus_core::prelude::*;
|
||||||
use dioxus_core::ScopeId;
|
use generational_box::{AnyStorage, UnsyncStorage};
|
||||||
use generational_box::Storage;
|
|
||||||
use std::fmt::Debug;
|
|
||||||
use std::fmt::Display;
|
|
||||||
|
|
||||||
/// A read only signal that has been mapped to a new type.
|
/// A read only signal that has been mapped to a new type.
|
||||||
pub struct MappedSignal<U: 'static + ?Sized> {
|
pub struct MappedSignal<O: ?Sized + 'static, S: AnyStorage = UnsyncStorage> {
|
||||||
origin_scope: ScopeId,
|
try_read: Rc<dyn Fn() -> Result<S::Ref<O>, generational_box::BorrowError> + 'static>,
|
||||||
mapping: CopyValue<Box<dyn Fn() -> U>>,
|
peek: Rc<dyn Fn() -> S::Ref<O> + 'static>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MappedSignal<()> {
|
impl<O: ?Sized, S: AnyStorage> Clone for MappedSignal<O, S> {
|
||||||
/// Create a new mapped signal.
|
|
||||||
pub fn new<T, S, U>(
|
|
||||||
signal: Signal<T, S>,
|
|
||||||
mapping: impl Fn(&T) -> &U + 'static,
|
|
||||||
) -> MappedSignal<S::Ref<U>>
|
|
||||||
where
|
|
||||||
S: Storage<SignalData<T>>,
|
|
||||||
U: ?Sized,
|
|
||||||
{
|
|
||||||
MappedSignal {
|
|
||||||
origin_scope: signal.origin_scope(),
|
|
||||||
mapping: CopyValue::new(Box::new(move || S::map(signal.read(), &mapping))),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<U> MappedSignal<U> {
|
|
||||||
/// Get the scope that the signal was created in.
|
|
||||||
pub fn origin_scope(&self) -> ScopeId {
|
|
||||||
self.origin_scope
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get the current value of the signal. This will subscribe the current scope to the signal.
|
|
||||||
pub fn read(&self) -> U {
|
|
||||||
(self.mapping.read())()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Run a closure with a reference to the signal's value.
|
|
||||||
pub fn with<O>(&self, f: impl FnOnce(U) -> O) -> O {
|
|
||||||
f(self.read())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<U: ?Sized + Clone> MappedSignal<U> {
|
|
||||||
/// Get the current value of the signal. This will subscribe the current scope to the signal.
|
|
||||||
pub fn value(&self) -> U {
|
|
||||||
self.read().clone()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<U: ?Sized> PartialEq for MappedSignal<U> {
|
|
||||||
fn eq(&self, other: &Self) -> bool {
|
|
||||||
self.mapping == other.mapping
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<U> std::clone::Clone for MappedSignal<U> {
|
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
*self
|
MappedSignal {
|
||||||
|
try_read: self.try_read.clone(),
|
||||||
|
peek: self.peek.clone(),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<U> Copy for MappedSignal<U> {}
|
impl<O, S> MappedSignal<O, S>
|
||||||
|
where
|
||||||
impl<U: Display> Display for MappedSignal<U> {
|
O: ?Sized,
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
S: AnyStorage,
|
||||||
self.with(|v| Display::fmt(&v, f))
|
{
|
||||||
|
/// Create a new mapped signal.
|
||||||
|
pub(crate) fn new(
|
||||||
|
try_read: Rc<dyn Fn() -> Result<S::Ref<O>, generational_box::BorrowError> + 'static>,
|
||||||
|
peek: Rc<dyn Fn() -> S::Ref<O> + 'static>,
|
||||||
|
) -> Self {
|
||||||
|
MappedSignal { try_read, peek }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<U: Debug> Debug for MappedSignal<U> {
|
impl<O, S> Readable for MappedSignal<O, S>
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
where
|
||||||
self.with(|v| Debug::fmt(&v, f))
|
O: ?Sized,
|
||||||
|
S: AnyStorage,
|
||||||
|
{
|
||||||
|
type Target = O;
|
||||||
|
type Storage = S;
|
||||||
|
|
||||||
|
fn try_read(&self) -> Result<ReadableRef<Self>, generational_box::BorrowError> {
|
||||||
|
(self.try_read)()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn peek(&self) -> ReadableRef<Self> {
|
||||||
|
(self.peek)()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> std::ops::Deref for MappedSignal<T> {
|
impl<O, S> IntoAttributeValue for MappedSignal<O, S>
|
||||||
type Target = dyn Fn() -> T;
|
where
|
||||||
|
O: Clone + IntoAttributeValue,
|
||||||
|
S: AnyStorage,
|
||||||
|
{
|
||||||
|
fn into_value(self) -> dioxus_core::AttributeValue {
|
||||||
|
self.with(|f| f.clone().into_value())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<O, S> PartialEq for MappedSignal<O, S>
|
||||||
|
where
|
||||||
|
O: ?Sized,
|
||||||
|
S: AnyStorage,
|
||||||
|
{
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
std::ptr::eq(&self.peek, &other.peek) && std::ptr::eq(&self.try_read, &other.try_read)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Allow calling a signal with signal() syntax
|
||||||
|
///
|
||||||
|
/// Currently only limited to copy types, though could probably specialize for string/arc/rc
|
||||||
|
impl<O, S> Deref for MappedSignal<O, S>
|
||||||
|
where
|
||||||
|
O: Clone,
|
||||||
|
S: AnyStorage + 'static,
|
||||||
|
{
|
||||||
|
type Target = dyn Fn() -> O;
|
||||||
|
|
||||||
fn deref(&self) -> &Self::Target {
|
fn deref(&self) -> &Self::Target {
|
||||||
// https://github.com/dtolnay/case-studies/tree/master/callable-types
|
Readable::deref_impl(self)
|
||||||
|
|
||||||
// First we create a closure that captures something with the Same in memory layout as Self (MaybeUninit<Self>).
|
|
||||||
let uninit_callable = std::mem::MaybeUninit::<Self>::uninit();
|
|
||||||
// Then move that value into the closure. We assume that the closure now has a in memory layout of Self.
|
|
||||||
let uninit_closure = move || Self::read(unsafe { &*uninit_callable.as_ptr() });
|
|
||||||
|
|
||||||
// Check that the size of the closure is the same as the size of Self in case the compiler changed the layout of the closure.
|
|
||||||
let size_of_closure = std::mem::size_of_val(&uninit_closure);
|
|
||||||
assert_eq!(size_of_closure, std::mem::size_of::<Self>());
|
|
||||||
|
|
||||||
// Then cast the lifetime of the closure to the lifetime of &self.
|
|
||||||
fn cast_lifetime<'a, T>(_a: &T, b: &'a T) -> &'a T {
|
|
||||||
b
|
|
||||||
}
|
|
||||||
let reference_to_closure = cast_lifetime(
|
|
||||||
{
|
|
||||||
// The real closure that we will never use.
|
|
||||||
&uninit_closure
|
|
||||||
},
|
|
||||||
// We transmute self into a reference to the closure. This is safe because we know that the closure has the same memory layout as Self so &Closure == &Self.
|
|
||||||
unsafe { std::mem::transmute(self) },
|
|
||||||
);
|
|
||||||
|
|
||||||
// Cast the closure to a trait object.
|
|
||||||
reference_to_closure as &Self::Target
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,66 +1,92 @@
|
|||||||
use std::{mem::MaybeUninit, ops::Deref};
|
use std::{mem::MaybeUninit, ops::Index, rc::Rc};
|
||||||
|
|
||||||
|
use generational_box::AnyStorage;
|
||||||
|
|
||||||
|
use crate::MappedSignal;
|
||||||
|
|
||||||
|
/// A reference to a value that can be read from.
|
||||||
|
#[allow(type_alias_bounds)]
|
||||||
|
pub type ReadableRef<T: Readable, O = <T as Readable>::Target> = <T::Storage as AnyStorage>::Ref<O>;
|
||||||
|
|
||||||
/// A trait for states that can be read from like [`crate::Signal`], [`crate::GlobalSignal`], or [`crate::ReadOnlySignal`]. You may choose to accept this trait as a parameter instead of the concrete type to allow for more flexibility in your API. For example, instead of creating two functions, one that accepts a [`crate::Signal`] and one that accepts a [`crate::GlobalSignal`], you can create one function that accepts a [`Readable`] type.
|
/// A trait for states that can be read from like [`crate::Signal`], [`crate::GlobalSignal`], or [`crate::ReadOnlySignal`]. You may choose to accept this trait as a parameter instead of the concrete type to allow for more flexibility in your API. For example, instead of creating two functions, one that accepts a [`crate::Signal`] and one that accepts a [`crate::GlobalSignal`], you can create one function that accepts a [`Readable`] type.
|
||||||
pub trait Readable<T: 'static = ()> {
|
pub trait Readable {
|
||||||
/// The type of the reference.
|
/// The target type of the reference.
|
||||||
type Ref<R: ?Sized + 'static>: Deref<Target = R>;
|
type Target: ?Sized + 'static;
|
||||||
|
|
||||||
/// Map the reference to a new type.
|
/// The type of the storage this readable uses.
|
||||||
fn map_ref<I, U: ?Sized, F: FnOnce(&I) -> &U>(ref_: Self::Ref<I>, f: F) -> Self::Ref<U>;
|
type Storage: AnyStorage;
|
||||||
|
|
||||||
/// Try to map the reference to a new type.
|
/// Map the readable type to a new type.
|
||||||
fn try_map_ref<I, U: ?Sized, F: FnOnce(&I) -> Option<&U>>(
|
fn map<O>(self, f: impl Fn(&Self::Target) -> &O + 'static) -> MappedSignal<O, Self::Storage>
|
||||||
ref_: Self::Ref<I>,
|
where
|
||||||
f: F,
|
Self: Clone + Sized + 'static,
|
||||||
) -> Option<Self::Ref<U>>;
|
{
|
||||||
|
let mapping = Rc::new(f);
|
||||||
/// Try to get the current value of the state. If this is a signal, this will subscribe the current scope to the signal. If the value has been dropped, this will panic.
|
let try_read = Rc::new({
|
||||||
fn try_read(&self) -> Result<Self::Ref<T>, generational_box::BorrowError>;
|
let self_ = self.clone();
|
||||||
|
let mapping = mapping.clone();
|
||||||
|
move || {
|
||||||
|
self_
|
||||||
|
.try_read()
|
||||||
|
.map(|ref_| <Self::Storage as AnyStorage>::map(ref_, |r| mapping(r)))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
as Rc<
|
||||||
|
dyn Fn() -> Result<ReadableRef<Self, O>, generational_box::BorrowError> + 'static,
|
||||||
|
>;
|
||||||
|
let peek = Rc::new(move || <Self::Storage as AnyStorage>::map(self.peek(), |r| mapping(r)))
|
||||||
|
as Rc<dyn Fn() -> ReadableRef<Self, O> + 'static>;
|
||||||
|
MappedSignal::new(try_read, peek)
|
||||||
|
}
|
||||||
|
|
||||||
/// Get the current value of the state. If this is a signal, this will subscribe the current scope to the signal. If the value has been dropped, this will panic.
|
/// Get the current value of the state. If this is a signal, this will subscribe the current scope to the signal. If the value has been dropped, this will panic.
|
||||||
#[track_caller]
|
#[track_caller]
|
||||||
fn read(&self) -> Self::Ref<T> {
|
fn read(&self) -> ReadableRef<Self> {
|
||||||
self.try_read().unwrap()
|
self.try_read().unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Try to get the current value of the state. If this is a signal, this will subscribe the current scope to the signal. If the value has been dropped, this will panic.
|
||||||
|
#[track_caller]
|
||||||
|
fn try_read(&self) -> Result<ReadableRef<Self>, generational_box::BorrowError>;
|
||||||
|
|
||||||
/// Get the current value of the state without subscribing to updates. If the value has been dropped, this will panic.
|
/// Get the current value of the state without subscribing to updates. If the value has been dropped, this will panic.
|
||||||
fn peek(&self) -> Self::Ref<T>;
|
fn peek(&self) -> ReadableRef<Self>;
|
||||||
|
|
||||||
/// Clone the inner value and return it. If the value has been dropped, this will panic.
|
/// Clone the inner value and return it. If the value has been dropped, this will panic.
|
||||||
#[track_caller]
|
#[track_caller]
|
||||||
fn cloned(&self) -> T
|
fn cloned(&self) -> Self::Target
|
||||||
where
|
where
|
||||||
T: Clone,
|
Self::Target: Clone,
|
||||||
{
|
{
|
||||||
self.read().clone()
|
self.read().clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Run a function with a reference to the value. If the value has been dropped, this will panic.
|
/// Run a function with a reference to the value. If the value has been dropped, this will panic.
|
||||||
#[track_caller]
|
#[track_caller]
|
||||||
fn with<O>(&self, f: impl FnOnce(&T) -> O) -> O {
|
fn with<O>(&self, f: impl FnOnce(&Self::Target) -> O) -> O {
|
||||||
f(&*self.read())
|
f(&*self.read())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Run a function with a reference to the value. If the value has been dropped, this will panic.
|
/// Run a function with a reference to the value. If the value has been dropped, this will panic.
|
||||||
#[track_caller]
|
#[track_caller]
|
||||||
fn with_peek<O>(&self, f: impl FnOnce(&T) -> O) -> O {
|
fn with_peek<O>(&self, f: impl FnOnce(&Self::Target) -> O) -> O {
|
||||||
f(&*self.peek())
|
f(&*self.peek())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Index into the inner value and return a reference to the result. If the value has been dropped or the index is invalid, this will panic.
|
/// Index into the inner value and return a reference to the result. If the value has been dropped or the index is invalid, this will panic.
|
||||||
#[track_caller]
|
#[track_caller]
|
||||||
fn index<I>(&self, index: I) -> Self::Ref<T::Output>
|
fn index<I>(&self, index: I) -> ReadableRef<Self, <Self::Target as std::ops::Index<I>>::Output>
|
||||||
where
|
where
|
||||||
T: std::ops::Index<I>,
|
Self::Target: std::ops::Index<I>,
|
||||||
{
|
{
|
||||||
Self::map_ref(self.read(), |v| v.index(index))
|
<Self::Storage as AnyStorage>::map(self.read(), |v| v.index(index))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
fn deref_impl<'a>(&self) -> &'a dyn Fn() -> T
|
fn deref_impl<'a>(&self) -> &'a dyn Fn() -> Self::Target
|
||||||
where
|
where
|
||||||
Self: Sized + 'a,
|
Self: Sized + 'a,
|
||||||
T: Clone,
|
Self::Target: Clone,
|
||||||
{
|
{
|
||||||
// https://github.com/dtolnay/case-studies/tree/master/callable-types
|
// https://github.com/dtolnay/case-studies/tree/master/callable-types
|
||||||
|
|
||||||
@@ -92,7 +118,7 @@ pub trait Readable<T: 'static = ()> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// An extension trait for Readable<Vec<T>> that provides some convenience methods.
|
/// An extension trait for Readable<Vec<T>> that provides some convenience methods.
|
||||||
pub trait ReadableVecExt<T: 'static>: Readable<Vec<T>> {
|
pub trait ReadableVecExt<T: 'static>: Readable<Target = Vec<T>> {
|
||||||
/// Returns the length of the inner vector.
|
/// Returns the length of the inner vector.
|
||||||
#[track_caller]
|
#[track_caller]
|
||||||
fn len(&self) -> usize {
|
fn len(&self) -> usize {
|
||||||
@@ -107,45 +133,43 @@ pub trait ReadableVecExt<T: 'static>: Readable<Vec<T>> {
|
|||||||
|
|
||||||
/// Get the first element of the inner vector.
|
/// Get the first element of the inner vector.
|
||||||
#[track_caller]
|
#[track_caller]
|
||||||
fn first(&self) -> Option<Self::Ref<T>> {
|
fn first(&self) -> Option<ReadableRef<Self, T>> {
|
||||||
Self::try_map_ref(self.read(), |v| v.first())
|
<Self::Storage as AnyStorage>::try_map(self.read(), |v| v.first())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the last element of the inner vector.
|
/// Get the last element of the inner vector.
|
||||||
#[track_caller]
|
#[track_caller]
|
||||||
fn last(&self) -> Option<Self::Ref<T>> {
|
fn last(&self) -> Option<ReadableRef<Self, T>> {
|
||||||
Self::try_map_ref(self.read(), |v| v.last())
|
<Self::Storage as AnyStorage>::try_map(self.read(), |v| v.last())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the element at the given index of the inner vector.
|
/// Get the element at the given index of the inner vector.
|
||||||
#[track_caller]
|
#[track_caller]
|
||||||
fn get(&self, index: usize) -> Option<Self::Ref<T>> {
|
fn get(&self, index: usize) -> Option<ReadableRef<Self, T>> {
|
||||||
Self::try_map_ref(self.read(), |v| v.get(index))
|
<Self::Storage as AnyStorage>::try_map(self.read(), |v| v.get(index))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get an iterator over the values of the inner vector.
|
/// Get an iterator over the values of the inner vector.
|
||||||
#[track_caller]
|
#[track_caller]
|
||||||
fn iter(&self) -> ReadableValueIterator<'_, T, Self>
|
fn iter(&self) -> ReadableValueIterator<'_, Self>
|
||||||
where
|
where
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
{
|
{
|
||||||
ReadableValueIterator {
|
ReadableValueIterator {
|
||||||
index: 0,
|
index: 0,
|
||||||
value: self,
|
value: self,
|
||||||
phantom: std::marker::PhantomData,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// An iterator over the values of a `Readable<Vec<T>>`.
|
/// An iterator over the values of a `Readable<Vec<T>>`.
|
||||||
pub struct ReadableValueIterator<'a, T, R> {
|
pub struct ReadableValueIterator<'a, R> {
|
||||||
index: usize,
|
index: usize,
|
||||||
value: &'a R,
|
value: &'a R,
|
||||||
phantom: std::marker::PhantomData<T>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a, T: 'static, R: Readable<Vec<T>>> Iterator for ReadableValueIterator<'a, T, R> {
|
impl<'a, T: 'static, R: Readable<Target = Vec<T>>> Iterator for ReadableValueIterator<'a, R> {
|
||||||
type Item = R::Ref<T>;
|
type Item = ReadableRef<R, T>;
|
||||||
|
|
||||||
fn next(&mut self) -> Option<Self::Item> {
|
fn next(&mut self) -> Option<Self::Item> {
|
||||||
let index = self.index;
|
let index = self.index;
|
||||||
@@ -157,12 +181,12 @@ impl<'a, T: 'static, R: Readable<Vec<T>>> Iterator for ReadableValueIterator<'a,
|
|||||||
impl<T, R> ReadableVecExt<T> for R
|
impl<T, R> ReadableVecExt<T> for R
|
||||||
where
|
where
|
||||||
T: 'static,
|
T: 'static,
|
||||||
R: Readable<Vec<T>>,
|
R: Readable<Target = Vec<T>>,
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
/// An extension trait for Readable<Option<T>> that provides some convenience methods.
|
/// An extension trait for Readable<Option<T>> that provides some convenience methods.
|
||||||
pub trait ReadableOptionExt<T: 'static>: Readable<Option<T>> {
|
pub trait ReadableOptionExt<T: 'static>: Readable<Target = Option<T>> {
|
||||||
/// Unwraps the inner value and clones it.
|
/// Unwraps the inner value and clones it.
|
||||||
#[track_caller]
|
#[track_caller]
|
||||||
fn unwrap(&self) -> T
|
fn unwrap(&self) -> T
|
||||||
@@ -174,14 +198,14 @@ pub trait ReadableOptionExt<T: 'static>: Readable<Option<T>> {
|
|||||||
|
|
||||||
/// Attempts to read the inner value of the Option.
|
/// Attempts to read the inner value of the Option.
|
||||||
#[track_caller]
|
#[track_caller]
|
||||||
fn as_ref(&self) -> Option<Self::Ref<T>> {
|
fn as_ref(&self) -> Option<ReadableRef<Self, T>> {
|
||||||
Self::try_map_ref(self.read(), |v| v.as_ref())
|
<Self::Storage as AnyStorage>::try_map(self.read(), |v| v.as_ref())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, R> ReadableOptionExt<T> for R
|
impl<T, R> ReadableOptionExt<T> for R
|
||||||
where
|
where
|
||||||
T: 'static,
|
T: 'static,
|
||||||
R: Readable<Option<T>>,
|
R: Readable<Target = Option<T>>,
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::{read::Readable, Signal, SignalData};
|
use crate::{read::Readable, ReadableRef, Signal, SignalData};
|
||||||
use std::ops::Deref;
|
use std::ops::Deref;
|
||||||
|
|
||||||
use dioxus_core::{prelude::IntoAttributeValue, ScopeId};
|
use dioxus_core::{prelude::IntoAttributeValue, ScopeId};
|
||||||
@@ -54,22 +54,12 @@ impl<T: 'static, S: Storage<SignalData<T>>> ReadOnlySignal<T, S> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, S: Storage<SignalData<T>>> Readable<T> for ReadOnlySignal<T, S> {
|
impl<T, S: Storage<SignalData<T>>> Readable for ReadOnlySignal<T, S> {
|
||||||
type Ref<R: ?Sized + 'static> = S::Ref<R>;
|
type Target = T;
|
||||||
|
type Storage = S;
|
||||||
fn map_ref<I, U: ?Sized, F: FnOnce(&I) -> &U>(ref_: Self::Ref<I>, f: F) -> Self::Ref<U> {
|
|
||||||
S::map(ref_, f)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn try_map_ref<I, U: ?Sized, F: FnOnce(&I) -> Option<&U>>(
|
|
||||||
ref_: Self::Ref<I>,
|
|
||||||
f: F,
|
|
||||||
) -> Option<Self::Ref<U>> {
|
|
||||||
S::try_map(ref_, f)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[track_caller]
|
#[track_caller]
|
||||||
fn try_read(&self) -> Result<Self::Ref<T>, generational_box::BorrowError> {
|
fn try_read(&self) -> Result<ReadableRef<Self>, generational_box::BorrowError> {
|
||||||
self.inner.try_read()
|
self.inner.try_read()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
read::Readable, write::Writable, CopyValue, GlobalMemo, GlobalSignal, MappedSignal,
|
read::Readable, write::Writable, CopyValue, GlobalMemo, GlobalSignal, ReactiveContext,
|
||||||
ReactiveContext, ReadOnlySignal,
|
ReadOnlySignal, ReadableRef,
|
||||||
};
|
};
|
||||||
use dioxus_core::{
|
use dioxus_core::{
|
||||||
prelude::{flush_sync, spawn, IntoAttributeValue},
|
prelude::{flush_sync, spawn, IntoAttributeValue},
|
||||||
@@ -187,33 +187,18 @@ impl<T: 'static, S: Storage<SignalData<T>>> Signal<T, S> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Map the signal to a new type.
|
|
||||||
pub fn map<O>(self, f: impl Fn(&T) -> &O + 'static) -> MappedSignal<S::Ref<O>> {
|
|
||||||
MappedSignal::new(self, f)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get the generational id of the signal.
|
/// Get the generational id of the signal.
|
||||||
pub fn id(&self) -> generational_box::GenerationalBoxId {
|
pub fn id(&self) -> generational_box::GenerationalBoxId {
|
||||||
self.inner.id()
|
self.inner.id()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, S: Storage<SignalData<T>>> Readable<T> for Signal<T, S> {
|
impl<T, S: Storage<SignalData<T>>> Readable for Signal<T, S> {
|
||||||
type Ref<R: ?Sized + 'static> = S::Ref<R>;
|
type Target = T;
|
||||||
|
type Storage = S;
|
||||||
fn map_ref<I, U: ?Sized, F: FnOnce(&I) -> &U>(ref_: Self::Ref<I>, f: F) -> Self::Ref<U> {
|
|
||||||
S::map(ref_, f)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn try_map_ref<I, U: ?Sized, F: FnOnce(&I) -> Option<&U>>(
|
|
||||||
ref_: Self::Ref<I>,
|
|
||||||
f: F,
|
|
||||||
) -> Option<Self::Ref<U>> {
|
|
||||||
S::try_map(ref_, f)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[track_caller]
|
#[track_caller]
|
||||||
fn try_read(&self) -> Result<S::Ref<T>, generational_box::BorrowError> {
|
fn try_read(&self) -> Result<ReadableRef<Self>, generational_box::BorrowError> {
|
||||||
let inner = self.inner.try_read()?;
|
let inner = self.inner.try_read()?;
|
||||||
|
|
||||||
let reactive_context = ReactiveContext::current();
|
let reactive_context = ReactiveContext::current();
|
||||||
@@ -225,23 +210,27 @@ impl<T, S: Storage<SignalData<T>>> Readable<T> for Signal<T, S> {
|
|||||||
/// Get the current value of the signal. **Unlike read, this will not subscribe the current scope to the signal which can cause parts of your UI to not update.**
|
/// Get the current value of the signal. **Unlike read, this will not subscribe the current scope to the signal which can cause parts of your UI to not update.**
|
||||||
///
|
///
|
||||||
/// If the signal has been dropped, this will panic.
|
/// If the signal has been dropped, this will panic.
|
||||||
fn peek(&self) -> S::Ref<T> {
|
fn peek(&self) -> ReadableRef<Self> {
|
||||||
let inner = self.inner.read();
|
let inner = self.inner.read();
|
||||||
S::map(inner, |v| &v.value)
|
S::map(inner, |v| &v.value)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: 'static, S: Storage<SignalData<T>>> Writable<T> for Signal<T, S> {
|
impl<T: 'static, S: Storage<SignalData<T>>> Writable for Signal<T, S> {
|
||||||
type Mut<R: ?Sized + 'static> = Write<R, S>;
|
type Mut<R: ?Sized + 'static> = Write<R, S>;
|
||||||
|
|
||||||
fn map_mut<I, U: ?Sized + 'static, F: FnOnce(&mut I) -> &mut U>(
|
fn map_mut<I: ?Sized, U: ?Sized + 'static, F: FnOnce(&mut I) -> &mut U>(
|
||||||
ref_: Self::Mut<I>,
|
ref_: Self::Mut<I>,
|
||||||
f: F,
|
f: F,
|
||||||
) -> Self::Mut<U> {
|
) -> Self::Mut<U> {
|
||||||
Write::map(ref_, f)
|
Write::map(ref_, f)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn try_map_mut<I: 'static, U: ?Sized + 'static, F: FnOnce(&mut I) -> Option<&mut U>>(
|
fn try_map_mut<
|
||||||
|
I: ?Sized + 'static,
|
||||||
|
U: ?Sized + 'static,
|
||||||
|
F: FnOnce(&mut I) -> Option<&mut U>,
|
||||||
|
>(
|
||||||
ref_: Self::Mut<I>,
|
ref_: Self::Mut<I>,
|
||||||
f: F,
|
f: F,
|
||||||
) -> Option<Self::Mut<U>> {
|
) -> Option<Self::Mut<U>> {
|
||||||
|
|||||||
@@ -1,40 +1,46 @@
|
|||||||
use std::ops::DerefMut;
|
use std::ops::DerefMut;
|
||||||
|
use std::ops::IndexMut;
|
||||||
|
|
||||||
use crate::read::Readable;
|
use crate::read::Readable;
|
||||||
|
|
||||||
/// A trait for states that can be read from like [`crate::Signal`], or [`crate::GlobalSignal`]. You may choose to accept this trait as a parameter instead of the concrete type to allow for more flexibility in your API. For example, instead of creating two functions, one that accepts a [`crate::Signal`] and one that accepts a [`crate::GlobalSignal`], you can create one function that accepts a [`Writable`] type.
|
/// A trait for states that can be read from like [`crate::Signal`], or [`crate::GlobalSignal`]. You may choose to accept this trait as a parameter instead of the concrete type to allow for more flexibility in your API. For example, instead of creating two functions, one that accepts a [`crate::Signal`] and one that accepts a [`crate::GlobalSignal`], you can create one function that accepts a [`Writable`] type.
|
||||||
pub trait Writable<T: 'static>: Readable<T> {
|
pub trait Writable: Readable {
|
||||||
/// The type of the reference.
|
/// The type of the reference.
|
||||||
type Mut<R: ?Sized + 'static>: DerefMut<Target = R>;
|
type Mut<R: ?Sized + 'static>: DerefMut<Target = R> + 'static;
|
||||||
|
|
||||||
/// Map the reference to a new type.
|
/// Map the reference to a new type.
|
||||||
fn map_mut<I, U: ?Sized, F: FnOnce(&mut I) -> &mut U>(ref_: Self::Mut<I>, f: F)
|
fn map_mut<I: ?Sized, U: ?Sized, F: FnOnce(&mut I) -> &mut U>(
|
||||||
-> Self::Mut<U>;
|
ref_: Self::Mut<I>,
|
||||||
|
f: F,
|
||||||
|
) -> Self::Mut<U>;
|
||||||
|
|
||||||
/// Try to map the reference to a new type.
|
/// Try to map the reference to a new type.
|
||||||
fn try_map_mut<I, U: ?Sized, F: FnOnce(&mut I) -> Option<&mut U>>(
|
fn try_map_mut<I: ?Sized, U: ?Sized, F: FnOnce(&mut I) -> Option<&mut U>>(
|
||||||
ref_: Self::Mut<I>,
|
ref_: Self::Mut<I>,
|
||||||
f: F,
|
f: F,
|
||||||
) -> Option<Self::Mut<U>>;
|
) -> Option<Self::Mut<U>>;
|
||||||
|
|
||||||
/// Get a mutable reference to the value. If the value has been dropped, this will panic.
|
/// Get a mutable reference to the value. If the value has been dropped, this will panic.
|
||||||
#[track_caller]
|
#[track_caller]
|
||||||
fn write(&mut self) -> Self::Mut<T> {
|
fn write(&mut self) -> Self::Mut<Self::Target> {
|
||||||
self.try_write().unwrap()
|
self.try_write().unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Try to get a mutable reference to the value. If the value has been dropped, this will panic.
|
/// Try to get a mutable reference to the value. If the value has been dropped, this will panic.
|
||||||
fn try_write(&self) -> Result<Self::Mut<T>, generational_box::BorrowMutError>;
|
fn try_write(&self) -> Result<Self::Mut<Self::Target>, generational_box::BorrowMutError>;
|
||||||
|
|
||||||
/// Run a function with a mutable reference to the value. If the value has been dropped, this will panic.
|
/// Run a function with a mutable reference to the value. If the value has been dropped, this will panic.
|
||||||
#[track_caller]
|
#[track_caller]
|
||||||
fn with_mut<O>(&mut self, f: impl FnOnce(&mut T) -> O) -> O {
|
fn with_mut<O>(&mut self, f: impl FnOnce(&mut Self::Target) -> O) -> O {
|
||||||
f(&mut *self.write())
|
f(&mut *self.write())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set the value of the signal. This will trigger an update on all subscribers.
|
/// Set the value of the signal. This will trigger an update on all subscribers.
|
||||||
#[track_caller]
|
#[track_caller]
|
||||||
fn set(&mut self, value: T) {
|
fn set(&mut self, value: Self::Target)
|
||||||
|
where
|
||||||
|
Self::Target: Sized,
|
||||||
|
{
|
||||||
*self.write() = value;
|
*self.write() = value;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -42,38 +48,41 @@ pub trait Writable<T: 'static>: Readable<T> {
|
|||||||
#[track_caller]
|
#[track_caller]
|
||||||
fn toggle(&mut self)
|
fn toggle(&mut self)
|
||||||
where
|
where
|
||||||
T: std::ops::Not<Output = T> + Clone,
|
Self::Target: std::ops::Not<Output = Self::Target> + Clone,
|
||||||
{
|
{
|
||||||
self.set(!self.cloned());
|
self.set(!self.cloned());
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Index into the inner value and return a reference to the result.
|
/// Index into the inner value and return a reference to the result.
|
||||||
#[track_caller]
|
#[track_caller]
|
||||||
fn index_mut<I>(&mut self, index: I) -> Self::Mut<T::Output>
|
fn index_mut<I>(&mut self, index: I) -> Self::Mut<<Self::Target as std::ops::Index<I>>::Output>
|
||||||
where
|
where
|
||||||
T: std::ops::IndexMut<I>,
|
Self::Target: std::ops::IndexMut<I>,
|
||||||
{
|
{
|
||||||
Self::map_mut(self.write(), |v| v.index_mut(index))
|
Self::map_mut(self.write(), |v| v.index_mut(index))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Takes the value out of the Signal, leaving a Default in its place.
|
/// Takes the value out of the Signal, leaving a Default in its place.
|
||||||
#[track_caller]
|
#[track_caller]
|
||||||
fn take(&mut self) -> T
|
fn take(&mut self) -> Self::Target
|
||||||
where
|
where
|
||||||
T: Default,
|
Self::Target: Default,
|
||||||
{
|
{
|
||||||
self.with_mut(|v| std::mem::take(v))
|
self.with_mut(std::mem::take)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Replace the value in the Signal, returning the old value.
|
/// Replace the value in the Signal, returning the old value.
|
||||||
#[track_caller]
|
#[track_caller]
|
||||||
fn replace(&mut self, value: T) -> T {
|
fn replace(&mut self, value: Self::Target) -> Self::Target
|
||||||
|
where
|
||||||
|
Self::Target: Sized,
|
||||||
|
{
|
||||||
self.with_mut(|v| std::mem::replace(v, value))
|
self.with_mut(|v| std::mem::replace(v, value))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// An extension trait for Writable<Option<T>> that provides some convenience methods.
|
/// An extension trait for Writable<Option<T>> that provides some convenience methods.
|
||||||
pub trait WritableOptionExt<T: 'static>: Writable<Option<T>> {
|
pub trait WritableOptionExt<T: 'static>: Writable<Target = Option<T>> {
|
||||||
/// Gets the value out of the Option, or inserts the given value if the Option is empty.
|
/// Gets the value out of the Option, or inserts the given value if the Option is empty.
|
||||||
fn get_or_insert(&mut self, default: T) -> Self::Mut<T> {
|
fn get_or_insert(&mut self, default: T) -> Self::Mut<T> {
|
||||||
self.get_or_insert_with(|| default)
|
self.get_or_insert_with(|| default)
|
||||||
@@ -101,12 +110,12 @@ pub trait WritableOptionExt<T: 'static>: Writable<Option<T>> {
|
|||||||
impl<T, W> WritableOptionExt<T> for W
|
impl<T, W> WritableOptionExt<T> for W
|
||||||
where
|
where
|
||||||
T: 'static,
|
T: 'static,
|
||||||
W: Writable<Option<T>>,
|
W: Writable<Target = Option<T>>,
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
/// An extension trait for Writable<Vec<T>> that provides some convenience methods.
|
/// An extension trait for Writable<Vec<T>> that provides some convenience methods.
|
||||||
pub trait WritableVecExt<T: 'static>: Writable<Vec<T>> {
|
pub trait WritableVecExt<T: 'static>: Writable<Target = Vec<T>> {
|
||||||
/// Pushes a new value to the end of the vector.
|
/// Pushes a new value to the end of the vector.
|
||||||
#[track_caller]
|
#[track_caller]
|
||||||
fn push(&mut self, value: T) {
|
fn push(&mut self, value: T) {
|
||||||
@@ -175,26 +184,24 @@ pub trait WritableVecExt<T: 'static>: Writable<Vec<T>> {
|
|||||||
|
|
||||||
/// Gets an iterator over the values of the vector.
|
/// Gets an iterator over the values of the vector.
|
||||||
#[track_caller]
|
#[track_caller]
|
||||||
fn iter_mut(&self) -> WritableValueIterator<T, Self>
|
fn iter_mut(&self) -> WritableValueIterator<Self>
|
||||||
where
|
where
|
||||||
Self: Sized + Clone,
|
Self: Sized + Clone,
|
||||||
{
|
{
|
||||||
WritableValueIterator {
|
WritableValueIterator {
|
||||||
index: 0,
|
index: 0,
|
||||||
value: self.clone(),
|
value: self.clone(),
|
||||||
phantom: std::marker::PhantomData,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// An iterator over the values of a `Writable<Vec<T>>`.
|
/// An iterator over the values of a `Writable<Vec<T>>`.
|
||||||
pub struct WritableValueIterator<T, R> {
|
pub struct WritableValueIterator<R> {
|
||||||
index: usize,
|
index: usize,
|
||||||
value: R,
|
value: R,
|
||||||
phantom: std::marker::PhantomData<T>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: 'static, R: Writable<Vec<T>>> Iterator for WritableValueIterator<T, R> {
|
impl<T: 'static, R: Writable<Target = Vec<T>>> Iterator for WritableValueIterator<R> {
|
||||||
type Item = R::Mut<T>;
|
type Item = R::Mut<T>;
|
||||||
|
|
||||||
fn next(&mut self) -> Option<Self::Item> {
|
fn next(&mut self) -> Option<Self::Item> {
|
||||||
@@ -207,6 +214,6 @@ impl<T: 'static, R: Writable<Vec<T>>> Iterator for WritableValueIterator<T, R> {
|
|||||||
impl<T, W> WritableVecExt<T> for W
|
impl<T, W> WritableVecExt<T> for W
|
||||||
where
|
where
|
||||||
T: 'static,
|
T: 'static,
|
||||||
W: Writable<Vec<T>>,
|
W: Writable<Target = Vec<T>>,
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
@@ -10,7 +10,7 @@ use dioxus_html::{
|
|||||||
};
|
};
|
||||||
use js_sys::Array;
|
use js_sys::Array;
|
||||||
use wasm_bindgen::{prelude::wasm_bindgen, JsCast, JsValue};
|
use wasm_bindgen::{prelude::wasm_bindgen, JsCast, JsValue};
|
||||||
use web_sys::{Document, Element, Event, MouseEvent};
|
use web_sys::{Document, DragEvent, Element, Event, MouseEvent};
|
||||||
|
|
||||||
pub(crate) struct WebEventConverter;
|
pub(crate) struct WebEventConverter;
|
||||||
|
|
||||||
@@ -49,10 +49,7 @@ impl HtmlEventConverter for WebEventConverter {
|
|||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
fn convert_drag_data(&self, event: &dioxus_html::PlatformEventData) -> dioxus_html::DragData {
|
fn convert_drag_data(&self, event: &dioxus_html::PlatformEventData) -> dioxus_html::DragData {
|
||||||
let event = downcast_event(event);
|
let event = downcast_event(event);
|
||||||
DragData::new(WebDragData::new(
|
DragData::new(WebDragData::new(event.raw.clone().unchecked_into()))
|
||||||
event.element.clone(),
|
|
||||||
event.raw.clone().unchecked_into(),
|
|
||||||
))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
@@ -462,13 +459,12 @@ impl HasFileData for WebFormData {
|
|||||||
}
|
}
|
||||||
|
|
||||||
struct WebDragData {
|
struct WebDragData {
|
||||||
element: Element,
|
|
||||||
raw: MouseEvent,
|
raw: MouseEvent,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WebDragData {
|
impl WebDragData {
|
||||||
fn new(element: Element, raw: MouseEvent) -> Self {
|
fn new(raw: MouseEvent) -> Self {
|
||||||
Self { element, raw }
|
Self { raw }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -529,16 +525,15 @@ impl HasFileData for WebDragData {
|
|||||||
#[cfg(not(feature = "file_engine"))]
|
#[cfg(not(feature = "file_engine"))]
|
||||||
let files = None;
|
let files = None;
|
||||||
#[cfg(feature = "file_engine")]
|
#[cfg(feature = "file_engine")]
|
||||||
let files = self
|
let files = self.raw.dyn_ref::<DragEvent>().and_then(|drag_event| {
|
||||||
.element
|
drag_event.data_transfer().and_then(|dt| {
|
||||||
.dyn_ref()
|
dt.files().and_then(|files| {
|
||||||
.and_then(|input: &web_sys::HtmlInputElement| {
|
|
||||||
input.files().and_then(|files| {
|
|
||||||
#[allow(clippy::arc_with_non_send_sync)]
|
#[allow(clippy::arc_with_non_send_sync)]
|
||||||
crate::file_engine::WebFileEngine::new(files).map(|f| {
|
crate::file_engine::WebFileEngine::new(files).map(|f| {
|
||||||
std::sync::Arc::new(f) as std::sync::Arc<dyn dioxus_html::FileEngine>
|
std::sync::Arc::new(f) as std::sync::Arc<dyn dioxus_html::FileEngine>
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
files
|
files
|
||||||
|
|||||||
+12
-11
@@ -61,10 +61,7 @@ pub use crate::cfg::Config;
|
|||||||
#[cfg(feature = "file_engine")]
|
#[cfg(feature = "file_engine")]
|
||||||
pub use crate::file_engine::WebFileEngineExt;
|
pub use crate::file_engine::WebFileEngineExt;
|
||||||
use dioxus_core::VirtualDom;
|
use dioxus_core::VirtualDom;
|
||||||
use futures_util::{
|
use futures_util::{pin_mut, select, FutureExt, StreamExt};
|
||||||
future::{select, Either},
|
|
||||||
pin_mut, FutureExt, StreamExt,
|
|
||||||
};
|
|
||||||
|
|
||||||
mod cfg;
|
mod cfg;
|
||||||
mod dom;
|
mod dom;
|
||||||
@@ -159,17 +156,21 @@ pub async fn run(virtual_dom: VirtualDom, web_config: Config) {
|
|||||||
let (mut res, template) = {
|
let (mut res, template) = {
|
||||||
let work = dom.wait_for_work().fuse();
|
let work = dom.wait_for_work().fuse();
|
||||||
pin_mut!(work);
|
pin_mut!(work);
|
||||||
|
let mut rx_next = rx.select_next_some();
|
||||||
|
|
||||||
#[cfg(all(feature = "hot_reload", debug_assertions))]
|
#[cfg(all(feature = "hot_reload", debug_assertions))]
|
||||||
match select(work, select(hotreload_rx.next(), rx.next())).await {
|
{
|
||||||
Either::Left((_, _)) => (None, None),
|
let mut hot_reload_next = hotreload_rx.select_next_some();
|
||||||
Either::Right((Either::Left((new_template, _)), _)) => (None, new_template),
|
select! {
|
||||||
Either::Right((Either::Right((evt, _)), _)) => (evt, None),
|
_ = work => (None, None),
|
||||||
|
new_template = hot_reload_next => (None, Some(new_template)),
|
||||||
|
evt = rx_next => (Some(evt), None),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
#[cfg(not(all(feature = "hot_reload", debug_assertions)))]
|
#[cfg(not(all(feature = "hot_reload", debug_assertions)))]
|
||||||
match select(work, rx.next()).await {
|
select! {
|
||||||
Either::Left((_, _)) => (None, None),
|
_ = work => (None, None),
|
||||||
Either::Right((evt, _)) => (evt, None),
|
evt = rx_next => (Some(evt), None),
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user