Skip to content

Commit 36058d4

Browse files
authored
Improve AnyScope API (#2445)
* Improve AnyScope API Signed-off-by: Aaron Erhardt <[email protected]> * Make find_parent_scope public Signed-off-by: Aaron Erhardt <[email protected]>
1 parent 6fc9ef4 commit 36058d4

File tree

1 file changed

+24
-13
lines changed

1 file changed

+24
-13
lines changed

packages/yew/src/html/component/scope.rs

+24-13
Original file line numberDiff line numberDiff line change
@@ -113,24 +113,35 @@ impl AnyScope {
113113
}
114114

115115
/// Attempts to downcast into a typed scope
116+
///
117+
/// # Panics
118+
///
119+
/// If the self value can't be cast into the target type.
116120
pub fn downcast<COMP: BaseComponent>(self) -> Scope<COMP> {
121+
self.try_downcast::<COMP>().unwrap()
122+
}
123+
124+
/// Attempts to downcast into a typed scope
125+
///
126+
/// Returns [`None`] if the self value can't be cast into the target type.
127+
pub fn try_downcast<COMP: BaseComponent>(self) -> Option<Scope<COMP>> {
117128
let state = self.state.borrow();
118129

119-
state
120-
.as_ref()
121-
.map(|m| {
122-
m.inner
123-
.as_any()
124-
.downcast_ref::<CompStateInner<COMP>>()
125-
.unwrap()
126-
.context
127-
.link()
128-
.clone()
129-
})
130-
.unwrap()
130+
state.as_ref().map(|m| {
131+
m.inner
132+
.as_any()
133+
.downcast_ref::<CompStateInner<COMP>>()
134+
.unwrap()
135+
.context
136+
.link()
137+
.clone()
138+
})
131139
}
132140

133-
pub(crate) fn find_parent_scope<C: BaseComponent>(&self) -> Option<Scope<C>> {
141+
/// Attempts to find a parent scope of a certain type
142+
///
143+
/// Returns [`None`] if no parent scope with the specified type was found.
144+
pub fn find_parent_scope<C: BaseComponent>(&self) -> Option<Scope<C>> {
134145
let expected_type_id = TypeId::of::<C>();
135146
iter::successors(Some(self), |scope| scope.get_parent())
136147
.filter(|scope| scope.get_type_id() == &expected_type_id)

0 commit comments

Comments
 (0)