This repository was archived by the owner on Feb 5, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 233
Expand file tree
/
Copy pathpatternfly.dataTables.pfFilter.js
More file actions
483 lines (450 loc) · 15.6 KB
/
patternfly.dataTables.pfFilter.js
File metadata and controls
483 lines (450 loc) · 15.6 KB
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
/**
* @summary pfFilter for DataTables
* @description A collection of API methods providing simple filter functionality for DataTables. This ensures
* DataTables meets the Patternfly design pattern with a toolbar.
*
* To apply a filter, the user must press enter in the given filter input. The user may apply a filter to a different
* column via the given filter drop down. After a filter has been applied, the filter results text, active filter
* controls, and a clear all control are shown.
*
* The toolbar and empty state layouts are expected to contain the classes as shown in the example below.
*
* Example:
*
* <!-- NOTE: Some configuration may be omitted for clarity -->
* <div class="row toolbar-pf table-view-pf-toolbar" id="toolbar1">
* <div class="col-sm-12">
* <form class="toolbar-pf-actions">
* <div class="form-group toolbar-pf-filter">
* <label class="sr-only" for="filter">Rendering Engine</label>
* <div class="input-group">
* <div class="input-group-btn">
* <button type="button" class="btn btn-default dropdown-toggle" id="filter" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Rendering Engine <span class="caret"></span></button>
* <ul class="dropdown-menu">
* <li><a href="#" id="filter1">Rendering Engine</a></li>
* <li><a href="#" id="filter2">Browser</a></li>
* </ul>
* </div>
* <input type="text" class="form-control" placeholder="Filter By Rendering Engine..." autocomplete="off" id="filterInput">
* </div>
* </div>
* ...
* </form>
* <div class="row toolbar-pf-results">
* <div class="col-sm-9">
* <div class="hidden">
* <h5>0 Results</h5>
* <p>Active filters:</p>
* <ul class="list-inline"></ul>
* <p><a href="#">Clear All Filters</a></p>
* </div>
* </div>
* <div class="col-sm-3 table-view-pf-select-results">
* <strong>0</strong> of <strong>0</strong> selected
* </div>
* </div>
* </div>
* </div>
* <table class="table table-striped table-bordered table-hover" id="table1">
* <thead>
* <tr>
* <th><input type="checkbox" name="selectAll"></th>
* <th>Rendering Engine</th>
* <th>Browser</th>
* </tr>
* </thead>
* </table>
* ...
* <script>
* // NOTE: Some properties may be omitted for clarity
* $(document).ready(function() {
* var dt = $("#table1").DataTable({
* columns: [
* { data: null, ... },
* { data: "engine" },
* { data: "browser" }
* ],
* data: [
* { engine: "Gecko", browser: "Firefox" }
* { engine: "Trident", browser: "Mozilla" }
* ],
* dom: "t",
* pfConfig: {
* ...
* filterCaseInsensitive: true,
* filterCols: [
* null,
* {
* default: true,
* optionSelector: "#filter1",
* placeholder: "Filter By Rendering Engine..."
* }, {
* optionSelector: "#filter2",
* placeholder: "Filter By Browser..."
* }
* ],
* toolbarSelector: "#toolbar1"
* }
* });
* // Optional API to clear filters
* dt.table().pfFilter.clearFilters();
*
* // Optional API to add filter
* dt.table().pfFilter.addFilter({
* column: 2,
* name: "Browser",
* value: "Firefox"
* });
* });
* </script>
*
* Note: This functionality requires the following Javascript library files to be loaded:
*
* https://cdn.datatables.net/select/1.2.0/js/dataTables.select.min.js
*/
(function (factory) {
"use strict";
if (typeof define === "function" && define.amd) {
// AMD
define(["jquery", "datatables.net"], function ($) {
return factory($, window, document);
});
} else if (typeof exports === "object") {
// CommonJS
module.exports = function (root, $) {
if (!root) {
root = window;
}
if (!$ || !$.fn.dataTable) {
$ = require("datatables.net")(root, $).$;
}
return factory($, root, root.document);
};
} else {
// Browser
factory(jQuery, window, document);
}
}(function ($, window, document, undefined) {
"use strict";
var DataTable = $.fn.dataTable;
var ACTIVE_FILTER_CONTROLS_SELECTOR = ".list-inline"; // Active filter controls
var CLEAR_FILTERS_SELECTOR = ".toolbar-pf-results a"; // Clear filters control
var FILTER_SELECTOR = ".toolbar-pf-filter"; // Filter input
var FILTER_BUTTON_SELECTOR = FILTER_SELECTOR + " button"; // Filter button
var FILTER_INPUT_SELECTOR = FILTER_SELECTOR + " input"; // Filter input
var FILTER_LABEL_SELECTOR = FILTER_SELECTOR + " label"; // Filter label
var RESULTS_SELECTOR = ".toolbar-pf-results"; // Toolbar results row
var FILTER_RESULTS_SELECTOR = RESULTS_SELECTOR + " h5"; // Toolbar filter results
DataTable.pfFilter = {};
/**
* Initialize
*
* @param {DataTable.Api} dt DataTable
* @private
*/
DataTable.pfFilter.init = function (dt) {
var i;
var ctx = dt.settings()[0];
var opts = (ctx.oInit.pfConfig) ? ctx.oInit.pfConfig : {};
ctx._pfFilter = {};
ctx._pfFilter.filterButton = $(FILTER_BUTTON_SELECTOR, opts.toolbarSelector); // Filter button
ctx._pfFilter.filterCols = opts.filterCols; // Filter colums config
ctx._pfFilter.filterLabel = $(FILTER_LABEL_SELECTOR, opts.toolbarSelector); // Filter label
ctx._pfFilter.filterInput = $(FILTER_INPUT_SELECTOR, opts.toolbarSelector); // Filter input
ctx._pfFilter.filters = []; // Applied filters array
ctx._pfFilter.activeFilterControls = $(ACTIVE_FILTER_CONTROLS_SELECTOR, opts.toolbarSelector); // Active filter controls
ctx._pfFilter.activeFilters = ctx._pfFilter.activeFilterControls.closest("div"); // Active filters container
ctx._pfFilter.clearFilters = $(CLEAR_FILTERS_SELECTOR, opts.toolbarSelector); // Clear filters control
ctx._pfFilter.results = $(RESULTS_SELECTOR, opts.toolbarSelector); // Toolbar results row
ctx._pfFilter.filterCaseInsensitive = opts.filterCaseInsensitive; // Filter filter case insensitive
ctx._pfFilter.filterResults = $(FILTER_RESULTS_SELECTOR, opts.toolbarSelector); // Toolbar filter results
if (ctx._pfFilter.filterCols === undefined) {
return;
}
// Set default filter properties
for (i = 0; i < ctx._pfFilter.filterCols.length; i++) {
if (ctx._pfFilter.filterCols[i] === null) {
continue;
}
ctx._pfFilter.filterColumn = i; // Current filter column
ctx._pfFilter.filterName = $(ctx._pfFilter.filterCols[i].optionSelector).text(); // Name of current filter
if (ctx._pfFilter.filterCols[i].default === true) {
break;
}
}
// Handle click on filter menu to set current filter column and name
for (i = 0; i < ctx._pfFilter.filterCols.length; i++) {
handleFilterOption(dt, i); // Need to pass value of i as a function
}
// Handle actions when enter is pressed within filter input
handleFilterInput(dt);
// Handle actions when clear filters control is selected
handleClearFilters(dt);
// Simple filter
$.fn.dataTable.ext.search.push(function (ctx, data, dataIndex) {
var showThisRow = true;
// Must match all filters
if (ctx._pfFilter) {
$.each(ctx._pfFilter.filters, function (index, filter) {
if (ctx._pfFilter.filterCaseInsensitive !== undefined && ctx._pfFilter.filterCaseInsensitive === true) {
if (data[filter.column].toLowerCase().indexOf(filter.value.toLowerCase()) === -1) {
showThisRow = false;
}
} else {
if (data[filter.column].indexOf(filter.value) === -1) {
showThisRow = false;
}
}
});
}
return showThisRow;
});
$.event.trigger({
type: "init.pf",
message: "pfFilter has been initialized",
time: new Date()
});
};
// Local functions
/**
* update filters if server-side processing is enabled
* see more https://www.datatables.net/release-datatables/examples/data_sources/server_side.html
*
* @param {DataTable.Api} dt DataTable
* @private
*/
function updateRemoteFilters (dt) {
var ctx = dt.settings()[0];
var filters = [];
$.each(ctx._pfFilter.filters, function (index, filter) {
if (filters[filter.column] === undefined) {
filters[filter.column] = [];
}
filters[filter.column].push(filter.value);
});
dt.search('').columns().search(''); // clear before update
$.each(filters, function (column, values) {
if (values === undefined) {
return;
}
dt.column(column).search(values.join('|'), true, false, ctx._pfFilter.filterCaseInsensitive);
});
}
/**
* Add active filter control
*
* @param {DataTable.Api} dt DataTable
* @param {object} filter Properties associated with a new filter
* @param {string} filter.column - Column associated with DataTable
* @param {string} filter.name - Name of the filter
* @param {string} filter.value - Value of the filter
* @private
*/
function addActiveFilterControl (dt, filter) {
var ctx = dt.settings()[0];
var i;
// Append active filter control
ctx._pfFilter.activeFilterControls.append('<li><span class="label label-primary">' + filter.name + ': ' +
filter.value + '<a href="#"><span class="pficon pficon-close"/></a></span></li>');
// Handle click to clear active filter
$("a", ctx._pfFilter.activeFilterControls).last().on("click", function (e) {
// Find existing filter and remove
for (i = 0; i < ctx._pfFilter.filters.length; i++) {
if (ctx._pfFilter.filters[i].column === filter.column && ctx._pfFilter.filters[i].value === filter.value) {
ctx._pfFilter.filters.splice(i, 1);
$(this).parents("li").remove();
break;
}
}
if (ctx._pfFilter.filters.length === 0) {
ctx._pfFilter.activeFilters.addClass("hidden"); // Hide
}
if (ctx.oInit.serverSide) {
updateRemoteFilters(dt);
}
dt.draw();
updateFilterResults(dt);
});
// Show active filters
ctx._pfFilter.activeFilters.removeClass("hidden");
}
/**
* Add filter
*
* @param {DataTable.Api} dt DataTable
* @param {object} filter Properties associated with a new filter
* @param {string} filter.column - Column associated with DataTable
* @param {string} filter.name - Name of the filter
* @param {string} filter.value - Value of the filter
* @private
*/
function addFilter (dt, filter) {
var ctx = dt.settings()[0];
var found = false;
// Find existing entry
$.grep(ctx._pfFilter.filters, function (f) {
if (f.column === filter.column && f.value === filter.value) {
found = true;
}
});
// Add new filter
if (!found) {
ctx._pfFilter.filters.push(filter);
if (ctx.oInit.serverSide) {
updateRemoteFilters(dt);
}
dt.draw();
addActiveFilterControl(dt, filter);
updateFilterResults(dt);
}
ctx._pfFilter.filterInput.val(""); // Clear input
}
/**
* Clear filters
*
* @param {DataTable.Api} dt DataTable
* @private
*/
function clearFilters (dt) {
var ctx = dt.settings()[0];
ctx._pfFilter.filters.length = 0; // Reset filters
ctx._pfFilter.activeFilterControls.html(""); // Remove active filter controls
ctx._pfFilter.activeFilters.addClass("hidden"); // Hide active filters area
if (ctx.oInit.serverSide) {
updateRemoteFilters(dt);
}
dt.draw();
}
/**
* Handle actions when clear filters control is selected
*
* @param {DataTable.Api} dt DataTable
* @private
*/
function handleClearFilters (dt) {
var ctx = dt.settings()[0];
if (ctx._pfFilter.clearFilters === undefined || ctx._pfFilter.clearFilters.length === 0) {
return;
}
ctx._pfFilter.clearFilters.on("click", function (e) {
clearFilters(dt);
});
}
/**
* Handle actions when enter is pressed within filter input
*
* @param {DataTable.Api} dt DataTable
* @private
*/
function handleFilterInput (dt) {
var ctx = dt.settings()[0];
if (ctx._pfFilter.filterInput === undefined || ctx._pfFilter.filterInput.length === 0) {
return;
}
ctx._pfFilter.filterInput.on("keypress", function (e) {
var keycode = (e.keyCode ? e.keyCode : e.which);
if (keycode === 13) {
e.preventDefault();
if (this.value.trim().length > 0) {
addFilter(dt, {
column: ctx._pfFilter.filterColumn,
name: ctx._pfFilter.filterName,
value: this.value
});
}
return false;
}
return true;
});
}
/**
* Handle actions when filter options are selected
*
* @param {DataTable.Api} dt DataTable
* @param {number} i The column associated with this handler
* @private
*/
function handleFilterOption (dt, i) {
var ctx = dt.settings()[0];
if (ctx._pfFilter.filterCols[i] === null || ctx._pfFilter.filterCols[i].optionSelector === undefined) {
return;
}
$(ctx._pfFilter.filterCols[i].optionSelector).on("click", function (e) {
// Set input placeholder
if (ctx._pfFilter.filterInput !== undefined && ctx._pfFilter.filterInput.length !== 0) {
ctx._pfFilter.filterInput.get(0).placeholder = ctx._pfFilter.filterCols[i].placeholder;
}
// Set filter label
if (ctx._pfFilter.filterLabel !== undefined && ctx._pfFilter.filterLabel.length !== 0) {
ctx._pfFilter.filterLabel.html($(this).text());
}
// Set filter button
if (ctx._pfFilter.filterButton !== undefined && ctx._pfFilter.filterButton.length !== 0) {
ctx._pfFilter.filterButton.html($(this).text() + ' <span class="caret"></span>');
}
ctx._pfFilter.filterColumn = i; // Save filter column when applying filter
ctx._pfFilter.filterName = $(this).text(); // Save filter name for active filter control
});
}
/**
* Update active filter results
*
* @param {DataTable.Api} dt DataTable
* @private
*/
function updateFilterResults (dt) {
var ctx = dt.settings()[0];
var filteredRows;
if (ctx.oInit.serverSide) {
dt.on('draw', function () {
filteredRows = dt.ajax.json().recordsFiltered;
ctx._pfFilter.filterResults.html(filteredRows + " Results");
});
} else {
filteredRows = dt.rows({ "page": "current", "search": "applied" }).flatten().length;
}
if (ctx._pfFilter.filterResults === undefined || ctx._pfFilter.filterResults.length === 0) {
return;
}
ctx._pfFilter.filterResults.html(filteredRows + " Results");
}
// DataTables API
/**
* Add filter
*
* Example: dt.table().pfFilter.addFilter({
* column: 2,
* name: "Browser",
* value: "Firefox"
* });
*
* @param {object} filter Properties associated with a new filter
* @param {string} filter.column - Column associated with DataTable
* @param {string} filter.name - Name of the filter
* @param {string} filter.value - Value of the filter
*/
DataTable.Api.register("pfFilter.addFilter()", function (filter) {
return this.iterator("table", function (ctx) {
addFilter(new DataTable.Api(ctx), filter);
});
});
/**
* Clear filters
*
* Example: dt.table().pfFilter.clearFilters();
*
*/
DataTable.Api.register("pfFilter.clearFilters()", function () {
return this.iterator("table", function (ctx) {
clearFilters(new DataTable.Api(ctx));
});
});
// DataTables creation
$(document).on("init.dt", function (e, ctx, json) {
if (e.namespace !== "dt") {
return;
}
DataTable.pfFilter.init(new DataTable.Api(ctx));
});
return DataTable.pfFilter;
}));