import type {
ReactNodeList,
Thenable,
PendingThenable,
FulfilledThenable,
RejectedThenable,
} from 'shared/ReactTypes';
import isArray from 'shared/isArray';
import noop from 'shared/noop';
import {
getIteratorFn,
REACT_ELEMENT_TYPE,
REACT_LAZY_TYPE,
REACT_PORTAL_TYPE,
REACT_OPTIMISTIC_KEY,
} from 'shared/ReactSymbols';
import {enableOptimisticKey} from 'shared/ReactFeatureFlags';
import {checkKeyStringCoercion} from 'shared/CheckStringCoercion';
import {isValidElement, cloneAndReplaceKey} from './jsx/ReactJSXElement';
const SEPARATOR = '.';
const SUBSEPARATOR = ':';
function escape(key: string): string {
const escapeRegex = /[=:]/g;
const escaperLookup = {
'=': '=0',
':': '=2',
};
const escapedString = key.replace(escapeRegex, function (match) {
return escaperLookup[match];
});
return '$' + escapedString;
}
let didWarnAboutMaps = false;
const userProvidedKeyEscapeRegex = /\/+/g;
function escapeUserProvidedKey(text: string): string {
return text.replace(userProvidedKeyEscapeRegex, '$&/');
}
function getElementKey(element: any, index: number): string {
if (typeof element === 'object' && element !== null && element.key != null) {
if (enableOptimisticKey && element.key === REACT_OPTIMISTIC_KEY) {
if (__DEV__) {
console.error("React.Children helpers don't support optimisticKey.");
}
return index.toString(36);
}
if (__DEV__) {
checkKeyStringCoercion(element.key);
}
return escape('' + element.key);
}
return index.toString(36);
}
function resolveThenable<T>(thenable: Thenable<T>): T {
switch (thenable.status) {
case 'fulfilled': {
const fulfilledValue: T = thenable.value;
return fulfilledValue;
}
case 'rejected': {
const rejectedError = thenable.reason;
throw rejectedError;
}
default: {
if (typeof thenable.status === 'string') {
thenable.then(noop, noop);
} else {
const pendingThenable: PendingThenable<T> = (thenable: any);
pendingThenable.status = 'pending';
pendingThenable.then(
fulfilledValue => {
if (thenable.status === 'pending') {
const fulfilledThenable: FulfilledThenable<T> = (thenable: any);
fulfilledThenable.status = 'fulfilled';
fulfilledThenable.value = fulfilledValue;
}
},
(error: mixed) => {
if (thenable.status === 'pending') {
const rejectedThenable: RejectedThenable<T> = (thenable: any);
rejectedThenable.status = 'rejected';
rejectedThenable.reason = error;
}
},
);
}
switch ((thenable: Thenable<T>).status) {
case 'fulfilled': {
const fulfilledThenable: FulfilledThenable<T> = (thenable: any);
return fulfilledThenable.value;
}
case 'rejected': {
const rejectedThenable: RejectedThenable<T> = (thenable: any);
const rejectedError = rejectedThenable.reason;
throw rejectedError;
}
}
}
}
throw thenable;
}
function mapIntoArray(
children: ?ReactNodeList,
array: Array<React$Node>,
escapedPrefix: string,
nameSoFar: string,
callback: (?React$Node) => ?ReactNodeList,
): number {
const type = typeof children;
if (type === 'undefined' || type === 'boolean') {
children = null;
}
let invokeCallback = false;
if (children === null) {
invokeCallback = true;
} else {
switch (type) {
case 'bigint':
case 'string':
case 'number':
invokeCallback = true;
break;
case 'object':
switch ((children: any).$$typeof) {
case REACT_ELEMENT_TYPE:
case REACT_PORTAL_TYPE:
invokeCallback = true;
break;
case REACT_LAZY_TYPE:
const payload = (children: any)._payload;
const init = (children: any)._init;
return mapIntoArray(
init(payload),
array,
escapedPrefix,
nameSoFar,
callback,
);
}
}
}
if (invokeCallback) {
const child = children;
let mappedChild = callback(child);
const childKey =
nameSoFar === '' ? SEPARATOR + getElementKey(child, 0) : nameSoFar;
if (isArray(mappedChild)) {
let escapedChildKey = '';
if (childKey != null) {
escapedChildKey = escapeUserProvidedKey(childKey) + '/';
}
mapIntoArray(mappedChild, array, escapedChildKey, '', c => c);
} else if (mappedChild != null) {
if (isValidElement(mappedChild)) {
if (__DEV__) {
if (mappedChild.key != null) {
if (!child || child.key !== mappedChild.key) {
checkKeyStringCoercion(mappedChild.key);
}
}
}
const newChild = cloneAndReplaceKey(
mappedChild,
escapedPrefix +
(mappedChild.key != null &&
(!child || child.key !== mappedChild.key)
? escapeUserProvidedKey(
'' + mappedChild.key,
) + '/'
: '') +
childKey,
);
if (__DEV__) {
if (
nameSoFar !== '' &&
child != null &&
isValidElement(child) &&
child.key == null
) {
if (child._store && !child._store.validated) {
newChild._store.validated = 2;
}
}
}
mappedChild = newChild;
}
array.push(mappedChild);
}
return 1;
}
let child;
let nextName;
let subtreeCount = 0;
const nextNamePrefix =
nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;
if (isArray(children)) {
for (let i = 0; i < children.length; i++) {
child = children[i];
nextName = nextNamePrefix + getElementKey(child, i);
subtreeCount += mapIntoArray(
child,
array,
escapedPrefix,
nextName,
callback,
);
}
} else {
const iteratorFn = getIteratorFn(children);
if (typeof iteratorFn === 'function') {
const iterableChildren: Iterable<React$Node> & {
entries: any,
} = (children: any);
if (__DEV__) {
if (iteratorFn === iterableChildren.entries) {
if (!didWarnAboutMaps) {
console.warn(
'Using Maps as children is not supported. ' +
'Use an array of keyed ReactElements instead.',
);
}
didWarnAboutMaps = true;
}
}
const iterator = iteratorFn.call(iterableChildren);
let step;
let ii = 0;
while (!(step = iterator.next()).done) {
child = step.value;
nextName = nextNamePrefix + getElementKey(child, ii++);
subtreeCount += mapIntoArray(
child,
array,
escapedPrefix,
nextName,
callback,
);
}
} else if (type === 'object') {
if (typeof (children: any).then === 'function') {
return mapIntoArray(
resolveThenable((children: any)),
array,
escapedPrefix,
nameSoFar,
callback,
);
}
const childrenString = String((children: any));
throw new Error(
`Objects are not valid as a React child (found: ${
childrenString === '[object Object]'
? 'object with keys {' +
Object.keys((children: any)).join(', ') +
'}'
: childrenString
}). ` +
'If you meant to render a collection of children, use an array ' +
'instead.',
);
}
}
return subtreeCount;
}
type MapFunc = (child: ?React$Node, index: number) => ?ReactNodeList;
function mapChildren(
children: ?ReactNodeList,
func: MapFunc,
context: mixed,
): ?Array<React$Node> {
if (children == null) {
return children;
}
const result: Array<React$Node> = [];
let count = 0;
mapIntoArray(children, result, '', '', function (child) {
return func.call(context, child, count++);
});
return result;
}
function countChildren(children: ?ReactNodeList): number {
let n = 0;
mapChildren(children, () => {
n++;
});
return n;
}
type ForEachFunc = (child: ?React$Node) => void;
function forEachChildren(
children: ?ReactNodeList,
forEachFunc: ForEachFunc,
forEachContext: mixed,
): void {
mapChildren(
children,
function () {
forEachFunc.apply(this, arguments);
},
forEachContext,
);
}
function toArray(children: ?ReactNodeList): Array<React$Node> {
return mapChildren(children, child => child) || [];
}
function onlyChild<T>(children: T): T {
if (!isValidElement(children)) {
throw new Error(
'React.Children.only expected to receive a single React element child.',
);
}
return children;
}
export {
forEachChildren as forEach,
mapChildren as map,
countChildren as count,
onlyChild as only,
toArray,
};