use rdom_core::NodeId;
use crate::TuiDom;
pub fn value(dom: &TuiDom, input: NodeId) -> String {
let mut out = String::new();
for child in dom.node(input).child_nodes() {
if child.node_type() == rdom_core::NodeType::Text
&& let Some(s) = child.node_value()
{
out.push_str(s);
}
}
out
}
pub fn set_value(dom: &mut TuiDom, input: NodeId, new_value: &str) {
let _ = dom.set_attribute(input, "value", new_value);
let _ = crate::node::install_text_content(dom, input, new_value);
}
pub fn seed_all(dom: &mut TuiDom) {
let inputs: Vec<NodeId> = collect_inputs(dom, dom.root());
for id in inputs {
if !is_text_family_input(dom, id) {
continue;
}
let want = dom
.node(id)
.get_attribute("value")
.unwrap_or("")
.to_string();
let have = value(dom, id);
let has_text_child = dom
.node(id)
.child_nodes()
.any(|c| c.node_type() == rdom_core::NodeType::Text);
if !has_text_child || want != have {
let _ = crate::node::install_text_content(dom, id, &want);
}
}
let textareas: Vec<NodeId> = collect_textareas(dom, dom.root());
for id in textareas {
let has_text_child = dom
.node(id)
.child_nodes()
.any(|c| c.node_type() == rdom_core::NodeType::Text);
if !has_text_child {
let _ = crate::node::install_text_content(dom, id, "");
}
}
}
fn is_text_family_input(dom: &TuiDom, id: NodeId) -> bool {
matches!(
dom.node(id).get_attribute("type"),
None | Some("text")
| Some("password")
| Some("email")
| Some("url")
| Some("tel")
| Some("search")
| Some("number")
)
}
pub fn mirror_to_attribute(dom: &mut TuiDom, editable: NodeId) {
if dom.node(editable).tag_name() != Some("input") {
return;
}
let live = value(dom, editable);
let _ = dom.set_attribute(editable, "value", &live);
}
fn collect_inputs(dom: &TuiDom, root: NodeId) -> Vec<NodeId> {
let mut out = Vec::new();
walk_by_tag(dom, root, "input", &mut out);
out
}
fn collect_textareas(dom: &TuiDom, root: NodeId) -> Vec<NodeId> {
let mut out = Vec::new();
walk_by_tag(dom, root, "textarea", &mut out);
out
}
fn walk_by_tag(dom: &TuiDom, id: NodeId, tag: &str, out: &mut Vec<NodeId>) {
if dom.node(id).tag_name() == Some(tag) {
out.push(id);
}
for child in dom.node(id).child_nodes() {
walk_by_tag(dom, child.id(), tag, out);
}
}
#[cfg(test)]
mod tests;