-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
1352 lines (1212 loc) · 48 KB
/
script.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
// Scrollbar
const ps = new PerfectScrollbar("#cells", {
wheelSpeed: 10,
wheelPropagation: true,
swipeEasing: true
});
// Sheet Column Title and Row Number
for (let i = 1; i <= 100; i++) {
let columnNumber = i;
let columnTitle = "";
while (columnNumber != 0) {
columnNumber--;
let remainder = columnNumber % 26
columnTitle = String.fromCharCode(65 + remainder) + columnTitle;
columnNumber = Math.floor(columnNumber / 26);
}
$("#columns").append(`<div class="column-name column-${i}" id="${columnTitle}">${columnTitle}</div>`);
$("#rows").append(`<div class="row-name">${i}</div>`);
}
//cell data init
// new structure, only store values of those cells whose default properties have been changed
/*
cellData = {
"Sheet1": {
7: {
1: {...defaultProperties},
2: {...defaulProperties}
},
2: {
5: {...}
}
},
"Sheet2": {
...
}
}
*/
let cellData = {
"Sheet1": {}
};
// Keeping track of sheets
let selectedSheet = "Sheet1";
let totalSheets = 1;
let lastAddedSheet = 1;
let save = true;
// The default properties every cell has, applied in css
let defaultProperties = {
"font-family": "Times New Roman",
"font-size": "18",
"text": "",
"bold": false,
"italic": false,
"underlined": false,
"alignment": "left",
"color": "#000000",
"bgcolor": "#ffffff",
"upStream": [],
"downStream": []
};
// Generating cells
for (let i = 1; i <= 100; i++) {
let row = $('<div class="cell-row"></div>');
for (let j = 1; j <= 100; j++) {
row.append(`<div id="row-${i}-col-${j}" class="input-cell" contenteditable="false"></div>`);
}
$("#cells").append(row);
}
// Row Number & Column Titles scroll with cell scroll
$("#cells").scroll(function (e) {
$("#columns").scrollLeft(this.scrollLeft);
$("#rows").scrollTop(this.scrollTop);
});
// get row and col number of current cell
const getRowColumn = (cell) => {
let id = $(cell).attr("id");
let idArray = id.split("-");
let rowID = parseInt(idArray[1]);
let colID = parseInt(idArray[3]);
return [rowID, colID];
}
// get row and col number of adjacent cells
const getAdjacentCells = (row, col) => {
let top = $(`#row-${row - 1}-col-${col}`);
let left = $(`#row-${row}-col-${col - 1}`);
let down = $(`#row-${row + 1}-col-${col}`);
let right = $(`#row-${row}-col-${col + 1}`);
return [top, left, down, right];
}
// Double clicking on a cell makes it editable and focuses on that
$(".input-cell").dblclick(function (e) {
// Removes all selected cells first and selects current cell
$(".input-cell.selected").removeClass("selected top-selected down-selected left-selected right-selected");
$(this).addClass("selected");
$(this).attr("contenteditable", "true");
$(this).focus();
});
// Upon clicking elsewhere
$(".input-cell").blur(function (e) {
// making the cells uneditable
$(this).attr("contenteditable", "false");
// storing text in cellData object
updateCellData("text", $(this).text());
});
// Upon single click
$(".input-cell").click(function (e) {
// getting row number and column number of current cell
const [rowID, colID] = getRowColumn(this);
// getting neighbouring cells wrapped in jquery object
const [top, left, down, right] = getAdjacentCells(rowID, colID);
// checking if currently clicked cell has selected class and control key is pressed
if ($(this).hasClass("selected") && e.ctrlKey) {
// then unselect the current cell and remove classes from adjacent cells
unselectCell(this, e, top, left, down, right);
}
else {
// select the current cell and if adjacent cells are selected, add relevant classes to them
selectCell(this, e, top, left, down, right);
}
});
// Handles selection of current cell
function selectCell(element, event, top, left, down, right) {
// If control key was pressed simultaneously
if (event.ctrlKey) {
// if top cell exists
let topSelect;
if (top) {
topSelect = top.hasClass("selected");
}
// if down cell exists
let downSelect;
if (down) {
downSelect = down.hasClass("selected");
}
// if left cell exists
let leftSelect;
if (left) {
leftSelect = left.hasClass("selected");
}
// if right cell exists
let rightSelect;
if (right) {
rightSelect = right.hasClass("selected");
}
// if top cell is selected
if (topSelect) {
top.addClass("down-selected");
$(element).addClass("top-selected");
}
// if left cell is selected
if (leftSelect) {
left.addClass("right-selected");
$(element).addClass("left-selected");
}
// if down cell is selected
if (downSelect) {
down.addClass("top-selected");
$(element).addClass("down-selected");
}
// if right cell is selected
if (rightSelect) {
right.addClass("left-selected");
$(element).addClass("right-selected");
}
} else {
// If control key was not pressed then remove classes from previous selections
$(".input-cell.selected").removeClass("selected top-selected down-selected left-selected right-selected");
}
// Adding selected class to current selection
$(element).addClass("selected");
// Updating the header based on data in cellData object
changeHeader(getRowColumn(element));
}
// Handles cell property display on menu-icon bar depending upon property of that cell in cellData object
function changeHeader([rowID, colID]) {
let data;
// if cell exists in cellData
if (cellData[selectedSheet][rowID - 1] && cellData[selectedSheet][rowID - 1][colID - 1]) {
data = cellData[selectedSheet][rowID - 1][colID - 1];
}
else {
// if that row and column didn't exist in cellData
data = defaultProperties;
}
// deselecting the previously selected icon
$(".alignment.selected").removeClass("selected");
// selecting the matching alignment icon
$(`.alignment[data-type=${data.alignment}]`).addClass("selected");
// Updating the font style icon selections
updateFontStyleHeader(data, "bold");
updateFontStyleHeader(data, "italic");
updateFontStyleHeader(data, "underlined");
// Matching the cell color and text color icon div selections to current cell's props
$("#fill-color").css("border-bottom", `4px solid ${data.bgcolor}`);
$("#text-color").css("border-bottom", `4px solid ${data.color}`);
// Updates the value of font-size and family dropdowns
$("#font-family").val(data["font-family"]);
$("#font-size").val(data["font-size"]);
// changing the font of selected dropdown item
$("#font-family").css("font-family", data["font-family"]);
}
// Handles font-style icon changes based on currently selected property
function updateFontStyleHeader(data, property) {
// if the value of property in data object is true
if (data[property]) {
$(`#${property}`).addClass("selected");
}
else {
$(`#${property}`).removeClass("selected");
}
}
// Handles unselection of cells
function unselectCell(element, event, top, left, down, right) {
// if the user was not writing data in cell, then only remove classes
if ($(element).attr("contenteditable") == "false") {
if ($(element).hasClass("top-selected")) {
top.removeClass("down-selected");
}
if ($(element).hasClass("left-selected")) {
left.removeClass("right-selected");
}
if ($(element).hasClass("down-selected")) {
down.removeClass("top-selected");
}
if ($(element).hasClass("right-selected")) {
right.removeClass("left-selected");
}
$(element).removeClass("selected top-selected down-selected left-selected right-selected");
}
}
// For selecting cells with mouse click and drag
let startCellSelected = false;
let startCell = {};
let endCell = {};
let scrollXRStarted = false;
let scrollXLStarted = false;
// let scrollYTStarted = false;
// let scrollYDStarted = false;
// only used for scrolling/selecting start cell
$(".input-cell").mousemove(function (e) {
if (e.buttons == 1) {
e.preventDefault();
if (e.pageX > ($(window).width() - 10) && !scrollXRStarted) {
scrollXR();
}
else if (e.pageX < 10 && !scrollXLStarted) {
scrollXL();
}
// if(e.pageY > ($(window).height() - 30) && !scrollYDStarted) {
// scrollYD();
// }
// else if(e.pageY > 222 && e.pageY < 250 && !scrollYTStarted) {
// scrollYT();
// }
if (!startCellSelected) {
let [rowID, colID] = getRowColumn(this);
startCell = { "rowID": rowID, "colID": colID };
startCellSelected = true;
$(".input-cell.selected").attr("contenteditable", "false");
selectSubMatrix(startCell, startCell);
}
}
else {
startCellSelected = false;
}
});
// selects end cell and stops scrolling
$(".input-cell").mouseenter(function (e) {
if (e.buttons == 1) {
if (e.pageX < ($(window).width() - 10) && scrollXRStarted) {
clearInterval(scrollXRInterval);
scrollXRStarted = false;
}
if (e.pageX > 10 && scrollXLStarted) {
clearInterval(scrollXLInterval);
scrollXLStarted = false;
}
// if(e.pageY > 250 || e.pageY < 222 && scrollYTStarted) {
// clearInterval(scrollYTInterval);
// scrollYTStarted = false;
// }
// if(e.pageY < $(window).height() - 30 && scrollYDStarted) {
// clearInterval(scrollYDInterval);
// scrollYDStarted = false;
// }
let [rowID, colID] = getRowColumn(this);
endCell = { "rowID": rowID, "colID": colID };
selectSubMatrix(startCell, endCell);
}
});
// renders selection via mouse left btn click + drag
function selectSubMatrix(start, end) {
$(".input-cell.selected").removeClass("selected top-selected down-selected left-selected right-selected");
for (let i = Math.min(start.rowID, end.rowID); i <= Math.max(start.rowID, end.rowID); i++) {
for (let j = Math.min(start.colID, end.colID); j <= Math.max(start.colID, end.colID); j++) {
let [top, left, down, right] = getAdjacentCells(i, j);
let currentCell = $(`#row-${i}-col-${j}`)[0];
selectCell(currentCell, { ctrlKey: true }, top, left, down, right);
}
}
}
// selection + scrolling
// horizontal right
let scrollXRInterval;
function scrollXR() {
scrollXRStarted = true;
scrollXRInterval = setInterval(() => {
$("#cells").scrollLeft($("#cells").scrollLeft() + 100);
}, 100);
}
// horizontal left
let scrollXLInterval;
function scrollXL() {
scrollXLStarted = true;
scrollXLInterval = setInterval(() => {
$("#cells").scrollLeft($("#cells").scrollLeft() - 100);
}, 100);
}
// vertical up
// let scrollYTInterval;
// function scrollYT() {
// scrollYTInterval = setInterval(() => {
// $("#cells").scrollTop($("#cells").scrollTop() - 50);
// }, 100);
// }
// // vertical down
// let scrollYDInterval;
// function scrollYD() {
// scrollYDInterval = setInterval(() => {
// $("#cells").scrollTop($("#cells").scrollTop() + 50);
// }, 100);
// }
// handles selection + scrolling
$(".data-container").mousemove(function (e) {
if (e.buttons == 1) {
e.preventDefault();
if (e.pageX > ($(window).width() - 10) && !scrollXRStarted) {
scrollXR();
}
else if (e.pageX < 10 && !scrollXLStarted) {
scrollXL();
}
// if(e.pageY > ($(window).height() - 30) && !scrollYDStarted) {
// scrollYD();
// }
// else if(e.pageY > 222 && e.pageY < 250 && !scrollYTStarted) {
// scrollYT();
// }
}
});
// stops scrolling
$(".data-container").mouseup(function (e) {
clearInterval(scrollXRInterval);
clearInterval(scrollXLInterval);
scrollXLStarted = false;
scrollXRStarted = false;
// clearInterval(scrollYTInterval);
// clearInterval(scrollYDInterval);
// scrollYTStarted = false;
// scrollYDStarted = false;
// console.log("mouseup");
});
// handling text-alignment
$(".alignment").click(function (e) {
let alignment = $(this).attr("data-type");
$(".alignment.selected").removeClass("selected");
$(this).addClass("selected");
$(".input-cell.selected").css("text-align", alignment);
updateCellData("alignment", alignment);
});
// handling text styles
$("#bold").click(function (e) {
setStyle(this, "bold", "font-weight", "bold");
});
$("#italic").click(function (e) {
setStyle(this, "italic", "font-style", "italic");
});
$("#underlined").click(function (e) {
setStyle(this, "underlined", "text-decoration", "underline");
});
// Handles click on text-style icons
function setStyle(element, property, key, value) {
if ($(element).hasClass("selected")) {
$(element).removeClass("selected");
$(".input-cell.selected").css(key, "");
updateCellData(property, false);
}
else {
$(element).addClass("selected");
$(".input-cell.selected").css(key, value);
updateCellData(property, true);
}
}
// renders color picker jquery
// onColorSelected is invoked twice on page load
$(".pick-color").colorPick({
'initialColor': "#ABCD",
'allowRecent': true,
'recentMax': 5,
'allowCustomColor': false,
'palette': ["#1abc9c", "#16a085", "#2ecc71", "#27ae60", "#3498db", "#2980b9", "#9b59b6", "#8e44ad", "#34495e", "#2c3e50", "#f1c40f", "#f39c12", "#e67e22", "#d35400", "#e74c3c", "#c0392b", "#ecf0f1", "#bdc3c7", "#95a5a6", "#7f8c8d"],
'onColorSelected': function () {
if (this.color != "#ABCD") {
if ($(this.element.children()[1]).attr("id") == "fill-color") {
$(".input-cell.selected").css("background-color", this.color);
$("#fill-color").css("border-bottom", `4px solid ${this.color}`);
updateCellData("bgcolor", this.color);
}
if ($(this.element.children()[1]).attr("id") == "text-color") {
$(".input-cell.selected").css("color", this.color);
$("#text-color").css("border-bottom", `4px solid ${this.color}`);
updateCellData("color", this.color);
}
}
}
});
// Handles click on image
// Clicks the div which has color palette
$("#fill-color").click(function (e) {
setTimeout(() => {
$(this).parent().click();
}, 10);
});
$("#text-color").click(function (e) {
setTimeout(() => {
$(this).parent().click();
}, 10);
});
// Handles change in font-size/font-family
$(".menu-selector").change(function (e) {
let value = $(this).val();
let key = $(this).attr("id");
if (key == "font-family") {
$("#font-family").css(key, value);
}
if (!isNaN(value)) {
value = parseInt(value);
}
$(".input-cell.selected").css(key, value);
updateCellData(key, value);
});
// writing data to the cellData object
function updateCellData(property, value) {
let newCellData = cellData;
// if the value is not equal to default value
if (value != defaultProperties[property]) {
// iterate over each selected cell
$(".input-cell.selected").each(function (index, data) {
let [rowID, colID] = getRowColumn(data);
// checking if row exists in DB or not
// if it exists, that means some cell in that row was updated
// if it doesnt, that means first time changes
if (cellData[selectedSheet][rowID - 1] == undefined) {
cellData[selectedSheet][rowID - 1] = {};
cellData[selectedSheet][rowID - 1][colID - 1] = { ...defaultProperties, "upStream": [], "downStream": [] };
cellData[selectedSheet][rowID - 1][colID - 1][property] = value;
}
else {
// checking if that particular cell in row exists in DB or not
if (cellData[selectedSheet][rowID - 1][colID - 1] == undefined) {
cellData[selectedSheet][rowID - 1][colID - 1] = { ...defaultProperties, "upStream": [], "downStream": [] };
cellData[selectedSheet][rowID - 1][colID - 1][property] = value;
}
else {
cellData[selectedSheet][rowID - 1][colID - 1][property] = value;
}
}
});
}
// The value is being changed back to the default value
else {
$(".input-cell.selected").each(function (index, data) {
let [rowID, colID] = getRowColumn(data);
// checking if column exists, if it doesn't, that means default props are already set
if (cellData[selectedSheet][rowID - 1] && cellData[selectedSheet][rowID - 1][colID - 1]) {
cellData[selectedSheet][rowID - 1][colID - 1][property] = value;
// checking if the current object has become equal to default object
if (JSON.stringify(cellData[selectedSheet][rowID - 1][colID - 1]) == JSON.stringify(defaultProperties)) {
// Deleting cell column when it becomes default
delete cellData[selectedSheet][rowID - 1][colID - 1];
// Deleting row if empty
if (Object.keys(cellData[selectedSheet][rowID - 1]).length == 0) {
delete cellData[selectedSheet][rowID - 1];
}
}
}
});
}
if (save && JSON.stringify(newCellData) != JSON.stringify(cellData)) {
save = false;
}
}
// clicking anywhere on screen closes the sheet-options-modal
$(".app-container").click(function (e) {
$(".sheet-options-modal").remove();
// $(".file-options-modal").remove();
})
// Attaching event listeners to newly added sheet-tabs
function addSheetEvents() {
// On adding new sheet, it gets selected
// Adding event listener only on the selected sheet
$(".sheet-tab.selected").on("contextmenu", function (e) {
// prevents opening of context menu on right mouse btn click
e.preventDefault();
// if the clicked upon sheet is not selected
if ($(this).hasClass("selected") == false) {
// removing selection from current sheet
$(".sheet-tab.selected").removeClass("selected");
// Selecting the clicked upon sheet
$(this).addClass("selected");
selectSheet();
}
// Removing any previously opened modals
$(".sheet-options-modal").remove();
// Creating a new modal
let modal = $(`<div class="sheet-options-modal">
<div class="option sheet-rename">Rename</div>
<div class="option sheet-delete">Delete</div>
</div>`);
// x-coordinate of modal in UI
modal.css({ "left": e.pageX });
$(".app-container").append(modal);
// Handles Rename click event
$(".sheet-rename").click(function (e) {
// Creating a new modal
let renameModal = $(`<div class="sheet-modal-parent">
<div class="sheet-rename-modal">
<div class="sheet-modal-title">Rename Sheet</div>
<div class="sheet-modal-input-container">
<span class="sheet-modal-input-title">Rename Sheet To: </span>
<input type="text" class="sheet-modal-input" />
</div>
<div class="sheet-modal-confirmation">
<div class="button yes-btn">OK</div>
<div class="button no-btn">Cancel</div>
</div>
</div>
</div>`);
$(".app-container").append(renameModal);
// Cancel button closes the Modal
$(".no-btn").click(function (e) {
$(".sheet-modal-parent").remove();
});
// OK button calls renameSheet
$('.yes-btn').click(function (e) {
renameSheet();
});
// Enter press calls renameSheet
$(".sheet-modal-input").keypress(function (e) {
if (e.key == "Enter") {
renameSheet();
}
})
});
// Handles Delete option click
$(".sheet-delete").click(function (e) {
// Checking if it's possible to delete sheet
if (totalSheets > 1) {
// Creating a new modal
let deleteModal = $(`<div class="sheet-modal-parent">
<div class="sheet-delete-modal">
<div class="sheet-modal-title">${selectedSheet}</div>
<div class="sheet-modal-detail-container">
<span class="sheet-modal-detail-title">Are you sure?</span>
</div>
<div class="sheet-modal-confirmation">
<div class="button yes-btn">
<div class="material-icons delete-icon">delete</div>
Delete
</div>
<div class="button no-btn">Cancel</div>
</div>
</div>
</div>`);
$(".app-container").append(deleteModal);
// Cancel btn click
$(".no-btn").click(function (e) {
$(".sheet-modal-parent").remove();
});
// Invokes delete sheet
$(".yes-btn").click(function (e) {
deleteSheet();
});
}
// When there is single sheet
else {
let alertBox = $(`<div class="sheet-modal-parent">
<div class="alert-box">
<span class="alert-text">Sorry! It is not possible to delete your only sheet!</span>
</div>
</div>`);
$(".app-container").append(alertBox);
setTimeout(() => {
$(".sheet-modal-parent").remove();
}, 1500);
}
});
});
// Attaching click event to sheet tab when it was created
$(".sheet-tab.selected").click(function (e) {
// If the clicked upon sheet is not already selected
if (!$(this).hasClass("selected")) {
$(".sheet-tab.selected").removeClass("selected");
$(this).addClass("selected");
selectSheet();
}
});
}
// Attaching events to default sheet on page load/reload
addSheetEvents();
// Rename Sheet
function renameSheet() {
// Taking the value of name
let name = $(".sheet-modal-input").val();
// If the entered value is not empty or already present
if (name != "" && !Object.keys(cellData).includes(name)) {
// Changing the text of sheet tab
save = false;
$(".sheet-tab.selected").text(name);
// Updating the key in cellData
// This appraoch creates a dummy object and we will replace cellData with it
// These steps preserve the relative postioning of the keys in original object
let newCellData = {};
// Traversing on keys array of cellData
for (let sheet of Object.keys(cellData)) {
if (sheet == selectedSheet) {
newCellData[name] = cellData[sheet];
} else {
newCellData[sheet] = cellData[sheet];
}
}
cellData = newCellData;
selectedSheet = name;
$(".sheet-modal-parent").remove();
}
else {
// If the sheet name is invalid
$(".rename-error").remove();
$(".sheet-modal-input-container").append(`<div class="rename-error">Entered name is invalid or already exists!</div>`);
}
}
// Handles Sheet deletion
function deleteSheet() {
// Removing the modal
save = false;
$(".sheet-modal-parent").remove();
// index of the sheet being deleted
let index = Object.keys(cellData).indexOf(selectedSheet);
// Storing reference to current sheet
let currentSheet = $(".sheet-tab.selected");
// index = 0, select next sheet
if (index == 0) {
let nextSheet = currentSheet.next()[0];
if ($(nextSheet).hasClass("selected") == false) {
$(".sheet-tab.selected").removeClass("selected");
$(nextSheet).addClass("selected");
selectSheet();
}
}
// index > 0, select previous sheet
else {
let prevSheet = currentSheet.prev()[0];
if ($(prevSheet).hasClass("selected") == false) {
$(".sheet-tab.selected").removeClass("selected");
$(prevSheet).addClass("selected");
selectSheet();
}
}
// Removing sheet from UI
currentSheet.remove();
// Deleting the sheet from database
delete cellData[currentSheet.text()];
// Decrementing total Sheet Count
totalSheets--;
// console.log(cellData);
}
// Adding a blank sheet
$(".add-sheet").click(function (e) {
save = false;
lastAddedSheet += 1;
totalSheets += 1;
cellData[`Sheet${lastAddedSheet}`] = {};
$(".sheet-tab.selected").removeClass("selected");
$(".sheets-tab-container").append(`<div class="sheet-tab selected">Sheet${lastAddedSheet}</div>`);
selectSheet();
addSheetEvents();
$(".sheet-tab.selected")[0].scrollIntoView();
});
// selects sheet
function selectSheet() {
emptyPreviousSheet();
// Getting the name/key of current sheet
selectedSheet = $(".sheet-tab.selected").text();
loadCurrentSheet();
// Selects first cell
$("#row-1-col-1").click();
}
// traverse on cellData object and get the keys of rows and columns where changes were made
// Then change their css properties to all the default properties
// Removes content of previous sheet from UI
function emptyPreviousSheet() {
let data = cellData[selectedSheet];
let rowKeys = Object.keys(data);
for (let rowKey of rowKeys) {
let columnKeys = Object.keys(data[rowKey]);
let rowID = parseInt(rowKey);
for (let columnKey of columnKeys) {
let colID = parseInt(columnKey);
let cell = $(`#row-${rowID + 1}-col-${colID + 1}`);
cell.text("");
cell.css({
"font-family": "Times New Roman",
"font-size": "18px",
"font-weight": "normal",
"font-style": "normal",
"text-decoration": "none",
"text-align": "left",
"color": "#000000",
"background-color": "#ffffff"
});
}
}
}
// load the currently selected sheet on UI
function loadCurrentSheet() {
let data = cellData[selectedSheet];
let rowKeys = Object.keys(data);
for (let rowKey of rowKeys) {
let columnKeys = Object.keys(data[rowKey]);
let rowID = parseInt(rowKey);
for (let columnKey of columnKeys) {
let colID = parseInt(columnKey);
let cell = $(`#row-${rowID + 1}-col-${colID + 1}`);
cell.text(data[rowID][colID].text);
cell.css({
"font-family": data[rowID][colID]["font-family"],
"font-size": data[rowID][colID]["font-size"],
"font-weight": data[rowID][colID]["bold"] ? "bold" : "normal",
"font-style": data[rowID][colID]["italic"] ? "italic" : "normal",
"text-decoration": data[rowID][colID]["underlined"] ? "underline" : "none",
"text-align": data[rowID][colID]["alignment"],
"color": data[rowID][colID]["color"],
"background-color": data[rowID][colID]["bgcolor"]
});
}
}
}
// Left Arrow, Right Arrow click
$(".scroll-left, .scroll-right").click(function (e) {
// Storing keys in array
let keys = Object.keys(cellData);
// Finding the index of selected sheet
let selectedSheetIndex = keys.indexOf(selectedSheet);
// Storing ref to the current sheet
let currentSheet = $(".sheet-tab.selected");
// Sheets other than first sheet
if (selectedSheetIndex != 0 && $(this).text() == "arrow_left") {
let prevSheet = currentSheet.prev()[0];
if ($(prevSheet).hasClass("selected") == false) {
$(".sheet-tab.selected").removeClass("selected");
$(prevSheet).addClass("selected");
selectSheet();
}
}
// Sheets other than last sheet
else if (selectedSheetIndex != (keys.length - 1) && $(this).text() == "arrow_right") {
let nextSheet = currentSheet.next()[0];
if ($(nextSheet).hasClass("selected") == false) {
$(".sheet-tab.selected").removeClass("selected");
$(nextSheet).addClass("selected");
selectSheet();
}
}
// Adding bracket notation 0 because scrollIntoView is a JS method, not in jQuery
// Javascript methods work only on native DOM objects, not DOM objects wrapped in jQuery
// jQuery objects are arrays of DOM elements
$(".sheet-tab.selected")[0].scrollIntoView();
});
// Upon clicking the file option in menu bar
$("#menu-file").click(function (e) {
// Creating a modal
let fileModal = $(`<div class="file-modal">
<div class="file-options-modal">
<div class="close">
<div class="material-icons close-icon">arrow_circle_down</div>
<div>Close</div>
</div>
<div class="new">
<div class="material-icons new-icon">insert_drive_file</div>
<div>New</div>
</div>
<div class="open">
<div class="material-icons open-icon">folder_open</div>
<div>Open</div>
</div>
<div class="save">
<div class="material-icons save-icon">save</div>
<div>Save</div>
</div>
</div>
<div class="file-recent-modal"></div>
<div class="file-transparent"></div>
</div>`);
$(".app-container").append(fileModal);
// Animate modal opening
fileModal.animate({
width: "100vw"
}, 200);
// Handle modal closing
$(".close, .file-transparent, .new, .save, .open").click(function (e) {
fileModal.animate({
width: "0"
}, 200);
setTimeout(() => {
fileModal.remove();
}, 150);
});
// Handle click on "NEW" option
$(".new").click(function () {
// If file is already saved
if (save) {
newFile();
}
// if file is not saved, ask user
else {
let modal = $(`<div class="sheet-modal-parent">
<div class="sheet-delete-modal">
<div class="sheet-modal-title">${$(".title-bar").text()}</div>
<div class="sheet-modal-detail-container">
<span class="sheet-modal-detail-title">Do you want to save changes?</span>
</div>
<div class="sheet-modal-confirmation">
<div class="button yes-btn">Yes</div>
<div class="button no-btn">No</div>
</div>
</div>
</div>`);
$(".app-container").append(modal);
// Dont save, open new file
$(".no-btn").click(function (e) {
newFile();
modal.remove();
});
// save, then open new file
$(".yes-btn").click(function (e) {
// calls save file function
saveFile();
newFile();
modal.remove();
})
}
});
// Handles click on save option
$(".save").click(function (e) {
saveFile();
});
// Handles open option click
$(".open").click(function (e) {
openFile();
});
});
function newFile() {
// Empty the sheet
emptyPreviousSheet();
// reset DB
cellData = {
"Sheet1": {}
};
// Set values to default
totalSheets = 1;
lastAddedSheet = 1;
selectedSheet = "Sheet1";
save = true;
// Remove sheet tabs
$(".sheet-tab").remove();
// Add single sheet tab
$(".sheets-tab-container").append(`<div class="sheet-tab selected">Sheet1</div>`);
// Attach event listeners on new sheet
addSheetEvents();
// Change the file title to default title
$(".title-bar").text("Excel - Book");
// select first cell
$("#row-1-col-1").click();