Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve AnyScope API #2445

Merged
merged 2 commits into from Feb 26, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
37 changes: 24 additions & 13 deletions packages/yew/src/html/component/scope.rs
Expand Up @@ -113,24 +113,35 @@ impl AnyScope {
}

/// Attempts to downcast into a typed scope
///
/// # Panics
///
/// If the self value can't be cast into the target type.
pub fn downcast<COMP: BaseComponent>(self) -> Scope<COMP> {
self.try_downcast::<COMP>().unwrap()
}

/// Attempts to downcast into a typed scope
///
/// Returns [`None`] if the self value can't be cast into the target type.
pub fn try_downcast<COMP: BaseComponent>(self) -> Option<Scope<COMP>> {
let state = self.state.borrow();

state
.as_ref()
.map(|m| {
m.inner
.as_any()
.downcast_ref::<CompStateInner<COMP>>()
.unwrap()
.context
.link()
.clone()
})
.unwrap()
state.as_ref().map(|m| {
m.inner
.as_any()
.downcast_ref::<CompStateInner<COMP>>()
.unwrap()
.context
.link()
.clone()
})
}

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