Debian Codegraph @

templates/lib/extra/tabulator/tabulator.js

raw
1 /* Tabulator v6.3.1 (c) Oliver Folkerd 2025 */
2 (function (global, factory) {
3 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
4 typeof define === 'function' && define.amd ? define(factory) :
5 (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Tabulator = factory());
6 })(this, (function () { 'use strict';
7
8 var defaultOptions = {
9
10 debugEventsExternal:false, //flag to console log events
11 debugEventsInternal:false, //flag to console log events
12 debugInvalidOptions:true, //allow toggling of invalid option warnings
13 debugInvalidComponentFuncs:true, //allow toggling of invalid component warnings
14 debugInitialization:true, //allow toggling of pre initialization function call warnings
15 debugDeprecation:true, //allow toggling of deprecation warnings
16
17 height:false, //height of tabulator
18 minHeight:false, //minimum height of tabulator
19 maxHeight:false, //maximum height of tabulator
20
21 columnHeaderVertAlign:"top", //vertical alignment of column headers
22
23 popupContainer:false,
24
25 columns:[],//store for colum header info
26 columnDefaults:{}, //store column default props
27 rowHeader:false,
28
29 data:false, //default starting data
30
31 autoColumns:false, //build columns from data row structure
32 autoColumnsDefinitions:false,
33
34 nestedFieldSeparator:".", //separator for nested data
35
36 footerElement:false, //hold footer element
37
38 index:"id", //filed for row index
39
40 textDirection:"auto",
41
42 addRowPos:"bottom", //position to insert blank rows, top|bottom
43
44 headerVisible:true, //hide header
45
46 renderVertical:"virtual",
47 renderHorizontal:"basic",
48 renderVerticalBuffer:0, // set virtual DOM buffer size
49
50 scrollToRowPosition:"top",
51 scrollToRowIfVisible:true,
52
53 scrollToColumnPosition:"left",
54 scrollToColumnIfVisible:true,
55
56 rowFormatter:false,
57 rowFormatterPrint:null,
58 rowFormatterClipboard:null,
59 rowFormatterHtmlOutput:null,
60
61 rowHeight:null,
62
63 placeholder:false,
64
65 dataLoader:true,
66 dataLoaderLoading:false,
67 dataLoaderError:false,
68 dataLoaderErrorTimeout:3000,
69 dataSendParams:{},
70 dataReceiveParams:{},
71
72 dependencies:{},
73 };
74
75 class CoreFeature{
76
77 constructor(table){
78 this.table = table;
79 }
80
81 //////////////////////////////////////////
82 /////////////// DataLoad /////////////////
83 //////////////////////////////////////////
84
85 reloadData(data, silent, columnsChanged){
86 return this.table.dataLoader.load(data, undefined, undefined, undefined, silent, columnsChanged);
87 }
88
89 //////////////////////////////////////////
90 ///////////// Localization ///////////////
91 //////////////////////////////////////////
92
93 langText(){
94 return this.table.modules.localize.getText(...arguments);
95 }
96
97 langBind(){
98 return this.table.modules.localize.bind(...arguments);
99 }
100
101 langLocale(){
102 return this.table.modules.localize.getLocale(...arguments);
103 }
104
105
106 //////////////////////////////////////////
107 ////////// Inter Table Comms /////////////
108 //////////////////////////////////////////
109
110 commsConnections(){
111 return this.table.modules.comms.getConnections(...arguments);
112 }
113
114 commsSend(){
115 return this.table.modules.comms.send(...arguments);
116 }
117
118 //////////////////////////////////////////
119 //////////////// Layout /////////////////
120 //////////////////////////////////////////
121
122 layoutMode(){
123 return this.table.modules.layout.getMode();
124 }
125
126 layoutRefresh(force){
127 return this.table.modules.layout.layout(force);
128 }
129
130
131 //////////////////////////////////////////
132 /////////////// Event Bus ////////////////
133 //////////////////////////////////////////
134
135 subscribe(){
136 return this.table.eventBus.subscribe(...arguments);
137 }
138
139 unsubscribe(){
140 return this.table.eventBus.unsubscribe(...arguments);
141 }
142
143 subscribed(key){
144 return this.table.eventBus.subscribed(key);
145 }
146
147 subscriptionChange(){
148 return this.table.eventBus.subscriptionChange(...arguments);
149 }
150
151 dispatch(){
152 return this.table.eventBus.dispatch(...arguments);
153 }
154
155 chain(){
156 return this.table.eventBus.chain(...arguments);
157 }
158
159 confirm(){
160 return this.table.eventBus.confirm(...arguments);
161 }
162
163 dispatchExternal(){
164 return this.table.externalEvents.dispatch(...arguments);
165 }
166
167 subscribedExternal(key){
168 return this.table.externalEvents.subscribed(key);
169 }
170
171 subscriptionChangeExternal(){
172 return this.table.externalEvents.subscriptionChange(...arguments);
173 }
174
175 //////////////////////////////////////////
176 //////////////// Options /////////////////
177 //////////////////////////////////////////
178
179 options(key){
180 return this.table.options[key];
181 }
182
183 setOption(key, value){
184 if(typeof value !== "undefined"){
185 this.table.options[key] = value;
186 }
187
188 return this.table.options[key];
189 }
190
191 //////////////////////////////////////////
192 /////////// Deprecation Checks ///////////
193 //////////////////////////////////////////
194
195 deprecationCheck(oldOption, newOption, convert){
196 return this.table.deprecationAdvisor.check(oldOption, newOption, convert);
197 }
198
199 deprecationCheckMsg(oldOption, msg){
200 return this.table.deprecationAdvisor.checkMsg(oldOption, msg);
201 }
202
203 deprecationMsg(msg){
204 return this.table.deprecationAdvisor.msg(msg);
205 }
206 //////////////////////////////////////////
207 //////////////// Modules /////////////////
208 //////////////////////////////////////////
209
210 module(key){
211 return this.table.module(key);
212 }
213 }
214
215 //public column object
216 class ColumnComponent {
217 constructor (column){
218 this._column = column;
219 this.type = "ColumnComponent";
220
221 return new Proxy(this, {
222 get: function(target, name, receiver) {
223 if (typeof target[name] !== "undefined") {
224 return target[name];
225 }else {
226 return target._column.table.componentFunctionBinder.handle("column", target._column, name);
227 }
228 }
229 });
230 }
231
232 getElement(){
233 return this._column.getElement();
234 }
235
236 getDefinition(){
237 return this._column.getDefinition();
238 }
239
240 getField(){
241 return this._column.getField();
242 }
243
244 getTitleDownload() {
245 return this._column.getTitleDownload();
246 }
247
248 getCells(){
249 var cells = [];
250
251 this._column.cells.forEach(function(cell){
252 cells.push(cell.getComponent());
253 });
254
255 return cells;
256 }
257
258 isVisible(){
259 return this._column.visible;
260 }
261
262 show(){
263 if(this._column.isGroup){
264 this._column.columns.forEach(function(column){
265 column.show();
266 });
267 }else {
268 this._column.show();
269 }
270 }
271
272 hide(){
273 if(this._column.isGroup){
274 this._column.columns.forEach(function(column){
275 column.hide();
276 });
277 }else {
278 this._column.hide();
279 }
280 }
281
282 toggle(){
283 if(this._column.visible){
284 this.hide();
285 }else {
286 this.show();
287 }
288 }
289
290 delete(){
291 return this._column.delete();
292 }
293
294 getSubColumns(){
295 var output = [];
296
297 if(this._column.columns.length){
298 this._column.columns.forEach(function(column){
299 output.push(column.getComponent());
300 });
301 }
302
303 return output;
304 }
305
306 getParentColumn(){
307 return this._column.getParentComponent();
308 }
309
310 _getSelf(){
311 return this._column;
312 }
313
314 scrollTo(position, ifVisible){
315 return this._column.table.columnManager.scrollToColumn(this._column, position, ifVisible);
316 }
317
318 getTable(){
319 return this._column.table;
320 }
321
322 move(to, after){
323 var toColumn = this._column.table.columnManager.findColumn(to);
324
325 if(toColumn){
326 this._column.table.columnManager.moveColumn(this._column, toColumn, after);
327 }else {
328 console.warn("Move Error - No matching column found:", toColumn);
329 }
330 }
331
332 getNextColumn(){
333 var nextCol = this._column.nextColumn();
334
335 return nextCol ? nextCol.getComponent() : false;
336 }
337
338 getPrevColumn(){
339 var prevCol = this._column.prevColumn();
340
341 return prevCol ? prevCol.getComponent() : false;
342 }
343
344 updateDefinition(updates){
345 return this._column.updateDefinition(updates);
346 }
347
348 getWidth(){
349 return this._column.getWidth();
350 }
351
352 setWidth(width){
353 var result;
354
355 if(width === true){
356 result = this._column.reinitializeWidth(true);
357 }else {
358 result = this._column.setWidth(width);
359 }
360
361 this._column.table.columnManager.rerenderColumns(true);
362
363 return result;
364 }
365 }
366
367 var defaultColumnOptions = {
368 "title": undefined,
369 "field": undefined,
370 "columns": undefined,
371 "visible": undefined,
372 "hozAlign": undefined,
373 "vertAlign": undefined,
374 "width": undefined,
375 "minWidth": 40,
376 "maxWidth": undefined,
377 "maxInitialWidth": undefined,
378 "cssClass": undefined,
379 "variableHeight": undefined,
380 "headerVertical": undefined,
381 "headerHozAlign": undefined,
382 "headerWordWrap": false,
383 "editableTitle": undefined,
384 };
385
386 //public cell object
387 class CellComponent {
388
389 constructor (cell){
390 this._cell = cell;
391
392 return new Proxy(this, {
393 get: function(target, name, receiver) {
394 if (typeof target[name] !== "undefined") {
395 return target[name];
396 }else {
397 return target._cell.table.componentFunctionBinder.handle("cell", target._cell, name);
398 }
399 }
400 });
401 }
402
403 getValue(){
404 return this._cell.getValue();
405 }
406
407 getOldValue(){
408 return this._cell.getOldValue();
409 }
410
411 getInitialValue(){
412 return this._cell.initialValue;
413 }
414
415 getElement(){
416 return this._cell.getElement();
417 }
418
419 getRow(){
420 return this._cell.row.getComponent();
421 }
422
423 getData(transform){
424 return this._cell.row.getData(transform);
425 }
426 getType(){
427 return "cell";
428 }
429 getField(){
430 return this._cell.column.getField();
431 }
432
433 getColumn(){
434 return this._cell.column.getComponent();
435 }
436
437 setValue(value, mutate){
438 if(typeof mutate == "undefined"){
439 mutate = true;
440 }
441
442 this._cell.setValue(value, mutate);
443 }
444
445 restoreOldValue(){
446 this._cell.setValueActual(this._cell.getOldValue());
447 }
448
449 restoreInitialValue(){
450 this._cell.setValueActual(this._cell.initialValue);
451 }
452
453 checkHeight(){
454 this._cell.checkHeight();
455 }
456
457 getTable(){
458 return this._cell.table;
459 }
460
461 _getSelf(){
462 return this._cell;
463 }
464 }
465
466 class Cell extends CoreFeature{
467 constructor(column, row){
468 super(column.table);
469
470 this.table = column.table;
471 this.column = column;
472 this.row = row;
473 this.element = null;
474 this.value = null;
475 this.initialValue;
476 this.oldValue = null;
477 this.modules = {};
478
479 this.height = null;
480 this.width = null;
481 this.minWidth = null;
482
483 this.component = null;
484
485 this.loaded = false; //track if the cell has been added to the DOM yet
486
487 this.build();
488 }
489
490 //////////////// Setup Functions /////////////////
491 //generate element
492 build(){
493 this.generateElement();
494
495 this.setWidth();
496
497 this._configureCell();
498
499 this.setValueActual(this.column.getFieldValue(this.row.data));
500
501 this.initialValue = this.value;
502 }
503
504 generateElement(){
505 this.element = document.createElement('div');
506 this.element.className = "tabulator-cell";
507 this.element.setAttribute("role", "gridcell");
508
509 if(this.column.isRowHeader){
510 this.element.classList.add("tabulator-row-header");
511 }
512 }
513
514 _configureCell(){
515 var element = this.element,
516 field = this.column.getField(),
517 vertAligns = {
518 top:"flex-start",
519 bottom:"flex-end",
520 middle:"center",
521 },
522 hozAligns = {
523 left:"flex-start",
524 right:"flex-end",
525 center:"center",
526 };
527
528 //set text alignment
529 element.style.textAlign = this.column.hozAlign;
530
531 if(this.column.vertAlign){
532 element.style.display = "inline-flex";
533
534 element.style.alignItems = vertAligns[this.column.vertAlign] || "";
535
536 if(this.column.hozAlign){
537 element.style.justifyContent = hozAligns[this.column.hozAlign] || "";
538 }
539 }
540
541 if(field){
542 element.setAttribute("tabulator-field", field);
543 }
544
545 //add class to cell if needed
546 if(this.column.definition.cssClass){
547 var classNames = this.column.definition.cssClass.split(" ");
548 classNames.forEach((className) => {
549 element.classList.add(className);
550 });
551 }
552
553 this.dispatch("cell-init", this);
554
555 //hide cell if not visible
556 if(!this.column.visible){
557 this.hide();
558 }
559 }
560
561 //generate cell contents
562 _generateContents(){
563 var val;
564
565 val = this.chain("cell-format", this, null, () => {
566 return this.element.innerHTML = this.value;
567 });
568
569 switch(typeof val){
570 case "object":
571 if(val instanceof Node){
572
573 //clear previous cell contents
574 while(this.element.firstChild) this.element.removeChild(this.element.firstChild);
575
576 this.element.appendChild(val);
577 }else {
578 this.element.innerHTML = "";
579
580 if(val != null){
581 console.warn("Format Error - Formatter has returned a type of object, the only valid formatter object return is an instance of Node, the formatter returned:", val);
582 }
583 }
584 break;
585 case "undefined":
586 this.element.innerHTML = "";
587 break;
588 default:
589 this.element.innerHTML = val;
590 }
591 }
592
593 cellRendered(){
594 this.dispatch("cell-rendered", this);
595 }
596
597 //////////////////// Getters ////////////////////
598 getElement(containerOnly){
599 if(!this.loaded){
600 this.loaded = true;
601 if(!containerOnly){
602 this.layoutElement();
603 }
604 }
605
606 return this.element;
607 }
608
609 getValue(){
610 return this.value;
611 }
612
613 getOldValue(){
614 return this.oldValue;
615 }
616
617 //////////////////// Actions ////////////////////
618 setValue(value, mutate, force){
619 var changed = this.setValueProcessData(value, mutate, force);
620
621 if(changed){
622 this.dispatch("cell-value-updated", this);
623
624 this.cellRendered();
625
626 if(this.column.definition.cellEdited){
627 this.column.definition.cellEdited.call(this.table, this.getComponent());
628 }
629
630 this.dispatchExternal("cellEdited", this.getComponent());
631
632 if(this.subscribedExternal("dataChanged")){
633 this.dispatchExternal("dataChanged", this.table.rowManager.getData());
634 }
635 }
636 }
637
638 setValueProcessData(value, mutate, force){
639 var changed = false;
640
641 if(this.value !== value || force){
642
643 changed = true;
644
645 if(mutate){
646 value = this.chain("cell-value-changing", [this, value], null, value);
647 }
648 }
649
650 this.setValueActual(value);
651
652 if(changed){
653 this.dispatch("cell-value-changed", this);
654 }
655
656 return changed;
657 }
658
659 setValueActual(value){
660 this.oldValue = this.value;
661
662 this.value = value;
663
664 this.dispatch("cell-value-save-before", this);
665
666 this.column.setFieldValue(this.row.data, value);
667
668 this.dispatch("cell-value-save-after", this);
669
670 if(this.loaded){
671 this.layoutElement();
672 }
673 }
674
675 layoutElement(){
676 this._generateContents();
677
678 this.dispatch("cell-layout", this);
679 }
680
681 setWidth(){
682 this.width = this.column.width;
683 this.element.style.width = this.column.widthStyled;
684 }
685
686 clearWidth(){
687 this.width = "";
688 this.element.style.width = "";
689 }
690
691 getWidth(){
692 return this.width || this.element.offsetWidth;
693 }
694
695 setMinWidth(){
696 this.minWidth = this.column.minWidth;
697 this.element.style.minWidth = this.column.minWidthStyled;
698 }
699
700 setMaxWidth(){
701 this.maxWidth = this.column.maxWidth;
702 this.element.style.maxWidth = this.column.maxWidthStyled;
703 }
704
705 checkHeight(){
706 // var height = this.element.css("height");
707 this.row.reinitializeHeight();
708 }
709
710 clearHeight(){
711 this.element.style.height = "";
712 this.height = null;
713
714 this.dispatch("cell-height", this, "");
715 }
716
717 setHeight(){
718 this.height = this.row.height;
719 this.element.style.height = this.row.heightStyled;
720
721 this.dispatch("cell-height", this, this.row.heightStyled);
722 }
723
724 getHeight(){
725 return this.height || this.element.offsetHeight;
726 }
727
728 show(){
729 this.element.style.display = this.column.vertAlign ? "inline-flex" : "";
730 }
731
732 hide(){
733 this.element.style.display = "none";
734 }
735
736 delete(){
737 this.dispatch("cell-delete", this);
738
739 if(!this.table.rowManager.redrawBlock && this.element.parentNode){
740 this.element.parentNode.removeChild(this.element);
741 }
742
743 this.element = false;
744 this.column.deleteCell(this);
745 this.row.deleteCell(this);
746 this.calcs = {};
747 }
748
749 getIndex(){
750 return this.row.getCellIndex(this);
751 }
752
753 //////////////// Object Generation /////////////////
754 getComponent(){
755 if(!this.component){
756 this.component = new CellComponent(this);
757 }
758
759 return this.component;
760 }
761 }
762
763 class Column extends CoreFeature{
764
765 static defaultOptionList = defaultColumnOptions;
766
767 constructor(def, parent, rowHeader){
768 super(parent.table);
769
770 this.definition = def; //column definition
771 this.parent = parent; //hold parent object
772 this.type = "column"; //type of element
773 this.columns = []; //child columns
774 this.cells = []; //cells bound to this column
775 this.isGroup = false;
776 this.isRowHeader = rowHeader;
777 this.element = this.createElement(); //column header element
778 this.contentElement = false;
779 this.titleHolderElement = false;
780 this.titleElement = false;
781 this.groupElement = this.createGroupElement(); //column group holder element
782 this.hozAlign = ""; //horizontal text alignment
783 this.vertAlign = ""; //vert text alignment
784
785 //multi dimensional filed handling
786 this.field ="";
787 this.fieldStructure = "";
788 this.getFieldValue = "";
789 this.setFieldValue = "";
790
791 this.titleDownload = null;
792 this.titleFormatterRendered = false;
793
794 this.mapDefinitions();
795
796 this.setField(this.definition.field);
797
798 this.modules = {}; //hold module variables;
799
800 this.width = null; //column width
801 this.widthStyled = ""; //column width pre-styled to improve render efficiency
802 this.maxWidth = null; //column maximum width
803 this.maxWidthStyled = ""; //column maximum pre-styled to improve render efficiency
804 this.maxInitialWidth = null;
805 this.minWidth = null; //column minimum width
806 this.minWidthStyled = ""; //column minimum pre-styled to improve render efficiency
807 this.widthFixed = false; //user has specified a width for this column
808
809 this.visible = true; //default visible state
810
811 this.component = null;
812
813 //initialize column
814 if(this.definition.columns){
815
816 this.isGroup = true;
817
818 this.definition.columns.forEach((def, i) => {
819 var newCol = new Column(def, this);
820 this.attachColumn(newCol);
821 });
822
823 this.checkColumnVisibility();
824 }else {
825 parent.registerColumnField(this);
826 }
827
828 this._initialize();
829 }
830
831 createElement (){
832 var el = document.createElement("div");
833
834 el.classList.add("tabulator-col");
835 el.setAttribute("role", "columnheader");
836 el.setAttribute("aria-sort", "none");
837
838 if(this.isRowHeader){
839 el.classList.add("tabulator-row-header");
840 }
841
842 switch(this.table.options.columnHeaderVertAlign){
843 case "middle":
844 el.style.justifyContent = "center";
845 break;
846 case "bottom":
847 el.style.justifyContent = "flex-end";
848 break;
849 }
850
851 return el;
852 }
853
854 createGroupElement (){
855 var el = document.createElement("div");
856
857 el.classList.add("tabulator-col-group-cols");
858
859 return el;
860 }
861
862 mapDefinitions(){
863 var defaults = this.table.options.columnDefaults;
864
865 //map columnDefaults onto column definitions
866 if(defaults){
867 for(let key in defaults){
868 if(typeof this.definition[key] === "undefined"){
869 this.definition[key] = defaults[key];
870 }
871 }
872 }
873
874 this.definition = this.table.columnManager.optionsList.generate(Column.defaultOptionList, this.definition);
875 }
876
877 checkDefinition(){
878 Object.keys(this.definition).forEach((key) => {
879 if(Column.defaultOptionList.indexOf(key) === -1){
880 console.warn("Invalid column definition option in '" + (this.field || this.definition.title) + "' column:", key);
881 }
882 });
883 }
884
885 setField(field){
886 this.field = field;
887 this.fieldStructure = field ? (this.table.options.nestedFieldSeparator ? field.split(this.table.options.nestedFieldSeparator) : [field]) : [];
888 this.getFieldValue = this.fieldStructure.length > 1 ? this._getNestedData : this._getFlatData;
889 this.setFieldValue = this.fieldStructure.length > 1 ? this._setNestedData : this._setFlatData;
890 }
891
892 //register column position with column manager
893 registerColumnPosition(column){
894 this.parent.registerColumnPosition(column);
895 }
896
897 //register column position with column manager
898 registerColumnField(column){
899 this.parent.registerColumnField(column);
900 }
901
902 //trigger position registration
903 reRegisterPosition(){
904 if(this.isGroup){
905 this.columns.forEach(function(column){
906 column.reRegisterPosition();
907 });
908 }else {
909 this.registerColumnPosition(this);
910 }
911 }
912
913 //build header element
914 _initialize(){
915 var def = this.definition;
916
917 while(this.element.firstChild) this.element.removeChild(this.element.firstChild);
918
919 if(def.headerVertical){
920 this.element.classList.add("tabulator-col-vertical");
921
922 if(def.headerVertical === "flip"){
923 this.element.classList.add("tabulator-col-vertical-flip");
924 }
925 }
926
927 this.contentElement = this._buildColumnHeaderContent();
928
929 this.element.appendChild(this.contentElement);
930
931 if(this.isGroup){
932 this._buildGroupHeader();
933 }else {
934 this._buildColumnHeader();
935 }
936
937 this.dispatch("column-init", this);
938 }
939
940 //build header element for header
941 _buildColumnHeader(){
942 var def = this.definition;
943
944 this.dispatch("column-layout", this);
945
946 //set column visibility
947 if(typeof def.visible != "undefined"){
948 if(def.visible){
949 this.show(true);
950 }else {
951 this.hide(true);
952 }
953 }
954
955 //assign additional css classes to column header
956 if(def.cssClass){
957 var classNames = def.cssClass.split(" ");
958 classNames.forEach((className) => {
959 this.element.classList.add(className);
960 });
961 }
962
963 if(def.field){
964 this.element.setAttribute("tabulator-field", def.field);
965 }
966
967 //set min width if present
968 this.setMinWidth(parseInt(def.minWidth));
969
970 if (def.maxInitialWidth) {
971 this.maxInitialWidth = parseInt(def.maxInitialWidth);
972 }
973
974 if(def.maxWidth){
975 this.setMaxWidth(parseInt(def.maxWidth));
976 }
977
978 this.reinitializeWidth();
979
980 //set horizontal text alignment
981 this.hozAlign = this.definition.hozAlign;
982 this.vertAlign = this.definition.vertAlign;
983
984 this.titleElement.style.textAlign = this.definition.headerHozAlign;
985 }
986
987 _buildColumnHeaderContent(){
988 var contentElement = document.createElement("div");
989 contentElement.classList.add("tabulator-col-content");
990
991 this.titleHolderElement = document.createElement("div");
992 this.titleHolderElement.classList.add("tabulator-col-title-holder");
993
994 contentElement.appendChild(this.titleHolderElement);
995
996 this.titleElement = this._buildColumnHeaderTitle();
997
998 this.titleHolderElement.appendChild(this.titleElement);
999
1000 return contentElement;
1001 }
1002
1003 //build title element of column
1004 _buildColumnHeaderTitle(){
1005 var def = this.definition;
1006
1007 var titleHolderElement = document.createElement("div");
1008 titleHolderElement.classList.add("tabulator-col-title");
1009
1010 if(def.headerWordWrap){
1011 titleHolderElement.classList.add("tabulator-col-title-wrap");
1012 }
1013
1014 if(def.editableTitle){
1015 var titleElement = document.createElement("input");
1016 titleElement.classList.add("tabulator-title-editor");
1017
1018 titleElement.addEventListener("click", (e) => {
1019 e.stopPropagation();
1020 titleElement.focus();
1021 });
1022
1023 titleElement.addEventListener("mousedown", (e) => {
1024 e.stopPropagation();
1025 });
1026
1027 titleElement.addEventListener("change", () => {
1028 def.title = titleElement.value;
1029 this.dispatchExternal("columnTitleChanged", this.getComponent());
1030 });
1031
1032 titleHolderElement.appendChild(titleElement);
1033
1034 if(def.field){
1035 this.langBind("columns|" + def.field, (text) => {
1036 titleElement.value = text || (def.title || " ");
1037 });
1038 }else {
1039 titleElement.value = def.title || " ";
1040 }
1041
1042 }else {
1043 if(def.field){
1044 this.langBind("columns|" + def.field, (text) => {
1045 this._formatColumnHeaderTitle(titleHolderElement, text || (def.title || " "));
1046 });
1047 }else {
1048 this._formatColumnHeaderTitle(titleHolderElement, def.title || " ");
1049 }
1050 }
1051
1052 return titleHolderElement;
1053 }
1054
1055 _formatColumnHeaderTitle(el, title){
1056 var contents = this.chain("column-format", [this, title, el], null, () => {
1057 return title;
1058 });
1059
1060 switch(typeof contents){
1061 case "object":
1062 if(contents instanceof Node){
1063 el.appendChild(contents);
1064 }else {
1065 el.innerHTML = "";
1066 console.warn("Format Error - Title formatter has returned a type of object, the only valid formatter object return is an instance of Node, the formatter returned:", contents);
1067 }
1068 break;
1069 case "undefined":
1070 el.innerHTML = "";
1071 break;
1072 default:
1073 el.innerHTML = contents;
1074 }
1075 }
1076
1077 //build header element for column group
1078 _buildGroupHeader(){
1079 this.element.classList.add("tabulator-col-group");
1080 this.element.setAttribute("role", "columngroup");
1081 this.element.setAttribute("aria-title", this.definition.title);
1082
1083 //asign additional css classes to column header
1084 if(this.definition.cssClass){
1085 var classNames = this.definition.cssClass.split(" ");
1086 classNames.forEach((className) => {
1087 this.element.classList.add(className);
1088 });
1089 }
1090
1091 this.titleElement.style.textAlign = this.definition.headerHozAlign;
1092
1093 this.element.appendChild(this.groupElement);
1094 }
1095
1096 //flat field lookup
1097 _getFlatData(data){
1098 return data[this.field];
1099 }
1100
1101 //nested field lookup
1102 _getNestedData(data){
1103 var dataObj = data,
1104 structure = this.fieldStructure,
1105 length = structure.length,
1106 output;
1107
1108 for(let i = 0; i < length; i++){
1109
1110 dataObj = dataObj[structure[i]];
1111
1112 output = dataObj;
1113
1114 if(!dataObj){
1115 break;
1116 }
1117 }
1118
1119 return output;
1120 }
1121
1122 //flat field set
1123 _setFlatData(data, value){
1124 if(this.field){
1125 data[this.field] = value;
1126 }
1127 }
1128
1129 //nested field set
1130 _setNestedData(data, value){
1131 var dataObj = data,
1132 structure = this.fieldStructure,
1133 length = structure.length;
1134
1135 for(let i = 0; i < length; i++){
1136
1137 if(i == length -1){
1138 dataObj[structure[i]] = value;
1139 }else {
1140 if(!dataObj[structure[i]]){
1141 if(typeof value !== "undefined"){
1142 dataObj[structure[i]] = {};
1143 }else {
1144 break;
1145 }
1146 }
1147
1148 dataObj = dataObj[structure[i]];
1149 }
1150 }
1151 }
1152
1153 //attach column to this group
1154 attachColumn(column){
1155 if(this.groupElement){
1156 this.columns.push(column);
1157 this.groupElement.appendChild(column.getElement());
1158
1159 column.columnRendered();
1160 }else {
1161 console.warn("Column Warning - Column being attached to another column instead of column group");
1162 }
1163 }
1164
1165 //vertically align header in column
1166 verticalAlign(alignment, height){
1167
1168 //calculate height of column header and group holder element
1169 var parentHeight = this.parent.isGroup ? this.parent.getGroupElement().clientHeight : (height || this.parent.getHeadersElement().clientHeight);
1170 // var parentHeight = this.parent.isGroup ? this.parent.getGroupElement().clientHeight : this.parent.getHeadersElement().clientHeight;
1171
1172 this.element.style.height = parentHeight + "px";
1173
1174 this.dispatch("column-height", this, this.element.style.height);
1175
1176 if(this.isGroup){
1177 this.groupElement.style.minHeight = (parentHeight - this.contentElement.offsetHeight) + "px";
1178 }
1179
1180 //vertically align cell contents
1181 // if(!this.isGroup && alignment !== "top"){
1182 // if(alignment === "bottom"){
1183 // this.element.style.paddingTop = (this.element.clientHeight - this.contentElement.offsetHeight) + "px";
1184 // }else{
1185 // this.element.style.paddingTop = ((this.element.clientHeight - this.contentElement.offsetHeight) / 2) + "px";
1186 // }
1187 // }
1188
1189 this.columns.forEach(function(column){
1190 column.verticalAlign(alignment);
1191 });
1192 }
1193
1194 //clear vertical alignment
1195 clearVerticalAlign(){
1196 this.element.style.paddingTop = "";
1197 this.element.style.height = "";
1198 this.element.style.minHeight = "";
1199 this.groupElement.style.minHeight = "";
1200
1201 this.columns.forEach(function(column){
1202 column.clearVerticalAlign();
1203 });
1204
1205 this.dispatch("column-height", this, "");
1206 }
1207
1208 //// Retrieve Column Information ////
1209 //return column header element
1210 getElement(){
1211 return this.element;
1212 }
1213
1214 //return column group element
1215 getGroupElement(){
1216 return this.groupElement;
1217 }
1218
1219 //return field name
1220 getField(){
1221 return this.field;
1222 }
1223
1224 getTitleDownload() {
1225 return this.titleDownload;
1226 }
1227
1228 //return the first column in a group
1229 getFirstColumn(){
1230 if(!this.isGroup){
1231 return this;
1232 }else {
1233 if(this.columns.length){
1234 return this.columns[0].getFirstColumn();
1235 }else {
1236 return false;
1237 }
1238 }
1239 }
1240
1241 //return the last column in a group
1242 getLastColumn(){
1243 if(!this.isGroup){
1244 return this;
1245 }else {
1246 if(this.columns.length){
1247 return this.columns[this.columns.length -1].getLastColumn();
1248 }else {
1249 return false;
1250 }
1251 }
1252 }
1253
1254 //return all columns in a group
1255 getColumns(traverse){
1256 var columns = [];
1257
1258 if(traverse){
1259 this.columns.forEach((column) => {
1260 columns.push(column);
1261
1262 columns = columns.concat(column.getColumns(true));
1263 });
1264 }else {
1265 columns = this.columns;
1266 }
1267
1268 return columns;
1269 }
1270
1271 //return all columns in a group
1272 getCells(){
1273 return this.cells;
1274 }
1275
1276 //retrieve the top column in a group of columns
1277 getTopColumn(){
1278 if(this.parent.isGroup){
1279 return this.parent.getTopColumn();
1280 }else {
1281 return this;
1282 }
1283 }
1284
1285 //return column definition object
1286 getDefinition(updateBranches){
1287 var colDefs = [];
1288
1289 if(this.isGroup && updateBranches){
1290 this.columns.forEach(function(column){
1291 colDefs.push(column.getDefinition(true));
1292 });
1293
1294 this.definition.columns = colDefs;
1295 }
1296
1297 return this.definition;
1298 }
1299
1300 //////////////////// Actions ////////////////////
1301 checkColumnVisibility(){
1302 var visible = false;
1303
1304 this.columns.forEach(function(column){
1305 if(column.visible){
1306 visible = true;
1307 }
1308 });
1309
1310 if(visible){
1311 this.show();
1312 this.dispatchExternal("columnVisibilityChanged", this.getComponent(), false);
1313 }else {
1314 this.hide();
1315 }
1316 }
1317
1318 //show column
1319 show(silent, responsiveToggle){
1320 if(!this.visible){
1321 this.visible = true;
1322
1323 this.element.style.display = "";
1324
1325 if(this.parent.isGroup){
1326 this.parent.checkColumnVisibility();
1327 }
1328
1329 this.cells.forEach(function(cell){
1330 cell.show();
1331 });
1332
1333 if(!this.isGroup && this.width === null){
1334 this.reinitializeWidth();
1335 }
1336
1337 this.table.columnManager.verticalAlignHeaders();
1338
1339 this.dispatch("column-show", this, responsiveToggle);
1340
1341 if(!silent){
1342 this.dispatchExternal("columnVisibilityChanged", this.getComponent(), true);
1343 }
1344
1345 if(this.parent.isGroup){
1346 this.parent.matchChildWidths();
1347 }
1348
1349 if(!this.silent){
1350 this.table.columnManager.rerenderColumns();
1351 }
1352 }
1353 }
1354
1355 //hide column
1356 hide(silent, responsiveToggle){
1357 if(this.visible){
1358 this.visible = false;
1359
1360 this.element.style.display = "none";
1361
1362 this.table.columnManager.verticalAlignHeaders();
1363
1364 if(this.parent.isGroup){
1365 this.parent.checkColumnVisibility();
1366 }
1367
1368 this.cells.forEach(function(cell){
1369 cell.hide();
1370 });
1371
1372 this.dispatch("column-hide", this, responsiveToggle);
1373
1374 if(!silent){
1375 this.dispatchExternal("columnVisibilityChanged", this.getComponent(), false);
1376 }
1377
1378 if(this.parent.isGroup){
1379 this.parent.matchChildWidths();
1380 }
1381
1382 if(!this.silent){
1383 this.table.columnManager.rerenderColumns();
1384 }
1385 }
1386 }
1387
1388 matchChildWidths(){
1389 var childWidth = 0;
1390
1391 if(this.contentElement && this.columns.length){
1392 this.columns.forEach(function(column){
1393 if(column.visible){
1394 childWidth += column.getWidth();
1395 }
1396 });
1397
1398 this.contentElement.style.maxWidth = (childWidth - 1) + "px";
1399 if (this.table.initialized) {
1400 this.element.style.width = childWidth + "px";
1401 }
1402
1403 if(this.parent.isGroup){
1404 this.parent.matchChildWidths();
1405 }
1406 }
1407 }
1408
1409 removeChild(child){
1410 var index = this.columns.indexOf(child);
1411
1412 if(index > -1){
1413 this.columns.splice(index, 1);
1414 }
1415
1416 if(!this.columns.length){
1417 this.delete();
1418 }
1419 }
1420
1421 setWidth(width){
1422 this.widthFixed = true;
1423 this.setWidthActual(width);
1424 }
1425
1426 setWidthActual(width){
1427 if(isNaN(width)){
1428 width = Math.floor((this.table.element.clientWidth/100) * parseInt(width));
1429 }
1430
1431 width = Math.max(this.minWidth, width);
1432
1433 if(this.maxWidth){
1434 width = Math.min(this.maxWidth, width);
1435 }
1436
1437 this.width = width;
1438 this.widthStyled = width ? width + "px" : "";
1439
1440 this.element.style.width = this.widthStyled;
1441
1442 if(!this.isGroup){
1443 this.cells.forEach(function(cell){
1444 cell.setWidth();
1445 });
1446 }
1447
1448 if(this.parent.isGroup){
1449 this.parent.matchChildWidths();
1450 }
1451
1452 this.dispatch("column-width", this);
1453
1454 if(this.subscribedExternal("columnWidth")){
1455 this.dispatchExternal("columnWidth", this.getComponent());
1456 }
1457 }
1458
1459 checkCellHeights(){
1460 var rows = [];
1461
1462 this.cells.forEach(function(cell){
1463 if(cell.row.heightInitialized){
1464 if(cell.row.getElement().offsetParent !== null){
1465 rows.push(cell.row);
1466 cell.row.clearCellHeight();
1467 }else {
1468 cell.row.heightInitialized = false;
1469 }
1470 }
1471 });
1472
1473 rows.forEach(function(row){
1474 row.calcHeight();
1475 });
1476
1477 rows.forEach(function(row){
1478 row.setCellHeight();
1479 });
1480 }
1481
1482 getWidth(){
1483 var width = 0;
1484
1485 if(this.isGroup){
1486 this.columns.forEach(function(column){
1487 if(column.visible){
1488 width += column.getWidth();
1489 }
1490 });
1491 }else {
1492 width = this.width;
1493 }
1494
1495 return width;
1496 }
1497
1498 getLeftOffset(){
1499 var offset = this.element.offsetLeft;
1500
1501 if(this.parent.isGroup){
1502 offset += this.parent.getLeftOffset();
1503 }
1504
1505 return offset;
1506 }
1507
1508 getHeight(){
1509 return Math.ceil(this.element.getBoundingClientRect().height);
1510 }
1511
1512 setMinWidth(minWidth){
1513 if(this.maxWidth && minWidth > this.maxWidth){
1514 minWidth = this.maxWidth;
1515
1516 console.warn("the minWidth ("+ minWidth + "px) for column '" + this.field + "' cannot be bigger that its maxWidth ("+ this.maxWidthStyled + ")");
1517 }
1518
1519 this.minWidth = minWidth;
1520 this.minWidthStyled = minWidth ? minWidth + "px" : "";
1521
1522 this.element.style.minWidth = this.minWidthStyled;
1523
1524 this.cells.forEach(function(cell){
1525 cell.setMinWidth();
1526 });
1527 }
1528
1529 setMaxWidth(maxWidth){
1530 if(this.minWidth && maxWidth < this.minWidth){
1531 maxWidth = this.minWidth;
1532
1533 console.warn("the maxWidth ("+ maxWidth + "px) for column '" + this.field + "' cannot be smaller that its minWidth ("+ this.minWidthStyled + ")");
1534 }
1535
1536 this.maxWidth = maxWidth;
1537 this.maxWidthStyled = maxWidth ? maxWidth + "px" : "";
1538
1539 this.element.style.maxWidth = this.maxWidthStyled;
1540
1541 this.cells.forEach(function(cell){
1542 cell.setMaxWidth();
1543 });
1544 }
1545
1546 delete(){
1547 return new Promise((resolve, reject) => {
1548 if(this.isGroup){
1549 this.columns.forEach(function(column){
1550 column.delete();
1551 });
1552 }
1553
1554 this.dispatch("column-delete", this);
1555
1556 var cellCount = this.cells.length;
1557
1558 for(let i = 0; i < cellCount; i++){
1559 this.cells[0].delete();
1560 }
1561
1562 if(this.element.parentNode){
1563 this.element.parentNode.removeChild(this.element);
1564 }
1565
1566 this.element = false;
1567 this.contentElement = false;
1568 this.titleElement = false;
1569 this.groupElement = false;
1570
1571 if(this.parent.isGroup){
1572 this.parent.removeChild(this);
1573 }
1574
1575 this.table.columnManager.deregisterColumn(this);
1576
1577 this.table.columnManager.rerenderColumns(true);
1578
1579 this.dispatch("column-deleted", this);
1580
1581 resolve();
1582 });
1583 }
1584
1585 columnRendered(){
1586 if(this.titleFormatterRendered){
1587 this.titleFormatterRendered();
1588 }
1589
1590 this.dispatch("column-rendered", this);
1591 }
1592
1593 //////////////// Cell Management /////////////////
1594 //generate cell for this column
1595 generateCell(row){
1596 var cell = new Cell(this, row);
1597
1598 this.cells.push(cell);
1599
1600 return cell;
1601 }
1602
1603 nextColumn(){
1604 var index = this.table.columnManager.findColumnIndex(this);
1605 return index > -1 ? this._nextVisibleColumn(index + 1) : false;
1606 }
1607
1608 _nextVisibleColumn(index){
1609 var column = this.table.columnManager.getColumnByIndex(index);
1610 return !column || column.visible ? column : this._nextVisibleColumn(index + 1);
1611 }
1612
1613 prevColumn(){
1614 var index = this.table.columnManager.findColumnIndex(this);
1615 return index > -1 ? this._prevVisibleColumn(index - 1) : false;
1616 }
1617
1618 _prevVisibleColumn(index){
1619 var column = this.table.columnManager.getColumnByIndex(index);
1620 return !column || column.visible ? column : this._prevVisibleColumn(index - 1);
1621 }
1622
1623 reinitializeWidth(force){
1624 this.widthFixed = false;
1625
1626 //set width if present
1627 if(typeof this.definition.width !== "undefined" && !force){
1628 // maxInitialWidth ignored here as width specified
1629 this.setWidth(this.definition.width);
1630 }
1631
1632 this.dispatch("column-width-fit-before", this);
1633
1634 this.fitToData(force);
1635
1636 this.dispatch("column-width-fit-after", this);
1637 }
1638
1639 //set column width to maximum cell width for non group columns
1640 fitToData(force){
1641 if(this.isGroup){
1642 return;
1643 }
1644
1645 if(!this.widthFixed){
1646 this.element.style.width = "";
1647
1648 this.cells.forEach((cell) => {
1649 cell.clearWidth();
1650 });
1651 }
1652
1653 var maxWidth = this.element.offsetWidth;
1654
1655 if(!this.width || !this.widthFixed){
1656 this.cells.forEach((cell) => {
1657 var width = cell.getWidth();
1658
1659 if(width > maxWidth){
1660 maxWidth = width;
1661 }
1662 });
1663
1664 if(maxWidth){
1665 var setTo = maxWidth + 1;
1666
1667 if(force){
1668 this.setWidth(setTo);
1669 }else {
1670 if (this.maxInitialWidth && !force) {
1671 setTo = Math.min(setTo, this.maxInitialWidth);
1672 }
1673 this.setWidthActual(setTo);
1674 }
1675 }
1676 }
1677 }
1678
1679 updateDefinition(updates){
1680 var definition;
1681
1682 if(!this.isGroup){
1683 if(!this.parent.isGroup){
1684 definition = Object.assign({}, this.getDefinition());
1685 definition = Object.assign(definition, updates);
1686
1687 return this.table.columnManager.addColumn(definition, false, this)
1688 .then((column) => {
1689
1690 if(definition.field == this.field){
1691 this.field = false; //clear field name to prevent deletion of duplicate column from arrays
1692 }
1693
1694 return this.delete()
1695 .then(() => {
1696 return column.getComponent();
1697 });
1698
1699 });
1700 }else {
1701 console.error("Column Update Error - The updateDefinition function is only available on ungrouped columns");
1702 return Promise.reject("Column Update Error - The updateDefinition function is only available on columns, not column groups");
1703 }
1704 }else {
1705 console.error("Column Update Error - The updateDefinition function is only available on ungrouped columns");
1706 return Promise.reject("Column Update Error - The updateDefinition function is only available on columns, not column groups");
1707 }
1708 }
1709
1710 deleteCell(cell){
1711 var index = this.cells.indexOf(cell);
1712
1713 if(index > -1){
1714 this.cells.splice(index, 1);
1715 }
1716 }
1717
1718 //////////////// Object Generation /////////////////
1719 getComponent(){
1720 if(!this.component){
1721 this.component = new ColumnComponent(this);
1722 }
1723
1724 return this.component;
1725 }
1726
1727 getPosition(){
1728 return this.table.columnManager.getVisibleColumnsByIndex().indexOf(this) + 1;
1729 }
1730
1731 getParentComponent(){
1732 return this.parent instanceof Column ? this.parent.getComponent() : false;
1733 }
1734 }
1735
1736 class Helpers{
1737
1738 static elVisible(el){
1739 return !(el.offsetWidth <= 0 && el.offsetHeight <= 0);
1740 }
1741
1742 static elOffset(el){
1743 var box = el.getBoundingClientRect();
1744
1745 return {
1746 top: box.top + window.pageYOffset - document.documentElement.clientTop,
1747 left: box.left + window.pageXOffset - document.documentElement.clientLeft
1748 };
1749 }
1750
1751 static retrieveNestedData(separator, field, data){
1752 var structure = separator ? field.split(separator) : [field],
1753 length = structure.length,
1754 output;
1755
1756 for(let i = 0; i < length; i++){
1757
1758 data = data[structure[i]];
1759
1760 output = data;
1761
1762 if(!data){
1763 break;
1764 }
1765 }
1766
1767 return output;
1768 }
1769
1770 static deepClone(obj, clone, list = []){
1771 var objectProto = {}.__proto__,
1772 arrayProto = [].__proto__;
1773
1774 if (!clone){
1775 clone = Object.assign(Array.isArray(obj) ? [] : {}, obj);
1776 }
1777
1778 for(var i in obj) {
1779 let subject = obj[i],
1780 match, copy;
1781
1782 if(subject != null && typeof subject === "object" && (subject.__proto__ === objectProto || subject.__proto__ === arrayProto)){
1783 match = list.findIndex((item) => {
1784 return item.subject === subject;
1785 });
1786
1787 if(match > -1){
1788 clone[i] = list[match].copy;
1789 }else {
1790 copy = Object.assign(Array.isArray(subject) ? [] : {}, subject);
1791
1792 list.unshift({subject, copy});
1793
1794 clone[i] = this.deepClone(subject, copy, list);
1795 }
1796 }
1797 }
1798
1799 return clone;
1800 }
1801 }
1802
1803 class OptionsList {
1804 constructor(table, msgType, defaults = {}){
1805 this.table = table;
1806 this.msgType = msgType;
1807 this.registeredDefaults = Object.assign({}, defaults);
1808 }
1809
1810 register(option, value){
1811 this.registeredDefaults[option] = value;
1812 }
1813
1814 generate(defaultOptions, userOptions = {}){
1815 var output = Object.assign({}, this.registeredDefaults),
1816 warn = this.table.options.debugInvalidOptions || userOptions.debugInvalidOptions === true;
1817
1818 Object.assign(output, defaultOptions);
1819
1820 for (let key in userOptions){
1821 if(!output.hasOwnProperty(key)){
1822 if(warn){
1823 console.warn("Invalid " + this.msgType + " option:", key);
1824 }
1825
1826 output[key] = userOptions.key;
1827 }
1828 }
1829
1830
1831 for (let key in output){
1832 if(key in userOptions){
1833 output[key] = userOptions[key];
1834 }else {
1835 if(Array.isArray(output[key])){
1836 output[key] = Object.assign([], output[key]);
1837 }else if(typeof output[key] === "object" && output[key] !== null){
1838 output[key] = Object.assign({}, output[key]);
1839 }else if (typeof output[key] === "undefined"){
1840 delete output[key];
1841 }
1842 }
1843 }
1844
1845 return output;
1846 }
1847 }
1848
1849 class Renderer extends CoreFeature{
1850 constructor(table){
1851 super(table);
1852
1853 this.elementVertical = table.rowManager.element;
1854 this.elementHorizontal = table.columnManager.element;
1855 this.tableElement = table.rowManager.tableElement;
1856
1857 this.verticalFillMode = "fit"; // used by row manager to determine how to size the render area ("fit" - fits container to the contents, "fill" - fills the container without resizing it)
1858 }
1859
1860
1861 ///////////////////////////////////
1862 /////// Internal Bindings /////////
1863 ///////////////////////////////////
1864
1865 initialize(){
1866 //initialize core functionality
1867 }
1868
1869 clearRows(){
1870 //clear down existing rows layout
1871 }
1872
1873 clearColumns(){
1874 //clear down existing columns layout
1875 }
1876
1877
1878 reinitializeColumnWidths(columns){
1879 //resize columns to fit data
1880 }
1881
1882
1883 renderRows(){
1884 //render rows from a clean slate
1885 }
1886
1887 renderColumns(){
1888 //render columns from a clean slate
1889 }
1890
1891 rerenderRows(callback){
1892 // rerender rows and keep position
1893 if(callback){
1894 callback();
1895 }
1896 }
1897
1898 rerenderColumns(update, blockRedraw){
1899 //rerender columns
1900 }
1901
1902 renderRowCells(row){
1903 //render the cells in a row
1904 }
1905
1906 rerenderRowCells(row, force){
1907 //rerender the cells in a row
1908 }
1909
1910 scrollColumns(left, dir){
1911 //handle horizontal scrolling
1912 }
1913
1914 scrollRows(top, dir){
1915 //handle vertical scrolling
1916 }
1917
1918 resize(){
1919 //container has resized, carry out any needed recalculations (DO NOT RERENDER IN THIS FUNCTION)
1920 }
1921
1922 scrollToRow(row){
1923 //scroll to a specific row
1924 }
1925
1926 scrollToRowNearestTop(row){
1927 //determine weather the row is nearest the top or bottom of the table, return true for top or false for bottom
1928 }
1929
1930 visibleRows(includingBuffer){
1931 //return the visible rows
1932 return [];
1933 }
1934
1935 ///////////////////////////////////
1936 //////// Helper Functions /////////
1937 ///////////////////////////////////
1938
1939 rows(){
1940 return this.table.rowManager.getDisplayRows();
1941 }
1942
1943 styleRow(row, index){
1944 var rowEl = row.getElement();
1945
1946 if(index % 2){
1947 rowEl.classList.add("tabulator-row-even");
1948 rowEl.classList.remove("tabulator-row-odd");
1949 }else {
1950 rowEl.classList.add("tabulator-row-odd");
1951 rowEl.classList.remove("tabulator-row-even");
1952 }
1953 }
1954
1955 ///////////////////////////////////
1956 /////// External Triggers /////////
1957 /////// (DO NOT OVERRIDE) /////////
1958 ///////////////////////////////////
1959
1960 clear(){
1961 //clear down existing layout
1962 this.clearRows();
1963 this.clearColumns();
1964 }
1965
1966 render(){
1967 //render from a clean slate
1968 this.renderRows();
1969 this.renderColumns();
1970 }
1971
1972 rerender(callback){
1973 // rerender and keep position
1974 this.rerenderRows();
1975 this.rerenderColumns();
1976 }
1977
1978 scrollToRowPosition(row, position, ifVisible){
1979 var rowIndex = this.rows().indexOf(row),
1980 rowEl = row.getElement(),
1981 offset = 0;
1982
1983 return new Promise((resolve, reject) => {
1984 if(rowIndex > -1){
1985
1986 if(typeof ifVisible === "undefined"){
1987 ifVisible = this.table.options.scrollToRowIfVisible;
1988 }
1989
1990 //check row visibility
1991 if(!ifVisible){
1992 if(Helpers.elVisible(rowEl)){
1993 offset = Helpers.elOffset(rowEl).top - Helpers.elOffset(this.elementVertical).top;
1994
1995 if(offset > 0 && offset < this.elementVertical.clientHeight - rowEl.offsetHeight){
1996 resolve();
1997 return false;
1998 }
1999 }
2000 }
2001
2002 if(typeof position === "undefined"){
2003 position = this.table.options.scrollToRowPosition;
2004 }
2005
2006 if(position === "nearest"){
2007 position = this.scrollToRowNearestTop(row) ? "top" : "bottom";
2008 }
2009
2010 //scroll to row
2011 this.scrollToRow(row);
2012
2013 //align to correct position
2014 switch(position){
2015 case "middle":
2016 case "center":
2017
2018 if(this.elementVertical.scrollHeight - this.elementVertical.scrollTop == this.elementVertical.clientHeight){
2019 this.elementVertical.scrollTop = this.elementVertical.scrollTop + (rowEl.offsetTop - this.elementVertical.scrollTop) - ((this.elementVertical.scrollHeight - rowEl.offsetTop) / 2);
2020 }else {
2021 this.elementVertical.scrollTop = this.elementVertical.scrollTop - (this.elementVertical.clientHeight / 2);
2022 }
2023
2024 break;
2025
2026 case "bottom":
2027
2028 if(this.elementVertical.scrollHeight - this.elementVertical.scrollTop == this.elementVertical.clientHeight){
2029 this.elementVertical.scrollTop = this.elementVertical.scrollTop - (this.elementVertical.scrollHeight - rowEl.offsetTop) + rowEl.offsetHeight;
2030 }else {
2031 this.elementVertical.scrollTop = this.elementVertical.scrollTop - this.elementVertical.clientHeight + rowEl.offsetHeight;
2032 }
2033
2034 break;
2035
2036 case "top":
2037 this.elementVertical.scrollTop = rowEl.offsetTop;
2038 break;
2039 }
2040
2041 resolve();
2042
2043 }else {
2044 console.warn("Scroll Error - Row not visible");
2045 reject("Scroll Error - Row not visible");
2046 }
2047 });
2048 }
2049 }
2050
2051 class BasicHorizontal extends Renderer{
2052 constructor(table){
2053 super(table);
2054 }
2055
2056 renderRowCells(row, inFragment) {
2057 const rowFrag = document.createDocumentFragment();
2058 row.cells.forEach((cell) => {
2059 rowFrag.appendChild(cell.getElement());
2060 });
2061 row.element.appendChild(rowFrag);
2062
2063 if(!inFragment){
2064 row.cells.forEach((cell) => {
2065 cell.cellRendered();
2066 });
2067 }
2068 }
2069
2070 reinitializeColumnWidths(columns){
2071 columns.forEach(function(column){
2072 column.reinitializeWidth();
2073 });
2074 }
2075 }
2076
2077 class VirtualDomHorizontal extends Renderer{
2078 constructor(table){
2079 super(table);
2080
2081 this.leftCol = 0;
2082 this.rightCol = 0;
2083 this.scrollLeft = 0;
2084
2085 this.vDomScrollPosLeft = 0;
2086 this.vDomScrollPosRight = 0;
2087
2088 this.vDomPadLeft = 0;
2089 this.vDomPadRight = 0;
2090
2091 this.fitDataColAvg = 0;
2092
2093 this.windowBuffer = 200; //pixel margin to make column visible before it is shown on screen
2094
2095 this.visibleRows = null;
2096
2097 this.initialized = false;
2098 this.isFitData = false;
2099
2100 this.columns = [];
2101 }
2102
2103 initialize(){
2104 this.compatibilityCheck();
2105 this.layoutCheck();
2106 this.vertScrollListen();
2107 }
2108
2109 compatibilityCheck(){
2110 if(this.options("layout") == "fitDataTable"){
2111 console.warn("Horizontal Virtual DOM is not compatible with fitDataTable layout mode");
2112 }
2113
2114 if(this.options("responsiveLayout")){
2115 console.warn("Horizontal Virtual DOM is not compatible with responsive columns");
2116 }
2117
2118 if(this.options("rtl")){
2119 console.warn("Horizontal Virtual DOM is not currently compatible with RTL text direction");
2120 }
2121 }
2122
2123 layoutCheck(){
2124 this.isFitData = this.options("layout").startsWith('fitData');
2125 }
2126
2127 vertScrollListen(){
2128 this.subscribe("scroll-vertical", this.clearVisRowCache.bind(this));
2129 this.subscribe("data-refreshed", this.clearVisRowCache.bind(this));
2130 }
2131
2132 clearVisRowCache(){
2133 this.visibleRows = null;
2134 }
2135
2136 //////////////////////////////////////
2137 ///////// Public Functions ///////////
2138 //////////////////////////////////////
2139
2140 renderColumns(row, force){
2141 this.dataChange();
2142 }
2143
2144
2145 scrollColumns(left, dir){
2146 if(this.scrollLeft != left){
2147 this.scrollLeft = left;
2148
2149 this.scroll(left - (this.vDomScrollPosLeft + this.windowBuffer));
2150 }
2151 }
2152
2153 calcWindowBuffer(){
2154 var buffer = this.elementVertical.clientWidth;
2155
2156 this.table.columnManager.columnsByIndex.forEach((column) => {
2157 if(column.visible){
2158 var width = column.getWidth();
2159
2160 if(width > buffer){
2161 buffer = width;
2162 }
2163 }
2164 });
2165
2166 this.windowBuffer = buffer * 2;
2167 }
2168
2169 rerenderColumns(update, blockRedraw){
2170 var old = {
2171 cols:this.columns,
2172 leftCol:this.leftCol,
2173 rightCol:this.rightCol,
2174 },
2175 colPos = 0;
2176
2177 if(update && !this.initialized){
2178 return;
2179 }
2180
2181 this.clear();
2182
2183 this.calcWindowBuffer();
2184
2185 this.scrollLeft = this.elementVertical.scrollLeft;
2186
2187 this.vDomScrollPosLeft = this.scrollLeft - this.windowBuffer;
2188 this.vDomScrollPosRight = this.scrollLeft + this.elementVertical.clientWidth + this.windowBuffer;
2189
2190 this.table.columnManager.columnsByIndex.forEach((column) => {
2191 var config = {},
2192 width;
2193
2194 if(column.visible){
2195 if(!column.modules.frozen){
2196 width = column.getWidth();
2197
2198 config.leftPos = colPos;
2199 config.rightPos = colPos + width;
2200
2201 config.width = width;
2202
2203 if (this.isFitData) {
2204 config.fitDataCheck = column.modules.vdomHoz ? column.modules.vdomHoz.fitDataCheck : true;
2205 }
2206
2207 if((colPos + width > this.vDomScrollPosLeft) && (colPos < this.vDomScrollPosRight)){
2208 //column is visible
2209
2210 if(this.leftCol == -1){
2211 this.leftCol = this.columns.length;
2212 this.vDomPadLeft = colPos;
2213 }
2214
2215 this.rightCol = this.columns.length;
2216 }else {
2217 // column is hidden
2218 if(this.leftCol !== -1){
2219 this.vDomPadRight += width;
2220 }
2221 }
2222
2223 this.columns.push(column);
2224
2225 column.modules.vdomHoz = config;
2226
2227 colPos += width;
2228 }
2229 }
2230 });
2231
2232 this.tableElement.style.paddingLeft = this.vDomPadLeft + "px";
2233 this.tableElement.style.paddingRight = this.vDomPadRight + "px";
2234
2235 this.initialized = true;
2236
2237 if(!blockRedraw){
2238 if(!update || this.reinitChanged(old)){
2239 this.reinitializeRows();
2240 }
2241 }
2242
2243 this.elementVertical.scrollLeft = this.scrollLeft;
2244 }
2245
2246 renderRowCells(row){
2247 if(this.initialized){
2248 this.initializeRow(row);
2249 }else {
2250 const rowFrag = document.createDocumentFragment();
2251 row.cells.forEach((cell) => {
2252 rowFrag.appendChild(cell.getElement());
2253 });
2254 row.element.appendChild(rowFrag);
2255
2256 row.cells.forEach((cell) => {
2257 cell.cellRendered();
2258 });
2259 }
2260 }
2261
2262 rerenderRowCells(row, force){
2263 this.reinitializeRow(row, force);
2264 }
2265
2266 reinitializeColumnWidths(columns){
2267 for(let i = this.leftCol; i <= this.rightCol; i++){
2268 let col = this.columns[i];
2269
2270 if(col){
2271 col.reinitializeWidth();
2272 }
2273 }
2274 }
2275
2276 //////////////////////////////////////
2277 //////// Internal Rendering //////////
2278 //////////////////////////////////////
2279
2280 deinitialize(){
2281 this.initialized = false;
2282 }
2283
2284 clear(){
2285 this.columns = [];
2286
2287 this.leftCol = -1;
2288 this.rightCol = 0;
2289
2290 this.vDomScrollPosLeft = 0;
2291 this.vDomScrollPosRight = 0;
2292 this.vDomPadLeft = 0;
2293 this.vDomPadRight = 0;
2294 }
2295
2296 dataChange(){
2297 var change = false,
2298 row, rowEl;
2299
2300 if(this.isFitData){
2301 this.table.columnManager.columnsByIndex.forEach((column) => {
2302 if(!column.definition.width && column.visible){
2303 change = true;
2304 }
2305 });
2306
2307 if(change && this.table.rowManager.getDisplayRows().length){
2308 this.vDomScrollPosRight = this.scrollLeft + this.elementVertical.clientWidth + this.windowBuffer;
2309
2310 row = this.chain("rows-sample", [1], [], () => {
2311 return this.table.rowManager.getDisplayRows();
2312 })[0];
2313
2314 if(row){
2315 rowEl = row.getElement();
2316
2317 row.generateCells();
2318
2319 this.tableElement.appendChild(rowEl);
2320
2321 for(let colEnd = 0; colEnd < row.cells.length; colEnd++){
2322 let cell = row.cells[colEnd];
2323 rowEl.appendChild(cell.getElement());
2324
2325 cell.column.reinitializeWidth();
2326 }
2327
2328 rowEl.parentNode.removeChild(rowEl);
2329
2330 this.rerenderColumns(false, true);
2331 }
2332 }
2333 }else {
2334 if(this.options("layout") === "fitColumns"){
2335 this.layoutRefresh();
2336 this.rerenderColumns(false, true);
2337 }
2338 }
2339 }
2340
2341 reinitChanged(old){
2342 var match = true;
2343
2344 if(old.cols.length !== this.columns.length || old.leftCol !== this.leftCol || old.rightCol !== this.rightCol){
2345 return true;
2346 }
2347
2348 old.cols.forEach((col, i) => {
2349 if(col !== this.columns[i]){
2350 match = false;
2351 }
2352 });
2353
2354 return !match;
2355 }
2356
2357 reinitializeRows(){
2358 var visibleRows = this.getVisibleRows(),
2359 otherRows = this.table.rowManager.getRows().filter(row => !visibleRows.includes(row));
2360
2361 visibleRows.forEach((row) => {
2362 this.reinitializeRow(row, true);
2363 });
2364
2365 otherRows.forEach((row) =>{
2366 row.deinitialize();
2367 });
2368 }
2369
2370 getVisibleRows(){
2371 if (!this.visibleRows){
2372 this.visibleRows = this.table.rowManager.getVisibleRows();
2373 }
2374
2375 return this.visibleRows;
2376 }
2377
2378 scroll(diff){
2379 this.vDomScrollPosLeft += diff;
2380 this.vDomScrollPosRight += diff;
2381
2382 if(Math.abs(diff) > (this.windowBuffer / 2)){
2383 this.rerenderColumns();
2384 }else {
2385 if(diff > 0){
2386 //scroll right
2387 this.addColRight();
2388 this.removeColLeft();
2389 }else {
2390 //scroll left
2391 this.addColLeft();
2392 this.removeColRight();
2393 }
2394 }
2395 }
2396
2397 colPositionAdjust (start, end, diff){
2398 for(let i = start; i < end; i++){
2399 let column = this.columns[i];
2400
2401 column.modules.vdomHoz.leftPos += diff;
2402 column.modules.vdomHoz.rightPos += diff;
2403 }
2404 }
2405
2406 addColRight(){
2407 var changes = false,
2408 working = true;
2409
2410 while(working){
2411
2412 let column = this.columns[this.rightCol + 1];
2413
2414 if(column){
2415 if(column.modules.vdomHoz.leftPos <= this.vDomScrollPosRight){
2416 changes = true;
2417
2418 this.getVisibleRows().forEach((row) => {
2419 if(row.type !== "group"){
2420 var cell = row.getCell(column);
2421 row.getElement().insertBefore(cell.getElement(), row.getCell(this.columns[this.rightCol]).getElement().nextSibling);
2422 cell.cellRendered();
2423 }
2424 });
2425
2426 this.fitDataColActualWidthCheck(column);
2427
2428 this.rightCol++; // Don't move this below the >= check below
2429
2430 this.getVisibleRows().forEach((row) => {
2431 if(row.type !== "group"){
2432 row.modules.vdomHoz.rightCol = this.rightCol;
2433 }
2434 });
2435
2436 if(this.rightCol >= (this.columns.length - 1)){
2437 this.vDomPadRight = 0;
2438 }else {
2439 this.vDomPadRight -= column.getWidth();
2440 }
2441 }else {
2442 working = false;
2443 }
2444 }else {
2445 working = false;
2446 }
2447 }
2448
2449 if(changes){
2450 this.tableElement.style.paddingRight = this.vDomPadRight + "px";
2451 }
2452 }
2453
2454 addColLeft(){
2455 var changes = false,
2456 working = true;
2457
2458 while(working){
2459 let column = this.columns[this.leftCol - 1];
2460
2461 if(column){
2462 if(column.modules.vdomHoz.rightPos >= this.vDomScrollPosLeft){
2463 changes = true;
2464
2465 this.getVisibleRows().forEach((row) => {
2466 if(row.type !== "group"){
2467 var cell = row.getCell(column);
2468 row.getElement().insertBefore(cell.getElement(), row.getCell(this.columns[this.leftCol]).getElement());
2469 cell.cellRendered();
2470 }
2471 });
2472
2473 this.leftCol--; // don't move this below the <= check below
2474
2475 this.getVisibleRows().forEach((row) => {
2476 if(row.type !== "group"){
2477 row.modules.vdomHoz.leftCol = this.leftCol;
2478 }
2479 });
2480
2481 if(this.leftCol <= 0){ // replicating logic in addColRight
2482 this.vDomPadLeft = 0;
2483 }else {
2484 this.vDomPadLeft -= column.getWidth();
2485 }
2486
2487 let diff = this.fitDataColActualWidthCheck(column);
2488
2489 if(diff){
2490 this.scrollLeft = this.elementVertical.scrollLeft = this.elementVertical.scrollLeft + diff;
2491 this.vDomPadRight -= diff;
2492 }
2493
2494 }else {
2495 working = false;
2496 }
2497 }else {
2498 working = false;
2499 }
2500 }
2501
2502 if(changes){
2503 this.tableElement.style.paddingLeft = this.vDomPadLeft + "px";
2504 }
2505 }
2506
2507 removeColRight(){
2508 var changes = false,
2509 working = true;
2510
2511 while(working){
2512 let column = this.columns[this.rightCol];
2513
2514 if(column){
2515 if(column.modules.vdomHoz.leftPos > this.vDomScrollPosRight){
2516 changes = true;
2517
2518 this.getVisibleRows().forEach((row) => {
2519 if(row.type !== "group"){
2520 var cell = row.getCell(column);
2521
2522 try {
2523 row.getElement().removeChild(cell.getElement());
2524 } catch (ex) {
2525 console.warn("Could not removeColRight", ex.message);
2526 }
2527 }
2528 });
2529
2530 this.vDomPadRight += column.getWidth();
2531 this.rightCol --;
2532
2533 this.getVisibleRows().forEach((row) => {
2534 if(row.type !== "group"){
2535 row.modules.vdomHoz.rightCol = this.rightCol;
2536 }
2537 });
2538 }else {
2539 working = false;
2540 }
2541 }else {
2542 working = false;
2543 }
2544 }
2545
2546 if(changes){
2547 this.tableElement.style.paddingRight = this.vDomPadRight + "px";
2548 }
2549 }
2550
2551 removeColLeft(){
2552 var changes = false,
2553 working = true;
2554
2555 while(working){
2556 let column = this.columns[this.leftCol];
2557
2558 if(column){
2559 if(column.modules.vdomHoz.rightPos < this.vDomScrollPosLeft){
2560 changes = true;
2561
2562 this.getVisibleRows().forEach((row) => {
2563 if(row.type !== "group"){
2564 var cell = row.getCell(column);
2565
2566 try {
2567 row.getElement().removeChild(cell.getElement());
2568 } catch (ex) {
2569 console.warn("Could not removeColLeft", ex.message);
2570 }
2571 }
2572 });
2573
2574 this.vDomPadLeft += column.getWidth();
2575 this.leftCol ++;
2576
2577 this.getVisibleRows().forEach((row) => {
2578 if(row.type !== "group"){
2579 row.modules.vdomHoz.leftCol = this.leftCol;
2580 }
2581 });
2582 }else {
2583 working = false;
2584 }
2585 }else {
2586 working = false;
2587 }
2588 }
2589
2590 if(changes){
2591 this.tableElement.style.paddingLeft = this.vDomPadLeft + "px";
2592 }
2593 }
2594
2595 fitDataColActualWidthCheck(column){
2596 var newWidth, widthDiff;
2597
2598 if(column.modules.vdomHoz.fitDataCheck){
2599 column.reinitializeWidth();
2600
2601 newWidth = column.getWidth();
2602 widthDiff = newWidth - column.modules.vdomHoz.width;
2603
2604 if(widthDiff){
2605 column.modules.vdomHoz.rightPos += widthDiff;
2606 column.modules.vdomHoz.width = newWidth;
2607 this.colPositionAdjust(this.columns.indexOf(column) + 1, this.columns.length, widthDiff);
2608 }
2609
2610 column.modules.vdomHoz.fitDataCheck = false;
2611 }
2612
2613 return widthDiff;
2614 }
2615
2616 initializeRow(row){
2617 if(row.type !== "group"){
2618 row.modules.vdomHoz = {
2619 leftCol:this.leftCol,
2620 rightCol:this.rightCol,
2621 };
2622
2623 if(this.table.modules.frozenColumns){
2624 this.table.modules.frozenColumns.leftColumns.forEach((column) => {
2625 this.appendCell(row, column);
2626 });
2627 }
2628
2629 for(let i = this.leftCol; i <= this.rightCol; i++){
2630 this.appendCell(row, this.columns[i]);
2631 }
2632
2633 if(this.table.modules.frozenColumns){
2634 this.table.modules.frozenColumns.rightColumns.forEach((column) => {
2635 this.appendCell(row, column);
2636 });
2637 }
2638 }
2639 }
2640
2641 appendCell(row, column){
2642 if(column && column.visible){
2643 let cell = row.getCell(column);
2644
2645 row.getElement().appendChild(cell.getElement());
2646 cell.cellRendered();
2647 }
2648 }
2649
2650 reinitializeRow(row, force){
2651 if(row.type !== "group"){
2652 if(force || !row.modules.vdomHoz || row.modules.vdomHoz.leftCol !== this.leftCol || row.modules.vdomHoz.rightCol !== this.rightCol){
2653
2654 var rowEl = row.getElement();
2655 while(rowEl.firstChild) rowEl.removeChild(rowEl.firstChild);
2656
2657 this.initializeRow(row);
2658 }
2659 }
2660 }
2661 }
2662
2663 class ColumnManager extends CoreFeature {
2664
2665 constructor (table){
2666 super(table);
2667
2668 this.blockHozScrollEvent = false;
2669 this.headersElement = null;
2670 this.contentsElement = null;
2671 this.rowHeader = null;
2672 this.element = null ; //containing element
2673 this.columns = []; // column definition object
2674 this.columnsByIndex = []; //columns by index
2675 this.columnsByField = {}; //columns by field
2676 this.scrollLeft = 0;
2677 this.optionsList = new OptionsList(this.table, "column definition", defaultColumnOptions);
2678
2679 this.redrawBlock = false; //prevent redraws to allow multiple data manipulations before continuing
2680 this.redrawBlockUpdate = null; //store latest redraw update only status
2681
2682 this.renderer = null;
2683 }
2684
2685 ////////////// Setup Functions /////////////////
2686
2687 initialize(){
2688 this.initializeRenderer();
2689
2690 this.headersElement = this.createHeadersElement();
2691 this.contentsElement = this.createHeaderContentsElement();
2692 this.element = this.createHeaderElement();
2693
2694 this.contentsElement.insertBefore(this.headersElement, this.contentsElement.firstChild);
2695 this.element.insertBefore(this.contentsElement, this.element.firstChild);
2696
2697 this.initializeScrollWheelWatcher();
2698
2699 this.subscribe("scroll-horizontal", this.scrollHorizontal.bind(this));
2700 this.subscribe("scrollbar-vertical", this.padVerticalScrollbar.bind(this));
2701 }
2702
2703 padVerticalScrollbar(width){
2704 if(this.table.rtl){
2705 this.headersElement.style.marginLeft = width + "px";
2706 }else {
2707 this.headersElement.style.marginRight = width + "px";
2708 }
2709 }
2710
2711 initializeRenderer(){
2712 var renderClass;
2713
2714 var renderers = {
2715 "virtual": VirtualDomHorizontal,
2716 "basic": BasicHorizontal,
2717 };
2718
2719 if(typeof this.table.options.renderHorizontal === "string"){
2720 renderClass = renderers[this.table.options.renderHorizontal];
2721 }else {
2722 renderClass = this.table.options.renderHorizontal;
2723 }
2724
2725 if(renderClass){
2726 this.renderer = new renderClass(this.table, this.element, this.tableElement);
2727 this.renderer.initialize();
2728 }else {
2729 console.error("Unable to find matching renderer:", this.table.options.renderHorizontal);
2730 }
2731 }
2732
2733
2734 createHeadersElement (){
2735 var el = document.createElement("div");
2736
2737 el.classList.add("tabulator-headers");
2738 el.setAttribute("role", "row");
2739
2740 return el;
2741 }
2742
2743 createHeaderContentsElement (){
2744 var el = document.createElement("div");
2745
2746 el.classList.add("tabulator-header-contents");
2747 el.setAttribute("role", "rowgroup");
2748
2749 return el;
2750 }
2751
2752 createHeaderElement (){
2753 var el = document.createElement("div");
2754
2755 el.classList.add("tabulator-header");
2756 el.setAttribute("role", "rowgroup");
2757
2758 if(!this.table.options.headerVisible){
2759 el.classList.add("tabulator-header-hidden");
2760 }
2761
2762 return el;
2763 }
2764
2765 //return containing element
2766 getElement(){
2767 return this.element;
2768 }
2769
2770 //return containing contents element
2771 getContentsElement(){
2772 return this.contentsElement;
2773 }
2774
2775
2776 //return header containing element
2777 getHeadersElement(){
2778 return this.headersElement;
2779 }
2780
2781 //scroll horizontally to match table body
2782 scrollHorizontal(left){
2783 this.contentsElement.scrollLeft = left;
2784
2785 this.scrollLeft = left;
2786
2787 this.renderer.scrollColumns(left);
2788 }
2789
2790 initializeScrollWheelWatcher(){
2791 this.contentsElement.addEventListener("wheel", (e) => {
2792 var left;
2793
2794 if(e.deltaX){
2795 left = this.contentsElement.scrollLeft + e.deltaX;
2796
2797 this.table.rowManager.scrollHorizontal(left);
2798 this.table.columnManager.scrollHorizontal(left);
2799 }
2800 });
2801 }
2802
2803 ///////////// Column Setup Functions /////////////
2804 generateColumnsFromRowData(data){
2805 var cols = [],
2806 collProgress = {},
2807 rowSample = this.table.options.autoColumns === "full" ? data : [data[0]],
2808 definitions = this.table.options.autoColumnsDefinitions;
2809
2810 if(data && data.length){
2811
2812 rowSample.forEach((row) => {
2813
2814 Object.keys(row).forEach((key, index) => {
2815 let value = row[key],
2816 col;
2817
2818 if(!collProgress[key]){
2819 col = {
2820 field:key,
2821 title:key,
2822 sorter:this.calculateSorterFromValue(value),
2823 };
2824
2825 cols.splice(index, 0, col);
2826 collProgress[key] = typeof value === "undefined" ? col : true;
2827 }else if(collProgress[key] !== true){
2828 if(typeof value !== "undefined"){
2829 collProgress[key].sorter = this.calculateSorterFromValue(value);
2830 collProgress[key] = true;
2831 }
2832 }
2833 });
2834 });
2835
2836 if(definitions){
2837
2838 switch(typeof definitions){
2839 case "function":
2840 this.table.options.columns = definitions.call(this.table, cols);
2841 break;
2842
2843 case "object":
2844 if(Array.isArray(definitions)){
2845 cols.forEach((col) => {
2846 var match = definitions.find((def) => {
2847 return def.field === col.field;
2848 });
2849
2850 if(match){
2851 Object.assign(col, match);
2852 }
2853 });
2854
2855 }else {
2856 cols.forEach((col) => {
2857 if(definitions[col.field]){
2858 Object.assign(col, definitions[col.field]);
2859 }
2860 });
2861 }
2862
2863 this.table.options.columns = cols;
2864 break;
2865 }
2866 }else {
2867 this.table.options.columns = cols;
2868 }
2869
2870 this.setColumns(this.table.options.columns);
2871 }
2872 }
2873
2874 calculateSorterFromValue(value){
2875 var sorter;
2876
2877 switch(typeof value){
2878 case "undefined":
2879 sorter = "string";
2880 break;
2881
2882 case "boolean":
2883 sorter = "boolean";
2884 break;
2885
2886 case "number":
2887 sorter = "number";
2888 break;
2889
2890 case "object":
2891 if(Array.isArray(value)){
2892 sorter = "array";
2893 }else {
2894 sorter = "string";
2895 }
2896 break;
2897
2898 default:
2899 if(!isNaN(value) && value !== ""){
2900 sorter = "number";
2901 }else {
2902 if(value.match(/((^[0-9]+[a-z]+)|(^[a-z]+[0-9]+))+$/i)){
2903 sorter = "alphanum";
2904 }else {
2905 sorter = "string";
2906 }
2907 }
2908 break;
2909 }
2910
2911 return sorter;
2912 }
2913
2914 setColumns(cols, row){
2915 while(this.headersElement.firstChild) this.headersElement.removeChild(this.headersElement.firstChild);
2916
2917 this.columns = [];
2918 this.columnsByIndex = [];
2919 this.columnsByField = {};
2920
2921 this.dispatch("columns-loading");
2922 this.dispatchExternal("columnsLoading");
2923
2924 if(this.table.options.rowHeader){
2925 this.rowHeader = new Column(this.table.options.rowHeader === true ? {} : this.table.options.rowHeader, this, true);
2926 this.columns.push(this.rowHeader);
2927 this.headersElement.appendChild(this.rowHeader.getElement());
2928 this.rowHeader.columnRendered();
2929 }
2930
2931 cols.forEach((def, i) => {
2932 this._addColumn(def);
2933 });
2934
2935 this._reIndexColumns();
2936
2937 this.dispatch("columns-loaded");
2938
2939 if(this.subscribedExternal("columnsLoaded")){
2940 this.dispatchExternal("columnsLoaded", this.getComponents());
2941 }
2942
2943 this.rerenderColumns(false, true);
2944
2945 this.redraw(true);
2946 }
2947
2948 _addColumn(definition, before, nextToColumn){
2949 var column = new Column(definition, this),
2950 colEl = column.getElement(),
2951 index = nextToColumn ? this.findColumnIndex(nextToColumn) : nextToColumn;
2952
2953 //prevent adding of rows in front of row header
2954 if(before && this.rowHeader && (!nextToColumn || nextToColumn === this.rowHeader)){
2955 before = false;
2956 nextToColumn = this.rowHeader;
2957 index = 0;
2958 }
2959
2960 if(nextToColumn && index > -1){
2961 var topColumn = nextToColumn.getTopColumn();
2962 var parentIndex = this.columns.indexOf(topColumn);
2963 var nextEl = topColumn.getElement();
2964
2965 if(before){
2966 this.columns.splice(parentIndex, 0, column);
2967 nextEl.parentNode.insertBefore(colEl, nextEl);
2968 }else {
2969 this.columns.splice(parentIndex + 1, 0, column);
2970 nextEl.parentNode.insertBefore(colEl, nextEl.nextSibling);
2971 }
2972 }else {
2973 if(before){
2974 this.columns.unshift(column);
2975 this.headersElement.insertBefore(column.getElement(), this.headersElement.firstChild);
2976 }else {
2977 this.columns.push(column);
2978 this.headersElement.appendChild(column.getElement());
2979 }
2980 }
2981
2982 column.columnRendered();
2983
2984 return column;
2985 }
2986
2987 registerColumnField(col){
2988 if(col.definition.field){
2989 this.columnsByField[col.definition.field] = col;
2990 }
2991 }
2992
2993 registerColumnPosition(col){
2994 this.columnsByIndex.push(col);
2995 }
2996
2997 _reIndexColumns(){
2998 this.columnsByIndex = [];
2999
3000 this.columns.forEach(function(column){
3001 column.reRegisterPosition();
3002 });
3003 }
3004
3005 //ensure column headers take up the correct amount of space in column groups
3006 verticalAlignHeaders(){
3007 var minHeight = 0;
3008
3009 if(!this.redrawBlock){
3010
3011 this.headersElement.style.height="";
3012
3013 this.columns.forEach((column) => {
3014 column.clearVerticalAlign();
3015 });
3016
3017 this.columns.forEach((column) => {
3018 var height = column.getHeight();
3019
3020 if(height > minHeight){
3021 minHeight = height;
3022 }
3023 });
3024
3025 this.headersElement.style.height = minHeight + "px";
3026
3027 this.columns.forEach((column) => {
3028 column.verticalAlign(this.table.options.columnHeaderVertAlign, minHeight);
3029 });
3030
3031 this.table.rowManager.adjustTableSize();
3032 }
3033 }
3034
3035 //////////////// Column Details /////////////////
3036 findColumn(subject){
3037 var columns;
3038
3039 if(typeof subject == "object"){
3040
3041 if(subject instanceof Column){
3042 //subject is column element
3043 return subject;
3044 }else if(subject instanceof ColumnComponent){
3045 //subject is public column component
3046 return subject._getSelf() || false;
3047 }else if(typeof HTMLElement !== "undefined" && subject instanceof HTMLElement){
3048
3049 columns = [];
3050
3051 this.columns.forEach((column) => {
3052 columns.push(column);
3053 columns = columns.concat(column.getColumns(true));
3054 });
3055
3056 //subject is a HTML element of the column header
3057 let match = columns.find((column) => {
3058 return column.element === subject;
3059 });
3060
3061 return match || false;
3062 }
3063
3064 }else {
3065 //subject should be treated as the field name of the column
3066 return this.columnsByField[subject] || false;
3067 }
3068
3069 //catch all for any other type of input
3070 return false;
3071 }
3072
3073 getColumnByField(field){
3074 return this.columnsByField[field];
3075 }
3076
3077 getColumnsByFieldRoot(root){
3078 var matches = [];
3079
3080 Object.keys(this.columnsByField).forEach((field) => {
3081 var fieldRoot = this.table.options.nestedFieldSeparator ? field.split(this.table.options.nestedFieldSeparator)[0] : field;
3082 if(fieldRoot === root){
3083 matches.push(this.columnsByField[field]);
3084 }
3085 });
3086
3087 return matches;
3088 }
3089
3090 getColumnByIndex(index){
3091 return this.columnsByIndex[index];
3092 }
3093
3094 getFirstVisibleColumn(){
3095 var index = this.columnsByIndex.findIndex((col) => {
3096 return col.visible;
3097 });
3098
3099 return index > -1 ? this.columnsByIndex[index] : false;
3100 }
3101
3102 getVisibleColumnsByIndex() {
3103 return this.columnsByIndex.filter((col) => col.visible);
3104 }
3105
3106 getColumns(){
3107 return this.columns;
3108 }
3109
3110 findColumnIndex(column){
3111 return this.columnsByIndex.findIndex((col) => {
3112 return column === col;
3113 });
3114 }
3115
3116 //return all columns that are not groups
3117 getRealColumns(){
3118 return this.columnsByIndex;
3119 }
3120
3121 //traverse across columns and call action
3122 traverse(callback){
3123 this.columnsByIndex.forEach((column,i) =>{
3124 callback(column, i);
3125 });
3126 }
3127
3128 //get definitions of actual columns
3129 getDefinitions(active){
3130 var output = [];
3131
3132 this.columnsByIndex.forEach((column) => {
3133 if(!active || (active && column.visible)){
3134 output.push(column.getDefinition());
3135 }
3136 });
3137
3138 return output;
3139 }
3140
3141 //get full nested definition tree
3142 getDefinitionTree(){
3143 var output = [];
3144
3145 this.columns.forEach((column) => {
3146 output.push(column.getDefinition(true));
3147 });
3148
3149 return output;
3150 }
3151
3152 getComponents(structured){
3153 var output = [],
3154 columns = structured ? this.columns : this.columnsByIndex;
3155
3156 columns.forEach((column) => {
3157 output.push(column.getComponent());
3158 });
3159
3160 return output;
3161 }
3162
3163 getWidth(){
3164 var width = 0;
3165
3166 this.columnsByIndex.forEach((column) => {
3167 if(column.visible){
3168 width += column.getWidth();
3169 }
3170 });
3171
3172 return width;
3173 }
3174
3175 moveColumn(from, to, after){
3176 to.element.parentNode.insertBefore(from.element, to.element);
3177
3178 if(after){
3179 to.element.parentNode.insertBefore(to.element, from.element);
3180 }
3181
3182 this.moveColumnActual(from, to, after);
3183
3184 this.verticalAlignHeaders();
3185
3186 this.table.rowManager.reinitialize();
3187 }
3188
3189 moveColumnActual(from, to, after){
3190 if(from.parent.isGroup){
3191 this._moveColumnInArray(from.parent.columns, from, to, after);
3192 }else {
3193 this._moveColumnInArray(this.columns, from, to, after);
3194 }
3195
3196 this._moveColumnInArray(this.columnsByIndex, from, to, after, true);
3197
3198 this.rerenderColumns(true);
3199
3200 this.dispatch("column-moved", from, to, after);
3201
3202 if(this.subscribedExternal("columnMoved")){
3203 this.dispatchExternal("columnMoved", from.getComponent(), this.table.columnManager.getComponents());
3204 }
3205 }
3206
3207 _moveColumnInArray(columns, from, to, after, updateRows){
3208 var fromIndex = columns.indexOf(from),
3209 toIndex, rows = [];
3210
3211 if (fromIndex > -1) {
3212
3213 columns.splice(fromIndex, 1);
3214
3215 toIndex = columns.indexOf(to);
3216
3217 if (toIndex > -1) {
3218
3219 if(after){
3220 toIndex = toIndex+1;
3221 }
3222
3223 }else {
3224 toIndex = fromIndex;
3225 }
3226
3227 columns.splice(toIndex, 0, from);
3228
3229 if(updateRows){
3230
3231 rows = this.chain("column-moving-rows", [from, to, after], null, []) || [];
3232
3233 rows = rows.concat(this.table.rowManager.rows);
3234
3235 rows.forEach(function(row){
3236 if(row.cells.length){
3237 var cell = row.cells.splice(fromIndex, 1)[0];
3238 row.cells.splice(toIndex, 0, cell);
3239 }
3240 });
3241
3242 }
3243 }
3244 }
3245
3246 scrollToColumn(column, position, ifVisible){
3247 var left = 0,
3248 offset = column.getLeftOffset(),
3249 adjust = 0,
3250 colEl = column.getElement();
3251
3252
3253 return new Promise((resolve, reject) => {
3254
3255 if(typeof position === "undefined"){
3256 position = this.table.options.scrollToColumnPosition;
3257 }
3258
3259 if(typeof ifVisible === "undefined"){
3260 ifVisible = this.table.options.scrollToColumnIfVisible;
3261 }
3262
3263 if(column.visible){
3264
3265 //align to correct position
3266 switch(position){
3267 case "middle":
3268 case "center":
3269 adjust = -this.element.clientWidth / 2;
3270 break;
3271
3272 case "right":
3273 adjust = colEl.clientWidth - this.headersElement.clientWidth;
3274 break;
3275 }
3276
3277 //check column visibility
3278 if(!ifVisible){
3279 if(offset > 0 && offset + colEl.offsetWidth < this.element.clientWidth){
3280 return false;
3281 }
3282 }
3283
3284 //calculate scroll position
3285 left = offset + adjust;
3286
3287 left = Math.max(Math.min(left, this.table.rowManager.element.scrollWidth - this.table.rowManager.element.clientWidth),0);
3288
3289 this.table.rowManager.scrollHorizontal(left);
3290 this.scrollHorizontal(left);
3291
3292 resolve();
3293 }else {
3294 console.warn("Scroll Error - Column not visible");
3295 reject("Scroll Error - Column not visible");
3296 }
3297
3298 });
3299 }
3300
3301 //////////////// Cell Management /////////////////
3302 generateCells(row){
3303 var cells = [];
3304
3305 this.columnsByIndex.forEach((column) => {
3306 cells.push(column.generateCell(row));
3307 });
3308
3309 return cells;
3310 }
3311
3312 //////////////// Column Management /////////////////
3313 getFlexBaseWidth(){
3314 var totalWidth = this.table.element.clientWidth, //table element width
3315 fixedWidth = 0;
3316
3317 //adjust for vertical scrollbar if present
3318 if(this.table.rowManager.element.scrollHeight > this.table.rowManager.element.clientHeight){
3319 totalWidth -= this.table.rowManager.element.offsetWidth - this.table.rowManager.element.clientWidth;
3320 }
3321
3322 this.columnsByIndex.forEach(function(column){
3323 var width, minWidth, colWidth;
3324
3325 if(column.visible){
3326
3327 width = column.definition.width || 0;
3328
3329 minWidth = parseInt(column.minWidth);
3330
3331 if(typeof(width) == "string"){
3332 if(width.indexOf("%") > -1){
3333 colWidth = (totalWidth / 100) * parseInt(width) ;
3334 }else {
3335 colWidth = parseInt(width);
3336 }
3337 }else {
3338 colWidth = width;
3339 }
3340
3341 fixedWidth += colWidth > minWidth ? colWidth : minWidth;
3342
3343 }
3344 });
3345
3346 return fixedWidth;
3347 }
3348
3349 addColumn(definition, before, nextToColumn){
3350 return new Promise((resolve, reject) => {
3351 var column = this._addColumn(definition, before, nextToColumn);
3352
3353 this._reIndexColumns();
3354
3355 this.dispatch("column-add", definition, before, nextToColumn);
3356
3357 if(this.layoutMode() != "fitColumns"){
3358 column.reinitializeWidth();
3359 }
3360
3361 this.redraw(true);
3362
3363 this.table.rowManager.reinitialize();
3364
3365 this.rerenderColumns();
3366
3367 resolve(column);
3368 });
3369 }
3370
3371 //remove column from system
3372 deregisterColumn(column){
3373 var field = column.getField(),
3374 index;
3375
3376 //remove from field list
3377 if(field){
3378 delete this.columnsByField[field];
3379 }
3380
3381 //remove from index list
3382 index = this.columnsByIndex.indexOf(column);
3383
3384 if(index > -1){
3385 this.columnsByIndex.splice(index, 1);
3386 }
3387
3388 //remove from column list
3389 index = this.columns.indexOf(column);
3390
3391 if(index > -1){
3392 this.columns.splice(index, 1);
3393 }
3394
3395 this.verticalAlignHeaders();
3396
3397 this.redraw();
3398 }
3399
3400 rerenderColumns(update, silent){
3401 if(!this.redrawBlock){
3402 this.renderer.rerenderColumns(update, silent);
3403 }else {
3404 if(update === false || (update === true && this.redrawBlockUpdate === null)){
3405 this.redrawBlockUpdate = update;
3406 }
3407 }
3408 }
3409
3410 blockRedraw(){
3411 this.redrawBlock = true;
3412 this.redrawBlockUpdate = null;
3413 }
3414
3415 restoreRedraw(){
3416 this.redrawBlock = false;
3417 this.verticalAlignHeaders();
3418 this.renderer.rerenderColumns(this.redrawBlockUpdate);
3419
3420 }
3421
3422 //redraw columns
3423 redraw(force){
3424 if(Helpers.elVisible(this.element)){
3425 this.verticalAlignHeaders();
3426 }
3427
3428 if(force){
3429 this.table.rowManager.resetScroll();
3430 this.table.rowManager.reinitialize();
3431 }
3432
3433 if(!this.confirm("table-redrawing", force)){
3434 this.layoutRefresh(force);
3435 }
3436
3437 this.dispatch("table-redraw", force);
3438
3439 this.table.footerManager.redraw();
3440 }
3441 }
3442
3443 //public row object
3444 class RowComponent {
3445
3446 constructor (row){
3447 this._row = row;
3448
3449 return new Proxy(this, {
3450 get: function(target, name, receiver) {
3451 if (typeof target[name] !== "undefined") {
3452 return target[name];
3453 }else {
3454 return target._row.table.componentFunctionBinder.handle("row", target._row, name);
3455 }
3456 }
3457 });
3458 }
3459
3460 getData(transform){
3461 return this._row.getData(transform);
3462 }
3463
3464 getElement(){
3465 return this._row.getElement();
3466 }
3467
3468 getCells(){
3469 var cells = [];
3470
3471 this._row.getCells().forEach(function(cell){
3472 cells.push(cell.getComponent());
3473 });
3474
3475 return cells;
3476 }
3477
3478 getCell(column){
3479 var cell = this._row.getCell(column);
3480 return cell ? cell.getComponent() : false;
3481 }
3482
3483 getIndex(){
3484 return this._row.getData("data")[this._row.table.options.index];
3485 }
3486
3487 getPosition(){
3488 return this._row.getPosition();
3489 }
3490
3491 watchPosition(callback){
3492 return this._row.watchPosition(callback);
3493 }
3494
3495 delete(){
3496 return this._row.delete();
3497 }
3498
3499 scrollTo(position, ifVisible){
3500 return this._row.table.rowManager.scrollToRow(this._row, position, ifVisible);
3501 }
3502
3503 move(to, after){
3504 this._row.moveToRow(to, after);
3505 }
3506
3507 update(data){
3508 return this._row.updateData(data);
3509 }
3510
3511 normalizeHeight(){
3512 this._row.normalizeHeight(true);
3513 }
3514
3515 _getSelf(){
3516 return this._row;
3517 }
3518
3519 reformat(){
3520 return this._row.reinitialize();
3521 }
3522
3523 getTable(){
3524 return this._row.table;
3525 }
3526
3527 getNextRow(){
3528 var row = this._row.nextRow();
3529 return row ? row.getComponent() : row;
3530 }
3531
3532 getPrevRow(){
3533 var row = this._row.prevRow();
3534 return row ? row.getComponent() : row;
3535 }
3536 }
3537
3538 class Row extends CoreFeature{
3539 constructor (data, parent, type = "row"){
3540 super(parent.table);
3541
3542 this.parent = parent;
3543 this.data = {};
3544 this.type = type; //type of element
3545 this.element = false;
3546 this.modules = {}; //hold module variables;
3547 this.cells = [];
3548 this.height = 0; //hold element height
3549 this.heightStyled = ""; //hold element height pre-styled to improve render efficiency
3550 this.manualHeight = false; //user has manually set row height
3551 this.outerHeight = 0; //hold elements outer height
3552 this.initialized = false; //element has been rendered
3553 this.heightInitialized = false; //element has resized cells to fit
3554 this.position = 0; //store position of element in row list
3555 this.positionWatchers = [];
3556
3557 this.component = null;
3558
3559 this.created = false;
3560
3561 this.setData(data);
3562 }
3563
3564 create(){
3565 if(!this.created){
3566 this.created = true;
3567 this.generateElement();
3568 }
3569 }
3570
3571 createElement (){
3572 var el = document.createElement("div");
3573
3574 el.classList.add("tabulator-row");
3575 el.setAttribute("role", "row");
3576
3577 this.element = el;
3578 }
3579
3580 getElement(){
3581 this.create();
3582 return this.element;
3583 }
3584
3585 detachElement(){
3586 if (this.element && this.element.parentNode){
3587 this.element.parentNode.removeChild(this.element);
3588 }
3589 }
3590
3591 generateElement(){
3592 this.createElement();
3593 this.dispatch("row-init", this);
3594 }
3595
3596 generateCells(){
3597 this.cells = this.table.columnManager.generateCells(this);
3598 }
3599
3600 //functions to setup on first render
3601 initialize(force, inFragment){
3602 this.create();
3603
3604 if(!this.initialized || force){
3605
3606 this.deleteCells();
3607
3608 while(this.element.firstChild) this.element.removeChild(this.element.firstChild);
3609
3610 this.dispatch("row-layout-before", this);
3611
3612 this.generateCells();
3613
3614 this.initialized = true;
3615
3616 this.table.columnManager.renderer.renderRowCells(this, inFragment);
3617
3618 if(force){
3619 this.normalizeHeight();
3620 }
3621
3622 this.dispatch("row-layout", this);
3623
3624 if(this.table.options.rowFormatter){
3625 this.table.options.rowFormatter(this.getComponent());
3626 }
3627
3628 this.dispatch("row-layout-after", this);
3629 }else {
3630 this.table.columnManager.renderer.rerenderRowCells(this, inFragment);
3631 }
3632 }
3633
3634 rendered(){
3635 this.cells.forEach((cell) => {
3636 cell.cellRendered();
3637 });
3638 }
3639
3640 reinitializeHeight(){
3641 this.heightInitialized = false;
3642
3643 if(this.element && this.element.offsetParent !== null){
3644 this.normalizeHeight(true);
3645 }
3646 }
3647
3648 deinitialize(){
3649 this.initialized = false;
3650 }
3651
3652 deinitializeHeight(){
3653 this.heightInitialized = false;
3654 }
3655
3656 reinitialize(children){
3657 this.initialized = false;
3658 this.heightInitialized = false;
3659
3660 if(!this.manualHeight){
3661 this.height = 0;
3662 this.heightStyled = "";
3663 }
3664
3665 if(this.element && this.element.offsetParent !== null){
3666 this.initialize(true);
3667 }
3668
3669 this.dispatch("row-relayout", this);
3670 }
3671
3672 //get heights when doing bulk row style calcs in virtual DOM
3673 calcHeight(force){
3674 var maxHeight = 0, minHeight = 0;
3675
3676 if(this.table.options.rowHeight){
3677 this.height = this.table.options.rowHeight;
3678 }else {
3679 minHeight = this.calcMinHeight();
3680 maxHeight = this.calcMaxHeight();
3681
3682 if(force){
3683 this.height = Math.max(maxHeight, minHeight);
3684 }else {
3685 this.height = this.manualHeight ? this.height : Math.max(maxHeight, minHeight);
3686 }
3687 }
3688
3689 this.heightStyled = this.height ? this.height + "px" : "";
3690 this.outerHeight = this.element.offsetHeight;
3691 }
3692
3693 calcMinHeight(){
3694 return this.table.options.resizableRows ? this.element.clientHeight : 0;
3695 }
3696
3697 calcMaxHeight(){
3698 var maxHeight = 0;
3699
3700 this.cells.forEach(function(cell){
3701 var height = cell.getHeight();
3702
3703 if(height > maxHeight){
3704 maxHeight = height;
3705 }
3706 });
3707
3708 return maxHeight;
3709 }
3710
3711 //set of cells
3712 setCellHeight(){
3713 this.cells.forEach(function(cell){
3714 cell.setHeight();
3715 });
3716
3717 this.heightInitialized = true;
3718 }
3719
3720 clearCellHeight(){
3721 this.cells.forEach(function(cell){
3722 cell.clearHeight();
3723 });
3724 }
3725
3726 //normalize the height of elements in the row
3727 normalizeHeight(force){
3728 if(force && !this.table.options.rowHeight){
3729 this.clearCellHeight();
3730 }
3731
3732 this.calcHeight(force);
3733
3734 this.setCellHeight();
3735 }
3736
3737 //set height of rows
3738 setHeight(height, force){
3739 if(this.height != height || force){
3740
3741 this.manualHeight = true;
3742
3743 this.height = height;
3744 this.heightStyled = height ? height + "px" : "";
3745
3746 this.setCellHeight();
3747
3748 // this.outerHeight = this.element.outerHeight();
3749 this.outerHeight = this.element.offsetHeight;
3750
3751 if(this.subscribedExternal("rowHeight")){
3752 this.dispatchExternal("rowHeight", this.getComponent());
3753 }
3754 }
3755 }
3756
3757 //return rows outer height
3758 getHeight(){
3759 return this.outerHeight;
3760 }
3761
3762 //return rows outer Width
3763 getWidth(){
3764 return this.element.offsetWidth;
3765 }
3766
3767 //////////////// Cell Management /////////////////
3768 deleteCell(cell){
3769 var index = this.cells.indexOf(cell);
3770
3771 if(index > -1){
3772 this.cells.splice(index, 1);
3773 }
3774 }
3775
3776 //////////////// Data Management /////////////////
3777 setData(data){
3778 this.data = this.chain("row-data-init-before", [this, data], undefined, data);
3779
3780 this.dispatch("row-data-init-after", this);
3781 }
3782
3783 //update the rows data
3784 updateData(updatedData){
3785 var visible = this.element && Helpers.elVisible(this.element),
3786 tempData = {},
3787 newRowData;
3788
3789 return new Promise((resolve, reject) => {
3790
3791 if(typeof updatedData === "string"){
3792 updatedData = JSON.parse(updatedData);
3793 }
3794
3795 this.dispatch("row-data-save-before", this);
3796
3797 if(this.subscribed("row-data-changing")){
3798 tempData = Object.assign(tempData, this.data);
3799 tempData = Object.assign(tempData, updatedData);
3800 }
3801
3802 newRowData = this.chain("row-data-changing", [this, tempData, updatedData], null, updatedData);
3803
3804 //set data
3805 for (let attrname in newRowData) {
3806 this.data[attrname] = newRowData[attrname];
3807 }
3808
3809 this.dispatch("row-data-save-after", this);
3810
3811 //update affected cells only
3812 for (let attrname in updatedData) {
3813
3814 let columns = this.table.columnManager.getColumnsByFieldRoot(attrname);
3815
3816 columns.forEach((column) => {
3817 let cell = this.getCell(column.getField());
3818
3819 if(cell){
3820 let value = column.getFieldValue(newRowData);
3821 if(cell.getValue() !== value){
3822 cell.setValueProcessData(value);
3823
3824 if(visible){
3825 cell.cellRendered();
3826 }
3827 }
3828 }
3829 });
3830 }
3831
3832 //Partial reinitialization if visible
3833 if(visible){
3834 this.normalizeHeight(true);
3835
3836 if(this.table.options.rowFormatter){
3837 this.table.options.rowFormatter(this.getComponent());
3838 }
3839 }else {
3840 this.initialized = false;
3841 this.height = 0;
3842 this.heightStyled = "";
3843 }
3844
3845 this.dispatch("row-data-changed", this, visible, updatedData);
3846
3847 //this.reinitialize();
3848
3849 this.dispatchExternal("rowUpdated", this.getComponent());
3850
3851 if(this.subscribedExternal("dataChanged")){
3852 this.dispatchExternal("dataChanged", this.table.rowManager.getData());
3853 }
3854
3855 resolve();
3856 });
3857 }
3858
3859 getData(transform){
3860 if(transform){
3861 return this.chain("row-data-retrieve", [this, transform], null, this.data);
3862 }
3863
3864 return this.data;
3865 }
3866
3867 getCell(column){
3868 var match = false;
3869
3870 column = this.table.columnManager.findColumn(column);
3871
3872 if(!this.initialized && this.cells.length === 0){
3873 this.generateCells();
3874 }
3875
3876 match = this.cells.find(function(cell){
3877 return cell.column === column;
3878 });
3879
3880 return match;
3881 }
3882
3883 getCellIndex(findCell){
3884 return this.cells.findIndex(function(cell){
3885 return cell === findCell;
3886 });
3887 }
3888
3889 findCell(subject){
3890 return this.cells.find((cell) => {
3891 return cell.element === subject;
3892 });
3893 }
3894
3895 getCells(){
3896 if(!this.initialized && this.cells.length === 0){
3897 this.generateCells();
3898 }
3899
3900 return this.cells;
3901 }
3902
3903 nextRow(){
3904 var row = this.table.rowManager.nextDisplayRow(this, true);
3905 return row || false;
3906 }
3907
3908 prevRow(){
3909 var row = this.table.rowManager.prevDisplayRow(this, true);
3910 return row || false;
3911 }
3912
3913 moveToRow(to, before){
3914 var toRow = this.table.rowManager.findRow(to);
3915
3916 if(toRow){
3917 this.table.rowManager.moveRowActual(this, toRow, !before);
3918 this.table.rowManager.refreshActiveData("display", false, true);
3919 }else {
3920 console.warn("Move Error - No matching row found:", to);
3921 }
3922 }
3923
3924 ///////////////////// Actions /////////////////////
3925 delete(){
3926 this.dispatch("row-delete", this);
3927
3928 this.deleteActual();
3929
3930 return Promise.resolve();
3931 }
3932
3933 deleteActual(blockRedraw){
3934 this.detachModules();
3935
3936 this.table.rowManager.deleteRow(this, blockRedraw);
3937
3938 this.deleteCells();
3939
3940 this.initialized = false;
3941 this.heightInitialized = false;
3942 this.element = false;
3943
3944 this.dispatch("row-deleted", this);
3945 }
3946
3947 detachModules(){
3948 this.dispatch("row-deleting", this);
3949 }
3950
3951 deleteCells(){
3952 var cellCount = this.cells.length;
3953
3954 for(let i = 0; i < cellCount; i++){
3955 this.cells[0].delete();
3956 }
3957 }
3958
3959 wipe(){
3960 this.detachModules();
3961 this.deleteCells();
3962
3963 if(this.element){
3964 while(this.element.firstChild) this.element.removeChild(this.element.firstChild);
3965
3966 if(this.element.parentNode){
3967 this.element.parentNode.removeChild(this.element);
3968 }
3969 }
3970
3971 this.element = false;
3972 this.modules = {};
3973 }
3974
3975 isDisplayed(){
3976 return this.table.rowManager.getDisplayRows().includes(this);
3977 }
3978
3979 getPosition(){
3980 return this.isDisplayed() ? this.position : false;
3981 }
3982
3983 setPosition(position){
3984 if(position != this.position){
3985 this.position = position;
3986
3987 this.positionWatchers.forEach((callback) => {
3988 callback(this.position);
3989 });
3990 }
3991 }
3992
3993 watchPosition(callback){
3994 this.positionWatchers.push(callback);
3995
3996 callback(this.position);
3997 }
3998
3999 getGroup(){
4000 return this.modules.group || false;
4001 }
4002
4003 //////////////// Object Generation /////////////////
4004 getComponent(){
4005 if(!this.component){
4006 this.component = new RowComponent(this);
4007 }
4008
4009 return this.component;
4010 }
4011 }
4012
4013 class BasicVertical extends Renderer{
4014 constructor(table){
4015 super(table);
4016
4017 this.verticalFillMode = "fill";
4018
4019 this.scrollTop = 0;
4020 this.scrollLeft = 0;
4021
4022 this.scrollTop = 0;
4023 this.scrollLeft = 0;
4024 }
4025
4026 clearRows(){
4027 var element = this.tableElement;
4028
4029 // element.children.detach();
4030 while(element.firstChild) element.removeChild(element.firstChild);
4031
4032 element.scrollTop = 0;
4033 element.scrollLeft = 0;
4034
4035 element.style.minWidth = "";
4036 element.style.minHeight = "";
4037 element.style.display = "";
4038 element.style.visibility = "";
4039 }
4040
4041 renderRows() {
4042 var element = this.tableElement,
4043 onlyGroupHeaders = true,
4044 tableFrag = document.createDocumentFragment(),
4045 rows = this.rows();
4046
4047 rows.forEach((row, index) => {
4048 this.styleRow(row, index);
4049 row.initialize(false, true);
4050
4051 if (row.type !== "group") {
4052 onlyGroupHeaders = false;
4053 }
4054
4055 tableFrag.appendChild(row.getElement());
4056 });
4057
4058 element.appendChild(tableFrag);
4059
4060 rows.forEach((row) => {
4061 row.rendered();
4062
4063 if(!row.heightInitialized) {
4064 row.calcHeight(true);
4065 }
4066 });
4067
4068 rows.forEach((row) => {
4069 if(!row.heightInitialized) {
4070 row.setCellHeight();
4071 }
4072 });
4073
4074 if(onlyGroupHeaders){
4075 element.style.minWidth = this.table.columnManager.getWidth() + "px";
4076 }else {
4077 element.style.minWidth = "";
4078 }
4079 }
4080
4081
4082 rerenderRows(callback){
4083 this.clearRows();
4084
4085 if(callback){
4086 callback();
4087 }
4088
4089 this.renderRows();
4090
4091 if(!this.rows().length){
4092 this.table.rowManager.tableEmpty();
4093 }
4094 }
4095
4096 scrollToRowNearestTop(row){
4097 var rowTop = Helpers.elOffset(row.getElement()).top;
4098
4099 return !(Math.abs(this.elementVertical.scrollTop - rowTop) > Math.abs(this.elementVertical.scrollTop + this.elementVertical.clientHeight - rowTop));
4100 }
4101
4102 scrollToRow(row){
4103 var rowEl = row.getElement();
4104
4105 this.elementVertical.scrollTop = Helpers.elOffset(rowEl).top - Helpers.elOffset(this.elementVertical).top + this.elementVertical.scrollTop;
4106 }
4107
4108 visibleRows(includingBuffer){
4109 return this.rows();
4110 }
4111
4112 }
4113
4114 class VirtualDomVertical extends Renderer{
4115 constructor(table){
4116 super(table);
4117
4118 this.verticalFillMode = "fill";
4119
4120 this.scrollTop = 0;
4121 this.scrollLeft = 0;
4122
4123 this.vDomRowHeight = 20; //approximation of row heights for padding
4124
4125 this.vDomTop = 0; //hold position for first rendered row in the virtual DOM
4126 this.vDomBottom = 0; //hold position for last rendered row in the virtual DOM
4127
4128 this.vDomScrollPosTop = 0; //last scroll position of the vDom top;
4129 this.vDomScrollPosBottom = 0; //last scroll position of the vDom bottom;
4130
4131 this.vDomTopPad = 0; //hold value of padding for top of virtual DOM
4132 this.vDomBottomPad = 0; //hold value of padding for bottom of virtual DOM
4133
4134 this.vDomMaxRenderChain = 90; //the maximum number of dom elements that can be rendered in 1 go
4135
4136 this.vDomWindowBuffer = 0; //window row buffer before removing elements, to smooth scrolling
4137
4138 this.vDomWindowMinTotalRows = 20; //minimum number of rows to be generated in virtual dom (prevent buffering issues on tables with tall rows)
4139 this.vDomWindowMinMarginRows = 5; //minimum number of rows to be generated in virtual dom margin
4140
4141 this.vDomTopNewRows = []; //rows to normalize after appending to optimize render speed
4142 this.vDomBottomNewRows = []; //rows to normalize after appending to optimize render speed
4143 }
4144
4145 //////////////////////////////////////
4146 ///////// Public Functions ///////////
4147 //////////////////////////////////////
4148
4149 clearRows(){
4150 var element = this.tableElement;
4151
4152 // element.children.detach();
4153 while(element.firstChild) element.removeChild(element.firstChild);
4154
4155 element.style.paddingTop = "";
4156 element.style.paddingBottom = "";
4157 element.style.minHeight = "";
4158 element.style.display = "";
4159 element.style.visibility = "";
4160
4161 this.elementVertical.scrollTop = 0;
4162 this.elementVertical.scrollLeft = 0;
4163
4164 this.scrollTop = 0;
4165 this.scrollLeft = 0;
4166
4167 this.vDomTop = 0;
4168 this.vDomBottom = 0;
4169 this.vDomTopPad = 0;
4170 this.vDomBottomPad = 0;
4171 this.vDomScrollPosTop = 0;
4172 this.vDomScrollPosBottom = 0;
4173 }
4174
4175 renderRows(){
4176 this._virtualRenderFill();
4177 }
4178
4179 rerenderRows(callback){
4180 var scrollTop = this.elementVertical.scrollTop;
4181 var topRow = false;
4182 var topOffset = false;
4183
4184 var left = this.table.rowManager.scrollLeft;
4185
4186 var rows = this.rows();
4187
4188 for(var i = this.vDomTop; i <= this.vDomBottom; i++){
4189
4190 if(rows[i]){
4191 var diff = scrollTop - rows[i].getElement().offsetTop;
4192
4193 if(topOffset === false || Math.abs(diff) < topOffset){
4194 topOffset = diff;
4195 topRow = i;
4196 }else {
4197 break;
4198 }
4199 }
4200 }
4201
4202 rows.forEach((row) => {
4203 row.deinitializeHeight();
4204 });
4205
4206 if(callback){
4207 callback();
4208 }
4209
4210 if(this.rows().length){
4211 this._virtualRenderFill((topRow === false ? this.rows.length - 1 : topRow), true, topOffset || 0);
4212 }else {
4213 this.clear();
4214 this.table.rowManager.tableEmpty();
4215 }
4216
4217 this.scrollColumns(left);
4218 }
4219
4220 scrollColumns(left){
4221 this.table.rowManager.scrollHorizontal(left);
4222 }
4223
4224 scrollRows(top, dir){
4225 var topDiff = top - this.vDomScrollPosTop;
4226 var bottomDiff = top - this.vDomScrollPosBottom;
4227 var margin = this.vDomWindowBuffer * 2;
4228 var rows = this.rows();
4229
4230 this.scrollTop = top;
4231
4232 if(-topDiff > margin || bottomDiff > margin){
4233 //if big scroll redraw table;
4234 var left = this.table.rowManager.scrollLeft;
4235 this._virtualRenderFill(Math.floor((this.elementVertical.scrollTop / this.elementVertical.scrollHeight) * rows.length));
4236 this.scrollColumns(left);
4237 }else {
4238
4239 if(dir){
4240 //scrolling up
4241 if(topDiff < 0){
4242 this._addTopRow(rows, -topDiff);
4243 }
4244
4245 if(bottomDiff < 0){
4246 //hide bottom row if needed
4247 if(this.vDomScrollHeight - this.scrollTop > this.vDomWindowBuffer){
4248 this._removeBottomRow(rows, -bottomDiff);
4249 }else {
4250 this.vDomScrollPosBottom = this.scrollTop;
4251 }
4252 }
4253 }else {
4254
4255 if(bottomDiff >= 0){
4256 this._addBottomRow(rows, bottomDiff);
4257 }
4258
4259 //scrolling down
4260 if(topDiff >= 0){
4261 //hide top row if needed
4262 if(this.scrollTop > this.vDomWindowBuffer){
4263 this._removeTopRow(rows, topDiff);
4264 }else {
4265 this.vDomScrollPosTop = this.scrollTop;
4266 }
4267 }
4268 }
4269 }
4270 }
4271
4272 resize(){
4273 this.vDomWindowBuffer = this.table.options.renderVerticalBuffer || this.elementVertical.clientHeight;
4274 }
4275
4276 scrollToRowNearestTop(row){
4277 var rowIndex = this.rows().indexOf(row);
4278
4279 return !(Math.abs(this.vDomTop - rowIndex) > Math.abs(this.vDomBottom - rowIndex));
4280 }
4281
4282 scrollToRow(row){
4283 var index = this.rows().indexOf(row);
4284
4285 if(index > -1){
4286 this._virtualRenderFill(index, true);
4287 }
4288 }
4289
4290 visibleRows(includingBuffer){
4291 var topEdge = this.elementVertical.scrollTop,
4292 bottomEdge = this.elementVertical.clientHeight + topEdge,
4293 topFound = false,
4294 topRow = 0,
4295 bottomRow = 0,
4296 rows = this.rows();
4297
4298 if(includingBuffer){
4299 topRow = this.vDomTop;
4300 bottomRow = this.vDomBottom;
4301 }else {
4302 for(var i = this.vDomTop; i <= this.vDomBottom; i++){
4303 if(rows[i]){
4304 if(!topFound){
4305 if((topEdge - rows[i].getElement().offsetTop) >= 0){
4306 topRow = i;
4307 }else {
4308 topFound = true;
4309
4310 if(bottomEdge - rows[i].getElement().offsetTop >= 0){
4311 bottomRow = i;
4312 }else {
4313 break;
4314 }
4315 }
4316 }else {
4317 if(bottomEdge - rows[i].getElement().offsetTop >= 0){
4318 bottomRow = i;
4319 }else {
4320 break;
4321 }
4322 }
4323 }
4324 }
4325 }
4326
4327 return rows.slice(topRow, bottomRow + 1);
4328 }
4329
4330 //////////////////////////////////////
4331 //////// Internal Rendering //////////
4332 //////////////////////////////////////
4333
4334 //full virtual render
4335 _virtualRenderFill(position, forceMove, offset) {
4336 var element = this.tableElement,
4337 holder = this.elementVertical,
4338 topPad = 0,
4339 rowsHeight = 0,
4340 rowHeight = 0,
4341 heightOccupied = 0,
4342 topPadHeight = 0,
4343 i = 0,
4344 rows = this.rows(),
4345 rowsCount = rows.length,
4346 index = 0,
4347 row,
4348 rowFragment,
4349 renderedRows = [],
4350 totalRowsRendered = 0,
4351 rowsToRender = 0,
4352 fixedHeight = this.table.rowManager.fixedHeight,
4353 containerHeight = this.elementVertical.clientHeight,
4354 avgRowHeight = this.table.options.rowHeight,
4355 resized = true;
4356
4357 position = position || 0;
4358
4359 offset = offset || 0;
4360
4361 if(!position){
4362 this.clear();
4363 }else {
4364 while(element.firstChild) element.removeChild(element.firstChild);
4365
4366 //check if position is too close to bottom of table
4367 heightOccupied = (rowsCount - position + 1) * this.vDomRowHeight;
4368
4369 if(heightOccupied < containerHeight){
4370 position -= Math.ceil((containerHeight - heightOccupied) / this.vDomRowHeight);
4371 if(position < 0){
4372 position = 0;
4373 }
4374 }
4375
4376 //calculate initial pad
4377 topPad = Math.min(Math.max(Math.floor(this.vDomWindowBuffer / this.vDomRowHeight), this.vDomWindowMinMarginRows), position);
4378 position -= topPad;
4379 }
4380
4381 if(rowsCount && Helpers.elVisible(this.elementVertical)){
4382 this.vDomTop = position;
4383 this.vDomBottom = position -1;
4384
4385 if(fixedHeight || this.table.options.maxHeight) {
4386 if(avgRowHeight) {
4387 rowsToRender = (containerHeight / avgRowHeight) + (this.vDomWindowBuffer / avgRowHeight);
4388 }
4389 rowsToRender = Math.max(this.vDomWindowMinTotalRows, Math.ceil(rowsToRender));
4390 }
4391 else {
4392 rowsToRender = rowsCount;
4393 }
4394
4395 while(((rowsToRender == rowsCount || rowsHeight <= containerHeight + this.vDomWindowBuffer) || totalRowsRendered < this.vDomWindowMinTotalRows) && this.vDomBottom < rowsCount -1) {
4396 renderedRows = [];
4397 rowFragment = document.createDocumentFragment();
4398
4399 i = 0;
4400
4401 while ((i < rowsToRender) && this.vDomBottom < rowsCount -1) {
4402 index = this.vDomBottom + 1,
4403 row = rows[index];
4404
4405 this.styleRow(row, index);
4406
4407 row.initialize(false, true);
4408 if(!row.heightInitialized && !this.table.options.rowHeight){
4409 row.clearCellHeight();
4410 }
4411
4412 rowFragment.appendChild(row.getElement());
4413 renderedRows.push(row);
4414 this.vDomBottom ++;
4415 i++;
4416 }
4417
4418 if(!renderedRows.length){
4419 break;
4420 }
4421
4422 element.appendChild(rowFragment);
4423
4424 // NOTE: The next 3 loops are separate on purpose
4425 // This is to batch up the dom writes and reads which drastically improves performance
4426
4427 renderedRows.forEach((row) => {
4428 row.rendered();
4429
4430 if(!row.heightInitialized) {
4431 row.calcHeight(true);
4432 }
4433 });
4434
4435 renderedRows.forEach((row) => {
4436 if(!row.heightInitialized) {
4437 row.setCellHeight();
4438 }
4439 });
4440
4441 renderedRows.forEach((row) => {
4442 rowHeight = row.getHeight();
4443
4444 if(totalRowsRendered < topPad){
4445 topPadHeight += rowHeight;
4446 }else {
4447 rowsHeight += rowHeight;
4448 }
4449
4450 if(rowHeight > this.vDomWindowBuffer){
4451 this.vDomWindowBuffer = rowHeight * 2;
4452 }
4453 totalRowsRendered++;
4454 });
4455
4456 resized = this.table.rowManager.adjustTableSize();
4457 containerHeight = this.elementVertical.clientHeight;
4458 if(resized && (fixedHeight || this.table.options.maxHeight))
4459 {
4460 avgRowHeight = rowsHeight / totalRowsRendered;
4461 rowsToRender = Math.max(this.vDomWindowMinTotalRows, Math.ceil((containerHeight / avgRowHeight) + (this.vDomWindowBuffer / avgRowHeight)));
4462 }
4463 }
4464
4465 if(!position){
4466 this.vDomTopPad = 0;
4467 //adjust row height to match average of rendered elements
4468 this.vDomRowHeight = Math.floor((rowsHeight + topPadHeight) / totalRowsRendered);
4469 this.vDomBottomPad = this.vDomRowHeight * (rowsCount - this.vDomBottom -1);
4470
4471 this.vDomScrollHeight = topPadHeight + rowsHeight + this.vDomBottomPad - containerHeight;
4472 }else {
4473 this.vDomTopPad = !forceMove ? this.scrollTop - topPadHeight : (this.vDomRowHeight * this.vDomTop) + offset;
4474 this.vDomBottomPad = this.vDomBottom == rowsCount-1 ? 0 : Math.max(this.vDomScrollHeight - this.vDomTopPad - rowsHeight - topPadHeight, 0);
4475 }
4476
4477 element.style.paddingTop = this.vDomTopPad+"px";
4478 element.style.paddingBottom = this.vDomBottomPad+"px";
4479
4480 if(forceMove){
4481 this.scrollTop = this.vDomTopPad + (topPadHeight) + offset - (this.elementVertical.scrollWidth > this.elementVertical.clientWidth ? this.elementVertical.offsetHeight - containerHeight : 0);
4482 }
4483
4484 this.scrollTop = Math.min(this.scrollTop, this.elementVertical.scrollHeight - containerHeight);
4485
4486 //adjust for horizontal scrollbar if present (and not at top of table)
4487 if(this.elementVertical.scrollWidth > this.elementVertical.clientWidth && forceMove){
4488 this.scrollTop += this.elementVertical.offsetHeight - containerHeight;
4489 }
4490
4491 this.vDomScrollPosTop = this.scrollTop;
4492 this.vDomScrollPosBottom = this.scrollTop;
4493
4494 holder.scrollTop = this.scrollTop;
4495
4496 this.dispatch("render-virtual-fill");
4497 }
4498 }
4499
4500 _addTopRow(rows, fillableSpace){
4501 var table = this.tableElement,
4502 addedRows = [],
4503 paddingAdjust = 0,
4504 index = this.vDomTop -1,
4505 i = 0,
4506 working = true;
4507
4508 while(working){
4509 if(this.vDomTop){
4510 let row = rows[index],
4511 rowHeight, initialized;
4512
4513 if(row && i < this.vDomMaxRenderChain){
4514 rowHeight = row.getHeight() || this.vDomRowHeight;
4515 initialized = row.initialized;
4516
4517 if(fillableSpace >= rowHeight){
4518
4519 this.styleRow(row, index);
4520 table.insertBefore(row.getElement(), table.firstChild);
4521
4522 if(!row.initialized || !row.heightInitialized){
4523 addedRows.push(row);
4524 }
4525
4526 row.initialize();
4527
4528 if(!initialized){
4529 rowHeight = row.getElement().offsetHeight;
4530
4531 if(rowHeight > this.vDomWindowBuffer){
4532 this.vDomWindowBuffer = rowHeight * 2;
4533 }
4534 }
4535
4536 fillableSpace -= rowHeight;
4537 paddingAdjust += rowHeight;
4538
4539 this.vDomTop--;
4540 index--;
4541 i++;
4542
4543 }else {
4544 working = false;
4545 }
4546
4547 }else {
4548 working = false;
4549 }
4550
4551 }else {
4552 working = false;
4553 }
4554 }
4555
4556 for (let row of addedRows){
4557 row.clearCellHeight();
4558 }
4559
4560 this._quickNormalizeRowHeight(addedRows);
4561
4562 if(paddingAdjust){
4563 this.vDomTopPad -= paddingAdjust;
4564
4565 if(this.vDomTopPad < 0){
4566 this.vDomTopPad = index * this.vDomRowHeight;
4567 }
4568
4569 if(index < 1){
4570 this.vDomTopPad = 0;
4571 }
4572
4573 table.style.paddingTop = this.vDomTopPad + "px";
4574 this.vDomScrollPosTop -= paddingAdjust;
4575 }
4576 }
4577
4578 _removeTopRow(rows, fillableSpace){
4579 var removableRows = [],
4580 paddingAdjust = 0,
4581 i = 0,
4582 working = true;
4583
4584 while(working){
4585 let row = rows[this.vDomTop],
4586 rowHeight;
4587
4588 if(row && i < this.vDomMaxRenderChain){
4589 rowHeight = row.getHeight() || this.vDomRowHeight;
4590
4591 if(fillableSpace >= rowHeight){
4592 this.vDomTop++;
4593
4594 fillableSpace -= rowHeight;
4595 paddingAdjust += rowHeight;
4596
4597 removableRows.push(row);
4598 i++;
4599 }else {
4600 working = false;
4601 }
4602 }else {
4603 working = false;
4604 }
4605 }
4606
4607 for (let row of removableRows){
4608 let rowEl = row.getElement();
4609
4610 if(rowEl.parentNode){
4611 rowEl.parentNode.removeChild(rowEl);
4612 }
4613 }
4614
4615 if(paddingAdjust){
4616 this.vDomTopPad += paddingAdjust;
4617 this.tableElement.style.paddingTop = this.vDomTopPad + "px";
4618 this.vDomScrollPosTop += this.vDomTop ? paddingAdjust : paddingAdjust + this.vDomWindowBuffer;
4619 }
4620 }
4621
4622 _addBottomRow(rows, fillableSpace){
4623 var table = this.tableElement,
4624 addedRows = [],
4625 paddingAdjust = 0,
4626 index = this.vDomBottom + 1,
4627 i = 0,
4628 working = true;
4629
4630 while(working){
4631 let row = rows[index],
4632 rowHeight, initialized;
4633
4634 if(row && i < this.vDomMaxRenderChain){
4635 rowHeight = row.getHeight() || this.vDomRowHeight;
4636 initialized = row.initialized;
4637
4638 if(fillableSpace >= rowHeight){
4639
4640 this.styleRow(row, index);
4641 table.appendChild(row.getElement());
4642
4643 if(!row.initialized || !row.heightInitialized){
4644 addedRows.push(row);
4645 }
4646
4647 row.initialize();
4648
4649 if(!initialized){
4650 rowHeight = row.getElement().offsetHeight;
4651
4652 if(rowHeight > this.vDomWindowBuffer){
4653 this.vDomWindowBuffer = rowHeight * 2;
4654 }
4655 }
4656
4657 fillableSpace -= rowHeight;
4658 paddingAdjust += rowHeight;
4659
4660 this.vDomBottom++;
4661 index++;
4662 i++;
4663 }else {
4664 working = false;
4665 }
4666 }else {
4667 working = false;
4668 }
4669 }
4670
4671 for (let row of addedRows){
4672 row.clearCellHeight();
4673 }
4674
4675 this._quickNormalizeRowHeight(addedRows);
4676
4677 if(paddingAdjust){
4678 this.vDomBottomPad -= paddingAdjust;
4679
4680 if(this.vDomBottomPad < 0 || index == rows.length -1){
4681 this.vDomBottomPad = 0;
4682 }
4683
4684 table.style.paddingBottom = this.vDomBottomPad + "px";
4685 this.vDomScrollPosBottom += paddingAdjust;
4686 }
4687 }
4688
4689 _removeBottomRow(rows, fillableSpace){
4690 var removableRows = [],
4691 paddingAdjust = 0,
4692 i = 0,
4693 working = true;
4694
4695 while(working){
4696 let row = rows[this.vDomBottom],
4697 rowHeight;
4698
4699 if(row && i < this.vDomMaxRenderChain){
4700 rowHeight = row.getHeight() || this.vDomRowHeight;
4701
4702 if(fillableSpace >= rowHeight){
4703 this.vDomBottom --;
4704
4705 fillableSpace -= rowHeight;
4706 paddingAdjust += rowHeight;
4707
4708 removableRows.push(row);
4709 i++;
4710 }else {
4711 working = false;
4712 }
4713 }else {
4714 working = false;
4715 }
4716 }
4717
4718 for (let row of removableRows){
4719 let rowEl = row.getElement();
4720
4721 if(rowEl.parentNode){
4722 rowEl.parentNode.removeChild(rowEl);
4723 }
4724 }
4725
4726 if(paddingAdjust){
4727 this.vDomBottomPad += paddingAdjust;
4728
4729 if(this.vDomBottomPad < 0){
4730 this.vDomBottomPad = 0;
4731 }
4732
4733 this.tableElement.style.paddingBottom = this.vDomBottomPad + "px";
4734 this.vDomScrollPosBottom -= paddingAdjust;
4735 }
4736 }
4737
4738 _quickNormalizeRowHeight(rows){
4739 for(let row of rows){
4740 row.calcHeight();
4741 }
4742
4743 for(let row of rows){
4744 row.setCellHeight();
4745 }
4746 }
4747 }
4748
4749 class RowManager extends CoreFeature{
4750
4751 constructor(table){
4752 super(table);
4753
4754 this.element = this.createHolderElement(); //containing element
4755 this.tableElement = this.createTableElement(); //table element
4756 this.heightFixer = this.createTableElement(); //table element
4757 this.placeholder = null; //placeholder element
4758 this.placeholderContents = null; //placeholder element
4759
4760 this.firstRender = false; //handle first render
4761 this.renderMode = "virtual"; //current rendering mode
4762 this.fixedHeight = false; //current rendering mode
4763
4764 this.rows = []; //hold row data objects
4765 this.activeRowsPipeline = []; //hold calculation of active rows
4766 this.activeRows = []; //rows currently available to on display in the table
4767 this.activeRowsCount = 0; //count of active rows
4768
4769 this.displayRows = []; //rows currently on display in the table
4770 this.displayRowsCount = 0; //count of display rows
4771
4772 this.scrollTop = 0;
4773 this.scrollLeft = 0;
4774
4775 this.redrawBlock = false; //prevent redraws to allow multiple data manipulations before continuing
4776 this.redrawBlockRestoreConfig = false; //store latest redraw function calls for when redraw is needed
4777 this.redrawBlockRenderInPosition = false; //store latest redraw function calls for when redraw is needed
4778
4779 this.dataPipeline = []; //hold data pipeline tasks
4780 this.displayPipeline = []; //hold data display pipeline tasks
4781
4782 this.scrollbarWidth = 0;
4783
4784 this.renderer = null;
4785 }
4786
4787 //////////////// Setup Functions /////////////////
4788
4789 createHolderElement (){
4790 var el = document.createElement("div");
4791
4792 el.classList.add("tabulator-tableholder");
4793 el.setAttribute("tabindex", 0);
4794 // el.setAttribute("role", "rowgroup");
4795
4796 return el;
4797 }
4798
4799 createTableElement (){
4800 var el = document.createElement("div");
4801
4802 el.classList.add("tabulator-table");
4803 el.setAttribute("role", "rowgroup");
4804
4805 return el;
4806 }
4807
4808 initializePlaceholder(){
4809 var placeholder = this.table.options.placeholder;
4810
4811 if(typeof placeholder === "function"){
4812 placeholder = placeholder.call(this.table);
4813 }
4814
4815 placeholder = this.chain("placeholder", [placeholder], placeholder, placeholder) || placeholder;
4816
4817 //configure placeholder element
4818 if(placeholder){
4819 let el = document.createElement("div");
4820 el.classList.add("tabulator-placeholder");
4821
4822 if(typeof placeholder == "string"){
4823 let contents = document.createElement("div");
4824 contents.classList.add("tabulator-placeholder-contents");
4825 contents.innerHTML = placeholder;
4826
4827 el.appendChild(contents);
4828
4829 this.placeholderContents = contents;
4830
4831 }else if(typeof HTMLElement !== "undefined" && placeholder instanceof HTMLElement){
4832
4833 el.appendChild(placeholder);
4834 this.placeholderContents = placeholder;
4835 }else {
4836 console.warn("Invalid placeholder provided, must be string or HTML Element", placeholder);
4837
4838 this.el = null;
4839 }
4840
4841 this.placeholder = el;
4842 }
4843 }
4844
4845 //return containing element
4846 getElement(){
4847 return this.element;
4848 }
4849
4850 //return table element
4851 getTableElement(){
4852 return this.tableElement;
4853 }
4854
4855 initialize(){
4856 this.initializePlaceholder();
4857 this.initializeRenderer();
4858
4859 //initialize manager
4860 this.element.appendChild(this.tableElement);
4861
4862 this.firstRender = true;
4863
4864 //scroll header along with table body
4865 this.element.addEventListener("scroll", () => {
4866 var left = this.element.scrollLeft,
4867 leftDir = this.scrollLeft > left,
4868 top = this.element.scrollTop,
4869 topDir = this.scrollTop > top;
4870
4871 //handle horizontal scrolling
4872 if(this.scrollLeft != left){
4873 this.scrollLeft = left;
4874
4875 this.dispatch("scroll-horizontal", left, leftDir);
4876 this.dispatchExternal("scrollHorizontal", left, leftDir);
4877
4878 this._positionPlaceholder();
4879 }
4880
4881 //handle vertical scrolling
4882 if(this.scrollTop != top){
4883 this.scrollTop = top;
4884
4885 this.renderer.scrollRows(top, topDir);
4886
4887 this.dispatch("scroll-vertical", top, topDir);
4888 this.dispatchExternal("scrollVertical", top, topDir);
4889 }
4890 });
4891 }
4892
4893 ////////////////// Row Manipulation //////////////////
4894 findRow(subject){
4895 if(typeof subject == "object"){
4896 if(subject instanceof Row){
4897 //subject is row element
4898 return subject;
4899 }else if(subject instanceof RowComponent){
4900 //subject is public row component
4901 return subject._getSelf() || false;
4902 }else if(typeof HTMLElement !== "undefined" && subject instanceof HTMLElement){
4903 //subject is a HTML element of the row
4904 let match = this.rows.find((row) => {
4905 return row.getElement() === subject;
4906 });
4907
4908 return match || false;
4909 }else if(subject === null){
4910 return false;
4911 }
4912 }else if(typeof subject == "undefined"){
4913 return false;
4914 }else {
4915 //subject should be treated as the index of the row
4916 let match = this.rows.find((row) => {
4917 return row.data[this.table.options.index] == subject;
4918 });
4919
4920 return match || false;
4921 }
4922
4923 //catch all for any other type of input
4924 return false;
4925 }
4926
4927 getRowFromDataObject(data){
4928 var match = this.rows.find((row) => {
4929 return row.data === data;
4930 });
4931
4932 return match || false;
4933 }
4934
4935 getRowFromPosition(position){
4936 return this.getDisplayRows().find((row) => {
4937 return row.type === "row" && row.getPosition() === position && row.isDisplayed();
4938 });
4939 }
4940
4941 scrollToRow(row, position, ifVisible){
4942 return this.renderer.scrollToRowPosition(row, position, ifVisible);
4943 }
4944
4945 ////////////////// Data Handling //////////////////
4946 setData(data, renderInPosition, columnsChanged){
4947 return new Promise((resolve, reject)=>{
4948 if(renderInPosition && this.getDisplayRows().length){
4949 if(this.table.options.pagination){
4950 this._setDataActual(data, true);
4951 }else {
4952 this.reRenderInPosition(() => {
4953 this._setDataActual(data);
4954 });
4955 }
4956 }else {
4957 if(this.table.options.autoColumns && columnsChanged && this.table.initialized){
4958 this.table.columnManager.generateColumnsFromRowData(data);
4959 }
4960 this.resetScroll();
4961
4962 this._setDataActual(data);
4963 }
4964
4965 resolve();
4966 });
4967 }
4968
4969 _setDataActual(data, renderInPosition){
4970 this.dispatchExternal("dataProcessing", data);
4971
4972 this._wipeElements();
4973
4974 if(Array.isArray(data)){
4975 this.dispatch("data-processing", data);
4976
4977 data.forEach((def, i) => {
4978 if(def && typeof def === "object"){
4979 var row = new Row(def, this);
4980 this.rows.push(row);
4981 }else {
4982 console.warn("Data Loading Warning - Invalid row data detected and ignored, expecting object but received:", def);
4983 }
4984 });
4985
4986 this.refreshActiveData(false, false, renderInPosition);
4987
4988 this.dispatch("data-processed", data);
4989 this.dispatchExternal("dataProcessed", data);
4990 }else {
4991 console.error("Data Loading Error - Unable to process data due to invalid data type \nExpecting: array \nReceived: ", typeof data, "\nData: ", data);
4992 }
4993 }
4994
4995 _wipeElements(){
4996 this.dispatch("rows-wipe");
4997
4998 this.destroy();
4999
5000 this.adjustTableSize();
5001
5002 this.dispatch("rows-wiped");
5003 }
5004
5005 destroy(){
5006 this.rows.forEach((row) => {
5007 row.wipe();
5008 });
5009
5010 this.rows = [];
5011 this.activeRows = [];
5012 this.activeRowsPipeline = [];
5013 this.activeRowsCount = 0;
5014 this.displayRows = [];
5015 this.displayRowsCount = 0;
5016 }
5017
5018 deleteRow(row, blockRedraw){
5019 var allIndex = this.rows.indexOf(row),
5020 activeIndex = this.activeRows.indexOf(row);
5021
5022 if(activeIndex > -1){
5023 this.activeRows.splice(activeIndex, 1);
5024 }
5025
5026 if(allIndex > -1){
5027 this.rows.splice(allIndex, 1);
5028 }
5029
5030 this.setActiveRows(this.activeRows);
5031
5032 this.displayRowIterator((rows) => {
5033 var displayIndex = rows.indexOf(row);
5034
5035 if(displayIndex > -1){
5036 rows.splice(displayIndex, 1);
5037 }
5038 });
5039
5040 if(!blockRedraw){
5041 this.reRenderInPosition();
5042 }
5043
5044 this.regenerateRowPositions();
5045
5046 this.dispatchExternal("rowDeleted", row.getComponent());
5047
5048 if(!this.displayRowsCount){
5049 this.tableEmpty();
5050 }
5051
5052 if(this.subscribedExternal("dataChanged")){
5053 this.dispatchExternal("dataChanged", this.getData());
5054 }
5055 }
5056
5057 addRow(data, pos, index, blockRedraw){
5058 var row = this.addRowActual(data, pos, index, blockRedraw);
5059 return row;
5060 }
5061
5062 //add multiple rows
5063 addRows(data, pos, index, refreshDisplayOnly){
5064 var rows = [];
5065
5066 return new Promise((resolve, reject) => {
5067 pos = this.findAddRowPos(pos);
5068
5069 if(!Array.isArray(data)){
5070 data = [data];
5071 }
5072
5073 if((typeof index == "undefined" && pos) || (typeof index !== "undefined" && !pos)){
5074 data.reverse();
5075 }
5076
5077 data.forEach((item, i) => {
5078 var row = this.addRow(item, pos, index, true);
5079 rows.push(row);
5080 this.dispatch("row-added", row, item, pos, index);
5081 });
5082
5083 this.refreshActiveData(refreshDisplayOnly ? "displayPipeline" : false, false, true);
5084
5085 this.regenerateRowPositions();
5086
5087 if(this.displayRowsCount){
5088 this._clearPlaceholder();
5089 }
5090
5091 resolve(rows);
5092 });
5093 }
5094
5095 findAddRowPos(pos){
5096 if(typeof pos === "undefined"){
5097 pos = this.table.options.addRowPos;
5098 }
5099
5100 if(pos === "pos"){
5101 pos = true;
5102 }
5103
5104 if(pos === "bottom"){
5105 pos = false;
5106 }
5107
5108 return pos;
5109 }
5110
5111 addRowActual(data, pos, index, blockRedraw){
5112 var row = data instanceof Row ? data : new Row(data || {}, this),
5113 top = this.findAddRowPos(pos),
5114 allIndex = -1,
5115 activeIndex, chainResult;
5116
5117 if(!index){
5118 chainResult = this.chain("row-adding-position", [row, top], null, {index, top});
5119
5120 index = chainResult.index;
5121 top = chainResult.top;
5122 }
5123
5124 if(typeof index !== "undefined"){
5125 index = this.findRow(index);
5126 }
5127
5128 index = this.chain("row-adding-index", [row, index, top], null, index);
5129
5130 if(index){
5131 allIndex = this.rows.indexOf(index);
5132 }
5133
5134 if(index && allIndex > -1){
5135 activeIndex = this.activeRows.indexOf(index);
5136
5137 this.displayRowIterator(function(rows){
5138 var displayIndex = rows.indexOf(index);
5139
5140 if(displayIndex > -1){
5141 rows.splice((top ? displayIndex : displayIndex + 1), 0, row);
5142 }
5143 });
5144
5145 if(activeIndex > -1){
5146 this.activeRows.splice((top ? activeIndex : activeIndex + 1), 0, row);
5147 }
5148
5149 this.rows.splice((top ? allIndex : allIndex + 1), 0, row);
5150
5151 }else {
5152
5153 if(top){
5154
5155 this.displayRowIterator(function(rows){
5156 rows.unshift(row);
5157 });
5158
5159 this.activeRows.unshift(row);
5160 this.rows.unshift(row);
5161 }else {
5162 this.displayRowIterator(function(rows){
5163 rows.push(row);
5164 });
5165
5166 this.activeRows.push(row);
5167 this.rows.push(row);
5168 }
5169 }
5170
5171 this.setActiveRows(this.activeRows);
5172
5173 this.dispatchExternal("rowAdded", row.getComponent());
5174
5175 if(this.subscribedExternal("dataChanged")){
5176 this.dispatchExternal("dataChanged", this.table.rowManager.getData());
5177 }
5178
5179 if(!blockRedraw){
5180 this.reRenderInPosition();
5181 }
5182
5183 return row;
5184 }
5185
5186 moveRow(from, to, after){
5187 this.dispatch("row-move", from, to, after);
5188
5189 this.moveRowActual(from, to, after);
5190
5191 this.regenerateRowPositions();
5192
5193 this.dispatch("row-moved", from, to, after);
5194 this.dispatchExternal("rowMoved", from.getComponent());
5195 }
5196
5197 moveRowActual(from, to, after){
5198 this.moveRowInArray(this.rows, from, to, after);
5199 this.moveRowInArray(this.activeRows, from, to, after);
5200
5201 this.displayRowIterator((rows) => {
5202 this.moveRowInArray(rows, from, to, after);
5203 });
5204
5205 this.dispatch("row-moving", from, to, after);
5206 }
5207
5208 moveRowInArray(rows, from, to, after){
5209 var fromIndex, toIndex, start, end;
5210
5211 if(from !== to){
5212
5213 fromIndex = rows.indexOf(from);
5214
5215 if (fromIndex > -1) {
5216
5217 rows.splice(fromIndex, 1);
5218
5219 toIndex = rows.indexOf(to);
5220
5221 if (toIndex > -1) {
5222
5223 if(after){
5224 rows.splice(toIndex+1, 0, from);
5225 }else {
5226 rows.splice(toIndex, 0, from);
5227 }
5228
5229 }else {
5230 rows.splice(fromIndex, 0, from);
5231 }
5232 }
5233
5234 //restyle rows
5235 if(rows === this.getDisplayRows()){
5236
5237 start = fromIndex < toIndex ? fromIndex : toIndex;
5238 end = toIndex > fromIndex ? toIndex : fromIndex +1;
5239
5240 for(let i = start; i <= end; i++){
5241 if(rows[i]){
5242 this.styleRow(rows[i], i);
5243 }
5244 }
5245 }
5246 }
5247 }
5248
5249 clearData(){
5250 this.setData([]);
5251 }
5252
5253 getRowIndex(row){
5254 return this.findRowIndex(row, this.rows);
5255 }
5256
5257 getDisplayRowIndex(row){
5258 var index = this.getDisplayRows().indexOf(row);
5259 return index > -1 ? index : false;
5260 }
5261
5262 nextDisplayRow(row, rowOnly){
5263 var index = this.getDisplayRowIndex(row),
5264 nextRow = false;
5265
5266
5267 if(index !== false && index < this.displayRowsCount -1){
5268 nextRow = this.getDisplayRows()[index+1];
5269 }
5270
5271 if(nextRow && (!(nextRow instanceof Row) || nextRow.type != "row")){
5272 return this.nextDisplayRow(nextRow, rowOnly);
5273 }
5274
5275 return nextRow;
5276 }
5277
5278 prevDisplayRow(row, rowOnly){
5279 var index = this.getDisplayRowIndex(row),
5280 prevRow = false;
5281
5282 if(index){
5283 prevRow = this.getDisplayRows()[index-1];
5284 }
5285
5286 if(rowOnly && prevRow && (!(prevRow instanceof Row) || prevRow.type != "row")){
5287 return this.prevDisplayRow(prevRow, rowOnly);
5288 }
5289
5290 return prevRow;
5291 }
5292
5293 findRowIndex(row, list){
5294 var rowIndex;
5295
5296 row = this.findRow(row);
5297
5298 if(row){
5299 rowIndex = list.indexOf(row);
5300
5301 if(rowIndex > -1){
5302 return rowIndex;
5303 }
5304 }
5305
5306 return false;
5307 }
5308
5309 getData(active, transform){
5310 var output = [],
5311 rows = this.getRows(active);
5312
5313 rows.forEach(function(row){
5314 if(row.type == "row"){
5315 output.push(row.getData(transform || "data"));
5316 }
5317 });
5318
5319 return output;
5320 }
5321
5322 getComponents(active){
5323 var output = [],
5324 rows = this.getRows(active);
5325
5326 rows.forEach(function(row){
5327 output.push(row.getComponent());
5328 });
5329
5330 return output;
5331 }
5332
5333 getDataCount(active){
5334 var rows = this.getRows(active);
5335
5336 return rows.length;
5337 }
5338
5339 scrollHorizontal(left){
5340 this.scrollLeft = left;
5341 this.element.scrollLeft = left;
5342
5343 this.dispatch("scroll-horizontal", left);
5344 }
5345
5346 registerDataPipelineHandler(handler, priority){
5347 if(typeof priority !== "undefined"){
5348 this.dataPipeline.push({handler, priority});
5349 this.dataPipeline.sort((a, b) => {
5350 return a.priority - b.priority;
5351 });
5352 }else {
5353 console.error("Data pipeline handlers must have a priority in order to be registered");
5354 }
5355 }
5356
5357 registerDisplayPipelineHandler(handler, priority){
5358 if(typeof priority !== "undefined"){
5359 this.displayPipeline.push({handler, priority});
5360 this.displayPipeline.sort((a, b) => {
5361 return a.priority - b.priority;
5362 });
5363 }else {
5364 console.error("Display pipeline handlers must have a priority in order to be registered");
5365 }
5366 }
5367
5368 //set active data set
5369 refreshActiveData(handler, skipStage, renderInPosition){
5370 var table = this.table,
5371 stage = "",
5372 index = 0,
5373 cascadeOrder = ["all", "dataPipeline", "display", "displayPipeline", "end"];
5374
5375 if(!this.table.destroyed){
5376 if(typeof handler === "function"){
5377 index = this.dataPipeline.findIndex((item) => {
5378 return item.handler === handler;
5379 });
5380
5381 if(index > -1){
5382 stage = "dataPipeline";
5383
5384 if(skipStage){
5385 if(index == this.dataPipeline.length - 1){
5386 stage = "display";
5387 }else {
5388 index++;
5389 }
5390 }
5391 }else {
5392 index = this.displayPipeline.findIndex((item) => {
5393 return item.handler === handler;
5394 });
5395
5396 if(index > -1){
5397 stage = "displayPipeline";
5398
5399 if(skipStage){
5400 if(index == this.displayPipeline.length - 1){
5401 stage = "end";
5402 }else {
5403 index++;
5404 }
5405 }
5406 }else {
5407 console.error("Unable to refresh data, invalid handler provided", handler);
5408 return;
5409 }
5410 }
5411 }else {
5412 stage = handler || "all";
5413 index = 0;
5414 }
5415
5416 if(this.redrawBlock){
5417 if(!this.redrawBlockRestoreConfig || (this.redrawBlockRestoreConfig && ((this.redrawBlockRestoreConfig.stage === stage && index < this.redrawBlockRestoreConfig.index) || (cascadeOrder.indexOf(stage) < cascadeOrder.indexOf(this.redrawBlockRestoreConfig.stage))))){
5418 this.redrawBlockRestoreConfig = {
5419 handler: handler,
5420 skipStage: skipStage,
5421 renderInPosition: renderInPosition,
5422 stage:stage,
5423 index:index,
5424 };
5425 }
5426
5427 return;
5428 }else {
5429 if(Helpers.elVisible(this.element)){
5430 if(renderInPosition){
5431 this.reRenderInPosition(this.refreshPipelines.bind(this, handler, stage, index, renderInPosition));
5432 }else {
5433 this.refreshPipelines(handler, stage, index, renderInPosition);
5434
5435 if(!handler){
5436 this.table.columnManager.renderer.renderColumns();
5437 }
5438
5439 this.renderTable();
5440
5441 if(table.options.layoutColumnsOnNewData){
5442 this.table.columnManager.redraw(true);
5443 }
5444 }
5445 }else {
5446 this.refreshPipelines(handler, stage, index, renderInPosition);
5447 }
5448
5449 this.dispatch("data-refreshed");
5450 }
5451 }
5452 }
5453
5454 refreshPipelines(handler, stage, index, renderInPosition){
5455 this.dispatch("data-refreshing");
5456
5457 if(!handler || !this.activeRowsPipeline[0]){
5458 this.activeRowsPipeline[0] = this.rows.slice(0);
5459 }
5460
5461 //cascade through data refresh stages
5462 switch(stage){
5463 case "all":
5464 //handle case where all data needs refreshing
5465
5466 case "dataPipeline":
5467 for(let i = index; i < this.dataPipeline.length; i++){
5468 let result = this.dataPipeline[i].handler(this.activeRowsPipeline[i].slice(0));
5469
5470 this.activeRowsPipeline[i + 1] = result || this.activeRowsPipeline[i].slice(0);
5471 }
5472
5473 this.setActiveRows(this.activeRowsPipeline[this.dataPipeline.length]);
5474
5475 case "display":
5476 index = 0;
5477 this.resetDisplayRows();
5478
5479 case "displayPipeline":
5480 for(let i = index; i < this.displayPipeline.length; i++){
5481 let result = this.displayPipeline[i].handler((i ? this.getDisplayRows(i - 1) : this.activeRows).slice(0), renderInPosition);
5482
5483 this.setDisplayRows(result || this.getDisplayRows(i - 1).slice(0), i);
5484 }
5485
5486 case "end":
5487 //case to handle scenario when trying to skip past end stage
5488 this.regenerateRowPositions();
5489 }
5490
5491 if(this.getDisplayRows().length){
5492 this._clearPlaceholder();
5493 }
5494 }
5495
5496 //regenerate row positions
5497 regenerateRowPositions(){
5498 var rows = this.getDisplayRows();
5499 var index = 1;
5500
5501 rows.forEach((row) => {
5502 if (row.type === "row"){
5503 row.setPosition(index);
5504 index++;
5505 }
5506 });
5507 }
5508
5509 setActiveRows(activeRows){
5510 this.activeRows = this.activeRows = Object.assign([], activeRows);
5511 this.activeRowsCount = this.activeRows.length;
5512 }
5513
5514 //reset display rows array
5515 resetDisplayRows(){
5516 this.displayRows = [];
5517
5518 this.displayRows.push(this.activeRows.slice(0));
5519
5520 this.displayRowsCount = this.displayRows[0].length;
5521 }
5522
5523 //set display row pipeline data
5524 setDisplayRows(displayRows, index){
5525 this.displayRows[index] = displayRows;
5526
5527 if(index == this.displayRows.length -1){
5528 this.displayRowsCount = this.displayRows[this.displayRows.length -1].length;
5529 }
5530 }
5531
5532 getDisplayRows(index){
5533 if(typeof index == "undefined"){
5534 return this.displayRows.length ? this.displayRows[this.displayRows.length -1] : [];
5535 }else {
5536 return this.displayRows[index] || [];
5537 }
5538 }
5539
5540 getVisibleRows(chain, viewable){
5541 var rows = Object.assign([], this.renderer.visibleRows(!viewable));
5542
5543 if(chain){
5544 rows = this.chain("rows-visible", [viewable], rows, rows);
5545 }
5546
5547 return rows;
5548 }
5549
5550 //repeat action across display rows
5551 displayRowIterator(callback){
5552 this.activeRowsPipeline.forEach(callback);
5553 this.displayRows.forEach(callback);
5554
5555 this.displayRowsCount = this.displayRows[this.displayRows.length -1].length;
5556 }
5557
5558 //return only actual rows (not group headers etc)
5559 getRows(type){
5560 var rows = [];
5561
5562 switch(type){
5563 case "active":
5564 rows = this.activeRows;
5565 break;
5566
5567 case "display":
5568 rows = this.table.rowManager.getDisplayRows();
5569 break;
5570
5571 case "visible":
5572 rows = this.getVisibleRows(false, true);
5573 break;
5574
5575 default:
5576 rows = this.chain("rows-retrieve", type, null, this.rows) || this.rows;
5577 }
5578
5579 return rows;
5580 }
5581
5582 ///////////////// Table Rendering /////////////////
5583 //trigger rerender of table in current position
5584 reRenderInPosition(callback){
5585 if(this.redrawBlock){
5586 if(callback){
5587 callback();
5588 }else {
5589 this.redrawBlockRenderInPosition = true;
5590 }
5591 }else {
5592 this.dispatchExternal("renderStarted");
5593
5594 this.renderer.rerenderRows(callback);
5595
5596 if(!this.fixedHeight){
5597 this.adjustTableSize();
5598 }
5599
5600 this.scrollBarCheck();
5601
5602 this.dispatchExternal("renderComplete");
5603 }
5604 }
5605
5606 scrollBarCheck(){
5607 var scrollbarWidth = 0;
5608
5609 //adjust for vertical scrollbar moving table when present
5610 if(this.element.scrollHeight > this.element.clientHeight){
5611 scrollbarWidth = this.element.offsetWidth - this.element.clientWidth;
5612 }
5613
5614 if(scrollbarWidth !== this.scrollbarWidth){
5615 this.scrollbarWidth = scrollbarWidth;
5616 this.dispatch("scrollbar-vertical", scrollbarWidth);
5617 }
5618 }
5619
5620 initializeRenderer(){
5621 var renderClass;
5622
5623 var renderers = {
5624 "virtual": VirtualDomVertical,
5625 "basic": BasicVertical,
5626 };
5627
5628 if(typeof this.table.options.renderVertical === "string"){
5629 renderClass = renderers[this.table.options.renderVertical];
5630 }else {
5631 renderClass = this.table.options.renderVertical;
5632 }
5633
5634 if(renderClass){
5635 this.renderMode = this.table.options.renderVertical;
5636
5637 this.renderer = new renderClass(this.table, this.element, this.tableElement);
5638 this.renderer.initialize();
5639
5640 if((this.table.element.clientHeight || this.table.options.height) && !(this.table.options.minHeight && this.table.options.maxHeight)){
5641 this.fixedHeight = true;
5642 }else {
5643 this.fixedHeight = false;
5644 }
5645 }else {
5646 console.error("Unable to find matching renderer:", this.table.options.renderVertical);
5647 }
5648 }
5649
5650 getRenderMode(){
5651 return this.renderMode;
5652 }
5653
5654 renderTable(){
5655 this.dispatchExternal("renderStarted");
5656
5657 this.element.scrollTop = 0;
5658
5659 this._clearTable();
5660
5661 if(this.displayRowsCount){
5662 this.renderer.renderRows();
5663
5664 if(this.firstRender){
5665 this.firstRender = false;
5666
5667 if(!this.fixedHeight){
5668 this.adjustTableSize();
5669 }
5670
5671 this.layoutRefresh(true);
5672 }
5673 }else {
5674 this.renderEmptyScroll();
5675 }
5676
5677 if(!this.fixedHeight){
5678 this.adjustTableSize();
5679 }
5680
5681 this.dispatch("table-layout");
5682
5683 if(!this.displayRowsCount){
5684 this._showPlaceholder();
5685 }
5686
5687 this.scrollBarCheck();
5688
5689 this.dispatchExternal("renderComplete");
5690 }
5691
5692 //show scrollbars on empty table div
5693 renderEmptyScroll(){
5694 if(this.placeholder){
5695 this.tableElement.style.display = "none";
5696 }else {
5697 this.tableElement.style.minWidth = this.table.columnManager.getWidth() + "px";
5698 // this.tableElement.style.minHeight = "1px";
5699 // this.tableElement.style.visibility = "hidden";
5700 }
5701 }
5702
5703 _clearTable(){
5704 this._clearPlaceholder();
5705
5706 this.scrollTop = 0;
5707 this.scrollLeft = 0;
5708
5709 this.renderer.clearRows();
5710 }
5711
5712 tableEmpty(){
5713 this.renderEmptyScroll();
5714 this._showPlaceholder();
5715 }
5716
5717 checkPlaceholder(){
5718 if(this.displayRowsCount){
5719 this._clearPlaceholder();
5720 }else {
5721 this.tableEmpty();
5722 }
5723 }
5724
5725 _showPlaceholder(){
5726 if(this.placeholder){
5727 if(this.placeholder && this.placeholder.parentNode){
5728 this.placeholder.parentNode.removeChild(this.placeholder);
5729 }
5730
5731 this.initializePlaceholder();
5732
5733 this.placeholder.setAttribute("tabulator-render-mode", this.renderMode);
5734
5735 this.getElement().appendChild(this.placeholder);
5736 this._positionPlaceholder();
5737
5738 this.adjustTableSize();
5739 }
5740 }
5741
5742 _clearPlaceholder(){
5743 if(this.placeholder && this.placeholder.parentNode){
5744 this.placeholder.parentNode.removeChild(this.placeholder);
5745 }
5746
5747 // clear empty table placeholder min
5748 this.tableElement.style.minWidth = "";
5749 this.tableElement.style.display = "";
5750 }
5751
5752 _positionPlaceholder(){
5753 if(this.placeholder && this.placeholder.parentNode){
5754 this.placeholder.style.width = this.table.columnManager.getWidth() + "px";
5755 this.placeholderContents.style.width = this.table.rowManager.element.clientWidth + "px";
5756 this.placeholderContents.style.marginLeft = this.scrollLeft + "px";
5757 }
5758 }
5759
5760 styleRow(row, index){
5761 var rowEl = row.getElement();
5762
5763 if(index % 2){
5764 rowEl.classList.add("tabulator-row-even");
5765 rowEl.classList.remove("tabulator-row-odd");
5766 }else {
5767 rowEl.classList.add("tabulator-row-odd");
5768 rowEl.classList.remove("tabulator-row-even");
5769 }
5770 }
5771
5772 //normalize height of active rows
5773 normalizeHeight(force){
5774 this.activeRows.forEach(function(row){
5775 row.normalizeHeight(force);
5776 });
5777 }
5778
5779 //adjust the height of the table holder to fit in the Tabulator element
5780 adjustTableSize(){
5781 let initialHeight = this.element.clientHeight, minHeight;
5782 let resized = false;
5783
5784 if(this.renderer.verticalFillMode === "fill"){
5785 let otherHeight = Math.floor(this.table.columnManager.getElement().getBoundingClientRect().height + (this.table.footerManager && this.table.footerManager.active && !this.table.footerManager.external ? this.table.footerManager.getElement().getBoundingClientRect().height : 0));
5786
5787 if(this.fixedHeight){
5788 minHeight = isNaN(this.table.options.minHeight) ? this.table.options.minHeight : this.table.options.minHeight + "px";
5789
5790 const height = "calc(100% - " + otherHeight + "px)";
5791 this.element.style.minHeight = minHeight || "calc(100% - " + otherHeight + "px)";
5792 this.element.style.height = height;
5793 this.element.style.maxHeight = height;
5794 } else {
5795 this.element.style.height = "";
5796 this.element.style.height =
5797 this.table.element.clientHeight - otherHeight + "px";
5798 this.element.scrollTop = this.scrollTop;
5799 }
5800
5801 this.renderer.resize();
5802
5803 //check if the table has changed size when dealing with variable height tables
5804 if(!this.fixedHeight && initialHeight != this.element.clientHeight){
5805 resized = true;
5806 if(this.subscribed("table-resize")){
5807 this.dispatch("table-resize");
5808 }else {
5809 this.redraw();
5810 }
5811 }
5812
5813 this.scrollBarCheck();
5814 }
5815
5816 this._positionPlaceholder();
5817 return resized;
5818 }
5819
5820 //reinitialize all rows
5821 reinitialize(){
5822 this.rows.forEach(function(row){
5823 row.reinitialize(true);
5824 });
5825 }
5826
5827 //prevent table from being redrawn
5828 blockRedraw (){
5829 this.redrawBlock = true;
5830 this.redrawBlockRestoreConfig = false;
5831 }
5832
5833 //restore table redrawing
5834 restoreRedraw (){
5835 this.redrawBlock = false;
5836
5837 if(this.redrawBlockRestoreConfig){
5838 this.refreshActiveData(this.redrawBlockRestoreConfig.handler, this.redrawBlockRestoreConfig.skipStage, this.redrawBlockRestoreConfig.renderInPosition);
5839
5840 this.redrawBlockRestoreConfig = false;
5841 }else {
5842 if(this.redrawBlockRenderInPosition){
5843 this.reRenderInPosition();
5844 }
5845 }
5846
5847 this.redrawBlockRenderInPosition = false;
5848 }
5849
5850 //redraw table
5851 redraw (force){
5852 this.adjustTableSize();
5853 this.table.tableWidth = this.table.element.clientWidth;
5854
5855 if(!force){
5856 this.reRenderInPosition();
5857 this.scrollHorizontal(this.scrollLeft);
5858 }else {
5859 this.renderTable();
5860 }
5861 }
5862
5863 resetScroll(){
5864 this.element.scrollLeft = 0;
5865 this.element.scrollTop = 0;
5866
5867 if(this.table.browser === "ie"){
5868 var event = document.createEvent("Event");
5869 event.initEvent("scroll", false, true);
5870 this.element.dispatchEvent(event);
5871 }else {
5872 this.element.dispatchEvent(new Event('scroll'));
5873 }
5874 }
5875 }
5876
5877 class FooterManager extends CoreFeature{
5878
5879 constructor(table){
5880 super(table);
5881
5882 this.active = false;
5883 this.element = this.createElement(); //containing element
5884 this.containerElement = this.createContainerElement(); //containing element
5885 this.external = false;
5886 }
5887
5888 initialize(){
5889 this.initializeElement();
5890 }
5891
5892 createElement(){
5893 var el = document.createElement("div");
5894
5895 el.classList.add("tabulator-footer");
5896
5897 return el;
5898 }
5899
5900
5901 createContainerElement(){
5902 var el = document.createElement("div");
5903
5904 el.classList.add("tabulator-footer-contents");
5905
5906 this.element.appendChild(el);
5907
5908 return el;
5909 }
5910
5911 initializeElement(){
5912 if(this.table.options.footerElement){
5913
5914 switch(typeof this.table.options.footerElement){
5915 case "string":
5916 if(this.table.options.footerElement[0] === "<"){
5917 this.containerElement.innerHTML = this.table.options.footerElement;
5918 }else {
5919 this.external = true;
5920 this.containerElement = document.querySelector(this.table.options.footerElement);
5921 }
5922 break;
5923
5924 default:
5925 this.element = this.table.options.footerElement;
5926 break;
5927 }
5928 }
5929 }
5930
5931 getElement(){
5932 return this.element;
5933 }
5934
5935 append(element){
5936 this.activate();
5937
5938 this.containerElement.appendChild(element);
5939 this.table.rowManager.adjustTableSize();
5940 }
5941
5942 prepend(element){
5943 this.activate();
5944
5945 this.element.insertBefore(element, this.element.firstChild);
5946 this.table.rowManager.adjustTableSize();
5947 }
5948
5949 remove(element){
5950 element.parentNode.removeChild(element);
5951 this.deactivate();
5952 }
5953
5954 deactivate(force){
5955 if(!this.element.firstChild || force){
5956 if(!this.external){
5957 this.element.parentNode.removeChild(this.element);
5958 }
5959 this.active = false;
5960 }
5961 }
5962
5963 activate(){
5964 if(!this.active){
5965 this.active = true;
5966 if(!this.external){
5967 this.table.element.appendChild(this.getElement());
5968 this.table.element.style.display = '';
5969 }
5970 }
5971 }
5972
5973 redraw(){
5974 this.dispatch("footer-redraw");
5975 }
5976 }
5977
5978 class InteractionManager extends CoreFeature {
5979
5980 constructor (table){
5981 super(table);
5982
5983 this.el = null;
5984
5985 this.abortClasses = ["tabulator-headers", "tabulator-table"];
5986
5987 this.previousTargets = {};
5988
5989 this.listeners = [
5990 "click",
5991 "dblclick",
5992 "contextmenu",
5993 "mouseenter",
5994 "mouseleave",
5995 "mouseover",
5996 "mouseout",
5997 "mousemove",
5998 "mouseup",
5999 "mousedown",
6000 "touchstart",
6001 "touchend",
6002 ];
6003
6004 this.componentMap = {
6005 "tabulator-cell":"cell",
6006 "tabulator-row":"row",
6007 "tabulator-group":"group",
6008 "tabulator-col":"column",
6009 };
6010
6011 this.pseudoTrackers = {
6012 "row":{
6013 subscriber:null,
6014 target:null,
6015 },
6016 "cell":{
6017 subscriber:null,
6018 target:null,
6019 },
6020 "group":{
6021 subscriber:null,
6022 target:null,
6023 },
6024 "column":{
6025 subscriber:null,
6026 target:null,
6027 },
6028 };
6029
6030 this.pseudoTracking = false;
6031 }
6032
6033 initialize(){
6034 this.el = this.table.element;
6035
6036 this.buildListenerMap();
6037 this.bindSubscriptionWatchers();
6038 }
6039
6040 buildListenerMap(){
6041 var listenerMap = {};
6042
6043 this.listeners.forEach((listener) => {
6044 listenerMap[listener] = {
6045 handler:null,
6046 components:[],
6047 };
6048 });
6049
6050 this.listeners = listenerMap;
6051 }
6052
6053 bindPseudoEvents(){
6054 Object.keys(this.pseudoTrackers).forEach((key) => {
6055 this.pseudoTrackers[key].subscriber = this.pseudoMouseEnter.bind(this, key);
6056 this.subscribe(key + "-mouseover", this.pseudoTrackers[key].subscriber);
6057 });
6058
6059 this.pseudoTracking = true;
6060 }
6061
6062 pseudoMouseEnter(key, e, target){
6063 if(this.pseudoTrackers[key].target !== target){
6064
6065 if(this.pseudoTrackers[key].target){
6066 this.dispatch(key + "-mouseleave", e, this.pseudoTrackers[key].target);
6067 }
6068
6069 this.pseudoMouseLeave(key, e);
6070
6071 this.pseudoTrackers[key].target = target;
6072
6073 this.dispatch(key + "-mouseenter", e, target);
6074 }
6075 }
6076
6077 pseudoMouseLeave(key, e){
6078 var leaveList = Object.keys(this.pseudoTrackers),
6079 linkedKeys = {
6080 "row":["cell"],
6081 "cell":["row"],
6082 };
6083
6084 leaveList = leaveList.filter((item) => {
6085 var links = linkedKeys[key];
6086 return item !== key && (!links || (links && !links.includes(item)));
6087 });
6088
6089
6090 leaveList.forEach((key) => {
6091 var target = this.pseudoTrackers[key].target;
6092
6093 if(this.pseudoTrackers[key].target){
6094 this.dispatch(key + "-mouseleave", e, target);
6095
6096 this.pseudoTrackers[key].target = null;
6097 }
6098 });
6099 }
6100
6101
6102 bindSubscriptionWatchers(){
6103 var listeners = Object.keys(this.listeners),
6104 components = Object.values(this.componentMap);
6105
6106 for(let comp of components){
6107 for(let listener of listeners){
6108 let key = comp + "-" + listener;
6109
6110 this.subscriptionChange(key, this.subscriptionChanged.bind(this, comp, listener));
6111 }
6112 }
6113
6114 this.subscribe("table-destroy", this.clearWatchers.bind(this));
6115 }
6116
6117 subscriptionChanged(component, key, added){
6118 var listener = this.listeners[key].components,
6119 index = listener.indexOf(component),
6120 changed = false;
6121
6122 if(added){
6123 if(index === -1){
6124 listener.push(component);
6125 changed = true;
6126 }
6127 }else {
6128 if(!this.subscribed(component + "-" + key)){
6129 if(index > -1){
6130 listener.splice(index, 1);
6131 changed = true;
6132 }
6133 }
6134 }
6135
6136 if((key === "mouseenter" || key === "mouseleave") && !this.pseudoTracking){
6137 this.bindPseudoEvents();
6138 }
6139
6140 if(changed){
6141 this.updateEventListeners();
6142 }
6143 }
6144
6145 updateEventListeners(){
6146 for(let key in this.listeners){
6147 let listener = this.listeners[key];
6148
6149 if(listener.components.length){
6150 if(!listener.handler){
6151 listener.handler = this.track.bind(this, key);
6152 this.el.addEventListener(key, listener.handler);
6153 // this.el.addEventListener(key, listener.handler, {passive: true})
6154 }
6155 }else {
6156 if(listener.handler){
6157 this.el.removeEventListener(key, listener.handler);
6158 listener.handler = null;
6159 }
6160 }
6161 }
6162 }
6163
6164 track(type, e){
6165 var path = (e.composedPath && e.composedPath()) || e.path;
6166
6167 var targets = this.findTargets(path);
6168 targets = this.bindComponents(type, targets);
6169
6170 this.triggerEvents(type, e, targets);
6171
6172 if(this.pseudoTracking && (type == "mouseover" || type == "mouseleave") && !Object.keys(targets).length){
6173 this.pseudoMouseLeave("none", e);
6174 }
6175 }
6176
6177 findTargets(path){
6178 var targets = {};
6179
6180 let componentMap = Object.keys(this.componentMap);
6181
6182 for (let el of path) {
6183 let classList = el.classList ? [...el.classList] : [];
6184
6185 let abort = classList.filter((item) => {
6186 return this.abortClasses.includes(item);
6187 });
6188
6189 if(abort.length){
6190 break;
6191 }
6192
6193 let elTargets = classList.filter((item) => {
6194 return componentMap.includes(item);
6195 });
6196
6197 for (let target of elTargets) {
6198 if(!targets[this.componentMap[target]]){
6199 targets[this.componentMap[target]] = el;
6200 }
6201 }
6202 }
6203
6204 if(targets.group && targets.group === targets.row){
6205 delete targets.row;
6206 }
6207
6208 return targets;
6209 }
6210
6211 bindComponents(type, targets){
6212 //ensure row component is looked up before cell
6213 var keys = Object.keys(targets).reverse(),
6214 listener = this.listeners[type],
6215 matches = {},
6216 output = {},
6217 targetMatches = {};
6218
6219 for(let key of keys){
6220 let component,
6221 target = targets[key],
6222 previousTarget = this.previousTargets[key];
6223
6224 if(previousTarget && previousTarget.target === target){
6225 component = previousTarget.component;
6226 }else {
6227 switch(key){
6228 case "row":
6229 case "group":
6230 if(listener.components.includes("row") || listener.components.includes("cell") || listener.components.includes("group")){
6231 let rows = this.table.rowManager.getVisibleRows(true);
6232
6233 component = rows.find((row) => {
6234 return row.getElement() === target;
6235 });
6236
6237 if(targets["row"] && targets["row"].parentNode && targets["row"].parentNode.closest(".tabulator-row")){
6238 targets[key] = false;
6239 }
6240 }
6241 break;
6242
6243 case "column":
6244 if(listener.components.includes("column")){
6245 component = this.table.columnManager.findColumn(target);
6246 }
6247 break;
6248
6249 case "cell":
6250 if(listener.components.includes("cell")){
6251 if(matches["row"] instanceof Row){
6252 component = matches["row"].findCell(target);
6253 }else {
6254 if(targets["row"]){
6255 console.warn("Event Target Lookup Error - The row this cell is attached to cannot be found, has the table been reinitialized without being destroyed first?");
6256 }
6257 }
6258 }
6259 break;
6260 }
6261 }
6262
6263 if(component){
6264 matches[key] = component;
6265 targetMatches[key] = {
6266 target:target,
6267 component:component,
6268 };
6269 }
6270 }
6271
6272 this.previousTargets = targetMatches;
6273
6274 //reverse order keys are set in so events trigger in correct sequence
6275 Object.keys(targets).forEach((key) => {
6276 let value = matches[key];
6277 output[key] = value;
6278 });
6279
6280 return output;
6281 }
6282
6283 triggerEvents(type, e, targets){
6284 var listener = this.listeners[type];
6285
6286 for(let key in targets){
6287 if(targets[key] && listener.components.includes(key)){
6288 this.dispatch(key + "-" + type, e, targets[key]);
6289 }
6290 }
6291 }
6292
6293 clearWatchers(){
6294 for(let key in this.listeners){
6295 let listener = this.listeners[key];
6296
6297 if(listener.handler){
6298 this.el.removeEventListener(key, listener.handler);
6299 listener.handler = null;
6300 }
6301 }
6302 }
6303 }
6304
6305 class ComponentFunctionBinder{
6306
6307 constructor(table){
6308 this.table = table;
6309
6310 this.bindings = {};
6311 }
6312
6313 bind(type, funcName, handler){
6314 if(!this.bindings[type]){
6315 this.bindings[type] = {};
6316 }
6317
6318 if(this.bindings[type][funcName]){
6319 console.warn("Unable to bind component handler, a matching function name is already bound", type, funcName, handler);
6320 }else {
6321 this.bindings[type][funcName] = handler;
6322 }
6323 }
6324
6325 handle(type, component, name){
6326 if(this.bindings[type] && this.bindings[type][name] && typeof this.bindings[type][name].bind === 'function'){
6327 return this.bindings[type][name].bind(null, component);
6328 }else {
6329 if(name !== "then" && typeof name === "string" && !name.startsWith("_")){
6330 if(this.table.options.debugInvalidComponentFuncs){
6331 console.error("The " + type + " component does not have a " + name + " function, have you checked that you have the correct Tabulator module installed?");
6332 }
6333 }
6334 }
6335 }
6336 }
6337
6338 class DataLoader extends CoreFeature{
6339 constructor(table){
6340 super(table);
6341
6342 this.requestOrder = 0; //prevent requests coming out of sequence if overridden by another load request
6343 this.loading = false;
6344 }
6345
6346 initialize(){}
6347
6348 load(data, params, config, replace, silent, columnsChanged){
6349 var requestNo = ++this.requestOrder;
6350
6351 if(this.table.destroyed){
6352 return Promise.resolve();
6353 }
6354
6355 this.dispatchExternal("dataLoading", data);
6356
6357 //parse json data to array
6358 if (data && (data.indexOf("{") == 0 || data.indexOf("[") == 0)){
6359 data = JSON.parse(data);
6360 }
6361
6362 if(this.confirm("data-loading", [data, params, config, silent])){
6363 this.loading = true;
6364
6365 if(!silent){
6366 this.alertLoader();
6367 }
6368
6369 //get params for request
6370 params = this.chain("data-params", [data, config, silent], params || {}, params || {});
6371
6372 params = this.mapParams(params, this.table.options.dataSendParams);
6373
6374 var result = this.chain("data-load", [data, params, config, silent], false, Promise.resolve([]));
6375
6376 return result.then((response) => {
6377 if(!this.table.destroyed){
6378 if(!Array.isArray(response) && typeof response == "object"){
6379 response = this.mapParams(response, this.objectInvert(this.table.options.dataReceiveParams));
6380 }
6381
6382 var rowData = this.chain("data-loaded", [response], null, response);
6383
6384 if(requestNo == this.requestOrder){
6385 this.clearAlert();
6386
6387 if(rowData !== false){
6388 this.dispatchExternal("dataLoaded", rowData);
6389 this.table.rowManager.setData(rowData, replace, typeof columnsChanged === "undefined" ? !replace : columnsChanged);
6390 }
6391 }else {
6392 console.warn("Data Load Response Blocked - An active data load request was blocked by an attempt to change table data while the request was being made");
6393 }
6394 }else {
6395 console.warn("Data Load Response Blocked - Table has been destroyed");
6396 }
6397 }).catch((error) => {
6398 console.error("Data Load Error: ", error);
6399 this.dispatchExternal("dataLoadError", error);
6400
6401 if(!silent){
6402 this.alertError();
6403 }
6404
6405 setTimeout(() => {
6406 this.clearAlert();
6407 }, this.table.options.dataLoaderErrorTimeout);
6408 })
6409 .finally(() => {
6410 this.loading = false;
6411 });
6412 }else {
6413 this.dispatchExternal("dataLoaded", data);
6414
6415 if(!data){
6416 data = [];
6417 }
6418
6419 this.table.rowManager.setData(data, replace, typeof columnsChanged === "undefined" ? !replace : columnsChanged);
6420 return Promise.resolve();
6421 }
6422 }
6423
6424 mapParams(params, map){
6425 var output = {};
6426
6427 for(let key in params){
6428 output[map.hasOwnProperty(key) ? map[key] : key] = params[key];
6429 }
6430
6431 return output;
6432 }
6433
6434 objectInvert(obj){
6435 var output = {};
6436
6437 for(let key in obj){
6438 output[obj[key]] = key;
6439 }
6440
6441 return output;
6442 }
6443
6444 blockActiveLoad(){
6445 this.requestOrder++;
6446 }
6447
6448 alertLoader(){
6449 var shouldLoad = typeof this.table.options.dataLoader === "function" ? this.table.options.dataLoader() : this.table.options.dataLoader;
6450
6451 if(shouldLoad){
6452 this.table.alertManager.alert(this.table.options.dataLoaderLoading || this.langText("data|loading"));
6453 }
6454 }
6455
6456 alertError(){
6457 this.table.alertManager.alert(this.table.options.dataLoaderError || this.langText("data|error"), "error");
6458 }
6459
6460 clearAlert(){
6461 this.table.alertManager.clear();
6462 }
6463 }
6464
6465 class ExternalEventBus {
6466
6467 constructor(table, optionsList, debug){
6468 this.table = table;
6469 this.events = {};
6470 this.optionsList = optionsList || {};
6471 this.subscriptionNotifiers = {};
6472
6473 this.dispatch = debug ? this._debugDispatch.bind(this) : this._dispatch.bind(this);
6474 this.debug = debug;
6475 }
6476
6477 subscriptionChange(key, callback){
6478 if(!this.subscriptionNotifiers[key]){
6479 this.subscriptionNotifiers[key] = [];
6480 }
6481
6482 this.subscriptionNotifiers[key].push(callback);
6483
6484 if(this.subscribed(key)){
6485 this._notifySubscriptionChange(key, true);
6486 }
6487 }
6488
6489 subscribe(key, callback){
6490 if(!this.events[key]){
6491 this.events[key] = [];
6492 }
6493
6494 this.events[key].push(callback);
6495
6496 this._notifySubscriptionChange(key, true);
6497 }
6498
6499 unsubscribe(key, callback){
6500 var index;
6501
6502 if(this.events[key]){
6503 if(callback){
6504 index = this.events[key].findIndex((item) => {
6505 return item === callback;
6506 });
6507
6508 if(index > -1){
6509 this.events[key].splice(index, 1);
6510 }else {
6511 console.warn("Cannot remove event, no matching event found:", key, callback);
6512 return;
6513 }
6514 }else {
6515 delete this.events[key];
6516 }
6517 }else {
6518 console.warn("Cannot remove event, no events set on:", key);
6519 return;
6520 }
6521
6522 this._notifySubscriptionChange(key, false);
6523 }
6524
6525 subscribed(key){
6526 return this.events[key] && this.events[key].length;
6527 }
6528
6529 _notifySubscriptionChange(key, subscribed){
6530 var notifiers = this.subscriptionNotifiers[key];
6531
6532 if(notifiers){
6533 notifiers.forEach((callback)=>{
6534 callback(subscribed);
6535 });
6536 }
6537 }
6538
6539 _dispatch(){
6540 var args = Array.from(arguments),
6541 key = args.shift(),
6542 result;
6543
6544 if(this.events[key]){
6545 this.events[key].forEach((callback, i) => {
6546 let callResult = callback.apply(this.table, args);
6547
6548 if(!i){
6549 result = callResult;
6550 }
6551 });
6552 }
6553
6554 return result;
6555 }
6556
6557 _debugDispatch(){
6558 var args = Array.from(arguments),
6559 key = args[0];
6560
6561 args[0] = "ExternalEvent:" + args[0];
6562
6563 if(this.debug === true || this.debug.includes(key)){
6564 console.log(...args);
6565 }
6566
6567 return this._dispatch(...arguments);
6568 }
6569 }
6570
6571 class InternalEventBus {
6572
6573 constructor(debug){
6574 this.events = {};
6575 this.subscriptionNotifiers = {};
6576
6577 this.dispatch = debug ? this._debugDispatch.bind(this) : this._dispatch.bind(this);
6578 this.chain = debug ? this._debugChain.bind(this) : this._chain.bind(this);
6579 this.confirm = debug ? this._debugConfirm.bind(this) : this._confirm.bind(this);
6580 this.debug = debug;
6581 }
6582
6583 subscriptionChange(key, callback){
6584 if(!this.subscriptionNotifiers[key]){
6585 this.subscriptionNotifiers[key] = [];
6586 }
6587
6588 this.subscriptionNotifiers[key].push(callback);
6589
6590 if(this.subscribed(key)){
6591 this._notifySubscriptionChange(key, true);
6592 }
6593 }
6594
6595 subscribe(key, callback, priority = 10000){
6596 if(!this.events[key]){
6597 this.events[key] = [];
6598 }
6599
6600 this.events[key].push({callback, priority});
6601
6602 this.events[key].sort((a, b) => {
6603 return a.priority - b.priority;
6604 });
6605
6606 this._notifySubscriptionChange(key, true);
6607 }
6608
6609 unsubscribe(key, callback){
6610 var index;
6611
6612 if(this.events[key]){
6613 if(callback){
6614 index = this.events[key].findIndex((item) => {
6615 return item.callback === callback;
6616 });
6617
6618 if(index > -1){
6619 this.events[key].splice(index, 1);
6620 }else {
6621 console.warn("Cannot remove event, no matching event found:", key, callback);
6622 return;
6623 }
6624 }
6625 }else {
6626 console.warn("Cannot remove event, no events set on:", key);
6627 return;
6628 }
6629
6630 this._notifySubscriptionChange(key, false);
6631 }
6632
6633 subscribed(key){
6634 return this.events[key] && this.events[key].length;
6635 }
6636
6637 _chain(key, args, initialValue, fallback){
6638 var value = initialValue;
6639
6640 if(!Array.isArray(args)){
6641 args = [args];
6642 }
6643
6644 if(this.subscribed(key)){
6645 this.events[key].forEach((subscriber, i) => {
6646 value = subscriber.callback.apply(this, args.concat([value]));
6647 });
6648
6649 return value;
6650 }else {
6651 return typeof fallback === "function" ? fallback() : fallback;
6652 }
6653 }
6654
6655 _confirm(key, args){
6656 var confirmed = false;
6657
6658 if(!Array.isArray(args)){
6659 args = [args];
6660 }
6661
6662 if(this.subscribed(key)){
6663 this.events[key].forEach((subscriber, i) => {
6664 if(subscriber.callback.apply(this, args)){
6665 confirmed = true;
6666 }
6667 });
6668 }
6669
6670 return confirmed;
6671 }
6672
6673 _notifySubscriptionChange(key, subscribed){
6674 var notifiers = this.subscriptionNotifiers[key];
6675
6676 if(notifiers){
6677 notifiers.forEach((callback)=>{
6678 callback(subscribed);
6679 });
6680 }
6681 }
6682
6683 _dispatch(){
6684 var args = Array.from(arguments),
6685 key = args.shift();
6686
6687 if(this.events[key]){
6688 this.events[key].forEach((subscriber) => {
6689 subscriber.callback.apply(this, args);
6690 });
6691 }
6692 }
6693
6694 _debugDispatch(){
6695 var args = Array.from(arguments),
6696 key = args[0];
6697
6698 args[0] = "InternalEvent:" + key;
6699
6700 if(this.debug === true || this.debug.includes(key)){
6701 console.log(...args);
6702 }
6703
6704 return this._dispatch(...arguments);
6705 }
6706
6707 _debugChain(){
6708 var args = Array.from(arguments),
6709 key = args[0];
6710
6711 args[0] = "InternalEvent:" + key;
6712
6713 if(this.debug === true || this.debug.includes(key)){
6714 console.log(...args);
6715 }
6716
6717 return this._chain(...arguments);
6718 }
6719
6720 _debugConfirm(){
6721 var args = Array.from(arguments),
6722 key = args[0];
6723
6724 args[0] = "InternalEvent:" + key;
6725
6726 if(this.debug === true || this.debug.includes(key)){
6727 console.log(...args);
6728 }
6729
6730 return this._confirm(...arguments);
6731 }
6732 }
6733
6734 class DeprecationAdvisor extends CoreFeature{
6735
6736 constructor(table){
6737 super(table);
6738 }
6739
6740 _warnUser(){
6741 if(this.options("debugDeprecation")){
6742 console.warn(...arguments);
6743 }
6744 }
6745
6746 check(oldOption, newOption, convert){
6747 var msg = "";
6748
6749 if(typeof this.options(oldOption) !== "undefined"){
6750 msg = "Deprecated Setup Option - Use of the %c" + oldOption + "%c option is now deprecated";
6751
6752 if(newOption){
6753 msg = msg + ", Please use the %c" + newOption + "%c option instead";
6754 this._warnUser(msg, 'font-weight: bold;', 'font-weight: normal;', 'font-weight: bold;', 'font-weight: normal;');
6755
6756 if(convert){
6757 this.table.options[newOption] = this.table.options[oldOption];
6758 }
6759 }else {
6760 this._warnUser(msg, 'font-weight: bold;', 'font-weight: normal;');
6761 }
6762
6763 return false;
6764 }else {
6765 return true;
6766 }
6767 }
6768
6769 checkMsg(oldOption, msg){
6770 if(typeof this.options(oldOption) !== "undefined"){
6771 this._warnUser("%cDeprecated Setup Option - Use of the %c" + oldOption + " %c option is now deprecated, " + msg, 'font-weight: normal;', 'font-weight: bold;', 'font-weight: normal;');
6772
6773 return false;
6774 }else {
6775 return true;
6776 }
6777 }
6778
6779 msg(msg){
6780 this._warnUser(msg);
6781 }
6782 }
6783
6784 class DependencyRegistry extends CoreFeature{
6785
6786 constructor(table){
6787 super(table);
6788
6789 this.deps = {};
6790
6791 this.props = {
6792
6793 };
6794 }
6795
6796 initialize(){
6797 this.deps = Object.assign({}, this.options("dependencies"));
6798 }
6799
6800 lookup(key, prop, silent){
6801 if(Array.isArray(key)){
6802 for (const item of key) {
6803 var match = this.lookup(item, prop, true);
6804
6805 if(match){
6806 break;
6807 }
6808 }
6809
6810 if(match){
6811 return match;
6812 }else {
6813 this.error(key);
6814 }
6815 }else {
6816 if(prop){
6817 return this.lookupProp(key, prop, silent);
6818 }else {
6819 return this.lookupKey(key, silent);
6820 }
6821 }
6822 }
6823
6824 lookupProp(key, prop, silent){
6825 var dependency;
6826
6827 if(this.props[key] && this.props[key][prop]){
6828 return this.props[key][prop];
6829 }else {
6830 dependency = this.lookupKey(key, silent);
6831
6832 if(dependency){
6833 if(!this.props[key]){
6834 this.props[key] = {};
6835 }
6836
6837 this.props[key][prop] = dependency[prop] || dependency;
6838 return this.props[key][prop];
6839 }
6840 }
6841 }
6842
6843 lookupKey(key, silent){
6844 var dependency;
6845
6846 if(this.deps[key]){
6847 dependency = this.deps[key];
6848 }else if(window[key]){
6849 this.deps[key] = window[key];
6850 dependency = this.deps[key];
6851 }else {
6852 if(!silent){
6853 this.error(key);
6854 }
6855 }
6856
6857 return dependency;
6858 }
6859
6860 error(key){
6861 console.error("Unable to find dependency", key, "Please check documentation and ensure you have imported the required library into your project");
6862 }
6863 }
6864
6865 let Popup$1 = class Popup extends CoreFeature{
6866 constructor(table, element, parent){
6867 super(table);
6868
6869 this.element = element;
6870 this.container = this._lookupContainer();
6871
6872 this.parent = parent;
6873
6874 this.reversedX = false;
6875 this.childPopup = null;
6876 this.blurable = false;
6877 this.blurCallback = null;
6878 this.blurEventsBound = false;
6879 this.renderedCallback = null;
6880
6881 this.visible = false;
6882 this.hideable = true;
6883
6884 this.element.classList.add("tabulator-popup-container");
6885
6886 this.blurEvent = this.hide.bind(this, false);
6887 this.escEvent = this._escapeCheck.bind(this);
6888
6889 this.destroyBinding = this.tableDestroyed.bind(this);
6890 this.destroyed = false;
6891 }
6892
6893 tableDestroyed(){
6894 this.destroyed = true;
6895 this.hide(true);
6896 }
6897
6898 _lookupContainer(){
6899 var container = this.table.options.popupContainer;
6900
6901 if(typeof container === "string"){
6902 container = document.querySelector(container);
6903
6904 if(!container){
6905 console.warn("Menu Error - no container element found matching selector:", this.table.options.popupContainer , "(defaulting to document body)");
6906 }
6907 }else if (container === true){
6908 container = this.table.element;
6909 }
6910
6911 if(container && !this._checkContainerIsParent(container)){
6912 container = false;
6913 console.warn("Menu Error - container element does not contain this table:", this.table.options.popupContainer , "(defaulting to document body)");
6914 }
6915
6916 if(!container){
6917 container = document.body;
6918 }
6919
6920 return container;
6921 }
6922
6923 _checkContainerIsParent(container, element = this.table.element){
6924 if(container === element){
6925 return true;
6926 }else {
6927 return element.parentNode ? this._checkContainerIsParent(container, element.parentNode) : false;
6928 }
6929 }
6930
6931 renderCallback(callback){
6932 this.renderedCallback = callback;
6933 }
6934
6935 containerEventCoords(e){
6936 var touch = !(e instanceof MouseEvent);
6937
6938 var x = touch ? e.touches[0].pageX : e.pageX;
6939 var y = touch ? e.touches[0].pageY : e.pageY;
6940
6941 if(this.container !== document.body){
6942 let parentOffset = Helpers.elOffset(this.container);
6943
6944 x -= parentOffset.left;
6945 y -= parentOffset.top;
6946 }
6947
6948 return {x, y};
6949 }
6950
6951 elementPositionCoords(element, position = "right"){
6952 var offset = Helpers.elOffset(element),
6953 containerOffset, x, y;
6954
6955 if(this.container !== document.body){
6956 containerOffset = Helpers.elOffset(this.container);
6957
6958 offset.left -= containerOffset.left;
6959 offset.top -= containerOffset.top;
6960 }
6961
6962 switch(position){
6963 case "right":
6964 x = offset.left + element.offsetWidth;
6965 y = offset.top - 1;
6966 break;
6967
6968 case "bottom":
6969 x = offset.left;
6970 y = offset.top + element.offsetHeight;
6971 break;
6972
6973 case "left":
6974 x = offset.left;
6975 y = offset.top - 1;
6976 break;
6977
6978 case "top":
6979 x = offset.left;
6980 y = offset.top;
6981 break;
6982
6983 case "center":
6984 x = offset.left + (element.offsetWidth / 2);
6985 y = offset.top + (element.offsetHeight / 2);
6986 break;
6987
6988 }
6989
6990 return {x, y, offset};
6991 }
6992
6993 show(origin, position){
6994 var x, y, parentEl, parentOffset, coords;
6995
6996 if(this.destroyed || this.table.destroyed){
6997 return this;
6998 }
6999
7000 if(origin instanceof HTMLElement){
7001 parentEl = origin;
7002 coords = this.elementPositionCoords(origin, position);
7003
7004 parentOffset = coords.offset;
7005 x = coords.x;
7006 y = coords.y;
7007
7008 }else if(typeof origin === "number"){
7009 parentOffset = {top:0, left:0};
7010 x = origin;
7011 y = position;
7012 }else {
7013 coords = this.containerEventCoords(origin);
7014
7015 x = coords.x;
7016 y = coords.y;
7017
7018 this.reversedX = false;
7019 }
7020
7021 this.element.style.top = y + "px";
7022 this.element.style.left = x + "px";
7023
7024 this.container.appendChild(this.element);
7025
7026 if(typeof this.renderedCallback === "function"){
7027 this.renderedCallback();
7028 }
7029
7030 this._fitToScreen(x, y, parentEl, parentOffset, position);
7031
7032 this.visible = true;
7033
7034 this.subscribe("table-destroy", this.destroyBinding);
7035
7036 this.element.addEventListener("mousedown", (e) => {
7037 e.stopPropagation();
7038 });
7039
7040 return this;
7041 }
7042
7043 _fitToScreen(x, y, parentEl, parentOffset, position){
7044 var scrollTop = this.container === document.body ? document.documentElement.scrollTop : this.container.scrollTop;
7045
7046 //move menu to start on right edge if it is too close to the edge of the screen
7047 if((x + this.element.offsetWidth) >= this.container.offsetWidth || this.reversedX){
7048 this.element.style.left = "";
7049
7050 if(parentEl){
7051 this.element.style.right = (this.container.offsetWidth - parentOffset.left) + "px";
7052 }else {
7053 this.element.style.right = (this.container.offsetWidth - x) + "px";
7054 }
7055
7056 this.reversedX = true;
7057 }
7058
7059 //move menu to start on bottom edge if it is too close to the edge of the screen
7060 let offsetHeight = Math.max(this.container.offsetHeight, scrollTop ? this.container.scrollHeight : 0);
7061 if((y + this.element.offsetHeight) > offsetHeight) {
7062 if(parentEl){
7063 switch(position){
7064 case "bottom":
7065 this.element.style.top = (parseInt(this.element.style.top) - this.element.offsetHeight - parentEl.offsetHeight - 1) + "px";
7066 break;
7067
7068 default:
7069 this.element.style.top = (parseInt(this.element.style.top) - this.element.offsetHeight + parentEl.offsetHeight + 1) + "px";
7070 }
7071
7072 }else {
7073 this.element.style.height = offsetHeight + "px";
7074 }
7075 }
7076 }
7077
7078 isVisible(){
7079 return this.visible;
7080 }
7081
7082 hideOnBlur(callback){
7083 this.blurable = true;
7084
7085 if(this.visible){
7086 setTimeout(() => {
7087 if(this.visible){
7088 this.table.rowManager.element.addEventListener("scroll", this.blurEvent);
7089 this.subscribe("cell-editing", this.blurEvent);
7090 document.body.addEventListener("click", this.blurEvent);
7091 document.body.addEventListener("contextmenu", this.blurEvent);
7092 document.body.addEventListener("mousedown", this.blurEvent);
7093 window.addEventListener("resize", this.blurEvent);
7094 document.body.addEventListener("keydown", this.escEvent);
7095
7096 this.blurEventsBound = true;
7097 }
7098 }, 100);
7099
7100 this.blurCallback = callback;
7101 }
7102
7103 return this;
7104 }
7105
7106 _escapeCheck(e){
7107 if(e.keyCode == 27){
7108 this.hide();
7109 }
7110 }
7111
7112 blockHide(){
7113 this.hideable = false;
7114 }
7115
7116 restoreHide(){
7117 this.hideable = true;
7118 }
7119
7120 hide(silent = false){
7121 if(this.visible && this.hideable){
7122 if(this.blurable && this.blurEventsBound){
7123 document.body.removeEventListener("keydown", this.escEvent);
7124 document.body.removeEventListener("click", this.blurEvent);
7125 document.body.removeEventListener("contextmenu", this.blurEvent);
7126 document.body.removeEventListener("mousedown", this.blurEvent);
7127 window.removeEventListener("resize", this.blurEvent);
7128 this.table.rowManager.element.removeEventListener("scroll", this.blurEvent);
7129 this.unsubscribe("cell-editing", this.blurEvent);
7130
7131 this.blurEventsBound = false;
7132 }
7133
7134 if(this.childPopup){
7135 this.childPopup.hide();
7136 }
7137
7138 if(this.parent){
7139 this.parent.childPopup = null;
7140 }
7141
7142 if(this.element.parentNode){
7143 this.element.parentNode.removeChild(this.element);
7144 }
7145
7146 this.visible = false;
7147
7148 if(this.blurCallback && !silent){
7149 this.blurCallback();
7150 }
7151
7152 this.unsubscribe("table-destroy", this.destroyBinding);
7153 }
7154
7155 return this;
7156 }
7157
7158 child(element){
7159 if(this.childPopup){
7160 this.childPopup.hide();
7161 }
7162
7163 this.childPopup = new Popup(this.table, element, this);
7164
7165 return this.childPopup;
7166 }
7167 };
7168
7169 class Module extends CoreFeature{
7170
7171 constructor(table, name){
7172 super(table);
7173
7174 this._handler = null;
7175 }
7176
7177 initialize(){
7178 // setup module when table is initialized, to be overridden in module
7179 }
7180
7181
7182 ///////////////////////////////////
7183 ////// Options Registration ///////
7184 ///////////////////////////////////
7185
7186 registerTableOption(key, value){
7187 this.table.optionsList.register(key, value);
7188 }
7189
7190 registerColumnOption(key, value){
7191 this.table.columnManager.optionsList.register(key, value);
7192 }
7193
7194 ///////////////////////////////////
7195 /// Public Function Registration ///
7196 ///////////////////////////////////
7197
7198 registerTableFunction(name, func){
7199 if(typeof this.table[name] === "undefined"){
7200 this.table[name] = (...args) => {
7201 this.table.initGuard(name);
7202
7203 return func(...args);
7204 };
7205 }else {
7206 console.warn("Unable to bind table function, name already in use", name);
7207 }
7208 }
7209
7210 registerComponentFunction(component, func, handler){
7211 return this.table.componentFunctionBinder.bind(component, func, handler);
7212 }
7213
7214 ///////////////////////////////////
7215 ////////// Data Pipeline //////////
7216 ///////////////////////////////////
7217
7218 registerDataHandler(handler, priority){
7219 this.table.rowManager.registerDataPipelineHandler(handler, priority);
7220 this._handler = handler;
7221 }
7222
7223 registerDisplayHandler(handler, priority){
7224 this.table.rowManager.registerDisplayPipelineHandler(handler, priority);
7225 this._handler = handler;
7226 }
7227
7228 displayRows(adjust){
7229 var index = this.table.rowManager.displayRows.length - 1,
7230 lookupIndex;
7231
7232 if(this._handler){
7233 lookupIndex = this.table.rowManager.displayPipeline.findIndex((item) => {
7234 return item.handler === this._handler;
7235 });
7236
7237 if(lookupIndex > -1){
7238 index = lookupIndex;
7239 }
7240 }
7241
7242 if(adjust){
7243 index = index + adjust;
7244 }
7245
7246 if(this._handler){
7247 if(index > -1){
7248 return this.table.rowManager.getDisplayRows(index);
7249 }else {
7250 return this.activeRows();
7251 }
7252 }
7253 }
7254
7255 activeRows(){
7256 return this.table.rowManager.activeRows;
7257 }
7258
7259 refreshData(renderInPosition, handler){
7260 if(!handler){
7261 handler = this._handler;
7262 }
7263
7264 if(handler){
7265 this.table.rowManager.refreshActiveData(handler, false, renderInPosition);
7266 }
7267 }
7268
7269 ///////////////////////////////////
7270 //////// Footer Management ////////
7271 ///////////////////////////////////
7272
7273 footerAppend(element){
7274 return this.table.footerManager.append(element);
7275 }
7276
7277 footerPrepend(element){
7278 return this.table.footerManager.prepend(element);
7279 }
7280
7281 footerRemove(element){
7282 return this.table.footerManager.remove(element);
7283 }
7284
7285 ///////////////////////////////////
7286 //////// Popups Management ////////
7287 ///////////////////////////////////
7288
7289 popup(menuEl, menuContainer){
7290 return new Popup$1(this.table, menuEl, menuContainer);
7291 }
7292
7293 ///////////////////////////////////
7294 //////// Alert Management ////////
7295 ///////////////////////////////////
7296
7297 alert(content, type){
7298 return this.table.alertManager.alert(content, type);
7299 }
7300
7301 clearAlert(){
7302 return this.table.alertManager.clear();
7303 }
7304
7305 }
7306
7307 //resize columns to fit data they contain
7308 function fitData(columns, forced){
7309 if(forced){
7310 this.table.columnManager.renderer.reinitializeColumnWidths(columns);
7311 }
7312
7313 if(this.table.options.responsiveLayout && this.table.modExists("responsiveLayout", true)){
7314 this.table.modules.responsiveLayout.update();
7315 }
7316 }
7317
7318 //resize columns to fit data they contain and stretch row to fill table, also used for fitDataTable
7319 function fitDataGeneral(columns, forced){
7320 columns.forEach(function(column){
7321 column.reinitializeWidth();
7322 });
7323
7324 if(this.table.options.responsiveLayout && this.table.modExists("responsiveLayout", true)){
7325 this.table.modules.responsiveLayout.update();
7326 }
7327 }
7328
7329 //resize columns to fit data the contain and stretch last column to fill table
7330 function fitDataStretch(columns, forced){
7331 var colsWidth = 0,
7332 tableWidth = this.table.rowManager.element.clientWidth,
7333 gap = 0,
7334 lastCol = false;
7335
7336 columns.forEach((column, i) => {
7337 if(!column.widthFixed){
7338 column.reinitializeWidth();
7339 }
7340
7341 if(this.table.options.responsiveLayout ? column.modules.responsive.visible : column.visible){
7342 lastCol = column;
7343 }
7344
7345 if(column.visible){
7346 colsWidth += column.getWidth();
7347 }
7348 });
7349
7350 if(lastCol){
7351 gap = tableWidth - colsWidth + lastCol.getWidth();
7352
7353 if(this.table.options.responsiveLayout && this.table.modExists("responsiveLayout", true)){
7354 lastCol.setWidth(0);
7355 this.table.modules.responsiveLayout.update();
7356 }
7357
7358 if(gap > 0){
7359 lastCol.setWidth(gap);
7360 }else {
7361 lastCol.reinitializeWidth();
7362 }
7363 }else {
7364 if(this.table.options.responsiveLayout && this.table.modExists("responsiveLayout", true)){
7365 this.table.modules.responsiveLayout.update();
7366 }
7367 }
7368 }
7369
7370 //resize columns to fit
7371 function fitColumns(columns, forced){
7372 var totalWidth = this.table.rowManager.element.getBoundingClientRect().width; //table element width
7373 var fixedWidth = 0; //total width of columns with a defined width
7374 var flexWidth = 0; //total width available to flexible columns
7375 var flexGrowUnits = 0; //total number of widthGrow blocks across all columns
7376 var flexColWidth = 0; //desired width of flexible columns
7377 var flexColumns = []; //array of flexible width columns
7378 var fixedShrinkColumns = []; //array of fixed width columns that can shrink
7379 var flexShrinkUnits = 0; //total number of widthShrink blocks across all columns
7380 var overflowWidth = 0; //horizontal overflow width
7381 var gapFill = 0; //number of pixels to be added to final column to close and half pixel gaps
7382
7383 function calcWidth(width){
7384 var colWidth;
7385
7386 if(typeof(width) == "string"){
7387 if(width.indexOf("%") > -1){
7388 colWidth = (totalWidth / 100) * parseInt(width);
7389 }else {
7390 colWidth = parseInt(width);
7391 }
7392 }else {
7393 colWidth = width;
7394 }
7395
7396 return colWidth;
7397 }
7398
7399 //ensure columns resize to take up the correct amount of space
7400 function scaleColumns(columns, freeSpace, colWidth, shrinkCols){
7401 var oversizeCols = [],
7402 oversizeSpace = 0,
7403 remainingSpace = 0,
7404 nextColWidth = 0,
7405 remainingFlexGrowUnits = flexGrowUnits,
7406 gap = 0,
7407 changeUnits = 0,
7408 undersizeCols = [];
7409
7410 function calcGrow(col){
7411 return (colWidth * (col.column.definition.widthGrow || 1));
7412 }
7413
7414 function calcShrink(col){
7415 return (calcWidth(col.width) - (colWidth * (col.column.definition.widthShrink || 0)));
7416 }
7417
7418 columns.forEach(function(col, i){
7419 var width = shrinkCols ? calcShrink(col) : calcGrow(col);
7420 if(col.column.minWidth >= width){
7421 oversizeCols.push(col);
7422 }else {
7423 if(col.column.maxWidth && col.column.maxWidth < width){
7424 col.width = col.column.maxWidth;
7425 freeSpace -= col.column.maxWidth;
7426
7427 remainingFlexGrowUnits -= shrinkCols ? (col.column.definition.widthShrink || 1) : (col.column.definition.widthGrow || 1);
7428
7429 if(remainingFlexGrowUnits){
7430 colWidth = Math.floor(freeSpace/remainingFlexGrowUnits);
7431 }
7432 }else {
7433 undersizeCols.push(col);
7434 changeUnits += shrinkCols ? (col.column.definition.widthShrink || 1) : (col.column.definition.widthGrow || 1);
7435 }
7436 }
7437 });
7438
7439 if(oversizeCols.length){
7440 oversizeCols.forEach(function(col){
7441 oversizeSpace += shrinkCols ? col.width - col.column.minWidth : col.column.minWidth;
7442 col.width = col.column.minWidth;
7443 });
7444
7445 remainingSpace = freeSpace - oversizeSpace;
7446
7447 nextColWidth = changeUnits ? Math.floor(remainingSpace/changeUnits) : remainingSpace;
7448
7449 gap = scaleColumns(undersizeCols, remainingSpace, nextColWidth, shrinkCols);
7450 }else {
7451 gap = changeUnits ? freeSpace - (Math.floor(freeSpace/changeUnits) * changeUnits) : freeSpace;
7452
7453 undersizeCols.forEach(function(column){
7454 column.width = shrinkCols ? calcShrink(column) : calcGrow(column);
7455 });
7456 }
7457
7458 return gap;
7459 }
7460
7461 if(this.table.options.responsiveLayout && this.table.modExists("responsiveLayout", true)){
7462 this.table.modules.responsiveLayout.update();
7463 }
7464
7465 //adjust for vertical scrollbar if present
7466 if(this.table.rowManager.element.scrollHeight > this.table.rowManager.element.clientHeight){
7467 totalWidth -= this.table.rowManager.element.offsetWidth - this.table.rowManager.element.clientWidth;
7468 }
7469
7470 columns.forEach(function(column){
7471 var width, minWidth, colWidth;
7472
7473 if(column.visible){
7474
7475 width = column.definition.width;
7476 minWidth = parseInt(column.minWidth);
7477
7478 if(width){
7479
7480 colWidth = calcWidth(width);
7481
7482 fixedWidth += colWidth > minWidth ? colWidth : minWidth;
7483
7484 if(column.definition.widthShrink){
7485 fixedShrinkColumns.push({
7486 column:column,
7487 width:colWidth > minWidth ? colWidth : minWidth
7488 });
7489 flexShrinkUnits += column.definition.widthShrink;
7490 }
7491
7492 }else {
7493 flexColumns.push({
7494 column:column,
7495 width:0,
7496 });
7497 flexGrowUnits += column.definition.widthGrow || 1;
7498 }
7499 }
7500 });
7501
7502 //calculate available space
7503 flexWidth = totalWidth - fixedWidth;
7504
7505 //calculate correct column size
7506 flexColWidth = Math.floor(flexWidth / flexGrowUnits);
7507
7508 //generate column widths
7509 gapFill = scaleColumns(flexColumns, flexWidth, flexColWidth, false);
7510
7511 //increase width of last column to account for rounding errors
7512 if(flexColumns.length && gapFill > 0){
7513 flexColumns[flexColumns.length-1].width += gapFill;
7514 }
7515
7516 //calculate space for columns to be shrunk into
7517 flexColumns.forEach(function(col){
7518 flexWidth -= col.width;
7519 });
7520
7521 overflowWidth = Math.abs(gapFill) + flexWidth;
7522
7523 //shrink oversize columns if there is no available space
7524 if(overflowWidth > 0 && flexShrinkUnits){
7525 gapFill = scaleColumns(fixedShrinkColumns, overflowWidth, Math.floor(overflowWidth / flexShrinkUnits), true);
7526 }
7527
7528 //decrease width of last column to account for rounding errors
7529 if(gapFill && fixedShrinkColumns.length){
7530 fixedShrinkColumns[fixedShrinkColumns.length-1].width -= gapFill;
7531 }
7532
7533 flexColumns.forEach(function(col){
7534 col.column.setWidth(col.width);
7535 });
7536
7537 fixedShrinkColumns.forEach(function(col){
7538 col.column.setWidth(col.width);
7539 });
7540 }
7541
7542 var defaultModes = {
7543 fitData:fitData,
7544 fitDataFill:fitDataGeneral,
7545 fitDataTable:fitDataGeneral,
7546 fitDataStretch:fitDataStretch,
7547 fitColumns:fitColumns ,
7548 };
7549
7550 class Layout extends Module{
7551
7552 static moduleName = "layout";
7553
7554 //load defaults
7555 static modes = defaultModes;
7556
7557 constructor(table){
7558 super(table, "layout");
7559
7560 this.mode = null;
7561
7562 this.registerTableOption("layout", "fitData"); //layout type
7563 this.registerTableOption("layoutColumnsOnNewData", false); //update column widths on setData
7564
7565 this.registerColumnOption("widthGrow");
7566 this.registerColumnOption("widthShrink");
7567 }
7568
7569 //initialize layout system
7570 initialize(){
7571 var layout = this.table.options.layout;
7572
7573 if(Layout.modes[layout]){
7574 this.mode = layout;
7575 }else {
7576 console.warn("Layout Error - invalid mode set, defaulting to 'fitData' : " + layout);
7577 this.mode = 'fitData';
7578 }
7579
7580 this.table.element.setAttribute("tabulator-layout", this.mode);
7581 this.subscribe("column-init", this.initializeColumn.bind(this));
7582 }
7583
7584 initializeColumn(column){
7585 if(column.definition.widthGrow){
7586 column.definition.widthGrow = Number(column.definition.widthGrow);
7587 }
7588 if(column.definition.widthShrink){
7589 column.definition.widthShrink = Number(column.definition.widthShrink);
7590 }
7591 }
7592
7593 getMode(){
7594 return this.mode;
7595 }
7596
7597 //trigger table layout
7598 layout(dataChanged){
7599
7600 var variableHeight = this.table.columnManager.columnsByIndex.find((column) => column.definition.variableHeight || column.definition.formatter === "textarea");
7601
7602 this.dispatch("layout-refreshing");
7603 Layout.modes[this.mode].call(this, this.table.columnManager.columnsByIndex, dataChanged);
7604
7605 if(variableHeight){
7606 this.table.rowManager.normalizeHeight(true);
7607 }
7608
7609 this.dispatch("layout-refreshed");
7610 }
7611 }
7612
7613 var defaultLangs = {
7614 "default":{ //hold default locale text
7615 "groups":{
7616 "item":"item",
7617 "items":"items",
7618 },
7619 "columns":{
7620 },
7621 "data":{
7622 "loading":"Loading",
7623 "error":"Error",
7624 },
7625 "pagination":{
7626 "page_size":"Page Size",
7627 "page_title":"Show Page",
7628 "first":"First",
7629 "first_title":"First Page",
7630 "last":"Last",
7631 "last_title":"Last Page",
7632 "prev":"Prev",
7633 "prev_title":"Prev Page",
7634 "next":"Next",
7635 "next_title":"Next Page",
7636 "all":"All",
7637 "counter":{
7638 "showing": "Showing",
7639 "of": "of",
7640 "rows": "rows",
7641 "pages": "pages",
7642 }
7643 },
7644 "headerFilters":{
7645 "default":"filter column...",
7646 "columns":{}
7647 }
7648 },
7649 };
7650
7651 class Localize extends Module{
7652
7653 static moduleName = "localize";
7654
7655 //load defaults
7656 static langs = defaultLangs;
7657
7658 constructor(table){
7659 super(table);
7660
7661 this.locale = "default"; //current locale
7662 this.lang = false; //current language
7663 this.bindings = {}; //update events to call when locale is changed
7664 this.langList = {};
7665
7666 this.registerTableOption("locale", false); //current system language
7667 this.registerTableOption("langs", {});
7668 }
7669
7670 initialize(){
7671 this.langList = Helpers.deepClone(Localize.langs);
7672
7673 if(this.table.options.columnDefaults.headerFilterPlaceholder !== false){
7674 this.setHeaderFilterPlaceholder(this.table.options.columnDefaults.headerFilterPlaceholder);
7675 }
7676
7677 for(let locale in this.table.options.langs){
7678 this.installLang(locale, this.table.options.langs[locale]);
7679 }
7680
7681 this.setLocale(this.table.options.locale);
7682
7683 this.registerTableFunction("setLocale", this.setLocale.bind(this));
7684 this.registerTableFunction("getLocale", this.getLocale.bind(this));
7685 this.registerTableFunction("getLang", this.getLang.bind(this));
7686 }
7687
7688 //set header placeholder
7689 setHeaderFilterPlaceholder(placeholder){
7690 this.langList.default.headerFilters.default = placeholder;
7691 }
7692
7693 //setup a lang description object
7694 installLang(locale, lang){
7695 if(this.langList[locale]){
7696 this._setLangProp(this.langList[locale], lang);
7697 }else {
7698 this.langList[locale] = lang;
7699 }
7700 }
7701
7702 _setLangProp(lang, values){
7703 for(let key in values){
7704 if(lang[key] && typeof lang[key] == "object"){
7705 this._setLangProp(lang[key], values[key]);
7706 }else {
7707 lang[key] = values[key];
7708 }
7709 }
7710 }
7711
7712 //set current locale
7713 setLocale(desiredLocale){
7714 desiredLocale = desiredLocale || "default";
7715
7716 //fill in any matching language values
7717 function traverseLang(trans, path){
7718 for(var prop in trans){
7719 if(typeof trans[prop] == "object"){
7720 if(!path[prop]){
7721 path[prop] = {};
7722 }
7723 traverseLang(trans[prop], path[prop]);
7724 }else {
7725 path[prop] = trans[prop];
7726 }
7727 }
7728 }
7729
7730 //determining correct locale to load
7731 if(desiredLocale === true && navigator.language){
7732 //get local from system
7733 desiredLocale = navigator.language.toLowerCase();
7734 }
7735
7736 if(desiredLocale){
7737 //if locale is not set, check for matching top level locale else use default
7738 if(!this.langList[desiredLocale]){
7739 let prefix = desiredLocale.split("-")[0];
7740
7741 if(this.langList[prefix]){
7742 console.warn("Localization Error - Exact matching locale not found, using closest match: ", desiredLocale, prefix);
7743 desiredLocale = prefix;
7744 }else {
7745 console.warn("Localization Error - Matching locale not found, using default: ", desiredLocale);
7746 desiredLocale = "default";
7747 }
7748 }
7749 }
7750
7751 this.locale = desiredLocale;
7752
7753 //load default lang template
7754 this.lang = Helpers.deepClone(this.langList.default || {});
7755
7756 if(desiredLocale != "default"){
7757 traverseLang(this.langList[desiredLocale], this.lang);
7758 }
7759
7760 this.dispatchExternal("localized", this.locale, this.lang);
7761
7762 this._executeBindings();
7763 }
7764
7765 //get current locale
7766 getLocale(locale){
7767 return this.locale;
7768 }
7769
7770 //get lang object for given local or current if none provided
7771 getLang(locale){
7772 return locale ? this.langList[locale] : this.lang;
7773 }
7774
7775 //get text for current locale
7776 getText(path, value){
7777 var fillPath = value ? path + "|" + value : path,
7778 pathArray = fillPath.split("|"),
7779 text = this._getLangElement(pathArray, this.locale);
7780
7781 // if(text === false){
7782 // console.warn("Localization Error - Matching localized text not found for given path: ", path);
7783 // }
7784
7785 return text || "";
7786 }
7787
7788 //traverse langs object and find localized copy
7789 _getLangElement(path, locale){
7790 var root = this.lang;
7791
7792 path.forEach(function(level){
7793 var rootPath;
7794
7795 if(root){
7796 rootPath = root[level];
7797
7798 if(typeof rootPath != "undefined"){
7799 root = rootPath;
7800 }else {
7801 root = false;
7802 }
7803 }
7804 });
7805
7806 return root;
7807 }
7808
7809 //set update binding
7810 bind(path, callback){
7811 if(!this.bindings[path]){
7812 this.bindings[path] = [];
7813 }
7814
7815 this.bindings[path].push(callback);
7816
7817 callback(this.getText(path), this.lang);
7818 }
7819
7820 //iterate through bindings and trigger updates
7821 _executeBindings(){
7822 for(let path in this.bindings){
7823 this.bindings[path].forEach((binding) => {
7824 binding(this.getText(path), this.lang);
7825 });
7826 }
7827 }
7828 }
7829
7830 class Comms extends Module{
7831
7832 static moduleName = "comms";
7833
7834 constructor(table){
7835 super(table);
7836 }
7837
7838 initialize(){
7839 this.registerTableFunction("tableComms", this.receive.bind(this));
7840 }
7841
7842 getConnections(selectors){
7843 var connections = [],
7844 connection;
7845
7846 connection = this.table.constructor.registry.lookupTable(selectors);
7847
7848 connection.forEach((con) =>{
7849 if(this.table !== con){
7850 connections.push(con);
7851 }
7852 });
7853
7854 return connections;
7855 }
7856
7857 send(selectors, module, action, data){
7858 var connections = this.getConnections(selectors);
7859
7860 connections.forEach((connection) => {
7861 connection.tableComms(this.table.element, module, action, data);
7862 });
7863
7864 if(!connections.length && selectors){
7865 console.warn("Table Connection Error - No tables matching selector found", selectors);
7866 }
7867 }
7868
7869 receive(table, module, action, data){
7870 if(this.table.modExists(module)){
7871 return this.table.modules[module].commsReceived(table, action, data);
7872 }else {
7873 console.warn("Inter-table Comms Error - no such module:", module);
7874 }
7875 }
7876 }
7877
7878 var coreModules = /*#__PURE__*/Object.freeze({
7879 __proto__: null,
7880 CommsModule: Comms,
7881 LayoutModule: Layout,
7882 LocalizeModule: Localize
7883 });
7884
7885 class TableRegistry {
7886 static registry = {
7887 tables:[],
7888
7889 register(table){
7890 TableRegistry.registry.tables.push(table);
7891 },
7892
7893 deregister(table){
7894 var index = TableRegistry.registry.tables.indexOf(table);
7895
7896 if(index > -1){
7897 TableRegistry.registry.tables.splice(index, 1);
7898 }
7899 },
7900
7901 lookupTable(query, silent){
7902 var results = [],
7903 matches, match;
7904
7905 if(typeof query === "string"){
7906 matches = document.querySelectorAll(query);
7907
7908 if(matches.length){
7909 for(var i = 0; i < matches.length; i++){
7910 match = TableRegistry.registry.matchElement(matches[i]);
7911
7912 if(match){
7913 results.push(match);
7914 }
7915 }
7916 }
7917
7918 }else if((typeof HTMLElement !== "undefined" && query instanceof HTMLElement) || query instanceof TableRegistry){
7919 match = TableRegistry.registry.matchElement(query);
7920
7921 if(match){
7922 results.push(match);
7923 }
7924 }else if(Array.isArray(query)){
7925 query.forEach(function(item){
7926 results = results.concat(TableRegistry.registry.lookupTable(item));
7927 });
7928 }else {
7929 if(!silent){
7930 console.warn("Table Connection Error - Invalid Selector", query);
7931 }
7932 }
7933
7934 return results;
7935 },
7936
7937 matchElement(element){
7938 return TableRegistry.registry.tables.find(function(table){
7939 return element instanceof TableRegistry ? table === element : table.element === element;
7940 });
7941 }
7942 };
7943
7944
7945 static findTable(query){
7946 var results = TableRegistry.registry.lookupTable(query, true);
7947 return Array.isArray(results) && !results.length ? false : results;
7948 }
7949 }
7950
7951 class ModuleBinder extends TableRegistry {
7952
7953 static moduleBindings = {};
7954 static moduleExtensions = {};
7955 static modulesRegistered = false;
7956
7957 static defaultModules = false;
7958
7959 constructor(){
7960 super();
7961 }
7962
7963 static initializeModuleBinder(defaultModules){
7964 if(!ModuleBinder.modulesRegistered){
7965 ModuleBinder.modulesRegistered = true;
7966 ModuleBinder._registerModules(coreModules, true);
7967
7968 if(defaultModules){
7969 ModuleBinder._registerModules(defaultModules);
7970 }
7971 }
7972 }
7973
7974 static _extendModule(name, property, values){
7975 if(ModuleBinder.moduleBindings[name]){
7976 var source = ModuleBinder.moduleBindings[name][property];
7977
7978 if(source){
7979 if(typeof values == "object"){
7980 for(let key in values){
7981 source[key] = values[key];
7982 }
7983 }else {
7984 console.warn("Module Error - Invalid value type, it must be an object");
7985 }
7986 }else {
7987 console.warn("Module Error - property does not exist:", property);
7988 }
7989 }else {
7990 console.warn("Module Error - module does not exist:", name);
7991 }
7992 }
7993
7994 static _registerModules(modules, core){
7995 var mods = Object.values(modules);
7996
7997 if(core){
7998 mods.forEach((mod) => {
7999 mod.prototype.moduleCore = true;
8000 });
8001 }
8002
8003 ModuleBinder._registerModule(mods);
8004 }
8005
8006 static _registerModule(modules){
8007 if(!Array.isArray(modules)){
8008 modules = [modules];
8009 }
8010
8011 modules.forEach((mod) => {
8012 ModuleBinder._registerModuleBinding(mod);
8013 ModuleBinder._registerModuleExtensions(mod);
8014 });
8015 }
8016
8017 static _registerModuleBinding(mod){
8018 if(mod.moduleName){
8019 ModuleBinder.moduleBindings[mod.moduleName] = mod;
8020 }else {
8021 console.error("Unable to bind module, no moduleName defined", mod.moduleName);
8022 }
8023 }
8024
8025 static _registerModuleExtensions(mod){
8026 var extensions = mod.moduleExtensions;
8027
8028 if(mod.moduleExtensions){
8029 for (let modKey in extensions) {
8030 let ext = extensions[modKey];
8031
8032 if(ModuleBinder.moduleBindings[modKey]){
8033 for (let propKey in ext) {
8034 ModuleBinder._extendModule(modKey, propKey, ext[propKey]);
8035 }
8036 }else {
8037 if(!ModuleBinder.moduleExtensions[modKey]){
8038 ModuleBinder.moduleExtensions[modKey] = {};
8039 }
8040
8041 for (let propKey in ext) {
8042 if(!ModuleBinder.moduleExtensions[modKey][propKey]){
8043 ModuleBinder.moduleExtensions[modKey][propKey] = {};
8044 }
8045
8046 Object.assign(ModuleBinder.moduleExtensions[modKey][propKey], ext[propKey]);
8047 }
8048 }
8049 }
8050 }
8051
8052 ModuleBinder._extendModuleFromQueue(mod);
8053 }
8054
8055 static _extendModuleFromQueue(mod){
8056 var extensions = ModuleBinder.moduleExtensions[mod.moduleName];
8057
8058 if(extensions){
8059 for (let propKey in extensions) {
8060 ModuleBinder._extendModule(mod.moduleName, propKey, extensions[propKey]);
8061 }
8062 }
8063 }
8064
8065 //ensure that module are bound to instantiated function
8066 _bindModules(){
8067 var orderedStartMods = [],
8068 orderedEndMods = [],
8069 unOrderedMods = [];
8070
8071 this.modules = {};
8072
8073 for(var name in ModuleBinder.moduleBindings){
8074 let mod = ModuleBinder.moduleBindings[name];
8075 let module = new mod(this);
8076
8077 this.modules[name] = module;
8078
8079 if(mod.prototype.moduleCore){
8080 this.modulesCore.push(module);
8081 }else {
8082 if(mod.moduleInitOrder){
8083 if(mod.moduleInitOrder < 0){
8084 orderedStartMods.push(module);
8085 }else {
8086 orderedEndMods.push(module);
8087 }
8088
8089 }else {
8090 unOrderedMods.push(module);
8091 }
8092 }
8093 }
8094
8095 orderedStartMods.sort((a, b) => a.moduleInitOrder > b.moduleInitOrder ? 1 : -1);
8096 orderedEndMods.sort((a, b) => a.moduleInitOrder > b.moduleInitOrder ? 1 : -1);
8097
8098 this.modulesRegular = orderedStartMods.concat(unOrderedMods.concat(orderedEndMods));
8099 }
8100 }
8101
8102 class Alert extends CoreFeature{
8103 constructor(table){
8104 super(table);
8105
8106 this.element = this._createAlertElement();
8107 this.msgElement = this._createMsgElement();
8108 this.type = null;
8109
8110 this.element.appendChild(this.msgElement);
8111 }
8112
8113 _createAlertElement(){
8114 var el = document.createElement("div");
8115 el.classList.add("tabulator-alert");
8116 return el;
8117 }
8118
8119 _createMsgElement(){
8120 var el = document.createElement("div");
8121 el.classList.add("tabulator-alert-msg");
8122 el.setAttribute("role", "alert");
8123 return el;
8124 }
8125
8126 _typeClass(){
8127 return "tabulator-alert-state-" + this.type;
8128 }
8129
8130 alert(content, type = "msg"){
8131 if(content){
8132 this.clear();
8133
8134 this.dispatch("alert-show", type);
8135
8136 this.type = type;
8137
8138 while(this.msgElement.firstChild) this.msgElement.removeChild(this.msgElement.firstChild);
8139
8140 this.msgElement.classList.add(this._typeClass());
8141
8142 if(typeof content === "function"){
8143 content = content();
8144 }
8145
8146 if(content instanceof HTMLElement){
8147 this.msgElement.appendChild(content);
8148 }else {
8149 this.msgElement.innerHTML = content;
8150 }
8151
8152 this.table.element.appendChild(this.element);
8153 }
8154 }
8155
8156 clear(){
8157 this.dispatch("alert-hide", this.type);
8158
8159 if(this.element.parentNode){
8160 this.element.parentNode.removeChild(this.element);
8161 }
8162
8163 this.msgElement.classList.remove(this._typeClass());
8164 }
8165 }
8166
8167 class Tabulator extends ModuleBinder{
8168
8169 //default setup options
8170 static defaultOptions = defaultOptions;
8171
8172 static extendModule(){
8173 Tabulator.initializeModuleBinder();
8174 Tabulator._extendModule(...arguments);
8175 }
8176
8177 static registerModule(){
8178 Tabulator.initializeModuleBinder();
8179 Tabulator._registerModule(...arguments);
8180 }
8181
8182 constructor(element, options, modules){
8183 super();
8184
8185 Tabulator.initializeModuleBinder(modules);
8186
8187 this.options = {};
8188
8189 this.columnManager = null; // hold Column Manager
8190 this.rowManager = null; //hold Row Manager
8191 this.footerManager = null; //holder Footer Manager
8192 this.alertManager = null; //hold Alert Manager
8193 this.vdomHoz = null; //holder horizontal virtual dom
8194 this.externalEvents = null; //handle external event messaging
8195 this.eventBus = null; //handle internal event messaging
8196 this.interactionMonitor = false; //track user interaction
8197 this.browser = ""; //hold current browser type
8198 this.browserSlow = false; //handle reduced functionality for slower browsers
8199 this.browserMobile = false; //check if running on mobile, prevent resize cancelling edit on keyboard appearance
8200 this.rtl = false; //check if the table is in RTL mode
8201 this.originalElement = null; //hold original table element if it has been replaced
8202
8203 this.componentFunctionBinder = new ComponentFunctionBinder(this); //bind component functions
8204 this.dataLoader = false; //bind component functions
8205
8206 this.modules = {}; //hold all modules bound to this table
8207 this.modulesCore = []; //hold core modules bound to this table (for initialization purposes)
8208 this.modulesRegular = []; //hold regular modules bound to this table (for initialization purposes)
8209
8210 this.deprecationAdvisor = new DeprecationAdvisor(this);
8211 this.optionsList = new OptionsList(this, "table constructor");
8212
8213 this.dependencyRegistry = new DependencyRegistry(this);
8214
8215 this.initialized = false;
8216 this.destroyed = false;
8217
8218 if(this.initializeElement(element)){
8219
8220 this.initializeCoreSystems(options);
8221
8222 //delay table creation to allow event bindings immediately after the constructor
8223 setTimeout(() => {
8224 this._create();
8225 });
8226 }
8227
8228 this.constructor.registry.register(this); //register table for inter-device communication
8229 }
8230
8231 initializeElement(element){
8232 if(typeof HTMLElement !== "undefined" && element instanceof HTMLElement){
8233 this.element = element;
8234 return true;
8235 }else if(typeof element === "string"){
8236 this.element = document.querySelector(element);
8237
8238 if(this.element){
8239 return true;
8240 }else {
8241 console.error("Tabulator Creation Error - no element found matching selector: ", element);
8242 return false;
8243 }
8244 }else {
8245 console.error("Tabulator Creation Error - Invalid element provided:", element);
8246 return false;
8247 }
8248 }
8249
8250 initializeCoreSystems(options){
8251 this.columnManager = new ColumnManager(this);
8252 this.rowManager = new RowManager(this);
8253 this.footerManager = new FooterManager(this);
8254 this.dataLoader = new DataLoader(this);
8255 this.alertManager = new Alert(this);
8256
8257 this._bindModules();
8258
8259 this.options = this.optionsList.generate(Tabulator.defaultOptions, options);
8260
8261 this._clearObjectPointers();
8262
8263 this._mapDeprecatedFunctionality();
8264
8265 this.externalEvents = new ExternalEventBus(this, this.options, this.options.debugEventsExternal);
8266 this.eventBus = new InternalEventBus(this.options.debugEventsInternal);
8267
8268 this.interactionMonitor = new InteractionManager(this);
8269
8270 this.dataLoader.initialize();
8271 this.footerManager.initialize();
8272
8273 this.dependencyRegistry.initialize();
8274 }
8275
8276 //convert deprecated functionality to new functions
8277 _mapDeprecatedFunctionality(){
8278 //all previously deprecated functionality removed in the 6.0 release
8279 }
8280
8281 _clearSelection(){
8282
8283 this.element.classList.add("tabulator-block-select");
8284
8285 if (window.getSelection) {
8286 if (window.getSelection().empty) { // Chrome
8287 window.getSelection().empty();
8288 } else if (window.getSelection().removeAllRanges) { // Firefox
8289 window.getSelection().removeAllRanges();
8290 }
8291 } else if (document.selection) { // IE?
8292 document.selection.empty();
8293 }
8294
8295 this.element.classList.remove("tabulator-block-select");
8296 }
8297
8298 //create table
8299 _create(){
8300 this.externalEvents.dispatch("tableBuilding");
8301 this.eventBus.dispatch("table-building");
8302
8303 this._rtlCheck();
8304
8305 this._buildElement();
8306
8307 this._initializeTable();
8308
8309 this.initialized = true;
8310
8311 this._loadInitialData()
8312 .finally(() => {
8313 this.eventBus.dispatch("table-initialized");
8314 this.externalEvents.dispatch("tableBuilt");
8315 });
8316 }
8317
8318 _rtlCheck(){
8319 var style = window.getComputedStyle(this.element);
8320
8321 switch(this.options.textDirection){
8322 case"auto":
8323 if(style.direction !== "rtl"){
8324 break;
8325 }
8326
8327 case "rtl":
8328 this.element.classList.add("tabulator-rtl");
8329 this.rtl = true;
8330 break;
8331
8332 case "ltr":
8333 this.element.classList.add("tabulator-ltr");
8334
8335 default:
8336 this.rtl = false;
8337 }
8338 }
8339
8340 //clear pointers to objects in default config object
8341 _clearObjectPointers(){
8342 this.options.columns = this.options.columns.slice(0);
8343
8344 if(Array.isArray(this.options.data) && !this.options.reactiveData){
8345 this.options.data = this.options.data.slice(0);
8346 }
8347 }
8348
8349 //build tabulator element
8350 _buildElement(){
8351 var element = this.element,
8352 options = this.options,
8353 newElement;
8354
8355 if(element.tagName === "TABLE"){
8356 this.originalElement = this.element;
8357 newElement = document.createElement("div");
8358
8359 //transfer attributes to new element
8360 var attributes = element.attributes;
8361
8362 // loop through attributes and apply them on div
8363 for(var i in attributes){
8364 if(typeof attributes[i] == "object"){
8365 newElement.setAttribute(attributes[i].name, attributes[i].value);
8366 }
8367 }
8368
8369 // replace table with div element
8370 element.parentNode.replaceChild(newElement, element);
8371
8372 this.element = element = newElement;
8373 }
8374
8375 element.classList.add("tabulator");
8376 element.setAttribute("role", "grid");
8377
8378 //empty element
8379 while(element.firstChild) element.removeChild(element.firstChild);
8380
8381 //set table height
8382 if(options.height){
8383 options.height = isNaN(options.height) ? options.height : options.height + "px";
8384 element.style.height = options.height;
8385 }
8386
8387 //set table min height
8388 if(options.minHeight !== false){
8389 options.minHeight = isNaN(options.minHeight) ? options.minHeight : options.minHeight + "px";
8390 element.style.minHeight = options.minHeight;
8391 }
8392
8393 //set table maxHeight
8394 if(options.maxHeight !== false){
8395 options.maxHeight = isNaN(options.maxHeight) ? options.maxHeight : options.maxHeight + "px";
8396 element.style.maxHeight = options.maxHeight;
8397 }
8398 }
8399
8400 //initialize core systems and modules
8401 _initializeTable(){
8402 var element = this.element,
8403 options = this.options;
8404
8405 this.interactionMonitor.initialize();
8406
8407 this.columnManager.initialize();
8408 this.rowManager.initialize();
8409
8410 this._detectBrowser();
8411
8412 //initialize core modules
8413 this.modulesCore.forEach((mod) => {
8414 mod.initialize();
8415 });
8416
8417 //build table elements
8418 element.appendChild(this.columnManager.getElement());
8419 element.appendChild(this.rowManager.getElement());
8420
8421 if(options.footerElement){
8422 this.footerManager.activate();
8423 }
8424
8425 if(options.autoColumns && options.data){
8426
8427 this.columnManager.generateColumnsFromRowData(this.options.data);
8428 }
8429
8430 //initialize regular modules
8431 this.modulesRegular.forEach((mod) => {
8432 mod.initialize();
8433 });
8434
8435 this.columnManager.setColumns(options.columns);
8436
8437 this.eventBus.dispatch("table-built");
8438 }
8439
8440 _loadInitialData(){
8441 return this.dataLoader.load(this.options.data)
8442 .finally(() => {
8443 this.columnManager.verticalAlignHeaders();
8444 });
8445 }
8446
8447 //deconstructor
8448 destroy(){
8449 var element = this.element;
8450
8451 this.destroyed = true;
8452
8453 this.constructor.registry.deregister(this); //deregister table from inter-device communication
8454
8455 this.eventBus.dispatch("table-destroy");
8456
8457 //clear row data
8458 this.rowManager.destroy();
8459
8460 //clear DOM
8461 while(element.firstChild) element.removeChild(element.firstChild);
8462 element.classList.remove("tabulator");
8463
8464 this.externalEvents.dispatch("tableDestroyed");
8465 }
8466
8467 _detectBrowser(){
8468 var ua = navigator.userAgent||navigator.vendor||window.opera;
8469
8470 if(ua.indexOf("Trident") > -1){
8471 this.browser = "ie";
8472 this.browserSlow = true;
8473 }else if(ua.indexOf("Edge") > -1){
8474 this.browser = "edge";
8475 this.browserSlow = true;
8476 }else if(ua.indexOf("Firefox") > -1){
8477 this.browser = "firefox";
8478 this.browserSlow = false;
8479 }else if(ua.indexOf("Mac OS") > -1){
8480 this.browser = "safari";
8481 this.browserSlow = false;
8482 }else {
8483 this.browser = "other";
8484 this.browserSlow = false;
8485 }
8486
8487 this.browserMobile = /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(ua)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test(ua.slice(0,4));
8488 }
8489
8490 initGuard(func, msg){
8491 var stack, line;
8492
8493 if(this.options.debugInitialization && !this.initialized){
8494 if(!func){
8495 stack = new Error().stack.split("\n");
8496
8497 line = stack[0] == "Error" ? stack[2] : stack[1];
8498
8499 if(line[0] == " "){
8500 func = line.trim().split(" ")[1].split(".")[1];
8501 }else {
8502 func = line.trim().split("@")[0];
8503 }
8504 }
8505
8506 console.warn("Table Not Initialized - Calling the " + func + " function before the table is initialized may result in inconsistent behavior, Please wait for the `tableBuilt` event before calling this function." + (msg ? " " + msg : ""));
8507 }
8508
8509 return this.initialized;
8510 }
8511
8512 ////////////////// Data Handling //////////////////
8513 //block table redrawing
8514 blockRedraw(){
8515 this.initGuard();
8516
8517 this.eventBus.dispatch("redraw-blocking");
8518
8519 this.rowManager.blockRedraw();
8520 this.columnManager.blockRedraw();
8521
8522 this.eventBus.dispatch("redraw-blocked");
8523 }
8524
8525 //restore table redrawing
8526 restoreRedraw(){
8527 this.initGuard();
8528
8529 this.eventBus.dispatch("redraw-restoring");
8530
8531 this.rowManager.restoreRedraw();
8532 this.columnManager.restoreRedraw();
8533
8534 this.eventBus.dispatch("redraw-restored");
8535 }
8536
8537 //load data
8538 setData(data, params, config){
8539 this.initGuard(false, "To set initial data please use the 'data' property in the table constructor.");
8540
8541 return this.dataLoader.load(data, params, config, false);
8542 }
8543
8544 //clear data
8545 clearData(){
8546 this.initGuard();
8547
8548 this.dataLoader.blockActiveLoad();
8549 this.rowManager.clearData();
8550 }
8551
8552 //get table data array
8553 getData(active){
8554 return this.rowManager.getData(active);
8555 }
8556
8557 //get table data array count
8558 getDataCount(active){
8559 return this.rowManager.getDataCount(active);
8560 }
8561
8562 //replace data, keeping table in position with same sort
8563 replaceData(data, params, config){
8564 this.initGuard();
8565
8566 return this.dataLoader.load(data, params, config, true, true);
8567 }
8568
8569 //update table data
8570 updateData(data){
8571 var responses = 0;
8572
8573 this.initGuard();
8574
8575 return new Promise((resolve, reject) => {
8576 this.dataLoader.blockActiveLoad();
8577
8578 if(typeof data === "string"){
8579 data = JSON.parse(data);
8580 }
8581
8582 if(data && data.length > 0){
8583 data.forEach((item) => {
8584 var row = this.rowManager.findRow(item[this.options.index]);
8585
8586 if(row){
8587 responses++;
8588
8589 row.updateData(item)
8590 .then(()=>{
8591 responses--;
8592
8593 if(!responses){
8594 resolve();
8595 }
8596 })
8597 .catch((e) => {
8598 reject("Update Error - Unable to update row", item, e);
8599 });
8600 }else {
8601 reject("Update Error - Unable to find row", item);
8602 }
8603 });
8604 }else {
8605 console.warn("Update Error - No data provided");
8606 reject("Update Error - No data provided");
8607 }
8608 });
8609 }
8610
8611 addData(data, pos, index){
8612 this.initGuard();
8613
8614 return new Promise((resolve, reject) => {
8615 this.dataLoader.blockActiveLoad();
8616
8617 if(typeof data === "string"){
8618 data = JSON.parse(data);
8619 }
8620
8621 if(data){
8622 this.rowManager.addRows(data, pos, index)
8623 .then((rows) => {
8624 var output = [];
8625
8626 rows.forEach(function(row){
8627 output.push(row.getComponent());
8628 });
8629
8630 resolve(output);
8631 });
8632 }else {
8633 console.warn("Update Error - No data provided");
8634 reject("Update Error - No data provided");
8635 }
8636 });
8637 }
8638
8639 //update table data
8640 updateOrAddData(data){
8641 var rows = [],
8642 responses = 0;
8643
8644 this.initGuard();
8645
8646 return new Promise((resolve, reject) => {
8647 this.dataLoader.blockActiveLoad();
8648
8649 if(typeof data === "string"){
8650 data = JSON.parse(data);
8651 }
8652
8653 if(data && data.length > 0){
8654 data.forEach((item) => {
8655 var row = this.rowManager.findRow(item[this.options.index]);
8656
8657 responses++;
8658
8659 if(row){
8660 row.updateData(item)
8661 .then(()=>{
8662 responses--;
8663 rows.push(row.getComponent());
8664
8665 if(!responses){
8666 resolve(rows);
8667 }
8668 });
8669 }else {
8670 this.rowManager.addRows(item)
8671 .then((newRows)=>{
8672 responses--;
8673 rows.push(newRows[0].getComponent());
8674
8675 if(!responses){
8676 resolve(rows);
8677 }
8678 });
8679 }
8680 });
8681 }else {
8682 console.warn("Update Error - No data provided");
8683 reject("Update Error - No data provided");
8684 }
8685 });
8686 }
8687
8688 //get row object
8689 getRow(index){
8690 var row = this.rowManager.findRow(index);
8691
8692 if(row){
8693 return row.getComponent();
8694 }else {
8695 console.warn("Find Error - No matching row found:", index);
8696 return false;
8697 }
8698 }
8699
8700 //get row object
8701 getRowFromPosition(position){
8702 var row = this.rowManager.getRowFromPosition(position);
8703
8704 if(row){
8705 return row.getComponent();
8706 }else {
8707 console.warn("Find Error - No matching row found:", position);
8708 return false;
8709 }
8710 }
8711
8712 //delete row from table
8713 deleteRow(index){
8714 var foundRows = [];
8715
8716 this.initGuard();
8717
8718 if(!Array.isArray(index)){
8719 index = [index];
8720 }
8721
8722 //find matching rows
8723 for(let item of index){
8724 let row = this.rowManager.findRow(item, true);
8725
8726 if(row){
8727 foundRows.push(row);
8728 }else {
8729 console.error("Delete Error - No matching row found:", item);
8730 return Promise.reject("Delete Error - No matching row found");
8731 }
8732 }
8733
8734 //sort rows into correct order to ensure smooth delete from table
8735 foundRows.sort((a, b) => {
8736 return this.rowManager.rows.indexOf(a) > this.rowManager.rows.indexOf(b) ? 1 : -1;
8737 });
8738
8739 //delete rows
8740 foundRows.forEach((row) =>{
8741 row.delete();
8742 });
8743
8744 this.rowManager.reRenderInPosition();
8745
8746 return Promise.resolve();
8747 }
8748
8749 //add row to table
8750 addRow(data, pos, index){
8751 this.initGuard();
8752
8753 if(typeof data === "string"){
8754 data = JSON.parse(data);
8755 }
8756
8757 return this.rowManager.addRows(data, pos, index, true)
8758 .then((rows)=>{
8759 return rows[0].getComponent();
8760 });
8761 }
8762
8763 //update a row if it exists otherwise create it
8764 updateOrAddRow(index, data){
8765 var row = this.rowManager.findRow(index);
8766
8767 this.initGuard();
8768
8769 if(typeof data === "string"){
8770 data = JSON.parse(data);
8771 }
8772
8773 if(row){
8774 return row.updateData(data)
8775 .then(()=>{
8776 return row.getComponent();
8777 });
8778 }else {
8779 return this.rowManager.addRows(data)
8780 .then((rows)=>{
8781 return rows[0].getComponent();
8782 });
8783 }
8784 }
8785
8786 //update row data
8787 updateRow(index, data){
8788 var row = this.rowManager.findRow(index);
8789
8790 this.initGuard();
8791
8792 if(typeof data === "string"){
8793 data = JSON.parse(data);
8794 }
8795
8796 if(row){
8797 return row.updateData(data)
8798 .then(()=>{
8799 return Promise.resolve(row.getComponent());
8800 });
8801 }else {
8802 console.warn("Update Error - No matching row found:", index);
8803 return Promise.reject("Update Error - No matching row found");
8804 }
8805 }
8806
8807 //scroll to row in DOM
8808 scrollToRow(index, position, ifVisible){
8809 var row = this.rowManager.findRow(index);
8810
8811 if(row){
8812 return this.rowManager.scrollToRow(row, position, ifVisible);
8813 }else {
8814 console.warn("Scroll Error - No matching row found:", index);
8815 return Promise.reject("Scroll Error - No matching row found");
8816 }
8817 }
8818
8819 moveRow(from, to, after){
8820 var fromRow = this.rowManager.findRow(from);
8821
8822 this.initGuard();
8823
8824 if(fromRow){
8825 fromRow.moveToRow(to, after);
8826 }else {
8827 console.warn("Move Error - No matching row found:", from);
8828 }
8829 }
8830
8831 getRows(active){
8832 return this.rowManager.getComponents(active);
8833 }
8834
8835 //get position of row in table
8836 getRowPosition(index){
8837 var row = this.rowManager.findRow(index);
8838
8839 if(row){
8840 return row.getPosition();
8841 }else {
8842 console.warn("Position Error - No matching row found:", index);
8843 return false;
8844 }
8845 }
8846
8847 /////////////// Column Functions ///////////////
8848 setColumns(definition){
8849 this.initGuard(false, "To set initial columns please use the 'columns' property in the table constructor");
8850
8851 this.columnManager.setColumns(definition);
8852 }
8853
8854 getColumns(structured){
8855 return this.columnManager.getComponents(structured);
8856 }
8857
8858 getColumn(field){
8859 var column = this.columnManager.findColumn(field);
8860
8861 if(column){
8862 return column.getComponent();
8863 }else {
8864 console.warn("Find Error - No matching column found:", field);
8865 return false;
8866 }
8867 }
8868
8869 getColumnDefinitions(){
8870 return this.columnManager.getDefinitionTree();
8871 }
8872
8873 showColumn(field){
8874 var column = this.columnManager.findColumn(field);
8875
8876 this.initGuard();
8877
8878 if(column){
8879 column.show();
8880 }else {
8881 console.warn("Column Show Error - No matching column found:", field);
8882 return false;
8883 }
8884 }
8885
8886 hideColumn(field){
8887 var column = this.columnManager.findColumn(field);
8888
8889 this.initGuard();
8890
8891 if(column){
8892 column.hide();
8893 }else {
8894 console.warn("Column Hide Error - No matching column found:", field);
8895 return false;
8896 }
8897 }
8898
8899 toggleColumn(field){
8900 var column = this.columnManager.findColumn(field);
8901
8902 this.initGuard();
8903
8904 if(column){
8905 if(column.visible){
8906 column.hide();
8907 }else {
8908 column.show();
8909 }
8910 }else {
8911 console.warn("Column Visibility Toggle Error - No matching column found:", field);
8912 return false;
8913 }
8914 }
8915
8916 addColumn(definition, before, field){
8917 var column = this.columnManager.findColumn(field);
8918
8919 this.initGuard();
8920
8921 return this.columnManager.addColumn(definition, before, column)
8922 .then((column) => {
8923 return column.getComponent();
8924 });
8925 }
8926
8927 deleteColumn(field){
8928 var column = this.columnManager.findColumn(field);
8929
8930 this.initGuard();
8931
8932 if(column){
8933 return column.delete();
8934 }else {
8935 console.warn("Column Delete Error - No matching column found:", field);
8936 return Promise.reject();
8937 }
8938 }
8939
8940 updateColumnDefinition(field, definition){
8941 var column = this.columnManager.findColumn(field);
8942
8943 this.initGuard();
8944
8945 if(column){
8946 return column.updateDefinition(definition);
8947 }else {
8948 console.warn("Column Update Error - No matching column found:", field);
8949 return Promise.reject();
8950 }
8951 }
8952
8953 moveColumn(from, to, after){
8954 var fromColumn = this.columnManager.findColumn(from),
8955 toColumn = this.columnManager.findColumn(to);
8956
8957 this.initGuard();
8958
8959 if(fromColumn){
8960 if(toColumn){
8961 this.columnManager.moveColumn(fromColumn, toColumn, after);
8962 }else {
8963 console.warn("Move Error - No matching column found:", toColumn);
8964 }
8965 }else {
8966 console.warn("Move Error - No matching column found:", from);
8967 }
8968 }
8969
8970 //scroll to column in DOM
8971 scrollToColumn(field, position, ifVisible){
8972 return new Promise((resolve, reject) => {
8973 var column = this.columnManager.findColumn(field);
8974
8975 if(column){
8976 return this.columnManager.scrollToColumn(column, position, ifVisible);
8977 }else {
8978 console.warn("Scroll Error - No matching column found:", field);
8979 return Promise.reject("Scroll Error - No matching column found");
8980 }
8981 });
8982 }
8983
8984 //////////// General Public Functions ////////////
8985 //redraw list without updating data
8986 redraw(force){
8987 this.initGuard();
8988
8989 this.columnManager.redraw(force);
8990 this.rowManager.redraw(force);
8991 }
8992
8993 setHeight(height){
8994 this.options.height = isNaN(height) ? height : height + "px";
8995 this.element.style.height = this.options.height;
8996 this.rowManager.initializeRenderer();
8997 this.rowManager.redraw(true);
8998 }
8999
9000 //////////////////// Event Bus ///////////////////
9001
9002 on(key, callback){
9003 this.externalEvents.subscribe(key, callback);
9004 }
9005
9006 off(key, callback){
9007 this.externalEvents.unsubscribe(key, callback);
9008 }
9009
9010 dispatchEvent(){
9011 var args = Array.from(arguments);
9012 args.shift();
9013
9014 this.externalEvents.dispatch(...arguments);
9015 }
9016
9017 //////////////////// Alerts ///////////////////
9018
9019 alert(contents, type){
9020 this.initGuard();
9021
9022 this.alertManager.alert(contents, type);
9023 }
9024
9025 clearAlert(){
9026 this.initGuard();
9027
9028 this.alertManager.clear();
9029 }
9030
9031 ////////////// Extension Management //////////////
9032 modExists(plugin, required){
9033 if(this.modules[plugin]){
9034 return true;
9035 }else {
9036 if(required){
9037 console.error("Tabulator Module Not Installed: " + plugin);
9038 }
9039 return false;
9040 }
9041 }
9042
9043 module(key){
9044 var mod = this.modules[key];
9045
9046 if(!mod){
9047 console.error("Tabulator module not installed: " + key);
9048 }
9049
9050 return mod;
9051 }
9052 }
9053
9054 var defaultAccessors = {
9055 rownum:function(value, data, type, params, column, row){
9056 return row.getPosition();
9057 }
9058 };
9059
9060 class Accessor extends Module{
9061
9062 static moduleName = "accessor";
9063
9064 //load defaults
9065 static accessors = defaultAccessors;
9066
9067 constructor(table){
9068 super(table);
9069
9070 this.allowedTypes = ["", "data", "download", "clipboard", "print", "htmlOutput"]; //list of accessor types
9071
9072 this.registerColumnOption("accessor");
9073 this.registerColumnOption("accessorParams");
9074 this.registerColumnOption("accessorData");
9075 this.registerColumnOption("accessorDataParams");
9076 this.registerColumnOption("accessorDownload");
9077 this.registerColumnOption("accessorDownloadParams");
9078 this.registerColumnOption("accessorClipboard");
9079 this.registerColumnOption("accessorClipboardParams");
9080 this.registerColumnOption("accessorPrint");
9081 this.registerColumnOption("accessorPrintParams");
9082 this.registerColumnOption("accessorHtmlOutput");
9083 this.registerColumnOption("accessorHtmlOutputParams");
9084 }
9085
9086 initialize(){
9087 this.subscribe("column-layout", this.initializeColumn.bind(this));
9088 this.subscribe("row-data-retrieve", this.transformRow.bind(this));
9089 }
9090
9091 //initialize column accessor
9092 initializeColumn(column){
9093 var match = false,
9094 config = {};
9095
9096 this.allowedTypes.forEach((type) => {
9097 var key = "accessor" + (type.charAt(0).toUpperCase() + type.slice(1)),
9098 accessor;
9099
9100 if(column.definition[key]){
9101 accessor = this.lookupAccessor(column.definition[key]);
9102
9103 if(accessor){
9104 match = true;
9105
9106 config[key] = {
9107 accessor:accessor,
9108 params: column.definition[key + "Params"] || {},
9109 };
9110 }
9111 }
9112 });
9113
9114 if(match){
9115 column.modules.accessor = config;
9116 }
9117 }
9118
9119 lookupAccessor(value){
9120 var accessor = false;
9121
9122 //set column accessor
9123 switch(typeof value){
9124 case "string":
9125 if(Accessor.accessors[value]){
9126 accessor = Accessor.accessors[value];
9127 }else {
9128 console.warn("Accessor Error - No such accessor found, ignoring: ", value);
9129 }
9130 break;
9131
9132 case "function":
9133 accessor = value;
9134 break;
9135 }
9136
9137 return accessor;
9138 }
9139
9140 //apply accessor to row
9141 transformRow(row, type){
9142 var key = "accessor" + (type.charAt(0).toUpperCase() + type.slice(1)),
9143 rowComponent = row.getComponent();
9144
9145 //clone data object with deep copy to isolate internal data from returned result
9146 var data = Helpers.deepClone(row.data || {});
9147
9148 this.table.columnManager.traverse(function(column){
9149 var value, accessor, params, colComponent;
9150
9151 if(column.modules.accessor){
9152
9153 accessor = column.modules.accessor[key] || column.modules.accessor.accessor || false;
9154
9155 if(accessor){
9156 value = column.getFieldValue(data);
9157
9158 if(value != "undefined"){
9159 colComponent = column.getComponent();
9160 params = typeof accessor.params === "function" ? accessor.params(value, data, type, colComponent, rowComponent) : accessor.params;
9161 column.setFieldValue(data, accessor.accessor(value, data, type, params, colComponent, rowComponent));
9162 }
9163 }
9164 }
9165 });
9166
9167 return data;
9168 }
9169 }
9170
9171 var defaultConfig = {
9172 method: "GET",
9173 };
9174
9175 function generateParamsList$1(data, prefix){
9176 var output = [];
9177
9178 prefix = prefix || "";
9179
9180 if(Array.isArray(data)){
9181 data.forEach((item, i) => {
9182 output = output.concat(generateParamsList$1(item, prefix ? prefix + "[" + i + "]" : i));
9183 });
9184 }else if (typeof data === "object"){
9185 for (var key in data){
9186 output = output.concat(generateParamsList$1(data[key], prefix ? prefix + "[" + key + "]" : key));
9187 }
9188 }else {
9189 output.push({key:prefix, value:data});
9190 }
9191
9192 return output;
9193 }
9194
9195 function serializeParams(params){
9196 var output = generateParamsList$1(params),
9197 encoded = [];
9198
9199 output.forEach(function(item){
9200 encoded.push(encodeURIComponent(item.key) + "=" + encodeURIComponent(item.value));
9201 });
9202
9203 return encoded.join("&");
9204 }
9205
9206 function urlBuilder(url, config, params){
9207 if(url){
9208 if(params && Object.keys(params).length){
9209 if(!config.method || config.method.toLowerCase() == "get"){
9210 config.method = "get";
9211
9212 url += (url.includes("?") ? "&" : "?") + serializeParams(params);
9213 }
9214 }
9215 }
9216
9217 return url;
9218 }
9219
9220 function defaultLoaderPromise(url, config, params){
9221 var contentType;
9222
9223 return new Promise((resolve, reject) => {
9224 //set url
9225 url = this.urlGenerator.call(this.table, url, config, params);
9226
9227 //set body content if not GET request
9228 if(config.method.toUpperCase() != "GET"){
9229 contentType = typeof this.table.options.ajaxContentType === "object" ? this.table.options.ajaxContentType : this.contentTypeFormatters[this.table.options.ajaxContentType];
9230 if(contentType){
9231
9232 for(var key in contentType.headers){
9233 if(!config.headers){
9234 config.headers = {};
9235 }
9236
9237 if(typeof config.headers[key] === "undefined"){
9238 config.headers[key] = contentType.headers[key];
9239 }
9240 }
9241
9242 config.body = contentType.body.call(this, url, config, params);
9243
9244 }else {
9245 console.warn("Ajax Error - Invalid ajaxContentType value:", this.table.options.ajaxContentType);
9246 }
9247 }
9248
9249 if(url){
9250 //configure headers
9251 if(typeof config.headers === "undefined"){
9252 config.headers = {};
9253 }
9254
9255 if(typeof config.headers.Accept === "undefined"){
9256 config.headers.Accept = "application/json";
9257 }
9258
9259 if(typeof config.headers["X-Requested-With"] === "undefined"){
9260 config.headers["X-Requested-With"] = "XMLHttpRequest";
9261 }
9262
9263 if(typeof config.mode === "undefined"){
9264 config.mode = "cors";
9265 }
9266
9267 if(config.mode == "cors"){
9268 if(typeof config.headers["Origin"] === "undefined"){
9269 config.headers["Origin"] = window.location.origin;
9270 }
9271
9272 if(typeof config.credentials === "undefined"){
9273 config.credentials = 'same-origin';
9274 }
9275 }else {
9276 if(typeof config.credentials === "undefined"){
9277 config.credentials = 'include';
9278 }
9279 }
9280
9281 //send request
9282 fetch(url, config)
9283 .then((response)=>{
9284 if(response.ok) {
9285 response.json()
9286 .then((data)=>{
9287 resolve(data);
9288 }).catch((error)=>{
9289 reject(error);
9290 console.warn("Ajax Load Error - Invalid JSON returned", error);
9291 });
9292 }else {
9293 console.error("Ajax Load Error - Connection Error: " + response.status, response.statusText);
9294 reject(response);
9295 }
9296 })
9297 .catch((error)=>{
9298 console.error("Ajax Load Error - Connection Error: ", error);
9299 reject(error);
9300 });
9301 }else {
9302 console.warn("Ajax Load Error - No URL Set");
9303 resolve([]);
9304 }
9305 });
9306 }
9307
9308 function generateParamsList(data, prefix){
9309 var output = [];
9310
9311 prefix = prefix || "";
9312
9313 if(Array.isArray(data)){
9314 data.forEach((item, i) => {
9315 output = output.concat(generateParamsList(item, prefix ? prefix + "[" + i + "]" : i));
9316 });
9317 }else if (typeof data === "object"){
9318 for (var key in data){
9319 output = output.concat(generateParamsList(data[key], prefix ? prefix + "[" + key + "]" : key));
9320 }
9321 }else {
9322 output.push({key:prefix, value:data});
9323 }
9324
9325 return output;
9326 }
9327
9328 var defaultContentTypeFormatters = {
9329 "json":{
9330 headers:{
9331 'Content-Type': 'application/json',
9332 },
9333 body:function(url, config, params){
9334 return JSON.stringify(params);
9335 },
9336 },
9337 "form":{
9338 headers:{
9339 },
9340 body:function(url, config, params){
9341
9342 var output = generateParamsList(params),
9343 form = new FormData();
9344
9345 output.forEach(function(item){
9346 form.append(item.key, item.value);
9347 });
9348
9349 return form;
9350 },
9351 },
9352 };
9353
9354 class Ajax extends Module{
9355
9356 static moduleName = "ajax";
9357
9358 //load defaults
9359 static defaultConfig = defaultConfig;
9360 static defaultURLGenerator = urlBuilder;
9361 static defaultLoaderPromise = defaultLoaderPromise;
9362 static contentTypeFormatters = defaultContentTypeFormatters;
9363
9364 constructor(table){
9365 super(table);
9366
9367 this.config = {}; //hold config object for ajax request
9368 this.url = ""; //request URL
9369 this.urlGenerator = false;
9370 this.params = false; //request parameters
9371
9372 this.loaderPromise = false;
9373
9374 this.registerTableOption("ajaxURL", false); //url for ajax loading
9375 this.registerTableOption("ajaxURLGenerator", false);
9376 this.registerTableOption("ajaxParams", {}); //params for ajax loading
9377 this.registerTableOption("ajaxConfig", "get"); //ajax request type
9378 this.registerTableOption("ajaxContentType", "form"); //ajax request type
9379 this.registerTableOption("ajaxRequestFunc", false); //promise function
9380
9381 this.registerTableOption("ajaxRequesting", function(){});
9382 this.registerTableOption("ajaxResponse", false);
9383
9384 this.contentTypeFormatters = Ajax.contentTypeFormatters;
9385 }
9386
9387 //initialize setup options
9388 initialize(){
9389 this.loaderPromise = this.table.options.ajaxRequestFunc || Ajax.defaultLoaderPromise;
9390 this.urlGenerator = this.table.options.ajaxURLGenerator || Ajax.defaultURLGenerator;
9391
9392 if(this.table.options.ajaxURL){
9393 this.setUrl(this.table.options.ajaxURL);
9394 }
9395
9396
9397 this.setDefaultConfig(this.table.options.ajaxConfig);
9398
9399 this.registerTableFunction("getAjaxUrl", this.getUrl.bind(this));
9400
9401 this.subscribe("data-loading", this.requestDataCheck.bind(this));
9402 this.subscribe("data-params", this.requestParams.bind(this));
9403 this.subscribe("data-load", this.requestData.bind(this));
9404 }
9405
9406 requestParams(data, config, silent, params){
9407 var ajaxParams = this.table.options.ajaxParams;
9408
9409 if(ajaxParams){
9410 if(typeof ajaxParams === "function"){
9411 ajaxParams = ajaxParams.call(this.table);
9412 }
9413
9414 params = Object.assign(Object.assign({}, ajaxParams), params);
9415 }
9416
9417 return params;
9418 }
9419
9420 requestDataCheck(data, params, config, silent){
9421 return !!((!data && this.url) || typeof data === "string");
9422 }
9423
9424 requestData(url, params, config, silent, previousData){
9425 var ajaxConfig;
9426
9427 if(!previousData && this.requestDataCheck(url)){
9428 if(url){
9429 this.setUrl(url);
9430 }
9431
9432 ajaxConfig = this.generateConfig(config);
9433
9434 return this.sendRequest(this.url, params, ajaxConfig);
9435 }else {
9436 return previousData;
9437 }
9438 }
9439
9440 setDefaultConfig(config = {}){
9441 this.config = Object.assign({}, Ajax.defaultConfig);
9442
9443 if(typeof config == "string"){
9444 this.config.method = config;
9445 }else {
9446 Object.assign(this.config, config);
9447 }
9448 }
9449
9450 //load config object
9451 generateConfig(config = {}){
9452 var ajaxConfig = Object.assign({}, this.config);
9453
9454 if(typeof config == "string"){
9455 ajaxConfig.method = config;
9456 }else {
9457 Object.assign(ajaxConfig, config);
9458 }
9459
9460 return ajaxConfig;
9461 }
9462
9463 //set request url
9464 setUrl(url){
9465 this.url = url;
9466 }
9467
9468 //get request url
9469 getUrl(){
9470 return this.url;
9471 }
9472
9473 //send ajax request
9474 sendRequest(url, params, config){
9475 if(this.table.options.ajaxRequesting.call(this.table, url, params) !== false){
9476 return this.loaderPromise(url, config, params)
9477 .then((data)=>{
9478 if(this.table.options.ajaxResponse){
9479 data = this.table.options.ajaxResponse.call(this.table, url, params, data);
9480 }
9481
9482 return data;
9483 });
9484 }else {
9485 return Promise.reject();
9486 }
9487 }
9488 }
9489
9490 var defaultPasteActions = {
9491 replace:function(data){
9492 return this.table.setData(data);
9493 },
9494 update:function(data){
9495 return this.table.updateOrAddData(data);
9496 },
9497 insert:function(data){
9498 return this.table.addData(data);
9499 },
9500 };
9501
9502 var defaultPasteParsers = {
9503 table:function(clipboard){
9504 var data = [],
9505 headerFindSuccess = true,
9506 columns = this.table.columnManager.columns,
9507 columnMap = [],
9508 rows = [];
9509
9510 //get data from clipboard into array of columns and rows.
9511 clipboard = clipboard.split("\n");
9512
9513 clipboard.forEach(function(row){
9514 data.push(row.split("\t"));
9515 });
9516
9517 if(data.length && !(data.length === 1 && data[0].length < 2)){
9518
9519 //check if headers are present by title
9520 data[0].forEach(function(value){
9521 var column = columns.find(function(column){
9522 return value && column.definition.title && value.trim() && column.definition.title.trim() === value.trim();
9523 });
9524
9525 if(column){
9526 columnMap.push(column);
9527 }else {
9528 headerFindSuccess = false;
9529 }
9530 });
9531
9532 //check if column headers are present by field
9533 if(!headerFindSuccess){
9534 headerFindSuccess = true;
9535 columnMap = [];
9536
9537 data[0].forEach(function(value){
9538 var column = columns.find(function(column){
9539 return value && column.field && value.trim() && column.field.trim() === value.trim();
9540 });
9541
9542 if(column){
9543 columnMap.push(column);
9544 }else {
9545 headerFindSuccess = false;
9546 }
9547 });
9548
9549 if(!headerFindSuccess){
9550 columnMap = this.table.columnManager.columnsByIndex;
9551 }
9552 }
9553
9554 //remove header row if found
9555 if(headerFindSuccess){
9556 data.shift();
9557 }
9558
9559 data.forEach(function(item){
9560 var row = {};
9561
9562 item.forEach(function(value, i){
9563 if(columnMap[i]){
9564 row[columnMap[i].field] = value;
9565 }
9566 });
9567
9568 rows.push(row);
9569 });
9570
9571 return rows;
9572 }else {
9573 return false;
9574 }
9575 },
9576 };
9577
9578 var bindings$2 = {
9579 copyToClipboard:["ctrl + 67", "meta + 67"],
9580 };
9581
9582 var actions$2 = {
9583 copyToClipboard:function(e){
9584 if(!this.table.modules.edit.currentCell){
9585 if(this.table.modExists("clipboard", true)){
9586 this.table.modules.clipboard.copy(false, true);
9587 }
9588 }
9589 },
9590 };
9591
9592 var extensions$4 = {
9593 keybindings:{
9594 bindings:bindings$2,
9595 actions:actions$2
9596 },
9597 };
9598
9599 class Clipboard extends Module{
9600
9601 static moduleName = "clipboard";
9602 static moduleExtensions = extensions$4;
9603
9604 //load defaults
9605 static pasteActions = defaultPasteActions;
9606 static pasteParsers = defaultPasteParsers;
9607
9608 constructor(table){
9609 super(table);
9610
9611 this.mode = true;
9612 this.pasteParser = function(){};
9613 this.pasteAction = function(){};
9614 this.customSelection = false;
9615 this.rowRange = false;
9616 this.blocked = true; //block copy actions not originating from this command
9617
9618 this.registerTableOption("clipboard", false); //enable clipboard
9619 this.registerTableOption("clipboardCopyStyled", true); //formatted table data
9620 this.registerTableOption("clipboardCopyConfig", false); //clipboard config
9621 this.registerTableOption("clipboardCopyFormatter", false); //DEPRECATED - REMOVE in 5.0
9622 this.registerTableOption("clipboardCopyRowRange", "active"); //restrict clipboard to visible rows only
9623 this.registerTableOption("clipboardPasteParser", "table"); //convert pasted clipboard data to rows
9624 this.registerTableOption("clipboardPasteAction", "insert"); //how to insert pasted data into the table
9625
9626 this.registerColumnOption("clipboard");
9627 this.registerColumnOption("titleClipboard");
9628 }
9629
9630 initialize(){
9631 this.mode = this.table.options.clipboard;
9632
9633 this.rowRange = this.table.options.clipboardCopyRowRange;
9634
9635 if(this.mode === true || this.mode === "copy"){
9636 this.table.element.addEventListener("copy", (e) => {
9637 var plain, html, list;
9638
9639 if(!this.blocked){
9640 e.preventDefault();
9641
9642 if(this.customSelection){
9643 plain = this.customSelection;
9644
9645 if(this.table.options.clipboardCopyFormatter){
9646 plain = this.table.options.clipboardCopyFormatter("plain", plain);
9647 }
9648 }else {
9649
9650 list = this.table.modules.export.generateExportList(this.table.options.clipboardCopyConfig, this.table.options.clipboardCopyStyled, this.rowRange, "clipboard");
9651
9652 html = this.table.modules.export.generateHTMLTable(list);
9653 plain = html ? this.generatePlainContent(list) : "";
9654
9655 if(this.table.options.clipboardCopyFormatter){
9656 plain = this.table.options.clipboardCopyFormatter("plain", plain);
9657 html = this.table.options.clipboardCopyFormatter("html", html);
9658 }
9659 }
9660
9661 if (window.clipboardData && window.clipboardData.setData) {
9662 window.clipboardData.setData('Text', plain);
9663 } else if (e.clipboardData && e.clipboardData.setData) {
9664 e.clipboardData.setData('text/plain', plain);
9665 if(html){
9666 e.clipboardData.setData('text/html', html);
9667 }
9668 } else if (e.originalEvent && e.originalEvent.clipboardData.setData) {
9669 e.originalEvent.clipboardData.setData('text/plain', plain);
9670 if(html){
9671 e.originalEvent.clipboardData.setData('text/html', html);
9672 }
9673 }
9674
9675 this.dispatchExternal("clipboardCopied", plain, html);
9676
9677 this.reset();
9678 }
9679 });
9680 }
9681
9682 if(this.mode === true || this.mode === "paste"){
9683 this.table.element.addEventListener("paste", (e) => {
9684 this.paste(e);
9685 });
9686 }
9687
9688 this.setPasteParser(this.table.options.clipboardPasteParser);
9689 this.setPasteAction(this.table.options.clipboardPasteAction);
9690
9691 this.registerTableFunction("copyToClipboard", this.copy.bind(this));
9692 }
9693
9694 reset(){
9695 this.blocked = true;
9696 this.customSelection = false;
9697 }
9698
9699 generatePlainContent (list) {
9700 var output = [];
9701
9702 list.forEach((row) => {
9703 var rowData = [];
9704
9705 row.columns.forEach((col) => {
9706 var value = "";
9707
9708 if(col){
9709
9710 if(row.type === "group"){
9711 col.value = col.component.getKey();
9712 }
9713
9714 if(col.value === null){
9715 value = "";
9716 }else {
9717 switch(typeof col.value){
9718 case "object":
9719 value = JSON.stringify(col.value);
9720 break;
9721
9722 case "undefined":
9723 value = "";
9724 break;
9725
9726 default:
9727 value = col.value;
9728 }
9729 }
9730 }
9731
9732 rowData.push(value);
9733 });
9734
9735 output.push(rowData.join("\t"));
9736 });
9737
9738 return output.join("\n");
9739 }
9740
9741 copy (range, internal) {
9742 var sel, textRange;
9743 this.blocked = false;
9744 this.customSelection = false;
9745
9746
9747 if (this.mode === true || this.mode === "copy") {
9748
9749 this.rowRange = range || this.table.options.clipboardCopyRowRange;
9750
9751 if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined") {
9752 range = document.createRange();
9753 range.selectNodeContents(this.table.element);
9754 sel = window.getSelection();
9755
9756 if (sel.toString() && internal) {
9757 this.customSelection = sel.toString();
9758 }
9759
9760 sel.removeAllRanges();
9761 sel.addRange(range);
9762 } else if (typeof document.selection != "undefined" && typeof document.body.createTextRange != "undefined") {
9763 textRange = document.body.createTextRange();
9764 textRange.moveToElementText(this.table.element);
9765 textRange.select();
9766 }
9767
9768 document.execCommand('copy');
9769
9770 if (sel) {
9771 sel.removeAllRanges();
9772 }
9773 }
9774 }
9775
9776 //PASTE EVENT HANDLING
9777 setPasteAction(action){
9778
9779 switch(typeof action){
9780 case "string":
9781 this.pasteAction = Clipboard.pasteActions[action];
9782
9783 if(!this.pasteAction){
9784 console.warn("Clipboard Error - No such paste action found:", action);
9785 }
9786 break;
9787
9788 case "function":
9789 this.pasteAction = action;
9790 break;
9791 }
9792 }
9793
9794 setPasteParser(parser){
9795 switch(typeof parser){
9796 case "string":
9797 this.pasteParser = Clipboard.pasteParsers[parser];
9798
9799 if(!this.pasteParser){
9800 console.warn("Clipboard Error - No such paste parser found:", parser);
9801 }
9802 break;
9803
9804 case "function":
9805 this.pasteParser = parser;
9806 break;
9807 }
9808 }
9809
9810 paste(e){
9811 var data, rowData, rows;
9812
9813 if(this.checkPasteOrigin(e)){
9814
9815 data = this.getPasteData(e);
9816
9817 rowData = this.pasteParser.call(this, data);
9818
9819 if(rowData){
9820 e.preventDefault();
9821
9822 if(this.table.modExists("mutator")){
9823 rowData = this.mutateData(rowData);
9824 }
9825
9826 rows = this.pasteAction.call(this, rowData);
9827
9828 this.dispatchExternal("clipboardPasted", data, rowData, rows);
9829 }else {
9830 this.dispatchExternal("clipboardPasteError", data);
9831 }
9832 }
9833 }
9834
9835 mutateData(data){
9836 var output = [];
9837
9838 if(Array.isArray(data)){
9839 data.forEach((row) => {
9840 output.push(this.table.modules.mutator.transformRow(row, "clipboard"));
9841 });
9842 }else {
9843 output = data;
9844 }
9845
9846 return output;
9847 }
9848
9849
9850 checkPasteOrigin(e){
9851 var valid = true;
9852 var blocked = this.confirm("clipboard-paste", [e]);
9853
9854 if(blocked || !["DIV", "SPAN"].includes(e.target.tagName)){
9855 valid = false;
9856 }
9857
9858 return valid;
9859 }
9860
9861 getPasteData(e){
9862 var data;
9863
9864 if (window.clipboardData && window.clipboardData.getData) {
9865 data = window.clipboardData.getData('Text');
9866 } else if (e.clipboardData && e.clipboardData.getData) {
9867 data = e.clipboardData.getData('text/plain');
9868 } else if (e.originalEvent && e.originalEvent.clipboardData.getData) {
9869 data = e.originalEvent.clipboardData.getData('text/plain');
9870 }
9871
9872 return data;
9873 }
9874 }
9875
9876 class CalcComponent{
9877 constructor (row){
9878 this._row = row;
9879
9880 return new Proxy(this, {
9881 get: function(target, name, receiver) {
9882 if (typeof target[name] !== "undefined") {
9883 return target[name];
9884 }else {
9885 return target._row.table.componentFunctionBinder.handle("row", target._row, name);
9886 }
9887 }
9888 });
9889 }
9890
9891 getData(transform){
9892 return this._row.getData(transform);
9893 }
9894
9895 getElement(){
9896 return this._row.getElement();
9897 }
9898
9899 getTable(){
9900 return this._row.table;
9901 }
9902
9903 getCells(){
9904 var cells = [];
9905
9906 this._row.getCells().forEach(function(cell){
9907 cells.push(cell.getComponent());
9908 });
9909
9910 return cells;
9911 }
9912
9913 getCell(column){
9914 var cell = this._row.getCell(column);
9915 return cell ? cell.getComponent() : false;
9916 }
9917
9918 _getSelf(){
9919 return this._row;
9920 }
9921 }
9922
9923 var defaultCalculations = {
9924 "avg":function(values, data, calcParams){
9925 var output = 0,
9926 precision = typeof calcParams.precision !== "undefined" ? calcParams.precision : 2;
9927
9928 if(values.length){
9929 output = values.reduce(function(sum, value){
9930 return Number(sum) + Number(value);
9931 });
9932
9933 output = output / values.length;
9934
9935 output = precision !== false ? output.toFixed(precision) : output;
9936 }
9937
9938 return parseFloat(output).toString();
9939 },
9940 "max":function(values, data, calcParams){
9941 var output = null,
9942 precision = typeof calcParams.precision !== "undefined" ? calcParams.precision : false;
9943
9944 values.forEach(function(value){
9945
9946 value = Number(value);
9947
9948 if(value > output || output === null){
9949 output = value;
9950 }
9951 });
9952
9953 return output !== null ? (precision !== false ? output.toFixed(precision) : output) : "";
9954 },
9955 "min":function(values, data, calcParams){
9956 var output = null,
9957 precision = typeof calcParams.precision !== "undefined" ? calcParams.precision : false;
9958
9959 values.forEach(function(value){
9960
9961 value = Number(value);
9962
9963 if(value < output || output === null){
9964 output = value;
9965 }
9966 });
9967
9968 return output !== null ? (precision !== false ? output.toFixed(precision) : output) : "";
9969 },
9970 "sum":function(values, data, calcParams){
9971 var output = 0,
9972 precision = typeof calcParams.precision !== "undefined" ? calcParams.precision : false;
9973
9974 if(values.length){
9975 values.forEach(function(value){
9976 value = Number(value);
9977
9978 output += !isNaN(value) ? Number(value) : 0;
9979 });
9980 }
9981
9982 return precision !== false ? output.toFixed(precision) : output;
9983 },
9984 "concat":function(values, data, calcParams){
9985 var output = 0;
9986
9987 if(values.length){
9988 output = values.reduce(function(sum, value){
9989 return String(sum) + String(value);
9990 });
9991 }
9992
9993 return output;
9994 },
9995 "count":function(values, data, calcParams){
9996 var output = 0;
9997
9998 if(values.length){
9999 values.forEach(function(value){
10000 if(value){
10001 output ++;
10002 }
10003 });
10004 }
10005
10006 return output;
10007 },
10008 "unique":function(values, data, calcParams){
10009 var unique = values.filter((value, index) => {
10010 return (values || value === 0) && values.indexOf(value) === index;
10011 });
10012
10013 return unique.length;
10014 },
10015 };
10016
10017 class ColumnCalcs extends Module{
10018
10019 static moduleName = "columnCalcs";
10020
10021 //load defaults
10022 static calculations = defaultCalculations;
10023
10024 constructor(table){
10025 super(table);
10026
10027 this.topCalcs = [];
10028 this.botCalcs = [];
10029 this.genColumn = false;
10030 this.topElement = this.createElement();
10031 this.botElement = this.createElement();
10032 this.topRow = false;
10033 this.botRow = false;
10034 this.topInitialized = false;
10035 this.botInitialized = false;
10036
10037 this.blocked = false;
10038 this.recalcAfterBlock = false;
10039
10040 this.registerTableOption("columnCalcs", true);
10041
10042 this.registerColumnOption("topCalc");
10043 this.registerColumnOption("topCalcParams");
10044 this.registerColumnOption("topCalcFormatter");
10045 this.registerColumnOption("topCalcFormatterParams");
10046 this.registerColumnOption("bottomCalc");
10047 this.registerColumnOption("bottomCalcParams");
10048 this.registerColumnOption("bottomCalcFormatter");
10049 this.registerColumnOption("bottomCalcFormatterParams");
10050 }
10051
10052 createElement (){
10053 var el = document.createElement("div");
10054 el.classList.add("tabulator-calcs-holder");
10055 return el;
10056 }
10057
10058 initialize(){
10059 this.genColumn = new Column({field:"value"}, this);
10060
10061 this.subscribe("cell-value-changed", this.cellValueChanged.bind(this));
10062 this.subscribe("column-init", this.initializeColumnCheck.bind(this));
10063 this.subscribe("row-deleted", this.rowsUpdated.bind(this));
10064 this.subscribe("scroll-horizontal", this.scrollHorizontal.bind(this));
10065 this.subscribe("row-added", this.rowsUpdated.bind(this));
10066 this.subscribe("column-moved", this.recalcActiveRows.bind(this));
10067 this.subscribe("column-add", this.recalcActiveRows.bind(this));
10068 this.subscribe("data-refreshed", this.recalcActiveRowsRefresh.bind(this));
10069 this.subscribe("table-redraw", this.tableRedraw.bind(this));
10070 this.subscribe("rows-visible", this.visibleRows.bind(this));
10071 this.subscribe("scrollbar-vertical", this.adjustForScrollbar.bind(this));
10072
10073 this.subscribe("redraw-blocked", this.blockRedraw.bind(this));
10074 this.subscribe("redraw-restored", this.restoreRedraw.bind(this));
10075
10076 this.subscribe("table-redrawing", this.resizeHolderWidth.bind(this));
10077 this.subscribe("column-resized", this.resizeHolderWidth.bind(this));
10078 this.subscribe("column-show", this.resizeHolderWidth.bind(this));
10079 this.subscribe("column-hide", this.resizeHolderWidth.bind(this));
10080
10081 this.registerTableFunction("getCalcResults", this.getResults.bind(this));
10082 this.registerTableFunction("recalc", this.userRecalc.bind(this));
10083
10084
10085 this.resizeHolderWidth();
10086 }
10087
10088 resizeHolderWidth(){
10089 this.topElement.style.minWidth = this.table.columnManager.headersElement.offsetWidth + "px";
10090 }
10091
10092
10093 tableRedraw(force){
10094 this.recalc(this.table.rowManager.activeRows);
10095
10096 if(force){
10097 this.redraw();
10098 }
10099 }
10100
10101 blockRedraw(){
10102 this.blocked = true;
10103 this.recalcAfterBlock = false;
10104 }
10105
10106
10107 restoreRedraw(){
10108 this.blocked = false;
10109
10110 if(this.recalcAfterBlock){
10111 this.recalcAfterBlock = false;
10112 this.recalcActiveRowsRefresh();
10113 }
10114 }
10115
10116 ///////////////////////////////////
10117 ///////// Table Functions /////////
10118 ///////////////////////////////////
10119 userRecalc(){
10120 this.recalc(this.table.rowManager.activeRows);
10121 }
10122
10123 ///////////////////////////////////
10124 ///////// Internal Logic //////////
10125 ///////////////////////////////////
10126
10127 blockCheck(){
10128 if(this.blocked){
10129 this.recalcAfterBlock = true;
10130 }
10131
10132 return this.blocked;
10133 }
10134
10135 visibleRows(viewable, rows){
10136 if(this.topRow){
10137 rows.unshift(this.topRow);
10138 }
10139
10140 if(this.botRow){
10141 rows.push(this.botRow);
10142 }
10143
10144 return rows;
10145 }
10146
10147 rowsUpdated(row){
10148 if(this.table.options.groupBy){
10149 this.recalcRowGroup(row);
10150 }else {
10151 this.recalcActiveRows();
10152 }
10153 }
10154
10155 recalcActiveRowsRefresh(){
10156 if(this.table.options.groupBy && this.table.options.dataTreeStartExpanded && this.table.options.dataTree){
10157 this.recalcAll();
10158 }else {
10159 this.recalcActiveRows();
10160 }
10161 }
10162
10163 recalcActiveRows(){
10164 this.recalc(this.table.rowManager.activeRows);
10165 }
10166
10167 cellValueChanged(cell){
10168 if(cell.column.definition.topCalc || cell.column.definition.bottomCalc){
10169 if(this.table.options.groupBy){
10170 if(this.table.options.columnCalcs == "table" || this.table.options.columnCalcs == "both"){
10171 this.recalcActiveRows();
10172 }
10173
10174 if(this.table.options.columnCalcs != "table"){
10175 this.recalcRowGroup(cell.row);
10176 }
10177 }else {
10178 this.recalcActiveRows();
10179 }
10180 }
10181 }
10182
10183 initializeColumnCheck(column){
10184 if(column.definition.topCalc || column.definition.bottomCalc){
10185 this.initializeColumn(column);
10186 }
10187 }
10188
10189 //initialize column calcs
10190 initializeColumn(column){
10191 var def = column.definition;
10192
10193 var config = {
10194 topCalcParams:def.topCalcParams || {},
10195 botCalcParams:def.bottomCalcParams || {},
10196 };
10197
10198 if(def.topCalc){
10199
10200 switch(typeof def.topCalc){
10201 case "string":
10202 if(ColumnCalcs.calculations[def.topCalc]){
10203 config.topCalc = ColumnCalcs.calculations[def.topCalc];
10204 }else {
10205 console.warn("Column Calc Error - No such calculation found, ignoring: ", def.topCalc);
10206 }
10207 break;
10208
10209 case "function":
10210 config.topCalc = def.topCalc;
10211 break;
10212
10213 }
10214
10215 if(config.topCalc){
10216 column.modules.columnCalcs = config;
10217 this.topCalcs.push(column);
10218
10219 if(this.table.options.columnCalcs != "group"){
10220 this.initializeTopRow();
10221 }
10222 }
10223
10224 }
10225
10226 if(def.bottomCalc){
10227 switch(typeof def.bottomCalc){
10228 case "string":
10229 if(ColumnCalcs.calculations[def.bottomCalc]){
10230 config.botCalc = ColumnCalcs.calculations[def.bottomCalc];
10231 }else {
10232 console.warn("Column Calc Error - No such calculation found, ignoring: ", def.bottomCalc);
10233 }
10234 break;
10235
10236 case "function":
10237 config.botCalc = def.bottomCalc;
10238 break;
10239
10240 }
10241
10242 if(config.botCalc){
10243 column.modules.columnCalcs = config;
10244 this.botCalcs.push(column);
10245
10246 if(this.table.options.columnCalcs != "group"){
10247 this.initializeBottomRow();
10248 }
10249 }
10250 }
10251
10252 }
10253
10254 //dummy functions to handle being mock column manager
10255 registerColumnField(){}
10256
10257 removeCalcs(){
10258 var changed = false;
10259
10260 if(this.topInitialized){
10261 this.topInitialized = false;
10262 this.topElement.parentNode.removeChild(this.topElement);
10263 changed = true;
10264 }
10265
10266 if(this.botInitialized){
10267 this.botInitialized = false;
10268 this.footerRemove(this.botElement);
10269 changed = true;
10270 }
10271
10272 if(changed){
10273 this.table.rowManager.adjustTableSize();
10274 }
10275 }
10276
10277 reinitializeCalcs(){
10278 if(this.topCalcs.length){
10279 this.initializeTopRow();
10280 }
10281
10282 if(this.botCalcs.length){
10283 this.initializeBottomRow();
10284 }
10285 }
10286
10287 initializeTopRow(){
10288 var fragment = document.createDocumentFragment();
10289
10290 if(!this.topInitialized){
10291
10292 fragment.appendChild(document.createElement("br"));
10293 fragment.appendChild(this.topElement);
10294
10295 this.table.columnManager.getContentsElement().insertBefore(fragment, this.table.columnManager.headersElement.nextSibling);
10296 this.topInitialized = true;
10297 }
10298 }
10299
10300 initializeBottomRow(){
10301 if(!this.botInitialized){
10302 this.footerPrepend(this.botElement);
10303 this.botInitialized = true;
10304 }
10305 }
10306
10307 scrollHorizontal(left){
10308 if(this.botInitialized && this.botRow){
10309 this.botElement.scrollLeft = left;
10310 }
10311 }
10312
10313 recalc(rows){
10314 var data, row;
10315
10316 if(!this.blockCheck()){
10317 if(this.topInitialized || this.botInitialized){
10318 data = this.rowsToData(rows);
10319
10320 if(this.topInitialized){
10321 if(this.topRow){
10322 this.topRow.deleteCells();
10323 }
10324
10325 row = this.generateRow("top", data);
10326 this.topRow = row;
10327 while(this.topElement.firstChild) this.topElement.removeChild(this.topElement.firstChild);
10328 this.topElement.appendChild(row.getElement());
10329 row.initialize(true);
10330 }
10331
10332 if(this.botInitialized){
10333 if(this.botRow){
10334 this.botRow.deleteCells();
10335 }
10336
10337 row = this.generateRow("bottom", data);
10338 this.botRow = row;
10339 while(this.botElement.firstChild) this.botElement.removeChild(this.botElement.firstChild);
10340 this.botElement.appendChild(row.getElement());
10341 row.initialize(true);
10342 }
10343
10344 this.table.rowManager.adjustTableSize();
10345
10346 //set resizable handles
10347 if(this.table.modExists("frozenColumns")){
10348 this.table.modules.frozenColumns.layout();
10349 }
10350 }
10351 }
10352 }
10353
10354 recalcRowGroup(row){
10355 this.recalcGroup(this.table.modules.groupRows.getRowGroup(row));
10356 }
10357
10358 recalcAll(){
10359 if(this.topCalcs.length || this.botCalcs.length){
10360 if(this.table.options.columnCalcs !== "group"){
10361 this.recalcActiveRows();
10362 }
10363
10364 if(this.table.options.groupBy && this.table.options.columnCalcs !== "table"){
10365
10366 var groups = this.table.modules.groupRows.getChildGroups();
10367
10368 groups.forEach((group) => {
10369 this.recalcGroup(group);
10370 });
10371 }
10372 }
10373 }
10374
10375 recalcGroup(group){
10376 var data, rowData;
10377
10378 if(!this.blockCheck()){
10379 if(group){
10380 if(group.calcs){
10381 if(group.calcs.bottom){
10382 data = this.rowsToData(group.rows);
10383 rowData = this.generateRowData("bottom", data);
10384
10385 group.calcs.bottom.updateData(rowData);
10386 group.calcs.bottom.reinitialize();
10387 }
10388
10389 if(group.calcs.top){
10390 data = this.rowsToData(group.rows);
10391 rowData = this.generateRowData("top", data);
10392
10393 group.calcs.top.updateData(rowData);
10394 group.calcs.top.reinitialize();
10395 }
10396 }
10397 }
10398 }
10399 }
10400
10401 //generate top stats row
10402 generateTopRow(rows){
10403 return this.generateRow("top", this.rowsToData(rows));
10404 }
10405 //generate bottom stats row
10406 generateBottomRow(rows){
10407 return this.generateRow("bottom", this.rowsToData(rows));
10408 }
10409
10410 rowsToData(rows){
10411 var data = [],
10412 hasDataTreeColumnCalcs = this.table.options.dataTree && this.table.options.dataTreeChildColumnCalcs,
10413 dataTree = this.table.modules.dataTree;
10414
10415 rows.forEach((row) => {
10416 data.push(row.getData());
10417
10418 if(hasDataTreeColumnCalcs && row.modules.dataTree?.open){
10419 this.rowsToData(dataTree.getFilteredTreeChildren(row)).forEach(dataRow =>{
10420 data.push(row);
10421 });
10422 }
10423 });
10424 return data;
10425 }
10426
10427 //generate stats row
10428 generateRow(pos, data){
10429 var rowData = this.generateRowData(pos, data),
10430 row;
10431
10432 if(this.table.modExists("mutator")){
10433 this.table.modules.mutator.disable();
10434 }
10435
10436 row = new Row(rowData, this, "calc");
10437
10438 if(this.table.modExists("mutator")){
10439 this.table.modules.mutator.enable();
10440 }
10441
10442 row.getElement().classList.add("tabulator-calcs", "tabulator-calcs-" + pos);
10443
10444 row.component = false;
10445
10446 row.getComponent = () => {
10447 if(!row.component){
10448 row.component = new CalcComponent(row);
10449 }
10450
10451 return row.component;
10452 };
10453
10454 row.generateCells = () => {
10455
10456 var cells = [];
10457
10458 this.table.columnManager.columnsByIndex.forEach((column) => {
10459
10460 //set field name of mock column
10461 this.genColumn.setField(column.getField());
10462 this.genColumn.hozAlign = column.hozAlign;
10463
10464 if(column.definition[pos + "CalcFormatter"] && this.table.modExists("format")){
10465 this.genColumn.modules.format = {
10466 formatter: this.table.modules.format.lookupFormatter(column.definition[pos + "CalcFormatter"]),
10467 params: column.definition[pos + "CalcFormatterParams"] || {},
10468 };
10469 }else {
10470 this.genColumn.modules.format = {
10471 formatter: this.table.modules.format.lookupFormatter("plaintext"),
10472 params:{}
10473 };
10474 }
10475
10476 //ensure css class definition is replicated to calculation cell
10477 this.genColumn.definition.cssClass = column.definition.cssClass;
10478
10479 //generate cell and assign to correct column
10480 var cell = new Cell(this.genColumn, row);
10481 cell.getElement();
10482 cell.column = column;
10483 cell.setWidth();
10484
10485 column.cells.push(cell);
10486 cells.push(cell);
10487
10488 if(!column.visible){
10489 cell.hide();
10490 }
10491 });
10492
10493 row.cells = cells;
10494 };
10495
10496 return row;
10497 }
10498
10499 //generate stats row
10500 generateRowData(pos, data){
10501 var rowData = {},
10502 calcs = pos == "top" ? this.topCalcs : this.botCalcs,
10503 type = pos == "top" ? "topCalc" : "botCalc",
10504 params, paramKey;
10505
10506 calcs.forEach(function(column){
10507 var values = [];
10508
10509 if(column.modules.columnCalcs && column.modules.columnCalcs[type]){
10510 data.forEach(function(item){
10511 values.push(column.getFieldValue(item));
10512 });
10513
10514 paramKey = type + "Params";
10515 params = typeof column.modules.columnCalcs[paramKey] === "function" ? column.modules.columnCalcs[paramKey](values, data) : column.modules.columnCalcs[paramKey];
10516
10517 column.setFieldValue(rowData, column.modules.columnCalcs[type](values, data, params));
10518 }
10519 });
10520
10521 return rowData;
10522 }
10523
10524 hasTopCalcs(){
10525 return !!(this.topCalcs.length);
10526 }
10527
10528 hasBottomCalcs(){
10529 return !!(this.botCalcs.length);
10530 }
10531
10532 //handle table redraw
10533 redraw(){
10534 if(this.topRow){
10535 this.topRow.normalizeHeight(true);
10536 }
10537 if(this.botRow){
10538 this.botRow.normalizeHeight(true);
10539 }
10540 }
10541
10542 //return the calculated
10543 getResults(){
10544 var results = {},
10545 groups;
10546
10547 if(this.table.options.groupBy && this.table.modExists("groupRows")){
10548 groups = this.table.modules.groupRows.getGroups(true);
10549
10550 groups.forEach((group) => {
10551 results[group.getKey()] = this.getGroupResults(group);
10552 });
10553 }else {
10554 results = {
10555 top: this.topRow ? this.topRow.getData() : {},
10556 bottom: this.botRow ? this.botRow.getData() : {},
10557 };
10558 }
10559
10560 return results;
10561 }
10562
10563 //get results from a group
10564 getGroupResults(group){
10565 var groupObj = group._getSelf(),
10566 subGroups = group.getSubGroups(),
10567 subGroupResults = {},
10568 results = {};
10569
10570 subGroups.forEach((subgroup) => {
10571 subGroupResults[subgroup.getKey()] = this.getGroupResults(subgroup);
10572 });
10573
10574 results = {
10575 top: groupObj.calcs.top ? groupObj.calcs.top.getData() : {},
10576 bottom: groupObj.calcs.bottom ? groupObj.calcs.bottom.getData() : {},
10577 groups: subGroupResults,
10578 };
10579
10580 return results;
10581 }
10582
10583 adjustForScrollbar(width){
10584 if(this.botRow){
10585 if(this.table.rtl){
10586 this.botElement.style.paddingLeft = width + "px";
10587 }else {
10588 this.botElement.style.paddingRight = width + "px";
10589 }
10590 }
10591 }
10592 }
10593
10594 class DataTree extends Module{
10595
10596 static moduleName = "dataTree";
10597
10598 constructor(table){
10599 super(table);
10600
10601 this.indent = 10;
10602 this.field = "";
10603 this.collapseEl = null;
10604 this.expandEl = null;
10605 this.branchEl = null;
10606 this.elementField = false;
10607
10608 this.startOpen = function(){};
10609
10610 this.registerTableOption("dataTree", false); //enable data tree
10611 this.registerTableOption("dataTreeFilter", true); //filter child rows
10612 this.registerTableOption("dataTreeSort", true); //sort child rows
10613 this.registerTableOption("dataTreeElementColumn", false);
10614 this.registerTableOption("dataTreeBranchElement", true);//show data tree branch element
10615 this.registerTableOption("dataTreeChildIndent", 9); //data tree child indent in px
10616 this.registerTableOption("dataTreeChildField", "_children");//data tre column field to look for child rows
10617 this.registerTableOption("dataTreeCollapseElement", false);//data tree row collapse element
10618 this.registerTableOption("dataTreeExpandElement", false);//data tree row expand element
10619 this.registerTableOption("dataTreeStartExpanded", false);
10620 this.registerTableOption("dataTreeChildColumnCalcs", false);//include visible data tree rows in column calculations
10621 this.registerTableOption("dataTreeSelectPropagate", false);//selecting a parent row selects its children
10622
10623 //register component functions
10624 this.registerComponentFunction("row", "treeCollapse", this.collapseRow.bind(this));
10625 this.registerComponentFunction("row", "treeExpand", this.expandRow.bind(this));
10626 this.registerComponentFunction("row", "treeToggle", this.toggleRow.bind(this));
10627 this.registerComponentFunction("row", "getTreeParent", this.getTreeParent.bind(this));
10628 this.registerComponentFunction("row", "getTreeChildren", this.getRowChildren.bind(this));
10629 this.registerComponentFunction("row", "addTreeChild", this.addTreeChildRow.bind(this));
10630 this.registerComponentFunction("row", "isTreeExpanded", this.isRowExpanded.bind(this));
10631 }
10632
10633 initialize(){
10634 if(this.table.options.dataTree){
10635 var dummyEl = null,
10636 options = this.table.options;
10637
10638 this.field = options.dataTreeChildField;
10639 this.indent = options.dataTreeChildIndent;
10640
10641 if(this.options("movableRows")){
10642 console.warn("The movableRows option is not available with dataTree enabled, moving of child rows could result in unpredictable behavior");
10643 }
10644
10645 if(options.dataTreeBranchElement){
10646
10647 if(options.dataTreeBranchElement === true){
10648 this.branchEl = document.createElement("div");
10649 this.branchEl.classList.add("tabulator-data-tree-branch");
10650 }else {
10651 if(typeof options.dataTreeBranchElement === "string"){
10652 dummyEl = document.createElement("div");
10653 dummyEl.innerHTML = options.dataTreeBranchElement;
10654 this.branchEl = dummyEl.firstChild;
10655 }else {
10656 this.branchEl = options.dataTreeBranchElement;
10657 }
10658 }
10659 }else {
10660 this.branchEl = document.createElement("div");
10661 this.branchEl.classList.add("tabulator-data-tree-branch-empty");
10662 }
10663
10664 if(options.dataTreeCollapseElement){
10665 if(typeof options.dataTreeCollapseElement === "string"){
10666 dummyEl = document.createElement("div");
10667 dummyEl.innerHTML = options.dataTreeCollapseElement;
10668 this.collapseEl = dummyEl.firstChild;
10669 }else {
10670 this.collapseEl = options.dataTreeCollapseElement;
10671 }
10672 }else {
10673 this.collapseEl = document.createElement("div");
10674 this.collapseEl.classList.add("tabulator-data-tree-control");
10675 this.collapseEl.tabIndex = 0;
10676 this.collapseEl.innerHTML = "<div class='tabulator-data-tree-control-collapse'></div>";
10677 }
10678
10679 if(options.dataTreeExpandElement){
10680 if(typeof options.dataTreeExpandElement === "string"){
10681 dummyEl = document.createElement("div");
10682 dummyEl.innerHTML = options.dataTreeExpandElement;
10683 this.expandEl = dummyEl.firstChild;
10684 }else {
10685 this.expandEl = options.dataTreeExpandElement;
10686 }
10687 }else {
10688 this.expandEl = document.createElement("div");
10689 this.expandEl.classList.add("tabulator-data-tree-control");
10690 this.expandEl.tabIndex = 0;
10691 this.expandEl.innerHTML = "<div class='tabulator-data-tree-control-expand'></div>";
10692 }
10693
10694
10695 switch(typeof options.dataTreeStartExpanded){
10696 case "boolean":
10697 this.startOpen = function(row, index){
10698 return options.dataTreeStartExpanded;
10699 };
10700 break;
10701
10702 case "function":
10703 this.startOpen = options.dataTreeStartExpanded;
10704 break;
10705
10706 default:
10707 this.startOpen = function(row, index){
10708 return options.dataTreeStartExpanded[index];
10709 };
10710 break;
10711 }
10712
10713 this.subscribe("row-init", this.initializeRow.bind(this));
10714 this.subscribe("row-layout-after", this.layoutRow.bind(this));
10715 this.subscribe("row-deleting", this.rowDeleting.bind(this));
10716 this.subscribe("row-deleted", this.rowDelete.bind(this),0);
10717 this.subscribe("row-data-changed", this.rowDataChanged.bind(this), 10);
10718 this.subscribe("cell-value-updated", this.cellValueChanged.bind(this));
10719 this.subscribe("edit-cancelled", this.cellValueChanged.bind(this));
10720 this.subscribe("column-moving-rows", this.columnMoving.bind(this));
10721 this.subscribe("table-built", this.initializeElementField.bind(this));
10722 this.subscribe("table-redrawing", this.tableRedrawing.bind(this));
10723
10724 this.registerDisplayHandler(this.getRows.bind(this), 30);
10725 }
10726 }
10727
10728 tableRedrawing(force){
10729 var rows;
10730
10731 if(force){
10732 rows = this.table.rowManager.getRows();
10733
10734 rows.forEach((row) => {
10735 this.reinitializeRowChildren(row);
10736 });
10737 }
10738 }
10739
10740 initializeElementField(){
10741 var firstCol = this.table.columnManager.getFirstVisibleColumn();
10742
10743 this.elementField = this.table.options.dataTreeElementColumn || (firstCol ? firstCol.field : false);
10744 }
10745
10746 getRowChildren(row){
10747 return this.getTreeChildren(row, true);
10748 }
10749
10750 columnMoving(){
10751 var rows = [];
10752
10753 this.table.rowManager.rows.forEach((row) => {
10754 rows = rows.concat(this.getTreeChildren(row, false, true));
10755 });
10756
10757 return rows;
10758 }
10759
10760 rowDataChanged(row, visible, updatedData){
10761 if(this.redrawNeeded(updatedData)){
10762 this.initializeRow(row);
10763
10764 if(visible){
10765 this.layoutRow(row);
10766 this.refreshData(true);
10767 }
10768 }
10769 }
10770
10771 cellValueChanged(cell){
10772 var field = cell.column.getField();
10773
10774 if(field === this.elementField){
10775 this.layoutRow(cell.row);
10776 }
10777 }
10778
10779 initializeRow(row){
10780 var childArray = row.getData()[this.field];
10781 var isArray = Array.isArray(childArray);
10782
10783 var children = isArray || (!isArray && typeof childArray === "object" && childArray !== null);
10784
10785 if(!children && row.modules.dataTree && row.modules.dataTree.branchEl){
10786 row.modules.dataTree.branchEl.parentNode.removeChild(row.modules.dataTree.branchEl);
10787 }
10788
10789 if(!children && row.modules.dataTree && row.modules.dataTree.controlEl){
10790 row.modules.dataTree.controlEl.parentNode.removeChild(row.modules.dataTree.controlEl);
10791 }
10792
10793 row.modules.dataTree = {
10794 index: row.modules.dataTree ? row.modules.dataTree.index : 0,
10795 open: children ? (row.modules.dataTree ? row.modules.dataTree.open : this.startOpen(row.getComponent(), 0)) : false,
10796 controlEl: row.modules.dataTree && children ? row.modules.dataTree.controlEl : false,
10797 branchEl: row.modules.dataTree && children ? row.modules.dataTree.branchEl : false,
10798 parent: row.modules.dataTree ? row.modules.dataTree.parent : false,
10799 children:children,
10800 };
10801 }
10802
10803 reinitializeRowChildren(row){
10804 var children = this.getTreeChildren(row, false, true);
10805
10806 children.forEach(function(child){
10807 child.reinitialize(true);
10808 });
10809 }
10810
10811 layoutRow(row){
10812 var cell = this.elementField ? row.getCell(this.elementField) : row.getCells()[0],
10813 el = cell.getElement(),
10814 config = row.modules.dataTree;
10815
10816 if(config.branchEl){
10817 if(config.branchEl.parentNode){
10818 config.branchEl.parentNode.removeChild(config.branchEl);
10819 }
10820 config.branchEl = false;
10821 }
10822
10823 if(config.controlEl){
10824 if(config.controlEl.parentNode){
10825 config.controlEl.parentNode.removeChild(config.controlEl);
10826 }
10827 config.controlEl = false;
10828 }
10829
10830 this.generateControlElement(row, el);
10831
10832 row.getElement().classList.add("tabulator-tree-level-" + config.index);
10833
10834 if(config.index){
10835 if(this.branchEl){
10836 config.branchEl = this.branchEl.cloneNode(true);
10837 el.insertBefore(config.branchEl, el.firstChild);
10838
10839 if(this.table.rtl){
10840 config.branchEl.style.marginRight = (((config.branchEl.offsetWidth + config.branchEl.style.marginLeft) * (config.index - 1)) + (config.index * this.indent)) + "px";
10841 }else {
10842 config.branchEl.style.marginLeft = (((config.branchEl.offsetWidth + config.branchEl.style.marginRight) * (config.index - 1)) + (config.index * this.indent)) + "px";
10843 }
10844 }else {
10845
10846 if(this.table.rtl){
10847 el.style.paddingRight = parseInt(window.getComputedStyle(el, null).getPropertyValue('padding-right')) + (config.index * this.indent) + "px";
10848 }else {
10849 el.style.paddingLeft = parseInt(window.getComputedStyle(el, null).getPropertyValue('padding-left')) + (config.index * this.indent) + "px";
10850 }
10851 }
10852 }
10853 }
10854
10855 generateControlElement(row, el){
10856 var config = row.modules.dataTree,
10857 oldControl = config.controlEl;
10858
10859 el = el || row.getCells()[0].getElement();
10860
10861 if(config.children !== false){
10862
10863 if(config.open){
10864 config.controlEl = this.collapseEl.cloneNode(true);
10865 config.controlEl.addEventListener("click", (e) => {
10866 e.stopPropagation();
10867 this.collapseRow(row);
10868 });
10869 }else {
10870 config.controlEl = this.expandEl.cloneNode(true);
10871 config.controlEl.addEventListener("click", (e) => {
10872 e.stopPropagation();
10873 this.expandRow(row);
10874 });
10875 }
10876
10877 config.controlEl.addEventListener("mousedown", (e) => {
10878 e.stopPropagation();
10879 });
10880
10881 if(oldControl && oldControl.parentNode === el){
10882 oldControl.parentNode.replaceChild(config.controlEl,oldControl);
10883 }else {
10884 el.insertBefore(config.controlEl, el.firstChild);
10885 }
10886 }
10887 }
10888
10889 getRows(rows){
10890 var output = [];
10891
10892 rows.forEach((row, i) => {
10893 var config, children;
10894
10895 output.push(row);
10896
10897 if(row instanceof Row){
10898
10899 row.create();
10900
10901 config = row.modules.dataTree;
10902
10903 if(!config.index && config.children !== false){
10904 children = this.getChildren(row, false, true);
10905
10906 children.forEach((child) => {
10907 child.create();
10908 output.push(child);
10909 });
10910 }
10911 }
10912 });
10913
10914 return output;
10915 }
10916
10917 getChildren(row, allChildren, sortOnly){
10918 var config = row.modules.dataTree,
10919 children = [],
10920 output = [];
10921
10922 if(config.children !== false && (config.open || allChildren)){
10923 if(!Array.isArray(config.children)){
10924 config.children = this.generateChildren(row);
10925 }
10926
10927 if(this.table.modExists("filter") && this.table.options.dataTreeFilter){
10928 children = this.table.modules.filter.filter(config.children);
10929 }else {
10930 children = config.children;
10931 }
10932
10933 if(this.table.modExists("sort") && this.table.options.dataTreeSort){
10934 this.table.modules.sort.sort(children, sortOnly);
10935 }
10936
10937 children.forEach((child) => {
10938 output.push(child);
10939
10940 var subChildren = this.getChildren(child, false, true);
10941
10942 subChildren.forEach((sub) => {
10943 output.push(sub);
10944 });
10945 });
10946 }
10947
10948 return output;
10949 }
10950
10951 generateChildren(row){
10952 var children = [];
10953
10954 var childArray = row.getData()[this.field];
10955
10956 if(!Array.isArray(childArray)){
10957 childArray = [childArray];
10958 }
10959
10960 childArray.forEach((childData) => {
10961 var childRow = new Row(childData || {}, this.table.rowManager);
10962
10963 childRow.create();
10964
10965 childRow.modules.dataTree.index = row.modules.dataTree.index + 1;
10966 childRow.modules.dataTree.parent = row;
10967
10968 if(childRow.modules.dataTree.children){
10969 childRow.modules.dataTree.open = this.startOpen(childRow.getComponent(), childRow.modules.dataTree.index);
10970 }
10971 children.push(childRow);
10972 });
10973
10974 return children;
10975 }
10976
10977 expandRow(row, silent){
10978 var config = row.modules.dataTree;
10979
10980 if(config.children !== false){
10981 config.open = true;
10982
10983 row.reinitialize();
10984
10985 this.refreshData(true);
10986
10987 this.dispatchExternal("dataTreeRowExpanded", row.getComponent(), row.modules.dataTree.index);
10988 }
10989 }
10990
10991 collapseRow(row){
10992 var config = row.modules.dataTree;
10993
10994 if(config.children !== false){
10995 config.open = false;
10996
10997 row.reinitialize();
10998
10999 this.refreshData(true);
11000
11001 this.dispatchExternal("dataTreeRowCollapsed", row.getComponent(), row.modules.dataTree.index);
11002 }
11003 }
11004
11005 toggleRow(row){
11006 var config = row.modules.dataTree;
11007
11008 if(config.children !== false){
11009 if(config.open){
11010 this.collapseRow(row);
11011 }else {
11012 this.expandRow(row);
11013 }
11014 }
11015 }
11016
11017 isRowExpanded(row){
11018 return row.modules.dataTree.open;
11019 }
11020
11021 getTreeParent(row){
11022 return row.modules.dataTree.parent ? row.modules.dataTree.parent.getComponent() : false;
11023 }
11024
11025 getTreeParentRoot(row){
11026 return row.modules.dataTree && row.modules.dataTree.parent ? this.getTreeParentRoot(row.modules.dataTree.parent) : row;
11027 }
11028
11029 getFilteredTreeChildren(row){
11030 var config = row.modules.dataTree,
11031 output = [], children;
11032
11033 if(config.children){
11034
11035 if(!Array.isArray(config.children)){
11036 config.children = this.generateChildren(row);
11037 }
11038
11039 if(this.table.modExists("filter") && this.table.options.dataTreeFilter){
11040 children = this.table.modules.filter.filter(config.children);
11041 }else {
11042 children = config.children;
11043 }
11044
11045 children.forEach((childRow) => {
11046 if(childRow instanceof Row){
11047 output.push(childRow);
11048 }
11049 });
11050 }
11051
11052 return output;
11053 }
11054
11055 rowDeleting(row){
11056 var config = row.modules.dataTree;
11057
11058 if (config && config.children && Array.isArray(config.children)){
11059 config.children.forEach((childRow) => {
11060 if(childRow instanceof Row){
11061 childRow.wipe();
11062 }
11063 });
11064 }
11065 }
11066
11067 rowDelete(row){
11068 var parent = row.modules.dataTree.parent,
11069 childIndex;
11070
11071 if(parent){
11072 childIndex = this.findChildIndex(row, parent);
11073
11074 if(childIndex !== false){
11075 parent.data[this.field].splice(childIndex, 1);
11076 }
11077
11078 if(!parent.data[this.field].length){
11079 delete parent.data[this.field];
11080 }
11081
11082 this.initializeRow(parent);
11083 this.layoutRow(parent);
11084 }
11085
11086 this.refreshData(true);
11087 }
11088
11089 addTreeChildRow(row, data, top, index){
11090 var childIndex = false;
11091
11092 if(typeof data === "string"){
11093 data = JSON.parse(data);
11094 }
11095
11096 if(!Array.isArray(row.data[this.field])){
11097 row.data[this.field] = [];
11098
11099 row.modules.dataTree.open = this.startOpen(row.getComponent(), row.modules.dataTree.index);
11100 }
11101
11102 if(typeof index !== "undefined"){
11103 childIndex = this.findChildIndex(index, row);
11104
11105 if(childIndex !== false){
11106 row.data[this.field].splice((top ? childIndex : childIndex + 1), 0, data);
11107 }
11108 }
11109
11110 if(childIndex === false){
11111 if(top){
11112 row.data[this.field].unshift(data);
11113 }else {
11114 row.data[this.field].push(data);
11115 }
11116 }
11117
11118 this.initializeRow(row);
11119 this.layoutRow(row);
11120
11121 this.refreshData(true);
11122 }
11123
11124 findChildIndex(subject, parent){
11125 var match = false;
11126
11127 if(typeof subject == "object"){
11128
11129 if(subject instanceof Row){
11130 //subject is row element
11131 match = subject.data;
11132 }else if(subject instanceof RowComponent){
11133 //subject is public row component
11134 match = subject._getSelf().data;
11135 }else if(typeof HTMLElement !== "undefined" && subject instanceof HTMLElement){
11136 if(parent.modules.dataTree){
11137 match = parent.modules.dataTree.children.find((childRow) => {
11138 return childRow instanceof Row ? childRow.element === subject : false;
11139 });
11140
11141 if(match){
11142 match = match.data;
11143 }
11144 }
11145 }else if(subject === null){
11146 match = false;
11147 }
11148
11149 }else if(typeof subject == "undefined"){
11150 match = false;
11151 }else {
11152 //subject should be treated as the index of the row
11153 match = parent.data[this.field].find((row) => {
11154 return row.data[this.table.options.index] == subject;
11155 });
11156 }
11157
11158 if(match){
11159
11160 if(Array.isArray(parent.data[this.field])){
11161 match = parent.data[this.field].indexOf(match);
11162 }
11163
11164 if(match == -1){
11165 match = false;
11166 }
11167 }
11168
11169 //catch all for any other type of input
11170
11171 return match;
11172 }
11173
11174 getTreeChildren(row, component, recurse){
11175 var config = row.modules.dataTree,
11176 output = [];
11177
11178 if(config && config.children){
11179
11180 if(!Array.isArray(config.children)){
11181 config.children = this.generateChildren(row);
11182 }
11183
11184 config.children.forEach((childRow) => {
11185 if(childRow instanceof Row){
11186 output.push(component ? childRow.getComponent() : childRow);
11187
11188 if(recurse){
11189 this.getTreeChildren(childRow, component, recurse).forEach(child => {
11190 output.push(child);
11191 });
11192 }
11193 }
11194 });
11195 }
11196
11197 return output;
11198 }
11199
11200 getChildField(){
11201 return this.field;
11202 }
11203
11204 redrawNeeded(data){
11205 return (this.field ? typeof data[this.field] !== "undefined" : false) || (this.elementField ? typeof data[this.elementField] !== "undefined" : false);
11206 }
11207 }
11208
11209 function csv$1(list, options = {}, setFileContents){
11210 var delimiter = options.delimiter ? options.delimiter : ",",
11211 fileContents = [],
11212 headers = [];
11213
11214 list.forEach((row) => {
11215 var item = [];
11216
11217 switch(row.type){
11218 case "group":
11219 console.warn("Download Warning - CSV downloader cannot process row groups");
11220 break;
11221
11222 case "calc":
11223 console.warn("Download Warning - CSV downloader cannot process column calculations");
11224 break;
11225
11226 case "header":
11227 row.columns.forEach((col, i) => {
11228 if(col && col.depth === 1){
11229 headers[i] = typeof col.value == "undefined" || col.value === null ? "" : ('"' + String(col.value).split('"').join('""') + '"');
11230 }
11231 });
11232 break;
11233
11234 case "row":
11235 row.columns.forEach((col) => {
11236
11237 if(col){
11238
11239 switch(typeof col.value){
11240 case "object":
11241 col.value = col.value !== null ? JSON.stringify(col.value) : "";
11242 break;
11243
11244 case "undefined":
11245 col.value = "";
11246 break;
11247 }
11248
11249 item.push('"' + String(col.value).split('"').join('""') + '"');
11250 }
11251 });
11252
11253 fileContents.push(item.join(delimiter));
11254 break;
11255 }
11256 });
11257
11258 if(headers.length){
11259 fileContents.unshift(headers.join(delimiter));
11260 }
11261
11262 fileContents = fileContents.join("\n");
11263
11264 if(options.bom){
11265 fileContents = "\ufeff" + fileContents;
11266 }
11267
11268 setFileContents(fileContents, "text/csv");
11269 }
11270
11271 function json$2(list, options, setFileContents){
11272 var fileContents = [];
11273
11274 list.forEach((row) => {
11275 var item = {};
11276
11277 switch(row.type){
11278 case "header":
11279 break;
11280
11281 case "group":
11282 console.warn("Download Warning - JSON downloader cannot process row groups");
11283 break;
11284
11285 case "calc":
11286 console.warn("Download Warning - JSON downloader cannot process column calculations");
11287 break;
11288
11289 case "row":
11290 row.columns.forEach((col) => {
11291 if(col){
11292 item[col.component.getTitleDownload() || col.component.getField()] = col.value;
11293 }
11294 });
11295
11296 fileContents.push(item);
11297 break;
11298 }
11299 });
11300
11301 fileContents = JSON.stringify(fileContents, null, '\t');
11302
11303 setFileContents(fileContents, "application/json");
11304 }
11305
11306 function pdf(list, options = {}, setFileContents){
11307 var header = [],
11308 body = [],
11309 autoTableParams = {},
11310 rowGroupStyles = options.rowGroupStyles || {
11311 fontStyle: "bold",
11312 fontSize: 12,
11313 cellPadding: 6,
11314 fillColor: 220,
11315 },
11316 rowCalcStyles = options.rowCalcStyles || {
11317 fontStyle: "bold",
11318 fontSize: 10,
11319 cellPadding: 4,
11320 fillColor: 232,
11321 },
11322 jsPDFParams = options.jsPDF || {},
11323 title = options.title ? options.title : "",
11324 jspdfLib, doc;
11325
11326 if(!jsPDFParams.orientation){
11327 jsPDFParams.orientation = options.orientation || "landscape";
11328 }
11329
11330 if(!jsPDFParams.unit){
11331 jsPDFParams.unit = "pt";
11332 }
11333
11334 //parse row list
11335 list.forEach((row) => {
11336 switch(row.type){
11337 case "header":
11338 header.push(parseRow(row));
11339 break;
11340
11341 case "group":
11342 body.push(parseRow(row, rowGroupStyles));
11343 break;
11344
11345 case "calc":
11346 body.push(parseRow(row, rowCalcStyles));
11347 break;
11348
11349 case "row":
11350 body.push(parseRow(row));
11351 break;
11352 }
11353 });
11354
11355 function parseRow(row, styles){
11356 var rowData = [];
11357
11358 row.columns.forEach((col) =>{
11359 var cell;
11360
11361 if(col){
11362 switch(typeof col.value){
11363 case "object":
11364 col.value = col.value !== null ? JSON.stringify(col.value) : "";
11365 break;
11366
11367 case "undefined":
11368 col.value = "";
11369 break;
11370 }
11371
11372 cell = {
11373 content:col.value,
11374 colSpan:col.width,
11375 rowSpan:col.height,
11376 };
11377
11378 if(styles){
11379 cell.styles = styles;
11380 }
11381
11382 rowData.push(cell);
11383 }
11384 });
11385
11386 return rowData;
11387 }
11388
11389
11390 //configure PDF
11391 jspdfLib = this.dependencyRegistry.lookup("jspdf", "jsPDF");
11392 doc = new jspdfLib(jsPDFParams); //set document to landscape, better for most tables
11393
11394 if(options.autoTable){
11395 if(typeof options.autoTable === "function"){
11396 autoTableParams = options.autoTable(doc) || {};
11397 }else {
11398 autoTableParams = options.autoTable;
11399 }
11400 }
11401
11402 if(title){
11403 autoTableParams.didDrawPage = function(data) {
11404 doc.text(title, 40, 30);
11405 };
11406 }
11407
11408 autoTableParams.head = header;
11409 autoTableParams.body = body;
11410
11411 doc.autoTable(autoTableParams);
11412
11413 if(options.documentProcessing){
11414 options.documentProcessing(doc);
11415 }
11416
11417 setFileContents(doc.output("arraybuffer"), "application/pdf");
11418 }
11419
11420 function xlsx$1(list, options, setFileContents){
11421 var self = this,
11422 sheetName = options.sheetName || "Sheet1",
11423 XLSXLib = this.dependencyRegistry.lookup("XLSX"),
11424 workbook = XLSXLib.utils.book_new(),
11425 tableFeatures = new CoreFeature(this),
11426 compression = 'compress' in options ? options.compress : true,
11427 writeOptions = options.writeOptions || {bookType:'xlsx', bookSST:true, compression},
11428 output;
11429
11430 writeOptions.type = 'binary';
11431
11432 workbook.SheetNames = [];
11433 workbook.Sheets = {};
11434
11435 function generateSheet(){
11436 var rows = [],
11437 merges = [],
11438 worksheet = {},
11439 range = {s: {c:0, r:0}, e: {c:(list[0] ? list[0].columns.reduce((a, b) => a + (b && b.width ? b.width : 1), 0) : 0), r:list.length }};
11440
11441 //parse row list
11442 list.forEach((row, i) => {
11443 var rowData = [];
11444
11445 row.columns.forEach(function(col, j){
11446
11447 if(col){
11448 rowData.push(!(col.value instanceof Date) && typeof col.value === "object" ? JSON.stringify(col.value) : col.value);
11449
11450 if(col.width > 1 || col.height > -1){
11451 if(col.height > 1 || col.width > 1){
11452 merges.push({s:{r:i,c:j},e:{r:i + col.height - 1,c:j + col.width - 1}});
11453 }
11454 }
11455 }else {
11456 rowData.push("");
11457 }
11458 });
11459
11460 rows.push(rowData);
11461 });
11462
11463 //convert rows to worksheet
11464 XLSXLib.utils.sheet_add_aoa(worksheet, rows);
11465
11466 worksheet['!ref'] = XLSXLib.utils.encode_range(range);
11467
11468 if(merges.length){
11469 worksheet["!merges"] = merges;
11470 }
11471
11472 return worksheet;
11473 }
11474
11475 if(options.sheetOnly){
11476 setFileContents(generateSheet());
11477 return;
11478 }
11479
11480 if(options.sheets){
11481 for(var sheet in options.sheets){
11482
11483 if(options.sheets[sheet] === true){
11484 workbook.SheetNames.push(sheet);
11485 workbook.Sheets[sheet] = generateSheet();
11486 }else {
11487
11488 workbook.SheetNames.push(sheet);
11489
11490 tableFeatures.commsSend(options.sheets[sheet], "download", "intercept",{
11491 type:"xlsx",
11492 options:{sheetOnly:true},
11493 active:self.active,
11494 intercept:function(data){
11495 workbook.Sheets[sheet] = data;
11496 }
11497 });
11498 }
11499 }
11500 }else {
11501 workbook.SheetNames.push(sheetName);
11502 workbook.Sheets[sheetName] = generateSheet();
11503 }
11504
11505 if(options.documentProcessing){
11506 workbook = options.documentProcessing(workbook);
11507 }
11508
11509 //convert workbook to binary array
11510 function s2ab(s) {
11511 var buf = new ArrayBuffer(s.length);
11512 var view = new Uint8Array(buf);
11513 for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
11514 return buf;
11515 }
11516
11517 output = XLSXLib.write(workbook, writeOptions);
11518
11519 setFileContents(s2ab(output), "application/octet-stream");
11520 }
11521
11522 function html$1(list, options, setFileContents){
11523 if(this.modExists("export", true)){
11524 setFileContents(this.modules.export.generateHTMLTable(list), "text/html");
11525 }
11526 }
11527
11528 function jsonLines (list, options, setFileContents) {
11529 const fileContents = [];
11530
11531 list.forEach((row) => {
11532 const item = {};
11533
11534 switch (row.type) {
11535 case "header":
11536 break;
11537
11538 case "group":
11539 console.warn("Download Warning - JSON downloader cannot process row groups");
11540 break;
11541
11542 case "calc":
11543 console.warn("Download Warning - JSON downloader cannot process column calculations");
11544 break;
11545
11546 case "row":
11547 row.columns.forEach((col) => {
11548 if (col) {
11549 item[col.component.getTitleDownload() || col.component.getField()] = col.value;
11550 }
11551 });
11552
11553 fileContents.push(JSON.stringify(item));
11554 break;
11555 }
11556 });
11557
11558 setFileContents(fileContents.join("\n"), "application/x-ndjson");
11559 }
11560
11561 var defaultDownloaders = {
11562 csv:csv$1,
11563 json:json$2,
11564 jsonLines:jsonLines,
11565 pdf:pdf,
11566 xlsx:xlsx$1,
11567 html:html$1,
11568 };
11569
11570 class Download extends Module{
11571
11572 static moduleName = "download";
11573
11574 //load defaults
11575 static downloaders = defaultDownloaders;
11576
11577 constructor(table){
11578 super(table);
11579
11580 this.registerTableOption("downloadEncoder", function(data, mimeType){
11581 return new Blob([data],{type:mimeType});
11582 }); //function to manipulate download data
11583 this.registerTableOption("downloadConfig", {}); //download config
11584 this.registerTableOption("downloadRowRange", "active"); //restrict download to active rows only
11585
11586 this.registerColumnOption("download");
11587 this.registerColumnOption("titleDownload");
11588 }
11589
11590 initialize(){
11591 this.deprecatedOptionsCheck();
11592
11593 this.registerTableFunction("download", this.download.bind(this));
11594 this.registerTableFunction("downloadToTab", this.downloadToTab.bind(this));
11595 }
11596
11597 deprecatedOptionsCheck(){
11598
11599 }
11600
11601 ///////////////////////////////////
11602 ///////// Table Functions /////////
11603 ///////////////////////////////////
11604
11605 downloadToTab(type, filename, options, active){
11606 this.download(type, filename, options, active, true);
11607 }
11608
11609 ///////////////////////////////////
11610 ///////// Internal Logic //////////
11611 ///////////////////////////////////
11612
11613 //trigger file download
11614 download(type, filename, options, range, interceptCallback){
11615 var downloadFunc = false;
11616
11617 function buildLink(data, mime){
11618 if(interceptCallback){
11619 if(interceptCallback === true){
11620 this.triggerDownload(data, mime, type, filename, true);
11621 }else {
11622 interceptCallback(data);
11623 }
11624
11625 }else {
11626 this.triggerDownload(data, mime, type, filename);
11627 }
11628 }
11629
11630 if(typeof type == "function"){
11631 downloadFunc = type;
11632 }else {
11633 if(Download.downloaders[type]){
11634 downloadFunc = Download.downloaders[type];
11635 }else {
11636 console.warn("Download Error - No such download type found: ", type);
11637 }
11638 }
11639
11640 if(downloadFunc){
11641 var list = this.generateExportList(range);
11642
11643 downloadFunc.call(this.table, list , options || {}, buildLink.bind(this));
11644 }
11645 }
11646
11647 generateExportList(range){
11648 var list = this.table.modules.export.generateExportList(this.table.options.downloadConfig, false, range || this.table.options.downloadRowRange, "download");
11649
11650 //assign group header formatter
11651 var groupHeader = this.table.options.groupHeaderDownload;
11652
11653 if(groupHeader && !Array.isArray(groupHeader)){
11654 groupHeader = [groupHeader];
11655 }
11656
11657 list.forEach((row) => {
11658 var group;
11659
11660 if(row.type === "group"){
11661 group = row.columns[0];
11662
11663 if(groupHeader && groupHeader[row.indent]){
11664 group.value = groupHeader[row.indent](group.value, row.component._group.getRowCount(), row.component._group.getData(), row.component);
11665 }
11666 }
11667 });
11668
11669 return list;
11670 }
11671
11672 triggerDownload(data, mime, type, filename, newTab){
11673 var element = document.createElement('a'),
11674 blob = this.table.options.downloadEncoder(data, mime);
11675
11676 if(blob){
11677 if(newTab){
11678 window.open(window.URL.createObjectURL(blob));
11679 }else {
11680 filename = filename || "Tabulator." + (typeof type === "function" ? "txt" : type);
11681
11682 if(navigator.msSaveOrOpenBlob){
11683 navigator.msSaveOrOpenBlob(blob, filename);
11684 }else {
11685 element.setAttribute('href', window.URL.createObjectURL(blob));
11686
11687 //set file title
11688 element.setAttribute('download', filename);
11689
11690 //trigger download
11691 element.style.display = 'none';
11692 document.body.appendChild(element);
11693 element.click();
11694
11695 //remove temporary link element
11696 document.body.removeChild(element);
11697 }
11698 }
11699
11700 this.dispatchExternal("downloadComplete");
11701 }
11702 }
11703
11704 commsReceived(table, action, data){
11705 switch(action){
11706 case "intercept":
11707 this.download(data.type, "", data.options, data.active, data.intercept);
11708 break;
11709 }
11710 }
11711 }
11712
11713 function maskInput(el, options){
11714 var mask = options.mask,
11715 maskLetter = typeof options.maskLetterChar !== "undefined" ? options.maskLetterChar : "A",
11716 maskNumber = typeof options.maskNumberChar !== "undefined" ? options.maskNumberChar : "9",
11717 maskWildcard = typeof options.maskWildcardChar !== "undefined" ? options.maskWildcardChar : "*";
11718
11719 function fillSymbols(index){
11720 var symbol = mask[index];
11721 if(typeof symbol !== "undefined" && symbol !== maskWildcard && symbol !== maskLetter && symbol !== maskNumber){
11722 el.value = el.value + "" + symbol;
11723 fillSymbols(index+1);
11724 }
11725 }
11726
11727 el.addEventListener("keydown", (e) => {
11728 var index = el.value.length,
11729 char = e.key;
11730
11731 if(e.keyCode > 46 && !e.ctrlKey && !e.metaKey){
11732 if(index >= mask.length){
11733 e.preventDefault();
11734 e.stopPropagation();
11735 return false;
11736 }else {
11737 switch(mask[index]){
11738 case maskLetter:
11739 if(char.toUpperCase() == char.toLowerCase()){
11740 e.preventDefault();
11741 e.stopPropagation();
11742 return false;
11743 }
11744 break;
11745
11746 case maskNumber:
11747 if(isNaN(char)){
11748 e.preventDefault();
11749 e.stopPropagation();
11750 return false;
11751 }
11752 break;
11753
11754 case maskWildcard:
11755 break;
11756
11757 default:
11758 if(char !== mask[index]){
11759 e.preventDefault();
11760 e.stopPropagation();
11761 return false;
11762 }
11763 }
11764 }
11765 }
11766
11767 return;
11768 });
11769
11770 el.addEventListener("keyup", (e) => {
11771 if(e.keyCode > 46){
11772 if(options.maskAutoFill){
11773 fillSymbols(el.value.length);
11774 }
11775 }
11776 });
11777
11778
11779 if(!el.placeholder){
11780 el.placeholder = mask;
11781 }
11782
11783 if(options.maskAutoFill){
11784 fillSymbols(el.value.length);
11785 }
11786 }
11787
11788 //input element
11789 function input(cell, onRendered, success, cancel, editorParams){
11790 //create and style input
11791 var cellValue = cell.getValue(),
11792 input = document.createElement("input");
11793
11794 input.setAttribute("type", editorParams.search ? "search" : "text");
11795
11796 input.style.padding = "4px";
11797 input.style.width = "100%";
11798 input.style.boxSizing = "border-box";
11799
11800 if(editorParams.elementAttributes && typeof editorParams.elementAttributes == "object"){
11801 for (let key in editorParams.elementAttributes){
11802 if(key.charAt(0) == "+"){
11803 key = key.slice(1);
11804 input.setAttribute(key, input.getAttribute(key) + editorParams.elementAttributes["+" + key]);
11805 }else {
11806 input.setAttribute(key, editorParams.elementAttributes[key]);
11807 }
11808 }
11809 }
11810
11811 input.value = typeof cellValue !== "undefined" ? cellValue : "";
11812
11813 onRendered(function(){
11814 if(cell.getType() === "cell"){
11815 input.focus({preventScroll: true});
11816 input.style.height = "100%";
11817
11818 if(editorParams.selectContents){
11819 input.select();
11820 }
11821 }
11822 });
11823
11824 function onChange(e){
11825 if(((cellValue === null || typeof cellValue === "undefined") && input.value !== "") || input.value !== cellValue){
11826 if(success(input.value)){
11827 cellValue = input.value; //persist value if successfully validated incase editor is used as header filter
11828 }
11829 }else {
11830 cancel();
11831 }
11832 }
11833
11834 //submit new value on blur or change
11835 input.addEventListener("change", onChange);
11836 input.addEventListener("blur", onChange);
11837
11838 //submit new value on enter
11839 input.addEventListener("keydown", function(e){
11840 switch(e.keyCode){
11841 // case 9:
11842 case 13:
11843 onChange();
11844 break;
11845
11846 case 27:
11847 cancel();
11848 break;
11849
11850 case 35:
11851 case 36:
11852 e.stopPropagation();
11853 break;
11854 }
11855 });
11856
11857 if(editorParams.mask){
11858 maskInput(input, editorParams);
11859 }
11860
11861 return input;
11862 }
11863
11864 //resizable text area element
11865 function textarea$1(cell, onRendered, success, cancel, editorParams){
11866 var cellValue = cell.getValue(),
11867 vertNav = editorParams.verticalNavigation || "hybrid",
11868 value = String(cellValue !== null && typeof cellValue !== "undefined" ? cellValue : ""),
11869 input = document.createElement("textarea"),
11870 scrollHeight = 0;
11871
11872 //create and style input
11873 input.style.display = "block";
11874 input.style.padding = "2px";
11875 input.style.height = "100%";
11876 input.style.width = "100%";
11877 input.style.boxSizing = "border-box";
11878 input.style.whiteSpace = "pre-wrap";
11879 input.style.resize = "none";
11880
11881 if(editorParams.elementAttributes && typeof editorParams.elementAttributes == "object"){
11882 for (let key in editorParams.elementAttributes){
11883 if(key.charAt(0) == "+"){
11884 key = key.slice(1);
11885 input.setAttribute(key, input.getAttribute(key) + editorParams.elementAttributes["+" + key]);
11886 }else {
11887 input.setAttribute(key, editorParams.elementAttributes[key]);
11888 }
11889 }
11890 }
11891
11892 input.value = value;
11893
11894 onRendered(function(){
11895 if(cell.getType() === "cell"){
11896 input.focus({preventScroll: true});
11897 input.style.height = "100%";
11898
11899 input.scrollHeight;
11900 input.style.height = input.scrollHeight + "px";
11901 cell.getRow().normalizeHeight();
11902
11903 if(editorParams.selectContents){
11904 input.select();
11905 }
11906 }
11907 });
11908
11909 function onChange(e){
11910
11911 if(((cellValue === null || typeof cellValue === "undefined") && input.value !== "") || input.value !== cellValue){
11912
11913 if(success(input.value)){
11914 cellValue = input.value; //persist value if successfully validated incase editor is used as header filter
11915 }
11916
11917 setTimeout(function(){
11918 cell.getRow().normalizeHeight();
11919 },300);
11920 }else {
11921 cancel();
11922 }
11923 }
11924
11925 //submit new value on blur or change
11926 input.addEventListener("change", onChange);
11927 input.addEventListener("blur", onChange);
11928
11929 input.addEventListener("keyup", function(){
11930
11931 input.style.height = "";
11932
11933 var heightNow = input.scrollHeight;
11934
11935 input.style.height = heightNow + "px";
11936
11937 if(heightNow != scrollHeight){
11938 scrollHeight = heightNow;
11939 cell.getRow().normalizeHeight();
11940 }
11941 });
11942
11943 input.addEventListener("keydown", function(e){
11944
11945 switch(e.keyCode){
11946
11947 case 13:
11948 if(e.shiftKey && editorParams.shiftEnterSubmit){
11949 onChange();
11950 }
11951 break;
11952
11953 case 27:
11954 cancel();
11955 break;
11956
11957 case 38: //up arrow
11958 if(vertNav == "editor" || (vertNav == "hybrid" && input.selectionStart)){
11959 e.stopImmediatePropagation();
11960 e.stopPropagation();
11961 }
11962
11963 break;
11964
11965 case 40: //down arrow
11966 if(vertNav == "editor" || (vertNav == "hybrid" && input.selectionStart !== input.value.length)){
11967 e.stopImmediatePropagation();
11968 e.stopPropagation();
11969 }
11970 break;
11971
11972 case 35:
11973 case 36:
11974 e.stopPropagation();
11975 break;
11976 }
11977 });
11978
11979 if(editorParams.mask){
11980 maskInput(input, editorParams);
11981 }
11982
11983 return input;
11984 }
11985
11986 //input element with type of number
11987 function number$1(cell, onRendered, success, cancel, editorParams){
11988 var cellValue = cell.getValue(),
11989 vertNav = editorParams.verticalNavigation || "editor",
11990 input = document.createElement("input");
11991
11992 input.setAttribute("type", "number");
11993
11994 if(typeof editorParams.max != "undefined"){
11995 input.setAttribute("max", editorParams.max);
11996 }
11997
11998 if(typeof editorParams.min != "undefined"){
11999 input.setAttribute("min", editorParams.min);
12000 }
12001
12002 if(typeof editorParams.step != "undefined"){
12003 input.setAttribute("step", editorParams.step);
12004 }
12005
12006 //create and style input
12007 input.style.padding = "4px";
12008 input.style.width = "100%";
12009 input.style.boxSizing = "border-box";
12010
12011 if(editorParams.elementAttributes && typeof editorParams.elementAttributes == "object"){
12012 for (let key in editorParams.elementAttributes){
12013 if(key.charAt(0) == "+"){
12014 key = key.slice(1);
12015 input.setAttribute(key, input.getAttribute(key) + editorParams.elementAttributes["+" + key]);
12016 }else {
12017 input.setAttribute(key, editorParams.elementAttributes[key]);
12018 }
12019 }
12020 }
12021
12022 input.value = cellValue;
12023
12024 var blurFunc = function(e){
12025 onChange();
12026 };
12027
12028 onRendered(function () {
12029 if(cell.getType() === "cell"){
12030 //submit new value on blur
12031 input.removeEventListener("blur", blurFunc);
12032
12033 input.focus({preventScroll: true});
12034 input.style.height = "100%";
12035
12036 //submit new value on blur
12037 input.addEventListener("blur", blurFunc);
12038
12039 if(editorParams.selectContents){
12040 input.select();
12041 }
12042 }
12043 });
12044
12045 function onChange(){
12046 var value = input.value;
12047
12048 if(!isNaN(value) && value !==""){
12049 value = Number(value);
12050 }
12051
12052 if(value !== cellValue){
12053 if(success(value)){
12054 cellValue = value; //persist value if successfully validated incase editor is used as header filter
12055 }
12056 }else {
12057 cancel();
12058 }
12059 }
12060
12061 //submit new value on enter
12062 input.addEventListener("keydown", function(e){
12063 switch(e.keyCode){
12064 case 13:
12065 // case 9:
12066 onChange();
12067 break;
12068
12069 case 27:
12070 cancel();
12071 break;
12072
12073 case 38: //up arrow
12074 case 40: //down arrow
12075 if(vertNav == "editor"){
12076 e.stopImmediatePropagation();
12077 e.stopPropagation();
12078 }
12079 break;
12080
12081 case 35:
12082 case 36:
12083 e.stopPropagation();
12084 break;
12085 }
12086 });
12087
12088 if(editorParams.mask){
12089 maskInput(input, editorParams);
12090 }
12091
12092 return input;
12093 }
12094
12095 //input element with type of number
12096 function range(cell, onRendered, success, cancel, editorParams){
12097 var cellValue = cell.getValue(),
12098 input = document.createElement("input");
12099
12100 input.setAttribute("type", "range");
12101
12102 if (typeof editorParams.max != "undefined") {
12103 input.setAttribute("max", editorParams.max);
12104 }
12105
12106 if (typeof editorParams.min != "undefined") {
12107 input.setAttribute("min", editorParams.min);
12108 }
12109
12110 if (typeof editorParams.step != "undefined") {
12111 input.setAttribute("step", editorParams.step);
12112 }
12113
12114 //create and style input
12115 input.style.padding = "4px";
12116 input.style.width = "100%";
12117 input.style.boxSizing = "border-box";
12118
12119 if(editorParams.elementAttributes && typeof editorParams.elementAttributes == "object"){
12120 for (let key in editorParams.elementAttributes){
12121 if(key.charAt(0) == "+"){
12122 key = key.slice(1);
12123 input.setAttribute(key, input.getAttribute(key) + editorParams.elementAttributes["+" + key]);
12124 }else {
12125 input.setAttribute(key, editorParams.elementAttributes[key]);
12126 }
12127 }
12128 }
12129
12130 input.value = cellValue;
12131
12132 onRendered(function () {
12133 if(cell.getType() === "cell"){
12134 input.focus({preventScroll: true});
12135 input.style.height = "100%";
12136 }
12137 });
12138
12139 function onChange(){
12140 var value = input.value;
12141
12142 if(!isNaN(value) && value !==""){
12143 value = Number(value);
12144 }
12145
12146 if(value != cellValue){
12147 if(success(value)){
12148 cellValue = value; //persist value if successfully validated incase editor is used as header filter
12149 }
12150 }else {
12151 cancel();
12152 }
12153 }
12154
12155 //submit new value on blur
12156 input.addEventListener("blur", function(e){
12157 onChange();
12158 });
12159
12160 //submit new value on enter
12161 input.addEventListener("keydown", function(e){
12162 switch(e.keyCode){
12163 case 13:
12164 // case 9:
12165 onChange();
12166 break;
12167
12168 case 27:
12169 cancel();
12170 break;
12171 }
12172 });
12173
12174 return input;
12175 }
12176
12177 //input element
12178 function date$1(cell, onRendered, success, cancel, editorParams){
12179 var inputFormat = editorParams.format,
12180 vertNav = editorParams.verticalNavigation || "editor",
12181 DT = inputFormat ? (window.DateTime || luxon.DateTime) : null;
12182
12183 //create and style input
12184 var cellValue = cell.getValue(),
12185 input = document.createElement("input");
12186
12187 function convertDate(value){
12188 var newDatetime;
12189
12190 if(DT.isDateTime(value)){
12191 newDatetime = value;
12192 }else if(inputFormat === "iso"){
12193 newDatetime = DT.fromISO(String(value));
12194 }else {
12195 newDatetime = DT.fromFormat(String(value), inputFormat);
12196 }
12197
12198 return newDatetime.toFormat("yyyy-MM-dd");
12199 }
12200
12201 input.type = "date";
12202 input.style.padding = "4px";
12203 input.style.width = "100%";
12204 input.style.boxSizing = "border-box";
12205
12206 if(editorParams.max){
12207 input.setAttribute("max", inputFormat ? convertDate(editorParams.max) : editorParams.max);
12208 }
12209
12210 if(editorParams.min){
12211 input.setAttribute("min", inputFormat ? convertDate(editorParams.min) : editorParams.min);
12212 }
12213
12214 if(editorParams.elementAttributes && typeof editorParams.elementAttributes == "object"){
12215 for (let key in editorParams.elementAttributes){
12216 if(key.charAt(0) == "+"){
12217 key = key.slice(1);
12218 input.setAttribute(key, input.getAttribute(key) + editorParams.elementAttributes["+" + key]);
12219 }else {
12220 input.setAttribute(key, editorParams.elementAttributes[key]);
12221 }
12222 }
12223 }
12224
12225 cellValue = typeof cellValue !== "undefined" ? cellValue : "";
12226
12227 if(inputFormat){
12228 if(DT){
12229 cellValue = convertDate(cellValue);
12230 }else {
12231 console.error("Editor Error - 'date' editor 'format' param is dependant on luxon.js");
12232 }
12233 }
12234
12235 input.value = cellValue;
12236
12237 onRendered(function(){
12238 if(cell.getType() === "cell"){
12239 input.focus({preventScroll: true});
12240 input.style.height = "100%";
12241
12242 if(editorParams.selectContents){
12243 input.select();
12244 }
12245 }
12246 });
12247
12248 function onChange(){
12249 var value = input.value,
12250 luxDate;
12251
12252 if(((cellValue === null || typeof cellValue === "undefined") && value !== "") || value !== cellValue){
12253
12254 if(value && inputFormat){
12255 luxDate = DT.fromFormat(String(value), "yyyy-MM-dd");
12256
12257 switch(inputFormat){
12258 case true:
12259 value = luxDate;
12260 break;
12261
12262 case "iso":
12263 value = luxDate.toISO();
12264 break;
12265
12266 default:
12267 value = luxDate.toFormat(inputFormat);
12268 }
12269 }
12270
12271 if(success(value)){
12272 cellValue = input.value; //persist value if successfully validated incase editor is used as header filter
12273 }
12274 }else {
12275 cancel();
12276 }
12277 }
12278
12279 //submit new value on blur
12280 input.addEventListener("blur", function(e) {
12281 if (e.relatedTarget || e.rangeParent || e.explicitOriginalTarget !== input) {
12282 onChange(); // only on a "true" blur; not when focusing browser's date/time picker
12283 }
12284 });
12285
12286 //submit new value on enter
12287 input.addEventListener("keydown", function(e){
12288 switch(e.keyCode){
12289 // case 9:
12290 case 13:
12291 onChange();
12292 break;
12293
12294 case 27:
12295 cancel();
12296 break;
12297
12298 case 35:
12299 case 36:
12300 e.stopPropagation();
12301 break;
12302
12303 case 38: //up arrow
12304 case 40: //down arrow
12305 if(vertNav == "editor"){
12306 e.stopImmediatePropagation();
12307 e.stopPropagation();
12308 }
12309 break;
12310 }
12311 });
12312
12313 return input;
12314 }
12315
12316 //input element
12317 function time$1(cell, onRendered, success, cancel, editorParams){
12318 var inputFormat = editorParams.format,
12319 vertNav = editorParams.verticalNavigation || "editor",
12320 DT = inputFormat ? (window.DateTime || luxon.DateTime) : null,
12321 newDatetime;
12322
12323 //create and style input
12324 var cellValue = cell.getValue(),
12325 input = document.createElement("input");
12326
12327 input.type = "time";
12328 input.style.padding = "4px";
12329 input.style.width = "100%";
12330 input.style.boxSizing = "border-box";
12331
12332 if(editorParams.elementAttributes && typeof editorParams.elementAttributes == "object"){
12333 for (let key in editorParams.elementAttributes){
12334 if(key.charAt(0) == "+"){
12335 key = key.slice(1);
12336 input.setAttribute(key, input.getAttribute(key) + editorParams.elementAttributes["+" + key]);
12337 }else {
12338 input.setAttribute(key, editorParams.elementAttributes[key]);
12339 }
12340 }
12341 }
12342
12343 cellValue = typeof cellValue !== "undefined" ? cellValue : "";
12344
12345 if(inputFormat){
12346 if(DT){
12347 if(DT.isDateTime(cellValue)){
12348 newDatetime = cellValue;
12349 }else if(inputFormat === "iso"){
12350 newDatetime = DT.fromISO(String(cellValue));
12351 }else {
12352 newDatetime = DT.fromFormat(String(cellValue), inputFormat);
12353 }
12354
12355 cellValue = newDatetime.toFormat("HH:mm");
12356
12357 }else {
12358 console.error("Editor Error - 'date' editor 'format' param is dependant on luxon.js");
12359 }
12360 }
12361
12362 input.value = cellValue;
12363
12364 onRendered(function(){
12365 if(cell.getType() == "cell"){
12366 input.focus({preventScroll: true});
12367 input.style.height = "100%";
12368
12369 if(editorParams.selectContents){
12370 input.select();
12371 }
12372 }
12373 });
12374
12375 function onChange(){
12376 var value = input.value,
12377 luxTime;
12378
12379 if(((cellValue === null || typeof cellValue === "undefined") && value !== "") || value !== cellValue){
12380
12381 if(value && inputFormat){
12382 luxTime = DT.fromFormat(String(value), "hh:mm");
12383
12384 switch(inputFormat){
12385 case true:
12386 value = luxTime;
12387 break;
12388
12389 case "iso":
12390 value = luxTime.toISO();
12391 break;
12392
12393 default:
12394 value = luxTime.toFormat(inputFormat);
12395 }
12396 }
12397
12398 if(success(value)){
12399 cellValue = input.value; //persist value if successfully validated incase editor is used as header filter
12400 }
12401 }else {
12402 cancel();
12403 }
12404 }
12405
12406 //submit new value on blur
12407 input.addEventListener("blur", function(e) {
12408 if (e.relatedTarget || e.rangeParent || e.explicitOriginalTarget !== input) {
12409 onChange(); // only on a "true" blur; not when focusing browser's date/time picker
12410 }
12411 });
12412
12413 //submit new value on enter
12414 input.addEventListener("keydown", function(e){
12415 switch(e.keyCode){
12416 // case 9:
12417 case 13:
12418 onChange();
12419 break;
12420
12421 case 27:
12422 cancel();
12423 break;
12424
12425 case 35:
12426 case 36:
12427 e.stopPropagation();
12428 break;
12429
12430 case 38: //up arrow
12431 case 40: //down arrow
12432 if(vertNav == "editor"){
12433 e.stopImmediatePropagation();
12434 e.stopPropagation();
12435 }
12436 break;
12437 }
12438 });
12439
12440 return input;
12441 }
12442
12443 //input element
12444 function datetime$2(cell, onRendered, success, cancel, editorParams){
12445 var inputFormat = editorParams.format,
12446 vertNav = editorParams.verticalNavigation || "editor",
12447 DT = inputFormat ? (this.table.dependencyRegistry.lookup(["luxon", "DateTime"], "DateTime")) : null,
12448 newDatetime;
12449
12450 //create and style input
12451 var cellValue = cell.getValue(),
12452 input = document.createElement("input");
12453
12454 input.type = "datetime-local";
12455 input.style.padding = "4px";
12456 input.style.width = "100%";
12457 input.style.boxSizing = "border-box";
12458
12459 if(editorParams.elementAttributes && typeof editorParams.elementAttributes == "object"){
12460 for (let key in editorParams.elementAttributes){
12461 if(key.charAt(0) == "+"){
12462 key = key.slice(1);
12463 input.setAttribute(key, input.getAttribute(key) + editorParams.elementAttributes["+" + key]);
12464 }else {
12465 input.setAttribute(key, editorParams.elementAttributes[key]);
12466 }
12467 }
12468 }
12469
12470 cellValue = typeof cellValue !== "undefined" ? cellValue : "";
12471
12472 if(inputFormat){
12473 if(DT){
12474 if(DT.isDateTime(cellValue)){
12475 newDatetime = cellValue;
12476 }else if(inputFormat === "iso"){
12477 newDatetime = DT.fromISO(String(cellValue));
12478 }else {
12479 newDatetime = DT.fromFormat(String(cellValue), inputFormat);
12480 }
12481
12482 cellValue = newDatetime.toFormat("yyyy-MM-dd") + "T" + newDatetime.toFormat("HH:mm");
12483 }else {
12484 console.error("Editor Error - 'date' editor 'format' param is dependant on luxon.js");
12485 }
12486 }
12487
12488 input.value = cellValue;
12489
12490 onRendered(function(){
12491 if(cell.getType() === "cell"){
12492 input.focus({preventScroll: true});
12493 input.style.height = "100%";
12494
12495 if(editorParams.selectContents){
12496 input.select();
12497 }
12498 }
12499 });
12500
12501 function onChange(){
12502 var value = input.value,
12503 luxDateTime;
12504
12505 if(((cellValue === null || typeof cellValue === "undefined") && value !== "") || value !== cellValue){
12506
12507 if(value && inputFormat){
12508 luxDateTime = DT.fromISO(String(value));
12509
12510 switch(inputFormat){
12511 case true:
12512 value = luxDateTime;
12513 break;
12514
12515 case "iso":
12516 value = luxDateTime.toISO();
12517 break;
12518
12519 default:
12520 value = luxDateTime.toFormat(inputFormat);
12521 }
12522 }
12523
12524 if(success(value)){
12525 cellValue = input.value; //persist value if successfully validated incase editor is used as header filter
12526 }
12527 }else {
12528 cancel();
12529 }
12530 }
12531
12532 //submit new value on blur
12533 input.addEventListener("blur", function(e) {
12534 if (e.relatedTarget || e.rangeParent || e.explicitOriginalTarget !== input) {
12535 onChange(); // only on a "true" blur; not when focusing browser's date/time picker
12536 }
12537 });
12538
12539 //submit new value on enter
12540 input.addEventListener("keydown", function(e){
12541 switch(e.keyCode){
12542 // case 9:
12543 case 13:
12544 onChange();
12545 break;
12546
12547 case 27:
12548 cancel();
12549 break;
12550
12551 case 35:
12552 case 36:
12553 e.stopPropagation();
12554 break;
12555
12556 case 38: //up arrow
12557 case 40: //down arrow
12558 if(vertNav == "editor"){
12559 e.stopImmediatePropagation();
12560 e.stopPropagation();
12561 }
12562 break;
12563 }
12564 });
12565
12566 return input;
12567 }
12568
12569 let Edit$1 = class Edit{
12570 constructor(editor, cell, onRendered, success, cancel, editorParams){
12571 this.edit = editor;
12572 this.table = editor.table;
12573 this.cell = cell;
12574 this.params = this._initializeParams(editorParams);
12575
12576 this.data = [];
12577 this.displayItems = [];
12578 this.currentItems = [];
12579 this.focusedItem = null;
12580
12581 this.input = this._createInputElement();
12582 this.listEl = this._createListElement();
12583
12584 this.initialValues = null;
12585
12586 this.isFilter = cell.getType() === "header";
12587
12588 this.filterTimeout = null;
12589 this.filtered = false;
12590 this.typing = false;
12591
12592 this.values = [];
12593 this.popup = null;
12594
12595 this.listIteration = 0;
12596
12597 this.lastAction="";
12598 this.filterTerm="";
12599
12600 this.blurable = true;
12601
12602 this.actions = {
12603 success:success,
12604 cancel:cancel
12605 };
12606
12607 this._deprecatedOptionsCheck();
12608 this._initializeValue();
12609
12610 onRendered(this._onRendered.bind(this));
12611 }
12612
12613 _deprecatedOptionsCheck(){
12614 // if(this.params.listItemFormatter){
12615 // this.cell.getTable().deprecationAdvisor.msg("The listItemFormatter editor param has been deprecated, please see the latest editor documentation for updated options");
12616 // }
12617
12618 // if(this.params.sortValuesList){
12619 // this.cell.getTable().deprecationAdvisor.msg("The sortValuesList editor param has been deprecated, please see the latest editor documentation for updated options");
12620 // }
12621
12622 // if(this.params.searchFunc){
12623 // this.cell.getTable().deprecationAdvisor.msg("The searchFunc editor param has been deprecated, please see the latest editor documentation for updated options");
12624 // }
12625
12626 // if(this.params.searchingPlaceholder){
12627 // this.cell.getTable().deprecationAdvisor.msg("The searchingPlaceholder editor param has been deprecated, please see the latest editor documentation for updated options");
12628 // }
12629 }
12630
12631 _initializeValue(){
12632 var initialValue = this.cell.getValue();
12633
12634 if(typeof initialValue === "undefined" && typeof this.params.defaultValue !== "undefined"){
12635 initialValue = this.params.defaultValue;
12636 }
12637
12638 this.initialValues = this.params.multiselect ? initialValue : [initialValue];
12639
12640 if(this.isFilter){
12641 this.input.value = this.initialValues ? this.initialValues.join(",") : "";
12642 this.headerFilterInitialListGen();
12643 }
12644 }
12645
12646 _onRendered(){
12647 var cellEl = this.cell.getElement();
12648
12649 function clickStop(e){
12650 e.stopPropagation();
12651 }
12652
12653 if(!this.isFilter){
12654 this.input.style.height = "100%";
12655 this.input.focus({preventScroll: true});
12656 }
12657
12658
12659 cellEl.addEventListener("click", clickStop);
12660
12661 setTimeout(() => {
12662 cellEl.removeEventListener("click", clickStop);
12663 }, 1000);
12664
12665 this.input.addEventListener("mousedown", this._preventPopupBlur.bind(this));
12666 }
12667
12668 _createListElement(){
12669 var listEl = document.createElement("div");
12670 listEl.classList.add("tabulator-edit-list");
12671
12672 listEl.addEventListener("mousedown", this._preventBlur.bind(this));
12673 listEl.addEventListener("keydown", this._inputKeyDown.bind(this));
12674
12675 return listEl;
12676 }
12677
12678 _setListWidth(){
12679 var element = this.isFilter ? this.input : this.cell.getElement();
12680
12681 this.listEl.style.minWidth = element.offsetWidth + "px";
12682
12683 if(this.params.maxWidth){
12684 if(this.params.maxWidth === true){
12685 this.listEl.style.maxWidth = element.offsetWidth + "px";
12686 }else if(typeof this.params.maxWidth === "number"){
12687 this.listEl.style.maxWidth = this.params.maxWidth + "px";
12688 }else {
12689 this.listEl.style.maxWidth = this.params.maxWidth;
12690 }
12691 }
12692
12693 }
12694
12695 _createInputElement(){
12696 var attribs = this.params.elementAttributes;
12697 var input = document.createElement("input");
12698
12699 input.setAttribute("type", this.params.clearable ? "search" : "text");
12700
12701 input.style.padding = "4px";
12702 input.style.width = "100%";
12703 input.style.boxSizing = "border-box";
12704
12705 if(!this.params.autocomplete){
12706 input.style.cursor = "default";
12707 input.style.caretColor = "transparent";
12708 // input.readOnly = (this.edit.currentCell != false);
12709 }
12710
12711 if(attribs && typeof attribs == "object"){
12712 for (let key in attribs){
12713 if(key.charAt(0) == "+"){
12714 key = key.slice(1);
12715 input.setAttribute(key, input.getAttribute(key) + attribs["+" + key]);
12716 }else {
12717 input.setAttribute(key, attribs[key]);
12718 }
12719 }
12720 }
12721
12722 if(this.params.mask){
12723 maskInput(input, this.params);
12724 }
12725
12726 this._bindInputEvents(input);
12727
12728 return input;
12729 }
12730
12731 _initializeParams(params){
12732 var valueKeys = ["values", "valuesURL", "valuesLookup"],
12733 valueCheck;
12734
12735 params = Object.assign({}, params);
12736
12737 params.verticalNavigation = params.verticalNavigation || "editor";
12738 params.placeholderLoading = typeof params.placeholderLoading === "undefined" ? "Searching ..." : params.placeholderLoading;
12739 params.placeholderEmpty = typeof params.placeholderEmpty === "undefined" ? "No Results Found" : params.placeholderEmpty;
12740 params.filterDelay = typeof params.filterDelay === "undefined" ? 300 : params.filterDelay;
12741
12742 params.emptyValue = Object.keys(params).includes("emptyValue") ? params.emptyValue : "";
12743
12744 valueCheck = Object.keys(params).filter(key => valueKeys.includes(key)).length;
12745
12746 if(!valueCheck){
12747 console.warn("list editor config error - either the values, valuesURL, or valuesLookup option must be set");
12748 }else if(valueCheck > 1){
12749 console.warn("list editor config error - only one of the values, valuesURL, or valuesLookup options can be set on the same editor");
12750 }
12751
12752 if(params.autocomplete){
12753 if(params.multiselect){
12754 params.multiselect = false;
12755 console.warn("list editor config error - multiselect option is not available when autocomplete is enabled");
12756 }
12757 }else {
12758 if(params.freetext){
12759 params.freetext = false;
12760 console.warn("list editor config error - freetext option is only available when autocomplete is enabled");
12761 }
12762
12763 if(params.filterFunc){
12764 params.filterFunc = false;
12765 console.warn("list editor config error - filterFunc option is only available when autocomplete is enabled");
12766 }
12767
12768 if(params.filterRemote){
12769 params.filterRemote = false;
12770 console.warn("list editor config error - filterRemote option is only available when autocomplete is enabled");
12771 }
12772
12773 if(params.mask){
12774 params.mask = false;
12775 console.warn("list editor config error - mask option is only available when autocomplete is enabled");
12776 }
12777
12778 if(params.allowEmpty){
12779 params.allowEmpty = false;
12780 console.warn("list editor config error - allowEmpty option is only available when autocomplete is enabled");
12781 }
12782
12783 if(params.listOnEmpty){
12784 params.listOnEmpty = false;
12785 console.warn("list editor config error - listOnEmpty option is only available when autocomplete is enabled");
12786 }
12787 }
12788
12789 if(params.filterRemote && !(typeof params.valuesLookup === "function" || params.valuesURL)){
12790 params.filterRemote = false;
12791 console.warn("list editor config error - filterRemote option should only be used when values list is populated from a remote source");
12792 }
12793 return params;
12794 }
12795 //////////////////////////////////////
12796 ////////// Event Handling ////////////
12797 //////////////////////////////////////
12798
12799 _bindInputEvents(input){
12800 input.addEventListener("focus", this._inputFocus.bind(this));
12801 input.addEventListener("click", this._inputClick.bind(this));
12802 input.addEventListener("blur", this._inputBlur.bind(this));
12803 input.addEventListener("keydown", this._inputKeyDown.bind(this));
12804 input.addEventListener("search", this._inputSearch.bind(this));
12805
12806 if(this.params.autocomplete){
12807 input.addEventListener("keyup", this._inputKeyUp.bind(this));
12808 }
12809 }
12810
12811
12812 _inputFocus(e){
12813 this.rebuildOptionsList();
12814 }
12815
12816 _filter(){
12817 if(this.params.filterRemote){
12818 clearTimeout(this.filterTimeout);
12819
12820 this.filterTimeout = setTimeout(() => {
12821 this.rebuildOptionsList();
12822 }, this.params.filterDelay);
12823 }else {
12824 this._filterList();
12825 }
12826 }
12827
12828 _inputClick(e){
12829 e.stopPropagation();
12830 }
12831
12832 _inputBlur(e){
12833 if(this.blurable){
12834 if(this.popup){
12835 this.popup.hide();
12836 }else {
12837 this._resolveValue(true);
12838 }
12839 }
12840 }
12841
12842 _inputSearch(){
12843 this._clearChoices();
12844 }
12845
12846 _inputKeyDown(e){
12847 switch(e.keyCode){
12848
12849 case 38: //up arrow
12850 this._keyUp(e);
12851 break;
12852
12853 case 40: //down arrow
12854 this._keyDown(e);
12855 break;
12856
12857 case 37: //left arrow
12858 case 39: //right arrow
12859 this._keySide(e);
12860 break;
12861
12862 case 13: //enter
12863 this._keyEnter();
12864 break;
12865
12866 case 27: //escape
12867 this._keyEsc();
12868 break;
12869
12870 case 36: //home
12871 case 35: //end
12872 this._keyHomeEnd(e);
12873 break;
12874
12875 case 9: //tab
12876 this._keyTab(e);
12877 break;
12878
12879 default:
12880 this._keySelectLetter(e);
12881 }
12882 }
12883
12884 _inputKeyUp(e){
12885 switch(e.keyCode){
12886 case 38: //up arrow
12887 case 37: //left arrow
12888 case 39: //up arrow
12889 case 40: //right arrow
12890 case 13: //enter
12891 case 27: //escape
12892 break;
12893
12894 default:
12895 this._keyAutoCompLetter(e);
12896 }
12897 }
12898
12899 _preventPopupBlur(){
12900 if(this.popup){
12901 this.popup.blockHide();
12902 }
12903
12904 setTimeout(() =>{
12905 if(this.popup){
12906 this.popup.restoreHide();
12907 }
12908 }, 10);
12909 }
12910
12911 _preventBlur(){
12912 this.blurable = false;
12913
12914 setTimeout(() =>{
12915 this.blurable = true;
12916 }, 10);
12917 }
12918
12919 //////////////////////////////////////
12920 //////// Keyboard Navigation /////////
12921 //////////////////////////////////////
12922
12923 _keyTab(e){
12924 if(this.params.autocomplete && this.lastAction === "typing"){
12925 this._resolveValue(true);
12926 }else {
12927 if(this.focusedItem){
12928 this._chooseItem(this.focusedItem, true);
12929 }
12930 }
12931 }
12932
12933 _keyUp(e){
12934 var index = this.displayItems.indexOf(this.focusedItem);
12935
12936 if(this.params.verticalNavigation == "editor" || (this.params.verticalNavigation == "hybrid" && index)){
12937 e.stopImmediatePropagation();
12938 e.stopPropagation();
12939 e.preventDefault();
12940
12941 if(index > 0){
12942 this._focusItem(this.displayItems[index - 1]);
12943 }
12944 }
12945 }
12946
12947 _keyDown(e){
12948 var index = this.displayItems.indexOf(this.focusedItem);
12949
12950 if(this.params.verticalNavigation == "editor" || (this.params.verticalNavigation == "hybrid" && index < this.displayItems.length - 1)){
12951 e.stopImmediatePropagation();
12952 e.stopPropagation();
12953 e.preventDefault();
12954
12955 if(index < this.displayItems.length - 1){
12956 if(index == -1){
12957 this._focusItem(this.displayItems[0]);
12958 }else {
12959 this._focusItem(this.displayItems[index + 1]);
12960 }
12961 }
12962 }
12963 }
12964
12965 _keySide(e){
12966 if(!this.params.autocomplete){
12967 e.stopImmediatePropagation();
12968 e.stopPropagation();
12969 e.preventDefault();
12970 }
12971 }
12972
12973 _keyEnter(e){
12974 if(this.params.autocomplete && this.lastAction === "typing"){
12975 this._resolveValue(true);
12976 }else {
12977 if(this.focusedItem){
12978 this._chooseItem(this.focusedItem);
12979 }
12980 }
12981 }
12982
12983 _keyEsc(e){
12984 this._cancel();
12985 }
12986
12987 _keyHomeEnd(e){
12988 if(this.params.autocomplete){
12989 //prevent table navigation while using input element
12990 e.stopImmediatePropagation();
12991 }
12992 }
12993
12994 _keySelectLetter(e){
12995 if(!this.params.autocomplete){
12996 // if(this.edit.currentCell === false){
12997 e.preventDefault();
12998 // }
12999
13000 if(e.keyCode >= 38 && e.keyCode <= 90){
13001 this._scrollToValue(e.keyCode);
13002 }
13003 }
13004 }
13005
13006 _keyAutoCompLetter(e){
13007 this._filter();
13008 this.lastAction = "typing";
13009 this.typing = true;
13010 }
13011
13012
13013 _scrollToValue(char){
13014 clearTimeout(this.filterTimeout);
13015
13016 var character = String.fromCharCode(char).toLowerCase();
13017 this.filterTerm += character.toLowerCase();
13018
13019 var match = this.displayItems.find((item) => {
13020 return typeof item.label !== "undefined" && item.label.toLowerCase().startsWith(this.filterTerm);
13021 });
13022
13023 if(match){
13024 this._focusItem(match);
13025 }
13026
13027 this.filterTimeout = setTimeout(() => {
13028 this.filterTerm = "";
13029 }, 800);
13030 }
13031
13032 _focusItem(item){
13033 this.lastAction = "focus";
13034
13035 if(this.focusedItem && this.focusedItem.element){
13036 this.focusedItem.element.classList.remove("focused");
13037 }
13038
13039 this.focusedItem = item;
13040
13041 if(item && item.element){
13042 item.element.classList.add("focused");
13043 item.element.scrollIntoView({behavior: 'smooth', block: 'nearest', inline: 'start'});
13044 }
13045 }
13046
13047
13048 //////////////////////////////////////
13049 /////// Data List Generation /////////
13050 //////////////////////////////////////
13051 headerFilterInitialListGen(){
13052 this._generateOptions(true);
13053 }
13054
13055 rebuildOptionsList(){
13056 this._generateOptions()
13057 .then(this._sortOptions.bind(this))
13058 .then(this._buildList.bind(this))
13059 .then(this._showList.bind(this))
13060 .catch((e) => {
13061 if(!Number.isInteger(e)){
13062 console.error("List generation error", e);
13063 }
13064 });
13065 }
13066
13067 _filterList(){
13068 this._buildList(this._filterOptions());
13069 this._showList();
13070 }
13071
13072 _generateOptions(silent){
13073 var values = [];
13074 var iteration = ++ this.listIteration;
13075
13076 this.filtered = false;
13077
13078 if(this.params.values){
13079 values = this.params.values;
13080 }else if (this.params.valuesURL){
13081 values = this._ajaxRequest(this.params.valuesURL, this.input.value);
13082 }else {
13083 if(typeof this.params.valuesLookup === "function"){
13084 values = this.params.valuesLookup(this.cell, this.input.value);
13085 }else if(this.params.valuesLookup){
13086 values = this._uniqueColumnValues(this.params.valuesLookupField);
13087 }
13088 }
13089
13090 if(values instanceof Promise){
13091 if(!silent){
13092 this._addPlaceholder(this.params.placeholderLoading);
13093 }
13094
13095 return values.then()
13096 .then((responseValues) => {
13097 if(this.listIteration === iteration){
13098 return this._parseList(responseValues);
13099 }else {
13100 return Promise.reject(iteration);
13101 }
13102 });
13103 }else {
13104 return Promise.resolve(this._parseList(values));
13105 }
13106 }
13107
13108 _addPlaceholder(contents){
13109 var placeholder = document.createElement("div");
13110
13111 if(typeof contents === "function"){
13112 contents = contents(this.cell.getComponent(), this.listEl);
13113 }
13114
13115 if(contents){
13116 this._clearList();
13117
13118 if(contents instanceof HTMLElement){
13119 placeholder = contents;
13120 }else {
13121 placeholder.classList.add("tabulator-edit-list-placeholder");
13122 placeholder.innerHTML = contents;
13123 }
13124
13125 this.listEl.appendChild(placeholder);
13126
13127 this._showList();
13128 }
13129 }
13130
13131 _ajaxRequest(url, term){
13132 var params = this.params.filterRemote ? {term:term} : {};
13133 url = urlBuilder(url, {}, params);
13134
13135 return fetch(url)
13136 .then((response)=>{
13137 if(response.ok) {
13138 return response.json()
13139 .catch((error)=>{
13140 console.warn("List Ajax Load Error - Invalid JSON returned", error);
13141 return Promise.reject(error);
13142 });
13143 }else {
13144 console.error("List Ajax Load Error - Connection Error: " + response.status, response.statusText);
13145 return Promise.reject(response);
13146 }
13147 })
13148 .catch((error)=>{
13149 console.error("List Ajax Load Error - Connection Error: ", error);
13150 return Promise.reject(error);
13151 });
13152 }
13153
13154 _uniqueColumnValues(field){
13155 var output = {},
13156 data = this.table.getData(this.params.valuesLookup),
13157 column;
13158
13159 if(field){
13160 column = this.table.columnManager.getColumnByField(field);
13161 }else {
13162 column = this.cell.getColumn()._getSelf();
13163 }
13164
13165 if(column){
13166 data.forEach((row) => {
13167 var val = column.getFieldValue(row);
13168
13169 if(!this._emptyValueCheck(val)){
13170 if(this.params.multiselect && Array.isArray(val)){
13171 val.forEach((item) => {
13172 if(!this._emptyValueCheck(item)){
13173 output[item] = true;
13174 }
13175 });
13176 }else {
13177 output[val] = true;
13178 }
13179
13180 }
13181 });
13182 }else {
13183 console.warn("unable to find matching column to create select lookup list:", field);
13184 output = [];
13185 }
13186
13187 return Object.keys(output);
13188 }
13189
13190 _emptyValueCheck(value){
13191 return value === null || typeof value === "undefined" || value === "";
13192 }
13193
13194 _parseList(inputValues){
13195 var data = [];
13196
13197 if(!Array.isArray(inputValues)){
13198 inputValues = Object.entries(inputValues).map(([key, value]) => {
13199 return {
13200 label:value,
13201 value:key,
13202 };
13203 });
13204 }
13205
13206 inputValues.forEach((value) => {
13207 if(typeof value !== "object"){
13208 value = {
13209 label:value,
13210 value:value,
13211 };
13212 }
13213
13214 this._parseListItem(value, data, 0);
13215 });
13216
13217 if(!this.currentItems.length && this.params.freetext){
13218 this.input.value = this.initialValues;
13219 this.typing = true;
13220 this.lastAction = "typing";
13221 }
13222
13223 this.data = data;
13224
13225 return data;
13226 }
13227
13228 _parseListItem(option, data, level){
13229 var item = {};
13230
13231 if(option.options){
13232 item = this._parseListGroup(option, level + 1);
13233 }else {
13234 item = {
13235 label:option.label,
13236 value:option.value,
13237 itemParams:option.itemParams,
13238 elementAttributes: option.elementAttributes,
13239 element:false,
13240 selected:false,
13241 visible:true,
13242 level:level,
13243 original:option,
13244 };
13245
13246 if(this.initialValues && this.initialValues.indexOf(option.value) > -1){
13247 this._chooseItem(item, true);
13248 }
13249 }
13250
13251 data.push(item);
13252 }
13253
13254 _parseListGroup(option, level){
13255 var item = {
13256 label:option.label,
13257 group:true,
13258 itemParams:option.itemParams,
13259 elementAttributes:option.elementAttributes,
13260 element:false,
13261 visible:true,
13262 level:level,
13263 options:[],
13264 original:option,
13265 };
13266
13267 option.options.forEach((child) => {
13268 this._parseListItem(child, item.options, level);
13269 });
13270
13271 return item;
13272 }
13273
13274 _sortOptions(options){
13275 var sorter;
13276
13277 if(this.params.sort){
13278 sorter = typeof this.params.sort === "function" ? this.params.sort : this._defaultSortFunction.bind(this);
13279
13280 this._sortGroup(sorter, options);
13281 }
13282
13283 return options;
13284 }
13285
13286 _sortGroup(sorter, options){
13287 options.sort((a,b) => {
13288 return sorter(a.label, b.label, a.value, b.value, a.original, b.original);
13289 });
13290
13291 options.forEach((option) => {
13292 if(option.group){
13293 this._sortGroup(sorter, option.options);
13294 }
13295 });
13296 }
13297
13298 _defaultSortFunction(as, bs){
13299 var a, b, a1, b1, i= 0, L, rx = /(\d+)|(\D+)/g, rd = /\d/;
13300 var emptyAlign = 0;
13301
13302 if(this.params.sort === "desc"){
13303 [as, bs] = [bs, as];
13304 }
13305
13306 //handle empty values
13307 if(!as && as!== 0){
13308 emptyAlign = !bs && bs!== 0 ? 0 : -1;
13309 }else if(!bs && bs!== 0){
13310 emptyAlign = 1;
13311 }else {
13312 if(isFinite(as) && isFinite(bs)) return as - bs;
13313 a = String(as).toLowerCase();
13314 b = String(bs).toLowerCase();
13315 if(a === b) return 0;
13316 if(!(rd.test(a) && rd.test(b))) return a > b ? 1 : -1;
13317 a = a.match(rx);
13318 b = b.match(rx);
13319 L = a.length > b.length ? b.length : a.length;
13320 while(i < L){
13321 a1= a[i];
13322 b1= b[i++];
13323 if(a1 !== b1){
13324 if(isFinite(a1) && isFinite(b1)){
13325 if(a1.charAt(0) === "0") a1 = "." + a1;
13326 if(b1.charAt(0) === "0") b1 = "." + b1;
13327 return a1 - b1;
13328 }
13329 else return a1 > b1 ? 1 : -1;
13330 }
13331 }
13332
13333 return a.length > b.length;
13334 }
13335
13336 return emptyAlign;
13337 }
13338
13339 _filterOptions(){
13340 var filterFunc = this.params.filterFunc || this._defaultFilterFunc,
13341 term = this.input.value;
13342
13343 if(term){
13344 this.filtered = true;
13345
13346 this.data.forEach((item) => {
13347 this._filterItem(filterFunc, term, item);
13348 });
13349 }else {
13350 this.filtered = false;
13351 }
13352
13353 return this.data;
13354 }
13355
13356 _filterItem(func, term, item){
13357 var matches = false;
13358
13359 if(!item.group){
13360 item.visible = func(term, item.label, item.value, item.original);
13361 }else {
13362 item.options.forEach((option) => {
13363 if(this._filterItem(func, term, option)){
13364 matches = true;
13365 }
13366 });
13367
13368 item.visible = matches;
13369 }
13370
13371 return item.visible;
13372 }
13373
13374 _defaultFilterFunc(term, label, value, item){
13375 term = String(term).toLowerCase();
13376
13377 if(label !== null && typeof label !== "undefined"){
13378 if(String(label).toLowerCase().indexOf(term) > -1 || String(value).toLowerCase().indexOf(term) > -1){
13379 return true;
13380 }
13381 }
13382
13383 return false;
13384 }
13385
13386 //////////////////////////////////////
13387 /////////// Display List /////////////
13388 //////////////////////////////////////
13389
13390 _clearList(){
13391 while(this.listEl.firstChild) this.listEl.removeChild(this.listEl.firstChild);
13392
13393 this.displayItems = [];
13394 }
13395
13396 _buildList(data){
13397 this._clearList();
13398
13399 data.forEach((option) => {
13400 this._buildItem(option);
13401 });
13402
13403 if(!this.displayItems.length){
13404 this._addPlaceholder(this.params.placeholderEmpty);
13405 }
13406 }
13407
13408 _buildItem(item){
13409 var el = item.element,
13410 contents;
13411
13412 if(!this.filtered || item.visible){
13413
13414 if(!el){
13415 el = document.createElement("div");
13416 el.tabIndex = 0;
13417
13418 contents = this.params.itemFormatter ? this.params.itemFormatter(item.label, item.value, item.original, el) : item.label;
13419
13420 if(contents instanceof HTMLElement){
13421 el.appendChild(contents);
13422 }else {
13423 el.innerHTML = contents;
13424 }
13425
13426 if(item.group){
13427 el.classList.add("tabulator-edit-list-group");
13428 }else {
13429 el.classList.add("tabulator-edit-list-item");
13430 }
13431
13432 el.classList.add("tabulator-edit-list-group-level-" + item.level);
13433
13434 if(item.elementAttributes && typeof item.elementAttributes == "object"){
13435 for (let key in item.elementAttributes){
13436 if(key.charAt(0) == "+"){
13437 key = key.slice(1);
13438 el.setAttribute(key, this.input.getAttribute(key) + item.elementAttributes["+" + key]);
13439 }else {
13440 el.setAttribute(key, item.elementAttributes[key]);
13441 }
13442 }
13443 }
13444
13445 if(item.group){
13446 el.addEventListener("click", this._groupClick.bind(this, item));
13447 }else {
13448 el.addEventListener("click", this._itemClick.bind(this, item));
13449 }
13450
13451 el.addEventListener("mousedown", this._preventBlur.bind(this));
13452
13453 item.element = el;
13454 }
13455
13456 this._styleItem(item);
13457
13458 this.listEl.appendChild(el);
13459
13460 if(item.group){
13461 item.options.forEach((option) => {
13462 this._buildItem(option);
13463 });
13464 }else {
13465 this.displayItems.push(item);
13466 }
13467 }
13468 }
13469
13470 _showList(){
13471 var startVis = this.popup && this.popup.isVisible();
13472
13473 if(this.input.parentNode){
13474 if(this.params.autocomplete && this.input.value === "" && !this.params.listOnEmpty){
13475 if(this.popup){
13476 this.popup.hide(true);
13477 }
13478 return;
13479 }
13480
13481 this._setListWidth();
13482
13483 if(!this.popup){
13484 this.popup = this.edit.popup(this.listEl);
13485 }
13486
13487 this.popup.show(this.cell.getElement(), "bottom");
13488
13489 if(!startVis){
13490 setTimeout(() => {
13491 this.popup.hideOnBlur(this._resolveValue.bind(this, true));
13492 }, 10);
13493 }
13494 }
13495 }
13496
13497 _styleItem(item){
13498 if(item && item.element){
13499 if(item.selected){
13500 item.element.classList.add("active");
13501 }else {
13502 item.element.classList.remove("active");
13503 }
13504 }
13505 }
13506
13507 //////////////////////////////////////
13508 ///////// User Interaction ///////////
13509 //////////////////////////////////////
13510
13511 _itemClick(item, e){
13512 e.stopPropagation();
13513
13514 this._chooseItem(item);
13515 }
13516
13517 _groupClick(item, e){
13518 e.stopPropagation();
13519 }
13520
13521
13522 //////////////////////////////////////
13523 ////// Current Item Management ///////
13524 //////////////////////////////////////
13525
13526 _cancel(){
13527 this.popup.hide(true);
13528 this.actions.cancel();
13529 }
13530
13531 _clearChoices(){
13532 this.typing = true;
13533
13534 this.currentItems.forEach((item) => {
13535 item.selected = false;
13536 this._styleItem(item);
13537 });
13538
13539 this.currentItems = [];
13540
13541 this.focusedItem = null;
13542 }
13543
13544 _chooseItem(item, silent){
13545 var index;
13546
13547 this.typing = false;
13548
13549 if(this.params.multiselect){
13550 index = this.currentItems.indexOf(item);
13551
13552 if(index > -1){
13553 this.currentItems.splice(index, 1);
13554 item.selected = false;
13555 }else {
13556 this.currentItems.push(item);
13557 item.selected = true;
13558 }
13559
13560 this.input.value = this.currentItems.map(item => item.label).join(",");
13561
13562 this._styleItem(item);
13563
13564 }else {
13565 this.currentItems = [item];
13566 item.selected = true;
13567
13568 this.input.value = item.label;
13569
13570 this._styleItem(item);
13571
13572 if(!silent){
13573 this._resolveValue();
13574 }
13575 }
13576
13577 this._focusItem(item);
13578 }
13579
13580 _resolveValue(blur){
13581 var output, initialValue;
13582
13583 if(this.popup){
13584 this.popup.hide(true);
13585 }
13586
13587 if(this.params.multiselect){
13588 output = this.currentItems.map(item => item.value);
13589 }else {
13590 if(blur && this.params.autocomplete && this.typing){
13591 if(this.params.freetext || (this.params.allowEmpty && this.input.value === "")){
13592 output = this.input.value;
13593 }else {
13594 this.actions.cancel();
13595 return;
13596 }
13597 }else {
13598 if(this.currentItems[0]){
13599 output = this.currentItems[0].value;
13600 }else {
13601 initialValue = Array.isArray(this.initialValues) ? this.initialValues[0] : this.initialValues;
13602
13603 if(initialValue === null || typeof initialValue === "undefined" || initialValue === ""){
13604 output = initialValue;
13605 }else {
13606 output = this.params.emptyValue;
13607 }
13608 }
13609
13610 }
13611 }
13612
13613 if(output === ""){
13614 output = this.params.emptyValue;
13615 }
13616
13617 this.actions.success(output);
13618
13619 if(this.isFilter){
13620 this.initialValues = output && !Array.isArray(output) ? [output] : output;
13621 this.currentItems = [];
13622 }
13623 }
13624
13625 };
13626
13627 function list(cell, onRendered, success, cancel, editorParams){
13628 var list = new Edit$1(this, cell, onRendered, success, cancel, editorParams);
13629
13630 return list.input;
13631 }
13632
13633 //star rating
13634 function star$1(cell, onRendered, success, cancel, editorParams){
13635 var self = this,
13636 element = cell.getElement(),
13637 value = cell.getValue(),
13638 maxStars = element.getElementsByTagName("svg").length || 5,
13639 size = element.getElementsByTagName("svg")[0] ? element.getElementsByTagName("svg")[0].getAttribute("width") : 14,
13640 stars = [],
13641 starsHolder = document.createElement("div"),
13642 star = document.createElementNS('http://www.w3.org/2000/svg', "svg");
13643
13644
13645 //change star type
13646 function starChange(val){
13647 stars.forEach(function(star, i){
13648 if(i < val){
13649 if(self.table.browser == "ie"){
13650 star.setAttribute("class", "tabulator-star-active");
13651 }else {
13652 star.classList.replace("tabulator-star-inactive", "tabulator-star-active");
13653 }
13654
13655 star.innerHTML = '<polygon fill="#488CE9" stroke="#014AAE" stroke-width="37.6152" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" points="259.216,29.942 330.27,173.919 489.16,197.007 374.185,309.08 401.33,467.31 259.216,392.612 117.104,467.31 144.25,309.08 29.274,197.007 188.165,173.919 "/>';
13656 }else {
13657 if(self.table.browser == "ie"){
13658 star.setAttribute("class", "tabulator-star-inactive");
13659 }else {
13660 star.classList.replace("tabulator-star-active", "tabulator-star-inactive");
13661 }
13662
13663 star.innerHTML = '<polygon fill="#010155" stroke="#686868" stroke-width="37.6152" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" points="259.216,29.942 330.27,173.919 489.16,197.007 374.185,309.08 401.33,467.31 259.216,392.612 117.104,467.31 144.25,309.08 29.274,197.007 188.165,173.919 "/>';
13664 }
13665 });
13666 }
13667
13668 //build stars
13669 function buildStar(i){
13670
13671 var starHolder = document.createElement("span");
13672 var nextStar = star.cloneNode(true);
13673
13674 stars.push(nextStar);
13675
13676 starHolder.addEventListener("mouseenter", function(e){
13677 e.stopPropagation();
13678 e.stopImmediatePropagation();
13679 starChange(i);
13680 });
13681
13682 starHolder.addEventListener("mousemove", function(e){
13683 e.stopPropagation();
13684 e.stopImmediatePropagation();
13685 });
13686
13687 starHolder.addEventListener("click", function(e){
13688 e.stopPropagation();
13689 e.stopImmediatePropagation();
13690 success(i);
13691 element.blur();
13692 });
13693
13694 starHolder.appendChild(nextStar);
13695 starsHolder.appendChild(starHolder);
13696
13697 }
13698
13699 //handle keyboard navigation value change
13700 function changeValue(val){
13701 value = val;
13702 starChange(val);
13703 }
13704
13705 //style cell
13706 element.style.whiteSpace = "nowrap";
13707 element.style.overflow = "hidden";
13708 element.style.textOverflow = "ellipsis";
13709
13710 //style holding element
13711 starsHolder.style.verticalAlign = "middle";
13712 starsHolder.style.display = "inline-block";
13713 starsHolder.style.padding = "4px";
13714
13715 //style star
13716 star.setAttribute("width", size);
13717 star.setAttribute("height", size);
13718 star.setAttribute("viewBox", "0 0 512 512");
13719 star.setAttribute("xml:space", "preserve");
13720 star.style.padding = "0 1px";
13721
13722 if(editorParams.elementAttributes && typeof editorParams.elementAttributes == "object"){
13723 for (let key in editorParams.elementAttributes){
13724 if(key.charAt(0) == "+"){
13725 key = key.slice(1);
13726 starsHolder.setAttribute(key, starsHolder.getAttribute(key) + editorParams.elementAttributes["+" + key]);
13727 }else {
13728 starsHolder.setAttribute(key, editorParams.elementAttributes[key]);
13729 }
13730 }
13731 }
13732
13733 //create correct number of stars
13734 for(var i=1;i<= maxStars;i++){
13735 buildStar(i);
13736 }
13737
13738 //ensure value does not exceed number of stars
13739 value = Math.min(parseInt(value), maxStars);
13740
13741 // set initial styling of stars
13742 starChange(value);
13743
13744 starsHolder.addEventListener("mousemove", function(e){
13745 starChange(0);
13746 });
13747
13748 starsHolder.addEventListener("click", function(e){
13749 success(0);
13750 });
13751
13752 element.addEventListener("blur", function(e){
13753 cancel();
13754 });
13755
13756 //allow key based navigation
13757 element.addEventListener("keydown", function(e){
13758 switch(e.keyCode){
13759 case 39: //right arrow
13760 changeValue(value + 1);
13761 break;
13762
13763 case 37: //left arrow
13764 changeValue(value - 1);
13765 break;
13766
13767 case 13: //enter
13768 success(value);
13769 break;
13770
13771 case 27: //escape
13772 cancel();
13773 break;
13774 }
13775 });
13776
13777 return starsHolder;
13778 }
13779
13780 //draggable progress bar
13781 function progress$1(cell, onRendered, success, cancel, editorParams){
13782 var element = cell.getElement(),
13783 max = typeof editorParams.max === "undefined" ? ((element.getElementsByTagName("div")[0] && element.getElementsByTagName("div")[0].getAttribute("max")) || 100) : editorParams.max,
13784 min = typeof editorParams.min === "undefined" ? ((element.getElementsByTagName("div")[0] && element.getElementsByTagName("div")[0].getAttribute("min")) || 0) : editorParams.min,
13785 percent = (max - min) / 100,
13786 value = cell.getValue() || 0,
13787 handle = document.createElement("div"),
13788 bar = document.createElement("div"),
13789 mouseDrag, mouseDragWidth;
13790
13791 //set new value
13792 function updateValue(){
13793 var style = window.getComputedStyle(element, null);
13794
13795 var calcVal = (percent * Math.round(bar.offsetWidth / ((element.clientWidth - parseInt(style.getPropertyValue("padding-left")) - parseInt(style.getPropertyValue("padding-right")))/100))) + min;
13796 success(calcVal);
13797 element.setAttribute("aria-valuenow", calcVal);
13798 element.setAttribute("aria-label", value);
13799 }
13800
13801 //style handle
13802 handle.style.position = "absolute";
13803 handle.style.right = "0";
13804 handle.style.top = "0";
13805 handle.style.bottom = "0";
13806 handle.style.width = "5px";
13807 handle.classList.add("tabulator-progress-handle");
13808
13809 //style bar
13810 bar.style.display = "inline-block";
13811 bar.style.position = "relative";
13812 // bar.style.top = "8px";
13813 // bar.style.bottom = "8px";
13814 // bar.style.left = "4px";
13815 // bar.style.marginRight = "4px";
13816 bar.style.height = "100%";
13817 bar.style.backgroundColor = "#488CE9";
13818 bar.style.maxWidth = "100%";
13819 bar.style.minWidth = "0%";
13820
13821 if(editorParams.elementAttributes && typeof editorParams.elementAttributes == "object"){
13822 for (let key in editorParams.elementAttributes){
13823 if(key.charAt(0) == "+"){
13824 key = key.slice(1);
13825 bar.setAttribute(key, bar.getAttribute(key) + editorParams.elementAttributes["+" + key]);
13826 }else {
13827 bar.setAttribute(key, editorParams.elementAttributes[key]);
13828 }
13829 }
13830 }
13831
13832 //style cell
13833 element.style.padding = "4px 4px";
13834
13835 //make sure value is in range
13836 value = Math.min(parseFloat(value), max);
13837 value = Math.max(parseFloat(value), min);
13838
13839 //workout percentage
13840 value = Math.round((value - min) / percent);
13841 // bar.style.right = value + "%";
13842 bar.style.width = value + "%";
13843
13844 element.setAttribute("aria-valuemin", min);
13845 element.setAttribute("aria-valuemax", max);
13846
13847 bar.appendChild(handle);
13848
13849 handle.addEventListener("mousedown", function(e){
13850 mouseDrag = e.screenX;
13851 mouseDragWidth = bar.offsetWidth;
13852 });
13853
13854 handle.addEventListener("mouseover", function(){
13855 handle.style.cursor = "ew-resize";
13856 });
13857
13858 element.addEventListener("mousemove", function(e){
13859 if(mouseDrag){
13860 bar.style.width = (mouseDragWidth + e.screenX - mouseDrag) + "px";
13861 }
13862 });
13863
13864 element.addEventListener("mouseup", function(e){
13865 if(mouseDrag){
13866 e.stopPropagation();
13867 e.stopImmediatePropagation();
13868
13869 mouseDrag = false;
13870 mouseDragWidth = false;
13871
13872 updateValue();
13873 }
13874 });
13875
13876 //allow key based navigation
13877 element.addEventListener("keydown", function(e){
13878 switch(e.keyCode){
13879 case 39: //right arrow
13880 e.preventDefault();
13881 bar.style.width = (bar.clientWidth + element.clientWidth/100) + "px";
13882 break;
13883
13884 case 37: //left arrow
13885 e.preventDefault();
13886 bar.style.width = (bar.clientWidth - element.clientWidth/100) + "px";
13887 break;
13888
13889 case 9: //tab
13890 case 13: //enter
13891 updateValue();
13892 break;
13893
13894 case 27: //escape
13895 cancel();
13896 break;
13897
13898 }
13899 });
13900
13901 element.addEventListener("blur", function(){
13902 cancel();
13903 });
13904
13905 return bar;
13906 }
13907
13908 //checkbox
13909 function tickCross$1(cell, onRendered, success, cancel, editorParams){
13910 var value = cell.getValue(),
13911 input = document.createElement("input"),
13912 tristate = editorParams.tristate,
13913 indetermValue = typeof editorParams.indeterminateValue === "undefined" ? null : editorParams.indeterminateValue,
13914 indetermState = false,
13915 trueValueSet = Object.keys(editorParams).includes("trueValue"),
13916 falseValueSet = Object.keys(editorParams).includes("falseValue");
13917
13918 input.setAttribute("type", "checkbox");
13919 input.style.marginTop = "5px";
13920 input.style.boxSizing = "border-box";
13921
13922 if(editorParams.elementAttributes && typeof editorParams.elementAttributes == "object"){
13923 for (let key in editorParams.elementAttributes){
13924 if(key.charAt(0) == "+"){
13925 key = key.slice(1);
13926 input.setAttribute(key, input.getAttribute(key) + editorParams.elementAttributes["+" + key]);
13927 }else {
13928 input.setAttribute(key, editorParams.elementAttributes[key]);
13929 }
13930 }
13931 }
13932
13933 input.value = value;
13934
13935 if(tristate && (typeof value === "undefined" || value === indetermValue || value === "")){
13936 indetermState = true;
13937 input.indeterminate = true;
13938 }
13939
13940 if(this.table.browser != "firefox" && this.table.browser != "safari"){ //prevent blur issue on mac firefox
13941 onRendered(function(){
13942 if(cell.getType() === "cell"){
13943 input.focus({preventScroll: true});
13944 }
13945 });
13946 }
13947
13948 input.checked = trueValueSet ? value === editorParams.trueValue : (value === true || value === "true" || value === "True" || value === 1);
13949
13950 function setValue(blur){
13951 var checkedValue = input.checked;
13952
13953 if(trueValueSet && checkedValue){
13954 checkedValue = editorParams.trueValue;
13955 }else if(falseValueSet && !checkedValue){
13956 checkedValue = editorParams.falseValue;
13957 }
13958
13959 if(tristate){
13960 if(!blur){
13961 if(input.checked && !indetermState){
13962 input.checked = false;
13963 input.indeterminate = true;
13964 indetermState = true;
13965 return indetermValue;
13966 }else {
13967 indetermState = false;
13968 return checkedValue;
13969 }
13970 }else {
13971 if(indetermState){
13972 return indetermValue;
13973 }else {
13974 return checkedValue;
13975 }
13976 }
13977 }else {
13978 return checkedValue;
13979 }
13980 }
13981
13982 //submit new value on blur
13983 input.addEventListener("change", function(e){
13984 success(setValue());
13985 });
13986
13987 input.addEventListener("blur", function(e){
13988 success(setValue(true));
13989 });
13990
13991 //submit new value on enter
13992 input.addEventListener("keydown", function(e){
13993 if(e.keyCode == 13){
13994 success(setValue());
13995 }
13996 if(e.keyCode == 27){
13997 cancel();
13998 }
13999 });
14000
14001 return input;
14002 }
14003
14004 function adaptable$1(cell, onRendered, success, cancel, params){
14005 var column = cell._getSelf().column,
14006 lookup, editorFunc, editorParams;
14007
14008 function defaultLookup(cell){
14009 var value = cell.getValue(),
14010 editor = "input";
14011
14012 switch(typeof value){
14013 case "number":
14014 editor = "number";
14015 break;
14016
14017 case "boolean":
14018 editor = "tickCross";
14019 break;
14020
14021 case "string":
14022 if(value.includes("\n")){
14023 editor = "textarea";
14024 }
14025 break;
14026 }
14027
14028 return editor;
14029 }
14030
14031 lookup = params.editorLookup ? params.editorLookup(cell) : defaultLookup(cell);
14032
14033 if(params.paramsLookup){
14034 editorParams = typeof params.paramsLookup === "function" ? params.paramsLookup(lookup, cell) : params.paramsLookup[lookup];
14035 }
14036
14037 editorFunc = this.table.modules.edit.lookupEditor(lookup, column);
14038
14039 return editorFunc.call(this, cell, onRendered, success, cancel, editorParams || {});
14040 }
14041
14042 var defaultEditors = {
14043 input:input,
14044 textarea:textarea$1,
14045 number:number$1,
14046 range:range,
14047 date:date$1,
14048 time:time$1,
14049 datetime:datetime$2,
14050 list:list,
14051 star:star$1,
14052 progress:progress$1,
14053 tickCross:tickCross$1,
14054 adaptable:adaptable$1,
14055 };
14056
14057 class Edit extends Module{
14058
14059 static moduleName = "edit";
14060
14061 //load defaults
14062 static editors = defaultEditors;
14063
14064 constructor(table){
14065 super(table);
14066
14067 this.currentCell = false; //hold currently editing cell
14068 this.mouseClick = false; //hold mousedown state to prevent click binding being overridden by editor opening
14069 this.recursionBlock = false; //prevent focus recursion
14070 this.invalidEdit = false;
14071 this.editedCells = [];
14072 this.convertEmptyValues = false;
14073
14074 this.editors = Edit.editors;
14075
14076 this.registerTableOption("editTriggerEvent", "focus");
14077 this.registerTableOption("editorEmptyValue");
14078 this.registerTableOption("editorEmptyValueFunc", this.emptyValueCheck.bind(this));
14079
14080 this.registerColumnOption("editable");
14081 this.registerColumnOption("editor");
14082 this.registerColumnOption("editorParams");
14083 this.registerColumnOption("editorEmptyValue");
14084 this.registerColumnOption("editorEmptyValueFunc");
14085
14086 this.registerColumnOption("cellEditing");
14087 this.registerColumnOption("cellEdited");
14088 this.registerColumnOption("cellEditCancelled");
14089
14090 this.registerTableFunction("getEditedCells", this.getEditedCells.bind(this));
14091 this.registerTableFunction("clearCellEdited", this.clearCellEdited.bind(this));
14092 this.registerTableFunction("navigatePrev", this.navigatePrev.bind(this));
14093 this.registerTableFunction("navigateNext", this.navigateNext.bind(this));
14094 this.registerTableFunction("navigateLeft", this.navigateLeft.bind(this));
14095 this.registerTableFunction("navigateRight", this.navigateRight.bind(this));
14096 this.registerTableFunction("navigateUp", this.navigateUp.bind(this));
14097 this.registerTableFunction("navigateDown", this.navigateDown.bind(this));
14098
14099 this.registerComponentFunction("cell", "isEdited", this.cellIsEdited.bind(this));
14100 this.registerComponentFunction("cell", "clearEdited", this.clearEdited.bind(this));
14101 this.registerComponentFunction("cell", "edit", this.editCell.bind(this));
14102 this.registerComponentFunction("cell", "cancelEdit", this.cellCancelEdit.bind(this));
14103
14104 this.registerComponentFunction("cell", "navigatePrev", this.navigatePrev.bind(this));
14105 this.registerComponentFunction("cell", "navigateNext", this.navigateNext.bind(this));
14106 this.registerComponentFunction("cell", "navigateLeft", this.navigateLeft.bind(this));
14107 this.registerComponentFunction("cell", "navigateRight", this.navigateRight.bind(this));
14108 this.registerComponentFunction("cell", "navigateUp", this.navigateUp.bind(this));
14109 this.registerComponentFunction("cell", "navigateDown", this.navigateDown.bind(this));
14110 }
14111
14112 initialize(){
14113 this.subscribe("cell-init", this.bindEditor.bind(this));
14114 this.subscribe("cell-delete", this.clearEdited.bind(this));
14115 this.subscribe("cell-value-changed", this.updateCellClass.bind(this));
14116 this.subscribe("column-layout", this.initializeColumnCheck.bind(this));
14117 this.subscribe("column-delete", this.columnDeleteCheck.bind(this));
14118 this.subscribe("row-deleting", this.rowDeleteCheck.bind(this));
14119 this.subscribe("row-layout", this.rowEditableCheck.bind(this));
14120 this.subscribe("data-refreshing", this.cancelEdit.bind(this));
14121 this.subscribe("clipboard-paste", this.pasteBlocker.bind(this));
14122
14123 this.subscribe("keybinding-nav-prev", this.navigatePrev.bind(this, undefined));
14124 this.subscribe("keybinding-nav-next", this.keybindingNavigateNext.bind(this));
14125
14126 // this.subscribe("keybinding-nav-left", this.navigateLeft.bind(this, undefined));
14127 // this.subscribe("keybinding-nav-right", this.navigateRight.bind(this, undefined));
14128 this.subscribe("keybinding-nav-up", this.navigateUp.bind(this, undefined));
14129 this.subscribe("keybinding-nav-down", this.navigateDown.bind(this, undefined));
14130
14131 if(Object.keys(this.table.options).includes("editorEmptyValue")){
14132 this.convertEmptyValues = true;
14133 }
14134 }
14135
14136
14137 ///////////////////////////////////
14138 ///////// Paste Negation //////////
14139 ///////////////////////////////////
14140
14141 pasteBlocker(e){
14142 if(this.currentCell){
14143 return true;
14144 }
14145 }
14146
14147
14148 ///////////////////////////////////
14149 ////// Keybinding Functions ///////
14150 ///////////////////////////////////
14151
14152 keybindingNavigateNext(e){
14153 var cell = this.currentCell,
14154 newRow = this.options("tabEndNewRow");
14155
14156 if(cell){
14157 if(!this.navigateNext(cell, e)){
14158 if(newRow){
14159 cell.getElement().firstChild.blur();
14160
14161 if(!this.invalidEdit){
14162
14163 if(newRow === true){
14164 newRow = this.table.addRow({});
14165 }else {
14166 if(typeof newRow == "function"){
14167 newRow = this.table.addRow(newRow(cell.row.getComponent()));
14168 }else {
14169 newRow = this.table.addRow(Object.assign({}, newRow));
14170 }
14171 }
14172
14173 newRow.then(() => {
14174 setTimeout(() => {
14175 cell.getComponent().navigateNext();
14176 });
14177 });
14178 }
14179 }
14180 }
14181 }
14182 }
14183
14184 ///////////////////////////////////
14185 ///////// Cell Functions //////////
14186 ///////////////////////////////////
14187
14188 cellIsEdited(cell){
14189 return !! cell.modules.edit && cell.modules.edit.edited;
14190 }
14191
14192 cellCancelEdit(cell){
14193 if(cell === this.currentCell){
14194 this.table.modules.edit.cancelEdit();
14195 }else {
14196 console.warn("Cancel Editor Error - This cell is not currently being edited ");
14197 }
14198 }
14199
14200
14201 ///////////////////////////////////
14202 ///////// Table Functions /////////
14203 ///////////////////////////////////
14204 updateCellClass(cell){
14205 if(this.allowEdit(cell)) {
14206 cell.getElement().classList.add("tabulator-editable");
14207 }
14208 else {
14209 cell.getElement().classList.remove("tabulator-editable");
14210 }
14211 }
14212
14213 clearCellEdited(cells){
14214 if(!cells){
14215 cells = this.table.modules.edit.getEditedCells();
14216 }
14217
14218 if(!Array.isArray(cells)){
14219 cells = [cells];
14220 }
14221
14222 cells.forEach((cell) => {
14223 this.table.modules.edit.clearEdited(cell._getSelf());
14224 });
14225 }
14226
14227 navigatePrev(cell = this.currentCell, e){
14228 var nextCell, prevRow;
14229
14230 if(cell){
14231
14232 if(e){
14233 e.preventDefault();
14234 }
14235
14236 nextCell = this.navigateLeft();
14237
14238 if(nextCell){
14239 return true;
14240 }else {
14241 prevRow = this.table.rowManager.prevDisplayRow(cell.row, true);
14242
14243 if(prevRow){
14244 nextCell = this.findPrevEditableCell(prevRow, prevRow.cells.length);
14245
14246 if(nextCell){
14247 nextCell.getComponent().edit();
14248 return true;
14249 }
14250 }
14251 }
14252 }
14253
14254 return false;
14255 }
14256
14257 navigateNext(cell = this.currentCell, e){
14258 var nextCell, nextRow;
14259
14260 if(cell){
14261
14262 if(e){
14263 e.preventDefault();
14264 }
14265
14266 nextCell = this.navigateRight();
14267
14268 if(nextCell){
14269 return true;
14270 }else {
14271 nextRow = this.table.rowManager.nextDisplayRow(cell.row, true);
14272
14273 if(nextRow){
14274 nextCell = this.findNextEditableCell(nextRow, -1);
14275
14276 if(nextCell){
14277 nextCell.getComponent().edit();
14278 return true;
14279 }
14280 }
14281 }
14282 }
14283
14284 return false;
14285 }
14286
14287 navigateLeft(cell = this.currentCell, e){
14288 var index, nextCell;
14289
14290 if(cell){
14291
14292 if(e){
14293 e.preventDefault();
14294 }
14295
14296 index = cell.getIndex();
14297 nextCell = this.findPrevEditableCell(cell.row, index);
14298
14299 if(nextCell){
14300 nextCell.getComponent().edit();
14301 return true;
14302 }
14303 }
14304
14305 return false;
14306 }
14307
14308 navigateRight(cell = this.currentCell, e){
14309 var index, nextCell;
14310
14311 if(cell){
14312
14313 if(e){
14314 e.preventDefault();
14315 }
14316
14317 index = cell.getIndex();
14318 nextCell = this.findNextEditableCell(cell.row, index);
14319
14320 if(nextCell){
14321 nextCell.getComponent().edit();
14322 return true;
14323 }
14324 }
14325
14326 return false;
14327 }
14328
14329 navigateUp(cell = this.currentCell, e){
14330 var index, nextRow;
14331
14332 if(cell){
14333
14334 if(e){
14335 e.preventDefault();
14336 }
14337
14338 index = cell.getIndex();
14339 nextRow = this.table.rowManager.prevDisplayRow(cell.row, true);
14340
14341 if(nextRow){
14342 nextRow.cells[index].getComponent().edit();
14343 return true;
14344 }
14345 }
14346
14347 return false;
14348 }
14349
14350 navigateDown(cell = this.currentCell, e){
14351 var index, nextRow;
14352
14353 if(cell){
14354
14355 if(e){
14356 e.preventDefault();
14357 }
14358
14359 index = cell.getIndex();
14360 nextRow = this.table.rowManager.nextDisplayRow(cell.row, true);
14361
14362 if(nextRow){
14363 nextRow.cells[index].getComponent().edit();
14364 return true;
14365 }
14366 }
14367
14368 return false;
14369 }
14370
14371 findNextEditableCell(row, index){
14372 var nextCell = false;
14373
14374 if(index < row.cells.length-1){
14375 for(var i = index+1; i < row.cells.length; i++){
14376 let cell = row.cells[i];
14377
14378 if(cell.column.modules.edit && Helpers.elVisible(cell.getElement())){
14379 let allowEdit = this.allowEdit(cell);
14380
14381 if(allowEdit){
14382 nextCell = cell;
14383 break;
14384 }
14385 }
14386 }
14387 }
14388
14389 return nextCell;
14390 }
14391
14392 findPrevEditableCell(row, index){
14393 var prevCell = false;
14394
14395 if(index > 0){
14396 for(var i = index-1; i >= 0; i--){
14397 let cell = row.cells[i];
14398
14399 if(cell.column.modules.edit && Helpers.elVisible(cell.getElement())){
14400 let allowEdit = this.allowEdit(cell);
14401
14402 if(allowEdit){
14403 prevCell = cell;
14404 break;
14405 }
14406 }
14407 }
14408 }
14409
14410 return prevCell;
14411 }
14412
14413 ///////////////////////////////////
14414 ///////// Internal Logic //////////
14415 ///////////////////////////////////
14416
14417 initializeColumnCheck(column){
14418 if(typeof column.definition.editor !== "undefined"){
14419 this.initializeColumn(column);
14420 }
14421 }
14422
14423 columnDeleteCheck(column){
14424 if(this.currentCell && this.currentCell.column === column){
14425 this.cancelEdit();
14426 }
14427 }
14428
14429 rowDeleteCheck(row){
14430 if(this.currentCell && this.currentCell.row === row){
14431 this.cancelEdit();
14432 }
14433 }
14434
14435 rowEditableCheck(row){
14436 row.getCells().forEach((cell) => {
14437 if(cell.column.modules.edit && typeof cell.column.modules.edit.check === "function"){
14438 this.updateCellClass(cell);
14439 }
14440 });
14441 }
14442
14443 //initialize column editor
14444 initializeColumn(column){
14445 var convertEmpty = Object.keys(column.definition).includes("editorEmptyValue");
14446
14447 var config = {
14448 editor:false,
14449 blocked:false,
14450 check:column.definition.editable,
14451 params:column.definition.editorParams || {},
14452 convertEmptyValues:convertEmpty,
14453 editorEmptyValue:column.definition.editorEmptyValue,
14454 editorEmptyValueFunc:column.definition.editorEmptyValueFunc,
14455 };
14456
14457 //set column editor
14458 config.editor = this.lookupEditor(column.definition.editor, column);
14459
14460 if(config.editor){
14461 column.modules.edit = config;
14462 }
14463 }
14464
14465 lookupEditor(editor, column){
14466 var editorFunc;
14467
14468 switch(typeof editor){
14469 case "string":
14470 if(this.editors[editor]){
14471 editorFunc = this.editors[editor];
14472 }else {
14473 console.warn("Editor Error - No such editor found: ", editor);
14474 }
14475 break;
14476
14477 case "function":
14478 editorFunc = editor;
14479 break;
14480
14481 case "boolean":
14482 if(editor === true){
14483 if(typeof column.definition.formatter !== "function"){
14484 if(this.editors[column.definition.formatter]){
14485 editorFunc = this.editors[column.definition.formatter];
14486 }else {
14487 editorFunc = this.editors["input"];
14488 }
14489 }else {
14490 console.warn("Editor Error - Cannot auto lookup editor for a custom formatter: ", column.definition.formatter);
14491 }
14492 }
14493 break;
14494 }
14495
14496 return editorFunc;
14497 }
14498
14499 getCurrentCell(){
14500 return this.currentCell ? this.currentCell.getComponent() : false;
14501 }
14502
14503 clearEditor(cancel){
14504 var cell = this.currentCell,
14505 cellEl;
14506
14507 this.invalidEdit = false;
14508
14509 if(cell){
14510 this.currentCell = false;
14511
14512 cellEl = cell.getElement();
14513
14514 this.dispatch("edit-editor-clear", cell, cancel);
14515
14516 cellEl.classList.remove("tabulator-editing");
14517
14518 while(cellEl.firstChild) cellEl.removeChild(cellEl.firstChild);
14519
14520 cell.row.getElement().classList.remove("tabulator-editing");
14521
14522 cell.table.element.classList.remove("tabulator-editing");
14523 }
14524 }
14525
14526 cancelEdit(){
14527 if(this.currentCell){
14528 var cell = this.currentCell;
14529 var component = this.currentCell.getComponent();
14530
14531 this.clearEditor(true);
14532 cell.setValueActual(cell.getValue());
14533 cell.cellRendered();
14534
14535 if(cell.column.definition.editor == "textarea" || cell.column.definition.variableHeight){
14536 cell.row.normalizeHeight(true);
14537 }
14538
14539 if(cell.column.definition.cellEditCancelled){
14540 cell.column.definition.cellEditCancelled.call(this.table, component);
14541 }
14542
14543 this.dispatch("edit-cancelled", cell);
14544 this.dispatchExternal("cellEditCancelled", component);
14545 }
14546 }
14547
14548 //return a formatted value for a cell
14549 bindEditor(cell){
14550 if(cell.column.modules.edit){
14551 var self = this,
14552 element = cell.getElement(true);
14553
14554 this.updateCellClass(cell);
14555 element.setAttribute("tabindex", 0);
14556
14557 element.addEventListener("mousedown", function(e){
14558 if (e.button === 2) {
14559 e.preventDefault();
14560 }else {
14561 self.mouseClick = true;
14562 }
14563 });
14564
14565 if(this.options("editTriggerEvent") === "dblclick"){
14566 element.addEventListener("dblclick", function(e){
14567 if(!element.classList.contains("tabulator-editing")){
14568 element.focus({preventScroll: true});
14569 self.edit(cell, e, false);
14570 }
14571 });
14572 }
14573
14574
14575 if(this.options("editTriggerEvent") === "focus" || this.options("editTriggerEvent") === "click"){
14576 element.addEventListener("click", function(e){
14577 if(!element.classList.contains("tabulator-editing")){
14578 element.focus({preventScroll: true});
14579 self.edit(cell, e, false);
14580 }
14581 });
14582 }
14583
14584 if(this.options("editTriggerEvent") === "focus"){
14585 element.addEventListener("focus", function(e){
14586 if(!self.recursionBlock){
14587 self.edit(cell, e, false);
14588 }
14589 });
14590 }
14591 }
14592 }
14593
14594 focusCellNoEvent(cell, block){
14595 this.recursionBlock = true;
14596
14597 if(!(block && this.table.browser === "ie")){
14598 cell.getElement().focus({preventScroll: true});
14599 }
14600
14601 this.recursionBlock = false;
14602 }
14603
14604 editCell(cell, forceEdit){
14605 this.focusCellNoEvent(cell);
14606 this.edit(cell, false, forceEdit);
14607 }
14608
14609 focusScrollAdjust(cell){
14610 if(this.table.rowManager.getRenderMode() == "virtual"){
14611 var topEdge = this.table.rowManager.element.scrollTop,
14612 bottomEdge = this.table.rowManager.element.clientHeight + this.table.rowManager.element.scrollTop,
14613 rowEl = cell.row.getElement();
14614
14615 if(rowEl.offsetTop < topEdge){
14616 this.table.rowManager.element.scrollTop -= (topEdge - rowEl.offsetTop);
14617 }else {
14618 if(rowEl.offsetTop + rowEl.offsetHeight > bottomEdge){
14619 this.table.rowManager.element.scrollTop += (rowEl.offsetTop + rowEl.offsetHeight - bottomEdge);
14620 }
14621 }
14622
14623 var leftEdge = this.table.rowManager.element.scrollLeft,
14624 rightEdge = this.table.rowManager.element.clientWidth + this.table.rowManager.element.scrollLeft,
14625 cellEl = cell.getElement();
14626
14627 if(this.table.modExists("frozenColumns")){
14628 leftEdge += parseInt(this.table.modules.frozenColumns.leftMargin || 0);
14629 rightEdge -= parseInt(this.table.modules.frozenColumns.rightMargin || 0);
14630 }
14631
14632 if(this.table.options.renderHorizontal === "virtual"){
14633 leftEdge -= parseInt(this.table.columnManager.renderer.vDomPadLeft);
14634 rightEdge -= parseInt(this.table.columnManager.renderer.vDomPadLeft);
14635 }
14636
14637 if(cellEl.offsetLeft < leftEdge){
14638 this.table.rowManager.element.scrollLeft -= (leftEdge - cellEl.offsetLeft);
14639 }else {
14640 if(cellEl.offsetLeft + cellEl.offsetWidth > rightEdge){
14641 this.table.rowManager.element.scrollLeft += (cellEl.offsetLeft + cellEl.offsetWidth - rightEdge);
14642 }
14643 }
14644 }
14645 }
14646
14647 allowEdit(cell) {
14648 var check = cell.column.modules.edit ? true : false;
14649
14650 if(cell.column.modules.edit){
14651 switch(typeof cell.column.modules.edit.check){
14652 case "function":
14653 if(cell.row.initialized){
14654 check = cell.column.modules.edit.check(cell.getComponent());
14655 }
14656 break;
14657
14658 case "string":
14659 check = !!cell.row.data[cell.column.modules.edit.check];
14660 break;
14661
14662 case "boolean":
14663 check = cell.column.modules.edit.check;
14664 break;
14665 }
14666 }
14667
14668 return check;
14669 }
14670
14671 edit(cell, e, forceEdit){
14672 var self = this,
14673 allowEdit = true,
14674 rendered = function(){},
14675 element = cell.getElement(),
14676 editFinished = false,
14677 cellEditor, component, params;
14678
14679 //prevent editing if another cell is refusing to leave focus (eg. validation fail)
14680
14681 if(this.currentCell){
14682 if(!this.invalidEdit && this.currentCell !== cell){
14683 this.cancelEdit();
14684 }
14685 return;
14686 }
14687
14688 //handle successful value change
14689 function success(value){
14690 if(self.currentCell === cell && !editFinished){
14691 var valid = self.chain("edit-success", [cell, value], true, true);
14692
14693 if(valid === true || self.table.options.validationMode === "highlight"){
14694
14695 editFinished = true;
14696
14697 self.clearEditor();
14698
14699 if(!cell.modules.edit){
14700 cell.modules.edit = {};
14701 }
14702
14703 cell.modules.edit.edited = true;
14704
14705 if(self.editedCells.indexOf(cell) == -1){
14706 self.editedCells.push(cell);
14707 }
14708
14709 value = self.transformEmptyValues(value, cell);
14710
14711 cell.setValue(value, true);
14712
14713 return valid === true;
14714 }else {
14715 editFinished = true;
14716 self.invalidEdit = true;
14717 self.focusCellNoEvent(cell, true);
14718 rendered();
14719
14720 setTimeout(() => {
14721 editFinished = false;
14722 }, 10);
14723 return false;
14724 }
14725 }
14726 }
14727
14728 //handle aborted edit
14729 function cancel(){
14730 // editFinished = true;
14731
14732 if(self.currentCell === cell && !editFinished){
14733 self.cancelEdit();
14734 }
14735 }
14736
14737 function onRendered(callback){
14738 rendered = callback;
14739 }
14740
14741 if(!cell.column.modules.edit.blocked){
14742 if(e){
14743 e.stopPropagation();
14744 }
14745
14746 allowEdit = this.allowEdit(cell);
14747
14748 if(allowEdit || forceEdit){
14749 self.cancelEdit();
14750
14751 self.currentCell = cell;
14752
14753 this.focusScrollAdjust(cell);
14754
14755 component = cell.getComponent();
14756
14757 if(this.mouseClick){
14758 this.mouseClick = false;
14759
14760 if(cell.column.definition.cellClick){
14761 cell.column.definition.cellClick.call(this.table, e, component);
14762 }
14763 }
14764
14765 if(cell.column.definition.cellEditing){
14766 cell.column.definition.cellEditing.call(this.table, component);
14767 }
14768
14769 this.dispatch("cell-editing", cell);
14770 this.dispatchExternal("cellEditing", component);
14771
14772 params = typeof cell.column.modules.edit.params === "function" ? cell.column.modules.edit.params(component) : cell.column.modules.edit.params;
14773
14774 cellEditor = cell.column.modules.edit.editor.call(self, component, onRendered, success, cancel, params);
14775
14776 //if editor returned, add to DOM, if false, abort edit
14777 if(this.currentCell && cellEditor !== false){
14778 if(cellEditor instanceof Node){
14779 element.classList.add("tabulator-editing");
14780 cell.row.getElement().classList.add("tabulator-editing");
14781 cell.table.element.classList.add("tabulator-editing");
14782 while(element.firstChild) element.removeChild(element.firstChild);
14783 element.appendChild(cellEditor);
14784
14785 //trigger onRendered Callback
14786 rendered();
14787
14788 //prevent editing from triggering rowClick event
14789 var children = element.children;
14790
14791 for (var i = 0; i < children.length; i++) {
14792 children[i].addEventListener("click", function(e){
14793 e.stopPropagation();
14794 });
14795 }
14796 }else {
14797 console.warn("Edit Error - Editor should return an instance of Node, the editor returned:", cellEditor);
14798 this.blur(element);
14799 return false;
14800 }
14801 }else {
14802 this.blur(element);
14803 return false;
14804 }
14805
14806 return true;
14807 }else {
14808 this.mouseClick = false;
14809 this.blur(element);
14810 return false;
14811 }
14812 }else {
14813 this.mouseClick = false;
14814 this.blur(element);
14815 return false;
14816 }
14817 }
14818
14819 emptyValueCheck(value){
14820 return value === "" || value === null || typeof value === "undefined";
14821 }
14822
14823 transformEmptyValues(value, cell){
14824 var mod = cell.column.modules.edit,
14825 convert = mod.convertEmptyValues || this.convertEmptyValues,
14826 checkFunc;
14827
14828 if(convert){
14829 checkFunc = mod.editorEmptyValueFunc || this.options("editorEmptyValueFunc");
14830
14831 if(checkFunc && checkFunc(value)){
14832 value = mod.convertEmptyValues ? mod.editorEmptyValue : this.options("editorEmptyValue");
14833 }
14834 }
14835
14836 return value;
14837 }
14838
14839 blur(element){
14840 if(!this.confirm("edit-blur", [element]) ){
14841 element.blur();
14842 }
14843 }
14844
14845 getEditedCells(){
14846 var output = [];
14847
14848 this.editedCells.forEach((cell) => {
14849 output.push(cell.getComponent());
14850 });
14851
14852 return output;
14853 }
14854
14855 clearEdited(cell){
14856 var editIndex;
14857
14858 if(cell.modules.edit && cell.modules.edit.edited){
14859 cell.modules.edit.edited = false;
14860
14861 this.dispatch("edit-edited-clear", cell);
14862 }
14863
14864 editIndex = this.editedCells.indexOf(cell);
14865
14866 if(editIndex > -1){
14867 this.editedCells.splice(editIndex, 1);
14868 }
14869 }
14870 }
14871
14872 class ExportRow{
14873 constructor(type, columns, component, indent){
14874 this.type = type;
14875 this.columns = columns;
14876 this.component = component || false;
14877 this.indent = indent || 0;
14878 }
14879 }
14880
14881 class ExportColumn{
14882 constructor(value, component, width, height, depth){
14883 this.value = value;
14884 this.component = component || false;
14885 this.width = width;
14886 this.height = height;
14887 this.depth = depth;
14888 }
14889 }
14890
14891 var columnLookups$1 = {
14892
14893 };
14894
14895 var rowLookups$1 = {
14896 visible:function(){
14897 return this.rowManager.getVisibleRows(false, true);
14898 },
14899 all:function(){
14900 return this.rowManager.rows;
14901 },
14902 selected:function(){
14903 return this.modules.selectRow.selectedRows;
14904 },
14905 active:function(){
14906 if(this.options.pagination){
14907 return this.rowManager.getDisplayRows(this.rowManager.displayRows.length - 2);
14908 }else {
14909 return this.rowManager.getDisplayRows();
14910 }
14911 },
14912 };
14913
14914 class Export extends Module{
14915
14916 static moduleName = "export";
14917
14918 static columnLookups = columnLookups$1;
14919 static rowLookups = rowLookups$1;
14920
14921 constructor(table){
14922 super(table);
14923
14924 this.config = {};
14925 this.cloneTableStyle = true;
14926 this.colVisProp = "";
14927 this.colVisPropAttach = "";
14928
14929 this.registerTableOption("htmlOutputConfig", false); //html output config
14930
14931 this.registerColumnOption("htmlOutput");
14932 this.registerColumnOption("titleHtmlOutput");
14933 }
14934
14935 initialize(){
14936 this.registerTableFunction("getHtml", this.getHtml.bind(this));
14937 }
14938
14939 ///////////////////////////////////
14940 ///////// Internal Logic //////////
14941 ///////////////////////////////////
14942
14943 generateExportList(config, style, range, colVisProp){
14944 var headers, body, columns, colLookup;
14945
14946 this.cloneTableStyle = style;
14947 this.config = config || {};
14948 this.colVisProp = colVisProp;
14949 this.colVisPropAttach = this.colVisProp.charAt(0).toUpperCase() + this.colVisProp.slice(1);
14950
14951 colLookup = Export.columnLookups[range];
14952
14953 if(colLookup){
14954 columns = colLookup.call(this.table);
14955 columns = columns.filter(col => this.columnVisCheck(col));
14956 }
14957
14958 headers = this.config.columnHeaders !== false ? this.headersToExportRows(this.generateColumnGroupHeaders(columns)) : [];
14959
14960 if(columns){
14961 columns = columns.map(col => col.getComponent());
14962 }
14963
14964 body = this.bodyToExportRows(this.rowLookup(range), columns);
14965
14966 return headers.concat(body);
14967 }
14968
14969 generateTable(config, style, range, colVisProp){
14970 var list = this.generateExportList(config, style, range, colVisProp);
14971
14972 return this.generateTableElement(list);
14973 }
14974
14975 rowLookup(range){
14976 var rows = [],
14977 rowLookup;
14978
14979 if(typeof range == "function"){
14980 range.call(this.table).forEach((row) =>{
14981 row = this.table.rowManager.findRow(row);
14982
14983 if(row){
14984 rows.push(row);
14985 }
14986 });
14987 }else {
14988 rowLookup = Export.rowLookups[range] || Export.rowLookups["active"];
14989
14990 rows = rowLookup.call(this.table);
14991 }
14992
14993 return Object.assign([], rows);
14994 }
14995
14996 generateColumnGroupHeaders(columns){
14997 var output = [];
14998
14999 if (!columns) {
15000 columns = this.config.columnGroups !== false ? this.table.columnManager.columns : this.table.columnManager.columnsByIndex;
15001 }
15002
15003 columns.forEach((column) => {
15004 var colData = this.processColumnGroup(column);
15005
15006 if(colData){
15007 output.push(colData);
15008 }
15009 });
15010
15011
15012
15013 return output;
15014 }
15015
15016 processColumnGroup(column){
15017 var subGroups = column.columns,
15018 maxDepth = 0,
15019 title = column.definition["title" + (this.colVisPropAttach)] || column.definition.title;
15020
15021 var groupData = {
15022 title:title,
15023 column:column,
15024 depth:1,
15025 };
15026
15027 if(subGroups.length){
15028 groupData.subGroups = [];
15029 groupData.width = 0;
15030
15031 subGroups.forEach((subGroup) => {
15032 var subGroupData = this.processColumnGroup(subGroup);
15033
15034 if(subGroupData){
15035 groupData.width += subGroupData.width;
15036 groupData.subGroups.push(subGroupData);
15037
15038 if(subGroupData.depth > maxDepth){
15039 maxDepth = subGroupData.depth;
15040 }
15041 }
15042 });
15043
15044 groupData.depth += maxDepth;
15045
15046 if(!groupData.width){
15047 return false;
15048 }
15049 }else {
15050 if(this.columnVisCheck(column)){
15051 groupData.width = 1;
15052 }else {
15053 return false;
15054 }
15055 }
15056
15057 return groupData;
15058 }
15059
15060 columnVisCheck(column){
15061 var visProp = column.definition[this.colVisProp];
15062
15063 if(this.config.rowHeaders === false && column.isRowHeader){
15064 return false;
15065 }
15066
15067 if(typeof visProp === "function"){
15068 visProp = visProp.call(this.table, column.getComponent());
15069 }
15070
15071 if(visProp === false || visProp === true){
15072 return visProp;
15073 }
15074
15075 return column.visible && column.field;
15076 }
15077
15078 headersToExportRows(columns){
15079 var headers = [],
15080 headerDepth = 0,
15081 exportRows = [];
15082
15083 function parseColumnGroup(column, level){
15084
15085 var depth = headerDepth - level;
15086
15087 if(typeof headers[level] === "undefined"){
15088 headers[level] = [];
15089 }
15090
15091 column.height = column.subGroups ? 1 : (depth - column.depth) + 1;
15092
15093 headers[level].push(column);
15094
15095 if(column.height > 1){
15096 for(let i = 1; i < column.height; i ++){
15097
15098 if(typeof headers[level + i] === "undefined"){
15099 headers[level + i] = [];
15100 }
15101
15102 headers[level + i].push(false);
15103 }
15104 }
15105
15106 if(column.width > 1){
15107 for(let i = 1; i < column.width; i ++){
15108 headers[level].push(false);
15109 }
15110 }
15111
15112 if(column.subGroups){
15113 column.subGroups.forEach(function(subGroup){
15114 parseColumnGroup(subGroup, level+1);
15115 });
15116 }
15117 }
15118
15119 //calculate maximum header depth
15120 columns.forEach(function(column){
15121 if(column.depth > headerDepth){
15122 headerDepth = column.depth;
15123 }
15124 });
15125
15126 columns.forEach(function(column){
15127 parseColumnGroup(column,0);
15128 });
15129
15130 headers.forEach((header) => {
15131 var columns = [];
15132
15133 header.forEach((col) => {
15134 if(col){
15135 let title = typeof col.title === "undefined" ? "" : col.title;
15136 columns.push(new ExportColumn(title, col.column.getComponent(), col.width, col.height, col.depth));
15137 }else {
15138 columns.push(null);
15139 }
15140 });
15141
15142 exportRows.push(new ExportRow("header", columns));
15143 });
15144
15145 return exportRows;
15146 }
15147
15148 bodyToExportRows(rows, columns = []){
15149 var exportRows = [];
15150
15151 if (columns.length === 0) {
15152 this.table.columnManager.columnsByIndex.forEach((column) => {
15153 if (this.columnVisCheck(column)) {
15154 columns.push(column.getComponent());
15155 }
15156 });
15157 }
15158
15159 if(this.config.columnCalcs !== false && this.table.modExists("columnCalcs")){
15160 if(this.table.modules.columnCalcs.topInitialized){
15161 rows.unshift(this.table.modules.columnCalcs.topRow);
15162 }
15163
15164 if(this.table.modules.columnCalcs.botInitialized){
15165 rows.push(this.table.modules.columnCalcs.botRow);
15166 }
15167 }
15168
15169 rows = rows.filter((row) => {
15170 switch(row.type){
15171 case "group":
15172 return this.config.rowGroups !== false;
15173
15174 case "calc":
15175 return this.config.columnCalcs !== false;
15176
15177 case "row":
15178 return !(this.table.options.dataTree && this.config.dataTree === false && row.modules.dataTree.parent);
15179 }
15180
15181 return true;
15182 });
15183
15184 rows.forEach((row, i) => {
15185 var rowData = row.getData(this.colVisProp);
15186 var exportCols = [];
15187 var indent = 0;
15188
15189 switch(row.type){
15190 case "group":
15191 indent = row.level;
15192 exportCols.push(new ExportColumn(row.key, row.getComponent(), columns.length, 1));
15193 break;
15194
15195 case "calc" :
15196 case "row" :
15197 columns.forEach((col) => {
15198 exportCols.push(new ExportColumn(col._column.getFieldValue(rowData), col, 1, 1));
15199 });
15200
15201 if(this.table.options.dataTree && this.config.dataTree !== false){
15202 indent = row.modules.dataTree.index;
15203 }
15204 break;
15205 }
15206
15207 exportRows.push(new ExportRow(row.type, exportCols, row.getComponent(), indent));
15208 });
15209
15210 return exportRows;
15211 }
15212
15213 generateTableElement(list){
15214 var table = document.createElement("table"),
15215 headerEl = document.createElement("thead"),
15216 bodyEl = document.createElement("tbody"),
15217 styles = this.lookupTableStyles(),
15218 rowFormatter = this.table.options["rowFormatter" + (this.colVisPropAttach)],
15219 setup = {};
15220
15221 setup.rowFormatter = rowFormatter !== null ? rowFormatter : this.table.options.rowFormatter;
15222
15223 if(this.table.options.dataTree &&this.config.dataTree !== false && this.table.modExists("columnCalcs")){
15224 setup.treeElementField = this.table.modules.dataTree.elementField;
15225 }
15226
15227 //assign group header formatter
15228 setup.groupHeader = this.table.options["groupHeader" + (this.colVisPropAttach)];
15229
15230 if(setup.groupHeader && !Array.isArray(setup.groupHeader)){
15231 setup.groupHeader = [setup.groupHeader];
15232 }
15233
15234 table.classList.add("tabulator-print-table");
15235
15236 this.mapElementStyles(this.table.columnManager.getHeadersElement(), headerEl, ["border-top", "border-left", "border-right", "border-bottom", "background-color", "color", "font-weight", "font-family", "font-size"]);
15237
15238 if(list.length > 1000){
15239 console.warn("It may take a long time to render an HTML table with more than 1000 rows");
15240 }
15241
15242 list.forEach((row, i) => {
15243 let rowEl;
15244
15245 switch(row.type){
15246 case "header":
15247 headerEl.appendChild(this.generateHeaderElement(row, setup, styles));
15248 break;
15249
15250 case "group":
15251 bodyEl.appendChild(this.generateGroupElement(row, setup, styles));
15252 break;
15253
15254 case "calc":
15255 bodyEl.appendChild(this.generateCalcElement(row, setup, styles));
15256 break;
15257
15258 case "row":
15259 rowEl = this.generateRowElement(row, setup, styles);
15260
15261 this.mapElementStyles(((i % 2) && styles.evenRow) ? styles.evenRow : styles.oddRow, rowEl, ["border-top", "border-left", "border-right", "border-bottom", "color", "font-weight", "font-family", "font-size", "background-color"]);
15262 bodyEl.appendChild(rowEl);
15263 break;
15264 }
15265 });
15266
15267 if(headerEl.innerHTML){
15268 table.appendChild(headerEl);
15269 }
15270
15271 table.appendChild(bodyEl);
15272
15273
15274 this.mapElementStyles(this.table.element, table, ["border-top", "border-left", "border-right", "border-bottom"]);
15275 return table;
15276 }
15277
15278 lookupTableStyles(){
15279 var styles = {};
15280
15281 //lookup row styles
15282 if(this.cloneTableStyle && window.getComputedStyle){
15283 styles.oddRow = this.table.element.querySelector(".tabulator-row-odd:not(.tabulator-group):not(.tabulator-calcs)");
15284 styles.evenRow = this.table.element.querySelector(".tabulator-row-even:not(.tabulator-group):not(.tabulator-calcs)");
15285 styles.calcRow = this.table.element.querySelector(".tabulator-row.tabulator-calcs");
15286 styles.firstRow = this.table.element.querySelector(".tabulator-row:not(.tabulator-group):not(.tabulator-calcs)");
15287 styles.firstGroup = this.table.element.getElementsByClassName("tabulator-group")[0];
15288
15289 if(styles.firstRow){
15290 styles.styleCells = styles.firstRow.getElementsByClassName("tabulator-cell");
15291 styles.styleRowHeader = styles.firstRow.getElementsByClassName("tabulator-row-header")[0];
15292 styles.firstCell = styles.styleCells[0];
15293 styles.lastCell = styles.styleCells[styles.styleCells.length - 1];
15294 }
15295 }
15296
15297 return styles;
15298 }
15299
15300 generateHeaderElement(row, setup, styles){
15301 var rowEl = document.createElement("tr");
15302
15303 row.columns.forEach((column) => {
15304 if(column){
15305 var cellEl = document.createElement("th");
15306 var classNames = column.component._column.definition.cssClass ? column.component._column.definition.cssClass.split(" ") : [];
15307
15308 cellEl.colSpan = column.width;
15309 cellEl.rowSpan = column.height;
15310
15311 cellEl.innerHTML = column.value;
15312
15313 if(this.cloneTableStyle){
15314 cellEl.style.boxSizing = "border-box";
15315 }
15316
15317 classNames.forEach(function(className) {
15318 cellEl.classList.add(className);
15319 });
15320
15321 this.mapElementStyles(column.component.getElement(), cellEl, ["text-align", "border-left", "border-right", "background-color", "color", "font-weight", "font-family", "font-size"]);
15322 this.mapElementStyles(column.component._column.contentElement, cellEl, ["padding-top", "padding-left", "padding-right", "padding-bottom"]);
15323
15324 if(column.component._column.visible){
15325 this.mapElementStyles(column.component.getElement(), cellEl, ["width"]);
15326 }else {
15327 if(column.component._column.definition.width){
15328 cellEl.style.width = column.component._column.definition.width + "px";
15329 }
15330 }
15331
15332 if(column.component._column.parent && column.component._column.parent.isGroup){
15333 this.mapElementStyles(column.component._column.parent.groupElement, cellEl, ["border-top"]);
15334 }else {
15335 this.mapElementStyles(column.component.getElement(), cellEl, ["border-top"]);
15336 }
15337
15338 if(column.component._column.isGroup){
15339 this.mapElementStyles(column.component.getElement(), cellEl, ["border-bottom"]);
15340 }else {
15341 this.mapElementStyles(this.table.columnManager.getElement(), cellEl, ["border-bottom"]);
15342 }
15343
15344 rowEl.appendChild(cellEl);
15345 }
15346 });
15347
15348 return rowEl;
15349 }
15350
15351 generateGroupElement(row, setup, styles){
15352
15353 var rowEl = document.createElement("tr"),
15354 cellEl = document.createElement("td"),
15355 group = row.columns[0];
15356
15357 rowEl.classList.add("tabulator-print-table-row");
15358
15359 if(setup.groupHeader && setup.groupHeader[row.indent]){
15360 group.value = setup.groupHeader[row.indent](group.value, row.component._group.getRowCount(), row.component._group.getData(), row.component);
15361 }else {
15362 if(setup.groupHeader !== false){
15363 group.value = row.component._group.generator(group.value, row.component._group.getRowCount(), row.component._group.getData(), row.component);
15364 }
15365 }
15366
15367 cellEl.colSpan = group.width;
15368 cellEl.innerHTML = group.value;
15369
15370 rowEl.classList.add("tabulator-print-table-group");
15371 rowEl.classList.add("tabulator-group-level-" + row.indent);
15372
15373 if(group.component.isVisible()){
15374 rowEl.classList.add("tabulator-group-visible");
15375 }
15376
15377 this.mapElementStyles(styles.firstGroup, rowEl, ["border-top", "border-left", "border-right", "border-bottom", "color", "font-weight", "font-family", "font-size", "background-color"]);
15378 this.mapElementStyles(styles.firstGroup, cellEl, ["padding-top", "padding-left", "padding-right", "padding-bottom"]);
15379
15380 rowEl.appendChild(cellEl);
15381
15382 return rowEl;
15383 }
15384
15385 generateCalcElement(row, setup, styles){
15386 var rowEl = this.generateRowElement(row, setup, styles);
15387
15388 rowEl.classList.add("tabulator-print-table-calcs");
15389 this.mapElementStyles(styles.calcRow, rowEl, ["border-top", "border-left", "border-right", "border-bottom", "color", "font-weight", "font-family", "font-size", "background-color"]);
15390
15391 return rowEl;
15392 }
15393
15394 generateRowElement(row, setup, styles){
15395 var rowEl = document.createElement("tr");
15396
15397 rowEl.classList.add("tabulator-print-table-row");
15398
15399 row.columns.forEach((col, i) => {
15400 if(col){
15401 var cellEl = document.createElement("td"),
15402 column = col.component._column,
15403 table = this.table,
15404 index = table.columnManager.findColumnIndex(column),
15405 value = col.value,
15406 cellStyle, styleProps;
15407
15408 var cellWrapper = {
15409 modules:{},
15410 getValue:function(){
15411 return value;
15412 },
15413 getField:function(){
15414 return column.definition.field;
15415 },
15416 getElement:function(){
15417 return cellEl;
15418 },
15419 getType:function(){
15420 return "cell";
15421 },
15422 getColumn:function(){
15423 return column.getComponent();
15424 },
15425 getData:function(){
15426 return row.component.getData();
15427 },
15428 getRow:function(){
15429 return row.component;
15430 },
15431 getTable:function(){
15432 return table;
15433 },
15434 getComponent:function(){
15435 return cellWrapper;
15436 },
15437 column:column,
15438 };
15439
15440 var classNames = column.definition.cssClass ? column.definition.cssClass.split(" ") : [];
15441
15442 classNames.forEach(function(className) {
15443 cellEl.classList.add(className);
15444 });
15445
15446 if(this.table.modExists("format") && this.config.formatCells !== false){
15447 value = this.table.modules.format.formatExportValue(cellWrapper, this.colVisProp);
15448 }else {
15449 switch(typeof value){
15450 case "object":
15451 value = value !== null ? JSON.stringify(value) : "";
15452 break;
15453
15454 case "undefined":
15455 value = "";
15456 break;
15457 }
15458 }
15459
15460 if(value instanceof Node){
15461 cellEl.appendChild(value);
15462 }else {
15463 cellEl.innerHTML = value;
15464 }
15465
15466 styleProps = ["padding-top", "padding-left", "padding-right", "padding-bottom", "border-top", "border-left", "border-right", "border-bottom", "color", "font-weight", "font-family", "font-size", "text-align"];
15467
15468 if(column.isRowHeader){
15469 cellStyle = styles.styleRowHeader;
15470 styleProps.push("background-color");
15471 }else {
15472 cellStyle = styles.styleCells && styles.styleCells[index] ? styles.styleCells[index] : styles.firstCell;
15473 }
15474
15475 if(cellStyle){
15476 this.mapElementStyles(cellStyle, cellEl, styleProps);
15477
15478 if(column.definition.align){
15479 cellEl.style.textAlign = column.definition.align;
15480 }
15481 }
15482
15483 if(this.table.options.dataTree && this.config.dataTree !== false){
15484 if((setup.treeElementField && setup.treeElementField == column.field) || (!setup.treeElementField && i == 0)){
15485 if(row.component._row.modules.dataTree.controlEl){
15486 cellEl.insertBefore(row.component._row.modules.dataTree.controlEl.cloneNode(true), cellEl.firstChild);
15487 }
15488 if(row.component._row.modules.dataTree.branchEl){
15489 cellEl.insertBefore(row.component._row.modules.dataTree.branchEl.cloneNode(true), cellEl.firstChild);
15490 }
15491 }
15492 }
15493
15494 rowEl.appendChild(cellEl);
15495
15496 if(cellWrapper.modules.format && cellWrapper.modules.format.renderedCallback){
15497 cellWrapper.modules.format.renderedCallback();
15498 }
15499 }
15500 });
15501
15502 if(setup.rowFormatter && row.type === "row" && this.config.formatCells !== false){
15503 let formatComponent = Object.assign(row.component);
15504
15505 formatComponent.getElement = function(){return rowEl;};
15506
15507 setup.rowFormatter(row.component);
15508 }
15509
15510 return rowEl;
15511 }
15512
15513 generateHTMLTable(list){
15514 var holder = document.createElement("div");
15515
15516 holder.appendChild(this.generateTableElement(list));
15517
15518 return holder.innerHTML;
15519 }
15520
15521 getHtml(visible, style, config, colVisProp){
15522 var list = this.generateExportList(config || this.table.options.htmlOutputConfig, style, visible, colVisProp || "htmlOutput");
15523
15524 return this.generateHTMLTable(list);
15525 }
15526
15527 mapElementStyles(from, to, props){
15528 if(this.cloneTableStyle && from && to){
15529
15530 var lookup = {
15531 "background-color" : "backgroundColor",
15532 "color" : "fontColor",
15533 "width" : "width",
15534 "font-weight" : "fontWeight",
15535 "font-family" : "fontFamily",
15536 "font-size" : "fontSize",
15537 "text-align" : "textAlign",
15538 "border-top" : "borderTop",
15539 "border-left" : "borderLeft",
15540 "border-right" : "borderRight",
15541 "border-bottom" : "borderBottom",
15542 "padding-top" : "paddingTop",
15543 "padding-left" : "paddingLeft",
15544 "padding-right" : "paddingRight",
15545 "padding-bottom" : "paddingBottom",
15546 };
15547
15548 if(window.getComputedStyle){
15549 var fromStyle = window.getComputedStyle(from);
15550
15551 props.forEach(function(prop){
15552 if(!to.style[lookup[prop]]){
15553 to.style[lookup[prop]] = fromStyle.getPropertyValue(prop);
15554 }
15555 });
15556 }
15557 }
15558 }
15559 }
15560
15561 var defaultFilters = {
15562
15563 //equal to
15564 "=":function(filterVal, rowVal, rowData, filterParams){
15565 return rowVal == filterVal ? true : false;
15566 },
15567
15568 //less than
15569 "<":function(filterVal, rowVal, rowData, filterParams){
15570 return rowVal < filterVal ? true : false;
15571 },
15572
15573 //less than or equal to
15574 "<=":function(filterVal, rowVal, rowData, filterParams){
15575 return rowVal <= filterVal ? true : false;
15576 },
15577
15578 //greater than
15579 ">":function(filterVal, rowVal, rowData, filterParams){
15580 return rowVal > filterVal ? true : false;
15581 },
15582
15583 //greater than or equal to
15584 ">=":function(filterVal, rowVal, rowData, filterParams){
15585 return rowVal >= filterVal ? true : false;
15586 },
15587
15588 //not equal to
15589 "!=":function(filterVal, rowVal, rowData, filterParams){
15590 return rowVal != filterVal ? true : false;
15591 },
15592
15593 "regex":function(filterVal, rowVal, rowData, filterParams){
15594
15595 if(typeof filterVal == "string"){
15596 filterVal = new RegExp(filterVal);
15597 }
15598
15599 return filterVal.test(rowVal);
15600 },
15601
15602 //contains the string
15603 "like":function(filterVal, rowVal, rowData, filterParams){
15604 if(filterVal === null || typeof filterVal === "undefined"){
15605 return rowVal === filterVal ? true : false;
15606 }else {
15607 if(typeof rowVal !== 'undefined' && rowVal !== null){
15608 return String(rowVal).toLowerCase().indexOf(filterVal.toLowerCase()) > -1;
15609 }
15610 else {
15611 return false;
15612 }
15613 }
15614 },
15615
15616 //contains the keywords
15617 "keywords":function(filterVal, rowVal, rowData, filterParams){
15618 var keywords = filterVal.toLowerCase().split(typeof filterParams.separator === "undefined" ? " " : filterParams.separator),
15619 value = String(rowVal === null || typeof rowVal === "undefined" ? "" : rowVal).toLowerCase(),
15620 matches = [];
15621
15622 keywords.forEach((keyword) =>{
15623 if(value.includes(keyword)){
15624 matches.push(true);
15625 }
15626 });
15627
15628 return filterParams.matchAll ? matches.length === keywords.length : !!matches.length;
15629 },
15630
15631 //starts with the string
15632 "starts":function(filterVal, rowVal, rowData, filterParams){
15633 if(filterVal === null || typeof filterVal === "undefined"){
15634 return rowVal === filterVal ? true : false;
15635 }else {
15636 if(typeof rowVal !== 'undefined' && rowVal !== null){
15637 return String(rowVal).toLowerCase().startsWith(filterVal.toLowerCase());
15638 }
15639 else {
15640 return false;
15641 }
15642 }
15643 },
15644
15645 //ends with the string
15646 "ends":function(filterVal, rowVal, rowData, filterParams){
15647 if(filterVal === null || typeof filterVal === "undefined"){
15648 return rowVal === filterVal ? true : false;
15649 }else {
15650 if(typeof rowVal !== 'undefined' && rowVal !== null){
15651 return String(rowVal).toLowerCase().endsWith(filterVal.toLowerCase());
15652 }
15653 else {
15654 return false;
15655 }
15656 }
15657 },
15658
15659 //in array
15660 "in":function(filterVal, rowVal, rowData, filterParams){
15661 if(Array.isArray(filterVal)){
15662 return filterVal.length ? filterVal.indexOf(rowVal) > -1 : true;
15663 }else {
15664 console.warn("Filter Error - filter value is not an array:", filterVal);
15665 return false;
15666 }
15667 },
15668 };
15669
15670 class Filter extends Module{
15671
15672 static moduleName = "filter";
15673
15674 //load defaults
15675 static filters = defaultFilters;
15676
15677 constructor(table){
15678 super(table);
15679
15680 this.filterList = []; //hold filter list
15681 this.headerFilters = {}; //hold column filters
15682 this.headerFilterColumns = []; //hold columns that use header filters
15683
15684 this.prevHeaderFilterChangeCheck = "";
15685 this.prevHeaderFilterChangeCheck = "{}";
15686
15687 this.changed = false; //has filtering changed since last render
15688 this.tableInitialized = false;
15689
15690 this.registerTableOption("filterMode", "local"); //local or remote filtering
15691
15692 this.registerTableOption("initialFilter", false); //initial filtering criteria
15693 this.registerTableOption("initialHeaderFilter", false); //initial header filtering criteria
15694 this.registerTableOption("headerFilterLiveFilterDelay", 300); //delay before updating column after user types in header filter
15695 this.registerTableOption("placeholderHeaderFilter", false); //placeholder when header filter is empty
15696
15697 this.registerColumnOption("headerFilter");
15698 this.registerColumnOption("headerFilterPlaceholder");
15699 this.registerColumnOption("headerFilterParams");
15700 this.registerColumnOption("headerFilterEmptyCheck");
15701 this.registerColumnOption("headerFilterFunc");
15702 this.registerColumnOption("headerFilterFuncParams");
15703 this.registerColumnOption("headerFilterLiveFilter");
15704
15705 this.registerTableFunction("searchRows", this.searchRows.bind(this));
15706 this.registerTableFunction("searchData", this.searchData.bind(this));
15707
15708 this.registerTableFunction("setFilter", this.userSetFilter.bind(this));
15709 this.registerTableFunction("refreshFilter", this.userRefreshFilter.bind(this));
15710 this.registerTableFunction("addFilter", this.userAddFilter.bind(this));
15711 this.registerTableFunction("getFilters", this.getFilters.bind(this));
15712 this.registerTableFunction("setHeaderFilterFocus", this.userSetHeaderFilterFocus.bind(this));
15713 this.registerTableFunction("getHeaderFilterValue", this.userGetHeaderFilterValue.bind(this));
15714 this.registerTableFunction("setHeaderFilterValue", this.userSetHeaderFilterValue.bind(this));
15715 this.registerTableFunction("getHeaderFilters", this.getHeaderFilters.bind(this));
15716 this.registerTableFunction("removeFilter", this.userRemoveFilter.bind(this));
15717 this.registerTableFunction("clearFilter", this.userClearFilter.bind(this));
15718 this.registerTableFunction("clearHeaderFilter", this.userClearHeaderFilter.bind(this));
15719
15720 this.registerComponentFunction("column", "headerFilterFocus", this.setHeaderFilterFocus.bind(this));
15721 this.registerComponentFunction("column", "reloadHeaderFilter", this.reloadHeaderFilter.bind(this));
15722 this.registerComponentFunction("column", "getHeaderFilterValue", this.getHeaderFilterValue.bind(this));
15723 this.registerComponentFunction("column", "setHeaderFilterValue", this.setHeaderFilterValue.bind(this));
15724 }
15725
15726 initialize(){
15727 this.subscribe("column-init", this.initializeColumnHeaderFilter.bind(this));
15728 this.subscribe("column-width-fit-before", this.hideHeaderFilterElements.bind(this));
15729 this.subscribe("column-width-fit-after", this.showHeaderFilterElements.bind(this));
15730 this.subscribe("table-built", this.tableBuilt.bind(this));
15731 this.subscribe("placeholder", this.generatePlaceholder.bind(this));
15732
15733 if(this.table.options.filterMode === "remote"){
15734 this.subscribe("data-params", this.remoteFilterParams.bind(this));
15735 }
15736
15737 this.registerDataHandler(this.filter.bind(this), 10);
15738 }
15739
15740 tableBuilt(){
15741 if(this.table.options.initialFilter){
15742 this.setFilter(this.table.options.initialFilter);
15743 }
15744
15745 if(this.table.options.initialHeaderFilter){
15746 this.table.options.initialHeaderFilter.forEach((item) => {
15747
15748 var column = this.table.columnManager.findColumn(item.field);
15749
15750 if(column){
15751 this.setHeaderFilterValue(column, item.value);
15752 }else {
15753 console.warn("Column Filter Error - No matching column found:", item.field);
15754 return false;
15755 }
15756 });
15757 }
15758
15759 this.tableInitialized = true;
15760 }
15761
15762 remoteFilterParams(data, config, silent, params){
15763 params.filter = this.getFilters(true, true);
15764 return params;
15765 }
15766
15767 generatePlaceholder(text){
15768 if(this.table.options.placeholderHeaderFilter && Object.keys(this.headerFilters).length){
15769 return this.table.options.placeholderHeaderFilter;
15770 }
15771 }
15772
15773 ///////////////////////////////////
15774 ///////// Table Functions /////////
15775 ///////////////////////////////////
15776
15777 //set standard filters
15778 userSetFilter(field, type, value, params){
15779 this.setFilter(field, type, value, params);
15780 this.refreshFilter();
15781 }
15782
15783 //set standard filters
15784 userRefreshFilter(){
15785 this.refreshFilter();
15786 }
15787
15788 //add filter to array
15789 userAddFilter(field, type, value, params){
15790 this.addFilter(field, type, value, params);
15791 this.refreshFilter();
15792 }
15793
15794 userSetHeaderFilterFocus(field){
15795 var column = this.table.columnManager.findColumn(field);
15796
15797 if(column){
15798 this.setHeaderFilterFocus(column);
15799 }else {
15800 console.warn("Column Filter Focus Error - No matching column found:", field);
15801 return false;
15802 }
15803 }
15804
15805 userGetHeaderFilterValue(field) {
15806 var column = this.table.columnManager.findColumn(field);
15807
15808 if(column){
15809 return this.getHeaderFilterValue(column);
15810 }else {
15811 console.warn("Column Filter Error - No matching column found:", field);
15812 }
15813 }
15814
15815 userSetHeaderFilterValue(field, value){
15816 var column = this.table.columnManager.findColumn(field);
15817
15818 if(column){
15819 this.setHeaderFilterValue(column, value);
15820 }else {
15821 console.warn("Column Filter Error - No matching column found:", field);
15822 return false;
15823 }
15824 }
15825
15826 //remove filter from array
15827 userRemoveFilter(field, type, value){
15828 this.removeFilter(field, type, value);
15829 this.refreshFilter();
15830 }
15831
15832 //clear filters
15833 userClearFilter(all){
15834 this.clearFilter(all);
15835 this.refreshFilter();
15836 }
15837
15838 //clear header filters
15839 userClearHeaderFilter(){
15840 this.clearHeaderFilter();
15841 this.refreshFilter();
15842 }
15843
15844
15845 //search for specific row components
15846 searchRows(field, type, value){
15847 return this.search("rows", field, type, value);
15848 }
15849
15850 //search for specific data
15851 searchData(field, type, value){
15852 return this.search("data", field, type, value);
15853 }
15854
15855 ///////////////////////////////////
15856 ///////// Internal Logic //////////
15857 ///////////////////////////////////
15858
15859 initializeColumnHeaderFilter(column){
15860 var def = column.definition;
15861
15862 if(def.headerFilter){
15863 this.initializeColumn(column);
15864 }
15865 }
15866
15867 //initialize column header filter
15868 initializeColumn(column, value){
15869 var self = this,
15870 field = column.getField();
15871
15872 //handle successfully value change
15873 function success(value){
15874 var filterType = (column.modules.filter.tagType == "input" && column.modules.filter.attrType == "text") || column.modules.filter.tagType == "textarea" ? "partial" : "match",
15875 type = "",
15876 filterChangeCheck = "",
15877 filterFunc;
15878
15879 if(typeof column.modules.filter.prevSuccess === "undefined" || column.modules.filter.prevSuccess !== value){
15880
15881 column.modules.filter.prevSuccess = value;
15882
15883 if(!column.modules.filter.emptyFunc(value)){
15884 column.modules.filter.value = value;
15885
15886 switch(typeof column.definition.headerFilterFunc){
15887 case "string":
15888 if(Filter.filters[column.definition.headerFilterFunc]){
15889 type = column.definition.headerFilterFunc;
15890 filterFunc = function(data){
15891 var params = column.definition.headerFilterFuncParams || {};
15892 var fieldVal = column.getFieldValue(data);
15893
15894 params = typeof params === "function" ? params(value, fieldVal, data) : params;
15895
15896 return Filter.filters[column.definition.headerFilterFunc](value, fieldVal, data, params);
15897 };
15898 }else {
15899 console.warn("Header Filter Error - Matching filter function not found: ", column.definition.headerFilterFunc);
15900 }
15901 break;
15902
15903 case "function":
15904 filterFunc = function(data){
15905 var params = column.definition.headerFilterFuncParams || {};
15906 var fieldVal = column.getFieldValue(data);
15907
15908 params = typeof params === "function" ? params(value, fieldVal, data) : params;
15909
15910 return column.definition.headerFilterFunc(value, fieldVal, data, params);
15911 };
15912
15913 type = filterFunc;
15914 break;
15915 }
15916
15917 if(!filterFunc){
15918 switch(filterType){
15919 case "partial":
15920 filterFunc = function(data){
15921 var colVal = column.getFieldValue(data);
15922
15923 if(typeof colVal !== 'undefined' && colVal !== null){
15924 return String(colVal).toLowerCase().indexOf(String(value).toLowerCase()) > -1;
15925 }else {
15926 return false;
15927 }
15928 };
15929 type = "like";
15930 break;
15931
15932 default:
15933 filterFunc = function(data){
15934 return column.getFieldValue(data) == value;
15935 };
15936 type = "=";
15937 }
15938 }
15939
15940 self.headerFilters[field] = {value:value, func:filterFunc, type:type};
15941 }else {
15942 delete self.headerFilters[field];
15943 }
15944
15945 column.modules.filter.value = value;
15946
15947 filterChangeCheck = JSON.stringify(self.headerFilters);
15948
15949 if(self.prevHeaderFilterChangeCheck !== filterChangeCheck){
15950 self.prevHeaderFilterChangeCheck = filterChangeCheck;
15951
15952 self.trackChanges();
15953 self.refreshFilter();
15954 }
15955 }
15956
15957 return true;
15958 }
15959
15960 column.modules.filter = {
15961 success:success,
15962 attrType:false,
15963 tagType:false,
15964 emptyFunc:false,
15965 };
15966
15967 this.generateHeaderFilterElement(column);
15968 }
15969
15970 generateHeaderFilterElement(column, initialValue, reinitialize){
15971 var self = this,
15972 success = column.modules.filter.success,
15973 field = column.getField(),
15974 filterElement, editor, editorElement, cellWrapper, typingTimer, searchTrigger, params, onRenderedCallback;
15975
15976 column.modules.filter.value = initialValue;
15977
15978 //handle aborted edit
15979 function cancel(){}
15980
15981 function onRendered(callback){
15982 onRenderedCallback = callback;
15983 }
15984
15985 if(column.modules.filter.headerElement && column.modules.filter.headerElement.parentNode){
15986 column.contentElement.removeChild(column.modules.filter.headerElement.parentNode);
15987 }
15988
15989 if(field){
15990
15991 //set empty value function
15992 column.modules.filter.emptyFunc = column.definition.headerFilterEmptyCheck || function(value){
15993 return !value && value !== 0;
15994 };
15995
15996 filterElement = document.createElement("div");
15997 filterElement.classList.add("tabulator-header-filter");
15998
15999 //set column editor
16000 switch(typeof column.definition.headerFilter){
16001 case "string":
16002 if(self.table.modules.edit.editors[column.definition.headerFilter]){
16003 editor = self.table.modules.edit.editors[column.definition.headerFilter];
16004
16005 if((column.definition.headerFilter === "tick" || column.definition.headerFilter === "tickCross") && !column.definition.headerFilterEmptyCheck){
16006 column.modules.filter.emptyFunc = function(value){
16007 return value !== true && value !== false;
16008 };
16009 }
16010 }else {
16011 console.warn("Filter Error - Cannot build header filter, No such editor found: ", column.definition.editor);
16012 }
16013 break;
16014
16015 case "function":
16016 editor = column.definition.headerFilter;
16017 break;
16018
16019 case "boolean":
16020 if(column.modules.edit && column.modules.edit.editor){
16021 editor = column.modules.edit.editor;
16022 }else {
16023 if(column.definition.formatter && self.table.modules.edit.editors[column.definition.formatter]){
16024 editor = self.table.modules.edit.editors[column.definition.formatter];
16025
16026 if((column.definition.formatter === "tick" || column.definition.formatter === "tickCross") && !column.definition.headerFilterEmptyCheck){
16027 column.modules.filter.emptyFunc = function(value){
16028 return value !== true && value !== false;
16029 };
16030 }
16031 }else {
16032 editor = self.table.modules.edit.editors["input"];
16033 }
16034 }
16035 break;
16036 }
16037
16038 if(editor){
16039
16040 cellWrapper = {
16041 getValue:function(){
16042 return typeof initialValue !== "undefined" ? initialValue : "";
16043 },
16044 getField:function(){
16045 return column.definition.field;
16046 },
16047 getElement:function(){
16048 return filterElement;
16049 },
16050 getColumn:function(){
16051 return column.getComponent();
16052 },
16053 getTable:() => {
16054 return this.table;
16055 },
16056 getType:() => {
16057 return "header";
16058 },
16059 getRow:function(){
16060 return {
16061 normalizeHeight:function(){
16062
16063 }
16064 };
16065 }
16066 };
16067
16068 params = column.definition.headerFilterParams || {};
16069
16070 params = typeof params === "function" ? params.call(self.table, cellWrapper) : params;
16071
16072 editorElement = editor.call(this.table.modules.edit, cellWrapper, onRendered, success, cancel, params);
16073
16074 if(!editorElement){
16075 console.warn("Filter Error - Cannot add filter to " + field + " column, editor returned a value of false");
16076 return;
16077 }
16078
16079 if(!(editorElement instanceof Node)){
16080 console.warn("Filter Error - Cannot add filter to " + field + " column, editor should return an instance of Node, the editor returned:", editorElement);
16081 return;
16082 }
16083
16084 //set Placeholder Text
16085 self.langBind("headerFilters|columns|" + column.definition.field, function(value){
16086 editorElement.setAttribute("placeholder", typeof value !== "undefined" && value ? value : (column.definition.headerFilterPlaceholder || self.langText("headerFilters|default")));
16087 });
16088
16089 //focus on element on click
16090 editorElement.addEventListener("click", function(e){
16091 e.stopPropagation();
16092 editorElement.focus();
16093 });
16094
16095 editorElement.addEventListener("focus", (e) => {
16096 var left = this.table.columnManager.contentsElement.scrollLeft;
16097
16098 var headerPos = this.table.rowManager.element.scrollLeft;
16099
16100 if(left !== headerPos){
16101 this.table.rowManager.scrollHorizontal(left);
16102 this.table.columnManager.scrollHorizontal(left);
16103 }
16104 });
16105
16106 //live update filters as user types
16107 typingTimer = false;
16108
16109 searchTrigger = function(e){
16110 if(typingTimer){
16111 clearTimeout(typingTimer);
16112 }
16113
16114 typingTimer = setTimeout(function(){
16115 success(editorElement.value);
16116 },self.table.options.headerFilterLiveFilterDelay);
16117 };
16118
16119 column.modules.filter.headerElement = editorElement;
16120 column.modules.filter.attrType = editorElement.hasAttribute("type") ? editorElement.getAttribute("type").toLowerCase() : "" ;
16121 column.modules.filter.tagType = editorElement.tagName.toLowerCase();
16122
16123 if(column.definition.headerFilterLiveFilter !== false){
16124
16125 if (
16126 !(
16127 column.definition.headerFilter === 'autocomplete' ||
16128 column.definition.headerFilter === 'tickCross' ||
16129 ((column.definition.editor === 'autocomplete' ||
16130 column.definition.editor === 'tickCross') &&
16131 column.definition.headerFilter === true)
16132 )
16133 ) {
16134 editorElement.addEventListener("keyup", searchTrigger);
16135 editorElement.addEventListener("search", searchTrigger);
16136
16137
16138 //update number filtered columns on change
16139 if(column.modules.filter.attrType == "number"){
16140 editorElement.addEventListener("change", function(e){
16141 success(editorElement.value);
16142 });
16143 }
16144
16145 //change text inputs to search inputs to allow for clearing of field
16146 if(column.modules.filter.attrType == "text" && this.table.browser !== "ie"){
16147 editorElement.setAttribute("type", "search");
16148 // editorElement.off("change blur"); //prevent blur from triggering filter and preventing selection click
16149 }
16150
16151 }
16152
16153 //prevent input and select elements from propagating click to column sorters etc
16154 if(column.modules.filter.tagType == "input" || column.modules.filter.tagType == "select" || column.modules.filter.tagType == "textarea"){
16155 editorElement.addEventListener("mousedown",function(e){
16156 e.stopPropagation();
16157 });
16158 }
16159 }
16160
16161 filterElement.appendChild(editorElement);
16162
16163 column.contentElement.appendChild(filterElement);
16164
16165 if(!reinitialize){
16166 self.headerFilterColumns.push(column);
16167 }
16168
16169 if(onRenderedCallback){
16170 onRenderedCallback();
16171 }
16172 }
16173 }else {
16174 console.warn("Filter Error - Cannot add header filter, column has no field set:", column.definition.title);
16175 }
16176 }
16177
16178 //hide all header filter elements (used to ensure correct column widths in "fitData" layout mode)
16179 hideHeaderFilterElements(){
16180 this.headerFilterColumns.forEach(function(column){
16181 if(column.modules.filter && column.modules.filter.headerElement){
16182 column.modules.filter.headerElement.style.display = 'none';
16183 }
16184 });
16185 }
16186
16187 //show all header filter elements (used to ensure correct column widths in "fitData" layout mode)
16188 showHeaderFilterElements(){
16189 this.headerFilterColumns.forEach(function(column){
16190 if(column.modules.filter && column.modules.filter.headerElement){
16191 column.modules.filter.headerElement.style.display = '';
16192 }
16193 });
16194 }
16195
16196 //programmatically set focus of header filter
16197 setHeaderFilterFocus(column){
16198 if(column.modules.filter && column.modules.filter.headerElement){
16199 column.modules.filter.headerElement.focus();
16200 }else {
16201 console.warn("Column Filter Focus Error - No header filter set on column:", column.getField());
16202 }
16203 }
16204
16205 //programmatically get value of header filter
16206 getHeaderFilterValue(column){
16207 if(column.modules.filter && column.modules.filter.headerElement){
16208 return column.modules.filter.value;
16209 } else {
16210 console.warn("Column Filter Error - No header filter set on column:", column.getField());
16211 }
16212 }
16213
16214 //programmatically set value of header filter
16215 setHeaderFilterValue(column, value){
16216 if (column){
16217 if(column.modules.filter && column.modules.filter.headerElement){
16218 this.generateHeaderFilterElement(column, value, true);
16219 column.modules.filter.success(value);
16220 }else {
16221 console.warn("Column Filter Error - No header filter set on column:", column.getField());
16222 }
16223 }
16224 }
16225
16226 reloadHeaderFilter(column){
16227 if (column){
16228 if(column.modules.filter && column.modules.filter.headerElement){
16229 this.generateHeaderFilterElement(column, column.modules.filter.value, true);
16230 }else {
16231 console.warn("Column Filter Error - No header filter set on column:", column.getField());
16232 }
16233 }
16234 }
16235
16236 refreshFilter(){
16237 if(this.tableInitialized){
16238 if(this.table.options.filterMode === "remote"){
16239 this.reloadData(null, false, false);
16240 }else {
16241 this.refreshData(true);
16242 }
16243 }
16244
16245 //TODO - Persist left position of row manager
16246 // left = this.scrollLeft;
16247 // this.scrollHorizontal(left);
16248 }
16249
16250 //check if the filters has changed since last use
16251 trackChanges(){
16252 this.changed = true;
16253 this.dispatch("filter-changed");
16254 }
16255
16256 //check if the filters has changed since last use
16257 hasChanged(){
16258 var changed = this.changed;
16259 this.changed = false;
16260 return changed;
16261 }
16262
16263 //set standard filters
16264 setFilter(field, type, value, params){
16265 this.filterList = [];
16266
16267 if(!Array.isArray(field)){
16268 field = [{field:field, type:type, value:value, params:params}];
16269 }
16270
16271 this.addFilter(field);
16272 }
16273
16274 //add filter to array
16275 addFilter(field, type, value, params){
16276 var changed = false;
16277
16278 if(!Array.isArray(field)){
16279 field = [{field:field, type:type, value:value, params:params}];
16280 }
16281
16282 field.forEach((filter) => {
16283 filter = this.findFilter(filter);
16284
16285 if(filter){
16286 this.filterList.push(filter);
16287 changed = true;
16288 }
16289 });
16290
16291 if(changed){
16292 this.trackChanges();
16293 }
16294 }
16295
16296 findFilter(filter){
16297 var column;
16298
16299 if(Array.isArray(filter)){
16300 return this.findSubFilters(filter);
16301 }
16302
16303 var filterFunc = false;
16304
16305 if(typeof filter.field == "function"){
16306 filterFunc = function(data){
16307 return filter.field(data, filter.type || {});// pass params to custom filter function
16308 };
16309 }else {
16310
16311 if(Filter.filters[filter.type]){
16312
16313 column = this.table.columnManager.getColumnByField(filter.field);
16314
16315 if(column){
16316 filterFunc = function(data){
16317 return Filter.filters[filter.type](filter.value, column.getFieldValue(data), data, filter.params || {});
16318 };
16319 }else {
16320 filterFunc = function(data){
16321 return Filter.filters[filter.type](filter.value, data[filter.field], data, filter.params || {});
16322 };
16323 }
16324
16325
16326 }else {
16327 console.warn("Filter Error - No such filter type found, ignoring: ", filter.type);
16328 }
16329 }
16330
16331 filter.func = filterFunc;
16332
16333 return filter.func ? filter : false;
16334 }
16335
16336 findSubFilters(filters){
16337 var output = [];
16338
16339 filters.forEach((filter) => {
16340 filter = this.findFilter(filter);
16341
16342 if(filter){
16343 output.push(filter);
16344 }
16345 });
16346
16347 return output.length ? output : false;
16348 }
16349
16350 //get all filters
16351 getFilters(all, ajax){
16352 var output = [];
16353
16354 if(all){
16355 output = this.getHeaderFilters();
16356 }
16357
16358 if(ajax){
16359 output.forEach(function(item){
16360 if(typeof item.type == "function"){
16361 item.type = "function";
16362 }
16363 });
16364 }
16365
16366 output = output.concat(this.filtersToArray(this.filterList, ajax));
16367
16368 return output;
16369 }
16370
16371 //filter to Object
16372 filtersToArray(filterList, ajax){
16373 var output = [];
16374
16375 filterList.forEach((filter) => {
16376 var item;
16377
16378 if(Array.isArray(filter)){
16379 output.push(this.filtersToArray(filter, ajax));
16380 }else {
16381 item = {field:filter.field, type:filter.type, value:filter.value};
16382
16383 if(ajax){
16384 if(typeof item.type == "function"){
16385 item.type = "function";
16386 }
16387 }
16388
16389 output.push(item);
16390 }
16391 });
16392
16393 return output;
16394 }
16395
16396 //get all filters
16397 getHeaderFilters(){
16398 var output = [];
16399
16400 for(var key in this.headerFilters){
16401 output.push({field:key, type:this.headerFilters[key].type, value:this.headerFilters[key].value});
16402 }
16403
16404 return output;
16405 }
16406
16407 //remove filter from array
16408 removeFilter(field, type, value){
16409 if(!Array.isArray(field)){
16410 field = [{field:field, type:type, value:value}];
16411 }
16412
16413 field.forEach((filter) => {
16414 var index = -1;
16415
16416 if(typeof filter.field == "object"){
16417 index = this.filterList.findIndex((element) => {
16418 return filter === element;
16419 });
16420 }else {
16421 index = this.filterList.findIndex((element) => {
16422 return filter.field === element.field && filter.type === element.type && filter.value === element.value;
16423 });
16424 }
16425
16426 if(index > -1){
16427 this.filterList.splice(index, 1);
16428 }else {
16429 console.warn("Filter Error - No matching filter type found, ignoring: ", filter.type);
16430 }
16431 });
16432
16433 this.trackChanges();
16434 }
16435
16436 //clear filters
16437 clearFilter(all){
16438 this.filterList = [];
16439
16440 if(all){
16441 this.clearHeaderFilter();
16442 }
16443
16444 this.trackChanges();
16445 }
16446
16447 //clear header filters
16448 clearHeaderFilter(){
16449 this.headerFilters = {};
16450 this.prevHeaderFilterChangeCheck = "{}";
16451
16452 this.headerFilterColumns.forEach((column) => {
16453 if(typeof column.modules.filter.value !== "undefined"){
16454 delete column.modules.filter.value;
16455 }
16456 column.modules.filter.prevSuccess = undefined;
16457 this.reloadHeaderFilter(column);
16458 });
16459
16460 this.trackChanges();
16461 }
16462
16463 //search data and return matching rows
16464 search (searchType, field, type, value){
16465 var activeRows = [],
16466 filterList = [];
16467
16468 if(!Array.isArray(field)){
16469 field = [{field:field, type:type, value:value}];
16470 }
16471
16472 field.forEach((filter) => {
16473 filter = this.findFilter(filter);
16474
16475 if(filter){
16476 filterList.push(filter);
16477 }
16478 });
16479
16480 this.table.rowManager.rows.forEach((row) => {
16481 var match = true;
16482
16483 filterList.forEach((filter) => {
16484 if(!this.filterRecurse(filter, row.getData())){
16485 match = false;
16486 }
16487 });
16488
16489 if(match){
16490 activeRows.push(searchType === "data" ? row.getData("data") : row.getComponent());
16491 }
16492
16493 });
16494
16495 return activeRows;
16496 }
16497
16498 //filter row array
16499 filter(rowList, filters){
16500 var activeRows = [],
16501 activeRowComponents = [];
16502
16503 if(this.subscribedExternal("dataFiltering")){
16504 this.dispatchExternal("dataFiltering", this.getFilters(true));
16505 }
16506
16507 if(this.table.options.filterMode !== "remote" && (this.filterList.length || Object.keys(this.headerFilters).length)){
16508
16509 rowList.forEach((row) => {
16510 if(this.filterRow(row)){
16511 activeRows.push(row);
16512 }
16513 });
16514
16515 }else {
16516 activeRows = rowList.slice(0);
16517 }
16518
16519 if(this.subscribedExternal("dataFiltered")){
16520
16521 activeRows.forEach((row) => {
16522 activeRowComponents.push(row.getComponent());
16523 });
16524
16525 this.dispatchExternal("dataFiltered", this.getFilters(true), activeRowComponents);
16526 }
16527
16528 return activeRows;
16529 }
16530
16531 //filter individual row
16532 filterRow(row, filters){
16533 var match = true,
16534 data = row.getData();
16535
16536 this.filterList.forEach((filter) => {
16537 if(!this.filterRecurse(filter, data)){
16538 match = false;
16539 }
16540 });
16541
16542
16543 for(var field in this.headerFilters){
16544 if(!this.headerFilters[field].func(data)){
16545 match = false;
16546 }
16547 }
16548
16549 return match;
16550 }
16551
16552 filterRecurse(filter, data){
16553 var match = false;
16554
16555 if(Array.isArray(filter)){
16556 filter.forEach((subFilter) => {
16557 if(this.filterRecurse(subFilter, data)){
16558 match = true;
16559 }
16560 });
16561 }else {
16562 match = filter.func(data);
16563 }
16564
16565 return match;
16566 }
16567 }
16568
16569 function plaintext(cell, formatterParams, onRendered){
16570 return this.emptyToSpace(this.sanitizeHTML(cell.getValue()));
16571 }
16572
16573 function html(cell, formatterParams, onRendered){
16574 return cell.getValue();
16575 }
16576
16577 function textarea(cell, formatterParams, onRendered){
16578 cell.getElement().style.whiteSpace = "pre-wrap";
16579 return this.emptyToSpace(this.sanitizeHTML(cell.getValue()));
16580 }
16581
16582 function money(cell, formatterParams, onRendered){
16583 var floatVal = parseFloat(cell.getValue()),
16584 sign = "",
16585 number, integer, decimal, rgx, value;
16586
16587 var decimalSym = formatterParams.decimal || ".";
16588 var thousandSym = formatterParams.thousand || ",";
16589 var negativeSign = formatterParams.negativeSign || "-";
16590 var symbol = formatterParams.symbol || "";
16591 var after = !!formatterParams.symbolAfter;
16592 var precision = typeof formatterParams.precision !== "undefined" ? formatterParams.precision : 2;
16593
16594 if(isNaN(floatVal)){
16595 return this.emptyToSpace(this.sanitizeHTML(cell.getValue()));
16596 }
16597
16598 if(floatVal < 0){
16599 floatVal = Math.abs(floatVal);
16600 sign = negativeSign;
16601 }
16602
16603 number = precision !== false ? floatVal.toFixed(precision) : floatVal;
16604 number = String(number).split(".");
16605
16606 integer = number[0];
16607 decimal = number.length > 1 ? decimalSym + number[1] : "";
16608
16609 if (formatterParams.thousand !== false) {
16610 rgx = /(\d+)(\d{3})/;
16611
16612 while (rgx.test(integer)){
16613 integer = integer.replace(rgx, "$1" + thousandSym + "$2");
16614 }
16615 }
16616
16617 value = integer + decimal;
16618
16619 if(sign === true){
16620 value = "(" + value + ")";
16621 return after ? value + symbol : symbol + value;
16622 }else {
16623 return after ? sign + value + symbol : sign + symbol + value;
16624 }
16625 }
16626
16627 function link(cell, formatterParams, onRendered){
16628 var value = cell.getValue(),
16629 urlPrefix = formatterParams.urlPrefix || "",
16630 download = formatterParams.download,
16631 label = value,
16632 el = document.createElement("a"),
16633 data;
16634
16635 function labelTraverse(path, data){
16636 var item = path.shift(),
16637 value = data[item];
16638
16639 if(path.length && typeof value === "object"){
16640 return labelTraverse(path, value);
16641 }
16642
16643 return value;
16644 }
16645
16646 if(formatterParams.labelField){
16647 data = cell.getData();
16648 label = labelTraverse(formatterParams.labelField.split(this.table.options.nestedFieldSeparator), data);
16649 }
16650
16651 if(formatterParams.label){
16652 switch(typeof formatterParams.label){
16653 case "string":
16654 label = formatterParams.label;
16655 break;
16656
16657 case "function":
16658 label = formatterParams.label(cell);
16659 break;
16660 }
16661 }
16662
16663 if(label){
16664 if(formatterParams.urlField){
16665 data = cell.getData();
16666
16667 value = Helpers.retrieveNestedData(this.table.options.nestedFieldSeparator, formatterParams.urlField, data);
16668 }
16669
16670 if(formatterParams.url){
16671 switch(typeof formatterParams.url){
16672 case "string":
16673 value = formatterParams.url;
16674 break;
16675
16676 case "function":
16677 value = formatterParams.url(cell);
16678 break;
16679 }
16680 }
16681
16682 el.setAttribute("href", urlPrefix + value);
16683
16684 if(formatterParams.target){
16685 el.setAttribute("target", formatterParams.target);
16686 }
16687
16688 if(formatterParams.download){
16689
16690 if(typeof download == "function"){
16691 download = download(cell);
16692 }else {
16693 download = download === true ? "" : download;
16694 }
16695
16696 el.setAttribute("download", download);
16697 }
16698
16699 el.innerHTML = this.emptyToSpace(this.sanitizeHTML(label));
16700
16701 return el;
16702 }else {
16703 return "&nbsp;";
16704 }
16705 }
16706
16707 function image(cell, formatterParams, onRendered){
16708 var el = document.createElement("img"),
16709 src = cell.getValue();
16710
16711 if(formatterParams.urlPrefix){
16712 src = formatterParams.urlPrefix + cell.getValue();
16713 }
16714
16715 if(formatterParams.urlSuffix){
16716 src = src + formatterParams.urlSuffix;
16717 }
16718
16719 el.setAttribute("src", src);
16720
16721 switch(typeof formatterParams.height){
16722 case "number":
16723 el.style.height = formatterParams.height + "px";
16724 break;
16725
16726 case "string":
16727 el.style.height = formatterParams.height;
16728 break;
16729 }
16730
16731 switch(typeof formatterParams.width){
16732 case "number":
16733 el.style.width = formatterParams.width + "px";
16734 break;
16735
16736 case "string":
16737 el.style.width = formatterParams.width;
16738 break;
16739 }
16740
16741 el.addEventListener("load", function(){
16742 cell.getRow().normalizeHeight();
16743 });
16744
16745 return el;
16746 }
16747
16748 function tickCross(cell, formatterParams, onRendered){
16749 var value = cell.getValue(),
16750 element = cell.getElement(),
16751 empty = formatterParams.allowEmpty,
16752 truthy = formatterParams.allowTruthy,
16753 trueValueSet = Object.keys(formatterParams).includes("trueValue"),
16754 tick = typeof formatterParams.tickElement !== "undefined" ? formatterParams.tickElement : '<svg enable-background="new 0 0 24 24" height="14" width="14" viewBox="0 0 24 24" xml:space="preserve" ><path fill="#2DC214" clip-rule="evenodd" d="M21.652,3.211c-0.293-0.295-0.77-0.295-1.061,0L9.41,14.34 c-0.293,0.297-0.771,0.297-1.062,0L3.449,9.351C3.304,9.203,3.114,9.13,2.923,9.129C2.73,9.128,2.534,9.201,2.387,9.351 l-2.165,1.946C0.078,11.445,0,11.63,0,11.823c0,0.194,0.078,0.397,0.223,0.544l4.94,5.184c0.292,0.296,0.771,0.776,1.062,1.07 l2.124,2.141c0.292,0.293,0.769,0.293,1.062,0l14.366-14.34c0.293-0.294,0.293-0.777,0-1.071L21.652,3.211z" fill-rule="evenodd"/></svg>',
16755 cross = typeof formatterParams.crossElement !== "undefined" ? formatterParams.crossElement : '<svg enable-background="new 0 0 24 24" height="14" width="14" viewBox="0 0 24 24" xml:space="preserve" ><path fill="#CE1515" d="M22.245,4.015c0.313,0.313,0.313,0.826,0,1.139l-6.276,6.27c-0.313,0.312-0.313,0.826,0,1.14l6.273,6.272 c0.313,0.313,0.313,0.826,0,1.14l-2.285,2.277c-0.314,0.312-0.828,0.312-1.142,0l-6.271-6.271c-0.313-0.313-0.828-0.313-1.141,0 l-6.276,6.267c-0.313,0.313-0.828,0.313-1.141,0l-2.282-2.28c-0.313-0.313-0.313-0.826,0-1.14l6.278-6.269 c0.313-0.312,0.313-0.826,0-1.14L1.709,5.147c-0.314-0.313-0.314-0.827,0-1.14l2.284-2.278C4.308,1.417,4.821,1.417,5.135,1.73 L11.405,8c0.314,0.314,0.828,0.314,1.141,0.001l6.276-6.267c0.312-0.312,0.826-0.312,1.141,0L22.245,4.015z"/></svg>';
16756
16757 if((trueValueSet && value === formatterParams.trueValue) || (!trueValueSet && ((truthy && value) || (value === true || value === "true" || value === "True" || value === 1 || value === "1")))){
16758 element.setAttribute("aria-checked", true);
16759 return tick || "";
16760 }else {
16761 if(empty && (value === "null" || value === "" || value === null || typeof value === "undefined")){
16762 element.setAttribute("aria-checked", "mixed");
16763 return "";
16764 }else {
16765 element.setAttribute("aria-checked", false);
16766 return cross || "";
16767 }
16768 }
16769 }
16770
16771 function datetime$1(cell, formatterParams, onRendered){
16772 var DT = this.table.dependencyRegistry.lookup(["luxon", "DateTime"], "DateTime");
16773 var inputFormat = formatterParams.inputFormat || "yyyy-MM-dd HH:mm:ss";
16774 var outputFormat = formatterParams.outputFormat || "dd/MM/yyyy HH:mm:ss";
16775 var invalid = typeof formatterParams.invalidPlaceholder !== "undefined" ? formatterParams.invalidPlaceholder : "";
16776 var value = cell.getValue();
16777
16778 if(typeof DT != "undefined"){
16779 var newDatetime;
16780
16781 if(DT.isDateTime(value)){
16782 newDatetime = value;
16783 }else if(inputFormat === "iso"){
16784 newDatetime = DT.fromISO(String(value));
16785 }else {
16786 newDatetime = DT.fromFormat(String(value), inputFormat);
16787 }
16788
16789 if(newDatetime.isValid){
16790 if(formatterParams.timezone){
16791 newDatetime = newDatetime.setZone(formatterParams.timezone);
16792 }
16793
16794 return newDatetime.toFormat(outputFormat);
16795 }else {
16796 if(invalid === true || !value){
16797 return value;
16798 }else if(typeof invalid === "function"){
16799 return invalid(value);
16800 }else {
16801 return invalid;
16802 }
16803 }
16804 }else {
16805 console.error("Format Error - 'datetime' formatter is dependant on luxon.js");
16806 }
16807 }
16808
16809 function datetimediff (cell, formatterParams, onRendered) {
16810 var DT = this.table.dependencyRegistry.lookup(["luxon", "DateTime"], "DateTime");
16811 var inputFormat = formatterParams.inputFormat || "yyyy-MM-dd HH:mm:ss";
16812 var invalid = typeof formatterParams.invalidPlaceholder !== "undefined" ? formatterParams.invalidPlaceholder : "";
16813 var suffix = typeof formatterParams.suffix !== "undefined" ? formatterParams.suffix : false;
16814 var unit = typeof formatterParams.unit !== "undefined" ? formatterParams.unit : "days";
16815 var humanize = typeof formatterParams.humanize !== "undefined" ? formatterParams.humanize : false;
16816 var date = typeof formatterParams.date !== "undefined" ? formatterParams.date : DT.now();
16817 var value = cell.getValue();
16818
16819 if(typeof DT != "undefined"){
16820 var newDatetime;
16821
16822 if(DT.isDateTime(value)){
16823 newDatetime = value;
16824 }else if(inputFormat === "iso"){
16825 newDatetime = DT.fromISO(String(value));
16826 }else {
16827 newDatetime = DT.fromFormat(String(value), inputFormat);
16828 }
16829
16830 if (newDatetime.isValid){
16831 if(humanize){
16832 return newDatetime.diff(date, unit).toHuman() + (suffix ? " " + suffix : "");
16833 }else {
16834 return parseInt(newDatetime.diff(date, unit)[unit]) + (suffix ? " " + suffix : "");
16835 }
16836 } else {
16837
16838 if (invalid === true) {
16839 return value;
16840 } else if (typeof invalid === "function") {
16841 return invalid(value);
16842 } else {
16843 return invalid;
16844 }
16845 }
16846 }else {
16847 console.error("Format Error - 'datetimediff' formatter is dependant on luxon.js");
16848 }
16849 }
16850
16851 function lookup (cell, formatterParams, onRendered) {
16852 var value = cell.getValue();
16853
16854 if (typeof formatterParams[value] === "undefined") {
16855 console.warn('Missing display value for ' + value);
16856 return value;
16857 }
16858
16859 return formatterParams[value];
16860 }
16861
16862 function star(cell, formatterParams, onRendered){
16863 var value = cell.getValue(),
16864 element = cell.getElement(),
16865 maxStars = formatterParams && formatterParams.stars ? formatterParams.stars : 5,
16866 stars = document.createElement("span"),
16867 star = document.createElementNS('http://www.w3.org/2000/svg', "svg"),
16868 starActive = '<polygon fill="#FFEA00" stroke="#C1AB60" stroke-width="37.6152" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" points="259.216,29.942 330.27,173.919 489.16,197.007 374.185,309.08 401.33,467.31 259.216,392.612 117.104,467.31 144.25,309.08 29.274,197.007 188.165,173.919 "/>',
16869 starInactive = '<polygon fill="#D2D2D2" stroke="#686868" stroke-width="37.6152" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" points="259.216,29.942 330.27,173.919 489.16,197.007 374.185,309.08 401.33,467.31 259.216,392.612 117.104,467.31 144.25,309.08 29.274,197.007 188.165,173.919 "/>';
16870
16871 //style stars holder
16872 stars.style.verticalAlign = "middle";
16873
16874 //style star
16875 star.setAttribute("width", "14");
16876 star.setAttribute("height", "14");
16877 star.setAttribute("viewBox", "0 0 512 512");
16878 star.setAttribute("xml:space", "preserve");
16879 star.style.padding = "0 1px";
16880
16881 value = value && !isNaN(value) ? parseInt(value) : 0;
16882
16883 value = Math.max(0, Math.min(value, maxStars));
16884
16885 for(var i=1;i<= maxStars;i++){
16886 var nextStar = star.cloneNode(true);
16887 nextStar.innerHTML = i <= value ? starActive : starInactive;
16888
16889 stars.appendChild(nextStar);
16890 }
16891
16892 element.style.whiteSpace = "nowrap";
16893 element.style.overflow = "hidden";
16894 element.style.textOverflow = "ellipsis";
16895
16896 element.setAttribute("aria-label", value);
16897
16898 return stars;
16899 }
16900
16901 function traffic(cell, formatterParams, onRendered){
16902 var value = this.sanitizeHTML(cell.getValue()) || 0,
16903 el = document.createElement("span"),
16904 max = formatterParams && formatterParams.max ? formatterParams.max : 100,
16905 min = formatterParams && formatterParams.min ? formatterParams.min : 0,
16906 colors = formatterParams && typeof formatterParams.color !== "undefined" ? formatterParams.color : ["red", "orange", "green"],
16907 color = "#666666",
16908 percent, percentValue;
16909
16910 if(isNaN(value) || typeof cell.getValue() === "undefined"){
16911 return;
16912 }
16913
16914 el.classList.add("tabulator-traffic-light");
16915
16916 //make sure value is in range
16917 percentValue = parseFloat(value) <= max ? parseFloat(value) : max;
16918 percentValue = parseFloat(percentValue) >= min ? parseFloat(percentValue) : min;
16919
16920 //workout percentage
16921 percent = (max - min) / 100;
16922 percentValue = Math.round((percentValue - min) / percent);
16923
16924 //set color
16925 switch(typeof colors){
16926 case "string":
16927 color = colors;
16928 break;
16929 case "function":
16930 color = colors(value);
16931 break;
16932 case "object":
16933 if(Array.isArray(colors)){
16934 var unit = 100 / colors.length;
16935 var index = Math.floor(percentValue / unit);
16936
16937 index = Math.min(index, colors.length - 1);
16938 index = Math.max(index, 0);
16939 color = colors[index];
16940 break;
16941 }
16942 }
16943
16944 el.style.backgroundColor = color;
16945
16946 return el;
16947 }
16948
16949 function progress(cell, formatterParams = {}, onRendered){ //progress bar
16950 var value = this.sanitizeHTML(cell.getValue()) || 0,
16951 element = cell.getElement(),
16952 max = formatterParams.max ? formatterParams.max : 100,
16953 min = formatterParams.min ? formatterParams.min : 0,
16954 legendAlign = formatterParams.legendAlign ? formatterParams.legendAlign : "center",
16955 percent, percentValue, color, legend, legendColor;
16956
16957 //make sure value is in range
16958 percentValue = parseFloat(value) <= max ? parseFloat(value) : max;
16959 percentValue = parseFloat(percentValue) >= min ? parseFloat(percentValue) : min;
16960
16961 //workout percentage
16962 percent = (max - min) / 100;
16963 percentValue = Math.round((percentValue - min) / percent);
16964
16965 //set bar color
16966 switch(typeof formatterParams.color){
16967 case "string":
16968 color = formatterParams.color;
16969 break;
16970 case "function":
16971 color = formatterParams.color(value);
16972 break;
16973 case "object":
16974 if(Array.isArray(formatterParams.color)){
16975 let unit = 100 / formatterParams.color.length;
16976 let index = Math.floor(percentValue / unit);
16977
16978 index = Math.min(index, formatterParams.color.length - 1);
16979 index = Math.max(index, 0);
16980 color = formatterParams.color[index];
16981 break;
16982 }
16983 default:
16984 color = "#2DC214";
16985 }
16986
16987 //generate legend
16988 switch(typeof formatterParams.legend){
16989 case "string":
16990 legend = formatterParams.legend;
16991 break;
16992 case "function":
16993 legend = formatterParams.legend(value);
16994 break;
16995 case "boolean":
16996 legend = value;
16997 break;
16998 default:
16999 legend = false;
17000 }
17001
17002 //set legend color
17003 switch(typeof formatterParams.legendColor){
17004 case "string":
17005 legendColor = formatterParams.legendColor;
17006 break;
17007 case "function":
17008 legendColor = formatterParams.legendColor(value);
17009 break;
17010 case "object":
17011 if(Array.isArray(formatterParams.legendColor)){
17012 let unit = 100 / formatterParams.legendColor.length;
17013 let index = Math.floor(percentValue / unit);
17014
17015 index = Math.min(index, formatterParams.legendColor.length - 1);
17016 index = Math.max(index, 0);
17017 legendColor = formatterParams.legendColor[index];
17018 }
17019 break;
17020 default:
17021 legendColor = "#000";
17022 }
17023
17024 element.style.minWidth = "30px";
17025 element.style.position = "relative";
17026
17027 element.setAttribute("aria-label", percentValue);
17028
17029 var barEl = document.createElement("div");
17030 barEl.style.display = "inline-block";
17031 barEl.style.width = percentValue + "%";
17032 barEl.style.backgroundColor = color;
17033 barEl.style.height = "100%";
17034
17035 barEl.setAttribute('data-max', max);
17036 barEl.setAttribute('data-min', min);
17037
17038 var barContainer = document.createElement("div");
17039 barContainer.style.position = "relative";
17040 barContainer.style.width = "100%";
17041 barContainer.style.height = "100%";
17042
17043 if(legend){
17044 var legendEl = document.createElement("div");
17045 legendEl.style.position = "absolute";
17046 legendEl.style.top = 0;
17047 legendEl.style.left = 0;
17048 legendEl.style.textAlign = legendAlign;
17049 legendEl.style.width = "100%";
17050 legendEl.style.color = legendColor;
17051 legendEl.innerHTML = legend;
17052 }
17053
17054 onRendered(function(){
17055
17056 //handle custom element needed if formatter is to be included in printed/downloaded output
17057 if(!(cell instanceof CellComponent)){
17058 var holderEl = document.createElement("div");
17059 holderEl.style.position = "absolute";
17060 holderEl.style.top = "4px";
17061 holderEl.style.bottom = "4px";
17062 holderEl.style.left = "4px";
17063 holderEl.style.right = "4px";
17064
17065 element.appendChild(holderEl);
17066
17067 element = holderEl;
17068 }
17069
17070 element.appendChild(barContainer);
17071 barContainer.appendChild(barEl);
17072
17073 if(legend){
17074 barContainer.appendChild(legendEl);
17075 }
17076 });
17077
17078 return "";
17079 }
17080
17081 function color(cell, formatterParams, onRendered){
17082 cell.getElement().style.backgroundColor = this.sanitizeHTML(cell.getValue());
17083 return "";
17084 }
17085
17086 function buttonTick(cell, formatterParams, onRendered){
17087 return '<svg enable-background="new 0 0 24 24" height="14" width="14" viewBox="0 0 24 24" xml:space="preserve" ><path fill="#2DC214" clip-rule="evenodd" d="M21.652,3.211c-0.293-0.295-0.77-0.295-1.061,0L9.41,14.34 c-0.293,0.297-0.771,0.297-1.062,0L3.449,9.351C3.304,9.203,3.114,9.13,2.923,9.129C2.73,9.128,2.534,9.201,2.387,9.351 l-2.165,1.946C0.078,11.445,0,11.63,0,11.823c0,0.194,0.078,0.397,0.223,0.544l4.94,5.184c0.292,0.296,0.771,0.776,1.062,1.07 l2.124,2.141c0.292,0.293,0.769,0.293,1.062,0l14.366-14.34c0.293-0.294,0.293-0.777,0-1.071L21.652,3.211z" fill-rule="evenodd"/></svg>';
17088 }
17089
17090 function buttonCross(cell, formatterParams, onRendered){
17091 return '<svg enable-background="new 0 0 24 24" height="14" width="14" viewBox="0 0 24 24" xml:space="preserve" ><path fill="#CE1515" d="M22.245,4.015c0.313,0.313,0.313,0.826,0,1.139l-6.276,6.27c-0.313,0.312-0.313,0.826,0,1.14l6.273,6.272 c0.313,0.313,0.313,0.826,0,1.14l-2.285,2.277c-0.314,0.312-0.828,0.312-1.142,0l-6.271-6.271c-0.313-0.313-0.828-0.313-1.141,0 l-6.276,6.267c-0.313,0.313-0.828,0.313-1.141,0l-2.282-2.28c-0.313-0.313-0.313-0.826,0-1.14l6.278-6.269 c0.313-0.312,0.313-0.826,0-1.14L1.709,5.147c-0.314-0.313-0.314-0.827,0-1.14l2.284-2.278C4.308,1.417,4.821,1.417,5.135,1.73 L11.405,8c0.314,0.314,0.828,0.314,1.141,0.001l6.276-6.267c0.312-0.312,0.826-0.312,1.141,0L22.245,4.015z"/></svg>';
17092 }
17093
17094 function toggle(cell, formatterParams, onRendered){
17095 var value = cell.getValue(),
17096 size = formatterParams.size ||15,
17097 sizePx = size + "px",
17098 containEl, switchEl,
17099 onValue = formatterParams.hasOwnProperty("onValue") ? formatterParams.onValue : true,
17100 offValue = formatterParams.hasOwnProperty("offValue") ? formatterParams.offValue : false,
17101
17102
17103 state = formatterParams.onTruthy ? value : value === onValue;
17104
17105
17106 containEl = document.createElement("div");
17107 containEl.classList.add("tabulator-toggle");
17108
17109 if(state){
17110 containEl.classList.add("tabulator-toggle-on");
17111 containEl.style.flexDirection = "row-reverse";
17112
17113 if(formatterParams.onColor){
17114 containEl.style.background = formatterParams.onColor;
17115 }
17116 }else {
17117 if(formatterParams.offColor){
17118 containEl.style.background = formatterParams.offColor;
17119 }
17120 }
17121
17122 containEl.style.width = (2.5 * size) + "px";
17123 containEl.style.borderRadius = sizePx;
17124
17125 if(formatterParams.clickable){
17126 containEl.addEventListener("click", (e) => {
17127 cell.setValue(state ? offValue : onValue);
17128 });
17129 }
17130
17131 switchEl = document.createElement("div");
17132 switchEl.classList.add("tabulator-toggle-switch");
17133
17134 switchEl.style.height = sizePx;
17135 switchEl.style.width = sizePx;
17136 switchEl.style.borderRadius = sizePx;
17137
17138 containEl.appendChild(switchEl);
17139
17140 return containEl;
17141 }
17142
17143 function rownum(cell, formatterParams, onRendered){
17144 var content = document.createElement("span");
17145 var row = cell.getRow();
17146 var table = cell.getTable();
17147
17148 row.watchPosition((position) => {
17149 if (formatterParams.relativeToPage) {
17150 position += table.modules.page.getPageSize() * (table.modules.page.getPage() - 1);
17151 }
17152 content.innerText = position;
17153 });
17154
17155 return content;
17156 }
17157
17158 function handle(cell, formatterParams, onRendered){
17159 cell.getElement().classList.add("tabulator-row-handle");
17160 return "<div class='tabulator-row-handle-box'><div class='tabulator-row-handle-bar'></div><div class='tabulator-row-handle-bar'></div><div class='tabulator-row-handle-bar'></div></div>";
17161 }
17162
17163 function adaptable(cell, params, onRendered){
17164 var lookup, formatterFunc, formatterParams;
17165
17166 function defaultLookup(cell){
17167 var value = cell.getValue(),
17168 formatter = "plaintext";
17169
17170 switch(typeof value){
17171 case "boolean":
17172 formatter = "tickCross";
17173 break;
17174
17175 case "string":
17176 if(value.includes("\n")){
17177 formatter = "textarea";
17178 }
17179 break;
17180 }
17181
17182 return formatter;
17183 }
17184
17185 lookup = params.formatterLookup ? params.formatterLookup(cell) : defaultLookup(cell);
17186
17187 if(params.paramsLookup){
17188 formatterParams = typeof params.paramsLookup === "function" ? params.paramsLookup(lookup, cell) : params.paramsLookup[lookup];
17189 }
17190
17191 formatterFunc = this.table.modules.format.lookupFormatter(lookup);
17192
17193 return formatterFunc.call(this, cell, formatterParams || {}, onRendered);
17194 }
17195
17196 function array$2(cell, formatterParams, onRendered){
17197 var delimiter = formatterParams.delimiter || ",",
17198 value = cell.getValue(),
17199 table = this.table,
17200 valueMap;
17201
17202 if(formatterParams.valueMap){
17203 if(typeof formatterParams.valueMap === "string"){
17204 valueMap = function(value){
17205 return value.map((item) => {
17206 return Helpers.retrieveNestedData(table.options.nestedFieldSeparator, formatterParams.valueMap, item);
17207 });
17208 };
17209 }else {
17210 valueMap = formatterParams.valueMap;
17211 }
17212 }
17213
17214 if(Array.isArray(value)){
17215 if(valueMap){
17216 value = valueMap(value);
17217 }
17218
17219 return value.join(delimiter);
17220 }else {
17221 return value;
17222 }
17223 }
17224
17225 function json$1(cell, formatterParams, onRendered){
17226 var indent = formatterParams.indent || "\t",
17227 multiline = typeof formatterParams.multiline === "undefined" ? true : formatterParams.multiline,
17228 replacer = formatterParams.replacer || null,
17229 value = cell.getValue();
17230
17231 if(multiline){
17232 cell.getElement().style.whiteSpace = "pre-wrap";
17233 }
17234
17235 return JSON.stringify(value, replacer, indent);
17236 }
17237
17238 var defaultFormatters = {
17239 plaintext:plaintext,
17240 html:html,
17241 textarea:textarea,
17242 money:money,
17243 link:link,
17244 image:image,
17245 tickCross:tickCross,
17246 datetime:datetime$1,
17247 datetimediff:datetimediff,
17248 lookup:lookup,
17249 star:star,
17250 traffic:traffic,
17251 progress:progress,
17252 color:color,
17253 buttonTick:buttonTick,
17254 buttonCross:buttonCross,
17255 toggle:toggle,
17256 rownum:rownum,
17257 handle:handle,
17258 adaptable:adaptable,
17259 array:array$2,
17260 json:json$1,
17261 };
17262
17263 class Format extends Module{
17264
17265 static moduleName = "format";
17266
17267 //load defaults
17268 static formatters = defaultFormatters;
17269
17270 constructor(table){
17271 super(table);
17272
17273 this.registerColumnOption("formatter");
17274 this.registerColumnOption("formatterParams");
17275
17276 this.registerColumnOption("formatterPrint");
17277 this.registerColumnOption("formatterPrintParams");
17278 this.registerColumnOption("formatterClipboard");
17279 this.registerColumnOption("formatterClipboardParams");
17280 this.registerColumnOption("formatterHtmlOutput");
17281 this.registerColumnOption("formatterHtmlOutputParams");
17282 this.registerColumnOption("titleFormatter");
17283 this.registerColumnOption("titleFormatterParams");
17284 }
17285
17286 initialize(){
17287 this.subscribe("cell-format", this.formatValue.bind(this));
17288 this.subscribe("cell-rendered", this.cellRendered.bind(this));
17289 this.subscribe("column-layout", this.initializeColumn.bind(this));
17290 this.subscribe("column-format", this.formatHeader.bind(this));
17291 }
17292
17293 //initialize column formatter
17294 initializeColumn(column){
17295 column.modules.format = this.lookupTypeFormatter(column, "");
17296
17297 if(typeof column.definition.formatterPrint !== "undefined"){
17298 column.modules.format.print = this.lookupTypeFormatter(column, "Print");
17299 }
17300
17301 if(typeof column.definition.formatterClipboard !== "undefined"){
17302 column.modules.format.clipboard = this.lookupTypeFormatter(column, "Clipboard");
17303 }
17304
17305 if(typeof column.definition.formatterHtmlOutput !== "undefined"){
17306 column.modules.format.htmlOutput = this.lookupTypeFormatter(column, "HtmlOutput");
17307 }
17308 }
17309
17310 lookupTypeFormatter(column, type){
17311 var config = {params:column.definition["formatter" + type + "Params"] || {}},
17312 formatter = column.definition["formatter" + type];
17313
17314 config.formatter = this.lookupFormatter(formatter);
17315
17316 return config;
17317 }
17318
17319
17320 lookupFormatter(formatter){
17321 var formatterFunc;
17322
17323 //set column formatter
17324 switch(typeof formatter){
17325 case "string":
17326 if(Format.formatters[formatter]){
17327 formatterFunc = Format.formatters[formatter];
17328 }else {
17329 console.warn("Formatter Error - No such formatter found: ", formatter);
17330 formatterFunc = Format.formatters.plaintext;
17331 }
17332 break;
17333
17334 case "function":
17335 formatterFunc = formatter;
17336 break;
17337
17338 default:
17339 formatterFunc = Format.formatters.plaintext;
17340 break;
17341 }
17342
17343 return formatterFunc;
17344 }
17345
17346 cellRendered(cell){
17347 if(cell.modules.format && cell.modules.format.renderedCallback && !cell.modules.format.rendered){
17348 cell.modules.format.renderedCallback();
17349 cell.modules.format.rendered = true;
17350 }
17351 }
17352
17353 //return a formatted value for a column header
17354 formatHeader(column, title, el){
17355 var formatter, params, onRendered, mockCell;
17356
17357 if(column.definition.titleFormatter){
17358 formatter = this.lookupFormatter(column.definition.titleFormatter);
17359
17360 onRendered = (callback) => {
17361 column.titleFormatterRendered = callback;
17362 };
17363
17364 mockCell = {
17365 getValue:function(){
17366 return title;
17367 },
17368 getElement:function(){
17369 return el;
17370 },
17371 getType:function(){
17372 return "header";
17373 },
17374 getColumn:function(){
17375 return column.getComponent();
17376 },
17377 getTable:() => {
17378 return this.table;
17379 }
17380 };
17381
17382 params = column.definition.titleFormatterParams || {};
17383
17384 params = typeof params === "function" ? params() : params;
17385
17386 return formatter.call(this, mockCell, params, onRendered);
17387 }else {
17388 return title;
17389 }
17390 }
17391
17392
17393 //return a formatted value for a cell
17394 formatValue(cell){
17395 var component = cell.getComponent(),
17396 params = typeof cell.column.modules.format.params === "function" ? cell.column.modules.format.params(component) : cell.column.modules.format.params;
17397
17398 function onRendered(callback){
17399 if(!cell.modules.format){
17400 cell.modules.format = {};
17401 }
17402
17403 cell.modules.format.renderedCallback = callback;
17404 cell.modules.format.rendered = false;
17405 }
17406
17407 return cell.column.modules.format.formatter.call(this, component, params, onRendered);
17408 }
17409
17410 formatExportValue(cell, type){
17411 var formatter = cell.column.modules.format[type],
17412 params;
17413
17414 if(formatter){
17415 params = typeof formatter.params === "function" ? formatter.params(cell.getComponent()) : formatter.params;
17416
17417 function onRendered(callback){
17418 if(!cell.modules.format){
17419 cell.modules.format = {};
17420 }
17421
17422 cell.modules.format.renderedCallback = callback;
17423 cell.modules.format.rendered = false;
17424 }
17425
17426 return formatter.formatter.call(this, cell.getComponent(), params, onRendered);
17427
17428 }else {
17429 return this.formatValue(cell);
17430 }
17431 }
17432
17433 sanitizeHTML(value){
17434 if(value){
17435 var entityMap = {
17436 '&': '&amp;',
17437 '<': '&lt;',
17438 '>': '&gt;',
17439 '"': '&quot;',
17440 "'": '&#39;',
17441 '/': '&#x2F;',
17442 '`': '&#x60;',
17443 '=': '&#x3D;'
17444 };
17445
17446 return String(value).replace(/[&<>"'`=/]/g, function (s) {
17447 return entityMap[s];
17448 });
17449 }else {
17450 return value;
17451 }
17452 }
17453
17454 emptyToSpace(value){
17455 return value === null || typeof value === "undefined" || value === "" ? "&nbsp;" : value;
17456 }
17457
17458 }
17459
17460 class FrozenColumns extends Module{
17461
17462 static moduleName = "frozenColumns";
17463
17464 constructor(table){
17465 super(table);
17466
17467 this.leftColumns = [];
17468 this.rightColumns = [];
17469 this.initializationMode = "left";
17470 this.active = false;
17471 this.blocked = true;
17472
17473 this.registerColumnOption("frozen");
17474 }
17475
17476 //reset initial state
17477 reset(){
17478 this.initializationMode = "left";
17479 this.leftColumns = [];
17480 this.rightColumns = [];
17481 this.active = false;
17482 }
17483
17484 initialize(){
17485 this.subscribe("cell-layout", this.layoutCell.bind(this));
17486 this.subscribe("column-init", this.initializeColumn.bind(this));
17487 this.subscribe("column-width", this.layout.bind(this));
17488 this.subscribe("row-layout-after", this.layoutRow.bind(this));
17489 this.subscribe("table-layout", this.layout.bind(this));
17490 this.subscribe("columns-loading", this.reset.bind(this));
17491
17492 this.subscribe("column-add", this.reinitializeColumns.bind(this));
17493 this.subscribe("column-deleted", this.reinitializeColumns.bind(this));
17494 this.subscribe("column-hide", this.reinitializeColumns.bind(this));
17495 this.subscribe("column-show", this.reinitializeColumns.bind(this));
17496 this.subscribe("columns-loaded", this.reinitializeColumns.bind(this));
17497
17498 this.subscribe("table-redraw", this.layout.bind(this));
17499 this.subscribe("layout-refreshing", this.blockLayout.bind(this));
17500 this.subscribe("layout-refreshed", this.unblockLayout.bind(this));
17501 this.subscribe("scrollbar-vertical", this.adjustForScrollbar.bind(this));
17502 }
17503
17504 blockLayout(){
17505 this.blocked = true;
17506 }
17507
17508 unblockLayout(){
17509 this.blocked = false;
17510 }
17511
17512 layoutCell(cell){
17513 this.layoutElement(cell.element, cell.column);
17514 }
17515
17516 reinitializeColumns(){
17517 this.reset();
17518
17519 this.table.columnManager.columnsByIndex.forEach((column) => {
17520 this.initializeColumn(column);
17521 });
17522
17523 this.layout();
17524 }
17525
17526 //initialize specific column
17527 initializeColumn(column){
17528 var config = {margin:0, edge:false};
17529
17530 if(!column.isGroup){
17531 if(this.frozenCheck(column)){
17532 config.position = this.initializationMode;
17533
17534 if(this.initializationMode == "left"){
17535 this.leftColumns.push(column);
17536 }else {
17537 this.rightColumns.unshift(column);
17538 }
17539
17540 this.active = true;
17541
17542 column.modules.frozen = config;
17543 }else {
17544 this.initializationMode = "right";
17545 }
17546 }
17547 }
17548
17549 frozenCheck(column){
17550 if(column.parent.isGroup && column.definition.frozen){
17551 console.warn("Frozen Column Error - Parent column group must be frozen, not individual columns or sub column groups");
17552 }
17553
17554 if(column.parent.isGroup){
17555 return this.frozenCheck(column.parent);
17556 }else {
17557 return column.definition.frozen;
17558 }
17559 }
17560
17561 //layout calculation rows
17562 layoutCalcRows(){
17563 if(this.table.modExists("columnCalcs")){
17564 if(this.table.modules.columnCalcs.topInitialized && this.table.modules.columnCalcs.topRow){
17565 this.layoutRow(this.table.modules.columnCalcs.topRow);
17566 }
17567
17568 if(this.table.modules.columnCalcs.botInitialized && this.table.modules.columnCalcs.botRow){
17569 this.layoutRow(this.table.modules.columnCalcs.botRow);
17570 }
17571
17572 if(this.table.modExists("groupRows")){
17573 this.layoutGroupCalcs(this.table.modules.groupRows.getGroups());
17574 }
17575 }
17576 }
17577
17578 layoutGroupCalcs(groups){
17579 groups.forEach((group) => {
17580 if(group.calcs.top){
17581 this.layoutRow(group.calcs.top);
17582 }
17583
17584 if(group.calcs.bottom){
17585 this.layoutRow(group.calcs.bottom);
17586 }
17587
17588 if(group.groupList && group.groupList.length){
17589 this.layoutGroupCalcs(group.groupList);
17590 }
17591 });
17592 }
17593
17594 //calculate column positions and layout headers
17595 layoutColumnPosition(allCells){
17596 var leftParents = [];
17597
17598 var leftMargin = 0;
17599 var rightMargin = 0;
17600
17601 this.leftColumns.forEach((column, i) => {
17602 column.modules.frozen.marginValue = leftMargin;
17603 column.modules.frozen.margin = column.modules.frozen.marginValue + "px";
17604
17605 if(column.visible){
17606 leftMargin += column.getWidth();
17607 }
17608
17609 if(i == this.leftColumns.length - 1){
17610 column.modules.frozen.edge = true;
17611 }else {
17612 column.modules.frozen.edge = false;
17613 }
17614
17615 if(column.parent.isGroup){
17616 var parentEl = this.getColGroupParentElement(column);
17617 if(!leftParents.includes(parentEl)){
17618 this.layoutElement(parentEl, column);
17619 leftParents.push(parentEl);
17620 }
17621
17622 parentEl.classList.toggle("tabulator-frozen-left", column.modules.frozen.edge && column.modules.frozen.position === "left");
17623 parentEl.classList.toggle("tabulator-frozen-right", column.modules.frozen.edge && column.modules.frozen.position === "right");
17624 }else {
17625 this.layoutElement(column.getElement(), column);
17626 }
17627
17628 if(allCells){
17629 column.cells.forEach((cell) => {
17630 this.layoutElement(cell.getElement(true), column);
17631 });
17632 }
17633 });
17634
17635 this.rightColumns.forEach((column, i) => {
17636
17637 column.modules.frozen.marginValue = rightMargin;
17638 column.modules.frozen.margin = column.modules.frozen.marginValue + "px";
17639
17640 if(column.visible){
17641 rightMargin += column.getWidth();
17642 }
17643
17644 if(i == this.rightColumns.length - 1){
17645 column.modules.frozen.edge = true;
17646 }else {
17647 column.modules.frozen.edge = false;
17648 }
17649
17650 if(column.parent.isGroup){
17651 this.layoutElement(this.getColGroupParentElement(column), column);
17652 }else {
17653 this.layoutElement(column.getElement(), column);
17654 }
17655
17656 if(allCells){
17657 column.cells.forEach((cell) => {
17658 this.layoutElement(cell.getElement(true), column);
17659 });
17660 }
17661 });
17662 }
17663
17664 getColGroupParentElement(column){
17665 return column.parent.isGroup ? this.getColGroupParentElement(column.parent) : column.getElement();
17666 }
17667
17668 //layout columns appropriately
17669 layout(){
17670 if(this.active && !this.blocked){
17671 //calculate left columns
17672 this.layoutColumnPosition();
17673
17674 this.reinitializeRows();
17675
17676 this.layoutCalcRows();
17677 }
17678 }
17679
17680 reinitializeRows(){
17681 var visibleRows = this.table.rowManager.getVisibleRows(true);
17682 var otherRows = this.table.rowManager.getRows().filter(row => !visibleRows.includes(row));
17683
17684 otherRows.forEach((row) =>{
17685 row.deinitialize();
17686 });
17687
17688 visibleRows.forEach((row) =>{
17689 if(row.type === "row"){
17690 this.layoutRow(row);
17691 }
17692 });
17693 }
17694
17695 layoutRow(row){
17696 if(this.table.options.layout === "fitDataFill" && this.rightColumns.length){
17697 this.table.rowManager.getTableElement().style.minWidth = "calc(100% - " + this.rightMargin + ")";
17698 }
17699
17700 this.leftColumns.forEach((column) => {
17701 var cell = row.getCell(column);
17702
17703 if(cell){
17704 this.layoutElement(cell.getElement(true), column);
17705 }
17706 });
17707
17708 this.rightColumns.forEach((column) => {
17709 var cell = row.getCell(column);
17710
17711 if(cell){
17712 this.layoutElement(cell.getElement(true), column);
17713 }
17714 });
17715 }
17716
17717 layoutElement(element, column){
17718 var position;
17719
17720 if(column.modules.frozen && element){
17721 element.style.position = "sticky";
17722
17723 if(this.table.rtl){
17724 position = column.modules.frozen.position === "left" ? "right" : "left";
17725 }else {
17726 position = column.modules.frozen.position;
17727 }
17728
17729 element.style[position] = column.modules.frozen.margin;
17730
17731 element.classList.add("tabulator-frozen");
17732
17733 element.classList.toggle("tabulator-frozen-left", column.modules.frozen.edge && column.modules.frozen.position === "left");
17734 element.classList.toggle("tabulator-frozen-right", column.modules.frozen.edge && column.modules.frozen.position === "right");
17735 }
17736 }
17737
17738 adjustForScrollbar(width){
17739 if(this.rightColumns.length){
17740 this.table.columnManager.getContentsElement().style.width = "calc(100% - " + width + "px)";
17741 }
17742 }
17743
17744 getFrozenColumns(){
17745 return this.leftColumns.concat(this.rightColumns);
17746 }
17747
17748 _calcSpace(columns, index){
17749 var width = 0;
17750
17751 for (let i = 0; i < index; i++){
17752 if(columns[i].visible){
17753 width += columns[i].getWidth();
17754 }
17755 }
17756
17757 return width;
17758 }
17759 }
17760
17761 class FrozenRows extends Module{
17762
17763 static moduleName = "frozenRows";
17764
17765 constructor(table){
17766 super(table);
17767
17768 this.topElement = document.createElement("div");
17769 this.rows = [];
17770
17771 //register component functions
17772 this.registerComponentFunction("row", "freeze", this.freezeRow.bind(this));
17773 this.registerComponentFunction("row", "unfreeze", this.unfreezeRow.bind(this));
17774 this.registerComponentFunction("row", "isFrozen", this.isRowFrozen.bind(this));
17775
17776 //register table options
17777 this.registerTableOption("frozenRowsField", "id"); //field to choose frozen rows by
17778 this.registerTableOption("frozenRows", false); //holder for frozen row identifiers
17779 }
17780
17781 initialize(){
17782 var fragment = document.createDocumentFragment();
17783
17784 this.rows = [];
17785
17786 this.topElement.classList.add("tabulator-frozen-rows-holder");
17787
17788 fragment.appendChild(document.createElement("br"));
17789 fragment.appendChild(this.topElement);
17790
17791 // this.table.columnManager.element.append(this.topElement);
17792 this.table.columnManager.getContentsElement().insertBefore(fragment, this.table.columnManager.headersElement.nextSibling);
17793
17794 this.subscribe("row-deleting", this.detachRow.bind(this));
17795 this.subscribe("rows-visible", this.visibleRows.bind(this));
17796
17797 this.registerDisplayHandler(this.getRows.bind(this), 10);
17798
17799 if(this.table.options.frozenRows){
17800 this.subscribe("data-processed", this.initializeRows.bind(this));
17801 this.subscribe("row-added", this.initializeRow.bind(this));
17802 this.subscribe("table-redrawing", this.resizeHolderWidth.bind(this));
17803 this.subscribe("column-resized", this.resizeHolderWidth.bind(this));
17804 this.subscribe("column-show", this.resizeHolderWidth.bind(this));
17805 this.subscribe("column-hide", this.resizeHolderWidth.bind(this));
17806 }
17807
17808 this.resizeHolderWidth();
17809 }
17810
17811 resizeHolderWidth(){
17812 this.topElement.style.minWidth = this.table.columnManager.headersElement.offsetWidth + "px";
17813 }
17814
17815 initializeRows(){
17816 this.table.rowManager.getRows().forEach((row) => {
17817 this.initializeRow(row);
17818 });
17819 }
17820
17821 initializeRow(row){
17822 var frozenRows = this.table.options.frozenRows,
17823 rowType = typeof frozenRows;
17824
17825 if(rowType === "number"){
17826 if(row.getPosition() && (row.getPosition() + this.rows.length) <= frozenRows){
17827 this.freezeRow(row);
17828 }
17829 }else if(rowType === "function"){
17830 if(frozenRows.call(this.table, row.getComponent())){
17831 this.freezeRow(row);
17832 }
17833 }else if(Array.isArray(frozenRows)){
17834 if(frozenRows.includes(row.data[this.options("frozenRowsField")])){
17835 this.freezeRow(row);
17836 }
17837 }
17838 }
17839
17840 isRowFrozen(row){
17841 var index = this.rows.indexOf(row);
17842 return index > -1;
17843 }
17844
17845 isFrozen(){
17846 return !!this.rows.length;
17847 }
17848
17849 visibleRows(viewable, rows){
17850 this.rows.forEach((row) => {
17851 rows.push(row);
17852 });
17853
17854 return rows;
17855 }
17856
17857 //filter frozen rows out of display data
17858 getRows(rows){
17859 var output = rows.slice(0);
17860
17861 this.rows.forEach(function(row){
17862 var index = output.indexOf(row);
17863
17864 if(index > -1){
17865 output.splice(index, 1);
17866 }
17867 });
17868
17869 return output;
17870 }
17871
17872 freezeRow(row){
17873 if(!row.modules.frozen){
17874 row.modules.frozen = true;
17875 this.topElement.appendChild(row.getElement());
17876 row.initialize();
17877 row.normalizeHeight();
17878
17879 this.rows.push(row);
17880
17881 this.refreshData(false, "display");
17882
17883 this.table.rowManager.adjustTableSize();
17884
17885 this.styleRows();
17886
17887 }else {
17888 console.warn("Freeze Error - Row is already frozen");
17889 }
17890 }
17891
17892 unfreezeRow(row){
17893 if(row.modules.frozen){
17894
17895 row.modules.frozen = false;
17896
17897 this.detachRow(row);
17898
17899 this.table.rowManager.adjustTableSize();
17900
17901 this.refreshData(false, "display");
17902
17903 if(this.rows.length){
17904 this.styleRows();
17905 }
17906
17907 }else {
17908 console.warn("Freeze Error - Row is already unfrozen");
17909 }
17910 }
17911
17912 detachRow(row){
17913 var index = this.rows.indexOf(row);
17914
17915 if(index > -1){
17916 var rowEl = row.getElement();
17917
17918 if(rowEl.parentNode){
17919 rowEl.parentNode.removeChild(rowEl);
17920 }
17921
17922 this.rows.splice(index, 1);
17923 }
17924 }
17925
17926 styleRows(row){
17927 this.rows.forEach((row, i) => {
17928 this.table.rowManager.styleRow(row, i);
17929 });
17930 }
17931 }
17932
17933 //public group object
17934 class GroupComponent {
17935 constructor (group){
17936 this._group = group;
17937 this.type = "GroupComponent";
17938
17939 return new Proxy(this, {
17940 get: function(target, name, receiver) {
17941 if (typeof target[name] !== "undefined") {
17942 return target[name];
17943 }else {
17944 return target._group.groupManager.table.componentFunctionBinder.handle("group", target._group, name);
17945 }
17946 }
17947 });
17948 }
17949
17950 getKey(){
17951 return this._group.key;
17952 }
17953
17954 getField(){
17955 return this._group.field;
17956 }
17957
17958 getElement(){
17959 return this._group.element;
17960 }
17961
17962 getRows(){
17963 return this._group.getRows(true);
17964 }
17965
17966 getSubGroups(){
17967 return this._group.getSubGroups(true);
17968 }
17969
17970 getParentGroup(){
17971 return this._group.parent ? this._group.parent.getComponent() : false;
17972 }
17973
17974 isVisible(){
17975 return this._group.visible;
17976 }
17977
17978 show(){
17979 this._group.show();
17980 }
17981
17982 hide(){
17983 this._group.hide();
17984 }
17985
17986 toggle(){
17987 this._group.toggleVisibility();
17988 }
17989
17990 scrollTo(position, ifVisible){
17991 return this._group.groupManager.table.rowManager.scrollToRow(this._group, position, ifVisible);
17992 }
17993
17994 _getSelf(){
17995 return this._group;
17996 }
17997
17998 getTable(){
17999 return this._group.groupManager.table;
18000 }
18001 }
18002
18003 //Group functions
18004 class Group{
18005
18006 constructor(groupManager, parent, level, key, field, generator, oldGroup){
18007 this.groupManager = groupManager;
18008 this.parent = parent;
18009 this.key = key;
18010 this.level = level;
18011 this.field = field;
18012 this.hasSubGroups = level < (groupManager.groupIDLookups.length - 1);
18013 this.addRow = this.hasSubGroups ? this._addRowToGroup : this._addRow;
18014 this.type = "group"; //type of element
18015 this.old = oldGroup;
18016 this.rows = [];
18017 this.groups = [];
18018 this.groupList = [];
18019 this.generator = generator;
18020 this.element = false;
18021 this.elementContents = false;
18022 this.height = 0;
18023 this.outerHeight = 0;
18024 this.initialized = false;
18025 this.calcs = {};
18026 this.initialized = false;
18027 this.modules = {};
18028 this.arrowElement = false;
18029
18030 this.visible = oldGroup ? oldGroup.visible : (typeof groupManager.startOpen[level] !== "undefined" ? groupManager.startOpen[level] : groupManager.startOpen[0]);
18031
18032 this.component = null;
18033
18034 this.createElements();
18035 this.addBindings();
18036
18037 this.createValueGroups();
18038 }
18039
18040 wipe(elementsOnly){
18041 if(!elementsOnly){
18042 if(this.groupList.length){
18043 this.groupList.forEach(function(group){
18044 group.wipe();
18045 });
18046 }else {
18047 this.rows.forEach((row) => {
18048 if(row.modules){
18049 delete row.modules.group;
18050 }
18051 });
18052 }
18053 }
18054
18055 this.element = false;
18056 this.arrowElement = false;
18057 this.elementContents = false;
18058 }
18059
18060 createElements(){
18061 var arrow = document.createElement("div");
18062 arrow.classList.add("tabulator-arrow");
18063
18064 this.element = document.createElement("div");
18065 this.element.classList.add("tabulator-row");
18066 this.element.classList.add("tabulator-group");
18067 this.element.classList.add("tabulator-group-level-" + this.level);
18068 this.element.setAttribute("role", "rowgroup");
18069
18070 this.arrowElement = document.createElement("div");
18071 this.arrowElement.classList.add("tabulator-group-toggle");
18072 this.arrowElement.appendChild(arrow);
18073
18074 //setup movable rows
18075 if(this.groupManager.table.options.movableRows !== false && this.groupManager.table.modExists("moveRow")){
18076 this.groupManager.table.modules.moveRow.initializeGroupHeader(this);
18077 }
18078 }
18079
18080 createValueGroups(){
18081 var level = this.level + 1;
18082 if(this.groupManager.allowedValues && this.groupManager.allowedValues[level]){
18083 this.groupManager.allowedValues[level].forEach((value) => {
18084 this._createGroup(value, level);
18085 });
18086 }
18087 }
18088
18089 addBindings(){
18090 var toggleElement;
18091
18092 if(this.groupManager.table.options.groupToggleElement){
18093 toggleElement = this.groupManager.table.options.groupToggleElement == "arrow" ? this.arrowElement : this.element;
18094
18095 toggleElement.addEventListener("click", (e) => {
18096 if(this.groupManager.table.options.groupToggleElement === "arrow"){
18097 e.stopPropagation();
18098 e.stopImmediatePropagation();
18099 }
18100
18101 //allow click event to propagate before toggling visibility
18102 setTimeout(() => {
18103 this.toggleVisibility();
18104 });
18105 });
18106 }
18107 }
18108
18109 _createGroup(groupID, level){
18110 var groupKey = level + "_" + groupID;
18111 var group = new Group(this.groupManager, this, level, groupID, this.groupManager.groupIDLookups[level].field, this.groupManager.headerGenerator[level] || this.groupManager.headerGenerator[0], this.old ? this.old.groups[groupKey] : false);
18112
18113 this.groups[groupKey] = group;
18114 this.groupList.push(group);
18115 }
18116
18117 _addRowToGroup(row){
18118
18119 var level = this.level + 1;
18120
18121 if(this.hasSubGroups){
18122 var groupID = this.groupManager.groupIDLookups[level].func(row.getData()),
18123 groupKey = level + "_" + groupID;
18124
18125 if(this.groupManager.allowedValues && this.groupManager.allowedValues[level]){
18126 if(this.groups[groupKey]){
18127 this.groups[groupKey].addRow(row);
18128 }
18129 }else {
18130 if(!this.groups[groupKey]){
18131 this._createGroup(groupID, level);
18132 }
18133
18134 this.groups[groupKey].addRow(row);
18135 }
18136 }
18137 }
18138
18139 _addRow(row){
18140 this.rows.push(row);
18141 row.modules.group = this;
18142 }
18143
18144 insertRow(row, to, after){
18145 var data = this.conformRowData({});
18146
18147 row.updateData(data);
18148
18149 var toIndex = this.rows.indexOf(to);
18150
18151 if(toIndex > -1){
18152 if(after){
18153 this.rows.splice(toIndex+1, 0, row);
18154 }else {
18155 this.rows.splice(toIndex, 0, row);
18156 }
18157 }else {
18158 if(after){
18159 this.rows.push(row);
18160 }else {
18161 this.rows.unshift(row);
18162 }
18163 }
18164
18165 row.modules.group = this;
18166
18167 // this.generateGroupHeaderContents();
18168
18169 if(this.groupManager.table.modExists("columnCalcs") && this.groupManager.table.options.columnCalcs != "table"){
18170 this.groupManager.table.modules.columnCalcs.recalcGroup(this);
18171 }
18172
18173 this.groupManager.updateGroupRows(true);
18174 }
18175
18176 scrollHeader(left){
18177 if(this.arrowElement){
18178 this.arrowElement.style.marginLeft = left;
18179
18180 this.groupList.forEach(function(child){
18181 child.scrollHeader(left);
18182 });
18183 }
18184 }
18185
18186 getRowIndex(row){}
18187
18188 //update row data to match grouping constraints
18189 conformRowData(data){
18190 if(this.field){
18191 data[this.field] = this.key;
18192 }else {
18193 console.warn("Data Conforming Error - Cannot conform row data to match new group as groupBy is a function");
18194 }
18195
18196 if(this.parent){
18197 data = this.parent.conformRowData(data);
18198 }
18199
18200 return data;
18201 }
18202
18203 removeRow(row){
18204 var index = this.rows.indexOf(row);
18205 var el = row.getElement();
18206
18207 if(index > -1){
18208 this.rows.splice(index, 1);
18209 }
18210
18211 if(!this.groupManager.table.options.groupValues && !this.rows.length){
18212 if(this.parent){
18213 this.parent.removeGroup(this);
18214 }else {
18215 this.groupManager.removeGroup(this);
18216 }
18217
18218 this.groupManager.updateGroupRows(true);
18219
18220 }else {
18221
18222 if(el.parentNode){
18223 el.parentNode.removeChild(el);
18224 }
18225
18226 if(!this.groupManager.blockRedraw){
18227 this.generateGroupHeaderContents();
18228
18229 if(this.groupManager.table.modExists("columnCalcs") && this.groupManager.table.options.columnCalcs != "table"){
18230 this.groupManager.table.modules.columnCalcs.recalcGroup(this);
18231 }
18232 }
18233
18234 }
18235 }
18236
18237 removeGroup(group){
18238 var groupKey = group.level + "_" + group.key,
18239 index;
18240
18241 if(this.groups[groupKey]){
18242 delete this.groups[groupKey];
18243
18244 index = this.groupList.indexOf(group);
18245
18246 if(index > -1){
18247 this.groupList.splice(index, 1);
18248 }
18249
18250 if(!this.groupList.length){
18251 if(this.parent){
18252 this.parent.removeGroup(this);
18253 }else {
18254 this.groupManager.removeGroup(this);
18255 }
18256 }
18257 }
18258 }
18259
18260 getHeadersAndRows(){
18261 var output = [];
18262
18263 output.push(this);
18264
18265 this._visSet();
18266
18267
18268 if(this.calcs.top){
18269 this.calcs.top.detachElement();
18270 this.calcs.top.deleteCells();
18271 }
18272
18273 if(this.calcs.bottom){
18274 this.calcs.bottom.detachElement();
18275 this.calcs.bottom.deleteCells();
18276 }
18277
18278
18279
18280 if(this.visible){
18281 if(this.groupList.length){
18282 this.groupList.forEach(function(group){
18283 output = output.concat(group.getHeadersAndRows());
18284 });
18285
18286 }else {
18287 if(this.groupManager.table.options.columnCalcs != "table" && this.groupManager.table.modExists("columnCalcs") && this.groupManager.table.modules.columnCalcs.hasTopCalcs()){
18288 this.calcs.top = this.groupManager.table.modules.columnCalcs.generateTopRow(this.rows);
18289 output.push(this.calcs.top);
18290 }
18291
18292 output = output.concat(this.rows);
18293
18294 if(this.groupManager.table.options.columnCalcs != "table" && this.groupManager.table.modExists("columnCalcs") && this.groupManager.table.modules.columnCalcs.hasBottomCalcs()){
18295 this.calcs.bottom = this.groupManager.table.modules.columnCalcs.generateBottomRow(this.rows);
18296 output.push(this.calcs.bottom);
18297 }
18298 }
18299 }else {
18300 if(!this.groupList.length && this.groupManager.table.options.columnCalcs != "table"){
18301
18302 if(this.groupManager.table.modExists("columnCalcs")){
18303 if(this.groupManager.table.modules.columnCalcs.hasTopCalcs()){
18304 if(this.groupManager.table.options.groupClosedShowCalcs){
18305 this.calcs.top = this.groupManager.table.modules.columnCalcs.generateTopRow(this.rows);
18306 output.push(this.calcs.top);
18307 }
18308 }
18309
18310 if(this.groupManager.table.modules.columnCalcs.hasBottomCalcs()){
18311 if(this.groupManager.table.options.groupClosedShowCalcs){
18312 this.calcs.bottom = this.groupManager.table.modules.columnCalcs.generateBottomRow(this.rows);
18313 output.push(this.calcs.bottom);
18314 }
18315 }
18316 }
18317 }
18318
18319 }
18320
18321 return output;
18322 }
18323
18324 getData(visible, transform){
18325 var output = [];
18326
18327 this._visSet();
18328
18329 if(!visible || (visible && this.visible)){
18330 this.rows.forEach((row) => {
18331 output.push(row.getData(transform || "data"));
18332 });
18333 }
18334
18335 return output;
18336 }
18337
18338 getRowCount(){
18339 var count = 0;
18340
18341 if(this.groupList.length){
18342 this.groupList.forEach((group) => {
18343 count += group.getRowCount();
18344 });
18345 }else {
18346 count = this.rows.length;
18347 }
18348 return count;
18349 }
18350
18351
18352 toggleVisibility(){
18353 if(this.visible){
18354 this.hide();
18355 }else {
18356 this.show();
18357 }
18358 }
18359
18360 hide(){
18361 this.visible = false;
18362
18363 if(this.groupManager.table.rowManager.getRenderMode() == "basic" && !this.groupManager.table.options.pagination){
18364
18365 this.element.classList.remove("tabulator-group-visible");
18366
18367 if(this.groupList.length){
18368 this.groupList.forEach((group) => {
18369
18370 var rows = group.getHeadersAndRows();
18371
18372 rows.forEach((row) => {
18373 row.detachElement();
18374 });
18375 });
18376
18377 }else {
18378 this.rows.forEach((row) => {
18379 var rowEl = row.getElement();
18380 rowEl.parentNode.removeChild(rowEl);
18381 });
18382 }
18383
18384 this.groupManager.updateGroupRows(true);
18385
18386 }else {
18387 this.groupManager.updateGroupRows(true);
18388 }
18389
18390 this.groupManager.table.externalEvents.dispatch("groupVisibilityChanged", this.getComponent(), false);
18391 }
18392
18393 show(){
18394 this.visible = true;
18395
18396 if(this.groupManager.table.rowManager.getRenderMode() == "basic" && !this.groupManager.table.options.pagination){
18397
18398 this.element.classList.add("tabulator-group-visible");
18399
18400 var prev = this.generateElement();
18401
18402 if(this.groupList.length){
18403 this.groupList.forEach((group) => {
18404 var rows = group.getHeadersAndRows();
18405
18406 rows.forEach((row) => {
18407 var rowEl = row.getElement();
18408 prev.parentNode.insertBefore(rowEl, prev.nextSibling);
18409 row.initialize();
18410 prev = rowEl;
18411 });
18412 });
18413
18414 }else {
18415 this.rows.forEach((row) => {
18416 var rowEl = row.getElement();
18417 prev.parentNode.insertBefore(rowEl, prev.nextSibling);
18418 row.initialize();
18419 prev = rowEl;
18420 });
18421 }
18422
18423 this.groupManager.updateGroupRows(true);
18424 }else {
18425 this.groupManager.updateGroupRows(true);
18426 }
18427
18428 this.groupManager.table.externalEvents.dispatch("groupVisibilityChanged", this.getComponent(), true);
18429 }
18430
18431 _visSet(){
18432 var data = [];
18433
18434 if(typeof this.visible == "function"){
18435
18436 this.rows.forEach(function(row){
18437 data.push(row.getData());
18438 });
18439
18440 this.visible = this.visible(this.key, this.getRowCount(), data, this.getComponent());
18441 }
18442 }
18443
18444 getRowGroup(row){
18445 var match = false;
18446 if(this.groupList.length){
18447 this.groupList.forEach(function(group){
18448 var result = group.getRowGroup(row);
18449
18450 if(result){
18451 match = result;
18452 }
18453 });
18454 }else {
18455 if(this.rows.find(function(item){
18456 return item === row;
18457 })){
18458 match = this;
18459 }
18460 }
18461
18462 return match;
18463 }
18464
18465 getSubGroups(component){
18466 var output = [];
18467
18468 this.groupList.forEach(function(child){
18469 output.push(component ? child.getComponent() : child);
18470 });
18471
18472 return output;
18473 }
18474
18475 getRows(component, includeChildren){
18476 var output = [];
18477
18478 if(includeChildren && this.groupList.length){
18479 this.groupList.forEach((group) => {
18480 output = output.concat(group.getRows(component, includeChildren));
18481 });
18482 }else {
18483 this.rows.forEach(function(row){
18484 output.push(component ? row.getComponent() : row);
18485 });
18486 }
18487
18488 return output;
18489 }
18490
18491 generateGroupHeaderContents(){
18492 var data = [];
18493
18494 var rows = this.getRows(false, true);
18495
18496 rows.forEach(function(row){
18497 data.push(row.getData());
18498 });
18499
18500 this.elementContents = this.generator(this.key, this.getRowCount(), data, this.getComponent());
18501
18502 while(this.element.firstChild) this.element.removeChild(this.element.firstChild);
18503
18504 if(typeof this.elementContents === "string"){
18505 this.element.innerHTML = this.elementContents;
18506 }else {
18507 this.element.appendChild(this.elementContents);
18508 }
18509
18510 this.element.insertBefore(this.arrowElement, this.element.firstChild);
18511 }
18512
18513 getPath(path = []) {
18514 path.unshift(this.key);
18515 if(this.parent) {
18516 this.parent.getPath(path);
18517 }
18518 return path;
18519 }
18520
18521 ////////////// Standard Row Functions //////////////
18522
18523 getElement(){
18524 return this.elementContents ? this.element : this.generateElement();
18525 }
18526
18527 generateElement(){
18528 this.addBindings = false;
18529
18530 this._visSet();
18531
18532 if(this.visible){
18533 this.element.classList.add("tabulator-group-visible");
18534 }else {
18535 this.element.classList.remove("tabulator-group-visible");
18536 }
18537
18538 for(var i = 0; i < this.element.childNodes.length; ++i){
18539 this.element.childNodes[i].parentNode.removeChild(this.element.childNodes[i]);
18540 }
18541
18542 this.generateGroupHeaderContents();
18543
18544 // this.addBindings();
18545
18546 return this.element;
18547 }
18548
18549 detachElement(){
18550 if (this.element && this.element.parentNode){
18551 this.element.parentNode.removeChild(this.element);
18552 }
18553 }
18554
18555 //normalize the height of elements in the row
18556 normalizeHeight(){
18557 this.setHeight(this.element.clientHeight);
18558 }
18559
18560 initialize(force){
18561 if(!this.initialized || force){
18562 this.normalizeHeight();
18563 this.initialized = true;
18564 }
18565 }
18566
18567 reinitialize(){
18568 this.initialized = false;
18569 this.height = 0;
18570
18571 if(Helpers.elVisible(this.element)){
18572 this.initialize(true);
18573 }
18574 }
18575
18576 setHeight(height){
18577 if(this.height != height){
18578 this.height = height;
18579 this.outerHeight = this.element.offsetHeight;
18580 }
18581 }
18582
18583 //return rows outer height
18584 getHeight(){
18585 return this.outerHeight;
18586 }
18587
18588 getGroup(){
18589 return this;
18590 }
18591
18592 reinitializeHeight(){}
18593
18594 calcHeight(){}
18595
18596 setCellHeight(){}
18597
18598 clearCellHeight(){}
18599
18600 deinitializeHeight(){}
18601
18602 rendered(){}
18603
18604 //////////////// Object Generation /////////////////
18605 getComponent(){
18606 if(!this.component){
18607 this.component = new GroupComponent(this);
18608 }
18609
18610 return this.component;
18611 }
18612 }
18613
18614 class GroupRows extends Module{
18615
18616 static moduleName = "groupRows";
18617
18618 constructor(table){
18619 super(table);
18620
18621 this.groupIDLookups = false; //enable table grouping and set field to group by
18622 this.startOpen = [function(){return false;}]; //starting state of group
18623 this.headerGenerator = [function(){return "";}];
18624 this.groupList = []; //ordered list of groups
18625 this.allowedValues = false;
18626 this.groups = {}; //hold row groups
18627
18628 this.displayHandler = this.getRows.bind(this);
18629
18630 this.blockRedraw = false;
18631
18632 //register table options
18633 this.registerTableOption("groupBy", false); //enable table grouping and set field to group by
18634 this.registerTableOption("groupStartOpen", true); //starting state of group
18635 this.registerTableOption("groupValues", false);
18636 this.registerTableOption("groupUpdateOnCellEdit", false);
18637 this.registerTableOption("groupHeader", false); //header generation function
18638 this.registerTableOption("groupHeaderPrint", null);
18639 this.registerTableOption("groupHeaderClipboard", null);
18640 this.registerTableOption("groupHeaderHtmlOutput", null);
18641 this.registerTableOption("groupHeaderDownload", null);
18642 this.registerTableOption("groupToggleElement", "arrow");
18643 this.registerTableOption("groupClosedShowCalcs", false);
18644
18645 //register table functions
18646 this.registerTableFunction("setGroupBy", this.setGroupBy.bind(this));
18647 this.registerTableFunction("setGroupValues", this.setGroupValues.bind(this));
18648 this.registerTableFunction("setGroupStartOpen", this.setGroupStartOpen.bind(this));
18649 this.registerTableFunction("setGroupHeader", this.setGroupHeader.bind(this));
18650 this.registerTableFunction("getGroups", this.userGetGroups.bind(this));
18651 this.registerTableFunction("getGroupedData", this.userGetGroupedData.bind(this));
18652
18653 //register component functions
18654 this.registerComponentFunction("row", "getGroup", this.rowGetGroup.bind(this));
18655 }
18656
18657 //initialize group configuration
18658 initialize(){
18659 this.subscribe("table-destroy", this._blockRedrawing.bind(this));
18660 this.subscribe("rows-wipe", this._blockRedrawing.bind(this));
18661 this.subscribe("rows-wiped", this._restore_redrawing.bind(this));
18662
18663 if(this.table.options.groupBy){
18664 if(this.table.options.groupUpdateOnCellEdit){
18665 this.subscribe("cell-value-updated", this.cellUpdated.bind(this));
18666 this.subscribe("row-data-changed", this.reassignRowToGroup.bind(this), 0);
18667 }
18668
18669 this.subscribe("table-built", this.configureGroupSetup.bind(this));
18670
18671 this.subscribe("row-deleting", this.rowDeleting.bind(this));
18672 this.subscribe("row-deleted", this.rowsUpdated.bind(this));
18673 this.subscribe("scroll-horizontal", this.scrollHeaders.bind(this));
18674 this.subscribe("rows-wipe", this.wipe.bind(this));
18675 this.subscribe("rows-added", this.rowsUpdated.bind(this));
18676 this.subscribe("row-moving", this.rowMoving.bind(this));
18677 this.subscribe("row-adding-index", this.rowAddingIndex.bind(this));
18678
18679 this.subscribe("rows-sample", this.rowSample.bind(this));
18680
18681 this.subscribe("render-virtual-fill", this.virtualRenderFill.bind(this));
18682
18683 this.registerDisplayHandler(this.displayHandler, 20);
18684
18685 this.initialized = true;
18686 }
18687 }
18688
18689 _blockRedrawing(){
18690 this.blockRedraw = true;
18691 }
18692
18693 _restore_redrawing(){
18694 this.blockRedraw = false;
18695 }
18696
18697 configureGroupSetup(){
18698 if(this.table.options.groupBy){
18699 var groupBy = this.table.options.groupBy,
18700 startOpen = this.table.options.groupStartOpen,
18701 groupHeader = this.table.options.groupHeader;
18702
18703 this.allowedValues = this.table.options.groupValues;
18704
18705 if(Array.isArray(groupBy) && Array.isArray(groupHeader) && groupBy.length > groupHeader.length){
18706 console.warn("Error creating group headers, groupHeader array is shorter than groupBy array");
18707 }
18708
18709 this.headerGenerator = [function(){return "";}];
18710 this.startOpen = [function(){return false;}]; //starting state of group
18711
18712 this.langBind("groups|item", (langValue, lang) => {
18713 this.headerGenerator[0] = (value, count, data) => { //header layout function
18714 return (typeof value === "undefined" ? "" : value) + "<span>(" + count + " " + ((count === 1) ? langValue : lang.groups.items) + ")</span>";
18715 };
18716 });
18717
18718 this.groupIDLookups = [];
18719
18720 if(groupBy){
18721 if(this.table.modExists("columnCalcs") && this.table.options.columnCalcs != "table" && this.table.options.columnCalcs != "both"){
18722 this.table.modules.columnCalcs.removeCalcs();
18723 }
18724 }else {
18725 if(this.table.modExists("columnCalcs") && this.table.options.columnCalcs != "group"){
18726
18727 var cols = this.table.columnManager.getRealColumns();
18728
18729 cols.forEach((col) => {
18730 if(col.definition.topCalc){
18731 this.table.modules.columnCalcs.initializeTopRow();
18732 }
18733
18734 if(col.definition.bottomCalc){
18735 this.table.modules.columnCalcs.initializeBottomRow();
18736 }
18737 });
18738 }
18739 }
18740
18741 if(!Array.isArray(groupBy)){
18742 groupBy = [groupBy];
18743 }
18744
18745 groupBy.forEach((group, i) => {
18746 var lookupFunc, column;
18747
18748 if(typeof group == "function"){
18749 lookupFunc = group;
18750 }else {
18751 column = this.table.columnManager.getColumnByField(group);
18752
18753 if(column){
18754 lookupFunc = function(data){
18755 return column.getFieldValue(data);
18756 };
18757 }else {
18758 lookupFunc = function(data){
18759 return data[group];
18760 };
18761 }
18762 }
18763
18764 this.groupIDLookups.push({
18765 field: typeof group === "function" ? false : group,
18766 func:lookupFunc,
18767 values:this.allowedValues ? this.allowedValues[i] : false,
18768 });
18769 });
18770
18771 if(startOpen){
18772 if(!Array.isArray(startOpen)){
18773 startOpen = [startOpen];
18774 }
18775
18776 startOpen.forEach((level) => {
18777 });
18778
18779 this.startOpen = startOpen;
18780 }
18781
18782 if(groupHeader){
18783 this.headerGenerator = Array.isArray(groupHeader) ? groupHeader : [groupHeader];
18784 }
18785 }else {
18786 this.groupList = [];
18787 this.groups = {};
18788 }
18789 }
18790
18791 rowSample(rows, prevValue){
18792 if(this.table.options.groupBy){
18793 var group = this.getGroups(false)[0];
18794
18795 prevValue.push(group.getRows(false)[0]);
18796 }
18797
18798 return prevValue;
18799 }
18800
18801 virtualRenderFill(){
18802 var el = this.table.rowManager.tableElement;
18803 var rows = this.table.rowManager.getVisibleRows();
18804
18805 if(this.table.options.groupBy){
18806 rows = rows.filter((row) => {
18807 return row.type !== "group";
18808 });
18809
18810 el.style.minWidth = !rows.length ? this.table.columnManager.getWidth() + "px" : "";
18811 }else {
18812 return rows;
18813 }
18814 }
18815
18816 rowAddingIndex(row, index, top){
18817 if(this.table.options.groupBy){
18818 this.assignRowToGroup(row);
18819
18820 var groupRows = row.modules.group.rows;
18821
18822 if(groupRows.length > 1){
18823 if(!index || (index && groupRows.indexOf(index) == -1)){
18824 if(top){
18825 if(groupRows[0] !== row){
18826 index = groupRows[0];
18827 this.table.rowManager.moveRowInArray(row.modules.group.rows, row, index, !top);
18828 }
18829 }else {
18830 if(groupRows[groupRows.length -1] !== row){
18831 index = groupRows[groupRows.length -1];
18832 this.table.rowManager.moveRowInArray(row.modules.group.rows, row, index, !top);
18833 }
18834 }
18835 }else {
18836 this.table.rowManager.moveRowInArray(row.modules.group.rows, row, index, !top);
18837 }
18838 }
18839
18840 return index;
18841 }
18842 }
18843
18844 trackChanges(){
18845 this.dispatch("group-changed");
18846 }
18847
18848 ///////////////////////////////////
18849 ///////// Table Functions /////////
18850 ///////////////////////////////////
18851
18852 setGroupBy(groups){
18853 this.table.options.groupBy = groups;
18854
18855 if(!this.initialized){
18856 this.initialize();
18857 }
18858
18859 this.configureGroupSetup();
18860
18861 if(!groups && this.table.modExists("columnCalcs") && this.table.options.columnCalcs === true){
18862 this.table.modules.columnCalcs.reinitializeCalcs();
18863 }
18864
18865 this.refreshData();
18866
18867 this.trackChanges();
18868 }
18869
18870 setGroupValues(groupValues){
18871 this.table.options.groupValues = groupValues;
18872 this.configureGroupSetup();
18873 this.refreshData();
18874
18875 this.trackChanges();
18876 }
18877
18878 setGroupStartOpen(values){
18879 this.table.options.groupStartOpen = values;
18880 this.configureGroupSetup();
18881
18882 if(this.table.options.groupBy){
18883 this.refreshData();
18884
18885 this.trackChanges();
18886 }else {
18887 console.warn("Grouping Update - cant refresh view, no groups have been set");
18888 }
18889 }
18890
18891 setGroupHeader(values){
18892 this.table.options.groupHeader = values;
18893 this.configureGroupSetup();
18894
18895 if(this.table.options.groupBy){
18896 this.refreshData();
18897
18898 this.trackChanges();
18899 }else {
18900 console.warn("Grouping Update - cant refresh view, no groups have been set");
18901 }
18902 }
18903
18904 userGetGroups(values){
18905 return this.getGroups(true);
18906 }
18907
18908 // get grouped table data in the same format as getData()
18909 userGetGroupedData(){
18910 return this.table.options.groupBy ? this.getGroupedData() : this.getData();
18911 }
18912
18913
18914 ///////////////////////////////////////
18915 ///////// Component Functions /////////
18916 ///////////////////////////////////////
18917
18918 rowGetGroup(row){
18919 return row.modules.group ? row.modules.group.getComponent() : false;
18920 }
18921
18922 ///////////////////////////////////
18923 ///////// Internal Logic //////////
18924 ///////////////////////////////////
18925
18926 rowMoving(from, to, after){
18927 if(this.table.options.groupBy){
18928 if(!after && to instanceof Group){
18929 to = this.table.rowManager.prevDisplayRow(from) || to;
18930 }
18931
18932 var toGroup = to instanceof Group ? to : to.modules.group;
18933 var fromGroup = from instanceof Group ? from : from.modules.group;
18934
18935 if(toGroup === fromGroup){
18936 this.table.rowManager.moveRowInArray(toGroup.rows, from, to, after);
18937 }else {
18938 if(fromGroup){
18939 fromGroup.removeRow(from);
18940 }
18941
18942 toGroup.insertRow(from, to, after);
18943 }
18944 }
18945 }
18946
18947
18948 rowDeleting(row){
18949 //remove from group
18950 if(this.table.options.groupBy && row.modules.group){
18951 row.modules.group.removeRow(row);
18952 }
18953 }
18954
18955 rowsUpdated(row){
18956 if(this.table.options.groupBy){
18957 this.updateGroupRows(true);
18958 }
18959 }
18960
18961 cellUpdated(cell){
18962 if(this.table.options.groupBy){
18963 this.reassignRowToGroup(cell.row);
18964 }
18965 }
18966
18967 //return appropriate rows with group headers
18968 getRows(rows){
18969 if(this.table.options.groupBy && this.groupIDLookups.length){
18970
18971 this.dispatchExternal("dataGrouping");
18972
18973 this.generateGroups(rows);
18974
18975 if(this.subscribedExternal("dataGrouped")){
18976 this.dispatchExternal("dataGrouped", this.getGroups(true));
18977 }
18978
18979 return this.updateGroupRows();
18980
18981 }else {
18982 return rows.slice(0);
18983 }
18984 }
18985
18986 getGroups(component){
18987 var groupComponents = [];
18988
18989 this.groupList.forEach(function(group){
18990 groupComponents.push(component ? group.getComponent() : group);
18991 });
18992
18993 return groupComponents;
18994 }
18995
18996 getChildGroups(group){
18997 var groupComponents = [];
18998
18999 if(!group){
19000 group = this;
19001 }
19002
19003 group.groupList.forEach((child) => {
19004 if(child.groupList.length){
19005 groupComponents = groupComponents.concat(this.getChildGroups(child));
19006 }else {
19007 groupComponents.push(child);
19008 }
19009 });
19010
19011 return groupComponents;
19012 }
19013
19014 wipe(){
19015 if(this.table.options.groupBy){
19016 this.groupList.forEach(function(group){
19017 group.wipe();
19018 });
19019
19020 this.groupList = [];
19021 this.groups = {};
19022 }
19023 }
19024
19025 pullGroupListData(groupList) {
19026 var groupListData = [];
19027
19028 groupList.forEach((group) => {
19029 var groupHeader = {};
19030 groupHeader.level = 0;
19031 groupHeader.rowCount = 0;
19032 groupHeader.headerContent = "";
19033 var childData = [];
19034
19035 if (group.hasSubGroups) {
19036 childData = this.pullGroupListData(group.groupList);
19037
19038 groupHeader.level = group.level;
19039 groupHeader.rowCount = childData.length - group.groupList.length; // data length minus number of sub-headers
19040 groupHeader.headerContent = group.generator(group.key, groupHeader.rowCount, group.rows, group);
19041
19042 groupListData.push(groupHeader);
19043 groupListData = groupListData.concat(childData);
19044 }
19045
19046 else {
19047 groupHeader.level = group.level;
19048 groupHeader.headerContent = group.generator(group.key, group.rows.length, group.rows, group);
19049 groupHeader.rowCount = group.getRows().length;
19050
19051 groupListData.push(groupHeader);
19052
19053 group.getRows().forEach((row) => {
19054 groupListData.push(row.getData("data"));
19055 });
19056 }
19057 });
19058
19059 return groupListData;
19060 }
19061
19062 getGroupedData(){
19063
19064 return this.pullGroupListData(this.groupList);
19065 }
19066
19067 getRowGroup(row){
19068 var match = false;
19069
19070 if(this.options("dataTree")){
19071 row = this.table.modules.dataTree.getTreeParentRoot(row);
19072 }
19073
19074 this.groupList.forEach((group) => {
19075 var result = group.getRowGroup(row);
19076
19077 if(result){
19078 match = result;
19079 }
19080 });
19081
19082 return match;
19083 }
19084
19085 countGroups(){
19086 return this.groupList.length;
19087 }
19088
19089 generateGroups(rows){
19090 var oldGroups = this.groups;
19091
19092 this.groups = {};
19093 this.groupList = [];
19094
19095 if(this.allowedValues && this.allowedValues[0]){
19096 this.allowedValues[0].forEach((value) => {
19097 this.createGroup(value, 0, oldGroups);
19098 });
19099
19100 rows.forEach((row) => {
19101 this.assignRowToExistingGroup(row, oldGroups);
19102 });
19103 }else {
19104 rows.forEach((row) => {
19105 this.assignRowToGroup(row, oldGroups);
19106 });
19107 }
19108
19109 Object.values(oldGroups).forEach((group) => {
19110 group.wipe(true);
19111 });
19112 }
19113
19114
19115 createGroup(groupID, level, oldGroups){
19116 var groupKey = level + "_" + groupID,
19117 group;
19118
19119 oldGroups = oldGroups || [];
19120
19121 group = new Group(this, false, level, groupID, this.groupIDLookups[0].field, this.headerGenerator[0], oldGroups[groupKey]);
19122
19123 this.groups[groupKey] = group;
19124 this.groupList.push(group);
19125 }
19126
19127 assignRowToExistingGroup(row, oldGroups){
19128 var groupID = this.groupIDLookups[0].func(row.getData()),
19129 groupKey = "0_" + groupID;
19130
19131 if(this.groups[groupKey]){
19132 this.groups[groupKey].addRow(row);
19133 }
19134 }
19135
19136 assignRowToGroup(row, oldGroups){
19137 var groupID = this.groupIDLookups[0].func(row.getData()),
19138 newGroupNeeded = !this.groups["0_" + groupID];
19139
19140 if(newGroupNeeded){
19141 this.createGroup(groupID, 0, oldGroups);
19142 }
19143
19144 this.groups["0_" + groupID].addRow(row);
19145
19146 return !newGroupNeeded;
19147 }
19148
19149 reassignRowToGroup(row){
19150 if(row.type === "row"){
19151 var oldRowGroup = row.modules.group,
19152 oldGroupPath = oldRowGroup.getPath(),
19153 newGroupPath = this.getExpectedPath(row),
19154 samePath;
19155
19156 // figure out if new group path is the same as old group path
19157 samePath = (oldGroupPath.length == newGroupPath.length) && oldGroupPath.every((element, index) => {
19158 return element === newGroupPath[index];
19159 });
19160
19161 // refresh if they new path and old path aren't the same (aka the row's groupings have changed)
19162 if(!samePath) {
19163 oldRowGroup.removeRow(row);
19164 this.assignRowToGroup(row, this.groups);
19165 this.refreshData(true);
19166 }
19167 }
19168 }
19169
19170 getExpectedPath(row) {
19171 var groupPath = [], rowData = row.getData();
19172
19173 this.groupIDLookups.forEach((groupId) => {
19174 groupPath.push(groupId.func(rowData));
19175 });
19176
19177 return groupPath;
19178 }
19179
19180 updateGroupRows(force){
19181 var output = [];
19182
19183 if(!this.blockRedraw){
19184 this.groupList.forEach((group) => {
19185 output = output.concat(group.getHeadersAndRows());
19186 });
19187
19188 if(force){
19189 this.refreshData(true);
19190 }
19191 }
19192
19193 return output;
19194 }
19195
19196 scrollHeaders(left){
19197 if(this.table.options.groupBy){
19198 if(this.table.options.renderHorizontal === "virtual"){
19199 left -= this.table.columnManager.renderer.vDomPadLeft;
19200 }
19201
19202 left = left + "px";
19203
19204 this.groupList.forEach((group) => {
19205 group.scrollHeader(left);
19206 });
19207 }
19208 }
19209
19210 removeGroup(group){
19211 var groupKey = group.level + "_" + group.key,
19212 index;
19213
19214 if(this.groups[groupKey]){
19215 delete this.groups[groupKey];
19216
19217 index = this.groupList.indexOf(group);
19218
19219 if(index > -1){
19220 this.groupList.splice(index, 1);
19221 }
19222 }
19223 }
19224
19225 checkBasicModeGroupHeaderWidth(){
19226 var element = this.table.rowManager.tableElement,
19227 onlyGroupHeaders = true;
19228
19229 this.table.rowManager.getDisplayRows().forEach((row, index) =>{
19230 this.table.rowManager.styleRow(row, index);
19231 element.appendChild(row.getElement());
19232 row.initialize(true);
19233
19234 if(row.type !== "group"){
19235 onlyGroupHeaders = false;
19236 }
19237 });
19238
19239 if(onlyGroupHeaders){
19240 element.style.minWidth = this.table.columnManager.getWidth() + "px";
19241 }else {
19242 element.style.minWidth = "";
19243 }
19244 }
19245
19246 }
19247
19248 var defaultUndoers = {
19249 cellEdit: function(action){
19250 action.component.setValueProcessData(action.data.oldValue);
19251 action.component.cellRendered();
19252 },
19253
19254 rowAdd: function(action){
19255 action.component.deleteActual();
19256
19257 this.table.rowManager.checkPlaceholder();
19258 },
19259
19260 rowDelete: function(action){
19261 var newRow = this.table.rowManager.addRowActual(action.data.data, action.data.pos, action.data.index);
19262
19263 if(this.table.options.groupBy && this.table.modExists("groupRows")){
19264 this.table.modules.groupRows.updateGroupRows(true);
19265 }
19266
19267 this._rebindRow(action.component, newRow);
19268
19269 this.table.rowManager.checkPlaceholder();
19270 },
19271
19272 rowMove: function(action){
19273 var after = (action.data.posFrom - action.data.posTo) > 0;
19274
19275 this.table.rowManager.moveRowActual(action.component, this.table.rowManager.getRowFromPosition(action.data.posFrom), after);
19276
19277 this.table.rowManager.regenerateRowPositions();
19278 this.table.rowManager.reRenderInPosition();
19279 },
19280 };
19281
19282 var defaultRedoers = {
19283 cellEdit: function(action){
19284 action.component.setValueProcessData(action.data.newValue);
19285 action.component.cellRendered();
19286 },
19287
19288 rowAdd: function(action){
19289 var newRow = this.table.rowManager.addRowActual(action.data.data, action.data.pos, action.data.index);
19290
19291 if(this.table.options.groupBy && this.table.modExists("groupRows")){
19292 this.table.modules.groupRows.updateGroupRows(true);
19293 }
19294
19295 this._rebindRow(action.component, newRow);
19296
19297 this.table.rowManager.checkPlaceholder();
19298 },
19299
19300 rowDelete:function(action){
19301 action.component.deleteActual();
19302
19303 this.table.rowManager.checkPlaceholder();
19304 },
19305
19306 rowMove: function(action){
19307 this.table.rowManager.moveRowActual(action.component, this.table.rowManager.getRowFromPosition(action.data.posTo), action.data.after);
19308
19309 this.table.rowManager.regenerateRowPositions();
19310 this.table.rowManager.reRenderInPosition();
19311 },
19312 };
19313
19314 var bindings$1 = {
19315 undo:["ctrl + 90", "meta + 90"],
19316 redo:["ctrl + 89", "meta + 89"],
19317 };
19318
19319 var actions$1 = {
19320 undo:function(e){
19321 var cell = false;
19322 if(this.table.options.history && this.table.modExists("history") && this.table.modExists("edit")){
19323
19324 cell = this.table.modules.edit.currentCell;
19325
19326 if(!cell){
19327 e.preventDefault();
19328 this.table.modules.history.undo();
19329 }
19330 }
19331 },
19332
19333 redo:function(e){
19334 var cell = false;
19335 if(this.table.options.history && this.table.modExists("history") && this.table.modExists("edit")){
19336
19337 cell = this.table.modules.edit.currentCell;
19338
19339 if(!cell){
19340 e.preventDefault();
19341 this.table.modules.history.redo();
19342 }
19343 }
19344 },
19345 };
19346
19347 var extensions$3 = {
19348 keybindings:{
19349 bindings:bindings$1,
19350 actions:actions$1
19351 },
19352 };
19353
19354 class History extends Module{
19355
19356 static moduleName = "history";
19357 static moduleExtensions = extensions$3;
19358
19359 //load defaults
19360 static undoers = defaultUndoers;
19361 static redoers = defaultRedoers;
19362
19363 constructor(table){
19364 super(table);
19365
19366 this.history = [];
19367 this.index = -1;
19368
19369 this.registerTableOption("history", false); //enable edit history
19370 }
19371
19372 initialize(){
19373 if(this.table.options.history){
19374 this.subscribe("cell-value-updated", this.cellUpdated.bind(this));
19375 this.subscribe("cell-delete", this.clearComponentHistory.bind(this));
19376 this.subscribe("row-delete", this.rowDeleted.bind(this));
19377 this.subscribe("rows-wipe", this.clear.bind(this));
19378 this.subscribe("row-added", this.rowAdded.bind(this));
19379 this.subscribe("row-move", this.rowMoved.bind(this));
19380 }
19381
19382 this.registerTableFunction("undo", this.undo.bind(this));
19383 this.registerTableFunction("redo", this.redo.bind(this));
19384 this.registerTableFunction("getHistoryUndoSize", this.getHistoryUndoSize.bind(this));
19385 this.registerTableFunction("getHistoryRedoSize", this.getHistoryRedoSize.bind(this));
19386 this.registerTableFunction("clearHistory", this.clear.bind(this));
19387 }
19388
19389 rowMoved(from, to, after){
19390 this.action("rowMove", from, {posFrom:from.getPosition(), posTo:to.getPosition(), to:to, after:after});
19391 }
19392
19393 rowAdded(row, data, pos, index){
19394 this.action("rowAdd", row, {data:data, pos:pos, index:index});
19395 }
19396
19397 rowDeleted(row){
19398 var index, rows;
19399
19400 if(this.table.options.groupBy){
19401
19402 rows = row.getComponent().getGroup()._getSelf().rows;
19403 index = rows.indexOf(row);
19404
19405 if(index){
19406 index = rows[index-1];
19407 }
19408 }else {
19409 index = row.table.rowManager.getRowIndex(row);
19410
19411 if(index){
19412 index = row.table.rowManager.rows[index-1];
19413 }
19414 }
19415
19416 this.action("rowDelete", row, {data:row.getData(), pos:!index, index:index});
19417 }
19418
19419 cellUpdated(cell){
19420 this.action("cellEdit", cell, {oldValue:cell.oldValue, newValue:cell.value});
19421 }
19422
19423 clear(){
19424 this.history = [];
19425 this.index = -1;
19426 }
19427
19428 action(type, component, data){
19429 this.history = this.history.slice(0, this.index + 1);
19430
19431 this.history.push({
19432 type:type,
19433 component:component,
19434 data:data,
19435 });
19436
19437 this.index ++;
19438 }
19439
19440 getHistoryUndoSize(){
19441 return this.index + 1;
19442 }
19443
19444 getHistoryRedoSize(){
19445 return this.history.length - (this.index + 1);
19446 }
19447
19448 clearComponentHistory(component){
19449 var index = this.history.findIndex(function(item){
19450 return item.component === component;
19451 });
19452
19453 if(index > -1){
19454 this.history.splice(index, 1);
19455 if(index <= this.index){
19456 this.index--;
19457 }
19458
19459 this.clearComponentHistory(component);
19460 }
19461 }
19462
19463 undo(){
19464 if(this.index > -1){
19465 let action = this.history[this.index];
19466
19467 History.undoers[action.type].call(this, action);
19468
19469 this.index--;
19470
19471 this.dispatchExternal("historyUndo", action.type, action.component.getComponent(), action.data);
19472
19473 return true;
19474 }else {
19475 console.warn(this.options("history") ? "History Undo Error - No more history to undo" : "History module not enabled");
19476 return false;
19477 }
19478 }
19479
19480 redo(){
19481 if(this.history.length-1 > this.index){
19482
19483 this.index++;
19484
19485 let action = this.history[this.index];
19486
19487 History.redoers[action.type].call(this, action);
19488
19489 this.dispatchExternal("historyRedo", action.type, action.component.getComponent(), action.data);
19490
19491 return true;
19492 }else {
19493 console.warn(this.options("history") ? "History Redo Error - No more history to redo" : "History module not enabled");
19494 return false;
19495 }
19496 }
19497
19498 //rebind rows to new element after deletion
19499 _rebindRow(oldRow, newRow){
19500 this.history.forEach(function(action){
19501 if(action.component instanceof Row){
19502 if(action.component === oldRow){
19503 action.component = newRow;
19504 }
19505 }else if(action.component instanceof Cell){
19506 if(action.component.row === oldRow){
19507 var field = action.component.column.getField();
19508
19509 if(field){
19510 action.component = newRow.getCell(field);
19511 }
19512
19513 }
19514 }
19515 });
19516 }
19517 }
19518
19519 class HtmlTableImport extends Module{
19520
19521 static moduleName = "htmlTableImport";
19522
19523 constructor(table){
19524 super(table);
19525
19526 this.fieldIndex = [];
19527 this.hasIndex = false;
19528 }
19529
19530 initialize(){
19531 this.tableElementCheck();
19532 }
19533
19534 tableElementCheck(){
19535 if(this.table.originalElement && this.table.originalElement.tagName === "TABLE"){
19536 if(this.table.originalElement.childNodes.length){
19537 this.parseTable();
19538 }else {
19539 console.warn("Unable to parse data from empty table tag, Tabulator should be initialized on a div tag unless importing data from a table element.");
19540 }
19541 }
19542 }
19543
19544 parseTable(){
19545 var element = this.table.originalElement,
19546 options = this.table.options,
19547 headers = element.getElementsByTagName("th"),
19548 rows = element.getElementsByTagName("tbody")[0],
19549 data = [];
19550
19551 this.hasIndex = false;
19552
19553 this.dispatchExternal("htmlImporting");
19554
19555 rows = rows ? rows.getElementsByTagName("tr") : [];
19556
19557 //check for Tabulator inline options
19558 this._extractOptions(element, options);
19559
19560 if(headers.length){
19561 this._extractHeaders(headers, rows);
19562 }else {
19563 this._generateBlankHeaders(headers, rows);
19564 }
19565
19566 //iterate through table rows and build data set
19567 for(var index = 0; index < rows.length; index++){
19568 var row = rows[index],
19569 cells = row.getElementsByTagName("td"),
19570 item = {};
19571
19572 //create index if the don't exist in table
19573 if(!this.hasIndex){
19574 item[options.index] = index;
19575 }
19576
19577 for(var i = 0; i < cells.length; i++){
19578 var cell = cells[i];
19579 if(typeof this.fieldIndex[i] !== "undefined"){
19580 item[this.fieldIndex[i]] = cell.innerHTML;
19581 }
19582 }
19583
19584 //add row data to item
19585 data.push(item);
19586 }
19587
19588 options.data = data;
19589
19590 this.dispatchExternal("htmlImported");
19591 }
19592
19593 //extract tabulator attribute options
19594 _extractOptions(element, options, defaultOptions){
19595 var attributes = element.attributes;
19596 var optionsArr = defaultOptions ? Object.keys(defaultOptions) : Object.keys(options);
19597 var optionsList = {};
19598
19599 optionsArr.forEach((item) => {
19600 optionsList[item.toLowerCase()] = item;
19601 });
19602
19603 for(var index in attributes){
19604 var attrib = attributes[index];
19605 var name;
19606
19607 if(attrib && typeof attrib == "object" && attrib.name && attrib.name.indexOf("tabulator-") === 0){
19608 name = attrib.name.replace("tabulator-", "");
19609
19610 if(typeof optionsList[name] !== "undefined"){
19611 options[optionsList[name]] = this._attribValue(attrib.value);
19612 }
19613 }
19614 }
19615 }
19616
19617 //get value of attribute
19618 _attribValue(value){
19619 if(value === "true"){
19620 return true;
19621 }
19622
19623 if(value === "false"){
19624 return false;
19625 }
19626
19627 return value;
19628 }
19629
19630 //find column if it has already been defined
19631 _findCol(title){
19632 var match = this.table.options.columns.find((column) => {
19633 return column.title === title;
19634 });
19635
19636 return match || false;
19637 }
19638
19639 //extract column from headers
19640 _extractHeaders(headers, rows){
19641 for(var index = 0; index < headers.length; index++){
19642 var header = headers[index],
19643 exists = false,
19644 col = this._findCol(header.textContent),
19645 width;
19646
19647 if(col){
19648 exists = true;
19649 }else {
19650 col = {title:header.textContent.trim()};
19651 }
19652
19653 if(!col.field) {
19654 col.field = header.textContent.trim().toLowerCase().replaceAll(" ", "_");
19655 }
19656
19657 width = header.getAttribute("width");
19658
19659 if(width && !col.width) {
19660 col.width = width;
19661 }
19662
19663 //check for Tabulator inline options
19664 this._extractOptions(header, col, this.table.columnManager.optionsList.registeredDefaults);
19665
19666 this.fieldIndex[index] = col.field;
19667
19668 if(col.field == this.table.options.index){
19669 this.hasIndex = true;
19670 }
19671
19672 if(!exists){
19673 this.table.options.columns.push(col);
19674 }
19675
19676 }
19677 }
19678
19679 //generate blank headers
19680 _generateBlankHeaders(headers, rows){
19681 for(var index = 0; index < headers.length; index++){
19682 var header = headers[index],
19683 col = {title:"", field:"col" + index};
19684
19685 this.fieldIndex[index] = col.field;
19686
19687 var width = header.getAttribute("width");
19688
19689 if(width){
19690 col.width = width;
19691 }
19692
19693 this.table.options.columns.push(col);
19694 }
19695 }
19696 }
19697
19698 function csv(input){
19699 var data = [],
19700 row = 0,
19701 col = 0,
19702 inQuote = false;
19703
19704 //Iterate over each character
19705 for (let index = 0; index < input.length; index++) {
19706 let char = input[index],
19707 nextChar = input[index+1];
19708
19709 //Initialize empty row
19710 if(!data[row]){
19711 data[row] = [];
19712 }
19713
19714 //Initialize empty column
19715 if(!data[row][col]){
19716 data[row][col] = "";
19717 }
19718
19719 //Handle quotation mark inside string
19720 if (char == '"' && inQuote && nextChar == '"') {
19721 data[row][col] += char;
19722 index++;
19723 continue;
19724 }
19725
19726 //Begin / End Quote
19727 if (char == '"') {
19728 inQuote = !inQuote;
19729 continue;
19730 }
19731
19732 //Next column (if not in quote)
19733 if (char == ',' && !inQuote) {
19734 col++;
19735 continue;
19736 }
19737
19738 //New row if new line and not in quote (CRLF)
19739 if (char == '\r' && nextChar == '\n' && !inQuote) {
19740 col = 0;
19741 row++;
19742 index++;
19743 continue;
19744 }
19745
19746 //New row if new line and not in quote (CR or LF)
19747 if ((char == '\r' || char == '\n') && !inQuote) {
19748 col = 0;
19749 row++;
19750 continue;
19751 }
19752
19753 //Normal Character, append to column
19754 data[row][col] += char;
19755 }
19756
19757 return data;
19758 }
19759
19760 function json(input){
19761 try {
19762 return JSON.parse(input);
19763 } catch(e) {
19764 console.warn("JSON Import Error - File contents is invalid JSON", e);
19765 return Promise.reject();
19766 }
19767 }
19768
19769 function array$1 (input){
19770 return input;
19771 }
19772
19773 function xlsx(input){
19774 var XLSXLib = this.dependencyRegistry.lookup("XLSX"),
19775 workbook2 = XLSXLib.read(input),
19776 sheet = workbook2.Sheets[workbook2.SheetNames[0]];
19777
19778 return XLSXLib.utils.sheet_to_json(sheet, {header: 1 });
19779 }
19780
19781 var defaultImporters = {
19782 csv:csv,
19783 json:json,
19784 array:array$1,
19785 xlsx:xlsx,
19786 };
19787
19788 class Import extends Module{
19789
19790 static moduleName = "import";
19791
19792 //load defaults
19793 static importers = defaultImporters;
19794
19795 constructor(table){
19796 super(table);
19797
19798 this.registerTableOption("importFormat");
19799 this.registerTableOption("importReader", "text");
19800 this.registerTableOption("importHeaderTransform");
19801 this.registerTableOption("importValueTransform");
19802 this.registerTableOption("importDataValidator");
19803 this.registerTableOption("importFileValidator");
19804 }
19805
19806 initialize(){
19807 this.registerTableFunction("import", this.importFromFile.bind(this));
19808
19809 if(this.table.options.importFormat){
19810 this.subscribe("data-loading", this.loadDataCheck.bind(this), 10);
19811 this.subscribe("data-load", this.loadData.bind(this), 10);
19812 }
19813 }
19814
19815 loadDataCheck(data){
19816 return this.table.options.importFormat && (typeof data === "string" || (Array.isArray(data) && data.length && Array.isArray(data)));
19817 }
19818
19819 loadData(data, params, config, silent, previousData){
19820 return this.importData(this.lookupImporter(), data)
19821 .then(this.structureData.bind(this))
19822 .catch((err) => {
19823 console.error("Import Error:", err || "Unable to import data");
19824 return Promise.reject(err);
19825 });
19826 }
19827
19828 lookupImporter(importFormat){
19829 var importer;
19830
19831 if(!importFormat){
19832 importFormat = this.table.options.importFormat;
19833 }
19834
19835 if(typeof importFormat === "string"){
19836 importer = Import.importers[importFormat];
19837 }else {
19838 importer = importFormat;
19839 }
19840
19841 if(!importer){
19842 console.error("Import Error - Importer not found:", importFormat);
19843 }
19844
19845 return importer;
19846 }
19847
19848 importFromFile(importFormat, extension, importReader){
19849 var importer = this.lookupImporter(importFormat);
19850
19851 if(importer){
19852 return this.pickFile(extension, importReader)
19853 .then(this.importData.bind(this, importer))
19854 .then(this.structureData.bind(this))
19855 .then(this.mutateData.bind(this))
19856 .then(this.validateData.bind(this))
19857 .then(this.setData.bind(this))
19858 .catch((err) => {
19859 this.dispatch("import-error", err);
19860 this.dispatchExternal("importError", err);
19861
19862 console.error("Import Error:", err || "Unable to import file");
19863
19864 this.table.dataLoader.alertError();
19865
19866 setTimeout(() => {
19867 this.table.dataLoader.clearAlert();
19868 }, 3000);
19869
19870 return Promise.reject(err);
19871 });
19872 }
19873 }
19874
19875 pickFile(extensions, importReader){
19876 return new Promise((resolve, reject) => {
19877 var input = document.createElement("input");
19878 input.type = "file";
19879 input.accept = extensions;
19880
19881 input.addEventListener("change", (e) => {
19882 var file = input.files[0],
19883 reader = new FileReader(),
19884 valid = this.validateFile(file);
19885
19886 if(valid === true){
19887
19888 this.dispatch("import-importing", input.files);
19889 this.dispatchExternal("importImporting", input.files);
19890
19891 switch(importReader || this.table.options.importReader){
19892 case "buffer":
19893 reader.readAsArrayBuffer(file);
19894 break;
19895
19896 case "binary":
19897 reader.readAsBinaryString(file);
19898 break;
19899
19900 case "url":
19901 reader.readAsDataURL(file);
19902 break;
19903
19904 case "text":
19905 default:
19906 reader.readAsText(file);
19907 }
19908
19909 reader.onload = (e) => {
19910 resolve(reader.result);
19911 };
19912
19913 reader.onerror = (e) => {
19914 console.warn("File Load Error - Unable to read file");
19915 reject(e);
19916 };
19917 }else {
19918 reject(valid);
19919 }
19920 });
19921
19922 this.dispatch("import-choose");
19923 this.dispatchExternal("importChoose");
19924 input.click();
19925 });
19926 }
19927
19928 importData(importer, fileContents){
19929 var data;
19930
19931 this.table.dataLoader.alertLoader();
19932
19933 return new Promise((resolve, reject) => {
19934 setTimeout(() => {
19935 data = importer.call(this.table, fileContents);
19936
19937 if(data instanceof Promise){
19938 resolve(data);
19939 }else {
19940 data ? resolve(data) : reject();
19941 }
19942 }, 10);
19943 });
19944 }
19945
19946 structureData(parsedData){
19947 var data = [];
19948
19949 if(Array.isArray(parsedData) && parsedData.length && Array.isArray(parsedData[0])){
19950 if(this.table.options.autoColumns){
19951 data = this.structureArrayToObject(parsedData);
19952 }else {
19953 data = this.structureArrayToColumns(parsedData);
19954 }
19955
19956 return data;
19957 }else {
19958 return parsedData;
19959 }
19960 }
19961
19962 mutateData(data){
19963 var output = [];
19964
19965 if(Array.isArray(data)){
19966 data.forEach((row) => {
19967 output.push(this.table.modules.mutator.transformRow(row, "import"));
19968 });
19969 }else {
19970 output = data;
19971 }
19972
19973 return output;
19974 }
19975
19976 transformHeader(headers){
19977 var output = [];
19978
19979 if(this.table.options.importHeaderTransform){
19980 headers.forEach((item) => {
19981 output.push(this.table.options.importHeaderTransform.call(this.table, item, headers));
19982 });
19983 }else {
19984 return headers;
19985 }
19986
19987 return output;
19988 }
19989
19990 transformData(row){
19991 var output = [];
19992
19993 if(this.table.options.importValueTransform){
19994 row.forEach((item) => {
19995 output.push(this.table.options.importValueTransform.call(this.table, item, row));
19996 });
19997 }else {
19998 return row;
19999 }
20000
20001 return output;
20002 }
20003
20004 structureArrayToObject(parsedData){
20005 var columns = this.transformHeader(parsedData.shift());
20006
20007 var data = parsedData.map((values) => {
20008 var row = {};
20009
20010 values = this.transformData(values);
20011
20012 columns.forEach((key, i) => {
20013 row[key] = values[i];
20014 });
20015
20016 return row;
20017 });
20018
20019 return data;
20020 }
20021
20022 structureArrayToColumns(parsedData){
20023 var data = [],
20024 firstRow = this.transformHeader(parsedData[0]),
20025 columns = this.table.getColumns();
20026
20027 //remove first row if it is the column names
20028 if(columns[0] && firstRow[0]){
20029 if(columns[0].getDefinition().title === firstRow[0]){
20030 parsedData.shift();
20031 }
20032 }
20033
20034 //convert row arrays to objects
20035 parsedData.forEach((rowData) => {
20036 var row = {};
20037
20038 rowData = this.transformData(rowData);
20039
20040 rowData.forEach((value, index) => {
20041 var column = columns[index];
20042
20043 if(column){
20044 row[column.getField()] = value;
20045 }
20046 });
20047
20048 data.push(row);
20049 });
20050
20051 return data;
20052 }
20053
20054 validateFile(file){
20055 if(this.table.options.importFileValidator){
20056 return this.table.options.importFileValidator.call(this.table, file);
20057 }
20058
20059 return true;
20060 }
20061
20062 validateData(data){
20063 var result;
20064
20065 if(this.table.options.importDataValidator){
20066 result = this.table.options.importDataValidator.call(this.table, data);
20067
20068 if(result === true){
20069 return data;
20070 }else {
20071 return Promise.reject(result);
20072 }
20073 }
20074
20075 return data;
20076 }
20077
20078 setData(data){
20079 this.dispatch("import-imported", data);
20080 this.dispatchExternal("importImported", data);
20081
20082 this.table.dataLoader.clearAlert();
20083
20084 return this.table.setData(data);
20085 }
20086 }
20087
20088 class Interaction extends Module{
20089
20090 static moduleName = "interaction";
20091
20092 constructor(table){
20093 super(table);
20094
20095 this.eventMap = {
20096 //row events
20097 rowClick:"row-click",
20098 rowDblClick:"row-dblclick",
20099 rowContext:"row-contextmenu",
20100 rowMouseEnter:"row-mouseenter",
20101 rowMouseLeave:"row-mouseleave",
20102 rowMouseOver:"row-mouseover",
20103 rowMouseOut:"row-mouseout",
20104 rowMouseMove:"row-mousemove",
20105 rowMouseDown:"row-mousedown",
20106 rowMouseUp:"row-mouseup",
20107 rowTap:"row",
20108 rowDblTap:"row",
20109 rowTapHold:"row",
20110
20111 //cell events
20112 cellClick:"cell-click",
20113 cellDblClick:"cell-dblclick",
20114 cellContext:"cell-contextmenu",
20115 cellMouseEnter:"cell-mouseenter",
20116 cellMouseLeave:"cell-mouseleave",
20117 cellMouseOver:"cell-mouseover",
20118 cellMouseOut:"cell-mouseout",
20119 cellMouseMove:"cell-mousemove",
20120 cellMouseDown:"cell-mousedown",
20121 cellMouseUp:"cell-mouseup",
20122 cellTap:"cell",
20123 cellDblTap:"cell",
20124 cellTapHold:"cell",
20125
20126 //column header events
20127 headerClick:"column-click",
20128 headerDblClick:"column-dblclick",
20129 headerContext:"column-contextmenu",
20130 headerMouseEnter:"column-mouseenter",
20131 headerMouseLeave:"column-mouseleave",
20132 headerMouseOver:"column-mouseover",
20133 headerMouseOut:"column-mouseout",
20134 headerMouseMove:"column-mousemove",
20135 headerMouseDown:"column-mousedown",
20136 headerMouseUp:"column-mouseup",
20137 headerTap:"column",
20138 headerDblTap:"column",
20139 headerTapHold:"column",
20140
20141 //group header
20142 groupClick:"group-click",
20143 groupDblClick:"group-dblclick",
20144 groupContext:"group-contextmenu",
20145 groupMouseEnter:"group-mouseenter",
20146 groupMouseLeave:"group-mouseleave",
20147 groupMouseOver:"group-mouseover",
20148 groupMouseOut:"group-mouseout",
20149 groupMouseMove:"group-mousemove",
20150 groupMouseDown:"group-mousedown",
20151 groupMouseUp:"group-mouseup",
20152 groupTap:"group",
20153 groupDblTap:"group",
20154 groupTapHold:"group",
20155 };
20156
20157 this.subscribers = {};
20158
20159 this.touchSubscribers = {};
20160
20161 this.columnSubscribers = {};
20162
20163 this.touchWatchers = {
20164 row:{
20165 tap:null,
20166 tapDbl:null,
20167 tapHold:null,
20168 },
20169 cell:{
20170 tap:null,
20171 tapDbl:null,
20172 tapHold:null,
20173 },
20174 column:{
20175 tap:null,
20176 tapDbl:null,
20177 tapHold:null,
20178 },
20179 group:{
20180 tap:null,
20181 tapDbl:null,
20182 tapHold:null,
20183 }
20184 };
20185
20186 this.registerColumnOption("headerClick");
20187 this.registerColumnOption("headerDblClick");
20188 this.registerColumnOption("headerContext");
20189 this.registerColumnOption("headerMouseEnter");
20190 this.registerColumnOption("headerMouseLeave");
20191 this.registerColumnOption("headerMouseOver");
20192 this.registerColumnOption("headerMouseOut");
20193 this.registerColumnOption("headerMouseMove");
20194 this.registerColumnOption("headerMouseDown");
20195 this.registerColumnOption("headerMouseUp");
20196 this.registerColumnOption("headerTap");
20197 this.registerColumnOption("headerDblTap");
20198 this.registerColumnOption("headerTapHold");
20199
20200 this.registerColumnOption("cellClick");
20201 this.registerColumnOption("cellDblClick");
20202 this.registerColumnOption("cellContext");
20203 this.registerColumnOption("cellMouseEnter");
20204 this.registerColumnOption("cellMouseLeave");
20205 this.registerColumnOption("cellMouseOver");
20206 this.registerColumnOption("cellMouseOut");
20207 this.registerColumnOption("cellMouseMove");
20208 this.registerColumnOption("cellMouseDown");
20209 this.registerColumnOption("cellMouseUp");
20210 this.registerColumnOption("cellTap");
20211 this.registerColumnOption("cellDblTap");
20212 this.registerColumnOption("cellTapHold");
20213
20214 }
20215
20216 initialize(){
20217 this.initializeExternalEvents();
20218
20219 this.subscribe("column-init", this.initializeColumn.bind(this));
20220 this.subscribe("cell-dblclick", this.cellContentsSelectionFixer.bind(this));
20221 this.subscribe("scroll-horizontal", this.clearTouchWatchers.bind(this));
20222 this.subscribe("scroll-vertical", this.clearTouchWatchers.bind(this));
20223 }
20224
20225 clearTouchWatchers(){
20226 var types = Object.values(this.touchWatchers);
20227
20228 types.forEach((type) => {
20229 for(let key in type){
20230 type[key] = null;
20231 }
20232 });
20233 }
20234
20235 cellContentsSelectionFixer(e, cell){
20236 var range;
20237
20238 if(this.table.modExists("edit")){
20239 if (this.table.modules.edit.currentCell === cell){
20240 return; //prevent instant selection of editor content
20241 }
20242 }
20243
20244 e.preventDefault();
20245
20246 try{
20247 if (document.selection) { // IE
20248 range = document.body.createTextRange();
20249 range.moveToElementText(cell.getElement());
20250 range.select();
20251 } else if (window.getSelection) {
20252 range = document.createRange();
20253 range.selectNode(cell.getElement());
20254 window.getSelection().removeAllRanges();
20255 window.getSelection().addRange(range);
20256 }
20257 }catch(e){}
20258 }
20259
20260 initializeExternalEvents(){
20261 for(let key in this.eventMap){
20262 this.subscriptionChangeExternal(key, this.subscriptionChanged.bind(this, key));
20263 }
20264 }
20265
20266 subscriptionChanged(key, added){
20267 if(added){
20268 if(!this.subscribers[key]){
20269 if(this.eventMap[key].includes("-")){
20270 this.subscribers[key] = this.handle.bind(this, key);
20271 this.subscribe(this.eventMap[key], this.subscribers[key]);
20272 }else {
20273 this.subscribeTouchEvents(key);
20274 }
20275 }
20276 }else {
20277 if(this.eventMap[key].includes("-")){
20278 if(this.subscribers[key] && !this.columnSubscribers[key] && !this.subscribedExternal(key)){
20279 this.unsubscribe(this.eventMap[key], this.subscribers[key]);
20280 delete this.subscribers[key];
20281 }
20282 }else {
20283 this.unsubscribeTouchEvents(key);
20284 }
20285 }
20286 }
20287
20288
20289 subscribeTouchEvents(key){
20290 var type = this.eventMap[key];
20291
20292 if(!this.touchSubscribers[type + "-touchstart"]){
20293 this.touchSubscribers[type + "-touchstart"] = this.handleTouch.bind(this, type, "start");
20294 this.touchSubscribers[type + "-touchend"] = this.handleTouch.bind(this, type, "end");
20295
20296 this.subscribe(type + "-touchstart", this.touchSubscribers[type + "-touchstart"]);
20297 this.subscribe(type + "-touchend", this.touchSubscribers[type + "-touchend"]);
20298 }
20299
20300 this.subscribers[key] = true;
20301 }
20302
20303 unsubscribeTouchEvents(key){
20304 var noTouch = true,
20305 type = this.eventMap[key];
20306
20307 if(this.subscribers[key] && !this.subscribedExternal(key)){
20308 delete this.subscribers[key];
20309
20310 for(let i in this.eventMap){
20311 if(this.eventMap[i] === type){
20312 if(this.subscribers[i]){
20313 noTouch = false;
20314 }
20315 }
20316 }
20317
20318 if(noTouch){
20319 this.unsubscribe(type + "-touchstart", this.touchSubscribers[type + "-touchstart"]);
20320 this.unsubscribe(type + "-touchend", this.touchSubscribers[type + "-touchend"]);
20321
20322 delete this.touchSubscribers[type + "-touchstart"];
20323 delete this.touchSubscribers[type + "-touchend"];
20324 }
20325 }
20326 }
20327
20328 initializeColumn(column){
20329 var def = column.definition;
20330
20331 for(let key in this.eventMap){
20332 if(def[key]){
20333 this.subscriptionChanged(key, true);
20334
20335 if(!this.columnSubscribers[key]){
20336 this.columnSubscribers[key] = [];
20337 }
20338
20339 this.columnSubscribers[key].push(column);
20340 }
20341 }
20342 }
20343
20344 handle(action, e, component){
20345 this.dispatchEvent(action, e, component);
20346 }
20347
20348 handleTouch(type, action, e, component){
20349 var watchers = this.touchWatchers[type];
20350
20351 if(type === "column"){
20352 type = "header";
20353 }
20354
20355 switch(action){
20356 case "start":
20357 watchers.tap = true;
20358
20359 clearTimeout(watchers.tapHold);
20360
20361 watchers.tapHold = setTimeout(() => {
20362 clearTimeout(watchers.tapHold);
20363 watchers.tapHold = null;
20364
20365 watchers.tap = null;
20366 clearTimeout(watchers.tapDbl);
20367 watchers.tapDbl = null;
20368
20369 this.dispatchEvent(type + "TapHold", e, component);
20370 }, 1000);
20371 break;
20372
20373 case "end":
20374 if(watchers.tap){
20375
20376 watchers.tap = null;
20377 this.dispatchEvent(type + "Tap", e, component);
20378 }
20379
20380 if(watchers.tapDbl){
20381 clearTimeout(watchers.tapDbl);
20382 watchers.tapDbl = null;
20383
20384 this.dispatchEvent(type + "DblTap", e, component);
20385 }else {
20386 watchers.tapDbl = setTimeout(() => {
20387 clearTimeout(watchers.tapDbl);
20388 watchers.tapDbl = null;
20389 }, 300);
20390 }
20391
20392 clearTimeout(watchers.tapHold);
20393 watchers.tapHold = null;
20394 break;
20395 }
20396 }
20397
20398 dispatchEvent(action, e, component){
20399 var componentObj = component.getComponent(),
20400 callback;
20401
20402 if(this.columnSubscribers[action]){
20403
20404 if(component instanceof Cell){
20405 callback = component.column.definition[action];
20406 }else if(component instanceof Column){
20407 callback = component.definition[action];
20408 }
20409
20410 if(callback){
20411 callback(e, componentObj);
20412 }
20413 }
20414
20415 this.dispatchExternal(action, e, componentObj);
20416 }
20417 }
20418
20419 var defaultBindings = {
20420 navPrev:"shift + 9",
20421 navNext:9,
20422 navUp:38,
20423 navDown:40,
20424 navLeft:37,
20425 navRight:39,
20426 scrollPageUp:33,
20427 scrollPageDown:34,
20428 scrollToStart:36,
20429 scrollToEnd:35,
20430 };
20431
20432 var defaultActions = {
20433 keyBlock:function(e){
20434 e.stopPropagation();
20435 e.preventDefault();
20436 },
20437
20438 scrollPageUp:function(e){
20439 var rowManager = this.table.rowManager,
20440 newPos = rowManager.scrollTop - rowManager.element.clientHeight;
20441
20442 e.preventDefault();
20443
20444 if(rowManager.displayRowsCount){
20445 if(newPos >= 0){
20446 rowManager.element.scrollTop = newPos;
20447 }else {
20448 rowManager.scrollToRow(rowManager.getDisplayRows()[0]);
20449 }
20450 }
20451
20452 this.table.element.focus();
20453 },
20454
20455 scrollPageDown:function(e){
20456 var rowManager = this.table.rowManager,
20457 newPos = rowManager.scrollTop + rowManager.element.clientHeight,
20458 scrollMax = rowManager.element.scrollHeight;
20459
20460 e.preventDefault();
20461
20462 if(rowManager.displayRowsCount){
20463 if(newPos <= scrollMax){
20464 rowManager.element.scrollTop = newPos;
20465 }else {
20466 rowManager.scrollToRow(rowManager.getDisplayRows()[rowManager.displayRowsCount - 1]);
20467 }
20468 }
20469
20470 this.table.element.focus();
20471
20472 },
20473
20474 scrollToStart:function(e){
20475 var rowManager = this.table.rowManager;
20476
20477 e.preventDefault();
20478
20479 if(rowManager.displayRowsCount){
20480 rowManager.scrollToRow(rowManager.getDisplayRows()[0]);
20481 }
20482
20483 this.table.element.focus();
20484 },
20485
20486 scrollToEnd:function(e){
20487 var rowManager = this.table.rowManager;
20488
20489 e.preventDefault();
20490
20491 if(rowManager.displayRowsCount){
20492 rowManager.scrollToRow(rowManager.getDisplayRows()[rowManager.displayRowsCount - 1]);
20493 }
20494
20495 this.table.element.focus();
20496 },
20497
20498 navPrev:function(e){
20499 this.dispatch("keybinding-nav-prev", e);
20500 },
20501
20502 navNext:function(e){
20503 this.dispatch("keybinding-nav-next", e);
20504 },
20505
20506 navLeft:function(e){
20507 this.dispatch("keybinding-nav-left", e);
20508 },
20509
20510 navRight:function(e){
20511 this.dispatch("keybinding-nav-right", e);
20512 },
20513
20514 navUp:function(e){
20515 this.dispatch("keybinding-nav-up", e);
20516 },
20517
20518 navDown:function(e){
20519 this.dispatch("keybinding-nav-down", e);
20520 },
20521 };
20522
20523 class Keybindings extends Module{
20524
20525 static moduleName = "keybindings";
20526
20527 //load defaults
20528 static bindings = defaultBindings;
20529 static actions = defaultActions;
20530
20531 constructor(table){
20532 super(table);
20533
20534 this.watchKeys = null;
20535 this.pressedKeys = null;
20536 this.keyupBinding = false;
20537 this.keydownBinding = false;
20538
20539 this.registerTableOption("keybindings", {}); //array for keybindings
20540 this.registerTableOption("tabEndNewRow", false); //create new row when tab to end of table
20541 }
20542
20543 initialize(){
20544 var bindings = this.table.options.keybindings,
20545 mergedBindings = {};
20546
20547 this.watchKeys = {};
20548 this.pressedKeys = [];
20549
20550 if(bindings !== false){
20551 Object.assign(mergedBindings, Keybindings.bindings);
20552 Object.assign(mergedBindings, bindings);
20553
20554 this.mapBindings(mergedBindings);
20555 this.bindEvents();
20556 }
20557
20558 this.subscribe("table-destroy", this.clearBindings.bind(this));
20559 }
20560
20561 mapBindings(bindings){
20562 for(let key in bindings){
20563 if(Keybindings.actions[key]){
20564 if(bindings[key]){
20565 if(typeof bindings[key] !== "object"){
20566 bindings[key] = [bindings[key]];
20567 }
20568
20569 bindings[key].forEach((binding) => {
20570 var bindingList = Array.isArray(binding) ? binding : [binding];
20571
20572 bindingList.forEach((item) => {
20573 this.mapBinding(key, item);
20574 });
20575 });
20576 }
20577 }else {
20578 console.warn("Key Binding Error - no such action:", key);
20579 }
20580 }
20581 }
20582
20583 mapBinding(action, symbolsList){
20584 var binding = {
20585 action: Keybindings.actions[action],
20586 keys: [],
20587 ctrl: false,
20588 shift: false,
20589 meta: false,
20590 };
20591
20592 var symbols = symbolsList.toString().toLowerCase().split(" ").join("").split("+");
20593
20594 symbols.forEach((symbol) => {
20595 switch(symbol){
20596 case "ctrl":
20597 binding.ctrl = true;
20598 break;
20599
20600 case "shift":
20601 binding.shift = true;
20602 break;
20603
20604 case "meta":
20605 binding.meta = true;
20606 break;
20607
20608 default:
20609 symbol = isNaN(symbol) ? symbol.toUpperCase().charCodeAt(0) : parseInt(symbol);
20610 binding.keys.push(symbol);
20611
20612 if(!this.watchKeys[symbol]){
20613 this.watchKeys[symbol] = [];
20614 }
20615
20616 this.watchKeys[symbol].push(binding);
20617 }
20618 });
20619 }
20620
20621 bindEvents(){
20622 var self = this;
20623
20624 this.keyupBinding = function(e){
20625 var code = e.keyCode;
20626 var bindings = self.watchKeys[code];
20627
20628 if(bindings){
20629
20630 self.pressedKeys.push(code);
20631
20632 bindings.forEach(function(binding){
20633 self.checkBinding(e, binding);
20634 });
20635 }
20636 };
20637
20638 this.keydownBinding = function(e){
20639 var code = e.keyCode;
20640 var bindings = self.watchKeys[code];
20641
20642 if(bindings){
20643
20644 var index = self.pressedKeys.indexOf(code);
20645
20646 if(index > -1){
20647 self.pressedKeys.splice(index, 1);
20648 }
20649 }
20650 };
20651
20652 this.table.element.addEventListener("keydown", this.keyupBinding);
20653
20654 this.table.element.addEventListener("keyup", this.keydownBinding);
20655 }
20656
20657 clearBindings(){
20658 if(this.keyupBinding){
20659 this.table.element.removeEventListener("keydown", this.keyupBinding);
20660 }
20661
20662 if(this.keydownBinding){
20663 this.table.element.removeEventListener("keyup", this.keydownBinding);
20664 }
20665 }
20666
20667 checkBinding(e, binding){
20668 var match = true;
20669
20670 if(e.ctrlKey == binding.ctrl && e.shiftKey == binding.shift && e.metaKey == binding.meta){
20671 binding.keys.forEach((key) => {
20672 var index = this.pressedKeys.indexOf(key);
20673
20674 if(index == -1){
20675 match = false;
20676 }
20677 });
20678
20679 if(match){
20680 binding.action.call(this, e);
20681 }
20682
20683 return true;
20684 }
20685
20686 return false;
20687 }
20688 }
20689
20690 class Menu extends Module{
20691
20692 static moduleName = "menu";
20693
20694 constructor(table){
20695 super(table);
20696
20697 this.menuContainer = null;
20698 this.nestedMenuBlock = false;
20699
20700 this.currentComponent = null;
20701 this.rootPopup = null;
20702
20703 this.columnSubscribers = {};
20704
20705 // this.registerTableOption("menuContainer", undefined); //deprecated
20706
20707 this.registerTableOption("rowContextMenu", false);
20708 this.registerTableOption("rowClickMenu", false);
20709 this.registerTableOption("rowDblClickMenu", false);
20710 this.registerTableOption("groupContextMenu", false);
20711 this.registerTableOption("groupClickMenu", false);
20712 this.registerTableOption("groupDblClickMenu", false);
20713
20714 this.registerColumnOption("headerContextMenu");
20715 this.registerColumnOption("headerClickMenu");
20716 this.registerColumnOption("headerDblClickMenu");
20717 this.registerColumnOption("headerMenu");
20718 this.registerColumnOption("headerMenuIcon");
20719 this.registerColumnOption("contextMenu");
20720 this.registerColumnOption("clickMenu");
20721 this.registerColumnOption("dblClickMenu");
20722
20723 }
20724
20725 initialize(){
20726 this.deprecatedOptionsCheck();
20727 this.initializeRowWatchers();
20728 this.initializeGroupWatchers();
20729
20730 this.subscribe("column-init", this.initializeColumn.bind(this));
20731 }
20732
20733 deprecatedOptionsCheck(){
20734 // if(!this.deprecationCheck("menuContainer", "popupContainer")){
20735 // this.table.options.popupContainer = this.table.options.menuContainer;
20736 // }
20737 }
20738
20739 initializeRowWatchers(){
20740 if(this.table.options.rowContextMenu){
20741 this.subscribe("row-contextmenu", this.loadMenuEvent.bind(this, this.table.options.rowContextMenu));
20742 this.table.on("rowTapHold", this.loadMenuEvent.bind(this, this.table.options.rowContextMenu));
20743 }
20744
20745 if(this.table.options.rowClickMenu){
20746 this.subscribe("row-click", this.loadMenuEvent.bind(this, this.table.options.rowClickMenu));
20747 }
20748
20749 if(this.table.options.rowDblClickMenu){
20750 this.subscribe("row-dblclick", this.loadMenuEvent.bind(this, this.table.options.rowDblClickMenu));
20751 }
20752 }
20753
20754 initializeGroupWatchers(){
20755 if(this.table.options.groupContextMenu){
20756 this.subscribe("group-contextmenu", this.loadMenuEvent.bind(this, this.table.options.groupContextMenu));
20757 this.table.on("groupTapHold", this.loadMenuEvent.bind(this, this.table.options.groupContextMenu));
20758 }
20759
20760 if(this.table.options.groupClickMenu){
20761 this.subscribe("group-click", this.loadMenuEvent.bind(this, this.table.options.groupClickMenu));
20762 }
20763
20764 if(this.table.options.groupDblClickMenu){
20765 this.subscribe("group-dblclick", this.loadMenuEvent.bind(this, this.table.options.groupDblClickMenu));
20766 }
20767 }
20768
20769 initializeColumn(column){
20770 var def = column.definition;
20771
20772 //handle column events
20773 if(def.headerContextMenu && !this.columnSubscribers.headerContextMenu){
20774 this.columnSubscribers.headerContextMenu = this.loadMenuTableColumnEvent.bind(this, "headerContextMenu");
20775 this.subscribe("column-contextmenu", this.columnSubscribers.headerContextMenu);
20776 this.table.on("headerTapHold", this.loadMenuTableColumnEvent.bind(this, "headerContextMenu"));
20777 }
20778
20779 if(def.headerClickMenu && !this.columnSubscribers.headerClickMenu){
20780 this.columnSubscribers.headerClickMenu = this.loadMenuTableColumnEvent.bind(this, "headerClickMenu");
20781 this.subscribe("column-click", this.columnSubscribers.headerClickMenu);
20782 }
20783
20784 if(def.headerDblClickMenu && !this.columnSubscribers.headerDblClickMenu){
20785 this.columnSubscribers.headerDblClickMenu = this.loadMenuTableColumnEvent.bind(this, "headerDblClickMenu");
20786 this.subscribe("column-dblclick", this.columnSubscribers.headerDblClickMenu);
20787 }
20788
20789 if(def.headerMenu){
20790 this.initializeColumnHeaderMenu(column);
20791 }
20792
20793 //handle cell events
20794 if(def.contextMenu && !this.columnSubscribers.contextMenu){
20795 this.columnSubscribers.contextMenu = this.loadMenuTableCellEvent.bind(this, "contextMenu");
20796 this.subscribe("cell-contextmenu", this.columnSubscribers.contextMenu);
20797 this.table.on("cellTapHold", this.loadMenuTableCellEvent.bind(this, "contextMenu"));
20798 }
20799
20800 if(def.clickMenu && !this.columnSubscribers.clickMenu){
20801 this.columnSubscribers.clickMenu = this.loadMenuTableCellEvent.bind(this, "clickMenu");
20802 this.subscribe("cell-click", this.columnSubscribers.clickMenu);
20803 }
20804
20805 if(def.dblClickMenu && !this.columnSubscribers.dblClickMenu){
20806 this.columnSubscribers.dblClickMenu = this.loadMenuTableCellEvent.bind(this, "dblClickMenu");
20807 this.subscribe("cell-dblclick", this.columnSubscribers.dblClickMenu);
20808 }
20809 }
20810
20811 initializeColumnHeaderMenu(column){
20812 var icon = column.definition.headerMenuIcon,
20813 headerMenuEl;
20814
20815 headerMenuEl = document.createElement("span");
20816 headerMenuEl.classList.add("tabulator-header-popup-button");
20817
20818 if(icon){
20819 if(typeof icon === "function"){
20820 icon = icon(column.getComponent());
20821 }
20822
20823 if(icon instanceof HTMLElement){
20824 headerMenuEl.appendChild(icon);
20825 }else {
20826 headerMenuEl.innerHTML = icon;
20827 }
20828 }else {
20829 headerMenuEl.innerHTML = "&vellip;";
20830 }
20831
20832 headerMenuEl.addEventListener("click", (e) => {
20833 e.stopPropagation();
20834 e.preventDefault();
20835
20836 this.loadMenuEvent(column.definition.headerMenu, e, column);
20837 });
20838
20839 column.titleElement.insertBefore(headerMenuEl, column.titleElement.firstChild);
20840 }
20841
20842 loadMenuTableCellEvent(option, e, cell){
20843 if(cell._cell){
20844 cell = cell._cell;
20845 }
20846
20847 if(cell.column.definition[option]){
20848 this.loadMenuEvent(cell.column.definition[option], e, cell);
20849 }
20850 }
20851
20852 loadMenuTableColumnEvent(option, e, column){
20853 if(column._column){
20854 column = column._column;
20855 }
20856
20857 if(column.definition[option]){
20858 this.loadMenuEvent(column.definition[option], e, column);
20859 }
20860 }
20861
20862 loadMenuEvent(menu, e, component){
20863 if(component._group){
20864 component = component._group;
20865 }else if(component._row){
20866 component = component._row;
20867 }
20868
20869 menu = typeof menu == "function" ? menu.call(this.table, e, component.getComponent()) : menu;
20870
20871 this.loadMenu(e, component, menu);
20872 }
20873
20874 loadMenu(e, component, menu, parentEl, parentPopup){
20875 var touch = !(e instanceof MouseEvent),
20876 menuEl = document.createElement("div"),
20877 popup;
20878
20879 menuEl.classList.add("tabulator-menu");
20880
20881 if(!touch){
20882 e.preventDefault();
20883 }
20884
20885 //abort if no menu set
20886 if(!menu || !menu.length){
20887 return;
20888 }
20889
20890 if(!parentEl){
20891 if(this.nestedMenuBlock){
20892 //abort if child menu already open
20893 if(this.rootPopup){
20894 return;
20895 }
20896 }else {
20897 this.nestedMenuBlock = setTimeout(() => {
20898 this.nestedMenuBlock = false;
20899 }, 100);
20900 }
20901
20902 if(this.rootPopup){
20903 this.rootPopup.hide();
20904 }
20905
20906 this.rootPopup = popup = this.popup(menuEl);
20907
20908 }else {
20909 popup = parentPopup.child(menuEl);
20910 }
20911
20912 menu.forEach((item) => {
20913 var itemEl = document.createElement("div"),
20914 label = item.label,
20915 disabled = item.disabled;
20916
20917 if(item.separator){
20918 itemEl.classList.add("tabulator-menu-separator");
20919 }else {
20920 itemEl.classList.add("tabulator-menu-item");
20921
20922 if(typeof label == "function"){
20923 label = label.call(this.table, component.getComponent());
20924 }
20925
20926 if(label instanceof Node){
20927 itemEl.appendChild(label);
20928 }else {
20929 itemEl.innerHTML = label;
20930 }
20931
20932 if(typeof disabled == "function"){
20933 disabled = disabled.call(this.table, component.getComponent());
20934 }
20935
20936 if(disabled){
20937 itemEl.classList.add("tabulator-menu-item-disabled");
20938 itemEl.addEventListener("click", (e) => {
20939 e.stopPropagation();
20940 });
20941 }else {
20942 if(item.menu && item.menu.length){
20943 itemEl.addEventListener("click", (e) => {
20944 e.stopPropagation();
20945 this.loadMenu(e, component, item.menu, itemEl, popup);
20946 });
20947 }else {
20948 if(item.action){
20949 itemEl.addEventListener("click", (e) => {
20950 item.action(e, component.getComponent());
20951 });
20952 }
20953 }
20954 }
20955
20956 if(item.menu && item.menu.length){
20957 itemEl.classList.add("tabulator-menu-item-submenu");
20958 }
20959 }
20960
20961 menuEl.appendChild(itemEl);
20962 });
20963
20964 menuEl.addEventListener("click", (e) => {
20965 if(this.rootPopup){
20966 this.rootPopup.hide();
20967 }
20968 });
20969
20970 popup.show(parentEl || e);
20971
20972 if(popup === this.rootPopup){
20973 this.rootPopup.hideOnBlur(() => {
20974 this.rootPopup = null;
20975
20976 if(this.currentComponent){
20977 this.dispatch("menu-closed", menu, popup);
20978 this.dispatchExternal("menuClosed", this.currentComponent.getComponent());
20979 this.currentComponent = null;
20980 }
20981 });
20982
20983 this.currentComponent = component;
20984
20985 this.dispatch("menu-opened", menu, popup);
20986 this.dispatchExternal("menuOpened", component.getComponent());
20987 }
20988 }
20989 }
20990
20991 class MoveColumns extends Module{
20992
20993 static moduleName = "moveColumn";
20994
20995 constructor(table){
20996 super(table);
20997
20998 this.placeholderElement = this.createPlaceholderElement();
20999 this.hoverElement = false; //floating column header element
21000 this.checkTimeout = false; //click check timeout holder
21001 this.checkPeriod = 250; //period to wait on mousedown to consider this a move and not a click
21002 this.moving = false; //currently moving column
21003 this.toCol = false; //destination column
21004 this.toColAfter = false; //position of moving column relative to the destination column
21005 this.startX = 0; //starting position within header element
21006 this.autoScrollMargin = 40; //auto scroll on edge when within margin
21007 this.autoScrollStep = 5; //auto scroll distance in pixels
21008 this.autoScrollTimeout = false; //auto scroll timeout
21009 this.touchMove = false;
21010
21011 this.moveHover = this.moveHover.bind(this);
21012 this.endMove = this.endMove.bind(this);
21013
21014 this.registerTableOption("movableColumns", false); //enable movable columns
21015 }
21016
21017 createPlaceholderElement(){
21018 var el = document.createElement("div");
21019
21020 el.classList.add("tabulator-col");
21021 el.classList.add("tabulator-col-placeholder");
21022
21023 return el;
21024 }
21025
21026 initialize(){
21027 if(this.table.options.movableColumns){
21028 this.subscribe("column-init", this.initializeColumn.bind(this));
21029 this.subscribe("alert-show", this.abortMove.bind(this));
21030 }
21031 }
21032
21033 abortMove(){
21034 clearTimeout(this.checkTimeout);
21035 }
21036
21037 initializeColumn(column){
21038 var self = this,
21039 config = {},
21040 colEl;
21041
21042 if(!column.modules.frozen && !column.isGroup && !column.isRowHeader){
21043 colEl = column.getElement();
21044
21045 config.mousemove = function(e){
21046 if(column.parent === self.moving.parent){
21047 if((((self.touchMove ? e.touches[0].pageX : e.pageX) - Helpers.elOffset(colEl).left) + self.table.columnManager.contentsElement.scrollLeft) > (column.getWidth() / 2)){
21048 if(self.toCol !== column || !self.toColAfter){
21049 colEl.parentNode.insertBefore(self.placeholderElement, colEl.nextSibling);
21050 self.moveColumn(column, true);
21051 }
21052 }else {
21053 if(self.toCol !== column || self.toColAfter){
21054 colEl.parentNode.insertBefore(self.placeholderElement, colEl);
21055 self.moveColumn(column, false);
21056 }
21057 }
21058 }
21059 }.bind(self);
21060
21061 colEl.addEventListener("mousedown", function(e){
21062 self.touchMove = false;
21063 if(e.which === 1){
21064 self.checkTimeout = setTimeout(function(){
21065 self.startMove(e, column);
21066 }, self.checkPeriod);
21067 }
21068 });
21069
21070 colEl.addEventListener("mouseup", function(e){
21071 if(e.which === 1){
21072 if(self.checkTimeout){
21073 clearTimeout(self.checkTimeout);
21074 }
21075 }
21076 });
21077
21078 self.bindTouchEvents(column);
21079 }
21080
21081 column.modules.moveColumn = config;
21082 }
21083
21084 bindTouchEvents(column){
21085 var colEl = column.getElement(),
21086 startXMove = false, //shifting center position of the cell
21087 nextCol, prevCol, nextColWidth, prevColWidth, nextColWidthLast, prevColWidthLast;
21088
21089 colEl.addEventListener("touchstart", (e) => {
21090 this.checkTimeout = setTimeout(() => {
21091 this.touchMove = true;
21092 nextCol = column.nextColumn();
21093 nextColWidth = nextCol ? nextCol.getWidth()/2 : 0;
21094 prevCol = column.prevColumn();
21095 prevColWidth = prevCol ? prevCol.getWidth()/2 : 0;
21096 nextColWidthLast = 0;
21097 prevColWidthLast = 0;
21098 startXMove = false;
21099
21100 this.startMove(e, column);
21101 }, this.checkPeriod);
21102 }, {passive: true});
21103
21104 colEl.addEventListener("touchmove", (e) => {
21105 var diff, moveToCol;
21106
21107 if(this.moving){
21108 this.moveHover(e);
21109
21110 if(!startXMove){
21111 startXMove = e.touches[0].pageX;
21112 }
21113
21114 diff = e.touches[0].pageX - startXMove;
21115
21116 if(diff > 0){
21117 if(nextCol && diff - nextColWidthLast > nextColWidth){
21118 moveToCol = nextCol;
21119
21120 if(moveToCol !== column){
21121 startXMove = e.touches[0].pageX;
21122 moveToCol.getElement().parentNode.insertBefore(this.placeholderElement, moveToCol.getElement().nextSibling);
21123 this.moveColumn(moveToCol, true);
21124 }
21125 }
21126 }else {
21127 if(prevCol && -diff - prevColWidthLast > prevColWidth){
21128 moveToCol = prevCol;
21129
21130 if(moveToCol !== column){
21131 startXMove = e.touches[0].pageX;
21132 moveToCol.getElement().parentNode.insertBefore(this.placeholderElement, moveToCol.getElement());
21133 this.moveColumn(moveToCol, false);
21134 }
21135 }
21136 }
21137
21138 if(moveToCol){
21139 nextCol = moveToCol.nextColumn();
21140 nextColWidthLast = nextColWidth;
21141 nextColWidth = nextCol ? nextCol.getWidth() / 2 : 0;
21142 prevCol = moveToCol.prevColumn();
21143 prevColWidthLast = prevColWidth;
21144 prevColWidth = prevCol ? prevCol.getWidth() / 2 : 0;
21145 }
21146 }
21147 }, {passive: true});
21148
21149 colEl.addEventListener("touchend", (e) => {
21150 if(this.checkTimeout){
21151 clearTimeout(this.checkTimeout);
21152 }
21153 if(this.moving){
21154 this.endMove(e);
21155 }
21156 });
21157 }
21158
21159 startMove(e, column){
21160 var element = column.getElement(),
21161 headerElement = this.table.columnManager.getContentsElement(),
21162 headersElement = this.table.columnManager.getHeadersElement();
21163
21164 //Prevent moving columns when range selection is active
21165 if(this.table.modules.selectRange && this.table.modules.selectRange.columnSelection){
21166 if(this.table.modules.selectRange.mousedown && this.table.modules.selectRange.selecting === "column"){
21167 return;
21168 }
21169 }
21170
21171 this.moving = column;
21172 this.startX = (this.touchMove ? e.touches[0].pageX : e.pageX) - Helpers.elOffset(element).left;
21173
21174 this.table.element.classList.add("tabulator-block-select");
21175
21176 //create placeholder
21177 this.placeholderElement.style.width = column.getWidth() + "px";
21178 this.placeholderElement.style.height = column.getHeight() + "px";
21179
21180 element.parentNode.insertBefore(this.placeholderElement, element);
21181 element.parentNode.removeChild(element);
21182
21183 //create hover element
21184 this.hoverElement = element.cloneNode(true);
21185 this.hoverElement.classList.add("tabulator-moving");
21186
21187 headerElement.appendChild(this.hoverElement);
21188
21189 this.hoverElement.style.left = "0";
21190 this.hoverElement.style.bottom = (headerElement.clientHeight - headersElement.offsetHeight) + "px";
21191
21192 if(!this.touchMove){
21193 this._bindMouseMove();
21194
21195 document.body.addEventListener("mousemove", this.moveHover);
21196 document.body.addEventListener("mouseup", this.endMove);
21197 }
21198
21199 this.moveHover(e);
21200
21201 this.dispatch("column-moving", e, this.moving);
21202 }
21203
21204 _bindMouseMove(){
21205 this.table.columnManager.columnsByIndex.forEach(function(column){
21206 if(column.modules.moveColumn.mousemove){
21207 column.getElement().addEventListener("mousemove", column.modules.moveColumn.mousemove);
21208 }
21209 });
21210 }
21211
21212 _unbindMouseMove(){
21213 this.table.columnManager.columnsByIndex.forEach(function(column){
21214 if(column.modules.moveColumn.mousemove){
21215 column.getElement().removeEventListener("mousemove", column.modules.moveColumn.mousemove);
21216 }
21217 });
21218 }
21219
21220 moveColumn(column, after){
21221 var movingCells = this.moving.getCells();
21222
21223 this.toCol = column;
21224 this.toColAfter = after;
21225
21226 if(after){
21227 column.getCells().forEach(function(cell, i){
21228 var cellEl = cell.getElement(true);
21229
21230 if(cellEl.parentNode && movingCells[i]){
21231 cellEl.parentNode.insertBefore(movingCells[i].getElement(), cellEl.nextSibling);
21232 }
21233 });
21234 }else {
21235 column.getCells().forEach(function(cell, i){
21236 var cellEl = cell.getElement(true);
21237
21238 if(cellEl.parentNode && movingCells[i]){
21239 cellEl.parentNode.insertBefore(movingCells[i].getElement(), cellEl);
21240 }
21241 });
21242 }
21243 }
21244
21245 endMove(e){
21246 if(e.which === 1 || this.touchMove){
21247 this._unbindMouseMove();
21248
21249 this.placeholderElement.parentNode.insertBefore(this.moving.getElement(), this.placeholderElement.nextSibling);
21250 this.placeholderElement.parentNode.removeChild(this.placeholderElement);
21251 this.hoverElement.parentNode.removeChild(this.hoverElement);
21252
21253 this.table.element.classList.remove("tabulator-block-select");
21254
21255 if(this.toCol){
21256 this.table.columnManager.moveColumnActual(this.moving, this.toCol, this.toColAfter);
21257 }
21258
21259 this.moving = false;
21260 this.toCol = false;
21261 this.toColAfter = false;
21262
21263 if(!this.touchMove){
21264 document.body.removeEventListener("mousemove", this.moveHover);
21265 document.body.removeEventListener("mouseup", this.endMove);
21266 }
21267 }
21268 }
21269
21270 moveHover(e){
21271 var columnHolder = this.table.columnManager.getContentsElement(),
21272 scrollLeft = columnHolder.scrollLeft,
21273 xPos = ((this.touchMove ? e.touches[0].pageX : e.pageX) - Helpers.elOffset(columnHolder).left) + scrollLeft,
21274 scrollPos;
21275
21276 this.hoverElement.style.left = (xPos - this.startX) + "px";
21277
21278 if(xPos - scrollLeft < this.autoScrollMargin){
21279 if(!this.autoScrollTimeout){
21280 this.autoScrollTimeout = setTimeout(() => {
21281 scrollPos = Math.max(0,scrollLeft-5);
21282 this.table.rowManager.getElement().scrollLeft = scrollPos;
21283 this.autoScrollTimeout = false;
21284 }, 1);
21285 }
21286 }
21287
21288 if(scrollLeft + columnHolder.clientWidth - xPos < this.autoScrollMargin){
21289 if(!this.autoScrollTimeout){
21290 this.autoScrollTimeout = setTimeout(() => {
21291 scrollPos = Math.min(columnHolder.clientWidth, scrollLeft+5);
21292 this.table.rowManager.getElement().scrollLeft = scrollPos;
21293 this.autoScrollTimeout = false;
21294 }, 1);
21295 }
21296 }
21297 }
21298 }
21299
21300 var defaultSenders = {
21301 delete:function(fromRow, toRow, toTable){
21302 fromRow.delete();
21303 }
21304 };
21305
21306 var defaultReceivers = {
21307 insert:function(fromRow, toRow, fromTable){
21308 this.table.addRow(fromRow.getData(), undefined, toRow);
21309 return true;
21310 },
21311
21312 add:function(fromRow, toRow, fromTable){
21313 this.table.addRow(fromRow.getData());
21314 return true;
21315 },
21316
21317 update:function(fromRow, toRow, fromTable){
21318 if(toRow){
21319 toRow.update(fromRow.getData());
21320 return true;
21321 }
21322
21323 return false;
21324 },
21325
21326 replace:function(fromRow, toRow, fromTable){
21327 if(toRow){
21328 this.table.addRow(fromRow.getData(), undefined, toRow);
21329 toRow.delete();
21330 return true;
21331 }
21332
21333 return false;
21334 },
21335 };
21336
21337 class MoveRows extends Module{
21338
21339 static moduleName = "moveRow";
21340
21341 //load defaults
21342 static senders = defaultSenders;
21343 static receivers = defaultReceivers;
21344
21345 constructor(table){
21346 super(table);
21347
21348 this.placeholderElement = this.createPlaceholderElement();
21349 this.hoverElement = false; //floating row header element
21350 this.checkTimeout = false; //click check timeout holder
21351 this.checkPeriod = 150; //period to wait on mousedown to consider this a move and not a click
21352 this.moving = false; //currently moving row
21353 this.toRow = false; //destination row
21354 this.toRowAfter = false; //position of moving row relative to the destination row
21355 this.hasHandle = false; //row has handle instead of fully movable row
21356 this.startY = 0; //starting Y position within header element
21357 this.startX = 0; //starting X position within header element
21358
21359 this.moveHover = this.moveHover.bind(this);
21360 this.endMove = this.endMove.bind(this);
21361 this.tableRowDropEvent = false;
21362
21363 this.touchMove = false;
21364
21365 this.connection = false;
21366 this.connectionSelectorsTables = false;
21367 this.connectionSelectorsElements = false;
21368 this.connectionElements = [];
21369 this.connections = [];
21370
21371 this.connectedTable = false;
21372 this.connectedRow = false;
21373
21374 this.registerTableOption("movableRows", false); //enable movable rows
21375 this.registerTableOption("movableRowsConnectedTables", false); //tables for movable rows to be connected to
21376 this.registerTableOption("movableRowsConnectedElements", false); //other elements for movable rows to be connected to
21377 this.registerTableOption("movableRowsSender", false);
21378 this.registerTableOption("movableRowsReceiver", "insert");
21379
21380 this.registerColumnOption("rowHandle");
21381 }
21382
21383 createPlaceholderElement(){
21384 var el = document.createElement("div");
21385
21386 el.classList.add("tabulator-row");
21387 el.classList.add("tabulator-row-placeholder");
21388
21389 return el;
21390 }
21391
21392 initialize(){
21393 if(this.table.options.movableRows){
21394 this.connectionSelectorsTables = this.table.options.movableRowsConnectedTables;
21395 this.connectionSelectorsElements = this.table.options.movableRowsConnectedElements;
21396
21397 this.connection = this.connectionSelectorsTables || this.connectionSelectorsElements;
21398
21399 this.subscribe("cell-init", this.initializeCell.bind(this));
21400 this.subscribe("column-init", this.initializeColumn.bind(this));
21401 this.subscribe("row-init", this.initializeRow.bind(this));
21402 }
21403 }
21404
21405 initializeGroupHeader(group){
21406 var self = this,
21407 config = {};
21408
21409 //inter table drag drop
21410 config.mouseup = function(e){
21411 self.tableRowDrop(e, group);
21412 }.bind(self);
21413
21414 //same table drag drop
21415 config.mousemove = function(e){
21416 var rowEl;
21417
21418 if(((e.pageY - Helpers.elOffset(group.element).top) + self.table.rowManager.element.scrollTop) > (group.getHeight() / 2)){
21419 if(self.toRow !== group || !self.toRowAfter){
21420 rowEl = group.getElement();
21421 rowEl.parentNode.insertBefore(self.placeholderElement, rowEl.nextSibling);
21422 self.moveRow(group, true);
21423 }
21424 }else {
21425 if(self.toRow !== group || self.toRowAfter){
21426 rowEl = group.getElement();
21427 if(rowEl.previousSibling){
21428 rowEl.parentNode.insertBefore(self.placeholderElement, rowEl);
21429 self.moveRow(group, false);
21430 }
21431 }
21432 }
21433 }.bind(self);
21434
21435 group.modules.moveRow = config;
21436 }
21437
21438 initializeRow(row){
21439 var self = this,
21440 config = {},
21441 rowEl;
21442
21443 //inter table drag drop
21444 config.mouseup = function(e){
21445 self.tableRowDrop(e, row);
21446 }.bind(self);
21447
21448 //same table drag drop
21449 config.mousemove = function(e){
21450 var rowEl = row.getElement();
21451
21452 if(((e.pageY - Helpers.elOffset(rowEl).top) + self.table.rowManager.element.scrollTop) > (row.getHeight() / 2)){
21453 if(self.toRow !== row || !self.toRowAfter){
21454 rowEl.parentNode.insertBefore(self.placeholderElement, rowEl.nextSibling);
21455 self.moveRow(row, true);
21456 }
21457 }else {
21458 if(self.toRow !== row || self.toRowAfter){
21459 rowEl.parentNode.insertBefore(self.placeholderElement, rowEl);
21460 self.moveRow(row, false);
21461 }
21462 }
21463 }.bind(self);
21464
21465
21466 if(!this.hasHandle){
21467
21468 rowEl = row.getElement();
21469
21470 rowEl.addEventListener("mousedown", function(e){
21471 if(e.which === 1){
21472 self.checkTimeout = setTimeout(function(){
21473 self.startMove(e, row);
21474 }, self.checkPeriod);
21475 }
21476 });
21477
21478 rowEl.addEventListener("mouseup", function(e){
21479 if(e.which === 1){
21480 if(self.checkTimeout){
21481 clearTimeout(self.checkTimeout);
21482 }
21483 }
21484 });
21485
21486 this.bindTouchEvents(row, row.getElement());
21487 }
21488
21489 row.modules.moveRow = config;
21490 }
21491
21492 initializeColumn(column){
21493 if(column.definition.rowHandle && this.table.options.movableRows !== false){
21494 this.hasHandle = true;
21495 }
21496 }
21497
21498 initializeCell(cell){
21499 if(cell.column.definition.rowHandle && this.table.options.movableRows !== false){
21500 var self = this,
21501 cellEl = cell.getElement(true);
21502
21503 cellEl.addEventListener("mousedown", function(e){
21504 if(e.which === 1){
21505 self.checkTimeout = setTimeout(function(){
21506 self.startMove(e, cell.row);
21507 }, self.checkPeriod);
21508 }
21509 });
21510
21511 cellEl.addEventListener("mouseup", function(e){
21512 if(e.which === 1){
21513 if(self.checkTimeout){
21514 clearTimeout(self.checkTimeout);
21515 }
21516 }
21517 });
21518
21519 this.bindTouchEvents(cell.row, cellEl);
21520 }
21521 }
21522
21523 bindTouchEvents(row, element){
21524 var startYMove = false, //shifting center position of the cell
21525 nextRow, prevRow, nextRowHeight, prevRowHeight, nextRowHeightLast, prevRowHeightLast;
21526
21527 element.addEventListener("touchstart", (e) => {
21528 this.checkTimeout = setTimeout(() => {
21529 this.touchMove = true;
21530 nextRow = row.nextRow();
21531 nextRowHeight = nextRow ? nextRow.getHeight()/2 : 0;
21532 prevRow = row.prevRow();
21533 prevRowHeight = prevRow ? prevRow.getHeight()/2 : 0;
21534 nextRowHeightLast = 0;
21535 prevRowHeightLast = 0;
21536 startYMove = false;
21537
21538 this.startMove(e, row);
21539 }, this.checkPeriod);
21540 }, {passive: true});
21541 this.moving, this.toRow, this.toRowAfter;
21542 element.addEventListener("touchmove", (e) => {
21543
21544 var diff, moveToRow;
21545
21546 if(this.moving){
21547 e.preventDefault();
21548
21549 this.moveHover(e);
21550
21551 if(!startYMove){
21552 startYMove = e.touches[0].pageY;
21553 }
21554
21555 diff = e.touches[0].pageY - startYMove;
21556
21557 if(diff > 0){
21558 if(nextRow && diff - nextRowHeightLast > nextRowHeight){
21559 moveToRow = nextRow;
21560
21561 if(moveToRow !== row){
21562 startYMove = e.touches[0].pageY;
21563 moveToRow.getElement().parentNode.insertBefore(this.placeholderElement, moveToRow.getElement().nextSibling);
21564 this.moveRow(moveToRow, true);
21565 }
21566 }
21567 }else {
21568 if(prevRow && -diff - prevRowHeightLast > prevRowHeight){
21569 moveToRow = prevRow;
21570
21571 if(moveToRow !== row){
21572 startYMove = e.touches[0].pageY;
21573 moveToRow.getElement().parentNode.insertBefore(this.placeholderElement, moveToRow.getElement());
21574 this.moveRow(moveToRow, false);
21575 }
21576 }
21577 }
21578
21579 if(moveToRow){
21580 nextRow = moveToRow.nextRow();
21581 nextRowHeightLast = nextRowHeight;
21582 nextRowHeight = nextRow ? nextRow.getHeight() / 2 : 0;
21583 prevRow = moveToRow.prevRow();
21584 prevRowHeightLast = prevRowHeight;
21585 prevRowHeight = prevRow ? prevRow.getHeight() / 2 : 0;
21586 }
21587 }
21588 });
21589
21590 element.addEventListener("touchend", (e) => {
21591 if(this.checkTimeout){
21592 clearTimeout(this.checkTimeout);
21593 }
21594 if(this.moving){
21595 this.endMove(e);
21596 this.touchMove = false;
21597 }
21598 });
21599 }
21600
21601 _bindMouseMove(){
21602 this.table.rowManager.getDisplayRows().forEach((row) => {
21603 if((row.type === "row" || row.type === "group") && row.modules.moveRow && row.modules.moveRow.mousemove){
21604 row.getElement().addEventListener("mousemove", row.modules.moveRow.mousemove);
21605 }
21606 });
21607 }
21608
21609 _unbindMouseMove(){
21610 this.table.rowManager.getDisplayRows().forEach((row) => {
21611 if((row.type === "row" || row.type === "group") && row.modules.moveRow && row.modules.moveRow.mousemove){
21612 row.getElement().removeEventListener("mousemove", row.modules.moveRow.mousemove);
21613 }
21614 });
21615 }
21616
21617 startMove(e, row){
21618 var element = row.getElement();
21619
21620 this.setStartPosition(e, row);
21621
21622 this.moving = row;
21623
21624 this.table.element.classList.add("tabulator-block-select");
21625
21626 //create placeholder
21627 this.placeholderElement.style.width = row.getWidth() + "px";
21628 this.placeholderElement.style.height = row.getHeight() + "px";
21629
21630 if(!this.connection){
21631 element.parentNode.insertBefore(this.placeholderElement, element);
21632 element.parentNode.removeChild(element);
21633 }else {
21634 this.table.element.classList.add("tabulator-movingrow-sending");
21635 this.connectToTables(row);
21636 }
21637
21638 //create hover element
21639 this.hoverElement = element.cloneNode(true);
21640 this.hoverElement.classList.add("tabulator-moving");
21641
21642 if(this.connection){
21643 document.body.appendChild(this.hoverElement);
21644 this.hoverElement.style.left = "0";
21645 this.hoverElement.style.top = "0";
21646 this.hoverElement.style.width = this.table.element.clientWidth + "px";
21647 this.hoverElement.style.whiteSpace = "nowrap";
21648 this.hoverElement.style.overflow = "hidden";
21649 this.hoverElement.style.pointerEvents = "none";
21650 }else {
21651 this.table.rowManager.getTableElement().appendChild(this.hoverElement);
21652
21653 this.hoverElement.style.left = "0";
21654 this.hoverElement.style.top = "0";
21655
21656 this._bindMouseMove();
21657 }
21658
21659 document.body.addEventListener("mousemove", this.moveHover);
21660 document.body.addEventListener("mouseup", this.endMove);
21661
21662 this.dispatchExternal("rowMoving", row.getComponent());
21663
21664 this.moveHover(e);
21665 }
21666
21667 setStartPosition(e, row){
21668 var pageX = this.touchMove ? e.touches[0].pageX : e.pageX,
21669 pageY = this.touchMove ? e.touches[0].pageY : e.pageY,
21670 element, position;
21671
21672 element = row.getElement();
21673 if(this.connection){
21674 position = element.getBoundingClientRect();
21675
21676 this.startX = position.left - pageX + window.pageXOffset;
21677 this.startY = position.top - pageY + window.pageYOffset;
21678 }else {
21679 this.startY = (pageY - element.getBoundingClientRect().top);
21680 }
21681 }
21682
21683 endMove(e){
21684 if(!e || e.which === 1 || this.touchMove){
21685 this._unbindMouseMove();
21686
21687 if(!this.connection){
21688 this.placeholderElement.parentNode.insertBefore(this.moving.getElement(), this.placeholderElement.nextSibling);
21689 this.placeholderElement.parentNode.removeChild(this.placeholderElement);
21690 }
21691
21692 this.hoverElement.parentNode.removeChild(this.hoverElement);
21693
21694 this.table.element.classList.remove("tabulator-block-select");
21695
21696 if(this.toRow){
21697 this.table.rowManager.moveRow(this.moving, this.toRow, this.toRowAfter);
21698 }else {
21699 this.dispatchExternal("rowMoveCancelled", this.moving.getComponent());
21700 }
21701
21702 this.moving = false;
21703 this.toRow = false;
21704 this.toRowAfter = false;
21705
21706 document.body.removeEventListener("mousemove", this.moveHover);
21707 document.body.removeEventListener("mouseup", this.endMove);
21708
21709 if(this.connection){
21710 this.table.element.classList.remove("tabulator-movingrow-sending");
21711 this.disconnectFromTables();
21712 }
21713 }
21714 }
21715
21716 moveRow(row, after){
21717 this.toRow = row;
21718 this.toRowAfter = after;
21719 }
21720
21721 moveHover(e){
21722 if(this.connection){
21723 this.moveHoverConnections.call(this, e);
21724 }else {
21725 this.moveHoverTable.call(this, e);
21726 }
21727 }
21728
21729 moveHoverTable(e){
21730 var rowHolder = this.table.rowManager.getElement(),
21731 scrollTop = rowHolder.scrollTop,
21732 yPos = ((this.touchMove ? e.touches[0].pageY : e.pageY) - rowHolder.getBoundingClientRect().top) + scrollTop;
21733
21734 this.hoverElement.style.top = Math.min(yPos - this.startY, this.table.rowManager.element.scrollHeight - this.hoverElement.offsetHeight) + "px";
21735 }
21736
21737 moveHoverConnections(e){
21738 this.hoverElement.style.left = (this.startX + (this.touchMove ? e.touches[0].pageX : e.pageX)) + "px";
21739 this.hoverElement.style.top = (this.startY + (this.touchMove ? e.touches[0].pageY : e.pageY)) + "px";
21740 }
21741
21742 elementRowDrop(e, element, row){
21743 this.dispatchExternal("movableRowsElementDrop", e, element, row ? row.getComponent() : false);
21744 }
21745
21746 //establish connection with other tables
21747 connectToTables(row){
21748 var connectionTables;
21749
21750 if(this.connectionSelectorsTables){
21751 connectionTables = this.commsConnections(this.connectionSelectorsTables);
21752
21753 this.dispatchExternal("movableRowsSendingStart", connectionTables);
21754
21755 this.commsSend(this.connectionSelectorsTables, "moveRow", "connect", {
21756 row:row,
21757 });
21758 }
21759
21760 if(this.connectionSelectorsElements){
21761
21762 this.connectionElements = [];
21763
21764 if(!Array.isArray(this.connectionSelectorsElements)){
21765 this.connectionSelectorsElements = [this.connectionSelectorsElements];
21766 }
21767
21768 this.connectionSelectorsElements.forEach((query) => {
21769 if(typeof query === "string"){
21770 this.connectionElements = this.connectionElements.concat(Array.prototype.slice.call(document.querySelectorAll(query)));
21771 }else {
21772 this.connectionElements.push(query);
21773 }
21774 });
21775
21776 this.connectionElements.forEach((element) => {
21777 var dropEvent = (e) => {
21778 this.elementRowDrop(e, element, this.moving);
21779 };
21780
21781 element.addEventListener("mouseup", dropEvent);
21782 element.tabulatorElementDropEvent = dropEvent;
21783
21784 element.classList.add("tabulator-movingrow-receiving");
21785 });
21786 }
21787 }
21788
21789 //disconnect from other tables
21790 disconnectFromTables(){
21791 var connectionTables;
21792
21793 if(this.connectionSelectorsTables){
21794 connectionTables = this.commsConnections(this.connectionSelectorsTables);
21795
21796 this.dispatchExternal("movableRowsSendingStop", connectionTables);
21797
21798 this.commsSend(this.connectionSelectorsTables, "moveRow", "disconnect");
21799 }
21800
21801 this.connectionElements.forEach((element) => {
21802 element.classList.remove("tabulator-movingrow-receiving");
21803 element.removeEventListener("mouseup", element.tabulatorElementDropEvent);
21804 delete element.tabulatorElementDropEvent;
21805 });
21806 }
21807
21808 //accept incomming connection
21809 connect(table, row){
21810 if(!this.connectedTable){
21811 this.connectedTable = table;
21812 this.connectedRow = row;
21813
21814 this.table.element.classList.add("tabulator-movingrow-receiving");
21815
21816 this.table.rowManager.getDisplayRows().forEach((row) => {
21817 if(row.type === "row" && row.modules.moveRow && row.modules.moveRow.mouseup){
21818 row.getElement().addEventListener("mouseup", row.modules.moveRow.mouseup);
21819 }
21820 });
21821
21822 this.tableRowDropEvent = this.tableRowDrop.bind(this);
21823
21824 this.table.element.addEventListener("mouseup", this.tableRowDropEvent);
21825
21826 this.dispatchExternal("movableRowsReceivingStart", row, table);
21827
21828 return true;
21829 }else {
21830 console.warn("Move Row Error - Table cannot accept connection, already connected to table:", this.connectedTable);
21831 return false;
21832 }
21833 }
21834
21835 //close incoming connection
21836 disconnect(table){
21837 if(table === this.connectedTable){
21838 this.connectedTable = false;
21839 this.connectedRow = false;
21840
21841 this.table.element.classList.remove("tabulator-movingrow-receiving");
21842
21843 this.table.rowManager.getDisplayRows().forEach((row) =>{
21844 if(row.type === "row" && row.modules.moveRow && row.modules.moveRow.mouseup){
21845 row.getElement().removeEventListener("mouseup", row.modules.moveRow.mouseup);
21846 }
21847 });
21848
21849 this.table.element.removeEventListener("mouseup", this.tableRowDropEvent);
21850
21851 this.dispatchExternal("movableRowsReceivingStop", table);
21852 }else {
21853 console.warn("Move Row Error - trying to disconnect from non connected table");
21854 }
21855 }
21856
21857 dropComplete(table, row, success){
21858 var sender = false;
21859
21860 if(success){
21861
21862 switch(typeof this.table.options.movableRowsSender){
21863 case "string":
21864 sender = MoveRows.senders[this.table.options.movableRowsSender];
21865 break;
21866
21867 case "function":
21868 sender = this.table.options.movableRowsSender;
21869 break;
21870 }
21871
21872 if(sender){
21873 sender.call(this, this.moving ? this.moving.getComponent() : undefined, row ? row.getComponent() : undefined, table);
21874 }else {
21875 if(this.table.options.movableRowsSender){
21876 console.warn("Mover Row Error - no matching sender found:", this.table.options.movableRowsSender);
21877 }
21878 }
21879
21880 this.dispatchExternal("movableRowsSent", this.moving.getComponent(), row ? row.getComponent() : undefined, table);
21881 }else {
21882 this.dispatchExternal("movableRowsSentFailed", this.moving.getComponent(), row ? row.getComponent() : undefined, table);
21883 }
21884
21885 this.endMove();
21886 }
21887
21888 tableRowDrop(e, row){
21889 var receiver = false,
21890 success = false;
21891
21892 e.stopImmediatePropagation();
21893
21894 switch(typeof this.table.options.movableRowsReceiver){
21895 case "string":
21896 receiver = MoveRows.receivers[this.table.options.movableRowsReceiver];
21897 break;
21898
21899 case "function":
21900 receiver = this.table.options.movableRowsReceiver;
21901 break;
21902 }
21903
21904 if(receiver){
21905 success = receiver.call(this, this.connectedRow.getComponent(), row ? row.getComponent() : undefined, this.connectedTable);
21906 }else {
21907 console.warn("Mover Row Error - no matching receiver found:", this.table.options.movableRowsReceiver);
21908 }
21909
21910 if(success){
21911 this.dispatchExternal("movableRowsReceived", this.connectedRow.getComponent(), row ? row.getComponent() : undefined, this.connectedTable);
21912 }else {
21913 this.dispatchExternal("movableRowsReceivedFailed", this.connectedRow.getComponent(), row ? row.getComponent() : undefined, this.connectedTable);
21914 }
21915
21916 this.commsSend(this.connectedTable, "moveRow", "dropcomplete", {
21917 row:row,
21918 success:success,
21919 });
21920 }
21921
21922 commsReceived(table, action, data){
21923 switch(action){
21924 case "connect":
21925 return this.connect(table, data.row);
21926
21927 case "disconnect":
21928 return this.disconnect(table);
21929
21930 case "dropcomplete":
21931 return this.dropComplete(table, data.row, data.success);
21932 }
21933 }
21934 }
21935
21936 var defaultMutators = {};
21937
21938 class Mutator extends Module{
21939
21940 static moduleName = "mutator";
21941
21942 //load defaults
21943 static mutators = defaultMutators;
21944
21945 constructor(table){
21946 super(table);
21947
21948 this.allowedTypes = ["", "data", "edit", "clipboard", "import"]; //list of mutation types
21949 this.enabled = true;
21950
21951 this.registerColumnOption("mutator");
21952 this.registerColumnOption("mutatorParams");
21953 this.registerColumnOption("mutatorData");
21954 this.registerColumnOption("mutatorDataParams");
21955 this.registerColumnOption("mutatorEdit");
21956 this.registerColumnOption("mutatorEditParams");
21957 this.registerColumnOption("mutatorClipboard");
21958 this.registerColumnOption("mutatorClipboardParams");
21959 this.registerColumnOption("mutatorImport");
21960 this.registerColumnOption("mutatorImportParams");
21961 this.registerColumnOption("mutateLink");
21962 }
21963
21964 initialize(){
21965 this.subscribe("cell-value-changing", this.transformCell.bind(this));
21966 this.subscribe("cell-value-changed", this.mutateLink.bind(this));
21967 this.subscribe("column-layout", this.initializeColumn.bind(this));
21968 this.subscribe("row-data-init-before", this.rowDataChanged.bind(this));
21969 this.subscribe("row-data-changing", this.rowDataChanged.bind(this));
21970 }
21971
21972 rowDataChanged(row, tempData, updatedData){
21973 return this.transformRow(tempData, "data", updatedData);
21974 }
21975
21976 //initialize column mutator
21977 initializeColumn(column){
21978 var match = false,
21979 config = {};
21980
21981 this.allowedTypes.forEach((type) => {
21982 var key = "mutator" + (type.charAt(0).toUpperCase() + type.slice(1)),
21983 mutator;
21984
21985 if(column.definition[key]){
21986 mutator = this.lookupMutator(column.definition[key]);
21987
21988 if(mutator){
21989 match = true;
21990
21991 config[key] = {
21992 mutator:mutator,
21993 params: column.definition[key + "Params"] || {},
21994 };
21995 }
21996 }
21997 });
21998
21999 if(match){
22000 column.modules.mutate = config;
22001 }
22002 }
22003
22004 lookupMutator(value){
22005 var mutator = false;
22006
22007 //set column mutator
22008 switch(typeof value){
22009 case "string":
22010 if(Mutator.mutators[value]){
22011 mutator = Mutator.mutators[value];
22012 }else {
22013 console.warn("Mutator Error - No such mutator found, ignoring: ", value);
22014 }
22015 break;
22016
22017 case "function":
22018 mutator = value;
22019 break;
22020 }
22021
22022 return mutator;
22023 }
22024
22025 //apply mutator to row
22026 transformRow(data, type, updatedData){
22027 var key = "mutator" + (type.charAt(0).toUpperCase() + type.slice(1)),
22028 value;
22029
22030 // console.log("key", key)
22031
22032 if(this.enabled){
22033
22034 this.table.columnManager.traverse((column) => {
22035 var mutator, params, component;
22036
22037 if(column.modules.mutate){
22038 mutator = column.modules.mutate[key] || column.modules.mutate.mutator || false;
22039
22040 if(mutator){
22041 value = column.getFieldValue(typeof updatedData !== "undefined" ? updatedData : data);
22042
22043 if((type == "data" && !updatedData)|| typeof value !== "undefined"){
22044 component = column.getComponent();
22045 params = typeof mutator.params === "function" ? mutator.params(value, data, type, component) : mutator.params;
22046 column.setFieldValue(data, mutator.mutator(value, data, type, params, component));
22047 }
22048 }
22049 }
22050 });
22051 }
22052
22053 return data;
22054 }
22055
22056 //apply mutator to new cell value
22057 transformCell(cell, value){
22058 if(cell.column.modules.mutate){
22059 var mutator = cell.column.modules.mutate.mutatorEdit || cell.column.modules.mutate.mutator || false,
22060 tempData = {};
22061
22062 if(mutator){
22063 tempData = Object.assign(tempData, cell.row.getData());
22064 cell.column.setFieldValue(tempData, value);
22065 return mutator.mutator(value, tempData, "edit", mutator.params, cell.getComponent());
22066 }
22067 }
22068
22069 return value;
22070 }
22071
22072 mutateLink(cell){
22073 var links = cell.column.definition.mutateLink;
22074
22075 if(links){
22076 if(!Array.isArray(links)){
22077 links = [links];
22078 }
22079
22080 links.forEach((link) => {
22081 var linkCell = cell.row.getCell(link);
22082
22083 if(linkCell){
22084 linkCell.setValue(linkCell.getValue(), true, true);
22085 }
22086 });
22087 }
22088 }
22089
22090 enable(){
22091 this.enabled = true;
22092 }
22093
22094 disable(){
22095 this.enabled = false;
22096 }
22097 }
22098
22099 function rows(pageSize, currentRow, currentPage, totalRows, totalPages){
22100 var el = document.createElement("span"),
22101 showingEl = document.createElement("span"),
22102 valueEl = document.createElement("span"),
22103 ofEl = document.createElement("span"),
22104 totalEl = document.createElement("span"),
22105 rowsEl = document.createElement("span");
22106
22107 this.table.modules.localize.langBind("pagination|counter|showing", (value) => {
22108 showingEl.innerHTML = value;
22109 });
22110
22111 this.table.modules.localize.langBind("pagination|counter|of", (value) => {
22112 ofEl.innerHTML = value;
22113 });
22114
22115 this.table.modules.localize.langBind("pagination|counter|rows", (value) => {
22116 rowsEl.innerHTML = value;
22117 });
22118
22119 if(totalRows){
22120 valueEl.innerHTML = " " + currentRow + "-" + Math.min((currentRow + pageSize - 1), totalRows) + " ";
22121
22122 totalEl.innerHTML = " " + totalRows + " ";
22123
22124 el.appendChild(showingEl);
22125 el.appendChild(valueEl);
22126 el.appendChild(ofEl);
22127 el.appendChild(totalEl);
22128 el.appendChild(rowsEl);
22129 }else {
22130 valueEl.innerHTML = " 0 ";
22131
22132 el.appendChild(showingEl);
22133 el.appendChild(valueEl);
22134 el.appendChild(rowsEl);
22135 }
22136
22137 return el;
22138 }
22139
22140 function pages(pageSize, currentRow, currentPage, totalRows, totalPages){
22141
22142 var el = document.createElement("span"),
22143 showingEl = document.createElement("span"),
22144 valueEl = document.createElement("span"),
22145 ofEl = document.createElement("span"),
22146 totalEl = document.createElement("span"),
22147 rowsEl = document.createElement("span");
22148
22149 this.table.modules.localize.langBind("pagination|counter|showing", (value) => {
22150 showingEl.innerHTML = value;
22151 });
22152
22153 valueEl.innerHTML = " " + currentPage + " ";
22154
22155 this.table.modules.localize.langBind("pagination|counter|of", (value) => {
22156 ofEl.innerHTML = value;
22157 });
22158
22159 totalEl.innerHTML = " " + totalPages + " ";
22160
22161 this.table.modules.localize.langBind("pagination|counter|pages", (value) => {
22162 rowsEl.innerHTML = value;
22163 });
22164
22165 el.appendChild(showingEl);
22166 el.appendChild(valueEl);
22167 el.appendChild(ofEl);
22168 el.appendChild(totalEl);
22169 el.appendChild(rowsEl);
22170
22171 return el;
22172 }
22173
22174 var defaultPageCounters = {
22175 rows:rows,
22176 pages:pages,
22177 };
22178
22179 class Page extends Module{
22180
22181 static moduleName = "page";
22182
22183 //load defaults
22184 static pageCounters = defaultPageCounters;
22185
22186 constructor(table){
22187 super(table);
22188
22189 this.mode = "local";
22190 this.progressiveLoad = false;
22191
22192 this.element = null;
22193 this.pageCounterElement = null;
22194 this.pageCounter = null;
22195
22196 this.size = 0;
22197 this.page = 1;
22198 this.count = 5;
22199 this.max = 1;
22200
22201 this.remoteRowCountEstimate = null;
22202
22203 this.initialLoad = true;
22204 this.dataChanging = false; //flag to check if data is being changed by this module
22205
22206 this.pageSizes = [];
22207
22208 this.registerTableOption("pagination", false); //set pagination type
22209 this.registerTableOption("paginationMode", "local"); //local or remote pagination
22210 this.registerTableOption("paginationSize", false); //set number of rows to a page
22211 this.registerTableOption("paginationInitialPage", 1); //initial page to show on load
22212 this.registerTableOption("paginationCounter", false); // set pagination counter
22213 this.registerTableOption("paginationCounterElement", false); // set pagination counter
22214 this.registerTableOption("paginationButtonCount", 5); // set count of page button
22215 this.registerTableOption("paginationSizeSelector", false); //add pagination size selector element
22216 this.registerTableOption("paginationElement", false); //element to hold pagination numbers
22217 // this.registerTableOption("paginationDataSent", {}); //pagination data sent to the server
22218 // this.registerTableOption("paginationDataReceived", {}); //pagination data received from the server
22219 this.registerTableOption("paginationAddRow", "page"); //add rows on table or page
22220 this.registerTableOption("paginationOutOfRange", false); //reset the current page when the last page < this.page, values: false|function|any value accepted by setPage()
22221
22222 this.registerTableOption("progressiveLoad", false); //progressive loading
22223 this.registerTableOption("progressiveLoadDelay", 0); //delay between requests
22224 this.registerTableOption("progressiveLoadScrollMargin", 0); //margin before scroll begins
22225
22226 this.registerTableFunction("setMaxPage", this.setMaxPage.bind(this));
22227 this.registerTableFunction("setPage", this.setPage.bind(this));
22228 this.registerTableFunction("setPageToRow", this.userSetPageToRow.bind(this));
22229 this.registerTableFunction("setPageSize", this.userSetPageSize.bind(this));
22230 this.registerTableFunction("getPageSize", this.getPageSize.bind(this));
22231 this.registerTableFunction("previousPage", this.previousPage.bind(this));
22232 this.registerTableFunction("nextPage", this.nextPage.bind(this));
22233 this.registerTableFunction("getPage", this.getPage.bind(this));
22234 this.registerTableFunction("getPageMax", this.getPageMax.bind(this));
22235
22236 //register component functions
22237 this.registerComponentFunction("row", "pageTo", this.setPageToRow.bind(this));
22238 }
22239
22240 initialize(){
22241 if(this.table.options.pagination){
22242 this.subscribe("row-deleted", this.rowsUpdated.bind(this));
22243 this.subscribe("row-added", this.rowsUpdated.bind(this));
22244 this.subscribe("data-processed", this.initialLoadComplete.bind(this));
22245 this.subscribe("table-built", this.calculatePageSizes.bind(this));
22246 this.subscribe("footer-redraw", this.footerRedraw.bind(this));
22247
22248 if(this.table.options.paginationAddRow == "page"){
22249 this.subscribe("row-adding-position", this.rowAddingPosition.bind(this));
22250 }
22251
22252 if(this.table.options.paginationMode === "remote"){
22253 this.subscribe("data-params", this.remotePageParams.bind(this));
22254 this.subscribe("data-loaded", this._parseRemoteData.bind(this));
22255 }
22256
22257 if(this.table.options.progressiveLoad){
22258 console.error("Progressive Load Error - Pagination and progressive load cannot be used at the same time");
22259 }
22260
22261 this.registerDisplayHandler(this.restOnRenderBefore.bind(this), 40);
22262 this.registerDisplayHandler(this.getRows.bind(this), 50);
22263
22264 this.createElements();
22265 this.initializePageCounter();
22266 this.initializePaginator();
22267 }else if(this.table.options.progressiveLoad){
22268 this.subscribe("data-params", this.remotePageParams.bind(this));
22269 this.subscribe("data-loaded", this._parseRemoteData.bind(this));
22270 this.subscribe("table-built", this.calculatePageSizes.bind(this));
22271 this.subscribe("data-processed", this.initialLoadComplete.bind(this));
22272
22273 this.initializeProgressive(this.table.options.progressiveLoad);
22274
22275 if(this.table.options.progressiveLoad === "scroll"){
22276 this.subscribe("scroll-vertical", this.scrollVertical.bind(this));
22277 }
22278 }
22279 }
22280
22281 rowAddingPosition(row, top){
22282 var rowManager = this.table.rowManager,
22283 displayRows = rowManager.getDisplayRows(),
22284 index;
22285
22286 if(top){
22287 if(displayRows.length){
22288 index = displayRows[0];
22289 }else {
22290 if(rowManager.activeRows.length){
22291 index = rowManager.activeRows[rowManager.activeRows.length-1];
22292 top = false;
22293 }
22294 }
22295 }else {
22296 if(displayRows.length){
22297 index = displayRows[displayRows.length - 1];
22298 top = displayRows.length < this.size ? false : true;
22299 }
22300 }
22301
22302 return {index, top};
22303 }
22304
22305 calculatePageSizes(){
22306 var testElRow, testElCell;
22307
22308 if(this.table.options.paginationSize){
22309 this.size = this.table.options.paginationSize;
22310 }else {
22311 testElRow = document.createElement("div");
22312 testElRow.classList.add("tabulator-row");
22313 testElRow.style.visibility = "hidden";
22314
22315 testElCell = document.createElement("div");
22316 testElCell.classList.add("tabulator-cell");
22317 testElCell.innerHTML = "Page Row Test";
22318
22319 testElRow.appendChild(testElCell);
22320
22321 this.table.rowManager.getTableElement().appendChild(testElRow);
22322
22323 this.size = Math.floor(this.table.rowManager.getElement().clientHeight / testElRow.offsetHeight);
22324
22325 this.table.rowManager.getTableElement().removeChild(testElRow);
22326 }
22327
22328 this.dispatchExternal("pageSizeChanged", this.size);
22329
22330 this.generatePageSizeSelectList();
22331 }
22332
22333 initialLoadComplete(){
22334 this.initialLoad = false;
22335 }
22336
22337 remotePageParams(data, config, silent, params){
22338 if(!this.initialLoad){
22339 if((this.progressiveLoad && !silent) || (!this.progressiveLoad && !this.dataChanging)){
22340 this.reset(true);
22341 }
22342 }
22343
22344 //configure request params
22345 params.page = this.page;
22346
22347 //set page size if defined
22348 if(this.size){
22349 params.size = this.size;
22350 }
22351
22352 return params;
22353 }
22354
22355 ///////////////////////////////////
22356 ///////// Table Functions /////////
22357 ///////////////////////////////////
22358
22359 userSetPageToRow(row){
22360 if(this.table.options.pagination){
22361 row = this.table.rowManager.findRow(row);
22362
22363 if(row){
22364 return this.setPageToRow(row);
22365 }
22366 }
22367
22368 return Promise.reject();
22369 }
22370
22371 userSetPageSize(size){
22372 if(this.table.options.pagination){
22373 this.setPageSize(size);
22374 return this.setPage(1);
22375 }else {
22376 return false;
22377 }
22378 }
22379 ///////////////////////////////////
22380 ///////// Internal Logic //////////
22381 ///////////////////////////////////
22382
22383 scrollVertical(top, dir){
22384 var element, diff, margin;
22385 if(!dir && !this.table.dataLoader.loading){
22386 element = this.table.rowManager.getElement();
22387 diff = element.scrollHeight - element.clientHeight - top;
22388 margin = this.table.options.progressiveLoadScrollMargin || (element.clientHeight * 2);
22389
22390 if(diff < margin){
22391 this.nextPage()
22392 .catch(() => {}); //consume the exception thrown when on the last page
22393 }
22394 }
22395 }
22396
22397 restOnRenderBefore(rows, renderInPosition){
22398 if(!renderInPosition){
22399 if(this.mode === "local"){
22400 this.reset();
22401 }
22402 }
22403
22404 return rows;
22405 }
22406
22407 rowsUpdated(){
22408 this.refreshData(true, "all");
22409 }
22410
22411 createElements(){
22412 var button;
22413
22414 this.element = document.createElement("span");
22415 this.element.classList.add("tabulator-paginator");
22416
22417 this.pagesElement = document.createElement("span");
22418 this.pagesElement.classList.add("tabulator-pages");
22419
22420 button = document.createElement("button");
22421 button.classList.add("tabulator-page");
22422 button.setAttribute("type", "button");
22423 button.setAttribute("role", "button");
22424 button.setAttribute("aria-label", "");
22425 button.setAttribute("title", "");
22426
22427 this.firstBut = button.cloneNode(true);
22428 this.firstBut.setAttribute("data-page", "first");
22429
22430 this.prevBut = button.cloneNode(true);
22431 this.prevBut.setAttribute("data-page", "prev");
22432
22433 this.nextBut = button.cloneNode(true);
22434 this.nextBut.setAttribute("data-page", "next");
22435
22436 this.lastBut = button.cloneNode(true);
22437 this.lastBut.setAttribute("data-page", "last");
22438
22439 if(this.table.options.paginationSizeSelector){
22440 this.pageSizeSelect = document.createElement("select");
22441 this.pageSizeSelect.classList.add("tabulator-page-size");
22442 }
22443 }
22444
22445 generatePageSizeSelectList(){
22446 var pageSizes = [];
22447
22448 if(this.pageSizeSelect){
22449
22450 if(Array.isArray(this.table.options.paginationSizeSelector)){
22451 pageSizes = this.table.options.paginationSizeSelector;
22452 this.pageSizes = pageSizes;
22453
22454 if(this.pageSizes.indexOf(this.size) == -1){
22455 pageSizes.unshift(this.size);
22456 }
22457 }else {
22458
22459 if(this.pageSizes.indexOf(this.size) == -1){
22460 pageSizes = [];
22461
22462 for (let i = 1; i < 5; i++){
22463 pageSizes.push(this.size * i);
22464 }
22465
22466 this.pageSizes = pageSizes;
22467 }else {
22468 pageSizes = this.pageSizes;
22469 }
22470 }
22471
22472 while(this.pageSizeSelect.firstChild) this.pageSizeSelect.removeChild(this.pageSizeSelect.firstChild);
22473
22474 pageSizes.forEach((item) => {
22475 var itemEl = document.createElement("option");
22476 itemEl.value = item;
22477
22478 if(item === true){
22479 this.langBind("pagination|all", function(value){
22480 itemEl.innerHTML = value;
22481 });
22482 }else {
22483 itemEl.innerHTML = item;
22484 }
22485
22486
22487
22488 this.pageSizeSelect.appendChild(itemEl);
22489 });
22490
22491 this.pageSizeSelect.value = this.size;
22492 }
22493 }
22494
22495 initializePageCounter(){
22496 var counter = this.table.options.paginationCounter,
22497 pageCounter = null;
22498
22499 if(counter){
22500 if(typeof counter === "function"){
22501 pageCounter = counter;
22502 }else {
22503 pageCounter = Page.pageCounters[counter];
22504 }
22505
22506 if(pageCounter){
22507 this.pageCounter = pageCounter;
22508
22509 this.pageCounterElement = document.createElement("span");
22510 this.pageCounterElement.classList.add("tabulator-page-counter");
22511 }else {
22512 console.warn("Pagination Error - No such page counter found: ", counter);
22513 }
22514 }
22515 }
22516
22517 //setup pagination
22518 initializePaginator(hidden){
22519 var pageSelectLabel, paginationCounterHolder;
22520
22521 if(!hidden){
22522 //build pagination element
22523
22524 //bind localizations
22525 this.langBind("pagination|first", (value) => {
22526 this.firstBut.innerHTML = value;
22527 });
22528
22529 this.langBind("pagination|first_title", (value) => {
22530 this.firstBut.setAttribute("aria-label", value);
22531 this.firstBut.setAttribute("title", value);
22532 });
22533
22534 this.langBind("pagination|prev", (value) => {
22535 this.prevBut.innerHTML = value;
22536 });
22537
22538 this.langBind("pagination|prev_title", (value) => {
22539 this.prevBut.setAttribute("aria-label", value);
22540 this.prevBut.setAttribute("title", value);
22541 });
22542
22543 this.langBind("pagination|next", (value) => {
22544 this.nextBut.innerHTML = value;
22545 });
22546
22547 this.langBind("pagination|next_title", (value) => {
22548 this.nextBut.setAttribute("aria-label", value);
22549 this.nextBut.setAttribute("title", value);
22550 });
22551
22552 this.langBind("pagination|last", (value) => {
22553 this.lastBut.innerHTML = value;
22554 });
22555
22556 this.langBind("pagination|last_title", (value) => {
22557 this.lastBut.setAttribute("aria-label", value);
22558 this.lastBut.setAttribute("title", value);
22559 });
22560
22561 //click bindings
22562 this.firstBut.addEventListener("click", () => {
22563 this.setPage(1);
22564 });
22565
22566 this.prevBut.addEventListener("click", () => {
22567 this.previousPage();
22568 });
22569
22570 this.nextBut.addEventListener("click", () => {
22571 this.nextPage();
22572 });
22573
22574 this.lastBut.addEventListener("click", () => {
22575 this.setPage(this.max);
22576 });
22577
22578 if(this.table.options.paginationElement){
22579 this.element = this.table.options.paginationElement;
22580 }
22581
22582 if(this.pageSizeSelect){
22583 pageSelectLabel = document.createElement("label");
22584
22585 this.langBind("pagination|page_size", (value) => {
22586 this.pageSizeSelect.setAttribute("aria-label", value);
22587 this.pageSizeSelect.setAttribute("title", value);
22588 pageSelectLabel.innerHTML = value;
22589 });
22590
22591 this.element.appendChild(pageSelectLabel);
22592 this.element.appendChild(this.pageSizeSelect);
22593
22594 this.pageSizeSelect.addEventListener("change", (e) => {
22595 this.setPageSize(this.pageSizeSelect.value == "true" ? true : this.pageSizeSelect.value);
22596 this.setPage(1);
22597 });
22598 }
22599
22600 //append to DOM
22601 this.element.appendChild(this.firstBut);
22602 this.element.appendChild(this.prevBut);
22603 this.element.appendChild(this.pagesElement);
22604 this.element.appendChild(this.nextBut);
22605 this.element.appendChild(this.lastBut);
22606
22607 if(!this.table.options.paginationElement){
22608 if(this.table.options.paginationCounter){
22609
22610 if(this.table.options.paginationCounterElement){
22611 if(this.table.options.paginationCounterElement instanceof HTMLElement){
22612 this.table.options.paginationCounterElement.appendChild(this.pageCounterElement);
22613 }else if(typeof this.table.options.paginationCounterElement === "string"){
22614 paginationCounterHolder = document.querySelector(this.table.options.paginationCounterElement);
22615
22616 if(paginationCounterHolder){
22617 paginationCounterHolder.appendChild(this.pageCounterElement);
22618 }else {
22619 console.warn("Pagination Error - Unable to find element matching paginationCounterElement selector:", this.table.options.paginationCounterElement);
22620 }
22621 }
22622 }else {
22623 this.footerAppend(this.pageCounterElement);
22624 }
22625
22626 }
22627
22628 this.footerAppend(this.element);
22629 }
22630
22631 this.page = this.table.options.paginationInitialPage;
22632 this.count = this.table.options.paginationButtonCount;
22633 }
22634
22635 //set default values
22636 this.mode = this.table.options.paginationMode;
22637 }
22638
22639 initializeProgressive(mode){
22640 this.initializePaginator(true);
22641 this.mode = "progressive_" + mode;
22642 this.progressiveLoad = true;
22643 }
22644
22645 trackChanges(){
22646 this.dispatch("page-changed");
22647 }
22648
22649 //calculate maximum page from number of rows
22650 setMaxRows(rowCount){
22651 if(!rowCount){
22652 this.max = 1;
22653 }else {
22654 this.max = this.size === true ? 1 : Math.ceil(rowCount/this.size);
22655 }
22656
22657 if(this.page > this.max){
22658 this.page = this.max;
22659 }
22660 }
22661
22662 //reset to first page without triggering action
22663 reset(force){
22664 if(!this.initialLoad){
22665 if(this.mode == "local" || force){
22666 this.page = 1;
22667 this.trackChanges();
22668 }
22669 }
22670 }
22671
22672 //set the maximum page
22673 setMaxPage(max){
22674
22675 max = parseInt(max);
22676
22677 this.max = max || 1;
22678
22679 if(this.page > this.max){
22680 this.page = this.max;
22681 this.trigger();
22682 }
22683 }
22684
22685 //set current page number
22686 setPage(page){
22687 switch(page){
22688 case "first":
22689 return this.setPage(1);
22690
22691 case "prev":
22692 return this.previousPage();
22693
22694 case "next":
22695 return this.nextPage();
22696
22697 case "last":
22698 return this.setPage(this.max);
22699 }
22700
22701 page = parseInt(page);
22702
22703 if((page > 0 && page <= this.max) || this.mode !== "local"){
22704 this.page = page;
22705
22706 this.trackChanges();
22707
22708 return this.trigger();
22709 }else {
22710 console.warn("Pagination Error - Requested page is out of range of 1 - " + this.max + ":", page);
22711 return Promise.reject();
22712 }
22713 }
22714
22715 setPageToRow(row){
22716 var rows = this.displayRows(-1);
22717 var index = rows.indexOf(row);
22718
22719 if(index > -1){
22720 var page = this.size === true ? 1 : Math.ceil((index + 1) / this.size);
22721
22722 return this.setPage(page);
22723 }else {
22724 console.warn("Pagination Error - Requested row is not visible");
22725 return Promise.reject();
22726 }
22727 }
22728
22729 setPageSize(size){
22730 if(size !== true){
22731 size = parseInt(size);
22732 }
22733
22734 if(size > 0){
22735 this.size = size;
22736 this.dispatchExternal("pageSizeChanged", size);
22737 }
22738
22739 if(this.pageSizeSelect){
22740 // this.pageSizeSelect.value = size;
22741 this.generatePageSizeSelectList();
22742 }
22743
22744 this.trackChanges();
22745 }
22746
22747 _setPageCounter(totalRows, size, currentRow){
22748 var content;
22749
22750 if(this.pageCounter){
22751
22752 if(this.mode === "remote"){
22753 size = this.size;
22754 currentRow = ((this.page - 1) * this.size) + 1;
22755 totalRows = this.remoteRowCountEstimate;
22756 }
22757
22758 content = this.pageCounter.call(this, size, currentRow, this.page, totalRows, this.max);
22759
22760 switch(typeof content){
22761 case "object":
22762 if(content instanceof Node){
22763
22764 //clear previous cell contents
22765 while(this.pageCounterElement.firstChild) this.pageCounterElement.removeChild(this.pageCounterElement.firstChild);
22766
22767 this.pageCounterElement.appendChild(content);
22768 }else {
22769 this.pageCounterElement.innerHTML = "";
22770
22771 if(content != null){
22772 console.warn("Page Counter Error - Page Counter has returned a type of object, the only valid page counter object return is an instance of Node, the page counter returned:", content);
22773 }
22774 }
22775 break;
22776 case "undefined":
22777 this.pageCounterElement.innerHTML = "";
22778 break;
22779 default:
22780 this.pageCounterElement.innerHTML = content;
22781 }
22782 }
22783 }
22784
22785 //setup the pagination buttons
22786 _setPageButtons(){
22787 let leftSize = Math.floor((this.count-1) / 2);
22788 let rightSize = Math.ceil((this.count-1) / 2);
22789 let min = this.max - this.page + leftSize + 1 < this.count ? this.max-this.count+1: Math.max(this.page-leftSize,1);
22790 let max = this.page <= rightSize? Math.min(this.count, this.max) :Math.min(this.page+rightSize, this.max);
22791
22792 while(this.pagesElement.firstChild) this.pagesElement.removeChild(this.pagesElement.firstChild);
22793
22794 if(this.page == 1){
22795 this.firstBut.disabled = true;
22796 this.prevBut.disabled = true;
22797 }else {
22798 this.firstBut.disabled = false;
22799 this.prevBut.disabled = false;
22800 }
22801
22802 if(this.page == this.max){
22803 this.lastBut.disabled = true;
22804 this.nextBut.disabled = true;
22805 }else {
22806 this.lastBut.disabled = false;
22807 this.nextBut.disabled = false;
22808 }
22809
22810 for(let i = min; i <= max; i++){
22811 if(i>0 && i <= this.max){
22812 this.pagesElement.appendChild(this._generatePageButton(i));
22813 }
22814 }
22815
22816 this.footerRedraw();
22817 }
22818
22819 _generatePageButton(page){
22820 var button = document.createElement("button");
22821
22822 button.classList.add("tabulator-page");
22823 if(page == this.page){
22824 button.classList.add("active");
22825 }
22826
22827 button.setAttribute("type", "button");
22828 button.setAttribute("role", "button");
22829
22830 this.langBind("pagination|page_title", (value) => {
22831 button.setAttribute("aria-label", value + " " + page);
22832 button.setAttribute("title", value + " " + page);
22833 });
22834
22835 button.setAttribute("data-page", page);
22836 button.textContent = page;
22837
22838 button.addEventListener("click", (e) => {
22839 this.setPage(page);
22840 });
22841
22842 return button;
22843 }
22844
22845 //previous page
22846 previousPage(){
22847 if(this.page > 1){
22848 this.page--;
22849
22850 this.trackChanges();
22851
22852 return this.trigger();
22853
22854 }else {
22855 console.warn("Pagination Error - Previous page would be less than page 1:", 0);
22856 return Promise.reject();
22857 }
22858 }
22859
22860 //next page
22861 nextPage(){
22862 if(this.page < this.max){
22863 this.page++;
22864
22865 this.trackChanges();
22866
22867 return this.trigger();
22868
22869 }else {
22870 if(!this.progressiveLoad){
22871 console.warn("Pagination Error - Next page would be greater than maximum page of " + this.max + ":", this.max + 1);
22872 }
22873 return Promise.reject();
22874 }
22875 }
22876
22877 //return current page number
22878 getPage(){
22879 return this.page;
22880 }
22881
22882 //return max page number
22883 getPageMax(){
22884 return this.max;
22885 }
22886
22887 getPageSize(size){
22888 return this.size;
22889 }
22890
22891 getMode(){
22892 return this.mode;
22893 }
22894
22895 //return appropriate rows for current page
22896 getRows(data){
22897 var actualRowPageSize = 0,
22898 output, start, end, actualStartRow;
22899
22900 var actualRows = data.filter((row) => {
22901 return row.type === "row";
22902 });
22903
22904 if(this.mode == "local"){
22905 output = [];
22906
22907 this.setMaxRows(data.length);
22908
22909 if(this.size === true){
22910 start = 0;
22911 end = data.length;
22912 }else {
22913 start = this.size * (this.page - 1);
22914 end = start + parseInt(this.size);
22915 }
22916
22917 this._setPageButtons();
22918
22919 for(let i = start; i < end; i++){
22920 let row = data[i];
22921
22922 if(row){
22923 output.push(row);
22924
22925 if(row.type === "row"){
22926 if(!actualStartRow){
22927 actualStartRow = row;
22928 }
22929
22930 actualRowPageSize++;
22931 }
22932 }
22933 }
22934
22935 this._setPageCounter(actualRows.length, actualRowPageSize, actualStartRow ? (actualRows.indexOf(actualStartRow) + 1) : 0);
22936
22937 return output;
22938 }else {
22939 this._setPageButtons();
22940 this._setPageCounter(actualRows.length);
22941
22942 return data.slice(0);
22943 }
22944 }
22945
22946 trigger(){
22947 var left;
22948
22949 switch(this.mode){
22950 case "local":
22951 left = this.table.rowManager.scrollLeft;
22952
22953 this.refreshData();
22954 this.table.rowManager.scrollHorizontal(left);
22955
22956 this.dispatchExternal("pageLoaded", this.getPage());
22957
22958 return Promise.resolve();
22959
22960 case "remote":
22961 this.dataChanging = true;
22962 return this.reloadData(null)
22963 .finally(() => {
22964 this.dataChanging = false;
22965 });
22966
22967 case "progressive_load":
22968 case "progressive_scroll":
22969 return this.reloadData(null, true);
22970
22971 default:
22972 console.warn("Pagination Error - no such pagination mode:", this.mode);
22973 return Promise.reject();
22974 }
22975 }
22976
22977 _parseRemoteData(data){
22978 var margin, paginationOutOfRange;
22979
22980 if(typeof data.last_page === "undefined"){
22981 console.warn("Remote Pagination Error - Server response missing '" + (this.options("dataReceiveParams").last_page || "last_page") + "' property");
22982 }
22983
22984 if(data.data){
22985 this.max = parseInt(data.last_page) || 1;
22986
22987 this.remoteRowCountEstimate = typeof data.last_row !== "undefined" ? data.last_row : (data.last_page * this.size - (this.page == data.last_page ? (this.size - data.data.length) : 0));
22988
22989 if(this.progressiveLoad){
22990 switch(this.mode){
22991 case "progressive_load":
22992
22993 if(this.page == 1){
22994 this.table.rowManager.setData(data.data, false, this.page == 1);
22995 }else {
22996 this.table.rowManager.addRows(data.data);
22997 }
22998
22999 if(this.page < this.max){
23000 setTimeout(() => {
23001 this.nextPage();
23002 }, this.table.options.progressiveLoadDelay);
23003 }
23004 break;
23005
23006 case "progressive_scroll":
23007 data = this.page === 1 ? data.data : this.table.rowManager.getData().concat(data.data);
23008
23009 this.table.rowManager.setData(data, this.page !== 1, this.page == 1);
23010
23011 margin = this.table.options.progressiveLoadScrollMargin || (this.table.rowManager.element.clientHeight * 2);
23012
23013 if(this.table.rowManager.element.scrollHeight <= (this.table.rowManager.element.clientHeight + margin)){
23014 if(this.page < this.max){
23015 setTimeout(() => {
23016 this.nextPage();
23017 });
23018 }
23019 }
23020 break;
23021 }
23022
23023 return false;
23024 }else {
23025
23026 if(this.page > this.max){
23027 console.warn( "Remote Pagination Error - Server returned last page value lower than the current page" );
23028
23029 paginationOutOfRange = this.options('paginationOutOfRange');
23030
23031 if(paginationOutOfRange){
23032 return this.setPage(typeof paginationOutOfRange === 'function' ? paginationOutOfRange.call(this, this.page, this.max) : paginationOutOfRange);
23033 }
23034 }
23035
23036 // left = this.table.rowManager.scrollLeft;
23037 this.dispatchExternal("pageLoaded", this.getPage());
23038 // this.table.rowManager.scrollHorizontal(left);
23039 // this.table.columnManager.scrollHorizontal(left);
23040 }
23041
23042 }else {
23043 console.warn("Remote Pagination Error - Server response missing '" + (this.options("dataReceiveParams").data || "data") + "' property");
23044 }
23045
23046 return data.data;
23047 }
23048
23049 //handle the footer element being redrawn
23050 footerRedraw(){
23051 var footer = this.table.footerManager.containerElement;
23052
23053 if((Math.ceil(footer.clientWidth) - footer.scrollWidth) < 0){
23054 this.pagesElement.style.display = 'none';
23055 }else {
23056 this.pagesElement.style.display = '';
23057
23058 if((Math.ceil(footer.clientWidth) - footer.scrollWidth) < 0){
23059 this.pagesElement.style.display = 'none';
23060 }
23061 }
23062 }
23063 }
23064
23065 // read persistance information from storage
23066 var defaultReaders = {
23067 local:function(id, type){
23068 var data = localStorage.getItem(id + "-" + type);
23069
23070 return data ? JSON.parse(data) : false;
23071 },
23072 cookie:function(id, type){
23073 var cookie = document.cookie,
23074 key = id + "-" + type,
23075 cookiePos = cookie.indexOf(key + "="),
23076 end, data;
23077
23078 //if cookie exists, decode and load column data into tabulator
23079 if(cookiePos > -1){
23080 cookie = cookie.slice(cookiePos);
23081
23082 end = cookie.indexOf(";");
23083
23084 if(end > -1){
23085 cookie = cookie.slice(0, end);
23086 }
23087
23088 data = cookie.replace(key + "=", "");
23089 }
23090
23091 return data ? JSON.parse(data) : false;
23092 }
23093 };
23094
23095 //write persistence information to storage
23096 var defaultWriters = {
23097 local:function(id, type, data){
23098 localStorage.setItem(id + "-" + type, JSON.stringify(data));
23099 },
23100 cookie:function(id, type, data){
23101 var expireDate = new Date();
23102
23103 expireDate.setDate(expireDate.getDate() + 10000);
23104
23105 document.cookie = id + "-" + type + "=" + JSON.stringify(data) + "; expires=" + expireDate.toUTCString();
23106 }
23107 };
23108
23109 class Persistence extends Module{
23110
23111 static moduleName = "persistence";
23112
23113 static moduleInitOrder = -10;
23114
23115 //load defaults
23116 static readers = defaultReaders;
23117 static writers = defaultWriters;
23118
23119 constructor(table){
23120 super(table);
23121
23122 this.mode = "";
23123 this.id = "";
23124 // this.persistProps = ["field", "width", "visible"];
23125 this.defWatcherBlock = false;
23126 this.config = {};
23127 this.readFunc = false;
23128 this.writeFunc = false;
23129
23130 this.registerTableOption("persistence", false);
23131 this.registerTableOption("persistenceID", ""); //key for persistent storage
23132 this.registerTableOption("persistenceMode", true); //mode for storing persistence information
23133 this.registerTableOption("persistenceReaderFunc", false); //function for handling persistence data reading
23134 this.registerTableOption("persistenceWriterFunc", false); //function for handling persistence data writing
23135 }
23136
23137 // Test for whether localStorage is available for use.
23138 localStorageTest() {
23139 var testKey = "_tabulator_test";
23140
23141 try {
23142 window.localStorage.setItem( testKey, testKey);
23143 window.localStorage.removeItem( testKey );
23144 return true;
23145 } catch(e) {
23146 return false;
23147 }
23148 }
23149
23150 //setup parameters
23151 initialize(){
23152 if(this.table.options.persistence){
23153 //determine persistent layout storage type
23154 var mode = this.table.options.persistenceMode,
23155 id = this.table.options.persistenceID,
23156 retrievedData;
23157
23158 this.mode = mode !== true ? mode : (this.localStorageTest() ? "local" : "cookie");
23159
23160 if(this.table.options.persistenceReaderFunc){
23161 if(typeof this.table.options.persistenceReaderFunc === "function"){
23162 this.readFunc = this.table.options.persistenceReaderFunc;
23163 }else {
23164 if(Persistence.readers[this.table.options.persistenceReaderFunc]){
23165 this.readFunc = Persistence.readers[this.table.options.persistenceReaderFunc];
23166 }else {
23167 console.warn("Persistence Read Error - invalid reader set", this.table.options.persistenceReaderFunc);
23168 }
23169 }
23170 }else {
23171 if(Persistence.readers[this.mode]){
23172 this.readFunc = Persistence.readers[this.mode];
23173 }else {
23174 console.warn("Persistence Read Error - invalid reader set", this.mode);
23175 }
23176 }
23177
23178 if(this.table.options.persistenceWriterFunc){
23179 if(typeof this.table.options.persistenceWriterFunc === "function"){
23180 this.writeFunc = this.table.options.persistenceWriterFunc;
23181 }else {
23182 if(Persistence.writers[this.table.options.persistenceWriterFunc]){
23183 this.writeFunc = Persistence.writers[this.table.options.persistenceWriterFunc];
23184 }else {
23185 console.warn("Persistence Write Error - invalid reader set", this.table.options.persistenceWriterFunc);
23186 }
23187 }
23188 }else {
23189 if(Persistence.writers[this.mode]){
23190 this.writeFunc = Persistence.writers[this.mode];
23191 }else {
23192 console.warn("Persistence Write Error - invalid writer set", this.mode);
23193 }
23194 }
23195
23196 //set storage tag
23197 this.id = "tabulator-" + (id || (this.table.element.getAttribute("id") || ""));
23198
23199 this.config = {
23200 sort:this.table.options.persistence === true || this.table.options.persistence.sort,
23201 filter:this.table.options.persistence === true || this.table.options.persistence.filter,
23202 headerFilter:this.table.options.persistence === true || this.table.options.persistence.headerFilter,
23203 group:this.table.options.persistence === true || this.table.options.persistence.group,
23204 page:this.table.options.persistence === true || this.table.options.persistence.page,
23205 columns:this.table.options.persistence === true ? ["title", "width", "visible"] : this.table.options.persistence.columns,
23206 };
23207
23208 //load pagination data if needed
23209 if(this.config.page){
23210 retrievedData = this.retrieveData("page");
23211
23212 if(retrievedData){
23213 if(typeof retrievedData.paginationSize !== "undefined" && (this.config.page === true || this.config.page.size)){
23214 this.table.options.paginationSize = retrievedData.paginationSize;
23215 }
23216
23217 if(typeof retrievedData.paginationInitialPage !== "undefined" && (this.config.page === true || this.config.page.page)){
23218 this.table.options.paginationInitialPage = retrievedData.paginationInitialPage;
23219 }
23220 }
23221 }
23222
23223 //load group data if needed
23224 if(this.config.group){
23225 retrievedData = this.retrieveData("group");
23226
23227 if(retrievedData){
23228 if(typeof retrievedData.groupBy !== "undefined" && (this.config.group === true || this.config.group.groupBy)){
23229 this.table.options.groupBy = retrievedData.groupBy;
23230 }
23231 if(typeof retrievedData.groupStartOpen !== "undefined" && (this.config.group === true || this.config.group.groupStartOpen)){
23232 this.table.options.groupStartOpen = retrievedData.groupStartOpen;
23233 }
23234 if(typeof retrievedData.groupHeader !== "undefined" && (this.config.group === true || this.config.group.groupHeader)){
23235 this.table.options.groupHeader = retrievedData.groupHeader;
23236 }
23237 }
23238 }
23239
23240 if(this.config.columns){
23241 this.table.options.columns = this.load("columns", this.table.options.columns);
23242 this.subscribe("column-init", this.initializeColumn.bind(this));
23243 this.subscribe("column-show", this.save.bind(this, "columns"));
23244 this.subscribe("column-hide", this.save.bind(this, "columns"));
23245 this.subscribe("column-moved", this.save.bind(this, "columns"));
23246 }
23247
23248 this.subscribe("table-built", this.tableBuilt.bind(this), 0);
23249
23250 this.subscribe("table-redraw", this.tableRedraw.bind(this));
23251
23252 this.subscribe("filter-changed", this.eventSave.bind(this, "filter"));
23253 this.subscribe("filter-changed", this.eventSave.bind(this, "headerFilter"));
23254 this.subscribe("sort-changed", this.eventSave.bind(this, "sort"));
23255 this.subscribe("group-changed", this.eventSave.bind(this, "group"));
23256 this.subscribe("page-changed", this.eventSave.bind(this, "page"));
23257 this.subscribe("column-resized", this.eventSave.bind(this, "columns"));
23258 this.subscribe("column-width", this.eventSave.bind(this, "columns"));
23259 this.subscribe("layout-refreshed", this.eventSave.bind(this, "columns"));
23260 }
23261
23262 this.registerTableFunction("getColumnLayout", this.getColumnLayout.bind(this));
23263 this.registerTableFunction("setColumnLayout", this.setColumnLayout.bind(this));
23264 }
23265
23266 eventSave(type){
23267 if(this.config[type]){
23268 this.save(type);
23269 }
23270 }
23271
23272 tableBuilt(){
23273 var sorters, filters, headerFilters;
23274
23275 if(this.config.sort){
23276 sorters = this.load("sort");
23277
23278 if(!sorters === false){
23279 this.table.options.initialSort = sorters;
23280 }
23281 }
23282
23283 if(this.config.filter){
23284 filters = this.load("filter");
23285
23286 if(!filters === false){
23287 this.table.options.initialFilter = filters;
23288 }
23289 }
23290 if(this.config.headerFilter){
23291 headerFilters = this.load("headerFilter");
23292
23293 if(!headerFilters === false){
23294 this.table.options.initialHeaderFilter = headerFilters;
23295 }
23296 }
23297
23298 }
23299
23300 tableRedraw(force){
23301 if(force && this.config.columns){
23302 this.save("columns");
23303 }
23304 }
23305
23306 ///////////////////////////////////
23307 ///////// Table Functions /////////
23308 ///////////////////////////////////
23309
23310 getColumnLayout(){
23311 return this.parseColumns(this.table.columnManager.getColumns());
23312 }
23313
23314 setColumnLayout(layout){
23315 this.table.columnManager.setColumns(this.mergeDefinition(this.table.options.columns, layout, true));
23316 return true;
23317 }
23318
23319 ///////////////////////////////////
23320 ///////// Internal Logic //////////
23321 ///////////////////////////////////
23322
23323 initializeColumn(column){
23324 var def, keys;
23325
23326 if(this.config.columns){
23327 this.defWatcherBlock = true;
23328
23329 def = column.getDefinition();
23330
23331 keys = this.config.columns === true ? Object.keys(def) : this.config.columns;
23332
23333 keys.forEach((key)=>{
23334 var props = Object.getOwnPropertyDescriptor(def, key);
23335 var value = def[key];
23336
23337 if(props){
23338 Object.defineProperty(def, key, {
23339 set: (newValue) => {
23340 value = newValue;
23341
23342 if(!this.defWatcherBlock){
23343 this.save("columns");
23344 }
23345
23346 if(props.set){
23347 props.set(newValue);
23348 }
23349 },
23350 get:() => {
23351 if(props.get){
23352 props.get();
23353 }
23354 return value;
23355 }
23356 });
23357 }
23358 });
23359
23360 this.defWatcherBlock = false;
23361 }
23362 }
23363
23364 //load saved definitions
23365 load(type, current){
23366 var data = this.retrieveData(type);
23367
23368 if(current){
23369 data = data ? this.mergeDefinition(current, data) : current;
23370 }
23371
23372 return data;
23373 }
23374
23375 //retrieve data from memory
23376 retrieveData(type){
23377 return this.readFunc ? this.readFunc(this.id, type) : false;
23378 }
23379
23380 //merge old and new column definitions
23381 mergeDefinition(oldCols, newCols, mergeAllNew){
23382 var output = [];
23383
23384 newCols = newCols || [];
23385
23386 newCols.forEach((column, to) => {
23387 var from = this._findColumn(oldCols, column),
23388 keys;
23389
23390 if(from){
23391 if(mergeAllNew){
23392 keys = Object.keys(column);
23393 }else if(this.config.columns === true || this.config.columns == undefined){
23394 keys = Object.keys(from);
23395 keys.push("width");
23396 }else {
23397 keys = this.config.columns;
23398 }
23399
23400 keys.forEach((key)=>{
23401 if(key !== "columns" && typeof column[key] !== "undefined"){
23402 from[key] = column[key];
23403 }
23404 });
23405
23406 if(from.columns){
23407 from.columns = this.mergeDefinition(from.columns, column.columns);
23408 }
23409
23410 output.push(from);
23411 }
23412 });
23413
23414 oldCols.forEach((column, i) => {
23415 var from = this._findColumn(newCols, column);
23416
23417 if (!from) {
23418 if(output.length>i){
23419 output.splice(i, 0, column);
23420 }else {
23421 output.push(column);
23422 }
23423 }
23424 });
23425
23426 return output;
23427 }
23428
23429 //find matching columns
23430 _findColumn(columns, subject){
23431 var type = subject.columns ? "group" : (subject.field ? "field" : "object");
23432
23433 return columns.find(function(col){
23434 switch(type){
23435 case "group":
23436 return col.title === subject.title && col.columns.length === subject.columns.length;
23437
23438 case "field":
23439 return col.field === subject.field;
23440
23441 case "object":
23442 return col === subject;
23443 }
23444 });
23445 }
23446
23447 //save data
23448 save(type){
23449 var data = {};
23450
23451 switch(type){
23452 case "columns":
23453 data = this.parseColumns(this.table.columnManager.getColumns());
23454 break;
23455
23456 case "filter":
23457 data = this.table.modules.filter.getFilters();
23458 break;
23459
23460 case "headerFilter":
23461 data = this.table.modules.filter.getHeaderFilters();
23462 break;
23463
23464 case "sort":
23465 data = this.validateSorters(this.table.modules.sort.getSort());
23466 break;
23467
23468 case "group":
23469 data = this.getGroupConfig();
23470 break;
23471
23472 case "page":
23473 data = this.getPageConfig();
23474 break;
23475 }
23476
23477 if(this.writeFunc){
23478 this.writeFunc(this.id, type, data);
23479 }
23480
23481 }
23482
23483 //ensure sorters contain no function data
23484 validateSorters(data){
23485 data.forEach(function(item){
23486 item.column = item.field;
23487 delete item.field;
23488 });
23489
23490 return data;
23491 }
23492
23493 getGroupConfig(){
23494 var data = {};
23495
23496 if(this.config.group){
23497 if(this.config.group === true || this.config.group.groupBy){
23498 data.groupBy = this.table.options.groupBy;
23499 }
23500
23501 if(this.config.group === true || this.config.group.groupStartOpen){
23502 data.groupStartOpen = this.table.options.groupStartOpen;
23503 }
23504
23505 if(this.config.group === true || this.config.group.groupHeader){
23506 data.groupHeader = this.table.options.groupHeader;
23507 }
23508 }
23509
23510 return data;
23511 }
23512
23513 getPageConfig(){
23514 var data = {};
23515
23516 if(this.config.page){
23517 if(this.config.page === true || this.config.page.size){
23518 data.paginationSize = this.table.modules.page.getPageSize();
23519 }
23520
23521 if(this.config.page === true || this.config.page.page){
23522 data.paginationInitialPage = this.table.modules.page.getPage();
23523 }
23524 }
23525
23526 return data;
23527 }
23528
23529
23530 //parse columns for data to store
23531 parseColumns(columns){
23532 var definitions = [],
23533 excludedKeys = ["headerContextMenu", "headerMenu", "contextMenu", "clickMenu"];
23534
23535 columns.forEach((column) => {
23536 var defStore = {},
23537 colDef = column.getDefinition(),
23538 keys;
23539
23540 if(column.isGroup){
23541 defStore.title = colDef.title;
23542 defStore.columns = this.parseColumns(column.getColumns());
23543 }else {
23544 defStore.field = column.getField();
23545
23546 if(this.config.columns === true || this.config.columns == undefined){
23547 keys = Object.keys(colDef);
23548 keys.push("width");
23549 keys.push("visible");
23550 }else {
23551 keys = this.config.columns;
23552 }
23553
23554 keys.forEach((key)=>{
23555 switch(key){
23556 case "width":
23557 defStore.width = column.getWidth();
23558 break;
23559 case "visible":
23560 defStore.visible = column.visible;
23561 break;
23562
23563 default:
23564 if(typeof colDef[key] !== "function" && excludedKeys.indexOf(key) === -1){
23565 defStore[key] = colDef[key];
23566 }
23567 }
23568 });
23569 }
23570
23571 definitions.push(defStore);
23572 });
23573
23574 return definitions;
23575 }
23576 }
23577
23578 class Popup extends Module{
23579
23580 static moduleName = "popup";
23581
23582 constructor(table){
23583 super(table);
23584
23585 this.columnSubscribers = {};
23586
23587 this.registerTableOption("rowContextPopup", false);
23588 this.registerTableOption("rowClickPopup", false);
23589 this.registerTableOption("rowDblClickPopup", false);
23590 this.registerTableOption("groupContextPopup", false);
23591 this.registerTableOption("groupClickPopup", false);
23592 this.registerTableOption("groupDblClickPopup", false);
23593
23594 this.registerColumnOption("headerContextPopup");
23595 this.registerColumnOption("headerClickPopup");
23596 this.registerColumnOption("headerDblClickPopup");
23597 this.registerColumnOption("headerPopup");
23598 this.registerColumnOption("headerPopupIcon");
23599 this.registerColumnOption("contextPopup");
23600 this.registerColumnOption("clickPopup");
23601 this.registerColumnOption("dblClickPopup");
23602
23603 this.registerComponentFunction("cell", "popup", this._componentPopupCall.bind(this));
23604 this.registerComponentFunction("column", "popup", this._componentPopupCall.bind(this));
23605 this.registerComponentFunction("row", "popup", this._componentPopupCall.bind(this));
23606 this.registerComponentFunction("group", "popup", this._componentPopupCall.bind(this));
23607
23608 }
23609
23610 initialize(){
23611 this.initializeRowWatchers();
23612 this.initializeGroupWatchers();
23613
23614 this.subscribe("column-init", this.initializeColumn.bind(this));
23615 }
23616
23617 _componentPopupCall(component, contents, position){
23618 this.loadPopupEvent(contents, null, component, position);
23619 }
23620
23621 initializeRowWatchers(){
23622 if(this.table.options.rowContextPopup){
23623 this.subscribe("row-contextmenu", this.loadPopupEvent.bind(this, this.table.options.rowContextPopup));
23624 this.table.on("rowTapHold", this.loadPopupEvent.bind(this, this.table.options.rowContextPopup));
23625 }
23626
23627 if(this.table.options.rowClickPopup){
23628 this.subscribe("row-click", this.loadPopupEvent.bind(this, this.table.options.rowClickPopup));
23629 }
23630
23631 if(this.table.options.rowDblClickPopup){
23632 this.subscribe("row-dblclick", this.loadPopupEvent.bind(this, this.table.options.rowDblClickPopup));
23633 }
23634 }
23635
23636 initializeGroupWatchers(){
23637 if(this.table.options.groupContextPopup){
23638 this.subscribe("group-contextmenu", this.loadPopupEvent.bind(this, this.table.options.groupContextPopup));
23639 this.table.on("groupTapHold", this.loadPopupEvent.bind(this, this.table.options.groupContextPopup));
23640 }
23641
23642 if(this.table.options.groupClickPopup){
23643 this.subscribe("group-click", this.loadPopupEvent.bind(this, this.table.options.groupClickPopup));
23644 }
23645
23646 if(this.table.options.groupDblClickPopup){
23647 this.subscribe("group-dblclick", this.loadPopupEvent.bind(this, this.table.options.groupDblClickPopup));
23648 }
23649 }
23650
23651 initializeColumn(column){
23652 var def = column.definition;
23653
23654 //handle column events
23655 if(def.headerContextPopup && !this.columnSubscribers.headerContextPopup){
23656 this.columnSubscribers.headerContextPopup = this.loadPopupTableColumnEvent.bind(this, "headerContextPopup");
23657 this.subscribe("column-contextmenu", this.columnSubscribers.headerContextPopup);
23658 this.table.on("headerTapHold", this.loadPopupTableColumnEvent.bind(this, "headerContextPopup"));
23659 }
23660
23661 if(def.headerClickPopup && !this.columnSubscribers.headerClickPopup){
23662 this.columnSubscribers.headerClickPopup = this.loadPopupTableColumnEvent.bind(this, "headerClickPopup");
23663 this.subscribe("column-click", this.columnSubscribers.headerClickPopup);
23664
23665
23666 }if(def.headerDblClickPopup && !this.columnSubscribers.headerDblClickPopup){
23667 this.columnSubscribers.headerDblClickPopup = this.loadPopupTableColumnEvent.bind(this, "headerDblClickPopup");
23668 this.subscribe("column-dblclick", this.columnSubscribers.headerDblClickPopup);
23669 }
23670
23671 if(def.headerPopup){
23672 this.initializeColumnHeaderPopup(column);
23673 }
23674
23675 //handle cell events
23676 if(def.contextPopup && !this.columnSubscribers.contextPopup){
23677 this.columnSubscribers.contextPopup = this.loadPopupTableCellEvent.bind(this, "contextPopup");
23678 this.subscribe("cell-contextmenu", this.columnSubscribers.contextPopup);
23679 this.table.on("cellTapHold", this.loadPopupTableCellEvent.bind(this, "contextPopup"));
23680 }
23681
23682 if(def.clickPopup && !this.columnSubscribers.clickPopup){
23683 this.columnSubscribers.clickPopup = this.loadPopupTableCellEvent.bind(this, "clickPopup");
23684 this.subscribe("cell-click", this.columnSubscribers.clickPopup);
23685 }
23686
23687 if(def.dblClickPopup && !this.columnSubscribers.dblClickPopup){
23688 this.columnSubscribers.dblClickPopup = this.loadPopupTableCellEvent.bind(this, "dblClickPopup");
23689 this.subscribe("cell-click", this.columnSubscribers.dblClickPopup);
23690 }
23691 }
23692
23693 initializeColumnHeaderPopup(column){
23694 var icon = column.definition.headerPopupIcon,
23695 headerPopupEl;
23696
23697 headerPopupEl = document.createElement("span");
23698 headerPopupEl.classList.add("tabulator-header-popup-button");
23699
23700 if(icon){
23701 if(typeof icon === "function"){
23702 icon = icon(column.getComponent());
23703 }
23704
23705 if(icon instanceof HTMLElement){
23706 headerPopupEl.appendChild(icon);
23707 }else {
23708 headerPopupEl.innerHTML = icon;
23709 }
23710 }else {
23711 headerPopupEl.innerHTML = "&vellip;";
23712 }
23713
23714 headerPopupEl.addEventListener("click", (e) => {
23715 e.stopPropagation();
23716 e.preventDefault();
23717
23718 this.loadPopupEvent(column.definition.headerPopup, e, column);
23719 });
23720
23721 column.titleElement.insertBefore(headerPopupEl, column.titleElement.firstChild);
23722 }
23723
23724 loadPopupTableCellEvent(option, e, cell){
23725 if(cell._cell){
23726 cell = cell._cell;
23727 }
23728
23729 if(cell.column.definition[option]){
23730 this.loadPopupEvent(cell.column.definition[option], e, cell);
23731 }
23732 }
23733
23734 loadPopupTableColumnEvent(option, e, column){
23735 if(column._column){
23736 column = column._column;
23737 }
23738
23739 if(column.definition[option]){
23740 this.loadPopupEvent(column.definition[option], e, column);
23741 }
23742 }
23743
23744 loadPopupEvent(contents, e, component, position){
23745 var renderedCallback;
23746
23747 function onRendered(callback){
23748 renderedCallback = callback;
23749 }
23750
23751 if(component._group){
23752 component = component._group;
23753 }else if(component._row){
23754 component = component._row;
23755 }
23756
23757 contents = typeof contents == "function" ? contents.call(this.table, e, component.getComponent(), onRendered) : contents;
23758
23759 this.loadPopup(e, component, contents, renderedCallback, position);
23760 }
23761
23762 loadPopup(e, component, contents, renderedCallback, position){
23763 var touch = !(e instanceof MouseEvent),
23764 contentsEl, popup;
23765
23766 if(contents instanceof HTMLElement){
23767 contentsEl = contents;
23768 }else {
23769 contentsEl = document.createElement("div");
23770 contentsEl.innerHTML = contents;
23771 }
23772
23773 contentsEl.classList.add("tabulator-popup");
23774
23775 contentsEl.addEventListener("click", (e) =>{
23776 e.stopPropagation();
23777 });
23778
23779 if(!touch){
23780 e.preventDefault();
23781 }
23782
23783 popup = this.popup(contentsEl);
23784
23785 if(typeof renderedCallback === "function"){
23786 popup.renderCallback(renderedCallback);
23787 }
23788
23789 if(e){
23790 popup.show(e);
23791 }else {
23792 popup.show(component.getElement(), position || "center");
23793 }
23794
23795
23796 popup.hideOnBlur(() => {
23797 this.dispatchExternal("popupClosed", component.getComponent());
23798 });
23799
23800 this.dispatchExternal("popupOpened", component.getComponent());
23801 }
23802 }
23803
23804 class Print extends Module{
23805
23806 static moduleName = "print";
23807
23808 constructor(table){
23809 super(table);
23810
23811 this.element = false;
23812 this.manualBlock = false;
23813 this.beforeprintEventHandler = null;
23814 this.afterprintEventHandler = null;
23815
23816 this.registerTableOption("printAsHtml", false); //enable print as html
23817 this.registerTableOption("printFormatter", false); //printing page formatter
23818 this.registerTableOption("printHeader", false); //page header contents
23819 this.registerTableOption("printFooter", false); //page footer contents
23820 this.registerTableOption("printStyled", true); //enable print as html styling
23821 this.registerTableOption("printRowRange", "visible"); //restrict print to visible rows only
23822 this.registerTableOption("printConfig", {}); //print config options
23823
23824 this.registerColumnOption("print");
23825 this.registerColumnOption("titlePrint");
23826 }
23827
23828 initialize(){
23829 if(this.table.options.printAsHtml){
23830 this.beforeprintEventHandler = this.replaceTable.bind(this);
23831 this.afterprintEventHandler = this.cleanup.bind(this);
23832
23833 window.addEventListener("beforeprint", this.beforeprintEventHandler );
23834 window.addEventListener("afterprint", this.afterprintEventHandler);
23835 this.subscribe("table-destroy", this.destroy.bind(this));
23836 }
23837
23838 this.registerTableFunction("print", this.printFullscreen.bind(this));
23839 }
23840
23841 destroy(){
23842 if(this.table.options.printAsHtml){
23843 window.removeEventListener( "beforeprint", this.beforeprintEventHandler );
23844 window.removeEventListener( "afterprint", this.afterprintEventHandler );
23845 }
23846 }
23847
23848 ///////////////////////////////////
23849 ///////// Table Functions /////////
23850 ///////////////////////////////////
23851
23852 ///////////////////////////////////
23853 ///////// Internal Logic //////////
23854 ///////////////////////////////////
23855
23856 replaceTable(){
23857 if(!this.manualBlock){
23858 this.element = document.createElement("div");
23859 this.element.classList.add("tabulator-print-table");
23860
23861 this.element.appendChild(this.table.modules.export.generateTable(this.table.options.printConfig, this.table.options.printStyled, this.table.options.printRowRange, "print"));
23862
23863 this.table.element.style.display = "none";
23864
23865 this.table.element.parentNode.insertBefore(this.element, this.table.element);
23866 }
23867 }
23868
23869 cleanup(){
23870 document.body.classList.remove("tabulator-print-fullscreen-hide");
23871
23872 if(this.element && this.element.parentNode){
23873 this.element.parentNode.removeChild(this.element);
23874 this.table.element.style.display = "";
23875 }
23876 }
23877
23878 printFullscreen(visible, style, config){
23879 var scrollX = window.scrollX,
23880 scrollY = window.scrollY,
23881 headerEl = document.createElement("div"),
23882 footerEl = document.createElement("div"),
23883 tableEl = this.table.modules.export.generateTable(typeof config != "undefined" ? config : this.table.options.printConfig, typeof style != "undefined" ? style : this.table.options.printStyled, visible || this.table.options.printRowRange, "print"),
23884 headerContent, footerContent;
23885
23886 this.manualBlock = true;
23887
23888 this.element = document.createElement("div");
23889 this.element.classList.add("tabulator-print-fullscreen");
23890
23891 if(this.table.options.printHeader){
23892 headerEl.classList.add("tabulator-print-header");
23893
23894 headerContent = typeof this.table.options.printHeader == "function" ? this.table.options.printHeader.call(this.table) : this.table.options.printHeader;
23895
23896 if(typeof headerContent == "string"){
23897 headerEl.innerHTML = headerContent;
23898 }else {
23899 headerEl.appendChild(headerContent);
23900 }
23901
23902 this.element.appendChild(headerEl);
23903 }
23904
23905 this.element.appendChild(tableEl);
23906
23907 if(this.table.options.printFooter){
23908 footerEl.classList.add("tabulator-print-footer");
23909
23910 footerContent = typeof this.table.options.printFooter == "function" ? this.table.options.printFooter.call(this.table) : this.table.options.printFooter;
23911
23912
23913 if(typeof footerContent == "string"){
23914 footerEl.innerHTML = footerContent;
23915 }else {
23916 footerEl.appendChild(footerContent);
23917 }
23918
23919 this.element.appendChild(footerEl);
23920 }
23921
23922 document.body.classList.add("tabulator-print-fullscreen-hide");
23923 document.body.appendChild(this.element);
23924
23925 if(this.table.options.printFormatter){
23926 this.table.options.printFormatter(this.element, tableEl);
23927 }
23928
23929 window.print();
23930
23931 this.cleanup();
23932
23933 window.scrollTo(scrollX, scrollY);
23934
23935 this.manualBlock = false;
23936 }
23937 }
23938
23939 class ReactiveData extends Module{
23940
23941 static moduleName = "reactiveData";
23942
23943 constructor(table){
23944 super(table);
23945
23946 this.data = false;
23947 this.blocked = false; //block reactivity while performing update
23948 this.origFuncs = {}; // hold original data array functions to allow replacement after data is done with
23949 this.currentVersion = 0;
23950
23951 this.registerTableOption("reactiveData", false); //enable data reactivity
23952 }
23953
23954 initialize(){
23955 if(this.table.options.reactiveData){
23956 this.subscribe("cell-value-save-before", this.block.bind(this, "cellsave"));
23957 this.subscribe("cell-value-save-after", this.unblock.bind(this, "cellsave"));
23958 this.subscribe("row-data-save-before", this.block.bind(this, "rowsave"));
23959 this.subscribe("row-data-save-after", this.unblock.bind(this, "rowsave"));
23960 this.subscribe("row-data-init-after", this.watchRow.bind(this));
23961 this.subscribe("data-processing", this.watchData.bind(this));
23962 this.subscribe("table-destroy", this.unwatchData.bind(this));
23963 }
23964 }
23965
23966 watchData(data){
23967 var self = this,
23968 version;
23969
23970 this.currentVersion ++;
23971
23972 version = this.currentVersion;
23973
23974 this.unwatchData();
23975
23976 this.data = data;
23977
23978 //override array push function
23979 this.origFuncs.push = data.push;
23980
23981 Object.defineProperty(this.data, "push", {
23982 enumerable: false,
23983 configurable: true,
23984 value: function(){
23985 var args = Array.from(arguments),
23986 result;
23987
23988 if(!self.blocked && version === self.currentVersion){
23989 self.block("data-push");
23990
23991 args.forEach((arg) => {
23992 self.table.rowManager.addRowActual(arg, false);
23993 });
23994
23995 result = self.origFuncs.push.apply(data, arguments);
23996
23997 self.unblock("data-push");
23998 }
23999
24000 return result;
24001 }
24002 });
24003
24004 //override array unshift function
24005 this.origFuncs.unshift = data.unshift;
24006
24007 Object.defineProperty(this.data, "unshift", {
24008 enumerable: false,
24009 configurable: true,
24010 value: function(){
24011 var args = Array.from(arguments),
24012 result;
24013
24014 if(!self.blocked && version === self.currentVersion){
24015 self.block("data-unshift");
24016
24017 args.forEach((arg) => {
24018 self.table.rowManager.addRowActual(arg, true);
24019 });
24020
24021 result = self.origFuncs.unshift.apply(data, arguments);
24022
24023 self.unblock("data-unshift");
24024 }
24025
24026 return result;
24027 }
24028 });
24029
24030
24031 //override array shift function
24032 this.origFuncs.shift = data.shift;
24033
24034 Object.defineProperty(this.data, "shift", {
24035 enumerable: false,
24036 configurable: true,
24037 value: function(){
24038 var row, result;
24039
24040 if(!self.blocked && version === self.currentVersion){
24041 self.block("data-shift");
24042
24043 if(self.data.length){
24044 row = self.table.rowManager.getRowFromDataObject(self.data[0]);
24045
24046 if(row){
24047 row.deleteActual();
24048 }
24049 }
24050
24051 result = self.origFuncs.shift.call(data);
24052
24053 self.unblock("data-shift");
24054 }
24055
24056 return result;
24057 }
24058 });
24059
24060 //override array pop function
24061 this.origFuncs.pop = data.pop;
24062
24063 Object.defineProperty(this.data, "pop", {
24064 enumerable: false,
24065 configurable: true,
24066 value: function(){
24067 var row, result;
24068
24069 if(!self.blocked && version === self.currentVersion){
24070 self.block("data-pop");
24071
24072 if(self.data.length){
24073 row = self.table.rowManager.getRowFromDataObject(self.data[self.data.length - 1]);
24074
24075 if(row){
24076 row.deleteActual();
24077 }
24078 }
24079
24080 result = self.origFuncs.pop.call(data);
24081
24082 self.unblock("data-pop");
24083 }
24084
24085 return result;
24086 }
24087 });
24088
24089
24090 //override array splice function
24091 this.origFuncs.splice = data.splice;
24092
24093 Object.defineProperty(this.data, "splice", {
24094 enumerable: false,
24095 configurable: true,
24096 value: function(){
24097 var args = Array.from(arguments),
24098 start = args[0] < 0 ? data.length + args[0] : args[0],
24099 end = args[1],
24100 newRows = args[2] ? args.slice(2) : false,
24101 startRow, result;
24102
24103 if(!self.blocked && version === self.currentVersion){
24104 self.block("data-splice");
24105 //add new rows
24106 if(newRows){
24107 startRow = data[start] ? self.table.rowManager.getRowFromDataObject(data[start]) : false;
24108
24109 if(startRow){
24110 newRows.forEach((rowData) => {
24111 self.table.rowManager.addRowActual(rowData, true, startRow, true);
24112 });
24113 }else {
24114 newRows = newRows.slice().reverse();
24115
24116 newRows.forEach((rowData) => {
24117 self.table.rowManager.addRowActual(rowData, true, false, true);
24118 });
24119 }
24120 }
24121
24122 //delete removed rows
24123 if(end !== 0){
24124 var oldRows = data.slice(start, typeof args[1] === "undefined" ? args[1] : start + end);
24125
24126 oldRows.forEach((rowData, i) => {
24127 var row = self.table.rowManager.getRowFromDataObject(rowData);
24128
24129 if(row){
24130 row.deleteActual(i !== oldRows.length - 1);
24131 }
24132 });
24133 }
24134
24135 if(newRows || end !== 0){
24136 self.table.rowManager.reRenderInPosition();
24137 }
24138
24139 result = self.origFuncs.splice.apply(data, arguments);
24140
24141 self.unblock("data-splice");
24142 }
24143
24144 return result ;
24145 }
24146 });
24147 }
24148
24149 unwatchData(){
24150 if(this.data !== false){
24151 for(var key in this.origFuncs){
24152 Object.defineProperty(this.data, key, {
24153 enumerable: true,
24154 configurable:true,
24155 writable:true,
24156 value: this.origFuncs.key,
24157 });
24158 }
24159 }
24160 }
24161
24162 watchRow(row){
24163 var data = row.getData();
24164
24165 for(var key in data){
24166 this.watchKey(row, data, key);
24167 }
24168
24169 if(this.table.options.dataTree){
24170 this.watchTreeChildren(row);
24171 }
24172 }
24173
24174 watchTreeChildren (row){
24175 var self = this,
24176 childField = row.getData()[this.table.options.dataTreeChildField],
24177 origFuncs = {};
24178
24179 if(childField){
24180
24181 origFuncs.push = childField.push;
24182
24183 Object.defineProperty(childField, "push", {
24184 enumerable: false,
24185 configurable: true,
24186 value: () => {
24187 if(!self.blocked){
24188 self.block("tree-push");
24189
24190 var result = origFuncs.push.apply(childField, arguments);
24191 this.rebuildTree(row);
24192
24193 self.unblock("tree-push");
24194 }
24195
24196 return result;
24197 }
24198 });
24199
24200 origFuncs.unshift = childField.unshift;
24201
24202 Object.defineProperty(childField, "unshift", {
24203 enumerable: false,
24204 configurable: true,
24205 value: () => {
24206 if(!self.blocked){
24207 self.block("tree-unshift");
24208
24209 var result = origFuncs.unshift.apply(childField, arguments);
24210 this.rebuildTree(row);
24211
24212 self.unblock("tree-unshift");
24213 }
24214
24215 return result;
24216 }
24217 });
24218
24219 origFuncs.shift = childField.shift;
24220
24221 Object.defineProperty(childField, "shift", {
24222 enumerable: false,
24223 configurable: true,
24224 value: () => {
24225 if(!self.blocked){
24226 self.block("tree-shift");
24227
24228 var result = origFuncs.shift.call(childField);
24229 this.rebuildTree(row);
24230
24231 self.unblock("tree-shift");
24232 }
24233
24234 return result;
24235 }
24236 });
24237
24238 origFuncs.pop = childField.pop;
24239
24240 Object.defineProperty(childField, "pop", {
24241 enumerable: false,
24242 configurable: true,
24243 value: () => {
24244 if(!self.blocked){
24245 self.block("tree-pop");
24246
24247 var result = origFuncs.pop.call(childField);
24248 this.rebuildTree(row);
24249
24250 self.unblock("tree-pop");
24251 }
24252
24253 return result;
24254 }
24255 });
24256
24257 origFuncs.splice = childField.splice;
24258
24259 Object.defineProperty(childField, "splice", {
24260 enumerable: false,
24261 configurable: true,
24262 value: () => {
24263 if(!self.blocked){
24264 self.block("tree-splice");
24265
24266 var result = origFuncs.splice.apply(childField, arguments);
24267 this.rebuildTree(row);
24268
24269 self.unblock("tree-splice");
24270 }
24271
24272 return result;
24273 }
24274 });
24275 }
24276 }
24277
24278 rebuildTree(row){
24279 this.table.modules.dataTree.initializeRow(row);
24280 this.table.modules.dataTree.layoutRow(row);
24281 this.table.rowManager.refreshActiveData("tree", false, true);
24282 }
24283
24284 watchKey(row, data, key){
24285 var self = this,
24286 props = Object.getOwnPropertyDescriptor(data, key),
24287 value = data[key],
24288 version = this.currentVersion;
24289
24290 Object.defineProperty(data, key, {
24291 set: (newValue) => {
24292 value = newValue;
24293 if(!self.blocked && version === self.currentVersion){
24294 self.block("key");
24295
24296 var update = {};
24297 update[key] = newValue;
24298 row.updateData(update);
24299
24300 self.unblock("key");
24301 }
24302
24303 if(props.set){
24304 props.set(newValue);
24305 }
24306 },
24307 get:() => {
24308
24309 if(props.get){
24310 props.get();
24311 }
24312
24313 return value;
24314 }
24315 });
24316 }
24317
24318 unwatchRow(row){
24319 var data = row.getData();
24320
24321 for(var key in data){
24322 Object.defineProperty(data, key, {
24323 value:data[key],
24324 });
24325 }
24326 }
24327
24328 block(key){
24329 if(!this.blocked){
24330 this.blocked = key;
24331 }
24332 }
24333
24334 unblock(key){
24335 if(this.blocked === key){
24336 this.blocked = false;
24337 }
24338 }
24339 }
24340
24341 class ResizeColumns extends Module{
24342
24343 static moduleName = "resizeColumns";
24344
24345 constructor(table){
24346 super(table);
24347
24348 this.startColumn = false;
24349 this.startX = false;
24350 this.startWidth = false;
24351 this.latestX = false;
24352 this.handle = null;
24353 this.initialNextColumn = null;
24354 this.nextColumn = null;
24355
24356 this.initialized = false;
24357 this.registerColumnOption("resizable", true);
24358 this.registerTableOption("resizableColumnFit", false);
24359 this.registerTableOption("resizableColumnGuide", false);
24360 }
24361
24362 initialize(){
24363 this.subscribe("column-rendered", this.layoutColumnHeader.bind(this));
24364 }
24365
24366 initializeEventWatchers(){
24367 if(!this.initialized){
24368
24369 this.subscribe("cell-rendered", this.layoutCellHandles.bind(this));
24370 this.subscribe("cell-delete", this.deInitializeComponent.bind(this));
24371
24372 this.subscribe("cell-height", this.resizeHandle.bind(this));
24373 this.subscribe("column-moved", this.columnLayoutUpdated.bind(this));
24374
24375 this.subscribe("column-hide", this.deInitializeColumn.bind(this));
24376 this.subscribe("column-show", this.columnLayoutUpdated.bind(this));
24377 this.subscribe("column-width", this.columnWidthUpdated.bind(this));
24378
24379 this.subscribe("column-delete", this.deInitializeComponent.bind(this));
24380 this.subscribe("column-height", this.resizeHandle.bind(this));
24381
24382 this.initialized = true;
24383 }
24384 }
24385
24386
24387 layoutCellHandles(cell){
24388 if(cell.row.type === "row"){
24389 this.deInitializeComponent(cell);
24390 this.initializeColumn("cell", cell, cell.column, cell.element);
24391 }
24392 }
24393
24394 layoutColumnHeader(column){
24395 if(column.definition.resizable){
24396 this.initializeEventWatchers();
24397 this.deInitializeComponent(column);
24398 this.initializeColumn("header", column, column, column.element);
24399 }
24400 }
24401
24402 columnLayoutUpdated(column){
24403 var prev = column.prevColumn();
24404
24405 this.reinitializeColumn(column);
24406
24407 if(prev){
24408 this.reinitializeColumn(prev);
24409 }
24410 }
24411
24412 columnWidthUpdated(column){
24413 if(column.modules.frozen){
24414 if(this.table.modules.frozenColumns.leftColumns.includes(column)){
24415 this.table.modules.frozenColumns.leftColumns.forEach((col) => {
24416 this.reinitializeColumn(col);
24417 });
24418 }else if(this.table.modules.frozenColumns.rightColumns.includes(column)){
24419 this.table.modules.frozenColumns.rightColumns.forEach((col) => {
24420 this.reinitializeColumn(col);
24421 });
24422 }
24423 }
24424 }
24425
24426 frozenColumnOffset(column){
24427 var offset = false;
24428
24429 if(column.modules.frozen){
24430 offset = column.modules.frozen.marginValue;
24431
24432 if(column.modules.frozen.position === "left"){
24433 offset += column.getWidth() - 3;
24434 }else {
24435 if(offset){
24436 offset -= 3;
24437 }
24438 }
24439 }
24440
24441 return offset !== false ? offset + "px" : false;
24442 }
24443
24444 reinitializeColumn(column){
24445 var frozenOffset = this.frozenColumnOffset(column);
24446
24447 column.cells.forEach((cell) => {
24448 if(cell.modules.resize && cell.modules.resize.handleEl){
24449 if(frozenOffset){
24450 cell.modules.resize.handleEl.style[column.modules.frozen.position] = frozenOffset;
24451 cell.modules.resize.handleEl.style["z-index"] = 11;
24452 }
24453
24454 cell.element.after(cell.modules.resize.handleEl);
24455 }
24456 });
24457
24458 if(column.modules.resize && column.modules.resize.handleEl){
24459 if(frozenOffset){
24460 column.modules.resize.handleEl.style[column.modules.frozen.position] = frozenOffset;
24461 }
24462
24463 column.element.after(column.modules.resize.handleEl);
24464 }
24465 }
24466
24467 initializeColumn(type, component, column, element){
24468 var self = this,
24469 variableHeight = false,
24470 mode = column.definition.resizable,
24471 config = {},
24472 nearestColumn = column.getLastColumn();
24473
24474 //set column resize mode
24475 if(type === "header"){
24476 variableHeight = column.definition.formatter == "textarea" || column.definition.variableHeight;
24477 config = {variableHeight:variableHeight};
24478 }
24479
24480 if((mode === true || mode == type) && this._checkResizability(nearestColumn)){
24481
24482 var handle = document.createElement('span');
24483 handle.className = "tabulator-col-resize-handle";
24484
24485 handle.addEventListener("click", function(e){
24486 e.stopPropagation();
24487 });
24488
24489 var handleDown = function(e){
24490 self.startColumn = column;
24491 self.initialNextColumn = self.nextColumn = nearestColumn.nextColumn();
24492 self._mouseDown(e, nearestColumn, handle);
24493 };
24494
24495 handle.addEventListener("mousedown", handleDown);
24496 handle.addEventListener("touchstart", handleDown, {passive: true});
24497
24498 //resize column on double click
24499 handle.addEventListener("dblclick", (e) => {
24500 var oldWidth = nearestColumn.getWidth();
24501
24502 e.stopPropagation();
24503 nearestColumn.reinitializeWidth(true);
24504
24505 if(oldWidth !== nearestColumn.getWidth()){
24506 self.dispatch("column-resized", nearestColumn);
24507 self.dispatchExternal("columnResized", nearestColumn.getComponent());
24508 }
24509 });
24510
24511 if(column.modules.frozen){
24512 handle.style.position = "sticky";
24513 handle.style[column.modules.frozen.position] = this.frozenColumnOffset(column);
24514 }
24515
24516 config.handleEl = handle;
24517
24518 if(element.parentNode && column.visible){
24519 element.after(handle);
24520 }
24521 }
24522
24523 component.modules.resize = config;
24524 }
24525
24526 deInitializeColumn(column){
24527 this.deInitializeComponent(column);
24528
24529 column.cells.forEach((cell) => {
24530 this.deInitializeComponent(cell);
24531 });
24532 }
24533
24534 deInitializeComponent(component){
24535 var handleEl;
24536
24537 if(component.modules.resize){
24538 handleEl = component.modules.resize.handleEl;
24539
24540 if(handleEl && handleEl.parentElement){
24541 handleEl.parentElement.removeChild(handleEl);
24542 }
24543 }
24544 }
24545
24546 resizeHandle(component, height){
24547 if(component.modules.resize && component.modules.resize.handleEl){
24548 component.modules.resize.handleEl.style.height = height;
24549 }
24550 }
24551
24552 resize(e, column){
24553 var x = typeof e.clientX === "undefined" ? e.touches[0].clientX : e.clientX,
24554 startDiff = x - this.startX,
24555 moveDiff = x - this.latestX,
24556 blockedBefore, blockedAfter;
24557
24558 this.latestX = x;
24559
24560 if(this.table.rtl){
24561 startDiff = -startDiff;
24562 moveDiff = -moveDiff;
24563 }
24564
24565 blockedBefore = column.width == column.minWidth || column.width == column.maxWidth;
24566
24567 column.setWidth(this.startWidth + startDiff);
24568
24569 blockedAfter = column.width == column.minWidth || column.width == column.maxWidth;
24570
24571 if(moveDiff < 0){
24572 this.nextColumn = this.initialNextColumn;
24573 }
24574
24575 if(this.table.options.resizableColumnFit && this.nextColumn && !(blockedBefore && blockedAfter)){
24576 let colWidth = this.nextColumn.getWidth();
24577
24578 if(moveDiff > 0){
24579 if(colWidth <= this.nextColumn.minWidth){
24580 this.nextColumn = this.nextColumn.nextColumn();
24581 }
24582 }
24583
24584 if(this.nextColumn){
24585 this.nextColumn.setWidth(this.nextColumn.getWidth() - moveDiff);
24586 }
24587 }
24588
24589 this.table.columnManager.rerenderColumns(true);
24590
24591 if(!this.table.browserSlow && column.modules.resize && column.modules.resize.variableHeight){
24592 column.checkCellHeights();
24593 }
24594 }
24595
24596 calcGuidePosition(e, column, handle) {
24597 var mouseX = typeof e.clientX === "undefined" ? e.touches[0].clientX : e.clientX,
24598 handleX = handle.getBoundingClientRect().x - this.table.element.getBoundingClientRect().x,
24599 tableX = this.table.element.getBoundingClientRect().x,
24600 columnX = column.element.getBoundingClientRect().left - tableX,
24601 mouseDiff = mouseX - this.startX,
24602 pos = Math.max(handleX + mouseDiff, columnX + column.minWidth);
24603
24604 if(column.maxWidth){
24605 pos = Math.min(pos, columnX + column.maxWidth);
24606 }
24607
24608 return pos;
24609 }
24610
24611 _checkResizability(column){
24612 return column.definition.resizable;
24613 }
24614
24615 _mouseDown(e, column, handle){
24616 var self = this,
24617 guideEl;
24618
24619 this.dispatchExternal("columnResizing", column.getComponent());
24620
24621 if(self.table.options.resizableColumnGuide){
24622 guideEl = document.createElement("span");
24623 guideEl.classList.add('tabulator-col-resize-guide');
24624 self.table.element.appendChild(guideEl);
24625 setTimeout(() => {
24626 guideEl.style.left = self.calcGuidePosition(e, column, handle) + "px";
24627 });
24628 }
24629
24630 self.table.element.classList.add("tabulator-block-select");
24631
24632 function mouseMove(e){
24633 if(self.table.options.resizableColumnGuide){
24634 guideEl.style.left = self.calcGuidePosition(e, column, handle) + "px";
24635 }else {
24636 self.resize(e, column);
24637 }
24638 }
24639
24640 function mouseUp(e){
24641 if(self.table.options.resizableColumnGuide){
24642 self.resize(e, column);
24643 guideEl.remove();
24644 }
24645
24646 //block editor from taking action while resizing is taking place
24647 if(self.startColumn.modules.edit){
24648 self.startColumn.modules.edit.blocked = false;
24649 }
24650
24651 if(self.table.browserSlow && column.modules.resize && column.modules.resize.variableHeight){
24652 column.checkCellHeights();
24653 }
24654
24655 document.body.removeEventListener("mouseup", mouseUp);
24656 document.body.removeEventListener("mousemove", mouseMove);
24657
24658 handle.removeEventListener("touchmove", mouseMove);
24659 handle.removeEventListener("touchend", mouseUp);
24660
24661 self.table.element.classList.remove("tabulator-block-select");
24662
24663 if(self.startWidth !== column.getWidth()){
24664 self.table.columnManager.verticalAlignHeaders();
24665
24666 self.dispatch("column-resized", column);
24667 self.dispatchExternal("columnResized", column.getComponent());
24668 }
24669 }
24670
24671 e.stopPropagation(); //prevent resize from interfering with movable columns
24672
24673 //block editor from taking action while resizing is taking place
24674 if(self.startColumn.modules.edit){
24675 self.startColumn.modules.edit.blocked = true;
24676 }
24677
24678 self.startX = typeof e.clientX === "undefined" ? e.touches[0].clientX : e.clientX;
24679 self.latestX = self.startX;
24680 self.startWidth = column.getWidth();
24681
24682 document.body.addEventListener("mousemove", mouseMove);
24683 document.body.addEventListener("mouseup", mouseUp);
24684 handle.addEventListener("touchmove", mouseMove, {passive: true});
24685 handle.addEventListener("touchend", mouseUp);
24686 }
24687 }
24688
24689 class ResizeRows extends Module{
24690
24691 static moduleName = "resizeRows";
24692
24693 constructor(table){
24694 super(table);
24695
24696 this.startColumn = false;
24697 this.startY = false;
24698 this.startHeight = false;
24699 this.handle = null;
24700 this.prevHandle = null;
24701
24702 this.registerTableOption("resizableRows", false); //resizable rows
24703 this.registerTableOption("resizableRowGuide", false);
24704 }
24705
24706 initialize(){
24707 if(this.table.options.resizableRows){
24708 this.subscribe("row-layout-after", this.initializeRow.bind(this));
24709 }
24710 }
24711
24712 initializeRow(row){
24713 var self = this,
24714 rowEl = row.getElement();
24715
24716 var handle = document.createElement('div');
24717 handle.className = "tabulator-row-resize-handle";
24718
24719 var prevHandle = document.createElement('div');
24720 prevHandle.className = "tabulator-row-resize-handle prev";
24721
24722 handle.addEventListener("click", function(e){
24723 e.stopPropagation();
24724 });
24725
24726 var handleDown = function(e){
24727 self.startRow = row;
24728 self._mouseDown(e, row, handle);
24729 };
24730
24731 handle.addEventListener("mousedown", handleDown);
24732 handle.addEventListener("touchstart", handleDown, {passive: true});
24733
24734 prevHandle.addEventListener("click", function(e){
24735 e.stopPropagation();
24736 });
24737
24738 var prevHandleDown = function(e){
24739 var prevRow = self.table.rowManager.prevDisplayRow(row);
24740
24741 if(prevRow){
24742 self.startRow = prevRow;
24743 self._mouseDown(e, prevRow, prevHandle);
24744 }
24745 };
24746
24747 prevHandle.addEventListener("mousedown",prevHandleDown);
24748 prevHandle.addEventListener("touchstart",prevHandleDown, {passive: true});
24749
24750 rowEl.appendChild(handle);
24751 rowEl.appendChild(prevHandle);
24752 }
24753
24754 resize(e, row) {
24755 row.setHeight(this.startHeight + ((typeof e.screenY === "undefined" ? e.touches[0].screenY : e.screenY) - this.startY));
24756 }
24757
24758 calcGuidePosition(e, row, handle) {
24759 var mouseY = typeof e.screenY === "undefined" ? e.touches[0].screenY : e.screenY,
24760 handleY = handle.getBoundingClientRect().y - this.table.element.getBoundingClientRect().y,
24761 tableY = this.table.element.getBoundingClientRect().y,
24762 rowY = row.element.getBoundingClientRect().top - tableY,
24763 mouseDiff = mouseY - this.startY;
24764
24765 return Math.max(handleY + mouseDiff, rowY);
24766 }
24767
24768 _mouseDown(e, row, handle){
24769 var self = this,
24770 guideEl;
24771
24772 self.dispatchExternal("rowResizing", row.getComponent());
24773
24774 if(self.table.options.resizableRowGuide){
24775 guideEl = document.createElement("span");
24776 guideEl.classList.add('tabulator-row-resize-guide');
24777 self.table.element.appendChild(guideEl);
24778 setTimeout(() => {
24779 guideEl.style.top = self.calcGuidePosition(e, row, handle) + "px";
24780 });
24781 }
24782
24783 self.table.element.classList.add("tabulator-block-select");
24784
24785 function mouseMove(e){
24786 if(self.table.options.resizableRowGuide){
24787 guideEl.style.top = self.calcGuidePosition(e, row, handle) + "px";
24788 }else {
24789 self.resize(e, row);
24790 }
24791 }
24792
24793 function mouseUp(e){
24794 if(self.table.options.resizableRowGuide){
24795 self.resize(e, row);
24796 guideEl.remove();
24797 }
24798
24799 // //block editor from taking action while resizing is taking place
24800 // if(self.startColumn.modules.edit){
24801 // self.startColumn.modules.edit.blocked = false;
24802 // }
24803
24804 document.body.removeEventListener("mouseup", mouseMove);
24805 document.body.removeEventListener("mousemove", mouseMove);
24806
24807 handle.removeEventListener("touchmove", mouseMove);
24808 handle.removeEventListener("touchend", mouseUp);
24809
24810 self.table.element.classList.remove("tabulator-block-select");
24811
24812 self.dispatchExternal("rowResized", row.getComponent());
24813 }
24814
24815 e.stopPropagation(); //prevent resize from interfering with movable columns
24816
24817 //block editor from taking action while resizing is taking place
24818 // if(self.startColumn.modules.edit){
24819 // self.startColumn.modules.edit.blocked = true;
24820 // }
24821
24822 self.startY = typeof e.screenY === "undefined" ? e.touches[0].screenY : e.screenY;
24823 self.startHeight = row.getHeight();
24824
24825 document.body.addEventListener("mousemove", mouseMove);
24826 document.body.addEventListener("mouseup", mouseUp);
24827
24828 handle.addEventListener("touchmove", mouseMove, {passive: true});
24829 handle.addEventListener("touchend", mouseUp);
24830 }
24831 }
24832
24833 class ResizeTable extends Module{
24834
24835 static moduleName = "resizeTable";
24836
24837 constructor(table){
24838 super(table);
24839
24840 this.binding = false;
24841 this.visibilityObserver = false;
24842 this.resizeObserver = false;
24843 this.containerObserver = false;
24844
24845 this.tableHeight = 0;
24846 this.tableWidth = 0;
24847 this.containerHeight = 0;
24848 this.containerWidth = 0;
24849
24850 this.autoResize = false;
24851
24852 this.visible = false;
24853
24854 this.initialized = false;
24855 this.initialRedraw = false;
24856
24857 this.registerTableOption("autoResize", true); //auto resize table
24858 }
24859
24860 initialize(){
24861 if(this.table.options.autoResize){
24862 var table = this.table,
24863 tableStyle;
24864
24865 this.tableHeight = table.element.clientHeight;
24866 this.tableWidth = table.element.clientWidth;
24867
24868 if(table.element.parentNode){
24869 this.containerHeight = table.element.parentNode.clientHeight;
24870 this.containerWidth = table.element.parentNode.clientWidth;
24871 }
24872
24873 if(typeof IntersectionObserver !== "undefined" && typeof ResizeObserver !== "undefined" && table.rowManager.getRenderMode() === "virtual"){
24874
24875 this.initializeVisibilityObserver();
24876
24877 this.autoResize = true;
24878
24879 this.resizeObserver = new ResizeObserver((entry) => {
24880 if(!table.browserMobile || (table.browserMobile && (!table.modules.edit || (table.modules.edit && !table.modules.edit.currentCell)))){
24881
24882 var nodeHeight = Math.floor(entry[0].contentRect.height);
24883 var nodeWidth = Math.floor(entry[0].contentRect.width);
24884
24885 if(this.tableHeight != nodeHeight || this.tableWidth != nodeWidth){
24886 this.tableHeight = nodeHeight;
24887 this.tableWidth = nodeWidth;
24888
24889 if(table.element.parentNode){
24890 this.containerHeight = table.element.parentNode.clientHeight;
24891 this.containerWidth = table.element.parentNode.clientWidth;
24892 }
24893
24894 this.redrawTable();
24895 }
24896 }
24897 });
24898
24899 this.resizeObserver.observe(table.element);
24900
24901 tableStyle = window.getComputedStyle(table.element);
24902
24903 if(this.table.element.parentNode && !this.table.rowManager.fixedHeight && (tableStyle.getPropertyValue("max-height") || tableStyle.getPropertyValue("min-height"))){
24904
24905 this.containerObserver = new ResizeObserver((entry) => {
24906 if(!table.browserMobile || (table.browserMobile && (!table.modules.edit || (table.modules.edit && !table.modules.edit.currentCell)))){
24907
24908 var nodeHeight = Math.floor(entry[0].contentRect.height);
24909 var nodeWidth = Math.floor(entry[0].contentRect.width);
24910
24911 if(this.containerHeight != nodeHeight || this.containerWidth != nodeWidth){
24912 this.containerHeight = nodeHeight;
24913 this.containerWidth = nodeWidth;
24914 this.tableHeight = table.element.clientHeight;
24915 this.tableWidth = table.element.clientWidth;
24916 }
24917
24918 this.redrawTable();
24919 }
24920 });
24921
24922 this.containerObserver.observe(this.table.element.parentNode);
24923 }
24924
24925 this.subscribe("table-resize", this.tableResized.bind(this));
24926
24927 }else {
24928 this.binding = function(){
24929 if(!table.browserMobile || (table.browserMobile && (!table.modules.edit || (table.modules.edit && !table.modules.edit.currentCell)))){
24930 table.columnManager.rerenderColumns(true);
24931 table.redraw();
24932 }
24933 };
24934
24935 window.addEventListener("resize", this.binding);
24936 }
24937
24938 this.subscribe("table-destroy", this.clearBindings.bind(this));
24939 }
24940 }
24941
24942 initializeVisibilityObserver(){
24943 this.visibilityObserver = new IntersectionObserver((entries) => {
24944 this.visible = entries[0].isIntersecting;
24945
24946 if(!this.initialized){
24947 this.initialized = true;
24948 this.initialRedraw = !this.visible;
24949 }else {
24950 if(this.visible){
24951 this.redrawTable(this.initialRedraw);
24952 this.initialRedraw = false;
24953 }
24954 }
24955 });
24956
24957 this.visibilityObserver.observe(this.table.element);
24958 }
24959
24960 redrawTable(force){
24961 if(this.initialized && this.visible){
24962 this.table.columnManager.rerenderColumns(true);
24963 this.table.redraw(force);
24964 }
24965 }
24966
24967 tableResized(){
24968 this.table.rowManager.redraw();
24969 }
24970
24971 clearBindings(){
24972 if(this.binding){
24973 window.removeEventListener("resize", this.binding);
24974 }
24975
24976 if(this.resizeObserver){
24977 this.resizeObserver.unobserve(this.table.element);
24978 }
24979
24980 if(this.visibilityObserver){
24981 this.visibilityObserver.unobserve(this.table.element);
24982 }
24983
24984 if(this.containerObserver){
24985 this.containerObserver.unobserve(this.table.element.parentNode);
24986 }
24987 }
24988 }
24989
24990 function responsiveCollapse(cell, formatterParams, onRendered){
24991 var el = document.createElement("div"),
24992 config = cell.getRow()._row.modules.responsiveLayout;
24993
24994 el.classList.add("tabulator-responsive-collapse-toggle");
24995
24996 el.innerHTML = `<svg class='tabulator-responsive-collapse-toggle-open' viewbox="0 0 24 24">
24997 <line x1="7" y1="12" x2="17" y2="12" fill="none" stroke-width="3" stroke-linecap="round" />
24998 <line y1="7" x1="12" y2="17" x2="12" fill="none" stroke-width="3" stroke-linecap="round" />
24999 </svg>
25000
25001 <svg class='tabulator-responsive-collapse-toggle-close' viewbox="0 0 24 24">
25002 <line x1="7" y1="12" x2="17" y2="12" fill="none" stroke-width="3" stroke-linecap="round" />
25003 </svg>`;
25004
25005 cell.getElement().classList.add("tabulator-row-handle");
25006
25007 function toggleList(isOpen){
25008 var collapseEl = config.element;
25009
25010 config.open = isOpen;
25011
25012 if(collapseEl){
25013
25014 if(config.open){
25015 el.classList.add("open");
25016 collapseEl.style.display = '';
25017 }else {
25018 el.classList.remove("open");
25019 collapseEl.style.display = 'none';
25020 }
25021 }
25022 }
25023
25024 el.addEventListener("click", function(e){
25025 e.stopImmediatePropagation();
25026 toggleList(!config.open);
25027 cell.getTable().rowManager.adjustTableSize();
25028 });
25029
25030 toggleList(config.open);
25031
25032 return el;
25033 }
25034
25035 var extensions$2 = {
25036 format:{
25037 formatters:{
25038 responsiveCollapse:responsiveCollapse,
25039 }
25040 }
25041 };
25042
25043 class ResponsiveLayout extends Module{
25044
25045 static moduleName = "responsiveLayout";
25046 static moduleExtensions = extensions$2;
25047
25048 constructor(table){
25049 super(table);
25050
25051 this.columns = [];
25052 this.hiddenColumns = [];
25053 this.mode = "";
25054 this.index = 0;
25055 this.collapseFormatter = [];
25056 this.collapseStartOpen = true;
25057 this.collapseHandleColumn = false;
25058
25059 this.registerTableOption("responsiveLayout", false); //responsive layout flags
25060 this.registerTableOption("responsiveLayoutCollapseStartOpen", true); //start showing collapsed data
25061 this.registerTableOption("responsiveLayoutCollapseUseFormatters", true); //responsive layout collapse formatter
25062 this.registerTableOption("responsiveLayoutCollapseFormatter", false); //responsive layout collapse formatter
25063
25064 this.registerColumnOption("responsive");
25065 }
25066
25067 //generate responsive columns list
25068 initialize(){
25069 if(this.table.options.responsiveLayout){
25070 this.subscribe("column-layout", this.initializeColumn.bind(this));
25071 this.subscribe("column-show", this.updateColumnVisibility.bind(this));
25072 this.subscribe("column-hide", this.updateColumnVisibility.bind(this));
25073 this.subscribe("columns-loaded", this.initializeResponsivity.bind(this));
25074 this.subscribe("column-moved", this.initializeResponsivity.bind(this));
25075 this.subscribe("column-add", this.initializeResponsivity.bind(this));
25076 this.subscribe("column-delete", this.initializeResponsivity.bind(this));
25077
25078 this.subscribe("table-redrawing", this.tableRedraw.bind(this));
25079
25080 if(this.table.options.responsiveLayout === "collapse"){
25081 this.subscribe("row-data-changed", this.generateCollapsedRowContent.bind(this));
25082 this.subscribe("row-init", this.initializeRow.bind(this));
25083 this.subscribe("row-layout", this.layoutRow.bind(this));
25084 }
25085 }
25086 }
25087
25088 tableRedraw(force){
25089 if(["fitColumns", "fitDataStretch"].indexOf(this.layoutMode()) === -1){
25090 if(!force){
25091 this.update();
25092 }
25093 }
25094 }
25095
25096 initializeResponsivity(){
25097 var columns = [];
25098
25099 this.mode = this.table.options.responsiveLayout;
25100 this.collapseFormatter = this.table.options.responsiveLayoutCollapseFormatter || this.formatCollapsedData;
25101 this.collapseStartOpen = this.table.options.responsiveLayoutCollapseStartOpen;
25102 this.hiddenColumns = [];
25103
25104 if(this.collapseFormatter){
25105 this.collapseFormatter = this.collapseFormatter.bind(this.table);
25106 }
25107
25108 //determine level of responsivity for each column
25109 this.table.columnManager.columnsByIndex.forEach((column, i) => {
25110 if(column.modules.responsive){
25111 if(column.modules.responsive.order && column.modules.responsive.visible){
25112 column.modules.responsive.index = i;
25113 columns.push(column);
25114
25115 if(!column.visible && this.mode === "collapse"){
25116 this.hiddenColumns.push(column);
25117 }
25118 }
25119 }
25120 });
25121
25122 //sort list by responsivity
25123 columns = columns.reverse();
25124 columns = columns.sort((a, b) => {
25125 var diff = b.modules.responsive.order - a.modules.responsive.order;
25126 return diff || (b.modules.responsive.index - a.modules.responsive.index);
25127 });
25128
25129 this.columns = columns;
25130
25131 if(this.mode === "collapse"){
25132 this.generateCollapsedContent();
25133 }
25134
25135 //assign collapse column
25136 for (let col of this.table.columnManager.columnsByIndex){
25137 if(col.definition.formatter == "responsiveCollapse"){
25138 this.collapseHandleColumn = col;
25139 break;
25140 }
25141 }
25142
25143 if(this.collapseHandleColumn){
25144 if(this.hiddenColumns.length){
25145 this.collapseHandleColumn.show();
25146 }else {
25147 this.collapseHandleColumn.hide();
25148 }
25149 }
25150 }
25151
25152 //define layout information
25153 initializeColumn(column){
25154 var def = column.getDefinition();
25155
25156 column.modules.responsive = {order: typeof def.responsive === "undefined" ? 1 : def.responsive, visible:def.visible === false ? false : true};
25157 }
25158
25159 initializeRow(row){
25160 var el;
25161
25162 if(row.type !== "calc"){
25163 el = document.createElement("div");
25164 el.classList.add("tabulator-responsive-collapse");
25165
25166 row.modules.responsiveLayout = {
25167 element:el,
25168 open:this.collapseStartOpen,
25169 };
25170
25171 if(!this.collapseStartOpen){
25172 el.style.display = 'none';
25173 }
25174 }
25175 }
25176
25177 layoutRow(row){
25178 var rowEl = row.getElement();
25179
25180 if(row.modules.responsiveLayout){
25181 rowEl.appendChild(row.modules.responsiveLayout.element);
25182 this.generateCollapsedRowContent(row);
25183 }
25184 }
25185
25186 //update column visibility
25187 updateColumnVisibility(column, responsiveToggle){
25188 if(!responsiveToggle && column.modules.responsive){
25189 column.modules.responsive.visible = column.visible;
25190 this.initializeResponsivity();
25191 }
25192 }
25193
25194 hideColumn(column){
25195 var colCount = this.hiddenColumns.length;
25196
25197 column.hide(false, true);
25198
25199 if(this.mode === "collapse"){
25200 this.hiddenColumns.unshift(column);
25201 this.generateCollapsedContent();
25202
25203 if(this.collapseHandleColumn && !colCount){
25204 this.collapseHandleColumn.show();
25205 }
25206 }
25207 }
25208
25209 showColumn(column){
25210 var index;
25211
25212 column.show(false, true);
25213 //set column width to prevent calculation loops on uninitialized columns
25214 column.setWidth(column.getWidth());
25215
25216 if(this.mode === "collapse"){
25217 index = this.hiddenColumns.indexOf(column);
25218
25219 if(index > -1){
25220 this.hiddenColumns.splice(index, 1);
25221 }
25222
25223 this.generateCollapsedContent();
25224
25225 if(this.collapseHandleColumn && !this.hiddenColumns.length){
25226 this.collapseHandleColumn.hide();
25227 }
25228 }
25229 }
25230
25231 //redraw columns to fit space
25232 update(){
25233 var working = true;
25234
25235 while(working){
25236
25237 let width = this.table.modules.layout.getMode() == "fitColumns" ? this.table.columnManager.getFlexBaseWidth() : this.table.columnManager.getWidth();
25238
25239 let diff = (this.table.options.headerVisible ? this.table.columnManager.element.clientWidth : this.table.element.clientWidth) - width;
25240
25241 if(diff < 0){
25242 //table is too wide
25243 let column = this.columns[this.index];
25244
25245 if(column){
25246 this.hideColumn(column);
25247 this.index ++;
25248 }else {
25249 working = false;
25250 }
25251
25252 }else {
25253
25254 //table has spare space
25255 let column = this.columns[this.index -1];
25256
25257 if(column){
25258 if(diff > 0){
25259 if(diff >= column.getWidth()){
25260 this.showColumn(column);
25261 this.index --;
25262 }else {
25263 working = false;
25264 }
25265 }else {
25266 working = false;
25267 }
25268 }else {
25269 working = false;
25270 }
25271 }
25272
25273 if(!this.table.rowManager.activeRowsCount){
25274 this.table.rowManager.renderEmptyScroll();
25275 }
25276 }
25277 }
25278
25279 generateCollapsedContent(){
25280 var rows = this.table.rowManager.getDisplayRows();
25281
25282 rows.forEach((row) => {
25283 this.generateCollapsedRowContent(row);
25284 });
25285 }
25286
25287 generateCollapsedRowContent(row){
25288 var el, contents;
25289
25290 if(row.modules.responsiveLayout){
25291 el = row.modules.responsiveLayout.element;
25292
25293 while(el.firstChild) el.removeChild(el.firstChild);
25294
25295 contents = this.collapseFormatter(this.generateCollapsedRowData(row));
25296 if(contents){
25297 el.appendChild(contents);
25298 }
25299 row.calcHeight(true);
25300 }
25301 }
25302
25303 generateCollapsedRowData(row){
25304 var data = row.getData(),
25305 output = [],
25306 mockCellComponent;
25307
25308 this.hiddenColumns.forEach((column) => {
25309 var value = column.getFieldValue(data);
25310
25311 if(column.definition.title && column.field){
25312 if(column.modules.format && this.table.options.responsiveLayoutCollapseUseFormatters){
25313
25314 mockCellComponent = {
25315 value:false,
25316 data:{},
25317 getValue:function(){
25318 return value;
25319 },
25320 getData:function(){
25321 return data;
25322 },
25323 getType:function(){
25324 return "cell";
25325 },
25326 getElement:function(){
25327 return document.createElement("div");
25328 },
25329 getRow:function(){
25330 return row.getComponent();
25331 },
25332 getColumn:function(){
25333 return column.getComponent();
25334 },
25335 getTable:() => {
25336 return this.table;
25337 },
25338 };
25339
25340 function onRendered(callback){
25341 callback();
25342 }
25343
25344 output.push({
25345 field: column.field,
25346 title: column.definition.title,
25347 value: column.modules.format.formatter.call(this.table.modules.format, mockCellComponent, column.modules.format.params, onRendered)
25348 });
25349 }else {
25350 output.push({
25351 field: column.field,
25352 title: column.definition.title,
25353 value: value
25354 });
25355 }
25356 }
25357 });
25358
25359 return output;
25360 }
25361
25362 formatCollapsedData(data){
25363 var list = document.createElement("table");
25364
25365 data.forEach((item) => {
25366 var row = document.createElement("tr");
25367 var titleData = document.createElement("td");
25368 var valueData = document.createElement("td");
25369 var node_content;
25370
25371 var titleHighlight = document.createElement("strong");
25372 titleData.appendChild(titleHighlight);
25373
25374 this.modules.localize.bind("columns|" + item.field, function(text){
25375 titleHighlight.innerHTML = text || item.title;
25376 });
25377
25378 if(item.value instanceof Node){
25379 node_content = document.createElement("div");
25380 node_content.appendChild(item.value);
25381 valueData.appendChild(node_content);
25382 }else {
25383 valueData.innerHTML = item.value;
25384 }
25385
25386 row.appendChild(titleData);
25387 row.appendChild(valueData);
25388 list.appendChild(row);
25389 });
25390
25391 return Object.keys(data).length ? list : "";
25392 }
25393 }
25394
25395 function rowSelection(cell, formatterParams, onRendered){
25396 var checkbox = document.createElement("input");
25397 var blocked = false;
25398
25399 checkbox.type = 'checkbox';
25400
25401 checkbox.setAttribute("aria-label", "Select Row");
25402
25403 if(this.table.modExists("selectRow", true)){
25404
25405 checkbox.addEventListener("click", (e) => {
25406 e.stopPropagation();
25407 });
25408
25409 if(typeof cell.getRow == 'function'){
25410 var row = cell.getRow();
25411
25412 if(row instanceof RowComponent){
25413
25414 checkbox.addEventListener("change", (e) => {
25415 if(this.table.options.selectableRowsRangeMode === "click"){
25416 if(!blocked){
25417 row.toggleSelect();
25418 }else {
25419 blocked = false;
25420 }
25421 }else {
25422 row.toggleSelect();
25423 }
25424 });
25425
25426 if(this.table.options.selectableRowsRangeMode === "click"){
25427 checkbox.addEventListener("click", (e) => {
25428 blocked = true;
25429 this.table.modules.selectRow.handleComplexRowClick(row._row, e);
25430 });
25431 }
25432
25433 checkbox.checked = row.isSelected && row.isSelected();
25434 this.table.modules.selectRow.registerRowSelectCheckbox(row, checkbox);
25435 }else {
25436 checkbox = "";
25437 }
25438 }else {
25439 checkbox.addEventListener("change", (e) => {
25440 if(this.table.modules.selectRow.selectedRows.length){
25441 this.table.deselectRow();
25442 }else {
25443 this.table.selectRow(formatterParams.rowRange);
25444 }
25445 });
25446
25447 this.table.modules.selectRow.registerHeaderSelectCheckbox(checkbox);
25448 }
25449 }
25450
25451 return checkbox;
25452 }
25453
25454 var extensions$1 = {
25455 format:{
25456 formatters:{
25457 rowSelection:rowSelection,
25458 }
25459 }
25460 };
25461
25462 class SelectRow extends Module{
25463
25464 static moduleName = "selectRow";
25465 static moduleExtensions = extensions$1;
25466
25467 constructor(table){
25468 super(table);
25469
25470 this.selecting = false; //flag selecting in progress
25471 this.lastClickedRow = false; //last clicked row
25472 this.selectPrev = []; //hold previously selected element for drag drop selection
25473 this.selectedRows = []; //hold selected rows
25474 this.headerCheckboxElement = null; // hold header select element
25475
25476 this.registerTableOption("selectableRows", "highlight"); //highlight rows on hover
25477 this.registerTableOption("selectableRowsRangeMode", "drag"); //highlight rows on hover
25478 this.registerTableOption("selectableRowsRollingSelection", true); //roll selection once maximum number of selectable rows is reached
25479 this.registerTableOption("selectableRowsPersistence", true); // maintain selection when table view is updated
25480 this.registerTableOption("selectableRowsCheck", function(data, row){return true;}); //check whether row is selectable
25481
25482 this.registerTableFunction("selectRow", this.selectRows.bind(this));
25483 this.registerTableFunction("deselectRow", this.deselectRows.bind(this));
25484 this.registerTableFunction("toggleSelectRow", this.toggleRow.bind(this));
25485 this.registerTableFunction("getSelectedRows", this.getSelectedRows.bind(this));
25486 this.registerTableFunction("getSelectedData", this.getSelectedData.bind(this));
25487
25488 //register component functions
25489 this.registerComponentFunction("row", "select", this.selectRows.bind(this));
25490 this.registerComponentFunction("row", "deselect", this.deselectRows.bind(this));
25491 this.registerComponentFunction("row", "toggleSelect", this.toggleRow.bind(this));
25492 this.registerComponentFunction("row", "isSelected", this.isRowSelected.bind(this));
25493 }
25494
25495 initialize(){
25496
25497 this.deprecatedOptionsCheck();
25498
25499 if(this.table.options.selectableRows === "highlight" && this.table.options.selectableRange){
25500 this.table.options.selectableRows = false;
25501 }
25502
25503 if(this.table.options.selectableRows !== false){
25504 this.subscribe("row-init", this.initializeRow.bind(this));
25505 this.subscribe("row-deleting", this.rowDeleted.bind(this));
25506 this.subscribe("rows-wipe", this.clearSelectionData.bind(this));
25507 this.subscribe("rows-retrieve", this.rowRetrieve.bind(this));
25508
25509 if(this.table.options.selectableRows && !this.table.options.selectableRowsPersistence){
25510 this.subscribe("data-refreshing", this.deselectRows.bind(this));
25511 }
25512 }
25513 }
25514
25515 deprecatedOptionsCheck(){
25516 // this.deprecationCheck("selectable", "selectableRows", true);
25517 // this.deprecationCheck("selectableRollingSelection", "selectableRowsRollingSelection", true);
25518 // this.deprecationCheck("selectableRangeMode", "selectableRowsRangeMode", true);
25519 // this.deprecationCheck("selectablePersistence", "selectableRowsPersistence", true);
25520 // this.deprecationCheck("selectableCheck", "selectableRowsCheck", true);
25521 }
25522
25523 rowRetrieve(type, prevValue){
25524 return type === "selected" ? this.selectedRows : prevValue;
25525 }
25526
25527 rowDeleted(row){
25528 this._deselectRow(row, true);
25529 }
25530
25531 clearSelectionData(silent){
25532 var prevSelected = this.selectedRows.length;
25533
25534 this.selecting = false;
25535 this.lastClickedRow = false;
25536 this.selectPrev = [];
25537 this.selectedRows = [];
25538
25539 if(prevSelected && silent !== true){
25540 this._rowSelectionChanged();
25541 }
25542 }
25543
25544 initializeRow(row){
25545 var self = this,
25546 selectable = self.checkRowSelectability(row),
25547 element = row.getElement();
25548
25549 // trigger end of row selection
25550 var endSelect = function(){
25551
25552 setTimeout(function(){
25553 self.selecting = false;
25554 }, 50);
25555
25556 document.body.removeEventListener("mouseup", endSelect);
25557 };
25558
25559 row.modules.select = {selected:false};
25560
25561 element.classList.toggle("tabulator-selectable", selectable);
25562 element.classList.toggle("tabulator-unselectable", !selectable);
25563
25564 //set row selection class
25565 if(self.checkRowSelectability(row)){
25566 if(self.table.options.selectableRows && self.table.options.selectableRows != "highlight"){
25567 if(self.table.options.selectableRowsRangeMode === "click"){
25568 element.addEventListener("click", this.handleComplexRowClick.bind(this, row));
25569 }else {
25570 element.addEventListener("click", function(e){
25571 if(!self.table.modExists("edit") || !self.table.modules.edit.getCurrentCell()){
25572 self.table._clearSelection();
25573 }
25574
25575 if(!self.selecting){
25576 self.toggleRow(row);
25577 }
25578 });
25579
25580 element.addEventListener("mousedown", function(e){
25581 if(e.shiftKey){
25582 self.table._clearSelection();
25583
25584 self.selecting = true;
25585
25586 self.selectPrev = [];
25587
25588 document.body.addEventListener("mouseup", endSelect);
25589 document.body.addEventListener("keyup", endSelect);
25590
25591 self.toggleRow(row);
25592
25593 return false;
25594 }
25595 });
25596
25597 element.addEventListener("mouseenter", function(e){
25598 if(self.selecting){
25599 self.table._clearSelection();
25600 self.toggleRow(row);
25601
25602 if(self.selectPrev[1] == row){
25603 self.toggleRow(self.selectPrev[0]);
25604 }
25605 }
25606 });
25607
25608 element.addEventListener("mouseout", function(e){
25609 if(self.selecting){
25610 self.table._clearSelection();
25611 self.selectPrev.unshift(row);
25612 }
25613 });
25614 }
25615 }
25616 }
25617 }
25618
25619 handleComplexRowClick(row, e){
25620 if(e.shiftKey){
25621 this.table._clearSelection();
25622 this.lastClickedRow = this.lastClickedRow || row;
25623
25624 var lastClickedRowIdx = this.table.rowManager.getDisplayRowIndex(this.lastClickedRow);
25625 var rowIdx = this.table.rowManager.getDisplayRowIndex(row);
25626
25627 var fromRowIdx = lastClickedRowIdx <= rowIdx ? lastClickedRowIdx : rowIdx;
25628 var toRowIdx = lastClickedRowIdx >= rowIdx ? lastClickedRowIdx : rowIdx;
25629
25630 var rows = this.table.rowManager.getDisplayRows().slice(0);
25631 var toggledRows = rows.splice(fromRowIdx, toRowIdx - fromRowIdx + 1);
25632
25633 if(e.ctrlKey || e.metaKey){
25634 toggledRows.forEach((toggledRow)=>{
25635 if(toggledRow !== this.lastClickedRow){
25636
25637 if(this.table.options.selectableRows !== true && !this.isRowSelected(row)){
25638 if(this.selectedRows.length < this.table.options.selectableRows){
25639 this.toggleRow(toggledRow);
25640 }
25641 }else {
25642 this.toggleRow(toggledRow);
25643 }
25644 }
25645 });
25646 this.lastClickedRow = row;
25647 }else {
25648 this.deselectRows(undefined, true);
25649
25650 if(this.table.options.selectableRows !== true){
25651 if(toggledRows.length > this.table.options.selectableRows){
25652 toggledRows = toggledRows.slice(0, this.table.options.selectableRows);
25653 }
25654 }
25655
25656 this.selectRows(toggledRows);
25657 }
25658 this.table._clearSelection();
25659 }
25660 else if(e.ctrlKey || e.metaKey){
25661 this.toggleRow(row);
25662 this.lastClickedRow = row;
25663 }else {
25664 this.deselectRows(undefined, true);
25665 this.selectRows(row);
25666 this.lastClickedRow = row;
25667 }
25668 }
25669
25670 checkRowSelectability(row){
25671 if(row && row.type === "row"){
25672 return this.table.options.selectableRowsCheck.call(this.table, row.getComponent());
25673 }
25674
25675 return false;
25676 }
25677
25678 //toggle row selection
25679 toggleRow(row){
25680 if(this.checkRowSelectability(row)){
25681 if(row.modules.select && row.modules.select.selected){
25682 this._deselectRow(row);
25683 }else {
25684 this._selectRow(row);
25685 }
25686 }
25687 }
25688
25689 //select a number of rows
25690 selectRows(rows){
25691 var changes = [],
25692 rowMatch, change;
25693
25694 switch(typeof rows){
25695 case "undefined":
25696 rowMatch = this.table.rowManager.rows;
25697 break;
25698
25699 case "number":
25700 rowMatch = this.table.rowManager.findRow(rows);
25701 break;
25702
25703 case "string":
25704 rowMatch = this.table.rowManager.findRow(rows);
25705
25706 if(!rowMatch){
25707 rowMatch = this.table.rowManager.getRows(rows);
25708 }
25709 break;
25710
25711 default:
25712 rowMatch = rows;
25713 break;
25714 }
25715
25716 if(Array.isArray(rowMatch)){
25717 if(rowMatch.length){
25718 rowMatch.forEach((row) => {
25719 change = this._selectRow(row, true, true);
25720
25721 if(change){
25722 changes.push(change);
25723 }
25724 });
25725
25726 this._rowSelectionChanged(false, changes);
25727 }
25728 }else {
25729 if(rowMatch){
25730 this._selectRow(rowMatch, false, true);
25731 }
25732 }
25733 }
25734
25735 //select an individual row
25736 _selectRow(rowInfo, silent, force){
25737 //handle max row count
25738 if(!isNaN(this.table.options.selectableRows) && this.table.options.selectableRows !== true && !force){
25739 if(this.selectedRows.length >= this.table.options.selectableRows){
25740 if(this.table.options.selectableRowsRollingSelection){
25741 this._deselectRow(this.selectedRows[0]);
25742 }else {
25743 return false;
25744 }
25745 }
25746 }
25747
25748 var row = this.table.rowManager.findRow(rowInfo);
25749
25750 if(row){
25751 if(this.selectedRows.indexOf(row) == -1){
25752 row.getElement().classList.add("tabulator-selected");
25753 if(!row.modules.select){
25754 row.modules.select = {};
25755 }
25756
25757 row.modules.select.selected = true;
25758 if(row.modules.select.checkboxEl){
25759 row.modules.select.checkboxEl.checked = true;
25760 }
25761
25762 this.selectedRows.push(row);
25763
25764 if(this.table.options.dataTreeSelectPropagate){
25765 this.childRowSelection(row, true);
25766 }
25767
25768 this.dispatchExternal("rowSelected", row.getComponent());
25769
25770 this._rowSelectionChanged(silent, row);
25771
25772 return row;
25773 }
25774 }else {
25775 if(!silent){
25776 console.warn("Selection Error - No such row found, ignoring selection:" + rowInfo);
25777 }
25778 }
25779 }
25780
25781 isRowSelected(row){
25782 return this.selectedRows.indexOf(row) !== -1;
25783 }
25784
25785 //deselect a number of rows
25786 deselectRows(rows, silent){
25787 var changes = [],
25788 rowMatch, change;
25789
25790 switch(typeof rows){
25791 case "undefined":
25792 rowMatch = Object.assign([], this.selectedRows);
25793 break;
25794
25795 case "number":
25796 rowMatch = this.table.rowManager.findRow(rows);
25797 break;
25798
25799 case "string":
25800 rowMatch = this.table.rowManager.findRow(rows);
25801
25802 if(!rowMatch){
25803 rowMatch = this.table.rowManager.getRows(rows);
25804 }
25805 break;
25806
25807 default:
25808 rowMatch = rows;
25809 break;
25810 }
25811
25812 if(Array.isArray(rowMatch)){
25813 if(rowMatch.length){
25814 rowMatch.forEach((row) => {
25815 change = this._deselectRow(row, true, true);
25816
25817 if(change){
25818 changes.push(change);
25819 }
25820 });
25821
25822 this._rowSelectionChanged(silent, [], changes);
25823 }
25824 }else {
25825 if(rowMatch){
25826 this._deselectRow(rowMatch, silent, true);
25827 }
25828 }
25829 }
25830
25831 //deselect an individual row
25832 _deselectRow(rowInfo, silent){
25833 var self = this,
25834 row = self.table.rowManager.findRow(rowInfo),
25835 index, element;
25836
25837 if(row){
25838 index = self.selectedRows.findIndex(function(selectedRow){
25839 return selectedRow == row;
25840 });
25841
25842 if(index > -1){
25843
25844 element = row.getElement();
25845
25846 if(element){
25847 element.classList.remove("tabulator-selected");
25848 }
25849
25850 if(!row.modules.select){
25851 row.modules.select = {};
25852 }
25853
25854 row.modules.select.selected = false;
25855 if(row.modules.select.checkboxEl){
25856 row.modules.select.checkboxEl.checked = false;
25857 }
25858 self.selectedRows.splice(index, 1);
25859
25860 if(this.table.options.dataTreeSelectPropagate){
25861 this.childRowSelection(row, false);
25862 }
25863
25864 this.dispatchExternal("rowDeselected", row.getComponent());
25865
25866 self._rowSelectionChanged(silent, undefined, row);
25867
25868 return row;
25869 }
25870 }else {
25871 if(!silent){
25872 console.warn("Deselection Error - No such row found, ignoring selection:" + rowInfo);
25873 }
25874 }
25875 }
25876
25877 getSelectedData(){
25878 var data = [];
25879
25880 this.selectedRows.forEach(function(row){
25881 data.push(row.getData());
25882 });
25883
25884 return data;
25885 }
25886
25887 getSelectedRows(){
25888 var rows = [];
25889
25890 this.selectedRows.forEach(function(row){
25891 rows.push(row.getComponent());
25892 });
25893
25894 return rows;
25895 }
25896
25897 _rowSelectionChanged(silent, selected = [], deselected = []){
25898 if(this.headerCheckboxElement){
25899 if(this.selectedRows.length === 0){
25900 this.headerCheckboxElement.checked = false;
25901 this.headerCheckboxElement.indeterminate = false;
25902 } else if(this.table.rowManager.rows.length === this.selectedRows.length){
25903 this.headerCheckboxElement.checked = true;
25904 this.headerCheckboxElement.indeterminate = false;
25905 } else {
25906 this.headerCheckboxElement.indeterminate = true;
25907 this.headerCheckboxElement.checked = false;
25908 }
25909 }
25910
25911 if(!silent){
25912 if(!Array.isArray(selected)){
25913 selected = [selected];
25914 }
25915
25916 selected = selected.map(row => row.getComponent());
25917
25918 if(!Array.isArray(deselected)){
25919 deselected = [deselected];
25920 }
25921
25922 deselected = deselected.map(row => row.getComponent());
25923
25924 this.dispatchExternal("rowSelectionChanged", this.getSelectedData(), this.getSelectedRows(), selected, deselected);
25925 }
25926 }
25927
25928 registerRowSelectCheckbox (row, element) {
25929 if(!row._row.modules.select){
25930 row._row.modules.select = {};
25931 }
25932
25933 row._row.modules.select.checkboxEl = element;
25934 }
25935
25936 registerHeaderSelectCheckbox (element) {
25937 this.headerCheckboxElement = element;
25938 }
25939
25940 childRowSelection(row, select){
25941 var children = this.table.modules.dataTree.getChildren(row, true, true);
25942
25943 if(select){
25944 for(let child of children){
25945 this._selectRow(child, true);
25946 }
25947 }else {
25948 for(let child of children){
25949 this._deselectRow(child, true);
25950 }
25951 }
25952 }
25953 }
25954
25955 class RangeComponent {
25956 constructor(range) {
25957 this._range = range;
25958
25959 return new Proxy(this, {
25960 get: function (target, name, receiver) {
25961 if (typeof target[name] !== "undefined") {
25962 return target[name];
25963 } else {
25964 return target._range.table.componentFunctionBinder.handle("range", target._range, name);
25965 }
25966 },
25967 });
25968 }
25969
25970 getElement() {
25971 return this._range.element;
25972 }
25973
25974 getData() {
25975 return this._range.getData();
25976 }
25977
25978 getCells() {
25979 return this._range.getCells(true, true);
25980 }
25981
25982 getStructuredCells() {
25983 return this._range.getStructuredCells();
25984 }
25985
25986 getRows() {
25987 return this._range.getRows().map((row) => row.getComponent());
25988 }
25989
25990 getColumns() {
25991 return this._range.getColumns().map((column) => column.getComponent());
25992 }
25993
25994 getBounds() {
25995 return this._range.getBounds();
25996 }
25997
25998 getTopEdge() {
25999 return this._range.top;
26000 }
26001
26002 getBottomEdge() {
26003 return this._range.bottom;
26004 }
26005
26006 getLeftEdge() {
26007 return this._range.left;
26008 }
26009
26010 getRightEdge() {
26011 return this._range.right;
26012 }
26013
26014 setBounds(start, end){
26015 if(this._range.destroyedGuard("setBounds")){
26016 this._range.setBounds(start ? start._cell : start, end ? end._cell : end);
26017 }
26018 }
26019
26020 setStartBound(start){
26021 if(this._range.destroyedGuard("setStartBound")){
26022 this._range.setEndBound(start ? start._cell : start);
26023 this._range.rangeManager.layoutElement();
26024 }
26025 }
26026
26027 setEndBound(end){
26028 if(this._range.destroyedGuard("setEndBound")){
26029 this._range.setEndBound(end ? end._cell : end);
26030 this._range.rangeManager.layoutElement();
26031 }
26032 }
26033
26034 clearValues(){
26035 if(this._range.destroyedGuard("clearValues")){
26036 this._range.clearValues();
26037 }
26038 }
26039
26040 remove(){
26041 if(this._range.destroyedGuard("remove")){
26042 this._range.destroy(true);
26043 }
26044 }
26045 }
26046
26047 class Range extends CoreFeature{
26048 constructor(table, rangeManager, start, end) {
26049 super(table);
26050
26051 this.rangeManager = rangeManager;
26052 this.element = null;
26053 this.initialized = false;
26054 this.initializing = {
26055 start:false,
26056 end:false,
26057 };
26058 this.destroyed = false;
26059
26060 this.top = 0;
26061 this.bottom = 0;
26062 this.left = 0;
26063 this.right = 0;
26064
26065 this.table = table;
26066 this.start = {row:0, col:0};
26067 this.end = {row:0, col:0};
26068
26069 if(this.rangeManager.rowHeader){
26070 this.left = 1;
26071 this.right = 1;
26072 this.start.col = 1;
26073 this.end.col = 1;
26074 }
26075
26076 this.initElement();
26077
26078 setTimeout(() => {
26079 this.initBounds(start, end);
26080 });
26081 }
26082
26083 initElement(){
26084 this.element = document.createElement("div");
26085 this.element.classList.add("tabulator-range");
26086 }
26087
26088 initBounds(start, end){
26089 this._updateMinMax();
26090
26091 if(start){
26092 this.setBounds(start, end || start);
26093 }
26094 }
26095
26096 ///////////////////////////////////
26097 /////// Boundary Setup ///////
26098 ///////////////////////////////////
26099
26100 setStart(row, col) {
26101 if(this.start.row !== row || this.start.col !== col){
26102 this.start.row = row;
26103 this.start.col = col;
26104
26105 this.initializing.start = true;
26106 this._updateMinMax();
26107 }
26108 }
26109
26110 setEnd(row, col) {
26111 if(this.end.row !== row || this.end.col !== col){
26112 this.end.row = row;
26113 this.end.col = col;
26114
26115 this.initializing.end = true;
26116 this._updateMinMax();
26117 }
26118 }
26119
26120 setBounds(start, end, visibleRows){
26121 if(start){
26122 this.setStartBound(start);
26123 }
26124
26125 this.setEndBound(end || start);
26126 this.rangeManager.layoutElement(visibleRows);
26127 }
26128
26129 setStartBound(element){
26130 var row, col;
26131
26132 if (element.type === "column") {
26133 if(this.rangeManager.columnSelection){
26134 this.setStart(0, element.getPosition() - 1);
26135 }
26136 }else {
26137 row = element.row.position - 1;
26138 col = element.column.getPosition() - 1;
26139
26140 if (element.column === this.rangeManager.rowHeader) {
26141 this.setStart(row, 1);
26142 } else {
26143 this.setStart(row, col);
26144 }
26145 }
26146 }
26147
26148 setEndBound(element){
26149 var rowsCount = this._getTableRows().length,
26150 row, col, isRowHeader;
26151
26152 if (element.type === "column") {
26153 if(this.rangeManager.columnSelection){
26154 if (this.rangeManager.selecting === "column") {
26155 this.setEnd(rowsCount - 1, element.getPosition() - 1);
26156 } else if (this.rangeManager.selecting === "cell") {
26157 this.setEnd(0, element.getPosition() - 1);
26158 }
26159 }
26160 }else {
26161 row = element.row.position - 1;
26162 col = element.column.getPosition() - 1;
26163 isRowHeader = element.column === this.rangeManager.rowHeader;
26164
26165 if (this.rangeManager.selecting === "row") {
26166 this.setEnd(row, this._getTableColumns().length - 1);
26167 } else if (this.rangeManager.selecting !== "row" && isRowHeader) {
26168 this.setEnd(row, 0);
26169 } else if (this.rangeManager.selecting === "column") {
26170 this.setEnd(rowsCount - 1, col);
26171 } else {
26172 this.setEnd(row, col);
26173 }
26174 }
26175 }
26176
26177 _updateMinMax() {
26178 this.top = Math.min(this.start.row, this.end.row);
26179 this.bottom = Math.max(this.start.row, this.end.row);
26180 this.left = Math.min(this.start.col, this.end.col);
26181 this.right = Math.max(this.start.col, this.end.col);
26182
26183 if(this.initialized){
26184 this.dispatchExternal("rangeChanged", this.getComponent());
26185 }else {
26186 if(this.initializing.start && this.initializing.end){
26187 this.initialized = true;
26188 this.dispatchExternal("rangeAdded", this.getComponent());
26189 }
26190 }
26191 }
26192
26193 _getTableColumns() {
26194 return this.table.columnManager.getVisibleColumnsByIndex();
26195 }
26196
26197 _getTableRows() {
26198 return this.table.rowManager.getDisplayRows().filter(row=> row.type === "row");
26199 }
26200
26201 ///////////////////////////////////
26202 /////// Rendering ///////
26203 ///////////////////////////////////
26204
26205 layout() {
26206 var _vDomTop = this.table.rowManager.renderer.vDomTop,
26207 _vDomBottom = this.table.rowManager.renderer.vDomBottom,
26208 _vDomLeft = this.table.columnManager.renderer.leftCol,
26209 _vDomRight = this.table.columnManager.renderer.rightCol,
26210 top, bottom, left, right, topLeftCell, bottomRightCell, topLeftCellEl, bottomRightCellEl, topLeftRowEl, bottomRightRowEl;
26211
26212 if(this.table.options.renderHorizontal === "virtual" && this.rangeManager.rowHeader) {
26213 _vDomRight += 1;
26214 }
26215
26216 if (_vDomTop == null) {
26217 _vDomTop = 0;
26218 }
26219
26220 if (_vDomBottom == null) {
26221 _vDomBottom = Infinity;
26222 }
26223
26224 if (_vDomLeft == null) {
26225 _vDomLeft = 0;
26226 }
26227
26228 if (_vDomRight == null) {
26229 _vDomRight = Infinity;
26230 }
26231
26232 if (this.overlaps(_vDomLeft, _vDomTop, _vDomRight, _vDomBottom)) {
26233 top = Math.max(this.top, _vDomTop);
26234 bottom = Math.min(this.bottom, _vDomBottom);
26235 left = Math.max(this.left, _vDomLeft);
26236 right = Math.min(this.right, _vDomRight);
26237
26238 topLeftCell = this.rangeManager.getCell(top, left);
26239 bottomRightCell = this.rangeManager.getCell(bottom, right);
26240 topLeftCellEl = topLeftCell.getElement();
26241 bottomRightCellEl = bottomRightCell.getElement();
26242 topLeftRowEl = topLeftCell.row.getElement();
26243 bottomRightRowEl = bottomRightCell.row.getElement();
26244
26245 this.element.classList.add("tabulator-range-active");
26246 // this.element.classList.toggle("tabulator-range-active", this === this.rangeManager.activeRange);
26247
26248 if(this.table.rtl){
26249 this.element.style.right = topLeftRowEl.offsetWidth - topLeftCellEl.offsetLeft - topLeftCellEl.offsetWidth + "px";
26250 this.element.style.width = topLeftCellEl.offsetLeft + topLeftCellEl.offsetWidth - bottomRightCellEl.offsetLeft + "px";
26251 }else {
26252 this.element.style.left = topLeftRowEl.offsetLeft + topLeftCellEl.offsetLeft + "px";
26253 this.element.style.width = bottomRightCellEl.offsetLeft + bottomRightCellEl.offsetWidth - topLeftCellEl.offsetLeft + "px";
26254 }
26255
26256 this.element.style.top = topLeftRowEl.offsetTop + "px";
26257 this.element.style.height = bottomRightRowEl.offsetTop + bottomRightRowEl.offsetHeight - topLeftRowEl.offsetTop + "px";
26258 }
26259 }
26260
26261 atTopLeft(cell) {
26262 return cell.row.position - 1 === this.top && cell.column.getPosition() - 1 === this.left;
26263 }
26264
26265 atBottomRight(cell) {
26266 return cell.row.position - 1 === this.bottom && cell.column.getPosition() - 1 === this.right;
26267 }
26268
26269 occupies(cell) {
26270 return this.occupiesRow(cell.row) && this.occupiesColumn(cell.column);
26271 }
26272
26273 occupiesRow(row) {
26274 return this.top <= row.position - 1 && row.position - 1 <= this.bottom;
26275 }
26276
26277 occupiesColumn(col) {
26278 return this.left <= col.getPosition() - 1 && col.getPosition() - 1 <= this.right;
26279 }
26280
26281 overlaps(left, top, right, bottom) {
26282 if ((this.left > right || left > this.right) || (this.top > bottom || top > this.bottom)){
26283 return false;
26284 }
26285
26286 return true;
26287 }
26288
26289 getData() {
26290 var data = [],
26291 rows = this.getRows(),
26292 columns = this.getColumns();
26293
26294 rows.forEach((row) => {
26295 var rowData = row.getData(),
26296 result = {};
26297
26298 columns.forEach((column) => {
26299 result[column.field] = rowData[column.field];
26300 });
26301
26302 data.push(result);
26303 });
26304
26305 return data;
26306 }
26307
26308 getCells(structured, component) {
26309 var cells = [],
26310 rows = this.getRows(),
26311 columns = this.getColumns();
26312
26313 if (structured) {
26314 cells = rows.map((row) => {
26315 var arr = [];
26316
26317 row.getCells().forEach((cell) => {
26318 if (columns.includes(cell.column)) {
26319 arr.push(component ? cell.getComponent() : cell);
26320 }
26321 });
26322
26323 return arr;
26324 });
26325 } else {
26326 rows.forEach((row) => {
26327 row.getCells().forEach((cell) => {
26328 if (columns.includes(cell.column)) {
26329 cells.push(component ? cell.getComponent() : cell);
26330 }
26331 });
26332 });
26333 }
26334
26335 return cells;
26336 }
26337
26338 getStructuredCells() {
26339 return this.getCells(true, true);
26340 }
26341
26342 getRows() {
26343 return this._getTableRows().slice(this.top, this.bottom + 1);
26344 }
26345
26346 getColumns() {
26347 return this._getTableColumns().slice(this.left, this.right + 1);
26348 }
26349
26350 clearValues(){
26351 var cells = this.getCells();
26352 var clearValue = this.table.options.selectableRangeClearCellsValue;
26353
26354 this.table.blockRedraw();
26355
26356 cells.forEach((cell) => {
26357 cell.setValue(clearValue);
26358 });
26359
26360 this.table.restoreRedraw();
26361
26362 }
26363
26364 getBounds(component){
26365 var cells = this.getCells(false, component),
26366 output = {
26367 start:null,
26368 end:null,
26369 };
26370
26371 if(cells.length){
26372 output.start = cells[0];
26373 output.end = cells[cells.length - 1];
26374 }else {
26375 console.warn("No bounds defined on range");
26376 }
26377
26378 return output;
26379 }
26380
26381 getComponent() {
26382 if (!this.component) {
26383 this.component = new RangeComponent(this);
26384 }
26385 return this.component;
26386 }
26387
26388 destroy(notify) {
26389 this.destroyed = true;
26390
26391 this.element.remove();
26392
26393 if(notify){
26394 this.rangeManager.rangeRemoved(this);
26395 }
26396
26397 if(this.initialized){
26398 this.dispatchExternal("rangeRemoved", this.getComponent());
26399 }
26400 }
26401
26402 destroyedGuard(func){
26403 if(this.destroyed){
26404 console.warn("You cannot call the " + func + " function on a destroyed range");
26405 }
26406
26407 return !this.destroyed;
26408 }
26409 }
26410
26411 var bindings = {
26412 rangeJumpUp:["ctrl + 38", "meta + 38"],
26413 rangeJumpDown:["ctrl + 40", "meta + 40"],
26414 rangeJumpLeft:["ctrl + 37", "meta + 37"],
26415 rangeJumpRight:["ctrl + 39", "meta + 39"],
26416 rangeExpandUp:"shift + 38",
26417 rangeExpandDown:"shift + 40",
26418 rangeExpandLeft:"shift + 37",
26419 rangeExpandRight:"shift + 39",
26420 rangeExpandJumpUp:["ctrl + shift + 38", "meta + shift + 38"],
26421 rangeExpandJumpDown:["ctrl + shift + 40", "meta + shift + 40"],
26422 rangeExpandJumpLeft:["ctrl + shift + 37", "meta + shift + 37"],
26423 rangeExpandJumpRight:["ctrl + shift + 39", "meta + shift + 39"],
26424 };
26425
26426 var actions = {
26427 rangeJumpLeft: function(e){
26428 this.dispatch("keybinding-nav-range", e, "left", true, false);
26429 },
26430 rangeJumpRight: function(e){
26431 this.dispatch("keybinding-nav-range", e, "right", true, false);
26432 },
26433 rangeJumpUp: function(e){
26434 this.dispatch("keybinding-nav-range", e, "up", true, false);
26435 },
26436 rangeJumpDown: function(e){
26437 this.dispatch("keybinding-nav-range", e, "down", true, false);
26438 },
26439 rangeExpandLeft: function(e){
26440 this.dispatch("keybinding-nav-range", e, "left", false, true);
26441 },
26442 rangeExpandRight: function(e){
26443 this.dispatch("keybinding-nav-range", e, "right", false, true);
26444 },
26445 rangeExpandUp: function(e){
26446 this.dispatch("keybinding-nav-range", e, "up", false, true);
26447 },
26448 rangeExpandDown: function(e){
26449 this.dispatch("keybinding-nav-range", e, "down", false, true);
26450 },
26451 rangeExpandJumpLeft: function(e){
26452 this.dispatch("keybinding-nav-range", e, "left", true, true);
26453 },
26454 rangeExpandJumpRight: function(e){
26455 this.dispatch("keybinding-nav-range", e, "right", true, true);
26456 },
26457 rangeExpandJumpUp: function(e){
26458 this.dispatch("keybinding-nav-range", e, "up", true, true);
26459 },
26460 rangeExpandJumpDown: function(e){
26461 this.dispatch("keybinding-nav-range", e, "down", true, true);
26462 },
26463 };
26464
26465 var pasteActions = {
26466 range:function(data){
26467 var rows = [],
26468 range = this.table.modules.selectRange.activeRange,
26469 singleCell = false,
26470 bounds, startCell, startRow, rowWidth, dataLength;
26471
26472 dataLength = data.length;
26473
26474 if(range){
26475 bounds = range.getBounds();
26476 startCell = bounds.start;
26477
26478 if(bounds.start === bounds.end){
26479 singleCell = true;
26480 }
26481
26482 if(startCell){
26483 rows = this.table.rowManager.activeRows.slice();
26484 startRow = rows.indexOf(startCell.row);
26485
26486 if(singleCell){
26487 rowWidth = data.length;
26488 }else {
26489 rowWidth = (rows.indexOf(bounds.end.row) - startRow) + 1;
26490 }
26491
26492
26493 if(startRow >-1){
26494 this.table.blockRedraw();
26495
26496 rows = rows.slice(startRow, startRow + rowWidth);
26497
26498 rows.forEach((row, i) => {
26499 row.updateData(data[i % dataLength]);
26500 });
26501
26502 this.table.restoreRedraw();
26503 }
26504 }
26505 }
26506
26507 return rows;
26508 }
26509 };
26510
26511 var pasteParsers = {
26512 range:function(clipboard){
26513 var data = [],
26514 rows = [],
26515 range = this.table.modules.selectRange.activeRange,
26516 singleCell = false,
26517 bounds, startCell, colWidth, columnMap, startCol;
26518
26519 if(range){
26520 bounds = range.getBounds();
26521 startCell = bounds.start;
26522
26523 if(bounds.start === bounds.end){
26524 singleCell = true;
26525 }
26526
26527 if(startCell){
26528 //get data from clipboard into array of columns and rows.
26529 clipboard = clipboard.split("\n");
26530
26531 clipboard.forEach(function(row){
26532 data.push(row.split("\t"));
26533 });
26534
26535 if(data.length){
26536 columnMap = this.table.columnManager.getVisibleColumnsByIndex();
26537 startCol = columnMap.indexOf(startCell.column);
26538
26539 if(startCol > -1){
26540 if(singleCell){
26541 colWidth = data[0].length;
26542 }else {
26543 colWidth = (columnMap.indexOf(bounds.end.column) - startCol) + 1;
26544 }
26545
26546 columnMap = columnMap.slice(startCol, startCol + colWidth);
26547
26548 data.forEach((item) => {
26549 var row = {};
26550 var itemLength = item.length;
26551
26552 columnMap.forEach(function(col, i){
26553 row[col.field] = item[i % itemLength];
26554 });
26555
26556 rows.push(row);
26557 });
26558
26559 return rows;
26560 }
26561 }
26562 }
26563 }
26564
26565 return false;
26566 }
26567 };
26568
26569 var columnLookups = {
26570 range:function(){
26571 var columns = this.modules.selectRange.selectedColumns();
26572
26573 if(this.columnManager.rowHeader){
26574 columns.unshift(this.columnManager.rowHeader);
26575 }
26576
26577 return columns;
26578 },
26579 };
26580
26581 var rowLookups = {
26582 range:function(){
26583 return this.modules.selectRange.selectedRows();
26584 },
26585 };
26586
26587 var extensions = {
26588 keybindings:{
26589 bindings:bindings,
26590 actions:actions
26591 },
26592 clipboard:{
26593 pasteActions:pasteActions,
26594 pasteParsers:pasteParsers
26595 },
26596 export:{
26597 columnLookups:columnLookups,
26598 rowLookups:rowLookups,
26599 }
26600 };
26601
26602 class SelectRange extends Module {
26603
26604 static moduleName = "selectRange";
26605 static moduleInitOrder = 1;
26606 static moduleExtensions = extensions;
26607
26608 constructor(table) {
26609 super(table);
26610
26611 this.selecting = "cell";
26612 this.mousedown = false;
26613 this.ranges = [];
26614 this.overlay = null;
26615 this.rowHeader = null;
26616 this.layoutChangeTimeout = null;
26617 this.columnSelection = false;
26618 this.rowSelection = false;
26619 this.maxRanges = 0;
26620 this.activeRange = false;
26621 this.blockKeydown = false;
26622
26623 this.keyDownEvent = this._handleKeyDown.bind(this);
26624 this.mouseUpEvent = this._handleMouseUp.bind(this);
26625
26626 this.registerTableOption("selectableRange", false); //enable selectable range
26627 this.registerTableOption("selectableRangeColumns", false); //enable selectable range
26628 this.registerTableOption("selectableRangeRows", false); //enable selectable range
26629 this.registerTableOption("selectableRangeClearCells", false); //allow clearing of active range
26630 this.registerTableOption("selectableRangeClearCellsValue", undefined); //value for cleared active range
26631 this.registerTableOption("selectableRangeAutoFocus", true); //focus on a cell after resetRanges
26632
26633 this.registerTableFunction("getRangesData", this.getRangesData.bind(this));
26634 this.registerTableFunction("getRanges", this.getRanges.bind(this));
26635 this.registerTableFunction("addRange", this.addRangeFromComponent.bind(this));
26636
26637 this.registerComponentFunction("cell", "getRanges", this.cellGetRanges.bind(this));
26638 this.registerComponentFunction("row", "getRanges", this.rowGetRanges.bind(this));
26639 this.registerComponentFunction("column", "getRanges", this.colGetRanges.bind(this));
26640 }
26641
26642 ///////////////////////////////////
26643 /////// Initialization ///////
26644 ///////////////////////////////////
26645
26646 initialize() {
26647 if (this.options("selectableRange")) {
26648 if(!this.options("selectableRows")){
26649 this.maxRanges = this.options("selectableRange");
26650
26651 this.initializeTable();
26652 this.initializeWatchers();
26653 }else {
26654 console.warn("SelectRange functionality cannot be used in conjunction with row selection");
26655 }
26656
26657 if(this.options('columns').findIndex((column) => column.frozen) > 0) {
26658 console.warn("Having frozen column in arbitrary position with selectRange option may result in unpredictable behavior.");
26659 }
26660
26661 if(this.options('columns').filter((column) => column.frozen) > 1) {
26662 console.warn("Having multiple frozen columns with selectRange option may result in unpredictable behavior.");
26663 }
26664 }
26665 }
26666
26667
26668 initializeTable() {
26669 this.overlay = document.createElement("div");
26670 this.overlay.classList.add("tabulator-range-overlay");
26671
26672 this.rangeContainer = document.createElement("div");
26673 this.rangeContainer.classList.add("tabulator-range-container");
26674
26675 this.activeRangeCellElement = document.createElement("div");
26676 this.activeRangeCellElement.classList.add("tabulator-range-cell-active");
26677
26678 this.overlay.appendChild(this.rangeContainer);
26679 this.overlay.appendChild(this.activeRangeCellElement);
26680
26681 this.table.rowManager.element.addEventListener("keydown", this.keyDownEvent);
26682
26683 this.resetRanges();
26684
26685 this.table.rowManager.element.appendChild(this.overlay);
26686 this.table.columnManager.element.setAttribute("tabindex", 0);
26687 this.table.element.classList.add("tabulator-ranges");
26688 }
26689
26690 initializeWatchers() {
26691 this.columnSelection = this.options("selectableRangeColumns");
26692 this.rowSelection = this.options("selectableRangeRows");
26693
26694 this.subscribe("column-init", this.initializeColumn.bind(this));
26695 this.subscribe("column-mousedown", this.handleColumnMouseDown.bind(this));
26696 this.subscribe("column-mousemove", this.handleColumnMouseMove.bind(this));
26697 this.subscribe("column-resized", this.handleColumnResized.bind(this));
26698 this.subscribe("column-moving", this.handleColumnMoving.bind(this));
26699 this.subscribe("column-moved", this.handleColumnMoved.bind(this));
26700 this.subscribe("column-width", this.layoutChange.bind(this));
26701 this.subscribe("column-height", this.layoutChange.bind(this));
26702 this.subscribe("column-resized", this.layoutChange.bind(this));
26703 this.subscribe("columns-loaded", this.updateHeaderColumn.bind(this));
26704
26705 this.subscribe("cell-height", this.layoutChange.bind(this));
26706 this.subscribe("cell-rendered", this.renderCell.bind(this));
26707 this.subscribe("cell-mousedown", this.handleCellMouseDown.bind(this));
26708 this.subscribe("cell-mousemove", this.handleCellMouseMove.bind(this));
26709 this.subscribe("cell-click", this.handleCellClick.bind(this));
26710 this.subscribe("cell-editing", this.handleEditingCell.bind(this));
26711
26712 this.subscribe("page-changed", this.redraw.bind(this));
26713
26714 this.subscribe("scroll-vertical", this.layoutChange.bind(this));
26715 this.subscribe("scroll-horizontal", this.layoutChange.bind(this));
26716
26717 this.subscribe("data-destroy", this.tableDestroyed.bind(this));
26718 this.subscribe("data-processed", this.resetRanges.bind(this));
26719
26720 this.subscribe("table-layout", this.layoutElement.bind(this));
26721 this.subscribe("table-redraw", this.redraw.bind(this));
26722 this.subscribe("table-destroy", this.tableDestroyed.bind(this));
26723
26724 this.subscribe("edit-editor-clear", this.finishEditingCell.bind(this));
26725 this.subscribe("edit-blur", this.restoreFocus.bind(this));
26726
26727 this.subscribe("keybinding-nav-prev", this.keyNavigate.bind(this, "left"));
26728 this.subscribe("keybinding-nav-next", this.keyNavigate.bind(this, "right"));
26729 this.subscribe("keybinding-nav-left", this.keyNavigate.bind(this, "left"));
26730 this.subscribe("keybinding-nav-right", this.keyNavigate.bind(this, "right"));
26731 this.subscribe("keybinding-nav-up", this.keyNavigate.bind(this, "up"));
26732 this.subscribe("keybinding-nav-down", this.keyNavigate.bind(this, "down"));
26733 this.subscribe("keybinding-nav-range", this.keyNavigateRange.bind(this));
26734 }
26735
26736
26737 initializeColumn(column) {
26738 if(this.columnSelection && column.definition.headerSort && this.options("headerSortClickElement") !== "icon"){
26739 console.warn("Using column headerSort with selectableRangeColumns option may result in unpredictable behavior. Consider using headerSortClickElement: 'icon'.");
26740 }
26741
26742 if (column.modules.edit) ;
26743 }
26744
26745 updateHeaderColumn(){
26746 var frozenCols;
26747
26748 if(this.rowSelection){
26749 this.rowHeader = this.table.columnManager.getVisibleColumnsByIndex()[0];
26750
26751 if(this.rowHeader){
26752 this.rowHeader.definition.cssClass = this.rowHeader.definition.cssClass + " tabulator-range-row-header";
26753
26754 if(this.rowHeader.definition.headerSort){
26755 console.warn("Using column headerSort with selectableRangeRows option may result in unpredictable behavior");
26756 }
26757
26758 if(this.rowHeader.definition.editor){
26759 console.warn("Using column editor with selectableRangeRows option may result in unpredictable behavior");
26760 }
26761 }
26762 }
26763
26764 //warn if invalid frozen column configuration detected
26765 if(this.table.modules.frozenColumns && this.table.modules.frozenColumns.active){
26766 frozenCols = this.table.modules.frozenColumns.getFrozenColumns();
26767
26768 if(frozenCols.length > 1 || (frozenCols.length === 1 && frozenCols[0] !== this.rowHeader)){
26769 console.warn("Using frozen columns that are not the range header in combination with the selectRange option may result in unpredictable behavior");
26770 }
26771 }
26772 }
26773
26774 ///////////////////////////////////
26775 /////// Table Functions ///////
26776 ///////////////////////////////////
26777
26778 getRanges(){
26779 return this.ranges.map((range) => range.getComponent());
26780 }
26781
26782 getRangesData() {
26783 return this.ranges.map((range) => range.getData());
26784 }
26785
26786 addRangeFromComponent(start, end){
26787 start = start ? start._cell : null;
26788 end = end ? end._cell : null;
26789
26790 return this.addRange(start, end);
26791 }
26792
26793 ///////////////////////////////////
26794 /////// Component Functions ///////
26795 ///////////////////////////////////
26796
26797 cellGetRanges(cell){
26798 var ranges = [];
26799
26800 if (cell.column === this.rowHeader) {
26801 ranges = this.ranges.filter((range) => range.occupiesRow(cell.row));
26802 } else {
26803 ranges = this.ranges.filter((range) => range.occupies(cell));
26804 }
26805
26806 return ranges.map((range) => range.getComponent());
26807 }
26808
26809 rowGetRanges(row){
26810 var ranges = this.ranges.filter((range) => range.occupiesRow(row));
26811
26812 return ranges.map((range) => range.getComponent());
26813 }
26814
26815 colGetRanges(col){
26816 var ranges = this.ranges.filter((range) => range.occupiesColumn(col));
26817
26818 return ranges.map((range) => range.getComponent());
26819 }
26820
26821 ///////////////////////////////////
26822 ////////// Event Handlers /////////
26823 ///////////////////////////////////
26824
26825 _handleMouseUp(e){
26826 this.mousedown = false;
26827 document.removeEventListener("mouseup", this.mouseUpEvent);
26828 }
26829
26830 _handleKeyDown(e) {
26831 if (!this.blockKeydown && (!this.table.modules.edit || (this.table.modules.edit && !this.table.modules.edit.currentCell))) {
26832 if (e.key === "Enter") {
26833 // is editing a cell?
26834 if (this.table.modules.edit && this.table.modules.edit.currentCell) {
26835 return;
26836 }
26837
26838 this.table.modules.edit.editCell(this.getActiveCell());
26839
26840 e.preventDefault();
26841 }
26842
26843 if ((e.key === "Backspace" || e.key === "Delete") && this.options("selectableRangeClearCells")) {
26844 if(this.activeRange){
26845 this.activeRange.clearValues();
26846 }
26847 }
26848 }
26849 }
26850
26851 initializeFocus(cell){
26852 var range;
26853
26854 this.restoreFocus();
26855
26856 try{
26857 if (document.selection) { // IE
26858 range = document.body.createTextRange();
26859 range.moveToElementText(cell.getElement());
26860 range.select();
26861 } else if (window.getSelection) {
26862 range = document.createRange();
26863 range.selectNode(cell.getElement());
26864 window.getSelection().removeAllRanges();
26865 window.getSelection().addRange(range);
26866 }
26867 }catch(e){}
26868 }
26869
26870 restoreFocus(element){
26871 this.table.rowManager.element.focus();
26872
26873 return true;
26874 }
26875
26876 ///////////////////////////////////
26877 ////// Column Functionality ///////
26878 ///////////////////////////////////
26879
26880 handleColumnResized(column) {
26881 var selected;
26882
26883 if (this.selecting !== "column" && this.selecting !== "all") {
26884 return;
26885 }
26886
26887 selected = this.ranges.some((range) => range.occupiesColumn(column));
26888
26889 if (!selected) {
26890 return;
26891 }
26892
26893 this.ranges.forEach((range) => {
26894 var selectedColumns = range.getColumns(true);
26895
26896 selectedColumns.forEach((selectedColumn) => {
26897 if (selectedColumn !== column) {
26898 selectedColumn.setWidth(column.width);
26899 }
26900 });
26901 });
26902 }
26903
26904 handleColumnMoving(_event, column) {
26905 this.resetRanges().setBounds(column);
26906 this.overlay.style.visibility = "hidden";
26907 }
26908
26909 handleColumnMoved(from, _to, _after) {
26910 this.activeRange.setBounds(from);
26911 this.layoutElement();
26912 }
26913
26914 handleColumnMouseDown(event, column) {
26915 if (event.button === 2 && (this.selecting === "column" || this.selecting === "all") && this.activeRange.occupiesColumn(column)) {
26916 return;
26917 }
26918
26919 //If columns are movable, allow dragging columns only if they are not
26920 //selected. Dragging selected columns should move the columns instead.
26921 if(this.table.options.movableColumns && this.selecting === "column" && this.activeRange.occupiesColumn(column)){
26922 return;
26923 }
26924
26925 this.mousedown = true;
26926
26927 document.addEventListener("mouseup", this.mouseUpEvent);
26928
26929 this.newSelection(event, column);
26930 }
26931
26932 handleColumnMouseMove(e, column) {
26933 if (column === this.rowHeader || !this.mousedown || this.selecting === 'all') {
26934 return;
26935 }
26936
26937 this.activeRange.setBounds(false, column, true);
26938 }
26939
26940 ///////////////////////////////////
26941 //////// Cell Functionality ///////
26942 ///////////////////////////////////
26943
26944 renderCell(cell) {
26945 var el = cell.getElement(),
26946 rangeIdx = this.ranges.findIndex((range) => range.occupies(cell));
26947
26948 el.classList.toggle("tabulator-range-selected", rangeIdx !== -1);
26949 el.classList.toggle("tabulator-range-only-cell-selected", this.ranges.length === 1 && this.ranges[0].atTopLeft(cell) && this.ranges[0].atBottomRight(cell));
26950
26951 el.dataset.range = rangeIdx;
26952 }
26953
26954 handleCellMouseDown(event, cell) {
26955 if (event.button === 2 && (this.activeRange.occupies(cell) || ((this.selecting === "row" || this.selecting === "all") && this.activeRange.occupiesRow(cell.row)))) {
26956 return;
26957 }
26958
26959 this.mousedown = true;
26960
26961 document.addEventListener("mouseup", this.mouseUpEvent);
26962
26963 this.newSelection(event, cell);
26964 }
26965
26966 handleCellMouseMove(e, cell) {
26967 if (!this.mousedown || this.selecting === "all") {
26968 return;
26969 }
26970
26971 this.activeRange.setBounds(false, cell, true);
26972 }
26973
26974 handleCellClick(e, cell){
26975 this.initializeFocus(cell);
26976 }
26977
26978 handleEditingCell(cell) {
26979 if(this.activeRange){
26980 this.activeRange.setBounds(cell);
26981 }
26982 }
26983
26984 finishEditingCell() {
26985 this.blockKeydown = true;
26986 this.table.rowManager.element.focus();
26987
26988 setTimeout(() => {
26989 this.blockKeydown = false;
26990 }, 10);
26991 }
26992
26993 ///////////////////////////////////
26994 /////// Navigation ///////
26995 ///////////////////////////////////
26996
26997 keyNavigate(dir, e){
26998 if(this.navigate(false, false, dir));
26999 e.preventDefault();
27000 }
27001
27002 keyNavigateRange(e, dir, jump, expand){
27003 if(this.navigate(jump, expand, dir));
27004 e.preventDefault();
27005 }
27006
27007 navigate(jump, expand, dir) {
27008 var moved = false,
27009 range, rangeEdge, prevRect, nextRow, nextCol, row, column,
27010 rowRect, rowManagerRect, columnRect, columnManagerRect;
27011
27012 // Don't navigate while editing
27013 if (this.table.modules.edit && this.table.modules.edit.currentCell) {
27014 return false;
27015 }
27016
27017 // If there are more than 1 range, use the active range and destroy the others
27018 if (this.ranges.length > 1) {
27019 this.ranges = this.ranges.filter((range) => {
27020 if (range === this.activeRange) {
27021 range.setEnd(range.start.row, range.start.col);
27022 return true;
27023 }
27024 range.destroy();
27025 return false;
27026 });
27027 }
27028
27029 range = this.activeRange;
27030 prevRect = {
27031 top: range.top,
27032 bottom: range.bottom,
27033 left: range.left,
27034 right: range.right
27035 };
27036
27037 rangeEdge = expand ? range.end : range.start;
27038 nextRow = rangeEdge.row;
27039 nextCol = rangeEdge.col;
27040
27041 if(jump){
27042 switch(dir){
27043 case "left":
27044 nextCol = this.findJumpCellLeft(range.start.row, rangeEdge.col);
27045 break;
27046 case "right":
27047 nextCol = this.findJumpCellRight(range.start.row, rangeEdge.col);
27048 break;
27049 case "up":
27050 nextRow = this.findJumpCellUp(rangeEdge.row, range.start.col);
27051 break;
27052 case "down":
27053 nextRow = this.findJumpCellDown(rangeEdge.row, range.start.col);
27054 break;
27055 }
27056 }else {
27057 if(expand){
27058 if ((this.selecting === 'row' && (dir === 'left' || dir === 'right')) || (this.selecting === 'column' && (dir === 'up' || dir === 'down'))) {
27059 return;
27060 }
27061 }
27062
27063 switch(dir){
27064 case "left":
27065 nextCol = Math.max(nextCol - 1, 0);
27066 break;
27067 case "right":
27068 nextCol = Math.min(nextCol + 1, this.getTableColumns().length - 1);
27069 break;
27070 case "up":
27071 nextRow = Math.max(nextRow - 1, 0);
27072 break;
27073 case "down":
27074 nextRow = Math.min(nextRow + 1, this.getTableRows().length - 1);
27075 break;
27076 }
27077 }
27078
27079 if(this.rowHeader && nextCol === 0) {
27080 nextCol = 1;
27081 }
27082
27083 if(!expand){
27084 range.setStart(nextRow, nextCol);
27085 }
27086
27087 range.setEnd(nextRow, nextCol);
27088
27089 if(!expand){
27090 this.selecting = "cell";
27091 }
27092
27093 moved = prevRect.top !== range.top || prevRect.bottom !== range.bottom || prevRect.left !== range.left || prevRect.right !== range.right;
27094
27095 if (moved) {
27096 row = this.getRowByRangePos(range.end.row);
27097 column = this.getColumnByRangePos(range.end.col);
27098 rowRect = row.getElement().getBoundingClientRect();
27099 columnRect = column.getElement().getBoundingClientRect();
27100 rowManagerRect = this.table.rowManager.getElement().getBoundingClientRect();
27101 columnManagerRect = this.table.columnManager.getElement().getBoundingClientRect();
27102
27103 if(!(rowRect.top >= rowManagerRect.top && rowRect.bottom <= rowManagerRect.bottom)){
27104 if(row.getElement().parentNode && column.getElement().parentNode){
27105 // Use faster autoScroll when the elements are on the DOM
27106 this.autoScroll(range, row.getElement(), column.getElement());
27107 }else {
27108 row.getComponent().scrollTo(undefined, false);
27109 }
27110 }
27111
27112 if(!(columnRect.left >= columnManagerRect.left + this.getRowHeaderWidth() && columnRect.right <= columnManagerRect.right)){
27113 if(row.getElement().parentNode && column.getElement().parentNode){
27114 // Use faster autoScroll when the elements are on the DOM
27115 this.autoScroll(range, row.getElement(), column.getElement());
27116 }else {
27117 column.getComponent().scrollTo(undefined, false);
27118 }
27119 }
27120
27121 this.layoutElement();
27122
27123 return true;
27124 }
27125 }
27126
27127 rangeRemoved(removed){
27128 this.ranges = this.ranges.filter((range) => range !== removed);
27129
27130 if(this.activeRange === removed){
27131 if(this.ranges.length){
27132 this.activeRange = this.ranges[this.ranges.length - 1];
27133 }else {
27134 this.addRange();
27135 }
27136 }
27137
27138 this.layoutElement();
27139 }
27140
27141 findJumpRow(column, rows, reverse, emptyStart, emptySide){
27142 if(reverse){
27143 rows = rows.reverse();
27144 }
27145
27146 return this.findJumpItem(emptyStart, emptySide, rows, function(row){return row.getData()[column.getField()];});
27147 }
27148
27149 findJumpCol(row, columns, reverse, emptyStart, emptySide){
27150 if(reverse){
27151 columns = columns.reverse();
27152 }
27153
27154 return this.findJumpItem(emptyStart, emptySide, columns, function(column){return row.getData()[column.getField()];});
27155 }
27156
27157 findJumpItem(emptyStart, emptySide, items, valueResolver){
27158 var nextItem;
27159
27160 for(let currentItem of items){
27161 let currentValue = valueResolver(currentItem);
27162
27163 if(emptyStart){
27164 nextItem = currentItem;
27165 if(currentValue){
27166 break;
27167 }
27168 }else {
27169 if(emptySide){
27170 nextItem = currentItem;
27171
27172 if(currentValue){
27173 break;
27174 }
27175 }else {
27176 if(currentValue){
27177 nextItem = currentItem;
27178 }else {
27179 break;
27180 }
27181 }
27182 }
27183 }
27184
27185 return nextItem;
27186 }
27187
27188 findJumpCellLeft(rowPos, colPos){
27189 var row = this.getRowByRangePos(rowPos),
27190 columns = this.getTableColumns(),
27191 isStartingCellEmpty = this.isEmpty(row.getData()[columns[colPos].getField()]),
27192 isLeftOfStartingCellEmpty = columns[colPos - 1] ? this.isEmpty(row.getData()[columns[colPos - 1].getField()]) : false,
27193 targetCols = this.rowHeader ? columns.slice(1, colPos) : columns.slice(0, colPos),
27194 jumpCol = this.findJumpCol(row, targetCols, true, isStartingCellEmpty, isLeftOfStartingCellEmpty);
27195
27196 if(jumpCol){
27197 return jumpCol.getPosition() - 1;
27198 }
27199
27200 return colPos;
27201 }
27202
27203 findJumpCellRight(rowPos, colPos){
27204 var row = this.getRowByRangePos(rowPos),
27205 columns = this.getTableColumns(),
27206 isStartingCellEmpty = this.isEmpty(row.getData()[columns[colPos].getField()]),
27207 isRightOfStartingCellEmpty = columns[colPos + 1] ? this.isEmpty(row.getData()[columns[colPos + 1].getField()]) : false,
27208 jumpCol = this.findJumpCol(row, columns.slice(colPos + 1, columns.length), false, isStartingCellEmpty, isRightOfStartingCellEmpty);
27209
27210 if(jumpCol){
27211 return jumpCol.getPosition() - 1;
27212 }
27213
27214 return colPos;
27215 }
27216
27217 findJumpCellUp(rowPos, colPos) {
27218 var column = this.getColumnByRangePos(colPos),
27219 rows = this.getTableRows(),
27220 isStartingCellEmpty = this.isEmpty(rows[rowPos].getData()[column.getField()]),
27221 isTopOfStartingCellEmpty = rows[rowPos - 1] ? this.isEmpty(rows[rowPos - 1].getData()[column.getField()]) : false,
27222 jumpRow = this.findJumpRow(column, rows.slice(0, rowPos), true, isStartingCellEmpty, isTopOfStartingCellEmpty);
27223
27224 if(jumpRow){
27225 return jumpRow.position - 1;
27226 }
27227
27228 return rowPos;
27229 }
27230
27231 findJumpCellDown(rowPos, colPos) {
27232 var column = this.getColumnByRangePos(colPos),
27233 rows = this.getTableRows(),
27234 isStartingCellEmpty = this.isEmpty(rows[rowPos].getData()[column.getField()]),
27235 isBottomOfStartingCellEmpty = rows[rowPos + 1] ? this.isEmpty(rows[rowPos + 1].getData()[column.getField()]) : false,
27236 jumpRow = this.findJumpRow(column, rows.slice(rowPos + 1, rows.length), false, isStartingCellEmpty, isBottomOfStartingCellEmpty);
27237
27238 if(jumpRow){
27239 return jumpRow.position - 1;
27240 }
27241
27242 return rowPos;
27243 }
27244
27245 ///////////////////////////////////
27246 /////// Selection ///////
27247 ///////////////////////////////////
27248 newSelection(event, element) {
27249 var range;
27250
27251 if (element.type === "column") {
27252 if(!this.columnSelection){
27253 return;
27254 }
27255
27256 if (element === this.rowHeader) {
27257 range = this.resetRanges();
27258 this.selecting = "all";
27259
27260 var topLeftCell, bottomRightCell = this.getCell(-1, -1);
27261
27262 if(this.rowHeader){
27263 topLeftCell = this.getCell(0, 1);
27264 }else {
27265 topLeftCell = this.getCell(0, 0);
27266 }
27267
27268 range.setBounds(topLeftCell, bottomRightCell);
27269 return;
27270 } else {
27271 this.selecting = "column";
27272 }
27273 } else if (element.column === this.rowHeader) {
27274 this.selecting = "row";
27275 } else {
27276 this.selecting = "cell";
27277 }
27278
27279 if (event.shiftKey) {
27280 this.activeRange.setBounds(false, element);
27281 } else if (event.ctrlKey) {
27282 this.addRange().setBounds(element);
27283 } else {
27284 this.resetRanges().setBounds(element);
27285 }
27286 }
27287
27288 autoScroll(range, row, column) {
27289 var tableHolder = this.table.rowManager.element,
27290 rect, view, withinHorizontalView, withinVerticalView;
27291
27292 if (typeof row === 'undefined') {
27293 row = this.getRowByRangePos(range.end.row).getElement();
27294 }
27295
27296 if (typeof column === 'undefined') {
27297 column = this.getColumnByRangePos(range.end.col).getElement();
27298 }
27299
27300 rect = {
27301 left: column.offsetLeft,
27302 right: column.offsetLeft + column.offsetWidth,
27303 top: row.offsetTop,
27304 bottom: row.offsetTop + row.offsetHeight,
27305 };
27306
27307 view = {
27308 left: tableHolder.scrollLeft + this.getRowHeaderWidth(),
27309 right: Math.ceil(tableHolder.scrollLeft + tableHolder.clientWidth),
27310 top: tableHolder.scrollTop,
27311 bottom: tableHolder.scrollTop + tableHolder.offsetHeight - this.table.rowManager.scrollbarWidth,
27312 };
27313
27314 withinHorizontalView = view.left < rect.left && rect.left < view.right && view.left < rect.right && rect.right < view.right;
27315
27316 withinVerticalView = view.top < rect.top && rect.top < view.bottom && view.top < rect.bottom && rect.bottom < view.bottom;
27317
27318 if (!withinHorizontalView) {
27319 if (rect.left < view.left) {
27320 tableHolder.scrollLeft = rect.left - this.getRowHeaderWidth();
27321 } else if (rect.right > view.right) {
27322 tableHolder.scrollLeft = Math.min(rect.right - tableHolder.clientWidth, rect.left - this.getRowHeaderWidth());
27323 }
27324 }
27325
27326 if (!withinVerticalView) {
27327 if (rect.top < view.top) {
27328 tableHolder.scrollTop = rect.top;
27329 } else if (rect.bottom > view.bottom) {
27330 tableHolder.scrollTop = rect.bottom - tableHolder.clientHeight;
27331 }
27332 }
27333 }
27334
27335
27336 ///////////////////////////////////
27337 /////// Layout ///////
27338 ///////////////////////////////////
27339
27340 layoutChange(){
27341 this.overlay.style.visibility = "hidden";
27342 clearTimeout(this.layoutChangeTimeout);
27343 this.layoutChangeTimeout = setTimeout(this.layoutRanges.bind(this), 200);
27344 }
27345
27346 redraw(force) {
27347 if (force) {
27348 this.selecting = 'cell';
27349 this.resetRanges();
27350 this.layoutElement();
27351 }
27352 }
27353
27354 layoutElement(visibleRows) {
27355 var rows;
27356
27357 if (visibleRows) {
27358 rows = this.table.rowManager.getVisibleRows(true);
27359 } else {
27360 rows = this.table.rowManager.getRows();
27361 }
27362
27363 rows.forEach((row) => {
27364 if (row.type === "row") {
27365 this.layoutRow(row);
27366 row.cells.forEach((cell) => this.renderCell(cell));
27367 }
27368 });
27369
27370 this.getTableColumns().forEach((column) => {
27371 this.layoutColumn(column);
27372 });
27373
27374 this.layoutRanges();
27375 }
27376
27377 layoutRow(row) {
27378 var el = row.getElement(),
27379 selected = false,
27380 occupied = this.ranges.some((range) => range.occupiesRow(row));
27381
27382 if (this.selecting === "row") {
27383 selected = occupied;
27384 } else if (this.selecting === "all") {
27385 selected = true;
27386 }
27387
27388 el.classList.toggle("tabulator-range-selected", selected);
27389 el.classList.toggle("tabulator-range-highlight", occupied);
27390 }
27391
27392 layoutColumn(column) {
27393 var el = column.getElement(),
27394 selected = false,
27395 occupied = this.ranges.some((range) => range.occupiesColumn(column));
27396
27397 if (this.selecting === "column") {
27398 selected = occupied;
27399 } else if (this.selecting === "all") {
27400 selected = true;
27401 }
27402
27403 el.classList.toggle("tabulator-range-selected", selected);
27404 el.classList.toggle("tabulator-range-highlight", occupied);
27405 }
27406
27407 layoutRanges() {
27408 var activeCell, activeCellEl, activeRowEl;
27409
27410 if (!this.table.initialized) {
27411 return;
27412 }
27413
27414 activeCell = this.getActiveCell();
27415
27416 if (!activeCell) {
27417 return;
27418 }
27419
27420 activeCellEl = activeCell.getElement();
27421 activeRowEl = activeCell.row.getElement();
27422
27423 if(this.table.rtl){
27424 this.activeRangeCellElement.style.right = activeRowEl.offsetWidth - activeCellEl.offsetLeft - activeCellEl.offsetWidth + "px";
27425 }else {
27426 this.activeRangeCellElement.style.left = activeRowEl.offsetLeft + activeCellEl.offsetLeft + "px";
27427 }
27428
27429 this.activeRangeCellElement.style.top = activeRowEl.offsetTop + "px";
27430 this.activeRangeCellElement.style.width = activeCellEl.offsetWidth + "px";
27431 this.activeRangeCellElement.style.height = activeRowEl.offsetHeight + "px";
27432
27433 this.ranges.forEach((range) => range.layout());
27434
27435 this.overlay.style.visibility = "visible";
27436 }
27437
27438
27439 ///////////////////////////////////
27440 /////// Helper Functions ///////
27441 ///////////////////////////////////
27442
27443 getCell(rowIdx, colIdx) {
27444 var row;
27445
27446 if (colIdx < 0) {
27447 colIdx = this.getTableColumns().length + colIdx;
27448 if (colIdx < 0) {
27449 return null;
27450 }
27451 }
27452
27453 if (rowIdx < 0) {
27454 rowIdx = this.getTableRows().length + rowIdx;
27455 }
27456
27457 row = this.table.rowManager.getRowFromPosition(rowIdx + 1);
27458
27459 return row ? row.getCells(false, true).filter((cell) => cell.column.visible)[colIdx] : null;
27460 }
27461
27462
27463 getActiveCell() {
27464 return this.getCell(this.activeRange.start.row, this.activeRange.start.col);
27465 }
27466
27467 getRowByRangePos(pos) {
27468 return this.getTableRows()[pos];
27469 }
27470
27471 getColumnByRangePos(pos) {
27472 return this.getTableColumns()[pos];
27473 }
27474
27475 getTableRows() {
27476 return this.table.rowManager.getDisplayRows().filter(row=> row.type === "row");
27477 }
27478
27479 getTableColumns() {
27480 return this.table.columnManager.getVisibleColumnsByIndex();
27481 }
27482
27483 addRange(start, end) {
27484 var range;
27485
27486 if(this.maxRanges !== true && this.ranges.length >= this.maxRanges){
27487 this.ranges.shift().destroy();
27488 }
27489
27490 range = new Range(this.table, this, start, end);
27491
27492 this.activeRange = range;
27493 this.ranges.push(range);
27494 this.rangeContainer.appendChild(range.element);
27495
27496 return range;
27497 }
27498
27499 resetRanges() {
27500 var range, cell, visibleCells;
27501
27502 this.ranges.forEach((range) => range.destroy());
27503 this.ranges = [];
27504
27505 range = this.addRange();
27506
27507 if(this.table.rowManager.activeRows.length){
27508 visibleCells = this.table.rowManager.activeRows[0].cells.filter((cell) => cell.column.visible);
27509 cell = visibleCells[this.rowHeader ? 1 : 0];
27510
27511 if(cell){
27512 range.setBounds(cell);
27513 if(this.options("selectableRangeAutoFocus")){
27514 this.initializeFocus(cell);
27515 }
27516 }
27517 }
27518
27519 return range;
27520 }
27521
27522 tableDestroyed(){
27523 document.removeEventListener("mouseup", this.mouseUpEvent);
27524 this.table.rowManager.element.removeEventListener("keydown", this.keyDownEvent);
27525 }
27526
27527 selectedRows(component) {
27528 return component ? this.activeRange.getRows().map((row) => row.getComponent()) : this.activeRange.getRows();
27529 }
27530
27531 selectedColumns(component) {
27532 return component ? this.activeRange.getColumns().map((col) => col.getComponent()) : this.activeRange.getColumns();
27533 }
27534
27535 getRowHeaderWidth(){
27536 if(!this.rowHeader){
27537 return 0;
27538 }
27539 return this.rowHeader.getElement().offsetWidth;
27540 }
27541
27542 isEmpty(value) {
27543 return value === null || value === undefined || value === "";
27544 }
27545 }
27546
27547 //sort numbers
27548 function number(a, b, aRow, bRow, column, dir, params){
27549 var alignEmptyValues = params.alignEmptyValues;
27550 var decimal = params.decimalSeparator;
27551 var thousand = params.thousandSeparator;
27552 var emptyAlign = 0;
27553
27554 a = String(a);
27555 b = String(b);
27556
27557 if(thousand){
27558 a = a.split(thousand).join("");
27559 b = b.split(thousand).join("");
27560 }
27561
27562 if(decimal){
27563 a = a.split(decimal).join(".");
27564 b = b.split(decimal).join(".");
27565 }
27566
27567 a = parseFloat(a);
27568 b = parseFloat(b);
27569
27570 //handle non numeric values
27571 if(isNaN(a)){
27572 emptyAlign = isNaN(b) ? 0 : -1;
27573 }else if(isNaN(b)){
27574 emptyAlign = 1;
27575 }else {
27576 //compare valid values
27577 return a - b;
27578 }
27579
27580 //fix empty values in position
27581 if((alignEmptyValues === "top" && dir === "desc") || (alignEmptyValues === "bottom" && dir === "asc")){
27582 emptyAlign *= -1;
27583 }
27584
27585 return emptyAlign;
27586 }
27587
27588 //sort strings
27589 function string(a, b, aRow, bRow, column, dir, params){
27590 var alignEmptyValues = params.alignEmptyValues;
27591 var emptyAlign = 0;
27592 var locale;
27593
27594 //handle empty values
27595 if(!a){
27596 emptyAlign = !b ? 0 : -1;
27597 }else if(!b){
27598 emptyAlign = 1;
27599 }else {
27600 //compare valid values
27601 switch(typeof params.locale){
27602 case "boolean":
27603 if(params.locale){
27604 locale = this.langLocale();
27605 }
27606 break;
27607 case "string":
27608 locale = params.locale;
27609 break;
27610 }
27611
27612 return String(a).toLowerCase().localeCompare(String(b).toLowerCase(), locale);
27613 }
27614
27615 //fix empty values in position
27616 if((alignEmptyValues === "top" && dir === "desc") || (alignEmptyValues === "bottom" && dir === "asc")){
27617 emptyAlign *= -1;
27618 }
27619
27620 return emptyAlign;
27621 }
27622
27623 //sort datetime
27624 function datetime(a, b, aRow, bRow, column, dir, params){
27625 var DT = this.table.dependencyRegistry.lookup(["luxon", "DateTime"], "DateTime");
27626 var format = params.format || "dd/MM/yyyy HH:mm:ss",
27627 alignEmptyValues = params.alignEmptyValues,
27628 emptyAlign = 0;
27629
27630 if(typeof DT != "undefined"){
27631 if(!DT.isDateTime(a)){
27632 if(format === "iso"){
27633 a = DT.fromISO(String(a));
27634 }else {
27635 a = DT.fromFormat(String(a), format);
27636 }
27637 }
27638
27639 if(!DT.isDateTime(b)){
27640 if(format === "iso"){
27641 b = DT.fromISO(String(b));
27642 }else {
27643 b = DT.fromFormat(String(b), format);
27644 }
27645 }
27646
27647 if(!a.isValid){
27648 emptyAlign = !b.isValid ? 0 : -1;
27649 }else if(!b.isValid){
27650 emptyAlign = 1;
27651 }else {
27652 //compare valid values
27653 return a - b;
27654 }
27655
27656 //fix empty values in position
27657 if((alignEmptyValues === "top" && dir === "desc") || (alignEmptyValues === "bottom" && dir === "asc")){
27658 emptyAlign *= -1;
27659 }
27660
27661 return emptyAlign;
27662
27663 }else {
27664 console.error("Sort Error - 'datetime' sorter is dependant on luxon.js");
27665 }
27666 }
27667
27668 //sort date
27669 function date(a, b, aRow, bRow, column, dir, params){
27670 if(!params.format){
27671 params.format = "dd/MM/yyyy";
27672 }
27673
27674 return datetime.call(this, a, b, aRow, bRow, column, dir, params);
27675 }
27676
27677 //sort times
27678 function time(a, b, aRow, bRow, column, dir, params){
27679 if(!params.format){
27680 params.format = "HH:mm";
27681 }
27682
27683 return datetime.call(this, a, b, aRow, bRow, column, dir, params);
27684 }
27685
27686 //sort booleans
27687 function boolean(a, b, aRow, bRow, column, dir, params){
27688 var el1 = a === true || a === "true" || a === "True" || a === 1 ? 1 : 0;
27689 var el2 = b === true || b === "true" || b === "True" || b === 1 ? 1 : 0;
27690
27691 return el1 - el2;
27692 }
27693
27694 //sort if element contains any data
27695 function array(a, b, aRow, bRow, column, dir, params){
27696 var type = params.type || "length",
27697 alignEmptyValues = params.alignEmptyValues,
27698 emptyAlign = 0,
27699 table = this.table,
27700 valueMap;
27701
27702 if(params.valueMap){
27703 if(typeof params.valueMap === "string"){
27704 valueMap = function(value){
27705 return value.map((item) => {
27706 return Helpers.retrieveNestedData(table.options.nestedFieldSeparator, params.valueMap, item);
27707 });
27708 };
27709 }else {
27710 valueMap = params.valueMap;
27711 }
27712 }
27713
27714 function calc(value){
27715 var result;
27716
27717 if(valueMap){
27718 value = valueMap(value);
27719 }
27720
27721 switch(type){
27722 case "length":
27723 result = value.length;
27724 break;
27725
27726 case "sum":
27727 result = value.reduce(function(c, d){
27728 return c + d;
27729 });
27730 break;
27731
27732 case "max":
27733 result = Math.max.apply(null, value) ;
27734 break;
27735
27736 case "min":
27737 result = Math.min.apply(null, value) ;
27738 break;
27739
27740 case "avg":
27741 result = value.reduce(function(c, d){
27742 return c + d;
27743 }) / value.length;
27744 break;
27745
27746 case "string":
27747 result = value.join("");
27748 break;
27749 }
27750
27751 return result;
27752 }
27753
27754 //handle non array values
27755 if(!Array.isArray(a)){
27756 emptyAlign = !Array.isArray(b) ? 0 : -1;
27757 }else if(!Array.isArray(b)){
27758 emptyAlign = 1;
27759 }else {
27760 if(type === "string"){
27761 return String(calc(a)).toLowerCase().localeCompare(String(calc(b)).toLowerCase());
27762 }else {
27763 return calc(b) - calc(a);
27764 }
27765 }
27766
27767 //fix empty values in position
27768 if((alignEmptyValues === "top" && dir === "desc") || (alignEmptyValues === "bottom" && dir === "asc")){
27769 emptyAlign *= -1;
27770 }
27771
27772 return emptyAlign;
27773 }
27774
27775 //sort if element contains any data
27776 function exists(a, b, aRow, bRow, column, dir, params){
27777 var el1 = typeof a == "undefined" ? 0 : 1;
27778 var el2 = typeof b == "undefined" ? 0 : 1;
27779
27780 return el1 - el2;
27781 }
27782
27783 //sort alpha numeric strings
27784 function alphanum(as, bs, aRow, bRow, column, dir, params){
27785 var a, b, a1, b1, i= 0, L, rx = /(\d+)|(\D+)/g, rd = /\d/;
27786 var alignEmptyValues = params.alignEmptyValues;
27787 var emptyAlign = 0;
27788
27789 //handle empty values
27790 if(!as && as!== 0){
27791 emptyAlign = !bs && bs!== 0 ? 0 : -1;
27792 }else if(!bs && bs!== 0){
27793 emptyAlign = 1;
27794 }else {
27795
27796 if(isFinite(as) && isFinite(bs)) return as - bs;
27797 a = String(as).toLowerCase();
27798 b = String(bs).toLowerCase();
27799 if(a === b) return 0;
27800 if(!(rd.test(a) && rd.test(b))) return a > b ? 1 : -1;
27801 a = a.match(rx);
27802 b = b.match(rx);
27803 L = a.length > b.length ? b.length : a.length;
27804 while(i < L){
27805 a1= a[i];
27806 b1= b[i++];
27807 if(a1 !== b1){
27808 if(isFinite(a1) && isFinite(b1)){
27809 if(a1.charAt(0) === "0") a1 = "." + a1;
27810 if(b1.charAt(0) === "0") b1 = "." + b1;
27811 return a1 - b1;
27812 }
27813 else return a1 > b1 ? 1 : -1;
27814 }
27815 }
27816
27817 return a.length > b.length;
27818 }
27819
27820 //fix empty values in position
27821 if((alignEmptyValues === "top" && dir === "desc") || (alignEmptyValues === "bottom" && dir === "asc")){
27822 emptyAlign *= -1;
27823 }
27824
27825 return emptyAlign;
27826 }
27827
27828 var defaultSorters = {
27829 number:number,
27830 string:string,
27831 date:date,
27832 time:time,
27833 datetime:datetime,
27834 boolean:boolean,
27835 array:array,
27836 exists:exists,
27837 alphanum:alphanum
27838 };
27839
27840 class Sort extends Module{
27841
27842 static moduleName = "sort";
27843
27844 //load defaults
27845 static sorters = defaultSorters;
27846
27847 constructor(table){
27848 super(table);
27849
27850 this.sortList = []; //holder current sort
27851 this.changed = false; //has the sort changed since last render
27852
27853 this.registerTableOption("sortMode", "local"); //local or remote sorting
27854
27855 this.registerTableOption("initialSort", false); //initial sorting criteria
27856 this.registerTableOption("columnHeaderSortMulti", true); //multiple or single column sorting
27857 this.registerTableOption("sortOrderReverse", false); //reverse internal sort ordering
27858 this.registerTableOption("headerSortElement", "<div class='tabulator-arrow'></div>"); //header sort element
27859 this.registerTableOption("headerSortClickElement", "header"); //element which triggers sort when clicked
27860
27861 this.registerColumnOption("sorter");
27862 this.registerColumnOption("sorterParams");
27863
27864 this.registerColumnOption("headerSort", true);
27865 this.registerColumnOption("headerSortStartingDir");
27866 this.registerColumnOption("headerSortTristate");
27867
27868 }
27869
27870 initialize(){
27871 this.subscribe("column-layout", this.initializeColumn.bind(this));
27872 this.subscribe("table-built", this.tableBuilt.bind(this));
27873 this.registerDataHandler(this.sort.bind(this), 20);
27874
27875 this.registerTableFunction("setSort", this.userSetSort.bind(this));
27876 this.registerTableFunction("getSorters", this.getSort.bind(this));
27877 this.registerTableFunction("clearSort", this.clearSort.bind(this));
27878
27879 if(this.table.options.sortMode === "remote"){
27880 this.subscribe("data-params", this.remoteSortParams.bind(this));
27881 }
27882 }
27883
27884 tableBuilt(){
27885 if(this.table.options.initialSort){
27886 this.setSort(this.table.options.initialSort);
27887 }
27888 }
27889
27890 remoteSortParams(data, config, silent, params){
27891 var sorters = this.getSort();
27892
27893 sorters.forEach((item) => {
27894 delete item.column;
27895 });
27896
27897 params.sort = sorters;
27898
27899 return params;
27900 }
27901
27902
27903 ///////////////////////////////////
27904 ///////// Table Functions /////////
27905 ///////////////////////////////////
27906
27907 userSetSort(sortList, dir){
27908 this.setSort(sortList, dir);
27909 // this.table.rowManager.sorterRefresh();
27910 this.refreshSort();
27911 }
27912
27913 clearSort(){
27914 this.clear();
27915 // this.table.rowManager.sorterRefresh();
27916 this.refreshSort();
27917 }
27918
27919
27920 ///////////////////////////////////
27921 ///////// Internal Logic //////////
27922 ///////////////////////////////////
27923
27924 //initialize column header for sorting
27925 initializeColumn(column){
27926 var sorter = false,
27927 colEl,
27928 arrowEl;
27929
27930 switch(typeof column.definition.sorter){
27931 case "string":
27932 if(Sort.sorters[column.definition.sorter]){
27933 sorter = Sort.sorters[column.definition.sorter];
27934 }else {
27935 console.warn("Sort Error - No such sorter found: ", column.definition.sorter);
27936 }
27937 break;
27938
27939 case "function":
27940 sorter = column.definition.sorter;
27941 break;
27942 }
27943
27944 column.modules.sort = {
27945 sorter:sorter, dir:"none",
27946 params:column.definition.sorterParams || {},
27947 startingDir:column.definition.headerSortStartingDir || "asc",
27948 tristate: column.definition.headerSortTristate,
27949 };
27950
27951 if(column.definition.headerSort !== false){
27952
27953 colEl = column.getElement();
27954
27955 colEl.classList.add("tabulator-sortable");
27956
27957 arrowEl = document.createElement("div");
27958 arrowEl.classList.add("tabulator-col-sorter");
27959
27960 switch(this.table.options.headerSortClickElement){
27961 case "icon":
27962 arrowEl.classList.add("tabulator-col-sorter-element");
27963 break;
27964 case "header":
27965 colEl.classList.add("tabulator-col-sorter-element");
27966 break;
27967 default:
27968 colEl.classList.add("tabulator-col-sorter-element");
27969 break;
27970 }
27971
27972 switch(this.table.options.headerSortElement){
27973 case "function":
27974 //do nothing
27975 break;
27976
27977 case "object":
27978 arrowEl.appendChild(this.table.options.headerSortElement);
27979 break;
27980
27981 default:
27982 arrowEl.innerHTML = this.table.options.headerSortElement;
27983 }
27984
27985 //create sorter arrow
27986 column.titleHolderElement.appendChild(arrowEl);
27987
27988 column.modules.sort.element = arrowEl;
27989
27990 this.setColumnHeaderSortIcon(column, "none");
27991
27992 if(this.table.options.headerSortClickElement === "icon"){
27993 arrowEl.addEventListener("mousedown", (e) => {
27994 e.stopPropagation();
27995 });
27996 }
27997
27998 //sort on click
27999 (this.table.options.headerSortClickElement === "icon" ? arrowEl : colEl).addEventListener("click", (e) => {
28000 var dir = "",
28001 sorters=[],
28002 match = false;
28003
28004 if(column.modules.sort){
28005 if(column.modules.sort.tristate){
28006 if(column.modules.sort.dir == "none"){
28007 dir = column.modules.sort.startingDir;
28008 }else {
28009 if(column.modules.sort.dir == column.modules.sort.startingDir){
28010 dir = column.modules.sort.dir == "asc" ? "desc" : "asc";
28011 }else {
28012 dir = "none";
28013 }
28014 }
28015 }else {
28016 switch(column.modules.sort.dir){
28017 case "asc":
28018 dir = "desc";
28019 break;
28020
28021 case "desc":
28022 dir = "asc";
28023 break;
28024
28025 default:
28026 dir = column.modules.sort.startingDir;
28027 }
28028 }
28029
28030 if (this.table.options.columnHeaderSortMulti && (e.shiftKey || e.ctrlKey)) {
28031 sorters = this.getSort();
28032
28033 match = sorters.findIndex((sorter) => {
28034 return sorter.field === column.getField();
28035 });
28036
28037 if(match > -1){
28038 sorters[match].dir = dir;
28039
28040 match = sorters.splice(match, 1)[0];
28041 if(dir != "none"){
28042 sorters.push(match);
28043 }
28044 }else {
28045 if(dir != "none"){
28046 sorters.push({column:column, dir:dir});
28047 }
28048 }
28049
28050 //add to existing sort
28051 this.setSort(sorters);
28052 }else {
28053 if(dir == "none"){
28054 this.clear();
28055 }else {
28056 //sort by column only
28057 this.setSort(column, dir);
28058 }
28059
28060 }
28061
28062 // this.table.rowManager.sorterRefresh(!this.sortList.length);
28063 this.refreshSort();
28064 }
28065 });
28066 }
28067 }
28068
28069 refreshSort(){
28070 if(this.table.options.sortMode === "remote"){
28071 this.reloadData(null, false, false);
28072 }else {
28073 this.refreshData(true);
28074 }
28075
28076 //TODO - Persist left position of row manager
28077 // left = this.scrollLeft;
28078 // this.scrollHorizontal(left);
28079 }
28080
28081 //check if the sorters have changed since last use
28082 hasChanged(){
28083 var changed = this.changed;
28084 this.changed = false;
28085 return changed;
28086 }
28087
28088 //return current sorters
28089 getSort(){
28090 var self = this,
28091 sorters = [];
28092
28093 self.sortList.forEach(function(item){
28094 if(item.column){
28095 sorters.push({column:item.column.getComponent(), field:item.column.getField(), dir:item.dir});
28096 }
28097 });
28098
28099 return sorters;
28100 }
28101
28102 //change sort list and trigger sort
28103 setSort(sortList, dir){
28104 var self = this,
28105 newSortList = [];
28106
28107 if(!Array.isArray(sortList)){
28108 sortList = [{column: sortList, dir:dir}];
28109 }
28110
28111 sortList.forEach(function(item){
28112 var column;
28113
28114 column = self.table.columnManager.findColumn(item.column);
28115
28116 if(column){
28117 item.column = column;
28118 newSortList.push(item);
28119 self.changed = true;
28120 }else {
28121 console.warn("Sort Warning - Sort field does not exist and is being ignored: ", item.column);
28122 }
28123
28124 });
28125
28126 self.sortList = newSortList;
28127
28128 this.dispatch("sort-changed");
28129 }
28130
28131 //clear sorters
28132 clear(){
28133 this.setSort([]);
28134 }
28135
28136 //find appropriate sorter for column
28137 findSorter(column){
28138 var row = this.table.rowManager.activeRows[0],
28139 sorter = "string",
28140 field, value;
28141
28142 if(row){
28143 row = row.getData();
28144 field = column.getField();
28145
28146 if(field){
28147
28148 value = column.getFieldValue(row);
28149
28150 switch(typeof value){
28151 case "undefined":
28152 sorter = "string";
28153 break;
28154
28155 case "boolean":
28156 sorter = "boolean";
28157 break;
28158
28159 default:
28160 if(!isNaN(value) && value !== ""){
28161 sorter = "number";
28162 }else {
28163 if(value.match(/((^[0-9]+[a-z]+)|(^[a-z]+[0-9]+))+$/i)){
28164 sorter = "alphanum";
28165 }
28166 }
28167 break;
28168 }
28169 }
28170 }
28171
28172 return Sort.sorters[sorter];
28173 }
28174
28175 //work through sort list sorting data
28176 sort(data, sortOnly){
28177 var self = this,
28178 sortList = this.table.options.sortOrderReverse ? self.sortList.slice().reverse() : self.sortList,
28179 sortListActual = [],
28180 rowComponents = [];
28181
28182 if(this.subscribedExternal("dataSorting")){
28183 this.dispatchExternal("dataSorting", self.getSort());
28184 }
28185
28186 if(!sortOnly) {
28187 self.clearColumnHeaders();
28188 }
28189
28190 if(this.table.options.sortMode !== "remote"){
28191
28192 //build list of valid sorters and trigger column specific callbacks before sort begins
28193 sortList.forEach(function(item, i){
28194 var sortObj;
28195
28196 if(item.column){
28197 sortObj = item.column.modules.sort;
28198
28199 if(sortObj){
28200
28201 //if no sorter has been defined, take a guess
28202 if(!sortObj.sorter){
28203 sortObj.sorter = self.findSorter(item.column);
28204 }
28205
28206 item.params = typeof sortObj.params === "function" ? sortObj.params(item.column.getComponent(), item.dir) : sortObj.params;
28207
28208 sortListActual.push(item);
28209 }
28210
28211 if(!sortOnly) {
28212 self.setColumnHeader(item.column, item.dir);
28213 }
28214 }
28215 });
28216
28217 //sort data
28218 if (sortListActual.length) {
28219 self._sortItems(data, sortListActual);
28220 }
28221
28222 }else if(!sortOnly) {
28223 sortList.forEach(function(item, i){
28224 self.setColumnHeader(item.column, item.dir);
28225 });
28226 }
28227
28228
28229 if(this.subscribedExternal("dataSorted")){
28230 data.forEach((row) => {
28231 rowComponents.push(row.getComponent());
28232 });
28233
28234 this.dispatchExternal("dataSorted", self.getSort(), rowComponents);
28235 }
28236
28237 return data;
28238 }
28239
28240 //clear sort arrows on columns
28241 clearColumnHeaders(){
28242 this.table.columnManager.getRealColumns().forEach((column) => {
28243 if(column.modules.sort){
28244 column.modules.sort.dir = "none";
28245 column.getElement().setAttribute("aria-sort", "none");
28246 this.setColumnHeaderSortIcon(column, "none");
28247 }
28248 });
28249 }
28250
28251 //set the column header sort direction
28252 setColumnHeader(column, dir){
28253 column.modules.sort.dir = dir;
28254 column.getElement().setAttribute("aria-sort", dir === "asc" ? "ascending" : "descending");
28255 this.setColumnHeaderSortIcon(column, dir);
28256 }
28257
28258 setColumnHeaderSortIcon(column, dir){
28259 var sortEl = column.modules.sort.element,
28260 arrowEl;
28261
28262 if(column.definition.headerSort && typeof this.table.options.headerSortElement === "function"){
28263 while(sortEl.firstChild) sortEl.removeChild(sortEl.firstChild);
28264
28265 arrowEl = this.table.options.headerSortElement.call(this.table, column.getComponent(), dir);
28266
28267 if(typeof arrowEl === "object"){
28268 sortEl.appendChild(arrowEl);
28269 }else {
28270 sortEl.innerHTML = arrowEl;
28271 }
28272 }
28273 }
28274
28275 //sort each item in sort list
28276 _sortItems(data, sortList){
28277 var sorterCount = sortList.length - 1;
28278
28279 data.sort((a, b) => {
28280 var result;
28281
28282 for(var i = sorterCount; i>= 0; i--){
28283 let sortItem = sortList[i];
28284
28285 result = this._sortRow(a, b, sortItem.column, sortItem.dir, sortItem.params);
28286
28287 if(result !== 0){
28288 break;
28289 }
28290 }
28291
28292 return result;
28293 });
28294 }
28295
28296 //process individual rows for a sort function on active data
28297 _sortRow(a, b, column, dir, params){
28298 var el1Comp, el2Comp;
28299
28300 //switch elements depending on search direction
28301 var el1 = dir == "asc" ? a : b;
28302 var el2 = dir == "asc" ? b : a;
28303
28304 a = column.getFieldValue(el1.getData());
28305 b = column.getFieldValue(el2.getData());
28306
28307 a = typeof a !== "undefined" ? a : "";
28308 b = typeof b !== "undefined" ? b : "";
28309
28310 el1Comp = el1.getComponent();
28311 el2Comp = el2.getComponent();
28312
28313 return column.modules.sort.sorter.call(this, a, b, el1Comp, el2Comp, column.getComponent(), dir, params);
28314 }
28315 }
28316
28317 class GridCalculator{
28318 constructor(columns, rows){
28319 this.columnCount = columns;
28320 this.rowCount = rows;
28321
28322 this.columnString = [];
28323 this.columns = [];
28324 this.rows = [];
28325 }
28326
28327 genColumns(data){
28328 var colCount = Math.max(this.columnCount, Math.max(...data.map(item => item.length)));
28329
28330 this.columnString = [];
28331 this.columns = [];
28332
28333 for(let i = 1; i <= colCount; i++){
28334 this.incrementChar(this.columnString.length - 1);
28335 this.columns.push(this.columnString.join(""));
28336 }
28337
28338 return this.columns;
28339 }
28340
28341 genRows(data){
28342 var rowCount = Math.max(this.rowCount, data.length);
28343
28344 this.rows = [];
28345
28346 for(let i = 1; i <= rowCount; i++){
28347 this.rows.push(i);
28348 }
28349
28350 return this.rows;
28351 }
28352
28353 incrementChar(i){
28354 let char = this.columnString[i];
28355
28356 if(char){
28357 if(char !== "Z"){
28358 this.columnString[i] = String.fromCharCode(this.columnString[i].charCodeAt(0) + 1);
28359 }else {
28360 this.columnString[i] = "A";
28361
28362 if(i){
28363 this.incrementChar(i-1);
28364 }else {
28365 this.columnString.push("A");
28366 }
28367 }
28368 }else {
28369 this.columnString.push("A");
28370 }
28371 }
28372
28373 setRowCount(count){
28374 this.rowCount = count;
28375 }
28376
28377 setColumnCount(count){
28378 this.columnCount = count;
28379 }
28380 }
28381
28382 class SheetComponent {
28383 constructor(sheet) {
28384 this._sheet = sheet;
28385
28386 return new Proxy(this, {
28387 get: function (target, name, receiver) {
28388 if (typeof target[name] !== "undefined") {
28389 return target[name];
28390 } else {
28391 return target._sheet.table.componentFunctionBinder.handle("sheet", target._sheet, name);
28392 }
28393 },
28394 });
28395 }
28396
28397 getTitle(){
28398 return this._sheet.title;
28399 }
28400
28401 getKey(){
28402 return this._sheet.key;
28403 }
28404
28405 getDefinition(){
28406 return this._sheet.getDefinition();
28407 }
28408
28409 getData() {
28410 return this._sheet.getData();
28411 }
28412
28413 setData(data) {
28414 return this._sheet.setData(data);
28415 }
28416
28417 clear(){
28418 return this._sheet.clear();
28419 }
28420
28421 remove(){
28422 return this._sheet.remove();
28423 }
28424
28425 active(){
28426 return this._sheet.active();
28427 }
28428
28429 setTitle(title){
28430 return this._sheet.setTitle(title);
28431 }
28432
28433 setRows(rows){
28434 return this._sheet.setRows(rows);
28435 }
28436
28437 setColumns(columns){
28438 return this._sheet.setColumns(columns);
28439 }
28440 }
28441
28442 class Sheet extends CoreFeature{
28443 constructor(spreadsheetManager, definition) {
28444 super(spreadsheetManager.table);
28445
28446 this.spreadsheetManager = spreadsheetManager;
28447 this.definition = definition;
28448
28449 this.title = this.definition.title || "";
28450 this.key = this.definition.key || this.definition.title;
28451 this.rowCount = this.definition.rows;
28452 this.columnCount = this.definition.columns;
28453 this.data = this.definition.data || [];
28454 this.element = null;
28455 this.isActive = false;
28456
28457 this.grid = new GridCalculator(this.columnCount, this.rowCount);
28458
28459 this.defaultColumnDefinition = {width:100, headerHozAlign:"center", headerSort:false};
28460 this.columnDefinition = Object.assign(this.defaultColumnDefinition, this.options("spreadsheetColumnDefinition"));
28461
28462 this.columnDefs = [];
28463 this.rowDefs = [];
28464 this.columnFields = [];
28465 this.columns = [];
28466 this.rows = [];
28467
28468 this.scrollTop = null;
28469 this.scrollLeft = null;
28470
28471 this.initialize();
28472
28473 this.dispatchExternal("sheetAdded", this.getComponent());
28474 }
28475
28476 ///////////////////////////////////
28477 ///////// Initialization //////////
28478 ///////////////////////////////////
28479
28480 initialize(){
28481 this.initializeElement();
28482 this.initializeColumns();
28483 this.initializeRows();
28484 }
28485
28486 reinitialize(){
28487 this.initializeColumns();
28488 this.initializeRows();
28489 }
28490
28491 initializeElement(){
28492 this.element = document.createElement("div");
28493 this.element.classList.add("tabulator-spreadsheet-tab");
28494 this.element.innerText = this.title;
28495
28496 this.element.addEventListener("click", () => {
28497 this.spreadsheetManager.loadSheet(this);
28498 });
28499 }
28500
28501 initializeColumns(){
28502 this.grid.setColumnCount(this.columnCount);
28503 this.columnFields = this.grid.genColumns(this.data);
28504
28505 this.columnDefs = [];
28506
28507 this.columnFields.forEach((ref) => {
28508 var def = Object.assign({}, this.columnDefinition);
28509 def.field = ref;
28510 def.title = ref;
28511
28512 this.columnDefs.push(def);
28513 });
28514 }
28515
28516 initializeRows(){
28517 var refs;
28518
28519 this.grid.setRowCount(this.rowCount);
28520
28521 refs = this.grid.genRows(this.data);
28522
28523 this.rowDefs = [];
28524
28525 refs.forEach((ref, i) => {
28526 var def = {"_id":ref};
28527 var data = this.data[i];
28528
28529 if(data){
28530 data.forEach((val, j) => {
28531 var field = this.columnFields[j];
28532
28533 if(field){
28534 def[field] = val;
28535 }
28536 });
28537 }
28538
28539 this.rowDefs.push(def);
28540 });
28541 }
28542
28543 unload(){
28544 this.isActive = false;
28545 this.scrollTop = this.table.rowManager.scrollTop;
28546 this.scrollLeft = this.table.rowManager.scrollLeft;
28547 this.data = this.getData(true);
28548 this.element.classList.remove("tabulator-spreadsheet-tab-active");
28549 }
28550
28551 load(){
28552
28553 var wasInactive = !this.isActive;
28554
28555 this.isActive = true;
28556 this.table.blockRedraw();
28557 this.table.setData([]);
28558 this.table.setColumns(this.columnDefs);
28559 this.table.setData(this.rowDefs);
28560 this.table.restoreRedraw();
28561
28562 if(wasInactive && this.scrollTop !== null){
28563 this.table.rowManager.element.scrollLeft = this.scrollLeft;
28564 this.table.rowManager.element.scrollTop = this.scrollTop;
28565 }
28566
28567 this.element.classList.add("tabulator-spreadsheet-tab-active");
28568
28569 this.dispatchExternal("sheetLoaded", this.getComponent());
28570 }
28571
28572 ///////////////////////////////////
28573 //////// Helper Functions /////////
28574 ///////////////////////////////////
28575
28576 getComponent(){
28577 return new SheetComponent(this);
28578 }
28579
28580 getDefinition(){
28581 return {
28582 title:this.title,
28583 key:this.key,
28584 rows:this.rowCount,
28585 columns:this.columnCount,
28586 data:this.getData(),
28587 };
28588 }
28589
28590 getData(full){
28591 var output = [],
28592 rowWidths,
28593 outputWidth, outputHeight;
28594
28595 //map data to array format
28596 this.rowDefs.forEach((rowData) => {
28597 var row = [];
28598
28599 this.columnFields.forEach((field) => {
28600 row.push(rowData[field]);
28601 });
28602
28603 output.push(row);
28604 });
28605
28606 //trim output
28607 if(!full && !this.options("spreadsheetOutputFull")){
28608
28609 //calculate used area of data
28610 rowWidths = output.map(row => row.findLastIndex(val => typeof val !== 'undefined') + 1);
28611 outputWidth = Math.max(...rowWidths);
28612 outputHeight = rowWidths.findLastIndex(width => width > 0) + 1;
28613
28614 output = output.slice(0, outputHeight);
28615 output = output.map(row => row.slice(0, outputWidth));
28616 }
28617
28618 return output;
28619 }
28620
28621 setData(data){
28622 this.data = data;
28623 this.reinitialize();
28624
28625 this.dispatchExternal("sheetUpdated", this.getComponent());
28626
28627 if(this.isActive){
28628 this.load();
28629 }
28630 }
28631
28632 clear(){
28633 this.setData([]);
28634 }
28635
28636 setTitle(title){
28637 this.title = title;
28638 this.element.innerText = title;
28639
28640 this.dispatchExternal("sheetUpdated", this.getComponent());
28641 }
28642
28643 setRows(rows){
28644 this.rowCount = rows;
28645 this.initializeRows();
28646
28647 this.dispatchExternal("sheetUpdated", this.getComponent());
28648
28649 if(this.isActive){
28650 this.load();
28651 }
28652 }
28653
28654 setColumns(columns){
28655 this.columnCount = columns;
28656 this.reinitialize();
28657
28658 this.dispatchExternal("sheetUpdated", this.getComponent());
28659
28660 if(this.isActive){
28661 this.load();
28662 }
28663 }
28664
28665 remove(){
28666 this.spreadsheetManager.removeSheet(this);
28667 }
28668
28669 destroy(){
28670 if(this.element.parentNode){
28671 this.element.parentNode.removeChild(this.element);
28672 }
28673
28674 this.dispatchExternal("sheetRemoved", this.getComponent());
28675 }
28676
28677 active(){
28678 this.spreadsheetManager.loadSheet(this);
28679 }
28680 }
28681
28682 class Spreadsheet extends Module{
28683
28684 static moduleName = "spreadsheet";
28685
28686 constructor(table){
28687 super(table);
28688
28689 this.sheets = [];
28690 this.element = null;
28691
28692 this.registerTableOption("spreadsheet", false);
28693 this.registerTableOption("spreadsheetRows", 50);
28694 this.registerTableOption("spreadsheetColumns", 50);
28695 this.registerTableOption("spreadsheetColumnDefinition", {});
28696 this.registerTableOption("spreadsheetOutputFull", false);
28697 this.registerTableOption("spreadsheetData", false);
28698 this.registerTableOption("spreadsheetSheets", false);
28699 this.registerTableOption("spreadsheetSheetTabs", false);
28700 this.registerTableOption("spreadsheetSheetTabsElement", false);
28701
28702 this.registerTableFunction("setSheets", this.setSheets.bind(this));
28703 this.registerTableFunction("addSheet", this.addSheet.bind(this));
28704 this.registerTableFunction("getSheets", this.getSheets.bind(this));
28705 this.registerTableFunction("getSheetDefinitions", this.getSheetDefinitions.bind(this));
28706 this.registerTableFunction("setSheetData", this.setSheetData.bind(this));
28707 this.registerTableFunction("getSheet", this.getSheet.bind(this));
28708 this.registerTableFunction("getSheetData", this.getSheetData.bind(this));
28709 this.registerTableFunction("clearSheet", this.clearSheet.bind(this));
28710 this.registerTableFunction("removeSheet", this.removeSheetFunc.bind(this));
28711 this.registerTableFunction("activeSheet", this.activeSheetFunc.bind(this));
28712 }
28713
28714 ///////////////////////////////////
28715 ////// Module Initialization //////
28716 ///////////////////////////////////
28717
28718
28719 initialize(){
28720 if(this.options("spreadsheet")){
28721 this.subscribe("table-initialized", this.tableInitialized.bind(this));
28722 this.subscribe("data-loaded", this.loadRemoteData.bind(this));
28723
28724 this.table.options.index = "_id";
28725
28726 if(this.options("spreadsheetData") && this.options("spreadsheetSheets")){
28727 console.warn("You cannot use spreadsheetData and spreadsheetSheets at the same time, ignoring spreadsheetData");
28728
28729 this.table.options.spreadsheetData = false;
28730 }
28731
28732 this.compatibilityCheck();
28733
28734 if(this.options("spreadsheetSheetTabs")){
28735 this.initializeTabset();
28736 }
28737 }
28738 }
28739
28740 compatibilityCheck(){
28741 if(this.options("data")){
28742 console.warn("Do not use the data option when working with spreadsheets, use either spreadsheetData or spreadsheetSheets to pass data into the table");
28743 }
28744
28745 if(this.options("pagination")){
28746 console.warn("The spreadsheet module is not compatible with the pagination module");
28747 }
28748
28749 if(this.options("groupBy")){
28750 console.warn("The spreadsheet module is not compatible with the row grouping module");
28751 }
28752
28753 if(this.options("responsiveCollapse")){
28754 console.warn("The spreadsheet module is not compatible with the responsive collapse module");
28755 }
28756 }
28757 initializeTabset(){
28758 this.element = document.createElement("div");
28759 this.element.classList.add("tabulator-spreadsheet-tabs");
28760 var altContainer = this.options("spreadsheetSheetTabsElement");
28761
28762 if(altContainer && !(altContainer instanceof HTMLElement)){
28763 altContainer = document.querySelector(altContainer);
28764
28765 if(!altContainer){
28766 console.warn("Unable to find element matching spreadsheetSheetTabsElement selector:", this.options("spreadsheetSheetTabsElement"));
28767 }
28768 }
28769
28770 if(altContainer){
28771 altContainer.appendChild(this.element);
28772 }else {
28773 this.footerAppend(this.element);
28774 }
28775 }
28776
28777 tableInitialized(){
28778 if(this.sheets.length){
28779 this.loadSheet(this.sheets[0]);
28780 }else {
28781
28782 if(this.options("spreadsheetSheets")){
28783 this.loadSheets(this.options("spreadsheetSheets"));
28784 }else if(this.options("spreadsheetData")){
28785 this.loadData(this.options("spreadsheetData"));
28786 }
28787 }
28788 }
28789
28790 ///////////////////////////////////
28791 /////////// Ajax Parsing //////////
28792 ///////////////////////////////////
28793
28794 loadRemoteData(data, data1, data2){
28795 console.log("data", data, data1, data2);
28796
28797 if(Array.isArray(data)){
28798
28799 this.table.dataLoader.clearAlert();
28800 this.dispatchExternal("dataLoaded", data);
28801
28802 if(!data.length || Array.isArray(data[0])){
28803 this.loadData(data);
28804 }else {
28805 this.loadSheets(data);
28806 }
28807 }else {
28808 console.error("Spreadsheet Loading Error - Unable to process remote data due to invalid data type \nExpecting: array \nReceived: ", typeof data, "\nData: ", data);
28809 }
28810
28811 return false;
28812 }
28813
28814 ///////////////////////////////////
28815 ///////// Sheet Management ////////
28816 ///////////////////////////////////
28817
28818
28819 loadData(data){
28820 var def = {
28821 data:data,
28822 };
28823
28824 this.loadSheet(this.newSheet(def));
28825 }
28826
28827 destroySheets(){
28828 this.sheets.forEach((sheet) => {
28829 sheet.destroy();
28830 });
28831
28832 this.sheets = [];
28833 this.activeSheet = null;
28834 }
28835
28836 loadSheets(sheets){
28837 if(!Array.isArray(sheets)){
28838 sheets = [];
28839 }
28840
28841 this.destroySheets();
28842
28843 sheets.forEach((def) => {
28844 this.newSheet(def);
28845 });
28846
28847 this.loadSheet(this.sheets[0]);
28848 }
28849
28850 loadSheet(sheet){
28851 if(this.activeSheet !== sheet){
28852 if(this.activeSheet){
28853 this.activeSheet.unload();
28854 }
28855
28856 this.activeSheet = sheet;
28857
28858 sheet.load();
28859 }
28860 }
28861
28862 newSheet(definition = {}){
28863 var sheet;
28864
28865 if(!definition.rows){
28866 definition.rows = this.options("spreadsheetRows");
28867 }
28868
28869 if(!definition.columns){
28870 definition.columns = this.options("spreadsheetColumns");
28871 }
28872
28873 sheet = new Sheet(this, definition);
28874
28875 this.sheets.push(sheet);
28876
28877 if(this.element){
28878 this.element.appendChild(sheet.element);
28879 }
28880
28881 return sheet;
28882 }
28883
28884 removeSheet(sheet){
28885 var index = this.sheets.indexOf(sheet),
28886 prevSheet;
28887
28888 if(this.sheets.length > 1){
28889 if(index > -1){
28890 this.sheets.splice(index, 1);
28891 sheet.destroy();
28892
28893 if(this.activeSheet === sheet){
28894
28895 prevSheet = this.sheets[index - 1] || this.sheets[0];
28896
28897 if(prevSheet){
28898 this.loadSheet(prevSheet);
28899 }else {
28900 this.activeSheet = null;
28901 }
28902 }
28903 }
28904 }else {
28905 console.warn("Unable to remove sheet, at least one sheet must be active");
28906 }
28907 }
28908
28909 lookupSheet(key){
28910 if(!key){
28911 return this.activeSheet;
28912 }else if(key instanceof Sheet){
28913 return key;
28914 }else if(key instanceof SheetComponent){
28915 return key._sheet;
28916 }else {
28917 return this.sheets.find(sheet => sheet.key === key) || false;
28918 }
28919 }
28920
28921
28922 ///////////////////////////////////
28923 //////// Public Functions /////////
28924 ///////////////////////////////////
28925
28926 setSheets(sheets){
28927 this.loadSheets(sheets);
28928
28929 return this.getSheets();
28930 }
28931
28932 addSheet(sheet){
28933 return this.newSheet(sheet).getComponent();
28934 }
28935
28936 getSheetDefinitions(){
28937 return this.sheets.map(sheet => sheet.getDefinition());
28938 }
28939
28940 getSheets(){
28941 return this.sheets.map(sheet => sheet.getComponent());
28942 }
28943
28944 getSheet(key){
28945 var sheet = this.lookupSheet(key);
28946
28947 return sheet ? sheet.getComponent() : false;
28948 }
28949
28950 setSheetData(key, data){
28951 if (key && !data){
28952 data = key;
28953 key = false;
28954 }
28955
28956 var sheet = this.lookupSheet(key);
28957
28958 return sheet ? sheet.setData(data) : false;
28959 }
28960
28961 getSheetData(key){
28962 var sheet = this.lookupSheet(key);
28963
28964 return sheet ? sheet.getData() : false;
28965 }
28966
28967 clearSheet(key){
28968 var sheet = this.lookupSheet(key);
28969
28970 return sheet ? sheet.clear() : false;
28971 }
28972
28973 removeSheetFunc(key){
28974 var sheet = this.lookupSheet(key);
28975
28976 if(sheet){
28977 this.removeSheet(sheet);
28978 }
28979 }
28980
28981 activeSheetFunc(key){
28982 var sheet = this.lookupSheet(key);
28983
28984 return sheet ? this.loadSheet(sheet) : false;
28985 }
28986 }
28987
28988 class Tooltip extends Module{
28989
28990 static moduleName = "tooltip";
28991
28992 constructor(table){
28993 super(table);
28994
28995 this.tooltipSubscriber = null,
28996 this.headerSubscriber = null,
28997
28998 this.timeout = null;
28999 this.popupInstance = null;
29000
29001 // this.registerTableOption("tooltipGenerationMode", undefined); //deprecated
29002 this.registerTableOption("tooltipDelay", 300);
29003
29004 this.registerColumnOption("tooltip");
29005 this.registerColumnOption("headerTooltip");
29006 }
29007
29008 initialize(){
29009 this.deprecatedOptionsCheck();
29010
29011 this.subscribe("column-init", this.initializeColumn.bind(this));
29012 }
29013
29014 deprecatedOptionsCheck(){
29015 // this.deprecationCheckMsg("tooltipGenerationMode", "This option is no longer needed as tooltips are always generated on hover now");
29016 }
29017
29018 initializeColumn(column){
29019 if(column.definition.headerTooltip && !this.headerSubscriber){
29020 this.headerSubscriber = true;
29021
29022 this.subscribe("column-mousemove", this.mousemoveCheck.bind(this, "headerTooltip"));
29023 this.subscribe("column-mouseout", this.mouseoutCheck.bind(this, "headerTooltip"));
29024 }
29025
29026 if(column.definition.tooltip && !this.tooltipSubscriber){
29027 this.tooltipSubscriber = true;
29028
29029 this.subscribe("cell-mousemove", this.mousemoveCheck.bind(this, "tooltip"));
29030 this.subscribe("cell-mouseout", this.mouseoutCheck.bind(this, "tooltip"));
29031 }
29032 }
29033
29034 mousemoveCheck(action, e, component){
29035 var tooltip = action === "tooltip" ? component.column.definition.tooltip : component.definition.headerTooltip;
29036
29037 if(tooltip){
29038 this.clearPopup();
29039 this.timeout = setTimeout(this.loadTooltip.bind(this, e, component, tooltip), this.table.options.tooltipDelay);
29040 }
29041 }
29042
29043 mouseoutCheck(action, e, component){
29044 if(!this.popupInstance){
29045 this.clearPopup();
29046 }
29047 }
29048
29049 clearPopup(action, e, component){
29050 clearTimeout(this.timeout);
29051 this.timeout = null;
29052
29053 if(this.popupInstance){
29054 this.popupInstance.hide();
29055 }
29056 }
29057
29058 loadTooltip(e, component, tooltip){
29059 var contentsEl, renderedCallback, coords;
29060
29061 function onRendered(callback){
29062 renderedCallback = callback;
29063 }
29064
29065 if(typeof tooltip === "function"){
29066 tooltip = tooltip(e, component.getComponent(), onRendered);
29067 }
29068
29069 if(tooltip instanceof HTMLElement){
29070 contentsEl = tooltip;
29071 }else {
29072 contentsEl = document.createElement("div");
29073
29074 if(tooltip === true){
29075 if(component instanceof Cell){
29076 tooltip = component.value;
29077 }else {
29078 if(component.definition.field){
29079 this.langBind("columns|" + component.definition.field, (value) => {
29080 contentsEl.innerHTML = tooltip = value || component.definition.title;
29081 });
29082 }else {
29083 tooltip = component.definition.title;
29084 }
29085 }
29086 }
29087
29088 contentsEl.innerHTML = tooltip;
29089 }
29090
29091 if(tooltip || tooltip === 0 || tooltip === false){
29092 contentsEl.classList.add("tabulator-tooltip");
29093
29094 contentsEl.addEventListener("mousemove", e => e.preventDefault());
29095
29096 this.popupInstance = this.popup(contentsEl);
29097
29098 if(typeof renderedCallback === "function"){
29099 this.popupInstance.renderCallback(renderedCallback);
29100 }
29101
29102 coords = this.popupInstance.containerEventCoords(e);
29103
29104 this.popupInstance.show(coords.x + 15, coords.y + 15).hideOnBlur(() => {
29105 this.dispatchExternal("TooltipClosed", component.getComponent());
29106 this.popupInstance = null;
29107 });
29108
29109 this.dispatchExternal("TooltipOpened", component.getComponent());
29110 }
29111 }
29112 }
29113
29114 var defaultValidators = {
29115 //is integer
29116 integer: function(cell, value, parameters){
29117 if(value === "" || value === null || typeof value === "undefined"){
29118 return true;
29119 }
29120
29121 value = Number(value);
29122
29123 return !isNaN(value) && isFinite(value) && Math.floor(value) === value;
29124 },
29125
29126 //is float
29127 float: function(cell, value, parameters){
29128 if(value === "" || value === null || typeof value === "undefined"){
29129 return true;
29130 }
29131
29132 value = Number(value);
29133
29134 return !isNaN(value) && isFinite(value) && value % 1 !== 0;
29135 },
29136
29137 //must be a number
29138 numeric: function(cell, value, parameters){
29139 if(value === "" || value === null || typeof value === "undefined"){
29140 return true;
29141 }
29142 return !isNaN(value);
29143 },
29144
29145 //must be a string
29146 string: function(cell, value, parameters){
29147 if(value === "" || value === null || typeof value === "undefined"){
29148 return true;
29149 }
29150 return isNaN(value);
29151 },
29152
29153 //must be alphanumeric
29154 alphanumeric: function(cell, value, parameters){
29155 if(value === "" || value === null || typeof value === "undefined"){
29156 return true;
29157 }
29158
29159 var reg = new RegExp(/^[a-z0-9]+$/i);
29160
29161 return reg.test(value);
29162 },
29163
29164 //maximum value
29165 max: function(cell, value, parameters){
29166 if(value === "" || value === null || typeof value === "undefined"){
29167 return true;
29168 }
29169 return parseFloat(value) <= parameters;
29170 },
29171
29172 //minimum value
29173 min: function(cell, value, parameters){
29174 if(value === "" || value === null || typeof value === "undefined"){
29175 return true;
29176 }
29177 return parseFloat(value) >= parameters;
29178 },
29179
29180 //starts with value
29181 starts: function(cell, value, parameters){
29182 if(value === "" || value === null || typeof value === "undefined"){
29183 return true;
29184 }
29185 return String(value).toLowerCase().startsWith(String(parameters).toLowerCase());
29186 },
29187
29188 //ends with value
29189 ends: function(cell, value, parameters){
29190 if(value === "" || value === null || typeof value === "undefined"){
29191 return true;
29192 }
29193 return String(value).toLowerCase().endsWith(String(parameters).toLowerCase());
29194 },
29195
29196
29197 //minimum string length
29198 minLength: function(cell, value, parameters){
29199 if(value === "" || value === null || typeof value === "undefined"){
29200 return true;
29201 }
29202 return String(value).length >= parameters;
29203 },
29204
29205 //maximum string length
29206 maxLength: function(cell, value, parameters){
29207 if(value === "" || value === null || typeof value === "undefined"){
29208 return true;
29209 }
29210 return String(value).length <= parameters;
29211 },
29212
29213 //in provided value list
29214 in: function(cell, value, parameters){
29215 if(value === "" || value === null || typeof value === "undefined"){
29216 return true;
29217 }
29218
29219 if(typeof parameters == "string"){
29220 parameters = parameters.split("|");
29221 }
29222
29223 return parameters.indexOf(value) > -1;
29224 },
29225
29226 //must match provided regex
29227 regex: function(cell, value, parameters){
29228 if(value === "" || value === null || typeof value === "undefined"){
29229 return true;
29230 }
29231 var reg = new RegExp(parameters);
29232
29233 return reg.test(value);
29234 },
29235
29236 //value must be unique in this column
29237 unique: function(cell, value, parameters){
29238 if(value === "" || value === null || typeof value === "undefined"){
29239 return true;
29240 }
29241 var unique = true;
29242
29243 var cellData = cell.getData();
29244 var column = cell.getColumn()._getSelf();
29245
29246 this.table.rowManager.rows.forEach(function(row){
29247 var data = row.getData();
29248
29249 if(data !== cellData){
29250 if(value == column.getFieldValue(data)){
29251 unique = false;
29252 }
29253 }
29254 });
29255
29256 return unique;
29257 },
29258
29259 //must have a value
29260 required:function(cell, value, parameters){
29261 return value !== "" && value !== null && typeof value !== "undefined";
29262 },
29263 };
29264
29265 class Validate extends Module{
29266
29267 static moduleName = "validate";
29268
29269 //load defaults
29270 static validators = defaultValidators;
29271
29272 constructor(table){
29273 super(table);
29274
29275 this.invalidCells = [];
29276
29277 this.registerTableOption("validationMode", "blocking");
29278
29279 this.registerColumnOption("validator");
29280
29281 this.registerTableFunction("getInvalidCells", this.getInvalidCells.bind(this));
29282 this.registerTableFunction("clearCellValidation", this.userClearCellValidation.bind(this));
29283 this.registerTableFunction("validate", this.userValidate.bind(this));
29284
29285 this.registerComponentFunction("cell", "isValid", this.cellIsValid.bind(this));
29286 this.registerComponentFunction("cell", "clearValidation", this.clearValidation.bind(this));
29287 this.registerComponentFunction("cell", "validate", this.cellValidate.bind(this));
29288
29289 this.registerComponentFunction("column", "validate", this.columnValidate.bind(this));
29290 this.registerComponentFunction("row", "validate", this.rowValidate.bind(this));
29291 }
29292
29293
29294 initialize(){
29295 this.subscribe("cell-delete", this.clearValidation.bind(this));
29296 this.subscribe("column-layout", this.initializeColumnCheck.bind(this));
29297
29298 this.subscribe("edit-success", this.editValidate.bind(this));
29299 this.subscribe("edit-editor-clear", this.editorClear.bind(this));
29300 this.subscribe("edit-edited-clear", this.editedClear.bind(this));
29301 }
29302
29303 ///////////////////////////////////
29304 ///////// Event Handling //////////
29305 ///////////////////////////////////
29306
29307 editValidate(cell, value, previousValue){
29308 var valid = this.table.options.validationMode !== "manual" ? this.validate(cell.column.modules.validate, cell, value) : true;
29309
29310 // allow time for editor to make render changes then style cell
29311 if(valid !== true){
29312 setTimeout(() => {
29313 cell.getElement().classList.add("tabulator-validation-fail");
29314 this.dispatchExternal("validationFailed", cell.getComponent(), value, valid);
29315 });
29316 }
29317
29318 return valid;
29319 }
29320
29321 editorClear(cell, cancelled){
29322 if(cancelled){
29323 if(cell.column.modules.validate){
29324 this.cellValidate(cell);
29325 }
29326 }
29327
29328 cell.getElement().classList.remove("tabulator-validation-fail");
29329 }
29330
29331 editedClear(cell){
29332 if(cell.modules.validate){
29333 cell.modules.validate.invalid = false;
29334 }
29335 }
29336
29337 ///////////////////////////////////
29338 ////////// Cell Functions /////////
29339 ///////////////////////////////////
29340
29341 cellIsValid(cell){
29342 return cell.modules.validate ? (cell.modules.validate.invalid || true) : true;
29343 }
29344
29345 cellValidate(cell){
29346 return this.validate(cell.column.modules.validate, cell, cell.getValue());
29347 }
29348
29349 ///////////////////////////////////
29350 ///////// Column Functions ////////
29351 ///////////////////////////////////
29352
29353 columnValidate(column){
29354 var invalid = [];
29355
29356 column.cells.forEach((cell) => {
29357 if(this.cellValidate(cell) !== true){
29358 invalid.push(cell.getComponent());
29359 }
29360 });
29361
29362 return invalid.length ? invalid : true;
29363 }
29364
29365 ///////////////////////////////////
29366 ////////// Row Functions //////////
29367 ///////////////////////////////////
29368
29369 rowValidate(row){
29370 var invalid = [];
29371
29372 row.cells.forEach((cell) => {
29373 if(this.cellValidate(cell) !== true){
29374 invalid.push(cell.getComponent());
29375 }
29376 });
29377
29378 return invalid.length ? invalid : true;
29379 }
29380
29381 ///////////////////////////////////
29382 ///////// Table Functions /////////
29383 ///////////////////////////////////
29384
29385
29386 userClearCellValidation(cells){
29387 if(!cells){
29388 cells = this.getInvalidCells();
29389 }
29390
29391 if(!Array.isArray(cells)){
29392 cells = [cells];
29393 }
29394
29395 cells.forEach((cell) => {
29396 this.clearValidation(cell._getSelf());
29397 });
29398 }
29399
29400 userValidate(cells){
29401 var output = [];
29402
29403 //clear row data
29404 this.table.rowManager.rows.forEach((row) => {
29405 row = row.getComponent();
29406
29407 var valid = row.validate();
29408
29409 if(valid !== true){
29410 output = output.concat(valid);
29411 }
29412 });
29413
29414 return output.length ? output : true;
29415 }
29416
29417 ///////////////////////////////////
29418 ///////// Internal Logic //////////
29419 ///////////////////////////////////
29420
29421 initializeColumnCheck(column){
29422 if(typeof column.definition.validator !== "undefined"){
29423 this.initializeColumn(column);
29424 }
29425 }
29426
29427 //validate
29428 initializeColumn(column){
29429 var self = this,
29430 config = [],
29431 validator;
29432
29433 if(column.definition.validator){
29434
29435 if(Array.isArray(column.definition.validator)){
29436 column.definition.validator.forEach((item) => {
29437 validator = self._extractValidator(item);
29438
29439 if(validator){
29440 config.push(validator);
29441 }
29442 });
29443
29444 }else {
29445 validator = this._extractValidator(column.definition.validator);
29446
29447 if(validator){
29448 config.push(validator);
29449 }
29450 }
29451
29452 column.modules.validate = config.length ? config : false;
29453 }
29454 }
29455
29456 _extractValidator(value){
29457 var type, params, pos;
29458
29459 switch(typeof value){
29460 case "string":
29461 pos = value.indexOf(':');
29462
29463 if(pos > -1){
29464 type = value.substring(0,pos);
29465 params = value.substring(pos+1);
29466 }else {
29467 type = value;
29468 }
29469
29470 return this._buildValidator(type, params);
29471
29472 case "function":
29473 return this._buildValidator(value);
29474
29475 case "object":
29476 return this._buildValidator(value.type, value.parameters);
29477 }
29478 }
29479
29480 _buildValidator(type, params){
29481
29482 var func = typeof type == "function" ? type : Validate.validators[type];
29483
29484 if(!func){
29485 console.warn("Validator Setup Error - No matching validator found:", type);
29486 return false;
29487 }else {
29488 return {
29489 type:typeof type == "function" ? "function" : type,
29490 func:func,
29491 params:params,
29492 };
29493 }
29494 }
29495
29496 validate(validators, cell, value){
29497 var self = this,
29498 failedValidators = [],
29499 invalidIndex = this.invalidCells.indexOf(cell);
29500
29501 if(validators){
29502 validators.forEach((item) => {
29503 if(!item.func.call(self, cell.getComponent(), value, item.params)){
29504 failedValidators.push({
29505 type:item.type,
29506 parameters:item.params
29507 });
29508 }
29509 });
29510 }
29511
29512 if(!cell.modules.validate){
29513 cell.modules.validate = {};
29514 }
29515
29516 if(!failedValidators.length){
29517 cell.modules.validate.invalid = false;
29518 cell.getElement().classList.remove("tabulator-validation-fail");
29519
29520 if(invalidIndex > -1){
29521 this.invalidCells.splice(invalidIndex, 1);
29522 }
29523 }else {
29524 cell.modules.validate.invalid = failedValidators;
29525
29526 if(this.table.options.validationMode !== "manual"){
29527 cell.getElement().classList.add("tabulator-validation-fail");
29528 }
29529
29530 if(invalidIndex == -1){
29531 this.invalidCells.push(cell);
29532 }
29533 }
29534
29535 return failedValidators.length ? failedValidators : true;
29536 }
29537
29538 getInvalidCells(){
29539 var output = [];
29540
29541 this.invalidCells.forEach((cell) => {
29542 output.push(cell.getComponent());
29543 });
29544
29545 return output;
29546 }
29547
29548 clearValidation(cell){
29549 var invalidIndex;
29550
29551 if(cell.modules.validate && cell.modules.validate.invalid){
29552
29553 cell.getElement().classList.remove("tabulator-validation-fail");
29554 cell.modules.validate.invalid = false;
29555
29556 invalidIndex = this.invalidCells.indexOf(cell);
29557
29558 if(invalidIndex > -1){
29559 this.invalidCells.splice(invalidIndex, 1);
29560 }
29561 }
29562 }
29563 }
29564
29565 var allModules = /*#__PURE__*/Object.freeze({
29566 __proto__: null,
29567 AccessorModule: Accessor,
29568 AjaxModule: Ajax,
29569 ClipboardModule: Clipboard,
29570 ColumnCalcsModule: ColumnCalcs,
29571 DataTreeModule: DataTree,
29572 DownloadModule: Download,
29573 EditModule: Edit,
29574 ExportModule: Export,
29575 FilterModule: Filter,
29576 FormatModule: Format,
29577 FrozenColumnsModule: FrozenColumns,
29578 FrozenRowsModule: FrozenRows,
29579 GroupRowsModule: GroupRows,
29580 HistoryModule: History,
29581 HtmlTableImportModule: HtmlTableImport,
29582 ImportModule: Import,
29583 InteractionModule: Interaction,
29584 KeybindingsModule: Keybindings,
29585 MenuModule: Menu,
29586 MoveColumnsModule: MoveColumns,
29587 MoveRowsModule: MoveRows,
29588 MutatorModule: Mutator,
29589 PageModule: Page,
29590 PersistenceModule: Persistence,
29591 PopupModule: Popup,
29592 PrintModule: Print,
29593 ReactiveDataModule: ReactiveData,
29594 ResizeColumnsModule: ResizeColumns,
29595 ResizeRowsModule: ResizeRows,
29596 ResizeTableModule: ResizeTable,
29597 ResponsiveLayoutModule: ResponsiveLayout,
29598 SelectRangeModule: SelectRange,
29599 SelectRowModule: SelectRow,
29600 SortModule: Sort,
29601 SpreadsheetModule: Spreadsheet,
29602 TooltipModule: Tooltip,
29603 ValidateModule: Validate
29604 });
29605
29606 //tabulator with all modules installed
29607
29608 class TabulatorFull extends Tabulator {
29609 static extendModule(){
29610 Tabulator.initializeModuleBinder(allModules);
29611 Tabulator._extendModule(...arguments);
29612 }
29613
29614 static registerModule(){
29615 Tabulator.initializeModuleBinder(allModules);
29616 Tabulator._registerModule(...arguments);
29617 }
29618
29619 constructor(element, options, modules){
29620 super(element, options, allModules);
29621 }
29622 }
29623
29624 var TabulatorFull$1 = TabulatorFull;
29625
29626 return TabulatorFull$1;
29627
29628 }));
29629 //# sourceMappingURL=tabulator.js.map