diff --git a/packages/react-native/ReactCommon/react/renderer/observers/resize/ResizeObserverManager.cpp b/packages/react-native/ReactCommon/react/renderer/observers/resize/ResizeObserverManager.cpp index a6b05188a73b..40e8721c18ef 100644 --- a/packages/react-native/ReactCommon/react/renderer/observers/resize/ResizeObserverManager.cpp +++ b/packages/react-native/ReactCommon/react/renderer/observers/resize/ResizeObserverManager.cpp @@ -127,10 +127,12 @@ void ResizeObserverManager::connect( } notifyResizeObserversFunction_ = std::move(notifyResizeObserversFunction); + runtimeScheduler_ = &runtimeScheduler; + pendingWake_ = std::make_shared>(false); + shadowTreeRegistry_ = &uiManager.getShadowTreeRegistry(); runtimeScheduler.setResizeObserverDelegate(this); uiManager.registerCommitHook(*this); - shadowTreeRegistry_ = &uiManager.getShadowTreeRegistry(); commitHookRegistered_ = true; } @@ -145,7 +147,11 @@ void ResizeObserverManager::disconnect( } runtimeScheduler.setResizeObserverDelegate(nullptr); + // UIManager holds its hook mutex during dispatch; unregister takes it + // exclusively and waits for in-flight calls before these members are reset. uiManager.unregisterCommitHook(*this); + runtimeScheduler_ = nullptr; + pendingWake_.reset(); shadowTreeRegistry_ = nullptr; // May run from inside `broadcastActiveResizeObservations` (a callback can @@ -195,9 +201,8 @@ void ResizeObserverManager::shadowTreeDidCommit( affectedLayoutableNodes) noexcept { TraceSection s{"ResizeObserverManager::shadowTreeDidCommit"}; - // Runs on the commit hook (any thread), so it only collects which observed - // targets went dirty; it must not compute observations or notify JS. - // `runResizeObservations` (JS thread) does that against the latest tree. + // The commit hook only collects dirty families. Sizes are computed by the + // resize-observation rendering step on the JS thread. auto surfaceId = shadowTree.getSurfaceId(); std::unordered_set observedFamilies; @@ -223,14 +228,24 @@ void ResizeObserverManager::shadowTreeDidCommit( } } - std::unique_lock lock(dirtyFamiliesMutex_); - // Record the commit even with no dirty family, so `runResizeObservations` - // re-checks for removed targets (they aren't in `affectedLayoutableNodes`). - committedSurfaceIds_.insert(surfaceId); - if (!newlyDirtyFamilies.empty()) { + { + std::unique_lock lock(dirtyFamiliesMutex_); + // Record the commit even with no dirty family, so `runResizeObservations` + // re-checks for removed targets (they aren't in `affectedLayoutableNodes`). + committedSurfaceIds_.insert(surfaceId); + if (newlyDirtyFamilies.empty()) { + return; + } + auto& dirtyFamilies = dirtyFamiliesBySurfaceId_[surfaceId]; dirtyFamilies.insert(newlyDirtyFamilies.begin(), newlyDirtyFamilies.end()); } + + auto pendingWake = pendingWake_; + if (!pendingWake->exchange(true)) { + runtimeScheduler_->scheduleWork( + [pendingWake](jsi::Runtime&) { pendingWake->store(false); }); + } } #pragma mark - RuntimeSchedulerResizeObserverDelegate diff --git a/packages/react-native/ReactCommon/react/renderer/observers/resize/ResizeObserverManager.h b/packages/react-native/ReactCommon/react/renderer/observers/resize/ResizeObserverManager.h index 58c6fbf3438f..557cd7e9ce76 100644 --- a/packages/react-native/ReactCommon/react/renderer/observers/resize/ResizeObserverManager.h +++ b/packages/react-native/ReactCommon/react/renderer/observers/resize/ResizeObserverManager.h @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -112,6 +113,8 @@ class ResizeObserverManager final : public UIManagerCommitHook, public RuntimeSc std::mutex dirtyFamiliesMutex_; std::function notifyResizeObserversFunction_; + RuntimeScheduler *runtimeScheduler_{nullptr}; + std::shared_ptr> pendingWake_; bool commitHookRegistered_{}; // Set for the duration of `runResizeObservations`. The broadcast runs JS, diff --git a/packages/react-native/src/private/testing/fantom/specs/NativeFantom.js b/packages/react-native/src/private/testing/fantom/specs/NativeFantom.js index d4ef3a3e39ca..5b0807484325 100644 --- a/packages/react-native/src/private/testing/fantom/specs/NativeFantom.js +++ b/packages/react-native/src/private/testing/fantom/specs/NativeFantom.js @@ -84,6 +84,12 @@ interface Spec extends TurboModule { viewportOffsetY?: number, ) => RootTag; stopSurface: (surfaceId: RootTag) => void; + updateSurfaceConstraints: ( + surfaceId: RootTag, + viewportWidth: number, + viewportHeight: number, + devicePixelRatio: number, + ) => void; enqueueNativeEvent: ( shadowNode: unknown /* ShadowNode */, type: string, diff --git a/packages/react-native/src/private/webapis/resizeobserver/__tests__/ResizeObserver-itest.js b/packages/react-native/src/private/webapis/resizeobserver/__tests__/ResizeObserver-itest.js index edb667d73ec1..b89bf9b43690 100644 --- a/packages/react-native/src/private/webapis/resizeobserver/__tests__/ResizeObserver-itest.js +++ b/packages/react-native/src/private/webapis/resizeobserver/__tests__/ResizeObserver-itest.js @@ -17,6 +17,8 @@ import type ResizeObserverSizeType from '../ResizeObserverSize'; import type {HostInstance} from 'react-native'; import {createShadowNodeReferenceCountingRef} from '../../../__tests__/utilities/ShadowNodeReferenceCounter'; +// Queue-idle assertions have no public Fantom wrapper. +import NativeFantom from '../../../testing/fantom/specs/NativeFantom'; import * as Fantom from '@react-native/fantom'; import nullthrows from 'nullthrows'; import * as React from 'react'; @@ -1561,6 +1563,339 @@ describe('ResizeObserver', () => { }); }); + describe('native layout updates', () => { + it('should not enqueue a wake when a native commit has no dirty observed family', () => { + const nodeRef = createRef(); + const root = Fantom.createRoot({viewportWidth: 100, viewportHeight: 80}); + const callback = jest.fn(); + Fantom.runTask(() => { + root.render( + + + , + ); + }); + const node = nullthrows(nodeRef.current); + Fantom.runTask(() => { + observer = new ResizeObserver(callback); + observer.observe(node); + }); + NativeFantom.validateEmptyMessageQueue(); + + Fantom.runOnUIThread(() => root.updateSurfaceConstraints(200, 160)); + NativeFantom.validateEmptyMessageQueue(); + expect(callback).toHaveBeenCalledTimes(1); + Fantom.runTask(() => { + const rect = node.getBoundingClientRect(); + expect([rect.x, rect.y, rect.width, rect.height]).toEqual([ + 0, 0, 50, 40, + ]); + }); + }); + + it('should not notify when only the observed target position changes', () => { + const nodeRef = createRef(); + const root = Fantom.createRoot({viewportWidth: 100, viewportHeight: 80}); + const callback = jest.fn(); + Fantom.runTask(() => { + root.render( + + + , + ); + }); + const node = nullthrows(nodeRef.current); + Fantom.runTask(() => { + observer = new ResizeObserver(callback); + observer.observe(node); + }); + NativeFantom.validateEmptyMessageQueue(); + Fantom.runOnUIThread(() => root.updateSurfaceConstraints(200, 160)); + Fantom.runWorkLoop(); + expect(callback).toHaveBeenCalledTimes(1); + Fantom.runTask(() => { + const rect = node.getBoundingClientRect(); + expect([rect.x, rect.y, rect.width, rect.height]).toEqual([ + 150, 120, 50, 40, + ]); + }); + }); + + it('should not notify when a native padding change preserves the observed border box', () => { + const nodeRef = createRef(); + const root = Fantom.createRoot({viewportWidth: 100, viewportHeight: 80}); + const callback = jest.fn(); + Fantom.runTask(() => { + root.render( + , + ); + }); + const node = nullthrows(nodeRef.current); + Fantom.runTask(() => { + observer = new ResizeObserver(callback); + observer.observe(node, {box: 'border-box'}); + }); + NativeFantom.validateEmptyMessageQueue(); + Fantom.runOnUIThread(() => root.updateSurfaceConstraints(200, 160)); + Fantom.runWorkLoop(); + expect(callback).toHaveBeenCalledTimes(1); + }); + + it('should wake when a native padding change resizes the observed content box', () => { + const nodeRef = createRef(); + const root = Fantom.createRoot({viewportWidth: 100, viewportHeight: 80}); + const widths: Array = []; + Fantom.runTask(() => { + root.render( + , + ); + }); + const node = nullthrows(nodeRef.current); + Fantom.runTask(() => { + observer = new ResizeObserver(entries => + widths.push(entries[0].contentRect.width), + ); + observer.observe(node); + }); + expect(widths).toEqual([80]); + Fantom.runOnUIThread(() => root.updateSurfaceConstraints(200, 160)); + expect(widths).toEqual([80]); + Fantom.runWorkLoop(); + expect(widths).toEqual([80, 60]); + }); + + it('should deliver a native resize without onLayout or an unrelated JS task', () => { + const nodeRef = createRef(); + const root = Fantom.createRoot({viewportWidth: 100, viewportHeight: 80}); + const sizes: Array<[number, number]> = []; + + Fantom.runTask(() => { + root.render( + , + ); + }); + const node = nullthrows(nodeRef.current); + Fantom.runTask(() => { + observer = new ResizeObserver(entries => { + sizes.push([ + entries[0].contentRect.width, + entries[0].contentRect.height, + ]); + }); + observer.observe(node); + }); + + Fantom.runOnUIThread(() => { + root.updateSurfaceConstraints(200, 160); + }); + expect(sizes).toEqual([[100, 80]]); + Fantom.runWorkLoop(); + expect(sizes).toEqual([ + [100, 80], + [200, 160], + ]); + }); + + it('should dispatch ResizeObserver before onLayout for a native resize', () => { + const nodeRef = createRef(); + const root = Fantom.createRoot({viewportWidth: 100, viewportHeight: 80}); + const events: Array = []; + + Fantom.runTask(() => { + root.render( + + events.push(`layout:${event.nativeEvent.layout.width}`) + } + />, + ); + }); + const node = nullthrows(nodeRef.current); + Fantom.runTask(() => { + observer = new ResizeObserver(entries => { + events.push(`resize:${entries[0].contentRect.width}`); + }); + observer.observe(node); + }); + events.length = 0; + + Fantom.runOnUIThread(() => { + root.updateSurfaceConstraints(200, 160); + }); + expect(events).toEqual([]); + Fantom.runWorkLoop(); + expect(events).toEqual(['resize:200', 'layout:200']); + }); + + it('should preserve an onLayout task queued before observation starts', () => { + const nodeRef = createRef(); + const root = Fantom.createRoot({viewportWidth: 100, viewportHeight: 80}); + const events: Array = []; + Fantom.runTask(() => { + root.render( + { + events.push(`layout:${event.nativeEvent.layout.width}`); + }} + />, + ); + }); + events.length = 0; + const node = nullthrows(nodeRef.current); + + Fantom.runOnUIThread(() => { + root.updateSurfaceConstraints(200, 160); + }); + // Register without flushing the already queued native event task. + observer = new ResizeObserver(entries => { + events.push(`resize:${entries[0].contentRect.width}`); + }); + observer.observe(node); + Fantom.runOnUIThread(() => { + root.updateSurfaceConstraints(300, 240); + }); + expect(events).toEqual([]); + Fantom.runWorkLoop(); + // Events queued before observe() retain their place in the task queue. + expect(events).toEqual(['layout:300', 'resize:300']); + }); + + it('should coalesce native resizes before dispatching onLayout', () => { + const nodeRef = createRef(); + const root = Fantom.createRoot({viewportWidth: 100, viewportHeight: 80}); + const events: Array = []; + + Fantom.runTask(() => { + root.render( + + events.push(`layout:${event.nativeEvent.layout.width}`) + } + />, + ); + }); + const node = nullthrows(nodeRef.current); + Fantom.runTask(() => { + observer = new ResizeObserver(entries => { + events.push(`resize:${entries[0].contentRect.width}`); + }); + observer.observe(node); + }); + events.length = 0; + + Fantom.runOnUIThread(() => { + root.updateSurfaceConstraints(200, 160); + root.updateSurfaceConstraints(300, 240); + }); + expect(events).toEqual([]); + Fantom.runWorkLoop(); + expect(events).toEqual(['resize:300', 'layout:300']); + }); + + it('should not schedule a resize notification for an unobserved surface', () => { + const observedRef = createRef(); + const observedRoot = Fantom.createRoot(); + const otherRoot = Fantom.createRoot(); + const callback = jest.fn(); + + Fantom.runTask(() => { + observedRoot.render(); + otherRoot.render(); + }); + Fantom.runTask(() => { + observer = new ResizeObserver(callback); + observer.observe(nullthrows(observedRef.current)); + }); + expect(callback).toHaveBeenCalledTimes(1); + + Fantom.runOnUIThread(() => { + otherRoot.updateSurfaceConstraints(200, 160); + }); + expect(callback).toHaveBeenCalledTimes(1); + }); + + it('should handle reconnecting before a disconnected wake is drained', () => { + const nodeRef = createRef(); + const root = Fantom.createRoot({viewportWidth: 100, viewportHeight: 80}); + const firstCallback = jest.fn(); + const secondCallback = jest.fn(); + Fantom.runTask(() => { + root.render( + , + ); + }); + const node = nullthrows(nodeRef.current); + Fantom.runTask(() => { + observer = new ResizeObserver(firstCallback); + observer.observe(node); + }); + Fantom.runOnUIThread(() => { + root.updateSurfaceConstraints(200, 160); + }); + observer.disconnect(); + // Reconnect while the previous connection's wake is still queued. + observer = new ResizeObserver(secondCallback); + observer.observe(node); + Fantom.runOnUIThread(() => { + root.updateSurfaceConstraints(300, 240); + }); + Fantom.runWorkLoop(); + expect(firstCallback).toHaveBeenCalledTimes(1); + expect(secondCallback).toHaveBeenCalledTimes(1); + expect(secondCallback.mock.lastCall[0][0].contentRect.width).toBe(300); + }); + + it('should discard a queued resize after disconnect and allow reconnecting', () => { + const nodeRef = createRef(); + const root = Fantom.createRoot({viewportWidth: 100, viewportHeight: 80}); + const sizes: Array = []; + + Fantom.runTask(() => { + root.render( + , + ); + }); + const node = nullthrows(nodeRef.current); + Fantom.runTask(() => { + observer = new ResizeObserver(entries => + sizes.push(entries[0].contentRect.width), + ); + observer.observe(node); + }); + Fantom.runOnUIThread(() => { + root.updateSurfaceConstraints(200, 160); + }); + observer.disconnect(); + Fantom.runWorkLoop(); + expect(sizes).toEqual([100]); + + Fantom.runTask(() => observer.observe(node)); + expect(sizes).toEqual([100, 200]); + Fantom.runOnUIThread(() => { + root.updateSurfaceConstraints(300, 240); + }); + Fantom.runWorkLoop(); + expect(sizes).toEqual([100, 200, 300]); + }); + }); + describe('delivery timing', () => { it('should deliver observations before a task scheduled from the same tick', () => { const nodeRef = createRef(); diff --git a/private/react-native-fantom/__docs__/README.md b/private/react-native-fantom/__docs__/README.md index 830e6d96426d..29f428dc6f48 100644 --- a/private/react-native-fantom/__docs__/README.md +++ b/private/react-native-fantom/__docs__/README.md @@ -113,6 +113,10 @@ values. If another root is still alive and the new metrics differ from the current global dimensions, Fantom applies the new values and emits a warning. Call `root.destroy()` when a root is no longer needed. +`root.updateSurfaceConstraints(width, height)` changes native root constraints +without rendering React or flushing pending work. Use it to test root and +relative child layout when a native host resizes the surface. + Each root also uses its `fontScale` for native text and text-input measurement, including line heights and wrapping. `allowFontScaling={false}` opts a component out, and `maxFontSizeMultiplier` caps its scale. Existing roots retain their own diff --git a/private/react-native-fantom/src/__tests__/Fantom-itest.js b/private/react-native-fantom/src/__tests__/Fantom-itest.js index 211e09022d47..8f435e2356b8 100644 --- a/private/react-native-fantom/src/__tests__/Fantom-itest.js +++ b/private/react-native-fantom/src/__tests__/Fantom-itest.js @@ -50,6 +50,71 @@ function getActualViewportDimensions(root: Root): { } describe('Fantom', () => { + describe('root.updateSurfaceConstraints', () => { + it('resizes the root and percentage-sized descendants without another React render', () => { + const root = Fantom.createRoot({viewportWidth: 100, viewportHeight: 80}); + const nodeRef = createRef(); + Fantom.runTask(() => { + root.render( + , + ); + }); + const node = nullthrows(nodeRef.current); + Fantom.runTask(() => { + const documentElement = nullthrows(root.document.documentElement); + expect(documentElement.getBoundingClientRect().width).toBe(100); + expect(node.getBoundingClientRect().width).toBe(50); + }); + + root.updateSurfaceConstraints(200, 160); + Fantom.runTask(() => { + const documentElement = nullthrows(root.document.documentElement); + expect(documentElement.getBoundingClientRect().width).toBe(200); + expect(documentElement.getBoundingClientRect().height).toBe(160); + expect(node.getBoundingClientRect().width).toBe(100); + expect(node.getBoundingClientRect().height).toBe(40); + expect(nodeRef.current).toBe(node); + }); + + root.updateSurfaceConstraints(80, 40); + Fantom.runTask(() => { + const documentElement = nullthrows(root.document.documentElement); + expect(documentElement.getBoundingClientRect().width).toBe(80); + expect(documentElement.getBoundingClientRect().height).toBe(40); + expect(node.getBoundingClientRect().width).toBe(40); + expect(node.getBoundingClientRect().height).toBe(10); + }); + root.destroy(); + }); + + it('does not flush pending JS work when updating native constraints', () => { + const root = Fantom.createRoot({viewportWidth: 100, viewportHeight: 80}); + Fantom.runTask(() => root.render()); + let didRunTask = false; + Fantom.scheduleTask(() => { + didRunTask = true; + expect( + nullthrows(root.document.documentElement).getBoundingClientRect() + .width, + ).toBe(200); + }); + + root.updateSurfaceConstraints(200, 160); + expect(didRunTask).toBe(false); + Fantom.runWorkLoop(); + expect(didRunTask).toBe(true); + root.destroy(); + }); + + it('rejects resizing a destroyed root', () => { + const root = Fantom.createRoot(); + root.destroy(); + expect(() => root.updateSurfaceConstraints(200, 160)).toThrow( + 'Cannot resize a destroyed root.', + ); + }); + }); + describe('scheduleTask', () => { it('does not run task immediately', () => { let didRun = false; diff --git a/private/react-native-fantom/src/index.js b/private/react-native-fantom/src/index.js index 943472e42572..2f5711616e0e 100644 --- a/private/react-native-fantom/src/index.js +++ b/private/react-native-fantom/src/index.js @@ -184,6 +184,22 @@ class Root { return NativeFantom.takeMountingManagerLogs(this.#surfaceId); } + /** + * Changes the root's native surface constraints without rendering React, + * updating Dimensions, or flushing pending work. + */ + updateSurfaceConstraints(width: number, height: number): void { + if (this.#destroyed) { + throw new Error('Cannot resize a destroyed root.'); + } + NativeFantom.updateSurfaceConstraints( + this.#surfaceId, + width, + height, + this.#devicePixelRatio, + ); + } + destroy() { // TODO: check for leaks. NativeFantom.stopSurface(this.#surfaceId); diff --git a/private/react-native-fantom/tester/src/NativeFantom.cpp b/private/react-native-fantom/tester/src/NativeFantom.cpp index 0567b1746af1..487dbea094c7 100644 --- a/private/react-native-fantom/tester/src/NativeFantom.cpp +++ b/private/react-native-fantom/tester/src/NativeFantom.cpp @@ -60,6 +60,19 @@ void NativeFantom::stopSurface(jsi::Runtime& /*runtime*/, SurfaceId surfaceId) { appDelegate_.stopSurface(surfaceId); } +void NativeFantom::updateSurfaceConstraints( + jsi::Runtime& /*runtime*/, + SurfaceId surfaceId, + double viewportWidth, + double viewportHeight, + double devicePixelRatio) { + appDelegate_.updateSurfaceConstraints( + surfaceId, + static_cast(viewportWidth), + static_cast(viewportHeight), + static_cast(devicePixelRatio)); +} + void NativeFantom::produceFramesForDuration( jsi::Runtime& /*runtime*/, double milliseconds) { diff --git a/private/react-native-fantom/tester/src/NativeFantom.h b/private/react-native-fantom/tester/src/NativeFantom.h index b26aa851c17e..90d677146703 100644 --- a/private/react-native-fantom/tester/src/NativeFantom.h +++ b/private/react-native-fantom/tester/src/NativeFantom.h @@ -89,6 +89,13 @@ class NativeFantom : public NativeFantomCxxSpec { void stopSurface(jsi::Runtime &runtime, SurfaceId surfaceId); + void updateSurfaceConstraints( + jsi::Runtime &runtime, + SurfaceId surfaceId, + double viewportWidth, + double viewportHeight, + double devicePixelRatio); + void produceFramesForDuration(jsi::Runtime &runtime, double milliseconds); void flushMessageQueue(jsi::Runtime &runtime);