feat: get web working properly

This commit is contained in:
Jonathan Kelley committed 2022-11-30 17:21:10 -05:00
1 parent 3c19def550
commit 18d6b1ad6f
26 files changed
+674 -1422

No files matched your search

+19 -13
View File
@@ -13,7 +13,7 @@ pub(crate) struct ElementRef {
pub path: ElementPath,
// The actual template
pub template: *mut VNode<'static>,
pub template: *const VNode<'static>,
}
#[derive(Clone, Copy)]
@@ -58,10 +58,22 @@ impl VirtualDom {
}
pub(crate) fn try_reclaim(&mut self, el: ElementId) -> Option<ElementRef> {
assert_ne!(el, ElementId(0));
if el.0 == 0 {
panic!(
"Invalid element set to 0 - {:#?}",
std::backtrace::Backtrace::force_capture()
)
}
println!("reclaiming {:?}", el);
self.elements.try_remove(el.0)
}
pub(crate) fn update_template(&mut self, el: ElementId, node: &VNode) {
let node: *const VNode = node as *const _;
self.elements[el.0].template = unsafe { std::mem::transmute(node) };
}
// Drop a scope and all its children
pub(crate) fn drop_scope(&mut self, id: ScopeId) {
let scope = self.scopes.get(id.0).unwrap();
@@ -73,21 +85,15 @@ impl VirtualDom {
}
}
let scope = self.scopes.get(id.0).unwrap();
if let Some(root) = unsafe { scope.as_ref().previous_frame().try_load_node() } {
let root = unsafe { root.extend_lifetime_ref() };
if let RenderReturn::Sync(Ok(node)) = root {
self.drop_scope_inner(node)
}
}
let scope = self.scopes.get(id.0).unwrap().as_ref();
let scope = self.scopes.get_mut(id.0).unwrap();
scope.props.take();
// Drop all the hooks once the children are dropped
// this means we'll drop hooks bottom-up
for hook in scope.hook_list.borrow_mut().drain(..) {
for hook in scope.hook_list.get_mut().drain(..) {
println!("dropping hook !");
drop(unsafe { BumpBox::from_raw(hook) });
println!("hook dropped !");
}
}
+1 -1
View File
@@ -129,7 +129,7 @@ impl<'b> VirtualDom {
AttributeValue::Listener(_) => {
self.mutations.push(NewEventListener {
// all listeners start with "on"
event_name: &unbounded_name[2..],
name: &unbounded_name[2..],
scope: cur_scope,
id,
})
+62 -8
View File
@@ -1,3 +1,5 @@
use std::cell::Cell;
use crate::{
arena::ElementId,
factory::RenderReturn,
@@ -59,10 +61,17 @@ impl<'b> VirtualDom {
}
fn diff_node(&mut self, left_template: &'b VNode<'b>, right_template: &'b VNode<'b>) {
println!(
"diffing node {:#?},\n\n{:#?}",
left_template.template.id, right_template.template.id
);
if left_template.template.id != right_template.template.id {
return self.light_diff_templates(left_template, right_template);
}
println!("diffing attributs...");
for (left_attr, right_attr) in left_template
.dynamic_attrs
.iter()
@@ -73,6 +82,11 @@ impl<'b> VirtualDom {
.mounted_element
.set(left_attr.mounted_element.get());
// We want to make sure anything listener that gets pulled is valid
if let AttributeValue::Listener(_) = right_attr.value {
self.update_template(left_attr.mounted_element.get(), right_template);
}
if left_attr.value != right_attr.value || left_attr.volatile {
// todo: add more types of attribute values
match right_attr.value {
@@ -92,6 +106,8 @@ impl<'b> VirtualDom {
}
}
println!("diffing dyn nodes...");
for (idx, (left_node, right_node)) in left_template
.dynamic_nodes
.iter()
@@ -101,13 +117,24 @@ impl<'b> VirtualDom {
match (left_node, right_node) {
(Text(left), Text(right)) => self.diff_vtext(left, right),
(Fragment(left), Fragment(right)) => self.diff_non_empty_fragment(left, right),
(Placeholder(left), Placeholder(right)) => {
right.set(left.get());
}
(Component(left), Component(right)) => {
self.diff_vcomponent(left, right, right_template, idx)
}
_ => self.replace(left_template, right_template),
(Placeholder(left), Fragment(right)) => {
self.replace_placeholder_with_nodes(left, right)
}
(Fragment(left), Placeholder(right)) => {
self.replace_nodes_with_placeholder(left, right)
}
_ => todo!(),
};
}
println!("applying roots...");
// Make sure the roots get transferred over
for (left, right) in left_template
.root_ids
@@ -118,6 +145,30 @@ impl<'b> VirtualDom {
}
}
fn replace_placeholder_with_nodes(&mut self, l: &'b Cell<ElementId>, r: &'b [VNode<'b>]) {
let m = self.create_children(r);
let id = l.get();
self.mutations.push(Mutation::ReplaceWith { id, m });
self.reclaim(id);
}
fn replace_nodes_with_placeholder(&mut self, l: &'b [VNode<'b>], r: &'b Cell<ElementId>) {
// Create the placeholder first, ensuring we get a dedicated ID for the placeholder
let placeholder = self.next_element(&l[0], &[]);
r.set(placeholder);
self.mutations
.push(Mutation::CreatePlaceholder { id: placeholder });
// Remove the old nodes, except for onea
let first = self.replace_inner(&l[0]);
self.remove_nodes(&l[1..]);
self.mutations
.push(Mutation::ReplaceWith { id: first, m: 1 });
self.try_reclaim(first);
}
fn diff_vcomponent(
&mut self,
left: &'b VComponent<'b>,
@@ -140,6 +191,7 @@ impl<'b> VirtualDom {
};
self.mutations
.push(Mutation::ReplaceWith { id, m: created });
self.drop_scope(left.scope.get().unwrap());
return;
}
@@ -154,15 +206,12 @@ impl<'b> VirtualDom {
// If the props are static, then we try to memoize by setting the new with the old
// The target scopestate still has the reference to the old props, so there's no need to update anything
// This also implicitly drops the new props since they're not used
if left.static_props && unsafe { old.memoize(new.as_ref()) } {
if left.static_props && unsafe { old.as_ref().unwrap().memoize(new.as_ref()) } {
return;
}
// If the props are dynamic *or* the memoization failed, then we need to diff the props
// First, move over the props from the old to the new, dropping old props in the process
self.scopes[scope_id.0].props = unsafe { std::mem::transmute(new.as_ref()) };
right.props.set(Some(new));
self.scopes[scope_id.0].props = unsafe { std::mem::transmute(new) };
// Now run the component and diff it
self.run_scope(scope_id);
@@ -335,7 +384,7 @@ impl<'b> VirtualDom {
};
}
fn diff_non_empty_fragment(&mut self, new: &'b [VNode<'b>], old: &'b [VNode<'b>]) {
fn diff_non_empty_fragment(&mut self, old: &'b [VNode<'b>], new: &'b [VNode<'b>]) {
let new_is_keyed = new[0].key.is_some();
let old_is_keyed = old[0].key.is_some();
debug_assert!(
@@ -346,6 +395,9 @@ impl<'b> VirtualDom {
old.iter().all(|o| o.key.is_some() == old_is_keyed),
"all siblings must be keyed or all siblings must be non-keyed"
);
println!("Diffing fragment {:?}, {:?}", old.len(), new.len());
if new_is_keyed && old_is_keyed {
self.diff_keyed_children(old, new);
} else {
@@ -368,7 +420,9 @@ impl<'b> VirtualDom {
debug_assert!(!new.is_empty());
debug_assert!(!old.is_empty());
match old.len().cmp(&new.len()) {
println!("Diffing non keyed children");
match dbg!(old.len().cmp(&new.len())) {
Ordering::Greater => self.remove_nodes(&old[new.len()..]),
Ordering::Less => self.create_and_insert_after(&new[old.len()..], old.last().unwrap()),
Ordering::Equal => {}
+4 -4
View File
@@ -158,7 +158,7 @@ pub enum Mutation<'a> {
/// Create a new Event Listener.
NewEventListener {
/// The name of the event to listen for.
event_name: &'a str,
name: &'a str,
/// The ID of the node to attach the listener to.
scope: ScopeId,
@@ -169,11 +169,11 @@ pub enum Mutation<'a> {
/// Remove an existing Event Listener.
RemoveEventListener {
/// The name of the event to remove.
name: &'a str,
/// The ID of the node to remove.
id: ElementId,
/// The name of the event to remove.
event: &'a str,
},
Remove {
id: ElementId,
+5 -2
View File
@@ -28,7 +28,7 @@ impl VirtualDom {
parent,
id,
height,
props,
props: Some(props),
placeholder: Default::default(),
node_arena_1: BumpFrame::new(50),
node_arena_2: BumpFrame::new(50),
@@ -86,6 +86,8 @@ impl VirtualDom {
}
pub(crate) fn run_scope(&mut self, scope_id: ScopeId) -> &RenderReturn {
println!("Running scope {:?}", scope_id);
// Cycle to the next frame and then reset it
// This breaks any latent references, invalidating every pointer referencing into it.
// Remove all the outdated listeners
@@ -100,7 +102,8 @@ impl VirtualDom {
scope.hook_idx.set(0);
// safety: due to how we traverse the tree, we know that the scope is not currently aliased
let props: &dyn AnyProps = mem::transmute(&*scope.props);
let props = scope.props.as_ref().unwrap().as_ref();
let props: &dyn AnyProps = mem::transmute(props);
props.render(scope).extend_lifetime()
};
+1 -1
View File
@@ -82,7 +82,7 @@ pub struct ScopeState {
pub(crate) tasks: Rc<Scheduler>,
pub(crate) spawned_tasks: HashSet<TaskId>,
pub(crate) props: Box<dyn AnyProps<'static>>,
pub(crate) props: Option<Box<dyn AnyProps<'static>>>,
pub(crate) placeholder: Cell<Option<ElementId>>,
}
+24 -6
View File
@@ -362,6 +362,8 @@ impl VirtualDom {
let target_path = el_ref.path;
for (idx, attr) in template.dynamic_attrs.iter().enumerate() {
println!("{:?} \n {:?} \n {:?}", attr, name, element);
let this_path = template.template.attr_paths[idx];
// listeners are required to be prefixed with "on", but they come back to the virtualdom with that missing
@@ -383,6 +385,8 @@ impl VirtualDom {
}
}
println!("calling listeners: {:?}", listeners);
// Now that we've accumulated all the parent attributes for the target element, call them in reverse order
// We check the bubble state between each call to see if the event has been stopped from bubbling
for listener in listeners.drain(..).rev() {
@@ -399,6 +403,8 @@ impl VirtualDom {
parent_path = template.parent.and_then(|id| self.elements.get(id.0));
}
println!("all listeners exhausted");
}
/// Wait for the scheduler to have any work.
@@ -448,12 +454,15 @@ impl VirtualDom {
}
}
/// Swap the current mutations with a new
fn finalize(&mut self) -> Mutations {
// todo: make this a routine
let mut out = Mutations::default();
std::mem::swap(&mut self.mutations, &mut out);
out
/// Process all events in the queue until there are no more left
pub fn process_events(&mut self) {
while let Ok(Some(msg)) = self.rx.try_next() {
match msg {
SchedulerMsg::Immediate(id) => self.mark_dirty(id),
SchedulerMsg::TaskNotified(task) => self.handle_task_wakeup(task),
SchedulerMsg::SuspenseNotified(id) => self.handle_suspense_wakeup(id),
}
}
}
/// Performs a *full* rebuild of the virtual dom, returning every edit required to generate the actual dom from scratch.
@@ -515,6 +524,7 @@ impl VirtualDom {
///
/// If no suspense trees are present
pub async fn render_with_deadline(&mut self, deadline: impl Future<Output = ()>) -> Mutations {
println!("render with deadline");
pin_mut!(deadline);
loop {
@@ -600,6 +610,14 @@ impl VirtualDom {
}
}
}
/// Swap the current mutations with a new
fn finalize(&mut self) -> Mutations {
// todo: make this a routine
let mut out = Mutations::default();
std::mem::swap(&mut self.mutations, &mut out);
out
}
}
impl Drop for VirtualDom {