Remove cx in more places

This commit is contained in:
Jonathan Kelley committed 2024-01-13 21:18:36 -08:00
1 parent 1dde044697
commit 9881a94e67
10 files changed
+122 -127

No files matched your search

+1 -1
View File
@@ -74,7 +74,7 @@ pub(crate) mod innerlude {
pub use crate::innerlude::{ pub use crate::innerlude::{
fc_to_builder, generation, once, schedule_update, schedule_update_any, vdom_is_rendering, fc_to_builder, generation, once, schedule_update, schedule_update_any, vdom_is_rendering,
AnyValue, Attribute, AttributeValue, CapturedError, Component, DynamicNode, Element, ElementId, AnyValue, Attribute, AttributeValue, CapturedError, Component, DynamicNode, Element, ElementId,
Event, Fragment, IntoDynNode, Mutation, MutationsVec, NoOpMutations, Properties, RenderReturn, Event, Fragment, IntoDynNode, Mutation, Mutations, NoOpMutations, Properties, RenderReturn,
ScopeId, Task, Template, TemplateAttribute, TemplateNode, VComponent, VNode, VNodeInner, ScopeId, Task, Template, TemplateAttribute, TemplateNode, VComponent, VNode, VNodeInner,
VPlaceholder, VText, VirtualDom, WriteMutations, VPlaceholder, VText, VirtualDom, WriteMutations,
}; };
+3 -3
View File
@@ -327,7 +327,7 @@ pub enum Mutation {
/// A static list of mutations that can be applied to the DOM. Note: this list does not contain any `Any` attribute values /// A static list of mutations that can be applied to the DOM. Note: this list does not contain any `Any` attribute values
#[derive(Debug, PartialEq, Default)] #[derive(Debug, PartialEq, Default)]
pub struct MutationsVec { pub struct Mutations {
/// The list of Scopes that were diffed, created, and removed during the Diff process. /// The list of Scopes that were diffed, created, and removed during the Diff process.
pub dirty_scopes: FxHashSet<ScopeId>, pub dirty_scopes: FxHashSet<ScopeId>,
@@ -340,7 +340,7 @@ pub struct MutationsVec {
pub edits: Vec<Mutation>, pub edits: Vec<Mutation>,
} }
impl MutationsVec { impl Mutations {
/// Rewrites IDs to just be "template", so you can compare the mutations /// Rewrites IDs to just be "template", so you can compare the mutations
/// ///
/// Used really only for testing /// Used really only for testing
@@ -355,7 +355,7 @@ impl MutationsVec {
} }
} }
impl WriteMutations for MutationsVec { impl WriteMutations for Mutations {
fn register_template(&mut self, template: Template) { fn register_template(&mut self, template: Template) {
self.templates.push(template) self.templates.push(template)
} }
+7 -7
View File
@@ -13,7 +13,7 @@ use crate::{
nodes::{Template, TemplateId}, nodes::{Template, TemplateId},
runtime::{Runtime, RuntimeGuard}, runtime::{Runtime, RuntimeGuard},
scopes::ScopeId, scopes::ScopeId,
AttributeValue, Element, Event, MutationsVec, AttributeValue, Element, Event, Mutations,
}; };
use futures_util::{pin_mut, StreamExt}; use futures_util::{pin_mut, StreamExt};
use rustc_hash::{FxHashMap, FxHashSet}; use rustc_hash::{FxHashMap, FxHashSet};
@@ -565,8 +565,8 @@ impl VirtualDom {
} }
/// [`VirtualDom::rebuild`] to a vector of mutations for testing purposes /// [`VirtualDom::rebuild`] to a vector of mutations for testing purposes
pub fn rebuild_to_vec(&mut self) -> MutationsVec { pub fn rebuild_to_vec(&mut self) -> Mutations {
let mut mutations = MutationsVec::default(); let mut mutations = Mutations::default();
self.rebuild(&mut mutations); self.rebuild(&mut mutations);
mutations mutations
} }
@@ -591,8 +591,8 @@ impl VirtualDom {
} }
/// [`Self::render_immediate`] to a vector of mutations for testing purposes /// [`Self::render_immediate`] to a vector of mutations for testing purposes
pub fn render_immediate_to_vec(&mut self) -> MutationsVec { pub fn render_immediate_to_vec(&mut self) -> Mutations {
let mut mutations = MutationsVec::default(); let mut mutations = Mutations::default();
self.render_immediate(&mut mutations); self.render_immediate(&mut mutations);
mutations mutations
} }
@@ -665,8 +665,8 @@ impl VirtualDom {
pub async fn render_with_deadline_to_vec( pub async fn render_with_deadline_to_vec(
&mut self, &mut self,
deadline: impl Future<Output = ()>, deadline: impl Future<Output = ()>,
) -> MutationsVec { ) -> Mutations {
let mut mutations = MutationsVec::default(); let mut mutations = Mutations::default();
self.render_with_deadline(deadline, &mut mutations).await; self.render_with_deadline(deadline, &mut mutations).await;
mutations mutations
} }
+1 -1
View File
@@ -140,7 +140,7 @@ impl EditQueue {
// max_template_count.fetch_add(1, Ordering::Relaxed); // max_template_count.fetch_add(1, Ordering::Relaxed);
// } // }
// pub fn create_template_node(channel: &mut Channel, node: &'static TemplateNode<'static>) { // pub fn create_template_node(channel: &mut Channel, node: &'static TemplateNode) {
// use TemplateNode::*; // use TemplateNode::*;
// match node { // match node {
// Element { // Element {
+96 -98
View File
@@ -23,89 +23,87 @@ use std::sync::Arc;
/// ///
/// - dependencies: a tuple of references to values that are PartialEq + Clone /// - dependencies: a tuple of references to values that are PartialEq + Clone
#[must_use = "Consider using `cx.spawn` to run a future without reading its value"] #[must_use = "Consider using `cx.spawn` to run a future without reading its value"]
pub fn use_server_future<T, F, D>( pub fn use_server_future<T, F>(future: impl FnOnce() -> F) -> Option<UseServerFuture<T>>
dependencies: D,
future: impl FnOnce(D::Out) -> F,
) -> Option<&UseServerFuture<T>>
where where
T: 'static + Serialize + DeserializeOwned + Debug, T: 'static + Serialize + DeserializeOwned + Debug,
F: Future<Output = T> + 'static, F: Future<Output = T> + 'static,
D: UseFutureDep,
{ {
let state = cx.use_hook(move || UseServerFuture { todo!()
update: cx.schedule_update(),
needs_regen: Cell::new(true),
value: Default::default(),
task: Cell::new(None),
dependencies: Vec::new(),
});
let first_run = { state.value.borrow().as_ref().is_none() && state.task.get().is_none() }; // let state = use_hook(move || UseServerFuture {
// update: schedule_update(),
// needs_regen: Cell::new(true),
// value: Default::default(),
// task: Cell::new(None),
// dependencies: Vec::new(),
// });
#[cfg(not(feature = "ssr"))] // let first_run = { state.value.borrow().as_ref().is_none() && state.task.get().is_none() };
{
if first_run {
match crate::html_storage::deserialize::take_server_data() {
Some(data) => {
tracing::trace!("Loaded {data:?} from server");
*state.value.borrow_mut() = Some(Box::new(data));
state.needs_regen.set(false);
return Some(state);
}
None => {
tracing::trace!("Failed to load from server... running future");
}
};
}
}
if dependencies.clone().apply(&mut state.dependencies) || state.needs_regen.get() { // #[cfg(not(feature = "ssr"))]
// We don't need regen anymore // {
state.needs_regen.set(false); // if first_run {
// match crate::html_storage::deserialize::take_server_data() {
// Some(data) => {
// tracing::trace!("Loaded {data:?} from server");
// *state.value.borrow_mut() = Some(Box::new(data));
// state.needs_regen.set(false);
// return Some(state);
// }
// None => {
// tracing::trace!("Failed to load from server... running future");
// }
// };
// }
// }
// Create the new future // if dependencies.clone().apply(&mut state.dependencies) || state.needs_regen.get() {
let fut = future(dependencies.out()); // // We don't need regen anymore
// state.needs_regen.set(false);
// Clone in our cells // // Create the new future
let value = state.value.clone(); // let fut = future(dependencies.out());
let schedule_update = state.update.clone();
// Cancel the current future // // Clone in our cells
if let Some(current) = state.task.take() { // let value = state.value.clone();
cx.remove_future(current); // let schedule_update = state.update.clone();
}
state.task.set(Some(cx.push_future(async move { // // Cancel the current future
let data; // if let Some(current) = state.task.take() {
#[cfg(feature = "ssr")] // cx.remove_future(current);
{ // }
data = fut.await;
if first_run {
if let Err(err) = crate::prelude::server_context().push_html_data(&data) {
tracing::error!("Failed to push HTML data: {}", err);
};
}
}
#[cfg(not(feature = "ssr"))]
{
data = fut.await;
}
*value.borrow_mut() = Some(Box::new(data));
schedule_update(); // state.task.set(Some(cx.push_future(async move {
}))); // let data;
} // #[cfg(feature = "ssr")]
// {
// data = fut.await;
// if first_run {
// if let Err(err) = crate::prelude::server_context().push_html_data(&data) {
// tracing::error!("Failed to push HTML data: {}", err);
// };
// }
// }
// #[cfg(not(feature = "ssr"))]
// {
// data = fut.await;
// }
// *value.borrow_mut() = Some(Box::new(data));
if first_run { // schedule_update();
#[cfg(feature = "ssr")] // })));
{ // }
tracing::trace!("Suspending first run of use_server_future");
cx.suspend(); // if first_run {
} // #[cfg(feature = "ssr")]
None // {
} else { // tracing::trace!("Suspending first run of use_server_future");
Some(state) // cx.suspend();
} // }
// None
// } else {
// Some(state)
// }
} }
pub struct UseServerFuture<T> { pub struct UseServerFuture<T> {
@@ -117,36 +115,36 @@ pub struct UseServerFuture<T> {
} }
impl<T> UseServerFuture<T> { impl<T> UseServerFuture<T> {
/// Restart the future with new dependencies. // /// Restart the future with new dependencies.
/// // ///
/// Will not cancel the previous future, but will ignore any values that it // /// Will not cancel the previous future, but will ignore any values that it
/// generates. // /// generates.
pub fn restart(&self) { // pub fn restart(&self) {
self.needs_regen.set(true); // self.needs_regen.set(true);
(self.update)(); // (self.update)();
} // }
/// Forcefully cancel a future // /// Forcefully cancel a future
pub fn cancel(&self) { // pub fn cancel(&self) {
if let Some(task) = self.task.take() { // if let Some(task) = self.task.take() {
cx.remove_future(task); // cx.remove_future(task);
} // }
} // }
/// Return any value, even old values if the future has not yet resolved. // /// Return any value, even old values if the future has not yet resolved.
/// // ///
/// If the future has never completed, the returned value will be `None`. // /// If the future has never completed, the returned value will be `None`.
pub fn value(&self) -> Ref<'_, T> { // pub fn value(&self) -> Ref<'_, T> {
Ref::map(self.value.borrow(), |v| v.as_deref().unwrap()) // Ref::map(self.value.borrow(), |v| v.as_deref().unwrap())
} // }
/// Get the ID of the future in Dioxus' internal scheduler // /// Get the ID of the future in Dioxus' internal scheduler
pub fn task(&self) -> Option<Task> { // pub fn task(&self) -> Option<Task> {
self.task.get() // self.task.get()
} // }
/// Get the current state of the future. // /// Get the current state of the future.
pub fn reloading(&self) -> bool { // pub fn reloading(&self) -> bool {
self.task.get().is_some() // self.task.get().is_some()
} // }
} }
+2 -2
View File
@@ -4,7 +4,7 @@ use dioxus::prelude::*;
/// Used by the launch macro /// Used by the launch macro
#[doc(hidden)] #[doc(hidden)]
pub fn RouteWithCfg<R>(cx: Scope<FullstackRouterConfig<R>>) -> Element pub fn RouteWithCfg<R>(props: FullstackRouterConfig<R>) -> Element
where where
R: dioxus_router::prelude::Routable, R: dioxus_router::prelude::Routable,
<R as std::str::FromStr>::Err: std::fmt::Display, <R as std::str::FromStr>::Err: std::fmt::Display,
@@ -14,7 +14,7 @@ where
#[cfg(feature = "ssr")] #[cfg(feature = "ssr")]
let context = crate::prelude::server_context(); let context = crate::prelude::server_context();
let cfg = *cx.props; let cfg = props;
render! { render! {
dioxus_router::prelude::Router::<R> { dioxus_router::prelude::Router::<R> {
config: move || { config: move || {
+3 -2
View File
@@ -1,6 +1,7 @@
#![allow(clippy::await_holding_refcell_ref)] #![allow(clippy::await_holding_refcell_ref)]
use async_trait::async_trait; use async_trait::async_trait;
use dioxus_core::prelude::{consume_context, provide_context};
use dioxus_html::prelude::{EvalError, EvalProvider, Evaluator}; use dioxus_html::prelude::{EvalError, EvalProvider, Evaluator};
use std::{cell::RefCell, rc::Rc}; use std::{cell::RefCell, rc::Rc};
@@ -8,9 +9,9 @@ use crate::query::{Query, QueryEngine};
/// Provides the DesktopEvalProvider through [`cx.provide_context`]. /// Provides the DesktopEvalProvider through [`cx.provide_context`].
pub fn init_eval() { pub fn init_eval() {
let query = cx.consume_context::<QueryEngine>().unwrap(); let query = consume_context::<QueryEngine>().unwrap();
let provider: Rc<dyn EvalProvider> = Rc::new(DesktopEvalProvider { query }); let provider: Rc<dyn EvalProvider> = Rc::new(DesktopEvalProvider { query });
cx.provide_context(provider); provide_context(provider);
} }
/// Reprents the desktop-target's provider of evaluators. /// Reprents the desktop-target's provider of evaluators.
+5 -5
View File
@@ -5,7 +5,7 @@ use crate::{
query::{QueryEngine, QueryResult}, query::{QueryEngine, QueryResult},
LiveViewError, LiveViewError,
}; };
use dioxus_core::{prelude::*, BorrowedAttributeValue, Mutations}; use dioxus_core::{prelude::*, Attribute, AttributeValue, Mutations};
use dioxus_html::{event_bubbles, EventData, HtmlEvent, MountedData, PlatformEventData}; use dioxus_html::{event_bubbles, EventData, HtmlEvent, MountedData, PlatformEventData};
use dioxus_interpreter_js::binary_protocol::Channel; use dioxus_interpreter_js::binary_protocol::Channel;
use futures_util::{pin_mut, SinkExt, StreamExt}; use futures_util::{pin_mut, SinkExt, StreamExt};
@@ -38,7 +38,7 @@ impl LiveViewPool {
pub async fn launch( pub async fn launch(
&self, &self,
ws: impl LiveViewSocket, ws: impl LiveViewSocket,
app: fn(Scope<()>) -> Element, app: fn(()) -> Element,
) -> Result<(), LiveViewError> { ) -> Result<(), LiveViewError> {
self.launch_with_props(ws, app, ()).await self.launch_with_props(ws, app, ()).await
} }
@@ -46,7 +46,7 @@ impl LiveViewPool {
pub async fn launch_with_props<T: Send + 'static>( pub async fn launch_with_props<T: Send + 'static>(
&self, &self,
ws: impl LiveViewSocket, ws: impl LiveViewSocket,
app: fn(Scope<T>) -> Element, app: fn(T) -> Element,
props: T, props: T,
) -> Result<(), LiveViewError> { ) -> Result<(), LiveViewError> {
self.launch_virtualdom(ws, move || VirtualDom::new_with_props(app, props)) self.launch_virtualdom(ws, move || VirtualDom::new_with_props(app, props))
@@ -133,7 +133,7 @@ pub async fn run(mut vdom: VirtualDom, ws: impl LiveViewSocket) -> Result<(), Li
let (query_tx, mut query_rx) = tokio::sync::mpsc::unbounded_channel(); let (query_tx, mut query_rx) = tokio::sync::mpsc::unbounded_channel();
let query_engine = QueryEngine::new(query_tx); let query_engine = QueryEngine::new(query_tx);
vdom.base_scope().provide_context(query_engine.clone()); vdom.base_scope().provide_context(query_engine.clone());
init_eval(vdom.base_scope()); init_eval();
// pin the futures so we can use select! // pin the futures so we can use select!
pin_mut!(ws); pin_mut!(ws);
@@ -271,7 +271,7 @@ fn add_template(
*max_template_count += 1 *max_template_count += 1
} }
fn create_template_node(channel: &mut Channel, v: &'static TemplateNode<'static>) { fn create_template_node(channel: &mut Channel, v: &'static TemplateNode) {
use TemplateNode::*; use TemplateNode::*;
match v { match v {
Element { Element {
+2 -2
View File
@@ -40,7 +40,7 @@ fn create_random_template_node(
template_idx: &mut usize, template_idx: &mut usize,
attr_idx: &mut usize, attr_idx: &mut usize,
depth: usize, depth: usize,
) -> TemplateNode<'static> { ) -> TemplateNode {
match rand::random::<u8>() % 4 { match rand::random::<u8>() % 4 {
0 => { 0 => {
let attrs = { let attrs = {
@@ -96,7 +96,7 @@ fn create_random_template_node(
} }
fn generate_paths( fn generate_paths(
node: &TemplateNode<'static>, node: &TemplateNode,
current_path: &[u8], current_path: &[u8],
node_paths: &mut Vec<Vec<u8>>, node_paths: &mut Vec<Vec<u8>>,
attr_paths: &mut Vec<Vec<u8>>, attr_paths: &mut Vec<Vec<u8>>,
+2 -6
View File
@@ -15,15 +15,11 @@ fn App() -> Element {
onclick: move |_| *signal.write() += 1, onclick: move |_| *signal.write() += 1,
"Increase" "Increase"
} }
Child { Child { signal: doubled }
signal: doubled
}
} }
} }
#[component] #[component]
fn Child(signal: ReadOnlySignal<usize>) -> Element { fn Child(signal: ReadOnlySignal<usize>) -> Element {
render! { render! { "{signal}" }
"{signal}"
}
} }