highlight-words 2.0.0 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/Readme.md CHANGED
@@ -51,6 +51,7 @@ console.log(chunks);
51
51
  [Play with this example on Code Sandbox.][sandbox-vanilla]
52
52
 
53
53
  Alternatively, you can also use a regular expression as part of the query string to search for.
54
+
54
55
  ```js
55
56
  const chunks = highlightWords({
56
57
  text: 'The quick brown fox jumped over the lazy dog',
@@ -102,12 +103,14 @@ console.log(chunks);
102
103
  > If using a regular expresssion, you can choose to either enclose the pattern in a string or not. In both cases, you need to format the regular expression properly, i.e. enclose the pattern between slashes, **and** you need to create capture groups, so that the match is remembered for later use.
103
104
  >
104
105
  > **Valid regular expression usage**
106
+ >
105
107
  > ```
106
108
  > query: '/(quick|brown|fox)/'
107
109
  > query: /(quick|brown|fox)/
108
110
  > ```
109
111
  >
110
- >**Invalid regular expression usage**
112
+ > **Invalid regular expression usage**
113
+ >
111
114
  > ```
112
115
  > query: '(quick|brown|fox)'
113
116
  > query: '/quick|brown|fox/'
@@ -269,7 +272,7 @@ MIT License - fork, modify and use however you want.
269
272
  [npm-version-badge]: https://img.shields.io/npm/v/highlight-words.svg?style=flat-square
270
273
  [highlight-words-npm]: https://www.npmjs.com/package/highlight-words
271
274
  [npm-downloads-badge]: https://img.shields.io/npm/dt/highlight-words.svg?style=flat-square
272
- [build-status-badge]: https://img.shields.io/circleci/build/github/tricinel/cuddy?label=circleci&style=flat-square
275
+ [build-status-badge]: https://github.com/tricinel/highlight-words/actions/workflows/ci.yml/badge.svg
273
276
  [sandbox-react]: https://codesandbox.io/s/highlight-words-react-1h7qw
274
277
  [sandbox-angular]: https://codesandbox.io/s/highlight-words-angular-xpp46
275
278
  [sandbox-vue]: https://codesandbox.io/s/highlight-words-vue-zopni
@@ -1,27 +1,28 @@
1
- declare namespace HighlightWords {
2
- interface Chunk {
3
- key: string;
4
- text: string;
5
- match: boolean;
6
- }
7
- interface Options {
8
- text: string;
9
- query: string;
10
- clipBy?: number;
11
- matchExactly?: boolean;
12
- }
13
- interface Clip {
14
- curr: Chunk;
15
- next?: Chunk;
16
- prev?: Chunk;
17
- clipBy?: number;
18
- }
19
- interface Query {
20
- terms: string;
21
- matchExactly?: boolean;
22
- }
23
- }
1
+ // Generated by dts-bundle-generator v9.5.1
24
2
 
3
+ export declare namespace HighlightWords {
4
+ interface Chunk {
5
+ key: string;
6
+ text: string;
7
+ match: boolean;
8
+ }
9
+ interface Options {
10
+ text: string;
11
+ query: string;
12
+ clipBy?: number;
13
+ matchExactly?: boolean;
14
+ }
15
+ interface Clip {
16
+ curr: Chunk;
17
+ next?: Chunk;
18
+ prev?: Chunk;
19
+ clipBy?: number;
20
+ }
21
+ interface Query {
22
+ terms: string;
23
+ matchExactly?: boolean;
24
+ }
25
+ }
25
26
  /**
26
27
  * Split a text into chunks denoting which are a match and which are not based on a user search term.
27
28
  * @param text String The text to split.
@@ -31,4 +32,8 @@ declare namespace HighlightWords {
31
32
  */
32
33
  declare const highlightWords: ({ text, query, clipBy, matchExactly }: Readonly<HighlightWords.Options>) => HighlightWords.Chunk[];
33
34
 
34
- export { HighlightWords, highlightWords as default };
35
+ export {
36
+ highlightWords as default,
37
+ };
38
+
39
+ export {};
@@ -1,27 +1,28 @@
1
- declare namespace HighlightWords {
2
- interface Chunk {
3
- key: string;
4
- text: string;
5
- match: boolean;
6
- }
7
- interface Options {
8
- text: string;
9
- query: string;
10
- clipBy?: number;
11
- matchExactly?: boolean;
12
- }
13
- interface Clip {
14
- curr: Chunk;
15
- next?: Chunk;
16
- prev?: Chunk;
17
- clipBy?: number;
18
- }
19
- interface Query {
20
- terms: string;
21
- matchExactly?: boolean;
22
- }
23
- }
1
+ // Generated by dts-bundle-generator v9.5.1
24
2
 
3
+ export declare namespace HighlightWords {
4
+ interface Chunk {
5
+ key: string;
6
+ text: string;
7
+ match: boolean;
8
+ }
9
+ interface Options {
10
+ text: string;
11
+ query: string;
12
+ clipBy?: number;
13
+ matchExactly?: boolean;
14
+ }
15
+ interface Clip {
16
+ curr: Chunk;
17
+ next?: Chunk;
18
+ prev?: Chunk;
19
+ clipBy?: number;
20
+ }
21
+ interface Query {
22
+ terms: string;
23
+ matchExactly?: boolean;
24
+ }
25
+ }
25
26
  /**
26
27
  * Split a text into chunks denoting which are a match and which are not based on a user search term.
27
28
  * @param text String The text to split.
@@ -31,4 +32,8 @@ declare namespace HighlightWords {
31
32
  */
32
33
  declare const highlightWords: ({ text, query, clipBy, matchExactly }: Readonly<HighlightWords.Options>) => HighlightWords.Chunk[];
33
34
 
34
- export { HighlightWords, highlightWords as default };
35
+ export {
36
+ highlightWords as default,
37
+ };
38
+
39
+ export {};
@@ -1,122 +1,105 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- const hasProp = (prop) => (obj) => obj !== null && typeof obj === "object" && prop in obj;
6
- const hasMatch = hasProp("match");
7
- const chunkExists = (chunk) => typeof chunk !== "undefined";
8
- function clip({
9
- curr,
10
- next,
11
- prev,
12
- clipBy = 3
13
- }) {
14
- const words = curr.text.split(" ");
15
- const len = words.length;
16
- if (curr.match || clipBy >= len) {
17
- return curr.text;
18
- }
19
- const ellipsis = "...";
20
- if (chunkExists(next) && chunkExists(prev) && hasMatch(prev) && hasMatch(next)) {
21
- if (len > clipBy * 2) {
22
- return [
23
- ...words.slice(0, clipBy),
24
- ellipsis,
25
- ...words.slice(-clipBy)
26
- ].join(" ");
27
- }
28
- return curr.text;
29
- }
30
- if (chunkExists(next) && hasMatch(next)) {
31
- return [ellipsis, ...words.slice(-clipBy)].join(" ");
32
- }
33
- if (chunkExists(prev) && hasMatch(prev)) {
34
- return [...words.slice(0, clipBy), ellipsis].join(" ");
35
- }
36
- return curr.text;
1
+ Object.defineProperties(exports, {
2
+ __esModule: { value: true },
3
+ [Symbol.toStringTag]: { value: "Module" }
4
+ });
5
+ //#region src/clip.ts
6
+ var hasProp = (prop) => (obj) => obj !== null && typeof obj === "object" && prop in obj;
7
+ var hasMatch = hasProp("match");
8
+ var chunkExists = (chunk) => typeof chunk !== "undefined";
9
+ /**
10
+ * This provides context around a chunk's text, based on the next and previous chunks.
11
+ * e.g. If we have the string "The quick brown fox jumped over the lazy dog",
12
+ * and the search term "fox jumped", with a padding of 2, we want to have the end result be:
13
+ * "... quick brown fox jumped over the ..."
14
+ * The search term, "fox jumped" is left as is, and the left and right chunks, instead of having
15
+ * the text in full, will be clipped.
16
+ */
17
+ function clip({ curr, next, prev, clipBy = 3 }) {
18
+ const words = curr.text.split(" ");
19
+ const len = words.length;
20
+ if (curr.match || clipBy >= len) return curr.text;
21
+ const ellipsis = "...";
22
+ if (chunkExists(next) && chunkExists(prev) && hasMatch(prev) && hasMatch(next)) {
23
+ if (len > clipBy * 2) return [
24
+ ...words.slice(0, clipBy),
25
+ ellipsis,
26
+ ...words.slice(-clipBy)
27
+ ].join(" ");
28
+ return curr.text;
29
+ }
30
+ if (chunkExists(next) && hasMatch(next)) return [ellipsis, ...words.slice(-clipBy)].join(" ");
31
+ if (chunkExists(prev) && hasMatch(prev)) return [...words.slice(0, clipBy), ellipsis].join(" ");
32
+ return curr.text;
37
33
  }
38
-
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)})`;
34
+ //#endregion
35
+ //#region src/regexp.ts
36
+ var escapeRegexp = (term) => term.replace(/[|\\{}()[\]^$+*?.-]/g, (char) => `\\${char}`);
37
+ var termsToRegExpString = (terms) => terms.replace(/\s{2,}/g, " ").split(" ").join("|");
38
+ var regexpQuery = ({ terms, matchExactly = false }) => {
39
+ if (typeof terms !== "string") throw new TypeError("Expected a string");
40
+ const escapedTerms = escapeRegexp(terms.trim());
41
+ return `(${matchExactly ? escapedTerms : termsToRegExpString(escapedTerms)})`;
50
42
  };
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]);
59
- }
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
- }
43
+ var buildRegexp = ({ terms, matchExactly = false }) => {
44
+ try {
45
+ const fromString = /^([/~@;%#'])(.*?)\1([gimsuy]*)$/.exec(terms);
46
+ if (fromString) return new RegExp(fromString[2], fromString[3]);
47
+ return new RegExp(regexpQuery({
48
+ terms,
49
+ matchExactly
50
+ }), "ig");
51
+ } catch {
52
+ throw new TypeError("Expected terms to be either a string or a RegExp!");
53
+ }
64
54
  };
65
-
66
- let IDX = 36;
67
- let HEX = "";
68
- while (IDX--) {
69
- HEX += IDX.toString(36);
70
- }
55
+ //#endregion
56
+ //#region src/uid.ts
57
+ var IDX = 36;
58
+ var HEX = "";
59
+ while (IDX--) HEX += IDX.toString(36);
71
60
  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;
61
+ let str = "";
62
+ let num = len;
63
+ while (num--) str += HEX[Math.random() * 36 | 0];
64
+ return str;
78
65
  }
79
-
80
- const hasLength = (str) => str.length > 0;
81
- const highlightWords = ({
82
- text,
83
- query,
84
- clipBy,
85
- matchExactly = false
86
- }) => {
87
- const safeQuery = typeof query === "string" ? query.trim() : query;
88
- if (safeQuery === "") {
89
- return [
90
- {
91
- key: uid(),
92
- text,
93
- match: false
94
- }
95
- ];
96
- }
97
- const searchRegexp = buildRegexp({ terms: query, matchExactly });
98
- return text.split(searchRegexp).filter(hasLength).map((str) => ({
99
- // Compose the object for a match
100
- key: uid(),
101
- text: str,
102
- match: matchExactly ? str.toLowerCase() === safeQuery.toLowerCase() : searchRegexp.test(str)
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
- }
119
- }));
66
+ //#endregion
67
+ //#region src/index.ts
68
+ var hasLength = (str) => str.length > 0;
69
+ /**
70
+ * Split a text into chunks denoting which are a match and which are not based on a user search term.
71
+ * @param text String The text to split.
72
+ * @param query String The query to split by. This can contain multiple words.
73
+ * @param clipBy Number Clip the non-matches by a certain number of words to provide context around the matches.
74
+ * @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.
75
+ */
76
+ var highlightWords = ({ text, query, clipBy, matchExactly = false }) => {
77
+ const safeQuery = typeof query === "string" ? query.trim() : query;
78
+ if (safeQuery === "") return [{
79
+ key: uid(),
80
+ text,
81
+ match: false
82
+ }];
83
+ const searchRegexp = buildRegexp({
84
+ terms: query,
85
+ matchExactly
86
+ });
87
+ return text.split(searchRegexp).filter(hasLength).map((str) => {
88
+ searchRegexp.lastIndex = 0;
89
+ return {
90
+ key: uid(),
91
+ text: str,
92
+ match: matchExactly ? str.toLowerCase() === safeQuery.toLowerCase() : searchRegexp.test(str)
93
+ };
94
+ }).map((chunk, index, chunks) => ({
95
+ ...chunk,
96
+ ...typeof clipBy === "number" && { text: clip({
97
+ curr: chunk,
98
+ ...index < chunks.length - 1 && { next: chunks[index + 1] },
99
+ ...index > 0 && { prev: chunks[index - 1] },
100
+ clipBy
101
+ }) }
102
+ }));
120
103
  };
121
-
104
+ //#endregion
122
105
  exports.default = highlightWords;
@@ -1,2 +1,2 @@
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
- //# sourceMappingURL=highlight-words.min.js.map
1
+ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});var e=(e=>t=>typeof t==`object`&&!!t&&e in t)(`match`),t=e=>e!==void 0;function n({curr:n,next:r,prev:i,clipBy:a=3}){let o=n.text.split(` `),s=o.length;return n.match||a>=s?n.text:t(r)&&t(i)&&e(i)&&e(r)?s>a*2?[...o.slice(0,a),`...`,...o.slice(-a)].join(` `):n.text:t(r)&&e(r)?[`...`,...o.slice(-a)].join(` `):t(i)&&e(i)?[...o.slice(0,a),`...`].join(` `):n.text}for(var r=e=>e.replace(/[|\\{}()[\]^$+*?.-]/g,e=>`\\${e}`),i=e=>e.replace(/\s{2,}/g,` `).split(` `).join(`|`),a=({terms:e,matchExactly:t=!1})=>{if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=r(e.trim());return`(${t?n:i(n)})`},o=({terms:e,matchExactly:t=!1})=>{try{let n=/^([/~@;%#'])(.*?)\1([gimsuy]*)$/.exec(e);return n?new RegExp(n[2],n[3]):new RegExp(a({terms:e,matchExactly:t}),`ig`)}catch{throw TypeError(`Expected terms to be either a string or a RegExp!`)}},s=36,c=``;s--;)c+=s.toString(36);function l(e=11){let t=``,n=e;for(;n--;)t+=c[Math.random()*36|0];return t}var u=e=>e.length>0,d=({text:e,query:t,clipBy:r,matchExactly:i=!1})=>{let a=typeof t==`string`?t.trim():t;if(a===``)return[{key:l(),text:e,match:!1}];let s=o({terms:t,matchExactly:i});return e.split(s).filter(u).map(e=>(s.lastIndex=0,{key:l(),text:e,match:i?e.toLowerCase()===a.toLowerCase():s.test(e)})).map((e,t,i)=>({...e,...typeof r==`number`&&{text:n({curr:e,...t<i.length-1&&{next:i[t+1]},...t>0&&{prev:i[t-1]},clipBy:r})}}))};exports.default=d;
2
+ //# sourceMappingURL=highlight-words.min.js.map
@@ -1 +1 @@
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,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,CAC5C,GAAI,OAAOF,GAAU,SACnB,MAAM,IAAI,UAAU,mBAAmB,EAGzC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ACH,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
+ {"version":3,"file":"highlight-words.min.js","names":[],"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 searchRegexp.lastIndex = 0;\n return {\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 })\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"],"mappings":"+FAOA,IAAM,GAHA,GACH,GACiB,OAAO,GAAQ,YAA/B,GAA2C,KAAQ,EACtC,CAA8B,OAAO,EAEhD,EACJ,GACyC,IAAU,OAUrD,SAAwB,EAAK,CAC3B,OACA,OACA,OACA,SAAS,GACqB,CAC9B,IAAM,EAAQ,EAAK,KAAK,MAAM,GAAG,EAC3B,EAAM,EAAM,OAgDlB,OA5CI,EAAK,OAAS,GAAU,EACnB,EAAK,KAQZ,EAAY,CAAI,GAChB,EAAY,CAAI,GAChB,EAAS,CAAI,GACb,EAAS,CAAI,EAIT,EAAM,EAAS,EACV,CACL,GAAG,EAAM,MAAM,EAAG,CAAM,EACxB,MACA,GAAG,EAAM,MAAM,CAAC,CAAM,CACxB,CAAC,CAAC,KAAK,GAAG,EAGL,EAAK,KAKV,EAAY,CAAI,GAAK,EAAS,CAAI,EAI7B,CAAC,MAAU,GAAG,EAAM,MAAM,CAAC,CAAM,CAAC,CAAC,CAAC,KAAK,GAAG,EAGjD,EAAY,CAAI,GAAK,EAAS,CAAI,EAI7B,CAAC,GAAG,EAAM,MAAM,EAAG,CAAM,EAAG,KAAQ,CAAC,CAAC,KAAK,GAAG,EAIhD,EAAK,IACd,CEvEA,IDFA,IAAM,EAAgB,GACpB,EAAK,QAAQ,uBAAyB,GAAiB,KAAK,GAAM,EAE9D,EAAuB,GAC3B,EACG,QAAQ,UAAW,GAAG,CAAC,CACvB,MAAM,GAAG,CAAC,CACV,KAAK,GAAG,EAEP,GAAe,CACnB,QACA,eAAe,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AAE,KAAM,EAAO,EAAQ,EAAG,EAC3D,GAAI,EAAQ,GAAK,CAAE,KAAM,EAAO,EAAQ,EAAG,EAC3C,QACF,CAAC,CACH,CACF,EAAE,CACN"}
@@ -1,2 +1,60 @@
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
- //# sourceMappingURL=highlight-words.min.mjs.map
1
+ var e = ((e) => (t) => typeof t == "object" && !!t && e in t)("match"), t = (e) => e !== void 0;
2
+ function n({ curr: n, next: r, prev: i, clipBy: a = 3 }) {
3
+ let o = n.text.split(" "), s = o.length;
4
+ return n.match || a >= s ? n.text : t(r) && t(i) && e(i) && e(r) ? s > a * 2 ? [
5
+ ...o.slice(0, a),
6
+ "...",
7
+ ...o.slice(-a)
8
+ ].join(" ") : n.text : t(r) && e(r) ? ["...", ...o.slice(-a)].join(" ") : t(i) && e(i) ? [...o.slice(0, a), "..."].join(" ") : n.text;
9
+ }
10
+ for (var r = (e) => e.replace(/[|\\{}()[\]^$+*?.-]/g, (e) => `\\${e}`), i = (e) => e.replace(/\s{2,}/g, " ").split(" ").join("|"), a = ({ terms: e, matchExactly: t = !1 }) => {
11
+ if (typeof e != "string") throw TypeError("Expected a string");
12
+ let n = r(e.trim());
13
+ return `(${t ? n : i(n)})`;
14
+ }, o = ({ terms: e, matchExactly: t = !1 }) => {
15
+ try {
16
+ let n = /^([/~@;%#'])(.*?)\1([gimsuy]*)$/.exec(e);
17
+ return n ? new RegExp(n[2], n[3]) : new RegExp(a({
18
+ terms: e,
19
+ matchExactly: t
20
+ }), "ig");
21
+ } catch {
22
+ throw TypeError("Expected terms to be either a string or a RegExp!");
23
+ }
24
+ }, s = 36, c = ""; s--;) c += s.toString(36);
25
+ function l(e = 11) {
26
+ let t = "", n = e;
27
+ for (; n--;) t += c[Math.random() * 36 | 0];
28
+ return t;
29
+ }
30
+ //#endregion
31
+ //#region src/index.ts
32
+ var u = (e) => e.length > 0, d = ({ text: e, query: t, clipBy: r, matchExactly: i = !1 }) => {
33
+ let a = typeof t == "string" ? t.trim() : t;
34
+ if (a === "") return [{
35
+ key: l(),
36
+ text: e,
37
+ match: !1
38
+ }];
39
+ let s = o({
40
+ terms: t,
41
+ matchExactly: i
42
+ });
43
+ return e.split(s).filter(u).map((e) => (s.lastIndex = 0, {
44
+ key: l(),
45
+ text: e,
46
+ match: i ? e.toLowerCase() === a.toLowerCase() : s.test(e)
47
+ })).map((e, t, i) => ({
48
+ ...e,
49
+ ...typeof r == "number" && { text: n({
50
+ curr: e,
51
+ ...t < i.length - 1 && { next: i[t + 1] },
52
+ ...t > 0 && { prev: i[t - 1] },
53
+ clipBy: r
54
+ }) }
55
+ }));
56
+ };
57
+ //#endregion
58
+ export { d as default };
59
+
60
+ //# sourceMappingURL=highlight-words.min.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"highlight-words.min.mjs","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":"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,EAAG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AAKP,EAAI,EACT,KAAAK,EACA,MAAO,EACT,CACF,EAGF,MAAMG,EAAeZ,EAAY,CAAE,MAAOU,EAAO,aAAAZ,CAAa,CAAC,EAI/D,OAAOW,EACJ,MAAMG,CAAY,EAClB,OAAOL,CAAS,EAChB,IAAKF,IAAS,CAEb,IAAKD,IACL,KAAMC,EACN,MAAOP,EACHO,EAAI,YAAA,IAAkBM,EAAU,cAChCC,EAAa,KAAKP,CAAG,CAC3B,EAAE,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
+ {"version":3,"file":"highlight-words.min.mjs","names":[],"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 searchRegexp.lastIndex = 0;\n return {\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 })\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"],"mappings":"AAOA,IAAM,MAHA,OACH,MACiB,OAAO,KAAQ,cAA/B,KAA2C,KAAQ,EACtC,CAA8B,OAAO,GAEhD,KACJ,MACyC,MAAU;AAUrD,SAAwB,EAAK,EAC3B,SACA,SACA,SACA,YAAS,KACqB;CAC9B,IAAM,IAAQ,EAAK,KAAK,MAAM,GAAG,GAC3B,IAAM,EAAM;CAgDlB,OA5CI,EAAK,SAAS,KAAU,IACnB,EAAK,OAQZ,EAAY,CAAI,KAChB,EAAY,CAAI,KAChB,EAAS,CAAI,KACb,EAAS,CAAI,IAIT,IAAM,IAAS,IACV;EACL,GAAG,EAAM,MAAM,GAAG,CAAM;EACxB;EACA,GAAG,EAAM,MAAM,CAAC,CAAM;CACxB,CAAC,CAAC,KAAK,GAAG,IAGL,EAAK,OAKV,EAAY,CAAI,KAAK,EAAS,CAAI,IAI7B,CAAC,OAAU,GAAG,EAAM,MAAM,CAAC,CAAM,CAAC,C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AC;CAI/D,OAAO,EACJ,MAAM,CAAY,CAAC,CACnB,OAAO,CAAS,CAAC,CACjB,KAAK,OACJ,EAAa,YAAY,GAClB;EAEL,KAAK,EAAI;EACT,MAAM;EACN,OAAO,IACH,EAAI,YAAY,MAAM,EAAU,YAAY,IAC5C,EAAa,KAAK,CAAG;CAC3B,EACD,CAAC,CACD,KAAK,GAAsB,GAAO,OAAsC;EAEvE,GAAG;EACH,GAAI,OAAO,KAAW,YAAY,EAEhC,MAAM,EAAK;GACT,MAAM;GACN,GAAI,IAAQ,EAAO,SAAS,KAAK,EAAE,MAAM,EAAO,IAAQ,GAAG;GAC3D,GAAI,IAAQ,KAAK,EAAE,MAAM,EAAO,IAAQ,GAAG;GAC3C;EACF,CAAC,EACH;CACF,EAAE;AACN"}
@@ -1,118 +1,101 @@
1
- const hasProp = (prop) => (obj) => obj !== null && typeof obj === "object" && prop in obj;
2
- const hasMatch = hasProp("match");
3
- const chunkExists = (chunk) => typeof chunk !== "undefined";
4
- function clip({
5
- curr,
6
- next,
7
- prev,
8
- clipBy = 3
9
- }) {
10
- const words = curr.text.split(" ");
11
- const len = words.length;
12
- if (curr.match || clipBy >= len) {
13
- return curr.text;
14
- }
15
- const ellipsis = "...";
16
- if (chunkExists(next) && chunkExists(prev) && hasMatch(prev) && hasMatch(next)) {
17
- if (len > clipBy * 2) {
18
- return [
19
- ...words.slice(0, clipBy),
20
- ellipsis,
21
- ...words.slice(-clipBy)
22
- ].join(" ");
23
- }
24
- return curr.text;
25
- }
26
- if (chunkExists(next) && hasMatch(next)) {
27
- return [ellipsis, ...words.slice(-clipBy)].join(" ");
28
- }
29
- if (chunkExists(prev) && hasMatch(prev)) {
30
- return [...words.slice(0, clipBy), ellipsis].join(" ");
31
- }
32
- return curr.text;
1
+ //#region src/clip.ts
2
+ var hasProp = (prop) => (obj) => obj !== null && typeof obj === "object" && prop in obj;
3
+ var hasMatch = hasProp("match");
4
+ var chunkExists = (chunk) => typeof chunk !== "undefined";
5
+ /**
6
+ * This provides context around a chunk's text, based on the next and previous chunks.
7
+ * e.g. If we have the string "The quick brown fox jumped over the lazy dog",
8
+ * and the search term "fox jumped", with a padding of 2, we want to have the end result be:
9
+ * "... quick brown fox jumped over the ..."
10
+ * The search term, "fox jumped" is left as is, and the left and right chunks, instead of having
11
+ * the text in full, will be clipped.
12
+ */
13
+ function clip({ curr, next, prev, clipBy = 3 }) {
14
+ const words = curr.text.split(" ");
15
+ const len = words.length;
16
+ if (curr.match || clipBy >= len) return curr.text;
17
+ const ellipsis = "...";
18
+ if (chunkExists(next) && chunkExists(prev) && hasMatch(prev) && hasMatch(next)) {
19
+ if (len > clipBy * 2) return [
20
+ ...words.slice(0, clipBy),
21
+ ellipsis,
22
+ ...words.slice(-clipBy)
23
+ ].join(" ");
24
+ return curr.text;
25
+ }
26
+ if (chunkExists(next) && hasMatch(next)) return [ellipsis, ...words.slice(-clipBy)].join(" ");
27
+ if (chunkExists(prev) && hasMatch(prev)) return [...words.slice(0, clipBy), ellipsis].join(" ");
28
+ return curr.text;
33
29
  }
34
-
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)})`;
30
+ //#endregion
31
+ //#region src/regexp.ts
32
+ var escapeRegexp = (term) => term.replace(/[|\\{}()[\]^$+*?.-]/g, (char) => `\\${char}`);
33
+ var termsToRegExpString = (terms) => terms.replace(/\s{2,}/g, " ").split(" ").join("|");
34
+ var regexpQuery = ({ terms, matchExactly = false }) => {
35
+ if (typeof terms !== "string") throw new TypeError("Expected a string");
36
+ const escapedTerms = escapeRegexp(terms.trim());
37
+ return `(${matchExactly ? escapedTerms : termsToRegExpString(escapedTerms)})`;
46
38
  };
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]);
55
- }
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
- }
39
+ var buildRegexp = ({ terms, matchExactly = false }) => {
40
+ try {
41
+ const fromString = /^([/~@;%#'])(.*?)\1([gimsuy]*)$/.exec(terms);
42
+ if (fromString) return new RegExp(fromString[2], fromString[3]);
43
+ return new RegExp(regexpQuery({
44
+ terms,
45
+ matchExactly
46
+ }), "ig");
47
+ } catch {
48
+ throw new TypeError("Expected terms to be either a string or a RegExp!");
49
+ }
60
50
  };
61
-
62
- let IDX = 36;
63
- let HEX = "";
64
- while (IDX--) {
65
- HEX += IDX.toString(36);
66
- }
51
+ //#endregion
52
+ //#region src/uid.ts
53
+ var IDX = 36;
54
+ var HEX = "";
55
+ while (IDX--) HEX += IDX.toString(36);
67
56
  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;
57
+ let str = "";
58
+ let num = len;
59
+ while (num--) str += HEX[Math.random() * 36 | 0];
60
+ return str;
74
61
  }
75
-
76
- const hasLength = (str) => str.length > 0;
77
- const highlightWords = ({
78
- text,
79
- query,
80
- clipBy,
81
- matchExactly = false
82
- }) => {
83
- const safeQuery = typeof query === "string" ? query.trim() : query;
84
- if (safeQuery === "") {
85
- return [
86
- {
87
- key: uid(),
88
- text,
89
- match: false
90
- }
91
- ];
92
- }
93
- const searchRegexp = buildRegexp({ terms: query, matchExactly });
94
- return text.split(searchRegexp).filter(hasLength).map((str) => ({
95
- // Compose the object for a match
96
- key: uid(),
97
- text: str,
98
- match: matchExactly ? str.toLowerCase() === safeQuery.toLowerCase() : searchRegexp.test(str)
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
- }
115
- }));
62
+ //#endregion
63
+ //#region src/index.ts
64
+ var hasLength = (str) => str.length > 0;
65
+ /**
66
+ * Split a text into chunks denoting which are a match and which are not based on a user search term.
67
+ * @param text String The text to split.
68
+ * @param query String The query to split by. This can contain multiple words.
69
+ * @param clipBy Number Clip the non-matches by a certain number of words to provide context around the matches.
70
+ * @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.
71
+ */
72
+ var highlightWords = ({ text, query, clipBy, matchExactly = false }) => {
73
+ const safeQuery = typeof query === "string" ? query.trim() : query;
74
+ if (safeQuery === "") return [{
75
+ key: uid(),
76
+ text,
77
+ match: false
78
+ }];
79
+ const searchRegexp = buildRegexp({
80
+ terms: query,
81
+ matchExactly
82
+ });
83
+ return text.split(searchRegexp).filter(hasLength).map((str) => {
84
+ searchRegexp.lastIndex = 0;
85
+ return {
86
+ key: uid(),
87
+ text: str,
88
+ match: matchExactly ? str.toLowerCase() === safeQuery.toLowerCase() : searchRegexp.test(str)
89
+ };
90
+ }).map((chunk, index, chunks) => ({
91
+ ...chunk,
92
+ ...typeof clipBy === "number" && { text: clip({
93
+ curr: chunk,
94
+ ...index < chunks.length - 1 && { next: chunks[index + 1] },
95
+ ...index > 0 && { prev: chunks[index - 1] },
96
+ clipBy
97
+ }) }
98
+ }));
116
99
  };
117
-
100
+ //#endregion
118
101
  export { highlightWords as default };
package/package.json CHANGED
@@ -1,39 +1,30 @@
1
1
  {
2
2
  "name": "highlight-words",
3
- "version": "2.0.0",
3
+ "version": "2.1.1",
4
4
  "description": "Split a piece text into multiple chunks based on a search query, allowing you to highlight the matches.",
5
- "engines": {
6
- "node": ">= 20",
7
- "npm": ">= 9"
5
+ "keywords": [
6
+ "highlight",
7
+ "regex",
8
+ "search",
9
+ "string"
10
+ ],
11
+ "homepage": "https://github.com/tricinel/highlight-words#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/tricinel/highlight-words/issues"
8
14
  },
15
+ "license": "MIT",
16
+ "author": "Bogdan Lazar",
9
17
  "repository": {
10
18
  "type": "git",
11
19
  "url": "https://github.com/tricinel/highlight-words.git"
12
20
  },
13
- "bugs": {
14
- "url": "https://github.com/tricinel/highlight-words/issues"
15
- },
16
- "homepage": "https://github.com/tricinel/highlight-words#readme",
17
- "author": "Bogdan Lazar",
18
- "license": "MIT",
19
- "keywords": [
20
- "string",
21
- "search",
22
- "highlight",
23
- "regex"
24
- ],
25
21
  "files": [
26
22
  "dist"
27
23
  ],
28
- "eslintIgnore": [
29
- "node_modules",
30
- "dist",
31
- "coverage"
32
- ],
33
24
  "type": "commonjs",
34
- "typings": "dist/highlight-words.d.ts",
35
25
  "main": "dist/highlight-words.js",
36
26
  "module": "dist/highlight-words.mjs",
27
+ "typings": "dist/highlight-words.d.ts",
37
28
  "exports": {
38
29
  ".": {
39
30
  "require": "./dist/highlight-words.js",
@@ -43,30 +34,43 @@
43
34
  "scripts": {
44
35
  "prepare": "lefthook install || true",
45
36
  "prebuild": "cross-env rimraf dist",
46
- "build": "rollup -c",
47
- "watch": "rollup -cw",
37
+ "build:lib:normal": "vite build",
38
+ "build:lib:min": "cross-env MINIFY=true vite build",
39
+ "build:lib": "npm-run-all build:lib:normal build:lib:min",
40
+ "build:types": "dts-bundle-generator -o dist/highlight-words.d.ts src/index.ts && dts-bundle-generator -o dist/highlight-words.d.mts src/index.ts",
41
+ "build:dist:normal": "vite build",
42
+ "build:dist:min": "cross-env MINIFY=true vite build",
43
+ "build:dist": "npm-run-all prebuild build:dist:normal build:dist:min",
44
+ "build": "npm-run-all prebuild build:lib build:types",
45
+ "watch": "vite build --watch",
48
46
  "typecheck": "tsc --noEmit",
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",
47
+ "format": "oxfmt --check .",
48
+ "format:write": "oxfmt --write .",
49
+ "lint": "oxlint -c .oxlintrc.json .",
50
+ "test:dev": "vitest run -c vitest.config.mts",
51
+ "test:dev:watch": "vitest",
52
+ "test:dist": "vitest run -c vitest.dist.config.mts",
53
+ "test": "npm-run-all -p test:dev test:dist",
54
+ "validate": "npm-run-all typecheck lint format test:dev",
55
+ "pretest:dist": "npm-run-all build:dist",
55
56
  "prepublishOnly": "npm-run-all validate format:write build"
56
57
  },
57
58
  "devDependencies": {
58
- "@biomejs/biome": "1.8.3",
59
- "cross-env": "^7.0.3",
60
- "esbuild": "^0.23.1",
61
- "lefthook": "^1.7.15",
59
+ "@types/node": "^25.7.0",
60
+ "cross-env": "^10.1.0",
61
+ "dts-bundle-generator": "^9.5.1",
62
+ "lefthook": "^2.1.6",
62
63
  "npm-run-all": "^4.1.5",
64
+ "oxfmt": "^0.49.0",
65
+ "oxlint": "^1.64.0",
63
66
  "rimraf": "^6.0.1",
64
- "rollup": "^4.21.2",
65
- "rollup-plugin-dts": "^6.1.1",
66
- "rollup-plugin-esbuild": "^6.1.1",
67
67
  "tsc-files": "^1.1.4",
68
- "typescript": "^5.5.4",
69
- "vite-tsconfig-paths": "^5.0.1",
70
- "vitest": "^2.0.5"
68
+ "typescript": "^6.0.3",
69
+ "vite": "^8.0.12",
70
+ "vitest": "^4.1.6"
71
+ },
72
+ "engines": {
73
+ "node": ">= 22",
74
+ "npm": ">= 10"
71
75
  }
72
76
  }