-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlist.js
1608 lines (1288 loc) · 50.8 KB
/
list.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
let nowDirId;
// history.scrollRestoration = "auto";
//init
//분기해서 사용하는 거 중요함
document.addEventListener("DOMContentLoaded", function () {
if (window.location.pathname === "/list.html") {
initListPage();
} else if (window.location.pathname === "/dirList.html") {
readDBAndDisplay();
document.getElementById("dirAddButton").addEventListener("click", () => { dirAddButtonClick(); });
defaultDirSet();
}
});
/**
* 스크롤이 움직일때마다 값을 sessionStorage에 넣어줌
*/
// let scrollHeight;
// addEventListener('scroll', (event) => {
// scrollHeight = $(document).scrollTop();
// sessionStorage.setItem("scrollY", scrollHeight);
// });
/**
* 스크롤 위치 지정
*/
// $(document).ready(function() {
// const scrollY = parseInt(sessionStorage.getItem("scrollY"));
// if(scrollY && scrollY > 0){
// window.scrollTo(0, scrollY);
// }
// });
//dir추가 버튼
function dirAddButtonClick() {
var dir = document.getElementById("dir_template");
var copy = dir.content.cloneNode(true);
// 버튼 이벤트 리스너 추가
// 오 템플릿이기 때문에, 이벤트 리스너도 템플릿 생성할 때 추가하도록 해야함
const editButton = copy.querySelector(".button-edit");
const deleteButton = copy.querySelector(".button-del");
const dirLink = copy.querySelector(".dir-link");
const dirText = copy.querySelector(".dir-text");
editButton.addEventListener("click", function () {
setupDirEditEvent(this);
});
deleteButton.addEventListener("click", function () {
setupDirDeleteEvent(this);
});
// 데이터베이스 추가
const data = [{ dir_name: '새 폴더' }];
writeDB(data, 'dirStore', function (d_id) {
// console.log(`dirAddButton 눌러쓸 때의 d_id : ${d_id}`);
copy.querySelector(".dir-list").id = d_id;
// dir_id를 사용하여 링크 생성
const dir_id = d_id;
const dirName = '새 폴더';
console.log('href생성 전');
console.log(dir_id, dirName);
// dirLink.href = `./list.html?dir_id=${dir_id}&dirname=${encodeURIComponent(dirName)}`;
//chrome-extension://ennclpjamlaabgaipfcmcffiemgkjdph/list.html?dir_id=53&dirname=NEW%20DIR
// 확장 프로그램 내의 상대 경로를 절대 경로로 변환
const extensionURL = chrome.runtime.getURL(`list.html?dir_id=${dir_id}&dirname=${encodeURIComponent(dirName)}`);
dirLink.href = extensionURL;
dirText.textContent = dirName;
console.log(dirLink.href);
document.getElementById("dir_container").appendChild(copy);
});
}
function setupDirEditEvent(button) {
const dirElement = button.closest("li");
const dirTextElement = dirElement.querySelector(".dir-text");
const currentTextValue = dirTextElement.textContent;
const dir_id = dirElement.id;
// input 생성
const inputElement = document.createElement("input");
inputElement.type = "text";
inputElement.value = currentTextValue;
inputElement.classList.add("input-dir", "editing");
const aElement = dirElement.querySelector("a");
dirElement.replaceChild(inputElement, aElement);
inputElement.focus();
inputElement.select();
dirElement.classList.add("editing");
button.classList.add("editing");
document.addEventListener("click", e => {
if (!(e.target.classList.contains("editing"))) {
const newDirName = inputElement.value.trim();
if (newDirName !== "") {
editDB("dirStore", "dir_name", parseInt(dir_id), newDirName, true);
}
else {
alert("내용을 입력해주세요");
}
}
})
// 엔터가 눌렸을 때 수정이 완료되도록
inputElement.addEventListener("keydown", function (event) {
if (event.key === "Enter") {
const newDirName = inputElement.value.trim();
if (newDirName !== "") {
// const newDirTextElement = document.createElement("h1");
// newDirTextElement.classList.add("dir-text");
// newDirTextElement.textContent = newDirName;
// const newAElement = document.createElement("a");
// // 새로운 URL 파라미터로 dir_id와 dirname을 사용하여 페이지를 업데이트
// // newAElement.href = `./list.html?dir_id=${dir_id}&dirname=${encodeURIComponent(newDirName)}`;
// const extensionURL = chrome.runtime.getURL(`list.html?dir_id=${dir_id}&dirname=${encodeURIComponent(newDirName)}`);
// newAElement.href = extensionURL;
// console.log('edit href');
// console.log(newAElement.href);
// newAElement.appendChild(newDirTextElement);
// const buttonEdit = dirElement.querySelector(".button-edit");
// const buttonDel = dirElement.querySelector(".button-del");
// const newLiElement = document.createElement("li");
// newLiElement.classList.add("dir-list", "dir");
// newLiElement.appendChild(newAElement);
// newLiElement.appendChild(buttonEdit);
// newLiElement.appendChild(buttonDel);
// dirElement.parentNode.replaceChild(newLiElement, dirElement);
// 디렉토리 이름 데이터베이스에 업데이트
editDB("dirStore", "dir_name", parseInt(dir_id), newDirName, true);
//그냥 editDirNameDB (editDB) 함수에서 success 하면 location.reload() 하도록 코드 작성했어,,
//어차피 새로고침하니까 위에 코드는 필요 없어지는 거 아닌가 싶어서 주석처리했구! -10월 14일의 채린...-
} else {
alert("내용을 입력해주세요");
}
}
});
}
function setupDirDeleteEvent(button) {
const dirElement = button.closest("li");
const d_id = dirElement.id;
readValueDB('userHistoryStore', 'nowExecutedDir', 1)
.then(result => {
//현재 실행 중인 dir과 삭제하려는 dir이 동일하다면 "삭제할 수 없음"
if (parseInt(result) == d_id) {
console.log("dirCannotDeleteModal 보여주기");
const dirCannotDeleteModal = document.getElementById("dirCannotDeleteModal");
dirCannotDeleteModal.style.display = "flex";
const dirCannotDeletecloseBtn = dirCannotDeleteModal.querySelector(".closeBtn");
dirCannotDeletecloseBtn.addEventListener("click", e => {
dirCannotDeleteModal.style.display = "none";
})
}
//현재 실행 중인 dir과 삭제하려는 dir이 동일하지 않다면 "진짜 삭제하실?"
else {
const dirDeleteModal = document.getElementById("dirDeleteModal");
dirDeleteModal.style.display = "flex";
const dirDeleteModalcloseBtn = dirDeleteModal.querySelector(".closeBtn");
const dirDeleteModalDeleteBtn = dirDeleteModal.querySelector(".deleteBtn");
dirDeleteModalcloseBtn.addEventListener("click", e => {
dirDeleteModal.style.display = "none";
})
dirDeleteModalDeleteBtn.addEventListener("click", e => {
dirElement.parentNode.removeChild(dirElement);
deleteDirDB(d_id);
dirDeleteModal.style.display = "none";
})
}
})
.catch(error => {
console.error("에러: " + error);
});
}
// 리스트 페이지 로드 될 때
async function initListPage() {
const urlParams = new URLSearchParams(window.location.search);
const dirNameElement = document.querySelector("#dir-title");
const dirBox = document.querySelector(".dir");
var userHistoryData = await readDBbyStoreName('userHistoryStore');
var dirId = urlParams.get("dir_id");
var dirName;
var dirData;
if (dirId != null) { //dir 폴더로부터 넘어 올 때
dirData = await readDBbyStoreNameAndId('dirStore', parseInt(dirId));
} else { //dir 폴더로부터 열리는 것이 아닐 때
try {
dirId = userHistoryData[0]['recentlyExecutedDir'];
dirData = await readDBbyStoreNameAndId('dirStore', parseInt(dirId));
//recentlyExecutedDir가 삭제 됨 -> 아무 디렉토리
if (initDirName == undefined) {
var tempDir = await readDBbyStoreName('dirStore');
dirId = tempDir[0]['d_id'];
dirData = await readDBbyStoreNameAndId('dirStore', parseInt(dirId));
}
} catch (error) {
}
}
dirName = dirData['dir_name']
if (dirName != null) {
dirNameElement.textContent = dirName;
// dirNameElement.style.overflow = 'hidden';
}
//dir title 수정
var dirTitleBox = document.getElementById('dir-title-box');
dirTitleBox.addEventListener("click", () => {
// input 생성
const inputElement = document.createElement("input");
inputElement.type = "text";
inputElement.value = dirNameElement.textContent;
inputElement.classList.add("input-dir", "editing");
dirTitleBox.replaceChild(inputElement, dirNameElement);
inputElement.focus();
inputElement.select();
dirTitleBox.classList.add("editing");
//엔터 완료
inputElement.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
const newDirName = inputElement.value.trim();
if (newDirName !== "") {
editDB("dirStore", "dir_name", parseInt(dirId), newDirName);
location.reload();
} else {
alert("내용을 입력해주세요");
}
}
});
// document.addEventListener("click", e => {
// if (!(e.target.classList.contains("editing"))) {
// const newDirName = inputElement.value.trim();
// if (newDirName !== "") {
// editDB("dirStore", "dir_name", parseInt(dirId), newDirName);
// document.reload();
// }
// else {
// alert("내용을 입력해주세요");
// }
// }
// })
});
nowDirId = dirId;
editUserHistoryRecentlyVisitedDB('userHistoryStore', 1, nowDirId);
var nowExecutedDir = userHistoryData[0]['nowExecutedDir'];
if (dirId == nowExecutedDir) {
dirBox.style.backgroundColor = '#DFF5E5';
}
addEvent();
//스크롤 위치 지정
window.scrollTo(0, dirData.scroll);
let scrollHeight;
let topButton = document.querySelector('#button-top');
addEventListener('scroll', (event) => {
scrollHeight = window.scrollY || document.documentElement.scrollTop;
console.log(`scroll 위치 : ${scrollHeight}`);
editDB("dirStore", "scroll", parseInt(nowDirId), scrollHeight, false);
if (scrollHeight != 0) {
topButton.style.opacity = "100";
} else {
topButton.style.opacity = "0";
}
});
topButton.addEventListener('click', (event) => {
window.scrollTo(0, 0);
});
}
function startBtnEvent() {
let modal = document.getElementById("startModal");
let content = document.getElementById("startModalContent");
let dirBox = document.getElementById("dir-title");
let dirName = dirBox.textContent;
content.innerHTML = "<b>[" + dirName + "]</b> <br>폴더에 검색 기록이 저장됩니다.";
modal.classList.replace("hidden", "clicked");
setTimeout(() => { modal.classList.replace("clicked", "hidden"); }, 5000);
//console.log("startEvent executed");
}
// //dir-name 에 title 부여
//list.html에서만 가능하니 주의해야함
// document.getElementById("dir-name").title =
// document.getElementById("dir-name").innerHTML;
// db에서 데이터를 읽는 함수
function readDBbyStoreName(store_name) {
return new Promise((resolve, reject) => {
var request = indexedDB.open("HeyGoogler", 1);
request.onerror = function (event) {
reject(new Error("DB error: " + event.target.errorCode));
};
request.onsuccess = function (event) {
const db = request.result;
const transaction = db.transaction([store_name], "readonly");
const objectStore = transaction.objectStore(store_name);
const requestGetAll = objectStore.getAll();
requestGetAll.onsuccess = function (event) {
const data = event.target.result;
console.log('readDB 테스트 실행 데이터 값 : ');
console.log(data);
resolve(data); // 비동기 작업이 완료되면 데이터를 반환
};
requestGetAll.onerror = function (event) {
reject(new Error("데이터 읽기 실패"));
};
};
});
}
// db에서 데이터를 읽는 함수
function readDBbyStoreNameAndId(store_name, id) {
return new Promise((resolve, reject) => {
var request = indexedDB.open("HeyGoogler", 1);
request.onerror = function (event) {
reject(new Error("DB error: " + event.target.errorCode));
};
request.onsuccess = function (event) {
const db = request.result;
const transaction = db.transaction([store_name], "readonly");
const objectStore = transaction.objectStore(store_name);
const requestGet = objectStore.get(parseInt(id));
requestGet.onsuccess = function (event) {
const data = event.target.result;
console.log('readDB dirname by id 테스트 실행 데이터 값 : ');
console.log(data);
resolve(data); // 비동기 작업이 완료되면 데이터를 반환
};
requestGet.onerror = function (event) {
reject(new Error("데이터 읽기 실패"));
};
};
});
}
async function getNowDirId() {
try {
var userHistoryData = await readDBbyStoreName('userHistoryStore');
console.log('현재 실ㅇ중인 ');
console.log(userHistoryData[0]['nowExecutedDir']);
data = userHistoryData[0]['nowExecutedDir'];
return data;
} catch (error) {
return 0;
}
}
/********************************************************************************************************* */
var reloadButton = document.getElementById("button-reload");
var folderButton = document.getElementById("button-folder");
var startButton = document.getElementById("button-start");
var stopButton = document.getElementById("button-stop");
chrome.action.getBadgeText({}, (txt) => {
if (txt == "ON") {
startButton.src = "images/icon_start_true.svg";
} else {
startButton.src = "images/icon_start.svg";
}
});
//stopButton 눌림 action
stopButton.addEventListener("mousedown", () => {
stopButton.src = "images/icon_stop_true.svg";
});
stopButton.addEventListener("mouseup", () => {
stopButton.src = "images/icon_stop.svg";
});
//reload
reloadButton.addEventListener("click", () => {
location.reload();
console.log("reloaded");
});
//tooltip
reloadButton.addEventListener("mouseover", () => {
document.getElementById("tooltip-reload").style.display = "block";
});
reloadButton.addEventListener("mouseout", () => {
document.getElementById("tooltip-reload").style.display = "none";
});
folderButton.addEventListener("mouseover", () => {
document.getElementById("tooltip-folder").style.display = "block";
});
folderButton.addEventListener("mouseout", () => {
document.getElementById("tooltip-folder").style.display = "none";
});
startButton.addEventListener("mouseover", () => {
document.getElementById("tooltip-start").style.display = "block";
});
startButton.addEventListener("mouseout", () => {
document.getElementById("tooltip-start").style.display = "none";
});
stopButton.addEventListener("mouseover", () => {
document.getElementById("tooltip-stop").style.display = "block";
});
stopButton.addEventListener("mouseout", () => {
document.getElementById("tooltip-stop").style.display = "none";
});
//send message to background.js when the start/stop button clicked
startButton.addEventListener("click", () => {
startButton.src = "images/icon_start_true.svg";
chrome.runtime.sendMessage({ onDirId: nowDirId, txt: "Start the extension from list.js" });
editUserHistoryNowDirDB('userHistoryStore', 1, nowDirId);
editUserHistoryRecentlyExecutedDirDB('userHistoryStore', 1, nowDirId);
document.querySelector('.dir').style.backgroundColor = '#DFF5E5';
//거의 10퍼센트 확률로 두번째거 안 먹히는데,, 계속 지속되면 처음 실행되고 다음 되록 수정
startBtnEvent();
});
stopButton.addEventListener("click", () => {
startButton.src = "images/icon_start.svg";
chrome.runtime.sendMessage("Stop the extension from list.js");
editUserHistoryNowDirDB('userHistoryStore', 1, 'none');
location.reload();
});
chrome.action.onClicked.addListener(() => {
chrome.action.getBadgeText({}, (txt) => {
if (txt == "ON") {
startButton.src = "images/icon_start_true.svg";
} else {
startButton.src = "images/icon_start.svg";
}
});
});
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message == "Auto Synchronization message") location.reload();
});
//새로운 값 입력
//db입력 함수 (backtground.js에서 동일한 코드인데 import하는 등 효율적인 방법이 없을까?
function intitDB() {
//만들면 좋을듯
}
//데이터베이수눈 비동기 작업! 콜백 함수로 전달해서 사용해야할 것
function writeDB(datas, store_name, callback) {
var request = indexedDB.open("HeyGoogler", 1);
request.onerror = function (event) {
console.log("DB error", event.target.errorCode);
};
request.onsuccess = function (event) {
const db = request.result;
const transaction = db.transaction([store_name], "readwrite");
transaction.oncomplete = function (event) {
console.log("성공");
};
transaction.onerror = function (event) {
console.log("실패");
};
const objectStore = transaction.objectStore(store_name);
for (const data of datas) {
const request = objectStore.add(data);
request.onsuccess = function (event) {
console.log(`dirDB 입력 완료 : ${event.target.result}`);
// return event.target.result;
callback(event.target.result);
};
}
};
}
//edit 재사용성을 높이고 샆어
//민지 함수랑 같이 확인
function editDirNameDB(id, name) {
var request = indexedDB.open("HeyGoogler", 1);
request.onerror = function (event) {
console.log("DB error", event.target.errorCode);
};
request.onsuccess = function (event) {
const db = request.result;
const transaction = db.transaction('dirStore', "readwrite");
transaction.oncomplete = function (event) {
console.log("성공");
};
transaction.onerror = function (event) {
console.log("실패");
};
const objectStore = transaction.objectStore('dirStore');
//아 변수명 잘 못 지음
// console.log(`수정 get 전의 ${id} , ${id.type}`);
var requestId = objectStore.get(parseInt(id)); //주의~~!!
// console.log(`requestId ${requestId}`);
// console.log(requestId);
requestId.onerror = function (event) { console.log("requestId error"); }
requestId.onsuccess = function (event) {
var data = event.target.result;
// console.log(`수정 될 ${data}`);
data.dir_name = name;
var requestUpdate = objectStore.put(data);
requestUpdate.onerror = function (event) { console.log("requestUpdate error"); }
requestUpdate.onsuccess = function (event) { location.reload(); }
}
};
}
//재사용성 높이도록 리팩토링
function deleteDirDB(id) {
var request = indexedDB.open("HeyGoogler", 1);
request.onerror = function (event) {
console.log("DB error", event.target.errorCode);
};
request.onsuccess = function (event) {
const db = request.result;
//dirDel
const transaction = db.transaction('dirStore', "readwrite");
transaction.oncomplete = function (event) {
console.log("성공");
};
transaction.onerror = function (event) {
console.log("실패");
};
const objectStore = transaction.objectStore('dirStore');
var requestDel = objectStore.delete(parseInt(id)); //주의~~!!
requestDel.onerror = function (event) { console.log("requestId error"); }
requestDel.onsuccess = function (event) {
console.log("dir 삭제 성공");
}
//del 하위 keyword
let keywordTransaction = db.transaction('keywordStore', 'readwrite');
keywordTransaction.oncomplete = function (event) {
console.log("키워드 성공");
};
keywordTransaction.onerror = function (event) {
console.log("키워드 실패");
};
const keywordObjectStore = keywordTransaction.objectStore('keywordStore');
const keywordSearch = keywordObjectStore.index("dir_id").getAll(parseInt(id));
console.log('여기');
console.log(keywordSearch);
keywordSearch.onsuccess = (e) => {
keywords = e.target.result;
for (let i = 0; i < keywords.length; i++) {
deleteDB('keywordStore', keywords[i].id);
}
}
keywordTransaction.onerror = function (event) {
console.log("트랜잭션 오류:", event.target.error);
};
// keywordTransaction.oncomplete = function (event) {
// db.close();
// };
//del 하위 url
let urlTransaction = db.transaction('urlStore', 'readwrite');
const urlObjectStore = urlTransaction.objectStore('urlStore');
const urlSearch = urlObjectStore.index("dir_id").getAll(parseInt(id));
urlSearch.onsuccess = (e) => {
urls = e.target.result;
for (let i = 0; i < urls.length; i++) {
deleteDB('urlStore', urls[i].id);
}
}
urlTransaction.onerror = function (event) {
console.log("트랜잭션 오류:", event.target.error);
};
urlTransaction.oncomplete = function (event) {
db.close();
};
}
}
/********************************************************************************************************* */
//열려있는 객체 저장소 정보를 open_Obs 변수로 전달
var urlStore = 'urlStore';
var keyStore = 'keywordStore';
function Toggle(data) {
for (var i = 0; i < data.length; i++) {
const k = data[i].keyword;
const id = data[i].id;
const isToggled = data[i].isToggled;
console.log(id);
const kwBox = document.getElementById("green-" + k);
const pathArea = document.getElementById("white-" + k);
const toggleButton = kwBox.querySelector(".toggle_keyword");
let isPushed = isToggled;
toggleButton.addEventListener("click", () => {
// 토글 상태에 따라 컨텐츠 표시/숨김
if (isPushed) {
editDB("keywordStore", "isToggled", parseInt(id), false, false);
toggleButton.classList.add("toggleShown");
toggleButton.classList.remove("toggleHidden");
pathArea.style.maxHeight = '100vh'
pathArea.style.opacity = '1';
} else {
// 토글될 컨텐츠 숨김 (애니메이션 포함)
editDB("keywordStore", "isToggled", parseInt(id), true, false);
toggleButton.classList.add("toggleHidden");
toggleButton.classList.remove("toggleShown");
pathArea.style.maxHeight = '0';
}
isPushed = !isPushed;
})
}
}
// 데이터를 화면에 출력하는 함수
function displayURL(data) {
//컨텐츠 들어갈 위치
const container = document.getElementById('dataContainer');
// 데이터를 텍스트로 변환하여 화면에 추가
for (var i = 0; i < data.length; i++) {
const key = data[i][0];
const k = data[i][1];
const t = data[i][2];
const p = data[i][3];
const m = data[i][4];
//console.log("displayURL: "+key);
const area = document.getElementById("white-" + k);
const template = document.getElementById("path_template");
const clone = template.content.cloneNode(true);
const title = clone.querySelector(".path-box").querySelector(".title");
const path = clone.querySelector(".path-box").querySelector(".path");
const memoIcon = clone.querySelector(".path-box").querySelector(".memoIcon");
title.innerHTML = t;
path.innerHTML = p;
memoIcon.id = m;
if (!!memoIcon.id.trim()) {
memoIcon.style.display = 'block';
}
memoIcon.addEventListener("mouseover", () => {
path.innerHTML = m;
path.style.display = "flex";
path.style.fontSize = "12px";
path.style.textDecoration = "none";
})
memoIcon.addEventListener("mouseout", () => {
path.innerHTML = p;
path.style.display = "block";
path.style.fontSize = "14px";
path.style.textDecoration = "underline";
})
clone.querySelector("#tooltip-title").innerHTML = t;
clone.querySelector(".path-box").querySelector(".hyperLink").addEventListener("click", () => {
chrome.tabs.create({ url: p });
})
//삭제 기능을 위해 삭제 버튼에 데이터 id 값 추가
var deleteBtn = clone.querySelector('.white-menu1');
deleteBtn.setAttribute('key', key);
//각 삭제 버튼에 클릭 이벤트 리스너를 추가
deleteBtn.addEventListener('click', () => {
deleteDB(urlStore, key);
});
const memoBtn = clone.querySelector('.white-menu3');
let inputMemo = document.getElementById("memoInput");
memoBtn.setAttribute('key', key);
const modal = document.getElementById("modal")
let memoFlag;
memoBtn.addEventListener('click', (e) => {
modal.style.display = "flex";
memoFlag = e.target.getAttribute("key");
readValueDB('urlStore', 'memo', parseInt(memoFlag))
.then(result => {
//console.log("제대로 읽어짐****************" + result);
//console.log(typeof(result));
inputMemo.setAttribute('value', result);
})
.catch(error => {
console.log("메모 디폴트값 불러오기 에러" + error);
});
//console.log(e);
//console.log("memo버튼 클릭했을 때 memoFlag : " + memoFlag);
})
const closeBtn = modal.querySelector(".closeBtn")
closeBtn.addEventListener("click", e => {
modal.style.display = "none";
})
const memoSaveBtn = modal.querySelector(".saveBtn")
memoSaveBtn.addEventListener("click", e => {
let userInputMemo = inputMemo.value;
//console.log(userInputMemo);
//console.log("모달에서 저장 눌렀을 때 memoFlag : " + memoFlag);
//console.log("를 int로 parsing한 memoFlag : " + parseInt(memoFlag));
editDB("urlStore", "memo", parseInt(memoFlag), userInputMemo, true);
modal.style.display = "none"
})
inputMemo.addEventListener("keydown", function (event) {
if (event.key === "Enter") {
let userInputMemo = inputMemo.value;
editDB("urlStore", "memo", parseInt(memoFlag), userInputMemo, true, true);
modal.style.display = "none"
}
})
modal.addEventListener("click", e => {
const evTarget = e.target
if (evTarget.classList.contains("modal-overlay")) {
modal.style.display = "none"
}
})
const editBtn = clone.querySelector('.white-menu2');
let inputTitle = document.getElementById("titleInput");
editBtn.setAttribute('key', key);
const editmodal = document.getElementById("modal-t")
let editFlag;
editBtn.addEventListener('click', (e) => {
editmodal.style.display = "flex";
//몇 번째 요소 선택했는지 인덱스저장
editFlag = e.target.getAttribute("key");
readValueDB('urlStore', 'title', parseInt(editFlag))
.then(result => {
//console.log("제대로 읽어짐****************" + result);
//console.log(typeof(result));
inputTitle.setAttribute('value', result);
})
.catch(error => {
console.log("타이틀 디폴트값 불러오기 에러" + error);
});
})
const editcloseBtn = editmodal.querySelector(".closeBtn")
editcloseBtn.addEventListener("click", e => {
editmodal.style.display = "none";
})
const editSaveBtn = editmodal.querySelector(".saveBtn")
editSaveBtn.addEventListener("click", e => {
let userInputTitle = inputTitle.value;
if (!!userInputTitle.trim()) {
editDB("urlStore", "title", parseInt(editFlag), userInputTitle, true);
editmodal.style.display = "none"
}
})
inputTitle.addEventListener("keydown", function (event) {
if (event.key === "Enter") {
let userInputTitle = inputTitle.value;
if (!!userInputTitle.trim()) {
editDB("urlStore", "title", parseInt(editFlag), userInputTitle, true);
editmodal.style.display = "none"
}
}
})
editmodal.addEventListener("click", e => {
const editevTarget = e.target
if (editevTarget.classList.contains("modal-overlay")) {
editmodal.style.display = "none";
}
})
if (area) {
area.appendChild(clone);
}
}
}
// displayMenu();
// displayTooltip();
async function defaultDirSet() {
console.log('디폴트 디비 함수 실행됨');
try {
var dirData = await readDBbyStoreName('dirStore');
if (dirData.length < 1) {
dirAddButtonClick();
//위 함수도 따로 더 범용성 있게 하면 좋을 듯,, 클릭이 아니라 그냥 add자체로
}
} catch (error) {
console.error(error);
}
}
function displayTooltip(dataCount) {
for (let i = 0; i < dataCount; i++) {
const textElement = document.getElementsByClassName("title")[i];
const textContent = textElement.textContent;
const textLength = textContent.length;
if (textLength > 22) {
let selectedTitle = document.getElementsByClassName("title");
selectedTitle = selectedTitle[i];
let titleTooltip = document.getElementsByClassName("tooltipTitle");
titleTooltip = titleTooltip[i];
selectedTitle.addEventListener("mouseover", (e) => {
let posX = textElement.getBoundingClientRect().left;
let posY = textElement.getBoundingClientRect().top + window.scrollY;
let h = textElement.offsetHeight;
titleTooltip.style.display = "block";
titleTooltip.style.left = posX - 5 + "px"
titleTooltip.style.right = posX - 10 + "px"
titleTooltip.style.top = posY + h + 3 + "px";
});
selectedTitle.addEventListener("mouseout", () => {
titleTooltip.style.display = "none";
});
}
}
}
function displayKeyword(data) {
//컨텐츠 들어갈 위치
const container = document.getElementById('dataContainer');
// 데이터를 텍스트로 변환하여 화면에 추가
for (var i = 0; i < data.length; i++) {
const k = data[i][1];
console.log(k);
const gk = data[i][0];
const toggleStatus = data[i][2];
console.log(toggleStatus);
const template = document.getElementById("keyword_template");
const clone = template.content.cloneNode(true);
clone.querySelector(".keyword-box").querySelector(".keyword").innerHTML = k;
clone.querySelector(".keyword-box").id = "green-" + k;
clone.querySelector(".path-area").id = "white-" + k;
const toggleButton = clone.querySelector(".keyword-box").querySelector(".toggle_keyword");
clone.querySelector(".keyword-box").querySelector(".keyword").addEventListener("click", () => {
const url = "https://www.google.com/search?q=" + k;
chrome.tabs.create({ url: url });
})
let greenBox = clone.getElementById("green-" + k);
greenBox.setAttribute('Key', gk);
if (toggleStatus) {
toggleButton.classList.remove("toggleShown");
toggleButton.classList.add("toggleHidden");
clone.querySelector(".path-area").style.maxHeight = '0';
}
if (!toggleStatus) {
toggleButton.classList.add("toggleShown");
toggleButton.classList.remove("toggleHidden");
clone.querySelector(".path-area").style.maxHeight = '100vh'
clone.querySelector(".path-area").style.opacity = '1';
}
container.appendChild(clone);
}
}
function displayMenu(dataCount) {