use crate::any_props::AnyProps;
use crate::innerlude::{BorrowedAttributeValue, VComponent, VPlaceholder, VText};
use crate::mutations::Mutation;
use crate::mutations::Mutation::*;
use crate::nodes::VNode;
use crate::nodes::{DynamicNode, TemplateNode};
use crate::virtual_dom::VirtualDom;
use crate::{AttributeValue, ElementId, RenderReturn, ScopeId, SuspenseContext, Template};
use std::cell::Cell;
use std::iter::Peekable;
use std::rc::Rc;
use TemplateNode::*;
fn sort_bfs(paths: &[&'static [u8]]) -> Vec<(usize, &'static [u8])> {
let mut with_indecies = paths.iter().copied().enumerate().collect::<Vec<_>>();
with_indecies.sort_unstable_by(|(_, a), (_, b)| {
let mut a = a.iter();
let mut b = b.iter();
loop {
match (a.next(), b.next()) {
(Some(a), Some(b)) => {
if a != b {
return a.cmp(b);
}
}
(Some(_), None) => return std::cmp::Ordering::Less,
(None, Some(_)) => return std::cmp::Ordering::Greater,
(None, None) => return std::cmp::Ordering::Equal,
}
}
});
with_indecies
}
#[test]
fn sorting() {
let r: [(usize, &[u8]); 5] = [
(0, &[0, 1]),
(1, &[0, 2]),
(2, &[1, 0]),
(4, &[1, 1]),
(3, &[1, 2]),
];
assert_eq!(
sort_bfs(&[&[0, 1,], &[0, 2,], &[1, 0,], &[1, 2,], &[1, 1,],]),
r
);
assert!(matches!(&[0], &[_, ..]))
}
impl<'b> VirtualDom {
pub(crate) fn create_scope(&mut self, scope: ScopeId, template: &'b VNode<'b>) -> usize {
self.scope_stack.push(scope);
let out = self.create(template);
self.scope_stack.pop();
out
}
pub(crate) fn create(&mut self, node: &'b VNode<'b>) -> usize {
#[cfg(debug_assertions)]
{
let (path, byte_index) = node.template.get().name.rsplit_once(':').unwrap();
if let Some(template) = self
.templates
.get(path)
.and_then(|map| map.get(&byte_index.parse().unwrap()))
{
node.template.set(*template);
}
}
node.root_ids
.intialize(vec![ElementId(0); node.template.get().roots.len()].into_boxed_slice());
self.register_template(node.template.get());
self.mutations
.edits
.reserve(node.template.get().roots.len());
#[cfg(not(debug_assertions))]
let (mut attrs, mut nodes) = (
node.template
.get()
.attr_paths
.iter()
.copied()
.enumerate()
.peekable(),
node.template
.get()
.node_paths
.iter()
.copied()
.enumerate()
.map(|(i, path)| ((i, i), path))
.peekable(),
);
#[cfg(debug_assertions)]
let (attrs_sorted, nodes_sorted) = {
(
sort_bfs(node.template.get().attr_paths),
sort_bfs(node.template.get().node_paths),
)
};
#[cfg(debug_assertions)]
let (mut attrs, mut nodes) = {
(
attrs_sorted.into_iter().peekable(),
nodes_sorted
.iter()
.copied()
.enumerate()
.map(|(i, (id, path))| ((id, i), path))
.peekable(),
)
};
node.template
.get()
.roots
.iter()
.enumerate()
.map(|(idx, root)| match root {
DynamicText { id } | Dynamic { id } => {
nodes.next().unwrap();
self.write_dynamic_root(node, *id)
}
Element { .. } => {
#[cfg(not(debug_assertions))]
let id = self.write_element_root(node, idx, &mut attrs, &mut nodes, &[]);
#[cfg(debug_assertions)]
let id =
self.write_element_root(node, idx, &mut attrs, &mut nodes, &nodes_sorted);
id
}
Text { .. } => self.write_static_text_root(node, idx),
})
.sum()
}
fn write_static_text_root(&mut self, node: &VNode, idx: usize) -> usize {
self.load_template_root(node, idx);
1
}
fn write_dynamic_root(&mut self, template: &'b VNode<'b>, idx: usize) -> usize {
use DynamicNode::*;
match &template.dynamic_nodes[idx] {
node @ Component { .. } | node @ Fragment(_) => {
self.create_dynamic_node(template, node, idx)
}
Placeholder(VPlaceholder { id }) => {
let id = self.set_slot(template, id, idx);
self.mutations.push(CreatePlaceholder { id });
1
}
Text(VText { id, value }) => {
let id = self.set_slot(template, id, idx);
self.create_static_text(value, id);
1
}
}
}
fn create_static_text(&mut self, value: &str, id: ElementId) {
let unbounded_text: &str = unsafe { std::mem::transmute(value) };
self.mutations.push(CreateTextNode {
value: unbounded_text,
id,
});
}
fn write_element_root(
&mut self,
template: &'b VNode<'b>,
root_idx: usize,
dynamic_attrs: &mut Peekable<impl Iterator<Item = (usize, &'static [u8])>>,
dynamic_nodes_iter: &mut Peekable<impl Iterator<Item = ((usize, usize), &'static [u8])>>,
dynamic_nodes: &[(usize, &'static [u8])],
) -> usize {
let root_on_stack = self.load_template_root(template, root_idx);
self.write_attrs_on_root(dynamic_attrs, root_idx as u8, root_on_stack, template);
self.load_placeholders(dynamic_nodes_iter, dynamic_nodes, root_idx as u8, template);
1
}
#[allow(unused)]
fn load_placeholders(
&mut self,
dynamic_nodes_iter: &mut Peekable<impl Iterator<Item = ((usize, usize), &'static [u8])>>,
dynamic_nodes: &[(usize, &'static [u8])],
root_idx: u8,
template: &'b VNode<'b>,
) {
let (start, end) = match collect_dyn_node_range(dynamic_nodes_iter, root_idx) {
Some((a, b)) => (a, b),
None => return,
};
#[cfg(not(debug_assertions))]
let reversed_iter = (start..=end).rev();
#[cfg(debug_assertions)]
let reversed_iter = (start..=end)
.rev()
.map(|sorted_index| dynamic_nodes[sorted_index].0);
for idx in reversed_iter {
let m = self.create_dynamic_node(template, &template.dynamic_nodes[idx], idx);
if m > 0 {
let path = &template.template.get().node_paths[idx][1..];
self.mutations.push(ReplacePlaceholder { m, path });
}
}
}
fn write_attrs_on_root(
&mut self,
attrs: &mut Peekable<impl Iterator<Item = (usize, &'static [u8])>>,
root_idx: u8,
root: ElementId,
node: &VNode,
) {
while let Some((mut attr_id, path)) =
attrs.next_if(|(_, p)| p.first().copied() == Some(root_idx))
{
let id = self.assign_static_node_as_dynamic(path, root, node, attr_id);
loop {
self.write_attribute(&node.dynamic_attrs[attr_id], id);
match attrs.next_if(|(_, p)| *p == path) {
Some((next_attr_id, _)) => attr_id = next_attr_id,
None => break,
}
}
}
}
fn write_attribute(&mut self, attribute: &'b crate::Attribute<'b>, id: ElementId) {
attribute.mounted_element.set(id);
let unbounded_name: &str = unsafe { std::mem::transmute(attribute.name) };
match &attribute.value {
AttributeValue::Listener(_) => {
self.mutations.push(NewEventListener {
name: &unbounded_name[2..],
id,
})
}
_ => {
let value: BorrowedAttributeValue<'b> = (&attribute.value).into();
let unbounded_value = unsafe { std::mem::transmute(value) };
self.mutations.push(SetAttribute {
name: unbounded_name,
value: unbounded_value,
ns: attribute.namespace,
id,
})
}
}
}
fn load_template_root(&mut self, template: &VNode, root_idx: usize) -> ElementId {
let this_id = self.next_root(template, root_idx);
template.root_ids.set(root_idx, this_id);
self.mutations.push(LoadTemplate {
name: template.template.get().name,
index: root_idx,
id: this_id,
});
this_id
}
fn assign_static_node_as_dynamic(
&mut self,
path: &'static [u8],
this_id: ElementId,
template: &VNode,
attr_id: usize,
) -> ElementId {
if path.len() == 1 {
return this_id;
}
let id = self.next_element(template, template.template.get().attr_paths[attr_id]);
self.mutations.push(Mutation::AssignId {
path: &path[1..],
id,
});
id
}
pub(crate) fn register_template_first_byte_index(&mut self, mut template: Template<'static>) {
let (path, _) = template.name.rsplit_once(':').unwrap();
if let Some((_, old_template)) = self
.templates
.entry(path)
.or_default()
.iter_mut()
.min_by_key(|(byte_index, _)| **byte_index)
{
template.name = old_template.name;
*old_template = template;
} else {
self.templates
.entry(path)
.or_default()
.insert(usize::MAX, template);
}
if !template.is_completely_dynamic() {
self.mutations.templates.push(template);
}
}
pub(crate) fn register_template(&mut self, mut template: Template<'static>) {
let (path, byte_index) = template.name.rsplit_once(':').unwrap();
let byte_index = byte_index.parse::<usize>().unwrap();
if self
.templates
.get(&path)
.filter(|set| set.contains_key(&byte_index))
.is_none()
{
#[cfg(debug_assertions)]
if let Some(mut new_template) = self
.templates
.get_mut(path)
.and_then(|map| map.remove(&usize::MAX))
{
new_template.name = template.name;
template = new_template;
}
self.templates
.entry(path)
.or_default()
.insert(byte_index, template);
if !template.is_completely_dynamic() {
self.mutations.templates.push(template);
}
}
}
pub(crate) fn create_dynamic_node(
&mut self,
template: &'b VNode<'b>,
node: &'b DynamicNode<'b>,
idx: usize,
) -> usize {
use DynamicNode::*;
match node {
Text(text) => self.create_dynamic_text(template, text, idx),
Placeholder(place) => self.create_placeholder(place, template, idx),
Component(component) => self.create_component_node(template, component, idx),
Fragment(frag) => frag.iter().map(|child| self.create(child)).sum(),
}
}
fn create_dynamic_text(
&mut self,
template: &'b VNode<'b>,
text: &'b VText<'b>,
idx: usize,
) -> usize {
let new_id = self.next_element(template, template.template.get().node_paths[idx]);
text.id.set(Some(new_id));
let value = unsafe { std::mem::transmute(text.value) };
self.mutations.push(HydrateText {
id: new_id,
path: &template.template.get().node_paths[idx][1..],
value,
});
0
}
pub(crate) fn create_placeholder(
&mut self,
placeholder: &VPlaceholder,
template: &'b VNode<'b>,
idx: usize,
) -> usize {
let id = self.next_element(template, template.template.get().node_paths[idx]);
placeholder.id.set(Some(id));
self.mutations.push(AssignId {
path: &template.template.get().node_paths[idx][1..],
id,
});
0
}
pub(super) fn create_component_node(
&mut self,
template: &'b VNode<'b>,
component: &'b VComponent<'b>,
idx: usize,
) -> usize {
use RenderReturn::*;
let scope = self.load_scope_from_vcomponent(component);
component.scope.set(Some(scope));
match unsafe { self.run_scope(scope).extend_lifetime_ref() } {
Ready(t) => self.mount_component(scope, template, t, idx),
Aborted(t) => self.mount_aborted(template, t),
Pending(_) => self.mount_async(template, idx, scope),
}
}
fn load_scope_from_vcomponent(&mut self, component: &VComponent) -> ScopeId {
component
.props
.take()
.map(|props| {
let unbounded_props: Box<dyn AnyProps> = unsafe { std::mem::transmute(props) };
self.new_scope(unbounded_props, component.name).id
})
.unwrap_or_else(|| component.scope.get().unwrap())
}
fn mount_component(
&mut self,
scope: ScopeId,
parent: &'b VNode<'b>,
new: &'b VNode<'b>,
idx: usize,
) -> usize {
let mutations_to_this_point = self.mutations.edits.len();
let created = self.create_scope(scope, new);
if self.collected_leaves.is_empty() {
return created;
}
let boundary = match self.scopes[scope].has_context::<Rc<SuspenseContext>>() {
Some(boundary) => boundary,
_ => return created,
};
let new_id = self.next_element(new, parent.template.get().node_paths[idx]);
self.scopes[scope].placeholder.set(Some(new_id));
let split_off = unsafe {
std::mem::transmute::<Vec<Mutation>, Vec<Mutation>>(
self.mutations.edits.split_off(mutations_to_this_point),
)
};
boundary.mutations.borrow_mut().edits.extend(split_off);
boundary.created_on_stack.set(created);
boundary
.waiting_on
.borrow_mut()
.extend(self.collected_leaves.drain(..));
self.mutations.push(AssignId {
id: new_id,
path: &parent.template.get().node_paths[idx][1..],
});
0
}
fn mount_aborted(&mut self, parent: &'b VNode<'b>, placeholder: &VPlaceholder) -> usize {
let id = self.next_element(parent, &[]);
self.mutations.push(Mutation::CreatePlaceholder { id });
placeholder.id.set(Some(id));
1
}
fn mount_async(&mut self, template: &VNode, idx: usize, scope: ScopeId) -> usize {
let new_id = self.next_element(template, template.template.get().node_paths[idx]);
self.scopes[scope].placeholder.set(Some(new_id));
self.mutations.push(AssignId {
id: new_id,
path: &template.template.get().node_paths[idx][1..],
});
0
}
fn set_slot(
&mut self,
template: &'b VNode<'b>,
slot: &'b Cell<Option<ElementId>>,
id: usize,
) -> ElementId {
let id = self.next_element(template, template.template.get().node_paths[id]);
slot.set(Some(id));
id
}
}
fn collect_dyn_node_range(
dynamic_nodes: &mut Peekable<impl Iterator<Item = ((usize, usize), &'static [u8])>>,
root_idx: u8,
) -> Option<(usize, usize)> {
let start = match dynamic_nodes.peek() {
Some(((_, idx), [first, ..])) if *first == root_idx => *idx,
_ => return None,
};
let mut end = start;
while let Some(((_, idx), p)) =
dynamic_nodes.next_if(|(_, p)| matches!(p, [idx, ..] if *idx == root_idx))
{
if p.len() == 1 {
continue;
}
end = idx;
}
Some((start, end))
}