UNPKG

2.36 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.getTextFromChildren = getTextFromChildren;
7
8var React = _interopRequireWildcard(require("react"));
9
10function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
11
12function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
13
14function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
15
16var JOINABLE_TYPES = new Set(['string', 'number']); // Checks the children of a React component to ensure every value is a number
17// or a string. If they are, they are joined and returned. Useful for collecting
18// text from the child of a node to use as an attribute.
19
20function getTextFromChildren(children) {
21 var childList = React.Children.toArray(children).filter(function (child) {
22 return child !== null && child !== undefined;
23 });
24
25 if (!childList.length) {
26 return null;
27 }
28
29 var isJoinable = childList.every(function (child) {
30 return JOINABLE_TYPES.has(_typeof(child));
31 });
32
33 if (!isJoinable) {
34 return null;
35 } // Join on an empty string to preserve React's whitespace handling:
36 // <Tag>foo{'bar'}baz</Tag> => 'foobar'
37 // <Tag>foo {'bar'} baz</Tag> => 'foo bar baz'
38
39
40 return childList.join('');
41}
\No newline at end of file