forked from webismymind/editablegrid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
editablegrid.js
1651 lines (1441 loc) · 53.2 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
headerRenderer: null,
headerEditor: null,
cellRenderer: null,
cellEditor: null,
cellValidators: [],
enumProvider: null,
optionValues: 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) {
var values = this.enumProvider.getOptionValuesForRender(this.editablegrid, this, rowIndex);
return values ? values : this.optionValues;
};
Column.prototype.getOptionValuesForEdit = function(rowIndex) {
var values = this.enumProvider.getOptionValuesForEdit(this.editablegrid, this, rowIndex);
return values ? 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>
* </ul>
* @constructor
* @class EditableGrid
*/
function EditableGrid(name, config) { if (name) this.init(name, config); }
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) + ".");
};
// default properties
var props =
{
enableSort: true,
doubleclick: false,
editmode: "absolute",
editorzoneid: "",
allowSimultaneousEdition: false,
saveOnBlur: true,
invalidClassName: "invalid",
ignoreLastRow: false,
caption: null,
dateFormat: "EU",
shortMonthNames: null,
smartColorsBar: ["#dc243c","#4040f6","#00f629","#efe100","#f93fb1","#6f8183","#111111"],
smartColorsPie: ["#FF0000","#00FF00","#0000FF","#FFD700","#FF00FF","#00FFFF","#800080"],
pageSize: 0
};
// override default properties with the ones given
for (var p in props) this[p] = props[p];
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/)
};
// 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) {
this.sortUpImage = new Image();
this.sortUpImage.src = this.baseUrl + "/images/bullet_arrow_up.png";
this.sortDownImage = new Image();
this.sortDownImage.src = this.baseUrl + "/images/bullet_arrow_down.png";
}
};
/**
* 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.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() {};
/**
* Load metadata and data from an XML url
*/
EditableGrid.prototype.loadXML = function(url)
{
// we use a trick to avoid getting an old version from the browser's cache
var orig_url = url;
var sep = url.indexOf('?') >= 0 ? '&' : '?';
url += sep + Math.floor(Math.random() * 100000);
with (this) {
// IE
if (window.ActiveXObject)
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.onreadystatechange = function() {
if (xmlDoc.readyState == 4) {
processXML();
tableLoaded();
}
};
xmlDoc.load(url);
}
// Safari
else if (/*Browser.WebKit && */ window.XMLHttpRequest)
{
xmlDoc = new XMLHttpRequest();
xmlDoc.onreadystatechange = function () {
if (xmlDoc.readyState == 4) {
xmlDoc = xmlDoc.responseXML;
if (!xmlDoc) { /* alert("Could not load XML from url '" + orig_url + "'"); */ return false; }
processXML();
tableLoaded();
}
};
xmlDoc.open("GET", url, true);
xmlDoc.send("");
}
// Firefox (and other browsers)
else if (document.implementation && document.implementation.createDocument)
{
xmlDoc = document.implementation.createDocument("", "", null);
xmlDoc.onload = function() {
processXML();
tableLoaded();
};
xmlDoc.load(url);
}
// should never happen
else {
alert("Cannot load XML file with this browser!");
return false;
}
return true;
}
};
/**
* Process the XML content
* @private
*/
EditableGrid.prototype.processXML = function()
{
with (this) {
// clear model and pointer to current table
this.columns = [];
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) return false;
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 optionValues = null;
var enumValues = col.getElementsByTagName("values");
if (enumValues.length > 0) {
optionValues = {};
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++) {
groupOptionValues[enumValues[v].getAttribute("value")] = enumValues[v].firstChild ? enumValues[v].firstChild.nodeValue : "";
}
optionValues[enumGroups[g].getAttribute("label")] = groupOptionValues;
}
}
else {
enumValues = enumValues[0].getElementsByTagName("value");
for (var v = 0; v < enumValues.length; v++) {
optionValues[enumValues[v].getAttribute("value")] = enumValues[v].firstChild ? enumValues[v].firstChild.nodeValue : "";
}
}
}
// create new column
var column = 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,
optionValues: optionValues,
enumProvider: (optionValues ? new EnumProvider() : null),
columnIndex: i
});
// parse column type
parseColumnType(column);
// create suited cell renderer
_createCellRenderer(column);
_createHeaderRenderer(column);
// create suited cell editor
_createCellEditor(column);
_createHeaderEditor(column);
// add default cell validators based on the column type
_addDefaultCellValidators(column);
// add column
column.editablegrid = this;
columns.push(column);
}
// 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) alert("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") ? rows[i].getAttribute("id") : "" };
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);
}
}
};
/**
* Parse column type
* @private
*/
EditableGrid.prototype.parseColumnType = function(column)
{
// 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 = null;
if (column.unit == '') column.unit = null;
if (column.nansymbol == '') column.nansymbol = null;
};
/**
* Get typed value
* @private
*/
EditableGrid.prototype.getTypedValue = function(columnIndex, cellValue)
{
var colType = this.getColumnType(columnIndex);
if (colType == 'boolean') cellValue = (cellValue && cellValue != 0 && cellValue != "false") ? true : false;
if (colType == 'integer') { cellValue = parseInt(cellValue); }
if (colType == 'double') { cellValue = parseFloat(cellValue); }
if (colType == 'string') { cellValue = "" + cellValue; }
return cellValue;
};
/**
* Attach to an existing HTML table, using given column definitions
*/
EditableGrid.prototype.attachToHTMLTable = function(_table, _columns)
{
with (this) {
// clear model and pointer to current table
this.columns = [];
this.data = [];
this.dataUnfiltered = null;
this.table = null;
// we have our new columns
columns = _columns;
for (var c = 0; c < columns.length; c++) {
// set column index and back pointer
var column = columns[c];
column.editablegrid = this;
column.columnIndex = c;
// parse column type
parseColumnType(column);
// create suited enum provider, renderer and editor if none given
if (!column.enumProvider) column.enumProvider = column.optionValues ? new EnumProvider() : null;
if (!column.cellRenderer) _createCellRenderer(column);
if (!column.headerRenderer) _createHeaderRenderer(column);
if (!column.cellEditor) _createCellEditor(column);
if (!column.headerEditor) _createHeaderEditor(column);
// add default cell validators based on the column type
_addDefaultCellValidators(column);
}
// get pointers to table components
this.table = typeof _table == 'string' ? _$(_table) : _table ;
if (!this.table) alert("Invalid table given: " + _table);
this.tHead = this.table.tHead;
this.tBody = this.table.tBodies[0];
// create table body if needed
if (!tBody) {
tBody = document.createElement("TBODY");
table.insertBefore(tBody, table.firstChild);
}
// create table header if needed
if (!tHead) {
tHead = document.createElement("THEAD");
table.insertBefore(tHead, tBody);
}
// if header is empty use first body row as header
if (tHead.rows.length == 0 && tBody.rows.length > 0)
tHead.appendChild(tBody.rows[0]);
// check that header has exactly one row
this.nbHeaderRows = tHead.rows.length;
/*if (tHead.rows.length != 1) {
alert("You table header must have exactly row!");
return false;
}*/
// load header labels
var rows = 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 < columns.length; j++) {
if (!columns[columnIndexInModel].label) columns[columnIndexInModel].label = cols[j].innerHTML;
var colspan = parseInt(cols[j].getAttribute("colspan"));
columnIndexInModel += colspan > 1 ? colspan : 1;
}
}
// load content
var rows = 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 < columns.length; j++) rowData.push(this.getTypedValue(j, cols[j].innerHTML));
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 ? 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 ? 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 $ == 'undefined' || typeof $.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 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) { alert("[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
*/
EditableGrid.prototype.getColumnName = function(columnIndexOrName)
{
return this.getColumn(columnIndexOrName).name;
};
/**
* Returns the label of a column
* @param {Object} columnIndexOrName index or name of the column
*/
EditableGrid.prototype.getColumnLabel = function(columnIndexOrName)
{
return this.getColumn(columnIndexOrName).label;
};
/**
* Returns the type of a column
* @param {Object} columnIndexOrName index or name of the column
*/
EditableGrid.prototype.getColumnType = function(columnIndexOrName)
{
return this.getColumn(columnIndexOrName).datatype;
};
/**
* Returns the unit of a column
* @param {Object} columnIndexOrName index or name of the column
*/
EditableGrid.prototype.getColumnUnit = function(columnIndexOrName)
{
return this.getColumn(columnIndexOrName).unit;
};
/**
* Returns the precision of a column
* @param {Object} columnIndexOrName index or name of the column
*/
EditableGrid.prototype.getColumnPrecision = function(columnIndexOrName)
{
return this.getColumn(columnIndexOrName).precision;
};
/**
* Returns true if the column is to be displayed in a bar chart
* @param {Object} columnIndexOrName index or name of the column
*/
EditableGrid.prototype.isColumnBar = function(columnIndexOrName)
{
var column = this.getColumn(columnIndexOrName);
return (column.bar && column.isNumerical());
};
/**
* Returns true if the column is numerical (double or integer)
* @param {Object} columnIndexOrName index or name of the column
*/
EditableGrid.prototype.isColumnNumerical = function(columnIndexOrName)
{
var column = this.getColumn(columnIndexOrName);
return column.isNumerical();;
};
/**
* Returns the value at the specified index
* @param {Integer} rowIndex
* @param {Integer} columnIndex
*/
EditableGrid.prototype.getValueAt = function(rowIndex, columnIndex)
{
// check and get column
if (columnIndex < 0 || columnIndex >= this.columns.length) { alert("[getValueAt] Invalid column index " + columnIndex); return null; }
var column = this.columns[columnIndex];
// get value in model
if (rowIndex < 0) return column.label;
if (typeof this.data[rowIndex] == 'undefined') alert("[getValueAt] Invalid row index " + rowIndex);
var rowData = this.data[rowIndex]['columns'];
return rowData ? rowData[columnIndex] : null;
};
/**
* Sets the value at the specified index
* @param {Integer} rowIndex
* @param {Integer} columnIndex
* @param {Object} value
* @param {Boolean} render
*/
EditableGrid.prototype.setValueAt = function(rowIndex, columnIndex, value, render)
{
if (typeof render == "undefined") render = true;
var previousValue = null;;
// check and get column
if (columnIndex < 0 || columnIndex >= this.columns.length) { alert("[setValueAt] Invalid column index " + columnIndex); return null; }
var column = this.columns[columnIndex];
// set new value in model
if (rowIndex < 0) {
previousValue = column.label;
column.label = value;
}
else {
var rowData = this.data[rowIndex]['columns'];
previousValue = rowData[columnIndex];
if (rowData) rowData[columnIndex] = this.getTypedValue(columnIndex, value);
}
// render new value
if (render) {
var renderer = rowIndex < 0 ? column.headerRenderer : column.cellRenderer;
renderer._render(rowIndex, columnIndex, this.getCell(rowIndex, columnIndex), value);
}
return previousValue;
};
/**
* Find column index from its name
* @param {Object} columnIndexOrName index or name of the column
*/
EditableGrid.prototype.getColumnIndex = function(columnIndexOrName)
{
if (typeof columnIndexOrName == "undefined" || columnIndexOrName === "") return -1;
// TODO: problem because the name of a column could be a valid index, and we cannot make the distinction here!
// if columnIndexOrName is a number which is a valid index return it
if (!isNaN(columnIndexOrName) && columnIndexOrName >= 0 && columnIndexOrName < this.columns.length) return columnIndexOrName;
// otherwise search for the name
for (var c = 0; c < this.columns.length; c++) if (this.columns[c].name == columnIndexOrName) return c;
return -1;
};
/**
* Get HTML row object at given index
* @param {Integer} index of the row
*/
EditableGrid.prototype.getRow = function(rowIndex)
{
if (rowIndex < 0) return this.tHead.rows[rowIndex + this.nbHeaderRows];
if (typeof this.data[rowIndex] == 'undefined') alert("[getRow] Invalid row index " + rowIndex);
return _$(this._getRowDOMId(this.data[rowIndex].id));
};
/**
* Get row id for given row index
* @param {Integer} index of the row
*/
EditableGrid.prototype.getRowId = function(rowIndex)
{
return (rowIndex < 0 || rowIndex >= this.data.length) ? null : this.data[rowIndex]['id'];
};
/**
* Get index of row with given id
* @param {Integer} rowId or HTML row object
*/
EditableGrid.prototype.getRowIndex = function(rowId)
{
rowId = typeof rowId == 'object' ? rowId.rowId : rowId;
for (var rowIndex = 0; rowIndex < this.data.length; rowIndex++) if (this.data[rowIndex].id == rowId) return rowIndex;
return -1;
};
/**
* Get custom row attribute specified in XML
* @param {Integer} index of the row
* @param {String} name of the attribute
*/
EditableGrid.prototype.getRowAttribute = function(rowIndex, attributeName)
{
return this.data[rowIndex][attributeName];
};
/**
* Set custom row attribute
* @param {Integer} index of the row
* @param {String} name of the attribute
* @param value of the attribute
*/
EditableGrid.prototype.setRowAttribute = function(rowIndex, attributeName, attributeValue)
{
this.data[rowIndex][attributeName] = attributeValue;
};
/**
* Get Id of row in HTML DOM
* @private
*/
EditableGrid.prototype._getRowDOMId = function(rowId)
{
return this.currentContainerid != null ? this.name + "_" + rowId : rowId;
};
/**
* Remove row with given id
* @param {Integer} rowIndex
*/
EditableGrid.prototype.removeRow = function(rowIndex)
{
// work on unfiltered data
var filterActive = this.dataUnfiltered != null;
if (filterActive) this.data = this.dataUnfiltered;
// delete row from DOM (needed for attach mode)
var tr = _$(this._getRowDOMId(this.data[rowIndex].id));
if (tr != null) this.tBody.removeChild(tr);
// delete row from data
this.data.splice(rowIndex, 1);
if (filterActive) {
// keep only visible rows in data
this.dataUnfiltered = this.data;
this.data = [];
for (var r = 0; r < this.dataUnfiltered.length; r++) if (this.dataUnfiltered[r].visible) this.data.push(this.dataUnfiltered[r]);
}
this.refreshGrid();
};
/**
* Return an associative array (column name => value) of values in row with given index
* @param {Integer} rowIndex
*/
EditableGrid.prototype.getRowValues = function(rowIndex)
{
var rowValues = {};
for (var columnIndex = 0; columnIndex < this.getColumnCount(); columnIndex++) {
rowValues[this.getColumnName(columnIndex)] = this.getValueAt(rowIndex, columnIndex);
}
return rowValues;
};
/**
* Append row with given id and data
* @param {Integer} rowId id of new row
* @param {Integer} columns
* @param {Boolean} dontSort
*/
EditableGrid.prototype.appendRow = function(rowId, cellValues, dontSort)
{
return this.insertRow(rowId, this.data.length, cellValues, dontSort);
};
/**
* Insert row with given id and data at given location
* @param {Integer} rowIndex index of row before which to insert new row
* @param {Integer} rowId id of new row
* @param {Integer} columns
* @param {Boolean} dontSort
*/
EditableGrid.prototype.insertRow = function(rowIndex, rowId, cellValues, dontSort)
{
// work on unfiltered data
var filterActive = this.dataUnfiltered != null;
if (filterActive) this.data = this.dataUnfiltered;
// append row in DOM (needed for attach mode)
if (this.currentContainerid == null) {
var tr = this.tBody.insertRow(rowIndex);
tr.id = this._getRowDOMId(rowId);
for (var c = 0; c < this.columns.length; c++) tr.insertCell(c);
}
// append row in data
var rowData = [];
for (var c = 0; c < this.columns.length; c++) {
var cellValue = this.columns[c].name in cellValues ? cellValues[this.columns[c].name] : "";
rowData.push(this.getTypedValue(c, cellValue));
}
for (var r = 0; r < this.data.length; r++) if (this.data[r].originalIndex >= rowIndex) this.data[r].originalIndex++;
this.data.splice(rowIndex, 0, { visible: true, originalIndex: rowIndex, id: rowId, columns: rowData });
if (filterActive) {
// keep only visible rows in data
this.dataUnfiltered = this.data;
this.data = [];
for (var r = 0; r < this.dataUnfiltered.length; r++) if (this.dataUnfiltered[r].visible) this.data.push(this.dataUnfiltered[r]);
}
this.refreshGrid();
// sort and filter table
if (!dontSort) this.sort();
this.filter();
};
/**
* Sets the column header cell renderer for the specified column index
* @param {Object} columnIndexOrName index or name of the column
* @param {CellRenderer} cellRenderer
*/
EditableGrid.prototype.setHeaderRenderer = function(columnIndexOrName, cellRenderer)
{
var columnIndex = this.getColumnIndex(columnIndexOrName);
if (columnIndex < 0) alert("[setHedareRenderer] Invalid column: " + columnIndexOrName);
else {
var column = this.columns[columnIndex];
column.headerRenderer = (this.enableSort && column.datatype != "html") ? new SortHeaderRenderer(column.name, cellRenderer) : cellRenderer;
// give access to the column from the cell renderer
if (cellRenderer) {
if (this.enableSort && column.datatype != "html") {
column.headerRenderer.editablegrid = this;
column.headerRenderer.column = column;
}
cellRenderer.editablegrid = this;
cellRenderer.column = column;
}
}
};
/**
* Sets the cell renderer for the specified column index
* @param {Object} columnIndexOrName index or name of the column
* @param {CellRenderer} cellRenderer
*/
EditableGrid.prototype.setCellRenderer = function(columnIndexOrName, cellRenderer)
{
var columnIndex = this.getColumnIndex(columnIndexOrName);
if (columnIndex < 0) alert("[setCellRenderer] Invalid column: " + columnIndexOrName);
else {
var column = this.columns[columnIndex];
column.cellRenderer = cellRenderer;
// give access to the column from the cell renderer
if (cellRenderer) {
cellRenderer.editablegrid = this;
cellRenderer.column = column;
}
}
};
/**
* Sets the cell editor for the specified column index
* @param {Object} columnIndexOrName index or name of the column
* @param {CellEditor} cellEditor