highlight-words 1.0.5 → 1.1.0

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,28 +1,42 @@
1
- ###v1.0.5
1
+ ### v1.1.0
2
+
3
+ ---
4
+
5
+ - Switch to new build system
6
+ - Drop umd support
7
+
8
+ ### v1.0.6
9
+
10
+ ---
11
+
12
+ - Improve a little bit the internals using the new eslint rules
13
+ - Update dependencies
14
+
15
+ ### v1.0.5
2
16
 
3
17
  ---
4
18
 
5
19
  - Clip now handles the case when both the next and the previous chunks are a match and there are enough words in the current match to clip by
6
20
 
7
- ###v1.0.4
21
+ ### v1.0.4
8
22
 
9
23
  ---
10
24
 
11
25
  - Small fix to make sure we don't match when the query is just a bunch of white space
12
26
 
13
- ###v1.0.2
27
+ ### v1.0.2
14
28
 
15
29
  ---
16
30
 
17
31
  - Small fix to regexp builder to trim any leading and trailing white space
18
32
 
19
- ###v1.0.1
33
+ ### v1.0.1
20
34
 
21
35
  ---
22
36
 
23
37
  - Small fix to the modules path in package.json
24
38
 
25
- ###v1.0.0
39
+ ### v1.0.0
26
40
 
27
41
  ---
28
42
 
package/Readme.md CHANGED
@@ -141,6 +141,59 @@ By default, the highlighter won't assume any HTML element to wrap matched text,
141
141
 
142
142
  [Play with the Svelte example on Code Sandbox.][sandbox-svelte]
143
143
 
144
+ ## A note on accessibility
145
+
146
+ When we are splitting a piece of text into multiple chunks for the purpose of styling each chunk differently, and then using said chunks **instead** of the original text, we are doing a disservice to our users who might rely on a screen reader. This is because some screen readers will read out the chunks of text individually rather than in one continous flow. For example, if we were to split the text _Eeeh! Help me!_, `highlight-words` will return to us several chunks. We then might decide to wrap each chunk's text in a `span`, like so:
147
+
148
+ ```html
149
+ <p>
150
+ <span>E</span>
151
+ <span>e</span>
152
+ <span>e</span>
153
+ <span>h! H</span>
154
+ <span>e</span>
155
+ <span>lp m</span>
156
+ <span>e</span>
157
+ <span>!</span>
158
+ </p>
159
+ ```
160
+
161
+ Some screen readers will announce each letter **e** individually. Not ideal!
162
+
163
+ Let's make it accessible by using aria attributes to allow screen readers to correctly announce our text.
164
+
165
+ ```html
166
+ <p aria-label="Eeeh! Help me!">
167
+ <span aria-hidden="true">E</span>
168
+ <span aria-hidden="true">e</span>
169
+ <span aria-hidden="true">e</span>
170
+ <span aria-hidden="true">h! H</span>
171
+ <span aria-hidden="true">e</span>
172
+ <span aria-hidden="true">lp m</span>
173
+ <span aria-hidden="true">e</span>
174
+ <span aria-hidden="true">!</span>
175
+ </p>
176
+ ```
177
+
178
+ or, for less repetition:
179
+
180
+ ```html
181
+ <p aria-label="Eeeh! Help me!">
182
+ <span aria-hidden="true">
183
+ <span>E</span>
184
+ <span>e</span>
185
+ <span>e</span>
186
+ <span>h! H</span>
187
+ <span>e</span>
188
+ <span>lp m</span>
189
+ <span>e</span>
190
+ <span>!</span>
191
+ </span>
192
+ </p>
193
+ ```
194
+
195
+ For a much better write-up than I could put together, have a read of [Michelle Barker's How to Accessibly Split Text](https://css-irl.info/how-to-accessibly-split-text).
196
+
144
197
  ## License
145
198
 
146
199
  MIT License - fork, modify and use however you want.
@@ -150,7 +203,7 @@ MIT License - fork, modify and use however you want.
150
203
  [npm-version-badge]: https://img.shields.io/npm/v/highlight-words.svg?style=flat-square
151
204
  [highlight-words-npm]: https://www.npmjs.com/package/highlight-words
152
205
  [npm-downloads-badge]: https://img.shields.io/npm/dt/highlight-words.svg?style=flat-square
153
- [build-status-badge]: https://img.shields.io/travis/tricinel/highlight-words.svg?style=flat-square
206
+ [build-status-badge]: https://img.shields.io/circleci/build/github/tricinel/cuddy?label=circleci&style=flat-square
154
207
  [sandbox-react]: https://codesandbox.io/s/highlight-words-react-1h7qw
155
208
  [sandbox-angular]: https://codesandbox.io/s/highlight-words-angular-xpp46
156
209
  [sandbox-vue]: https://codesandbox.io/s/highlight-words-vue-zopni
@@ -1,33 +1,35 @@
1
- declare namespace HighlightWords {
2
- interface Chunk {
3
- key: string;
4
- text: string;
5
- match: boolean;
6
- }
7
- interface Options {
8
- text: string;
9
- query: string;
10
- clipBy?: number;
11
- matchExactly?: boolean;
12
- }
13
- interface Clip {
14
- curr: Chunk;
15
- next: Chunk;
16
- prev: Chunk;
17
- clipBy?: number;
18
- }
19
- interface Query {
20
- terms: string;
21
- matchExactly?: boolean;
22
- }
23
- }
24
- export { HighlightWords };
25
- /**
26
- * Split a text into chunks denoting which are a match and which are not based on a user search term.
27
- * @param text String The text to split.
28
- * @param query String The query to split by. This can contain multiple words.
29
- * @param clipBy Number Clip the non-matches by a certain number of words to provide context around the matches.
30
- * @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.
31
- */
32
- declare const highlightWords: ({ text, query, clipBy, matchExactly }: HighlightWords.Options) => HighlightWords.Chunk[];
33
- export default highlightWords;
1
+ declare namespace HighlightWords {
2
+ interface Chunk {
3
+ key: string;
4
+ text: string;
5
+ match: boolean;
6
+ }
7
+ interface Options {
8
+ text: string;
9
+ query: string;
10
+ clipBy?: number;
11
+ matchExactly?: boolean;
12
+ }
13
+ interface Clip {
14
+ curr: Chunk;
15
+ next?: Chunk;
16
+ prev?: Chunk;
17
+ clipBy?: number;
18
+ }
19
+ interface Query {
20
+ terms: string;
21
+ matchExactly?: boolean;
22
+ }
23
+ }
24
+
25
+ /**
26
+ * Split a text into chunks denoting which are a match and which are not based on a user search term.
27
+ * @param text String The text to split.
28
+ * @param query String The query to split by. This can contain multiple words.
29
+ * @param clipBy Number Clip the non-matches by a certain number of words to provide context around the matches.
30
+ * @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.
31
+ */
32
+ declare const highlightWords: ({ text, query, clipBy, matchExactly }: Readonly<HighlightWords.Options>) => HighlightWords.Chunk[];
33
+
34
+ export default highlightWords;
35
+ export { HighlightWords };
@@ -0,0 +1,97 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ let IDX = 36;
6
+ let HEX = "";
7
+ while (IDX--) {
8
+ HEX += IDX.toString(36);
9
+ }
10
+ function uid(len = 11) {
11
+ let str = "";
12
+ let num = len;
13
+ while (num--) {
14
+ str += HEX[Math.random() * 36 | 0];
15
+ }
16
+ return str;
17
+ }
18
+
19
+ const escapeRegexp = (term) => term.replace(/[|\\{}()[\]^$+*?.-]/g, (char) => `\\${char}`);
20
+ const regexpQuery = ({
21
+ terms,
22
+ matchExactly = false
23
+ }) => {
24
+ if (typeof terms !== "string") {
25
+ throw new TypeError("Expected a string");
26
+ }
27
+ const escapedTerms = escapeRegexp(terms.trim());
28
+ return `(${matchExactly ? escapedTerms : escapedTerms.split(" ").join("|")})`;
29
+ };
30
+
31
+ const hasProp = (prop) => (obj) => obj !== null && typeof obj !== "undefined" && prop in obj;
32
+ const hasMatch = hasProp("match");
33
+ const chunkExists = (chunk) => typeof chunk !== "undefined";
34
+ function clip({
35
+ curr,
36
+ next,
37
+ prev,
38
+ clipBy = 3
39
+ }) {
40
+ const words = curr.text.split(" ");
41
+ const len = words.length;
42
+ if (curr.match || clipBy >= len) {
43
+ return curr.text;
44
+ }
45
+ const ellipsis = "...";
46
+ if (chunkExists(next) && chunkExists(prev) && hasMatch(prev) && hasMatch(next)) {
47
+ if (len > clipBy * 2) {
48
+ return [
49
+ ...words.slice(0, clipBy),
50
+ ellipsis,
51
+ ...words.slice(-clipBy)
52
+ ].join(" ");
53
+ }
54
+ return curr.text;
55
+ }
56
+ if (chunkExists(next) && hasMatch(next)) {
57
+ return [ellipsis, ...words.slice(-clipBy)].join(" ");
58
+ }
59
+ if (chunkExists(prev) && hasMatch(prev)) {
60
+ return [...words.slice(0, clipBy), ellipsis].join(" ");
61
+ }
62
+ return curr.text;
63
+ }
64
+
65
+ var __assign = Object.assign;
66
+ const hasLength = (str) => str.length > 0;
67
+ const highlightWords = ({
68
+ text,
69
+ query,
70
+ clipBy,
71
+ matchExactly = false
72
+ }) => {
73
+ const safeQuery = query.trim();
74
+ if (safeQuery === "") {
75
+ return [
76
+ {
77
+ key: uid(),
78
+ text,
79
+ match: false
80
+ }
81
+ ];
82
+ }
83
+ const searchRegexp = new RegExp(regexpQuery({terms: safeQuery, matchExactly}), "ig");
84
+ return text.split(searchRegexp).filter(hasLength).map((str) => ({
85
+ key: uid(),
86
+ text: str,
87
+ match: matchExactly ? str.toLowerCase() === safeQuery.toLowerCase() : searchRegexp.test(str)
88
+ })).map((chunk, index, chunks) => __assign(__assign({}, chunk), typeof clipBy === "number" && {
89
+ text: clip(__assign(__assign(__assign({
90
+ curr: chunk
91
+ }, index < chunks.length - 1 && {next: chunks[index + 1]}), index > 0 && {prev: chunks[index - 1]}), {
92
+ clipBy
93
+ }))
94
+ }));
95
+ };
96
+
97
+ exports.default = highlightWords;
@@ -0,0 +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="",s=e;for(;s--;)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 s=escapeRegexp(e.trim());return`(${t?s:s.split(" ").join("|")})`},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:s,clipBy:r=3}){const o=e.text.split(" "),i=o.length;if(e.match||r>=i)return e.text;const n="...";return chunkExists(t)&&chunkExists(s)&&hasMatch(s)&&hasMatch(t)?i>r*2?[...o.slice(0,r),n,...o.slice(-r)].join(" "):e.text:chunkExists(t)&&hasMatch(t)?[n,...o.slice(-r)].join(" "):chunkExists(s)&&hasMatch(s)?[...o.slice(0,r),n].join(" "):e.text}var __assign=Object.assign;const hasLength=e=>e.length>0,highlightWords=({text:e,query:t,clipBy:s,matchExactly:r=!1})=>{const o=t.trim();if(o==="")return[{key:uid(),text:e,match:!1}];const i=new RegExp(regexpQuery({terms:o,matchExactly:r}),"ig");return e.split(i).filter(hasLength).map(n=>({key:uid(),text:n,match:r?n.toLowerCase()===o.toLowerCase():i.test(n)})).map((n,a,l)=>__assign(__assign({},n),typeof s=="number"&&{text:clip(__assign(__assign(__assign({curr:n},a<l.length-1&&{next:l[a+1]}),a>0&&{prev:l[a-1]}),{clipBy:s}))}))};exports.default=highlightWords;
2
+ //# sourceMappingURL=highlight-words.min.js.map
@@ -0,0 +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\nexport default regexpQuery;\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 regexpQuery 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 = query.trim();\n\n if (safeQuery === '') {\n return [\n {\n key: uid(),\n text,\n match: false\n }\n ];\n }\n\n const searchRegexp = new RegExp(\n regexpQuery({ terms: safeQuery, matchExactly }),\n 'ig'\n );\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;;ACbxE,MAAM,UAAU,CAAI,SAAiB,CAAC,QACpC,QAAQ,QAAQ,OAAO,QAAQ,eAAe,QAAQ;AACxD,MAAM,WAAW,QAA8B;AAE/C,MAAM,cAAc,CAClB,UACkC,OAAO,UAAU;cAUxB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA,SAAS;AAAA;AAET,QAAM,QAAQ,KAAK,KAAK,MAAM;AAC9B,QAAM,MAAM,MAAM;AAIlB,MAAI,KAAK,SAAS,UAAU;AAC1B,WAAO,KAAK;AAAA;AAKd,QAAM,WAAW;AAEjB,MACE,YAAY,SACZ,YAAY,SACZ,SAAS,SACT,SAAS;AAIT,QAAI,MAAM,SAAS;AACjB,aAAO;AAAA,QACL,GAAG,MAAM,MAAM,GAAG;AAAA,QAClB;AAAA,QACA,GAAG,MAAM,MAAM,CAAC;AAAA,QAChB,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,MAAM;AAExB,MAAI,cAAc;AAChB,WAAO;AAAA,MACL;AAAA,QACE,KAAK;AAAA,QACL;AAAA,QACA,OAAO;AAAA;AAAA;AAAA;AAKb,QAAM,eAAe,IAAI,OACvB,YAAY,CAAE,OAAO,WAAW,gBAChC;AAKF,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;;;;"}
@@ -0,0 +1,2 @@
1
+ let h=36,u="";for(;h--;)u+=h.toString(36);function p(e=11){let t="",n=e;for(;n--;)t+=u[Math.random()*36|0];return t}const m=e=>e.replace(/[|\\{}()[\]^$+*?.-]/g,t=>`\\${t}`),d=({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("|")})`},w=e=>t=>t!==null&&typeof t!="undefined"&&e in t,f=w("match"),c=e=>typeof e!="undefined";function x({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 c(t)&&c(n)&&f(n)&&f(t)?i>r*2?[...o.slice(0,r),s,...o.slice(-r)].join(" "):e.text:c(t)&&f(t)?[s,...o.slice(-r)].join(" "):c(n)&&f(n)?[...o.slice(0,r),s].join(" "):e.text}var a=Object.assign;const E=e=>e.length>0,j=({text:e,query:t,clipBy:n,matchExactly:r=!1})=>{const o=t.trim();if(o==="")return[{key:p(),text:e,match:!1}];const i=new RegExp(d({terms:o,matchExactly:r}),"ig");return e.split(i).filter(E).map(s=>({key:p(),text:s,match:r?s.toLowerCase()===o.toLowerCase():i.test(s)})).map((s,l,g)=>a(a({},s),typeof n=="number"&&{text:x(a(a(a({curr:s},l<g.length-1&&{next:g[l+1]}),l>0&&{prev:g[l-1]}),{clipBy:n}))}))};export default j;
2
+ //# sourceMappingURL=highlight-words.min.mjs.map
@@ -0,0 +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\nexport default regexpQuery;\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 regexpQuery 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 = query.trim();\n\n if (safeQuery === '') {\n return [\n {\n key: uid(),\n text,\n match: false\n }\n ];\n }\n\n const searchRegexp = new RegExp(\n regexpQuery({ terms: safeQuery, matchExactly }),\n 'ig'\n );\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;;ACbxE,MAAM,UAAU,CAAI,SAAiB,CAAC,QACpC,QAAQ,QAAQ,OAAO,QAAQ,eAAe,QAAQ;AACxD,MAAM,WAAW,QAA8B;AAE/C,MAAM,cAAc,CAClB,UACkC,OAAO,UAAU;cAUxB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA,SAAS;AAAA;AAET,QAAM,QAAQ,KAAK,KAAK,MAAM;AAC9B,QAAM,MAAM,MAAM;AAIlB,MAAI,KAAK,SAAS,UAAU;AAC1B,WAAO,KAAK;AAAA;AAKd,QAAM,WAAW;AAEjB,MACE,YAAY,SACZ,YAAY,SACZ,SAAS,SACT,SAAS;AAIT,QAAI,MAAM,SAAS;AACjB,aAAO;AAAA,QACL,GAAG,MAAM,MAAM,GAAG;AAAA,QAClB;AAAA,QACA,GAAG,MAAM,MAAM,CAAC;AAAA,QAChB,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,MAAM;AAExB,MAAI,cAAc;AAChB,WAAO;AAAA,MACL;AAAA,QACE,KAAK;AAAA,QACL;AAAA,QACA,OAAO;AAAA;AAAA;AAAA;AAKb,QAAM,eAAe,IAAI,OACvB,YAAY,CAAE,OAAO,WAAW,gBAChC;AAKF,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;;;;"}
@@ -0,0 +1,93 @@
1
+ let IDX = 36;
2
+ let HEX = "";
3
+ while (IDX--) {
4
+ HEX += IDX.toString(36);
5
+ }
6
+ function uid(len = 11) {
7
+ let str = "";
8
+ let num = len;
9
+ while (num--) {
10
+ str += HEX[Math.random() * 36 | 0];
11
+ }
12
+ return str;
13
+ }
14
+
15
+ const escapeRegexp = (term) => term.replace(/[|\\{}()[\]^$+*?.-]/g, (char) => `\\${char}`);
16
+ const regexpQuery = ({
17
+ terms,
18
+ matchExactly = false
19
+ }) => {
20
+ if (typeof terms !== "string") {
21
+ throw new TypeError("Expected a string");
22
+ }
23
+ const escapedTerms = escapeRegexp(terms.trim());
24
+ return `(${matchExactly ? escapedTerms : escapedTerms.split(" ").join("|")})`;
25
+ };
26
+
27
+ const hasProp = (prop) => (obj) => obj !== null && typeof obj !== "undefined" && prop in obj;
28
+ const hasMatch = hasProp("match");
29
+ const chunkExists = (chunk) => typeof chunk !== "undefined";
30
+ function clip({
31
+ curr,
32
+ next,
33
+ prev,
34
+ clipBy = 3
35
+ }) {
36
+ const words = curr.text.split(" ");
37
+ const len = words.length;
38
+ if (curr.match || clipBy >= len) {
39
+ return curr.text;
40
+ }
41
+ const ellipsis = "...";
42
+ if (chunkExists(next) && chunkExists(prev) && hasMatch(prev) && hasMatch(next)) {
43
+ if (len > clipBy * 2) {
44
+ return [
45
+ ...words.slice(0, clipBy),
46
+ ellipsis,
47
+ ...words.slice(-clipBy)
48
+ ].join(" ");
49
+ }
50
+ return curr.text;
51
+ }
52
+ if (chunkExists(next) && hasMatch(next)) {
53
+ return [ellipsis, ...words.slice(-clipBy)].join(" ");
54
+ }
55
+ if (chunkExists(prev) && hasMatch(prev)) {
56
+ return [...words.slice(0, clipBy), ellipsis].join(" ");
57
+ }
58
+ return curr.text;
59
+ }
60
+
61
+ var __assign = Object.assign;
62
+ const hasLength = (str) => str.length > 0;
63
+ const highlightWords = ({
64
+ text,
65
+ query,
66
+ clipBy,
67
+ matchExactly = false
68
+ }) => {
69
+ const safeQuery = query.trim();
70
+ if (safeQuery === "") {
71
+ return [
72
+ {
73
+ key: uid(),
74
+ text,
75
+ match: false
76
+ }
77
+ ];
78
+ }
79
+ const searchRegexp = new RegExp(regexpQuery({terms: safeQuery, matchExactly}), "ig");
80
+ return text.split(searchRegexp).filter(hasLength).map((str) => ({
81
+ key: uid(),
82
+ text: str,
83
+ match: matchExactly ? str.toLowerCase() === safeQuery.toLowerCase() : searchRegexp.test(str)
84
+ })).map((chunk, index, chunks) => __assign(__assign({}, chunk), typeof clipBy === "number" && {
85
+ text: clip(__assign(__assign(__assign({
86
+ curr: chunk
87
+ }, index < chunks.length - 1 && {next: chunks[index + 1]}), index > 0 && {prev: chunks[index - 1]}), {
88
+ clipBy
89
+ }))
90
+ }));
91
+ };
92
+
93
+ export default highlightWords;
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "highlight-words",
3
- "version": "1.0.5",
3
+ "version": "1.1.0",
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
- "node": ">= 10",
6
+ "node": ">= 12",
7
7
  "npm": ">= 6"
8
8
  },
9
9
  "repository": {
@@ -30,53 +30,49 @@
30
30
  "dist",
31
31
  "coverage"
32
32
  ],
33
- "main": "dist/lib/index.js",
34
- "module": "dist/lib-esm/index.js",
35
- "browser": "dist/bundles/highlight-words.js",
33
+ "main": "dist/highlight-words.js",
34
+ "module": "dist/highlight-words.mjs",
35
+ "typings": "dist/highlight-words.d.ts",
36
36
  "scripts": {
37
37
  "prebuild": "cross-env rimraf dist",
38
38
  "build": "rollup -c",
39
39
  "watch": "rollup -cw",
40
40
  "typecheck": "tsc --noEmit",
41
- "lint": "eslint src/**/*.ts",
41
+ "lint": "eslint src --ext .ts",
42
42
  "format": "prettier --write \"src/**/*.ts\"",
43
- "test:ci": "jest --runInBand --ci",
44
43
  "test": "jest",
45
44
  "test:mutations": "stryker run",
46
- "release": "release-it"
45
+ "prepublishOnly": "npm-run-all test typecheck lint build"
47
46
  },
48
47
  "devDependencies": {
49
- "@babel/core": "^7.5.4",
50
- "@babel/plugin-transform-typescript": "^7.5.5",
51
- "@babel/preset-env": "^7.5.4",
52
- "@babel/preset-typescript": "^7.3.3",
53
- "@stryker-mutator/babel-transpiler": "^2.0.2",
54
- "@stryker-mutator/core": "^2.0.2",
55
- "@stryker-mutator/jest-runner": "^2.0.2",
56
- "@stryker-mutator/typescript": "^2.0.2",
57
- "@types/jest": "^24.0.15",
58
- "@typescript-eslint/eslint-plugin": "^1.12.0",
59
- "@typescript-eslint/parser": "^1.12.0",
60
- "cross-env": "^5.2.0",
61
- "eslint": "^6.1.0",
62
- "eslint-config-prettier": "^6.0.0",
63
- "eslint-plugin-jest": "^22.8.0",
64
- "eslint-plugin-prettier": "^3.1.0",
65
- "husky": "^3.0.0",
66
- "jest": "^24.8.0",
67
- "jest-watch-typeahead": "^0.3.1",
68
- "lint-staged": "^9.2.0",
48
+ "@babel/core": "^7.12.13",
49
+ "@babel/plugin-transform-typescript": "^7.12.13",
50
+ "@babel/preset-env": "^7.12.13",
51
+ "@babel/preset-typescript": "^7.12.13",
52
+ "@stryker-mutator/core": "^4.4.1",
53
+ "@stryker-mutator/jest-runner": "^4.4.1",
54
+ "@types/jest": "^26.0.20",
55
+ "@typescript-eslint/eslint-plugin": "^4.15.0",
56
+ "@typescript-eslint/parser": "^4.15.0",
57
+ "cross-env": "^7.0.3",
58
+ "esbuild": "^0.8.44",
59
+ "eslint": "^7.19.0",
60
+ "eslint-config-frontwerk-typescript": "^1.2.2",
61
+ "eslint-config-prettier": "^7.2.0",
62
+ "eslint-plugin-import": "^2.22.1",
63
+ "eslint-plugin-jest": "^24.1.3",
64
+ "eslint-plugin-prettier": "^3.3.1",
65
+ "husky": "^5.0.9",
66
+ "jest": "^26.6.3",
67
+ "jest-watch-typeahead": "^0.6.1",
68
+ "lint-staged": "^10.5.4",
69
+ "npm-run-all": "^4.1.5",
69
70
  "precise-commits": "^1.0.2",
70
- "prettier": "^1.18.2",
71
- "release-it": "^12.3.5",
72
- "rimraf": "^2.6.3",
73
- "rollup": "^1.17.0",
74
- "rollup-plugin-babel": "^4.3.3",
75
- "rollup-plugin-commonjs": "^10.0.2",
76
- "rollup-plugin-copy": "^3.1.0",
77
- "rollup-plugin-node-resolve": "^5.2.0",
78
- "rollup-plugin-terser": "^5.1.1",
79
- "rollup-plugin-typescript2": "^0.22.0",
80
- "typescript": "^3.5.3"
71
+ "prettier": "^2.2.1",
72
+ "rimraf": "^3.0.2",
73
+ "rollup": "^2.38.5",
74
+ "rollup-plugin-dts": "^2.0.1",
75
+ "rollup-plugin-esbuild": "^2.6.1",
76
+ "typescript": "^4.1.4"
81
77
  }
82
78
  }
@@ -1,147 +0,0 @@
1
- (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
3
- typeof define === 'function' && define.amd ? define(factory) :
4
- (global = global || self, global.HighlightWords = factory());
5
- }(this, function () { 'use strict';
6
-
7
- /*! *****************************************************************************
8
- Copyright (c) Microsoft Corporation. All rights reserved.
9
- Licensed under the Apache License, Version 2.0 (the "License"); you may not use
10
- this file except in compliance with the License. You may obtain a copy of the
11
- License at http://www.apache.org/licenses/LICENSE-2.0
12
-
13
- THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
- KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
15
- WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
16
- MERCHANTABLITY OR NON-INFRINGEMENT.
17
-
18
- See the Apache Version 2.0 License for specific language governing permissions
19
- and limitations under the License.
20
- ***************************************************************************** */
21
-
22
- var __assign = function() {
23
- __assign = Object.assign || function __assign(t) {
24
- for (var s, i = 1, n = arguments.length; i < n; i++) {
25
- s = arguments[i];
26
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
27
- }
28
- return t;
29
- };
30
- return __assign.apply(this, arguments);
31
- };
32
-
33
- // https://stackoverflow.com/questions/26501688/a-typescript-guid-class
34
- function uuidv4() {
35
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
36
- var r = (Math.random() * 16) | 0; // tslint:disable-line no-bitwise
37
- return (c == 'x' ? r : (r & 0x3) | 0x8).toString(16); // tslint:disable-line no-bitwise
38
- });
39
- }
40
-
41
- // We need escape certain characters before creating the RegExp
42
- // https://github.com/sindresorhus/escape-string-regexp
43
- var escapeRegexp = function (term) {
44
- return term.replace(/[|\\{}()[\]^$+*?.-]/g, function (char) { return "\\" + char; });
45
- };
46
- var regexpQuery = function (_a) {
47
- var terms = _a.terms, _b = _a.matchExactly, matchExactly = _b === void 0 ? false : _b;
48
- if (typeof terms !== 'string') {
49
- throw new TypeError('Expected a string');
50
- }
51
- var escapedTerms = escapeRegexp(terms.trim());
52
- return "(" + (matchExactly ? escapedTerms : escapedTerms.split(' ').join('|')) + ")";
53
- };
54
-
55
- /**
56
- * This provides context around a chunk's text, based on the next and previous chunks.
57
- * e.g. If we have the string "The quick brown fox jumped over the lazy dog",
58
- * and the search term "fox jumped", with a padding of 2, we want to have the end result be:
59
- * "... quick brown fox jumped over the ..."
60
- * The search term, "fox jumped" is left as is, and the left and right chunks, instead of having
61
- * the text in full, will be clipped.
62
- */
63
- function clip(_a) {
64
- var curr = _a.curr, next = _a.next, prev = _a.prev, _b = _a.clipBy, clipBy = _b === void 0 ? 3 : _b;
65
- var words = curr.text.split(' ');
66
- var len = words.length;
67
- // If the current is a match, we leave it alone
68
- // Or if the clipBy is greater than or equal to the length of the words, there's nothing to clip
69
- if (curr.match || clipBy >= len) {
70
- return curr.text;
71
- }
72
- // If we have a clipBy greater than the length of the words in the current match,
73
- // it means we can clip the words in the current chunk
74
- var ellipsis = '...';
75
- if (prev && prev.match && next && next.match) {
76
- // Both the previous and the next chunks are a match
77
- // Let's check if we have enough words to clip by on both sides
78
- if (len > clipBy * 2) {
79
- return words.slice(0, clipBy).concat([
80
- ellipsis
81
- ], words.slice(-clipBy)).join(' ');
82
- }
83
- else {
84
- return curr.text;
85
- }
86
- }
87
- // We start to check the next and previous matches in order to
88
- // properly position the elipsis
89
- if (next && next.match) {
90
- // The chunk right after this one is a match
91
- // So we need the elipsis at the start of the returned text
92
- // so that it sticks correctly to the next (match)'s text
93
- return [ellipsis].concat(words.slice(-clipBy)).join(' ');
94
- }
95
- if (prev && prev.match) {
96
- // The chunk right before this one is a match
97
- // So we need the elipsis at the end of the returned text
98
- // so that it sticks correctly to the previous (match)'s text
99
- return words.slice(0, clipBy).concat([ellipsis]).join(' ');
100
- }
101
- // If we made it this far, just return the text
102
- return curr.text;
103
- }
104
-
105
- var hasLength = function (str) { return str.length > 0; };
106
- /**
107
- * Split a text into chunks denoting which are a match and which are not based on a user search term.
108
- * @param text String The text to split.
109
- * @param query String The query to split by. This can contain multiple words.
110
- * @param clipBy Number Clip the non-matches by a certain number of words to provide context around the matches.
111
- * @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.
112
- */
113
- var highlightWords = function (_a) {
114
- var text = _a.text, query = _a.query, clipBy = _a.clipBy, _b = _a.matchExactly, matchExactly = _b === void 0 ? false : _b;
115
- // Let's make sure that the user cannot pass in just a bunch of spaces
116
- query = query.trim();
117
- if (query === '') {
118
- return [
119
- {
120
- key: uuidv4(),
121
- text: text,
122
- match: false
123
- }
124
- ];
125
- }
126
- var searchRegexp = new RegExp(regexpQuery({ terms: query, matchExactly: matchExactly }), 'ig');
127
- return text
128
- .split(searchRegexp) // split the entire thing into an array of matches and non-matches
129
- .filter(hasLength) //filter any matches that have the text with length of 0
130
- .map(function (str) { return ({
131
- // compose the object for a match
132
- key: uuidv4(),
133
- text: str,
134
- match: matchExactly
135
- ? str.toLowerCase() === query.toLowerCase()
136
- : searchRegexp.test(str)
137
- }); })
138
- .map(function (chunk, index, chunks) { return (__assign({}, chunk, (clipBy && {
139
- // we only overwrite the text if there is a clip
140
- text: clip(__assign({ curr: chunk }, (index < chunks.length - 1 && { next: chunks[index + 1] }), (index > 0 && { prev: chunks[index - 1] }), { // if this wasn't the first chunk, set the previous chunk
141
- clipBy: clipBy }))
142
- }))); });
143
- };
144
-
145
- return highlightWords;
146
-
147
- }));
@@ -1 +0,0 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).HighlightWords=e()}(this,function(){"use strict";var t=function(){return(t=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++)for(var i in e=arguments[r])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)};function e(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var e=16*Math.random()|0;return("x"==t?e:3&e|8).toString(16)})}function r(t){var e=t.curr,r=t.next,n=t.prev,i=t.clipBy,c=void 0===i?3:i,x=e.text.split(" "),o=x.length;if(e.match||c>=o)return e.text;var a="...";return n&&n.match&&r&&r.match?o>2*c?x.slice(0,c).concat([a],x.slice(-c)).join(" "):e.text:r&&r.match?[a].concat(x.slice(-c)).join(" "):n&&n.match?x.slice(0,c).concat([a]).join(" "):e.text}var n=function(t){return t.length>0};return function(i){var c=i.text,x=i.query,o=i.clipBy,a=i.matchExactly,u=void 0!==a&&a;if(""===(x=x.trim()))return[{key:e(),text:c,match:!1}];var f=new RegExp(function(t){var e=t.terms,r=t.matchExactly,n=void 0!==r&&r;if("string"!=typeof e)throw new TypeError("Expected a string");var i=e.trim().replace(/[|\\{}()[\]^$+*?.-]/g,function(t){return"\\"+t});return"("+(n?i:i.split(" ").join("|"))+")"}({terms:x,matchExactly:u}),"ig");return c.split(f).filter(n).map(function(t){return{key:e(),text:t,match:u?t.toLowerCase()===x.toLowerCase():f.test(t)}}).map(function(e,n,i){return t({},e,o&&{text:r(t({curr:e},n<i.length-1&&{next:i[n+1]},n>0&&{prev:i[n-1]},{clipBy:o}))})})}});
@@ -1,10 +0,0 @@
1
- import { HighlightWords } from '.';
2
- /**
3
- * This provides context around a chunk's text, based on the next and previous chunks.
4
- * e.g. If we have the string "The quick brown fox jumped over the lazy dog",
5
- * and the search term "fox jumped", with a padding of 2, we want to have the end result be:
6
- * "... quick brown fox jumped over the ..."
7
- * The search term, "fox jumped" is left as is, and the left and right chunks, instead of having
8
- * the text in full, will be clipped.
9
- */
10
- export default function clip({ curr, next, prev, clipBy }: HighlightWords.Clip): string;
package/dist/lib/index.js DELETED
@@ -1,141 +0,0 @@
1
- 'use strict';
2
-
3
- /*! *****************************************************************************
4
- Copyright (c) Microsoft Corporation. All rights reserved.
5
- Licensed under the Apache License, Version 2.0 (the "License"); you may not use
6
- this file except in compliance with the License. You may obtain a copy of the
7
- License at http://www.apache.org/licenses/LICENSE-2.0
8
-
9
- THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
10
- KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
11
- WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
12
- MERCHANTABLITY OR NON-INFRINGEMENT.
13
-
14
- See the Apache Version 2.0 License for specific language governing permissions
15
- and limitations under the License.
16
- ***************************************************************************** */
17
-
18
- var __assign = function() {
19
- __assign = Object.assign || function __assign(t) {
20
- for (var s, i = 1, n = arguments.length; i < n; i++) {
21
- s = arguments[i];
22
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
23
- }
24
- return t;
25
- };
26
- return __assign.apply(this, arguments);
27
- };
28
-
29
- // https://stackoverflow.com/questions/26501688/a-typescript-guid-class
30
- function uuidv4() {
31
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
32
- var r = (Math.random() * 16) | 0; // tslint:disable-line no-bitwise
33
- return (c == 'x' ? r : (r & 0x3) | 0x8).toString(16); // tslint:disable-line no-bitwise
34
- });
35
- }
36
-
37
- // We need escape certain characters before creating the RegExp
38
- // https://github.com/sindresorhus/escape-string-regexp
39
- var escapeRegexp = function (term) {
40
- return term.replace(/[|\\{}()[\]^$+*?.-]/g, function (char) { return "\\" + char; });
41
- };
42
- var regexpQuery = function (_a) {
43
- var terms = _a.terms, _b = _a.matchExactly, matchExactly = _b === void 0 ? false : _b;
44
- if (typeof terms !== 'string') {
45
- throw new TypeError('Expected a string');
46
- }
47
- var escapedTerms = escapeRegexp(terms.trim());
48
- return "(" + (matchExactly ? escapedTerms : escapedTerms.split(' ').join('|')) + ")";
49
- };
50
-
51
- /**
52
- * This provides context around a chunk's text, based on the next and previous chunks.
53
- * e.g. If we have the string "The quick brown fox jumped over the lazy dog",
54
- * and the search term "fox jumped", with a padding of 2, we want to have the end result be:
55
- * "... quick brown fox jumped over the ..."
56
- * The search term, "fox jumped" is left as is, and the left and right chunks, instead of having
57
- * the text in full, will be clipped.
58
- */
59
- function clip(_a) {
60
- var curr = _a.curr, next = _a.next, prev = _a.prev, _b = _a.clipBy, clipBy = _b === void 0 ? 3 : _b;
61
- var words = curr.text.split(' ');
62
- var len = words.length;
63
- // If the current is a match, we leave it alone
64
- // Or if the clipBy is greater than or equal to the length of the words, there's nothing to clip
65
- if (curr.match || clipBy >= len) {
66
- return curr.text;
67
- }
68
- // If we have a clipBy greater than the length of the words in the current match,
69
- // it means we can clip the words in the current chunk
70
- var ellipsis = '...';
71
- if (prev && prev.match && next && next.match) {
72
- // Both the previous and the next chunks are a match
73
- // Let's check if we have enough words to clip by on both sides
74
- if (len > clipBy * 2) {
75
- return words.slice(0, clipBy).concat([
76
- ellipsis
77
- ], words.slice(-clipBy)).join(' ');
78
- }
79
- else {
80
- return curr.text;
81
- }
82
- }
83
- // We start to check the next and previous matches in order to
84
- // properly position the elipsis
85
- if (next && next.match) {
86
- // The chunk right after this one is a match
87
- // So we need the elipsis at the start of the returned text
88
- // so that it sticks correctly to the next (match)'s text
89
- return [ellipsis].concat(words.slice(-clipBy)).join(' ');
90
- }
91
- if (prev && prev.match) {
92
- // The chunk right before this one is a match
93
- // So we need the elipsis at the end of the returned text
94
- // so that it sticks correctly to the previous (match)'s text
95
- return words.slice(0, clipBy).concat([ellipsis]).join(' ');
96
- }
97
- // If we made it this far, just return the text
98
- return curr.text;
99
- }
100
-
101
- var hasLength = function (str) { return str.length > 0; };
102
- /**
103
- * Split a text into chunks denoting which are a match and which are not based on a user search term.
104
- * @param text String The text to split.
105
- * @param query String The query to split by. This can contain multiple words.
106
- * @param clipBy Number Clip the non-matches by a certain number of words to provide context around the matches.
107
- * @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.
108
- */
109
- var highlightWords = function (_a) {
110
- var text = _a.text, query = _a.query, clipBy = _a.clipBy, _b = _a.matchExactly, matchExactly = _b === void 0 ? false : _b;
111
- // Let's make sure that the user cannot pass in just a bunch of spaces
112
- query = query.trim();
113
- if (query === '') {
114
- return [
115
- {
116
- key: uuidv4(),
117
- text: text,
118
- match: false
119
- }
120
- ];
121
- }
122
- var searchRegexp = new RegExp(regexpQuery({ terms: query, matchExactly: matchExactly }), 'ig');
123
- return text
124
- .split(searchRegexp) // split the entire thing into an array of matches and non-matches
125
- .filter(hasLength) //filter any matches that have the text with length of 0
126
- .map(function (str) { return ({
127
- // compose the object for a match
128
- key: uuidv4(),
129
- text: str,
130
- match: matchExactly
131
- ? str.toLowerCase() === query.toLowerCase()
132
- : searchRegexp.test(str)
133
- }); })
134
- .map(function (chunk, index, chunks) { return (__assign({}, chunk, (clipBy && {
135
- // we only overwrite the text if there is a clip
136
- text: clip(__assign({ curr: chunk }, (index < chunks.length - 1 && { next: chunks[index + 1] }), (index > 0 && { prev: chunks[index - 1] }), { // if this wasn't the first chunk, set the previous chunk
137
- clipBy: clipBy }))
138
- }))); });
139
- };
140
-
141
- module.exports = highlightWords;
@@ -1,3 +0,0 @@
1
- import { HighlightWords } from './';
2
- declare const regexpQuery: ({ terms, matchExactly }: HighlightWords.Query) => string;
3
- export default regexpQuery;
@@ -1 +0,0 @@
1
- export default function uuidv4(): string;
@@ -1,10 +0,0 @@
1
- import { HighlightWords } from '.';
2
- /**
3
- * This provides context around a chunk's text, based on the next and previous chunks.
4
- * e.g. If we have the string "The quick brown fox jumped over the lazy dog",
5
- * and the search term "fox jumped", with a padding of 2, we want to have the end result be:
6
- * "... quick brown fox jumped over the ..."
7
- * The search term, "fox jumped" is left as is, and the left and right chunks, instead of having
8
- * the text in full, will be clipped.
9
- */
10
- export default function clip({ curr, next, prev, clipBy }: HighlightWords.Clip): string;
@@ -1,33 +0,0 @@
1
- declare namespace HighlightWords {
2
- interface Chunk {
3
- key: string;
4
- text: string;
5
- match: boolean;
6
- }
7
- interface Options {
8
- text: string;
9
- query: string;
10
- clipBy?: number;
11
- matchExactly?: boolean;
12
- }
13
- interface Clip {
14
- curr: Chunk;
15
- next: Chunk;
16
- prev: Chunk;
17
- clipBy?: number;
18
- }
19
- interface Query {
20
- terms: string;
21
- matchExactly?: boolean;
22
- }
23
- }
24
- export { HighlightWords };
25
- /**
26
- * Split a text into chunks denoting which are a match and which are not based on a user search term.
27
- * @param text String The text to split.
28
- * @param query String The query to split by. This can contain multiple words.
29
- * @param clipBy Number Clip the non-matches by a certain number of words to provide context around the matches.
30
- * @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.
31
- */
32
- declare const highlightWords: ({ text, query, clipBy, matchExactly }: HighlightWords.Options) => HighlightWords.Chunk[];
33
- export default highlightWords;
@@ -1,139 +0,0 @@
1
- /*! *****************************************************************************
2
- Copyright (c) Microsoft Corporation. All rights reserved.
3
- Licensed under the Apache License, Version 2.0 (the "License"); you may not use
4
- this file except in compliance with the License. You may obtain a copy of the
5
- License at http://www.apache.org/licenses/LICENSE-2.0
6
-
7
- THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
8
- KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
9
- WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
10
- MERCHANTABLITY OR NON-INFRINGEMENT.
11
-
12
- See the Apache Version 2.0 License for specific language governing permissions
13
- and limitations under the License.
14
- ***************************************************************************** */
15
-
16
- var __assign = function() {
17
- __assign = Object.assign || function __assign(t) {
18
- for (var s, i = 1, n = arguments.length; i < n; i++) {
19
- s = arguments[i];
20
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
21
- }
22
- return t;
23
- };
24
- return __assign.apply(this, arguments);
25
- };
26
-
27
- // https://stackoverflow.com/questions/26501688/a-typescript-guid-class
28
- function uuidv4() {
29
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
30
- var r = (Math.random() * 16) | 0; // tslint:disable-line no-bitwise
31
- return (c == 'x' ? r : (r & 0x3) | 0x8).toString(16); // tslint:disable-line no-bitwise
32
- });
33
- }
34
-
35
- // We need escape certain characters before creating the RegExp
36
- // https://github.com/sindresorhus/escape-string-regexp
37
- var escapeRegexp = function (term) {
38
- return term.replace(/[|\\{}()[\]^$+*?.-]/g, function (char) { return "\\" + char; });
39
- };
40
- var regexpQuery = function (_a) {
41
- var terms = _a.terms, _b = _a.matchExactly, matchExactly = _b === void 0 ? false : _b;
42
- if (typeof terms !== 'string') {
43
- throw new TypeError('Expected a string');
44
- }
45
- var escapedTerms = escapeRegexp(terms.trim());
46
- return "(" + (matchExactly ? escapedTerms : escapedTerms.split(' ').join('|')) + ")";
47
- };
48
-
49
- /**
50
- * This provides context around a chunk's text, based on the next and previous chunks.
51
- * e.g. If we have the string "The quick brown fox jumped over the lazy dog",
52
- * and the search term "fox jumped", with a padding of 2, we want to have the end result be:
53
- * "... quick brown fox jumped over the ..."
54
- * The search term, "fox jumped" is left as is, and the left and right chunks, instead of having
55
- * the text in full, will be clipped.
56
- */
57
- function clip(_a) {
58
- var curr = _a.curr, next = _a.next, prev = _a.prev, _b = _a.clipBy, clipBy = _b === void 0 ? 3 : _b;
59
- var words = curr.text.split(' ');
60
- var len = words.length;
61
- // If the current is a match, we leave it alone
62
- // Or if the clipBy is greater than or equal to the length of the words, there's nothing to clip
63
- if (curr.match || clipBy >= len) {
64
- return curr.text;
65
- }
66
- // If we have a clipBy greater than the length of the words in the current match,
67
- // it means we can clip the words in the current chunk
68
- var ellipsis = '...';
69
- if (prev && prev.match && next && next.match) {
70
- // Both the previous and the next chunks are a match
71
- // Let's check if we have enough words to clip by on both sides
72
- if (len > clipBy * 2) {
73
- return words.slice(0, clipBy).concat([
74
- ellipsis
75
- ], words.slice(-clipBy)).join(' ');
76
- }
77
- else {
78
- return curr.text;
79
- }
80
- }
81
- // We start to check the next and previous matches in order to
82
- // properly position the elipsis
83
- if (next && next.match) {
84
- // The chunk right after this one is a match
85
- // So we need the elipsis at the start of the returned text
86
- // so that it sticks correctly to the next (match)'s text
87
- return [ellipsis].concat(words.slice(-clipBy)).join(' ');
88
- }
89
- if (prev && prev.match) {
90
- // The chunk right before this one is a match
91
- // So we need the elipsis at the end of the returned text
92
- // so that it sticks correctly to the previous (match)'s text
93
- return words.slice(0, clipBy).concat([ellipsis]).join(' ');
94
- }
95
- // If we made it this far, just return the text
96
- return curr.text;
97
- }
98
-
99
- var hasLength = function (str) { return str.length > 0; };
100
- /**
101
- * Split a text into chunks denoting which are a match and which are not based on a user search term.
102
- * @param text String The text to split.
103
- * @param query String The query to split by. This can contain multiple words.
104
- * @param clipBy Number Clip the non-matches by a certain number of words to provide context around the matches.
105
- * @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.
106
- */
107
- var highlightWords = function (_a) {
108
- var text = _a.text, query = _a.query, clipBy = _a.clipBy, _b = _a.matchExactly, matchExactly = _b === void 0 ? false : _b;
109
- // Let's make sure that the user cannot pass in just a bunch of spaces
110
- query = query.trim();
111
- if (query === '') {
112
- return [
113
- {
114
- key: uuidv4(),
115
- text: text,
116
- match: false
117
- }
118
- ];
119
- }
120
- var searchRegexp = new RegExp(regexpQuery({ terms: query, matchExactly: matchExactly }), 'ig');
121
- return text
122
- .split(searchRegexp) // split the entire thing into an array of matches and non-matches
123
- .filter(hasLength) //filter any matches that have the text with length of 0
124
- .map(function (str) { return ({
125
- // compose the object for a match
126
- key: uuidv4(),
127
- text: str,
128
- match: matchExactly
129
- ? str.toLowerCase() === query.toLowerCase()
130
- : searchRegexp.test(str)
131
- }); })
132
- .map(function (chunk, index, chunks) { return (__assign({}, chunk, (clipBy && {
133
- // we only overwrite the text if there is a clip
134
- text: clip(__assign({ curr: chunk }, (index < chunks.length - 1 && { next: chunks[index + 1] }), (index > 0 && { prev: chunks[index - 1] }), { // if this wasn't the first chunk, set the previous chunk
135
- clipBy: clipBy }))
136
- }))); });
137
- };
138
-
139
- export default highlightWords;
@@ -1,3 +0,0 @@
1
- import { HighlightWords } from './';
2
- declare const regexpQuery: ({ terms, matchExactly }: HighlightWords.Query) => string;
3
- export default regexpQuery;
@@ -1 +0,0 @@
1
- export default function uuidv4(): string;