UNPKG

2.63 kBJavaScriptView Raw
1/**
2 * Copyright (c) 2013-present, Facebook, Inc.
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 *
8 */
9
10'use strict';
11
12var KeyEscapeUtils = require('./KeyEscapeUtils');
13var traverseAllChildren = require('./traverseAllChildren');
14var warning = require('fbjs/lib/warning');
15
16var ReactComponentTreeHook;
17
18if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test') {
19 // Temporary hack.
20 // Inline requires don't work well with Jest:
21 // https://github.com/facebook/react/issues/7240
22 // Remove the inline requires when we don't need them anymore:
23 // https://github.com/facebook/react/pull/7178
24 ReactComponentTreeHook = require('./ReactComponentTreeHook');
25}
26
27/**
28 * @param {function} traverseContext Context passed through traversal.
29 * @param {?ReactComponent} child React child component.
30 * @param {!string} name String name of key path to child.
31 * @param {number=} selfDebugID Optional debugID of the current internal instance.
32 */
33function flattenSingleChildIntoContext(traverseContext, child, name, selfDebugID) {
34 // We found a component instance.
35 if (traverseContext && typeof traverseContext === 'object') {
36 var result = traverseContext;
37 var keyUnique = result[name] === undefined;
38 if (process.env.NODE_ENV !== 'production') {
39 if (!ReactComponentTreeHook) {
40 ReactComponentTreeHook = require('./ReactComponentTreeHook');
41 }
42 if (!keyUnique) {
43 process.env.NODE_ENV !== 'production' ? warning(false, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.%s', KeyEscapeUtils.unescape(name), ReactComponentTreeHook.getStackAddendumByID(selfDebugID)) : void 0;
44 }
45 }
46 if (keyUnique && child != null) {
47 result[name] = child;
48 }
49 }
50}
51
52/**
53 * Flattens children that are typically specified as `props.children`. Any null
54 * children will not be included in the resulting object.
55 * @return {!object} flattened children keyed by name.
56 */
57function flattenChildren(children, selfDebugID) {
58 if (children == null) {
59 return children;
60 }
61 var result = {};
62
63 if (process.env.NODE_ENV !== 'production') {
64 traverseAllChildren(children, function (traverseContext, child, name) {
65 return flattenSingleChildIntoContext(traverseContext, child, name, selfDebugID);
66 }, result);
67 } else {
68 traverseAllChildren(children, flattenSingleChildIntoContext, result);
69 }
70 return result;
71}
72
73module.exports = flattenChildren;
\No newline at end of file