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))); 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(); List<ViewComponent> getAllAncestors();
} }

View File

@ -70,7 +70,7 @@ public class DefaultComponentContext implements ComponentContext {
public @Nullable ViewComponent findNearestAncestor(Predicate<? super ViewComponent> matching) { public @Nullable ViewComponent findNearestAncestor(Predicate<? super ViewComponent> matching) {
final List<ViewComponent> componentStack = this.getRenderContext().getComponentStack(); final List<ViewComponent> componentStack = this.getRenderContext().getComponentStack();
if (componentStack.size() > 1) { if (componentStack.size() > 1) {
for (final var ancestor : componentStack.subList(1, componentStack.size() -1)) { for (final var ancestor : componentStack.subList(1, componentStack.size() - 1)) {
if (matching.test(ancestor)) { if (matching.test(ancestor)) {
return ancestor; return ancestor;
} }
@ -79,6 +79,19 @@ public class DefaultComponentContext implements ComponentContext {
return null; 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 @Override
public List<ViewComponent> getAllAncestors() { public List<ViewComponent> getAllAncestors() {
final List<ViewComponent> componentStack = this.getRenderContext().getComponentStack(); final List<ViewComponent> componentStack = this.getRenderContext().getComponentStack();