This repository has been archived by the owner on Nov 4, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
tables.js
1950 lines (1697 loc) · 64.1 KB
/
tables.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Parses a string (csv, tsv, etc.) into an object
* @param {String} str String to parse into object
* @param {String} delimeter Delimeter to split the rows by
* @param {String} escape Escape character to escape delimeters
* @returns {Object[]} Array of objects
*/
const parseSV = (str, delimeter, escape) => {
// return [{a: 1, b: 2}, {a: 3, b: 4}]
// include " in the string to escape it
// headers is first row, it could have " in it to escape commas
// data is the rest of the rows
// split the string into rows
const data = str.split('\n');
// get the headers
const headers = data[0].split(delimeter).map((h) => {
if (h[0] === escape && h[h.length - 1] === escape) {
return h.substring(1, h.length - 1);
} else {
return h;
}
});
data.shift();
// get the data
return data.map((row) => {
const splitRow = row.split(delimeter).map(r => {
if (r[0] === escape && r[r.length - 1] === escape) {
return r.substring(1, r.length - 1);
} else {
return r;
}
});
console.log(splitRow);
return splitRow.reduce((acc, curr, i) => {
acc[headers[i]] = curr.trim();
return acc;
}, {});
});
}
const parseHTML = (str) => {
const div = document.createElement('div');
div.innerHTML = str;
return div.firstChild;
}
/**
* A class that handles the state of a table
*/
class Table_StateStack {
constructor() {
this.states = [];
this.currentState = null;
this.currentIndex = -1;
this.locked = false;
this.currentUnsavedState = null;
this.currentUnsavedIndex = -1;
this.unsavedStates = [];
}
/**
*
* @param {Any} state Anything
* @returns Copied state with no dependencies
*/
copyState(state) {
if (Array.isArray(state)) {
return [...state];
}
switch (typeof state) {
case 'object':
return {...state };
default:
return JSON.parse(JSON.stringify(state));
}
}
/**
*
* @param {Any} state This can be anything, it will be passed to onChange()
*/
addState(state) {
if (this.currentIndex < this.states.length - 1) {
// remove all states after currentIndex
this.states = this.states.splice(0, this.currentIndex + 1);
this.states.push(this.copyState(state));
this.currentIndex = this.states.length - 1;
this.currentState = this.states[this.currentIndex];
} else {
this.states.push(this.copyState(state));
this.currentIndex = this.states.length - 1;
this.currentState = this.states[this.currentIndex];
}
this.resolve();
}
/**
*
* @param {Any} state This can be anything, it will be passed to onChange()
*/
addUnsavedState(state) {
if (this.currentUnsavedIndex < this.unsavedStates.length - 1) {
// remove all states after currentIndex
this.unsavedStates = this.unsavedStates.splice(0, this.currentUnsavedIndex + 1);
this.unsavedStates.push(this.copyState(state));
this.currentUnsavedIndex = this.unsavedStates.length - 1;
this.currentUnsavedState = this.unsavedStates[this.currentUnsavedIndex];
} else {
this.unsavedStates.push(this.copyState(state));
this.currentUnsavedIndex = this.unsavedStates.length - 1;
this.currentUnsavedState = this.unsavedStates[this.currentUnsavedIndex];
}
this.unsavedStates = this.unsavedStates.filter((s, i) => this.unsavedStates.indexOf(s) === i);
this.resolveUnsaved();
}
/**
* This is called when the stack is cleared
*/
nextUnsaved() {
if (this.unsavedStates.length > 0 && this.currentUnsavedIndex < this.unsavedStates.length - 1) {
this.currentUnsavedState = this.unsavedStates[this.currentUnsavedIndex + 1];
this.currentUnsavedIndex++;
this.resolveUnsaved();
} else {
return null;
}
}
/**
* This is called when the stack is cleared
*/
prevUnsaved() {
if (this.unsavedStates.length > 0 && this.currentUnsavedIndex > 0) {
this.currentUnsavedState = this.unsavedStates[this.currentUnsavedIndex - 1];
this.currentUnsavedIndex--;
this.resolveUnsaved();
} else {
return null;
}
}
/**
* Destroys the stack and calls onClear()
*/
clearStates() {
this.states = [];
this.currentIndex = -1;
this.onClear();
this.currentState = null;
this.unsavedStates = [];
}
/**
* Goes to the next state in the stack
*/
next() {
if (this.states.length > 0 && this.currentIndex < this.states.length - 1) {
this.currentState = this.states[this.currentIndex + 1];
this.currentIndex++;
this.resolve();
} else {
this.onReject(this.currentState);
}
}
/**
* Goes to the previous state in the stack
*/
prev() {
if (this.states.length > 0 && this.currentIndex > 0) {
this.currentState = this.states[this.currentIndex - 1];
this.currentIndex--;
// this.findBranch(this.currentIndex);
this.resolve();
} else {
this.onReject(this.currentState);
}
}
/**
* Gets the number of states in the current stack
*/
get numStacks() {
return this.states.length;
}
/**
* Resolves the current state
*/
resolve() {
if (this.locked) {
this.onReject(this.currentState);
} else {
this.onChange(this.currentState);
}
}
resolveUnsaved() {
if (this.locked) {
this.onRejectUnsaved(this.currentUnsavedState);
} else {
this.onChangeUnsaved(this.currentUnsavedState);
}
}
/**
* Customizable callback for when the state changes
*/
onChange() {}
/**
* Customizable callback for when the state changes
*/
onChangeUnsaved() {}
/**
* Customizable callback for when the state changes to a rejected state
*/
onReject() {
throw new Error('State does not exist, nothing has changed');
}
/**
* Customizable callback for when the state changes to a rejected state
*/
onRejectUnsaved() {
throw new Error('State does not exist, nothing has changed');
}
/**
* Customizable callback for when the stack is cleared
*/
onClear() {}
/**
* Customizable callback for when the stack is locked
*/
get hasNext() {
return this.currentIndex < this.states.length - 1;
}
/**
* Customizable callback for when the stack is locked
*/
get hasPrev() {
return this.currentIndex > 0;
}
/**
* Customizable callback for when the stack is locked
*/
get hasUnsavedNext() {
return this.currentUnsavedIndex < this.unsavedStates.length - 1;
}
/**
* Customizable callback for when the stack is locked
*/
get hasUnsavedPrev() {
return this.currentUnsavedIndex > 0;
}
}
/**
* A class for creating a table
* @public
* @class
* @classdesc A class for creating a table
*
* @since 1.1.0
*
* @example
* const table = new Table('table', [], [], {});
*/
class Table {
/**
* @param {HTMLElement | String} table The table element or css selector for the table
*
*
*
* @param {Object[]} headers The headers for the table
*
* @param {String} headers[].title The title of the header
* @param {String} headers[].name The name of the header (used the same as title)
* @param {String} headers[].key The key of the header (used the same as name)
*
* @param {Function} headers[].getData A function that returns the data for the td element (takes in the row data)
* @param {Function} headers[].sort A function that returns the data for the column (takes in (TableRow, TableRow))
* @param {Boolean} headers[].minimize Whether or not to add minimize functionality to the header
* @param {Object} headers.th An object with properties for the th element
* @param {String[]} headers[].th.classes An array of classes to add to the td elements
*
* @param {Object} headers[].td An object with properties for the td elements
* @param {String[]} headers[].td.lasses An array of classes to add to the th elements
* @param {Object[]} headers[].td.classTests An array of objects with class tests for the td elements
* @param {String} headers[].td.classTests[].class The class to add to the td element
* @param {String[]} headers[].td.classTests[].classes The class to add to the td element
* @param {Function} headers[].td.classTests[].test A function that returns a boolean for whether or not to add the class to the td element (takes in the row data)
* @todo Divide td and th into separate objects within the headers array
*
* @param {Object[]} headers[].th.listeners An array of objects with event listeners for the th elements
* @param {String} headers[].th.listeners[].listener The event listener type
* @param {Function} headers[].th.listeners[].callback The callback function for the event listener (uses 1.1.0+ data structure)
* @param {Function} headers[].th.listeners[].action The action function for the event listener (takes in the 1.0.0 data structure)
*
* @param {Object[]} headers[].td.listeners An array of objects with event listeners for the td elements
* @param {String} headers[].td.listeners[].listener The event listener type
* @param {Function} headers[].td.listeners[].callback The callback function for the event listener (uses 1.1.0+ data structure)
* @param {Function} headers[].td.listeners[].action The action function for the event listener (takes in the 1.0.0 data structure)
*
* @param {Any[]} data The data for the table
*
*
*
* @param {Object} options The options for the table
*
*
* @param {Function} options.appendTest A function that returns a boolean for whether or not to append a row, takes in the row data
*
* @param {Object} options.tr The options for the tr elements
* @param {Object[]} options.tr.isteners An array of objects with event listeners for the table rows
* @param {String} options.tr.listeners[].listener The event listener type
* @param {Function} options.tr.listeners[].callback The callback function for the event listener (uses 1.1.0+ data structure)
* @param {Function} options.tr.listeners[].action The action function for the event listener (takes in the 1.0.0 data structure)
*
* @param {Object[]} options.tr.attributes An array of objects with attributes for the table rows
* @param {String} options.tr.attributes[].attribute The attribute name
* @param {String | Function} options.tr.attributes[].value The attribute value or a function that returns the attribute value (takes in the row data)
*
*
* @param {String[]} options.trClasses An array of classes to add to the table rows
*
*
* @param {Object[]} options.colGroup An array of objects with colGroup for the table
* @param {String} options.colGroup[].span The span of the colGroup
* @param {String} options.colGroup[].classes The classes of the colGroup
*
*
* @param {Object[]} options.tr.classTests An array of objects with tests for the table rows
* @param {String} options.tr.classTests[].class The class to add to the row
* @param {String[]} options.tr.classTests[].classes The classes to add to the row
* @param {Function} options.tr.classTests[].test A function that returns a boolean for whether or not to add the class to the row (takes in the row data)
*
*
* @param {Boolean} options.fixedHeaders Whether or not to use style.position = 'sticky' for the headers
* @param {String[]} options.classes An array of classes to add to the table element
*
*
* @param {Object} options.dataTable Options for the DataTables library (use with JQuery and DataTables) Or just set it to true to use the default options
* @param {Object} options.datatable Options for the DataTables library (use with JQuery and DataTables) Or just set it to true to use the default options
*
*
* @param {Object} options.reorder Under Construction: Options for the drag/drop reorder functionality
*
* @param {Object} options.reorder.listeners An object with event listeners for each drag event
* @param {Function} options.reorder.listeners.onDragStart The event listener for when a row is dragged (uses event)
* @param {Function} options.reorder.listeners.onDrag The event listener for when a row is dragged over (uses event)
* @param {Function} options.reorder.listeners.onDragEnd The event listener for when a row is dropped (uses event)
* @param {Function} options.reorder.listeners.onDrop The event listener for when a row is dropped (uses event)
* @param {Function} options.reorder.listeners.onDragEnter The event listener for when a row is dragged over (uses event)
* @param {Function} options.reorder.listeners.onDragLeave The event listener for when a row is dragged over (uses event)
*
* @param {Object} options.reorder.classes An object with classes for each drag event
* @param {String[]} options.reorder.classes.dragging The class for when a row is being dragged
* @param {String[]} options.reorder.classes.dragover The class for when a row is being dragged over
* @param {String[]} options.reorder.classes.dragenter The class for when a row is being dragged over
* @param {String[]} options.reorder.classes.dragleave The class for when a row is being dragged over
* @param {String[]} options.reorder.classes.dragstart The class for when a row is being dragged
* @param {String[]} options.reorder.classes.dragend The class for when a row is being dragged
* @param {String[]} options.reorder.classes.drop The class for when a row is being dropped
*
* @param {HTMLElement | String} options.reorder.handle The element that is used to drag the row
*
*
* @param {Object} options.sort Options for the sorting functionality (each header must containt a sort property)
* @param {String[]} options.sort.classes The classes for the sorting buttons
*
*
* @param {Object} options.editable Options for the editable functionality, applies contenteditable="true" to all td elements. Each getData() in the header must return a string
* @param {Function} options.onChange The function to call when the data changes
* @param {Function} options.onCancel The function to call when the data changes
*
*
* // TODO: do all of these below here
* @param {Object} options.search Under Construction: Options for the search functionality
* @param {String} options.search.placeholder The placeholder for the search input
* @param {String[]} options.search.classes The classes for the search input
*
*
* @param {Object} options.pagination Under Construction: Options for the pagination functionality
* @param {Number} options.pagination.perPage The number of rows to show per page
* @param {String[]} options.pagination.classes The classes for the search input
* @param {Object} options.pagination.icons The icons for the pagination buttons
* @param {String} options.pagination.icons.first The icon for the first page button
* @param {String} options.pagination.icons.prev The icon for the previous page button
* @param {String} options.pagination.icons.next The icon for the next page button
* @param {String} options.pagination.icons.last The icon for the last page button
*
*
* @param {String | HTMLElement} options.caption Under Construction: The caption for the table
*
*
* @param {Object} options.insert Under Construction: Options for the insert functionality
*
* @param {Object} options.insert.row Options for inserting rows
* @param {Object} options.insert.row.classes The classes for the insert row button
* @param {String | HTMLElement} options.insert.row.icon The icon for the insert row button
* @param {Function} options.insert.row.onClick The function to call when the insert row button is clicked
*
* @param {Object} options.insert.column Options for inserting columns
* @param {Object} options.insert.column.classes The classes for the insert column button
* @param {String | HTMLElement} options.insert.column.icon The icon for the insert column button
* @param {Function} options.insert.column.onClick The function to call when the insert column button is clicked
*
*
* @param {Object} options.delete Under Construction: Options for the delete functionality
*
* @param {Object} options.delete.row Options for deleting rows
* @param {Object} options.delete.row.classes The classes for the delete row button
* @param {String | HTMLElement} options.delete.row.icon The icon for the delete row button
* @param {Function} options.delete.row.onClick The function to call when the delete row button is clicked
*
* @param {Object} options.delete.column Options for deleting columns
* @param {Object} options.delete.column.classes The classes for the delete column button
* @param {String | HTMLElement} options.delete.column.icon The icon for the delete column button
* @param {Function} options.delete.column.onClick The function to call when the delete column button is clicked
*/
constructor(table, headers, data, options) {
if (typeof table === 'string') table = document.querySelector(table);
if (!table || !table.querySelector) {
throw new Error('Table must be an HTML element');
}
if (!headers) {
throw new Error('Headers must be provided');
}
if (!data) {
throw new Error('Data must be provided');
}
/**
* Whether the table has been rendered
* @type {Boolean}
* @private
*/
this.rendered = false;
/**
* The table element
* @type {HTMLElement}
* @public
*/
this.el = table;
/**
* The rows in the table
* @type {Array<TableRow>}
* @public
*/
this.rows = [];
/**
* The columns in the table
* @type {Array<TableColumn>}
* @public
*/
this.columns = new Array(headers.length).fill();
/**
* The headers in the table (passed in the constructor)
* @type {Array<Object>}
* @public
*/
this.headers = Array.isArray(headers) ? headers.map(h => {
return typeof headers == 'string' ? { title: h } : h;
}) : (typeof headers === 'object' ? Object.keys(headers).map(h => {
return {
title: h,
...headers[h]
}
}) : [])
/**
* The options for the table (passed in the constructor)
* @type {Object}
* @public
*/
this.options = options || {};
/**
* The original data in the table (passed in the constructor)
* @type {Array<Any>}
* @public
*/
this.originalData = [...data];
/**
* The data in the table (passed in the constructor)
* @type {Array<Any>}
* @public
*/
this.data = data;
/**
* The rows for insert on a reordering table
* @type {Array<ReorderInsertRow>}
* @public
*/
this.insertRows = [];
/**
* The shown rows for insert on a reordering table
* @type {Array<ReorderInsertRow>}
* @public
*/
this.shownInsertRows = [];
/**
* The sections of the table (thead, tbody, tfoot, etc.)
* @type {Object}
* @public
*/
this.sections = {}
/**
* The state stack for the table
* @type {Table_StateStack}
* @public
*/
this.stack = new Table_StateStack();
this.stack.onChange = () => {
this.renderFromContent();
}
this.stack.onClear = () => {
this.destroy(true);
}
this.stack.onReject = () => {};
if (this.options.__render !== false) this.stack.addState(this);
}
/**
* Erases all elements in the table
* @param {Boolean} removeData Whether or not to remove the data from the table class
* @memberof Table
* @returns {void}
* @example
* table.destroy();
*/
destroy(removeData = false) {
this.el.innerHTML = '';
if (removeData) {
this.data = [];
this.rows = [];
this.headers = [];
this.columns = [];
this.insertRows = [];
}
}
/**
* Renders the table
* @memberof Table
* @returns {void}
* @example
* table.render();
*/
render() {
const {
evenColumns,
reorder,
caption
} = this.options;
this.destroy();
// add classes to the table
if (Array.isArray(this.options.classes)) {
this.el.classList.add(...this.options.classes);
}
if (reorder) {
// reorder logic
if (!this.options.trAttributes) this.options.trAttributes = [];
let {
listeners,
handle,
tdClassChanges
} = this.options.reorder;
if (!listeners) listeners = {};
if (!tdClassChanges) tdClassChanges = {};
// returns {x,y} from event regardless of whether it is a touch event or not
const getXY = (e) => {
if (e.touches) {
return {
x: e.touches[0].clientX,
y: e.touches[0].clientY
};
}
return {
x: e.clientX,
y: e.clientY
};
};
let isDragging = false;
// utilizes v1.0 event listener type
const dragStart = ({ event }) => {
event.preventDefault();
isDragging = true;
const tempTr = document.createElement('tr');
const td = document.createElement('td');
td.colSpan = this.headers.length;
td.style.height = '100%';
td.classList.add(...(tdClassChanges.tempTr ? tdClassChanges.tempTr : []));
tempTr.appendChild(td);
tempTr.id = 'temp-tr';
const tr = event.target.closest('tr');
tempTr.style.height = `${tr.offsetHeight}px`;
tr.style.transition = '';
tr.insertAdjacentElement('afterend', tempTr);
tr.querySelectorAll('td').forEach(td => {
td.classList.add(...(tdClassChanges.dragging ? tdClassChanges.dragging : []));
td.style.zIndex = '99999';
});
tr.style.cursor = 'grabbing !important';
tr.style.userSelect = 'none';
tr.style.position = 'fixed';
const { x, y } = getXY(event);
tr.dataset.x = x;
tr.dataset.y = y;
};
let lastTr;
const dragging = ({ event }) => {
if (!isDragging) return;
// console.log('dragging');
event.preventDefault();
const tr = event.target.closest('tr');
if (tr.style.position !== 'fixed') return;
const { x, y } = getXY(event);
const dx = x - tr.dataset.x;
const dy = y - tr.dataset.y;
tr.style.transform = `translate(${dx}px, ${dy}px)`;
// return;
const foundTr = this.rows.find(r => {
if (r.el == tr) return;
const rRect = r.el.getBoundingClientRect();
const trRect = tr.getBoundingClientRect();
return trRect.y + trRect.height / 2 > rRect.y && trRect.y + trRect.height / 2 < rRect.y + rRect.height;
});
if (foundTr) {
if (foundTr != lastTr) {
this.hideInsertRows();
if (lastTr) {
lastTr.el.querySelectorAll('td').forEach(td => {
td.classList.remove(...(tdClassChanges.swap ? tdClassChanges.swap : []));
});
}
foundTr.el.querySelectorAll('td').forEach(td => {
td.classList.add(...(tdClassChanges.swap ? tdClassChanges.swap : []));
});
// return;
this.showInsertRows(foundTr);
}
lastTr = foundTr;
const { above, below } = foundTr.insertRows;
const trRect = tr.getBoundingClientRect();
const aboveRect = above.el.getBoundingClientRect();
const belowRect = below.el.getBoundingClientRect();
if (trRect.y + trRect.height / 2 > aboveRect.y + aboveRect.height / 2) {
above.el.classList.add(...(tdClassChanges.insert ? tdClassChanges.insert : []));
// allowDragEnd = false;
} else {
above.el.classList.remove(...(tdClassChanges.insert ? tdClassChanges.insert : []));
// allowDragEnd = true;
}
if (trRect.y + trRect.height / 2 < belowRect.y + belowRect.height / 2) {
below.el.classList.add(...(tdClassChanges.insert ? tdClassChanges.insert : []));
allowDragEnd = false;
} else {
below.el.classList.remove(...(tdClassChanges.insert ? tdClassChanges.insert : []));
// allowDragEnd = true;
}
}
};
// let allowDragEnd = true;
const dragEnd = (e) => {
if (!isDragging) return;
e.event.preventDefault();
// console.log('Drag end');
const tr = e.event.target.closest('tr');
tr.style.cursor = '';
tr.style.userSelect = '';
tr.style.position = '';
// animate back to original position
tr.style.transition = 'transform 0.2s ease-in-out';
tr.style.transform = '';
const tempTr = this.el.querySelector('#temp-tr');
if (tempTr) tempTr.remove();
this.hideInsertRows();
this.el.querySelectorAll('td').forEach(td => {
td.classList.remove(...(tdClassChanges.swap ? tdClassChanges.swap : []));
td.classList.remove(...(tdClassChanges.dragging ? tdClassChanges.dragging : []));
td.classList.remove(...(tdClassChanges.insert ? tdClassChanges.insert : []));
td.style.zIndex = '';
});
isDragging = false;
};
this.options.trAttributes.push({
attribute: 'data-swap',
value: 'false'
}, {
attribute: 'data-insert',
value: 'false'
});
this.headers.unshift({
__drag: true,
title: 'Drag',
getData: () => {
if (handle) return handle;
const i = document.createElement('i');
i.classList.add('material-icons');
i.innerText = 'drag_indicator';
return i;
},
td: {
listeners: [{
event: 'mousedown',
action: dragStart,
callback: listeners.onDragStart ? listeners.onDragStart : () => {}
}, {
event: 'touchstart',
action: dragStart,
callback: listeners.onDragStart ? listeners.onDragStart : () => {}
}, {
event: 'mousemove',
action: dragging,
callback: listeners.onDrag ? listeners.onDrag : () => {}
}, {
event: 'touchmove',
action: dragging,
callback: listeners.onDrag ? listeners.onDrag : () => {}
}, {
event: 'mouseup',
action: dragEnd,
callback: listeners.onDragEnd ? listeners.onDragEnd : () => {}
}, {
event: 'touchend',
action: dragEnd,
callback: listeners.onDragEnd ? listeners.onDragEnd : () => {}
}, {
event: 'mouseleave',
action: dragEnd,
callback: listeners.onDragEnd ? listeners.onDragEnd : () => {}
}, {
event: 'touchcancel',
action: dragEnd,
callback: listeners.onDragEnd ? listeners.onDragEnd : () => {}
}],
attributes: [{
attribute: 'style',
value: 'cursor: grab; user-select: none;'
}]
}
});
this.headers = this.headers.filter((h, i) => this.headers.findIndex(h2 => h2.title === h.title) === i);
// insert 2 full span rows between each row
this.data = this.data.reduce((a, c, i) => {
if (i === 0) return [{
__insertRow: true
}, c, {
__insertRow: true
}];
return [...a, { // insert 2 for stripes
__insertRow: true
},
c,
{
__insertRow: true
}
];
}, []);
}
this.renderHeaders();
this.renderRows();
if (caption) {
if (typeof caption == 'object') {
const {
content,
attributes,
listeners,
classes
} = caption;
const captionEl = document.createElement('caption');
if (typeof content == string) captionEl.innerText = content;
else captionEl.appendChild(content);
if (attributes) attributes.forEach(attr => {
captionEl.setAttribute(attr.attribute, attr.value);
});
if (listeners) listeners.forEach(listener => {
captionEl.addEventListener(listener.event, listener.action);
});
if (classes) captionEl.classList.add(...classes);
// append at top
this.el.insertBefore(captionEl, this.el.firstChild);
} else {
const captionEl = document.createElement('caption');
captionEl.innerText = caption;
this.el.insertBefore(captionEl, this.el.firstChild);
}
}
// makes all columns the same width
if (evenColumns) {
const width = this.el.offsetWidth;
this.columns.forEach(col => {
col.cells.forEach(cell => {
cell.el.style.width = `${width / this.columns.length}px`;
});
});
}
// JQuery DataTables
if (this.options.dataTable || this.options.datatable) {
$(this.el).DataTable(this.options.dataTable || this.options.datatable);
}
}
/**
*
* @param {TableRow} row Shows the insert rows above and below the given row
* @returns {Array<TableRow>} The insert rows
* @memberof Table
* @private
* @since 1.0.0
* @version 1.0.0
* @example
* table.showInsertRows(table.rows[0]);
*/
showInsertRows(row) {
console.log('Showing insert rows', row);
row.insertRows.above.show();
row.insertRows.below.show();
row.insertRows.above.el.style.height = row.el.offsetHeight + 'px';
row.insertRows.below.el.style.height = row.el.offsetHeight + 'px';
this.shownInsertRows.push(row.insertRows.above, row.insertRows.below);
return [row.insertRows.above, row.insertRows.below];
}
/**
* Hides all the insert rows
* @returns {void}
* @memberof Table
* @private
* @since 1.0.0
* @version 1.0.0
* @example
* table.hideInsertRows();
*/
hideInsertRows() {
let { reorder: { tdClassChanges } } = this.options;
if (!tdClassChanges) tdClassChanges = {};
this.shownInsertRows.forEach(r => {
r.hide();
r.el.classList.remove(...(tdClassChanges.insert ? tdClassChanges.insert : []));
});
this.shownInsertRows = [];
}
/**
* Renders the table headers (Automatically called by `Table.render`)
* @returns {void}
* @memberof Table
* @private
* @since 1.0.0
* @version 1.0.0
* @example
* table.renderHeaders();
*/
renderHeaders() {
const thead = document.createElement('thead');
const tr = document.createElement('tr');
const tfoot = document.createElement('tfoot');
const tfootTr = document.createElement('tr');
const {
fixedHeaders,
editable,
minimize
} = this.options;
// test if duplicate h.title || h.key || h.name
const hasDuplicates = this.headers.some((h, i) => this.headers.findIndex(h2 => h2.title === h.title) !== i);
if (hasDuplicates && editable) {
console.warn('Duplicate header titles found. This may cause unexpected behavior on `Table.content`.');
}
this.tableHeaders = new TableRow([]);
this.columns = this.headers.map((h, i) => {
if (!h) return;
const th = new TableHeader(h.title);
const {
minimize,
sort,
th: _thInfo
} = h;
let thClasses,
thAttributes;
if (_thInfo) {
thClasses = _thInfo.classes;
thAttributes = _thInfo.attributes;
}
if (minimize) {
const i = document.createElement('i');
i.classList.add('material-icons');
if (h.__minimized) {
i.innerText = 'chevron_right';
th.el.innerHTML = '';
th.el.appendChild(i);
} else {
i.innerText = 'chevron_left';