use std::rc::Rc;
use super::runtime::Owner;
use super::{untrack, with_runtime};
use crate::view::Element;
pub fn mount_component<R>(fn_ptr: *const (), body: impl FnOnce() -> R) -> (Owner, R) {
let owner = Owner::new(None);
with_runtime(|rt| {
if let Some(o) = rt.owners.get_mut(owner) {
o.mount_fn = Some(fn_ptr);
}
rt.component_owners.entry(fn_ptr).or_default().push(owner);
});
let result = untrack(|| owner.with(body));
(owner, result)
}
pub fn unmount_component(owner: Owner) {
let fn_ptr = with_runtime(|rt| rt.owners.get(owner).and_then(|o| o.mount_fn));
if let Some(fp) = fn_ptr {
with_runtime(|rt| {
if let Some(list) = rt.component_owners.get_mut(&fp) {
list.retain(|o| *o != owner);
if list.is_empty() {
rt.component_owners.remove(&fp);
}
}
});
}
owner.dispose();
}
pub fn on_mount(f: impl FnOnce() + 'static) {
if Owner::current().is_none() {
super::warn_no_owner("on_mount");
return;
}
let callback = crate::lifetime::Scoped::new(Some(f));
with_runtime(|rt| {
rt.pending_mounts.push(Box::new(move || {
callback.with_mut(|f| f.take().expect("mount callback runs once")());
}))
});
}
pub fn flush_mounts() {
let queue: Vec<Box<dyn FnOnce()>> = with_runtime(|rt| std::mem::take(&mut rt.pending_mounts));
for cb in queue {
untrack(cb);
}
}
#[doc(hidden)]
pub fn owners_for_fn(fn_ptr: *const ()) -> Vec<Owner> {
with_runtime(|rt| {
rt.component_owners
.get(&fn_ptr)
.cloned()
.unwrap_or_default()
})
}
use std::cell::RefCell;
pub(crate) type PendingMounts = Vec<(MountId, Element)>;
thread_local! {
static PENDING_MOUNTS: RefCell<PendingMounts> = const { RefCell::new(Vec::new()) };
}
pub(crate) fn swap_pending_mounts(pending: &mut PendingMounts) {
PENDING_MOUNTS.with_borrow_mut(|active| std::mem::swap(active, pending));
}
pub(crate) fn discard_pending_mounts() {
PENDING_MOUNTS.with_borrow_mut(Vec::clear);
}
#[cfg(test)]
pub(crate) fn pending_mount_count() -> usize {
PENDING_MOUNTS.with_borrow(Vec::len)
}
pub(crate) fn forget_pending_mounts(ids: &[MountId]) {
if ids.is_empty() {
return;
}
PENDING_MOUNTS.with_borrow_mut(|pending| pending.retain(|(id, _)| !ids.contains(id)));
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MountId(pub(crate) u64);
type SourceHashFn = Rc<dyn Fn() -> u64 + 'static>;
pub(crate) struct MountSite {
pub fn_ptr: *const (),
pub body: Rc<dyn Fn() -> Element + 'static>,
pub owner: Option<Owner>,
pub body_root: Option<Element>,
pub parent: Option<Element>,
pub anchor: Option<Element>,
pub props_hash_fn: Rc<dyn Fn() -> u64 + 'static>,
pub props_hash: u64,
pub body_hash_fn: SourceHashFn,
pub body_hash: u64,
}
pub fn on_component_root_attached(parent: Element, child: Element) {
let mount_ids: Vec<MountId> = PENDING_MOUNTS.with_borrow_mut(|pending| {
let mut attached = Vec::new();
pending.retain(|(mount_id, root)| {
let matches = *root == child;
if matches {
attached.push(*mount_id);
}
!matches
});
attached
});
if mount_ids.is_empty() {
return;
}
let anchor = crate::view::previous_sibling(parent, child);
super::with_runtime(|rt| {
for mount_id in &mount_ids {
if let Some(site) = rt.mount_sites.get_mut(mount_id) {
site.parent = Some(parent);
site.anchor = anchor;
}
}
});
}
#[doc(hidden)]
pub fn __reset_pending_mount_for_tests() {
discard_pending_mounts();
}
pub fn mount_component_remountable<F>(
fn_ptr: *const (),
body: F,
props_hash_fn: Box<dyn Fn() -> u64 + 'static>,
body_hash_fn: Box<dyn Fn() -> u64 + 'static>,
) -> Element
where
F: Fn() -> Element + 'static,
{
let body: Rc<dyn Fn() -> Element + 'static> = Rc::new(body);
let props_hash_fn: Rc<dyn Fn() -> u64 + 'static> = Rc::from(props_hash_fn);
let props_hash = props_hash_fn();
let body_hash_fn: SourceHashFn = Rc::from(body_hash_fn);
let body_hash = body_hash_fn();
let body_for_first = body.clone();
let owner = Owner::new(None);
with_runtime(|rt| {
if let Some(o) = rt.owners.get_mut(owner) {
o.mount_fn = Some(fn_ptr);
}
rt.component_owners.entry(fn_ptr).or_default().push(owner);
});
let body_root = untrack(|| owner.with(|| (*body_for_first)()));
let mount_id = with_runtime(|rt| {
rt.mount_id_counter += 1;
let id = MountId(rt.mount_id_counter);
rt.mount_sites.insert(
id,
MountSite {
fn_ptr,
body,
owner: Some(owner),
body_root: Some(body_root),
parent: None,
anchor: None,
props_hash_fn,
props_hash,
body_hash_fn,
body_hash,
},
);
rt.fn_ptr_mounts.entry(fn_ptr).or_default().push(id);
id
});
PENDING_MOUNTS.with_borrow_mut(|pending| pending.push((mount_id, body_root)));
body_root
}
pub fn remount_components_for(patched_fns: &[*const ()]) -> RemountStats {
if patched_fns.is_empty() {
return RemountStats::default();
}
let patched_set: std::collections::HashSet<*const ()> = patched_fns.iter().copied().collect();
let ids: Vec<MountId> = with_runtime(|rt| {
let mut candidates: Vec<MountId> = Vec::new();
for fp in patched_fns {
if let Some(list) = rt.fn_ptr_mounts.get(fp) {
for id in list {
if !candidates.contains(id) {
candidates.push(*id);
}
}
}
}
candidates
.into_iter()
.filter(|mount_id| {
let site = match rt.mount_sites.get(mount_id) {
Some(s) => s,
None => return false,
};
let mut cursor = match site.owner {
Some(o) => o,
None => return false,
};
while let Some(parent) = rt.owners.get(cursor).and_then(|o| o.parent) {
if let Some(mf) = rt.owners.get(parent).and_then(|o| o.mount_fn)
&& patched_set.contains(&mf)
{
return false;
}
cursor = parent;
}
true
})
.collect()
});
remount_sites(ids)
}
pub fn remount_changed_components() -> RemountStats {
let sites: Vec<(MountId, SourceHashFn, u64)> = with_runtime(|rt| {
rt.mount_sites
.iter()
.filter(|(_, site)| site.owner.is_some())
.map(|(id, site)| (*id, site.body_hash_fn.clone(), site.body_hash))
.collect()
});
let changed: Vec<MountId> = sites
.into_iter()
.filter(|(_, body_hash_fn, body_hash)| body_hash_fn() != *body_hash)
.map(|(id, _, _)| id)
.collect();
if changed.is_empty() {
return RemountStats::default();
}
let mut ids: Vec<MountId> = with_runtime(|rt| {
let changed_owners: std::collections::HashSet<Owner> = changed
.iter()
.filter_map(|id| rt.mount_sites.get(id).and_then(|site| site.owner))
.collect();
changed
.into_iter()
.filter(|mount_id| {
let Some(mut cursor) = rt.mount_sites.get(mount_id).and_then(|site| site.owner)
else {
return false;
};
while let Some(parent) = rt.owners.get(cursor).and_then(|o| o.parent) {
if changed_owners.contains(&parent) {
return false;
}
cursor = parent;
}
true
})
.collect()
});
ids.sort_by_key(|id| id.0);
remount_sites(ids)
}
fn remount_sites(ids: Vec<MountId>) -> RemountStats {
if ids.is_empty() {
return RemountStats::default();
}
struct RemountInfo {
mount_id: MountId,
parent: Element,
old_body_root: Element,
body: Rc<dyn Fn() -> Element + 'static>,
fn_ptr: *const (),
props_hash_fn: Rc<dyn Fn() -> u64 + 'static>,
props_hash: u64,
body_hash_fn: SourceHashFn,
}
let infos: Vec<RemountInfo> = with_runtime(|rt| {
ids.iter()
.filter_map(|mid| {
let site = rt.mount_sites.get(mid)?;
Some(RemountInfo {
mount_id: *mid,
parent: site.parent?,
old_body_root: site.body_root?,
body: site.body.clone(),
fn_ptr: site.fn_ptr,
props_hash_fn: site.props_hash_fn.clone(),
props_hash: site.props_hash,
body_hash_fn: site.body_hash_fn.clone(),
})
})
.collect()
});
let (infos, layout_changed): (Vec<RemountInfo>, Vec<RemountInfo>) = infos
.into_iter()
.partition(|info| (info.props_hash_fn)() == info.props_hash);
let layout_changed = layout_changed.len();
if infos.is_empty() {
return RemountStats {
remounted: 0,
layout_changed,
};
}
let mut parent_snapshot: std::collections::HashMap<Element, Vec<Element>> =
std::collections::HashMap::new();
for info in &infos {
parent_snapshot
.entry(info.parent)
.or_insert_with(|| crate::view::children_of(info.parent));
}
let mut by_parent: std::collections::HashMap<Element, Vec<(Element, Option<Element>)>> =
std::collections::HashMap::new();
for info in &infos {
crate::view::remove_child(info.parent, info.old_body_root);
by_parent
.entry(info.parent)
.or_default()
.push((info.old_body_root, None));
}
let mut results: Vec<(MountId, Element, Element, Element, Owner, u64)> =
Vec::with_capacity(infos.len());
for info in infos {
let old_owner = with_runtime(|rt| {
let site = rt.mount_sites.get_mut(&info.mount_id)?;
site.body_root.take();
site.owner.take()
});
let parent_owner =
old_owner.and_then(|o| with_runtime(|rt| rt.owners.get(o).and_then(|s| s.parent)));
if let Some(o) = old_owner {
o.dispose();
}
let new_owner = Owner::new(parent_owner);
with_runtime(|rt| {
if let Some(o) = rt.owners.get_mut(new_owner) {
o.mount_fn = Some(info.fn_ptr);
}
rt.component_owners
.entry(info.fn_ptr)
.or_default()
.push(new_owner);
});
let new_body_root = untrack(|| new_owner.with(|| (*info.body)()));
if let Some(list) = by_parent.get_mut(&info.parent)
&& let Some(entry) = list
.iter_mut()
.find(|(o, n)| *o == info.old_body_root && n.is_none())
{
entry.1 = Some(new_body_root);
}
results.push((
info.mount_id,
info.parent,
info.old_body_root,
new_body_root,
new_owner,
(info.body_hash_fn)(),
));
}
for (parent, pairs) in &by_parent {
let snapshot = parent_snapshot.get(parent).cloned().unwrap_or_default();
let old_to_new: std::collections::HashMap<Element, Element> = pairs
.iter()
.filter_map(|(o, n)| n.map(|new_root| (*o, new_root)))
.collect();
let desired: Vec<Element> = snapshot
.iter()
.map(|c| old_to_new.get(c).copied().unwrap_or(*c))
.collect();
let new_set: std::collections::HashSet<Element> =
pairs.iter().filter_map(|(_, n)| *n).collect();
for (idx, child) in desired.iter().enumerate() {
if new_set.contains(child) {
crate::view::insert_child_at(*parent, *child, idx);
}
}
}
for (mount_id, _, old_root, new_root, new_owner, body_hash) in &results {
with_runtime(|rt| {
for site in rt.mount_sites.values_mut() {
if site.body_root == Some(*old_root) {
site.body_root = Some(*new_root);
}
}
if let Some(site) = rt.mount_sites.get_mut(mount_id) {
site.owner = Some(*new_owner);
site.body_root = Some(*new_root);
site.body_hash = *body_hash;
}
});
}
for (mount_id, parent, _, new_root, _, _) in &results {
let new_anchor = crate::view::previous_sibling(*parent, *new_root);
with_runtime(|rt| {
if let Some(site) = rt.mount_sites.get_mut(mount_id) {
site.anchor = new_anchor;
}
});
}
RemountStats {
remounted: results.len(),
layout_changed,
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct RemountStats {
pub remounted: usize,
pub layout_changed: usize,
}