Debian Codegraph @

templates/lib/extra/tabulator/tabulator.js

raw symbols SCIP
1 /* Tabulator v6.4.0 (c) Oliver Folkerd 2026 */
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
2748 return el;
2749 }
2750
2751 createHeaderElement (){
2752 var el = document.createElement("div");
2753
2754 el.classList.add("tabulator-header");
2755 el.setAttribute("role", "rowgroup");
2756
2757 if(!this.table.options.headerVisible){
2758 el.classList.add("tabulator-header-hidden");
2759 }
2760
2761 return el;
2762 }
2763
2764 //return containing element
2765 getElement(){
2766 return this.element;
2767 }
2768
2769 //return containing contents element
2770 getContentsElement(){
2771 return this.contentsElement;
2772 }
2773
2774
2775 //return header containing element
2776 getHeadersElement(){
2777 return this.headersElement;
2778 }
2779
2780 //scroll horizontally to match table body
2781 scrollHorizontal(left){
2782 this.contentsElement.scrollLeft = left;
2783
2784 this.scrollLeft = left;
2785
2786 this.renderer.scrollColumns(left);
2787 }
2788
2789 initializeScrollWheelWatcher(){
2790 this.contentsElement.addEventListener("wheel", (e) => {
2791 var left;
2792
2793 if(e.deltaX){
2794 left = this.contentsElement.scrollLeft + e.deltaX;
2795
2796 this.table.rowManager.scrollHorizontal(left);
2797 this.table.columnManager.scrollHorizontal(left);
2798 }
2799 });
2800 }
2801
2802 ///////////// Column Setup Functions /////////////
2803 generateColumnsFromRowData(data){
2804 var cols = [],
2805 collProgress = {},
2806 rowSample = this.table.options.autoColumns === "full" ? data : [data[0]],
2807 definitions = this.table.options.autoColumnsDefinitions;
2808
2809 if(data && data.length){
2810
2811 rowSample.forEach((row) => {
2812
2813 Object.keys(row).forEach((key, index) => {
2814 let value = row[key],
2815 col;
2816
2817 if(!collProgress[key]){
2818 col = {
2819 field:key,
2820 title:key,
2821 sorter:this.calculateSorterFromValue(value),
2822 };
2823
2824 cols.splice(index, 0, col);
2825 collProgress[key] = typeof value === "undefined" ? col : true;
2826 }else if(collProgress[key] !== true){
2827 if(typeof value !== "undefined"){
2828 collProgress[key].sorter = this.calculateSorterFromValue(value);
2829 collProgress[key] = true;
2830 }
2831 }
2832 });
2833 });
2834
2835 if(definitions){
2836
2837 switch(typeof definitions){
2838 case "function":
2839 this.table.options.columns = definitions.call(this.table, cols);
2840 break;
2841
2842 case "object":
2843 if(Array.isArray(definitions)){
2844 cols.forEach((col) => {
2845 var match = definitions.find((def) => {
2846 return def.field === col.field;
2847 });
2848
2849 if(match){
2850 Object.assign(col, match);
2851 }
2852 });
2853
2854 }else {
2855 cols.forEach((col) => {
2856 if(definitions[col.field]){
2857 Object.assign(col, definitions[col.field]);
2858 }
2859 });
2860 }
2861
2862 this.table.options.columns = cols;
2863 break;
2864 }
2865 }else {
2866 this.table.options.columns = cols;
2867 }
2868
2869 this.setColumns(this.table.options.columns);
2870 }
2871 }
2872
2873 calculateSorterFromValue(value){
2874 var sorter;
2875
2876 switch(typeof value){
2877 case "undefined":
2878 sorter = "string";
2879 break;
2880
2881 case "boolean":
2882 sorter = "boolean";
2883 break;
2884
2885 case "number":
2886 sorter = "number";
2887 break;
2888
2889 case "object":
2890 if(Array.isArray(value)){
2891 sorter = "array";
2892 }else {
2893 sorter = "string";
2894 }
2895 break;
2896
2897 default:
2898 if(!isNaN(value) && value !== ""){
2899 sorter = "number";
2900 }else {
2901 if(value.match(/((^[0-9]+[a-z]+)|(^[a-z]+[0-9]+))+$/i)){
2902 sorter = "alphanum";
2903 }else {
2904 sorter = "string";
2905 }
2906 }
2907 break;
2908 }
2909
2910 return sorter;
2911 }
2912
2913 setColumns(cols, row){
2914 while(this.headersElement.firstChild) this.headersElement.removeChild(this.headersElement.firstChild);
2915
2916 this.columns = [];
2917 this.columnsByIndex = [];
2918 this.columnsByField = {};
2919
2920 this.dispatch("columns-loading");
2921 this.dispatchExternal("columnsLoading");
2922
2923 if(this.table.options.rowHeader){
2924 this.rowHeader = new Column(this.table.options.rowHeader === true ? {} : this.table.options.rowHeader, this, true);
2925 this.columns.push(this.rowHeader);
2926 this.headersElement.appendChild(this.rowHeader.getElement());
2927 this.rowHeader.columnRendered();
2928 }
2929
2930 cols.forEach((def, i) => {
2931 this._addColumn(def);
2932 });
2933
2934 this._reIndexColumns();
2935
2936 this.dispatch("columns-loaded");
2937
2938 if(this.subscribedExternal("columnsLoaded")){
2939 this.dispatchExternal("columnsLoaded", this.getComponents());
2940 }
2941
2942 this.rerenderColumns(false, true);
2943
2944 this.redraw(true);
2945 }
2946
2947 _addColumn(definition, before, nextToColumn){
2948 var column = new Column(definition, this),
2949 colEl = column.getElement(),
2950 index = nextToColumn ? this.findColumnIndex(nextToColumn) : nextToColumn;
2951
2952 //prevent adding of rows in front of row header
2953 if(before && this.rowHeader && (!nextToColumn || nextToColumn === this.rowHeader)){
2954 before = false;
2955 nextToColumn = this.rowHeader;
2956 index = 0;
2957 }
2958
2959 if(nextToColumn && index > -1){
2960 var topColumn = nextToColumn.getTopColumn();
2961 var parentIndex = this.columns.indexOf(topColumn);
2962 var nextEl = topColumn.getElement();
2963
2964 if(before){
2965 this.columns.splice(parentIndex, 0, column);
2966 nextEl.parentNode.insertBefore(colEl, nextEl);
2967 }else {
2968 this.columns.splice(parentIndex + 1, 0, column);
2969 nextEl.parentNode.insertBefore(colEl, nextEl.nextSibling);
2970 }
2971 }else {
2972 if(before){
2973 this.columns.unshift(column);
2974 this.headersElement.insertBefore(column.getElement(), this.headersElement.firstChild);
2975 }else {
2976 this.columns.push(column);
2977 this.headersElement.appendChild(column.getElement());
2978 }
2979 }
2980
2981 column.columnRendered();
2982
2983 return column;
2984 }
2985
2986 registerColumnField(col){
2987 if(col.definition.field){
2988 this.columnsByField[col.definition.field] = col;
2989 }
2990 }
2991
2992 registerColumnPosition(col){
2993 this.columnsByIndex.push(col);
2994 }
2995
2996 _reIndexColumns(){
2997 this.columnsByIndex = [];
2998
2999 this.columns.forEach(function(column){
3000 column.reRegisterPosition();
3001 });
3002 }
3003
3004 //ensure column headers take up the correct amount of space in column groups
3005 verticalAlignHeaders(){
3006 var minHeight = 0;
3007
3008 if(!this.redrawBlock){
3009
3010 this.headersElement.style.height="";
3011
3012 this.columns.forEach((column) => {
3013 column.clearVerticalAlign();
3014 });
3015
3016 this.columns.forEach((column) => {
3017 var height = column.getHeight();
3018
3019 if(height > minHeight){
3020 minHeight = height;
3021 }
3022 });
3023
3024 this.headersElement.style.height = minHeight + "px";
3025
3026 this.columns.forEach((column) => {
3027 column.verticalAlign(this.table.options.columnHeaderVertAlign, minHeight);
3028 });
3029
3030 this.table.rowManager.adjustTableSize();
3031 }
3032 }
3033
3034 //////////////// Column Details /////////////////
3035 findColumn(subject){
3036 var columns;
3037
3038 if(typeof subject == "object"){
3039
3040 if(subject instanceof Column){
3041 //subject is column element
3042 return subject;
3043 }else if(subject instanceof ColumnComponent){
3044 //subject is public column component
3045 return subject._getSelf() || false;
3046 }else if(typeof HTMLElement !== "undefined" && subject instanceof HTMLElement){
3047
3048 columns = [];
3049
3050 this.columns.forEach((column) => {
3051 columns.push(column);
3052 columns = columns.concat(column.getColumns(true));
3053 });
3054
3055 //subject is a HTML element of the column header
3056 let match = columns.find((column) => {
3057 return column.element === subject;
3058 });
3059
3060 return match || false;
3061 }
3062
3063 }else {
3064 //subject should be treated as the field name of the column
3065 return this.columnsByField[subject] || false;
3066 }
3067
3068 //catch all for any other type of input
3069 return false;
3070 }
3071
3072 getColumnByField(field){
3073 return this.columnsByField[field];
3074 }
3075
3076 getColumnsByFieldRoot(root){
3077 var matches = [];
3078
3079 Object.keys(this.columnsByField).forEach((field) => {
3080 var fieldRoot = this.table.options.nestedFieldSeparator ? field.split(this.table.options.nestedFieldSeparator)[0] : field;
3081 if(fieldRoot === root){
3082 matches.push(this.columnsByField[field]);
3083 }
3084 });
3085
3086 return matches;
3087 }
3088
3089 getColumnByIndex(index){
3090 return this.columnsByIndex[index];
3091 }
3092
3093 getFirstVisibleColumn(){
3094 var index = this.columnsByIndex.findIndex((col) => {
3095 return col.visible;
3096 });
3097
3098 return index > -1 ? this.columnsByIndex[index] : false;
3099 }
3100
3101 getVisibleColumnsByIndex() {
3102 return this.columnsByIndex.filter((col) => col.visible);
3103 }
3104
3105 getColumns(){
3106 return this.columns;
3107 }
3108
3109 findColumnIndex(column){
3110 return this.columnsByIndex.findIndex((col) => {
3111 return column === col;
3112 });
3113 }
3114
3115 //return all columns that are not groups
3116 getRealColumns(){
3117 return this.columnsByIndex;
3118 }
3119
3120 //traverse across columns and call action
3121 traverse(callback){
3122 this.columnsByIndex.forEach((column,i) =>{
3123 callback(column, i);
3124 });
3125 }
3126
3127 //get definitions of actual columns
3128 getDefinitions(active){
3129 var output = [];
3130
3131 this.columnsByIndex.forEach((column) => {
3132 if(!active || (active && column.visible)){
3133 output.push(column.getDefinition());
3134 }
3135 });
3136
3137 return output;
3138 }
3139
3140 //get full nested definition tree
3141 getDefinitionTree(){
3142 var output = [];
3143
3144 this.columns.forEach((column) => {
3145 output.push(column.getDefinition(true));
3146 });
3147
3148 return output;
3149 }
3150
3151 getComponents(structured){
3152 var output = [],
3153 columns = structured ? this.columns : this.columnsByIndex;
3154
3155 columns.forEach((column) => {
3156 output.push(column.getComponent());
3157 });
3158
3159 return output;
3160 }
3161
3162 getWidth(){
3163 var width = 0;
3164
3165 this.columnsByIndex.forEach((column) => {
3166 if(column.visible){
3167 width += column.getWidth();
3168 }
3169 });
3170
3171 return width;
3172 }
3173
3174 moveColumn(from, to, after){
3175 to.element.parentNode.insertBefore(from.element, to.element);
3176
3177 if(after){
3178 to.element.parentNode.insertBefore(to.element, from.element);
3179 }
3180
3181 this.moveColumnActual(from, to, after);
3182
3183 this.verticalAlignHeaders();
3184
3185 this.table.rowManager.reinitialize();
3186 }
3187
3188 moveColumnActual(from, to, after){
3189 if(from.parent.isGroup){
3190 this._moveColumnInArray(from.parent.columns, from, to, after);
3191 }else {
3192 this._moveColumnInArray(this.columns, from, to, after);
3193 }
3194
3195 this._moveColumnInArray(this.columnsByIndex, from, to, after, true);
3196
3197 this.rerenderColumns(true);
3198
3199 this.dispatch("column-moved", from, to, after);
3200
3201 if(this.subscribedExternal("columnMoved")){
3202 this.dispatchExternal("columnMoved", from.getComponent(), this.table.columnManager.getComponents());
3203 }
3204 }
3205
3206 _moveColumnInArray(columns, from, to, after, updateRows){
3207 var fromIndex = columns.indexOf(from),
3208 toIndex, rows = [];
3209
3210 if (fromIndex > -1) {
3211
3212 columns.splice(fromIndex, 1);
3213
3214 toIndex = columns.indexOf(to);
3215
3216 if (toIndex > -1) {
3217
3218 if(after){
3219 toIndex = toIndex+1;
3220 }
3221
3222 }else {
3223 toIndex = fromIndex;
3224 }
3225
3226 columns.splice(toIndex, 0, from);
3227
3228 if(updateRows){
3229
3230 rows = this.chain("column-moving-rows", [from, to, after], null, []) || [];
3231
3232 rows = rows.concat(this.table.rowManager.rows);
3233
3234 rows.forEach(function(row){
3235 if(row.cells.length){
3236 var cell = row.cells.splice(fromIndex, 1)[0];
3237 row.cells.splice(toIndex, 0, cell);
3238 }
3239 });
3240
3241 }
3242 }
3243 }
3244
3245 scrollToColumn(column, position, ifVisible){
3246 var left = 0,
3247 offset = column.getLeftOffset(),
3248 adjust = 0,
3249 colEl = column.getElement();
3250
3251
3252 return new Promise((resolve, reject) => {
3253
3254 if(typeof position === "undefined"){
3255 position = this.table.options.scrollToColumnPosition;
3256 }
3257
3258 if(typeof ifVisible === "undefined"){
3259 ifVisible = this.table.options.scrollToColumnIfVisible;
3260 }
3261
3262 if(column.visible){
3263
3264 //align to correct position
3265 switch(position){
3266 case "middle":
3267 case "center":
3268 adjust = -this.element.clientWidth / 2;
3269 break;
3270
3271 case "right":
3272 adjust = colEl.clientWidth - this.headersElement.clientWidth;
3273 break;
3274 }
3275
3276 //check column visibility
3277 if(!ifVisible){
3278 if(offset > 0 && offset + colEl.offsetWidth < this.element.clientWidth){
3279 return false;
3280 }
3281 }
3282
3283 //calculate scroll position
3284 left = offset + adjust;
3285
3286 left = Math.max(Math.min(left, this.table.rowManager.element.scrollWidth - this.table.rowManager.element.clientWidth),0);
3287
3288 this.table.rowManager.scrollHorizontal(left);
3289 this.scrollHorizontal(left);
3290
3291 resolve();
3292 }else {
3293 console.warn("Scroll Error - Column not visible");
3294 reject("Scroll Error - Column not visible");
3295 }
3296
3297 });
3298 }
3299
3300 //////////////// Cell Management /////////////////
3301 generateCells(row){
3302 var cells = [];
3303
3304 this.columnsByIndex.forEach((column) => {
3305 cells.push(column.generateCell(row));
3306 });
3307
3308 return cells;
3309 }
3310
3311 //////////////// Column Management /////////////////
3312 getFlexBaseWidth(){
3313 var totalWidth = this.table.element.clientWidth, //table element width
3314 fixedWidth = 0;
3315
3316 //adjust for vertical scrollbar if present
3317 if(this.table.rowManager.element.scrollHeight > this.table.rowManager.element.clientHeight){
3318 totalWidth -= this.table.rowManager.element.offsetWidth - this.table.rowManager.element.clientWidth;
3319 }
3320
3321 this.columnsByIndex.forEach(function(column){
3322 var width, minWidth, colWidth;
3323
3324 if(column.visible){
3325
3326 width = column.definition.width || 0;
3327
3328 minWidth = parseInt(column.minWidth);
3329
3330 if(typeof(width) == "string"){
3331 if(width.indexOf("%") > -1){
3332 colWidth = (totalWidth / 100) * parseInt(width) ;
3333 }else {
3334 colWidth = parseInt(width);
3335 }
3336 }else {
3337 colWidth = width;
3338 }
3339
3340 fixedWidth += colWidth > minWidth ? colWidth : minWidth;
3341
3342 }
3343 });
3344
3345 return fixedWidth;
3346 }
3347
3348 addColumn(definition, before, nextToColumn){
3349 return new Promise((resolve, reject) => {
3350 var column = this._addColumn(definition, before, nextToColumn);
3351
3352 this._reIndexColumns();
3353
3354 this.dispatch("column-add", definition, before, nextToColumn);
3355
3356 if(this.layoutMode() != "fitColumns"){
3357 column.reinitializeWidth();
3358 }
3359
3360 this.redraw(true);
3361
3362 this.table.rowManager.reinitialize();
3363
3364 this.rerenderColumns();
3365
3366 resolve(column);
3367 });
3368 }
3369
3370 //remove column from system
3371 deregisterColumn(column){
3372 var field = column.getField(),
3373 index;
3374
3375 //remove from field list
3376 if(field){
3377 delete this.columnsByField[field];
3378 }
3379
3380 //remove from index list
3381 index = this.columnsByIndex.indexOf(column);
3382
3383 if(index > -1){
3384 this.columnsByIndex.splice(index, 1);
3385 }
3386
3387 //remove from column list
3388 index = this.columns.indexOf(column);
3389
3390 if(index > -1){
3391 this.columns.splice(index, 1);
3392 }
3393
3394 this.verticalAlignHeaders();
3395
3396 this.redraw();
3397 }
3398
3399 rerenderColumns(update, silent){
3400 if(!this.redrawBlock){
3401 this.renderer.rerenderColumns(update, silent);
3402 }else {
3403 if(update === false || (update === true && this.redrawBlockUpdate === null)){
3404 this.redrawBlockUpdate = update;
3405 }
3406 }
3407 }
3408
3409 blockRedraw(){
3410 this.redrawBlock = true;
3411 this.redrawBlockUpdate = null;
3412 }
3413
3414 restoreRedraw(){
3415 this.redrawBlock = false;
3416 this.verticalAlignHeaders();
3417 this.renderer.rerenderColumns(this.redrawBlockUpdate);
3418
3419 }
3420
3421 //redraw columns
3422 redraw(force){
3423 if(Helpers.elVisible(this.element)){
3424 this.verticalAlignHeaders();
3425 }
3426
3427 if(force){
3428 this.table.rowManager.resetScroll();
3429 this.table.rowManager.reinitialize();
3430 }
3431
3432 if(!this.confirm("table-redrawing", force)){
3433 this.layoutRefresh(force);
3434 }
3435
3436 this.dispatch("table-redraw", force);
3437
3438 this.table.footerManager.redraw();
3439 }
3440 }
3441
3442 //public row object
3443 class RowComponent {
3444
3445 constructor (row){
3446 this._row = row;
3447
3448 return new Proxy(this, {
3449 get: function(target, name, receiver) {
3450 if (typeof target[name] !== "undefined") {
3451 return target[name];
3452 }else {
3453 return target._row.table.componentFunctionBinder.handle("row", target._row, name);
3454 }
3455 }
3456 });
3457 }
3458
3459 getData(transform){
3460 return this._row.getData(transform);
3461 }
3462
3463 getElement(){
3464 return this._row.getElement();
3465 }
3466
3467 getCells(){
3468 var cells = [];
3469
3470 this._row.getCells().forEach(function(cell){
3471 cells.push(cell.getComponent());
3472 });
3473
3474 return cells;
3475 }
3476
3477 getCell(column){
3478 var cell = this._row.getCell(column);
3479 return cell ? cell.getComponent() : false;
3480 }
3481
3482 getIndex(){
3483 return this._row.getData("data")[this._row.table.options.index];
3484 }
3485
3486 getPosition(){
3487 return this._row.getPosition();
3488 }
3489
3490 watchPosition(callback){
3491 return this._row.watchPosition(callback);
3492 }
3493
3494 delete(){
3495 return this._row.delete();
3496 }
3497
3498 scrollTo(position, ifVisible){
3499 return this._row.table.rowManager.scrollToRow(this._row, position, ifVisible);
3500 }
3501
3502 move(to, after){
3503 this._row.moveToRow(to, after);
3504 }
3505
3506 update(data){
3507 return this._row.updateData(data);
3508 }
3509
3510 normalizeHeight(){
3511 this._row.normalizeHeight(true);
3512 }
3513
3514 _getSelf(){
3515 return this._row;
3516 }
3517
3518 reformat(){
3519 return this._row.reinitialize();
3520 }
3521
3522 getTable(){
3523 return this._row.table;
3524 }
3525
3526 getNextRow(){
3527 var row = this._row.nextRow();
3528 return row ? row.getComponent() : row;
3529 }
3530
3531 getPrevRow(){
3532 var row = this._row.prevRow();
3533 return row ? row.getComponent() : row;
3534 }
3535 }
3536
3537 class Row extends CoreFeature{
3538 constructor (data, parent, type = "row"){
3539 super(parent.table);
3540
3541 this.parent = parent;
3542 this.data = {};
3543 this.type = type; //type of element
3544 this.element = false;
3545 this.modules = {}; //hold module variables;
3546 this.cells = [];
3547 this.height = 0; //hold element height
3548 this.heightStyled = ""; //hold element height pre-styled to improve render efficiency
3549 this.manualHeight = false; //user has manually set row height
3550 this.outerHeight = 0; //hold elements outer height
3551 this.initialized = false; //element has been rendered
3552 this.heightInitialized = false; //element has resized cells to fit
3553 this.position = 0; //store position of element in row list
3554 this.positionWatchers = [];
3555
3556 this.component = null;
3557
3558 this.created = false;
3559
3560 this.setData(data);
3561 }
3562
3563 create(){
3564 if(!this.created){
3565 this.created = true;
3566 this.generateElement();
3567 }
3568 }
3569
3570 createElement (){
3571 var el = document.createElement("div");
3572
3573 el.classList.add("tabulator-row");
3574 el.setAttribute("role", "row");
3575
3576 this.element = el;
3577 }
3578
3579 getElement(){
3580 this.create();
3581 return this.element;
3582 }
3583
3584 detachElement(){
3585 if (this.element && this.element.parentNode){
3586 this.element.parentNode.removeChild(this.element);
3587 }
3588 }
3589
3590 generateElement(){
3591 this.createElement();
3592 this.dispatch("row-init", this);
3593 }
3594
3595 generateCells(){
3596 this.cells = this.table.columnManager.generateCells(this);
3597 }
3598
3599 //functions to setup on first render
3600 initialize(force, inFragment){
3601 this.create();
3602
3603 if(!this.initialized || force){
3604
3605 this.deleteCells();
3606
3607 while(this.element.firstChild) this.element.removeChild(this.element.firstChild);
3608
3609 this.dispatch("row-layout-before", this);
3610
3611 this.generateCells();
3612
3613 this.initialized = true;
3614
3615 this.table.columnManager.renderer.renderRowCells(this, inFragment);
3616
3617 if(force){
3618 this.normalizeHeight();
3619 }
3620
3621 this.dispatch("row-layout", this);
3622
3623 if(this.table.options.rowFormatter){
3624 this.table.options.rowFormatter(this.getComponent());
3625 }
3626
3627 this.dispatch("row-layout-after", this);
3628 }else {
3629 this.table.columnManager.renderer.rerenderRowCells(this, inFragment);
3630 }
3631 }
3632
3633 rendered(){
3634 this.cells.forEach((cell) => {
3635 cell.cellRendered();
3636 });
3637 }
3638
3639 reinitializeHeight(){
3640 this.heightInitialized = false;
3641
3642 if(this.element && this.element.offsetParent !== null){
3643 this.normalizeHeight(true);
3644 }
3645 }
3646
3647 deinitialize(){
3648 this.initialized = false;
3649 }
3650
3651 deinitializeHeight(){
3652 this.heightInitialized = false;
3653 }
3654
3655 reinitialize(children){
3656 this.initialized = false;
3657 this.heightInitialized = false;
3658
3659 if(!this.manualHeight){
3660 this.height = 0;
3661 this.heightStyled = "";
3662 }
3663
3664 if(this.element && this.element.offsetParent !== null){
3665 this.initialize(true);
3666 }
3667
3668 this.dispatch("row-relayout", this);
3669 }
3670
3671 //get heights when doing bulk row style calcs in virtual DOM
3672 calcHeight(force){
3673 var maxHeight = 0, minHeight = 0;
3674
3675 if(this.table.options.rowHeight){
3676 this.height = this.table.options.rowHeight;
3677 }else {
3678 minHeight = this.calcMinHeight();
3679 maxHeight = this.calcMaxHeight();
3680
3681 if(force){
3682 this.height = Math.max(maxHeight, minHeight);
3683 }else {
3684 this.height = this.manualHeight ? this.height : Math.max(maxHeight, minHeight);
3685 }
3686 }
3687
3688 this.heightStyled = this.height ? this.height + "px" : "";
3689 this.outerHeight = this.element.offsetHeight;
3690 }
3691
3692 calcMinHeight(){
3693 return this.table.options.resizableRows ? this.element.clientHeight : 0;
3694 }
3695
3696 calcMaxHeight(){
3697 var maxHeight = 0;
3698
3699 this.cells.forEach(function(cell){
3700 var height = cell.getHeight();
3701
3702 if(height > maxHeight){
3703 maxHeight = height;
3704 }
3705 });
3706
3707 return maxHeight;
3708 }
3709
3710 //set of cells
3711 setCellHeight(){
3712 this.cells.forEach(function(cell){
3713 cell.setHeight();
3714 });
3715
3716 this.heightInitialized = true;
3717 }
3718
3719 clearCellHeight(){
3720 this.cells.forEach(function(cell){
3721 cell.clearHeight();
3722 });
3723 }
3724
3725 //normalize the height of elements in the row
3726 normalizeHeight(force){
3727 if(force && !this.table.options.rowHeight){
3728 this.clearCellHeight();
3729 }
3730
3731 this.calcHeight(force);
3732
3733 this.setCellHeight();
3734 }
3735
3736 //set height of rows
3737 setHeight(height, force){
3738 if(this.height != height || force){
3739
3740 this.manualHeight = true;
3741
3742 this.height = height;
3743 this.heightStyled = height ? height + "px" : "";
3744
3745 this.setCellHeight();
3746
3747 // this.outerHeight = this.element.outerHeight();
3748 this.outerHeight = this.element.offsetHeight;
3749
3750 if(this.subscribedExternal("rowHeight")){
3751 this.dispatchExternal("rowHeight", this.getComponent());
3752 }
3753 }
3754 }
3755
3756 //return rows outer height
3757 getHeight(){
3758 return this.outerHeight;
3759 }
3760
3761 //return rows outer Width
3762 getWidth(){
3763 return this.element.offsetWidth;
3764 }
3765
3766 //////////////// Cell Management /////////////////
3767 deleteCell(cell){
3768 var index = this.cells.indexOf(cell);
3769
3770 if(index > -1){
3771 this.cells.splice(index, 1);
3772 }
3773 }
3774
3775 //////////////// Data Management /////////////////
3776 setData(data){
3777 this.data = this.chain("row-data-init-before", [this, data], undefined, data);
3778
3779 this.dispatch("row-data-init-after", this);
3780 }
3781
3782 //update the rows data
3783 updateData(updatedData){
3784 var visible = this.element && Helpers.elVisible(this.element),
3785 tempData = {},
3786 newRowData;
3787
3788 return new Promise((resolve, reject) => {
3789
3790 if(typeof updatedData === "string"){
3791 updatedData = JSON.parse(updatedData);
3792 }
3793
3794 this.dispatch("row-data-save-before", this);
3795
3796 if(this.subscribed("row-data-changing")){
3797 tempData = Object.assign(tempData, this.data);
3798 tempData = Object.assign(tempData, updatedData);
3799 }
3800
3801 newRowData = this.chain("row-data-changing", [this, tempData, updatedData], null, updatedData);
3802
3803 // compute cells to update
3804 // This must be done prior to updating the row data otherwise uninitialized cells get
3805 // generated directly with the updated data, which prevents the run of callbacks
3806 // registered on cells updates (e.g. mutators)
3807 const cellsToUpdate = [];
3808 for (let attrname in updatedData) {
3809
3810 let columns = this.table.columnManager.getColumnsByFieldRoot(attrname);
3811
3812 columns.forEach((column) => {
3813 let cell = this.getCell(column.getField());
3814
3815 if(cell){
3816 let value = column.getFieldValue(newRowData);
3817 if(cell.getValue() !== value){
3818 cellsToUpdate.push([cell, value]);
3819 }
3820 }
3821 });
3822 }
3823
3824 //set data
3825 for (let attrname in newRowData) {
3826 this.data[attrname] = newRowData[attrname];
3827 }
3828
3829 this.dispatch("row-data-save-after", this);
3830
3831 //update affected cells only
3832 cellsToUpdate.forEach(([cell, value]) => {
3833 cell.setValueProcessData(value);
3834
3835 if(visible){
3836 cell.cellRendered();
3837 }
3838 });
3839
3840 //Partial reinitialization if visible
3841 if(visible){
3842 this.normalizeHeight(true);
3843
3844 if(this.table.options.rowFormatter){
3845 this.table.options.rowFormatter(this.getComponent());
3846 }
3847 }else {
3848 this.initialized = false;
3849 this.height = 0;
3850 this.heightStyled = "";
3851 }
3852
3853 this.dispatch("row-data-changed", this, visible, updatedData);
3854
3855 //this.reinitialize();
3856
3857 this.dispatchExternal("rowUpdated", this.getComponent());
3858
3859 if(this.subscribedExternal("dataChanged")){
3860 this.dispatchExternal("dataChanged", this.table.rowManager.getData());
3861 }
3862
3863 resolve();
3864 });
3865 }
3866
3867 getData(transform){
3868 if(transform){
3869 return this.chain("row-data-retrieve", [this, transform], null, this.data);
3870 }
3871
3872 return this.data;
3873 }
3874
3875 getCell(column){
3876 var match = false;
3877
3878 column = this.table.columnManager.findColumn(column);
3879
3880 if(!this.initialized && this.cells.length === 0){
3881 this.generateCells();
3882 }
3883
3884 match = this.cells.find(function(cell){
3885 return cell.column === column;
3886 });
3887
3888 return match;
3889 }
3890
3891 getCellIndex(findCell){
3892 return this.cells.findIndex(function(cell){
3893 return cell === findCell;
3894 });
3895 }
3896
3897 findCell(subject){
3898 return this.cells.find((cell) => {
3899 return cell.element === subject;
3900 });
3901 }
3902
3903 getCells(){
3904 if(!this.initialized && this.cells.length === 0){
3905 this.generateCells();
3906 }
3907
3908 return this.cells;
3909 }
3910
3911 nextRow(){
3912 var row = this.table.rowManager.nextDisplayRow(this, true);
3913 return row || false;
3914 }
3915
3916 prevRow(){
3917 var row = this.table.rowManager.prevDisplayRow(this, true);
3918 return row || false;
3919 }
3920
3921 moveToRow(to, before){
3922 var toRow = this.table.rowManager.findRow(to);
3923
3924 if(toRow){
3925 this.table.rowManager.moveRowActual(this, toRow, !before);
3926 this.table.rowManager.refreshActiveData("display", false, true);
3927 }else {
3928 console.warn("Move Error - No matching row found:", to);
3929 }
3930 }
3931
3932 ///////////////////// Actions /////////////////////
3933 delete(){
3934 this.dispatch("row-delete", this);
3935
3936 this.deleteActual();
3937
3938 return Promise.resolve();
3939 }
3940
3941 deleteActual(blockRedraw){
3942 this.detachModules();
3943
3944 this.table.rowManager.deleteRow(this, blockRedraw);
3945
3946 this.deleteCells();
3947
3948 this.initialized = false;
3949 this.heightInitialized = false;
3950 this.element = false;
3951
3952 this.dispatch("row-deleted", this);
3953 }
3954
3955 detachModules(){
3956 this.dispatch("row-deleting", this);
3957 }
3958
3959 deleteCells(){
3960 var cellCount = this.cells.length;
3961
3962 for(let i = 0; i < cellCount; i++){
3963 this.cells[0].delete();
3964 }
3965 }
3966
3967 wipe(){
3968 this.detachModules();
3969 this.deleteCells();
3970
3971 if(this.element){
3972 while(this.element.firstChild) this.element.removeChild(this.element.firstChild);
3973
3974 if(this.element.parentNode){
3975 this.element.parentNode.removeChild(this.element);
3976 }
3977 }
3978
3979 this.element = false;
3980 this.modules = {};
3981 }
3982
3983 isDisplayed(){
3984 return this.table.rowManager.getDisplayRows().includes(this);
3985 }
3986
3987 getPosition(){
3988 return this.isDisplayed() ? this.position : false;
3989 }
3990
3991 setPosition(position){
3992 if(position != this.position){
3993 this.position = position;
3994
3995 this.positionWatchers.forEach((callback) => {
3996 callback(this.position);
3997 });
3998 }
3999 }
4000
4001 watchPosition(callback){
4002 this.positionWatchers.push(callback);
4003
4004 callback(this.position);
4005 }
4006
4007 getGroup(){
4008 return this.modules.group || false;
4009 }
4010
4011 //////////////// Object Generation /////////////////
4012 getComponent(){
4013 if(!this.component){
4014 this.component = new RowComponent(this);
4015 }
4016
4017 return this.component;
4018 }
4019 }
4020
4021 class BasicVertical extends Renderer{
4022 constructor(table){
4023 super(table);
4024
4025 this.verticalFillMode = "fill";
4026
4027 this.scrollTop = 0;
4028 this.scrollLeft = 0;
4029
4030 this.scrollTop = 0;
4031 this.scrollLeft = 0;
4032 }
4033
4034 clearRows(){
4035 var element = this.tableElement;
4036
4037 // element.children.detach();
4038 while(element.firstChild) element.removeChild(element.firstChild);
4039
4040 element.scrollTop = 0;
4041 element.scrollLeft = 0;
4042
4043 element.style.minWidth = "";
4044 element.style.minHeight = "";
4045 element.style.display = "";
4046 element.style.visibility = "";
4047 }
4048
4049 renderRows() {
4050 var element = this.tableElement,
4051 onlyGroupHeaders = true,
4052 tableFrag = document.createDocumentFragment(),
4053 rows = this.rows();
4054
4055 rows.forEach((row, index) => {
4056 this.styleRow(row, index);
4057 row.initialize(false, true);
4058
4059 if (row.type !== "group") {
4060 onlyGroupHeaders = false;
4061 }
4062
4063 tableFrag.appendChild(row.getElement());
4064 });
4065
4066 element.appendChild(tableFrag);
4067
4068 rows.forEach((row) => {
4069 row.rendered();
4070
4071 if(!row.heightInitialized) {
4072 row.calcHeight(true);
4073 }
4074 });
4075
4076 rows.forEach((row) => {
4077 if(!row.heightInitialized) {
4078 row.setCellHeight();
4079 }
4080 });
4081
4082 if(onlyGroupHeaders){
4083 element.style.minWidth = this.table.columnManager.getWidth() + "px";
4084 }else {
4085 element.style.minWidth = "";
4086 }
4087 }
4088
4089
4090 rerenderRows(callback){
4091 this.clearRows();
4092
4093 if(callback){
4094 callback();
4095 }
4096
4097 this.renderRows();
4098
4099 if(!this.rows().length){
4100 this.table.rowManager.tableEmpty();
4101 }
4102 }
4103
4104 scrollToRowNearestTop(row){
4105 var rowTop = Helpers.elOffset(row.getElement()).top;
4106
4107 return !(Math.abs(this.elementVertical.scrollTop - rowTop) > Math.abs(this.elementVertical.scrollTop + this.elementVertical.clientHeight - rowTop));
4108 }
4109
4110 scrollToRow(row){
4111 var rowEl = row.getElement();
4112
4113 this.elementVertical.scrollTop = Helpers.elOffset(rowEl).top - Helpers.elOffset(this.elementVertical).top + this.elementVertical.scrollTop;
4114 }
4115
4116 visibleRows(includingBuffer){
4117 return this.rows();
4118 }
4119
4120 }
4121
4122 class VirtualDomVertical extends Renderer{
4123 constructor(table){
4124 super(table);
4125
4126 this.verticalFillMode = "fill";
4127
4128 this.scrollTop = 0;
4129 this.scrollLeft = 0;
4130
4131 this.vDomRowHeight = 20; //approximation of row heights for padding
4132
4133 this.vDomTop = 0; //hold position for first rendered row in the virtual DOM
4134 this.vDomBottom = 0; //hold position for last rendered row in the virtual DOM
4135
4136 this.vDomScrollPosTop = 0; //last scroll position of the vDom top;
4137 this.vDomScrollPosBottom = 0; //last scroll position of the vDom bottom;
4138
4139 this.vDomTopPad = 0; //hold value of padding for top of virtual DOM
4140 this.vDomBottomPad = 0; //hold value of padding for bottom of virtual DOM
4141
4142 this.vDomMaxRenderChain = 90; //the maximum number of dom elements that can be rendered in 1 go
4143
4144 this.vDomWindowBuffer = 0; //window row buffer before removing elements, to smooth scrolling
4145
4146 this.vDomWindowMinTotalRows = 20; //minimum number of rows to be generated in virtual dom (prevent buffering issues on tables with tall rows)
4147 this.vDomWindowMinMarginRows = 5; //minimum number of rows to be generated in virtual dom margin
4148
4149 this.vDomTopNewRows = []; //rows to normalize after appending to optimize render speed
4150 this.vDomBottomNewRows = []; //rows to normalize after appending to optimize render speed
4151 }
4152
4153 //////////////////////////////////////
4154 ///////// Public Functions ///////////
4155 //////////////////////////////////////
4156
4157 clearRows(){
4158 var element = this.tableElement;
4159
4160 // element.children.detach();
4161 while(element.firstChild) element.removeChild(element.firstChild);
4162
4163 element.style.paddingTop = "";
4164 element.style.paddingBottom = "";
4165 element.style.minHeight = "";
4166 element.style.display = "";
4167 element.style.visibility = "";
4168
4169 this.elementVertical.scrollTop = 0;
4170 this.elementVertical.scrollLeft = 0;
4171
4172 this.scrollTop = 0;
4173 this.scrollLeft = 0;
4174
4175 this.vDomTop = 0;
4176 this.vDomBottom = 0;
4177 this.vDomTopPad = 0;
4178 this.vDomBottomPad = 0;
4179 this.vDomScrollPosTop = 0;
4180 this.vDomScrollPosBottom = 0;
4181 }
4182
4183 renderRows(){
4184 this._virtualRenderFill();
4185 }
4186
4187 rerenderRows(callback){
4188 var scrollTop = this.elementVertical.scrollTop;
4189 var topRow = false;
4190 var topOffset = false;
4191
4192 var left = this.table.rowManager.scrollLeft;
4193
4194 var rows = this.rows();
4195
4196 for(var i = this.vDomTop; i <= this.vDomBottom; i++){
4197
4198 if(rows[i]){
4199 var diff = scrollTop - rows[i].getElement().offsetTop;
4200
4201 if(topOffset === false || Math.abs(diff) < topOffset){
4202 topOffset = diff;
4203 topRow = i;
4204 }else {
4205 break;
4206 }
4207 }
4208 }
4209
4210 rows.forEach((row) => {
4211 row.deinitializeHeight();
4212 });
4213
4214 if(callback){
4215 callback();
4216 }
4217
4218 if(this.rows().length){
4219 this._virtualRenderFill((topRow === false ? this.rows.length - 1 : topRow), true, topOffset || 0);
4220 }else {
4221 this.clear();
4222 this.table.rowManager.tableEmpty();
4223 }
4224
4225 this.scrollColumns(left);
4226 }
4227
4228 scrollColumns(left){
4229 this.table.rowManager.scrollHorizontal(left);
4230 }
4231
4232 scrollRows(top, dir){
4233 var topDiff = top - this.vDomScrollPosTop;
4234 var bottomDiff = top - this.vDomScrollPosBottom;
4235 var margin = this.vDomWindowBuffer * 2;
4236 var rows = this.rows();
4237
4238 this.scrollTop = top;
4239
4240 if(-topDiff > margin || bottomDiff > margin){
4241 //if big scroll redraw table;
4242 var left = this.table.rowManager.scrollLeft;
4243 this._virtualRenderFill(Math.floor((this.elementVertical.scrollTop / this.elementVertical.scrollHeight) * rows.length));
4244 this.scrollColumns(left);
4245 }else {
4246
4247 if(dir){
4248 //scrolling up
4249 if(topDiff < 0){
4250 this._addTopRow(rows, -topDiff);
4251 }
4252
4253 if(bottomDiff < 0){
4254 //hide bottom row if needed
4255 if(this.vDomScrollHeight - this.scrollTop > this.vDomWindowBuffer){
4256 this._removeBottomRow(rows, -bottomDiff);
4257 }else {
4258 this.vDomScrollPosBottom = this.scrollTop;
4259 }
4260 }
4261 }else {
4262
4263 if(bottomDiff >= 0){
4264 this._addBottomRow(rows, bottomDiff);
4265 }
4266
4267 //scrolling down
4268 if(topDiff >= 0){
4269 //hide top row if needed
4270 if(this.scrollTop > this.vDomWindowBuffer){
4271 this._removeTopRow(rows, topDiff);
4272 }else {
4273 this.vDomScrollPosTop = this.scrollTop;
4274 }
4275 }
4276 }
4277 }
4278 }
4279
4280 resize(){
4281 this.vDomWindowBuffer = this.table.options.renderVerticalBuffer || this.elementVertical.clientHeight;
4282 }
4283
4284 scrollToRowNearestTop(row){
4285 var rowIndex = this.rows().indexOf(row);
4286
4287 return !(Math.abs(this.vDomTop - rowIndex) > Math.abs(this.vDomBottom - rowIndex));
4288 }
4289
4290 scrollToRow(row){
4291 var index = this.rows().indexOf(row);
4292
4293 if(index > -1){
4294 this._virtualRenderFill(index, true);
4295 }
4296 }
4297
4298 visibleRows(includingBuffer){
4299 var topEdge = this.elementVertical.scrollTop,
4300 bottomEdge = this.elementVertical.clientHeight + topEdge,
4301 topFound = false,
4302 topRow = 0,
4303 bottomRow = 0,
4304 rows = this.rows();
4305
4306 if(includingBuffer){
4307 topRow = this.vDomTop;
4308 bottomRow = this.vDomBottom;
4309 }else {
4310 for(var i = this.vDomTop; i <= this.vDomBottom; i++){
4311 if(rows[i]){
4312 if(!topFound){
4313 if((topEdge - rows[i].getElement().offsetTop) >= 0){
4314 topRow = i;
4315 }else {
4316 topFound = true;
4317
4318 if(bottomEdge - rows[i].getElement().offsetTop >= 0){
4319 bottomRow = i;
4320 }else {
4321 break;
4322 }
4323 }
4324 }else {
4325 if(bottomEdge - rows[i].getElement().offsetTop >= 0){
4326 bottomRow = i;
4327 }else {
4328 break;
4329 }
4330 }
4331 }
4332 }
4333 }
4334
4335 return rows.slice(topRow, bottomRow + 1);
4336 }
4337
4338 //////////////////////////////////////
4339 //////// Internal Rendering //////////
4340 //////////////////////////////////////
4341
4342 //full virtual render
4343 _virtualRenderFill(position, forceMove, offset) {
4344 var element = this.tableElement,
4345 holder = this.elementVertical,
4346 topPad = 0,
4347 rowsHeight = 0,
4348 rowHeight = 0,
4349 heightOccupied = 0,
4350 topPadHeight = 0,
4351 i = 0,
4352 rows = this.rows(),
4353 rowsCount = rows.length,
4354 index = 0,
4355 row,
4356 rowFragment,
4357 renderedRows = [],
4358 totalRowsRendered = 0,
4359 rowsToRender = 0,
4360 fixedHeight = this.table.rowManager.fixedHeight,
4361 containerHeight = this.elementVertical.clientHeight,
4362 avgRowHeight = this.table.options.rowHeight,
4363 resized = true;
4364
4365 position = position || 0;
4366
4367 offset = offset || 0;
4368
4369 if(!position){
4370 this.clear();
4371 }else {
4372 while(element.firstChild) element.removeChild(element.firstChild);
4373
4374 //check if position is too close to bottom of table
4375 heightOccupied = (rowsCount - position + 1) * this.vDomRowHeight;
4376
4377 if(heightOccupied < containerHeight){
4378 position -= Math.ceil((containerHeight - heightOccupied) / this.vDomRowHeight);
4379 if(position < 0){
4380 position = 0;
4381 }
4382 }
4383
4384 //calculate initial pad
4385 topPad = Math.min(Math.max(Math.floor(this.vDomWindowBuffer / this.vDomRowHeight), this.vDomWindowMinMarginRows), position);
4386 position -= topPad;
4387 }
4388
4389 if(rowsCount && Helpers.elVisible(this.elementVertical)){
4390 this.vDomTop = position;
4391 this.vDomBottom = position -1;
4392
4393 if(fixedHeight || this.table.options.maxHeight) {
4394 if(avgRowHeight) {
4395 rowsToRender = (containerHeight / avgRowHeight) + (this.vDomWindowBuffer / avgRowHeight);
4396 }
4397 rowsToRender = Math.max(this.vDomWindowMinTotalRows, Math.ceil(rowsToRender));
4398 }
4399 else {
4400 rowsToRender = rowsCount;
4401 }
4402
4403 while(((rowsToRender == rowsCount || rowsHeight <= containerHeight + this.vDomWindowBuffer) || totalRowsRendered < this.vDomWindowMinTotalRows) && this.vDomBottom < rowsCount -1) {
4404 renderedRows = [];
4405 rowFragment = document.createDocumentFragment();
4406
4407 i = 0;
4408
4409 while ((i < rowsToRender) && this.vDomBottom < rowsCount -1) {
4410 index = this.vDomBottom + 1,
4411 row = rows[index];
4412
4413 this.styleRow(row, index);
4414
4415 row.initialize(false, true);
4416 if(!row.heightInitialized && !this.table.options.rowHeight){
4417 row.clearCellHeight();
4418 }
4419
4420 rowFragment.appendChild(row.getElement());
4421 renderedRows.push(row);
4422 this.vDomBottom ++;
4423 i++;
4424 }
4425
4426 if(!renderedRows.length){
4427 break;
4428 }
4429
4430 element.appendChild(rowFragment);
4431
4432 // NOTE: The next 4 loops are separate on purpose
4433 // This is to batch up the dom writes and reads which drastically improves performance
4434
4435 renderedRows.forEach((row) => {
4436 row.rendered();
4437 });
4438
4439 const rowsNeedingHeightInit = [];
4440 renderedRows.forEach((row) => {
4441 if(!row.heightInitialized) {
4442 row.calcHeight(true);
4443 rowsNeedingHeightInit.push(row);
4444 }
4445 });
4446
4447 rowsNeedingHeightInit.forEach((row) => {
4448 row.setCellHeight();
4449 });
4450
4451 renderedRows.forEach((row) => {
4452 rowHeight = row.getHeight();
4453
4454 if(totalRowsRendered < topPad){
4455 topPadHeight += rowHeight;
4456 }else {
4457 rowsHeight += rowHeight;
4458 }
4459
4460 if(rowHeight > this.vDomWindowBuffer){
4461 this.vDomWindowBuffer = rowHeight * 2;
4462 }
4463 totalRowsRendered++;
4464 });
4465
4466 resized = this.table.rowManager.adjustTableSize();
4467 containerHeight = this.elementVertical.clientHeight;
4468 if(resized && (fixedHeight || this.table.options.maxHeight))
4469 {
4470 avgRowHeight = rowsHeight / totalRowsRendered;
4471 rowsToRender = Math.max(this.vDomWindowMinTotalRows, Math.ceil((containerHeight / avgRowHeight) + (this.vDomWindowBuffer / avgRowHeight)));
4472 }
4473 }
4474
4475 if(!position){
4476 this.vDomTopPad = 0;
4477 //adjust row height to match average of rendered elements
4478 this.vDomRowHeight = Math.floor((rowsHeight + topPadHeight) / totalRowsRendered);
4479 this.vDomBottomPad = this.vDomRowHeight * (rowsCount - this.vDomBottom -1);
4480
4481 this.vDomScrollHeight = topPadHeight + rowsHeight + this.vDomBottomPad - containerHeight;
4482 }else {
4483 this.vDomTopPad = !forceMove ? this.scrollTop - topPadHeight : (this.vDomRowHeight * this.vDomTop) + offset;
4484 this.vDomBottomPad = this.vDomBottom == rowsCount-1 ? 0 : Math.max(this.vDomScrollHeight - this.vDomTopPad - rowsHeight - topPadHeight, 0);
4485 }
4486
4487 element.style.paddingTop = this.vDomTopPad+"px";
4488 element.style.paddingBottom = this.vDomBottomPad+"px";
4489
4490 if(forceMove){
4491 this.scrollTop = this.vDomTopPad + (topPadHeight) + offset - (this.elementVertical.scrollWidth > this.elementVertical.clientWidth ? this.elementVertical.offsetHeight - containerHeight : 0);
4492 }
4493
4494 this.scrollTop = Math.min(this.scrollTop, this.elementVertical.scrollHeight - containerHeight);
4495
4496 //adjust for horizontal scrollbar if present (and not at top of table)
4497 if(this.elementVertical.scrollWidth > this.elementVertical.clientWidth && forceMove){
4498 this.scrollTop += this.elementVertical.offsetHeight - containerHeight;
4499 }
4500
4501 this.vDomScrollPosTop = this.scrollTop;
4502 this.vDomScrollPosBottom = this.scrollTop;
4503
4504 holder.scrollTop = this.scrollTop;
4505
4506 this.dispatch("render-virtual-fill");
4507 }
4508 }
4509
4510 _addTopRow(rows, fillableSpace){
4511 var table = this.tableElement,
4512 addedRows = [],
4513 paddingAdjust = 0,
4514 index = this.vDomTop -1,
4515 i = 0,
4516 working = true;
4517
4518 while(working){
4519 if(this.vDomTop){
4520 let row = rows[index],
4521 rowHeight, initialized;
4522
4523 if(row && i < this.vDomMaxRenderChain){
4524 rowHeight = row.getHeight() || this.vDomRowHeight;
4525 initialized = row.initialized;
4526
4527 if(fillableSpace >= rowHeight){
4528
4529 this.styleRow(row, index);
4530 table.insertBefore(row.getElement(), table.firstChild);
4531
4532 if(!row.initialized || !row.heightInitialized){
4533 addedRows.push(row);
4534 }
4535
4536 row.initialize();
4537
4538 if(!initialized){
4539 rowHeight = row.getElement().offsetHeight;
4540
4541 if(rowHeight > this.vDomWindowBuffer){
4542 this.vDomWindowBuffer = rowHeight * 2;
4543 }
4544 }
4545
4546 fillableSpace -= rowHeight;
4547 paddingAdjust += rowHeight;
4548
4549 this.vDomTop--;
4550 index--;
4551 i++;
4552
4553 }else {
4554 working = false;
4555 }
4556
4557 }else {
4558 working = false;
4559 }
4560
4561 }else {
4562 working = false;
4563 }
4564 }
4565
4566 for (let row of addedRows){
4567 row.clearCellHeight();
4568 }
4569
4570 this._quickNormalizeRowHeight(addedRows);
4571
4572 if(paddingAdjust){
4573 this.vDomTopPad -= paddingAdjust;
4574
4575 if(this.vDomTopPad < 0){
4576 this.vDomTopPad = index * this.vDomRowHeight;
4577 }
4578
4579 if(index < 1){
4580 this.vDomTopPad = 0;
4581 }
4582
4583 table.style.paddingTop = this.vDomTopPad + "px";
4584 this.vDomScrollPosTop -= paddingAdjust;
4585 }
4586 }
4587
4588 _removeTopRow(rows, fillableSpace){
4589 var removableRows = [],
4590 paddingAdjust = 0,
4591 i = 0,
4592 working = true;
4593
4594 while(working){
4595 let row = rows[this.vDomTop],
4596 rowHeight;
4597
4598 if(row && i < this.vDomMaxRenderChain){
4599 rowHeight = row.getHeight() || this.vDomRowHeight;
4600
4601 if(fillableSpace >= rowHeight){
4602 this.vDomTop++;
4603
4604 fillableSpace -= rowHeight;
4605 paddingAdjust += rowHeight;
4606
4607 removableRows.push(row);
4608 i++;
4609 }else {
4610 working = false;
4611 }
4612 }else {
4613 working = false;
4614 }
4615 }
4616
4617 for (let row of removableRows){
4618 let rowEl = row.getElement();
4619
4620 if(rowEl.parentNode){
4621 rowEl.parentNode.removeChild(rowEl);
4622 }
4623 }
4624
4625 if(paddingAdjust){
4626 this.vDomTopPad += paddingAdjust;
4627 this.tableElement.style.paddingTop = this.vDomTopPad + "px";
4628 this.vDomScrollPosTop += this.vDomTop ? paddingAdjust : paddingAdjust + this.vDomWindowBuffer;
4629 }
4630 }
4631
4632 _addBottomRow(rows, fillableSpace){
4633 var table = this.tableElement,
4634 addedRows = [],
4635 paddingAdjust = 0,
4636 index = this.vDomBottom + 1,
4637 i = 0,
4638 working = true;
4639
4640 while(working){
4641 let row = rows[index],
4642 rowHeight, initialized;
4643
4644 if(row && i < this.vDomMaxRenderChain){
4645 rowHeight = row.getHeight() || this.vDomRowHeight;
4646 initialized = row.initialized;
4647
4648 if(fillableSpace >= rowHeight){
4649
4650 this.styleRow(row, index);
4651 table.appendChild(row.getElement());
4652
4653 if(!row.initialized || !row.heightInitialized){
4654 addedRows.push(row);
4655 }
4656
4657 row.initialize();
4658
4659 if(!initialized){
4660 rowHeight = row.getElement().offsetHeight;
4661
4662 if(rowHeight > this.vDomWindowBuffer){
4663 this.vDomWindowBuffer = rowHeight * 2;
4664 }
4665 }
4666
4667 fillableSpace -= rowHeight;
4668 paddingAdjust += rowHeight;
4669
4670 this.vDomBottom++;
4671 index++;
4672 i++;
4673 }else {
4674 working = false;
4675 }
4676 }else {
4677 working = false;
4678 }
4679 }
4680
4681 for (let row of addedRows){
4682 row.clearCellHeight();
4683 }
4684
4685 this._quickNormalizeRowHeight(addedRows);
4686
4687 if(paddingAdjust){
4688 this.vDomBottomPad -= paddingAdjust;
4689
4690 if(this.vDomBottomPad < 0 || index == rows.length -1){
4691 this.vDomBottomPad = 0;
4692 }
4693
4694 table.style.paddingBottom = this.vDomBottomPad + "px";
4695 this.vDomScrollPosBottom += paddingAdjust;
4696 }
4697 }
4698
4699 _removeBottomRow(rows, fillableSpace){
4700 var removableRows = [],
4701 paddingAdjust = 0,
4702 i = 0,
4703 working = true;
4704
4705 while(working){
4706 let row = rows[this.vDomBottom],
4707 rowHeight;
4708
4709 if(row && i < this.vDomMaxRenderChain){
4710 rowHeight = row.getHeight() || this.vDomRowHeight;
4711
4712 if(fillableSpace >= rowHeight){
4713 this.vDomBottom --;
4714
4715 fillableSpace -= rowHeight;
4716 paddingAdjust += rowHeight;
4717
4718 removableRows.push(row);
4719 i++;
4720 }else {
4721 working = false;
4722 }
4723 }else {
4724 working = false;
4725 }
4726 }
4727
4728 for (let row of removableRows){
4729 let rowEl = row.getElement();
4730
4731 if(rowEl.parentNode){
4732 rowEl.parentNode.removeChild(rowEl);
4733 }
4734 }
4735
4736 if(paddingAdjust){
4737 this.vDomBottomPad += paddingAdjust;
4738
4739 if(this.vDomBottomPad < 0){
4740 this.vDomBottomPad = 0;
4741 }
4742
4743 this.tableElement.style.paddingBottom = this.vDomBottomPad + "px";
4744 this.vDomScrollPosBottom -= paddingAdjust;
4745 }
4746 }
4747
4748 _quickNormalizeRowHeight(rows){
4749 for(let row of rows){
4750 row.calcHeight();
4751 }
4752
4753 for(let row of rows){
4754 row.setCellHeight();
4755 }
4756 }
4757 }
4758
4759 class RowManager extends CoreFeature{
4760
4761 constructor(table){
4762 super(table);
4763
4764 this.element = this.createHolderElement(); //containing element
4765 this.tableElement = this.createTableElement(); //table element
4766 this.heightFixer = this.createTableElement(); //table element
4767 this.placeholder = null; //placeholder element
4768 this.placeholderContents = null; //placeholder element
4769
4770 this.firstRender = false; //handle first render
4771 this.renderMode = "virtual"; //current rendering mode
4772 this.fixedHeight = false; //current rendering mode
4773
4774 this.rows = []; //hold row data objects
4775 this.activeRowsPipeline = []; //hold calculation of active rows
4776 this.activeRows = []; //rows currently available to on display in the table
4777 this.activeRowsCount = 0; //count of active rows
4778
4779 this.displayRows = []; //rows currently on display in the table
4780 this.displayRowsCount = 0; //count of display rows
4781
4782 this.scrollTop = 0;
4783 this.scrollLeft = 0;
4784
4785 this.redrawBlock = false; //prevent redraws to allow multiple data manipulations before continuing
4786 this.redrawBlockRestoreConfig = false; //store latest redraw function calls for when redraw is needed
4787 this.redrawBlockRenderInPosition = false; //store latest redraw function calls for when redraw is needed
4788
4789 this.dataPipeline = []; //hold data pipeline tasks
4790 this.displayPipeline = []; //hold data display pipeline tasks
4791
4792 this.scrollbarWidth = 0;
4793
4794 this.renderer = null;
4795 }
4796
4797 //////////////// Setup Functions /////////////////
4798
4799 createHolderElement (){
4800 var el = document.createElement("div");
4801
4802 el.classList.add("tabulator-tableholder");
4803 el.setAttribute("tabindex", 0);
4804 // el.setAttribute("role", "rowgroup");
4805
4806 return el;
4807 }
4808
4809 createTableElement (){
4810 var el = document.createElement("div");
4811
4812 el.classList.add("tabulator-table");
4813 el.setAttribute("role", "rowgroup");
4814 el.setAttribute("id", "tabulator-table-body");
4815
4816 return el;
4817 }
4818
4819 initializePlaceholder(){
4820 var placeholder = this.table.options.placeholder;
4821
4822 if(typeof placeholder === "function"){
4823 placeholder = placeholder.call(this.table);
4824 }
4825
4826 placeholder = this.chain("placeholder", [placeholder], placeholder, placeholder) || placeholder;
4827
4828 //configure placeholder element
4829 if(placeholder){
4830 let el = document.createElement("div");
4831 el.classList.add("tabulator-placeholder");
4832
4833 if(typeof placeholder == "string"){
4834 let contents = document.createElement("div");
4835 contents.classList.add("tabulator-placeholder-contents");
4836 contents.innerHTML = placeholder;
4837
4838 el.appendChild(contents);
4839
4840 this.placeholderContents = contents;
4841
4842 }else if(typeof HTMLElement !== "undefined" && placeholder instanceof HTMLElement){
4843
4844 el.appendChild(placeholder);
4845 this.placeholderContents = placeholder;
4846 }else {
4847 console.warn("Invalid placeholder provided, must be string or HTML Element", placeholder);
4848
4849 this.el = null;
4850 }
4851
4852 this.placeholder = el;
4853 }
4854 }
4855
4856 //return containing element
4857 getElement(){
4858 return this.element;
4859 }
4860
4861 //return table element
4862 getTableElement(){
4863 return this.tableElement;
4864 }
4865
4866 initialize(){
4867 this.initializePlaceholder();
4868 this.initializeRenderer();
4869
4870 //initialize manager
4871 this.element.appendChild(this.tableElement);
4872
4873 this.firstRender = true;
4874
4875 //scroll header along with table body
4876 this.element.addEventListener("scroll", () => {
4877 var left = this.element.scrollLeft,
4878 leftDir = this.scrollLeft > left,
4879 top = this.element.scrollTop,
4880 topDir = this.scrollTop > top;
4881
4882 //handle horizontal scrolling
4883 if(this.scrollLeft != left){
4884 this.scrollLeft = left;
4885
4886 this.dispatch("scroll-horizontal", left, leftDir);
4887 this.dispatchExternal("scrollHorizontal", left, leftDir);
4888
4889 this._positionPlaceholder();
4890 }
4891
4892 //handle vertical scrolling
4893 if(this.scrollTop != top){
4894 this.scrollTop = top;
4895
4896 this.renderer.scrollRows(top, topDir);
4897
4898 this.dispatch("scroll-vertical", top, topDir);
4899 this.dispatchExternal("scrollVertical", top, topDir);
4900 }
4901 });
4902 }
4903
4904 ////////////////// Row Manipulation //////////////////
4905 findRow(subject){
4906 if(typeof subject == "object"){
4907 if(subject instanceof Row){
4908 //subject is row element
4909 return subject;
4910 }else if(subject instanceof RowComponent){
4911 //subject is public row component
4912 return subject._getSelf() || false;
4913 }else if(typeof HTMLElement !== "undefined" && subject instanceof HTMLElement){
4914 //subject is a HTML element of the row
4915 let match = this.rows.find((row) => {
4916 return row.getElement() === subject;
4917 });
4918
4919 return match || false;
4920 }else if(subject === null){
4921 return false;
4922 }
4923 }else if(typeof subject == "undefined"){
4924 return false;
4925 }else {
4926 //subject should be treated as the index of the row
4927 let match = this.rows.find((row) => {
4928 return row.data[this.table.options.index] == subject;
4929 });
4930
4931 return match || false;
4932 }
4933
4934 //catch all for any other type of input
4935 return false;
4936 }
4937
4938 getRowFromDataObject(data){
4939 var match = this.rows.find((row) => {
4940 return row.data === data;
4941 });
4942
4943 return match || false;
4944 }
4945
4946 getRowFromPosition(position){
4947 return this.getDisplayRows().find((row) => {
4948 return row.type === "row" && row.getPosition() === position && row.isDisplayed();
4949 });
4950 }
4951
4952 scrollToRow(row, position, ifVisible){
4953 return this.renderer.scrollToRowPosition(row, position, ifVisible);
4954 }
4955
4956 ////////////////// Data Handling //////////////////
4957 setData(data, renderInPosition, columnsChanged){
4958 return new Promise((resolve, reject)=>{
4959 if(renderInPosition && this.getDisplayRows().length){
4960 if(this.table.options.pagination){
4961 this._setDataActual(data, true);
4962 }else {
4963 this.reRenderInPosition(() => {
4964 this._setDataActual(data);
4965 });
4966 }
4967 }else {
4968 if(this.table.options.autoColumns && columnsChanged && this.table.initialized){
4969 this.table.columnManager.generateColumnsFromRowData(data);
4970 }
4971 this.resetScroll();
4972
4973 this._setDataActual(data);
4974 }
4975
4976 resolve();
4977 });
4978 }
4979
4980 _setDataActual(data, renderInPosition){
4981 this.dispatchExternal("dataProcessing", data);
4982
4983 this._wipeElements();
4984
4985 if(Array.isArray(data)){
4986 this.dispatch("data-processing", data);
4987
4988 data.forEach((def, i) => {
4989 if(def && typeof def === "object"){
4990 var row = new Row(def, this);
4991 this.rows.push(row);
4992 }else {
4993 console.warn("Data Loading Warning - Invalid row data detected and ignored, expecting object but received:", def);
4994 }
4995 });
4996
4997 this.refreshActiveData(false, false, renderInPosition);
4998
4999 this.dispatch("data-processed", data);
5000 this.dispatchExternal("dataProcessed", data);
5001 }else {
5002 console.error("Data Loading Error - Unable to process data due to invalid data type \nExpecting: array \nReceived: ", typeof data, "\nData: ", data);
5003 }
5004 }
5005
5006 _wipeElements(){
5007 this.dispatch("rows-wipe");
5008
5009 this.destroy();
5010
5011 this.adjustTableSize();
5012
5013 this.dispatch("rows-wiped");
5014 }
5015
5016 destroy(){
5017 this.rows.forEach((row) => {
5018 row.wipe();
5019 });
5020
5021 this.rows = [];
5022 this.activeRows = [];
5023 this.activeRowsPipeline = [];
5024 this.activeRowsCount = 0;
5025 this.displayRows = [];
5026 this.displayRowsCount = 0;
5027 }
5028
5029 deleteRow(row, blockRedraw){
5030 var allIndex = this.rows.indexOf(row),
5031 activeIndex = this.activeRows.indexOf(row);
5032
5033 if(activeIndex > -1){
5034 this.activeRows.splice(activeIndex, 1);
5035 }
5036
5037 if(allIndex > -1){
5038 this.rows.splice(allIndex, 1);
5039 }
5040
5041 this.setActiveRows(this.activeRows);
5042
5043 this.displayRowIterator((rows) => {
5044 var displayIndex = rows.indexOf(row);
5045
5046 if(displayIndex > -1){
5047 rows.splice(displayIndex, 1);
5048 }
5049 });
5050
5051 if(!blockRedraw){
5052 this.reRenderInPosition();
5053 }
5054
5055 this.regenerateRowPositions();
5056
5057 this.dispatchExternal("rowDeleted", row.getComponent());
5058
5059 if(!this.displayRowsCount){
5060 this.tableEmpty();
5061 }
5062
5063 if(this.subscribedExternal("dataChanged")){
5064 this.dispatchExternal("dataChanged", this.getData());
5065 }
5066 }
5067
5068 addRow(data, pos, index, blockRedraw){
5069 var row = this.addRowActual(data, pos, index, blockRedraw);
5070 return row;
5071 }
5072
5073 //add multiple rows
5074 addRows(data, pos, index, refreshDisplayOnly){
5075 var rows = [];
5076
5077 return new Promise((resolve, reject) => {
5078 pos = this.findAddRowPos(pos);
5079
5080 if(!Array.isArray(data)){
5081 data = [data];
5082 }
5083
5084 if((typeof index == "undefined" && pos) || (typeof index !== "undefined" && !pos)){
5085 data.reverse();
5086 }
5087
5088 data.forEach((item, i) => {
5089 var row = this.addRow(item, pos, index, true);
5090 rows.push(row);
5091 this.dispatch("row-added", row, item, pos, index);
5092 });
5093
5094 this.refreshActiveData(refreshDisplayOnly ? "displayPipeline" : false, false, true);
5095
5096 this.regenerateRowPositions();
5097
5098 if(this.displayRowsCount){
5099 this._clearPlaceholder();
5100 }
5101
5102 resolve(rows);
5103 });
5104 }
5105
5106 findAddRowPos(pos){
5107 if(typeof pos === "undefined"){
5108 pos = this.table.options.addRowPos;
5109 }
5110
5111 if(pos === "pos"){
5112 pos = true;
5113 }
5114
5115 if(pos === "bottom"){
5116 pos = false;
5117 }
5118
5119 return pos;
5120 }
5121
5122 addRowActual(data, pos, index, blockRedraw){
5123 var row = data instanceof Row ? data : new Row(data || {}, this),
5124 top = this.findAddRowPos(pos),
5125 allIndex = -1,
5126 activeIndex, chainResult;
5127
5128 if(!index){
5129 chainResult = this.chain("row-adding-position", [row, top], null, {index, top});
5130
5131 index = chainResult.index;
5132 top = chainResult.top;
5133 }
5134
5135 if(typeof index !== "undefined"){
5136 index = this.findRow(index);
5137 }
5138
5139 index = this.chain("row-adding-index", [row, index, top], null, index);
5140
5141 if(index){
5142 allIndex = this.rows.indexOf(index);
5143 }
5144
5145 if(index && allIndex > -1){
5146 activeIndex = this.activeRows.indexOf(index);
5147
5148 this.displayRowIterator(function(rows){
5149 var displayIndex = rows.indexOf(index);
5150
5151 if(displayIndex > -1){
5152 rows.splice((top ? displayIndex : displayIndex + 1), 0, row);
5153 }
5154 });
5155
5156 if(activeIndex > -1){
5157 this.activeRows.splice((top ? activeIndex : activeIndex + 1), 0, row);
5158 }
5159
5160 this.rows.splice((top ? allIndex : allIndex + 1), 0, row);
5161
5162 }else {
5163
5164 if(top){
5165
5166 this.displayRowIterator(function(rows){
5167 rows.unshift(row);
5168 });
5169
5170 this.activeRows.unshift(row);
5171 this.rows.unshift(row);
5172 }else {
5173 this.displayRowIterator(function(rows){
5174 rows.push(row);
5175 });
5176
5177 this.activeRows.push(row);
5178 this.rows.push(row);
5179 }
5180 }
5181
5182 this.setActiveRows(this.activeRows);
5183
5184 this.dispatchExternal("rowAdded", row.getComponent());
5185
5186 if(this.subscribedExternal("dataChanged")){
5187 this.dispatchExternal("dataChanged", this.table.rowManager.getData());
5188 }
5189
5190 if(!blockRedraw){
5191 this.reRenderInPosition();
5192 }
5193
5194 return row;
5195 }
5196
5197 moveRow(from, to, after){
5198 this.dispatch("row-move", from, to, after);
5199
5200 this.moveRowActual(from, to, after);
5201
5202 this.regenerateRowPositions();
5203
5204 this.dispatch("row-moved", from, to, after);
5205 this.dispatchExternal("rowMoved", from.getComponent());
5206 }
5207
5208 moveRowActual(from, to, after){
5209 this.moveRowInArray(this.rows, from, to, after);
5210 this.moveRowInArray(this.activeRows, from, to, after);
5211
5212 this.displayRowIterator((rows) => {
5213 this.moveRowInArray(rows, from, to, after);
5214 });
5215
5216 this.dispatch("row-moving", from, to, after);
5217 }
5218
5219 moveRowInArray(rows, from, to, after){
5220 var fromIndex, toIndex, start, end;
5221
5222 if(from !== to){
5223
5224 fromIndex = rows.indexOf(from);
5225
5226 if (fromIndex > -1) {
5227
5228 rows.splice(fromIndex, 1);
5229
5230 toIndex = rows.indexOf(to);
5231
5232 if (toIndex > -1) {
5233
5234 if(after){
5235 rows.splice(toIndex+1, 0, from);
5236 }else {
5237 rows.splice(toIndex, 0, from);
5238 }
5239
5240 }else {
5241 rows.splice(fromIndex, 0, from);
5242 }
5243 }
5244
5245 //restyle rows
5246 if(rows === this.getDisplayRows()){
5247
5248 start = fromIndex < toIndex ? fromIndex : toIndex;
5249 end = toIndex > fromIndex ? toIndex : fromIndex +1;
5250
5251 for(let i = start; i <= end; i++){
5252 if(rows[i]){
5253 this.styleRow(rows[i], i);
5254 }
5255 }
5256 }
5257 }
5258 }
5259
5260 clearData(){
5261 this.setData([]);
5262 }
5263
5264 getRowIndex(row){
5265 return this.findRowIndex(row, this.rows);
5266 }
5267
5268 getDisplayRowIndex(row){
5269 var index = this.getDisplayRows().indexOf(row);
5270 return index > -1 ? index : false;
5271 }
5272
5273 nextDisplayRow(row, rowOnly){
5274 var index = this.getDisplayRowIndex(row),
5275 nextRow = false;
5276
5277
5278 if(index !== false && index < this.displayRowsCount -1){
5279 nextRow = this.getDisplayRows()[index+1];
5280 }
5281
5282 if(nextRow && (!(nextRow instanceof Row) || nextRow.type != "row")){
5283 return this.nextDisplayRow(nextRow, rowOnly);
5284 }
5285
5286 return nextRow;
5287 }
5288
5289 prevDisplayRow(row, rowOnly){
5290 var index = this.getDisplayRowIndex(row),
5291 prevRow = false;
5292
5293 if(index){
5294 prevRow = this.getDisplayRows()[index-1];
5295 }
5296
5297 if(rowOnly && prevRow && (!(prevRow instanceof Row) || prevRow.type != "row")){
5298 return this.prevDisplayRow(prevRow, rowOnly);
5299 }
5300
5301 return prevRow;
5302 }
5303
5304 findRowIndex(row, list){
5305 var rowIndex;
5306
5307 row = this.findRow(row);
5308
5309 if(row){
5310 rowIndex = list.indexOf(row);
5311
5312 if(rowIndex > -1){
5313 return rowIndex;
5314 }
5315 }
5316
5317 return false;
5318 }
5319
5320 getData(active, transform){
5321 var output = [],
5322 rows = this.getRows(active);
5323
5324 rows.forEach(function(row){
5325 if(row.type == "row"){
5326 output.push(row.getData(transform || "data"));
5327 }
5328 });
5329
5330 return output;
5331 }
5332
5333 getComponents(active){
5334 var output = [],
5335 rows = this.getRows(active);
5336
5337 rows.forEach(function(row){
5338 output.push(row.getComponent());
5339 });
5340
5341 return output;
5342 }
5343
5344 getDataCount(active){
5345 var rows = this.getRows(active);
5346
5347 return rows.length;
5348 }
5349
5350 scrollHorizontal(left){
5351 this.scrollLeft = left;
5352 this.element.scrollLeft = left;
5353
5354 this.dispatch("scroll-horizontal", left);
5355 }
5356
5357 registerDataPipelineHandler(handler, priority){
5358 if(typeof priority !== "undefined"){
5359 this.dataPipeline.push({handler, priority});
5360 this.dataPipeline.sort((a, b) => {
5361 return a.priority - b.priority;
5362 });
5363 }else {
5364 console.error("Data pipeline handlers must have a priority in order to be registered");
5365 }
5366 }
5367
5368 registerDisplayPipelineHandler(handler, priority){
5369 if(typeof priority !== "undefined"){
5370 this.displayPipeline.push({handler, priority});
5371 this.displayPipeline.sort((a, b) => {
5372 return a.priority - b.priority;
5373 });
5374 }else {
5375 console.error("Display pipeline handlers must have a priority in order to be registered");
5376 }
5377 }
5378
5379 //set active data set
5380 refreshActiveData(handler, skipStage, renderInPosition){
5381 var table = this.table,
5382 stage = "",
5383 index = 0,
5384 cascadeOrder = ["all", "dataPipeline", "display", "displayPipeline", "end"];
5385
5386 if(!this.table.destroyed){
5387 if(typeof handler === "function"){
5388 index = this.dataPipeline.findIndex((item) => {
5389 return item.handler === handler;
5390 });
5391
5392 if(index > -1){
5393 stage = "dataPipeline";
5394
5395 if(skipStage){
5396 if(index == this.dataPipeline.length - 1){
5397 stage = "display";
5398 }else {
5399 index++;
5400 }
5401 }
5402 }else {
5403 index = this.displayPipeline.findIndex((item) => {
5404 return item.handler === handler;
5405 });
5406
5407 if(index > -1){
5408 stage = "displayPipeline";
5409
5410 if(skipStage){
5411 if(index == this.displayPipeline.length - 1){
5412 stage = "end";
5413 }else {
5414 index++;
5415 }
5416 }
5417 }else {
5418 console.error("Unable to refresh data, invalid handler provided", handler);
5419 return;
5420 }
5421 }
5422 }else {
5423 stage = handler || "all";
5424 index = 0;
5425 }
5426
5427 if(this.redrawBlock){
5428 if(!this.redrawBlockRestoreConfig || (this.redrawBlockRestoreConfig && ((this.redrawBlockRestoreConfig.stage === stage && index < this.redrawBlockRestoreConfig.index) || (cascadeOrder.indexOf(stage) < cascadeOrder.indexOf(this.redrawBlockRestoreConfig.stage))))){
5429 this.redrawBlockRestoreConfig = {
5430 handler: handler,
5431 skipStage: skipStage,
5432 renderInPosition: renderInPosition,
5433 stage:stage,
5434 index:index,
5435 };
5436 }
5437
5438 return;
5439 }else {
5440 if(Helpers.elVisible(this.element)){
5441 if(renderInPosition){
5442 this.reRenderInPosition(this.refreshPipelines.bind(this, handler, stage, index, renderInPosition));
5443 }else {
5444 this.refreshPipelines(handler, stage, index, renderInPosition);
5445
5446 if(!handler){
5447 this.table.columnManager.renderer.renderColumns();
5448 }
5449
5450 this.renderTable();
5451
5452 if(table.options.layoutColumnsOnNewData){
5453 this.table.columnManager.redraw(true);
5454 }
5455 }
5456 }else {
5457 this.refreshPipelines(handler, stage, index, renderInPosition);
5458 }
5459
5460 this.dispatch("data-refreshed");
5461 }
5462 }
5463 }
5464
5465 refreshPipelines(handler, stage, index, renderInPosition){
5466 this.dispatch("data-refreshing");
5467
5468 if(!handler || !this.activeRowsPipeline[0]){
5469 this.activeRowsPipeline[0] = this.rows.slice(0);
5470 }
5471
5472 //cascade through data refresh stages
5473 switch(stage){
5474 case "all":
5475 //handle case where all data needs refreshing
5476
5477 case "dataPipeline":
5478 for(let i = index; i < this.dataPipeline.length; i++){
5479 let result = this.dataPipeline[i].handler(this.activeRowsPipeline[i].slice(0));
5480
5481 this.activeRowsPipeline[i + 1] = result || this.activeRowsPipeline[i].slice(0);
5482 }
5483
5484 this.setActiveRows(this.activeRowsPipeline[this.dataPipeline.length]);
5485
5486 case "display":
5487 index = 0;
5488 this.resetDisplayRows();
5489
5490 case "displayPipeline":
5491 for(let i = index; i < this.displayPipeline.length; i++){
5492 let result = this.displayPipeline[i].handler((i ? this.getDisplayRows(i - 1) : this.activeRows).slice(0), renderInPosition);
5493
5494 this.setDisplayRows(result || this.getDisplayRows(i - 1).slice(0), i);
5495 }
5496
5497 case "end":
5498 //case to handle scenario when trying to skip past end stage
5499 this.regenerateRowPositions();
5500 }
5501
5502 if(this.getDisplayRows().length){
5503 this._clearPlaceholder();
5504 }
5505 }
5506
5507 //regenerate row positions
5508 regenerateRowPositions(){
5509 var rows = this.getDisplayRows();
5510 var index = 1;
5511
5512 rows.forEach((row) => {
5513 if (row.type === "row"){
5514 row.setPosition(index);
5515 index++;
5516 }
5517 });
5518 }
5519
5520 setActiveRows(activeRows){
5521 this.activeRows = this.activeRows = Object.assign([], activeRows);
5522 this.activeRowsCount = this.activeRows.length;
5523 }
5524
5525 //reset display rows array
5526 resetDisplayRows(){
5527 this.displayRows = [];
5528
5529 this.displayRows.push(this.activeRows.slice(0));
5530
5531 this.displayRowsCount = this.displayRows[0].length;
5532 }
5533
5534 //set display row pipeline data
5535 setDisplayRows(displayRows, index){
5536 this.displayRows[index] = displayRows;
5537
5538 if(index == this.displayRows.length -1){
5539 this.displayRowsCount = this.displayRows[this.displayRows.length -1].length;
5540 }
5541 }
5542
5543 getDisplayRows(index){
5544 if(typeof index == "undefined"){
5545 return this.displayRows.length ? this.displayRows[this.displayRows.length -1] : [];
5546 }else {
5547 return this.displayRows[index] || [];
5548 }
5549 }
5550
5551 getVisibleRows(chain, viewable){
5552 var rows = Object.assign([], this.renderer.visibleRows(!viewable));
5553
5554 if(chain){
5555 rows = this.chain("rows-visible", [viewable], rows, rows);
5556 }
5557
5558 return rows;
5559 }
5560
5561 //repeat action across display rows
5562 displayRowIterator(callback){
5563 this.activeRowsPipeline.forEach(callback);
5564 this.displayRows.forEach(callback);
5565
5566 this.displayRowsCount = this.displayRows[this.displayRows.length -1].length;
5567 }
5568
5569 //return only actual rows (not group headers etc)
5570 getRows(type){
5571 var rows = [];
5572
5573 switch(type){
5574 case "active":
5575 rows = this.activeRows;
5576 break;
5577
5578 case "display":
5579 rows = this.table.rowManager.getDisplayRows();
5580 break;
5581
5582 case "visible":
5583 rows = this.getVisibleRows(false, true);
5584 break;
5585
5586 default:
5587 rows = this.chain("rows-retrieve", type, null, this.rows) || this.rows;
5588 }
5589
5590 return rows;
5591 }
5592
5593 ///////////////// Table Rendering /////////////////
5594 //trigger rerender of table in current position
5595 reRenderInPosition(callback){
5596 if(this.redrawBlock){
5597 if(callback){
5598 callback();
5599 }else {
5600 this.redrawBlockRenderInPosition = true;
5601 }
5602 }else {
5603 this.dispatchExternal("renderStarted");
5604
5605 this.renderer.rerenderRows(callback);
5606
5607 if(!this.fixedHeight){
5608 this.adjustTableSize();
5609 }
5610
5611 this.scrollBarCheck();
5612
5613 this.dispatchExternal("renderComplete");
5614 }
5615 }
5616
5617 scrollBarCheck(){
5618 var scrollbarWidth = 0;
5619
5620 //adjust for vertical scrollbar moving table when present
5621 if(this.element.scrollHeight > this.element.clientHeight){
5622 scrollbarWidth = this.element.offsetWidth - this.element.clientWidth;
5623 }
5624
5625 if(scrollbarWidth !== this.scrollbarWidth){
5626 this.scrollbarWidth = scrollbarWidth;
5627 this.dispatch("scrollbar-vertical", scrollbarWidth);
5628 }
5629 }
5630
5631 initializeRenderer(){
5632 var renderClass;
5633
5634 var renderers = {
5635 "virtual": VirtualDomVertical,
5636 "basic": BasicVertical,
5637 };
5638
5639 if(typeof this.table.options.renderVertical === "string"){
5640 renderClass = renderers[this.table.options.renderVertical];
5641 }else {
5642 renderClass = this.table.options.renderVertical;
5643 }
5644
5645 if(renderClass){
5646 this.renderMode = this.table.options.renderVertical;
5647
5648 this.renderer = new renderClass(this.table, this.element, this.tableElement);
5649 this.renderer.initialize();
5650
5651 if((this.table.element.clientHeight || this.table.options.height) && !(this.table.options.minHeight && this.table.options.maxHeight)){
5652 this.fixedHeight = true;
5653 }else {
5654 this.fixedHeight = false;
5655 }
5656 }else {
5657 console.error("Unable to find matching renderer:", this.table.options.renderVertical);
5658 }
5659 }
5660
5661 getRenderMode(){
5662 return this.renderMode;
5663 }
5664
5665 renderTable(){
5666 this.dispatchExternal("renderStarted");
5667
5668 this.element.scrollTop = 0;
5669
5670 this._clearTable();
5671
5672 if(this.displayRowsCount){
5673 this.renderer.renderRows();
5674
5675 if(this.firstRender){
5676 this.firstRender = false;
5677
5678 if(!this.fixedHeight){
5679 this.adjustTableSize();
5680 }
5681
5682 this.layoutRefresh(true);
5683 }
5684 }else {
5685 this.renderEmptyScroll();
5686 }
5687
5688 if(!this.fixedHeight){
5689 this.adjustTableSize();
5690 }
5691
5692 this.dispatch("table-layout");
5693
5694 if(!this.displayRowsCount){
5695 this._showPlaceholder();
5696 }
5697
5698 this.scrollBarCheck();
5699
5700 this.dispatchExternal("renderComplete");
5701 }
5702
5703 //show scrollbars on empty table div
5704 renderEmptyScroll(){
5705 if(this.placeholder){
5706 this.tableElement.style.display = "none";
5707 }else {
5708 this.tableElement.style.minWidth = this.table.columnManager.getWidth() + "px";
5709 // this.tableElement.style.minHeight = "1px";
5710 // this.tableElement.style.visibility = "hidden";
5711 }
5712 }
5713
5714 _clearTable(){
5715 this._clearPlaceholder();
5716
5717 this.scrollTop = 0;
5718 this.scrollLeft = 0;
5719
5720 this.renderer.clearRows();
5721 }
5722
5723 tableEmpty(){
5724 this.renderEmptyScroll();
5725 this._showPlaceholder();
5726 }
5727
5728 checkPlaceholder(){
5729 if(this.displayRowsCount){
5730 this._clearPlaceholder();
5731 }else {
5732 this.tableEmpty();
5733 }
5734 }
5735
5736 _showPlaceholder(){
5737 if(this.placeholder){
5738 if(this.placeholder && this.placeholder.parentNode){
5739 this.placeholder.parentNode.removeChild(this.placeholder);
5740 }
5741
5742 this.initializePlaceholder();
5743
5744 this.placeholder.setAttribute("tabulator-render-mode", this.renderMode);
5745
5746 this.getElement().appendChild(this.placeholder);
5747 this._positionPlaceholder();
5748
5749 this.adjustTableSize();
5750 }
5751 }
5752
5753 _clearPlaceholder(){
5754 if(this.placeholder && this.placeholder.parentNode){
5755 this.placeholder.parentNode.removeChild(this.placeholder);
5756 }
5757
5758 // clear empty table placeholder min
5759 this.tableElement.style.minWidth = "";
5760 this.tableElement.style.display = "";
5761 }
5762
5763 _positionPlaceholder(){
5764 if(this.placeholder && this.placeholder.parentNode){
5765 this.placeholder.style.width = this.table.columnManager.getWidth() + "px";
5766 this.placeholderContents.style.width = this.table.rowManager.element.clientWidth + "px";
5767 this.placeholderContents.style.marginLeft = this.scrollLeft + "px";
5768 }
5769 }
5770
5771 styleRow(row, index){
5772 var rowEl = row.getElement();
5773
5774 if(index % 2){
5775 rowEl.classList.add("tabulator-row-even");
5776 rowEl.classList.remove("tabulator-row-odd");
5777 }else {
5778 rowEl.classList.add("tabulator-row-odd");
5779 rowEl.classList.remove("tabulator-row-even");
5780 }
5781 }
5782
5783 //normalize height of active rows
5784 normalizeHeight(force){
5785 this.activeRows.forEach(function(row){
5786 row.normalizeHeight(force);
5787 });
5788 }
5789
5790 //adjust the height of the table holder to fit in the Tabulator element
5791 adjustTableSize(){
5792 let initialHeight = this.element.clientHeight, minHeight;
5793 let resized = false;
5794
5795 if(this.renderer.verticalFillMode === "fill"){
5796 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));
5797
5798 if(this.fixedHeight){
5799 minHeight = isNaN(this.table.options.minHeight) ? this.table.options.minHeight : this.table.options.minHeight + "px";
5800
5801 const height = "calc(100% - " + otherHeight + "px)";
5802 this.element.style.minHeight = minHeight || "calc(100% - " + otherHeight + "px)";
5803 this.element.style.height = height;
5804 this.element.style.maxHeight = height;
5805 } else {
5806 this.element.style.height = "";
5807 this.element.style.height =
5808 this.table.element.clientHeight - otherHeight + "px";
5809 this.element.scrollTop = this.scrollTop;
5810 }
5811
5812 this.renderer.resize();
5813
5814 //check if the table has changed size when dealing with variable height tables
5815 if(!this.fixedHeight && initialHeight != this.element.clientHeight){
5816 resized = true;
5817 if(!this.redrawing){ // prevent recursive redraws
5818 this.redrawing = true;
5819 if(this.subscribed("table-resize")){
5820 this.dispatch("table-resize");
5821 }else {
5822 this.redraw();
5823 }
5824 this.redrawing = false;
5825 }
5826 }
5827
5828 this.scrollBarCheck();
5829 }
5830
5831 this._positionPlaceholder();
5832 return resized;
5833 }
5834
5835 //reinitialize all rows
5836 reinitialize(){
5837 this.rows.forEach(function(row){
5838 row.reinitialize(true);
5839 });
5840 }
5841
5842 //prevent table from being redrawn
5843 blockRedraw (){
5844 this.redrawBlock = true;
5845 this.redrawBlockRestoreConfig = false;
5846 }
5847
5848 //restore table redrawing
5849 restoreRedraw (){
5850 this.redrawBlock = false;
5851
5852 if(this.redrawBlockRestoreConfig){
5853 this.refreshActiveData(this.redrawBlockRestoreConfig.handler, this.redrawBlockRestoreConfig.skipStage, this.redrawBlockRestoreConfig.renderInPosition);
5854
5855 this.redrawBlockRestoreConfig = false;
5856 }else {
5857 if(this.redrawBlockRenderInPosition){
5858 this.reRenderInPosition();
5859 }
5860 }
5861
5862 this.redrawBlockRenderInPosition = false;
5863 }
5864
5865 //redraw table
5866 redraw (force){
5867 this.adjustTableSize();
5868 this.table.tableWidth = this.table.element.clientWidth;
5869
5870 if(!force){
5871 this.reRenderInPosition();
5872 this.scrollHorizontal(this.scrollLeft);
5873 }else {
5874 this.renderTable();
5875 }
5876 }
5877
5878 resetScroll(){
5879 this.element.scrollLeft = 0;
5880 this.element.scrollTop = 0;
5881
5882 if(this.table.browser === "ie"){
5883 var event = document.createEvent("Event");
5884 event.initEvent("scroll", false, true);
5885 this.element.dispatchEvent(event);
5886 }else {
5887 this.element.dispatchEvent(new Event('scroll'));
5888 }
5889 }
5890 }
5891
5892 class FooterManager extends CoreFeature{
5893
5894 constructor(table){
5895 super(table);
5896
5897 this.active = false;
5898 this.element = this.createElement(); //containing element
5899 this.containerElement = this.createContainerElement(); //containing element
5900 this.external = false;
5901 }
5902
5903 initialize(){
5904 this.initializeElement();
5905 }
5906
5907 createElement(){
5908 var el = document.createElement("div");
5909
5910 el.classList.add("tabulator-footer");
5911
5912 return el;
5913 }
5914
5915
5916 createContainerElement(){
5917 var el = document.createElement("div");
5918
5919 el.classList.add("tabulator-footer-contents");
5920
5921 this.element.appendChild(el);
5922
5923 return el;
5924 }
5925
5926 initializeElement(){
5927 if(this.table.options.footerElement){
5928
5929 switch(typeof this.table.options.footerElement){
5930 case "string":
5931 if(this.table.options.footerElement[0] === "<"){
5932 this.containerElement.innerHTML = this.table.options.footerElement;
5933 }else {
5934 this.external = true;
5935 this.containerElement = document.querySelector(this.table.options.footerElement);
5936 }
5937 break;
5938
5939 default:
5940 this.element = this.table.options.footerElement;
5941 break;
5942 }
5943 }
5944 }
5945
5946 getElement(){
5947 return this.element;
5948 }
5949
5950 append(element){
5951 this.activate();
5952
5953 this.containerElement.appendChild(element);
5954 this.table.rowManager.adjustTableSize();
5955 }
5956
5957 prepend(element){
5958 this.activate();
5959
5960 this.element.insertBefore(element, this.element.firstChild);
5961 this.table.rowManager.adjustTableSize();
5962 }
5963
5964 remove(element){
5965 element.parentNode.removeChild(element);
5966 this.deactivate();
5967 }
5968
5969 deactivate(force){
5970 if(!this.element.firstChild || force){
5971 if(!this.external){
5972 this.element.parentNode.removeChild(this.element);
5973 }
5974 this.active = false;
5975 }
5976 }
5977
5978 activate(){
5979 if(!this.active){
5980 this.active = true;
5981 if(!this.external){
5982 this.table.element.appendChild(this.getElement());
5983 this.table.element.style.display = '';
5984 }
5985 }
5986 }
5987
5988 redraw(){
5989 this.dispatch("footer-redraw");
5990 }
5991 }
5992
5993 class InteractionManager extends CoreFeature {
5994
5995 constructor (table){
5996 super(table);
5997
5998 this.el = null;
5999
6000 this.abortClasses = ["tabulator-headers", "tabulator-table"];
6001
6002 this.previousTargets = {};
6003
6004 this.listeners = [
6005 "click",
6006 "dblclick",
6007 "contextmenu",
6008 "mouseenter",
6009 "mouseleave",
6010 "mouseover",
6011 "mouseout",
6012 "mousemove",
6013 "mouseup",
6014 "mousedown",
6015 "touchstart",
6016 "touchend",
6017 ];
6018
6019 this.componentMap = {
6020 "tabulator-cell":"cell",
6021 "tabulator-row":"row",
6022 "tabulator-group":"group",
6023 "tabulator-col":"column",
6024 };
6025
6026 this.pseudoTrackers = {
6027 "row":{
6028 subscriber:null,
6029 target:null,
6030 },
6031 "cell":{
6032 subscriber:null,
6033 target:null,
6034 },
6035 "group":{
6036 subscriber:null,
6037 target:null,
6038 },
6039 "column":{
6040 subscriber:null,
6041 target:null,
6042 },
6043 };
6044
6045 this.pseudoTracking = false;
6046 }
6047
6048 initialize(){
6049 this.el = this.table.element;
6050
6051 this.buildListenerMap();
6052 this.bindSubscriptionWatchers();
6053 }
6054
6055 buildListenerMap(){
6056 var listenerMap = {};
6057
6058 this.listeners.forEach((listener) => {
6059 listenerMap[listener] = {
6060 handler:null,
6061 components:[],
6062 };
6063 });
6064
6065 this.listeners = listenerMap;
6066 }
6067
6068 bindPseudoEvents(){
6069 Object.keys(this.pseudoTrackers).forEach((key) => {
6070 this.pseudoTrackers[key].subscriber = this.pseudoMouseEnter.bind(this, key);
6071 this.subscribe(key + "-mouseover", this.pseudoTrackers[key].subscriber);
6072 });
6073
6074 this.pseudoTracking = true;
6075 }
6076
6077 pseudoMouseEnter(key, e, target){
6078 if(this.pseudoTrackers[key].target !== target){
6079
6080 if(this.pseudoTrackers[key].target){
6081 this.dispatch(key + "-mouseleave", e, this.pseudoTrackers[key].target);
6082 }
6083
6084 this.pseudoMouseLeave(key, e);
6085
6086 this.pseudoTrackers[key].target = target;
6087
6088 this.dispatch(key + "-mouseenter", e, target);
6089 }
6090 }
6091
6092 pseudoMouseLeave(key, e){
6093 var leaveList = Object.keys(this.pseudoTrackers),
6094 linkedKeys = {
6095 "row":["cell"],
6096 "cell":["row"],
6097 };
6098
6099 leaveList = leaveList.filter((item) => {
6100 var links = linkedKeys[key];
6101 return item !== key && (!links || (links && !links.includes(item)));
6102 });
6103
6104
6105 leaveList.forEach((key) => {
6106 var target = this.pseudoTrackers[key].target;
6107
6108 if(this.pseudoTrackers[key].target){
6109 this.dispatch(key + "-mouseleave", e, target);
6110
6111 this.pseudoTrackers[key].target = null;
6112 }
6113 });
6114 }
6115
6116
6117 bindSubscriptionWatchers(){
6118 var listeners = Object.keys(this.listeners),
6119 components = Object.values(this.componentMap);
6120
6121 for(let comp of components){
6122 for(let listener of listeners){
6123 let key = comp + "-" + listener;
6124
6125 this.subscriptionChange(key, this.subscriptionChanged.bind(this, comp, listener));
6126 }
6127 }
6128
6129 this.subscribe("table-destroy", this.clearWatchers.bind(this));
6130 }
6131
6132 subscriptionChanged(component, key, added){
6133 var listener = this.listeners[key].components,
6134 index = listener.indexOf(component),
6135 changed = false;
6136
6137 if(added){
6138 if(index === -1){
6139 listener.push(component);
6140 changed = true;
6141 }
6142 }else {
6143 if(!this.subscribed(component + "-" + key)){
6144 if(index > -1){
6145 listener.splice(index, 1);
6146 changed = true;
6147 }
6148 }
6149 }
6150
6151 if((key === "mouseenter" || key === "mouseleave") && !this.pseudoTracking){
6152 this.bindPseudoEvents();
6153 }
6154
6155 if(changed){
6156 this.updateEventListeners();
6157 }
6158 }
6159
6160 updateEventListeners(){
6161 for(let key in this.listeners){
6162 let listener = this.listeners[key];
6163
6164 if(listener.components.length){
6165 if(!listener.handler){
6166 listener.handler = this.track.bind(this, key);
6167 this.el.addEventListener(key, listener.handler);
6168 // this.el.addEventListener(key, listener.handler, {passive: true})
6169 }
6170 }else {
6171 if(listener.handler){
6172 this.el.removeEventListener(key, listener.handler);
6173 listener.handler = null;
6174 }
6175 }
6176 }
6177 }
6178
6179 track(type, e){
6180 var path = (e.composedPath && e.composedPath()) || e.path;
6181
6182 var targets = this.findTargets(path);
6183 targets = this.bindComponents(type, targets);
6184
6185 this.triggerEvents(type, e, targets);
6186
6187 if(this.pseudoTracking && (type == "mouseover" || type == "mouseleave") && !Object.keys(targets).length){
6188 this.pseudoMouseLeave("none", e);
6189 }
6190 }
6191
6192 findTargets(path){
6193 var targets = {};
6194
6195 let componentMap = Object.keys(this.componentMap);
6196
6197 for (let el of path) {
6198 let classList = el.classList ? [...el.classList] : [];
6199
6200 let abort = classList.filter((item) => {
6201 return this.abortClasses.includes(item);
6202 });
6203
6204 if(abort.length){
6205 break;
6206 }
6207
6208 let elTargets = classList.filter((item) => {
6209 return componentMap.includes(item);
6210 });
6211
6212 for (let target of elTargets) {
6213 if(!targets[this.componentMap[target]]){
6214 targets[this.componentMap[target]] = el;
6215 }
6216 }
6217 }
6218
6219 if(targets.group && targets.group === targets.row){
6220 delete targets.row;
6221 }
6222
6223 return targets;
6224 }
6225
6226 bindComponents(type, targets){
6227 //ensure row component is looked up before cell
6228 var keys = Object.keys(targets).reverse(),
6229 listener = this.listeners[type],
6230 matches = {},
6231 output = {},
6232 targetMatches = {};
6233
6234 for(let key of keys){
6235 let component,
6236 target = targets[key],
6237 previousTarget = this.previousTargets[key];
6238
6239 if(previousTarget && previousTarget.target === target){
6240 component = previousTarget.component;
6241 }else {
6242 switch(key){
6243 case "row":
6244 case "group":
6245 if(listener.components.includes("row") || listener.components.includes("cell") || listener.components.includes("group")){
6246 let rows = this.table.rowManager.getVisibleRows(true);
6247
6248 component = rows.find((row) => {
6249 return row.getElement() === target;
6250 });
6251
6252 if(targets["row"] && targets["row"].parentNode && targets["row"].parentNode.closest(".tabulator-row")){
6253 targets[key] = false;
6254 }
6255 }
6256 break;
6257
6258 case "column":
6259 if(listener.components.includes("column")){
6260 component = this.table.columnManager.findColumn(target);
6261 }
6262 break;
6263
6264 case "cell":
6265 if(listener.components.includes("cell")){
6266 if(matches["row"] instanceof Row){
6267 component = matches["row"].findCell(target);
6268 }else {
6269 if(targets["row"]){
6270 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?");
6271 }
6272 }
6273 }
6274 break;
6275 }
6276 }
6277
6278 if(component){
6279 matches[key] = component;
6280 targetMatches[key] = {
6281 target:target,
6282 component:component,
6283 };
6284 }
6285 }
6286
6287 this.previousTargets = targetMatches;
6288
6289 //reverse order keys are set in so events trigger in correct sequence
6290 Object.keys(targets).forEach((key) => {
6291 let value = matches[key];
6292 output[key] = value;
6293 });
6294
6295 return output;
6296 }
6297
6298 triggerEvents(type, e, targets){
6299 var listener = this.listeners[type];
6300
6301 for(let key in targets){
6302 if(targets[key] && listener.components.includes(key)){
6303 this.dispatch(key + "-" + type, e, targets[key]);
6304 }
6305 }
6306 }
6307
6308 clearWatchers(){
6309 for(let key in this.listeners){
6310 let listener = this.listeners[key];
6311
6312 if(listener.handler){
6313 this.el.removeEventListener(key, listener.handler);
6314 listener.handler = null;
6315 }
6316 }
6317 }
6318 }
6319
6320 class ComponentFunctionBinder{
6321
6322 constructor(table){
6323 this.table = table;
6324
6325 this.bindings = {};
6326 }
6327
6328 bind(type, funcName, handler){
6329 if(!this.bindings[type]){
6330 this.bindings[type] = {};
6331 }
6332
6333 if(this.bindings[type][funcName]){
6334 console.warn("Unable to bind component handler, a matching function name is already bound", type, funcName, handler);
6335 }else {
6336 this.bindings[type][funcName] = handler;
6337 }
6338 }
6339
6340 handle(type, component, name){
6341 if(this.bindings[type] && this.bindings[type][name] && typeof this.bindings[type][name].bind === 'function'){
6342 return this.bindings[type][name].bind(null, component);
6343 }else {
6344 if(name !== "then" && typeof name === "string" && !name.startsWith("_")){
6345 if(this.table.options.debugInvalidComponentFuncs){
6346 console.error("The " + type + " component does not have a " + name + " function, have you checked that you have the correct Tabulator module installed?");
6347 }
6348 }
6349 }
6350 }
6351 }
6352
6353 class DataLoader extends CoreFeature{
6354 constructor(table){
6355 super(table);
6356
6357 this.requestOrder = 0; //prevent requests coming out of sequence if overridden by another load request
6358 this.loading = false;
6359 }
6360
6361 initialize(){}
6362
6363 load(data, params, config, replace, silent, columnsChanged){
6364 var requestNo = ++this.requestOrder;
6365
6366 if(this.table.destroyed){
6367 return Promise.resolve();
6368 }
6369
6370 this.dispatchExternal("dataLoading", data);
6371
6372 //parse json data to array
6373 if (data && (data.indexOf("{") == 0 || data.indexOf("[") == 0)){
6374 data = JSON.parse(data);
6375 }
6376
6377 if(this.confirm("data-loading", [data, params, config, silent])){
6378 this.loading = true;
6379
6380 if(!silent){
6381 this.alertLoader();
6382 }
6383
6384 //get params for request
6385 params = this.chain("data-params", [data, config, silent], params || {}, params || {});
6386
6387 params = this.mapParams(params, this.table.options.dataSendParams);
6388
6389 var result = this.chain("data-load", [data, params, config, silent], false, Promise.resolve([]));
6390
6391 return result.then((response) => {
6392 if(!this.table.destroyed){
6393 if(!Array.isArray(response) && typeof response == "object"){
6394 response = this.mapParams(response, this.objectInvert(this.table.options.dataReceiveParams));
6395 }
6396
6397 var rowData = this.chain("data-loaded", [response], null, response);
6398
6399 if(requestNo == this.requestOrder){
6400 this.clearAlert();
6401
6402 if(rowData !== false){
6403 this.dispatchExternal("dataLoaded", rowData);
6404 this.table.rowManager.setData(rowData, replace, typeof columnsChanged === "undefined" ? !replace : columnsChanged);
6405 }
6406 }else {
6407 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");
6408 }
6409 }else {
6410 console.warn("Data Load Response Blocked - Table has been destroyed");
6411 }
6412 }).catch((error) => {
6413 console.error("Data Load Error: ", error);
6414 this.dispatchExternal("dataLoadError", error);
6415
6416 if(!silent){
6417 this.alertError();
6418 }
6419
6420 setTimeout(() => {
6421 this.clearAlert();
6422 }, this.table.options.dataLoaderErrorTimeout);
6423 })
6424 .finally(() => {
6425 this.loading = false;
6426 });
6427 }else {
6428 this.dispatchExternal("dataLoaded", data);
6429
6430 if(!data){
6431 data = [];
6432 }
6433
6434 this.table.rowManager.setData(data, replace, typeof columnsChanged === "undefined" ? !replace : columnsChanged);
6435 return Promise.resolve();
6436 }
6437 }
6438
6439 mapParams(params, map){
6440 var output = {};
6441
6442 for(let key in params){
6443 output[map.hasOwnProperty(key) ? map[key] : key] = params[key];
6444 }
6445
6446 return output;
6447 }
6448
6449 objectInvert(obj){
6450 var output = {};
6451
6452 for(let key in obj){
6453 output[obj[key]] = key;
6454 }
6455
6456 return output;
6457 }
6458
6459 blockActiveLoad(){
6460 this.requestOrder++;
6461 }
6462
6463 alertLoader(){
6464 var shouldLoad = typeof this.table.options.dataLoader === "function" ? this.table.options.dataLoader() : this.table.options.dataLoader;
6465
6466 if(shouldLoad){
6467 this.table.alertManager.alert(this.table.options.dataLoaderLoading || this.langText("data|loading"));
6468 }
6469 }
6470
6471 alertError(){
6472 this.table.alertManager.alert(this.table.options.dataLoaderError || this.langText("data|error"), "error");
6473 }
6474
6475 clearAlert(){
6476 this.table.alertManager.clear();
6477 }
6478 }
6479
6480 class ExternalEventBus {
6481
6482 constructor(table, optionsList, debug){
6483 this.table = table;
6484 this.events = {};
6485 this.optionsList = optionsList || {};
6486 this.subscriptionNotifiers = {};
6487
6488 this.dispatch = debug ? this._debugDispatch.bind(this) : this._dispatch.bind(this);
6489 this.debug = debug;
6490 }
6491
6492 subscriptionChange(key, callback){
6493 if(!this.subscriptionNotifiers[key]){
6494 this.subscriptionNotifiers[key] = [];
6495 }
6496
6497 this.subscriptionNotifiers[key].push(callback);
6498
6499 if(this.subscribed(key)){
6500 this._notifySubscriptionChange(key, true);
6501 }
6502 }
6503
6504 subscribe(key, callback){
6505 if(!this.events[key]){
6506 this.events[key] = [];
6507 }
6508
6509 this.events[key].push(callback);
6510
6511 this._notifySubscriptionChange(key, true);
6512 }
6513
6514 unsubscribe(key, callback){
6515 var index;
6516
6517 if(this.events[key]){
6518 if(callback){
6519 index = this.events[key].findIndex((item) => {
6520 return item === callback;
6521 });
6522
6523 if(index > -1){
6524 this.events[key].splice(index, 1);
6525 }else {
6526 console.warn("Cannot remove event, no matching event found:", key, callback);
6527 return;
6528 }
6529 }else {
6530 delete this.events[key];
6531 }
6532 }else {
6533 console.warn("Cannot remove event, no events set on:", key);
6534 return;
6535 }
6536
6537 this._notifySubscriptionChange(key, false);
6538 }
6539
6540 subscribed(key){
6541 return this.events[key] && this.events[key].length;
6542 }
6543
6544 _notifySubscriptionChange(key, subscribed){
6545 var notifiers = this.subscriptionNotifiers[key];
6546
6547 if(notifiers){
6548 notifiers.forEach((callback)=>{
6549 callback(subscribed);
6550 });
6551 }
6552 }
6553
6554 _dispatch(){
6555 var args = Array.from(arguments),
6556 key = args.shift(),
6557 result;
6558
6559 if(this.events[key]){
6560 this.events[key].forEach((callback, i) => {
6561 let callResult = callback.apply(this.table, args);
6562
6563 if(!i){
6564 result = callResult;
6565 }
6566 });
6567 }
6568
6569 return result;
6570 }
6571
6572 _debugDispatch(){
6573 var args = Array.from(arguments),
6574 key = args[0];
6575
6576 args[0] = "ExternalEvent:" + args[0];
6577
6578 if(this.debug === true || this.debug.includes(key)){
6579 console.log(...args);
6580 }
6581
6582 return this._dispatch(...arguments);
6583 }
6584 }
6585
6586 class InternalEventBus {
6587
6588 constructor(debug){
6589 this.events = {};
6590 this.subscriptionNotifiers = {};
6591
6592 this.dispatch = debug ? this._debugDispatch.bind(this) : this._dispatch.bind(this);
6593 this.chain = debug ? this._debugChain.bind(this) : this._chain.bind(this);
6594 this.confirm = debug ? this._debugConfirm.bind(this) : this._confirm.bind(this);
6595 this.debug = debug;
6596 }
6597
6598 subscriptionChange(key, callback){
6599 if(!this.subscriptionNotifiers[key]){
6600 this.subscriptionNotifiers[key] = [];
6601 }
6602
6603 this.subscriptionNotifiers[key].push(callback);
6604
6605 if(this.subscribed(key)){
6606 this._notifySubscriptionChange(key, true);
6607 }
6608 }
6609
6610 subscribe(key, callback, priority = 10000){
6611 if(!this.events[key]){
6612 this.events[key] = [];
6613 }
6614
6615 this.events[key].push({callback, priority});
6616
6617 this.events[key].sort((a, b) => {
6618 return a.priority - b.priority;
6619 });
6620
6621 this._notifySubscriptionChange(key, true);
6622 }
6623
6624 unsubscribe(key, callback){
6625 var index;
6626
6627 if(this.events[key]){
6628 if(callback){
6629 index = this.events[key].findIndex((item) => {
6630 return item.callback === callback;
6631 });
6632
6633 if(index > -1){
6634 this.events[key].splice(index, 1);
6635 }else {
6636 console.warn("Cannot remove event, no matching event found:", key, callback);
6637 return;
6638 }
6639 }
6640 }else {
6641 console.warn("Cannot remove event, no events set on:", key);
6642 return;
6643 }
6644
6645 this._notifySubscriptionChange(key, false);
6646 }
6647
6648 subscribed(key){
6649 return this.events[key] && this.events[key].length;
6650 }
6651
6652 _chain(key, args, initialValue, fallback){
6653 var value = initialValue;
6654
6655 if(!Array.isArray(args)){
6656 args = [args];
6657 }
6658
6659 if(this.subscribed(key)){
6660 this.events[key].forEach((subscriber, i) => {
6661 value = subscriber.callback.apply(this, args.concat([value]));
6662 });
6663
6664 return value;
6665 }else {
6666 return typeof fallback === "function" ? fallback() : fallback;
6667 }
6668 }
6669
6670 _confirm(key, args){
6671 var confirmed = false;
6672
6673 if(!Array.isArray(args)){
6674 args = [args];
6675 }
6676
6677 if(this.subscribed(key)){
6678 this.events[key].forEach((subscriber, i) => {
6679 if(subscriber.callback.apply(this, args)){
6680 confirmed = true;
6681 }
6682 });
6683 }
6684
6685 return confirmed;
6686 }
6687
6688 _notifySubscriptionChange(key, subscribed){
6689 var notifiers = this.subscriptionNotifiers[key];
6690
6691 if(notifiers){
6692 notifiers.forEach((callback)=>{
6693 callback(subscribed);
6694 });
6695 }
6696 }
6697
6698 _dispatch(){
6699 var args = Array.from(arguments),
6700 key = args.shift();
6701
6702 if(this.events[key]){
6703 this.events[key].forEach((subscriber) => {
6704 subscriber.callback.apply(this, args);
6705 });
6706 }
6707 }
6708
6709 _debugDispatch(){
6710 var args = Array.from(arguments),
6711 key = args[0];
6712
6713 args[0] = "InternalEvent:" + key;
6714
6715 if(this.debug === true || this.debug.includes(key)){
6716 console.log(...args);
6717 }
6718
6719 return this._dispatch(...arguments);
6720 }
6721
6722 _debugChain(){
6723 var args = Array.from(arguments),
6724 key = args[0];
6725
6726 args[0] = "InternalEvent:" + key;
6727
6728 if(this.debug === true || this.debug.includes(key)){
6729 console.log(...args);
6730 }
6731
6732 return this._chain(...arguments);
6733 }
6734
6735 _debugConfirm(){
6736 var args = Array.from(arguments),
6737 key = args[0];
6738
6739 args[0] = "InternalEvent:" + key;
6740
6741 if(this.debug === true || this.debug.includes(key)){
6742 console.log(...args);
6743 }
6744
6745 return this._confirm(...arguments);
6746 }
6747 }
6748
6749 class DeprecationAdvisor extends CoreFeature{
6750
6751 constructor(table){
6752 super(table);
6753 }
6754
6755 _warnUser(){
6756 if(this.options("debugDeprecation")){
6757 console.warn(...arguments);
6758 }
6759 }
6760
6761 check(oldOption, newOption, convert){
6762 var msg = "";
6763
6764 if(typeof this.options(oldOption) !== "undefined"){
6765 msg = "Deprecated Setup Option - Use of the %c" + oldOption + "%c option is now deprecated";
6766
6767 if(newOption){
6768 msg = msg + ", Please use the %c" + newOption + "%c option instead";
6769 this._warnUser(msg, 'font-weight: bold;', 'font-weight: normal;', 'font-weight: bold;', 'font-weight: normal;');
6770
6771 if(convert){
6772 this.table.options[newOption] = this.table.options[oldOption];
6773 }
6774 }else {
6775 this._warnUser(msg, 'font-weight: bold;', 'font-weight: normal;');
6776 }
6777
6778 return false;
6779 }else {
6780 return true;
6781 }
6782 }
6783
6784 checkMsg(oldOption, msg){
6785 if(typeof this.options(oldOption) !== "undefined"){
6786 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;');
6787
6788 return false;
6789 }else {
6790 return true;
6791 }
6792 }
6793
6794 msg(msg){
6795 this._warnUser(msg);
6796 }
6797 }
6798
6799 class DependencyRegistry extends CoreFeature{
6800
6801 constructor(table){
6802 super(table);
6803
6804 this.deps = {};
6805
6806 this.props = {
6807
6808 };
6809 }
6810
6811 initialize(){
6812 this.deps = Object.assign({}, this.options("dependencies"));
6813 }
6814
6815 lookup(key, prop, silent){
6816 if(Array.isArray(key)){
6817 for (const item of key) {
6818 var match = this.lookup(item, prop, true);
6819
6820 if(match){
6821 break;
6822 }
6823 }
6824
6825 if(match){
6826 return match;
6827 }else {
6828 this.error(key);
6829 }
6830 }else {
6831 if(prop){
6832 return this.lookupProp(key, prop, silent);
6833 }else {
6834 return this.lookupKey(key, silent);
6835 }
6836 }
6837 }
6838
6839 lookupProp(key, prop, silent){
6840 var dependency;
6841
6842 if(this.props[key] && this.props[key][prop]){
6843 return this.props[key][prop];
6844 }else {
6845 dependency = this.lookupKey(key, silent);
6846
6847 if(dependency){
6848 if(!this.props[key]){
6849 this.props[key] = {};
6850 }
6851
6852 this.props[key][prop] = dependency[prop] || dependency;
6853 return this.props[key][prop];
6854 }
6855 }
6856 }
6857
6858 lookupKey(key, silent){
6859 var dependency;
6860
6861 if(this.deps[key]){
6862 dependency = this.deps[key];
6863 }else if(window[key]){
6864 this.deps[key] = window[key];
6865 dependency = this.deps[key];
6866 }else {
6867 if(!silent){
6868 this.error(key);
6869 }
6870 }
6871
6872 return dependency;
6873 }
6874
6875 error(key){
6876 console.error("Unable to find dependency", key, "Please check documentation and ensure you have imported the required library into your project");
6877 }
6878 }
6879
6880 let Popup$1 = class Popup extends CoreFeature{
6881 constructor(table, element, parent){
6882 super(table);
6883
6884 this.element = element;
6885 this.container = this._lookupContainer();
6886
6887 this.parent = parent;
6888
6889 this.reversedX = false;
6890 this.childPopup = null;
6891 this.blurable = false;
6892 this.blurCallback = null;
6893 this.blurEventsBound = false;
6894 this.renderedCallback = null;
6895
6896 this.visible = false;
6897 this.hideable = true;
6898
6899 this.element.classList.add("tabulator-popup-container");
6900
6901 this.blurEvent = this.hide.bind(this, false);
6902 this.escEvent = this._escapeCheck.bind(this);
6903
6904 this.destroyBinding = this.tableDestroyed.bind(this);
6905 this.destroyed = false;
6906 }
6907
6908 tableDestroyed(){
6909 this.destroyed = true;
6910 this.hide(true);
6911 }
6912
6913 _lookupContainer(){
6914 var container = this.table.options.popupContainer;
6915
6916 if(typeof container === "string"){
6917 container = document.querySelector(container);
6918
6919 if(!container){
6920 console.warn("Menu Error - no container element found matching selector:", this.table.options.popupContainer , "(defaulting to document body)");
6921 }
6922 }else if (container === true){
6923 container = this.table.element;
6924 }
6925
6926 if(container && !this._checkContainerIsParent(container)){
6927 container = false;
6928 console.warn("Menu Error - container element does not contain this table:", this.table.options.popupContainer , "(defaulting to document body)");
6929 }
6930
6931 if(!container){
6932 container = document.body;
6933 }
6934
6935 return container;
6936 }
6937
6938 _checkContainerIsParent(container, element = this.table.element){
6939 if(container === element){
6940 return true;
6941 }else {
6942 return element.parentNode ? this._checkContainerIsParent(container, element.parentNode) : false;
6943 }
6944 }
6945
6946 renderCallback(callback){
6947 this.renderedCallback = callback;
6948 }
6949
6950 containerEventCoords(e){
6951 var touch = !(e instanceof MouseEvent);
6952
6953 var x = touch ? e.touches[0].pageX : e.pageX;
6954 var y = touch ? e.touches[0].pageY : e.pageY;
6955
6956 if(this.container !== document.body){
6957 let parentOffset = Helpers.elOffset(this.container);
6958
6959 x -= parentOffset.left;
6960 y -= parentOffset.top;
6961 }
6962
6963 return {x, y};
6964 }
6965
6966 elementPositionCoords(element, position = "right"){
6967 var offset = Helpers.elOffset(element),
6968 containerOffset, x, y;
6969
6970 if(this.container !== document.body){
6971 containerOffset = Helpers.elOffset(this.container);
6972
6973 offset.left -= containerOffset.left;
6974 offset.top -= containerOffset.top;
6975 }
6976
6977 switch(position){
6978 case "right":
6979 x = offset.left + element.offsetWidth;
6980 y = offset.top - 1;
6981 break;
6982
6983 case "bottom":
6984 x = offset.left;
6985 y = offset.top + element.offsetHeight;
6986 break;
6987
6988 case "left":
6989 x = offset.left;
6990 y = offset.top - 1;
6991 break;
6992
6993 case "top":
6994 x = offset.left;
6995 y = offset.top;
6996 break;
6997
6998 case "center":
6999 x = offset.left + (element.offsetWidth / 2);
7000 y = offset.top + (element.offsetHeight / 2);
7001 break;
7002
7003 }
7004
7005 return {x, y, offset};
7006 }
7007
7008 show(origin, position){
7009 var x, y, parentEl, parentOffset, coords;
7010
7011 if(this.destroyed || this.table.destroyed){
7012 return this;
7013 }
7014
7015 if(origin instanceof HTMLElement){
7016 parentEl = origin;
7017 coords = this.elementPositionCoords(origin, position);
7018
7019 parentOffset = coords.offset;
7020 x = coords.x;
7021 y = coords.y;
7022
7023 }else if(typeof origin === "number"){
7024 parentOffset = {top:0, left:0};
7025 x = origin;
7026 y = position;
7027 }else {
7028 coords = this.containerEventCoords(origin);
7029
7030 x = coords.x;
7031 y = coords.y;
7032
7033 this.reversedX = false;
7034 }
7035
7036 this.element.style.top = y + "px";
7037 this.element.style.left = x + "px";
7038
7039 this.container.appendChild(this.element);
7040
7041 if(typeof this.renderedCallback === "function"){
7042 this.renderedCallback();
7043 }
7044
7045 this._fitToScreen(x, y, parentEl, parentOffset, position);
7046
7047 this.visible = true;
7048
7049 this.subscribe("table-destroy", this.destroyBinding);
7050
7051 this.element.addEventListener("mousedown", (e) => {
7052 e.stopPropagation();
7053 });
7054
7055 return this;
7056 }
7057
7058 _fitToScreen(x, y, parentEl, parentOffset, position){
7059 var scrollTop = this.container === document.body ? document.documentElement.scrollTop : this.container.scrollTop;
7060
7061 //move menu to start on right edge if it is too close to the edge of the screen
7062 if((x + this.element.offsetWidth) >= this.container.offsetWidth || this.reversedX){
7063 this.element.style.left = "";
7064
7065 if(parentEl){
7066 this.element.style.right = (this.container.offsetWidth - parentOffset.left) + "px";
7067 }else {
7068 this.element.style.right = (this.container.offsetWidth - x) + "px";
7069 }
7070
7071 this.reversedX = true;
7072 }
7073
7074 //move menu to start on bottom edge if it is too close to the edge of the screen
7075 let offsetHeight = Math.max(this.container.offsetHeight, scrollTop ? this.container.scrollHeight : 0);
7076 if((y + this.element.offsetHeight) > offsetHeight) {
7077 if(parentEl){
7078 switch(position){
7079 case "bottom":
7080 this.element.style.top = (parseInt(this.element.style.top) - this.element.offsetHeight - parentEl.offsetHeight - 1) + "px";
7081 break;
7082
7083 default:
7084 this.element.style.top = (parseInt(this.element.style.top) - this.element.offsetHeight + parentEl.offsetHeight + 1) + "px";
7085 }
7086
7087 }else {
7088 this.element.style.height = offsetHeight + "px";
7089 }
7090 }
7091 }
7092
7093 isVisible(){
7094 return this.visible;
7095 }
7096
7097 hideOnBlur(callback){
7098 this.blurable = true;
7099
7100 if(this.visible){
7101 setTimeout(() => {
7102 if(this.visible){
7103 this.table.rowManager.element.addEventListener("scroll", this.blurEvent);
7104 this.subscribe("cell-editing", this.blurEvent);
7105 document.body.addEventListener("click", this.blurEvent);
7106 document.body.addEventListener("contextmenu", this.blurEvent);
7107 document.body.addEventListener("mousedown", this.blurEvent);
7108 window.addEventListener("resize", this.blurEvent);
7109 document.body.addEventListener("keydown", this.escEvent);
7110
7111 this.blurEventsBound = true;
7112 }
7113 }, 100);
7114
7115 this.blurCallback = callback;
7116 }
7117
7118 return this;
7119 }
7120
7121 /** @param {KeyboardEvent} e */
7122 _escapeCheck(e){
7123 if(e.key == 27){
7124 this.hide();
7125 }
7126 }
7127
7128 blockHide(){
7129 this.hideable = false;
7130 }
7131
7132 restoreHide(){
7133 this.hideable = true;
7134 }
7135
7136 hide(silent = false){
7137 if(this.visible && this.hideable){
7138 if(this.blurable && this.blurEventsBound){
7139 document.body.removeEventListener("keydown", this.escEvent);
7140 document.body.removeEventListener("click", this.blurEvent);
7141 document.body.removeEventListener("contextmenu", this.blurEvent);
7142 document.body.removeEventListener("mousedown", this.blurEvent);
7143 window.removeEventListener("resize", this.blurEvent);
7144 this.table.rowManager.element.removeEventListener("scroll", this.blurEvent);
7145 this.unsubscribe("cell-editing", this.blurEvent);
7146
7147 this.blurEventsBound = false;
7148 }
7149
7150 if(this.childPopup){
7151 this.childPopup.hide();
7152 }
7153
7154 if(this.parent){
7155 this.parent.childPopup = null;
7156 }
7157
7158 if(this.element.parentNode){
7159 this.element.parentNode.removeChild(this.element);
7160 }
7161
7162 this.visible = false;
7163
7164 if(this.blurCallback && !silent){
7165 this.blurCallback();
7166 }
7167
7168 this.unsubscribe("table-destroy", this.destroyBinding);
7169 }
7170
7171 return this;
7172 }
7173
7174 child(element){
7175 if(this.childPopup){
7176 this.childPopup.hide();
7177 }
7178
7179 this.childPopup = new Popup(this.table, element, this);
7180
7181 return this.childPopup;
7182 }
7183 };
7184
7185 class Module extends CoreFeature{
7186
7187 constructor(table, name){
7188 super(table);
7189
7190 this._handler = null;
7191 }
7192
7193 initialize(){
7194 // setup module when table is initialized, to be overridden in module
7195 }
7196
7197
7198 ///////////////////////////////////
7199 ////// Options Registration ///////
7200 ///////////////////////////////////
7201
7202 registerTableOption(key, value){
7203 this.table.optionsList.register(key, value);
7204 }
7205
7206 registerColumnOption(key, value){
7207 this.table.columnManager.optionsList.register(key, value);
7208 }
7209
7210 ///////////////////////////////////
7211 /// Public Function Registration ///
7212 ///////////////////////////////////
7213
7214 registerTableFunction(name, func){
7215 if(typeof this.table[name] === "undefined"){
7216 this.table[name] = (...args) => {
7217 this.table.initGuard(name);
7218
7219 return func(...args);
7220 };
7221 }else {
7222 console.warn("Unable to bind table function, name already in use", name);
7223 }
7224 }
7225
7226 registerComponentFunction(component, func, handler){
7227 return this.table.componentFunctionBinder.bind(component, func, handler);
7228 }
7229
7230 ///////////////////////////////////
7231 ////////// Data Pipeline //////////
7232 ///////////////////////////////////
7233
7234 registerDataHandler(handler, priority){
7235 this.table.rowManager.registerDataPipelineHandler(handler, priority);
7236 this._handler = handler;
7237 }
7238
7239 registerDisplayHandler(handler, priority){
7240 this.table.rowManager.registerDisplayPipelineHandler(handler, priority);
7241 this._handler = handler;
7242 }
7243
7244 displayRows(adjust){
7245 var index = this.table.rowManager.displayRows.length - 1,
7246 lookupIndex;
7247
7248 if(this._handler){
7249 lookupIndex = this.table.rowManager.displayPipeline.findIndex((item) => {
7250 return item.handler === this._handler;
7251 });
7252
7253 if(lookupIndex > -1){
7254 index = lookupIndex;
7255 }
7256 }
7257
7258 if(adjust){
7259 index = index + adjust;
7260 }
7261
7262 if(this._handler){
7263 if(index > -1){
7264 return this.table.rowManager.getDisplayRows(index);
7265 }else {
7266 return this.activeRows();
7267 }
7268 }
7269 }
7270
7271 activeRows(){
7272 return this.table.rowManager.activeRows;
7273 }
7274
7275 refreshData(renderInPosition, handler){
7276 if(!handler){
7277 handler = this._handler;
7278 }
7279
7280 if(handler){
7281 this.table.rowManager.refreshActiveData(handler, false, renderInPosition);
7282 }
7283 }
7284
7285 ///////////////////////////////////
7286 //////// Footer Management ////////
7287 ///////////////////////////////////
7288
7289 footerAppend(element){
7290 return this.table.footerManager.append(element);
7291 }
7292
7293 footerPrepend(element){
7294 return this.table.footerManager.prepend(element);
7295 }
7296
7297 footerRemove(element){
7298 return this.table.footerManager.remove(element);
7299 }
7300
7301 ///////////////////////////////////
7302 //////// Popups Management ////////
7303 ///////////////////////////////////
7304
7305 popup(menuEl, menuContainer){
7306 return new Popup$1(this.table, menuEl, menuContainer);
7307 }
7308
7309 ///////////////////////////////////
7310 //////// Alert Management ////////
7311 ///////////////////////////////////
7312
7313 alert(content, type){
7314 return this.table.alertManager.alert(content, type);
7315 }
7316
7317 clearAlert(){
7318 return this.table.alertManager.clear();
7319 }
7320
7321 }
7322
7323 //resize columns to fit data they contain
7324 function fitData(columns, forced){
7325 if(forced){
7326 this.table.columnManager.renderer.reinitializeColumnWidths(columns);
7327 }
7328
7329 if(this.table.options.responsiveLayout && this.table.modExists("responsiveLayout", true)){
7330 this.table.modules.responsiveLayout.update();
7331 }
7332 }
7333
7334 //resize columns to fit data they contain and stretch row to fill table, also used for fitDataTable
7335 function fitDataGeneral(columns, forced){
7336 columns.forEach(function(column){
7337 column.reinitializeWidth();
7338 });
7339
7340 if(this.table.options.responsiveLayout && this.table.modExists("responsiveLayout", true)){
7341 this.table.modules.responsiveLayout.update();
7342 }
7343 }
7344
7345 //resize columns to fit data the contain and stretch last column to fill table
7346 function fitDataStretch(columns, forced){
7347 var colsWidth = 0,
7348 tableWidth = this.table.rowManager.element.clientWidth,
7349 gap = 0,
7350 lastCol = false;
7351
7352 columns.forEach((column, i) => {
7353 if(!column.widthFixed){
7354 column.reinitializeWidth();
7355 }
7356
7357 if(this.table.options.responsiveLayout ? column.modules.responsive.visible : column.visible){
7358 lastCol = column;
7359 }
7360
7361 if(column.visible){
7362 colsWidth += column.getWidth();
7363 }
7364 });
7365
7366 if(lastCol){
7367 gap = tableWidth - colsWidth + lastCol.getWidth();
7368
7369 if(this.table.options.responsiveLayout && this.table.modExists("responsiveLayout", true)){
7370 lastCol.setWidth(0);
7371 this.table.modules.responsiveLayout.update();
7372 }
7373
7374 if(gap > 0){
7375 lastCol.setWidth(gap);
7376 }else {
7377 lastCol.reinitializeWidth();
7378 }
7379 }else {
7380 if(this.table.options.responsiveLayout && this.table.modExists("responsiveLayout", true)){
7381 this.table.modules.responsiveLayout.update();
7382 }
7383 }
7384 }
7385
7386 //resize columns to fit
7387 function fitColumns(columns, forced){
7388 var totalWidth = this.table.rowManager.element.getBoundingClientRect().width; //table element width
7389 var fixedWidth = 0; //total width of columns with a defined width
7390 var flexWidth = 0; //total width available to flexible columns
7391 var flexGrowUnits = 0; //total number of widthGrow blocks across all columns
7392 var flexColWidth = 0; //desired width of flexible columns
7393 var flexColumns = []; //array of flexible width columns
7394 var fixedShrinkColumns = []; //array of fixed width columns that can shrink
7395 var flexShrinkUnits = 0; //total number of widthShrink blocks across all columns
7396 var overflowWidth = 0; //horizontal overflow width
7397 var gapFill = 0; //number of pixels to be added to final column to close and half pixel gaps
7398
7399 function calcWidth(width){
7400 var colWidth;
7401
7402 if(typeof(width) == "string"){
7403 if(width.indexOf("%") > -1){
7404 colWidth = (totalWidth / 100) * parseInt(width);
7405 }else {
7406 colWidth = parseInt(width);
7407 }
7408 }else {
7409 colWidth = width;
7410 }
7411
7412 return colWidth;
7413 }
7414
7415 //ensure columns resize to take up the correct amount of space
7416 function scaleColumns(columns, freeSpace, colWidth, shrinkCols){
7417 var oversizeCols = [],
7418 oversizeSpace = 0,
7419 remainingSpace = 0,
7420 nextColWidth = 0,
7421 remainingFlexGrowUnits = flexGrowUnits,
7422 gap = 0,
7423 changeUnits = 0,
7424 undersizeCols = [];
7425
7426 function calcGrow(col){
7427 return (colWidth * (col.column.definition.widthGrow || 1));
7428 }
7429
7430 function calcShrink(col){
7431 return (calcWidth(col.width) - (colWidth * (col.column.definition.widthShrink || 0)));
7432 }
7433
7434 columns.forEach(function(col, i){
7435 var width = shrinkCols ? calcShrink(col) : calcGrow(col);
7436 if(col.column.minWidth >= width){
7437 oversizeCols.push(col);
7438 }else {
7439 if(col.column.maxWidth && col.column.maxWidth < width){
7440 col.width = col.column.maxWidth;
7441 freeSpace -= col.column.maxWidth;
7442
7443 remainingFlexGrowUnits -= shrinkCols ? (col.column.definition.widthShrink || 1) : (col.column.definition.widthGrow || 1);
7444
7445 if(remainingFlexGrowUnits){
7446 colWidth = Math.floor(freeSpace/remainingFlexGrowUnits);
7447 }
7448 }else {
7449 undersizeCols.push(col);
7450 changeUnits += shrinkCols ? (col.column.definition.widthShrink || 1) : (col.column.definition.widthGrow || 1);
7451 }
7452 }
7453 });
7454
7455 if(oversizeCols.length){
7456 oversizeCols.forEach(function(col){
7457 oversizeSpace += shrinkCols ? col.width - col.column.minWidth : col.column.minWidth;
7458 col.width = col.column.minWidth;
7459 });
7460
7461 remainingSpace = freeSpace - oversizeSpace;
7462
7463 nextColWidth = changeUnits ? Math.floor(remainingSpace/changeUnits) : remainingSpace;
7464
7465 gap = scaleColumns(undersizeCols, remainingSpace, nextColWidth, shrinkCols);
7466 }else {
7467 gap = changeUnits ? freeSpace - (Math.floor(freeSpace/changeUnits) * changeUnits) : freeSpace;
7468
7469 undersizeCols.forEach(function(column){
7470 column.width = shrinkCols ? calcShrink(column) : calcGrow(column);
7471 });
7472 }
7473
7474 return gap;
7475 }
7476
7477 if(this.table.options.responsiveLayout && this.table.modExists("responsiveLayout", true)){
7478 this.table.modules.responsiveLayout.update();
7479 }
7480
7481 //adjust for vertical scrollbar if present
7482 if(this.table.rowManager.element.scrollHeight > this.table.rowManager.element.clientHeight){
7483 totalWidth -= this.table.rowManager.element.offsetWidth - this.table.rowManager.element.clientWidth;
7484 }
7485
7486 columns.forEach(function(column){
7487 var width, minWidth, colWidth;
7488
7489 if(column.visible){
7490
7491 width = column.definition.width;
7492 minWidth = parseInt(column.minWidth);
7493
7494 if(width){
7495
7496 colWidth = calcWidth(width);
7497
7498 fixedWidth += colWidth > minWidth ? colWidth : minWidth;
7499
7500 if(column.definition.widthShrink){
7501 fixedShrinkColumns.push({
7502 column:column,
7503 width:colWidth > minWidth ? colWidth : minWidth
7504 });
7505 flexShrinkUnits += column.definition.widthShrink;
7506 }
7507
7508 }else {
7509 flexColumns.push({
7510 column:column,
7511 width:0,
7512 });
7513 flexGrowUnits += column.definition.widthGrow || 1;
7514 }
7515 }
7516 });
7517
7518 //calculate available space
7519 flexWidth = totalWidth - fixedWidth;
7520
7521 //calculate correct column size
7522 flexColWidth = Math.floor(flexWidth / flexGrowUnits);
7523
7524 //generate column widths
7525 gapFill = scaleColumns(flexColumns, flexWidth, flexColWidth, false);
7526
7527 //increase width of last column to account for rounding errors
7528 if(flexColumns.length && gapFill > 0){
7529 flexColumns[flexColumns.length-1].width += gapFill;
7530 }
7531
7532 //calculate space for columns to be shrunk into
7533 flexColumns.forEach(function(col){
7534 flexWidth -= col.width;
7535 });
7536
7537 overflowWidth = Math.abs(gapFill) + flexWidth;
7538
7539 //shrink oversize columns if there is no available space
7540 if(overflowWidth > 0 && flexShrinkUnits){
7541 gapFill = scaleColumns(fixedShrinkColumns, overflowWidth, Math.floor(overflowWidth / flexShrinkUnits), true);
7542 }
7543
7544 //decrease width of last column to account for rounding errors
7545 if(gapFill && fixedShrinkColumns.length){
7546 fixedShrinkColumns[fixedShrinkColumns.length-1].width -= gapFill;
7547 }
7548
7549 flexColumns.forEach(function(col){
7550 col.column.setWidth(col.width);
7551 });
7552
7553 fixedShrinkColumns.forEach(function(col){
7554 col.column.setWidth(col.width);
7555 });
7556 }
7557
7558 var defaultModes = {
7559 fitData:fitData,
7560 fitDataFill:fitDataGeneral,
7561 fitDataTable:fitDataGeneral,
7562 fitDataStretch:fitDataStretch,
7563 fitColumns:fitColumns ,
7564 };
7565
7566 class Layout extends Module{
7567
7568 static moduleName = "layout";
7569
7570 //load defaults
7571 static modes = defaultModes;
7572
7573 constructor(table){
7574 super(table, "layout");
7575
7576 this.mode = null;
7577
7578 this.registerTableOption("layout", "fitData"); //layout type
7579 this.registerTableOption("layoutColumnsOnNewData", false); //update column widths on setData
7580
7581 this.registerColumnOption("widthGrow");
7582 this.registerColumnOption("widthShrink");
7583 }
7584
7585 //initialize layout system
7586 initialize(){
7587 var layout = this.table.options.layout;
7588
7589 if(Layout.modes[layout]){
7590 this.mode = layout;
7591 }else {
7592 console.warn("Layout Error - invalid mode set, defaulting to 'fitData' : " + layout);
7593 this.mode = 'fitData';
7594 }
7595
7596 this.table.element.setAttribute("tabulator-layout", this.mode);
7597 this.subscribe("column-init", this.initializeColumn.bind(this));
7598 }
7599
7600 initializeColumn(column){
7601 if(column.definition.widthGrow){
7602 column.definition.widthGrow = Number(column.definition.widthGrow);
7603 }
7604 if(column.definition.widthShrink){
7605 column.definition.widthShrink = Number(column.definition.widthShrink);
7606 }
7607 }
7608
7609 getMode(){
7610 return this.mode;
7611 }
7612
7613 //trigger table layout
7614 layout(dataChanged){
7615
7616 var variableHeight = this.table.columnManager.columnsByIndex.find((column) => column.definition.variableHeight || column.definition.formatter === "textarea");
7617
7618 this.dispatch("layout-refreshing");
7619 Layout.modes[this.mode].call(this, this.table.columnManager.columnsByIndex, dataChanged);
7620
7621 if(variableHeight){
7622 this.table.rowManager.normalizeHeight(true);
7623 }
7624
7625 this.dispatch("layout-refreshed");
7626 }
7627 }
7628
7629 var defaultLangs = {
7630 "default":{ //hold default locale text
7631 "groups":{
7632 "item":"item",
7633 "items":"items",
7634 },
7635 "columns":{
7636 },
7637 "data":{
7638 "loading":"Loading",
7639 "error":"Error",
7640 },
7641 "pagination":{
7642 "page_size":"Page Size",
7643 "page_title":"Show Page",
7644 "first":"First",
7645 "first_title":"First Page",
7646 "last":"Last",
7647 "last_title":"Last Page",
7648 "prev":"Prev",
7649 "prev_title":"Prev Page",
7650 "next":"Next",
7651 "next_title":"Next Page",
7652 "all":"All",
7653 "counter":{
7654 "showing": "Showing",
7655 "of": "of",
7656 "rows": "rows",
7657 "pages": "pages",
7658 }
7659 },
7660 "headerFilters":{
7661 "default":"filter column...",
7662 "columns":{}
7663 }
7664 },
7665 };
7666
7667 class Localize extends Module{
7668
7669 static moduleName = "localize";
7670
7671 //load defaults
7672 static langs = defaultLangs;
7673
7674 constructor(table){
7675 super(table);
7676
7677 this.locale = "default"; //current locale
7678 this.lang = false; //current language
7679 this.bindings = {}; //update events to call when locale is changed
7680 this.langList = {};
7681
7682 this.registerTableOption("locale", false); //current system language
7683 this.registerTableOption("langs", {});
7684 }
7685
7686 initialize(){
7687 this.langList = Helpers.deepClone(Localize.langs);
7688
7689 if(this.table.options.columnDefaults.headerFilterPlaceholder !== false){
7690 this.setHeaderFilterPlaceholder(this.table.options.columnDefaults.headerFilterPlaceholder);
7691 }
7692
7693 for(let locale in this.table.options.langs){
7694 this.installLang(locale, this.table.options.langs[locale]);
7695 }
7696
7697 this.setLocale(this.table.options.locale);
7698
7699 this.registerTableFunction("setLocale", this.setLocale.bind(this));
7700 this.registerTableFunction("getLocale", this.getLocale.bind(this));
7701 this.registerTableFunction("getLang", this.getLang.bind(this));
7702 }
7703
7704 //set header placeholder
7705 setHeaderFilterPlaceholder(placeholder){
7706 this.langList.default.headerFilters.default = placeholder;
7707 }
7708
7709 //setup a lang description object
7710 installLang(locale, lang){
7711 if(this.langList[locale]){
7712 this._setLangProp(this.langList[locale], lang);
7713 }else {
7714 this.langList[locale] = lang;
7715 }
7716 }
7717
7718 _setLangProp(lang, values){
7719 for(let key in values){
7720 if(lang[key] && typeof lang[key] == "object"){
7721 this._setLangProp(lang[key], values[key]);
7722 }else {
7723 lang[key] = values[key];
7724 }
7725 }
7726 }
7727
7728 //set current locale
7729 setLocale(desiredLocale){
7730 desiredLocale = desiredLocale || "default";
7731
7732 //fill in any matching language values
7733 function traverseLang(trans, path){
7734 for(var prop in trans){
7735 if(typeof trans[prop] == "object"){
7736 if(!path[prop]){
7737 path[prop] = {};
7738 }
7739 traverseLang(trans[prop], path[prop]);
7740 }else {
7741 path[prop] = trans[prop];
7742 }
7743 }
7744 }
7745
7746 //determining correct locale to load
7747 if(desiredLocale === true && navigator.language){
7748 //get local from system
7749 desiredLocale = navigator.language.toLowerCase();
7750 }
7751
7752 if(desiredLocale){
7753 //if locale is not set, check for matching top level locale else use default
7754 if(!this.langList[desiredLocale]){
7755 let prefix = desiredLocale.split("-")[0];
7756
7757 if(this.langList[prefix]){
7758 console.warn("Localization Error - Exact matching locale not found, using closest match: ", desiredLocale, prefix);
7759 desiredLocale = prefix;
7760 }else {
7761 console.warn("Localization Error - Matching locale not found, using default: ", desiredLocale);
7762 desiredLocale = "default";
7763 }
7764 }
7765 }
7766
7767 this.locale = desiredLocale;
7768
7769 //load default lang template
7770 this.lang = Helpers.deepClone(this.langList.default || {});
7771
7772 if(desiredLocale != "default"){
7773 traverseLang(this.langList[desiredLocale], this.lang);
7774 }
7775
7776 this.dispatchExternal("localized", this.locale, this.lang);
7777
7778 this._executeBindings();
7779 }
7780
7781 //get current locale
7782 getLocale(locale){
7783 return this.locale;
7784 }
7785
7786 //get lang object for given local or current if none provided
7787 getLang(locale){
7788 return locale ? this.langList[locale] : this.lang;
7789 }
7790
7791 //get text for current locale
7792 getText(path, value){
7793 var fillPath = value ? path + "|" + value : path,
7794 pathArray = fillPath.split("|"),
7795 text = this._getLangElement(pathArray, this.locale);
7796
7797 // if(text === false){
7798 // console.warn("Localization Error - Matching localized text not found for given path: ", path);
7799 // }
7800
7801 return text || "";
7802 }
7803
7804 //traverse langs object and find localized copy
7805 _getLangElement(path, locale){
7806 var root = this.lang;
7807
7808 path.forEach(function(level){
7809 var rootPath;
7810
7811 if(root){
7812 rootPath = root[level];
7813
7814 if(typeof rootPath != "undefined"){
7815 root = rootPath;
7816 }else {
7817 root = false;
7818 }
7819 }
7820 });
7821
7822 return root;
7823 }
7824
7825 //set update binding
7826 bind(path, callback){
7827 if(!this.bindings[path]){
7828 this.bindings[path] = [];
7829 }
7830
7831 this.bindings[path].push(callback);
7832
7833 callback(this.getText(path), this.lang);
7834 }
7835
7836 //iterate through bindings and trigger updates
7837 _executeBindings(){
7838 for(let path in this.bindings){
7839 this.bindings[path].forEach((binding) => {
7840 binding(this.getText(path), this.lang);
7841 });
7842 }
7843 }
7844 }
7845
7846 class Comms extends Module{
7847
7848 static moduleName = "comms";
7849
7850 constructor(table){
7851 super(table);
7852 }
7853
7854 initialize(){
7855 this.registerTableFunction("tableComms", this.receive.bind(this));
7856 }
7857
7858 getConnections(selectors){
7859 var connections = [],
7860 connection;
7861
7862 connection = this.table.constructor.registry.lookupTable(selectors);
7863
7864 connection.forEach((con) =>{
7865 if(this.table !== con){
7866 connections.push(con);
7867 }
7868 });
7869
7870 return connections;
7871 }
7872
7873 send(selectors, module, action, data){
7874 var connections = this.getConnections(selectors);
7875
7876 connections.forEach((connection) => {
7877 connection.tableComms(this.table.element, module, action, data);
7878 });
7879
7880 if(!connections.length && selectors){
7881 console.warn("Table Connection Error - No tables matching selector found", selectors);
7882 }
7883 }
7884
7885 receive(table, module, action, data){
7886 if(this.table.modExists(module)){
7887 return this.table.modules[module].commsReceived(table, action, data);
7888 }else {
7889 console.warn("Inter-table Comms Error - no such module:", module);
7890 }
7891 }
7892 }
7893
7894 var coreModules = /*#__PURE__*/Object.freeze({
7895 __proto__: null,
7896 CommsModule: Comms,
7897 LayoutModule: Layout,
7898 LocalizeModule: Localize
7899 });
7900
7901 class TableRegistry {
7902 static registry = {
7903 tables:[],
7904
7905 register(table){
7906 TableRegistry.registry.tables.push(table);
7907 },
7908
7909 deregister(table){
7910 var index = TableRegistry.registry.tables.indexOf(table);
7911
7912 if(index > -1){
7913 TableRegistry.registry.tables.splice(index, 1);
7914 }
7915 },
7916
7917 lookupTable(query, silent){
7918 var results = [],
7919 matches, match;
7920
7921 if(typeof query === "string"){
7922 matches = document.querySelectorAll(query);
7923
7924 if(matches.length){
7925 for(var i = 0; i < matches.length; i++){
7926 match = TableRegistry.registry.matchElement(matches[i]);
7927
7928 if(match){
7929 results.push(match);
7930 }
7931 }
7932 }
7933
7934 }else if((typeof HTMLElement !== "undefined" && query instanceof HTMLElement) || query instanceof TableRegistry){
7935 match = TableRegistry.registry.matchElement(query);
7936
7937 if(match){
7938 results.push(match);
7939 }
7940 }else if(Array.isArray(query)){
7941 query.forEach(function(item){
7942 results = results.concat(TableRegistry.registry.lookupTable(item));
7943 });
7944 }else {
7945 if(!silent){
7946 console.warn("Table Connection Error - Invalid Selector", query);
7947 }
7948 }
7949
7950 return results;
7951 },
7952
7953 matchElement(element){
7954 return TableRegistry.registry.tables.find(function(table){
7955 return element instanceof TableRegistry ? table === element : table.element === element;
7956 });
7957 }
7958 };
7959
7960
7961 static findTable(query){
7962 var results = TableRegistry.registry.lookupTable(query, true);
7963 return Array.isArray(results) && !results.length ? false : results;
7964 }
7965 }
7966
7967 class ModuleBinder extends TableRegistry {
7968
7969 static moduleBindings = {};
7970 static moduleExtensions = {};
7971 static modulesRegistered = false;
7972
7973 static defaultModules = false;
7974
7975 constructor(){
7976 super();
7977 }
7978
7979 static initializeModuleBinder(defaultModules){
7980 if(!ModuleBinder.modulesRegistered){
7981 ModuleBinder.modulesRegistered = true;
7982 ModuleBinder._registerModules(coreModules, true);
7983
7984 if(defaultModules){
7985 ModuleBinder._registerModules(defaultModules);
7986 }
7987 }
7988 }
7989
7990 static _extendModule(name, property, values){
7991 if(ModuleBinder.moduleBindings[name]){
7992 var source = ModuleBinder.moduleBindings[name][property];
7993
7994 if(source){
7995 if(typeof values == "object"){
7996 for(let key in values){
7997 source[key] = values[key];
7998 }
7999 }else {
8000 console.warn("Module Error - Invalid value type, it must be an object");
8001 }
8002 }else {
8003 console.warn("Module Error - property does not exist:", property);
8004 }
8005 }else {
8006 console.warn("Module Error - module does not exist:", name);
8007 }
8008 }
8009
8010 static _registerModules(modules, core){
8011 var mods = Object.values(modules);
8012
8013 if(core){
8014 mods.forEach((mod) => {
8015 mod.prototype.moduleCore = true;
8016 });
8017 }
8018
8019 ModuleBinder._registerModule(mods);
8020 }
8021
8022 static _registerModule(modules){
8023 if(!Array.isArray(modules)){
8024 modules = [modules];
8025 }
8026
8027 modules.forEach((mod) => {
8028 ModuleBinder._registerModuleBinding(mod);
8029 ModuleBinder._registerModuleExtensions(mod);
8030 });
8031 }
8032
8033 static _registerModuleBinding(mod){
8034 if(mod.moduleName){
8035 ModuleBinder.moduleBindings[mod.moduleName] = mod;
8036 }else {
8037 console.error("Unable to bind module, no moduleName defined", mod.moduleName);
8038 }
8039 }
8040
8041 static _registerModuleExtensions(mod){
8042 var extensions = mod.moduleExtensions;
8043
8044 if(mod.moduleExtensions){
8045 for (let modKey in extensions) {
8046 let ext = extensions[modKey];
8047
8048 if(ModuleBinder.moduleBindings[modKey]){
8049 for (let propKey in ext) {
8050 ModuleBinder._extendModule(modKey, propKey, ext[propKey]);
8051 }
8052 }else {
8053 if(!ModuleBinder.moduleExtensions[modKey]){
8054 ModuleBinder.moduleExtensions[modKey] = {};
8055 }
8056
8057 for (let propKey in ext) {
8058 if(!ModuleBinder.moduleExtensions[modKey][propKey]){
8059 ModuleBinder.moduleExtensions[modKey][propKey] = {};
8060 }
8061
8062 Object.assign(ModuleBinder.moduleExtensions[modKey][propKey], ext[propKey]);
8063 }
8064 }
8065 }
8066 }
8067
8068 ModuleBinder._extendModuleFromQueue(mod);
8069 }
8070
8071 static _extendModuleFromQueue(mod){
8072 var extensions = ModuleBinder.moduleExtensions[mod.moduleName];
8073
8074 if(extensions){
8075 for (let propKey in extensions) {
8076 ModuleBinder._extendModule(mod.moduleName, propKey, extensions[propKey]);
8077 }
8078 }
8079 }
8080
8081 //ensure that module are bound to instantiated function
8082 _bindModules(){
8083 var orderedStartMods = [],
8084 orderedEndMods = [],
8085 unOrderedMods = [];
8086
8087 this.modules = {};
8088
8089 for(var name in ModuleBinder.moduleBindings){
8090 let mod = ModuleBinder.moduleBindings[name];
8091 let module = new mod(this);
8092
8093 this.modules[name] = module;
8094
8095 if(mod.prototype.moduleCore){
8096 this.modulesCore.push(module);
8097 }else {
8098 if(mod.moduleInitOrder){
8099 if(mod.moduleInitOrder < 0){
8100 orderedStartMods.push(module);
8101 }else {
8102 orderedEndMods.push(module);
8103 }
8104
8105 }else {
8106 unOrderedMods.push(module);
8107 }
8108 }
8109 }
8110
8111 orderedStartMods.sort((a, b) => a.moduleInitOrder > b.moduleInitOrder ? 1 : -1);
8112 orderedEndMods.sort((a, b) => a.moduleInitOrder > b.moduleInitOrder ? 1 : -1);
8113
8114 this.modulesRegular = orderedStartMods.concat(unOrderedMods.concat(orderedEndMods));
8115 }
8116 }
8117
8118 class Alert extends CoreFeature{
8119 constructor(table){
8120 super(table);
8121
8122 this.element = this._createAlertElement();
8123 this.msgElement = this._createMsgElement();
8124 this.type = null;
8125
8126 this.element.appendChild(this.msgElement);
8127 }
8128
8129 _createAlertElement(){
8130 var el = document.createElement("div");
8131 el.classList.add("tabulator-alert");
8132 return el;
8133 }
8134
8135 _createMsgElement(){
8136 var el = document.createElement("div");
8137 el.classList.add("tabulator-alert-msg");
8138 el.setAttribute("role", "alert");
8139 return el;
8140 }
8141
8142 _typeClass(){
8143 return "tabulator-alert-state-" + this.type;
8144 }
8145
8146 alert(content, type = "msg"){
8147 if(content){
8148 this.clear();
8149
8150 this.dispatch("alert-show", type);
8151
8152 this.type = type;
8153
8154 while(this.msgElement.firstChild) this.msgElement.removeChild(this.msgElement.firstChild);
8155
8156 this.msgElement.classList.add(this._typeClass());
8157
8158 if(typeof content === "function"){
8159 content = content();
8160 }
8161
8162 if(content instanceof HTMLElement){
8163 this.msgElement.appendChild(content);
8164 }else {
8165 this.msgElement.innerHTML = content;
8166 }
8167
8168 this.table.element.appendChild(this.element);
8169 }
8170 }
8171
8172 clear(){
8173 this.dispatch("alert-hide", this.type);
8174
8175 if(this.element.parentNode){
8176 this.element.parentNode.removeChild(this.element);
8177 }
8178
8179 this.msgElement.classList.remove(this._typeClass());
8180 }
8181 }
8182
8183 class Tabulator extends ModuleBinder{
8184
8185 //default setup options
8186 static defaultOptions = defaultOptions;
8187
8188 static extendModule(){
8189 Tabulator.initializeModuleBinder();
8190 Tabulator._extendModule(...arguments);
8191 }
8192
8193 static registerModule(){
8194 Tabulator.initializeModuleBinder();
8195 Tabulator._registerModule(...arguments);
8196 }
8197
8198 constructor(element, options, modules){
8199 super();
8200
8201 Tabulator.initializeModuleBinder(modules);
8202
8203 this.options = {};
8204
8205 this.columnManager = null; // hold Column Manager
8206 this.rowManager = null; //hold Row Manager
8207 this.footerManager = null; //holder Footer Manager
8208 this.alertManager = null; //hold Alert Manager
8209 this.vdomHoz = null; //holder horizontal virtual dom
8210 this.externalEvents = null; //handle external event messaging
8211 this.eventBus = null; //handle internal event messaging
8212 this.interactionMonitor = false; //track user interaction
8213 this.browser = ""; //hold current browser type
8214 this.browserSlow = false; //handle reduced functionality for slower browsers
8215 this.browserMobile = false; //check if running on mobile, prevent resize cancelling edit on keyboard appearance
8216 this.rtl = false; //check if the table is in RTL mode
8217 this.originalElement = null; //hold original table element if it has been replaced
8218
8219 this.componentFunctionBinder = new ComponentFunctionBinder(this); //bind component functions
8220 this.dataLoader = false; //bind component functions
8221
8222 this.modules = {}; //hold all modules bound to this table
8223 this.modulesCore = []; //hold core modules bound to this table (for initialization purposes)
8224 this.modulesRegular = []; //hold regular modules bound to this table (for initialization purposes)
8225
8226 this.deprecationAdvisor = new DeprecationAdvisor(this);
8227 this.optionsList = new OptionsList(this, "table constructor");
8228
8229 this.dependencyRegistry = new DependencyRegistry(this);
8230
8231 this.initialized = false;
8232 this.destroyed = false;
8233
8234 if(this.initializeElement(element)){
8235
8236 this.initializeCoreSystems(options);
8237
8238 //delay table creation to allow event bindings immediately after the constructor
8239 setTimeout(() => {
8240 this._create();
8241 });
8242 }
8243
8244 this.constructor.registry.register(this); //register table for inter-device communication
8245 }
8246
8247 initializeElement(element){
8248 if(typeof HTMLElement !== "undefined" && element instanceof HTMLElement){
8249 this.element = element;
8250 return true;
8251 }else if(typeof element === "string"){
8252 this.element = document.querySelector(element);
8253
8254 if(this.element){
8255 return true;
8256 }else {
8257 console.error("Tabulator Creation Error - no element found matching selector: ", element);
8258 return false;
8259 }
8260 }else {
8261 console.error("Tabulator Creation Error - Invalid element provided:", element);
8262 return false;
8263 }
8264 }
8265
8266 initializeCoreSystems(options){
8267 this.columnManager = new ColumnManager(this);
8268 this.rowManager = new RowManager(this);
8269 this.footerManager = new FooterManager(this);
8270 this.dataLoader = new DataLoader(this);
8271 this.alertManager = new Alert(this);
8272
8273 this._bindModules();
8274
8275 this.options = this.optionsList.generate(Tabulator.defaultOptions, options);
8276
8277 this._clearObjectPointers();
8278
8279 this._mapDeprecatedFunctionality();
8280
8281 this.externalEvents = new ExternalEventBus(this, this.options, this.options.debugEventsExternal);
8282 this.eventBus = new InternalEventBus(this.options.debugEventsInternal);
8283
8284 this.interactionMonitor = new InteractionManager(this);
8285
8286 this.dataLoader.initialize();
8287 this.footerManager.initialize();
8288
8289 this.dependencyRegistry.initialize();
8290 }
8291
8292 //convert deprecated functionality to new functions
8293 _mapDeprecatedFunctionality(){
8294 //all previously deprecated functionality removed in the 6.0 release
8295 }
8296
8297 _clearSelection(){
8298
8299 this.element.classList.add("tabulator-block-select");
8300
8301 if (window.getSelection) {
8302 if (window.getSelection().empty) { // Chrome
8303 window.getSelection().empty();
8304 } else if (window.getSelection().removeAllRanges) { // Firefox
8305 window.getSelection().removeAllRanges();
8306 }
8307 } else if (document.selection) { // IE?
8308 document.selection.empty();
8309 }
8310
8311 this.element.classList.remove("tabulator-block-select");
8312 }
8313
8314 //create table
8315 _create(){
8316 this.externalEvents.dispatch("tableBuilding");
8317 this.eventBus.dispatch("table-building");
8318
8319 this._rtlCheck();
8320
8321 this._buildElement();
8322
8323 this._initializeTable();
8324
8325 this.initialized = true;
8326
8327 this._loadInitialData()
8328 .finally(() => {
8329 this.eventBus.dispatch("table-initialized");
8330 this.externalEvents.dispatch("tableBuilt");
8331 });
8332 }
8333
8334 _rtlCheck(){
8335 var style = window.getComputedStyle(this.element);
8336
8337 switch(this.options.textDirection){
8338 case "auto":
8339 if(style.direction !== "rtl"){
8340 break;
8341 }
8342
8343 case "rtl":
8344 this.element.classList.add("tabulator-rtl");
8345 this.rtl = true;
8346 break;
8347
8348 case "ltr":
8349 this.element.classList.add("tabulator-ltr");
8350
8351 default:
8352 this.rtl = false;
8353 }
8354 }
8355
8356 //clear pointers to objects in default config object
8357 _clearObjectPointers(){
8358 this.options.columns = this.options.columns.slice(0);
8359
8360 if(Array.isArray(this.options.data) && !this.options.reactiveData){
8361 this.options.data = this.options.data.slice(0);
8362 }
8363 }
8364
8365 //build tabulator element
8366 _buildElement(){
8367 var element = this.element,
8368 options = this.options,
8369 newElement;
8370
8371 if(element.tagName === "TABLE"){
8372 this.originalElement = this.element;
8373 newElement = document.createElement("div");
8374
8375 //transfer attributes to new element
8376 var attributes = element.attributes;
8377
8378 // loop through attributes and apply them on div
8379 for(var i in attributes){
8380 if(typeof attributes[i] == "object"){
8381 newElement.setAttribute(attributes[i].name, attributes[i].value);
8382 }
8383 }
8384
8385 // replace table with div element
8386 element.parentNode.replaceChild(newElement, element);
8387
8388 this.element = element = newElement;
8389 }
8390
8391 element.classList.add("tabulator");
8392 element.setAttribute("role", "grid");
8393 element.setAttribute("aria-owns", "tabulator-table-body");
8394
8395 //empty element
8396 while(element.firstChild) element.removeChild(element.firstChild);
8397
8398 //set table height
8399 if(options.height){
8400 options.height = isNaN(options.height) ? options.height : options.height + "px";
8401 element.style.height = options.height;
8402 }
8403
8404 //set table min height
8405 if(options.minHeight !== false){
8406 options.minHeight = isNaN(options.minHeight) ? options.minHeight : options.minHeight + "px";
8407 element.style.minHeight = options.minHeight;
8408 }
8409
8410 //set table maxHeight
8411 if(options.maxHeight !== false){
8412 options.maxHeight = isNaN(options.maxHeight) ? options.maxHeight : options.maxHeight + "px";
8413 element.style.maxHeight = options.maxHeight;
8414 }
8415 }
8416
8417 //initialize core systems and modules
8418 _initializeTable(){
8419 var element = this.element,
8420 options = this.options;
8421
8422 this.interactionMonitor.initialize();
8423
8424 this.columnManager.initialize();
8425 this.rowManager.initialize();
8426
8427 this._detectBrowser();
8428
8429 //initialize core modules
8430 this.modulesCore.forEach((mod) => {
8431 mod.initialize();
8432 });
8433
8434 //build table elements
8435 element.appendChild(this.columnManager.getElement());
8436 element.appendChild(this.rowManager.getElement());
8437
8438 if(options.footerElement){
8439 this.footerManager.activate();
8440 }
8441
8442 if(options.autoColumns && options.data){
8443
8444 this.columnManager.generateColumnsFromRowData(this.options.data);
8445 }
8446
8447 //initialize regular modules
8448 this.modulesRegular.forEach((mod) => {
8449 mod.initialize();
8450 });
8451
8452 this.columnManager.setColumns(options.columns);
8453
8454 this.eventBus.dispatch("table-built");
8455 }
8456
8457 _loadInitialData(){
8458 return this.dataLoader.load(this.options.data)
8459 .finally(() => {
8460 this.columnManager.verticalAlignHeaders();
8461 });
8462 }
8463
8464 //deconstructor
8465 destroy(){
8466 var element = this.element;
8467
8468 this.destroyed = true;
8469
8470 this.constructor.registry.deregister(this); //deregister table from inter-device communication
8471
8472 this.eventBus.dispatch("table-destroy");
8473
8474 //clear row data
8475 this.rowManager.destroy();
8476
8477 //clear DOM
8478 while(element.firstChild) element.removeChild(element.firstChild);
8479 element.classList.remove("tabulator");
8480 element.removeAttribute("tabulator-layout");
8481
8482 this.externalEvents.dispatch("tableDestroyed");
8483 }
8484
8485 _detectBrowser(){
8486 var ua = navigator.userAgent||navigator.vendor||window.opera;
8487
8488 if(ua.indexOf("Trident") > -1){
8489 this.browser = "ie";
8490 this.browserSlow = true;
8491 }else if(ua.indexOf("Edge") > -1){
8492 this.browser = "edge";
8493 this.browserSlow = true;
8494 }else if(ua.indexOf("Firefox") > -1){
8495 this.browser = "firefox";
8496 this.browserSlow = false;
8497 }else if(ua.indexOf("Mac OS") > -1){
8498 this.browser = "safari";
8499 this.browserSlow = false;
8500 }else {
8501 this.browser = "other";
8502 this.browserSlow = false;
8503 }
8504
8505 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));
8506 }
8507
8508 initGuard(func, msg){
8509 var stack, line;
8510
8511 if(this.options.debugInitialization && !this.initialized){
8512 if(!func){
8513 stack = new Error().stack.split("\n");
8514
8515 line = stack[0] == "Error" ? stack[2] : stack[1];
8516
8517 if(line[0] == " "){
8518 func = line.trim().split(" ")[1].split(".")[1];
8519 }else {
8520 func = line.trim().split("@")[0];
8521 }
8522 }
8523
8524 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 : ""));
8525 }
8526
8527 return this.initialized;
8528 }
8529
8530 ////////////////// Data Handling //////////////////
8531 //block table redrawing
8532 blockRedraw(){
8533 this.initGuard();
8534
8535 this.eventBus.dispatch("redraw-blocking");
8536
8537 this.rowManager.blockRedraw();
8538 this.columnManager.blockRedraw();
8539
8540 this.eventBus.dispatch("redraw-blocked");
8541 }
8542
8543 //restore table redrawing
8544 restoreRedraw(){
8545 this.initGuard();
8546
8547 this.eventBus.dispatch("redraw-restoring");
8548
8549 this.rowManager.restoreRedraw();
8550 this.columnManager.restoreRedraw();
8551
8552 this.eventBus.dispatch("redraw-restored");
8553 }
8554
8555 //load data
8556 setData(data, params, config){
8557 this.initGuard(false, "To set initial data please use the 'data' property in the table constructor.");
8558
8559 return this.dataLoader.load(data, params, config, false);
8560 }
8561
8562 //clear data
8563 clearData(){
8564 this.initGuard();
8565
8566 this.dataLoader.blockActiveLoad();
8567 this.rowManager.clearData();
8568 }
8569
8570 //get table data array
8571 getData(active){
8572 return this.rowManager.getData(active);
8573 }
8574
8575 //get table data array count
8576 getDataCount(active){
8577 return this.rowManager.getDataCount(active);
8578 }
8579
8580 //replace data, keeping table in position with same sort
8581 replaceData(data, params, config){
8582 this.initGuard();
8583
8584 return this.dataLoader.load(data, params, config, true, true);
8585 }
8586
8587 //update table data
8588 updateData(data){
8589 var responses = 0;
8590
8591 this.initGuard();
8592
8593 return new Promise((resolve, reject) => {
8594 this.dataLoader.blockActiveLoad();
8595
8596 if(typeof data === "string"){
8597 data = JSON.parse(data);
8598 }
8599
8600 if(data && data.length > 0){
8601 data.forEach((item) => {
8602 var row = this.rowManager.findRow(item[this.options.index]);
8603
8604 if(row){
8605 responses++;
8606
8607 row.updateData(item)
8608 .then(()=>{
8609 responses--;
8610
8611 if(!responses){
8612 resolve();
8613 }
8614 })
8615 .catch((e) => {
8616 reject("Update Error - Unable to update row", item, e);
8617 });
8618 }else {
8619 reject("Update Error - Unable to find row", item);
8620 }
8621 });
8622 }else {
8623 console.warn("Update Error - No data provided");
8624 reject("Update Error - No data provided");
8625 }
8626 });
8627 }
8628
8629 addData(data, pos, index){
8630 this.initGuard();
8631
8632 return new Promise((resolve, reject) => {
8633 this.dataLoader.blockActiveLoad();
8634
8635 if(typeof data === "string"){
8636 data = JSON.parse(data);
8637 }
8638
8639 if(data){
8640 this.rowManager.addRows(data, pos, index)
8641 .then((rows) => {
8642 var output = [];
8643
8644 rows.forEach(function(row){
8645 output.push(row.getComponent());
8646 });
8647
8648 resolve(output);
8649 });
8650 }else {
8651 console.warn("Update Error - No data provided");
8652 reject("Update Error - No data provided");
8653 }
8654 });
8655 }
8656
8657 //update table data
8658 updateOrAddData(data){
8659 var rows = [],
8660 responses = 0;
8661
8662 this.initGuard();
8663
8664 return new Promise((resolve, reject) => {
8665 this.dataLoader.blockActiveLoad();
8666
8667 if(typeof data === "string"){
8668 data = JSON.parse(data);
8669 }
8670
8671 if(data && data.length > 0){
8672 data.forEach((item) => {
8673 var row = this.rowManager.findRow(item[this.options.index]);
8674
8675 responses++;
8676
8677 if(row){
8678 row.updateData(item)
8679 .then(()=>{
8680 responses--;
8681 rows.push(row.getComponent());
8682
8683 if(!responses){
8684 resolve(rows);
8685 }
8686 });
8687 }else {
8688 this.rowManager.addRows(item)
8689 .then((newRows)=>{
8690 responses--;
8691 rows.push(newRows[0].getComponent());
8692
8693 if(!responses){
8694 resolve(rows);
8695 }
8696 });
8697 }
8698 });
8699 }else {
8700 console.warn("Update Error - No data provided");
8701 reject("Update Error - No data provided");
8702 }
8703 });
8704 }
8705
8706 //get row object
8707 getRow(index){
8708 var row = this.rowManager.findRow(index);
8709
8710 if(row){
8711 return row.getComponent();
8712 }else {
8713 console.warn("Find Error - No matching row found:", index);
8714 return false;
8715 }
8716 }
8717
8718 //get row object
8719 getRowFromPosition(position){
8720 var row = this.rowManager.getRowFromPosition(position);
8721
8722 if(row){
8723 return row.getComponent();
8724 }else {
8725 console.warn("Find Error - No matching row found:", position);
8726 return false;
8727 }
8728 }
8729
8730 //delete row from table
8731 deleteRow(index){
8732 var foundRows = [];
8733
8734 this.initGuard();
8735
8736 if(!Array.isArray(index)){
8737 index = [index];
8738 }
8739
8740 //find matching rows
8741 for(let item of index){
8742 let row = this.rowManager.findRow(item, true);
8743
8744 if(row){
8745 foundRows.push(row);
8746 }else {
8747 console.error("Delete Error - No matching row found:", item);
8748 return Promise.reject("Delete Error - No matching row found");
8749 }
8750 }
8751
8752 //sort rows into correct order to ensure smooth delete from table
8753 foundRows.sort((a, b) => {
8754 return this.rowManager.rows.indexOf(a) > this.rowManager.rows.indexOf(b) ? 1 : -1;
8755 });
8756
8757 //delete rows
8758 foundRows.forEach((row) =>{
8759 row.delete();
8760 });
8761
8762 this.rowManager.reRenderInPosition();
8763
8764 return Promise.resolve();
8765 }
8766
8767 //add row to table
8768 addRow(data, pos, index){
8769 this.initGuard();
8770
8771 if(typeof data === "string"){
8772 data = JSON.parse(data);
8773 }
8774
8775 return this.rowManager.addRows(data, pos, index, true)
8776 .then((rows)=>{
8777 return rows[0].getComponent();
8778 });
8779 }
8780
8781 //update a row if it exists otherwise create it
8782 updateOrAddRow(index, data){
8783 var row = this.rowManager.findRow(index);
8784
8785 this.initGuard();
8786
8787 if(typeof data === "string"){
8788 data = JSON.parse(data);
8789 }
8790
8791 if(row){
8792 return row.updateData(data)
8793 .then(()=>{
8794 return row.getComponent();
8795 });
8796 }else {
8797 return this.rowManager.addRows(data)
8798 .then((rows)=>{
8799 return rows[0].getComponent();
8800 });
8801 }
8802 }
8803
8804 //update row data
8805 updateRow(index, data){
8806 var row = this.rowManager.findRow(index);
8807
8808 this.initGuard();
8809
8810 if(typeof data === "string"){
8811 data = JSON.parse(data);
8812 }
8813
8814 if(row){
8815 return row.updateData(data)
8816 .then(()=>{
8817 return Promise.resolve(row.getComponent());
8818 });
8819 }else {
8820 console.warn("Update Error - No matching row found:", index);
8821 return Promise.reject("Update Error - No matching row found");
8822 }
8823 }
8824
8825 //scroll to row in DOM
8826 scrollToRow(index, position, ifVisible){
8827 var row = this.rowManager.findRow(index);
8828
8829 if(row){
8830 return this.rowManager.scrollToRow(row, position, ifVisible);
8831 }else {
8832 console.warn("Scroll Error - No matching row found:", index);
8833 return Promise.reject("Scroll Error - No matching row found");
8834 }
8835 }
8836
8837 moveRow(from, to, after){
8838 var fromRow = this.rowManager.findRow(from);
8839
8840 this.initGuard();
8841
8842 if(fromRow){
8843 fromRow.moveToRow(to, after);
8844 }else {
8845 console.warn("Move Error - No matching row found:", from);
8846 }
8847 }
8848
8849 getRows(active){
8850 return this.rowManager.getComponents(active);
8851 }
8852
8853 //get position of row in table
8854 getRowPosition(index){
8855 var row = this.rowManager.findRow(index);
8856
8857 if(row){
8858 return row.getPosition();
8859 }else {
8860 console.warn("Position Error - No matching row found:", index);
8861 return false;
8862 }
8863 }
8864
8865 /////////////// Column Functions ///////////////
8866 setColumns(definition){
8867 this.initGuard(false, "To set initial columns please use the 'columns' property in the table constructor");
8868
8869 this.columnManager.setColumns(definition);
8870 }
8871
8872 getColumns(structured){
8873 return this.columnManager.getComponents(structured);
8874 }
8875
8876 getColumn(field){
8877 var column = this.columnManager.findColumn(field);
8878
8879 if(column){
8880 return column.getComponent();
8881 }else {
8882 console.warn("Find Error - No matching column found:", field);
8883 return false;
8884 }
8885 }
8886
8887 getColumnDefinitions(){
8888 return this.columnManager.getDefinitionTree();
8889 }
8890
8891 showColumn(field){
8892 var column = this.columnManager.findColumn(field);
8893
8894 this.initGuard();
8895
8896 if(column){
8897 column.show();
8898 }else {
8899 console.warn("Column Show Error - No matching column found:", field);
8900 return false;
8901 }
8902 }
8903
8904 hideColumn(field){
8905 var column = this.columnManager.findColumn(field);
8906
8907 this.initGuard();
8908
8909 if(column){
8910 column.hide();
8911 }else {
8912 console.warn("Column Hide Error - No matching column found:", field);
8913 return false;
8914 }
8915 }
8916
8917 toggleColumn(field){
8918 var column = this.columnManager.findColumn(field);
8919
8920 this.initGuard();
8921
8922 if(column){
8923 if(column.visible){
8924 column.hide();
8925 }else {
8926 column.show();
8927 }
8928 }else {
8929 console.warn("Column Visibility Toggle Error - No matching column found:", field);
8930 return false;
8931 }
8932 }
8933
8934 addColumn(definition, before, field){
8935 var column = this.columnManager.findColumn(field);
8936
8937 this.initGuard();
8938
8939 return this.columnManager.addColumn(definition, before, column)
8940 .then((column) => {
8941 return column.getComponent();
8942 });
8943 }
8944
8945 deleteColumn(field){
8946 var column = this.columnManager.findColumn(field);
8947
8948 this.initGuard();
8949
8950 if(column){
8951 return column.delete();
8952 }else {
8953 console.warn("Column Delete Error - No matching column found:", field);
8954 return Promise.reject();
8955 }
8956 }
8957
8958 updateColumnDefinition(field, definition){
8959 var column = this.columnManager.findColumn(field);
8960
8961 this.initGuard();
8962
8963 if(column){
8964 return column.updateDefinition(definition);
8965 }else {
8966 console.warn("Column Update Error - No matching column found:", field);
8967 return Promise.reject();
8968 }
8969 }
8970
8971 moveColumn(from, to, after){
8972 var fromColumn = this.columnManager.findColumn(from),
8973 toColumn = this.columnManager.findColumn(to);
8974
8975 this.initGuard();
8976
8977 if(fromColumn){
8978 if(toColumn){
8979 this.columnManager.moveColumn(fromColumn, toColumn, after);
8980 }else {
8981 console.warn("Move Error - No matching column found:", toColumn);
8982 }
8983 }else {
8984 console.warn("Move Error - No matching column found:", from);
8985 }
8986 }
8987
8988 //scroll to column in DOM
8989 scrollToColumn(field, position, ifVisible){
8990 return new Promise((resolve, reject) => {
8991 var column = this.columnManager.findColumn(field);
8992
8993 if(column){
8994 return this.columnManager.scrollToColumn(column, position, ifVisible);
8995 }else {
8996 console.warn("Scroll Error - No matching column found:", field);
8997 return Promise.reject("Scroll Error - No matching column found");
8998 }
8999 });
9000 }
9001
9002 //////////// General Public Functions ////////////
9003 //redraw list without updating data
9004 redraw(force){
9005 this.initGuard();
9006
9007 this.columnManager.redraw(force);
9008 this.rowManager.redraw(force);
9009 }
9010
9011 setHeight(height){
9012 this.options.height = isNaN(height) ? height : height + "px";
9013 this.element.style.height = this.options.height;
9014 this.rowManager.initializeRenderer();
9015 this.rowManager.redraw(true);
9016 }
9017
9018 setMaxHeight(maxHeight){
9019 this.options.maxHeight = isNaN(maxHeight) ? maxHeight : maxHeight + "px";
9020 this.element.style.maxHeight = this.options.maxHeight;
9021 this.rowManager.initializeRenderer();
9022 this.rowManager.redraw(true);
9023 }
9024
9025 setMinHeight(minHeight){
9026 this.options.minHeight = isNaN(minHeight) ? minHeight : minHeight + "px";
9027 this.element.style.minHeight = this.options.minHeight;
9028 this.rowManager.initializeRenderer();
9029 this.rowManager.redraw(true);
9030 }
9031
9032 //////////////////// Event Bus ///////////////////
9033
9034 on(key, callback){
9035 this.externalEvents.subscribe(key, callback);
9036 }
9037
9038 off(key, callback){
9039 this.externalEvents.unsubscribe(key, callback);
9040 }
9041
9042 dispatchEvent(){
9043 var args = Array.from(arguments);
9044 args.shift();
9045
9046 this.externalEvents.dispatch(...arguments);
9047 }
9048
9049 //////////////////// Alerts ///////////////////
9050
9051 alert(contents, type){
9052 this.initGuard();
9053
9054 this.alertManager.alert(contents, type);
9055 }
9056
9057 clearAlert(){
9058 this.initGuard();
9059
9060 this.alertManager.clear();
9061 }
9062
9063 ////////////// Extension Management //////////////
9064 modExists(plugin, required){
9065 if(this.modules[plugin]){
9066 return true;
9067 }else {
9068 if(required){
9069 console.error("Tabulator Module Not Installed: " + plugin);
9070 }
9071 return false;
9072 }
9073 }
9074
9075 module(key){
9076 var mod = this.modules[key];
9077
9078 if(!mod){
9079 console.error("Tabulator module not installed: " + key);
9080 }
9081
9082 return mod;
9083 }
9084 }
9085
9086 var defaultAccessors = {
9087 rownum:function(value, data, type, params, column, row){
9088 return row.getPosition();
9089 }
9090 };
9091
9092 class Accessor extends Module{
9093
9094 static moduleName = "accessor";
9095
9096 //load defaults
9097 static accessors = defaultAccessors;
9098
9099 constructor(table){
9100 super(table);
9101
9102 this.allowedTypes = ["", "data", "download", "clipboard", "print", "htmlOutput"]; //list of accessor types
9103
9104 this.registerColumnOption("accessor");
9105 this.registerColumnOption("accessorParams");
9106 this.registerColumnOption("accessorData");
9107 this.registerColumnOption("accessorDataParams");
9108 this.registerColumnOption("accessorDownload");
9109 this.registerColumnOption("accessorDownloadParams");
9110 this.registerColumnOption("accessorClipboard");
9111 this.registerColumnOption("accessorClipboardParams");
9112 this.registerColumnOption("accessorPrint");
9113 this.registerColumnOption("accessorPrintParams");
9114 this.registerColumnOption("accessorHtmlOutput");
9115 this.registerColumnOption("accessorHtmlOutputParams");
9116 }
9117
9118 initialize(){
9119 this.subscribe("column-layout", this.initializeColumn.bind(this));
9120 this.subscribe("row-data-retrieve", this.transformRow.bind(this));
9121 }
9122
9123 //initialize column accessor
9124 initializeColumn(column){
9125 var match = false,
9126 config = {};
9127
9128 this.allowedTypes.forEach((type) => {
9129 var key = "accessor" + (type.charAt(0).toUpperCase() + type.slice(1)),
9130 accessor;
9131
9132 if(column.definition[key]){
9133 accessor = this.lookupAccessor(column.definition[key]);
9134
9135 if(accessor){
9136 match = true;
9137
9138 config[key] = {
9139 accessor:accessor,
9140 params: column.definition[key + "Params"] || {},
9141 };
9142 }
9143 }
9144 });
9145
9146 if(match){
9147 column.modules.accessor = config;
9148 }
9149 }
9150
9151 lookupAccessor(value){
9152 var accessor = false;
9153
9154 //set column accessor
9155 switch(typeof value){
9156 case "string":
9157 if(Accessor.accessors[value]){
9158 accessor = Accessor.accessors[value];
9159 }else {
9160 console.warn("Accessor Error - No such accessor found, ignoring: ", value);
9161 }
9162 break;
9163
9164 case "function":
9165 accessor = value;
9166 break;
9167 }
9168
9169 return accessor;
9170 }
9171
9172 //apply accessor to row
9173 transformRow(row, type){
9174 var key = "accessor" + (type.charAt(0).toUpperCase() + type.slice(1)),
9175 rowComponent = row.getComponent();
9176
9177 //clone data object with deep copy to isolate internal data from returned result
9178 var data = Helpers.deepClone(row.data || {});
9179
9180 this.table.columnManager.traverse(function(column){
9181 var value, accessor, params, colComponent;
9182
9183 if(column.modules.accessor){
9184
9185 accessor = column.modules.accessor[key] || column.modules.accessor.accessor || false;
9186
9187 if(accessor){
9188 value = column.getFieldValue(data);
9189
9190 if(value != "undefined"){
9191 colComponent = column.getComponent();
9192 params = typeof accessor.params === "function" ? accessor.params(value, data, type, colComponent, rowComponent) : accessor.params;
9193 column.setFieldValue(data, accessor.accessor(value, data, type, params, colComponent, rowComponent));
9194 }
9195 }
9196 }
9197 });
9198
9199 return data;
9200 }
9201 }
9202
9203 var defaultConfig = {
9204 method: "GET",
9205 };
9206
9207 function generateParamsList$1(data, prefix){
9208 var output = [];
9209
9210 prefix = prefix || "";
9211
9212 if(Array.isArray(data)){
9213 data.forEach((item, i) => {
9214 output = output.concat(generateParamsList$1(item, prefix ? prefix + "[" + i + "]" : i));
9215 });
9216 }else if (typeof data === "object"){
9217 for (var key in data){
9218 output = output.concat(generateParamsList$1(data[key], prefix ? prefix + "[" + key + "]" : key));
9219 }
9220 }else {
9221 output.push({key:prefix, value:data});
9222 }
9223
9224 return output;
9225 }
9226
9227 function serializeParams(params){
9228 var output = generateParamsList$1(params),
9229 encoded = [];
9230
9231 output.forEach(function(item){
9232 encoded.push(encodeURIComponent(item.key) + "=" + encodeURIComponent(item.value));
9233 });
9234
9235 return encoded.join("&");
9236 }
9237
9238 function urlBuilder(url, config, params){
9239 if(url){
9240 if(params && Object.keys(params).length){
9241 if(!config.method || config.method.toLowerCase() == "get"){
9242 config.method = "get";
9243
9244 url += (url.includes("?") ? "&" : "?") + serializeParams(params);
9245 }
9246 }
9247 }
9248
9249 return url;
9250 }
9251
9252 function defaultLoaderPromise(url, config, params){
9253 var contentType;
9254
9255 return new Promise((resolve, reject) => {
9256 //set url
9257 url = this.urlGenerator.call(this.table, url, config, params);
9258
9259 //set body content if not GET request
9260 if(config.method.toUpperCase() != "GET"){
9261 contentType = typeof this.table.options.ajaxContentType === "object" ? this.table.options.ajaxContentType : this.contentTypeFormatters[this.table.options.ajaxContentType];
9262 if(contentType){
9263
9264 for(var key in contentType.headers){
9265 if(!config.headers){
9266 config.headers = {};
9267 }
9268
9269 if(typeof config.headers[key] === "undefined"){
9270 config.headers[key] = contentType.headers[key];
9271 }
9272 }
9273
9274 config.body = contentType.body.call(this, url, config, params);
9275
9276 }else {
9277 console.warn("Ajax Error - Invalid ajaxContentType value:", this.table.options.ajaxContentType);
9278 }
9279 }
9280
9281 if(url){
9282 //configure headers
9283 if(typeof config.headers === "undefined"){
9284 config.headers = {};
9285 }
9286
9287 if(typeof config.headers.Accept === "undefined"){
9288 config.headers.Accept = "application/json";
9289 }
9290
9291 if(typeof config.headers["X-Requested-With"] === "undefined"){
9292 config.headers["X-Requested-With"] = "XMLHttpRequest";
9293 }
9294
9295 if(typeof config.mode === "undefined"){
9296 config.mode = "cors";
9297 }
9298
9299 if(config.mode == "cors"){
9300 if(typeof config.headers["Origin"] === "undefined"){
9301 config.headers["Origin"] = window.location.origin;
9302 }
9303
9304 if(typeof config.credentials === "undefined"){
9305 config.credentials = 'same-origin';
9306 }
9307 }else {
9308 if(typeof config.credentials === "undefined"){
9309 config.credentials = 'include';
9310 }
9311 }
9312
9313 //send request
9314 fetch(url, config)
9315 .then((response)=>{
9316 if(response.ok) {
9317 response.json()
9318 .then((data)=>{
9319 resolve(data);
9320 }).catch((error)=>{
9321 reject(error);
9322 console.warn("Ajax Load Error - Invalid JSON returned", error);
9323 });
9324 }else {
9325 console.error("Ajax Load Error - Connection Error: " + response.status, response.statusText);
9326 reject(response);
9327 }
9328 })
9329 .catch((error)=>{
9330 console.error("Ajax Load Error - Connection Error: ", error);
9331 reject(error);
9332 });
9333 }else {
9334 console.warn("Ajax Load Error - No URL Set");
9335 resolve([]);
9336 }
9337 });
9338 }
9339
9340 function generateParamsList(data, prefix){
9341 var output = [];
9342
9343 prefix = prefix || "";
9344
9345 if(Array.isArray(data)){
9346 data.forEach((item, i) => {
9347 output = output.concat(generateParamsList(item, prefix ? prefix + "[" + i + "]" : i));
9348 });
9349 }else if (typeof data === "object"){
9350 for (var key in data){
9351 output = output.concat(generateParamsList(data[key], prefix ? prefix + "[" + key + "]" : key));
9352 }
9353 }else {
9354 output.push({key:prefix, value:data});
9355 }
9356
9357 return output;
9358 }
9359
9360 var defaultContentTypeFormatters = {
9361 "json":{
9362 headers:{
9363 'Content-Type': 'application/json',
9364 },
9365 body:function(url, config, params){
9366 return JSON.stringify(params);
9367 },
9368 },
9369 "form":{
9370 headers:{
9371 },
9372 body:function(url, config, params){
9373
9374 var output = generateParamsList(params),
9375 form = new FormData();
9376
9377 output.forEach(function(item){
9378 form.append(item.key, item.value);
9379 });
9380
9381 return form;
9382 },
9383 },
9384 };
9385
9386 class Ajax extends Module{
9387
9388 static moduleName = "ajax";
9389
9390 //load defaults
9391 static defaultConfig = defaultConfig;
9392 static defaultURLGenerator = urlBuilder;
9393 static defaultLoaderPromise = defaultLoaderPromise;
9394 static contentTypeFormatters = defaultContentTypeFormatters;
9395
9396 constructor(table){
9397 super(table);
9398
9399 this.config = {}; //hold config object for ajax request
9400 this.url = ""; //request URL
9401 this.urlGenerator = false;
9402 this.params = false; //request parameters
9403
9404 this.loaderPromise = false;
9405
9406 this.registerTableOption("ajaxURL", false); //url for ajax loading
9407 this.registerTableOption("ajaxURLGenerator", false);
9408 this.registerTableOption("ajaxParams", {}); //params for ajax loading
9409 this.registerTableOption("ajaxConfig", "get"); //ajax request type
9410 this.registerTableOption("ajaxContentType", "form"); //ajax request type
9411 this.registerTableOption("ajaxRequestFunc", false); //promise function
9412
9413 this.registerTableOption("ajaxRequesting", function(){});
9414 this.registerTableOption("ajaxResponse", false);
9415
9416 this.contentTypeFormatters = Ajax.contentTypeFormatters;
9417 }
9418
9419 //initialize setup options
9420 initialize(){
9421 this.loaderPromise = this.table.options.ajaxRequestFunc || Ajax.defaultLoaderPromise;
9422 this.urlGenerator = this.table.options.ajaxURLGenerator || Ajax.defaultURLGenerator;
9423
9424 if(this.table.options.ajaxURL){
9425 this.setUrl(this.table.options.ajaxURL);
9426 }
9427
9428
9429 this.setDefaultConfig(this.table.options.ajaxConfig);
9430
9431 this.registerTableFunction("getAjaxUrl", this.getUrl.bind(this));
9432
9433 this.subscribe("data-loading", this.requestDataCheck.bind(this));
9434 this.subscribe("data-params", this.requestParams.bind(this));
9435 this.subscribe("data-load", this.requestData.bind(this));
9436 }
9437
9438 requestParams(data, config, silent, params){
9439 var ajaxParams = this.table.options.ajaxParams;
9440
9441 if(ajaxParams){
9442 if(typeof ajaxParams === "function"){
9443 ajaxParams = ajaxParams.call(this.table);
9444 }
9445
9446 params = Object.assign(Object.assign({}, ajaxParams), params);
9447 }
9448
9449 return params;
9450 }
9451
9452 requestDataCheck(data, params, config, silent){
9453 return !!((!data && this.url) || typeof data === "string");
9454 }
9455
9456 requestData(url, params, config, silent, previousData){
9457 var ajaxConfig;
9458
9459 if(!previousData && this.requestDataCheck(url)){
9460 if(url){
9461 this.setUrl(url);
9462 }
9463
9464 ajaxConfig = this.generateConfig(config);
9465
9466 return this.sendRequest(this.url, params, ajaxConfig);
9467 }else {
9468 return previousData;
9469 }
9470 }
9471
9472 setDefaultConfig(config = {}){
9473 this.config = Object.assign({}, Ajax.defaultConfig);
9474
9475 if(typeof config == "string"){
9476 this.config.method = config;
9477 }else {
9478 Object.assign(this.config, config);
9479 }
9480 }
9481
9482 //load config object
9483 generateConfig(config = {}){
9484 var ajaxConfig = Object.assign({}, this.config);
9485
9486 if(typeof config == "string"){
9487 ajaxConfig.method = config;
9488 }else {
9489 Object.assign(ajaxConfig, config);
9490 }
9491
9492 return ajaxConfig;
9493 }
9494
9495 //set request url
9496 setUrl(url){
9497 this.url = url;
9498 }
9499
9500 //get request url
9501 getUrl(){
9502 return this.url;
9503 }
9504
9505 //send ajax request
9506 sendRequest(url, params, config){
9507 if(this.table.options.ajaxRequesting.call(this.table, url, params) !== false){
9508 return this.loaderPromise(url, config, params)
9509 .then((data)=>{
9510 if(this.table.options.ajaxResponse){
9511 data = this.table.options.ajaxResponse.call(this.table, url, params, data);
9512 }
9513
9514 return data;
9515 });
9516 }else {
9517 return Promise.reject();
9518 }
9519 }
9520 }
9521
9522 var defaultPasteActions = {
9523 replace:function(data){
9524 return this.table.setData(data);
9525 },
9526 update:function(data){
9527 return this.table.updateOrAddData(data);
9528 },
9529 insert:function(data){
9530 return this.table.addData(data);
9531 },
9532 };
9533
9534 var defaultPasteParsers = {
9535 table:function(clipboard){
9536 var data = [],
9537 headerFindSuccess = true,
9538 columns = this.table.columnManager.columns,
9539 columnMap = [],
9540 rows = [];
9541
9542 //get data from clipboard into array of columns and rows.
9543 clipboard = clipboard.split("\n");
9544
9545 clipboard.forEach(function(row){
9546 data.push(row.split("\t"));
9547 });
9548
9549 if(data.length && !(data.length === 1 && data[0].length < 2)){
9550
9551 //check if headers are present by title
9552 data[0].forEach(function(value){
9553 var column = columns.find(function(column){
9554 return value && column.definition.title && value.trim() && column.definition.title.trim() === value.trim();
9555 });
9556
9557 if(column){
9558 columnMap.push(column);
9559 }else {
9560 headerFindSuccess = false;
9561 }
9562 });
9563
9564 //check if column headers are present by field
9565 if(!headerFindSuccess){
9566 headerFindSuccess = true;
9567 columnMap = [];
9568
9569 data[0].forEach(function(value){
9570 var column = columns.find(function(column){
9571 return value && column.field && value.trim() && column.field.trim() === value.trim();
9572 });
9573
9574 if(column){
9575 columnMap.push(column);
9576 }else {
9577 headerFindSuccess = false;
9578 }
9579 });
9580
9581 if(!headerFindSuccess){
9582 columnMap = this.table.columnManager.columnsByIndex;
9583 }
9584 }
9585
9586 //remove header row if found
9587 if(headerFindSuccess){
9588 data.shift();
9589 }
9590
9591 data.forEach(function(item){
9592 var row = {};
9593
9594 item.forEach(function(value, i){
9595 if(columnMap[i]){
9596 row[columnMap[i].field] = value;
9597 }
9598 });
9599
9600 rows.push(row);
9601 });
9602
9603 return rows;
9604 }else {
9605 return false;
9606 }
9607 },
9608 };
9609
9610 var bindings$2 = {
9611 copyToClipboard:["ctrl + 67", "meta + 67"],
9612 };
9613
9614 var actions$2 = {
9615 copyToClipboard:function(e){
9616 if(!this.table.modules.edit.currentCell){
9617 if(this.table.modExists("clipboard", true)){
9618 this.table.modules.clipboard.copy(false, true);
9619 }
9620 }
9621 },
9622 };
9623
9624 var extensions$4 = {
9625 keybindings:{
9626 bindings:bindings$2,
9627 actions:actions$2
9628 },
9629 };
9630
9631 class Clipboard extends Module{
9632
9633 static moduleName = "clipboard";
9634 static moduleExtensions = extensions$4;
9635
9636 //load defaults
9637 static pasteActions = defaultPasteActions;
9638 static pasteParsers = defaultPasteParsers;
9639
9640 constructor(table){
9641 super(table);
9642
9643 this.mode = true;
9644 this.pasteParser = function(){};
9645 this.pasteAction = function(){};
9646 this.customSelection = false;
9647 this.rowRange = false;
9648 this.blocked = true; //block copy actions not originating from this command
9649
9650 this.registerTableOption("clipboard", false); //enable clipboard
9651 this.registerTableOption("clipboardCopyStyled", true); //formatted table data
9652 this.registerTableOption("clipboardCopyConfig", false); //clipboard config
9653 this.registerTableOption("clipboardCopyFormatter", false); //DEPRECATED - REMOVE in 5.0
9654 this.registerTableOption("clipboardCopyRowRange", "active"); //restrict clipboard to visible rows only
9655 this.registerTableOption("clipboardPasteParser", "table"); //convert pasted clipboard data to rows
9656 this.registerTableOption("clipboardPasteAction", "insert"); //how to insert pasted data into the table
9657
9658 this.registerColumnOption("clipboard");
9659 this.registerColumnOption("titleClipboard");
9660 }
9661
9662 initialize(){
9663 this.mode = this.table.options.clipboard;
9664
9665 this.rowRange = this.table.options.clipboardCopyRowRange;
9666
9667 if(this.mode === true || this.mode === "copy"){
9668 this.table.element.addEventListener("copy", (e) => {
9669 var plain, html, list;
9670
9671 if(!this.blocked){
9672 e.preventDefault();
9673
9674 if(this.customSelection){
9675 plain = this.customSelection;
9676
9677 if(this.table.options.clipboardCopyFormatter){
9678 plain = this.table.options.clipboardCopyFormatter("plain", plain);
9679 }
9680 }else {
9681
9682 list = this.table.modules.export.generateExportList(this.table.options.clipboardCopyConfig, this.table.options.clipboardCopyStyled, this.rowRange, "clipboard");
9683
9684 html = this.table.modules.export.generateHTMLTable(list);
9685 plain = html ? this.generatePlainContent(list) : "";
9686
9687 if(this.table.options.clipboardCopyFormatter){
9688 plain = this.table.options.clipboardCopyFormatter("plain", plain);
9689 html = this.table.options.clipboardCopyFormatter("html", html);
9690 }
9691 }
9692
9693 if (window.clipboardData && window.clipboardData.setData) {
9694 window.clipboardData.setData('Text', plain);
9695 } else if (e.clipboardData && e.clipboardData.setData) {
9696 e.clipboardData.setData('text/plain', plain);
9697 if(html){
9698 e.clipboardData.setData('text/html', html);
9699 }
9700 } else if (e.originalEvent && e.originalEvent.clipboardData.setData) {
9701 e.originalEvent.clipboardData.setData('text/plain', plain);
9702 if(html){
9703 e.originalEvent.clipboardData.setData('text/html', html);
9704 }
9705 }
9706
9707 this.dispatchExternal("clipboardCopied", plain, html);
9708
9709 this.reset();
9710 }
9711 });
9712 }
9713
9714 if(this.mode === true || this.mode === "paste"){
9715 this.table.element.addEventListener("paste", (e) => {
9716 this.paste(e);
9717 });
9718 }
9719
9720 this.setPasteParser(this.table.options.clipboardPasteParser);
9721 this.setPasteAction(this.table.options.clipboardPasteAction);
9722
9723 this.registerTableFunction("copyToClipboard", this.copy.bind(this));
9724 }
9725
9726 reset(){
9727 this.blocked = true;
9728 this.customSelection = false;
9729 }
9730
9731 generatePlainContent (list) {
9732 var output = [];
9733
9734 list.forEach((row) => {
9735 var rowData = [];
9736
9737 row.columns.forEach((col) => {
9738 var value = "";
9739
9740 if(col){
9741
9742 if(row.type === "group"){
9743 col.value = col.component.getKey();
9744 }
9745
9746 if(col.value === null){
9747 value = "";
9748 }else {
9749 switch(typeof col.value){
9750 case "object":
9751 value = JSON.stringify(col.value);
9752 break;
9753
9754 case "undefined":
9755 value = "";
9756 break;
9757
9758 default:
9759 value = col.value;
9760 }
9761 }
9762 }
9763
9764 rowData.push(value);
9765 });
9766
9767 output.push(rowData.join("\t"));
9768 });
9769
9770 return output.join("\n");
9771 }
9772
9773 copy (range, internal) {
9774 var sel, textRange;
9775 this.blocked = false;
9776 this.customSelection = false;
9777
9778
9779 if (this.mode === true || this.mode === "copy") {
9780
9781 this.rowRange = range || this.table.options.clipboardCopyRowRange;
9782
9783 if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined") {
9784 range = document.createRange();
9785 range.selectNodeContents(this.table.element);
9786 sel = window.getSelection();
9787
9788 if (sel.toString() && internal) {
9789 this.customSelection = sel.toString();
9790 }
9791
9792 sel.removeAllRanges();
9793 sel.addRange(range);
9794 } else if (typeof document.selection != "undefined" && typeof document.body.createTextRange != "undefined") {
9795 textRange = document.body.createTextRange();
9796 textRange.moveToElementText(this.table.element);
9797 textRange.select();
9798 }
9799
9800 document.execCommand('copy');
9801
9802 if (sel) {
9803 sel.removeAllRanges();
9804 }
9805 }
9806 }
9807
9808 //PASTE EVENT HANDLING
9809 setPasteAction(action){
9810
9811 switch(typeof action){
9812 case "string":
9813 this.pasteAction = Clipboard.pasteActions[action];
9814
9815 if(!this.pasteAction){
9816 console.warn("Clipboard Error - No such paste action found:", action);
9817 }
9818 break;
9819
9820 case "function":
9821 this.pasteAction = action;
9822 break;
9823 }
9824 }
9825
9826 setPasteParser(parser){
9827 switch(typeof parser){
9828 case "string":
9829 this.pasteParser = Clipboard.pasteParsers[parser];
9830
9831 if(!this.pasteParser){
9832 console.warn("Clipboard Error - No such paste parser found:", parser);
9833 }
9834 break;
9835
9836 case "function":
9837 this.pasteParser = parser;
9838 break;
9839 }
9840 }
9841
9842 paste(e){
9843 var data, rowData, rows;
9844
9845 if(this.checkPasteOrigin(e)){
9846
9847 data = this.getPasteData(e);
9848
9849 rowData = this.pasteParser.call(this, data);
9850
9851 if(rowData){
9852 e.preventDefault();
9853
9854 if(this.table.modExists("mutator")){
9855 rowData = this.mutateData(rowData);
9856 }
9857
9858 rows = this.pasteAction.call(this, rowData);
9859
9860 this.dispatchExternal("clipboardPasted", data, rowData, rows);
9861 }else {
9862 this.dispatchExternal("clipboardPasteError", data);
9863 }
9864 }
9865 }
9866
9867 mutateData(data){
9868 var output = [];
9869
9870 if(Array.isArray(data)){
9871 data.forEach((row) => {
9872 output.push(this.table.modules.mutator.transformRow(row, "clipboard"));
9873 });
9874 }else {
9875 output = data;
9876 }
9877
9878 return output;
9879 }
9880
9881
9882 checkPasteOrigin(e){
9883 var valid = true;
9884 var blocked = this.confirm("clipboard-paste", [e]);
9885
9886 if(blocked || !["DIV", "SPAN"].includes(e.target.tagName)){
9887 valid = false;
9888 }
9889
9890 return valid;
9891 }
9892
9893 getPasteData(e){
9894 var data;
9895
9896 if (window.clipboardData && window.clipboardData.getData) {
9897 data = window.clipboardData.getData('Text');
9898 } else if (e.clipboardData && e.clipboardData.getData) {
9899 data = e.clipboardData.getData('text/plain');
9900 } else if (e.originalEvent && e.originalEvent.clipboardData.getData) {
9901 data = e.originalEvent.clipboardData.getData('text/plain');
9902 }
9903
9904 return data;
9905 }
9906 }
9907
9908 class CalcComponent{
9909 constructor (row){
9910 this._row = row;
9911
9912 return new Proxy(this, {
9913 get: function(target, name, receiver) {
9914 if (typeof target[name] !== "undefined") {
9915 return target[name];
9916 }else {
9917 return target._row.table.componentFunctionBinder.handle("row", target._row, name);
9918 }
9919 }
9920 });
9921 }
9922
9923 getData(transform){
9924 return this._row.getData(transform);
9925 }
9926
9927 getElement(){
9928 return this._row.getElement();
9929 }
9930
9931 getTable(){
9932 return this._row.table;
9933 }
9934
9935 getCells(){
9936 var cells = [];
9937
9938 this._row.getCells().forEach(function(cell){
9939 cells.push(cell.getComponent());
9940 });
9941
9942 return cells;
9943 }
9944
9945 getCell(column){
9946 var cell = this._row.getCell(column);
9947 return cell ? cell.getComponent() : false;
9948 }
9949
9950 _getSelf(){
9951 return this._row;
9952 }
9953 }
9954
9955 var defaultCalculations = {
9956 "avg":function(values, data, calcParams){
9957 var output = 0,
9958 precision = typeof calcParams.precision !== "undefined" ? calcParams.precision : 2;
9959
9960 if(values.length){
9961 output = values.reduce(function(sum, value){
9962 return Number(sum) + Number(value);
9963 });
9964
9965 output = output / values.length;
9966
9967 output = precision !== false ? output.toFixed(precision) : output;
9968 }
9969
9970 return parseFloat(output).toString();
9971 },
9972 "max":function(values, data, calcParams){
9973 var output = null,
9974 precision = typeof calcParams.precision !== "undefined" ? calcParams.precision : false;
9975
9976 values.forEach(function(value){
9977
9978 value = Number(value);
9979
9980 if(value > output || output === null){
9981 output = value;
9982 }
9983 });
9984
9985 return output !== null ? (precision !== false ? output.toFixed(precision) : output) : "";
9986 },
9987 "min":function(values, data, calcParams){
9988 var output = null,
9989 precision = typeof calcParams.precision !== "undefined" ? calcParams.precision : false;
9990
9991 values.forEach(function(value){
9992
9993 value = Number(value);
9994
9995 if(value < output || output === null){
9996 output = value;
9997 }
9998 });
9999
10000 return output !== null ? (precision !== false ? output.toFixed(precision) : output) : "";
10001 },
10002 "sum":function(values, data, calcParams){
10003 var output = 0,
10004 precision = typeof calcParams.precision !== "undefined" ? calcParams.precision : false;
10005
10006 if(values.length){
10007 values.forEach(function(value){
10008 value = Number(value);
10009
10010 output += !isNaN(value) ? Number(value) : 0;
10011 });
10012 }
10013
10014 return precision !== false ? output.toFixed(precision) : output;
10015 },
10016 "concat":function(values, data, calcParams){
10017 var output = 0;
10018
10019 if(values.length){
10020 output = values.reduce(function(sum, value){
10021 return String(sum) + String(value);
10022 });
10023 }
10024
10025 return output;
10026 },
10027 "count":function(values, data, calcParams){
10028 var output = 0;
10029
10030 if(values.length){
10031 values.forEach(function(value){
10032 if(value){
10033 output ++;
10034 }
10035 });
10036 }
10037
10038 return output;
10039 },
10040 "unique":function(values, data, calcParams){
10041 var unique = values.filter((value, index) => {
10042 return (values || value === 0) && values.indexOf(value) === index;
10043 });
10044
10045 return unique.length;
10046 },
10047 };
10048
10049 class ColumnCalcs extends Module{
10050
10051 static moduleName = "columnCalcs";
10052
10053 //load defaults
10054 static calculations = defaultCalculations;
10055
10056 constructor(table){
10057 super(table);
10058
10059 this.topCalcs = [];
10060 this.botCalcs = [];
10061 this.genColumn = false;
10062 this.topElement = this.createElement();
10063 this.botElement = this.createElement();
10064 this.topRow = false;
10065 this.botRow = false;
10066 this.topInitialized = false;
10067 this.botInitialized = false;
10068
10069 this.blocked = false;
10070 this.recalcAfterBlock = false;
10071
10072 this.registerTableOption("columnCalcs", true);
10073
10074 this.registerColumnOption("topCalc");
10075 this.registerColumnOption("topCalcParams");
10076 this.registerColumnOption("topCalcFormatter");
10077 this.registerColumnOption("topCalcFormatterParams");
10078 this.registerColumnOption("bottomCalc");
10079 this.registerColumnOption("bottomCalcParams");
10080 this.registerColumnOption("bottomCalcFormatter");
10081 this.registerColumnOption("bottomCalcFormatterParams");
10082 }
10083
10084 createElement (){
10085 var el = document.createElement("div");
10086 el.classList.add("tabulator-calcs-holder");
10087 return el;
10088 }
10089
10090 initialize(){
10091 this.genColumn = new Column({field:"value"}, this);
10092
10093 this.subscribe("cell-value-changed", this.cellValueChanged.bind(this));
10094 this.subscribe("column-init", this.initializeColumnCheck.bind(this));
10095 this.subscribe("row-deleted", this.rowsUpdated.bind(this));
10096 this.subscribe("scroll-horizontal", this.scrollHorizontal.bind(this));
10097 this.subscribe("row-added", this.rowsUpdated.bind(this));
10098 this.subscribe("column-moved", this.recalcActiveRows.bind(this));
10099 this.subscribe("column-add", this.recalcActiveRows.bind(this));
10100 this.subscribe("data-refreshed", this.recalcActiveRowsRefresh.bind(this));
10101 this.subscribe("table-redraw", this.tableRedraw.bind(this));
10102 this.subscribe("rows-visible", this.visibleRows.bind(this));
10103 this.subscribe("scrollbar-vertical", this.adjustForScrollbar.bind(this));
10104
10105 this.subscribe("redraw-blocked", this.blockRedraw.bind(this));
10106 this.subscribe("redraw-restored", this.restoreRedraw.bind(this));
10107
10108 this.subscribe("table-redrawing", this.resizeHolderWidth.bind(this));
10109 this.subscribe("column-resized", this.resizeHolderWidth.bind(this));
10110 this.subscribe("column-show", this.resizeHolderWidth.bind(this));
10111 this.subscribe("column-hide", this.resizeHolderWidth.bind(this));
10112
10113 this.registerTableFunction("getCalcResults", this.getResults.bind(this));
10114 this.registerTableFunction("recalc", this.userRecalc.bind(this));
10115
10116
10117 this.resizeHolderWidth();
10118 }
10119
10120 resizeHolderWidth(){
10121 this.topElement.style.minWidth = this.table.columnManager.headersElement.offsetWidth + "px";
10122 }
10123
10124
10125 tableRedraw(force){
10126 this.recalc(this.table.rowManager.activeRows);
10127
10128 if(force){
10129 this.redraw();
10130 }
10131 }
10132
10133 blockRedraw(){
10134 this.blocked = true;
10135 this.recalcAfterBlock = false;
10136 }
10137
10138
10139 restoreRedraw(){
10140 this.blocked = false;
10141
10142 if(this.recalcAfterBlock){
10143 this.recalcAfterBlock = false;
10144 this.recalcActiveRowsRefresh();
10145 }
10146 }
10147
10148 ///////////////////////////////////
10149 ///////// Table Functions /////////
10150 ///////////////////////////////////
10151 userRecalc(){
10152 this.recalc(this.table.rowManager.activeRows);
10153 }
10154
10155 ///////////////////////////////////
10156 ///////// Internal Logic //////////
10157 ///////////////////////////////////
10158
10159 blockCheck(){
10160 if(this.blocked){
10161 this.recalcAfterBlock = true;
10162 }
10163
10164 return this.blocked;
10165 }
10166
10167 visibleRows(viewable, rows){
10168 if(this.topRow){
10169 rows.unshift(this.topRow);
10170 }
10171
10172 if(this.botRow){
10173 rows.push(this.botRow);
10174 }
10175
10176 return rows;
10177 }
10178
10179 rowsUpdated(row){
10180 if(this.table.options.groupBy){
10181 this.recalcRowGroup(row);
10182 }else {
10183 this.recalcActiveRows();
10184 }
10185 }
10186
10187 recalcActiveRowsRefresh(){
10188 if(this.table.options.groupBy && this.table.options.dataTreeStartExpanded && this.table.options.dataTree){
10189 this.recalcAll();
10190 }else {
10191 this.recalcActiveRows();
10192 }
10193 }
10194
10195 recalcActiveRows(){
10196 this.recalc(this.table.rowManager.activeRows);
10197 }
10198
10199 cellValueChanged(cell){
10200 if(cell.column.definition.topCalc || cell.column.definition.bottomCalc){
10201 if(this.table.options.groupBy){
10202 if(this.table.options.columnCalcs == "table" || this.table.options.columnCalcs == "both"){
10203 this.recalcActiveRows();
10204 }
10205
10206 if(this.table.options.columnCalcs != "table"){
10207 this.recalcRowGroup(cell.row);
10208 }
10209 }else {
10210 this.recalcActiveRows();
10211 }
10212 }
10213 }
10214
10215 initializeColumnCheck(column){
10216 if(column.definition.topCalc || column.definition.bottomCalc){
10217 this.initializeColumn(column);
10218 }
10219 }
10220
10221 //initialize column calcs
10222 initializeColumn(column){
10223 var def = column.definition;
10224
10225 var config = {
10226 topCalcParams:def.topCalcParams || {},
10227 botCalcParams:def.bottomCalcParams || {},
10228 };
10229
10230 if(def.topCalc){
10231
10232 switch(typeof def.topCalc){
10233 case "string":
10234 if(ColumnCalcs.calculations[def.topCalc]){
10235 config.topCalc = ColumnCalcs.calculations[def.topCalc];
10236 }else {
10237 console.warn("Column Calc Error - No such calculation found, ignoring: ", def.topCalc);
10238 }
10239 break;
10240
10241 case "function":
10242 config.topCalc = def.topCalc;
10243 break;
10244
10245 }
10246
10247 if(config.topCalc){
10248 column.modules.columnCalcs = config;
10249 this.topCalcs.push(column);
10250
10251 if(this.table.options.columnCalcs != "group"){
10252 this.initializeTopRow();
10253 }
10254 }
10255
10256 }
10257
10258 if(def.bottomCalc){
10259 switch(typeof def.bottomCalc){
10260 case "string":
10261 if(ColumnCalcs.calculations[def.bottomCalc]){
10262 config.botCalc = ColumnCalcs.calculations[def.bottomCalc];
10263 }else {
10264 console.warn("Column Calc Error - No such calculation found, ignoring: ", def.bottomCalc);
10265 }
10266 break;
10267
10268 case "function":
10269 config.botCalc = def.bottomCalc;
10270 break;
10271
10272 }
10273
10274 if(config.botCalc){
10275 column.modules.columnCalcs = config;
10276 this.botCalcs.push(column);
10277
10278 if(this.table.options.columnCalcs != "group"){
10279 this.initializeBottomRow();
10280 }
10281 }
10282 }
10283
10284 }
10285
10286 //dummy functions to handle being mock column manager
10287 registerColumnField(){}
10288
10289 removeCalcs(){
10290 var changed = false;
10291
10292 if(this.topInitialized){
10293 this.topInitialized = false;
10294 this.topElement.parentNode.removeChild(this.topElement);
10295 changed = true;
10296 }
10297
10298 if(this.botInitialized){
10299 this.botInitialized = false;
10300 this.footerRemove(this.botElement);
10301 changed = true;
10302 }
10303
10304 if(changed){
10305 this.table.rowManager.adjustTableSize();
10306 }
10307 }
10308
10309 reinitializeCalcs(){
10310 if(this.topCalcs.length){
10311 this.initializeTopRow();
10312 }
10313
10314 if(this.botCalcs.length){
10315 this.initializeBottomRow();
10316 }
10317 }
10318
10319 initializeTopRow(){
10320 var fragment = document.createDocumentFragment();
10321
10322 if(!this.topInitialized){
10323
10324 fragment.appendChild(document.createElement("br"));
10325 fragment.appendChild(this.topElement);
10326
10327 this.table.columnManager.getContentsElement().insertBefore(fragment, this.table.columnManager.headersElement.nextSibling);
10328 this.topInitialized = true;
10329 }
10330 }
10331
10332 initializeBottomRow(){
10333 if(!this.botInitialized){
10334 this.footerPrepend(this.botElement);
10335 this.botInitialized = true;
10336 }
10337 }
10338
10339 scrollHorizontal(left){
10340 if(this.botInitialized && this.botRow){
10341 this.botElement.scrollLeft = left;
10342 }
10343 }
10344
10345 recalc(rows){
10346 var data, row;
10347
10348 if(!this.blockCheck()){
10349 if(this.topInitialized || this.botInitialized){
10350 data = this.rowsToData(rows);
10351
10352 if(this.topInitialized){
10353 if(this.topRow){
10354 this.topRow.deleteCells();
10355 }
10356
10357 row = this.generateRow("top", data);
10358 this.topRow = row;
10359 while(this.topElement.firstChild) this.topElement.removeChild(this.topElement.firstChild);
10360 this.topElement.appendChild(row.getElement());
10361 row.initialize(true);
10362 }
10363
10364 if(this.botInitialized){
10365 if(this.botRow){
10366 this.botRow.deleteCells();
10367 }
10368
10369 row = this.generateRow("bottom", data);
10370 this.botRow = row;
10371 while(this.botElement.firstChild) this.botElement.removeChild(this.botElement.firstChild);
10372 this.botElement.appendChild(row.getElement());
10373 row.initialize(true);
10374 }
10375
10376 this.table.rowManager.adjustTableSize();
10377
10378 //set resizable handles
10379 if(this.table.modExists("frozenColumns")){
10380 this.table.modules.frozenColumns.layout();
10381 }
10382 }
10383 }
10384 }
10385
10386 recalcRowGroup(row){
10387 this.recalcGroup(this.table.modules.groupRows.getRowGroup(row));
10388 }
10389
10390 recalcAll(){
10391 if(this.topCalcs.length || this.botCalcs.length){
10392 if(this.table.options.columnCalcs !== "group"){
10393 this.recalcActiveRows();
10394 }
10395
10396 if(this.table.options.groupBy && this.table.options.columnCalcs !== "table"){
10397
10398 var groups = this.table.modules.groupRows.getChildGroups();
10399
10400 groups.forEach((group) => {
10401 this.recalcGroup(group);
10402 });
10403 }
10404 }
10405 }
10406
10407 recalcGroup(group){
10408 var data, rowData;
10409
10410 if(!this.blockCheck()){
10411 if(group){
10412 if(group.calcs){
10413 if(group.calcs.bottom){
10414 data = this.rowsToData(group.rows);
10415 rowData = this.generateRowData("bottom", data);
10416
10417 group.calcs.bottom.updateData(rowData);
10418 group.calcs.bottom.reinitialize();
10419 }
10420
10421 if(group.calcs.top){
10422 data = this.rowsToData(group.rows);
10423 rowData = this.generateRowData("top", data);
10424
10425 group.calcs.top.updateData(rowData);
10426 group.calcs.top.reinitialize();
10427 }
10428 }
10429 }
10430 }
10431 }
10432
10433 //generate top stats row
10434 generateTopRow(rows){
10435 return this.generateRow("top", this.rowsToData(rows));
10436 }
10437 //generate bottom stats row
10438 generateBottomRow(rows){
10439 return this.generateRow("bottom", this.rowsToData(rows));
10440 }
10441
10442 rowsToData(rows){
10443 var data = [],
10444 hasDataTreeColumnCalcs = this.table.options.dataTree && this.table.options.dataTreeChildColumnCalcs,
10445 dataTree = this.table.modules.dataTree;
10446
10447 rows.forEach((row) => {
10448 data.push(row.getData());
10449
10450 if(hasDataTreeColumnCalcs && row.modules.dataTree?.open){
10451 this.rowsToData(dataTree.getFilteredTreeChildren(row)).forEach(dataRow =>{
10452 data.push(row);
10453 });
10454 }
10455 });
10456 return data;
10457 }
10458
10459 //generate stats row
10460 generateRow(pos, data){
10461 var rowData = this.generateRowData(pos, data),
10462 row;
10463
10464 if(this.table.modExists("mutator")){
10465 this.table.modules.mutator.disable();
10466 }
10467
10468 row = new Row(rowData, this, "calc");
10469
10470 if(this.table.modExists("mutator")){
10471 this.table.modules.mutator.enable();
10472 }
10473
10474 row.getElement().classList.add("tabulator-calcs", "tabulator-calcs-" + pos);
10475
10476 row.component = false;
10477
10478 row.getComponent = () => {
10479 if(!row.component){
10480 row.component = new CalcComponent(row);
10481 }
10482
10483 return row.component;
10484 };
10485
10486 row.generateCells = () => {
10487
10488 var cells = [];
10489
10490 this.table.columnManager.columnsByIndex.forEach((column) => {
10491
10492 //set field name of mock column
10493 this.genColumn.setField(column.getField());
10494 this.genColumn.hozAlign = column.hozAlign;
10495
10496 if(column.definition[pos + "CalcFormatter"] && this.table.modExists("format")){
10497 this.genColumn.modules.format = {
10498 formatter: this.table.modules.format.lookupFormatter(column.definition[pos + "CalcFormatter"]),
10499 params: column.definition[pos + "CalcFormatterParams"] || {},
10500 };
10501 }else {
10502 this.genColumn.modules.format = {
10503 formatter: this.table.modules.format.lookupFormatter("plaintext"),
10504 params:{}
10505 };
10506 }
10507
10508 //ensure css class definition is replicated to calculation cell
10509 this.genColumn.definition.cssClass = column.definition.cssClass;
10510
10511 //generate cell and assign to correct column
10512 var cell = new Cell(this.genColumn, row);
10513 cell.getElement();
10514 cell.column = column;
10515 cell.setWidth();
10516
10517 column.cells.push(cell);
10518 cells.push(cell);
10519
10520 if(!column.visible){
10521 cell.hide();
10522 }
10523 });
10524
10525 row.cells = cells;
10526 };
10527
10528 return row;
10529 }
10530
10531 //generate stats row
10532 generateRowData(pos, data){
10533 var rowData = {},
10534 calcs = pos == "top" ? this.topCalcs : this.botCalcs,
10535 type = pos == "top" ? "topCalc" : "botCalc",
10536 params, paramKey;
10537
10538 calcs.forEach(function(column){
10539 var values = [];
10540
10541 if(column.modules.columnCalcs && column.modules.columnCalcs[type]){
10542 data.forEach(function(item){
10543 values.push(column.getFieldValue(item));
10544 });
10545
10546 paramKey = type + "Params";
10547 params = typeof column.modules.columnCalcs[paramKey] === "function" ? column.modules.columnCalcs[paramKey](values, data) : column.modules.columnCalcs[paramKey];
10548
10549 column.setFieldValue(rowData, column.modules.columnCalcs[type](values, data, params));
10550 }
10551 });
10552
10553 return rowData;
10554 }
10555
10556 hasTopCalcs(){
10557 return !!(this.topCalcs.length);
10558 }
10559
10560 hasBottomCalcs(){
10561 return !!(this.botCalcs.length);
10562 }
10563
10564 //handle table redraw
10565 redraw(){
10566 if(this.topRow){
10567 this.topRow.normalizeHeight(true);
10568 }
10569 if(this.botRow){
10570 this.botRow.normalizeHeight(true);
10571 }
10572 }
10573
10574 //return the calculated
10575 getResults(){
10576 var results = {},
10577 groups;
10578
10579 if(this.table.options.groupBy && this.table.modExists("groupRows")){
10580 groups = this.table.modules.groupRows.getGroups(true);
10581
10582 groups.forEach((group) => {
10583 results[group.getKey()] = this.getGroupResults(group);
10584 });
10585 }else {
10586 results = {
10587 top: this.topRow ? this.topRow.getData() : {},
10588 bottom: this.botRow ? this.botRow.getData() : {},
10589 };
10590 }
10591
10592 return results;
10593 }
10594
10595 //get results from a group
10596 getGroupResults(group){
10597 var groupObj = group._getSelf(),
10598 subGroups = group.getSubGroups(),
10599 subGroupResults = {},
10600 results = {};
10601
10602 subGroups.forEach((subgroup) => {
10603 subGroupResults[subgroup.getKey()] = this.getGroupResults(subgroup);
10604 });
10605
10606 results = {
10607 top: groupObj.calcs.top ? groupObj.calcs.top.getData() : {},
10608 bottom: groupObj.calcs.bottom ? groupObj.calcs.bottom.getData() : {},
10609 groups: subGroupResults,
10610 };
10611
10612 return results;
10613 }
10614
10615 adjustForScrollbar(width){
10616 if(this.botRow){
10617 if(this.table.rtl){
10618 this.botElement.style.paddingLeft = width + "px";
10619 }else {
10620 this.botElement.style.paddingRight = width + "px";
10621 }
10622 }
10623 }
10624 }
10625
10626 class DataTree extends Module{
10627
10628 static moduleName = "dataTree";
10629
10630 constructor(table){
10631 super(table);
10632
10633 this.indent = 10;
10634 this.field = "";
10635 this.collapseEl = null;
10636 this.expandEl = null;
10637 this.branchEl = null;
10638 this.elementField = false;
10639
10640 this.startOpen = function(){};
10641
10642 this.registerTableOption("dataTree", false); //enable data tree
10643 this.registerTableOption("dataTreeFilter", true); //filter child rows
10644 this.registerTableOption("dataTreeSort", true); //sort child rows
10645 this.registerTableOption("dataTreeElementColumn", false);
10646 this.registerTableOption("dataTreeBranchElement", true);//show data tree branch element
10647 this.registerTableOption("dataTreeChildIndent", 9); //data tree child indent in px
10648 this.registerTableOption("dataTreeChildField", "_children");//data tre column field to look for child rows
10649 this.registerTableOption("dataTreeCollapseElement", false);//data tree row collapse element
10650 this.registerTableOption("dataTreeExpandElement", false);//data tree row expand element
10651 this.registerTableOption("dataTreeStartExpanded", false);
10652 this.registerTableOption("dataTreeChildColumnCalcs", false);//include visible data tree rows in column calculations
10653 this.registerTableOption("dataTreeSelectPropagate", false);//selecting a parent row selects its children
10654
10655 //register component functions
10656 this.registerComponentFunction("row", "treeCollapse", this.collapseRow.bind(this));
10657 this.registerComponentFunction("row", "treeExpand", this.expandRow.bind(this));
10658 this.registerComponentFunction("row", "treeToggle", this.toggleRow.bind(this));
10659 this.registerComponentFunction("row", "getTreeParent", this.getTreeParent.bind(this));
10660 this.registerComponentFunction("row", "getTreeChildren", this.getRowChildren.bind(this));
10661 this.registerComponentFunction("row", "addTreeChild", this.addTreeChildRow.bind(this));
10662 this.registerComponentFunction("row", "isTreeExpanded", this.isRowExpanded.bind(this));
10663 }
10664
10665 initialize(){
10666 if(this.table.options.dataTree){
10667 var dummyEl = null,
10668 options = this.table.options;
10669
10670 this.field = options.dataTreeChildField;
10671 this.indent = options.dataTreeChildIndent;
10672
10673 if(this.options("movableRows")){
10674 console.warn("The movableRows option is not available with dataTree enabled, moving of child rows could result in unpredictable behavior");
10675 }
10676
10677 if(options.dataTreeBranchElement){
10678
10679 if(options.dataTreeBranchElement === true){
10680 this.branchEl = document.createElement("div");
10681 this.branchEl.classList.add("tabulator-data-tree-branch");
10682 }else {
10683 if(typeof options.dataTreeBranchElement === "string"){
10684 dummyEl = document.createElement("div");
10685 dummyEl.innerHTML = options.dataTreeBranchElement;
10686 this.branchEl = dummyEl.firstChild;
10687 }else {
10688 this.branchEl = options.dataTreeBranchElement;
10689 }
10690 }
10691 }else {
10692 this.branchEl = document.createElement("div");
10693 this.branchEl.classList.add("tabulator-data-tree-branch-empty");
10694 }
10695
10696 if(options.dataTreeCollapseElement){
10697 if(typeof options.dataTreeCollapseElement === "string"){
10698 dummyEl = document.createElement("div");
10699 dummyEl.innerHTML = options.dataTreeCollapseElement;
10700 this.collapseEl = dummyEl.firstChild;
10701 }else {
10702 this.collapseEl = options.dataTreeCollapseElement;
10703 }
10704 }else {
10705 this.collapseEl = document.createElement("div");
10706 this.collapseEl.classList.add("tabulator-data-tree-control");
10707 this.collapseEl.tabIndex = 0;
10708 this.collapseEl.innerHTML = "<div class='tabulator-data-tree-control-collapse'></div>";
10709 }
10710
10711 if(options.dataTreeExpandElement){
10712 if(typeof options.dataTreeExpandElement === "string"){
10713 dummyEl = document.createElement("div");
10714 dummyEl.innerHTML = options.dataTreeExpandElement;
10715 this.expandEl = dummyEl.firstChild;
10716 }else {
10717 this.expandEl = options.dataTreeExpandElement;
10718 }
10719 }else {
10720 this.expandEl = document.createElement("div");
10721 this.expandEl.classList.add("tabulator-data-tree-control");
10722 this.expandEl.tabIndex = 0;
10723 this.expandEl.innerHTML = "<div class='tabulator-data-tree-control-expand'></div>";
10724 }
10725
10726
10727 switch(typeof options.dataTreeStartExpanded){
10728 case "boolean":
10729 this.startOpen = function(row, index){
10730 return options.dataTreeStartExpanded;
10731 };
10732 break;
10733
10734 case "function":
10735 this.startOpen = options.dataTreeStartExpanded;
10736 break;
10737
10738 default:
10739 this.startOpen = function(row, index){
10740 return options.dataTreeStartExpanded[index];
10741 };
10742 break;
10743 }
10744
10745 this.subscribe("row-init", this.initializeRow.bind(this));
10746 this.subscribe("row-layout-after", this.layoutRow.bind(this));
10747 this.subscribe("row-deleting", this.rowDeleting.bind(this));
10748 this.subscribe("row-deleted", this.rowDelete.bind(this),0);
10749 this.subscribe("row-data-changed", this.rowDataChanged.bind(this), 10);
10750 this.subscribe("cell-value-updated", this.cellValueChanged.bind(this));
10751 this.subscribe("edit-cancelled", this.cellValueChanged.bind(this));
10752 this.subscribe("column-moving-rows", this.columnMoving.bind(this));
10753 this.subscribe("table-built", this.initializeElementField.bind(this));
10754 this.subscribe("table-redrawing", this.tableRedrawing.bind(this));
10755
10756 this.registerDisplayHandler(this.getRows.bind(this), 30);
10757 }
10758 }
10759
10760 tableRedrawing(force){
10761 var rows;
10762
10763 if(force){
10764 rows = this.table.rowManager.getRows();
10765
10766 rows.forEach((row) => {
10767 this.reinitializeRowChildren(row);
10768 });
10769 }
10770 }
10771
10772 initializeElementField(){
10773 var firstCol = this.table.columnManager.getFirstVisibleColumn();
10774
10775 this.elementField = this.table.options.dataTreeElementColumn || (firstCol ? firstCol.field : false);
10776 }
10777
10778 getRowChildren(row){
10779 return this.getTreeChildren(row, true);
10780 }
10781
10782 columnMoving(){
10783 var rows = [];
10784
10785 this.table.rowManager.rows.forEach((row) => {
10786 rows = rows.concat(this.getTreeChildren(row, false, true));
10787 });
10788
10789 return rows;
10790 }
10791
10792 rowDataChanged(row, visible, updatedData){
10793 if(this.redrawNeeded(updatedData)){
10794 this.initializeRow(row);
10795
10796 if(visible){
10797 this.layoutRow(row);
10798 this.refreshData(true);
10799 }
10800 }
10801 }
10802
10803 cellValueChanged(cell){
10804 var field = cell.column.getField();
10805
10806 if(field === this.elementField){
10807 this.layoutRow(cell.row);
10808 }
10809 }
10810
10811 initializeRow(row){
10812 var childArray = row.getData()[this.field];
10813 var isArray = Array.isArray(childArray);
10814
10815 var children = isArray || (!isArray && typeof childArray === "object" && childArray !== null);
10816
10817 if(!children && row.modules.dataTree && row.modules.dataTree.branchEl && row.modules.dataTree.branchEl.parentNode){
10818 row.modules.dataTree.branchEl.parentNode.removeChild(row.modules.dataTree.branchEl);
10819 }
10820
10821 if(!children && row.modules.dataTree && row.modules.dataTree.controlEl && row.modules.dataTree.controlEl.parentNode){
10822 row.modules.dataTree.controlEl.parentNode.removeChild(row.modules.dataTree.controlEl);
10823 }
10824
10825 row.modules.dataTree = {
10826 index: row.modules.dataTree ? row.modules.dataTree.index : 0,
10827 open: children ? (row.modules.dataTree ? row.modules.dataTree.open : this.startOpen(row.getComponent(), 0)) : false,
10828 controlEl: row.modules.dataTree && children ? row.modules.dataTree.controlEl : false,
10829 branchEl: row.modules.dataTree && children ? row.modules.dataTree.branchEl : false,
10830 parent: row.modules.dataTree ? row.modules.dataTree.parent : false,
10831 children:children,
10832 };
10833 }
10834
10835 reinitializeRowChildren(row){
10836 var children = this.getTreeChildren(row, false, true);
10837
10838 children.forEach(function(child){
10839 child.reinitialize(true);
10840 });
10841 }
10842
10843 layoutRow(row){
10844 var cell = this.elementField ? row.getCell(this.elementField) : row.getCells()[0],
10845 el = cell.getElement(),
10846 config = row.modules.dataTree;
10847
10848 if(config.branchEl){
10849 if(config.branchEl.parentNode){
10850 config.branchEl.parentNode.removeChild(config.branchEl);
10851 }
10852 config.branchEl = false;
10853 }
10854
10855 if(config.controlEl){
10856 if(config.controlEl.parentNode){
10857 config.controlEl.parentNode.removeChild(config.controlEl);
10858 }
10859 config.controlEl = false;
10860 }
10861
10862 this.generateControlElement(row, el);
10863
10864 row.getElement().classList.add("tabulator-tree-level-" + config.index);
10865
10866 if(config.index){
10867 if(this.branchEl){
10868 config.branchEl = this.branchEl.cloneNode(true);
10869 el.insertBefore(config.branchEl, el.firstChild);
10870
10871 if(this.table.rtl){
10872 config.branchEl.style.marginRight = (((config.branchEl.offsetWidth + config.branchEl.style.marginLeft) * (config.index - 1)) + (config.index * this.indent)) + "px";
10873 }else {
10874 config.branchEl.style.marginLeft = (((config.branchEl.offsetWidth + config.branchEl.style.marginRight) * (config.index - 1)) + (config.index * this.indent)) + "px";
10875 }
10876 }else {
10877
10878 if(this.table.rtl){
10879 el.style.paddingRight = parseInt(window.getComputedStyle(el, null).getPropertyValue('padding-right')) + (config.index * this.indent) + "px";
10880 }else {
10881 el.style.paddingLeft = parseInt(window.getComputedStyle(el, null).getPropertyValue('padding-left')) + (config.index * this.indent) + "px";
10882 }
10883 }
10884 }
10885 }
10886
10887 generateControlElement(row, el){
10888 var config = row.modules.dataTree,
10889 oldControl = config.controlEl;
10890
10891 el = el || row.getCells()[0].getElement();
10892
10893 if(config.children !== false){
10894
10895 if(config.open){
10896 config.controlEl = this.collapseEl.cloneNode(true);
10897 config.controlEl.addEventListener("click", (e) => {
10898 e.stopPropagation();
10899 this.collapseRow(row);
10900 });
10901 }else {
10902 config.controlEl = this.expandEl.cloneNode(true);
10903 config.controlEl.addEventListener("click", (e) => {
10904 e.stopPropagation();
10905 this.expandRow(row);
10906 });
10907 }
10908
10909 config.controlEl.addEventListener("mousedown", (e) => {
10910 e.stopPropagation();
10911 });
10912
10913 if(oldControl && oldControl.parentNode === el){
10914 oldControl.parentNode.replaceChild(config.controlEl,oldControl);
10915 }else {
10916 el.insertBefore(config.controlEl, el.firstChild);
10917 }
10918 }
10919 }
10920
10921 getRows(rows){
10922 var output = [];
10923
10924 rows.forEach((row, i) => {
10925 var config, children;
10926
10927 output.push(row);
10928
10929 if(row instanceof Row){
10930
10931 row.create();
10932
10933 config = row.modules.dataTree;
10934
10935 if(!config.index && config.children !== false){
10936 children = this.getChildren(row, false, true);
10937
10938 children.forEach((child) => {
10939 child.create();
10940 output.push(child);
10941 });
10942 }
10943 }
10944 });
10945
10946 return output;
10947 }
10948
10949 getChildren(row, allChildren, sortOnly){
10950 var config = row.modules.dataTree,
10951 children = [],
10952 output = [];
10953
10954 if(config.children !== false && (config.open || allChildren)){
10955 if(!Array.isArray(config.children)){
10956 config.children = this.generateChildren(row);
10957 }
10958
10959 if(this.table.modExists("filter") && this.table.options.dataTreeFilter){
10960 children = this.table.modules.filter.filter(config.children);
10961 }else {
10962 children = config.children;
10963 }
10964
10965 if(this.table.modExists("sort") && this.table.options.dataTreeSort){
10966 this.table.modules.sort.sort(children, sortOnly);
10967 }
10968
10969 children.forEach((child) => {
10970 output.push(child);
10971
10972 var subChildren = this.getChildren(child, false, true);
10973
10974 subChildren.forEach((sub) => {
10975 output.push(sub);
10976 });
10977 });
10978 }
10979
10980 return output;
10981 }
10982
10983 generateChildren(row){
10984 var children = [];
10985
10986 var childArray = row.getData()[this.field];
10987
10988 if(!Array.isArray(childArray)){
10989 childArray = [childArray];
10990 }
10991
10992 childArray.forEach((childData) => {
10993 var childRow = new Row(childData || {}, this.table.rowManager);
10994
10995 childRow.create();
10996
10997 childRow.modules.dataTree.index = row.modules.dataTree.index + 1;
10998 childRow.modules.dataTree.parent = row;
10999
11000 if(childRow.modules.dataTree.children){
11001 childRow.modules.dataTree.open = this.startOpen(childRow.getComponent(), childRow.modules.dataTree.index);
11002 }
11003 children.push(childRow);
11004 });
11005
11006 return children;
11007 }
11008
11009 expandRow(row, silent){
11010 var config = row.modules.dataTree;
11011
11012 if(config.children !== false){
11013 config.open = true;
11014
11015 row.reinitialize();
11016
11017 this.refreshData(true);
11018
11019 this.dispatchExternal("dataTreeRowExpanded", row.getComponent(), row.modules.dataTree.index);
11020 }
11021 }
11022
11023 collapseRow(row){
11024 var config = row.modules.dataTree;
11025
11026 if(config.children !== false){
11027 config.open = false;
11028
11029 row.reinitialize();
11030
11031 this.refreshData(true);
11032
11033 this.dispatchExternal("dataTreeRowCollapsed", row.getComponent(), row.modules.dataTree.index);
11034 }
11035 }
11036
11037 toggleRow(row){
11038 var config = row.modules.dataTree;
11039
11040 if(config.children !== false){
11041 if(config.open){
11042 this.collapseRow(row);
11043 }else {
11044 this.expandRow(row);
11045 }
11046 }
11047 }
11048
11049 isRowExpanded(row){
11050 return row.modules.dataTree.open;
11051 }
11052
11053 getTreeParent(row){
11054 return row.modules.dataTree.parent ? row.modules.dataTree.parent.getComponent() : false;
11055 }
11056
11057 getTreeParentRoot(row){
11058 return row.modules.dataTree && row.modules.dataTree.parent ? this.getTreeParentRoot(row.modules.dataTree.parent) : row;
11059 }
11060
11061 getFilteredTreeChildren(row){
11062 var config = row.modules.dataTree,
11063 output = [], children;
11064
11065 if(config.children){
11066
11067 if(!Array.isArray(config.children)){
11068 config.children = this.generateChildren(row);
11069 }
11070
11071 if(this.table.modExists("filter") && this.table.options.dataTreeFilter){
11072 children = this.table.modules.filter.filter(config.children);
11073 }else {
11074 children = config.children;
11075 }
11076
11077 children.forEach((childRow) => {
11078 if(childRow instanceof Row){
11079 output.push(childRow);
11080 }
11081 });
11082 }
11083
11084 return output;
11085 }
11086
11087 rowDeleting(row){
11088 var config = row.modules.dataTree;
11089
11090 if (config && config.children && Array.isArray(config.children)){
11091 config.children.forEach((childRow) => {
11092 if(childRow instanceof Row){
11093 childRow.wipe();
11094 }
11095 });
11096 }
11097 }
11098
11099 rowDelete(row){
11100 var parent = row.modules.dataTree.parent,
11101 childIndex;
11102
11103 if(parent){
11104 childIndex = this.findChildIndex(row, parent);
11105
11106 if(childIndex !== false){
11107 parent.data[this.field].splice(childIndex, 1);
11108 }
11109
11110 if(!parent.data[this.field].length){
11111 delete parent.data[this.field];
11112 }
11113
11114 this.initializeRow(parent);
11115 this.layoutRow(parent);
11116 }
11117
11118 this.refreshData(true);
11119 }
11120
11121 addTreeChildRow(row, data, top, index){
11122 var childIndex = false;
11123
11124 if(typeof data === "string"){
11125 data = JSON.parse(data);
11126 }
11127
11128 if(!Array.isArray(row.data[this.field])){
11129 row.data[this.field] = [];
11130
11131 row.modules.dataTree.open = this.startOpen(row.getComponent(), row.modules.dataTree.index);
11132 }
11133
11134 if(typeof index !== "undefined"){
11135 childIndex = this.findChildIndex(index, row);
11136
11137 if(childIndex !== false){
11138 row.data[this.field].splice((top ? childIndex : childIndex + 1), 0, data);
11139 }
11140 }
11141
11142 if(childIndex === false){
11143 if(top){
11144 row.data[this.field].unshift(data);
11145 }else {
11146 row.data[this.field].push(data);
11147 }
11148 }
11149
11150 this.initializeRow(row);
11151 this.layoutRow(row);
11152
11153 this.refreshData(true);
11154 }
11155
11156 findChildIndex(subject, parent){
11157 var match = false;
11158
11159 if(typeof subject == "object"){
11160
11161 if(subject instanceof Row){
11162 //subject is row element
11163 match = subject.data;
11164 }else if(subject instanceof RowComponent){
11165 //subject is public row component
11166 match = subject._getSelf().data;
11167 }else if(typeof HTMLElement !== "undefined" && subject instanceof HTMLElement){
11168 if(parent.modules.dataTree){
11169 match = parent.modules.dataTree.children.find((childRow) => {
11170 return childRow instanceof Row ? childRow.element === subject : false;
11171 });
11172
11173 if(match){
11174 match = match.data;
11175 }
11176 }
11177 }else if(subject === null){
11178 match = false;
11179 }
11180
11181 }else if(typeof subject == "undefined"){
11182 match = false;
11183 }else {
11184 //subject should be treated as the index of the row
11185 match = parent.data[this.field].find((row) => {
11186 return row.data[this.table.options.index] == subject;
11187 });
11188 }
11189
11190 if(match){
11191
11192 if(Array.isArray(parent.data[this.field])){
11193 match = parent.data[this.field].indexOf(match);
11194 }
11195
11196 if(match == -1){
11197 match = false;
11198 }
11199 }
11200
11201 //catch all for any other type of input
11202
11203 return match;
11204 }
11205
11206 getTreeChildren(row, component, recurse){
11207 var config = row.modules.dataTree,
11208 output = [];
11209
11210 if(config && config.children){
11211
11212 if(!Array.isArray(config.children)){
11213 config.children = this.generateChildren(row);
11214 }
11215
11216 config.children.forEach((childRow) => {
11217 if(childRow instanceof Row){
11218 output.push(component ? childRow.getComponent() : childRow);
11219
11220 if(recurse){
11221 this.getTreeChildren(childRow, component, recurse).forEach(child => {
11222 output.push(child);
11223 });
11224 }
11225 }
11226 });
11227 }
11228
11229 return output;
11230 }
11231
11232 getChildField(){
11233 return this.field;
11234 }
11235
11236 redrawNeeded(data){
11237 return (this.field ? typeof data[this.field] !== "undefined" : false) || (this.elementField ? typeof data[this.elementField] !== "undefined" : false);
11238 }
11239 }
11240
11241 function csv$1(list, options = {}, setFileContents){
11242 var delimiter = options.delimiter ? options.delimiter : ",",
11243 fileContents = [],
11244 headers = [];
11245
11246 list.forEach((row) => {
11247 var item = [];
11248
11249 switch(row.type){
11250 case "group":
11251 console.warn("Download Warning - CSV downloader cannot process row groups");
11252 break;
11253
11254 case "calc":
11255 console.warn("Download Warning - CSV downloader cannot process column calculations");
11256 break;
11257
11258 case "header":
11259 row.columns.forEach((col, i) => {
11260 if(col && col.depth === 1){
11261 headers[i] = typeof col.value == "undefined" || col.value === null ? "" : ('"' + String(col.value).split('"').join('""') + '"');
11262 }
11263 });
11264 break;
11265
11266 case "row":
11267 row.columns.forEach((col) => {
11268
11269 if(col){
11270
11271 switch(typeof col.value){
11272 case "object":
11273 col.value = col.value !== null ? JSON.stringify(col.value) : "";
11274 break;
11275
11276 case "undefined":
11277 col.value = "";
11278 break;
11279 }
11280
11281 item.push('"' + String(col.value).split('"').join('""') + '"');
11282 }
11283 });
11284
11285 fileContents.push(item.join(delimiter));
11286 break;
11287 }
11288 });
11289
11290 if(headers.length){
11291 fileContents.unshift(headers.join(delimiter));
11292 }
11293
11294 fileContents = fileContents.join("\n");
11295
11296 if(options.bom){
11297 fileContents = "\ufeff" + fileContents;
11298 }
11299
11300 setFileContents(fileContents, "text/csv");
11301 }
11302
11303 function json$2(list, options, setFileContents){
11304 var fileContents = [];
11305
11306 list.forEach((row) => {
11307 var item = {};
11308
11309 switch(row.type){
11310 case "header":
11311 break;
11312
11313 case "group":
11314 console.warn("Download Warning - JSON downloader cannot process row groups");
11315 break;
11316
11317 case "calc":
11318 console.warn("Download Warning - JSON downloader cannot process column calculations");
11319 break;
11320
11321 case "row":
11322 row.columns.forEach((col) => {
11323 if(col){
11324 item[col.component.getTitleDownload() || col.component.getField()] = col.value;
11325 }
11326 });
11327
11328 fileContents.push(item);
11329 break;
11330 }
11331 });
11332
11333 fileContents = JSON.stringify(fileContents, null, '\t');
11334
11335 setFileContents(fileContents, "application/json");
11336 }
11337
11338 function pdf(list, options = {}, setFileContents){
11339 var header = [],
11340 body = [],
11341 autoTableParams = {},
11342 rowGroupStyles = options.rowGroupStyles || {
11343 fontStyle: "bold",
11344 fontSize: 12,
11345 cellPadding: 6,
11346 fillColor: 220,
11347 },
11348 rowCalcStyles = options.rowCalcStyles || {
11349 fontStyle: "bold",
11350 fontSize: 10,
11351 cellPadding: 4,
11352 fillColor: 232,
11353 },
11354 jsPDFParams = options.jsPDF || {},
11355 title = options.title ? options.title : "",
11356 jspdfLib, doc;
11357
11358 if(!jsPDFParams.orientation){
11359 jsPDFParams.orientation = options.orientation || "landscape";
11360 }
11361
11362 if(!jsPDFParams.unit){
11363 jsPDFParams.unit = "pt";
11364 }
11365
11366 //parse row list
11367 list.forEach((row) => {
11368 switch(row.type){
11369 case "header":
11370 header.push(parseRow(row));
11371 break;
11372
11373 case "group":
11374 body.push(parseRow(row, rowGroupStyles));
11375 break;
11376
11377 case "calc":
11378 body.push(parseRow(row, rowCalcStyles));
11379 break;
11380
11381 case "row":
11382 body.push(parseRow(row));
11383 break;
11384 }
11385 });
11386
11387 function parseRow(row, styles){
11388 var rowData = [];
11389
11390 row.columns.forEach((col) =>{
11391 var cell;
11392
11393 if(col){
11394 switch(typeof col.value){
11395 case "object":
11396 col.value = col.value !== null ? JSON.stringify(col.value) : "";
11397 break;
11398
11399 case "undefined":
11400 col.value = "";
11401 break;
11402 }
11403
11404 cell = {
11405 content:col.value,
11406 colSpan:col.width,
11407 rowSpan:col.height,
11408 };
11409
11410 if(styles){
11411 cell.styles = styles;
11412 }
11413
11414 rowData.push(cell);
11415 }
11416 });
11417
11418 return rowData;
11419 }
11420
11421
11422 //configure PDF
11423 jspdfLib = this.dependencyRegistry.lookup("jspdf", "jsPDF");
11424 doc = new jspdfLib(jsPDFParams); //set document to landscape, better for most tables
11425
11426 if(options.autoTable){
11427 if(typeof options.autoTable === "function"){
11428 autoTableParams = options.autoTable(doc) || {};
11429 }else {
11430 autoTableParams = options.autoTable;
11431 }
11432 }
11433
11434 if(title){
11435 autoTableParams.didDrawPage = function(data) {
11436 doc.text(title, 40, 30);
11437 };
11438 }
11439
11440 autoTableParams.head = header;
11441 autoTableParams.body = body;
11442
11443 doc.autoTable(autoTableParams);
11444
11445 if(options.documentProcessing){
11446 options.documentProcessing(doc);
11447 }
11448
11449 setFileContents(doc.output("arraybuffer"), "application/pdf");
11450 }
11451
11452 function xlsx$1(list, options, setFileContents){
11453 var self = this,
11454 sheetName = options.sheetName || "Sheet1",
11455 XLSXLib = this.dependencyRegistry.lookup("XLSX"),
11456 workbook = XLSXLib.utils.book_new(),
11457 tableFeatures = new CoreFeature(this),
11458 compression = 'compress' in options ? options.compress : true,
11459 writeOptions = options.writeOptions || {bookType:'xlsx', bookSST:true, compression},
11460 output;
11461
11462 writeOptions.type = 'binary';
11463
11464 workbook.SheetNames = [];
11465 workbook.Sheets = {};
11466
11467 function generateSheet(){
11468 var rows = [],
11469 merges = [],
11470 worksheet = {},
11471 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 }};
11472
11473 //parse row list
11474 list.forEach((row, i) => {
11475 var rowData = [];
11476
11477 row.columns.forEach(function(col, j){
11478
11479 if(col){
11480 rowData.push(!(col.value instanceof Date) && typeof col.value === "object" ? JSON.stringify(col.value) : col.value);
11481
11482 if(col.width > 1 || col.height > -1){
11483 if(col.height > 1 || col.width > 1){
11484 merges.push({s:{r:i,c:j},e:{r:i + col.height - 1,c:j + col.width - 1}});
11485 }
11486 }
11487 }else {
11488 rowData.push("");
11489 }
11490 });
11491
11492 rows.push(rowData);
11493 });
11494
11495 //convert rows to worksheet
11496 XLSXLib.utils.sheet_add_aoa(worksheet, rows);
11497
11498 worksheet['!ref'] = XLSXLib.utils.encode_range(range);
11499
11500 if(merges.length){
11501 worksheet["!merges"] = merges;
11502 }
11503
11504 return worksheet;
11505 }
11506
11507 if(options.sheetOnly){
11508 setFileContents(generateSheet());
11509 return;
11510 }
11511
11512 if(options.sheets){
11513 for(var sheet in options.sheets){
11514
11515 if(options.sheets[sheet] === true){
11516 workbook.SheetNames.push(sheet);
11517 workbook.Sheets[sheet] = generateSheet();
11518 }else {
11519
11520 workbook.SheetNames.push(sheet);
11521
11522 tableFeatures.commsSend(options.sheets[sheet], "download", "intercept",{
11523 type:"xlsx",
11524 options:{sheetOnly:true},
11525 active:self.active,
11526 intercept:function(data){
11527 workbook.Sheets[sheet] = data;
11528 }
11529 });
11530 }
11531 }
11532 }else {
11533 workbook.SheetNames.push(sheetName);
11534 workbook.Sheets[sheetName] = generateSheet();
11535 }
11536
11537 if(options.documentProcessing){
11538 workbook = options.documentProcessing(workbook);
11539 }
11540
11541 //convert workbook to binary array
11542 function s2ab(s) {
11543 var buf = new ArrayBuffer(s.length);
11544 var view = new Uint8Array(buf);
11545 for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
11546 return buf;
11547 }
11548
11549 output = XLSXLib.write(workbook, writeOptions);
11550
11551 setFileContents(s2ab(output), "application/octet-stream");
11552 }
11553
11554 function html$1(list, options, setFileContents){
11555 if(this.modExists("export", true)){
11556 setFileContents(this.modules.export.generateHTMLTable(list), "text/html");
11557 }
11558 }
11559
11560 function jsonLines (list, options, setFileContents) {
11561 const fileContents = [];
11562
11563 list.forEach((row) => {
11564 const item = {};
11565
11566 switch (row.type) {
11567 case "header":
11568 break;
11569
11570 case "group":
11571 console.warn("Download Warning - JSON downloader cannot process row groups");
11572 break;
11573
11574 case "calc":
11575 console.warn("Download Warning - JSON downloader cannot process column calculations");
11576 break;
11577
11578 case "row":
11579 row.columns.forEach((col) => {
11580 if (col) {
11581 item[col.component.getTitleDownload() || col.component.getField()] = col.value;
11582 }
11583 });
11584
11585 fileContents.push(JSON.stringify(item));
11586 break;
11587 }
11588 });
11589
11590 setFileContents(fileContents.join("\n"), "application/x-ndjson");
11591 }
11592
11593 var defaultDownloaders = {
11594 csv:csv$1,
11595 json:json$2,
11596 jsonLines:jsonLines,
11597 pdf:pdf,
11598 xlsx:xlsx$1,
11599 html:html$1,
11600 };
11601
11602 class Download extends Module{
11603
11604 static moduleName = "download";
11605
11606 //load defaults
11607 static downloaders = defaultDownloaders;
11608
11609 constructor(table){
11610 super(table);
11611
11612 this.registerTableOption("downloadEncoder", function(data, mimeType){
11613 return new Blob([data],{type:mimeType});
11614 }); //function to manipulate download data
11615 this.registerTableOption("downloadConfig", {}); //download config
11616 this.registerTableOption("downloadRowRange", "active"); //restrict download to active rows only
11617
11618 this.registerColumnOption("download");
11619 this.registerColumnOption("titleDownload");
11620 }
11621
11622 initialize(){
11623 this.deprecatedOptionsCheck();
11624
11625 this.registerTableFunction("download", this.download.bind(this));
11626 this.registerTableFunction("downloadToTab", this.downloadToTab.bind(this));
11627 }
11628
11629 deprecatedOptionsCheck(){
11630
11631 }
11632
11633 ///////////////////////////////////
11634 ///////// Table Functions /////////
11635 ///////////////////////////////////
11636
11637 downloadToTab(type, filename, options, active){
11638 this.download(type, filename, options, active, true);
11639 }
11640
11641 ///////////////////////////////////
11642 ///////// Internal Logic //////////
11643 ///////////////////////////////////
11644
11645 //trigger file download
11646 download(type, filename, options, range, interceptCallback){
11647 var downloadFunc = false;
11648
11649 function buildLink(data, mime){
11650 if(interceptCallback){
11651 if(interceptCallback === true){
11652 this.triggerDownload(data, mime, type, filename, true);
11653 }else {
11654 interceptCallback(data);
11655 }
11656
11657 }else {
11658 this.triggerDownload(data, mime, type, filename);
11659 }
11660 }
11661
11662 if(typeof type == "function"){
11663 downloadFunc = type;
11664 }else {
11665 if(Download.downloaders[type]){
11666 downloadFunc = Download.downloaders[type];
11667 }else {
11668 console.warn("Download Error - No such download type found: ", type);
11669 }
11670 }
11671
11672 if(downloadFunc){
11673 var list = this.generateExportList(range);
11674
11675 downloadFunc.call(this.table, list , options || {}, buildLink.bind(this));
11676 }
11677 }
11678
11679 generateExportList(range){
11680 var list = this.table.modules.export.generateExportList(this.table.options.downloadConfig, false, range || this.table.options.downloadRowRange, "download");
11681
11682 //assign group header formatter
11683 var groupHeader = this.table.options.groupHeaderDownload;
11684
11685 if(groupHeader && !Array.isArray(groupHeader)){
11686 groupHeader = [groupHeader];
11687 }
11688
11689 list.forEach((row) => {
11690 var group;
11691
11692 if(row.type === "group"){
11693 group = row.columns[0];
11694
11695 if(groupHeader && groupHeader[row.indent]){
11696 group.value = groupHeader[row.indent](group.value, row.component._group.getRowCount(), row.component._group.getData(), row.component);
11697 }
11698 }
11699 });
11700
11701 return list;
11702 }
11703
11704 triggerDownload(data, mime, type, filename, newTab){
11705 var element = document.createElement('a'),
11706 blob = this.table.options.downloadEncoder(data, mime);
11707
11708 if(blob){
11709 if(newTab){
11710 window.open(window.URL.createObjectURL(blob));
11711 }else {
11712 filename = filename || "Tabulator." + (typeof type === "function" ? "txt" : type);
11713
11714 if(navigator.msSaveOrOpenBlob){
11715 navigator.msSaveOrOpenBlob(blob, filename);
11716 }else {
11717 element.setAttribute('href', window.URL.createObjectURL(blob));
11718
11719 //set file title
11720 element.setAttribute('download', filename);
11721
11722 //trigger download
11723 element.style.display = 'none';
11724 document.body.appendChild(element);
11725 element.click();
11726
11727 //remove temporary link element
11728 document.body.removeChild(element);
11729 }
11730 }
11731
11732 this.dispatchExternal("downloadComplete");
11733 }
11734 }
11735
11736 commsReceived(table, action, data){
11737 switch(action){
11738 case "intercept":
11739 this.download(data.type, "", data.options, data.active, data.intercept);
11740 break;
11741 }
11742 }
11743 }
11744
11745 function maskInput(el, options){
11746 var mask = options.mask,
11747 maskLetter = typeof options.maskLetterChar !== "undefined" ? options.maskLetterChar : "A",
11748 maskNumber = typeof options.maskNumberChar !== "undefined" ? options.maskNumberChar : "9",
11749 maskWildcard = typeof options.maskWildcardChar !== "undefined" ? options.maskWildcardChar : "*";
11750
11751 function fillSymbols(index){
11752 var symbol = mask[index];
11753 if(typeof symbol !== "undefined" && symbol !== maskWildcard && symbol !== maskLetter && symbol !== maskNumber){
11754 el.value = el.value + "" + symbol;
11755 fillSymbols(index+1);
11756 }
11757 }
11758
11759 el.addEventListener("keydown", (e) => {
11760 var index = el.value.length,
11761 char = e.key;
11762
11763 if(e.key.length === 1 && !e.ctrlKey && !e.metaKey){
11764 if(index >= mask.length){
11765 e.preventDefault();
11766 e.stopPropagation();
11767 return false;
11768 }else {
11769 switch(mask[index]){
11770 case maskLetter:
11771 if(char.toUpperCase() == char.toLowerCase()){
11772 e.preventDefault();
11773 e.stopPropagation();
11774 return false;
11775 }
11776 break;
11777
11778 case maskNumber:
11779 if(isNaN(char)){
11780 e.preventDefault();
11781 e.stopPropagation();
11782 return false;
11783 }
11784 break;
11785
11786 case maskWildcard:
11787 break;
11788
11789 default:
11790 if(char !== mask[index]){
11791 e.preventDefault();
11792 e.stopPropagation();
11793 return false;
11794 }
11795 }
11796 }
11797 }
11798
11799 return;
11800 });
11801
11802 el.addEventListener("keyup", (e) => {
11803 if(e.key.length === 1){
11804 if(options.maskAutoFill){
11805 fillSymbols(el.value.length);
11806 }
11807 }
11808 });
11809
11810
11811 if(!el.placeholder){
11812 el.placeholder = mask;
11813 }
11814
11815 if(options.maskAutoFill){
11816 fillSymbols(el.value.length);
11817 }
11818 }
11819
11820 //input element
11821 function input(cell, onRendered, success, cancel, editorParams){
11822 //create and style input
11823 var cellValue = cell.getValue(),
11824 input = document.createElement("input");
11825
11826 input.setAttribute("type", editorParams.search ? "search" : "text");
11827
11828 input.style.padding = "4px";
11829 input.style.width = "100%";
11830 input.style.boxSizing = "border-box";
11831
11832 if(editorParams.elementAttributes && typeof editorParams.elementAttributes == "object"){
11833 for (let key in editorParams.elementAttributes){
11834 if(key.charAt(0) == "+"){
11835 key = key.slice(1);
11836 input.setAttribute(key, input.getAttribute(key) + editorParams.elementAttributes["+" + key]);
11837 }else {
11838 input.setAttribute(key, editorParams.elementAttributes[key]);
11839 }
11840 }
11841 }
11842
11843 input.value = typeof cellValue !== "undefined" ? cellValue : "";
11844
11845 onRendered(function(){
11846 if(cell.getType() === "cell"){
11847 input.focus({preventScroll: true});
11848 input.style.height = "100%";
11849
11850 if(editorParams.selectContents){
11851 input.select();
11852 }
11853 }
11854 });
11855
11856 function onChange(e){
11857 if(((cellValue === null || typeof cellValue === "undefined") && input.value !== "") || input.value !== cellValue){
11858 if(success(input.value)){
11859 cellValue = input.value; //persist value if successfully validated incase editor is used as header filter
11860 }
11861 }else {
11862 cancel();
11863 }
11864 }
11865
11866 //submit new value on blur or change
11867 input.addEventListener("change", onChange);
11868 input.addEventListener("blur", onChange);
11869
11870 //submit new value on enter
11871 input.addEventListener("keydown", function(e){
11872 switch(e.key){
11873 // case "Tab":
11874 case "Enter":
11875 onChange();
11876 break;
11877
11878 case "Escape":
11879 cancel();
11880 break;
11881
11882 case "End":
11883 case "Home":
11884 e.stopPropagation();
11885 break;
11886 }
11887 });
11888
11889 if(editorParams.mask){
11890 maskInput(input, editorParams);
11891 }
11892
11893 return input;
11894 }
11895
11896 //resizable text area element
11897 function textarea$1(cell, onRendered, success, cancel, editorParams){
11898 var cellValue = cell.getValue(),
11899 vertNav = editorParams.verticalNavigation || "hybrid",
11900 value = String(cellValue !== null && typeof cellValue !== "undefined" ? cellValue : ""),
11901 input = document.createElement("textarea"),
11902 scrollHeight = 0;
11903
11904 //create and style input
11905 input.style.display = "block";
11906 input.style.padding = "2px";
11907 input.style.height = "100%";
11908 input.style.width = "100%";
11909 input.style.boxSizing = "border-box";
11910 input.style.whiteSpace = "pre-wrap";
11911 input.style.resize = "none";
11912
11913 if(editorParams.elementAttributes && typeof editorParams.elementAttributes == "object"){
11914 for (let key in editorParams.elementAttributes){
11915 if(key.charAt(0) == "+"){
11916 key = key.slice(1);
11917 input.setAttribute(key, input.getAttribute(key) + editorParams.elementAttributes["+" + key]);
11918 }else {
11919 input.setAttribute(key, editorParams.elementAttributes[key]);
11920 }
11921 }
11922 }
11923
11924 input.value = value;
11925
11926 onRendered(function(){
11927 if(cell.getType() === "cell"){
11928 input.focus({preventScroll: true});
11929 input.style.height = "100%";
11930
11931 input.scrollHeight;
11932 input.style.height = input.scrollHeight + "px";
11933 cell.getRow().normalizeHeight();
11934
11935 if(editorParams.selectContents){
11936 input.select();
11937 }
11938 }
11939 });
11940
11941 function onChange(e){
11942
11943 if(((cellValue === null || typeof cellValue === "undefined") && input.value !== "") || input.value !== cellValue){
11944
11945 if(success(input.value)){
11946 cellValue = input.value; //persist value if successfully validated incase editor is used as header filter
11947 }
11948
11949 setTimeout(function(){
11950 cell.getRow().normalizeHeight();
11951 },300);
11952 }else {
11953 cancel();
11954 }
11955 }
11956
11957 //submit new value on blur or change
11958 input.addEventListener("change", onChange);
11959 input.addEventListener("blur", onChange);
11960
11961 input.addEventListener("keyup", function(){
11962
11963 input.style.height = "";
11964
11965 var heightNow = input.scrollHeight;
11966
11967 input.style.height = heightNow + "px";
11968
11969 if(heightNow != scrollHeight){
11970 scrollHeight = heightNow;
11971 cell.getRow().normalizeHeight();
11972 }
11973 });
11974
11975 input.addEventListener("keydown", function(e){
11976
11977 switch(e.key){
11978
11979 case "Enter":
11980 if(e.shiftKey && editorParams.shiftEnterSubmit){
11981 onChange();
11982 }
11983 break;
11984
11985 case "Escape":
11986 cancel();
11987 break;
11988
11989 case "ArrowUp":
11990 if(vertNav == "editor" || (vertNav == "hybrid" && input.selectionStart)){
11991 e.stopImmediatePropagation();
11992 e.stopPropagation();
11993 }
11994
11995 break;
11996
11997 case "ArrowDown":
11998 if(vertNav == "editor" || (vertNav == "hybrid" && input.selectionStart !== input.value.length)){
11999 e.stopImmediatePropagation();
12000 e.stopPropagation();
12001 }
12002 break;
12003
12004 case "End":
12005 case "Home":
12006 e.stopPropagation();
12007 break;
12008 }
12009 });
12010
12011 if(editorParams.mask){
12012 maskInput(input, editorParams);
12013 }
12014
12015 return input;
12016 }
12017
12018 //input element with type of number
12019 function number$1(cell, onRendered, success, cancel, editorParams){
12020 var cellValue = cell.getValue(),
12021 vertNav = editorParams.verticalNavigation || "editor",
12022 input = document.createElement("input");
12023
12024 input.setAttribute("type", "number");
12025
12026 if(typeof editorParams.max != "undefined"){
12027 input.setAttribute("max", editorParams.max);
12028 }
12029
12030 if(typeof editorParams.min != "undefined"){
12031 input.setAttribute("min", editorParams.min);
12032 }
12033
12034 if(typeof editorParams.step != "undefined"){
12035 input.setAttribute("step", editorParams.step);
12036 }
12037
12038 //create and style input
12039 input.style.padding = "4px";
12040 input.style.width = "100%";
12041 input.style.boxSizing = "border-box";
12042
12043 if(editorParams.elementAttributes && typeof editorParams.elementAttributes == "object"){
12044 for (let key in editorParams.elementAttributes){
12045 if(key.charAt(0) == "+"){
12046 key = key.slice(1);
12047 input.setAttribute(key, input.getAttribute(key) + editorParams.elementAttributes["+" + key]);
12048 }else {
12049 input.setAttribute(key, editorParams.elementAttributes[key]);
12050 }
12051 }
12052 }
12053
12054 input.value = cellValue;
12055
12056 var blurFunc = function(e){
12057 onChange();
12058 };
12059
12060 onRendered(function () {
12061 if(cell.getType() === "cell"){
12062 //submit new value on blur
12063 input.removeEventListener("blur", blurFunc);
12064
12065 input.focus({preventScroll: true});
12066 input.style.height = "100%";
12067
12068 //submit new value on blur
12069 input.addEventListener("blur", blurFunc);
12070
12071 if(editorParams.selectContents){
12072 input.select();
12073 }
12074 }
12075 });
12076
12077 function onChange(){
12078 var value = input.value;
12079
12080 if(!isNaN(value) && value !==""){
12081 value = Number(value);
12082 }
12083
12084 if(value !== cellValue){
12085 if(success(value)){
12086 cellValue = value; //persist value if successfully validated incase editor is used as header filter
12087 }
12088 }else {
12089 cancel();
12090 }
12091 }
12092
12093 //submit new value on enter
12094 input.addEventListener("keydown", function(e){
12095 switch(e.key){
12096 case "Enter":
12097 // case "Tab":
12098 onChange();
12099 break;
12100
12101 case "Escape":
12102 cancel();
12103 break;
12104
12105 case "ArrowUp":
12106 case "ArrowDown":
12107 if(vertNav == "editor"){
12108 e.stopImmediatePropagation();
12109 e.stopPropagation();
12110 }
12111 break;
12112
12113 case "End":
12114 case "Home":
12115 e.stopPropagation();
12116 break;
12117 }
12118 });
12119
12120 if(editorParams.mask){
12121 maskInput(input, editorParams);
12122 }
12123
12124 return input;
12125 }
12126
12127 //input element with type of number
12128 function range(cell, onRendered, success, cancel, editorParams){
12129 var cellValue = cell.getValue(),
12130 input = document.createElement("input");
12131
12132 input.setAttribute("type", "range");
12133
12134 if (typeof editorParams.max != "undefined") {
12135 input.setAttribute("max", editorParams.max);
12136 }
12137
12138 if (typeof editorParams.min != "undefined") {
12139 input.setAttribute("min", editorParams.min);
12140 }
12141
12142 if (typeof editorParams.step != "undefined") {
12143 input.setAttribute("step", editorParams.step);
12144 }
12145
12146 //create and style input
12147 input.style.padding = "4px";
12148 input.style.width = "100%";
12149 input.style.boxSizing = "border-box";
12150
12151 if(editorParams.elementAttributes && typeof editorParams.elementAttributes == "object"){
12152 for (let key in editorParams.elementAttributes){
12153 if(key.charAt(0) == "+"){
12154 key = key.slice(1);
12155 input.setAttribute(key, input.getAttribute(key) + editorParams.elementAttributes["+" + key]);
12156 }else {
12157 input.setAttribute(key, editorParams.elementAttributes[key]);
12158 }
12159 }
12160 }
12161
12162 input.value = cellValue;
12163
12164 onRendered(function () {
12165 if(cell.getType() === "cell"){
12166 input.focus({preventScroll: true});
12167 input.style.height = "100%";
12168 }
12169 });
12170
12171 function onChange(){
12172 var value = input.value;
12173
12174 if(!isNaN(value) && value !==""){
12175 value = Number(value);
12176 }
12177
12178 if(value != cellValue){
12179 if(success(value)){
12180 cellValue = value; //persist value if successfully validated incase editor is used as header filter
12181 }
12182 }else {
12183 cancel();
12184 }
12185 }
12186
12187 //submit new value on blur
12188 input.addEventListener("blur", function(e){
12189 onChange();
12190 });
12191
12192 //submit new value on enter
12193 input.addEventListener("keydown", function(e){
12194 switch(e.key){
12195 case "Enter":
12196 // case "Tab":
12197 onChange();
12198 break;
12199
12200 case "Escape":
12201 cancel();
12202 break;
12203 }
12204 });
12205
12206 return input;
12207 }
12208
12209 //input element
12210 function date$1(cell, onRendered, success, cancel, editorParams){
12211 var inputFormat = editorParams.format,
12212 vertNav = editorParams.verticalNavigation || "editor",
12213 DT = inputFormat ? (window.DateTime || luxon.DateTime) : null;
12214
12215 //create and style input
12216 var cellValue = cell.getValue(),
12217 input = document.createElement("input");
12218
12219 function convertDate(value){
12220 var newDatetime;
12221
12222 if(DT.isDateTime(value)){
12223 newDatetime = value;
12224 }else if(inputFormat === "iso"){
12225 newDatetime = DT.fromISO(String(value));
12226 }else {
12227 newDatetime = DT.fromFormat(String(value), inputFormat);
12228 }
12229
12230 return newDatetime.toFormat("yyyy-MM-dd");
12231 }
12232
12233 input.type = "date";
12234 input.style.padding = "4px";
12235 input.style.width = "100%";
12236 input.style.boxSizing = "border-box";
12237
12238 if(editorParams.max){
12239 input.setAttribute("max", inputFormat ? convertDate(editorParams.max) : editorParams.max);
12240 }
12241
12242 if(editorParams.min){
12243 input.setAttribute("min", inputFormat ? convertDate(editorParams.min) : editorParams.min);
12244 }
12245
12246 if(editorParams.elementAttributes && typeof editorParams.elementAttributes == "object"){
12247 for (let key in editorParams.elementAttributes){
12248 if(key.charAt(0) == "+"){
12249 key = key.slice(1);
12250 input.setAttribute(key, input.getAttribute(key) + editorParams.elementAttributes["+" + key]);
12251 }else {
12252 input.setAttribute(key, editorParams.elementAttributes[key]);
12253 }
12254 }
12255 }
12256
12257 cellValue = typeof cellValue !== "undefined" ? cellValue : "";
12258
12259 if(inputFormat){
12260 if(DT){
12261 cellValue = convertDate(cellValue);
12262 }else {
12263 console.error("Editor Error - 'date' editor 'format' param is dependant on luxon.js");
12264 }
12265 }
12266
12267 input.value = cellValue;
12268
12269 onRendered(function(){
12270 if(cell.getType() === "cell"){
12271 input.focus({preventScroll: true});
12272 input.style.height = "100%";
12273
12274 if(editorParams.selectContents){
12275 input.select();
12276 }
12277 }
12278 });
12279
12280 function onChange(){
12281 var value = input.value,
12282 luxDate;
12283
12284 if(((cellValue === null || typeof cellValue === "undefined") && value !== "") || value !== cellValue){
12285
12286 if(value && inputFormat){
12287 luxDate = DT.fromFormat(String(value), "yyyy-MM-dd");
12288
12289 switch(inputFormat){
12290 case true:
12291 value = luxDate;
12292 break;
12293
12294 case "iso":
12295 value = luxDate.toISO();
12296 break;
12297
12298 default:
12299 value = luxDate.toFormat(inputFormat);
12300 }
12301 }
12302
12303 if(success(value)){
12304 cellValue = input.value; //persist value if successfully validated incase editor is used as header filter
12305 }
12306 }else {
12307 cancel();
12308 }
12309 }
12310
12311 //submit new value on blur
12312 input.addEventListener("blur", function(e) {
12313 if (e.relatedTarget || e.rangeParent || e.explicitOriginalTarget !== input) {
12314 onChange(); // only on a "true" blur; not when focusing browser's date/time picker
12315 }
12316 });
12317
12318 //submit new value on enter
12319 input.addEventListener("keydown", function(e){
12320 switch(e.key){
12321 // case "Tab":
12322 case "Enter":
12323 onChange();
12324 break;
12325
12326 case "Escape":
12327 cancel();
12328 break;
12329
12330 case "End":
12331 case "Home":
12332 e.stopPropagation();
12333 break;
12334
12335 case "ArrowUp":
12336 case "ArrowDown":
12337 if(vertNav == "editor"){
12338 e.stopImmediatePropagation();
12339 e.stopPropagation();
12340 }
12341 break;
12342 }
12343 });
12344
12345 return input;
12346 }
12347
12348 //input element
12349 function time$1(cell, onRendered, success, cancel, editorParams){
12350 var inputFormat = editorParams.format,
12351 vertNav = editorParams.verticalNavigation || "editor",
12352 DT = inputFormat ? (window.DateTime || luxon.DateTime) : null,
12353 newDatetime;
12354
12355 //create and style input
12356 var cellValue = cell.getValue(),
12357 input = document.createElement("input");
12358
12359 input.type = "time";
12360 input.style.padding = "4px";
12361 input.style.width = "100%";
12362 input.style.boxSizing = "border-box";
12363
12364 if(editorParams.elementAttributes && typeof editorParams.elementAttributes == "object"){
12365 for (let key in editorParams.elementAttributes){
12366 if(key.charAt(0) == "+"){
12367 key = key.slice(1);
12368 input.setAttribute(key, input.getAttribute(key) + editorParams.elementAttributes["+" + key]);
12369 }else {
12370 input.setAttribute(key, editorParams.elementAttributes[key]);
12371 }
12372 }
12373 }
12374
12375 cellValue = typeof cellValue !== "undefined" ? cellValue : "";
12376
12377 if(inputFormat){
12378 if(DT){
12379 if(DT.isDateTime(cellValue)){
12380 newDatetime = cellValue;
12381 }else if(inputFormat === "iso"){
12382 newDatetime = DT.fromISO(String(cellValue));
12383 }else {
12384 newDatetime = DT.fromFormat(String(cellValue), inputFormat);
12385 }
12386
12387 cellValue = newDatetime.toFormat("HH:mm");
12388
12389 }else {
12390 console.error("Editor Error - 'date' editor 'format' param is dependant on luxon.js");
12391 }
12392 }
12393
12394 input.value = cellValue;
12395
12396 onRendered(function(){
12397 if(cell.getType() == "cell"){
12398 input.focus({preventScroll: true});
12399 input.style.height = "100%";
12400
12401 if(editorParams.selectContents){
12402 input.select();
12403 }
12404 }
12405 });
12406
12407 function onChange(){
12408 var value = input.value,
12409 luxTime;
12410
12411 if(((cellValue === null || typeof cellValue === "undefined") && value !== "") || value !== cellValue){
12412
12413 if(value && inputFormat){
12414 luxTime = DT.fromFormat(String(value), "hh:mm");
12415
12416 switch(inputFormat){
12417 case true:
12418 value = luxTime;
12419 break;
12420
12421 case "iso":
12422 value = luxTime.toISO();
12423 break;
12424
12425 default:
12426 value = luxTime.toFormat(inputFormat);
12427 }
12428 }
12429
12430 if(success(value)){
12431 cellValue = input.value; //persist value if successfully validated incase editor is used as header filter
12432 }
12433 }else {
12434 cancel();
12435 }
12436 }
12437
12438 //submit new value on blur
12439 input.addEventListener("blur", function(e) {
12440 if (e.relatedTarget || e.rangeParent || e.explicitOriginalTarget !== input) {
12441 onChange(); // only on a "true" blur; not when focusing browser's date/time picker
12442 }
12443 });
12444
12445 //submit new value on enter
12446 input.addEventListener("keydown", function(e){
12447 switch(e.key){
12448 // case "Tab":
12449 case "Enter":
12450 onChange();
12451 break;
12452
12453 case "Escape":
12454 cancel();
12455 break;
12456
12457 case "End":
12458 case "Home":
12459 e.stopPropagation();
12460 break;
12461
12462 case "ArrowUp":
12463 case "ArrowDown":
12464 if(vertNav == "editor"){
12465 e.stopImmediatePropagation();
12466 e.stopPropagation();
12467 }
12468 break;
12469 }
12470 });
12471
12472 return input;
12473 }
12474
12475 //input element
12476 function datetime$2(cell, onRendered, success, cancel, editorParams){
12477 var inputFormat = editorParams.format,
12478 vertNav = editorParams.verticalNavigation || "editor",
12479 DT = inputFormat ? (this.table.dependencyRegistry.lookup(["luxon", "DateTime"], "DateTime")) : null,
12480 newDatetime;
12481
12482 //create and style input
12483 var cellValue = cell.getValue(),
12484 input = document.createElement("input");
12485
12486 input.type = "datetime-local";
12487 input.style.padding = "4px";
12488 input.style.width = "100%";
12489 input.style.boxSizing = "border-box";
12490
12491 if(editorParams.elementAttributes && typeof editorParams.elementAttributes == "object"){
12492 for (let key in editorParams.elementAttributes){
12493 if(key.charAt(0) == "+"){
12494 key = key.slice(1);
12495 input.setAttribute(key, input.getAttribute(key) + editorParams.elementAttributes["+" + key]);
12496 }else {
12497 input.setAttribute(key, editorParams.elementAttributes[key]);
12498 }
12499 }
12500 }
12501
12502 cellValue = typeof cellValue !== "undefined" ? cellValue : "";
12503
12504 if(inputFormat){
12505 if(DT){
12506 if(DT.isDateTime(cellValue)){
12507 newDatetime = cellValue;
12508 }else if(inputFormat === "iso"){
12509 newDatetime = DT.fromISO(String(cellValue));
12510 }else {
12511 newDatetime = DT.fromFormat(String(cellValue), inputFormat);
12512 }
12513
12514 cellValue = newDatetime.toFormat("yyyy-MM-dd") + "T" + newDatetime.toFormat("HH:mm");
12515 }else {
12516 console.error("Editor Error - 'date' editor 'format' param is dependant on luxon.js");
12517 }
12518 }
12519
12520 input.value = cellValue;
12521
12522 onRendered(function(){
12523 if(cell.getType() === "cell"){
12524 input.focus({preventScroll: true});
12525 input.style.height = "100%";
12526
12527 if(editorParams.selectContents){
12528 input.select();
12529 }
12530 }
12531 });
12532
12533 function onChange(){
12534 var value = input.value,
12535 luxDateTime;
12536
12537 if(((cellValue === null || typeof cellValue === "undefined") && value !== "") || value !== cellValue){
12538
12539 if(value && inputFormat){
12540 luxDateTime = DT.fromISO(String(value));
12541
12542 switch(inputFormat){
12543 case true:
12544 value = luxDateTime;
12545 break;
12546
12547 case "iso":
12548 value = luxDateTime.toISO();
12549 break;
12550
12551 default:
12552 value = luxDateTime.toFormat(inputFormat);
12553 }
12554 }
12555
12556 if(success(value)){
12557 cellValue = input.value; //persist value if successfully validated incase editor is used as header filter
12558 }
12559 }else {
12560 cancel();
12561 }
12562 }
12563
12564 //submit new value on blur
12565 input.addEventListener("blur", function(e) {
12566 if (e.relatedTarget || e.rangeParent || e.explicitOriginalTarget !== input) {
12567 onChange(); // only on a "true" blur; not when focusing browser's date/time picker
12568 }
12569 });
12570
12571 //submit new value on enter
12572 input.addEventListener("keydown", function(e){
12573 switch(e.key){
12574 // case "Tab":
12575 case "Enter":
12576 onChange();
12577 break;
12578
12579 case "Escape":
12580 cancel();
12581 break;
12582
12583 case "End":
12584 case "Home":
12585 e.stopPropagation();
12586 break;
12587
12588 case "ArrowUp":
12589 case "ArrowDown":
12590 if(vertNav == "editor"){
12591 e.stopImmediatePropagation();
12592 e.stopPropagation();
12593 }
12594 break;
12595 }
12596 });
12597
12598 return input;
12599 }
12600
12601 let Edit$1 = class Edit{
12602 constructor(editor, cell, onRendered, success, cancel, editorParams){
12603 this.edit = editor;
12604 this.table = editor.table;
12605 this.cell = cell;
12606 this.params = this._initializeParams(editorParams);
12607
12608 this.data = [];
12609 this.displayItems = [];
12610 this.currentItems = [];
12611 this.focusedItem = null;
12612
12613 this.input = this._createInputElement();
12614 this.listEl = this._createListElement();
12615
12616 this.initialValues = null;
12617
12618 this.isFilter = cell.getType() === "header";
12619
12620 this.filterTimeout = null;
12621 this.filtered = false;
12622 this.typing = false;
12623
12624 this.values = [];
12625 this.popup = null;
12626
12627 this.listIteration = 0;
12628
12629 this.lastAction="";
12630 this.filterTerm="";
12631
12632 this.blurable = true;
12633
12634 this.actions = {
12635 success:success,
12636 cancel:cancel
12637 };
12638
12639 this._deprecatedOptionsCheck();
12640 this._initializeValue();
12641
12642 onRendered(this._onRendered.bind(this));
12643 }
12644
12645 _deprecatedOptionsCheck(){
12646 // if(this.params.listItemFormatter){
12647 // this.cell.getTable().deprecationAdvisor.msg("The listItemFormatter editor param has been deprecated, please see the latest editor documentation for updated options");
12648 // }
12649
12650 // if(this.params.sortValuesList){
12651 // this.cell.getTable().deprecationAdvisor.msg("The sortValuesList editor param has been deprecated, please see the latest editor documentation for updated options");
12652 // }
12653
12654 // if(this.params.searchFunc){
12655 // this.cell.getTable().deprecationAdvisor.msg("The searchFunc editor param has been deprecated, please see the latest editor documentation for updated options");
12656 // }
12657
12658 // if(this.params.searchingPlaceholder){
12659 // this.cell.getTable().deprecationAdvisor.msg("The searchingPlaceholder editor param has been deprecated, please see the latest editor documentation for updated options");
12660 // }
12661 }
12662
12663 _initializeValue(){
12664 var initialValue = this.cell.getValue();
12665
12666 if(typeof initialValue === "undefined" && typeof this.params.defaultValue !== "undefined"){
12667 initialValue = this.params.defaultValue;
12668 }
12669
12670 this.initialValues = this.params.multiselect ? initialValue : [initialValue];
12671
12672 if(this.isFilter){
12673 this.input.value = this.initialValues ? this.initialValues.join(",") : "";
12674 this.headerFilterInitialListGen();
12675 }
12676 }
12677
12678 _onRendered(){
12679 var cellEl = this.cell.getElement();
12680
12681 function clickStop(e){
12682 e.stopPropagation();
12683 }
12684
12685 if(!this.isFilter){
12686 this.input.style.height = "100%";
12687 this.input.focus({preventScroll: true});
12688 }
12689
12690
12691 cellEl.addEventListener("click", clickStop);
12692
12693 setTimeout(() => {
12694 cellEl.removeEventListener("click", clickStop);
12695 }, 1000);
12696
12697 this.input.addEventListener("mousedown", this._preventPopupBlur.bind(this));
12698 }
12699
12700 _createListElement(){
12701 var listEl = document.createElement("div");
12702 listEl.classList.add("tabulator-edit-list");
12703
12704 listEl.addEventListener("mousedown", this._preventBlur.bind(this));
12705 listEl.addEventListener("keydown", this._inputKeyDown.bind(this));
12706
12707 return listEl;
12708 }
12709
12710 _setListWidth(){
12711 var element = this.isFilter ? this.input : this.cell.getElement();
12712
12713 this.listEl.style.minWidth = element.offsetWidth + "px";
12714
12715 if(this.params.maxWidth){
12716 if(this.params.maxWidth === true){
12717 this.listEl.style.maxWidth = element.offsetWidth + "px";
12718 }else if(typeof this.params.maxWidth === "number"){
12719 this.listEl.style.maxWidth = this.params.maxWidth + "px";
12720 }else {
12721 this.listEl.style.maxWidth = this.params.maxWidth;
12722 }
12723 }
12724
12725 }
12726
12727 _createInputElement(){
12728 var attribs = this.params.elementAttributes;
12729 var input = document.createElement("input");
12730
12731 input.setAttribute("type", this.params.clearable ? "search" : "text");
12732
12733 input.style.padding = "4px";
12734 input.style.width = "100%";
12735 input.style.boxSizing = "border-box";
12736
12737 if(!this.params.autocomplete){
12738 input.style.cursor = "default";
12739 input.style.caretColor = "transparent";
12740 // input.readOnly = (this.edit.currentCell != false);
12741 }
12742
12743 if(attribs && typeof attribs == "object"){
12744 for (let key in attribs){
12745 if(key.charAt(0) == "+"){
12746 key = key.slice(1);
12747 input.setAttribute(key, input.getAttribute(key) + attribs["+" + key]);
12748 }else {
12749 input.setAttribute(key, attribs[key]);
12750 }
12751 }
12752 }
12753
12754 if(this.params.mask){
12755 maskInput(input, this.params);
12756 }
12757
12758 this._bindInputEvents(input);
12759
12760 return input;
12761 }
12762
12763 _initializeParams(params){
12764 var valueKeys = ["values", "valuesURL", "valuesLookup"],
12765 valueCheck;
12766
12767 params = Object.assign({}, params);
12768
12769 params.verticalNavigation = params.verticalNavigation || "editor";
12770 params.placeholderLoading = typeof params.placeholderLoading === "undefined" ? "Searching ..." : params.placeholderLoading;
12771 params.placeholderEmpty = typeof params.placeholderEmpty === "undefined" ? "No Results Found" : params.placeholderEmpty;
12772 params.filterDelay = typeof params.filterDelay === "undefined" ? 300 : params.filterDelay;
12773
12774 params.emptyValue = Object.keys(params).includes("emptyValue") ? params.emptyValue : "";
12775
12776 valueCheck = Object.keys(params).filter(key => valueKeys.includes(key)).length;
12777
12778 if(!valueCheck){
12779 console.warn("list editor config error - either the values, valuesURL, or valuesLookup option must be set");
12780 }else if(valueCheck > 1){
12781 console.warn("list editor config error - only one of the values, valuesURL, or valuesLookup options can be set on the same editor");
12782 }
12783
12784 if(params.autocomplete){
12785 if(params.multiselect){
12786 params.multiselect = false;
12787 console.warn("list editor config error - multiselect option is not available when autocomplete is enabled");
12788 }
12789 }else {
12790 if(params.freetext){
12791 params.freetext = false;
12792 console.warn("list editor config error - freetext option is only available when autocomplete is enabled");
12793 }
12794
12795 if(params.filterFunc){
12796 params.filterFunc = false;
12797 console.warn("list editor config error - filterFunc option is only available when autocomplete is enabled");
12798 }
12799
12800 if(params.filterRemote){
12801 params.filterRemote = false;
12802 console.warn("list editor config error - filterRemote option is only available when autocomplete is enabled");
12803 }
12804
12805 if(params.mask){
12806 params.mask = false;
12807 console.warn("list editor config error - mask option is only available when autocomplete is enabled");
12808 }
12809
12810 if(params.allowEmpty){
12811 params.allowEmpty = false;
12812 console.warn("list editor config error - allowEmpty option is only available when autocomplete is enabled");
12813 }
12814
12815 if(params.listOnEmpty){
12816 params.listOnEmpty = false;
12817 console.warn("list editor config error - listOnEmpty option is only available when autocomplete is enabled");
12818 }
12819 }
12820
12821 if(params.filterRemote && !(typeof params.valuesLookup === "function" || params.valuesURL)){
12822 params.filterRemote = false;
12823 console.warn("list editor config error - filterRemote option should only be used when values list is populated from a remote source");
12824 }
12825 return params;
12826 }
12827 //////////////////////////////////////
12828 ////////// Event Handling ////////////
12829 //////////////////////////////////////
12830
12831 _bindInputEvents(input){
12832 input.addEventListener("focus", this._inputFocus.bind(this));
12833 input.addEventListener("click", this._inputClick.bind(this));
12834 input.addEventListener("blur", this._inputBlur.bind(this));
12835 input.addEventListener("keydown", this._inputKeyDown.bind(this));
12836 input.addEventListener("search", this._inputSearch.bind(this));
12837
12838 if(this.params.autocomplete){
12839 input.addEventListener("keyup", this._inputKeyUp.bind(this));
12840 }
12841 }
12842
12843
12844 _inputFocus(e){
12845 this.rebuildOptionsList();
12846 }
12847
12848 _filter(){
12849 if(this.params.filterRemote){
12850 clearTimeout(this.filterTimeout);
12851
12852 this.filterTimeout = setTimeout(() => {
12853 this.rebuildOptionsList();
12854 }, this.params.filterDelay);
12855 }else {
12856 this._filterList();
12857 }
12858 }
12859
12860 _inputClick(e){
12861 e.stopPropagation();
12862 }
12863
12864 _inputBlur(e){
12865 if(this.blurable){
12866 if(this.popup){
12867 this.popup.hide();
12868 }else {
12869 this._resolveValue(true);
12870 }
12871 }
12872 }
12873
12874 _inputSearch(){
12875 this._clearChoices();
12876 }
12877
12878 _inputKeyDown(e){
12879 switch(e.key){
12880
12881 case "ArrowUp":
12882 this._keyUp(e);
12883 break;
12884
12885 case "ArrowDown":
12886 this._keyDown(e);
12887 break;
12888
12889 case "ArrowLeft":
12890 case "ArrowRight":
12891 this._keySide(e);
12892 break;
12893
12894 case "Enter":
12895 this._keyEnter();
12896 break;
12897
12898 case "Escape":
12899 this._keyEsc();
12900 break;
12901
12902 case "Home":
12903 case "End":
12904 this._keyHomeEnd(e);
12905 break;
12906
12907 case "Tab":
12908 this._keyTab(e);
12909 break;
12910
12911 default:
12912 this._keySelectLetter(e);
12913 }
12914 }
12915
12916 _inputKeyUp(e){
12917 switch(e.key){
12918 case "ArrowUp":
12919 case "ArrowLeft":
12920 case "ArrowRight":
12921 case "ArrowDown":
12922 case "Enter":
12923 case "Escape":
12924 break;
12925
12926 default:
12927 this._keyAutoCompLetter(e);
12928 }
12929 }
12930
12931 _preventPopupBlur(){
12932 if(this.popup){
12933 this.popup.blockHide();
12934 }
12935
12936 setTimeout(() =>{
12937 if(this.popup){
12938 this.popup.restoreHide();
12939 }
12940 }, 10);
12941 }
12942
12943 _preventBlur(){
12944 this.blurable = false;
12945
12946 setTimeout(() =>{
12947 this.blurable = true;
12948 }, 10);
12949 }
12950
12951 //////////////////////////////////////
12952 //////// Keyboard Navigation /////////
12953 //////////////////////////////////////
12954
12955 _keyTab(e){
12956 if(this.params.autocomplete && this.lastAction === "typing"){
12957 this._resolveValue(true);
12958 }else {
12959 if(this.focusedItem){
12960 this._chooseItem(this.focusedItem, true);
12961 }
12962 }
12963 }
12964
12965 _keyUp(e){
12966 var index = this.displayItems.indexOf(this.focusedItem);
12967
12968 if(this.params.verticalNavigation == "editor" || (this.params.verticalNavigation == "hybrid" && index)){
12969 e.stopImmediatePropagation();
12970 e.stopPropagation();
12971 e.preventDefault();
12972
12973 if(index > 0){
12974 this._focusItem(this.displayItems[index - 1]);
12975 }
12976 }
12977 }
12978
12979 _keyDown(e){
12980 var index = this.displayItems.indexOf(this.focusedItem);
12981
12982 if(this.params.verticalNavigation == "editor" || (this.params.verticalNavigation == "hybrid" && index < this.displayItems.length - 1)){
12983 e.stopImmediatePropagation();
12984 e.stopPropagation();
12985 e.preventDefault();
12986
12987 if(index < this.displayItems.length - 1){
12988 if(index == -1){
12989 this._focusItem(this.displayItems[0]);
12990 }else {
12991 this._focusItem(this.displayItems[index + 1]);
12992 }
12993 }
12994 }
12995 }
12996
12997 _keySide(e){
12998 if(!this.params.autocomplete){
12999 e.stopImmediatePropagation();
13000 e.stopPropagation();
13001 e.preventDefault();
13002 }
13003 }
13004
13005 _keyEnter(e){
13006 if(this.params.autocomplete && this.lastAction === "typing"){
13007 this._resolveValue(true);
13008 }else {
13009 if(this.focusedItem){
13010 this._chooseItem(this.focusedItem);
13011 }
13012 }
13013 }
13014
13015 _keyEsc(e){
13016 this._cancel();
13017 }
13018
13019 _keyHomeEnd(e){
13020 if(this.params.autocomplete){
13021 //prevent table navigation while using input element
13022 e.stopImmediatePropagation();
13023 }
13024 }
13025
13026 _keySelectLetter(e){
13027 if(!this.params.autocomplete){
13028 // if(this.edit.currentCell === false){
13029 e.preventDefault();
13030 // }
13031
13032 if(e.key.length === 1){
13033 this._scrollToValue(e.key.toUpperCase().charCodeAt(0));
13034 }
13035 }
13036 }
13037
13038 _keyAutoCompLetter(e){
13039 this._filter();
13040 this.lastAction = "typing";
13041 this.typing = true;
13042 }
13043
13044
13045 _scrollToValue(char){
13046 clearTimeout(this.filterTimeout);
13047
13048 var character = String.fromCharCode(char).toLowerCase();
13049 this.filterTerm += character.toLowerCase();
13050
13051 var match = this.displayItems.find((item) => {
13052 return typeof item.label !== "undefined" && item.label.toLowerCase().startsWith(this.filterTerm);
13053 });
13054
13055 if(match){
13056 this._focusItem(match);
13057 }
13058
13059 this.filterTimeout = setTimeout(() => {
13060 this.filterTerm = "";
13061 }, 800);
13062 }
13063
13064 _focusItem(item){
13065 this.lastAction = "focus";
13066
13067 if(this.focusedItem && this.focusedItem.element){
13068 this.focusedItem.element.classList.remove("focused");
13069 }
13070
13071 this.focusedItem = item;
13072
13073 if(item && item.element){
13074 item.element.classList.add("focused");
13075 item.element.scrollIntoView({behavior: 'smooth', block: 'nearest', inline: 'start'});
13076 }
13077 }
13078
13079
13080 //////////////////////////////////////
13081 /////// Data List Generation /////////
13082 //////////////////////////////////////
13083 headerFilterInitialListGen(){
13084 this._generateOptions(true);
13085 }
13086
13087 rebuildOptionsList(){
13088 this._generateOptions()
13089 .then(this._sortOptions.bind(this))
13090 .then(this._buildList.bind(this))
13091 .then(this._showList.bind(this))
13092 .catch((e) => {
13093 if(!Number.isInteger(e)){
13094 console.error("List generation error", e);
13095 }
13096 });
13097 }
13098
13099 _filterList(){
13100 this._buildList(this._filterOptions());
13101 this._showList();
13102 }
13103
13104 _generateOptions(silent){
13105 var values = [];
13106 var iteration = ++ this.listIteration;
13107
13108 this.filtered = false;
13109
13110 if(this.params.values){
13111 values = this.params.values;
13112 }else if (this.params.valuesURL){
13113 values = this._ajaxRequest(this.params.valuesURL, this.input.value);
13114 }else {
13115 if(typeof this.params.valuesLookup === "function"){
13116 values = this.params.valuesLookup(this.cell, this.input.value);
13117 }else if(this.params.valuesLookup){
13118 values = this._uniqueColumnValues(this.params.valuesLookupField);
13119 }
13120 }
13121
13122 if(values instanceof Promise){
13123 if(!silent){
13124 this._addPlaceholder(this.params.placeholderLoading);
13125 }
13126
13127 return values.then()
13128 .then((responseValues) => {
13129 if(this.listIteration === iteration){
13130 return this._parseList(responseValues);
13131 }else {
13132 return Promise.reject(iteration);
13133 }
13134 });
13135 }else {
13136 return Promise.resolve(this._parseList(values));
13137 }
13138 }
13139
13140 _addPlaceholder(contents){
13141 var placeholder = document.createElement("div");
13142
13143 if(typeof contents === "function"){
13144 contents = contents(this.cell.getComponent(), this.listEl);
13145 }
13146
13147 if(contents){
13148 this._clearList();
13149
13150 if(contents instanceof HTMLElement){
13151 placeholder = contents;
13152 }else {
13153 placeholder.classList.add("tabulator-edit-list-placeholder");
13154 placeholder.innerHTML = contents;
13155 }
13156
13157 this.listEl.appendChild(placeholder);
13158
13159 this._showList();
13160 }
13161 }
13162
13163 _ajaxRequest(url, term){
13164 var params = this.params.filterRemote ? {term:term} : {};
13165 url = urlBuilder(url, {}, params);
13166
13167 return fetch(url)
13168 .then((response)=>{
13169 if(response.ok) {
13170 return response.json()
13171 .catch((error)=>{
13172 console.warn("List Ajax Load Error - Invalid JSON returned", error);
13173 return Promise.reject(error);
13174 });
13175 }else {
13176 console.error("List Ajax Load Error - Connection Error: " + response.status, response.statusText);
13177 return Promise.reject(response);
13178 }
13179 })
13180 .catch((error)=>{
13181 console.error("List Ajax Load Error - Connection Error: ", error);
13182 return Promise.reject(error);
13183 });
13184 }
13185
13186 _uniqueColumnValues(field){
13187 var output = {},
13188 data = this.table.getData(this.params.valuesLookup),
13189 column;
13190
13191 if(field){
13192 column = this.table.columnManager.getColumnByField(field);
13193 }else {
13194 column = this.cell.getColumn()._getSelf();
13195 }
13196
13197 if(column){
13198 data.forEach((row) => {
13199 var val = column.getFieldValue(row);
13200
13201 if(!this._emptyValueCheck(val)){
13202 if(this.params.multiselect && Array.isArray(val)){
13203 val.forEach((item) => {
13204 if(!this._emptyValueCheck(item)){
13205 output[item] = true;
13206 }
13207 });
13208 }else {
13209 output[val] = true;
13210 }
13211
13212 }
13213 });
13214 }else {
13215 console.warn("unable to find matching column to create select lookup list:", field);
13216 output = [];
13217 }
13218
13219 return Object.keys(output);
13220 }
13221
13222 _emptyValueCheck(value){
13223 return value === null || typeof value === "undefined" || value === "";
13224 }
13225
13226 _parseList(inputValues){
13227 var data = [];
13228
13229 if(!Array.isArray(inputValues)){
13230 inputValues = Object.entries(inputValues).map(([key, value]) => {
13231 return {
13232 label:value,
13233 value:key,
13234 };
13235 });
13236 }
13237
13238 inputValues.forEach((value) => {
13239 if(typeof value !== "object"){
13240 value = {
13241 label:value,
13242 value:value,
13243 };
13244 }
13245
13246 this._parseListItem(value, data, 0);
13247 });
13248
13249 if(!this.currentItems.length && this.params.freetext){
13250 this.input.value = this.initialValues;
13251 this.typing = true;
13252 this.lastAction = "typing";
13253 }
13254
13255 this.data = data;
13256
13257 return data;
13258 }
13259
13260 _parseListItem(option, data, level){
13261 var item = {};
13262
13263 if(option.options){
13264 item = this._parseListGroup(option, level + 1);
13265 }else {
13266 item = {
13267 label:option.label,
13268 value:option.value,
13269 itemParams:option.itemParams,
13270 elementAttributes: option.elementAttributes,
13271 element:false,
13272 selected:false,
13273 visible:true,
13274 level:level,
13275 original:option,
13276 };
13277
13278 if(this.initialValues && this.initialValues.indexOf(option.value) > -1){
13279 this._chooseItem(item, true);
13280 }
13281 }
13282
13283 data.push(item);
13284 }
13285
13286 _parseListGroup(option, level){
13287 var item = {
13288 label:option.label,
13289 group:true,
13290 itemParams:option.itemParams,
13291 elementAttributes:option.elementAttributes,
13292 element:false,
13293 visible:true,
13294 level:level,
13295 options:[],
13296 original:option,
13297 };
13298
13299 option.options.forEach((child) => {
13300 this._parseListItem(child, item.options, level);
13301 });
13302
13303 return item;
13304 }
13305
13306 _sortOptions(options){
13307 var sorter;
13308
13309 if(this.params.sort){
13310 sorter = typeof this.params.sort === "function" ? this.params.sort : this._defaultSortFunction.bind(this);
13311
13312 this._sortGroup(sorter, options);
13313 }
13314
13315 return options;
13316 }
13317
13318 _sortGroup(sorter, options){
13319 options.sort((a,b) => {
13320 return sorter(a.label, b.label, a.value, b.value, a.original, b.original);
13321 });
13322
13323 options.forEach((option) => {
13324 if(option.group){
13325 this._sortGroup(sorter, option.options);
13326 }
13327 });
13328 }
13329
13330 _defaultSortFunction(as, bs){
13331 var a, b, a1, b1, i= 0, L, rx = /(\d+)|(\D+)/g, rd = /\d/;
13332 var emptyAlign = 0;
13333
13334 if(this.params.sort === "desc"){
13335 [as, bs] = [bs, as];
13336 }
13337
13338 //handle empty values
13339 if(!as && as!== 0){
13340 emptyAlign = !bs && bs!== 0 ? 0 : -1;
13341 }else if(!bs && bs!== 0){
13342 emptyAlign = 1;
13343 }else {
13344 if(isFinite(as) && isFinite(bs)) return as - bs;
13345 a = String(as).toLowerCase();
13346 b = String(bs).toLowerCase();
13347 if(a === b) return 0;
13348 if(!(rd.test(a) && rd.test(b))) return a > b ? 1 : -1;
13349 a = a.match(rx);
13350 b = b.match(rx);
13351 L = a.length > b.length ? b.length : a.length;
13352 while(i < L){
13353 a1= a[i];
13354 b1= b[i++];
13355 if(a1 !== b1){
13356 if(isFinite(a1) && isFinite(b1)){
13357 if(a1.charAt(0) === "0") a1 = "." + a1;
13358 if(b1.charAt(0) === "0") b1 = "." + b1;
13359 return a1 - b1;
13360 }
13361 else return a1 > b1 ? 1 : -1;
13362 }
13363 }
13364
13365 return a.length > b.length;
13366 }
13367
13368 return emptyAlign;
13369 }
13370
13371 _filterOptions(){
13372 var filterFunc = this.params.filterFunc || this._defaultFilterFunc,
13373 term = this.input.value;
13374
13375 if(term){
13376 this.filtered = true;
13377
13378 this.data.forEach((item) => {
13379 this._filterItem(filterFunc, term, item);
13380 });
13381 }else {
13382 this.filtered = false;
13383 }
13384
13385 return this.data;
13386 }
13387
13388 _filterItem(func, term, item){
13389 var matches = false;
13390
13391 if(!item.group){
13392 item.visible = func(term, item.label, item.value, item.original);
13393 }else {
13394 item.options.forEach((option) => {
13395 if(this._filterItem(func, term, option)){
13396 matches = true;
13397 }
13398 });
13399
13400 item.visible = matches;
13401 }
13402
13403 return item.visible;
13404 }
13405
13406 _defaultFilterFunc(term, label, value, item){
13407 term = String(term).toLowerCase();
13408
13409 if(label !== null && typeof label !== "undefined"){
13410 if(String(label).toLowerCase().indexOf(term) > -1 || String(value).toLowerCase().indexOf(term) > -1){
13411 return true;
13412 }
13413 }
13414
13415 return false;
13416 }
13417
13418 //////////////////////////////////////
13419 /////////// Display List /////////////
13420 //////////////////////////////////////
13421
13422 _clearList(){
13423 while(this.listEl.firstChild) this.listEl.removeChild(this.listEl.firstChild);
13424
13425 this.displayItems = [];
13426 }
13427
13428 _buildList(data){
13429 this._clearList();
13430
13431 data.forEach((option) => {
13432 this._buildItem(option);
13433 });
13434
13435 if(!this.displayItems.length){
13436 this._addPlaceholder(this.params.placeholderEmpty);
13437 }
13438 }
13439
13440 _buildItem(item){
13441 var el = item.element,
13442 contents;
13443
13444 if(!this.filtered || item.visible){
13445
13446 if(!el){
13447 el = document.createElement("div");
13448 el.tabIndex = 0;
13449
13450 contents = this.params.itemFormatter ? this.params.itemFormatter(item.label, item.value, item.original, el) : item.label;
13451
13452 if(contents instanceof HTMLElement){
13453 el.appendChild(contents);
13454 }else {
13455 el.innerHTML = contents;
13456 }
13457
13458 if(item.group){
13459 el.classList.add("tabulator-edit-list-group");
13460 }else {
13461 el.classList.add("tabulator-edit-list-item");
13462 }
13463
13464 el.classList.add("tabulator-edit-list-group-level-" + item.level);
13465
13466 if(item.elementAttributes && typeof item.elementAttributes == "object"){
13467 for (let key in item.elementAttributes){
13468 if(key.charAt(0) == "+"){
13469 key = key.slice(1);
13470 el.setAttribute(key, this.input.getAttribute(key) + item.elementAttributes["+" + key]);
13471 }else {
13472 el.setAttribute(key, item.elementAttributes[key]);
13473 }
13474 }
13475 }
13476
13477 if(item.group){
13478 el.addEventListener("click", this._groupClick.bind(this, item));
13479 }else {
13480 el.addEventListener("click", this._itemClick.bind(this, item));
13481 }
13482
13483 el.addEventListener("mousedown", this._preventBlur.bind(this));
13484
13485 item.element = el;
13486 }
13487
13488 this._styleItem(item);
13489
13490 this.listEl.appendChild(el);
13491
13492 if(item.group){
13493 item.options.forEach((option) => {
13494 this._buildItem(option);
13495 });
13496 }else {
13497 this.displayItems.push(item);
13498 }
13499 }
13500 }
13501
13502 _showList(){
13503 var startVis = this.popup && this.popup.isVisible();
13504
13505 if(this.input.parentNode){
13506 if(this.params.autocomplete && this.input.value === "" && !this.params.listOnEmpty){
13507 if(this.popup){
13508 this.popup.hide(true);
13509 }
13510 return;
13511 }
13512
13513 this._setListWidth();
13514
13515 if(!this.popup){
13516 this.popup = this.edit.popup(this.listEl);
13517 }
13518
13519 this.popup.show(this.cell.getElement(), "bottom");
13520
13521 if(!startVis){
13522 setTimeout(() => {
13523 this.popup.hideOnBlur(this._resolveValue.bind(this, true));
13524 }, 10);
13525 }
13526 }
13527 }
13528
13529 _styleItem(item){
13530 if(item && item.element){
13531 if(item.selected){
13532 item.element.classList.add("active");
13533 }else {
13534 item.element.classList.remove("active");
13535 }
13536 }
13537 }
13538
13539 //////////////////////////////////////
13540 ///////// User Interaction ///////////
13541 //////////////////////////////////////
13542
13543 _itemClick(item, e){
13544 e.stopPropagation();
13545
13546 this._chooseItem(item);
13547 }
13548
13549 _groupClick(item, e){
13550 e.stopPropagation();
13551 }
13552
13553
13554 //////////////////////////////////////
13555 ////// Current Item Management ///////
13556 //////////////////////////////////////
13557
13558 _cancel(){
13559 this.popup.hide(true);
13560 this.actions.cancel();
13561 }
13562
13563 _clearChoices(){
13564 this.typing = true;
13565
13566 this.currentItems.forEach((item) => {
13567 item.selected = false;
13568 this._styleItem(item);
13569 });
13570
13571 this.currentItems = [];
13572
13573 this.focusedItem = null;
13574 }
13575
13576 _chooseItem(item, silent){
13577 var index;
13578
13579 this.typing = false;
13580
13581 if(this.params.multiselect){
13582 index = this.currentItems.indexOf(item);
13583
13584 if(index > -1){
13585 this.currentItems.splice(index, 1);
13586 item.selected = false;
13587 }else {
13588 this.currentItems.push(item);
13589 item.selected = true;
13590 }
13591
13592 this.input.value = this.currentItems.map(item => item.label).join(",");
13593
13594 this._styleItem(item);
13595
13596 }else {
13597 this.currentItems = [item];
13598 item.selected = true;
13599
13600 this.input.value = item.label;
13601
13602 this._styleItem(item);
13603
13604 if(!silent){
13605 this._resolveValue();
13606 }
13607 }
13608
13609 this._focusItem(item);
13610 }
13611
13612 _resolveValue(blur){
13613 var output, initialValue;
13614
13615 if(this.popup){
13616 this.popup.hide(true);
13617 }
13618
13619 if(this.params.multiselect){
13620 output = this.currentItems.map(item => item.value);
13621 }else {
13622 if(blur && this.params.autocomplete && this.typing){
13623 if(this.params.freetext || (this.params.allowEmpty && this.input.value === "")){
13624 output = this.input.value;
13625 }else {
13626 this.actions.cancel();
13627 return;
13628 }
13629 }else {
13630 if(this.currentItems[0]){
13631 output = this.currentItems[0].value;
13632 }else {
13633 initialValue = Array.isArray(this.initialValues) ? this.initialValues[0] : this.initialValues;
13634
13635 if(initialValue === null || typeof initialValue === "undefined" || initialValue === ""){
13636 output = initialValue;
13637 }else {
13638 output = this.params.emptyValue;
13639 }
13640 }
13641
13642 }
13643 }
13644
13645 if(output === ""){
13646 output = this.params.emptyValue;
13647 }
13648
13649 this.actions.success(output);
13650
13651 if(this.isFilter){
13652 this.initialValues = output && !Array.isArray(output) ? [output] : output;
13653 this.currentItems = [];
13654 }
13655 }
13656
13657 };
13658
13659 function list(cell, onRendered, success, cancel, editorParams){
13660 var list = new Edit$1(this, cell, onRendered, success, cancel, editorParams);
13661
13662 return list.input;
13663 }
13664
13665 //star rating
13666 function star$1(cell, onRendered, success, cancel, editorParams){
13667 var self = this,
13668 element = cell.getElement(),
13669 value = cell.getValue(),
13670 maxStars = element.getElementsByTagName("svg").length || 5,
13671 size = element.getElementsByTagName("svg")[0] ? element.getElementsByTagName("svg")[0].getAttribute("width") : 14,
13672 stars = [],
13673 starsHolder = document.createElement("div"),
13674 star = document.createElementNS('http://www.w3.org/2000/svg', "svg");
13675
13676
13677 //change star type
13678 function starChange(val){
13679 stars.forEach(function(star, i){
13680 if(i < val){
13681 if(self.table.browser == "ie"){
13682 star.setAttribute("class", "tabulator-star-active");
13683 }else {
13684 star.classList.replace("tabulator-star-inactive", "tabulator-star-active");
13685 }
13686
13687 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 "/>';
13688 }else {
13689 if(self.table.browser == "ie"){
13690 star.setAttribute("class", "tabulator-star-inactive");
13691 }else {
13692 star.classList.replace("tabulator-star-active", "tabulator-star-inactive");
13693 }
13694
13695 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 "/>';
13696 }
13697 });
13698 }
13699
13700 //build stars
13701 function buildStar(i){
13702
13703 var starHolder = document.createElement("span");
13704 var nextStar = star.cloneNode(true);
13705
13706 stars.push(nextStar);
13707
13708 starHolder.addEventListener("mouseenter", function(e){
13709 e.stopPropagation();
13710 e.stopImmediatePropagation();
13711 starChange(i);
13712 });
13713
13714 starHolder.addEventListener("mousemove", function(e){
13715 e.stopPropagation();
13716 e.stopImmediatePropagation();
13717 });
13718
13719 starHolder.addEventListener("click", function(e){
13720 e.stopPropagation();
13721 e.stopImmediatePropagation();
13722 success(i);
13723 element.blur();
13724 });
13725
13726 starHolder.appendChild(nextStar);
13727 starsHolder.appendChild(starHolder);
13728
13729 }
13730
13731 //handle keyboard navigation value change
13732 function changeValue(val){
13733 value = val;
13734 starChange(val);
13735 }
13736
13737 //style cell
13738 element.style.whiteSpace = "nowrap";
13739 element.style.overflow = "hidden";
13740 element.style.textOverflow = "ellipsis";
13741
13742 //style holding element
13743 starsHolder.style.verticalAlign = "middle";
13744 starsHolder.style.display = "inline-block";
13745 starsHolder.style.padding = "4px";
13746
13747 //style star
13748 star.setAttribute("width", size);
13749 star.setAttribute("height", size);
13750 star.setAttribute("viewBox", "0 0 512 512");
13751 star.setAttribute("xml:space", "preserve");
13752 star.style.padding = "0 1px";
13753
13754 if(editorParams.elementAttributes && typeof editorParams.elementAttributes == "object"){
13755 for (let key in editorParams.elementAttributes){
13756 if(key.charAt(0) == "+"){
13757 key = key.slice(1);
13758 starsHolder.setAttribute(key, starsHolder.getAttribute(key) + editorParams.elementAttributes["+" + key]);
13759 }else {
13760 starsHolder.setAttribute(key, editorParams.elementAttributes[key]);
13761 }
13762 }
13763 }
13764
13765 //create correct number of stars
13766 for(var i=1;i<= maxStars;i++){
13767 buildStar(i);
13768 }
13769
13770 //ensure value does not exceed number of stars
13771 value = Math.min(parseInt(value), maxStars);
13772
13773 // set initial styling of stars
13774 starChange(value);
13775
13776 starsHolder.addEventListener("mousemove", function(e){
13777 starChange(0);
13778 });
13779
13780 starsHolder.addEventListener("click", function(e){
13781 success(0);
13782 });
13783
13784 element.addEventListener("blur", function(e){
13785 cancel();
13786 });
13787
13788 //allow key based navigation
13789 element.addEventListener("keydown", function(e){
13790 switch(e.key){
13791 case "ArrowRight":
13792 changeValue(value + 1);
13793 break;
13794
13795 case "ArrowLeft":
13796 changeValue(value - 1);
13797 break;
13798
13799 case "Enter":
13800 success(value);
13801 break;
13802
13803 case "Escape":
13804 cancel();
13805 break;
13806 }
13807 });
13808
13809 return starsHolder;
13810 }
13811
13812 //draggable progress bar
13813 function progress$1(cell, onRendered, success, cancel, editorParams){
13814 var element = cell.getElement(),
13815 max = typeof editorParams.max === "undefined" ? ((element.getElementsByTagName("div")[0] && element.getElementsByTagName("div")[0].getAttribute("max")) || 100) : editorParams.max,
13816 min = typeof editorParams.min === "undefined" ? ((element.getElementsByTagName("div")[0] && element.getElementsByTagName("div")[0].getAttribute("min")) || 0) : editorParams.min,
13817 percent = (max - min) / 100,
13818 value = cell.getValue() || 0,
13819 handle = document.createElement("div"),
13820 bar = document.createElement("div"),
13821 mouseDrag, mouseDragWidth;
13822
13823 //set new value
13824 function updateValue(){
13825 var style = window.getComputedStyle(element, null);
13826
13827 var calcVal = (percent * Math.round(bar.offsetWidth / ((element.clientWidth - parseInt(style.getPropertyValue("padding-left")) - parseInt(style.getPropertyValue("padding-right")))/100))) + min;
13828 success(calcVal);
13829 element.setAttribute("aria-valuenow", calcVal);
13830 element.setAttribute("aria-label", value);
13831 }
13832
13833 //style handle
13834 handle.style.position = "absolute";
13835 handle.style.right = "0";
13836 handle.style.top = "0";
13837 handle.style.bottom = "0";
13838 handle.style.width = "5px";
13839 handle.classList.add("tabulator-progress-handle");
13840
13841 //style bar
13842 bar.style.display = "inline-block";
13843 bar.style.position = "relative";
13844 // bar.style.top = "8px";
13845 // bar.style.bottom = "8px";
13846 // bar.style.left = "4px";
13847 // bar.style.marginRight = "4px";
13848 bar.style.height = "100%";
13849 bar.style.backgroundColor = "#488CE9";
13850 bar.style.maxWidth = "100%";
13851 bar.style.minWidth = "0%";
13852
13853 if(editorParams.elementAttributes && typeof editorParams.elementAttributes == "object"){
13854 for (let key in editorParams.elementAttributes){
13855 if(key.charAt(0) == "+"){
13856 key = key.slice(1);
13857 bar.setAttribute(key, bar.getAttribute(key) + editorParams.elementAttributes["+" + key]);
13858 }else {
13859 bar.setAttribute(key, editorParams.elementAttributes[key]);
13860 }
13861 }
13862 }
13863
13864 //style cell
13865 element.style.padding = "4px 4px";
13866
13867 //make sure value is in range
13868 value = Math.min(parseFloat(value), max);
13869 value = Math.max(parseFloat(value), min);
13870
13871 //workout percentage
13872 value = Math.round((value - min) / percent);
13873 // bar.style.right = value + "%";
13874 bar.style.width = value + "%";
13875
13876 element.setAttribute("aria-valuemin", min);
13877 element.setAttribute("aria-valuemax", max);
13878
13879 bar.appendChild(handle);
13880
13881 handle.addEventListener("mousedown", function(e){
13882 mouseDrag = e.screenX;
13883 mouseDragWidth = bar.offsetWidth;
13884 });
13885
13886 handle.addEventListener("mouseover", function(){
13887 handle.style.cursor = "ew-resize";
13888 });
13889
13890 element.addEventListener("mousemove", function(e){
13891 if(mouseDrag){
13892 bar.style.width = (mouseDragWidth + e.screenX - mouseDrag) + "px";
13893 }
13894 });
13895
13896 element.addEventListener("mouseup", function(e){
13897 if(mouseDrag){
13898 e.stopPropagation();
13899 e.stopImmediatePropagation();
13900
13901 mouseDrag = false;
13902 mouseDragWidth = false;
13903
13904 updateValue();
13905 }
13906 });
13907
13908 //allow key based navigation
13909 element.addEventListener("keydown", function(e){
13910 switch(e.key){
13911 case "ArrowRight":
13912 e.preventDefault();
13913 bar.style.width = (bar.clientWidth + element.clientWidth/100) + "px";
13914 break;
13915
13916 case "ArrowLeft":
13917 e.preventDefault();
13918 bar.style.width = (bar.clientWidth - element.clientWidth/100) + "px";
13919 break;
13920
13921 case "Tab":
13922 case "Enter":
13923 updateValue();
13924 break;
13925
13926 case "Escape":
13927 cancel();
13928 break;
13929
13930 }
13931 });
13932
13933 element.addEventListener("blur", function(){
13934 cancel();
13935 });
13936
13937 return bar;
13938 }
13939
13940 //checkbox
13941 function tickCross$1(cell, onRendered, success, cancel, editorParams){
13942 var value = cell.getValue(),
13943 input = document.createElement("input"),
13944 tristate = editorParams.tristate,
13945 indetermValue = typeof editorParams.indeterminateValue === "undefined" ? null : editorParams.indeterminateValue,
13946 indetermState = false,
13947 trueValueSet = Object.keys(editorParams).includes("trueValue"),
13948 falseValueSet = Object.keys(editorParams).includes("falseValue");
13949
13950 input.setAttribute("type", "checkbox");
13951 input.style.marginTop = "5px";
13952 input.style.boxSizing = "border-box";
13953
13954 if(editorParams.elementAttributes && typeof editorParams.elementAttributes == "object"){
13955 for (let key in editorParams.elementAttributes){
13956 if(key.charAt(0) == "+"){
13957 key = key.slice(1);
13958 input.setAttribute(key, input.getAttribute(key) + editorParams.elementAttributes["+" + key]);
13959 }else {
13960 input.setAttribute(key, editorParams.elementAttributes[key]);
13961 }
13962 }
13963 }
13964
13965 input.value = value;
13966
13967 if(tristate && (typeof value === "undefined" || value === indetermValue || value === "")){
13968 indetermState = true;
13969 input.indeterminate = true;
13970 }
13971
13972 if(this.table.browser != "firefox" && this.table.browser != "safari"){ //prevent blur issue on mac firefox
13973 onRendered(function(){
13974 if(cell.getType() === "cell"){
13975 input.focus({preventScroll: true});
13976 }
13977 });
13978 }
13979
13980 input.checked = trueValueSet ? value === editorParams.trueValue : (value === true || value === "true" || value === "True" || value === 1);
13981
13982 function setValue(blur){
13983 var checkedValue = input.checked;
13984
13985 if(trueValueSet && checkedValue){
13986 checkedValue = editorParams.trueValue;
13987 }else if(falseValueSet && !checkedValue){
13988 checkedValue = editorParams.falseValue;
13989 }
13990
13991 if(tristate){
13992 if(!blur){
13993 if(input.checked && !indetermState){
13994 input.checked = false;
13995 input.indeterminate = true;
13996 indetermState = true;
13997 return indetermValue;
13998 }else {
13999 indetermState = false;
14000 return checkedValue;
14001 }
14002 }else {
14003 if(indetermState){
14004 return indetermValue;
14005 }else {
14006 return checkedValue;
14007 }
14008 }
14009 }else {
14010 return checkedValue;
14011 }
14012 }
14013
14014 //submit new value on blur
14015 input.addEventListener("change", function(e){
14016 success(setValue());
14017 });
14018
14019 input.addEventListener("blur", function(e){
14020 success(setValue(true));
14021 });
14022
14023 //submit new value on enter
14024 input.addEventListener("keydown", function(e){
14025 if(e.key == "Enter"){
14026 success(setValue());
14027 }
14028 if(e.key == "Escape"){
14029 cancel();
14030 }
14031 });
14032
14033 return input;
14034 }
14035
14036 function adaptable$1(cell, onRendered, success, cancel, params){
14037 var column = cell._getSelf().column,
14038 lookup, editorFunc, editorParams;
14039
14040 function defaultLookup(cell){
14041 var value = cell.getValue(),
14042 editor = "input";
14043
14044 switch(typeof value){
14045 case "number":
14046 editor = "number";
14047 break;
14048
14049 case "boolean":
14050 editor = "tickCross";
14051 break;
14052
14053 case "string":
14054 if(value.includes("\n")){
14055 editor = "textarea";
14056 }
14057 break;
14058 }
14059
14060 return editor;
14061 }
14062
14063 lookup = params.editorLookup ? params.editorLookup(cell) : defaultLookup(cell);
14064
14065 if(params.paramsLookup){
14066 editorParams = typeof params.paramsLookup === "function" ? params.paramsLookup(lookup, cell) : params.paramsLookup[lookup];
14067 }
14068
14069 editorFunc = this.table.modules.edit.lookupEditor(lookup, column);
14070
14071 return editorFunc.call(this, cell, onRendered, success, cancel, editorParams || {});
14072 }
14073
14074 var defaultEditors = {
14075 input:input,
14076 textarea:textarea$1,
14077 number:number$1,
14078 range:range,
14079 date:date$1,
14080 time:time$1,
14081 datetime:datetime$2,
14082 list:list,
14083 star:star$1,
14084 progress:progress$1,
14085 tickCross:tickCross$1,
14086 adaptable:adaptable$1,
14087 };
14088
14089 class Edit extends Module{
14090
14091 static moduleName = "edit";
14092
14093 //load defaults
14094 static editors = defaultEditors;
14095
14096 constructor(table){
14097 super(table);
14098
14099 this.currentCell = false; //hold currently editing cell
14100 this.mouseClick = false; //hold mousedown state to prevent click binding being overridden by editor opening
14101 this.recursionBlock = false; //prevent focus recursion
14102 this.invalidEdit = false;
14103 this.editedCells = [];
14104 this.convertEmptyValues = false;
14105
14106 this.editors = Edit.editors;
14107
14108 this.registerTableOption("editTriggerEvent", "focus");
14109 this.registerTableOption("editorEmptyValue");
14110 this.registerTableOption("editorEmptyValueFunc", this.emptyValueCheck.bind(this));
14111
14112 this.registerColumnOption("editable");
14113 this.registerColumnOption("editor");
14114 this.registerColumnOption("editorParams");
14115 this.registerColumnOption("editorEmptyValue");
14116 this.registerColumnOption("editorEmptyValueFunc");
14117
14118 this.registerColumnOption("cellEditing");
14119 this.registerColumnOption("cellEdited");
14120 this.registerColumnOption("cellEditCancelled");
14121
14122 this.registerTableFunction("getEditedCells", this.getEditedCells.bind(this));
14123 this.registerTableFunction("clearCellEdited", this.clearCellEdited.bind(this));
14124 this.registerTableFunction("navigatePrev", this.navigatePrev.bind(this));
14125 this.registerTableFunction("navigateNext", this.navigateNext.bind(this));
14126 this.registerTableFunction("navigateLeft", this.navigateLeft.bind(this));
14127 this.registerTableFunction("navigateRight", this.navigateRight.bind(this));
14128 this.registerTableFunction("navigateUp", this.navigateUp.bind(this));
14129 this.registerTableFunction("navigateDown", this.navigateDown.bind(this));
14130
14131 this.registerComponentFunction("cell", "isEdited", this.cellIsEdited.bind(this));
14132 this.registerComponentFunction("cell", "clearEdited", this.clearEdited.bind(this));
14133 this.registerComponentFunction("cell", "edit", this.editCell.bind(this));
14134 this.registerComponentFunction("cell", "cancelEdit", this.cellCancelEdit.bind(this));
14135
14136 this.registerComponentFunction("cell", "navigatePrev", this.navigatePrev.bind(this));
14137 this.registerComponentFunction("cell", "navigateNext", this.navigateNext.bind(this));
14138 this.registerComponentFunction("cell", "navigateLeft", this.navigateLeft.bind(this));
14139 this.registerComponentFunction("cell", "navigateRight", this.navigateRight.bind(this));
14140 this.registerComponentFunction("cell", "navigateUp", this.navigateUp.bind(this));
14141 this.registerComponentFunction("cell", "navigateDown", this.navigateDown.bind(this));
14142 }
14143
14144 initialize(){
14145 this.subscribe("cell-init", this.bindEditor.bind(this));
14146 this.subscribe("cell-delete", this.clearEdited.bind(this));
14147 this.subscribe("cell-value-changed", this.updateCellClass.bind(this));
14148 this.subscribe("column-layout", this.initializeColumnCheck.bind(this));
14149 this.subscribe("column-delete", this.columnDeleteCheck.bind(this));
14150 this.subscribe("row-deleting", this.rowDeleteCheck.bind(this));
14151 this.subscribe("row-layout", this.rowEditableCheck.bind(this));
14152 this.subscribe("data-refreshing", this.cancelEdit.bind(this));
14153 this.subscribe("clipboard-paste", this.pasteBlocker.bind(this));
14154
14155 if (!this.confirm("edit-nav-disabled")) {
14156 this.subscribe("keybinding-nav-prev", this.navigatePrev.bind(this, undefined));
14157 this.subscribe("keybinding-nav-next", this.keybindingNavigateNext.bind(this));
14158
14159 // this.subscribe("keybinding-nav-left", this.navigateLeft.bind(this, undefined));
14160 // this.subscribe("keybinding-nav-right", this.navigateRight.bind(this, undefined));
14161 this.subscribe("keybinding-nav-up", this.navigateUp.bind(this, undefined));
14162 this.subscribe("keybinding-nav-down", this.navigateDown.bind(this, undefined));
14163 }
14164
14165 // Add event handlers for other modules to access editing state and functionality
14166 this.subscribe("edit-check-editing", this.checkEditing.bind(this));
14167 this.subscribe("edit-cancel-cell", this.cancelEditEvent.bind(this));
14168
14169 if(Object.keys(this.table.options).includes("editorEmptyValue")){
14170 this.convertEmptyValues = true;
14171 }
14172 }
14173
14174
14175 ///////////////////////////////////
14176 ///////// Paste Negation //////////
14177 ///////////////////////////////////
14178
14179 pasteBlocker(e){
14180 if(this.currentCell){
14181 return true;
14182 }
14183 }
14184
14185
14186 ///////////////////////////////////
14187 ////// Keybinding Functions ///////
14188 ///////////////////////////////////
14189
14190 keybindingNavigateNext(e){
14191 var cell = this.currentCell,
14192 newRow = this.options("tabEndNewRow");
14193
14194 if(cell){
14195 if(!this.navigateNext(cell, e)){
14196 if(newRow){
14197 cell.getElement().firstChild.blur();
14198
14199 if(!this.invalidEdit){
14200
14201 if(newRow === true){
14202 newRow = this.table.addRow({});
14203 }else {
14204 if(typeof newRow == "function"){
14205 newRow = this.table.addRow(newRow(cell.row.getComponent()));
14206 }else {
14207 newRow = this.table.addRow(Object.assign({}, newRow));
14208 }
14209 }
14210
14211 newRow.then(() => {
14212 setTimeout(() => {
14213 cell.getComponent().navigateNext();
14214 });
14215 });
14216 }
14217 }
14218 }
14219 }
14220 }
14221
14222 ///////////////////////////////////
14223 ///////// Cell Functions //////////
14224 ///////////////////////////////////
14225
14226 cellIsEdited(cell){
14227 return !! cell.modules.edit && cell.modules.edit.edited;
14228 }
14229
14230 cellCancelEdit(cell){
14231 if(cell === this.currentCell){
14232 this.table.modules.edit.cancelEdit();
14233 }else {
14234 console.warn("Cancel Editor Error - This cell is not currently being edited ");
14235 }
14236 }
14237
14238
14239 ///////////////////////////////////
14240 ///////// Table Functions /////////
14241 ///////////////////////////////////
14242 updateCellClass(cell){
14243 if(this.allowEdit(cell)) {
14244 cell.getElement().classList.add("tabulator-editable");
14245 }
14246 else {
14247 cell.getElement().classList.remove("tabulator-editable");
14248 }
14249 }
14250
14251 clearCellEdited(cells){
14252 if(!cells){
14253 cells = this.table.modules.edit.getEditedCells();
14254 }
14255
14256 if(!Array.isArray(cells)){
14257 cells = [cells];
14258 }
14259
14260 cells.forEach((cell) => {
14261 this.table.modules.edit.clearEdited(cell._getSelf());
14262 });
14263 }
14264
14265 navigatePrev(cell = this.currentCell, e){
14266 var nextCell, prevRow;
14267
14268 if(cell){
14269
14270 if(e){
14271 e.preventDefault();
14272 }
14273
14274 nextCell = this.navigateLeft();
14275
14276 if(nextCell){
14277 return true;
14278 }else {
14279 prevRow = this.table.rowManager.prevDisplayRow(cell.row, true);
14280
14281 if(prevRow){
14282 nextCell = this.findPrevEditableCell(prevRow, prevRow.cells.length);
14283
14284 if(nextCell){
14285 nextCell.getComponent().edit();
14286 return true;
14287 }
14288 }
14289 }
14290 }
14291
14292 return false;
14293 }
14294
14295 navigateNext(cell = this.currentCell, e){
14296 var nextCell, nextRow;
14297
14298 if(cell){
14299
14300 if(e){
14301 e.preventDefault();
14302 }
14303
14304 nextCell = this.navigateRight();
14305
14306 if(nextCell){
14307 return true;
14308 }else {
14309 nextRow = this.table.rowManager.nextDisplayRow(cell.row, true);
14310
14311 if(nextRow){
14312 nextCell = this.findNextEditableCell(nextRow, -1);
14313
14314 if(nextCell){
14315 nextCell.getComponent().edit();
14316 return true;
14317 }
14318 }
14319 }
14320 }
14321
14322 return false;
14323 }
14324
14325 navigateLeft(cell = this.currentCell, e){
14326 var index, nextCell;
14327
14328 if(cell){
14329
14330 if(e){
14331 e.preventDefault();
14332 }
14333
14334 index = cell.getIndex();
14335 nextCell = this.findPrevEditableCell(cell.row, index);
14336
14337 if(nextCell){
14338 nextCell.getComponent().edit();
14339 return true;
14340 }
14341 }
14342
14343 return false;
14344 }
14345
14346 navigateRight(cell = this.currentCell, e){
14347 var index, nextCell;
14348
14349 if(cell){
14350
14351 if(e){
14352 e.preventDefault();
14353 }
14354
14355 index = cell.getIndex();
14356 nextCell = this.findNextEditableCell(cell.row, index);
14357
14358 if(nextCell){
14359 nextCell.getComponent().edit();
14360 return true;
14361 }
14362 }
14363
14364 return false;
14365 }
14366
14367 navigateUp(cell = this.currentCell, e){
14368 var index, nextRow;
14369
14370 if(cell){
14371
14372 if(e){
14373 e.preventDefault();
14374 }
14375
14376 index = cell.getIndex();
14377 nextRow = this.table.rowManager.prevDisplayRow(cell.row, true);
14378
14379 if(nextRow){
14380 nextRow.cells[index].getComponent().edit();
14381 return true;
14382 }
14383 }
14384
14385 return false;
14386 }
14387
14388 navigateDown(cell = this.currentCell, e){
14389 var index, nextRow;
14390
14391 if(cell){
14392
14393 if(e){
14394 e.preventDefault();
14395 }
14396
14397 index = cell.getIndex();
14398 nextRow = this.table.rowManager.nextDisplayRow(cell.row, true);
14399
14400 if(nextRow){
14401 nextRow.cells[index].getComponent().edit();
14402 return true;
14403 }
14404 }
14405
14406 return false;
14407 }
14408
14409 findNextEditableCell(row, index){
14410 var nextCell = false;
14411
14412 if(index < row.cells.length-1){
14413 for(var i = index+1; i < row.cells.length; i++){
14414 let cell = row.cells[i];
14415
14416 if(cell.column.modules.edit && Helpers.elVisible(cell.getElement())){
14417 let allowEdit = this.allowEdit(cell);
14418
14419 if(allowEdit){
14420 nextCell = cell;
14421 break;
14422 }
14423 }
14424 }
14425 }
14426
14427 return nextCell;
14428 }
14429
14430 findPrevEditableCell(row, index){
14431 var prevCell = false;
14432
14433 if(index > 0){
14434 for(var i = index-1; i >= 0; i--){
14435 let cell = row.cells[i];
14436
14437 if(cell.column.modules.edit && Helpers.elVisible(cell.getElement())){
14438 let allowEdit = this.allowEdit(cell);
14439
14440 if(allowEdit){
14441 prevCell = cell;
14442 break;
14443 }
14444 }
14445 }
14446 }
14447
14448 return prevCell;
14449 }
14450
14451 ///////////////////////////////////
14452 ///////// Internal Logic //////////
14453 ///////////////////////////////////
14454
14455 initializeColumnCheck(column){
14456 if(typeof column.definition.editor !== "undefined"){
14457 this.initializeColumn(column);
14458 }
14459 }
14460
14461 columnDeleteCheck(column){
14462 if(this.currentCell && this.currentCell.column === column){
14463 this.cancelEdit();
14464 }
14465 }
14466
14467 rowDeleteCheck(row){
14468 if(this.currentCell && this.currentCell.row === row){
14469 this.cancelEdit();
14470 }
14471 }
14472
14473 rowEditableCheck(row){
14474 row.getCells().forEach((cell) => {
14475 if(cell.column.modules.edit && typeof cell.column.modules.edit.check === "function"){
14476 this.updateCellClass(cell);
14477 }
14478 });
14479 }
14480
14481 //initialize column editor
14482 initializeColumn(column){
14483 var convertEmpty = Object.keys(column.definition).includes("editorEmptyValue");
14484
14485 var config = {
14486 editor:false,
14487 blocked:false,
14488 check:column.definition.editable,
14489 params:column.definition.editorParams || {},
14490 convertEmptyValues:convertEmpty,
14491 editorEmptyValue:column.definition.editorEmptyValue,
14492 editorEmptyValueFunc:column.definition.editorEmptyValueFunc,
14493 };
14494
14495 //set column editor
14496 config.editor = this.lookupEditor(column.definition.editor, column);
14497
14498 if(config.editor){
14499 column.modules.edit = config;
14500 }
14501 }
14502
14503 lookupEditor(editor, column){
14504 var editorFunc;
14505
14506 switch(typeof editor){
14507 case "string":
14508 if(this.editors[editor]){
14509 editorFunc = this.editors[editor];
14510 }else {
14511 console.warn("Editor Error - No such editor found: ", editor);
14512 }
14513 break;
14514
14515 case "function":
14516 editorFunc = editor;
14517 break;
14518
14519 case "boolean":
14520 if(editor === true){
14521 if(typeof column.definition.formatter !== "function"){
14522 if(this.editors[column.definition.formatter]){
14523 editorFunc = this.editors[column.definition.formatter];
14524 }else {
14525 editorFunc = this.editors["input"];
14526 }
14527 }else {
14528 console.warn("Editor Error - Cannot auto lookup editor for a custom formatter: ", column.definition.formatter);
14529 }
14530 }
14531 break;
14532 }
14533
14534 return editorFunc;
14535 }
14536
14537 getCurrentCell(){
14538 return this.currentCell ? this.currentCell.getComponent() : false;
14539 }
14540
14541 checkEditing(){
14542 return !!this.currentCell;
14543 }
14544
14545 cancelEditEvent(){
14546 if(this.currentCell){
14547 this.cancelEdit();
14548 return true;
14549 }
14550 return false;
14551 }
14552
14553
14554 clearEditor(cancel){
14555 var cell = this.currentCell,
14556 cellEl;
14557
14558 this.invalidEdit = false;
14559
14560 if(cell){
14561 this.currentCell = false;
14562
14563 cellEl = cell.getElement();
14564
14565 this.dispatch("edit-editor-clear", cell, cancel);
14566
14567 cellEl.classList.remove("tabulator-editing");
14568
14569 while(cellEl.firstChild) cellEl.removeChild(cellEl.firstChild);
14570
14571 cell.row.getElement().classList.remove("tabulator-editing");
14572
14573 cell.table.element.classList.remove("tabulator-editing");
14574 }
14575 }
14576
14577 cancelEdit(){
14578 if(this.currentCell){
14579 var cell = this.currentCell;
14580 var component = this.currentCell.getComponent();
14581
14582 this.clearEditor(true);
14583 cell.setValueActual(cell.getValue());
14584 cell.cellRendered();
14585
14586 if(cell.column.definition.editor == "textarea" || cell.column.definition.variableHeight){
14587 cell.row.normalizeHeight(true);
14588 }
14589
14590 if(cell.column.definition.cellEditCancelled){
14591 cell.column.definition.cellEditCancelled.call(this.table, component);
14592 }
14593
14594 this.dispatch("edit-cancelled", cell);
14595 this.dispatchExternal("cellEditCancelled", component);
14596 }
14597 }
14598
14599 //return a formatted value for a cell
14600 bindEditor(cell){
14601 if(cell.column.modules.edit){
14602 var self = this,
14603 element = cell.getElement(true);
14604
14605 this.updateCellClass(cell);
14606 element.setAttribute("tabindex", 0);
14607
14608 element.addEventListener("mousedown", function(e){
14609 if (e.button === 2) {
14610 e.preventDefault();
14611 }else {
14612 self.mouseClick = true;
14613 }
14614 });
14615
14616 if(this.options("editTriggerEvent") === "dblclick"){
14617 element.addEventListener("dblclick", function(e){
14618 if(!element.classList.contains("tabulator-editing")){
14619 element.focus({preventScroll: true});
14620 self.edit(cell, e, false);
14621 }
14622 });
14623 }
14624
14625
14626 if(this.options("editTriggerEvent") === "focus" || this.options("editTriggerEvent") === "click"){
14627 element.addEventListener("click", function(e){
14628 if(!element.classList.contains("tabulator-editing")){
14629 element.focus({preventScroll: true});
14630 self.edit(cell, e, false);
14631 }
14632 });
14633 }
14634
14635 if(this.options("editTriggerEvent") === "focus"){
14636 element.addEventListener("focus", function(e){
14637 if(!self.recursionBlock){
14638 self.edit(cell, e, false);
14639 }
14640 });
14641 }
14642 }
14643 }
14644
14645 focusCellNoEvent(cell, block){
14646 this.recursionBlock = true;
14647
14648 if(!(block && this.table.browser === "ie")){
14649 cell.getElement().focus({preventScroll: true});
14650 }
14651
14652 this.recursionBlock = false;
14653 }
14654
14655 editCell(cell, forceEdit){
14656 this.focusCellNoEvent(cell);
14657 this.edit(cell, false, forceEdit);
14658 }
14659
14660 focusScrollAdjust(cell){
14661 if(this.table.rowManager.getRenderMode() == "virtual"){
14662 var topEdge = this.table.rowManager.element.scrollTop,
14663 bottomEdge = this.table.rowManager.element.clientHeight + this.table.rowManager.element.scrollTop,
14664 rowEl = cell.row.getElement();
14665
14666 if(rowEl.offsetTop < topEdge){
14667 this.table.rowManager.element.scrollTop -= (topEdge - rowEl.offsetTop);
14668 }else {
14669 if(rowEl.offsetTop + rowEl.offsetHeight > bottomEdge){
14670 this.table.rowManager.element.scrollTop += (rowEl.offsetTop + rowEl.offsetHeight - bottomEdge);
14671 }
14672 }
14673
14674 var leftEdge = this.table.rowManager.element.scrollLeft,
14675 rightEdge = this.table.rowManager.element.clientWidth + this.table.rowManager.element.scrollLeft,
14676 cellEl = cell.getElement();
14677
14678 if(this.table.modExists("frozenColumns")){
14679 leftEdge += parseInt(this.table.modules.frozenColumns.leftMargin || 0);
14680 rightEdge -= parseInt(this.table.modules.frozenColumns.rightMargin || 0);
14681 }
14682
14683 if(this.table.options.renderHorizontal === "virtual"){
14684 leftEdge -= parseInt(this.table.columnManager.renderer.vDomPadLeft);
14685 rightEdge -= parseInt(this.table.columnManager.renderer.vDomPadLeft);
14686 }
14687
14688 if(cellEl.offsetLeft < leftEdge){
14689 this.table.rowManager.element.scrollLeft -= (leftEdge - cellEl.offsetLeft);
14690 }else {
14691 if(cellEl.offsetLeft + cellEl.offsetWidth > rightEdge){
14692 this.table.rowManager.element.scrollLeft += (cellEl.offsetLeft + cellEl.offsetWidth - rightEdge);
14693 }
14694 }
14695 }
14696 }
14697
14698 allowEdit(cell) {
14699 var check = cell.column.modules.edit ? true : false;
14700
14701 if(cell.column.modules.edit){
14702 switch(typeof cell.column.modules.edit.check){
14703 case "function":
14704 if(cell.row.initialized){
14705 check = cell.column.modules.edit.check(cell.getComponent());
14706 }
14707 break;
14708
14709 case "string":
14710 check = !!cell.row.data[cell.column.modules.edit.check];
14711 break;
14712
14713 case "boolean":
14714 check = cell.column.modules.edit.check;
14715 break;
14716 }
14717 }
14718
14719 return check;
14720 }
14721
14722 edit(cell, e, forceEdit){
14723 var self = this,
14724 allowEdit = true,
14725 rendered = function(){},
14726 element = cell.getElement(),
14727 editFinished = false,
14728 cellEditor, component, params;
14729
14730 //prevent editing if another cell is refusing to leave focus (eg. validation fail)
14731
14732 if(this.currentCell){
14733 if(!this.invalidEdit && this.currentCell !== cell){
14734 this.cancelEdit();
14735 }
14736 return;
14737 }
14738
14739 //handle successful value change
14740 function success(value){
14741 if(self.currentCell === cell && !editFinished){
14742 var valid = self.chain("edit-success", [cell, value], true, true);
14743
14744 if(valid === true || self.table.options.validationMode === "highlight"){
14745
14746 editFinished = true;
14747
14748 self.clearEditor();
14749
14750 if(!cell.modules.edit){
14751 cell.modules.edit = {};
14752 }
14753
14754 cell.modules.edit.edited = true;
14755
14756 if(self.editedCells.indexOf(cell) == -1){
14757 self.editedCells.push(cell);
14758 }
14759
14760 value = self.transformEmptyValues(value, cell);
14761
14762 cell.setValue(value, true);
14763
14764 return valid === true;
14765 }else {
14766 editFinished = true;
14767 self.invalidEdit = true;
14768 self.focusCellNoEvent(cell, true);
14769 rendered();
14770
14771 setTimeout(() => {
14772 editFinished = false;
14773 }, 10);
14774 return false;
14775 }
14776 }
14777 }
14778
14779 //handle aborted edit
14780 function cancel(){
14781 // editFinished = true;
14782
14783 if(self.currentCell === cell && !editFinished){
14784 self.cancelEdit();
14785 }
14786 }
14787
14788 function onRendered(callback){
14789 rendered = callback;
14790 }
14791
14792 if(!cell.column.modules.edit.blocked){
14793 if(e){
14794 e.stopPropagation();
14795 }
14796
14797 allowEdit = this.allowEdit(cell);
14798
14799 if(allowEdit || forceEdit){
14800 self.cancelEdit();
14801
14802 self.currentCell = cell;
14803
14804 this.focusScrollAdjust(cell);
14805
14806 component = cell.getComponent();
14807
14808 if(this.mouseClick){
14809 this.mouseClick = false;
14810
14811 if(cell.column.definition.cellClick){
14812 cell.column.definition.cellClick.call(this.table, e, component);
14813 }
14814 }
14815
14816 if(cell.column.definition.cellEditing){
14817 cell.column.definition.cellEditing.call(this.table, component);
14818 }
14819
14820 this.dispatch("cell-editing", cell);
14821 this.dispatchExternal("cellEditing", component);
14822
14823 params = typeof cell.column.modules.edit.params === "function" ? cell.column.modules.edit.params(component) : cell.column.modules.edit.params;
14824
14825 cellEditor = cell.column.modules.edit.editor.call(self, component, onRendered, success, cancel, params);
14826
14827 //if editor returned, add to DOM, if false, abort edit
14828 if(this.currentCell && cellEditor !== false){
14829 if(cellEditor instanceof Node){
14830 element.classList.add("tabulator-editing");
14831 cell.row.getElement().classList.add("tabulator-editing");
14832 cell.table.element.classList.add("tabulator-editing");
14833 while(element.firstChild) element.removeChild(element.firstChild);
14834 element.appendChild(cellEditor);
14835
14836 //trigger onRendered Callback
14837 rendered();
14838
14839 //prevent editing from triggering rowClick event
14840 var children = element.children;
14841
14842 for (var i = 0; i < children.length; i++) {
14843 children[i].addEventListener("click", function(e){
14844 e.stopPropagation();
14845 });
14846 }
14847 }else {
14848 console.warn("Edit Error - Editor should return an instance of Node, the editor returned:", cellEditor);
14849 this.blur(element);
14850 return false;
14851 }
14852 }else {
14853 this.blur(element);
14854 return false;
14855 }
14856
14857 return true;
14858 }else {
14859 this.mouseClick = false;
14860 this.blur(element);
14861 return false;
14862 }
14863 }else {
14864 this.mouseClick = false;
14865 this.blur(element);
14866 return false;
14867 }
14868 }
14869
14870 emptyValueCheck(value){
14871 return value === "" || value === null || typeof value === "undefined";
14872 }
14873
14874 transformEmptyValues(value, cell){
14875 var mod = cell.column.modules.edit,
14876 convert = mod.convertEmptyValues || this.convertEmptyValues,
14877 checkFunc;
14878
14879 if(convert){
14880 checkFunc = mod.editorEmptyValueFunc || this.options("editorEmptyValueFunc");
14881
14882 if(checkFunc && checkFunc(value)){
14883 value = mod.convertEmptyValues ? mod.editorEmptyValue : this.options("editorEmptyValue");
14884 }
14885 }
14886
14887 return value;
14888 }
14889
14890 blur(element){
14891 if(!this.confirm("edit-blur", [element]) ){
14892 element.blur();
14893 }
14894 }
14895
14896 getEditedCells(){
14897 var output = [];
14898
14899 this.editedCells.forEach((cell) => {
14900 output.push(cell.getComponent());
14901 });
14902
14903 return output;
14904 }
14905
14906 clearEdited(cell){
14907 var editIndex;
14908
14909 if(cell.modules.edit && cell.modules.edit.edited){
14910 cell.modules.edit.edited = false;
14911
14912 this.dispatch("edit-edited-clear", cell);
14913 }
14914
14915 editIndex = this.editedCells.indexOf(cell);
14916
14917 if(editIndex > -1){
14918 this.editedCells.splice(editIndex, 1);
14919 }
14920 }
14921 }
14922
14923 class ExportRow{
14924 constructor(type, columns, component, indent){
14925 this.type = type;
14926 this.columns = columns;
14927 this.component = component || false;
14928 this.indent = indent || 0;
14929 }
14930 }
14931
14932 class ExportColumn{
14933 constructor(value, component, width, height, depth){
14934 this.value = value;
14935 this.component = component || false;
14936 this.width = width;
14937 this.height = height;
14938 this.depth = depth;
14939 }
14940 }
14941
14942 var columnLookups$1 = {
14943
14944 };
14945
14946 var rowLookups$1 = {
14947 visible:function(){
14948 return this.rowManager.getVisibleRows(false, true);
14949 },
14950 all:function(){
14951 return this.rowManager.rows;
14952 },
14953 selected:function(){
14954 return this.modules.selectRow.selectedRows;
14955 },
14956 active:function(){
14957 if(this.options.pagination){
14958 return this.rowManager.getDisplayRows(this.rowManager.displayRows.length - 2);
14959 }else {
14960 return this.rowManager.getDisplayRows();
14961 }
14962 },
14963 };
14964
14965 class Export extends Module{
14966
14967 static moduleName = "export";
14968
14969 static columnLookups = columnLookups$1;
14970 static rowLookups = rowLookups$1;
14971
14972 constructor(table){
14973 super(table);
14974
14975 this.config = {};
14976 this.cloneTableStyle = true;
14977 this.colVisProp = "";
14978 this.colVisPropAttach = "";
14979
14980 this.registerTableOption("htmlOutputConfig", false); //html output config
14981
14982 this.registerColumnOption("htmlOutput");
14983 this.registerColumnOption("titleHtmlOutput");
14984 }
14985
14986 initialize(){
14987 this.registerTableFunction("getHtml", this.getHtml.bind(this));
14988 }
14989
14990 ///////////////////////////////////
14991 ///////// Internal Logic //////////
14992 ///////////////////////////////////
14993
14994 generateExportList(config, style, range, colVisProp){
14995 var headers, body, columns, colLookup;
14996
14997 this.cloneTableStyle = style;
14998 this.config = config || {};
14999 this.colVisProp = colVisProp;
15000 this.colVisPropAttach = this.colVisProp.charAt(0).toUpperCase() + this.colVisProp.slice(1);
15001
15002 colLookup = Export.columnLookups[range];
15003
15004 if(colLookup){
15005 columns = colLookup.call(this.table);
15006 columns = columns.filter(col => this.columnVisCheck(col));
15007 }
15008
15009 headers = this.config.columnHeaders !== false ? this.headersToExportRows(this.generateColumnGroupHeaders(columns)) : [];
15010
15011 if(columns){
15012 columns = columns.map(col => col.getComponent());
15013 }
15014
15015 body = this.bodyToExportRows(this.rowLookup(range), columns);
15016
15017 return headers.concat(body);
15018 }
15019
15020 generateTable(config, style, range, colVisProp){
15021 var list = this.generateExportList(config, style, range, colVisProp);
15022
15023 return this.generateTableElement(list);
15024 }
15025
15026 rowLookup(range){
15027 var rows = [],
15028 rowLookup;
15029
15030 if(typeof range == "function"){
15031 range.call(this.table).forEach((row) =>{
15032 row = this.table.rowManager.findRow(row);
15033
15034 if(row){
15035 rows.push(row);
15036 }
15037 });
15038 }else {
15039 rowLookup = Export.rowLookups[range] || Export.rowLookups["active"];
15040
15041 rows = rowLookup.call(this.table);
15042 }
15043
15044 return Object.assign([], rows);
15045 }
15046
15047 generateColumnGroupHeaders(columns){
15048 var output = [];
15049
15050 if (!columns) {
15051 columns = this.config.columnGroups !== false ? this.table.columnManager.columns : this.table.columnManager.columnsByIndex;
15052 }
15053
15054 columns.forEach((column) => {
15055 var colData = this.processColumnGroup(column);
15056
15057 if(colData){
15058 output.push(colData);
15059 }
15060 });
15061
15062
15063
15064 return output;
15065 }
15066
15067 processColumnGroup(column){
15068 var subGroups = column.columns,
15069 maxDepth = 0,
15070 title = column.definition["title" + (this.colVisPropAttach)] || column.definition.title;
15071
15072 var groupData = {
15073 title:title,
15074 column:column,
15075 depth:1,
15076 };
15077
15078 if(subGroups.length){
15079 groupData.subGroups = [];
15080 groupData.width = 0;
15081
15082 subGroups.forEach((subGroup) => {
15083 var subGroupData = this.processColumnGroup(subGroup);
15084
15085 if(subGroupData){
15086 groupData.width += subGroupData.width;
15087 groupData.subGroups.push(subGroupData);
15088
15089 if(subGroupData.depth > maxDepth){
15090 maxDepth = subGroupData.depth;
15091 }
15092 }
15093 });
15094
15095 groupData.depth += maxDepth;
15096
15097 if(!groupData.width){
15098 return false;
15099 }
15100 }else {
15101 if(this.columnVisCheck(column)){
15102 groupData.width = 1;
15103 }else {
15104 return false;
15105 }
15106 }
15107
15108 return groupData;
15109 }
15110
15111 columnVisCheck(column){
15112 var visProp = column.definition[this.colVisProp];
15113
15114 if(this.config.rowHeaders === false && column.isRowHeader){
15115 return false;
15116 }
15117
15118 if(typeof visProp === "function"){
15119 visProp = visProp.call(this.table, column.getComponent());
15120 }
15121
15122 if(visProp === false || visProp === true){
15123 return visProp;
15124 }
15125
15126 return column.visible && column.field;
15127 }
15128
15129 headersToExportRows(columns){
15130 var headers = [],
15131 headerDepth = 0,
15132 exportRows = [];
15133
15134 function parseColumnGroup(column, level){
15135
15136 var depth = headerDepth - level;
15137
15138 if(typeof headers[level] === "undefined"){
15139 headers[level] = [];
15140 }
15141
15142 column.height = column.subGroups ? 1 : (depth - column.depth) + 1;
15143
15144 headers[level].push(column);
15145
15146 if(column.height > 1){
15147 for(let i = 1; i < column.height; i ++){
15148
15149 if(typeof headers[level + i] === "undefined"){
15150 headers[level + i] = [];
15151 }
15152
15153 headers[level + i].push(false);
15154 }
15155 }
15156
15157 if(column.width > 1){
15158 for(let i = 1; i < column.width; i ++){
15159 headers[level].push(false);
15160 }
15161 }
15162
15163 if(column.subGroups){
15164 column.subGroups.forEach(function(subGroup){
15165 parseColumnGroup(subGroup, level+1);
15166 });
15167 }
15168 }
15169
15170 //calculate maximum header depth
15171 columns.forEach(function(column){
15172 if(column.depth > headerDepth){
15173 headerDepth = column.depth;
15174 }
15175 });
15176
15177 columns.forEach(function(column){
15178 parseColumnGroup(column,0);
15179 });
15180
15181 headers.forEach((header) => {
15182 var columns = [];
15183
15184 header.forEach((col) => {
15185 if(col){
15186 let title = typeof col.title === "undefined" ? "" : col.title;
15187 columns.push(new ExportColumn(title, col.column.getComponent(), col.width, col.height, col.depth));
15188 }else {
15189 columns.push(null);
15190 }
15191 });
15192
15193 exportRows.push(new ExportRow("header", columns));
15194 });
15195
15196 return exportRows;
15197 }
15198
15199 bodyToExportRows(rows, columns = []){
15200 var exportRows = [];
15201
15202 if (columns.length === 0) {
15203 this.table.columnManager.columnsByIndex.forEach((column) => {
15204 if (this.columnVisCheck(column)) {
15205 columns.push(column.getComponent());
15206 }
15207 });
15208 }
15209
15210 if(this.config.columnCalcs !== false && this.table.modExists("columnCalcs")){
15211 if(this.table.modules.columnCalcs.topInitialized){
15212 rows.unshift(this.table.modules.columnCalcs.topRow);
15213 }
15214
15215 if(this.table.modules.columnCalcs.botInitialized){
15216 rows.push(this.table.modules.columnCalcs.botRow);
15217 }
15218 }
15219
15220 rows = rows.filter((row) => {
15221 switch(row.type){
15222 case "group":
15223 return this.config.rowGroups !== false;
15224
15225 case "calc":
15226 return this.config.columnCalcs !== false;
15227
15228 case "row":
15229 return !(this.table.options.dataTree && this.config.dataTree === false && row.modules.dataTree.parent);
15230 }
15231
15232 return true;
15233 });
15234
15235 rows.forEach((row, i) => {
15236 var rowData = row.getData(this.colVisProp);
15237 var exportCols = [];
15238 var indent = 0;
15239
15240 switch(row.type){
15241 case "group":
15242 indent = row.level;
15243 exportCols.push(new ExportColumn(row.key, row.getComponent(), columns.length, 1));
15244 break;
15245
15246 case "calc" :
15247 case "row" :
15248 columns.forEach((col) => {
15249 exportCols.push(new ExportColumn(col._column.getFieldValue(rowData), col, 1, 1));
15250 });
15251
15252 if(this.table.options.dataTree && this.config.dataTree !== false){
15253 indent = row.modules.dataTree.index;
15254 }
15255 break;
15256 }
15257
15258 exportRows.push(new ExportRow(row.type, exportCols, row.getComponent(), indent));
15259 });
15260
15261 return exportRows;
15262 }
15263
15264 generateTableElement(list){
15265 var table = document.createElement("table"),
15266 headerEl = document.createElement("thead"),
15267 bodyEl = document.createElement("tbody"),
15268 styles = this.lookupTableStyles(),
15269 rowFormatter = this.table.options["rowFormatter" + (this.colVisPropAttach)],
15270 setup = {};
15271
15272 setup.rowFormatter = rowFormatter !== null ? rowFormatter : this.table.options.rowFormatter;
15273
15274 if(this.table.options.dataTree &&this.config.dataTree !== false && this.table.modExists("columnCalcs")){
15275 setup.treeElementField = this.table.modules.dataTree.elementField;
15276 }
15277
15278 //assign group header formatter
15279 setup.groupHeader = this.table.options["groupHeader" + (this.colVisPropAttach)];
15280
15281 if(setup.groupHeader && !Array.isArray(setup.groupHeader)){
15282 setup.groupHeader = [setup.groupHeader];
15283 }
15284
15285 table.classList.add("tabulator-print-table");
15286
15287 this.mapElementStyles(this.table.columnManager.getHeadersElement(), headerEl, ["border-top", "border-left", "border-right", "border-bottom", "background-color", "color", "font-weight", "font-family", "font-size"]);
15288
15289 if(list.length > 1000){
15290 console.warn("It may take a long time to render an HTML table with more than 1000 rows");
15291 }
15292
15293 list.forEach((row, i) => {
15294 let rowEl;
15295
15296 switch(row.type){
15297 case "header":
15298 headerEl.appendChild(this.generateHeaderElement(row, setup, styles));
15299 break;
15300
15301 case "group":
15302 bodyEl.appendChild(this.generateGroupElement(row, setup, styles));
15303 break;
15304
15305 case "calc":
15306 bodyEl.appendChild(this.generateCalcElement(row, setup, styles));
15307 break;
15308
15309 case "row":
15310 rowEl = this.generateRowElement(row, setup, styles);
15311
15312 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"]);
15313 bodyEl.appendChild(rowEl);
15314 break;
15315 }
15316 });
15317
15318 if(headerEl.innerHTML){
15319 table.appendChild(headerEl);
15320 }
15321
15322 table.appendChild(bodyEl);
15323
15324
15325 this.mapElementStyles(this.table.element, table, ["border-top", "border-left", "border-right", "border-bottom"]);
15326 return table;
15327 }
15328
15329 lookupTableStyles(){
15330 var styles = {};
15331
15332 //lookup row styles
15333 if(this.cloneTableStyle && window.getComputedStyle){
15334 styles.oddRow = this.table.element.querySelector(".tabulator-row-odd:not(.tabulator-group):not(.tabulator-calcs)");
15335 styles.evenRow = this.table.element.querySelector(".tabulator-row-even:not(.tabulator-group):not(.tabulator-calcs)");
15336 styles.calcRow = this.table.element.querySelector(".tabulator-row.tabulator-calcs");
15337 styles.firstRow = this.table.element.querySelector(".tabulator-row:not(.tabulator-group):not(.tabulator-calcs)");
15338 styles.firstGroup = this.table.element.getElementsByClassName("tabulator-group")[0];
15339
15340 if(styles.firstRow){
15341 styles.styleCells = styles.firstRow.getElementsByClassName("tabulator-cell");
15342 styles.styleRowHeader = styles.firstRow.getElementsByClassName("tabulator-row-header")[0];
15343 styles.firstCell = styles.styleCells[0];
15344 styles.lastCell = styles.styleCells[styles.styleCells.length - 1];
15345 }
15346 }
15347
15348 return styles;
15349 }
15350
15351 generateHeaderElement(row, setup, styles){
15352 var rowEl = document.createElement("tr");
15353
15354 row.columns.forEach((column) => {
15355 if(column){
15356 var cellEl = document.createElement("th");
15357 var classNames = column.component._column.definition.cssClass ? column.component._column.definition.cssClass.split(" ") : [];
15358
15359 cellEl.colSpan = column.width;
15360 cellEl.rowSpan = column.height;
15361
15362 cellEl.innerHTML = column.value;
15363
15364 if(this.cloneTableStyle){
15365 cellEl.style.boxSizing = "border-box";
15366 }
15367
15368 classNames.forEach(function(className) {
15369 cellEl.classList.add(className);
15370 });
15371
15372 this.mapElementStyles(column.component.getElement(), cellEl, ["text-align", "border-left", "border-right", "background-color", "color", "font-weight", "font-family", "font-size"]);
15373 this.mapElementStyles(column.component._column.contentElement, cellEl, ["padding-top", "padding-left", "padding-right", "padding-bottom"]);
15374
15375 if(column.component._column.visible){
15376 this.mapElementStyles(column.component.getElement(), cellEl, ["width"]);
15377 }else {
15378 if(column.component._column.definition.width){
15379 cellEl.style.width = column.component._column.definition.width + "px";
15380 }
15381 }
15382
15383 if(column.component._column.parent && column.component._column.parent.isGroup){
15384 this.mapElementStyles(column.component._column.parent.groupElement, cellEl, ["border-top"]);
15385 }else {
15386 this.mapElementStyles(column.component.getElement(), cellEl, ["border-top"]);
15387 }
15388
15389 if(column.component._column.isGroup){
15390 this.mapElementStyles(column.component.getElement(), cellEl, ["border-bottom"]);
15391 }else {
15392 this.mapElementStyles(this.table.columnManager.getElement(), cellEl, ["border-bottom"]);
15393 }
15394
15395 rowEl.appendChild(cellEl);
15396 }
15397 });
15398
15399 return rowEl;
15400 }
15401
15402 generateGroupElement(row, setup, styles){
15403
15404 var rowEl = document.createElement("tr"),
15405 cellEl = document.createElement("td"),
15406 group = row.columns[0];
15407
15408 rowEl.classList.add("tabulator-print-table-row");
15409
15410 if(setup.groupHeader && setup.groupHeader[row.indent]){
15411 group.value = setup.groupHeader[row.indent](group.value, row.component._group.getRowCount(), row.component._group.getData(), row.component);
15412 }else {
15413 if(setup.groupHeader !== false){
15414 group.value = row.component._group.generator(group.value, row.component._group.getRowCount(), row.component._group.getData(), row.component);
15415 }
15416 }
15417
15418 cellEl.colSpan = group.width;
15419 cellEl.innerHTML = group.value;
15420
15421 rowEl.classList.add("tabulator-print-table-group");
15422 rowEl.classList.add("tabulator-group-level-" + row.indent);
15423
15424 if(group.component.isVisible()){
15425 rowEl.classList.add("tabulator-group-visible");
15426 }
15427
15428 this.mapElementStyles(styles.firstGroup, rowEl, ["border-top", "border-left", "border-right", "border-bottom", "color", "font-weight", "font-family", "font-size", "background-color"]);
15429 this.mapElementStyles(styles.firstGroup, cellEl, ["padding-top", "padding-left", "padding-right", "padding-bottom"]);
15430
15431 rowEl.appendChild(cellEl);
15432
15433 return rowEl;
15434 }
15435
15436 generateCalcElement(row, setup, styles){
15437 var rowEl = this.generateRowElement(row, setup, styles);
15438
15439 rowEl.classList.add("tabulator-print-table-calcs");
15440 this.mapElementStyles(styles.calcRow, rowEl, ["border-top", "border-left", "border-right", "border-bottom", "color", "font-weight", "font-family", "font-size", "background-color"]);
15441
15442 return rowEl;
15443 }
15444
15445 generateRowElement(row, setup, styles){
15446 var rowEl = document.createElement("tr");
15447
15448 rowEl.classList.add("tabulator-print-table-row");
15449
15450 row.columns.forEach((col, i) => {
15451 if(col){
15452 var cellEl = document.createElement("td"),
15453 column = col.component._column,
15454 table = this.table,
15455 index = table.columnManager.findColumnIndex(column),
15456 value = col.value,
15457 cellStyle, styleProps;
15458
15459 var cellWrapper = {
15460 modules:{},
15461 getValue:function(){
15462 return value;
15463 },
15464 getField:function(){
15465 return column.definition.field;
15466 },
15467 getElement:function(){
15468 return cellEl;
15469 },
15470 getType:function(){
15471 return "cell";
15472 },
15473 getColumn:function(){
15474 return column.getComponent();
15475 },
15476 getData:function(){
15477 return row.component.getData();
15478 },
15479 getRow:function(){
15480 return row.component;
15481 },
15482 getTable:function(){
15483 return table;
15484 },
15485 getComponent:function(){
15486 return cellWrapper;
15487 },
15488 column:column,
15489 };
15490
15491 var classNames = column.definition.cssClass ? column.definition.cssClass.split(" ") : [];
15492
15493 classNames.forEach(function(className) {
15494 cellEl.classList.add(className);
15495 });
15496
15497 if(this.table.modExists("format") && this.config.formatCells !== false){
15498 value = this.table.modules.format.formatExportValue(cellWrapper, this.colVisProp);
15499 }else {
15500 switch(typeof value){
15501 case "object":
15502 value = value !== null ? JSON.stringify(value) : "";
15503 break;
15504
15505 case "undefined":
15506 value = "";
15507 break;
15508 }
15509 }
15510
15511 if(value instanceof Node){
15512 cellEl.appendChild(value);
15513 }else {
15514 cellEl.innerHTML = value;
15515 }
15516
15517 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"];
15518
15519 if(column.isRowHeader){
15520 cellStyle = styles.styleRowHeader;
15521 styleProps.push("background-color");
15522 }else {
15523 cellStyle = styles.styleCells && styles.styleCells[index] ? styles.styleCells[index] : styles.firstCell;
15524 }
15525
15526 if(cellStyle){
15527 this.mapElementStyles(cellStyle, cellEl, styleProps);
15528
15529 if(column.definition.align){
15530 cellEl.style.textAlign = column.definition.align;
15531 }
15532 }
15533
15534 if(this.table.options.dataTree && this.config.dataTree !== false){
15535 if((setup.treeElementField && setup.treeElementField == column.field) || (!setup.treeElementField && i == 0)){
15536 if(row.component._row.modules.dataTree.controlEl){
15537 cellEl.insertBefore(row.component._row.modules.dataTree.controlEl.cloneNode(true), cellEl.firstChild);
15538 }
15539 if(row.component._row.modules.dataTree.branchEl){
15540 cellEl.insertBefore(row.component._row.modules.dataTree.branchEl.cloneNode(true), cellEl.firstChild);
15541 }
15542 }
15543 }
15544
15545 rowEl.appendChild(cellEl);
15546
15547 if(cellWrapper.modules.format && cellWrapper.modules.format.renderedCallback){
15548 cellWrapper.modules.format.renderedCallback();
15549 }
15550 }
15551 });
15552
15553 if(setup.rowFormatter && row.type === "row" && this.config.formatCells !== false){
15554 let formatComponent = Object.assign(row.component);
15555
15556 formatComponent.getElement = function(){return rowEl;};
15557
15558 setup.rowFormatter(row.component);
15559 }
15560
15561 return rowEl;
15562 }
15563
15564 generateHTMLTable(list){
15565 var holder = document.createElement("div");
15566
15567 holder.appendChild(this.generateTableElement(list));
15568
15569 return holder.innerHTML;
15570 }
15571
15572 getHtml(visible, style, config, colVisProp){
15573 var list = this.generateExportList(config || this.table.options.htmlOutputConfig, style, visible, colVisProp || "htmlOutput");
15574
15575 return this.generateHTMLTable(list);
15576 }
15577
15578 mapElementStyles(from, to, props){
15579 if(this.cloneTableStyle && from && to){
15580
15581 var lookup = {
15582 "background-color" : "backgroundColor",
15583 "color" : "fontColor",
15584 "width" : "width",
15585 "font-weight" : "fontWeight",
15586 "font-family" : "fontFamily",
15587 "font-size" : "fontSize",
15588 "text-align" : "textAlign",
15589 "border-top" : "borderTop",
15590 "border-left" : "borderLeft",
15591 "border-right" : "borderRight",
15592 "border-bottom" : "borderBottom",
15593 "padding-top" : "paddingTop",
15594 "padding-left" : "paddingLeft",
15595 "padding-right" : "paddingRight",
15596 "padding-bottom" : "paddingBottom",
15597 };
15598
15599 if(window.getComputedStyle){
15600 var fromStyle = window.getComputedStyle(from);
15601
15602 props.forEach(function(prop){
15603 if(!to.style[lookup[prop]]){
15604 to.style[lookup[prop]] = fromStyle.getPropertyValue(prop);
15605 }
15606 });
15607 }
15608 }
15609 }
15610 }
15611
15612 var defaultFilters = {
15613
15614 //equal to
15615 "=":function(filterVal, rowVal, rowData, filterParams){
15616 return rowVal == filterVal ? true : false;
15617 },
15618
15619 //less than
15620 "<":function(filterVal, rowVal, rowData, filterParams){
15621 return rowVal < filterVal ? true : false;
15622 },
15623
15624 //less than or equal to
15625 "<=":function(filterVal, rowVal, rowData, filterParams){
15626 return rowVal <= filterVal ? true : false;
15627 },
15628
15629 //greater than
15630 ">":function(filterVal, rowVal, rowData, filterParams){
15631 return rowVal > filterVal ? true : false;
15632 },
15633
15634 //greater than or equal to
15635 ">=":function(filterVal, rowVal, rowData, filterParams){
15636 return rowVal >= filterVal ? true : false;
15637 },
15638
15639 //not equal to
15640 "!=":function(filterVal, rowVal, rowData, filterParams){
15641 return rowVal != filterVal ? true : false;
15642 },
15643
15644 "regex":function(filterVal, rowVal, rowData, filterParams){
15645
15646 if(typeof filterVal == "string"){
15647 filterVal = new RegExp(filterVal);
15648 }
15649
15650 return filterVal.test(rowVal);
15651 },
15652
15653 //contains the string
15654 "like":function(filterVal, rowVal, rowData, filterParams){
15655 if(filterVal === null || typeof filterVal === "undefined"){
15656 return rowVal === filterVal ? true : false;
15657 }else {
15658 if(typeof rowVal !== 'undefined' && rowVal !== null){
15659 return String(rowVal).toLowerCase().indexOf(filterVal.toLowerCase()) > -1;
15660 }
15661 else {
15662 return false;
15663 }
15664 }
15665 },
15666
15667 //contains the keywords
15668 "keywords":function(filterVal, rowVal, rowData, filterParams){
15669 var keywords = filterVal.toLowerCase().split(typeof filterParams.separator === "undefined" ? " " : filterParams.separator),
15670 value = String(rowVal === null || typeof rowVal === "undefined" ? "" : rowVal).toLowerCase(),
15671 matches = [];
15672
15673 keywords.forEach((keyword) =>{
15674 if(value.includes(keyword)){
15675 matches.push(true);
15676 }
15677 });
15678
15679 return filterParams.matchAll ? matches.length === keywords.length : !!matches.length;
15680 },
15681
15682 //starts with the string
15683 "starts":function(filterVal, rowVal, rowData, filterParams){
15684 if(filterVal === null || typeof filterVal === "undefined"){
15685 return rowVal === filterVal ? true : false;
15686 }else {
15687 if(typeof rowVal !== 'undefined' && rowVal !== null){
15688 return String(rowVal).toLowerCase().startsWith(filterVal.toLowerCase());
15689 }
15690 else {
15691 return false;
15692 }
15693 }
15694 },
15695
15696 //ends with the string
15697 "ends":function(filterVal, rowVal, rowData, filterParams){
15698 if(filterVal === null || typeof filterVal === "undefined"){
15699 return rowVal === filterVal ? true : false;
15700 }else {
15701 if(typeof rowVal !== 'undefined' && rowVal !== null){
15702 return String(rowVal).toLowerCase().endsWith(filterVal.toLowerCase());
15703 }
15704 else {
15705 return false;
15706 }
15707 }
15708 },
15709
15710 //in array
15711 "in":function(filterVal, rowVal, rowData, filterParams){
15712 if(Array.isArray(filterVal)){
15713 return filterVal.length ? filterVal.indexOf(rowVal) > -1 : true;
15714 }else {
15715 console.warn("Filter Error - filter value is not an array:", filterVal);
15716 return false;
15717 }
15718 },
15719 };
15720
15721 class Filter extends Module{
15722
15723 static moduleName = "filter";
15724
15725 //load defaults
15726 static filters = defaultFilters;
15727
15728 constructor(table){
15729 super(table);
15730
15731 this.filterList = []; //hold filter list
15732 this.headerFilters = {}; //hold column filters
15733 this.headerFilterColumns = []; //hold columns that use header filters
15734
15735 this.prevHeaderFilterChangeCheck = "";
15736 this.prevHeaderFilterChangeCheck = "{}";
15737
15738 this.changed = false; //has filtering changed since last render
15739 this.tableInitialized = false;
15740
15741 this.registerTableOption("filterMode", "local"); //local or remote filtering
15742
15743 this.registerTableOption("initialFilter", false); //initial filtering criteria
15744 this.registerTableOption("initialHeaderFilter", false); //initial header filtering criteria
15745 this.registerTableOption("headerFilterLiveFilterDelay", 300); //delay before updating column after user types in header filter
15746 this.registerTableOption("placeholderHeaderFilter", false); //placeholder when header filter is empty
15747
15748 this.registerColumnOption("headerFilter");
15749 this.registerColumnOption("headerFilterPlaceholder");
15750 this.registerColumnOption("headerFilterParams");
15751 this.registerColumnOption("headerFilterEmptyCheck");
15752 this.registerColumnOption("headerFilterFunc");
15753 this.registerColumnOption("headerFilterFuncParams");
15754 this.registerColumnOption("headerFilterLiveFilter");
15755
15756 this.registerTableFunction("searchRows", this.searchRows.bind(this));
15757 this.registerTableFunction("searchData", this.searchData.bind(this));
15758
15759 this.registerTableFunction("setFilter", this.userSetFilter.bind(this));
15760 this.registerTableFunction("refreshFilter", this.userRefreshFilter.bind(this));
15761 this.registerTableFunction("addFilter", this.userAddFilter.bind(this));
15762 this.registerTableFunction("getFilters", this.getFilters.bind(this));
15763 this.registerTableFunction("setHeaderFilterFocus", this.userSetHeaderFilterFocus.bind(this));
15764 this.registerTableFunction("getHeaderFilterValue", this.userGetHeaderFilterValue.bind(this));
15765 this.registerTableFunction("setHeaderFilterValue", this.userSetHeaderFilterValue.bind(this));
15766 this.registerTableFunction("getHeaderFilters", this.getHeaderFilters.bind(this));
15767 this.registerTableFunction("removeFilter", this.userRemoveFilter.bind(this));
15768 this.registerTableFunction("clearFilter", this.userClearFilter.bind(this));
15769 this.registerTableFunction("clearHeaderFilter", this.userClearHeaderFilter.bind(this));
15770
15771 this.registerComponentFunction("column", "headerFilterFocus", this.setHeaderFilterFocus.bind(this));
15772 this.registerComponentFunction("column", "reloadHeaderFilter", this.reloadHeaderFilter.bind(this));
15773 this.registerComponentFunction("column", "getHeaderFilterValue", this.getHeaderFilterValue.bind(this));
15774 this.registerComponentFunction("column", "setHeaderFilterValue", this.setHeaderFilterValue.bind(this));
15775 }
15776
15777 initialize(){
15778 this.subscribe("column-init", this.initializeColumnHeaderFilter.bind(this));
15779 this.subscribe("column-width-fit-before", this.hideHeaderFilterElements.bind(this));
15780 this.subscribe("column-width-fit-after", this.showHeaderFilterElements.bind(this));
15781 this.subscribe("table-built", this.tableBuilt.bind(this));
15782 this.subscribe("placeholder", this.generatePlaceholder.bind(this));
15783
15784 if(this.table.options.filterMode === "remote"){
15785 this.subscribe("data-params", this.remoteFilterParams.bind(this));
15786 }
15787
15788 this.registerDataHandler(this.filter.bind(this), 10);
15789 }
15790
15791 tableBuilt(){
15792 if(this.table.options.initialFilter){
15793 this.setFilter(this.table.options.initialFilter);
15794 }
15795
15796 if(this.table.options.initialHeaderFilter){
15797 this.table.options.initialHeaderFilter.forEach((item) => {
15798
15799 var column = this.table.columnManager.findColumn(item.field);
15800
15801 if(column){
15802 this.setHeaderFilterValue(column, item.value);
15803 }else {
15804 console.warn("Column Filter Error - No matching column found:", item.field);
15805 return false;
15806 }
15807 });
15808 }
15809
15810 this.tableInitialized = true;
15811 }
15812
15813 remoteFilterParams(data, config, silent, params){
15814 params.filter = this.getFilters(true, true);
15815 return params;
15816 }
15817
15818 generatePlaceholder(text){
15819 if(this.table.options.placeholderHeaderFilter && Object.keys(this.headerFilters).length){
15820 return this.table.options.placeholderHeaderFilter;
15821 }
15822 }
15823
15824 ///////////////////////////////////
15825 ///////// Table Functions /////////
15826 ///////////////////////////////////
15827
15828 //set standard filters
15829 userSetFilter(field, type, value, params){
15830 this.setFilter(field, type, value, params);
15831 this.refreshFilter();
15832 }
15833
15834 //set standard filters
15835 userRefreshFilter(){
15836 this.refreshFilter();
15837 }
15838
15839 //add filter to array
15840 userAddFilter(field, type, value, params){
15841 this.addFilter(field, type, value, params);
15842 this.refreshFilter();
15843 }
15844
15845 userSetHeaderFilterFocus(field){
15846 var column = this.table.columnManager.findColumn(field);
15847
15848 if(column){
15849 this.setHeaderFilterFocus(column);
15850 }else {
15851 console.warn("Column Filter Focus Error - No matching column found:", field);
15852 return false;
15853 }
15854 }
15855
15856 userGetHeaderFilterValue(field) {
15857 var column = this.table.columnManager.findColumn(field);
15858
15859 if(column){
15860 return this.getHeaderFilterValue(column);
15861 }else {
15862 console.warn("Column Filter Error - No matching column found:", field);
15863 }
15864 }
15865
15866 userSetHeaderFilterValue(field, value){
15867 var column = this.table.columnManager.findColumn(field);
15868
15869 if(column){
15870 this.setHeaderFilterValue(column, value);
15871 }else {
15872 console.warn("Column Filter Error - No matching column found:", field);
15873 return false;
15874 }
15875 }
15876
15877 //remove filter from array
15878 userRemoveFilter(field, type, value){
15879 this.removeFilter(field, type, value);
15880 this.refreshFilter();
15881 }
15882
15883 //clear filters
15884 userClearFilter(all){
15885 this.clearFilter(all);
15886 this.refreshFilter();
15887 }
15888
15889 //clear header filters
15890 userClearHeaderFilter(){
15891 this.clearHeaderFilter();
15892 this.refreshFilter();
15893 }
15894
15895
15896 //search for specific row components
15897 searchRows(field, type, value){
15898 return this.search("rows", field, type, value);
15899 }
15900
15901 //search for specific data
15902 searchData(field, type, value){
15903 return this.search("data", field, type, value);
15904 }
15905
15906 ///////////////////////////////////
15907 ///////// Internal Logic //////////
15908 ///////////////////////////////////
15909
15910 initializeColumnHeaderFilter(column){
15911 var def = column.definition;
15912
15913 if(def.headerFilter){
15914 this.initializeColumn(column);
15915 }
15916 }
15917
15918 //initialize column header filter
15919 initializeColumn(column, value){
15920 var self = this,
15921 field = column.getField();
15922
15923 //handle successfully value change
15924 function success(value){
15925 var filterType = (column.modules.filter.tagType == "input" && column.modules.filter.attrType == "text") || column.modules.filter.tagType == "textarea" ? "partial" : "match",
15926 type = "",
15927 filterChangeCheck = "",
15928 filterFunc;
15929
15930 if(typeof column.modules.filter.prevSuccess === "undefined" || column.modules.filter.prevSuccess !== value){
15931
15932 column.modules.filter.prevSuccess = value;
15933
15934 if(!column.modules.filter.emptyFunc(value)){
15935 column.modules.filter.value = value;
15936
15937 switch(typeof column.definition.headerFilterFunc){
15938 case "string":
15939 if(Filter.filters[column.definition.headerFilterFunc]){
15940 type = column.definition.headerFilterFunc;
15941 filterFunc = function(data){
15942 var params = column.definition.headerFilterFuncParams || {};
15943 var fieldVal = column.getFieldValue(data);
15944
15945 params = typeof params === "function" ? params(value, fieldVal, data) : params;
15946
15947 return Filter.filters[column.definition.headerFilterFunc](value, fieldVal, data, params);
15948 };
15949 }else {
15950 console.warn("Header Filter Error - Matching filter function not found: ", column.definition.headerFilterFunc);
15951 }
15952 break;
15953
15954 case "function":
15955 filterFunc = function(data){
15956 var params = column.definition.headerFilterFuncParams || {};
15957 var fieldVal = column.getFieldValue(data);
15958
15959 params = typeof params === "function" ? params(value, fieldVal, data) : params;
15960
15961 return column.definition.headerFilterFunc(value, fieldVal, data, params);
15962 };
15963
15964 type = filterFunc;
15965 break;
15966 }
15967
15968 if(!filterFunc){
15969 switch(filterType){
15970 case "partial":
15971 filterFunc = function(data){
15972 var colVal = column.getFieldValue(data);
15973
15974 if(typeof colVal !== 'undefined' && colVal !== null){
15975 return String(colVal).toLowerCase().indexOf(String(value).toLowerCase()) > -1;
15976 }else {
15977 return false;
15978 }
15979 };
15980 type = "like";
15981 break;
15982
15983 default:
15984 filterFunc = function(data){
15985 return column.getFieldValue(data) == value;
15986 };
15987 type = "=";
15988 }
15989 }
15990
15991 self.headerFilters[field] = {value:value, func:filterFunc, type:type};
15992 }else {
15993 delete self.headerFilters[field];
15994 }
15995
15996 column.modules.filter.value = value;
15997
15998 filterChangeCheck = JSON.stringify(self.headerFilters);
15999
16000 if(self.prevHeaderFilterChangeCheck !== filterChangeCheck){
16001 self.prevHeaderFilterChangeCheck = filterChangeCheck;
16002
16003 self.trackChanges();
16004 self.refreshFilter();
16005 }
16006 }
16007
16008 return true;
16009 }
16010
16011 column.modules.filter = {
16012 success:success,
16013 attrType:false,
16014 tagType:false,
16015 emptyFunc:false,
16016 };
16017
16018 this.generateHeaderFilterElement(column);
16019 }
16020
16021 generateHeaderFilterElement(column, initialValue, reinitialize){
16022 var self = this,
16023 success = column.modules.filter.success,
16024 field = column.getField(),
16025 filterElement, editor, editorElement, cellWrapper, typingTimer, searchTrigger, params, onRenderedCallback;
16026
16027 column.modules.filter.value = initialValue;
16028
16029 //handle aborted edit
16030 function cancel(){}
16031
16032 function onRendered(callback){
16033 onRenderedCallback = callback;
16034 }
16035
16036 if(column.modules.filter.headerElement && column.modules.filter.headerElement.parentNode){
16037 column.contentElement.removeChild(column.modules.filter.headerElement.parentNode);
16038 }
16039
16040 if(field){
16041
16042 //set empty value function
16043 column.modules.filter.emptyFunc = column.definition.headerFilterEmptyCheck || function(value){
16044 return !value && value !== 0;
16045 };
16046
16047 filterElement = document.createElement("div");
16048 filterElement.classList.add("tabulator-header-filter");
16049
16050 //set column editor
16051 switch(typeof column.definition.headerFilter){
16052 case "string":
16053 if(self.table.modules.edit.editors[column.definition.headerFilter]){
16054 editor = self.table.modules.edit.editors[column.definition.headerFilter];
16055
16056 if((column.definition.headerFilter === "tick" || column.definition.headerFilter === "tickCross") && !column.definition.headerFilterEmptyCheck){
16057 column.modules.filter.emptyFunc = function(value){
16058 return value !== true && value !== false;
16059 };
16060 }
16061 }else {
16062 console.warn("Filter Error - Cannot build header filter, No such editor found: ", column.definition.editor);
16063 }
16064 break;
16065
16066 case "function":
16067 editor = column.definition.headerFilter;
16068 break;
16069
16070 case "boolean":
16071 if(column.modules.edit && column.modules.edit.editor){
16072 editor = column.modules.edit.editor;
16073 }else {
16074 if(column.definition.formatter && self.table.modules.edit.editors[column.definition.formatter]){
16075 editor = self.table.modules.edit.editors[column.definition.formatter];
16076
16077 if((column.definition.formatter === "tick" || column.definition.formatter === "tickCross") && !column.definition.headerFilterEmptyCheck){
16078 column.modules.filter.emptyFunc = function(value){
16079 return value !== true && value !== false;
16080 };
16081 }
16082 }else {
16083 editor = self.table.modules.edit.editors["input"];
16084 }
16085 }
16086 break;
16087 }
16088
16089 if(editor){
16090
16091 cellWrapper = {
16092 getValue:function(){
16093 return typeof initialValue !== "undefined" ? initialValue : "";
16094 },
16095 getField:function(){
16096 return column.definition.field;
16097 },
16098 getElement:function(){
16099 return filterElement;
16100 },
16101 getColumn:function(){
16102 return column.getComponent();
16103 },
16104 getTable:() => {
16105 return this.table;
16106 },
16107 getType:() => {
16108 return "header";
16109 },
16110 getRow:function(){
16111 return {
16112 normalizeHeight:function(){
16113
16114 }
16115 };
16116 }
16117 };
16118
16119 params = column.definition.headerFilterParams || {};
16120
16121 params = typeof params === "function" ? params.call(self.table, cellWrapper) : params;
16122
16123 editorElement = editor.call(this.table.modules.edit, cellWrapper, onRendered, success, cancel, params);
16124
16125 if(!editorElement){
16126 console.warn("Filter Error - Cannot add filter to " + field + " column, editor returned a value of false");
16127 return;
16128 }
16129
16130 if(!(editorElement instanceof Node)){
16131 console.warn("Filter Error - Cannot add filter to " + field + " column, editor should return an instance of Node, the editor returned:", editorElement);
16132 return;
16133 }
16134
16135 //set Placeholder Text
16136 self.langBind("headerFilters|columns|" + column.definition.field, function(value){
16137 editorElement.setAttribute("placeholder", typeof value !== "undefined" && value ? value : (column.definition.headerFilterPlaceholder || self.langText("headerFilters|default")));
16138 });
16139
16140 //focus on element on click
16141 editorElement.addEventListener("click", function(e){
16142 e.stopPropagation();
16143 editorElement.focus();
16144 });
16145
16146 editorElement.addEventListener("focus", (e) => {
16147 var left = this.table.columnManager.contentsElement.scrollLeft;
16148
16149 var headerPos = this.table.rowManager.element.scrollLeft;
16150
16151 if(left !== headerPos){
16152 this.table.rowManager.scrollHorizontal(left);
16153 this.table.columnManager.scrollHorizontal(left);
16154 }
16155 });
16156
16157 //live update filters as user types
16158 typingTimer = false;
16159
16160 searchTrigger = function(e){
16161 if(typingTimer){
16162 clearTimeout(typingTimer);
16163 }
16164
16165 typingTimer = setTimeout(function(){
16166 success(editorElement.value);
16167 },self.table.options.headerFilterLiveFilterDelay);
16168 };
16169
16170 column.modules.filter.headerElement = editorElement;
16171 column.modules.filter.attrType = editorElement.hasAttribute("type") ? editorElement.getAttribute("type").toLowerCase() : "" ;
16172 column.modules.filter.tagType = editorElement.tagName.toLowerCase();
16173
16174 if(column.definition.headerFilterLiveFilter !== false){
16175
16176 if (
16177 !(
16178 column.definition.headerFilter === 'autocomplete' ||
16179 column.definition.headerFilter === 'tickCross' ||
16180 ((column.definition.editor === 'autocomplete' ||
16181 column.definition.editor === 'tickCross') &&
16182 column.definition.headerFilter === true)
16183 )
16184 ) {
16185 editorElement.addEventListener("keyup", searchTrigger);
16186 editorElement.addEventListener("search", searchTrigger);
16187
16188
16189 //update number filtered columns on change
16190 if(column.modules.filter.attrType == "number"){
16191 editorElement.addEventListener("change", function(e){
16192 success(editorElement.value);
16193 });
16194 }
16195
16196 //change text inputs to search inputs to allow for clearing of field
16197 if(column.modules.filter.attrType == "text" && this.table.browser !== "ie"){
16198 editorElement.setAttribute("type", "search");
16199 // editorElement.off("change blur"); //prevent blur from triggering filter and preventing selection click
16200 }
16201
16202 }
16203
16204 //prevent input and select elements from propagating click to column sorters etc
16205 if(column.modules.filter.tagType == "input" || column.modules.filter.tagType == "select" || column.modules.filter.tagType == "textarea"){
16206 editorElement.addEventListener("mousedown",function(e){
16207 e.stopPropagation();
16208 });
16209 }
16210 }
16211
16212 filterElement.appendChild(editorElement);
16213
16214 column.contentElement.appendChild(filterElement);
16215
16216 if(!reinitialize){
16217 self.headerFilterColumns.push(column);
16218 }
16219
16220 if(onRenderedCallback){
16221 onRenderedCallback();
16222 }
16223 }
16224 }else {
16225 console.warn("Filter Error - Cannot add header filter, column has no field set:", column.definition.title);
16226 }
16227 }
16228
16229 //hide all header filter elements (used to ensure correct column widths in "fitData" layout mode)
16230 hideHeaderFilterElements(){
16231 this.headerFilterColumns.forEach(function(column){
16232 if(column.modules.filter && column.modules.filter.headerElement){
16233 column.modules.filter.headerElement.style.display = 'none';
16234 }
16235 });
16236 }
16237
16238 //show all header filter elements (used to ensure correct column widths in "fitData" layout mode)
16239 showHeaderFilterElements(){
16240 this.headerFilterColumns.forEach(function(column){
16241 if(column.modules.filter && column.modules.filter.headerElement){
16242 column.modules.filter.headerElement.style.display = '';
16243 }
16244 });
16245 }
16246
16247 //programmatically set focus of header filter
16248 setHeaderFilterFocus(column){
16249 if(column.modules.filter && column.modules.filter.headerElement){
16250 column.modules.filter.headerElement.focus();
16251 }else {
16252 console.warn("Column Filter Focus Error - No header filter set on column:", column.getField());
16253 }
16254 }
16255
16256 //programmatically get value of header filter
16257 getHeaderFilterValue(column){
16258 if(column.modules.filter && column.modules.filter.headerElement){
16259 return column.modules.filter.value;
16260 } else {
16261 console.warn("Column Filter Error - No header filter set on column:", column.getField());
16262 }
16263 }
16264
16265 //programmatically set value of header filter
16266 setHeaderFilterValue(column, value){
16267 if (column){
16268 if(column.modules.filter && column.modules.filter.headerElement){
16269 this.generateHeaderFilterElement(column, value, true);
16270 column.modules.filter.success(value);
16271 }else {
16272 console.warn("Column Filter Error - No header filter set on column:", column.getField());
16273 }
16274 }
16275 }
16276
16277 reloadHeaderFilter(column){
16278 if (column){
16279 if(column.modules.filter && column.modules.filter.headerElement){
16280 this.generateHeaderFilterElement(column, column.modules.filter.value, true);
16281 }else {
16282 console.warn("Column Filter Error - No header filter set on column:", column.getField());
16283 }
16284 }
16285 }
16286
16287 refreshFilter(){
16288 if(this.tableInitialized){
16289 if(this.table.options.filterMode === "remote"){
16290 this.reloadData(null, false, false);
16291 }else {
16292 this.refreshData(true);
16293 }
16294 }
16295
16296 //TODO - Persist left position of row manager
16297 // left = this.scrollLeft;
16298 // this.scrollHorizontal(left);
16299 }
16300
16301 //check if the filters has changed since last use
16302 trackChanges(){
16303 this.changed = true;
16304 this.dispatch("filter-changed");
16305 }
16306
16307 //check if the filters has changed since last use
16308 hasChanged(){
16309 var changed = this.changed;
16310 this.changed = false;
16311 return changed;
16312 }
16313
16314 //set standard filters
16315 setFilter(field, type, value, params){
16316 this.filterList = [];
16317
16318 if(!Array.isArray(field)){
16319 field = [{field:field, type:type, value:value, params:params}];
16320 }
16321
16322 this.addFilter(field);
16323 }
16324
16325 //add filter to array
16326 addFilter(field, type, value, params){
16327 var changed = false;
16328
16329 if(!Array.isArray(field)){
16330 field = [{field:field, type:type, value:value, params:params}];
16331 }
16332
16333 field.forEach((filter) => {
16334 filter = this.findFilter(filter);
16335
16336 if(filter){
16337 this.filterList.push(filter);
16338 changed = true;
16339 }
16340 });
16341
16342 if(changed){
16343 this.trackChanges();
16344 }
16345 }
16346
16347 findFilter(filter){
16348 var column;
16349
16350 if(Array.isArray(filter)){
16351 return this.findSubFilters(filter);
16352 }
16353
16354 var filterFunc = false;
16355
16356 if(typeof filter.field == "function"){
16357 filterFunc = function(data){
16358 return filter.field(data, filter.type || {});// pass params to custom filter function
16359 };
16360 }else {
16361
16362 if(Filter.filters[filter.type]){
16363
16364 column = this.table.columnManager.getColumnByField(filter.field);
16365
16366 if(column){
16367 filterFunc = function(data){
16368 return Filter.filters[filter.type](filter.value, column.getFieldValue(data), data, filter.params || {});
16369 };
16370 }else {
16371 filterFunc = function(data){
16372 return Filter.filters[filter.type](filter.value, data[filter.field], data, filter.params || {});
16373 };
16374 }
16375
16376
16377 }else {
16378 console.warn("Filter Error - No such filter type found, ignoring: ", filter.type);
16379 }
16380 }
16381
16382 filter.func = filterFunc;
16383
16384 return filter.func ? filter : false;
16385 }
16386
16387 findSubFilters(filters){
16388 var output = [];
16389
16390 filters.forEach((filter) => {
16391 filter = this.findFilter(filter);
16392
16393 if(filter){
16394 output.push(filter);
16395 }
16396 });
16397
16398 return output.length ? output : false;
16399 }
16400
16401 //get all filters
16402 getFilters(all, ajax){
16403 var output = [];
16404
16405 if(all){
16406 output = this.getHeaderFilters();
16407 }
16408
16409 if(ajax){
16410 output.forEach(function(item){
16411 if(typeof item.type == "function"){
16412 item.type = "function";
16413 }
16414 });
16415 }
16416
16417 output = output.concat(this.filtersToArray(this.filterList, ajax));
16418
16419 return output;
16420 }
16421
16422 //filter to Object
16423 filtersToArray(filterList, ajax){
16424 var output = [];
16425
16426 filterList.forEach((filter) => {
16427 var item;
16428
16429 if(Array.isArray(filter)){
16430 output.push(this.filtersToArray(filter, ajax));
16431 }else {
16432 item = {field:filter.field, type:filter.type, value:filter.value};
16433
16434 if(ajax){
16435 if(typeof item.type == "function"){
16436 item.type = "function";
16437 }
16438 }
16439
16440 output.push(item);
16441 }
16442 });
16443
16444 return output;
16445 }
16446
16447 //get all filters
16448 getHeaderFilters(){
16449 var output = [];
16450
16451 for(var key in this.headerFilters){
16452 output.push({field:key, type:this.headerFilters[key].type, value:this.headerFilters[key].value});
16453 }
16454
16455 return output;
16456 }
16457
16458 //remove filter from array
16459 removeFilter(field, type, value){
16460 if(!Array.isArray(field)){
16461 field = [{field:field, type:type, value:value}];
16462 }
16463
16464 field.forEach((filter) => {
16465 var index = -1;
16466
16467 if(typeof filter.field == "object"){
16468 index = this.filterList.findIndex((element) => {
16469 return filter === element;
16470 });
16471 }else {
16472 index = this.filterList.findIndex((element) => {
16473 return filter.field === element.field && filter.type === element.type && filter.value === element.value;
16474 });
16475 }
16476
16477 if(index > -1){
16478 this.filterList.splice(index, 1);
16479 }else {
16480 console.warn("Filter Error - No matching filter type found, ignoring: ", filter.type);
16481 }
16482 });
16483
16484 this.trackChanges();
16485 }
16486
16487 //clear filters
16488 clearFilter(all){
16489 this.filterList = [];
16490
16491 if(all){
16492 this.clearHeaderFilter();
16493 }
16494
16495 this.trackChanges();
16496 }
16497
16498 //clear header filters
16499 clearHeaderFilter(){
16500 this.headerFilters = {};
16501 this.prevHeaderFilterChangeCheck = "{}";
16502
16503 this.headerFilterColumns.forEach((column) => {
16504 if(typeof column.modules.filter.value !== "undefined"){
16505 delete column.modules.filter.value;
16506 }
16507 column.modules.filter.prevSuccess = undefined;
16508 this.reloadHeaderFilter(column);
16509 });
16510
16511 this.trackChanges();
16512 }
16513
16514 //search data and return matching rows
16515 search (searchType, field, type, value){
16516 var activeRows = [],
16517 filterList = [];
16518
16519 if(!Array.isArray(field)){
16520 field = [{field:field, type:type, value:value}];
16521 }
16522
16523 field.forEach((filter) => {
16524 filter = this.findFilter(filter);
16525
16526 if(filter){
16527 filterList.push(filter);
16528 }
16529 });
16530
16531 this.table.rowManager.rows.forEach((row) => {
16532 var match = true;
16533
16534 filterList.forEach((filter) => {
16535 if(!this.filterRecurse(filter, row.getData())){
16536 match = false;
16537 }
16538 });
16539
16540 if(match){
16541 activeRows.push(searchType === "data" ? row.getData("data") : row.getComponent());
16542 }
16543
16544 });
16545
16546 return activeRows;
16547 }
16548
16549 //filter row array
16550 filter(rowList, filters){
16551 var activeRows = [],
16552 activeRowComponents = [];
16553
16554 if(this.subscribedExternal("dataFiltering")){
16555 this.dispatchExternal("dataFiltering", this.getFilters(true));
16556 }
16557
16558 if(this.table.options.filterMode !== "remote" && (this.filterList.length || Object.keys(this.headerFilters).length)){
16559
16560 rowList.forEach((row) => {
16561 if(this.filterRow(row)){
16562 activeRows.push(row);
16563 }
16564 });
16565
16566 }else {
16567 activeRows = rowList.slice(0);
16568 }
16569
16570 if(this.subscribedExternal("dataFiltered")){
16571
16572 activeRows.forEach((row) => {
16573 activeRowComponents.push(row.getComponent());
16574 });
16575
16576 this.dispatchExternal("dataFiltered", this.getFilters(true), activeRowComponents);
16577 }
16578
16579 return activeRows;
16580 }
16581
16582 //filter individual row
16583 filterRow(row, filters){
16584 var match = true,
16585 data = row.getData();
16586
16587 this.filterList.forEach((filter) => {
16588 if(!this.filterRecurse(filter, data)){
16589 match = false;
16590 }
16591 });
16592
16593
16594 for(var field in this.headerFilters){
16595 if(!this.headerFilters[field].func(data)){
16596 match = false;
16597 }
16598 }
16599
16600 return match;
16601 }
16602
16603 filterRecurse(filter, data){
16604 var match = false;
16605
16606 if(Array.isArray(filter)){
16607 filter.forEach((subFilter) => {
16608 if(this.filterRecurse(subFilter, data)){
16609 match = true;
16610 }
16611 });
16612 }else {
16613 match = filter.func(data);
16614 }
16615
16616 return match;
16617 }
16618 }
16619
16620 function plaintext(cell, formatterParams, onRendered){
16621 return this.emptyToSpace(this.sanitizeHTML(cell.getValue()));
16622 }
16623
16624 function html(cell, formatterParams, onRendered){
16625 return cell.getValue();
16626 }
16627
16628 function textarea(cell, formatterParams, onRendered){
16629 cell.getElement().style.whiteSpace = "pre-wrap";
16630 return this.emptyToSpace(this.sanitizeHTML(cell.getValue()));
16631 }
16632
16633 function money(cell, formatterParams, onRendered){
16634 var floatVal = parseFloat(cell.getValue()),
16635 sign = "",
16636 number, integer, decimal, rgx, value;
16637
16638 var decimalSym = formatterParams.decimal || ".";
16639 var thousandSym = formatterParams.thousand || ",";
16640 var negativeSign = formatterParams.negativeSign || "-";
16641 var symbol = formatterParams.symbol || "";
16642 var after = !!formatterParams.symbolAfter;
16643 var precision = typeof formatterParams.precision !== "undefined" ? formatterParams.precision : 2;
16644
16645 if(isNaN(floatVal)){
16646 return this.emptyToSpace(this.sanitizeHTML(cell.getValue()));
16647 }
16648
16649 if(floatVal < 0){
16650 floatVal = Math.abs(floatVal);
16651 sign = negativeSign;
16652 }
16653
16654 number = precision !== false ? floatVal.toFixed(precision) : floatVal;
16655 number = String(number).split(".");
16656
16657 integer = number[0];
16658 decimal = number.length > 1 ? decimalSym + number[1] : "";
16659
16660 if (formatterParams.thousand !== false) {
16661 rgx = /(\d+)(\d{3})/;
16662
16663 while (rgx.test(integer)){
16664 integer = integer.replace(rgx, "$1" + thousandSym + "$2");
16665 }
16666 }
16667
16668 value = integer + decimal;
16669
16670 if(sign === true){
16671 value = "(" + value + ")";
16672 return after ? value + symbol : symbol + value;
16673 }else {
16674 return after ? sign + value + symbol : sign + symbol + value;
16675 }
16676 }
16677
16678 function link(cell, formatterParams, onRendered){
16679 var value = cell.getValue(),
16680 urlPrefix = formatterParams.urlPrefix || "",
16681 download = formatterParams.download,
16682 label = value,
16683 el = document.createElement("a"),
16684 data;
16685
16686 function labelTraverse(path, data){
16687 var item = path.shift(),
16688 value = data[item];
16689
16690 if(path.length && typeof value === "object"){
16691 return labelTraverse(path, value);
16692 }
16693
16694 return value;
16695 }
16696
16697 if(formatterParams.labelField){
16698 data = cell.getData();
16699 label = labelTraverse(formatterParams.labelField.split(this.table.options.nestedFieldSeparator), data);
16700 }
16701
16702 if(formatterParams.label){
16703 switch(typeof formatterParams.label){
16704 case "string":
16705 label = formatterParams.label;
16706 break;
16707
16708 case "function":
16709 label = formatterParams.label(cell);
16710 break;
16711 }
16712 }
16713
16714 if(label){
16715 if(formatterParams.urlField){
16716 data = cell.getData();
16717
16718 value = Helpers.retrieveNestedData(this.table.options.nestedFieldSeparator, formatterParams.urlField, data);
16719 }
16720
16721 if(formatterParams.url){
16722 switch(typeof formatterParams.url){
16723 case "string":
16724 value = formatterParams.url;
16725 break;
16726
16727 case "function":
16728 value = formatterParams.url(cell);
16729 break;
16730 }
16731 }
16732
16733 el.setAttribute("href", urlPrefix + value);
16734
16735 if(formatterParams.target){
16736 el.setAttribute("target", formatterParams.target);
16737 }
16738
16739 if(formatterParams.download){
16740
16741 if(typeof download == "function"){
16742 download = download(cell);
16743 }else {
16744 download = download === true ? "" : download;
16745 }
16746
16747 el.setAttribute("download", download);
16748 }
16749
16750 el.innerHTML = this.emptyToSpace(this.sanitizeHTML(label));
16751
16752 return el;
16753 }else {
16754 return "&nbsp;";
16755 }
16756 }
16757
16758 function image(cell, formatterParams, onRendered){
16759 var el = document.createElement("img"),
16760 src = cell.getValue();
16761
16762 if(formatterParams.urlPrefix){
16763 src = formatterParams.urlPrefix + cell.getValue();
16764 }
16765
16766 if(formatterParams.urlSuffix){
16767 src = src + formatterParams.urlSuffix;
16768 }
16769
16770 el.setAttribute("src", src);
16771
16772 switch(typeof formatterParams.height){
16773 case "number":
16774 el.style.height = formatterParams.height + "px";
16775 break;
16776
16777 case "string":
16778 el.style.height = formatterParams.height;
16779 break;
16780 }
16781
16782 switch(typeof formatterParams.width){
16783 case "number":
16784 el.style.width = formatterParams.width + "px";
16785 break;
16786
16787 case "string":
16788 el.style.width = formatterParams.width;
16789 break;
16790 }
16791
16792 el.addEventListener("load", function(){
16793 cell.getRow().normalizeHeight();
16794 });
16795
16796 return el;
16797 }
16798
16799 function tickCross(cell, formatterParams, onRendered){
16800 var value = cell.getValue(),
16801 element = cell.getElement(),
16802 empty = formatterParams.allowEmpty,
16803 truthy = formatterParams.allowTruthy,
16804 trueValueSet = Object.keys(formatterParams).includes("trueValue"),
16805 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>',
16806 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>';
16807
16808 if((trueValueSet && value === formatterParams.trueValue) || (!trueValueSet && ((truthy && value) || (value === true || value === "true" || value === "True" || value === 1 || value === "1")))){
16809 element.setAttribute("aria-checked", true);
16810 return tick || "";
16811 }else {
16812 if(empty && (value === "null" || value === "" || value === null || typeof value === "undefined")){
16813 element.setAttribute("aria-checked", "mixed");
16814 return "";
16815 }else {
16816 element.setAttribute("aria-checked", false);
16817 return cross || "";
16818 }
16819 }
16820 }
16821
16822 function datetime$1(cell, formatterParams, onRendered){
16823 var DT = this.table.dependencyRegistry.lookup(["luxon", "DateTime"], "DateTime");
16824 var inputFormat = formatterParams.inputFormat || "yyyy-MM-dd HH:mm:ss";
16825 var outputFormat = formatterParams.outputFormat || "dd/MM/yyyy HH:mm:ss";
16826 var invalid = typeof formatterParams.invalidPlaceholder !== "undefined" ? formatterParams.invalidPlaceholder : "";
16827 var value = cell.getValue();
16828
16829 if(typeof DT != "undefined"){
16830 var newDatetime;
16831
16832 if(DT.isDateTime(value)){
16833 newDatetime = value;
16834 }else if(inputFormat === "iso"){
16835 newDatetime = DT.fromISO(String(value));
16836 }else {
16837 newDatetime = DT.fromFormat(String(value), inputFormat);
16838 }
16839
16840 if(newDatetime.isValid){
16841 if(formatterParams.timezone){
16842 newDatetime = newDatetime.setZone(formatterParams.timezone);
16843 }
16844
16845 return newDatetime.toFormat(outputFormat);
16846 }else {
16847 if(invalid === true || !value){
16848 return value;
16849 }else if(typeof invalid === "function"){
16850 return invalid(value);
16851 }else {
16852 return invalid;
16853 }
16854 }
16855 }else {
16856 console.error("Format Error - 'datetime' formatter is dependant on luxon.js");
16857 }
16858 }
16859
16860 function datetimediff (cell, formatterParams, onRendered) {
16861 var DT = this.table.dependencyRegistry.lookup(["luxon", "DateTime"], "DateTime");
16862 var inputFormat = formatterParams.inputFormat || "yyyy-MM-dd HH:mm:ss";
16863 var invalid = typeof formatterParams.invalidPlaceholder !== "undefined" ? formatterParams.invalidPlaceholder : "";
16864 var suffix = typeof formatterParams.suffix !== "undefined" ? formatterParams.suffix : false;
16865 var unit = typeof formatterParams.unit !== "undefined" ? formatterParams.unit : "days";
16866 var humanize = typeof formatterParams.humanize !== "undefined" ? formatterParams.humanize : false;
16867 var date = typeof formatterParams.date !== "undefined" ? formatterParams.date : DT.now();
16868 var value = cell.getValue();
16869
16870 if(typeof DT != "undefined"){
16871 var newDatetime;
16872
16873 if(DT.isDateTime(value)){
16874 newDatetime = value;
16875 }else if(inputFormat === "iso"){
16876 newDatetime = DT.fromISO(String(value));
16877 }else {
16878 newDatetime = DT.fromFormat(String(value), inputFormat);
16879 }
16880
16881 if (newDatetime.isValid){
16882 if(humanize){
16883 return newDatetime.diff(date, unit).toHuman() + (suffix ? " " + suffix : "");
16884 }else {
16885 return parseInt(newDatetime.diff(date, unit)[unit]) + (suffix ? " " + suffix : "");
16886 }
16887 } else {
16888
16889 if (invalid === true) {
16890 return value;
16891 } else if (typeof invalid === "function") {
16892 return invalid(value);
16893 } else {
16894 return invalid;
16895 }
16896 }
16897 }else {
16898 console.error("Format Error - 'datetimediff' formatter is dependant on luxon.js");
16899 }
16900 }
16901
16902 function lookup (cell, formatterParams, onRendered) {
16903 var value = cell.getValue();
16904
16905 if (typeof formatterParams[value] === "undefined") {
16906 console.warn('Missing display value for ' + value);
16907 return value;
16908 }
16909
16910 return formatterParams[value];
16911 }
16912
16913 function star(cell, formatterParams, onRendered){
16914 var value = cell.getValue(),
16915 element = cell.getElement(),
16916 maxStars = formatterParams && formatterParams.stars ? formatterParams.stars : 5,
16917 stars = document.createElement("span"),
16918 star = document.createElementNS('http://www.w3.org/2000/svg', "svg"),
16919 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 "/>',
16920 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 "/>';
16921
16922 //style stars holder
16923 stars.style.verticalAlign = "middle";
16924
16925 //style star
16926 star.setAttribute("width", "14");
16927 star.setAttribute("height", "14");
16928 star.setAttribute("viewBox", "0 0 512 512");
16929 star.setAttribute("xml:space", "preserve");
16930 star.style.padding = "0 1px";
16931
16932 value = value && !isNaN(value) ? parseInt(value) : 0;
16933
16934 value = Math.max(0, Math.min(value, maxStars));
16935
16936 for(var i=1;i<= maxStars;i++){
16937 var nextStar = star.cloneNode(true);
16938 nextStar.innerHTML = i <= value ? starActive : starInactive;
16939
16940 stars.appendChild(nextStar);
16941 }
16942
16943 element.style.whiteSpace = "nowrap";
16944 element.style.overflow = "hidden";
16945 element.style.textOverflow = "ellipsis";
16946
16947 element.setAttribute("aria-label", value);
16948
16949 return stars;
16950 }
16951
16952 function traffic(cell, formatterParams, onRendered){
16953 var value = this.sanitizeHTML(cell.getValue()) || 0,
16954 el = document.createElement("span"),
16955 max = formatterParams && formatterParams.max ? formatterParams.max : 100,
16956 min = formatterParams && formatterParams.min ? formatterParams.min : 0,
16957 colors = formatterParams && typeof formatterParams.color !== "undefined" ? formatterParams.color : ["red", "orange", "green"],
16958 color = "#666666",
16959 percent, percentValue;
16960
16961 if(isNaN(value) || typeof cell.getValue() === "undefined"){
16962 return;
16963 }
16964
16965 el.classList.add("tabulator-traffic-light");
16966
16967 //make sure value is in range
16968 percentValue = parseFloat(value) <= max ? parseFloat(value) : max;
16969 percentValue = parseFloat(percentValue) >= min ? parseFloat(percentValue) : min;
16970
16971 //workout percentage
16972 percent = (max - min) / 100;
16973 percentValue = Math.round((percentValue - min) / percent);
16974
16975 //set color
16976 switch(typeof colors){
16977 case "string":
16978 color = colors;
16979 break;
16980 case "function":
16981 color = colors(value);
16982 break;
16983 case "object":
16984 if(Array.isArray(colors)){
16985 var unit = 100 / colors.length;
16986 var index = Math.floor(percentValue / unit);
16987
16988 index = Math.min(index, colors.length - 1);
16989 index = Math.max(index, 0);
16990 color = colors[index];
16991 break;
16992 }
16993 }
16994
16995 el.style.backgroundColor = color;
16996
16997 return el;
16998 }
16999
17000 function progress(cell, formatterParams = {}, onRendered){ //progress bar
17001 var value = this.sanitizeHTML(cell.getValue()) || 0,
17002 element = cell.getElement(),
17003 max = formatterParams.max ? formatterParams.max : 100,
17004 min = formatterParams.min ? formatterParams.min : 0,
17005 legendAlign = formatterParams.legendAlign ? formatterParams.legendAlign : "center",
17006 percent, percentValue, color, legend, legendColor;
17007
17008 //make sure value is in range
17009 percentValue = parseFloat(value) <= max ? parseFloat(value) : max;
17010 percentValue = parseFloat(percentValue) >= min ? parseFloat(percentValue) : min;
17011
17012 //workout percentage
17013 percent = (max - min) / 100;
17014 percentValue = Math.round((percentValue - min) / percent);
17015
17016 //set bar color
17017 switch(typeof formatterParams.color){
17018 case "string":
17019 color = formatterParams.color;
17020 break;
17021 case "function":
17022 color = formatterParams.color(value);
17023 break;
17024 case "object":
17025 if(Array.isArray(formatterParams.color)){
17026 let unit = 100 / formatterParams.color.length;
17027 let index = Math.floor(percentValue / unit);
17028
17029 index = Math.min(index, formatterParams.color.length - 1);
17030 index = Math.max(index, 0);
17031 color = formatterParams.color[index];
17032 break;
17033 }
17034 default:
17035 color = "#2DC214";
17036 }
17037
17038 //generate legend
17039 switch(typeof formatterParams.legend){
17040 case "string":
17041 legend = formatterParams.legend;
17042 break;
17043 case "function":
17044 legend = formatterParams.legend(value);
17045 break;
17046 case "boolean":
17047 legend = value;
17048 break;
17049 default:
17050 legend = false;
17051 }
17052
17053 //set legend color
17054 switch(typeof formatterParams.legendColor){
17055 case "string":
17056 legendColor = formatterParams.legendColor;
17057 break;
17058 case "function":
17059 legendColor = formatterParams.legendColor(value);
17060 break;
17061 case "object":
17062 if(Array.isArray(formatterParams.legendColor)){
17063 let unit = 100 / formatterParams.legendColor.length;
17064 let index = Math.floor(percentValue / unit);
17065
17066 index = Math.min(index, formatterParams.legendColor.length - 1);
17067 index = Math.max(index, 0);
17068 legendColor = formatterParams.legendColor[index];
17069 }
17070 break;
17071 default:
17072 legendColor = "#000";
17073 }
17074
17075 element.style.minWidth = "30px";
17076 element.style.position = "relative";
17077
17078 element.setAttribute("aria-label", percentValue);
17079
17080 var barEl = document.createElement("div");
17081 barEl.style.display = "inline-block";
17082 barEl.style.width = percentValue + "%";
17083 barEl.style.backgroundColor = color;
17084 barEl.style.height = "100%";
17085
17086 barEl.setAttribute('data-max', max);
17087 barEl.setAttribute('data-min', min);
17088
17089 var barContainer = document.createElement("div");
17090 barContainer.style.position = "relative";
17091 barContainer.style.width = "100%";
17092 barContainer.style.height = "100%";
17093
17094 if(legend){
17095 var legendEl = document.createElement("div");
17096 legendEl.style.position = "absolute";
17097 legendEl.style.top = 0;
17098 legendEl.style.left = 0;
17099 legendEl.style.textAlign = legendAlign;
17100 legendEl.style.width = "100%";
17101 legendEl.style.color = legendColor;
17102 legendEl.innerHTML = legend;
17103 }
17104
17105 onRendered(function(){
17106
17107 //handle custom element needed if formatter is to be included in printed/downloaded output
17108 if(!(cell instanceof CellComponent)){
17109 var holderEl = document.createElement("div");
17110 holderEl.style.position = "absolute";
17111 holderEl.style.top = "4px";
17112 holderEl.style.bottom = "4px";
17113 holderEl.style.left = "4px";
17114 holderEl.style.right = "4px";
17115
17116 element.appendChild(holderEl);
17117
17118 element = holderEl;
17119 }
17120
17121 element.appendChild(barContainer);
17122 barContainer.appendChild(barEl);
17123
17124 if(legend){
17125 barContainer.appendChild(legendEl);
17126 }
17127 });
17128
17129 return "";
17130 }
17131
17132 function color(cell, formatterParams, onRendered){
17133 cell.getElement().style.backgroundColor = this.sanitizeHTML(cell.getValue());
17134 return "";
17135 }
17136
17137 function buttonTick(cell, formatterParams, onRendered){
17138 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>';
17139 }
17140
17141 function buttonCross(cell, formatterParams, onRendered){
17142 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>';
17143 }
17144
17145 function toggle(cell, formatterParams, onRendered){
17146 var value = cell.getValue(),
17147 size = formatterParams.size ||15,
17148 sizePx = size + "px",
17149 containEl, switchEl,
17150 onValue = formatterParams.hasOwnProperty("onValue") ? formatterParams.onValue : true,
17151 offValue = formatterParams.hasOwnProperty("offValue") ? formatterParams.offValue : false,
17152
17153
17154 state = formatterParams.onTruthy ? value : value === onValue;
17155
17156
17157 containEl = document.createElement("div");
17158 containEl.classList.add("tabulator-toggle");
17159
17160 if(state){
17161 containEl.classList.add("tabulator-toggle-on");
17162 containEl.style.flexDirection = "row-reverse";
17163
17164 if(formatterParams.onColor){
17165 containEl.style.background = formatterParams.onColor;
17166 }
17167 }else {
17168 if(formatterParams.offColor){
17169 containEl.style.background = formatterParams.offColor;
17170 }
17171 }
17172
17173 containEl.style.width = (2.5 * size) + "px";
17174 containEl.style.borderRadius = sizePx;
17175
17176 if(formatterParams.clickable){
17177 containEl.addEventListener("click", (e) => {
17178 cell.setValue(state ? offValue : onValue);
17179 });
17180 }
17181
17182 switchEl = document.createElement("div");
17183 switchEl.classList.add("tabulator-toggle-switch");
17184
17185 switchEl.style.height = sizePx;
17186 switchEl.style.width = sizePx;
17187 switchEl.style.borderRadius = sizePx;
17188
17189 containEl.appendChild(switchEl);
17190
17191 return containEl;
17192 }
17193
17194 function rownum(cell, formatterParams, onRendered){
17195 var content = document.createElement("span");
17196 var row = cell.getRow();
17197 var table = cell.getTable();
17198
17199 row.watchPosition((position) => {
17200 if (formatterParams.relativeToPage) {
17201 position += table.modules.page.getPageSize() * (table.modules.page.getPage() - 1);
17202 }
17203 content.innerText = position;
17204 });
17205
17206 return content;
17207 }
17208
17209 function handle(cell, formatterParams, onRendered){
17210 cell.getElement().classList.add("tabulator-row-handle");
17211 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>";
17212 }
17213
17214 function adaptable(cell, params, onRendered){
17215 var lookup, formatterFunc, formatterParams;
17216
17217 function defaultLookup(cell){
17218 var value = cell.getValue(),
17219 formatter = "plaintext";
17220
17221 switch(typeof value){
17222 case "boolean":
17223 formatter = "tickCross";
17224 break;
17225
17226 case "string":
17227 if(value.includes("\n")){
17228 formatter = "textarea";
17229 }
17230 break;
17231 }
17232
17233 return formatter;
17234 }
17235
17236 lookup = params.formatterLookup ? params.formatterLookup(cell) : defaultLookup(cell);
17237
17238 if(params.paramsLookup){
17239 formatterParams = typeof params.paramsLookup === "function" ? params.paramsLookup(lookup, cell) : params.paramsLookup[lookup];
17240 }
17241
17242 formatterFunc = this.table.modules.format.lookupFormatter(lookup);
17243
17244 return formatterFunc.call(this, cell, formatterParams || {}, onRendered);
17245 }
17246
17247 function array$2(cell, formatterParams, onRendered){
17248 var delimiter = formatterParams.delimiter || ",",
17249 value = cell.getValue(),
17250 table = this.table,
17251 valueMap;
17252
17253 if(formatterParams.valueMap){
17254 if(typeof formatterParams.valueMap === "string"){
17255 valueMap = function(value){
17256 return value.map((item) => {
17257 return Helpers.retrieveNestedData(table.options.nestedFieldSeparator, formatterParams.valueMap, item);
17258 });
17259 };
17260 }else {
17261 valueMap = formatterParams.valueMap;
17262 }
17263 }
17264
17265 if(Array.isArray(value)){
17266 if(valueMap){
17267 value = valueMap(value);
17268 }
17269
17270 return value.join(delimiter);
17271 }else {
17272 return value;
17273 }
17274 }
17275
17276 function json$1(cell, formatterParams, onRendered){
17277 var indent = formatterParams.indent || "\t",
17278 multiline = typeof formatterParams.multiline === "undefined" ? true : formatterParams.multiline,
17279 replacer = formatterParams.replacer || null,
17280 value = cell.getValue();
17281
17282 if(multiline){
17283 cell.getElement().style.whiteSpace = "pre-wrap";
17284 }
17285
17286 return JSON.stringify(value, replacer, indent);
17287 }
17288
17289 var defaultFormatters = {
17290 plaintext:plaintext,
17291 html:html,
17292 textarea:textarea,
17293 money:money,
17294 link:link,
17295 image:image,
17296 tickCross:tickCross,
17297 datetime:datetime$1,
17298 datetimediff:datetimediff,
17299 lookup:lookup,
17300 star:star,
17301 traffic:traffic,
17302 progress:progress,
17303 color:color,
17304 buttonTick:buttonTick,
17305 buttonCross:buttonCross,
17306 toggle:toggle,
17307 rownum:rownum,
17308 handle:handle,
17309 adaptable:adaptable,
17310 array:array$2,
17311 json:json$1,
17312 };
17313
17314 class Format extends Module{
17315
17316 static moduleName = "format";
17317
17318 //load defaults
17319 static formatters = defaultFormatters;
17320
17321 constructor(table){
17322 super(table);
17323
17324 this.registerColumnOption("formatter");
17325 this.registerColumnOption("formatterParams");
17326
17327 this.registerColumnOption("formatterPrint");
17328 this.registerColumnOption("formatterPrintParams");
17329 this.registerColumnOption("formatterClipboard");
17330 this.registerColumnOption("formatterClipboardParams");
17331 this.registerColumnOption("formatterHtmlOutput");
17332 this.registerColumnOption("formatterHtmlOutputParams");
17333 this.registerColumnOption("titleFormatter");
17334 this.registerColumnOption("titleFormatterParams");
17335 }
17336
17337 initialize(){
17338 this.subscribe("cell-format", this.formatValue.bind(this));
17339 this.subscribe("cell-rendered", this.cellRendered.bind(this));
17340 this.subscribe("column-layout", this.initializeColumn.bind(this));
17341 this.subscribe("column-format", this.formatHeader.bind(this));
17342 }
17343
17344 //initialize column formatter
17345 initializeColumn(column){
17346 column.modules.format = this.lookupTypeFormatter(column, "");
17347
17348 if(typeof column.definition.formatterPrint !== "undefined"){
17349 column.modules.format.print = this.lookupTypeFormatter(column, "Print");
17350 }
17351
17352 if(typeof column.definition.formatterClipboard !== "undefined"){
17353 column.modules.format.clipboard = this.lookupTypeFormatter(column, "Clipboard");
17354 }
17355
17356 if(typeof column.definition.formatterHtmlOutput !== "undefined"){
17357 column.modules.format.htmlOutput = this.lookupTypeFormatter(column, "HtmlOutput");
17358 }
17359 }
17360
17361 lookupTypeFormatter(column, type){
17362 var config = {params:column.definition["formatter" + type + "Params"] || {}},
17363 formatter = column.definition["formatter" + type];
17364
17365 config.formatter = this.lookupFormatter(formatter);
17366
17367 return config;
17368 }
17369
17370
17371 lookupFormatter(formatter){
17372 var formatterFunc;
17373
17374 //set column formatter
17375 switch(typeof formatter){
17376 case "string":
17377 if(Format.formatters[formatter]){
17378 formatterFunc = Format.formatters[formatter];
17379 }else {
17380 console.warn("Formatter Error - No such formatter found: ", formatter);
17381 formatterFunc = Format.formatters.plaintext;
17382 }
17383 break;
17384
17385 case "function":
17386 formatterFunc = formatter;
17387 break;
17388
17389 default:
17390 formatterFunc = Format.formatters.plaintext;
17391 break;
17392 }
17393
17394 return formatterFunc;
17395 }
17396
17397 cellRendered(cell){
17398 if(cell.modules.format && cell.modules.format.renderedCallback && !cell.modules.format.rendered){
17399 cell.modules.format.renderedCallback();
17400 cell.modules.format.rendered = true;
17401 }
17402 }
17403
17404 //return a formatted value for a column header
17405 formatHeader(column, title, el){
17406 var formatter, params, onRendered, mockCell;
17407
17408 if(column.definition.titleFormatter){
17409 formatter = this.lookupFormatter(column.definition.titleFormatter);
17410
17411 onRendered = (callback) => {
17412 column.titleFormatterRendered = callback;
17413 };
17414
17415 mockCell = {
17416 getValue:function(){
17417 return title;
17418 },
17419 getElement:function(){
17420 return el;
17421 },
17422 getType:function(){
17423 return "header";
17424 },
17425 getColumn:function(){
17426 return column.getComponent();
17427 },
17428 getTable:() => {
17429 return this.table;
17430 }
17431 };
17432
17433 params = column.definition.titleFormatterParams || {};
17434
17435 params = typeof params === "function" ? params() : params;
17436
17437 return formatter.call(this, mockCell, params, onRendered);
17438 }else {
17439 return title;
17440 }
17441 }
17442
17443
17444 //return a formatted value for a cell
17445 formatValue(cell){
17446 var component = cell.getComponent(),
17447 params = typeof cell.column.modules.format.params === "function" ? cell.column.modules.format.params(component) : cell.column.modules.format.params;
17448
17449 function onRendered(callback){
17450 if(!cell.modules.format){
17451 cell.modules.format = {};
17452 }
17453
17454 cell.modules.format.renderedCallback = callback;
17455 cell.modules.format.rendered = false;
17456 }
17457
17458 return cell.column.modules.format.formatter.call(this, component, params, onRendered);
17459 }
17460
17461 formatExportValue(cell, type){
17462 var formatter = cell.column.modules.format[type],
17463 params;
17464
17465 if(formatter){
17466 params = typeof formatter.params === "function" ? formatter.params(cell.getComponent()) : formatter.params;
17467
17468 function onRendered(callback){
17469 if(!cell.modules.format){
17470 cell.modules.format = {};
17471 }
17472
17473 cell.modules.format.renderedCallback = callback;
17474 cell.modules.format.rendered = false;
17475 }
17476
17477 return formatter.formatter.call(this, cell.getComponent(), params, onRendered);
17478
17479 }else {
17480 return this.formatValue(cell);
17481 }
17482 }
17483
17484 sanitizeHTML(value){
17485 if(value){
17486 var entityMap = {
17487 '&': '&amp;',
17488 '<': '&lt;',
17489 '>': '&gt;',
17490 '"': '&quot;',
17491 "'": '&#39;',
17492 '/': '&#x2F;',
17493 '`': '&#x60;',
17494 '=': '&#x3D;'
17495 };
17496
17497 return String(value).replace(/[&<>"'`=/]/g, function (s) {
17498 return entityMap[s];
17499 });
17500 }else {
17501 return value;
17502 }
17503 }
17504
17505 emptyToSpace(value){
17506 return value === null || typeof value === "undefined" || value === "" ? "&nbsp;" : value;
17507 }
17508
17509 }
17510
17511 class FrozenColumns extends Module{
17512
17513 static moduleName = "frozenColumns";
17514
17515 constructor(table){
17516 super(table);
17517
17518 this.leftColumns = [];
17519 this.rightColumns = [];
17520 this.initializationMode = "left";
17521 this.active = false;
17522 this.blocked = true;
17523
17524 this.registerColumnOption("frozen");
17525 }
17526
17527 //reset initial state
17528 reset(){
17529 this.initializationMode = "left";
17530 this.leftColumns = [];
17531 this.rightColumns = [];
17532 this.active = false;
17533 }
17534
17535 initialize(){
17536 this.subscribe("cell-layout", this.layoutCell.bind(this));
17537 this.subscribe("column-init", this.initializeColumn.bind(this));
17538 this.subscribe("column-width", this.layout.bind(this));
17539 this.subscribe("row-layout-after", this.layoutRow.bind(this));
17540 this.subscribe("table-layout", this.layout.bind(this));
17541 this.subscribe("columns-loading", this.reset.bind(this));
17542
17543 this.subscribe("column-add", this.reinitializeColumns.bind(this));
17544 this.subscribe("column-deleted", this.reinitializeColumns.bind(this));
17545 this.subscribe("column-hide", this.reinitializeColumns.bind(this));
17546 this.subscribe("column-show", this.reinitializeColumns.bind(this));
17547 this.subscribe("columns-loaded", this.reinitializeColumns.bind(this));
17548
17549 this.subscribe("table-redraw", this.layout.bind(this));
17550 this.subscribe("layout-refreshing", this.blockLayout.bind(this));
17551 this.subscribe("layout-refreshed", this.unblockLayout.bind(this));
17552 this.subscribe("scrollbar-vertical", this.adjustForScrollbar.bind(this));
17553 }
17554
17555 blockLayout(){
17556 this.blocked = true;
17557 }
17558
17559 unblockLayout(){
17560 this.blocked = false;
17561 }
17562
17563 layoutCell(cell){
17564 this.layoutElement(cell.element, cell.column);
17565 }
17566
17567 reinitializeColumns(){
17568 this.reset();
17569
17570 this.table.columnManager.columnsByIndex.forEach((column) => {
17571 this.initializeColumn(column);
17572 });
17573
17574 this.layout();
17575 }
17576
17577 //initialize specific column
17578 initializeColumn(column){
17579 var config = {margin:0, edge:false};
17580
17581 if(!column.isGroup){
17582 if(this.frozenCheck(column)){
17583 config.position = this.initializationMode;
17584
17585 if(this.initializationMode == "left"){
17586 this.leftColumns.push(column);
17587 }else {
17588 this.rightColumns.unshift(column);
17589 }
17590
17591 this.active = true;
17592
17593 column.modules.frozen = config;
17594 }else {
17595 this.initializationMode = "right";
17596 }
17597 }
17598 }
17599
17600 frozenCheck(column){
17601 if(column.parent.isGroup && column.definition.frozen){
17602 console.warn("Frozen Column Error - Parent column group must be frozen, not individual columns or sub column groups");
17603 }
17604
17605 if(column.parent.isGroup){
17606 return this.frozenCheck(column.parent);
17607 }else {
17608 return column.definition.frozen;
17609 }
17610 }
17611
17612 //layout calculation rows
17613 layoutCalcRows(){
17614 if(this.table.modExists("columnCalcs")){
17615 if(this.table.modules.columnCalcs.topInitialized && this.table.modules.columnCalcs.topRow){
17616 this.layoutRow(this.table.modules.columnCalcs.topRow);
17617 }
17618
17619 if(this.table.modules.columnCalcs.botInitialized && this.table.modules.columnCalcs.botRow){
17620 this.layoutRow(this.table.modules.columnCalcs.botRow);
17621 }
17622
17623 if(this.table.modExists("groupRows")){
17624 this.layoutGroupCalcs(this.table.modules.groupRows.getGroups());
17625 }
17626 }
17627 }
17628
17629 layoutGroupCalcs(groups){
17630 groups.forEach((group) => {
17631 if(group.calcs.top){
17632 this.layoutRow(group.calcs.top);
17633 }
17634
17635 if(group.calcs.bottom){
17636 this.layoutRow(group.calcs.bottom);
17637 }
17638
17639 if(group.groupList && group.groupList.length){
17640 this.layoutGroupCalcs(group.groupList);
17641 }
17642 });
17643 }
17644
17645 //calculate column positions and layout headers
17646 layoutColumnPosition(allCells){
17647 var leftParents = [];
17648
17649 var leftMargin = 0;
17650 var rightMargin = 0;
17651
17652 this.leftColumns.forEach((column, i) => {
17653 column.modules.frozen.marginValue = leftMargin;
17654 column.modules.frozen.margin = column.modules.frozen.marginValue + "px";
17655
17656 if(column.visible){
17657 leftMargin += column.getWidth();
17658 }
17659
17660 if(i == this.leftColumns.length - 1){
17661 column.modules.frozen.edge = true;
17662 }else {
17663 column.modules.frozen.edge = false;
17664 }
17665
17666 if(column.parent.isGroup){
17667 var parentEl = this.getColGroupParentElement(column);
17668 if(!leftParents.includes(parentEl)){
17669 this.layoutElement(parentEl, column);
17670 leftParents.push(parentEl);
17671 }
17672
17673 parentEl.classList.toggle("tabulator-frozen-left", column.modules.frozen.edge && column.modules.frozen.position === "left");
17674 parentEl.classList.toggle("tabulator-frozen-right", column.modules.frozen.edge && column.modules.frozen.position === "right");
17675 }else {
17676 this.layoutElement(column.getElement(), column);
17677 }
17678
17679 if(allCells){
17680 column.cells.forEach((cell) => {
17681 this.layoutElement(cell.getElement(true), column);
17682 });
17683 }
17684 });
17685
17686 this.rightColumns.forEach((column, i) => {
17687
17688 column.modules.frozen.marginValue = rightMargin;
17689 column.modules.frozen.margin = column.modules.frozen.marginValue + "px";
17690
17691 if(column.visible){
17692 rightMargin += column.getWidth();
17693 }
17694
17695 if(i == this.rightColumns.length - 1){
17696 column.modules.frozen.edge = true;
17697 }else {
17698 column.modules.frozen.edge = false;
17699 }
17700
17701 if(column.parent.isGroup){
17702 this.layoutElement(this.getColGroupParentElement(column), column);
17703 }else {
17704 this.layoutElement(column.getElement(), column);
17705 }
17706
17707 if(allCells){
17708 column.cells.forEach((cell) => {
17709 this.layoutElement(cell.getElement(true), column);
17710 });
17711 }
17712 });
17713 }
17714
17715 getColGroupParentElement(column){
17716 return column.parent.isGroup ? this.getColGroupParentElement(column.parent) : column.getElement();
17717 }
17718
17719 //layout columns appropriately
17720 layout(){
17721 if(this.active && !this.blocked){
17722 //calculate left columns
17723 this.layoutColumnPosition();
17724
17725 this.reinitializeRows();
17726
17727 this.layoutCalcRows();
17728 }
17729 }
17730
17731 reinitializeRows(){
17732 var visibleRows = this.table.rowManager.getVisibleRows(true);
17733 var otherRows = this.table.rowManager.getRows().filter(row => !visibleRows.includes(row));
17734
17735 otherRows.forEach((row) =>{
17736 row.deinitialize();
17737 });
17738
17739 visibleRows.forEach((row) =>{
17740 if(row.type === "row"){
17741 this.layoutRow(row);
17742 }
17743 });
17744 }
17745
17746 layoutRow(row){
17747 if(this.table.options.layout === "fitDataFill" && this.rightColumns.length){
17748 this.table.rowManager.getTableElement().style.minWidth = "calc(100% - " + this.rightMargin + ")";
17749 }
17750
17751 this.leftColumns.forEach((column) => {
17752 var cell = row.getCell(column);
17753
17754 if(cell){
17755 this.layoutElement(cell.getElement(true), column);
17756 }
17757 });
17758
17759 this.rightColumns.forEach((column) => {
17760 var cell = row.getCell(column);
17761
17762 if(cell){
17763 this.layoutElement(cell.getElement(true), column);
17764 }
17765 });
17766 }
17767
17768 layoutElement(element, column){
17769 var position;
17770
17771 if(column.modules.frozen && element){
17772 element.style.position = "sticky";
17773
17774 if(this.table.rtl){
17775 position = column.modules.frozen.position === "left" ? "right" : "left";
17776 }else {
17777 position = column.modules.frozen.position;
17778 }
17779
17780 element.style[position] = column.modules.frozen.margin;
17781
17782 element.classList.add("tabulator-frozen");
17783
17784 element.classList.toggle("tabulator-frozen-left", column.modules.frozen.edge && column.modules.frozen.position === "left");
17785 element.classList.toggle("tabulator-frozen-right", column.modules.frozen.edge && column.modules.frozen.position === "right");
17786 }
17787 }
17788
17789 adjustForScrollbar(width){
17790 if(this.rightColumns.length){
17791 this.table.columnManager.getContentsElement().style.width = "calc(100% - " + width + "px)";
17792 }
17793 }
17794
17795 getFrozenColumns(){
17796 return this.leftColumns.concat(this.rightColumns);
17797 }
17798
17799 _calcSpace(columns, index){
17800 var width = 0;
17801
17802 for (let i = 0; i < index; i++){
17803 if(columns[i].visible){
17804 width += columns[i].getWidth();
17805 }
17806 }
17807
17808 return width;
17809 }
17810 }
17811
17812 class FrozenRows extends Module{
17813
17814 static moduleName = "frozenRows";
17815
17816 constructor(table){
17817 super(table);
17818
17819 this.topElement = document.createElement("div");
17820 this.rows = [];
17821
17822 //register component functions
17823 this.registerComponentFunction("row", "freeze", this.freezeRow.bind(this));
17824 this.registerComponentFunction("row", "unfreeze", this.unfreezeRow.bind(this));
17825 this.registerComponentFunction("row", "isFrozen", this.isRowFrozen.bind(this));
17826
17827 //register table options
17828 this.registerTableOption("frozenRowsField", "id"); //field to choose frozen rows by
17829 this.registerTableOption("frozenRows", false); //holder for frozen row identifiers
17830 }
17831
17832 initialize(){
17833 var fragment = document.createDocumentFragment();
17834
17835 this.rows = [];
17836
17837 this.topElement.classList.add("tabulator-frozen-rows-holder");
17838
17839 // Replaced by adding padding-top to the tabulator-frozen-rows-holder
17840 // See https://github.com/olifolkerd/tabulator/pull/4809
17841 //fragment.appendChild(document.createElement("br"));
17842 fragment.appendChild(this.topElement);
17843
17844 // this.table.columnManager.element.append(this.topElement);
17845 this.table.columnManager.getContentsElement().insertBefore(fragment, this.table.columnManager.headersElement.nextSibling);
17846
17847 this.subscribe("row-deleting", this.detachRow.bind(this));
17848 this.subscribe("rows-visible", this.visibleRows.bind(this));
17849
17850 this.registerDisplayHandler(this.getRows.bind(this), 10);
17851
17852 if(this.table.options.frozenRows){
17853 this.subscribe("data-processed", this.initializeRows.bind(this));
17854 this.subscribe("row-added", this.initializeRow.bind(this));
17855 this.subscribe("table-redrawing", this.resizeHolderWidth.bind(this));
17856 this.subscribe("column-resized", this.resizeHolderWidth.bind(this));
17857 this.subscribe("column-show", this.resizeHolderWidth.bind(this));
17858 this.subscribe("column-hide", this.resizeHolderWidth.bind(this));
17859 }
17860
17861 this.resizeHolderWidth();
17862 }
17863
17864 resizeHolderWidth(){
17865 this.topElement.style.minWidth = this.table.columnManager.headersElement.offsetWidth + "px";
17866 }
17867
17868 initializeRows(){
17869 this.table.rowManager.getRows().forEach((row) => {
17870 this.initializeRow(row);
17871 });
17872 }
17873
17874 initializeRow(row){
17875 var frozenRows = this.table.options.frozenRows,
17876 rowType = typeof frozenRows;
17877
17878 if(rowType === "number"){
17879 if(row.getPosition() && (row.getPosition() + this.rows.length) <= frozenRows){
17880 this.freezeRow(row);
17881 }
17882 }else if(rowType === "function"){
17883 if(frozenRows.call(this.table, row.getComponent())){
17884 this.freezeRow(row);
17885 }
17886 }else if(Array.isArray(frozenRows)){
17887 if(frozenRows.includes(row.data[this.options("frozenRowsField")])){
17888 this.freezeRow(row);
17889 }
17890 }
17891 }
17892
17893 isRowFrozen(row){
17894 var index = this.rows.indexOf(row);
17895 return index > -1;
17896 }
17897
17898 isFrozen(){
17899 return !!this.rows.length;
17900 }
17901
17902 visibleRows(viewable, rows){
17903 this.rows.forEach((row) => {
17904 rows.push(row);
17905 });
17906
17907 return rows;
17908 }
17909
17910 //filter frozen rows out of display data
17911 getRows(rows){
17912 var output = rows.slice(0);
17913
17914 this.rows.forEach(function(row){
17915 var index = output.indexOf(row);
17916
17917 if(index > -1){
17918 output.splice(index, 1);
17919 }
17920 });
17921
17922 return output;
17923 }
17924
17925 freezeRow(row){
17926 if(!row.modules.frozen){
17927 row.modules.frozen = true;
17928 this.topElement.appendChild(row.getElement());
17929 row.initialize();
17930 row.normalizeHeight();
17931
17932 this.rows.push(row);
17933
17934 this.refreshData(false, "display");
17935
17936 this.table.rowManager.adjustTableSize();
17937
17938 this.styleRows();
17939
17940 }else {
17941 console.warn("Freeze Error - Row is already frozen");
17942 }
17943 }
17944
17945 unfreezeRow(row){
17946 if(row.modules.frozen){
17947
17948 row.modules.frozen = false;
17949
17950 this.detachRow(row);
17951
17952 this.table.rowManager.adjustTableSize();
17953
17954 this.refreshData(false, "display");
17955
17956 if(this.rows.length){
17957 this.styleRows();
17958 }
17959
17960 }else {
17961 console.warn("Freeze Error - Row is already unfrozen");
17962 }
17963 }
17964
17965 detachRow(row){
17966 var index = this.rows.indexOf(row);
17967
17968 if(index > -1){
17969 var rowEl = row.getElement();
17970
17971 if(rowEl.parentNode){
17972 rowEl.parentNode.removeChild(rowEl);
17973 }
17974
17975 this.rows.splice(index, 1);
17976 }
17977 }
17978
17979 styleRows(row){
17980 this.rows.forEach((row, i) => {
17981 this.table.rowManager.styleRow(row, i);
17982 });
17983 }
17984 }
17985
17986 //public group object
17987 class GroupComponent {
17988 constructor (group){
17989 this._group = group;
17990 this.type = "GroupComponent";
17991
17992 return new Proxy(this, {
17993 get: function(target, name, receiver) {
17994 if (typeof target[name] !== "undefined") {
17995 return target[name];
17996 }else {
17997 return target._group.groupManager.table.componentFunctionBinder.handle("group", target._group, name);
17998 }
17999 }
18000 });
18001 }
18002
18003 getKey(){
18004 return this._group.key;
18005 }
18006
18007 getField(){
18008 return this._group.field;
18009 }
18010
18011 getElement(){
18012 return this._group.element;
18013 }
18014
18015 getRows(){
18016 return this._group.getRows(true);
18017 }
18018
18019 getSubGroups(){
18020 return this._group.getSubGroups(true);
18021 }
18022
18023 getParentGroup(){
18024 return this._group.parent ? this._group.parent.getComponent() : false;
18025 }
18026
18027 isVisible(){
18028 return this._group.visible;
18029 }
18030
18031 show(){
18032 this._group.show();
18033 }
18034
18035 hide(){
18036 this._group.hide();
18037 }
18038
18039 toggle(){
18040 this._group.toggleVisibility();
18041 }
18042
18043 scrollTo(position, ifVisible){
18044 return this._group.groupManager.table.rowManager.scrollToRow(this._group, position, ifVisible);
18045 }
18046
18047 _getSelf(){
18048 return this._group;
18049 }
18050
18051 getTable(){
18052 return this._group.groupManager.table;
18053 }
18054 }
18055
18056 //Group functions
18057 class Group{
18058
18059 constructor(groupManager, parent, level, key, field, generator, oldGroup){
18060 this.groupManager = groupManager;
18061 this.parent = parent;
18062 this.key = key;
18063 this.level = level;
18064 this.field = field;
18065 this.hasSubGroups = level < (groupManager.groupIDLookups.length - 1);
18066 this.addRow = this.hasSubGroups ? this._addRowToGroup : this._addRow;
18067 this.type = "group"; //type of element
18068 this.old = oldGroup;
18069 this.rows = [];
18070 this.groups = [];
18071 this.groupList = [];
18072 this.generator = generator;
18073 this.element = false;
18074 this.elementContents = false;
18075 this.height = 0;
18076 this.outerHeight = 0;
18077 this.initialized = false;
18078 this.calcs = {};
18079 this.initialized = false;
18080 this.modules = {};
18081 this.arrowElement = false;
18082
18083 this.visible = oldGroup ? oldGroup.visible : (typeof groupManager.startOpen[level] !== "undefined" ? groupManager.startOpen[level] : groupManager.startOpen[0]);
18084
18085 this.component = null;
18086
18087 this.createElements();
18088 this.addBindings();
18089
18090 this.createValueGroups();
18091 }
18092
18093 wipe(elementsOnly){
18094 if(!elementsOnly){
18095 if(this.groupList.length){
18096 this.groupList.forEach(function(group){
18097 group.wipe();
18098 });
18099 }else {
18100 this.rows.forEach((row) => {
18101 if(row.modules){
18102 delete row.modules.group;
18103 }
18104 });
18105 }
18106 }
18107
18108 this.element = false;
18109 this.arrowElement = false;
18110 this.elementContents = false;
18111 }
18112
18113 createElements(){
18114 var arrow = document.createElement("div");
18115 arrow.classList.add("tabulator-arrow");
18116
18117 this.element = document.createElement("div");
18118 this.element.classList.add("tabulator-row");
18119 this.element.classList.add("tabulator-group");
18120 this.element.classList.add("tabulator-group-level-" + this.level);
18121 this.element.setAttribute("role", "rowgroup");
18122
18123 this.arrowElement = document.createElement("div");
18124 this.arrowElement.classList.add("tabulator-group-toggle");
18125 this.arrowElement.appendChild(arrow);
18126
18127 //setup movable rows
18128 if(this.groupManager.table.options.movableRows !== false && this.groupManager.table.modExists("moveRow")){
18129 this.groupManager.table.modules.moveRow.initializeGroupHeader(this);
18130 }
18131 }
18132
18133 createValueGroups(){
18134 var level = this.level + 1;
18135 if(this.groupManager.allowedValues && this.groupManager.allowedValues[level]){
18136 this.groupManager.allowedValues[level].forEach((value) => {
18137 this._createGroup(value, level);
18138 });
18139 }
18140 }
18141
18142 addBindings(){
18143 var toggleElement;
18144
18145 if(this.groupManager.table.options.groupToggleElement){
18146 toggleElement = this.groupManager.table.options.groupToggleElement == "arrow" ? this.arrowElement : this.element;
18147
18148 toggleElement.addEventListener("click", (e) => {
18149 if(this.groupManager.table.options.groupToggleElement === "arrow"){
18150 e.stopPropagation();
18151 e.stopImmediatePropagation();
18152 }
18153
18154 //allow click event to propagate before toggling visibility
18155 setTimeout(() => {
18156 this.toggleVisibility();
18157 });
18158 });
18159 }
18160 }
18161
18162 _createGroup(groupID, level){
18163 var groupKey = level + "_" + groupID;
18164 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);
18165
18166 this.groups[groupKey] = group;
18167 this.groupList.push(group);
18168 }
18169
18170 _addRowToGroup(row){
18171
18172 var level = this.level + 1;
18173
18174 if(this.hasSubGroups){
18175 var groupID = this.groupManager.groupIDLookups[level].func(row.getData()),
18176 groupKey = level + "_" + groupID;
18177
18178 if(this.groupManager.allowedValues && this.groupManager.allowedValues[level]){
18179 if(this.groups[groupKey]){
18180 this.groups[groupKey].addRow(row);
18181 }
18182 }else {
18183 if(!this.groups[groupKey]){
18184 this._createGroup(groupID, level);
18185 }
18186
18187 this.groups[groupKey].addRow(row);
18188 }
18189 }
18190 }
18191
18192 _addRow(row){
18193 this.rows.push(row);
18194 row.modules.group = this;
18195 }
18196
18197 insertRow(row, to, after){
18198 var data = this.conformRowData({});
18199
18200 row.updateData(data);
18201
18202 var toIndex = this.rows.indexOf(to);
18203
18204 if(toIndex > -1){
18205 if(after){
18206 this.rows.splice(toIndex+1, 0, row);
18207 }else {
18208 this.rows.splice(toIndex, 0, row);
18209 }
18210 }else {
18211 if(after){
18212 this.rows.push(row);
18213 }else {
18214 this.rows.unshift(row);
18215 }
18216 }
18217
18218 row.modules.group = this;
18219
18220 // this.generateGroupHeaderContents();
18221
18222 if(this.groupManager.table.modExists("columnCalcs") && this.groupManager.table.options.columnCalcs != "table"){
18223 this.groupManager.table.modules.columnCalcs.recalcGroup(this);
18224 }
18225
18226 this.groupManager.updateGroupRows(true);
18227 }
18228
18229 scrollHeader(left){
18230 if(this.arrowElement){
18231 this.arrowElement.style.marginLeft = left;
18232
18233 this.groupList.forEach(function(child){
18234 child.scrollHeader(left);
18235 });
18236 }
18237 }
18238
18239 getRowIndex(row){}
18240
18241 //update row data to match grouping constraints
18242 conformRowData(data){
18243 if(this.field){
18244 data[this.field] = this.key;
18245 }else {
18246 console.warn("Data Conforming Error - Cannot conform row data to match new group as groupBy is a function");
18247 }
18248
18249 if(this.parent){
18250 data = this.parent.conformRowData(data);
18251 }
18252
18253 return data;
18254 }
18255
18256 removeRow(row){
18257 var index = this.rows.indexOf(row);
18258 var el = row.getElement();
18259
18260 if(index > -1){
18261 this.rows.splice(index, 1);
18262 }
18263
18264 if(!this.groupManager.table.options.groupValues && !this.rows.length){
18265 if(this.parent){
18266 this.parent.removeGroup(this);
18267 }else {
18268 this.groupManager.removeGroup(this);
18269 }
18270
18271 this.groupManager.updateGroupRows(true);
18272
18273 }else {
18274
18275 if(el.parentNode){
18276 el.parentNode.removeChild(el);
18277 }
18278
18279 if(!this.groupManager.blockRedraw){
18280 this.generateGroupHeaderContents();
18281
18282 if(this.groupManager.table.modExists("columnCalcs") && this.groupManager.table.options.columnCalcs != "table"){
18283 this.groupManager.table.modules.columnCalcs.recalcGroup(this);
18284 }
18285 }
18286
18287 }
18288 }
18289
18290 removeGroup(group){
18291 var groupKey = group.level + "_" + group.key,
18292 index;
18293
18294 if(this.groups[groupKey]){
18295 delete this.groups[groupKey];
18296
18297 index = this.groupList.indexOf(group);
18298
18299 if(index > -1){
18300 this.groupList.splice(index, 1);
18301 }
18302
18303 if(!this.groupList.length){
18304 if(this.parent){
18305 this.parent.removeGroup(this);
18306 }else {
18307 this.groupManager.removeGroup(this);
18308 }
18309 }
18310 }
18311 }
18312
18313 getHeadersAndRows(){
18314 var output = [];
18315
18316 output.push(this);
18317
18318 this._visSet();
18319
18320
18321 if(this.calcs.top){
18322 this.calcs.top.detachElement();
18323 this.calcs.top.deleteCells();
18324 }
18325
18326 if(this.calcs.bottom){
18327 this.calcs.bottom.detachElement();
18328 this.calcs.bottom.deleteCells();
18329 }
18330
18331
18332
18333 if(this.visible){
18334 if(this.groupList.length){
18335 this.groupList.forEach(function(group){
18336 output = output.concat(group.getHeadersAndRows());
18337 });
18338
18339 }else {
18340 if(this.groupManager.table.options.columnCalcs != "table" && this.groupManager.table.modExists("columnCalcs") && this.groupManager.table.modules.columnCalcs.hasTopCalcs()){
18341 this.calcs.top = this.groupManager.table.modules.columnCalcs.generateTopRow(this.rows);
18342 output.push(this.calcs.top);
18343 }
18344
18345 output = output.concat(this.rows);
18346
18347 if(this.groupManager.table.options.columnCalcs != "table" && this.groupManager.table.modExists("columnCalcs") && this.groupManager.table.modules.columnCalcs.hasBottomCalcs()){
18348 this.calcs.bottom = this.groupManager.table.modules.columnCalcs.generateBottomRow(this.rows);
18349 output.push(this.calcs.bottom);
18350 }
18351 }
18352 }else {
18353 if(!this.groupList.length && this.groupManager.table.options.columnCalcs != "table"){
18354
18355 if(this.groupManager.table.modExists("columnCalcs")){
18356 if(this.groupManager.table.modules.columnCalcs.hasTopCalcs()){
18357 if(this.groupManager.table.options.groupClosedShowCalcs){
18358 this.calcs.top = this.groupManager.table.modules.columnCalcs.generateTopRow(this.rows);
18359 output.push(this.calcs.top);
18360 }
18361 }
18362
18363 if(this.groupManager.table.modules.columnCalcs.hasBottomCalcs()){
18364 if(this.groupManager.table.options.groupClosedShowCalcs){
18365 this.calcs.bottom = this.groupManager.table.modules.columnCalcs.generateBottomRow(this.rows);
18366 output.push(this.calcs.bottom);
18367 }
18368 }
18369 }
18370 }
18371
18372 }
18373
18374 return output;
18375 }
18376
18377 getData(visible, transform){
18378 var output = [];
18379
18380 this._visSet();
18381
18382 if(!visible || (visible && this.visible)){
18383 this.rows.forEach((row) => {
18384 output.push(row.getData(transform || "data"));
18385 });
18386 }
18387
18388 return output;
18389 }
18390
18391 getRowCount(){
18392 var count = 0;
18393
18394 if(this.groupList.length){
18395 this.groupList.forEach((group) => {
18396 count += group.getRowCount();
18397 });
18398 }else {
18399 count = this.rows.length;
18400 }
18401 return count;
18402 }
18403
18404
18405 toggleVisibility(){
18406 if(this.visible){
18407 this.hide();
18408 }else {
18409 this.show();
18410 }
18411 }
18412
18413 hide(){
18414 this.visible = false;
18415
18416 if(this.groupManager.table.rowManager.getRenderMode() == "basic" && !this.groupManager.table.options.pagination){
18417
18418 this.element.classList.remove("tabulator-group-visible");
18419
18420 if(this.groupList.length){
18421 this.groupList.forEach((group) => {
18422
18423 var rows = group.getHeadersAndRows();
18424
18425 rows.forEach((row) => {
18426 row.detachElement();
18427 });
18428 });
18429
18430 }else {
18431 this.rows.forEach((row) => {
18432 var rowEl = row.getElement();
18433 rowEl.parentNode.removeChild(rowEl);
18434 });
18435 }
18436
18437 this.groupManager.updateGroupRows(true);
18438
18439 }else {
18440 this.groupManager.updateGroupRows(true);
18441 }
18442
18443 this.groupManager.table.externalEvents.dispatch("groupVisibilityChanged", this.getComponent(), false);
18444 }
18445
18446 show(){
18447 this.visible = true;
18448
18449 if(this.groupManager.table.rowManager.getRenderMode() == "basic" && !this.groupManager.table.options.pagination){
18450
18451 this.element.classList.add("tabulator-group-visible");
18452
18453 var prev = this.generateElement();
18454
18455 if(this.groupList.length){
18456 this.groupList.forEach((group) => {
18457 var rows = group.getHeadersAndRows();
18458
18459 rows.forEach((row) => {
18460 var rowEl = row.getElement();
18461 prev.parentNode.insertBefore(rowEl, prev.nextSibling);
18462 row.initialize();
18463 prev = rowEl;
18464 });
18465 });
18466
18467 }else {
18468 this.rows.forEach((row) => {
18469 var rowEl = row.getElement();
18470 prev.parentNode.insertBefore(rowEl, prev.nextSibling);
18471 row.initialize();
18472 prev = rowEl;
18473 });
18474 }
18475
18476 this.groupManager.updateGroupRows(true);
18477 }else {
18478 this.groupManager.updateGroupRows(true);
18479 }
18480
18481 this.groupManager.table.externalEvents.dispatch("groupVisibilityChanged", this.getComponent(), true);
18482 }
18483
18484 _visSet(){
18485 var data = [];
18486
18487 if(typeof this.visible == "function"){
18488
18489 this.rows.forEach(function(row){
18490 data.push(row.getData());
18491 });
18492
18493 this.visible = this.visible(this.key, this.getRowCount(), data, this.getComponent());
18494 }
18495 }
18496
18497 getRowGroup(row){
18498 var match = false;
18499 if(this.groupList.length){
18500 this.groupList.forEach(function(group){
18501 var result = group.getRowGroup(row);
18502
18503 if(result){
18504 match = result;
18505 }
18506 });
18507 }else {
18508 if(this.rows.find(function(item){
18509 return item === row;
18510 })){
18511 match = this;
18512 }
18513 }
18514
18515 return match;
18516 }
18517
18518 getSubGroups(component){
18519 var output = [];
18520
18521 this.groupList.forEach(function(child){
18522 output.push(component ? child.getComponent() : child);
18523 });
18524
18525 return output;
18526 }
18527
18528 getRows(component, includeChildren){
18529 var output = [];
18530
18531 if(includeChildren && this.groupList.length){
18532 this.groupList.forEach((group) => {
18533 output = output.concat(group.getRows(component, includeChildren));
18534 });
18535 }else {
18536 this.rows.forEach(function(row){
18537 output.push(component ? row.getComponent() : row);
18538 });
18539 }
18540
18541 return output;
18542 }
18543
18544 generateGroupHeaderContents(){
18545 var data = [];
18546
18547 var rows = this.getRows(false, true);
18548
18549 rows.forEach(function(row){
18550 data.push(row.getData());
18551 });
18552
18553 this.elementContents = this.generator(this.key, this.getRowCount(), data, this.getComponent());
18554
18555 while(this.element.firstChild) this.element.removeChild(this.element.firstChild);
18556
18557 if(typeof this.elementContents === "string"){
18558 this.element.innerHTML = this.elementContents;
18559 }else {
18560 this.element.appendChild(this.elementContents);
18561 }
18562
18563 this.element.insertBefore(this.arrowElement, this.element.firstChild);
18564 }
18565
18566 getPath(path = []) {
18567 path.unshift(this.key);
18568 if(this.parent) {
18569 this.parent.getPath(path);
18570 }
18571 return path;
18572 }
18573
18574 ////////////// Standard Row Functions //////////////
18575
18576 getElement(){
18577 return this.elementContents ? this.element : this.generateElement();
18578 }
18579
18580 generateElement(){
18581 this.addBindings = false;
18582
18583 this._visSet();
18584
18585 if(this.visible){
18586 this.element.classList.add("tabulator-group-visible");
18587 }else {
18588 this.element.classList.remove("tabulator-group-visible");
18589 }
18590
18591 for(var i = 0; i < this.element.childNodes.length; ++i){
18592 this.element.childNodes[i].parentNode.removeChild(this.element.childNodes[i]);
18593 }
18594
18595 this.generateGroupHeaderContents();
18596
18597 // this.addBindings();
18598
18599 return this.element;
18600 }
18601
18602 detachElement(){
18603 if (this.element && this.element.parentNode){
18604 this.element.parentNode.removeChild(this.element);
18605 }
18606 }
18607
18608 //normalize the height of elements in the row
18609 normalizeHeight(){
18610 this.setHeight(this.element.clientHeight);
18611 }
18612
18613 initialize(force){
18614 if(!this.initialized || force){
18615 this.normalizeHeight();
18616 this.initialized = true;
18617 }
18618 }
18619
18620 reinitialize(){
18621 this.initialized = false;
18622 this.height = 0;
18623
18624 if(Helpers.elVisible(this.element)){
18625 this.initialize(true);
18626 }
18627 }
18628
18629 setHeight(height){
18630 if(this.height != height){
18631 this.height = height;
18632 this.outerHeight = this.element.offsetHeight;
18633 }
18634 }
18635
18636 //return rows outer height
18637 getHeight(){
18638 return this.outerHeight;
18639 }
18640
18641 getGroup(){
18642 return this;
18643 }
18644
18645 reinitializeHeight(){}
18646
18647 calcHeight(){}
18648
18649 setCellHeight(){}
18650
18651 clearCellHeight(){}
18652
18653 deinitializeHeight(){}
18654
18655 rendered(){}
18656
18657 //////////////// Object Generation /////////////////
18658 getComponent(){
18659 if(!this.component){
18660 this.component = new GroupComponent(this);
18661 }
18662
18663 return this.component;
18664 }
18665 }
18666
18667 class GroupRows extends Module{
18668
18669 static moduleName = "groupRows";
18670
18671 constructor(table){
18672 super(table);
18673
18674 this.groupIDLookups = false; //enable table grouping and set field to group by
18675 this.startOpen = [function(){return false;}]; //starting state of group
18676 this.headerGenerator = [function(){return "";}];
18677 this.groupList = []; //ordered list of groups
18678 this.allowedValues = false;
18679 this.groups = {}; //hold row groups
18680
18681 this.displayHandler = this.getRows.bind(this);
18682
18683 this.blockRedraw = false;
18684
18685 //register table options
18686 this.registerTableOption("groupBy", false); //enable table grouping and set field to group by
18687 this.registerTableOption("groupStartOpen", true); //starting state of group
18688 this.registerTableOption("groupValues", false);
18689 this.registerTableOption("groupUpdateOnCellEdit", false);
18690 this.registerTableOption("groupHeader", false); //header generation function
18691 this.registerTableOption("groupHeaderPrint", null);
18692 this.registerTableOption("groupHeaderClipboard", null);
18693 this.registerTableOption("groupHeaderHtmlOutput", null);
18694 this.registerTableOption("groupHeaderDownload", null);
18695 this.registerTableOption("groupToggleElement", "arrow");
18696 this.registerTableOption("groupClosedShowCalcs", false);
18697
18698 //register table functions
18699 this.registerTableFunction("setGroupBy", this.setGroupBy.bind(this));
18700 this.registerTableFunction("setGroupValues", this.setGroupValues.bind(this));
18701 this.registerTableFunction("setGroupStartOpen", this.setGroupStartOpen.bind(this));
18702 this.registerTableFunction("setGroupHeader", this.setGroupHeader.bind(this));
18703 this.registerTableFunction("getGroups", this.userGetGroups.bind(this));
18704 this.registerTableFunction("getGroupedData", this.userGetGroupedData.bind(this));
18705
18706 //register component functions
18707 this.registerComponentFunction("row", "getGroup", this.rowGetGroup.bind(this));
18708 }
18709
18710 //initialize group configuration
18711 initialize(){
18712 this.subscribe("table-destroy", this._blockRedrawing.bind(this));
18713 this.subscribe("rows-wipe", this._blockRedrawing.bind(this));
18714 this.subscribe("rows-wiped", this._restore_redrawing.bind(this));
18715
18716 if(this.table.options.groupBy){
18717 if(this.table.options.groupUpdateOnCellEdit){
18718 this.subscribe("cell-value-updated", this.cellUpdated.bind(this));
18719 this.subscribe("row-data-changed", this.reassignRowToGroup.bind(this), 0);
18720 }
18721
18722 this.subscribe("table-built", this.configureGroupSetup.bind(this));
18723
18724 this.subscribe("row-deleting", this.rowDeleting.bind(this));
18725 this.subscribe("row-deleted", this.rowsUpdated.bind(this));
18726 this.subscribe("scroll-horizontal", this.scrollHeaders.bind(this));
18727 this.subscribe("rows-wipe", this.wipe.bind(this));
18728 this.subscribe("rows-added", this.rowsUpdated.bind(this));
18729 this.subscribe("row-moving", this.rowMoving.bind(this));
18730 this.subscribe("row-adding-index", this.rowAddingIndex.bind(this));
18731
18732 this.subscribe("rows-sample", this.rowSample.bind(this));
18733
18734 this.subscribe("render-virtual-fill", this.virtualRenderFill.bind(this));
18735
18736 this.registerDisplayHandler(this.displayHandler, 20);
18737
18738 this.initialized = true;
18739 }
18740 }
18741
18742 _blockRedrawing(){
18743 this.blockRedraw = true;
18744 }
18745
18746 _restore_redrawing(){
18747 this.blockRedraw = false;
18748 }
18749
18750 configureGroupSetup(){
18751 if(this.table.options.groupBy){
18752 var groupBy = this.table.options.groupBy,
18753 startOpen = this.table.options.groupStartOpen,
18754 groupHeader = this.table.options.groupHeader;
18755
18756 this.allowedValues = this.table.options.groupValues;
18757
18758 if(Array.isArray(groupBy) && Array.isArray(groupHeader) && groupBy.length > groupHeader.length){
18759 console.warn("Error creating group headers, groupHeader array is shorter than groupBy array");
18760 }
18761
18762 this.headerGenerator = [function(){return "";}];
18763 this.startOpen = [function(){return false;}]; //starting state of group
18764
18765 this.langBind("groups|item", (langValue, lang) => {
18766 this.headerGenerator[0] = (value, count, data) => { //header layout function
18767 return (typeof value === "undefined" ? "" : value) + "<span>(" + count + " " + ((count === 1) ? langValue : lang.groups.items) + ")</span>";
18768 };
18769 });
18770
18771 this.groupIDLookups = [];
18772
18773 if(groupBy){
18774 if(this.table.modExists("columnCalcs") && this.table.options.columnCalcs != "table" && this.table.options.columnCalcs != "both"){
18775 this.table.modules.columnCalcs.removeCalcs();
18776 }
18777 }else {
18778 if(this.table.modExists("columnCalcs") && this.table.options.columnCalcs != "group"){
18779
18780 var cols = this.table.columnManager.getRealColumns();
18781
18782 cols.forEach((col) => {
18783 if(col.definition.topCalc){
18784 this.table.modules.columnCalcs.initializeTopRow();
18785 }
18786
18787 if(col.definition.bottomCalc){
18788 this.table.modules.columnCalcs.initializeBottomRow();
18789 }
18790 });
18791 }
18792 }
18793
18794 if(!Array.isArray(groupBy)){
18795 groupBy = [groupBy];
18796 }
18797
18798 groupBy.forEach((group, i) => {
18799 var lookupFunc, column;
18800
18801 if(typeof group == "function"){
18802 lookupFunc = group;
18803 }else {
18804 column = this.table.columnManager.getColumnByField(group);
18805
18806 if(column){
18807 lookupFunc = function(data){
18808 return column.getFieldValue(data);
18809 };
18810 }else {
18811 lookupFunc = function(data){
18812 return data[group];
18813 };
18814 }
18815 }
18816
18817 this.groupIDLookups.push({
18818 field: typeof group === "function" ? false : group,
18819 func:lookupFunc,
18820 values:this.allowedValues ? this.allowedValues[i] : false,
18821 });
18822 });
18823
18824 if(startOpen){
18825 if(!Array.isArray(startOpen)){
18826 startOpen = [startOpen];
18827 }
18828
18829 startOpen.forEach((level) => {
18830 });
18831
18832 this.startOpen = startOpen;
18833 }
18834
18835 if(groupHeader){
18836 this.headerGenerator = Array.isArray(groupHeader) ? groupHeader : [groupHeader];
18837 }
18838 }else {
18839 this.groupList = [];
18840 this.groups = {};
18841 }
18842 }
18843
18844 rowSample(rows, prevValue){
18845 if(this.table.options.groupBy){
18846 var group = this.getGroups(false)[0];
18847
18848 prevValue.push(group.getRows(false)[0]);
18849 }
18850
18851 return prevValue;
18852 }
18853
18854 virtualRenderFill(){
18855 var el = this.table.rowManager.tableElement;
18856 var rows = this.table.rowManager.getVisibleRows();
18857
18858 if(this.table.options.groupBy){
18859 rows = rows.filter((row) => {
18860 return row.type !== "group";
18861 });
18862
18863 el.style.minWidth = !rows.length ? this.table.columnManager.getWidth() + "px" : "";
18864 }else {
18865 return rows;
18866 }
18867 }
18868
18869 rowAddingIndex(row, index, top){
18870 if(this.table.options.groupBy){
18871 this.assignRowToGroup(row);
18872
18873 var groupRows = row.modules.group.rows;
18874
18875 if(groupRows.length > 1){
18876 if(!index || (index && groupRows.indexOf(index) == -1)){
18877 if(top){
18878 if(groupRows[0] !== row){
18879 index = groupRows[0];
18880 this.table.rowManager.moveRowInArray(row.modules.group.rows, row, index, !top);
18881 }
18882 }else {
18883 if(groupRows[groupRows.length -1] !== row){
18884 index = groupRows[groupRows.length -1];
18885 this.table.rowManager.moveRowInArray(row.modules.group.rows, row, index, !top);
18886 }
18887 }
18888 }else {
18889 this.table.rowManager.moveRowInArray(row.modules.group.rows, row, index, !top);
18890 }
18891 }
18892
18893 return index;
18894 }
18895 }
18896
18897 trackChanges(){
18898 this.dispatch("group-changed");
18899 }
18900
18901 ///////////////////////////////////
18902 ///////// Table Functions /////////
18903 ///////////////////////////////////
18904
18905 setGroupBy(groups){
18906 this.table.options.groupBy = groups;
18907
18908 if(!this.initialized){
18909 this.initialize();
18910 }
18911
18912 this.configureGroupSetup();
18913
18914 if(!groups && this.table.modExists("columnCalcs") && this.table.options.columnCalcs === true){
18915 this.table.modules.columnCalcs.reinitializeCalcs();
18916 }
18917
18918 this.refreshData();
18919
18920 this.trackChanges();
18921 }
18922
18923 setGroupValues(groupValues){
18924 this.table.options.groupValues = groupValues;
18925 this.configureGroupSetup();
18926 this.refreshData();
18927
18928 this.trackChanges();
18929 }
18930
18931 setGroupStartOpen(values){
18932 this.table.options.groupStartOpen = values;
18933 this.configureGroupSetup();
18934
18935 if(this.table.options.groupBy){
18936 this.refreshData();
18937
18938 this.trackChanges();
18939 }else {
18940 console.warn("Grouping Update - cant refresh view, no groups have been set");
18941 }
18942 }
18943
18944 setGroupHeader(values){
18945 this.table.options.groupHeader = values;
18946 this.configureGroupSetup();
18947
18948 if(this.table.options.groupBy){
18949 this.refreshData();
18950
18951 this.trackChanges();
18952 }else {
18953 console.warn("Grouping Update - cant refresh view, no groups have been set");
18954 }
18955 }
18956
18957 userGetGroups(values){
18958 return this.getGroups(true);
18959 }
18960
18961 // get grouped table data in the same format as getData()
18962 userGetGroupedData(){
18963 return this.table.options.groupBy ? this.getGroupedData() : this.getData();
18964 }
18965
18966
18967 ///////////////////////////////////////
18968 ///////// Component Functions /////////
18969 ///////////////////////////////////////
18970
18971 rowGetGroup(row){
18972 return row.modules.group ? row.modules.group.getComponent() : false;
18973 }
18974
18975 ///////////////////////////////////
18976 ///////// Internal Logic //////////
18977 ///////////////////////////////////
18978
18979 rowMoving(from, to, after){
18980 if(this.table.options.groupBy){
18981 if(!after && to instanceof Group){
18982 to = this.table.rowManager.prevDisplayRow(from) || to;
18983 }
18984
18985 var toGroup = to instanceof Group ? to : to.modules.group;
18986 var fromGroup = from instanceof Group ? from : from.modules.group;
18987
18988 if(toGroup === fromGroup){
18989 this.table.rowManager.moveRowInArray(toGroup.rows, from, to, after);
18990 }else {
18991 if(fromGroup){
18992 fromGroup.removeRow(from);
18993 }
18994
18995 toGroup.insertRow(from, to, after);
18996 }
18997 }
18998 }
18999
19000
19001 rowDeleting(row){
19002 //remove from group
19003 if(this.table.options.groupBy && row.modules.group){
19004 row.modules.group.removeRow(row);
19005 }
19006 }
19007
19008 rowsUpdated(row){
19009 if(this.table.options.groupBy){
19010 this.updateGroupRows(true);
19011 }
19012 }
19013
19014 cellUpdated(cell){
19015 if(this.table.options.groupBy){
19016 this.reassignRowToGroup(cell.row);
19017 }
19018 }
19019
19020 //return appropriate rows with group headers
19021 getRows(rows){
19022 if(this.table.options.groupBy && this.groupIDLookups.length){
19023
19024 this.dispatchExternal("dataGrouping");
19025
19026 this.generateGroups(rows);
19027
19028 if(this.subscribedExternal("dataGrouped")){
19029 this.dispatchExternal("dataGrouped", this.getGroups(true));
19030 }
19031
19032 return this.updateGroupRows();
19033
19034 }else {
19035 return rows.slice(0);
19036 }
19037 }
19038
19039 getGroups(component){
19040 var groupComponents = [];
19041
19042 this.groupList.forEach(function(group){
19043 groupComponents.push(component ? group.getComponent() : group);
19044 });
19045
19046 return groupComponents;
19047 }
19048
19049 getChildGroups(group){
19050 var groupComponents = [];
19051
19052 if(!group){
19053 group = this;
19054 }
19055
19056 group.groupList.forEach((child) => {
19057 if(child.groupList.length){
19058 groupComponents = groupComponents.concat(this.getChildGroups(child));
19059 }else {
19060 groupComponents.push(child);
19061 }
19062 });
19063
19064 return groupComponents;
19065 }
19066
19067 wipe(){
19068 if(this.table.options.groupBy){
19069 this.groupList.forEach(function(group){
19070 group.wipe();
19071 });
19072
19073 this.groupList = [];
19074 this.groups = {};
19075 }
19076 }
19077
19078 pullGroupListData(groupList) {
19079 var groupListData = [];
19080
19081 groupList.forEach((group) => {
19082 var groupHeader = {};
19083 groupHeader.level = 0;
19084 groupHeader.rowCount = 0;
19085 groupHeader.headerContent = "";
19086 var childData = [];
19087
19088 if (group.hasSubGroups) {
19089 childData = this.pullGroupListData(group.groupList);
19090
19091 groupHeader.level = group.level;
19092 groupHeader.rowCount = childData.length - group.groupList.length; // data length minus number of sub-headers
19093 groupHeader.headerContent = group.generator(group.key, groupHeader.rowCount, group.rows, group);
19094
19095 groupListData.push(groupHeader);
19096 groupListData = groupListData.concat(childData);
19097 }
19098
19099 else {
19100 groupHeader.level = group.level;
19101 groupHeader.headerContent = group.generator(group.key, group.rows.length, group.rows, group);
19102 groupHeader.rowCount = group.getRows().length;
19103
19104 groupListData.push(groupHeader);
19105
19106 group.getRows().forEach((row) => {
19107 groupListData.push(row.getData("data"));
19108 });
19109 }
19110 });
19111
19112 return groupListData;
19113 }
19114
19115 getGroupedData(){
19116
19117 return this.pullGroupListData(this.groupList);
19118 }
19119
19120 getRowGroup(row){
19121 var match = false;
19122
19123 if(this.options("dataTree")){
19124 row = this.table.modules.dataTree.getTreeParentRoot(row);
19125 }
19126
19127 this.groupList.forEach((group) => {
19128 var result = group.getRowGroup(row);
19129
19130 if(result){
19131 match = result;
19132 }
19133 });
19134
19135 return match;
19136 }
19137
19138 countGroups(){
19139 return this.groupList.length;
19140 }
19141
19142 generateGroups(rows){
19143 var oldGroups = this.groups;
19144
19145 this.groups = {};
19146 this.groupList = [];
19147
19148 if(this.allowedValues && this.allowedValues[0]){
19149 this.allowedValues[0].forEach((value) => {
19150 this.createGroup(value, 0, oldGroups);
19151 });
19152
19153 rows.forEach((row) => {
19154 this.assignRowToExistingGroup(row, oldGroups);
19155 });
19156 }else {
19157 rows.forEach((row) => {
19158 this.assignRowToGroup(row, oldGroups);
19159 });
19160 }
19161
19162 Object.values(oldGroups).forEach((group) => {
19163 group.wipe(true);
19164 });
19165 }
19166
19167
19168 createGroup(groupID, level, oldGroups){
19169 var groupKey = level + "_" + groupID,
19170 group;
19171
19172 oldGroups = oldGroups || [];
19173
19174 group = new Group(this, false, level, groupID, this.groupIDLookups[0].field, this.headerGenerator[0], oldGroups[groupKey]);
19175
19176 this.groups[groupKey] = group;
19177 this.groupList.push(group);
19178 }
19179
19180 assignRowToExistingGroup(row, oldGroups){
19181 var groupID = this.groupIDLookups[0].func(row.getData()),
19182 groupKey = "0_" + groupID;
19183
19184 if(this.groups[groupKey]){
19185 this.groups[groupKey].addRow(row);
19186 }
19187 }
19188
19189 assignRowToGroup(row, oldGroups){
19190 var groupID = this.groupIDLookups[0].func(row.getData()),
19191 newGroupNeeded = !this.groups["0_" + groupID];
19192
19193 if(newGroupNeeded){
19194 this.createGroup(groupID, 0, oldGroups);
19195 }
19196
19197 this.groups["0_" + groupID].addRow(row);
19198
19199 return !newGroupNeeded;
19200 }
19201
19202 reassignRowToGroup(row){
19203 if(row.type === "row"){
19204 var oldRowGroup = row.modules.group,
19205 oldGroupPath = oldRowGroup.getPath(),
19206 newGroupPath = this.getExpectedPath(row),
19207 samePath;
19208
19209 // figure out if new group path is the same as old group path
19210 samePath = (oldGroupPath.length == newGroupPath.length) && oldGroupPath.every((element, index) => {
19211 return element === newGroupPath[index];
19212 });
19213
19214 // refresh if they new path and old path aren't the same (aka the row's groupings have changed)
19215 if(!samePath) {
19216 oldRowGroup.removeRow(row);
19217 this.assignRowToGroup(row, this.groups);
19218 this.refreshData(true);
19219 }
19220 }
19221 }
19222
19223 getExpectedPath(row) {
19224 var groupPath = [], rowData = row.getData();
19225
19226 this.groupIDLookups.forEach((groupId) => {
19227 groupPath.push(groupId.func(rowData));
19228 });
19229
19230 return groupPath;
19231 }
19232
19233 updateGroupRows(force){
19234 var output = [];
19235
19236 if(!this.blockRedraw){
19237 this.groupList.forEach((group) => {
19238 output = output.concat(group.getHeadersAndRows());
19239 });
19240
19241 if(force){
19242 this.refreshData(true);
19243 }
19244 }
19245
19246 return output;
19247 }
19248
19249 scrollHeaders(left){
19250 if(this.table.options.groupBy){
19251 if(this.table.options.renderHorizontal === "virtual"){
19252 left -= this.table.columnManager.renderer.vDomPadLeft;
19253 }
19254
19255 left = left + "px";
19256
19257 this.groupList.forEach((group) => {
19258 group.scrollHeader(left);
19259 });
19260 }
19261 }
19262
19263 removeGroup(group){
19264 var groupKey = group.level + "_" + group.key,
19265 index;
19266
19267 if(this.groups[groupKey]){
19268 delete this.groups[groupKey];
19269
19270 index = this.groupList.indexOf(group);
19271
19272 if(index > -1){
19273 this.groupList.splice(index, 1);
19274 }
19275 }
19276 }
19277
19278 checkBasicModeGroupHeaderWidth(){
19279 var element = this.table.rowManager.tableElement,
19280 onlyGroupHeaders = true;
19281
19282 this.table.rowManager.getDisplayRows().forEach((row, index) =>{
19283 this.table.rowManager.styleRow(row, index);
19284 element.appendChild(row.getElement());
19285 row.initialize(true);
19286
19287 if(row.type !== "group"){
19288 onlyGroupHeaders = false;
19289 }
19290 });
19291
19292 if(onlyGroupHeaders){
19293 element.style.minWidth = this.table.columnManager.getWidth() + "px";
19294 }else {
19295 element.style.minWidth = "";
19296 }
19297 }
19298
19299 }
19300
19301 var defaultUndoers = {
19302 cellEdit: function(action){
19303 action.component.setValueProcessData(action.data.oldValue);
19304 action.component.cellRendered();
19305 },
19306
19307 rowAdd: function(action){
19308 action.component.deleteActual();
19309
19310 this.table.rowManager.checkPlaceholder();
19311 },
19312
19313 rowDelete: function(action){
19314 var newRow = this.table.rowManager.addRowActual(action.data.data, action.data.pos, action.data.index);
19315
19316 if(this.table.options.groupBy && this.table.modExists("groupRows")){
19317 this.table.modules.groupRows.updateGroupRows(true);
19318 }
19319
19320 this._rebindRow(action.component, newRow);
19321
19322 this.table.rowManager.checkPlaceholder();
19323 },
19324
19325 rowMove: function(action){
19326 var after = (action.data.posFrom - action.data.posTo) > 0;
19327
19328 this.table.rowManager.moveRowActual(action.component, this.table.rowManager.getRowFromPosition(action.data.posFrom), after);
19329
19330 this.table.rowManager.regenerateRowPositions();
19331 this.table.rowManager.reRenderInPosition();
19332 },
19333 };
19334
19335 var defaultRedoers = {
19336 cellEdit: function(action){
19337 action.component.setValueProcessData(action.data.newValue);
19338 action.component.cellRendered();
19339 },
19340
19341 rowAdd: function(action){
19342 var newRow = this.table.rowManager.addRowActual(action.data.data, action.data.pos, action.data.index);
19343
19344 if(this.table.options.groupBy && this.table.modExists("groupRows")){
19345 this.table.modules.groupRows.updateGroupRows(true);
19346 }
19347
19348 this._rebindRow(action.component, newRow);
19349
19350 this.table.rowManager.checkPlaceholder();
19351 },
19352
19353 rowDelete:function(action){
19354 action.component.deleteActual();
19355
19356 this.table.rowManager.checkPlaceholder();
19357 },
19358
19359 rowMove: function(action){
19360 this.table.rowManager.moveRowActual(action.component, this.table.rowManager.getRowFromPosition(action.data.posTo), action.data.after);
19361
19362 this.table.rowManager.regenerateRowPositions();
19363 this.table.rowManager.reRenderInPosition();
19364 },
19365 };
19366
19367 var bindings$1 = {
19368 undo:["ctrl + 90", "meta + 90"],
19369 redo:["ctrl + 89", "meta + 89"],
19370 };
19371
19372 var actions$1 = {
19373 undo:function(e){
19374 var cell = false;
19375 if(this.table.options.history && this.table.modExists("history") && this.table.modExists("edit")){
19376
19377 cell = this.table.modules.edit.currentCell;
19378
19379 if(!cell){
19380 e.preventDefault();
19381 this.table.modules.history.undo();
19382 }
19383 }
19384 },
19385
19386 redo:function(e){
19387 var cell = false;
19388 if(this.table.options.history && this.table.modExists("history") && this.table.modExists("edit")){
19389
19390 cell = this.table.modules.edit.currentCell;
19391
19392 if(!cell){
19393 e.preventDefault();
19394 this.table.modules.history.redo();
19395 }
19396 }
19397 },
19398 };
19399
19400 var extensions$3 = {
19401 keybindings:{
19402 bindings:bindings$1,
19403 actions:actions$1
19404 },
19405 };
19406
19407 class History extends Module{
19408
19409 static moduleName = "history";
19410 static moduleExtensions = extensions$3;
19411
19412 //load defaults
19413 static undoers = defaultUndoers;
19414 static redoers = defaultRedoers;
19415
19416 constructor(table){
19417 super(table);
19418
19419 this.history = [];
19420 this.index = -1;
19421
19422 this.registerTableOption("history", false); //enable edit history
19423 }
19424
19425 initialize(){
19426 if(this.table.options.history){
19427 this.subscribe("cell-value-updated", this.cellUpdated.bind(this));
19428 this.subscribe("cell-delete", this.clearComponentHistory.bind(this));
19429 this.subscribe("row-delete", this.rowDeleted.bind(this));
19430 this.subscribe("rows-wipe", this.clear.bind(this));
19431 this.subscribe("row-added", this.rowAdded.bind(this));
19432 this.subscribe("row-move", this.rowMoved.bind(this));
19433 }
19434
19435 this.registerTableFunction("undo", this.undo.bind(this));
19436 this.registerTableFunction("redo", this.redo.bind(this));
19437 this.registerTableFunction("getHistoryUndoSize", this.getHistoryUndoSize.bind(this));
19438 this.registerTableFunction("getHistoryRedoSize", this.getHistoryRedoSize.bind(this));
19439 this.registerTableFunction("clearHistory", this.clear.bind(this));
19440 }
19441
19442 rowMoved(from, to, after){
19443 this.action("rowMove", from, {posFrom:from.getPosition(), posTo:to.getPosition(), to:to, after:after});
19444 }
19445
19446 rowAdded(row, data, pos, index){
19447 this.action("rowAdd", row, {data:data, pos:pos, index:index});
19448 }
19449
19450 rowDeleted(row){
19451 var index, rows;
19452
19453 if(this.table.options.groupBy){
19454
19455 rows = row.getComponent().getGroup()._getSelf().rows;
19456 index = rows.indexOf(row);
19457
19458 if(index){
19459 index = rows[index-1];
19460 }
19461 }else {
19462 index = row.table.rowManager.getRowIndex(row);
19463
19464 if(index){
19465 index = row.table.rowManager.rows[index-1];
19466 }
19467 }
19468
19469 this.action("rowDelete", row, {data:row.getData(), pos:!index, index:index});
19470 }
19471
19472 cellUpdated(cell){
19473 this.action("cellEdit", cell, {oldValue:cell.oldValue, newValue:cell.value});
19474 }
19475
19476 clear(){
19477 this.history = [];
19478 this.index = -1;
19479 }
19480
19481 action(type, component, data){
19482 this.history = this.history.slice(0, this.index + 1);
19483
19484 this.history.push({
19485 type:type,
19486 component:component,
19487 data:data,
19488 });
19489
19490 this.index ++;
19491 }
19492
19493 getHistoryUndoSize(){
19494 return this.index + 1;
19495 }
19496
19497 getHistoryRedoSize(){
19498 return this.history.length - (this.index + 1);
19499 }
19500
19501 clearComponentHistory(component){
19502 var index = this.history.findIndex(function(item){
19503 return item.component === component;
19504 });
19505
19506 if(index > -1){
19507 this.history.splice(index, 1);
19508 if(index <= this.index){
19509 this.index--;
19510 }
19511
19512 this.clearComponentHistory(component);
19513 }
19514 }
19515
19516 undo(){
19517 if(this.index > -1){
19518 let action = this.history[this.index];
19519
19520 History.undoers[action.type].call(this, action);
19521
19522 this.index--;
19523
19524 this.dispatchExternal("historyUndo", action.type, action.component.getComponent(), action.data);
19525
19526 return true;
19527 }else {
19528 console.warn(this.options("history") ? "History Undo Error - No more history to undo" : "History module not enabled");
19529 return false;
19530 }
19531 }
19532
19533 redo(){
19534 if(this.history.length-1 > this.index){
19535
19536 this.index++;
19537
19538 let action = this.history[this.index];
19539
19540 History.redoers[action.type].call(this, action);
19541
19542 this.dispatchExternal("historyRedo", action.type, action.component.getComponent(), action.data);
19543
19544 return true;
19545 }else {
19546 console.warn(this.options("history") ? "History Redo Error - No more history to redo" : "History module not enabled");
19547 return false;
19548 }
19549 }
19550
19551 //rebind rows to new element after deletion
19552 _rebindRow(oldRow, newRow){
19553 this.history.forEach(function(action){
19554 if(action.component instanceof Row){
19555 if(action.component === oldRow){
19556 action.component = newRow;
19557 }
19558 }else if(action.component instanceof Cell){
19559 if(action.component.row === oldRow){
19560 var field = action.component.column.getField();
19561
19562 if(field){
19563 action.component = newRow.getCell(field);
19564 }
19565
19566 }
19567 }
19568 });
19569 }
19570 }
19571
19572 class HtmlTableImport extends Module{
19573
19574 static moduleName = "htmlTableImport";
19575
19576 constructor(table){
19577 super(table);
19578
19579 this.fieldIndex = [];
19580 this.hasIndex = false;
19581 }
19582
19583 initialize(){
19584 this.tableElementCheck();
19585 }
19586
19587 tableElementCheck(){
19588 if(this.table.originalElement && this.table.originalElement.tagName === "TABLE"){
19589 if(this.table.originalElement.childNodes.length){
19590 this.parseTable();
19591 }else {
19592 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.");
19593 }
19594 }
19595 }
19596
19597 parseTable(){
19598 var element = this.table.originalElement,
19599 options = this.table.options,
19600 headers = element.getElementsByTagName("th"),
19601 rows = element.getElementsByTagName("tbody")[0],
19602 data = [];
19603
19604 this.hasIndex = false;
19605
19606 this.dispatchExternal("htmlImporting");
19607
19608 rows = rows ? rows.getElementsByTagName("tr") : [];
19609
19610 //check for Tabulator inline options
19611 this._extractOptions(element, options);
19612
19613 if(headers.length){
19614 this._extractHeaders(headers, rows);
19615 }else {
19616 this._generateBlankHeaders(headers, rows);
19617 }
19618
19619 //iterate through table rows and build data set
19620 for(var index = 0; index < rows.length; index++){
19621 var row = rows[index],
19622 cells = row.getElementsByTagName("td"),
19623 item = {};
19624
19625 //create index if the don't exist in table
19626 if(!this.hasIndex){
19627 item[options.index] = index;
19628 }
19629
19630 for(var i = 0; i < cells.length; i++){
19631 var cell = cells[i];
19632 if(typeof this.fieldIndex[i] !== "undefined"){
19633 item[this.fieldIndex[i]] = cell.innerHTML;
19634 }
19635 }
19636
19637 //add row data to item
19638 data.push(item);
19639 }
19640
19641 options.data = data;
19642
19643 this.dispatchExternal("htmlImported");
19644 }
19645
19646 //extract tabulator attribute options
19647 _extractOptions(element, options, defaultOptions){
19648 var attributes = element.attributes;
19649 var optionsArr = defaultOptions ? Object.keys(defaultOptions) : Object.keys(options);
19650 var optionsList = {};
19651
19652 optionsArr.forEach((item) => {
19653 optionsList[item.toLowerCase()] = item;
19654 });
19655
19656 for(var index in attributes){
19657 var attrib = attributes[index];
19658 var name;
19659
19660 if(attrib && typeof attrib == "object" && attrib.name && attrib.name.indexOf("tabulator-") === 0){
19661 name = attrib.name.replace("tabulator-", "");
19662
19663 if(typeof optionsList[name] !== "undefined"){
19664 options[optionsList[name]] = this._attribValue(attrib.value);
19665 }
19666 }
19667 }
19668 }
19669
19670 //get value of attribute
19671 _attribValue(value){
19672 if(value === "true"){
19673 return true;
19674 }
19675
19676 if(value === "false"){
19677 return false;
19678 }
19679
19680 return value;
19681 }
19682
19683 //find column if it has already been defined
19684 _findCol(title){
19685 var match = this.table.options.columns.find((column) => {
19686 return column.title === title;
19687 });
19688
19689 return match || false;
19690 }
19691
19692 //extract column from headers
19693 _extractHeaders(headers, rows){
19694 for(var index = 0; index < headers.length; index++){
19695 var header = headers[index],
19696 exists = false,
19697 col = this._findCol(header.textContent),
19698 width;
19699
19700 if(col){
19701 exists = true;
19702 }else {
19703 col = {title:header.textContent.trim()};
19704 }
19705
19706 if(!col.field) {
19707 col.field = header.textContent.trim().toLowerCase().replaceAll(" ", "_");
19708 }
19709
19710 width = header.getAttribute("width");
19711
19712 if(width && !col.width) {
19713 col.width = width;
19714 }
19715
19716 //check for Tabulator inline options
19717 this._extractOptions(header, col, this.table.columnManager.optionsList.registeredDefaults);
19718
19719 this.fieldIndex[index] = col.field;
19720
19721 if(col.field == this.table.options.index){
19722 this.hasIndex = true;
19723 }
19724
19725 if(!exists){
19726 this.table.options.columns.push(col);
19727 }
19728
19729 }
19730 }
19731
19732 //generate blank headers
19733 _generateBlankHeaders(headers, rows){
19734 for(var index = 0; index < headers.length; index++){
19735 var header = headers[index],
19736 col = {title:"", field:"col" + index};
19737
19738 this.fieldIndex[index] = col.field;
19739
19740 var width = header.getAttribute("width");
19741
19742 if(width){
19743 col.width = width;
19744 }
19745
19746 this.table.options.columns.push(col);
19747 }
19748 }
19749 }
19750
19751 function csv(input){
19752 var data = [],
19753 row = 0,
19754 col = 0,
19755 inQuote = false;
19756
19757 //Iterate over each character
19758 for (let index = 0; index < input.length; index++) {
19759 let char = input[index],
19760 nextChar = input[index+1];
19761
19762 //Initialize empty row
19763 if(!data[row]){
19764 data[row] = [];
19765 }
19766
19767 //Initialize empty column
19768 if(!data[row][col]){
19769 data[row][col] = "";
19770 }
19771
19772 //Handle quotation mark inside string
19773 if (char == '"' && inQuote && nextChar == '"') {
19774 data[row][col] += char;
19775 index++;
19776 continue;
19777 }
19778
19779 //Begin / End Quote
19780 if (char == '"') {
19781 inQuote = !inQuote;
19782 continue;
19783 }
19784
19785 //Next column (if not in quote)
19786 if (char == ',' && !inQuote) {
19787 col++;
19788 continue;
19789 }
19790
19791 //New row if new line and not in quote (CRLF)
19792 if (char == '\r' && nextChar == '\n' && !inQuote) {
19793 col = 0;
19794 row++;
19795 index++;
19796 continue;
19797 }
19798
19799 //New row if new line and not in quote (CR or LF)
19800 if ((char == '\r' || char == '\n') && !inQuote) {
19801 col = 0;
19802 row++;
19803 continue;
19804 }
19805
19806 //Normal Character, append to column
19807 data[row][col] += char;
19808 }
19809
19810 return data;
19811 }
19812
19813 function json(input){
19814 try {
19815 return JSON.parse(input);
19816 } catch(e) {
19817 console.warn("JSON Import Error - File contents is invalid JSON", e);
19818 return Promise.reject();
19819 }
19820 }
19821
19822 function array$1 (input){
19823 return input;
19824 }
19825
19826 function xlsx(input){
19827 var XLSXLib = this.dependencyRegistry.lookup("XLSX"),
19828 workbook2 = XLSXLib.read(input),
19829 sheet = workbook2.Sheets[workbook2.SheetNames[0]];
19830
19831 return XLSXLib.utils.sheet_to_json(sheet, {header: 1 });
19832 }
19833
19834 var defaultImporters = {
19835 csv:csv,
19836 json:json,
19837 array:array$1,
19838 xlsx:xlsx,
19839 };
19840
19841 class Import extends Module{
19842
19843 static moduleName = "import";
19844
19845 //load defaults
19846 static importers = defaultImporters;
19847
19848 constructor(table){
19849 super(table);
19850
19851 this.registerTableOption("importFormat");
19852 this.registerTableOption("importReader", "text");
19853 this.registerTableOption("importHeaderTransform");
19854 this.registerTableOption("importValueTransform");
19855 this.registerTableOption("importDataValidator");
19856 this.registerTableOption("importFileValidator");
19857 }
19858
19859 initialize(){
19860 this.registerTableFunction("import", this.importFromFile.bind(this));
19861
19862 if(this.table.options.importFormat){
19863 this.subscribe("data-loading", this.loadDataCheck.bind(this), 10);
19864 this.subscribe("data-load", this.loadData.bind(this), 10);
19865 }
19866 }
19867
19868 loadDataCheck(data){
19869 return this.table.options.importFormat && (typeof data === "string" || (Array.isArray(data) && data.length && Array.isArray(data)));
19870 }
19871
19872 loadData(data, params, config, silent, previousData){
19873 return this.importData(this.lookupImporter(), data)
19874 .then(this.structureData.bind(this))
19875 .catch((err) => {
19876 console.error("Import Error:", err || "Unable to import data");
19877 return Promise.reject(err);
19878 });
19879 }
19880
19881 lookupImporter(importFormat){
19882 var importer;
19883
19884 if(!importFormat){
19885 importFormat = this.table.options.importFormat;
19886 }
19887
19888 if(typeof importFormat === "string"){
19889 importer = Import.importers[importFormat];
19890 }else {
19891 importer = importFormat;
19892 }
19893
19894 if(!importer){
19895 console.error("Import Error - Importer not found:", importFormat);
19896 }
19897
19898 return importer;
19899 }
19900
19901 importFromFile(importFormat, extension, importReader){
19902 var importer = this.lookupImporter(importFormat);
19903
19904 if(importer){
19905 return this.pickFile(extension, importReader)
19906 .then(this.importData.bind(this, importer))
19907 .then(this.structureData.bind(this))
19908 .then(this.mutateData.bind(this))
19909 .then(this.validateData.bind(this))
19910 .then(this.setData.bind(this))
19911 .catch((err) => {
19912 this.dispatch("import-error", err);
19913 this.dispatchExternal("importError", err);
19914
19915 console.error("Import Error:", err || "Unable to import file");
19916
19917 this.table.dataLoader.alertError();
19918
19919 setTimeout(() => {
19920 this.table.dataLoader.clearAlert();
19921 }, 3000);
19922
19923 return Promise.reject(err);
19924 });
19925 }
19926 }
19927
19928 pickFile(extensions, importReader){
19929 return new Promise((resolve, reject) => {
19930 var input = document.createElement("input");
19931 input.type = "file";
19932 input.accept = extensions;
19933
19934 input.addEventListener("change", (e) => {
19935 var file = input.files[0],
19936 reader = new FileReader(),
19937 valid = this.validateFile(file);
19938
19939 if(valid === true){
19940
19941 this.dispatch("import-importing", input.files);
19942 this.dispatchExternal("importImporting", input.files);
19943
19944 switch(importReader || this.table.options.importReader){
19945 case "buffer":
19946 reader.readAsArrayBuffer(file);
19947 break;
19948
19949 case "binary":
19950 reader.readAsBinaryString(file);
19951 break;
19952
19953 case "url":
19954 reader.readAsDataURL(file);
19955 break;
19956
19957 case "text":
19958 default:
19959 reader.readAsText(file);
19960 }
19961
19962 reader.onload = (e) => {
19963 resolve(reader.result);
19964 };
19965
19966 reader.onerror = (e) => {
19967 console.warn("File Load Error - Unable to read file");
19968 reject(e);
19969 };
19970 }else {
19971 reject(valid);
19972 }
19973 });
19974
19975 this.dispatch("import-choose");
19976 this.dispatchExternal("importChoose");
19977 input.click();
19978 });
19979 }
19980
19981 importData(importer, fileContents){
19982 var data;
19983
19984 this.table.dataLoader.alertLoader();
19985
19986 return new Promise((resolve, reject) => {
19987 setTimeout(() => {
19988 data = importer.call(this.table, fileContents);
19989
19990 if(data instanceof Promise){
19991 resolve(data);
19992 }else {
19993 data ? resolve(data) : reject();
19994 }
19995 }, 10);
19996 });
19997 }
19998
19999 structureData(parsedData){
20000 var data = [];
20001
20002 if(Array.isArray(parsedData) && parsedData.length && Array.isArray(parsedData[0])){
20003 if(this.table.options.autoColumns){
20004 data = this.structureArrayToObject(parsedData);
20005 }else {
20006 data = this.structureArrayToColumns(parsedData);
20007 }
20008
20009 return data;
20010 }else {
20011 return parsedData;
20012 }
20013 }
20014
20015 mutateData(data){
20016 var output = [];
20017
20018 if(Array.isArray(data)){
20019 data.forEach((row) => {
20020 output.push(this.table.modules.mutator.transformRow(row, "import"));
20021 });
20022 }else {
20023 output = data;
20024 }
20025
20026 return output;
20027 }
20028
20029 transformHeader(headers){
20030 var output = [];
20031
20032 if(this.table.options.importHeaderTransform){
20033 headers.forEach((item) => {
20034 output.push(this.table.options.importHeaderTransform.call(this.table, item, headers));
20035 });
20036 }else {
20037 return headers;
20038 }
20039
20040 return output;
20041 }
20042
20043 transformData(row){
20044 var output = [];
20045
20046 if(this.table.options.importValueTransform){
20047 row.forEach((item) => {
20048 output.push(this.table.options.importValueTransform.call(this.table, item, row));
20049 });
20050 }else {
20051 return row;
20052 }
20053
20054 return output;
20055 }
20056
20057 structureArrayToObject(parsedData){
20058 var columns = this.transformHeader(parsedData.shift());
20059
20060 var data = parsedData.map((values) => {
20061 var row = {};
20062
20063 values = this.transformData(values);
20064
20065 columns.forEach((key, i) => {
20066 row[key] = values[i];
20067 });
20068
20069 return row;
20070 });
20071
20072 return data;
20073 }
20074
20075 structureArrayToColumns(parsedData){
20076 var data = [],
20077 firstRow = this.transformHeader(parsedData[0]),
20078 columns = this.table.getColumns();
20079
20080 //remove first row if it is the column names
20081 if(columns[0] && firstRow[0]){
20082 if(columns[0].getDefinition().title === firstRow[0]){
20083 parsedData.shift();
20084 }
20085 }
20086
20087 //convert row arrays to objects
20088 parsedData.forEach((rowData) => {
20089 var row = {};
20090
20091 rowData = this.transformData(rowData);
20092
20093 rowData.forEach((value, index) => {
20094 var column = columns[index];
20095
20096 if(column){
20097 row[column.getField()] = value;
20098 }
20099 });
20100
20101 data.push(row);
20102 });
20103
20104 return data;
20105 }
20106
20107 validateFile(file){
20108 if(this.table.options.importFileValidator){
20109 return this.table.options.importFileValidator.call(this.table, file);
20110 }
20111
20112 return true;
20113 }
20114
20115 validateData(data){
20116 var result;
20117
20118 if(this.table.options.importDataValidator){
20119 result = this.table.options.importDataValidator.call(this.table, data);
20120
20121 if(result === true){
20122 return data;
20123 }else {
20124 return Promise.reject(result);
20125 }
20126 }
20127
20128 return data;
20129 }
20130
20131 setData(data){
20132 this.dispatch("import-imported", data);
20133 this.dispatchExternal("importImported", data);
20134
20135 this.table.dataLoader.clearAlert();
20136
20137 return this.table.setData(data);
20138 }
20139 }
20140
20141 class Interaction extends Module{
20142
20143 static moduleName = "interaction";
20144
20145 constructor(table){
20146 super(table);
20147
20148 this.eventMap = {
20149 //row events
20150 rowClick:"row-click",
20151 rowDblClick:"row-dblclick",
20152 rowContext:"row-contextmenu",
20153 rowMouseEnter:"row-mouseenter",
20154 rowMouseLeave:"row-mouseleave",
20155 rowMouseOver:"row-mouseover",
20156 rowMouseOut:"row-mouseout",
20157 rowMouseMove:"row-mousemove",
20158 rowMouseDown:"row-mousedown",
20159 rowMouseUp:"row-mouseup",
20160 rowTap:"row",
20161 rowDblTap:"row",
20162 rowTapHold:"row",
20163
20164 //cell events
20165 cellClick:"cell-click",
20166 cellDblClick:"cell-dblclick",
20167 cellContext:"cell-contextmenu",
20168 cellMouseEnter:"cell-mouseenter",
20169 cellMouseLeave:"cell-mouseleave",
20170 cellMouseOver:"cell-mouseover",
20171 cellMouseOut:"cell-mouseout",
20172 cellMouseMove:"cell-mousemove",
20173 cellMouseDown:"cell-mousedown",
20174 cellMouseUp:"cell-mouseup",
20175 cellTap:"cell",
20176 cellDblTap:"cell",
20177 cellTapHold:"cell",
20178
20179 //column header events
20180 headerClick:"column-click",
20181 headerDblClick:"column-dblclick",
20182 headerContext:"column-contextmenu",
20183 headerMouseEnter:"column-mouseenter",
20184 headerMouseLeave:"column-mouseleave",
20185 headerMouseOver:"column-mouseover",
20186 headerMouseOut:"column-mouseout",
20187 headerMouseMove:"column-mousemove",
20188 headerMouseDown:"column-mousedown",
20189 headerMouseUp:"column-mouseup",
20190 headerTap:"column",
20191 headerDblTap:"column",
20192 headerTapHold:"column",
20193
20194 //group header
20195 groupClick:"group-click",
20196 groupDblClick:"group-dblclick",
20197 groupContext:"group-contextmenu",
20198 groupMouseEnter:"group-mouseenter",
20199 groupMouseLeave:"group-mouseleave",
20200 groupMouseOver:"group-mouseover",
20201 groupMouseOut:"group-mouseout",
20202 groupMouseMove:"group-mousemove",
20203 groupMouseDown:"group-mousedown",
20204 groupMouseUp:"group-mouseup",
20205 groupTap:"group",
20206 groupDblTap:"group",
20207 groupTapHold:"group",
20208 };
20209
20210 this.subscribers = {};
20211
20212 this.touchSubscribers = {};
20213
20214 this.columnSubscribers = {};
20215
20216 this.touchWatchers = {
20217 row:{
20218 tap:null,
20219 tapDbl:null,
20220 tapHold:null,
20221 },
20222 cell:{
20223 tap:null,
20224 tapDbl:null,
20225 tapHold:null,
20226 },
20227 column:{
20228 tap:null,
20229 tapDbl:null,
20230 tapHold:null,
20231 },
20232 group:{
20233 tap:null,
20234 tapDbl:null,
20235 tapHold:null,
20236 }
20237 };
20238
20239 this.registerColumnOption("headerClick");
20240 this.registerColumnOption("headerDblClick");
20241 this.registerColumnOption("headerContext");
20242 this.registerColumnOption("headerMouseEnter");
20243 this.registerColumnOption("headerMouseLeave");
20244 this.registerColumnOption("headerMouseOver");
20245 this.registerColumnOption("headerMouseOut");
20246 this.registerColumnOption("headerMouseMove");
20247 this.registerColumnOption("headerMouseDown");
20248 this.registerColumnOption("headerMouseUp");
20249 this.registerColumnOption("headerTap");
20250 this.registerColumnOption("headerDblTap");
20251 this.registerColumnOption("headerTapHold");
20252
20253 this.registerColumnOption("cellClick");
20254 this.registerColumnOption("cellDblClick");
20255 this.registerColumnOption("cellContext");
20256 this.registerColumnOption("cellMouseEnter");
20257 this.registerColumnOption("cellMouseLeave");
20258 this.registerColumnOption("cellMouseOver");
20259 this.registerColumnOption("cellMouseOut");
20260 this.registerColumnOption("cellMouseMove");
20261 this.registerColumnOption("cellMouseDown");
20262 this.registerColumnOption("cellMouseUp");
20263 this.registerColumnOption("cellTap");
20264 this.registerColumnOption("cellDblTap");
20265 this.registerColumnOption("cellTapHold");
20266
20267 }
20268
20269 initialize(){
20270 this.initializeExternalEvents();
20271
20272 this.subscribe("column-init", this.initializeColumn.bind(this));
20273 this.subscribe("cell-dblclick", this.cellContentsSelectionFixer.bind(this));
20274 this.subscribe("scroll-horizontal", this.clearTouchWatchers.bind(this));
20275 this.subscribe("scroll-vertical", this.clearTouchWatchers.bind(this));
20276 }
20277
20278 clearTouchWatchers(){
20279 var types = Object.values(this.touchWatchers);
20280
20281 types.forEach((type) => {
20282 for(let key in type){
20283 type[key] = null;
20284 }
20285 });
20286 }
20287
20288 cellContentsSelectionFixer(e, cell){
20289 var range;
20290
20291 if(this.table.modExists("edit")){
20292 if (this.table.modules.edit.currentCell === cell){
20293 return; //prevent instant selection of editor content
20294 }
20295 }
20296
20297 e.preventDefault();
20298
20299 try{
20300 if (document.selection) { // IE
20301 range = document.body.createTextRange();
20302 range.moveToElementText(cell.getElement());
20303 range.select();
20304 } else if (window.getSelection) {
20305 range = document.createRange();
20306 range.selectNode(cell.getElement());
20307 window.getSelection().removeAllRanges();
20308 window.getSelection().addRange(range);
20309 }
20310 }catch(e){}
20311 }
20312
20313 initializeExternalEvents(){
20314 for(let key in this.eventMap){
20315 this.subscriptionChangeExternal(key, this.subscriptionChanged.bind(this, key));
20316 }
20317 }
20318
20319 subscriptionChanged(key, added){
20320 if(added){
20321 if(!this.subscribers[key]){
20322 if(this.eventMap[key].includes("-")){
20323 this.subscribers[key] = this.handle.bind(this, key);
20324 this.subscribe(this.eventMap[key], this.subscribers[key]);
20325 }else {
20326 this.subscribeTouchEvents(key);
20327 }
20328 }
20329 }else {
20330 if(this.eventMap[key].includes("-")){
20331 if(this.subscribers[key] && !this.columnSubscribers[key] && !this.subscribedExternal(key)){
20332 this.unsubscribe(this.eventMap[key], this.subscribers[key]);
20333 delete this.subscribers[key];
20334 }
20335 }else {
20336 this.unsubscribeTouchEvents(key);
20337 }
20338 }
20339 }
20340
20341
20342 subscribeTouchEvents(key){
20343 var type = this.eventMap[key];
20344
20345 if(!this.touchSubscribers[type + "-touchstart"]){
20346 this.touchSubscribers[type + "-touchstart"] = this.handleTouch.bind(this, type, "start");
20347 this.touchSubscribers[type + "-touchend"] = this.handleTouch.bind(this, type, "end");
20348
20349 this.subscribe(type + "-touchstart", this.touchSubscribers[type + "-touchstart"]);
20350 this.subscribe(type + "-touchend", this.touchSubscribers[type + "-touchend"]);
20351 }
20352
20353 this.subscribers[key] = true;
20354 }
20355
20356 unsubscribeTouchEvents(key){
20357 var noTouch = true,
20358 type = this.eventMap[key];
20359
20360 if(this.subscribers[key] && !this.subscribedExternal(key)){
20361 delete this.subscribers[key];
20362
20363 for(let i in this.eventMap){
20364 if(this.eventMap[i] === type){
20365 if(this.subscribers[i]){
20366 noTouch = false;
20367 }
20368 }
20369 }
20370
20371 if(noTouch){
20372 this.unsubscribe(type + "-touchstart", this.touchSubscribers[type + "-touchstart"]);
20373 this.unsubscribe(type + "-touchend", this.touchSubscribers[type + "-touchend"]);
20374
20375 delete this.touchSubscribers[type + "-touchstart"];
20376 delete this.touchSubscribers[type + "-touchend"];
20377 }
20378 }
20379 }
20380
20381 initializeColumn(column){
20382 var def = column.definition;
20383
20384 for(let key in this.eventMap){
20385 if(def[key]){
20386 this.subscriptionChanged(key, true);
20387
20388 if(!this.columnSubscribers[key]){
20389 this.columnSubscribers[key] = [];
20390 }
20391
20392 this.columnSubscribers[key].push(column);
20393 }
20394 }
20395 }
20396
20397 handle(action, e, component){
20398 this.dispatchEvent(action, e, component);
20399 }
20400
20401 handleTouch(type, action, e, component){
20402 var watchers = this.touchWatchers[type];
20403
20404 if(type === "column"){
20405 type = "header";
20406 }
20407
20408 switch(action){
20409 case "start":
20410 watchers.tap = true;
20411
20412 clearTimeout(watchers.tapHold);
20413
20414 watchers.tapHold = setTimeout(() => {
20415 clearTimeout(watchers.tapHold);
20416 watchers.tapHold = null;
20417
20418 watchers.tap = null;
20419 clearTimeout(watchers.tapDbl);
20420 watchers.tapDbl = null;
20421
20422 this.dispatchEvent(type + "TapHold", e, component);
20423 }, 1000);
20424 break;
20425
20426 case "end":
20427 if(watchers.tap){
20428
20429 watchers.tap = null;
20430 this.dispatchEvent(type + "Tap", e, component);
20431 }
20432
20433 if(watchers.tapDbl){
20434 clearTimeout(watchers.tapDbl);
20435 watchers.tapDbl = null;
20436
20437 this.dispatchEvent(type + "DblTap", e, component);
20438 }else {
20439 watchers.tapDbl = setTimeout(() => {
20440 clearTimeout(watchers.tapDbl);
20441 watchers.tapDbl = null;
20442 }, 300);
20443 }
20444
20445 clearTimeout(watchers.tapHold);
20446 watchers.tapHold = null;
20447 break;
20448 }
20449 }
20450
20451 dispatchEvent(action, e, component){
20452 var componentObj = component.getComponent(),
20453 callback;
20454
20455 if(this.columnSubscribers[action]){
20456
20457 if(component instanceof Cell){
20458 callback = component.column.definition[action];
20459 }else if(component instanceof Column){
20460 callback = component.definition[action];
20461 }
20462
20463 if(callback){
20464 callback(e, componentObj);
20465 }
20466 }
20467
20468 this.dispatchExternal(action, e, componentObj);
20469 }
20470 }
20471
20472 var defaultBindings = {
20473 navPrev:"shift + 9",
20474 navNext:9,
20475 navUp:38,
20476 navDown:40,
20477 navLeft:37,
20478 navRight:39,
20479 scrollPageUp:33,
20480 scrollPageDown:34,
20481 scrollToStart:36,
20482 scrollToEnd:35,
20483 };
20484
20485 var defaultActions = {
20486 keyBlock:function(e){
20487 e.stopPropagation();
20488 e.preventDefault();
20489 },
20490
20491 scrollPageUp:function(e){
20492 var rowManager = this.table.rowManager,
20493 newPos = rowManager.scrollTop - rowManager.element.clientHeight;
20494
20495 e.preventDefault();
20496
20497 if(rowManager.displayRowsCount){
20498 if(newPos >= 0){
20499 rowManager.element.scrollTop = newPos;
20500 }else {
20501 rowManager.scrollToRow(rowManager.getDisplayRows()[0]);
20502 }
20503 }
20504
20505 this.table.element.focus();
20506 },
20507
20508 scrollPageDown:function(e){
20509 var rowManager = this.table.rowManager,
20510 newPos = rowManager.scrollTop + rowManager.element.clientHeight,
20511 scrollMax = rowManager.element.scrollHeight;
20512
20513 e.preventDefault();
20514
20515 if(rowManager.displayRowsCount){
20516 if(newPos <= scrollMax){
20517 rowManager.element.scrollTop = newPos;
20518 }else {
20519 rowManager.scrollToRow(rowManager.getDisplayRows()[rowManager.displayRowsCount - 1]);
20520 }
20521 }
20522
20523 this.table.element.focus();
20524
20525 },
20526
20527 scrollToStart:function(e){
20528 var rowManager = this.table.rowManager;
20529
20530 e.preventDefault();
20531
20532 if(rowManager.displayRowsCount){
20533 rowManager.scrollToRow(rowManager.getDisplayRows()[0]);
20534 }
20535
20536 this.table.element.focus();
20537 },
20538
20539 scrollToEnd:function(e){
20540 var rowManager = this.table.rowManager;
20541
20542 e.preventDefault();
20543
20544 if(rowManager.displayRowsCount){
20545 rowManager.scrollToRow(rowManager.getDisplayRows()[rowManager.displayRowsCount - 1]);
20546 }
20547
20548 this.table.element.focus();
20549 },
20550
20551 navPrev:function(e){
20552 this.dispatch("keybinding-nav-prev", e);
20553 },
20554
20555 navNext:function(e){
20556 this.dispatch("keybinding-nav-next", e);
20557 },
20558
20559 navLeft:function(e){
20560 this.dispatch("keybinding-nav-left", e);
20561 },
20562
20563 navRight:function(e){
20564 this.dispatch("keybinding-nav-right", e);
20565 },
20566
20567 navUp:function(e){
20568 this.dispatch("keybinding-nav-up", e);
20569 },
20570
20571 navDown:function(e){
20572 this.dispatch("keybinding-nav-down", e);
20573 },
20574 };
20575
20576 class Keybindings extends Module{
20577
20578 static moduleName = "keybindings";
20579
20580 //load defaults
20581 static bindings = defaultBindings;
20582 static actions = defaultActions;
20583
20584 constructor(table){
20585 super(table);
20586
20587 this.watchKeys = null;
20588 this.pressedKeys = null;
20589 this.keyupBinding = false;
20590 this.keydownBinding = false;
20591
20592 this.registerTableOption("keybindings", {}); //array for keybindings
20593 this.registerTableOption("tabEndNewRow", false); //create new row when tab to end of table
20594 }
20595
20596 initialize(){
20597 var bindings = this.table.options.keybindings,
20598 mergedBindings = {};
20599
20600 this.watchKeys = {};
20601 this.pressedKeys = [];
20602
20603 if(bindings !== false){
20604 Object.assign(mergedBindings, Keybindings.bindings);
20605 Object.assign(mergedBindings, bindings);
20606
20607 this.mapBindings(mergedBindings);
20608 this.bindEvents();
20609 }
20610
20611 this.subscribe("table-destroy", this.clearBindings.bind(this));
20612 }
20613
20614 mapBindings(bindings){
20615 for(let key in bindings){
20616 if(Keybindings.actions[key]){
20617 if(bindings[key]){
20618 if(typeof bindings[key] !== "object"){
20619 bindings[key] = [bindings[key]];
20620 }
20621
20622 bindings[key].forEach((binding) => {
20623 var bindingList = Array.isArray(binding) ? binding : [binding];
20624
20625 bindingList.forEach((item) => {
20626 this.mapBinding(key, item);
20627 });
20628 });
20629 }
20630 }else {
20631 console.warn("Key Binding Error - no such action:", key);
20632 }
20633 }
20634 }
20635
20636 getKeyCode(e){
20637 // Convert modern e.key to legacy numeric key code for compatibility
20638 if(e.key.length === 1){
20639 return e.key.toUpperCase().charCodeAt(0);
20640 }
20641
20642 // Handle special keys
20643 var specialKeys = {
20644 "Enter": 13,
20645 "Escape": 27,
20646 "Tab": 9,
20647 "Backspace": 8,
20648 "Delete": 46,
20649 "ArrowUp": 38,
20650 "ArrowDown": 40,
20651 "ArrowLeft": 37,
20652 "ArrowRight": 39,
20653 "Home": 36,
20654 "End": 35,
20655 "PageUp": 33,
20656 "PageDown": 34,
20657 "Insert": 45
20658 };
20659
20660 return specialKeys[e.key] || e.keyCode || 0;
20661 }
20662
20663 mapBinding(action, symbolsList){
20664 var binding = {
20665 action: Keybindings.actions[action],
20666 keys: [],
20667 ctrl: false,
20668 shift: false,
20669 meta: false,
20670 };
20671
20672 var symbols = symbolsList.toString().toLowerCase().split(" ").join("").split("+");
20673
20674 symbols.forEach((symbol) => {
20675 switch(symbol){
20676 case "ctrl":
20677 binding.ctrl = true;
20678 break;
20679
20680 case "shift":
20681 binding.shift = true;
20682 break;
20683
20684 case "meta":
20685 binding.meta = true;
20686 break;
20687
20688 default:
20689 symbol = isNaN(symbol) ? symbol.toUpperCase().charCodeAt(0) : parseInt(symbol);
20690 binding.keys.push(symbol);
20691
20692 if(!this.watchKeys[symbol]){
20693 this.watchKeys[symbol] = [];
20694 }
20695
20696 this.watchKeys[symbol].push(binding);
20697 }
20698 });
20699 }
20700
20701 bindEvents(){
20702 var self = this;
20703
20704 this.keyupBinding = function(e){
20705 var code = self.getKeyCode(e);
20706 var bindings = self.watchKeys[code];
20707
20708 if(bindings){
20709
20710 self.pressedKeys.push(code);
20711
20712 bindings.forEach(function(binding){
20713 self.checkBinding(e, binding);
20714 });
20715 }
20716 };
20717
20718 this.keydownBinding = function(e){
20719 var code = self.getKeyCode(e);
20720 var bindings = self.watchKeys[code];
20721
20722 if(bindings){
20723
20724 var index = self.pressedKeys.indexOf(code);
20725
20726 if(index > -1){
20727 self.pressedKeys.splice(index, 1);
20728 }
20729 }
20730 };
20731
20732 this.table.element.addEventListener("keydown", this.keyupBinding);
20733
20734 this.table.element.addEventListener("keyup", this.keydownBinding);
20735 }
20736
20737 clearBindings(){
20738 if(this.keyupBinding){
20739 this.table.element.removeEventListener("keydown", this.keyupBinding);
20740 }
20741
20742 if(this.keydownBinding){
20743 this.table.element.removeEventListener("keyup", this.keydownBinding);
20744 }
20745 }
20746
20747 checkBinding(e, binding){
20748 var match = true;
20749
20750 if(e.ctrlKey == binding.ctrl && e.shiftKey == binding.shift && e.metaKey == binding.meta){
20751 binding.keys.forEach((key) => {
20752 var index = this.pressedKeys.indexOf(key);
20753
20754 if(index == -1){
20755 match = false;
20756 }
20757 });
20758
20759 if(match){
20760 binding.action.call(this, e);
20761 }
20762
20763 return true;
20764 }
20765
20766 return false;
20767 }
20768 }
20769
20770 class Menu extends Module{
20771
20772 static moduleName = "menu";
20773
20774 constructor(table){
20775 super(table);
20776
20777 this.menuContainer = null;
20778 this.nestedMenuBlock = false;
20779
20780 this.currentComponent = null;
20781 this.rootPopup = null;
20782
20783 this.columnSubscribers = {};
20784
20785 // this.registerTableOption("menuContainer", undefined); //deprecated
20786
20787 this.registerTableOption("rowContextMenu", false);
20788 this.registerTableOption("rowClickMenu", false);
20789 this.registerTableOption("rowDblClickMenu", false);
20790 this.registerTableOption("groupContextMenu", false);
20791 this.registerTableOption("groupClickMenu", false);
20792 this.registerTableOption("groupDblClickMenu", false);
20793
20794 this.registerColumnOption("headerContextMenu");
20795 this.registerColumnOption("headerClickMenu");
20796 this.registerColumnOption("headerDblClickMenu");
20797 this.registerColumnOption("headerMenu");
20798 this.registerColumnOption("headerMenuIcon");
20799 this.registerColumnOption("contextMenu");
20800 this.registerColumnOption("clickMenu");
20801 this.registerColumnOption("dblClickMenu");
20802
20803 }
20804
20805 initialize(){
20806 this.deprecatedOptionsCheck();
20807 this.initializeRowWatchers();
20808 this.initializeGroupWatchers();
20809
20810 this.subscribe("column-init", this.initializeColumn.bind(this));
20811 }
20812
20813 deprecatedOptionsCheck(){
20814 // if(!this.deprecationCheck("menuContainer", "popupContainer")){
20815 // this.table.options.popupContainer = this.table.options.menuContainer;
20816 // }
20817 }
20818
20819 initializeRowWatchers(){
20820 if(this.table.options.rowContextMenu){
20821 this.subscribe("row-contextmenu", this.loadMenuEvent.bind(this, this.table.options.rowContextMenu));
20822 this.table.on("rowTapHold", this.loadMenuEvent.bind(this, this.table.options.rowContextMenu));
20823 }
20824
20825 if(this.table.options.rowClickMenu){
20826 this.subscribe("row-click", this.loadMenuEvent.bind(this, this.table.options.rowClickMenu));
20827 }
20828
20829 if(this.table.options.rowDblClickMenu){
20830 this.subscribe("row-dblclick", this.loadMenuEvent.bind(this, this.table.options.rowDblClickMenu));
20831 }
20832 }
20833
20834 initializeGroupWatchers(){
20835 if(this.table.options.groupContextMenu){
20836 this.subscribe("group-contextmenu", this.loadMenuEvent.bind(this, this.table.options.groupContextMenu));
20837 this.table.on("groupTapHold", this.loadMenuEvent.bind(this, this.table.options.groupContextMenu));
20838 }
20839
20840 if(this.table.options.groupClickMenu){
20841 this.subscribe("group-click", this.loadMenuEvent.bind(this, this.table.options.groupClickMenu));
20842 }
20843
20844 if(this.table.options.groupDblClickMenu){
20845 this.subscribe("group-dblclick", this.loadMenuEvent.bind(this, this.table.options.groupDblClickMenu));
20846 }
20847 }
20848
20849 initializeColumn(column){
20850 var def = column.definition;
20851
20852 //handle column events
20853 if(def.headerContextMenu && !this.columnSubscribers.headerContextMenu){
20854 this.columnSubscribers.headerContextMenu = this.loadMenuTableColumnEvent.bind(this, "headerContextMenu");
20855 this.subscribe("column-contextmenu", this.columnSubscribers.headerContextMenu);
20856 this.table.on("headerTapHold", this.loadMenuTableColumnEvent.bind(this, "headerContextMenu"));
20857 }
20858
20859 if(def.headerClickMenu && !this.columnSubscribers.headerClickMenu){
20860 this.columnSubscribers.headerClickMenu = this.loadMenuTableColumnEvent.bind(this, "headerClickMenu");
20861 this.subscribe("column-click", this.columnSubscribers.headerClickMenu);
20862 }
20863
20864 if(def.headerDblClickMenu && !this.columnSubscribers.headerDblClickMenu){
20865 this.columnSubscribers.headerDblClickMenu = this.loadMenuTableColumnEvent.bind(this, "headerDblClickMenu");
20866 this.subscribe("column-dblclick", this.columnSubscribers.headerDblClickMenu);
20867 }
20868
20869 if(def.headerMenu){
20870 this.initializeColumnHeaderMenu(column);
20871 }
20872
20873 //handle cell events
20874 if(def.contextMenu && !this.columnSubscribers.contextMenu){
20875 this.columnSubscribers.contextMenu = this.loadMenuTableCellEvent.bind(this, "contextMenu");
20876 this.subscribe("cell-contextmenu", this.columnSubscribers.contextMenu);
20877 this.table.on("cellTapHold", this.loadMenuTableCellEvent.bind(this, "contextMenu"));
20878 }
20879
20880 if(def.clickMenu && !this.columnSubscribers.clickMenu){
20881 this.columnSubscribers.clickMenu = this.loadMenuTableCellEvent.bind(this, "clickMenu");
20882 this.subscribe("cell-click", this.columnSubscribers.clickMenu);
20883 }
20884
20885 if(def.dblClickMenu && !this.columnSubscribers.dblClickMenu){
20886 this.columnSubscribers.dblClickMenu = this.loadMenuTableCellEvent.bind(this, "dblClickMenu");
20887 this.subscribe("cell-dblclick", this.columnSubscribers.dblClickMenu);
20888 }
20889 }
20890
20891 initializeColumnHeaderMenu(column){
20892 var icon = column.definition.headerMenuIcon,
20893 headerMenuEl;
20894
20895 headerMenuEl = document.createElement("span");
20896 headerMenuEl.classList.add("tabulator-header-popup-button");
20897
20898 if(icon){
20899 if(typeof icon === "function"){
20900 icon = icon(column.getComponent());
20901 }
20902
20903 if(icon instanceof HTMLElement){
20904 headerMenuEl.appendChild(icon);
20905 }else {
20906 headerMenuEl.innerHTML = icon;
20907 }
20908 }else {
20909 headerMenuEl.innerHTML = "&vellip;";
20910 }
20911
20912 headerMenuEl.addEventListener("click", (e) => {
20913 e.stopPropagation();
20914 e.preventDefault();
20915
20916 this.loadMenuEvent(column.definition.headerMenu, e, column);
20917 });
20918
20919 column.titleElement.insertBefore(headerMenuEl, column.titleElement.firstChild);
20920 }
20921
20922 loadMenuTableCellEvent(option, e, cell){
20923 if(cell._cell){
20924 cell = cell._cell;
20925 }
20926
20927 if(cell.column.definition[option]){
20928 this.loadMenuEvent(cell.column.definition[option], e, cell);
20929 }
20930 }
20931
20932 loadMenuTableColumnEvent(option, e, column){
20933 if(column._column){
20934 column = column._column;
20935 }
20936
20937 if(column.definition[option]){
20938 this.loadMenuEvent(column.definition[option], e, column);
20939 }
20940 }
20941
20942 loadMenuEvent(menu, e, component){
20943 if(component._group){
20944 component = component._group;
20945 }else if(component._row){
20946 component = component._row;
20947 }
20948
20949 menu = typeof menu == "function" ? menu.call(this.table, e, component.getComponent()) : menu;
20950
20951 this.loadMenu(e, component, menu);
20952 }
20953
20954 loadMenu(e, component, menu, parentEl, parentPopup){
20955 var touch = !(e instanceof MouseEvent),
20956 menuEl = document.createElement("div"),
20957 popup;
20958
20959 menuEl.classList.add("tabulator-menu");
20960
20961 if(!touch){
20962 e.preventDefault();
20963 }
20964
20965 //abort if no menu set
20966 if(!menu || !menu.length){
20967 return;
20968 }
20969
20970 if(!parentEl){
20971 if(this.nestedMenuBlock){
20972 //abort if child menu already open
20973 if(this.rootPopup){
20974 return;
20975 }
20976 }else {
20977 this.nestedMenuBlock = setTimeout(() => {
20978 this.nestedMenuBlock = false;
20979 }, 100);
20980 }
20981
20982 if(this.rootPopup){
20983 this.rootPopup.hide();
20984 }
20985
20986 this.rootPopup = popup = this.popup(menuEl);
20987
20988 }else {
20989 popup = parentPopup.child(menuEl);
20990 }
20991
20992 menu.forEach((item) => {
20993 var itemEl = document.createElement("div"),
20994 label = item.label,
20995 disabled = item.disabled;
20996
20997 if(item.separator){
20998 itemEl.classList.add("tabulator-menu-separator");
20999 }else {
21000 itemEl.classList.add("tabulator-menu-item");
21001
21002 if(typeof label == "function"){
21003 label = label.call(this.table, component.getComponent());
21004 }
21005
21006 if(label instanceof Node){
21007 itemEl.appendChild(label);
21008 }else {
21009 itemEl.innerHTML = label;
21010 }
21011
21012 if(typeof disabled == "function"){
21013 disabled = disabled.call(this.table, component.getComponent());
21014 }
21015
21016 if(disabled){
21017 itemEl.classList.add("tabulator-menu-item-disabled");
21018 itemEl.addEventListener("click", (e) => {
21019 e.stopPropagation();
21020 });
21021 }else {
21022 if(item.menu && item.menu.length){
21023 itemEl.addEventListener("click", (e) => {
21024 e.stopPropagation();
21025 this.loadMenu(e, component, item.menu, itemEl, popup);
21026 });
21027 }else {
21028 if(item.action){
21029 itemEl.addEventListener("click", (e) => {
21030 item.action(e, component.getComponent());
21031 });
21032 }
21033 }
21034 }
21035
21036 if(item.menu && item.menu.length){
21037 itemEl.classList.add("tabulator-menu-item-submenu");
21038 }
21039 }
21040
21041 menuEl.appendChild(itemEl);
21042 });
21043
21044 menuEl.addEventListener("click", (e) => {
21045 if(this.rootPopup){
21046 this.rootPopup.hide();
21047 }
21048 });
21049
21050 popup.show(parentEl || e);
21051
21052 if(popup === this.rootPopup){
21053 this.rootPopup.hideOnBlur(() => {
21054 this.rootPopup = null;
21055
21056 if(this.currentComponent){
21057 this.dispatch("menu-closed", menu, popup);
21058 this.dispatchExternal("menuClosed", this.currentComponent.getComponent());
21059 this.currentComponent = null;
21060 }
21061 });
21062
21063 this.currentComponent = component;
21064
21065 this.dispatch("menu-opened", menu, popup);
21066 this.dispatchExternal("menuOpened", component.getComponent());
21067 }
21068 }
21069 }
21070
21071 class MoveColumns extends Module{
21072
21073 static moduleName = "moveColumn";
21074
21075 constructor(table){
21076 super(table);
21077
21078 this.placeholderElement = this.createPlaceholderElement();
21079 this.hoverElement = false; //floating column header element
21080 this.checkTimeout = false; //click check timeout holder
21081 this.checkPeriod = 250; //period to wait on mousedown to consider this a move and not a click
21082 this.moving = false; //currently moving column
21083 this.toCol = false; //destination column
21084 this.toColAfter = false; //position of moving column relative to the destination column
21085 this.startX = 0; //starting position within header element
21086 this.autoScrollMargin = 40; //auto scroll on edge when within margin
21087 this.autoScrollStep = 5; //auto scroll distance in pixels
21088 this.autoScrollTimeout = false; //auto scroll timeout
21089 this.touchMove = false;
21090
21091 this.moveHover = this.moveHover.bind(this);
21092 this.endMove = this.endMove.bind(this);
21093
21094 this.registerTableOption("movableColumns", false); //enable movable columns
21095 }
21096
21097 createPlaceholderElement(){
21098 var el = document.createElement("div");
21099
21100 el.classList.add("tabulator-col");
21101 el.classList.add("tabulator-col-placeholder");
21102
21103 return el;
21104 }
21105
21106 initialize(){
21107 if(this.table.options.movableColumns){
21108 this.subscribe("column-init", this.initializeColumn.bind(this));
21109 this.subscribe("alert-show", this.abortMove.bind(this));
21110 }
21111 }
21112
21113 abortMove(){
21114 clearTimeout(this.checkTimeout);
21115 }
21116
21117 initializeColumn(column){
21118 var self = this,
21119 config = {},
21120 colEl;
21121
21122 if(!column.modules.frozen && !column.isGroup && !column.isRowHeader){
21123 colEl = column.getElement();
21124
21125 config.mousemove = function(e){
21126 if(column.parent === self.moving.parent){
21127 if((((self.touchMove ? e.touches[0].pageX : e.pageX) - Helpers.elOffset(colEl).left) + self.table.columnManager.contentsElement.scrollLeft) > (column.getWidth() / 2)){
21128 if(self.toCol !== column || !self.toColAfter){
21129 colEl.parentNode.insertBefore(self.placeholderElement, colEl.nextSibling);
21130 self.moveColumn(column, true);
21131 }
21132 }else {
21133 if(self.toCol !== column || self.toColAfter){
21134 colEl.parentNode.insertBefore(self.placeholderElement, colEl);
21135 self.moveColumn(column, false);
21136 }
21137 }
21138 }
21139 }.bind(self);
21140
21141 colEl.addEventListener("mousedown", function(e){
21142 self.touchMove = false;
21143 if(e.which === 1){
21144 self.checkTimeout = setTimeout(function(){
21145 self.startMove(e, column);
21146 }, self.checkPeriod);
21147 }
21148 });
21149
21150 colEl.addEventListener("mouseup", function(e){
21151 if(e.which === 1){
21152 if(self.checkTimeout){
21153 clearTimeout(self.checkTimeout);
21154 }
21155 }
21156 });
21157
21158 self.bindTouchEvents(column);
21159 }
21160
21161 column.modules.moveColumn = config;
21162 }
21163
21164 bindTouchEvents(column){
21165 var colEl = column.getElement(),
21166 startXMove = false, //shifting center position of the cell
21167 nextCol, prevCol, nextColWidth, prevColWidth, nextColWidthLast, prevColWidthLast;
21168
21169 colEl.addEventListener("touchstart", (e) => {
21170 this.checkTimeout = setTimeout(() => {
21171 this.touchMove = true;
21172 nextCol = column.nextColumn();
21173 nextColWidth = nextCol ? nextCol.getWidth()/2 : 0;
21174 prevCol = column.prevColumn();
21175 prevColWidth = prevCol ? prevCol.getWidth()/2 : 0;
21176 nextColWidthLast = 0;
21177 prevColWidthLast = 0;
21178 startXMove = false;
21179
21180 this.startMove(e, column);
21181 }, this.checkPeriod);
21182 }, {passive: true});
21183
21184 colEl.addEventListener("touchmove", (e) => {
21185 var diff, moveToCol;
21186
21187 if(this.moving){
21188 this.moveHover(e);
21189
21190 if(!startXMove){
21191 startXMove = e.touches[0].pageX;
21192 }
21193
21194 diff = e.touches[0].pageX - startXMove;
21195
21196 if(diff > 0){
21197 if(nextCol && diff - nextColWidthLast > nextColWidth){
21198 moveToCol = nextCol;
21199
21200 if(moveToCol !== column){
21201 startXMove = e.touches[0].pageX;
21202 moveToCol.getElement().parentNode.insertBefore(this.placeholderElement, moveToCol.getElement().nextSibling);
21203 this.moveColumn(moveToCol, true);
21204 }
21205 }
21206 }else {
21207 if(prevCol && -diff - prevColWidthLast > prevColWidth){
21208 moveToCol = prevCol;
21209
21210 if(moveToCol !== column){
21211 startXMove = e.touches[0].pageX;
21212 moveToCol.getElement().parentNode.insertBefore(this.placeholderElement, moveToCol.getElement());
21213 this.moveColumn(moveToCol, false);
21214 }
21215 }
21216 }
21217
21218 if(moveToCol){
21219 nextCol = moveToCol.nextColumn();
21220 nextColWidthLast = nextColWidth;
21221 nextColWidth = nextCol ? nextCol.getWidth() / 2 : 0;
21222 prevCol = moveToCol.prevColumn();
21223 prevColWidthLast = prevColWidth;
21224 prevColWidth = prevCol ? prevCol.getWidth() / 2 : 0;
21225 }
21226 }
21227 }, {passive: true});
21228
21229 colEl.addEventListener("touchend", (e) => {
21230 if(this.checkTimeout){
21231 clearTimeout(this.checkTimeout);
21232 }
21233 if(this.moving){
21234 this.endMove(e);
21235 }
21236 });
21237 }
21238
21239 startMove(e, column){
21240 var element = column.getElement(),
21241 headerElement = this.table.columnManager.getContentsElement(),
21242 headersElement = this.table.columnManager.getHeadersElement();
21243
21244 //Prevent moving columns when range selection is active
21245 if(this.table.modules.selectRange && this.table.modules.selectRange.columnSelection){
21246 if(this.table.modules.selectRange.mousedown && this.table.modules.selectRange.selecting === "column"){
21247 return;
21248 }
21249 }
21250
21251 this.moving = column;
21252 this.startX = (this.touchMove ? e.touches[0].pageX : e.pageX) - Helpers.elOffset(element).left;
21253
21254 this.table.element.classList.add("tabulator-block-select");
21255
21256 //create placeholder
21257 this.placeholderElement.style.width = column.getWidth() + "px";
21258 this.placeholderElement.style.height = column.getHeight() + "px";
21259
21260 element.parentNode.insertBefore(this.placeholderElement, element);
21261 element.parentNode.removeChild(element);
21262
21263 //create hover element
21264 this.hoverElement = element.cloneNode(true);
21265 this.hoverElement.classList.add("tabulator-moving");
21266
21267 headerElement.appendChild(this.hoverElement);
21268
21269 this.hoverElement.style.left = "0";
21270 this.hoverElement.style.bottom = (headerElement.clientHeight - headersElement.offsetHeight) + "px";
21271
21272 if(!this.touchMove){
21273 this._bindMouseMove();
21274
21275 document.body.addEventListener("mousemove", this.moveHover);
21276 document.body.addEventListener("mouseup", this.endMove);
21277 }
21278
21279 this.moveHover(e);
21280
21281 this.dispatch("column-moving", e, this.moving);
21282 }
21283
21284 _bindMouseMove(){
21285 this.table.columnManager.columnsByIndex.forEach(function(column){
21286 if(column.modules.moveColumn.mousemove){
21287 column.getElement().addEventListener("mousemove", column.modules.moveColumn.mousemove);
21288 }
21289 });
21290 }
21291
21292 _unbindMouseMove(){
21293 this.table.columnManager.columnsByIndex.forEach(function(column){
21294 if(column.modules.moveColumn.mousemove){
21295 column.getElement().removeEventListener("mousemove", column.modules.moveColumn.mousemove);
21296 }
21297 });
21298 }
21299
21300 moveColumn(column, after){
21301 var movingCells = this.moving.getCells();
21302
21303 this.toCol = column;
21304 this.toColAfter = after;
21305
21306 if(after){
21307 column.getCells().forEach(function(cell, i){
21308 var cellEl = cell.getElement(true);
21309
21310 if(cellEl.parentNode && movingCells[i]){
21311 cellEl.parentNode.insertBefore(movingCells[i].getElement(), cellEl.nextSibling);
21312 }
21313 });
21314 }else {
21315 column.getCells().forEach(function(cell, i){
21316 var cellEl = cell.getElement(true);
21317
21318 if(cellEl.parentNode && movingCells[i]){
21319 cellEl.parentNode.insertBefore(movingCells[i].getElement(), cellEl);
21320 }
21321 });
21322 }
21323 }
21324
21325 endMove(e){
21326 if(e.which === 1 || this.touchMove){
21327 this._unbindMouseMove();
21328
21329 this.placeholderElement.parentNode.insertBefore(this.moving.getElement(), this.placeholderElement.nextSibling);
21330 this.placeholderElement.parentNode.removeChild(this.placeholderElement);
21331 this.hoverElement.parentNode.removeChild(this.hoverElement);
21332
21333 this.table.element.classList.remove("tabulator-block-select");
21334
21335 if(this.toCol){
21336 this.table.columnManager.moveColumnActual(this.moving, this.toCol, this.toColAfter);
21337 }
21338
21339 this.moving = false;
21340 this.toCol = false;
21341 this.toColAfter = false;
21342
21343 if(!this.touchMove){
21344 document.body.removeEventListener("mousemove", this.moveHover);
21345 document.body.removeEventListener("mouseup", this.endMove);
21346 }
21347 }
21348 }
21349
21350 moveHover(e){
21351 var columnHolder = this.table.columnManager.getContentsElement(),
21352 scrollLeft = columnHolder.scrollLeft,
21353 xPos = ((this.touchMove ? e.touches[0].pageX : e.pageX) - Helpers.elOffset(columnHolder).left) + scrollLeft,
21354 scrollPos;
21355
21356 this.hoverElement.style.left = (xPos - this.startX) + "px";
21357
21358 if(xPos - scrollLeft < this.autoScrollMargin){
21359 if(!this.autoScrollTimeout){
21360 this.autoScrollTimeout = setTimeout(() => {
21361 scrollPos = Math.max(0,scrollLeft-5);
21362 this.table.rowManager.getElement().scrollLeft = scrollPos;
21363 this.autoScrollTimeout = false;
21364 }, 1);
21365 }
21366 }
21367
21368 if(scrollLeft + columnHolder.clientWidth - xPos < this.autoScrollMargin){
21369 if(!this.autoScrollTimeout){
21370 this.autoScrollTimeout = setTimeout(() => {
21371 scrollPos = Math.min(columnHolder.clientWidth, scrollLeft+5);
21372 this.table.rowManager.getElement().scrollLeft = scrollPos;
21373 this.autoScrollTimeout = false;
21374 }, 1);
21375 }
21376 }
21377 }
21378 }
21379
21380 var defaultSenders = {
21381 delete:function(fromRow, toRow, toTable){
21382 fromRow.delete();
21383 }
21384 };
21385
21386 var defaultReceivers = {
21387 insert:function(fromRow, toRow, fromTable){
21388 this.table.addRow(fromRow.getData(), undefined, toRow);
21389 return true;
21390 },
21391
21392 add:function(fromRow, toRow, fromTable){
21393 this.table.addRow(fromRow.getData());
21394 return true;
21395 },
21396
21397 update:function(fromRow, toRow, fromTable){
21398 if(toRow){
21399 toRow.update(fromRow.getData());
21400 return true;
21401 }
21402
21403 return false;
21404 },
21405
21406 replace:function(fromRow, toRow, fromTable){
21407 if(toRow){
21408 this.table.addRow(fromRow.getData(), undefined, toRow);
21409 toRow.delete();
21410 return true;
21411 }
21412
21413 return false;
21414 },
21415 };
21416
21417 class MoveRows extends Module{
21418
21419 static moduleName = "moveRow";
21420
21421 //load defaults
21422 static senders = defaultSenders;
21423 static receivers = defaultReceivers;
21424
21425 constructor(table){
21426 super(table);
21427
21428 this.placeholderElement = this.createPlaceholderElement();
21429 this.hoverElement = false; //floating row header element
21430 this.checkTimeout = false; //click check timeout holder
21431 this.checkPeriod = 150; //period to wait on mousedown to consider this a move and not a click
21432 this.moving = false; //currently moving row
21433 this.toRow = false; //destination row
21434 this.toRowAfter = false; //position of moving row relative to the destination row
21435 this.hasHandle = false; //row has handle instead of fully movable row
21436 this.startY = 0; //starting Y position within header element
21437 this.startX = 0; //starting X position within header element
21438
21439 this.moveHover = this.moveHover.bind(this);
21440 this.endMove = this.endMove.bind(this);
21441 this.tableRowDropEvent = false;
21442
21443 this.touchMove = false;
21444
21445 this.connection = false;
21446 this.connectionSelectorsTables = false;
21447 this.connectionSelectorsElements = false;
21448 this.connectionElements = [];
21449 this.connections = [];
21450
21451 this.connectedTable = false;
21452 this.connectedRow = false;
21453
21454 this.registerTableOption("movableRows", false); //enable movable rows
21455 this.registerTableOption("movableRowsConnectedTables", false); //tables for movable rows to be connected to
21456 this.registerTableOption("movableRowsConnectedElements", false); //other elements for movable rows to be connected to
21457 this.registerTableOption("movableRowsSender", false);
21458 this.registerTableOption("movableRowsReceiver", "insert");
21459
21460 this.registerColumnOption("rowHandle");
21461 }
21462
21463 createPlaceholderElement(){
21464 var el = document.createElement("div");
21465
21466 el.classList.add("tabulator-row");
21467 el.classList.add("tabulator-row-placeholder");
21468
21469 return el;
21470 }
21471
21472 initialize(){
21473 if(this.table.options.movableRows){
21474 this.connectionSelectorsTables = this.table.options.movableRowsConnectedTables;
21475 this.connectionSelectorsElements = this.table.options.movableRowsConnectedElements;
21476
21477 this.connection = this.connectionSelectorsTables || this.connectionSelectorsElements;
21478
21479 this.subscribe("cell-init", this.initializeCell.bind(this));
21480 this.subscribe("column-init", this.initializeColumn.bind(this));
21481 this.subscribe("row-init", this.initializeRow.bind(this));
21482 }
21483 }
21484
21485 initializeGroupHeader(group){
21486 var self = this,
21487 config = {};
21488
21489 //inter table drag drop
21490 config.mouseup = function(e){
21491 self.tableRowDrop(e, group);
21492 }.bind(self);
21493
21494 //same table drag drop
21495 config.mousemove = function(e){
21496 var rowEl;
21497
21498 if(((e.pageY - Helpers.elOffset(group.element).top) + self.table.rowManager.element.scrollTop) > (group.getHeight() / 2)){
21499 if(self.toRow !== group || !self.toRowAfter){
21500 rowEl = group.getElement();
21501 rowEl.parentNode.insertBefore(self.placeholderElement, rowEl.nextSibling);
21502 self.moveRow(group, true);
21503 }
21504 }else {
21505 if(self.toRow !== group || self.toRowAfter){
21506 rowEl = group.getElement();
21507 if(rowEl.previousSibling){
21508 rowEl.parentNode.insertBefore(self.placeholderElement, rowEl);
21509 self.moveRow(group, false);
21510 }
21511 }
21512 }
21513 }.bind(self);
21514
21515 group.modules.moveRow = config;
21516 }
21517
21518 initializeRow(row){
21519 var self = this,
21520 config = {},
21521 rowEl;
21522
21523 //inter table drag drop
21524 config.mouseup = function(e){
21525 self.tableRowDrop(e, row);
21526 }.bind(self);
21527
21528 //same table drag drop
21529 config.mousemove = function(e){
21530 var rowEl = row.getElement();
21531
21532 if(((e.pageY - Helpers.elOffset(rowEl).top) + self.table.rowManager.element.scrollTop) > (row.getHeight() / 2)){
21533 if(self.toRow !== row || !self.toRowAfter){
21534 rowEl.parentNode.insertBefore(self.placeholderElement, rowEl.nextSibling);
21535 self.moveRow(row, true);
21536 }
21537 }else {
21538 if(self.toRow !== row || self.toRowAfter){
21539 rowEl.parentNode.insertBefore(self.placeholderElement, rowEl);
21540 self.moveRow(row, false);
21541 }
21542 }
21543 }.bind(self);
21544
21545
21546 if(!this.hasHandle){
21547
21548 rowEl = row.getElement();
21549
21550 rowEl.addEventListener("mousedown", function(e){
21551 if(e.which === 1){
21552 self.checkTimeout = setTimeout(function(){
21553 self.startMove(e, row);
21554 }, self.checkPeriod);
21555 }
21556 });
21557
21558 rowEl.addEventListener("mouseup", function(e){
21559 if(e.which === 1){
21560 if(self.checkTimeout){
21561 clearTimeout(self.checkTimeout);
21562 }
21563 }
21564 });
21565
21566 this.bindTouchEvents(row, row.getElement());
21567 }
21568
21569 row.modules.moveRow = config;
21570 }
21571
21572 initializeColumn(column){
21573 if(column.definition.rowHandle && this.table.options.movableRows !== false){
21574 this.hasHandle = true;
21575 }
21576 }
21577
21578 initializeCell(cell){
21579 if(cell.column.definition.rowHandle && this.table.options.movableRows !== false){
21580 var self = this,
21581 cellEl = cell.getElement(true);
21582
21583 cellEl.addEventListener("mousedown", function(e){
21584 if(e.which === 1){
21585 self.checkTimeout = setTimeout(function(){
21586 self.startMove(e, cell.row);
21587 }, self.checkPeriod);
21588 }
21589 });
21590
21591 cellEl.addEventListener("mouseup", function(e){
21592 if(e.which === 1){
21593 if(self.checkTimeout){
21594 clearTimeout(self.checkTimeout);
21595 }
21596 }
21597 });
21598
21599 this.bindTouchEvents(cell.row, cellEl);
21600 }
21601 }
21602
21603 bindTouchEvents(row, element){
21604 var startYMove = false, //shifting center position of the cell
21605 nextRow, prevRow, nextRowHeight, prevRowHeight, nextRowHeightLast, prevRowHeightLast;
21606
21607 element.addEventListener("touchstart", (e) => {
21608 this.checkTimeout = setTimeout(() => {
21609 this.touchMove = true;
21610 nextRow = row.nextRow();
21611 nextRowHeight = nextRow ? nextRow.getHeight()/2 : 0;
21612 prevRow = row.prevRow();
21613 prevRowHeight = prevRow ? prevRow.getHeight()/2 : 0;
21614 nextRowHeightLast = 0;
21615 prevRowHeightLast = 0;
21616 startYMove = false;
21617
21618 this.startMove(e, row);
21619 }, this.checkPeriod);
21620 }, {passive: true});
21621 this.moving, this.toRow, this.toRowAfter;
21622 element.addEventListener("touchmove", (e) => {
21623
21624 var diff, moveToRow;
21625
21626 if(this.moving){
21627 e.preventDefault();
21628
21629 this.moveHover(e);
21630
21631 if(!startYMove){
21632 startYMove = e.touches[0].pageY;
21633 }
21634
21635 diff = e.touches[0].pageY - startYMove;
21636
21637 if(diff > 0){
21638 if(nextRow && diff - nextRowHeightLast > nextRowHeight){
21639 moveToRow = nextRow;
21640
21641 if(moveToRow !== row){
21642 startYMove = e.touches[0].pageY;
21643 moveToRow.getElement().parentNode.insertBefore(this.placeholderElement, moveToRow.getElement().nextSibling);
21644 this.moveRow(moveToRow, true);
21645 }
21646 }
21647 }else {
21648 if(prevRow && -diff - prevRowHeightLast > prevRowHeight){
21649 moveToRow = prevRow;
21650
21651 if(moveToRow !== row){
21652 startYMove = e.touches[0].pageY;
21653 moveToRow.getElement().parentNode.insertBefore(this.placeholderElement, moveToRow.getElement());
21654 this.moveRow(moveToRow, false);
21655 }
21656 }
21657 }
21658
21659 if(moveToRow){
21660 nextRow = moveToRow.nextRow();
21661 nextRowHeightLast = nextRowHeight;
21662 nextRowHeight = nextRow ? nextRow.getHeight() / 2 : 0;
21663 prevRow = moveToRow.prevRow();
21664 prevRowHeightLast = prevRowHeight;
21665 prevRowHeight = prevRow ? prevRow.getHeight() / 2 : 0;
21666 }
21667 }
21668 });
21669
21670 element.addEventListener("touchend", (e) => {
21671 if(this.checkTimeout){
21672 clearTimeout(this.checkTimeout);
21673 }
21674 if(this.moving){
21675 this.endMove(e);
21676 this.touchMove = false;
21677 }
21678 });
21679 }
21680
21681 _bindMouseMove(){
21682 this.table.rowManager.getDisplayRows().forEach((row) => {
21683 if((row.type === "row" || row.type === "group") && row.modules.moveRow && row.modules.moveRow.mousemove){
21684 row.getElement().addEventListener("mousemove", row.modules.moveRow.mousemove);
21685 }
21686 });
21687 }
21688
21689 _unbindMouseMove(){
21690 this.table.rowManager.getDisplayRows().forEach((row) => {
21691 if((row.type === "row" || row.type === "group") && row.modules.moveRow && row.modules.moveRow.mousemove){
21692 row.getElement().removeEventListener("mousemove", row.modules.moveRow.mousemove);
21693 }
21694 });
21695 }
21696
21697 startMove(e, row){
21698 var element = row.getElement();
21699
21700 this.setStartPosition(e, row);
21701
21702 this.moving = row;
21703
21704 this.table.element.classList.add("tabulator-block-select");
21705
21706 //create placeholder
21707 this.placeholderElement.style.width = row.getWidth() + "px";
21708 this.placeholderElement.style.height = row.getHeight() + "px";
21709
21710 if(!this.connection){
21711 element.parentNode.insertBefore(this.placeholderElement, element);
21712 element.parentNode.removeChild(element);
21713 }else {
21714 this.table.element.classList.add("tabulator-movingrow-sending");
21715 this.connectToTables(row);
21716 }
21717
21718 //create hover element
21719 this.hoverElement = element.cloneNode(true);
21720 this.hoverElement.classList.add("tabulator-moving");
21721
21722 if(this.connection){
21723 document.body.appendChild(this.hoverElement);
21724 this.hoverElement.style.left = "0";
21725 this.hoverElement.style.top = "0";
21726 this.hoverElement.style.width = this.table.element.clientWidth + "px";
21727 this.hoverElement.style.whiteSpace = "nowrap";
21728 this.hoverElement.style.overflow = "hidden";
21729 this.hoverElement.style.pointerEvents = "none";
21730 }else {
21731 this.table.rowManager.getTableElement().appendChild(this.hoverElement);
21732
21733 this.hoverElement.style.left = "0";
21734 this.hoverElement.style.top = "0";
21735
21736 this._bindMouseMove();
21737 }
21738
21739 document.body.addEventListener("mousemove", this.moveHover);
21740 document.body.addEventListener("mouseup", this.endMove);
21741
21742 this.dispatchExternal("rowMoving", row.getComponent());
21743
21744 this.moveHover(e);
21745 }
21746
21747 setStartPosition(e, row){
21748 var pageX = this.touchMove ? e.touches[0].pageX : e.pageX,
21749 pageY = this.touchMove ? e.touches[0].pageY : e.pageY,
21750 element, position;
21751
21752 element = row.getElement();
21753 if(this.connection){
21754 position = element.getBoundingClientRect();
21755
21756 this.startX = position.left - pageX + window.pageXOffset;
21757 this.startY = position.top - pageY + window.pageYOffset;
21758 }else {
21759 this.startY = (pageY - element.getBoundingClientRect().top);
21760 }
21761 }
21762
21763 endMove(e){
21764 if(!e || e.which === 1 || this.touchMove){
21765 this._unbindMouseMove();
21766
21767 if(!this.connection){
21768 this.placeholderElement.parentNode.insertBefore(this.moving.getElement(), this.placeholderElement.nextSibling);
21769 this.placeholderElement.parentNode.removeChild(this.placeholderElement);
21770 }
21771
21772 this.hoverElement.parentNode.removeChild(this.hoverElement);
21773
21774 this.table.element.classList.remove("tabulator-block-select");
21775
21776 if(this.toRow){
21777 this.table.rowManager.moveRow(this.moving, this.toRow, this.toRowAfter);
21778 }else {
21779 this.dispatchExternal("rowMoveCancelled", this.moving.getComponent());
21780 }
21781
21782 this.moving = false;
21783 this.toRow = false;
21784 this.toRowAfter = false;
21785
21786 document.body.removeEventListener("mousemove", this.moveHover);
21787 document.body.removeEventListener("mouseup", this.endMove);
21788
21789 if(this.connection){
21790 this.table.element.classList.remove("tabulator-movingrow-sending");
21791 this.disconnectFromTables();
21792 }
21793 }
21794 }
21795
21796 moveRow(row, after){
21797 this.toRow = row;
21798 this.toRowAfter = after;
21799 }
21800
21801 moveHover(e){
21802 if(this.connection){
21803 this.moveHoverConnections.call(this, e);
21804 }else {
21805 this.moveHoverTable.call(this, e);
21806 }
21807 }
21808
21809 moveHoverTable(e){
21810 var rowHolder = this.table.rowManager.getElement(),
21811 scrollTop = rowHolder.scrollTop,
21812 yPos = ((this.touchMove ? e.touches[0].pageY : e.pageY) - rowHolder.getBoundingClientRect().top) + scrollTop;
21813
21814 this.hoverElement.style.top = Math.min(yPos - this.startY, this.table.rowManager.element.scrollHeight - this.hoverElement.offsetHeight) + "px";
21815 }
21816
21817 moveHoverConnections(e){
21818 this.hoverElement.style.left = (this.startX + (this.touchMove ? e.touches[0].pageX : e.pageX)) + "px";
21819 this.hoverElement.style.top = (this.startY + (this.touchMove ? e.touches[0].pageY : e.pageY)) + "px";
21820 }
21821
21822 elementRowDrop(e, element, row){
21823 this.dispatchExternal("movableRowsElementDrop", e, element, row ? row.getComponent() : false);
21824 }
21825
21826 //establish connection with other tables
21827 connectToTables(row){
21828 var connectionTables;
21829
21830 if(this.connectionSelectorsTables){
21831 connectionTables = this.commsConnections(this.connectionSelectorsTables);
21832
21833 this.dispatchExternal("movableRowsSendingStart", connectionTables);
21834
21835 this.commsSend(this.connectionSelectorsTables, "moveRow", "connect", {
21836 row:row,
21837 });
21838 }
21839
21840 if(this.connectionSelectorsElements){
21841
21842 this.connectionElements = [];
21843
21844 if(!Array.isArray(this.connectionSelectorsElements)){
21845 this.connectionSelectorsElements = [this.connectionSelectorsElements];
21846 }
21847
21848 this.connectionSelectorsElements.forEach((query) => {
21849 if(typeof query === "string"){
21850 this.connectionElements = this.connectionElements.concat(Array.prototype.slice.call(document.querySelectorAll(query)));
21851 }else {
21852 this.connectionElements.push(query);
21853 }
21854 });
21855
21856 this.connectionElements.forEach((element) => {
21857 var dropEvent = (e) => {
21858 this.elementRowDrop(e, element, this.moving);
21859 };
21860
21861 element.addEventListener("mouseup", dropEvent);
21862 element.tabulatorElementDropEvent = dropEvent;
21863
21864 element.classList.add("tabulator-movingrow-receiving");
21865 });
21866 }
21867 }
21868
21869 //disconnect from other tables
21870 disconnectFromTables(){
21871 var connectionTables;
21872
21873 if(this.connectionSelectorsTables){
21874 connectionTables = this.commsConnections(this.connectionSelectorsTables);
21875
21876 this.dispatchExternal("movableRowsSendingStop", connectionTables);
21877
21878 this.commsSend(this.connectionSelectorsTables, "moveRow", "disconnect");
21879 }
21880
21881 this.connectionElements.forEach((element) => {
21882 element.classList.remove("tabulator-movingrow-receiving");
21883 element.removeEventListener("mouseup", element.tabulatorElementDropEvent);
21884 delete element.tabulatorElementDropEvent;
21885 });
21886 }
21887
21888 //accept incomming connection
21889 connect(table, row){
21890 if(!this.connectedTable){
21891 this.connectedTable = table;
21892 this.connectedRow = row;
21893
21894 this.table.element.classList.add("tabulator-movingrow-receiving");
21895
21896 this.table.rowManager.getDisplayRows().forEach((row) => {
21897 if(row.type === "row" && row.modules.moveRow && row.modules.moveRow.mouseup){
21898 row.getElement().addEventListener("mouseup", row.modules.moveRow.mouseup);
21899 }
21900 });
21901
21902 this.tableRowDropEvent = this.tableRowDrop.bind(this);
21903
21904 this.table.element.addEventListener("mouseup", this.tableRowDropEvent);
21905
21906 this.dispatchExternal("movableRowsReceivingStart", row, table);
21907
21908 return true;
21909 }else {
21910 console.warn("Move Row Error - Table cannot accept connection, already connected to table:", this.connectedTable);
21911 return false;
21912 }
21913 }
21914
21915 //close incoming connection
21916 disconnect(table){
21917 if(table === this.connectedTable){
21918 this.connectedTable = false;
21919 this.connectedRow = false;
21920
21921 this.table.element.classList.remove("tabulator-movingrow-receiving");
21922
21923 this.table.rowManager.getDisplayRows().forEach((row) =>{
21924 if(row.type === "row" && row.modules.moveRow && row.modules.moveRow.mouseup){
21925 row.getElement().removeEventListener("mouseup", row.modules.moveRow.mouseup);
21926 }
21927 });
21928
21929 this.table.element.removeEventListener("mouseup", this.tableRowDropEvent);
21930
21931 this.dispatchExternal("movableRowsReceivingStop", table);
21932 }else {
21933 console.warn("Move Row Error - trying to disconnect from non connected table");
21934 }
21935 }
21936
21937 dropComplete(table, row, success){
21938 var sender = false;
21939
21940 if(success){
21941
21942 switch(typeof this.table.options.movableRowsSender){
21943 case "string":
21944 sender = MoveRows.senders[this.table.options.movableRowsSender];
21945 break;
21946
21947 case "function":
21948 sender = this.table.options.movableRowsSender;
21949 break;
21950 }
21951
21952 if(sender){
21953 sender.call(this, this.moving ? this.moving.getComponent() : undefined, row ? row.getComponent() : undefined, table);
21954 }else {
21955 if(this.table.options.movableRowsSender){
21956 console.warn("Mover Row Error - no matching sender found:", this.table.options.movableRowsSender);
21957 }
21958 }
21959
21960 this.dispatchExternal("movableRowsSent", this.moving.getComponent(), row ? row.getComponent() : undefined, table);
21961 }else {
21962 this.dispatchExternal("movableRowsSentFailed", this.moving.getComponent(), row ? row.getComponent() : undefined, table);
21963 }
21964
21965 this.endMove();
21966 }
21967
21968 tableRowDrop(e, row){
21969 var receiver = false,
21970 success = false;
21971
21972 e.stopImmediatePropagation();
21973
21974 switch(typeof this.table.options.movableRowsReceiver){
21975 case "string":
21976 receiver = MoveRows.receivers[this.table.options.movableRowsReceiver];
21977 break;
21978
21979 case "function":
21980 receiver = this.table.options.movableRowsReceiver;
21981 break;
21982 }
21983
21984 if(receiver){
21985 success = receiver.call(this, this.connectedRow.getComponent(), row ? row.getComponent() : undefined, this.connectedTable);
21986 }else {
21987 console.warn("Mover Row Error - no matching receiver found:", this.table.options.movableRowsReceiver);
21988 }
21989
21990 if(success){
21991 this.dispatchExternal("movableRowsReceived", this.connectedRow.getComponent(), row ? row.getComponent() : undefined, this.connectedTable);
21992 }else {
21993 this.dispatchExternal("movableRowsReceivedFailed", this.connectedRow.getComponent(), row ? row.getComponent() : undefined, this.connectedTable);
21994 }
21995
21996 this.commsSend(this.connectedTable, "moveRow", "dropcomplete", {
21997 row:row,
21998 success:success,
21999 });
22000 }
22001
22002 commsReceived(table, action, data){
22003 switch(action){
22004 case "connect":
22005 return this.connect(table, data.row);
22006
22007 case "disconnect":
22008 return this.disconnect(table);
22009
22010 case "dropcomplete":
22011 return this.dropComplete(table, data.row, data.success);
22012 }
22013 }
22014 }
22015
22016 var defaultMutators = {};
22017
22018 class Mutator extends Module{
22019
22020 static moduleName = "mutator";
22021
22022 //load defaults
22023 static mutators = defaultMutators;
22024
22025 constructor(table){
22026 super(table);
22027
22028 this.allowedTypes = ["", "data", "edit", "clipboard", "import"]; //list of mutation types
22029 this.enabled = true;
22030
22031 this.registerColumnOption("mutator");
22032 this.registerColumnOption("mutatorParams");
22033 this.registerColumnOption("mutatorData");
22034 this.registerColumnOption("mutatorDataParams");
22035 this.registerColumnOption("mutatorEdit");
22036 this.registerColumnOption("mutatorEditParams");
22037 this.registerColumnOption("mutatorClipboard");
22038 this.registerColumnOption("mutatorClipboardParams");
22039 this.registerColumnOption("mutatorImport");
22040 this.registerColumnOption("mutatorImportParams");
22041 this.registerColumnOption("mutateLink");
22042 }
22043
22044 initialize(){
22045 this.subscribe("cell-value-changing", this.transformCell.bind(this));
22046 this.subscribe("cell-value-changed", this.mutateLink.bind(this));
22047 this.subscribe("column-layout", this.initializeColumn.bind(this));
22048 this.subscribe("row-data-init-before", this.rowDataChanged.bind(this));
22049 this.subscribe("row-data-changing", this.rowDataChanged.bind(this));
22050 }
22051
22052 rowDataChanged(row, tempData, updatedData){
22053 return this.transformRow(tempData, "data", updatedData);
22054 }
22055
22056 //initialize column mutator
22057 initializeColumn(column){
22058 var match = false,
22059 config = {};
22060
22061 this.allowedTypes.forEach((type) => {
22062 var key = "mutator" + (type.charAt(0).toUpperCase() + type.slice(1)),
22063 mutator;
22064
22065 if(column.definition[key]){
22066 mutator = this.lookupMutator(column.definition[key]);
22067
22068 if(mutator){
22069 match = true;
22070
22071 config[key] = {
22072 mutator:mutator,
22073 params: column.definition[key + "Params"] || {},
22074 };
22075 }
22076 }
22077 });
22078
22079 if(match){
22080 column.modules.mutate = config;
22081 }
22082 }
22083
22084 lookupMutator(value){
22085 var mutator = false;
22086
22087 //set column mutator
22088 switch(typeof value){
22089 case "string":
22090 if(Mutator.mutators[value]){
22091 mutator = Mutator.mutators[value];
22092 }else {
22093 console.warn("Mutator Error - No such mutator found, ignoring: ", value);
22094 }
22095 break;
22096
22097 case "function":
22098 mutator = value;
22099 break;
22100 }
22101
22102 return mutator;
22103 }
22104
22105 //apply mutator to row
22106 transformRow(data, type, updatedData){
22107 var key = "mutator" + (type.charAt(0).toUpperCase() + type.slice(1)),
22108 value;
22109
22110 // console.log("key", key)
22111
22112 if(this.enabled){
22113
22114 this.table.columnManager.traverse((column) => {
22115 var mutator, params, component;
22116
22117 if(column.modules.mutate){
22118 mutator = column.modules.mutate[key] || column.modules.mutate.mutator || false;
22119
22120 if(mutator){
22121 value = column.getFieldValue(typeof updatedData !== "undefined" ? updatedData : data);
22122
22123 if((type == "data" && !updatedData)|| typeof value !== "undefined"){
22124 component = column.getComponent();
22125 params = typeof mutator.params === "function" ? mutator.params(value, data, type, component) : mutator.params;
22126 column.setFieldValue(data, mutator.mutator(value, data, type, params, component));
22127 }
22128 }
22129 }
22130 });
22131 }
22132
22133 return data;
22134 }
22135
22136 //apply mutator to new cell value
22137 transformCell(cell, value){
22138 if(cell.column.modules.mutate){
22139 var mutator = cell.column.modules.mutate.mutatorEdit || cell.column.modules.mutate.mutator || false,
22140 tempData = {};
22141
22142 if(mutator){
22143 tempData = Object.assign(tempData, cell.row.getData());
22144 cell.column.setFieldValue(tempData, value);
22145 return mutator.mutator(value, tempData, "edit", mutator.params, cell.getComponent());
22146 }
22147 }
22148
22149 return value;
22150 }
22151
22152 mutateLink(cell){
22153 var links = cell.column.definition.mutateLink;
22154
22155 if(links){
22156 if(!Array.isArray(links)){
22157 links = [links];
22158 }
22159
22160 links.forEach((link) => {
22161 var linkCell = cell.row.getCell(link);
22162
22163 if(linkCell){
22164 linkCell.setValue(linkCell.getValue(), true, true);
22165 }
22166 });
22167 }
22168 }
22169
22170 enable(){
22171 this.enabled = true;
22172 }
22173
22174 disable(){
22175 this.enabled = false;
22176 }
22177 }
22178
22179 function rows(pageSize, currentRow, currentPage, totalRows, totalPages){
22180 var el = document.createElement("span"),
22181 showingEl = document.createElement("span"),
22182 valueEl = document.createElement("span"),
22183 ofEl = document.createElement("span"),
22184 totalEl = document.createElement("span"),
22185 rowsEl = document.createElement("span");
22186
22187 this.table.modules.localize.langBind("pagination|counter|showing", (value) => {
22188 showingEl.innerHTML = value;
22189 });
22190
22191 this.table.modules.localize.langBind("pagination|counter|of", (value) => {
22192 ofEl.innerHTML = value;
22193 });
22194
22195 this.table.modules.localize.langBind("pagination|counter|rows", (value) => {
22196 rowsEl.innerHTML = value;
22197 });
22198
22199 if(totalRows){
22200 valueEl.innerHTML = " " + currentRow + "-" + Math.min((currentRow + pageSize - 1), totalRows) + " ";
22201
22202 totalEl.innerHTML = " " + totalRows + " ";
22203
22204 el.appendChild(showingEl);
22205 el.appendChild(valueEl);
22206 el.appendChild(ofEl);
22207 el.appendChild(totalEl);
22208 el.appendChild(rowsEl);
22209 }else {
22210 valueEl.innerHTML = " 0 ";
22211
22212 el.appendChild(showingEl);
22213 el.appendChild(valueEl);
22214 el.appendChild(rowsEl);
22215 }
22216
22217 return el;
22218 }
22219
22220 function pages(pageSize, currentRow, currentPage, totalRows, totalPages){
22221
22222 var el = document.createElement("span"),
22223 showingEl = document.createElement("span"),
22224 valueEl = document.createElement("span"),
22225 ofEl = document.createElement("span"),
22226 totalEl = document.createElement("span"),
22227 rowsEl = document.createElement("span");
22228
22229 this.table.modules.localize.langBind("pagination|counter|showing", (value) => {
22230 showingEl.innerHTML = value;
22231 });
22232
22233 valueEl.innerHTML = " " + currentPage + " ";
22234
22235 this.table.modules.localize.langBind("pagination|counter|of", (value) => {
22236 ofEl.innerHTML = value;
22237 });
22238
22239 totalEl.innerHTML = " " + totalPages + " ";
22240
22241 this.table.modules.localize.langBind("pagination|counter|pages", (value) => {
22242 rowsEl.innerHTML = value;
22243 });
22244
22245 el.appendChild(showingEl);
22246 el.appendChild(valueEl);
22247 el.appendChild(ofEl);
22248 el.appendChild(totalEl);
22249 el.appendChild(rowsEl);
22250
22251 return el;
22252 }
22253
22254 var defaultPageCounters = {
22255 rows:rows,
22256 pages:pages,
22257 };
22258
22259 class Page extends Module{
22260
22261 static moduleName = "page";
22262
22263 //load defaults
22264 static pageCounters = defaultPageCounters;
22265
22266 constructor(table){
22267 super(table);
22268
22269 this.mode = "local";
22270 this.progressiveLoad = false;
22271
22272 this.element = null;
22273 this.pageCounterElement = null;
22274 this.pageCounter = null;
22275
22276 this.size = 0;
22277 this.page = 1;
22278 this.count = 5;
22279 this.max = 1;
22280
22281 this.remoteRowCountEstimate = null;
22282
22283 this.initialLoad = true;
22284 this.dataChanging = false; //flag to check if data is being changed by this module
22285
22286 this.pageSizes = [];
22287
22288 this.registerTableOption("pagination", false); //set pagination type
22289 this.registerTableOption("paginationMode", "local"); //local or remote pagination
22290 this.registerTableOption("paginationSize", false); //set number of rows to a page
22291 this.registerTableOption("paginationInitialPage", 1); //initial page to show on load
22292 this.registerTableOption("paginationCounter", false); // set pagination counter
22293 this.registerTableOption("paginationCounterElement", false); // set pagination counter
22294 this.registerTableOption("paginationButtonCount", 5); // set count of page button
22295 this.registerTableOption("paginationSizeSelector", false); //add pagination size selector element
22296 this.registerTableOption("paginationElement", false); //element to hold pagination numbers
22297 // this.registerTableOption("paginationDataSent", {}); //pagination data sent to the server
22298 // this.registerTableOption("paginationDataReceived", {}); //pagination data received from the server
22299 this.registerTableOption("paginationAddRow", "page"); //add rows on table or page
22300 this.registerTableOption("paginationOutOfRange", false); //reset the current page when the last page < this.page, values: false|function|any value accepted by setPage()
22301
22302 this.registerTableOption("progressiveLoad", false); //progressive loading
22303 this.registerTableOption("progressiveLoadDelay", 0); //delay between requests
22304 this.registerTableOption("progressiveLoadScrollMargin", 0); //margin before scroll begins
22305
22306 this.registerTableFunction("setMaxPage", this.setMaxPage.bind(this));
22307 this.registerTableFunction("setPage", this.setPage.bind(this));
22308 this.registerTableFunction("setPageToRow", this.userSetPageToRow.bind(this));
22309 this.registerTableFunction("setPageSize", this.userSetPageSize.bind(this));
22310 this.registerTableFunction("getPageSize", this.getPageSize.bind(this));
22311 this.registerTableFunction("previousPage", this.previousPage.bind(this));
22312 this.registerTableFunction("nextPage", this.nextPage.bind(this));
22313 this.registerTableFunction("getPage", this.getPage.bind(this));
22314 this.registerTableFunction("getPageMax", this.getPageMax.bind(this));
22315
22316 //register component functions
22317 this.registerComponentFunction("row", "pageTo", this.setPageToRow.bind(this));
22318 }
22319
22320 initialize(){
22321 if(this.table.options.pagination){
22322 this.subscribe("row-deleted", this.rowsUpdated.bind(this));
22323 this.subscribe("row-added", this.rowsUpdated.bind(this));
22324 this.subscribe("data-processed", this.initialLoadComplete.bind(this));
22325 this.subscribe("table-built", this.calculatePageSizes.bind(this));
22326 this.subscribe("footer-redraw", this.footerRedraw.bind(this));
22327
22328 if(this.table.options.paginationAddRow == "page"){
22329 this.subscribe("row-adding-position", this.rowAddingPosition.bind(this));
22330 }
22331
22332 if(this.table.options.paginationMode === "remote"){
22333 this.subscribe("data-params", this.remotePageParams.bind(this));
22334 this.subscribe("data-loaded", this._parseRemoteData.bind(this));
22335 }
22336
22337 if(this.table.options.progressiveLoad){
22338 console.error("Progressive Load Error - Pagination and progressive load cannot be used at the same time");
22339 }
22340
22341 this.registerDisplayHandler(this.restOnRenderBefore.bind(this), 40);
22342 this.registerDisplayHandler(this.getRows.bind(this), 50);
22343
22344 this.createElements();
22345 this.initializePageCounter();
22346 this.initializePaginator();
22347 }else if(this.table.options.progressiveLoad){
22348 this.subscribe("data-params", this.remotePageParams.bind(this));
22349 this.subscribe("data-loaded", this._parseRemoteData.bind(this));
22350 this.subscribe("table-built", this.calculatePageSizes.bind(this));
22351 this.subscribe("data-processed", this.initialLoadComplete.bind(this));
22352
22353 this.initializeProgressive(this.table.options.progressiveLoad);
22354
22355 if(this.table.options.progressiveLoad === "scroll"){
22356 this.subscribe("scroll-vertical", this.scrollVertical.bind(this));
22357 }
22358 }
22359 }
22360
22361 rowAddingPosition(row, top){
22362 var rowManager = this.table.rowManager,
22363 displayRows = rowManager.getDisplayRows(),
22364 index;
22365
22366 if(top){
22367 if(displayRows.length){
22368 index = displayRows[0];
22369 }else {
22370 if(rowManager.activeRows.length){
22371 index = rowManager.activeRows[rowManager.activeRows.length-1];
22372 top = false;
22373 }
22374 }
22375 }else {
22376 if(displayRows.length){
22377 index = displayRows[displayRows.length - 1];
22378 top = displayRows.length < this.size ? false : true;
22379 }
22380 }
22381
22382 return {index, top};
22383 }
22384
22385 calculatePageSizes(){
22386 var testElRow, testElCell;
22387
22388 if(this.table.options.paginationSize){
22389 this.size = this.table.options.paginationSize;
22390 }else {
22391 testElRow = document.createElement("div");
22392 testElRow.classList.add("tabulator-row");
22393 testElRow.style.visibility = "hidden";
22394
22395 testElCell = document.createElement("div");
22396 testElCell.classList.add("tabulator-cell");
22397 testElCell.innerHTML = "Page Row Test";
22398
22399 testElRow.appendChild(testElCell);
22400
22401 this.table.rowManager.getTableElement().appendChild(testElRow);
22402
22403 this.size = Math.floor(this.table.rowManager.getElement().clientHeight / testElRow.offsetHeight);
22404
22405 this.table.rowManager.getTableElement().removeChild(testElRow);
22406 }
22407
22408 this.dispatchExternal("pageSizeChanged", this.size);
22409
22410 this.generatePageSizeSelectList();
22411 }
22412
22413 initialLoadComplete(){
22414 this.initialLoad = false;
22415 }
22416
22417 remotePageParams(data, config, silent, params){
22418 if(!this.initialLoad){
22419 if((this.progressiveLoad && !silent) || (!this.progressiveLoad && !this.dataChanging)){
22420 this.reset(true);
22421 }
22422 }
22423
22424 //configure request params
22425 params.page = this.page;
22426
22427 //set page size if defined
22428 if(this.size){
22429 params.size = this.size;
22430 }
22431
22432 return params;
22433 }
22434
22435 ///////////////////////////////////
22436 ///////// Table Functions /////////
22437 ///////////////////////////////////
22438
22439 userSetPageToRow(row){
22440 if(this.table.options.pagination){
22441 row = this.table.rowManager.findRow(row);
22442
22443 if(row){
22444 return this.setPageToRow(row);
22445 }
22446 }
22447
22448 return Promise.reject();
22449 }
22450
22451 userSetPageSize(size){
22452 if(this.table.options.pagination){
22453 this.setPageSize(size);
22454 return this.setPage(1);
22455 }else {
22456 return false;
22457 }
22458 }
22459 ///////////////////////////////////
22460 ///////// Internal Logic //////////
22461 ///////////////////////////////////
22462
22463 scrollVertical(top, dir){
22464 var element, diff, margin;
22465 if(!dir && !this.table.dataLoader.loading){
22466 element = this.table.rowManager.getElement();
22467 diff = element.scrollHeight - element.clientHeight - top;
22468 margin = this.table.options.progressiveLoadScrollMargin || (element.clientHeight * 2);
22469
22470 if(diff < margin){
22471 this.nextPage()
22472 .catch(() => {}); //consume the exception thrown when on the last page
22473 }
22474 }
22475 }
22476
22477 restOnRenderBefore(rows, renderInPosition){
22478 if(!renderInPosition){
22479 if(this.mode === "local"){
22480 this.reset();
22481 }
22482 }
22483
22484 return rows;
22485 }
22486
22487 rowsUpdated(){
22488 this.refreshData(true, "all");
22489 }
22490
22491 createElements(){
22492 var button;
22493
22494 this.element = document.createElement("span");
22495 this.element.classList.add("tabulator-paginator");
22496
22497 this.pagesElement = document.createElement("span");
22498 this.pagesElement.classList.add("tabulator-pages");
22499
22500 button = document.createElement("button");
22501 button.classList.add("tabulator-page");
22502 button.setAttribute("type", "button");
22503 button.setAttribute("role", "button");
22504 button.setAttribute("aria-label", "");
22505 button.setAttribute("title", "");
22506
22507 this.firstBut = button.cloneNode(true);
22508 this.firstBut.setAttribute("data-page", "first");
22509
22510 this.prevBut = button.cloneNode(true);
22511 this.prevBut.setAttribute("data-page", "prev");
22512
22513 this.nextBut = button.cloneNode(true);
22514 this.nextBut.setAttribute("data-page", "next");
22515
22516 this.lastBut = button.cloneNode(true);
22517 this.lastBut.setAttribute("data-page", "last");
22518
22519 if(this.table.options.paginationSizeSelector){
22520 this.pageSizeSelect = document.createElement("select");
22521 this.pageSizeSelect.classList.add("tabulator-page-size");
22522 }
22523 }
22524
22525 generatePageSizeSelectList(){
22526 var pageSizes = [];
22527
22528 if(this.pageSizeSelect){
22529
22530 if(Array.isArray(this.table.options.paginationSizeSelector)){
22531 pageSizes = this.table.options.paginationSizeSelector;
22532 this.pageSizes = pageSizes;
22533
22534 if(this.pageSizes.indexOf(this.size) == -1){
22535 pageSizes.unshift(this.size);
22536 }
22537 }else {
22538
22539 if(this.pageSizes.indexOf(this.size) == -1){
22540 pageSizes = [];
22541
22542 for (let i = 1; i < 5; i++){
22543 pageSizes.push(this.size * i);
22544 }
22545
22546 this.pageSizes = pageSizes;
22547 }else {
22548 pageSizes = this.pageSizes;
22549 }
22550 }
22551
22552 while(this.pageSizeSelect.firstChild) this.pageSizeSelect.removeChild(this.pageSizeSelect.firstChild);
22553
22554 pageSizes.forEach((item) => {
22555 var itemEl = document.createElement("option");
22556 itemEl.value = item;
22557
22558 if(item === true){
22559 this.langBind("pagination|all", function(value){
22560 itemEl.innerHTML = value;
22561 });
22562 }else {
22563 itemEl.innerHTML = item;
22564 }
22565
22566
22567
22568 this.pageSizeSelect.appendChild(itemEl);
22569 });
22570
22571 this.pageSizeSelect.value = this.size;
22572 }
22573 }
22574
22575 initializePageCounter(){
22576 var counter = this.table.options.paginationCounter,
22577 pageCounter = null;
22578
22579 if(counter){
22580 if(typeof counter === "function"){
22581 pageCounter = counter;
22582 }else {
22583 pageCounter = Page.pageCounters[counter];
22584 }
22585
22586 if(pageCounter){
22587 this.pageCounter = pageCounter;
22588
22589 this.pageCounterElement = document.createElement("span");
22590 this.pageCounterElement.classList.add("tabulator-page-counter");
22591 }else {
22592 console.warn("Pagination Error - No such page counter found: ", counter);
22593 }
22594 }
22595 }
22596
22597 //setup pagination
22598 initializePaginator(hidden){
22599 var pageSelectLabel, paginationCounterHolder;
22600
22601 if(!hidden){
22602 //build pagination element
22603
22604 //bind localizations
22605 this.langBind("pagination|first", (value) => {
22606 this.firstBut.innerHTML = value;
22607 });
22608
22609 this.langBind("pagination|first_title", (value) => {
22610 this.firstBut.setAttribute("aria-label", value);
22611 this.firstBut.setAttribute("title", value);
22612 });
22613
22614 this.langBind("pagination|prev", (value) => {
22615 this.prevBut.innerHTML = value;
22616 });
22617
22618 this.langBind("pagination|prev_title", (value) => {
22619 this.prevBut.setAttribute("aria-label", value);
22620 this.prevBut.setAttribute("title", value);
22621 });
22622
22623 this.langBind("pagination|next", (value) => {
22624 this.nextBut.innerHTML = value;
22625 });
22626
22627 this.langBind("pagination|next_title", (value) => {
22628 this.nextBut.setAttribute("aria-label", value);
22629 this.nextBut.setAttribute("title", value);
22630 });
22631
22632 this.langBind("pagination|last", (value) => {
22633 this.lastBut.innerHTML = value;
22634 });
22635
22636 this.langBind("pagination|last_title", (value) => {
22637 this.lastBut.setAttribute("aria-label", value);
22638 this.lastBut.setAttribute("title", value);
22639 });
22640
22641 //click bindings
22642 this.firstBut.addEventListener("click", () => {
22643 this.setPage(1);
22644 });
22645
22646 this.prevBut.addEventListener("click", () => {
22647 this.previousPage();
22648 });
22649
22650 this.nextBut.addEventListener("click", () => {
22651 this.nextPage();
22652 });
22653
22654 this.lastBut.addEventListener("click", () => {
22655 this.setPage(this.max);
22656 });
22657
22658 if(this.table.options.paginationElement){
22659 this.element = this.table.options.paginationElement;
22660 }
22661
22662 if(this.pageSizeSelect){
22663 pageSelectLabel = document.createElement("label");
22664
22665 this.langBind("pagination|page_size", (value) => {
22666 this.pageSizeSelect.setAttribute("aria-label", value);
22667 this.pageSizeSelect.setAttribute("title", value);
22668 pageSelectLabel.innerHTML = value;
22669 });
22670
22671 this.element.appendChild(pageSelectLabel);
22672 this.element.appendChild(this.pageSizeSelect);
22673
22674 this.pageSizeSelect.addEventListener("change", (e) => {
22675 this.setPageSize(this.pageSizeSelect.value == "true" ? true : this.pageSizeSelect.value);
22676 this.setPage(1);
22677 });
22678 }
22679
22680 //append to DOM
22681 this.element.appendChild(this.firstBut);
22682 this.element.appendChild(this.prevBut);
22683 this.element.appendChild(this.pagesElement);
22684 this.element.appendChild(this.nextBut);
22685 this.element.appendChild(this.lastBut);
22686
22687 if(!this.table.options.paginationElement){
22688 if(this.table.options.paginationCounter){
22689
22690 if(this.table.options.paginationCounterElement){
22691 if(this.table.options.paginationCounterElement instanceof HTMLElement){
22692 this.table.options.paginationCounterElement.appendChild(this.pageCounterElement);
22693 }else if(typeof this.table.options.paginationCounterElement === "string"){
22694 paginationCounterHolder = document.querySelector(this.table.options.paginationCounterElement);
22695
22696 if(paginationCounterHolder){
22697 paginationCounterHolder.appendChild(this.pageCounterElement);
22698 }else {
22699 console.warn("Pagination Error - Unable to find element matching paginationCounterElement selector:", this.table.options.paginationCounterElement);
22700 }
22701 }
22702 }else {
22703 this.footerAppend(this.pageCounterElement);
22704 }
22705
22706 }
22707
22708 this.footerAppend(this.element);
22709 }
22710
22711 this.page = this.table.options.paginationInitialPage;
22712 this.count = this.table.options.paginationButtonCount;
22713 }
22714
22715 //set default values
22716 this.mode = this.table.options.paginationMode;
22717 }
22718
22719 initializeProgressive(mode){
22720 this.initializePaginator(true);
22721 this.mode = "progressive_" + mode;
22722 this.progressiveLoad = true;
22723 }
22724
22725 trackChanges(){
22726 this.dispatch("page-changed");
22727 }
22728
22729 //calculate maximum page from number of rows
22730 setMaxRows(rowCount){
22731 if(!rowCount){
22732 this.max = 1;
22733 }else {
22734 this.max = this.size === true ? 1 : Math.ceil(rowCount/this.size);
22735 }
22736
22737 if(this.page > this.max){
22738 this.page = this.max;
22739 }
22740 }
22741
22742 //reset to first page without triggering action
22743 reset(force){
22744 if(!this.initialLoad){
22745 if(this.mode == "local" || force){
22746 this.page = 1;
22747 this.trackChanges();
22748 }
22749 }
22750 }
22751
22752 //set the maximum page
22753 setMaxPage(max){
22754
22755 max = parseInt(max);
22756
22757 this.max = max || 1;
22758
22759 if(this.page > this.max){
22760 this.page = this.max;
22761 this.trigger();
22762 }
22763 }
22764
22765 //set current page number
22766 setPage(page){
22767 switch(page){
22768 case "first":
22769 return this.setPage(1);
22770
22771 case "prev":
22772 return this.previousPage();
22773
22774 case "next":
22775 return this.nextPage();
22776
22777 case "last":
22778 return this.setPage(this.max);
22779 }
22780
22781 page = parseInt(page);
22782
22783 if((page > 0 && page <= this.max) || this.mode !== "local"){
22784 this.page = page;
22785
22786 this.trackChanges();
22787
22788 return this.trigger();
22789 }else {
22790 console.warn("Pagination Error - Requested page is out of range of 1 - " + this.max + ":", page);
22791 return Promise.reject();
22792 }
22793 }
22794
22795 setPageToRow(row){
22796 var rows = this.displayRows(-1);
22797 var index = rows.indexOf(row);
22798
22799 if(index > -1){
22800 var page = this.size === true ? 1 : Math.ceil((index + 1) / this.size);
22801
22802 return this.setPage(page);
22803 }else {
22804 console.warn("Pagination Error - Requested row is not visible");
22805 return Promise.reject();
22806 }
22807 }
22808
22809 setPageSize(size){
22810 if(size !== true){
22811 size = parseInt(size);
22812 }
22813
22814 if(size > 0){
22815 this.size = size;
22816 this.dispatchExternal("pageSizeChanged", size);
22817 }
22818
22819 if(this.pageSizeSelect){
22820 // this.pageSizeSelect.value = size;
22821 this.generatePageSizeSelectList();
22822 }
22823
22824 this.trackChanges();
22825 }
22826
22827 _setPageCounter(totalRows, size, currentRow){
22828 var content;
22829
22830 if(this.pageCounter){
22831
22832 if(this.mode === "remote"){
22833 size = this.size;
22834 currentRow = ((this.page - 1) * this.size) + 1;
22835 totalRows = this.remoteRowCountEstimate;
22836 }
22837
22838 content = this.pageCounter.call(this, size, currentRow, this.page, totalRows, this.max);
22839
22840 switch(typeof content){
22841 case "object":
22842 if(content instanceof Node){
22843
22844 //clear previous cell contents
22845 while(this.pageCounterElement.firstChild) this.pageCounterElement.removeChild(this.pageCounterElement.firstChild);
22846
22847 this.pageCounterElement.appendChild(content);
22848 }else {
22849 this.pageCounterElement.innerHTML = "";
22850
22851 if(content != null){
22852 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);
22853 }
22854 }
22855 break;
22856 case "undefined":
22857 this.pageCounterElement.innerHTML = "";
22858 break;
22859 default:
22860 this.pageCounterElement.innerHTML = content;
22861 }
22862 }
22863 }
22864
22865 //setup the pagination buttons
22866 _setPageButtons(){
22867 let leftSize = Math.floor((this.count-1) / 2);
22868 let rightSize = Math.ceil((this.count-1) / 2);
22869 let min = this.max - this.page + leftSize + 1 < this.count ? this.max-this.count+1: Math.max(this.page-leftSize,1);
22870 let max = this.page <= rightSize? Math.min(this.count, this.max) :Math.min(this.page+rightSize, this.max);
22871
22872 while(this.pagesElement.firstChild) this.pagesElement.removeChild(this.pagesElement.firstChild);
22873
22874 if(this.page == 1){
22875 this.firstBut.disabled = true;
22876 this.prevBut.disabled = true;
22877 }else {
22878 this.firstBut.disabled = false;
22879 this.prevBut.disabled = false;
22880 }
22881
22882 if(this.page == this.max){
22883 this.lastBut.disabled = true;
22884 this.nextBut.disabled = true;
22885 }else {
22886 this.lastBut.disabled = false;
22887 this.nextBut.disabled = false;
22888 }
22889
22890 for(let i = min; i <= max; i++){
22891 if(i>0 && i <= this.max){
22892 this.pagesElement.appendChild(this._generatePageButton(i));
22893 }
22894 }
22895
22896 this.footerRedraw();
22897 }
22898
22899 _generatePageButton(page){
22900 var button = document.createElement("button");
22901
22902 button.classList.add("tabulator-page");
22903 if(page == this.page){
22904 button.classList.add("active");
22905 }
22906
22907 button.setAttribute("type", "button");
22908 button.setAttribute("role", "button");
22909
22910 this.langBind("pagination|page_title", (value) => {
22911 button.setAttribute("aria-label", value + " " + page);
22912 button.setAttribute("title", value + " " + page);
22913 });
22914
22915 button.setAttribute("data-page", page);
22916 button.textContent = page;
22917
22918 button.addEventListener("click", (e) => {
22919 this.setPage(page);
22920 });
22921
22922 return button;
22923 }
22924
22925 //previous page
22926 previousPage(){
22927 if(this.page > 1){
22928 this.page--;
22929
22930 this.trackChanges();
22931
22932 return this.trigger();
22933
22934 }else {
22935 console.warn("Pagination Error - Previous page would be less than page 1:", 0);
22936 return Promise.reject();
22937 }
22938 }
22939
22940 //next page
22941 nextPage(){
22942 if(this.page < this.max){
22943 this.page++;
22944
22945 this.trackChanges();
22946
22947 return this.trigger();
22948
22949 }else {
22950 if(!this.progressiveLoad){
22951 console.warn("Pagination Error - Next page would be greater than maximum page of " + this.max + ":", this.max + 1);
22952 }
22953 return Promise.reject();
22954 }
22955 }
22956
22957 //return current page number
22958 getPage(){
22959 return this.page;
22960 }
22961
22962 //return max page number
22963 getPageMax(){
22964 return this.max;
22965 }
22966
22967 getPageSize(size){
22968 return this.size;
22969 }
22970
22971 getMode(){
22972 return this.mode;
22973 }
22974
22975 //return appropriate rows for current page
22976 getRows(data){
22977 var actualRowPageSize = 0,
22978 output, start, end, actualStartRow;
22979
22980 var actualRows = data.filter((row) => {
22981 return row.type === "row";
22982 });
22983
22984 if(this.mode == "local"){
22985 output = [];
22986
22987 this.setMaxRows(data.length);
22988
22989 if(this.size === true){
22990 start = 0;
22991 end = data.length;
22992 }else {
22993 start = this.size * (this.page - 1);
22994 end = start + parseInt(this.size);
22995 }
22996
22997 this._setPageButtons();
22998
22999 for(let i = start; i < end; i++){
23000 let row = data[i];
23001
23002 if(row){
23003 output.push(row);
23004
23005 if(row.type === "row"){
23006 if(!actualStartRow){
23007 actualStartRow = row;
23008 }
23009
23010 actualRowPageSize++;
23011 }
23012 }
23013 }
23014
23015 this._setPageCounter(actualRows.length, actualRowPageSize, actualStartRow ? (actualRows.indexOf(actualStartRow) + 1) : 0);
23016
23017 return output;
23018 }else {
23019 this._setPageButtons();
23020 this._setPageCounter(actualRows.length);
23021
23022 return data.slice(0);
23023 }
23024 }
23025
23026 trigger(){
23027 var left;
23028
23029 switch(this.mode){
23030 case "local":
23031 left = this.table.rowManager.scrollLeft;
23032
23033 this.refreshData();
23034 this.table.rowManager.scrollHorizontal(left);
23035
23036 this.dispatchExternal("pageLoaded", this.getPage());
23037
23038 return Promise.resolve();
23039
23040 case "remote":
23041 this.dataChanging = true;
23042 return this.reloadData(null)
23043 .finally(() => {
23044 this.dataChanging = false;
23045 });
23046
23047 case "progressive_load":
23048 case "progressive_scroll":
23049 return this.reloadData(null, true);
23050
23051 default:
23052 console.warn("Pagination Error - no such pagination mode:", this.mode);
23053 return Promise.reject();
23054 }
23055 }
23056
23057 _parseRemoteData(data){
23058 var margin, paginationOutOfRange;
23059
23060 if(typeof data.last_page === "undefined"){
23061 console.warn("Remote Pagination Error - Server response missing '" + (this.options("dataReceiveParams").last_page || "last_page") + "' property");
23062 }
23063
23064 if(data.data){
23065 this.max = parseInt(data.last_page) || 1;
23066
23067 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));
23068
23069 if(this.progressiveLoad){
23070 switch(this.mode){
23071 case "progressive_load":
23072
23073 if(this.page == 1){
23074 this.table.rowManager.setData(data.data, false, this.page == 1);
23075 }else {
23076 this.table.rowManager.addRows(data.data);
23077 }
23078
23079 if(this.page < this.max){
23080 setTimeout(() => {
23081 this.nextPage();
23082 }, this.table.options.progressiveLoadDelay);
23083 }
23084 break;
23085
23086 case "progressive_scroll":
23087 data = this.page === 1 ? data.data : this.table.rowManager.getData().concat(data.data);
23088
23089 this.table.rowManager.setData(data, this.page !== 1, this.page == 1);
23090
23091 margin = this.table.options.progressiveLoadScrollMargin || (this.table.rowManager.element.clientHeight * 2);
23092
23093 if(this.table.rowManager.element.scrollHeight <= (this.table.rowManager.element.clientHeight + margin)){
23094 if(this.page < this.max){
23095 setTimeout(() => {
23096 this.nextPage();
23097 });
23098 }
23099 }
23100 break;
23101 }
23102
23103 return false;
23104 }else {
23105
23106 if(this.page > this.max){
23107 console.warn( "Remote Pagination Error - Server returned last page value lower than the current page" );
23108
23109 paginationOutOfRange = this.options('paginationOutOfRange');
23110
23111 if(paginationOutOfRange){
23112 return this.setPage(typeof paginationOutOfRange === 'function' ? paginationOutOfRange.call(this, this.page, this.max) : paginationOutOfRange);
23113 }
23114 }
23115
23116 // left = this.table.rowManager.scrollLeft;
23117 this.dispatchExternal("pageLoaded", this.getPage());
23118 // this.table.rowManager.scrollHorizontal(left);
23119 // this.table.columnManager.scrollHorizontal(left);
23120 }
23121
23122 }else {
23123 console.warn("Remote Pagination Error - Server response missing '" + (this.options("dataReceiveParams").data || "data") + "' property");
23124 }
23125
23126 return data.data;
23127 }
23128
23129 //handle the footer element being redrawn
23130 footerRedraw(){
23131 var footer = this.table.footerManager.containerElement;
23132
23133 if((Math.ceil(footer.clientWidth) - footer.scrollWidth) < 0){
23134 this.pagesElement.style.display = 'none';
23135 }else {
23136 this.pagesElement.style.display = '';
23137
23138 if((Math.ceil(footer.clientWidth) - footer.scrollWidth) < 0){
23139 this.pagesElement.style.display = 'none';
23140 }
23141 }
23142 }
23143 }
23144
23145 // read persistance information from storage
23146 var defaultReaders = {
23147 local:function(id, type){
23148 var data = localStorage.getItem(id + "-" + type);
23149
23150 return data ? JSON.parse(data) : false;
23151 },
23152 cookie:function(id, type){
23153 var cookie = document.cookie,
23154 key = id + "-" + type,
23155 cookiePos = cookie.indexOf(key + "="),
23156 end, data;
23157
23158 //if cookie exists, decode and load column data into tabulator
23159 if(cookiePos > -1){
23160 cookie = cookie.slice(cookiePos);
23161
23162 end = cookie.indexOf(";");
23163
23164 if(end > -1){
23165 cookie = cookie.slice(0, end);
23166 }
23167
23168 data = cookie.replace(key + "=", "");
23169 }
23170
23171 return data ? JSON.parse(data) : false;
23172 }
23173 };
23174
23175 //write persistence information to storage
23176 var defaultWriters = {
23177 local:function(id, type, data){
23178 localStorage.setItem(id + "-" + type, JSON.stringify(data));
23179 },
23180 cookie:function(id, type, data){
23181 var expireDate = new Date();
23182
23183 expireDate.setDate(expireDate.getDate() + 10000);
23184
23185 document.cookie = id + "-" + type + "=" + JSON.stringify(data) + "; expires=" + expireDate.toUTCString();
23186 }
23187 };
23188
23189 class Persistence extends Module{
23190
23191 static moduleName = "persistence";
23192
23193 static moduleInitOrder = -10;
23194
23195 //load defaults
23196 static readers = defaultReaders;
23197 static writers = defaultWriters;
23198
23199 constructor(table){
23200 super(table);
23201
23202 this.mode = "";
23203 this.id = "";
23204 // this.persistProps = ["field", "width", "visible"];
23205 this.defWatcherBlock = false;
23206 this.config = {};
23207 this.readFunc = false;
23208 this.writeFunc = false;
23209
23210 this.registerTableOption("persistence", false);
23211 this.registerTableOption("persistenceID", ""); //key for persistent storage
23212 this.registerTableOption("persistenceMode", true); //mode for storing persistence information
23213 this.registerTableOption("persistenceReaderFunc", false); //function for handling persistence data reading
23214 this.registerTableOption("persistenceWriterFunc", false); //function for handling persistence data writing
23215 }
23216
23217 // Test for whether localStorage is available for use.
23218 localStorageTest() {
23219 var testKey = "_tabulator_test";
23220
23221 try {
23222 window.localStorage.setItem( testKey, testKey);
23223 window.localStorage.removeItem( testKey );
23224 return true;
23225 } catch(e) {
23226 return false;
23227 }
23228 }
23229
23230 //setup parameters
23231 initialize(){
23232 if(this.table.options.persistence){
23233 //determine persistent layout storage type
23234 var mode = this.table.options.persistenceMode,
23235 id = this.table.options.persistenceID,
23236 retrievedData;
23237
23238 this.mode = mode !== true ? mode : (this.localStorageTest() ? "local" : "cookie");
23239
23240 if(this.table.options.persistenceReaderFunc){
23241 if(typeof this.table.options.persistenceReaderFunc === "function"){
23242 this.readFunc = this.table.options.persistenceReaderFunc;
23243 }else {
23244 if(Persistence.readers[this.table.options.persistenceReaderFunc]){
23245 this.readFunc = Persistence.readers[this.table.options.persistenceReaderFunc];
23246 }else {
23247 console.warn("Persistence Read Error - invalid reader set", this.table.options.persistenceReaderFunc);
23248 }
23249 }
23250 }else {
23251 if(Persistence.readers[this.mode]){
23252 this.readFunc = Persistence.readers[this.mode];
23253 }else {
23254 console.warn("Persistence Read Error - invalid reader set", this.mode);
23255 }
23256 }
23257
23258 if(this.table.options.persistenceWriterFunc){
23259 if(typeof this.table.options.persistenceWriterFunc === "function"){
23260 this.writeFunc = this.table.options.persistenceWriterFunc;
23261 }else {
23262 if(Persistence.writers[this.table.options.persistenceWriterFunc]){
23263 this.writeFunc = Persistence.writers[this.table.options.persistenceWriterFunc];
23264 }else {
23265 console.warn("Persistence Write Error - invalid reader set", this.table.options.persistenceWriterFunc);
23266 }
23267 }
23268 }else {
23269 if(Persistence.writers[this.mode]){
23270 this.writeFunc = Persistence.writers[this.mode];
23271 }else {
23272 console.warn("Persistence Write Error - invalid writer set", this.mode);
23273 }
23274 }
23275
23276 //set storage tag
23277 this.id = "tabulator-" + (id || (this.table.element.getAttribute("id") || ""));
23278
23279 this.config = {
23280 sort:this.table.options.persistence === true || this.table.options.persistence.sort,
23281 filter:this.table.options.persistence === true || this.table.options.persistence.filter,
23282 headerFilter:this.table.options.persistence === true || this.table.options.persistence.headerFilter,
23283 group:this.table.options.persistence === true || this.table.options.persistence.group,
23284 page:this.table.options.persistence === true || this.table.options.persistence.page,
23285 columns:this.table.options.persistence === true ? ["title", "width", "visible"] : this.table.options.persistence.columns,
23286 };
23287
23288 //load pagination data if needed
23289 if(this.config.page){
23290 retrievedData = this.retrieveData("page");
23291
23292 if(retrievedData){
23293 if(typeof retrievedData.paginationSize !== "undefined" && (this.config.page === true || this.config.page.size)){
23294 this.table.options.paginationSize = retrievedData.paginationSize;
23295 }
23296
23297 if(typeof retrievedData.paginationInitialPage !== "undefined" && (this.config.page === true || this.config.page.page)){
23298 this.table.options.paginationInitialPage = retrievedData.paginationInitialPage;
23299 }
23300 }
23301 }
23302
23303 //load group data if needed
23304 if(this.config.group){
23305 retrievedData = this.retrieveData("group");
23306
23307 if(retrievedData){
23308 if(typeof retrievedData.groupBy !== "undefined" && (this.config.group === true || this.config.group.groupBy)){
23309 this.table.options.groupBy = retrievedData.groupBy;
23310 }
23311 if(typeof retrievedData.groupStartOpen !== "undefined" && (this.config.group === true || this.config.group.groupStartOpen)){
23312 this.table.options.groupStartOpen = retrievedData.groupStartOpen;
23313 }
23314 if(typeof retrievedData.groupHeader !== "undefined" && (this.config.group === true || this.config.group.groupHeader)){
23315 this.table.options.groupHeader = retrievedData.groupHeader;
23316 }
23317 }
23318 }
23319
23320 if(this.config.columns){
23321 this.table.options.columns = this.load("columns", this.table.options.columns);
23322 this.subscribe("column-init", this.initializeColumn.bind(this));
23323 this.subscribe("column-show", this.save.bind(this, "columns"));
23324 this.subscribe("column-hide", this.save.bind(this, "columns"));
23325 this.subscribe("column-moved", this.save.bind(this, "columns"));
23326 }
23327
23328 this.subscribe("table-built", this.tableBuilt.bind(this), 0);
23329
23330 this.subscribe("table-redraw", this.tableRedraw.bind(this));
23331
23332 this.subscribe("filter-changed", this.eventSave.bind(this, "filter"));
23333 this.subscribe("filter-changed", this.eventSave.bind(this, "headerFilter"));
23334 this.subscribe("sort-changed", this.eventSave.bind(this, "sort"));
23335 this.subscribe("group-changed", this.eventSave.bind(this, "group"));
23336 this.subscribe("page-changed", this.eventSave.bind(this, "page"));
23337 this.subscribe("column-resized", this.eventSave.bind(this, "columns"));
23338 this.subscribe("column-width", this.eventSave.bind(this, "columns"));
23339 this.subscribe("layout-refreshed", this.eventSave.bind(this, "columns"));
23340 }
23341
23342 this.registerTableFunction("getColumnLayout", this.getColumnLayout.bind(this));
23343 this.registerTableFunction("setColumnLayout", this.setColumnLayout.bind(this));
23344 }
23345
23346 eventSave(type){
23347 if(this.config[type]){
23348 this.save(type);
23349 }
23350 }
23351
23352 tableBuilt(){
23353 var sorters, filters, headerFilters;
23354
23355 if(this.config.sort){
23356 sorters = this.load("sort");
23357
23358 if(!sorters === false){
23359 this.table.options.initialSort = sorters;
23360 }
23361 }
23362
23363 if(this.config.filter){
23364 filters = this.load("filter");
23365
23366 if(!filters === false){
23367 this.table.options.initialFilter = filters;
23368 }
23369 }
23370 if(this.config.headerFilter){
23371 headerFilters = this.load("headerFilter");
23372
23373 if(!headerFilters === false){
23374 this.table.options.initialHeaderFilter = headerFilters;
23375 }
23376 }
23377
23378 }
23379
23380 tableRedraw(force){
23381 if(force && this.config.columns){
23382 this.save("columns");
23383 }
23384 }
23385
23386 ///////////////////////////////////
23387 ///////// Table Functions /////////
23388 ///////////////////////////////////
23389
23390 getColumnLayout(){
23391 return this.parseColumns(this.table.columnManager.getColumns());
23392 }
23393
23394 setColumnLayout(layout){
23395 this.table.columnManager.setColumns(this.mergeDefinition(this.table.options.columns, layout, true));
23396 return true;
23397 }
23398
23399 ///////////////////////////////////
23400 ///////// Internal Logic //////////
23401 ///////////////////////////////////
23402
23403 initializeColumn(column){
23404 var def, keys;
23405
23406 if(this.config.columns){
23407 this.defWatcherBlock = true;
23408
23409 def = column.getDefinition();
23410
23411 keys = this.config.columns === true ? Object.keys(def) : this.config.columns;
23412
23413 keys.forEach((key)=>{
23414 var props = Object.getOwnPropertyDescriptor(def, key);
23415 var value = def[key];
23416
23417 if(props){
23418 Object.defineProperty(def, key, {
23419 set: (newValue) => {
23420 value = newValue;
23421
23422 if(!this.defWatcherBlock){
23423 this.save("columns");
23424 }
23425
23426 if(props.set){
23427 props.set(newValue);
23428 }
23429 },
23430 get:() => {
23431 if(props.get){
23432 props.get();
23433 }
23434 return value;
23435 }
23436 });
23437 }
23438 });
23439
23440 this.defWatcherBlock = false;
23441 }
23442 }
23443
23444 //load saved definitions
23445 load(type, current){
23446 var data = this.retrieveData(type);
23447
23448 if(current){
23449 data = data ? this.mergeDefinition(current, data) : current;
23450 }
23451
23452 return data;
23453 }
23454
23455 //retrieve data from memory
23456 retrieveData(type){
23457 return this.readFunc ? this.readFunc(this.id, type) : false;
23458 }
23459
23460 //merge old and new column definitions
23461 mergeDefinition(oldCols, newCols, mergeAllNew){
23462 var output = [];
23463
23464 newCols = newCols || [];
23465
23466 newCols.forEach((column, to) => {
23467 var from = this._findColumn(oldCols, column),
23468 keys;
23469
23470 if(from){
23471 if(mergeAllNew){
23472 keys = Object.keys(column);
23473 }else if(this.config.columns === true || this.config.columns == undefined){
23474 keys = Object.keys(from);
23475 keys.push("width");
23476 }else {
23477 keys = this.config.columns;
23478 }
23479
23480 keys.forEach((key)=>{
23481 if(key !== "columns" && typeof column[key] !== "undefined"){
23482 from[key] = column[key];
23483 }
23484 });
23485
23486 if(from.columns){
23487 from.columns = this.mergeDefinition(from.columns, column.columns);
23488 }
23489
23490 output.push(from);
23491 }
23492 });
23493
23494 oldCols.forEach((column, i) => {
23495 var from = this._findColumn(newCols, column);
23496
23497 if (!from) {
23498 if(output.length>i){
23499 output.splice(i, 0, column);
23500 }else {
23501 output.push(column);
23502 }
23503 }
23504 });
23505
23506 return output;
23507 }
23508
23509 //find matching columns
23510 _findColumn(columns, subject){
23511 var type = subject.columns ? "group" : (subject.field ? "field" : "object");
23512
23513 return columns.find(function(col){
23514 switch(type){
23515 case "group":
23516 return col.title === subject.title && col.columns.length === subject.columns.length;
23517
23518 case "field":
23519 return col.field === subject.field;
23520
23521 case "object":
23522 return col === subject;
23523 }
23524 });
23525 }
23526
23527 //save data
23528 save(type){
23529 var data = {};
23530
23531 switch(type){
23532 case "columns":
23533 data = this.parseColumns(this.table.columnManager.getColumns());
23534 break;
23535
23536 case "filter":
23537 data = this.table.modules.filter.getFilters();
23538 break;
23539
23540 case "headerFilter":
23541 data = this.table.modules.filter.getHeaderFilters();
23542 break;
23543
23544 case "sort":
23545 data = this.validateSorters(this.table.modules.sort.getSort());
23546 break;
23547
23548 case "group":
23549 data = this.getGroupConfig();
23550 break;
23551
23552 case "page":
23553 data = this.getPageConfig();
23554 break;
23555 }
23556
23557 if(this.writeFunc){
23558 this.writeFunc(this.id, type, data);
23559 }
23560
23561 }
23562
23563 //ensure sorters contain no function data
23564 validateSorters(data){
23565 data.forEach(function(item){
23566 item.column = item.field;
23567 delete item.field;
23568 });
23569
23570 return data;
23571 }
23572
23573 getGroupConfig(){
23574 var data = {};
23575
23576 if(this.config.group){
23577 if(this.config.group === true || this.config.group.groupBy){
23578 data.groupBy = this.table.options.groupBy;
23579 }
23580
23581 if(this.config.group === true || this.config.group.groupStartOpen){
23582 data.groupStartOpen = this.table.options.groupStartOpen;
23583 }
23584
23585 if(this.config.group === true || this.config.group.groupHeader){
23586 data.groupHeader = this.table.options.groupHeader;
23587 }
23588 }
23589
23590 return data;
23591 }
23592
23593 getPageConfig(){
23594 var data = {};
23595
23596 if(this.config.page){
23597 if(this.config.page === true || this.config.page.size){
23598 data.paginationSize = this.table.modules.page.getPageSize();
23599 }
23600
23601 if(this.config.page === true || this.config.page.page){
23602 data.paginationInitialPage = this.table.modules.page.getPage();
23603 }
23604 }
23605
23606 return data;
23607 }
23608
23609
23610 //parse columns for data to store
23611 parseColumns(columns){
23612 var definitions = [],
23613 excludedKeys = ["headerContextMenu", "headerMenu", "contextMenu", "clickMenu"];
23614
23615 columns.forEach((column) => {
23616 var defStore = {},
23617 colDef = column.getDefinition(),
23618 keys;
23619
23620 if(column.isGroup){
23621 defStore.title = colDef.title;
23622 defStore.columns = this.parseColumns(column.getColumns());
23623 }else {
23624 defStore.field = column.getField();
23625
23626 if(this.config.columns === true || this.config.columns == undefined){
23627 keys = Object.keys(colDef);
23628 keys.push("width");
23629 keys.push("visible");
23630 }else {
23631 keys = this.config.columns;
23632 }
23633
23634 keys.forEach((key)=>{
23635 switch(key){
23636 case "width":
23637 defStore.width = column.getWidth();
23638 break;
23639 case "visible":
23640 defStore.visible = column.visible;
23641 break;
23642
23643 default:
23644 if(typeof colDef[key] !== "function" && excludedKeys.indexOf(key) === -1){
23645 defStore[key] = colDef[key];
23646 }
23647 }
23648 });
23649 }
23650
23651 definitions.push(defStore);
23652 });
23653
23654 return definitions;
23655 }
23656 }
23657
23658 class Popup extends Module{
23659
23660 static moduleName = "popup";
23661
23662 constructor(table){
23663 super(table);
23664
23665 this.columnSubscribers = {};
23666
23667 this.registerTableOption("rowContextPopup", false);
23668 this.registerTableOption("rowClickPopup", false);
23669 this.registerTableOption("rowDblClickPopup", false);
23670 this.registerTableOption("groupContextPopup", false);
23671 this.registerTableOption("groupClickPopup", false);
23672 this.registerTableOption("groupDblClickPopup", false);
23673
23674 this.registerColumnOption("headerContextPopup");
23675 this.registerColumnOption("headerClickPopup");
23676 this.registerColumnOption("headerDblClickPopup");
23677 this.registerColumnOption("headerPopup");
23678 this.registerColumnOption("headerPopupIcon");
23679 this.registerColumnOption("contextPopup");
23680 this.registerColumnOption("clickPopup");
23681 this.registerColumnOption("dblClickPopup");
23682
23683 this.registerComponentFunction("cell", "popup", this._componentPopupCall.bind(this));
23684 this.registerComponentFunction("column", "popup", this._componentPopupCall.bind(this));
23685 this.registerComponentFunction("row", "popup", this._componentPopupCall.bind(this));
23686 this.registerComponentFunction("group", "popup", this._componentPopupCall.bind(this));
23687
23688 }
23689
23690 initialize(){
23691 this.initializeRowWatchers();
23692 this.initializeGroupWatchers();
23693
23694 this.subscribe("column-init", this.initializeColumn.bind(this));
23695 }
23696
23697 _componentPopupCall(component, contents, position){
23698 this.loadPopupEvent(contents, null, component, position);
23699 }
23700
23701 initializeRowWatchers(){
23702 if(this.table.options.rowContextPopup){
23703 this.subscribe("row-contextmenu", this.loadPopupEvent.bind(this, this.table.options.rowContextPopup));
23704 this.table.on("rowTapHold", this.loadPopupEvent.bind(this, this.table.options.rowContextPopup));
23705 }
23706
23707 if(this.table.options.rowClickPopup){
23708 this.subscribe("row-click", this.loadPopupEvent.bind(this, this.table.options.rowClickPopup));
23709 }
23710
23711 if(this.table.options.rowDblClickPopup){
23712 this.subscribe("row-dblclick", this.loadPopupEvent.bind(this, this.table.options.rowDblClickPopup));
23713 }
23714 }
23715
23716 initializeGroupWatchers(){
23717 if(this.table.options.groupContextPopup){
23718 this.subscribe("group-contextmenu", this.loadPopupEvent.bind(this, this.table.options.groupContextPopup));
23719 this.table.on("groupTapHold", this.loadPopupEvent.bind(this, this.table.options.groupContextPopup));
23720 }
23721
23722 if(this.table.options.groupClickPopup){
23723 this.subscribe("group-click", this.loadPopupEvent.bind(this, this.table.options.groupClickPopup));
23724 }
23725
23726 if(this.table.options.groupDblClickPopup){
23727 this.subscribe("group-dblclick", this.loadPopupEvent.bind(this, this.table.options.groupDblClickPopup));
23728 }
23729 }
23730
23731 initializeColumn(column){
23732 var def = column.definition;
23733
23734 //handle column events
23735 if(def.headerContextPopup && !this.columnSubscribers.headerContextPopup){
23736 this.columnSubscribers.headerContextPopup = this.loadPopupTableColumnEvent.bind(this, "headerContextPopup");
23737 this.subscribe("column-contextmenu", this.columnSubscribers.headerContextPopup);
23738 this.table.on("headerTapHold", this.loadPopupTableColumnEvent.bind(this, "headerContextPopup"));
23739 }
23740
23741 if(def.headerClickPopup && !this.columnSubscribers.headerClickPopup){
23742 this.columnSubscribers.headerClickPopup = this.loadPopupTableColumnEvent.bind(this, "headerClickPopup");
23743 this.subscribe("column-click", this.columnSubscribers.headerClickPopup);
23744
23745
23746 }if(def.headerDblClickPopup && !this.columnSubscribers.headerDblClickPopup){
23747 this.columnSubscribers.headerDblClickPopup = this.loadPopupTableColumnEvent.bind(this, "headerDblClickPopup");
23748 this.subscribe("column-dblclick", this.columnSubscribers.headerDblClickPopup);
23749 }
23750
23751 if(def.headerPopup){
23752 this.initializeColumnHeaderPopup(column);
23753 }
23754
23755 //handle cell events
23756 if(def.contextPopup && !this.columnSubscribers.contextPopup){
23757 this.columnSubscribers.contextPopup = this.loadPopupTableCellEvent.bind(this, "contextPopup");
23758 this.subscribe("cell-contextmenu", this.columnSubscribers.contextPopup);
23759 this.table.on("cellTapHold", this.loadPopupTableCellEvent.bind(this, "contextPopup"));
23760 }
23761
23762 if(def.clickPopup && !this.columnSubscribers.clickPopup){
23763 this.columnSubscribers.clickPopup = this.loadPopupTableCellEvent.bind(this, "clickPopup");
23764 this.subscribe("cell-click", this.columnSubscribers.clickPopup);
23765 }
23766
23767 if(def.dblClickPopup && !this.columnSubscribers.dblClickPopup){
23768 this.columnSubscribers.dblClickPopup = this.loadPopupTableCellEvent.bind(this, "dblClickPopup");
23769 this.subscribe("cell-click", this.columnSubscribers.dblClickPopup);
23770 }
23771 }
23772
23773 initializeColumnHeaderPopup(column){
23774 var icon = column.definition.headerPopupIcon,
23775 headerPopupEl;
23776
23777 headerPopupEl = document.createElement("span");
23778 headerPopupEl.classList.add("tabulator-header-popup-button");
23779
23780 if(icon){
23781 if(typeof icon === "function"){
23782 icon = icon(column.getComponent());
23783 }
23784
23785 if(icon instanceof HTMLElement){
23786 headerPopupEl.appendChild(icon);
23787 }else {
23788 headerPopupEl.innerHTML = icon;
23789 }
23790 }else {
23791 headerPopupEl.innerHTML = "&vellip;";
23792 }
23793
23794 headerPopupEl.addEventListener("click", (e) => {
23795 e.stopPropagation();
23796 e.preventDefault();
23797
23798 this.loadPopupEvent(column.definition.headerPopup, e, column);
23799 });
23800
23801 column.titleElement.insertBefore(headerPopupEl, column.titleElement.firstChild);
23802 }
23803
23804 loadPopupTableCellEvent(option, e, cell){
23805 if(cell._cell){
23806 cell = cell._cell;
23807 }
23808
23809 if(cell.column.definition[option]){
23810 this.loadPopupEvent(cell.column.definition[option], e, cell);
23811 }
23812 }
23813
23814 loadPopupTableColumnEvent(option, e, column){
23815 if(column._column){
23816 column = column._column;
23817 }
23818
23819 if(column.definition[option]){
23820 this.loadPopupEvent(column.definition[option], e, column);
23821 }
23822 }
23823
23824 loadPopupEvent(contents, e, component, position){
23825 var renderedCallback;
23826
23827 function onRendered(callback){
23828 renderedCallback = callback;
23829 }
23830
23831 if(component._group){
23832 component = component._group;
23833 }else if(component._row){
23834 component = component._row;
23835 }
23836
23837 contents = typeof contents == "function" ? contents.call(this.table, e, component.getComponent(), onRendered) : contents;
23838
23839 this.loadPopup(e, component, contents, renderedCallback, position);
23840 }
23841
23842 loadPopup(e, component, contents, renderedCallback, position){
23843 var touch = !(e instanceof MouseEvent),
23844 contentsEl, popup;
23845
23846 if(contents instanceof HTMLElement){
23847 contentsEl = contents;
23848 }else {
23849 contentsEl = document.createElement("div");
23850 contentsEl.innerHTML = contents;
23851 }
23852
23853 contentsEl.classList.add("tabulator-popup");
23854
23855 contentsEl.addEventListener("click", (e) =>{
23856 e.stopPropagation();
23857 });
23858
23859 if(!touch){
23860 e.preventDefault();
23861 }
23862
23863 popup = this.popup(contentsEl);
23864
23865 if(typeof renderedCallback === "function"){
23866 popup.renderCallback(renderedCallback);
23867 }
23868
23869 if(e){
23870 popup.show(e);
23871 }else {
23872 popup.show(component.getElement(), position || "center");
23873 }
23874
23875
23876 popup.hideOnBlur(() => {
23877 this.dispatchExternal("popupClosed", component.getComponent());
23878 });
23879
23880 this.dispatchExternal("popupOpened", component.getComponent());
23881 }
23882 }
23883
23884 class Print extends Module{
23885
23886 static moduleName = "print";
23887
23888 constructor(table){
23889 super(table);
23890
23891 this.element = false;
23892 this.manualBlock = false;
23893 this.beforeprintEventHandler = null;
23894 this.afterprintEventHandler = null;
23895
23896 this.registerTableOption("printAsHtml", false); //enable print as html
23897 this.registerTableOption("printFormatter", false); //printing page formatter
23898 this.registerTableOption("printHeader", false); //page header contents
23899 this.registerTableOption("printFooter", false); //page footer contents
23900 this.registerTableOption("printStyled", true); //enable print as html styling
23901 this.registerTableOption("printRowRange", "visible"); //restrict print to visible rows only
23902 this.registerTableOption("printConfig", {}); //print config options
23903
23904 this.registerColumnOption("print");
23905 this.registerColumnOption("titlePrint");
23906 }
23907
23908 initialize(){
23909 if(this.table.options.printAsHtml){
23910 this.beforeprintEventHandler = this.replaceTable.bind(this);
23911 this.afterprintEventHandler = this.cleanup.bind(this);
23912
23913 window.addEventListener("beforeprint", this.beforeprintEventHandler );
23914 window.addEventListener("afterprint", this.afterprintEventHandler);
23915 this.subscribe("table-destroy", this.destroy.bind(this));
23916 }
23917
23918 this.registerTableFunction("print", this.printFullscreen.bind(this));
23919 }
23920
23921 destroy(){
23922 if(this.table.options.printAsHtml){
23923 window.removeEventListener( "beforeprint", this.beforeprintEventHandler );
23924 window.removeEventListener( "afterprint", this.afterprintEventHandler );
23925 }
23926 }
23927
23928 ///////////////////////////////////
23929 ///////// Table Functions /////////
23930 ///////////////////////////////////
23931
23932 ///////////////////////////////////
23933 ///////// Internal Logic //////////
23934 ///////////////////////////////////
23935
23936 replaceTable(){
23937 if(!this.manualBlock){
23938 this.element = document.createElement("div");
23939 this.element.classList.add("tabulator-print-table");
23940
23941 this.element.appendChild(this.table.modules.export.generateTable(this.table.options.printConfig, this.table.options.printStyled, this.table.options.printRowRange, "print"));
23942
23943 this.table.element.style.display = "none";
23944
23945 this.table.element.parentNode.insertBefore(this.element, this.table.element);
23946 }
23947 }
23948
23949 cleanup(){
23950 document.body.classList.remove("tabulator-print-fullscreen-hide");
23951
23952 if(this.element && this.element.parentNode){
23953 this.element.parentNode.removeChild(this.element);
23954 this.table.element.style.display = "";
23955 }
23956 }
23957
23958 printFullscreen(visible, style, config){
23959 var scrollX = window.scrollX,
23960 scrollY = window.scrollY,
23961 headerEl = document.createElement("div"),
23962 footerEl = document.createElement("div"),
23963 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"),
23964 headerContent, footerContent;
23965
23966 this.manualBlock = true;
23967
23968 this.element = document.createElement("div");
23969 this.element.classList.add("tabulator-print-fullscreen");
23970
23971 if(this.table.options.printHeader){
23972 headerEl.classList.add("tabulator-print-header");
23973
23974 headerContent = typeof this.table.options.printHeader == "function" ? this.table.options.printHeader.call(this.table) : this.table.options.printHeader;
23975
23976 if(typeof headerContent == "string"){
23977 headerEl.innerHTML = headerContent;
23978 }else {
23979 headerEl.appendChild(headerContent);
23980 }
23981
23982 this.element.appendChild(headerEl);
23983 }
23984
23985 this.element.appendChild(tableEl);
23986
23987 if(this.table.options.printFooter){
23988 footerEl.classList.add("tabulator-print-footer");
23989
23990 footerContent = typeof this.table.options.printFooter == "function" ? this.table.options.printFooter.call(this.table) : this.table.options.printFooter;
23991
23992
23993 if(typeof footerContent == "string"){
23994 footerEl.innerHTML = footerContent;
23995 }else {
23996 footerEl.appendChild(footerContent);
23997 }
23998
23999 this.element.appendChild(footerEl);
24000 }
24001
24002 document.body.classList.add("tabulator-print-fullscreen-hide");
24003 document.body.appendChild(this.element);
24004
24005 if(this.table.options.printFormatter){
24006 this.table.options.printFormatter(this.element, tableEl);
24007 }
24008
24009 window.print();
24010
24011 this.cleanup();
24012
24013 window.scrollTo(scrollX, scrollY);
24014
24015 this.manualBlock = false;
24016 }
24017 }
24018
24019 class ReactiveData extends Module{
24020
24021 static moduleName = "reactiveData";
24022
24023 constructor(table){
24024 super(table);
24025
24026 this.data = false;
24027 this.blocked = false; //block reactivity while performing update
24028 this.origFuncs = {}; // hold original data array functions to allow replacement after data is done with
24029 this.currentVersion = 0;
24030
24031 this.registerTableOption("reactiveData", false); //enable data reactivity
24032 }
24033
24034 initialize(){
24035 if(this.table.options.reactiveData){
24036 this.subscribe("cell-value-save-before", this.block.bind(this, "cellsave"));
24037 this.subscribe("cell-value-save-after", this.unblock.bind(this, "cellsave"));
24038 this.subscribe("row-data-save-before", this.block.bind(this, "rowsave"));
24039 this.subscribe("row-data-save-after", this.unblock.bind(this, "rowsave"));
24040 this.subscribe("row-data-init-after", this.watchRow.bind(this));
24041 this.subscribe("data-processing", this.watchData.bind(this));
24042 this.subscribe("table-destroy", this.unwatchData.bind(this));
24043 }
24044 }
24045
24046 watchData(data){
24047 var self = this,
24048 version;
24049
24050 this.currentVersion ++;
24051
24052 version = this.currentVersion;
24053
24054 this.unwatchData();
24055
24056 this.data = data;
24057
24058 //override array push function
24059 this.origFuncs.push = data.push;
24060
24061 Object.defineProperty(this.data, "push", {
24062 enumerable: false,
24063 configurable: true,
24064 value: function(){
24065 var args = Array.from(arguments),
24066 result;
24067
24068 if(!self.blocked && version === self.currentVersion){
24069 self.block("data-push");
24070
24071 args.forEach((arg) => {
24072 self.table.rowManager.addRowActual(arg, false);
24073 });
24074
24075 result = self.origFuncs.push.apply(data, arguments);
24076
24077 self.unblock("data-push");
24078 }
24079
24080 return result;
24081 }
24082 });
24083
24084 //override array unshift function
24085 this.origFuncs.unshift = data.unshift;
24086
24087 Object.defineProperty(this.data, "unshift", {
24088 enumerable: false,
24089 configurable: true,
24090 value: function(){
24091 var args = Array.from(arguments),
24092 result;
24093
24094 if(!self.blocked && version === self.currentVersion){
24095 self.block("data-unshift");
24096
24097 args.forEach((arg) => {
24098 self.table.rowManager.addRowActual(arg, true);
24099 });
24100
24101 result = self.origFuncs.unshift.apply(data, arguments);
24102
24103 self.unblock("data-unshift");
24104 }
24105
24106 return result;
24107 }
24108 });
24109
24110
24111 //override array shift function
24112 this.origFuncs.shift = data.shift;
24113
24114 Object.defineProperty(this.data, "shift", {
24115 enumerable: false,
24116 configurable: true,
24117 value: function(){
24118 var row, result;
24119
24120 if(!self.blocked && version === self.currentVersion){
24121 self.block("data-shift");
24122
24123 if(self.data.length){
24124 row = self.table.rowManager.getRowFromDataObject(self.data[0]);
24125
24126 if(row){
24127 row.deleteActual();
24128 }
24129 }
24130
24131 result = self.origFuncs.shift.call(data);
24132
24133 self.unblock("data-shift");
24134 }
24135
24136 return result;
24137 }
24138 });
24139
24140 //override array pop function
24141 this.origFuncs.pop = data.pop;
24142
24143 Object.defineProperty(this.data, "pop", {
24144 enumerable: false,
24145 configurable: true,
24146 value: function(){
24147 var row, result;
24148
24149 if(!self.blocked && version === self.currentVersion){
24150 self.block("data-pop");
24151
24152 if(self.data.length){
24153 row = self.table.rowManager.getRowFromDataObject(self.data[self.data.length - 1]);
24154
24155 if(row){
24156 row.deleteActual();
24157 }
24158 }
24159
24160 result = self.origFuncs.pop.call(data);
24161
24162 self.unblock("data-pop");
24163 }
24164
24165 return result;
24166 }
24167 });
24168
24169
24170 //override array splice function
24171 this.origFuncs.splice = data.splice;
24172
24173 Object.defineProperty(this.data, "splice", {
24174 enumerable: false,
24175 configurable: true,
24176 value: function(){
24177 var args = Array.from(arguments),
24178 start = args[0] < 0 ? data.length + args[0] : args[0],
24179 end = args[1],
24180 newRows = args[2] ? args.slice(2) : false,
24181 startRow, result;
24182
24183 if(!self.blocked && version === self.currentVersion){
24184 self.block("data-splice");
24185 //add new rows
24186 if(newRows){
24187 startRow = data[start] ? self.table.rowManager.getRowFromDataObject(data[start]) : false;
24188
24189 if(startRow){
24190 newRows.forEach((rowData) => {
24191 self.table.rowManager.addRowActual(rowData, true, startRow, true);
24192 });
24193 }else {
24194 newRows = newRows.slice().reverse();
24195
24196 newRows.forEach((rowData) => {
24197 self.table.rowManager.addRowActual(rowData, true, false, true);
24198 });
24199 }
24200 }
24201
24202 //delete removed rows
24203 if(end !== 0){
24204 var oldRows = data.slice(start, typeof args[1] === "undefined" ? args[1] : start + end);
24205
24206 oldRows.forEach((rowData, i) => {
24207 var row = self.table.rowManager.getRowFromDataObject(rowData);
24208
24209 if(row){
24210 row.deleteActual(i !== oldRows.length - 1);
24211 }
24212 });
24213 }
24214
24215 if(newRows || end !== 0){
24216 self.table.rowManager.reRenderInPosition();
24217 }
24218
24219 result = self.origFuncs.splice.apply(data, arguments);
24220
24221 self.unblock("data-splice");
24222 }
24223
24224 return result ;
24225 }
24226 });
24227 }
24228
24229 unwatchData(){
24230 if(this.data !== false){
24231 for(var key in this.origFuncs){
24232 Object.defineProperty(this.data, key, {
24233 enumerable: true,
24234 configurable:true,
24235 writable:true,
24236 value: this.origFuncs[key],
24237 });
24238 }
24239 }
24240 }
24241
24242 watchRow(row){
24243 var data = row.getData();
24244
24245 for(var key in data){
24246 this.watchKey(row, data, key);
24247 }
24248
24249 if(this.table.options.dataTree){
24250 this.watchTreeChildren(row);
24251 }
24252 }
24253
24254 watchTreeChildren (row){
24255 var self = this,
24256 childField = row.getData()[this.table.options.dataTreeChildField],
24257 origFuncs = {};
24258
24259 if(childField){
24260
24261 origFuncs.push = childField.push;
24262
24263 Object.defineProperty(childField, "push", {
24264 enumerable: false,
24265 configurable: true,
24266 value: () => {
24267 if(!self.blocked){
24268 self.block("tree-push");
24269
24270 var result = origFuncs.push.apply(childField, arguments);
24271 this.rebuildTree(row);
24272
24273 self.unblock("tree-push");
24274 }
24275
24276 return result;
24277 }
24278 });
24279
24280 origFuncs.unshift = childField.unshift;
24281
24282 Object.defineProperty(childField, "unshift", {
24283 enumerable: false,
24284 configurable: true,
24285 value: () => {
24286 if(!self.blocked){
24287 self.block("tree-unshift");
24288
24289 var result = origFuncs.unshift.apply(childField, arguments);
24290 this.rebuildTree(row);
24291
24292 self.unblock("tree-unshift");
24293 }
24294
24295 return result;
24296 }
24297 });
24298
24299 origFuncs.shift = childField.shift;
24300
24301 Object.defineProperty(childField, "shift", {
24302 enumerable: false,
24303 configurable: true,
24304 value: () => {
24305 if(!self.blocked){
24306 self.block("tree-shift");
24307
24308 var result = origFuncs.shift.call(childField);
24309 this.rebuildTree(row);
24310
24311 self.unblock("tree-shift");
24312 }
24313
24314 return result;
24315 }
24316 });
24317
24318 origFuncs.pop = childField.pop;
24319
24320 Object.defineProperty(childField, "pop", {
24321 enumerable: false,
24322 configurable: true,
24323 value: () => {
24324 if(!self.blocked){
24325 self.block("tree-pop");
24326
24327 var result = origFuncs.pop.call(childField);
24328 this.rebuildTree(row);
24329
24330 self.unblock("tree-pop");
24331 }
24332
24333 return result;
24334 }
24335 });
24336
24337 origFuncs.splice = childField.splice;
24338
24339 Object.defineProperty(childField, "splice", {
24340 enumerable: false,
24341 configurable: true,
24342 value: () => {
24343 if(!self.blocked){
24344 self.block("tree-splice");
24345
24346 var result = origFuncs.splice.apply(childField, arguments);
24347 this.rebuildTree(row);
24348
24349 self.unblock("tree-splice");
24350 }
24351
24352 return result;
24353 }
24354 });
24355 }
24356 }
24357
24358 rebuildTree(row){
24359 this.table.modules.dataTree.initializeRow(row);
24360 this.table.modules.dataTree.layoutRow(row);
24361 this.table.rowManager.refreshActiveData("tree", false, true);
24362 }
24363
24364 watchKey(row, data, key){
24365 var self = this,
24366 props = Object.getOwnPropertyDescriptor(data, key),
24367 value = data[key],
24368 version = this.currentVersion;
24369
24370 Object.defineProperty(data, key, {
24371 set: (newValue) => {
24372 value = newValue;
24373 if(!self.blocked && version === self.currentVersion){
24374 self.block("key");
24375
24376 var update = {};
24377 update[key] = newValue;
24378 row.updateData(update);
24379
24380 self.unblock("key");
24381 }
24382
24383 if(props.set){
24384 props.set(newValue);
24385 }
24386 },
24387 get:() => {
24388
24389 if(props.get){
24390 props.get();
24391 }
24392
24393 return value;
24394 }
24395 });
24396 }
24397
24398 unwatchRow(row){
24399 var data = row.getData();
24400
24401 for(var key in data){
24402 Object.defineProperty(data, key, {
24403 value:data[key],
24404 });
24405 }
24406 }
24407
24408 block(key){
24409 if(!this.blocked){
24410 this.blocked = key;
24411 }
24412 }
24413
24414 unblock(key){
24415 if(this.blocked === key){
24416 this.blocked = false;
24417 }
24418 }
24419 }
24420
24421 class ResizeColumns extends Module{
24422
24423 static moduleName = "resizeColumns";
24424
24425 constructor(table){
24426 super(table);
24427
24428 this.startColumn = false;
24429 this.startX = false;
24430 this.startWidth = false;
24431 this.latestX = false;
24432 this.handle = null;
24433 this.initialNextColumn = null;
24434 this.nextColumn = null;
24435
24436 this.initialized = false;
24437 this.registerColumnOption("resizable", true);
24438 this.registerTableOption("resizableColumnFit", false);
24439 this.registerTableOption("resizableColumnGuide", false);
24440 }
24441
24442 initialize(){
24443 this.subscribe("column-rendered", this.layoutColumnHeader.bind(this));
24444 }
24445
24446 initializeEventWatchers(){
24447 if(!this.initialized){
24448
24449 this.subscribe("cell-rendered", this.layoutCellHandles.bind(this));
24450 this.subscribe("cell-delete", this.deInitializeComponent.bind(this));
24451
24452 this.subscribe("cell-height", this.resizeHandle.bind(this));
24453 this.subscribe("column-moved", this.columnLayoutUpdated.bind(this));
24454
24455 this.subscribe("column-hide", this.deInitializeColumn.bind(this));
24456 this.subscribe("column-show", this.columnLayoutUpdated.bind(this));
24457 this.subscribe("column-width", this.columnWidthUpdated.bind(this));
24458
24459 this.subscribe("column-delete", this.deInitializeComponent.bind(this));
24460 this.subscribe("column-height", this.resizeHandle.bind(this));
24461
24462 this.initialized = true;
24463 }
24464 }
24465
24466
24467 layoutCellHandles(cell){
24468 if(cell.row.type === "row"){
24469 this.deInitializeComponent(cell);
24470 this.initializeColumn("cell", cell, cell.column, cell.element);
24471 }
24472 }
24473
24474 layoutColumnHeader(column){
24475 if(column.definition.resizable){
24476 this.initializeEventWatchers();
24477 this.deInitializeComponent(column);
24478 this.initializeColumn("header", column, column, column.element);
24479 }
24480 }
24481
24482 columnLayoutUpdated(column){
24483 var prev = column.prevColumn();
24484
24485 this.reinitializeColumn(column);
24486
24487 if(prev){
24488 this.reinitializeColumn(prev);
24489 }
24490 }
24491
24492 columnWidthUpdated(column){
24493 if(column.modules.frozen){
24494 if(this.table.modules.frozenColumns.leftColumns.includes(column)){
24495 this.table.modules.frozenColumns.leftColumns.forEach((col) => {
24496 this.reinitializeColumn(col);
24497 });
24498 }else if(this.table.modules.frozenColumns.rightColumns.includes(column)){
24499 this.table.modules.frozenColumns.rightColumns.forEach((col) => {
24500 this.reinitializeColumn(col);
24501 });
24502 }
24503 }
24504 }
24505
24506 frozenColumnOffset(column){
24507 var offset = false;
24508
24509 if(column.modules.frozen){
24510 offset = column.modules.frozen.marginValue;
24511
24512 if(column.modules.frozen.position === "left"){
24513 offset += column.getWidth() - 3;
24514 }else {
24515 if(offset){
24516 offset -= 3;
24517 }
24518 }
24519 }
24520
24521 return offset !== false ? offset + "px" : false;
24522 }
24523
24524 reinitializeColumn(column){
24525 var frozenOffset = this.frozenColumnOffset(column);
24526
24527 column.cells.forEach((cell) => {
24528 if(cell.modules.resize && cell.modules.resize.handleEl){
24529 if(frozenOffset){
24530 cell.modules.resize.handleEl.style[column.modules.frozen.position] = frozenOffset;
24531 cell.modules.resize.handleEl.style["z-index"] = 11;
24532 }
24533
24534 cell.element.after(cell.modules.resize.handleEl);
24535 }
24536 });
24537
24538 if(column.modules.resize && column.modules.resize.handleEl){
24539 if(frozenOffset){
24540 column.modules.resize.handleEl.style[column.modules.frozen.position] = frozenOffset;
24541 }
24542
24543 column.element.after(column.modules.resize.handleEl);
24544 }
24545 }
24546
24547 initializeColumn(type, component, column, element){
24548 var self = this,
24549 variableHeight = false,
24550 mode = column.definition.resizable,
24551 config = {},
24552 nearestColumn = column.getLastColumn();
24553
24554 //set column resize mode
24555 if(type === "header"){
24556 variableHeight = column.definition.formatter == "textarea" || column.definition.variableHeight;
24557 config = {variableHeight:variableHeight};
24558 }
24559
24560 if((mode === true || mode == type) && this._checkResizability(nearestColumn)){
24561
24562 var handle = document.createElement('span');
24563 handle.className = "tabulator-col-resize-handle";
24564
24565 handle.addEventListener("click", function(e){
24566 e.stopPropagation();
24567 });
24568
24569 var handleDown = function(e){
24570 self.startColumn = column;
24571 self.initialNextColumn = self.nextColumn = nearestColumn.nextColumn();
24572 self._mouseDown(e, nearestColumn, handle);
24573 };
24574
24575 handle.addEventListener("mousedown", handleDown);
24576 handle.addEventListener("touchstart", handleDown, {passive: true});
24577
24578 //resize column on double click
24579 handle.addEventListener("dblclick", (e) => {
24580 var oldWidth = nearestColumn.getWidth();
24581
24582 e.stopPropagation();
24583 nearestColumn.reinitializeWidth(true);
24584
24585 if(oldWidth !== nearestColumn.getWidth()){
24586 self.dispatch("column-resized", nearestColumn);
24587 self.dispatchExternal("columnResized", nearestColumn.getComponent());
24588 }
24589 });
24590
24591 if(column.modules.frozen){
24592 handle.style.position = "sticky";
24593 handle.style[column.modules.frozen.position] = this.frozenColumnOffset(column);
24594 }
24595
24596 config.handleEl = handle;
24597
24598 if(element.parentNode && column.visible){
24599 element.after(handle);
24600 }
24601 }
24602
24603 component.modules.resize = config;
24604 }
24605
24606 deInitializeColumn(column){
24607 this.deInitializeComponent(column);
24608
24609 column.cells.forEach((cell) => {
24610 this.deInitializeComponent(cell);
24611 });
24612 }
24613
24614 deInitializeComponent(component){
24615 var handleEl;
24616
24617 if(component.modules.resize){
24618 handleEl = component.modules.resize.handleEl;
24619
24620 if(handleEl && handleEl.parentElement){
24621 handleEl.parentElement.removeChild(handleEl);
24622 }
24623 }
24624 }
24625
24626 resizeHandle(component, height){
24627 if(component.modules.resize && component.modules.resize.handleEl){
24628 component.modules.resize.handleEl.style.height = height;
24629 }
24630 }
24631
24632 resize(e, column){
24633 var x = typeof e.clientX === "undefined" ? e.touches[0].clientX : e.clientX,
24634 startDiff = x - this.startX,
24635 moveDiff = x - this.latestX,
24636 blockedBefore, blockedAfter;
24637
24638 this.latestX = x;
24639
24640 if(this.table.rtl){
24641 startDiff = -startDiff;
24642 moveDiff = -moveDiff;
24643 }
24644
24645 blockedBefore = column.width == column.minWidth || column.width == column.maxWidth;
24646
24647 column.setWidth(this.startWidth + startDiff);
24648
24649 blockedAfter = column.width == column.minWidth || column.width == column.maxWidth;
24650
24651 if(moveDiff < 0){
24652 this.nextColumn = this.initialNextColumn;
24653 }
24654
24655 if(this.table.options.resizableColumnFit && this.nextColumn && !(blockedBefore && blockedAfter)){
24656 let colWidth = this.nextColumn.getWidth();
24657
24658 if(moveDiff > 0){
24659 if(colWidth <= this.nextColumn.minWidth){
24660 this.nextColumn = this.nextColumn.nextColumn();
24661 }
24662 }
24663
24664 if(this.nextColumn){
24665 this.nextColumn.setWidth(this.nextColumn.getWidth() - moveDiff);
24666 }
24667 }
24668
24669 this.table.columnManager.rerenderColumns(true);
24670
24671 if(!this.table.browserSlow && column.modules.resize && column.modules.resize.variableHeight){
24672 column.checkCellHeights();
24673 }
24674 }
24675
24676 calcGuidePosition(e, column, handle) {
24677 var mouseX = typeof e.clientX === "undefined" ? e.touches[0].clientX : e.clientX,
24678 handleX = handle.getBoundingClientRect().x - this.table.element.getBoundingClientRect().x,
24679 tableX = this.table.element.getBoundingClientRect().x,
24680 columnX = column.element.getBoundingClientRect().left - tableX,
24681 mouseDiff = mouseX - this.startX,
24682 pos = Math.max(handleX + mouseDiff, columnX + column.minWidth);
24683
24684 if(column.maxWidth){
24685 pos = Math.min(pos, columnX + column.maxWidth);
24686 }
24687
24688 return pos;
24689 }
24690
24691 _checkResizability(column){
24692 return column.definition.resizable;
24693 }
24694
24695 _mouseDown(e, column, handle){
24696 var self = this,
24697 guideEl;
24698
24699 this.dispatchExternal("columnResizing", column.getComponent());
24700
24701 if(self.table.options.resizableColumnGuide){
24702 guideEl = document.createElement("span");
24703 guideEl.classList.add('tabulator-col-resize-guide');
24704 self.table.element.appendChild(guideEl);
24705 setTimeout(() => {
24706 guideEl.style.left = self.calcGuidePosition(e, column, handle) + "px";
24707 });
24708 }
24709
24710 self.table.element.classList.add("tabulator-block-select");
24711
24712 function mouseMove(e){
24713 if(self.table.options.resizableColumnGuide){
24714 guideEl.style.left = self.calcGuidePosition(e, column, handle) + "px";
24715 }else {
24716 self.resize(e, column);
24717 }
24718 }
24719
24720 function mouseUp(e){
24721 if(self.table.options.resizableColumnGuide){
24722 self.resize(e, column);
24723 guideEl.remove();
24724 }
24725
24726 //block editor from taking action while resizing is taking place
24727 if(self.startColumn.modules.edit){
24728 self.startColumn.modules.edit.blocked = false;
24729 }
24730
24731 if(self.table.browserSlow && column.modules.resize && column.modules.resize.variableHeight){
24732 column.checkCellHeights();
24733 }
24734
24735 document.body.removeEventListener("mouseup", mouseUp);
24736 document.body.removeEventListener("mousemove", mouseMove);
24737
24738 handle.removeEventListener("touchmove", mouseMove);
24739 handle.removeEventListener("touchend", mouseUp);
24740
24741 self.table.element.classList.remove("tabulator-block-select");
24742
24743 if(self.startWidth !== column.getWidth()){
24744 self.table.columnManager.verticalAlignHeaders();
24745
24746 self.dispatch("column-resized", column);
24747 self.dispatchExternal("columnResized", column.getComponent());
24748 }
24749 }
24750
24751 e.stopPropagation(); //prevent resize from interfering with movable columns
24752
24753 //block editor from taking action while resizing is taking place
24754 if(self.startColumn.modules.edit){
24755 self.startColumn.modules.edit.blocked = true;
24756 }
24757
24758 self.startX = typeof e.clientX === "undefined" ? e.touches[0].clientX : e.clientX;
24759 self.latestX = self.startX;
24760 self.startWidth = column.getWidth();
24761
24762 document.body.addEventListener("mousemove", mouseMove);
24763 document.body.addEventListener("mouseup", mouseUp);
24764 handle.addEventListener("touchmove", mouseMove, {passive: true});
24765 handle.addEventListener("touchend", mouseUp);
24766 }
24767 }
24768
24769 class ResizeRows extends Module{
24770
24771 static moduleName = "resizeRows";
24772
24773 constructor(table){
24774 super(table);
24775
24776 this.startColumn = false;
24777 this.startY = false;
24778 this.startHeight = false;
24779 this.handle = null;
24780 this.prevHandle = null;
24781
24782 this.registerTableOption("resizableRows", false); //resizable rows
24783 this.registerTableOption("resizableRowGuide", false);
24784 }
24785
24786 initialize(){
24787 if(this.table.options.resizableRows){
24788 this.subscribe("row-layout-after", this.initializeRow.bind(this));
24789 }
24790 }
24791
24792 initializeRow(row){
24793 var self = this,
24794 rowEl = row.getElement();
24795
24796 var handle = document.createElement('div');
24797 handle.className = "tabulator-row-resize-handle";
24798
24799 var prevHandle = document.createElement('div');
24800 prevHandle.className = "tabulator-row-resize-handle prev";
24801
24802 handle.addEventListener("click", function(e){
24803 e.stopPropagation();
24804 });
24805
24806 var handleDown = function(e){
24807 self.startRow = row;
24808 self._mouseDown(e, row, handle);
24809 };
24810
24811 handle.addEventListener("mousedown", handleDown);
24812 handle.addEventListener("touchstart", handleDown, {passive: true});
24813
24814 prevHandle.addEventListener("click", function(e){
24815 e.stopPropagation();
24816 });
24817
24818 var prevHandleDown = function(e){
24819 var prevRow = self.table.rowManager.prevDisplayRow(row);
24820
24821 if(prevRow){
24822 self.startRow = prevRow;
24823 self._mouseDown(e, prevRow, prevHandle);
24824 }
24825 };
24826
24827 prevHandle.addEventListener("mousedown",prevHandleDown);
24828 prevHandle.addEventListener("touchstart",prevHandleDown, {passive: true});
24829
24830 rowEl.appendChild(handle);
24831 rowEl.appendChild(prevHandle);
24832 }
24833
24834 resize(e, row) {
24835 row.setHeight(this.startHeight + ((typeof e.screenY === "undefined" ? e.touches[0].screenY : e.screenY) - this.startY));
24836 }
24837
24838 calcGuidePosition(e, row, handle) {
24839 var mouseY = typeof e.screenY === "undefined" ? e.touches[0].screenY : e.screenY,
24840 handleY = handle.getBoundingClientRect().y - this.table.element.getBoundingClientRect().y,
24841 tableY = this.table.element.getBoundingClientRect().y,
24842 rowY = row.element.getBoundingClientRect().top - tableY,
24843 mouseDiff = mouseY - this.startY;
24844
24845 return Math.max(handleY + mouseDiff, rowY);
24846 }
24847
24848 _mouseDown(e, row, handle){
24849 var self = this,
24850 guideEl;
24851
24852 self.dispatchExternal("rowResizing", row.getComponent());
24853
24854 if(self.table.options.resizableRowGuide){
24855 guideEl = document.createElement("span");
24856 guideEl.classList.add('tabulator-row-resize-guide');
24857 self.table.element.appendChild(guideEl);
24858 setTimeout(() => {
24859 guideEl.style.top = self.calcGuidePosition(e, row, handle) + "px";
24860 });
24861 }
24862
24863 self.table.element.classList.add("tabulator-block-select");
24864
24865 function mouseMove(e){
24866 if(self.table.options.resizableRowGuide){
24867 guideEl.style.top = self.calcGuidePosition(e, row, handle) + "px";
24868 }else {
24869 self.resize(e, row);
24870 }
24871 }
24872
24873 function mouseUp(e){
24874 if(self.table.options.resizableRowGuide){
24875 self.resize(e, row);
24876 guideEl.remove();
24877 }
24878
24879 // //block editor from taking action while resizing is taking place
24880 // if(self.startColumn.modules.edit){
24881 // self.startColumn.modules.edit.blocked = false;
24882 // }
24883
24884 document.body.removeEventListener("mouseup", mouseMove);
24885 document.body.removeEventListener("mousemove", mouseMove);
24886
24887 handle.removeEventListener("touchmove", mouseMove);
24888 handle.removeEventListener("touchend", mouseUp);
24889
24890 self.table.element.classList.remove("tabulator-block-select");
24891
24892 self.dispatchExternal("rowResized", row.getComponent());
24893 }
24894
24895 e.stopPropagation(); //prevent resize from interfering with movable columns
24896
24897 //block editor from taking action while resizing is taking place
24898 // if(self.startColumn.modules.edit){
24899 // self.startColumn.modules.edit.blocked = true;
24900 // }
24901
24902 self.startY = typeof e.screenY === "undefined" ? e.touches[0].screenY : e.screenY;
24903 self.startHeight = row.getHeight();
24904
24905 document.body.addEventListener("mousemove", mouseMove);
24906 document.body.addEventListener("mouseup", mouseUp);
24907
24908 handle.addEventListener("touchmove", mouseMove, {passive: true});
24909 handle.addEventListener("touchend", mouseUp);
24910 }
24911 }
24912
24913 class ResizeTable extends Module{
24914
24915 static moduleName = "resizeTable";
24916
24917 constructor(table){
24918 super(table);
24919
24920 this.binding = false;
24921 this.visibilityObserver = false;
24922 this.resizeObserver = false;
24923 this.containerObserver = false;
24924
24925 this.tableHeight = 0;
24926 this.tableWidth = 0;
24927 this.containerHeight = 0;
24928 this.containerWidth = 0;
24929
24930 this.autoResize = false;
24931
24932 this.visible = false;
24933
24934 this.initialized = false;
24935 this.initialRedraw = false;
24936
24937 this.registerTableOption("autoResize", true); //auto resize table
24938 }
24939
24940 initialize(){
24941 if(this.table.options.autoResize){
24942 var table = this.table,
24943 tableStyle;
24944
24945 this.tableHeight = table.element.clientHeight;
24946 this.tableWidth = table.element.clientWidth;
24947
24948 if(table.element.parentNode){
24949 this.containerHeight = table.element.parentNode.clientHeight;
24950 this.containerWidth = table.element.parentNode.clientWidth;
24951 }
24952
24953 if(typeof IntersectionObserver !== "undefined" && typeof ResizeObserver !== "undefined" && table.rowManager.getRenderMode() === "virtual"){
24954
24955 this.initializeVisibilityObserver();
24956
24957 this.autoResize = true;
24958
24959 this.resizeObserver = new ResizeObserver((entry) => {
24960 if(!table.browserMobile || (table.browserMobile && (!table.modules.edit || (table.modules.edit && !table.modules.edit.currentCell)))){
24961
24962 var nodeHeight = Math.floor(entry[0].contentRect.height);
24963 var nodeWidth = Math.floor(entry[0].contentRect.width);
24964
24965 if(this.tableHeight != nodeHeight || this.tableWidth != nodeWidth){
24966 this.tableHeight = nodeHeight;
24967 this.tableWidth = nodeWidth;
24968
24969 if(table.element.parentNode){
24970 this.containerHeight = table.element.parentNode.clientHeight;
24971 this.containerWidth = table.element.parentNode.clientWidth;
24972 }
24973
24974 this.redrawTable();
24975 }
24976 }
24977 });
24978
24979 this.resizeObserver.observe(table.element);
24980
24981 tableStyle = window.getComputedStyle(table.element);
24982
24983 if(this.table.element.parentNode && !this.table.rowManager.fixedHeight && (tableStyle.getPropertyValue("max-height") || tableStyle.getPropertyValue("min-height"))){
24984
24985 this.containerObserver = new ResizeObserver((entry) => {
24986 if(!table.browserMobile || (table.browserMobile && (!table.modules.edit || (table.modules.edit && !table.modules.edit.currentCell)))){
24987
24988 var nodeHeight = Math.floor(entry[0].contentRect.height);
24989 var nodeWidth = Math.floor(entry[0].contentRect.width);
24990
24991 if(this.containerHeight != nodeHeight || this.containerWidth != nodeWidth){
24992 this.containerHeight = nodeHeight;
24993 this.containerWidth = nodeWidth;
24994 this.tableHeight = table.element.clientHeight;
24995 this.tableWidth = table.element.clientWidth;
24996 }
24997
24998 this.redrawTable();
24999 }
25000 });
25001
25002 this.containerObserver.observe(this.table.element.parentNode);
25003 }
25004
25005 this.subscribe("table-resize", this.tableResized.bind(this));
25006
25007 }else {
25008 this.binding = function(){
25009 if(!table.browserMobile || (table.browserMobile && (!table.modules.edit || (table.modules.edit && !table.modules.edit.currentCell)))){
25010 table.columnManager.rerenderColumns(true);
25011 table.redraw();
25012 }
25013 };
25014
25015 window.addEventListener("resize", this.binding);
25016 }
25017
25018 this.subscribe("table-destroy", this.clearBindings.bind(this));
25019 }
25020 }
25021
25022 initializeVisibilityObserver(){
25023 this.visibilityObserver = new IntersectionObserver((entries) => {
25024 this.visible = entries[entries.length - 1].isIntersecting;
25025
25026 if(!this.initialized){
25027 this.initialized = true;
25028 this.initialRedraw = !this.visible;
25029 }else {
25030 if(this.visible){
25031 this.redrawTable(this.initialRedraw);
25032 this.initialRedraw = false;
25033 }
25034 }
25035 });
25036
25037 this.visibilityObserver.observe(this.table.element);
25038 }
25039
25040 redrawTable(force){
25041 if(this.initialized && this.visible){
25042 this.table.columnManager.rerenderColumns(true);
25043 this.table.redraw(force);
25044 }
25045 }
25046
25047 tableResized(){
25048 this.table.rowManager.redraw();
25049 }
25050
25051 clearBindings(){
25052 if(this.binding){
25053 window.removeEventListener("resize", this.binding);
25054 }
25055
25056 if(this.resizeObserver){
25057 this.resizeObserver.unobserve(this.table.element);
25058 }
25059
25060 if(this.visibilityObserver){
25061 this.visibilityObserver.unobserve(this.table.element);
25062 }
25063
25064 if(this.containerObserver){
25065 this.containerObserver.unobserve(this.table.element.parentNode);
25066 }
25067 }
25068 }
25069
25070 function responsiveCollapse(cell, formatterParams, onRendered){
25071 var el = document.createElement("div"),
25072 config = cell.getRow()._row.modules.responsiveLayout;
25073
25074 el.classList.add("tabulator-responsive-collapse-toggle");
25075
25076 el.innerHTML = `<svg class='tabulator-responsive-collapse-toggle-open' viewbox="0 0 24 24">
25077 <line x1="7" y1="12" x2="17" y2="12" fill="none" stroke-width="3" stroke-linecap="round" />
25078 <line y1="7" x1="12" y2="17" x2="12" fill="none" stroke-width="3" stroke-linecap="round" />
25079 </svg>
25080
25081 <svg class='tabulator-responsive-collapse-toggle-close' viewbox="0 0 24 24">
25082 <line x1="7" y1="12" x2="17" y2="12" fill="none" stroke-width="3" stroke-linecap="round" />
25083 </svg>`;
25084
25085 cell.getElement().classList.add("tabulator-row-handle");
25086
25087 function toggleList(isOpen){
25088 var collapseEl = config.element;
25089
25090 config.open = isOpen;
25091
25092 if(collapseEl){
25093
25094 if(config.open){
25095 el.classList.add("open");
25096 collapseEl.style.display = '';
25097 }else {
25098 el.classList.remove("open");
25099 collapseEl.style.display = 'none';
25100 }
25101 }
25102 }
25103
25104 el.addEventListener("click", function(e){
25105 e.stopImmediatePropagation();
25106 toggleList(!config.open);
25107 cell.getTable().rowManager.adjustTableSize();
25108 });
25109
25110 toggleList(config.open);
25111
25112 return el;
25113 }
25114
25115 var extensions$2 = {
25116 format:{
25117 formatters:{
25118 responsiveCollapse:responsiveCollapse,
25119 }
25120 }
25121 };
25122
25123 class ResponsiveLayout extends Module{
25124
25125 static moduleName = "responsiveLayout";
25126 static moduleExtensions = extensions$2;
25127
25128 constructor(table){
25129 super(table);
25130
25131 this.columns = [];
25132 this.hiddenColumns = [];
25133 this.mode = "";
25134 this.index = 0;
25135 this.collapseFormatter = [];
25136 this.collapseStartOpen = true;
25137 this.collapseHandleColumn = false;
25138
25139 this.registerTableOption("responsiveLayout", false); //responsive layout flags
25140 this.registerTableOption("responsiveLayoutCollapseStartOpen", true); //start showing collapsed data
25141 this.registerTableOption("responsiveLayoutCollapseUseFormatters", true); //responsive layout collapse formatter
25142 this.registerTableOption("responsiveLayoutCollapseFormatter", false); //responsive layout collapse formatter
25143
25144 this.registerColumnOption("responsive");
25145 }
25146
25147 //generate responsive columns list
25148 initialize(){
25149 if(this.table.options.responsiveLayout){
25150 this.subscribe("column-layout", this.initializeColumn.bind(this));
25151 this.subscribe("column-show", this.updateColumnVisibility.bind(this));
25152 this.subscribe("column-hide", this.updateColumnVisibility.bind(this));
25153 this.subscribe("columns-loaded", this.initializeResponsivity.bind(this));
25154 this.subscribe("column-moved", this.initializeResponsivity.bind(this));
25155 this.subscribe("column-add", this.initializeResponsivity.bind(this));
25156 this.subscribe("column-delete", this.initializeResponsivity.bind(this));
25157
25158 this.subscribe("table-redrawing", this.tableRedraw.bind(this));
25159
25160 if(this.table.options.responsiveLayout === "collapse"){
25161 this.subscribe("row-data-changed", this.generateCollapsedRowContent.bind(this));
25162 this.subscribe("row-init", this.initializeRow.bind(this));
25163 this.subscribe("row-layout", this.layoutRow.bind(this));
25164 }
25165 }
25166 }
25167
25168 tableRedraw(force){
25169 if(["fitColumns", "fitDataStretch"].indexOf(this.layoutMode()) === -1){
25170 if(!force){
25171 this.update();
25172 }
25173 }
25174 }
25175
25176 initializeResponsivity(){
25177 var columns = [];
25178
25179 this.mode = this.table.options.responsiveLayout;
25180 this.collapseFormatter = this.table.options.responsiveLayoutCollapseFormatter || this.formatCollapsedData;
25181 this.collapseStartOpen = this.table.options.responsiveLayoutCollapseStartOpen;
25182 this.hiddenColumns = [];
25183
25184 if(this.collapseFormatter){
25185 this.collapseFormatter = this.collapseFormatter.bind(this.table);
25186 }
25187
25188 //determine level of responsivity for each column
25189 this.table.columnManager.columnsByIndex.forEach((column, i) => {
25190 if(column.modules.responsive){
25191 if(column.modules.responsive.order && column.modules.responsive.visible){
25192 column.modules.responsive.index = i;
25193 columns.push(column);
25194
25195 if(!column.visible && this.mode === "collapse"){
25196 this.hiddenColumns.push(column);
25197 }
25198 }
25199 }
25200 });
25201
25202 //sort list by responsivity
25203 columns = columns.reverse();
25204 columns = columns.sort((a, b) => {
25205 var diff = b.modules.responsive.order - a.modules.responsive.order;
25206 return diff || (b.modules.responsive.index - a.modules.responsive.index);
25207 });
25208
25209 this.columns = columns;
25210
25211 if(this.mode === "collapse"){
25212 this.generateCollapsedContent();
25213 }
25214
25215 //assign collapse column
25216 for (let col of this.table.columnManager.columnsByIndex){
25217 if(col.definition.formatter == "responsiveCollapse"){
25218 this.collapseHandleColumn = col;
25219 break;
25220 }
25221 }
25222
25223 if(this.collapseHandleColumn){
25224 if(this.hiddenColumns.length){
25225 this.collapseHandleColumn.show();
25226 }else {
25227 this.collapseHandleColumn.hide();
25228 }
25229 }
25230 }
25231
25232 //define layout information
25233 initializeColumn(column){
25234 var def = column.getDefinition();
25235
25236 column.modules.responsive = {order: typeof def.responsive === "undefined" ? 1 : def.responsive, visible:def.visible === false ? false : true};
25237 }
25238
25239 initializeRow(row){
25240 var el;
25241
25242 if(row.type !== "calc"){
25243 el = document.createElement("div");
25244 el.classList.add("tabulator-responsive-collapse");
25245
25246 row.modules.responsiveLayout = {
25247 element:el,
25248 open:this.collapseStartOpen,
25249 };
25250
25251 if(!this.collapseStartOpen){
25252 el.style.display = 'none';
25253 }
25254 }
25255 }
25256
25257 layoutRow(row){
25258 var rowEl = row.getElement();
25259
25260 if(row.modules.responsiveLayout){
25261 rowEl.appendChild(row.modules.responsiveLayout.element);
25262 this.generateCollapsedRowContent(row);
25263 }
25264 }
25265
25266 //update column visibility
25267 updateColumnVisibility(column, responsiveToggle){
25268 if(!responsiveToggle && column.modules.responsive){
25269 column.modules.responsive.visible = column.visible;
25270 this.initializeResponsivity();
25271 }
25272 }
25273
25274 hideColumn(column){
25275 var colCount = this.hiddenColumns.length;
25276
25277 column.hide(false, true);
25278
25279 if(this.mode === "collapse"){
25280 this.hiddenColumns.unshift(column);
25281 this.generateCollapsedContent();
25282
25283 if(this.collapseHandleColumn && !colCount){
25284 this.collapseHandleColumn.show();
25285 }
25286 }
25287 }
25288
25289 showColumn(column){
25290 var index;
25291
25292 column.show(false, true);
25293 //set column width to prevent calculation loops on uninitialized columns
25294 column.setWidth(column.getWidth());
25295
25296 if(this.mode === "collapse"){
25297 index = this.hiddenColumns.indexOf(column);
25298
25299 if(index > -1){
25300 this.hiddenColumns.splice(index, 1);
25301 }
25302
25303 this.generateCollapsedContent();
25304
25305 if(this.collapseHandleColumn && !this.hiddenColumns.length){
25306 this.collapseHandleColumn.hide();
25307 }
25308 }
25309 }
25310
25311 //redraw columns to fit space
25312 update(){
25313 var working = true;
25314
25315 while(working){
25316
25317 let width = this.table.modules.layout.getMode() == "fitColumns" ? this.table.columnManager.getFlexBaseWidth() : this.table.columnManager.getWidth();
25318
25319 let diff = (this.table.options.headerVisible ? this.table.columnManager.element.clientWidth : this.table.element.clientWidth) - width;
25320
25321 if(diff < 0){
25322 //table is too wide
25323 let column = this.columns[this.index];
25324
25325 if(column){
25326 this.hideColumn(column);
25327 this.index ++;
25328 }else {
25329 working = false;
25330 }
25331
25332 }else {
25333
25334 //table has spare space
25335 let column = this.columns[this.index -1];
25336
25337 if(column){
25338 if(diff > 0){
25339 if(diff >= column.getWidth()){
25340 this.showColumn(column);
25341 this.index --;
25342 }else {
25343 working = false;
25344 }
25345 }else {
25346 working = false;
25347 }
25348 }else {
25349 working = false;
25350 }
25351 }
25352
25353 if(!this.table.rowManager.activeRowsCount){
25354 this.table.rowManager.renderEmptyScroll();
25355 }
25356 }
25357 }
25358
25359 generateCollapsedContent(){
25360 var rows = this.table.rowManager.getDisplayRows();
25361
25362 rows.forEach((row) => {
25363 this.generateCollapsedRowContent(row);
25364 });
25365 }
25366
25367 generateCollapsedRowContent(row){
25368 var el, contents;
25369
25370 if(row.modules.responsiveLayout){
25371 el = row.modules.responsiveLayout.element;
25372
25373 while(el.firstChild) el.removeChild(el.firstChild);
25374
25375 contents = this.collapseFormatter(this.generateCollapsedRowData(row));
25376 if(contents){
25377 el.appendChild(contents);
25378 }
25379 row.calcHeight(true);
25380 }
25381 }
25382
25383 generateCollapsedRowData(row){
25384 var data = row.getData(),
25385 output = [],
25386 mockCellComponent;
25387
25388 this.hiddenColumns.forEach((column) => {
25389 var value = column.getFieldValue(data);
25390
25391 if(column.definition.title && column.field){
25392 if(column.modules.format && this.table.options.responsiveLayoutCollapseUseFormatters){
25393
25394 mockCellComponent = {
25395 value:false,
25396 data:{},
25397 getValue:function(){
25398 return value;
25399 },
25400 getData:function(){
25401 return data;
25402 },
25403 getType:function(){
25404 return "cell";
25405 },
25406 getElement:function(){
25407 return document.createElement("div");
25408 },
25409 getRow:function(){
25410 return row.getComponent();
25411 },
25412 getColumn:function(){
25413 return column.getComponent();
25414 },
25415 getTable:() => {
25416 return this.table;
25417 },
25418 };
25419
25420 function onRendered(callback){
25421 callback();
25422 }
25423
25424 output.push({
25425 field: column.field,
25426 title: column.definition.title,
25427 value: column.modules.format.formatter.call(this.table.modules.format, mockCellComponent, column.modules.format.params, onRendered)
25428 });
25429 }else {
25430 output.push({
25431 field: column.field,
25432 title: column.definition.title,
25433 value: value
25434 });
25435 }
25436 }
25437 });
25438
25439 return output;
25440 }
25441
25442 formatCollapsedData(data){
25443 var list = document.createElement("table");
25444
25445 data.forEach((item) => {
25446 var row = document.createElement("tr");
25447 var titleData = document.createElement("td");
25448 var valueData = document.createElement("td");
25449 var node_content;
25450
25451 var titleHighlight = document.createElement("strong");
25452 titleData.appendChild(titleHighlight);
25453
25454 this.modules.localize.bind("columns|" + item.field, function(text){
25455 titleHighlight.innerHTML = text || item.title;
25456 });
25457
25458 if(item.value instanceof Node){
25459 node_content = document.createElement("div");
25460 node_content.appendChild(item.value);
25461 valueData.appendChild(node_content);
25462 }else {
25463 valueData.innerHTML = item.value;
25464 }
25465
25466 row.appendChild(titleData);
25467 row.appendChild(valueData);
25468 list.appendChild(row);
25469 });
25470
25471 return Object.keys(data).length ? list : "";
25472 }
25473 }
25474
25475 function rowSelection(cell, formatterParams, onRendered){
25476 var checkbox = document.createElement("input");
25477 var blocked = false;
25478
25479 checkbox.type = 'checkbox';
25480
25481 checkbox.setAttribute("aria-label", "Select Row");
25482
25483 if(this.table.modExists("selectRow", true)){
25484
25485 checkbox.addEventListener("click", (e) => {
25486 e.stopPropagation();
25487 });
25488
25489 if(typeof cell.getRow == 'function'){
25490 var row = cell.getRow();
25491
25492 if(row instanceof RowComponent){
25493
25494 checkbox.addEventListener("change", (e) => {
25495 if(this.table.options.selectableRowsRangeMode === "click"){
25496 if(!blocked){
25497 row.toggleSelect();
25498 }else {
25499 blocked = false;
25500 }
25501 }else {
25502 row.toggleSelect();
25503 }
25504 });
25505
25506 if(this.table.options.selectableRowsRangeMode === "click"){
25507 checkbox.addEventListener("click", (e) => {
25508 blocked = true;
25509 this.table.modules.selectRow.handleComplexRowClick(row._row, e);
25510 });
25511 }
25512
25513 checkbox.checked = row.isSelected && row.isSelected();
25514 this.table.modules.selectRow.registerRowSelectCheckbox(row, checkbox);
25515 }else {
25516 checkbox = "";
25517 }
25518 }else {
25519 checkbox.addEventListener("change", (e) => {
25520 if(this.table.modules.selectRow.selectedRows.length){
25521 this.table.deselectRow();
25522 }else {
25523 this.table.selectRow(formatterParams.rowRange);
25524 }
25525 });
25526
25527 this.table.modules.selectRow.registerHeaderSelectCheckbox(checkbox);
25528 }
25529 }
25530
25531 return checkbox;
25532 }
25533
25534 var extensions$1 = {
25535 format:{
25536 formatters:{
25537 rowSelection:rowSelection,
25538 }
25539 }
25540 };
25541
25542 class SelectRow extends Module{
25543
25544 static moduleName = "selectRow";
25545 static moduleExtensions = extensions$1;
25546
25547 constructor(table){
25548 super(table);
25549
25550 this.selecting = false; //flag selecting in progress
25551 this.lastClickedRow = false; //last clicked row
25552 this.selectPrev = []; //hold previously selected element for drag drop selection
25553 this.selectedRows = []; //hold selected rows
25554 this.headerCheckboxElement = null; // hold header select element
25555
25556 this.registerTableOption("selectableRows", "highlight"); //highlight rows on hover
25557 this.registerTableOption("selectableRowsRangeMode", "drag"); //highlight rows on hover
25558 this.registerTableOption("selectableRowsRollingSelection", true); //roll selection once maximum number of selectable rows is reached
25559 this.registerTableOption("selectableRowsPersistence", true); // maintain selection when table view is updated
25560 this.registerTableOption("selectableRowsCheck", function(data, row){return true;}); //check whether row is selectable
25561
25562 this.registerTableFunction("selectRow", this.selectRows.bind(this));
25563 this.registerTableFunction("deselectRow", this.deselectRows.bind(this));
25564 this.registerTableFunction("toggleSelectRow", this.toggleRow.bind(this));
25565 this.registerTableFunction("getSelectedRows", this.getSelectedRows.bind(this));
25566 this.registerTableFunction("getSelectedData", this.getSelectedData.bind(this));
25567
25568 //register component functions
25569 this.registerComponentFunction("row", "select", this.selectRows.bind(this));
25570 this.registerComponentFunction("row", "deselect", this.deselectRows.bind(this));
25571 this.registerComponentFunction("row", "toggleSelect", this.toggleRow.bind(this));
25572 this.registerComponentFunction("row", "isSelected", this.isRowSelected.bind(this));
25573 }
25574
25575 initialize(){
25576
25577 this.deprecatedOptionsCheck();
25578
25579 if(this.table.options.selectableRows === "highlight" && this.table.options.selectableRange){
25580 this.table.options.selectableRows = false;
25581 }
25582
25583 if(this.table.options.selectableRows !== false){
25584 this.subscribe("row-init", this.initializeRow.bind(this));
25585 this.subscribe("row-deleting", this.rowDeleted.bind(this));
25586 this.subscribe("rows-wipe", this.clearSelectionData.bind(this));
25587 this.subscribe("rows-retrieve", this.rowRetrieve.bind(this));
25588
25589 if(this.table.options.selectableRows && !this.table.options.selectableRowsPersistence){
25590 this.subscribe("data-refreshing", this.deselectRows.bind(this));
25591 }
25592 }
25593 }
25594
25595 deprecatedOptionsCheck(){
25596 // this.deprecationCheck("selectable", "selectableRows", true);
25597 // this.deprecationCheck("selectableRollingSelection", "selectableRowsRollingSelection", true);
25598 // this.deprecationCheck("selectableRangeMode", "selectableRowsRangeMode", true);
25599 // this.deprecationCheck("selectablePersistence", "selectableRowsPersistence", true);
25600 // this.deprecationCheck("selectableCheck", "selectableRowsCheck", true);
25601 }
25602
25603 rowRetrieve(type, prevValue){
25604 return type === "selected" ? this.selectedRows : prevValue;
25605 }
25606
25607 rowDeleted(row){
25608 this._deselectRow(row, true);
25609 }
25610
25611 clearSelectionData(silent){
25612 var prevSelected = this.selectedRows.length;
25613
25614 this.selecting = false;
25615 this.lastClickedRow = false;
25616 this.selectPrev = [];
25617 this.selectedRows = [];
25618
25619 if(prevSelected && silent !== true){
25620 this._rowSelectionChanged();
25621 }
25622 }
25623
25624 initializeRow(row){
25625 var self = this,
25626 selectable = self.checkRowSelectability(row),
25627 element = row.getElement();
25628
25629 // trigger end of row selection
25630 var endSelect = function(){
25631
25632 setTimeout(function(){
25633 self.selecting = false;
25634 }, 50);
25635
25636 document.body.removeEventListener("mouseup", endSelect);
25637 };
25638
25639 row.modules.select = {selected:false};
25640
25641 element.classList.toggle("tabulator-selectable", selectable);
25642 element.classList.toggle("tabulator-unselectable", !selectable);
25643
25644 //set row selection class
25645 if(self.checkRowSelectability(row)){
25646 if(self.table.options.selectableRows && self.table.options.selectableRows != "highlight"){
25647 if(self.table.options.selectableRowsRangeMode === "click"){
25648 element.addEventListener("click", this.handleComplexRowClick.bind(this, row));
25649 }else {
25650 element.addEventListener("click", function(e){
25651 if(!self.table.modExists("edit") || !self.table.modules.edit.getCurrentCell()){
25652 self.table._clearSelection();
25653 }
25654
25655 if(!self.selecting){
25656 self.toggleRow(row);
25657 }
25658 });
25659
25660 element.addEventListener("mousedown", function(e){
25661 if(e.shiftKey){
25662 self.table._clearSelection();
25663
25664 self.selecting = true;
25665
25666 self.selectPrev = [];
25667
25668 document.body.addEventListener("mouseup", endSelect);
25669 document.body.addEventListener("keyup", endSelect);
25670
25671 self.toggleRow(row);
25672
25673 return false;
25674 }
25675 });
25676
25677 element.addEventListener("mouseenter", function(e){
25678 if(self.selecting){
25679 self.table._clearSelection();
25680 self.toggleRow(row);
25681
25682 if(self.selectPrev[1] == row){
25683 self.toggleRow(self.selectPrev[0]);
25684 }
25685 }
25686 });
25687
25688 element.addEventListener("mouseout", function(e){
25689 if(self.selecting){
25690 self.table._clearSelection();
25691 self.selectPrev.unshift(row);
25692 }
25693 });
25694 }
25695 }
25696 }
25697 }
25698
25699 handleComplexRowClick(row, e){
25700 if(e.shiftKey){
25701 this.table._clearSelection();
25702 this.lastClickedRow = this.lastClickedRow || row;
25703
25704 var lastClickedRowIdx = this.table.rowManager.getDisplayRowIndex(this.lastClickedRow);
25705 var rowIdx = this.table.rowManager.getDisplayRowIndex(row);
25706
25707 var fromRowIdx = lastClickedRowIdx <= rowIdx ? lastClickedRowIdx : rowIdx;
25708 var toRowIdx = lastClickedRowIdx >= rowIdx ? lastClickedRowIdx : rowIdx;
25709
25710 var rows = this.table.rowManager.getDisplayRows().slice(0);
25711 var toggledRows = rows.splice(fromRowIdx, toRowIdx - fromRowIdx + 1);
25712
25713 if(e.ctrlKey || e.metaKey){
25714 toggledRows.forEach((toggledRow)=>{
25715 if(toggledRow !== this.lastClickedRow){
25716
25717 if(this.table.options.selectableRows !== true && !this.isRowSelected(row)){
25718 if(this.selectedRows.length < this.table.options.selectableRows){
25719 this.toggleRow(toggledRow);
25720 }
25721 }else {
25722 this.toggleRow(toggledRow);
25723 }
25724 }
25725 });
25726 this.lastClickedRow = row;
25727 }else {
25728 this.deselectRows(undefined, true);
25729
25730 if(this.table.options.selectableRows !== true){
25731 if(toggledRows.length > this.table.options.selectableRows){
25732 toggledRows = toggledRows.slice(0, this.table.options.selectableRows);
25733 }
25734 }
25735
25736 this.selectRows(toggledRows);
25737 }
25738 this.table._clearSelection();
25739 }
25740 else if(e.ctrlKey || e.metaKey){
25741 this.toggleRow(row);
25742 this.lastClickedRow = row;
25743 }else {
25744 this.deselectRows(undefined, true);
25745 this.selectRows(row);
25746 this.lastClickedRow = row;
25747 }
25748 }
25749
25750 checkRowSelectability(row){
25751 if(row && row.type === "row"){
25752 return this.table.options.selectableRowsCheck.call(this.table, row.getComponent());
25753 }
25754
25755 return false;
25756 }
25757
25758 //toggle row selection
25759 toggleRow(row){
25760 if(this.checkRowSelectability(row)){
25761 if(row.modules.select && row.modules.select.selected){
25762 this._deselectRow(row);
25763 }else {
25764 this._selectRow(row);
25765 }
25766 }
25767 }
25768
25769 //select a number of rows
25770 selectRows(rows){
25771 var changes = [],
25772 rowMatch, change;
25773
25774 switch(typeof rows){
25775 case "undefined":
25776 rowMatch = this.table.rowManager.rows;
25777 break;
25778
25779 case "number":
25780 rowMatch = this.table.rowManager.findRow(rows);
25781 break;
25782
25783 case "string":
25784 rowMatch = this.table.rowManager.findRow(rows);
25785
25786 if(!rowMatch){
25787 rowMatch = this.table.rowManager.getRows(rows);
25788 }
25789 break;
25790
25791 default:
25792 rowMatch = rows;
25793 break;
25794 }
25795
25796 if(Array.isArray(rowMatch)){
25797 if(rowMatch.length){
25798 rowMatch.forEach((row) => {
25799 change = this._selectRow(row, true, true);
25800
25801 if(change){
25802 changes.push(change);
25803 }
25804 });
25805
25806 this._rowSelectionChanged(false, changes);
25807 }
25808 }else {
25809 if(rowMatch){
25810 this._selectRow(rowMatch, false, true);
25811 }
25812 }
25813 }
25814
25815 //select an individual row
25816 _selectRow(rowInfo, silent, force){
25817 //handle max row count
25818 if(!isNaN(this.table.options.selectableRows) && this.table.options.selectableRows !== true && !force){
25819 if(this.selectedRows.length >= this.table.options.selectableRows){
25820 if(this.table.options.selectableRowsRollingSelection){
25821 this._deselectRow(this.selectedRows[0]);
25822 }else {
25823 return false;
25824 }
25825 }
25826 }
25827
25828 var row = this.table.rowManager.findRow(rowInfo);
25829
25830 if(row){
25831 if(this.selectedRows.indexOf(row) == -1){
25832 row.getElement().classList.add("tabulator-selected");
25833 if(!row.modules.select){
25834 row.modules.select = {};
25835 }
25836
25837 row.modules.select.selected = true;
25838 if(row.modules.select.checkboxEl){
25839 row.modules.select.checkboxEl.checked = true;
25840 }
25841
25842 this.selectedRows.push(row);
25843
25844 if(this.table.options.dataTreeSelectPropagate){
25845 this.childRowSelection(row, true);
25846 }
25847
25848 this.dispatchExternal("rowSelected", row.getComponent());
25849
25850 this._rowSelectionChanged(silent, row);
25851
25852 return row;
25853 }
25854 }else {
25855 if(!silent){
25856 console.warn("Selection Error - No such row found, ignoring selection:" + rowInfo);
25857 }
25858 }
25859 }
25860
25861 isRowSelected(row){
25862 return this.selectedRows.indexOf(row) !== -1;
25863 }
25864
25865 //deselect a number of rows
25866 deselectRows(rows, silent){
25867 var changes = [],
25868 rowMatch, change;
25869
25870 switch(typeof rows){
25871 case "undefined":
25872 rowMatch = Object.assign([], this.selectedRows);
25873 break;
25874
25875 case "number":
25876 rowMatch = this.table.rowManager.findRow(rows);
25877 break;
25878
25879 case "string":
25880 rowMatch = this.table.rowManager.findRow(rows);
25881
25882 if(!rowMatch){
25883 rowMatch = this.table.rowManager.getRows(rows);
25884 }
25885 break;
25886
25887 default:
25888 rowMatch = rows;
25889 break;
25890 }
25891
25892 if(Array.isArray(rowMatch)){
25893 if(rowMatch.length){
25894 rowMatch.forEach((row) => {
25895 change = this._deselectRow(row, true, true);
25896
25897 if(change){
25898 changes.push(change);
25899 }
25900 });
25901
25902 this._rowSelectionChanged(silent, [], changes);
25903 }
25904 }else {
25905 if(rowMatch){
25906 this._deselectRow(rowMatch, silent, true);
25907 }
25908 }
25909 }
25910
25911 //deselect an individual row
25912 _deselectRow(rowInfo, silent){
25913 var self = this,
25914 row = self.table.rowManager.findRow(rowInfo),
25915 index, element;
25916
25917 if(row){
25918 index = self.selectedRows.findIndex(function(selectedRow){
25919 return selectedRow == row;
25920 });
25921
25922 if(index > -1){
25923
25924 element = row.getElement();
25925
25926 if(element){
25927 element.classList.remove("tabulator-selected");
25928 }
25929
25930 if(!row.modules.select){
25931 row.modules.select = {};
25932 }
25933
25934 row.modules.select.selected = false;
25935 if(row.modules.select.checkboxEl){
25936 row.modules.select.checkboxEl.checked = false;
25937 }
25938 self.selectedRows.splice(index, 1);
25939
25940 if(this.table.options.dataTreeSelectPropagate){
25941 this.childRowSelection(row, false);
25942 }
25943
25944 this.dispatchExternal("rowDeselected", row.getComponent());
25945
25946 self._rowSelectionChanged(silent, undefined, row);
25947
25948 return row;
25949 }
25950 }else {
25951 if(!silent){
25952 console.warn("Deselection Error - No such row found, ignoring selection:" + rowInfo);
25953 }
25954 }
25955 }
25956
25957 getSelectedData(){
25958 var data = [];
25959
25960 this.selectedRows.forEach(function(row){
25961 data.push(row.getData());
25962 });
25963
25964 return data;
25965 }
25966
25967 getSelectedRows(){
25968 var rows = [];
25969
25970 this.selectedRows.forEach(function(row){
25971 rows.push(row.getComponent());
25972 });
25973
25974 return rows;
25975 }
25976
25977 _rowSelectionChanged(silent, selected = [], deselected = []){
25978 if(this.headerCheckboxElement){
25979 if(this.selectedRows.length === 0){
25980 this.headerCheckboxElement.checked = false;
25981 this.headerCheckboxElement.indeterminate = false;
25982 } else if(this.table.rowManager.rows.length === this.selectedRows.length){
25983 this.headerCheckboxElement.checked = true;
25984 this.headerCheckboxElement.indeterminate = false;
25985 } else {
25986 this.headerCheckboxElement.indeterminate = true;
25987 this.headerCheckboxElement.checked = false;
25988 }
25989 }
25990
25991 if(!silent){
25992 if(!Array.isArray(selected)){
25993 selected = [selected];
25994 }
25995
25996 selected = selected.map(row => row.getComponent());
25997
25998 if(!Array.isArray(deselected)){
25999 deselected = [deselected];
26000 }
26001
26002 deselected = deselected.map(row => row.getComponent());
26003
26004 this.dispatchExternal("rowSelectionChanged", this.getSelectedData(), this.getSelectedRows(), selected, deselected);
26005 }
26006 }
26007
26008 registerRowSelectCheckbox (row, element) {
26009 if(!row._row.modules.select){
26010 row._row.modules.select = {};
26011 }
26012
26013 row._row.modules.select.checkboxEl = element;
26014 }
26015
26016 registerHeaderSelectCheckbox (element) {
26017 this.headerCheckboxElement = element;
26018 }
26019
26020 childRowSelection(row, select){
26021 var children = this.table.modules.dataTree.getChildren(row, true, true);
26022
26023 if(select){
26024 for(let child of children){
26025 this._selectRow(child, true);
26026 }
26027 }else {
26028 for(let child of children){
26029 this._deselectRow(child, true);
26030 }
26031 }
26032 }
26033 }
26034
26035 class RangeComponent {
26036 constructor(range) {
26037 this._range = range;
26038
26039 return new Proxy(this, {
26040 get: function (target, name, receiver) {
26041 if (typeof target[name] !== "undefined") {
26042 return target[name];
26043 } else {
26044 return target._range.table.componentFunctionBinder.handle("range", target._range, name);
26045 }
26046 },
26047 });
26048 }
26049
26050 getElement() {
26051 return this._range.element;
26052 }
26053
26054 getData() {
26055 return this._range.getData();
26056 }
26057
26058 getCells() {
26059 return this._range.getCells(true, true);
26060 }
26061
26062 getStructuredCells() {
26063 return this._range.getStructuredCells();
26064 }
26065
26066 getRows() {
26067 return this._range.getRows().map((row) => row.getComponent());
26068 }
26069
26070 getColumns() {
26071 return this._range.getColumns().map((column) => column.getComponent());
26072 }
26073
26074 getBounds() {
26075 return this._range.getBounds();
26076 }
26077
26078 getTopEdge() {
26079 return this._range.top;
26080 }
26081
26082 getBottomEdge() {
26083 return this._range.bottom;
26084 }
26085
26086 getLeftEdge() {
26087 return this._range.left;
26088 }
26089
26090 getRightEdge() {
26091 return this._range.right;
26092 }
26093
26094 setBounds(start, end){
26095 if(this._range.destroyedGuard("setBounds")){
26096 this._range.setBounds(start ? start._cell : start, end ? end._cell : end);
26097 }
26098 }
26099
26100 setStartBound(start){
26101 if(this._range.destroyedGuard("setStartBound")){
26102 this._range.setEndBound(start ? start._cell : start);
26103 this._range.rangeManager.layoutElement();
26104 }
26105 }
26106
26107 setEndBound(end){
26108 if(this._range.destroyedGuard("setEndBound")){
26109 this._range.setEndBound(end ? end._cell : end);
26110 this._range.rangeManager.layoutElement();
26111 }
26112 }
26113
26114 clearValues(){
26115 if(this._range.destroyedGuard("clearValues")){
26116 this._range.clearValues();
26117 }
26118 }
26119
26120 remove(){
26121 if(this._range.destroyedGuard("remove")){
26122 this._range.destroy(true);
26123 }
26124 }
26125 }
26126
26127 class Range extends CoreFeature{
26128 constructor(table, rangeManager, start, end) {
26129 super(table);
26130
26131 this.rangeManager = rangeManager;
26132 this.element = null;
26133 this.initialized = false;
26134 this.initializing = {
26135 start:false,
26136 end:false,
26137 };
26138 this.destroyed = false;
26139
26140 this.top = 0;
26141 this.bottom = 0;
26142 this.left = 0;
26143 this.right = 0;
26144
26145 this.table = table;
26146 this.start = {row:undefined, col:undefined};
26147 this.end = {row:undefined, col:undefined};
26148
26149 if(this.rangeManager.rowHeader){
26150 this.left = 1;
26151 this.right = 1;
26152 this.start.col = 1;
26153 this.end.col = 1;
26154 }
26155
26156 this.initElement();
26157
26158 setTimeout(() => {
26159 this.initBounds(start, end);
26160 });
26161 }
26162
26163 initElement(){
26164 this.element = document.createElement("div");
26165 this.element.classList.add("tabulator-range");
26166 }
26167
26168 initBounds(start, end){
26169 this._updateMinMax();
26170
26171 if(start){
26172 this.setBounds(start, end || start);
26173 }
26174 }
26175
26176 ///////////////////////////////////
26177 /////// Boundary Setup ///////
26178 ///////////////////////////////////
26179
26180 setStart(row, col) {
26181 if(this.start.row !== row || this.start.col !== col){
26182 this.start.row = row;
26183 this.start.col = col;
26184
26185 this.initializing.start = true;
26186 this._updateMinMax();
26187 }
26188 }
26189
26190 setEnd(row, col) {
26191 if(this.end.row !== row || this.end.col !== col){
26192 this.end.row = row;
26193 this.end.col = col;
26194
26195 this.initializing.end = true;
26196 this._updateMinMax();
26197 }
26198 }
26199
26200 setBounds(start, end, visibleRows){
26201 if(start){
26202 this.setStartBound(start);
26203 }
26204
26205 this.setEndBound(end || start);
26206 this.rangeManager.layoutElement(visibleRows);
26207 }
26208
26209 setStartBound(element){
26210 var row, col;
26211
26212 if (element.type === "column") {
26213 if(this.rangeManager.columnSelection){
26214 this.setStart(0, element.getPosition() - 1);
26215 }
26216 }else {
26217 row = element.row.position - 1;
26218 col = element.column.getPosition() - 1;
26219
26220 if (element.column === this.rangeManager.rowHeader) {
26221 this.setStart(row, 1);
26222 } else {
26223 this.setStart(row, col);
26224 }
26225 }
26226 }
26227
26228 setEndBound(element){
26229 var rowsCount = this._getTableRows().length,
26230 row, col, isRowHeader;
26231
26232 if (element.type === "column") {
26233 if(this.rangeManager.columnSelection){
26234 if (this.rangeManager.selecting === "column") {
26235 this.setEnd(rowsCount - 1, element.getPosition() - 1);
26236 } else if (this.rangeManager.selecting === "cell") {
26237 this.setEnd(0, element.getPosition() - 1);
26238 }
26239 }
26240 }else {
26241 row = element.row.position - 1;
26242 col = element.column.getPosition() - 1;
26243 isRowHeader = element.column === this.rangeManager.rowHeader;
26244
26245 if (this.rangeManager.selecting === "row") {
26246 this.setEnd(row, this._getTableColumns().length - 1);
26247 } else if (this.rangeManager.selecting !== "row" && isRowHeader) {
26248 this.setEnd(row, 0);
26249 } else if (this.rangeManager.selecting === "column") {
26250 this.setEnd(rowsCount - 1, col);
26251 } else {
26252 this.setEnd(row, col);
26253 }
26254 }
26255 }
26256
26257 _updateMinMax() {
26258 this.top = Math.min(this.start.row, this.end.row);
26259 this.bottom = Math.max(this.start.row, this.end.row);
26260 this.left = Math.min(this.start.col, this.end.col);
26261 this.right = Math.max(this.start.col, this.end.col);
26262
26263 if(this.initialized){
26264 this.dispatchExternal("rangeChanged", this.getComponent());
26265 }else {
26266 if(this.initializing.start && this.initializing.end){
26267 this.initialized = true;
26268 this.dispatchExternal("rangeAdded", this.getComponent());
26269 }
26270 }
26271 }
26272
26273 _getTableColumns() {
26274 return this.table.columnManager.getVisibleColumnsByIndex();
26275 }
26276
26277 _getTableRows() {
26278 return this.table.rowManager.getDisplayRows().filter(row=> row.type === "row");
26279 }
26280
26281 ///////////////////////////////////
26282 /////// Rendering ///////
26283 ///////////////////////////////////
26284
26285 layout() {
26286 var _vDomTop = this.table.rowManager.renderer.vDomTop,
26287 _vDomBottom = this.table.rowManager.renderer.vDomBottom,
26288 _vDomLeft = this.table.columnManager.renderer.leftCol,
26289 _vDomRight = this.table.columnManager.renderer.rightCol,
26290 top, bottom, left, right, topLeftCell, bottomRightCell, topLeftCellEl, bottomRightCellEl, topLeftRowEl, bottomRightRowEl;
26291
26292 if(this.table.options.renderHorizontal === "virtual" && this.rangeManager.rowHeader) {
26293 _vDomRight += 1;
26294 }
26295
26296 if (_vDomTop == null) {
26297 _vDomTop = 0;
26298 }
26299
26300 if (_vDomBottom == null) {
26301 _vDomBottom = Infinity;
26302 }
26303
26304 if (_vDomLeft == null) {
26305 _vDomLeft = 0;
26306 }
26307
26308 if (_vDomRight == null) {
26309 _vDomRight = Infinity;
26310 }
26311
26312 if (this.overlaps(_vDomLeft, _vDomTop, _vDomRight, _vDomBottom)) {
26313 top = Math.max(this.top, _vDomTop);
26314 bottom = Math.min(this.bottom, _vDomBottom);
26315 left = Math.max(this.left, _vDomLeft);
26316 right = Math.min(this.right, _vDomRight);
26317
26318 topLeftCell = this.rangeManager.getCell(top, left);
26319 bottomRightCell = this.rangeManager.getCell(bottom, right);
26320 topLeftCellEl = topLeftCell.getElement();
26321 bottomRightCellEl = bottomRightCell.getElement();
26322 topLeftRowEl = topLeftCell.row.getElement();
26323 bottomRightRowEl = bottomRightCell.row.getElement();
26324
26325 this.element.classList.add("tabulator-range-active");
26326 // this.element.classList.toggle("tabulator-range-active", this === this.rangeManager.activeRange);
26327
26328 if(this.table.rtl){
26329 this.element.style.right = topLeftRowEl.offsetWidth - topLeftCellEl.offsetLeft - topLeftCellEl.offsetWidth + "px";
26330 this.element.style.width = topLeftCellEl.offsetLeft + topLeftCellEl.offsetWidth - bottomRightCellEl.offsetLeft + "px";
26331 }else {
26332 this.element.style.left = topLeftRowEl.offsetLeft + topLeftCellEl.offsetLeft + "px";
26333 this.element.style.width = bottomRightCellEl.offsetLeft + bottomRightCellEl.offsetWidth - topLeftCellEl.offsetLeft + "px";
26334 }
26335
26336 this.element.style.top = topLeftRowEl.offsetTop + "px";
26337 this.element.style.height = bottomRightRowEl.offsetTop + bottomRightRowEl.offsetHeight - topLeftRowEl.offsetTop + "px";
26338 }
26339 }
26340
26341 atTopLeft(cell) {
26342 return cell.row.position - 1 === this.top && cell.column.getPosition() - 1 === this.left;
26343 }
26344
26345 atBottomRight(cell) {
26346 return cell.row.position - 1 === this.bottom && cell.column.getPosition() - 1 === this.right;
26347 }
26348
26349 occupies(cell) {
26350 return this.occupiesRow(cell.row) && this.occupiesColumn(cell.column);
26351 }
26352
26353 occupiesRow(row) {
26354 return this.top <= row.position - 1 && row.position - 1 <= this.bottom;
26355 }
26356
26357 occupiesColumn(col) {
26358 return this.left <= col.getPosition() - 1 && col.getPosition() - 1 <= this.right;
26359 }
26360
26361 overlaps(left, top, right, bottom) {
26362 if ((this.left > right || left > this.right) || (this.top > bottom || top > this.bottom)){
26363 return false;
26364 }
26365
26366 return true;
26367 }
26368
26369 getData() {
26370 var data = [],
26371 rows = this.getRows(),
26372 columns = this.getColumns();
26373
26374 rows.forEach((row) => {
26375 var rowData = row.getData(),
26376 result = {};
26377
26378 columns.forEach((column) => {
26379 result[column.field] = rowData[column.field];
26380 });
26381
26382 data.push(result);
26383 });
26384
26385 return data;
26386 }
26387
26388 getCells(structured, component) {
26389 var cells = [],
26390 rows = this.getRows(),
26391 columns = this.getColumns();
26392
26393 if (structured) {
26394 cells = rows.map((row) => {
26395 var arr = [];
26396
26397 row.getCells().forEach((cell) => {
26398 if (columns.includes(cell.column)) {
26399 arr.push(component ? cell.getComponent() : cell);
26400 }
26401 });
26402
26403 return arr;
26404 });
26405 } else {
26406 rows.forEach((row) => {
26407 row.getCells().forEach((cell) => {
26408 if (columns.includes(cell.column)) {
26409 cells.push(component ? cell.getComponent() : cell);
26410 }
26411 });
26412 });
26413 }
26414
26415 return cells;
26416 }
26417
26418 getStructuredCells() {
26419 return this.getCells(true, true);
26420 }
26421
26422 getRows() {
26423 return this._getTableRows().slice(this.top, this.bottom + 1);
26424 }
26425
26426 getColumns() {
26427 return this._getTableColumns().slice(this.left, this.right + 1);
26428 }
26429
26430 clearValues(){
26431 var cells = this.getCells();
26432 var clearValue = this.table.options.selectableRangeClearCellsValue;
26433
26434 this.table.blockRedraw();
26435
26436 cells.forEach((cell) => {
26437 cell.setValue(clearValue);
26438 });
26439
26440 this.table.restoreRedraw();
26441
26442 }
26443
26444 getBounds(component){
26445 var cells = this.getCells(false, component),
26446 output = {
26447 start:null,
26448 end:null,
26449 };
26450
26451 if(cells.length){
26452 output.start = cells[0];
26453 output.end = cells[cells.length - 1];
26454 }else {
26455 console.warn("No bounds defined on range");
26456 }
26457
26458 return output;
26459 }
26460
26461 getComponent() {
26462 if (!this.component) {
26463 this.component = new RangeComponent(this);
26464 }
26465 return this.component;
26466 }
26467
26468 destroy(notify) {
26469 this.destroyed = true;
26470
26471 this.element.remove();
26472
26473 if(notify){
26474 this.rangeManager.rangeRemoved(this);
26475 }
26476
26477 if(this.initialized){
26478 this.dispatchExternal("rangeRemoved", this.getComponent());
26479 }
26480 }
26481
26482 destroyedGuard(func){
26483 if(this.destroyed){
26484 console.warn("You cannot call the " + func + " function on a destroyed range");
26485 }
26486
26487 return !this.destroyed;
26488 }
26489 }
26490
26491 var bindings = {
26492 rangeJumpUp:["ctrl + 38", "meta + 38"],
26493 rangeJumpDown:["ctrl + 40", "meta + 40"],
26494 rangeJumpLeft:["ctrl + 37", "meta + 37"],
26495 rangeJumpRight:["ctrl + 39", "meta + 39"],
26496 rangeExpandUp:"shift + 38",
26497 rangeExpandDown:"shift + 40",
26498 rangeExpandLeft:"shift + 37",
26499 rangeExpandRight:"shift + 39",
26500 rangeExpandJumpUp:["ctrl + shift + 38", "meta + shift + 38"],
26501 rangeExpandJumpDown:["ctrl + shift + 40", "meta + shift + 40"],
26502 rangeExpandJumpLeft:["ctrl + shift + 37", "meta + shift + 37"],
26503 rangeExpandJumpRight:["ctrl + shift + 39", "meta + shift + 39"],
26504 };
26505
26506 var actions = {
26507 rangeJumpLeft: function(e){
26508 this.dispatch("keybinding-nav-range", e, "left", true, false);
26509 },
26510 rangeJumpRight: function(e){
26511 this.dispatch("keybinding-nav-range", e, "right", true, false);
26512 },
26513 rangeJumpUp: function(e){
26514 this.dispatch("keybinding-nav-range", e, "up", true, false);
26515 },
26516 rangeJumpDown: function(e){
26517 this.dispatch("keybinding-nav-range", e, "down", true, false);
26518 },
26519 rangeExpandLeft: function(e){
26520 this.dispatch("keybinding-nav-range", e, "left", false, true);
26521 },
26522 rangeExpandRight: function(e){
26523 this.dispatch("keybinding-nav-range", e, "right", false, true);
26524 },
26525 rangeExpandUp: function(e){
26526 this.dispatch("keybinding-nav-range", e, "up", false, true);
26527 },
26528 rangeExpandDown: function(e){
26529 this.dispatch("keybinding-nav-range", e, "down", false, true);
26530 },
26531 rangeExpandJumpLeft: function(e){
26532 this.dispatch("keybinding-nav-range", e, "left", true, true);
26533 },
26534 rangeExpandJumpRight: function(e){
26535 this.dispatch("keybinding-nav-range", e, "right", true, true);
26536 },
26537 rangeExpandJumpUp: function(e){
26538 this.dispatch("keybinding-nav-range", e, "up", true, true);
26539 },
26540 rangeExpandJumpDown: function(e){
26541 this.dispatch("keybinding-nav-range", e, "down", true, true);
26542 },
26543 };
26544
26545 var pasteActions = {
26546 range:function(data){
26547 var rows = [],
26548 range = this.table.modules.selectRange.activeRange,
26549 singleCell = false,
26550 bounds, startCell, startRow, rowWidth, dataLength;
26551
26552 dataLength = data.length;
26553
26554 if(range){
26555 bounds = range.getBounds();
26556 startCell = bounds.start;
26557
26558 if(bounds.start === bounds.end){
26559 singleCell = true;
26560 }
26561
26562 if(startCell){
26563 rows = this.table.rowManager.activeRows.slice();
26564 startRow = rows.indexOf(startCell.row);
26565
26566 if(singleCell){
26567 rowWidth = data.length;
26568 }else {
26569 rowWidth = (rows.indexOf(bounds.end.row) - startRow) + 1;
26570 }
26571
26572
26573 if(startRow >-1){
26574 this.table.blockRedraw();
26575
26576 rows = rows.slice(startRow, startRow + rowWidth);
26577
26578 rows.forEach((row, i) => {
26579 row.updateData(data[i % dataLength]);
26580 });
26581
26582 this.table.restoreRedraw();
26583 }
26584 }
26585 }
26586
26587 return rows;
26588 }
26589 };
26590
26591 var pasteParsers = {
26592 range:function(clipboard){
26593 var data = [],
26594 rows = [],
26595 range = this.table.modules.selectRange.activeRange,
26596 singleCell = false,
26597 bounds, startCell, colWidth, columnMap, startCol;
26598
26599 if(range){
26600 bounds = range.getBounds();
26601 startCell = bounds.start;
26602
26603 if(bounds.start === bounds.end){
26604 singleCell = true;
26605 }
26606
26607 if(startCell){
26608 //get data from clipboard into array of columns and rows.
26609 clipboard = clipboard.split("\n");
26610
26611 clipboard.forEach(function(row){
26612 data.push(row.split("\t"));
26613 });
26614
26615 if(data.length){
26616 columnMap = this.table.columnManager.getVisibleColumnsByIndex();
26617 startCol = columnMap.indexOf(startCell.column);
26618
26619 if(startCol > -1){
26620 if(singleCell){
26621 colWidth = data[0].length;
26622 }else {
26623 colWidth = (columnMap.indexOf(bounds.end.column) - startCol) + 1;
26624 }
26625
26626 columnMap = columnMap.slice(startCol, startCol + colWidth);
26627
26628 data.forEach((item) => {
26629 var row = {};
26630 var itemLength = item.length;
26631
26632 columnMap.forEach(function(col, i){
26633 row[col.field] = item[i % itemLength];
26634 });
26635
26636 rows.push(row);
26637 });
26638
26639 return rows;
26640 }
26641 }
26642 }
26643 }
26644
26645 return false;
26646 }
26647 };
26648
26649 var columnLookups = {
26650 range:function(){
26651 var columns = this.modules.selectRange.selectedColumns();
26652
26653 if(this.columnManager.rowHeader){
26654 columns.unshift(this.columnManager.rowHeader);
26655 }
26656
26657 return columns;
26658 },
26659 };
26660
26661 var rowLookups = {
26662 range:function(){
26663 return this.modules.selectRange.selectedRows();
26664 },
26665 };
26666
26667 var extensions = {
26668 keybindings:{
26669 bindings:bindings,
26670 actions:actions
26671 },
26672 clipboard:{
26673 pasteActions:pasteActions,
26674 pasteParsers:pasteParsers
26675 },
26676 export:{
26677 columnLookups:columnLookups,
26678 rowLookups:rowLookups,
26679 }
26680 };
26681
26682 class SelectRange extends Module {
26683
26684 static moduleName = "selectRange";
26685 static moduleInitOrder = 1;
26686 static moduleExtensions = extensions;
26687
26688 constructor(table) {
26689 super(table);
26690
26691 this.selecting = "cell";
26692 this.mousedown = false;
26693 this.ranges = [];
26694 this.overlay = null;
26695 this.rowHeader = null;
26696 this.layoutChangeTimeout = null;
26697 this.columnSelection = false;
26698 this.rowSelection = false;
26699 this.maxRanges = 0;
26700 this.activeRange = false;
26701 this.blockKeydown = false;
26702
26703 this.keyDownEvent = this._handleKeyDown.bind(this);
26704 this.mouseUpEvent = this._handleMouseUp.bind(this);
26705
26706 this.registerTableOption("selectableRange", false); //enable selectable range
26707 this.registerTableOption("selectableRangeColumns", false); //enable selectable range
26708 this.registerTableOption("selectableRangeRows", false); //enable selectable range
26709 this.registerTableOption("selectableRangeClearCells", false); //allow clearing of active range
26710 this.registerTableOption("selectableRangeClearCellsValue", undefined); //value for cleared active range
26711 this.registerTableOption("selectableRangeAutoFocus", true); //focus on a cell after resetRanges
26712 this.registerTableOption("selectableRangeBlurEditOnNavigate", undefined); //prevent editing on navigation
26713
26714 this.registerTableFunction("getRangesData", this.getRangesData.bind(this));
26715 this.registerTableFunction("getRanges", this.getRanges.bind(this));
26716 this.registerTableFunction("addRange", this.addRangeFromComponent.bind(this));
26717
26718 this.registerComponentFunction("cell", "getRanges", this.cellGetRanges.bind(this));
26719 this.registerComponentFunction("row", "getRanges", this.rowGetRanges.bind(this));
26720 this.registerComponentFunction("column", "getRanges", this.colGetRanges.bind(this));
26721 }
26722
26723 ///////////////////////////////////
26724 /////// Initialization ///////
26725 ///////////////////////////////////
26726
26727 initialize() {
26728 if (this.options("selectableRange")) {
26729 if(!this.options("selectableRows")){
26730 this.maxRanges = this.options("selectableRange");
26731
26732 this.initializeTable();
26733 this.initializeWatchers();
26734 }else {
26735 console.warn("SelectRange functionality cannot be used in conjunction with row selection");
26736 }
26737
26738 if(this.options('columns').findIndex((column) => column.frozen) > 0) {
26739 console.warn("Having frozen column in arbitrary position with selectRange option may result in unpredictable behavior.");
26740 }
26741
26742 if(this.options('columns').filter((column) => column.frozen) > 1) {
26743 console.warn("Having multiple frozen columns with selectRange option may result in unpredictable behavior.");
26744 }
26745 }
26746
26747 this.subscribe("edit-nav-disabled", () => {
26748 return true; // Disable navigation in edit module
26749 });
26750 }
26751
26752
26753 initializeTable() {
26754 this.overlay = document.createElement("div");
26755 this.overlay.classList.add("tabulator-range-overlay");
26756
26757 this.rangeContainer = document.createElement("div");
26758 this.rangeContainer.classList.add("tabulator-range-container");
26759
26760 this.activeRangeCellElement = document.createElement("div");
26761 this.activeRangeCellElement.classList.add("tabulator-range-cell-active");
26762
26763 this.overlay.appendChild(this.rangeContainer);
26764 this.overlay.appendChild(this.activeRangeCellElement);
26765
26766 this.table.rowManager.element.addEventListener("keydown", this.keyDownEvent);
26767
26768 this.resetRanges();
26769
26770 this.table.rowManager.element.appendChild(this.overlay);
26771 this.table.columnManager.element.setAttribute("tabindex", 0);
26772 this.table.element.classList.add("tabulator-ranges");
26773 }
26774
26775 initializeWatchers() {
26776 this.columnSelection = this.options("selectableRangeColumns");
26777 this.rowSelection = this.options("selectableRangeRows");
26778
26779 this.subscribe("column-init", this.initializeColumn.bind(this));
26780 this.subscribe("column-mousedown", this.handleColumnMouseDown.bind(this));
26781 this.subscribe("column-mousemove", this.handleColumnMouseMove.bind(this));
26782 this.subscribe("column-resized", this.handleColumnResized.bind(this));
26783 this.subscribe("column-moving", this.handleColumnMoving.bind(this));
26784 this.subscribe("column-moved", this.handleColumnMoved.bind(this));
26785 this.subscribe("column-width", this.layoutChange.bind(this));
26786 this.subscribe("column-height", this.layoutChange.bind(this));
26787 this.subscribe("column-resized", this.layoutChange.bind(this));
26788 this.subscribe("columns-loaded", this.updateHeaderColumn.bind(this));
26789
26790 this.subscribe("cell-height", this.layoutChange.bind(this));
26791 this.subscribe("cell-rendered", this.renderCell.bind(this));
26792 this.subscribe("cell-mousedown", this.handleCellMouseDown.bind(this));
26793 this.subscribe("cell-mousemove", this.handleCellMouseMove.bind(this));
26794 this.subscribe("cell-click", this.handleCellClick.bind(this));
26795 this.subscribe("cell-editing", this.handleEditingCell.bind(this));
26796
26797 this.subscribe("page-changed", this.redraw.bind(this));
26798
26799 this.subscribe("scroll-vertical", this.layoutChange.bind(this));
26800 this.subscribe("scroll-horizontal", this.layoutChange.bind(this));
26801
26802 this.subscribe("data-destroy", this.tableDestroyed.bind(this));
26803 this.subscribe("data-processed", this.resetRanges.bind(this));
26804
26805 this.subscribe("table-layout", this.layoutElement.bind(this));
26806 this.subscribe("table-redraw", this.redraw.bind(this));
26807 this.subscribe("table-destroy", this.tableDestroyed.bind(this));
26808
26809 this.subscribe("edit-editor-clear", this.finishEditingCell.bind(this));
26810 this.subscribe("edit-blur", this.restoreFocus.bind(this));
26811
26812 this.subscribe("keybinding-nav-prev", this.keyNavigate.bind(this, "prev"));
26813 this.subscribe("keybinding-nav-next", this.keyNavigate.bind(this, "next"));
26814 this.subscribe("keybinding-nav-left", this.keyNavigate.bind(this, "left"));
26815 this.subscribe("keybinding-nav-right", this.keyNavigate.bind(this, "right"));
26816 this.subscribe("keybinding-nav-up", this.keyNavigate.bind(this, "up"));
26817 this.subscribe("keybinding-nav-down", this.keyNavigate.bind(this, "down"));
26818 this.subscribe("keybinding-nav-range", this.keyNavigateRange.bind(this));
26819 }
26820
26821
26822 initializeColumn(column) {
26823 if(this.columnSelection && column.definition.headerSort && this.options("headerSortClickElement") !== "icon"){
26824 console.warn("Using column headerSort with selectableRangeColumns option may result in unpredictable behavior. Consider using headerSortClickElement: 'icon'.");
26825 }
26826 }
26827
26828 updateHeaderColumn(){
26829 var frozenCols;
26830
26831 if(this.rowSelection){
26832 this.rowHeader = this.table.columnManager.getVisibleColumnsByIndex()[0];
26833
26834 if(this.rowHeader){
26835 this.rowHeader.definition.cssClass = this.rowHeader.definition.cssClass + " tabulator-range-row-header";
26836
26837 if(this.rowHeader.definition.headerSort){
26838 console.warn("Using column headerSort with selectableRangeRows option may result in unpredictable behavior");
26839 }
26840
26841 if(this.rowHeader.definition.editor){
26842 console.warn("Using column editor with selectableRangeRows option may result in unpredictable behavior");
26843 }
26844 }
26845 }
26846
26847 //warn if invalid frozen column configuration detected
26848 if(this.table.modules.frozenColumns && this.table.modules.frozenColumns.active){
26849 frozenCols = this.table.modules.frozenColumns.getFrozenColumns();
26850
26851 if(frozenCols.length > 1 || (frozenCols.length === 1 && frozenCols[0] !== this.rowHeader)){
26852 console.warn("Using frozen columns that are not the range header in combination with the selectRange option may result in unpredictable behavior");
26853 }
26854 }
26855 }
26856
26857 ///////////////////////////////////
26858 /////// Table Functions ///////
26859 ///////////////////////////////////
26860
26861 getRanges(){
26862 return this.ranges.map((range) => range.getComponent());
26863 }
26864
26865 getRangesData() {
26866 return this.ranges.map((range) => range.getData());
26867 }
26868
26869 addRangeFromComponent(start, end){
26870 start = start ? start._cell : null;
26871 end = end ? end._cell : null;
26872
26873 return this.addRange(start, end);
26874 }
26875
26876 ///////////////////////////////////
26877 /////// Component Functions ///////
26878 ///////////////////////////////////
26879
26880 cellGetRanges(cell){
26881 var ranges = [];
26882
26883 if (cell.column === this.rowHeader) {
26884 ranges = this.ranges.filter((range) => range.occupiesRow(cell.row));
26885 } else {
26886 ranges = this.ranges.filter((range) => range.occupies(cell));
26887 }
26888
26889 return ranges.map((range) => range.getComponent());
26890 }
26891
26892 rowGetRanges(row){
26893 var ranges = this.ranges.filter((range) => range.occupiesRow(row));
26894
26895 return ranges.map((range) => range.getComponent());
26896 }
26897
26898 colGetRanges(col){
26899 var ranges = this.ranges.filter((range) => range.occupiesColumn(col));
26900
26901 return ranges.map((range) => range.getComponent());
26902 }
26903
26904 ///////////////////////////////////
26905 ////////// Event Handlers /////////
26906 ///////////////////////////////////
26907
26908 _handleMouseUp(e){
26909 this.mousedown = false;
26910 document.removeEventListener("mouseup", this.mouseUpEvent);
26911 }
26912
26913 _handleKeyDown(e) {
26914 if (!this.blockKeydown && (!this.table.modules.edit || (this.table.modules.edit && !this.table.modules.edit.currentCell))) {
26915 if (e.key === "Enter") {
26916 // is editing a cell?
26917 if (this.table.modules.edit && this.table.modules.edit.currentCell) {
26918 return;
26919 }
26920
26921 this.table.modules.edit.editCell(this.getActiveCell());
26922
26923 e.preventDefault();
26924 }
26925
26926 if ((e.key === "Backspace" || e.key === "Delete") && this.options("selectableRangeClearCells")) {
26927 if(this.activeRange){
26928 this.activeRange.clearValues();
26929 }
26930 }
26931 }
26932 }
26933
26934 initializeFocus(cell){
26935 var range;
26936
26937 this.restoreFocus();
26938
26939 try{
26940 if (document.selection) { // IE
26941 range = document.body.createTextRange();
26942 range.moveToElementText(cell.getElement());
26943 range.select();
26944 } else if (window.getSelection) {
26945 range = document.createRange();
26946 range.selectNode(cell.getElement());
26947 window.getSelection().removeAllRanges();
26948 window.getSelection().addRange(range);
26949 }
26950 }catch(e){}
26951 }
26952
26953 restoreFocus(element){
26954 this.table.rowManager.element.focus();
26955
26956 return true;
26957 }
26958
26959 ///////////////////////////////////
26960 ////// Column Functionality ///////
26961 ///////////////////////////////////
26962
26963 handleColumnResized(column) {
26964 var selected;
26965
26966 if (this.selecting !== "column" && this.selecting !== "all") {
26967 return;
26968 }
26969
26970 selected = this.ranges.some((range) => range.occupiesColumn(column));
26971
26972 if (!selected) {
26973 return;
26974 }
26975
26976 this.ranges.forEach((range) => {
26977 var selectedColumns = range.getColumns(true);
26978
26979 selectedColumns.forEach((selectedColumn) => {
26980 if (selectedColumn !== column) {
26981 selectedColumn.setWidth(column.width);
26982 }
26983 });
26984 });
26985 }
26986
26987 handleColumnMoving(_event, column) {
26988 this.resetRanges().setBounds(column);
26989 this.overlay.style.visibility = "hidden";
26990 }
26991
26992 handleColumnMoved(from, _to, _after) {
26993 this.activeRange.setBounds(from);
26994 this.layoutElement();
26995 }
26996
26997 handleColumnMouseDown(event, column) {
26998 if (event.button === 2 && (this.selecting === "column" || this.selecting === "all") && this.activeRange.occupiesColumn(column)) {
26999 return;
27000 }
27001
27002 //If columns are movable, allow dragging columns only if they are not
27003 //selected. Dragging selected columns should move the columns instead.
27004 if(this.table.options.movableColumns && this.selecting === "column" && this.activeRange.occupiesColumn(column)){
27005 return;
27006 }
27007
27008 this.mousedown = true;
27009
27010 document.addEventListener("mouseup", this.mouseUpEvent);
27011
27012 this.newSelection(event, column);
27013 }
27014
27015 handleColumnMouseMove(e, column) {
27016 if (column === this.rowHeader || !this.mousedown || this.selecting === 'all') {
27017 return;
27018 }
27019
27020 this.activeRange.setBounds(false, column, true);
27021 }
27022
27023 ///////////////////////////////////
27024 //////// Cell Functionality ///////
27025 ///////////////////////////////////
27026
27027 renderCell(cell) {
27028 var el = cell.getElement(),
27029 rangeIdx = this.ranges.findIndex((range) => range.occupies(cell));
27030
27031 el.classList.toggle("tabulator-range-selected", rangeIdx !== -1);
27032 el.classList.toggle("tabulator-range-only-cell-selected", this.ranges.length === 1 && this.ranges[0].atTopLeft(cell) && this.ranges[0].atBottomRight(cell));
27033
27034 el.dataset.range = rangeIdx;
27035 }
27036
27037 handleCellMouseDown(event, cell) {
27038 if (event.button === 2 && (this.activeRange.occupies(cell) || ((this.selecting === "row" || this.selecting === "all") && this.activeRange.occupiesRow(cell.row)))) {
27039 return;
27040 }
27041
27042 this.mousedown = true;
27043
27044 document.addEventListener("mouseup", this.mouseUpEvent);
27045
27046 this.newSelection(event, cell);
27047 }
27048
27049 handleCellMouseMove(e, cell) {
27050 if (!this.mousedown || this.selecting === "all") {
27051 return;
27052 }
27053
27054 this.activeRange.setBounds(false, cell, true);
27055 }
27056
27057 handleCellClick(e, cell){
27058 this.initializeFocus(cell);
27059 }
27060
27061 handleEditingCell(cell) {
27062 if(this.activeRange){
27063 this.activeRange.setBounds(cell);
27064 }
27065 }
27066
27067 finishEditingCell() {
27068 this.blockKeydown = true;
27069 this.table.rowManager.element.focus();
27070
27071 setTimeout(() => {
27072 this.blockKeydown = false;
27073 }, 10);
27074 }
27075
27076 ///////////////////////////////////
27077 /////// Navigation ///////
27078 ///////////////////////////////////
27079
27080 keyNavigate(dir, e){
27081 if(this.options("selectableRangeBlurEditOnNavigate")){
27082 const isEditing = this.chain("edit-check-editing");
27083
27084 if(isEditing){
27085 if(dir === 'next' || dir === 'prev'){
27086 this.dispatch("edit-cancel-cell");
27087 }else {
27088 // Prevent navigating while editing except for next/prev
27089 return false;
27090 }
27091 }
27092 }
27093
27094 if (dir === 'prev') {
27095 dir = 'left';
27096 } else if (dir === 'next') {
27097 dir = 'right';
27098 }
27099
27100 if(this.navigate(false, false, dir)){
27101 e.preventDefault();
27102 }
27103 }
27104
27105 keyNavigateRange(e, dir, jump, expand){
27106 if(this.navigate(jump, expand, dir)){
27107 e.preventDefault();
27108 }
27109 }
27110
27111 navigate(jump, expand, dir) {
27112 var moved = false,
27113 range, rangeEdge, prevRect, nextRow, nextCol, row, column,
27114 rowRect, rowManagerRect, columnRect, columnManagerRect;
27115
27116 // Don't navigate while editing
27117 if (this.table.modules.edit && this.table.modules.edit.currentCell) {
27118 return false;
27119 }
27120
27121 // If there are more than 1 range, use the active range and destroy the others
27122 if (this.ranges.length > 1) {
27123 this.ranges = this.ranges.filter((range) => {
27124 if (range === this.activeRange) {
27125 range.setEnd(range.start.row, range.start.col);
27126 return true;
27127 }
27128 range.destroy();
27129 return false;
27130 });
27131 }
27132
27133 range = this.activeRange;
27134 prevRect = {
27135 top: range.top,
27136 bottom: range.bottom,
27137 left: range.left,
27138 right: range.right
27139 };
27140
27141 rangeEdge = expand ? range.end : range.start;
27142 nextRow = rangeEdge.row;
27143 nextCol = rangeEdge.col;
27144
27145 if(jump){
27146 switch(dir){
27147 case "left":
27148 nextCol = this.findJumpCellLeft(range.start.row, rangeEdge.col);
27149 break;
27150 case "right":
27151 nextCol = this.findJumpCellRight(range.start.row, rangeEdge.col);
27152 break;
27153 case "up":
27154 nextRow = this.findJumpCellUp(rangeEdge.row, range.start.col);
27155 break;
27156 case "down":
27157 nextRow = this.findJumpCellDown(rangeEdge.row, range.start.col);
27158 break;
27159 }
27160 }else {
27161 if(expand){
27162 if ((this.selecting === 'row' && (dir === 'left' || dir === 'right')) || (this.selecting === 'column' && (dir === 'up' || dir === 'down'))) {
27163 return;
27164 }
27165 }
27166
27167 switch(dir){
27168 case "left":
27169 nextCol = Math.max(nextCol - 1, 0);
27170 break;
27171 case "right":
27172 nextCol = Math.min(nextCol + 1, this.getTableColumns().length - 1);
27173 break;
27174 case "up":
27175 nextRow = Math.max(nextRow - 1, 0);
27176 break;
27177 case "down":
27178 nextRow = Math.min(nextRow + 1, this.getTableRows().length - 1);
27179 break;
27180 }
27181 }
27182
27183 if(this.rowHeader && nextCol === 0) {
27184 nextCol = 1;
27185 }
27186
27187 if(!expand){
27188 range.setStart(nextRow, nextCol);
27189 }
27190
27191 range.setEnd(nextRow, nextCol);
27192
27193 if(!expand){
27194 this.selecting = "cell";
27195 }
27196
27197 moved = prevRect.top !== range.top || prevRect.bottom !== range.bottom || prevRect.left !== range.left || prevRect.right !== range.right;
27198
27199 if (moved) {
27200 row = this.getRowByRangePos(range.end.row);
27201 column = this.getColumnByRangePos(range.end.col);
27202 rowRect = row.getElement().getBoundingClientRect();
27203 columnRect = column.getElement().getBoundingClientRect();
27204 rowManagerRect = this.table.rowManager.getElement().getBoundingClientRect();
27205 columnManagerRect = this.table.columnManager.getElement().getBoundingClientRect();
27206
27207 if(!(rowRect.top >= rowManagerRect.top && rowRect.bottom <= rowManagerRect.bottom)){
27208 if(row.getElement().parentNode && column.getElement().parentNode){
27209 // Use faster autoScroll when the elements are on the DOM
27210 this.autoScroll(range, row.getElement(), column.getElement());
27211 }else {
27212 row.getComponent().scrollTo(undefined, false);
27213 }
27214 }
27215
27216 if(!(columnRect.left >= columnManagerRect.left + this.getRowHeaderWidth() && columnRect.right <= columnManagerRect.right)){
27217 if(row.getElement().parentNode && column.getElement().parentNode){
27218 // Use faster autoScroll when the elements are on the DOM
27219 this.autoScroll(range, row.getElement(), column.getElement());
27220 }else {
27221 column.getComponent().scrollTo(undefined, false);
27222 }
27223 }
27224
27225 this.layoutElement();
27226 }
27227 return true;
27228 }
27229
27230 rangeRemoved(removed){
27231 this.ranges = this.ranges.filter((range) => range !== removed);
27232
27233 if(this.activeRange === removed){
27234 if(this.ranges.length){
27235 this.activeRange = this.ranges[this.ranges.length - 1];
27236 }else {
27237 this.addRange();
27238 }
27239 }
27240
27241 this.layoutElement(true);
27242 }
27243
27244 findJumpRow(column, rows, reverse, emptyStart, emptySide){
27245 if(reverse){
27246 rows = rows.reverse();
27247 }
27248
27249 return this.findJumpItem(emptyStart, emptySide, rows, function(row){return row.getData()[column.getField()];});
27250 }
27251
27252 findJumpCol(row, columns, reverse, emptyStart, emptySide){
27253 if(reverse){
27254 columns = columns.reverse();
27255 }
27256
27257 return this.findJumpItem(emptyStart, emptySide, columns, function(column){return row.getData()[column.getField()];});
27258 }
27259
27260 findJumpItem(emptyStart, emptySide, items, valueResolver){
27261 var nextItem;
27262
27263 for(let currentItem of items){
27264 let currentValue = valueResolver(currentItem);
27265
27266 if(emptyStart){
27267 nextItem = currentItem;
27268 if(currentValue){
27269 break;
27270 }
27271 }else {
27272 if(emptySide){
27273 nextItem = currentItem;
27274
27275 if(currentValue){
27276 break;
27277 }
27278 }else {
27279 if(currentValue){
27280 nextItem = currentItem;
27281 }else {
27282 break;
27283 }
27284 }
27285 }
27286 }
27287
27288 return nextItem;
27289 }
27290
27291 findJumpCellLeft(rowPos, colPos){
27292 var row = this.getRowByRangePos(rowPos),
27293 columns = this.getTableColumns(),
27294 isStartingCellEmpty = this.isEmpty(row.getData()[columns[colPos].getField()]),
27295 isLeftOfStartingCellEmpty = columns[colPos - 1] ? this.isEmpty(row.getData()[columns[colPos - 1].getField()]) : false,
27296 targetCols = this.rowHeader ? columns.slice(1, colPos) : columns.slice(0, colPos),
27297 jumpCol = this.findJumpCol(row, targetCols, true, isStartingCellEmpty, isLeftOfStartingCellEmpty);
27298
27299 if(jumpCol){
27300 return jumpCol.getPosition() - 1;
27301 }
27302
27303 return colPos;
27304 }
27305
27306 findJumpCellRight(rowPos, colPos){
27307 var row = this.getRowByRangePos(rowPos),
27308 columns = this.getTableColumns(),
27309 isStartingCellEmpty = this.isEmpty(row.getData()[columns[colPos].getField()]),
27310 isRightOfStartingCellEmpty = columns[colPos + 1] ? this.isEmpty(row.getData()[columns[colPos + 1].getField()]) : false,
27311 jumpCol = this.findJumpCol(row, columns.slice(colPos + 1, columns.length), false, isStartingCellEmpty, isRightOfStartingCellEmpty);
27312
27313 if(jumpCol){
27314 return jumpCol.getPosition() - 1;
27315 }
27316
27317 return colPos;
27318 }
27319
27320 findJumpCellUp(rowPos, colPos) {
27321 var column = this.getColumnByRangePos(colPos),
27322 rows = this.getTableRows(),
27323 isStartingCellEmpty = this.isEmpty(rows[rowPos].getData()[column.getField()]),
27324 isTopOfStartingCellEmpty = rows[rowPos - 1] ? this.isEmpty(rows[rowPos - 1].getData()[column.getField()]) : false,
27325 jumpRow = this.findJumpRow(column, rows.slice(0, rowPos), true, isStartingCellEmpty, isTopOfStartingCellEmpty);
27326
27327 if(jumpRow){
27328 return jumpRow.position - 1;
27329 }
27330
27331 return rowPos;
27332 }
27333
27334 findJumpCellDown(rowPos, colPos) {
27335 var column = this.getColumnByRangePos(colPos),
27336 rows = this.getTableRows(),
27337 isStartingCellEmpty = this.isEmpty(rows[rowPos].getData()[column.getField()]),
27338 isBottomOfStartingCellEmpty = rows[rowPos + 1] ? this.isEmpty(rows[rowPos + 1].getData()[column.getField()]) : false,
27339 jumpRow = this.findJumpRow(column, rows.slice(rowPos + 1, rows.length), false, isStartingCellEmpty, isBottomOfStartingCellEmpty);
27340
27341 if(jumpRow){
27342 return jumpRow.position - 1;
27343 }
27344
27345 return rowPos;
27346 }
27347
27348 ///////////////////////////////////
27349 /////// Selection ///////
27350 ///////////////////////////////////
27351 newSelection(event, element) {
27352 var range;
27353
27354 if (element.type === "column") {
27355 if(!this.columnSelection){
27356 return;
27357 }
27358
27359 if (element === this.rowHeader) {
27360 range = this.resetRanges();
27361 this.selecting = "all";
27362
27363 var topLeftCell, bottomRightCell = this.getCell(-1, -1);
27364
27365 if(this.rowHeader){
27366 topLeftCell = this.getCell(0, 1);
27367 }else {
27368 topLeftCell = this.getCell(0, 0);
27369 }
27370
27371 range.setBounds(topLeftCell, bottomRightCell);
27372 return;
27373 } else {
27374 this.selecting = "column";
27375 }
27376 } else if (element.column === this.rowHeader) {
27377 this.selecting = "row";
27378 } else {
27379 this.selecting = "cell";
27380 }
27381
27382 if (event.shiftKey) {
27383 this.activeRange.setBounds(false, element, true);
27384 } else if (event.ctrlKey) {
27385 this.addRange().setBounds(element, undefined, true);
27386 } else {
27387 this.resetRanges().setBounds(element, undefined, true);
27388 }
27389 }
27390
27391 autoScroll(range, row, column) {
27392 var tableHolder = this.table.rowManager.element,
27393 rect, view, withinHorizontalView, withinVerticalView;
27394
27395 if (typeof row === 'undefined') {
27396 row = this.getRowByRangePos(range.end.row).getElement();
27397 }
27398
27399 if (typeof column === 'undefined') {
27400 column = this.getColumnByRangePos(range.end.col).getElement();
27401 }
27402
27403 rect = {
27404 left: column.offsetLeft,
27405 right: column.offsetLeft + column.offsetWidth,
27406 top: row.offsetTop,
27407 bottom: row.offsetTop + row.offsetHeight,
27408 };
27409
27410 view = {
27411 left: tableHolder.scrollLeft + this.getRowHeaderWidth(),
27412 right: Math.ceil(tableHolder.scrollLeft + tableHolder.clientWidth),
27413 top: tableHolder.scrollTop,
27414 bottom: tableHolder.scrollTop + tableHolder.offsetHeight - this.table.rowManager.scrollbarWidth,
27415 };
27416
27417 withinHorizontalView = view.left < rect.left && rect.left < view.right && view.left < rect.right && rect.right < view.right;
27418
27419 withinVerticalView = view.top < rect.top && rect.top < view.bottom && view.top < rect.bottom && rect.bottom < view.bottom;
27420
27421 if (!withinHorizontalView) {
27422 if (rect.left < view.left) {
27423 tableHolder.scrollLeft = rect.left - this.getRowHeaderWidth();
27424 } else if (rect.right > view.right) {
27425 tableHolder.scrollLeft = Math.min(rect.right - tableHolder.clientWidth, rect.left - this.getRowHeaderWidth());
27426 }
27427 }
27428
27429 if (!withinVerticalView) {
27430 if (rect.top < view.top) {
27431 tableHolder.scrollTop = rect.top;
27432 } else if (rect.bottom > view.bottom) {
27433 tableHolder.scrollTop = rect.bottom - tableHolder.clientHeight;
27434 }
27435 }
27436 }
27437
27438
27439 ///////////////////////////////////
27440 /////// Layout ///////
27441 ///////////////////////////////////
27442
27443 layoutChange(){
27444 this.overlay.style.visibility = "hidden";
27445 clearTimeout(this.layoutChangeTimeout);
27446 this.layoutChangeTimeout = setTimeout(this.layoutRanges.bind(this), 200);
27447 }
27448
27449 redraw(force) {
27450 if (force) {
27451 this.selecting = 'cell';
27452 this.resetRanges();
27453 this.layoutElement();
27454 }
27455 }
27456
27457 layoutElement(visibleRows) {
27458 var rows;
27459
27460 if (visibleRows) {
27461 rows = this.table.rowManager.getVisibleRows(true);
27462 } else {
27463 rows = this.table.rowManager.getRows();
27464 }
27465
27466 rows.forEach((row) => {
27467 if (row.type === "row") {
27468 this.layoutRow(row);
27469 row.cells.forEach((cell) => this.renderCell(cell));
27470 }
27471 });
27472
27473 this.getTableColumns().forEach((column) => {
27474 this.layoutColumn(column);
27475 });
27476
27477 this.layoutRanges();
27478 }
27479
27480 layoutRow(row) {
27481 var el = row.getElement(),
27482 selected = false,
27483 occupied = this.ranges.some((range) => range.occupiesRow(row));
27484
27485 if (this.selecting === "row") {
27486 selected = occupied;
27487 } else if (this.selecting === "all") {
27488 selected = true;
27489 }
27490
27491 el.classList.toggle("tabulator-range-selected", selected);
27492 el.classList.toggle("tabulator-range-highlight", occupied);
27493 }
27494
27495 layoutColumn(column) {
27496 var el = column.getElement(),
27497 selected = false,
27498 occupied = this.ranges.some((range) => range.occupiesColumn(column));
27499
27500 if (this.selecting === "column") {
27501 selected = occupied;
27502 } else if (this.selecting === "all") {
27503 selected = true;
27504 }
27505
27506 el.classList.toggle("tabulator-range-selected", selected);
27507 el.classList.toggle("tabulator-range-highlight", occupied);
27508 }
27509
27510 layoutRanges() {
27511 var activeCell, activeCellEl, activeRowEl;
27512
27513 if (!this.table.initialized) {
27514 return;
27515 }
27516
27517 activeCell = this.getActiveCell();
27518
27519 if (!activeCell) {
27520 return;
27521 }
27522
27523 activeCellEl = activeCell.getElement();
27524 activeRowEl = activeCell.row.getElement();
27525
27526 if(this.table.rtl){
27527 this.activeRangeCellElement.style.right = activeRowEl.offsetWidth - activeCellEl.offsetLeft - activeCellEl.offsetWidth + "px";
27528 }else {
27529 this.activeRangeCellElement.style.left = activeRowEl.offsetLeft + activeCellEl.offsetLeft + "px";
27530 }
27531
27532 this.activeRangeCellElement.style.top = activeRowEl.offsetTop + "px";
27533 this.activeRangeCellElement.style.width = activeCellEl.offsetWidth + "px";
27534 this.activeRangeCellElement.style.height = activeRowEl.offsetHeight + "px";
27535
27536 this.ranges.forEach((range) => range.layout());
27537
27538 this.overlay.style.visibility = "visible";
27539 }
27540
27541
27542 ///////////////////////////////////
27543 /////// Helper Functions ///////
27544 ///////////////////////////////////
27545
27546 getCell(rowIdx, colIdx) {
27547 var row;
27548
27549 if (colIdx < 0) {
27550 colIdx = this.getTableColumns().length + colIdx;
27551 if (colIdx < 0) {
27552 return null;
27553 }
27554 }
27555
27556 if (rowIdx < 0) {
27557 rowIdx = this.getTableRows().length + rowIdx;
27558 }
27559
27560 row = this.table.rowManager.getRowFromPosition(rowIdx + 1);
27561
27562 return row ? row.getCells(false, true).filter((cell) => cell.column.visible)[colIdx] : null;
27563 }
27564
27565
27566 getActiveCell() {
27567 return this.getCell(this.activeRange.start.row, this.activeRange.start.col);
27568 }
27569
27570 getRowByRangePos(pos) {
27571 return this.getTableRows()[pos];
27572 }
27573
27574 getColumnByRangePos(pos) {
27575 return this.getTableColumns()[pos];
27576 }
27577
27578 getTableRows() {
27579 return this.table.rowManager.getDisplayRows().filter(row=> row.type === "row");
27580 }
27581
27582 getTableColumns() {
27583 return this.table.columnManager.getVisibleColumnsByIndex();
27584 }
27585
27586 addRange(start, end) {
27587 var range;
27588
27589 if(this.maxRanges !== true && this.ranges.length >= this.maxRanges){
27590 this.ranges.shift().destroy();
27591 }
27592
27593 range = new Range(this.table, this, start, end);
27594
27595 this.activeRange = range;
27596 this.ranges.push(range);
27597 this.rangeContainer.appendChild(range.element);
27598
27599 return range;
27600 }
27601
27602 resetRanges() {
27603 var range, cell, visibleCells;
27604
27605 this.ranges.forEach((range) => range.destroy());
27606 this.ranges = [];
27607
27608 range = this.addRange();
27609
27610 if(this.table.rowManager.activeRows.length){
27611 visibleCells = this.table.rowManager.activeRows[0].cells.filter((cell) => cell.column.visible);
27612 cell = visibleCells[this.rowHeader ? 1 : 0];
27613
27614 if(cell){
27615 range.setBounds(cell);
27616 if(this.options("selectableRangeAutoFocus")){
27617 this.initializeFocus(cell);
27618 }
27619 }
27620 }
27621
27622 return range;
27623 }
27624
27625 tableDestroyed(){
27626 document.removeEventListener("mouseup", this.mouseUpEvent);
27627 this.table.rowManager.element.removeEventListener("keydown", this.keyDownEvent);
27628 }
27629
27630 selectedRows(component) {
27631 return component ? this.activeRange.getRows().map((row) => row.getComponent()) : this.activeRange.getRows();
27632 }
27633
27634 selectedColumns(component) {
27635 return component ? this.activeRange.getColumns().map((col) => col.getComponent()) : this.activeRange.getColumns();
27636 }
27637
27638 getRowHeaderWidth(){
27639 if(!this.rowHeader){
27640 return 0;
27641 }
27642 return this.rowHeader.getElement().offsetWidth;
27643 }
27644
27645 isEmpty(value) {
27646 return value === null || value === undefined || value === "";
27647 }
27648 }
27649
27650 //sort numbers
27651 function number(a, b, aRow, bRow, column, dir, params){
27652 var alignEmptyValues = params.alignEmptyValues;
27653 var decimal = params.decimalSeparator;
27654 var thousand = params.thousandSeparator;
27655 var emptyAlign = 0;
27656
27657 a = String(a);
27658 b = String(b);
27659
27660 if(thousand){
27661 a = a.split(thousand).join("");
27662 b = b.split(thousand).join("");
27663 }
27664
27665 if(decimal){
27666 a = a.split(decimal).join(".");
27667 b = b.split(decimal).join(".");
27668 }
27669
27670 a = parseFloat(a);
27671 b = parseFloat(b);
27672
27673 //handle non numeric values
27674 if(isNaN(a)){
27675 emptyAlign = isNaN(b) ? 0 : -1;
27676 }else if(isNaN(b)){
27677 emptyAlign = 1;
27678 }else {
27679 //compare valid values
27680 return a - b;
27681 }
27682
27683 //fix empty values in position
27684 if((alignEmptyValues === "top" && dir === "desc") || (alignEmptyValues === "bottom" && dir === "asc")){
27685 emptyAlign *= -1;
27686 }
27687
27688 return emptyAlign;
27689 }
27690
27691 //sort strings
27692 function string(a, b, aRow, bRow, column, dir, params){
27693 var alignEmptyValues = params.alignEmptyValues;
27694 var emptyAlign = 0;
27695 var locale;
27696
27697 //handle empty values
27698 if(!a){
27699 emptyAlign = !b ? 0 : -1;
27700 }else if(!b){
27701 emptyAlign = 1;
27702 }else {
27703 //compare valid values
27704 switch(typeof params.locale){
27705 case "boolean":
27706 if(params.locale){
27707 locale = this.langLocale();
27708 }
27709 break;
27710 case "string":
27711 locale = params.locale;
27712 break;
27713 }
27714
27715 return String(a).toLowerCase().localeCompare(String(b).toLowerCase(), locale);
27716 }
27717
27718 //fix empty values in position
27719 if((alignEmptyValues === "top" && dir === "desc") || (alignEmptyValues === "bottom" && dir === "asc")){
27720 emptyAlign *= -1;
27721 }
27722
27723 return emptyAlign;
27724 }
27725
27726 //sort datetime
27727 function datetime(a, b, aRow, bRow, column, dir, params){
27728 var DT = this.table.dependencyRegistry.lookup(["luxon", "DateTime"], "DateTime");
27729 var format = params.format || "dd/MM/yyyy HH:mm:ss",
27730 alignEmptyValues = params.alignEmptyValues,
27731 emptyAlign = 0;
27732
27733 if(typeof DT != "undefined"){
27734 if(!DT.isDateTime(a)){
27735 if(format === "iso"){
27736 a = DT.fromISO(String(a));
27737 }else {
27738 a = DT.fromFormat(String(a), format);
27739 }
27740 }
27741
27742 if(!DT.isDateTime(b)){
27743 if(format === "iso"){
27744 b = DT.fromISO(String(b));
27745 }else {
27746 b = DT.fromFormat(String(b), format);
27747 }
27748 }
27749
27750 if(!a.isValid){
27751 emptyAlign = !b.isValid ? 0 : -1;
27752 }else if(!b.isValid){
27753 emptyAlign = 1;
27754 }else {
27755 //compare valid values
27756 return a - b;
27757 }
27758
27759 //fix empty values in position
27760 if((alignEmptyValues === "top" && dir === "desc") || (alignEmptyValues === "bottom" && dir === "asc")){
27761 emptyAlign *= -1;
27762 }
27763
27764 return emptyAlign;
27765
27766 }else {
27767 console.error("Sort Error - 'datetime' sorter is dependant on luxon.js");
27768 }
27769 }
27770
27771 //sort date
27772 function date(a, b, aRow, bRow, column, dir, params){
27773 if(!params.format){
27774 params.format = "dd/MM/yyyy";
27775 }
27776
27777 return datetime.call(this, a, b, aRow, bRow, column, dir, params);
27778 }
27779
27780 //sort times
27781 function time(a, b, aRow, bRow, column, dir, params){
27782 if(!params.format){
27783 params.format = "HH:mm";
27784 }
27785
27786 return datetime.call(this, a, b, aRow, bRow, column, dir, params);
27787 }
27788
27789 //sort booleans
27790 function boolean(a, b, aRow, bRow, column, dir, params){
27791 var el1 = a === true || a === "true" || a === "True" || a === 1 ? 1 : 0;
27792 var el2 = b === true || b === "true" || b === "True" || b === 1 ? 1 : 0;
27793
27794 return el1 - el2;
27795 }
27796
27797 //sort if element contains any data
27798 function array(a, b, aRow, bRow, column, dir, params){
27799 var type = params.type || "length",
27800 alignEmptyValues = params.alignEmptyValues,
27801 emptyAlign = 0,
27802 table = this.table,
27803 valueMap;
27804
27805 if(params.valueMap){
27806 if(typeof params.valueMap === "string"){
27807 valueMap = function(value){
27808 return value.map((item) => {
27809 return Helpers.retrieveNestedData(table.options.nestedFieldSeparator, params.valueMap, item);
27810 });
27811 };
27812 }else {
27813 valueMap = params.valueMap;
27814 }
27815 }
27816
27817 function calc(value){
27818 var result;
27819
27820 if(valueMap){
27821 value = valueMap(value);
27822 }
27823
27824 switch(type){
27825 case "length":
27826 result = value.length;
27827 break;
27828
27829 case "sum":
27830 result = value.reduce(function(c, d){
27831 return c + d;
27832 });
27833 break;
27834
27835 case "max":
27836 result = Math.max.apply(null, value) ;
27837 break;
27838
27839 case "min":
27840 result = Math.min.apply(null, value) ;
27841 break;
27842
27843 case "avg":
27844 result = value.reduce(function(c, d){
27845 return c + d;
27846 }) / value.length;
27847 break;
27848
27849 case "string":
27850 result = value.join("");
27851 break;
27852 }
27853
27854 return result;
27855 }
27856
27857 //handle non array values
27858 if(!Array.isArray(a)){
27859 emptyAlign = !Array.isArray(b) ? 0 : -1;
27860 }else if(!Array.isArray(b)){
27861 emptyAlign = 1;
27862 }else {
27863 if(type === "string"){
27864 return String(calc(a)).toLowerCase().localeCompare(String(calc(b)).toLowerCase());
27865 }else {
27866 return calc(b) - calc(a);
27867 }
27868 }
27869
27870 //fix empty values in position
27871 if((alignEmptyValues === "top" && dir === "desc") || (alignEmptyValues === "bottom" && dir === "asc")){
27872 emptyAlign *= -1;
27873 }
27874
27875 return emptyAlign;
27876 }
27877
27878 //sort if element contains any data
27879 function exists(a, b, aRow, bRow, column, dir, params){
27880 var el1 = typeof a == "undefined" ? 0 : 1;
27881 var el2 = typeof b == "undefined" ? 0 : 1;
27882
27883 return el1 - el2;
27884 }
27885
27886 //sort alpha numeric strings
27887 function alphanum(as, bs, aRow, bRow, column, dir, params){
27888 var a, b, a1, b1, i= 0, L, rx = /(\d+)|(\D+)/g, rd = /\d/;
27889 var alignEmptyValues = params.alignEmptyValues;
27890 var emptyAlign = 0;
27891
27892 //handle empty values
27893 if(!as && as!== 0){
27894 emptyAlign = !bs && bs!== 0 ? 0 : -1;
27895 }else if(!bs && bs!== 0){
27896 emptyAlign = 1;
27897 }else {
27898
27899 if(isFinite(as) && isFinite(bs)) return as - bs;
27900 a = String(as).toLowerCase();
27901 b = String(bs).toLowerCase();
27902 if(a === b) return 0;
27903 if(!(rd.test(a) && rd.test(b))) return a > b ? 1 : -1;
27904 a = a.match(rx);
27905 b = b.match(rx);
27906 L = a.length > b.length ? b.length : a.length;
27907 while(i < L){
27908 a1= a[i];
27909 b1= b[i++];
27910 if(a1 !== b1){
27911 if(isFinite(a1) && isFinite(b1)){
27912 if(a1.charAt(0) === "0") a1 = "." + a1;
27913 if(b1.charAt(0) === "0") b1 = "." + b1;
27914 return a1 - b1;
27915 }
27916 else return a1 > b1 ? 1 : -1;
27917 }
27918 }
27919
27920 return a.length > b.length;
27921 }
27922
27923 //fix empty values in position
27924 if((alignEmptyValues === "top" && dir === "desc") || (alignEmptyValues === "bottom" && dir === "asc")){
27925 emptyAlign *= -1;
27926 }
27927
27928 return emptyAlign;
27929 }
27930
27931 var defaultSorters = {
27932 number:number,
27933 string:string,
27934 date:date,
27935 time:time,
27936 datetime:datetime,
27937 boolean:boolean,
27938 array:array,
27939 exists:exists,
27940 alphanum:alphanum
27941 };
27942
27943 class Sort extends Module{
27944
27945 static moduleName = "sort";
27946
27947 //load defaults
27948 static sorters = defaultSorters;
27949
27950 constructor(table){
27951 super(table);
27952
27953 this.sortList = []; //holder current sort
27954 this.changed = false; //has the sort changed since last render
27955
27956 this.registerTableOption("sortMode", "local"); //local or remote sorting
27957
27958 this.registerTableOption("initialSort", false); //initial sorting criteria
27959 this.registerTableOption("columnHeaderSortMulti", true); //multiple or single column sorting
27960 this.registerTableOption("sortOrderReverse", false); //reverse internal sort ordering
27961 this.registerTableOption("headerSortElement", "<div class='tabulator-arrow'></div>"); //header sort element
27962 this.registerTableOption("headerSortClickElement", "header"); //element which triggers sort when clicked
27963
27964 this.registerColumnOption("sorter");
27965 this.registerColumnOption("sorterParams");
27966
27967 this.registerColumnOption("headerSort", true);
27968 this.registerColumnOption("headerSortStartingDir");
27969 this.registerColumnOption("headerSortTristate");
27970
27971 }
27972
27973 initialize(){
27974 this.subscribe("column-layout", this.initializeColumn.bind(this));
27975 this.subscribe("table-built", this.tableBuilt.bind(this));
27976 this.registerDataHandler(this.sort.bind(this), 20);
27977
27978 this.registerTableFunction("setSort", this.userSetSort.bind(this));
27979 this.registerTableFunction("getSorters", this.getSort.bind(this));
27980 this.registerTableFunction("clearSort", this.clearSort.bind(this));
27981
27982 if(this.table.options.sortMode === "remote"){
27983 this.subscribe("data-params", this.remoteSortParams.bind(this));
27984 }
27985 }
27986
27987 tableBuilt(){
27988 if(this.table.options.initialSort){
27989 this.setSort(this.table.options.initialSort);
27990 }
27991 }
27992
27993 remoteSortParams(data, config, silent, params){
27994 var sorters = this.getSort();
27995
27996 sorters.forEach((item) => {
27997 delete item.column;
27998 });
27999
28000 params.sort = sorters;
28001
28002 return params;
28003 }
28004
28005
28006 ///////////////////////////////////
28007 ///////// Table Functions /////////
28008 ///////////////////////////////////
28009
28010 userSetSort(sortList, dir){
28011 this.setSort(sortList, dir);
28012 // this.table.rowManager.sorterRefresh();
28013 this.refreshSort();
28014 }
28015
28016 clearSort(){
28017 this.clear();
28018 // this.table.rowManager.sorterRefresh();
28019 this.refreshSort();
28020 }
28021
28022
28023 ///////////////////////////////////
28024 ///////// Internal Logic //////////
28025 ///////////////////////////////////
28026
28027 //initialize column header for sorting
28028 initializeColumn(column){
28029 var sorter = false,
28030 colEl,
28031 arrowEl;
28032
28033 switch(typeof column.definition.sorter){
28034 case "string":
28035 if(Sort.sorters[column.definition.sorter]){
28036 sorter = Sort.sorters[column.definition.sorter];
28037 }else {
28038 console.warn("Sort Error - No such sorter found: ", column.definition.sorter);
28039 }
28040 break;
28041
28042 case "function":
28043 sorter = column.definition.sorter;
28044 break;
28045 }
28046
28047 column.modules.sort = {
28048 sorter:sorter, dir:"none",
28049 params:column.definition.sorterParams || {},
28050 startingDir:column.definition.headerSortStartingDir || "asc",
28051 tristate: column.definition.headerSortTristate,
28052 };
28053
28054 if(column.definition.headerSort !== false){
28055
28056 colEl = column.getElement();
28057
28058 colEl.classList.add("tabulator-sortable");
28059
28060 arrowEl = document.createElement("div");
28061 arrowEl.classList.add("tabulator-col-sorter");
28062
28063 switch(this.table.options.headerSortClickElement){
28064 case "icon":
28065 arrowEl.classList.add("tabulator-col-sorter-element");
28066 break;
28067 case "header":
28068 colEl.classList.add("tabulator-col-sorter-element");
28069 break;
28070 default:
28071 colEl.classList.add("tabulator-col-sorter-element");
28072 break;
28073 }
28074
28075 switch(this.table.options.headerSortElement){
28076 case "function":
28077 //do nothing
28078 break;
28079
28080 case "object":
28081 arrowEl.appendChild(this.table.options.headerSortElement);
28082 break;
28083
28084 default:
28085 arrowEl.innerHTML = this.table.options.headerSortElement;
28086 }
28087
28088 //create sorter arrow
28089 column.titleHolderElement.appendChild(arrowEl);
28090
28091 column.modules.sort.element = arrowEl;
28092
28093 this.setColumnHeaderSortIcon(column, "none");
28094
28095 if(this.table.options.headerSortClickElement === "icon"){
28096 arrowEl.addEventListener("mousedown", (e) => {
28097 e.stopPropagation();
28098 });
28099 }
28100
28101 //sort on click
28102 (this.table.options.headerSortClickElement === "icon" ? arrowEl : colEl).addEventListener("click", (e) => {
28103 var dir = "",
28104 sorters=[],
28105 match = false;
28106
28107 if(column.modules.sort){
28108 if(column.modules.sort.tristate){
28109 if(column.modules.sort.dir == "none"){
28110 dir = column.modules.sort.startingDir;
28111 }else {
28112 if(column.modules.sort.dir == column.modules.sort.startingDir){
28113 dir = column.modules.sort.dir == "asc" ? "desc" : "asc";
28114 }else {
28115 dir = "none";
28116 }
28117 }
28118 }else {
28119 switch(column.modules.sort.dir){
28120 case "asc":
28121 dir = "desc";
28122 break;
28123
28124 case "desc":
28125 dir = "asc";
28126 break;
28127
28128 default:
28129 dir = column.modules.sort.startingDir;
28130 }
28131 }
28132
28133 if (this.table.options.columnHeaderSortMulti && (e.shiftKey || e.ctrlKey)) {
28134 sorters = this.getSort();
28135
28136 match = sorters.findIndex((sorter) => {
28137 return sorter.field === column.getField();
28138 });
28139
28140 if(match > -1){
28141 sorters[match].dir = dir;
28142
28143 match = sorters.splice(match, 1)[0];
28144 if(dir != "none"){
28145 sorters.push(match);
28146 }
28147 }else {
28148 if(dir != "none"){
28149 sorters.push({column:column, dir:dir});
28150 }
28151 }
28152
28153 //add to existing sort
28154 this.setSort(sorters);
28155 }else {
28156 if(dir == "none"){
28157 this.clear();
28158 }else {
28159 //sort by column only
28160 this.setSort(column, dir);
28161 }
28162
28163 }
28164
28165 // this.table.rowManager.sorterRefresh(!this.sortList.length);
28166 this.refreshSort();
28167 }
28168 });
28169 }
28170 }
28171
28172 refreshSort(){
28173 if(this.table.options.sortMode === "remote"){
28174 this.reloadData(null, false, false);
28175 }else {
28176 this.refreshData(true);
28177 }
28178
28179 //TODO - Persist left position of row manager
28180 // left = this.scrollLeft;
28181 // this.scrollHorizontal(left);
28182 }
28183
28184 //check if the sorters have changed since last use
28185 hasChanged(){
28186 var changed = this.changed;
28187 this.changed = false;
28188 return changed;
28189 }
28190
28191 //return current sorters
28192 getSort(){
28193 var self = this,
28194 sorters = [];
28195
28196 self.sortList.forEach(function(item){
28197 if(item.column){
28198 sorters.push({column:item.column.getComponent(), field:item.column.getField(), dir:item.dir});
28199 }
28200 });
28201
28202 return sorters;
28203 }
28204
28205 //change sort list and trigger sort
28206 setSort(sortList, dir){
28207 var self = this,
28208 newSortList = [];
28209
28210 if(!Array.isArray(sortList)){
28211 sortList = [{column: sortList, dir:dir}];
28212 }
28213
28214 sortList.forEach(function(item){
28215 var column;
28216
28217 column = self.table.columnManager.findColumn(item.column);
28218
28219 if(column){
28220 item.column = column;
28221 newSortList.push(item);
28222 self.changed = true;
28223 }else {
28224 console.warn("Sort Warning - Sort field does not exist and is being ignored: ", item.column);
28225 }
28226
28227 });
28228
28229 self.sortList = newSortList;
28230
28231 this.dispatch("sort-changed");
28232 }
28233
28234 //clear sorters
28235 clear(){
28236 this.setSort([]);
28237 }
28238
28239 //find appropriate sorter for column
28240 findSorter(column){
28241 var row = this.table.rowManager.activeRows[0],
28242 sorter = "string",
28243 field, value;
28244
28245 if(row){
28246 row = row.getData();
28247 field = column.getField();
28248
28249 if(field){
28250
28251 value = column.getFieldValue(row);
28252
28253 switch(typeof value){
28254 case "undefined":
28255 sorter = "string";
28256 break;
28257
28258 case "boolean":
28259 sorter = "boolean";
28260 break;
28261
28262 default:
28263 if(!isNaN(value) && value !== ""){
28264 sorter = "number";
28265 }else {
28266 if(value.match(/((^[0-9]+[a-z]+)|(^[a-z]+[0-9]+))+$/i)){
28267 sorter = "alphanum";
28268 }
28269 }
28270 break;
28271 }
28272 }
28273 }
28274
28275 return Sort.sorters[sorter];
28276 }
28277
28278 //work through sort list sorting data
28279 sort(data, sortOnly){
28280 var self = this,
28281 sortList = this.table.options.sortOrderReverse ? self.sortList.slice().reverse() : self.sortList,
28282 sortListActual = [],
28283 rowComponents = [];
28284
28285 if(this.subscribedExternal("dataSorting")){
28286 this.dispatchExternal("dataSorting", self.getSort());
28287 }
28288
28289 if(!sortOnly) {
28290 self.clearColumnHeaders();
28291 }
28292
28293 if(this.table.options.sortMode !== "remote"){
28294
28295 //build list of valid sorters and trigger column specific callbacks before sort begins
28296 sortList.forEach(function(item, i){
28297 var sortObj;
28298
28299 if(item.column){
28300 sortObj = item.column.modules.sort;
28301
28302 if(sortObj){
28303
28304 //if no sorter has been defined, take a guess
28305 if(!sortObj.sorter){
28306 sortObj.sorter = self.findSorter(item.column);
28307 }
28308
28309 item.params = typeof sortObj.params === "function" ? sortObj.params(item.column.getComponent(), item.dir) : sortObj.params;
28310
28311 sortListActual.push(item);
28312 }
28313
28314 if(!sortOnly) {
28315 self.setColumnHeader(item.column, item.dir);
28316 }
28317 }
28318 });
28319
28320 //sort data
28321 if (sortListActual.length) {
28322 self._sortItems(data, sortListActual);
28323 }
28324
28325 }else if(!sortOnly) {
28326 sortList.forEach(function(item, i){
28327 self.setColumnHeader(item.column, item.dir);
28328 });
28329 }
28330
28331
28332 if(this.subscribedExternal("dataSorted")){
28333 data.forEach((row) => {
28334 rowComponents.push(row.getComponent());
28335 });
28336
28337 this.dispatchExternal("dataSorted", self.getSort(), rowComponents);
28338 }
28339
28340 return data;
28341 }
28342
28343 //clear sort arrows on columns
28344 clearColumnHeaders(){
28345 this.table.columnManager.getRealColumns().forEach((column) => {
28346 if(column.modules.sort){
28347 column.modules.sort.dir = "none";
28348 column.getElement().setAttribute("aria-sort", "none");
28349 this.setColumnHeaderSortIcon(column, "none");
28350 }
28351 });
28352 }
28353
28354 //set the column header sort direction
28355 setColumnHeader(column, dir){
28356 column.modules.sort.dir = dir;
28357 column.getElement().setAttribute("aria-sort", dir === "asc" ? "ascending" : "descending");
28358 this.setColumnHeaderSortIcon(column, dir);
28359 }
28360
28361 setColumnHeaderSortIcon(column, dir){
28362 var sortEl = column.modules.sort.element,
28363 arrowEl;
28364
28365 if(column.definition.headerSort && typeof this.table.options.headerSortElement === "function"){
28366 while(sortEl.firstChild) sortEl.removeChild(sortEl.firstChild);
28367
28368 arrowEl = this.table.options.headerSortElement.call(this.table, column.getComponent(), dir);
28369
28370 if(typeof arrowEl === "object"){
28371 sortEl.appendChild(arrowEl);
28372 }else {
28373 sortEl.innerHTML = arrowEl;
28374 }
28375 }
28376 }
28377
28378 //sort each item in sort list
28379 _sortItems(data, sortList){
28380 var sorterCount = sortList.length - 1;
28381
28382 data.sort((a, b) => {
28383 var result;
28384
28385 for(var i = sorterCount; i>= 0; i--){
28386 let sortItem = sortList[i];
28387
28388 result = this._sortRow(a, b, sortItem.column, sortItem.dir, sortItem.params);
28389
28390 if(result !== 0){
28391 break;
28392 }
28393 }
28394
28395 return result;
28396 });
28397 }
28398
28399 //process individual rows for a sort function on active data
28400 _sortRow(a, b, column, dir, params){
28401 var el1Comp, el2Comp;
28402
28403 //switch elements depending on search direction
28404 var el1 = dir == "asc" ? a : b;
28405 var el2 = dir == "asc" ? b : a;
28406
28407 a = column.getFieldValue(el1.getData());
28408 b = column.getFieldValue(el2.getData());
28409
28410 a = typeof a !== "undefined" ? a : "";
28411 b = typeof b !== "undefined" ? b : "";
28412
28413 el1Comp = el1.getComponent();
28414 el2Comp = el2.getComponent();
28415
28416 return column.modules.sort.sorter.call(this, a, b, el1Comp, el2Comp, column.getComponent(), dir, params);
28417 }
28418 }
28419
28420 class GridCalculator{
28421 constructor(columns, rows){
28422 this.columnCount = columns;
28423 this.rowCount = rows;
28424
28425 this.columnString = [];
28426 this.columns = [];
28427 this.rows = [];
28428 }
28429
28430 genColumns(data){
28431 var colCount = Math.max(this.columnCount, Math.max(...data.map(item => item.length)));
28432
28433 this.columnString = [];
28434 this.columns = [];
28435
28436 for(let i = 1; i <= colCount; i++){
28437 this.incrementChar(this.columnString.length - 1);
28438 this.columns.push(this.columnString.join(""));
28439 }
28440
28441 return this.columns;
28442 }
28443
28444 genRows(data){
28445 var rowCount = Math.max(this.rowCount, data.length);
28446
28447 this.rows = [];
28448
28449 for(let i = 1; i <= rowCount; i++){
28450 this.rows.push(i);
28451 }
28452
28453 return this.rows;
28454 }
28455
28456 incrementChar(i){
28457 let char = this.columnString[i];
28458
28459 if(char){
28460 if(char !== "Z"){
28461 this.columnString[i] = String.fromCharCode(this.columnString[i].charCodeAt(0) + 1);
28462 }else {
28463 this.columnString[i] = "A";
28464
28465 if(i){
28466 this.incrementChar(i-1);
28467 }else {
28468 this.columnString.push("A");
28469 }
28470 }
28471 }else {
28472 this.columnString.push("A");
28473 }
28474 }
28475
28476 setRowCount(count){
28477 this.rowCount = count;
28478 }
28479
28480 setColumnCount(count){
28481 this.columnCount = count;
28482 }
28483 }
28484
28485 class SheetComponent {
28486 constructor(sheet) {
28487 this._sheet = sheet;
28488
28489 return new Proxy(this, {
28490 get: function (target, name, receiver) {
28491 if (typeof target[name] !== "undefined") {
28492 return target[name];
28493 } else {
28494 return target._sheet.table.componentFunctionBinder.handle("sheet", target._sheet, name);
28495 }
28496 },
28497 });
28498 }
28499
28500 getTitle(){
28501 return this._sheet.title;
28502 }
28503
28504 getKey(){
28505 return this._sheet.key;
28506 }
28507
28508 getDefinition(){
28509 return this._sheet.getDefinition();
28510 }
28511
28512 getData() {
28513 return this._sheet.getData();
28514 }
28515
28516 setData(data) {
28517 return this._sheet.setData(data);
28518 }
28519
28520 clear(){
28521 return this._sheet.clear();
28522 }
28523
28524 remove(){
28525 return this._sheet.remove();
28526 }
28527
28528 active(){
28529 return this._sheet.active();
28530 }
28531
28532 setTitle(title){
28533 return this._sheet.setTitle(title);
28534 }
28535
28536 setRows(rows){
28537 return this._sheet.setRows(rows);
28538 }
28539
28540 setColumns(columns){
28541 return this._sheet.setColumns(columns);
28542 }
28543 }
28544
28545 class Sheet extends CoreFeature{
28546 constructor(spreadsheetManager, definition) {
28547 super(spreadsheetManager.table);
28548
28549 this.spreadsheetManager = spreadsheetManager;
28550 this.definition = definition;
28551
28552 this.title = this.definition.title || "";
28553 this.key = this.definition.key || this.definition.title;
28554 this.rowCount = this.definition.rows;
28555 this.columnCount = this.definition.columns;
28556 this.data = this.definition.data || [];
28557 this.element = null;
28558 this.isActive = false;
28559
28560 this.grid = new GridCalculator(this.columnCount, this.rowCount);
28561
28562 this.defaultColumnDefinition = {width:100, headerHozAlign:"center", headerSort:false};
28563 this.columnDefinition = Object.assign(this.defaultColumnDefinition, this.options("spreadsheetColumnDefinition"));
28564
28565 this.columnDefs = [];
28566 this.rowDefs = [];
28567 this.columnFields = [];
28568 this.columns = [];
28569 this.rows = [];
28570
28571 this.scrollTop = null;
28572 this.scrollLeft = null;
28573
28574 this.initialize();
28575
28576 this.dispatchExternal("sheetAdded", this.getComponent());
28577 }
28578
28579 ///////////////////////////////////
28580 ///////// Initialization //////////
28581 ///////////////////////////////////
28582
28583 initialize(){
28584 this.initializeElement();
28585 this.initializeColumns();
28586 this.initializeRows();
28587 }
28588
28589 reinitialize(){
28590 this.initializeColumns();
28591 this.initializeRows();
28592 }
28593
28594 initializeElement(){
28595 this.element = document.createElement("div");
28596 this.element.classList.add("tabulator-spreadsheet-tab");
28597 this.element.innerText = this.title;
28598
28599 this.element.addEventListener("click", () => {
28600 this.spreadsheetManager.loadSheet(this);
28601 });
28602 }
28603
28604 initializeColumns(){
28605 this.grid.setColumnCount(this.columnCount);
28606 this.columnFields = this.grid.genColumns(this.data);
28607
28608 this.columnDefs = [];
28609
28610 this.columnFields.forEach((ref) => {
28611 var def = Object.assign({}, this.columnDefinition);
28612 def.field = ref;
28613 def.title = ref;
28614
28615 this.columnDefs.push(def);
28616 });
28617 }
28618
28619 initializeRows(){
28620 var refs;
28621
28622 this.grid.setRowCount(this.rowCount);
28623
28624 refs = this.grid.genRows(this.data);
28625
28626 this.rowDefs = [];
28627
28628 refs.forEach((ref, i) => {
28629 var def = {"_id":ref};
28630 var data = this.data[i];
28631
28632 if(data){
28633 data.forEach((val, j) => {
28634 var field = this.columnFields[j];
28635
28636 if(field){
28637 def[field] = val;
28638 }
28639 });
28640 }
28641
28642 this.rowDefs.push(def);
28643 });
28644 }
28645
28646 unload(){
28647 this.isActive = false;
28648 this.scrollTop = this.table.rowManager.scrollTop;
28649 this.scrollLeft = this.table.rowManager.scrollLeft;
28650 this.data = this.getData(true);
28651 this.element.classList.remove("tabulator-spreadsheet-tab-active");
28652 }
28653
28654 load(){
28655
28656 var wasInactive = !this.isActive;
28657
28658 this.isActive = true;
28659 this.table.blockRedraw();
28660 this.table.setData([]);
28661 this.table.setColumns(this.columnDefs);
28662 this.table.setData(this.rowDefs);
28663 this.table.restoreRedraw();
28664
28665 if(wasInactive && this.scrollTop !== null){
28666 this.table.rowManager.element.scrollLeft = this.scrollLeft;
28667 this.table.rowManager.element.scrollTop = this.scrollTop;
28668 }
28669
28670 this.element.classList.add("tabulator-spreadsheet-tab-active");
28671
28672 this.dispatchExternal("sheetLoaded", this.getComponent());
28673 }
28674
28675 ///////////////////////////////////
28676 //////// Helper Functions /////////
28677 ///////////////////////////////////
28678
28679 getComponent(){
28680 return new SheetComponent(this);
28681 }
28682
28683 getDefinition(){
28684 return {
28685 title:this.title,
28686 key:this.key,
28687 rows:this.rowCount,
28688 columns:this.columnCount,
28689 data:this.getData(),
28690 };
28691 }
28692
28693 getData(full){
28694 var output = [],
28695 rowWidths,
28696 outputWidth, outputHeight;
28697
28698 //map data to array format
28699 this.rowDefs.forEach((rowData) => {
28700 var row = [];
28701
28702 this.columnFields.forEach((field) => {
28703 row.push(rowData[field]);
28704 });
28705
28706 output.push(row);
28707 });
28708
28709 //trim output
28710 if(!full && !this.options("spreadsheetOutputFull")){
28711
28712 //calculate used area of data
28713 rowWidths = output.map(row => row.findLastIndex(val => typeof val !== 'undefined') + 1);
28714 outputWidth = Math.max(...rowWidths);
28715 outputHeight = rowWidths.findLastIndex(width => width > 0) + 1;
28716
28717 output = output.slice(0, outputHeight);
28718 output = output.map(row => row.slice(0, outputWidth));
28719 }
28720
28721 return output;
28722 }
28723
28724 setData(data){
28725 this.data = data;
28726 this.reinitialize();
28727
28728 this.dispatchExternal("sheetUpdated", this.getComponent());
28729
28730 if(this.isActive){
28731 this.load();
28732 }
28733 }
28734
28735 clear(){
28736 this.setData([]);
28737 }
28738
28739 setTitle(title){
28740 this.title = title;
28741 this.element.innerText = title;
28742
28743 this.dispatchExternal("sheetUpdated", this.getComponent());
28744 }
28745
28746 setRows(rows){
28747 this.rowCount = rows;
28748 this.initializeRows();
28749
28750 this.dispatchExternal("sheetUpdated", this.getComponent());
28751
28752 if(this.isActive){
28753 this.load();
28754 }
28755 }
28756
28757 setColumns(columns){
28758 this.columnCount = columns;
28759 this.reinitialize();
28760
28761 this.dispatchExternal("sheetUpdated", this.getComponent());
28762
28763 if(this.isActive){
28764 this.load();
28765 }
28766 }
28767
28768 remove(){
28769 this.spreadsheetManager.removeSheet(this);
28770 }
28771
28772 destroy(){
28773 if(this.element.parentNode){
28774 this.element.parentNode.removeChild(this.element);
28775 }
28776
28777 this.dispatchExternal("sheetRemoved", this.getComponent());
28778 }
28779
28780 active(){
28781 this.spreadsheetManager.loadSheet(this);
28782 }
28783 }
28784
28785 class Spreadsheet extends Module{
28786
28787 static moduleName = "spreadsheet";
28788
28789 constructor(table){
28790 super(table);
28791
28792 this.sheets = [];
28793 this.element = null;
28794
28795 this.registerTableOption("spreadsheet", false);
28796 this.registerTableOption("spreadsheetRows", 50);
28797 this.registerTableOption("spreadsheetColumns", 50);
28798 this.registerTableOption("spreadsheetColumnDefinition", {});
28799 this.registerTableOption("spreadsheetOutputFull", false);
28800 this.registerTableOption("spreadsheetData", false);
28801 this.registerTableOption("spreadsheetSheets", false);
28802 this.registerTableOption("spreadsheetSheetTabs", false);
28803 this.registerTableOption("spreadsheetSheetTabsElement", false);
28804
28805 this.registerTableFunction("setSheets", this.setSheets.bind(this));
28806 this.registerTableFunction("addSheet", this.addSheet.bind(this));
28807 this.registerTableFunction("getSheets", this.getSheets.bind(this));
28808 this.registerTableFunction("getSheetDefinitions", this.getSheetDefinitions.bind(this));
28809 this.registerTableFunction("setSheetData", this.setSheetData.bind(this));
28810 this.registerTableFunction("getSheet", this.getSheet.bind(this));
28811 this.registerTableFunction("getSheetData", this.getSheetData.bind(this));
28812 this.registerTableFunction("clearSheet", this.clearSheet.bind(this));
28813 this.registerTableFunction("removeSheet", this.removeSheetFunc.bind(this));
28814 this.registerTableFunction("activeSheet", this.activeSheetFunc.bind(this));
28815 }
28816
28817 ///////////////////////////////////
28818 ////// Module Initialization //////
28819 ///////////////////////////////////
28820
28821
28822 initialize(){
28823 if(this.options("spreadsheet")){
28824 this.subscribe("table-initialized", this.tableInitialized.bind(this));
28825 this.subscribe("data-loaded", this.loadRemoteData.bind(this));
28826
28827 this.table.options.index = "_id";
28828
28829 if(this.options("spreadsheetData") && this.options("spreadsheetSheets")){
28830 console.warn("You cannot use spreadsheetData and spreadsheetSheets at the same time, ignoring spreadsheetData");
28831
28832 this.table.options.spreadsheetData = false;
28833 }
28834
28835 this.compatibilityCheck();
28836
28837 if(this.options("spreadsheetSheetTabs")){
28838 this.initializeTabset();
28839 }
28840 }
28841 }
28842
28843 compatibilityCheck(){
28844 if(this.options("data")){
28845 console.warn("Do not use the data option when working with spreadsheets, use either spreadsheetData or spreadsheetSheets to pass data into the table");
28846 }
28847
28848 if(this.options("pagination")){
28849 console.warn("The spreadsheet module is not compatible with the pagination module");
28850 }
28851
28852 if(this.options("groupBy")){
28853 console.warn("The spreadsheet module is not compatible with the row grouping module");
28854 }
28855
28856 if(this.options("responsiveCollapse")){
28857 console.warn("The spreadsheet module is not compatible with the responsive collapse module");
28858 }
28859 }
28860 initializeTabset(){
28861 this.element = document.createElement("div");
28862 this.element.classList.add("tabulator-spreadsheet-tabs");
28863 var altContainer = this.options("spreadsheetSheetTabsElement");
28864
28865 if(altContainer && !(altContainer instanceof HTMLElement)){
28866 altContainer = document.querySelector(altContainer);
28867
28868 if(!altContainer){
28869 console.warn("Unable to find element matching spreadsheetSheetTabsElement selector:", this.options("spreadsheetSheetTabsElement"));
28870 }
28871 }
28872
28873 if(altContainer){
28874 altContainer.appendChild(this.element);
28875 }else {
28876 this.footerAppend(this.element);
28877 }
28878 }
28879
28880 tableInitialized(){
28881 if(this.sheets.length){
28882 this.loadSheet(this.sheets[0]);
28883 }else {
28884
28885 if(this.options("spreadsheetSheets")){
28886 this.loadSheets(this.options("spreadsheetSheets"));
28887 }else if(this.options("spreadsheetData")){
28888 this.loadData(this.options("spreadsheetData"));
28889 }
28890 }
28891 }
28892
28893 ///////////////////////////////////
28894 /////////// Ajax Parsing //////////
28895 ///////////////////////////////////
28896
28897 loadRemoteData(data, data1, data2){
28898 console.log("data", data, data1, data2);
28899
28900 if(Array.isArray(data)){
28901
28902 this.table.dataLoader.clearAlert();
28903 this.dispatchExternal("dataLoaded", data);
28904
28905 if(!data.length || Array.isArray(data[0])){
28906 this.loadData(data);
28907 }else {
28908 this.loadSheets(data);
28909 }
28910 }else {
28911 console.error("Spreadsheet Loading Error - Unable to process remote data due to invalid data type \nExpecting: array \nReceived: ", typeof data, "\nData: ", data);
28912 }
28913
28914 return false;
28915 }
28916
28917 ///////////////////////////////////
28918 ///////// Sheet Management ////////
28919 ///////////////////////////////////
28920
28921
28922 loadData(data){
28923 var def = {
28924 data:data,
28925 };
28926
28927 this.loadSheet(this.newSheet(def));
28928 }
28929
28930 destroySheets(){
28931 this.sheets.forEach((sheet) => {
28932 sheet.destroy();
28933 });
28934
28935 this.sheets = [];
28936 this.activeSheet = null;
28937 }
28938
28939 loadSheets(sheets){
28940 if(!Array.isArray(sheets)){
28941 sheets = [];
28942 }
28943
28944 this.destroySheets();
28945
28946 sheets.forEach((def) => {
28947 this.newSheet(def);
28948 });
28949
28950 this.loadSheet(this.sheets[0]);
28951 }
28952
28953 loadSheet(sheet){
28954 if(this.activeSheet !== sheet){
28955 if(this.activeSheet){
28956 this.activeSheet.unload();
28957 }
28958
28959 this.activeSheet = sheet;
28960
28961 sheet.load();
28962 }
28963 }
28964
28965 newSheet(definition = {}){
28966 var sheet;
28967
28968 if(!definition.rows){
28969 definition.rows = this.options("spreadsheetRows");
28970 }
28971
28972 if(!definition.columns){
28973 definition.columns = this.options("spreadsheetColumns");
28974 }
28975
28976 sheet = new Sheet(this, definition);
28977
28978 this.sheets.push(sheet);
28979
28980 if(this.element){
28981 this.element.appendChild(sheet.element);
28982 }
28983
28984 return sheet;
28985 }
28986
28987 removeSheet(sheet){
28988 var index = this.sheets.indexOf(sheet),
28989 prevSheet;
28990
28991 if(this.sheets.length > 1){
28992 if(index > -1){
28993 this.sheets.splice(index, 1);
28994 sheet.destroy();
28995
28996 if(this.activeSheet === sheet){
28997
28998 prevSheet = this.sheets[index - 1] || this.sheets[0];
28999
29000 if(prevSheet){
29001 this.loadSheet(prevSheet);
29002 }else {
29003 this.activeSheet = null;
29004 }
29005 }
29006 }
29007 }else {
29008 console.warn("Unable to remove sheet, at least one sheet must be active");
29009 }
29010 }
29011
29012 lookupSheet(key){
29013 if(!key){
29014 return this.activeSheet;
29015 }else if(key instanceof Sheet){
29016 return key;
29017 }else if(key instanceof SheetComponent){
29018 return key._sheet;
29019 }else {
29020 return this.sheets.find(sheet => sheet.key === key) || false;
29021 }
29022 }
29023
29024
29025 ///////////////////////////////////
29026 //////// Public Functions /////////
29027 ///////////////////////////////////
29028
29029 setSheets(sheets){
29030 this.loadSheets(sheets);
29031
29032 return this.getSheets();
29033 }
29034
29035 addSheet(sheet){
29036 return this.newSheet(sheet).getComponent();
29037 }
29038
29039 getSheetDefinitions(){
29040 return this.sheets.map(sheet => sheet.getDefinition());
29041 }
29042
29043 getSheets(){
29044 return this.sheets.map(sheet => sheet.getComponent());
29045 }
29046
29047 getSheet(key){
29048 var sheet = this.lookupSheet(key);
29049
29050 return sheet ? sheet.getComponent() : false;
29051 }
29052
29053 setSheetData(key, data){
29054 if (key && !data){
29055 data = key;
29056 key = false;
29057 }
29058
29059 var sheet = this.lookupSheet(key);
29060
29061 return sheet ? sheet.setData(data) : false;
29062 }
29063
29064 getSheetData(key){
29065 var sheet = this.lookupSheet(key);
29066
29067 return sheet ? sheet.getData() : false;
29068 }
29069
29070 clearSheet(key){
29071 var sheet = this.lookupSheet(key);
29072
29073 return sheet ? sheet.clear() : false;
29074 }
29075
29076 removeSheetFunc(key){
29077 var sheet = this.lookupSheet(key);
29078
29079 if(sheet){
29080 this.removeSheet(sheet);
29081 }
29082 }
29083
29084 activeSheetFunc(key){
29085 var sheet = this.lookupSheet(key);
29086
29087 return sheet ? this.loadSheet(sheet) : false;
29088 }
29089 }
29090
29091 class Tooltip extends Module{
29092
29093 static moduleName = "tooltip";
29094
29095 constructor(table){
29096 super(table);
29097
29098 this.tooltipSubscriber = null,
29099 this.headerSubscriber = null,
29100
29101 this.timeout = null;
29102 this.popupInstance = null;
29103
29104 // this.registerTableOption("tooltipGenerationMode", undefined); //deprecated
29105 this.registerTableOption("tooltipDelay", 300);
29106
29107 this.registerColumnOption("tooltip");
29108 this.registerColumnOption("headerTooltip");
29109 }
29110
29111 initialize(){
29112 this.deprecatedOptionsCheck();
29113
29114 this.subscribe("column-init", this.initializeColumn.bind(this));
29115 }
29116
29117 deprecatedOptionsCheck(){
29118 // this.deprecationCheckMsg("tooltipGenerationMode", "This option is no longer needed as tooltips are always generated on hover now");
29119 }
29120
29121 initializeColumn(column){
29122 if(column.definition.headerTooltip && !this.headerSubscriber){
29123 this.headerSubscriber = true;
29124
29125 this.subscribe("column-mousemove", this.mousemoveCheck.bind(this, "headerTooltip"));
29126 this.subscribe("column-mouseout", this.mouseoutCheck.bind(this, "headerTooltip"));
29127 }
29128
29129 if(column.definition.tooltip && !this.tooltipSubscriber){
29130 this.tooltipSubscriber = true;
29131
29132 this.subscribe("cell-mousemove", this.mousemoveCheck.bind(this, "tooltip"));
29133 this.subscribe("cell-mouseout", this.mouseoutCheck.bind(this, "tooltip"));
29134 }
29135 }
29136
29137 mousemoveCheck(action, e, component){
29138 var tooltip = action === "tooltip" ? component.column.definition.tooltip : component.definition.headerTooltip;
29139
29140 if(tooltip){
29141 this.clearPopup();
29142 this.timeout = setTimeout(this.loadTooltip.bind(this, e, component, tooltip), this.table.options.tooltipDelay);
29143 }
29144 }
29145
29146 mouseoutCheck(action, e, component){
29147 if(!this.popupInstance){
29148 this.clearPopup();
29149 }
29150 }
29151
29152 clearPopup(action, e, component){
29153 clearTimeout(this.timeout);
29154 this.timeout = null;
29155
29156 if(this.popupInstance){
29157 this.popupInstance.hide();
29158 }
29159 }
29160
29161 loadTooltip(e, component, tooltip){
29162 var contentsEl, renderedCallback, coords;
29163
29164 function onRendered(callback){
29165 renderedCallback = callback;
29166 }
29167
29168 if(typeof tooltip === "function"){
29169 tooltip = tooltip(e, component.getComponent(), onRendered);
29170 }
29171
29172 if(tooltip instanceof HTMLElement){
29173 contentsEl = tooltip;
29174 }else {
29175 contentsEl = document.createElement("div");
29176
29177 if(tooltip === true){
29178 if(component instanceof Cell){
29179 tooltip = component.value;
29180 }else {
29181 if(component.definition.field){
29182 this.langBind("columns|" + component.definition.field, (value) => {
29183 contentsEl.innerHTML = tooltip = value || component.definition.title;
29184 });
29185 }else {
29186 tooltip = component.definition.title;
29187 }
29188 }
29189 }
29190
29191 contentsEl.innerHTML = tooltip;
29192 }
29193
29194 if(tooltip || tooltip === 0 || tooltip === false){
29195 contentsEl.classList.add("tabulator-tooltip");
29196
29197 contentsEl.addEventListener("mousemove", e => e.preventDefault());
29198
29199 this.popupInstance = this.popup(contentsEl);
29200
29201 if(typeof renderedCallback === "function"){
29202 this.popupInstance.renderCallback(renderedCallback);
29203 }
29204
29205 coords = this.popupInstance.containerEventCoords(e);
29206
29207 this.popupInstance.show(coords.x + 15, coords.y + 15).hideOnBlur(() => {
29208 this.dispatchExternal("TooltipClosed", component.getComponent());
29209 this.popupInstance = null;
29210 });
29211
29212 this.dispatchExternal("TooltipOpened", component.getComponent());
29213 }
29214 }
29215 }
29216
29217 var defaultValidators = {
29218 //is integer
29219 integer: function(cell, value, parameters){
29220 if(value === "" || value === null || typeof value === "undefined"){
29221 return true;
29222 }
29223
29224 value = Number(value);
29225
29226 return !isNaN(value) && isFinite(value) && Math.floor(value) === value;
29227 },
29228
29229 //is float
29230 float: function(cell, value, parameters){
29231 if(value === "" || value === null || typeof value === "undefined"){
29232 return true;
29233 }
29234
29235 value = Number(value);
29236
29237 return !isNaN(value) && isFinite(value) && value % 1 !== 0;
29238 },
29239
29240 //must be a number
29241 numeric: function(cell, value, parameters){
29242 if(value === "" || value === null || typeof value === "undefined"){
29243 return true;
29244 }
29245 return !isNaN(value);
29246 },
29247
29248 //must be a string
29249 string: function(cell, value, parameters){
29250 if(value === "" || value === null || typeof value === "undefined"){
29251 return true;
29252 }
29253 return isNaN(value);
29254 },
29255
29256 //must be alphanumeric
29257 alphanumeric: function(cell, value, parameters){
29258 if(value === "" || value === null || typeof value === "undefined"){
29259 return true;
29260 }
29261
29262 var reg = new RegExp(/^[a-z0-9]+$/i);
29263
29264 return reg.test(value);
29265 },
29266
29267 //maximum value
29268 max: function(cell, value, parameters){
29269 if(value === "" || value === null || typeof value === "undefined"){
29270 return true;
29271 }
29272 return parseFloat(value) <= parameters;
29273 },
29274
29275 //minimum value
29276 min: function(cell, value, parameters){
29277 if(value === "" || value === null || typeof value === "undefined"){
29278 return true;
29279 }
29280 return parseFloat(value) >= parameters;
29281 },
29282
29283 //starts with value
29284 starts: function(cell, value, parameters){
29285 if(value === "" || value === null || typeof value === "undefined"){
29286 return true;
29287 }
29288 return String(value).toLowerCase().startsWith(String(parameters).toLowerCase());
29289 },
29290
29291 //ends with value
29292 ends: function(cell, value, parameters){
29293 if(value === "" || value === null || typeof value === "undefined"){
29294 return true;
29295 }
29296 return String(value).toLowerCase().endsWith(String(parameters).toLowerCase());
29297 },
29298
29299
29300 //minimum string length
29301 minLength: function(cell, value, parameters){
29302 if(value === "" || value === null || typeof value === "undefined"){
29303 return true;
29304 }
29305 return String(value).length >= parameters;
29306 },
29307
29308 //maximum string length
29309 maxLength: function(cell, value, parameters){
29310 if(value === "" || value === null || typeof value === "undefined"){
29311 return true;
29312 }
29313 return String(value).length <= parameters;
29314 },
29315
29316 //in provided value list
29317 in: function(cell, value, parameters){
29318 if(value === "" || value === null || typeof value === "undefined"){
29319 return true;
29320 }
29321
29322 if(typeof parameters == "string"){
29323 parameters = parameters.split("|");
29324 }
29325
29326 return parameters.indexOf(value) > -1;
29327 },
29328
29329 //must match provided regex
29330 regex: function(cell, value, parameters){
29331 if(value === "" || value === null || typeof value === "undefined"){
29332 return true;
29333 }
29334 var reg = new RegExp(parameters);
29335
29336 return reg.test(value);
29337 },
29338
29339 //value must be unique in this column
29340 unique: function(cell, value, parameters){
29341 if(value === "" || value === null || typeof value === "undefined"){
29342 return true;
29343 }
29344 var unique = true;
29345
29346 var cellData = cell.getData();
29347 var column = cell.getColumn()._getSelf();
29348
29349 this.table.rowManager.rows.forEach(function(row){
29350 var data = row.getData();
29351
29352 if(data !== cellData){
29353 if(value == column.getFieldValue(data)){
29354 unique = false;
29355 }
29356 }
29357 });
29358
29359 return unique;
29360 },
29361
29362 //must have a value
29363 required:function(cell, value, parameters){
29364 return value !== "" && value !== null && typeof value !== "undefined";
29365 },
29366 };
29367
29368 class Validate extends Module{
29369
29370 static moduleName = "validate";
29371
29372 //load defaults
29373 static validators = defaultValidators;
29374
29375 constructor(table){
29376 super(table);
29377
29378 this.invalidCells = [];
29379
29380 this.registerTableOption("validationMode", "blocking");
29381
29382 this.registerColumnOption("validator");
29383
29384 this.registerTableFunction("getInvalidCells", this.getInvalidCells.bind(this));
29385 this.registerTableFunction("clearCellValidation", this.userClearCellValidation.bind(this));
29386 this.registerTableFunction("validate", this.userValidate.bind(this));
29387
29388 this.registerComponentFunction("cell", "isValid", this.cellIsValid.bind(this));
29389 this.registerComponentFunction("cell", "clearValidation", this.clearValidation.bind(this));
29390 this.registerComponentFunction("cell", "validate", this.cellValidate.bind(this));
29391
29392 this.registerComponentFunction("column", "validate", this.columnValidate.bind(this));
29393 this.registerComponentFunction("row", "validate", this.rowValidate.bind(this));
29394 }
29395
29396
29397 initialize(){
29398 this.subscribe("cell-delete", this.clearValidation.bind(this));
29399 this.subscribe("column-layout", this.initializeColumnCheck.bind(this));
29400
29401 this.subscribe("edit-success", this.editValidate.bind(this));
29402 this.subscribe("edit-editor-clear", this.editorClear.bind(this));
29403 this.subscribe("edit-edited-clear", this.editedClear.bind(this));
29404 }
29405
29406 ///////////////////////////////////
29407 ///////// Event Handling //////////
29408 ///////////////////////////////////
29409
29410 editValidate(cell, value, previousValue){
29411 var valid = this.table.options.validationMode !== "manual" ? this.validate(cell.column.modules.validate, cell, value) : true;
29412
29413 // allow time for editor to make render changes then style cell
29414 if(valid !== true){
29415 setTimeout(() => {
29416 cell.getElement().classList.add("tabulator-validation-fail");
29417 this.dispatchExternal("validationFailed", cell.getComponent(), value, valid);
29418 });
29419 }
29420
29421 return valid;
29422 }
29423
29424 editorClear(cell, cancelled){
29425 if(cancelled){
29426 if(cell.column.modules.validate){
29427 this.cellValidate(cell);
29428 }
29429 }
29430
29431 cell.getElement().classList.remove("tabulator-validation-fail");
29432 }
29433
29434 editedClear(cell){
29435 if(cell.modules.validate){
29436 cell.modules.validate.invalid = false;
29437 }
29438 }
29439
29440 ///////////////////////////////////
29441 ////////// Cell Functions /////////
29442 ///////////////////////////////////
29443
29444 cellIsValid(cell){
29445 return cell.modules.validate ? (cell.modules.validate.invalid || true) : true;
29446 }
29447
29448 cellValidate(cell){
29449 return this.validate(cell.column.modules.validate, cell, cell.getValue());
29450 }
29451
29452 ///////////////////////////////////
29453 ///////// Column Functions ////////
29454 ///////////////////////////////////
29455
29456 columnValidate(column){
29457 var invalid = [];
29458
29459 column.cells.forEach((cell) => {
29460 if(this.cellValidate(cell) !== true){
29461 invalid.push(cell.getComponent());
29462 }
29463 });
29464
29465 return invalid.length ? invalid : true;
29466 }
29467
29468 ///////////////////////////////////
29469 ////////// Row Functions //////////
29470 ///////////////////////////////////
29471
29472 rowValidate(row){
29473 var invalid = [];
29474
29475 row.cells.forEach((cell) => {
29476 if(this.cellValidate(cell) !== true){
29477 invalid.push(cell.getComponent());
29478 }
29479 });
29480
29481 return invalid.length ? invalid : true;
29482 }
29483
29484 ///////////////////////////////////
29485 ///////// Table Functions /////////
29486 ///////////////////////////////////
29487
29488
29489 userClearCellValidation(cells){
29490 if(!cells){
29491 cells = this.getInvalidCells();
29492 }
29493
29494 if(!Array.isArray(cells)){
29495 cells = [cells];
29496 }
29497
29498 cells.forEach((cell) => {
29499 this.clearValidation(cell._getSelf());
29500 });
29501 }
29502
29503 userValidate(cells){
29504 var output = [];
29505
29506 //clear row data
29507 this.table.rowManager.rows.forEach((row) => {
29508 row = row.getComponent();
29509
29510 var valid = row.validate();
29511
29512 if(valid !== true){
29513 output = output.concat(valid);
29514 }
29515 });
29516
29517 return output.length ? output : true;
29518 }
29519
29520 ///////////////////////////////////
29521 ///////// Internal Logic //////////
29522 ///////////////////////////////////
29523
29524 initializeColumnCheck(column){
29525 if(typeof column.definition.validator !== "undefined"){
29526 this.initializeColumn(column);
29527 }
29528 }
29529
29530 //validate
29531 initializeColumn(column){
29532 var self = this,
29533 config = [],
29534 validator;
29535
29536 if(column.definition.validator){
29537
29538 if(Array.isArray(column.definition.validator)){
29539 column.definition.validator.forEach((item) => {
29540 validator = self._extractValidator(item);
29541
29542 if(validator){
29543 config.push(validator);
29544 }
29545 });
29546
29547 }else {
29548 validator = this._extractValidator(column.definition.validator);
29549
29550 if(validator){
29551 config.push(validator);
29552 }
29553 }
29554
29555 column.modules.validate = config.length ? config : false;
29556 }
29557 }
29558
29559 _extractValidator(value){
29560 var type, params, pos;
29561
29562 switch(typeof value){
29563 case "string":
29564 pos = value.indexOf(':');
29565
29566 if(pos > -1){
29567 type = value.substring(0,pos);
29568 params = value.substring(pos+1);
29569 }else {
29570 type = value;
29571 }
29572
29573 return this._buildValidator(type, params);
29574
29575 case "function":
29576 return this._buildValidator(value);
29577
29578 case "object":
29579 return this._buildValidator(value.type, value.parameters);
29580 }
29581 }
29582
29583 _buildValidator(type, params){
29584
29585 var func = typeof type == "function" ? type : Validate.validators[type];
29586
29587 if(!func){
29588 console.warn("Validator Setup Error - No matching validator found:", type);
29589 return false;
29590 }else {
29591 return {
29592 type:typeof type == "function" ? "function" : type,
29593 func:func,
29594 params:params,
29595 };
29596 }
29597 }
29598
29599 validate(validators, cell, value){
29600 var self = this,
29601 failedValidators = [],
29602 invalidIndex = this.invalidCells.indexOf(cell);
29603
29604 if(validators){
29605 validators.forEach((item) => {
29606 if(!item.func.call(self, cell.getComponent(), value, item.params)){
29607 failedValidators.push({
29608 type:item.type,
29609 parameters:item.params
29610 });
29611 }
29612 });
29613 }
29614
29615 if(!cell.modules.validate){
29616 cell.modules.validate = {};
29617 }
29618
29619 if(!failedValidators.length){
29620 cell.modules.validate.invalid = false;
29621 cell.getElement().classList.remove("tabulator-validation-fail");
29622
29623 if(invalidIndex > -1){
29624 this.invalidCells.splice(invalidIndex, 1);
29625 }
29626 }else {
29627 cell.modules.validate.invalid = failedValidators;
29628
29629 if(this.table.options.validationMode !== "manual"){
29630 cell.getElement().classList.add("tabulator-validation-fail");
29631 }
29632
29633 if(invalidIndex == -1){
29634 this.invalidCells.push(cell);
29635 }
29636 }
29637
29638 return failedValidators.length ? failedValidators : true;
29639 }
29640
29641 getInvalidCells(){
29642 var output = [];
29643
29644 this.invalidCells.forEach((cell) => {
29645 output.push(cell.getComponent());
29646 });
29647
29648 return output;
29649 }
29650
29651 clearValidation(cell){
29652 var invalidIndex;
29653
29654 if(cell.modules.validate && cell.modules.validate.invalid){
29655
29656 cell.getElement().classList.remove("tabulator-validation-fail");
29657 cell.modules.validate.invalid = false;
29658
29659 invalidIndex = this.invalidCells.indexOf(cell);
29660
29661 if(invalidIndex > -1){
29662 this.invalidCells.splice(invalidIndex, 1);
29663 }
29664 }
29665 }
29666 }
29667
29668 var allModules = /*#__PURE__*/Object.freeze({
29669 __proto__: null,
29670 AccessorModule: Accessor,
29671 AjaxModule: Ajax,
29672 ClipboardModule: Clipboard,
29673 ColumnCalcsModule: ColumnCalcs,
29674 DataTreeModule: DataTree,
29675 DownloadModule: Download,
29676 EditModule: Edit,
29677 ExportModule: Export,
29678 FilterModule: Filter,
29679 FormatModule: Format,
29680 FrozenColumnsModule: FrozenColumns,
29681 FrozenRowsModule: FrozenRows,
29682 GroupRowsModule: GroupRows,
29683 HistoryModule: History,
29684 HtmlTableImportModule: HtmlTableImport,
29685 ImportModule: Import,
29686 InteractionModule: Interaction,
29687 KeybindingsModule: Keybindings,
29688 MenuModule: Menu,
29689 MoveColumnsModule: MoveColumns,
29690 MoveRowsModule: MoveRows,
29691 MutatorModule: Mutator,
29692 PageModule: Page,
29693 PersistenceModule: Persistence,
29694 PopupModule: Popup,
29695 PrintModule: Print,
29696 ReactiveDataModule: ReactiveData,
29697 ResizeColumnsModule: ResizeColumns,
29698 ResizeRowsModule: ResizeRows,
29699 ResizeTableModule: ResizeTable,
29700 ResponsiveLayoutModule: ResponsiveLayout,
29701 SelectRangeModule: SelectRange,
29702 SelectRowModule: SelectRow,
29703 SortModule: Sort,
29704 SpreadsheetModule: Spreadsheet,
29705 TooltipModule: Tooltip,
29706 ValidateModule: Validate
29707 });
29708
29709 //tabulator with all modules installed
29710
29711 class TabulatorFull extends Tabulator {
29712 static extendModule(){
29713 Tabulator.initializeModuleBinder(allModules);
29714 Tabulator._extendModule(...arguments);
29715 }
29716
29717 static registerModule(){
29718 Tabulator.initializeModuleBinder(allModules);
29719 Tabulator._registerModule(...arguments);
29720 }
29721
29722 constructor(element, options, modules){
29723 super(element, options, allModules);
29724 }
29725 }
29726
29727 return TabulatorFull;
29728
29729 }));
29730 //# sourceMappingURL=tabulator.js.map