Bug 27944: Add "requested" stage in article request process
[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 /* Plugin to allow sorting on numeric data stored in a span's title attribute
74  *
75  * Ex: <td><span title="[% decimal_number_that_JS_parseFloat_accepts %]">
76  *              [% formatted currency %]
77  *     </span></td>
78  *
79  * In DataTables config:
80  *     "aoColumns": [
81  *        { "sType": "title-numeric" },
82  *      ]
83  * http://datatables.net/plug-ins/sorting#hidden_title
84  */
85 jQuery.extend( jQuery.fn.dataTableExt.oSort, {
86     "title-numeric-pre": function ( a ) {
87         var x = a.match(/title="*(-?[0-9\.]+)/)[1];
88         return parseFloat( x );
89     },
90
91     "title-numeric-asc": function ( a, b ) {
92         return ((a < b) ? -1 : ((a > b) ? 1 : 0));
93     },
94
95     "title-numeric-desc": function ( a, b ) {
96         return ((a < b) ? 1 : ((a > b) ? -1 : 0));
97     }
98 } );
99
100 (function() {
101
102     /* Plugin to allow text sorting to ignore articles
103      *
104      * In DataTables config:
105      *     "aoColumns": [
106      *        { "sType": "anti-the" },
107      *      ]
108      * Based on the plugin found here:
109      * http://datatables.net/plug-ins/sorting#anti_the
110      * Modified to exclude HTML tags from sorting
111      * Extended to accept a string of space-separated articles
112      * from a configuration file (in English, "a," "an," and "the")
113      */
114
115     var config_exclude_articles_from_sort = window.CONFIG_EXCLUDE_ARTICLES_FROM_SORT || "a an the";
116     if (config_exclude_articles_from_sort){
117         var articles = config_exclude_articles_from_sort.split(" ");
118         var rpattern = "";
119         for( var i=0; i<articles.length; i++){
120             rpattern += "^" + articles[i] + " ";
121             if(i < articles.length - 1){ rpattern += "|"; }
122         }
123         var re = new RegExp(rpattern, "i");
124     }
125
126     jQuery.extend( jQuery.fn.dataTableExt.oSort, {
127         "anti-the-pre": function ( a ) {
128             var x = String(a).replace( /<[\s\S]*?>/g, "" );
129             var y = x.trim();
130             var z = y.replace(re, "").toLowerCase();
131             return z;
132         },
133
134         "anti-the-asc": function ( a, b ) {
135             return ((a < b) ? -1 : ((a > b) ? 1 : 0));
136         },
137
138         "anti-the-desc": function ( a, b ) {
139             return ((a < b) ? 1 : ((a > b) ? -1 : 0));
140         }
141     });
142
143 }());
144
145 (function($) {
146
147     $.fn.api = function(options, columns_settings, add_filters) {
148         var settings = null;
149         if(options) {
150             if(!options.criteria || ['contains', 'starts_with', 'ends_with', 'exact'].indexOf(options.criteria.toLowerCase()) === -1) options.criteria = 'contains';
151             options.criteria = options.criteria.toLowerCase();
152             settings = $.extend(true, {}, dataTablesDefaults, {
153                         'deferRender': true,
154                         "paging": true,
155                         'serverSide': true,
156                         'searching': true,
157                         'processing': true,
158                         'language': {
159                             'emptyTable': (options.emptyTable) ? options.emptyTable : "No data available in table"
160                         },
161                         'pagingType': 'full',
162                         'ajax': {
163                             'type': 'GET',
164                             'cache': true,
165                             'dataSrc': 'data',
166                             'beforeSend': function(xhr, settings) {
167                                 this._xhr = xhr;
168                                 if(options.embed) {
169                                     xhr.setRequestHeader('x-koha-embed', Array.isArray(options.embed)?options.embed.join(','):options.embed);
170                                 }
171                                 if(options.header_filter && options.query_parameters) {
172                                     xhr.setRequestHeader('x-koha-query', options.query_parameters);
173                                     delete options.query_parameters;
174                                 }
175                             },
176                             'dataFilter': function(data, type) {
177                                 var json = {data: JSON.parse(data)};
178                                 if(total = this._xhr.getResponseHeader('x-total-count')) {
179                                     json.recordsTotal = total;
180                                     json.recordsFiltered = total;
181                                 }
182                                 if(total = this._xhr.getResponseHeader('x-base-total-count')) {
183                                     json.recordsTotal = total;
184                                 }
185                                 return JSON.stringify(json);
186                             },
187                             'data': function( data, settings ) {
188                                 var length = data.length;
189                                 var start  = data.start;
190
191                                 var dataSet = {
192                                     _page: Math.floor(start/length) + 1,
193                                     _per_page: length
194                                 };
195
196                                 var filter = data.search.value;
197                                 var query_parameters = settings.aoColumns
198                                 .filter(function(col) {
199                                     return col.bSearchable && typeof col.data == 'string' && (data.columns[col.idx].search.value != '' || filter != '')
200                                 })
201                                 .map(function(col) {
202                                     var part = {};
203                                     var value = data.columns[col.idx].search.value != '' ? data.columns[col.idx].search.value : filter;
204                                     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?'%':'')};
205                                     return part;
206                                 });
207
208                                 if(query_parameters.length) {
209                                     query_parameters = JSON.stringify(query_parameters.length === 1?query_parameters[0]:query_parameters);
210                                     if(options.header_filter) {
211                                         options.query_parameters = query_parameters;
212                                     } else {
213                                         dataSet.q = query_parameters;
214                                         delete options.query_parameters;
215                                     }
216                                 } else {
217                                     delete options.query_parameters;
218                                 }
219
220                                 dataSet._match = options.criteria;
221
222                                 if(options.columns) {
223                                     var order = data.order;
224                                     order.forEach(function (e,i) {
225                                         var order_col      = e.column;
226                                         var order_by       = options.columns[order_col].data;
227                                         var order_dir      = e.dir == 'asc' ? '+' : '-';
228                                         dataSet._order_by = order_dir + (!order_by.includes('.')?'me.'+order_by:order_by);
229                                     });
230                                 }
231
232                                 return dataSet;
233                             }
234                         }
235                     }, options);
236         }
237
238         var counter = 0;
239         var hidden_ids = [];
240         var included_ids = [];
241
242         $(columns_settings).each( function() {
243             var named_id = $( 'thead th[data-colname="' + this.columnname + '"]', this ).index( 'th' );
244             var used_id = settings.bKohaColumnsUseNames ? named_id : counter;
245             if ( used_id == -1 ) return;
246
247             if ( this['is_hidden'] == "1" ) {
248                 hidden_ids.push( used_id );
249             }
250             if ( this['cannot_be_toggled'] == "0" ) {
251                 included_ids.push( used_id );
252             }
253             counter++;
254         });
255
256         var exportColumns = ":visible:not(.noExport)";
257         if( settings.hasOwnProperty("exportColumns") ){
258             // A custom buttons configuration has been passed from the page
259             exportColumns = settings["exportColumns"];
260         }
261
262         var export_format = {
263             body: function ( data, row, column, node ) {
264                 var newnode = $(node);
265
266                 if ( newnode.find(".noExport").length > 0 ) {
267                     newnode = newnode.clone();
268                     newnode.find(".noExport").remove();
269                 }
270
271                 return newnode.text().replace( /\n/g, ' ' ).trim();
272             }
273         };
274
275         var export_buttons = [
276             {
277                 extend: 'excelHtml5',
278                 text: __("Excel"),
279                 exportOptions: {
280                     columns: exportColumns,
281                     format:  export_format
282                 },
283             },
284             {
285                 extend: 'csvHtml5',
286                 text: __("CSV"),
287                 exportOptions: {
288                     columns: exportColumns,
289                     format:  export_format
290                 },
291             },
292             {
293                 extend: 'copyHtml5',
294                 text: __("Copy"),
295                 exportOptions: {
296                     columns: exportColumns,
297                     format:  export_format
298                 },
299             },
300             {
301                 extend: 'print',
302                 text: __("Print"),
303                 exportOptions: {
304                     columns: exportColumns,
305                     format:  export_format
306                 },
307             }
308         ];
309
310         settings[ "buttons" ] = [
311             {
312                 fade: 100,
313                 className: "dt_button_clear_filter",
314                 titleAttr: __("Clear filter"),
315                 enabled: false,
316                 text: '<i class="fa fa-lg fa-remove"></i> <span class="dt-button-text">' + __("Clear filter") + '</span>',
317                 action: function ( e, dt, node ) {
318                     dt.search( "" ).draw("page");
319                     node.addClass("disabled");
320                 }
321             }
322         ];
323
324         if( included_ids.length > 0 ){
325             settings[ "buttons" ].push(
326                 {
327                     extend: 'colvis',
328                     fade: 100,
329                     columns: included_ids,
330                     className: "columns_controls",
331                     titleAttr: __("Columns settings"),
332                     text: '<i class="fa fa-lg fa-gear"></i> <span class="dt-button-text">' + __("Columns") + '</span>',
333                     exportOptions: {
334                         columns: exportColumns
335                     }
336                 }
337             );
338         }
339
340         settings[ "buttons" ].push(
341             {
342                 extend: 'collection',
343                 autoClose: true,
344                 fade: 100,
345                 className: "export_controls",
346                 titleAttr: __("Export or print"),
347                 text: '<i class="fa fa-lg fa-download"></i> <span class="dt-button-text">' + __("Export") + '</span>',
348                 buttons: export_buttons
349             }
350         );
351
352         $(".dt_button_clear_filter, .columns_controls, .export_controls").tooltip();
353
354         return $(this).dataTable(settings);
355     };
356
357 })(jQuery);