From 9c2e713dae8440ca368cda4d2d8b55f6ab8f737b Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Tue, 15 Aug 2023 09:30:43 -0500 Subject: [PATCH 01/83] fix recycling nodes in native core --- packages/native-core/src/dioxus.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/native-core/src/dioxus.rs b/packages/native-core/src/dioxus.rs index 3e9ff9ee0..e5042f756 100644 --- a/packages/native-core/src/dioxus.rs +++ b/packages/native-core/src/dioxus.rs @@ -57,6 +57,12 @@ impl DioxusState { node.insert(ElementIdComponent(element_id)); if self.node_id_mapping.len() <= element_id.0 { self.node_id_mapping.resize(element_id.0 + 1, None); + } else { + if let Some(mut node) = + self.node_id_mapping[element_id.0].and_then(|id| node.real_dom_mut().get_mut(id)) + { + node.remove(); + } } self.node_id_mapping[element_id.0] = Some(node_id); } From 0d773eac63cbf8b6d9ffe459d9d5ca81c96bb2fc Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Tue, 15 Aug 2023 10:37:27 -0500 Subject: [PATCH 02/83] fix clippy --- packages/native-core/src/dioxus.rs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/packages/native-core/src/dioxus.rs b/packages/native-core/src/dioxus.rs index e5042f756..c245de4fc 100644 --- a/packages/native-core/src/dioxus.rs +++ b/packages/native-core/src/dioxus.rs @@ -57,13 +57,12 @@ impl DioxusState { node.insert(ElementIdComponent(element_id)); if self.node_id_mapping.len() <= element_id.0 { self.node_id_mapping.resize(element_id.0 + 1, None); - } else { - if let Some(mut node) = - self.node_id_mapping[element_id.0].and_then(|id| node.real_dom_mut().get_mut(id)) - { - node.remove(); - } + } else if let Some(mut node) = + self.node_id_mapping[element_id.0].and_then(|id| node.real_dom_mut().get_mut(id)) + { + node.remove(); } + self.node_id_mapping[element_id.0] = Some(node_id); } From df85b25548cfff642af2b4ac4a4521b53027cb52 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Mon, 21 Aug 2023 14:23:02 -0500 Subject: [PATCH 03/83] Add debug information to borrows and ownership in signals --- packages/generational-box/Cargo.toml | 1 + packages/generational-box/src/lib.rs | 445 ++++++++++++++++++++++++--- packages/signals/src/effect.rs | 2 +- packages/signals/src/impls.rs | 33 +- packages/signals/src/rt.rs | 33 +- packages/signals/src/signal.rs | 58 +++- 6 files changed, 497 insertions(+), 75 deletions(-) diff --git a/packages/generational-box/Cargo.toml b/packages/generational-box/Cargo.toml index 6c5a5a841..cc0db9cec 100644 --- a/packages/generational-box/Cargo.toml +++ b/packages/generational-box/Cargo.toml @@ -15,3 +15,4 @@ rand = "0.8.5" [features] default = ["check_generation"] check_generation = [] +debug_borrows = [] diff --git a/packages/generational-box/src/lib.rs b/packages/generational-box/src/lib.rs index 60bd41419..7d64a1ed3 100644 --- a/packages/generational-box/src/lib.rs +++ b/packages/generational-box/src/lib.rs @@ -2,9 +2,13 @@ #![warn(missing_docs)] use std::{ + any::Any, cell::{Cell, Ref, RefCell, RefMut}, - fmt::Debug, + error::Error, + fmt::{Debug, Display}, marker::PhantomData, + ops::{Deref, DerefMut}, + panic::Location, rc::Rc, }; @@ -153,6 +157,8 @@ pub struct GenerationalBox { raw: MemoryLocation, #[cfg(any(debug_assertions, feature = "check_generation"))] generation: u32, + #[cfg(any(debug_assertions, feature = "check_generation"))] + created_at: &'static std::panic::Location<'static>, _marker: PhantomData, } @@ -161,7 +167,7 @@ impl Debug for GenerationalBox { #[cfg(any(debug_assertions, feature = "check_generation"))] f.write_fmt(format_args!( "{:?}@{:?}", - self.raw.data.as_ptr(), + self.raw.0.data.as_ptr(), self.generation ))?; #[cfg(not(any(debug_assertions, feature = "check_generation")))] @@ -175,7 +181,7 @@ impl GenerationalBox { fn validate(&self) -> bool { #[cfg(any(debug_assertions, feature = "check_generation"))] { - self.raw.generation.get() == self.generation + self.raw.0.generation.get() == self.generation } #[cfg(not(any(debug_assertions, feature = "check_generation")))] { @@ -184,43 +190,51 @@ impl GenerationalBox { } /// Try to read the value. Returns None if the value is no longer valid. - pub fn try_read(&self) -> Option> { - self.validate() - .then(|| { - Ref::filter_map(self.raw.data.borrow(), |any| { - any.as_ref()?.downcast_ref::() - }) - .ok() - }) - .flatten() + #[track_caller] + pub fn try_read(&self) -> Result, BorrowError> { + if !self.validate() { + return Err(BorrowError::Dropped(ValueDroppedError { + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + created_at: self.created_at, + })); + } + self.raw.try_borrow( + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + self.created_at, + ) } /// Read the value. Panics if the value is no longer valid. - pub fn read(&self) -> Ref<'_, T> { + #[track_caller] + pub fn read(&self) -> GenerationalRef<'_, T> { self.try_read().unwrap() } /// Try to write the value. Returns None if the value is no longer valid. - pub fn try_write(&self) -> Option> { - self.validate() - .then(|| { - RefMut::filter_map(self.raw.data.borrow_mut(), |any| { - any.as_mut()?.downcast_mut::() - }) - .ok() - }) - .flatten() + #[track_caller] + pub fn try_write(&self) -> Result, BorrowMutError> { + if !self.validate() { + return Err(BorrowMutError::Dropped(ValueDroppedError { + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + created_at: self.created_at, + })); + } + self.raw.try_borrow_mut( + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + self.created_at, + ) } /// Write the value. Panics if the value is no longer valid. - pub fn write(&self) -> RefMut<'_, T> { + #[track_caller] + pub fn write(&self) -> GenerationalRefMut<'_, T> { self.try_write().unwrap() } /// Set the value. Panics if the value is no longer valid. pub fn set(&self, value: T) { self.validate().then(|| { - *self.raw.data.borrow_mut() = Some(Box::new(value)); + *self.raw.0.data.borrow_mut() = Some(Box::new(value)); }); } @@ -228,7 +242,8 @@ impl GenerationalBox { pub fn ptr_eq(&self, other: &Self) -> bool { #[cfg(any(debug_assertions, feature = "check_generation"))] { - self.raw.data.as_ptr() == other.raw.data.as_ptr() && self.generation == other.generation + self.raw.0.data.as_ptr() == other.raw.0.data.as_ptr() + && self.generation == other.generation } #[cfg(not(any(debug_assertions, feature = "check_generation")))] { @@ -246,26 +261,38 @@ impl Clone for GenerationalBox { } #[derive(Clone, Copy)] -struct MemoryLocation { - data: &'static RefCell>>, +struct MemoryLocation(&'static MemoryLocationInner); + +struct MemoryLocationInner { + data: RefCell>>, #[cfg(any(debug_assertions, feature = "check_generation"))] - generation: &'static Cell, + generation: Cell, + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + borrowed_at: RefCell>>, + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + borrowed_mut_at: Cell>>, } impl MemoryLocation { #[allow(unused)] fn drop(&self) { - let old = self.data.borrow_mut().take(); + let old = self.0.data.borrow_mut().take(); #[cfg(any(debug_assertions, feature = "check_generation"))] if old.is_some() { drop(old); - let new_generation = self.generation.get() + 1; - self.generation.set(new_generation); + let new_generation = self.0.generation.get() + 1; + self.0.generation.set(new_generation); } } - fn replace(&mut self, value: T) -> GenerationalBox { - let mut inner_mut = self.data.borrow_mut(); + fn replace_with_caller( + &mut self, + value: T, + #[cfg(any(debug_assertions, feature = "check_generation"))] caller: &'static Location< + 'static, + >, + ) -> GenerationalBox { + let mut inner_mut = self.0.data.borrow_mut(); let raw = Box::new(value); let old = inner_mut.replace(raw); @@ -273,10 +300,318 @@ impl MemoryLocation { GenerationalBox { raw: *self, #[cfg(any(debug_assertions, feature = "check_generation"))] - generation: self.generation.get(), + generation: self.0.generation.get(), + #[cfg(any(debug_assertions, feature = "check_generation"))] + created_at: caller, _marker: PhantomData, } } + + #[track_caller] + fn try_borrow( + &self, + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + created_at: &'static std::panic::Location<'static>, + ) -> Result, BorrowError> { + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + self.0 + .borrowed_at + .borrow_mut() + .push(std::panic::Location::caller()); + match self.0.data.try_borrow() { + Ok(borrow) => match Ref::filter_map(borrow, |any| any.as_ref()?.downcast_ref::()) { + Ok(reference) => Ok(GenerationalRef { + inner: reference, + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + borrow: GenerationalRefBorrowInfo { + borrowed_at: std::panic::Location::caller(), + borrowed_from: self.0, + }, + }), + Err(_) => Err(BorrowError::Dropped(ValueDroppedError { + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + created_at, + })), + }, + Err(_) => Err(BorrowError::AlreadyBorrowedMut(AlreadyBorrowedMutError { + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + borrowed_mut_at: self.0.borrowed_mut_at.get().unwrap(), + })), + } + } + + #[track_caller] + fn try_borrow_mut( + &self, + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + created_at: &'static std::panic::Location<'static>, + ) -> Result, BorrowMutError> { + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + { + self.0 + .borrowed_mut_at + .set(Some(std::panic::Location::caller())); + } + match self.0.data.try_borrow_mut() { + Ok(borrow_mut) => { + match RefMut::filter_map(borrow_mut, |any| any.as_mut()?.downcast_mut::()) { + Ok(reference) => Ok(GenerationalRefMut { + inner: reference, + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + borrow: GenerationalRefMutBorrowInfo { + borrowed_from: self.0, + }, + }), + Err(_) => Err(BorrowMutError::Dropped(ValueDroppedError { + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + created_at, + })), + } + } + Err(_) => Err(BorrowMutError::AlreadyBorrowed(AlreadyBorrowedError { + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + borrowed_at: self.0.borrowed_at.borrow().clone(), + })), + } + } +} + +#[derive(Debug, Clone)] +/// An error that can occur when trying to borrow a value. +pub enum BorrowError { + /// The value was dropped. + Dropped(ValueDroppedError), + /// The value was already borrowed mutably. + AlreadyBorrowedMut(AlreadyBorrowedMutError), +} + +impl Display for BorrowError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + BorrowError::Dropped(error) => Display::fmt(error, f), + BorrowError::AlreadyBorrowedMut(error) => Display::fmt(error, f), + } + } +} + +impl Error for BorrowError {} + +#[derive(Debug, Clone)] +/// An error that can occur when trying to borrow a value mutably. +pub enum BorrowMutError { + /// The value was dropped. + Dropped(ValueDroppedError), + /// The value was already borrowed. + AlreadyBorrowed(AlreadyBorrowedError), + /// The value was already borrowed mutably. + AlreadyBorrowedMut(AlreadyBorrowedMutError), +} + +impl Display for BorrowMutError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + BorrowMutError::Dropped(error) => Display::fmt(error, f), + BorrowMutError::AlreadyBorrowedMut(error) => Display::fmt(error, f), + BorrowMutError::AlreadyBorrowed(error) => Display::fmt(error, f), + } + } +} + +impl Error for BorrowMutError {} + +/// An error that can occur when trying to use a value that has been dropped. +#[derive(Debug, Copy, Clone)] +pub struct ValueDroppedError { + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + created_at: &'static std::panic::Location<'static>, +} + +impl Display for ValueDroppedError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Failed to borrow because the value was dropped.")?; + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + f.write_fmt(format_args!("created_at: {}", self.created_at))?; + Ok(()) + } +} + +impl std::error::Error for ValueDroppedError {} + +/// An error that can occur when trying to borrow a value that has already been borrowed mutably. +#[derive(Debug, Copy, Clone)] +pub struct AlreadyBorrowedMutError { + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + borrowed_mut_at: &'static std::panic::Location<'static>, +} + +impl Display for AlreadyBorrowedMutError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Failed to borrow because the value was already borrowed mutably.")?; + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + f.write_fmt(format_args!("borrowed_mut_at: {}", self.borrowed_mut_at))?; + Ok(()) + } +} + +impl std::error::Error for AlreadyBorrowedMutError {} + +/// An error that can occur when trying to borrow a value mutably that has already been borrowed immutably. +#[derive(Debug, Clone)] +pub struct AlreadyBorrowedError { + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + borrowed_at: Vec<&'static std::panic::Location<'static>>, +} + +impl Display for AlreadyBorrowedError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Failed to borrow mutably because the value was already borrowed immutably.")?; + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + f.write_str("borrowed_at:")?; + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + for location in self.borrowed_at.iter() { + f.write_fmt(format_args!("\t{}", location))?; + } + Ok(()) + } +} + +impl std::error::Error for AlreadyBorrowedError {} + +/// A reference to a value in a generational box. +pub struct GenerationalRef<'a, T: 'static> { + inner: Ref<'a, T>, + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + borrow: GenerationalRefBorrowInfo, +} + +impl<'a, T: 'static> GenerationalRef<'a, T> { + /// Map one ref type to another. + pub fn map(orig: GenerationalRef<'a, T>, f: F) -> GenerationalRef<'a, U> + where + F: FnOnce(&T) -> &U, + { + GenerationalRef { + inner: Ref::map(orig.inner, f), + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + borrow: GenerationalRefBorrowInfo { + borrowed_at: orig.borrow.borrowed_at, + borrowed_from: orig.borrow.borrowed_from, + }, + } + } + + /// Filter one ref type to another. + pub fn filter_map(orig: GenerationalRef<'a, T>, f: F) -> Option> + where + F: FnOnce(&T) -> Option<&U>, + { + let Self { + inner, + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + borrow, + } = orig; + Ref::filter_map(inner, f).ok().map(|inner| GenerationalRef { + inner, + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + borrow: GenerationalRefBorrowInfo { + borrowed_at: borrow.borrowed_at, + borrowed_from: borrow.borrowed_from, + }, + }) + } +} + +impl<'a, T: 'static> Deref for GenerationalRef<'a, T> { + type Target = T; + + fn deref(&self) -> &Self::Target { + self.inner.deref() + } +} + +#[cfg(any(debug_assertions, feature = "debug_borrows"))] +struct GenerationalRefBorrowInfo { + borrowed_at: &'static std::panic::Location<'static>, + borrowed_from: &'static MemoryLocationInner, +} + +#[cfg(any(debug_assertions, feature = "debug_borrows"))] +impl Drop for GenerationalRefBorrowInfo { + fn drop(&mut self) { + self.borrowed_from + .borrowed_at + .borrow_mut() + .retain(|location| std::ptr::eq(*location, self.borrowed_at as *const _)); + } +} + +/// A mutable reference to a value in a generational box. +pub struct GenerationalRefMut<'a, T: 'static> { + inner: RefMut<'a, T>, + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + borrow: GenerationalRefMutBorrowInfo, +} + +impl<'a, T: 'static> GenerationalRefMut<'a, T> { + /// Map one ref type to another. + pub fn map(orig: GenerationalRefMut<'a, T>, f: F) -> GenerationalRefMut<'a, U> + where + F: FnOnce(&mut T) -> &mut U, + { + GenerationalRefMut { + inner: RefMut::map(orig.inner, f), + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + borrow: orig.borrow, + } + } + + /// Filter one ref type to another. + pub fn filter_map( + orig: GenerationalRefMut<'a, T>, + f: F, + ) -> Option> + where + F: FnOnce(&mut T) -> Option<&mut U>, + { + let Self { + inner, + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + borrow, + } = orig; + RefMut::filter_map(inner, f) + .ok() + .map(|inner| GenerationalRefMut { + inner, + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + borrow, + }) + } +} + +impl<'a, T: 'static> Deref for GenerationalRefMut<'a, T> { + type Target = T; + + fn deref(&self) -> &Self::Target { + self.inner.deref() + } +} + +impl<'a, T: 'static> DerefMut for GenerationalRefMut<'a, T> { + fn deref_mut(&mut self) -> &mut Self::Target { + self.inner.deref_mut() + } +} + +#[cfg(any(debug_assertions, feature = "debug_borrows"))] +struct GenerationalRefMutBorrowInfo { + borrowed_from: &'static MemoryLocationInner, +} + +#[cfg(any(debug_assertions, feature = "debug_borrows"))] +impl Drop for GenerationalRefMutBorrowInfo { + fn drop(&mut self) { + self.borrowed_from.borrowed_mut_at.take(); + } } /// Handles recycling generational boxes that have been dropped. Your application should have one store or one store per thread. @@ -305,12 +640,16 @@ impl Store { if let Some(location) = self.recycled.borrow_mut().pop() { location } else { - let data: &'static RefCell<_> = self.bump.alloc(RefCell::new(None)); - MemoryLocation { - data, + let data: &'static MemoryLocationInner = self.bump.alloc(MemoryLocationInner { + data: RefCell::new(None), #[cfg(any(debug_assertions, feature = "check_generation"))] - generation: self.bump.alloc(Cell::new(0)), - } + generation: Cell::new(0), + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + borrowed_at: Default::default(), + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + borrowed_mut_at: Default::default(), + }); + MemoryLocation(data) } } @@ -331,9 +670,31 @@ pub struct Owner { impl Owner { /// Insert a value into the store. The value will be dropped when the owner is dropped. + #[track_caller] pub fn insert(&self, value: T) -> GenerationalBox { let mut location = self.store.claim(); - let key = location.replace(value); + let key = location.replace_with_caller( + value, + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + std::panic::Location::caller(), + ); + self.owned.borrow_mut().push(location); + key + } + + /// Insert a value into the store with a specific location blamed for creating the value. The value will be dropped when the owner is dropped. + pub fn insert_with_caller( + &self, + value: T, + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + caller: &'static std::panic::Location<'static>, + ) -> GenerationalBox { + let mut location = self.store.claim(); + let key = location.replace_with_caller( + value, + #[cfg(any(debug_assertions, feature = "debug_borrows"))] + caller, + ); self.owned.borrow_mut().push(location); key } @@ -344,7 +705,9 @@ impl Owner { GenerationalBox { raw: location, #[cfg(any(debug_assertions, feature = "check_generation"))] - generation: location.generation.get(), + generation: location.0.generation.get(), + #[cfg(any(debug_assertions, feature = "check_generation"))] + created_at: std::panic::Location::caller(), _marker: PhantomData, } } diff --git a/packages/signals/src/effect.rs b/packages/signals/src/effect.rs index 0685938a0..0110ce4d1 100644 --- a/packages/signals/src/effect.rs +++ b/packages/signals/src/effect.rs @@ -83,7 +83,7 @@ impl Effect { /// Run the effect callback immediately. Returns `true` if the effect was run. Returns `false` is the effect is dead. pub fn try_run(&self) { - if let Some(mut callback) = self.callback.try_write() { + if let Ok(mut callback) = self.callback.try_write() { { get_effect_stack().effects.borrow_mut().push(*self); } diff --git a/packages/signals/src/impls.rs b/packages/signals/src/impls.rs index 6427c2e2b..8029ac312 100644 --- a/packages/signals/src/impls.rs +++ b/packages/signals/src/impls.rs @@ -1,7 +1,7 @@ use crate::rt::CopyValue; use crate::signal::{ReadOnlySignal, Signal, Write}; - -use std::cell::{Ref, RefMut}; +use generational_box::GenerationalRef; +use generational_box::GenerationalRefMut; use std::{ fmt::{Debug, Display}, @@ -38,8 +38,8 @@ macro_rules! read_impls { impl $ty> { /// Read a value from the inner vector. - pub fn get(&self, index: usize) -> Option> { - Ref::filter_map(self.read(), |v| v.get(index)).ok() + pub fn get(&self, index: usize) -> Option> { + GenerationalRef::filter_map(self.read(), |v| v.get(index)) } } @@ -52,9 +52,9 @@ macro_rules! read_impls { self.with(|v| v.clone()).unwrap() } - /// Attemps to read the inner value of the Option. - pub fn as_ref(&self) -> Option> { - Ref::filter_map(self.read(), |v| v.as_ref()).ok() + /// Attempts to read the inner value of the Option. + pub fn as_ref(&self) -> Option> { + GenerationalRef::filter_map(self.read(), |v| v.as_ref()) } } }; @@ -182,19 +182,22 @@ macro_rules! write_impls { } /// Gets the value out of the Option, or inserts the given value if the Option is empty. - pub fn get_or_insert(&self, default: T) -> Ref<'_, T> { + pub fn get_or_insert(&self, default: T) -> GenerationalRef<'_, T> { self.get_or_insert_with(|| default) } /// Gets the value out of the Option, or inserts the value returned by the given function if the Option is empty. - pub fn get_or_insert_with(&self, default: impl FnOnce() -> T) -> Ref<'_, T> { + pub fn get_or_insert_with( + &self, + default: impl FnOnce() -> T, + ) -> GenerationalRef<'_, T> { let borrow = self.read(); if borrow.is_none() { drop(borrow); self.with_mut(|v| *v = Some(default())); - Ref::map(self.read(), |v| v.as_ref().unwrap()) + GenerationalRef::map(self.read(), |v| v.as_ref().unwrap()) } else { - Ref::map(borrow, |v| v.as_ref().unwrap()) + GenerationalRef::map(borrow, |v| v.as_ref().unwrap()) } } } @@ -238,15 +241,15 @@ impl IntoIterator for CopyValue> { impl CopyValue> { /// Write to an element in the inner vector. - pub fn get_mut(&self, index: usize) -> Option> { - RefMut::filter_map(self.write(), |v| v.get_mut(index)).ok() + pub fn get_mut(&self, index: usize) -> Option> { + GenerationalRefMut::filter_map(self.write(), |v| v.get_mut(index)) } } impl CopyValue> { /// Deref the inner value mutably. - pub fn as_mut(&self) -> Option> { - RefMut::filter_map(self.write(), |v| v.as_mut()).ok() + pub fn as_mut(&self) -> Option> { + GenerationalRefMut::filter_map(self.write(), |v| v.as_mut()) } } diff --git a/packages/signals/src/rt.rs b/packages/signals/src/rt.rs index 7322d43b4..acf598217 100644 --- a/packages/signals/src/rt.rs +++ b/packages/signals/src/rt.rs @@ -1,14 +1,15 @@ -use std::cell::{Ref, RefMut}; - +use std::panic::Location; use std::rc::Rc; use dioxus_core::prelude::{ - consume_context, consume_context_from_scope, current_scope_id, provide_context, + consume_context, consume_context_from_scope, current_scope_id, has_context, provide_context, provide_context_to_scope, provide_root_context, }; use dioxus_core::ScopeId; -use generational_box::{GenerationalBox, Owner, Store}; +use generational_box::{ + BorrowError, BorrowMutError, GenerationalBox, GenerationalRef, GenerationalRefMut, Owner, Store, +}; fn current_store() -> Store { match consume_context() { @@ -21,7 +22,7 @@ fn current_store() -> Store { } fn current_owner() -> Rc { - match consume_context() { + match has_context() { Some(rt) => rt, None => { let owner = Rc::new(current_store().owner()); @@ -74,6 +75,7 @@ impl CopyValue { /// Create a new CopyValue. The value will be stored in the current component. /// /// Once the component this value is created in is dropped, the value will be dropped. + #[track_caller] pub fn new(value: T) -> Self { let owner = current_owner(); @@ -83,6 +85,15 @@ impl CopyValue { } } + pub(crate) fn new_with_caller(value: T, caller: &'static Location<'static>) -> Self { + let owner = current_owner(); + + Self { + value: owner.insert_with_caller(value, caller), + origin_scope: current_scope_id().expect("in a virtual dom"), + } + } + /// Create a new CopyValue. The value will be stored in the given scope. When the specified scope is dropped, the value will be dropped. pub fn new_in_scope(value: T, scope: ScopeId) -> Self { let owner = owner_in_scope(scope); @@ -108,22 +119,26 @@ impl CopyValue { } /// Try to read the value. If the value has been dropped, this will return None. - pub fn try_read(&self) -> Option> { + #[track_caller] + pub fn try_read(&self) -> Result, BorrowError> { self.value.try_read() } /// Read the value. If the value has been dropped, this will panic. - pub fn read(&self) -> Ref<'_, T> { + #[track_caller] + pub fn read(&self) -> GenerationalRef<'_, T> { self.value.read() } /// Try to write the value. If the value has been dropped, this will return None. - pub fn try_write(&self) -> Option> { + #[track_caller] + pub fn try_write(&self) -> Result, BorrowMutError> { self.value.try_write() } /// Write the value. If the value has been dropped, this will panic. - pub fn write(&self) -> RefMut<'_, T> { + #[track_caller] + pub fn write(&self) -> GenerationalRefMut<'_, T> { self.value.write() } diff --git a/packages/signals/src/signal.rs b/packages/signals/src/signal.rs index a5599a1ce..1656f559e 100644 --- a/packages/signals/src/signal.rs +++ b/packages/signals/src/signal.rs @@ -1,6 +1,7 @@ use std::{ - cell::{Ref, RefCell, RefMut}, + cell::RefCell, ops::{Deref, DerefMut}, + panic::Location, rc::Rc, sync::Arc, }; @@ -9,6 +10,7 @@ use dioxus_core::{ prelude::{current_scope_id, has_context, provide_context, schedule_update_any}, ScopeId, ScopeState, }; +use generational_box::{GenerationalRef, GenerationalRefMut}; use crate::{CopyValue, Effect}; @@ -43,8 +45,18 @@ use crate::{CopyValue, Effect}; /// } /// } /// ``` +#[track_caller] pub fn use_signal(cx: &ScopeState, f: impl FnOnce() -> T) -> Signal { - *cx.use_hook(|| Signal::new(f())) + #[cfg(debug_assertions)] + let caller = Location::caller(); + + *cx.use_hook(|| { + Signal::new_with_caller( + f(), + #[cfg(debug_assertions)] + caller, + ) + }) } #[derive(Clone)] @@ -134,6 +146,7 @@ impl<'de, T: serde::Deserialize<'de> + 'static> serde::Deserialize<'de> for Sign impl Signal { /// Creates a new Signal. Signals are a Copy state management solution with automatic dependency tracking. + #[track_caller] pub fn new(value: T) -> Self { Self { inner: CopyValue::new(SignalData { @@ -145,6 +158,25 @@ impl Signal { } } + /// Creates a new Signal. Signals are a Copy state management solution with automatic dependency tracking. + fn new_with_caller( + value: T, + #[cfg(debug_assertions)] caller: &'static Location<'static>, + ) -> Self { + Self { + inner: CopyValue::new_with_caller( + SignalData { + subscribers: Default::default(), + effect_subscribers: Default::default(), + update_any: schedule_update_any().expect("in a virtual dom"), + value, + }, + #[cfg(debug_assertions)] + caller, + ), + } + } + /// Get the scope the signal was created in. pub fn origin_scope(&self) -> ScopeId { self.inner.origin_scope() @@ -152,7 +184,8 @@ impl Signal { /// Get the current value of the signal. This will subscribe the current scope to the signal. /// If the signal has been dropped, this will panic. - pub fn read(&self) -> Ref { + #[track_caller] + pub fn read(&self) -> GenerationalRef { let inner = self.inner.read(); if let Some(effect) = Effect::current() { let mut effect_subscribers = inner.effect_subscribers.borrow_mut(); @@ -176,14 +209,15 @@ impl Signal { } } } - Ref::map(inner, |v| &v.value) + GenerationalRef::map(inner, |v| &v.value) } /// Get a mutable reference to the signal's value. /// If the signal has been dropped, this will panic. + #[track_caller] pub fn write(&self) -> Write<'_, T> { let inner = self.inner.write(); - let borrow = RefMut::map(inner, |v| &mut v.value); + let borrow = GenerationalRefMut::map(inner, |v| &mut v.value); Write { write: borrow, signal: SignalSubscriberDrop { signal: *self }, @@ -219,12 +253,14 @@ impl Signal { } /// Set the value of the signal. This will trigger an update on all subscribers. + #[track_caller] pub fn set(&self, value: T) { *self.write() = value; } /// Run a closure with a reference to the signal's value. /// If the signal has been dropped, this will panic. + #[track_caller] pub fn with(&self, f: impl FnOnce(&T) -> O) -> O { let write = self.read(); f(&*write) @@ -232,6 +268,7 @@ impl Signal { /// Run a closure with a mutable reference to the signal's value. /// If the signal has been dropped, this will panic. + #[track_caller] pub fn with_mut(&self, f: impl FnOnce(&mut T) -> O) -> O { let mut write = self.write(); f(&mut *write) @@ -241,6 +278,7 @@ impl Signal { impl Signal { /// Get the current value of the signal. This will subscribe the current scope to the signal. /// If the signal has been dropped, this will panic. + #[track_caller] pub fn value(&self) -> T { self.read().clone() } @@ -264,7 +302,7 @@ impl Drop for SignalSubscriberDrop { /// A mutable reference to a signal's value. pub struct Write<'a, T: 'static, I: 'static = T> { - write: RefMut<'a, T>, + write: GenerationalRefMut<'a, T>, signal: SignalSubscriberDrop, } @@ -273,7 +311,7 @@ impl<'a, T: 'static, I: 'static> Write<'a, T, I> { pub fn map(myself: Self, f: impl FnOnce(&mut T) -> &mut O) -> Write<'a, O, I> { let Self { write, signal } = myself; Write { - write: RefMut::map(write, f), + write: GenerationalRefMut::map(write, f), signal, } } @@ -284,7 +322,7 @@ impl<'a, T: 'static, I: 'static> Write<'a, T, I> { f: impl FnOnce(&mut T) -> Option<&mut O>, ) -> Option> { let Self { write, signal } = myself; - let write = RefMut::filter_map(write, f).ok(); + let write = GenerationalRefMut::filter_map(write, f); write.map(|write| Write { write, signal }) } } @@ -320,11 +358,13 @@ impl ReadOnlySignal { } /// Get the current value of the signal. This will subscribe the current scope to the signal. - pub fn read(&self) -> Ref { + #[track_caller] + pub fn read(&self) -> GenerationalRef { self.inner.read() } /// Run a closure with a reference to the signal's value. + #[track_caller] pub fn with(&self, f: impl FnOnce(&T) -> O) -> O { self.inner.with(f) } From f09a2e2280f74a9ac4e50d298e6f665bad1f8ea2 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Mon, 21 Aug 2023 14:28:45 -0500 Subject: [PATCH 04/83] fix release builds --- packages/generational-box/Cargo.toml | 1 + packages/generational-box/src/lib.rs | 26 ++++++++++++-------------- packages/signals/src/rt.rs | 12 +++++++++--- packages/signals/src/signal.rs | 5 ++--- 4 files changed, 24 insertions(+), 20 deletions(-) diff --git a/packages/generational-box/Cargo.toml b/packages/generational-box/Cargo.toml index cc0db9cec..7151ec103 100644 --- a/packages/generational-box/Cargo.toml +++ b/packages/generational-box/Cargo.toml @@ -16,3 +16,4 @@ rand = "0.8.5" default = ["check_generation"] check_generation = [] debug_borrows = [] +debug_ownership = [] diff --git a/packages/generational-box/src/lib.rs b/packages/generational-box/src/lib.rs index 7d64a1ed3..1f8cbbe11 100644 --- a/packages/generational-box/src/lib.rs +++ b/packages/generational-box/src/lib.rs @@ -8,7 +8,6 @@ use std::{ fmt::{Debug, Display}, marker::PhantomData, ops::{Deref, DerefMut}, - panic::Location, rc::Rc, }; @@ -157,7 +156,7 @@ pub struct GenerationalBox { raw: MemoryLocation, #[cfg(any(debug_assertions, feature = "check_generation"))] generation: u32, - #[cfg(any(debug_assertions, feature = "check_generation"))] + #[cfg(any(debug_assertions, feature = "debug_ownership"))] created_at: &'static std::panic::Location<'static>, _marker: PhantomData, } @@ -288,9 +287,8 @@ impl MemoryLocation { fn replace_with_caller( &mut self, value: T, - #[cfg(any(debug_assertions, feature = "check_generation"))] caller: &'static Location< - 'static, - >, + #[cfg(any(debug_assertions, feature = "debug_ownership"))] + caller: &'static std::panic::Location<'static>, ) -> GenerationalBox { let mut inner_mut = self.0.data.borrow_mut(); @@ -301,7 +299,7 @@ impl MemoryLocation { raw: *self, #[cfg(any(debug_assertions, feature = "check_generation"))] generation: self.0.generation.get(), - #[cfg(any(debug_assertions, feature = "check_generation"))] + #[cfg(any(debug_assertions, feature = "debug_ownership"))] created_at: caller, _marker: PhantomData, } @@ -310,7 +308,7 @@ impl MemoryLocation { #[track_caller] fn try_borrow( &self, - #[cfg(any(debug_assertions, feature = "debug_borrows"))] + #[cfg(any(debug_assertions, feature = "debug_ownership"))] created_at: &'static std::panic::Location<'static>, ) -> Result, BorrowError> { #[cfg(any(debug_assertions, feature = "debug_borrows"))] @@ -329,7 +327,7 @@ impl MemoryLocation { }, }), Err(_) => Err(BorrowError::Dropped(ValueDroppedError { - #[cfg(any(debug_assertions, feature = "debug_borrows"))] + #[cfg(any(debug_assertions, feature = "debug_ownership"))] created_at, })), }, @@ -343,7 +341,7 @@ impl MemoryLocation { #[track_caller] fn try_borrow_mut( &self, - #[cfg(any(debug_assertions, feature = "debug_borrows"))] + #[cfg(any(debug_assertions, feature = "debug_ownership"))] created_at: &'static std::panic::Location<'static>, ) -> Result, BorrowMutError> { #[cfg(any(debug_assertions, feature = "debug_borrows"))] @@ -363,7 +361,7 @@ impl MemoryLocation { }, }), Err(_) => Err(BorrowMutError::Dropped(ValueDroppedError { - #[cfg(any(debug_assertions, feature = "debug_borrows"))] + #[cfg(any(debug_assertions, feature = "debug_ownership"))] created_at, })), } @@ -422,14 +420,14 @@ impl Error for BorrowMutError {} /// An error that can occur when trying to use a value that has been dropped. #[derive(Debug, Copy, Clone)] pub struct ValueDroppedError { - #[cfg(any(debug_assertions, feature = "debug_borrows"))] + #[cfg(any(debug_assertions, feature = "debug_ownership"))] created_at: &'static std::panic::Location<'static>, } impl Display for ValueDroppedError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("Failed to borrow because the value was dropped.")?; - #[cfg(any(debug_assertions, feature = "debug_borrows"))] + #[cfg(any(debug_assertions, feature = "debug_ownership"))] f.write_fmt(format_args!("created_at: {}", self.created_at))?; Ok(()) } @@ -686,7 +684,7 @@ impl Owner { pub fn insert_with_caller( &self, value: T, - #[cfg(any(debug_assertions, feature = "debug_borrows"))] + #[cfg(any(debug_assertions, feature = "debug_ownership"))] caller: &'static std::panic::Location<'static>, ) -> GenerationalBox { let mut location = self.store.claim(); @@ -706,7 +704,7 @@ impl Owner { raw: location, #[cfg(any(debug_assertions, feature = "check_generation"))] generation: location.0.generation.get(), - #[cfg(any(debug_assertions, feature = "check_generation"))] + #[cfg(any(debug_assertions, feature = "debug_ownership"))] created_at: std::panic::Location::caller(), _marker: PhantomData, } diff --git a/packages/signals/src/rt.rs b/packages/signals/src/rt.rs index acf598217..aee3b0858 100644 --- a/packages/signals/src/rt.rs +++ b/packages/signals/src/rt.rs @@ -1,4 +1,3 @@ -use std::panic::Location; use std::rc::Rc; use dioxus_core::prelude::{ @@ -85,11 +84,18 @@ impl CopyValue { } } - pub(crate) fn new_with_caller(value: T, caller: &'static Location<'static>) -> Self { + pub(crate) fn new_with_caller( + value: T, + #[cfg(debug_assertions)] caller: &'static std::panic::Location<'static>, + ) -> Self { let owner = current_owner(); Self { - value: owner.insert_with_caller(value, caller), + value: owner.insert_with_caller( + value, + #[cfg(debug_assertions)] + caller, + ), origin_scope: current_scope_id().expect("in a virtual dom"), } } diff --git a/packages/signals/src/signal.rs b/packages/signals/src/signal.rs index 1656f559e..70a809e85 100644 --- a/packages/signals/src/signal.rs +++ b/packages/signals/src/signal.rs @@ -1,7 +1,6 @@ use std::{ cell::RefCell, ops::{Deref, DerefMut}, - panic::Location, rc::Rc, sync::Arc, }; @@ -48,7 +47,7 @@ use crate::{CopyValue, Effect}; #[track_caller] pub fn use_signal(cx: &ScopeState, f: impl FnOnce() -> T) -> Signal { #[cfg(debug_assertions)] - let caller = Location::caller(); + let caller = std::panic::Location::caller(); *cx.use_hook(|| { Signal::new_with_caller( @@ -161,7 +160,7 @@ impl Signal { /// Creates a new Signal. Signals are a Copy state management solution with automatic dependency tracking. fn new_with_caller( value: T, - #[cfg(debug_assertions)] caller: &'static Location<'static>, + #[cfg(debug_assertions)] caller: &'static std::panic::Location<'static>, ) -> Self { Self { inner: CopyValue::new_with_caller( From 18f8daf0bdc30a6eb71ab7e91863442a13d47ca6 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Mon, 21 Aug 2023 15:00:31 -0500 Subject: [PATCH 05/83] fix generational box tests --- packages/generational-box/README.md | 2 ++ packages/generational-box/src/lib.rs | 13 ++++++++----- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/packages/generational-box/README.md b/packages/generational-box/README.md index 5ab7926ba..f8d4885b8 100644 --- a/packages/generational-box/README.md +++ b/packages/generational-box/README.md @@ -11,6 +11,8 @@ Three main types manage state in Generational Box: Example: ```rust +use generational_box::Store; + // Create a store for this thread let store = Store::default(); diff --git a/packages/generational-box/src/lib.rs b/packages/generational-box/src/lib.rs index 1f8cbbe11..84a81769d 100644 --- a/packages/generational-box/src/lib.rs +++ b/packages/generational-box/src/lib.rs @@ -32,12 +32,12 @@ fn reused() { let first_ptr; { let owner = store.owner(); - first_ptr = owner.insert(1).raw.data.as_ptr(); + first_ptr = owner.insert(1).raw.0.data.as_ptr(); drop(owner); } { let owner = store.owner(); - let second_ptr = owner.insert(1234).raw.data.as_ptr(); + let second_ptr = owner.insert(1234).raw.0.data.as_ptr(); assert_eq!(first_ptr, second_ptr); drop(owner); } @@ -56,7 +56,10 @@ fn leaking_is_ok() { // don't drop the owner std::mem::forget(owner); } - assert_eq!(key.try_read().as_deref(), Some(&"hello world".to_string())); + assert_eq!( + key.try_read().as_deref().unwrap(), + &"hello world".to_string() + ); } #[test] @@ -71,7 +74,7 @@ fn drops() { key = owner.insert(data); // drop the owner } - assert!(key.try_read().is_none()); + assert!(key.try_read().is_err()); } #[test] @@ -132,7 +135,7 @@ fn fuzz() { println!("{:?}", path); for key in valid_keys.iter() { let value = key.read(); - println!("{:?}", value); + println!("{:?}", &*value); assert!(value.starts_with("hello world")); } #[cfg(any(debug_assertions, feature = "check_generation"))] From 885580f3af9aa092e5da1c6ab30433a9147faec8 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Sat, 2 Sep 2023 18:24:42 -0500 Subject: [PATCH 06/83] update to wry 0.31.0 --- examples/mobile_demo/Cargo.toml | 2 +- packages/desktop/Cargo.toml | 4 +- packages/desktop/src/desktop_context.rs | 15 +- packages/desktop/src/lib.rs | 30 ++- packages/desktop/src/mobile_shortcut.rs | 21 +- packages/desktop/src/shortcut.rs | 325 ++++++++++++------------ 6 files changed, 207 insertions(+), 190 deletions(-) diff --git a/examples/mobile_demo/Cargo.toml b/examples/mobile_demo/Cargo.toml index d22269a0c..ba2af2312 100644 --- a/examples/mobile_demo/Cargo.toml +++ b/examples/mobile_demo/Cargo.toml @@ -35,7 +35,7 @@ frameworks = ["WebKit"] [dependencies] anyhow = "1.0.56" log = "0.4.11" -wry = "0.28.0" +wry = "0.31.0" dioxus = { path = "../../packages/dioxus" } dioxus-desktop = { path = "../../packages/desktop", features = [ "tokio_runtime", diff --git a/packages/desktop/Cargo.toml b/packages/desktop/Cargo.toml index a85c2e045..311e224bb 100644 --- a/packages/desktop/Cargo.toml +++ b/packages/desktop/Cargo.toml @@ -19,7 +19,7 @@ serde = "1.0.136" serde_json = "1.0.79" thiserror = { workspace = true } log = { workspace = true } -wry = { version = "0.28.0" } +wry = { version = "0.31.0" } futures-channel = { workspace = true } tokio = { workspace = true, features = [ "sync", @@ -41,6 +41,7 @@ async-trait = "0.1.68" [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" +global-hotkey = { git = "https://github.com/tauri-apps/global-hotkey" } [target.'cfg(target_os = "ios")'.dependencies] objc = "0.2.7" @@ -55,7 +56,6 @@ default = ["tokio_runtime", "hot-reload"] tokio_runtime = ["tokio"] fullscreen = ["wry/fullscreen"] transparent = ["wry/transparent"] -tray = ["wry/tray"] hot-reload = ["dioxus-hot-reload"] [dev-dependencies] diff --git a/packages/desktop/src/desktop_context.rs b/packages/desktop/src/desktop_context.rs index 166366379..5393fe113 100644 --- a/packages/desktop/src/desktop_context.rs +++ b/packages/desktop/src/desktop_context.rs @@ -5,9 +5,7 @@ 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::shortcut::{ShortcutId, ShortcutRegistry, ShortcutRegistryError}; use crate::Config; use crate::WebviewHandler; use dioxus_core::ScopeState; @@ -15,7 +13,6 @@ use dioxus_core::VirtualDom; #[cfg(all(feature = "hot-reload", debug_assertions))] use dioxus_hot_reload::HotReloadMsg; 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; @@ -233,11 +230,11 @@ 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: global_hotkey::hotkey::HotKey, callback: impl FnMut() + 'static, ) -> Result { self.shortcut_manager - .add_shortcut(accelerator, Box::new(callback)) + .add_shortcut(hotkey, Box::new(callback)) } /// Remove a global shortcut @@ -370,11 +367,7 @@ impl WryWindowEventHandlerInner { ) { // 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), - .. - } => { + Event::WindowEvent { window_id, .. } => { if *window_id != self.window_id { return; } diff --git a/packages/desktop/src/lib.rs b/packages/desktop/src/lib.rs index 070bfa7d1..130170b6f 100644 --- a/packages/desktop/src/lib.rs +++ b/packages/desktop/src/lib.rs @@ -10,15 +10,14 @@ mod escape; mod eval; mod events; mod file_upload; +#[cfg(any(target_os = "ios", target_os = "android"))] +mod mobile_shortcut; mod protocol; mod query; mod shortcut; mod waker; mod webview; -#[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; @@ -32,6 +31,16 @@ use dioxus_html::{native_bind::NativeFileEngine, FormData, HtmlEvent}; use element::DesktopElement; use eval::init_eval; use futures_util::{pin_mut, FutureExt}; +#[cfg(any( + target_os = "windows", + target_os = "macos", + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" +))] +use global_hotkey::GlobalHotKeyEvent; use shortcut::ShortcutRegistry; pub use shortcut::{use_global_shortcut, ShortcutHandle, ShortcutId, ShortcutRegistryError}; use std::cell::Cell; @@ -43,10 +52,11 @@ use tao::event_loop::{EventLoopProxy, EventLoopWindowTarget}; pub use tao::window::WindowBuilder; use tao::{ event::{Event, StartCause, WindowEvent}, - event_loop::{ControlFlow, EventLoop}, + event_loop::ControlFlow, }; pub use wry; pub use wry::application as tao; +use wry::application::event_loop::EventLoopBuilder; use wry::webview::WebView; use wry::{application::window::WindowId, webview::WebContext}; @@ -118,7 +128,7 @@ pub fn launch_cfg(root: Component, config_builder: Config) { /// } /// ``` pub fn launch_with_props(root: Component

, props: P, cfg: Config) { - let event_loop = EventLoop::::with_user_event(); + let event_loop = EventLoopBuilder::::with_user_event().build(); let proxy = event_loop.create_proxy(); @@ -155,7 +165,8 @@ pub fn launch_with_props(root: Component

, props: P, cfg: Config) let queue = WebviewQueue::default(); - let shortcut_manager = ShortcutRegistry::new(&event_loop); + let shortcut_manager = ShortcutRegistry::new(); + let global_hotkey_channel = GlobalHotKeyEvent::receiver(); // 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 @@ -163,10 +174,14 @@ pub fn launch_with_props(root: Component

, props: P, cfg: Config) let cfg = Rc::new(Cell::new(Some(cfg))); event_loop.run(move |window_event, event_loop, control_flow| { - *control_flow = ControlFlow::Wait; + *control_flow = ControlFlow::Poll; event_handlers.apply_event(&window_event, event_loop); + if let Ok(event) = global_hotkey_channel.try_recv() { + shortcut_manager.call_handlers(event); + } + match window_event { Event::WindowEvent { event, window_id, .. @@ -366,7 +381,6 @@ pub fn launch_with_props(root: Component

, props: P, cfg: Config) _ => {} }, - Event::GlobalShortcutEvent(id) => shortcut_manager.call_handlers(id), _ => {} } }) diff --git a/packages/desktop/src/mobile_shortcut.rs b/packages/desktop/src/mobile_shortcut.rs index 29149b55b..b4919dfdf 100644 --- a/packages/desktop/src/mobile_shortcut.rs +++ b/packages/desktop/src/mobile_shortcut.rs @@ -4,7 +4,16 @@ use super::*; use wry::application::accelerator::Accelerator; use wry::application::event_loop::EventLoopWindowTarget; -pub struct GlobalShortcut(); +pub struct HotKey(); + +impl FromStr for HotKey { + type Err = (); + + fn from_str(s: &str) -> Result { + Ok(HotKey()) + } +} + pub struct ShortcutManager(); impl ShortcutManager { @@ -53,3 +62,13 @@ impl fmt::Display for ShortcutManagerError { } } } + +struct HotkeyError; + +struct GlobalHotKeyEvent { + id: u32, +} + +pub(crate) type Code = dioxus::prelude::Code; + +struct GlobalHotKeyManager {} diff --git a/packages/desktop/src/shortcut.rs b/packages/desktop/src/shortcut.rs index ffc64a232..9696fa520 100644 --- a/packages/desktop/src/shortcut.rs +++ b/packages/desktop/src/shortcut.rs @@ -3,39 +3,29 @@ use std::{cell::RefCell, collections::HashMap, rc::Rc, 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 wry::application::keyboard::ModifiersState; use crate::{desktop_context::DesktopContext, use_window}; -#[cfg(any( - target_os = "windows", - target_os = "macos", - target_os = "linux", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "netbsd", - target_os = "openbsd" -))] -use wry::application::global_shortcut::{GlobalShortcut, ShortcutManager, ShortcutManagerError}; +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>, + manager: Rc>, shortcuts: ShortcutMap, } -type ShortcutMap = Rc>>; +type ShortcutMap = Rc>>; struct Shortcut { #[allow(unused)] - shortcut: GlobalShortcut, + shortcut: HotKey, callbacks: Slab>, } @@ -54,15 +44,15 @@ impl Shortcut { } impl ShortcutRegistry { - pub fn new(target: &EventLoopWindowTarget) -> Self { + pub fn new() -> Self { Self { - manager: Rc::new(RefCell::new(ShortcutManager::new(target))), + manager: Rc::new(RefCell::new(GlobalHotKeyManager::new().unwrap())), shortcuts: Rc::new(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,10 +61,10 @@ impl ShortcutRegistry { pub(crate) fn add_shortcut( &self, - accelerator: Accelerator, + hotkey: global_hotkey::hotkey::HotKey, callback: Box, ) -> Result { - 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) { @@ -84,12 +74,12 @@ impl ShortcutRegistry { number: id, } } else { - match self.manager.borrow_mut().register(accelerator) { - Ok(global_shortcut) => { + match self.manager.borrow_mut().register(hotkey) { + Ok(_) => { let mut slab = Slab::new(); let id = slab.insert(callback); let shortcut = Shortcut { - shortcut: global_shortcut, + shortcut: hotkey, callbacks: slab, }; shortcuts.insert(accelerator_id, shortcut); @@ -98,7 +88,7 @@ impl ShortcutRegistry { number: id, } } - Err(ShortcutManagerError::InvalidAccelerator(shortcut)) => { + Err(HotkeyError::HotKeyParseError(shortcut)) => { return Err(ShortcutRegistryError::InvalidShortcut(shortcut)) } Err(err) => return Err(ShortcutRegistryError::Other(Box::new(err))), @@ -113,15 +103,6 @@ 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); } } @@ -130,8 +111,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.borrow_mut().unregister_all(&hotkeys); } } @@ -148,7 +129,7 @@ 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, } @@ -160,33 +141,42 @@ pub struct ShortcutHandle { } 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() } } +#[cfg(any( + target_os = "windows", + target_os = "macos", + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" +))] /// Get a closure that executes any JavaScript in the WebView context. pub fn use_global_shortcut( cx: &ScopeState, @@ -220,143 +210,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), } } From d1575b40d1648768ce80e621e1c75f6ffcd428b8 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Mon, 4 Sep 2023 08:24:38 -0500 Subject: [PATCH 07/83] fix mobile build --- packages/desktop/Cargo.toml | 1 + packages/desktop/src/desktop_context.rs | 4 +- packages/desktop/src/lib.rs | 11 +--- packages/desktop/src/mobile_shortcut.rs | 69 +++++++++++++++---------- packages/desktop/src/shortcut.rs | 22 ++++---- 5 files changed, 57 insertions(+), 50 deletions(-) diff --git a/packages/desktop/Cargo.toml b/packages/desktop/Cargo.toml index 311e224bb..a17b52b1a 100644 --- a/packages/desktop/Cargo.toml +++ b/packages/desktop/Cargo.toml @@ -37,6 +37,7 @@ slab = { workspace = true } futures-util = { workspace = true } urlencoding = "2.1.2" async-trait = "0.1.68" +crossbeam-channel = "0.5.8" [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] diff --git a/packages/desktop/src/desktop_context.rs b/packages/desktop/src/desktop_context.rs index 5393fe113..c5f9f5ca5 100644 --- a/packages/desktop/src/desktop_context.rs +++ b/packages/desktop/src/desktop_context.rs @@ -5,7 +5,7 @@ use std::rc::Weak; use crate::create_new_window; use crate::events::IpcMessage; use crate::query::QueryEngine; -use crate::shortcut::{ShortcutId, ShortcutRegistry, ShortcutRegistryError}; +use crate::shortcut::{HotKey, ShortcutId, ShortcutRegistry, ShortcutRegistryError}; use crate::Config; use crate::WebviewHandler; use dioxus_core::ScopeState; @@ -230,7 +230,7 @@ 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, - hotkey: global_hotkey::hotkey::HotKey, + hotkey: HotKey, callback: impl FnMut() + 'static, ) -> Result { self.shortcut_manager diff --git a/packages/desktop/src/lib.rs b/packages/desktop/src/lib.rs index 130170b6f..a96cd5abf 100644 --- a/packages/desktop/src/lib.rs +++ b/packages/desktop/src/lib.rs @@ -19,6 +19,7 @@ mod waker; mod webview; use crate::query::QueryResult; +use crate::shortcut::GlobalHotKeyEvent; pub use cfg::{Config, WindowCloseBehaviour}; pub use desktop_context::DesktopContext; pub use desktop_context::{ @@ -31,16 +32,6 @@ use dioxus_html::{native_bind::NativeFileEngine, FormData, HtmlEvent}; use element::DesktopElement; use eval::init_eval; use futures_util::{pin_mut, FutureExt}; -#[cfg(any( - target_os = "windows", - target_os = "macos", - target_os = "linux", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "netbsd", - target_os = "openbsd" -))] -use global_hotkey::GlobalHotKeyEvent; use shortcut::ShortcutRegistry; pub use shortcut::{use_global_shortcut, ShortcutHandle, ShortcutId, ShortcutRegistryError}; use std::cell::Cell; diff --git a/packages/desktop/src/mobile_shortcut.rs b/packages/desktop/src/mobile_shortcut.rs index b4919dfdf..c6144344b 100644 --- a/packages/desktop/src/mobile_shortcut.rs +++ b/packages/desktop/src/mobile_shortcut.rs @@ -1,38 +1,51 @@ #![allow(unused)] use super::*; -use wry::application::accelerator::Accelerator; +use std::str::FromStr; use wry::application::event_loop::EventLoopWindowTarget; -pub struct HotKey(); +use dioxus_html::input_data::keyboard_types::Modifiers; + +#[derive(Clone, Debug)] +pub struct Accelerator; + +#[derive(Clone, Copy)] +pub struct HotKey; + +impl HotKey { + pub fn new(mods: Option, key: Code) -> Self { + Self + } + + pub fn id(&self) -> u32 { + 0 + } +} impl FromStr for HotKey { type Err = (); fn from_str(s: &str) -> Result { - Ok(HotKey()) + Ok(HotKey) } } -pub struct ShortcutManager(); +pub struct GlobalHotKeyManager(); -impl ShortcutManager { - pub fn new(target: &EventLoopWindowTarget) -> Self { - Self() +impl GlobalHotKeyManager { + pub fn new() -> Result { + Ok(Self()) } - pub fn register( - &mut self, - accelerator: Accelerator, - ) -> Result { - Ok(GlobalShortcut()) + pub fn register(&mut self, accelerator: HotKey) -> Result { + Ok(HotKey) } - pub fn unregister(&mut self, id: ShortcutId) -> Result<(), ShortcutManagerError> { + pub fn unregister(&mut self, id: HotKey) -> Result<(), HotkeyError> { Ok(()) } - pub fn unregister_all(&mut self) -> Result<(), ShortcutManagerError> { + pub fn unregister_all(&mut self, _: &[HotKey]) -> Result<(), HotkeyError> { Ok(()) } } @@ -42,33 +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), } } } -struct HotkeyError; - -struct GlobalHotKeyEvent { - id: u32, +pub struct GlobalHotKeyEvent { + pub id: u32, } -pub(crate) type Code = dioxus::prelude::Code; +impl GlobalHotKeyEvent { + pub fn receiver() -> crossbeam_channel::Receiver { + crossbeam_channel::unbounded().1 + } +} -struct GlobalHotKeyManager {} +pub(crate) type Code = dioxus_html::input_data::keyboard_types::Code; diff --git a/packages/desktop/src/shortcut.rs b/packages/desktop/src/shortcut.rs index 9696fa520..66ab4ba7a 100644 --- a/packages/desktop/src/shortcut.rs +++ b/packages/desktop/src/shortcut.rs @@ -7,7 +7,16 @@ use wry::application::keyboard::ModifiersState; use crate::{desktop_context::DesktopContext, use_window}; -use global_hotkey::{ +#[cfg(any( + target_os = "windows", + target_os = "macos", + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" +))] +pub use global_hotkey::{ hotkey::{Code, HotKey}, Error as HotkeyError, GlobalHotKeyEvent, GlobalHotKeyManager, }; @@ -61,7 +70,7 @@ impl ShortcutRegistry { pub(crate) fn add_shortcut( &self, - hotkey: global_hotkey::hotkey::HotKey, + hotkey: HotKey, callback: Box, ) -> Result { let accelerator_id = hotkey.clone().id(); @@ -168,15 +177,6 @@ impl IntoAccelerator for &str { } } -#[cfg(any( - target_os = "windows", - target_os = "macos", - target_os = "linux", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "netbsd", - target_os = "openbsd" -))] /// Get a closure that executes any JavaScript in the WebView context. pub fn use_global_shortcut( cx: &ScopeState, From e86c1647d835b72688279603af16cffada43c13a Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Mon, 4 Sep 2023 08:33:56 -0500 Subject: [PATCH 08/83] fix clippy --- packages/core/src/diff.rs | 3 +-- packages/desktop/src/desktop_context.rs | 9 +++------ 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/packages/core/src/diff.rs b/packages/core/src/diff.rs index dd4cf8147..58fceaa48 100644 --- a/packages/core/src/diff.rs +++ b/packages/core/src/diff.rs @@ -577,8 +577,7 @@ impl<'b> VirtualDom { } // 4. Compute the LIS of this list - let mut lis_sequence = Vec::default(); - lis_sequence.reserve(new_index_to_old_index.len()); + let mut lis_sequence = Vec::with_capacity(new_index_to_old_index.len()); let mut predecessors = vec![0; new_index_to_old_index.len()]; let mut starts = vec![0; new_index_to_old_index.len()]; diff --git a/packages/desktop/src/desktop_context.rs b/packages/desktop/src/desktop_context.rs index c5f9f5ca5..d2c29f676 100644 --- a/packages/desktop/src/desktop_context.rs +++ b/packages/desktop/src/desktop_context.rs @@ -366,13 +366,10 @@ impl WryWindowEventHandlerInner { target: &EventLoopWindowTarget, ) { // if this event does not apply to the window this listener cares about, return - match event { - Event::WindowEvent { 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) } From d994e3e7221b404b1a69c6f099a9b46a9e5a4eed Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Sat, 23 Sep 2023 07:57:41 -0500 Subject: [PATCH 09/83] make the layer module public in fullstack --- packages/fullstack/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/fullstack/src/lib.rs b/packages/fullstack/src/lib.rs index f2d3e5533..384560c0a 100644 --- a/packages/fullstack/src/lib.rs +++ b/packages/fullstack/src/lib.rs @@ -19,7 +19,7 @@ mod hooks; mod hot_reload; pub mod launch; #[cfg(feature = "ssr")] -mod layer; +pub mod layer; #[cfg(feature = "ssr")] mod render; #[cfg(feature = "ssr")] From d2f0f4b4b6009f995c9dcb1e228cb8f67f93d4a9 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Mon, 25 Sep 2023 12:25:21 -0500 Subject: [PATCH 10/83] document layer and service --- packages/fullstack/src/layer.rs | 5 +++++ packages/fullstack/src/lib.rs | 4 +++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/packages/fullstack/src/layer.rs b/packages/fullstack/src/layer.rs index 10e67b3f5..60f76107b 100644 --- a/packages/fullstack/src/layer.rs +++ b/packages/fullstack/src/layer.rs @@ -3,7 +3,9 @@ use tracing_futures::Instrument; use http::{Request, Response}; +/// A layer that wraps a service. This can be used to add additional information to the request, or response on top of some other service pub trait Layer: Send + Sync + 'static { + /// Wrap a boxed service with this layer fn layer(&self, inner: BoxedService) -> BoxedService; } @@ -17,7 +19,9 @@ where } } +/// A service is a function that takes a request and returns an async response pub trait Service { + /// Run the service and produce a future that resolves to a response fn run( &mut self, req: http::Request, @@ -55,6 +59,7 @@ where } } +/// A boxed service is a type-erased service that can be used without knowing the underlying type pub struct BoxedService(pub Box); impl tower::Service> for BoxedService { diff --git a/packages/fullstack/src/lib.rs b/packages/fullstack/src/lib.rs index 384560c0a..75707b931 100644 --- a/packages/fullstack/src/lib.rs +++ b/packages/fullstack/src/lib.rs @@ -19,7 +19,7 @@ mod hooks; mod hot_reload; pub mod launch; #[cfg(feature = "ssr")] -pub mod layer; +mod layer; #[cfg(feature = "ssr")] mod render; #[cfg(feature = "ssr")] @@ -40,6 +40,8 @@ pub mod prelude { #[cfg(not(feature = "ssr"))] pub use crate::html_storage::deserialize::get_root_props_from_document; pub use crate::launch::LaunchBuilder; + #[cfg(feature = "ssr")] + pub use crate::layer::{Layer, Service}; #[cfg(all(feature = "ssr", feature = "router"))] pub use crate::render::pre_cache_static_routes_with_props; #[cfg(feature = "ssr")] From 6e85ecea128d5d30aaadc6ae3f466623950b8c75 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Wed, 25 Oct 2023 10:23:23 -0500 Subject: [PATCH 11/83] fix use shared state lint in release mode --- packages/hooks/src/use_shared_state.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/hooks/src/use_shared_state.rs b/packages/hooks/src/use_shared_state.rs index 37226c759..0c0f43508 100644 --- a/packages/hooks/src/use_shared_state.rs +++ b/packages/hooks/src/use_shared_state.rs @@ -26,6 +26,7 @@ macro_rules! debug_location { } pub mod error { + #[cfg(debug_assertions)] fn locations_display(locations: &[&'static std::panic::Location<'static>]) -> String { locations .iter() From b9dae3e1e0c535225a64756e58dd7570caabf9ad Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Wed, 25 Oct 2023 15:06:08 -0500 Subject: [PATCH 12/83] don't ignore leaks in miri --- .github/workflows/miri.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/miri.yml b/.github/workflows/miri.yml index 4a467b9b2..f9ad3855f 100644 --- a/.github/workflows/miri.yml +++ b/.github/workflows/miri.yml @@ -86,8 +86,7 @@ jobs: # working-directory: tokio env: - # todo: disable memory leaks ignore - MIRIFLAGS: -Zmiri-disable-isolation -Zmiri-strict-provenance -Zmiri-retag-fields -Zmiri-ignore-leaks + MIRIFLAGS: -Zmiri-disable-isolation -Zmiri-strict-provenance -Zmiri-retag-fields PROPTEST_CASES: 10 # Cache the global cargo directory, but NOT the local `target` directory which From eea4a02ef59c07fcd2e143e838a4080a8d59cb49 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Thu, 26 Oct 2023 13:23:12 -0500 Subject: [PATCH 13/83] add comments about the cause of the leak --- packages/core/src/bump_frame.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/core/src/bump_frame.rs b/packages/core/src/bump_frame.rs index 9ae11ab79..6927bd8bc 100644 --- a/packages/core/src/bump_frame.rs +++ b/packages/core/src/bump_frame.rs @@ -7,6 +7,8 @@ use std::cell::{Cell, UnsafeCell}; pub(crate) struct BumpFrame { pub bump: UnsafeCell, pub node: Cell<*const RenderReturn<'static>>, + + // The bump allocator will not call the destructor of the objects it allocated. Attributes and props need to have there destructor called, so we keep a list of them to drop before the bump allocator is reset. pub(crate) attributes_to_drop_before_reset: RefCell>>, pub(crate) props_to_drop_before_reset: RefCell>>, } @@ -43,6 +45,10 @@ impl BumpFrame { .push(attribute); } + /// Reset the bump allocator and drop all the attributes and props that were allocated in it. + /// + /// # Safety + /// The caller must insure that no reference to anything allocated in the bump allocator is available after this function is called. pub(crate) unsafe fn reset(&self) { let mut attributes = self.attributes_to_drop_before_reset.borrow_mut(); attributes.drain(..).for_each(|attribute| { From c5e647e97d0567e8362662a80ce474b95aa638ac Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Mon, 30 Oct 2023 08:39:37 -0500 Subject: [PATCH 14/83] add read untracked to signals --- packages/signals/src/signal.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/packages/signals/src/signal.rs b/packages/signals/src/signal.rs index 9213307ff..0ad96349d 100644 --- a/packages/signals/src/signal.rs +++ b/packages/signals/src/signal.rs @@ -200,6 +200,13 @@ impl Signal { Ref::map(inner, |v| &v.value) } + /// Get the current value of the signal. **Unlike read, this will not subscribe the current scope to the signal which can cause parts of your UI to not update.** + /// If the signal has been dropped, this will panic. + pub fn read_untracked(&self) -> Ref { + let inner = self.inner.read(); + Ref::map(inner, |v| &v.value) + } + /// Get a mutable reference to the signal's value. /// If the signal has been dropped, this will panic. pub fn write(&self) -> Write<'_, T> { @@ -385,6 +392,12 @@ impl ReadOnlySignal { self.inner.read() } + /// Get the current value of the signal. **Unlike read, this will not subscribe the current scope to the signal which can cause parts of your UI to not update.** + /// If the signal has been dropped, this will panic. + pub fn read_untracked(&self) -> Ref { + self.inner.read_untracked() + } + /// Run a closure with a reference to the signal's value. pub fn with(&self, f: impl FnOnce(&T) -> O) -> O { self.inner.with(f) From 5fdff4b7ed1d2ea5b6af9ff98261f96c2cdb6578 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Tue, 31 Oct 2023 13:49:29 -0500 Subject: [PATCH 15/83] bump wry to 0.34 --- examples/mobile_demo/Cargo.toml | 2 +- packages/desktop/Cargo.toml | 6 ++---- packages/desktop/src/webview.rs | 33 +++++++++++++++++++++++++++++---- packages/html/Cargo.toml | 2 +- 4 files changed, 33 insertions(+), 10 deletions(-) diff --git a/examples/mobile_demo/Cargo.toml b/examples/mobile_demo/Cargo.toml index ba2af2312..a90ff4f36 100644 --- a/examples/mobile_demo/Cargo.toml +++ b/examples/mobile_demo/Cargo.toml @@ -35,7 +35,7 @@ frameworks = ["WebKit"] [dependencies] anyhow = "1.0.56" log = "0.4.11" -wry = "0.31.0" +wry = "0.34.0" dioxus = { path = "../../packages/dioxus" } dioxus-desktop = { path = "../../packages/desktop", features = [ "tokio_runtime", diff --git a/packages/desktop/Cargo.toml b/packages/desktop/Cargo.toml index e9b95e573..31324e728 100644 --- a/packages/desktop/Cargo.toml +++ b/packages/desktop/Cargo.toml @@ -19,7 +19,7 @@ serde = "1.0.136" serde_json = "1.0.79" thiserror = { workspace = true } tracing = { workspace = true } -wry = { version = "0.31.0", default-features = false, features = ["protocol", "file-drop"] } +wry = { version = "0.34.0", default-features = false, features = ["tao", "protocol", "file-drop"] } futures-channel = { workspace = true } tokio = { workspace = true, features = [ "sync", @@ -41,7 +41,7 @@ crossbeam-channel = "0.5.8" [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" +rfd = "0.12" global-hotkey = { git = "https://github.com/tauri-apps/global-hotkey" } [target.'cfg(target_os = "ios")'.dependencies] @@ -58,8 +58,6 @@ tokio_runtime = ["tokio"] fullscreen = ["wry/fullscreen"] transparent = ["wry/transparent"] devtools = ["wry/devtools"] -tray = ["wry/tray"] -dox = ["wry/dox"] hot-reload = ["dioxus-hot-reload"] [package.metadata.docs.rs] diff --git a/packages/desktop/src/webview.rs b/packages/desktop/src/webview.rs index 6e6d26b17..cffb6f6b5 100644 --- a/packages/desktop/src/webview.rs +++ b/packages/desktop/src/webview.rs @@ -5,6 +5,7 @@ use tao::event_loop::{EventLoopProxy, EventLoopWindowTarget}; pub use wry; pub use wry::application as tao; use wry::application::window::Window; +use wry::http::Response; use wry::webview::{WebContext, WebView, WebViewBuilder}; pub fn build( @@ -44,9 +45,24 @@ pub fn build( _ = 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_custom_protocol( + String::from("dioxus"), + move |r| match protocol::desktop_handler( + &r, + custom_head.clone(), + index_file.clone(), + &root_name, + ) { + Ok(response) => response, + Err(err) => { + tracing::error!("Error: {}", err); + Response::builder() + .status(500) + .body(err.to_string().into_bytes().into()) + .unwrap() + } + }, + ) .with_file_drop_handler(move |window, evet| { file_handler .as_ref() @@ -71,7 +87,16 @@ pub fn build( // .with_web_context(&mut web_context); for (name, handler) in cfg.protocols.drain(..) { - webview = webview.with_custom_protocol(name, handler) + webview = webview.with_custom_protocol(name, move |r| match handler(&r) { + Ok(response) => response, + Err(err) => { + tracing::error!("Error: {}", err); + Response::builder() + .status(500) + .body(err.to_string().into_bytes().into()) + .unwrap() + } + }) } if cfg.disable_context_menu { diff --git a/packages/html/Cargo.toml b/packages/html/Cargo.toml index 5644b440c..39b5455f2 100644 --- a/packages/html/Cargo.toml +++ b/packages/html/Cargo.toml @@ -21,7 +21,7 @@ keyboard-types = "0.7" async-trait = "0.1.58" serde-value = "0.7.0" tokio = { workspace = true, features = ["fs", "io-util"], optional = true } -rfd = { version = "0.11.3", optional = true } +rfd = { version = "0.12", optional = true } async-channel = "1.8.0" serde_json = { version = "1", optional = true } From fdec47b90bc09945ccb5f26012b492f38587d872 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Wed, 1 Nov 2023 08:19:35 -0500 Subject: [PATCH 16/83] fix clippy --- packages/generational-box/src/lib.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/generational-box/src/lib.rs b/packages/generational-box/src/lib.rs index 628308340..f56904ede 100644 --- a/packages/generational-box/src/lib.rs +++ b/packages/generational-box/src/lib.rs @@ -485,7 +485,7 @@ pub struct GenerationalRef { borrow: GenerationalRefBorrowInfo, } -impl<'a, T: 'static> GenerationalRef { +impl GenerationalRef { /// Map one ref type to another. pub fn map(orig: GenerationalRef, f: F) -> GenerationalRef where @@ -522,7 +522,7 @@ impl<'a, T: 'static> GenerationalRef { } } -impl<'a, T: 'static> Deref for GenerationalRef { +impl Deref for GenerationalRef { type Target = T; fn deref(&self) -> &Self::Target { @@ -586,7 +586,7 @@ impl GenerationalRefMut { } } -impl<'a, T: 'static> Deref for GenerationalRefMut { +impl Deref for GenerationalRefMut { type Target = T; fn deref(&self) -> &Self::Target { @@ -594,7 +594,7 @@ impl<'a, T: 'static> Deref for GenerationalRefMut { } } -impl<'a, T: 'static> DerefMut for GenerationalRefMut { +impl DerefMut for GenerationalRefMut { fn deref_mut(&mut self) -> &mut Self::Target { self.inner.deref_mut() } From 52fb0801933eed40bea1c9edb58544693810e544 Mon Sep 17 00:00:00 2001 From: Alex Parrill Date: Tue, 31 Oct 2023 20:48:19 -0400 Subject: [PATCH 17/83] Use indentation settings in dx fmt and vscode extension Adds the ability to specify an indent string to public autofmt methods - either a sequence of spaces or a tab character. Get the indentation style and size from rustfmt for dx fmt, or from the editor settings for the vscode extension. Closes #1595 --- packages/autofmt/src/buffer.rs | 11 +- packages/autofmt/src/element.rs | 12 +- packages/autofmt/src/expr.rs | 6 +- packages/autofmt/src/indent.rs | 108 ++++++++++++++++++ packages/autofmt/src/lib.rs | 27 ++--- packages/autofmt/src/writer.rs | 4 +- packages/autofmt/tests/samples.rs | 2 +- packages/autofmt/tests/wrong.rs | 15 ++- .../wrong/{comments.rsx => comments-4sp.rsx} | 0 ...ments.wrong.rsx => comments-4sp.wrong.rsx} | 0 packages/autofmt/tests/wrong/comments-tab.rsx | 7 ++ .../tests/wrong/comments-tab.wrong.rsx | 5 + .../tests/wrong/{multi.rsx => multi-4sp.rsx} | 0 .../{multi.wrong.rsx => multi-4sp.wrong.rsx} | 0 packages/autofmt/tests/wrong/multi-tab.rsx | 3 + .../autofmt/tests/wrong/multi-tab.wrong.rsx | 5 + .../{multiexpr.rsx => multiexpr-4sp.rsx} | 0 ...expr.wrong.rsx => multiexpr-4sp.wrong.rsx} | 0 .../autofmt/tests/wrong/multiexpr-tab.rsx | 8 ++ .../tests/wrong/multiexpr-tab.wrong.rsx | 5 + packages/cli/src/cli/autoformat.rs | 68 ++++++++++- packages/extension/src/lib.rs | 46 ++++++-- packages/extension/src/main.ts | 2 +- 23 files changed, 283 insertions(+), 51 deletions(-) create mode 100644 packages/autofmt/src/indent.rs rename packages/autofmt/tests/wrong/{comments.rsx => comments-4sp.rsx} (100%) rename packages/autofmt/tests/wrong/{comments.wrong.rsx => comments-4sp.wrong.rsx} (100%) create mode 100644 packages/autofmt/tests/wrong/comments-tab.rsx create mode 100644 packages/autofmt/tests/wrong/comments-tab.wrong.rsx rename packages/autofmt/tests/wrong/{multi.rsx => multi-4sp.rsx} (100%) rename packages/autofmt/tests/wrong/{multi.wrong.rsx => multi-4sp.wrong.rsx} (100%) create mode 100644 packages/autofmt/tests/wrong/multi-tab.rsx create mode 100644 packages/autofmt/tests/wrong/multi-tab.wrong.rsx rename packages/autofmt/tests/wrong/{multiexpr.rsx => multiexpr-4sp.rsx} (100%) rename packages/autofmt/tests/wrong/{multiexpr.wrong.rsx => multiexpr-4sp.wrong.rsx} (100%) create mode 100644 packages/autofmt/tests/wrong/multiexpr-tab.rsx create mode 100644 packages/autofmt/tests/wrong/multiexpr-tab.wrong.rsx diff --git a/packages/autofmt/src/buffer.rs b/packages/autofmt/src/buffer.rs index fea5a4a3f..f19a7d8dc 100644 --- a/packages/autofmt/src/buffer.rs +++ b/packages/autofmt/src/buffer.rs @@ -8,13 +8,14 @@ use std::fmt::{Result, Write}; use dioxus_rsx::IfmtInput; -use crate::write_ifmt; +use crate::{indent::IndentOptions, write_ifmt}; /// The output buffer that tracks indent and string #[derive(Debug, Default)] pub struct Buffer { pub buf: String, - pub indent: usize, + pub indent_level: usize, + pub indent: IndentOptions, } impl Buffer { @@ -31,16 +32,16 @@ impl Buffer { } pub fn tab(&mut self) -> Result { - self.write_tabs(self.indent) + self.write_tabs(self.indent_level) } pub fn indented_tab(&mut self) -> Result { - self.write_tabs(self.indent + 1) + self.write_tabs(self.indent_level + 1) } pub fn write_tabs(&mut self, num: usize) -> std::fmt::Result { for _ in 0..num { - write!(self.buf, " ")? + write!(self.buf, "{}", self.indent.indent_str())? } Ok(()) } diff --git a/packages/autofmt/src/element.rs b/packages/autofmt/src/element.rs index dbc336401..27e7b31f1 100644 --- a/packages/autofmt/src/element.rs +++ b/packages/autofmt/src/element.rs @@ -66,7 +66,7 @@ impl Writer<'_> { // check if we have a lot of attributes let attr_len = self.is_short_attrs(attributes); - let is_short_attr_list = (attr_len + self.out.indent * 4) < 80; + let is_short_attr_list = (attr_len + self.out.indent_level * 4) < 80; let children_len = self.is_short_children(children); let is_small_children = children_len.is_some(); @@ -86,7 +86,7 @@ impl Writer<'_> { // if we have few children and few attributes, make it a one-liner if is_short_attr_list && is_small_children { - if children_len.unwrap() + attr_len + self.out.indent * 4 < 100 { + if children_len.unwrap() + attr_len + self.out.indent_level * 4 < 100 { opt_level = ShortOptimization::Oneliner; } else { opt_level = ShortOptimization::PropsOnTop; @@ -185,11 +185,11 @@ impl Writer<'_> { } while let Some(attr) = attr_iter.next() { - self.out.indent += 1; + self.out.indent_level += 1; if !sameline { self.write_comments(attr.attr.start())?; } - self.out.indent -= 1; + self.out.indent_level -= 1; if !sameline { self.out.indented_tabbed_line()?; @@ -398,14 +398,14 @@ impl Writer<'_> { for idx in start.line..end.line { let line = &self.src[idx]; if line.trim().starts_with("//") { - for _ in 0..self.out.indent + 1 { + for _ in 0..self.out.indent_level + 1 { write!(self.out, " ")? } writeln!(self.out, "{}", line.trim()).unwrap(); } } - for _ in 0..self.out.indent { + for _ in 0..self.out.indent_level { write!(self.out, " ")? } diff --git a/packages/autofmt/src/expr.rs b/packages/autofmt/src/expr.rs index b0257f8c3..b7a93a4fc 100644 --- a/packages/autofmt/src/expr.rs +++ b/packages/autofmt/src/expr.rs @@ -29,7 +29,7 @@ impl Writer<'_> { let first_line = &self.src[start.line - 1]; write!(self.out, "{}", &first_line[start.column - 1..].trim_start())?; - let prev_block_indent_level = crate::leading_whitespaces(first_line) / 4; + let prev_block_indent_level = self.out.indent.count_indents(first_line); for (id, line) in self.src[start.line..end.line].iter().enumerate() { writeln!(self.out)?; @@ -43,9 +43,9 @@ impl Writer<'_> { }; // trim the leading whitespace - let previous_indent = crate::leading_whitespaces(line) / 4; + let previous_indent = self.out.indent.count_indents(line); let offset = previous_indent.saturating_sub(prev_block_indent_level); - let required_indent = self.out.indent + offset; + let required_indent = self.out.indent_level + offset; self.out.write_tabs(required_indent)?; let line = line.trim_start(); diff --git a/packages/autofmt/src/indent.rs b/packages/autofmt/src/indent.rs new file mode 100644 index 000000000..2cce7cf1e --- /dev/null +++ b/packages/autofmt/src/indent.rs @@ -0,0 +1,108 @@ +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum IndentType { + Spaces, + Tabs, +} + +#[derive(Debug, Clone)] +pub struct IndentOptions { + width: usize, + indent_string: String, +} + +impl IndentOptions { + pub fn new(typ: IndentType, width: usize) -> Self { + assert_ne!(width, 0, "Cannot have an indent width of 0"); + Self { + width, + indent_string: match typ { + IndentType::Tabs => "\t".into(), + IndentType::Spaces => " ".repeat(width), + }, + } + } + + /// Gets a string containing one indent worth of whitespace + pub fn indent_str(&self) -> &str { + &self.indent_string + } + + /// Computes the line length in characters, counting tabs as the indent width. + pub fn line_length(&self, line: &str) -> usize { + line.chars() + .map(|ch| if ch == '\t' { self.width } else { 1 }) + .sum() + } + + /// Estimates how many times the line has been indented. + pub fn count_indents(&self, mut line: &str) -> usize { + let mut indent = 0; + while !line.is_empty() { + // Try to count tabs + let num_tabs = line.chars().take_while(|ch| *ch == '\t').count(); + if num_tabs > 0 { + indent += num_tabs; + line = &line[num_tabs..]; + continue; + } + + // Try to count spaces + let num_spaces = line.chars().take_while(|ch| *ch == ' ').count(); + if num_spaces >= self.width { + // Intentionally floor here to take only the amount of space that matches an indent + let num_space_indents = num_spaces / self.width; + indent += num_space_indents; + line = &line[num_space_indents * self.width..]; + continue; + } + + // Line starts with either non-indent characters or an unevent amount of spaces, + // so no more indent remains. + break; + } + indent + } +} + +impl Default for IndentOptions { + fn default() -> Self { + Self::new(IndentType::Spaces, 4) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn count_indents() { + assert_eq!( + IndentOptions::new(IndentType::Spaces, 4).count_indents("no indentation here!"), + 0 + ); + assert_eq!( + IndentOptions::new(IndentType::Spaces, 4).count_indents(" v += 2"), + 1 + ); + assert_eq!( + IndentOptions::new(IndentType::Spaces, 4).count_indents(" v += 2"), + 2 + ); + assert_eq!( + IndentOptions::new(IndentType::Spaces, 4).count_indents(" v += 2"), + 2 + ); + assert_eq!( + IndentOptions::new(IndentType::Spaces, 4).count_indents("\t\tv += 2"), + 2 + ); + assert_eq!( + IndentOptions::new(IndentType::Spaces, 4).count_indents("\t\t v += 2"), + 2 + ); + assert_eq!( + IndentOptions::new(IndentType::Spaces, 2).count_indents(" v += 2"), + 2 + ); + } +} diff --git a/packages/autofmt/src/lib.rs b/packages/autofmt/src/lib.rs index 64a342885..0c3fe6bb8 100644 --- a/packages/autofmt/src/lib.rs +++ b/packages/autofmt/src/lib.rs @@ -16,8 +16,11 @@ mod collect_macros; mod component; mod element; mod expr; +mod indent; mod writer; +pub use indent::{IndentOptions, IndentType}; + /// A modification to the original file to be applied by an IDE /// /// Right now this re-writes entire rsx! blocks at a time, instead of precise line-by-line changes. @@ -47,7 +50,7 @@ pub struct FormattedBlock { /// back to the file precisely. /// /// Nested blocks of RSX will be handled automatically -pub fn fmt_file(contents: &str) -> Vec { +pub fn fmt_file(contents: &str, indent: IndentOptions) -> Vec { let mut formatted_blocks = Vec::new(); let parsed = syn::parse_file(contents).unwrap(); @@ -61,6 +64,7 @@ pub fn fmt_file(contents: &str) -> Vec { } let mut writer = Writer::new(contents); + writer.out.indent = indent; // Don't parse nested macros let mut end_span = LineColumn { column: 0, line: 0 }; @@ -76,7 +80,10 @@ pub fn fmt_file(contents: &str) -> Vec { let rsx_start = macro_path.span().start(); - writer.out.indent = leading_whitespaces(writer.src[rsx_start.line - 1]) / 4; + writer.out.indent_level = writer + .out + .indent + .count_indents(writer.src[rsx_start.line - 1]); write_body(&mut writer, &body); @@ -159,12 +166,13 @@ pub fn fmt_block_from_expr(raw: &str, expr: ExprMacro) -> Option { buf.consume() } -pub fn fmt_block(block: &str, indent_level: usize) -> Option { +pub fn fmt_block(block: &str, indent_level: usize, indent: IndentOptions) -> Option { let body = syn::parse_str::(block).unwrap(); let mut buf = Writer::new(block); - buf.out.indent = indent_level; + buf.out.indent = indent; + buf.out.indent_level = indent_level; write_body(&mut buf, &body); @@ -230,14 +238,3 @@ pub(crate) fn write_ifmt(input: &IfmtInput, writable: &mut impl Write) -> std::f let display = DisplayIfmt(input); write!(writable, "{}", display) } - -pub fn leading_whitespaces(input: &str) -> usize { - input - .chars() - .map_while(|c| match c { - ' ' => Some(1), - '\t' => Some(4), - _ => None, - }) - .sum() -} diff --git a/packages/autofmt/src/writer.rs b/packages/autofmt/src/writer.rs index 59f135592..bb333e8df 100644 --- a/packages/autofmt/src/writer.rs +++ b/packages/autofmt/src/writer.rs @@ -96,11 +96,11 @@ impl<'a> Writer<'a> { // Push out the indent level and write each component, line by line pub fn write_body_indented(&mut self, children: &[BodyNode]) -> Result { - self.out.indent += 1; + self.out.indent_level += 1; self.write_body_no_indent(children)?; - self.out.indent -= 1; + self.out.indent_level -= 1; Ok(()) } diff --git a/packages/autofmt/tests/samples.rs b/packages/autofmt/tests/samples.rs index 8145b0e8e..9431d700e 100644 --- a/packages/autofmt/tests/samples.rs +++ b/packages/autofmt/tests/samples.rs @@ -12,7 +12,7 @@ macro_rules! twoway { #[test] fn $name() { let src = include_str!(concat!("./samples/", stringify!($name), ".rsx")); - let formatted = dioxus_autofmt::fmt_file(src); + let formatted = dioxus_autofmt::fmt_file(src, Default::default()); let out = dioxus_autofmt::apply_formats(src, formatted); // normalize line endings let out = out.replace("\r", ""); diff --git a/packages/autofmt/tests/wrong.rs b/packages/autofmt/tests/wrong.rs index 5a0fb8a87..145d03807 100644 --- a/packages/autofmt/tests/wrong.rs +++ b/packages/autofmt/tests/wrong.rs @@ -1,10 +1,12 @@ +use dioxus_autofmt::{IndentType, IndentOptions}; + macro_rules! twoway { - ($val:literal => $name:ident) => { + ($val:literal => $name:ident ($indent:expr)) => { #[test] fn $name() { let src_right = include_str!(concat!("./wrong/", $val, ".rsx")); let src_wrong = include_str!(concat!("./wrong/", $val, ".wrong.rsx")); - let formatted = dioxus_autofmt::fmt_file(src_wrong); + let formatted = dioxus_autofmt::fmt_file(src_wrong, $indent); let out = dioxus_autofmt::apply_formats(src_wrong, formatted); // normalize line endings @@ -16,8 +18,11 @@ macro_rules! twoway { }; } -twoway!("comments" => comments); +twoway!("comments-4sp" => comments_4sp (IndentOptions::new(IndentType::Spaces, 4))); +twoway!("comments-tab" => comments_tab (IndentOptions::new(IndentType::Tabs, 4))); -twoway!("multi" => multi); +twoway!("multi-4sp" => multi_4sp (IndentOptions::new(IndentType::Spaces, 4))); +twoway!("multi-tab" => multi_tab (IndentOptions::new(IndentType::Tabs, 4))); -twoway!("multiexpr" => multiexpr); +twoway!("multiexpr-4sp" => multiexpr_4sp (IndentOptions::new(IndentType::Spaces, 4))); +twoway!("multiexpr-tab" => multiexpr_tab (IndentOptions::new(IndentType::Tabs, 4))); diff --git a/packages/autofmt/tests/wrong/comments.rsx b/packages/autofmt/tests/wrong/comments-4sp.rsx similarity index 100% rename from packages/autofmt/tests/wrong/comments.rsx rename to packages/autofmt/tests/wrong/comments-4sp.rsx diff --git a/packages/autofmt/tests/wrong/comments.wrong.rsx b/packages/autofmt/tests/wrong/comments-4sp.wrong.rsx similarity index 100% rename from packages/autofmt/tests/wrong/comments.wrong.rsx rename to packages/autofmt/tests/wrong/comments-4sp.wrong.rsx diff --git a/packages/autofmt/tests/wrong/comments-tab.rsx b/packages/autofmt/tests/wrong/comments-tab.rsx new file mode 100644 index 000000000..4c05e347e --- /dev/null +++ b/packages/autofmt/tests/wrong/comments-tab.rsx @@ -0,0 +1,7 @@ +rsx! { + div { + // Comments + class: "asdasd", + "hello world" + } +} diff --git a/packages/autofmt/tests/wrong/comments-tab.wrong.rsx b/packages/autofmt/tests/wrong/comments-tab.wrong.rsx new file mode 100644 index 000000000..eac96642d --- /dev/null +++ b/packages/autofmt/tests/wrong/comments-tab.wrong.rsx @@ -0,0 +1,5 @@ +rsx! { + div { + // Comments + class: "asdasd", "hello world" } +} diff --git a/packages/autofmt/tests/wrong/multi.rsx b/packages/autofmt/tests/wrong/multi-4sp.rsx similarity index 100% rename from packages/autofmt/tests/wrong/multi.rsx rename to packages/autofmt/tests/wrong/multi-4sp.rsx diff --git a/packages/autofmt/tests/wrong/multi.wrong.rsx b/packages/autofmt/tests/wrong/multi-4sp.wrong.rsx similarity index 100% rename from packages/autofmt/tests/wrong/multi.wrong.rsx rename to packages/autofmt/tests/wrong/multi-4sp.wrong.rsx diff --git a/packages/autofmt/tests/wrong/multi-tab.rsx b/packages/autofmt/tests/wrong/multi-tab.rsx new file mode 100644 index 000000000..1fb85c3d0 --- /dev/null +++ b/packages/autofmt/tests/wrong/multi-tab.rsx @@ -0,0 +1,3 @@ +fn app(cx: Scope) -> Element { + cx.render(rsx! { div { "hello world" } }) +} diff --git a/packages/autofmt/tests/wrong/multi-tab.wrong.rsx b/packages/autofmt/tests/wrong/multi-tab.wrong.rsx new file mode 100644 index 000000000..d818f9535 --- /dev/null +++ b/packages/autofmt/tests/wrong/multi-tab.wrong.rsx @@ -0,0 +1,5 @@ +fn app(cx: Scope) -> Element { + cx.render(rsx! { + div {"hello world" } + }) +} diff --git a/packages/autofmt/tests/wrong/multiexpr.rsx b/packages/autofmt/tests/wrong/multiexpr-4sp.rsx similarity index 100% rename from packages/autofmt/tests/wrong/multiexpr.rsx rename to packages/autofmt/tests/wrong/multiexpr-4sp.rsx diff --git a/packages/autofmt/tests/wrong/multiexpr.wrong.rsx b/packages/autofmt/tests/wrong/multiexpr-4sp.wrong.rsx similarity index 100% rename from packages/autofmt/tests/wrong/multiexpr.wrong.rsx rename to packages/autofmt/tests/wrong/multiexpr-4sp.wrong.rsx diff --git a/packages/autofmt/tests/wrong/multiexpr-tab.rsx b/packages/autofmt/tests/wrong/multiexpr-tab.rsx new file mode 100644 index 000000000..1fc3401c4 --- /dev/null +++ b/packages/autofmt/tests/wrong/multiexpr-tab.rsx @@ -0,0 +1,8 @@ +fn ItWroks() { + cx.render(rsx! { + div { class: "flex flex-wrap items-center dark:text-white py-16 border-t font-light", + left, + right + } + }) +} diff --git a/packages/autofmt/tests/wrong/multiexpr-tab.wrong.rsx b/packages/autofmt/tests/wrong/multiexpr-tab.wrong.rsx new file mode 100644 index 000000000..073107541 --- /dev/null +++ b/packages/autofmt/tests/wrong/multiexpr-tab.wrong.rsx @@ -0,0 +1,5 @@ +fn ItWroks() { + cx.render(rsx! { + div { class: "flex flex-wrap items-center dark:text-white py-16 border-t font-light", left, right } + }) +} diff --git a/packages/cli/src/cli/autoformat.rs b/packages/cli/src/cli/autoformat.rs index 1d1cbcd24..6c1ce04a1 100644 --- a/packages/cli/src/cli/autoformat.rs +++ b/packages/cli/src/cli/autoformat.rs @@ -1,3 +1,4 @@ +use dioxus_autofmt::{IndentOptions, IndentType}; use futures::{stream::FuturesUnordered, StreamExt}; use std::{fs, path::Path, process::exit}; @@ -35,7 +36,8 @@ impl Autoformat { } if let Some(raw) = self.raw { - if let Some(inner) = dioxus_autofmt::fmt_block(&raw, 0) { + let indent = indentation_for(".")?; + if let Some(inner) = dioxus_autofmt::fmt_block(&raw, 0, indent) { println!("{}", inner); } else { // exit process with error @@ -46,17 +48,21 @@ impl Autoformat { // Format single file if let Some(file) = self.file { - let file_content = if file == "-" { + let file_content; + let indent; + if file == "-" { + indent = indentation_for(".")?; let mut contents = String::new(); std::io::stdin().read_to_string(&mut contents)?; - Ok(contents) + file_content = Ok(contents); } else { - fs::read_to_string(&file) + indent = indentation_for(".")?; + file_content = fs::read_to_string(&file); }; match file_content { Ok(s) => { - let edits = dioxus_autofmt::fmt_file(&s); + let edits = dioxus_autofmt::fmt_file(&s, indent); let out = dioxus_autofmt::apply_formats(&s, edits); if file == "-" { print!("{}", out); @@ -93,6 +99,12 @@ async fn autoformat_project(check: bool) -> Result<()> { let mut files_to_format = vec![]; collect_rs_files(&crate_config.crate_dir, &mut files_to_format); + if files_to_format.is_empty() { + return Ok(()); + } + + let indent = indentation_for(&files_to_format[0])?; + let counts = files_to_format .into_iter() .filter(|file| { @@ -104,10 +116,11 @@ async fn autoformat_project(check: bool) -> Result<()> { }) .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); + let edits = dioxus_autofmt::fmt_file(&contents, _indent.clone()); let len = edits.len(); if !edits.is_empty() { @@ -151,6 +164,49 @@ async fn autoformat_project(check: bool) -> Result<()> { Ok(()) } +fn indentation_for(file_or_dir: impl AsRef) -> Result { + let out = std::process::Command::new("cargo") + .args(["fmt", "--", "--print-config", "current"]) + .arg(file_or_dir.as_ref()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::inherit()) + .output()?; + if !out.status.success() { + return Err(Error::CargoError("cargo fmt failed".into())); + } + + let config = String::from_utf8_lossy(&out.stdout); + + let hard_tabs = config + .lines() + .find(|line| line.starts_with("hard_tabs ")) + .and_then(|line| line.split_once('=')) + .map(|(_, value)| value.trim() == "true") + .ok_or_else(|| { + Error::RuntimeError("Could not find hard_tabs option in rustfmt config".into()) + })?; + let tab_spaces = config + .lines() + .find(|line| line.starts_with("tab_spaces ")) + .and_then(|line| line.split_once('=')) + .map(|(_, value)| value.trim().parse::()) + .ok_or_else(|| { + Error::RuntimeError("Could not find tab_spaces option in rustfmt config".into()) + })? + .map_err(|_| { + Error::RuntimeError("Could not parse tab_spaces option in rustfmt config".into()) + })?; + + Ok(IndentOptions::new( + if hard_tabs { + IndentType::Tabs + } else { + IndentType::Spaces + }, + tab_spaces, + )) +} + fn collect_rs_files(folder: &Path, files: &mut Vec) { let Ok(folder) = folder.read_dir() else { return; diff --git a/packages/extension/src/lib.rs b/packages/extension/src/lib.rs index abcdaf598..fb9cca8a9 100644 --- a/packages/extension/src/lib.rs +++ b/packages/extension/src/lib.rs @@ -1,17 +1,39 @@ //! This file exports functions into the vscode extension -use dioxus_autofmt::FormattedBlock; +use dioxus_autofmt::{FormattedBlock, IndentOptions, IndentType}; use wasm_bindgen::prelude::*; #[wasm_bindgen] -pub fn format_rsx(raw: String) -> String { - let block = dioxus_autofmt::fmt_block(&raw, 0); +pub fn format_rsx(raw: String, use_tabs: bool, indent_size: usize) -> String { + let block = dioxus_autofmt::fmt_block( + &raw, + 0, + IndentOptions::new( + if use_tabs { + IndentType::Tabs + } else { + IndentType::Spaces + }, + indent_size, + ), + ); block.unwrap() } #[wasm_bindgen] -pub fn format_selection(raw: String) -> String { - let block = dioxus_autofmt::fmt_block(&raw, 0); +pub fn format_selection(raw: String, use_tabs: bool, indent_size: usize) -> String { + let block = dioxus_autofmt::fmt_block( + &raw, + 0, + IndentOptions::new( + if use_tabs { + IndentType::Tabs + } else { + IndentType::Spaces + }, + indent_size, + ), + ); block.unwrap() } @@ -35,8 +57,18 @@ impl FormatBlockInstance { } #[wasm_bindgen] -pub fn format_file(contents: String) -> FormatBlockInstance { - let _edits = dioxus_autofmt::fmt_file(&contents); +pub fn format_file(contents: String, use_tabs: bool, indent_size: usize) -> FormatBlockInstance { + let _edits = dioxus_autofmt::fmt_file( + &contents, + IndentOptions::new( + if use_tabs { + IndentType::Tabs + } else { + IndentType::Spaces + }, + indent_size, + ), + ); let out = dioxus_autofmt::apply_formats(&contents, _edits.clone()); FormatBlockInstance { new: out, _edits } } diff --git a/packages/extension/src/main.ts b/packages/extension/src/main.ts index fc12457ad..4ceee487c 100644 --- a/packages/extension/src/main.ts +++ b/packages/extension/src/main.ts @@ -90,7 +90,7 @@ function fmtDocument(document: vscode.TextDocument) { if (!editor) return; // Need an editor to apply text edits. const contents = editor.document.getText(); - const formatted = dioxus.format_file(contents); + const formatted = dioxus.format_file(contents, !editor.options.insertSpaces, editor.options.tabSize); // Replace the entire text document // Yes, this is a bit heavy handed, but the dioxus side doesn't know the line/col scheme that vscode is using From 0f2923a385c94e13f53ba6920a632ed21d9fcc8d Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Thu, 2 Nov 2023 13:17:21 -0500 Subject: [PATCH 18/83] fix extension types --- packages/extension/src/main.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/extension/src/main.ts b/packages/extension/src/main.ts index 4ceee487c..76b7261f1 100644 --- a/packages/extension/src/main.ts +++ b/packages/extension/src/main.ts @@ -90,7 +90,13 @@ function fmtDocument(document: vscode.TextDocument) { if (!editor) return; // Need an editor to apply text edits. const contents = editor.document.getText(); - const formatted = dioxus.format_file(contents, !editor.options.insertSpaces, editor.options.tabSize); + let tabSize: number; + if (typeof editor.options.tabSize === 'number') { + tabSize = editor.options.tabSize; + } else { + tabSize = 4; + } + const formatted = dioxus.format_file(contents, !editor.options.insertSpaces, tabSize); // Replace the entire text document // Yes, this is a bit heavy handed, but the dioxus side doesn't know the line/col scheme that vscode is using From 0aa4875ec0b32e85f8d2d4e23997dacb9ddec3b6 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Thu, 2 Nov 2023 13:59:46 -0500 Subject: [PATCH 19/83] fix formating --- packages/autofmt/tests/wrong.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/autofmt/tests/wrong.rs b/packages/autofmt/tests/wrong.rs index 145d03807..06a0f00d1 100644 --- a/packages/autofmt/tests/wrong.rs +++ b/packages/autofmt/tests/wrong.rs @@ -1,4 +1,4 @@ -use dioxus_autofmt::{IndentType, IndentOptions}; +use dioxus_autofmt::{IndentOptions, IndentType}; macro_rules! twoway { ($val:literal => $name:ident ($indent:expr)) => { From b9554fd744426eeb1fd2ae03202ec9c57f8d5d58 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Sun, 5 Nov 2023 08:32:39 -0600 Subject: [PATCH 20/83] add a noop evaluator to the ssr renderer --- .../examples/axum-hello-world/src/main.rs | 1 + packages/fullstack/src/render.rs | 2 + packages/ssr/Cargo.toml | 3 ++ packages/ssr/src/eval.rs | 42 +++++++++++++++++++ packages/ssr/src/incremental.rs | 1 + packages/ssr/src/lib.rs | 2 + 6 files changed, 51 insertions(+) create mode 100644 packages/ssr/src/eval.rs diff --git a/packages/fullstack/examples/axum-hello-world/src/main.rs b/packages/fullstack/examples/axum-hello-world/src/main.rs index 8f1d3c8c6..64e5b44a0 100644 --- a/packages/fullstack/examples/axum-hello-world/src/main.rs +++ b/packages/fullstack/examples/axum-hello-world/src/main.rs @@ -24,6 +24,7 @@ fn app(cx: Scope) -> Element { let mut count = use_state(cx, || 0); let text = use_state(cx, || "...".to_string()); + let eval = use_eval(cx); cx.render(rsx! { div { diff --git a/packages/fullstack/src/render.rs b/packages/fullstack/src/render.rs index cda41f82c..886a5bd99 100644 --- a/packages/fullstack/src/render.rs +++ b/packages/fullstack/src/render.rs @@ -45,6 +45,8 @@ impl SsrRendererPool { .expect("couldn't spawn runtime") .block_on(async move { let mut vdom = VirtualDom::new_with_props(component, props); + // Make sure the evaluator is initialized + dioxus_ssr::eval::init_eval(vdom.base_scope()); let mut to = WriteBuffer { buffer: Vec::new() }; // before polling the future, we need to set the context let prev_context = diff --git a/packages/ssr/Cargo.toml b/packages/ssr/Cargo.toml index f6376452d..71f5b26a0 100644 --- a/packages/ssr/Cargo.toml +++ b/packages/ssr/Cargo.toml @@ -10,6 +10,7 @@ keywords = ["dom", "ui", "gui", "react", "ssr"] [dependencies] dioxus-core = { workspace = true, features = ["serialize"] } +dioxus-html = { workspace = true } askama_escape = "0.10.3" thiserror = "1.0.23" rustc-hash = "1.1.0" @@ -17,6 +18,8 @@ lru = "0.10.0" tracing = { workspace = true } http = "0.2.9" tokio = { version = "1.28", features = ["full"], optional = true } +async-trait = "0.1.58" +serde_json = { version = "1.0" } [dev-dependencies] dioxus = { workspace = true } diff --git a/packages/ssr/src/eval.rs b/packages/ssr/src/eval.rs new file mode 100644 index 000000000..2ab74f4e1 --- /dev/null +++ b/packages/ssr/src/eval.rs @@ -0,0 +1,42 @@ +use async_trait::async_trait; +use dioxus_core::ScopeState; +use dioxus_html::prelude::{EvalError, EvalProvider, Evaluator}; +use std::rc::Rc; + +/// Provides the SSREvalProvider through [`cx.provide_context`]. +pub fn init_eval(cx: &ScopeState) { + let provider: Rc = Rc::new(SSREvalProvider {}); + cx.provide_context(provider); +} + +/// Reprents the ssr-target's provider of evaluators. +pub struct SSREvalProvider; +impl EvalProvider for SSREvalProvider { + fn new_evaluator(&self, _: String) -> Result, EvalError> { + Ok(Rc::new(SSREvaluator) as Rc) + } +} + +/// Represents a ssr-target's JavaScript evaluator. +pub struct SSREvaluator; + +// In ssr rendering we never run or resolve evals. +#[async_trait(?Send)] +impl Evaluator for SSREvaluator { + /// Runs the evaluated JavaScript. + async fn join(&self) -> Result { + std::future::pending::<()>().await; + unreachable!() + } + + /// Sends a message to the evaluated JavaScript. + fn send(&self, _el: serde_json::Value) -> Result<(), EvalError> { + Ok(()) + } + + /// Gets an UnboundedReceiver to receive messages from the evaluated JavaScript. + async fn recv(&self) -> Result { + std::future::pending::<()>().await; + unreachable!() + } +} diff --git a/packages/ssr/src/incremental.rs b/packages/ssr/src/incremental.rs index c3bb25314..34ffa3443 100644 --- a/packages/ssr/src/incremental.rs +++ b/packages/ssr/src/incremental.rs @@ -81,6 +81,7 @@ impl IncrementalRenderer { let mut html_buffer = WriteBuffer { buffer: Vec::new() }; { let mut vdom = VirtualDom::new_with_props(comp, props); + crate::eval::init_eval(vdom.base_scope()); rebuild_with(&mut vdom).await; renderer.render_before_body(&mut *html_buffer)?; diff --git a/packages/ssr/src/lib.rs b/packages/ssr/src/lib.rs index 6794d1f14..fdc0e9333 100644 --- a/packages/ssr/src/lib.rs +++ b/packages/ssr/src/lib.rs @@ -10,6 +10,7 @@ pub mod incremental; #[cfg(feature = "incremental")] mod incremental_cfg; +pub mod eval; pub mod renderer; pub mod template; @@ -42,6 +43,7 @@ pub fn render_lazy(f: LazyNodes<'_, '_>) -> String { }; let mut dom = VirtualDom::new_with_props(lazy_app, props); + crate::eval::init_eval(dom.base_scope()); _ = dom.rebuild(); Renderer::new().render(&dom) From 7f4e2af0c48e33915e96f0ac5e75b4c18e706632 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Mon, 13 Nov 2023 08:17:08 -0600 Subject: [PATCH 21/83] fix string memory leak --- packages/core/src/nodes.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/core/src/nodes.rs b/packages/core/src/nodes.rs index c83b1059a..b6a685ad3 100644 --- a/packages/core/src/nodes.rs +++ b/packages/core/src/nodes.rs @@ -707,7 +707,7 @@ impl<'a, 'b> IntoDynNode<'b> for &'a str { impl IntoDynNode<'_> for String { fn into_vnode(self, cx: &ScopeState) -> DynamicNode { DynamicNode::Text(VText { - value: cx.bump().alloc(self), + value: cx.bump().alloc_str(&self), id: Default::default(), }) } From 83f7ef9a447547c720e310b10e1682dc7762bdbc Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Sun, 19 Nov 2023 09:58:00 -0600 Subject: [PATCH 22/83] add an optional cleanup closure to the use effect hook --- examples/readme.rs | 6 +++ packages/hooks/src/use_effect.rs | 79 ++++++++++++++++++++++++++++---- 2 files changed, 76 insertions(+), 9 deletions(-) diff --git a/examples/readme.rs b/examples/readme.rs index f4668488b..b39c04765 100644 --- a/examples/readme.rs +++ b/examples/readme.rs @@ -11,6 +11,12 @@ fn main() { fn app(cx: Scope) -> Element { let mut count = use_state(cx, || 0); + use_effect(cx, (), move |()| async {}); + + use_effect(cx, (count.get(),), move |(count,)| async move { + move || println!("Count unmounted from {}", count) + }); + cx.render(rsx! { h1 { "High-Five counter: {count}" } button { onclick: move |_| count += 1, "Up high!" } diff --git a/packages/hooks/src/use_effect.rs b/packages/hooks/src/use_effect.rs index e72afe27f..1f5faecdd 100644 --- a/packages/hooks/src/use_effect.rs +++ b/packages/hooks/src/use_effect.rs @@ -1,5 +1,10 @@ use dioxus_core::{ScopeState, TaskId}; -use std::{any::Any, cell::Cell, future::Future}; +use std::{ + any::Any, + cell::{Cell, RefCell}, + future::Future, + rc::Rc, +}; use crate::UseFutureDep; @@ -14,7 +19,7 @@ use crate::UseFutureDep; /// ## Arguments /// /// - `dependencies`: a tuple of references to values that are `PartialEq` + `Clone`. -/// - `future`: a closure that takes the `dependencies` as arguments and returns a `'static` future. +/// - `future`: a closure that takes the `dependencies` as arguments and returns a `'static` future. That future may return nothing or a closure that will be executed when the dependencies change to clean up the effect. /// /// ## Examples /// @@ -33,6 +38,16 @@ use crate::UseFutureDep; /// } /// }); /// +/// // Only fetch the user data when the id changes. +/// use_effect(cx, (id,), |(id,)| { +/// to_owned![name]; +/// async move { +/// let user = fetch_user(id).await; +/// name.set(user.name); +/// move || println!("Cleaning up from {}", id); +/// } +/// }); +/// /// let name = name.get().clone().unwrap_or("Loading...".to_string()); /// /// render!( @@ -45,34 +60,80 @@ use crate::UseFutureDep; /// render!(Profile { id: 0 }) /// } /// ``` -pub fn use_effect(cx: &ScopeState, dependencies: D, future: impl FnOnce(D::Out) -> F) +pub fn use_effect(cx: &ScopeState, dependencies: D, future: impl FnOnce(D::Out) -> R) where - T: 'static, - F: Future + 'static, D: UseFutureDep, + R: UseEffectReturn, { struct UseEffect { needs_regen: bool, task: Cell>, dependencies: Vec>, + cleanup: UseEffectCleanup, + } + + impl Drop for UseEffect { + fn drop(&mut self) { + if let Some(cleanup) = self.cleanup.borrow_mut().take() { + cleanup(); + } + } } let state = cx.use_hook(move || UseEffect { needs_regen: true, task: Cell::new(None), dependencies: Vec::new(), + cleanup: Rc::new(RefCell::new(None)), }); if dependencies.clone().apply(&mut state.dependencies) || state.needs_regen { + // Call the cleanup function if it exists + if let Some(cleanup) = state.cleanup.borrow_mut().take() { + cleanup(); + } + // We don't need regen anymore state.needs_regen = false; // Create the new future - let fut = future(dependencies.out()); + let return_value = future(dependencies.out()); - state.task.set(Some(cx.push_future(async move { - fut.await; - }))); + if let Some(task) = return_value.apply(state.cleanup.clone(), cx) { + state.task.set(Some(task)); + } + } +} + +type UseEffectCleanup = Rc>>>; + +/// Something that can be returned from a `use_effect` hook. +pub trait UseEffectReturn { + fn apply(self, oncleanup: UseEffectCleanup, cx: &ScopeState) -> Option; +} + +impl UseEffectReturn<()> for T +where + T: Future + 'static, +{ + fn apply(self, _: UseEffectCleanup, cx: &ScopeState) -> Option { + Some(cx.push_future(self)) + } +} + +#[doc(hidden)] +pub struct CleanupFutureMarker; +impl UseEffectReturn for T +where + T: Future + 'static, + F: FnOnce() + 'static, +{ + fn apply(self, oncleanup: UseEffectCleanup, cx: &ScopeState) -> Option { + let task = cx.push_future(async move { + let cleanup = self.await; + *oncleanup.borrow_mut() = Some(Box::new(cleanup) as Box); + }); + Some(task) } } From 3c115bbef76f21435d8db886a799a47503026e5f Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Sun, 19 Nov 2023 10:03:18 -0600 Subject: [PATCH 23/83] add into attribute value impl for String --- packages/core/src/nodes.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/core/src/nodes.rs b/packages/core/src/nodes.rs index c83b1059a..b489a7e4d 100644 --- a/packages/core/src/nodes.rs +++ b/packages/core/src/nodes.rs @@ -791,6 +791,12 @@ impl<'a> IntoAttributeValue<'a> for &'a str { } } +impl<'a> IntoAttributeValue<'a> for String { + fn into_value(self, cx: &'a Bump) -> AttributeValue<'a> { + AttributeValue::Text(cx.alloc_str(&self)) + } +} + impl<'a> IntoAttributeValue<'a> for f64 { fn into_value(self, _: &'a Bump) -> AttributeValue<'a> { AttributeValue::Float(self) From 0ee21dff1e962bb5e1c22cfde15ecb4bc07c49fb Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Mon, 20 Nov 2023 09:33:39 -0600 Subject: [PATCH 24/83] fix missing item in hot reloading diffing --- packages/cli/src/logging.rs | 14 +++++- packages/cli/src/server/output.rs | 25 ++++++----- packages/rsx/Cargo.toml | 1 + .../rsx/src/hot_reload/hot_reload_diff.rs | 44 ++++++++++++++++--- .../src/hot_reload/hot_reloading_file_map.rs | 27 +++++++++--- 5 files changed, 87 insertions(+), 24 deletions(-) diff --git a/packages/cli/src/logging.rs b/packages/cli/src/logging.rs index 48c2a2788..31d088737 100644 --- a/packages/cli/src/logging.rs +++ b/packages/cli/src/logging.rs @@ -28,7 +28,19 @@ pub fn set_up_logging() { message = message, )); }) - .level(log::LevelFilter::Info) + .level(match std::env::var("DIOXUS_LOG") { + Ok(level) => match level.to_lowercase().as_str() { + "error" => log::LevelFilter::Error, + "warn" => log::LevelFilter::Warn, + "info" => log::LevelFilter::Info, + "debug" => log::LevelFilter::Debug, + "trace" => log::LevelFilter::Trace, + _ => { + panic!("Invalid log level: {}", level) + } + }, + Err(_) => log::LevelFilter::Info, + }) .chain(std::io::stdout()) .apply() .unwrap(); diff --git a/packages/cli/src/server/output.rs b/packages/cli/src/server/output.rs index 71323dd29..4e148b0f1 100644 --- a/packages/cli/src/server/output.rs +++ b/packages/cli/src/server/output.rs @@ -22,17 +22,20 @@ pub fn print_console_info( options: PrettierOptions, web_info: Option, ) { - if let Ok(native_clearseq) = Command::new(if cfg!(target_os = "windows") { - "cls" - } else { - "clear" - }) - .output() - { - print!("{}", String::from_utf8_lossy(&native_clearseq.stdout)); - } else { - // Try ANSI-Escape characters - print!("\x1b[2J\x1b[H"); + // Don't clear the screen if the user has set the DIOXUS_LOG environment variable to "trace" so that we can see the logs + if Some("trace") != std::env::var("DIOXUS_LOG").ok().as_deref() { + if let Ok(native_clearseq) = Command::new(if cfg!(target_os = "windows") { + "cls" + } else { + "clear" + }) + .output() + { + print!("{}", String::from_utf8_lossy(&native_clearseq.stdout)); + } else { + // Try ANSI-Escape characters + print!("\x1b[2J\x1b[H"); + } } let mut profile = if config.release { "Release" } else { "Debug" }.to_string(); diff --git a/packages/rsx/Cargo.toml b/packages/rsx/Cargo.toml index bc866acb7..72b51a051 100644 --- a/packages/rsx/Cargo.toml +++ b/packages/rsx/Cargo.toml @@ -20,6 +20,7 @@ quote = { version = "1.0" } serde = { version = "1.0", features = ["derive"], optional = true } internment = { version = "0.7.0", optional = true } krates = { version = "0.12.6", optional = true } +tracing.workspace = true [features] hot_reload = ["krates", "internment"] diff --git a/packages/rsx/src/hot_reload/hot_reload_diff.rs b/packages/rsx/src/hot_reload/hot_reload_diff.rs index 22a01875d..7e19d3aad 100644 --- a/packages/rsx/src/hot_reload/hot_reload_diff.rs +++ b/packages/rsx/src/hot_reload/hot_reload_diff.rs @@ -1,4 +1,5 @@ use proc_macro2::TokenStream; +use quote::ToTokens; use syn::{File, Macro}; pub enum DiffResult { @@ -10,13 +11,30 @@ pub enum DiffResult { pub fn find_rsx(new: &File, old: &File) -> DiffResult { let mut rsx_calls = Vec::new(); if new.items.len() != old.items.len() { + tracing::trace!( + "found not hot reload-able change {:#?} != {:#?}", + new.items + .iter() + .map(|i| i.to_token_stream().to_string()) + .collect::>(), + old.items + .iter() + .map(|i| i.to_token_stream().to_string()) + .collect::>() + ); return DiffResult::CodeChanged; } for (new, old) in new.items.iter().zip(old.items.iter()) { if find_rsx_item(new, old, &mut rsx_calls) { + tracing::trace!( + "found not hot reload-able change {:#?} != {:#?}", + new.to_token_stream().to_string(), + old.to_token_stream().to_string() + ); return DiffResult::CodeChanged; } } + tracing::trace!("found hot reload-able changes {:#?}", rsx_calls); DiffResult::RsxChanged(rsx_calls) } @@ -94,6 +112,9 @@ fn find_rsx_item( (syn::ImplItem::Macro(new_item), syn::ImplItem::Macro(old_item)) => { old_item != new_item } + (syn::ImplItem::Verbatim(stream), syn::ImplItem::Verbatim(stream2)) => { + stream.to_string() != stream2.to_string() + } _ => true, } { return true; @@ -186,10 +207,12 @@ fn find_rsx_trait( } } (syn::TraitItem::Fn(new_item), syn::TraitItem::Fn(old_item)) => { - if let (Some(new_block), Some(old_block)) = (&new_item.default, &old_item.default) { - find_rsx_block(new_block, old_block, rsx_calls) - } else { - true + match (&new_item.default, &old_item.default) { + (Some(new_block), Some(old_block)) => { + find_rsx_block(new_block, old_block, rsx_calls) + } + (None, None) => false, + _ => true, } } (syn::TraitItem::Type(new_item), syn::TraitItem::Type(old_item)) => { @@ -198,6 +221,9 @@ fn find_rsx_trait( (syn::TraitItem::Macro(new_item), syn::TraitItem::Macro(old_item)) => { old_item != new_item } + (syn::TraitItem::Verbatim(stream), syn::TraitItem::Verbatim(stream2)) => { + stream.to_string() != stream2.to_string() + } _ => true, } { return true; @@ -355,6 +381,11 @@ fn find_rsx_expr( || new_expr.or2_token != old_expr.or2_token || new_expr.output != old_expr.output } + (syn::Expr::Const(new_expr), syn::Expr::Const(old_expr)) => { + find_rsx_block(&new_expr.block, &old_expr.block, rsx_calls) + || new_expr.attrs != old_expr.attrs + || new_expr.const_token != old_expr.const_token + } (syn::Expr::Continue(new_expr), syn::Expr::Continue(old_expr)) => old_expr != new_expr, (syn::Expr::Field(new_expr), syn::Expr::Field(old_expr)) => { find_rsx_expr(&new_expr.base, &old_expr.base, rsx_calls) @@ -402,6 +433,7 @@ fn find_rsx_expr( || new_expr.attrs != old_expr.attrs || new_expr.bracket_token != old_expr.bracket_token } + (syn::Expr::Infer(new_expr), syn::Expr::Infer(old_expr)) => new_expr != old_expr, (syn::Expr::Let(new_expr), syn::Expr::Let(old_expr)) => { find_rsx_expr(&new_expr.expr, &old_expr.expr, rsx_calls) || new_expr.attrs != old_expr.attrs @@ -589,7 +621,9 @@ fn find_rsx_expr( _ => true, } } - (syn::Expr::Verbatim(_), syn::Expr::Verbatim(_)) => false, + (syn::Expr::Verbatim(stream), syn::Expr::Verbatim(stream2)) => { + stream.to_string() != stream2.to_string() + } _ => true, } } diff --git a/packages/rsx/src/hot_reload/hot_reloading_file_map.rs b/packages/rsx/src/hot_reload/hot_reloading_file_map.rs index 0393142b4..7e36dddf9 100644 --- a/packages/rsx/src/hot_reload/hot_reloading_file_map.rs +++ b/packages/rsx/src/hot_reload/hot_reloading_file_map.rs @@ -51,17 +51,24 @@ impl FileMap { fn find_rs_files( root: PathBuf, filter: &mut impl FnMut(&Path) -> bool, - ) -> io::Result { + ) -> FileMapSearchResult { let mut files = HashMap::new(); let mut errors = Vec::new(); if root.is_dir() { - for entry in (fs::read_dir(root)?).flatten() { + let read_dir = match fs::read_dir(root) { + Ok(read_dir) => read_dir, + Err(err) => { + errors.push(err); + return FileMapSearchResult { map: files, errors }; + } + }; + for entry in read_dir.flatten() { let path = entry.path(); if !filter(&path) { let FileMapSearchResult { map, errors: child_errors, - } = find_rs_files(path, filter)?; + } = find_rs_files(path, filter); errors.extend(child_errors); files.extend(map); } @@ -69,14 +76,20 @@ impl FileMap { } else if root.extension().and_then(|s| s.to_str()) == Some("rs") { if let Ok(mut file) = File::open(root.clone()) { let mut src = String::new(); - file.read_to_string(&mut src)?; - files.insert(root, (src, None)); + match file.read_to_string(&mut src) { + Ok(_) => { + files.insert(root, (src, None)); + } + Err(err) => { + errors.push(err); + } + } } } - Ok(FileMapSearchResult { map: files, errors }) + FileMapSearchResult { map: files, errors } } - let FileMapSearchResult { map, errors } = find_rs_files(path, &mut filter)?; + let FileMapSearchResult { map, errors } = find_rs_files(path, &mut filter); let result = Self { map, in_workspace: HashMap::new(), From 8cf8f66c272e0bc13942d7fa01c1adfae3d2155d Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Mon, 20 Nov 2023 09:47:03 -0600 Subject: [PATCH 25/83] add more logging to desktop hot reloading --- packages/cli/src/server/desktop/mod.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/cli/src/server/desktop/mod.rs b/packages/cli/src/server/desktop/mod.rs index 978b97d43..be722323b 100644 --- a/packages/cli/src/server/desktop/mod.rs +++ b/packages/cli/src/server/desktop/mod.rs @@ -73,6 +73,7 @@ pub async fn serve(config: CrateConfig, hot_reload_state: Option 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; @@ -212,6 +213,7 @@ fn send_msg(msg: HotReloadMsg, channel: &mut impl std::io::Write) -> bool { pub fn start_desktop(config: &CrateConfig) -> Result<(Child, BuildResult)> { // Run the desktop application + log::trace!("Building application"); let result = crate::builder::build_desktop(config, true)?; match &config.executable { @@ -222,6 +224,7 @@ pub fn start_desktop(config: &CrateConfig) -> Result<(Child, BuildResult)> { if cfg!(windows) { file.set_extension("exe"); } + log::trace!("Running application from {:?}", file); let child = Command::new(file.to_str().unwrap()).spawn()?; Ok((child, result)) From 7a459e15d8316abfdb5b39d25deb4fff9318fbfe Mon Sep 17 00:00:00 2001 From: ealmloff Date: Tue, 21 Nov 2023 16:28:06 -0600 Subject: [PATCH 26/83] Update packages/hooks/src/use_effect.rs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Marc Espín --- packages/hooks/src/use_effect.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/hooks/src/use_effect.rs b/packages/hooks/src/use_effect.rs index 1f5faecdd..6fb2fcf9e 100644 --- a/packages/hooks/src/use_effect.rs +++ b/packages/hooks/src/use_effect.rs @@ -44,7 +44,7 @@ use crate::UseFutureDep; /// async move { /// let user = fetch_user(id).await; /// name.set(user.name); -/// move || println!("Cleaning up from {}", id); +/// move || println!("Cleaning up from {}", id) /// } /// }); /// From 017d7e96bf1ed70463f01d3fb9dc52824179269e Mon Sep 17 00:00:00 2001 From: ealmloff Date: Tue, 21 Nov 2023 16:28:31 -0600 Subject: [PATCH 27/83] restore readme.rs --- examples/readme.rs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/examples/readme.rs b/examples/readme.rs index b39c04765..f4668488b 100644 --- a/examples/readme.rs +++ b/examples/readme.rs @@ -11,12 +11,6 @@ fn main() { fn app(cx: Scope) -> Element { let mut count = use_state(cx, || 0); - use_effect(cx, (), move |()| async {}); - - use_effect(cx, (count.get(),), move |(count,)| async move { - move || println!("Count unmounted from {}", count) - }); - cx.render(rsx! { h1 { "High-Five counter: {count}" } button { onclick: move |_| count += 1, "Up high!" } From 1c0b33cef44678beab17bbcccaeabff48f3c2027 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Sun, 26 Nov 2023 09:21:27 -0600 Subject: [PATCH 28/83] fix hot reloading svg elements --- packages/hot-reload/src/file_watcher.rs | 2 +- packages/html/src/elements.rs | 53 +++++++++++++++++++++++-- 2 files changed, 50 insertions(+), 5 deletions(-) diff --git a/packages/hot-reload/src/file_watcher.rs b/packages/hot-reload/src/file_watcher.rs index 2509dd789..5b8b76b37 100644 --- a/packages/hot-reload/src/file_watcher.rs +++ b/packages/hot-reload/src/file_watcher.rs @@ -122,7 +122,7 @@ pub fn init(cfg: Config) { } = cfg; if let Ok(crate_dir) = PathBuf::from_str(root_path) { - // try to find the gitingore file + // try to find the gitignore file let gitignore_file_path = crate_dir.join(".gitignore"); let (gitignore, _) = ignore::gitignore::Gitignore::new(gitignore_file_path); diff --git a/packages/html/src/elements.rs b/packages/html/src/elements.rs index 6a0e546fa..5e0d0995d 100644 --- a/packages/html/src/elements.rs +++ b/packages/html/src/elements.rs @@ -74,7 +74,7 @@ macro_rules! impl_attribute_match { $attr:ident $fil:ident: $vil:ident (in $ns:literal), ) => { if $attr == stringify!($fil) { - return Some((stringify!(fil), Some(ns))); + return Some((stringify!(fil), Some($ns))); } }; } @@ -180,14 +180,26 @@ macro_rules! impl_element_match { }; ( - $el:ident $name:ident $namespace:tt { + $el:ident $name:ident $namespace:literal { $( $fil:ident: $vil:ident $extra:tt, )* } ) => { if $el == stringify!($name) { - return Some((stringify!($name), Some(stringify!($namespace)))); + return dbg!(Some((stringify!($name), Some($namespace)))); + } + }; + + ( + $el:ident $name:ident [$_:literal, $namespace:tt] { + $( + $fil:ident: $vil:ident $extra:tt, + )* + } + ) => { + if $el == stringify!($name) { + return dbg!(Some((stringify!($name), Some($namespace)))); } }; } @@ -207,6 +219,8 @@ macro_rules! impl_element_match_attributes { $attr $fil: $vil ($extra), ); )* + + return impl_map_global_attributes!($el $attr $name None); } }; @@ -223,10 +237,41 @@ macro_rules! impl_element_match_attributes { $attr $fil: $vil ($extra), ); )* + + return impl_map_global_attributes!($el $attr $name $namespace); } } } +#[cfg(feature = "hot-reload-context")] +macro_rules! impl_map_global_attributes { + ( + $el:ident $attr:ident $element:ident None + ) => { + map_global_attributes($attr) + }; + + ( + $el:ident $attr:ident $element:ident $namespace:literal + ) => { + if $namespace == "http://www.w3.org/2000/svg" { + map_svg_attributes($attr) + } else { + map_global_attributes($attr) + } + }; + + ( + $el:ident $attr:ident $element:ident [$name:literal, $namespace:tt] + ) => { + if $namespace == "http://www.w3.org/2000/svg" { + map_svg_attributes($attr) + } else { + map_global_attributes($attr) + } + }; +} + macro_rules! builder_constructors { ( $( @@ -254,7 +299,7 @@ macro_rules! builder_constructors { } ); )* - map_global_attributes(attribute).or_else(|| map_svg_attributes(attribute)) + None } fn map_element(element: &str) -> Option<(&'static str, Option<&'static str>)> { From 141554a7861f8c589f246a611f10c332f4e8a711 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Sun, 26 Nov 2023 09:23:27 -0600 Subject: [PATCH 29/83] remove logging --- packages/html/src/elements.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/html/src/elements.rs b/packages/html/src/elements.rs index 5e0d0995d..d7db36a04 100644 --- a/packages/html/src/elements.rs +++ b/packages/html/src/elements.rs @@ -187,7 +187,7 @@ macro_rules! impl_element_match { } ) => { if $el == stringify!($name) { - return dbg!(Some((stringify!($name), Some($namespace)))); + return Some((stringify!($name), Some($namespace))); } }; @@ -199,7 +199,7 @@ macro_rules! impl_element_match { } ) => { if $el == stringify!($name) { - return dbg!(Some((stringify!($name), Some($namespace)))); + return Some((stringify!($name), Some($namespace))); } }; } From be94c69f116ede6bec01373b1a47277256fd2db9 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Wed, 29 Nov 2023 11:38:28 -0600 Subject: [PATCH 30/83] make optional props accept T or Option --- examples/optional_props.rs | 6 +++++ packages/core-macro/src/props/mod.rs | 33 ++++++++-------------------- 2 files changed, 15 insertions(+), 24 deletions(-) diff --git a/examples/optional_props.rs b/examples/optional_props.rs index c5652a2e7..d5cf1e711 100644 --- a/examples/optional_props.rs +++ b/examples/optional_props.rs @@ -12,6 +12,12 @@ fn main() { fn app(cx: Scope) -> Element { cx.render(rsx! { + Button { + a: "asd".to_string(), + c: "asd".to_string(), + d: Some("asd".to_string()), + e: Some("asd".to_string()), + } Button { a: "asd".to_string(), c: "asd".to_string(), diff --git a/packages/core-macro/src/props/mod.rs b/packages/core-macro/src/props/mod.rs index 6e6c43d66..f8450e36a 100644 --- a/packages/core-macro/src/props/mod.rs +++ b/packages/core-macro/src/props/mod.rs @@ -783,31 +783,16 @@ Finally, call `.build()` to create the instance of `{name}`. None => quote!(), }; - // NOTE: both auto_into and strip_option affect `arg_type` and `arg_expr`, but the order of - // nesting is different so we have to do this little dance. - let arg_type = if field.builder_attr.strip_option { - field.type_from_inside_option(false).ok_or_else(|| { - Error::new_spanned( - field_type, - "can't `strip_option` - field is not `Option<...>`", + let arg_type = field_type; + let (arg_type, arg_expr) = + if field.builder_attr.auto_into || field.builder_attr.strip_option { + ( + quote!(impl ::core::convert::Into<#arg_type>), + quote!(#field_name.into()), ) - })? - } else { - field_type - }; - let (arg_type, arg_expr) = if field.builder_attr.auto_into { - ( - quote!(impl ::core::convert::Into<#arg_type>), - quote!(#field_name.into()), - ) - } else { - (quote!(#arg_type), quote!(#field_name)) - }; - let arg_expr = if field.builder_attr.strip_option { - quote!(Some(#arg_expr)) - } else { - arg_expr - }; + } else { + (quote!(#arg_type), quote!(#field_name)) + }; let repeated_fields_error_type_name = syn::Ident::new( &format!( From 533c7bab492d121b79b126458429fc5774c3a39e Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Wed, 29 Nov 2023 11:39:38 -0600 Subject: [PATCH 31/83] show more cases in the optional props example --- examples/optional_props.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/examples/optional_props.rs b/examples/optional_props.rs index d5cf1e711..8108d437d 100644 --- a/examples/optional_props.rs +++ b/examples/optional_props.rs @@ -20,10 +20,16 @@ fn app(cx: Scope) -> Element { } Button { a: "asd".to_string(), + b: "asd".to_string(), c: "asd".to_string(), d: Some("asd".to_string()), e: "asd".to_string(), } + Button { + a: "asd".to_string(), + c: "asd".to_string(), + d: Some("asd".to_string()), + } }) } From a840e012d81d6b2de5b3ec7fcd91a65552c40a18 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Wed, 29 Nov 2023 11:46:18 -0600 Subject: [PATCH 32/83] fix clippy --- packages/core-macro/src/props/mod.rs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/packages/core-macro/src/props/mod.rs b/packages/core-macro/src/props/mod.rs index f8450e36a..d7a580705 100644 --- a/packages/core-macro/src/props/mod.rs +++ b/packages/core-macro/src/props/mod.rs @@ -243,10 +243,6 @@ mod field_info { } .into() } - - pub fn type_from_inside_option(&self, check_option_name: bool) -> Option<&syn::Type> { - type_from_inside_option(self.ty, check_option_name) - } } #[derive(Debug, Default, Clone)] From 0a3b794a1cc3a9c215ca37b0d0510f70850778b5 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Fri, 1 Dec 2023 15:56:14 -0600 Subject: [PATCH 33/83] add a warning about wry gnu support to dioxus desktop --- packages/desktop/src/lib.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/packages/desktop/src/lib.rs b/packages/desktop/src/lib.rs index 63a8914f3..13d52b032 100644 --- a/packages/desktop/src/lib.rs +++ b/packages/desktop/src/lib.rs @@ -19,6 +19,17 @@ mod webview; #[cfg(any(target_os = "ios", target_os = "android"))] mod mobile_shortcut; +// WARN about wry support on windows gnu targets. GNU windows targets don't work well in wry currently +#[cfg(all(windows, target_env = "gnu"))] +mod wry_gnu_warning { + #[allow(dead_code)] + #[must_use = "GNU windows targets can have issues with Wry. Using the MSVC toolchain is recommended"] + struct WryGnuWarning; + const _: () = { + let dont_use_gnu = WryGnuWarning; + }; +} + use crate::query::QueryResult; pub use cfg::{Config, WindowCloseBehaviour}; pub use desktop_context::DesktopContext; From a4600294c5c5dfc9c130b0db652d7ba2d036a1e8 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Fri, 1 Dec 2023 22:17:51 -0600 Subject: [PATCH 34/83] allow users to disable the warning in a feature --- packages/desktop/Cargo.toml | 1 + packages/desktop/src/lib.rs | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/desktop/Cargo.toml b/packages/desktop/Cargo.toml index dcb994120..f0ea9e189 100644 --- a/packages/desktop/Cargo.toml +++ b/packages/desktop/Cargo.toml @@ -59,6 +59,7 @@ devtools = ["wry/devtools"] tray = ["wry/tray"] dox = ["wry/dox"] hot-reload = ["dioxus-hot-reload"] +gnu = [] [package.metadata.docs.rs] default-features = false diff --git a/packages/desktop/src/lib.rs b/packages/desktop/src/lib.rs index 13d52b032..9a5ba6c64 100644 --- a/packages/desktop/src/lib.rs +++ b/packages/desktop/src/lib.rs @@ -20,10 +20,10 @@ mod webview; mod mobile_shortcut; // WARN about wry support on windows gnu targets. GNU windows targets don't work well in wry currently -#[cfg(all(windows, target_env = "gnu"))] +#[cfg(all(windows, target_env = "gnu", not(feature = "gnu")))] mod wry_gnu_warning { #[allow(dead_code)] - #[must_use = "GNU windows targets can have issues with Wry. Using the MSVC toolchain is recommended"] + #[must_use = "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"] struct WryGnuWarning; const _: () = { let dont_use_gnu = WryGnuWarning; From b965fc23e96fb8a56b5e8e4b601bbd76f28ad74f Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Wed, 6 Dec 2023 17:01:51 -0600 Subject: [PATCH 35/83] use a temp directory for the hot reloading pipe on desktop, fullstack and liveview --- packages/cli/src/server/desktop/mod.rs | 5 +++-- packages/hot-reload/src/file_watcher.rs | 7 ++++--- packages/hot-reload/src/lib.rs | 3 ++- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/packages/cli/src/server/desktop/mod.rs b/packages/cli/src/server/desktop/mod.rs index 98d6e9244..6373487b3 100644 --- a/packages/cli/src/server/desktop/mod.rs +++ b/packages/cli/src/server/desktop/mod.rs @@ -109,7 +109,8 @@ pub async fn serve(config: CrateConfig, hot_reload_state: Option } async fn start_desktop_hot_reload(hot_reload_state: HotReloadState) -> Result<()> { - match LocalSocketListener::bind("@dioxusin") { + let path = std::env::temp_dir().join("dioxusin"); + match LocalSocketListener::bind(path) { Ok(local_socket_stream) => { let aborted = Arc::new(Mutex::new(false)); // States @@ -188,7 +189,7 @@ fn clear_paths() { // We check if the file socket is already open from an old session and then delete it let paths = ["./dioxusin", "./@dioxusin"]; for path in paths { - let path = std::path::PathBuf::from(path); + let path = std::env::temp_dir().join(path); if path.exists() { let _ = std::fs::remove_file(path); } diff --git a/packages/hot-reload/src/file_watcher.rs b/packages/hot-reload/src/file_watcher.rs index 2509dd789..bbd0a7660 100644 --- a/packages/hot-reload/src/file_watcher.rs +++ b/packages/hot-reload/src/file_watcher.rs @@ -157,16 +157,17 @@ pub fn init(cfg: Config) { // 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 - let paths = ["./dioxusin", "./@dioxusin"]; + let paths = ["./dioxusin"]; for path in paths { - let path = PathBuf::from(path); + let path = std::env::temp_dir().join(path); if path.exists() { let _ = std::fs::remove_file(path); } } } - match LocalSocketListener::bind("@dioxusin") { + let path = std::env::temp_dir().join("dioxusin"); + match LocalSocketListener::bind(path) { Ok(local_socket_stream) => { let aborted = Arc::new(Mutex::new(false)); diff --git a/packages/hot-reload/src/lib.rs b/packages/hot-reload/src/lib.rs index 68692b72b..07bd70a8d 100644 --- a/packages/hot-reload/src/lib.rs +++ b/packages/hot-reload/src/lib.rs @@ -24,7 +24,8 @@ pub enum HotReloadMsg { /// Connect to the hot reloading listener. The callback provided will be called every time a template change is detected pub fn connect(mut f: impl FnMut(HotReloadMsg) + Send + 'static) { std::thread::spawn(move || { - if let Ok(socket) = LocalSocketStream::connect("@dioxusin") { + let path = std::env::temp_dir().join("dioxusin"); + if let Ok(socket) = LocalSocketStream::connect(path) { let mut buf_reader = BufReader::new(socket); loop { let mut buf = String::new(); From ab1fab5f50e5e9b487ce2f7e4535d659b1d3e274 Mon Sep 17 00:00:00 2001 From: Jonathan Kelley Date: Wed, 6 Dec 2023 16:49:05 -0800 Subject: [PATCH 36/83] No publish demos --- examples/openid_connect_demo/Cargo.toml | 1 + examples/query_segments_demo/Cargo.toml | 1 + 2 files changed, 2 insertions(+) diff --git a/examples/openid_connect_demo/Cargo.toml b/examples/openid_connect_demo/Cargo.toml index 4c5f47061..2a1abe173 100644 --- a/examples/openid_connect_demo/Cargo.toml +++ b/examples/openid_connect_demo/Cargo.toml @@ -2,6 +2,7 @@ name = "openid_auth_demo" version = "0.1.0" edition = "2021" +publish = false # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/examples/query_segments_demo/Cargo.toml b/examples/query_segments_demo/Cargo.toml index 4a7d784c7..ee9f49c70 100644 --- a/examples/query_segments_demo/Cargo.toml +++ b/examples/query_segments_demo/Cargo.toml @@ -2,6 +2,7 @@ name = "query_segments_demo" version = "0.1.0" edition = "2021" +publish = false # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html From d3f6ff703c0f90cd58da8d459be056db29f3c38e Mon Sep 17 00:00:00 2001 From: Jonathan Kelley Date: Wed, 6 Dec 2023 16:56:35 -0800 Subject: [PATCH 37/83] Release 0.4.3 dioxus@0.4.3 dioxus-autofmt@0.4.3 dioxus-check@0.4.3 dioxus-cli@0.4.3 dioxus-core@0.4.3 dioxus-core-macro@0.4.3 dioxus-desktop@0.4.3 dioxus-fullstack@0.4.3 dioxus-hooks@0.4.3 dioxus-hot-reload@0.4.3 dioxus-html@0.4.3 dioxus-interpreter-js@0.4.3 dioxus-liveview@0.4.3 dioxus-mobile@0.4.3 dioxus-native-core@0.4.3 dioxus-native-core-macro@0.4.3 dioxus-router@0.4.3 dioxus-router-macro@0.4.3 dioxus-rsx@0.4.3 dioxus-signals@0.4.3 dioxus-ssr@0.4.3 dioxus-tui@0.4.3 dioxus-web@0.4.3 dioxus_server_macro@0.4.3 fermi@0.4.3 generational-box@0.4.3 plasmo@0.4.3 rsx-rosetta@0.4.3 Generated by cargo-workspaces --- Cargo.toml | 6 +++--- examples/tailwind/Cargo.toml | 2 +- packages/cli/Cargo.toml | 2 +- packages/generational-box/Cargo.toml | 2 +- packages/signals/Cargo.toml | 4 ++-- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 06e4ca1fa..1772c1f47 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -50,7 +50,7 @@ members = [ exclude = ["examples/mobile_demo"] [workspace.package] -version = "0.4.2" +version = "0.4.3" # dependencies that are shared across packages [workspace.dependencies] @@ -77,7 +77,7 @@ dioxus-native-core = { path = "packages/native-core", version = "0.4.0" } dioxus-native-core-macro = { path = "packages/native-core-macro", version = "0.4.0" } rsx-rosetta = { path = "packages/rsx-rosetta", version = "0.4.0" } dioxus-signals = { path = "packages/signals" } -generational-box = { path = "packages/generational-box", version = "0.1.0" } +generational-box = { path = "packages/generational-box", version = "0.4.3" } dioxus-hot-reload = { path = "packages/hot-reload", version = "0.4.0" } dioxus-fullstack = { path = "packages/fullstack", version = "0.4.1" } dioxus_server_macro = { path = "packages/server-macro", version = "0.4.1" } @@ -99,7 +99,7 @@ prettyplease = { package = "prettier-please", version = "0.2", features = [ # It is not meant to be published, but is used so "cargo run --example XYZ" works properly [package] name = "dioxus-examples" -version = "0.0.0" +version = "0.4.3" authors = ["Jonathan Kelley"] edition = "2021" description = "Top level crate for the Dioxus repository" diff --git a/examples/tailwind/Cargo.toml b/examples/tailwind/Cargo.toml index 5c2fbe666..26ac202f1 100644 --- a/examples/tailwind/Cargo.toml +++ b/examples/tailwind/Cargo.toml @@ -18,4 +18,4 @@ dioxus = { path = "../../packages/dioxus" } dioxus-desktop = { path = "../../packages/desktop" } [target.'cfg(target_arch = "wasm32")'.dependencies] -dioxus-web = { path = "../../packages/web" } \ No newline at end of file +dioxus-web = { path = "../../packages/web" } diff --git a/packages/cli/Cargo.toml b/packages/cli/Cargo.toml index adb0239f2..128133602 100644 --- a/packages/cli/Cargo.toml +++ b/packages/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "dioxus-cli" -version = "0.4.1" +version = "0.4.3" authors = ["Jonathan Kelley"] edition = "2021" description = "CLI tool for developing, testing, and publishing Dioxus apps" diff --git a/packages/generational-box/Cargo.toml b/packages/generational-box/Cargo.toml index 661c9725b..f070c1805 100644 --- a/packages/generational-box/Cargo.toml +++ b/packages/generational-box/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "generational-box" authors = ["Evan Almloff"] -version = "0.1.0" +version = "0.4.3" edition = "2018" description = "A box backed by a generational runtime" license = "MIT OR Apache-2.0" diff --git a/packages/signals/Cargo.toml b/packages/signals/Cargo.toml index 56e19bbd8..34ae671b3 100644 --- a/packages/signals/Cargo.toml +++ b/packages/signals/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "dioxus-signals" authors = ["Jonathan Kelley"] -version = "0.0.0" +version = "0.4.3" edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html @@ -20,4 +20,4 @@ tokio = { version = "1", features = ["full"] } [features] default = [] -serialize = ["serde"] \ No newline at end of file +serialize = ["serde"] From 16982c9f69adcebae9d9f086328bb20b11d6882b Mon Sep 17 00:00:00 2001 From: Jonathan Kelley Date: Wed, 6 Dec 2023 20:54:50 -0800 Subject: [PATCH 38/83] Add metadata for signals crate --- packages/signals/Cargo.toml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/signals/Cargo.toml b/packages/signals/Cargo.toml index 34ae671b3..c85fb6d7f 100644 --- a/packages/signals/Cargo.toml +++ b/packages/signals/Cargo.toml @@ -3,6 +3,12 @@ name = "dioxus-signals" authors = ["Jonathan Kelley"] version = "0.4.3" edition = "2018" +description = "Signals for Dioxus" +license = "MIT OR Apache-2.0" +repository = "https://github.com/DioxusLabs/dioxus/" +homepage = "https://dioxuslabs.com" +keywords = ["dom", "ui", "gui", "react", "wasm"] +rust-version = "1.60.0" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html From 69bf6b9dd7a8872e38a846ea8094d76589d05b21 Mon Sep 17 00:00:00 2001 From: Jonathan Kelley Date: Wed, 6 Dec 2023 21:27:26 -0800 Subject: [PATCH 39/83] CI: adjust matrix test to install rustfmt during autofmt tests --- .github/workflows/main.yml | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 037525557..1b1f1ed7b 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -124,8 +124,6 @@ jobs: } steps: - - uses: actions/checkout@v4 - - name: install stable uses: dtolnay/rust-toolchain@master with: @@ -141,6 +139,11 @@ jobs: workspaces: core -> ../target save-if: ${{ matrix.features.key == 'all' }} + - name: Install rustfmt + run: rustup component add rustfmt + + - uses: actions/checkout@v4 + - name: test run: | ${{ env.RUST_CARGO_COMMAND }} ${{ matrix.platform.command }} ${{ matrix.platform.args }} --target ${{ matrix.platform.target }} From 9a13df2c737b4232bcf76946eff2cbac5d111896 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Thu, 7 Dec 2023 07:00:59 -0600 Subject: [PATCH 40/83] move hot reload socket into the target directory --- packages/cli/src/server/desktop/mod.rs | 21 +++++++++++---------- packages/hot-reload/src/file_watcher.rs | 14 ++++++-------- packages/hot-reload/src/lib.rs | 7 +++++-- 3 files changed, 22 insertions(+), 20 deletions(-) diff --git a/packages/cli/src/server/desktop/mod.rs b/packages/cli/src/server/desktop/mod.rs index 6373487b3..86f9d971a 100644 --- a/packages/cli/src/server/desktop/mod.rs +++ b/packages/cli/src/server/desktop/mod.rs @@ -43,8 +43,6 @@ pub async fn startup(config: CrateConfig) -> Result<()> { let hot_reload_tx = broadcast::channel(100).0; - clear_paths(); - Some(HotReloadState { messages: hot_reload_tx.clone(), file_map: file_map.clone(), @@ -109,7 +107,13 @@ pub async fn serve(config: CrateConfig, hot_reload_state: Option } async fn start_desktop_hot_reload(hot_reload_state: HotReloadState) -> Result<()> { - let path = std::env::temp_dir().join("dioxusin"); + let metadata = cargo_metadata::MetadataCommand::new() + .no_deps() + .exec() + .unwrap(); + let target_dir = metadata.target_directory.as_std_path(); + let path = target_dir.join("dioxusin"); + clear_paths(&path); match LocalSocketListener::bind(path) { Ok(local_socket_stream) => { let aborted = Arc::new(Mutex::new(false)); @@ -182,17 +186,14 @@ async fn start_desktop_hot_reload(hot_reload_state: HotReloadState) -> Result<() Ok(()) } -fn clear_paths() { +fn clear_paths(file_socket_path: &std::path::Path) { if cfg!(target_os = "macos") { // 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 - let paths = ["./dioxusin", "./@dioxusin"]; - for path in paths { - let path = std::env::temp_dir().join(path); - if path.exists() { - let _ = std::fs::remove_file(path); - } + + if file_socket_path.exists() { + let _ = std::fs::remove_file(file_socket_path); } } } diff --git a/packages/hot-reload/src/file_watcher.rs b/packages/hot-reload/src/file_watcher.rs index bbd0a7660..c83c62ad9 100644 --- a/packages/hot-reload/src/file_watcher.rs +++ b/packages/hot-reload/src/file_watcher.rs @@ -152,22 +152,20 @@ pub fn init(cfg: Config) { } let file_map = Arc::new(Mutex::new(file_map)); + let target_dir = crate_dir.join("target"); + let hot_reload_socket_path = target_dir.join("dioxusin"); + #[cfg(target_os = "macos")] { // 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 - let paths = ["./dioxusin"]; - for path in paths { - let path = std::env::temp_dir().join(path); - if path.exists() { - let _ = std::fs::remove_file(path); - } + if hot_reload_socket_path.exists() { + let _ = std::fs::remove_file(hot_reload_socket_path); } } - let path = std::env::temp_dir().join("dioxusin"); - match LocalSocketListener::bind(path) { + match LocalSocketListener::bind(hot_reload_socket_path) { Ok(local_socket_stream) => { let aborted = Arc::new(Mutex::new(false)); diff --git a/packages/hot-reload/src/lib.rs b/packages/hot-reload/src/lib.rs index 07bd70a8d..46efb8341 100644 --- a/packages/hot-reload/src/lib.rs +++ b/packages/hot-reload/src/lib.rs @@ -1,4 +1,7 @@ -use std::io::{BufRead, BufReader}; +use std::{ + io::{BufRead, BufReader}, + path::PathBuf, +}; use dioxus_core::Template; #[cfg(feature = "file_watcher")] @@ -24,7 +27,7 @@ pub enum HotReloadMsg { /// Connect to the hot reloading listener. The callback provided will be called every time a template change is detected pub fn connect(mut f: impl FnMut(HotReloadMsg) + Send + 'static) { std::thread::spawn(move || { - let path = std::env::temp_dir().join("dioxusin"); + let path = PathBuf::from("./").join("target").join("dioxusin"); if let Ok(socket) = LocalSocketStream::connect(path) { let mut buf_reader = BufReader::new(socket); loop { From 2bab4eb6c3748ca8803a1332ff57502979da7e55 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Thu, 7 Dec 2023 07:06:43 -0600 Subject: [PATCH 41/83] rename read_untracked to peak --- packages/signals/src/signal.rs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/packages/signals/src/signal.rs b/packages/signals/src/signal.rs index 0ad96349d..88853c473 100644 --- a/packages/signals/src/signal.rs +++ b/packages/signals/src/signal.rs @@ -171,7 +171,8 @@ impl Signal { self.inner.origin_scope() } - /// Get the current value of the signal. This will subscribe the current scope to the signal. + /// Get the current value of the signal. This will subscribe the current scope to the signal. If you would like to read the signal without subscribing to it, you can use [`Self::peak`] instead. + /// /// If the signal has been dropped, this will panic. pub fn read(&self) -> Ref { let inner = self.inner.read(); @@ -201,13 +202,15 @@ impl Signal { } /// Get the current value of the signal. **Unlike read, this will not subscribe the current scope to the signal which can cause parts of your UI to not update.** + /// /// If the signal has been dropped, this will panic. - pub fn read_untracked(&self) -> Ref { + pub fn peak(&self) -> Ref { let inner = self.inner.read(); Ref::map(inner, |v| &v.value) } /// Get a mutable reference to the signal's value. + /// /// If the signal has been dropped, this will panic. pub fn write(&self) -> Write<'_, T> { let inner = self.inner.write(); @@ -387,15 +390,18 @@ impl ReadOnlySignal { self.inner.origin_scope() } - /// Get the current value of the signal. This will subscribe the current scope to the signal. + /// Get the current value of the signal. This will subscribe the current scope to the signal. If you would like to read the signal without subscribing to it, you can use [`Self::peak`] instead. + /// + /// If the signal has been dropped, this will panic. pub fn read(&self) -> Ref { self.inner.read() } /// Get the current value of the signal. **Unlike read, this will not subscribe the current scope to the signal which can cause parts of your UI to not update.** + /// /// If the signal has been dropped, this will panic. - pub fn read_untracked(&self) -> Ref { - self.inner.read_untracked() + pub fn peak(&self) -> Ref { + self.inner.peak() } /// Run a closure with a reference to the signal's value. From 7d2bbda53dc94b07cfe0aad8499b3eb408ecce99 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Thu, 7 Dec 2023 07:10:53 -0600 Subject: [PATCH 42/83] move gnu warning to build script --- packages/desktop/build.rs | 9 +++++++++ packages/desktop/src/lib.rs | 11 ----------- 2 files changed, 9 insertions(+), 11 deletions(-) create mode 100644 packages/desktop/build.rs diff --git a/packages/desktop/build.rs b/packages/desktop/build.rs new file mode 100644 index 000000000..2061732e8 --- /dev/null +++ b/packages/desktop/build.rs @@ -0,0 +1,9 @@ +fn main() { + // 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" + && !cfg!(feature = "gnu") + { + 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") + } +} diff --git a/packages/desktop/src/lib.rs b/packages/desktop/src/lib.rs index 9a5ba6c64..63a8914f3 100644 --- a/packages/desktop/src/lib.rs +++ b/packages/desktop/src/lib.rs @@ -19,17 +19,6 @@ mod webview; #[cfg(any(target_os = "ios", target_os = "android"))] mod mobile_shortcut; -// WARN about wry support on windows gnu targets. GNU windows targets don't work well in wry currently -#[cfg(all(windows, target_env = "gnu", not(feature = "gnu")))] -mod wry_gnu_warning { - #[allow(dead_code)] - #[must_use = "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"] - struct WryGnuWarning; - const _: () = { - let dont_use_gnu = WryGnuWarning; - }; -} - use crate::query::QueryResult; pub use cfg::{Config, WindowCloseBehaviour}; pub use desktop_context::DesktopContext; From 1c2a6fa010fb8c7f209a229b59750951123670a7 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Thu, 7 Dec 2023 07:19:41 -0600 Subject: [PATCH 43/83] fix signals with debug information --- packages/signals/src/signal.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/signals/src/signal.rs b/packages/signals/src/signal.rs index a5ee6b198..6c4052b98 100644 --- a/packages/signals/src/signal.rs +++ b/packages/signals/src/signal.rs @@ -237,9 +237,9 @@ impl Signal { /// Get the current value of the signal. **Unlike read, this will not subscribe the current scope to the signal which can cause parts of your UI to not update.** /// /// If the signal has been dropped, this will panic. - pub fn peak(&self) -> Ref { + pub fn peak(&self) -> GenerationalRef { let inner = self.inner.read(); - Ref::map(inner, |v| &v.value) + GenerationalRef::map(inner, |v| &v.value) } /// Get a mutable reference to the signal's value. @@ -439,7 +439,7 @@ impl ReadOnlySignal { /// Get the current value of the signal. **Unlike read, this will not subscribe the current scope to the signal which can cause parts of your UI to not update.** /// /// If the signal has been dropped, this will panic. - pub fn peak(&self) -> Ref { + pub fn peak(&self) -> GenerationalRef { self.inner.peak() } From df57cc7d9c69fe20566cc5a3af39add83ce5e694 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Thu, 7 Dec 2023 08:29:14 -0600 Subject: [PATCH 44/83] fix disconnects that happen while a server function is being resolved --- packages/fullstack/src/adapters/mod.rs | 38 +++++++++++++------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/packages/fullstack/src/adapters/mod.rs b/packages/fullstack/src/adapters/mod.rs index 98d190919..d368b9c73 100644 --- a/packages/fullstack/src/adapters/mod.rs +++ b/packages/fullstack/src/adapters/mod.rs @@ -89,26 +89,26 @@ impl Service for ServerFnHandler { let parts = Arc::new(RwLock::new(parts)); // Because the future returned by `server_fn_handler` is `Send`, and the future returned by this function must be send, we need to spawn a new runtime - let (resp_tx, resp_rx) = tokio::sync::oneshot::channel(); let pool = get_local_pool(); - pool.spawn_pinned({ - let function = function.clone(); - let mut server_context = server_context.clone(); - server_context.parts = parts; - move || async move { - let data = match function.encoding() { - Encoding::Url | Encoding::Cbor => &body, - Encoding::GetJSON | Encoding::GetCBOR => &query, - }; - let server_function_future = function.call((), data); - let server_function_future = - ProvideServerContext::new(server_function_future, server_context.clone()); - let resp = server_function_future.await; - - resp_tx.send(resp).unwrap(); - } - }); - let result = resp_rx.await.unwrap(); + let result = pool + .spawn_pinned({ + let function = function.clone(); + let mut server_context = server_context.clone(); + server_context.parts = parts; + move || async move { + let data = match function.encoding() { + Encoding::Url | Encoding::Cbor => &body, + Encoding::GetJSON | Encoding::GetCBOR => &query, + }; + let server_function_future = function.call((), data); + let server_function_future = ProvideServerContext::new( + server_function_future, + server_context.clone(), + ); + server_function_future.await + } + }) + .await?; let mut res = http::Response::builder(); // Set the headers from the server context From a1550460ce8cda98998d074243c995955cf6557a Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Thu, 7 Dec 2023 11:37:59 -0600 Subject: [PATCH 45/83] Fix peek spelling --- packages/signals/src/signal.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/signals/src/signal.rs b/packages/signals/src/signal.rs index 6c4052b98..1dc4bd36e 100644 --- a/packages/signals/src/signal.rs +++ b/packages/signals/src/signal.rs @@ -203,7 +203,7 @@ impl Signal { self.inner.origin_scope() } - /// Get the current value of the signal. This will subscribe the current scope to the signal. If you would like to read the signal without subscribing to it, you can use [`Self::peak`] instead. + /// Get the current value of the signal. This will subscribe the current scope to the signal. If you would like to read the signal without subscribing to it, you can use [`Self::peek`] instead. /// /// If the signal has been dropped, this will panic. #[track_caller] @@ -237,7 +237,7 @@ impl Signal { /// Get the current value of the signal. **Unlike read, this will not subscribe the current scope to the signal which can cause parts of your UI to not update.** /// /// If the signal has been dropped, this will panic. - pub fn peak(&self) -> GenerationalRef { + pub fn peek(&self) -> GenerationalRef { let inner = self.inner.read(); GenerationalRef::map(inner, |v| &v.value) } @@ -428,7 +428,7 @@ impl ReadOnlySignal { self.inner.origin_scope() } - /// Get the current value of the signal. This will subscribe the current scope to the signal. If you would like to read the signal without subscribing to it, you can use [`Self::peak`] instead. + /// Get the current value of the signal. This will subscribe the current scope to the signal. If you would like to read the signal without subscribing to it, you can use [`Self::peek`] instead. /// /// If the signal has been dropped, this will panic. #[track_caller] @@ -439,8 +439,8 @@ impl ReadOnlySignal { /// Get the current value of the signal. **Unlike read, this will not subscribe the current scope to the signal which can cause parts of your UI to not update.** /// /// If the signal has been dropped, this will panic. - pub fn peak(&self) -> GenerationalRef { - self.inner.peak() + pub fn peek(&self) -> GenerationalRef { + self.inner.peek() } /// Run a closure with a reference to the signal's value. From fc31876a573a42ed03549c102bd15b709e60f197 Mon Sep 17 00:00:00 2001 From: Exotik850 <60969639+Exotik850@users.noreply.github.com> Date: Thu, 7 Dec 2023 12:35:16 -0600 Subject: [PATCH 46/83] Wasm target check before build (#1689) * Add `rustup show` check for wasm32 target * better place for check * fmt * clippy fmt --- packages/cli/src/builder.rs | 12 ++++++++++++ packages/cli/src/cli/build.rs | 8 ++++---- packages/core/src/diff.rs | 2 +- packages/dioxus-tui/examples/colorpicker.rs | 12 ++++++------ packages/fermi/src/lib.rs | 2 -- packages/router-macro/src/redirect.rs | 1 + packages/rsx/src/lib.rs | 2 +- .../signals/examples/split_subscriptions.rs | 18 +++++------------- packages/web/src/hot_reload.rs | 15 ++++++--------- 9 files changed, 36 insertions(+), 36 deletions(-) diff --git a/packages/cli/src/builder.rs b/packages/cli/src/builder.rs index 08e636237..f7b6a3071 100644 --- a/packages/cli/src/builder.rs +++ b/packages/cli/src/builder.rs @@ -48,6 +48,18 @@ pub fn build(config: &CrateConfig, quiet: bool) -> Result { // [1] Build the .wasm module log::info!("🚅 Running build command..."); + + let wasm_check_command = std::process::Command::new("rustup") + .args(["show"]) + .output()?; + let wasm_check_output = String::from_utf8(wasm_check_command.stdout).unwrap(); + if !wasm_check_output.contains("wasm32-unknown-unknown") { + log::info!("wasm32-unknown-unknown target not detected, installing.."); + let _ = std::process::Command::new("rustup") + .args(["target", "add", "wasm32-unknown-unknown"]) + .output()?; + } + let cmd = subprocess::Exec::cmd("cargo"); let cmd = cmd .cwd(crate_dir) diff --git a/packages/cli/src/cli/build.rs b/packages/cli/src/cli/build.rs index 7fe29f8ce..63a2969e0 100644 --- a/packages/cli/src/cli/build.rs +++ b/packages/cli/src/cli/build.rs @@ -37,8 +37,8 @@ impl Build { .platform .unwrap_or(crate_config.dioxus_config.application.default_platform); - #[cfg(feature = "plugin")] - let _ = PluginManager::on_build_start(&crate_config, &platform); + // #[cfg(feature = "plugin")] + // let _ = PluginManager::on_build_start(&crate_config, &platform); match platform { Platform::Web => { @@ -66,8 +66,8 @@ impl Build { )?; file.write_all(temp.as_bytes())?; - #[cfg(feature = "plugin")] - let _ = PluginManager::on_build_finish(&crate_config, &platform); + // #[cfg(feature = "plugin")] + // let _ = PluginManager::on_build_finish(&crate_config, &platform); Ok(()) } diff --git a/packages/core/src/diff.rs b/packages/core/src/diff.rs index 74017db0f..2de862218 100644 --- a/packages/core/src/diff.rs +++ b/packages/core/src/diff.rs @@ -560,7 +560,7 @@ 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.get(0).is_some() { + if old.first().is_some() { self.remove_nodes(&old[1..]); self.replace(&old[0], new); } else { diff --git a/packages/dioxus-tui/examples/colorpicker.rs b/packages/dioxus-tui/examples/colorpicker.rs index 00f8ef7e0..01cc38cda 100644 --- a/packages/dioxus-tui/examples/colorpicker.rs +++ b/packages/dioxus-tui/examples/colorpicker.rs @@ -15,21 +15,21 @@ fn app(cx: Scope) -> Element { let mapping: DioxusElementToNodeId = cx.consume_context().unwrap(); // disable templates so that every node has an id and can be queried cx.render(rsx! { - div{ + div { width: "100%", background_color: "hsl({hue}, 70%, {brightness}%)", onmousemove: move |evt| { if let RenderReturn::Ready(node) = cx.root_node() { - if let Some(id) = node.root_ids.borrow().get(0).cloned() { + if let Some(id) = node.root_ids.borrow().first().cloned() { let node = tui_query.get(mapping.get_node_id(id).unwrap()); - let Size{width, height} = node.size().unwrap(); + let Size { width, height } = node.size().unwrap(); let pos = evt.inner().element_coordinates(); - hue.set((pos.x as f32/width as f32)*255.0); - brightness.set((pos.y as f32/height as f32)*100.0); + hue.set((pos.x as f32 / width as f32) * 255.0); + brightness.set((pos.y as f32 / height as f32) * 100.0); } } }, - "hsl({hue}, 70%, {brightness}%)", + "hsl({hue}, 70%, {brightness}%)" } }) } diff --git a/packages/fermi/src/lib.rs b/packages/fermi/src/lib.rs index 52bf4cd09..dc5ccf010 100644 --- a/packages/fermi/src/lib.rs +++ b/packages/fermi/src/lib.rs @@ -22,8 +22,6 @@ mod atoms { pub use atom::*; pub use atomfamily::*; pub use atomref::*; - pub use selector::*; - pub use selectorfamily::*; } pub mod hooks { diff --git a/packages/router-macro/src/redirect.rs b/packages/router-macro/src/redirect.rs index c1efb8b4d..2933bbc8e 100644 --- a/packages/router-macro/src/redirect.rs +++ b/packages/router-macro/src/redirect.rs @@ -75,6 +75,7 @@ impl Redirect { let (segments, query) = parse_route_segments( path.span(), + #[allow(clippy::map_identity)] closure_arguments.iter().map(|(name, ty)| (name, ty)), &path.value(), )?; diff --git a/packages/rsx/src/lib.rs b/packages/rsx/src/lib.rs index bdf32b272..5db6baee9 100644 --- a/packages/rsx/src/lib.rs +++ b/packages/rsx/src/lib.rs @@ -193,7 +193,7 @@ impl<'a> ToTokens for TemplateRenderer<'a> { fn to_tokens(&self, out_tokens: &mut TokenStream2) { let mut context = DynamicContext::default(); - let key = match self.roots.get(0) { + let key = match self.roots.first() { Some(BodyNode::Element(el)) if self.roots.len() == 1 => el.key.clone(), Some(BodyNode::Component(comp)) if self.roots.len() == 1 => comp.key().cloned(), _ => None, diff --git a/packages/signals/examples/split_subscriptions.rs b/packages/signals/examples/split_subscriptions.rs index 3eb60ed29..bb286b4b7 100644 --- a/packages/signals/examples/split_subscriptions.rs +++ b/packages/signals/examples/split_subscriptions.rs @@ -22,15 +22,9 @@ fn app(cx: Scope) -> Element { use_context_provider(cx, ApplicationData::default); render! { - div { - ReadsFirst {} - } - div { - ReadsSecond {} - } - div { - ReadsManySignals {} - } + div { ReadsFirst {} } + div { ReadsSecond {} } + div { ReadsManySignals {} } } } @@ -107,16 +101,14 @@ fn ReadsManySignals(cx: Scope) -> Element { } button { onclick: move |_| { - if let Some(first) = data.many_signals.read().get(0) { + if let Some(first) = data.many_signals.read().first() { *first.write() += 1; } }, "Increase First Item" } for signal in data.many_signals { - Child { - count: signal, - } + Child { count: signal } } } } diff --git a/packages/web/src/hot_reload.rs b/packages/web/src/hot_reload.rs index 6256cc935..e8b4e42e4 100644 --- a/packages/web/src/hot_reload.rs +++ b/packages/web/src/hot_reload.rs @@ -5,7 +5,6 @@ use futures_channel::mpsc::UnboundedReceiver; use dioxus_core::Template; pub(crate) fn init() -> UnboundedReceiver> { - use std::convert::TryInto; use wasm_bindgen::closure::Closure; use wasm_bindgen::JsCast; use web_sys::{MessageEvent, WebSocket}; @@ -31,14 +30,12 @@ pub(crate) fn init() -> UnboundedReceiver> { // change the rsx when new data is received let cl = Closure::wrap(Box::new(move |e: MessageEvent| { if let Ok(text) = e.data().dyn_into::() { - let text: Result = text.try_into(); - if let Ok(string) = text { - let val = serde_json::from_str::(&string).unwrap(); - // leak the value - let val: &'static serde_json::Value = Box::leak(Box::new(val)); - let template: Template<'_> = Template::deserialize(val).unwrap(); - tx.unbounded_send(template).unwrap(); - } + let string: String = text.into(); + let val = serde_json::from_str::(&string).unwrap(); + // leak the value + let val: &'static serde_json::Value = Box::leak(Box::new(val)); + let template: Template<'_> = Template::deserialize(val).unwrap(); + tx.unbounded_send(template).unwrap(); } }) as Box); From 6b7545f60a85a3add0259ecc801c03737cc9fddd Mon Sep 17 00:00:00 2001 From: Alex Parrill Date: Thu, 7 Dec 2023 17:13:50 -0500 Subject: [PATCH 47/83] Add loading attribute to img element (#1699) Useful for lazy loading: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#loading --- packages/html/src/elements.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/html/src/elements.rs b/packages/html/src/elements.rs index d7db36a04..a42c01950 100644 --- a/packages/html/src/elements.rs +++ b/packages/html/src/elements.rs @@ -827,6 +827,7 @@ builder_constructors! { decoding: ImageDecoding DEFAULT, height: usize DEFAULT, ismap: Bool DEFAULT, + loading: String DEFAULT, src: Uri DEFAULT, srcset: String DEFAULT, // FIXME this is much more complicated usemap: String DEFAULT, // FIXME should be a fragment starting with '#' From 972235bd6fba872c72a236e21fd4f5b855434d8f Mon Sep 17 00:00:00 2001 From: Benjamin Manns Date: Sun, 10 Dec 2023 13:16:59 -0500 Subject: [PATCH 48/83] Fix doc tests by adding formatting to CLI README (#1706) The README for cli gets included in lib.rs via `include_str!`. The code snippets then get assumed to be Rust, which fails if running `cargo test --doc`. This is not a huge problem, but was brought to my attention because Nix's `buildRustPackage` runs `cargo test` including doc tests (unlike what get run for this project on CI). This means I can't update the Nix package to 0.4.3 without changing the test flags (which I think I'll see about doing anyways, as that's how Dioxus runs CI). --- packages/cli/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/cli/README.md b/packages/cli/README.md index 8379f22cc..2325d6784 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -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 ``` From 695bf009d11be0a8b717257ab2d56adf8873c489 Mon Sep 17 00:00:00 2001 From: YuKun Liu Date: Mon, 11 Dec 2023 11:27:55 -0800 Subject: [PATCH 49/83] fix: dx create not work (#1709) --- packages/cli/src/main.rs | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/packages/cli/src/main.rs b/packages/cli/src/main.rs index 7ca1b2c9a..2358551f2 100644 --- a/packages/cli/src/main.rs +++ b/packages/cli/src/main.rs @@ -42,34 +42,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())) .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 +83,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 +109,6 @@ async fn main() -> anyhow::Result<()> { Ok(()) } + _ => Err(anyhow::anyhow!(bin.unwrap_err())), } } From 0cb13942daffa8aa69a9a61aaa7982ea165d586f Mon Sep 17 00:00:00 2001 From: xfalcon Date: Wed, 13 Dec 2023 22:30:40 +0800 Subject: [PATCH 50/83] fix: command error with dx build --verbose (#1715) error msg: cannot set both --verbose and --quiet --- packages/cli/src/builder.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/cli/src/builder.rs b/packages/cli/src/builder.rs index f7b6a3071..759be7dec 100644 --- a/packages/cli/src/builder.rs +++ b/packages/cli/src/builder.rs @@ -265,7 +265,6 @@ pub fn build_desktop(config: &CrateConfig, _is_serve: bool) -> Result Result Date: Wed, 13 Dec 2023 09:44:01 -0600 Subject: [PATCH 51/83] Autoformat ignores files in `.gitignore` (#1704) * Make autofmt ignore gitignored files * don't panic if it can't get the git ignore files * replace some with ok * Filter rs files from gitignore * fmt * remove early return * only ignore paths that start with target --------- Co-authored-by: Evan Almloff --- packages/cli/Cargo.toml | 1 + packages/cli/src/cli/autoformat.rs | 175 ++++++++++++++++------------- 2 files changed, 96 insertions(+), 80 deletions(-) diff --git a/packages/cli/Cargo.toml b/packages/cli/Cargo.toml index 128133602..4c115184e 100644 --- a/packages/cli/Cargo.toml +++ b/packages/cli/Cargo.toml @@ -83,6 +83,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 = [] diff --git a/packages/cli/src/cli/autoformat.rs b/packages/cli/src/cli/autoformat.rs index 6c1ce04a1..812a4c325 100644 --- a/packages/cli/src/cli/autoformat.rs +++ b/packages/cli/src/cli/autoformat.rs @@ -27,15 +27,17 @@ pub struct Autoformat { impl Autoformat { // Todo: autoformat the entire crate pub async fn autoformat(self) -> Result<()> { + let Autoformat { check, raw, file } = self; + // Default to formatting the project - if self.raw.is_none() && self.file.is_none() { - if let Err(e) = autoformat_project(self.check).await { + if raw.is_none() && file.is_none() { + if let Err(e) = autoformat_project(check).await { eprintln!("error formatting project: {}", e); exit(1); } } - if let Some(raw) = self.raw { + if let Some(raw) = raw { let indent = indentation_for(".")?; if let Some(inner) = dioxus_autofmt::fmt_block(&raw, 0, indent) { println!("{}", inner); @@ -47,47 +49,90 @@ impl Autoformat { } // Format single file - if let Some(file) = self.file { - let file_content; - let indent; - if file == "-" { - indent = indentation_for(".")?; - let mut contents = String::new(); - std::io::stdin().read_to_string(&mut contents)?; - file_content = Ok(contents); - } else { - indent = indentation_for(".")?; - 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)?; } Ok(()) } } +fn refactor_file(file: String) -> Result<(), Error> { + let indent = indentation_for(".")?; + 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 { + 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, + indent: IndentOptions, +) -> Result { + 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 @@ -96,8 +141,7 @@ impl Autoformat { async fn autoformat_project(check: bool) -> Result<()> { let crate_config = crate::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(()); @@ -107,38 +151,17 @@ async fn autoformat_project(check: 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 - }) - .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), @@ -148,13 +171,7 @@ async fn autoformat_project(check: bool) -> Result<()> { .collect::>() .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); @@ -207,26 +224,24 @@ fn indentation_for(file_or_dir: impl AsRef) -> Result { )) } -fn collect_rs_files(folder: &Path, files: &mut Vec) { - let Ok(folder) = folder.read_dir() else { +fn collect_rs_files(folder: &impl AsRef, files: &mut Vec) { + 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); } } From d5ec22a26f3148f12712e2ff1a4ea4849ddc12f6 Mon Sep 17 00:00:00 2001 From: Will Crichton Date: Fri, 15 Dec 2023 11:16:25 -0800 Subject: [PATCH 52/83] Add custom asynchronous asset handlers --- packages/desktop/src/desktop_context.rs | 23 ++++ packages/desktop/src/lib.rs | 5 +- packages/desktop/src/protocol.rs | 143 +++++++++++++++++++++++- packages/desktop/src/webview.rs | 42 ++++--- 4 files changed, 194 insertions(+), 19 deletions(-) diff --git a/packages/desktop/src/desktop_context.rs b/packages/desktop/src/desktop_context.rs index a48068d84..7f4ef9d1d 100644 --- a/packages/desktop/src/desktop_context.rs +++ b/packages/desktop/src/desktop_context.rs @@ -1,11 +1,18 @@ use std::cell::RefCell; +use std::future::Future; +use std::path::Path; use std::rc::Rc; use std::rc::Weak; use crate::create_new_window; use crate::events::IpcMessage; +use crate::protocol::AssetFuture; +use crate::protocol::AssetHandlerId; +use crate::protocol::AssetHandlerRegistry; +use crate::protocol::AssetResponse; use crate::query::QueryEngine; use crate::shortcut::{HotKey, ShortcutId, ShortcutRegistry, ShortcutRegistryError}; +use crate::AssetHandler; use crate::Config; use crate::WebviewHandler; use dioxus_core::ScopeState; @@ -64,6 +71,8 @@ pub struct DesktopService { pub(crate) shortcut_manager: ShortcutRegistry, + pub(crate) asset_handlers: AssetHandlerRegistry, + #[cfg(target_os = "ios")] pub(crate) views: Rc>>, } @@ -88,6 +97,7 @@ impl DesktopService { webviews: WebviewQueue, event_handlers: WindowEventHandlers, shortcut_manager: ShortcutRegistry, + asset_handlers: AssetHandlerRegistry, ) -> Self { Self { webview: Rc::new(webview), @@ -97,6 +107,7 @@ impl DesktopService { pending_windows: webviews, event_handlers, shortcut_manager, + asset_handlers, #[cfg(target_os = "ios")] views: Default::default(), } @@ -247,6 +258,18 @@ impl DesktopService { self.shortcut_manager.remove_all() } + /// Provide a callback to handle asset loading yourself. + /// + /// See [`use_asset_handle`](crate::use_asset_handle) for a convenient hook. + pub async fn register_asset_handler(&self, f: impl AssetHandler) { + self.asset_handlers.register_handler(f).await; + } + + /// Removes an asset handler by its identifier. + pub async fn remove_asset_handler(&self, id: AssetHandlerId) { + self.asset_handlers.remove_handler(id).await; + } + /// Push an objc view to the window #[cfg(target_os = "ios")] pub fn push_view(&self, view: objc_id::ShareId) { diff --git a/packages/desktop/src/lib.rs b/packages/desktop/src/lib.rs index d6d5ef4a5..f8155c333 100644 --- a/packages/desktop/src/lib.rs +++ b/packages/desktop/src/lib.rs @@ -32,6 +32,7 @@ use dioxus_html::{native_bind::NativeFileEngine, FormData, HtmlEvent}; use element::DesktopElement; use eval::init_eval; use futures_util::{pin_mut, FutureExt}; +pub use protocol::{use_asset_handler, AssetFuture, AssetHandler, AssetHandlerId, AssetResponse}; use shortcut::ShortcutRegistry; pub use shortcut::{use_global_shortcut, ShortcutHandle, ShortcutId, ShortcutRegistryError}; use std::cell::Cell; @@ -393,7 +394,8 @@ fn create_new_window( event_handlers: &WindowEventHandlers, shortcut_manager: ShortcutRegistry, ) -> WebviewHandler { - let (webview, web_context) = webview::build(&mut cfg, event_loop, proxy.clone()); + let (webview, web_context, asset_handlers) = + webview::build(&mut cfg, event_loop, proxy.clone()); let desktop_context = Rc::from(DesktopService::new( webview, proxy.clone(), @@ -401,6 +403,7 @@ fn create_new_window( queue.clone(), event_handlers.clone(), shortcut_manager, + asset_handlers, )); let cx = dom.base_scope(); diff --git a/packages/desktop/src/protocol.rs b/packages/desktop/src/protocol.rs index 2f660b7a2..774c0900a 100644 --- a/packages/desktop/src/protocol.rs +++ b/packages/desktop/src/protocol.rs @@ -1,13 +1,25 @@ +use dioxus_core::ScopeState; use dioxus_interpreter_js::{COMMON_JS, INTERPRETER_JS}; use std::{ borrow::Cow, + collections::HashMap, + future::Future, path::{Path, PathBuf}, + pin::Pin, + rc::Rc, + sync::Arc, +}; +use tokio::{ + runtime::Handle, + sync::{OnceCell, RwLock}, }; use wry::{ http::{status::StatusCode, Request, Response}, Result, }; +use crate::{use_window, DesktopContext}; + fn module_loader(root_name: &str) -> String { let js = INTERPRETER_JS.replace( "/*POST_HANDLE_EDITS*/", @@ -51,12 +63,132 @@ fn module_loader(root_name: &str) -> String { ) } -pub(super) fn desktop_handler( +/// An arbitrary asset is an HTTP response containing a binary body. +pub type AssetResponse = Response>; + +/// A future that returns an [`AssetResponse`]. This future may be spawned in a new thread, +/// so it must be [`Send`], [`Sync`], and `'static`. +pub trait AssetFuture: Future> + Send + Sync + 'static {} +impl> + Send + Sync + 'static> AssetFuture for T {} + +/// A handler that takes an asset [`Path`] and returns a future that loads the path. +/// This handler is stashed indefinitely in a context object, so it must be `'static`. +pub trait AssetHandler: Fn(&Path) -> F + Send + Sync + 'static {} +impl F + Send + Sync + 'static> AssetHandler for T {} + +/// An identifier for a registered asset handler, returned by [`AssetHandlerRegistry::register_handler`]. +#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)] +pub struct AssetHandlerId(usize); + +struct AssetHandlerRegistryInner { + handlers: HashMap< + AssetHandlerId, + Box Pin> + Send + Sync + 'static>, + >, + counter: AssetHandlerId, +} + +#[derive(Clone)] +pub struct AssetHandlerRegistry(Arc>); + +impl AssetHandlerRegistry { + pub fn new() -> Self { + AssetHandlerRegistry(Arc::new(RwLock::new(AssetHandlerRegistryInner { + handlers: HashMap::new(), + counter: AssetHandlerId(0), + }))) + } + + pub async fn register_handler( + &self, + f: impl AssetHandler, + ) -> AssetHandlerId { + let mut registry = self.0.write().await; + let id = registry.counter; + registry + .handlers + .insert(id, Box::new(move |path| Box::pin(f(path)))); + registry.counter.0 += 1; + id + } + + pub async fn remove_handler(&self, id: AssetHandlerId) -> Option<()> { + let mut registry = self.0.write().await; + registry.handlers.remove(&id).map(|_| ()) + } + + pub async fn try_handlers(&self, path: &Path) -> Option { + let registry = self.0.read().await; + for handler in registry.handlers.values() { + if let Some(response) = handler(path).await { + return Some(response); + } + } + None + } +} + +/// A handle to a registered asset handler. +pub struct AssetHandlerHandle { + desktop: DesktopContext, + handler_id: Rc>, +} + +impl AssetHandlerHandle { + /// Returns the [`AssetHandlerId`] for this handle. + /// + /// Because registering an ID is asynchronous, this may return `None` if the + /// registration has not completed yet. + pub fn handler_id(&self) -> Option { + self.handler_id.get().copied() + } +} + +impl Drop for AssetHandlerHandle { + fn drop(&mut self) { + let cell = Rc::clone(&self.handler_id); + let desktop = Rc::clone(&self.desktop); + tokio::task::block_in_place(move || { + Handle::current().block_on(async move { + if let Some(id) = cell.get() { + desktop.asset_handlers.remove_handler(*id).await; + } + }) + }); + } +} + +/// 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, + handler: impl AssetHandler, +) -> &AssetHandlerHandle { + let desktop = Rc::clone(&use_window(cx)); + cx.use_hook(|| { + let handler_id = Rc::new(OnceCell::new()); + let handler_id_ref = Rc::clone(&handler_id); + let desktop_ref = Rc::clone(&desktop); + cx.push_future(async move { + let id = desktop.asset_handlers.register_handler(handler).await; + handler_id.set(id).unwrap(); + }); + AssetHandlerHandle { + desktop: desktop_ref, + handler_id: handler_id_ref, + } + }) +} + +pub(super) async fn desktop_handler( request: &Request>, custom_head: Option, custom_index: Option, root_name: &str, -) -> Result>> { + asset_handlers: &AssetHandlerRegistry, +) -> Result { // 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. @@ -96,6 +228,13 @@ pub(super) fn desktop_handler( .expect("expected URL to be UTF-8 encoded"); let path = PathBuf::from(&*decoded); + // If the user provided a custom asset handler, then call it and return the response + // if the request was handled. + if let Some(response) = asset_handlers.try_handlers(&path).await { + return Ok(response); + } + + // Else, try to serve a file from the filesystem. // 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()) diff --git a/packages/desktop/src/webview.rs b/packages/desktop/src/webview.rs index cffb6f6b5..e2179352f 100644 --- a/packages/desktop/src/webview.rs +++ b/packages/desktop/src/webview.rs @@ -1,5 +1,7 @@ +use std::sync::Arc; + use crate::desktop_context::EventData; -use crate::protocol; +use crate::protocol::{self, AssetHandlerRegistry}; use crate::{desktop_context::UserWindowEvent, Config}; use tao::event_loop::{EventLoopProxy, EventLoopWindowTarget}; pub use wry; @@ -12,7 +14,7 @@ pub fn build( cfg: &mut Config, event_loop: &EventLoopWindowTarget, proxy: EventLoopProxy, -) -> (WebView, WebContext) { +) -> (WebView, WebContext, AssetHandlerRegistry) { let builder = cfg.window.clone(); let window = builder.with_visible(false).build(event_loop).unwrap(); let file_handler = cfg.file_drop_handler.take(); @@ -33,6 +35,8 @@ pub fn build( } let mut web_context = WebContext::new(cfg.data_dir.clone()); + let asset_handlers = AssetHandlerRegistry::new(); + let asset_handlers_ref = asset_handlers.clone(); let mut webview = WebViewBuilder::new(window) .unwrap() @@ -45,24 +49,30 @@ pub fn build( _ = proxy.send_event(UserWindowEvent(EventData::Ipc(message), window.id())); } }) - .with_custom_protocol( - String::from("dioxus"), - move |r| match protocol::desktop_handler( - &r, - custom_head.clone(), - index_file.clone(), - &root_name, - ) { - Ok(response) => response, - Err(err) => { + .with_asynchronous_custom_protocol(String::from("dioxus"), move |request, responder| { + let custom_head = custom_head.clone(); + let index_file = index_file.clone(); + let root_name = root_name.clone(); + let asset_handlers_ref = asset_handlers_ref.clone(); + tokio::spawn(async move { + let response_res = protocol::desktop_handler( + &request, + custom_head.clone(), + index_file.clone(), + &root_name, + &asset_handlers_ref, + ) + .await; + let response = response_res.unwrap_or_else(|err| { tracing::error!("Error: {}", err); Response::builder() .status(500) .body(err.to_string().into_bytes().into()) .unwrap() - } - }, - ) + }); + responder.respond(response); + }); + }) .with_file_drop_handler(move |window, evet| { file_handler .as_ref() @@ -119,5 +129,5 @@ pub fn build( webview = webview.with_devtools(true); } - (webview.build().unwrap(), web_context) + (webview.build().unwrap(), web_context, asset_handlers) } From 7bede0be59c9e48d55342c9f01978c34f8cc3a53 Mon Sep 17 00:00:00 2001 From: Will Crichton Date: Fri, 15 Dec 2023 11:30:19 -0800 Subject: [PATCH 53/83] Remove unused imports --- packages/desktop/src/desktop_context.rs | 3 --- packages/desktop/src/webview.rs | 2 -- 2 files changed, 5 deletions(-) diff --git a/packages/desktop/src/desktop_context.rs b/packages/desktop/src/desktop_context.rs index 7f4ef9d1d..cab3b4589 100644 --- a/packages/desktop/src/desktop_context.rs +++ b/packages/desktop/src/desktop_context.rs @@ -1,6 +1,4 @@ use std::cell::RefCell; -use std::future::Future; -use std::path::Path; use std::rc::Rc; use std::rc::Weak; @@ -9,7 +7,6 @@ use crate::events::IpcMessage; use crate::protocol::AssetFuture; use crate::protocol::AssetHandlerId; use crate::protocol::AssetHandlerRegistry; -use crate::protocol::AssetResponse; use crate::query::QueryEngine; use crate::shortcut::{HotKey, ShortcutId, ShortcutRegistry, ShortcutRegistryError}; use crate::AssetHandler; diff --git a/packages/desktop/src/webview.rs b/packages/desktop/src/webview.rs index e2179352f..1b13216c7 100644 --- a/packages/desktop/src/webview.rs +++ b/packages/desktop/src/webview.rs @@ -1,5 +1,3 @@ -use std::sync::Arc; - use crate::desktop_context::EventData; use crate::protocol::{self, AssetHandlerRegistry}; use crate::{desktop_context::UserWindowEvent, Config}; From 2321c1ad4448aa8b2759972fa695a9944bc8c203 Mon Sep 17 00:00:00 2001 From: w3irdrobot <3712883+w3irdrobot@users.noreply.github.com> Date: Fri, 15 Dec 2023 18:55:19 -0500 Subject: [PATCH 54/83] add error log when root element isn't found (#1724) --- packages/web/Cargo.toml | 1 + packages/web/src/dom.rs | 11 ++++++++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/packages/web/Cargo.toml b/packages/web/Cargo.toml index 35eb9c5f1..b2a8e94c8 100644 --- a/packages/web/Cargo.toml +++ b/packages/web/Cargo.toml @@ -42,6 +42,7 @@ features = [ "HtmlFormElement", "Text", "Window", + "console", ] [features] diff --git a/packages/web/src/dom.rs b/packages/web/src/dom.rs index f45d6558a..b8e9255f7 100644 --- a/packages/web/src/dom.rs +++ b/packages/web/src/dom.rs @@ -45,7 +45,16 @@ impl WebsysDom { let document = load_document(); let root = match document.get_element_by_id(&cfg.rootname) { Some(root) => root, - None => document.create_element("body").ok().unwrap(), + None => { + web_sys::console::error_1( + &format!( + "element '#{}' not found. mounting to the body.", + cfg.rootname + ) + .into(), + ); + document.create_element("body").ok().unwrap() + } }; let interpreter = Channel::default(); From 1002bc955b5f569eb9e74da90b62b16c45d43bc6 Mon Sep 17 00:00:00 2001 From: Will Crichton Date: Sat, 16 Dec 2023 21:44:39 -0800 Subject: [PATCH 55/83] Replace AssetHandlerId with slab and usize --- packages/desktop/src/desktop_context.rs | 11 +++--- packages/desktop/src/lib.rs | 2 +- packages/desktop/src/protocol.rs | 45 +++++++------------------ 3 files changed, 20 insertions(+), 38 deletions(-) diff --git a/packages/desktop/src/desktop_context.rs b/packages/desktop/src/desktop_context.rs index cab3b4589..fb0615900 100644 --- a/packages/desktop/src/desktop_context.rs +++ b/packages/desktop/src/desktop_context.rs @@ -5,7 +5,6 @@ use std::rc::Weak; use crate::create_new_window; use crate::events::IpcMessage; use crate::protocol::AssetFuture; -use crate::protocol::AssetHandlerId; use crate::protocol::AssetHandlerRegistry; use crate::query::QueryEngine; use crate::shortcut::{HotKey, ShortcutId, ShortcutRegistry, ShortcutRegistryError}; @@ -258,13 +257,15 @@ impl DesktopService { /// Provide a callback to handle asset loading yourself. /// /// See [`use_asset_handle`](crate::use_asset_handle) for a convenient hook. - pub async fn register_asset_handler(&self, f: impl AssetHandler) { - self.asset_handlers.register_handler(f).await; + pub async fn register_asset_handler(&self, f: impl AssetHandler) -> usize { + self.asset_handlers.register_handler(f).await } /// Removes an asset handler by its identifier. - pub async fn remove_asset_handler(&self, id: AssetHandlerId) { - self.asset_handlers.remove_handler(id).await; + /// + /// Returns `None` if the handler did not exist. + pub async fn remove_asset_handler(&self, id: usize) -> Option<()> { + self.asset_handlers.remove_handler(id).await } /// Push an objc view to the window diff --git a/packages/desktop/src/lib.rs b/packages/desktop/src/lib.rs index f8155c333..515c26009 100644 --- a/packages/desktop/src/lib.rs +++ b/packages/desktop/src/lib.rs @@ -32,7 +32,7 @@ use dioxus_html::{native_bind::NativeFileEngine, FormData, HtmlEvent}; use element::DesktopElement; use eval::init_eval; use futures_util::{pin_mut, FutureExt}; -pub use protocol::{use_asset_handler, AssetFuture, AssetHandler, AssetHandlerId, AssetResponse}; +pub use protocol::{use_asset_handler, AssetFuture, AssetHandler, AssetResponse}; use shortcut::ShortcutRegistry; pub use shortcut::{use_global_shortcut, ShortcutHandle, ShortcutId, ShortcutRegistryError}; use std::cell::Cell; diff --git a/packages/desktop/src/protocol.rs b/packages/desktop/src/protocol.rs index 774c0900a..cb21245f8 100644 --- a/packages/desktop/src/protocol.rs +++ b/packages/desktop/src/protocol.rs @@ -1,5 +1,6 @@ use dioxus_core::ScopeState; use dioxus_interpreter_js::{COMMON_JS, INTERPRETER_JS}; +use slab::Slab; use std::{ borrow::Cow, collections::HashMap, @@ -76,50 +77,30 @@ impl> + Send + Sync + 'static> AssetFut pub trait AssetHandler: Fn(&Path) -> F + Send + Sync + 'static {} impl F + Send + Sync + 'static> AssetHandler for T {} -/// An identifier for a registered asset handler, returned by [`AssetHandlerRegistry::register_handler`]. -#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)] -pub struct AssetHandlerId(usize); - -struct AssetHandlerRegistryInner { - handlers: HashMap< - AssetHandlerId, - Box Pin> + Send + Sync + 'static>, - >, - counter: AssetHandlerId, -} +type AssetHandlerRegistryInner = + Slab Pin> + Send + Sync + 'static>>; #[derive(Clone)] pub struct AssetHandlerRegistry(Arc>); impl AssetHandlerRegistry { pub fn new() -> Self { - AssetHandlerRegistry(Arc::new(RwLock::new(AssetHandlerRegistryInner { - handlers: HashMap::new(), - counter: AssetHandlerId(0), - }))) + AssetHandlerRegistry(Arc::new(RwLock::new(Slab::new()))) } - pub async fn register_handler( - &self, - f: impl AssetHandler, - ) -> AssetHandlerId { + pub async fn register_handler(&self, f: impl AssetHandler) -> usize { let mut registry = self.0.write().await; - let id = registry.counter; - registry - .handlers - .insert(id, Box::new(move |path| Box::pin(f(path)))); - registry.counter.0 += 1; - id + registry.insert(Box::new(move |path| Box::pin(f(path)))) } - pub async fn remove_handler(&self, id: AssetHandlerId) -> Option<()> { + pub async fn remove_handler(&self, id: usize) -> Option<()> { let mut registry = self.0.write().await; - registry.handlers.remove(&id).map(|_| ()) + registry.try_remove(id).map(|_| ()) } pub async fn try_handlers(&self, path: &Path) -> Option { let registry = self.0.read().await; - for handler in registry.handlers.values() { + for (_, handler) in registry.iter() { if let Some(response) = handler(path).await { return Some(response); } @@ -131,15 +112,15 @@ impl AssetHandlerRegistry { /// A handle to a registered asset handler. pub struct AssetHandlerHandle { desktop: DesktopContext, - handler_id: Rc>, + handler_id: Rc>, } impl AssetHandlerHandle { - /// Returns the [`AssetHandlerId`] for this handle. + /// Returns the ID for this handle. /// /// Because registering an ID is asynchronous, this may return `None` if the /// registration has not completed yet. - pub fn handler_id(&self) -> Option { + pub fn handler_id(&self) -> Option { self.handler_id.get().copied() } } @@ -166,7 +147,7 @@ pub fn use_asset_handler( cx: &ScopeState, handler: impl AssetHandler, ) -> &AssetHandlerHandle { - let desktop = Rc::clone(&use_window(cx)); + let desktop = Rc::clone(use_window(cx)); cx.use_hook(|| { let handler_id = Rc::new(OnceCell::new()); let handler_id_ref = Rc::clone(&handler_id); From cf413780c1a00240ec9eaf9f4bd19c09119f5250 Mon Sep 17 00:00:00 2001 From: Exotik850 <60969639+Exotik850@users.noreply.github.com> Date: Sun, 17 Dec 2023 15:26:40 -0600 Subject: [PATCH 56/83] Make hot reload error only show once (#1725) --- packages/cli/src/server/desktop/mod.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/cli/src/server/desktop/mod.rs b/packages/cli/src/server/desktop/mod.rs index fec1e5a99..97f316d3c 100644 --- a/packages/cli/src/server/desktop/mod.rs +++ b/packages/cli/src/server/desktop/mod.rs @@ -127,6 +127,7 @@ async fn start_desktop_hot_reload(hot_reload_state: HotReloadState) -> Result<() let file_map = hot_reload_state.file_map.clone(); let channels = channels.clone(); let aborted = aborted.clone(); + let mut error_shown = false; move || { loop { //accept() will block the thread when local_socket_stream is in blocking mode (default) @@ -154,7 +155,8 @@ 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 { + if !error_shown && err.kind() != std::io::ErrorKind::WouldBlock { + error_shown = true; 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); } } From e7515d18c1eef6f8547ea7e3ee1137561fdbb165 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Sun, 17 Dec 2023 15:39:48 -0600 Subject: [PATCH 57/83] show multiple different error messages in hot reloading --- packages/cli/src/server/desktop/mod.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/packages/cli/src/server/desktop/mod.rs b/packages/cli/src/server/desktop/mod.rs index 97f316d3c..c89fb858c 100644 --- a/packages/cli/src/server/desktop/mod.rs +++ b/packages/cli/src/server/desktop/mod.rs @@ -7,10 +7,11 @@ use crate::{ }; use dioxus_hot_reload::HotReloadMsg; -use dioxus_html::HtmlCtx; +use dioxus_html::{HtmlCtx, SvgAttributes}; use dioxus_rsx::hot_reload::*; use interprocess_docfix::local_socket::LocalSocketListener; use std::{ + collections::HashSet, process::{Child, Command}, sync::{Arc, Mutex, RwLock}, }; @@ -127,7 +128,6 @@ async fn start_desktop_hot_reload(hot_reload_state: HotReloadState) -> Result<() let file_map = hot_reload_state.file_map.clone(); let channels = channels.clone(); let aborted = aborted.clone(); - let mut error_shown = false; move || { loop { //accept() will block the thread when local_socket_stream is in blocking mode (default) @@ -155,8 +155,11 @@ async fn start_desktop_hot_reload(hot_reload_state: HotReloadState) -> Result<() println!("Connected to hot reloading 🚀"); } Err(err) => { - if !error_shown && err.kind() != std::io::ErrorKind::WouldBlock { - error_shown = true; + 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); } } From 2a764aaf6a3854469a005e533b5dc8547116ca1e Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Sun, 17 Dec 2023 15:42:58 -0600 Subject: [PATCH 58/83] remove some unused CLI imports --- packages/cli/src/server/desktop/mod.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/cli/src/server/desktop/mod.rs b/packages/cli/src/server/desktop/mod.rs index c89fb858c..ec21fa4c0 100644 --- a/packages/cli/src/server/desktop/mod.rs +++ b/packages/cli/src/server/desktop/mod.rs @@ -7,11 +7,10 @@ use crate::{ }; use dioxus_hot_reload::HotReloadMsg; -use dioxus_html::{HtmlCtx, SvgAttributes}; +use dioxus_html::HtmlCtx; use dioxus_rsx::hot_reload::*; use interprocess_docfix::local_socket::LocalSocketListener; use std::{ - collections::HashSet, process::{Child, Command}, sync::{Arc, Mutex, RwLock}, }; From 7649ad84a14aaf920f6ac9facbbdbb5787f41a25 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Sun, 17 Dec 2023 17:14:49 -0600 Subject: [PATCH 59/83] allow asset handlers to read the whole request --- packages/desktop/src/lib.rs | 2 +- packages/desktop/src/protocol.rs | 76 +++++++++++++++++++++++++------- packages/desktop/src/webview.rs | 2 +- 3 files changed, 61 insertions(+), 19 deletions(-) diff --git a/packages/desktop/src/lib.rs b/packages/desktop/src/lib.rs index 515c26009..18739aeda 100644 --- a/packages/desktop/src/lib.rs +++ b/packages/desktop/src/lib.rs @@ -32,7 +32,7 @@ use dioxus_html::{native_bind::NativeFileEngine, FormData, HtmlEvent}; use element::DesktopElement; use eval::init_eval; use futures_util::{pin_mut, FutureExt}; -pub use protocol::{use_asset_handler, AssetFuture, AssetHandler, AssetResponse}; +pub use protocol::{use_asset_handler, AssetFuture, AssetHandler, AssetRequest, AssetResponse}; use shortcut::ShortcutRegistry; pub use shortcut::{use_global_shortcut, ShortcutHandle, ShortcutId, ShortcutRegistryError}; use std::cell::Cell; diff --git a/packages/desktop/src/protocol.rs b/packages/desktop/src/protocol.rs index cb21245f8..31930da50 100644 --- a/packages/desktop/src/protocol.rs +++ b/packages/desktop/src/protocol.rs @@ -3,8 +3,8 @@ use dioxus_interpreter_js::{COMMON_JS, INTERPRETER_JS}; use slab::Slab; use std::{ borrow::Cow, - collections::HashMap, future::Future, + ops::{Deref, DerefMut}, path::{Path, PathBuf}, pin::Pin, rc::Rc, @@ -72,13 +72,57 @@ pub type AssetResponse = Response>; pub trait AssetFuture: Future> + Send + Sync + 'static {} impl> + Send + Sync + 'static> AssetFuture for T {} -/// A handler that takes an asset [`Path`] and returns a future that loads the path. +/// A request for an asset. This is a wrapper around [`Request>`] that provides methods specific to asset requests. +pub struct AssetRequest { + path: PathBuf, + request: Request>, +} + +impl AssetRequest { + /// Get the path the asset request is for + pub fn path(&self) -> &Path { + &self.path + } +} + +impl From>> for AssetRequest { + fn from(request: Request>) -> Self { + let decoded = urlencoding::decode(request.uri().path().trim_start_matches('/')) + .expect("expected URL to be UTF-8 encoded"); + let path = PathBuf::from(&*decoded); + Self { request, path } + } +} + +impl Deref for AssetRequest { + type Target = Request>; + + fn deref(&self) -> &Self::Target { + &self.request + } +} + +impl DerefMut for AssetRequest { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.request + } +} + +/// A handler that takes an [`AssetRequest`] and returns a future that either loads the asset, or returns `None`. /// This handler is stashed indefinitely in a context object, so it must be `'static`. -pub trait AssetHandler: Fn(&Path) -> F + Send + Sync + 'static {} -impl F + Send + Sync + 'static> AssetHandler for T {} +pub trait AssetHandler: Send + Sync + 'static { + /// Handle an asset request, returning a future that either loads the asset, or returns `None` + fn handle_request(&self, request: &AssetRequest) -> F; +} + +impl F + Send + Sync + 'static> AssetHandler for T { + fn handle_request(&self, request: &AssetRequest) -> F { + self(request) + } +} type AssetHandlerRegistryInner = - Slab Pin> + Send + Sync + 'static>>; + Slab Pin> + Send + Sync + 'static>>; #[derive(Clone)] pub struct AssetHandlerRegistry(Arc>); @@ -90,7 +134,7 @@ impl AssetHandlerRegistry { pub async fn register_handler(&self, f: impl AssetHandler) -> usize { let mut registry = self.0.write().await; - registry.insert(Box::new(move |path| Box::pin(f(path)))) + registry.insert(Box::new(move |req| Box::pin(f.handle_request(req)))) } pub async fn remove_handler(&self, id: usize) -> Option<()> { @@ -98,10 +142,10 @@ impl AssetHandlerRegistry { registry.try_remove(id).map(|_| ()) } - pub async fn try_handlers(&self, path: &Path) -> Option { + pub async fn try_handlers(&self, req: &AssetRequest) -> Option { let registry = self.0.read().await; for (_, handler) in registry.iter() { - if let Some(response) = handler(path).await { + if let Some(response) = handler(req).await { return Some(response); } } @@ -164,12 +208,14 @@ pub fn use_asset_handler( } pub(super) async fn desktop_handler( - request: &Request>, + request: Request>, custom_head: Option, custom_index: Option, root_name: &str, asset_handlers: &AssetHandlerRegistry, ) -> Result { + let request = AssetRequest::from(request); + // 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. @@ -204,25 +250,21 @@ pub(super) async fn desktop_handler( .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 user provided a custom asset handler, then call it and return the response // if the request was handled. - if let Some(response) = asset_handlers.try_handlers(&path).await { + if let Some(response) = asset_handlers.try_handlers(&request).await { return Ok(response); } // Else, try to serve a file from the filesystem. + // 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); + .join(&request.path); if !asset.exists() { - asset = PathBuf::from("/").join(path); + asset = PathBuf::from("/").join(request.path); } if asset.exists() { diff --git a/packages/desktop/src/webview.rs b/packages/desktop/src/webview.rs index 1b13216c7..0294d3460 100644 --- a/packages/desktop/src/webview.rs +++ b/packages/desktop/src/webview.rs @@ -54,7 +54,7 @@ pub fn build( let asset_handlers_ref = asset_handlers_ref.clone(); tokio::spawn(async move { let response_res = protocol::desktop_handler( - &request, + request, custom_head.clone(), index_file.clone(), &root_name, From 9eee4ab8f8ae0c58929adca2c411b84c02d82372 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Sun, 17 Dec 2023 17:14:55 -0600 Subject: [PATCH 60/83] add a dynamic asset example --- examples/dynamic_asset.rs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 examples/dynamic_asset.rs diff --git a/examples/dynamic_asset.rs b/examples/dynamic_asset.rs new file mode 100644 index 000000000..1c004e015 --- /dev/null +++ b/examples/dynamic_asset.rs @@ -0,0 +1,29 @@ +use dioxus::prelude::*; +use dioxus_desktop::wry::http::Response; +use dioxus_desktop::{use_asset_handler, AssetRequest}; +use std::path::Path; + +fn main() { + dioxus_desktop::launch(app); +} + +fn app(cx: Scope) -> Element { + use_asset_handler(cx, |request: &AssetRequest| { + let path = request.path().to_path_buf(); + async move { + if path != Path::new("logo.png") { + return None; + } + let image_data: &[u8] = include_bytes!("./assets/logo.png"); + Some(Response::new(image_data.into())) + } + }); + + cx.render(rsx! { + div { + img { + src: "logo.png" + } + } + }) +} From cd019db9ef89a39bf58e33064a4f32b370018acb Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 18 Dec 2023 08:04:53 -0600 Subject: [PATCH 61/83] Bump actions/upload-artifact from 3 to 4 (#1726) Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 3 to 4. - [Release notes](https://github.com/actions/upload-artifact/releases) - [Commits](https://github.com/actions/upload-artifact/compare/v3...v4) --- updated-dependencies: - dependency-name: actions/upload-artifact dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/playwright.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/playwright.yml b/.github/workflows/playwright.yml index cb5a1f1bb..7b23c6111 100644 --- a/.github/workflows/playwright.yml +++ b/.github/workflows/playwright.yml @@ -43,7 +43,7 @@ jobs: # args: --path packages/cli - name: Run Playwright tests run: npx playwright test - - uses: actions/upload-artifact@v3 + - uses: actions/upload-artifact@v4 if: always() with: name: playwright-report From ec4c1e0a441a6c475632de5244db9b889680471d Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Mon, 18 Dec 2023 08:32:50 -0600 Subject: [PATCH 62/83] add video stream example --- Cargo.toml | 1 + examples/video_stream.rs | 178 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 179 insertions(+) create mode 100644 examples/video_stream.rs diff --git a/Cargo.toml b/Cargo.toml index a78f60d3e..41cd7cd83 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -133,3 +133,4 @@ fern = { version = "0.6.0", features = ["colored"] } env_logger = "0.10.0" simple_logger = "4.0.0" thiserror = { workspace = true } +http-range = "0.1.5" diff --git a/examples/video_stream.rs b/examples/video_stream.rs new file mode 100644 index 000000000..6338a7d68 --- /dev/null +++ b/examples/video_stream.rs @@ -0,0 +1,178 @@ +use dioxus::prelude::*; +use dioxus_desktop::wry::http; +use dioxus_desktop::wry::http::Response; +use dioxus_desktop::{use_asset_handler, AssetRequest}; +use http::{header::*, response::Builder as ResponseBuilder, status::StatusCode}; +use std::borrow::Cow; +use std::sync::{Arc, Mutex}; +use std::{ + io::{Read, Seek, SeekFrom, Write}, + path::PathBuf, +}; + +fn main() { + dioxus_desktop::launch(app); +} + +fn app(cx: Scope) -> Element { + let id = Arc::new(Mutex::new(0)); + use_asset_handler(cx, move |request: &AssetRequest| { + let response: Option>> = match get_stream_response(request, &id) + { + Ok(response) => Some(response.map(Cow::Owned)), + Err(err) => { + eprintln!("Error: {}", err); + None + } + }; + async move { response } + }); + + cx.render(rsx! { + div { + video { + src: "test_video.mp4", + autoplay: true, + controls: true, + width: 640, + height: 480, + } + } + }) +} + +fn get_stream_response( + request: &AssetRequest, + boundary_id: &Arc>, +) -> Result>, Box> { + let video_file = PathBuf::from("./examples/assets/test_video.mp4"); + + let mut file = std::fs::File::open(&video_file)?; + + // get file length + let len = { + let old_pos = file.stream_position()?; + let len = file.seek(SeekFrom::End(0))?; + file.seek(SeekFrom::Start(old_pos))?; + len + }; + + let mut resp = ResponseBuilder::new().header(CONTENT_TYPE, "video/mp4"); + + // if the webview sent a range header, we need to send a 206 in return + // Actually only macOS and Windows are supported. Linux will ALWAYS return empty headers. + let http_response = if let Some(range_header) = request.headers().get("range") { + let not_satisfiable = || { + ResponseBuilder::new() + .status(StatusCode::RANGE_NOT_SATISFIABLE) + .header(CONTENT_RANGE, format!("bytes */{len}")) + .body(vec![]) + }; + + // parse range header + let ranges = if let Ok(ranges) = http_range::HttpRange::parse(range_header.to_str()?, len) { + ranges + .iter() + // map the output back to spec range , example: 0-499 + .map(|r| (r.start, r.start + r.length - 1)) + .collect::>() + } else { + return Ok(not_satisfiable()?); + }; + + /// The Maximum bytes we send in one range + const MAX_LEN: u64 = 1000 * 1024; + + if ranges.len() == 1 { + let &(start, mut end) = ranges.first().unwrap(); + + // check if a range is not satisfiable + // + // this should be already taken care of by HttpRange::parse + // but checking here again for extra assurance + if start >= len || end >= len || end < start { + return Ok(not_satisfiable()?); + } + + // adjust end byte for MAX_LEN + end = start + (end - start).min(len - start).min(MAX_LEN - 1); + + // calculate number of bytes needed to be read + let bytes_to_read = end + 1 - start; + + // allocate a buf with a suitable capacity + let mut buf = Vec::with_capacity(bytes_to_read as usize); + // seek the file to the starting byte + file.seek(SeekFrom::Start(start))?; + // read the needed bytes + file.take(bytes_to_read).read_to_end(&mut buf)?; + + resp = resp.header(CONTENT_RANGE, format!("bytes {start}-{end}/{len}")); + resp = resp.header(CONTENT_LENGTH, end + 1 - start); + resp = resp.status(StatusCode::PARTIAL_CONTENT); + resp.body(buf) + } else { + let mut buf = Vec::new(); + let ranges = ranges + .iter() + .filter_map(|&(start, mut end)| { + // filter out unsatisfiable ranges + // + // this should be already taken care of by HttpRange::parse + // but checking here again for extra assurance + if start >= len || end >= len || end < start { + None + } else { + // adjust end byte for MAX_LEN + end = start + (end - start).min(len - start).min(MAX_LEN - 1); + Some((start, end)) + } + }) + .collect::>(); + + let mut id = boundary_id.lock().unwrap(); + *id += 1; + let boundary = format!("sadasq2e{id}"); + let boundary_sep = format!("\r\n--{boundary}\r\n"); + let boundary_closer = format!("\r\n--{boundary}\r\n"); + + resp = resp.header( + CONTENT_TYPE, + format!("multipart/byteranges; boundary={boundary}"), + ); + + for (end, start) in ranges { + // a new range is being written, write the range boundary + buf.write_all(boundary_sep.as_bytes())?; + + // write the needed headers `Content-Type` and `Content-Range` + buf.write_all(format!("{CONTENT_TYPE}: video/mp4\r\n").as_bytes())?; + buf.write_all( + format!("{CONTENT_RANGE}: bytes {start}-{end}/{len}\r\n").as_bytes(), + )?; + + // write the separator to indicate the start of the range body + buf.write_all("\r\n".as_bytes())?; + + // calculate number of bytes needed to be read + let bytes_to_read = end + 1 - start; + + let mut local_buf = vec![0_u8; bytes_to_read as usize]; + file.seek(SeekFrom::Start(start))?; + file.read_exact(&mut local_buf)?; + buf.extend_from_slice(&local_buf); + } + // all ranges have been written, write the closing boundary + buf.write_all(boundary_closer.as_bytes())?; + + resp.body(buf) + } + } else { + resp = resp.header(CONTENT_LENGTH, len); + let mut buf = Vec::with_capacity(len as usize); + file.read_to_end(&mut buf)?; + resp.body(buf) + }; + + http_response.map_err(Into::into) +} From dfb118e06ccc97885979da3bd8924de330b2078d Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Mon, 18 Dec 2023 09:34:30 -0600 Subject: [PATCH 63/83] make the video streaming async --- .gitignore | 1 + examples/video_stream.rs | 108 ++++++++++++++++--------------- packages/desktop/src/protocol.rs | 16 ++--- 3 files changed, 65 insertions(+), 60 deletions(-) diff --git a/.gitignore b/.gitignore index b8025753e..364e8d0fb 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,7 @@ /dist Cargo.lock .DS_Store +/examples/assets/test_video.mp4 .vscode/* !.vscode/settings.json diff --git a/examples/video_stream.rs b/examples/video_stream.rs index 6338a7d68..f495299f4 100644 --- a/examples/video_stream.rs +++ b/examples/video_stream.rs @@ -4,56 +4,64 @@ use dioxus_desktop::wry::http::Response; use dioxus_desktop::{use_asset_handler, AssetRequest}; use http::{header::*, response::Builder as ResponseBuilder, status::StatusCode}; use std::borrow::Cow; -use std::sync::{Arc, Mutex}; -use std::{ - io::{Read, Seek, SeekFrom, Write}, - path::PathBuf, -}; +use std::{io::SeekFrom, path::PathBuf}; +use tokio::io::AsyncReadExt; +use tokio::io::AsyncSeekExt; +use tokio::io::AsyncWriteExt; + +const VIDEO_PATH: &str = "./examples/assets/test_video.mp4"; fn main() { + let video_file = PathBuf::from(VIDEO_PATH); + if !video_file.exists() { + tokio::runtime::Runtime::new() + .unwrap() + .block_on(async move { + println!("Downloading video file..."); + let video_url = + "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"; + let mut response = reqwest::get(video_url).await.unwrap(); + let mut file = tokio::fs::File::create(&video_file).await.unwrap(); + while let Some(chunk) = response.chunk().await.unwrap() { + file.write_all(&chunk).await.unwrap(); + } + }); + } dioxus_desktop::launch(app); } fn app(cx: Scope) -> Element { - let id = Arc::new(Mutex::new(0)); use_asset_handler(cx, move |request: &AssetRequest| { - let response: Option>> = match get_stream_response(request, &id) - { - Ok(response) => Some(response.map(Cow::Owned)), - Err(err) => { - eprintln!("Error: {}", err); - None - } - }; - async move { response } + let request = request.clone(); + async move { + let video_file = PathBuf::from(VIDEO_PATH); + let mut file = tokio::fs::File::open(&video_file).await.unwrap(); + let response: Option>> = + match get_stream_response(&mut file, &request).await { + Ok(response) => Some(response.map(Cow::Owned)), + Err(err) => { + eprintln!("Error: {}", err); + None + } + }; + response + } }); - cx.render(rsx! { - div { - video { - src: "test_video.mp4", - autoplay: true, - controls: true, - width: 640, - height: 480, - } - } - }) + render! { + div { video { src: "test_video.mp4", autoplay: true, controls: true, width: 640, height: 480 } } + } } -fn get_stream_response( +async fn get_stream_response( + asset: &mut (impl tokio::io::AsyncSeek + tokio::io::AsyncRead + Unpin + Send + Sync), request: &AssetRequest, - boundary_id: &Arc>, ) -> Result>, Box> { - let video_file = PathBuf::from("./examples/assets/test_video.mp4"); - - let mut file = std::fs::File::open(&video_file)?; - - // get file length + // get stream length let len = { - let old_pos = file.stream_position()?; - let len = file.seek(SeekFrom::End(0))?; - file.seek(SeekFrom::Start(old_pos))?; + let old_pos = asset.stream_position().await?; + let len = asset.seek(SeekFrom::End(0)).await?; + asset.seek(SeekFrom::Start(old_pos)).await?; len }; @@ -103,9 +111,9 @@ fn get_stream_response( // allocate a buf with a suitable capacity let mut buf = Vec::with_capacity(bytes_to_read as usize); // seek the file to the starting byte - file.seek(SeekFrom::Start(start))?; + asset.seek(SeekFrom::Start(start)).await?; // read the needed bytes - file.take(bytes_to_read).read_to_end(&mut buf)?; + asset.take(bytes_to_read).read_to_end(&mut buf).await?; resp = resp.header(CONTENT_RANGE, format!("bytes {start}-{end}/{len}")); resp = resp.header(CONTENT_LENGTH, end + 1 - start); @@ -130,9 +138,7 @@ fn get_stream_response( }) .collect::>(); - let mut id = boundary_id.lock().unwrap(); - *id += 1; - let boundary = format!("sadasq2e{id}"); + let boundary = format!("{:x}", rand::random::()); let boundary_sep = format!("\r\n--{boundary}\r\n"); let boundary_closer = format!("\r\n--{boundary}\r\n"); @@ -143,34 +149,34 @@ fn get_stream_response( for (end, start) in ranges { // a new range is being written, write the range boundary - buf.write_all(boundary_sep.as_bytes())?; + buf.write_all(boundary_sep.as_bytes()).await?; // write the needed headers `Content-Type` and `Content-Range` - buf.write_all(format!("{CONTENT_TYPE}: video/mp4\r\n").as_bytes())?; - buf.write_all( - format!("{CONTENT_RANGE}: bytes {start}-{end}/{len}\r\n").as_bytes(), - )?; + buf.write_all(format!("{CONTENT_TYPE}: video/mp4\r\n").as_bytes()) + .await?; + buf.write_all(format!("{CONTENT_RANGE}: bytes {start}-{end}/{len}\r\n").as_bytes()) + .await?; // write the separator to indicate the start of the range body - buf.write_all("\r\n".as_bytes())?; + buf.write_all("\r\n".as_bytes()).await?; // calculate number of bytes needed to be read let bytes_to_read = end + 1 - start; let mut local_buf = vec![0_u8; bytes_to_read as usize]; - file.seek(SeekFrom::Start(start))?; - file.read_exact(&mut local_buf)?; + asset.seek(SeekFrom::Start(start)).await?; + asset.read_exact(&mut local_buf).await?; buf.extend_from_slice(&local_buf); } // all ranges have been written, write the closing boundary - buf.write_all(boundary_closer.as_bytes())?; + buf.write_all(boundary_closer.as_bytes()).await?; resp.body(buf) } } else { resp = resp.header(CONTENT_LENGTH, len); let mut buf = Vec::with_capacity(len as usize); - file.read_to_end(&mut buf)?; + asset.read_to_end(&mut buf).await?; resp.body(buf) }; diff --git a/packages/desktop/src/protocol.rs b/packages/desktop/src/protocol.rs index 31930da50..46be1b942 100644 --- a/packages/desktop/src/protocol.rs +++ b/packages/desktop/src/protocol.rs @@ -4,7 +4,7 @@ use slab::Slab; use std::{ borrow::Cow, future::Future, - ops::{Deref, DerefMut}, + ops::Deref, path::{Path, PathBuf}, pin::Pin, rc::Rc, @@ -72,10 +72,11 @@ pub type AssetResponse = Response>; pub trait AssetFuture: Future> + Send + Sync + 'static {} impl> + Send + Sync + 'static> AssetFuture for T {} +#[derive(Debug, Clone)] /// A request for an asset. This is a wrapper around [`Request>`] that provides methods specific to asset requests. pub struct AssetRequest { path: PathBuf, - request: Request>, + request: Arc>>, } impl AssetRequest { @@ -90,7 +91,10 @@ impl From>> for AssetRequest { let decoded = urlencoding::decode(request.uri().path().trim_start_matches('/')) .expect("expected URL to be UTF-8 encoded"); let path = PathBuf::from(&*decoded); - Self { request, path } + Self { + request: Arc::new(request), + path, + } } } @@ -102,12 +106,6 @@ impl Deref for AssetRequest { } } -impl DerefMut for AssetRequest { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.request - } -} - /// A handler that takes an [`AssetRequest`] and returns a future that either loads the asset, or returns `None`. /// This handler is stashed indefinitely in a context object, so it must be `'static`. pub trait AssetHandler: Send + Sync + 'static { From 1880bdb308c15233a78cf313190ec41254137b93 Mon Sep 17 00:00:00 2001 From: ealmloff Date: Wed, 20 Dec 2023 10:28:24 -0600 Subject: [PATCH 64/83] Remove link to Tide's contributing guidelines --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d1ec98019..65cd08263 100644 --- a/README.md +++ b/README.md @@ -161,7 +161,7 @@ So... Dioxus is great, but why won't it work for me? ## Contributing - Check out the website [section on contributing](https://dioxuslabs.com/learn/0.4/contributing). - Report issues on our [issue tracker](https://github.com/dioxuslabs/dioxus/issues). -- Join the discord and ask questions! +- [Join](https://discord.gg/XgGxMSkvUM) the discord and ask questions! From 37e9876a703e03b891f795aaf70142f461ba3bd5 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Wed, 20 Dec 2023 15:18:20 -0600 Subject: [PATCH 65/83] bump salvo --- packages/fullstack/Cargo.toml | 2 +- packages/fullstack/examples/salvo-hello-world/Cargo.toml | 2 +- packages/liveview/Cargo.toml | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/fullstack/Cargo.toml b/packages/fullstack/Cargo.toml index 8de27a9b1..2f3eca420 100644 --- a/packages/fullstack/Cargo.toml +++ b/packages/fullstack/Cargo.toml @@ -26,7 +26,7 @@ tower = { version = "0.4.13", features = ["util"], optional = true } axum-macros = "0.3.7" # salvo -salvo = { version = "0.46.0", optional = true, features = ["serve-static", "websocket", "compression"] } +salvo = { version = "0.63.0", optional = true, features = ["serve-static", "websocket", "compression"] } serde = "1.0.159" # Dioxus + SSR diff --git a/packages/fullstack/examples/salvo-hello-world/Cargo.toml b/packages/fullstack/examples/salvo-hello-world/Cargo.toml index ca0d85ecf..3d4e74c5b 100644 --- a/packages/fullstack/examples/salvo-hello-world/Cargo.toml +++ b/packages/fullstack/examples/salvo-hello-world/Cargo.toml @@ -12,7 +12,7 @@ dioxus = { workspace = true } dioxus-fullstack = { workspace = true } tokio = { workspace = true, features = ["full"], optional = true } serde = "1.0.159" -salvo = { version = "0.37.9", optional = true } +salvo = { version = "0.63.0", optional = true } execute = "0.2.12" reqwest = "0.11.18" simple_logger = "4.2.0" diff --git a/packages/liveview/Cargo.toml b/packages/liveview/Cargo.toml index cbd7b75f5..50d984c7e 100644 --- a/packages/liveview/Cargo.toml +++ b/packages/liveview/Cargo.toml @@ -34,7 +34,7 @@ warp = { version = "0.3.3", optional = true } axum = { version = "0.6.1", optional = true, features = ["ws"] } # salvo -salvo = { version = "0.44.1", optional = true, features = ["ws"] } +salvo = { version = "0.63.0", optional = true, features = ["websocket"] } once_cell = "1.17.1" async-trait = "0.1.71" @@ -49,7 +49,7 @@ tokio = { workspace = true, features = ["full"] } dioxus = { workspace = true } warp = "0.3.3" axum = { version = "0.6.1", features = ["ws"] } -salvo = { version = "0.44.1", features = ["affix", "ws"] } +salvo = { version = "0.63.0", features = ["affix", "websocket"] } tower = "0.4.13" [features] From 451d935aa2cadbf0c681b6296b89d7220feda4d2 Mon Sep 17 00:00:00 2001 From: tigerros Date: Sat, 30 Dec 2023 01:18:50 +0100 Subject: [PATCH 66/83] fix typo (#1759) --- packages/core/src/lazynodes.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/core/src/lazynodes.rs b/packages/core/src/lazynodes.rs index 3189086b4..ae1bd2109 100644 --- a/packages/core/src/lazynodes.rs +++ b/packages/core/src/lazynodes.rs @@ -18,7 +18,7 @@ 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. /// /// From 3733fbf47d8da934432778c149073473297f6715 Mon Sep 17 00:00:00 2001 From: Georges KABBOUCHI Date: Sat, 30 Dec 2023 21:49:32 +0200 Subject: [PATCH 67/83] feat(liveview): add rocket adapter (#1761) --- packages/liveview/Cargo.toml | 13 +++- packages/liveview/README.md | 1 + packages/liveview/examples/rocket.rs | 76 +++++++++++++++++++ .../liveview/src/adapters/rocket_adapter.rs | 25 ++++++ packages/liveview/src/lib.rs | 5 ++ 5 files changed, 119 insertions(+), 1 deletion(-) create mode 100644 packages/liveview/examples/rocket.rs create mode 100644 packages/liveview/src/adapters/rocket_adapter.rs diff --git a/packages/liveview/Cargo.toml b/packages/liveview/Cargo.toml index cbd7b75f5..0f35f4ae6 100644 --- a/packages/liveview/Cargo.toml +++ b/packages/liveview/Cargo.toml @@ -38,6 +38,10 @@ salvo = { version = "0.44.1", optional = true, features = ["ws"] } once_cell = "1.17.1" async-trait = "0.1.71" +# rocket +rocket = { version = "0.5.0", optional = true } +rocket_ws = { version = "0.1.0", optional = true } + # actix is ... complicated? # actix-files = { version = "0.6.2", optional = true } # actix-web = { version = "4.2.1", optional = true } @@ -49,13 +53,16 @@ tokio = { workspace = true, features = ["full"] } dioxus = { workspace = true } warp = "0.3.3" axum = { version = "0.6.1", features = ["ws"] } -salvo = { version = "0.44.1", features = ["affix", "ws"] } +# salvo = { version = "0.44.1", features = ["affix", "ws"] } +rocket = "0.5.0" +rocket_ws = "0.1.0" tower = "0.4.13" [features] default = ["hot-reload"] # actix = ["actix-files", "actix-web", "actix-ws"] hot-reload = ["dioxus-hot-reload"] +rocket = ["dep:rocket", "dep:rocket_ws"] [[example]] name = "axum" @@ -68,3 +75,7 @@ required-features = ["salvo"] [[example]] name = "warp" required-features = ["warp"] + +[[example]] +name = "rocket" +required-features = ["rocket"] diff --git a/packages/liveview/README.md b/packages/liveview/README.md index cbae3c53a..13af3c36f 100644 --- a/packages/liveview/README.md +++ b/packages/liveview/README.md @@ -28,6 +28,7 @@ The current backend frameworks supported include: - Axum - Warp - Salvo +- Rocket Dioxus-LiveView exports some primitives to wire up an app into an existing backend framework. diff --git a/packages/liveview/examples/rocket.rs b/packages/liveview/examples/rocket.rs new file mode 100644 index 000000000..8256db7f8 --- /dev/null +++ b/packages/liveview/examples/rocket.rs @@ -0,0 +1,76 @@ +#[macro_use] +extern crate rocket; + +use dioxus::prelude::*; +use dioxus_liveview::LiveViewPool; +use rocket::response::content::RawHtml; +use rocket::{Config, Rocket, State}; +use rocket_ws::{Channel, WebSocket}; + +fn app(cx: Scope) -> Element { + let mut num = use_state(cx, || 0); + + cx.render(rsx! { + div { + "hello Rocket! {num}" + button { onclick: move |_| num += 1, "Increment" } + } + }) +} + +fn index_page_with_glue(glue: &str) -> RawHtml { + RawHtml(format!( + r#" + + + Dioxus LiveView with Rocket +

+ {glue} + + "#, + glue = glue + )) +} + +#[get("/")] +async fn index(config: &Config) -> RawHtml { + index_page_with_glue(&dioxus_liveview::interpreter_glue(&format!( + "ws://{addr}:{port}/ws", + addr = config.address, + port = config.port, + ))) +} + +#[get("/as-path")] +async fn as_path() -> RawHtml { + index_page_with_glue(&dioxus_liveview::interpreter_glue("/ws")) +} + +#[get("/ws")] +fn ws(ws: WebSocket, pool: &State) -> Channel<'static> { + let pool = pool.inner().to_owned(); + + ws.channel(move |stream| { + Box::pin(async move { + let _ = pool + .launch(dioxus_liveview::rocket_socket(stream), app) + .await; + Ok(()) + }) + }) +} + +#[tokio::main] +async fn main() { + let view = dioxus_liveview::LiveViewPool::new(); + + Rocket::build() + .manage(view) + .mount("/", routes![index, as_path, ws]) + .ignite() + .await + .expect("Failed to ignite rocket") + .launch() + .await + .expect("Failed to launch rocket"); +} diff --git a/packages/liveview/src/adapters/rocket_adapter.rs b/packages/liveview/src/adapters/rocket_adapter.rs new file mode 100644 index 000000000..8a9840bf2 --- /dev/null +++ b/packages/liveview/src/adapters/rocket_adapter.rs @@ -0,0 +1,25 @@ +use crate::{LiveViewError, LiveViewSocket}; +use rocket::futures::{SinkExt, StreamExt}; +use rocket_ws::{result::Error, stream::DuplexStream, Message}; + +/// Convert a rocket websocket into a LiveViewSocket +/// +/// This is required to launch a LiveView app using the rocket web framework +pub fn rocket_socket(stream: DuplexStream) -> impl LiveViewSocket { + stream + .map(transform_rx) + .with(transform_tx) + .sink_map_err(|_| LiveViewError::SendingFailed) +} + +fn transform_rx(message: Result) -> Result, LiveViewError> { + message + .map_err(|_| LiveViewError::SendingFailed)? + .into_text() + .map(|s| s.into_bytes()) + .map_err(|_| LiveViewError::SendingFailed) +} + +async fn transform_tx(message: Vec) -> Result { + Ok(Message::Text(String::from_utf8_lossy(&message).to_string())) +} diff --git a/packages/liveview/src/lib.rs b/packages/liveview/src/lib.rs index 6a2768fd5..40d6186dc 100644 --- a/packages/liveview/src/lib.rs +++ b/packages/liveview/src/lib.rs @@ -18,6 +18,11 @@ pub mod adapters { #[cfg(feature = "salvo")] pub use salvo_adapter::*; + + #[cfg(feature = "rocket")] + pub mod rocket_adapter; + #[cfg(feature = "rocket")] + pub use rocket_adapter::*; } pub use adapters::*; From 0166eafafb20eaf7acdbdd67bae44d037c3870b1 Mon Sep 17 00:00:00 2001 From: Hampus Lidin Date: Sat, 30 Dec 2023 20:53:12 +0100 Subject: [PATCH 68/83] Send mount event when hydrating (#1764) --- packages/web/src/dom.rs | 26 +++++++++++++++----------- packages/web/src/rehydrate.rs | 19 ++++++++++++++----- 2 files changed, 29 insertions(+), 16 deletions(-) diff --git a/packages/web/src/dom.rs b/packages/web/src/dom.rs index b8e9255f7..22701bf4e 100644 --- a/packages/web/src/dom.rs +++ b/packages/web/src/dom.rs @@ -256,17 +256,21 @@ impl WebsysDom { i.flush(); for id in to_mount { - let node = get_node(id.0 as u32); - if let Some(element) = node.dyn_ref::() { - let data: MountedData = element.into(); - let data = Rc::new(data); - let _ = self.event_channel.unbounded_send(UiEvent { - name: "mounted".to_string(), - bubbles: false, - element: id, - data, - }); - } + self.send_mount_event(id); + } + } + + pub(crate) fn send_mount_event(&self, id: ElementId) { + let node = get_node(id.0 as u32); + if let Some(element) = node.dyn_ref::() { + let data: MountedData = element.into(); + let data = Rc::new(data); + let _ = self.event_channel.unbounded_send(UiEvent { + name: "mounted".to_string(), + bubbles: false, + element: id, + data, + }); } } } diff --git a/packages/web/src/rehydrate.rs b/packages/web/src/rehydrate.rs index 4415ceb37..11c68f89c 100644 --- a/packages/web/src/rehydrate.rs +++ b/packages/web/src/rehydrate.rs @@ -125,6 +125,7 @@ impl WebsysDom { children, attrs, .. } => { let mut mounted_id = None; + let mut should_send_mount_event = true; for attr in *attrs { if let dioxus_core::TemplateAttribute::Dynamic { id } = attr { let attribute = &vnode.dynamic_attrs[*id]; @@ -134,16 +135,24 @@ impl WebsysDom { let name = attribute.name; if let AttributeValue::Listener(_) = value { let event_name = &name[2..]; - self.interpreter.new_event_listener( - event_name, - id.0 as u32, - event_bubbles(event_name) as u8, - ); + match event_name { + "mounted" => should_send_mount_event = true, + _ => { + self.interpreter.new_event_listener( + event_name, + id.0 as u32, + event_bubbles(event_name) as u8, + ); + } + } } } } if let Some(id) = mounted_id { set_node(hydrated, id, current_child.clone()?); + if should_send_mount_event { + self.send_mount_event(id); + } } if !children.is_empty() { let mut children_current_child = current_child From a0b95a82a0fa16d9101897554444878da7096f74 Mon Sep 17 00:00:00 2001 From: werner291 Date: Mon, 1 Jan 2024 17:22:52 +0100 Subject: [PATCH 69/83] Implemented From> for ReadOnlySignal (#1772) --- packages/signals/src/signal.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/signals/src/signal.rs b/packages/signals/src/signal.rs index 1dc4bd36e..946a6c380 100644 --- a/packages/signals/src/signal.rs +++ b/packages/signals/src/signal.rs @@ -495,3 +495,9 @@ impl Deref for ReadOnlySignal { reference_to_closure as &Self::Target } } + +impl From> for ReadOnlySignal { + fn from(signal: Signal) -> Self { + Self::new(signal) + } +} From 8230566c4d761f6235ce4eba5a990bcb35af194f Mon Sep 17 00:00:00 2001 From: Hampus Lidin Date: Tue, 2 Jan 2024 17:01:53 +0100 Subject: [PATCH 70/83] Add doc comment on generated inline properties struct (#1775) --- .../core-macro/src/component_body_deserializers/component.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/core-macro/src/component_body_deserializers/component.rs b/packages/core-macro/src/component_body_deserializers/component.rs index 36cda850c..994e51709 100644 --- a/packages/core-macro/src/component_body_deserializers/component.rs +++ b/packages/core-macro/src/component_body_deserializers/component.rs @@ -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 From fd7c9e0359823f767f8b90a0b156be4babdb7a22 Mon Sep 17 00:00:00 2001 From: abhi Date: Tue, 2 Jan 2024 16:02:58 +0000 Subject: [PATCH 71/83] fix empty render causing panic (#1769) (#1774) * fix empty render causing panic (#1769) * use an default root column instead of an empty root column * fix formatting * restore create.rs in core --------- Co-authored-by: Evan Almloff --- packages/core/src/create.rs | 3 +- packages/rsx/src/lib.rs | 17 ++++--- packages/ssr/src/renderer.rs | 88 ++++++++++++++++++++++++++++++++++++ 3 files changed, 101 insertions(+), 7 deletions(-) diff --git a/packages/core/src/create.rs b/packages/core/src/create.rs index a61a8cace..733a796ce 100644 --- a/packages/core/src/create.rs +++ b/packages/core/src/create.rs @@ -205,7 +205,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 /// @@ -405,6 +405,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::().unwrap(); // First, check if we've already seen this template if self diff --git a/packages/rsx/src/lib.rs b/packages/rsx/src/lib.rs index 5db6baee9..458075b63 100644 --- a/packages/rsx/src/lib.rs +++ b/packages/rsx/src/lib.rs @@ -204,12 +204,17 @@ impl<'a> ToTokens for TemplateRenderer<'a> { None => quote! { None }, }; - let spndbg = format!("{:?}", self.roots[0].span()); - let root_col = spndbg - .rsplit_once("..") - .and_then(|(_, after)| after.split_once(')').map(|(before, _)| before)) - .unwrap_or_default(); - + let root_col = match self.roots.first() { + Some(first_root) => { + let first_root_span = format!("{:?}", first_root.span()); + first_root_span + .rsplit_once("..") + .and_then(|(_, after)| after.split_once(')').map(|(before, _)| before)) + .unwrap_or_default() + .to_string() + } + _ => "0".to_string(), + }; let root_printer = self.roots.iter().enumerate().map(|(idx, root)| { context.current_path.push(idx as u8); let out = context.render_static_node(root); diff --git a/packages/ssr/src/renderer.rs b/packages/ssr/src/renderer.rs index 98afef8b7..c0f9b6c75 100644 --- a/packages/ssr/src/renderer.rs +++ b/packages/ssr/src/renderer.rs @@ -238,6 +238,94 @@ fn to_string_works() { assert_eq!(out, "
Hello world 1 -->123<-- Hello world 2
nest 1
nest 2
</diiiiiiiiv>
finalize 0
finalize 1
finalize 2
finalize 3
finalize 4
"); } +#[test] +fn empty_for_loop_works() { + use dioxus::prelude::*; + + fn app(cx: Scope) -> Element { + render! { + div { class: "asdasdasd", + for _ in (0..5) { + + } + } + } + } + + let mut dom = VirtualDom::new(app); + _ = dom.rebuild(); + + let mut renderer = Renderer::new(); + let out = renderer.render(&dom); + + for item in renderer.template_cache.iter() { + if item.1.segments.len() > 5 { + assert_eq!( + item.1.segments, + vec![ + PreRendered("
".into()), + InnerHtmlMarker, + PreRendered("
".into(),), + ] + ); + } + } + + use Segment::*; + + assert_eq!(out, "
"); +} + +#[test] +fn empty_render_works() { + use dioxus::prelude::*; + + fn app(cx: Scope) -> Element { + render! {} + } + + let mut dom = VirtualDom::new(app); + _ = dom.rebuild(); + + let mut renderer = Renderer::new(); + let out = renderer.render(&dom); + + for item in renderer.template_cache.iter() { + if item.1.segments.len() > 5 { + assert_eq!(item.1.segments, vec![]); + } + } + assert_eq!(out, ""); +} + +#[test] +fn empty_rsx_works() { + use dioxus::prelude::*; + + fn app(_: Scope) -> Element { + rsx! {}; + None + } + + let mut dom = VirtualDom::new(app); + _ = dom.rebuild(); + + let mut renderer = Renderer::new(); + let out = renderer.render(&dom); + + for item in renderer.template_cache.iter() { + if item.1.segments.len() > 5 { + assert_eq!(item.1.segments, vec![]); + } + } + assert_eq!(out, ""); +} + pub(crate) const BOOL_ATTRS: &[&str] = &[ "allowfullscreen", "allowpaymentrequest", From 80a8e1f512bbaeb71695107e64d1d2d3c10477f9 Mon Sep 17 00:00:00 2001 From: Bennett-Petzold <46354948+Bennett-Petzold@users.noreply.github.com> Date: Tue, 2 Jan 2024 16:19:29 -0500 Subject: [PATCH 72/83] Add Cargo Arguments and Cross-Architecture Support (#1777) * Add passthrough to cargo build * Add platform_triple flag * Add handling to bundle and serve commands * Show full stacked error from Tauri in bundling Previously only the top-level error was shown, giving only vague data for debugging the build process * Adjust bundle platform triple when cross compiling * Rename --platform-triple to --target * restore some deleted docs on CLI commands --------- Co-authored-by: Evan Almloff --- packages/cli/src/builder.rs | 17 ++++++++++++++++- packages/cli/src/cli/build.rs | 6 ++++++ packages/cli/src/cli/bundle.rs | 15 +++++++++++++-- packages/cli/src/cli/cfg.rs | 32 ++++++++++++++++++++++++-------- packages/cli/src/cli/serve.rs | 6 ++++++ packages/cli/src/config.rs | 16 ++++++++++++++++ 6 files changed, 81 insertions(+), 11 deletions(-) diff --git a/packages/cli/src/builder.rs b/packages/cli/src/builder.rs index 759be7dec..a5721d7a6 100644 --- a/packages/cli/src/builder.rs +++ b/packages/cli/src/builder.rs @@ -93,6 +93,8 @@ pub fn build(config: &CrateConfig, quiet: bool) -> Result { 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), @@ -286,6 +288,14 @@ pub fn build_desktop(config: &CrateConfig, _is_serve: bool) -> Result cmd.arg("--bin").arg(name), crate::ExecutableType::Lib(name) => cmd.arg("--lib").arg(name), @@ -303,12 +313,17 @@ pub fn build_desktop(config: &CrateConfig, _is_serve: bool) -> Result { file_name = name.clone(); - config.target_dir.join(release_type).join(name) + config + .target_dir + .join(target_platform) + .join(release_type) + .join(name) } crate::ExecutableType::Example(name) => { file_name = name.clone(); config .target_dir + .join(target_platform) .join(release_type) .join("examples") .join(name) diff --git a/packages/cli/src/cli/build.rs b/packages/cli/src/cli/build.rs index 63a2969e0..0deeb38ca 100644 --- a/packages/cli/src/cli/build.rs +++ b/packages/cli/src/cli/build.rs @@ -37,6 +37,12 @@ impl Build { .platform .unwrap_or(crate_config.dioxus_config.application.default_platform); + if let Some(target) = self.build.target { + crate_config.set_target(target); + } + + crate_config.set_cargo_args(self.build.cargo_args); + // #[cfg(feature = "plugin")] // let _ = PluginManager::on_build_start(&crate_config, &platform); diff --git a/packages/cli/src/cli/bundle.rs b/packages/cli/src/cli/bundle.rs index 80b52cf2f..fd97930ed 100644 --- a/packages/cli/src/cli/bundle.rs +++ b/packages/cli/src/cli/bundle.rs @@ -76,6 +76,12 @@ 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)?; @@ -148,6 +154,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 +167,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(()) diff --git a/packages/cli/src/cli/cfg.rs b/packages/cli/src/cli/cfg.rs index 2a441a1c8..0d2a5e212 100644 --- a/packages/cli/src/cli/cfg.rs +++ b/packages/cli/src/cli/cfg.rs @@ -6,10 +6,6 @@ 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, - /// Build in release mode [default: false] #[clap(long)] #[serde(default)] @@ -35,14 +31,18 @@ pub struct ConfigOptsBuild { /// Space separated list of features to activate #[clap(long)] pub features: Option>, + + /// Rustc platform triple + #[clap(long)] + pub target: Option, + + /// Extra arguments passed to cargo build + #[clap(last = true)] + pub cargo_args: Vec, } #[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, - /// Port of dev server #[clap(long)] #[clap(default_value_t = 8080)] @@ -89,6 +89,14 @@ pub struct ConfigOptsServe { /// Space separated list of features to activate #[clap(long)] pub features: Option>, + + /// Rustc platform triple + #[clap(long)] + pub target: Option, + + /// Extra arguments passed to cargo build + #[clap(last = true)] + pub cargo_args: Vec, } #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Serialize, Deserialize, Debug)] @@ -129,4 +137,12 @@ pub struct ConfigOptsBundle { /// Space separated list of features to activate #[clap(long)] pub features: Option>, + + /// Rustc platform triple + #[clap(long)] + pub target: Option, + + /// Extra arguments passed to cargo build + #[clap(last = true)] + pub cargo_args: Vec, } diff --git a/packages/cli/src/cli/serve.rs b/packages/cli/src/cli/serve.rs index 433d611b7..e08b02339 100644 --- a/packages/cli/src/cli/serve.rs +++ b/packages/cli/src/cli/serve.rs @@ -34,6 +34,12 @@ impl Serve { // 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 .platform diff --git a/packages/cli/src/config.rs b/packages/cli/src/config.rs index 3abf47f0c..727504e6a 100644 --- a/packages/cli/src/config.rs +++ b/packages/cli/src/config.rs @@ -211,6 +211,8 @@ pub struct CrateConfig { pub verbose: bool, pub custom_profile: Option, pub features: Option>, + pub target: Option, + pub cargo_args: Vec, } #[derive(Debug, Clone)] @@ -278,6 +280,8 @@ impl CrateConfig { let verbose = false; let custom_profile = None; let features = None; + let target = None; + let cargo_args = vec![]; Ok(Self { out_dir, @@ -294,6 +298,8 @@ impl CrateConfig { custom_profile, features, verbose, + target, + cargo_args, }) } @@ -331,6 +337,16 @@ impl CrateConfig { 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) -> &mut Self { + self.cargo_args = cargo_args; + self + } } #[derive(Debug, Clone, Serialize, Deserialize, Default)] From 2f9b6e7dea89f4af422d6c56f315e7ecc8880c37 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Wed, 3 Jan 2024 08:26:14 -0600 Subject: [PATCH 73/83] fix non string layout attributes in rink --- packages/rink/src/layout.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/rink/src/layout.rs b/packages/rink/src/layout.rs index dbdadac3f..72c8f68b2 100644 --- a/packages/rink/src/layout.rs +++ b/packages/rink/src/layout.rs @@ -92,10 +92,10 @@ impl State for TaffyLayout { attribute, value, .. } in attributes { - if let Some(text) = value.as_text() { + if value.as_custom().is_none() { apply_layout_attributes_cfg( &attribute.name, - text, + &value.to_string(), &mut style, &LayoutConfigeration { border_widths: BorderWidths { From cde5ac5f585c607d6b53f29e8e7ecac88df34306 Mon Sep 17 00:00:00 2001 From: ealmloff Date: Wed, 3 Jan 2024 14:01:50 -0600 Subject: [PATCH 74/83] fix invalid locations never being dropped (#1747) --- packages/generational-box/src/lib.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/generational-box/src/lib.rs b/packages/generational-box/src/lib.rs index f56904ede..57a02a5d7 100644 --- a/packages/generational-box/src/lib.rs +++ b/packages/generational-box/src/lib.rs @@ -700,14 +700,16 @@ impl Owner { /// Creates an invalid handle. This is useful for creating a handle that will be filled in later. If you use this before the value is filled in, you will get may get a panic or an out of date value. pub fn invalid(&self) -> GenerationalBox { let location = self.store.claim(); - GenerationalBox { + let key = GenerationalBox { raw: location, #[cfg(any(debug_assertions, feature = "check_generation"))] generation: location.0.generation.get(), #[cfg(any(debug_assertions, feature = "debug_ownership"))] created_at: std::panic::Location::caller(), _marker: PhantomData, - } + }; + self.owned.borrow_mut().push(location); + key } } From 937be8b752c48b03f02014130970fa924981cc91 Mon Sep 17 00:00:00 2001 From: ealmloff Date: Wed, 3 Jan 2024 14:02:08 -0600 Subject: [PATCH 75/83] fix the on double click event and depreciate ondblclick (#1743) --- examples/all_events.rs | 11 +- examples/todomvc.rs | 89 ++++++++------- packages/desktop/headless_tests/events.rs | 101 ++++++++++++------ .../examples/all_terminal_events.rs | 20 ++-- packages/fullstack/src/hooks/server_cached.rs | 4 +- packages/html/src/events/mouse.rs | 18 +++- packages/web/src/cache.rs | 2 +- 7 files changed, 143 insertions(+), 102 deletions(-) diff --git a/examples/all_events.rs b/examples/all_events.rs index 594a736d5..3f57ec747 100644 --- a/examples/all_events.rs +++ b/examples/all_events.rs @@ -53,8 +53,7 @@ fn app(cx: Scope) -> Element { }; cx.render(rsx! ( - div { - style: "{CONTAINER_STYLE}", + div { style: "{CONTAINER_STYLE}", div { style: "{RECT_STYLE}", // focusing is necessary to catch keyboard events @@ -62,7 +61,7 @@ fn app(cx: Scope) -> Element { onmousemove: move |event| log_event(Event::MouseMove(event)), onclick: move |event| log_event(Event::MouseClick(event)), - ondblclick: move |event| log_event(Event::MouseDoubleClick(event)), + ondoubleclick: move |event| log_event(Event::MouseDoubleClick(event)), onmousedown: move |event| log_event(Event::MouseDown(event)), onmouseup: move |event| log_event(Event::MouseUp(event)), @@ -77,9 +76,7 @@ fn app(cx: Scope) -> Element { "Hover, click, type or scroll to see the info down below" } - div { - events.read().iter().map(|event| rsx!( div { "{event:?}" } )) - }, - }, + div { events.read().iter().map(|event| rsx!( div { "{event:?}" } )) } + } )) } diff --git a/examples/todomvc.rs b/examples/todomvc.rs index 9ec2dc228..0f3fada71 100644 --- a/examples/todomvc.rs +++ b/examples/todomvc.rs @@ -48,11 +48,8 @@ pub fn app(cx: Scope<()>) -> Element { cx.render(rsx! { section { class: "todoapp", style { include_str!("./assets/todomvc.css") } - TodoHeader { - todos: todos, - } - section { - class: "main", + TodoHeader { todos: todos } + section { class: "main", if !todos.is_empty() { rsx! { input { @@ -103,31 +100,34 @@ pub fn TodoHeader<'a>(cx: Scope<'a, TodoHeaderProps<'a>>) -> Element { cx.render(rsx! { header { class: "header", - h1 {"todos"} - input { - class: "new-todo", - placeholder: "What needs to be done?", - value: "{draft}", - autofocus: "true", - oninput: move |evt| { - draft.set(evt.value.clone()); - }, - onkeydown: move |evt| { - if evt.key() == Key::Enter && !draft.is_empty() { - cx.props.todos.make_mut().insert( - **todo_id, - TodoItem { - id: **todo_id, - checked: false, - contents: draft.to_string(), - }, - ); - *todo_id.make_mut() += 1; - draft.set("".to_string()); + h1 { "todos" } + input { + class: "new-todo", + placeholder: "What needs to be done?", + value: "{draft}", + autofocus: "true", + oninput: move |evt| { + draft.set(evt.value.clone()); + }, + onkeydown: move |evt| { + if evt.key() == Key::Enter && !draft.is_empty() { + cx.props + .todos + .make_mut() + .insert( + **todo_id, + TodoItem { + id: **todo_id, + checked: false, + contents: draft.to_string(), + }, + ); + *todo_id.make_mut() += 1; + draft.set("".to_string()); + } } } } - } }) } @@ -146,8 +146,7 @@ pub fn TodoEntry<'a>(cx: Scope<'a, TodoEntryProps<'a>>) -> Element { let editing = if **is_editing { "editing" } else { "" }; cx.render(rsx!{ - li { - class: "{completed} {editing}", + li { class: "{completed} {editing}", div { class: "view", input { class: "toggle", @@ -160,14 +159,16 @@ pub fn TodoEntry<'a>(cx: Scope<'a, TodoEntryProps<'a>>) -> Element { } label { r#for: "cbg-{todo.id}", - ondblclick: move |_| is_editing.set(true), + ondoubleclick: move |_| is_editing.set(true), prevent_default: "onclick", "{todo.contents}" } button { class: "destroy", - onclick: move |_| { cx.props.todos.make_mut().remove(&todo.id); }, - prevent_default: "onclick", + onclick: move |_| { + cx.props.todos.make_mut().remove(&todo.id); + }, + prevent_default: "onclick" } } is_editing.then(|| rsx!{ @@ -213,15 +214,15 @@ pub fn ListFooter<'a>(cx: Scope<'a, ListFooterProps<'a>>) -> Element { cx.render(rsx! { footer { class: "footer", span { class: "todo-count", - strong {"{active_todo_count} "} - span {"{active_todo_text} left"} + strong { "{active_todo_count} " } + span { "{active_todo_text} left" } } ul { class: "filters", - for (state, state_text, url) in [ - (FilterState::All, "All", "#/"), - (FilterState::Active, "Active", "#/active"), - (FilterState::Completed, "Completed", "#/completed"), - ] { + for (state , state_text , url) in [ + (FilterState::All, "All", "#/"), + (FilterState::Active, "Active", "#/active"), + (FilterState::Completed, "Completed", "#/completed"), +] { li { a { href: url, @@ -250,8 +251,14 @@ pub fn PageFooter(cx: Scope) -> Element { cx.render(rsx! { footer { class: "info", p { "Double-click to edit a todo" } - p { "Created by ", a { href: "http://github.com/jkelleyrtp/", "jkelleyrtp" }} - p { "Part of ", a { href: "http://todomvc.com", "TodoMVC" }} + p { + "Created by " + a { href: "http://github.com/jkelleyrtp/", "jkelleyrtp" } + } + p { + "Part of " + a { href: "http://todomvc.com", "TodoMVC" } + } } }) } diff --git a/packages/desktop/headless_tests/events.rs b/packages/desktop/headless_tests/events.rs index ac62cd37b..6d29b6ffa 100644 --- a/packages/desktop/headless_tests/events.rs +++ b/packages/desktop/headless_tests/events.rs @@ -229,75 +229,111 @@ 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)); + assert_eq!( + event.data.trigger_button(), + Some(dioxus_html::input_data::MouseButton::Primary), + ); recieved_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)); + assert!( + event + .data + .held_buttons() + .contains(dioxus_html::input_data::MouseButton::Secondary), + ); recieved_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)); + 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{ + 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), + ); + recieved_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)); + 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{ + 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)); + assert_eq!( + event.data.trigger_button(), + Some(dioxus_html::input_data::MouseButton::Primary), + ); recieved_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) } } - input{ + input { id: "key_down_div", onkeydown: move |event| { println!("{:?}", event.data); @@ -306,11 +342,10 @@ fn app(cx: Scope) -> Element { assert_eq!(event.data.code().to_string(), "KeyA"); assert_eq!(event.data.location, 0); assert!(event.data.is_auto_repeating()); - recieved_events.modify(|x| *x + 1) } } - input{ + input { id: "key_up_div", onkeyup: move |event| { println!("{:?}", event.data); @@ -319,11 +354,10 @@ fn app(cx: Scope) -> Element { assert_eq!(event.data.code().to_string(), "KeyA"); assert_eq!(event.data.location, 0); assert!(!event.data.is_auto_repeating()); - recieved_events.modify(|x| *x + 1) } } - input{ + input { id: "key_press_div", onkeypress: move |event| { println!("{:?}", event.data); @@ -332,18 +366,17 @@ fn app(cx: Scope) -> Element { assert_eq!(event.data.code().to_string(), "KeyA"); assert_eq!(event.data.location, 0); assert!(!event.data.is_auto_repeating()); - recieved_events.modify(|x| *x + 1) } } - input{ + input { id: "focus_in_div", onfocusin: move |event| { println!("{:?}", event.data); recieved_events.modify(|x| *x + 1) } } - input{ + input { id: "focus_out_div", onfocusout: move |event| { println!("{:?}", event.data); diff --git a/packages/dioxus-tui/examples/all_terminal_events.rs b/packages/dioxus-tui/examples/all_terminal_events.rs index 483e9afdf..004578807 100644 --- a/packages/dioxus-tui/examples/all_terminal_events.rs +++ b/packages/dioxus-tui/examples/all_terminal_events.rs @@ -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 } + } }) } diff --git a/packages/fullstack/src/hooks/server_cached.rs b/packages/fullstack/src/hooks/server_cached.rs index 519f70dae..572efd2b7 100644 --- a/packages/fullstack/src/hooks/server_cached.rs +++ b/packages/fullstack/src/hooks/server_cached.rs @@ -12,9 +12,11 @@ use serde::{de::DeserializeOwned, Serialize}; /// use dioxus_fullstack::prelude::*; /// /// fn app(cx: Scope) -> Element { -/// let state1 = use_state(cx, || from_server(|| { +/// let state1 = use_state(cx, || server_cached(|| { /// 1234 /// })); +/// +/// todo!() /// } /// ``` pub fn server_cached(server_fn: impl Fn() -> O) -> O { diff --git a/packages/html/src/events/mouse.rs b/packages/html/src/events/mouse.rs index 55d081900..ea5bf29d3 100644 --- a/packages/html/src/events/mouse.rs +++ b/packages/html/src/events/mouse.rs @@ -119,10 +119,7 @@ impl_event! { /// oncontextmenu oncontextmenu - /// ondoubleclick - ondoubleclick - - /// ondoubleclick + #[deprecated(since = "0.5.0", note = "use ondoubleclick instead")] ondblclick /// onmousedown @@ -149,6 +146,19 @@ impl_event! { onmouseup } +/// ondoubleclick +#[inline] +pub fn ondoubleclick<'a, E: crate::EventReturn, T>(_cx: &'a ::dioxus_core::ScopeState, mut _f: impl FnMut(::dioxus_core::Event) -> E + 'a) -> ::dioxus_core::Attribute<'a> { + ::dioxus_core::Attribute::new( + "ondblclick", + _cx.listener(move |e: ::dioxus_core::Event| { + _f(e).spawn(_cx); + }), + None, + false, + ) +} + impl MouseData { /// Construct MouseData with the specified properties /// diff --git a/packages/web/src/cache.rs b/packages/web/src/cache.rs index e17203a65..bfd0fd197 100644 --- a/packages/web/src/cache.rs +++ b/packages/web/src/cache.rs @@ -190,7 +190,7 @@ pub static BUILTIN_INTERNED_STRINGS: &[&str] = &[ "oncopy", "oncuechange", "oncut", - "ondblclick", + "ondoubleclick", "ondrag", "ondragend", "ondragenter", From 43d9fe1ab0c626611d787f1d3052738e810db215 Mon Sep 17 00:00:00 2001 From: ealmloff Date: Wed, 3 Jan 2024 14:02:21 -0600 Subject: [PATCH 76/83] Clear the cache on rebuild in the incremental renderer (#1741) --- packages/ssr/src/incremental_cfg.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/packages/ssr/src/incremental_cfg.rs b/packages/ssr/src/incremental_cfg.rs index 1a4ea3418..15a6ad44e 100644 --- a/packages/ssr/src/incremental_cfg.rs +++ b/packages/ssr/src/incremental_cfg.rs @@ -67,6 +67,7 @@ pub struct IncrementalRendererConfig { memory_cache_limit: usize, invalidate_after: Option, map_path: Option, + clear_cache: bool, } impl Default for IncrementalRendererConfig { @@ -83,9 +84,16 @@ impl IncrementalRendererConfig { memory_cache_limit: 10000, invalidate_after: None, map_path: None, + clear_cache: true, } } + /// Clear the cache on startup (default: true) + pub fn clear_cache(mut self, clear_cache: bool) -> Self { + self.clear_cache = clear_cache; + self + } + /// Set a mapping from the route to the file path. This will override the default mapping configured with `static_dir`. /// The function should return the path to the folder to store the index.html file in. pub fn map_path PathBuf + Send + Sync + 'static>(mut self, map_path: F) -> Self { @@ -114,7 +122,7 @@ impl IncrementalRendererConfig { /// Build the incremental renderer. pub fn build(self) -> IncrementalRenderer { let static_dir = self.static_dir.clone(); - IncrementalRenderer { + let mut renderer = IncrementalRenderer { static_dir: self.static_dir.clone(), memory_cache: NonZeroUsize::new(self.memory_cache_limit) .map(|limit| lru::LruCache::with_hasher(limit, Default::default())), @@ -129,6 +137,12 @@ impl IncrementalRendererConfig { path }) }), + }; + + if self.clear_cache { + renderer.invalidate_all(); } + + renderer } } From 2e424436b362d2c72165d6b51a1683fe7d3e7e66 Mon Sep 17 00:00:00 2001 From: ealmloff Date: Wed, 3 Jan 2024 14:02:36 -0600 Subject: [PATCH 77/83] don't remove futures spawned by spawn_forever when the component is removed (#1708) --- packages/core/src/scope_context.rs | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/packages/core/src/scope_context.rs b/packages/core/src/scope_context.rs index 59bed3b1f..eeede6a81 100644 --- a/packages/core/src/scope_context.rs +++ b/packages/core/src/scope_context.rs @@ -230,17 +230,7 @@ impl ScopeContext { /// This is good for tasks that need to be run after the component has been dropped. pub fn spawn_forever(&self, fut: impl Future + '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. From afb258b658f55a1568b8d7c97b617b34f75c1aea Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Wed, 3 Jan 2024 15:18:27 -0600 Subject: [PATCH 78/83] Fix elements and attributes mapping for dx translate --- packages/html/Cargo.toml | 1 + packages/html/src/elements.rs | 48 +++++++++++++++++++-- packages/html/src/global_attributes.rs | 46 ++++++++++++++++++++ packages/html/src/lib.rs | 2 + packages/rsx-rosetta/Cargo.toml | 1 + packages/rsx-rosetta/src/lib.rs | 42 +++++++++++++----- packages/rsx-rosetta/tests/h-tags.rs | 33 ++++++++++++++ packages/rsx-rosetta/tests/raw.rs | 21 +++++++++ packages/rsx-rosetta/tests/simple.rs | 4 -- packages/rsx-rosetta/tests/web-component.rs | 21 +++++++++ 10 files changed, 202 insertions(+), 17 deletions(-) create mode 100644 packages/rsx-rosetta/tests/h-tags.rs create mode 100644 packages/rsx-rosetta/tests/raw.rs create mode 100644 packages/rsx-rosetta/tests/web-component.rs diff --git a/packages/html/Cargo.toml b/packages/html/Cargo.toml index 5644b440c..d12f7cf52 100644 --- a/packages/html/Cargo.toml +++ b/packages/html/Cargo.toml @@ -68,3 +68,4 @@ mounted = [ wasm-bind = ["web-sys", "wasm-bindgen"] native-bind = ["tokio"] hot-reload-context = ["dioxus-rsx"] +html-to-rsx = [] diff --git a/packages/html/src/elements.rs b/packages/html/src/elements.rs index a42c01950..03231c0e9 100644 --- a/packages/html/src/elements.rs +++ b/packages/html/src/elements.rs @@ -79,6 +79,25 @@ macro_rules! impl_attribute_match { }; } +#[cfg(feature = "html-to-rsx")] +macro_rules! impl_html_to_rsx_attribute_match { + ( + $attr:ident $fil:ident $name:literal + ) => { + if $attr == $name { + return Some(stringify!($fil)); + } + }; + + ( + $attr:ident $fil:ident $_:tt + ) => { + if $attr == stringify!($fil) { + return Some(stringify!($fil)); + } + }; +} + macro_rules! impl_element { ( $(#[$attr:meta])* @@ -316,6 +335,30 @@ macro_rules! builder_constructors { } } + #[cfg(feature = "html-to-rsx")] + pub fn map_html_attribute_to_rsx(html: &str) -> Option<&'static str> { + $( + $( + impl_html_to_rsx_attribute_match!( + html $fil $extra + ); + )* + )* + + None + } + + #[cfg(feature = "html-to-rsx")] + pub fn map_html_element_to_rsx(html: &str) -> Option<&'static str> { + $( + if html == stringify!($name) { + return Some(stringify!($name)); + } + )* + + None + } + $( impl_element!( $(#[$attr])* @@ -998,9 +1041,8 @@ builder_constructors! { src: Uri DEFAULT, text: String DEFAULT, - // r#async: Bool, - // r#type: String, // TODO could be an enum - r#type: String "type", + r#async: Bool "async", + r#type: String "type", // TODO could be an enum r#script: String "script", }; diff --git a/packages/html/src/global_attributes.rs b/packages/html/src/global_attributes.rs index 02b0b32ed..639026b33 100644 --- a/packages/html/src/global_attributes.rs +++ b/packages/html/src/global_attributes.rs @@ -33,12 +33,44 @@ macro_rules! trait_method_mapping { }; } +#[cfg(feature = "html-to-rsx")] +macro_rules! html_to_rsx_attribute_mapping { + ( + $matching:ident; + $(#[$attr:meta])* + $name:ident; + ) => { + if $matching == stringify!($name) { + return Some(stringify!($name)); + } + }; + ( + $matching:ident; + $(#[$attr:meta])* + $name:ident: $lit:literal; + ) => { + if $matching == stringify!($lit) { + return Some(stringify!($name)); + } + }; + ( + $matching:ident; + $(#[$attr:meta])* + $name:ident: $lit:literal, $ns:literal; + ) => { + if $matching == stringify!($lit) { + return Some(stringify!($name)); + } + }; +} + macro_rules! trait_methods { ( @base $(#[$trait_attr:meta])* $trait:ident; $fn:ident; + $fn_html_to_rsx:ident; $( $(#[$attr:meta])* $name:ident $(: $($arg:literal),*)*; @@ -62,6 +94,18 @@ macro_rules! trait_methods { )* None } + + #[cfg(feature = "html-to-rsx")] + #[doc = "Converts an HTML attribute to an RSX attribute"] + pub(crate) fn $fn_html_to_rsx(html: &str) -> Option<&'static str> { + $( + html_to_rsx_attribute_mapping! { + html; + $name$(: $($arg),*)*; + } + )* + None + } }; // Rename the incoming ident and apply a custom namespace @@ -79,6 +123,7 @@ trait_methods! { GlobalAttributes; map_global_attributes; + map_html_global_attributes_to_rsx; /// Prevent the default action for this element. /// @@ -1593,6 +1638,7 @@ trait_methods! { @base SvgAttributes; map_svg_attributes; + map_html_svg_attributes_to_rsx; /// Prevent the default action for this element. /// diff --git a/packages/html/src/lib.rs b/packages/html/src/lib.rs index 6dd7c42bd..c44777801 100644 --- a/packages/html/src/lib.rs +++ b/packages/html/src/lib.rs @@ -19,6 +19,8 @@ mod elements; #[cfg(feature = "hot-reload-context")] pub use elements::HtmlCtx; +#[cfg(feature = "html-to-rsx")] +pub use elements::{map_html_attribute_to_rsx, map_html_element_to_rsx}; pub mod events; pub mod geometry; mod global_attributes; diff --git a/packages/rsx-rosetta/Cargo.toml b/packages/rsx-rosetta/Cargo.toml index ab5d4e882..9cd53b02f 100644 --- a/packages/rsx-rosetta/Cargo.toml +++ b/packages/rsx-rosetta/Cargo.toml @@ -15,6 +15,7 @@ keywords = ["dom", "ui", "gui", "react"] [dependencies] dioxus-autofmt = { workspace = true } dioxus-rsx = { workspace = true } +dioxus-html = { workspace = true, features = ["html-to-rsx"]} html_parser.workspace = true proc-macro2 = "1.0.49" quote = "1.0.23" diff --git a/packages/rsx-rosetta/src/lib.rs b/packages/rsx-rosetta/src/lib.rs index 3c11f3a90..e12c6f021 100644 --- a/packages/rsx-rosetta/src/lib.rs +++ b/packages/rsx-rosetta/src/lib.rs @@ -2,6 +2,7 @@ #![doc(html_logo_url = "https://avatars.githubusercontent.com/u/79236386")] #![doc(html_favicon_url = "https://avatars.githubusercontent.com/u/79236386")] +use dioxus_html::{map_html_element_to_rsx, map_html_attribute_to_rsx}; use convert_case::{Case, Casing}; use dioxus_rsx::{ BodyNode, CallBody, Component, Element, ElementAttr, ElementAttrNamed, ElementName, IfmtInput, @@ -24,26 +25,47 @@ pub fn rsx_node_from_html(node: &Node) -> Option { match node { Node::Text(text) => Some(BodyNode::Text(ifmt_from_text(text))), Node::Element(el) => { - let el_name = el.name.to_case(Case::Snake); - let el_name = ElementName::Ident(Ident::new(el_name.as_str(), Span::call_site())); + let el_name = if let Some(name) = map_html_element_to_rsx(&el.name) { + ElementName::Ident(Ident::new(name, Span::call_site())) + } else { + // if we don't recognize it and it has a dash, we assume it's a web component + if el.name.contains('-') { + ElementName::Custom(LitStr::new(&el.name, Span::call_site())) + } else { + // otherwise, it might be an element that isn't supported yet + ElementName::Ident(Ident::new( + &el.name.to_case(Case::Snake), + Span::call_site(), + )) + } + }; let mut attributes: Vec<_> = el .attributes .iter() .map(|(name, value)| { - let ident = if matches!(name.as_str(), "for" | "async" | "type" | "as") { - Ident::new_raw(name.as_str(), Span::call_site()) + let value = ifmt_from_text(value.as_deref().unwrap_or("false")); + let attr = if let Some(name) = map_html_attribute_to_rsx(name) { + let ident = if let Some(name) = name.strip_prefix("r#") { + Ident::new_raw(name, Span::call_site()) + } else { + Ident::new(name, Span::call_site()) + }; + ElementAttr::AttrText { + value, + name: ident, + } } else { - let new_name = name.to_case(Case::Snake); - Ident::new(new_name.as_str(), Span::call_site()) + // If we don't recognize the attribute, we assume it's a custom attribute + ElementAttr::CustomAttrText { + value, + name: LitStr::new(name, Span::call_site()), + } }; ElementAttrNamed { el_name: el_name.clone(), - attr: ElementAttr::AttrText { - value: ifmt_from_text(value.as_deref().unwrap_or("false")), - name: ident, - }, + attr } }) .collect(); diff --git a/packages/rsx-rosetta/tests/h-tags.rs b/packages/rsx-rosetta/tests/h-tags.rs new file mode 100644 index 000000000..eb179c57f --- /dev/null +++ b/packages/rsx-rosetta/tests/h-tags.rs @@ -0,0 +1,33 @@ +use html_parser::Dom; + +#[test] +fn h_tags_translate() { + let html = r#" +
+

hello world!

+

hello world!

+

hello world!

+

hello world!

+
hello world!
+
hello world!
+
+ "# + .trim(); + + let dom = Dom::parse(html).unwrap(); + + let body = rsx_rosetta::rsx_from_html(&dom); + + let out = dioxus_autofmt::write_block_out(body).unwrap(); + + let expected = r#" + div { + h1 { "hello world!" } + h2 { "hello world!" } + h3 { "hello world!" } + h4 { "hello world!" } + h5 { "hello world!" } + h6 { "hello world!" } + }"#; + pretty_assertions::assert_eq!(&out, &expected); +} diff --git a/packages/rsx-rosetta/tests/raw.rs b/packages/rsx-rosetta/tests/raw.rs new file mode 100644 index 000000000..a3ed1eef8 --- /dev/null +++ b/packages/rsx-rosetta/tests/raw.rs @@ -0,0 +1,21 @@ +use html_parser::Dom; + +#[test] +fn raw_attribute() { + let html = r#" +
+
hello world!
+
+ "# + .trim(); + + let dom = Dom::parse(html).unwrap(); + + let body = rsx_rosetta::rsx_from_html(&dom); + + let out = dioxus_autofmt::write_block_out(body).unwrap(); + + let expected = r#" + div { div { "unrecognizedattribute": "asd", "hello world!" } }"#; + pretty_assertions::assert_eq!(&out, &expected); +} diff --git a/packages/rsx-rosetta/tests/simple.rs b/packages/rsx-rosetta/tests/simple.rs index b8fd095e1..3f3f8230a 100644 --- a/packages/rsx-rosetta/tests/simple.rs +++ b/packages/rsx-rosetta/tests/simple.rs @@ -9,8 +9,6 @@ fn simple_elements() {
hello world!
hello world!
hello world!
-
hello world!
- hello world! "# .trim(); @@ -28,8 +26,6 @@ fn simple_elements() { div { id: "asd", "hello world!" } div { r#for: "asd", "hello world!" } div { r#async: "asd", "hello world!" } - div { large_thing: "asd", "hello world!" } - ai_is_awesome { "hello world!" } }"#; pretty_assertions::assert_eq!(&out, &expected); } diff --git a/packages/rsx-rosetta/tests/web-component.rs b/packages/rsx-rosetta/tests/web-component.rs new file mode 100644 index 000000000..c7309e1b7 --- /dev/null +++ b/packages/rsx-rosetta/tests/web-component.rs @@ -0,0 +1,21 @@ +use html_parser::Dom; + +#[test] +fn web_components_translate() { + let html = r#" +
+ +
+ "# + .trim(); + + let dom = Dom::parse(html).unwrap(); + + let body = rsx_rosetta::rsx_from_html(&dom); + + let out = dioxus_autofmt::write_block_out(body).unwrap(); + + let expected = r#" + div { my-component {} }"#; + pretty_assertions::assert_eq!(&out, &expected); +} From bc557906fe798e0bd1403fb609d7a5e6eb5b62be Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Wed, 3 Jan 2024 15:18:37 -0600 Subject: [PATCH 79/83] fix formatting --- packages/fullstack/src/hooks/server_cached.rs | 2 +- packages/html/src/events/mouse.rs | 5 ++++- packages/rsx-rosetta/src/lib.rs | 14 ++++---------- 3 files changed, 9 insertions(+), 12 deletions(-) diff --git a/packages/fullstack/src/hooks/server_cached.rs b/packages/fullstack/src/hooks/server_cached.rs index 572efd2b7..b3f9113b5 100644 --- a/packages/fullstack/src/hooks/server_cached.rs +++ b/packages/fullstack/src/hooks/server_cached.rs @@ -15,7 +15,7 @@ use serde::{de::DeserializeOwned, Serialize}; /// let state1 = use_state(cx, || server_cached(|| { /// 1234 /// })); -/// +/// /// todo!() /// } /// ``` diff --git a/packages/html/src/events/mouse.rs b/packages/html/src/events/mouse.rs index ea5bf29d3..17128f4e4 100644 --- a/packages/html/src/events/mouse.rs +++ b/packages/html/src/events/mouse.rs @@ -148,7 +148,10 @@ impl_event! { /// ondoubleclick #[inline] -pub fn ondoubleclick<'a, E: crate::EventReturn, T>(_cx: &'a ::dioxus_core::ScopeState, mut _f: impl FnMut(::dioxus_core::Event) -> E + 'a) -> ::dioxus_core::Attribute<'a> { +pub fn ondoubleclick<'a, E: crate::EventReturn, T>( + _cx: &'a ::dioxus_core::ScopeState, + mut _f: impl FnMut(::dioxus_core::Event) -> E + 'a, +) -> ::dioxus_core::Attribute<'a> { ::dioxus_core::Attribute::new( "ondblclick", _cx.listener(move |e: ::dioxus_core::Event| { diff --git a/packages/rsx-rosetta/src/lib.rs b/packages/rsx-rosetta/src/lib.rs index e12c6f021..49b6b6fc7 100644 --- a/packages/rsx-rosetta/src/lib.rs +++ b/packages/rsx-rosetta/src/lib.rs @@ -2,8 +2,8 @@ #![doc(html_logo_url = "https://avatars.githubusercontent.com/u/79236386")] #![doc(html_favicon_url = "https://avatars.githubusercontent.com/u/79236386")] -use dioxus_html::{map_html_element_to_rsx, map_html_attribute_to_rsx}; use convert_case::{Case, Casing}; +use dioxus_html::{map_html_attribute_to_rsx, map_html_element_to_rsx}; use dioxus_rsx::{ BodyNode, CallBody, Component, Element, ElementAttr, ElementAttrNamed, ElementName, IfmtInput, }; @@ -33,10 +33,7 @@ pub fn rsx_node_from_html(node: &Node) -> Option { ElementName::Custom(LitStr::new(&el.name, Span::call_site())) } else { // otherwise, it might be an element that isn't supported yet - ElementName::Ident(Ident::new( - &el.name.to_case(Case::Snake), - Span::call_site(), - )) + ElementName::Ident(Ident::new(&el.name.to_case(Case::Snake), Span::call_site())) } }; @@ -51,10 +48,7 @@ pub fn rsx_node_from_html(node: &Node) -> Option { } else { Ident::new(name, Span::call_site()) }; - ElementAttr::AttrText { - value, - name: ident, - } + ElementAttr::AttrText { value, name: ident } } else { // If we don't recognize the attribute, we assume it's a custom attribute ElementAttr::CustomAttrText { @@ -65,7 +59,7 @@ pub fn rsx_node_from_html(node: &Node) -> Option { ElementAttrNamed { el_name: el_name.clone(), - attr + attr, } }) .collect(); From 422df68fea099edbf93f3e345dac05552c549801 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Wed, 3 Jan 2024 15:35:24 -0600 Subject: [PATCH 80/83] fix formatting --- packages/fullstack/src/hooks/server_cached.rs | 2 +- packages/html/src/events/mouse.rs | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/packages/fullstack/src/hooks/server_cached.rs b/packages/fullstack/src/hooks/server_cached.rs index 572efd2b7..b3f9113b5 100644 --- a/packages/fullstack/src/hooks/server_cached.rs +++ b/packages/fullstack/src/hooks/server_cached.rs @@ -15,7 +15,7 @@ use serde::{de::DeserializeOwned, Serialize}; /// let state1 = use_state(cx, || server_cached(|| { /// 1234 /// })); -/// +/// /// todo!() /// } /// ``` diff --git a/packages/html/src/events/mouse.rs b/packages/html/src/events/mouse.rs index ea5bf29d3..17128f4e4 100644 --- a/packages/html/src/events/mouse.rs +++ b/packages/html/src/events/mouse.rs @@ -148,7 +148,10 @@ impl_event! { /// ondoubleclick #[inline] -pub fn ondoubleclick<'a, E: crate::EventReturn, T>(_cx: &'a ::dioxus_core::ScopeState, mut _f: impl FnMut(::dioxus_core::Event) -> E + 'a) -> ::dioxus_core::Attribute<'a> { +pub fn ondoubleclick<'a, E: crate::EventReturn, T>( + _cx: &'a ::dioxus_core::ScopeState, + mut _f: impl FnMut(::dioxus_core::Event) -> E + 'a, +) -> ::dioxus_core::Attribute<'a> { ::dioxus_core::Attribute::new( "ondblclick", _cx.listener(move |e: ::dioxus_core::Event| { From 682beeccfd87ba1f6e06fd2d5b17bfcff9797253 Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Wed, 3 Jan 2024 15:45:19 -0600 Subject: [PATCH 81/83] fallback to global attributes when mapping rsx rosetta html attribute names --- packages/html/src/elements.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/packages/html/src/elements.rs b/packages/html/src/elements.rs index 03231c0e9..ca3f4aee7 100644 --- a/packages/html/src/elements.rs +++ b/packages/html/src/elements.rs @@ -345,6 +345,14 @@ macro_rules! builder_constructors { )* )* + if let Some(name) = crate::map_html_global_attributes_to_rsx(html) { + return Some(name); + } + + if let Some(name) = crate::map_html_svg_attributes_to_rsx(html) { + return Some(name); + } + None } From c56d3662e973f60b05ba06e29a38cfe1b34b1ff5 Mon Sep 17 00:00:00 2001 From: ealmloff Date: Thu, 4 Jan 2024 09:06:38 -0600 Subject: [PATCH 82/83] document the type name as optional in the server function docs (#1748) --- packages/server-macro/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/server-macro/src/lib.rs b/packages/server-macro/src/lib.rs index 5ad9a682b..871de33bc 100644 --- a/packages/server-macro/src/lib.rs +++ b/packages/server-macro/src/lib.rs @@ -19,7 +19,7 @@ use syn::{ /// are enabled), it will instead make a network request to the server. /// /// You can specify one, two, or three arguments to the server function: -/// 1. **Required**: A type name that will be used to identify and register the server function +/// 1. *Optional*: A type name that will be used to identify and register the server function /// (e.g., `MyServerFn`). /// 2. *Optional*: A URL prefix at which the function will be mounted when it’s registered /// (e.g., `"/api"`). Defaults to `"/"`. From f913b2ce53483b9c352d0ba633e665d7017eb10b Mon Sep 17 00:00:00 2001 From: ealmloff Date: Thu, 4 Jan 2024 09:06:57 -0600 Subject: [PATCH 83/83] don't cache assets in the CLI (#1742) --- packages/cli/src/server/web/mod.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/cli/src/server/web/mod.rs b/packages/cli/src/server/web/mod.rs index 0e1413597..98ff1e078 100644 --- a/packages/cli/src/server/web/mod.rs +++ b/packages/cli/src/server/web/mod.rs @@ -11,6 +11,7 @@ use axum::{ body::{Full, HttpBody}, extract::{ws::Message, Extension, TypedHeader, WebSocketUpgrade}, http::{ + self, header::{HeaderName, HeaderValue}, Method, Response, StatusCode, }, @@ -262,7 +263,7 @@ async fn setup_router( .override_response_header(HeaderName::from_static("cross-origin-opener-policy"), coop) .and_then( move |response: Response| async move { - let response = if file_service_config + let mut response = if file_service_config .dioxus_config .web .watcher @@ -290,6 +291,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) }, )