use crate::editor::{MutationListenerOptions, NodeMutation};
use crate::lexical_utils::get_node_by_key;
use crate::node::NodeKey;
use crate::{Editor, LexicalError, Unregister};
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
fn code_gutter(children: &[crate::NodeRef]) -> String {
let mut gutter = String::from("1");
let mut count = 1;
for child in children {
if child.get_type() == "linebreak" {
count += 1;
gutter.push('\n');
gutter.push_str(&count.to_string());
}
}
gutter
}
pub fn register_code_gutter(
editor: &Editor,
set_gutter: impl Fn(&str, &str) + 'static,
) -> Result<Unregister, LexicalError> {
if editor.is_headless() {
return Ok(Box::new(|| {}));
}
let cached_children_length: Rc<RefCell<HashMap<NodeKey, usize>>> = Rc::default();
let weak = editor.weak();
editor.register_mutation_listener(
"code",
move |mutations, _| {
let Some(editor) = weak.upgrade().map(Editor) else {
return;
};
let mut cache = cached_children_length.borrow_mut();
let _ = editor.read_with_mode(crate::EditorReadMode::Latest, || {
for (key, mutation) in mutations {
match mutation {
NodeMutation::Destroyed => {
cache.remove(key);
continue;
}
NodeMutation::Created => {
cache.remove(key);
}
NodeMutation::Updated => {}
}
let Some(node) = get_node_by_key(key) else {
continue;
};
let children = node.get_children();
if cache.get(key) == Some(&children.len()) {
continue;
}
cache.insert(key.clone(), children.len());
set_gutter(key, &code_gutter(&children));
}
});
},
MutationListenerOptions {
skip_initialization: false,
},
)
}