UNPKG

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