UNPKG

lucid-ui

Version:

A UI component library from AppNexus.

85 lines (75 loc) 2.15 kB
import _escapeRegExp from "lodash/escapeRegExp"; import _find from "lodash/find"; import _has from "lodash/has"; import _isString from "lodash/isString"; import React from 'react'; /** * Performs a regex search and returns a partitioning around the matching substring: [pre, match, post] * * @param text: string to search * @param pattern: RegExp patten * @param length (optional): provide a max length for the matching substring * * @return string[] */ export function partitionText(text, pattern, length) { var index; if (length) { index = text.search(pattern); } else { var result = pattern.exec(text); if (result) { length = result[0].length; index = result.index; } else { length = 0; index = -1; } } if (index === -1) { return ['', '', text]; } else if (index === 0) { return ['', text.substr(0, length), text.substring(length)]; } else { return [text.substring(0, index), text.substr(index, length), text.substring(index + length)]; } } /** * Returns the combined text of all descendant strings * * @param node: a component props object * * @return string */ export function getCombinedChildText(node) { if (!node || !node.children) { return ''; } if (_isString(node.children)) { return node.children; } return React.Children.toArray(node.children).filter(function (child) { return _has(child, 'props'); }) // filter out primitive types .map(function (child) { return getCombinedChildText(child.props); }).reduce(function (combinedText, childText) { return combinedText + childText; }, _find(React.Children.toArray(node.children), _isString) || ''); } /** * Perform a regex search on all text found in a component's descendants * * @param text * @param node * * @return boolean */ export function propsSearch() { var text = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; var node = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; if (!text) { return true; } return new RegExp(_escapeRegExp(text), 'i').test(getCombinedChildText(node)); }