Merge branch 'master' into feat/inline-attributes-fmt

This commit is contained in:
Jonathan Kelley committed 2024-01-08 20:00:14 -08:00
commit 2876a7deb2
285 files changed
+26437 -5759

No files matched your search

+57 -27
View File
@@ -49,6 +49,7 @@ impl Writer<'_> {
attributes,
children,
brace,
..
} = el;
/*
@@ -165,7 +166,7 @@ impl Writer<'_> {
fn write_attributes(
&mut self,
attributes: &[ElementAttrNamed],
attributes: &[AttributeType],
key: &Option<IfmtInput>,
sameline: bool,
) -> Result {
@@ -187,7 +188,7 @@ impl Writer<'_> {
while let Some(attr) = attr_iter.next() {
self.out.indent_level += 1;
if !sameline {
self.write_comments(attr.attr.start())?;
self.write_comments(attr.start())?;
}
self.out.indent_level -= 1;
@@ -209,12 +210,34 @@ impl Writer<'_> {
Ok(())
}
fn write_attribute(&mut self, attr: &ElementAttrNamed) -> Result {
match &attr.attr {
ElementAttr::AttrText { name, value } => {
write!(self.out, "{name}: {value}", value = ifmt_to_string(value))?;
fn write_attribute_name(&mut self, attr: &ElementAttrName) -> Result {
match attr {
ElementAttrName::BuiltIn(name) => {
write!(self.out, "{}", name)?;
}
ElementAttr::AttrExpression { name, value } => {
ElementAttrName::Custom(name) => {
write!(self.out, "{}", name.to_token_stream())?;
}
}
Ok(())
}
fn write_attribute_value(&mut self, value: &ElementAttrValue) -> Result {
match value {
ElementAttrValue::AttrOptionalExpr { condition, value } => {
write!(
self.out,
"if {condition} {{ ",
condition = prettyplease::unparse_expr(condition),
)?;
self.write_attribute_value(value)?;
write!(self.out, " }}")?;
}
ElementAttrValue::AttrLiteral(value) => {
write!(self.out, "{value}", value = ifmt_to_string(value))?;
}
ElementAttrValue::AttrExpr(value) => {
let out = prettyplease::unparse_expr(value);
let mut lines = out.split('\n').peekable();
let first = lines.next().unwrap();
@@ -222,9 +245,9 @@ impl Writer<'_> {
// a one-liner for whatever reason
// Does not need a new line
if lines.peek().is_none() {
write!(self.out, "{name}: {first}")?;
write!(self.out, "{first}")?;
} else {
writeln!(self.out, "{name}: {first}")?;
writeln!(self.out, "{first}")?;
while let Some(line) = lines.next() {
self.out.indented_tab()?;
@@ -237,22 +260,7 @@ impl Writer<'_> {
}
}
}
ElementAttr::CustomAttrText { name, value } => {
write!(
self.out,
"{name}: {value}",
name = name.to_token_stream(),
value = ifmt_to_string(value)
)?;
}
ElementAttr::CustomAttrExpression { name, value } => {
let out = prettyplease::unparse_expr(value);
write!(self.out, "{}: {}", name.to_token_stream(), out)?;
}
ElementAttr::EventTokens { name, tokens } => {
ElementAttrValue::EventTokens(tokens) => {
let out = self.retrieve_formatted_expr(tokens).to_string();
let mut lines = out.split('\n').peekable();
let first = lines.next().unwrap();
@@ -260,9 +268,9 @@ impl Writer<'_> {
// a one-liner for whatever reason
// Does not need a new line
if lines.peek().is_none() {
write!(self.out, "{name}: {first}")?;
write!(self.out, "{first}")?;
} else {
writeln!(self.out, "{name}: {first}")?;
writeln!(self.out, "{first}")?;
while let Some(line) = lines.next() {
self.out.indented_tab()?;
@@ -280,6 +288,28 @@ impl Writer<'_> {
Ok(())
}
fn write_attribute(&mut self, attr: &AttributeType) -> Result {
match attr {
AttributeType::Named(attr) => self.write_named_attribute(attr),
AttributeType::Spread(attr) => self.write_spread_attribute(attr),
}
}
fn write_named_attribute(&mut self, attr: &ElementAttrNamed) -> Result {
self.write_attribute_name(&attr.attr.name)?;
write!(self.out, ": ")?;
self.write_attribute_value(&attr.attr.value)?;
Ok(())
}
fn write_spread_attribute(&mut self, attr: &Expr) -> Result {
write!(self.out, "..")?;
write!(self.out, "{}", prettyplease::unparse_expr(attr))?;
Ok(())
}
// make sure the comments are actually relevant to this element.
// test by making sure this element is the primary element on this line
pub fn current_span_is_primary(&self, location: Span) -> bool {
+54 -36
View File
@@ -1,4 +1,4 @@
use dioxus_rsx::{BodyNode, ElementAttr, ElementAttrNamed, ForLoop};
use dioxus_rsx::{AttributeType, BodyNode, ElementAttrValue, ForLoop};
use proc_macro2::{LineColumn, Span};
use quote::ToTokens;
use std::{
@@ -132,12 +132,45 @@ impl<'a> Writer<'a> {
Ok(())
}
pub(crate) fn is_short_attrs(&mut self, attributes: &[ElementAttrNamed]) -> usize {
pub(crate) fn attr_value_len(&mut self, value: &ElementAttrValue) -> usize {
match value {
ElementAttrValue::AttrOptionalExpr { condition, value } => {
let condition_len = self.retrieve_formatted_expr(condition).len();
let value_len = self.attr_value_len(value);
condition_len + value_len + 6
}
ElementAttrValue::AttrLiteral(lit) => ifmt_to_string(lit).len(),
ElementAttrValue::AttrExpr(expr) => expr.span().line_length(),
ElementAttrValue::EventTokens(tokens) => {
let location = Location::new(tokens.span().start());
let len = if let std::collections::hash_map::Entry::Vacant(e) =
self.cached_formats.entry(location)
{
let formatted = prettyplease::unparse_expr(tokens);
let len = if formatted.contains('\n') {
10000
} else {
formatted.len()
};
e.insert(formatted);
len
} else {
self.cached_formats[&location].len()
};
len
}
}
}
pub(crate) fn is_short_attrs(&mut self, attributes: &[AttributeType]) -> usize {
let mut total = 0;
for attr in attributes {
if self.current_span_is_primary(attr.attr.start()) {
'line: for line in self.src[..attr.attr.start().start().line - 1].iter().rev() {
if self.current_span_is_primary(attr.start()) {
'line: for line in self.src[..attr.start().start().line - 1].iter().rev() {
match (line.trim().starts_with("//"), line.is_empty()) {
(true, _) => return 100000,
(_, true) => continue 'line,
@@ -146,40 +179,25 @@ impl<'a> Writer<'a> {
}
}
total += match &attr.attr {
ElementAttr::AttrText { value, name } => {
ifmt_to_string(value).len() + name.span().line_length() + 6
}
ElementAttr::AttrExpression { name, value } => {
value.span().line_length() + name.span().line_length() + 6
}
ElementAttr::CustomAttrText { value, name } => {
ifmt_to_string(value).len() + name.to_token_stream().to_string().len() + 6
}
ElementAttr::CustomAttrExpression { name, value } => {
name.to_token_stream().to_string().len() + value.span().line_length() + 6
}
ElementAttr::EventTokens { tokens, name } => {
let location = Location::new(tokens.span().start());
let len = if let std::collections::hash_map::Entry::Vacant(e) =
self.cached_formats.entry(location)
{
let formatted = prettyplease::unparse_expr(tokens);
let len = if formatted.contains('\n') {
10000
} else {
formatted.len()
};
e.insert(formatted);
len
} else {
self.cached_formats[&location].len()
match attr {
AttributeType::Named(attr) => {
let name_len = match &attr.attr.name {
dioxus_rsx::ElementAttrName::BuiltIn(name) => {
let name = name.to_string();
name.len()
}
dioxus_rsx::ElementAttrName::Custom(name) => name.value().len() + 2,
};
len + name.span().line_length() + 6
total += name_len;
total += self.attr_value_len(&attr.attr.value);
}
AttributeType::Spread(expr) => {
let expr_len = self.retrieve_formatted_expr(expr).len();
total += expr_len + 3;
}
};
total += 6;
}
total
@@ -218,7 +236,7 @@ impl<'a> Writer<'a> {
}
}
trait SpanLength {
pub(crate) trait SpanLength {
fn line_length(&self) -> usize;
}
impl SpanLength for Span {
+1 -1
View File
@@ -33,7 +33,7 @@ rsx! {
}
// No children, minimal props
img { class: "mb-6 mx-auto h-24", src: "artemis-assets/images/friends.png", alt: "" }
img { class: "mb-6 mx-auto h-24", src: "artemis-assets/images/friends.png" }
// One level compression
div {
+4
View File
@@ -0,0 +1,4 @@
/target
Cargo.lock
.DS_Store
.idea/
+26
View File
@@ -0,0 +1,26 @@
[package]
name = "dioxus-cli-config"
version = "0.4.1"
authors = ["Jonathan Kelley"]
edition = "2021"
description = "Configuration for the Dioxus CLI"
repository = "https://github.com/DioxusLabs/dioxus/"
license = "MIT OR Apache-2.0"
keywords = ["react", "gui", "cli", "dioxus", "wasm"]
[dependencies]
clap = { version = "4.2", features = ["derive"], optional = true }
serde = { version = "1.0.136", features = ["derive"] }
serde_json = "1.0.79"
toml = { version = "0.5.8", optional = true }
cargo_toml = { version = "0.16.0", optional = true }
once_cell = "1.18.0"
tracing.workspace = true
# bundling
tauri-bundler = { version = "=1.4.0", features = ["native-tls-vendored"], optional = true }
tauri-utils = { version = "=1.5.*", optional = true }
[features]
default = []
cli = ["tauri-bundler", "tauri-utils", "clap", "toml", "cargo_toml"]
+5
View File
@@ -0,0 +1,5 @@
<div style="text-align: center">
<h1>📦✨ Dioxus CLI Configuration</h1>
</div>
The **dioxus-cli-config** contains the configuration for the **dioxus-cli**.
+260
View File
@@ -0,0 +1,260 @@
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct BundleConfig {
pub identifier: Option<String>,
pub publisher: Option<String>,
pub icon: Option<Vec<String>>,
pub resources: Option<Vec<String>>,
pub copyright: Option<String>,
pub category: Option<String>,
pub short_description: Option<String>,
pub long_description: Option<String>,
pub external_bin: Option<Vec<String>>,
pub deb: Option<DebianSettings>,
pub macos: Option<MacOsSettings>,
pub windows: Option<WindowsSettings>,
}
#[cfg(feature = "cli")]
impl From<BundleConfig> for tauri_bundler::BundleSettings {
fn from(val: BundleConfig) -> Self {
tauri_bundler::BundleSettings {
identifier: val.identifier,
publisher: val.publisher,
icon: val.icon,
resources: val.resources,
copyright: val.copyright,
category: val.category.and_then(|c| c.parse().ok()),
short_description: val.short_description,
long_description: val.long_description,
external_bin: val.external_bin,
deb: val.deb.map(Into::into).unwrap_or_default(),
macos: val.macos.map(Into::into).unwrap_or_default(),
windows: val.windows.map(Into::into).unwrap_or_default(),
..Default::default()
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct DebianSettings {
pub depends: Option<Vec<String>>,
pub files: HashMap<PathBuf, PathBuf>,
pub nsis: Option<NsisSettings>,
}
#[cfg(feature = "cli")]
impl From<DebianSettings> for tauri_bundler::DebianSettings {
fn from(val: DebianSettings) -> Self {
tauri_bundler::DebianSettings {
depends: val.depends,
files: val.files,
desktop_template: None,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct WixSettings {
pub language: Vec<(String, Option<PathBuf>)>,
pub template: Option<PathBuf>,
pub fragment_paths: Vec<PathBuf>,
pub component_group_refs: Vec<String>,
pub component_refs: Vec<String>,
pub feature_group_refs: Vec<String>,
pub feature_refs: Vec<String>,
pub merge_refs: Vec<String>,
pub skip_webview_install: bool,
pub license: Option<PathBuf>,
pub enable_elevated_update_task: bool,
pub banner_path: Option<PathBuf>,
pub dialog_image_path: Option<PathBuf>,
pub fips_compliant: bool,
}
#[cfg(feature = "cli")]
impl From<WixSettings> for tauri_bundler::WixSettings {
fn from(val: WixSettings) -> Self {
tauri_bundler::WixSettings {
language: tauri_bundler::bundle::WixLanguage({
let mut languages: Vec<_> = val
.language
.iter()
.map(|l| {
(
l.0.clone(),
tauri_bundler::bundle::WixLanguageConfig {
locale_path: l.1.clone(),
},
)
})
.collect();
if languages.is_empty() {
languages.push(("en-US".into(), Default::default()));
}
languages
}),
template: val.template,
fragment_paths: val.fragment_paths,
component_group_refs: val.component_group_refs,
component_refs: val.component_refs,
feature_group_refs: val.feature_group_refs,
feature_refs: val.feature_refs,
merge_refs: val.merge_refs,
skip_webview_install: val.skip_webview_install,
license: val.license,
enable_elevated_update_task: val.enable_elevated_update_task,
banner_path: val.banner_path,
dialog_image_path: val.dialog_image_path,
fips_compliant: val.fips_compliant,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct MacOsSettings {
pub frameworks: Option<Vec<String>>,
pub minimum_system_version: Option<String>,
pub license: Option<String>,
pub exception_domain: Option<String>,
pub signing_identity: Option<String>,
pub provider_short_name: Option<String>,
pub entitlements: Option<String>,
pub info_plist_path: Option<PathBuf>,
}
#[cfg(feature = "cli")]
impl From<MacOsSettings> for tauri_bundler::MacOsSettings {
fn from(val: MacOsSettings) -> Self {
tauri_bundler::MacOsSettings {
frameworks: val.frameworks,
minimum_system_version: val.minimum_system_version,
license: val.license,
exception_domain: val.exception_domain,
signing_identity: val.signing_identity,
provider_short_name: val.provider_short_name,
entitlements: val.entitlements,
info_plist_path: val.info_plist_path,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WindowsSettings {
pub digest_algorithm: Option<String>,
pub certificate_thumbprint: Option<String>,
pub timestamp_url: Option<String>,
pub tsp: bool,
pub wix: Option<WixSettings>,
pub icon_path: Option<PathBuf>,
pub webview_install_mode: WebviewInstallMode,
pub webview_fixed_runtime_path: Option<PathBuf>,
pub allow_downgrades: bool,
pub nsis: Option<NsisSettings>,
}
#[cfg(feature = "cli")]
impl From<WindowsSettings> for tauri_bundler::WindowsSettings {
fn from(val: WindowsSettings) -> Self {
tauri_bundler::WindowsSettings {
digest_algorithm: val.digest_algorithm,
certificate_thumbprint: val.certificate_thumbprint,
timestamp_url: val.timestamp_url,
tsp: val.tsp,
wix: val.wix.map(Into::into),
icon_path: val.icon_path.unwrap_or("icons/icon.ico".into()),
webview_install_mode: val.webview_install_mode.into(),
webview_fixed_runtime_path: val.webview_fixed_runtime_path,
allow_downgrades: val.allow_downgrades,
nsis: val.nsis.map(Into::into),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NsisSettings {
pub template: Option<PathBuf>,
pub license: Option<PathBuf>,
pub header_image: Option<PathBuf>,
pub sidebar_image: Option<PathBuf>,
pub installer_icon: Option<PathBuf>,
pub install_mode: NSISInstallerMode,
pub languages: Option<Vec<String>>,
pub custom_language_files: Option<HashMap<String, PathBuf>>,
pub display_language_selector: bool,
}
#[cfg(feature = "cli")]
impl From<NsisSettings> for tauri_bundler::NsisSettings {
fn from(val: NsisSettings) -> Self {
tauri_bundler::NsisSettings {
license: val.license,
header_image: val.header_image,
sidebar_image: val.sidebar_image,
installer_icon: val.installer_icon,
install_mode: val.install_mode.into(),
languages: val.languages,
display_language_selector: val.display_language_selector,
custom_language_files: None,
template: None,
compression: None,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum NSISInstallerMode {
CurrentUser,
PerMachine,
Both,
}
#[cfg(feature = "cli")]
impl From<NSISInstallerMode> for tauri_utils::config::NSISInstallerMode {
fn from(val: NSISInstallerMode) -> Self {
match val {
NSISInstallerMode::CurrentUser => tauri_utils::config::NSISInstallerMode::CurrentUser,
NSISInstallerMode::PerMachine => tauri_utils::config::NSISInstallerMode::PerMachine,
NSISInstallerMode::Both => tauri_utils::config::NSISInstallerMode::Both,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum WebviewInstallMode {
Skip,
DownloadBootstrapper { silent: bool },
EmbedBootstrapper { silent: bool },
OfflineInstaller { silent: bool },
FixedRuntime { path: PathBuf },
}
#[cfg(feature = "cli")]
impl WebviewInstallMode {
fn into(self) -> tauri_utils::config::WebviewInstallMode {
match self {
Self::Skip => tauri_utils::config::WebviewInstallMode::Skip,
Self::DownloadBootstrapper { silent } => {
tauri_utils::config::WebviewInstallMode::DownloadBootstrapper { silent }
}
Self::EmbedBootstrapper { silent } => {
tauri_utils::config::WebviewInstallMode::EmbedBootstrapper { silent }
}
Self::OfflineInstaller { silent } => {
tauri_utils::config::WebviewInstallMode::OfflineInstaller { silent }
}
Self::FixedRuntime { path } => {
tauri_utils::config::WebviewInstallMode::FixedRuntime { path }
}
}
}
}
impl Default for WebviewInstallMode {
fn default() -> Self {
Self::OfflineInstaller { silent: false }
}
}
@@ -1,12 +1,33 @@
//! Utilities for working with cargo and rust files
use crate::error::{Error, Result};
use std::error::Error;
use std::{
env, fs,
env,
fmt::{Display, Formatter},
fs,
path::{Path, PathBuf},
process::Command,
str,
};
#[derive(Debug, Clone)]
pub struct CargoError {
msg: String,
}
impl CargoError {
pub fn new(msg: String) -> Self {
Self { msg }
}
}
impl Display for CargoError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "CargoError: {}", self.msg)
}
}
impl Error for CargoError {}
/// How many parent folders are searched for a `Cargo.toml`
const MAX_ANCESTORS: u32 = 10;
@@ -19,7 +40,7 @@ pub struct Metadata {
/// Returns the root of the crate that the command is run from
///
/// If the command is run from the workspace root, this will return the top-level Cargo.toml
pub fn crate_root() -> Result<PathBuf> {
pub fn crate_root() -> Result<PathBuf, CargoError> {
// From the current directory we work our way up, looking for `Cargo.toml`
env::current_dir()
.ok()
@@ -35,7 +56,7 @@ pub fn crate_root() -> Result<PathBuf> {
None
})
.ok_or_else(|| {
Error::CargoError("Failed to find directory containing Cargo.toml".to_string())
CargoError::new("Failed to find directory containing Cargo.toml".to_string())
})
}
@@ -53,11 +74,11 @@ fn contains_manifest(path: &Path) -> bool {
impl Metadata {
/// Returns the struct filled from `cargo metadata` output
/// TODO @Jon, find a different way that doesn't rely on the cargo metadata command (it's slow)
pub fn get() -> Result<Self> {
pub fn get() -> Result<Self, CargoError> {
let output = Command::new("cargo")
.args(["metadata"])
.output()
.map_err(|_| Error::CargoError("Manifset".to_string()))?;
.map_err(|_| CargoError::new("Manifset".to_string()))?;
if !output.status.success() {
let mut msg = str::from_utf8(&output.stderr).unwrap().trim();
@@ -65,22 +86,22 @@ impl Metadata {
msg = &msg[7..];
}
return Err(Error::CargoError(msg.to_string()));
return Err(CargoError::new(msg.to_string()));
}
let stdout = str::from_utf8(&output.stdout).unwrap();
if let Some(line) = stdout.lines().next() {
let meta: serde_json::Value = serde_json::from_str(line)
.map_err(|_| Error::CargoError("InvalidOutput".to_string()))?;
.map_err(|_| CargoError::new("InvalidOutput".to_string()))?;
let workspace_root = meta["workspace_root"]
.as_str()
.ok_or_else(|| Error::CargoError("InvalidOutput".to_string()))?
.ok_or_else(|| CargoError::new("InvalidOutput".to_string()))?
.into();
let target_directory = meta["target_directory"]
.as_str()
.ok_or_else(|| Error::CargoError("InvalidOutput".to_string()))?
.ok_or_else(|| CargoError::new("InvalidOutput".to_string()))?
.into();
return Ok(Self {
@@ -89,6 +110,6 @@ impl Metadata {
});
}
Err(Error::CargoError("InvalidOutput".to_string()))
Err(CargoError::new("InvalidOutput".to_string()))
}
}
+492
View File
@@ -0,0 +1,492 @@
use crate::BundleConfig;
use crate::CargoError;
use core::fmt::{Display, Formatter};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Debug)]
#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
pub enum Platform {
#[cfg_attr(feature = "cli", clap(name = "web"))]
#[serde(rename = "web")]
Web,
#[cfg_attr(feature = "cli", clap(name = "desktop"))]
#[serde(rename = "desktop")]
Desktop,
#[cfg_attr(feature = "cli", clap(name = "fullstack"))]
#[serde(rename = "fullstack")]
Fullstack,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DioxusConfig {
pub application: ApplicationConfig,
pub web: WebConfig,
#[serde(default)]
pub bundle: BundleConfig,
#[cfg(feature = "cli")]
#[serde(default = "default_plugin")]
pub plugin: toml::Value,
}
#[cfg(feature = "cli")]
fn default_plugin() -> toml::Value {
toml::Value::Boolean(true)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoadDioxusConfigError {
location: String,
error: String,
}
impl std::fmt::Display for LoadDioxusConfigError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} {}", self.location, self.error)
}
}
impl std::error::Error for LoadDioxusConfigError {}
#[derive(Debug)]
pub enum CrateConfigError {
Cargo(CargoError),
Io(std::io::Error),
#[cfg(feature = "cli")]
Toml(toml::de::Error),
LoadDioxusConfig(LoadDioxusConfigError),
}
impl From<CargoError> for CrateConfigError {
fn from(err: CargoError) -> Self {
Self::Cargo(err)
}
}
impl From<std::io::Error> for CrateConfigError {
fn from(err: std::io::Error) -> Self {
Self::Io(err)
}
}
#[cfg(feature = "cli")]
impl From<toml::de::Error> for CrateConfigError {
fn from(err: toml::de::Error) -> Self {
Self::Toml(err)
}
}
impl From<LoadDioxusConfigError> for CrateConfigError {
fn from(err: LoadDioxusConfigError) -> Self {
Self::LoadDioxusConfig(err)
}
}
impl Display for CrateConfigError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::Cargo(err) => write!(f, "{}", err),
Self::Io(err) => write!(f, "{}", err),
#[cfg(feature = "cli")]
Self::Toml(err) => write!(f, "{}", err),
Self::LoadDioxusConfig(err) => write!(f, "{}", err),
}
}
}
impl std::error::Error for CrateConfigError {}
impl DioxusConfig {
#[cfg(feature = "cli")]
/// Load the dioxus config from a path
pub fn load(bin: Option<PathBuf>) -> Result<Option<DioxusConfig>, CrateConfigError> {
let crate_dir = crate::cargo::crate_root();
let crate_dir = match crate_dir {
Ok(dir) => {
if let Some(bin) = bin {
dir.join(bin)
} else {
dir
}
}
Err(_) => return Ok(None),
};
let crate_dir = crate_dir.as_path();
let Some(dioxus_conf_file) = acquire_dioxus_toml(crate_dir) else {
return Ok(None);
};
let dioxus_conf_file = dioxus_conf_file.as_path();
let cfg = toml::from_str::<DioxusConfig>(&std::fs::read_to_string(dioxus_conf_file)?)
.map_err(|err| {
let error_location = dioxus_conf_file
.strip_prefix(crate_dir)
.unwrap_or(dioxus_conf_file)
.display();
CrateConfigError::LoadDioxusConfig(LoadDioxusConfigError {
location: error_location.to_string(),
error: err.to_string(),
})
})
.map(Some);
match cfg {
Ok(Some(mut cfg)) => {
let name = cfg.application.name.clone();
if cfg.bundle.identifier.is_none() {
cfg.bundle.identifier = Some(format!("io.github.{name}"));
}
if cfg.bundle.publisher.is_none() {
cfg.bundle.publisher = Some(name);
}
Ok(Some(cfg))
}
cfg => cfg,
}
}
}
#[cfg(feature = "cli")]
fn acquire_dioxus_toml(dir: &std::path::Path) -> Option<PathBuf> {
// prefer uppercase
let uppercase_conf = dir.join("Dioxus.toml");
if uppercase_conf.is_file() {
return Some(uppercase_conf);
}
// lowercase is fine too
let lowercase_conf = dir.join("dioxus.toml");
if lowercase_conf.is_file() {
return Some(lowercase_conf);
}
None
}
impl Default for DioxusConfig {
fn default() -> Self {
let name = default_name();
Self {
application: ApplicationConfig {
name: name.clone(),
default_platform: default_platform(),
out_dir: out_dir_default(),
asset_dir: asset_dir_default(),
#[cfg(feature = "cli")]
tools: Default::default(),
sub_package: None,
},
web: WebConfig {
app: WebAppConfig {
title: default_title(),
base_path: None,
},
proxy: vec![],
watcher: Default::default(),
resource: WebResourceConfig {
dev: WebDevResourceConfig {
style: vec![],
script: vec![],
},
style: Some(vec![]),
script: Some(vec![]),
},
https: WebHttpsConfig {
enabled: None,
mkcert: None,
key_path: None,
cert_path: None,
},
},
bundle: BundleConfig {
identifier: Some(format!("io.github.{name}")),
publisher: Some(name),
..Default::default()
},
#[cfg(feature = "cli")]
plugin: toml::Value::Table(toml::map::Map::new()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApplicationConfig {
#[serde(default = "default_name")]
pub name: String,
#[serde(default = "default_platform")]
pub default_platform: Platform,
#[serde(default = "out_dir_default")]
pub out_dir: PathBuf,
#[serde(default = "asset_dir_default")]
pub asset_dir: PathBuf,
#[cfg(feature = "cli")]
#[serde(default)]
pub tools: std::collections::HashMap<String, toml::Value>,
#[serde(default)]
pub sub_package: Option<String>,
}
fn default_name() -> String {
"name".into()
}
fn default_platform() -> Platform {
Platform::Web
}
fn asset_dir_default() -> PathBuf {
PathBuf::from("public")
}
fn out_dir_default() -> PathBuf {
PathBuf::from("dist")
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebConfig {
#[serde(default)]
pub app: WebAppConfig,
#[serde(default)]
pub proxy: Vec<WebProxyConfig>,
#[serde(default)]
pub watcher: WebWatcherConfig,
#[serde(default)]
pub resource: WebResourceConfig,
#[serde(default)]
pub https: WebHttpsConfig,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebAppConfig {
#[serde(default = "default_title")]
pub title: String,
pub base_path: Option<String>,
}
impl Default for WebAppConfig {
fn default() -> Self {
Self {
title: default_title(),
base_path: None,
}
}
}
fn default_title() -> String {
"dioxus | ⛺".into()
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebProxyConfig {
pub backend: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebWatcherConfig {
#[serde(default = "watch_path_default")]
pub watch_path: Vec<PathBuf>,
#[serde(default)]
pub reload_html: bool,
#[serde(default = "true_bool")]
pub index_on_404: bool,
}
impl Default for WebWatcherConfig {
fn default() -> Self {
Self {
watch_path: watch_path_default(),
reload_html: false,
index_on_404: true,
}
}
}
fn watch_path_default() -> Vec<PathBuf> {
vec![PathBuf::from("src"), PathBuf::from("examples")]
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct WebResourceConfig {
pub dev: WebDevResourceConfig,
pub style: Option<Vec<PathBuf>>,
pub script: Option<Vec<PathBuf>>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct WebDevResourceConfig {
#[serde(default)]
pub style: Vec<PathBuf>,
#[serde(default)]
pub script: Vec<PathBuf>,
}
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct WebHttpsConfig {
pub enabled: Option<bool>,
pub mkcert: Option<bool>,
pub key_path: Option<String>,
pub cert_path: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CrateConfig {
pub out_dir: PathBuf,
pub crate_dir: PathBuf,
pub workspace_dir: PathBuf,
pub target_dir: PathBuf,
pub asset_dir: PathBuf,
#[cfg(feature = "cli")]
pub manifest: cargo_toml::Manifest<cargo_toml::Value>,
pub executable: ExecutableType,
pub dioxus_config: DioxusConfig,
pub release: bool,
pub hot_reload: bool,
pub cross_origin_policy: bool,
pub verbose: bool,
pub custom_profile: Option<String>,
pub features: Option<Vec<String>>,
pub target: Option<String>,
pub cargo_args: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ExecutableType {
Binary(String),
Lib(String),
Example(String),
}
impl CrateConfig {
#[cfg(feature = "cli")]
pub fn new(bin: Option<PathBuf>) -> Result<Self, CrateConfigError> {
let dioxus_config = DioxusConfig::load(bin.clone())?.unwrap_or_default();
let crate_root = crate::crate_root()?;
let crate_dir = if let Some(package) = &dioxus_config.application.sub_package {
crate_root.join(package)
} else if let Some(bin) = bin {
crate_root.join(bin)
} else {
crate_root
};
let meta = crate::Metadata::get()?;
let workspace_dir = meta.workspace_root;
let target_dir = meta.target_directory;
let out_dir = crate_dir.join(&dioxus_config.application.out_dir);
let cargo_def = &crate_dir.join("Cargo.toml");
let asset_dir = crate_dir.join(&dioxus_config.application.asset_dir);
let manifest = cargo_toml::Manifest::from_path(cargo_def).unwrap();
let mut output_filename = String::from("dioxus_app");
if let Some(package) = &manifest.package.as_ref() {
output_filename = match &package.default_run {
Some(default_run_target) => default_run_target.to_owned(),
None => manifest
.bin
.iter()
.find(|b| b.name == manifest.package.as_ref().map(|pkg| pkg.name.clone()))
.or(manifest
.bin
.iter()
.find(|b| b.path == Some("src/main.rs".to_owned())))
.or(manifest.bin.first())
.or(manifest.lib.as_ref())
.and_then(|prod| prod.name.clone())
.unwrap_or(String::from("dioxus_app")),
};
}
let executable = ExecutableType::Binary(output_filename);
let release = false;
let hot_reload = false;
let verbose = false;
let custom_profile = None;
let features = None;
let target = None;
let cargo_args = vec![];
Ok(Self {
out_dir,
crate_dir,
workspace_dir,
target_dir,
asset_dir,
#[cfg(feature = "cli")]
manifest,
executable,
release,
dioxus_config,
hot_reload,
cross_origin_policy: false,
custom_profile,
features,
verbose,
target,
cargo_args,
})
}
pub fn as_example(&mut self, example_name: String) -> &mut Self {
self.executable = ExecutableType::Example(example_name);
self
}
pub fn with_release(&mut self, release: bool) -> &mut Self {
self.release = release;
self
}
pub fn with_hot_reload(&mut self, hot_reload: bool) -> &mut Self {
self.hot_reload = hot_reload;
self
}
pub fn with_cross_origin_policy(&mut self, cross_origin_policy: bool) -> &mut Self {
self.cross_origin_policy = cross_origin_policy;
self
}
pub fn with_verbose(&mut self, verbose: bool) -> &mut Self {
self.verbose = verbose;
self
}
pub fn set_profile(&mut self, profile: String) -> &mut Self {
self.custom_profile = Some(profile);
self
}
pub fn set_features(&mut self, features: Vec<String>) -> &mut Self {
self.features = Some(features);
self
}
pub fn set_target(&mut self, target: String) -> &mut Self {
self.target = Some(target);
self
}
pub fn set_cargo_args(&mut self, cargo_args: Vec<String>) -> &mut Self {
self.cargo_args = cargo_args;
self
}
}
fn true_bool() -> bool {
true
}
+58
View File
@@ -0,0 +1,58 @@
#![doc = include_str!("../README.md")]
#![doc(html_logo_url = "https://avatars.githubusercontent.com/u/79236386")]
#![doc(html_favicon_url = "https://avatars.githubusercontent.com/u/79236386")]
mod config;
pub use config::*;
mod bundle;
pub use bundle::*;
mod cargo;
pub use cargo::*;
#[doc(hidden)]
pub mod __private {
use crate::CrateConfig;
pub const CONFIG_ENV: &str = "DIOXUS_CONFIG";
pub fn save_config(config: &CrateConfig) -> CrateConfigDropGuard {
std::env::set_var(CONFIG_ENV, serde_json::to_string(config).unwrap());
CrateConfigDropGuard
}
/// A guard that removes the config from the environment when dropped.
pub struct CrateConfigDropGuard;
impl Drop for CrateConfigDropGuard {
fn drop(&mut self) {
std::env::remove_var(CONFIG_ENV);
}
}
}
/// An error that occurs when the dioxus CLI was not used to build the application.
#[derive(Debug)]
pub struct DioxusCLINotUsed;
impl std::fmt::Display for DioxusCLINotUsed {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("dioxus CLI was not used to build the application")
}
}
impl std::error::Error for DioxusCLINotUsed {}
/// The current crate's configuration.
pub static CURRENT_CONFIG: once_cell::sync::Lazy<
Result<crate::config::CrateConfig, DioxusCLINotUsed>,
> = once_cell::sync::Lazy::new(|| {
CURRENT_CONFIG_JSON
.and_then(|config| serde_json::from_str(config).ok())
.ok_or_else(|| {
tracing::error!("A library is trying to access the crate's configuration, but the dioxus CLI was not used to build the application.");
DioxusCLINotUsed
})
});
/// The current crate's configuration.
pub const CURRENT_CONFIG_JSON: Option<&str> = std::option_env!("DIOXUS_CONFIG");
+8 -3
View File
@@ -14,6 +14,7 @@ clap = { version = "4.2", features = ["derive"] }
thiserror = { workspace = true }
wasm-bindgen-cli-support = "0.2"
colored = "2.0.0"
dioxus-cli-config = { workspace = true, features = ["cli"] }
# features
log = "0.4.14"
@@ -30,7 +31,7 @@ cargo_metadata = "0.15.0"
tokio = { version = "1.16.1", features = ["fs", "sync", "rt", "macros"] }
atty = "0.2.14"
chrono = "0.4.19"
anyhow = "1.0.53"
anyhow = "1"
hyper = "0.14.17"
hyper-rustls = "0.23.2"
indicatif = "0.17.5"
@@ -72,8 +73,11 @@ cargo-generate = "0.18"
toml_edit = "0.19.11"
# bundling
tauri-bundler = { version = "=1.3.0", features = ["native-tls-vendored"] }
tauri-utils = "=1.4.*"
tauri-bundler = { version = "=1.4.*", features = ["native-tls-vendored"] }
tauri-utils = "=1.5.*"
# todo: don't make this optional
manganis-cli-support = { workspace = true, features = ["webp", "html"] }
dioxus-autofmt = { workspace = true }
dioxus-check = { workspace = true }
@@ -83,6 +87,7 @@ dioxus-html = { workspace = true, features = ["hot-reload-context"] }
dioxus-core = { workspace = true, features = ["serialize"] }
dioxus-hot-reload = { workspace = true }
interprocess-docfix = { version = "1.2.2" }
gitignore = "1.0.8"
[features]
default = []
+4 -4
View File
@@ -10,7 +10,7 @@ It handles building, bundling, development and publishing to simplify developmen
### Install the stable version (recommended)
```
```shell
cargo install dioxus-cli
```
@@ -20,7 +20,7 @@ To get the latest bug fixes and features, you can install the development versio
However, this is not fully tested.
That means you're probably going to have more bugs despite having the latest bug fixes.
```
```shell
cargo install --git https://github.com/DioxusLabs/dioxus dioxus-cli
```
@@ -29,7 +29,7 @@ and install it in Cargo's global binary directory (`~/.cargo/bin/` by default).
### Install from local folder
```
```shell
cargo install --path . --debug
```
@@ -40,7 +40,7 @@ It will be cloned from the [dioxus-template](https://github.com/DioxusLabs/dioxu
Alternatively, you can specify the template path:
```
```shell
dx create hello --template gh:dioxuslabs/dioxus-template
```
+60
View File
@@ -0,0 +1,60 @@
use std::{fs::File, io::Write, path::PathBuf};
use crate::Result;
use dioxus_cli_config::CrateConfig;
use manganis_cli_support::{AssetManifest, AssetManifestExt};
pub fn asset_manifest(crate_config: &CrateConfig) -> AssetManifest {
AssetManifest::load_from_path(
crate_config.crate_dir.join("Cargo.toml"),
crate_config.workspace_dir.join("Cargo.lock"),
)
}
/// Create a head file that contains all of the imports for assets that the user project uses
pub fn create_assets_head(config: &CrateConfig) -> Result<()> {
let manifest = asset_manifest(config);
let mut file = File::create(config.out_dir.join("__assets_head.html"))?;
file.write_all(manifest.head().as_bytes())?;
Ok(())
}
/// Process any assets collected from the binary
pub(crate) fn process_assets(config: &CrateConfig) -> anyhow::Result<()> {
let manifest = asset_manifest(config);
let static_asset_output_dir = PathBuf::from(
config
.dioxus_config
.web
.app
.base_path
.clone()
.unwrap_or_default(),
);
let static_asset_output_dir = config.out_dir.join(static_asset_output_dir);
manifest.copy_static_assets_to(static_asset_output_dir)?;
Ok(())
}
/// A guard that sets up the environment for the web renderer to compile in. This guard sets the location that assets will be served from
pub(crate) struct WebAssetConfigDropGuard;
impl WebAssetConfigDropGuard {
pub fn new() -> Self {
// Set up the collect asset config
manganis_cli_support::Config::default()
.with_assets_serve_location("/")
.save();
Self {}
}
}
impl Drop for WebAssetConfigDropGuard {
fn drop(&mut self) {
// Reset the config
manganis_cli_support::Config::default().save();
}
}
+2 -2
View File
@@ -1,5 +1,5 @@
// Dioxus-CLI
// https://github.com/DioxusLabs/cli
// https://github.com/DioxusLabs/dioxus/tree/master/packages/cli
(function () {
var protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
@@ -22,4 +22,4 @@
}
};
ws.onclose = reload_upon_connect;
})()
})()
+82 -50
View File
@@ -1,11 +1,14 @@
use crate::{
config::{CrateConfig, ExecutableType},
assets::{asset_manifest, create_assets_head, process_assets, WebAssetConfigDropGuard},
error::{Error, Result},
tools::Tool,
DioxusConfig,
};
use cargo_metadata::{diagnostic::Diagnostic, Message};
use dioxus_cli_config::crate_root;
use dioxus_cli_config::CrateConfig;
use dioxus_cli_config::ExecutableType;
use indicatif::{ProgressBar, ProgressStyle};
use lazy_static::lazy_static;
use serde::Serialize;
use std::{
fs::{copy, create_dir_all, File},
@@ -16,17 +19,20 @@ use std::{
};
use wasm_bindgen_cli_support::Bindgen;
lazy_static! {
static ref PROGRESS_BARS: indicatif::MultiProgress = indicatif::MultiProgress::new();
}
#[derive(Serialize, Debug, Clone)]
pub struct BuildResult {
pub warnings: Vec<Diagnostic>,
pub elapsed_time: u128,
}
#[allow(unused)]
pub fn build(config: &CrateConfig, quiet: bool) -> Result<BuildResult> {
pub fn build(config: &CrateConfig, _: bool, skip_assets: bool) -> Result<BuildResult> {
// [1] Build the project with cargo, generating a wasm32-unknown-unknown target (is there a more specific, better target to leverage?)
// [2] Generate the appropriate build folders
// [3] Wasm-bindgen the .wasm fiile, and move it into the {builddir}/modules/xxxx/xxxx_bg.wasm
// [3] Wasm-bindgen the .wasm file, and move it into the {builddir}/modules/xxxx/xxxx_bg.wasm
// [4] Wasm-opt the .wasm file with whatever optimizations need to be done
// [5][OPTIONAL] Builds the Tailwind CSS file using the Tailwind standalone binary
// [6] Link up the html page to the wasm module
@@ -41,10 +47,13 @@ pub fn build(config: &CrateConfig, quiet: bool) -> Result<BuildResult> {
..
} = config;
let _gaurd = WebAssetConfigDropGuard::new();
// start to build the assets
let ignore_files = build_assets(config)?;
let t_start = std::time::Instant::now();
let _guard = dioxus_cli_config::__private::save_config(config);
// [1] Build the .wasm module
log::info!("🚅 Running build command...");
@@ -60,8 +69,8 @@ pub fn build(config: &CrateConfig, quiet: bool) -> Result<BuildResult> {
.output()?;
}
let cmd = subprocess::Exec::cmd("cargo");
let cmd = cmd
let cmd = subprocess::Exec::cmd("cargo")
.env("CARGO_TARGET_DIR", target_dir)
.cwd(crate_dir)
.arg("build")
.arg("--target")
@@ -93,6 +102,8 @@ pub fn build(config: &CrateConfig, quiet: bool) -> Result<BuildResult> {
cmd
};
let cmd = cmd.args(&config.cargo_args);
let cmd = match executable {
ExecutableType::Binary(name) => cmd.arg("--bin").arg(name),
ExecutableType::Lib(name) => cmd.arg("--lib").arg(name),
@@ -144,7 +155,7 @@ pub fn build(config: &CrateConfig, quiet: bool) -> Result<BuildResult> {
}
// check binaryen:wasm-opt tool
let dioxus_tools = dioxus_config.application.tools.clone().unwrap_or_default();
let dioxus_tools = dioxus_config.application.tools.clone();
if dioxus_tools.contains_key("binaryen") {
let info = dioxus_tools.get("binaryen").unwrap();
let binaryen = crate::tools::Tool::Binaryen;
@@ -250,22 +261,31 @@ pub fn build(config: &CrateConfig, quiet: bool) -> Result<BuildResult> {
}
}
if !skip_assets {
process_assets(config)?;
}
Ok(BuildResult {
warnings: warning_messages,
elapsed_time: t_start.elapsed().as_millis(),
})
}
pub fn build_desktop(config: &CrateConfig, _is_serve: bool) -> Result<BuildResult> {
pub fn build_desktop(
config: &CrateConfig,
_is_serve: bool,
skip_assets: bool,
) -> Result<BuildResult> {
log::info!("🚅 Running build [Desktop] command...");
let t_start = std::time::Instant::now();
let ignore_files = build_assets(config)?;
let _guard = dioxus_cli_config::__private::save_config(config);
let mut cmd = subprocess::Exec::cmd("cargo")
.env("CARGO_TARGET_DIR", &config.target_dir)
.cwd(&config.crate_dir)
.arg("build")
.arg("--quiet")
.arg("--message-format=json");
if config.release {
@@ -273,6 +293,8 @@ pub fn build_desktop(config: &CrateConfig, _is_serve: bool) -> Result<BuildResul
}
if config.verbose {
cmd = cmd.arg("--verbose");
} else {
cmd = cmd.arg("--quiet");
}
if config.custom_profile.is_some() {
@@ -285,10 +307,18 @@ pub fn build_desktop(config: &CrateConfig, _is_serve: bool) -> Result<BuildResul
cmd = cmd.arg("--features").arg(features_str);
}
if let Some(target) = &config.target {
cmd = cmd.arg("--target").arg(target);
}
let target_platform = config.target.as_deref().unwrap_or("");
cmd = cmd.args(&config.cargo_args);
let cmd = match &config.executable {
crate::ExecutableType::Binary(name) => cmd.arg("--bin").arg(name),
crate::ExecutableType::Lib(name) => cmd.arg("--lib").arg(name),
crate::ExecutableType::Example(name) => cmd.arg("--example").arg(name),
ExecutableType::Binary(name) => cmd.arg("--bin").arg(name),
ExecutableType::Lib(name) => cmd.arg("--lib").arg(name),
ExecutableType::Example(name) => cmd.arg("--example").arg(name),
};
let warning_messages = prettier_build(cmd)?;
@@ -300,14 +330,19 @@ pub fn build_desktop(config: &CrateConfig, _is_serve: bool) -> Result<BuildResul
let file_name: String;
let mut res_path = match &config.executable {
crate::ExecutableType::Binary(name) | crate::ExecutableType::Lib(name) => {
file_name = name.clone();
config.target_dir.join(release_type).join(name)
}
crate::ExecutableType::Example(name) => {
ExecutableType::Binary(name) | ExecutableType::Lib(name) => {
file_name = name.clone();
config
.target_dir
.join(target_platform)
.join(release_type)
.join(name)
}
ExecutableType::Example(name) => {
file_name = name.clone();
config
.target_dir
.join(target_platform)
.join(release_type)
.join("examples")
.join(name)
@@ -359,15 +394,16 @@ pub fn build_desktop(config: &CrateConfig, _is_serve: bool) -> Result<BuildResul
}
}
if !skip_assets {
// Collect assets
process_assets(config)?;
// Create the __assets_head.html file for bundling
create_assets_head(config)?;
}
log::info!(
"🚩 Build completed: [./{}]",
config
.dioxus_config
.application
.out_dir
.clone()
.unwrap_or_else(|| PathBuf::from("dist"))
.display()
config.dioxus_config.application.out_dir.clone().display()
);
println!("build desktop done");
@@ -381,8 +417,9 @@ pub fn build_desktop(config: &CrateConfig, _is_serve: bool) -> Result<BuildResul
fn prettier_build(cmd: subprocess::Exec) -> anyhow::Result<Vec<Diagnostic>> {
let mut warning_messages: Vec<Diagnostic> = vec![];
let pb = ProgressBar::new_spinner();
let mut pb = ProgressBar::new_spinner();
pb.enable_steady_tick(Duration::from_millis(200));
pb = PROGRESS_BARS.add(pb);
pb.set_style(
ProgressStyle::with_template("{spinner:.dim.bold} {wide_msg}")
.unwrap()
@@ -390,14 +427,6 @@ fn prettier_build(cmd: subprocess::Exec) -> anyhow::Result<Vec<Diagnostic>> {
);
pb.set_message("💼 Waiting to start build the project...");
struct StopSpinOnDrop(ProgressBar);
impl Drop for StopSpinOnDrop {
fn drop(&mut self) {
self.0.finish_and_clear();
}
}
let stdout = cmd.detached().stream_stdout()?;
let reader = std::io::BufReader::new(stdout);
@@ -433,14 +462,18 @@ fn prettier_build(cmd: subprocess::Exec) -> anyhow::Result<Vec<Diagnostic>> {
std::process::exit(1);
}
}
_ => (), // Unknown message
_ => {
// Unknown message
}
}
}
Ok(warning_messages)
}
pub fn gen_page(config: &DioxusConfig, serve: bool) -> String {
let crate_root = crate::cargo::crate_root().unwrap();
pub fn gen_page(config: &CrateConfig, serve: bool, skip_assets: bool) -> String {
let _gaurd = WebAssetConfigDropGuard::new();
let crate_root = crate_root().unwrap();
let custom_html_file = crate_root.join("index.html");
let mut html = if custom_html_file.is_file() {
let mut buf = String::new();
@@ -454,14 +487,14 @@ pub fn gen_page(config: &DioxusConfig, serve: bool) -> String {
String::from(include_str!("./assets/index.html"))
};
let resources = config.web.resource.clone();
let resources = config.dioxus_config.web.resource.clone();
let mut style_list = resources.style.unwrap_or_default();
let mut script_list = resources.script.unwrap_or_default();
if serve {
let mut dev_style = resources.dev.style.clone().unwrap_or_default();
let mut dev_script = resources.dev.script.unwrap_or_default();
let mut dev_style = resources.dev.style.clone();
let mut dev_script = resources.dev.script.clone();
style_list.append(&mut dev_style);
script_list.append(&mut dev_script);
}
@@ -474,14 +507,18 @@ pub fn gen_page(config: &DioxusConfig, serve: bool) -> String {
))
}
if config
.dioxus_config
.application
.tools
.clone()
.unwrap_or_default()
.contains_key("tailwindcss")
{
style_str.push_str("<link rel=\"stylesheet\" href=\"/{base_path}/tailwind.css\">\n");
}
if !skip_assets {
let manifest = asset_manifest(config);
style_str.push_str(&manifest.head());
}
replace_or_insert_before("{style_include}", &style_str, "</head", &mut html);
@@ -502,11 +539,11 @@ pub fn gen_page(config: &DioxusConfig, serve: bool) -> String {
);
}
let base_path = match &config.web.app.base_path {
let base_path = match &config.dioxus_config.web.app.base_path {
Some(path) => path,
None => ".",
};
let app_name = &config.application.name;
let app_name = &config.dioxus_config.application.name;
// Check if a script already exists
if html.contains("{app_name}") && html.contains("{base_path}") {
html = html.replace("{app_name}", app_name);
@@ -530,12 +567,7 @@ pub fn gen_page(config: &DioxusConfig, serve: bool) -> String {
);
}
let title = config
.web
.app
.title
.clone()
.unwrap_or_else(|| "dioxus | ⛺".into());
let title = config.dioxus_config.web.app.title.clone();
replace_or_insert_before("{app_title}", &title, "</title", &mut html);
@@ -562,7 +594,7 @@ fn build_assets(config: &CrateConfig) -> Result<Vec<PathBuf>> {
let mut result = vec![];
let dioxus_config = &config.dioxus_config;
let dioxus_tools = dioxus_config.application.tools.clone().unwrap_or_default();
let dioxus_tools = dioxus_config.application.tools.clone();
// check sass tool state
let sass = Tool::Sass;
+102 -81
View File
@@ -31,15 +31,23 @@ pub struct Autoformat {
impl Autoformat {
// Todo: autoformat the entire crate
pub async fn autoformat(self) -> Result<()> {
let Autoformat {
check,
raw,
file,
split_line_attributes,
..
} = self;
// Default to formatting the project
if self.raw.is_none() && self.file.is_none() {
if let Err(e) = autoformat_project(self.check, self.split_line_attributes).await {
if raw.is_none() && file.is_none() {
if let Err(e) = autoformat_project(check, split_line_attributes).await {
eprintln!("error formatting project: {}", e);
exit(1);
}
}
if let Some(raw) = self.raw {
if let Some(raw) = raw {
let indent = indentation_for(".", self.split_line_attributes)?;
if let Some(inner) = dioxus_autofmt::fmt_block(&raw, 0, indent) {
println!("{}", inner);
@@ -51,57 +59,99 @@ impl Autoformat {
}
// Format single file
if let Some(file) = self.file {
let file_content;
let indent;
if file == "-" {
indent = indentation_for(".", self.split_line_attributes)?;
let mut contents = String::new();
std::io::stdin().read_to_string(&mut contents)?;
file_content = Ok(contents);
} else {
indent = indentation_for(".", self.split_line_attributes)?;
file_content = fs::read_to_string(&file);
};
match file_content {
Ok(s) => {
let edits = dioxus_autofmt::fmt_file(&s, indent);
let out = dioxus_autofmt::apply_formats(&s, edits);
if file == "-" {
print!("{}", out);
} else {
match fs::write(&file, out) {
Ok(_) => {
println!("formatted {}", file);
}
Err(e) => {
eprintln!("failed to write formatted content to file: {}", e);
}
}
}
}
Err(e) => {
eprintln!("failed to open file: {}", e);
exit(1);
}
}
if let Some(file) = file {
refactor_file(file, split_line_attributes)?;
}
Ok(())
}
}
fn refactor_file(file: String, split_line_attributes: bool) -> Result<(), Error> {
let indent = indentation_for(".", split_line_attributes)?;
let file_content = if file == "-" {
let mut contents = String::new();
std::io::stdin().read_to_string(&mut contents)?;
Ok(contents)
} else {
fs::read_to_string(&file)
};
let Ok(s) = file_content else {
eprintln!("failed to open file: {}", file_content.unwrap_err());
exit(1);
};
let edits = dioxus_autofmt::fmt_file(&s, indent);
let out = dioxus_autofmt::apply_formats(&s, edits);
if file == "-" {
print!("{}", out);
} else if let Err(e) = fs::write(&file, out) {
eprintln!("failed to write formatted content to file: {e}",);
} else {
println!("formatted {}", file);
}
Ok(())
}
fn get_project_files(config: &CrateConfig) -> Vec<PathBuf> {
let mut files = vec![];
let gitignore_path = config.crate_dir.join(".gitignore");
if gitignore_path.is_file() {
let gitigno = gitignore::File::new(gitignore_path.as_path()).unwrap();
if let Ok(git_files) = gitigno.included_files() {
let git_files = git_files
.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
}
fn is_target_dir(file: &Path) -> bool {
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>,
indent: IndentOptions,
) -> Result<usize, tokio::io::Error> {
let contents = tokio::fs::read_to_string(&path).await?;
let edits = dioxus_autofmt::fmt_file(&contents, indent);
let len = edits.len();
if !edits.is_empty() {
let out = dioxus_autofmt::apply_formats(&contents, edits);
tokio::fs::write(path, out).await?;
}
Ok(len)
}
/// 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
///
/// 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<()> {
let crate_config = crate::CrateConfig::new(None)?;
let crate_config = dioxus_cli_config::CrateConfig::new(None)?;
let mut files_to_format = vec![];
collect_rs_files(&crate_config.crate_dir, &mut files_to_format);
let files_to_format = get_project_files(&crate_config);
if files_to_format.is_empty() {
return Ok(());
@@ -111,38 +161,17 @@ async fn autoformat_project(check: bool, split_line_attributes: bool) -> Result<
let counts = files_to_format
.into_iter()
.filter(|file| {
if file.components().any(|f| f.as_os_str() == "target") {
return false;
}
true
})
.map(|path| async {
let _path = path.clone();
let _indent = indent.clone();
let res = tokio::spawn(async move {
let contents = tokio::fs::read_to_string(&path).await?;
let edits = dioxus_autofmt::fmt_file(&contents, _indent.clone());
let len = edits.len();
if !edits.is_empty() {
let out = dioxus_autofmt::apply_formats(&contents, edits);
tokio::fs::write(&path, out).await?;
}
Ok(len) as Result<usize, tokio::io::Error>
})
.await;
let path_clone = path.clone();
let res = tokio::spawn(format_file(path, indent.clone())).await;
match res {
Err(err) => {
eprintln!("error formatting file: {}\n{err}", _path.display());
eprintln!("error formatting file: {}\n{err}", path_clone.display());
None
}
Ok(Err(err)) => {
eprintln!("error formatting file: {}\n{err}", _path.display());
eprintln!("error formatting file: {}\n{err}", path_clone.display());
None
}
Ok(Ok(res)) => Some(res),
@@ -152,13 +181,7 @@ async fn autoformat_project(check: bool, split_line_attributes: bool) -> Result<
.collect::<Vec<_>>()
.await;
let files_formatted: usize = counts
.into_iter()
.map(|f| match f {
Some(res) => res,
_ => 0,
})
.sum();
let files_formatted: usize = counts.into_iter().flatten().sum();
if files_formatted > 0 && check {
eprintln!("{} files needed formatting", files_formatted);
@@ -215,26 +238,24 @@ fn indentation_for(
))
}
fn collect_rs_files(folder: &Path, files: &mut Vec<PathBuf>) {
let Ok(folder) = folder.read_dir() else {
fn collect_rs_files(folder: &impl AsRef<Path>, files: &mut Vec<PathBuf>) {
if is_target_dir(folder.as_ref()) {
return;
}
let Ok(folder) = folder.as_ref().read_dir() else {
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" {
if ext == "rs" && !is_target_dir(&path) {
files.push(path);
}
}
+53 -17
View File
@@ -1,6 +1,9 @@
use crate::cfg::Platform;
use crate::assets::WebAssetConfigDropGuard;
#[cfg(feature = "plugin")]
use crate::plugin::PluginManager;
use crate::server::fullstack::FullstackServerEnvGuard;
use crate::server::fullstack::FullstackWebEnvGuard;
use dioxus_cli_config::Platform;
use super::*;
@@ -13,23 +16,26 @@ pub struct Build {
}
impl Build {
pub fn build(self, bin: Option<PathBuf>) -> Result<()> {
let mut crate_config = crate::CrateConfig::new(bin)?;
pub fn build(self, bin: Option<PathBuf>, target_dir: Option<&std::path::Path>) -> Result<()> {
let mut crate_config = dioxus_cli_config::CrateConfig::new(bin)?;
if let Some(target_dir) = target_dir {
crate_config.target_dir = target_dir.to_path_buf();
}
// change the release state.
crate_config.with_release(self.build.release);
crate_config.with_verbose(self.build.verbose);
if self.build.example.is_some() {
crate_config.as_example(self.build.example.unwrap());
crate_config.as_example(self.build.example.clone().unwrap());
}
if self.build.profile.is_some() {
crate_config.set_profile(self.build.profile.unwrap());
crate_config.set_profile(self.build.profile.clone().unwrap());
}
if self.build.features.is_some() {
crate_config.set_features(self.build.features.unwrap());
crate_config.set_features(self.build.features.clone().unwrap());
}
let platform = self
@@ -37,31 +43,61 @@ impl Build {
.platform
.unwrap_or(crate_config.dioxus_config.application.default_platform);
if let Some(target) = self.build.target.clone() {
crate_config.set_target(target);
}
crate_config.set_cargo_args(self.build.cargo_args.clone());
// #[cfg(feature = "plugin")]
// let _ = PluginManager::on_build_start(&crate_config, &platform);
match platform {
Platform::Web => {
crate::builder::build(&crate_config, true)?;
crate::builder::build(&crate_config, false, self.build.skip_assets)?;
}
Platform::Desktop => {
crate::builder::build_desktop(&crate_config, false)?;
crate::builder::build_desktop(&crate_config, false, self.build.skip_assets)?;
}
Platform::Fullstack => {
// Fullstack mode must be built with web configs on the desktop (server) binary as well as the web binary
let _config = WebAssetConfigDropGuard::new();
{
let mut web_config = crate_config.clone();
let _gaurd = FullstackWebEnvGuard::new(&self.build);
let web_feature = self.build.client_feature;
let features = &mut web_config.features;
match features {
Some(features) => {
features.push(web_feature);
}
None => web_config.features = Some(vec![web_feature]),
};
crate::builder::build(&crate_config, false, self.build.skip_assets)?;
}
{
let mut desktop_config = crate_config.clone();
let desktop_feature = self.build.server_feature;
let features = &mut desktop_config.features;
match features {
Some(features) => {
features.push(desktop_feature);
}
None => desktop_config.features = Some(vec![desktop_feature]),
};
let _gaurd =
FullstackServerEnvGuard::new(self.build.force_debug, self.build.release);
crate::builder::build_desktop(&desktop_config, false, self.build.skip_assets)?;
}
}
}
let temp = gen_page(&crate_config.dioxus_config, false);
let temp = gen_page(&crate_config, false, self.build.skip_assets);
let mut file = std::fs::File::create(
crate_config
.crate_dir
.join(
crate_config
.dioxus_config
.application
.out_dir
.clone()
.unwrap_or_else(|| PathBuf::from("dist")),
)
.join(crate_config.dioxus_config.application.out_dir.clone())
.join("index.html"),
)?;
file.write_all(temp.as_bytes())?;
+33 -7
View File
@@ -1,4 +1,5 @@
use core::panic;
use dioxus_cli_config::ExecutableType;
use std::{fs::create_dir_all, str::FromStr};
use tauri_bundler::{BundleSettings, PackageSettings, SettingsBuilder};
@@ -62,7 +63,7 @@ impl From<PackageType> for tauri_bundler::PackageType {
impl Bundle {
pub fn bundle(self, bin: Option<PathBuf>) -> Result<()> {
let mut crate_config = crate::CrateConfig::new(bin)?;
let mut crate_config = dioxus_cli_config::CrateConfig::new(bin)?;
// change the release state.
crate_config.with_release(self.build.release);
@@ -76,16 +77,22 @@ impl Bundle {
crate_config.set_profile(self.build.profile.unwrap());
}
if let Some(target) = &self.build.target {
crate_config.set_target(target.to_string());
}
crate_config.set_cargo_args(self.build.cargo_args);
// build the desktop app
build_desktop(&crate_config, false)?;
build_desktop(&crate_config, false, false)?;
// copy the binary to the out dir
let package = crate_config.manifest.package.unwrap();
let mut name: PathBuf = match &crate_config.executable {
crate::ExecutableType::Binary(name)
| crate::ExecutableType::Lib(name)
| crate::ExecutableType::Example(name) => name,
ExecutableType::Binary(name)
| ExecutableType::Lib(name)
| ExecutableType::Example(name) => name,
}
.into();
if cfg!(windows) {
@@ -128,6 +135,20 @@ impl Bundle {
}
}
// Add all assets from collect assets to the bundle
#[cfg(feature = "collect-assets")]
{
let config = manganis_cli_support::Config::current();
let location = config.assets_serve_location().to_string();
let location = format!("./{}", location);
println!("Adding assets from {} to bundle", location);
if let Some(resources) = &mut bundle_settings.resources {
resources.push(location);
} else {
bundle_settings.resources = Some(vec![location]);
}
}
let mut settings = SettingsBuilder::new()
.project_out_directory(crate_config.out_dir)
.package_settings(PackageSettings {
@@ -148,6 +169,11 @@ impl Bundle {
.collect(),
);
}
if let Some(target) = &self.build.target {
settings = settings.target(target.to_string());
}
let settings = settings.build();
// on macos we need to set CI=true (https://github.com/tauri-apps/tauri/issues/2567)
@@ -156,9 +182,9 @@ impl Bundle {
tauri_bundler::bundle::bundle_project(settings.unwrap()).unwrap_or_else(|err|{
#[cfg(target_os = "macos")]
panic!("Failed to bundle project: {}\nMake sure you have automation enabled in your terminal (https://github.com/tauri-apps/tauri/issues/3055#issuecomment-1624389208) and full disk access enabled for your terminal (https://github.com/tauri-apps/tauri/issues/3055#issuecomment-1624389208)", err);
panic!("Failed to bundle project: {:#?}\nMake sure you have automation enabled in your terminal (https://github.com/tauri-apps/tauri/issues/3055#issuecomment-1624389208) and full disk access enabled for your terminal (https://github.com/tauri-apps/tauri/issues/3055#issuecomment-1624389208)", err);
#[cfg(not(target_os = "macos"))]
panic!("Failed to bundle project: {}", err);
panic!("Failed to bundle project: {:#?}", err);
});
Ok(())
+80 -20
View File
@@ -1,20 +1,20 @@
use clap::ValueEnum;
use serde::Serialize;
use dioxus_cli_config::Platform;
use super::*;
/// Config options for the build system.
#[derive(Clone, Debug, Default, Deserialize, Parser)]
pub struct ConfigOptsBuild {
/// The index HTML file to drive the bundling process [default: index.html]
#[arg(long)]
pub target: Option<PathBuf>,
/// Build in release mode [default: false]
#[clap(long)]
#[serde(default)]
pub release: bool,
/// This flag only applies to fullstack builds. By default fullstack builds will run with something in between debug and release mode. This flag will force the build to run in debug mode. [default: false]
#[clap(long)]
#[serde(default)]
pub force_debug: bool,
// Use verbose output [default: false]
#[clap(long)]
#[serde(default)]
@@ -32,17 +32,53 @@ pub struct ConfigOptsBuild {
#[clap(long, value_enum)]
pub platform: Option<Platform>,
/// Skip collecting assets from dependencies [default: false]
#[clap(long)]
#[serde(default)]
pub skip_assets: bool,
/// Space separated list of features to activate
#[clap(long)]
pub features: Option<Vec<String>>,
/// The feature to use for the client in a fullstack app [default: "web"]
#[clap(long, default_value_t = { "web".to_string() })]
pub client_feature: String,
/// The feature to use for the server in a fullstack app [default: "ssr"]
#[clap(long, default_value_t = { "ssr".to_string() })]
pub server_feature: String,
/// Rustc platform triple
#[clap(long)]
pub target: Option<String>,
/// Extra arguments passed to cargo build
#[clap(last = true)]
pub cargo_args: Vec<String>,
}
impl From<ConfigOptsServe> for ConfigOptsBuild {
fn from(serve: ConfigOptsServe) -> Self {
Self {
target: serve.target,
release: serve.release,
verbose: serve.verbose,
example: serve.example,
profile: serve.profile,
platform: serve.platform,
features: serve.features,
client_feature: serve.client_feature,
server_feature: serve.server_feature,
skip_assets: serve.skip_assets,
force_debug: serve.force_debug,
cargo_args: serve.cargo_args,
}
}
}
#[derive(Clone, Debug, Default, Deserialize, Parser)]
pub struct ConfigOptsServe {
/// The index HTML file to drive the bundling process [default: index.html]
#[arg(short, long)]
pub target: Option<PathBuf>,
/// Port of dev server
#[clap(long)]
#[clap(default_value_t = 8080)]
@@ -62,6 +98,11 @@ pub struct ConfigOptsServe {
#[serde(default)]
pub release: bool,
/// This flag only applies to fullstack builds. By default fullstack builds will run with something in between debug and release mode. This flag will force the build to run in debug mode. [default: false]
#[clap(long)]
#[serde(default)]
pub force_debug: bool,
// Use verbose output [default: false]
#[clap(long)]
#[serde(default)]
@@ -71,7 +112,7 @@ pub struct ConfigOptsServe {
#[clap(long)]
pub profile: Option<String>,
/// Build platform: support Web & Desktop [default: "default_platform"]
/// Build platform: support Web, Desktop, and Fullstack [default: "default_platform"]
#[clap(long, value_enum)]
pub platform: Option<Platform>,
@@ -89,16 +130,27 @@ pub struct ConfigOptsServe {
/// Space separated list of features to activate
#[clap(long)]
pub features: Option<Vec<String>>,
}
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Serialize, Deserialize, Debug)]
pub enum Platform {
#[clap(name = "web")]
#[serde(rename = "web")]
Web,
#[clap(name = "desktop")]
#[serde(rename = "desktop")]
Desktop,
/// Skip collecting assets from dependencies [default: false]
#[clap(long)]
#[serde(default)]
pub skip_assets: bool,
/// The feature to use for the client in a fullstack app [default: "web"]
#[clap(long, default_value_t = { "web".to_string() })]
pub client_feature: String,
/// The feature to use for the server in a fullstack app [default: "ssr"]
#[clap(long, default_value_t = { "ssr".to_string() })]
pub server_feature: String,
/// Rustc platform triple
#[clap(long)]
pub target: Option<String>,
/// Extra arguments passed to cargo build
#[clap(last = true)]
pub cargo_args: Vec<String>,
}
/// Config options for the bundling system.
@@ -129,4 +181,12 @@ pub struct ConfigOptsBundle {
/// Space separated list of features to activate
#[clap(long)]
pub features: Option<Vec<String>>,
/// Rustc platform triple
#[clap(long)]
pub target: Option<String>,
/// Extra arguments passed to cargo build
#[clap(last = true)]
pub cargo_args: Vec<String>,
}
+1 -1
View File
@@ -47,7 +47,7 @@ async fn check_file_and_report(path: PathBuf) -> Result<()> {
///
/// Doesn't do mod-descending, so it will still try to check unreachable files. TODO.
async fn check_project_and_report() -> Result<()> {
let crate_config = crate::CrateConfig::new(None)?;
let crate_config = dioxus_cli_config::CrateConfig::new(None)?;
let mut files_to_check = vec![];
collect_rs_files(&crate_config.crate_dir, &mut files_to_check);
+8 -6
View File
@@ -7,7 +7,7 @@ pub struct Clean {}
impl Clean {
pub fn clean(self, bin: Option<PathBuf>) -> Result<()> {
let crate_config = crate::CrateConfig::new(bin)?;
let crate_config = dioxus_cli_config::CrateConfig::new(bin)?;
let output = Command::new("cargo")
.arg("clean")
@@ -19,15 +19,17 @@ impl Clean {
return custom_error!("Cargo clean failed.");
}
let out_dir = crate_config
.dioxus_config
.application
.out_dir
.unwrap_or_else(|| PathBuf::from("dist"));
let out_dir = crate_config.dioxus_config.application.out_dir;
if crate_config.crate_dir.join(&out_dir).is_dir() {
remove_dir_all(crate_config.crate_dir.join(&out_dir))?;
}
let fullstack_out_dir = crate_config.crate_dir.join(".dioxus");
if fullstack_out_dir.is_dir() {
remove_dir_all(fullstack_out_dir)?;
}
Ok(())
}
}
+7 -2
View File
@@ -1,3 +1,5 @@
use dioxus_cli_config::crate_root;
use super::*;
/// Dioxus config file controls
@@ -26,7 +28,7 @@ pub enum Config {
impl Config {
pub fn config(self) -> Result<()> {
let crate_root = crate::cargo::crate_root()?;
let crate_root = crate_root()?;
match self {
Config::Init {
name,
@@ -48,7 +50,10 @@ impl Config {
log::info!("🚩 Init config file completed.");
}
Config::FormatPrint {} => {
println!("{:#?}", crate::CrateConfig::new(None)?.dioxus_config);
println!(
"{:#?}",
dioxus_cli_config::CrateConfig::new(None)?.dioxus_config
);
}
Config::CustomHtml {} => {
let html_path = crate_root.join("index.html");
+2 -1
View File
@@ -15,9 +15,10 @@ use crate::{
cfg::{ConfigOptsBuild, ConfigOptsServe},
custom_error,
error::Result,
gen_page, server, CrateConfig, Error,
gen_page, server, Error,
};
use clap::{Parser, Subcommand};
use dioxus_cli_config::CrateConfig;
use html_parser::Dom;
use serde::Deserialize;
use std::{
+28 -19
View File
@@ -1,3 +1,5 @@
use dioxus_cli_config::Platform;
use super::*;
use std::{fs::create_dir_all, io::Write, path::PathBuf};
@@ -11,7 +13,8 @@ pub struct Serve {
impl Serve {
pub async fn serve(self, bin: Option<PathBuf>) -> Result<()> {
let mut crate_config = crate::CrateConfig::new(bin)?;
let mut crate_config = dioxus_cli_config::CrateConfig::new(bin)?;
let serve_cfg = self.serve.clone();
// change the relase state.
crate_config.with_hot_reload(self.serve.hot_reload);
@@ -31,8 +34,11 @@ impl Serve {
crate_config.set_features(self.serve.features.unwrap());
}
// Subdirectories don't work with the server
crate_config.dioxus_config.web.app.base_path = None;
if let Some(target) = self.serve.target {
crate_config.set_target(target);
}
crate_config.set_cargo_args(self.serve.cargo_args);
let platform = self
.serve
@@ -40,32 +46,35 @@ impl Serve {
.unwrap_or(crate_config.dioxus_config.application.default_platform);
match platform {
cfg::Platform::Web => {
Platform::Web => {
// generate dev-index page
Serve::regen_dev_page(&crate_config)?;
Serve::regen_dev_page(&crate_config, self.serve.skip_assets)?;
// start the develop server
server::web::startup(self.serve.port, crate_config.clone(), self.serve.open)
.await?;
server::web::startup(
self.serve.port,
crate_config.clone(),
self.serve.open,
self.serve.skip_assets,
)
.await?;
}
cfg::Platform::Desktop => {
server::desktop::startup(crate_config.clone()).await?;
Platform::Desktop => {
server::desktop::startup(crate_config.clone(), &serve_cfg).await?;
}
Platform::Fullstack => {
server::fullstack::startup(crate_config.clone(), &serve_cfg).await?;
}
}
Ok(())
}
pub fn regen_dev_page(crate_config: &CrateConfig) -> Result<()> {
let serve_html = gen_page(&crate_config.dioxus_config, true);
pub fn regen_dev_page(crate_config: &CrateConfig, skip_assets: bool) -> Result<()> {
let serve_html = gen_page(crate_config, true, skip_assets);
let dist_path = crate_config.crate_dir.join(
crate_config
.dioxus_config
.application
.out_dir
.clone()
.unwrap_or_else(|| PathBuf::from("dist")),
);
let dist_path = crate_config
.crate_dir
.join(crate_config.dioxus_config.application.out_dir.clone());
if !dist_path.is_dir() {
create_dir_all(&dist_path)?;
}
-582
View File
@@ -1,582 +0,0 @@
use crate::{cfg::Platform, error::Result};
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
path::{Path, PathBuf},
};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DioxusConfig {
pub application: ApplicationConfig,
pub web: WebConfig,
#[serde(default)]
pub bundle: BundleConfig,
#[serde(default = "default_plugin")]
pub plugin: toml::Value,
}
fn default_plugin() -> toml::Value {
toml::Value::Boolean(true)
}
impl DioxusConfig {
pub fn load(bin: Option<PathBuf>) -> crate::error::Result<Option<DioxusConfig>> {
let crate_dir = crate::cargo::crate_root();
let crate_dir = match crate_dir {
Ok(dir) => {
if let Some(bin) = bin {
dir.join(bin)
} else {
dir
}
}
Err(_) => return Ok(None),
};
let crate_dir = crate_dir.as_path();
let Some(dioxus_conf_file) = acquire_dioxus_toml(crate_dir) else {
return Ok(None);
};
let dioxus_conf_file = dioxus_conf_file.as_path();
let cfg = toml::from_str::<DioxusConfig>(&std::fs::read_to_string(dioxus_conf_file)?)
.map_err(|err| {
let error_location = dioxus_conf_file
.strip_prefix(crate_dir)
.unwrap_or(dioxus_conf_file)
.display();
crate::Error::Unique(format!("{error_location} {err}"))
})
.map(Some);
match cfg {
Ok(Some(mut cfg)) => {
let name = cfg.application.name.clone();
if cfg.bundle.identifier.is_none() {
cfg.bundle.identifier = Some(format!("io.github.{name}"));
}
if cfg.bundle.publisher.is_none() {
cfg.bundle.publisher = Some(name);
}
Ok(Some(cfg))
}
cfg => cfg,
}
}
}
fn acquire_dioxus_toml(dir: &Path) -> Option<PathBuf> {
// prefer uppercase
let uppercase_conf = dir.join("Dioxus.toml");
if uppercase_conf.is_file() {
return Some(uppercase_conf);
}
// lowercase is fine too
let lowercase_conf = dir.join("dioxus.toml");
if lowercase_conf.is_file() {
return Some(lowercase_conf);
}
None
}
impl Default for DioxusConfig {
fn default() -> Self {
let name = "name";
Self {
application: ApplicationConfig {
name: name.into(),
default_platform: Platform::Web,
out_dir: Some(PathBuf::from("dist")),
asset_dir: Some(PathBuf::from("public")),
tools: None,
sub_package: None,
},
web: WebConfig {
app: WebAppConfig {
title: Some("dioxus | ⛺".into()),
base_path: None,
},
proxy: Some(vec![]),
watcher: WebWatcherConfig {
watch_path: Some(vec![PathBuf::from("src"), PathBuf::from("examples")]),
reload_html: Some(false),
index_on_404: Some(true),
},
resource: WebResourceConfig {
dev: WebDevResourceConfig {
style: Some(vec![]),
script: Some(vec![]),
},
style: Some(vec![]),
script: Some(vec![]),
},
https: WebHttpsConfig {
enabled: None,
mkcert: None,
key_path: None,
cert_path: None,
},
},
bundle: BundleConfig {
identifier: Some(format!("io.github.{name}")),
publisher: Some(name.into()),
..Default::default()
},
plugin: toml::Value::Table(toml::map::Map::new()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApplicationConfig {
pub name: String,
pub default_platform: Platform,
pub out_dir: Option<PathBuf>,
pub asset_dir: Option<PathBuf>,
pub tools: Option<HashMap<String, toml::Value>>,
pub sub_package: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebConfig {
pub app: WebAppConfig,
pub proxy: Option<Vec<WebProxyConfig>>,
pub watcher: WebWatcherConfig,
pub resource: WebResourceConfig,
#[serde(default)]
pub https: WebHttpsConfig,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebAppConfig {
pub title: Option<String>,
pub base_path: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebProxyConfig {
pub backend: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebWatcherConfig {
pub watch_path: Option<Vec<PathBuf>>,
pub reload_html: Option<bool>,
pub index_on_404: Option<bool>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebResourceConfig {
pub dev: WebDevResourceConfig,
pub style: Option<Vec<PathBuf>>,
pub script: Option<Vec<PathBuf>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebDevResourceConfig {
pub style: Option<Vec<PathBuf>>,
pub script: Option<Vec<PathBuf>>,
}
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct WebHttpsConfig {
pub enabled: Option<bool>,
pub mkcert: Option<bool>,
pub key_path: Option<String>,
pub cert_path: Option<String>,
}
#[derive(Debug, Clone)]
pub struct CrateConfig {
pub out_dir: PathBuf,
pub crate_dir: PathBuf,
pub workspace_dir: PathBuf,
pub target_dir: PathBuf,
pub asset_dir: PathBuf,
pub manifest: cargo_toml::Manifest<cargo_toml::Value>,
pub executable: ExecutableType,
pub dioxus_config: DioxusConfig,
pub release: bool,
pub hot_reload: bool,
pub cross_origin_policy: bool,
pub verbose: bool,
pub custom_profile: Option<String>,
pub features: Option<Vec<String>>,
}
#[derive(Debug, Clone)]
pub enum ExecutableType {
Binary(String),
Lib(String),
Example(String),
}
impl CrateConfig {
pub fn new(bin: Option<PathBuf>) -> Result<Self> {
let dioxus_config = DioxusConfig::load(bin.clone())?.unwrap_or_default();
let crate_root = crate::cargo::crate_root()?;
let crate_dir = if let Some(package) = &dioxus_config.application.sub_package {
crate_root.join(package)
} else if let Some(bin) = bin {
crate_root.join(bin)
} else {
crate_root
};
let meta = crate::cargo::Metadata::get()?;
let workspace_dir = meta.workspace_root;
let target_dir = meta.target_directory;
let out_dir = match dioxus_config.application.out_dir {
Some(ref v) => crate_dir.join(v),
None => crate_dir.join("dist"),
};
let cargo_def = &crate_dir.join("Cargo.toml");
let asset_dir = match dioxus_config.application.asset_dir {
Some(ref v) => crate_dir.join(v),
None => crate_dir.join("public"),
};
let manifest = cargo_toml::Manifest::from_path(cargo_def).unwrap();
let mut output_filename = String::from("dioxus_app");
if let Some(package) = &manifest.package.as_ref() {
output_filename = match &package.default_run {
Some(default_run_target) => default_run_target.to_owned(),
None => manifest
.bin
.iter()
.find(|b| b.name == manifest.package.as_ref().map(|pkg| pkg.name.clone()))
.or(manifest
.bin
.iter()
.find(|b| b.path == Some("src/main.rs".to_owned())))
.or(manifest.bin.first())
.or(manifest.lib.as_ref())
.and_then(|prod| prod.name.clone())
.unwrap_or(String::from("dioxus_app")),
};
}
let executable = ExecutableType::Binary(output_filename);
let release = false;
let hot_reload = false;
let verbose = false;
let custom_profile = None;
let features = None;
Ok(Self {
out_dir,
crate_dir,
workspace_dir,
target_dir,
asset_dir,
manifest,
executable,
release,
dioxus_config,
hot_reload,
cross_origin_policy: false,
custom_profile,
features,
verbose,
})
}
pub fn as_example(&mut self, example_name: String) -> &mut Self {
self.executable = ExecutableType::Example(example_name);
self
}
pub fn with_release(&mut self, release: bool) -> &mut Self {
self.release = release;
self
}
pub fn with_hot_reload(&mut self, hot_reload: bool) -> &mut Self {
self.hot_reload = hot_reload;
self
}
pub fn with_cross_origin_policy(&mut self, cross_origin_policy: bool) -> &mut Self {
self.cross_origin_policy = cross_origin_policy;
self
}
pub fn with_verbose(&mut self, verbose: bool) -> &mut Self {
self.verbose = verbose;
self
}
pub fn set_profile(&mut self, profile: String) -> &mut Self {
self.custom_profile = Some(profile);
self
}
pub fn set_features(&mut self, features: Vec<String>) -> &mut Self {
self.features = Some(features);
self
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct BundleConfig {
pub identifier: Option<String>,
pub publisher: Option<String>,
pub icon: Option<Vec<String>>,
pub resources: Option<Vec<String>>,
pub copyright: Option<String>,
pub category: Option<String>,
pub short_description: Option<String>,
pub long_description: Option<String>,
pub external_bin: Option<Vec<String>>,
pub deb: Option<DebianSettings>,
pub macos: Option<MacOsSettings>,
pub windows: Option<WindowsSettings>,
}
impl From<BundleConfig> for tauri_bundler::BundleSettings {
fn from(val: BundleConfig) -> Self {
tauri_bundler::BundleSettings {
identifier: val.identifier,
publisher: val.publisher,
icon: val.icon,
resources: val.resources,
copyright: val.copyright,
category: val.category.and_then(|c| c.parse().ok()),
short_description: val.short_description,
long_description: val.long_description,
external_bin: val.external_bin,
deb: val.deb.map(Into::into).unwrap_or_default(),
macos: val.macos.map(Into::into).unwrap_or_default(),
windows: val.windows.map(Into::into).unwrap_or_default(),
..Default::default()
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct DebianSettings {
pub depends: Option<Vec<String>>,
pub files: HashMap<PathBuf, PathBuf>,
pub nsis: Option<NsisSettings>,
}
impl From<DebianSettings> for tauri_bundler::DebianSettings {
fn from(val: DebianSettings) -> Self {
tauri_bundler::DebianSettings {
depends: val.depends,
files: val.files,
desktop_template: None,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct WixSettings {
pub language: Vec<(String, Option<PathBuf>)>,
pub template: Option<PathBuf>,
pub fragment_paths: Vec<PathBuf>,
pub component_group_refs: Vec<String>,
pub component_refs: Vec<String>,
pub feature_group_refs: Vec<String>,
pub feature_refs: Vec<String>,
pub merge_refs: Vec<String>,
pub skip_webview_install: bool,
pub license: Option<PathBuf>,
pub enable_elevated_update_task: bool,
pub banner_path: Option<PathBuf>,
pub dialog_image_path: Option<PathBuf>,
pub fips_compliant: bool,
}
impl From<WixSettings> for tauri_bundler::WixSettings {
fn from(val: WixSettings) -> Self {
tauri_bundler::WixSettings {
language: tauri_bundler::bundle::WixLanguage({
let mut languages: Vec<_> = val
.language
.iter()
.map(|l| {
(
l.0.clone(),
tauri_bundler::bundle::WixLanguageConfig {
locale_path: l.1.clone(),
},
)
})
.collect();
if languages.is_empty() {
languages.push(("en-US".into(), Default::default()));
}
languages
}),
template: val.template,
fragment_paths: val.fragment_paths,
component_group_refs: val.component_group_refs,
component_refs: val.component_refs,
feature_group_refs: val.feature_group_refs,
feature_refs: val.feature_refs,
merge_refs: val.merge_refs,
skip_webview_install: val.skip_webview_install,
license: val.license,
enable_elevated_update_task: val.enable_elevated_update_task,
banner_path: val.banner_path,
dialog_image_path: val.dialog_image_path,
fips_compliant: val.fips_compliant,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct MacOsSettings {
pub frameworks: Option<Vec<String>>,
pub minimum_system_version: Option<String>,
pub license: Option<String>,
pub exception_domain: Option<String>,
pub signing_identity: Option<String>,
pub provider_short_name: Option<String>,
pub entitlements: Option<String>,
pub info_plist_path: Option<PathBuf>,
}
impl From<MacOsSettings> for tauri_bundler::MacOsSettings {
fn from(val: MacOsSettings) -> Self {
tauri_bundler::MacOsSettings {
frameworks: val.frameworks,
minimum_system_version: val.minimum_system_version,
license: val.license,
exception_domain: val.exception_domain,
signing_identity: val.signing_identity,
provider_short_name: val.provider_short_name,
entitlements: val.entitlements,
info_plist_path: val.info_plist_path,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WindowsSettings {
pub digest_algorithm: Option<String>,
pub certificate_thumbprint: Option<String>,
pub timestamp_url: Option<String>,
pub tsp: bool,
pub wix: Option<WixSettings>,
pub icon_path: Option<PathBuf>,
pub webview_install_mode: WebviewInstallMode,
pub webview_fixed_runtime_path: Option<PathBuf>,
pub allow_downgrades: bool,
pub nsis: Option<NsisSettings>,
}
impl From<WindowsSettings> for tauri_bundler::WindowsSettings {
fn from(val: WindowsSettings) -> Self {
tauri_bundler::WindowsSettings {
digest_algorithm: val.digest_algorithm,
certificate_thumbprint: val.certificate_thumbprint,
timestamp_url: val.timestamp_url,
tsp: val.tsp,
wix: val.wix.map(Into::into),
icon_path: val.icon_path.unwrap_or("icons/icon.ico".into()),
webview_install_mode: val.webview_install_mode.into(),
webview_fixed_runtime_path: val.webview_fixed_runtime_path,
allow_downgrades: val.allow_downgrades,
nsis: val.nsis.map(Into::into),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NsisSettings {
pub template: Option<PathBuf>,
pub license: Option<PathBuf>,
pub header_image: Option<PathBuf>,
pub sidebar_image: Option<PathBuf>,
pub installer_icon: Option<PathBuf>,
pub install_mode: NSISInstallerMode,
pub languages: Option<Vec<String>>,
pub custom_language_files: Option<HashMap<String, PathBuf>>,
pub display_language_selector: bool,
}
impl From<NsisSettings> for tauri_bundler::NsisSettings {
fn from(val: NsisSettings) -> Self {
tauri_bundler::NsisSettings {
license: val.license,
header_image: val.header_image,
sidebar_image: val.sidebar_image,
installer_icon: val.installer_icon,
install_mode: val.install_mode.into(),
languages: val.languages,
display_language_selector: val.display_language_selector,
custom_language_files: None,
template: None,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum NSISInstallerMode {
CurrentUser,
PerMachine,
Both,
}
impl From<NSISInstallerMode> for tauri_utils::config::NSISInstallerMode {
fn from(val: NSISInstallerMode) -> Self {
match val {
NSISInstallerMode::CurrentUser => tauri_utils::config::NSISInstallerMode::CurrentUser,
NSISInstallerMode::PerMachine => tauri_utils::config::NSISInstallerMode::PerMachine,
NSISInstallerMode::Both => tauri_utils::config::NSISInstallerMode::Both,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum WebviewInstallMode {
Skip,
DownloadBootstrapper { silent: bool },
EmbedBootstrapper { silent: bool },
OfflineInstaller { silent: bool },
FixedRuntime { path: PathBuf },
}
impl WebviewInstallMode {
fn into(self) -> tauri_utils::config::WebviewInstallMode {
match self {
Self::Skip => tauri_utils::config::WebviewInstallMode::Skip,
Self::DownloadBootstrapper { silent } => {
tauri_utils::config::WebviewInstallMode::DownloadBootstrapper { silent }
}
Self::EmbedBootstrapper { silent } => {
tauri_utils::config::WebviewInstallMode::EmbedBootstrapper { silent }
}
Self::OfflineInstaller { silent } => {
tauri_utils::config::WebviewInstallMode::OfflineInstaller { silent }
}
Self::FixedRuntime { path } => {
tauri_utils::config::WebviewInstallMode::FixedRuntime { path }
}
}
}
}
impl Default for WebviewInstallMode {
fn default() -> Self {
Self::OfflineInstaller { silent: false }
}
}
+18
View File
@@ -72,6 +72,24 @@ impl From<hyper::Error> for Error {
}
}
impl From<dioxus_cli_config::LoadDioxusConfigError> for Error {
fn from(e: dioxus_cli_config::LoadDioxusConfigError) -> Self {
Self::RuntimeError(e.to_string())
}
}
impl From<dioxus_cli_config::CargoError> for Error {
fn from(e: dioxus_cli_config::CargoError) -> Self {
Self::CargoError(e.to_string())
}
}
impl From<dioxus_cli_config::CrateConfigError> for Error {
fn from(e: dioxus_cli_config::CrateConfigError) -> Self {
Self::RuntimeError(e.to_string())
}
}
#[macro_export]
macro_rules! custom_error {
($msg:literal $(,)?) => {
+1 -6
View File
@@ -4,21 +4,16 @@
pub const DIOXUS_CLI_VERSION: &str = "0.4.1";
mod assets;
pub mod builder;
pub mod server;
pub mod tools;
pub use builder::*;
pub mod cargo;
pub use cargo::*;
pub mod cli;
pub use cli::*;
pub mod config;
pub use config::*;
pub mod error;
pub use error::*;
+17 -13
View File
@@ -1,3 +1,4 @@
use dioxus_cli_config::DioxusConfig;
use std::path::PathBuf;
use anyhow::anyhow;
@@ -42,34 +43,36 @@ async fn main() -> anyhow::Result<()> {
set_up_logging();
let bin = get_bin(args.bin)?;
let bin = get_bin(args.bin);
let _dioxus_config = DioxusConfig::load(Some(bin.clone()))
if let Ok(bin) = &bin {
let _dioxus_config = DioxusConfig::load(Some(bin.clone()))
.map_err(|e| anyhow!("Failed to load Dioxus config because: {e}"))?
.unwrap_or_else(|| {
log::warn!("You appear to be creating a Dioxus project from scratch; we will use the default config");
DioxusConfig::default()
});
#[cfg(feature = "plugin")]
PluginManager::init(_dioxus_config.plugin)
.map_err(|e| anyhow!("🚫 Plugin system initialization failed: {e}"))?;
#[cfg(feature = "plugin")]
PluginManager::init(_dioxus_config.plugin)
.map_err(|e| anyhow!("🚫 Plugin system initialization failed: {e}"))?;
}
match args.action {
Translate(opts) => opts
.translate()
.map_err(|e| anyhow!("🚫 Translation of HTML into RSX failed: {}", e)),
Build(opts) => opts
.build(Some(bin.clone()))
Build(opts) if bin.is_ok() => opts
.build(Some(bin.unwrap().clone()), None)
.map_err(|e| anyhow!("🚫 Building project failed: {}", e)),
Clean(opts) => opts
.clean(Some(bin.clone()))
Clean(opts) if bin.is_ok() => opts
.clean(Some(bin.unwrap().clone()))
.map_err(|e| anyhow!("🚫 Cleaning project failed: {}", e)),
Serve(opts) => opts
.serve(Some(bin.clone()))
Serve(opts) if bin.is_ok() => opts
.serve(Some(bin.unwrap().clone()))
.await
.map_err(|e| anyhow!("🚫 Serving project failed: {}", e)),
@@ -81,8 +84,8 @@ async fn main() -> anyhow::Result<()> {
.config()
.map_err(|e| anyhow!("🚫 Configuring new project failed: {}", e)),
Bundle(opts) => opts
.bundle(Some(bin.clone()))
Bundle(opts) if bin.is_ok() => opts
.bundle(Some(bin.unwrap().clone()))
.map_err(|e| anyhow!("🚫 Bundling project failed: {}", e)),
#[cfg(feature = "plugin")]
@@ -107,5 +110,6 @@ async fn main() -> anyhow::Result<()> {
Ok(())
}
_ => Err(anyhow::anyhow!(bin.unwrap_err())),
}
}
+83 -36
View File
@@ -1,10 +1,14 @@
use crate::server::Platform;
use crate::{
cfg::ConfigOptsServe,
server::{
output::{print_console_info, PrettierOptions},
setup_file_watcher,
},
BuildResult, CrateConfig, Result,
BuildResult, Result,
};
use dioxus_cli_config::CrateConfig;
use dioxus_cli_config::ExecutableType;
use dioxus_hot_reload::HotReloadMsg;
use dioxus_html::HtmlCtx;
@@ -21,7 +25,14 @@ use plugin::PluginManager;
use super::HotReloadState;
pub async fn startup(config: CrateConfig) -> Result<()> {
pub async fn startup(config: CrateConfig, serve: &ConfigOptsServe) -> Result<()> {
startup_with_platform::<DesktopPlatform>(config, serve).await
}
pub(crate) async fn startup_with_platform<P: Platform + Send + 'static>(
config: CrateConfig,
serve_cfg: &ConfigOptsServe,
) -> Result<()> {
// ctrl-c shutdown checker
let _crate_config = config.clone();
let _ = ctrlc::set_handler(move || {
@@ -51,15 +62,18 @@ pub async fn startup(config: CrateConfig) -> Result<()> {
false => None,
};
serve(config, hot_reload_state).await?;
serve::<P>(config, serve_cfg, hot_reload_state).await?;
Ok(())
}
/// Start the server without hot reload
pub async fn serve(config: CrateConfig, hot_reload_state: Option<HotReloadState>) -> Result<()> {
let (child, first_build_result) = start_desktop(&config)?;
let currently_running_child: RwLock<Child> = RwLock::new(child);
async fn serve<P: Platform + Send + 'static>(
config: CrateConfig,
serve: &ConfigOptsServe,
hot_reload_state: Option<HotReloadState>,
) -> Result<()> {
let platform = RwLock::new(P::start(&config, serve)?);
log::info!("🚀 Starting development server...");
@@ -68,15 +82,7 @@ pub async fn serve(config: CrateConfig, hot_reload_state: Option<HotReloadState>
let _watcher = setup_file_watcher(
{
let config = config.clone();
move || {
let mut current_child = currently_running_child.write().unwrap();
log::trace!("Killing old process");
current_child.kill()?;
let (child, result) = start_desktop(&config)?;
*current_child = child;
Ok(result)
}
move || platform.write().unwrap().rebuild(&config)
},
&config,
None,
@@ -84,19 +90,9 @@ pub async fn serve(config: CrateConfig, hot_reload_state: Option<HotReloadState>
)
.await?;
// Print serve info
print_console_info(
&config,
PrettierOptions {
changed: vec![],
warnings: first_build_result.warnings,
elapsed_time: first_build_result.elapsed_time,
},
None,
);
match hot_reload_state {
Some(hot_reload_state) => {
// The open interprocess sockets
start_desktop_hot_reload(hot_reload_state).await?;
}
None => {
@@ -154,7 +150,11 @@ async fn start_desktop_hot_reload(hot_reload_state: HotReloadState) -> Result<()
println!("Connected to hot reloading 🚀");
}
Err(err) => {
if err.kind() != std::io::ErrorKind::WouldBlock {
let error_string = err.to_string();
// Filter out any error messages about a operation that may block and an error message that triggers on some operating systems that says "Waiting for a process to open the other end of the pipe" without WouldBlock being set
let display_error = err.kind() != std::io::ErrorKind::WouldBlock
&& !error_string.contains("Waiting for a process");
if display_error {
println!("Error connecting to hot reloading: {} (Hot reloading is a feature of the dioxus-cli. If you are not using the CLI, this error can be ignored)", err);
}
}
@@ -188,7 +188,7 @@ async fn start_desktop_hot_reload(hot_reload_state: HotReloadState) -> Result<()
}
fn clear_paths(file_socket_path: &std::path::Path) {
if cfg!(target_os = "macos") {
if cfg!(unix) {
// On unix, if you force quit the application, it can leave the file socket open
// This will cause the local socket listener to fail to open
// We check if the file socket is already open from an old session and then delete it
@@ -213,23 +213,70 @@ fn send_msg(msg: HotReloadMsg, channel: &mut impl std::io::Write) -> bool {
}
}
pub fn start_desktop(config: &CrateConfig) -> Result<(Child, BuildResult)> {
fn start_desktop(config: &CrateConfig, skip_assets: bool) -> Result<(RAIIChild, BuildResult)> {
// Run the desktop application
log::trace!("Building application");
let result = crate::builder::build_desktop(config, true)?;
let result = crate::builder::build_desktop(config, true, skip_assets)?;
match &config.executable {
crate::ExecutableType::Binary(name)
| crate::ExecutableType::Lib(name)
| crate::ExecutableType::Example(name) => {
ExecutableType::Binary(name)
| ExecutableType::Lib(name)
| ExecutableType::Example(name) => {
let mut file = config.out_dir.join(name);
if cfg!(windows) {
file.set_extension("exe");
}
log::trace!("Running application from {:?}", file);
let child = Command::new(file.to_str().unwrap()).spawn()?;
let active = "DIOXUS_ACTIVE";
let child = RAIIChild(
Command::new(file.to_str().unwrap())
.env(active, "true")
.spawn()?,
);
Ok((child, result))
}
}
}
pub(crate) struct DesktopPlatform {
currently_running_child: RAIIChild,
skip_assets: bool,
}
impl Platform for DesktopPlatform {
fn start(config: &CrateConfig, serve: &ConfigOptsServe) -> Result<Self> {
let (child, first_build_result) = start_desktop(config, serve.skip_assets)?;
log::info!("🚀 Starting development server...");
// Print serve info
print_console_info(
config,
PrettierOptions {
changed: vec![],
warnings: first_build_result.warnings,
elapsed_time: first_build_result.elapsed_time,
},
None,
);
Ok(Self {
currently_running_child: child,
skip_assets: serve.skip_assets,
})
}
fn rebuild(&mut self, config: &CrateConfig) -> Result<BuildResult> {
self.currently_running_child.0.kill()?;
let (child, result) = start_desktop(config, self.skip_assets)?;
self.currently_running_child = child;
Ok(result)
}
}
struct RAIIChild(Child);
impl Drop for RAIIChild {
fn drop(&mut self) {
let _ = self.0.kill();
}
}
+164
View File
@@ -0,0 +1,164 @@
use dioxus_cli_config::CrateConfig;
use crate::{
assets::WebAssetConfigDropGuard,
cfg::{ConfigOptsBuild, ConfigOptsServe},
Result,
};
use super::{desktop, Platform};
pub async fn startup(config: CrateConfig, serve: &ConfigOptsServe) -> Result<()> {
desktop::startup_with_platform::<FullstackPlatform>(config, serve).await
}
fn start_web_build_thread(
config: &CrateConfig,
serve: &ConfigOptsServe,
) -> std::thread::JoinHandle<Result<()>> {
let serve = serve.clone();
let target_directory = config.crate_dir.join(".dioxus").join("web");
std::fs::create_dir_all(&target_directory).unwrap();
std::thread::spawn(move || build_web(serve, &target_directory))
}
struct FullstackPlatform {
serve: ConfigOptsServe,
desktop: desktop::DesktopPlatform,
_config: WebAssetConfigDropGuard,
}
impl Platform for FullstackPlatform {
fn start(config: &CrateConfig, serve: &ConfigOptsServe) -> Result<Self>
where
Self: Sized,
{
let thread_handle = start_web_build_thread(config, serve);
let mut desktop_config = config.clone();
let desktop_feature = serve.server_feature.clone();
let features = &mut desktop_config.features;
match features {
Some(features) => {
features.push(desktop_feature);
}
None => desktop_config.features = Some(vec![desktop_feature]),
};
let config = WebAssetConfigDropGuard::new();
let desktop = desktop::DesktopPlatform::start(&desktop_config, serve)?;
thread_handle
.join()
.map_err(|_| anyhow::anyhow!("Failed to join thread"))??;
Ok(Self {
desktop,
serve: serve.clone(),
_config: config,
})
}
fn rebuild(&mut self, crate_config: &CrateConfig) -> Result<crate::BuildResult> {
let thread_handle = start_web_build_thread(crate_config, &self.serve);
let result = {
let mut desktop_config = crate_config.clone();
let desktop_feature = self.serve.server_feature.clone();
let features = &mut desktop_config.features;
match features {
Some(features) => {
features.push(desktop_feature);
}
None => desktop_config.features = Some(vec![desktop_feature]),
};
let _gaurd = FullstackServerEnvGuard::new(self.serve.force_debug, self.serve.release);
self.desktop.rebuild(&desktop_config)
};
thread_handle
.join()
.map_err(|_| anyhow::anyhow!("Failed to join thread"))??;
result
}
}
fn build_web(serve: ConfigOptsServe, target_directory: &std::path::Path) -> Result<()> {
let mut web_config: ConfigOptsBuild = serve.into();
let web_feature = web_config.client_feature.clone();
let features = &mut web_config.features;
match features {
Some(features) => {
features.push(web_feature);
}
None => web_config.features = Some(vec![web_feature]),
};
web_config.platform = Some(dioxus_cli_config::Platform::Web);
let _gaurd = FullstackWebEnvGuard::new(&web_config);
crate::cli::build::Build { build: web_config }.build(None, Some(target_directory))
}
// Debug mode web builds have a very large size by default. If debug mode is not enabled, we strip some of the debug info by default
// This reduces a hello world from ~40MB to ~2MB
pub(crate) struct FullstackWebEnvGuard {
old_rustflags: Option<String>,
}
impl FullstackWebEnvGuard {
pub fn new(serve: &ConfigOptsBuild) -> Self {
Self {
old_rustflags: (!serve.force_debug).then(|| {
let old_rustflags = std::env::var("RUSTFLAGS").unwrap_or_default();
let debug_assertions = if serve.release {
""
} else {
" -C debug-assertions"
};
std::env::set_var(
"RUSTFLAGS",
format!(
"{old_rustflags} -C debuginfo=none -C strip=debuginfo{debug_assertions}"
),
);
old_rustflags
}),
}
}
}
impl Drop for FullstackWebEnvGuard {
fn drop(&mut self) {
if let Some(old_rustflags) = self.old_rustflags.take() {
std::env::set_var("RUSTFLAGS", old_rustflags);
}
}
}
// Debug mode web builds have a very large size by default. If debug mode is not enabled, we strip some of the debug info by default
// This reduces a hello world from ~40MB to ~2MB
pub(crate) struct FullstackServerEnvGuard {
old_rustflags: Option<String>,
}
impl FullstackServerEnvGuard {
pub fn new(debug: bool, release: bool) -> Self {
Self {
old_rustflags: (!debug).then(|| {
let old_rustflags = std::env::var("RUSTFLAGS").unwrap_or_default();
let debug_assertions = if release { "" } else { " -C debug-assertions" };
std::env::set_var(
"RUSTFLAGS",
format!("{old_rustflags} -C opt-level=2 {debug_assertions}"),
);
old_rustflags
}),
}
}
}
impl Drop for FullstackServerEnvGuard {
fn drop(&mut self) {
if let Some(old_rustflags) = self.old_rustflags.take() {
std::env::set_var("RUSTFLAGS", old_rustflags);
}
}
}
+12 -12
View File
@@ -1,19 +1,18 @@
use crate::{BuildResult, CrateConfig, Result};
use crate::{cfg::ConfigOptsServe, BuildResult, Result};
use dioxus_cli_config::CrateConfig;
use cargo_metadata::diagnostic::Diagnostic;
use dioxus_core::Template;
use dioxus_html::HtmlCtx;
use dioxus_rsx::hot_reload::*;
use notify::{RecommendedWatcher, Watcher};
use std::{
path::PathBuf,
sync::{Arc, Mutex},
};
use std::sync::{Arc, Mutex};
use tokio::sync::broadcast::{self};
mod output;
use output::*;
pub mod desktop;
pub mod fullstack;
pub mod web;
/// Sets up a file watcher
@@ -26,13 +25,7 @@ async fn setup_file_watcher<F: Fn() -> Result<BuildResult> + Send + 'static>(
let mut last_update_time = chrono::Local::now().timestamp();
// file watcher: check file change
let allow_watch_path = config
.dioxus_config
.web
.watcher
.watch_path
.clone()
.unwrap_or_else(|| vec![PathBuf::from("src"), PathBuf::from("examples")]);
let allow_watch_path = config.dioxus_config.web.watcher.watch_path.clone();
let watcher_config = config.clone();
let mut watcher = notify::recommended_watcher(move |info: notify::Result<notify::Event>| {
@@ -141,6 +134,13 @@ async fn setup_file_watcher<F: Fn() -> Result<BuildResult> + Send + 'static>(
Ok(watcher)
}
pub(crate) trait Platform {
fn start(config: &CrateConfig, serve: &ConfigOptsServe) -> Result<Self>
where
Self: Sized;
fn rebuild(&mut self, config: &CrateConfig) -> Result<BuildResult>;
}
#[derive(Clone)]
pub struct HotReloadState {
pub messages: broadcast::Sender<Template<'static>>,
+9 -16
View File
@@ -1,6 +1,7 @@
use crate::server::Diagnostic;
use crate::CrateConfig;
use colored::Colorize;
use dioxus_cli_config::crate_root;
use dioxus_cli_config::CrateConfig;
use std::path::PathBuf;
use std::process::Command;
@@ -43,25 +44,19 @@ pub fn print_console_info(
profile = config.custom_profile.as_ref().unwrap().to_string();
}
let hot_reload = if config.hot_reload { "RSX" } else { "Normal" };
let crate_root = crate::cargo::crate_root().unwrap();
let crate_root = crate_root().unwrap();
let custom_html_file = if crate_root.join("index.html").is_file() {
"Custom [index.html]"
} else {
"Default"
};
let url_rewrite = if config
.dioxus_config
.web
.watcher
.index_on_404
.unwrap_or(false)
{
let url_rewrite = if config.dioxus_config.web.watcher.index_on_404 {
"True"
} else {
"False"
};
let proxies = config.dioxus_config.web.proxy.as_ref();
let proxies = &config.dioxus_config.web.proxy;
if options.changed.is_empty() {
println!(
@@ -109,12 +104,10 @@ pub fn print_console_info(
println!();
println!("\t> Profile : {}", profile.green());
println!("\t> Hot Reload : {}", hot_reload.cyan());
if let Some(proxies) = proxies {
if !proxies.is_empty() {
println!("\t> Proxies :");
for proxy in proxies {
println!("\t\t- {}", proxy.backend.blue());
}
if !proxies.is_empty() {
println!("\t> Proxies :");
for proxy in proxies {
println!("\t\t- {}", proxy.backend.blue());
}
}
println!("\t> Index Template : {}", custom_html_file.green());
+47 -22
View File
@@ -5,12 +5,13 @@ use crate::{
output::{print_console_info, PrettierOptions, WebServerInfo},
setup_file_watcher, HotReloadState,
},
BuildResult, CrateConfig, Result, WebHttpsConfig,
BuildResult, Result,
};
use axum::{
body::{Full, HttpBody},
extract::{ws::Message, Extension, TypedHeader, WebSocketUpgrade},
http::{
self,
header::{HeaderName, HeaderValue},
Method, Response, StatusCode,
},
@@ -19,6 +20,8 @@ use axum::{
Router,
};
use axum_server::tls_rustls::RustlsConfig;
use dioxus_cli_config::CrateConfig;
use dioxus_cli_config::WebHttpsConfig;
use dioxus_html::HtmlCtx;
use dioxus_rsx::hot_reload::*;
@@ -47,7 +50,12 @@ struct WsReloadState {
update: broadcast::Sender<()>,
}
pub async fn startup(port: u16, config: CrateConfig, start_browser: bool) -> Result<()> {
pub async fn startup(
port: u16,
config: CrateConfig,
start_browser: bool,
skip_assets: bool,
) -> Result<()> {
// ctrl-c shutdown checker
let _crate_config = config.clone();
let _ = ctrlc::set_handler(move || {
@@ -79,7 +87,15 @@ pub async fn startup(port: u16, config: CrateConfig, start_browser: bool) -> Res
false => None,
};
serve(ip, port, config, start_browser, hot_reload_state).await?;
serve(
ip,
port,
config,
start_browser,
skip_assets,
hot_reload_state,
)
.await?;
Ok(())
}
@@ -90,9 +106,10 @@ pub async fn serve(
port: u16,
config: CrateConfig,
start_browser: bool,
skip_assets: bool,
hot_reload_state: Option<HotReloadState>,
) -> Result<()> {
let first_build_result = crate::builder::build(&config, true)?;
let first_build_result = crate::builder::build(&config, false, skip_assets)?;
log::info!("🚀 Starting development server...");
@@ -105,7 +122,7 @@ pub async fn serve(
{
let config = config.clone();
let reload_tx = reload_tx.clone();
move || build(&config, &reload_tx)
move || build(&config, &reload_tx, skip_assets)
},
&config,
Some(WebServerInfo {
@@ -262,12 +279,7 @@ async fn setup_router(
.override_response_header(HeaderName::from_static("cross-origin-opener-policy"), coop)
.and_then(
move |response: Response<ServeFileSystemResponseBody>| async move {
let response = if file_service_config
.dioxus_config
.web
.watcher
.index_on_404
.unwrap_or(false)
let mut response = if file_service_config.dioxus_config.web.watcher.index_on_404
&& response.status() == StatusCode::NOT_FOUND
{
let body = Full::from(
@@ -290,6 +302,13 @@ async fn setup_router(
} else {
response.map(|body| body.boxed())
};
let headers = response.headers_mut();
headers.insert(
http::header::CACHE_CONTROL,
HeaderValue::from_static("no-cache"),
);
headers.insert(http::header::PRAGMA, HeaderValue::from_static("no-cache"));
headers.insert(http::header::EXPIRES, HeaderValue::from_static("0"));
Ok(response)
},
)
@@ -299,7 +318,7 @@ async fn setup_router(
let mut router = Router::new().route("/_dioxus/ws", get(ws_handler));
// Setup proxy
for proxy_config in config.dioxus_config.web.proxy.unwrap_or_default() {
for proxy_config in config.dioxus_config.web.proxy {
router = proxy::add_proxy(router, &proxy_config)?;
}
@@ -313,6 +332,18 @@ async fn setup_router(
},
));
router = if let Some(base_path) = config.dioxus_config.web.app.base_path.clone() {
let base_path = format!("/{}", base_path.trim_matches('/'));
Router::new()
.nest(&base_path, axum::routing::any_service(router))
.fallback(get(move || {
let base_path = base_path.clone();
async move { format!("Outside of the base path: {}", base_path) }
}))
} else {
router
};
// Setup routes
router = router
.route("/_dioxus/hot_reload", get(hot_reload_handler))
@@ -412,18 +443,12 @@ async fn ws_handler(
})
}
fn build(config: &CrateConfig, reload_tx: &Sender<()>) -> Result<BuildResult> {
let result = builder::build(config, true)?;
fn build(config: &CrateConfig, reload_tx: &Sender<()>, skip_assets: bool) -> Result<BuildResult> {
let result = builder::build(config, true, skip_assets)?;
// change the websocket reload state to true;
// the page will auto-reload.
if config
.dioxus_config
.web
.watcher
.reload_html
.unwrap_or(false)
{
let _ = Serve::regen_dev_page(config);
if config.dioxus_config.web.watcher.reload_html {
let _ = Serve::regen_dev_page(config, skip_assets);
}
let _ = reload_tx.send(());
Ok(result)
+2 -1
View File
@@ -1,4 +1,5 @@
use crate::{Result, WebProxyConfig};
use crate::Result;
use dioxus_cli_config::WebProxyConfig;
use anyhow::Context;
use axum::{http::StatusCode, routing::any, Router};
+2 -1
View File
@@ -15,10 +15,11 @@ proc-macro = true
[dependencies]
proc-macro2 = { version = "1.0" }
quote = "1.0"
syn = { version = "2.0", features = ["full", "extra-traits"] }
syn = { version = "2.0", features = ["full", "extra-traits", "visit"] }
dioxus-rsx = { workspace = true }
dioxus-core = { workspace = true }
constcat = "0.3.0"
convert_case = "^0.6.0"
prettyplease = "0.2.15"
# testing
@@ -58,8 +58,11 @@ impl ToTokens for ComponentDeserializerOutput {
fn to_tokens(&self, tokens: &mut TokenStream2) {
let comp_fn = &self.comp_fn;
let props_struct = &self.props_struct;
let fn_ident = &comp_fn.sig.ident;
let doc = format!("Properties for the [`{fn_ident}`] component.");
tokens.append_all(quote! {
#[doc = #doc]
#props_struct
#[allow(non_snake_case)]
#comp_fn
+277 -24
View File
@@ -24,6 +24,10 @@ pub fn impl_my_derive(ast: &syn::DeriveInput) -> Result<TokenStream, Error> {
.included_fields()
.map(|f| struct_info.field_impl(f))
.collect::<Result<Vec<_>, _>>()?;
let extends = struct_info
.extend_fields()
.map(|f| struct_info.extends_impl(f))
.collect::<Result<Vec<_>, _>>()?;
let fields = quote!(#(#fields)*).into_iter();
let required_fields = struct_info
.included_fields()
@@ -36,6 +40,7 @@ pub fn impl_my_derive(ast: &syn::DeriveInput) -> Result<TokenStream, Error> {
#builder_creation
#conversion_helper
#( #fields )*
#( #extends )*
#( #required_fields )*
#build_method
}
@@ -167,8 +172,8 @@ mod field_info {
use proc_macro2::TokenStream;
use quote::quote;
use syn::spanned::Spanned;
use syn::Expr;
use syn::{parse::Error, punctuated::Punctuated};
use syn::{Expr, Path};
use super::util::{
expr_to_single_string, ident_to_type, path_to_single_string, strip_raw_ident_prefix,
@@ -199,6 +204,13 @@ mod field_info {
);
}
// extended field is automatically empty
if !builder_attr.extends.is_empty() {
builder_attr.default = Some(
syn::parse(quote!(::core::default::Default::default()).into()).unwrap(),
);
}
// auto detect optional
let strip_option_auto = builder_attr.strip_option
|| !builder_attr.ignore_option
@@ -253,6 +265,7 @@ mod field_info {
pub auto_into: bool,
pub strip_option: bool,
pub ignore_option: bool,
pub extends: Vec<Path>,
}
impl FieldBuilderAttr {
@@ -305,6 +318,17 @@ mod field_info {
let name = expr_to_single_string(&assign.left)
.ok_or_else(|| Error::new_spanned(&assign.left, "Expected identifier"))?;
match name.as_str() {
"extends" => {
if let syn::Expr::Path(path) = *assign.right {
self.extends.push(path.path);
Ok(())
} else {
Err(Error::new_spanned(
assign.right,
"Expected simple identifier",
))
}
}
"default" => {
self.default = Some(*assign.right);
Ok(())
@@ -359,6 +383,11 @@ mod field_info {
Ok(())
}
"extend" => {
self.extends.push(path.path);
Ok(())
}
_ => {
macro_rules! handle_fields {
( $( $flag:expr, $field:ident, $already:expr; )* ) => {
@@ -462,11 +491,14 @@ fn type_from_inside_option(ty: &syn::Type, check_option_name: bool) -> Option<&s
}
mod struct_info {
use convert_case::{Case, Casing};
use proc_macro2::TokenStream;
use quote::quote;
use syn::parse::Error;
use syn::punctuated::Punctuated;
use syn::Expr;
use syn::spanned::Spanned;
use syn::visit::Visit;
use syn::{parse_quote, Expr, Ident};
use super::field_info::{FieldBuilderAttr, FieldInfo};
use super::util::{
@@ -489,7 +521,46 @@ mod struct_info {
impl<'a> StructInfo<'a> {
pub fn included_fields(&self) -> impl Iterator<Item = &FieldInfo<'a>> {
self.fields.iter().filter(|f| !f.builder_attr.skip)
self.fields
.iter()
.filter(|f| !f.builder_attr.skip && f.builder_attr.extends.is_empty())
}
pub fn extend_fields(&self) -> impl Iterator<Item = &FieldInfo<'a>> {
self.fields
.iter()
.filter(|f| !f.builder_attr.extends.is_empty())
}
fn extend_lifetime(&self) -> syn::Result<Option<syn::Lifetime>> {
let first_extend = self.extend_fields().next();
match first_extend {
Some(f) => {
struct VisitFirstLifetime(Option<syn::Lifetime>);
impl Visit<'_> for VisitFirstLifetime {
fn visit_lifetime(&mut self, lifetime: &'_ syn::Lifetime) {
if self.0.is_none() {
self.0 = Some(lifetime.clone());
}
}
}
let name = f.name;
let mut visitor = VisitFirstLifetime(None);
visitor.visit_type(f.ty);
visitor.0.ok_or_else(|| {
syn::Error::new_spanned(
name,
"Unable to find lifetime for extended field. Please specify it manually",
)
}).map(Some)
}
None => Ok(None),
}
}
pub fn new(
@@ -536,7 +607,17 @@ mod struct_info {
// Therefore, we will generate code that shortcircuits the "comparison" in memoization
let are_there_generics = !self.generics.params.is_empty();
let (impl_generics, ty_generics, where_clause) = self.generics.split_for_impl();
let extend_lifetime = self.extend_lifetime()?;
let generics = self.generics.clone();
let (_, ty_generics, where_clause) = generics.split_for_impl();
let impl_generics = self.modify_generics(|g| {
if extend_lifetime.is_none() {
g.params.insert(0, parse_quote!('__bump));
}
});
let (impl_generics, _, _) = impl_generics.split_for_impl();
let (_, b_initial_generics, _) = self.generics.split_for_impl();
let all_fields_param = syn::GenericParam::Type(
syn::Ident::new("TypedBuilderFields", proc_macro2::Span::call_site()).into(),
);
@@ -544,7 +625,7 @@ mod struct_info {
g.params.insert(0, all_fields_param.clone());
});
let empties_tuple = type_tuple(self.included_fields().map(|_| empty_type()));
let generics_with_empty = modify_types_generics_hack(&ty_generics, |args| {
let generics_with_empty = modify_types_generics_hack(&b_initial_generics, |args| {
args.insert(0, syn::GenericArgument::Type(empties_tuple.clone().into()));
});
let phantom_generics = self.generics.params.iter().filter_map(|param| match param {
@@ -603,8 +684,7 @@ Finally, call `.build()` to create the instance of `{name}`.
quote!(#[doc(hidden)])
};
let (b_generics_impl, b_generics_ty, b_generics_where_extras_predicates) =
b_generics.split_for_impl();
let (_, _, b_generics_where_extras_predicates) = b_generics.split_for_impl();
let mut b_generics_where: syn::WhereClause = syn::parse2(quote! {
where TypedBuilderFields: Clone
})?;
@@ -624,12 +704,39 @@ Finally, call `.build()` to create the instance of `{name}`.
false => quote! { true },
};
let extend_fields = self.extend_fields().map(|f| {
let name = f.name;
let ty = f.ty;
quote!(#name: #ty)
});
let extend_fields_value = self.extend_fields().map(|f| {
let name = f.name;
quote!(#name: Vec::new())
});
let has_extend_fields = self.extend_fields().next().is_some();
let take_bump = if has_extend_fields {
quote!(bump: _cx.bump(),)
} else {
quote!()
};
let bump_field = if has_extend_fields {
quote!(bump: & #extend_lifetime ::dioxus::core::exports::bumpalo::Bump,)
} else {
quote!()
};
let extend_lifetime = extend_lifetime.unwrap_or(syn::Lifetime::new(
"'__bump",
proc_macro2::Span::call_site(),
));
Ok(quote! {
impl #impl_generics #name #ty_generics #where_clause {
#[doc = #builder_method_doc]
#[allow(dead_code, clippy::type_complexity)]
#vis fn builder() -> #builder_name #generics_with_empty {
#vis fn builder(_cx: & #extend_lifetime ::dioxus::prelude::ScopeState) -> #builder_name #generics_with_empty {
#builder_name {
#(#extend_fields_value,)*
#take_bump
fields: #empties_tuple,
_phantom: ::core::default::Default::default(),
}
@@ -640,26 +747,19 @@ Finally, call `.build()` to create the instance of `{name}`.
#builder_type_doc
#[allow(dead_code, non_camel_case_types, non_snake_case)]
#vis struct #builder_name #b_generics {
#(#extend_fields,)*
#bump_field
fields: #all_fields_param,
_phantom: (#( #phantom_generics ),*),
}
impl #b_generics_impl Clone for #builder_name #b_generics_ty #b_generics_where {
fn clone(&self) -> Self {
Self {
fields: self.fields.clone(),
_phantom: ::core::default::Default::default(),
}
}
}
impl #impl_generics ::dioxus::prelude::Properties for #name #ty_generics
impl #impl_generics ::dioxus::prelude::Properties<#extend_lifetime> for #name #ty_generics
#b_generics_where_extras_predicates
{
type Builder = #builder_name #generics_with_empty;
const IS_STATIC: bool = #is_static;
fn builder() -> Self::Builder {
#name::builder()
fn builder(_cx: &#extend_lifetime ::dioxus::prelude::ScopeState) -> Self::Builder {
#name::builder(_cx)
}
unsafe fn memoize(&self, other: &Self) -> bool {
#can_memoize
@@ -694,11 +794,143 @@ Finally, call `.build()` to create the instance of `{name}`.
})
}
pub fn extends_impl(&self, field: &FieldInfo) -> Result<TokenStream, Error> {
let StructInfo {
ref builder_name, ..
} = *self;
let field_name = field.name;
let descructuring = self.included_fields().map(|f| {
if f.ordinal == field.ordinal {
quote!(_)
} else {
let name = f.name;
quote!(#name)
}
});
let reconstructing = self.included_fields().map(|f| f.name);
// Add the bump lifetime to the generics
let mut ty_generics: Vec<syn::GenericArgument> = self
.generics
.params
.iter()
.map(|generic_param| match generic_param {
syn::GenericParam::Type(type_param) => {
let ident = type_param.ident.clone();
syn::parse(quote!(#ident).into()).unwrap()
}
syn::GenericParam::Lifetime(lifetime_def) => {
syn::GenericArgument::Lifetime(lifetime_def.lifetime.clone())
}
syn::GenericParam::Const(const_param) => {
let ident = const_param.ident.clone();
syn::parse(quote!(#ident).into()).unwrap()
}
})
.collect();
let mut target_generics_tuple = empty_type_tuple();
let mut ty_generics_tuple = empty_type_tuple();
let generics = self.modify_generics(|g| {
let index_after_lifetime_in_generics = g
.params
.iter()
.filter(|arg| matches!(arg, syn::GenericParam::Lifetime(_)))
.count();
for f in self.included_fields() {
if f.ordinal == field.ordinal {
ty_generics_tuple.elems.push_value(empty_type());
target_generics_tuple
.elems
.push_value(f.tuplized_type_ty_param());
} else {
g.params
.insert(index_after_lifetime_in_generics, f.generic_ty_param());
let generic_argument: syn::Type = f.type_ident();
ty_generics_tuple.elems.push_value(generic_argument.clone());
target_generics_tuple.elems.push_value(generic_argument);
}
ty_generics_tuple.elems.push_punct(Default::default());
target_generics_tuple.elems.push_punct(Default::default());
}
});
let mut target_generics = ty_generics.clone();
let index_after_lifetime_in_generics = target_generics
.iter()
.filter(|arg| matches!(arg, syn::GenericArgument::Lifetime(_)))
.count();
target_generics.insert(
index_after_lifetime_in_generics,
syn::GenericArgument::Type(target_generics_tuple.into()),
);
ty_generics.insert(
index_after_lifetime_in_generics,
syn::GenericArgument::Type(ty_generics_tuple.into()),
);
let (impl_generics, _, where_clause) = generics.split_for_impl();
let forward_extended_fields = self.extend_fields().map(|f| {
let name = f.name;
quote!(#name: self.#name)
});
let extend_lifetime = self.extend_lifetime()?.ok_or(Error::new_spanned(
field_name,
"Unable to find lifetime for extended field. Please specify it manually",
))?;
let extends_impl = field.builder_attr.extends.iter().map(|path| {
let name_str = path_to_single_string(path).unwrap();
let camel_name = name_str.to_case(Case::UpperCamel);
let marker_name = Ident::new(
format!("{}Extension", &camel_name).as_str(),
path.span(),
);
quote! {
#[allow(dead_code, non_camel_case_types, missing_docs)]
impl #impl_generics dioxus_elements::extensions::#marker_name < #extend_lifetime > for #builder_name < #( #ty_generics ),* > #where_clause {}
}
});
Ok(quote! {
#[allow(dead_code, non_camel_case_types, missing_docs)]
impl #impl_generics ::dioxus::prelude::HasAttributes<#extend_lifetime> for #builder_name < #( #ty_generics ),* > #where_clause {
fn push_attribute(
mut self,
name: &#extend_lifetime str,
ns: Option<&'static str>,
attr: impl ::dioxus::prelude::IntoAttributeValue<#extend_lifetime>,
volatile: bool
) -> Self {
let ( #(#descructuring,)* ) = self.fields;
self.#field_name.push(
::dioxus::core::Attribute::new(
name,
{
use ::dioxus::prelude::IntoAttributeValue;
attr.into_value(self.bump)
},
ns,
volatile,
)
);
#builder_name {
#(#forward_extended_fields,)*
bump: self.bump,
fields: ( #(#reconstructing,)* ),
_phantom: self._phantom,
}
}
}
#(#extends_impl)*
})
}
pub fn field_impl(&self, field: &FieldInfo) -> Result<TokenStream, Error> {
let FieldInfo {
name: field_name,
ty: field_type,
..
name: field_name, ..
} = field;
if *field_name == "key" {
return Err(Error::new_spanned(field_name, "Naming a prop `key` is not allowed because the name can conflict with the built in key attribute. See https://dioxuslabs.com/learn/0.4/reference/dynamic_rendering#rendering-lists for more information about keys"));
@@ -717,6 +949,12 @@ Finally, call `.build()` to create the instance of `{name}`.
});
let reconstructing = self.included_fields().map(|f| f.name);
let FieldInfo {
name: field_name,
ty: field_type,
..
} = field;
// Add the bump lifetime to the generics
let mut ty_generics: Vec<syn::GenericArgument> = self
.generics
.params
@@ -800,6 +1038,16 @@ Finally, call `.build()` to create the instance of `{name}`.
);
let repeated_fields_error_message = format!("Repeated field {field_name}");
let forward_extended_fields = self.extend_fields().map(|f| {
let name = f.name;
quote!(#name: self.#name)
});
let forward_bump = if self.extend_fields().next().is_some() {
quote!(bump: self.bump,)
} else {
quote!()
};
Ok(quote! {
#[allow(dead_code, non_camel_case_types, missing_docs)]
impl #impl_generics #builder_name < #( #ty_generics ),* > #where_clause {
@@ -809,6 +1057,8 @@ Finally, call `.build()` to create the instance of `{name}`.
let #field_name = (#arg_expr,);
let ( #(#descructuring,)* ) = self.fields;
#builder_name {
#(#forward_extended_fields,)*
#forward_bump
fields: ( #(#reconstructing,)* ),
_phantom: self._phantom,
}
@@ -842,6 +1092,7 @@ Finally, call `.build()` to create the instance of `{name}`.
name: ref field_name,
..
} = field;
// Add a bump lifetime to the generics
let mut builder_generics: Vec<syn::GenericArgument> = self
.generics
.params
@@ -1009,7 +1260,9 @@ Finally, call `.build()` to create the instance of `{name}`.
// reordering based on that, but for now this much simpler thing is a reasonable approach.
let assignments = self.fields.iter().map(|field| {
let name = &field.name;
if let Some(ref default) = field.builder_attr.default {
if !field.builder_attr.extends.is_empty() {
quote!(let #name = self.#name;)
} else if let Some(ref default) = field.builder_attr.default {
if field.builder_attr.skip {
quote!(let #name = #default;)
} else {
+1
View File
@@ -36,6 +36,7 @@ serde = { version = "1", features = ["derive"], optional = true }
[dev-dependencies]
tokio = { workspace = true, features = ["full"] }
dioxus = { workspace = true }
dioxus-html = { workspace = true, features = ["serialize"] }
pretty_assertions = "1.3.0"
rand = "0.8.5"
dioxus-ssr = { workspace = true }
+71 -59
View File
@@ -1,3 +1,4 @@
use crate::ScopeState;
use std::ptr::NonNull;
use crate::{
@@ -13,62 +14,50 @@ use crate::{
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct ElementId(pub usize);
pub(crate) struct ElementRef {
/// An Element that can be bubbled to's unique identifier.
///
/// `BubbleId` is a `usize` that is unique across the entire VirtualDOM - but not unique across time. If a component is
/// unmounted, then the `BubbleId` will be reused for a new component.
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct VNodeId(pub usize);
#[derive(Debug, Clone, Copy)]
pub struct ElementRef {
// the pathway of the real element inside the template
pub path: ElementPath,
pub(crate) path: ElementPath,
// The actual template
pub template: Option<NonNull<VNode<'static>>>,
pub(crate) template: VNodeId,
// The scope the element belongs to
pub scope: ScopeId,
pub(crate) scope: ScopeId,
}
#[derive(Clone, Copy, Debug)]
pub enum ElementPath {
Deep(&'static [u8]),
Root(usize),
}
impl ElementRef {
pub(crate) fn none() -> Self {
Self {
template: None,
path: ElementPath::Root(0),
scope: ScopeId::ROOT,
}
}
pub struct ElementPath {
pub(crate) path: &'static [u8],
}
impl VirtualDom {
pub(crate) fn next_element(&mut self, template: &VNode, path: &'static [u8]) -> ElementId {
self.next_reference(template, ElementPath::Deep(path))
pub(crate) fn next_element(&mut self) -> ElementId {
ElementId(self.elements.insert(None))
}
pub(crate) fn next_root(&mut self, template: &VNode, path: usize) -> ElementId {
self.next_reference(template, ElementPath::Root(path))
}
pub(crate) fn next_vnode_ref(&mut self, vnode: &VNode) -> VNodeId {
let new_id = VNodeId(self.element_refs.insert(Some(unsafe {
std::mem::transmute::<NonNull<VNode>, _>(vnode.into())
})));
pub(crate) fn next_null(&mut self) -> ElementId {
let entry = self.elements.vacant_entry();
let id = entry.key();
// Set this id to be dropped when the scope is rerun
if let Some(scope) = self.runtime.current_scope_id() {
self.scopes[scope.0]
.element_refs_to_drop
.borrow_mut()
.push(new_id);
}
entry.insert(ElementRef::none());
ElementId(id)
}
fn next_reference(&mut self, template: &VNode, path: ElementPath) -> ElementId {
let entry = self.elements.vacant_entry();
let id = entry.key();
let scope = self.runtime.current_scope_id().unwrap_or(ScopeId::ROOT);
entry.insert(ElementRef {
// We know this is non-null because it comes from a reference
template: Some(unsafe { NonNull::new_unchecked(template as *const _ as *mut _) }),
path,
scope,
});
ElementId(id)
new_id
}
pub(crate) fn reclaim(&mut self, el: ElementId) {
@@ -76,7 +65,7 @@ impl VirtualDom {
.unwrap_or_else(|| panic!("cannot reclaim {:?}", el));
}
pub(crate) fn try_reclaim(&mut self, el: ElementId) -> Option<ElementRef> {
pub(crate) fn try_reclaim(&mut self, el: ElementId) -> Option<()> {
if el.0 == 0 {
panic!(
"Cannot reclaim the root element - {:#?}",
@@ -84,12 +73,12 @@ impl VirtualDom {
);
}
self.elements.try_remove(el.0)
self.elements.try_remove(el.0).map(|_| ())
}
pub(crate) fn update_template(&mut self, el: ElementId, node: &VNode) {
let node: *const VNode = node as *const _;
self.elements[el.0].template = unsafe { std::mem::transmute(node) };
pub(crate) fn set_template(&mut self, id: VNodeId, vnode: &VNode) {
self.element_refs[id.0] =
Some(unsafe { std::mem::transmute::<NonNull<VNode>, _>(vnode.into()) });
}
// Drop a scope and all its children
@@ -101,6 +90,15 @@ impl VirtualDom {
id,
});
// Remove all VNode ids from the scope
for id in self.scopes[id.0]
.element_refs_to_drop
.borrow_mut()
.drain(..)
{
self.element_refs.try_remove(id.0);
}
self.ensure_drop_safety(id);
if recursive {
@@ -145,14 +143,25 @@ impl VirtualDom {
}
/// Descend through the tree, removing any borrowed props and listeners
pub(crate) fn ensure_drop_safety(&self, scope_id: ScopeId) {
pub(crate) fn ensure_drop_safety(&mut self, scope_id: ScopeId) {
let scope = &self.scopes[scope_id.0];
{
// Drop all element refs that could be invalidated when the component was rerun
let mut element_refs = self.scopes[scope_id.0].element_refs_to_drop.borrow_mut();
let element_refs_slab = &mut self.element_refs;
for element_ref in element_refs.drain(..) {
if let Some(element_ref) = element_refs_slab.get_mut(element_ref.0) {
*element_ref = None;
}
}
}
// make sure we drop all borrowed props manually to guarantee that their drop implementation is called before we
// run the hooks (which hold an &mut Reference)
// recursively call ensure_drop_safety on all children
let mut props = scope.borrowed_props.borrow_mut();
props.drain(..).for_each(|comp| {
let props = { scope.borrowed_props.borrow_mut().clone() };
for comp in props {
let comp = unsafe { &*comp };
match comp.scope.get() {
Some(child) if child != scope_id => self.ensure_drop_safety(child),
@@ -161,10 +170,19 @@ impl VirtualDom {
if let Ok(mut props) = comp.props.try_borrow_mut() {
*props = None;
}
});
}
let scope = &self.scopes[scope_id.0];
scope.borrowed_props.borrow_mut().clear();
// Now that all the references are gone, we can safely drop our own references in our listeners.
let mut listeners = scope.attributes_to_drop_before_render.borrow_mut();
scope.drop_listeners();
}
}
impl ScopeState {
/// Drop all listeners that were allocated in the bump allocator.
pub(crate) fn drop_listeners(&self) {
let mut listeners = self.attributes_to_drop_before_render.borrow_mut();
listeners.drain(..).for_each(|listener| {
let listener = unsafe { &*listener };
if let AttributeValue::Listener(l) = &listener.value {
@@ -176,18 +194,12 @@ impl VirtualDom {
impl ElementPath {
pub(crate) fn is_decendant(&self, small: &&[u8]) -> bool {
match *self {
ElementPath::Deep(big) => small.len() <= big.len() && *small == &big[..small.len()],
ElementPath::Root(r) => small.len() == 1 && small[0] == r as u8,
}
small.len() <= self.path.len() && *small == &self.path[..small.len()]
}
}
impl PartialEq<&[u8]> for ElementPath {
fn eq(&self, other: &&[u8]) -> bool {
match *self {
ElementPath::Deep(deep) => deep.eq(*other),
ElementPath::Root(r) => other.len() == 1 && other[0] == r as u8,
}
self.path.eq(*other)
}
}
+97 -45
View File
@@ -1,5 +1,8 @@
use crate::any_props::AnyProps;
use crate::innerlude::{BorrowedAttributeValue, VComponent, VPlaceholder, VText};
use crate::innerlude::{
AttributeType, BorrowedAttributeValue, ElementPath, ElementRef, MountedAttribute, VComponent,
VPlaceholder, VText,
};
use crate::mutations::Mutation;
use crate::mutations::Mutation::*;
use crate::nodes::VNode;
@@ -94,6 +97,9 @@ impl<'b> VirtualDom {
nodes_mut.resize(len, ElementId::default());
};
// Set this node id
node.stable_id.set(Some(self.next_vnode_ref(node)));
// The best renderers will have templates prehydrated and registered
// Just in case, let's create the template using instructions anyways
self.register_template(node.template.get());
@@ -181,15 +187,30 @@ impl<'b> VirtualDom {
use DynamicNode::*;
match &template.dynamic_nodes[idx] {
node @ Component { .. } | node @ Fragment(_) => {
self.create_dynamic_node(template, node, idx)
let template_ref = ElementRef {
path: ElementPath {
path: template.template.get().node_paths[idx],
},
template: template.stable_id().unwrap(),
scope: self.runtime.current_scope_id().unwrap_or(ScopeId(0)),
};
self.create_dynamic_node(template_ref, node)
}
Placeholder(VPlaceholder { id }) => {
let id = self.set_slot(template, id, idx);
Placeholder(VPlaceholder { id, parent }) => {
let template_ref = ElementRef {
path: ElementPath {
path: template.template.get().node_paths[idx],
},
template: template.stable_id().unwrap(),
scope: self.runtime.current_scope_id().unwrap_or(ScopeId(0)),
};
parent.set(Some(template_ref));
let id = self.set_slot(id);
self.mutations.push(CreatePlaceholder { id });
1
}
Text(VText { id, value }) => {
let id = self.set_slot(template, id, idx);
let id = self.set_slot(id);
self.create_static_text(value, id);
1
}
@@ -205,7 +226,7 @@ impl<'b> VirtualDom {
});
}
/// We write all the descndent data for this element
/// We write all the descendent data for this element
///
/// Elements can contain other nodes - and those nodes can be dynamic or static
///
@@ -265,7 +286,14 @@ impl<'b> VirtualDom {
.map(|sorted_index| dynamic_nodes[sorted_index].0);
for idx in reversed_iter {
let m = self.create_dynamic_node(template, &template.dynamic_nodes[idx], idx);
let boundary_ref = ElementRef {
path: ElementPath {
path: template.template.get().node_paths[idx],
},
template: template.stable_id().unwrap(),
scope: self.runtime.current_scope_id().unwrap_or(ScopeId(0)),
};
let m = self.create_dynamic_node(boundary_ref, &template.dynamic_nodes[idx]);
if m > 0 {
// The path is one shorter because the top node is the root
let path = &template.template.get().node_paths[idx][1..];
@@ -279,15 +307,15 @@ impl<'b> VirtualDom {
attrs: &mut Peekable<impl Iterator<Item = (usize, &'static [u8])>>,
root_idx: u8,
root: ElementId,
node: &VNode,
node: &'b VNode<'b>,
) {
while let Some((mut attr_id, path)) =
attrs.next_if(|(_, p)| p.first().copied() == Some(root_idx))
{
let id = self.assign_static_node_as_dynamic(path, root, node, attr_id);
let id = self.assign_static_node_as_dynamic(path, root);
loop {
self.write_attribute(&node.dynamic_attrs[attr_id], id);
self.write_attribute_type(node, &node.dynamic_attrs[attr_id], attr_id, id);
// Only push the dynamic attributes forward if they match the current path (same element)
match attrs.next_if(|(_, p)| *p == path) {
@@ -298,15 +326,44 @@ impl<'b> VirtualDom {
}
}
fn write_attribute(&mut self, attribute: &'b crate::Attribute<'b>, id: ElementId) {
fn write_attribute_type(
&mut self,
vnode: &'b VNode<'b>,
attribute: &'b MountedAttribute<'b>,
idx: usize,
id: ElementId,
) {
// Make sure we set the attribute's associated id
attribute.mounted_element.set(id);
match &attribute.ty {
AttributeType::Single(attribute) => self.write_attribute(vnode, attribute, idx, id),
AttributeType::Many(attribute) => {
for attribute in *attribute {
self.write_attribute(vnode, attribute, idx, id);
}
}
}
}
pub(crate) fn write_attribute(
&mut self,
vnode: &'b VNode<'b>,
attribute: &'b crate::Attribute<'b>,
idx: usize,
id: ElementId,
) {
// Safety: we promise not to re-alias this text later on after committing it to the mutation
let unbounded_name: &str = unsafe { std::mem::transmute(attribute.name) };
match &attribute.value {
AttributeValue::Listener(_) => {
let path = &vnode.template.get().attr_paths[idx];
let element_ref = ElementRef {
path: ElementPath { path },
template: vnode.stable_id().unwrap(),
scope: self.runtime.current_scope_id().unwrap_or(ScopeId(0)),
};
self.elements[id.0] = Some(element_ref);
self.mutations.push(NewEventListener {
// all listeners start with "on"
name: &unbounded_name[2..],
@@ -330,7 +387,7 @@ impl<'b> VirtualDom {
fn load_template_root(&mut self, template: &VNode, root_idx: usize) -> ElementId {
// Get an ID for this root since it's a real root
let this_id = self.next_root(template, root_idx);
let this_id = self.next_element();
template.root_ids.borrow_mut()[root_idx] = this_id;
self.mutations.push(LoadTemplate {
@@ -353,8 +410,6 @@ impl<'b> VirtualDom {
&mut self,
path: &'static [u8],
this_id: ElementId,
template: &VNode,
attr_id: usize,
) -> ElementId {
if path.len() == 1 {
return this_id;
@@ -362,7 +417,7 @@ impl<'b> VirtualDom {
// if attribute is on a root node, then we've already created the element
// Else, it's deep in the template and we should create a new id for it
let id = self.next_element(template, template.template.get().attr_paths[attr_id]);
let id = self.next_element();
self.mutations.push(Mutation::AssignId {
path: &path[1..],
@@ -405,6 +460,7 @@ impl<'b> VirtualDom {
#[allow(unused_mut)]
pub(crate) fn register_template(&mut self, mut template: Template<'static>) {
let (path, byte_index) = template.name.rsplit_once(':').unwrap();
let byte_index = byte_index.parse::<usize>().unwrap();
// First, check if we've already seen this template
if self
@@ -439,27 +495,21 @@ impl<'b> VirtualDom {
pub(crate) fn create_dynamic_node(
&mut self,
template: &'b VNode<'b>,
parent: ElementRef,
node: &'b DynamicNode<'b>,
idx: usize,
) -> usize {
use DynamicNode::*;
match node {
Text(text) => self.create_dynamic_text(template, text, idx),
Placeholder(place) => self.create_placeholder(place, template, idx),
Component(component) => self.create_component_node(template, component),
Fragment(frag) => frag.iter().map(|child| self.create(child)).sum(),
Text(text) => self.create_dynamic_text(parent, text),
Placeholder(place) => self.create_placeholder(place, parent),
Component(component) => self.create_component_node(Some(parent), component),
Fragment(frag) => self.create_children(*frag, Some(parent)),
}
}
fn create_dynamic_text(
&mut self,
template: &'b VNode<'b>,
text: &'b VText<'b>,
idx: usize,
) -> usize {
fn create_dynamic_text(&mut self, parent: ElementRef, text: &'b VText<'b>) -> usize {
// Allocate a dynamic element reference for this text node
let new_id = self.next_element(template, template.template.get().node_paths[idx]);
let new_id = self.next_element();
// Make sure the text node is assigned to the correct element
text.id.set(Some(new_id));
@@ -470,7 +520,7 @@ impl<'b> VirtualDom {
// Add the mutation to the list
self.mutations.push(HydrateText {
id: new_id,
path: &template.template.get().node_paths[idx][1..],
path: &parent.path.path[1..],
value,
});
@@ -481,18 +531,20 @@ impl<'b> VirtualDom {
pub(crate) fn create_placeholder(
&mut self,
placeholder: &VPlaceholder,
template: &'b VNode<'b>,
idx: usize,
parent: ElementRef,
) -> usize {
// Allocate a dynamic element reference for this text node
let id = self.next_element(template, template.template.get().node_paths[idx]);
let id = self.next_element();
// Make sure the text node is assigned to the correct element
placeholder.id.set(Some(id));
// Assign the placeholder's parent
placeholder.parent.set(Some(parent));
// Assign the ID to the existing node in the template
self.mutations.push(AssignId {
path: &template.template.get().node_paths[idx][1..],
path: &parent.path.path[1..],
id,
});
@@ -502,7 +554,7 @@ impl<'b> VirtualDom {
pub(super) fn create_component_node(
&mut self,
template: &'b VNode<'b>,
parent: Option<ElementRef>,
component: &'b VComponent<'b>,
) -> usize {
use RenderReturn::*;
@@ -514,8 +566,11 @@ impl<'b> VirtualDom {
match unsafe { self.run_scope(scope).extend_lifetime_ref() } {
// Create the component's root element
Ready(t) => self.create_scope(scope, t),
Aborted(t) => self.mount_aborted(template, t),
Ready(t) => {
self.assign_boundary_ref(parent, t);
self.create_scope(scope, t)
}
Aborted(t) => self.mount_aborted(t, parent),
}
}
@@ -531,20 +586,17 @@ impl<'b> VirtualDom {
.unwrap_or_else(|| component.scope.get().unwrap())
}
fn mount_aborted(&mut self, parent: &'b VNode<'b>, placeholder: &VPlaceholder) -> usize {
let id = self.next_element(parent, &[]);
fn mount_aborted(&mut self, placeholder: &VPlaceholder, parent: Option<ElementRef>) -> usize {
let id = self.next_element();
self.mutations.push(Mutation::CreatePlaceholder { id });
placeholder.id.set(Some(id));
placeholder.parent.set(parent);
1
}
fn set_slot(
&mut self,
template: &'b VNode<'b>,
slot: &'b Cell<Option<ElementId>>,
id: usize,
) -> ElementId {
let id = self.next_element(template, template.template.get().node_paths[id]);
fn set_slot(&mut self, slot: &'b Cell<Option<ElementId>>) -> ElementId {
let id = self.next_element();
slot.set(Some(id));
id
}
+222 -69
View File
@@ -1,7 +1,10 @@
use crate::{
any_props::AnyProps,
arena::ElementId,
innerlude::{BorrowedAttributeValue, DirtyScope, VComponent, VPlaceholder, VText},
innerlude::{
AttributeType, BorrowedAttributeValue, DirtyScope, ElementPath, ElementRef, VComponent,
VPlaceholder, VText,
},
mutations::Mutation,
nodes::RenderReturn,
nodes::{DynamicNode, VNode},
@@ -39,19 +42,27 @@ impl<'b> VirtualDom {
(Ready(l), Aborted(p)) => self.diff_ok_to_err(l, p),
// Just move over the placeholder
(Aborted(l), Aborted(r)) => r.id.set(l.id.get()),
(Aborted(l), Aborted(r)) => {
r.id.set(l.id.get());
r.parent.set(l.parent.get())
}
// Placeholder becomes something
// We should also clear the error now
(Aborted(l), Ready(r)) => self.replace_placeholder(l, [r]),
(Aborted(l), Ready(r)) => self.replace_placeholder(
l,
[r],
l.parent.get().expect("root node should not be none"),
),
};
}
self.runtime.scope_stack.borrow_mut().pop();
}
fn diff_ok_to_err(&mut self, l: &'b VNode<'b>, p: &'b VPlaceholder) {
let id = self.next_null();
let id = self.next_element();
p.id.set(Some(id));
p.parent.set(l.parent.get());
self.mutations.push(Mutation::CreatePlaceholder { id });
let pre_edits = self.mutations.edits.len();
@@ -81,12 +92,24 @@ impl<'b> VirtualDom {
if let Some(&template) = map.get(&byte_index) {
right_template.template.set(template);
if template != left_template.template.get() {
return self.replace(left_template, [right_template]);
let parent = left_template.parent.take();
return self.replace(left_template, [right_template], parent);
}
}
}
}
// Copy over the parent
{
right_template.parent.set(left_template.parent.get());
}
// Update the bubble id pointer
right_template.stable_id.set(left_template.stable_id.get());
if let Some(bubble_id) = right_template.stable_id.get() {
self.set_template(bubble_id, right_template);
}
// If the templates are the same, we don't need to do anything, nor do we want to
if templates_are_the_same(left_template, right_template) {
return;
@@ -103,18 +126,54 @@ impl<'b> VirtualDom {
.dynamic_attrs
.iter()
.zip(right_template.dynamic_attrs.iter())
.for_each(|(left_attr, right_attr)| {
.enumerate()
.for_each(|(idx, (left_attr, right_attr))| {
// Move over the ID from the old to the new
right_attr
.mounted_element
.set(left_attr.mounted_element.get());
let mounted_id = left_attr.mounted_element.get();
right_attr.mounted_element.set(mounted_id);
// We want to make sure anything that gets pulled is valid
self.update_template(left_attr.mounted_element.get(), right_template);
match (&left_attr.ty, &right_attr.ty) {
(AttributeType::Single(left), AttributeType::Single(right)) => {
self.diff_attribute(left, right, mounted_id)
}
(AttributeType::Many(left), AttributeType::Many(right)) => {
let mut left_iter = left.iter().peekable();
let mut right_iter = right.iter().peekable();
// If the attributes are different (or volatile), we need to update them
if left_attr.value != right_attr.value || left_attr.volatile {
self.update_attribute(right_attr, left_attr);
loop {
match (left_iter.peek(), right_iter.peek()) {
(Some(left), Some(right)) => {
// check which name is greater
match left.name.cmp(right.name) {
std::cmp::Ordering::Less => self.remove_attribute(
left.name,
left.namespace,
mounted_id,
),
std::cmp::Ordering::Greater => self.write_attribute(
right_template,
right,
idx,
mounted_id,
),
std::cmp::Ordering::Equal => {
self.diff_attribute(left, right, mounted_id)
}
}
}
(Some(_), None) => {
let left = left_iter.next().unwrap();
self.remove_attribute(left.name, left.namespace, mounted_id)
}
(None, Some(_)) => {
let right = right_iter.next().unwrap();
self.write_attribute(right_template, right, idx, mounted_id)
}
(None, None) => break,
}
}
}
_ => unreachable!("The macro should never generate this case"),
}
});
@@ -123,8 +182,16 @@ impl<'b> VirtualDom {
.dynamic_nodes
.iter()
.zip(right_template.dynamic_nodes.iter())
.for_each(|(left_node, right_node)| {
self.diff_dynamic_node(left_node, right_node, right_template);
.enumerate()
.for_each(|(dyn_node_idx, (left_node, right_node))| {
let current_ref = ElementRef {
template: right_template.stable_id().unwrap(),
path: ElementPath {
path: left_template.template.get().node_paths[dyn_node_idx],
},
scope: self.runtime.scope_stack.borrow().last().copied().unwrap(),
};
self.diff_dynamic_node(left_node, right_node, current_ref);
});
// Make sure the roots get transferred over while we're here
@@ -135,14 +202,17 @@ impl<'b> VirtualDom {
right.push(element);
}
}
}
let root_ids = right_template.root_ids.borrow();
// Update the node refs
for i in 0..root_ids.len() {
if let Some(root_id) = root_ids.get(i) {
self.update_template(*root_id, right_template);
}
fn diff_attribute(
&mut self,
left_attr: &'b Attribute<'b>,
right_attr: &'b Attribute<'b>,
id: ElementId,
) {
// If the attributes are different (or volatile), we need to update them
if left_attr.value != right_attr.value || left_attr.volatile {
self.update_attribute(right_attr, left_attr, id);
}
}
@@ -150,25 +220,45 @@ impl<'b> VirtualDom {
&mut self,
left_node: &'b DynamicNode<'b>,
right_node: &'b DynamicNode<'b>,
node: &'b VNode<'b>,
parent: ElementRef,
) {
match (left_node, right_node) {
(Text(left), Text(right)) => self.diff_vtext(left, right, node),
(Fragment(left), Fragment(right)) => self.diff_non_empty_fragment(left, right),
(Placeholder(left), Placeholder(right)) => right.id.set(left.id.get()),
(Component(left), Component(right)) => self.diff_vcomponent(left, right, node),
(Placeholder(left), Fragment(right)) => self.replace_placeholder(left, *right),
(Fragment(left), Placeholder(right)) => self.node_to_placeholder(left, right),
(Text(left), Text(right)) => self.diff_vtext(left, right),
(Fragment(left), Fragment(right)) => self.diff_non_empty_fragment(left, right, parent),
(Placeholder(left), Placeholder(right)) => {
right.id.set(left.id.get());
right.parent.set(left.parent.get());
},
(Component(left), Component(right)) => self.diff_vcomponent(left, right, Some(parent)),
(Placeholder(left), Fragment(right)) => self.replace_placeholder(left, *right, parent),
(Fragment(left), Placeholder(right)) => self.node_to_placeholder(left, right, parent),
_ => todo!("This is an usual custom case for dynamic nodes. We don't know how to handle it yet."),
};
}
fn update_attribute(&mut self, right_attr: &'b Attribute<'b>, left_attr: &'b Attribute) {
fn remove_attribute(&mut self, name: &'b str, ns: Option<&'static str>, id: ElementId) {
let name = unsafe { std::mem::transmute(name) };
let value: BorrowedAttributeValue<'b> = BorrowedAttributeValue::None;
let value = unsafe { std::mem::transmute(value) };
self.mutations.push(Mutation::SetAttribute {
id,
ns,
name,
value,
});
}
fn update_attribute(
&mut self,
right_attr: &'b Attribute<'b>,
left_attr: &'b Attribute<'b>,
id: ElementId,
) {
let name = unsafe { std::mem::transmute(left_attr.name) };
let value: BorrowedAttributeValue<'b> = (&right_attr.value).into();
let value = unsafe { std::mem::transmute(value) };
self.mutations.push(Mutation::SetAttribute {
id: left_attr.mounted_element.get(),
id,
ns: right_attr.namespace,
name,
value,
@@ -179,7 +269,7 @@ impl<'b> VirtualDom {
&mut self,
left: &'b VComponent<'b>,
right: &'b VComponent<'b>,
right_template: &'b VNode<'b>,
parent: Option<ElementRef>,
) {
if std::ptr::eq(left, right) {
return;
@@ -187,7 +277,7 @@ impl<'b> VirtualDom {
// Replace components that have different render fns
if left.render_fn != right.render_fn {
return self.replace_vcomponent(right_template, right, left);
return self.replace_vcomponent(right, left, parent);
}
// Make sure the new vcomponent has the right scopeid associated to it
@@ -228,11 +318,11 @@ impl<'b> VirtualDom {
fn replace_vcomponent(
&mut self,
right_template: &'b VNode<'b>,
right: &'b VComponent<'b>,
left: &'b VComponent<'b>,
parent: Option<ElementRef>,
) {
let m = self.create_component_node(right_template, right);
let m = self.create_component_node(parent, right);
let pre_edits = self.mutations.edits.len();
@@ -287,11 +377,12 @@ impl<'b> VirtualDom {
/// }
/// ```
fn light_diff_templates(&mut self, left: &'b VNode<'b>, right: &'b VNode<'b>) {
let parent = left.parent.take();
match matching_components(left, right) {
None => self.replace(left, [right]),
None => self.replace(left, [right], parent),
Some(components) => components
.into_iter()
.for_each(|(l, r)| self.diff_vcomponent(l, r, right)),
.for_each(|(l, r)| self.diff_vcomponent(l, r, parent)),
}
}
@@ -299,11 +390,8 @@ impl<'b> VirtualDom {
///
/// This just moves the ID of the old node over to the new node, and then sets the text of the new node if it's
/// different.
fn diff_vtext(&mut self, left: &'b VText<'b>, right: &'b VText<'b>, node: &'b VNode<'b>) {
let id = left
.id
.get()
.unwrap_or_else(|| self.next_element(node, &[0]));
fn diff_vtext(&mut self, left: &'b VText<'b>, right: &'b VText<'b>) {
let id = left.id.get().unwrap_or_else(|| self.next_element());
right.id.set(Some(id));
if left.value != right.value {
@@ -312,7 +400,12 @@ impl<'b> VirtualDom {
}
}
fn diff_non_empty_fragment(&mut self, old: &'b [VNode<'b>], new: &'b [VNode<'b>]) {
fn diff_non_empty_fragment(
&mut self,
old: &'b [VNode<'b>],
new: &'b [VNode<'b>],
parent: ElementRef,
) {
let new_is_keyed = new[0].key.is_some();
let old_is_keyed = old[0].key.is_some();
debug_assert!(
@@ -325,9 +418,9 @@ impl<'b> VirtualDom {
);
if new_is_keyed && old_is_keyed {
self.diff_keyed_children(old, new);
self.diff_keyed_children(old, new, parent);
} else {
self.diff_non_keyed_children(old, new);
self.diff_non_keyed_children(old, new, parent);
}
}
@@ -339,7 +432,12 @@ impl<'b> VirtualDom {
// [... parent]
//
// the change list stack is in the same state when this function returns.
fn diff_non_keyed_children(&mut self, old: &'b [VNode<'b>], new: &'b [VNode<'b>]) {
fn diff_non_keyed_children(
&mut self,
old: &'b [VNode<'b>],
new: &'b [VNode<'b>],
parent: ElementRef,
) {
use std::cmp::Ordering;
// Handled these cases in `diff_children` before calling this function.
@@ -348,7 +446,9 @@ impl<'b> VirtualDom {
match old.len().cmp(&new.len()) {
Ordering::Greater => self.remove_nodes(&old[new.len()..]),
Ordering::Less => self.create_and_insert_after(&new[old.len()..], old.last().unwrap()),
Ordering::Less => {
self.create_and_insert_after(&new[old.len()..], old.last().unwrap(), parent)
}
Ordering::Equal => {}
}
@@ -373,7 +473,12 @@ impl<'b> VirtualDom {
// https://github.com/infernojs/inferno/blob/36fd96/packages/inferno/src/DOM/patching.ts#L530-L739
//
// The stack is empty upon entry.
fn diff_keyed_children(&mut self, old: &'b [VNode<'b>], new: &'b [VNode<'b>]) {
fn diff_keyed_children(
&mut self,
old: &'b [VNode<'b>],
new: &'b [VNode<'b>],
parent: ElementRef,
) {
if cfg!(debug_assertions) {
let mut keys = rustc_hash::FxHashSet::default();
let mut assert_unique_keys = |children: &'b [VNode<'b>]| {
@@ -401,7 +506,7 @@ impl<'b> VirtualDom {
//
// `shared_prefix_count` is the count of how many nodes at the start of
// `new` and `old` share the same keys.
let (left_offset, right_offset) = match self.diff_keyed_ends(old, new) {
let (left_offset, right_offset) = match self.diff_keyed_ends(old, new, parent) {
Some(count) => count,
None => return,
};
@@ -427,18 +532,18 @@ impl<'b> VirtualDom {
if left_offset == 0 {
// insert at the beginning of the old list
let foothold = &old[old.len() - right_offset];
self.create_and_insert_before(new_middle, foothold);
self.create_and_insert_before(new_middle, foothold, parent);
} else if right_offset == 0 {
// insert at the end the old list
let foothold = old.last().unwrap();
self.create_and_insert_after(new_middle, foothold);
self.create_and_insert_after(new_middle, foothold, parent);
} else {
// inserting in the middle
let foothold = &old[left_offset - 1];
self.create_and_insert_after(new_middle, foothold);
self.create_and_insert_after(new_middle, foothold, parent);
}
} else {
self.diff_keyed_middle(old_middle, new_middle);
self.diff_keyed_middle(old_middle, new_middle, parent);
}
}
@@ -451,6 +556,7 @@ impl<'b> VirtualDom {
&mut self,
old: &'b [VNode<'b>],
new: &'b [VNode<'b>],
parent: ElementRef,
) -> Option<(usize, usize)> {
let mut left_offset = 0;
@@ -466,7 +572,7 @@ impl<'b> VirtualDom {
// If that was all of the old children, then create and append the remaining
// new children and we're finished.
if left_offset == old.len() {
self.create_and_insert_after(&new[left_offset..], old.last().unwrap());
self.create_and_insert_after(&new[left_offset..], old.last().unwrap(), parent);
return None;
}
@@ -505,7 +611,12 @@ impl<'b> VirtualDom {
//
// Upon exit from this function, it will be restored to that same self.
#[allow(clippy::too_many_lines)]
fn diff_keyed_middle(&mut self, old: &'b [VNode<'b>], new: &'b [VNode<'b>]) {
fn diff_keyed_middle(
&mut self,
old: &'b [VNode<'b>],
new: &'b [VNode<'b>],
parent: ElementRef,
) {
/*
1. Map the old keys into a numerical ordering based on indices.
2. Create a map of old key to its index
@@ -560,9 +671,9 @@ impl<'b> VirtualDom {
// If none of the old keys are reused by the new children, then we remove all the remaining old children and
// create the new children afresh.
if shared_keys.is_empty() {
if old.first().is_some() {
if !old.is_empty() {
self.remove_nodes(&old[1..]);
self.replace(&old[0], new);
self.replace(&old[0], new, Some(parent));
} else {
// I think this is wrong - why are we appending?
// only valid of the if there are no trailing elements
@@ -739,20 +850,38 @@ impl<'b> VirtualDom {
.sum()
}
fn create_children(&mut self, nodes: impl IntoIterator<Item = &'b VNode<'b>>) -> usize {
pub(crate) fn create_children(
&mut self,
nodes: impl IntoIterator<Item = &'b VNode<'b>>,
parent: Option<ElementRef>,
) -> usize {
nodes
.into_iter()
.fold(0, |acc, child| acc + self.create(child))
.map(|child| {
self.assign_boundary_ref(parent, child);
self.create(child)
})
.sum()
}
fn create_and_insert_before(&mut self, new: &'b [VNode<'b>], before: &'b VNode<'b>) {
let m = self.create_children(new);
fn create_and_insert_before(
&mut self,
new: &'b [VNode<'b>],
before: &'b VNode<'b>,
parent: ElementRef,
) {
let m = self.create_children(new, Some(parent));
let id = self.find_first_element(before);
self.mutations.push(Mutation::InsertBefore { id, m })
}
fn create_and_insert_after(&mut self, new: &'b [VNode<'b>], after: &'b VNode<'b>) {
let m = self.create_children(new);
fn create_and_insert_after(
&mut self,
new: &'b [VNode<'b>],
after: &'b VNode<'b>,
parent: ElementRef,
) {
let m = self.create_children(new, Some(parent));
let id = self.find_last_element(after);
self.mutations.push(Mutation::InsertAfter { id, m })
}
@@ -762,15 +891,21 @@ impl<'b> VirtualDom {
&mut self,
l: &'b VPlaceholder,
r: impl IntoIterator<Item = &'b VNode<'b>>,
parent: ElementRef,
) {
let m = self.create_children(r);
let m = self.create_children(r, Some(parent));
let id = l.id.get().unwrap();
self.mutations.push(Mutation::ReplaceWith { id, m });
self.reclaim(id);
}
fn replace(&mut self, left: &'b VNode<'b>, right: impl IntoIterator<Item = &'b VNode<'b>>) {
let m = self.create_children(right);
fn replace(
&mut self,
left: &'b VNode<'b>,
right: impl IntoIterator<Item = &'b VNode<'b>>,
parent: Option<ElementRef>,
) {
let m = self.create_children(right, parent);
let pre_edits = self.mutations.edits.len();
@@ -789,11 +924,12 @@ impl<'b> VirtualDom {
};
}
fn node_to_placeholder(&mut self, l: &'b [VNode<'b>], r: &'b VPlaceholder) {
fn node_to_placeholder(&mut self, l: &'b [VNode<'b>], r: &'b VPlaceholder, parent: ElementRef) {
// Create the placeholder first, ensuring we get a dedicated ID for the placeholder
let placeholder = self.next_element(&l[0], &[]);
let placeholder = self.next_element();
r.id.set(Some(placeholder));
r.parent.set(Some(parent));
self.mutations
.push(Mutation::CreatePlaceholder { id: placeholder });
@@ -831,6 +967,16 @@ impl<'b> VirtualDom {
// Clean up the roots, assuming we need to generate mutations for these
// This is done last in order to preserve Node ID reclaim order (reclaim in reverse order of claim)
self.reclaim_roots(node, gen_muts);
// Clean up the vnode id
self.reclaim_vnode_id(node);
}
fn reclaim_vnode_id(&mut self, node: &'b VNode<'b>) {
// Clean up the vnode id
if let Some(id) = node.stable_id() {
self.element_refs.remove(id.0);
}
}
fn reclaim_roots(&mut self, node: &VNode, gen_muts: bool) {
@@ -989,6 +1135,13 @@ impl<'b> VirtualDom {
}
}
}
pub(crate) fn assign_boundary_ref(&mut self, parent: Option<ElementRef>, child: &'b VNode<'b>) {
if let Some(parent) = parent {
// assign the parent of the child
child.parent.set(Some(parent));
}
}
}
/// Are the templates the same?
+1
View File
@@ -0,0 +1 @@
+351 -63
View File
@@ -1,25 +1,68 @@
use crate::{ScopeId, ScopeState};
use crate::{
scope_context::{consume_context, current_scope_id, schedule_update_any},
Element, IntoDynNode, LazyNodes, Properties, Scope, ScopeId, ScopeState, Template,
TemplateAttribute, TemplateNode, VNode,
};
use std::{
any::{Any, TypeId},
cell::RefCell,
fmt::Debug,
backtrace::Backtrace,
cell::{Cell, RefCell},
error::Error,
fmt::{Debug, Display},
rc::Rc,
sync::Arc,
};
/// A boundary that will capture any errors from child components
pub struct ErrorBoundary {
error: RefCell<Option<CapturedError>>,
_id: ScopeId,
/// Provide an error boundary to catch errors from child components
pub fn use_error_boundary(cx: &ScopeState) -> &ErrorBoundary {
cx.use_hook(|| cx.provide_context(ErrorBoundary::new()))
}
/// A boundary that will capture any errors from child components
#[derive(Debug, Clone, Default)]
pub struct ErrorBoundary {
inner: Rc<ErrorBoundaryInner>,
}
/// A boundary that will capture any errors from child components
pub struct ErrorBoundaryInner {
error: RefCell<Option<CapturedError>>,
_id: ScopeId,
rerun_boundary: Arc<dyn Fn(ScopeId) + Send + Sync>,
}
impl Debug for ErrorBoundaryInner {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ErrorBoundaryInner")
.field("error", &self.error)
.finish()
}
}
#[derive(Debug)]
/// An instance of an error captured by a descendant component.
pub struct CapturedError {
/// The error captured by the error boundary
pub error: Box<dyn Debug + 'static>,
/// The backtrace of the error
pub backtrace: Backtrace,
/// The scope that threw the error
pub scope: ScopeId,
}
impl Display for CapturedError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!(
"Encountered error: {:?}\nIn scope: {:?}\nBacktrace: {}",
self.error, self.scope, self.backtrace
))
}
}
impl Error for CapturedError {}
impl CapturedError {
/// Downcast the error type into a concrete error type
pub fn downcast<T: 'static>(&self) -> Option<&T> {
@@ -32,17 +75,56 @@ impl CapturedError {
}
}
impl ErrorBoundary {
pub fn new(id: ScopeId) -> Self {
impl Default for ErrorBoundaryInner {
fn default() -> Self {
Self {
error: RefCell::new(None),
_id: id,
_id: current_scope_id()
.expect("Cannot create an error boundary outside of a component's scope."),
rerun_boundary: schedule_update_any().unwrap(),
}
}
}
impl ErrorBoundary {
/// Create a new error boundary
pub fn new() -> Self {
Self::default()
}
/// Create a new error boundary in the current scope
pub(crate) fn new_in_scope(
scope: ScopeId,
rerun_boundary: Arc<dyn Fn(ScopeId) + Send + Sync>,
) -> Self {
Self {
inner: Rc::new(ErrorBoundaryInner {
error: RefCell::new(None),
_id: scope,
rerun_boundary,
}),
}
}
/// Push an error into this Error Boundary
pub fn insert_error(&self, scope: ScopeId, error: Box<dyn Debug + 'static>) {
self.error.replace(Some(CapturedError { error, scope }));
pub fn insert_error(
&self,
scope: ScopeId,
error: Box<dyn Debug + 'static>,
backtrace: Backtrace,
) {
println!("{:?} {:?}", error, self.inner._id);
self.inner.error.replace(Some(CapturedError {
error,
scope,
backtrace,
}));
(self.inner.rerun_boundary)(self.inner._id);
}
/// Take any error that has been captured by this error boundary
pub fn take_error(&self) -> Option<CapturedError> {
self.inner.error.take()
}
}
@@ -59,7 +141,7 @@ impl ErrorBoundary {
/// ```rust, ignore
/// #[component]
/// fn App(cx: Scope, count: String) -> Element {
/// let id: i32 = count.parse().throw(cx)?;
/// let id: i32 = count.parse().throw()?;
///
/// cx.render(rsx! {
/// div { "Count {}" }
@@ -84,14 +166,14 @@ pub trait Throw<S = ()>: Sized {
/// ```rust, ignore
/// #[component]
/// fn App(cx: Scope, count: String) -> Element {
/// let id: i32 = count.parse().throw(cx)?;
/// let id: i32 = count.parse().throw()?;
///
/// cx.render(rsx! {
/// div { "Count {}" }
/// })
/// }
/// ```
fn throw(self, cx: &ScopeState) -> Option<Self::Out>;
fn throw(self) -> Option<Self::Out>;
/// Returns an option that evaluates to None if there is an error, injecting the error to the nearest error boundary.
///
@@ -107,45 +189,46 @@ pub trait Throw<S = ()>: Sized {
/// ```rust, ignore
/// #[component]
/// fn App(cx: Scope, count: String) -> Element {
/// let id: i32 = count.parse().throw(cx)?;
/// let id: i32 = count.parse().throw()?;
///
/// cx.render(rsx! {
/// div { "Count {}" }
/// })
/// }
/// ```
fn throw_with<D: Debug + 'static>(
self,
cx: &ScopeState,
e: impl FnOnce() -> D,
) -> Option<Self::Out>;
fn throw_with<D: Debug + 'static>(self, e: impl FnOnce() -> D) -> Option<Self::Out> {
self.throw().or_else(|| throw_error(e()))
}
}
fn throw_error<T>(e: impl Debug + 'static) -> Option<T> {
if let Some(cx) = consume_context::<ErrorBoundary>() {
match current_scope_id() {
Some(id) => cx.insert_error(id, Box::new(e), Backtrace::capture()),
None => {
tracing::error!("Cannot throw error outside of a component's scope.")
}
}
}
None
}
/// We call clone on any errors that can be owned out of a reference
impl<'a, T, O: Debug + 'static, E: ToOwned<Owned = O>> Throw for &'a Result<T, E> {
type Out = &'a T;
fn throw(self, cx: &ScopeState) -> Option<Self::Out> {
fn throw(self) -> Option<Self::Out> {
match self {
Ok(t) => Some(t),
Err(e) => {
cx.throw(e.to_owned());
None
}
Err(e) => throw_error(e.to_owned()),
}
}
fn throw_with<D: Debug + 'static>(
self,
cx: &ScopeState,
err: impl FnOnce() -> D,
) -> Option<Self::Out> {
fn throw_with<D: Debug + 'static>(self, err: impl FnOnce() -> D) -> Option<Self::Out> {
match self {
Ok(t) => Some(t),
Err(_e) => {
cx.throw(err());
None
}
Err(_e) => throw_error(err()),
}
}
}
@@ -154,25 +237,15 @@ impl<'a, T, O: Debug + 'static, E: ToOwned<Owned = O>> Throw for &'a Result<T, E
impl<T, E: Debug + 'static> Throw for Result<T, E> {
type Out = T;
fn throw(self, cx: &ScopeState) -> Option<T> {
fn throw(self) -> Option<T> {
match self {
Ok(t) => Some(t),
Err(e) => {
cx.throw(e);
None
}
Err(e) => throw_error(e),
}
}
fn throw_with<D: Debug + 'static>(
self,
cx: &ScopeState,
error: impl FnOnce() -> D,
) -> Option<Self::Out> {
self.ok().or_else(|| {
cx.throw(error());
None
})
fn throw_with<D: Debug + 'static>(self, error: impl FnOnce() -> D) -> Option<Self::Out> {
self.ok().or_else(|| throw_error(error()))
}
}
@@ -180,21 +253,236 @@ impl<T, E: Debug + 'static> Throw for Result<T, E> {
impl<T> Throw for Option<T> {
type Out = T;
fn throw(self, cx: &ScopeState) -> Option<T> {
self.or_else(|| {
cx.throw("None error.");
None
})
fn throw(self) -> Option<T> {
self.or_else(|| throw_error("Attempted to unwrap a None value."))
}
fn throw_with<D: Debug + 'static>(
self,
cx: &ScopeState,
error: impl FnOnce() -> D,
) -> Option<Self::Out> {
self.or_else(|| {
cx.throw(error());
None
})
fn throw_with<D: Debug + 'static>(self, error: impl FnOnce() -> D) -> Option<Self::Out> {
self.or_else(|| throw_error(error()))
}
}
pub struct ErrorHandler<'a>(Box<dyn Fn(CapturedError) -> LazyNodes<'a, 'a> + 'a>);
impl<'a, F: Fn(CapturedError) -> LazyNodes<'a, 'a> + 'a> From<F> for ErrorHandler<'a> {
fn from(value: F) -> Self {
Self(Box::new(value))
}
}
fn default_handler<'a>(error: CapturedError) -> LazyNodes<'a, 'a> {
LazyNodes::new(move |__cx: &ScopeState| -> VNode {
static TEMPLATE: Template = Template {
name: "error_handle.rs:42:5:884",
roots: &[TemplateNode::Element {
tag: "pre",
namespace: None,
attrs: &[TemplateAttribute::Static {
name: "color",
namespace: Some("style"),
value: "red",
}],
children: &[TemplateNode::DynamicText { id: 0usize }],
}],
node_paths: &[&[0u8, 0u8]],
attr_paths: &[],
};
VNode {
parent: Default::default(),
stable_id: Default::default(),
key: None,
template: std::cell::Cell::new(TEMPLATE),
root_ids: bumpalo::collections::Vec::with_capacity_in(1usize, __cx.bump()).into(),
dynamic_nodes: __cx
.bump()
.alloc([__cx.text_node(format_args!("{0}", error))]),
dynamic_attrs: __cx.bump().alloc([]),
}
})
}
pub struct ErrorBoundaryProps<'a> {
children: Element<'a>,
handle_error: ErrorHandler<'a>,
}
impl<'a> ErrorBoundaryProps<'a> {
/**
Create a builder for building `ErrorBoundaryProps`.
On the builder, call `.children(...)`(optional), `.handle_error(...)`(optional) to set the values of the fields.
Finally, call `.build()` to create the instance of `ErrorBoundaryProps`.
*/
#[allow(dead_code)]
pub fn builder() -> ErrorBoundaryPropsBuilder<'a, ((), ())> {
ErrorBoundaryPropsBuilder {
fields: ((), ()),
_phantom: ::core::default::Default::default(),
}
}
}
#[must_use]
#[doc(hidden)]
#[allow(dead_code, non_camel_case_types, non_snake_case)]
pub struct ErrorBoundaryPropsBuilder<'a, TypedBuilderFields> {
fields: TypedBuilderFields,
_phantom: ::core::marker::PhantomData<&'a ()>,
}
impl<'a, TypedBuilderFields> Clone for ErrorBoundaryPropsBuilder<'a, TypedBuilderFields>
where
TypedBuilderFields: Clone,
{
fn clone(&self) -> Self {
Self {
fields: self.fields.clone(),
_phantom: ::core::default::Default::default(),
}
}
}
impl<'a> Properties<'a> for ErrorBoundaryProps<'a> {
type Builder = ErrorBoundaryPropsBuilder<'a, ((), ())>;
const IS_STATIC: bool = false;
fn builder(_: &'a ScopeState) -> Self::Builder {
ErrorBoundaryProps::builder()
}
unsafe fn memoize(&self, _: &Self) -> bool {
false
}
}
#[doc(hidden)]
#[allow(dead_code, non_camel_case_types, non_snake_case)]
pub trait ErrorBoundaryPropsBuilder_Optional<T> {
fn into_value<F: FnOnce() -> T>(self, default: F) -> T;
}
impl<T> ErrorBoundaryPropsBuilder_Optional<T> for () {
fn into_value<F: FnOnce() -> T>(self, default: F) -> T {
default()
}
}
impl<T> ErrorBoundaryPropsBuilder_Optional<T> for (T,) {
fn into_value<F: FnOnce() -> T>(self, _: F) -> T {
self.0
}
}
#[allow(dead_code, non_camel_case_types, missing_docs)]
impl<'a, __handle_error> ErrorBoundaryPropsBuilder<'a, ((), __handle_error)> {
pub fn children(
self,
children: Element<'a>,
) -> ErrorBoundaryPropsBuilder<'a, ((Element<'a>,), __handle_error)> {
let children = (children,);
let (_, handle_error) = self.fields;
ErrorBoundaryPropsBuilder {
fields: (children, handle_error),
_phantom: self._phantom,
}
}
}
#[doc(hidden)]
#[allow(dead_code, non_camel_case_types, non_snake_case)]
pub enum ErrorBoundaryPropsBuilder_Error_Repeated_field_children {}
#[doc(hidden)]
#[allow(dead_code, non_camel_case_types, missing_docs)]
impl<'a, __handle_error> ErrorBoundaryPropsBuilder<'a, ((Element<'a>,), __handle_error)> {
#[deprecated(note = "Repeated field children")]
pub fn children(
self,
_: ErrorBoundaryPropsBuilder_Error_Repeated_field_children,
) -> ErrorBoundaryPropsBuilder<'a, ((Element<'a>,), __handle_error)> {
self
}
}
#[allow(dead_code, non_camel_case_types, missing_docs)]
impl<'a, __children> ErrorBoundaryPropsBuilder<'a, (__children, ())> {
pub fn handle_error(
self,
handle_error: impl ::core::convert::Into<ErrorHandler<'a>>,
) -> ErrorBoundaryPropsBuilder<'a, (__children, (ErrorHandler<'a>,))> {
let handle_error = (handle_error.into(),);
let (children, _) = self.fields;
ErrorBoundaryPropsBuilder {
fields: (children, handle_error),
_phantom: self._phantom,
}
}
}
#[doc(hidden)]
#[allow(dead_code, non_camel_case_types, non_snake_case)]
pub enum ErrorBoundaryPropsBuilder_Error_Repeated_field_handle_error {}
#[doc(hidden)]
#[allow(dead_code, non_camel_case_types, missing_docs)]
impl<'a, __children> ErrorBoundaryPropsBuilder<'a, (__children, (ErrorHandler<'a>,))> {
#[deprecated(note = "Repeated field handle_error")]
pub fn handle_error(
self,
_: ErrorBoundaryPropsBuilder_Error_Repeated_field_handle_error,
) -> ErrorBoundaryPropsBuilder<'a, (__children, (ErrorHandler<'a>,))> {
self
}
}
#[allow(dead_code, non_camel_case_types, missing_docs)]
impl<
'a,
__handle_error: ErrorBoundaryPropsBuilder_Optional<ErrorHandler<'a>>,
__children: ErrorBoundaryPropsBuilder_Optional<Element<'a>>,
> ErrorBoundaryPropsBuilder<'a, (__children, __handle_error)>
{
pub fn build(self) -> ErrorBoundaryProps<'a> {
let (children, handle_error) = self.fields;
let children = ErrorBoundaryPropsBuilder_Optional::into_value(children, || {
::core::default::Default::default()
});
let handle_error = ErrorBoundaryPropsBuilder_Optional::into_value(handle_error, || {
ErrorHandler(Box::new(default_handler))
});
ErrorBoundaryProps {
children,
handle_error,
}
}
}
/// Create a new error boundary component.
///
/// ## Details
///
/// Error boundaries handle errors within a specific part of your application. Any errors passed in a child with [`Throw`] will be caught by the nearest error boundary.
///
/// ## Example
///
/// ```rust, ignore
/// rsx!{
/// ErrorBoundary {
/// handle_error: |error| rsx! { "Oops, we encountered an error. Please report {error} to the developer of this application" }
/// ThrowsError {}
/// }
/// }
/// ```
///
/// ## Usage
///
/// Error boundaries are an easy way to handle errors in your application.
/// They are similar to `try/catch` in JavaScript, but they only catch errors in the tree below them.
/// Error boundaries are quick to implement, but it can be useful to individually handle errors in your components to provide a better user experience when you know that an error is likely to occur.
#[allow(non_upper_case_globals, non_snake_case)]
pub fn ErrorBoundary<'a>(cx: Scope<'a, ErrorBoundaryProps<'a>>) -> Element {
let error_boundary = use_error_boundary(cx);
match error_boundary.take_error() {
Some(error) => cx.render((cx.props.handle_error.0)(error)),
None => Some({
let __cx = cx;
static TEMPLATE: Template = Template {
name: "examples/error_handle.rs:81:17:2342",
roots: &[TemplateNode::Dynamic { id: 0usize }],
node_paths: &[&[0u8]],
attr_paths: &[],
};
VNode {
parent: Cell::new(None),
stable_id: Cell::new(None),
key: None,
template: std::cell::Cell::new(TEMPLATE),
root_ids: bumpalo::collections::Vec::with_capacity_in(1usize, __cx.bump()).into(),
dynamic_nodes: __cx.bump().alloc([{
let ___nodes = (&cx.props.children).into_dyn_node(__cx);
___nodes
}]),
dynamic_attrs: __cx.bump().alloc([]),
}
}),
}
}
+21
View File
@@ -28,6 +28,27 @@ pub struct Event<T: 'static + ?Sized> {
}
impl<T> Event<T> {
/// Map the event data to a new type
///
/// # Example
///
/// ```rust, ignore
/// rsx! {
/// button {
/// onclick: move |evt: Event<FormData>| {
/// let data = evt.map(|data| data.value());
/// assert_eq!(data.inner(), "hello world");
/// }
/// }
/// }
/// ```
pub fn map<U: 'static, F: FnOnce(&T) -> U>(&self, f: F) -> Event<U> {
Event {
data: Rc::new(f(&self.data)),
propagates: self.propagates.clone(),
}
}
/// Prevent this event from continuing to bubble up the tree to parent elements.
///
/// # Example
+10 -10
View File
@@ -28,14 +28,14 @@ use crate::innerlude::*;
#[allow(non_upper_case_globals, non_snake_case)]
pub fn Fragment<'a>(cx: Scope<'a, FragmentProps<'a>>) -> Element {
let children = cx.props.0.as_ref()?;
Some(VNode {
key: children.key,
parent: children.parent,
template: children.template.clone(),
root_ids: children.root_ids.clone(),
dynamic_nodes: children.dynamic_nodes,
dynamic_attrs: children.dynamic_attrs,
})
Some(cx.vnode(
children.parent.clone(),
children.key,
children.template.clone(),
children.root_ids.clone(),
children.dynamic_nodes,
children.dynamic_attrs,
))
}
pub struct FragmentProps<'a>(Element<'a>);
@@ -91,10 +91,10 @@ impl<'a, const A: bool> FragmentBuilder<'a, A> {
/// })
/// }
/// ```
impl<'a> Properties for FragmentProps<'a> {
impl<'a> Properties<'_> for FragmentProps<'a> {
type Builder = FragmentBuilder<'a, false>;
const IS_STATIC: bool = false;
fn builder() -> Self::Builder {
fn builder(_cx: &ScopeState) -> Self::Builder {
FragmentBuilder(None)
}
unsafe fn memoize(&self, _other: &Self) -> bool {
+11 -11
View File
@@ -18,13 +18,13 @@ use crate::{innerlude::VNode, ScopeState};
/// A concrete type provider for closures that build [`VNode`] structures.
///
/// This struct wraps lazy structs that build [`VNode`] trees Normally, we cannot perform a blanket implementation over
/// This struct wraps lazy structs that build [`VNode`] trees. Normally, we cannot perform a blanket implementation over
/// closures, but if we wrap the closure in a concrete type, we can use it for different branches in matching.
///
///
/// ```rust, ignore
/// LazyNodes::new(|f| {
/// static TEMPLATE: dioxus::core::Template = dioxus::core::Template {
/// static TEMPLATE: dioxus::core::Template = dioxus::core::Template {
/// name: "main.rs:5:5:20", // Source location of the template for hot reloading
/// roots: &[
/// dioxus::core::TemplateNode::Element {
@@ -37,19 +37,19 @@ use crate::{innerlude::VNode, ScopeState};
/// node_paths: &[],
/// attr_paths: &[],
/// };
/// dioxus::core::VNode {
/// parent: None,
/// key: None,
/// template: std::cell::Cell::new(TEMPLATE),
/// root_ids: dioxus::core::exports::bumpalo::collections::Vec::with_capacity_in(
/// f.vnode(
/// None,
/// None,
/// std::cell::Cell::new(TEMPLATE),
/// dioxus::core::exports::bumpalo::collections::Vec::with_capacity_in(
/// 1usize,
/// f.bump(),
/// )
/// .into(),
/// dynamic_nodes: f.bump().alloc([]),
/// dynamic_attrs: f.bump().alloc([]),
/// })
/// }
/// f.bump().alloc([]),
/// f.bump().alloc([]),
/// )
/// })
/// ```
///
/// Find more information about how to construct [`VNode`] at <https://dioxuslabs.com/learn/0.4/contributing/walkthrough_readme#the-rsx-macro>
+10 -9
View File
@@ -76,11 +76,11 @@ pub(crate) mod innerlude {
}
pub use crate::innerlude::{
fc_to_builder, vdom_is_rendering, AnyValue, Attribute, AttributeValue, BorrowedAttributeValue,
CapturedError, Component, DynamicNode, Element, ElementId, Event, Fragment, IntoDynNode,
LazyNodes, Mutation, Mutations, Properties, RenderReturn, Scope, ScopeId, ScopeState, Scoped,
TaskId, Template, TemplateAttribute, TemplateNode, VComponent, VNode, VPlaceholder, VText,
VirtualDom,
fc_to_builder, vdom_is_rendering, AnyValue, Attribute, AttributeType, AttributeValue,
BorrowedAttributeValue, CapturedError, Component, DynamicNode, Element, ElementId, Event,
Fragment, HasAttributes, IntoDynNode, LazyNodes, MountedAttribute, Mutation, Mutations,
Properties, RenderReturn, Scope, ScopeId, ScopeState, Scoped, TaskId, Template,
TemplateAttribute, TemplateNode, VComponent, VNode, VPlaceholder, VText, VirtualDom,
};
/// The purpose of this module is to alleviate imports of many common types
@@ -90,10 +90,11 @@ pub mod prelude {
pub use crate::innerlude::{
consume_context, consume_context_from_scope, current_scope_id, fc_to_builder, has_context,
provide_context, provide_context_to_scope, provide_root_context, push_future,
remove_future, schedule_update_any, spawn, spawn_forever, suspend, throw, AnyValue,
Component, Element, Event, EventHandler, Fragment, IntoAttributeValue, IntoDynNode,
LazyNodes, Properties, Runtime, RuntimeGuard, Scope, ScopeId, ScopeState, Scoped, TaskId,
Template, TemplateAttribute, TemplateNode, Throw, VNode, VirtualDom,
remove_future, schedule_update_any, spawn, spawn_forever, suspend, use_error_boundary,
AnyValue, Attribute, AttributeType, Component, Element, ErrorBoundary, Event, EventHandler,
Fragment, HasAttributes, IntoAttributeValue, IntoDynNode, LazyNodes, MountedAttribute,
Properties, Runtime, RuntimeGuard, Scope, ScopeId, ScopeState, Scoped, TaskId, Template,
TemplateAttribute, TemplateNode, Throw, VNode, VirtualDom,
};
}
+1 -1
View File
@@ -26,7 +26,7 @@ pub struct Mutations<'a> {
/// Any templates encountered while diffing the DOM.
///
/// These must be loaded into a cache before applying the edits
pub templates: Vec<Template<'a>>,
pub templates: Vec<Template<'static>>,
/// Any mutations required to patch the renderer to match the layout of the VirtualDom
pub edits: Vec<Mutation<'a>>,
+164 -51
View File
@@ -1,3 +1,4 @@
use crate::innerlude::{ElementRef, VNodeId};
use crate::{
any_props::AnyProps, arena::ElementId, Element, Event, LazyNodes, ScopeId, ScopeState,
};
@@ -39,6 +40,7 @@ impl<'a> Default for RenderReturn<'a> {
///
/// The dynamic parts of the template are stored separately from the static parts. This allows faster diffing by skipping
/// static parts of the template.
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct VNode<'a> {
/// The key given to the root of this template.
@@ -47,7 +49,10 @@ pub struct VNode<'a> {
pub key: Option<&'a str>,
/// When rendered, this template will be linked to its parent manually
pub parent: Option<ElementId>,
pub(crate) parent: Cell<Option<ElementRef>>,
/// The bubble id assigned to the child that we need to update and drop when diffing happens
pub(crate) stable_id: Cell<Option<VNodeId>>,
/// The static nodes and static descriptor of the template
pub template: Cell<Template<'static>>,
@@ -60,25 +65,49 @@ pub struct VNode<'a> {
pub dynamic_nodes: &'a [DynamicNode<'a>],
/// The dynamic parts of the template
pub dynamic_attrs: &'a [Attribute<'a>],
pub dynamic_attrs: &'a [MountedAttribute<'a>],
}
impl<'a> VNode<'a> {
/// Create a template with no nodes that will be skipped over during diffing
pub fn empty(cx: &'a ScopeState) -> Element<'a> {
Some(VNode {
key: None,
parent: None,
root_ids: RefCell::new(bumpalo::collections::Vec::new_in(cx.bump())),
dynamic_nodes: &[],
dynamic_attrs: &[],
template: Cell::new(Template {
Some(cx.vnode(
Cell::new(None),
None,
Cell::new(Template {
name: "dioxus-empty",
roots: &[],
node_paths: &[],
attr_paths: &[],
}),
})
RefCell::new(bumpalo::collections::Vec::new_in(cx.bump())),
&[],
&[],
))
}
/// Create a new VNode
pub fn new(
key: Option<&'a str>,
template: Template<'static>,
root_ids: bumpalo::collections::Vec<'a, ElementId>,
dynamic_nodes: &'a [DynamicNode<'a>],
dynamic_attrs: &'a [MountedAttribute<'a>],
) -> Self {
Self {
key,
parent: Cell::new(None),
stable_id: Cell::new(None),
template: Cell::new(template),
root_ids: RefCell::new(root_ids),
dynamic_nodes,
dynamic_attrs,
}
}
/// Get the stable id of this node used for bubbling events
pub(crate) fn stable_id(&self) -> Option<VNodeId> {
self.stable_id.get()
}
/// Load a dynamic root at the given index
@@ -319,7 +348,7 @@ pub struct VComponent<'a> {
/// The function pointer of the component, known at compile time
///
/// It is possible that components get folded at comppile time, so these shouldn't be really used as a key
/// It is possible that components get folded at compile time, so these shouldn't be really used as a key
pub(crate) render_fn: *const (),
pub(crate) props: RefCell<Option<Box<dyn AnyProps<'a> + 'a>>>,
@@ -372,6 +401,8 @@ impl<'a> VText<'a> {
pub struct VPlaceholder {
/// The ID of this node in the real DOM
pub(crate) id: Cell<Option<ElementId>>,
/// The parent of this node
pub(crate) parent: Cell<Option<ElementRef>>,
}
impl VPlaceholder {
@@ -414,6 +445,51 @@ pub enum TemplateAttribute<'a> {
},
}
/// An attribute with information about its position in the DOM and the element it was mounted to
#[derive(Debug)]
pub struct MountedAttribute<'a> {
pub(crate) ty: AttributeType<'a>,
/// The element in the DOM that this attribute belongs to
pub(crate) mounted_element: Cell<ElementId>,
}
impl<'a> From<Attribute<'a>> for MountedAttribute<'a> {
fn from(attr: Attribute<'a>) -> Self {
Self {
ty: AttributeType::Single(attr),
mounted_element: Default::default(),
}
}
}
impl<'a> From<&'a [Attribute<'a>]> for MountedAttribute<'a> {
fn from(attr: &'a [Attribute<'a>]) -> Self {
Self {
ty: AttributeType::Many(attr),
mounted_element: Default::default(),
}
}
}
impl<'a> From<&'a Vec<Attribute<'a>>> for MountedAttribute<'a> {
fn from(attr: &'a Vec<Attribute<'a>>) -> Self {
attr.as_slice().into()
}
}
impl<'a> MountedAttribute<'a> {
/// Get the type of this attribute
pub fn attribute_type(&self) -> &AttributeType<'a> {
&self.ty
}
/// Get the element that this attribute is mounted to
pub fn mounted_element(&self) -> ElementId {
self.mounted_element.get()
}
}
/// An attribute on a DOM node, such as `id="my-thing"` or `href="https://example.com"`
#[derive(Debug)]
pub struct Attribute<'a> {
@@ -430,9 +506,6 @@ pub struct Attribute<'a> {
/// An indication of we should always try and set the attribute. Used in controlled components to ensure changes are propagated
pub volatile: bool,
/// The element in the DOM that this attribute belongs to
pub(crate) mounted_element: Cell<ElementId>,
}
impl<'a> Attribute<'a> {
@@ -448,13 +521,40 @@ impl<'a> Attribute<'a> {
value,
namespace,
volatile,
mounted_element: Cell::new(ElementId::default()),
}
}
}
/// The type of an attribute
#[derive(Debug)]
pub enum AttributeType<'a> {
/// A single attribute
Single(Attribute<'a>),
/// Many different attributes sorted by name
Many(&'a [Attribute<'a>]),
}
impl<'a> AttributeType<'a> {
/// Call the given function on each attribute
pub fn for_each<'b, F>(&'b self, mut f: F)
where
F: FnMut(&'b Attribute<'a>),
{
match self {
Self::Single(attr) => f(attr),
Self::Many(attrs) => attrs.iter().for_each(f),
}
}
/// Get the element that this attribute is mounted to
pub fn mounted_element(&self) -> ElementId {
self.mounted_element.get()
/// Try to call the given function on each attribute
pub fn try_for_each<'b, F, E>(&'b self, mut f: F) -> Result<(), E>
where
F: FnMut(&'b Attribute<'a>) -> Result<(), E>,
{
match self {
Self::Single(attr) => f(attr),
Self::Many(attrs) => attrs.iter().try_for_each(f),
}
}
}
@@ -651,52 +751,52 @@ pub trait IntoDynNode<'a, A = ()> {
/// Consume this item along with a scopestate and produce a DynamicNode
///
/// You can use the bump alloactor of the scopestate to creat the dynamic node
fn into_vnode(self, cx: &'a ScopeState) -> DynamicNode<'a>;
fn into_dyn_node(self, cx: &'a ScopeState) -> DynamicNode<'a>;
}
impl<'a> IntoDynNode<'a> for () {
fn into_vnode(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
fn into_dyn_node(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
DynamicNode::default()
}
}
impl<'a> IntoDynNode<'a> for VNode<'a> {
fn into_vnode(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
fn into_dyn_node(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
DynamicNode::Fragment(_cx.bump().alloc([self]))
}
}
impl<'a> IntoDynNode<'a> for DynamicNode<'a> {
fn into_vnode(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
fn into_dyn_node(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
self
}
}
impl<'a, T: IntoDynNode<'a>> IntoDynNode<'a> for Option<T> {
fn into_vnode(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
fn into_dyn_node(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
match self {
Some(val) => val.into_vnode(_cx),
Some(val) => val.into_dyn_node(_cx),
None => DynamicNode::default(),
}
}
}
impl<'a> IntoDynNode<'a> for &Element<'a> {
fn into_vnode(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
fn into_dyn_node(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
match self.as_ref() {
Some(val) => val.clone().into_vnode(_cx),
Some(val) => val.clone().into_dyn_node(_cx),
_ => DynamicNode::default(),
}
}
}
impl<'a, 'b> IntoDynNode<'a> for LazyNodes<'a, 'b> {
fn into_vnode(self, cx: &'a ScopeState) -> DynamicNode<'a> {
fn into_dyn_node(self, cx: &'a ScopeState) -> DynamicNode<'a> {
DynamicNode::Fragment(cx.bump().alloc([cx.render(self).unwrap()]))
}
}
impl<'a, 'b> IntoDynNode<'b> for &'a str {
fn into_vnode(self, cx: &'b ScopeState) -> DynamicNode<'b> {
fn into_dyn_node(self, cx: &'b ScopeState) -> DynamicNode<'b> {
DynamicNode::Text(VText {
value: cx.bump().alloc_str(self),
id: Default::default(),
@@ -705,7 +805,7 @@ impl<'a, 'b> IntoDynNode<'b> for &'a str {
}
impl IntoDynNode<'_> for String {
fn into_vnode(self, cx: &ScopeState) -> DynamicNode {
fn into_dyn_node(self, cx: &ScopeState) -> DynamicNode {
DynamicNode::Text(VText {
value: cx.bump().alloc_str(&self),
id: Default::default(),
@@ -714,42 +814,43 @@ impl IntoDynNode<'_> for String {
}
impl<'b> IntoDynNode<'b> for Arguments<'_> {
fn into_vnode(self, cx: &'b ScopeState) -> DynamicNode<'b> {
fn into_dyn_node(self, cx: &'b ScopeState) -> DynamicNode<'b> {
cx.text_node(self)
}
}
impl<'a> IntoDynNode<'a> for &'a VNode<'a> {
fn into_vnode(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
DynamicNode::Fragment(_cx.bump().alloc([VNode {
parent: self.parent,
template: self.template.clone(),
root_ids: self.root_ids.clone(),
key: self.key,
dynamic_nodes: self.dynamic_nodes,
dynamic_attrs: self.dynamic_attrs,
}]))
fn into_dyn_node(self, cx: &'a ScopeState) -> DynamicNode<'a> {
let vnode = cx.vnode(
self.parent.clone(),
self.key,
self.template.clone(),
self.root_ids.clone(),
self.dynamic_nodes,
self.dynamic_attrs,
);
DynamicNode::Fragment(cx.bump().alloc([vnode]))
}
}
pub trait IntoTemplate<'a> {
fn into_template(self, _cx: &'a ScopeState) -> VNode<'a>;
pub trait IntoVNode<'a> {
fn into_vnode(self, _cx: &'a ScopeState) -> VNode<'a>;
}
impl<'a> IntoTemplate<'a> for VNode<'a> {
fn into_template(self, _cx: &'a ScopeState) -> VNode<'a> {
impl<'a> IntoVNode<'a> for VNode<'a> {
fn into_vnode(self, _cx: &'a ScopeState) -> VNode<'a> {
self
}
}
impl<'a> IntoTemplate<'a> for Element<'a> {
fn into_template(self, cx: &'a ScopeState) -> VNode<'a> {
impl<'a> IntoVNode<'a> for Element<'a> {
fn into_vnode(self, cx: &'a ScopeState) -> VNode<'a> {
match self {
Some(val) => val.into_template(cx),
Some(val) => val.into_vnode(cx),
_ => VNode::empty(cx).unwrap(),
}
}
}
impl<'a, 'b> IntoTemplate<'a> for LazyNodes<'a, 'b> {
fn into_template(self, cx: &'a ScopeState) -> VNode<'a> {
impl<'a, 'b> IntoVNode<'a> for LazyNodes<'a, 'b> {
fn into_vnode(self, cx: &'a ScopeState) -> VNode<'a> {
cx.render(self).unwrap()
}
}
@@ -759,12 +860,12 @@ pub struct FromNodeIterator;
impl<'a, T, I> IntoDynNode<'a, FromNodeIterator> for T
where
T: Iterator<Item = I>,
I: IntoTemplate<'a>,
I: IntoVNode<'a>,
{
fn into_vnode(self, cx: &'a ScopeState) -> DynamicNode<'a> {
fn into_dyn_node(self, cx: &'a ScopeState) -> DynamicNode<'a> {
let mut nodes = bumpalo::collections::Vec::new_in(cx.bump());
nodes.extend(self.into_iter().map(|node| node.into_template(cx)));
nodes.extend(self.into_iter().map(|node| node.into_vnode(cx)));
match nodes.into_bump_slice() {
children if children.is_empty() => DynamicNode::default(),
@@ -838,3 +939,15 @@ impl<'a, T: IntoAttributeValue<'a>> IntoAttributeValue<'a> for Option<T> {
}
}
}
/// A trait for anything that has a dynamic list of attributes
pub trait HasAttributes<'a> {
/// Push an attribute onto the list of attributes
fn push_attribute(
self,
name: &'a str,
ns: Option<&'static str>,
attr: impl IntoAttributeValue<'a>,
volatile: bool,
) -> Self;
}
+9 -6
View File
@@ -32,7 +32,7 @@ use crate::innerlude::*;
/// data: &'a str
/// }
/// ```
pub trait Properties: Sized {
pub trait Properties<'a>: Sized {
/// The type of the builder for this component.
/// Used to create "in-progress" versions of the props.
type Builder;
@@ -41,7 +41,7 @@ pub trait Properties: Sized {
const IS_STATIC: bool;
/// Create a builder for this component.
fn builder() -> Self::Builder;
fn builder(cx: &'a ScopeState) -> Self::Builder;
/// Memoization can only happen if the props are valid for the 'static lifetime
///
@@ -51,10 +51,10 @@ pub trait Properties: Sized {
unsafe fn memoize(&self, other: &Self) -> bool;
}
impl Properties for () {
impl Properties<'_> for () {
type Builder = EmptyBuilder;
const IS_STATIC: bool = true;
fn builder() -> Self::Builder {
fn builder(_cx: &ScopeState) -> Self::Builder {
EmptyBuilder {}
}
unsafe fn memoize(&self, _other: &Self) -> bool {
@@ -70,8 +70,11 @@ impl EmptyBuilder {
/// This utility function launches the builder method so rsx! and html! macros can use the typed-builder pattern
/// to initialize a component's props.
pub fn fc_to_builder<'a, T: Properties + 'a>(_: fn(Scope<'a, T>) -> Element<'a>) -> T::Builder {
T::builder()
pub fn fc_to_builder<'a, T: Properties<'a> + 'a>(
cx: &'a ScopeState,
_: fn(Scope<'a, T>) -> Element<'a>,
) -> T::Builder {
T::builder(cx)
}
#[cfg(not(miri))]
+23 -1
View File
@@ -87,6 +87,16 @@ impl Runtime {
self.scope_stack.borrow().last().copied()
}
/// Call this function with the current scope set to the given scope
///
/// Useful in a limited number of scenarios, not public.
pub(crate) fn with_scope<O>(&self, id: ScopeId, f: impl FnOnce() -> O) -> O {
self.scope_stack.borrow_mut().push(id);
let o = f();
self.scope_stack.borrow_mut().pop();
o
}
/// Get the context for any scope given its ID
///
/// This is useful for inserting or removing contexts from a scope, or rendering out its root node
@@ -98,7 +108,7 @@ impl Runtime {
}
}
/// A gaurd for a new runtime. This must be used to override the current runtime when importing components from a dynamic library that has it's own runtime.
/// A guard for a new runtime. This must be used to override the current runtime when importing components from a dynamic library that has it's own runtime.
///
/// ```rust
/// use dioxus::prelude::*;
@@ -123,6 +133,7 @@ impl Runtime {
/// }
/// }
///
/// # #[allow(non_snake_case)]
/// fn Component(cx: Scope<ComponentProps>) -> Element {
/// cx.use_hook(|| RuntimeGuard::new(cx.props.runtime.clone()));
///
@@ -137,6 +148,17 @@ impl RuntimeGuard {
push_runtime(runtime.clone());
Self(runtime)
}
/// Run a function with a given runtime and scope in context
pub fn with<O>(runtime: Rc<Runtime>, scope: Option<ScopeId>, f: impl FnOnce() -> O) -> O {
let guard = Self::new(runtime.clone());
let o = match scope {
Some(scope) => Runtime::with_scope(&runtime, scope, f),
None => f(),
};
drop(guard);
o
}
}
impl Drop for RuntimeGuard {
+11 -7
View File
@@ -19,7 +19,7 @@ pub struct TaskId(pub usize);
/// the task itself is the waker
pub(crate) struct LocalTask {
pub scope: ScopeId,
pub(super) task: RefCell<Pin<Box<dyn Future<Output = ()> + 'static>>>,
pub task: RefCell<Pin<Box<dyn Future<Output = ()> + 'static>>>,
pub waker: Waker,
}
@@ -48,11 +48,15 @@ impl Scheduler {
})),
};
entry.insert(task);
let mut cx = std::task::Context::from_waker(&task.waker);
self.sender
.unbounded_send(SchedulerMsg::TaskNotified(task_id))
.expect("Scheduler should exist");
if !task.task.borrow_mut().as_mut().poll(&mut cx).is_ready() {
self.sender
.unbounded_send(SchedulerMsg::TaskNotified(task_id))
.expect("Scheduler should exist");
}
entry.insert(task);
task_id
}
@@ -60,8 +64,8 @@ impl Scheduler {
/// Drop the future with the given TaskId
///
/// This does not abort the task, so you'll want to wrap it in an aborthandle if that's important to you
pub fn remove(&self, id: TaskId) {
self.tasks.borrow_mut().try_remove(id.0);
pub fn remove(&self, id: TaskId) -> Option<LocalTask> {
self.tasks.borrow_mut().try_remove(id.0)
}
}
+1
View File
@@ -36,6 +36,7 @@ impl VirtualDom {
borrowed_props: Default::default(),
attributes_to_drop_before_render: Default::default(),
element_refs_to_drop: Default::default(),
}));
let context =
+8 -32
View File
@@ -1,5 +1,5 @@
use crate::{
innerlude::{ErrorBoundary, Scheduler, SchedulerMsg},
innerlude::{Scheduler, SchedulerMsg},
runtime::{with_current_scope, with_runtime},
Element, ScopeId, TaskId,
};
@@ -7,7 +7,6 @@ use rustc_hash::FxHashSet;
use std::{
any::Any,
cell::{Cell, RefCell},
fmt::Debug,
future::Future,
rc::Rc,
sync::Arc,
@@ -230,17 +229,7 @@ impl ScopeContext {
/// This is good for tasks that need to be run after the component has been dropped.
pub fn spawn_forever(&self, fut: impl Future<Output = ()> + 'static) -> TaskId {
// The root scope will never be unmounted so we can just add the task at the top of the app
let id = self.tasks.spawn(ScopeId::ROOT, fut);
// wake up the scheduler if it is sleeping
self.tasks
.sender
.unbounded_send(SchedulerMsg::TaskNotified(id))
.expect("Scheduler should exist");
self.spawned_tasks.borrow_mut().insert(id);
id
self.tasks.spawn(ScopeId::ROOT, fut)
}
/// Informs the scheduler that this task is no longer needed and should be removed.
@@ -250,19 +239,6 @@ impl ScopeContext {
self.tasks.remove(id);
}
/// Inject an error into the nearest error boundary and quit rendering
///
/// The error doesn't need to implement Error or any specific traits since the boundary
/// itself will downcast the error into a trait object.
pub fn throw(&self, error: impl Debug + 'static) -> Option<()> {
if let Some(cx) = self.consume_context::<Rc<ErrorBoundary>>() {
cx.insert_error(self.scope_id(), Box::new(error));
}
// Always return none during a throw
None
}
/// Mark this component as suspended and then return None
pub fn suspend(&self) -> Option<Element> {
self.suspended.set(true);
@@ -332,11 +308,6 @@ pub fn suspend() -> Option<Element<'static>> {
None
}
/// Throw an error into the nearest error boundary
pub fn throw(error: impl Debug + 'static) -> Option<()> {
with_current_scope(|cx| cx.throw(error)).flatten()
}
/// Pushes the future onto the poll queue to be polled after the component renders.
pub fn push_future(fut: impl Future<Output = ()> + 'static) -> Option<TaskId> {
with_current_scope(|cx| cx.push_future(fut))
@@ -347,11 +318,16 @@ pub fn spawn(fut: impl Future<Output = ()> + 'static) {
with_current_scope(|cx| cx.spawn(fut));
}
/// Spawn a future on a component given its [`ScopeId`].
pub fn spawn_at(fut: impl Future<Output = ()> + 'static, scope_id: ScopeId) -> Option<TaskId> {
with_runtime(|rt| rt.get_context(scope_id).unwrap().push_future(fut))
}
/// Spawn a future that Dioxus won't clean up when this component is unmounted
///
/// This is good for tasks that need to be run after the component has been dropped.
pub fn spawn_forever(fut: impl Future<Output = ()> + 'static) -> Option<TaskId> {
with_current_scope(|cx| cx.spawn_forever(fut))
spawn_at(fut, ScopeId(0))
}
/// Informs the scheduler that this task is no longer needed and should be removed.
+61 -42
View File
@@ -2,13 +2,13 @@ use crate::{
any_props::AnyProps,
any_props::VProps,
bump_frame::BumpFrame,
innerlude::ErrorBoundary,
innerlude::{DynamicNode, EventHandler, VComponent, VText},
innerlude::{DynamicNode, ElementRef, EventHandler, VComponent, VNodeId, VText},
lazynodes::LazyNodes,
nodes::{IntoAttributeValue, IntoDynNode, RenderReturn},
runtime::Runtime,
scope_context::ScopeContext,
AnyValue, Attribute, AttributeValue, Element, Event, Properties, TaskId,
AnyValue, Attribute, AttributeType, AttributeValue, Element, ElementId, Event,
MountedAttribute, Properties, TaskId, Template, VNode,
};
use bumpalo::{boxed::Box as BumpBox, Bump};
use std::{
@@ -94,6 +94,7 @@ pub struct ScopeState {
pub(crate) hook_idx: Cell<usize>,
pub(crate) borrowed_props: RefCell<Vec<*const VComponent<'static>>>,
pub(crate) element_refs_to_drop: RefCell<Vec<VNodeId>>,
pub(crate) attributes_to_drop_before_render: RefCell<Vec<*const Attribute<'static>>>,
pub(crate) props: Option<Box<dyn AnyProps<'static>>>,
@@ -101,6 +102,7 @@ pub struct ScopeState {
impl Drop for ScopeState {
fn drop(&mut self) {
self.drop_listeners();
self.runtime.remove_context(self.context_id);
}
}
@@ -344,25 +346,45 @@ impl<'src> ScopeState {
/// // Actually build the tree and allocate it
/// cx.render(lazy_tree)
/// }
///```
/// ```
pub fn render(&'src self, rsx: LazyNodes<'src, '_>) -> Element<'src> {
let element = rsx.call(self);
// Note: We can't do anything in this function related to safety because the user could always circumvent it by creating a VNode manually and return it without calling this function
Some(rsx.call(self))
}
/// Create a [`crate::VNode`] from the component parts
pub fn vnode(
&'src self,
parent: Cell<Option<ElementRef>>,
key: Option<&'src str>,
template: Cell<Template<'static>>,
root_ids: RefCell<bumpalo::collections::Vec<'src, ElementId>>,
dynamic_nodes: &'src [DynamicNode<'src>],
dynamic_attrs: &'src [MountedAttribute<'src>],
) -> VNode<'src> {
let mut listeners = self.attributes_to_drop_before_render.borrow_mut();
for attr in element.dynamic_attrs {
match attr.value {
// We need to drop listeners before the next render because they may borrow data from the borrowed props which will be dropped
AttributeValue::Listener(_) => {
let unbounded = unsafe { std::mem::transmute(attr as *const Attribute) };
listeners.push(unbounded);
}
// We need to drop any values manually to make sure that their drop implementation is called before the next render
AttributeValue::Any(_) => {
let unbounded = unsafe { std::mem::transmute(attr as *const Attribute) };
self.previous_frame().add_attribute_to_drop(unbounded);
}
for attr in dynamic_attrs {
let attrs = match attr.ty {
AttributeType::Single(ref attr) => std::slice::from_ref(attr),
AttributeType::Many(attrs) => attrs,
};
_ => (),
for attr in attrs {
match attr.value {
// We need to drop listeners before the next render because they may borrow data from the borrowed props which will be dropped
AttributeValue::Listener(_) => {
let unbounded = unsafe { std::mem::transmute(attr as *const Attribute) };
listeners.push(unbounded);
}
// We need to drop any values manually to make sure that their drop implementation is called before the next render
AttributeValue::Any(_) => {
let unbounded = unsafe { std::mem::transmute(attr as *const Attribute) };
self.previous_frame().add_attribute_to_drop(unbounded);
}
_ => (),
}
}
}
@@ -371,7 +393,7 @@ impl<'src> ScopeState {
.previous_frame()
.props_to_drop_before_reset
.borrow_mut();
for node in element.dynamic_nodes {
for node in dynamic_nodes {
if let DynamicNode::Component(comp) = node {
let unbounded = unsafe { std::mem::transmute(comp as *const VComponent) };
if !comp.static_props {
@@ -381,7 +403,15 @@ impl<'src> ScopeState {
}
}
Some(element)
VNode {
stable_id: Default::default(),
key,
parent,
template,
root_ids,
dynamic_nodes,
dynamic_attrs,
}
}
/// Create a dynamic text node using [`Arguments`] and the [`ScopeState`]'s internal [`Bump`] allocator
@@ -406,7 +436,7 @@ impl<'src> ScopeState {
/// Convert any item that implements [`IntoDynNode`] into a [`DynamicNode`] using the internal [`Bump`] allocator
pub fn make_node<'c, I>(&'src self, into: impl IntoDynNode<'src, I> + 'c) -> DynamicNode {
into.into_vnode(self)
into.into_dyn_node(self)
}
/// Create a new [`Attribute`] from a name, value, namespace, and volatile bool
@@ -419,13 +449,15 @@ impl<'src> ScopeState {
value: impl IntoAttributeValue<'src>,
namespace: Option<&'static str>,
volatile: bool,
) -> Attribute<'src> {
Attribute {
name,
namespace,
volatile,
) -> MountedAttribute<'src> {
MountedAttribute {
ty: AttributeType::Single(Attribute {
name,
namespace,
volatile,
value: value.into_value(self.bump()),
}),
mounted_element: Default::default(),
value: value.into_value(self.bump()),
}
}
@@ -451,7 +483,7 @@ impl<'src> ScopeState {
) -> DynamicNode<'src>
where
// The properties must be valid until the next bump frame
P: Properties + 'src,
P: Properties<'src> + 'src,
// The current bump allocator frame must outlive the child's borrowed props
'src: 'child,
{
@@ -466,7 +498,7 @@ impl<'src> ScopeState {
render_fn: component as *const (),
static_props: P::IS_STATIC,
props: RefCell::new(Some(extended)),
scope: Cell::new(None),
scope: Default::default(),
})
}
@@ -517,19 +549,6 @@ impl<'src> ScopeState {
AttributeValue::Any(RefCell::new(Some(boxed)))
}
/// Inject an error into the nearest error boundary and quit rendering
///
/// The error doesn't need to implement Error or any specific traits since the boundary
/// itself will downcast the error into a trait object.
pub fn throw(&self, error: impl Debug + 'static) -> Option<()> {
if let Some(cx) = self.consume_context::<Rc<ErrorBoundary>>() {
cx.insert_error(self.scope_id(), Box::new(error));
}
// Always return none during a throw
None
}
/// Mark this component as suspended and then return None
pub fn suspend(&self) -> Option<Element> {
let cx = self.context();
+98 -74
View File
@@ -11,12 +11,14 @@ use crate::{
nodes::{Template, TemplateId},
runtime::{Runtime, RuntimeGuard},
scopes::{ScopeId, ScopeState},
AttributeValue, Element, Event, Scope,
AttributeValue, Element, Event, Scope, VNode,
};
use futures_util::{pin_mut, StreamExt};
use rustc_hash::{FxHashMap, FxHashSet};
use slab::Slab;
use std::{any::Any, cell::Cell, collections::BTreeSet, future::Future, rc::Rc};
use std::{
any::Any, cell::Cell, collections::BTreeSet, future::Future, ptr::NonNull, rc::Rc, sync::Arc,
};
/// A virtual node system that progresses user events and diffs UI trees.
///
@@ -186,7 +188,10 @@ pub struct VirtualDom {
pub(crate) templates: FxHashMap<TemplateId, FxHashMap<usize, Template<'static>>>,
// Every element is actually a dual reference - one to the template and the other to the dynamic node in that template
pub(crate) elements: Slab<ElementRef>,
pub(crate) element_refs: Slab<Option<NonNull<VNode<'static>>>>,
// The element ids that are used in the renderer
pub(crate) elements: Slab<Option<ElementRef>>,
pub(crate) mutations: Mutations<'static>,
@@ -263,6 +268,7 @@ impl VirtualDom {
dirty_scopes: Default::default(),
templates: Default::default(),
elements: Default::default(),
element_refs: Default::default(),
mutations: Mutations::default(),
suspended_scopes: Default::default(),
};
@@ -273,10 +279,13 @@ impl VirtualDom {
);
// Unlike react, we provide a default error boundary that just renders the error as a string
root.provide_context(Rc::new(ErrorBoundary::new(ScopeId::ROOT)));
root.provide_context(Rc::new(ErrorBoundary::new_in_scope(
ScopeId::ROOT,
Arc::new(|_| {}),
)));
// the root element is always given element ID 0 since it's the container for the entire tree
dom.elements.insert(ElementRef::none());
dom.elements.insert(None);
dom
}
@@ -314,9 +323,9 @@ impl VirtualDom {
}
}
/// Call a listener inside the VirtualDom with data from outside the VirtualDom.
/// Call a listener inside the VirtualDom with data from outside the VirtualDom. **The ElementId passed in must be the id of an dynamic element, not a static node or a text node.**
///
/// This method will identify the appropriate element. The data must match up with the listener delcared. Note that
/// This method will identify the appropriate element. The data must match up with the listener declared. Note that
/// this method does not give any indication as to the success of the listener call. If the listener is not found,
/// nothing will happen.
///
@@ -353,8 +362,15 @@ impl VirtualDom {
| | | <-- no, broke early
| <-- no, broke early
*/
let mut parent_path = self.elements.get(element.0);
let mut listeners = vec![];
let parent_path = match self.elements.get(element.0) {
Some(Some(el)) => el,
_ => return,
};
let mut parent_node = self
.element_refs
.get(parent_path.template.0)
.cloned()
.map(|el| (*parent_path, el));
// We will clone this later. The data itself is wrapped in RC to be used in callbacks if required
let uievent = Event {
@@ -365,82 +381,93 @@ impl VirtualDom {
// If the event bubbles, we traverse through the tree until we find the target element.
if bubbles {
// Loop through each dynamic attribute (in a depth first order) in this template before moving up to the template's parent.
while let Some(el_ref) = parent_path {
while let Some((path, el_ref)) = parent_node {
let mut listeners = vec![];
// safety: we maintain references of all vnodes in the element slab
if let Some(template) = el_ref.template {
let template = unsafe { template.as_ref() };
let node_template = template.template.get();
let target_path = el_ref.path;
let template = unsafe { el_ref.unwrap().as_ref() };
let node_template = template.template.get();
let target_path = path.path;
for (idx, attr) in template.dynamic_attrs.iter().enumerate() {
let this_path = node_template.attr_paths[idx];
for (idx, attr) in template.dynamic_attrs.iter().enumerate() {
let this_path = node_template.attr_paths[idx];
// Remove the "on" prefix if it exists, TODO, we should remove this and settle on one
if attr.name.trim_start_matches("on") == name
&& target_path.is_decendant(&this_path)
{
listeners.push(&attr.value);
// Break if this is the exact target element.
// This means we won't call two listeners with the same name on the same element. This should be
// documented, or be rejected from the rsx! macro outright
if target_path == this_path {
break;
// Remove the "on" prefix if it exists, TODO, we should remove this and settle on one
if target_path.is_decendant(&this_path) {
attr.ty.for_each(|attribute| {
if attribute.name.trim_start_matches("on") == name {
if let AttributeValue::Listener(listener) = &attribute.value {
listeners.push(listener);
}
}
});
// Break if this is the exact target element.
// This means we won't call two listeners with the same name on the same element. This should be
// documented, or be rejected from the rsx! macro outright
if target_path == this_path {
break;
}
}
// Now that we've accumulated all the parent attributes for the target element, call them in reverse order
// We check the bubble state between each call to see if the event has been stopped from bubbling
for listener in listeners.drain(..).rev() {
if let AttributeValue::Listener(listener) = listener {
let origin = el_ref.scope;
self.runtime.scope_stack.borrow_mut().push(origin);
self.runtime.rendering.set(false);
if let Some(cb) = listener.borrow_mut().as_deref_mut() {
cb(uievent.clone());
}
self.runtime.scope_stack.borrow_mut().pop();
self.runtime.rendering.set(true);
if !uievent.propagates.get() {
return;
}
}
}
parent_path = template.parent.and_then(|id| self.elements.get(id.0));
} else {
break;
}
// Now that we've accumulated all the parent attributes for the target element, call them in reverse order
// We check the bubble state between each call to see if the event has been stopped from bubbling
for listener in listeners.into_iter().rev() {
let origin = path.scope;
self.runtime.scope_stack.borrow_mut().push(origin);
self.runtime.rendering.set(false);
if let Some(cb) = listener.borrow_mut().as_deref_mut() {
cb(uievent.clone());
}
self.runtime.scope_stack.borrow_mut().pop();
self.runtime.rendering.set(true);
if !uievent.propagates.get() {
return;
}
}
parent_node = template.parent.get().and_then(|element_ref| {
self.element_refs
.get(element_ref.template.0)
.cloned()
.map(|el| (element_ref, el))
});
}
} else {
// Otherwise, we just call the listener on the target element
if let Some(el_ref) = parent_path {
if let Some((path, el_ref)) = parent_node {
// safety: we maintain references of all vnodes in the element slab
if let Some(template) = el_ref.template {
let template = unsafe { template.as_ref() };
let node_template = template.template.get();
let target_path = el_ref.path;
let template = unsafe { el_ref.unwrap().as_ref() };
let node_template = template.template.get();
let target_path = path.path;
for (idx, attr) in template.dynamic_attrs.iter().enumerate() {
let this_path = node_template.attr_paths[idx];
for (idx, attr) in template.dynamic_attrs.iter().enumerate() {
let this_path = node_template.attr_paths[idx];
// Remove the "on" prefix if it exists, TODO, we should remove this and settle on one
// Only call the listener if this is the exact target element.
if attr.name.trim_start_matches("on") == name && target_path == this_path {
if let AttributeValue::Listener(listener) = &attr.value {
let origin = el_ref.scope;
self.runtime.scope_stack.borrow_mut().push(origin);
self.runtime.rendering.set(false);
if let Some(cb) = listener.borrow_mut().as_deref_mut() {
cb(uievent.clone());
// Remove the "on" prefix if it exists, TODO, we should remove this and settle on one
// Only call the listener if this is the exact target element.
if target_path == this_path {
let mut should_stop = false;
attr.ty.for_each(|attribute| {
if attribute.name.trim_start_matches("on") == name {
if let AttributeValue::Listener(listener) = &attribute.value {
let origin = path.scope;
self.runtime.scope_stack.borrow_mut().push(origin);
self.runtime.rendering.set(false);
if let Some(cb) = listener.borrow_mut().as_deref_mut() {
cb(uievent.clone());
}
self.runtime.scope_stack.borrow_mut().pop();
self.runtime.rendering.set(true);
should_stop = true;
}
self.runtime.scope_stack.borrow_mut().pop();
self.runtime.rendering.set(true);
break;
}
});
if should_stop {
return;
}
}
}
@@ -563,7 +590,7 @@ impl VirtualDom {
// If an error occurs, we should try to render the default error component and context where the error occured
RenderReturn::Aborted(placeholder) => {
tracing::debug!("Ran into suspended or aborted scope during rebuild");
let id = self.next_null();
let id = self.next_element();
placeholder.id.set(Some(id));
self.mutations.push(Mutation::CreatePlaceholder { id });
}
@@ -595,15 +622,12 @@ impl VirtualDom {
/// The mutations will be thrown out, so it's best to use this method for things like SSR that have async content
pub async fn wait_for_suspense(&mut self) {
loop {
// println!("waiting for suspense {:?}", self.suspended_scopes);
if self.suspended_scopes.is_empty() {
return;
}
// println!("waiting for suspense");
self.wait_for_work().await;
// println!("Rendered immediately");
_ = self.render_immediate();
}
}
+2 -2
View File
@@ -24,9 +24,9 @@ fn NoneChild(_cx: Scope) -> Element {
}
fn ThrowChild(cx: Scope) -> Element {
cx.throw(std::io::Error::new(std::io::ErrorKind::AddrInUse, "asd"))?;
Err(std::io::Error::new(std::io::ErrorKind::AddrInUse, "asd")).throw()?;
let _g: i32 = "123123".parse().throw(cx)?;
let _g: i32 = "123123".parse().throw()?;
cx.render(rsx! {
div {}
+82
View File
@@ -0,0 +1,82 @@
use dioxus::prelude::*;
use dioxus_core::ElementId;
use std::{rc::Rc, sync::Mutex};
static CLICKS: Mutex<usize> = Mutex::new(0);
#[test]
fn events_propagate() {
set_event_converter(Box::new(dioxus_html::SerializedHtmlEventConverter));
let mut dom = VirtualDom::new(app);
_ = dom.rebuild();
// Top-level click is registered
dom.handle_event(
"click",
Rc::new(PlatformEventData::new(Box::<SerializedMouseData>::default())),
ElementId(1),
true,
);
assert_eq!(*CLICKS.lock().unwrap(), 1);
// break reference....
for _ in 0..5 {
dom.mark_dirty(ScopeId(0));
_ = dom.render_immediate();
}
// Lower click is registered
dom.handle_event(
"click",
Rc::new(PlatformEventData::new(Box::<SerializedMouseData>::default())),
ElementId(2),
true,
);
assert_eq!(*CLICKS.lock().unwrap(), 3);
// break reference....
for _ in 0..5 {
dom.mark_dirty(ScopeId(0));
_ = dom.render_immediate();
}
// Stop propagation occurs
dom.handle_event(
"click",
Rc::new(PlatformEventData::new(Box::<SerializedMouseData>::default())),
ElementId(2),
true,
);
assert_eq!(*CLICKS.lock().unwrap(), 3);
}
fn app(cx: Scope) -> Element {
render! {
div { onclick: move |_| {
println!("top clicked");
*CLICKS.lock().unwrap() += 1;
},
vec![
render! {
problematic_child {}
}
].into_iter()
}
}
}
fn problematic_child(cx: Scope) -> Element {
render! {
button { onclick: move |evt| {
println!("bottom clicked");
let mut clicks = CLICKS.lock().unwrap();
if *clicks == 3 {
evt.stop_propagation();
} else {
*clicks += 1;
}
} }
}
}
+36 -33
View File
@@ -1,8 +1,8 @@
#![cfg(not(miri))]
use dioxus::prelude::Props;
use dioxus_core::*;
use std::{cell::Cell, collections::HashSet};
use dioxus_core::{MountedAttribute, *};
use std::{cell::Cell, cfg, collections::HashSet};
fn random_ns() -> Option<&'static str> {
let namespace = rand::random::<u8>() % 2;
@@ -170,22 +170,24 @@ fn create_random_dynamic_node(cx: &ScopeState, depth: usize) -> DynamicNode {
let range = if depth > 5 { 1 } else { 4 };
match rand::random::<u8>() % range {
0 => DynamicNode::Placeholder(Default::default()),
1 => cx.make_node((0..(rand::random::<u8>() % 5)).map(|_| VNode {
key: None,
parent: Default::default(),
template: Cell::new(Template {
name: concat!(file!(), ":", line!(), ":", column!(), ":0"),
roots: &[TemplateNode::Dynamic { id: 0 }],
node_paths: &[&[0]],
attr_paths: &[],
}),
root_ids: bumpalo::collections::Vec::new_in(cx.bump()).into(),
dynamic_nodes: cx.bump().alloc([cx.component(
create_random_element,
DepthProps { depth, root: false },
"create_random_element",
)]),
dynamic_attrs: &[],
1 => cx.make_node((0..(rand::random::<u8>() % 5)).map(|_| {
cx.vnode(
None.into(),
Default::default(),
Cell::new(Template {
name: concat!(file!(), ":", line!(), ":", column!(), ":0"),
roots: &[TemplateNode::Dynamic { id: 0 }],
node_paths: &[&[0]],
attr_paths: &[],
}),
bumpalo::collections::Vec::new_in(cx.bump()).into(),
cx.bump().alloc([cx.component(
create_random_element,
DepthProps { depth, root: false },
"create_random_element",
)]),
&[],
)
})),
2 => cx.component(
create_random_element,
@@ -205,7 +207,7 @@ fn create_random_dynamic_node(cx: &ScopeState, depth: usize) -> DynamicNode {
}
}
fn create_random_dynamic_attr(cx: &ScopeState) -> Attribute {
fn create_random_dynamic_attr(cx: &ScopeState) -> MountedAttribute {
let value = match rand::random::<u8>() % 7 {
0 => AttributeValue::Text(Box::leak(
format!("{}", rand::random::<usize>()).into_boxed_str(),
@@ -217,7 +219,7 @@ fn create_random_dynamic_attr(cx: &ScopeState) -> Attribute {
5 => AttributeValue::None,
6 => {
let value = cx.listener(|e: Event<String>| println!("{:?}", e));
return Attribute::new("ondata", value, None, false);
return Attribute::new("ondata", value, None, false).into();
}
_ => unreachable!(),
};
@@ -227,6 +229,7 @@ fn create_random_dynamic_attr(cx: &ScopeState) -> Attribute {
random_ns(),
rand::random(),
)
.into()
}
static mut TEMPLATE_COUNT: usize = 0;
@@ -271,13 +274,13 @@ fn create_random_element(cx: Scope<DepthProps>) -> Element {
)
.into_boxed_str(),
));
// println!("{template:#?}");
let node = VNode {
key: None,
parent: None,
template: Cell::new(template),
root_ids: bumpalo::collections::Vec::new_in(cx.bump()).into(),
dynamic_nodes: {
println!("{template:#?}");
let node = cx.vnode(
None.into(),
None,
Cell::new(template),
bumpalo::collections::Vec::new_in(cx.bump()).into(),
{
let dynamic_nodes: Vec<_> = dynamic_node_types
.iter()
.map(|ty| match ty {
@@ -291,12 +294,12 @@ fn create_random_element(cx: Scope<DepthProps>) -> Element {
.collect();
cx.bump().alloc(dynamic_nodes)
},
dynamic_attrs: cx.bump().alloc(
cx.bump().alloc(
(0..template.attr_paths.len())
.map(|_| create_random_dynamic_attr(cx))
.collect::<Vec<_>>(),
),
};
);
Some(node)
}
_ => None,
@@ -306,10 +309,10 @@ fn create_random_element(cx: Scope<DepthProps>) -> Element {
}
// test for panics when creating random nodes and templates
#[cfg(not(miri))]
#[test]
fn create() {
for _ in 0..1000 {
let repeat_count = if cfg!(miri) { 100 } else { 1000 };
for _ in 0..repeat_count {
let mut vdom =
VirtualDom::new_with_props(create_random_element, DepthProps { depth: 0, root: true });
let _ = vdom.rebuild();
@@ -318,10 +321,10 @@ fn create() {
// test for panics when diffing random nodes
// This test will change the template every render which is not very realistic, but it helps stress the system
#[cfg(not(miri))]
#[test]
fn diff() {
for _ in 0..100000 {
let repeat_count = if cfg!(miri) { 100 } else { 1000 };
for _ in 0..repeat_count {
let mut vdom =
VirtualDom::new_with_props(create_random_element, DepthProps { depth: 0, root: true });
let _ = vdom.rebuild();
+4 -1
View File
@@ -10,6 +10,8 @@ fn basic_syntax_is_a_template(cx: Scope) -> Element {
div { key: "12345",
class: "asd",
class: "{asd}",
class: if true { "{asd}" },
class: if false { "{asd}" },
onclick: move |_| {},
div { "{var}" }
div {
@@ -24,6 +26,7 @@ fn basic_syntax_is_a_template(cx: Scope) -> Element {
}
})
}
#[test]
fn dual_stream() {
let mut dom = VirtualDom::new(basic_syntax_is_a_template);
@@ -36,7 +39,7 @@ fn dual_stream() {
LoadTemplate { name: "template", index: 0, id: ElementId(1) },
SetAttribute {
name: "class",
value: (&*bump.alloc("123".into_value(&bump))).into(),
value: (&*bump.alloc("asd 123 123".into_value(&bump))).into(),
id: ElementId(1),
ns: None,
},
+8 -1
View File
@@ -4,6 +4,7 @@
//! Tests for the lifecycle of components.
use dioxus::core::{ElementId, Mutation::*};
use dioxus::prelude::*;
use dioxus_html::SerializedHtmlEventConverter;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
@@ -39,6 +40,7 @@ fn manual_diffing() {
#[test]
fn events_generate() {
set_event_converter(Box::new(SerializedHtmlEventConverter));
fn app(cx: Scope) -> Element {
let count = cx.use_hook(|| 0);
@@ -56,7 +58,12 @@ fn events_generate() {
let mut dom = VirtualDom::new(app);
_ = dom.rebuild();
dom.handle_event("click", Rc::new(MouseData::default()), ElementId(1), true);
dom.handle_event(
"click",
Rc::new(PlatformEventData::new(Box::<SerializedMouseData>::default())),
ElementId(1),
true,
);
dom.mark_dirty(ScopeId::ROOT);
let edits = dom.render_immediate();
+9 -1
View File
@@ -1,15 +1,23 @@
use crate::dioxus_elements::SerializedMouseData;
use dioxus::prelude::*;
use dioxus_core::ElementId;
use dioxus_elements::SerializedHtmlEventConverter;
use std::rc::Rc;
#[test]
fn miri_rollover() {
set_event_converter(Box::new(SerializedHtmlEventConverter));
let mut dom = VirtualDom::new(App);
_ = dom.rebuild();
for _ in 0..3 {
dom.handle_event("click", Rc::new(MouseData::default()), ElementId(2), true);
dom.handle_event(
"click",
Rc::new(PlatformEventData::new(Box::<SerializedMouseData>::default())),
ElementId(2),
true,
);
dom.process_events();
_ = dom.render_immediate();
}
+1 -1
View File
@@ -11,7 +11,7 @@ fn it_works() {
let mut dom = VirtualDom::new(app);
_ = dom.rebuild();
dom.wait_for_suspense().await;
let out = dioxus_ssr::pre_render(&dom);
let out = dioxus_ssr::render(&dom);
assert_eq!(out, "<div>Waiting for... child</div>");
+25 -25
View File
@@ -1,13 +1,33 @@
//! Verify that tasks get polled by the virtualdom properly, and that we escape wait_for_work safely
use dioxus::prelude::*;
use std::{sync::atomic::AtomicUsize, time::Duration};
static POLL_COUNT: AtomicUsize = AtomicUsize::new(0);
#[cfg(not(miri))]
#[tokio::test]
async fn it_works() {
use dioxus::prelude::*;
use std::{sync::atomic::AtomicUsize, time::Duration};
static POLL_COUNT: AtomicUsize = AtomicUsize::new(0);
fn app(cx: Scope) -> Element {
cx.use_hook(|| {
cx.spawn(async {
for x in 0..10 {
tokio::time::sleep(Duration::from_micros(50)).await;
POLL_COUNT.fetch_add(x, std::sync::atomic::Ordering::Relaxed);
}
});
cx.spawn(async {
for x in 0..10 {
tokio::time::sleep(Duration::from_micros(25)).await;
POLL_COUNT.fetch_add(x * 2, std::sync::atomic::Ordering::Relaxed);
}
});
});
cx.render(rsx!(()))
}
let mut dom = VirtualDom::new(app);
let _ = dom.rebuild();
@@ -24,23 +44,3 @@ async fn it_works() {
135
);
}
fn app(cx: Scope) -> Element {
cx.use_hook(|| {
cx.spawn(async {
for x in 0..10 {
tokio::time::sleep(Duration::from_micros(50)).await;
POLL_COUNT.fetch_add(x, std::sync::atomic::Ordering::Relaxed);
}
});
cx.spawn(async {
for x in 0..10 {
tokio::time::sleep(Duration::from_micros(25)).await;
POLL_COUNT.fetch_add(x * 2, std::sync::atomic::Ordering::Relaxed);
}
});
});
cx.render(rsx!(()))
}
+1
View File
@@ -0,0 +1 @@
/src/minified.js
+27 -8
View File
@@ -11,15 +11,25 @@ keywords = ["dom", "ui", "gui", "react"]
[dependencies]
dioxus-core = { workspace = true, features = ["serialize"] }
dioxus-html = { workspace = true, features = ["serialize", "native-bind"] }
dioxus-interpreter-js = { workspace = true }
dioxus-html = { workspace = true, features = [
"serialize",
"native-bind",
"mounted",
"eval",
] }
dioxus-interpreter-js = { workspace = true, features = ["binary-protocol"] }
dioxus-hot-reload = { workspace = true, optional = true }
dioxus-cli-config = { workspace = true }
serde = "1.0.136"
serde_json = "1.0.79"
thiserror = { workspace = true }
wry = { version = "0.28.0", default-features = false, features = ["protocol", "file-drop"] }
tracing = { workspace = true }
wry = { version = "0.35.0", default-features = false, features = [
"os-webview",
"protocol",
"file-drop",
] }
futures-channel = { workspace = true }
tokio = { workspace = true, features = [
"sync",
@@ -33,14 +43,20 @@ webbrowser = "0.8.0"
infer = "0.11.0"
dunce = "1.0.2"
slab = { workspace = true }
rustc-hash = { workspace = true }
futures-util = { workspace = true }
urlencoding = "2.1.2"
async-trait = "0.1.68"
crossbeam-channel = "0.5.8"
tao = { version = "0.24.0", features = ["rwh_05"] }
[target.'cfg(any(target_os = "windows",target_os = "macos",target_os = "linux",target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))'.dependencies]
rfd = "0.11.3"
# This is only for debug mode, and it appears mobile does not support some packages this uses
manganis-cli-support = { workspace = true, optional = true, features = ["webp", "html"] }
rfd = "0.12"
global-hotkey = "0.4.1"
muda = "0.11.3"
[target.'cfg(target_os = "ios")'.dependencies]
objc = "0.2.7"
@@ -56,14 +72,13 @@ tokio_runtime = ["tokio"]
fullscreen = ["wry/fullscreen"]
transparent = ["wry/transparent"]
devtools = ["wry/devtools"]
tray = ["wry/tray"]
dox = ["wry/dox"]
hot-reload = ["dioxus-hot-reload"]
collect-assets = ["manganis-cli-support"]
gnu = []
[package.metadata.docs.rs]
default-features = false
features = [ "dox", "tokio_runtime", "hot-reload" ]
features = ["tokio_runtime", "hot-reload"]
[dev-dependencies]
dioxus-core-macro = { workspace = true }
@@ -72,6 +87,10 @@ dioxus = { workspace = true }
exitcode = "1.1.2"
scraper = "0.16.0"
[build-dependencies]
dioxus-interpreter-js = { workspace = true, features = ["binary-protocol"] }
minify-js = "0.5.6"
# These tests need to be run on the main thread, so they cannot use rust's test harness.
[[test]]
name = "check_events"
+86 -1
View File
@@ -1,4 +1,19 @@
fn main() {
use dioxus_interpreter_js::binary_protocol::SLEDGEHAMMER_JS;
use std::io::Write;
const EDITS_PATH: &str = {
#[cfg(any(target_os = "android", target_os = "windows"))]
{
"http://dioxus.index.html/edits"
}
#[cfg(not(any(target_os = "android", target_os = "windows")))]
{
"dioxus://index.html/edits"
}
};
fn check_gnu() {
// WARN about wry support on windows gnu targets. GNU windows targets don't work well in wry currently
if std::env::var("CARGO_CFG_WINDOWS").is_ok()
&& std::env::var("CARGO_CFG_TARGET_ENV").unwrap() == "gnu"
@@ -7,3 +22,73 @@ fn main() {
println!("cargo:warning=GNU windows targets have some limitations within Wry. Using the MSVC windows toolchain is recommended. If you would like to use continue using GNU, you can read https://github.com/wravery/webview2-rs#cross-compilation and disable this warning by adding the gnu feature to dioxus-desktop in your Cargo.toml")
}
}
fn main() {
check_gnu();
let prevent_file_upload = r#"// Prevent file inputs from opening the file dialog on click
let inputs = document.querySelectorAll("input");
for (let input of inputs) {
if (!input.getAttribute("data-dioxus-file-listener")) {
// prevent file inputs from opening the file dialog on click
const type = input.getAttribute("type");
if (type === "file") {
input.setAttribute("data-dioxus-file-listener", true);
input.addEventListener("click", (event) => {
let target = event.target;
let target_id = find_real_id(target);
if (target_id !== null) {
const send = (event_name) => {
const message = window.interpreter.serializeIpcMessage("file_diolog", { accept: target.getAttribute("accept"), directory: target.getAttribute("webkitdirectory") === "true", multiple: target.hasAttribute("multiple"), target: parseInt(target_id), bubbles: event_bubbles(event_name), event: event_name });
window.ipc.postMessage(message);
};
send("change&input");
}
event.preventDefault();
});
}
}
}"#;
let polling_request = format!(
r#"// Poll for requests
window.interpreter.wait_for_request = (headless) => {{
fetch(new Request("{EDITS_PATH}"))
.then(response => {{
response.arrayBuffer()
.then(bytes => {{
// In headless mode, the requestAnimationFrame callback is never called, so we need to run the bytes directly
if (headless) {{
run_from_bytes(bytes);
}}
else {{
requestAnimationFrame(() => {{
run_from_bytes(bytes);
}});
}}
window.interpreter.wait_for_request(headless);
}});
}})
}}"#
);
let mut interpreter = SLEDGEHAMMER_JS
.replace("/*POST_HANDLE_EDITS*/", prevent_file_upload)
.replace("export", "")
+ &polling_request;
while let Some(import_start) = interpreter.find("import") {
let import_end = interpreter[import_start..]
.find(|c| c == ';' || c == '\n')
.map(|i| i + import_start)
.unwrap_or_else(|| interpreter.len());
interpreter.replace_range(import_start..import_end, "");
}
let js = format!("{interpreter}\nconst config = new InterpreterConfig(false);");
use minify_js::*;
let session = Session::new();
let mut out = Vec::new();
minify(&session, TopLevelMode::Module, js.as_bytes(), &mut out).unwrap();
let minified = String::from_utf8(out).unwrap();
let mut file = std::fs::File::create("src/minified.js").unwrap();
file.write_all(minified.as_bytes()).unwrap();
}
+32
View File
@@ -0,0 +1,32 @@
use dioxus::prelude::*;
fn app(cx: Scope) -> Element {
let state = use_state(cx, || 0);
use_future(cx, (), |_| {
to_owned![state];
async move {
loop {
state += 1;
tokio::time::sleep(std::time::Duration::from_millis(1)).await;
}
}
});
cx.render(rsx! {
button {
onclick: move |_| {
state.set(0);
},
"reset"
}
for _ in 0..10000 {
div {
"hello desktop! {state}"
}
}
})
}
fn main() {
dioxus_desktop::launch(app);
}
+86 -53
View File
@@ -17,7 +17,7 @@ pub(crate) fn check_app_exits(app: Component) {
dioxus_desktop::launch_cfg(
app,
Config::new().with_window(WindowBuilder::new().with_visible(false)),
Config::new().with_window(WindowBuilder::new().with_visible(true)),
);
// Stop deadman's switch
@@ -52,7 +52,7 @@ fn mock_event(cx: &ScopeState, id: &'static str, value: &'static str) {
#[allow(deprecated)]
fn app(cx: Scope) -> Element {
let desktop_context: DesktopContext = cx.consume_context().unwrap();
let recieved_events = use_state(cx, || 0);
let received_events = use_state(cx, || 0);
// button
mock_event(
@@ -216,12 +216,12 @@ fn app(cx: Scope) -> Element {
r#"new FocusEvent("focusout",{bubbles: true})"#,
);
if **recieved_events == 12 {
if **received_events == 12 {
println!("all events recieved");
desktop_context.close();
}
cx.render(rsx! {
render! {
div {
button {
id: "button",
@@ -229,127 +229,160 @@ fn app(cx: Scope) -> Element {
println!("{:?}", event.data);
assert!(event.data.modifiers().is_empty());
assert!(event.data.held_buttons().is_empty());
assert_eq!(event.data.trigger_button(), Some(dioxus_html::input_data::MouseButton::Primary));
recieved_events.modify(|x| *x + 1)
},
assert_eq!(
event.data.trigger_button(),
Some(dioxus_html::input_data::MouseButton::Primary),
);
received_events.modify(|x| *x + 1)
}
}
div {
id: "mouse_move_div",
onmousemove: move |event| {
println!("{:?}", event.data);
assert!(event.data.modifiers().is_empty());
assert!(event.data.held_buttons().contains(dioxus_html::input_data::MouseButton::Secondary));
recieved_events.modify(|x| *x + 1)
},
assert!(
event
.data
.held_buttons()
.contains(dioxus_html::input_data::MouseButton::Secondary),
);
received_events.modify(|x| *x + 1)
}
}
div {
id: "mouse_click_div",
onclick: move |event| {
println!("{:?}", event.data);
assert!(event.data.modifiers().is_empty());
assert!(event.data.held_buttons().contains(dioxus_html::input_data::MouseButton::Secondary));
assert_eq!(event.data.trigger_button(), Some(dioxus_html::input_data::MouseButton::Secondary));
recieved_events.modify(|x| *x + 1)
},
}
div{
id: "mouse_dblclick_div",
ondblclick: move |event| {
println!("{:?}", event.data);
assert!(event.data.modifiers().is_empty());
assert!(event.data.held_buttons().contains(dioxus_html::input_data::MouseButton::Primary));
assert!(event.data.held_buttons().contains(dioxus_html::input_data::MouseButton::Secondary));
assert_eq!(event.data.trigger_button(), Some(dioxus_html::input_data::MouseButton::Secondary));
recieved_events.modify(|x| *x + 1)
assert!(
event
.data
.held_buttons()
.contains(dioxus_html::input_data::MouseButton::Secondary),
);
assert_eq!(
event.data.trigger_button(),
Some(dioxus_html::input_data::MouseButton::Secondary),
);
received_events.modify(|x| *x + 1)
}
}
div{
div {
id: "mouse_dblclick_div",
ondoubleclick: move |event| {
println!("{:?}", event.data);
assert!(event.data.modifiers().is_empty());
assert!(
event.data.held_buttons().contains(dioxus_html::input_data::MouseButton::Primary),
);
assert!(
event
.data
.held_buttons()
.contains(dioxus_html::input_data::MouseButton::Secondary),
);
assert_eq!(
event.data.trigger_button(),
Some(dioxus_html::input_data::MouseButton::Secondary),
);
received_events.modify(|x| *x + 1)
}
}
div {
id: "mouse_down_div",
onmousedown: move |event| {
println!("{:?}", event.data);
assert!(event.data.modifiers().is_empty());
assert!(event.data.held_buttons().contains(dioxus_html::input_data::MouseButton::Secondary));
assert_eq!(event.data.trigger_button(), Some(dioxus_html::input_data::MouseButton::Secondary));
recieved_events.modify(|x| *x + 1)
assert!(
event
.data
.held_buttons()
.contains(dioxus_html::input_data::MouseButton::Secondary),
);
assert_eq!(
event.data.trigger_button(),
Some(dioxus_html::input_data::MouseButton::Secondary),
);
received_events.modify(|x| *x + 1)
}
}
div{
div {
id: "mouse_up_div",
onmouseup: move |event| {
println!("{:?}", event.data);
assert!(event.data.modifiers().is_empty());
assert!(event.data.held_buttons().is_empty());
assert_eq!(event.data.trigger_button(), Some(dioxus_html::input_data::MouseButton::Primary));
recieved_events.modify(|x| *x + 1)
assert_eq!(
event.data.trigger_button(),
Some(dioxus_html::input_data::MouseButton::Primary),
);
received_events.modify(|x| *x + 1)
}
}
div{
div {
id: "wheel_div",
width: "100px",
height: "100px",
background_color: "red",
onwheel: move |event| {
println!("{:?}", event.data);
let dioxus_html::geometry::WheelDelta::Pixels(delta)= event.data.delta()else{
panic!("Expected delta to be in pixels")
};
let dioxus_html::geometry::WheelDelta::Pixels(delta) = event.data.delta() else {
panic!("Expected delta to be in pixels") };
assert_eq!(delta, Vector3D::new(1.0, 2.0, 3.0));
recieved_events.modify(|x| *x + 1)
received_events.modify(|x| *x + 1)
}
}
input{
input {
id: "key_down_div",
onkeydown: move |event| {
println!("{:?}", event.data);
assert!(event.data.modifiers().is_empty());
assert_eq!(event.data.key().to_string(), "a");
assert_eq!(event.data.code().to_string(), "KeyA");
assert_eq!(event.data.location, 0);
assert_eq!(event.data.location(), Location::Standard);
assert!(event.data.is_auto_repeating());
recieved_events.modify(|x| *x + 1)
received_events.modify(|x| *x + 1)
}
}
input{
input {
id: "key_up_div",
onkeyup: move |event| {
println!("{:?}", event.data);
assert!(event.data.modifiers().is_empty());
assert_eq!(event.data.key().to_string(), "a");
assert_eq!(event.data.code().to_string(), "KeyA");
assert_eq!(event.data.location, 0);
assert_eq!(event.data.location(), Location::Standard);
assert!(!event.data.is_auto_repeating());
recieved_events.modify(|x| *x + 1)
received_events.modify(|x| *x + 1)
}
}
input{
input {
id: "key_press_div",
onkeypress: move |event| {
println!("{:?}", event.data);
assert!(event.data.modifiers().is_empty());
assert_eq!(event.data.key().to_string(), "a");
assert_eq!(event.data.code().to_string(), "KeyA");
assert_eq!(event.data.location, 0);
assert_eq!(event.data.location(), Location::Standard);
assert!(!event.data.is_auto_repeating());
recieved_events.modify(|x| *x + 1)
received_events.modify(|x| *x + 1)
}
}
input{
input {
id: "focus_in_div",
onfocusin: move |event| {
println!("{:?}", event.data);
recieved_events.modify(|x| *x + 1)
received_events.modify(|x| *x + 1)
}
}
input{
input {
id: "focus_out_div",
onfocusout: move |event| {
println!("{:?}", event.data);
recieved_events.modify(|x| *x + 1)
received_events.modify(|x| *x + 1)
}
}
}
})
}
}
+2 -2
View File
@@ -2,8 +2,8 @@ use dioxus::prelude::*;
use dioxus_desktop::DesktopContext;
pub(crate) fn check_app_exits(app: Component) {
use dioxus_desktop::tao::window::WindowBuilder;
use dioxus_desktop::Config;
use tao::window::WindowBuilder;
// This is a deadman's switch to ensure that the app exits
let should_panic = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true));
let should_panic_clone = should_panic.clone();
@@ -16,7 +16,7 @@ pub(crate) fn check_app_exits(app: Component) {
dioxus_desktop::launch_cfg(
app,
Config::new().with_window(WindowBuilder::new().with_visible(false)),
Config::new().with_window(WindowBuilder::new().with_visible(true)),
);
should_panic.store(false, std::sync::atomic::Ordering::SeqCst);
+360
View File
@@ -0,0 +1,360 @@
use crate::{
config::{Config, WindowCloseBehaviour},
desktop_context::WindowEventHandlers,
element::DesktopElement,
file_upload::FileDialogRequest,
ipc::IpcMessage,
ipc::{EventData, UserWindowEvent},
query::QueryResult,
shortcut::{GlobalHotKeyEvent, ShortcutRegistry},
webview::WebviewInstance,
};
use crossbeam_channel::Receiver;
use dioxus_core::{Component, ElementId, VirtualDom};
use dioxus_html::{
native_bind::NativeFileEngine, FileEngine, HasFileData, HasFormData, HtmlEvent,
PlatformEventData,
};
use std::{
cell::{Cell, RefCell},
collections::HashMap,
rc::Rc,
sync::Arc,
};
use tao::{
event::Event,
event_loop::{ControlFlow, EventLoop, EventLoopBuilder, EventLoopProxy, EventLoopWindowTarget},
window::WindowId,
};
/// The single top-level object that manages all the running windows, assets, shortcuts, etc
pub(crate) struct App<P> {
// move the props into a cell so we can pop it out later to create the first window
// iOS panics if we create a window before the event loop is started, so we toss them into a cell
pub(crate) props: Cell<Option<P>>,
pub(crate) cfg: Cell<Option<Config>>,
// Stuff we need mutable access to
pub(crate) root: Component<P>,
pub(crate) control_flow: ControlFlow,
pub(crate) is_visible_before_start: bool,
pub(crate) window_behavior: WindowCloseBehaviour,
pub(crate) webviews: HashMap<WindowId, WebviewInstance>,
/// This single blob of state is shared between all the windows so they have access to the runtime state
///
/// This includes stuff like the event handlers, shortcuts, etc as well as ways to modify *other* windows
pub(crate) shared: Rc<SharedContext>,
}
/// A bundle of state shared between all the windows, providing a way for us to communicate with running webview.
///
/// Todo: everything in this struct is wrapped in Rc<>, but we really only need the one top-level refcell
pub struct SharedContext {
pub(crate) event_handlers: WindowEventHandlers,
pub(crate) pending_webviews: RefCell<Vec<WebviewInstance>>,
pub(crate) shortcut_manager: ShortcutRegistry,
pub(crate) global_hotkey_channel: Receiver<GlobalHotKeyEvent>,
pub(crate) proxy: EventLoopProxy<UserWindowEvent>,
pub(crate) target: EventLoopWindowTarget<UserWindowEvent>,
}
impl<P: 'static> App<P> {
pub fn new(cfg: Config, props: P, root: Component<P>) -> (EventLoop<UserWindowEvent>, Self) {
let event_loop = EventLoopBuilder::<UserWindowEvent>::with_user_event().build();
let app = Self {
root,
window_behavior: cfg.last_window_close_behaviour,
is_visible_before_start: true,
webviews: HashMap::new(),
control_flow: ControlFlow::Wait,
props: Cell::new(Some(props)),
cfg: Cell::new(Some(cfg)),
shared: Rc::new(SharedContext {
event_handlers: WindowEventHandlers::default(),
pending_webviews: Default::default(),
shortcut_manager: ShortcutRegistry::new(),
global_hotkey_channel: GlobalHotKeyEvent::receiver().clone(),
proxy: event_loop.create_proxy(),
target: event_loop.clone(),
}),
};
// Copy over any assets we find
// todo - re-enable this when we have a faster way of copying assets
#[cfg(feature = "collect-assets")]
crate::collect_assets::copy_assets();
// Set the event converter
dioxus_html::set_event_converter(Box::new(crate::events::SerializedHtmlEventConverter));
// Allow hotreloading to work - but only in debug mode
#[cfg(all(feature = "hot-reload", debug_assertions))]
app.connect_hotreload();
(event_loop, app)
}
pub fn tick(&mut self, window_event: &Event<'_, UserWindowEvent>) {
self.control_flow = ControlFlow::Wait;
self.shared
.event_handlers
.apply_event(window_event, &self.shared.target);
if let Ok(event) = self.shared.global_hotkey_channel.try_recv() {
self.shared.shortcut_manager.call_handlers(event);
}
}
#[cfg(all(feature = "hot-reload", debug_assertions))]
pub fn connect_hotreload(&self) {
dioxus_hot_reload::connect({
let proxy = self.shared.proxy.clone();
move |template| {
let _ = proxy.send_event(UserWindowEvent(
EventData::HotReloadEvent(template),
unsafe { WindowId::dummy() },
));
}
});
}
pub fn handle_new_window(&mut self) {
for handler in self.shared.pending_webviews.borrow_mut().drain(..) {
let id = handler.desktop_context.window.id();
self.webviews.insert(id, handler);
_ = self
.shared
.proxy
.send_event(UserWindowEvent(EventData::Poll, id));
}
}
pub fn handle_close_requested(&mut self, id: WindowId) {
use WindowCloseBehaviour::*;
match self.window_behavior {
LastWindowExitsApp => {
self.webviews.remove(&id);
if self.webviews.is_empty() {
self.control_flow = ControlFlow::Exit
}
}
LastWindowHides => {
let Some(webview) = self.webviews.get(&id) else {
return;
};
hide_app_window(&webview.desktop_context.webview);
}
CloseWindow => {
self.webviews.remove(&id);
}
}
}
pub fn window_destroyed(&mut self, id: WindowId) {
self.webviews.remove(&id);
if matches!(
self.window_behavior,
WindowCloseBehaviour::LastWindowExitsApp
) && self.webviews.is_empty()
{
self.control_flow = ControlFlow::Exit
}
}
pub fn handle_start_cause_init(&mut self) {
let props = self.props.take().unwrap();
let cfg = self.cfg.take().unwrap();
self.is_visible_before_start = cfg.window.window.visible;
let webview = WebviewInstance::new(
cfg,
VirtualDom::new_with_props(self.root, props),
self.shared.clone(),
);
let id = webview.desktop_context.window.id();
self.webviews.insert(id, webview);
_ = self
.shared
.proxy
.send_event(UserWindowEvent(EventData::Poll, id));
}
pub fn handle_browser_open(&mut self, msg: IpcMessage) {
if let Some(temp) = msg.params().as_object() {
if temp.contains_key("href") {
let open = webbrowser::open(temp["href"].as_str().unwrap());
if let Err(e) = open {
tracing::error!("Open Browser error: {:?}", e);
}
}
}
}
pub fn handle_initialize_msg(&mut self, id: WindowId) {
let view = self.webviews.get_mut(&id).unwrap();
view.desktop_context.send_edits(view.dom.rebuild());
view.desktop_context
.window
.set_visible(self.is_visible_before_start);
}
pub fn handle_close_msg(&mut self, id: WindowId) {
self.webviews.remove(&id);
if self.webviews.is_empty() {
self.control_flow = ControlFlow::Exit
}
}
pub fn handle_query_msg(&mut self, msg: IpcMessage, id: WindowId) {
let Ok(result) = serde_json::from_value::<QueryResult>(msg.params()) else {
return;
};
let Some(view) = self.webviews.get(&id) else {
return;
};
view.desktop_context.query.send(result);
}
pub fn handle_user_event_msg(&mut self, msg: IpcMessage, id: WindowId) {
let parsed_params = serde_json::from_value(msg.params())
.map_err(|err| tracing::error!("Error parsing user_event: {:?}", err));
let Ok(evt) = parsed_params else { return };
let HtmlEvent {
element,
name,
bubbles,
data,
} = evt;
let view = self.webviews.get_mut(&id).unwrap();
let query = view.desktop_context.query.clone();
// check for a mounted event placeholder and replace it with a desktop specific element
let as_any = match data {
dioxus_html::EventData::Mounted => {
let element = DesktopElement::new(element, view.desktop_context.clone(), query);
Rc::new(PlatformEventData::new(Box::new(element)))
}
_ => data.into_any(),
};
view.dom.handle_event(&name, as_any, element, bubbles);
view.desktop_context.send_edits(view.dom.render_immediate());
}
#[cfg(all(feature = "hot-reload", debug_assertions))]
pub fn handle_hot_reload_msg(&mut self, msg: dioxus_hot_reload::HotReloadMsg) {
match msg {
dioxus_hot_reload::HotReloadMsg::UpdateTemplate(template) => {
for webview in self.webviews.values_mut() {
webview.dom.replace_template(template);
webview.poll_vdom();
}
}
dioxus_hot_reload::HotReloadMsg::Shutdown => {
self.control_flow = ControlFlow::Exit;
}
}
}
pub fn handle_file_dialog_msg(&mut self, msg: IpcMessage, window: WindowId) {
let Ok(file_dialog) = serde_json::from_value::<FileDialogRequest>(msg.params()) else {
return;
};
struct DesktopFileUploadForm {
files: Arc<NativeFileEngine>,
}
impl HasFileData for DesktopFileUploadForm {
fn files(&self) -> Option<Arc<dyn FileEngine>> {
Some(self.files.clone())
}
}
impl HasFormData for DesktopFileUploadForm {
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
let id = ElementId(file_dialog.target);
let event_name = &file_dialog.event;
let event_bubbles = file_dialog.bubbles;
let files = file_dialog.get_file_event();
let data = Rc::new(PlatformEventData::new(Box::new(DesktopFileUploadForm {
files: Arc::new(NativeFileEngine::new(files)),
})));
let view = self.webviews.get_mut(&window).unwrap();
if event_name == "change&input" {
view.dom
.handle_event("input", data.clone(), id, event_bubbles);
view.dom.handle_event("change", data, id, event_bubbles);
} else {
view.dom.handle_event(event_name, data, id, event_bubbles);
}
view.desktop_context.send_edits(view.dom.render_immediate());
}
/// Poll the virtualdom until it's pending
///
/// The waker we give it is connected to the event loop, so it will wake up the event loop when it's ready to be polled again
///
/// All IO is done on the tokio runtime we started earlier
pub fn poll_vdom(&mut self, id: WindowId) {
let Some(view) = self.webviews.get_mut(&id) else {
return;
};
view.poll_vdom();
}
}
/// Different hide implementations per platform
#[allow(unused)]
pub fn hide_app_window(window: &wry::WebView) {
#[cfg(target_os = "windows")]
{
use tao::platform::windows::WindowExtWindows;
window.set_visible(false);
// window.set_skip_taskbar(true);
}
#[cfg(target_os = "linux")]
{
use tao::platform::unix::WindowExtUnix;
window.set_visible(false);
}
#[cfg(target_os = "macos")]
{
// window.set_visible(false); has the wrong behaviour on macOS
// It will hide the window but not show it again when the user switches
// back to the app. `NSApplication::hide:` has the correct behaviour
use objc::runtime::Object;
use objc::{msg_send, sel, sel_impl};
objc::rc::autoreleasepool(|| unsafe {
let app: *mut Object = msg_send![objc::class!(NSApplication), sharedApplication];
let nil = std::ptr::null_mut::<Object>();
let _: () = msg_send![app, hide: nil];
});
}
}
+61
View File
@@ -0,0 +1,61 @@
use dioxus_core::prelude::{Runtime, RuntimeGuard, ScopeId};
use rustc_hash::FxHashMap;
use std::{cell::RefCell, rc::Rc};
use wry::{http::Request, RequestAsyncResponder};
///
pub type AssetRequest = Request<Vec<u8>>;
pub struct AssetHandler {
f: Box<dyn Fn(AssetRequest, RequestAsyncResponder) + 'static>,
scope: ScopeId,
}
#[derive(Clone)]
pub struct AssetHandlerRegistry {
dom_rt: Rc<Runtime>,
handlers: Rc<RefCell<FxHashMap<String, AssetHandler>>>,
}
impl AssetHandlerRegistry {
pub fn new(dom_rt: Rc<Runtime>) -> Self {
AssetHandlerRegistry {
dom_rt,
handlers: Default::default(),
}
}
pub fn has_handler(&self, name: &str) -> bool {
self.handlers.borrow().contains_key(name)
}
pub fn handle_request(
&self,
name: &str,
request: AssetRequest,
responder: RequestAsyncResponder,
) {
if let Some(handler) = self.handlers.borrow().get(name) {
// make sure the runtime is alive for the duration of the handler
// We should do this for all the things - not just asset handlers
RuntimeGuard::with(self.dom_rt.clone(), Some(handler.scope), || {
(handler.f)(request, responder)
});
}
}
pub fn register_handler(
&self,
name: String,
f: Box<dyn Fn(AssetRequest, RequestAsyncResponder) + 'static>,
scope: ScopeId,
) {
self.handlers
.borrow_mut()
.insert(name, AssetHandler { f, scope });
}
pub fn remove_handler(&self, name: &str) -> Option<AssetHandler> {
self.handlers.borrow_mut().remove(name)
}
}
+60
View File
@@ -0,0 +1,60 @@
pub fn copy_assets() {
#[cfg(all(
debug_assertions,
any(
target_os = "windows",
target_os = "macos",
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
)
))]
{
// The CLI will copy assets to the current working directory
if std::env::var_os("DIOXUS_ACTIVE").is_some() {
return;
}
use manganis_cli_support::AssetManifest;
use manganis_cli_support::AssetManifestExt;
use manganis_cli_support::Config;
use std::path::PathBuf;
let config = Config::current();
let asset_location = config.assets_serve_location();
let asset_location = PathBuf::from(asset_location);
let _ = std::fs::remove_dir_all(&asset_location);
println!("Finding assets... (Note: if you run a dioxus desktop application with the CLI. This process will be significantly faster.)");
let manifest = AssetManifest::load();
let has_assets = manifest
.packages()
.iter()
.any(|package| !package.assets().is_empty());
if has_assets {
println!("Copying and optimizing assets...");
manifest.copy_static_assets_to(&asset_location).unwrap();
println!("Copied assets to {}", asset_location.display());
} else {
println!("No assets found");
}
}
#[cfg(not(all(
debug_assertions,
any(
target_os = "windows",
target_os = "macos",
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
)
)))]
{
println!(
"Skipping assets in release mode. You compile assets with the dioxus-cli in release mode"
);
}
}
@@ -1,16 +1,13 @@
use std::borrow::Cow;
use std::path::PathBuf;
use wry::application::window::Icon;
use dioxus_core::prelude::Component;
use tao::window::{Icon, WindowBuilder, WindowId};
use wry::{
application::window::{Window, WindowBuilder},
http::{Request as HttpRequest, Response as HttpResponse},
webview::FileDropEvent,
Result as WryResult,
FileDropEvent,
};
// pub(crate) type DynEventHandlerFn = dyn Fn(&mut EventLoop<()>, &mut WebView);
/// The behaviour of the application when the last window is closed.
#[derive(Copy, Clone, Eq, PartialEq)]
pub enum WindowCloseBehaviour {
@@ -36,20 +33,26 @@ pub struct Config {
pub(crate) root_name: String,
pub(crate) background_color: Option<(u8, u8, u8, u8)>,
pub(crate) last_window_close_behaviour: WindowCloseBehaviour,
pub(crate) enable_default_menu_bar: bool,
}
type DropHandler = Box<dyn Fn(&Window, FileDropEvent) -> bool>;
type DropHandler = Box<dyn Fn(WindowId, FileDropEvent) -> bool>;
pub(crate) type WryProtocol = (
String,
Box<dyn Fn(&HttpRequest<Vec<u8>>) -> WryResult<HttpResponse<Cow<'static, [u8]>>> + 'static>,
Box<dyn Fn(HttpRequest<Vec<u8>>) -> HttpResponse<Cow<'static, [u8]>> + 'static>,
);
impl Config {
/// Initializes a new `WindowBuilder` with default values.
#[inline]
pub fn new() -> Self {
let window = WindowBuilder::new().with_title("Dioxus app");
let window = WindowBuilder::new().with_title(
dioxus_cli_config::CURRENT_CONFIG
.as_ref()
.map(|c| c.dioxus_config.application.name.clone())
.unwrap_or("Dioxus App".to_string()),
);
Self {
// event_handler: None,
@@ -65,9 +68,32 @@ impl Config {
root_name: "main".to_string(),
background_color: None,
last_window_close_behaviour: WindowCloseBehaviour::LastWindowExitsApp,
enable_default_menu_bar: true,
}
}
/// Launch a Dioxus app using the given component and config
///
/// See the [`crate::launch::launch`] function for more details.
pub fn launch(self, root: Component<()>) {
crate::launch::launch_cfg(root, self)
}
/// Launch a Dioxus app using the given component, config, and props
///
/// See the [`crate::launch::launch_with_props`] function for more details.
pub fn launch_with_props<P: 'static>(self, root: Component<P>, props: P) {
crate::launch::launch_with_props(root, props, self)
}
/// Set whether the default menu bar should be enabled.
///
/// > Note: `enable` is `true` by default. To disable the default menu bar pass `false`.
pub fn with_default_menu_bar(mut self, enable: bool) -> Self {
self.enable_default_menu_bar = enable;
self
}
/// set the directory from which assets will be searched in release mode
pub fn with_resource_directory(mut self, path: impl Into<PathBuf>) -> Self {
self.resource_dir = Some(path.into());
@@ -108,10 +134,10 @@ impl Config {
self
}
/// Set a file drop handler
/// Set a file drop handler. If this is enabled, html drag events will be disabled.
pub fn with_file_drop_handler(
mut self,
handler: impl Fn(&Window, FileDropEvent) -> bool + 'static,
handler: impl Fn(WindowId, FileDropEvent) -> bool + 'static,
) -> Self {
self.file_drop_handler = Some(Box::new(handler));
self
@@ -120,7 +146,7 @@ impl Config {
/// Set a custom protocol
pub fn with_custom_protocol<F>(mut self, name: String, handler: F) -> Self
where
F: Fn(&HttpRequest<Vec<u8>>) -> WryResult<HttpResponse<Cow<'static, [u8]>>> + 'static,
F: Fn(HttpRequest<Vec<u8>>) -> HttpResponse<Cow<'static, [u8]>> + 'static,
{
self.protocols.push((name, Box::new(handler)));
self
+132 -151
View File
@@ -1,41 +1,42 @@
use std::cell::RefCell;
use std::rc::Rc;
use std::rc::Weak;
use crate::create_new_window;
use crate::events::IpcMessage;
use crate::query::QueryEngine;
use crate::shortcut::ShortcutId;
use crate::shortcut::ShortcutRegistry;
use crate::shortcut::ShortcutRegistryError;
use crate::Config;
use crate::WebviewHandler;
use dioxus_core::ScopeState;
use dioxus_core::VirtualDom;
#[cfg(all(feature = "hot-reload", debug_assertions))]
use dioxus_hot_reload::HotReloadMsg;
use crate::{
app::SharedContext,
assets::AssetHandlerRegistry,
edits::EditQueue,
ipc::{EventData, UserWindowEvent},
query::QueryEngine,
shortcut::{HotKey, ShortcutId, ShortcutRegistryError},
webview::WebviewInstance,
AssetRequest, Config,
};
use dioxus_core::{
prelude::{current_scope_id, ScopeId},
Mutations, VirtualDom,
};
use dioxus_interpreter_js::binary_protocol::Channel;
use rustc_hash::FxHashMap;
use slab::Slab;
use wry::application::accelerator::Accelerator;
use wry::application::event::Event;
use wry::application::event_loop::EventLoopProxy;
use wry::application::event_loop::EventLoopWindowTarget;
use std::{cell::RefCell, fmt::Debug, rc::Rc, rc::Weak, sync::atomic::AtomicU16};
use tao::{
event::Event,
event_loop::EventLoopWindowTarget,
window::{Fullscreen as WryFullscreen, Window, WindowId},
};
use wry::{RequestAsyncResponder, WebView};
#[cfg(target_os = "ios")]
use wry::application::platform::ios::WindowExtIOS;
use wry::application::window::Fullscreen as WryFullscreen;
use wry::application::window::Window;
use wry::application::window::WindowId;
use wry::webview::WebView;
use tao::platform::ios::WindowExtIOS;
pub type ProxyType = EventLoopProxy<UserWindowEvent>;
/// Get an imperative handle to the current window
pub fn use_window(cx: &ScopeState) -> &DesktopContext {
cx.use_hook(|| cx.consume_context::<DesktopContext>())
.as_ref()
.unwrap()
/// Get an imperative handle to the current window without using a hook
///
/// ## Panics
///
/// This function will panic if it is called outside of the context of a Dioxus App.
pub fn window() -> DesktopContext {
dioxus_core::prelude::consume_context().unwrap()
}
pub(crate) type WebviewQueue = Rc<RefCell<Vec<WebviewHandler>>>;
/// A handle to the [`DesktopService`] that can be passed around.
pub type DesktopContext = Rc<DesktopService>;
/// An imperative interface to the current window.
///
@@ -51,60 +52,69 @@ pub(crate) type WebviewQueue = Rc<RefCell<Vec<WebviewHandler>>>;
/// ```
pub struct DesktopService {
/// The wry/tao proxy to the current window
pub webview: Rc<WebView>,
pub webview: WebView,
/// The proxy to the event loop
pub proxy: ProxyType,
/// The tao window itself
pub window: Window,
pub(crate) shared: Rc<SharedContext>,
/// The receiver for queries about the current window
pub(super) query: QueryEngine,
pub(super) pending_windows: WebviewQueue,
pub(crate) event_loop: EventLoopWindowTarget<UserWindowEvent>,
pub(crate) event_handlers: WindowEventHandlers,
pub(crate) shortcut_manager: ShortcutRegistry,
pub(crate) edit_queue: EditQueue,
pub(crate) templates: RefCell<FxHashMap<String, u16>>,
pub(crate) max_template_count: AtomicU16,
pub(crate) channel: RefCell<Channel>,
pub(crate) asset_handlers: AssetHandlerRegistry,
#[cfg(target_os = "ios")]
pub(crate) views: Rc<RefCell<Vec<*mut objc::runtime::Object>>>,
}
/// A handle to the [`DesktopService`] that can be passed around.
pub type DesktopContext = Rc<DesktopService>;
/// A smart pointer to the current window.
impl std::ops::Deref for DesktopService {
type Target = Window;
fn deref(&self) -> &Self::Target {
self.webview.window()
&self.window
}
}
impl DesktopService {
pub(crate) fn new(
webview: WebView,
proxy: ProxyType,
event_loop: EventLoopWindowTarget<UserWindowEvent>,
webviews: WebviewQueue,
event_handlers: WindowEventHandlers,
shortcut_manager: ShortcutRegistry,
window: Window,
shared: Rc<SharedContext>,
edit_queue: EditQueue,
asset_handlers: AssetHandlerRegistry,
) -> Self {
Self {
webview: Rc::new(webview),
proxy,
event_loop,
window,
webview,
shared,
edit_queue,
asset_handlers,
query: Default::default(),
pending_windows: webviews,
event_handlers,
shortcut_manager,
templates: Default::default(),
max_template_count: Default::default(),
channel: Default::default(),
#[cfg(target_os = "ios")]
views: Default::default(),
}
}
/// Send a list of mutations to the webview
pub(crate) fn send_edits(&self, edits: Mutations) {
if let Some(bytes) = crate::edits::apply_edits(
edits,
&mut self.channel.borrow_mut(),
&mut self.templates.borrow_mut(),
&self.max_template_count,
) {
self.edit_queue.add_edits(bytes)
}
}
/// Create a new window using the props and window builder
///
/// Returns the webview handle for the new window.
@@ -113,35 +123,23 @@ impl DesktopService {
///
/// Be careful to not create a cycle of windows, or you might leak memory.
pub fn new_window(&self, dom: VirtualDom, cfg: Config) -> Weak<DesktopService> {
let window = create_new_window(
cfg,
&self.event_loop,
&self.proxy,
dom,
&self.pending_windows,
&self.event_handlers,
self.shortcut_manager.clone(),
);
let window = WebviewInstance::new(cfg, dom, self.shared.clone());
let desktop_context = window
.dom
.base_scope()
.consume_context::<Rc<DesktopService>>()
let cx = window.desktop_context.clone();
self.shared
.proxy
.send_event(UserWindowEvent(EventData::NewWindow, cx.id()))
.unwrap();
let id = window.desktop_context.webview.window().id();
self.proxy
.send_event(UserWindowEvent(EventData::NewWindow, id))
self.shared
.proxy
.send_event(UserWindowEvent(EventData::Poll, cx.id()))
.unwrap();
self.proxy
.send_event(UserWindowEvent(EventData::Poll, id))
.unwrap();
self.shared.pending_webviews.borrow_mut().push(window);
self.pending_windows.borrow_mut().push(window);
Rc::downgrade(&desktop_context)
Rc::downgrade(&cx)
}
/// trigger the drag-window event
@@ -153,41 +151,38 @@ impl DesktopService {
/// onmousedown: move |_| { desktop.drag_window(); }
/// ```
pub fn drag(&self) {
let window = self.webview.window();
// if the drag_window has any errors, we don't do anything
if window.fullscreen().is_none() {
window.drag_window().unwrap();
if self.window.fullscreen().is_none() {
_ = self.window.drag_window();
}
}
/// Toggle whether the window is maximized or not
pub fn toggle_maximized(&self) {
let window = self.webview.window();
window.set_maximized(!window.is_maximized())
self.window.set_maximized(!self.window.is_maximized())
}
/// close window
/// Close this window
pub fn close(&self) {
let _ = self
.shared
.proxy
.send_event(UserWindowEvent(EventData::CloseWindow, self.id()));
}
/// close window
/// Close a particular window, given its ID
pub fn close_window(&self, id: WindowId) {
let _ = self
.shared
.proxy
.send_event(UserWindowEvent(EventData::CloseWindow, id));
}
/// change window to fullscreen
pub fn set_fullscreen(&self, fullscreen: bool) {
if let Some(handle) = self.webview.window().current_monitor() {
self.webview
.window()
.set_fullscreen(fullscreen.then_some(WryFullscreen::Borderless(Some(handle))));
if let Some(handle) = &self.window.current_monitor() {
self.window.set_fullscreen(
fullscreen.then_some(WryFullscreen::Borderless(Some(handle.clone()))),
);
}
}
@@ -220,12 +215,12 @@ impl DesktopService {
&self,
handler: impl FnMut(&Event<UserWindowEvent>, &EventLoopWindowTarget<UserWindowEvent>) + 'static,
) -> WryEventHandlerId {
self.event_handlers.add(self.id(), handler)
self.shared.event_handlers.add(self.window.id(), handler)
}
/// Remove a wry event handler created with [`DesktopContext::create_wry_event_handler`]
pub fn remove_wry_event_handler(&self, id: WryEventHandlerId) {
self.event_handlers.remove(id)
self.shared.event_handlers.remove(id)
}
/// Create a global shortcut
@@ -233,27 +228,55 @@ impl DesktopService {
/// Linux: Only works on x11. See [this issue](https://github.com/tauri-apps/tao/issues/331) for more information.
pub fn create_shortcut(
&self,
accelerator: Accelerator,
hotkey: HotKey,
callback: impl FnMut() + 'static,
) -> Result<ShortcutId, ShortcutRegistryError> {
self.shortcut_manager
.add_shortcut(accelerator, Box::new(callback))
self.shared
.shortcut_manager
.add_shortcut(hotkey, Box::new(callback))
}
/// Remove a global shortcut
pub fn remove_shortcut(&self, id: ShortcutId) {
self.shortcut_manager.remove_shortcut(id)
self.shared.shortcut_manager.remove_shortcut(id)
}
/// Remove all global shortcuts
pub fn remove_all_shortcuts(&self) {
self.shortcut_manager.remove_all()
self.shared.shortcut_manager.remove_all()
}
/// Provide a callback to handle asset loading yourself.
/// If the ScopeId isn't provided, defaults to a global handler.
/// Note that the handler is namespaced by name, not ScopeId.
///
/// When the component is dropped, the handler is removed.
///
/// See [`use_asset_handle`](crate::use_asset_handle) for a convenient hook.
pub fn register_asset_handler(
&self,
name: String,
f: Box<dyn Fn(AssetRequest, RequestAsyncResponder) + 'static>,
scope: Option<ScopeId>,
) {
self.asset_handlers.register_handler(
name,
f,
scope.unwrap_or(current_scope_id().unwrap_or(ScopeId(0))),
)
}
/// Removes an asset handler by its identifier.
///
/// Returns `None` if the handler did not exist.
pub fn remove_asset_handler(&self, name: &str) -> Option<()> {
self.asset_handlers.remove_handler(name).map(|_| ())
}
/// Push an objc view to the window
#[cfg(target_os = "ios")]
pub fn push_view(&self, view: objc_id::ShareId<objc::runtime::Object>) {
let window = self.webview.window();
let window = &self.window;
unsafe {
use objc::runtime::Object;
@@ -273,7 +296,7 @@ impl DesktopService {
/// Pop an objc view from the window
#[cfg(target_os = "ios")]
pub fn pop_view(&self) {
let window = self.webview.window();
let window = &self.window;
unsafe {
use objc::runtime::Object;
@@ -287,23 +310,6 @@ impl DesktopService {
}
}
#[derive(Debug, Clone)]
pub struct UserWindowEvent(pub EventData, pub WindowId);
#[derive(Debug, Clone)]
pub enum EventData {
Poll,
Ipc(IpcMessage),
#[cfg(all(feature = "hot-reload", debug_assertions))]
HotReloadEvent(HotReloadMsg),
NewWindow,
CloseWindow,
}
#[cfg(target_os = "ios")]
fn is_main_thread() -> bool {
use objc::runtime::{Class, BOOL, NO};
@@ -369,45 +375,20 @@ impl WryWindowEventHandlerInner {
target: &EventLoopWindowTarget<UserWindowEvent>,
) {
// if this event does not apply to the window this listener cares about, return
match event {
Event::WindowEvent { window_id, .. }
| Event::MenuEvent {
window_id: Some(window_id),
..
} => {
if *window_id != self.window_id {
return;
}
if let Event::WindowEvent { window_id, .. } = event {
if *window_id != self.window_id {
return;
}
_ => (),
}
(self.handler)(event, target)
}
}
/// Get a closure that executes any JavaScript in the WebView context.
pub fn use_wry_event_handler(
cx: &ScopeState,
handler: impl FnMut(&Event<UserWindowEvent>, &EventLoopWindowTarget<UserWindowEvent>) + 'static,
) -> &WryEventHandler {
let desktop = use_window(cx);
cx.use_hook(move || {
let desktop = desktop.clone();
let id = desktop.create_wry_event_handler(handler);
WryEventHandler {
handlers: desktop.event_handlers.clone(),
id,
}
})
}
/// A wry event handler that is scoped to the current component and window. The event handler will only receive events for the window it was created for and global events.
///
/// This will automatically be removed when the component is unmounted.
pub struct WryEventHandler {
handlers: WindowEventHandlers,
pub(crate) handlers: WindowEventHandlers,
/// The unique identifier of the event handler.
pub id: WryEventHandlerId,
}
+172
View File
@@ -0,0 +1,172 @@
use dioxus_core::{BorrowedAttributeValue, Mutations, Template, TemplateAttribute, TemplateNode};
use dioxus_html::event_bubbles;
use dioxus_interpreter_js::binary_protocol::Channel;
use rustc_hash::FxHashMap;
use std::{
sync::atomic::AtomicU16,
sync::Arc,
sync::{atomic::Ordering, Mutex},
};
use wry::RequestAsyncResponder;
/// This handles communication between the requests that the webview makes and the interpreter. The interpreter
/// constantly makes long running requests to the webview to get any edits that should be made to the DOM almost like
/// server side events.
///
/// It will hold onto the requests until the interpreter is ready to handle them and hold onto any pending edits until
/// a new request is made.
#[derive(Default, Clone)]
pub(crate) struct EditQueue {
queue: Arc<Mutex<Vec<Vec<u8>>>>,
responder: Arc<Mutex<Option<RequestAsyncResponder>>>,
}
impl EditQueue {
pub fn handle_request(&self, responder: RequestAsyncResponder) {
let mut queue = self.queue.lock().unwrap();
if let Some(bytes) = queue.pop() {
responder.respond(wry::http::Response::new(bytes));
} else {
*self.responder.lock().unwrap() = Some(responder);
}
}
pub fn add_edits(&self, edits: Vec<u8>) {
let mut responder = self.responder.lock().unwrap();
if let Some(responder) = responder.take() {
responder.respond(wry::http::Response::new(edits));
} else {
self.queue.lock().unwrap().push(edits);
}
}
}
pub(crate) fn apply_edits(
mutations: Mutations,
channel: &mut Channel,
templates: &mut FxHashMap<String, u16>,
max_template_count: &AtomicU16,
) -> Option<Vec<u8>> {
if mutations.templates.is_empty() && mutations.edits.is_empty() {
return None;
}
for template in mutations.templates {
add_template(&template, channel, templates, max_template_count);
}
use dioxus_core::Mutation::*;
for edit in mutations.edits {
match edit {
AppendChildren { id, m } => channel.append_children(id.0 as u32, m as u16),
AssignId { path, id } => channel.assign_id(path, id.0 as u32),
CreatePlaceholder { id } => channel.create_placeholder(id.0 as u32),
CreateTextNode { value, id } => channel.create_text_node(value, id.0 as u32),
HydrateText { path, value, id } => channel.hydrate_text(path, value, id.0 as u32),
LoadTemplate { name, index, id } => {
if let Some(tmpl_id) = templates.get(name) {
channel.load_template(*tmpl_id, index as u16, id.0 as u32)
}
}
ReplaceWith { id, m } => channel.replace_with(id.0 as u32, m as u16),
ReplacePlaceholder { path, m } => channel.replace_placeholder(path, m as u16),
InsertAfter { id, m } => channel.insert_after(id.0 as u32, m as u16),
InsertBefore { id, m } => channel.insert_before(id.0 as u32, m as u16),
SetAttribute {
name,
value,
id,
ns,
} => match value {
BorrowedAttributeValue::Text(txt) => {
channel.set_attribute(id.0 as u32, name, txt, ns.unwrap_or_default())
}
BorrowedAttributeValue::Float(f) => {
channel.set_attribute(id.0 as u32, name, &f.to_string(), ns.unwrap_or_default())
}
BorrowedAttributeValue::Int(n) => {
channel.set_attribute(id.0 as u32, name, &n.to_string(), ns.unwrap_or_default())
}
BorrowedAttributeValue::Bool(b) => channel.set_attribute(
id.0 as u32,
name,
if b { "true" } else { "false" },
ns.unwrap_or_default(),
),
BorrowedAttributeValue::None => {
channel.remove_attribute(id.0 as u32, name, ns.unwrap_or_default())
}
_ => unreachable!(),
},
SetText { value, id } => channel.set_text(id.0 as u32, value),
NewEventListener { name, id, .. } => {
channel.new_event_listener(name, id.0 as u32, event_bubbles(name) as u8)
}
RemoveEventListener { name, id } => {
channel.remove_event_listener(name, id.0 as u32, event_bubbles(name) as u8)
}
Remove { id } => channel.remove(id.0 as u32),
PushRoot { id } => channel.push_root(id.0 as u32),
}
}
let bytes: Vec<_> = channel.export_memory().collect();
channel.reset();
Some(bytes)
}
pub fn add_template(
template: &Template<'static>,
channel: &mut Channel,
templates: &mut FxHashMap<String, u16>,
max_template_count: &AtomicU16,
) {
let current_max_template_count = max_template_count.load(Ordering::Relaxed);
for root in template.roots.iter() {
create_template_node(channel, root);
templates.insert(template.name.to_owned(), current_max_template_count);
}
channel.add_templates(current_max_template_count, template.roots.len() as u16);
max_template_count.fetch_add(1, Ordering::Relaxed);
}
pub fn create_template_node(channel: &mut Channel, node: &'static TemplateNode<'static>) {
use TemplateNode::*;
match node {
Element {
tag,
namespace,
attrs,
children,
..
} => {
// Push the current node onto the stack
match namespace {
Some(ns) => channel.create_element_ns(tag, ns),
None => channel.create_element(tag),
}
// Set attributes on the current node
for attr in *attrs {
if let TemplateAttribute::Static {
name,
value,
namespace,
} = attr
{
channel.set_top_attribute(name, value, namespace.unwrap_or_default())
}
}
// Add each child to the stack
for child in *children {
create_template_node(channel, child);
}
// Add all children to the parent
channel.append_children_to_top(children.len() as u16);
}
Text { text } => channel.create_raw_text(text),
DynamicText { .. } => channel.create_raw_text("p"),
Dynamic { .. } => channel.add_placeholder(),
}
}
+6 -5
View File
@@ -3,6 +3,7 @@ use dioxus_html::{geometry::euclid::Rect, MountedResult, RenderedElementBacking}
use crate::{desktop_context::DesktopContext, query::QueryEngine};
#[derive(Clone)]
/// A mounted element passed to onmounted events
pub struct DesktopElement {
id: ElementId,
@@ -17,8 +18,8 @@ impl DesktopElement {
}
impl RenderedElementBacking for DesktopElement {
fn get_raw_element(&self) -> dioxus_html::MountedResult<&dyn std::any::Any> {
Ok(self)
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn get_client_rect(
@@ -30,7 +31,7 @@ impl RenderedElementBacking for DesktopElement {
>,
>,
> {
let script = format!("return window.interpreter.GetClientRect({});", self.id.0);
let script = format!("return window.interpreter.getClientRect({});", self.id.0);
let fut = self
.query
@@ -54,7 +55,7 @@ impl RenderedElementBacking for DesktopElement {
behavior: dioxus_html::ScrollBehavior,
) -> std::pin::Pin<Box<dyn futures_util::Future<Output = dioxus_html::MountedResult<()>>>> {
let script = format!(
"return window.interpreter.ScrollTo({}, {});",
"return window.interpreter.scrollTo({}, {});",
self.id.0,
serde_json::to_string(&behavior).expect("Failed to serialize ScrollBehavior")
);
@@ -81,7 +82,7 @@ impl RenderedElementBacking for DesktopElement {
focus: bool,
) -> std::pin::Pin<Box<dyn futures_util::Future<Output = dioxus_html::MountedResult<()>>>> {
let script = format!(
"return window.interpreter.SetFocus({}, {});",
"return window.interpreter.setFocus({}, {});",
self.id.0, focus
);
+7 -9
View File
@@ -1,21 +1,19 @@
#![allow(clippy::await_holding_refcell_ref)]
use async_trait::async_trait;
use dioxus_core::ScopeState;
use dioxus_html::prelude::{EvalError, EvalProvider, Evaluator};
use std::{cell::RefCell, rc::Rc};
use crate::{query::Query, DesktopContext};
/// Provides the DesktopEvalProvider through [`cx.provide_context`].
pub fn init_eval(cx: &ScopeState) {
let desktop_ctx = cx.consume_context::<DesktopContext>().unwrap();
let provider: Rc<dyn EvalProvider> = Rc::new(DesktopEvalProvider { desktop_ctx });
cx.provide_context(provider);
}
/// Reprents the desktop-target's provider of evaluators.
pub struct DesktopEvalProvider {
desktop_ctx: DesktopContext,
pub(crate) desktop_ctx: DesktopContext,
}
impl DesktopEvalProvider {
pub fn new(desktop_ctx: DesktopContext) -> Self {
Self { desktop_ctx }
}
}
impl EvalProvider for DesktopEvalProvider {
+140 -11
View File
@@ -1,19 +1,148 @@
//! Convert a serialized event to an event trigger
use serde::{Deserialize, Serialize};
use crate::element::DesktopElement;
use dioxus_html::*;
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct IpcMessage {
method: String,
params: serde_json::Value,
}
pub(crate) struct SerializedHtmlEventConverter;
impl IpcMessage {
pub(crate) fn method(&self) -> &str {
self.method.as_str()
impl HtmlEventConverter for SerializedHtmlEventConverter {
fn convert_animation_data(&self, event: &PlatformEventData) -> AnimationData {
event
.downcast::<SerializedAnimationData>()
.cloned()
.unwrap()
.into()
}
pub(crate) fn params(self) -> serde_json::Value {
self.params
fn convert_clipboard_data(&self, event: &PlatformEventData) -> ClipboardData {
event
.downcast::<SerializedClipboardData>()
.cloned()
.unwrap()
.into()
}
fn convert_composition_data(&self, event: &PlatformEventData) -> CompositionData {
event
.downcast::<SerializedCompositionData>()
.cloned()
.unwrap()
.into()
}
fn convert_drag_data(&self, event: &PlatformEventData) -> DragData {
event
.downcast::<SerializedDragData>()
.cloned()
.unwrap()
.into()
}
fn convert_focus_data(&self, event: &PlatformEventData) -> FocusData {
event
.downcast::<SerializedFocusData>()
.cloned()
.unwrap()
.into()
}
fn convert_form_data(&self, event: &PlatformEventData) -> FormData {
event
.downcast::<SerializedFormData>()
.cloned()
.unwrap()
.into()
}
fn convert_image_data(&self, event: &PlatformEventData) -> ImageData {
event
.downcast::<SerializedImageData>()
.cloned()
.unwrap()
.into()
}
fn convert_keyboard_data(&self, event: &PlatformEventData) -> KeyboardData {
event
.downcast::<SerializedKeyboardData>()
.cloned()
.unwrap()
.into()
}
fn convert_media_data(&self, event: &PlatformEventData) -> MediaData {
event
.downcast::<SerializedMediaData>()
.cloned()
.unwrap()
.into()
}
fn convert_mounted_data(&self, event: &PlatformEventData) -> MountedData {
event.downcast::<DesktopElement>().cloned().unwrap().into()
}
fn convert_mouse_data(&self, event: &PlatformEventData) -> MouseData {
event
.downcast::<SerializedMouseData>()
.cloned()
.unwrap()
.into()
}
fn convert_pointer_data(&self, event: &PlatformEventData) -> PointerData {
event
.downcast::<SerializedPointerData>()
.cloned()
.unwrap()
.into()
}
fn convert_scroll_data(&self, event: &PlatformEventData) -> ScrollData {
event
.downcast::<SerializedScrollData>()
.cloned()
.unwrap()
.into()
}
fn convert_selection_data(&self, event: &PlatformEventData) -> SelectionData {
event
.downcast::<SerializedSelectionData>()
.cloned()
.unwrap()
.into()
}
fn convert_toggle_data(&self, event: &PlatformEventData) -> ToggleData {
event
.downcast::<SerializedToggleData>()
.cloned()
.unwrap()
.into()
}
fn convert_touch_data(&self, event: &PlatformEventData) -> TouchData {
event
.downcast::<SerializedTouchData>()
.cloned()
.unwrap()
.into()
}
fn convert_transition_data(&self, event: &PlatformEventData) -> TransitionData {
event
.downcast::<SerializedTransitionData>()
.cloned()
.unwrap()
.into()
}
fn convert_wheel_data(&self, event: &PlatformEventData) -> WheelData {
event
.downcast::<SerializedWheelData>()
.cloned()
.unwrap()
.into()
}
}
+64 -61
View File
@@ -14,74 +14,77 @@ pub(crate) struct FileDialogRequest {
pub bubbles: bool,
}
#[cfg(not(any(
target_os = "windows",
target_os = "macos",
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
)))]
pub(crate) fn get_file_event(_request: &FileDialogRequest) -> Vec<PathBuf> {
vec![]
}
#[allow(unused)]
impl FileDialogRequest {
#[cfg(not(any(
target_os = "windows",
target_os = "macos",
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
)))]
pub(crate) fn get_file_event(&self) -> Vec<PathBuf> {
vec![]
}
#[cfg(any(
target_os = "windows",
target_os = "macos",
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
pub(crate) fn get_file_event(request: &FileDialogRequest) -> Vec<PathBuf> {
fn get_file_event_for_folder(
request: &FileDialogRequest,
dialog: rfd::FileDialog,
) -> Vec<PathBuf> {
if request.multiple {
dialog.pick_folders().into_iter().flatten().collect()
} else {
dialog.pick_folder().into_iter().collect()
#[cfg(any(
target_os = "windows",
target_os = "macos",
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
pub(crate) fn get_file_event(&self) -> Vec<PathBuf> {
fn get_file_event_for_folder(
request: &FileDialogRequest,
dialog: rfd::FileDialog,
) -> Vec<PathBuf> {
if request.multiple {
dialog.pick_folders().into_iter().flatten().collect()
} else {
dialog.pick_folder().into_iter().collect()
}
}
}
fn get_file_event_for_file(
request: &FileDialogRequest,
mut dialog: rfd::FileDialog,
) -> Vec<PathBuf> {
let filters: Vec<_> = request
.accept
.as_deref()
.unwrap_or_default()
.split(',')
.filter_map(|s| Filters::from_str(s).ok())
.collect();
fn get_file_event_for_file(
request: &FileDialogRequest,
mut dialog: rfd::FileDialog,
) -> Vec<PathBuf> {
let filters: Vec<_> = request
.accept
.as_deref()
.unwrap_or_default()
.split(',')
.filter_map(|s| Filters::from_str(s).ok())
.collect();
let file_extensions: Vec<_> = filters
.iter()
.flat_map(|f| f.as_extensions().into_iter())
.collect();
let file_extensions: Vec<_> = filters
.iter()
.flat_map(|f| f.as_extensions().into_iter())
.collect();
dialog = dialog.add_filter("name", file_extensions.as_slice());
dialog = dialog.add_filter("name", file_extensions.as_slice());
let files: Vec<_> = if request.multiple {
dialog.pick_files().into_iter().flatten().collect()
let files: Vec<_> = if request.multiple {
dialog.pick_files().into_iter().flatten().collect()
} else {
dialog.pick_file().into_iter().collect()
};
files
}
let dialog = rfd::FileDialog::new();
if self.directory {
get_file_event_for_folder(self, dialog)
} else {
dialog.pick_file().into_iter().collect()
};
files
}
let dialog = rfd::FileDialog::new();
if request.directory {
get_file_event_for_folder(request, dialog)
} else {
get_file_event_for_file(request, dialog)
get_file_event_for_file(self, dialog)
}
}
}
+77
View File
@@ -0,0 +1,77 @@
use crate::{
assets::*, ipc::UserWindowEvent, shortcut::IntoAccelerator, window, DesktopContext,
ShortcutHandle, ShortcutRegistryError, WryEventHandler,
};
use dioxus_core::ScopeState;
use tao::{event::Event, event_loop::EventLoopWindowTarget};
use wry::RequestAsyncResponder;
/// Get an imperative handle to the current window
pub fn use_window(cx: &ScopeState) -> &DesktopContext {
cx.use_hook(|| cx.consume_context::<DesktopContext>())
.as_ref()
.unwrap()
}
/// Get a closure that executes any JavaScript in the WebView context.
pub fn use_wry_event_handler(
cx: &ScopeState,
handler: impl FnMut(&Event<UserWindowEvent>, &EventLoopWindowTarget<UserWindowEvent>) + 'static,
) -> &WryEventHandler {
cx.use_hook(move || {
let desktop = window();
let id = desktop.create_wry_event_handler(handler);
WryEventHandler {
handlers: desktop.shared.event_handlers.clone(),
id,
}
})
}
/// Provide a callback to handle asset loading yourself.
///
/// The callback takes a path as requested by the web view, and it should return `Some(response)`
/// if you want to load the asset, and `None` if you want to fallback on the default behavior.
pub fn use_asset_handler(
cx: &ScopeState,
name: &str,
handler: impl Fn(AssetRequest, RequestAsyncResponder) + 'static,
) {
cx.use_hook(|| {
crate::window().asset_handlers.register_handler(
name.to_string(),
Box::new(handler),
cx.scope_id(),
);
Handler(name.to_string())
});
// todo: can we just put ondrop in core?
struct Handler(String);
impl Drop for Handler {
fn drop(&mut self) {
_ = crate::window().asset_handlers.remove_handler(&self.0);
}
}
}
/// Get a closure that executes any JavaScript in the WebView context.
pub fn use_global_shortcut(
cx: &ScopeState,
accelerator: impl IntoAccelerator,
handler: impl FnMut() + 'static,
) -> &Result<ShortcutHandle, ShortcutRegistryError> {
cx.use_hook(move || {
let desktop = window();
let id = desktop.create_shortcut(accelerator.accelerator(), handler);
Ok(ShortcutHandle {
desktop,
shortcut_id: id?,
})
})
}
+9 -9
View File
@@ -1,12 +1,12 @@
<!DOCTYPE html>
<html>
<head>
<title>Dioxus app</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- CUSTOM HEAD -->
</head>
<body>
<div id="main"></div>
<!-- MODULE LOADER -->
</body>
<head>
<title>Dioxus app</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- CUSTOM HEAD -->
</head>
<body>
<div id="main"></div>
<!-- MODULE LOADER -->
</body>
</html>
+64
View File
@@ -0,0 +1,64 @@
use serde::{Deserialize, Serialize};
use tao::window::WindowId;
/// A pair of data
#[derive(Debug, Clone)]
pub struct UserWindowEvent(pub EventData, pub WindowId);
/// The data that might eminate from any window/webview
#[derive(Debug, Clone)]
pub enum EventData {
/// Poll the virtualdom
Poll,
/// Handle an ipc message eminating from the window.postMessage of a given webview
Ipc(IpcMessage),
/// Handle a hotreload event, basically telling us to update our templates
#[cfg(all(feature = "hot-reload", debug_assertions))]
HotReloadEvent(dioxus_hot_reload::HotReloadMsg),
/// Create a new window
NewWindow,
/// Close a given window (could be any window!)
CloseWindow,
}
/// A message struct that manages the communication between the webview and the eventloop code
///
/// This needs to be serializable across the JS boundary, so the method names and structs are sensitive.
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct IpcMessage {
method: String,
params: serde_json::Value,
}
/// A set of known messages that we need to respond to
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum IpcMethod<'a> {
FileDialog,
UserEvent,
Query,
BrowserOpen,
Initialize,
Other(&'a str),
}
impl IpcMessage {
pub(crate) fn method(&self) -> IpcMethod {
match self.method.as_str() {
// todo: this is a misspelling, needs to be fixed
"file_diolog" => IpcMethod::FileDialog,
"user_event" => IpcMethod::UserEvent,
"query" => IpcMethod::Query,
"browser_open" => IpcMethod::BrowserOpen,
"initialize" => IpcMethod::Initialize,
_ => IpcMethod::Other(&self.method),
}
}
pub(crate) fn params(self) -> serde_json::Value {
self.params
}
}
+132
View File
@@ -0,0 +1,132 @@
use crate::{
app::App,
ipc::{EventData, IpcMethod, UserWindowEvent},
Config,
};
use dioxus_core::*;
use tao::event::{Event, StartCause, WindowEvent};
/// Launch the WebView and run the event loop.
///
/// This function will start a multithreaded Tokio runtime as well the WebView event loop.
///
/// ```rust, no_run
/// use dioxus::prelude::*;
///
/// fn main() {
/// dioxus_desktop::launch(app);
/// }
///
/// fn app(cx: Scope) -> Element {
/// cx.render(rsx!{
/// h1 {"hello world!"}
/// })
/// }
/// ```
pub fn launch(root: Component) {
launch_with_props(root, (), Config::default())
}
/// Launch the WebView and run the event loop, with configuration.
///
/// This function will start a multithreaded Tokio runtime as well the WebView event loop.
///
/// You can configure the WebView window with a configuration closure
///
/// ```rust, no_run
/// use dioxus::prelude::*;
/// use dioxus_desktop::*;
///
/// fn main() {
/// dioxus_desktop::launch_cfg(app, Config::default().with_window(WindowBuilder::new().with_title("My App")));
/// }
///
/// fn app(cx: Scope) -> Element {
/// cx.render(rsx!{
/// h1 {"hello world!"}
/// })
/// }
/// ```
pub fn launch_cfg(root: Component, config_builder: Config) {
launch_with_props(root, (), config_builder)
}
/// Launch the WebView and run the event loop, with configuration and root props.
///
/// If the [`tokio`] feature is enabled, this will also startup and block a tokio runtime using the unconstrained task.
/// This function will start a multithreaded Tokio runtime as well the WebView event loop. This will block the current thread.
///
/// You can configure the WebView window with a configuration closure
///
/// ```rust, no_run
/// use dioxus::prelude::*;
/// use dioxus_desktop::Config;
///
/// fn main() {
/// dioxus_desktop::launch_with_props(app, AppProps { name: "asd" }, Config::default());
/// }
///
/// struct AppProps {
/// name: &'static str
/// }
///
/// fn app(cx: Scope<AppProps>) -> Element {
/// cx.render(rsx!{
/// h1 {"hello {cx.props.name}!"}
/// })
/// }
/// ```
pub fn launch_with_props<P: 'static>(root: Component<P>, props: P, cfg: Config) {
#[cfg(feature = "tokio")]
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap()
.block_on(tokio::task::unconstrained(async move {
launch_with_props_blocking(root, props, cfg);
}));
#[cfg(not(feature = "tokio"))]
launch_with_props_blocking(root, props, cfg);
}
/// Launch the WebView and run the event loop, with configuration and root props.
///
/// This will block the main thread, and *must* be spawned on the main thread. This function does not assume any runtime
/// and is equivalent to calling launch_with_props with the tokio feature disabled.
pub fn launch_with_props_blocking<P: 'static>(root: Component<P>, props: P, cfg: Config) {
let (event_loop, mut app) = App::new(cfg, props, root);
event_loop.run(move |window_event, _, control_flow| {
app.tick(&window_event);
match window_event {
Event::NewEvents(StartCause::Init) => app.handle_start_cause_init(),
Event::WindowEvent {
event, window_id, ..
} => match event {
WindowEvent::CloseRequested => app.handle_close_requested(window_id),
WindowEvent::Destroyed { .. } => app.window_destroyed(window_id),
_ => {}
},
Event::UserEvent(UserWindowEvent(event, id)) => match event {
EventData::Poll => app.poll_vdom(id),
EventData::NewWindow => app.handle_new_window(),
EventData::CloseWindow => app.handle_close_msg(id),
#[cfg(feature = "hot-reload")]
EventData::HotReloadEvent(msg) => app.handle_hot_reload_msg(msg),
EventData::Ipc(msg) => match msg.method() {
IpcMethod::FileDialog => app.handle_file_dialog_msg(msg, id),
IpcMethod::UserEvent => app.handle_user_event_msg(msg, id),
IpcMethod::Query => app.handle_query_msg(msg, id),
IpcMethod::BrowserOpen => app.handle_browser_open(msg),
IpcMethod::Initialize => app.handle_initialize_msg(id),
IpcMethod::Other(_) => {}
},
},
_ => {}
}
*control_flow = app.control_flow;
})
}
+28 -465
View File
@@ -3,486 +3,49 @@
#![doc(html_favicon_url = "https://avatars.githubusercontent.com/u/79236386")]
#![deny(missing_docs)]
mod cfg;
mod app;
mod assets;
mod config;
mod desktop_context;
mod edits;
mod element;
mod escape;
mod eval;
mod events;
mod file_upload;
mod hooks;
mod ipc;
mod menubar;
mod protocol;
mod query;
mod shortcut;
mod waker;
mod webview;
#[cfg(feature = "collect-assets")]
mod collect_assets;
// mobile shortcut is only supported on mobile platforms
#[cfg(any(target_os = "ios", target_os = "android"))]
mod mobile_shortcut;
use crate::query::QueryResult;
pub use cfg::{Config, WindowCloseBehaviour};
pub use desktop_context::DesktopContext;
pub use desktop_context::{
use_window, use_wry_event_handler, DesktopService, WryEventHandler, WryEventHandlerId,
};
use desktop_context::{EventData, UserWindowEvent, WebviewQueue, WindowEventHandlers};
use dioxus_core::*;
use dioxus_html::MountedData;
use dioxus_html::{native_bind::NativeFileEngine, FormData, HtmlEvent};
use element::DesktopElement;
use eval::init_eval;
use futures_util::{pin_mut, FutureExt};
use shortcut::ShortcutRegistry;
pub use shortcut::{use_global_shortcut, ShortcutHandle, ShortcutId, ShortcutRegistryError};
use std::cell::Cell;
use std::rc::Rc;
use std::task::Waker;
use std::{collections::HashMap, sync::Arc};
pub use tao::dpi::{LogicalSize, PhysicalSize};
use tao::event_loop::{EventLoopProxy, EventLoopWindowTarget};
// The main entrypoint for this crate
pub use launch::*;
mod launch;
// Reexport tao and wry, might want to re-export other important things
pub use tao;
pub use tao::dpi::{LogicalPosition, LogicalSize};
pub use tao::event::WindowEvent;
pub use tao::window::WindowBuilder;
use tao::{
event::{Event, StartCause, WindowEvent},
event_loop::{ControlFlow, EventLoop},
};
pub use wry;
pub use wry::application as tao;
use wry::webview::WebView;
use wry::{application::window::WindowId, webview::WebContext};
/// Launch the WebView and run the event loop.
///
/// This function will start a multithreaded Tokio runtime as well the WebView event loop.
///
/// ```rust, no_run
/// use dioxus::prelude::*;
///
/// fn main() {
/// dioxus_desktop::launch(app);
/// }
///
/// fn app(cx: Scope) -> Element {
/// cx.render(rsx!{
/// h1 {"hello world!"}
/// })
/// }
/// ```
pub fn launch(root: Component) {
launch_with_props(root, (), Config::default())
}
/// Launch the WebView and run the event loop, with configuration.
///
/// This function will start a multithreaded Tokio runtime as well the WebView event loop.
///
/// You can configure the WebView window with a configuration closure
///
/// ```rust, no_run
/// use dioxus::prelude::*;
/// use dioxus_desktop::*;
///
/// fn main() {
/// dioxus_desktop::launch_cfg(app, Config::default().with_window(WindowBuilder::new().with_title("My App")));
/// }
///
/// fn app(cx: Scope) -> Element {
/// cx.render(rsx!{
/// h1 {"hello world!"}
/// })
/// }
/// ```
pub fn launch_cfg(root: Component, config_builder: Config) {
launch_with_props(root, (), config_builder)
}
/// Launch the WebView and run the event loop, with configuration and root props.
///
/// This function will start a multithreaded Tokio runtime as well the WebView event loop. This will block the current thread.
///
/// You can configure the WebView window with a configuration closure
///
/// ```rust, no_run
/// use dioxus::prelude::*;
/// use dioxus_desktop::Config;
///
/// fn main() {
/// dioxus_desktop::launch_with_props(app, AppProps { name: "asd" }, Config::default());
/// }
///
/// struct AppProps {
/// name: &'static str
/// }
///
/// fn app(cx: Scope<AppProps>) -> Element {
/// cx.render(rsx!{
/// h1 {"hello {cx.props.name}!"}
/// })
/// }
/// ```
pub fn launch_with_props<P: 'static>(root: Component<P>, props: P, cfg: Config) {
let event_loop = EventLoop::<UserWindowEvent>::with_user_event();
let proxy = event_loop.create_proxy();
let window_behaviour = cfg.last_window_close_behaviour;
// Intialize hot reloading if it is enabled
#[cfg(all(feature = "hot-reload", debug_assertions))]
dioxus_hot_reload::connect({
let proxy = proxy.clone();
move |template| {
let _ = proxy.send_event(UserWindowEvent(
EventData::HotReloadEvent(template),
unsafe { WindowId::dummy() },
));
}
});
// We start the tokio runtime *on this thread*
// Any future we poll later will use this runtime to spawn tasks and for IO
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap();
// We enter the runtime but we poll futures manually, circumventing the per-task runtime budget
let _guard = rt.enter();
// We only have one webview right now, but we'll have more later
// Store them in a hashmap so we can remove them when they're closed
let mut webviews = HashMap::<WindowId, WebviewHandler>::new();
// We use this to allow dynamically adding and removing window event handlers
let event_handlers = WindowEventHandlers::default();
let queue = WebviewQueue::default();
let shortcut_manager = ShortcutRegistry::new(&event_loop);
// move the props into a cell so we can pop it out later to create the first window
// iOS panics if we create a window before the event loop is started
let props = Rc::new(Cell::new(Some(props)));
let cfg = Rc::new(Cell::new(Some(cfg)));
let mut is_visible_before_start = true;
event_loop.run(move |window_event, event_loop, control_flow| {
*control_flow = ControlFlow::Wait;
event_handlers.apply_event(&window_event, event_loop);
match window_event {
Event::WindowEvent {
event, window_id, ..
} => match event {
WindowEvent::CloseRequested => match window_behaviour {
cfg::WindowCloseBehaviour::LastWindowExitsApp => {
webviews.remove(&window_id);
if webviews.is_empty() {
*control_flow = ControlFlow::Exit
}
}
cfg::WindowCloseBehaviour::LastWindowHides => {
let Some(webview) = webviews.get(&window_id) else {
return;
};
hide_app_window(&webview.desktop_context.webview);
}
cfg::WindowCloseBehaviour::CloseWindow => {
webviews.remove(&window_id);
}
},
WindowEvent::Destroyed { .. } => {
webviews.remove(&window_id);
if matches!(
window_behaviour,
cfg::WindowCloseBehaviour::LastWindowExitsApp
) && webviews.is_empty()
{
*control_flow = ControlFlow::Exit
}
}
_ => {}
},
Event::NewEvents(StartCause::Init) => {
let props = props.take().unwrap();
let cfg = cfg.take().unwrap();
// Create a dom
let dom = VirtualDom::new_with_props(root, props);
is_visible_before_start = cfg.window.window.visible;
let handler = create_new_window(
cfg,
event_loop,
&proxy,
dom,
&queue,
&event_handlers,
shortcut_manager.clone(),
);
let id = handler.desktop_context.webview.window().id();
webviews.insert(id, handler);
_ = proxy.send_event(UserWindowEvent(EventData::Poll, id));
}
Event::UserEvent(UserWindowEvent(EventData::NewWindow, _)) => {
for handler in queue.borrow_mut().drain(..) {
let id = handler.desktop_context.webview.window().id();
webviews.insert(id, handler);
_ = proxy.send_event(UserWindowEvent(EventData::Poll, id));
}
}
Event::UserEvent(event) => match event.0 {
#[cfg(all(feature = "hot-reload", debug_assertions))]
EventData::HotReloadEvent(msg) => match msg {
dioxus_hot_reload::HotReloadMsg::UpdateTemplate(template) => {
for webview in webviews.values_mut() {
webview.dom.replace_template(template);
poll_vdom(webview);
}
}
dioxus_hot_reload::HotReloadMsg::Shutdown => {
*control_flow = ControlFlow::Exit;
}
},
EventData::CloseWindow => {
webviews.remove(&event.1);
if webviews.is_empty() {
*control_flow = ControlFlow::Exit
}
}
EventData::Poll => {
if let Some(view) = webviews.get_mut(&event.1) {
poll_vdom(view);
}
}
EventData::Ipc(msg) if msg.method() == "user_event" => {
let params = msg.params();
let evt = match serde_json::from_value::<HtmlEvent>(params) {
Ok(value) => value,
Err(_) => return,
};
let HtmlEvent {
element,
name,
bubbles,
data,
} = evt;
let view = webviews.get_mut(&event.1).unwrap();
// check for a mounted event placeholder and replace it with a desktop specific element
let as_any = if let dioxus_html::EventData::Mounted = &data {
let query = view
.dom
.base_scope()
.consume_context::<DesktopContext>()
.unwrap()
.query
.clone();
let element =
DesktopElement::new(element, view.desktop_context.clone(), query);
Rc::new(MountedData::new(element))
} else {
data.into_any()
};
view.dom.handle_event(&name, as_any, element, bubbles);
send_edits(view.dom.render_immediate(), &view.desktop_context.webview);
}
// When the webview sends a query, we need to send it to the query manager which handles dispatching the data to the correct pending query
EventData::Ipc(msg) if msg.method() == "query" => {
let params = msg.params();
if let Ok(result) = serde_json::from_value::<QueryResult>(params) {
let view = webviews.get(&event.1).unwrap();
let query = view
.dom
.base_scope()
.consume_context::<DesktopContext>()
.unwrap()
.query
.clone();
query.send(result);
}
}
EventData::Ipc(msg) if msg.method() == "initialize" => {
let view = webviews.get_mut(&event.1).unwrap();
send_edits(view.dom.rebuild(), &view.desktop_context.webview);
view.desktop_context
.webview
.window()
.set_visible(is_visible_before_start);
}
EventData::Ipc(msg) if msg.method() == "browser_open" => {
if let Some(temp) = msg.params().as_object() {
if temp.contains_key("href") {
let open = webbrowser::open(temp["href"].as_str().unwrap());
if let Err(e) = open {
tracing::error!("Open Browser error: {:?}", e);
}
}
}
}
EventData::Ipc(msg) if msg.method() == "file_diolog" => {
if let Ok(file_diolog) =
serde_json::from_value::<file_upload::FileDialogRequest>(msg.params())
{
let id = ElementId(file_diolog.target);
let event_name = &file_diolog.event;
let event_bubbles = file_diolog.bubbles;
let files = file_upload::get_file_event(&file_diolog);
let data = Rc::new(FormData {
value: Default::default(),
values: Default::default(),
files: Some(Arc::new(NativeFileEngine::new(files))),
});
let view = webviews.get_mut(&event.1).unwrap();
if event_name == "change&input" {
view.dom
.handle_event("input", data.clone(), id, event_bubbles);
view.dom.handle_event("change", data, id, event_bubbles);
} else {
view.dom.handle_event(event_name, data, id, event_bubbles);
}
send_edits(view.dom.render_immediate(), &view.desktop_context.webview);
}
}
_ => {}
},
Event::GlobalShortcutEvent(id) => shortcut_manager.call_handlers(id),
_ => {}
}
})
}
fn create_new_window(
mut cfg: Config,
event_loop: &EventLoopWindowTarget<UserWindowEvent>,
proxy: &EventLoopProxy<UserWindowEvent>,
dom: VirtualDom,
queue: &WebviewQueue,
event_handlers: &WindowEventHandlers,
shortcut_manager: ShortcutRegistry,
) -> WebviewHandler {
let (webview, web_context) = webview::build(&mut cfg, event_loop, proxy.clone());
let desktop_context = Rc::from(DesktopService::new(
webview,
proxy.clone(),
event_loop.clone(),
queue.clone(),
event_handlers.clone(),
shortcut_manager,
));
let cx = dom.base_scope();
cx.provide_context(desktop_context.clone());
// Init eval
init_eval(cx);
WebviewHandler {
// We want to poll the virtualdom and the event loop at the same time, so the waker will be connected to both
waker: waker::tao_waker(proxy, desktop_context.webview.window().id()),
desktop_context,
dom,
_web_context: web_context,
}
}
struct WebviewHandler {
dom: VirtualDom,
desktop_context: DesktopContext,
waker: Waker,
// Wry assumes the webcontext is alive for the lifetime of the webview.
// We need to keep the webcontext alive, otherwise the webview will crash
_web_context: WebContext,
}
/// Poll the virtualdom until it's pending
///
/// The waker we give it is connected to the event loop, so it will wake up the event loop when it's ready to be polled again
///
/// All IO is done on the tokio runtime we started earlier
fn poll_vdom(view: &mut WebviewHandler) {
let mut cx = std::task::Context::from_waker(&view.waker);
loop {
{
let fut = view.dom.wait_for_work();
pin_mut!(fut);
match fut.poll_unpin(&mut cx) {
std::task::Poll::Ready(_) => {}
std::task::Poll::Pending => break,
}
}
send_edits(view.dom.render_immediate(), &view.desktop_context.webview);
}
}
/// Send a list of mutations to the webview
fn send_edits(edits: Mutations, webview: &WebView) {
let serialized = serde_json::to_string(&edits).unwrap();
// todo: use SSE and binary data to send the edits with lower overhead
_ = webview.evaluate_script(&format!("window.interpreter.handleEdits({serialized})"));
}
/// Different hide implementations per platform
#[allow(unused)]
fn hide_app_window(webview: &WebView) {
#[cfg(target_os = "windows")]
{
use wry::application::platform::windows::WindowExtWindows;
webview.window().set_visible(false);
webview.window().set_skip_taskbar(true);
}
#[cfg(target_os = "linux")]
{
use wry::application::platform::unix::WindowExtUnix;
webview.window().set_visible(false);
}
#[cfg(target_os = "macos")]
{
// webview.window().set_visible(false); has the wrong behaviour on macOS
// It will hide the window but not show it again when the user switches
// back to the app. `NSApplication::hide:` has the correct behaviour
use objc::runtime::Object;
use objc::{msg_send, sel, sel_impl};
objc::rc::autoreleasepool(|| unsafe {
let app: *mut Object = msg_send![objc::class!(NSApplication), sharedApplication];
let nil = std::ptr::null_mut::<Object>();
let _: () = msg_send![app, hide: nil];
});
}
}
// Public exports
pub use assets::AssetRequest;
pub use config::{Config, WindowCloseBehaviour};
pub use desktop_context::{
window, DesktopContext, DesktopService, WryEventHandler, WryEventHandlerId,
};
pub use hooks::{use_asset_handler, use_global_shortcut, use_window, use_wry_event_handler};
pub use shortcut::{ShortcutHandle, ShortcutId, ShortcutRegistryError};
pub use wry::RequestAsyncResponder;
+79
View File
@@ -0,0 +1,79 @@
use tao::window::Window;
#[allow(unused)]
pub fn build_menu(window: &Window, default_menu_bar: bool) {
if default_menu_bar {
#[cfg(not(any(target_os = "ios", target_os = "android")))]
impl_::build_menu_bar(impl_::build_default_menu_bar(), window)
}
}
#[cfg(not(any(target_os = "ios", target_os = "android")))]
mod impl_ {
use super::*;
use muda::{Menu, PredefinedMenuItem, Submenu};
#[allow(unused)]
pub fn build_menu_bar(menu: Menu, window: &Window) {
#[cfg(target_os = "windows")]
use tao::platform::windows::WindowExtWindows;
#[cfg(target_os = "windows")]
menu.init_for_hwnd(window.hwnd());
// #[cfg(target_os = "linux")]
// {
// use tao::platform::unix::WindowExtUnix;
// menu.init_for_gtk_window(window, None);
// menu.init_for_gtk_window(window, Some(&ertical_gtk_box));
// }
#[cfg(target_os = "macos")]
menu.init_for_nsapp();
}
/// Builds a standard menu bar depending on the users platform. It may be used as a starting point
/// to further customize the menu bar and pass it to a [`WindowBuilder`](tao::window::WindowBuilder).
/// > Note: The default menu bar enables macOS shortcuts like cut/copy/paste.
/// > The menu bar differs per platform because of constraints introduced
/// > by [`MenuItem`](tao::menu::MenuItem).
pub fn build_default_menu_bar() -> Menu {
let menu = Menu::new();
// since it is uncommon on windows to have an "application menu"
// we add a "window" menu to be more consistent across platforms with the standard menu
let window_menu = Submenu::new("Window", true);
window_menu
.append_items(&[
&PredefinedMenuItem::fullscreen(None),
&PredefinedMenuItem::separator(),
&PredefinedMenuItem::hide(None),
&PredefinedMenuItem::hide_others(None),
&PredefinedMenuItem::show_all(None),
&PredefinedMenuItem::maximize(None),
&PredefinedMenuItem::minimize(None),
&PredefinedMenuItem::close_window(None),
&PredefinedMenuItem::separator(),
&PredefinedMenuItem::quit(None),
])
.unwrap();
let edit_menu = Submenu::new("Window", true);
edit_menu
.append_items(&[
&PredefinedMenuItem::undo(None),
&PredefinedMenuItem::redo(None),
&PredefinedMenuItem::separator(),
&PredefinedMenuItem::cut(None),
&PredefinedMenuItem::copy(None),
&PredefinedMenuItem::paste(None),
&PredefinedMenuItem::separator(),
&PredefinedMenuItem::select_all(None),
])
.unwrap();
menu.append_items(&[&window_menu, &edit_menu]).unwrap();
menu
}
}
+55 -21
View File
@@ -1,29 +1,51 @@
#![allow(unused)]
use super::*;
use wry::application::accelerator::Accelerator;
use wry::application::event_loop::EventLoopWindowTarget;
use std::str::FromStr;
use tao::event_loop::EventLoopWindowTarget;
pub struct GlobalShortcut();
pub struct ShortcutManager();
use dioxus_html::input_data::keyboard_types::Modifiers;
impl ShortcutManager {
pub fn new<T>(target: &EventLoopWindowTarget<T>) -> Self {
Self()
#[derive(Clone, Debug)]
pub struct Accelerator;
#[derive(Clone, Copy)]
pub struct HotKey;
impl HotKey {
pub fn new(mods: Option<Modifiers>, key: Code) -> Self {
Self
}
pub fn register(
&mut self,
accelerator: Accelerator,
) -> Result<GlobalShortcut, ShortcutManagerError> {
Ok(GlobalShortcut())
pub fn id(&self) -> u32 {
0
}
}
impl FromStr for HotKey {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(HotKey)
}
}
pub struct GlobalHotKeyManager();
impl GlobalHotKeyManager {
pub fn new() -> Result<Self, HotkeyError> {
Ok(Self())
}
pub fn unregister(&mut self, id: ShortcutId) -> Result<(), ShortcutManagerError> {
pub fn register(&self, accelerator: HotKey) -> Result<HotKey, HotkeyError> {
Ok(HotKey)
}
pub fn unregister(&self, id: HotKey) -> Result<(), HotkeyError> {
Ok(())
}
pub fn unregister_all(&mut self) -> Result<(), ShortcutManagerError> {
pub fn unregister_all(&self, _: &[HotKey]) -> Result<(), HotkeyError> {
Ok(())
}
}
@@ -33,23 +55,35 @@ use std::{error, fmt};
/// An error whose cause the `ShortcutManager` to fail.
#[non_exhaustive]
#[derive(Debug)]
pub enum ShortcutManagerError {
pub enum HotkeyError {
AcceleratorAlreadyRegistered(Accelerator),
AcceleratorNotRegistered(Accelerator),
InvalidAccelerator(String),
HotKeyParseError(String),
}
impl error::Error for ShortcutManagerError {}
impl fmt::Display for ShortcutManagerError {
impl error::Error for HotkeyError {}
impl fmt::Display for HotkeyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
match self {
ShortcutManagerError::AcceleratorAlreadyRegistered(e) => {
HotkeyError::AcceleratorAlreadyRegistered(e) => {
f.pad(&format!("hotkey already registered: {:?}", e))
}
ShortcutManagerError::AcceleratorNotRegistered(e) => {
HotkeyError::AcceleratorNotRegistered(e) => {
f.pad(&format!("hotkey not registered: {:?}", e))
}
ShortcutManagerError::InvalidAccelerator(e) => e.fmt(f),
HotkeyError::HotKeyParseError(e) => e.fmt(f),
}
}
}
pub struct GlobalHotKeyEvent {
pub id: u32,
}
impl GlobalHotKeyEvent {
pub fn receiver() -> crossbeam_channel::Receiver<GlobalHotKeyEvent> {
crossbeam_channel::unbounded().1
}
}
pub(crate) type Code = dioxus_html::input_data::keyboard_types::Code;
+178 -133
View File
@@ -1,151 +1,204 @@
use dioxus_interpreter_js::{COMMON_JS, INTERPRETER_JS};
use std::{
borrow::Cow,
path::{Path, PathBuf},
};
use crate::{assets::*, edits::EditQueue};
use std::path::{Path, PathBuf};
use wry::{
http::{status::StatusCode, Request, Response},
Result,
http::{status::StatusCode, Request, Response, Uri},
RequestAsyncResponder, Result,
};
fn module_loader(root_name: &str) -> String {
let js = INTERPRETER_JS.replace(
"/*POST_HANDLE_EDITS*/",
r#"// Prevent file inputs from opening the file dialog on click
let inputs = document.querySelectorAll("input");
for (let input of inputs) {
if (!input.getAttribute("data-dioxus-file-listener")) {
// prevent file inputs from opening the file dialog on click
const type = input.getAttribute("type");
if (type === "file") {
input.setAttribute("data-dioxus-file-listener", true);
input.addEventListener("click", (event) => {
let target = event.target;
let target_id = find_real_id(target);
if (target_id !== null) {
const send = (event_name) => {
const message = serializeIpcMessage("file_diolog", { accept: target.getAttribute("accept"), directory: target.getAttribute("webkitdirectory") === "true", multiple: target.hasAttribute("multiple"), target: parseInt(target_id), bubbles: event_bubbles(event_name), event: event_name });
window.ipc.postMessage(message);
};
send("change&input");
}
event.preventDefault();
});
}
}
}"#,
static MINIFIED: &str = include_str!("./minified.js");
static DEFAULT_INDEX: &str = include_str!("./index.html");
/// Build the index.html file we use for bootstrapping a new app
///
/// We use wry/webview by building a special index.html that forms a bridge between the webview and your rust code
///
/// This is similar to tauri, except we give more power to your rust code and less power to your frontend code.
/// This lets us skip a build/bundle step - your code just works - but limits how your Rust code can actually
/// mess with UI elements. We make this decision since other renderers like LiveView are very separate and can
/// never properly bridge the gap. Eventually of course, the idea is to build a custom CSS/HTML renderer where you
/// *do* have native control over elements, but that still won't work with liveview.
pub(super) fn index_request(
request: &Request<Vec<u8>>,
custom_head: Option<String>,
custom_index: Option<String>,
root_name: &str,
headless: bool,
) -> Option<Response<Vec<u8>>> {
// If the request is for the root, we'll serve the index.html file.
if request.uri().path() != "/" {
return None;
}
// Load a custom index file if provided
let mut index = custom_index.unwrap_or_else(|| DEFAULT_INDEX.to_string());
// Insert a custom head if provided
// We look just for the closing head tag. If a user provided a custom index with weird syntax, this might fail
if let Some(head) = custom_head {
index.insert_str(index.find("</head>").expect("Head element to exist"), &head);
}
// Inject our module loader by looking for a body tag
// A failure mode here, obviously, is if the user provided a custom index without a body tag
// Might want to document this
index.insert_str(
index.find("</body>").expect("Body element to exist"),
&module_loader(root_name, headless),
);
Response::builder()
.header("Content-Type", "text/html")
.header("Access-Control-Allow-Origin", "*")
.body(index.into())
.ok()
}
/// Handle a request from the webview
///
/// - Tries to stream edits if they're requested.
/// - If that doesn't match, tries a user provided asset handler
/// - If that doesn't match, tries to serve a file from the filesystem
pub(super) fn desktop_handler(
mut request: Request<Vec<u8>>,
asset_handlers: AssetHandlerRegistry,
edit_queue: &EditQueue,
responder: RequestAsyncResponder,
) {
// If the request is asking for edits (ie binary protocol streaming, do that)
if request.uri().path().trim_matches('/') == "edits" {
return edit_queue.handle_request(responder);
}
// If the user provided a custom asset handler, then call it and return the response if the request was handled.
// The path is the first part of the URI, so we need to trim the leading slash.
let path = PathBuf::from(
urlencoding::decode(request.uri().path().trim_start_matches('/'))
.expect("expected URL to be UTF-8 encoded")
.as_ref(),
);
let Some(name) = path.parent() else {
return tracing::error!("Asset request has no root {path:?}");
};
if let Some(name) = name.to_str() {
if asset_handlers.has_handler(name) {
// Trim the leading path from the URI
//
// I hope this is reliable!
//
// so a request for /assets/logos/logo.png?query=123 will become /logos/logo.png?query=123
strip_uri_prefix(&mut request, name);
return asset_handlers.handle_request(name, request, responder);
}
}
// Else, try to serve a file from the filesystem.
match serve_from_fs(path) {
Ok(res) => responder.respond(res),
Err(e) => tracing::error!("Error serving request from filesystem {}", e),
}
}
fn serve_from_fs(path: PathBuf) -> Result<Response<Vec<u8>>> {
// If the path is relative, we'll try to serve it from the assets directory.
let mut asset = get_asset_root_or_default().join(&path);
// If we can't find it, make it absolute and try again
if !asset.exists() {
asset = PathBuf::from("/").join(path);
}
if !asset.exists() {
return Ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(String::from("Not Found").into_bytes())?);
}
Ok(Response::builder()
.header("Content-Type", get_mime_from_path(&asset)?)
.body(std::fs::read(asset)?)?)
}
fn strip_uri_prefix(request: &mut Request<Vec<u8>>, name: &str) {
// trim the leading path
if let Some(path) = request.uri().path_and_query() {
let new_path = path
.path()
.trim_start_matches('/')
.strip_prefix(name)
.expect("expected path to have prefix");
let new_uri = Uri::builder()
.scheme(request.uri().scheme_str().unwrap_or("http"))
.path_and_query(format!("{}{}", new_path, path.query().unwrap_or("")))
.authority("index.html")
.build()
.expect("failed to build new URI");
*request.uri_mut() = new_uri;
}
}
/// Construct the inline script that boots up the page and bridges the webview with rust code.
///
/// The arguments here:
/// - root_name: the root element (by Id) that we stream edits into
/// - headless: is this page being loaded but invisible? Important because not all windows are visible and the
/// interpreter can't connect until the window is ready.
fn module_loader(root_id: &str, headless: bool) -> String {
format!(
r#"
<script type="module">
{js}
let rootname = "{root_name}";
let root = window.document.getElementById(rootname);
if (root != null) {{
window.interpreter = new Interpreter(root, new InterpreterConfig(true));
window.ipc.postMessage(serializeIpcMessage("initialize"));
{MINIFIED}
// Wait for the page to load
window.onload = function() {{
let rootname = "{root_id}";
let root_element = window.document.getElementById(rootname);
if (root_element != null) {{
window.interpreter.initialize(root_element);
window.ipc.postMessage(window.interpreter.serializeIpcMessage("initialize"));
}}
window.interpreter.wait_for_request({headless});
}}
</script>
"#
)
}
pub(super) fn desktop_handler(
request: &Request<Vec<u8>>,
custom_head: Option<String>,
custom_index: Option<String>,
root_name: &str,
) -> Result<Response<Cow<'static, [u8]>>> {
// If the request is for the root, we'll serve the index.html file.
if request.uri().path() == "/" {
// If a custom index is provided, just defer to that, expecting the user to know what they're doing.
// we'll look for the closing </body> tag and insert our little module loader there.
let body = match custom_index {
Some(custom_index) => custom_index
.replace("</body>", &format!("{}</body>", module_loader(root_name)))
.into_bytes(),
None => {
// Otherwise, we'll serve the default index.html and apply a custom head if that's specified.
let mut template = include_str!("./index.html").to_string();
if let Some(custom_head) = custom_head {
template = template.replace("<!-- CUSTOM HEAD -->", &custom_head);
}
template
.replace("<!-- MODULE LOADER -->", &module_loader(root_name))
.into_bytes()
}
};
return Response::builder()
.header("Content-Type", "text/html")
.body(Cow::from(body))
.map_err(From::from);
} else if request.uri().path() == "/common.js" {
return Response::builder()
.header("Content-Type", "text/javascript")
.body(Cow::from(COMMON_JS.as_bytes()))
.map_err(From::from);
}
// Else, try to serve a file from the filesystem.
let decoded = urlencoding::decode(request.uri().path().trim_start_matches('/'))
.expect("expected URL to be UTF-8 encoded");
let path = PathBuf::from(&*decoded);
// If the path is relative, we'll try to serve it from the assets directory.
let mut asset = get_asset_root()
.unwrap_or_else(|| Path::new(".").to_path_buf())
.join(&path);
if !asset.exists() {
asset = PathBuf::from("/").join(path);
}
if asset.exists() {
return Response::builder()
.header("Content-Type", get_mime_from_path(&asset)?)
.body(Cow::from(std::fs::read(asset)?))
.map_err(From::from);
}
Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Cow::from(String::from("Not Found").into_bytes()))
.map_err(From::from)
/// Get the assset directory, following tauri/cargo-bundles directory discovery approach
///
/// Defaults to the current directory if no asset directory is found, which is useful for development when the app
/// isn't bundled.
fn get_asset_root_or_default() -> PathBuf {
get_asset_root().unwrap_or_else(|| Path::new(".").to_path_buf())
}
/// Get the asset directory, following tauri/cargo-bundles directory discovery approach
///
/// Currently supports:
/// - [x] macOS
/// - [ ] Windows
/// - [ ] Linux (rpm)
/// - [ ] Linux (deb)
/// - [ ] iOS
/// - [ ] Android
#[allow(unreachable_code)]
fn get_asset_root() -> Option<PathBuf> {
/*
We're matching exactly how cargo-bundle works.
- [x] macOS
- [ ] Windows
- [ ] Linux (rpm)
- [ ] Linux (deb)
- [ ] iOS
- [ ] Android
*/
// If running under cargo, there's no bundle!
// There might be a smarter/more resilient way of doing this
if std::env::var_os("CARGO").is_some() {
return None;
}
// TODO: support for other platforms
#[cfg(target_os = "macos")]
{
let bundle = core_foundation::bundle::CFBundle::main_bundle();
let bundle_path = bundle.path()?;
let resources_path = bundle.resources_path()?;
let absolute_resources_root = bundle_path.join(resources_path);
let canonical_resources_root = dunce::canonicalize(absolute_resources_root).ok()?;
return Some(canonical_resources_root);
return dunce::canonicalize(absolute_resources_root).ok();
}
None
@@ -157,18 +210,10 @@ fn get_mime_from_path(trimmed: &Path) -> Result<&'static str> {
return Ok("image/svg+xml");
}
let res = match infer::get_from_path(trimmed)?.map(|f| f.mime_type()) {
Some(f) => {
if f == "text/plain" {
get_mime_by_ext(trimmed)
} else {
f
}
}
None => get_mime_by_ext(trimmed),
};
Ok(res)
match infer::get_from_path(trimmed)?.map(|f| f.mime_type()) {
Some(f) if f != "text/plain" => Ok(f),
_ => Ok(get_mime_by_ext(trimmed)),
}
}
/// Get the mime type from a URI using its extension
+179 -211
View File
@@ -1,15 +1,10 @@
use std::{cell::RefCell, collections::HashMap, rc::Rc, str::FromStr};
use std::{cell::RefCell, collections::HashMap, str::FromStr};
use dioxus_core::ScopeState;
use dioxus_html::input_data::keyboard_types::Modifiers;
use slab::Slab;
use wry::application::{
accelerator::{Accelerator, AcceleratorId},
event_loop::EventLoopWindowTarget,
keyboard::{KeyCode, ModifiersState},
};
use tao::keyboard::ModifiersState;
use crate::{desktop_context::DesktopContext, use_window};
use crate::desktop_context::DesktopContext;
#[cfg(any(
target_os = "windows",
@@ -20,22 +15,22 @@ use crate::{desktop_context::DesktopContext, use_window};
target_os = "netbsd",
target_os = "openbsd"
))]
use wry::application::global_shortcut::{GlobalShortcut, ShortcutManager, ShortcutManagerError};
pub use global_hotkey::{
hotkey::{Code, HotKey},
Error as HotkeyError, GlobalHotKeyEvent, GlobalHotKeyManager,
};
#[cfg(any(target_os = "ios", target_os = "android"))]
pub use crate::mobile_shortcut::*;
#[derive(Clone)]
pub(crate) struct ShortcutRegistry {
manager: Rc<RefCell<ShortcutManager>>,
shortcuts: ShortcutMap,
manager: GlobalHotKeyManager,
shortcuts: RefCell<HashMap<u32, Shortcut>>,
}
type ShortcutMap = Rc<RefCell<HashMap<AcceleratorId, Shortcut>>>;
struct Shortcut {
#[allow(unused)]
shortcut: GlobalShortcut,
shortcut: HotKey,
callbacks: Slab<Box<dyn FnMut()>>,
}
@@ -54,15 +49,15 @@ impl Shortcut {
}
impl ShortcutRegistry {
pub fn new<T>(target: &EventLoopWindowTarget<T>) -> Self {
pub fn new() -> Self {
Self {
manager: Rc::new(RefCell::new(ShortcutManager::new(target))),
shortcuts: Rc::new(RefCell::new(HashMap::new())),
manager: GlobalHotKeyManager::new().unwrap(),
shortcuts: RefCell::new(HashMap::new()),
}
}
pub(crate) fn call_handlers(&self, id: AcceleratorId) {
if let Some(Shortcut { callbacks, .. }) = self.shortcuts.borrow_mut().get_mut(&id) {
pub(crate) fn call_handlers(&self, id: GlobalHotKeyEvent) {
if let Some(Shortcut { callbacks, .. }) = self.shortcuts.borrow_mut().get_mut(&id.id) {
for (_, callback) in callbacks.iter_mut() {
(callback)();
}
@@ -71,40 +66,40 @@ impl ShortcutRegistry {
pub(crate) fn add_shortcut(
&self,
accelerator: Accelerator,
hotkey: HotKey,
callback: Box<dyn FnMut()>,
) -> Result<ShortcutId, ShortcutRegistryError> {
let accelerator_id = accelerator.clone().id();
let accelerator_id = hotkey.clone().id();
let mut shortcuts = self.shortcuts.borrow_mut();
Ok(
if let Some(callbacks) = shortcuts.get_mut(&accelerator_id) {
let id = callbacks.insert(callback);
ShortcutId {
id: accelerator_id,
number: id,
}
} else {
match self.manager.borrow_mut().register(accelerator) {
Ok(global_shortcut) => {
let mut slab = Slab::new();
let id = slab.insert(callback);
let shortcut = Shortcut {
shortcut: global_shortcut,
callbacks: slab,
};
shortcuts.insert(accelerator_id, shortcut);
ShortcutId {
id: accelerator_id,
number: id,
}
}
Err(ShortcutManagerError::InvalidAccelerator(shortcut)) => {
return Err(ShortcutRegistryError::InvalidShortcut(shortcut))
}
Err(err) => return Err(ShortcutRegistryError::Other(Box::new(err))),
}
},
)
if let Some(callbacks) = shortcuts.get_mut(&accelerator_id) {
return Ok(ShortcutId {
id: accelerator_id,
number: callbacks.insert(callback),
});
};
self.manager.register(hotkey).map_err(|e| match e {
HotkeyError::HotKeyParseError(shortcut) => {
ShortcutRegistryError::InvalidShortcut(shortcut)
}
err => ShortcutRegistryError::Other(Box::new(err)),
})?;
let mut shortcut = Shortcut {
shortcut: hotkey,
callbacks: Slab::new(),
};
let id = shortcut.callbacks.insert(callback);
shortcuts.insert(accelerator_id, shortcut);
Ok(ShortcutId {
id: accelerator_id,
number: id,
})
}
pub(crate) fn remove_shortcut(&self, id: ShortcutId) {
@@ -113,16 +108,7 @@ impl ShortcutRegistry {
callbacks.remove(id.number);
if callbacks.is_empty() {
if let Some(_shortcut) = shortcuts.remove(&id.id) {
#[cfg(any(
target_os = "windows",
target_os = "macos",
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
let _ = self.manager.borrow_mut().unregister(_shortcut.shortcut);
let _ = self.manager.unregister(_shortcut.shortcut);
}
}
}
@@ -130,8 +116,8 @@ impl ShortcutRegistry {
pub(crate) fn remove_all(&self) {
let mut shortcuts = self.shortcuts.borrow_mut();
shortcuts.clear();
let _ = self.manager.borrow_mut().unregister_all();
let hotkeys: Vec<_> = shortcuts.drain().map(|(_, v)| v.shortcut).collect();
let _ = self.manager.unregister_all(&hotkeys);
}
}
@@ -148,64 +134,45 @@ pub enum ShortcutRegistryError {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
/// An global id for a shortcut.
pub struct ShortcutId {
id: AcceleratorId,
id: u32,
number: usize,
}
/// A global shortcut. This will be automatically removed when it is dropped.
pub struct ShortcutHandle {
desktop: DesktopContext,
pub(crate) desktop: DesktopContext,
/// The id of the shortcut
pub shortcut_id: ShortcutId,
}
pub trait IntoAccelerator {
fn accelerator(&self) -> Accelerator;
fn accelerator(&self) -> HotKey;
}
impl IntoAccelerator for (dioxus_html::KeyCode, ModifiersState) {
fn accelerator(&self) -> Accelerator {
Accelerator::new(Some(self.1), self.0.into_key_code())
fn accelerator(&self) -> HotKey {
HotKey::new(Some(self.1.into_modifiers_state()), self.0.into_key_code())
}
}
impl IntoAccelerator for (ModifiersState, dioxus_html::KeyCode) {
fn accelerator(&self) -> Accelerator {
Accelerator::new(Some(self.0), self.1.into_key_code())
fn accelerator(&self) -> HotKey {
HotKey::new(Some(self.0.into_modifiers_state()), self.1.into_key_code())
}
}
impl IntoAccelerator for dioxus_html::KeyCode {
fn accelerator(&self) -> Accelerator {
Accelerator::new(None, self.into_key_code())
fn accelerator(&self) -> HotKey {
HotKey::new(None, self.into_key_code())
}
}
impl IntoAccelerator for &str {
fn accelerator(&self) -> Accelerator {
Accelerator::from_str(self).unwrap()
fn accelerator(&self) -> HotKey {
HotKey::from_str(self).unwrap()
}
}
/// Get a closure that executes any JavaScript in the WebView context.
pub fn use_global_shortcut(
cx: &ScopeState,
accelerator: impl IntoAccelerator,
handler: impl FnMut() + 'static,
) -> &Result<ShortcutHandle, ShortcutRegistryError> {
let desktop = use_window(cx);
cx.use_hook(move || {
let desktop = desktop.clone();
let id = desktop.create_shortcut(accelerator.accelerator(), handler);
Ok(ShortcutHandle {
desktop,
shortcut_id: id?,
})
})
}
impl ShortcutHandle {
/// Remove the shortcut.
pub fn remove(&self) {
@@ -220,143 +187,144 @@ impl Drop for ShortcutHandle {
}
pub trait IntoModifersState {
fn into_modifiers_state(self) -> ModifiersState;
fn into_modifiers_state(self) -> Modifiers;
}
impl IntoModifersState for ModifiersState {
fn into_modifiers_state(self) -> ModifiersState {
self
fn into_modifiers_state(self) -> Modifiers {
let mut modifiers = Modifiers::default();
if self.shift_key() {
modifiers |= Modifiers::SHIFT;
}
if self.control_key() {
modifiers |= Modifiers::CONTROL;
}
if self.alt_key() {
modifiers |= Modifiers::ALT;
}
if self.super_key() {
modifiers |= Modifiers::META;
}
modifiers
}
}
impl IntoModifersState for Modifiers {
fn into_modifiers_state(self) -> ModifiersState {
let mut state = ModifiersState::empty();
if self.contains(Modifiers::SHIFT) {
state |= ModifiersState::SHIFT
}
if self.contains(Modifiers::CONTROL) {
state |= ModifiersState::CONTROL
}
if self.contains(Modifiers::ALT) {
state |= ModifiersState::ALT
}
if self.contains(Modifiers::META) || self.contains(Modifiers::SUPER) {
state |= ModifiersState::SUPER
}
state
fn into_modifiers_state(self) -> Modifiers {
self
}
}
pub trait IntoKeyCode {
fn into_key_code(self) -> KeyCode;
fn into_key_code(self) -> Code;
}
impl IntoKeyCode for KeyCode {
fn into_key_code(self) -> KeyCode {
impl IntoKeyCode for Code {
fn into_key_code(self) -> Code {
self
}
}
impl IntoKeyCode for dioxus_html::KeyCode {
fn into_key_code(self) -> KeyCode {
fn into_key_code(self) -> Code {
match self {
dioxus_html::KeyCode::Backspace => KeyCode::Backspace,
dioxus_html::KeyCode::Tab => KeyCode::Tab,
dioxus_html::KeyCode::Clear => KeyCode::NumpadClear,
dioxus_html::KeyCode::Enter => KeyCode::Enter,
dioxus_html::KeyCode::Shift => KeyCode::ShiftLeft,
dioxus_html::KeyCode::Ctrl => KeyCode::ControlLeft,
dioxus_html::KeyCode::Alt => KeyCode::AltLeft,
dioxus_html::KeyCode::Pause => KeyCode::Pause,
dioxus_html::KeyCode::CapsLock => KeyCode::CapsLock,
dioxus_html::KeyCode::Escape => KeyCode::Escape,
dioxus_html::KeyCode::Space => KeyCode::Space,
dioxus_html::KeyCode::PageUp => KeyCode::PageUp,
dioxus_html::KeyCode::PageDown => KeyCode::PageDown,
dioxus_html::KeyCode::End => KeyCode::End,
dioxus_html::KeyCode::Home => KeyCode::Home,
dioxus_html::KeyCode::LeftArrow => KeyCode::ArrowLeft,
dioxus_html::KeyCode::UpArrow => KeyCode::ArrowUp,
dioxus_html::KeyCode::RightArrow => KeyCode::ArrowRight,
dioxus_html::KeyCode::DownArrow => KeyCode::ArrowDown,
dioxus_html::KeyCode::Insert => KeyCode::Insert,
dioxus_html::KeyCode::Delete => KeyCode::Delete,
dioxus_html::KeyCode::Num0 => KeyCode::Numpad0,
dioxus_html::KeyCode::Num1 => KeyCode::Numpad1,
dioxus_html::KeyCode::Num2 => KeyCode::Numpad2,
dioxus_html::KeyCode::Num3 => KeyCode::Numpad3,
dioxus_html::KeyCode::Num4 => KeyCode::Numpad4,
dioxus_html::KeyCode::Num5 => KeyCode::Numpad5,
dioxus_html::KeyCode::Num6 => KeyCode::Numpad6,
dioxus_html::KeyCode::Num7 => KeyCode::Numpad7,
dioxus_html::KeyCode::Num8 => KeyCode::Numpad8,
dioxus_html::KeyCode::Num9 => KeyCode::Numpad9,
dioxus_html::KeyCode::A => KeyCode::KeyA,
dioxus_html::KeyCode::B => KeyCode::KeyB,
dioxus_html::KeyCode::C => KeyCode::KeyC,
dioxus_html::KeyCode::D => KeyCode::KeyD,
dioxus_html::KeyCode::E => KeyCode::KeyE,
dioxus_html::KeyCode::F => KeyCode::KeyF,
dioxus_html::KeyCode::G => KeyCode::KeyG,
dioxus_html::KeyCode::H => KeyCode::KeyH,
dioxus_html::KeyCode::I => KeyCode::KeyI,
dioxus_html::KeyCode::J => KeyCode::KeyJ,
dioxus_html::KeyCode::K => KeyCode::KeyK,
dioxus_html::KeyCode::L => KeyCode::KeyL,
dioxus_html::KeyCode::M => KeyCode::KeyM,
dioxus_html::KeyCode::N => KeyCode::KeyN,
dioxus_html::KeyCode::O => KeyCode::KeyO,
dioxus_html::KeyCode::P => KeyCode::KeyP,
dioxus_html::KeyCode::Q => KeyCode::KeyQ,
dioxus_html::KeyCode::R => KeyCode::KeyR,
dioxus_html::KeyCode::S => KeyCode::KeyS,
dioxus_html::KeyCode::T => KeyCode::KeyT,
dioxus_html::KeyCode::U => KeyCode::KeyU,
dioxus_html::KeyCode::V => KeyCode::KeyV,
dioxus_html::KeyCode::W => KeyCode::KeyW,
dioxus_html::KeyCode::X => KeyCode::KeyX,
dioxus_html::KeyCode::Y => KeyCode::KeyY,
dioxus_html::KeyCode::Z => KeyCode::KeyZ,
dioxus_html::KeyCode::Numpad0 => KeyCode::Numpad0,
dioxus_html::KeyCode::Numpad1 => KeyCode::Numpad1,
dioxus_html::KeyCode::Numpad2 => KeyCode::Numpad2,
dioxus_html::KeyCode::Numpad3 => KeyCode::Numpad3,
dioxus_html::KeyCode::Numpad4 => KeyCode::Numpad4,
dioxus_html::KeyCode::Numpad5 => KeyCode::Numpad5,
dioxus_html::KeyCode::Numpad6 => KeyCode::Numpad6,
dioxus_html::KeyCode::Numpad7 => KeyCode::Numpad7,
dioxus_html::KeyCode::Numpad8 => KeyCode::Numpad8,
dioxus_html::KeyCode::Numpad9 => KeyCode::Numpad9,
dioxus_html::KeyCode::Multiply => KeyCode::NumpadMultiply,
dioxus_html::KeyCode::Add => KeyCode::NumpadAdd,
dioxus_html::KeyCode::Subtract => KeyCode::NumpadSubtract,
dioxus_html::KeyCode::DecimalPoint => KeyCode::NumpadDecimal,
dioxus_html::KeyCode::Divide => KeyCode::NumpadDivide,
dioxus_html::KeyCode::F1 => KeyCode::F1,
dioxus_html::KeyCode::F2 => KeyCode::F2,
dioxus_html::KeyCode::F3 => KeyCode::F3,
dioxus_html::KeyCode::F4 => KeyCode::F4,
dioxus_html::KeyCode::F5 => KeyCode::F5,
dioxus_html::KeyCode::F6 => KeyCode::F6,
dioxus_html::KeyCode::F7 => KeyCode::F7,
dioxus_html::KeyCode::F8 => KeyCode::F8,
dioxus_html::KeyCode::F9 => KeyCode::F9,
dioxus_html::KeyCode::F10 => KeyCode::F10,
dioxus_html::KeyCode::F11 => KeyCode::F11,
dioxus_html::KeyCode::F12 => KeyCode::F12,
dioxus_html::KeyCode::NumLock => KeyCode::NumLock,
dioxus_html::KeyCode::ScrollLock => KeyCode::ScrollLock,
dioxus_html::KeyCode::Semicolon => KeyCode::Semicolon,
dioxus_html::KeyCode::EqualSign => KeyCode::Equal,
dioxus_html::KeyCode::Comma => KeyCode::Comma,
dioxus_html::KeyCode::Period => KeyCode::Period,
dioxus_html::KeyCode::ForwardSlash => KeyCode::Slash,
dioxus_html::KeyCode::GraveAccent => KeyCode::Backquote,
dioxus_html::KeyCode::OpenBracket => KeyCode::BracketLeft,
dioxus_html::KeyCode::BackSlash => KeyCode::Backslash,
dioxus_html::KeyCode::CloseBraket => KeyCode::BracketRight,
dioxus_html::KeyCode::SingleQuote => KeyCode::Quote,
dioxus_html::KeyCode::Backspace => Code::Backspace,
dioxus_html::KeyCode::Tab => Code::Tab,
dioxus_html::KeyCode::Clear => Code::NumpadClear,
dioxus_html::KeyCode::Enter => Code::Enter,
dioxus_html::KeyCode::Shift => Code::ShiftLeft,
dioxus_html::KeyCode::Ctrl => Code::ControlLeft,
dioxus_html::KeyCode::Alt => Code::AltLeft,
dioxus_html::KeyCode::Pause => Code::Pause,
dioxus_html::KeyCode::CapsLock => Code::CapsLock,
dioxus_html::KeyCode::Escape => Code::Escape,
dioxus_html::KeyCode::Space => Code::Space,
dioxus_html::KeyCode::PageUp => Code::PageUp,
dioxus_html::KeyCode::PageDown => Code::PageDown,
dioxus_html::KeyCode::End => Code::End,
dioxus_html::KeyCode::Home => Code::Home,
dioxus_html::KeyCode::LeftArrow => Code::ArrowLeft,
dioxus_html::KeyCode::UpArrow => Code::ArrowUp,
dioxus_html::KeyCode::RightArrow => Code::ArrowRight,
dioxus_html::KeyCode::DownArrow => Code::ArrowDown,
dioxus_html::KeyCode::Insert => Code::Insert,
dioxus_html::KeyCode::Delete => Code::Delete,
dioxus_html::KeyCode::Num0 => Code::Numpad0,
dioxus_html::KeyCode::Num1 => Code::Numpad1,
dioxus_html::KeyCode::Num2 => Code::Numpad2,
dioxus_html::KeyCode::Num3 => Code::Numpad3,
dioxus_html::KeyCode::Num4 => Code::Numpad4,
dioxus_html::KeyCode::Num5 => Code::Numpad5,
dioxus_html::KeyCode::Num6 => Code::Numpad6,
dioxus_html::KeyCode::Num7 => Code::Numpad7,
dioxus_html::KeyCode::Num8 => Code::Numpad8,
dioxus_html::KeyCode::Num9 => Code::Numpad9,
dioxus_html::KeyCode::A => Code::KeyA,
dioxus_html::KeyCode::B => Code::KeyB,
dioxus_html::KeyCode::C => Code::KeyC,
dioxus_html::KeyCode::D => Code::KeyD,
dioxus_html::KeyCode::E => Code::KeyE,
dioxus_html::KeyCode::F => Code::KeyF,
dioxus_html::KeyCode::G => Code::KeyG,
dioxus_html::KeyCode::H => Code::KeyH,
dioxus_html::KeyCode::I => Code::KeyI,
dioxus_html::KeyCode::J => Code::KeyJ,
dioxus_html::KeyCode::K => Code::KeyK,
dioxus_html::KeyCode::L => Code::KeyL,
dioxus_html::KeyCode::M => Code::KeyM,
dioxus_html::KeyCode::N => Code::KeyN,
dioxus_html::KeyCode::O => Code::KeyO,
dioxus_html::KeyCode::P => Code::KeyP,
dioxus_html::KeyCode::Q => Code::KeyQ,
dioxus_html::KeyCode::R => Code::KeyR,
dioxus_html::KeyCode::S => Code::KeyS,
dioxus_html::KeyCode::T => Code::KeyT,
dioxus_html::KeyCode::U => Code::KeyU,
dioxus_html::KeyCode::V => Code::KeyV,
dioxus_html::KeyCode::W => Code::KeyW,
dioxus_html::KeyCode::X => Code::KeyX,
dioxus_html::KeyCode::Y => Code::KeyY,
dioxus_html::KeyCode::Z => Code::KeyZ,
dioxus_html::KeyCode::Numpad0 => Code::Numpad0,
dioxus_html::KeyCode::Numpad1 => Code::Numpad1,
dioxus_html::KeyCode::Numpad2 => Code::Numpad2,
dioxus_html::KeyCode::Numpad3 => Code::Numpad3,
dioxus_html::KeyCode::Numpad4 => Code::Numpad4,
dioxus_html::KeyCode::Numpad5 => Code::Numpad5,
dioxus_html::KeyCode::Numpad6 => Code::Numpad6,
dioxus_html::KeyCode::Numpad7 => Code::Numpad7,
dioxus_html::KeyCode::Numpad8 => Code::Numpad8,
dioxus_html::KeyCode::Numpad9 => Code::Numpad9,
dioxus_html::KeyCode::Multiply => Code::NumpadMultiply,
dioxus_html::KeyCode::Add => Code::NumpadAdd,
dioxus_html::KeyCode::Subtract => Code::NumpadSubtract,
dioxus_html::KeyCode::DecimalPoint => Code::NumpadDecimal,
dioxus_html::KeyCode::Divide => Code::NumpadDivide,
dioxus_html::KeyCode::F1 => Code::F1,
dioxus_html::KeyCode::F2 => Code::F2,
dioxus_html::KeyCode::F3 => Code::F3,
dioxus_html::KeyCode::F4 => Code::F4,
dioxus_html::KeyCode::F5 => Code::F5,
dioxus_html::KeyCode::F6 => Code::F6,
dioxus_html::KeyCode::F7 => Code::F7,
dioxus_html::KeyCode::F8 => Code::F8,
dioxus_html::KeyCode::F9 => Code::F9,
dioxus_html::KeyCode::F10 => Code::F10,
dioxus_html::KeyCode::F11 => Code::F11,
dioxus_html::KeyCode::F12 => Code::F12,
dioxus_html::KeyCode::NumLock => Code::NumLock,
dioxus_html::KeyCode::ScrollLock => Code::ScrollLock,
dioxus_html::KeyCode::Semicolon => Code::Semicolon,
dioxus_html::KeyCode::EqualSign => Code::Equal,
dioxus_html::KeyCode::Comma => Code::Comma,
dioxus_html::KeyCode::Period => Code::Period,
dioxus_html::KeyCode::ForwardSlash => Code::Slash,
dioxus_html::KeyCode::GraveAccent => Code::Backquote,
dioxus_html::KeyCode::OpenBracket => Code::BracketLeft,
dioxus_html::KeyCode::BackSlash => Code::Backslash,
dioxus_html::KeyCode::CloseBraket => Code::BracketRight,
dioxus_html::KeyCode::SingleQuote => Code::Quote,
key => panic!("Failed to convert {:?} to tao::keyboard::KeyCode, try using tao::keyboard::KeyCode directly", key),
}
}
+6 -8
View File
@@ -1,14 +1,15 @@
use crate::desktop_context::{EventData, UserWindowEvent};
use crate::ipc::{EventData, UserWindowEvent};
use futures_util::task::ArcWake;
use std::sync::Arc;
use wry::application::{event_loop::EventLoopProxy, window::WindowId};
use tao::{event_loop::EventLoopProxy, window::WindowId};
/// Create a waker that will send a poll event to the event loop.
///
/// This lets the VirtualDom "come up for air" and process events while the main thread is blocked by the WebView.
///
/// All other IO lives in the Tokio runtime,
pub fn tao_waker(proxy: &EventLoopProxy<UserWindowEvent>, id: WindowId) -> std::task::Waker {
/// All IO and multithreading lives on other threads. Thanks to tokio's work stealing approach, the main thread can never
/// claim a task while it's blocked by the event loop.
pub fn tao_waker(proxy: EventLoopProxy<UserWindowEvent>, id: WindowId) -> std::task::Waker {
struct DomHandle {
proxy: EventLoopProxy<UserWindowEvent>,
id: WindowId,
@@ -27,8 +28,5 @@ pub fn tao_waker(proxy: &EventLoopProxy<UserWindowEvent>, id: WindowId) -> std::
}
}
futures_util::task::waker(Arc::new(DomHandle {
id,
proxy: proxy.clone(),
}))
futures_util::task::waker(Arc::new(DomHandle { id, proxy }))
}
+173 -86
View File
@@ -1,98 +1,185 @@
use crate::desktop_context::EventData;
use crate::protocol;
use crate::{desktop_context::UserWindowEvent, Config};
use tao::event_loop::{EventLoopProxy, EventLoopWindowTarget};
pub use wry;
pub use wry::application as tao;
use wry::application::window::Window;
use wry::webview::{WebContext, WebView, WebViewBuilder};
use crate::{
app::SharedContext,
assets::AssetHandlerRegistry,
edits::EditQueue,
eval::DesktopEvalProvider,
ipc::{EventData, UserWindowEvent},
protocol::{self},
waker::tao_waker,
Config, DesktopContext, DesktopService,
};
use dioxus_core::VirtualDom;
use dioxus_html::prelude::EvalProvider;
use futures_util::{pin_mut, FutureExt};
use std::{rc::Rc, task::Waker};
use wry::{RequestAsyncResponder, WebContext, WebViewBuilder};
pub fn build(
cfg: &mut Config,
event_loop: &EventLoopWindowTarget<UserWindowEvent>,
proxy: EventLoopProxy<UserWindowEvent>,
) -> (WebView, WebContext) {
let builder = cfg.window.clone();
let window = builder.with_visible(false).build(event_loop).unwrap();
let file_handler = cfg.file_drop_handler.take();
let custom_head = cfg.custom_head.clone();
let index_file = cfg.custom_index.clone();
let root_name = cfg.root_name.clone();
pub struct WebviewInstance {
pub dom: VirtualDom,
pub desktop_context: DesktopContext,
pub waker: Waker,
// We assume that if the icon is None in cfg, then the user just didnt set it
if cfg.window.window.window_icon.is_none() {
window.set_window_icon(Some(
tao::window::Icon::from_rgba(
include_bytes!("./assets/default_icon.bin").to_vec(),
460,
460,
)
.expect("image parse failed"),
));
}
// Wry assumes the webcontext is alive for the lifetime of the webview.
// We need to keep the webcontext alive, otherwise the webview will crash
_web_context: WebContext,
}
let mut web_context = WebContext::new(cfg.data_dir.clone());
impl WebviewInstance {
pub fn new(mut cfg: Config, dom: VirtualDom, shared: Rc<SharedContext>) -> WebviewInstance {
let window = cfg.window.clone().build(&shared.target).unwrap();
let mut webview = WebViewBuilder::new(window)
.unwrap()
.with_transparent(cfg.window.window.transparent)
.with_url("dioxus://index.html/")
.unwrap()
.with_ipc_handler(move |window: &Window, payload: String| {
// TODO: allow users to specify their own menubars, again :/
#[cfg(not(any(target_os = "android", target_os = "ios")))]
crate::menubar::build_menu(&window, cfg.enable_default_menu_bar);
// We assume that if the icon is None in cfg, then the user just didnt set it
if cfg.window.window.window_icon.is_none() {
window.set_window_icon(Some(
tao::window::Icon::from_rgba(
include_bytes!("./assets/default_icon.bin").to_vec(),
460,
460,
)
.expect("image parse failed"),
));
}
let mut web_context = WebContext::new(cfg.data_dir.clone());
let edit_queue = EditQueue::default();
let asset_handlers = AssetHandlerRegistry::new(dom.runtime());
let headless = !cfg.window.window.visible;
// Rust :(
let window_id = window.id();
let file_handler = cfg.file_drop_handler.take();
let custom_head = cfg.custom_head.clone();
let index_file = cfg.custom_index.clone();
let root_name = cfg.root_name.clone();
let asset_handlers_ = asset_handlers.clone();
let edit_queue_ = edit_queue.clone();
let proxy_ = shared.proxy.clone();
let request_handler = move |request, responder: RequestAsyncResponder| {
// Try to serve the index file first
let index_bytes = protocol::index_request(
&request,
custom_head.clone(),
index_file.clone(),
&root_name,
headless,
);
// Otherwise, try to serve an asset, either from the user or the filesystem
match index_bytes {
Some(body) => responder.respond(body),
None => protocol::desktop_handler(
request,
asset_handlers_.clone(),
&edit_queue_,
responder,
),
}
};
let ipc_handler = move |payload: String| {
// defer the event to the main thread
if let Ok(message) = serde_json::from_str(&payload) {
_ = proxy.send_event(UserWindowEvent(EventData::Ipc(message), window.id()));
_ = proxy_.send_event(UserWindowEvent(EventData::Ipc(message), window_id));
}
})
.with_custom_protocol(String::from("dioxus"), move |r| {
protocol::desktop_handler(r, custom_head.clone(), index_file.clone(), &root_name)
})
.with_file_drop_handler(move |window, evet| {
file_handler
.as_ref()
.map(|handler| handler(window, evet))
.unwrap_or_default()
})
.with_web_context(&mut web_context);
};
#[cfg(windows)]
{
// Windows has a platform specific settings to disable the browser shortcut keys
use wry::webview::WebViewBuilderExtWindows;
webview = webview.with_browser_accelerator_keys(false);
let mut webview = WebViewBuilder::new(&window)
.with_transparent(cfg.window.window.transparent)
.with_url("dioxus://index.html/")
.unwrap()
.with_ipc_handler(ipc_handler)
.with_asynchronous_custom_protocol(String::from("dioxus"), request_handler)
.with_web_context(&mut web_context);
if let Some(handler) = file_handler {
webview = webview.with_file_drop_handler(move |evt| handler(window_id, evt))
}
// This was removed from wry, I'm not sure what replaced it
// #[cfg(windows)]
// {
// // Windows has a platform specific settings to disable the browser shortcut keys
// use wry::WebViewBuilderExtWindows;
// webview = webview.with_browser_accelerator_keys(false);
// }
if let Some(color) = cfg.background_color {
webview = webview.with_background_color(color);
}
for (name, handler) in cfg.protocols.drain(..) {
webview = webview.with_custom_protocol(name, handler);
}
const INITIALIZATION_SCRIPT: &str = r#"
if (document.addEventListener) {
document.addEventListener('contextmenu', function(e) {
e.preventDefault();
}, false);
} else {
document.attachEvent('oncontextmenu', function() {
window.event.returnValue = false;
});
}
"#;
if cfg.disable_context_menu {
// in release mode, we don't want to show the dev tool or reload menus
webview = webview.with_initialization_script(INITIALIZATION_SCRIPT)
} else {
// in debug, we are okay with the reload menu showing and dev tool
webview = webview.with_devtools(true);
}
let desktop_context = Rc::from(DesktopService::new(
webview.build().unwrap(),
window,
shared.clone(),
edit_queue,
asset_handlers,
));
// Provide the desktop context to the virtualdom
dom.base_scope().provide_context(desktop_context.clone());
// Also set up its eval provider
// It's important that we provide as dyn EvalProvider - using the concrete type has
// a different TypeId.
let provider: Rc<dyn EvalProvider> =
Rc::new(DesktopEvalProvider::new(desktop_context.clone()));
dom.base_scope().provide_context(provider);
WebviewInstance {
waker: tao_waker(shared.proxy.clone(), desktop_context.window.id()),
desktop_context,
dom,
_web_context: web_context,
}
}
if let Some(color) = cfg.background_color {
webview = webview.with_background_color(color);
pub fn poll_vdom(&mut self) {
let mut cx = std::task::Context::from_waker(&self.waker);
// Continously poll the virtualdom until it's pending
// Wait for work will return Ready when it has edits to be sent to the webview
// It will return Pending when it needs to be polled again - nothing is ready
loop {
{
let fut = self.dom.wait_for_work();
pin_mut!(fut);
match fut.poll_unpin(&mut cx) {
std::task::Poll::Ready(_) => {}
std::task::Poll::Pending => return,
}
}
self.desktop_context.send_edits(self.dom.render_immediate());
}
}
// These are commented out because wry is currently broken in wry
// let mut web_context = WebContext::new(cfg.data_dir.clone());
// .with_web_context(&mut web_context);
for (name, handler) in cfg.protocols.drain(..) {
webview = webview.with_custom_protocol(name, handler)
}
if cfg.disable_context_menu {
// in release mode, we don't want to show the dev tool or reload menus
webview = webview.with_initialization_script(
r#"
if (document.addEventListener) {
document.addEventListener('contextmenu', function(e) {
e.preventDefault();
}, false);
} else {
document.attachEvent('oncontextmenu', function() {
window.event.returnValue = false;
});
}
"#,
)
} else {
// in debug, we are okay with the reload menu showing and dev tool
webview = webview.with_devtools(true);
}
(webview.build().unwrap(), web_context)
}
@@ -37,7 +37,7 @@ fn app(cx: Scope) -> Element {
// todo: remove
let mut trimmed = format!("{event:?}");
trimmed.truncate(200);
rsx!(p { "{trimmed}" })
rsx!( p { "{trimmed}" } )
});
let log_event = move |event: Event| {
@@ -45,10 +45,7 @@ fn app(cx: Scope) -> Element {
};
cx.render(rsx! {
div {
width: "100%",
height: "100%",
flex_direction: "column",
div { width: "100%", height: "100%", flex_direction: "column",
div {
width: "80%",
height: "50%",
@@ -59,7 +56,7 @@ fn app(cx: Scope) -> Element {
onmousemove: move |event| log_event(Event::MouseMove(event.inner().clone())),
onclick: move |event| log_event(Event::MouseClick(event.inner().clone())),
ondblclick: move |event| log_event(Event::MouseDoubleClick(event.inner().clone())),
ondoubleclick: move |event| log_event(Event::MouseDoubleClick(event.inner().clone())),
onmousedown: move |event| log_event(Event::MouseDown(event.inner().clone())),
onmouseup: move |event| log_event(Event::MouseUp(event.inner().clone())),
@@ -73,13 +70,8 @@ fn app(cx: Scope) -> Element {
onfocusout: move |event| log_event(Event::FocusOut(event.inner().clone())),
"Hover, click, type or scroll to see the info down below"
},
div {
width: "80%",
height: "50%",
flex_direction: "column",
events_rendered,
},
},
}
div { width: "80%", height: "50%", flex_direction: "column", events_rendered }
}
})
}
+9 -10
View File
@@ -56,7 +56,6 @@ fn app(cx: Scope) -> Element {
width: "100%",
height: "100%",
flex_direction: "column",
div {
width: "100%",
height: "50%",
@@ -71,7 +70,7 @@ fn app(cx: Scope) -> Element {
onmouseenter: move |m| q1_color.set([get_brightness(m.inner()), 0, 0]),
onmousedown: move |m| q1_color.set([get_brightness(m.inner()), 0, 0]),
onmouseup: move |m| q1_color.set([get_brightness(m.inner()), 0, 0]),
onwheel: move |w| q1_color.set([q1_color[0] + (10.0*w.delta().strip_units().y) as i32, 0, 0]),
onwheel: move |w| q1_color.set([q1_color[0] + (10.0 * w.delta().strip_units().y) as i32, 0, 0]),
onmouseleave: move |_| q1_color.set([200; 3]),
onmousemove: update_data,
"click me"
@@ -85,7 +84,7 @@ fn app(cx: Scope) -> Element {
onmouseenter: move |m| q2_color.set([get_brightness(m.inner()); 3]),
onmousedown: move |m| q2_color.set([get_brightness(m.inner()); 3]),
onmouseup: move |m| q2_color.set([get_brightness(m.inner()); 3]),
onwheel: move |w| q2_color.set([q2_color[0] + (10.0*w.delta().strip_units().y) as i32;3]),
onwheel: move |w| q2_color.set([q2_color[0] + (10.0 * w.delta().strip_units().y) as i32; 3]),
onmouseleave: move |_| q2_color.set([200; 3]),
onmousemove: update_data,
"click me"
@@ -105,7 +104,7 @@ fn app(cx: Scope) -> Element {
onmouseenter: move |m| q3_color.set([0, get_brightness(m.inner()), 0]),
onmousedown: move |m| q3_color.set([0, get_brightness(m.inner()), 0]),
onmouseup: move |m| q3_color.set([0, get_brightness(m.inner()), 0]),
onwheel: move |w| q3_color.set([0, q3_color[1] + (10.0*w.delta().strip_units().y) as i32, 0]),
onwheel: move |w| q3_color.set([0, q3_color[1] + (10.0 * w.delta().strip_units().y) as i32, 0]),
onmouseleave: move |_| q3_color.set([200; 3]),
onmousemove: update_data,
"click me"
@@ -119,16 +118,16 @@ fn app(cx: Scope) -> Element {
onmouseenter: move |m| q4_color.set([0, 0, get_brightness(m.inner())]),
onmousedown: move |m| q4_color.set([0, 0, get_brightness(m.inner())]),
onmouseup: move |m| q4_color.set([0, 0, get_brightness(m.inner())]),
onwheel: move |w| q4_color.set([0, 0, q4_color[2] + (10.0*w.delta().strip_units().y) as i32]),
onwheel: move |w| q4_color.set([0, 0, q4_color[2] + (10.0 * w.delta().strip_units().y) as i32]),
onmouseleave: move |_| q4_color.set([200; 3]),
onmousemove: update_data,
"click me"
}
},
div {"Page coordinates: {page_coordinates}"},
div {"Element coordinates: {element_coordinates}"},
div {"Buttons: {buttons}"},
div {"Modifiers: {modifiers}"},
}
div { "Page coordinates: {page_coordinates}" }
div { "Element coordinates: {element_coordinates}" }
div { "Buttons: {buttons}" }
div { "Modifiers: {modifiers}" }
}
})
}
@@ -83,7 +83,7 @@ fn Grid(cx: Scope<GridProps>) -> Element {
let alpha = y as f32*100.0/size as f32 + counts.read()[x*size + y] as f32;
let key = format!("{}-{}", x, y);
rsx! {
Box{
Box {
x: x,
y: y,
alpha: 100.0,
+5 -5
View File
@@ -18,7 +18,7 @@ fn app(cx: Scope) -> Element {
justify_content: "center",
input {
oninput: |data| if &data.value == "good"{
oninput: |data| if &data.value()== "good"{
bg_green.set(true);
} else{
bg_green.set(false);
@@ -30,7 +30,7 @@ fn app(cx: Scope) -> Element {
checked: "true",
}
input {
oninput: |data| if &data.value == "hello world"{
oninput: |data| if &data.value()== "hello world"{
bg_green.set(true);
} else{
bg_green.set(false);
@@ -41,7 +41,7 @@ fn app(cx: Scope) -> Element {
}
input {
oninput: |data| {
if (data.value.parse::<f32>().unwrap() - 40.0).abs() < 5.0 {
if (data.value().parse::<f32>().unwrap() - 40.0).abs() < 5.0 {
bg_green.set(true);
} else{
bg_green.set(false);
@@ -55,7 +55,7 @@ fn app(cx: Scope) -> Element {
}
input {
oninput: |data| {
if data.value == "10"{
if data.value()== "10"{
bg_green.set(true);
} else{
bg_green.set(false);
@@ -68,7 +68,7 @@ fn app(cx: Scope) -> Element {
}
input {
oninput: |data| {
if data.value == "hello world"{
if data.value()== "hello world"{
bg_green.set(true);
} else{
bg_green.set(false);
+6 -6
View File
@@ -1,7 +1,6 @@
use std::{
any::Any,
fmt::{Display, Formatter},
rc::Rc,
};
use dioxus_core::{ElementId, Mutations, VirtualDom};
@@ -30,7 +29,7 @@ pub(crate) fn find_mount_events(mutations: &Mutations) -> Vec<ElementId> {
// We need to queue the mounted events to give rink time to rendere and resolve the layout of elements after they are created
pub(crate) fn create_mounted_events(
vdom: &VirtualDom,
events: &mut Vec<(ElementId, &'static str, Rc<dyn Any>, bool)>,
events: &mut Vec<(ElementId, &'static str, Box<dyn Any>, bool)>,
mount_events: impl Iterator<Item = (ElementId, NodeId)>,
) {
let query: Query = vdom
@@ -42,11 +41,12 @@ pub(crate) fn create_mounted_events(
query: query.clone(),
id: node_id,
};
events.push((id, "mounted", Rc::new(MountedData::new(element)), false));
events.push((id, "mounted", Box::new(MountedData::new(element)), false));
}
}
struct TuiElement {
#[derive(Clone)]
pub(crate) struct TuiElement {
query: Query,
id: NodeId,
}
@@ -82,8 +82,8 @@ impl RenderedElementBacking for TuiElement {
})
}
fn get_raw_element(&self) -> dioxus_html::MountedResult<&dyn std::any::Any> {
Ok(self)
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
+108
View File
@@ -0,0 +1,108 @@
use core::panic;
use dioxus_html::*;
use crate::element::TuiElement;
fn downcast(event: &PlatformEventData) -> plasmo::EventData {
event
.downcast::<plasmo::EventData>()
.expect("event should be of type EventData")
.clone()
}
pub(crate) struct SerializedHtmlEventConverter;
impl HtmlEventConverter for SerializedHtmlEventConverter {
fn convert_animation_data(&self, _: &PlatformEventData) -> AnimationData {
panic!("animation events not supported")
}
fn convert_clipboard_data(&self, _: &PlatformEventData) -> ClipboardData {
panic!("clipboard events not supported")
}
fn convert_composition_data(&self, _: &PlatformEventData) -> CompositionData {
panic!("composition events not supported")
}
fn convert_drag_data(&self, _: &PlatformEventData) -> DragData {
panic!("drag events not supported")
}
fn convert_focus_data(&self, event: &PlatformEventData) -> FocusData {
if let plasmo::EventData::Focus(event) = downcast(event) {
FocusData::new(event)
} else {
panic!("event should be of type Focus")
}
}
fn convert_form_data(&self, event: &PlatformEventData) -> FormData {
if let plasmo::EventData::Form(event) = downcast(event) {
FormData::new(event)
} else {
panic!("event should be of type Form")
}
}
fn convert_image_data(&self, _: &PlatformEventData) -> ImageData {
panic!("image events not supported")
}
fn convert_keyboard_data(&self, event: &PlatformEventData) -> KeyboardData {
if let plasmo::EventData::Keyboard(event) = downcast(event) {
KeyboardData::new(event)
} else {
panic!("event should be of type Keyboard")
}
}
fn convert_media_data(&self, _: &PlatformEventData) -> MediaData {
panic!("media events not supported")
}
fn convert_mounted_data(&self, event: &PlatformEventData) -> MountedData {
event.downcast::<TuiElement>().cloned().unwrap().into()
}
fn convert_mouse_data(&self, event: &PlatformEventData) -> MouseData {
if let plasmo::EventData::Mouse(event) = downcast(event) {
MouseData::new(event)
} else {
panic!("event should be of type Mouse")
}
}
fn convert_pointer_data(&self, _: &PlatformEventData) -> PointerData {
panic!("pointer events not supported")
}
fn convert_scroll_data(&self, _: &PlatformEventData) -> ScrollData {
panic!("scroll events not supported")
}
fn convert_selection_data(&self, _: &PlatformEventData) -> SelectionData {
panic!("selection events not supported")
}
fn convert_toggle_data(&self, _: &PlatformEventData) -> ToggleData {
panic!("toggle events not supported")
}
fn convert_touch_data(&self, _: &PlatformEventData) -> TouchData {
panic!("touch events not supported")
}
fn convert_transition_data(&self, _: &PlatformEventData) -> TransitionData {
panic!("transition events not supported")
}
fn convert_wheel_data(&self, event: &PlatformEventData) -> WheelData {
if let plasmo::EventData::Wheel(event) = downcast(event) {
WheelData::new(event)
} else {
panic!("event should be of type Wheel")
}
}
}
+11 -3
View File
@@ -3,6 +3,7 @@
#![doc(html_favicon_url = "https://avatars.githubusercontent.com/u/79236386")]
mod element;
mod events;
use std::{
any::Any,
@@ -12,6 +13,7 @@ use std::{
};
use dioxus_core::{Component, ElementId, VirtualDom};
use dioxus_html::PlatformEventData;
use dioxus_native_core::dioxus::{DioxusState, NodeImmutableDioxusExt};
use dioxus_native_core::prelude::*;
@@ -28,6 +30,8 @@ pub fn launch_cfg(app: Component<()>, cfg: Config) {
}
pub fn launch_cfg_with_props<Props: 'static>(app: Component<Props>, props: Props, cfg: Config) {
dioxus_html::set_event_converter(Box::new(events::SerializedHtmlEventConverter));
render(cfg, |rdom, taffy, event_tx| {
let dioxus_state = {
let mut rdom = rdom.write().unwrap();
@@ -85,7 +89,7 @@ struct DioxusRenderer {
vdom: VirtualDom,
dioxus_state: Rc<RwLock<DioxusState>>,
// Events that are queued up to be sent to the vdom next time the vdom is polled
queued_events: Vec<(ElementId, &'static str, Rc<dyn Any>, bool)>,
queued_events: Vec<(ElementId, &'static str, Box<dyn Any>, bool)>,
#[cfg(all(feature = "hot-reload", debug_assertions))]
hot_reload_rx: tokio::sync::mpsc::UnboundedReceiver<dioxus_hot_reload::HotReloadMsg>,
}
@@ -126,15 +130,19 @@ impl Driver for DioxusRenderer {
let id = { rdom.read().unwrap().get(id).unwrap().mounted_id() };
if let Some(id) = id {
let inner_value = value.deref().clone();
let boxed_event = Box::new(inner_value);
let platform_event = PlatformEventData::new(boxed_event);
self.vdom
.handle_event(event, inner_value.into_any(), id, bubbles);
.handle_event(event, Rc::new(platform_event), id, bubbles);
}
}
fn poll_async(&mut self) -> std::pin::Pin<Box<dyn futures::Future<Output = ()> + '_>> {
// Add any queued events
for (id, event, value, bubbles) in self.queued_events.drain(..) {
self.vdom.handle_event(event, value, id, bubbles);
let platform_event = PlatformEventData::new(value);
self.vdom
.handle_event(event, Rc::new(platform_event), id, bubbles);
}
#[cfg(all(feature = "hot-reload", debug_assertions))]
+15 -13
View File
@@ -63,7 +63,7 @@ fn key_down() {
onkeydown: move |evt| {
assert_eq!(evt.data.code(), Code::KeyA);
tui_ctx.quit();
},
}
}
})
}
@@ -95,9 +95,11 @@ fn mouse_down() {
width: "100%",
height: "100%",
onmousedown: move |evt| {
assert!(evt.data.held_buttons().contains(dioxus_html::input_data::MouseButton::Primary));
assert!(
evt.data.held_buttons().contains(dioxus_html::input_data::MouseButton::Primary)
);
tui_ctx.quit();
},
}
}
})
}
@@ -136,7 +138,7 @@ fn mouse_up() {
height: "100%",
onmouseup: move |_| {
tui_ctx.quit();
},
}
}
})
}
@@ -175,7 +177,7 @@ fn mouse_enter() {
height: "50%",
onmouseenter: move |_| {
tui_ctx.quit();
},
}
}
})
}
@@ -214,7 +216,7 @@ fn mouse_exit() {
height: "50%",
onmouseenter: move |_| {
tui_ctx.quit();
},
}
}
})
}
@@ -251,9 +253,9 @@ fn mouse_move() {
div {
width: "100%",
height: "100%",
onmousemove: move |_|{
onmousemove: move |_| {
tui_ctx.quit();
},
}
}
})
}
@@ -293,7 +295,7 @@ fn wheel() {
onwheel: move |evt| {
assert!(evt.data.delta().strip_units().y > 0.0);
tui_ctx.quit();
},
}
}
})
}
@@ -330,9 +332,9 @@ fn click() {
div {
width: "100%",
height: "100%",
onclick: move |_|{
onclick: move |_| {
tui_ctx.quit();
},
}
}
})
}
@@ -369,9 +371,9 @@ fn context_menu() {
div {
width: "100%",
height: "100%",
oncontextmenu: move |_|{
oncontextmenu: move |_| {
tui_ctx.quit();
},
}
}
})
}
-2
View File
@@ -36,8 +36,6 @@ criterion = "0.3.5"
thiserror = { workspace = true }
env_logger = "0.10.0"
tokio = { workspace = true, features = ["full"] }
# dioxus-edit-stream = { workspace = true }
[[bench]]
name = "jsframework"
Loaded 100 of 285 files, more files were not shown because too many files have changed in this diff. Show more