highlight-words 1.2.0 → 1.2.2-beta.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.
@@ -31,5 +31,4 @@ declare namespace HighlightWords {
31
31
  */
32
32
  declare const highlightWords: ({ text, query, clipBy, matchExactly }: Readonly<HighlightWords.Options>) => HighlightWords.Chunk[];
33
33
 
34
- export default highlightWords;
35
- export { HighlightWords };
34
+ export { HighlightWords, highlightWords as default };
@@ -17,6 +17,7 @@ function uid(len = 11) {
17
17
  }
18
18
 
19
19
  const escapeRegexp = (term) => term.replace(/[|\\{}()[\]^$+*?.-]/g, (char) => `\\${char}`);
20
+ const termsToRegExpString = (terms) => terms.replace(/\s{2,}/g, " ").split(" ").join("|");
20
21
  const regexpQuery = ({
21
22
  terms,
22
23
  matchExactly = false
@@ -25,7 +26,7 @@ const regexpQuery = ({
25
26
  throw new TypeError("Expected a string");
26
27
  }
27
28
  const escapedTerms = escapeRegexp(terms.trim());
28
- return `(${matchExactly ? escapedTerms : escapedTerms.split(" ").join("|")})`;
29
+ return `(${matchExactly ? escapedTerms : termsToRegExpString(escapedTerms)})`;
29
30
  };
30
31
  const buildRegexp = ({
31
32
  terms,
@@ -36,13 +37,13 @@ const buildRegexp = ({
36
37
  if (fromString) {
37
38
  return new RegExp(fromString[2], fromString[3]);
38
39
  }
39
- return new RegExp(regexpQuery({terms, matchExactly}), "ig");
40
+ return new RegExp(regexpQuery({ terms, matchExactly }), "ig");
40
41
  } catch (e) {
41
42
  throw new TypeError("Expected terms to be either a string or a RegExp!");
42
43
  }
43
44
  };
44
45
 
45
- const hasProp = (prop) => (obj) => obj !== null && typeof obj !== "undefined" && prop in obj;
46
+ const hasProp = (prop) => (obj) => obj !== null && typeof obj === "object" && prop in obj;
46
47
  const hasMatch = hasProp("match");
47
48
  const chunkExists = (chunk) => typeof chunk !== "undefined";
48
49
  function clip({
@@ -76,7 +77,25 @@ function clip({
76
77
  return curr.text;
77
78
  }
78
79
 
79
- var __assign = Object.assign;
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]);
95
+ }
96
+ return a;
97
+ };
98
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
80
99
  const hasLength = (str) => str.length > 0;
81
100
  const highlightWords = ({
82
101
  text,
@@ -94,15 +113,18 @@ const highlightWords = ({
94
113
  }
95
114
  ];
96
115
  }
97
- const searchRegexp = buildRegexp({terms: query, matchExactly});
116
+ const searchRegexp = buildRegexp({ terms: query, matchExactly });
98
117
  return text.split(searchRegexp).filter(hasLength).map((str) => ({
118
+ // Compose the object for a match
99
119
  key: uid(),
100
120
  text: str,
101
121
  match: matchExactly ? str.toLowerCase() === safeQuery.toLowerCase() : searchRegexp.test(str)
102
- })).map((chunk, index, chunks) => __assign(__assign({}, chunk), typeof clipBy === "number" && {
103
- text: clip(__assign(__assign(__assign({
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({
104
125
  curr: chunk
105
- }, index < chunks.length - 1 && {next: chunks[index + 1]}), index > 0 && {prev: chunks[index - 1]}), {
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
106
128
  clipBy
107
129
  }))
108
130
  }));
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});let IDX=36,HEX="";for(;IDX--;)HEX+=IDX.toString(36);function uid(e=11){let t="",n=e;for(;n--;)t+=HEX[Math.random()*36|0];return t}const escapeRegexp=e=>e.replace(/[|\\{}()[\]^$+*?.-]/g,t=>`\\${t}`),regexpQuery=({terms:e,matchExactly:t=!1})=>{if(typeof e!="string")throw new TypeError("Expected a string");const n=escapeRegexp(e.trim());return`(${t?n:n.split(" ").join("|")})`},buildRegexp=({terms:e,matchExactly:t=!1})=>{try{const n=/^([/~@;%#'])(.*?)\1([gimsuy]*)$/.exec(e);return n?new RegExp(n[2],n[3]):new RegExp(regexpQuery({terms:e,matchExactly:t}),"ig")}catch(n){throw new TypeError("Expected terms to be either a string or a RegExp!")}},hasProp=e=>t=>t!==null&&typeof t!="undefined"&&e in t,hasMatch=hasProp("match"),chunkExists=e=>typeof e!="undefined";function clip({curr:e,next:t,prev:n,clipBy:r=3}){const o=e.text.split(" "),i=o.length;if(e.match||r>=i)return e.text;const s="...";return chunkExists(t)&&chunkExists(n)&&hasMatch(n)&&hasMatch(t)?i>r*2?[...o.slice(0,r),s,...o.slice(-r)].join(" "):e.text:chunkExists(t)&&hasMatch(t)?[s,...o.slice(-r)].join(" "):chunkExists(n)&&hasMatch(n)?[...o.slice(0,r),s].join(" "):e.text}var __assign=Object.assign;const hasLength=e=>e.length>0,highlightWords=({text:e,query:t,clipBy:n,matchExactly:r=!1})=>{const o=typeof t=="string"?t.trim():t;if(o==="")return[{key:uid(),text:e,match:!1}];const i=buildRegexp({terms:t,matchExactly:r});return e.split(i).filter(hasLength).map(s=>({key:uid(),text:s,match:r?s.toLowerCase()===o.toLowerCase():i.test(s)})).map((s,a,c)=>__assign(__assign({},s),typeof n=="number"&&{text:clip(__assign(__assign(__assign({curr:s},a<c.length-1&&{next:c[a+1]}),a>0&&{prev:c[a-1]}),{clipBy:n}))}))};exports.default=highlightWords;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});let 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;
2
2
  //# sourceMappingURL=highlight-words.min.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"highlight-words.min.js","sources":["../src/uid.ts","../src/regexp.ts","../src/clip.ts","../src/index.ts"],"sourcesContent":["// https://github.com/lukeed/uid/blob/master/src/index.js\n/* eslint no-bitwise: 'off' */\n/* eslint no-plusplus: 'off' */\n/* eslint @typescript-eslint/strict-boolean-expressions: 'off' */\nlet IDX = 36;\nlet HEX = '';\nwhile (IDX--) {\n HEX += IDX.toString(36);\n}\n\nexport default function uid(len = 11): string {\n let str = '';\n let num = len;\n while (num--) {\n str += HEX[(Math.random() * 36) | 0];\n }\n return str;\n}\n","import type { HighlightWords } from '.'; // eslint-disable-line import/no-cycle\n\n// We need escape certain characters before creating the RegExp\n// https://github.com/sindresorhus/escape-string-regexp\nconst escapeRegexp = (term: string): string =>\n term.replace(/[|\\\\{}()[\\]^$+*?.-]/g, (char: string) => `\\\\${char}`);\n\nconst regexpQuery = ({\n terms,\n matchExactly = false\n}: Readonly<HighlightWords.Query>): string => {\n if (typeof terms !== 'string') {\n throw new TypeError('Expected a string');\n }\n\n const escapedTerms = escapeRegexp(terms.trim());\n return `(${matchExactly ? escapedTerms : escapedTerms.split(' ').join('|')})`;\n};\n\nconst buildRegexp = ({\n terms,\n matchExactly = false\n}: Readonly<HighlightWords.Query>): RegExp => {\n try {\n const fromString = /^([/~@;%#'])(.*?)\\1([gimsuy]*)$/.exec(terms);\n if (fromString) {\n return new RegExp(fromString[2], fromString[3]);\n }\n\n return new RegExp(regexpQuery({ terms, matchExactly }), 'ig');\n } catch {\n throw new TypeError('Expected terms to be either a string or a RegExp!');\n }\n};\n\nexport { regexpQuery };\n\nexport default buildRegexp;\n","/* eslint complexity: [\"error\", { \"max\": 12 }] */\nimport type { HighlightWords } from '.'; // eslint-disable-line import/no-cycle\n\nconst hasProp = <T>(prop: string) => (obj: T) =>\n obj !== null && typeof obj !== 'undefined' && prop in obj;\nconst hasMatch = hasProp<HighlightWords.Chunk>('match');\n\nconst chunkExists = (\n chunk: HighlightWords.Chunk | undefined\n): chunk is HighlightWords.Chunk => typeof chunk !== 'undefined';\n\n/**\n * This provides context around a chunk's text, based on the next and previous chunks.\n * e.g. If we have the string \"The quick brown fox jumped over the lazy dog\",\n * and the search term \"fox jumped\", with a padding of 2, we want to have the end result be:\n * \"... quick brown fox jumped over the ...\"\n * The search term, \"fox jumped\" is left as is, and the left and right chunks, instead of having\n * the text in full, will be clipped.\n */\nexport default function clip({\n curr,\n next,\n prev,\n clipBy = 3\n}: HighlightWords.Clip): string {\n const words = curr.text.split(' ');\n const len = words.length;\n\n // If the current is a match, we leave it alone\n // Or if the clipBy is greater than or equal to the length of the words, there's nothing to clip\n if (curr.match || clipBy >= len) {\n return curr.text;\n }\n\n // If we have a clipBy greater than the length of the words in the current match,\n // it means we can clip the words in the current chunk\n const ellipsis = '...';\n\n if (\n chunkExists(next) &&\n chunkExists(prev) &&\n hasMatch(prev) &&\n hasMatch(next)\n ) {\n // Both the previous and the next chunks are a match\n // Let's check if we have enough words to clip by on both sides\n if (len > clipBy * 2) {\n return [\n ...words.slice(0, clipBy),\n ellipsis,\n ...words.slice(-clipBy)\n ].join(' ');\n }\n\n return curr.text;\n }\n\n // We start to check the next and previous matches in order to\n // properly position the elipsis\n if (chunkExists(next) && hasMatch(next)) {\n // The chunk right after this one is a match\n // So we need the elipsis at the start of the returned text\n // so that it sticks correctly to the next (match)'s text\n return [ellipsis, ...words.slice(-clipBy)].join(' ');\n }\n\n if (chunkExists(prev) && hasMatch(prev)) {\n // The chunk right before this one is a match\n // So we need the elipsis at the end of the returned text\n // so that it sticks correctly to the previous (match)'s text\n return [...words.slice(0, clipBy), ellipsis].join(' ');\n }\n\n // If we made it this far, just return the text\n return curr.text;\n}\n","import uid from './uid';\nimport buildRegexp from './regexp'; // eslint-disable-line import/no-cycle\nimport clip from './clip'; // eslint-disable-line import/no-cycle\n\n/* eslint-disable import/no-unused-modules */\ndeclare namespace HighlightWords {\n export interface Chunk {\n key: string;\n text: string;\n match: boolean;\n }\n\n export interface Options {\n text: string;\n query: string;\n clipBy?: number;\n matchExactly?: boolean;\n }\n\n export interface Clip {\n curr: Chunk;\n next?: Chunk;\n prev?: Chunk;\n clipBy?: number;\n }\n\n export interface Query {\n terms: string;\n matchExactly?: boolean;\n }\n}\n\nexport { HighlightWords };\n/* eslint-enable import/no-unused-modules */\n\nconst hasLength = (str: string): boolean => str.length > 0;\n\n/**\n * Split a text into chunks denoting which are a match and which are not based on a user search term.\n * @param text String The text to split.\n * @param query String The query to split by. This can contain multiple words.\n * @param clipBy Number Clip the non-matches by a certain number of words to provide context around the matches.\n * @param matchExactly Boolean If we have multiple words in the query, we will match any of the words if exact is false. For example, searching for \"brown fox\" in \"the brown cute fox\" will yield both \"brown\" and \"fox\" as matches. While if exact is true, the same search will return no results.\n */\nconst highlightWords = ({\n text,\n query,\n clipBy,\n matchExactly = false\n}: Readonly<HighlightWords.Options>): HighlightWords.Chunk[] => {\n // Let's make sure that the user cannot pass in just a bunch of spaces\n const safeQuery = typeof query === 'string' ? query.trim() : query;\n\n if (safeQuery === '') {\n return [\n {\n key: uid(),\n text,\n match: false\n }\n ];\n }\n\n const searchRegexp = buildRegexp({ terms: query, matchExactly });\n\n type ReadonlyChunk = Readonly<HighlightWords.Chunk>; // eslint-disable-line @typescript-eslint/no-type-alias\n\n return text\n .split(searchRegexp) // Split the entire thing into an array of matches and non-matches\n .filter(hasLength) // Filter any matches that have the text with length of 0\n .map((str) => ({\n // Compose the object for a match\n key: uid(),\n text: str,\n match: matchExactly\n ? str.toLowerCase() === safeQuery.toLowerCase()\n : searchRegexp.test(str)\n }))\n .map((chunk: ReadonlyChunk, index, chunks: readonly ReadonlyChunk[]) => ({\n // For each chunk, clip the text if needed\n ...chunk, // All the props first\n ...(typeof clipBy === 'number' && {\n // We only overwrite the text if there is a clip\n text: clip({\n curr: chunk, // We need the current chunk\n ...(index < chunks.length - 1 && { next: chunks[index + 1] }), // If this wasn't the last chunk, set the next chunk\n ...(index > 0 && { prev: chunks[index - 1] }), // If this wasn't the first chunk, set the previous chunk\n clipBy\n })\n })\n }));\n};\n\nexport default highlightWords;\n"],"names":[],"mappings":";;;;AAIA,IAAI,MAAM;AACV,IAAI,MAAM;AACV,OAAO;AACL,SAAO,IAAI,SAAS;AAAA;aAGM,MAAM;AAChC,MAAI,MAAM;AACV,MAAI,MAAM;AACV,SAAO;AACL,WAAO,IAAK,KAAK,WAAW,KAAM;AAAA;AAEpC,SAAO;AAAA;;ACZT,MAAM,eAAe,CAAC,SACpB,KAAK,QAAQ,wBAAwB,CAAC,SAAiB,KAAK;AAE9D,MAAM,cAAc,CAAC;AAAA,EACnB;AAAA,EACA,eAAe;AAAA;AAEf,MAAI,OAAO,UAAU;AACnB,UAAM,IAAI,UAAU;AAAA;AAGtB,QAAM,eAAe,aAAa,MAAM;AACxC,SAAO,IAAI,eAAe,eAAe,aAAa,MAAM,KAAK,KAAK;AAAA;AAGxE,MAAM,cAAc,CAAC;AAAA,EACnB;AAAA,EACA,eAAe;AAAA;AAEf;AACE,UAAM,aAAa,kCAAkC,KAAK;AAC1D,QAAI;AACF,aAAO,IAAI,OAAO,WAAW,IAAI,WAAW;AAAA;AAG9C,WAAO,IAAI,OAAO,YAAY,CAAE,OAAO,gBAAiB;AAAA,WAClD;AACN,UAAM,IAAI,UAAU;AAAA;AAAA;;AC5BxB,MAAM,UAAU,CAAI,SAAiB,CAAC,QACpC,QAAQ,QAAQ,OAAO,QAAQ,eAAe,QAAQ;AACxD,MAAM,WAAW,QAA8B;AAE/C,MAAM,cAAc,CAClB,UACkC,OAAO,UAAU;cAUxB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,QAAQ,OAAO,SAAS,KAAK,CAAE,MAAM,OAAO,QAAQ,MACpD,QAAQ,KAAK,CAAE,MAAM,OAAO,QAAQ,MAH/B;AAAA,MAIT;AAAA;AAAA;AAAA;;;;"}
1
+ {"version":3,"file":"highlight-words.min.js","sources":["../src/uid.ts","../src/regexp.ts","../src/clip.ts","../src/index.ts"],"sourcesContent":["// https://github.com/lukeed/uid/blob/master/src/index.js\n/* eslint no-bitwise: 'off' */\n/* eslint no-plusplus: 'off' */\n/* eslint @typescript-eslint/strict-boolean-expressions: 'off' */\nlet IDX = 36;\nlet HEX = '';\nwhile (IDX--) {\n HEX += IDX.toString(36);\n}\n\nexport default function uid(len = 11): string {\n let str = '';\n let num = len;\n while (num--) {\n str += HEX[(Math.random() * 36) | 0];\n }\n return str;\n}\n","import type { HighlightWords } from '.'; // eslint-disable-line import/no-cycle\n\n// We need escape certain characters before creating the RegExp\n// https://github.com/sindresorhus/escape-string-regexp\nconst escapeRegexp = (term: string): string =>\n term.replace(/[|\\\\{}()[\\]^$+*?.-]/g, (char: string) => `\\\\${char}`);\n\nconst termsToRegExpString = (terms: string): string =>\n 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","index","chunks","__spreadValues","__spreadProps"],"mappings":"oEAIA,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,KAAK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DA,EAAAA,EAAQ,GAAK,CAAE,KAAMC,EAAOD,EAAQ,CAAC,CAAE,CAHlC,EAAA,CAIT,OAAAlB,CACF,CAAC,CAAA,CACH,CACA,CAAA,CACN"}
@@ -1,2 +1,2 @@
1
- let h=36,p="";for(;h--;)p+=h.toString(36);function u(e=11){let t="",n=e;for(;n--;)t+=p[Math.random()*36|0];return t}const m=e=>e.replace(/[|\\{}()[\]^$+*?.-]/g,t=>`\\${t}`),w=({terms:e,matchExactly:t=!1})=>{if(typeof e!="string")throw new TypeError("Expected a string");const n=m(e.trim());return`(${t?n:n.split(" ").join("|")})`},x=({terms:e,matchExactly:t=!1})=>{try{const n=/^([/~@;%#'])(.*?)\1([gimsuy]*)$/.exec(e);return n?new RegExp(n[2],n[3]):new RegExp(w({terms:e,matchExactly:t}),"ig")}catch(n){throw new TypeError("Expected terms to be either a string or a RegExp!")}},d=e=>t=>t!==null&&typeof t!="undefined"&&e in t,c=d("match"),g=e=>typeof e!="undefined";function E({curr:e,next:t,prev:n,clipBy:r=3}){const o=e.text.split(" "),i=o.length;if(e.match||r>=i)return e.text;const s="...";return g(t)&&g(n)&&c(n)&&c(t)?i>r*2?[...o.slice(0,r),s,...o.slice(-r)].join(" "):e.text:g(t)&&c(t)?[s,...o.slice(-r)].join(" "):g(n)&&c(n)?[...o.slice(0,r),s].join(" "):e.text}var a=Object.assign;const R=e=>e.length>0,$=({text:e,query:t,clipBy:n,matchExactly:r=!1})=>{const o=typeof t=="string"?t.trim():t;if(o==="")return[{key:u(),text:e,match:!1}];const i=x({terms:t,matchExactly:r});return e.split(i).filter(R).map(s=>({key:u(),text:s,match:r?s.toLowerCase()===o.toLowerCase():i.test(s)})).map((s,f,l)=>a(a({},s),typeof n=="number"&&{text:E(a(a(a({curr:s},f<l.length-1&&{next:l[f+1]}),f>0&&{prev:l[f-1]}),{clipBy:n}))}))};export default $;
1
+ let 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};
2
2
  //# sourceMappingURL=highlight-words.min.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"highlight-words.min.mjs","sources":["../src/uid.ts","../src/regexp.ts","../src/clip.ts","../src/index.ts"],"sourcesContent":["// https://github.com/lukeed/uid/blob/master/src/index.js\n/* eslint no-bitwise: 'off' */\n/* eslint no-plusplus: 'off' */\n/* eslint @typescript-eslint/strict-boolean-expressions: 'off' */\nlet IDX = 36;\nlet HEX = '';\nwhile (IDX--) {\n HEX += IDX.toString(36);\n}\n\nexport default function uid(len = 11): string {\n let str = '';\n let num = len;\n while (num--) {\n str += HEX[(Math.random() * 36) | 0];\n }\n return str;\n}\n","import type { HighlightWords } from '.'; // eslint-disable-line import/no-cycle\n\n// We need escape certain characters before creating the RegExp\n// https://github.com/sindresorhus/escape-string-regexp\nconst escapeRegexp = (term: string): string =>\n term.replace(/[|\\\\{}()[\\]^$+*?.-]/g, (char: string) => `\\\\${char}`);\n\nconst regexpQuery = ({\n terms,\n matchExactly = false\n}: Readonly<HighlightWords.Query>): string => {\n if (typeof terms !== 'string') {\n throw new TypeError('Expected a string');\n }\n\n const escapedTerms = escapeRegexp(terms.trim());\n return `(${matchExactly ? escapedTerms : escapedTerms.split(' ').join('|')})`;\n};\n\nconst buildRegexp = ({\n terms,\n matchExactly = false\n}: Readonly<HighlightWords.Query>): RegExp => {\n try {\n const fromString = /^([/~@;%#'])(.*?)\\1([gimsuy]*)$/.exec(terms);\n if (fromString) {\n return new RegExp(fromString[2], fromString[3]);\n }\n\n return new RegExp(regexpQuery({ terms, matchExactly }), 'ig');\n } catch {\n throw new TypeError('Expected terms to be either a string or a RegExp!');\n }\n};\n\nexport { regexpQuery };\n\nexport default buildRegexp;\n","/* eslint complexity: [\"error\", { \"max\": 12 }] */\nimport type { HighlightWords } from '.'; // eslint-disable-line import/no-cycle\n\nconst hasProp = <T>(prop: string) => (obj: T) =>\n obj !== null && typeof obj !== 'undefined' && prop in obj;\nconst hasMatch = hasProp<HighlightWords.Chunk>('match');\n\nconst chunkExists = (\n chunk: HighlightWords.Chunk | undefined\n): chunk is HighlightWords.Chunk => typeof chunk !== 'undefined';\n\n/**\n * This provides context around a chunk's text, based on the next and previous chunks.\n * e.g. If we have the string \"The quick brown fox jumped over the lazy dog\",\n * and the search term \"fox jumped\", with a padding of 2, we want to have the end result be:\n * \"... quick brown fox jumped over the ...\"\n * The search term, \"fox jumped\" is left as is, and the left and right chunks, instead of having\n * the text in full, will be clipped.\n */\nexport default function clip({\n curr,\n next,\n prev,\n clipBy = 3\n}: HighlightWords.Clip): string {\n const words = curr.text.split(' ');\n const len = words.length;\n\n // If the current is a match, we leave it alone\n // Or if the clipBy is greater than or equal to the length of the words, there's nothing to clip\n if (curr.match || clipBy >= len) {\n return curr.text;\n }\n\n // If we have a clipBy greater than the length of the words in the current match,\n // it means we can clip the words in the current chunk\n const ellipsis = '...';\n\n if (\n chunkExists(next) &&\n chunkExists(prev) &&\n hasMatch(prev) &&\n hasMatch(next)\n ) {\n // Both the previous and the next chunks are a match\n // Let's check if we have enough words to clip by on both sides\n if (len > clipBy * 2) {\n return [\n ...words.slice(0, clipBy),\n ellipsis,\n ...words.slice(-clipBy)\n ].join(' ');\n }\n\n return curr.text;\n }\n\n // We start to check the next and previous matches in order to\n // properly position the elipsis\n if (chunkExists(next) && hasMatch(next)) {\n // The chunk right after this one is a match\n // So we need the elipsis at the start of the returned text\n // so that it sticks correctly to the next (match)'s text\n return [ellipsis, ...words.slice(-clipBy)].join(' ');\n }\n\n if (chunkExists(prev) && hasMatch(prev)) {\n // The chunk right before this one is a match\n // So we need the elipsis at the end of the returned text\n // so that it sticks correctly to the previous (match)'s text\n return [...words.slice(0, clipBy), ellipsis].join(' ');\n }\n\n // If we made it this far, just return the text\n return curr.text;\n}\n","import uid from './uid';\nimport buildRegexp from './regexp'; // eslint-disable-line import/no-cycle\nimport clip from './clip'; // eslint-disable-line import/no-cycle\n\n/* eslint-disable import/no-unused-modules */\ndeclare namespace HighlightWords {\n export interface Chunk {\n key: string;\n text: string;\n match: boolean;\n }\n\n export interface Options {\n text: string;\n query: string;\n clipBy?: number;\n matchExactly?: boolean;\n }\n\n export interface Clip {\n curr: Chunk;\n next?: Chunk;\n prev?: Chunk;\n clipBy?: number;\n }\n\n export interface Query {\n terms: string;\n matchExactly?: boolean;\n }\n}\n\nexport { HighlightWords };\n/* eslint-enable import/no-unused-modules */\n\nconst hasLength = (str: string): boolean => str.length > 0;\n\n/**\n * Split a text into chunks denoting which are a match and which are not based on a user search term.\n * @param text String The text to split.\n * @param query String The query to split by. This can contain multiple words.\n * @param clipBy Number Clip the non-matches by a certain number of words to provide context around the matches.\n * @param matchExactly Boolean If we have multiple words in the query, we will match any of the words if exact is false. For example, searching for \"brown fox\" in \"the brown cute fox\" will yield both \"brown\" and \"fox\" as matches. While if exact is true, the same search will return no results.\n */\nconst highlightWords = ({\n text,\n query,\n clipBy,\n matchExactly = false\n}: Readonly<HighlightWords.Options>): HighlightWords.Chunk[] => {\n // Let's make sure that the user cannot pass in just a bunch of spaces\n const safeQuery = typeof query === 'string' ? query.trim() : query;\n\n if (safeQuery === '') {\n return [\n {\n key: uid(),\n text,\n match: false\n }\n ];\n }\n\n const searchRegexp = buildRegexp({ terms: query, matchExactly });\n\n type ReadonlyChunk = Readonly<HighlightWords.Chunk>; // eslint-disable-line @typescript-eslint/no-type-alias\n\n return text\n .split(searchRegexp) // Split the entire thing into an array of matches and non-matches\n .filter(hasLength) // Filter any matches that have the text with length of 0\n .map((str) => ({\n // Compose the object for a match\n key: uid(),\n text: str,\n match: matchExactly\n ? str.toLowerCase() === safeQuery.toLowerCase()\n : searchRegexp.test(str)\n }))\n .map((chunk: ReadonlyChunk, index, chunks: readonly ReadonlyChunk[]) => ({\n // For each chunk, clip the text if needed\n ...chunk, // All the props first\n ...(typeof clipBy === 'number' && {\n // We only overwrite the text if there is a clip\n text: clip({\n curr: chunk, // We need the current chunk\n ...(index < chunks.length - 1 && { next: chunks[index + 1] }), // If this wasn't the last chunk, set the next chunk\n ...(index > 0 && { prev: chunks[index - 1] }), // If this wasn't the first chunk, set the previous chunk\n clipBy\n })\n })\n }));\n};\n\nexport default highlightWords;\n"],"names":[],"mappings":"AAIA,IAAI,MAAM;AACV,IAAI,MAAM;AACV,OAAO;AACL,SAAO,IAAI,SAAS;AAAA;aAGM,MAAM;AAChC,MAAI,MAAM;AACV,MAAI,MAAM;AACV,SAAO;AACL,WAAO,IAAK,KAAK,WAAW,KAAM;AAAA;AAEpC,SAAO;AAAA;;ACZT,MAAM,eAAe,CAAC,SACpB,KAAK,QAAQ,wBAAwB,CAAC,SAAiB,KAAK;AAE9D,MAAM,cAAc,CAAC;AAAA,EACnB;AAAA,EACA,eAAe;AAAA;AAEf,MAAI,OAAO,UAAU;AACnB,UAAM,IAAI,UAAU;AAAA;AAGtB,QAAM,eAAe,aAAa,MAAM;AACxC,SAAO,IAAI,eAAe,eAAe,aAAa,MAAM,KAAK,KAAK;AAAA;AAGxE,MAAM,cAAc,CAAC;AAAA,EACnB;AAAA,EACA,eAAe;AAAA;AAEf;AACE,UAAM,aAAa,kCAAkC,KAAK;AAC1D,QAAI;AACF,aAAO,IAAI,OAAO,WAAW,IAAI,WAAW;AAAA;AAG9C,WAAO,IAAI,OAAO,YAAY,CAAE,OAAO,gBAAiB;AAAA,WAClD;AACN,UAAM,IAAI,UAAU;AAAA;AAAA;;AC5BxB,MAAM,UAAU,CAAI,SAAiB,CAAC,QACpC,QAAQ,QAAQ,OAAO,QAAQ,eAAe,QAAQ;AACxD,MAAM,WAAW,QAA8B;AAE/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;A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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,IAAI,UAAU,mDAAmD,CAC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.replace(/[|\\{}()[\]^$+*?.-]/g, (char) => `\\${char}`);
16
+ const termsToRegExpString = (terms) => terms.replace(/\s{2,}/g, " ").split(" ").join("|");
16
17
  const regexpQuery = ({
17
18
  terms,
18
19
  matchExactly = false
@@ -21,7 +22,7 @@ const regexpQuery = ({
21
22
  throw new TypeError("Expected a string");
22
23
  }
23
24
  const escapedTerms = escapeRegexp(terms.trim());
24
- return `(${matchExactly ? escapedTerms : escapedTerms.split(" ").join("|")})`;
25
+ return `(${matchExactly ? escapedTerms : termsToRegExpString(escapedTerms)})`;
25
26
  };
26
27
  const buildRegexp = ({
27
28
  terms,
@@ -32,13 +33,13 @@ const buildRegexp = ({
32
33
  if (fromString) {
33
34
  return new RegExp(fromString[2], fromString[3]);
34
35
  }
35
- return new RegExp(regexpQuery({terms, matchExactly}), "ig");
36
+ return new RegExp(regexpQuery({ terms, matchExactly }), "ig");
36
37
  } catch (e) {
37
38
  throw new TypeError("Expected terms to be either a string or a RegExp!");
38
39
  }
39
40
  };
40
41
 
41
- const hasProp = (prop) => (obj) => obj !== null && typeof obj !== "undefined" && prop in obj;
42
+ const hasProp = (prop) => (obj) => obj !== null && typeof obj === "object" && prop in obj;
42
43
  const hasMatch = hasProp("match");
43
44
  const chunkExists = (chunk) => typeof chunk !== "undefined";
44
45
  function clip({
@@ -72,7 +73,25 @@ function clip({
72
73
  return curr.text;
73
74
  }
74
75
 
75
- var __assign = Object.assign;
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]);
91
+ }
92
+ return a;
93
+ };
94
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
76
95
  const hasLength = (str) => str.length > 0;
77
96
  const highlightWords = ({
78
97
  text,
@@ -90,18 +109,21 @@ const highlightWords = ({
90
109
  }
91
110
  ];
92
111
  }
93
- const searchRegexp = buildRegexp({terms: query, matchExactly});
112
+ const searchRegexp = buildRegexp({ terms: query, matchExactly });
94
113
  return text.split(searchRegexp).filter(hasLength).map((str) => ({
114
+ // Compose the object for a match
95
115
  key: uid(),
96
116
  text: str,
97
117
  match: matchExactly ? str.toLowerCase() === safeQuery.toLowerCase() : searchRegexp.test(str)
98
- })).map((chunk, index, chunks) => __assign(__assign({}, chunk), typeof clipBy === "number" && {
99
- text: clip(__assign(__assign(__assign({
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({
100
121
  curr: chunk
101
- }, index < chunks.length - 1 && {next: chunks[index + 1]}), index > 0 && {prev: chunks[index - 1]}), {
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
102
124
  clipBy
103
125
  }))
104
126
  }));
105
127
  };
106
128
 
107
- export default highlightWords;
129
+ export { highlightWords as default };
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "highlight-words",
3
- "version": "1.2.0",
3
+ "version": "1.2.2-beta.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": ">= 12",
7
- "npm": ">= 6"
6
+ "node": ">= 16",
7
+ "npm": ">= 8"
8
8
  },
9
9
  "repository": {
10
10
  "type": "git",
@@ -36,10 +36,42 @@
36
36
  "module": "dist/highlight-words.mjs",
37
37
  "exports": {
38
38
  ".": {
39
- "require": "./dist/highlight-words.js",
39
+ "types": "./dist/highlight-words.d.ts",
40
+ "require": "./dist/highlight-words.js",
40
41
  "default": "./dist/highlight-words.mjs"
41
42
  }
42
43
  },
44
+ "devDependencies": {
45
+ "@babel/core": "^7.20.12",
46
+ "@babel/plugin-transform-typescript": "^7.20.13",
47
+ "@babel/preset-env": "^7.20.2",
48
+ "@babel/preset-typescript": "^7.18.6",
49
+ "@stryker-mutator/core": "^6.3.1",
50
+ "@stryker-mutator/jest-runner": "^6.3.1",
51
+ "@types/jest": "^29.4.0",
52
+ "@typescript-eslint/eslint-plugin": "^5.50.0",
53
+ "@typescript-eslint/parser": "^5.50.0",
54
+ "cross-env": "^7.0.3",
55
+ "esbuild": "^0.17.5",
56
+ "eslint": "^8.33.0",
57
+ "eslint-config-frontwerk-typescript": "^1.2.2",
58
+ "eslint-config-prettier": "^8.6.0",
59
+ "eslint-plugin-import": "^2.27.5",
60
+ "eslint-plugin-jest": "^27.2.1",
61
+ "eslint-plugin-prettier": "^4.2.1",
62
+ "husky": "^8.0.3",
63
+ "jest": "^29.4.1",
64
+ "jest-watch-typeahead": "^2.2.2",
65
+ "lint-staged": "^13.1.0",
66
+ "npm-run-all": "^4.1.5",
67
+ "precise-commits": "^1.0.2",
68
+ "prettier": "^2.8.3",
69
+ "rimraf": "^4.1.2",
70
+ "rollup": "^3.12.1",
71
+ "rollup-plugin-dts": "^5.1.1",
72
+ "rollup-plugin-esbuild": "^5.0.0",
73
+ "typescript": "^4.9.5"
74
+ },
43
75
  "scripts": {
44
76
  "prebuild": "cross-env rimraf dist",
45
77
  "build": "rollup -c",
@@ -48,38 +80,6 @@
48
80
  "lint": "eslint src --ext .ts",
49
81
  "format": "prettier --write \"src/**/*.ts\"",
50
82
  "test": "jest",
51
- "test:mutations": "stryker run",
52
- "prepublishOnly": "npm-run-all test typecheck lint build"
53
- },
54
- "devDependencies": {
55
- "@babel/core": "^7.12.13",
56
- "@babel/plugin-transform-typescript": "^7.12.13",
57
- "@babel/preset-env": "^7.12.13",
58
- "@babel/preset-typescript": "^7.12.13",
59
- "@stryker-mutator/core": "^4.4.1",
60
- "@stryker-mutator/jest-runner": "^4.4.1",
61
- "@types/jest": "^26.0.20",
62
- "@typescript-eslint/eslint-plugin": "^4.15.0",
63
- "@typescript-eslint/parser": "^4.15.0",
64
- "cross-env": "^7.0.3",
65
- "esbuild": "^0.8.44",
66
- "eslint": "^7.19.0",
67
- "eslint-config-frontwerk-typescript": "^1.2.2",
68
- "eslint-config-prettier": "^7.2.0",
69
- "eslint-plugin-import": "^2.22.1",
70
- "eslint-plugin-jest": "^24.1.3",
71
- "eslint-plugin-prettier": "^3.3.1",
72
- "husky": "^5.0.9",
73
- "jest": "^26.6.3",
74
- "jest-watch-typeahead": "^0.6.1",
75
- "lint-staged": "^10.5.4",
76
- "npm-run-all": "^4.1.5",
77
- "precise-commits": "^1.0.2",
78
- "prettier": "^2.2.1",
79
- "rimraf": "^3.0.2",
80
- "rollup": "^2.38.5",
81
- "rollup-plugin-dts": "^2.0.1",
82
- "rollup-plugin-esbuild": "^2.6.1",
83
- "typescript": "^4.1.4"
83
+ "test:mutations": "stryker run"
84
84
  }
85
- }
85
+ }
package/Changelog.md DELETED
@@ -1,49 +0,0 @@
1
- ### v1.2.0
2
-
3
- ---
4
-
5
- - Allow regular expression patterns to be used as a query
6
-
7
- ### v1.1.0
8
-
9
- ---
10
-
11
- - Switch to new build system
12
- - Drop umd support
13
-
14
- ### v1.0.6
15
-
16
- ---
17
-
18
- - Improve a little bit the internals using the new eslint rules
19
- - Update dependencies
20
-
21
- ### v1.0.5
22
-
23
- ---
24
-
25
- - 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
26
-
27
- ### v1.0.4
28
-
29
- ---
30
-
31
- - Small fix to make sure we don't match when the query is just a bunch of white space
32
-
33
- ### v1.0.2
34
-
35
- ---
36
-
37
- - Small fix to regexp builder to trim any leading and trailing white space
38
-
39
- ### v1.0.1
40
-
41
- ---
42
-
43
- - Small fix to the modules path in package.json
44
-
45
- ### v1.0.0
46
-
47
- ---
48
-
49
- - Yay. First release :)