deduplicate more find code

This commit is contained in:
Quaternions 2024-10-04 21:08:28 -07:00
parent 3a716373db
commit 7b8f091ab3

View File

@ -29,6 +29,13 @@ fn get_full_name(dom:&rbx_dom_weak::WeakDom,instance:&rbx_dom_weak::Instance)->S
full_name
}
pub fn find_first_child<'a>(dom:&'a rbx_dom_weak::WeakDom,instance:&rbx_dom_weak::Instance,name:&str)->Option<&'a rbx_dom_weak::Instance>{
instance.children().iter().filter_map(|&r|dom.get_by_ref(r)).find(|inst|inst.name==name)
}
pub fn find_first_descendant<'a>(dom:&'a rbx_dom_weak::WeakDom,instance:&rbx_dom_weak::Instance,name:&str)->Option<&'a rbx_dom_weak::Instance>{
dom.descendants_of(instance.referent()).find(|&inst|inst.name==name)
}
pub fn find_first_child_of_class<'a>(dom:&'a rbx_dom_weak::WeakDom,instance:&rbx_dom_weak::Instance,class:&str)->Option<&'a rbx_dom_weak::Instance>{
instance.children().iter().filter_map(|&r|dom.get_by_ref(r)).find(|inst|inst.class==class)
}
@ -171,10 +178,8 @@ impl Instance{
let instance=this.get(dom)?;
Ok(
match search_descendants.unwrap_or(false){
true=>dom.descendants_of(this.referent()).find(|inst|inst.name==name_str),
false=>instance.children().iter().filter_map(|&r|
dom.get_by_ref(r)
).find(|inst|inst.name==name_str),
true=>find_first_descendant(dom,instance,name_str),
false=>find_first_child(dom,instance,name_str),
}
.map(|instance|
Instance::new(instance.referent())
@ -192,7 +197,9 @@ impl Instance{
true=>find_first_descendant_of_class(dom,this.get(dom)?,class_str),
false=>find_first_child_of_class(dom,this.get(dom)?,class_str),
}
.map(|inst|(Instance::new(inst.referent())))
.map(|instance|
Instance::new(instance.referent())
)
)
})
});
@ -232,13 +239,9 @@ impl Instance{
}
//find a child with a matching name
Ok(
instance.children()
.iter()
.find(|&&r|
dom.get_by_ref(r)
.is_some_and(|instance|instance.name==index_str)
)
.map(|&referent|Instance::new(referent)).into_lua(lua)
find_first_child(dom,instance,index_str)
.map(|instance|Instance::new(instance.referent()))
.into_lua(lua)
)
})
});
@ -320,15 +323,11 @@ impl DataModel{
dom(lua,|dom|{
match service.as_str(){
"Lighting"=>{
let referent=dom.root()
.children()
.iter()
.find(|&&c|
dom.get_by_ref(c).is_some_and(|c|c.class=="Lighting")
).map(|r|*r)
.unwrap_or_else(||
dom.insert(dom.root_ref(),InstanceBuilder::new("Lighting"))
);
let referent=find_first_child_of_class(dom,dom.root(),"Lighting")
.map(|instance|instance.referent())
.unwrap_or_else(||
dom.insert(dom.root_ref(),InstanceBuilder::new("Lighting"))
);
Lighting::new(referent).into_lua(lua)
},
other=>Err::<mlua::Value,_>(mlua::Error::runtime(format!("Service '{other}' not supported"))),