forked from CottageLabs/facetview2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.facetview2.js
1712 lines (1412 loc) · 76.4 KB
/
jquery.facetview2.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
/*
* jquery.facetview2.js
*
* displays faceted browse results by querying a specified elasticsearch index
*
* http://cottagelabs.com
*
*/
/*****************************************************************************
* JAVASCRIPT PATCHES
****************************************************************************/
// Deal with indexOf issue in <IE9
// provided by commentary in repo issue - https://github.com/okfn/facetview/issues/18
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement /*, fromIndex */ ) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
}
}
/*****************************************************************************
* UTILITIES
****************************************************************************/
// first define the bind with delay function from (saves loading it separately)
// https://github.com/bgrins/bindWithDelay/blob/master/bindWithDelay.js
(function($) {
$.fn.bindWithDelay = function( type, data, fn, timeout, throttle ) {
var wait = null;
var that = this;
if ( $.isFunction( data ) ) {
throttle = timeout;
timeout = fn;
fn = data;
data = undefined;
}
function cb() {
var e = $.extend(true, { }, arguments[0]);
var throttler = function() {
wait = null;
fn.apply(that, [e]);
};
if (!throttle) { clearTimeout(wait); }
if (!throttle || !wait) { wait = setTimeout(throttler, timeout); }
}
return this.bind(type, data, cb);
};
})(jQuery);
function safeId(s) {
return s.replace(/\./gi,'_').replace(/\:/gi,'_')
}
// get the right facet element from the page
function facetElement(prefix, name, context) {
return $(prefix + safeId(name), context)
}
// get the right facet from the options, based on the name
function selectFacet(options, name) {
for (var i = 0; i < options.facets.length; i++) {
var item = options.facets[i];
if ('field' in item) {
if (item['field'] === name) {
return item
}
}
}
}
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
function ie8compat(o) {
// Clean up all array options
// IE8 interprets trailing commas as introducing an undefined
// object, e.g. ["a", "b", "c",] means ["a", "b", "c", undefined]
// in IE8. And maybe in older IE-s. So the user loading
// facetview might have put trailing commas in their config, but
// this will cause facetview to break in IE8 - so clean up!
function delete_last_element_of_array_if_undefined(array, recurse) {
var recurse = recurse || false;
if ($.type(array) == 'array') {
// delete the last item if it's undefined
if (array.length > 0 && $.type(array[array.length - 1]) == 'undefined') {
array.splice(array.length - 1, 1);
}
}
if (recurse) {
for ( var each = 0; each < array.length; each++ ) {
if ($.type(array[each]) == 'array') {
delete_last_element_of_array_if_undefined(array[each], true);
}
}
}
}
// first see if this clean up is necessary at all
var test = ["a", "b", "c", ]; // note trailing comma, will produce ["a", "b", "c", undefined] in IE8 and ["a", "b", "c"] in every sane browser
if ($.type(test[test.length - 1]) == 'undefined') {
// ok, cleanup is necessary, go
for (var key in o) {
if (o.hasOwnProperty(key)) {
var option = o[key];
delete_last_element_of_array_if_undefined(option, true);
}
}
}
}
/******************************************************************
* DEFAULT CALLBACKS
*****************************************************************/
///// the lifecycle callbacks ///////////////////////
function postInit(options, context) {}
function preSearch(options, context) {}
function postSearch(options, context) {}
function preRender(options, context) {}
function postRender(options, context) {}
/******************************************************************
* URL MANAGEMENT
*****************************************************************/
function shareableUrl(options, query_part_only, include_fragment) {
var source = elasticSearchQuery({"options" : options, "include_facets" : options.include_facets_in_url, "include_fields" : options.include_fields_in_url})
var querypart = "?source=" + encodeURIComponent(serialiseQueryObject(source))
include_fragment = include_fragment === undefined ? true : include_fragment
if (include_fragment) {
var fragment_identifier = options.url_fragment_identifier ? options.url_fragment_identifier : "";
querypart += fragment_identifier
}
if (query_part_only) {
return querypart
}
return 'http://' + window.location.host + window.location.pathname + querypart
}
function getUrlVars() {
var params = new Object;
var url = window.location.href;
var anchor = undefined;
if (url.indexOf("#") > -1) {
anchor = url.slice(url.indexOf('#'));
url = url.substring(0, url.indexOf('#'));
}
var hashes = url.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
var hash = hashes[i].split('=');
if (hash.length > 1) {
var newval = decodeURIComponent(hash[1]);
if (newval[0] == "[" || newval[0] == "{") {
// if it looks like a JSON object in string form...
// remove " (double quotes) at beginning and end of string to make it a valid
// representation of a JSON object, or the parser will complain
newval = newval.replace(/^"/,"").replace(/"$/,"");
var newval = JSON.parse(newval);
}
params[hash[0]] = newval;
}
}
if (anchor) {
params['url_fragment_identifier'] = anchor;
}
return params;
}
/******************************************************************
* FACETVIEW ITSELF
*****************************************************************/
(function($){
$.fn.facetview = function(options) {
// Load the Altmetric badge script
$.getScript("https://d1bxh8uas1mnw7.cloudfront.net/assets/embed.js", function(){
});
/**************************************************************
* handle the incoming options, default options and url parameters
*************************************************************/
// all of the possible options that will be used in the facetview lifecycle
// along with their documentation
var defaults = {
///// elasticsearch parameters /////////////////////////////
// the base search url which will respond to elasticsearch queries. Generally ends with _search
"search_url" : "http://localhost:9200/_search",
// datatype for ajax requests to use - overall recommend using jsonp
"datatype" : "json",
// if set, should be either * or ~
// if *, * will be prepended and appended to each string in the freetext search term
// if ~, ~ then ~ will be appended to each string in the freetext search term.
// If * or ~ or : are already in the freetext search term, no action will be taken.
"default_freetext_fuzzify": false, // or ~ or *
// due to a bug in elasticsearch's clustered node facet counts, we need to inflate
// the number of facet results we need to ensure that the results we actually want are
// accurate. This option tells us by how much.
// NOTE This also determines the max value of the '... view n more' link at the end of the facet
"elasticsearch_facet_inflation" : 100,
///// query aspects /////////////////////////////
// list of fields to be returned by the elasticsearch query. If omitted, full result set is returned
"fields" : false, // or an array of field names
// list of partial fields to be returned by the elasticsearch query. If omitted, full result set is returned
"partial_fields" : false, // or an array of partial fields
// list of script fields to be executed. Note that you should, in general, not pass actual scripts but
// references to stored scripts in the back-end ES. If not false, then an object corresponding to the
// ES script_fields structure
"script_fields" : false,
// number of results to display per page (i.e. to retrieve per query)
// NOTE ignored if page_size_dropdown is set to true in options
"page_size" : 10,
// enable the result size drop down, remove custom entry box
"page_size_dropdown" : false,
// page size options for down down menu
"page_size_options" : [10,25,50,100],
// cursor position in the elasticsearch result set
"from" : 0,
// list of fields and directions to sort in. Note that the UI only supports single value sorting
"sort" : [], // or something like [ {"title" : {"order" : "asc"}} ]
// field on which to focus the freetext search
"searchfield" : "", // e.g. title.exact
// fields to search on the freetext search
// NOTE ignored if searchfield is set.
// functionally, searchfield sets 'default_field' in the elasticsearch query
// while search_fields_multi sets 'fields'
"search_fields_multi" : "", // e.g. ["*folded","_all"]
// minimum score for returned free text query results
// usually only necessary if searching a field indexed using an ngram analyzer
"min_score" : null,
// freetext search string
"q" : "",
// add a button for csv export. requires the elasticsearch csv plugin (https://github.com/jprante/elasticsearch-csv)
"csv_export" : false,
// key fields to add to CSV export. usually best to set this on type by type basis.
"csv_keys" : "",
///// facet aspects /////////////////////////////
// The list of facets to be displayed and used to seed the filtering processes.
// Facets are complex fields which can look as follows:
/*
{
"field" : "<elasticsearch field>" // field upon which to facet
"display" : "<display name>", // display name for the UI
"type": "terms|range|geo_distance|statistical|date_histogram", // the kind of facet this will be
"open" : true|false, // whether the facet should be open or closed (initially)
"hidden" : true|false // whether the facet should be displayed at all (e.g. you may just want the data for a callback)
"disabled" : true|false // whether the facet should be acted upon in any way. This might be useful if you want to enable/disable facets under different circumstances via a callback
"tooltip" : "<html to be displayed under the facet's tool tip>" // if present the facet will present a link with the tooltip_text which would give the user some text or other functionality
"tooltip_text" : "<text to use to open the tooltip>", // sets the text of the tooltip link
// terms facet only
"size" : <num>, // how many terms should the facet limit to
"logic" : "AND|OR", // Whether to AND or OR selected facets together when filtering
"order" : "count|reverse_count|term|reverse_term", // which standard ordering to use for facet values
"deactivate_threshold" : <num>, // number of facet terms below which the facet is disabled
"hide_inactive" : true|false, // whether to hide or just disable the facet if below deactivate threshold
"value_function" : <function>, // function to be called on each value before display
"controls" : true|false // should the facet sort/size/bool controls be shown?
"ignore_empty_string" : true|false // should the terms facet ignore empty strings in display
// range facet only
"range" : [ // list of ranges (in order) which define the filters
{"from" : <num>, "to" : <num>, "display" : "<display name>"} // from = lower bound (inclusive), to = upper boud (exclusive)
], // display = display name for this range
"hide_empty_range" : true|false, // if there are no results for a given range, should it be hidden
// geo distance facet only
"distance" : [ // list of distances (in order) which define the filters
{"from" : <num>, "to" : <num>, "display" : "<display name>"} // from = lower bound (inclusive), to = upper boud (exclusive)
], // display = display name for this distance
"hide_empty_distance" : true|false, // if there are no results for a given distance, should it be hidden
"unit" : "<unit of distance, e.g. km or mi>" // unit to calculate distances in (e.g. km or mi)
"lat" : <latitude> // latitude from which to measure distances
"lon" : <longitude> // longitude from which to measure distances
// date histogram facet only
"interval" : "year, quarter, month, week, day, hour, minute ,second" // period to use for date histogram
"sort" : "asc|desc", // which ordering to use for date histogram
"hide_empty_date_bin" : true|false // whether to suppress display of date range with no values
"short_display" : <number to display initially> // the number of values to show initially (note you should set size=false)
// admin use only
"values" : <object> // the values associated with a successful query on this facet
}
*/
"facets" : [],
// user defined extra facets. These must be pre-formatted for elasticsearch, and they will
// simply be added to the query at query-time.
"extra_facets": {},
// default settings for each of the facet properties above. If a facet lacks a property, it will
// be initialised to the default
"default_facet_type" : "terms",
"default_facet_open" : false,
"default_facet_hidden" : false,
"default_facet_size" : 10,
"default_facet_operator" : "AND", // logic
"default_facet_order" : "count",
"default_facet_hide_inactive" : false,
"default_facet_deactivate_threshold" : 0, // equal to or less than this number will deactivate the facet
"default_facet_controls" : true,
"default_hide_empty_range" : true,
"default_hide_empty_distance" : true,
"default_distance_unit" : "km",
"default_distance_lat" : 51.4768, // Greenwich meridian (give or take a few decimal places)
"default_distance_lon" : 0.0, //
"default_date_histogram_interval" : "year",
"default_hide_empty_date_bin" : true,
"default_date_histogram_sort" : "asc",
"default_short_display" : false,
"default_ignore_empty_string" : false, // because filtering out empty strings is less performant
"default_tooltip" : false,
"default_tooltip_text" : "learn more",
///// search bar configuration /////////////////////////////
// list of options by which the search results can be sorted
// of the form of a list of: { 'display' : '<display name>', 'field' : '<field to sort by>'},
"search_sortby" : [],
// list of options for fields to which free text search can be constrained
// of the form of a list of: { 'display' : '<display name>', 'field' : '<field to search on>'},
"searchbox_fieldselect" : [],
// enable the share/save link feature
"sharesave_link" : true,
// provide a function which will do url shortening for the sharesave_link box
"url_shortener" : false,
// on free-text search, default operator for the elasticsearch query system to use
"default_operator" : "OR",
// enable the search button
"search_button" : false,
// amount of time between finishing typing and when a query is executed from the search box
"freetext_submit_delay" : 500,
///// url configuration /////////////////////////////
// FIXME: should we read in facets from urls, and if we do, what should we do about them?
// should facets be included in shareable urls. Turning this on makes them very long, and currently
// facetview does not read those facets back in if the URLs are parsed
"include_facets_in_url" : false,
// FIXME: should we read in fields from urls, and if we do, what should we do about them?
// should fields be included in shareable urls. Turning this on makes them very long, and currently
// facetview does not read those fields back in if the URLs are parsed
"include_fields_in_url" : false,
///// selected filters /////////////////////////////
// should the facet navigation show filters alongside other facet results which have not been selected
"selected_filters_in_facet" : true,
// should the "selected filters" area show the name of the facet from which the filter was selected
"show_filter_field" : true,
// should the "selected filters" area show the boolean logic used by the filter (taken from the facet.logic configuration)
"show_filter_logic" : true,
// FIXME: add support for pre-defined range filters
// a set of pre-defined filters which will always be applied to the search.
// Has the following structure, and works for terms filters only
// { "<field>" : ["<list of values>"] }
// requires a facet for the given field to be defined
"predefined_filters" : {},
// exclude any values that appear in pre-defined filters from any facets
// This prevents configuration-set filters from ever being seen in a facet, but ensures that
// they are always included when the search is carried out
"exclude_predefined_filters_from_facets" : true,
// current active filters
// DO NOT USE - this is for tracking internal state ONLY
"active_filters" : {},
///// general behaviour /////////////////////////////
// after initialisation, begin automatically with a search
"initialsearch" : true,
// enable debug. If debug is enabled, some technical information will be dumped to a
// visible textarea on the screen
"debug" : false,
// after search, the results will fade in over this number of milliseconds
"fadein" : 800,
// should the search url be synchronised with the browser's url bar after search
// NOTE: does not work in some browsers. See also share/save link option.
"pushstate" : true,
///// render functions /////////////////////////////
// for each render function, see the reference implementation for documentation on how they should work
// render the frame within which the facetview sits
"render_the_facetview" : theFacetview,
// render the search box - containing freetext search
"render_search_box" : searchBox,
// render the search options - containing sorting, etc
"render_search_options" : searchOptions,
// render the list of available facets. This will in turn call individual render methods
// for each facet type
"render_facet_list" : facetList,
// render the terms facet, the list of values, and the value itself
"render_terms_facet" : renderTermsFacet, // overall framework for a terms facet
"render_terms_facet_values" : renderTermsFacetValues, // the list of terms facet values
"render_terms_facet_result" : renderTermsFacetResult, // individual terms facet values
// render the range facet, the list of values, and the value itself
"render_range_facet" : renderRangeFacet, // overall framework for a range facet
"render_range_facet_values" : renderRangeFacetValues, // the list of range facet values
"render_range_facet_result" : renderRangeFacetResult, // individual range facet values
// render the geo distance facet, the list of values and the value itself
"render_geo_facet" : renderGeoFacet, // overall framework for a geo distance facet
"render_geo_facet_values" : renderGeoFacetValues, // the list of geo distance facet values
"render_geo_facet_result" : renderGeoFacetResult, // individual geo distance facet values
// render the date histogram facet
"render_date_histogram_facet" : renderDateHistogramFacet,
"render_date_histogram_values" : renderDateHistogramValues,
"render_date_histogram_result" : renderDateHistogramResult,
// render any searching notification (which will then be shown/hidden as needed)
"render_searching_notification" : searchingNotification,
// render the paging controls
"render_results_metadata" : basicPager, // or pageSlider
// render a "results not found" message
"render_not_found" : renderNotFound,
// render an individual result record
"render_result_record" : renderResultRecord,
// render a terms filter interface component (e.g. the filter name, boolean operator used, and selected values)
"render_active_terms_filter" : renderActiveTermsFilter,
// render a range filter interface component (e.g. the filter name and the human readable description of the selected range)
"render_active_range_filter" : renderActiveRangeFilter,
// render a geo distance filter interface component (e.g. the filter name and the human readable description of the selected range)
"render_active_geo_filter" : renderActiveGeoFilter,
// render a date histogram/range interface component (e.g. the filter name and the human readable description of the selected range)
"render_active_date_histogram_filter" : renderActiveDateHistogramFilter,
///// configs for standard render functions /////////////////////////////
// if you provide your own render functions you may or may not want to re-use these
"resultwrap_start":"<tr><td>",
"resultwrap_end":"</td></tr>",
"result_display" : [ [ {"pre" : "<strong>ID</strong>:", "field": "id", "post" : "<br><br>"} ] ],
"results_render_callbacks" : {},
///// behaviour functions /////////////////////////////
// called at the start of searching to display the searching notification
"behaviour_show_searching" : showSearchingNotification,
// called at the end of searching to hide the searching notification
"behaviour_finished_searching" : hideSearchingNotification,
// called after rendering a facet to determine whether it is visible/disabled
"behaviour_facet_visibility" : setFacetVisibility,
// called after rendering a facet to determine whether it should be open or closed
"behaviour_toggle_facet_open" : setFacetOpenness,
// called after changing the result set order to update the search bar
"behaviour_results_ordering" : setResultsOrder,
// called when the page size is changed
"behaviour_set_page_size" : setUIPageSize,
// called when page size changed by drop down
"behaviour_set_page_size_drop" : setUIPageSizeDrop,
// called when the page order is changed
"behaviour_set_order" : setUIOrder,
// called when the field we order by is changed
"behaviour_set_order_by" : setUIOrderBy,
// called when the search field is changed
"behaviour_set_search_field" : setUISearchField,
// called when the search string is set or updated
"behaviour_set_search_string" : setUISearchString,
// called when the facet size has been changed
"behaviour_set_facet_size" : setUIFacetSize,
// called when the facet sort order has changed
"behaviour_set_facet_sort" : setUIFacetSort,
// called when the facet And/Or setting has been changed
"behaviour_set_facet_and_or" : setUIFacetAndOr,
// called when the selected filters have changed
"behaviour_set_selected_filters" : setUISelectedFilters,
// called when the share url is shortened/lengthened
"behaviour_share_url" : setUIShareUrlChange,
"behaviour_date_histogram_showall" : dateHistogramShowAll,
"behaviour_date_histogram_showless" : dateHistogramShowLess,
///// lifecycle callbacks /////////////////////////////
// the default callbacks don't have any effect - replace them as needed
"post_init_callback" : postInit,
"pre_search_callback" : preSearch,
"post_search_callback" : postSearch,
"pre_render_callback" : preRender,
"post_render_callback" : postRender,
///// internal state monitoring /////////////////////////////
// these are used internally DO NOT USE
// they are here for completeness and documentation
// is a search currently in progress
"searching" : false,
// the raw query object
"queryobj" : false,
// the raw data coming back from elasticsearch
"rawdata" : false,
// the parsed data from elasticsearch
"data" : false,
// the short url for the current search, if it has been generated
"current_short_url" : false,
// should the short url or the long url be displayed to the user?
"show_short_url" : false
};
// Replace the default page size if page size options are defined
if (options.page_size_options && options.page_size_dropdown){
defaults['page_size'] = options.page_size_options[0];
}
function deriveOptions() {
// cleanup for ie8 purposes
ie8compat(options);
ie8compat(defaults);
// extend the defaults with the provided options
var provided_options = $.extend(defaults, options);
// deal with the options that come from the url, which require some special treatment
var url_params = getUrlVars();
var url_options = {};
if ("source" in url_params) {
url_options = optionsFromQuery(url_params["source"])
}
if ("url_fragment_identifier" in url_params) {
url_options["url_fragment_identifier"] = url_params["url_fragment_identifier"]
}
provided_options = $.extend(provided_options, url_options);
// copy the _selected_operators data into the relevant facets
// for each pre-selected operator, find the related facet and set its "logic" property
var so = provided_options._selected_operators ? provided_options._selected_operators : {};
for (var field in so) {
if (so.hasOwnProperty(field)) {
var operator = so[field];
for (var i=0; i < provided_options.facets.length; i=i+1) {
var facet = provided_options.facets[i];
if (facet.field === field) {
facet["logic"] = operator
}
}
}
}
if ("_selected_operators" in provided_options) {
delete provided_options._selected_operators
}
// tease apart the active filters from the predefined filters
if (!provided_options.predefined_filters) {
provided_options["active_filters"] = provided_options._active_filters
delete provided_options._active_filters
} else {
provided_options["active_filters"] = {};
for (var field in provided_options._active_filters) {
if (provided_options._active_filters.hasOwnProperty(field)) {
var filter_list = provided_options._active_filters[field];
provided_options["active_filters"][field] = [];
if (!(field in provided_options.predefined_filters)) {
provided_options["active_filters"][field] = filter_list
} else {
// FIXME: this does not support pre-defined range queries
var predefined_values = provided_options.predefined_filters[field];
for (var i=0; i < filter_list.length; i=i+1) {
var value = filter_list[i];
if ($.inArray(value, predefined_values) === -1) {
provided_options["active_filters"][field].push(value)
}
}
}
if (provided_options["active_filters"][field].length === 0) {
delete provided_options["active_filters"][field]
}
}
}
}
// copy in the defaults to the individual facets when they are needed
for (var i=0; i < provided_options.facets.length; i=i+1) {
var facet = provided_options.facets[i];
if (!("type" in facet)) { facet["type"] = provided_options.default_facet_type }
if (!("open" in facet)) { facet["open"] = provided_options.default_facet_open }
if (!("hidden" in facet)) { facet["hidden"] = provided_options.default_facet_hidden }
if (!("size" in facet)) { facet["size"] = provided_options.default_facet_size }
if (!("logic" in facet)) { facet["logic"] = provided_options.default_facet_operator }
if (!("order" in facet)) { facet["order"] = provided_options.default_facet_order }
if (!("hide_inactive" in facet)) { facet["hide_inactive"] = provided_options.default_facet_hide_inactive }
if (!("deactivate_threshold" in facet)) { facet["deactivate_threshold"] = provided_options.default_facet_deactivate_threshold }
if (!("controls" in facet)) { facet["controls"] = provided_options.default_facet_controls }
if (!("hide_empty_range" in facet)) { facet["hide_empty_range"] = provided_options.default_hide_empty_range }
if (!("hide_empty_distance" in facet)) { facet["hide_empty_distance"] = provided_options.default_hide_empty_distance }
if (!("unit" in facet)) { facet["unit"] = provided_options.default_distance_unit }
if (!("lat" in facet)) { facet["lat"] = provided_options.default_distance_lat }
if (!("lon" in facet)) { facet["lon"] = provided_options.default_distance_lon }
if (!("value_function" in facet)) { facet["value_function"] = function(value) { return value } }
if (!("interval" in facet)) { facet["interval"] = provided_options.default_date_histogram_interval }
if (!("hide_empty_date_bin" in facet)) { facet["hide_empty_date_bin"] = provided_options.default_hide_empty_date_bin }
if (!("sort" in facet)) { facet["sort"] = provided_options.default_date_histogram_sort }
if (!("disabled" in facet)) { facet["disabled"] = false } // no default setter for this - if you don't specify disabled, they are not disabled
if (!("short_display" in facet)) { facet["short_display"] = provided_options.default_short_display }
if (!("ignore_empty_string" in facet)) { facet["ignore_empty_string"] = provided_options.default_ignore_empty_string }
if (!("tooltip" in facet)) { facet["tooltip"] = provided_options.default_tooltip }
if (!("tooltip_text" in facet)) { facet["tooltip_text"] = provided_options.default_tooltip_text }
}
return provided_options
}
/******************************************************************
* OPTIONS MANAGEMENT
*****************************************************************/
function uiFromOptions() {
// set the current page size
options.behaviour_set_page_size(options, obj, {size: options.page_size});
// options.behaviour_set_page_size_drop(options, obj, {size: options.page_size});
// set the search order
var sorting = options.sort;
if (sorting.length > 1) {
var fields = [];
for (var i = 0; i < sorting.length; i++) {
var so = sorting[i];
var field = Object.keys(so);
fields.push(field)
}
sortoption = ''
sortoption = sortoption + '[';
sortoption = sortoption + "'" + fields.join("','") + "'";
sortoption = sortoption + ']';
// Do we need to set the order direction here?
options.behaviour_set_order_by(options, obj, {orderby: sortoption});
}
else {
sortoption = Object.keys(sorting[0])[0]
var dir = sorting[0][sortoption]["order"];
options.behaviour_set_order(options, obj, {order: dir});
options.behaviour_set_order_by(options, obj, {orderby: sortoption});
}
// set the search field
options.behaviour_set_search_field(options, obj, {field : options.searchfield});
// set the search string
options.behaviour_set_search_string(options, obj, {q: options.q});
// for each facet, set the facet size, order and and/or status
for (var i=0; i < options.facets.length; i=i+1) {
var f = options.facets[i];
if (f.hidden) {
continue;
}
options.behaviour_set_facet_size(options, obj, {facet : f});
options.behaviour_set_facet_sort(options, obj, {facet : f});
options.behaviour_set_facet_and_or(options, obj, {facet : f});
}
// for any existing filters, render them
options.behaviour_set_selected_filters(options, obj);
}
function urlFromOptions() {
if (options.pushstate && 'pushState' in window.history) {
var querypart = shareableUrl(options, true, true);
window.history.pushState("", "search", querypart);
}
// also set the default shareable url at this point
setShareableUrl()
}
/******************************************************************
* DEBUG
*****************************************************************/
function addDebug(msg, context) {
$(".facetview_debug", context).show().find("textarea").append(msg + "\n\n")
}
/**************************************************************
* functions for managing search option events
*************************************************************/
/////// paging /////////////////////////////////
// adjust how many results are shown
function clickPageSize(event) {
event.preventDefault();
var newhowmany = prompt('Currently displaying ' + options.page_size +
' results per page. How many would you like instead?');
if (newhowmany) {
options.page_size = parseInt(newhowmany);
options.from = 0;
options.behaviour_set_page_size(options, obj, {size: options.page_size});
options.behaviour_set_page_size_drop(options, obj, {size: options.page_size}); // TODO Remove this once I figure out how to implement the derp down correctly
doSearch();
}
}
/////// start again /////////////////////////////////
// erase the current search and reload the window
function clickStartAgain(event) {
event.preventDefault();
var base = window.location.href.split("?")[0];
//console.log(base)
window.location.replace(base);
//if(window.location.href.match(base)) {
// window.location.reload();
//}
//else { window.location.replace(base);}
}
/////// search ordering dropdown mod /////////////////////////////////
//
function changePageSize(event) {
event.preventDefault();
sizechoice = ($(this).attr('id'))
// switch item with 'selected' class
$('.facetview_size_drop', obj).removeClass('selected')
$(this).addClass('selected')
// synchronise the new sort with the options
savePageSizeOption(sizechoice);
// reset the cursor and issue a search
options.from = 0;
doSearch();
}
function savePageSizeOption(sizechoice) {
if (!sizechoice) {
var sizechoice = $('.facetview_size_drop', obj).val();
}
options.page_size = parseInt(sizechoice);
options.from = 0;
options.behaviour_set_page_size(options, obj, {size: options.page_size}); // TODO Remove once drop down is working correctly
options.behaviour_set_page_size_drop(options, obj, {size: options.page_size});
doSearch();
}
function changeOrderBy(event) {
event.preventDefault();
sortchoice = ($(this).attr('id'))
options.behaviour_set_order_by(options, obj, {orderby: sortchoice})
// switch item with 'selected' class
$('.facetview_orderby', obj).removeClass('selected')
$(this).addClass('selected')
// $('.dropdown-toggle').html($(this).html() + '<span class="caret"></span>');
// synchronise the new sort with the options
saveSortOption(sortchoice);
// reset the cursor and issue a search
options.from = 0;
doSearch();
}
/////// search ordering /////////////////////////////////
function clickOrder(event) {
event.preventDefault();
// switch the sort options around
if ($(this).attr('href') == 'desc') {
options.behaviour_set_order(options, obj, {order: "asc"})
} else {
options.behaviour_set_order(options, obj, {order: "desc"})
};
// synchronise the new sort with the options
saveSortOption();
// reset the cursor and issue a search
options.from = 0;
doSearch();
}
// save the sort options from the current UI
function saveSortOption(sortchoice) {
if (!sortchoice) { // I'm sure there's a beter way to do this //THIS NEEDS TO BE SET TO THE CORRECT SORT OPTIONS!!!!!
var sortchoice = $('.facetview_orderby', obj).val();
}
console.log($('.facetview_orderby', obj))
console.log($('.facetview_orderby', obj).val())
if (sortchoice) {
var sorting = [];
if (sortchoice.indexOf('[') === 0) {
sort_fields = JSON.parse(sortchoice.replace(/'/g, '"'));
for ( var each = 0; each < sort_fields.length; each++ ) {
sf = sort_fields[each];
sortobj = {};
sortobj[sf] = {'order': $('.facetview_order', obj).attr('href')};
sorting.push(sortobj);
}
} else {
sortobj = {};
sortobj[sortchoice] = {'order': $('.facetview_order', obj).attr('href')};
sorting.push(sortobj);
}
options.sort = sorting;
} else {
sortobj = {};
sortobj["_score"] = {'order': $('.facetview_order', obj).attr('href')};
sorting = [sortobj];
options.sort = sorting
}
}
/////// csv export /////////////////////////////////
function clickCSV(event) {
event.preventDefault();
if (options.csv_keys) {
csv_link = options.search_url + '_csv' + shareableUrl(options,true).replace('size%22%3A10','size%22%3A999999') + '&keys=' + options.csv_keys
}
else {
var data = options.data.records
var result = []
function recurse (cur, prop) {
if (Object(cur) !== cur) {
result[prop] = cur;
} else if (Array.isArray(cur)) {
for(var i=0, l=cur.length; i<l; i++)
recurse(cur[i], prop + "." + i + "");
if (l == 0)
result[prop] = [];
} else {
var isEmpty = true;
for (var p in cur) {
isEmpty = false;
recurse(cur[p], prop ? prop+"."+p : p);
}
if (isEmpty && prop)
result[prop] = {};
}
}
recurse(data, "");
row = ['name','uri'];
for (key in result){
numlength = (key.split('.',2)[1].length) // there's gotta be a better way
key = key.substr(2+numlength)
if (row.indexOf(key) < 0) {
row.push(key)
}
}
csv_link = options.search_url + '_csv' + shareableUrl(options,true).replace('size%22%3A10','size%22%3A999999') + '&keys=' + row.join()
}
window.location.href = csv_link;
}
/////// search fields /////////////////////////////////
// adjust the search field focus
function changeSearchField(event) {
event.preventDefault();
var field = $(this).val();
options.from = 0;
options.searchfield = field;
doSearch();
};
// keyup in search box
function keyupSearchText(event) {
event.preventDefault();
var q = $(this).val();
options.from = 0;
options.q = q;
doSearch()
}
// click of the search button
function clickSearch() {
event.preventDefault();
var q = $(".facetview_freetext", obj).val();
options.from = 0;