From e2bb415dfc071f46ddbdaedea98c7c22e87cbbf2 Mon Sep 17 00:00:00 2001 From: Maarten Veenstra Date: Wed, 19 Apr 2023 08:49:38 +0200 Subject: [PATCH] attach Interaction Observer to first visible child (handle 'display: contents') --- src/index.tsx | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/index.tsx b/src/index.tsx index 9ae22b2..1d5c5f5 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -27,6 +27,21 @@ function reducer() { return true; } +// find a visible node to observe +// NOTE: this just checks the first child at each level +function getFirstVisibleChild(el) { + const child = el.firstElementChild; + if (child) { + const style = getComputedStyle(child); + // element might contain visible children + if (!["contents"].includes(style.display)) { + return child; + } + + return getFirstVisibleChild(child); + } + return child; +} function LazyHydrate(props: Props) { const childRef = React.useRef(null); @@ -92,7 +107,7 @@ function LazyHydrate(props: Props) { const element = noWrapper ? rootElement : // As root node does not have any box model, it cannot intersect. - rootElement.firstElementChild; + getFirstVisibleChild(rootElement); if (element && typeof IntersectionObserver !== "undefined") { const observerOptions =