package/package.json000644 0000003026 3560116604 011547 0ustar00000000 000000 { "name": "highlight-words-core", "description": "Utility functions shared by react-highlight-words and react-native-highlight-words", "version": "1.2.2", "author": "Brian Vaughn ", "license": "MIT", "main": "dist/index.js", "scripts": { "build": "yarn build:source && yarn build:flow", "build:flow": "cp flow-template dist/index.js.flow", "build:source": "webpack --config webpack.config.dist.js --bail", "lint": "standard", "prebuild": "rimraf dist", "prepublish": "npm run build", "test": "mocha --compilers js:babel-register \"src/**/*.test.js\"" }, "files": [ "dist", "src/*.js" ], "keywords": [ "highlighter", "highlight", "text", "words", "matches", "substring", "occurrences", "search" ], "repository": { "type": "git", "url": "github.com/bvaughn/highlight-words-core.git" }, "standard": { "parser": "babel-eslint", "ignore": [ "build", "dist", "node_modules" ], "global": [ "afterAll", "afterEach", "beforeAll", "beforeEach", "describe", "it" ] }, "devDependencies": { "babel-cli": "6.8.0", "babel-core": "^6.5.1", "babel-eslint": "^6.0.4", "babel-loader": "^6.2.3", "babel-preset-es2015": "^6.14.0", "babel-preset-flow": "^6", "cross-env": "^1.0.7", "expect.js": "^0.3.1", "latinize": "^0.3.0", "mocha": "^3.0.2", "rimraf": "^2.4.3", "standard": "^7.0.1", "webpack": "^1.9.6" } } package/LICENSE000644 0000002071 3560116604 010265 0ustar00000000 000000 The MIT License (MIT) Copyright (c) 2015 Treasure Data Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. package/README.md000644 0000003500 3560116604 010535 0ustar00000000 000000 Utility functions shared by [`react-highlight-words`](https://github.com/bvaughn/react-highlight-words) and [`react-native-highlight-words`](https://github.com/clauderic/react-native-highlight-words). ## API The primary API for this package is a function exported as `findAll`. This method searches a string of text for a set of search terms and returns an array of "chunks" that describe the matches found. Each "chunk" is an object consisting of a pair of indices (`chunk.start` and `chunk.end`) and a boolean specfifying whether the chunk is a match (`chunk.highlight`). For example: ```js import { findAll } from "highlight-words-core"; const textToHighlight = "This is some text to highlight."; const searchWords = ["This", "i"]; const chunks = findAll({ searchWords, textToHighlight }); const highlightedText = chunks .map(chunk => { const { end, highlight, start } = chunk; const text = textToHighlight.substr(start, end - start); if (highlight) { return `${text}`; } else { return text; } }) .join(""); ``` [Run this example on Code Sandbox.](https://codesandbox.io/s/ykwrzrl6wx) ### `findAll` The `findAll` function accepts several parameters, although only the `searchWords` array and `textToHighlight` string are required. | Parameter | Required? | Type | Description | | --- | :---: | --- | --- | | autoEscape | | `boolean` | Escape special regular expression characters | | caseSensitive | | `boolean` | Search should be case sensitive | | findChunks | | `Function` | Custom find function (advanced) | | sanitize | | `Function` | Custom sanitize function (advanced) | | searchWords | ✅ | `Array` | Array of words to search for | | textToHighlight | ✅ | `string` | Text to search and highlight | ## License MIT License - fork, modify and use however you want. package/dist/index.js000644 0000016736 3560116604 011705 0ustar00000000 000000 module.exports = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(1); /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _utils = __webpack_require__(2); Object.defineProperty(exports, 'combineChunks', { enumerable: true, get: function get() { return _utils.combineChunks; } }); Object.defineProperty(exports, 'fillInChunks', { enumerable: true, get: function get() { return _utils.fillInChunks; } }); Object.defineProperty(exports, 'findAll', { enumerable: true, get: function get() { return _utils.findAll; } }); Object.defineProperty(exports, 'findChunks', { enumerable: true, get: function get() { return _utils.findChunks; } }); /***/ }), /* 2 */ /***/ (function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); /** * Creates an array of chunk objects representing both higlightable and non highlightable pieces of text that match each search word. * @return Array of "chunks" (where a Chunk is { start:number, end:number, highlight:boolean }) */ var findAll = exports.findAll = function findAll(_ref) { var autoEscape = _ref.autoEscape, _ref$caseSensitive = _ref.caseSensitive, caseSensitive = _ref$caseSensitive === undefined ? false : _ref$caseSensitive, _ref$findChunks = _ref.findChunks, findChunks = _ref$findChunks === undefined ? defaultFindChunks : _ref$findChunks, sanitize = _ref.sanitize, searchWords = _ref.searchWords, textToHighlight = _ref.textToHighlight; return fillInChunks({ chunksToHighlight: combineChunks({ chunks: findChunks({ autoEscape: autoEscape, caseSensitive: caseSensitive, sanitize: sanitize, searchWords: searchWords, textToHighlight: textToHighlight }) }), totalLength: textToHighlight ? textToHighlight.length : 0 }); }; /** * Takes an array of {start:number, end:number} objects and combines chunks that overlap into single chunks. * @return {start:number, end:number}[] */ var combineChunks = exports.combineChunks = function combineChunks(_ref2) { var chunks = _ref2.chunks; chunks = chunks.sort(function (first, second) { return first.start - second.start; }).reduce(function (processedChunks, nextChunk) { // First chunk just goes straight in the array... if (processedChunks.length === 0) { return [nextChunk]; } else { // ... subsequent chunks get checked to see if they overlap... var prevChunk = processedChunks.pop(); if (nextChunk.start <= prevChunk.end) { // It may be the case that prevChunk completely surrounds nextChunk, so take the // largest of the end indeces. var endIndex = Math.max(prevChunk.end, nextChunk.end); processedChunks.push({ highlight: false, start: prevChunk.start, end: endIndex }); } else { processedChunks.push(prevChunk, nextChunk); } return processedChunks; } }, []); return chunks; }; /** * Examine text for any matches. * If we find matches, add them to the returned array as a "chunk" object ({start:number, end:number}). * @return {start:number, end:number}[] */ var defaultFindChunks = function defaultFindChunks(_ref3) { var autoEscape = _ref3.autoEscape, caseSensitive = _ref3.caseSensitive, _ref3$sanitize = _ref3.sanitize, sanitize = _ref3$sanitize === undefined ? defaultSanitize : _ref3$sanitize, searchWords = _ref3.searchWords, textToHighlight = _ref3.textToHighlight; textToHighlight = sanitize(textToHighlight); return searchWords.filter(function (searchWord) { return searchWord; }) // Remove empty words .reduce(function (chunks, searchWord) { searchWord = sanitize(searchWord); if (autoEscape) { searchWord = escapeRegExpFn(searchWord); } var regex = new RegExp(searchWord, caseSensitive ? 'g' : 'gi'); var match = void 0; while (match = regex.exec(textToHighlight)) { var _start = match.index; var _end = regex.lastIndex; // We do not return zero-length matches if (_end > _start) { chunks.push({ highlight: false, start: _start, end: _end }); } // Prevent browsers like Firefox from getting stuck in an infinite loop // See http://www.regexguru.com/2008/04/watch-out-for-zero-length-matches/ if (match.index === regex.lastIndex) { regex.lastIndex++; } } return chunks; }, []); }; // Allow the findChunks to be overridden in findAll, // but for backwards compatibility we export as the old name exports.findChunks = defaultFindChunks; /** * Given a set of chunks to highlight, create an additional set of chunks * to represent the bits of text between the highlighted text. * @param chunksToHighlight {start:number, end:number}[] * @param totalLength number * @return {start:number, end:number, highlight:boolean}[] */ var fillInChunks = exports.fillInChunks = function fillInChunks(_ref4) { var chunksToHighlight = _ref4.chunksToHighlight, totalLength = _ref4.totalLength; var allChunks = []; var append = function append(start, end, highlight) { if (end - start > 0) { allChunks.push({ start: start, end: end, highlight: highlight }); } }; if (chunksToHighlight.length === 0) { append(0, totalLength, false); } else { var lastIndex = 0; chunksToHighlight.forEach(function (chunk) { append(lastIndex, chunk.start, false); append(chunk.start, chunk.end, true); lastIndex = chunk.end; }); append(lastIndex, totalLength, false); } return allChunks; }; function defaultSanitize(string) { return string; } function escapeRegExpFn(string) { return string.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'); } /***/ }) /******/ ]); //# sourceMappingURL=index.js.mappackage/dist/index.js.flow000644 0000000041 3560116604 012631 0ustar00000000 000000 // @flow export * from '../src';package/dist/index.js.map000644 0000024030 3560116604 012443 0ustar00000000 000000 {"version":3,"sources":["webpack:///webpack/bootstrap 2a95070affdf3c0054f1","webpack:///./src/index.js","webpack:///./src/utils.js"],"names":["combineChunks","fillInChunks","findAll","findChunks","autoEscape","caseSensitive","defaultFindChunks","sanitize","searchWords","textToHighlight","chunksToHighlight","chunks","totalLength","length","sort","first","second","start","reduce","processedChunks","nextChunk","prevChunk","pop","end","endIndex","Math","max","push","highlight","defaultSanitize","filter","searchWord","escapeRegExpFn","regex","RegExp","match","exec","index","lastIndex","allChunks","append","forEach","chunk","string","replace"],"mappings":";;AAAA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,uBAAe;AACf;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;;;;;;;;;;;;;;;;;;;;;;;;mBCp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,YAAO3B,MAAP;AACD,IA5BI,EA4BF,EA5BE,CAAP;AA6BD,EA5CD;AA6CA;AACA;SAC6BR,U,GAArBG,iB;;AAER;;;;;;;;AAOO,KAAML,sCAAe,SAAfA,YAAe,QAMR;AAAA,OALlBS,iBAKkB,SALlBA,iBAKkB;AAAA,OAJlBE,WAIkB,SAJlBA,WAIkB;;AAClB,OAAM2B,YAAY,EAAlB;AACA,OAAMC,SAAS,SAATA,MAAS,CAACvB,KAAD,EAAQM,GAAR,EAAaK,SAAb,EAA2B;AACxC,SAAIL,MAAMN,KAAN,GAAc,CAAlB,EAAqB;AACnBsB,iBAAUZ,IAAV,CAAe;AACbV,qBADa;AAEbM,iBAFa;AAGbK;AAHa,QAAf;AAKD;AACF,IARD;;AAUA,OAAIlB,kBAAkBG,MAAlB,KAA6B,CAAjC,EAAoC;AAClC2B,YAAO,CAAP,EAAU5B,WAAV,EAAuB,KAAvB;AACD,IAFD,MAEO;AACL,SAAI0B,YAAY,CAAhB;AACA5B,uBAAkB+B,OAAlB,CAA0B,UAACC,KAAD,EAAW;AACnCF,cAAOF,SAAP,EAAkBI,MAAMzB,KAAxB,EAA+B,KAA/B;AACAuB,cAAOE,MAAMzB,KAAb,EAAoByB,MAAMnB,GAA1B,EAA+B,IAA/B;AACAe,mBAAYI,MAAMnB,GAAlB;AACD,MAJD;AAKAiB,YAAOF,SAAP,EAAkB1B,WAAlB,EAA+B,KAA/B;AACD;AACD,UAAO2B,SAAP;AACD,EA9BM;;AAgCP,UAASV,eAAT,CAA0Bc,MAA1B,EAAkD;AAChD,UAAOA,MAAP;AACD;;AAED,UAASX,cAAT,CAAyBW,MAAzB,EAAiD;AAC/C,UAAOA,OAAOC,OAAP,CAAe,qCAAf,EAAsD,MAAtD,CAAP;AACD,E","file":"index.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\texports: {},\n \t\t\tid: moduleId,\n \t\t\tloaded: false\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.loaded = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(0);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap 2a95070affdf3c0054f1","// @flow\n\nexport { combineChunks, fillInChunks, findAll, findChunks } from './utils'\n\n\n\n// WEBPACK FOOTER //\n// ./src/index.js","// @flow\n\nexport type Chunk = {|\n highlight: boolean,\n start: number,\n end: number,\n|};\n\n/**\n * Creates an array of chunk objects representing both higlightable and non highlightable pieces of text that match each search word.\n * @return Array of \"chunks\" (where a Chunk is { start:number, end:number, highlight:boolean })\n */\nexport const findAll = ({\n autoEscape,\n caseSensitive = false,\n findChunks = defaultFindChunks,\n sanitize,\n searchWords,\n textToHighlight\n}: {\n autoEscape?: boolean,\n caseSensitive?: boolean,\n findChunks?: typeof defaultFindChunks,\n sanitize?: typeof defaultSanitize,\n searchWords: Array,\n textToHighlight: string,\n}): Array => (\n fillInChunks({\n chunksToHighlight: combineChunks({\n chunks: findChunks({\n autoEscape,\n caseSensitive,\n sanitize,\n searchWords,\n textToHighlight\n })\n }),\n totalLength: textToHighlight ? textToHighlight.length : 0\n })\n)\n\n/**\n * Takes an array of {start:number, end:number} objects and combines chunks that overlap into single chunks.\n * @return {start:number, end:number}[]\n */\nexport const combineChunks = ({\n chunks\n}: {\n chunks: Array,\n}): Array => {\n chunks = chunks\n .sort((first, second) => first.start - second.start)\n .reduce((processedChunks, nextChunk) => {\n // First chunk just goes straight in the array...\n if (processedChunks.length === 0) {\n return [nextChunk]\n } else {\n // ... subsequent chunks get checked to see if they overlap...\n const prevChunk = processedChunks.pop()\n if (nextChunk.start <= prevChunk.end) {\n // It may be the case that prevChunk completely surrounds nextChunk, so take the\n // largest of the end indeces.\n const endIndex = Math.max(prevChunk.end, nextChunk.end)\n processedChunks.push({highlight: false, start: prevChunk.start, end: endIndex})\n } else {\n processedChunks.push(prevChunk, nextChunk)\n }\n return processedChunks\n }\n }, [])\n\n return chunks\n}\n\n/**\n * Examine text for any matches.\n * If we find matches, add them to the returned array as a \"chunk\" object ({start:number, end:number}).\n * @return {start:number, end:number}[]\n */\nconst defaultFindChunks = ({\n autoEscape,\n caseSensitive,\n sanitize = defaultSanitize,\n searchWords,\n textToHighlight\n}: {\n autoEscape?: boolean,\n caseSensitive?: boolean,\n sanitize?: typeof defaultSanitize,\n searchWords: Array,\n textToHighlight: string,\n}): Array => {\n textToHighlight = sanitize(textToHighlight)\n\n return searchWords\n .filter(searchWord => searchWord) // Remove empty words\n .reduce((chunks, searchWord) => {\n searchWord = sanitize(searchWord)\n\n if (autoEscape) {\n searchWord = escapeRegExpFn(searchWord)\n }\n\n const regex = new RegExp(searchWord, caseSensitive ? 'g' : 'gi')\n\n let match\n while ((match = regex.exec(textToHighlight))) {\n let start = match.index\n let end = regex.lastIndex\n // We do not return zero-length matches\n if (end > start) {\n chunks.push({highlight: false, start, end})\n }\n\n // Prevent browsers like Firefox from getting stuck in an infinite loop\n // See http://www.regexguru.com/2008/04/watch-out-for-zero-length-matches/\n if (match.index === regex.lastIndex) {\n regex.lastIndex++\n }\n }\n\n return chunks\n }, [])\n}\n// Allow the findChunks to be overridden in findAll,\n// but for backwards compatibility we export as the old name\nexport {defaultFindChunks as findChunks}\n\n/**\n * Given a set of chunks to highlight, create an additional set of chunks\n * to represent the bits of text between the highlighted text.\n * @param chunksToHighlight {start:number, end:number}[]\n * @param totalLength number\n * @return {start:number, end:number, highlight:boolean}[]\n */\nexport const fillInChunks = ({\n chunksToHighlight,\n totalLength\n}: {\n chunksToHighlight: Array,\n totalLength: number,\n}): Array => {\n const allChunks = []\n const append = (start, end, highlight) => {\n if (end - start > 0) {\n allChunks.push({\n start,\n end,\n highlight\n })\n }\n }\n\n if (chunksToHighlight.length === 0) {\n append(0, totalLength, false)\n } else {\n let lastIndex = 0\n chunksToHighlight.forEach((chunk) => {\n append(lastIndex, chunk.start, false)\n append(chunk.start, chunk.end, true)\n lastIndex = chunk.end\n })\n append(lastIndex, totalLength, false)\n }\n return allChunks\n}\n\nfunction defaultSanitize (string: string): string {\n return string\n}\n\nfunction escapeRegExpFn (string: string): string {\n return string.replace(/[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\\\^\\$\\|]/g, '\\\\$&')\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils.js"],"sourceRoot":""}package/src/index.js000644 0000000125 3560116604 011512 0ustar00000000 000000 // @flow export { combineChunks, fillInChunks, findAll, findChunks } from './utils' package/src/utils.js000644 0000011301 3560116604 011541 0ustar00000000 000000 // @flow export type Chunk = {| highlight: boolean, start: number, end: number, |}; /** * Creates an array of chunk objects representing both higlightable and non highlightable pieces of text that match each search word. * @return Array of "chunks" (where a Chunk is { start:number, end:number, highlight:boolean }) */ export const findAll = ({ autoEscape, caseSensitive = false, findChunks = defaultFindChunks, sanitize, searchWords, textToHighlight }: { autoEscape?: boolean, caseSensitive?: boolean, findChunks?: typeof defaultFindChunks, sanitize?: typeof defaultSanitize, searchWords: Array, textToHighlight: string, }): Array => ( fillInChunks({ chunksToHighlight: combineChunks({ chunks: findChunks({ autoEscape, caseSensitive, sanitize, searchWords, textToHighlight }) }), totalLength: textToHighlight ? textToHighlight.length : 0 }) ) /** * Takes an array of {start:number, end:number} objects and combines chunks that overlap into single chunks. * @return {start:number, end:number}[] */ export const combineChunks = ({ chunks }: { chunks: Array, }): Array => { chunks = chunks .sort((first, second) => first.start - second.start) .reduce((processedChunks, nextChunk) => { // First chunk just goes straight in the array... if (processedChunks.length === 0) { return [nextChunk] } else { // ... subsequent chunks get checked to see if they overlap... const prevChunk = processedChunks.pop() if (nextChunk.start <= prevChunk.end) { // It may be the case that prevChunk completely surrounds nextChunk, so take the // largest of the end indeces. const endIndex = Math.max(prevChunk.end, nextChunk.end) processedChunks.push({highlight: false, start: prevChunk.start, end: endIndex}) } else { processedChunks.push(prevChunk, nextChunk) } return processedChunks } }, []) return chunks } /** * Examine text for any matches. * If we find matches, add them to the returned array as a "chunk" object ({start:number, end:number}). * @return {start:number, end:number}[] */ const defaultFindChunks = ({ autoEscape, caseSensitive, sanitize = defaultSanitize, searchWords, textToHighlight }: { autoEscape?: boolean, caseSensitive?: boolean, sanitize?: typeof defaultSanitize, searchWords: Array, textToHighlight: string, }): Array => { textToHighlight = sanitize(textToHighlight) return searchWords .filter(searchWord => searchWord) // Remove empty words .reduce((chunks, searchWord) => { searchWord = sanitize(searchWord) if (autoEscape) { searchWord = escapeRegExpFn(searchWord) } const regex = new RegExp(searchWord, caseSensitive ? 'g' : 'gi') let match while ((match = regex.exec(textToHighlight))) { let start = match.index let end = regex.lastIndex // We do not return zero-length matches if (end > start) { chunks.push({highlight: false, start, end}) } // Prevent browsers like Firefox from getting stuck in an infinite loop // See http://www.regexguru.com/2008/04/watch-out-for-zero-length-matches/ if (match.index === regex.lastIndex) { regex.lastIndex++ } } return chunks }, []) } // Allow the findChunks to be overridden in findAll, // but for backwards compatibility we export as the old name export {defaultFindChunks as findChunks} /** * Given a set of chunks to highlight, create an additional set of chunks * to represent the bits of text between the highlighted text. * @param chunksToHighlight {start:number, end:number}[] * @param totalLength number * @return {start:number, end:number, highlight:boolean}[] */ export const fillInChunks = ({ chunksToHighlight, totalLength }: { chunksToHighlight: Array, totalLength: number, }): Array => { const allChunks = [] const append = (start, end, highlight) => { if (end - start > 0) { allChunks.push({ start, end, highlight }) } } if (chunksToHighlight.length === 0) { append(0, totalLength, false) } else { let lastIndex = 0 chunksToHighlight.forEach((chunk) => { append(lastIndex, chunk.start, false) append(chunk.start, chunk.end, true) lastIndex = chunk.end }) append(lastIndex, totalLength, false) } return allChunks } function defaultSanitize (string: string): string { return string } function escapeRegExpFn (string: string): string { return string.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&') } package/src/utils.test.js000644 0000007667 3560116604 012543 0ustar00000000 000000 import * as Chunks from './utils.js' import expect from 'expect.js' import latinize from 'latinize' describe('utils', () => { // Positions: 01234567890123456789012345678901234567 const TEXT = 'This is a string with words to search.' it('should handle empty or null textToHighlight', () => { let result = Chunks.findAll({ searchWords: ['search'], textToHighlight: '' }) expect(result.length).to.equal(0) result = Chunks.findAll({ searchWords: ['search'] }) expect(result.length).to.equal(0) }) it('should highlight all occurrences of a word, regardless of capitalization', () => { const rawChunks = Chunks.findChunks({ searchWords: ['th'], textToHighlight: TEXT }) expect(rawChunks).to.eql([ {start: 0, end: 2, highlight: false}, {start: 19, end: 21, highlight: false} ]) }) it('should highlight words that partially overlap', () => { const combinedChunks = Chunks.combineChunks({ chunks: Chunks.findChunks({ searchWords: ['thi', 'is'], textToHighlight: TEXT }) }) expect(combinedChunks).to.eql([ {start: 0, end: 4, highlight: false}, {start: 5, end: 7, highlight: false} ]) }) it('should combine into the minimum number of marked and unmarked chunks', () => { const filledInChunks = Chunks.findAll({ searchWords: ['thi', 'is'], textToHighlight: TEXT }) expect(filledInChunks).to.eql([ {start: 0, end: 4, highlight: true}, {start: 4, end: 5, highlight: false}, {start: 5, end: 7, highlight: true}, {start: 7, end: 38, highlight: false} ]) }) it('should handle unclosed parentheses when autoEscape prop is truthy', () => { const rawChunks = Chunks.findChunks({ autoEscape: true, searchWords: ['text)'], textToHighlight: '(This is text)' }) expect(rawChunks).to.eql([ {start: 9, end: 14, highlight: false} ]) }) it('should match terms without accents against text with accents', () => { const rawChunks = Chunks.findChunks({ sanitize: latinize, searchWords: ['example'], textToHighlight: 'ỆᶍǍᶆṔƚÉ' }) expect(rawChunks).to.eql([ {start: 0, end: 7, highlight: false} ]) }) it('should support case sensitive matches', () => { let rawChunks = Chunks.findChunks({ caseSensitive: true, searchWords: ['t'], textToHighlight: TEXT }) expect(rawChunks).to.eql([ {start: 11, end: 12, highlight: false}, {start: 19, end: 20, highlight: false}, {start: 28, end: 29, highlight: false} ]) rawChunks = Chunks.findChunks({ caseSensitive: true, searchWords: ['T'], textToHighlight: TEXT }) expect(rawChunks).to.eql([ {start: 0, end: 1, highlight: false} ]) }) it('should handle zero-length matches correctly', () => { let rawChunks = Chunks.findChunks({ caseSensitive: true, searchWords: ['.*'], textToHighlight: TEXT }) expect(rawChunks).to.eql([ {start: 0, end: 38, highlight: false} ]) rawChunks = Chunks.findChunks({ caseSensitive: true, searchWords: ['w?'], textToHighlight: TEXT }) expect(rawChunks).to.eql([ {start: 17, end: 18, highlight: false}, {start: 22, end: 23, highlight: false} ]) }) it('should use custom findChunks', () => { let filledInChunks = Chunks.findAll({ findChunks: () => ( [{start: 1, end: 3}] ), searchWords: ['xxx'], textToHighlight: TEXT }) expect(filledInChunks).to.eql([ {start: 0, end: 1, highlight: false}, {start: 1, end: 3, highlight: true}, {start: 3, end: 38, highlight: false} ]) filledInChunks = Chunks.findAll({ findChunks: () => ( [] ), searchWords: ['This'], textToHighlight: TEXT }) expect(filledInChunks).to.eql([ {start: 0, end: 38, highlight: false} ]) }) })