Skip to content

Commit f2d860b

Browse files
committed
feat: support the IntersectionObserver scrollMargin option
Summary: `rootMargin` only dilates the root intersection rectangle, so it cannot reveal a target hidden inside an intermediate scroll container. Per spec that is `scrollMargin`'s job: it dilates the clip rect of every scrollport on the path from the root to the target, and of the root itself when the root is scrollable. Until now `scrollMargin` was explicitly rejected — the constructor threw on `'scrollMargin' in options` and the getter always threw. D117876568 (#58177) did the groundwork by adding `clipSpecifiedAncestor` and excluding the observation root from the ancestor clip walk, matching the spec's "while container is not root" loop. Per spec, only nodes with a content clip clip the target, and only scroll containers have their clip rects dilated. RN's clip walk used to clip at every node, including the target itself and `overflow: visible` ancestors (to their content bounds). That is a no-op without margins, but not with them: dilating those clips shrinks the target for negative (or mixed-sign) margins, and not dilating them lets a `visible` node re-clip content that a dilated scroll container below it revealed (e.g. the content container between two nested ScrollViews). So the walk now only clips at nodes with a content clip, only dilates scroll containers, and never dilates the measured node's own clip, since the spec starts the walk at its containing block. `overflowInset` cannot identify these nodes (it is also zero for a `visible` node whose children fit), and `react/renderer/core` cannot see Yoga styles, so `LayoutableShadowNode` gains virtual `hasContentClip()` and `isScrollContainer()` (both default `false`). `YogaLayoutableShadowNode` returns `overflow != visible` for the former and `overflow` is `hidden` or `scroll` for the latter. They're the same set today, but CSS `overflow: clip` is a content clip without being a scroll container, and `isScrollContainer()` uses an exhaustive switch so new `overflow` values must be classified explicitly. Only IntersectionObserver uses this clipping mode. Per spec, "both the scrollMargin and the rootMargin are applied to a scrollable intersection root's rectangle". The rect targets are clipped against is therefore further dilated by `scrollMargin` when the explicit root is a scroll container, with percentages resolved against the undilated root. `rootBounds` is the root intersection rectangle, which only `rootMargin` dilates, so it is unaffected. Changes: - `MarginValue` moves from `IntersectionObserver.h` to `RectangleEdges.h` (`react/renderer/core` cannot depend on `observers/intersection`), gaining `EdgeMargins` and `resolveEdgeMargins()`. This replaces the index-based `std::vector<MarginValue>` with named edges and retires `calculateRootMarginInsets`. - `LayoutInspectingPolicy` gains `std::optional<EdgeMargins> clipMargin`, applied to scroll-container ancestors only. The margins travel unresolved because percentages must resolve against each individual scrollport. - `enableOverflowClipping` only clips at nodes with a content clip. - `LayoutableShadowNode::hasContentClip()` and `isScrollContainer()`, overridden by `YogaLayoutableShadowNode`. - `IntersectionObserver` applies `scrollMargin` to a scrollable explicit root's clip rect. - `parseNormalizedRootMargin` becomes `parseNormalizedMargin`, returning `std::optional<EdgeMargins>` and shared by both options. - JS: `scrollMargin` added to `IntersectionObserverInit`, the throws are removed, and `normalizeRootMargin` becomes `normalizeMargin(value, name)` so errors name the right property. - RNTester: a prefetching example (toggle between `rootMargin` and `scrollMargin`, reporting items of a ScrollView within 500px of the viewport) showing that only `scrollMargin` can see past the ScrollView. One deviation, inherited from the existing `rootMargin` code: percentages on the vertical edges resolve against height (the spec resolves all four against width). Changelog: [GENERAL] [ADDED] - Support the `scrollMargin` option in IntersectionObserver Test Plan: New Fantom tests cover parsing and the getter, plus behaviour: revealing a target past an intermediate ScrollView, partial and insufficient margins, percentages resolved per scrollport, negative values, negative values not affecting `overflow: visible` ancestors or the target itself, `overflow: hidden` ancestors, scrollable and non-scrollable explicit roots (including combination with `rootMargin` and percentage resolution against the undilated root), nested ScrollViews, horizontal edges, the top edge after scrolling, and composition with `rootMargin` on the implicit root. ``` yarn fantom packages/react-native/src/private/webapis/intersectionobserver/ ``` All tests pass. With the C++ changes from the review fixes reverted, the negative-margin and scrollable-root tests fail, as expected. ``` yarn flow-check yarn lint ``` Clean. Manually verified the RNTester example on an iOS simulator. The `scripts/cxx-api/api-snapshots/*.api` files were taken from CI's `validate_cxx_api_snapshots` run (Doxygen 1.16.1); the only changes are the new public symbols above and the codegen'd `scrollMargin` option.
1 parent 5490f49 commit f2d860b

30 files changed

Lines changed: 1334 additions & 135 deletions

‎packages/react-native/ReactCommon/react/nativemodule/intersectionobserver/NativeIntersectionObserver.cpp‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ jsi::Object NativeIntersectionObserver::observeV2(
6363
auto thresholds = options.thresholds;
6464
auto rootThresholds = options.rootThresholds;
6565
auto rootMargin = options.rootMargin;
66+
auto scrollMargin = options.scrollMargin;
6667
auto& uiManager = getUIManagerFromRuntime(runtime);
6768

6869
intersectionObserverManager_.observe(
@@ -72,6 +73,7 @@ jsi::Object NativeIntersectionObserver::observeV2(
7273
thresholds,
7374
rootThresholds,
7475
rootMargin,
76+
scrollMargin,
7577
uiManager);
7678

7779
return tokenFromShadowNodeFamily(runtime, shadowNodeFamily);

‎packages/react-native/ReactCommon/react/nativemodule/intersectionobserver/NativeIntersectionObserver.h‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ using NativeIntersectionObserverObserveOptions = NativeIntersectionObserverNativ
3737
// rootThresholds
3838
std::optional<std::vector<Float>>,
3939
// rootMargin
40+
std::optional<std::string>,
41+
// scrollMargin
4042
std::optional<std::string>>;
4143

4244
template <>

‎packages/react-native/ReactCommon/react/renderer/components/view/YogaLayoutableShadowNode.cpp‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,23 @@ bool YogaLayoutableShadowNode::getIsLayoutClean() const {
178178
return !YGNodeIsDirty(&yogaNode_);
179179
}
180180

181+
bool YogaLayoutableShadowNode::hasContentClip() const {
182+
return YGNodeStyleGetOverflow(&yogaNode_) != YGOverflowVisible;
183+
}
184+
185+
bool YogaLayoutableShadowNode::isScrollContainer() const {
186+
// No `default`, so new `overflow` values must be classified explicitly
187+
// (-Wswitch).
188+
switch (YGNodeStyleGetOverflow(&yogaNode_)) {
189+
case YGOverflowHidden:
190+
case YGOverflowScroll:
191+
return true;
192+
case YGOverflowVisible:
193+
return false;
194+
}
195+
return false;
196+
}
197+
181198
#pragma mark - Mutating Methods
182199

183200
void YogaLayoutableShadowNode::enableMeasurement() {

‎packages/react-native/ReactCommon/react/renderer/components/view/YogaLayoutableShadowNode.h‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,10 @@ class YogaLayoutableShadowNode : public LayoutableShadowNode {
7979
void dirtyLayout() override;
8080
bool getIsLayoutClean() const override;
8181

82+
bool hasContentClip() const override;
83+
84+
bool isScrollContainer() const override;
85+
8286
/*
8387
* Computes layout using Yoga layout engine.
8488
* See `LayoutableShadowNode` for more details.

‎packages/react-native/ReactCommon/react/renderer/core/LayoutableShadowNode.cpp‎

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -181,11 +181,21 @@ LayoutMetrics LayoutableShadowNode::computeRelativeLayoutMetrics(
181181
resultFrame.origin += currentShadowNode->getContentOriginOffset(true);
182182
}
183183

184+
// Only nodes with a content clip clip their content. Clipping
185+
// `overflow: visible` nodes to their content bounds would cut off content
186+
// that a dilated (clipMargin) scroll container below them has revealed.
184187
if (policy.enableOverflowClipping &&
185-
(i != size - 1 || policy.clipSpecifiedAncestor)) {
186-
auto overflowInset = currentShadowNode->getLayoutMetrics().overflowInset;
187-
auto overflowRect = insetBy(
188-
currentFrame * currentShadowNode->getTransform(), overflowInset);
188+
(i != size - 1 || policy.clipSpecifiedAncestor) &&
189+
currentShadowNode->hasContentClip()) {
190+
auto overflowRect = currentFrame * currentShadowNode->getTransform();
191+
// Only scroll containers are dilated, and the measured node is not its
192+
// own container, so its clip is never dilated.
193+
if (policy.clipMargin.has_value() && i != 0 &&
194+
currentShadowNode->isScrollContainer()) {
195+
overflowRect = outsetBy(
196+
overflowRect,
197+
resolveEdgeMargins(*policy.clipMargin, overflowRect.size));
198+
}
189199
resultFrame = Rect::intersect(resultFrame, overflowRect);
190200
if (resultFrame.size.width == 0 && resultFrame.size.height == 0) {
191201
return EmptyLayoutMetrics;
@@ -224,6 +234,14 @@ Point LayoutableShadowNode::getContentOriginOffset(
224234
return {.x = 0, .y = 0};
225235
}
226236

237+
bool LayoutableShadowNode::hasContentClip() const {
238+
return false;
239+
}
240+
241+
bool LayoutableShadowNode::isScrollContainer() const {
242+
return false;
243+
}
244+
227245
bool LayoutableShadowNode::canBeTouchTarget() const {
228246
return false;
229247
}

‎packages/react-native/ReactCommon/react/renderer/core/LayoutableShadowNode.h‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
#include <array>
1313
#include <cmath>
1414
#include <memory>
15+
#include <optional>
1516
#include <vector>
1617

1718
#include <React/Debug.h>
@@ -42,12 +43,19 @@ class LayoutableShadowNode : public ShadowNode {
4243
struct LayoutInspectingPolicy {
4344
bool includeTransform{true};
4445
bool includeViewportOffset{false};
46+
// Clip against every node with a content clip (see hasContentClip) on the
47+
// way up from the measured node.
4548
bool enableOverflowClipping{false};
4649
// When enableOverflowClipping is true, also clip against the ancestor
4750
// passed as the reference node. IntersectionObserver sets this false:
4851
// the spec clips ancestors *until* the root, then intersects with the
4952
// rootMargin-expanded root intersection rectangle.
5053
bool clipSpecifiedAncestor{true};
54+
// When enableOverflowClipping is true, expand the clip rect of every
55+
// scroll container ancestor (see isScrollContainer) by these margins
56+
// before clipping (not the measured node's own clip). Percentages resolve
57+
// against each clip rect. This is IntersectionObserver's `scrollMargin`.
58+
std::optional<EdgeMargins> clipMargin{};
5159
};
5260

5361
using UnsharedList = std::vector<LayoutableShadowNode *>;
@@ -140,6 +148,21 @@ class LayoutableShadowNode : public ShadowNode {
140148
*/
141149
virtual Point getContentOriginOffset(bool includeTransform) const;
142150

151+
/*
152+
* Whether the node clips its content to its bounds (CSS "content clip"),
153+
* e.g. `overflow` other than `visible`.
154+
* Default implementation returns `false`.
155+
*/
156+
virtual bool hasContentClip() const;
157+
158+
/*
159+
* Whether the node is a scroll container in the CSS sense (`overflow:
160+
* hidden` or `scroll`). Every scroll container has a content clip, but not
161+
* every content clip is a scroll container (e.g. CSS `overflow: clip`).
162+
* Default implementation returns `false`.
163+
*/
164+
virtual bool isScrollContainer() const;
165+
143166
/*
144167
* Sets layout metrics for the shadow node.
145168
*/

‎packages/react-native/ReactCommon/react/renderer/graphics/RectangleEdges.h‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,40 @@ inline Rect outsetBy(const Rect &rect, const EdgeInsets &outsets) noexcept
8282
.height = rect.size.height + outsets.top + outsets.bottom}};
8383
}
8484

85+
/*
86+
* A margin value that is either an absolute length in points or a percentage
87+
* of the size it is resolved against.
88+
*/
89+
struct MarginValue {
90+
Float value{};
91+
bool isPercentage{false};
92+
93+
bool operator==(const MarginValue &rhs) const noexcept = default;
94+
};
95+
96+
/*
97+
* EdgeMargins
98+
*/
99+
using EdgeMargins = RectangleEdges<MarginValue>;
100+
101+
/*
102+
* Resolves margins into absolute insets against the given size.
103+
* Percentages on the vertical edges resolve against the height, and those on
104+
* the horizontal edges resolve against the width.
105+
*/
106+
inline EdgeInsets resolveEdgeMargins(const EdgeMargins &margins, const Size &size) noexcept
107+
{
108+
const auto resolve = [](const MarginValue &margin, Float basis) {
109+
return margin.isPercentage ? margin.value / 100.0f * basis : margin.value;
110+
};
111+
112+
return EdgeInsets{
113+
resolve(margins.left, size.width),
114+
resolve(margins.top, size.height),
115+
resolve(margins.right, size.width),
116+
resolve(margins.bottom, size.height)};
117+
}
118+
85119
} // namespace facebook::react
86120

87121
namespace std {

0 commit comments

Comments
 (0)