use blitz_dom::node::NodeData;
use blitz_dom::{BaseDocument, NodeId};
use crate::Result;
pub fn data(doc: &BaseDocument, node: NodeId) -> Result<Option<String>> {
Ok(match doc.get_node(node).map(|node| &node.data) {
Some(NodeData::Text(data)) => Some(data.content.clone()),
Some(NodeData::Comment { contents }) => Some(contents.clone()),
_ => None,
})
}
pub fn set_data(doc: &mut BaseDocument, node: NodeId, text: &str) -> Result<()> {
doc.mutate().set_node_text(node, text);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::document;
use crate::test_support::skeleton;
#[test]
fn data_reads_a_text_node() {
let (mut doc, _html, _head, _body) = skeleton();
let text = document::create_text_node(&mut doc, "hello").unwrap();
assert_eq!(data(&doc, text).unwrap(), Some("hello".to_string()));
}
#[test]
fn data_is_null_for_an_element() {
let (doc, _html, _head, body) = skeleton();
assert_eq!(data(&doc, body).unwrap(), None);
}
#[test]
fn data_reads_a_comments_contents() {
let (mut doc, _html, _head, _body) = skeleton();
let comment = document::create_comment(&mut doc, "note").unwrap();
assert_eq!(data(&doc, comment).unwrap(), Some("note".to_string()));
}
#[test]
fn set_data_rewrites_the_text_in_place() {
let (mut doc, _html, _head, _body) = skeleton();
let text = document::create_text_node(&mut doc, "before").unwrap();
set_data(&mut doc, text, "after").unwrap();
assert_eq!(data(&doc, text).unwrap(), Some("after".to_string()));
}
#[test]
fn a_comments_data_round_trips_through_a_write_and_a_clone() {
let (mut doc, _html, _head, _body) = skeleton();
let comment = document::create_comment(&mut doc, "first").unwrap();
assert_eq!(data(&doc, comment).unwrap(), Some("first".to_string()));
set_data(&mut doc, comment, "second").unwrap();
assert_eq!(data(&doc, comment).unwrap(), Some("second".to_string()));
let copy = crate::node::clone_node(&mut doc, comment, false).unwrap();
assert_ne!(copy, comment);
assert_eq!(
data(&doc, copy).unwrap(),
data(&doc, comment).unwrap(),
"a comment and its clone must report the same data"
);
assert_eq!(data(&doc, copy).unwrap(), Some("second".to_string()));
}
}