Remove cx in more places

This commit is contained in:
Jonathan Kelley 2024-01-13 21:18:36 -08:00
parent 1dde044697
commit 9881a94e67
No known key found for this signature in database
GPG key ID: 1FBB50F7EB0A08BE
10 changed files with 122 additions and 127 deletions

View file

@ -74,7 +74,7 @@ pub(crate) mod innerlude {
pub use crate::innerlude::{
fc_to_builder, generation, once, schedule_update, schedule_update_any, vdom_is_rendering,
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,
VPlaceholder, VText, VirtualDom, WriteMutations,
};

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
#[derive(Debug, PartialEq, Default)]
pub struct MutationsVec {
pub struct Mutations {
/// The list of Scopes that were diffed, created, and removed during the Diff process.
pub dirty_scopes: FxHashSet<ScopeId>,
@ -340,7 +340,7 @@ pub struct MutationsVec {
pub edits: Vec<Mutation>,
}
impl MutationsVec {
impl Mutations {
/// Rewrites IDs to just be "template", so you can compare the mutations
///
/// 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) {
self.templates.push(template)
}

View file

@ -13,7 +13,7 @@ use crate::{
nodes::{Template, TemplateId},
runtime::{Runtime, RuntimeGuard},
scopes::ScopeId,
AttributeValue, Element, Event, MutationsVec,
AttributeValue, Element, Event, Mutations,
};
use futures_util::{pin_mut, StreamExt};
use rustc_hash::{FxHashMap, FxHashSet};
@ -565,8 +565,8 @@ impl VirtualDom {
}
/// [`VirtualDom::rebuild`] to a vector of mutations for testing purposes
pub fn rebuild_to_vec(&mut self) -> MutationsVec {
let mut mutations = MutationsVec::default();
pub fn rebuild_to_vec(&mut self) -> Mutations {
let mut mutations = Mutations::default();
self.rebuild(&mut mutations);
mutations
}
@ -591,8 +591,8 @@ impl VirtualDom {
}
/// [`Self::render_immediate`] to a vector of mutations for testing purposes
pub fn render_immediate_to_vec(&mut self) -> MutationsVec {
let mut mutations = MutationsVec::default();
pub fn render_immediate_to_vec(&mut self) -> Mutations {
let mut mutations = Mutations::default();
self.render_immediate(&mut mutations);
mutations
}
@ -665,8 +665,8 @@ impl VirtualDom {
pub async fn render_with_deadline_to_vec(
&mut self,
deadline: impl Future<Output = ()>,
) -> MutationsVec {
let mut mutations = MutationsVec::default();
) -> Mutations {
let mut mutations = Mutations::default();
self.render_with_deadline(deadline, &mut mutations).await;
mutations
}

View file

@ -140,7 +140,7 @@ impl EditQueue {
// 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::*;
// match node {
// Element {

View file

@ -23,89 +23,87 @@ use std::sync::Arc;
///
/// - 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"]
pub fn use_server_future<T, F, D>(
dependencies: D,
future: impl FnOnce(D::Out) -> F,
) -> Option<&UseServerFuture<T>>
pub fn use_server_future<T, F>(future: impl FnOnce() -> F) -> Option<UseServerFuture<T>>
where
T: 'static + Serialize + DeserializeOwned + Debug,
F: Future<Output = T> + 'static,
D: UseFutureDep,
{
let state = cx.use_hook(move || UseServerFuture {
update: cx.schedule_update(),
needs_regen: Cell::new(true),
value: Default::default(),
task: Cell::new(None),
dependencies: Vec::new(),
});
todo!()
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"))]
{
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");
}
};
}
}
// let first_run = { state.value.borrow().as_ref().is_none() && state.task.get().is_none() };
if dependencies.clone().apply(&mut state.dependencies) || state.needs_regen.get() {
// We don't need regen anymore
state.needs_regen.set(false);
// #[cfg(not(feature = "ssr"))]
// {
// 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
let fut = future(dependencies.out());
// if dependencies.clone().apply(&mut state.dependencies) || state.needs_regen.get() {
// // We don't need regen anymore
// state.needs_regen.set(false);
// Clone in our cells
let value = state.value.clone();
let schedule_update = state.update.clone();
// // Create the new future
// let fut = future(dependencies.out());
// Cancel the current future
if let Some(current) = state.task.take() {
cx.remove_future(current);
}
// // Clone in our cells
// let value = state.value.clone();
// let schedule_update = state.update.clone();
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));
// // Cancel the current future
// if let Some(current) = state.task.take() {
// cx.remove_future(current);
// }
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 {
#[cfg(feature = "ssr")]
{
tracing::trace!("Suspending first run of use_server_future");
cx.suspend();
}
None
} else {
Some(state)
}
// schedule_update();
// })));
// }
// if first_run {
// #[cfg(feature = "ssr")]
// {
// tracing::trace!("Suspending first run of use_server_future");
// cx.suspend();
// }
// None
// } else {
// Some(state)
// }
}
pub struct UseServerFuture<T> {
@ -117,36 +115,36 @@ pub struct UseServerFuture<T> {
}
impl<T> UseServerFuture<T> {
/// Restart the future with new dependencies.
///
/// Will not cancel the previous future, but will ignore any values that it
/// generates.
pub fn restart(&self) {
self.needs_regen.set(true);
(self.update)();
}
// /// Restart the future with new dependencies.
// ///
// /// Will not cancel the previous future, but will ignore any values that it
// /// generates.
// pub fn restart(&self) {
// self.needs_regen.set(true);
// (self.update)();
// }
/// Forcefully cancel a future
pub fn cancel(&self) {
if let Some(task) = self.task.take() {
cx.remove_future(task);
}
}
// /// Forcefully cancel a future
// pub fn cancel(&self) {
// if let Some(task) = self.task.take() {
// cx.remove_future(task);
// }
// }
/// 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`.
pub fn value(&self) -> Ref<'_, T> {
Ref::map(self.value.borrow(), |v| v.as_deref().unwrap())
}
// /// 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`.
// pub fn value(&self) -> Ref<'_, T> {
// Ref::map(self.value.borrow(), |v| v.as_deref().unwrap())
// }
/// Get the ID of the future in Dioxus' internal scheduler
pub fn task(&self) -> Option<Task> {
self.task.get()
}
// /// Get the ID of the future in Dioxus' internal scheduler
// pub fn task(&self) -> Option<Task> {
// self.task.get()
// }
/// Get the current state of the future.
pub fn reloading(&self) -> bool {
self.task.get().is_some()
}
// /// Get the current state of the future.
// pub fn reloading(&self) -> bool {
// self.task.get().is_some()
// }
}

View file

@ -4,7 +4,7 @@ use dioxus::prelude::*;
/// Used by the launch macro
#[doc(hidden)]
pub fn RouteWithCfg<R>(cx: Scope<FullstackRouterConfig<R>>) -> Element
pub fn RouteWithCfg<R>(props: FullstackRouterConfig<R>) -> Element
where
R: dioxus_router::prelude::Routable,
<R as std::str::FromStr>::Err: std::fmt::Display,
@ -14,7 +14,7 @@ where
#[cfg(feature = "ssr")]
let context = crate::prelude::server_context();
let cfg = *cx.props;
let cfg = props;
render! {
dioxus_router::prelude::Router::<R> {
config: move || {

View file

@ -1,6 +1,7 @@
#![allow(clippy::await_holding_refcell_ref)]
use async_trait::async_trait;
use dioxus_core::prelude::{consume_context, provide_context};
use dioxus_html::prelude::{EvalError, EvalProvider, Evaluator};
use std::{cell::RefCell, rc::Rc};
@ -8,9 +9,9 @@ use crate::query::{Query, QueryEngine};
/// Provides the DesktopEvalProvider through [`cx.provide_context`].
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 });
cx.provide_context(provider);
provide_context(provider);
}
/// Reprents the desktop-target's provider of evaluators.

View file

@ -5,7 +5,7 @@ use crate::{
query::{QueryEngine, QueryResult},
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_interpreter_js::binary_protocol::Channel;
use futures_util::{pin_mut, SinkExt, StreamExt};
@ -38,7 +38,7 @@ impl LiveViewPool {
pub async fn launch(
&self,
ws: impl LiveViewSocket,
app: fn(Scope<()>) -> Element,
app: fn(()) -> Element,
) -> Result<(), LiveViewError> {
self.launch_with_props(ws, app, ()).await
}
@ -46,7 +46,7 @@ impl LiveViewPool {
pub async fn launch_with_props<T: Send + 'static>(
&self,
ws: impl LiveViewSocket,
app: fn(Scope<T>) -> Element,
app: fn(T) -> Element,
props: T,
) -> Result<(), LiveViewError> {
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_engine = QueryEngine::new(query_tx);
vdom.base_scope().provide_context(query_engine.clone());
init_eval(vdom.base_scope());
init_eval();
// pin the futures so we can use select!
pin_mut!(ws);
@ -271,7 +271,7 @@ fn add_template(
*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::*;
match v {
Element {

View file

@ -40,7 +40,7 @@ fn create_random_template_node(
template_idx: &mut usize,
attr_idx: &mut usize,
depth: usize,
) -> TemplateNode<'static> {
) -> TemplateNode {
match rand::random::<u8>() % 4 {
0 => {
let attrs = {
@ -96,7 +96,7 @@ fn create_random_template_node(
}
fn generate_paths(
node: &TemplateNode<'static>,
node: &TemplateNode,
current_path: &[u8],
node_paths: &mut Vec<Vec<u8>>,
attr_paths: &mut Vec<Vec<u8>>,

View file

@ -15,15 +15,11 @@ fn App() -> Element {
onclick: move |_| *signal.write() += 1,
"Increase"
}
Child {
signal: doubled
}
Child { signal: doubled }
}
}
#[component]
fn Child(signal: ReadOnlySignal<usize>) -> Element {
render! {
"{signal}"
}
render! { "{signal}" }
}