use plushie_core::protocol::TreeNode;
use serde_json::Value;
#[derive(Debug, Clone, Copy)]
pub struct Element<'a> {
node: &'a TreeNode,
}
impl<'a> Element<'a> {
pub fn new(node: &'a TreeNode) -> Self {
Self { node }
}
pub fn id(&self) -> &str {
&self.node.id
}
pub fn widget_type(&self) -> &str {
&self.node.type_name
}
pub fn node(&self) -> &'a TreeNode {
self.node
}
pub fn children(&self) -> Vec<Element<'a>> {
self.node.children.iter().map(Element::new).collect()
}
pub fn text(&self) -> Option<&'a str> {
for key in &["content", "label", "value", "placeholder"] {
if let Some(text) = self.node.props.get_str(key) {
return Some(text);
}
}
None
}
pub fn prop_str(&self, key: &str) -> Option<&'a str> {
self.node.props.get_str(key)
}
pub fn prop_f32(&self, key: &str) -> Option<f32> {
self.node.props.get_f32(key)
}
pub fn prop_bool(&self, key: &str) -> Option<bool> {
self.node.props.get_bool(key)
}
pub fn prop(&self, key: &str) -> Option<Value> {
self.node.props.get_value(key)
}
pub fn a11y(&self) -> Option<Value> {
self.node.props.get_value("a11y")
}
pub fn inferred_role(&self) -> String {
if let Some(a11y) = self.node.props.get_value("a11y")
&& let Some(role) = a11y.get("role").and_then(|v| v.as_str())
{
return role.to_string();
}
widget_type_to_role(&self.node.type_name).to_string()
}
pub fn is_focused(&self) -> bool {
if self.node.props.get_bool("focused") == Some(true) {
return true;
}
if let Some(a11y) = self.node.props.get_value("a11y")
&& a11y.get("focused").and_then(|v| v.as_bool()) == Some(true)
{
return true;
}
false
}
pub fn is_disabled(&self) -> bool {
self.node.props.get_bool("disabled") == Some(true)
}
}
impl<'a> From<&'a TreeNode> for Element<'a> {
fn from(node: &'a TreeNode) -> Self {
Self::new(node)
}
}
fn widget_type_to_role(widget_type: &str) -> &str {
match widget_type {
"button" => "button",
"checkbox" => "check_box",
"toggler" => "switch",
"radio" => "radio_button",
"text_input" => "text_input",
"text_editor" => "multiline_text_input",
"text" => "label",
"rich_text" => "label",
"slider" => "slider",
"vertical_slider" => "slider",
"pick_list" => "combo_box",
"combo_box" => "combo_box",
"progress_bar" => "progress_indicator",
"image" => "image",
"svg" => "image",
"scrollable" => "scroll_view",
"container" => "group",
"column" => "group",
"row" => "group",
"stack" => "group",
"grid" => "group",
"pane_grid" => "group",
"table" => "table",
"canvas" => "canvas",
"tooltip" => "tooltip",
"space" => "space",
"rule" => "separator",
other => other,
}
}