use crate::editor::NodeClass;
use crate::error::invariant;
use crate::lexical_selection::SelectionRef;
use crate::lexical_utils::{get_node_by_key, get_writable, mutate};
use crate::node::{LexicalNode, NodeKey, NodeRef};
use crate::updates::{get_active_editor_state, get_registry_editor};
use crate::{LexicalError, utf16};
use std::cmp::Ordering;
use std::rc::Rc;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct SlotMap {
entries: Vec<(String, NodeKey)>,
}
impl SlotMap {
pub(crate) fn len(&self) -> usize {
self.entries.len()
}
pub(crate) fn get(&self, name: &str) -> Option<&NodeKey> {
self.entries.iter().find(|(n, _)| n == name).map(|(_, k)| k)
}
pub(crate) fn set(&mut self, name: &str, key: NodeKey) {
match self.entries.iter_mut().find(|(n, _)| n == name) {
Some(entry) => entry.1 = key,
None => self.entries.push((name.to_owned(), key)),
}
}
fn delete(&mut self, name: &str) {
self.entries.retain(|(n, _)| n != name);
}
pub(crate) fn names(&self) -> impl Iterator<Item = &str> {
self.entries.iter().map(|(n, _)| n.as_str())
}
pub(crate) fn values(&self) -> impl Iterator<Item = &NodeKey> {
self.entries.iter().map(|(_, k)| k)
}
pub(crate) fn iter(&self) -> impl Iterator<Item = (&str, &NodeKey)> {
self.entries.iter().map(|(n, k)| (n.as_str(), k))
}
}
fn is_slot_node(node: &dyn LexicalNode) -> bool {
node.element().is_some() || node.is_decorator()
}
pub fn is_slot_host(node: &NodeRef) -> bool {
is_slot_node(&*node.get_latest())
}
pub fn is_slot_child(node: &NodeRef) -> bool {
is_slot_node(&*node.get_latest())
}
pub(crate) fn slot_host_key_field(node: &dyn LexicalNode) -> Option<&NodeKey> {
if is_slot_node(node) {
node.base().slot_host.as_ref()
} else {
None
}
}
pub(crate) fn slots_field(node: &dyn LexicalNode) -> Option<&SlotMap> {
if is_slot_node(node) {
node.base().slots.as_deref()
} else {
None
}
}
pub(crate) fn get_slot_host_key(node: &NodeRef) -> Option<NodeKey> {
slot_host_key_field(&*node.get_latest()).cloned()
}
pub fn get_slot_host(node: &NodeRef) -> Option<NodeRef> {
let slot_host_key = get_slot_host_key(node)?;
let host = get_node_by_key(&slot_host_key);
match host {
Some(host) if is_slot_host(&host) => Some(host),
_ => panic!("slotHost must be an ElementNode or a DecoratorNode"),
}
}
pub fn get_slot_name_within_host(slot_child: &NodeRef) -> Option<String> {
let host = get_slot_host(slot_child)?;
get_slot_map(&host)
.iter()
.find(|(_, key)| key.as_str() == slot_child.get_key())
.map(|(name, _)| name.to_owned())
}
pub fn get_slot_frame(node: &NodeRef) -> Option<NodeRef> {
let mut current = Some(node.clone());
while let Some(node) = current {
if get_slot_host_key(&node).is_some() {
return Some(node);
}
current = node.get_parent();
}
None
}
pub fn get_selection_slot_frame(
selection: Option<&SelectionRef>,
) -> Result<Option<NodeRef>, LexicalError> {
let Some(selection) = selection else {
return Ok(None);
};
let anchor_node = match selection.range() {
Some(range) => Some(range.anchor.get_node()?),
None => selection.get_nodes()?.into_iter().next(),
};
Ok(anchor_node.and_then(|node| get_slot_frame(&node)))
}
pub(crate) fn get_slot_map(node: &NodeRef) -> SlotMap {
slots_field(&*node.get_latest())
.cloned()
.unwrap_or_default()
}
pub fn get_slot_names(node: &NodeRef) -> Vec<String> {
get_slot_map(node).names().map(str::to_owned).collect()
}
pub fn get_slot(node: &NodeRef, name: &str) -> Option<NodeRef> {
let key = get_slot_map(node).get(name).cloned()?;
get_node_by_key(&key)
}
const RESERVED_SLOT_NAMES: [&str; 3] = ["__proto__", "constructor", "prototype"];
pub fn get_declared_slots(klass: &NodeClass) -> &'static [&'static str] {
(klass.declared_slots)()
}
pub(crate) fn get_slots_text_content(node: &dyn LexicalNode) -> String {
let mut text_content = String::new();
if let Some(slots) = slots_field(node) {
for key in slots.values() {
if let Some(slot) = get_node_by_key(key) {
text_content.push_str(&slot.get_text_content());
}
}
}
text_content
}
pub(crate) fn get_slots_text_content_size(node: &dyn LexicalNode) -> usize {
let mut text_content_size = 0;
if let Some(slots) = slots_field(node) {
for key in slots.values() {
if let Some(slot) = get_node_by_key(key) {
text_content_size += slot.get_text_content_size();
}
}
}
text_content_size
}
fn get_declared_slot_rank(
node_type: &str,
declared: &[&'static str],
) -> Result<Vec<&'static str>, LexicalError> {
let mut built: Vec<&'static str> = Vec::new();
for &name in declared {
invariant!(
!RESERVED_SLOT_NAMES.contains(&name),
"getDeclaredSlotRank: {node_type} declares reserved slot name \"{name}\"; __proto__, constructor, and prototype break the plain-object serialization of slots"
);
invariant!(
!built.contains(&name),
"getDeclaredSlotRank: {node_type} declares slot name \"{name}\" more than once; the canonical order would be ambiguous"
);
built.push(name);
}
Ok(built)
}
fn compare_slot_names(a: &str, b: &str, rank: &[&str]) -> Ordering {
let rank_a = rank.iter().position(|n| *n == a);
let rank_b = rank.iter().position(|n| *n == b);
match (rank_a, rank_b) {
(Some(a), Some(b)) => a.cmp(&b),
(Some(_), None) => Ordering::Less,
(None, Some(_)) => Ordering::Greater,
(None, None) => utf16::cmp(a, b),
}
}
fn canonicalize_slot_order(host: &NodeRef) -> Result<(), LexicalError> {
let entries = {
let latest = host.get_latest();
let Some(slots) = slots_field(&*latest) else {
return Ok(());
};
if slots.len() < 2 {
return Ok(());
}
let rank = get_declared_slot_rank(latest.get_type(), latest.declared_slots())?;
let names: Vec<&str> = slots.names().collect();
if names
.windows(2)
.all(|w| compare_slot_names(w[0], w[1], &rank) != Ordering::Greater)
{
return Ok(());
}
let mut entries = slots.entries.clone();
entries.sort_by(|(a, _), (b, _)| compare_slot_names(a, b, &rank));
entries
};
mutate(host.get_key(), |n| {
n.base_mut().slots = Some(Rc::new(SlotMap { entries }))
});
Ok(())
}
fn with_writable_slots(host: &str, f: impl FnOnce(&mut SlotMap)) {
mutate(host, |n| {
f(Rc::make_mut(n.base_mut().slots.get_or_insert_default()))
});
}
pub(crate) fn mark_slots_used() {
if let Some(editor) = get_registry_editor() {
editor.0.slots_used.set(true);
}
get_active_editor_state().0.slots_used.set(true);
}
pub(crate) fn slots_used() -> bool {
get_registry_editor().is_some_and(|e| e.0.slots_used.get())
}
pub fn set_slot(host: &NodeRef, name: &str, node: &NodeRef) -> Result<NodeRef, LexicalError> {
invariant!(
!RESERVED_SLOT_NAMES.contains(&name),
"$setSlot: \"{name}\" is a reserved slot name; __proto__, constructor, and prototype break the plain-object serialization of slots"
);
invariant!(
is_slot_host(host),
"$setSlot: host {} is not an ElementNode or DecoratorNode",
host.get_key()
);
if get_slot_map(host).get(name).map(String::as_str) == Some(node.get_key()) {
return Ok(host.clone());
}
invariant!(
(node.is_element() || node.is_decorator()) && !node.is_inline(),
"$setSlot: node {} is not a valid slot value; a slot value must be a non-inline ElementNode or DecoratorNode (the slot link itself is the shadow boundary).",
node.get_key()
);
invariant!(
!is_slot_ancestor_or_self(node, host),
"$setSlot: node {} cannot be slotted into {}; a node may not host itself or an ancestor reached through children or slot up-links — the slot up-link would form a cycle that loops isAttached/GC.",
node.get_key(),
host.get_key()
);
get_writable(host.get_key());
if let Some(previous_key) = get_slot_map(host).get(name).cloned() {
detach_slotted_node(&previous_key)?;
}
get_writable(node.get_key());
if let Some(previous_host) = get_slot_host(node) {
if let Some(previous_name) = get_slot_name_within_host(node) {
get_writable(previous_host.get_key());
with_writable_slots(previous_host.get_key(), |slots| {
slots.delete(&previous_name)
});
}
mutate(node.get_key(), |n| n.base_mut().slot_host = None);
}
crate::caret_tree::detach_node(node)?;
let host_key = host.get_key().to_owned();
mutate(node.get_key(), |n| n.base_mut().slot_host = Some(host_key));
let node_key = node.get_key().to_owned();
with_writable_slots(host.get_key(), |slots| slots.set(name, node_key));
canonicalize_slot_order(host)?;
mark_slots_used();
Ok(host.clone())
}
pub fn remove_slot(host: &NodeRef, name: &str) -> Result<NodeRef, LexicalError> {
invariant!(
is_slot_host(host),
"$removeSlot: host {} is not an ElementNode or DecoratorNode",
host.get_key()
);
get_writable(host.get_key());
if slots_field(&*host.get_latest()).is_none() {
return Ok(host.clone());
}
if let Some(previous_key) = get_slot_map(host).get(name).cloned() {
detach_slotted_node(&previous_key)?;
with_writable_slots(host.get_key(), |slots| slots.delete(name));
}
Ok(host.clone())
}
fn is_slot_ancestor_or_self(node: &NodeRef, host: &NodeRef) -> bool {
let mut key = Some(host.get_key().to_owned());
while let Some(k) = key {
if k == node.get_key() {
return true;
}
let Some(current) = get_node_by_key(&k) else {
break;
};
key = current.get_parent().map(|p| p.get_key().to_owned());
if key.is_none() {
key = get_slot_host_key(¤t);
}
}
false
}
pub(crate) fn error_on_slot_cycle_child(
parent: &NodeRef,
child: &NodeRef,
) -> Result<(), LexicalError> {
if !get_registry_editor().is_some_and(|e| e.0.slots_used.get()) {
return Ok(());
}
invariant!(
!is_slot_ancestor_or_self(child, parent),
"insert: node {} cannot become a child of {}; the parent is reachable from the node through slot up-links, so the insertion would form a cycle that loops isAttached/GC.",
child.get_key(),
parent.get_key()
);
Ok(())
}
fn detach_slotted_node(slot_key: &str) -> Result<(), LexicalError> {
let Some(previous) = get_node_by_key(slot_key) else {
return Ok(());
};
get_writable(slot_key);
invariant!(
is_slot_child(&previous),
"detach: slotted node {slot_key} must be an ElementNode or a DecoratorNode"
);
mutate(slot_key, |n| n.base_mut().slot_host = None);
previous.remove(false)
}