Added hasAncestor and findNearestAncestor(Class) methods to ComponentContext.

This commit is contained in:
Jesse Brault 2025-01-27 14:16:00 -06:00
parent 148ced050b
commit 369dc51779
2 changed files with 31 additions and 1 deletions

View File

@ -99,6 +99,23 @@ public interface ComponentContext {
return ancestorClass.cast(this.findNearestAncestor(matching.and(ancestorClass::isInstance)));
}
default <T extends ViewComponent> @Nullable T findNearestAncestor(Class<T> ancestorClass) {
return ancestorClass.cast(this.findNearestAncestor(ancestorClass::isInstance));
}
boolean hasAncestor(Predicate<? super ViewComponent> matching);
default <T extends ViewComponent> boolean hasAncestor(
Class<T> ancestorClass,
Predicate<? super ViewComponent> matching
) {
return this.hasAncestor(matching.and(ancestorClass::isInstance));
}
default <T extends ViewComponent> boolean hasAncestor(Class<T> ancestorClass) {
return this.hasAncestor(ancestorClass::isInstance);
}
List<ViewComponent> getAllAncestors();
}

View File

@ -79,6 +79,19 @@ public class DefaultComponentContext implements ComponentContext {
return null;
}
@Override
public boolean hasAncestor(Predicate<? super ViewComponent> matching) {
final List<ViewComponent> componentStack = this.getRenderContext().getComponentStack();
if (componentStack.size() > 1) {
for (final var ancestor : componentStack.subList(1, componentStack.size() - 1)) {
if (matching.test(ancestor)) {
return true;
}
}
}
return false;
}
@Override
public List<ViewComponent> getAllAncestors() {
final List<ViewComponent> componentStack = this.getRenderContext().getComponentStack();