highlight-words 1.2.2 → 2.0.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/Readme.md CHANGED
@@ -7,7 +7,7 @@ Give it a piece of text and a search query, and it splits it into chunks separat
7
7
  ## Installation
8
8
 
9
9
  ```
10
- yarn add highlight-words
10
+ pnpm add highlight-words
11
11
  ```
12
12
 
13
13
  ```
@@ -2,47 +2,6 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
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 termsToRegExpString = (terms) => terms.replace(/\s{2,}/g, " ").split(" ").join("|");
21
- const regexpQuery = ({
22
- terms,
23
- matchExactly = false
24
- }) => {
25
- if (typeof terms !== "string") {
26
- throw new TypeError("Expected a string");
27
- }
28
- const escapedTerms = escapeRegexp(terms.trim());
29
- return `(${matchExactly ? escapedTerms : termsToRegExpString(escapedTerms)})`;
30
- };
31
- const buildRegexp = ({
32
- terms,
33
- matchExactly = false
34
- }) => {
35
- try {
36
- const fromString = /^([/~@;%#'])(.*?)\1([gimsuy]*)$/.exec(terms);
37
- if (fromString) {
38
- return new RegExp(fromString[2], fromString[3]);
39
- }
40
- return new RegExp(regexpQuery({ terms, matchExactly }), "ig");
41
- } catch (e) {
42
- throw new TypeError("Expected terms to be either a string or a RegExp!");
43
- }
44
- };
45
-
46
5
  const hasProp = (prop) => (obj) => obj !== null && typeof obj === "object" && prop in obj;
47
6
  const hasMatch = hasProp("match");
48
7
  const chunkExists = (chunk) => typeof chunk !== "undefined";
@@ -77,25 +36,47 @@ function clip({
77
36
  return curr.text;
78
37
  }
79
38
 
80
- var __defProp = Object.defineProperty;
81
- var __defProps = Object.defineProperties;
82
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
83
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
84
- var __hasOwnProp = Object.prototype.hasOwnProperty;
85
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
86
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
87
- var __spreadValues = (a, b) => {
88
- for (var prop in b || (b = {}))
89
- if (__hasOwnProp.call(b, prop))
90
- __defNormalProp(a, prop, b[prop]);
91
- if (__getOwnPropSymbols)
92
- for (var prop of __getOwnPropSymbols(b)) {
93
- if (__propIsEnum.call(b, prop))
94
- __defNormalProp(a, prop, b[prop]);
39
+ const escapeRegexp = (term) => term.replace(/[|\\{}()[\]^$+*?.-]/g, (char) => `\\${char}`);
40
+ const termsToRegExpString = (terms) => terms.replace(/\s{2,}/g, " ").split(" ").join("|");
41
+ const regexpQuery = ({
42
+ terms,
43
+ matchExactly = false
44
+ }) => {
45
+ if (typeof terms !== "string") {
46
+ throw new TypeError("Expected a string");
47
+ }
48
+ const escapedTerms = escapeRegexp(terms.trim());
49
+ return `(${matchExactly ? escapedTerms : termsToRegExpString(escapedTerms)})`;
50
+ };
51
+ const buildRegexp = ({
52
+ terms,
53
+ matchExactly = false
54
+ }) => {
55
+ try {
56
+ const fromString = /^([/~@;%#'])(.*?)\1([gimsuy]*)$/.exec(terms);
57
+ if (fromString) {
58
+ return new RegExp(fromString[2], fromString[3]);
95
59
  }
96
- return a;
60
+ return new RegExp(regexpQuery({ terms, matchExactly }), "ig");
61
+ } catch {
62
+ throw new TypeError("Expected terms to be either a string or a RegExp!");
63
+ }
97
64
  };
98
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
65
+
66
+ let IDX = 36;
67
+ let HEX = "";
68
+ while (IDX--) {
69
+ HEX += IDX.toString(36);
70
+ }
71
+ function uid(len = 11) {
72
+ let str = "";
73
+ let num = len;
74
+ while (num--) {
75
+ str += HEX[Math.random() * 36 | 0];
76
+ }
77
+ return str;
78
+ }
79
+
99
80
  const hasLength = (str) => str.length > 0;
100
81
  const highlightWords = ({
101
82
  text,
@@ -119,14 +100,22 @@ const highlightWords = ({
119
100
  key: uid(),
120
101
  text: str,
121
102
  match: matchExactly ? str.toLowerCase() === safeQuery.toLowerCase() : searchRegexp.test(str)
122
- })).map((chunk, index, chunks) => __spreadValues(__spreadValues({}, chunk), typeof clipBy === "number" && {
123
- // We only overwrite the text if there is a clip
124
- text: clip(__spreadProps(__spreadValues(__spreadValues({
125
- curr: chunk
126
- }, index < chunks.length - 1 && { next: chunks[index + 1] }), index > 0 && { prev: chunks[index - 1] }), {
127
- // If this wasn't the first chunk, set the previous chunk
128
- clipBy
129
- }))
103
+ })).map((chunk, index, chunks) => ({
104
+ // For each chunk, clip the text if needed
105
+ ...chunk,
106
+ // All the props first
107
+ ...typeof clipBy === "number" && {
108
+ // We only overwrite the text if there is a clip
109
+ text: clip({
110
+ curr: chunk,
111
+ // We need the current chunk
112
+ ...index < chunks.length - 1 && { next: chunks[index + 1] },
113
+ // If this wasn't the last chunk, set the next chunk
114
+ ...index > 0 && { prev: chunks[index - 1] },
115
+ // If this wasn't the first chunk, set the previous chunk
116
+ clipBy
117
+ })
118
+ }
130
119
  }));
131
120
  };
132
121
 
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});let u=36,f="";for(;u--;)f+=u.toString(36);function m(t=11){let e="",r=t;for(;r--;)e+=f[Math.random()*36|0];return e}const h=t=>t.replace(/[|\\{}()[\]^$+*?.-]/g,e=>`\\${e}`),b=t=>t.replace(/\s{2,}/g," ").split(" ").join("|"),E=({terms:t,matchExactly:e=!1})=>{if(typeof t!="string")throw new TypeError("Expected a string");const r=h(t.trim());return`(${e?r:b(r)})`},j=({terms:t,matchExactly:e=!1})=>{try{const r=/^([/~@;%#'])(.*?)\1([gimsuy]*)$/.exec(t);return r?new RegExp(r[2],r[3]):new RegExp(E({terms:t,matchExactly:e}),"ig")}catch{throw new TypeError("Expected terms to be either a string or a RegExp!")}},w=t=>e=>e!==null&&typeof e=="object"&&t in e,l=w("match"),p=t=>typeof t<"u";function d({curr:t,next:e,prev:r,clipBy:n=3}){const o=t.text.split(" "),s=o.length;if(t.match||n>=s)return t.text;const c="...";return p(e)&&p(r)&&l(r)&&l(e)?s>n*2?[...o.slice(0,n),c,...o.slice(-n)].join(" "):t.text:p(e)&&l(e)?[c,...o.slice(-n)].join(" "):p(r)&&l(r)?[...o.slice(0,n),c].join(" "):t.text}var v=Object.defineProperty,O=Object.defineProperties,$=Object.getOwnPropertyDescriptors,g=Object.getOwnPropertySymbols,P=Object.prototype.hasOwnProperty,R=Object.prototype.propertyIsEnumerable,x=(t,e,r)=>e in t?v(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,i=(t,e)=>{for(var r in e||(e={}))P.call(e,r)&&x(t,r,e[r]);if(g)for(var r of g(e))R.call(e,r)&&x(t,r,e[r]);return t},B=(t,e)=>O(t,$(e));const C=t=>t.length>0,k=({text:t,query:e,clipBy:r,matchExactly:n=!1})=>{const o=typeof e=="string"?e.trim():e;if(o==="")return[{key:m(),text:t,match:!1}];const s=j({terms:e,matchExactly:n});return t.split(s).filter(C).map(c=>({key:m(),text:c,match:n?c.toLowerCase()===o.toLowerCase():s.test(c)})).map((c,a,y)=>i(i({},c),typeof r=="number"&&{text:d(B(i(i({curr:c},a<y.length-1&&{next:y[a+1]}),a>0&&{prev:y[a-1]}),{clipBy:r}))}))};exports.default=k;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});const y=t=>e=>e!==null&&typeof e=="object"&&t in e,i=y("match"),a=t=>typeof t<"u";function h({curr:t,next:e,prev:r,clipBy:n=3}){const o=t.text.split(" "),s=o.length;if(t.match||n>=s)return t.text;const c="...";return a(e)&&a(r)&&i(r)&&i(e)?s>n*2?[...o.slice(0,n),c,...o.slice(-n)].join(" "):t.text:a(e)&&i(e)?[c,...o.slice(-n)].join(" "):a(r)&&i(r)?[...o.slice(0,n),c].join(" "):t.text}const g=t=>t.replace(/[|\\{}()[\]^$+*?.-]/g,e=>`\\${e}`),f=t=>t.replace(/\s{2,}/g," ").split(" ").join("|"),E=({terms:t,matchExactly:e=!1})=>{if(typeof t!="string")throw new TypeError("Expected a string");const r=g(t.trim());return`(${e?r:f(r)})`},w=({terms:t,matchExactly:e=!1})=>{try{const r=/^([/~@;%#'])(.*?)\1([gimsuy]*)$/.exec(t);return r?new RegExp(r[2],r[3]):new RegExp(E({terms:t,matchExactly:e}),"ig")}catch{throw new TypeError("Expected terms to be either a string or a RegExp!")}};let m=36,u="";for(;m--;)u+=m.toString(36);function x(t=11){let e="",r=t;for(;r--;)e+=u[Math.random()*36|0];return e}const d=t=>t.length>0,j=({text:t,query:e,clipBy:r,matchExactly:n=!1})=>{const o=typeof e=="string"?e.trim():e;if(o==="")return[{key:x(),text:t,match:!1}];const s=w({terms:e,matchExactly:n});return t.split(s).filter(d).map(c=>({key:x(),text:c,match:n?c.toLowerCase()===o.toLowerCase():s.test(c)})).map((c,l,p)=>({...c,...typeof r=="number"&&{text:h({curr:c,...l<p.length-1&&{next:p[l+1]},...l>0&&{prev:p[l-1]},clipBy:r})}}))};exports.default=j;
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 termsToRegExpString = (terms: string): string =>\n terms\n .replace(/\\s{2,}/g, ' ')\n .split(' ')\n .join('|');\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 =\n <T>(prop: string) =>\n (obj: T) =>\n obj !== null && typeof obj === 'object' && 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":["IDX","HEX","uid","len","str","num","escapeRegexp","term","char","termsToRegExpString","terms","regexpQuery","matchExactly","escapedTerms","buildRegexp","fromString","hasProp","prop","obj","hasMatch","chunkExists","chunk","clip","curr","next","prev","clipBy","words","ellipsis","u","f","y","p","d","C","g","n","m","hasLength","highlightWords","text","query","safeQuery","searchRegexp","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EAAI,OAAS,EASnDmC,EAAiB,CAAC,CACtB,KAAAC,EACA,MAAAC,EACA,OAAAf,EACA,aAAAd,EAAe,EACjB,IAAgE,CAE9D,MAAM8B,EAAY,OAAOD,GAAU,SAAWA,EAAM,KAASA,EAAAA,EAE7D,GAAIC,IAAc,GAChB,MAAO,CACL,CACE,IAAKxC,IACL,KAAAsC,EACA,MAAO,EACT,CACF,EAGF,MAAMG,EAAe7B,EAAY,CAAE,MAAO2B,EAAO,aAAA7B,CAAa,CAAC,EAI/D,OAAO4B,EACJ,MAAMG,CAAY,EAClB,OAAOL,CAAS,EAChB,IAAKlC,IAAS,CAEb,IAAKF,IACL,KAAME,EACN,MAAOQ,EACHR,EAAI,YAAkBsC,IAAAA,EAAU,cAChCC,EAAa,KAAKvC,CAAG,CAC3B,EAAE,EACD,IAAI,CAACiB,EAAsBuB,EAAOC,IAAsCC,EAAAA,EAAA,CAAA,EAEpEzB,CAAAA,EACC,OAAOK,GAAW,UAAY,CAEhC,KAAMJ,EAAKyB,EAAAD,EAAAV,EAAA,CACT,KAAMf,CAAAA,EACFuB,EAAQC,EAAO,OAAS,GAAK,CAAE,KAAMA,EAAOD,EAAQ,CAAC,CAAE,CACvDA,EAAAA,EAAQ,GAAK,CAAE,KAAMC,EAAOD,EAAQ,CAAC,CAAE,CAHlC,EAAA,CAIT,OAAAlB,CACF,CAAC,CAAA,CACH,CACA,CAAA,CACN"}
1
+ {"version":3,"file":"highlight-words.min.js","sources":["../src/clip.ts","../src/regexp.ts","../src/uid.ts","../src/index.ts"],"sourcesContent":["/* eslint complexity: [\"error\", { \"max\": 12 }] */\nimport type { HighlightWords } from '.';\n\nconst hasProp =\n <T>(prop: string) =>\n (obj: T) =>\n obj !== null && typeof obj === 'object' && 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 type { HighlightWords } from '.';\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 terms\n .replace(/\\s{2,}/g, ' ')\n .split(' ')\n .join('|');\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","// 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 clip from './clip';\nimport buildRegexp from './regexp';\nimport uid from './uid';\n\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>;\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":["hasProp","prop","obj","hasMatch","chunkExists","chunk","clip","curr","next","prev","clipBy","words","len","ellipsis","escapeRegexp","term","char","termsToRegExpString","terms","regexpQuery","matchExactly","escapedTerms","buildRegexp","fromString","IDX","HEX","uid","str","num","hasLength","highlightWords","text","query","safeQuery","searchRegexp","index","chunks"],"mappings":"oEAGA,MAAMA,EACAC,GACHC,GACCA,IAAQ,MAAQ,OAAOA,GAAQ,UAAYD,KAAQC,EACjDC,EAAWH,EAA8B,OAAO,EAEhDI,EACJC,GACkC,OAAOA,EAAU,IAUrD,SAAwB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ACF,EAAE,CACN"}
@@ -1,2 +1,2 @@
1
- let m=36,f="";for(;m--;)f+=m.toString(36);function u(t=11){let e="",r=t;for(;r--;)e+=f[Math.random()*36|0];return e}const h=t=>t.replace(/[|\\{}()[\]^$+*?.-]/g,e=>`\\${e}`),b=t=>t.replace(/\s{2,}/g," ").split(" ").join("|"),E=({terms:t,matchExactly:e=!1})=>{if(typeof t!="string")throw new TypeError("Expected a string");const r=h(t.trim());return`(${e?r:b(r)})`},w=({terms:t,matchExactly:e=!1})=>{try{const r=/^([/~@;%#'])(.*?)\1([gimsuy]*)$/.exec(t);return r?new RegExp(r[2],r[3]):new RegExp(E({terms:t,matchExactly:e}),"ig")}catch{throw new TypeError("Expected terms to be either a string or a RegExp!")}},j=t=>e=>e!==null&&typeof e=="object"&&t in e,p=j("match"),l=t=>typeof t<"u";function v({curr:t,next:e,prev:r,clipBy:n=3}){const o=t.text.split(" "),a=o.length;if(t.match||n>=a)return t.text;const c="...";return l(e)&&l(r)&&p(r)&&p(e)?a>n*2?[...o.slice(0,n),c,...o.slice(-n)].join(" "):t.text:l(e)&&p(e)?[c,...o.slice(-n)].join(" "):l(r)&&p(r)?[...o.slice(0,n),c].join(" "):t.text}var d=Object.defineProperty,O=Object.defineProperties,$=Object.getOwnPropertyDescriptors,x=Object.getOwnPropertySymbols,P=Object.prototype.hasOwnProperty,R=Object.prototype.propertyIsEnumerable,g=(t,e,r)=>e in t?d(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,i=(t,e)=>{for(var r in e||(e={}))P.call(e,r)&&g(t,r,e[r]);if(x)for(var r of x(e))R.call(e,r)&&g(t,r,e[r]);return t},B=(t,e)=>O(t,$(e));const C=t=>t.length>0,k=({text:t,query:e,clipBy:r,matchExactly:n=!1})=>{const o=typeof e=="string"?e.trim():e;if(o==="")return[{key:u(),text:t,match:!1}];const a=w({terms:e,matchExactly:n});return t.split(a).filter(C).map(c=>({key:u(),text:c,match:n?c.toLowerCase()===o.toLowerCase():a.test(c)})).map((c,s,y)=>i(i({},c),typeof r=="number"&&{text:v(B(i(i({curr:c},s<y.length-1&&{next:y[s+1]}),s>0&&{prev:y[s-1]}),{clipBy:r}))}))};export{k as default};
1
+ const h=t=>e=>e!==null&&typeof e=="object"&&t in e,a=h("match"),i=t=>typeof t<"u";function g({curr:t,next:e,prev:r,clipBy:n=3}){const o=t.text.split(" "),s=o.length;if(t.match||n>=s)return t.text;const c="...";return i(e)&&i(r)&&a(r)&&a(e)?s>n*2?[...o.slice(0,n),c,...o.slice(-n)].join(" "):t.text:i(e)&&a(e)?[c,...o.slice(-n)].join(" "):i(r)&&a(r)?[...o.slice(0,n),c].join(" "):t.text}const u=t=>t.replace(/[|\\{}()[\]^$+*?.-]/g,e=>`\\${e}`),f=t=>t.replace(/\s{2,}/g," ").split(" ").join("|"),E=({terms:t,matchExactly:e=!1})=>{if(typeof t!="string")throw new TypeError("Expected a string");const r=u(t.trim());return`(${e?r:f(r)})`},w=({terms:t,matchExactly:e=!1})=>{try{const r=/^([/~@;%#'])(.*?)\1([gimsuy]*)$/.exec(t);return r?new RegExp(r[2],r[3]):new RegExp(E({terms:t,matchExactly:e}),"ig")}catch{throw new TypeError("Expected terms to be either a string or a RegExp!")}};let m=36,x="";for(;m--;)x+=m.toString(36);function y(t=11){let e="",r=t;for(;r--;)e+=x[Math.random()*36|0];return e}const j=t=>t.length>0,d=({text:t,query:e,clipBy:r,matchExactly:n=!1})=>{const o=typeof e=="string"?e.trim():e;if(o==="")return[{key:y(),text:t,match:!1}];const s=w({terms:e,matchExactly:n});return t.split(s).filter(j).map(c=>({key:y(),text:c,match:n?c.toLowerCase()===o.toLowerCase():s.test(c)})).map((c,l,p)=>({...c,...typeof r=="number"&&{text:g({curr:c,...l<p.length-1&&{next:p[l+1]},...l>0&&{prev:p[l-1]},clipBy:r})}}))};export{d as 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 termsToRegExpString = (terms: string): string =>\n terms\n .replace(/\\s{2,}/g, ' ')\n .split(' ')\n .join('|');\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 =\n <T>(prop: string) =>\n (obj: T) =>\n obj !== null && typeof obj === 'object' && 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":["IDX","HEX","uid","len","str","num","escapeRegexp","term","char","termsToRegExpString","terms","regexpQuery","matchExactly","escapedTerms","buildRegexp","fromString","hasProp","prop","obj","hasMatch","chunkExists","chunk","clip","curr","next","prev","clipBy","words","ellipsis","u","f","y","p","d","C","n","m","hasLength","highlightWords","text","query","safeQuery","searchRegexp","index","chunks","__spreadValues","__spreadProps"],"mappings":"AAIA,IAAIA,EAAM,GACNC,EAAM,GACV,KAAOD,KACLC,GAAOD,EAAI,SAAS,EAAE,EAGAE,SAAAA,EAAIC,EAAM,GAAY,CAC5C,IAAIC,EAAM,GACNC,EAAMF,EACV,KAAOE,KACLD,GAAOH,EAAK,KAAK,OAAW,EAAA,GAAM,CAAC,EAErC,OAAOG,CACT,CCbA,MAAME,EAAgBC,GACpBA,EAAK,QAAQ,uBAAyBC,GAAiB,KAAKA,GAAM,EAE9DC,EAAuBC,GAC3BA,EACG,QAAQ,UAAW,GAAG,EACtB,MAAM,GAAG,EACT,KAAK,GAAG,EAEPC,EAAc,CAAC,CACnB,MAAAD,EACA,aAAAE,EAAe,EACjB,IAA8C,CAC5C,GAAI,OAAOF,GAAU,SACnB,MAAM,IAAI,UAAU,mBAAmB,EAGzC,MAAMG,EAAeP,EAAaI,EAAM,KAAK,CAAC,EAC9C,MAAO,IAAIE,EAAeC,EAAeJ,EAAoBI,CAAY,IAC3E,EAEMC,EAAc,CAAC,CACnB,MAAAJ,EACA,aAAAE,EAAe,EACjB,IAA8C,CAC5C,GAAI,CACF,MAAMG,EAAa,kCAAkC,KAAKL,CAAK,EAC/D,OAAIK,EACK,IAAI,OAAOA,EAAW,CAAC,EAAGA,EAAW,CAAC,CAAC,EAGzC,IAAI,OAAOJ,EAAY,CAAE,MAAAD,EAAO,aAAAE,CAAa,CAAC,EAAG,IAAI,CAC9D,OACE,MAAM,IA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regexp.ts","../src/uid.ts","../src/index.ts"],"sourcesContent":["/* eslint complexity: [\"error\", { \"max\": 12 }] */\nimport type { HighlightWords } from '.';\n\nconst hasProp =\n <T>(prop: string) =>\n (obj: T) =>\n obj !== null && typeof obj === 'object' && 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 type { HighlightWords } from '.';\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 terms\n .replace(/\\s{2,}/g, ' ')\n .split(' ')\n .join('|');\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","// 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 clip from './clip';\nimport buildRegexp from './regexp';\nimport uid from './uid';\n\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>;\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":["hasProp","prop","obj","hasMatch","chunkExists","chunk","clip","curr","next","prev","clipBy","words","len","ellipsis","escapeRegexp","term","char","termsToRegExpString","terms","regexpQuery","matchExactly","escapedTerms","buildRegexp","fromString","IDX","HEX","uid","str","num","hasLength","highlightWords","text","query","safeQuery","searchRegexp","index","chunks"],"mappings":"AAGA,MAAMA,EACAC,GACHC,GACCA,IAAQ,MAAQ,OAAOA,GAAQ,UAAYD,KAAQC,EACjDC,EAAWH,EAA8B,OAAO,EAEhDI,EACJC,GACkC,OAAOA,EAAU,IAUrD,SAAwBC,EAAK,CAC3B,KAAAC,EACA,KAAAC,EACA,KAAAC,EACA,OAAAC,EAAS,CACX,EAAgC,CAC9B,MAAMC,EAAQJ,EAAK,KAAK,MAAM,GAAG,EAC3BK,EAAMD,EAAM,OAIlB,GAAIJ,EAAK,OAASG,GAAUE,EAC1B,OAAOL,EAAK,KAKd,MAAMM,EAAW,MAEjB,OACET,EAAYI,CAAI,GAChBJ,EAAYK,CAAI,GAChBN,EAASM,CAAI,GACbN,EAASK,CAAI,EAITI,EAAMF,EAAS,EACV,CACL,GAAGC,EAAM,MAAM,EAAGD,CAAM,EACxBG,EACA,GAAGF,EAAM,MAAM,CAACD,CAAM,CACxB,EAAE,KAAK,GAAG,EAGLH,EAAK,KAKVH,EAAYI,CAAI,GAAKL,EAASK,CAAI,EAI7B,CAACK,EAAU,GAAGF,EAAM,MAAM,CAACD,CAAM,CAAC,EAAE,KAAK,GAAG,EAGjDN,EAAYK,CAAI,GAAKN,EAASM,CAAI,EAI7B,CAAC,GAAGE,EAAM,MAAM,EAAGD,CAAM,EAAGG,CAAQ,EAAE,KAAK,GAAG,EAIhDN,EAAK,IACd,CCzEA,MAAMO,EAAgBC,GACpBA,EAAK,QAAQ,uBAAyBC,GAAiB,KAAKA,CAAI,EAAE,EAE9DC,EAAuBC,GAC3BA,EACG,QAAQ,UAAW,GAAG,EACtB,MAAM,GAAG,EACT,KAAK,GAAG,EAEPC,EAAc,CAAC,CACnB,MAAAD,EACA,aAAAE,EAAe,EACjB,IAA8C,C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AAE,EACD,IAAI,CAACtB,EAAsB8B,EAAOC,KAAsC,CAEvE,GAAG/B,EACH,GAAI,OAAOK,GAAW,UAAY,CAEhC,KAAMJ,EAAK,CACT,KAAMD,EACN,GAAI8B,EAAQC,EAAO,OAAS,GAAK,CAAE,KAAMA,EAAOD,EAAQ,CAAC,CAAE,EAC3D,GAAIA,EAAQ,GAAK,CAAE,KAAMC,EAAOD,EAAQ,CAAC,CAAE,EAC3C,OAAAzB,CACF,CAAC,CACH,CACF,EAAE,CACN"}
@@ -1,44 +1,3 @@
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 termsToRegExpString = (terms) => terms.replace(/\s{2,}/g, " ").split(" ").join("|");
17
- const regexpQuery = ({
18
- terms,
19
- matchExactly = false
20
- }) => {
21
- if (typeof terms !== "string") {
22
- throw new TypeError("Expected a string");
23
- }
24
- const escapedTerms = escapeRegexp(terms.trim());
25
- return `(${matchExactly ? escapedTerms : termsToRegExpString(escapedTerms)})`;
26
- };
27
- const buildRegexp = ({
28
- terms,
29
- matchExactly = false
30
- }) => {
31
- try {
32
- const fromString = /^([/~@;%#'])(.*?)\1([gimsuy]*)$/.exec(terms);
33
- if (fromString) {
34
- return new RegExp(fromString[2], fromString[3]);
35
- }
36
- return new RegExp(regexpQuery({ terms, matchExactly }), "ig");
37
- } catch (e) {
38
- throw new TypeError("Expected terms to be either a string or a RegExp!");
39
- }
40
- };
41
-
42
1
  const hasProp = (prop) => (obj) => obj !== null && typeof obj === "object" && prop in obj;
43
2
  const hasMatch = hasProp("match");
44
3
  const chunkExists = (chunk) => typeof chunk !== "undefined";
@@ -73,25 +32,47 @@ function clip({
73
32
  return curr.text;
74
33
  }
75
34
 
76
- var __defProp = Object.defineProperty;
77
- var __defProps = Object.defineProperties;
78
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
79
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
80
- var __hasOwnProp = Object.prototype.hasOwnProperty;
81
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
82
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
83
- var __spreadValues = (a, b) => {
84
- for (var prop in b || (b = {}))
85
- if (__hasOwnProp.call(b, prop))
86
- __defNormalProp(a, prop, b[prop]);
87
- if (__getOwnPropSymbols)
88
- for (var prop of __getOwnPropSymbols(b)) {
89
- if (__propIsEnum.call(b, prop))
90
- __defNormalProp(a, prop, b[prop]);
35
+ const escapeRegexp = (term) => term.replace(/[|\\{}()[\]^$+*?.-]/g, (char) => `\\${char}`);
36
+ const termsToRegExpString = (terms) => terms.replace(/\s{2,}/g, " ").split(" ").join("|");
37
+ const regexpQuery = ({
38
+ terms,
39
+ matchExactly = false
40
+ }) => {
41
+ if (typeof terms !== "string") {
42
+ throw new TypeError("Expected a string");
43
+ }
44
+ const escapedTerms = escapeRegexp(terms.trim());
45
+ return `(${matchExactly ? escapedTerms : termsToRegExpString(escapedTerms)})`;
46
+ };
47
+ const buildRegexp = ({
48
+ terms,
49
+ matchExactly = false
50
+ }) => {
51
+ try {
52
+ const fromString = /^([/~@;%#'])(.*?)\1([gimsuy]*)$/.exec(terms);
53
+ if (fromString) {
54
+ return new RegExp(fromString[2], fromString[3]);
91
55
  }
92
- return a;
56
+ return new RegExp(regexpQuery({ terms, matchExactly }), "ig");
57
+ } catch {
58
+ throw new TypeError("Expected terms to be either a string or a RegExp!");
59
+ }
93
60
  };
94
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
61
+
62
+ let IDX = 36;
63
+ let HEX = "";
64
+ while (IDX--) {
65
+ HEX += IDX.toString(36);
66
+ }
67
+ function uid(len = 11) {
68
+ let str = "";
69
+ let num = len;
70
+ while (num--) {
71
+ str += HEX[Math.random() * 36 | 0];
72
+ }
73
+ return str;
74
+ }
75
+
95
76
  const hasLength = (str) => str.length > 0;
96
77
  const highlightWords = ({
97
78
  text,
@@ -115,14 +96,22 @@ const highlightWords = ({
115
96
  key: uid(),
116
97
  text: str,
117
98
  match: matchExactly ? str.toLowerCase() === safeQuery.toLowerCase() : searchRegexp.test(str)
118
- })).map((chunk, index, chunks) => __spreadValues(__spreadValues({}, chunk), typeof clipBy === "number" && {
119
- // We only overwrite the text if there is a clip
120
- text: clip(__spreadProps(__spreadValues(__spreadValues({
121
- curr: chunk
122
- }, index < chunks.length - 1 && { next: chunks[index + 1] }), index > 0 && { prev: chunks[index - 1] }), {
123
- // If this wasn't the first chunk, set the previous chunk
124
- clipBy
125
- }))
99
+ })).map((chunk, index, chunks) => ({
100
+ // For each chunk, clip the text if needed
101
+ ...chunk,
102
+ // All the props first
103
+ ...typeof clipBy === "number" && {
104
+ // We only overwrite the text if there is a clip
105
+ text: clip({
106
+ curr: chunk,
107
+ // We need the current chunk
108
+ ...index < chunks.length - 1 && { next: chunks[index + 1] },
109
+ // If this wasn't the last chunk, set the next chunk
110
+ ...index > 0 && { prev: chunks[index - 1] },
111
+ // If this wasn't the first chunk, set the previous chunk
112
+ clipBy
113
+ })
114
+ }
126
115
  }));
127
116
  };
128
117
 
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "highlight-words",
3
- "version": "1.2.2",
3
+ "version": "2.0.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": ">= 16",
7
- "npm": ">= 8"
6
+ "node": ">= 20",
7
+ "npm": ">= 9"
8
8
  },
9
9
  "repository": {
10
10
  "type": "git",
@@ -40,45 +40,33 @@
40
40
  "default": "./dist/highlight-words.mjs"
41
41
  }
42
42
  },
43
- "devDependencies": {
44
- "@babel/core": "^7.21.5",
45
- "@babel/plugin-transform-typescript": "^7.21.3",
46
- "@babel/preset-env": "^7.21.5",
47
- "@babel/preset-typescript": "^7.21.5",
48
- "@stryker-mutator/core": "^6.4.2",
49
- "@stryker-mutator/jest-runner": "^6.4.2",
50
- "@types/jest": "^29.5.1",
51
- "@typescript-eslint/eslint-plugin": "^5.59.1",
52
- "@typescript-eslint/parser": "^5.59.1",
53
- "cross-env": "^7.0.3",
54
- "esbuild": "^0.17.18",
55
- "eslint": "^8.39.0",
56
- "eslint-config-frontwerk-typescript": "^1.2.2",
57
- "eslint-config-prettier": "^8.8.0",
58
- "eslint-plugin-import": "^2.27.5",
59
- "eslint-plugin-jest": "^27.2.1",
60
- "eslint-plugin-prettier": "^4.2.1",
61
- "husky": "^8.0.3",
62
- "jest": "^29.5.0",
63
- "jest-watch-typeahead": "^2.2.2",
64
- "lint-staged": "^13.2.2",
65
- "npm-run-all": "^4.1.5",
66
- "precise-commits": "^1.0.2",
67
- "prettier": "^2.8.8",
68
- "rimraf": "^5.0.0",
69
- "rollup": "^3.21.2",
70
- "rollup-plugin-dts": "^5.3.0",
71
- "rollup-plugin-esbuild": "^5.0.0",
72
- "typescript": "^5.0.4"
73
- },
74
43
  "scripts": {
44
+ "prepare": "lefthook install || true",
75
45
  "prebuild": "cross-env rimraf dist",
76
46
  "build": "rollup -c",
77
47
  "watch": "rollup -cw",
78
48
  "typecheck": "tsc --noEmit",
79
- "lint": "eslint src --ext .ts",
80
- "format": "prettier --write \"src/**/*.ts\"",
81
- "test": "jest",
82
- "test:mutations": "stryker run"
49
+ "format": "biome format .",
50
+ "format:write": "biome format --write .",
51
+ "lint": "biome lint .",
52
+ "test:unit": "vitest run",
53
+ "test:unit:dev": "vitest",
54
+ "validate": "npm-run-all typecheck lint format test:unit",
55
+ "prepublishOnly": "npm-run-all validate format:write build"
56
+ },
57
+ "devDependencies": {
58
+ "@biomejs/biome": "1.8.3",
59
+ "cross-env": "^7.0.3",
60
+ "esbuild": "^0.23.1",
61
+ "lefthook": "^1.7.15",
62
+ "npm-run-all": "^4.1.5",
63
+ "rimraf": "^6.0.1",
64
+ "rollup": "^4.21.2",
65
+ "rollup-plugin-dts": "^6.1.1",
66
+ "rollup-plugin-esbuild": "^6.1.1",
67
+ "tsc-files": "^1.1.4",
68
+ "typescript": "^5.5.4",
69
+ "vite-tsconfig-paths": "^5.0.1",
70
+ "vitest": "^2.0.5"
83
71
  }
84
- }
72
+ }