diff --git a/packages/react-native/Libraries/Components/View/__tests__/View-keepLayoutWhenAppendingUnchangedChildren-itest.js b/packages/react-native/Libraries/Components/View/__tests__/View-keepLayoutWhenAppendingUnchangedChildren-itest.js new file mode 100644 index 000000000000..6a564858b6d6 --- /dev/null +++ b/packages/react-native/Libraries/Components/View/__tests__/View-keepLayoutWhenAppendingUnchangedChildren-itest.js @@ -0,0 +1,218 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @fantom_flags keepLayoutWhenAppendingUnchangedChildren:* + * @fantom_flags updateRuntimeShadowNodeReferencesOnCommit:* + * @flow strict-local + * @format + */ + +import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment'; + +import type {HostInstance} from 'react-native'; + +import * as Fantom from '@react-native/fantom'; +import * as React from 'react'; +import {Text, View} from 'react-native'; + +// React rebuilds the children of an updated node by cloning it without +// children and appending them one by one. With +// `keepLayoutWhenAppendingUnchangedChildren`, the clone stays clean when the +// appended children lay out as before. These tests run with the flag off and +// on, render a sequence of updates, and check that the layout matches a fresh +// render of the last update. + +// `null` for a ref whose element is not rendered in the last update. +function rectOf(ref: { + current: HostInstance | null, +}): ?[number, number, number, number] { + if (ref.current == null) { + return null; + } + const rect = ref.current.getBoundingClientRect(); + return [rect.x, rect.y, rect.width, rect.height]; +} + +type Refs = ReadonlyArray>; + +function createRefs(count: number): Refs { + return Array.from({length: count}, () => React.createRef()); +} + +function expectSameLayoutAsFreshRender( + render: (step: number, refs: Refs) => React.MixedElement, + stepCount: number, + refCount: number, +): void { + const refs = createRefs(refCount); + const root = Fantom.createRoot(); + for (let step = 0; step < stepCount; step++) { + Fantom.runTask(() => { + root.render(render(step, refs)); + }); + } + + const freshRefs = createRefs(refCount); + const freshRoot = Fantom.createRoot(); + Fantom.runTask(() => { + freshRoot.render(render(stepCount - 1, freshRefs)); + }); + + expect(refs.map(rectOf)).toEqual(freshRefs.map(rectOf)); + + root.destroy(); + freshRoot.destroy(); +} + +// A row of `count` boxes inside two levels of containers, so that a change to +// one box rebuilds the children of every container above it. +function Boxes({ + count, + colorIndex, + wideIndex, + hidden, + refs, +}: { + count: number, + colorIndex: number, + wideIndex: number, + hidden?: boolean, + refs: Refs, +}): React.MixedElement { + return ( + +