forked from webismymind/editablegrid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
editablegrid.js
2267 lines (1966 loc) · 76.7 KB
/
editablegrid.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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
if (typeof _$ == 'undefined') {
function _$(elementId) { return document.getElementById(elementId); }
}
/**
* Creates a new column
* @constructor
* @class Represents a column in the editable grid
* @param {Object} config
*/
function Column(config)
{
// default properties
var props = {
name: "",
label: "",
editable: true,
renderable: true,
datatype: "string",
unit: null,
precision: -1, // means that all decimals are displayed
nansymbol: '',
decimal_point: ',',
thousands_separator: '.',
unit_before_number: false,
bar: true, // is the column to be displayed in a bar chart ? relevant only for numerical columns
hidden: false, // should the column be hidden by default
headerRenderer: null,
headerEditor: null,
cellRenderer: null,
cellEditor: null,
cellValidators: [],
enumProvider: null,
optionValues: null,
optionValuesForRender: null,
columnIndex: -1
};
// override default properties with the ones given
for (var p in props) this[p] = (typeof config == 'undefined' || typeof config[p] == 'undefined') ? props[p] : config[p];
}
Column.prototype.getOptionValuesForRender = function(rowIndex) {
if (!this.enumProvider) {
console.log('getOptionValuesForRender called on column ' + this.name + ' but there is no EnumProvider');
return null;
}
var values = this.enumProvider.getOptionValuesForRender(this.editablegrid, this, rowIndex);
return values ? values : this.optionValuesForRender;
};
Column.prototype.getOptionValuesForEdit = function(rowIndex) {
if (!this.enumProvider) {
console.log('getOptionValuesForEdit called on column ' + this.name + ' but there is no EnumProvider');
return null;
}
var values = this.enumProvider.getOptionValuesForEdit(this.editablegrid, this, rowIndex);
return values ? this.editablegrid._convertOptions(values) : this.optionValues;
};
Column.prototype.isValid = function(value) {
for (var i = 0; i < this.cellValidators.length; i++) if (!this.cellValidators[i].isValid(value)) return false;
return true;
};
Column.prototype.isNumerical = function() {
return this.datatype =='double' || this.datatype =='integer';
};
/**
* Creates a new enumeration provider
* @constructor
* @class Base class for all enumeration providers
* @param {Object} config
*/
function EnumProvider(config)
{
// default properties
this.getOptionValuesForRender = function(grid, column, rowIndex) { return null; };
this.getOptionValuesForEdit = function(grid, column, rowIndex) { return null; };
// override default properties with the ones given
for (var p in config) this[p] = config[p];
}
/**
* Creates a new EditableGrid.
* <p>You can specify here some configuration options (optional).
* <br/>You can also set these same configuration options afterwards.
* <p>These options are:
* <ul>
* <li>enableSort: enable sorting when clicking on column headers (default=true)</li>
* <li>doubleclick: use double click to edit cells (default=false)</li>
* <li>editmode: can be one of
* <ul>
* <li>absolute: cell editor comes over the cell (default)</li>
* <li>static: cell editor comes inside the cell</li>
* <li>fixed: cell editor comes in an external div</li>
* </ul>
* </li>
* <li>editorzoneid: used only when editmode is set to fixed, it is the id of the div to use for cell editors</li>
* <li>allowSimultaneousEdition: tells if several cells can be edited at the same time (default=false)<br/>
* Warning: on some Linux browsers (eg. Epiphany), a blur event is sent when the user clicks on a 'select' input to expand it.
* So practically, in these browsers you should set allowSimultaneousEdition to true if you want to use columns with option values and/or enum providers.
* This also used to happen in older versions of Google Chrome Linux but it has been fixed, so upgrade if needed.</li>
* <li>saveOnBlur: should be cells saved when clicking elsewhere ? (default=true)</li>
* <li>invalidClassName: CSS class to apply to text fields when the entered value is invalid (default="invalid")</li>
* <li>ignoreLastRow: ignore last row when sorting and charting the data (typically for a 'total' row)</li>
* <li>caption: text to use as the grid's caption</li>
* <li>dateFormat: EU or US (default="EU")</li>
* <li>shortMonthNames: list of month names (default=["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"])</li>
* <li>smartColorsBar: colors used for rendering (stacked) bar charts</li>
* <li>smartColorsPie: colors used for rendering pie charts</li>
* <li>pageSize: maximum number of rows displayed (0 means we don't want any pagination, which is the default)</li>
* <li>sortIconDown: icon used to show desc order</li>
* <li>sortIconUp: icon used to show asc order</li>
* </ul>
* @constructor
* @class EditableGrid
*/
function EditableGrid(name, config) {
if (typeof name != 'undefined' && name.replace(/\s+/g,'') == "") console.error("EditableGrid() : parameter [name] cannot be empty.");
if (name) this.init(name, config);
}
/**
* Default properties
*/
EditableGrid.prototype.enableSort = true;
EditableGrid.prototype.enableStore = true;
EditableGrid.prototype.doubleclick = false;
EditableGrid.prototype.editmode = "absolute";
EditableGrid.prototype.editorzoneid = "";
EditableGrid.prototype.allowSimultaneousEdition = false;
EditableGrid.prototype.saveOnBlur = true;
EditableGrid.prototype.invalidClassName = "invalid";
EditableGrid.prototype.ignoreLastRow = false;
EditableGrid.prototype.caption = null;
EditableGrid.prototype.dateFormat = "EU";
EditableGrid.prototype.shortMonthNames = null;
EditableGrid.prototype.smartColorsBar = ["#dc243c","#4040f6","#00f629","#efe100","#f93fb1","#6f8183","#111111"];
EditableGrid.prototype.smartColorsPie = ["#FF0000","#00FF00","#0000FF","#FFD700","#FF00FF","#00FFFF","#800080"];
EditableGrid.prototype.pageSize = 0; // client-side pagination, don't set this for server-side pagination!
//server-side pagination, sorting and filtering
EditableGrid.prototype.serverSide = false;
EditableGrid.prototype.pageCount = 0;
EditableGrid.prototype.totalRowCount = 0;
EditableGrid.prototype.unfilteredRowCount = 0;
EditableGrid.prototype.paginatorAttributes = null;
EditableGrid.prototype.lastURL = null;
EditableGrid.prototype.init = function (name, config)
{
if (typeof name != "string" || (typeof config != "object" && typeof config != "undefined")) {
alert("The EditableGrid constructor takes two arguments:\n- name (string)\n- config (object)\n\nGot instead " + (typeof name) + " and " + (typeof config) + ".");
};
// override default properties with the ones given
if (typeof config != 'undefined') for (var p in config) this[p] = config[p];
this.Browser = {
IE: !!(window.attachEvent && navigator.userAgent.indexOf('Opera') === -1),
Opera: navigator.userAgent.indexOf('Opera') > -1,
WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
Gecko: navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') === -1,
MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
};
if (typeof this.detectDir != 'function') {
var error = new Error();
alert("Who is calling me now ? " + error.stack);
}
// private data
this.name = name;
this.columns = [];
this.data = [];
this.dataUnfiltered = null; // non null means that data is filtered
this.xmlDoc = null;
this.sortedColumnName = -1;
this.sortDescending = false;
this.baseUrl = this.detectDir();
this.nbHeaderRows = 1;
this.lastSelectedRowIndex = -1;
this.currentPageIndex = 0;
this.currentFilter = null;
this.currentContainerid = null;
this.currentClassName = null;
this.currentTableid = null;
if (this.enableSort) {
if ( typeof config != "undefined" && typeof config['sortIconUp'] != "undefined" ) {
this.sortUpElement = new Image();
this.sortUpElement.src = config['sortIconUp'];
} else {
this.sortUpElement = document.createElement('span');
this.sortUpElement.innerHTML = '↑' // Unicode 'up' arrow
}
if ( typeof config != "undefined" && typeof config['sortIconDown'] != "undefined" ) {
this.sortDownElement = new Image();
this.sortDownElement.src = config['sortIconDown'];
} else {
this.sortDownElement = document.createElement('span');
this.sortDownElement.innerHTML = '↓' // Unicode 'down' arrow
}
}
// restore stored parameters, or use default values if nothing stored
this.currentPageIndex = this.localisset('pageIndex') ? parseInt(this.localget('pageIndex')) : 0;
this.sortedColumnName = this.localisset('sortColumnIndexOrName') ? this.localget('sortColumnIndexOrName') : -1;
this.sortDescending = this.localisset('sortColumnIndexOrName') && this.localisset('sortDescending') ? this.localget('sortDescending') == 'true' : false;
this.currentFilter = this.localisset('filter') ? this.localget('filter') : null;
};
/**
* Callback functions
*/
EditableGrid.prototype.tableLoaded = function() {};
EditableGrid.prototype.chartRendered = function() {};
EditableGrid.prototype.tableRendered = function(containerid, className, tableid) {};
EditableGrid.prototype.tableSorted = function(columnIndex, descending) {};
EditableGrid.prototype.tableFiltered = function() {};
EditableGrid.prototype.openedCellEditor = function(rowIndex, columnIndex) {};
EditableGrid.prototype.modelChanged = function(rowIndex, columnIndex, oldValue, newValue, row) {};
EditableGrid.prototype.rowSelected = function(oldRowIndex, newRowIndex) {};
EditableGrid.prototype.isHeaderEditable = function(rowIndex, columnIndex) { return false; };
EditableGrid.prototype.isEditable =function(rowIndex, columnIndex) { return true; };
EditableGrid.prototype.readonlyWarning = function() {};
/** Notifies that a row has been deleted */
EditableGrid.prototype.rowRemoved = function(oldRowIndex, rowId) {};
/**
* Load metadata and/or data from an XML url
* The callback "tableLoaded" is called when loading is complete.
*/
EditableGrid.prototype.loadXML = function(url, callback, dataOnly)
{
this.lastURL = url;
var self = this;
// IE
if (window.ActiveXObject)
{
this.xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
this.xmlDoc.onreadystatechange = function() {
if (self.xmlDoc.readyState == 4) {
self.processXML();
self._callback('xml', callback);
}
};
this.xmlDoc.load(this._addUrlParameters(url, dataOnly));
}
// generic Ajax
else if (window.XMLHttpRequest)
{
this.xmlDoc = new XMLHttpRequest();
this.xmlDoc.onreadystatechange = function () {
if (this.readyState == 4) {
self.xmlDoc = this.responseXML;
if (!self.xmlDoc) { console.error("Could not load XML from url '" + url + "'"); return false; }
self.processXML();
self._callback('xml', callback);
}
};
this.xmlDoc.open("GET", this._addUrlParameters(url, dataOnly), true);
this.xmlDoc.send("");
}
// Firefox (and some other browsers)
else if (document.implementation && document.implementation.createDocument)
{
this.xmlDoc = document.implementation.createDocument("", "", null);
this.xmlDoc.onload = function() {
self.processXML();
self._callback('xml', callback);
};
this.xmlDoc.load(this._addUrlParameters(url, dataOnly));
}
// should never happen
else {
alert("Cannot load a XML url with this browser!");
return false;
}
return true;
};
/**
* Load metadata and/or data from an XML string
* No callback "tableLoaded" is called since this is a synchronous operation.
*
* Contributed by Tim Consolazio of Tcoz Tech Services, [email protected]
* http://tcoztechwire.blogspot.com/2012/04/setxmlfromstring-extension-for.html
*/
EditableGrid.prototype.loadXMLFromString = function(xml)
{
if (window.DOMParser) {
var parser = new DOMParser();
this.xmlDoc = parser.parseFromString(xml, "application/xml");
}
else {
this.xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); // IE
this.xmlDoc.async = "false";
this.xmlDoc.loadXML(xml);
}
this.processXML();
};
/**
* Process the XML content
* @private
*/
EditableGrid.prototype.processXML = function()
{
with (this) {
// clear model and pointer to current table
this.data = [];
this.dataUnfiltered = null;
this.table = null;
// load metadata (only one tag <metadata> --> metadata[0])
var metadata = xmlDoc.getElementsByTagName("metadata");
if (metadata && metadata.length >= 1) {
this.columns = [];
var columnDeclarations = metadata[0].getElementsByTagName("column");
for (var i = 0; i < columnDeclarations.length; i++) {
// get column type
var col = columnDeclarations[i];
var datatype = col.getAttribute("datatype");
// get enumerated values if any
var optionValuesForRender = null;
var optionValues = null;
var enumValues = col.getElementsByTagName("values");
if (enumValues.length > 0) {
optionValues = [];
optionValuesForRender = {};
var enumGroups = enumValues[0].getElementsByTagName("group");
if (enumGroups.length > 0) {
for (var g = 0; g < enumGroups.length; g++) {
var groupOptionValues = [];
enumValues = enumGroups[g].getElementsByTagName("value");
for (var v = 0; v < enumValues.length; v++) {
var _value = enumValues[v].getAttribute("value");
var _label = enumValues[v].firstChild ? enumValues[v].firstChild.nodeValue : "";
optionValuesForRender[_value] = _label;
groupOptionValues.push({ value: _value, label: _label });
}
optionValues.push({ label: enumGroups[g].getAttribute("label"), values: groupOptionValues});
}
}
else {
enumValues = enumValues[0].getElementsByTagName("value");
for (var v = 0; v < enumValues.length; v++) {
var _value = enumValues[v].getAttribute("value");
var _label = enumValues[v].firstChild ? enumValues[v].firstChild.nodeValue : "";
optionValuesForRender[_value] = _label;
optionValues.push({ value: _value, label: _label });
}
}
}
// create new column
columns.push(new Column({
name: col.getAttribute("name"),
label: (typeof col.getAttribute("label") == 'string' ? col.getAttribute("label") : col.getAttribute("name")),
datatype: (col.getAttribute("datatype") ? col.getAttribute("datatype") : "string"),
editable: col.getAttribute("editable") == "true",
bar: (col.getAttribute("bar") ? col.getAttribute("bar") == "true" : true),
hidden: (col.getAttribute("hidden") ? col.getAttribute("hidden") == "true" : false),
optionValuesForRender: optionValuesForRender,
optionValues: optionValues
}));
}
// process columns
processColumns();
}
// load server-side pagination data
var paginator = xmlDoc.getElementsByTagName("paginator");
if (paginator && paginator.length >= 1) {
this.paginatorAttributes = null; // TODO: paginator[0].getAllAttributesAsPOJO;
this.pageCount = paginator[0].getAttribute('pagecount');
this.totalRowCount = paginator[0].getAttribute('totalrowcount');
this.unfilteredRowCount = paginator[0].getAttribute('unfilteredrowcount');
}
// if no row id is provided, we create one since we need one
var defaultRowId = 1;
// load content
var rows = xmlDoc.getElementsByTagName("row");
for (var i = 0; i < rows.length; i++)
{
// get all defined cell values
var cellValues = {};
var cols = rows[i].getElementsByTagName("column");
for (var j = 0; j < cols.length; j++) {
var colname = cols[j].getAttribute("name");
if (!colname) {
if (j >= columns.length) console.error("You defined too many columns for row " + (i+1));
else colname = columns[j].name;
}
cellValues[colname] = cols[j].firstChild ? cols[j].firstChild.nodeValue : "";
}
// for each row we keep the orginal index, the id and all other attributes that may have been set in the XML
var rowData = { visible: true, originalIndex: i, id: rows[i].getAttribute("id") !== null ? rows[i].getAttribute("id") : defaultRowId++ };
for (var attrIndex = 0; attrIndex < rows[i].attributes.length; attrIndex++) {
var node = rows[i].attributes.item(attrIndex);
if (node.nodeName != "id") rowData[node.nodeName] = node.nodeValue;
}
// get column values for this rows
rowData.columns = [];
for (var c = 0; c < columns.length; c++) {
var cellValue = columns[c].name in cellValues ? cellValues[columns[c].name] : "";
rowData.columns.push(getTypedValue(c, cellValue));
}
// add row data in our model
data.push(rowData);
}
}
return true;
};
/**
* Load metadata and/or data from a JSON url
* The callback "tableLoaded" is called when loading is complete.
*/
EditableGrid.prototype.loadJSON = function(url, callback, dataOnly)
{
this.lastURL = url;
var self = this;
// should never happen
if (!window.XMLHttpRequest) {
alert("Cannot load a JSON url with this browser!");
return false;
}
var ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function () {
if (this.readyState == 4) {
if (!this.responseText) { console.error("Could not load JSON from url '" + url + "'"); return false; }
if (!self.processJSON(this.responseText)) { console.error("Invalid JSON data obtained from url '" + url + "'"); return false; }
self._callback('json', callback);
}
};
ajaxRequest.open("GET", this._addUrlParameters(url, dataOnly), true);
ajaxRequest.send("");
return true;
};
EditableGrid.prototype._addUrlParameters = function(baseUrl, dataOnly)
{
// we add a dummy timestamp parameter to avoid getting an old version from the browser's cache
var sep = baseUrl.indexOf('?') >= 0 ? '&' : '?';
baseUrl += sep + (new Date().getTime());
if (!this.serverSide) return baseUrl;
// add pagination, filtering and sorting parameters to the base url
return baseUrl
+ "&page=" + (this.currentPageIndex + 1)
+ "&filter=" + (this.currentFilter ? encodeURIComponent(this.currentFilter) : "")
+ "&sort=" + (this.sortedColumnName && this.sortedColumnName != -1 ? encodeURIComponent(this.sortedColumnName) : "")
+ "&asc=" + (this.sortDescending ? 0 : 1)
+ (dataOnly ? '&data_only=1' : '');
};
EditableGrid.prototype._callback = function(type, callback)
{
if (callback) callback.call(this);
else {
if (this.serverSide) {
// deferred refreshGrid: first load the updated data from the server then call the original refreshGrid
this.refreshGrid = function(baseUrl) {
var callback = function() { EditableGrid.prototype.refreshGrid.call(this); };
var load = type == 'xml' ? this.loadXML : this.loadJSON;
load.call(this, baseUrl || this.lastURL, callback, true);
};
}
this.tableLoaded();
}
};
/**
* Load metadata and/or data from a JSON string
* No callback "tableLoaded" is called since this is a synchronous operation.
*/
EditableGrid.prototype.loadJSONFromString = function(json)
{
return this.processJSON(json);
};
/**
* Load metadata and/or data from a Javascript object
* No callback "tableLoaded" is called since this is a synchronous operation.
*/
EditableGrid.prototype.load = function(object)
{
return this.processJSON(object);
};
/**
* Update and render data for given rows from a Javascript object
*/
EditableGrid.prototype.update = function(object)
{
if (object.data) for (var i = 0; i < object.data.length; i++)
{
var row = object.data[i];
if (row.id == undefined || !row.values) continue;
// get row to update in our model
var rowIndex = this.getRowIndex(row.id);
var rowData = this.data[rowIndex];
// row values can be given as an array (same order as columns) or as an object (associative array)
if (Object.prototype.toString.call(row.values) !== '[object Array]' ) cellValues = row.values;
else {
cellValues = {};
for (var j = 0; j < row.values.length && j < this.columns.length; j++) cellValues[this.columns[j].name] = row.values[j];
}
// set all attributes that may have been set in the JSON
for (var attributeName in row) if (attributeName != "id" && attributeName != "values") rowData[attributeName] = row[attributeName];
// get column values for this rows
rowData.columns = [];
for (var c = 0; c < this.columns.length; c++) {
var cellValue = this.columns[c].name in cellValues ? cellValues[this.columns[c].name] : "";
rowData.columns.push(this.getTypedValue(c, cellValue));
}
// render row
var tr = this.getRow(rowIndex);
for (var j = 0; j < tr.cells.length && j < this.columns.length; j++) if (this.columns[j].renderable) this.columns[j].cellRenderer._render(rowIndex, j, tr.cells[j], this.getValueAt(rowIndex,j));
this.tableRendered(this.currentContainerid, this.currentClassName, this.currentTableid);
}
};
/**
* Process the JSON content
* @private
*/
EditableGrid.prototype.processJSON = function(jsonData)
{
if (typeof jsonData == "string") jsonData = eval("(" + jsonData + ")");
if (!jsonData) return false;
// clear model and pointer to current table
this.data = [];
this.dataUnfiltered = null;
this.table = null;
// load metadata
if (jsonData.metadata) {
// create columns
this.columns = [];
for (var c = 0; c < jsonData.metadata.length; c++) {
var columndata = jsonData.metadata[c];
var optionValues = columndata.values ? this._convertOptions(columndata.values) : null;
var optionValuesForRender = null;
if (optionValues) {
// build a fast lookup structure for rendering
var optionValuesForRender = {};
for (var optionIndex = 0; optionIndex < optionValues.length; optionIndex++) {
var optionValue = optionValues[optionIndex];
if (typeof optionValue.values == 'object') {
for (var groupOptionIndex = 0; groupOptionIndex < optionValue.values.length; groupOptionIndex++) {
var groupOptionValue = optionValue.values[groupOptionIndex];
optionValuesForRender[groupOptionValue.value] = groupOptionValue.label;
}
}
else optionValuesForRender[optionValue.value] = optionValue.label;
}
}
this.columns.push(new Column({
name: columndata.name,
label: (columndata.label ? columndata.label : columndata.name),
datatype: (columndata.datatype ? columndata.datatype : "string"),
editable: (columndata.editable ? true : false),
bar: (typeof columndata.bar == 'undefined' ? true : (columndata.bar || false)),
hidden: (typeof columndata.hidden == 'undefined' ? false : (columndata.hidden ? true : false)),
optionValuesForRender: optionValuesForRender,
optionValues: optionValues
}));
}
// process columns
this.processColumns();
}
// load server-side pagination data
if (jsonData.paginator) {
this.paginatorAttributes = jsonData.paginator;
this.pageCount = jsonData.paginator.pagecount;
this.totalRowCount = jsonData.paginator.totalrowcount;
this.unfilteredRowCount = jsonData.paginator.unfilteredrowcount;
}
// if no row id is provided, we create one since we need one
var defaultRowId = 1;
// load content
if (jsonData.data) for (var i = 0; i < jsonData.data.length; i++)
{
var row = jsonData.data[i];
if (!row.values) continue;
// row values can be given as an array (same order as columns) or as an object (associative array)
if (Object.prototype.toString.call(row.values) !== '[object Array]' ) cellValues = row.values;
else {
cellValues = {};
for (var j = 0; j < row.values.length && j < this.columns.length; j++) cellValues[this.columns[j].name] = row.values[j];
}
// for each row we keep the orginal index, the id and all other attributes that may have been set in the JSON
var rowData = { visible: true, originalIndex: i, id: row.id !== undefined && row.id !== null ? row.id : defaultRowId++ };
for (var attributeName in row) if (attributeName != "id" && attributeName != "values") rowData[attributeName] = row[attributeName];
// get column values for this rows
rowData.columns = [];
for (var c = 0; c < this.columns.length; c++) {
var cellValue = this.columns[c].name in cellValues ? cellValues[this.columns[c].name] : "";
rowData.columns.push(this.getTypedValue(c, cellValue));
}
// add row data in our model
this.data.push(rowData);
}
return true;
};
/**
* Process columns
* @private
*/
EditableGrid.prototype.processColumns = function()
{
for (var columnIndex = 0; columnIndex < this.columns.length; columnIndex++) {
var column = this.columns[columnIndex];
// set column index and back pointer
column.columnIndex = columnIndex;
column.editablegrid = this;
// parse column type
this.parseColumnType(column);
// create suited enum provider if none given
if (!column.enumProvider) column.enumProvider = column.optionValues ? new EnumProvider() : null;
// create suited cell renderer if none given
if (!column.cellRenderer) this._createCellRenderer(column);
if (!column.headerRenderer) this._createHeaderRenderer(column);
// create suited cell editor if none given
if (!column.cellEditor) this._createCellEditor(column);
if (!column.headerEditor) this._createHeaderEditor(column);
// add default cell validators based on the column type
this._addDefaultCellValidators(column);
}
};
/**
* Parse column type
* @private
*/
EditableGrid.prototype.parseColumnType = function(column)
{
// reset
column.unit = null;
column.precision = -1;
column.decimal_point = ',';
column.thousands_separator = '.';
column.unit_before_number = false;
column.nansymbol = '';
// extract precision, unit and number format from type if 6 given
if (column.datatype.match(/(.*)\((.*),(.*),(.*),(.*),(.*),(.*)\)$/)) {
column.datatype = RegExp.$1;
column.unit = RegExp.$2;
column.precision = parseInt(RegExp.$3);
column.decimal_point = RegExp.$4;
column.thousands_separator = RegExp.$5;
column.unit_before_number = RegExp.$6;
column.nansymbol = RegExp.$7;
// trim should be done after fetching RegExp matches beacuse it itself uses a RegExp and causes interferences!
column.unit = column.unit.trim();
column.decimal_point = column.decimal_point.trim();
column.thousands_separator = column.thousands_separator.trim();
column.unit_before_number = column.unit_before_number.trim() == '1';
column.nansymbol = column.nansymbol.trim();
}
// extract precision, unit and number format from type if 5 given
else if (column.datatype.match(/(.*)\((.*),(.*),(.*),(.*),(.*)\)$/)) {
column.datatype = RegExp.$1;
column.unit = RegExp.$2;
column.precision = parseInt(RegExp.$3);
column.decimal_point = RegExp.$4;
column.thousands_separator = RegExp.$5;
column.unit_before_number = RegExp.$6;
// trim should be done after fetching RegExp matches beacuse it itself uses a RegExp and causes interferences!
column.unit = column.unit.trim();
column.decimal_point = column.decimal_point.trim();
column.thousands_separator = column.thousands_separator.trim();
column.unit_before_number = column.unit_before_number.trim() == '1';
}
// extract precision, unit and nansymbol from type if 3 given
else if (column.datatype.match(/(.*)\((.*),(.*),(.*)\)$/)) {
column.datatype = RegExp.$1;
column.unit = RegExp.$2.trim();
column.precision = parseInt(RegExp.$3);
column.nansymbol = RegExp.$4.trim();
}
// extract precision and unit from type if two given
else if (column.datatype.match(/(.*)\((.*),(.*)\)$/)) {
column.datatype = RegExp.$1.trim();
column.unit = RegExp.$2.trim();
column.precision = parseInt(RegExp.$3);
}
// extract precision or unit from type if any given
else if (column.datatype.match(/(.*)\((.*)\)$/)) {
column.datatype = RegExp.$1.trim();
var unit_or_precision = RegExp.$2.trim();
if (unit_or_precision.match(/^[0-9]*$/)) column.precision = parseInt(unit_or_precision);
else column.unit = unit_or_precision;
}
if (column.decimal_point == 'comma') column.decimal_point = ',';
if (column.decimal_point == 'dot') column.decimal_point = '.';
if (column.thousands_separator == 'comma') column.thousands_separator = ',';
if (column.thousands_separator == 'dot') column.thousands_separator = '.';
if (isNaN(column.precision)) column.precision = -1;
if (column.unit == '') column.unit = null;
if (column.nansymbol == '') column.nansymbol = null;
};
/**
* Get typed value
* @private
*/
EditableGrid.prototype.getTypedValue = function(columnIndex, cellValue)
{
if (cellValue === null) return cellValue;
var colType = this.getColumnType(columnIndex);
if (colType == 'boolean') cellValue = (cellValue && cellValue != 0 && cellValue != "false" && cellValue != "f") ? true : false;
if (colType == 'integer') { cellValue = parseInt(cellValue, 10); }
if (colType == 'double') { cellValue = parseFloat(cellValue); }
if (colType == 'string') { cellValue = "" + cellValue; }
return cellValue;
};
/**
* Attach to an existing HTML table.
* The second parameter can be used to give the column definitions.
* This parameter is left for compatibility, but is deprecated: you should now use "load" to setup the metadata.
*/
EditableGrid.prototype.attachToHTMLTable = function(_table, _columns)
{
// clear model and pointer to current table
this.data = [];
this.dataUnfiltered = null;
this.table = null;
// process columns if given
if (_columns) {
this.columns = _columns;
for (var columnIndex = 0; columnIndex < this.columns.length; columnIndex++) this.columns[columnIndex].optionValues = this._convertOptions(this.columns[columnIndex].optionValues); // convert options from old format if needed
this.processColumns();
}
// get pointers to table components
this.table = typeof _table == 'string' ? _$(_table) : _table ;
if (!this.table) console.error("Invalid table given: " + _table);
this.tHead = this.table.tHead;
this.tBody = this.table.tBodies[0];
// create table body if needed
if (!this.tBody) {
this.tBody = document.createElement("TBODY");
this.table.insertBefore(this.tBody, this.table.firstChild);
}
// create table header if needed
if (!this.tHead) {
this.tHead = document.createElement("THEAD");
this.table.insertBefore(this.tHead, this.tBody);
}
// if header is empty use first body row as header
if (this.tHead.rows.length == 0 && this.tBody.rows.length > 0)
this.tHead.appendChild(this.tBody.rows[0]);
// get number of rows in header
this.nbHeaderRows = this.tHead.rows.length;
// load header labels
var rows = this.tHead.rows;
for (var i = 0; i < rows.length; i++) {
var cols = rows[i].cells;
var columnIndexInModel = 0;
for (var j = 0; j < cols.length && columnIndexInModel < this.columns.length; j++) {
if (!this.columns[columnIndexInModel].label || this.columns[columnIndexInModel].label == this.columns[columnIndexInModel].name) this.columns[columnIndexInModel].label = cols[j].innerHTML;
var colspan = parseInt(cols[j].getAttribute("colspan"));
columnIndexInModel += colspan > 1 ? colspan : 1;
}
}
// load content
var rows = this.tBody.rows;
for (var i = 0; i < rows.length; i++) {
var rowData = [];
var cols = rows[i].cells;
for (var j = 0; j < cols.length && j < this.columns.length; j++) rowData.push(this.getTypedValue(j, cols[j].innerHTML));
this.data.push({ visible: true, originalIndex: i, id: rows[i].id, columns: rowData });
rows[i].rowId = rows[i].id;
rows[i].id = this._getRowDOMId(rows[i].id);
}
};
/**
* Creates a suitable cell renderer for the column
* @private
*/
EditableGrid.prototype._createCellRenderer = function(column)
{
column.cellRenderer =
column.enumProvider && column.datatype == "list" && typeof MultiselectCellRenderer != 'undefined' ? new MultiselectCellRenderer() :
column.enumProvider ? new EnumCellRenderer() :
column.datatype == "integer" || column.datatype == "double" ? new NumberCellRenderer() :
column.datatype == "boolean" ? new CheckboxCellRenderer() :
column.datatype == "email" ? new EmailCellRenderer() :
column.datatype == "website" || column.datatype == "url" ? new WebsiteCellRenderer() :
column.datatype == "date" ? new DateCellRenderer() :
new CellRenderer();
// give access to the column from the cell renderer
if (column.cellRenderer) {
column.cellRenderer.editablegrid = this;
column.cellRenderer.column = column;
}
};
/**
* Creates a suitable header cell renderer for the column
* @private
*/
EditableGrid.prototype._createHeaderRenderer = function(column)
{
column.headerRenderer = (this.enableSort && column.datatype != "html") ? new SortHeaderRenderer(column.name) : new CellRenderer();
// give access to the column from the header cell renderer
if (column.headerRenderer) {
column.headerRenderer.editablegrid = this;
column.headerRenderer.column = column;
}
};
/**
* Creates a suitable cell editor for the column
* @private
*/
EditableGrid.prototype._createCellEditor = function(column)
{
column.cellEditor =
column.enumProvider && column.datatype == "list" && typeof MultiselectCellEditor != 'undefined' ? new MultiselectCellEditor() :
column.enumProvider ? new SelectCellEditor() :
column.datatype == "integer" || column.datatype == "double" ? new NumberCellEditor(column.datatype) :
column.datatype == "boolean" ? null :
column.datatype == "email" ? new TextCellEditor(column.precision) :
column.datatype == "website" || column.datatype == "url" ? new TextCellEditor(column.precision) :
column.datatype == "date" ? (typeof jQuery == 'undefined' || typeof jQuery.datepicker == 'undefined' ? new TextCellEditor(column.precision, 10) : new DateCellEditor({ fieldSize: column.precision, maxLength: 10 })) :
new TextCellEditor(column.precision);
// give access to the column from the cell editor
if (column.cellEditor) {
column.cellEditor.editablegrid = this;
column.cellEditor.column = column;
}
};
/**
* Creates a suitable header cell editor for the column
* @private
*/
EditableGrid.prototype._createHeaderEditor = function(column)
{
column.headerEditor = new TextCellEditor();
// give access to the column from the cell editor
if (column.headerEditor) {
column.headerEditor.editablegrid = this;
column.headerEditor.column = column;
}
};
/**
* Returns the number of rows
*/
EditableGrid.prototype.getRowCount = function()
{
return this.data.length;
};
/**
* Returns the number of rows, not taking the filter into account if any
*/
EditableGrid.prototype.getUnfilteredRowCount = function()
{
// given if server-side filtering is involved
if (this.unfilteredRowCount > 0) return this.unfilteredRowCount;
var _data = this.dataUnfiltered == null ? this.data : this.dataUnfiltered;
return _data.length;
};
/**
* Returns the number of rows in all pages
*/
EditableGrid.prototype.getTotalRowCount = function()
{
// different from getRowCount only is server-side pagination is involved
if (this.totalRowCount > 0) return this.totalRowCount;
return this.getRowCount();
};
/**
* Returns the number of columns
*/
EditableGrid.prototype.getColumnCount = function()
{
return this.columns.length;
};
/**
* Returns true if the column exists
* @param {Object} columnIndexOrName index or name of the column
*/
EditableGrid.prototype.hasColumn = function(columnIndexOrName)
{
return this.getColumnIndex(columnIndexOrName) >= 0;
};
/**
* Returns the column
* @param {Object} columnIndexOrName index or name of the column
*/
EditableGrid.prototype.getColumn = function(columnIndexOrName)
{
var colIndex = this.getColumnIndex(columnIndexOrName);
if (colIndex < 0) { console.error("[getColumn] Column not found with index or name " + columnIndexOrName); return null; }
return this.columns[colIndex];
};
/**
* Returns the name of a column
* @param {Object} columnIndexOrName index or name of the column