highlight-words 1.2.0-beta.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/Changelog.md CHANGED
@@ -1,3 +1,15 @@
1
+ ### v1.2.1
2
+
3
+ ---
4
+
5
+ - Fix regex when searching for string with two or more spaces (fixes #25)
6
+
7
+ ### v1.2.0
8
+
9
+ ---
10
+
11
+ - Allow regular expression patterns to be used as a query
12
+
1
13
  ### v1.1.0
2
14
 
3
15
  ---
package/Readme.md CHANGED
@@ -50,12 +50,78 @@ console.log(chunks);
50
50
 
51
51
  [Play with this example on Code Sandbox.][sandbox-vanilla]
52
52
 
53
+ Alternatively, you can also use a regular expression as part of the query string to search for.
54
+ ```js
55
+ const chunks = highlightWords({
56
+ text: 'The quick brown fox jumped over the lazy dog',
57
+ query: '/(quick|brown|fox)/'
58
+ });
59
+
60
+ console.log(chunks);
61
+ /*
62
+ [
63
+ {
64
+ key: '62acb210-76dd-4682-b948-8d359a966dcb'
65
+ text: 'The ',
66
+ match: false
67
+ },
68
+ {
69
+ key: '69779adf-6d7c-45ec-ae9b-49d0cb292e28'
70
+ text: 'quick',
71
+ match: true
72
+ },
73
+ {
74
+ key: 'a72a6578-9111-4dca-a30d-676aaf7964c0'
75
+ text: ' ',
76
+ match: false
77
+ },
78
+ {
79
+ key: '24301852-f38b-4b54-b1fe-d8a82f47c49e'
80
+ text: 'brown',
81
+ match: true
82
+ },
83
+ {
84
+ key: 'a72a6578-9111-4dca-a30d-676aaf7964c0'
85
+ text: ' ',
86
+ match: false
87
+ },
88
+ {
89
+ key: '797b3bab-9244-451c-b246-4b03025b0691'
90
+ text: 'fox',
91
+ match: true
92
+ },
93
+ {
94
+ key: 'c86dbb8a-3e5f-4c05-a48c-684abbb517e8'
95
+ text: ' jumped over the lazy dog',
96
+ match: false
97
+ }
98
+ ]
99
+ */
100
+ ```
101
+
102
+ > If using a regular expresssion, you can choose to either enclose the pattern in a string or not. In both cases, you need to format the regular expression properly, i.e. enclose the pattern between slashes, **and** you need to create capture groups, so that the match is remembered for later use.
103
+ >
104
+ > **Valid regular expression usage**
105
+ > ```
106
+ > query: '/(quick|brown|fox)/'
107
+ > query: /(quick|brown|fox)/
108
+ > ```
109
+ >
110
+ >**Invalid regular expression usage**
111
+ > ```
112
+ > query: '(quick|brown|fox)'
113
+ > query: '/quick|brown|fox/'
114
+ > query: /quick|brown|fox/
115
+ > ```
116
+
53
117
  ### Options
54
118
 
55
119
  You can add a few options for the highlighter.
56
120
 
57
121
  - _clipBy_. If you want to clip the occurences that are not a match and display elipses around them. This can help to provide context around your matches.
58
- - _matchExactly_. By default, the highlighter will look for occurences of either words in your query. For example, if you have `brown fox` as your `query`, the highlighter will consider both `brown` and `fox` as separate matches.
122
+ - _matchExactly_. By default, the highlighter will look for occurences of either words in your query. For example, if you have `brown fox` as your `query`, the highlighter will consider both `brown` and `fox` as separate matches. If set to `true`, then only the exact match of `brown fox` will be considered.
123
+
124
+ > _matchExactly_ will have no effect if you're using a regular expression as your query, since you will have full control over the query in that case.
59
125
 
60
126
  ### Arguments
61
127
 
@@ -64,7 +130,7 @@ You can add a few options for the highlighter.
64
130
  | Property | Type | Required? | Description | Default |
65
131
  | :------------- | :------ | :-------: | :------------------------------------------------------------ | :------ |
66
132
  | `text` | String | ✓ | The body of text you want to search in. | `empty` |
67
- | `query` | String | ✓ | The word or words you want to search for. | `empty` |
133
+ | `query` | String | ✓ | The word(s) or regular expression you want to search for. | `empty` |
68
134
  | `clipBy` | Number | | How many words do you want to clip from the non matches. | `null` |
69
135
  | `matchExactly` | Boolean | | Should we match the complete query or individual words in it? | `false` |
70
136
 
@@ -17,6 +17,9 @@ function uid(len = 11) {
17
17
  }
18
18
 
19
19
  const escapeRegexp = (term) => term.replace(/[|\\{}()[\]^$+*?.-]/g, (char) => `\\${char}`);
20
+ const termsToRegExpString = (terms) => {
21
+ return terms.replace(/\s{2,}/g, " ").split(" ").join("|");
22
+ };
20
23
  const regexpQuery = ({
21
24
  terms,
22
25
  matchExactly = false
@@ -25,7 +28,7 @@ const regexpQuery = ({
25
28
  throw new TypeError("Expected a string");
26
29
  }
27
30
  const escapedTerms = escapeRegexp(terms.trim());
28
- return `(${matchExactly ? escapedTerms : escapedTerms.split(" ").join("|")})`;
31
+ return `(${matchExactly ? escapedTerms : termsToRegExpString(escapedTerms)})`;
29
32
  };
30
33
  const buildRegexp = ({
31
34
  terms,
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});let IDX=36,HEX="";for(;IDX--;)HEX+=IDX.toString(36);function uid(e=11){let t="",n=e;for(;n--;)t+=HEX[Math.random()*36|0];return t}const escapeRegexp=e=>e.replace(/[|\\{}()[\]^$+*?.-]/g,t=>`\\${t}`),regexpQuery=({terms:e,matchExactly:t=!1})=>{if(typeof e!="string")throw new TypeError("Expected a string");const n=escapeRegexp(e.trim());return`(${t?n:n.split(" ").join("|")})`},buildRegexp=({terms:e,matchExactly:t=!1})=>{try{const n=/^([/~@;%#'])(.*?)\1([gimsuy]*)$/.exec(e);return n?new RegExp(n[2],n[3]):new RegExp(regexpQuery({terms:e,matchExactly:t}),"ig")}catch(n){throw new TypeError("Expected terms to be either a string or a RegExp!")}},hasProp=e=>t=>t!==null&&typeof t!="undefined"&&e in t,hasMatch=hasProp("match"),chunkExists=e=>typeof e!="undefined";function clip({curr:e,next:t,prev:n,clipBy:r=3}){const o=e.text.split(" "),i=o.length;if(e.match||r>=i)return e.text;const s="...";return chunkExists(t)&&chunkExists(n)&&hasMatch(n)&&hasMatch(t)?i>r*2?[...o.slice(0,r),s,...o.slice(-r)].join(" "):e.text:chunkExists(t)&&hasMatch(t)?[s,...o.slice(-r)].join(" "):chunkExists(n)&&hasMatch(n)?[...o.slice(0,r),s].join(" "):e.text}var __assign=Object.assign;const hasLength=e=>e.length>0,highlightWords=({text:e,query:t,clipBy:n,matchExactly:r=!1})=>{const o=typeof t=="string"?t.trim():t;if(o==="")return[{key:uid(),text:e,match:!1}];const i=buildRegexp({terms:t,matchExactly:r});return e.split(i).filter(hasLength).map(s=>({key:uid(),text:s,match:r?s.toLowerCase()===o.toLowerCase():i.test(s)})).map((s,a,c)=>__assign(__assign({},s),typeof n=="number"&&{text:clip(__assign(__assign(__assign({curr:s},a<c.length-1&&{next:c[a+1]}),a>0&&{prev:c[a-1]}),{clipBy:n}))}))};exports.default=highlightWords;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});let IDX=36,HEX="";for(;IDX--;)HEX+=IDX.toString(36);function uid(e=11){let t="",n=e;for(;n--;)t+=HEX[Math.random()*36|0];return t}const escapeRegexp=e=>e.replace(/[|\\{}()[\]^$+*?.-]/g,t=>`\\${t}`),termsToRegExpString=e=>e.replace(/\s{2,}/g," ").split(" ").join("|"),regexpQuery=({terms:e,matchExactly:t=!1})=>{if(typeof e!="string")throw new TypeError("Expected a string");const n=escapeRegexp(e.trim());return`(${t?n:termsToRegExpString(n)})`},buildRegexp=({terms:e,matchExactly:t=!1})=>{try{const n=/^([/~@;%#'])(.*?)\1([gimsuy]*)$/.exec(e);return n?new RegExp(n[2],n[3]):new RegExp(regexpQuery({terms:e,matchExactly:t}),"ig")}catch(n){throw new TypeError("Expected terms to be either a string or a RegExp!")}},hasProp=e=>t=>t!==null&&typeof t!="undefined"&&e in t,hasMatch=hasProp("match"),chunkExists=e=>typeof e!="undefined";function clip({curr:e,next:t,prev:n,clipBy:s=3}){const o=e.text.split(" "),i=o.length;if(e.match||s>=i)return e.text;const r="...";return chunkExists(t)&&chunkExists(n)&&hasMatch(n)&&hasMatch(t)?i>s*2?[...o.slice(0,s),r,...o.slice(-s)].join(" "):e.text:chunkExists(t)&&hasMatch(t)?[r,...o.slice(-s)].join(" "):chunkExists(n)&&hasMatch(n)?[...o.slice(0,s),r].join(" "):e.text}var __assign=Object.assign;const hasLength=e=>e.length>0,highlightWords=({text:e,query:t,clipBy:n,matchExactly:s=!1})=>{const o=typeof t=="string"?t.trim():t;if(o==="")return[{key:uid(),text:e,match:!1}];const i=buildRegexp({terms:t,matchExactly:s});return e.split(i).filter(hasLength).map(r=>({key:uid(),text:r,match:s?r.toLowerCase()===o.toLowerCase():i.test(r)})).map((r,a,c)=>__assign(__assign({},r),typeof n=="number"&&{text:clip(__assign(__assign(__assign({curr:r},a<c.length-1&&{next:c[a+1]}),a>0&&{prev:c[a-1]}),{clipBy:n}))}))};exports.default=highlightWords;
2
2
  //# sourceMappingURL=highlight-words.min.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"highlight-words.min.js","sources":["../src/uid.ts","../src/regexp.ts","../src/clip.ts","../src/index.ts"],"sourcesContent":["// https://github.com/lukeed/uid/blob/master/src/index.js\n/* eslint no-bitwise: 'off' */\n/* eslint no-plusplus: 'off' */\n/* eslint @typescript-eslint/strict-boolean-expressions: 'off' */\nlet IDX = 36;\nlet HEX = '';\nwhile (IDX--) {\n HEX += IDX.toString(36);\n}\n\nexport default function uid(len = 11): string {\n let str = '';\n let num = len;\n while (num--) {\n str += HEX[(Math.random() * 36) | 0];\n }\n return str;\n}\n","import type { HighlightWords } from '.'; // eslint-disable-line import/no-cycle\n\n// We need escape certain characters before creating the RegExp\n// https://github.com/sindresorhus/escape-string-regexp\nconst escapeRegexp = (term: string): string =>\n term.replace(/[|\\\\{}()[\\]^$+*?.-]/g, (char: string) => `\\\\${char}`);\n\nconst regexpQuery = ({\n terms,\n matchExactly = false\n}: Readonly<HighlightWords.Query>): string => {\n if (typeof terms !== 'string') {\n throw new TypeError('Expected a string');\n }\n\n const escapedTerms = escapeRegexp(terms.trim());\n return `(${matchExactly ? escapedTerms : escapedTerms.split(' ').join('|')})`;\n};\n\nconst buildRegexp = ({\n terms,\n matchExactly = false\n}: Readonly<HighlightWords.Query>): RegExp => {\n try {\n const fromString = /^([/~@;%#'])(.*?)\\1([gimsuy]*)$/.exec(terms);\n if (fromString) {\n return new RegExp(fromString[2], fromString[3]);\n }\n\n return new RegExp(regexpQuery({ terms, matchExactly }), 'ig');\n } catch {\n throw new TypeError('Expected terms to be either a string or a RegExp!');\n }\n};\n\nexport { regexpQuery };\n\nexport default buildRegexp;\n","/* eslint complexity: [\"error\", { \"max\": 12 }] */\nimport type { HighlightWords } from '.'; // eslint-disable-line import/no-cycle\n\nconst hasProp = <T>(prop: string) => (obj: T) =>\n obj !== null && typeof obj !== 'undefined' && prop in obj;\nconst hasMatch = hasProp<HighlightWords.Chunk>('match');\n\nconst chunkExists = (\n chunk: HighlightWords.Chunk | undefined\n): chunk is HighlightWords.Chunk => typeof chunk !== 'undefined';\n\n/**\n * This provides context around a chunk's text, based on the next and previous chunks.\n * e.g. If we have the string \"The quick brown fox jumped over the lazy dog\",\n * and the search term \"fox jumped\", with a padding of 2, we want to have the end result be:\n * \"... quick brown fox jumped over the ...\"\n * The search term, \"fox jumped\" is left as is, and the left and right chunks, instead of having\n * the text in full, will be clipped.\n */\nexport default function clip({\n curr,\n next,\n prev,\n clipBy = 3\n}: HighlightWords.Clip): string {\n const words = curr.text.split(' ');\n const len = words.length;\n\n // If the current is a match, we leave it alone\n // Or if the clipBy is greater than or equal to the length of the words, there's nothing to clip\n if (curr.match || clipBy >= len) {\n return curr.text;\n }\n\n // If we have a clipBy greater than the length of the words in the current match,\n // it means we can clip the words in the current chunk\n const ellipsis = '...';\n\n if (\n chunkExists(next) &&\n chunkExists(prev) &&\n hasMatch(prev) &&\n hasMatch(next)\n ) {\n // Both the previous and the next chunks are a match\n // Let's check if we have enough words to clip by on both sides\n if (len > clipBy * 2) {\n return [\n ...words.slice(0, clipBy),\n ellipsis,\n ...words.slice(-clipBy)\n ].join(' ');\n }\n\n return curr.text;\n }\n\n // We start to check the next and previous matches in order to\n // properly position the elipsis\n if (chunkExists(next) && hasMatch(next)) {\n // The chunk right after this one is a match\n // So we need the elipsis at the start of the returned text\n // so that it sticks correctly to the next (match)'s text\n return [ellipsis, ...words.slice(-clipBy)].join(' ');\n }\n\n if (chunkExists(prev) && hasMatch(prev)) {\n // The chunk right before this one is a match\n // So we need the elipsis at the end of the returned text\n // so that it sticks correctly to the previous (match)'s text\n return [...words.slice(0, clipBy), ellipsis].join(' ');\n }\n\n // If we made it this far, just return the text\n return curr.text;\n}\n","import uid from './uid';\nimport buildRegexp from './regexp'; // eslint-disable-line import/no-cycle\nimport clip from './clip'; // eslint-disable-line import/no-cycle\n\n/* eslint-disable import/no-unused-modules */\ndeclare namespace HighlightWords {\n export interface Chunk {\n key: string;\n text: string;\n match: boolean;\n }\n\n export interface Options {\n text: string;\n query: string;\n clipBy?: number;\n matchExactly?: boolean;\n }\n\n export interface Clip {\n curr: Chunk;\n next?: Chunk;\n prev?: Chunk;\n clipBy?: number;\n }\n\n export interface Query {\n terms: string;\n matchExactly?: boolean;\n }\n}\n\nexport { HighlightWords };\n/* eslint-enable import/no-unused-modules */\n\nconst hasLength = (str: string): boolean => str.length > 0;\n\n/**\n * Split a text into chunks denoting which are a match and which are not based on a user search term.\n * @param text String The text to split.\n * @param query String The query to split by. This can contain multiple words.\n * @param clipBy Number Clip the non-matches by a certain number of words to provide context around the matches.\n * @param matchExactly Boolean If we have multiple words in the query, we will match any of the words if exact is false. For example, searching for \"brown fox\" in \"the brown cute fox\" will yield both \"brown\" and \"fox\" as matches. While if exact is true, the same search will return no results.\n */\nconst highlightWords = ({\n text,\n query,\n clipBy,\n matchExactly = false\n}: Readonly<HighlightWords.Options>): HighlightWords.Chunk[] => {\n // Let's make sure that the user cannot pass in just a bunch of spaces\n const safeQuery = typeof query === 'string' ? query.trim() : query;\n\n if (safeQuery === '') {\n return [\n {\n key: uid(),\n text,\n match: false\n }\n ];\n }\n\n const searchRegexp = buildRegexp({ terms: query, matchExactly });\n\n type ReadonlyChunk = Readonly<HighlightWords.Chunk>; // eslint-disable-line @typescript-eslint/no-type-alias\n\n return text\n .split(searchRegexp) // Split the entire thing into an array of matches and non-matches\n .filter(hasLength) // Filter any matches that have the text with length of 0\n .map((str) => ({\n // Compose the object for a match\n key: uid(),\n text: str,\n match: matchExactly\n ? str.toLowerCase() === safeQuery.toLowerCase()\n : searchRegexp.test(str)\n }))\n .map((chunk: ReadonlyChunk, index, chunks: readonly ReadonlyChunk[]) => ({\n // For each chunk, clip the text if needed\n ...chunk, // All the props first\n ...(typeof clipBy === 'number' && {\n // We only overwrite the text if there is a clip\n text: clip({\n curr: chunk, // We need the current chunk\n ...(index < chunks.length - 1 && { next: chunks[index + 1] }), // If this wasn't the last chunk, set the next chunk\n ...(index > 0 && { prev: chunks[index - 1] }), // If this wasn't the first chunk, set the previous chunk\n clipBy\n })\n })\n }));\n};\n\nexport default highlightWords;\n"],"names":[],"mappings":";;;;AAIA,IAAI,MAAM;AACV,IAAI,MAAM;AACV,OAAO;AACL,SAAO,IAAI,SAAS;AAAA;aAGM,MAAM;AAChC,MAAI,MAAM;AACV,MAAI,MAAM;AACV,SAAO;AACL,WAAO,IAAK,KAAK,WAAW,KAAM;AAAA;AAEpC,SAAO;AAAA;;ACZT,MAAM,eAAe,CAAC,SACpB,KAAK,QAAQ,wBAAwB,CAAC,SAAiB,KAAK;AAE9D,MAAM,cAAc,CAAC;AAAA,EACnB;AAAA,EACA,eAAe;AAAA;AAEf,MAAI,OAAO,UAAU;AACnB,UAAM,IAAI,UAAU;AAAA;AAGtB,QAAM,eAAe,aAAa,MAAM;AACxC,SAAO,IAAI,eAAe,eAAe,aAAa,MAAM,KAAK,KAAK;AAAA;AAGxE,MAAM,cAAc,CAAC;AAAA,EACnB;AAAA,EACA,eAAe;AAAA;AAEf;AACE,UAAM,aAAa,kCAAkC,KAAK;AAC1D,QAAI;AACF,aAAO,IAAI,OAAO,WAAW,IAAI,WAAW;AAAA;AAG9C,WAAO,IAAI,OAAO,YAAY,CAAE,OAAO,gBAAiB;AAAA,WAClD;AACN,UAAM,IAAI,UAAU;AAAA;AAAA;;AC5BxB,MAAM,UAAU,CAAI,SAAiB,CAAC,QACpC,QAAQ,QAAQ,OAAO,QAAQ,eAAe,QAAQ;AACxD,MAAM,WAAW,QAA8B;AAE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IAEhC,MAAM,KAAK;AAAA,MACT,MAAM;AAAA,OACF,QAAQ,OAAO,SAAS,KAAK,CAAE,MAAM,OAAO,QAAQ,MACpD,QAAQ,KAAK,CAAE,MAAM,OAAO,QAAQ,MAH/B;AAAA,MAIT;AAAA;AAAA;AAAA;;;;"}
1
+ {"version":3,"file":"highlight-words.min.js","sources":["../src/uid.ts","../src/regexp.ts","../src/clip.ts","../src/index.ts"],"sourcesContent":["// https://github.com/lukeed/uid/blob/master/src/index.js\n/* eslint no-bitwise: 'off' */\n/* eslint no-plusplus: 'off' */\n/* eslint @typescript-eslint/strict-boolean-expressions: 'off' */\nlet IDX = 36;\nlet HEX = '';\nwhile (IDX--) {\n HEX += IDX.toString(36);\n}\n\nexport default function uid(len = 11): string {\n let str = '';\n let num = len;\n while (num--) {\n str += HEX[(Math.random() * 36) | 0];\n }\n return str;\n}\n","import type { HighlightWords } from '.'; // eslint-disable-line import/no-cycle\n\n// We need escape certain characters before creating the RegExp\n// https://github.com/sindresorhus/escape-string-regexp\nconst escapeRegexp = (term: string): string =>\n term.replace(/[|\\\\{}()[\\]^$+*?.-]/g, (char: string) => `\\\\${char}`);\n\nconst termsToRegExpString = (terms: string): string => {\n return terms\n .replace(/\\s{2,}/g, ' ')\n .split(' ')\n .join('|');\n};\n\nconst regexpQuery = ({\n terms,\n matchExactly = false\n}: Readonly<HighlightWords.Query>): string => {\n if (typeof terms !== 'string') {\n throw new TypeError('Expected a string');\n }\n\n const escapedTerms = escapeRegexp(terms.trim());\n return `(${matchExactly ? escapedTerms : termsToRegExpString(escapedTerms)})`;\n};\n\nconst buildRegexp = ({\n terms,\n matchExactly = false\n}: Readonly<HighlightWords.Query>): RegExp => {\n try {\n const fromString = /^([/~@;%#'])(.*?)\\1([gimsuy]*)$/.exec(terms);\n if (fromString) {\n return new RegExp(fromString[2], fromString[3]);\n }\n\n return new RegExp(regexpQuery({ terms, matchExactly }), 'ig');\n } catch {\n throw new TypeError('Expected terms to be either a string or a RegExp!');\n }\n};\n\nexport { regexpQuery };\n\nexport default buildRegexp;\n","/* eslint complexity: [\"error\", { \"max\": 12 }] */\nimport type { HighlightWords } from '.'; // eslint-disable-line import/no-cycle\n\nconst hasProp = <T>(prop: string) => (obj: T) =>\n obj !== null && typeof obj !== 'undefined' && prop in obj;\nconst hasMatch = hasProp<HighlightWords.Chunk>('match');\n\nconst chunkExists = (\n chunk: HighlightWords.Chunk | undefined\n): chunk is HighlightWords.Chunk => typeof chunk !== 'undefined';\n\n/**\n * This provides context around a chunk's text, based on the next and previous chunks.\n * e.g. If we have the string \"The quick brown fox jumped over the lazy dog\",\n * and the search term \"fox jumped\", with a padding of 2, we want to have the end result be:\n * \"... quick brown fox jumped over the ...\"\n * The search term, \"fox jumped\" is left as is, and the left and right chunks, instead of having\n * the text in full, will be clipped.\n */\nexport default function clip({\n curr,\n next,\n prev,\n clipBy = 3\n}: HighlightWords.Clip): string {\n const words = curr.text.split(' ');\n const len = words.length;\n\n // If the current is a match, we leave it alone\n // Or if the clipBy is greater than or equal to the length of the words, there's nothing to clip\n if (curr.match || clipBy >= len) {\n return curr.text;\n }\n\n // If we have a clipBy greater than the length of the words in the current match,\n // it means we can clip the words in the current chunk\n const ellipsis = '...';\n\n if (\n chunkExists(next) &&\n chunkExists(prev) &&\n hasMatch(prev) &&\n hasMatch(next)\n ) {\n // Both the previous and the next chunks are a match\n // Let's check if we have enough words to clip by on both sides\n if (len > clipBy * 2) {\n return [\n ...words.slice(0, clipBy),\n ellipsis,\n ...words.slice(-clipBy)\n ].join(' ');\n }\n\n return curr.text;\n }\n\n // We start to check the next and previous matches in order to\n // properly position the elipsis\n if (chunkExists(next) && hasMatch(next)) {\n // The chunk right after this one is a match\n // So we need the elipsis at the start of the returned text\n // so that it sticks correctly to the next (match)'s text\n return [ellipsis, ...words.slice(-clipBy)].join(' ');\n }\n\n if (chunkExists(prev) && hasMatch(prev)) {\n // The chunk right before this one is a match\n // So we need the elipsis at the end of the returned text\n // so that it sticks correctly to the previous (match)'s text\n return [...words.slice(0, clipBy), ellipsis].join(' ');\n }\n\n // If we made it this far, just return the text\n return curr.text;\n}\n","import uid from './uid';\nimport buildRegexp from './regexp'; // eslint-disable-line import/no-cycle\nimport clip from './clip'; // eslint-disable-line import/no-cycle\n\n/* eslint-disable import/no-unused-modules */\ndeclare namespace HighlightWords {\n export interface Chunk {\n key: string;\n text: string;\n match: boolean;\n }\n\n export interface Options {\n text: string;\n query: string;\n clipBy?: number;\n matchExactly?: boolean;\n }\n\n export interface Clip {\n curr: Chunk;\n next?: Chunk;\n prev?: Chunk;\n clipBy?: number;\n }\n\n export interface Query {\n terms: string;\n matchExactly?: boolean;\n }\n}\n\nexport { HighlightWords };\n/* eslint-enable import/no-unused-modules */\n\nconst hasLength = (str: string): boolean => str.length > 0;\n\n/**\n * Split a text into chunks denoting which are a match and which are not based on a user search term.\n * @param text String The text to split.\n * @param query String The query to split by. This can contain multiple words.\n * @param clipBy Number Clip the non-matches by a certain number of words to provide context around the matches.\n * @param matchExactly Boolean If we have multiple words in the query, we will match any of the words if exact is false. For example, searching for \"brown fox\" in \"the brown cute fox\" will yield both \"brown\" and \"fox\" as matches. While if exact is true, the same search will return no results.\n */\nconst highlightWords = ({\n text,\n query,\n clipBy,\n matchExactly = false\n}: Readonly<HighlightWords.Options>): HighlightWords.Chunk[] => {\n // Let's make sure that the user cannot pass in just a bunch of spaces\n const safeQuery = typeof query === 'string' ? query.trim() : query;\n\n if (safeQuery === '') {\n return [\n {\n key: uid(),\n text,\n match: false\n }\n ];\n }\n\n const searchRegexp = buildRegexp({ terms: query, matchExactly });\n\n type ReadonlyChunk = Readonly<HighlightWords.Chunk>; // eslint-disable-line @typescript-eslint/no-type-alias\n\n return text\n .split(searchRegexp) // Split the entire thing into an array of matches and non-matches\n .filter(hasLength) // Filter any matches that have the text with length of 0\n .map((str) => ({\n // Compose the object for a match\n key: uid(),\n text: str,\n match: matchExactly\n ? str.toLowerCase() === safeQuery.toLowerCase()\n : searchRegexp.test(str)\n }))\n .map((chunk: ReadonlyChunk, index, chunks: readonly ReadonlyChunk[]) => ({\n // For each chunk, clip the text if needed\n ...chunk, // All the props first\n ...(typeof clipBy === 'number' && {\n // We only overwrite the text if there is a clip\n text: clip({\n curr: chunk, // We need the current chunk\n ...(index < chunks.length - 1 && { next: chunks[index + 1] }), // If this wasn't the last chunk, set the next chunk\n ...(index > 0 && { prev: chunks[index - 1] }), // If this wasn't the first chunk, set the previous chunk\n clipBy\n })\n })\n }));\n};\n\nexport default highlightWords;\n"],"names":[],"mappings":";;;;AAIA,IAAI,MAAM;AACV,IAAI,MAAM;AACV,OAAO;AACL,SAAO,IAAI,SAAS;AAAA;aAGM,MAAM;AAChC,MAAI,MAAM;AACV,MAAI,MAAM;AACV,SAAO;AACL,WAAO,IAAK,KAAK,WAAW,KAAM;AAAA;AAEpC,SAAO;AAAA;;ACZT,MAAM,eAAe,CAAC,SACpB,KAAK,QAAQ,wBAAwB,CAAC,SAAiB,KAAK;AAE9D,MAAM,sBAAsB,CAAC;AAC3B,SAAO,MACJ,QAAQ,WAAW,KACnB,MAAM,KACN,KAAK;AAAA;AAGV,MAAM,cAAc,CAAC;AAAA,EACnB;AAAA,EACA,eAAe;AAAA;AAEf,MAAI,OAAO,UAAU;AACnB,UAAM,IAAI,UAAU;AAAA;AAGtB,QAAM,eAAe,aAAa,MAAM;AACxC,SAAO,IAAI,eAAe,eAAe,oBAAoB;AAAA;AAG/D,MAAM,cAAc,CAAC;AAAA,EACnB;AAAA,EACA,eAAe;AAAA;AAEf;AACE,UAAM,aAAa,kCAAkC,KAAK;AAC1D,QAAI;AACF,aAAO,IAAI,OAAO,WAAW,IAAI,WAAW;AAAA;AAG9C,WAAO,IAAI,OAAO,YAAY,CAAE,OAAO,gBAAiB;AAAA,WAClD;AACN,UAAM,IAAI,UAAU;AAAA;AAAA;;ACnCxB,MAAM,UAAU,CAAI,SAAiB,CAAC,QACpC,QAAQ,QAAQ,OAAO,QAAQ,eAAe,QAAQ;AACx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,OAAO,WAAW,YAAY;AAAA,IAEhC,MAAM,KAAK;AAAA,MACT,MAAM;AAAA,OACF,QAAQ,OAAO,SAAS,KAAK,CAAE,MAAM,OAAO,QAAQ,MACpD,QAAQ,KAAK,CAAE,MAAM,OAAO,QAAQ,MAH/B;AAAA,MAIT;AAAA;AAAA;AAAA;;;;"}
@@ -1,2 +1,2 @@
1
- let h=36,p="";for(;h--;)p+=h.toString(36);function u(e=11){let t="",n=e;for(;n--;)t+=p[Math.random()*36|0];return t}const m=e=>e.replace(/[|\\{}()[\]^$+*?.-]/g,t=>`\\${t}`),w=({terms:e,matchExactly:t=!1})=>{if(typeof e!="string")throw new TypeError("Expected a string");const n=m(e.trim());return`(${t?n:n.split(" ").join("|")})`},x=({terms:e,matchExactly:t=!1})=>{try{const n=/^([/~@;%#'])(.*?)\1([gimsuy]*)$/.exec(e);return n?new RegExp(n[2],n[3]):new RegExp(w({terms:e,matchExactly:t}),"ig")}catch(n){throw new TypeError("Expected terms to be either a string or a RegExp!")}},d=e=>t=>t!==null&&typeof t!="undefined"&&e in t,c=d("match"),g=e=>typeof e!="undefined";function E({curr:e,next:t,prev:n,clipBy:r=3}){const o=e.text.split(" "),i=o.length;if(e.match||r>=i)return e.text;const s="...";return g(t)&&g(n)&&c(n)&&c(t)?i>r*2?[...o.slice(0,r),s,...o.slice(-r)].join(" "):e.text:g(t)&&c(t)?[s,...o.slice(-r)].join(" "):g(n)&&c(n)?[...o.slice(0,r),s].join(" "):e.text}var a=Object.assign;const R=e=>e.length>0,$=({text:e,query:t,clipBy:n,matchExactly:r=!1})=>{const o=typeof t=="string"?t.trim():t;if(o==="")return[{key:u(),text:e,match:!1}];const i=x({terms:t,matchExactly:r});return e.split(i).filter(R).map(s=>({key:u(),text:s,match:r?s.toLowerCase()===o.toLowerCase():i.test(s)})).map((s,f,l)=>a(a({},s),typeof n=="number"&&{text:E(a(a(a({curr:s},f<l.length-1&&{next:l[f+1]}),f>0&&{prev:l[f-1]}),{clipBy:n}))}))};export default $;
1
+ let p=36,h="";for(;p--;)h+=p.toString(36);function u(e=11){let t="",n=e;for(;n--;)t+=h[Math.random()*36|0];return t}const m=e=>e.replace(/[|\\{}()[\]^$+*?.-]/g,t=>`\\${t}`),x=e=>e.replace(/\s{2,}/g," ").split(" ").join("|"),w=({terms:e,matchExactly:t=!1})=>{if(typeof e!="string")throw new TypeError("Expected a string");const n=m(e.trim());return`(${t?n:x(n)})`},d=({terms:e,matchExactly:t=!1})=>{try{const n=/^([/~@;%#'])(.*?)\1([gimsuy]*)$/.exec(e);return n?new RegExp(n[2],n[3]):new RegExp(w({terms:e,matchExactly:t}),"ig")}catch(n){throw new TypeError("Expected terms to be either a string or a RegExp!")}},E=e=>t=>t!==null&&typeof t!="undefined"&&e in t,c=E("match"),f=e=>typeof e!="undefined";function R({curr:e,next:t,prev:n,clipBy:s=3}){const o=e.text.split(" "),i=o.length;if(e.match||s>=i)return e.text;const r="...";return f(t)&&f(n)&&c(n)&&c(t)?i>s*2?[...o.slice(0,s),r,...o.slice(-s)].join(" "):e.text:f(t)&&c(t)?[r,...o.slice(-s)].join(" "):f(n)&&c(n)?[...o.slice(0,s),r].join(" "):e.text}var a=Object.assign;const T=e=>e.length>0,$=({text:e,query:t,clipBy:n,matchExactly:s=!1})=>{const o=typeof t=="string"?t.trim():t;if(o==="")return[{key:u(),text:e,match:!1}];const i=d({terms:t,matchExactly:s});return e.split(i).filter(T).map(r=>({key:u(),text:r,match:s?r.toLowerCase()===o.toLowerCase():i.test(r)})).map((r,g,l)=>a(a({},r),typeof n=="number"&&{text:R(a(a(a({curr:r},g<l.length-1&&{next:l[g+1]}),g>0&&{prev:l[g-1]}),{clipBy:n}))}))};export default $;
2
2
  //# sourceMappingURL=highlight-words.min.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"highlight-words.min.mjs","sources":["../src/uid.ts","../src/regexp.ts","../src/clip.ts","../src/index.ts"],"sourcesContent":["// https://github.com/lukeed/uid/blob/master/src/index.js\n/* eslint no-bitwise: 'off' */\n/* eslint no-plusplus: 'off' */\n/* eslint @typescript-eslint/strict-boolean-expressions: 'off' */\nlet IDX = 36;\nlet HEX = '';\nwhile (IDX--) {\n HEX += IDX.toString(36);\n}\n\nexport default function uid(len = 11): string {\n let str = '';\n let num = len;\n while (num--) {\n str += HEX[(Math.random() * 36) | 0];\n }\n return str;\n}\n","import type { HighlightWords } from '.'; // eslint-disable-line import/no-cycle\n\n// We need escape certain characters before creating the RegExp\n// https://github.com/sindresorhus/escape-string-regexp\nconst escapeRegexp = (term: string): string =>\n term.replace(/[|\\\\{}()[\\]^$+*?.-]/g, (char: string) => `\\\\${char}`);\n\nconst regexpQuery = ({\n terms,\n matchExactly = false\n}: Readonly<HighlightWords.Query>): string => {\n if (typeof terms !== 'string') {\n throw new TypeError('Expected a string');\n }\n\n const escapedTerms = escapeRegexp(terms.trim());\n return `(${matchExactly ? escapedTerms : escapedTerms.split(' ').join('|')})`;\n};\n\nconst buildRegexp = ({\n terms,\n matchExactly = false\n}: Readonly<HighlightWords.Query>): RegExp => {\n try {\n const fromString = /^([/~@;%#'])(.*?)\\1([gimsuy]*)$/.exec(terms);\n if (fromString) {\n return new RegExp(fromString[2], fromString[3]);\n }\n\n return new RegExp(regexpQuery({ terms, matchExactly }), 'ig');\n } catch {\n throw new TypeError('Expected terms to be either a string or a RegExp!');\n }\n};\n\nexport { regexpQuery };\n\nexport default buildRegexp;\n","/* eslint complexity: [\"error\", { \"max\": 12 }] */\nimport type { HighlightWords } from '.'; // eslint-disable-line import/no-cycle\n\nconst hasProp = <T>(prop: string) => (obj: T) =>\n obj !== null && typeof obj !== 'undefined' && prop in obj;\nconst hasMatch = hasProp<HighlightWords.Chunk>('match');\n\nconst chunkExists = (\n chunk: HighlightWords.Chunk | undefined\n): chunk is HighlightWords.Chunk => typeof chunk !== 'undefined';\n\n/**\n * This provides context around a chunk's text, based on the next and previous chunks.\n * e.g. If we have the string \"The quick brown fox jumped over the lazy dog\",\n * and the search term \"fox jumped\", with a padding of 2, we want to have the end result be:\n * \"... quick brown fox jumped over the ...\"\n * The search term, \"fox jumped\" is left as is, and the left and right chunks, instead of having\n * the text in full, will be clipped.\n */\nexport default function clip({\n curr,\n next,\n prev,\n clipBy = 3\n}: HighlightWords.Clip): string {\n const words = curr.text.split(' ');\n const len = words.length;\n\n // If the current is a match, we leave it alone\n // Or if the clipBy is greater than or equal to the length of the words, there's nothing to clip\n if (curr.match || clipBy >= len) {\n return curr.text;\n }\n\n // If we have a clipBy greater than the length of the words in the current match,\n // it means we can clip the words in the current chunk\n const ellipsis = '...';\n\n if (\n chunkExists(next) &&\n chunkExists(prev) &&\n hasMatch(prev) &&\n hasMatch(next)\n ) {\n // Both the previous and the next chunks are a match\n // Let's check if we have enough words to clip by on both sides\n if (len > clipBy * 2) {\n return [\n ...words.slice(0, clipBy),\n ellipsis,\n ...words.slice(-clipBy)\n ].join(' ');\n }\n\n return curr.text;\n }\n\n // We start to check the next and previous matches in order to\n // properly position the elipsis\n if (chunkExists(next) && hasMatch(next)) {\n // The chunk right after this one is a match\n // So we need the elipsis at the start of the returned text\n // so that it sticks correctly to the next (match)'s text\n return [ellipsis, ...words.slice(-clipBy)].join(' ');\n }\n\n if (chunkExists(prev) && hasMatch(prev)) {\n // The chunk right before this one is a match\n // So we need the elipsis at the end of the returned text\n // so that it sticks correctly to the previous (match)'s text\n return [...words.slice(0, clipBy), ellipsis].join(' ');\n }\n\n // If we made it this far, just return the text\n return curr.text;\n}\n","import uid from './uid';\nimport buildRegexp from './regexp'; // eslint-disable-line import/no-cycle\nimport clip from './clip'; // eslint-disable-line import/no-cycle\n\n/* eslint-disable import/no-unused-modules */\ndeclare namespace HighlightWords {\n export interface Chunk {\n key: string;\n text: string;\n match: boolean;\n }\n\n export interface Options {\n text: string;\n query: string;\n clipBy?: number;\n matchExactly?: boolean;\n }\n\n export interface Clip {\n curr: Chunk;\n next?: Chunk;\n prev?: Chunk;\n clipBy?: number;\n }\n\n export interface Query {\n terms: string;\n matchExactly?: boolean;\n }\n}\n\nexport { HighlightWords };\n/* eslint-enable import/no-unused-modules */\n\nconst hasLength = (str: string): boolean => str.length > 0;\n\n/**\n * Split a text into chunks denoting which are a match and which are not based on a user search term.\n * @param text String The text to split.\n * @param query String The query to split by. This can contain multiple words.\n * @param clipBy Number Clip the non-matches by a certain number of words to provide context around the matches.\n * @param matchExactly Boolean If we have multiple words in the query, we will match any of the words if exact is false. For example, searching for \"brown fox\" in \"the brown cute fox\" will yield both \"brown\" and \"fox\" as matches. While if exact is true, the same search will return no results.\n */\nconst highlightWords = ({\n text,\n query,\n clipBy,\n matchExactly = false\n}: Readonly<HighlightWords.Options>): HighlightWords.Chunk[] => {\n // Let's make sure that the user cannot pass in just a bunch of spaces\n const safeQuery = typeof query === 'string' ? query.trim() : query;\n\n if (safeQuery === '') {\n return [\n {\n key: uid(),\n text,\n match: false\n }\n ];\n }\n\n const searchRegexp = buildRegexp({ terms: query, matchExactly });\n\n type ReadonlyChunk = Readonly<HighlightWords.Chunk>; // eslint-disable-line @typescript-eslint/no-type-alias\n\n return text\n .split(searchRegexp) // Split the entire thing into an array of matches and non-matches\n .filter(hasLength) // Filter any matches that have the text with length of 0\n .map((str) => ({\n // Compose the object for a match\n key: uid(),\n text: str,\n match: matchExactly\n ? str.toLowerCase() === safeQuery.toLowerCase()\n : searchRegexp.test(str)\n }))\n .map((chunk: ReadonlyChunk, index, chunks: readonly ReadonlyChunk[]) => ({\n // For each chunk, clip the text if needed\n ...chunk, // All the props first\n ...(typeof clipBy === 'number' && {\n // We only overwrite the text if there is a clip\n text: clip({\n curr: chunk, // We need the current chunk\n ...(index < chunks.length - 1 && { next: chunks[index + 1] }), // If this wasn't the last chunk, set the next chunk\n ...(index > 0 && { prev: chunks[index - 1] }), // If this wasn't the first chunk, set the previous chunk\n clipBy\n })\n })\n }));\n};\n\nexport default highlightWords;\n"],"names":[],"mappings":"AAIA,IAAI,MAAM;AACV,IAAI,MAAM;AACV,OAAO;AACL,SAAO,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O,KAAK;AAAA;AAKd,MAAI,YAAY,SAAS,SAAS;AAIhC,WAAO,CAAC,UAAU,GAAG,MAAM,MAAM,CAAC,SAAS,KAAK;AAAA;AAGlD,MAAI,YAAY,SAAS,SAAS;AAIhC,WAAO,CAAC,GAAG,MAAM,MAAM,GAAG,SAAS,UAAU,KAAK;AAAA;AAIpD,SAAO,KAAK;AAAA;;;ACvCd,MAAM,YAAY,CAAC,QAAyB,IAAI,SAAS;MASnD,iBAAiB,CAAC;AAAA,EACtB;AAAA,EACA;AAAA,EACA;AAAA,EACA,eAAe;AAAA;AAGf,QAAM,YAAY,OAAO,UAAU,WAAW,MAAM,SAAS;AAE7D,MAAI,cAAc;AAChB,WAAO;AAAA,MACL;AAAA,QACE,KAAK;AAAA,QACL;AAAA,QACA,OAAO;AAAA;AAAA;AAAA;AAKb,QAAM,eAAe,YAAY,CAAE,OAAO,OAAO;AAIjD,SAAO,KACJ,MAAM,cACN,OAAO,WACP,IAAI,CAAC;AAAS,IAEb,KAAK;AAAA,IACL,MAAM;AAAA,IACN,OAAO,eACH,IAAI,kBAAkB,UAAU,gBAChC,aAAa,KAAK;AAAA,MAEvB,IAAI,CAAC,OAAsB,OAAO,WAAsC,sBAEpE,QACC,OAAO,WAAW,YAAY;AAAA,IAEhC,MAAM,KAAK;AAAA,MACT,MAAM;AAAA,OACF,QAAQ,OAAO,SAAS,KAAK,CAAE,MAAM,OAAO,QAAQ,MACpD,QAAQ,KAAK,CAAE,MAAM,OAAO,QAAQ,MAH/B;AAAA,MAIT;AAAA;AAAA;AAAA;;;;"}
1
+ {"version":3,"file":"highlight-words.min.mjs","sources":["../src/uid.ts","../src/regexp.ts","../src/clip.ts","../src/index.ts"],"sourcesContent":["// https://github.com/lukeed/uid/blob/master/src/index.js\n/* eslint no-bitwise: 'off' */\n/* eslint no-plusplus: 'off' */\n/* eslint @typescript-eslint/strict-boolean-expressions: 'off' */\nlet IDX = 36;\nlet HEX = '';\nwhile (IDX--) {\n HEX += IDX.toString(36);\n}\n\nexport default function uid(len = 11): string {\n let str = '';\n let num = len;\n while (num--) {\n str += HEX[(Math.random() * 36) | 0];\n }\n return str;\n}\n","import type { HighlightWords } from '.'; // eslint-disable-line import/no-cycle\n\n// We need escape certain characters before creating the RegExp\n// https://github.com/sindresorhus/escape-string-regexp\nconst escapeRegexp = (term: string): string =>\n term.replace(/[|\\\\{}()[\\]^$+*?.-]/g, (char: string) => `\\\\${char}`);\n\nconst termsToRegExpString = (terms: string): string => {\n return terms\n .replace(/\\s{2,}/g, ' ')\n .split(' ')\n .join('|');\n};\n\nconst regexpQuery = ({\n terms,\n matchExactly = false\n}: Readonly<HighlightWords.Query>): string => {\n if (typeof terms !== 'string') {\n throw new TypeError('Expected a string');\n }\n\n const escapedTerms = escapeRegexp(terms.trim());\n return `(${matchExactly ? escapedTerms : termsToRegExpString(escapedTerms)})`;\n};\n\nconst buildRegexp = ({\n terms,\n matchExactly = false\n}: Readonly<HighlightWords.Query>): RegExp => {\n try {\n const fromString = /^([/~@;%#'])(.*?)\\1([gimsuy]*)$/.exec(terms);\n if (fromString) {\n return new RegExp(fromString[2], fromString[3]);\n }\n\n return new RegExp(regexpQuery({ terms, matchExactly }), 'ig');\n } catch {\n throw new TypeError('Expected terms to be either a string or a RegExp!');\n }\n};\n\nexport { regexpQuery };\n\nexport default buildRegexp;\n","/* eslint complexity: [\"error\", { \"max\": 12 }] */\nimport type { HighlightWords } from '.'; // eslint-disable-line import/no-cycle\n\nconst hasProp = <T>(prop: string) => (obj: T) =>\n obj !== null && typeof obj !== 'undefined' && prop in obj;\nconst hasMatch = hasProp<HighlightWords.Chunk>('match');\n\nconst chunkExists = (\n chunk: HighlightWords.Chunk | undefined\n): chunk is HighlightWords.Chunk => typeof chunk !== 'undefined';\n\n/**\n * This provides context around a chunk's text, based on the next and previous chunks.\n * e.g. If we have the string \"The quick brown fox jumped over the lazy dog\",\n * and the search term \"fox jumped\", with a padding of 2, we want to have the end result be:\n * \"... quick brown fox jumped over the ...\"\n * The search term, \"fox jumped\" is left as is, and the left and right chunks, instead of having\n * the text in full, will be clipped.\n */\nexport default function clip({\n curr,\n next,\n prev,\n clipBy = 3\n}: HighlightWords.Clip): string {\n const words = curr.text.split(' ');\n const len = words.length;\n\n // If the current is a match, we leave it alone\n // Or if the clipBy is greater than or equal to the length of the words, there's nothing to clip\n if (curr.match || clipBy >= len) {\n return curr.text;\n }\n\n // If we have a clipBy greater than the length of the words in the current match,\n // it means we can clip the words in the current chunk\n const ellipsis = '...';\n\n if (\n chunkExists(next) &&\n chunkExists(prev) &&\n hasMatch(prev) &&\n hasMatch(next)\n ) {\n // Both the previous and the next chunks are a match\n // Let's check if we have enough words to clip by on both sides\n if (len > clipBy * 2) {\n return [\n ...words.slice(0, clipBy),\n ellipsis,\n ...words.slice(-clipBy)\n ].join(' ');\n }\n\n return curr.text;\n }\n\n // We start to check the next and previous matches in order to\n // properly position the elipsis\n if (chunkExists(next) && hasMatch(next)) {\n // The chunk right after this one is a match\n // So we need the elipsis at the start of the returned text\n // so that it sticks correctly to the next (match)'s text\n return [ellipsis, ...words.slice(-clipBy)].join(' ');\n }\n\n if (chunkExists(prev) && hasMatch(prev)) {\n // The chunk right before this one is a match\n // So we need the elipsis at the end of the returned text\n // so that it sticks correctly to the previous (match)'s text\n return [...words.slice(0, clipBy), ellipsis].join(' ');\n }\n\n // If we made it this far, just return the text\n return curr.text;\n}\n","import uid from './uid';\nimport buildRegexp from './regexp'; // eslint-disable-line import/no-cycle\nimport clip from './clip'; // eslint-disable-line import/no-cycle\n\n/* eslint-disable import/no-unused-modules */\ndeclare namespace HighlightWords {\n export interface Chunk {\n key: string;\n text: string;\n match: boolean;\n }\n\n export interface Options {\n text: string;\n query: string;\n clipBy?: number;\n matchExactly?: boolean;\n }\n\n export interface Clip {\n curr: Chunk;\n next?: Chunk;\n prev?: Chunk;\n clipBy?: number;\n }\n\n export interface Query {\n terms: string;\n matchExactly?: boolean;\n }\n}\n\nexport { HighlightWords };\n/* eslint-enable import/no-unused-modules */\n\nconst hasLength = (str: string): boolean => str.length > 0;\n\n/**\n * Split a text into chunks denoting which are a match and which are not based on a user search term.\n * @param text String The text to split.\n * @param query String The query to split by. This can contain multiple words.\n * @param clipBy Number Clip the non-matches by a certain number of words to provide context around the matches.\n * @param matchExactly Boolean If we have multiple words in the query, we will match any of the words if exact is false. For example, searching for \"brown fox\" in \"the brown cute fox\" will yield both \"brown\" and \"fox\" as matches. While if exact is true, the same search will return no results.\n */\nconst highlightWords = ({\n text,\n query,\n clipBy,\n matchExactly = false\n}: Readonly<HighlightWords.Options>): HighlightWords.Chunk[] => {\n // Let's make sure that the user cannot pass in just a bunch of spaces\n const safeQuery = typeof query === 'string' ? query.trim() : query;\n\n if (safeQuery === '') {\n return [\n {\n key: uid(),\n text,\n match: false\n }\n ];\n }\n\n const searchRegexp = buildRegexp({ terms: query, matchExactly });\n\n type ReadonlyChunk = Readonly<HighlightWords.Chunk>; // eslint-disable-line @typescript-eslint/no-type-alias\n\n return text\n .split(searchRegexp) // Split the entire thing into an array of matches and non-matches\n .filter(hasLength) // Filter any matches that have the text with length of 0\n .map((str) => ({\n // Compose the object for a match\n key: uid(),\n text: str,\n match: matchExactly\n ? str.toLowerCase() === safeQuery.toLowerCase()\n : searchRegexp.test(str)\n }))\n .map((chunk: ReadonlyChunk, index, chunks: readonly ReadonlyChunk[]) => ({\n // For each chunk, clip the text if needed\n ...chunk, // All the props first\n ...(typeof clipBy === 'number' && {\n // We only overwrite the text if there is a clip\n text: clip({\n curr: chunk, // We need the current chunk\n ...(index < chunks.length - 1 && { next: chunks[index + 1] }), // If this wasn't the last chunk, set the next chunk\n ...(index > 0 && { prev: chunks[index - 1] }), // If this wasn't the first chunk, set the previous chunk\n clipBy\n })\n })\n }));\n};\n\nexport default highlightWords;\n"],"names":[],"mappings":"AAIA,IAAI,MAAM;AACV,IAAI,MAAM;AACV,OAAO;AACL,SAAO,IAAI,SAAS;AAAA;aAGM,MAAM;AAChC,MAAI,MAAM;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B,KAAK;AAAA;AAGT,WAAO,KAAK;AAAA;AAKd,MAAI,YAAY,SAAS,SAAS;AAIhC,WAAO,CAAC,UAAU,GAAG,MAAM,MAAM,CAAC,SAAS,KAAK;AAAA;AAGlD,MAAI,YAAY,SAAS,SAAS;AAIhC,WAAO,CAAC,GAAG,MAAM,MAAM,GAAG,SAAS,UAAU,KAAK;AAAA;AAIpD,SAAO,KAAK;AAAA;;;ACvCd,MAAM,YAAY,CAAC,QAAyB,IAAI,SAAS;MASnD,iBAAiB,CAAC;AAAA,EACtB;AAAA,EACA;AAAA,EACA;AAAA,EACA,eAAe;AAAA;AAGf,QAAM,YAAY,OAAO,UAAU,WAAW,MAAM,SAAS;AAE7D,MAAI,cAAc;AAChB,WAAO;AAAA,MACL;AAAA,QACE,KAAK;AAAA,QACL;AAAA,QACA,OAAO;AAAA;AAAA;AAAA;AAKb,QAAM,eAAe,YAAY,CAAE,OAAO,OAAO;AAIjD,SAAO,KACJ,MAAM,cACN,OAAO,WACP,IAAI,CAAC;AAAS,IAEb,KAAK;AAAA,IACL,MAAM;AAAA,IACN,OAAO,eACH,IAAI,kBAAkB,UAAU,gBAChC,aAAa,KAAK;AAAA,MAEvB,IAAI,CAAC,OAAsB,OAAO,WAAsC,sBAEpE,QACC,OAAO,WAAW,YAAY;AAAA,IAEhC,MAAM,KAAK;AAAA,MACT,MAAM;AAAA,OACF,QAAQ,OAAO,SAAS,KAAK,CAAE,MAAM,OAAO,QAAQ,MACpD,QAAQ,KAAK,CAAE,MAAM,OAAO,QAAQ,MAH/B;AAAA,MAIT;AAAA;AAAA;AAAA;;;;"}
@@ -13,6 +13,9 @@ function uid(len = 11) {
13
13
  }
14
14
 
15
15
  const escapeRegexp = (term) => term.replace(/[|\\{}()[\]^$+*?.-]/g, (char) => `\\${char}`);
16
+ const termsToRegExpString = (terms) => {
17
+ return terms.replace(/\s{2,}/g, " ").split(" ").join("|");
18
+ };
16
19
  const regexpQuery = ({
17
20
  terms,
18
21
  matchExactly = false
@@ -21,7 +24,7 @@ const regexpQuery = ({
21
24
  throw new TypeError("Expected a string");
22
25
  }
23
26
  const escapedTerms = escapeRegexp(terms.trim());
24
- return `(${matchExactly ? escapedTerms : escapedTerms.split(" ").join("|")})`;
27
+ return `(${matchExactly ? escapedTerms : termsToRegExpString(escapedTerms)})`;
25
28
  };
26
29
  const buildRegexp = ({
27
30
  terms,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "highlight-words",
3
- "version": "1.2.0-beta.0",
3
+ "version": "1.2.1",
4
4
  "description": "Split a piece text into multiple chunks based on a search query, allowing you to highlight the matches.",
5
5
  "engines": {
6
6
  "node": ">= 12",