This repository has been archived by the owner on Jul 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 46
/
algoliasearch.helper.js
1422 lines (1265 loc) · 43.3 KB
/
algoliasearch.helper.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
var SearchParameters = require('./SearchParameters');
var SearchResults = require('./SearchResults');
var DerivedHelper = require('./DerivedHelper');
var requestBuilder = require('./requestBuilder');
var events = require('events');
var inherits = require('./functions/inherits');
var objectHasKeys = require('./functions/objectHasKeys');
var version = require('./version');
/**
* Event triggered when a parameter is set or updated
* @event AlgoliaSearchHelper#event:change
* @property {object} event
* @property {SearchParameters} event.state the current parameters with the latest changes applied
* @property {SearchResults} event.results the previous results received from Algolia. `null` before the first request
* @example
* helper.on('change', function(event) {
* console.log('The parameters have changed');
* });
*/
/**
* Event triggered when a main search is sent to Algolia
* @event AlgoliaSearchHelper#event:search
* @property {object} event
* @property {SearchParameters} event.state the parameters used for this search
* @property {SearchResults} event.results the results from the previous search. `null` if it is the first search.
* @example
* helper.on('search', function(event) {
* console.log('Search sent');
* });
*/
/**
* Event triggered when a search using `searchForFacetValues` is sent to Algolia
* @event AlgoliaSearchHelper#event:searchForFacetValues
* @property {object} event
* @property {SearchParameters} event.state the parameters used for this search it is the first search.
* @property {string} event.facet the facet searched into
* @property {string} event.query the query used to search in the facets
* @example
* helper.on('searchForFacetValues', function(event) {
* console.log('searchForFacetValues sent');
* });
*/
/**
* Event triggered when a search using `searchOnce` is sent to Algolia
* @event AlgoliaSearchHelper#event:searchOnce
* @property {object} event
* @property {SearchParameters} event.state the parameters used for this search it is the first search.
* @example
* helper.on('searchOnce', function(event) {
* console.log('searchOnce sent');
* });
*/
/**
* Event triggered when the results are retrieved from Algolia
* @event AlgoliaSearchHelper#event:result
* @property {object} event
* @property {SearchResults} event.results the results received from Algolia
* @property {SearchParameters} event.state the parameters used to query Algolia. Those might be different from the one in the helper instance (for example if the network is unreliable).
* @example
* helper.on('result', function(event) {
* console.log('Search results received');
* });
*/
/**
* Event triggered when Algolia sends back an error. For example, if an unknown parameter is
* used, the error can be caught using this event.
* @event AlgoliaSearchHelper#event:error
* @property {object} event
* @property {Error} event.error the error returned by the Algolia.
* @example
* helper.on('error', function(event) {
* console.log('Houston we got a problem.');
* });
*/
/**
* Event triggered when the queue of queries have been depleted (with any result or outdated queries)
* @event AlgoliaSearchHelper#event:searchQueueEmpty
* @example
* helper.on('searchQueueEmpty', function() {
* console.log('No more search pending');
* // This is received before the result event if we're not expecting new results
* });
*
* helper.search();
*/
/**
* Initialize a new AlgoliaSearchHelper
* @class
* @classdesc The AlgoliaSearchHelper is a class that ease the management of the
* search. It provides an event based interface for search callbacks:
* - change: when the internal search state is changed.
* This event contains a {@link SearchParameters} object and the
* {@link SearchResults} of the last result if any.
* - search: when a search is triggered using the `search()` method.
* - result: when the response is retrieved from Algolia and is processed.
* This event contains a {@link SearchResults} object and the
* {@link SearchParameters} corresponding to this answer.
* - error: when the response is an error. This event contains the error returned by the server.
* @param {AlgoliaSearch} client an AlgoliaSearch client
* @param {string} index the index name to query
* @param {SearchParameters | object} options an object defining the initial
* config of the search. It doesn't have to be a {SearchParameters},
* just an object containing the properties you need from it.
*/
function AlgoliaSearchHelper(client, index, options) {
if (typeof client.addAlgoliaAgent === 'function') {
client.addAlgoliaAgent('JS Helper (' + version + ')');
}
this.setClient(client);
var opts = options || {};
opts.index = index;
this.state = SearchParameters.make(opts);
this.lastResults = null;
this._queryId = 0;
this._lastQueryIdReceived = -1;
this.derivedHelpers = [];
this._currentNbQueries = 0;
}
inherits(AlgoliaSearchHelper, events.EventEmitter);
/**
* Start the search with the parameters set in the state. When the
* method is called, it triggers a `search` event. The results will
* be available through the `result` event. If an error occurs, an
* `error` will be fired instead.
* @return {AlgoliaSearchHelper}
* @fires search
* @fires result
* @fires error
* @chainable
*/
AlgoliaSearchHelper.prototype.search = function() {
this._search({onlyWithDerivedHelpers: false});
return this;
};
AlgoliaSearchHelper.prototype.searchOnlyWithDerivedHelpers = function() {
this._search({onlyWithDerivedHelpers: true});
return this;
};
/**
* Gets the search query parameters that would be sent to the Algolia Client
* for the hits
* @return {object} Query Parameters
*/
AlgoliaSearchHelper.prototype.getQuery = function() {
var state = this.state;
return requestBuilder._getHitsSearchParams(state);
};
/**
* Start a search using a modified version of the current state. This method does
* not trigger the helper lifecycle and does not modify the state kept internally
* by the helper. This second aspect means that the next search call will be the
* same as a search call before calling searchOnce.
* @param {object} options can contain all the parameters that can be set to SearchParameters
* plus the index
* @param {function} [callback] optional callback executed when the response from the
* server is back.
* @return {promise|undefined} if a callback is passed the method returns undefined
* otherwise it returns a promise containing an object with two keys :
* - content with a SearchResults
* - state with the state used for the query as a SearchParameters
* @example
* // Changing the number of records returned per page to 1
* // This example uses the callback API
* var state = helper.searchOnce({hitsPerPage: 1},
* function(error, content, state) {
* // if an error occurred it will be passed in error, otherwise its value is null
* // content contains the results formatted as a SearchResults
* // state is the instance of SearchParameters used for this search
* });
* @example
* // Changing the number of records returned per page to 1
* // This example uses the promise API
* var state1 = helper.searchOnce({hitsPerPage: 1})
* .then(promiseHandler);
*
* function promiseHandler(res) {
* // res contains
* // {
* // content : SearchResults
* // state : SearchParameters (the one used for this specific search)
* // }
* }
*/
AlgoliaSearchHelper.prototype.searchOnce = function(options, cb) {
var tempState = !options ? this.state : this.state.setQueryParameters(options);
var queries = requestBuilder._getQueries(tempState.index, tempState);
var self = this;
this._currentNbQueries++;
this.emit('searchOnce', {
state: tempState
});
if (cb) {
this.client
.search(queries)
.then(function(content) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) {
self.emit('searchQueueEmpty');
}
cb(null, new SearchResults(tempState, content.results), tempState);
})
.catch(function(err) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) {
self.emit('searchQueueEmpty');
}
cb(err, null, tempState);
});
return undefined;
}
return this.client.search(queries).then(function(content) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
return {
content: new SearchResults(tempState, content.results),
state: tempState,
_originalResponse: content
};
}, function(e) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
throw e;
});
};
/**
* Structure of each result when using
* [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues)
* @typedef FacetSearchHit
* @type {object}
* @property {string} value the facet value
* @property {string} highlighted the facet value highlighted with the query string
* @property {number} count number of occurrence of this facet value
* @property {boolean} isRefined true if the value is already refined
*/
/**
* Structure of the data resolved by the
* [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues)
* promise.
* @typedef FacetSearchResult
* @type {object}
* @property {FacetSearchHit} facetHits the results for this search for facet values
* @property {number} processingTimeMS time taken by the query inside the engine
*/
/**
* Search for facet values based on an query and the name of a faceted attribute. This
* triggers a search and will return a promise. On top of using the query, it also sends
* the parameters from the state so that the search is narrowed down to only the possible values.
*
* See the description of [FacetSearchResult](reference.html#FacetSearchResult)
* @param {string} facet the name of the faceted attribute
* @param {string} query the string query for the search
* @param {number} [maxFacetHits] the maximum number values returned. Should be > 0 and <= 100
* @param {object} [userState] the set of custom parameters to use on top of the current state. Setting a property to `undefined` removes
* it in the generated query.
* @return {promise.<FacetSearchResult>} the results of the search
*/
AlgoliaSearchHelper.prototype.searchForFacetValues = function(facet, query, maxFacetHits, userState) {
var clientHasSFFV = typeof this.client.searchForFacetValues === 'function';
if (
!clientHasSFFV &&
typeof this.client.initIndex !== 'function'
) {
throw new Error(
'search for facet values (searchable) was called, but this client does not have a function client.searchForFacetValues or client.initIndex(index).searchForFacetValues'
);
}
var state = this.state.setQueryParameters(userState || {});
var isDisjunctive = state.isDisjunctiveFacet(facet);
var algoliaQuery = requestBuilder.getSearchForFacetQuery(facet, query, maxFacetHits, state);
this._currentNbQueries++;
var self = this;
this.emit('searchForFacetValues', {
state: state,
facet: facet,
query: query
});
var searchForFacetValuesPromise = clientHasSFFV
? this.client.searchForFacetValues([{indexName: state.index, params: algoliaQuery}])
: this.client.initIndex(state.index).searchForFacetValues(algoliaQuery);
return searchForFacetValuesPromise.then(function addIsRefined(content) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
content = Array.isArray(content) ? content[0] : content;
content.facetHits.forEach(function(f) {
f.isRefined = isDisjunctive
? state.isDisjunctiveFacetRefined(facet, f.value)
: state.isFacetRefined(facet, f.value);
});
return content;
}, function(e) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
throw e;
});
};
/**
* Sets the text query used for the search.
*
* This method resets the current page to 0.
* @param {string} q the user query
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setQuery = function(q) {
this._change({
state: this.state.resetPage().setQuery(q),
isPageReset: true
});
return this;
};
/**
* Remove all the types of refinements except tags. A string can be provided to remove
* only the refinements of a specific attribute. For more advanced use case, you can
* provide a function instead. This function should follow the
* [clearCallback definition](#SearchParameters.clearCallback).
*
* This method resets the current page to 0.
* @param {string} [name] optional name of the facet / attribute on which we want to remove all refinements
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
* @example
* // Removing all the refinements
* helper.clearRefinements().search();
* @example
* // Removing all the filters on a the category attribute.
* helper.clearRefinements('category').search();
* @example
* // Removing only the exclude filters on the category facet.
* helper.clearRefinements(function(value, attribute, type) {
* return type === 'exclude' && attribute === 'category';
* }).search();
*/
AlgoliaSearchHelper.prototype.clearRefinements = function(name) {
this._change({
state: this.state.resetPage().clearRefinements(name),
isPageReset: true
});
return this;
};
/**
* Remove all the tag filters.
*
* This method resets the current page to 0.
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.clearTags = function() {
this._change({
state: this.state.resetPage().clearTags(),
isPageReset: true
});
return this;
};
/**
* Adds a disjunctive filter to a faceted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addDisjunctiveFacetRefinement = function(facet, value) {
this._change({
state: this.state.resetPage().addDisjunctiveFacetRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addDisjunctiveFacetRefinement}
*/
AlgoliaSearchHelper.prototype.addDisjunctiveRefine = function() {
return this.addDisjunctiveFacetRefinement.apply(this, arguments);
};
/**
* Adds a refinement on a hierarchical facet. It will throw
* an exception if the facet is not defined or if the facet
* is already refined.
*
* This method resets the current page to 0.
* @param {string} facet the facet name
* @param {string} path the hierarchical facet path
* @return {AlgoliaSearchHelper}
* @throws Error if the facet is not defined or if the facet is refined
* @chainable
* @fires change
*/
AlgoliaSearchHelper.prototype.addHierarchicalFacetRefinement = function(facet, value) {
this._change({
state: this.state.resetPage().addHierarchicalFacetRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* Adds a an numeric filter to an attribute with the `operator` and `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} attribute the attribute on which the numeric filter applies
* @param {string} operator the operator of the filter
* @param {number} value the value of the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addNumericRefinement = function(attribute, operator, value) {
this._change({
state: this.state.resetPage().addNumericRefinement(attribute, operator, value),
isPageReset: true
});
return this;
};
/**
* Adds a filter to a faceted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addFacetRefinement = function(facet, value) {
this._change({
state: this.state.resetPage().addFacetRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetRefinement}
*/
AlgoliaSearchHelper.prototype.addRefine = function() {
return this.addFacetRefinement.apply(this, arguments);
};
/**
* Adds a an exclusion filter to a faceted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addFacetExclusion = function(facet, value) {
this._change({
state: this.state.resetPage().addExcludeRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetExclusion}
*/
AlgoliaSearchHelper.prototype.addExclude = function() {
return this.addFacetExclusion.apply(this, arguments);
};
/**
* Adds a tag filter with the `tag` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} tag the tag to add to the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addTag = function(tag) {
this._change({
state: this.state.resetPage().addTagRefinement(tag),
isPageReset: true
});
return this;
};
/**
* Removes an numeric filter to an attribute with the `operator` and `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* Some parameters are optional, triggering different behavior:
* - if the value is not provided, then all the numeric value will be removed for the
* specified attribute/operator couple.
* - if the operator is not provided either, then all the numeric filter on this attribute
* will be removed.
*
* This method resets the current page to 0.
* @param {string} attribute the attribute on which the numeric filter applies
* @param {string} [operator] the operator of the filter
* @param {number} [value] the value of the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeNumericRefinement = function(attribute, operator, value) {
this._change({
state: this.state.resetPage().removeNumericRefinement(attribute, operator, value),
isPageReset: true
});
return this;
};
/**
* Removes a disjunctive filter to a faceted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeDisjunctiveFacetRefinement = function(facet, value) {
this._change({
state: this.state.resetPage().removeDisjunctiveFacetRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeDisjunctiveFacetRefinement}
*/
AlgoliaSearchHelper.prototype.removeDisjunctiveRefine = function() {
return this.removeDisjunctiveFacetRefinement.apply(this, arguments);
};
/**
* Removes the refinement set on a hierarchical facet.
* @param {string} facet the facet name
* @return {AlgoliaSearchHelper}
* @throws Error if the facet is not defined or if the facet is not refined
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeHierarchicalFacetRefinement = function(facet) {
this._change({
state: this.state.resetPage().removeHierarchicalFacetRefinement(facet),
isPageReset: true
});
return this;
};
/**
* Removes a filter to a faceted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeFacetRefinement = function(facet, value) {
this._change({
state: this.state.resetPage().removeFacetRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetRefinement}
*/
AlgoliaSearchHelper.prototype.removeRefine = function() {
return this.removeFacetRefinement.apply(this, arguments);
};
/**
* Removes an exclusion filter to a faceted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeFacetExclusion = function(facet, value) {
this._change({
state: this.state.resetPage().removeExcludeRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetExclusion}
*/
AlgoliaSearchHelper.prototype.removeExclude = function() {
return this.removeFacetExclusion.apply(this, arguments);
};
/**
* Removes a tag filter with the `tag` provided. If the
* filter is not set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} tag tag to remove from the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeTag = function(tag) {
this._change({
state: this.state.resetPage().removeTagRefinement(tag),
isPageReset: true
});
return this;
};
/**
* Adds or removes an exclusion filter to a faceted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.toggleFacetExclusion = function(facet, value) {
this._change({
state: this.state.resetPage().toggleExcludeFacetRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetExclusion}
*/
AlgoliaSearchHelper.prototype.toggleExclude = function() {
return this.toggleFacetExclusion.apply(this, arguments);
};
/**
* Adds or removes a filter to a faceted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method can be used for conjunctive, disjunctive and hierarchical filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
* @throws Error will throw an error if the facet is not declared in the settings of the helper
* @fires change
* @chainable
* @deprecated since version 2.19.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement}
*/
AlgoliaSearchHelper.prototype.toggleRefinement = function(facet, value) {
return this.toggleFacetRefinement(facet, value);
};
/**
* Adds or removes a filter to a faceted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method can be used for conjunctive, disjunctive and hierarchical filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
* @throws Error will throw an error if the facet is not declared in the settings of the helper
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.toggleFacetRefinement = function(facet, value) {
this._change({
state: this.state.resetPage().toggleFacetRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement}
*/
AlgoliaSearchHelper.prototype.toggleRefine = function() {
return this.toggleFacetRefinement.apply(this, arguments);
};
/**
* Adds or removes a tag filter with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method resets the current page to 0.
* @param {string} tag tag to remove or add
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.toggleTag = function(tag) {
this._change({
state: this.state.resetPage().toggleTagRefinement(tag),
isPageReset: true
});
return this;
};
/**
* Increments the page number by one.
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
* @example
* helper.setPage(0).nextPage().getPage();
* // returns 1
*/
AlgoliaSearchHelper.prototype.nextPage = function() {
var page = this.state.page || 0;
return this.setPage(page + 1);
};
/**
* Decrements the page number by one.
* @fires change
* @return {AlgoliaSearchHelper}
* @chainable
* @example
* helper.setPage(1).previousPage().getPage();
* // returns 0
*/
AlgoliaSearchHelper.prototype.previousPage = function() {
var page = this.state.page || 0;
return this.setPage(page - 1);
};
/**
* @private
*/
function setCurrentPage(page) {
if (page < 0) throw new Error('Page requested below 0.');
this._change({
state: this.state.setPage(page),
isPageReset: false
});
return this;
}
/**
* Change the current page
* @deprecated
* @param {number} page The page number
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setCurrentPage = setCurrentPage;
/**
* Updates the current page.
* @function
* @param {number} page The page number
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setPage = setCurrentPage;
/**
* Updates the name of the index that will be targeted by the query.
*
* This method resets the current page to 0.
* @param {string} name the index name
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setIndex = function(name) {
this._change({
state: this.state.resetPage().setIndex(name),
isPageReset: true
});
return this;
};
/**
* Update a parameter of the search. This method reset the page
*
* The complete list of parameters is available on the
* [Algolia website](https://www.algolia.com/doc/rest#query-an-index).
* The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts)
* or benefit from higher-level APIs (all the kind of filters and facets have their own API)
*
* This method resets the current page to 0.
* @param {string} parameter name of the parameter to update
* @param {any} value new value of the parameter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
* @example
* helper.setQueryParameter('hitsPerPage', 20).search();
*/
AlgoliaSearchHelper.prototype.setQueryParameter = function(parameter, value) {
this._change({
state: this.state.resetPage().setQueryParameter(parameter, value),
isPageReset: true
});
return this;
};
/**
* Set the whole state (warning: will erase previous state)
* @param {SearchParameters} newState the whole new state
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setState = function(newState) {
this._change({
state: SearchParameters.make(newState),
isPageReset: false
});
return this;
};
/**
* Override the current state without triggering a change event.
* Do not use this method unless you know what you are doing. (see the example
* for a legit use case)
* @param {SearchParameters} newState the whole new state
* @return {AlgoliaSearchHelper}
* @example
* helper.on('change', function(state){
* // In this function you might want to find a way to store the state in the url/history
* updateYourURL(state)
* })
* window.onpopstate = function(event){
* // This is naive though as you should check if the state is really defined etc.
* helper.overrideStateWithoutTriggeringChangeEvent(event.state).search()
* }
* @chainable
*/
AlgoliaSearchHelper.prototype.overrideStateWithoutTriggeringChangeEvent = function(newState) {
this.state = new SearchParameters(newState);
return this;
};
/**
* Check if an attribute has any numeric, conjunctive, disjunctive or hierarchical filters.
* @param {string} attribute the name of the attribute
* @return {boolean} true if the attribute is filtered by at least one value
* @example
* // hasRefinements works with numeric, conjunctive, disjunctive and hierarchical filters
* helper.hasRefinements('price'); // false
* helper.addNumericRefinement('price', '>', 100);
* helper.hasRefinements('price'); // true
*
* helper.hasRefinements('color'); // false
* helper.addFacetRefinement('color', 'blue');
* helper.hasRefinements('color'); // true
*
* helper.hasRefinements('material'); // false
* helper.addDisjunctiveFacetRefinement('material', 'plastic');
* helper.hasRefinements('material'); // true
*
* helper.hasRefinements('categories'); // false
* helper.toggleFacetRefinement('categories', 'kitchen > knife');
* helper.hasRefinements('categories'); // true
*
*/
AlgoliaSearchHelper.prototype.hasRefinements = function(attribute) {
if (objectHasKeys(this.state.getNumericRefinements(attribute))) {
return true;
} else if (this.state.isConjunctiveFacet(attribute)) {
return this.state.isFacetRefined(attribute);
} else if (this.state.isDisjunctiveFacet(attribute)) {
return this.state.isDisjunctiveFacetRefined(attribute);
} else if (this.state.isHierarchicalFacet(attribute)) {
return this.state.isHierarchicalFacetRefined(attribute);
}
// there's currently no way to know that the user did call `addNumericRefinement` at some point
// thus we cannot distinguish if there once was a numeric refinement that was cleared
// so we will return false in every other situations to be consistent
// while what we should do here is throw because we did not find the attribute in any type
// of refinement
return false;
};
/**
* Check if a value is excluded for a specific faceted attribute. If the value
* is omitted then the function checks if there is any excluding refinements.
*
* @param {string} facet name of the attribute for used for faceting
* @param {string} [value] optional value. If passed will test that this value
* is filtering the given facet.
* @return {boolean} true if refined
* @example
* helper.isExcludeRefined('color'); // false
* helper.isExcludeRefined('color', 'blue') // false
* helper.isExcludeRefined('color', 'red') // false
*
* helper.addFacetExclusion('color', 'red');
*
* helper.isExcludeRefined('color'); // true
* helper.isExcludeRefined('color', 'blue') // false
* helper.isExcludeRefined('color', 'red') // true
*/
AlgoliaSearchHelper.prototype.isExcluded = function(facet, value) {
return this.state.isExcludeRefined(facet, value);
};
/**