Bug 32185: Fix template typo in opac-reserve.pl
[koha.git] / koha-tmpl / opac-tmpl / bootstrap / js / datatables.js
1 /* global __ */
2 // These default options are for translation but can be used
3 // for any other datatables settings
4 // To use it, write:
5 //  $("#table_id").dataTable($.extend(true, {}, dataTableDefaults, {
6 //      // other settings
7 //  } ) );
8 var dataTablesDefaults = {
9     "language": {
10         "paginate": {
11             "first"    : window.MSG_DT_FIRST || "First",
12             "last"     : window.MSG_DT_LAST || "Last",
13             "next"     : window.MSG_DT_NEXT || "Next",
14             "previous" : window.MSG_DT_PREVIOUS || "Previous"
15         },
16         "emptyTable"       : window.MSG_DT_EMPTY_TABLE || "No data available in table",
17         "info"             : window.MSG_DT_INFO || "Showing _START_ to _END_ of _TOTAL_ entries",
18         "infoEmpty"        : window.MSG_DT_INFO_EMPTY || "No entries to show",
19         "infoFiltered"     : window.MSG_DT_INFO_FILTERED || "(filtered from _MAX_ total entries)",
20         "lengthMenu"       : window.MSG_DT_LENGTH_MENU || "Show _MENU_ entries",
21         "loadingRecords"   : window.MSG_DT_LOADING_RECORDS || "Loading...",
22         "processing"       : window.MSG_DT_PROCESSING || "Processing...",
23         "search"           : window.MSG_DT_SEARCH || "Search:",
24         "zeroRecords"      : window.MSG_DT_ZERO_RECORDS || "No matching records found",
25         buttons: {
26             "copyTitle"     : window.MSG_DT_COPY_TO_CLIPBOARD || "Copy to clipboard",
27             "copyKeys"      : window.MSG_DT_COPY_KEYS || "Press <i>ctrl</i> or <i>⌘</i> + <i>C</i> to copy the table data<br>to your system clipboard.<br><br>To cancel, click this message or press escape.",
28             "copySuccess": {
29                 _: window.MSG_DT_COPIED_ROWS || "Copied %d rows to clipboard",
30                 1: window.MSG_DT_COPIED_ONE_ROW || "Copied one row to clipboard",
31             },
32             "print": __("Print")
33         }
34     },
35     "dom": 't',
36     "buttons": [
37         'clearFilter', 'copy', 'csv', 'print'
38     ],
39     "paginate": false,
40     initComplete: function( settings) {
41         var tableId = settings.nTable.id
42         // When the DataTables search function is triggered,
43         // enable or disable the "Clear filter" button based on
44         // the presence of a search string
45         $("#" + tableId ).on( 'search.dt', function ( e, settings ) {
46             if( settings.oPreviousSearch.sSearch == "" ){
47                 $("#" + tableId + "_wrapper").find(".dt_button_clear_filter").addClass("disabled");
48             } else {
49                 $("#" + tableId + "_wrapper").find(".dt_button_clear_filter").removeClass("disabled");
50             }
51         });
52     }
53 };
54
55 $.fn.dataTable.ext.buttons.clearFilter = {
56     fade: 100,
57     className: "dt_button_clear_filter",
58     titleAttr: window.MSG_CLEAR_FILTER,
59     enabled: false,
60     text: '<i class="fa fa-lg fa-remove"></i> <span class="dt-button-text">' + window.MSG_CLEAR_FILTER + '</span>',
61     available: function ( dt ) {
62         // The "clear filter" button is made available if this test returns true
63         if( dt.settings()[0].aanFeatures.f ){ // aanFeatures.f is null if there is no search form
64             return true;
65         }
66     },
67     action: function ( e, dt, node ) {
68         dt.search( "" ).draw("page");
69         node.addClass("disabled");
70     }
71 };
72
73 (function() {
74
75     /* Plugin to allow text sorting to ignore articles
76      *
77      * In DataTables config:
78      *     "aoColumns": [
79      *        { "sType": "anti-the" },
80      *      ]
81      * Based on the plugin found here:
82      * http://datatables.net/plug-ins/sorting#anti_the
83      * Modified to exclude HTML tags from sorting
84      * Extended to accept a string of space-separated articles
85      * from a configuration file (in English, "a," "an," and "the")
86      */
87
88     var config_exclude_articles_from_sort = window.CONFIG_EXCLUDE_ARTICLES_FROM_SORT || "a an the";
89     if (config_exclude_articles_from_sort){
90         var articles = config_exclude_articles_from_sort.split(" ");
91         var rpattern = "";
92         for( var i=0; i<articles.length; i++){
93             rpattern += "^" + articles[i] + " ";
94             if(i < articles.length - 1){ rpattern += "|"; }
95         }
96         var re = new RegExp(rpattern, "i");
97     }
98
99     jQuery.extend( jQuery.fn.dataTableExt.oSort, {
100         "anti-the-pre": function ( a ) {
101             var x = String(a).replace( /<[\s\S]*?>/g, "" );
102             var y = x.trim();
103             var z = y.replace(re, "").toLowerCase();
104             return z;
105         },
106
107         "anti-the-asc": function ( a, b ) {
108             return ((a < b) ? -1 : ((a > b) ? 1 : 0));
109         },
110
111         "anti-the-desc": function ( a, b ) {
112             return ((a < b) ? 1 : ((a > b) ? -1 : 0));
113         }
114     });
115
116 }());
117
118 (function($) {
119
120     $.fn.api = function(options, columns_settings, add_filters) {
121         var settings = null;
122         if(options) {
123             if(!options.criteria || ['contains', 'starts_with', 'ends_with', 'exact'].indexOf(options.criteria.toLowerCase()) === -1) options.criteria = 'contains';
124             options.criteria = options.criteria.toLowerCase();
125             settings = $.extend(true, {}, dataTablesDefaults, {
126                         'deferRender': true,
127                         "paging": true,
128                         'serverSide': true,
129                         'searching': true,
130                         'processing': true,
131                         'language': {
132                             'emptyTable': (options.emptyTable) ? options.emptyTable : "No data available in table"
133                         },
134                         'pagingType': 'full',
135                         'ajax': {
136                             'type': 'GET',
137                             'cache': true,
138                             'dataSrc': 'data',
139                             'beforeSend': function(xhr, settings) {
140                                 this._xhr = xhr;
141                                 if(options.embed) {
142                                     xhr.setRequestHeader('x-koha-embed', Array.isArray(options.embed)?options.embed.join(','):options.embed);
143                                 }
144                                 if(options.header_filter && options.query_parameters) {
145                                     xhr.setRequestHeader('x-koha-query', options.query_parameters);
146                                     delete options.query_parameters;
147                                 }
148                             },
149                             'dataFilter': function(data, type) {
150                                 var json = {data: JSON.parse(data)};
151                                 if(total = this._xhr.getResponseHeader('x-total-count')) {
152                                     json.recordsTotal = total;
153                                     json.recordsFiltered = total;
154                                 }
155                                 if(total = this._xhr.getResponseHeader('x-base-total-count')) {
156                                     json.recordsTotal = total;
157                                 }
158                                 return JSON.stringify(json);
159                             },
160                             'data': function( data, settings ) {
161                                 var length = data.length;
162                                 var start  = data.start;
163
164                                 var dataSet = {
165                                     _page: Math.floor(start/length) + 1,
166                                     _per_page: length
167                                 };
168
169                                 var filter = data.search.value;
170                                 var query_parameters = settings.aoColumns
171                                 .filter(function(col) {
172                                     return col.bSearchable && typeof col.data == 'string' && (data.columns[col.idx].search.value != '' || filter != '')
173                                 })
174                                 .map(function(col) {
175                                     var part = {};
176                                     var value = data.columns[col.idx].search.value != '' ? data.columns[col.idx].search.value : filter;
177                                     part[!col.data.includes('.')?'me.'+col.data:col.data] = options.criteria === 'exact'?value:{like: (['contains', 'ends_with'].indexOf(options.criteria) !== -1?'%':'')+value+(['contains', 'starts_with'].indexOf(options.criteria) !== -1?'%':'')};
178                                     return part;
179                                 });
180
181                                 if(query_parameters.length) {
182                                     query_parameters = JSON.stringify(query_parameters.length === 1?query_parameters[0]:query_parameters);
183                                     if(options.header_filter) {
184                                         options.query_parameters = query_parameters;
185                                     } else {
186                                         dataSet.q = query_parameters;
187                                         delete options.query_parameters;
188                                     }
189                                 } else {
190                                     delete options.query_parameters;
191                                 }
192
193                                 dataSet._match = options.criteria;
194
195                                 if(options.columns) {
196                                     var order = data.order;
197                                     order.forEach(function (e,i) {
198                                         var order_col      = e.column;
199                                         var order_by       = options.columns[order_col].data;
200                                         var order_dir      = e.dir == 'asc' ? '+' : '-';
201                                         dataSet._order_by = order_dir + (!order_by.includes('.')?'me.'+order_by:order_by);
202                                     });
203                                 }
204
205                                 return dataSet;
206                             }
207                         }
208                     }, options);
209         }
210
211         var counter = 0;
212         var hidden_ids = [];
213         var included_ids = [];
214
215         $(columns_settings).each( function() {
216             var named_id = $( 'thead th[data-colname="' + this.columnname + '"]', this ).index( 'th' );
217             var used_id = settings.bKohaColumnsUseNames ? named_id : counter;
218             if ( used_id == -1 ) return;
219
220             if ( this['is_hidden'] == "1" ) {
221                 hidden_ids.push( used_id );
222             }
223             if ( this['cannot_be_toggled'] == "0" ) {
224                 included_ids.push( used_id );
225             }
226             counter++;
227         });
228
229         var exportColumns = ":visible:not(.noExport)";
230         if( settings.hasOwnProperty("exportColumns") ){
231             // A custom buttons configuration has been passed from the page
232             exportColumns = settings["exportColumns"];
233         }
234
235         var export_format = {
236             body: function ( data, row, column, node ) {
237                 var newnode = $(node);
238
239                 if ( newnode.find(".noExport").length > 0 ) {
240                     newnode = newnode.clone();
241                     newnode.find(".noExport").remove();
242                 }
243
244                 return newnode.text().replace( /\n/g, ' ' ).trim();
245             }
246         };
247
248         var export_buttons = [
249             {
250                 extend: 'excelHtml5',
251                 text: __("Excel"),
252                 exportOptions: {
253                     columns: exportColumns,
254                     format:  export_format
255                 },
256             },
257             {
258                 extend: 'csvHtml5',
259                 text: __("CSV"),
260                 exportOptions: {
261                     columns: exportColumns,
262                     format:  export_format
263                 },
264             },
265             {
266                 extend: 'copyHtml5',
267                 text: __("Copy"),
268                 exportOptions: {
269                     columns: exportColumns,
270                     format:  export_format
271                 },
272             },
273             {
274                 extend: 'print',
275                 text: __("Print"),
276                 exportOptions: {
277                     columns: exportColumns,
278                     format:  export_format
279                 },
280             }
281         ];
282
283         settings[ "buttons" ] = [
284             {
285                 fade: 100,
286                 className: "dt_button_clear_filter",
287                 titleAttr: __("Clear filter"),
288                 enabled: false,
289                 text: '<i class="fa fa-lg fa-remove"></i> <span class="dt-button-text">' + __("Clear filter") + '</span>',
290                 action: function ( e, dt, node ) {
291                     dt.search( "" ).draw("page");
292                     node.addClass("disabled");
293                 }
294             }
295         ];
296
297         if( included_ids.length > 0 ){
298             settings[ "buttons" ].push(
299                 {
300                     extend: 'colvis',
301                     fade: 100,
302                     columns: included_ids,
303                     className: "columns_controls",
304                     titleAttr: __("Columns settings"),
305                     text: '<i class="fa fa-lg fa-gear"></i> <span class="dt-button-text">' + __("Columns") + '</span>',
306                     exportOptions: {
307                         columns: exportColumns
308                     }
309                 }
310             );
311         }
312
313         settings[ "buttons" ].push(
314             {
315                 extend: 'collection',
316                 autoClose: true,
317                 fade: 100,
318                 className: "export_controls",
319                 titleAttr: __("Export or print"),
320                 text: '<i class="fa fa-lg fa-download"></i> <span class="dt-button-text">' + __("Export") + '</span>',
321                 buttons: export_buttons
322             }
323         );
324
325         $(".dt_button_clear_filter, .columns_controls, .export_controls").tooltip();
326
327         return $(this).dataTable(settings);
328     };
329
330 })(jQuery);