main
js 60 lines 2.14 KB
Raw
1 /**
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 *
7 * Shared logic for Fragment Ref operations for DOM and Fabric configs
8 *
9 * @flow
10 */
11
12 import type {Fiber} from 'react-reconciler/src/ReactInternalTypes';
13
14 import {getFragmentInstanceOrTextInstanceSiblings} from 'react-reconciler/src/ReactFiberTreeReflection';
15
16 export function compareDocumentPositionForEmptyFragment<TPublicInstance>(
17 fragmentFiber: Fiber,
18 parentHostInstance: TPublicInstance,
19 otherNode: TPublicInstance,
20 getPublicInstance: (fiber: Fiber) => TPublicInstance,
21 ): number {
22 let result;
23 // If the fragment has no children, we can use the parent and
24 // siblings to determine a position.
25 // $FlowFixMe[incompatible-use] Fabric PublicInstance is opaque
26 // $FlowFixMe[prop-missing]
27 const parentResult = parentHostInstance.compareDocumentPosition(otherNode);
28 result = parentResult;
29 if (parentHostInstance === otherNode) {
30 result = Node.DOCUMENT_POSITION_CONTAINS;
31 } else {
32 if (parentResult & Node.DOCUMENT_POSITION_CONTAINED_BY) {
33 // otherNode is one of the fragment's siblings. Use the next
34 // host sibling (via the parent tree, not fiber.sibling) to
35 // determine if its preceding or following.
36 const [, nextSiblingFiber] =
37 getFragmentInstanceOrTextInstanceSiblings(fragmentFiber);
38 if (nextSiblingFiber === null) {
39 result = Node.DOCUMENT_POSITION_PRECEDING;
40 } else {
41 const nextSiblingInstance = getPublicInstance(nextSiblingFiber);
42 const nextSiblingResult =
43 // $FlowFixMe[incompatible-use] Fabric PublicInstance is opaque
44 // $FlowFixMe[prop-missing]
45 nextSiblingInstance.compareDocumentPosition(otherNode);
46 if (
47 nextSiblingResult === 0 ||
48 nextSiblingResult & Node.DOCUMENT_POSITION_FOLLOWING
49 ) {
50 result = Node.DOCUMENT_POSITION_FOLLOWING;
51 } else {
52 result = Node.DOCUMENT_POSITION_PRECEDING;
53 }
54 }
55 }
56 }
57
58 result |= Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC;
59 return result;
60 }