@orchidjs/sifter 0.9.3 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +3 -1
  2. package/dist/cjs/sifter.js +776 -49
  3. package/dist/cjs/sifter.js.map +1 -1
  4. package/dist/esm/lib/sifter.js +368 -0
  5. package/dist/esm/lib/sifter.js.map +1 -0
  6. package/dist/{cjs → esm/lib}/utils.js +5 -24
  7. package/dist/esm/lib/utils.js.map +1 -0
  8. package/dist/esm/node_modules/@orchidjs/unicode-variants/dist/esm/index.js +508 -0
  9. package/dist/esm/node_modules/@orchidjs/unicode-variants/dist/esm/index.js.map +1 -0
  10. package/dist/esm/node_modules/@orchidjs/unicode-variants/dist/esm/regex.js +113 -0
  11. package/dist/esm/node_modules/@orchidjs/unicode-variants/dist/esm/regex.js.map +1 -0
  12. package/dist/esm/node_modules/@orchidjs/unicode-variants/dist/esm/strings.js +29 -0
  13. package/dist/esm/node_modules/@orchidjs/unicode-variants/dist/esm/strings.js.map +1 -0
  14. package/dist/esm/sifter.js +32 -36
  15. package/dist/esm/sifter.js.map +1 -1
  16. package/dist/esm/utils.js +3 -12
  17. package/dist/esm/utils.js.map +1 -1
  18. package/dist/types/sifter.d.ts +14 -7
  19. package/dist/types/types.d.ts +8 -7
  20. package/dist/types/utils.d.ts +2 -6
  21. package/dist/umd/sifter.js +1101 -638
  22. package/dist/umd/sifter.js.map +1 -1
  23. package/dist/umd/sifter.min.js +110 -78
  24. package/dist/umd/sifter.min.js.map +1 -1
  25. package/lib/sifter.ts +41 -45
  26. package/lib/types.ts +14 -10
  27. package/lib/utils.ts +4 -14
  28. package/package.json +5 -2
  29. package/dist/cjs/diacritics.js +0 -182
  30. package/dist/cjs/diacritics.js.map +0 -1
  31. package/dist/cjs/utils.js.map +0 -1
  32. package/dist/esm/diacritics.js +0 -173
  33. package/dist/esm/diacritics.js.map +0 -1
  34. package/dist/types/diacritics.d.ts +0 -35
  35. package/lib/diacritics.ts +0 -196
@@ -1,643 +1,1106 @@
1
1
  /*! sifter.js | https://github.com/orchidjs/sifter.js | Apache License (v2) */
2
2
  (function (global, factory) {
3
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
4
- typeof define === 'function' && define.amd ? define(factory) :
5
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.sifter = factory());
6
- }(this, (function () { 'use strict';
7
-
8
- // @ts-ignore TS2691 "An import path cannot end with a '.ts' extension"
9
- // https://github.com/andrewrk/node-diacritics/blob/master/index.js
10
- var latin_pat;
11
- const accent_pat = '[\u0300-\u036F\u{b7}\u{2be}]'; // \u{2bc}
12
-
13
- const accent_reg = new RegExp(accent_pat, 'gu');
14
- var diacritic_patterns;
15
- const latin_convert = {
16
- 'æ': 'ae',
17
- 'ⱥ': 'a',
18
- 'ø': 'o'
19
- };
20
- const convert_pat = new RegExp(Object.keys(latin_convert).join('|'), 'gu');
21
- const code_points = [[0, 65535]];
22
- /**
23
- * Remove accents
24
- * via https://github.com/krisk/Fuse/issues/133#issuecomment-318692703
25
- *
26
- */
27
-
28
- const asciifold = str => {
29
- return str.normalize('NFKD').replace(accent_reg, '').toLowerCase().replace(convert_pat, function (foreignletter) {
30
- return latin_convert[foreignletter] || foreignletter;
31
- });
32
- };
33
- /**
34
- * Convert array of strings to a regular expression
35
- * ex ['ab','a'] => (?:ab|a)
36
- * ex ['a','b'] => [ab]
37
- *
38
- */
39
-
40
- const arrayToPattern = (chars, glue = '|') => {
41
- if (chars.length === 1 && chars[0] != undefined) {
42
- return chars[0];
43
- }
44
-
45
- var longest = 1;
46
- chars.forEach(a => {
47
- longest = Math.max(longest, a.length);
48
- });
49
-
50
- if (longest == 1) {
51
- return '[' + chars.join('') + ']';
52
- }
53
-
54
- return '(?:' + chars.join(glue) + ')';
55
- };
56
- const escapeToPattern = chars => {
57
- const escaped = chars.map(diacritic => escape_regex(diacritic));
58
- return arrayToPattern(escaped);
59
- };
60
- /**
61
- * Get all possible combinations of substrings that add up to the given string
62
- * https://stackoverflow.com/questions/30169587/find-all-the-combination-of-substrings-that-add-up-to-the-given-string
63
- *
64
- */
65
-
66
- const allSubstrings = input => {
67
- if (input.length === 1) return [[input]];
68
- var result = [];
69
- allSubstrings(input.substring(1)).forEach(function (subresult) {
70
- var tmp = subresult.slice(0);
71
- tmp[0] = input.charAt(0) + tmp[0];
72
- result.push(tmp);
73
- tmp = subresult.slice(0);
74
- tmp.unshift(input.charAt(0));
75
- result.push(tmp);
76
- });
77
- return result;
78
- };
79
- /**
80
- * Generate a list of diacritics from the list of code points
81
- *
82
- */
83
-
84
- const generateDiacritics = code_points => {
85
- var diacritics = {};
86
- code_points.forEach(code_range => {
87
- for (let i = code_range[0]; i <= code_range[1]; i++) {
88
- let diacritic = String.fromCharCode(i);
89
- let latin = asciifold(diacritic);
90
-
91
- if (latin == diacritic.toLowerCase()) {
92
- continue;
93
- } // skip when latin is a string longer than 3 characters long
94
- // bc the resulting regex patterns will be long
95
- // eg:
96
- // latin صلى الله عليه وسلم length 18 code point 65018
97
- // latin جل جلاله length 8 code point 65019
98
-
99
-
100
- if (latin.length > 3) {
101
- continue;
102
- }
103
-
104
- const latin_diacritics = diacritics[latin] || [latin];
105
- const patt = new RegExp(escapeToPattern(latin_diacritics), 'iu');
106
-
107
- if (diacritic.match(patt)) {
108
- continue;
109
- }
110
-
111
- latin_diacritics.push(diacritic);
112
- diacritics[latin] = latin_diacritics;
113
- }
114
- }); // filter out if there's only one character in the list
115
- // todo: this may not be needed
116
-
117
- Object.keys(diacritics).forEach(latin => {
118
- const latin_diacritics = diacritics[latin] || [];
119
-
120
- if (latin_diacritics.length < 2) {
121
- delete diacritics[latin];
122
- }
123
- }); // latin character pattern
124
- // match longer substrings first
125
-
126
- let latin_chars = Object.keys(diacritics).sort((a, b) => b.length - a.length);
127
- latin_pat = new RegExp('(' + escapeToPattern(latin_chars) + accent_pat + '*)', 'gu'); // build diacritic patterns
128
- // ae needs:
129
- // (?:(?:ae|Æ|Ǽ|Ǣ)|(?:A|Ⓐ|A...)(?:E|ɛ|Ⓔ...))
130
-
131
- var diacritic_patterns = {};
132
- latin_chars.sort((a, b) => a.length - b.length).forEach(latin => {
133
- var substrings = allSubstrings(latin);
134
- var pattern = substrings.map(sub_pat => {
135
- sub_pat = sub_pat.map(l => {
136
- if (diacritics.hasOwnProperty(l)) {
137
- return escapeToPattern(diacritics[l]);
138
- }
139
-
140
- return l;
141
- });
142
- return arrayToPattern(sub_pat, '');
143
- });
144
- diacritic_patterns[latin] = arrayToPattern(pattern);
145
- });
146
- return diacritic_patterns;
147
- };
148
- /**
149
- * Expand a regular expression pattern to include diacritics
150
- * eg /a/ becomes /aⓐaẚàáâầấẫẩãāăằắẵẳȧǡäǟảåǻǎȁȃạậặḁąⱥɐɑAⒶAÀÁÂẦẤẪẨÃĀĂẰẮẴẲȦǠÄǞẢÅǺǍȀȂẠẬẶḀĄȺⱯ/
151
- *
152
- */
153
-
154
- const diacriticRegexPoints = regex => {
155
- if (diacritic_patterns === undefined) {
156
- diacritic_patterns = generateDiacritics(code_points);
157
- }
158
-
159
- const decomposed = regex.normalize('NFKD').toLowerCase();
160
- return decomposed.split(latin_pat).map(part => {
161
- // "ffl" or "ffl"
162
- const no_accent = asciifold(part);
163
-
164
- if (no_accent == '') {
165
- return '';
166
- }
167
-
168
- if (diacritic_patterns.hasOwnProperty(no_accent)) {
169
- return diacritic_patterns[no_accent];
170
- }
171
-
172
- return part;
173
- }).join('');
174
- };
175
-
176
- // @ts-ignore TS2691 "An import path cannot end with a '.ts' extension"
177
-
178
- /**
179
- * A property getter resolving dot-notation
180
- * @param {Object} obj The root object to fetch property on
181
- * @param {String} name The optionally dotted property name to fetch
182
- * @return {Object} The resolved property value
183
- */
184
- const getAttr = (obj, name) => {
185
- if (!obj) return;
186
- return obj[name];
187
- };
188
- /**
189
- * A property getter resolving dot-notation
190
- * @param {Object} obj The root object to fetch property on
191
- * @param {String} name The optionally dotted property name to fetch
192
- * @return {Object} The resolved property value
193
- */
194
-
195
- const getAttrNesting = (obj, name) => {
196
- if (!obj) return;
197
- var part,
198
- names = name.split(".");
199
-
200
- while ((part = names.shift()) && (obj = obj[part]));
201
-
202
- return obj;
203
- };
204
- /**
205
- * Calculates how close of a match the
206
- * given value is against a search token.
207
- *
208
- */
209
-
210
- const scoreValue = (value, token, weight) => {
211
- var score, pos;
212
- if (!value) return 0;
213
- value = value + '';
214
- pos = value.search(token.regex);
215
- if (pos === -1) return 0;
216
- score = token.string.length / value.length;
217
- if (pos === 0) score += 0.5;
218
- return score * weight;
219
- };
220
- /**
221
- *
222
- * https://stackoverflow.com/questions/63006601/why-does-u-throw-an-invalid-escape-error
223
- */
224
-
225
- const escape_regex = str => {
226
- return (str + '').replace(/([\$\(-\+\.\?\[-\^\{-\}])/g, '\\$1');
227
- };
228
- /**
229
- * Cast object property to an array if it exists and has a value
230
- *
231
- */
232
-
233
- const propToArray = (obj, key) => {
234
- var value = obj[key];
235
- if (typeof value == 'function') return value;
236
-
237
- if (value && !Array.isArray(value)) {
238
- obj[key] = [value];
239
- }
240
- };
241
- /**
242
- * Iterates over arrays and hashes.
243
- *
244
- * ```
245
- * iterate(this.items, function(item, id) {
246
- * // invoked for each item
247
- * });
248
- * ```
249
- *
250
- */
251
-
252
- const iterate = (object, callback) => {
253
- if (Array.isArray(object)) {
254
- object.forEach(callback);
255
- } else {
256
- for (var key in object) {
257
- if (object.hasOwnProperty(key)) {
258
- callback(object[key], key);
259
- }
260
- }
261
- }
262
- };
263
- const cmp = (a, b) => {
264
- if (typeof a === 'number' && typeof b === 'number') {
265
- return a > b ? 1 : a < b ? -1 : 0;
266
- }
267
-
268
- a = asciifold(a + '').toLowerCase();
269
- b = asciifold(b + '').toLowerCase();
270
- if (a > b) return 1;
271
- if (b > a) return -1;
272
- return 0;
273
- };
274
-
275
- /**
276
- * sifter.js
277
- * Copyright (c) 2013–2020 Brian Reavis & contributors
278
- *
279
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
280
- * file except in compliance with the License. You may obtain a copy of the License at:
281
- * http://www.apache.org/licenses/LICENSE-2.0
282
- *
283
- * Unless required by applicable law or agreed to in writing, software distributed under
284
- * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
285
- * ANY KIND, either express or implied. See the License for the specific language
286
- * governing permissions and limitations under the License.
287
- *
288
- * @author Brian Reavis <brian@thirdroute.com>
289
- */
290
-
291
- class Sifter {
292
- // []|{};
293
-
294
- /**
295
- * Textually searches arrays and hashes of objects
296
- * by property (or multiple properties). Designed
297
- * specifically for autocomplete.
298
- *
299
- */
300
- constructor(items, settings) {
301
- this.items = void 0;
302
- this.settings = void 0;
303
- this.items = items;
304
- this.settings = settings || {
305
- diacritics: true
306
- };
307
- }
308
-
309
- /**
310
- * Splits a search string into an array of individual
311
- * regexps to be used to match results.
312
- *
313
- */
314
- tokenize(query, respect_word_boundaries, weights) {
315
- if (!query || !query.length) return [];
316
- const tokens = [];
317
- const words = query.split(/\s+/);
318
- var field_regex;
319
-
320
- if (weights) {
321
- field_regex = new RegExp('^(' + Object.keys(weights).map(escape_regex).join('|') + ')\:(.*)$');
322
- }
323
-
324
- words.forEach(word => {
325
- let field_match;
326
- let field = null;
327
- let regex = null; // look for "field:query" tokens
328
-
329
- if (field_regex && (field_match = word.match(field_regex))) {
330
- field = field_match[1];
331
- word = field_match[2];
332
- }
333
-
334
- if (word.length > 0) {
335
- if (this.settings.diacritics) {
336
- regex = diacriticRegexPoints(word);
337
- } else {
338
- regex = escape_regex(word);
339
- }
340
-
341
- if (respect_word_boundaries) regex = "\\b" + regex;
342
- }
343
-
344
- tokens.push({
345
- string: word,
346
- regex: regex ? new RegExp(regex, 'iu') : null,
347
- field: field
348
- });
349
- });
350
- return tokens;
351
- }
352
-
353
- /**
354
- * Returns a function to be used to score individual results.
355
- *
356
- * Good matches will have a higher score than poor matches.
357
- * If an item is not a match, 0 will be returned by the function.
358
- *
359
- * @returns {function}
360
- */
361
- getScoreFunction(query, options) {
362
- var search = this.prepareSearch(query, options);
363
- return this._getScoreFunction(search);
364
- }
365
-
366
- _getScoreFunction(search) {
367
- const tokens = search.tokens,
368
- token_count = tokens.length;
369
-
370
- if (!token_count) {
371
- return function () {
372
- return 0;
373
- };
374
- }
375
-
376
- const fields = search.options.fields,
377
- weights = search.weights,
378
- field_count = fields.length,
379
- getAttrFn = search.getAttrFn;
380
-
381
- if (!field_count) {
382
- return function () {
383
- return 1;
384
- };
385
- }
386
- /**
387
- * Calculates the score of an object
388
- * against the search query.
389
- *
390
- */
391
-
392
-
393
- const scoreObject = function () {
394
- if (field_count === 1) {
395
- return function (token, data) {
396
- const field = fields[0].field;
397
- return scoreValue(getAttrFn(data, field), token, weights[field]);
398
- };
399
- }
400
-
401
- return function (token, data) {
402
- var sum = 0; // is the token specific to a field?
403
-
404
- if (token.field) {
405
- const value = getAttrFn(data, token.field);
406
-
407
- if (!token.regex && value) {
408
- sum += 1 / field_count;
409
- } else {
410
- sum += scoreValue(value, token, 1);
411
- }
412
- } else {
413
- iterate(weights, (weight, field) => {
414
- sum += scoreValue(getAttrFn(data, field), token, weight);
415
- });
416
- }
417
-
418
- return sum / field_count;
419
- };
420
- }();
421
-
422
- if (token_count === 1) {
423
- return function (data) {
424
- return scoreObject(tokens[0], data);
425
- };
426
- }
427
-
428
- if (search.options.conjunction === 'and') {
429
- return function (data) {
430
- var i = 0,
431
- score,
432
- sum = 0;
433
-
434
- for (; i < token_count; i++) {
435
- score = scoreObject(tokens[i], data);
436
- if (score <= 0) return 0;
437
- sum += score;
438
- }
439
-
440
- return sum / token_count;
441
- };
442
- } else {
443
- return function (data) {
444
- var sum = 0;
445
- iterate(tokens, token => {
446
- sum += scoreObject(token, data);
447
- });
448
- return sum / token_count;
449
- };
450
- }
451
- }
452
-
453
- /**
454
- * Returns a function that can be used to compare two
455
- * results, for sorting purposes. If no sorting should
456
- * be performed, `null` will be returned.
457
- *
458
- * @return function(a,b)
459
- */
460
- getSortFunction(query, options) {
461
- var search = this.prepareSearch(query, options);
462
- return this._getSortFunction(search);
463
- }
464
-
465
- _getSortFunction(search) {
466
- var i, n, implicit_score;
467
- const self = this,
468
- options = search.options,
469
- sort = !search.query && options.sort_empty ? options.sort_empty : options.sort,
470
- sort_flds = [],
471
- multipliers = [];
472
-
473
- if (typeof sort == 'function') {
474
- return sort.bind(this);
475
- }
476
- /**
477
- * Fetches the specified sort field value
478
- * from a search result item.
479
- *
480
- */
481
-
482
-
483
- const get_field = function get_field(name, result) {
484
- if (name === '$score') return result.score;
485
- return search.getAttrFn(self.items[result.id], name);
486
- }; // parse options
487
-
488
-
489
- if (sort) {
490
- for (i = 0, n = sort.length; i < n; i++) {
491
- if (search.query || sort[i].field !== '$score') {
492
- sort_flds.push(sort[i]);
493
- }
494
- }
495
- } // the "$score" field is implied to be the primary
496
- // sort field, unless it's manually specified
497
-
498
-
499
- if (search.query) {
500
- implicit_score = true;
501
-
502
- for (i = 0, n = sort_flds.length; i < n; i++) {
503
- if (sort_flds[i].field === '$score') {
504
- implicit_score = false;
505
- break;
506
- }
507
- }
508
-
509
- if (implicit_score) {
510
- sort_flds.unshift({
511
- field: '$score',
512
- direction: 'desc'
513
- });
514
- }
515
- } else {
516
- for (i = 0, n = sort_flds.length; i < n; i++) {
517
- if (sort_flds[i].field === '$score') {
518
- sort_flds.splice(i, 1);
519
- break;
520
- }
521
- }
522
- } // build function
523
-
524
-
525
- const sort_flds_count = sort_flds.length;
526
-
527
- if (!sort_flds_count) {
528
- return null;
529
- }
530
-
531
- return function (a, b) {
532
- var i, result, field;
533
-
534
- for (i = 0; i < sort_flds_count; i++) {
535
- field = sort_flds[i].field;
536
- let multiplier = multipliers[i];
537
-
538
- if (multiplier == undefined) {
539
- multiplier = sort_flds[i].direction === 'desc' ? -1 : 1;
540
- }
541
-
542
- result = multiplier * cmp(get_field(field, a), get_field(field, b));
543
- if (result) return result;
544
- }
545
-
546
- return 0;
547
- };
548
- }
549
-
550
- /**
551
- * Parses a search query and returns an object
552
- * with tokens and fields ready to be populated
553
- * with results.
554
- *
555
- */
556
- prepareSearch(query, optsUser) {
557
- const weights = {};
558
- var options = Object.assign({}, optsUser);
559
- propToArray(options, 'sort');
560
- propToArray(options, 'sort_empty'); // convert fields to new format
561
-
562
- if (options.fields) {
563
- propToArray(options, 'fields');
564
- const fields = [];
565
- options.fields.forEach(field => {
566
- if (typeof field == 'string') {
567
- field = {
568
- field: field,
569
- weight: 1
570
- };
571
- }
572
-
573
- fields.push(field);
574
- weights[field.field] = 'weight' in field ? field.weight : 1;
575
- });
576
- options.fields = fields;
577
- }
578
-
579
- return {
580
- options: options,
581
- query: query.toLowerCase().trim(),
582
- tokens: this.tokenize(query, options.respect_word_boundaries, weights),
583
- total: 0,
584
- items: [],
585
- weights: weights,
586
- getAttrFn: options.nesting ? getAttrNesting : getAttr
587
- };
588
- }
589
-
590
- /**
591
- * Searches through all items and returns a sorted array of matches.
592
- *
593
- */
594
- search(query, options) {
595
- var self = this,
596
- score,
597
- search;
598
- search = this.prepareSearch(query, options);
599
- options = search.options;
600
- query = search.query; // generate result scoring function
601
-
602
- const fn_score = options.score || self._getScoreFunction(search); // perform search and sort
603
-
604
-
605
- if (query.length) {
606
- iterate(self.items, (item, id) => {
607
- score = fn_score(item);
608
-
609
- if (options.filter === false || score > 0) {
610
- search.items.push({
611
- 'score': score,
612
- 'id': id
613
- });
614
- }
615
- });
616
- } else {
617
- iterate(self.items, (_, id) => {
618
- search.items.push({
619
- 'score': 1,
620
- 'id': id
621
- });
622
- });
623
- }
624
-
625
- const fn_sort = self._getSortFunction(search);
626
-
627
- if (fn_sort) search.items.sort(fn_sort); // apply limits
628
-
629
- search.total = search.items.length;
630
-
631
- if (typeof options.limit === 'number') {
632
- search.items = search.items.slice(0, options.limit);
633
- }
634
-
635
- return search;
636
- }
637
-
638
- }
639
-
640
- return Sifter;
3
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
4
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
5
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.sifter = {}));
6
+ }(this, (function (exports) { 'use strict';
7
+
8
+ /*! @orchidjs/unicode-variants | https://github.com/orchidjs/unicode-variants | Apache License (v2) */
9
+
10
+ /**
11
+ * Convert array of strings to a regular expression
12
+ * ex ['ab','a'] => (?:ab|a)
13
+ * ex ['a','b'] => [ab]
14
+ * @param {string[]} chars
15
+ * @return {string}
16
+ */
17
+ const arrayToPattern = chars => {
18
+ chars = chars.filter(Boolean);
19
+
20
+ if (chars.length < 2) {
21
+ return chars[0] || '';
22
+ }
23
+
24
+ return maxValueLength(chars) == 1 ? '[' + chars.join('') + ']' : '(?:' + chars.join('|') + ')';
25
+ };
26
+ /**
27
+ * @param {string[]} array
28
+ * @return {string}
29
+ */
30
+
31
+
32
+ const sequencePattern = array => {
33
+ if (!hasDuplicates(array)) {
34
+ return array.join('');
35
+ }
36
+
37
+ let pattern = '';
38
+ let prev_char_count = 0;
39
+
40
+ const prev_pattern = () => {
41
+ if (prev_char_count > 1) {
42
+ pattern += '{' + prev_char_count + '}';
43
+ }
44
+ };
45
+
46
+ array.forEach((char, i) => {
47
+ if (char === array[i - 1]) {
48
+ prev_char_count++;
49
+ return;
50
+ }
51
+
52
+ prev_pattern();
53
+ pattern += char;
54
+ prev_char_count = 1;
55
+ });
56
+ prev_pattern();
57
+ return pattern;
58
+ };
59
+ /**
60
+ * Convert array of strings to a regular expression
61
+ * ex ['ab','a'] => (?:ab|a)
62
+ * ex ['a','b'] => [ab]
63
+ * @param {Set<string>} chars
64
+ * @return {string}
65
+ */
66
+
67
+
68
+ const setToPattern = chars => {
69
+ let array = toArray(chars);
70
+ return arrayToPattern(array);
71
+ };
72
+ /**
73
+ *
74
+ * https://stackoverflow.com/questions/7376598/in-javascript-how-do-i-check-if-an-array-has-duplicate-values
75
+ * @param {any[]} array
76
+ */
77
+
78
+
79
+ const hasDuplicates = array => {
80
+ return new Set(array).size !== array.length;
81
+ };
82
+ /**
83
+ * https://stackoverflow.com/questions/63006601/why-does-u-throw-an-invalid-escape-error
84
+ * @param {string} str
85
+ * @return {string}
86
+ */
87
+
88
+
89
+ const escape_regex = str => {
90
+ return (str + '').replace(/([\$\(-\+\.\?\[-\^\{-\}])/g, '\\$1');
91
+ };
92
+ /**
93
+ * Return the max length of array values
94
+ * @param {string[]} array
95
+ *
96
+ */
97
+
98
+
99
+ const maxValueLength = array => {
100
+ return array.reduce((longest, value) => Math.max(longest, unicodeLength(value)), 0);
101
+ };
102
+ /**
103
+ * @param {string} str
104
+ */
105
+
106
+
107
+ const unicodeLength = str => {
108
+ return toArray(str).length;
109
+ };
110
+ /**
111
+ * @param {any} p
112
+ * @return {any[]}
113
+ */
114
+
115
+
116
+ const toArray = p => Array.from(p);
117
+
118
+ /*! @orchidjs/unicode-variants | https://github.com/orchidjs/unicode-variants | Apache License (v2) */
119
+
120
+ /**
121
+ * Get all possible combinations of substrings that add up to the given string
122
+ * https://stackoverflow.com/questions/30169587/find-all-the-combination-of-substrings-that-add-up-to-the-given-string
123
+ * @param {string} input
124
+ * @return {string[][]}
125
+ */
126
+ const allSubstrings = input => {
127
+ if (input.length === 1) return [[input]];
128
+ /** @type {string[][]} */
129
+
130
+ let result = [];
131
+ const start = input.substring(1);
132
+ const suba = allSubstrings(start);
133
+ suba.forEach(function (subresult) {
134
+ let tmp = subresult.slice(0);
135
+ tmp[0] = input.charAt(0) + tmp[0];
136
+ result.push(tmp);
137
+ tmp = subresult.slice(0);
138
+ tmp.unshift(input.charAt(0));
139
+ result.push(tmp);
140
+ });
141
+ return result;
142
+ };
143
+
144
+ /*! @orchidjs/unicode-variants | https://github.com/orchidjs/unicode-variants | Apache License (v2) */
145
+ /**
146
+ * @typedef {{[key:string]:string}} TUnicodeMap
147
+ * @typedef {{[key:string]:Set<string>}} TUnicodeSets
148
+ * @typedef {[[number,number]]} TCodePoints
149
+ * @typedef {{folded:string,composed:string,code_point:number}} TCodePointObj
150
+ * @typedef {{start:number,end:number,length:number,substr:string}} TSequencePart
151
+ */
152
+
153
+ /** @type {TCodePoints} */
154
+
155
+ const code_points = [[0, 65535]];
156
+ const accent_pat = '[\u0300-\u036F\u{b7}\u{2be}]'; // \u{2bc}
157
+
158
+ /** @type {TUnicodeMap} */
159
+
160
+ let unicode_map;
161
+ /** @type {RegExp} */
162
+
163
+ let multi_char_reg;
164
+ const max_char_length = 3;
165
+ /** @type {TUnicodeMap} */
166
+
167
+ const latin_convert = {
168
+ 'æ': 'ae',
169
+ 'ⱥ': 'a',
170
+ 'ø': 'o',
171
+ '⁄': '/',
172
+ '∕': '/'
173
+ };
174
+ const convert_pat = new RegExp(Object.keys(latin_convert).join('|') + '|' + accent_pat, 'gu');
175
+ /**
176
+ * Initialize the unicode_map from the give code point ranges
177
+ *
178
+ * @param {TCodePoints=} _code_points
179
+ */
180
+
181
+ const initialize = _code_points => {
182
+ if (unicode_map !== undefined) return;
183
+ unicode_map = generateMap(_code_points || code_points);
184
+ };
185
+ /**
186
+ * Helper method for normalize a string
187
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize
188
+ * @param {string} str
189
+ * @param {string} form
190
+ */
191
+
192
+
193
+ const normalize = (str, form = 'NFKD') => str.normalize(form);
194
+ /**
195
+ * Compatibility Decomposition without reordering string
196
+ * calling str.normalize('NFKD') on \u{594}\u{595}\u{596} becomes \u{596}\u{594}\u{595}
197
+ * @param {string} str
198
+ */
199
+
200
+
201
+ const decompose = str => {
202
+ if (str.match(/[\u0f71-\u0f81]/)) {
203
+ return toArray(str).reduce(
204
+ /**
205
+ * @param {string} result
206
+ * @param {string} char
207
+ */
208
+ (result, char) => {
209
+ return result + normalize(char);
210
+ }, '');
211
+ }
212
+
213
+ return normalize(str);
214
+ };
215
+ /**
216
+ * Remove accents
217
+ * via https://github.com/krisk/Fuse/issues/133#issuecomment-318692703
218
+ * @param {string} str
219
+ * @return {string}
220
+ */
221
+
222
+
223
+ const asciifold = str => {
224
+ return decompose(str).toLowerCase().replace(convert_pat,
225
+ /** @type {string} */
226
+ char => {
227
+ return latin_convert[char] || '';
228
+ });
229
+ };
230
+ /**
231
+ * Generate a list of unicode variants from the list of code points
232
+ * @param {TCodePoints} code_points
233
+ * @yield {TCodePointObj}
234
+ */
235
+
236
+
237
+ function* generator(code_points) {
238
+ for (const [code_point_min, code_point_max] of code_points) {
239
+ for (let i = code_point_min; i <= code_point_max; i++) {
240
+ let composed = String.fromCharCode(i);
241
+ let folded = asciifold(composed);
242
+
243
+ if (folded == composed.toLowerCase()) {
244
+ continue;
245
+ } // skip when folded is a string longer than 3 characters long
246
+ // bc the resulting regex patterns will be long
247
+ // eg:
248
+ // folded صلى الله عليه وسلم length 18 code point 65018
249
+ // folded جل جلاله length 8 code point 65019
250
+
251
+
252
+ if (folded.length > max_char_length) {
253
+ continue;
254
+ }
255
+
256
+ if (folded.length == 0) {
257
+ continue;
258
+ }
259
+
260
+ let decomposed = normalize(composed);
261
+ let recomposed = normalize(decomposed, 'NFC');
262
+
263
+ if (recomposed === composed && folded === decomposed) {
264
+ continue;
265
+ }
266
+
267
+ yield {
268
+ folded: folded,
269
+ composed: composed,
270
+ code_point: i
271
+ };
272
+ }
273
+ }
274
+ }
275
+ /**
276
+ * Generate a unicode map from the list of code points
277
+ * @param {TCodePoints} code_points
278
+ * @return {TUnicodeSets}
279
+ */
280
+
281
+
282
+ const generateSets = code_points => {
283
+ /** @type {{[key:string]:Set<string>}} */
284
+ const unicode_sets = {};
285
+ /**
286
+ * @param {string} folded
287
+ * @param {string} to_add
288
+ */
289
+
290
+ const addMatching = (folded, to_add) => {
291
+ /** @type {Set<string>} */
292
+ const folded_set = unicode_sets[folded] || new Set();
293
+ const patt = new RegExp('^' + setToPattern(folded_set) + '$', 'iu');
294
+
295
+ if (to_add.match(patt)) {
296
+ return;
297
+ }
298
+
299
+ folded_set.add(escape_regex(to_add));
300
+ unicode_sets[folded] = folded_set;
301
+ };
302
+
303
+ for (let value of generator(code_points)) {
304
+ addMatching(value.folded, value.folded);
305
+ addMatching(value.folded, value.composed);
306
+ }
307
+
308
+ return unicode_sets;
309
+ };
310
+ /**
311
+ * Generate a unicode map from the list of code points
312
+ * ae => (?:(?:ae|Æ|Ǽ|Ǣ)|(?:A|Ⓐ|A...)(?:E|ɛ|Ⓔ...))
313
+ *
314
+ * @param {TCodePoints} code_points
315
+ * @return {TUnicodeMap}
316
+ */
317
+
318
+
319
+ const generateMap = code_points => {
320
+ /** @type {TUnicodeSets} */
321
+ const unicode_sets = generateSets(code_points);
322
+ /** @type {TUnicodeMap} */
323
+
324
+ const unicode_map = {};
325
+ /** @type {string[]} */
326
+
327
+ let multi_char = [];
328
+
329
+ for (let folded in unicode_sets) {
330
+ let set = unicode_sets[folded];
331
+
332
+ if (set) {
333
+ unicode_map[folded] = setToPattern(set);
334
+ }
335
+
336
+ if (folded.length > 1) {
337
+ multi_char.push(escape_regex(folded));
338
+ }
339
+ }
340
+
341
+ multi_char.sort((a, b) => b.length - a.length);
342
+ const multi_char_patt = arrayToPattern(multi_char);
343
+ multi_char_reg = new RegExp('^' + multi_char_patt, 'u');
344
+ return unicode_map;
345
+ };
346
+ /**
347
+ * Map each element of an array from it's folded value to all possible unicode matches
348
+ * @param {string[]} strings
349
+ * @param {number} min_replacement
350
+ * @return {string}
351
+ */
352
+
353
+
354
+ const mapSequence = (strings, min_replacement = 1) => {
355
+ let chars_replaced = 0;
356
+ strings = strings.map(str => {
357
+ if (unicode_map[str]) {
358
+ chars_replaced += str.length;
359
+ }
360
+
361
+ return unicode_map[str] || str;
362
+ });
363
+
364
+ if (chars_replaced >= min_replacement) {
365
+ return sequencePattern(strings);
366
+ }
367
+
368
+ return '';
369
+ };
370
+ /**
371
+ * Convert a short string and split it into all possible patterns
372
+ * Keep a pattern only if min_replacement is met
373
+ *
374
+ * 'abc'
375
+ * => [['abc'],['ab','c'],['a','bc'],['a','b','c']]
376
+ * => ['abc-pattern','ab-c-pattern'...]
377
+ *
378
+ *
379
+ * @param {string} str
380
+ * @param {number} min_replacement
381
+ * @return {string}
382
+ */
383
+
384
+
385
+ const substringsToPattern = (str, min_replacement = 1) => {
386
+ min_replacement = Math.max(min_replacement, str.length - 1);
387
+ return arrayToPattern(allSubstrings(str).map(sub_pat => {
388
+ return mapSequence(sub_pat, min_replacement);
389
+ }));
390
+ };
391
+ /**
392
+ * Convert an array of sequences into a pattern
393
+ * [{start:0,end:3,length:3,substr:'iii'}...] => (?:iii...)
394
+ *
395
+ * @param {Sequence[]} sequences
396
+ * @param {boolean} all
397
+ */
398
+
399
+
400
+ const sequencesToPattern = (sequences, all = true) => {
401
+ let min_replacement = sequences.length > 1 ? 1 : 0;
402
+ return arrayToPattern(sequences.map(sequence => {
403
+ let seq = [];
404
+ const len = all ? sequence.length() : sequence.length() - 1;
405
+
406
+ for (let j = 0; j < len; j++) {
407
+ seq.push(substringsToPattern(sequence.substrs[j] || '', min_replacement));
408
+ }
409
+
410
+ return sequencePattern(seq);
411
+ }));
412
+ };
413
+ /**
414
+ * Return true if the sequence is already in the sequences
415
+ * @param {Sequence} needle_seq
416
+ * @param {Sequence[]} sequences
417
+ */
418
+
419
+
420
+ const inSequences = (needle_seq, sequences) => {
421
+ for (const seq of sequences) {
422
+ if (seq.start != needle_seq.start || seq.end != needle_seq.end) {
423
+ continue;
424
+ }
425
+
426
+ if (seq.substrs.join('') !== needle_seq.substrs.join('')) {
427
+ continue;
428
+ }
429
+
430
+ let needle_parts = needle_seq.parts;
431
+ /**
432
+ * @param {TSequencePart} part
433
+ */
434
+
435
+ const filter = part => {
436
+ for (const needle_part of needle_parts) {
437
+ if (needle_part.start === part.start && needle_part.substr === part.substr) {
438
+ return false;
439
+ }
440
+
441
+ if (part.length == 1 || needle_part.length == 1) {
442
+ continue;
443
+ } // check for overlapping parts
444
+ // a = ['::=','==']
445
+ // b = ['::','===']
446
+ // a = ['r','sm']
447
+ // b = ['rs','m']
448
+
449
+
450
+ if (part.start < needle_part.start && part.end > needle_part.start) {
451
+ return true;
452
+ }
453
+
454
+ if (needle_part.start < part.start && needle_part.end > part.start) {
455
+ return true;
456
+ }
457
+ }
458
+
459
+ return false;
460
+ };
461
+
462
+ let filtered = seq.parts.filter(filter);
463
+
464
+ if (filtered.length > 0) {
465
+ continue;
466
+ }
467
+
468
+ return true;
469
+ }
470
+
471
+ return false;
472
+ };
473
+
474
+ class Sequence {
475
+ constructor() {
476
+ /** @type {TSequencePart[]} */
477
+ this.parts = [];
478
+ /** @type {string[]} */
479
+
480
+ this.substrs = [];
481
+ this.start = 0;
482
+ this.end = 0;
483
+ }
484
+ /**
485
+ * @param {TSequencePart|undefined} part
486
+ */
487
+
488
+
489
+ add(part) {
490
+ if (part) {
491
+ this.parts.push(part);
492
+ this.substrs.push(part.substr);
493
+ this.start = Math.min(part.start, this.start);
494
+ this.end = Math.max(part.end, this.end);
495
+ }
496
+ }
497
+
498
+ last() {
499
+ return this.parts[this.parts.length - 1];
500
+ }
501
+
502
+ length() {
503
+ return this.parts.length;
504
+ }
505
+ /**
506
+ * @param {number} position
507
+ * @param {TSequencePart} last_piece
508
+ */
509
+
510
+
511
+ clone(position, last_piece) {
512
+ let clone = new Sequence();
513
+ let parts = JSON.parse(JSON.stringify(this.parts));
514
+ let last_part = parts.pop();
515
+
516
+ for (const part of parts) {
517
+ clone.add(part);
518
+ }
519
+
520
+ let last_substr = last_piece.substr.substring(0, position - last_part.start);
521
+ let clone_last_len = last_substr.length;
522
+ clone.add({
523
+ start: last_part.start,
524
+ end: last_part.start + clone_last_len,
525
+ length: clone_last_len,
526
+ substr: last_substr
527
+ });
528
+ return clone;
529
+ }
530
+
531
+ }
532
+ /**
533
+ * Expand a regular expression pattern to include unicode variants
534
+ * eg /a/ becomes /aⓐaẚàáâầấẫẩãāăằắẵẳȧǡäǟảåǻǎȁȃạậặḁąⱥɐɑAⒶAÀÁÂẦẤẪẨÃĀĂẰẮẴẲȦǠÄǞẢÅǺǍȀȂẠẬẶḀĄȺⱯ/
535
+ *
536
+ * Issue:
537
+ * ﺊﺋ [ 'ﺊ = \\u{fe8a}', 'ﺋ = \\u{fe8b}' ]
538
+ * becomes: ئئ [ 'ي = \\u{64a}', 'ٔ = \\u{654}', 'ي = \\u{64a}', 'ٔ = \\u{654}' ]
539
+ *
540
+ * İIJ = IIJ = ⅡJ
541
+ *
542
+ * 1/2/4
543
+ *
544
+ * @param {string} str
545
+ * @return {string|undefined}
546
+ */
547
+
548
+
549
+ const getPattern = str => {
550
+ initialize();
551
+ str = asciifold(str);
552
+ let pattern = '';
553
+ let sequences = [new Sequence()];
554
+
555
+ for (let i = 0; i < str.length; i++) {
556
+ let substr = str.substring(i);
557
+ let match = substr.match(multi_char_reg);
558
+ const char = str.substring(i, i + 1);
559
+ const match_str = match ? match[0] : null; // loop through sequences
560
+ // add either the char or multi_match
561
+
562
+ let overlapping = [];
563
+ let added_types = new Set();
564
+
565
+ for (const sequence of sequences) {
566
+ const last_piece = sequence.last();
567
+
568
+ if (!last_piece || last_piece.length == 1 || last_piece.end <= i) {
569
+ // if we have a multi match
570
+ if (match_str) {
571
+ const len = match_str.length;
572
+ sequence.add({
573
+ start: i,
574
+ end: i + len,
575
+ length: len,
576
+ substr: match_str
577
+ });
578
+ added_types.add('1');
579
+ } else {
580
+ sequence.add({
581
+ start: i,
582
+ end: i + 1,
583
+ length: 1,
584
+ substr: char
585
+ });
586
+ added_types.add('2');
587
+ }
588
+ } else if (match_str) {
589
+ let clone = sequence.clone(i, last_piece);
590
+ const len = match_str.length;
591
+ clone.add({
592
+ start: i,
593
+ end: i + len,
594
+ length: len,
595
+ substr: match_str
596
+ });
597
+ overlapping.push(clone);
598
+ } else {
599
+ // don't add char
600
+ // adding would create invalid patterns: 234 => [2,34,4]
601
+ added_types.add('3');
602
+ }
603
+ } // if we have overlapping
604
+
605
+
606
+ if (overlapping.length > 0) {
607
+ // ['ii','iii'] before ['i','i','iii']
608
+ overlapping = overlapping.sort((a, b) => {
609
+ return a.length() - b.length();
610
+ });
611
+
612
+ for (let clone of overlapping) {
613
+ // don't add if we already have an equivalent sequence
614
+ if (inSequences(clone, sequences)) {
615
+ continue;
616
+ }
617
+
618
+ sequences.push(clone);
619
+ }
620
+
621
+ continue;
622
+ } // if we haven't done anything unique
623
+ // clean up the patterns
624
+ // helps keep patterns smaller
625
+ // if str = 'r₨㎧aarss', pattern will be 446 instead of 655
626
+
627
+
628
+ if (i > 0 && added_types.size == 1 && !added_types.has('3')) {
629
+ pattern += sequencesToPattern(sequences, false);
630
+ let new_seq = new Sequence();
631
+ const old_seq = sequences[0];
632
+
633
+ if (old_seq) {
634
+ new_seq.add(old_seq.last());
635
+ }
636
+
637
+ sequences = [new_seq];
638
+ }
639
+ }
640
+
641
+ pattern += sequencesToPattern(sequences, true);
642
+ return pattern;
643
+ };
644
+
645
+ /**
646
+ * A property getter resolving dot-notation
647
+ * @param {Object} obj The root object to fetch property on
648
+ * @param {String} name The optionally dotted property name to fetch
649
+ * @return {Object} The resolved property value
650
+ */
651
+ const getAttr = (obj, name) => {
652
+ if (!obj) return;
653
+ return obj[name];
654
+ };
655
+ /**
656
+ * A property getter resolving dot-notation
657
+ * @param {Object} obj The root object to fetch property on
658
+ * @param {String} name The optionally dotted property name to fetch
659
+ * @return {Object} The resolved property value
660
+ */
661
+
662
+ const getAttrNesting = (obj, name) => {
663
+ if (!obj) return;
664
+ var part,
665
+ names = name.split(".");
666
+
667
+ while ((part = names.shift()) && (obj = obj[part]));
668
+
669
+ return obj;
670
+ };
671
+ /**
672
+ * Calculates how close of a match the
673
+ * given value is against a search token.
674
+ *
675
+ */
676
+
677
+ const scoreValue = (value, token, weight) => {
678
+ var score, pos;
679
+ if (!value) return 0;
680
+ value = value + '';
681
+ if (token.regex == null) return 0;
682
+ pos = value.search(token.regex);
683
+ if (pos === -1) return 0;
684
+ score = token.string.length / value.length;
685
+ if (pos === 0) score += 0.5;
686
+ return score * weight;
687
+ };
688
+ /**
689
+ * Cast object property to an array if it exists and has a value
690
+ *
691
+ */
692
+
693
+ const propToArray = (obj, key) => {
694
+ var value = obj[key];
695
+ if (typeof value == 'function') return value;
696
+
697
+ if (value && !Array.isArray(value)) {
698
+ obj[key] = [value];
699
+ }
700
+ };
701
+ /**
702
+ * Iterates over arrays and hashes.
703
+ *
704
+ * ```
705
+ * iterate(this.items, function(item, id) {
706
+ * // invoked for each item
707
+ * });
708
+ * ```
709
+ *
710
+ */
711
+
712
+ const iterate = (object, callback) => {
713
+ if (Array.isArray(object)) {
714
+ object.forEach(callback);
715
+ } else {
716
+ for (var key in object) {
717
+ if (object.hasOwnProperty(key)) {
718
+ callback(object[key], key);
719
+ }
720
+ }
721
+ }
722
+ };
723
+ const cmp = (a, b) => {
724
+ if (typeof a === 'number' && typeof b === 'number') {
725
+ return a > b ? 1 : a < b ? -1 : 0;
726
+ }
727
+
728
+ a = asciifold(a + '').toLowerCase();
729
+ b = asciifold(b + '').toLowerCase();
730
+ if (a > b) return 1;
731
+ if (b > a) return -1;
732
+ return 0;
733
+ };
734
+
735
+ /**
736
+ * sifter.js
737
+ * Copyright (c) 2013–2020 Brian Reavis & contributors
738
+ *
739
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
740
+ * file except in compliance with the License. You may obtain a copy of the License at:
741
+ * http://www.apache.org/licenses/LICENSE-2.0
742
+ *
743
+ * Unless required by applicable law or agreed to in writing, software distributed under
744
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
745
+ * ANY KIND, either express or implied. See the License for the specific language
746
+ * governing permissions and limitations under the License.
747
+ *
748
+ * @author Brian Reavis <brian@thirdroute.com>
749
+ */
750
+
751
+ class Sifter {
752
+ // []|{};
753
+
754
+ /**
755
+ * Textually searches arrays and hashes of objects
756
+ * by property (or multiple properties). Designed
757
+ * specifically for autocomplete.
758
+ *
759
+ */
760
+ constructor(items, settings) {
761
+ this.items = void 0;
762
+ this.settings = void 0;
763
+ this.items = items;
764
+ this.settings = settings || {
765
+ diacritics: true
766
+ };
767
+ }
768
+
769
+ /**
770
+ * Splits a search string into an array of individual
771
+ * regexps to be used to match results.
772
+ *
773
+ */
774
+ tokenize(query, respect_word_boundaries, weights) {
775
+ if (!query || !query.length) return [];
776
+ const tokens = [];
777
+ const words = query.split(/\s+/);
778
+ var field_regex;
779
+
780
+ if (weights) {
781
+ field_regex = new RegExp('^(' + Object.keys(weights).map(escape_regex).join('|') + ')\:(.*)$');
782
+ }
783
+
784
+ words.forEach(word => {
785
+ let field_match;
786
+ let field = null;
787
+ let regex = null; // look for "field:query" tokens
788
+
789
+ if (field_regex && (field_match = word.match(field_regex))) {
790
+ field = field_match[1];
791
+ word = field_match[2];
792
+ }
793
+
794
+ if (word.length > 0) {
795
+ if (this.settings.diacritics) {
796
+ regex = getPattern(word) || null;
797
+ } else {
798
+ regex = escape_regex(word);
799
+ }
800
+
801
+ if (regex && respect_word_boundaries) regex = "\\b" + regex;
802
+ }
803
+
804
+ tokens.push({
805
+ string: word,
806
+ regex: regex ? new RegExp(regex, 'iu') : null,
807
+ field: field
808
+ });
809
+ });
810
+ return tokens;
811
+ }
812
+
813
+ /**
814
+ * Returns a function to be used to score individual results.
815
+ *
816
+ * Good matches will have a higher score than poor matches.
817
+ * If an item is not a match, 0 will be returned by the function.
818
+ *
819
+ * @returns {T.ScoreFn}
820
+ */
821
+ getScoreFunction(query, options) {
822
+ var search = this.prepareSearch(query, options);
823
+ return this._getScoreFunction(search);
824
+ }
825
+ /**
826
+ * @returns {T.ScoreFn}
827
+ *
828
+ */
829
+
830
+
831
+ _getScoreFunction(search) {
832
+ const tokens = search.tokens,
833
+ token_count = tokens.length;
834
+
835
+ if (!token_count) {
836
+ return function () {
837
+ return 0;
838
+ };
839
+ }
840
+
841
+ const fields = search.options.fields,
842
+ weights = search.weights,
843
+ field_count = fields.length,
844
+ getAttrFn = search.getAttrFn;
845
+
846
+ if (!field_count) {
847
+ return function () {
848
+ return 1;
849
+ };
850
+ }
851
+ /**
852
+ * Calculates the score of an object
853
+ * against the search query.
854
+ *
855
+ */
856
+
857
+
858
+ const scoreObject = function () {
859
+ if (field_count === 1) {
860
+ return function (token, data) {
861
+ const field = fields[0].field;
862
+ return scoreValue(getAttrFn(data, field), token, weights[field] || 1);
863
+ };
864
+ }
865
+
866
+ return function (token, data) {
867
+ var sum = 0; // is the token specific to a field?
868
+
869
+ if (token.field) {
870
+ const value = getAttrFn(data, token.field);
871
+
872
+ if (!token.regex && value) {
873
+ sum += 1 / field_count;
874
+ } else {
875
+ sum += scoreValue(value, token, 1);
876
+ }
877
+ } else {
878
+ iterate(weights, (weight, field) => {
879
+ sum += scoreValue(getAttrFn(data, field), token, weight);
880
+ });
881
+ }
882
+
883
+ return sum / field_count;
884
+ };
885
+ }();
886
+
887
+ if (token_count === 1) {
888
+ return function (data) {
889
+ return scoreObject(tokens[0], data);
890
+ };
891
+ }
892
+
893
+ if (search.options.conjunction === 'and') {
894
+ return function (data) {
895
+ var score,
896
+ sum = 0;
897
+
898
+ for (let token of tokens) {
899
+ score = scoreObject(token, data);
900
+ if (score <= 0) return 0;
901
+ sum += score;
902
+ }
903
+
904
+ return sum / token_count;
905
+ };
906
+ } else {
907
+ return function (data) {
908
+ var sum = 0;
909
+ iterate(tokens, token => {
910
+ sum += scoreObject(token, data);
911
+ });
912
+ return sum / token_count;
913
+ };
914
+ }
915
+ }
916
+
917
+ /**
918
+ * Returns a function that can be used to compare two
919
+ * results, for sorting purposes. If no sorting should
920
+ * be performed, `null` will be returned.
921
+ *
922
+ * @return function(a,b)
923
+ */
924
+ getSortFunction(query, options) {
925
+ var search = this.prepareSearch(query, options);
926
+ return this._getSortFunction(search);
927
+ }
928
+
929
+ _getSortFunction(search) {
930
+ var implicit_score,
931
+ sort_flds = [];
932
+ const self = this,
933
+ options = search.options,
934
+ sort = !search.query && options.sort_empty ? options.sort_empty : options.sort;
935
+
936
+ if (typeof sort == 'function') {
937
+ return sort.bind(this);
938
+ }
939
+ /**
940
+ * Fetches the specified sort field value
941
+ * from a search result item.
942
+ *
943
+ */
944
+
945
+
946
+ const get_field = function get_field(name, result) {
947
+ if (name === '$score') return result.score;
948
+ return search.getAttrFn(self.items[result.id], name);
949
+ }; // parse options
950
+
951
+
952
+ if (sort) {
953
+ for (let s of sort) {
954
+ if (search.query || s.field !== '$score') {
955
+ sort_flds.push(s);
956
+ }
957
+ }
958
+ } // the "$score" field is implied to be the primary
959
+ // sort field, unless it's manually specified
960
+
961
+
962
+ if (search.query) {
963
+ implicit_score = true;
964
+
965
+ for (let fld of sort_flds) {
966
+ if (fld.field === '$score') {
967
+ implicit_score = false;
968
+ break;
969
+ }
970
+ }
971
+
972
+ if (implicit_score) {
973
+ sort_flds.unshift({
974
+ field: '$score',
975
+ direction: 'desc'
976
+ });
977
+ } // without a search.query, all items will have the same score
978
+
979
+ } else {
980
+ sort_flds = sort_flds.filter(fld => fld.field !== '$score');
981
+ } // build function
982
+
983
+
984
+ const sort_flds_count = sort_flds.length;
985
+
986
+ if (!sort_flds_count) {
987
+ return null;
988
+ }
989
+
990
+ return function (a, b) {
991
+ var result, field;
992
+
993
+ for (let sort_fld of sort_flds) {
994
+ field = sort_fld.field;
995
+ let multiplier = sort_fld.direction === 'desc' ? -1 : 1;
996
+ result = multiplier * cmp(get_field(field, a), get_field(field, b));
997
+ if (result) return result;
998
+ }
999
+
1000
+ return 0;
1001
+ };
1002
+ }
1003
+
1004
+ /**
1005
+ * Parses a search query and returns an object
1006
+ * with tokens and fields ready to be populated
1007
+ * with results.
1008
+ *
1009
+ */
1010
+ prepareSearch(query, optsUser) {
1011
+ const weights = {};
1012
+ var options = Object.assign({}, optsUser);
1013
+ propToArray(options, 'sort');
1014
+ propToArray(options, 'sort_empty'); // convert fields to new format
1015
+
1016
+ if (options.fields) {
1017
+ propToArray(options, 'fields');
1018
+ const fields = [];
1019
+ options.fields.forEach(field => {
1020
+ if (typeof field == 'string') {
1021
+ field = {
1022
+ field: field,
1023
+ weight: 1
1024
+ };
1025
+ }
1026
+
1027
+ fields.push(field);
1028
+ weights[field.field] = 'weight' in field ? field.weight : 1;
1029
+ });
1030
+ options.fields = fields;
1031
+ }
1032
+
1033
+ return {
1034
+ options: options,
1035
+ query: query.toLowerCase().trim(),
1036
+ tokens: this.tokenize(query, options.respect_word_boundaries, weights),
1037
+ total: 0,
1038
+ items: [],
1039
+ weights: weights,
1040
+ getAttrFn: options.nesting ? getAttrNesting : getAttr
1041
+ };
1042
+ }
1043
+
1044
+ /**
1045
+ * Searches through all items and returns a sorted array of matches.
1046
+ *
1047
+ */
1048
+ search(query, options) {
1049
+ var self = this,
1050
+ score,
1051
+ search;
1052
+ search = this.prepareSearch(query, options);
1053
+ options = search.options;
1054
+ query = search.query; // generate result scoring function
1055
+
1056
+ const fn_score = options.score || self._getScoreFunction(search); // perform search and sort
1057
+
1058
+
1059
+ if (query.length) {
1060
+ iterate(self.items, (item, id) => {
1061
+ score = fn_score(item);
1062
+
1063
+ if (options.filter === false || score > 0) {
1064
+ search.items.push({
1065
+ 'score': score,
1066
+ 'id': id
1067
+ });
1068
+ }
1069
+ });
1070
+ } else {
1071
+ iterate(self.items, (_, id) => {
1072
+ search.items.push({
1073
+ 'score': 1,
1074
+ 'id': id
1075
+ });
1076
+ });
1077
+ }
1078
+
1079
+ const fn_sort = self._getSortFunction(search);
1080
+
1081
+ if (fn_sort) search.items.sort(fn_sort); // apply limits
1082
+
1083
+ search.total = search.items.length;
1084
+
1085
+ if (typeof options.limit === 'number') {
1086
+ search.items = search.items.slice(0, options.limit);
1087
+ }
1088
+
1089
+ return search;
1090
+ }
1091
+
1092
+ }
1093
+
1094
+ exports.Sifter = Sifter;
1095
+ exports.cmp = cmp;
1096
+ exports.getAttr = getAttr;
1097
+ exports.getAttrNesting = getAttrNesting;
1098
+ exports.getPattern = getPattern;
1099
+ exports.iterate = iterate;
1100
+ exports.propToArray = propToArray;
1101
+ exports.scoreValue = scoreValue;
1102
+
1103
+ Object.defineProperty(exports, '__esModule', { value: true });
641
1104
 
642
1105
  })));
643
1106
  //# sourceMappingURL=sifter.js.map