react-highlighter-ts
Version:
a TypeScript rewrite of the package react-highlighter
73 lines • 2.94 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.deepMap = exports.removeDiacritics = exports.getSearch = exports.getMatchBoundaries = void 0;
const react_1 = require("react");
/**
* Get the indexes of the first and last characters of the matched string.
*/
function getMatchBoundaries(subject, search) {
const matches = search.exec(subject);
if (matches) {
return {
first: matches.index,
last: matches.index + matches[0].length,
};
}
}
exports.getMatchBoundaries = getMatchBoundaries;
/**
* Get the search prop, but always in the form of a regular expression. Use
* this as a proxy to search for consistency.
*/
function getSearch(props) {
const { search, ignoreDiacritics, diacriticsBlacklist, caseSensitive, } = props;
if (search instanceof RegExp) {
return search;
}
let s = escapeStringRegexp(search);
if (ignoreDiacritics) {
s = (0, exports.removeDiacritics)(s, diacriticsBlacklist);
}
return new RegExp(s, caseSensitive ? "" : "i");
}
exports.getSearch = getSearch;
const removeDiacritics = (s, blacklist) => {
if (!String.prototype.normalize) {
// Fall back to original string
return s;
}
if (!blacklist) {
// No blacklist, just remove all
return s.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
}
else {
const blacklistChars = blacklist.split("");
// Remove all diacritics that are not a part of a blacklisted character
// First char cannot be a diacritic
return s.normalize("NFD").replace(/.[\u0300-\u036f]+/g, function (m) {
return blacklistChars.indexOf(m.normalize()) > -1 ? m.normalize() : m[0];
});
}
};
exports.removeDiacritics = removeDiacritics;
const escapeStringRegexp = (s) => s ? s.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&").replace(/-/g, "\\x2d") : "";
/**
* Borrowed from https://github.com/fernandopasik/react-children-utilities/blob/9720f5fcc3f7cb46fa81909780d97356c201c041/src/lib/hasChildren.ts
*/
const hasChildren = (element) => (0, react_1.isValidElement)(element) &&
Boolean(element.props.children);
/**
* Borrowed from https://github.com/fernandopasik/react-children-utilities/blob/9720f5fcc3f7cb46fa81909780d97356c201c041/src/lib/deepMap.ts
*/
const deepMap = (children, deepMapFn) => {
return react_1.Children.toArray(children).map((child, index, mapChildren) => {
if ((0, react_1.isValidElement)(child) && hasChildren(child)) {
// Clone the child that has children and map them too
return deepMapFn((0, react_1.cloneElement)(child, Object.assign(Object.assign({}, child.props), { children: (0, exports.deepMap)(child.props.children, deepMapFn) })));
}
return deepMapFn(child, index, mapChildren);
});
};
exports.deepMap = deepMap;
exports.default = exports.deepMap;
//# sourceMappingURL=helpers.js.map