-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatagrid.js
473 lines (424 loc) · 15.1 KB
/
datagrid.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
/**
* (c) LemonadeJS Data Grid
*
* Website: https://lemonadejs.net
* MIT License
*/
// Load LemonadeJS
if (! lemonade && typeof(require) === 'function') {
var lemonade = require('lemonadejs');
}
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
global.Datagrid = factory();
}(this, (function () {
const Pagination = function(self) {
// The current result
let result = self.data;
const find = function(o, query) {
query = query.toLowerCase();
for (let key in o) {
let value = o[key];
if ((''+value).toLowerCase().search(query) >= 0) {
return true;
}
}
return false;
}
const search = function(str) {
if (str) {
// Filter the data
let t = [];
if (Array.isArray(self.data)) {
t = self.data.filter(function(item) {
return find(item, str);
});
}
// Result
result = t;
} else {
result = self.data;
}
// Go back to page zero
self.page = 0;
}
const page = function() {
if (! self.pagination) {
self.result = result;
} else {
// Pagination
let p = parseInt(self.pagination);
let s;
let f;
let numOfItems = result.length;
// Define the range for this pagination configuration
if (p && numOfItems > p) {
s = (p * self.page);
f = (p * self.page) + p;
if (numOfItems < f) {
f = numOfItems;
}
} else {
s = 0;
f = numOfItems;
}
// Change the page
p = [];
for (let i = s; i < f; i++) {
p.push(result[i]);
}
// Set the new results for the view
self.result = p;
// Update pagination
pagination();
}
}
const pagination = function() {
let pages = [];
// Update pagination
if (self.pagination > 0) {
// Get the number of the pages based on the data
let n = Math.ceil(result.length / self.pagination);
if (n > 1) {
let s;
let f;
// Controllers
if (self.page < 6) {
s = 0;
f = n < 10 ? n : 10;
} else if (n - self.page < 5) {
s = n - 9;
f = n;
if (s < 0) {
s = 0;
}
} else {
s = parseInt(self.page) - 4;
f = parseInt(self.page) + 5;
}
// First page
if (s > 0) {
pages.push({
title: 0,
value: '«'
});
}
// Link to each page
let i;
for (i = s; i < f; i++) {
pages.push({
title: i,
value: i+1,
selected: self.page == i
});
}
// Last page
if (f < n) {
pages.push({
title: n - 1,
value: '»'
});
}
}
}
self.pages = pages;
}
self.reloadPagination = function() {
pagination();
}
self.setPage = function(page) {
if (typeof(page) === 'object') {
page = page.target.title;
}
self.page = parseInt(page);
}
// Call back
return (prop) => {
if (prop === 'data' || prop === 'input') {
// Filter the results based on the new data/input
search(self.input);
// Dispatch onsearch event
Dispatch.call(self, 'onsearch', self);
} else if (prop === 'page') {
// Change the page sending the element where the property page is associated
page();
// Dispatch onchangepage event
Dispatch.call(self, 'onchangepage', self);
}
}
}
// Dispatcher
const Dispatch = function(type, option) {
if (typeof this[type] === 'function') {
this[type](this, option);
}
}
// Set the focus
const setFocus = function(el) {
if (el.innerText && el.innerText.length) {
let range = document.createRange();
let sel = window.getSelection();
let node = el.childNodes[el.childNodes.length-1];
range.setStart(node, node.length)
range.collapse(true)
sel.removeAllRanges()
sel.addRange(range)
el.scrollLeft = el.scrollWidth;
}
}
const Datagrid = function() {
let self = this;
// Make sure this is boolean
self.search = !!self.search;
// Make sure these are arrays
if (!Array.isArray(self.data)) {
self.data = [];
}
if (!Array.isArray(self.columns)) {
self.columns = [];
}
const remote = { };
/**
* Sorting rules
*/
const sorting = function(s) {
if (s.name) {
self.data = self.data.sort((a, b) => {
const valueA = lemonade.path.call(a, s.name);
const valueB = lemonade.path.call(b, s.name);
const isANumber = !isNaN(parseFloat(valueA)) && isFinite(valueA);
const isBNumber = !isNaN(parseFloat(valueB)) && isFinite(valueB);
if (isANumber && isBNumber && s.sorted === 'desc') {
return parseFloat(valueB) - parseFloat(valueA);
} else if (isANumber && isBNumber) {
return parseFloat(valueA) - parseFloat(valueB);
} else if (isANumber) {
return -1;
} else if (isBNumber) {
return 1;
} else if (s.sorted === 'asc') {
return valueB.localeCompare(valueA);
} else {
return valueA.localeCompare(valueB);
}
});
// Force refresh
if (self.pagination > 0) {
self.setPage(self.page);
}
}
}
/**
* Callback to the pagination
*/
const pagination = Pagination(self);
const isRemote = function() {
return self.url && self.remote;
}
self.fetchRemote = function() {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
res = JSON.parse(xhr.responseText);
let result = [];
if (Array.isArray(res.result)) {
result = res.result;
} else if (Array.isArray(res)) {
result = res;
}
if (isRemote()) {
for (let i = 0; i < res.total; i++) {
self.data[i] = {}
}
self.data.length = res.total
self.result = result
self.reloadPagination();
} else {
self.data = result;
}
} else {
console.error('Failed to fetch data. Status code: ' + xhr.status);
}
}
};
let url = self.url
if (self.remote) {
url += `?pagination=${self.pagination}&page=${self.page || 0}`;
if (remote.index) {
url += `&orderBy=${remote.index}&asc=${remote.order}`;
}
if (self.input) {
url += `&term=${self.input}`;
}
}
xhr.open('GET', url, true);
xhr.setRequestHeader('Content-Type', 'text/json')
xhr.send();
}
/**
* Lemonade onchange event
*/
self.onchange = function (prop) {
if (isRemote()) {
if (prop === 'page' || prop === 'input') {
self.fetchRemote();
}
} else {
pagination(prop);
}
}
/**
* Trigger results on the correct page or all content if pagination not defined
*/
self.onload = function() {
if (self.data.length > 0) {
self.page = 0;
} else if (self.url) {
self.fetchRemote();
}
}
/**
* Sorting event on headers
* @param e mouse event
* @param s header self objecd
*/
self.sort = function(e, s) {
// Remove sorting from all other columns
let cols = s.parent.columns;
let current = null;
for (let i = 0; i < cols.length; i++) {
if (cols[i].sorted) {
current = cols[i];
break;
}
}
// Sorting
if (current && current !== s) {
current.sorted = '';
}
// Direction
s.sorted = s.sorted === 'asc' ? 'desc' : 'asc';
// Apply sorting
if (isRemote()) {
remote.index = s.name;
remote.order = s.sorted === 'asc';
self.fetchRemote();
} else {
sorting(s);
}
}
/**
* Close the edition
*/
const closeEdition = function(e, s) {
// Remove edition attribute
e.target.removeAttribute('contenteditable');
// Scroll
e.target.scrollLeft = 0;
// Row position
let row = self.data.indexOf(s);
// Attribute name
let name = e.target.getAttribute('data-name');
// New value
let value = e.target.textContent;
// Update the value
self.setValue(name, row, value);
}
/**
* Start or stop the edition event handler
* @param e js event
* @param s row lemonade self object
*/
self.edit = function(e, s) {
// Only start the edition if the data grid is editable
if (self.editable) {
// This will stop the edition
if (e.type === 'blur') {
closeEdition(e, s);
} else {
e.target.setAttribute('contenteditable', true);
e.target.focus();
// Set caret
setFocus(e.target);
}
}
}
/**
* Key down event
*/
self.keydown = function(e, s) {
if (e.key === 'Enter') {
// Close edition
let edition = e.target.getAttribute('contenteditable');
if (edition) {
e.target.blur();
}
}
}
/**
* Set the value of a cell based on the provided coordinates.
* @param {Number | String} x The column identificator, can be the number or the name of the column.
* @param {Number} y The row position.
* @param {String} value The new value that the cell will receive.
*/
self.setValue = function (x, y, value) {
if (typeof(x) === 'number' && self.columns[x].name) {
x = self.columns[x].name;
}
// Update value
self.data[y][x] = value;
// Dispatch event
Dispatch.call(self, 'onupdate', { x, y, value });
}
/**
* Render when cell is ready
*/
self.render = function(e, s) {
let x = Array.prototype.indexOf.call(e.parentNode.children, e);
let y = self.data.indexOf(s);
if (self.columns[x] && self.columns[x].render) {
self.columns[x].render(e, e.textContent, x, y, s, self);
}
}
// String for the template
let columns = '';
// Build the columns structure
self.columns.forEach((v, k) => {
columns += `<td ondblclick="self.parent.edit" onblur="self.parent.edit" align="${v.align}"`;
if (! v.width) {
v.width = 100;
}
if (v.render) {
columns += ` :ready="self.parent.render"`;
}
if (v.wrap) {
columns += ` class="lm-data-grid-wrap"`;
}
if (v.name) {
columns += ` data-name="${v.name}">{{self.${v.name}}}</td>`;
} else {
// TODO: prepare for common arrays
columns += ` data-x="${k}">{{self.${k}}}</td>`;
}
});
return `<div class="lm-data-grid" :data="self.data" onkeydown="self.keydown">
<div class="lm-data-grid-search-section" search="{{self.search}}"><div>Search</div> <div><input type='text' :bind="self.input"/></div></div>
<table class="lm-data-grid-table">
<thead><tr :loop="self.columns"><th width="{{self.width}}" align="{{self.align}}" data-sorted="{{self.sorted}}" onclick="self.parent.sort">{{self.title}}</th></tr></thead>
<tbody :loop="self.result"><tr>${columns}</tr></tbody>
</table>
<div class="lm-data-grid-pagination-section"><ul :loop="self.pages" :page="self.page"><li onclick="self.parent.setPage" title="{{self.title}}" selected="{{self.selected}}">{{self.value}}</li></ul></div>
</div>`;
};
lemonade.setComponents({ Datagrid: Datagrid });
return function (root, options) {
if (typeof root == 'object') {
lemonade.render(Datagrid, root, options);
return options;
} else {
return Datagrid.call(this, root);
}
};
})));