-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdataTable.js
More file actions
455 lines (435 loc) · 17.3 KB
/
Copy pathdataTable.js
File metadata and controls
455 lines (435 loc) · 17.3 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
// REQUIERE UTILITARIOS.JS
var dataTable = function(divContainer, src, configParam={}, styles={}, events={}, rowEvents={}){
// Atributos
this.$element = $("#" + divContainer)
this.source = src
this.filteringFields = {}
this.sortingFields = {}
this.tableFiltered = []
this.tableContent
this.page
this.pageCount
this.columns
this.URLsort
this.URLfilter
this.config = {}
// Metodos
// Funcion para dibujar el contenido de la tabla (el tbody)
this.drawContent = function(){
// Busco el body de la tabla
var $tbody = $("#divTable tbody", this.$element)
// Limpio la tabla
$tbody.html("")
var content = this.tableFiltered
// Calculamos la cantidad de paginas
// Si tengo paginacion y el src no es webservice
if(this.page && !RegExp(/https?:\/{2}/).test(src)){
// Calculamos la pagina
this.pageCount = Math.ceil(content.length / this.config.pageSize)
var start = (this.page - 1) * this.config.pageSize
var end = start + this.config.pageSize
content = this.tableFiltered.slice(start, end)
}
var idRef = 0
content.forEach(function(row){
var $row = $("<tr>")
.addClass("tr_" + idRef++)
if (idRef % 2 == 0) {
$row.addClass("ui-state-default")
// $row.addClass("ui-state-default")
}
this.columns.forEach(function(key){
var $td = $("<td>") //.addClass("odd")
$row.append(
$td.html(row[key]).attr("id", key)
)
}.bind(this))
// Columna de iconos
var $tools = $("<th>").css("display", "flex")
if (this.config.editable){
// Icono para editar
$tools.append(
$("<img>")
.attr("src", "images/icons8-editar-48.png")
.attr("id", "imgEditar")
.css("height", "30px")
.on("click", function(){$(this).parent().parent().trigger("edit")})
)
// Icono para guardar
.append(
$("<img>")
.attr("src", "images/icons8-guardar-26.png")
.attr("id", "imgGuardar")
.css("height", "30px")
.css("display", "none")
.on("click", function(){$(this).parent().parent().trigger("update")})
)
$row.on("edit", function(){
var td = $(this).attr("class")
$("." + td + " #imgEditar").hide()
$("." + td + " #imgGuardar").show()
})
$row.on("update", function(){
var td = $(this).attr("class")
$("." + td + " #imgEditar").show()
$("." + td + " #imgGuardar").hide()
})
}
if (this.config.deletable){
// Icono para eliminar
$tools.append(
$("<img>")
.attr("src", "images/icons8-eliminar-100.png")
.css("height", "30px")
.on("click", function(){$(this).parent().parent().trigger("delete")})
)
$row.on("delete", function(){
var td = $(this).attr("class")
$("." + td).remove()
})
}
if (this.config.deletable || this.config.editable){
$row.append($tools)
}
// Agregar la fila al body de la tabla
addEventHandlers($row, {}, rowEvents)
$tbody.append($row)
}.bind(this))
// Paginacion
if (this.page){
$("#pagination").remove()
var $pageButton = $("<div>").attr("id","pagination")
.css("display", "flex")
.css("justify-content", "space-between")
.css("align-items", "center")
.css("padding", "5px")
.addClass("ui-widget-header ui-corner-br")
$pageButton.append(
$("<div>").append(
// Boton Pagina Atras
$("<img>").attr("src", "./images/icons8-arrow-first.png")
.on("click", function(){
this.page = 1
if(RegExp(/https?:\/{2}/).test(src)){
this.getContentFromURL(this.source, this.page, this.URLsort, this.URLfilter)
}
this.drawContent()
}.bind(this))
).append(
// Boton Primera Pagina
$("<img>").attr("src", "./images/icons8-arrow-previous.png")
.on("click", function(){
if (this.page > 1){
this.page--
if(RegExp(/https?:\/{2}/).test(src)){
this.getContentFromURL(this.source, this.page, this.URLsort, this.URLfilter)
}
this.drawContent()
} else {
alert("No se puede retroceder mas.")
}
}.bind(this))
)
)
// Pagina Actual
$pageButton.append(
$("<p>").attr("id", "actualPage").html("Pagina actual: " + this.page + " de " + this.pageCount)
.css("margin", 0)
)
// Ir a pagina especifica
$pageButton.append(
$("<div>")
.css("display", "flex")
.append(
// $("<button>").addClass("ui-button ui-corner-all ui-widget").html("Ir a pagina: ")
$("<button>").addClass("btn ui-widget-content").html("Ir a pagina: ")
.css("marginRight", "5px")
.on("click", function(){
var value = $("#page", $pageButton).val()
if (value > 0 && value <= this.pageCount){
this.page = $("#page", $pageButton).val()
if(RegExp(/https?:\/{2}/).test(src)){
this.getContentFromURL(this.source, this.page, this.URLsort, this.URLfilter)
}
this.drawContent()
} else {
alert("Valor " + value + " fuera de rango.")
}
}.bind(this))
)
.append(
$("<input>")
.attr("id", "page")
.attr("type", "number")
.attr("min", 1)
.attr("max", this.pageCount)
.attr("value", this.page)
)
)
$pageButton.append(
$("<div>").append(
// Boton Pagina Adelante
$("<img>").attr("src", "./images/icons8-arrow-next.png")
.on("click", function(){
if (this.page < this.pageCount){
this.page++
if(RegExp(/https?:\/{2}/).test(src)){
this.getContentFromURL(this.source, this.page, this.URLsort, this.URLfilter)
}
this.drawContent()
} else {
alert("No se puede avanzar mas")
}
}.bind(this))
).append(
// Boton Ultima Pagina
$("<img>").attr("src", "./images/icons8-arrow-last.png")
.on("click", function(){
this.page = this.pageCount
if(RegExp(/https?:\/{2}/).test(src)){
this.getContentFromURL(this.source, this.page, this.URLsort, this.URLfilter)
}
this.drawContent()
}.bind(this))
)
)
$pageButton.appendTo(this.$element)
addInputStyles(this.$element[0].id)
}
}
// Funcion para obtener el contenido de la tabla de una URL
this.getContentFromURL = function(url, page=false, sort=false, filter=false){
var data = {pageSize: this.config.pageSize}
if(page){
data["page"] = page
}
if(sort){
Object.assign(data, data, sort)
}
if(filter){
Object.assign(data, data, filter)
}
//
var result
// Overlay mientras se carga la pagina NO FUNCIONA AHORITA
$("body").append(
$("<div>")
.css("position", "absolute")
.css("right" , 0)
.css("left" , 0)
.css("bottom" , 0)
.css("top" , 0)
.css("background", "rgba(0,0,0,0.3)")
.attr("id", "overlay")
)
$.ajax({
url: url,
data: data,
success: function(response){
this.tableFiltered = response["data"]
this.pageCount = response["pageCount"]
$("body #overlay").remove()
result = response["data"]
}.bind(this),
async: false,
error: function(){
alert("No se pudo cargar el contenido.")
}
})
return result
}
//////////////////// CONSTRUCTOR
constructor = function(){
this.$element.append(
$("<div>").attr("id", "divTable")
.css("marginBottom", "5px")
)
var defaultConfig = {
page: false,
pageSize: 20,
deletable: false,
editable: false,
sortable: false, // false | "all" | [...sortable fields]
filterable: false // false | "all" | [...filterable fields]
}
Object.assign(this.config, defaultConfig, configParam)
this.page = this.config.page
// Chequeamos si la entrada es un url
if(RegExp(/https?:\/{2}/).test(src)){
this.tableContent = this.getContentFromURL(src, this.page)
} else {
this.tableContent = src
this.tableFiltered = src
this.pageCount = Math.ceil(src.length / this.config.pageSize)
}
if (this.tableContent.length > 0){
// Creamos la Tabla
var $table = $("<table>")
.css("backgroundColor", "white")
.addClass("table table-bordered table-hover dataTable display") //table-striped
$("#divTable", this.$element).append($table)
// Agregamos estilos
var defaultStyles = {
width: "100%"
}
addStyles(this.$element, defaultStyles, styles)
// Sacamos las columnas de la tabla
this.columns = Object.keys(this.tableContent[0])
// Table Header
var $tableHead = $("<thead>")
var $headRow = $("<tr>")
// Generar el Header de la tabla
this.columns.forEach(function(key){
var $filterInput = $("<input>")
var $th = $("<th>").addClass("ui-widget-header")
.addClass("ui-widget-header")
var $headTitle = $("<div>").html(key)
// Ordenamiento
if (this.config.sortable && (this.config.sortable === "all" || this.config.sortable.includes(key))){
$headTitle.css("display", "flex")
$headTitle.css("justifyContent", "space-around")
$headTitle.append(
$("<div>")
.append(
// Icono para ordenar ascendente
$("<span>").addClass("ui-icon ui-icon-caret-1-n")
.on("click", function(){
this.sortContent(key, "ASC")
}.bind(this))
)
.append(
// Icono para ordenar descendente
$("<span>").addClass("ui-icon ui-icon-caret-1-s")
.on("click", function(){
this.sortContent(key, "DESC")
}.bind(this))
)
)
}
$th.append($headTitle)
// Filtrado
if (this.config.filterable && (this.config.filterable === "all" || this.config.filterable.includes(key))){
$th.append(
// Input para filtrar
$filterInput.on("blur", function(){
this.filterContent(key, $filterInput.val())
}.bind(this))
)
}
$headRow.append($th)
}.bind(this))
// Columna de utilidades
if(this.config.editable || this.config.deletable) {
$headRow.append(
$("<th>").append($("<img>")
.attr("src", "images/icons8-caja-de-almacenamiento-de-herramientas-completa-50.png"))
.addClass("ui-widget-header")
)
}
$tableHead.append($headRow)
$table.append($tableHead)
// Table Body
$table.append($("<tbody>"))
this.drawContent()
// Fixed Header
$("#divTable", this.$element)
.css("overflow", "auto")
.css("maxHeight", "90vh")
$table.clone(true).css("marginBottom", "0").appendTo($("#divTable", this.$element))
$("table:nth-child(1)", this.$element)
.css("position", "sticky")
.css("top", "0")
.css("marginBottom", "0")
$("table:nth-child(1) tbody", this.$element)
.css("visibility", "collapse")
$("table:nth-child(2) thead", this.$element)
.css("visibility", "collapse")
// Asignamos los eventos que vienen como parametros
addEventHandlers(this.$element, undefined, events)
}
/////////////////// FIN CONSTRUCTOR
}.bind(this)() // Ejecutar el constructor
// Funcion para filtrar contenido
this.filterContent = function(field, filterValue){
// Si no tenemos paginacion | tengo paginacion pero el src es arreglo
if(!this.page || (this.page && !RegExp(/https?:\/{2}/).test(src))){
this.tableFiltered = this.tableContent
// Agregamos el campo actual al diccionario de filtros
this.filteringFields[field] = filterValue
var fields = Object.keys(this.filteringFields)
// Filtramos por cada campo
fields.forEach(function(_field){
this.tableFiltered = this.tableFiltered.filter( function(row){
if (row[_field].toString().toLowerCase().search(this.filteringFields[_field].toString().toLowerCase()) != -1) {
return true
} else {
return false
}
}.bind(this))
}.bind(this))
} else {
// Si tengo page es un webservice
this.page = 1
this.URLfilter = {filterField: field, filterValue: filterValue}
this.tableFiltered = this.getContentFromURL(this.source, this.page, this.URLsort, this.URLfilter)
}
this.drawContent()
}
// Funcion para ordenar por columna
this.sortContent = function(field, direction="ASC"){
if(!this.page || (this.page && !RegExp(/https?:\/{2}/).test(src))){
this.sortingFields = {}
this.sortingFields[field] = direction
this.tableFiltered.sort((a,b)=>{
if (this.sortingFields[field] == "ASC"){
// Orden Ascendente
if( a[field] < b[field] ){
return -1
} else {
return 1
}
} else {
// Orden Descendente
if( a[field] > b[field] ){
return -1
} else {
return 1
}
}
})
} else {
// Si tengo page es un webservice
this.page = 1
this.URLsort = {sortField: field, sortDirection: direction}
this.tableFiltered = this.getContentFromURL(this.source, this.page, this.URLsort, this.URLfilter)
}
this.drawContent()
}
}
// var testArray =
// [{"id":1,"first_name":"Winna","last_name":"Hrinchishin","email":"whrinchishin0@jigsy.com","gender":"Female","ip_address":"151.237.172.205"},
// {"id":2,"first_name":"Jasmin","last_name":"Pregel","email":"jpregel1@trellian.com","gender":"Female","ip_address":"52.45.131.80"},
// {"id":3,"first_name":"Jammal","last_name":"Goggin","email":"jgoggin2@liveinternet.ru","gender":"Male","ip_address":"238.22.97.248"},
// {"id":4,"first_name":"Erie","last_name":"Fugere","email":"efugere3@engadget.com","gender":"Male","ip_address":"114.100.170.17"},
// {"id":5,"first_name":"Hermine","last_name":"Proffer","email":"hproffer4@globo.com","gender":"Female","ip_address":"124.157.12.205"},
// {"id":6,"first_name":"Massimo","last_name":"Tremathack","email":"mtremathack5@elpais.com","gender":"Male","ip_address":"98.227.149.180"},
// {"id":7,"first_name":"Walsh","last_name":"Penman","email":"wpenman6@google.de","gender":"Male","ip_address":"116.190.210.219"},
// {"id":8,"first_name":"Ammamaria","last_name":"Shotboult","email":"ashotboult7@mashable.com","gender":"Female","ip_address":"101.114.117.164"},
// {"id":9,"first_name":"Edmon","last_name":"O'Shiels","email":"eoshiels8@nature.com","gender":"Male","ip_address":"150.126.222.244"},
// {"id":10,"first_name":"Welch","last_name":"Kienl","email":"wkienl9@acquirethisname.com","gender":"Male","ip_address":"58.16.173.74"},
// {"id":11,"first_name":"Carly","last_name":"MacCleay","email":"cmaccleaya@diigo.com","gender":"Female","ip_address":"65.112.77.94"},
// {"id":12,"first_name":"Selestina","last_name":"Joliffe","email":"sjoliffeb@xing.com","gender":"Female","ip_address":"64.166.28.87"},
// {"id":13,"first_name":"Gaylor","last_name":"Spellworth","email":"gspellworthc@prnewswire.com","gender":"Male","ip_address":"58.204.144.199"},
// {"id":14,"first_name":"Ashly","last_name":"Vashchenko","email":"avashchenkod@intel.com","gender":"Female","ip_address":"160.120.192.204"},
// {"id":15,"first_name":"Marylinda","last_name":"Rizzi","email":"mrizzie@latimes.com","gender":"Female","ip_address":"232.186.77.199"},
// {"id":16,"first_name":"Link","last_name":"Genty","email":"lgentyf@histats.com","gender":"Male","ip_address":"147.203.8.175"},
// {"id":17,"first_name":"Catarina","last_name":"Steadman","email":"csteadmang@adobe.com","gender":"Female","ip_address":"5.242.152.77"},
// {"id":18,"first_name":"Jasen","last_name":"Tash","email":"jtashh@unesco.org","gender":"Male","ip_address":"121.220.73.238"}]
// var table = new dataTable("table", testArray, {page: 1, pageSize: 7, filterable: "all", "sortable": "all"},
// var table = new dataTable("table", "http://localhost:52391/api/users/getUsers", {page: 1},
// var table = new dataTable("table", "http://localhost:3000", {page: 1},
var table = new dataTable("table", "http://localhost:3000", {page:1, pageSize: 9, editable:true, deletable:true,sortable:"all", filterable:"all"},
// var table = new dataTable("table", "http://localhost:3000", undefined,
undefined, undefined,
{"dblclick": function(){console.log(this)}, "delete": ()=>{alert("Borrando")}, "edit": ()=>{alert("Editando")} , "update": ()=>{alert("guardando")} })
// {"dblclick": ()=>{alert("doble click")}, "delete": function(){console.log(this); alert("Borrando")}})