-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptions.js
More file actions
1251 lines (1097 loc) · 56.7 KB
/
options.js
File metadata and controls
1251 lines (1097 loc) · 56.7 KB
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
const listBody = document.getElementById('listBody');
function showInfoToast(msg, isError = false) {
let container = document.getElementById('book-manager-info-toast-container');
if (!container) {
container = document.createElement('div');
container.id = 'book-manager-info-toast-container';
container.style.cssText = "position:fixed; bottom:20px; right:20px; z-index:999999; display:flex; flex-direction:column; gap:10px; pointer-events:none;";
document.body.appendChild(container);
}
const toast = document.createElement('div');
const bgColor = isError ? '#dc3545' : '#17a2b8';
toast.style.cssText = "background: " + bgColor + "; color: white; padding: 12px 35px 12px 20px; border-radius: 8px; font-size: 14px; font-weight: bold; box-shadow: 0 4px 12px rgba(0,0,0,0.3); opacity: 0; transform: translateX(20px); transition: all 0.3s ease; white-space: nowrap; pointer-events: auto; position: relative;";
toast.innerHTML = msg;
const closeBtn = document.createElement('span');
closeBtn.innerHTML = "×";
closeBtn.style.cssText = "position: absolute; top: 8px; right: 12px; font-size: 20px; font-weight: normal; cursor: pointer; opacity: 0.6; line-height: 1;";
closeBtn.onmouseover = () => closeBtn.style.opacity = '1';
closeBtn.onmouseout = () => closeBtn.style.opacity = '0.6';
closeBtn.onclick = () => {
toast.style.opacity = '0';
toast.style.transform = 'translateX(20px)';
setTimeout(() => { if (toast.parentNode) toast.remove(); }, 300);
};
toast.appendChild(closeBtn);
container.appendChild(toast);
void toast.offsetWidth;
toast.style.opacity = '1';
toast.style.transform = 'translateX(0)';
setTimeout(() => {
toast.style.opacity = '0';
toast.style.transform = 'translateX(20px)';
setTimeout(() => { if (toast.parentNode) toast.remove(); }, 350);
}, 3000);
}
function parseDateStr(str) {
if (!str) return 0;
let d = new Date(str).getTime();
if (!isNaN(d)) return d;
d = new Date(str.replace(/\.\s*/g, '/').replace(/\/$/, '')).getTime();
return isNaN(d) ? 0 : d;
}
function formatDisplayDate(str) {
if (!str) return '';
if (str.includes('T') || str.includes('-')) {
return new Date(str).toLocaleDateString('ko-KR');
}
return str;
}
function renderSites() {
chrome.storage.local.get({ allowedSites: [] }, (data) => {
const sites = Array.isArray(data.allowedSites) ? data.allowedSites : [];
document.getElementById('siteList').innerHTML = sites.map(s => {
if (typeof s === 'object') {
let detailTxt = s.detailSelector ? s.detailSelector : '<span style="color:#aaa;">미등록</span>';
return `<span class="site-tag">
<b style="font-size:13px; color:#0d6efd;">${s.url}</b>
<span style="color:var(--text-muted);">상세: <code>${detailTxt}</code></span>
<b style="color:red; cursor:pointer; font-size:14px; margin-left:4px;" data-site="${s.url}">×</b>
</span>`;
} else {
return `<span class="site-tag"><b>${s}</b> <b style="color:red; cursor:pointer;" data-site="${s}">×</b></span>`;
}
}).join('');
});
}
function renderFilters() {
chrome.storage.local.get({ filterWords: [] }, (data) => {
const filters = Array.isArray(data.filterWords) ? data.filterWords : [];
document.getElementById('filterList').innerHTML = filters.map(f => {
return `<span class="site-tag" style="background: rgba(220,53,69,0.05); border-color: rgba(220,53,69,0.2); margin:0;">
<b style="font-size:13px; color:#dc3545;">${f}</b>
<b style="color:#dc3545; cursor:pointer; font-size:15px; margin-left:6px; opacity:0.7;" data-filter="${f}">×</b>
</span>`;
}).join('');
});
}
let renderFrame;
let currentPage = 1;
const itemsPerPage = 100; // 한 페이지에 보여줄 항목 수 (100개 권장)
let totalPages = 1;
function renderList(filter = "", resetPage = false) {
if (resetPage) currentPage = 1; // 검색/정렬 시 페이지 1로 리셋
chrome.storage.local.get({ bookList: [], sortOption: 'id_desc' }, (data) => {
listBody.innerHTML = '';
let list = Array.isArray(data.bookList) ? data.bookList : [];
const completeCount = list.filter(b => b.type === 'complete').length;
const incompleteCount = list.filter(b => b.type === 'incomplete').length;
const excludeCount = list.filter(b => b.type === 'exclude').length;
document.getElementById('stat-total').innerText = list.length;
document.getElementById('stat-complete').innerText = completeCount;
document.getElementById('stat-incomplete').innerText = incompleteCount;
document.getElementById('stat-exclude').innerText = excludeCount;
const isDuplicateSearch = filter === "#중복";
let duplicateIds = new Set();
if (isDuplicateSearch) {
const titleMap = new Map();
list.forEach(b => {
if (!b || !b.title) return;
const normalized = b.title.replace(/[^a-zA-Z0-9가-힣ㄱ-ㅎㅏ-ㅣぁ-んァ-ヶー一-龥]/g, '').toLowerCase();
if (normalized.length === 0) return;
if (titleMap.has(normalized)) {
titleMap.get(normalized).push(b.id);
} else {
titleMap.set(normalized, [b.id]);
}
});
titleMap.forEach(ids => {
if (ids.length > 1) ids.forEach(id => duplicateIds.add(id));
});
}
// 필터링 적용
const normalizedFilter = filter.replace(/[^a-zA-Z0-9가-힣ㄱ-ㅎㅏ-ㅣ\sぁ-んァ-ヶー一-龥]/g, '').toLowerCase().trim().replace(/\s+/g, '');
const filteredList = list.filter(b => {
if (!b || !b.title) return false;
if (isDuplicateSearch) return duplicateIds.has(b.id);
if (b.title.toLowerCase().includes(filter.toLowerCase())) return true;
if (normalizedFilter) {
const normalizedTitle = b.title.replace(/[^a-zA-Z0-9가-힣ㄱ-ㅎㅏ-ㅣ\sぁ-んァ-ヶー一-龥]/g, '').toLowerCase().trim().replace(/\s+/g, '');
return normalizedTitle.includes(normalizedFilter);
}
return false;
});
// 전체 페이지 계산 및 현재 페이지 보정
totalPages = Math.ceil(filteredList.length / itemsPerPage) || 1;
if (currentPage > totalPages) currentPage = totalPages;
const countDisplay = document.getElementById('listCountDisplay');
if (countDisplay) {
if (isDuplicateSearch) {
countDisplay.innerHTML = `중복 의심 목록: 총 <span style="color:#fd7e14;">${filteredList.length}</span>건 (공백/기호 무시 시 동일한 항목 묶음)`;
} else if (filter.trim() === "") {
countDisplay.innerHTML = `전체 목록: 총 <span style="color:#0d6efd;">${filteredList.length}</span>건 (현재 <b style="color:var(--text);">${currentPage} / ${totalPages}</b> 페이지)`;
} else {
countDisplay.innerHTML = `검색 결과: 총 <span style="color:#e83e8c;">${filteredList.length}</span>건 (현재 <b style="color:var(--text);">${currentPage} / ${totalPages}</b> 페이지)`;
}
}
const findDuplicatesBtn = document.getElementById('findDuplicatesBtn');
if (findDuplicatesBtn) {
findDuplicatesBtn.onclick = () => {
if (searchInput) {
searchInput.value = '#중복';
searchInput.dispatchEvent(new Event('input'));
}
};
}
// 정렬 로직 적용
let sortFn;
switch(data.sortOption) {
case 'title_asc': sortFn = (a, b) => (a.title || '').localeCompare(b.title || ''); break;
case 'title_desc': sortFn = (a, b) => (b.title || '').localeCompare(a.title || ''); break;
case 'date_asc': sortFn = (a, b) => (parseDateStr(a.date) - parseDateStr(b.date)) || ((a.id || 0) - (b.id || 0)); break;
case 'date_desc': sortFn = (a, b) => (parseDateStr(b.date) - parseDateStr(a.date)) || ((b.id || 0) - (a.id || 0)); break;
case 'id_asc': sortFn = (a, b) => (a.id || 0) - (b.id || 0); break;
case 'id_desc':
default: sortFn = (a, b) => (b.id || 0) - (a.id || 0); break;
}
if (isDuplicateSearch) {
filteredList.sort((a, b) => {
const normA = (a.title || '').replace(/[^a-zA-Z0-9가-힣ㄱ-ㅎㅏ-ㅣぁ-んァ-ヶー一-龥]/g, '').toLowerCase();
const normB = (b.title || '').replace(/[^a-zA-Z0-9가-힣ㄱ-ㅎㅏ-ㅣぁ-んァ-ヶー一-龥]/g, '').toLowerCase();
if (normA < normB) return -1;
if (normA > normB) return 1;
return sortFn(a, b);
});
} else {
filteredList.sort(sortFn);
}
// 데이터 자르기 (Slice)
const startIndex = (currentPage - 1) * itemsPerPage;
const endIndex = Math.min(startIndex + itemsPerPage, filteredList.length);
const pageItems = filteredList.slice(startIndex, endIndex);
// 화면에 그리기
const fragment = document.createDocumentFragment();
let prevNorm = null;
pageItems.forEach(book => {
if (isDuplicateSearch) {
const normTitle = (book.title || '').replace(/[^a-zA-Z0-9가-힣ㄱ-ㅎㅏ-ㅣぁ-んァ-ヶー一-龥]/g, '').toLowerCase();
if (normTitle !== prevNorm) {
prevNorm = normTitle;
const groupTr = document.createElement('tr');
groupTr.className = 'group-header-tr';
groupTr.innerHTML = `<td colspan="6" style="text-align: left; padding: 6px 12px; font-weight: bold; font-size: 12px; background-color: rgba(127, 127, 127, 0.1); color: var(--text); border-bottom: 2px solid #fd7e14; border-top: 2px solid var(--border);">📦 동일 항목 그룹: <span style="color:#fd7e14;">${normTitle}</span></td>`;
fragment.appendChild(groupTr);
}
}
const tr = document.createElement('tr');
tr.innerHTML = `
<td>
<select class="edit-type" data-id="${book.id}" data-type="${book.type}" style="padding: 4px;">
<option value="exclude" ${book.type==='exclude'?'selected':''}>제외</option>
<option value="incomplete" ${book.type==='incomplete'?'selected':''}>미완</option>
<option value="complete" ${book.type==='complete'?'selected':''}>완결</option>
</select>
</td>
<td><input type="text" class="edit-title" value="${book.title}" data-id="${book.id}"></td>
<td><input type="text" class="edit-res" value="${book.resolution||''}" data-id="${book.id}" placeholder="해상도" style="width:65px"></td>
<td style="position:relative; vertical-align:middle; padding:0;">
<div style="display:flex; align-items:center; justify-content:center; gap:4px; width:100%; height:100%;">
<input type="text" class="edit-vol" value="${book.lastVol||''}" data-id="${book.id}" placeholder="권수" style="width:100%; min-width:35px; margin:0; padding:4px;">
${(book.missingVols && book.missingVols.length > 0)
? `<span class="missing-badge" style="flex-shrink:0; padding:2px 4px;" data-id="${book.id}">${book.missingVols.length}누락</span>`
: `<span class="missing-badge empty" style="flex-shrink:0; padding:2px 4px;" data-id="${book.id}">+누락</span>`}
</div>
</td>
<td style="color:var(--text-muted); font-size:11px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">${formatDisplayDate(book.date)}</td>
<td>
<button class="btn-save" data-id="${book.id}">수정</button>
<button class="btn-del" data-id="${book.id}">삭제</button>
</td>
`;
fragment.appendChild(tr);
});
listBody.appendChild(fragment);
// 페이지네이션 버튼 렌더링 호출
renderPagination();
});
}
// 하단 페이지네이션 버튼 생성 로직
function renderPagination() {
const container = document.getElementById('paginationContainer');
if (!container) return;
container.innerHTML = '';
if (totalPages <= 1) return;
const createBtn = (text, targetPage, disabled = false, active = false) => {
const btn = document.createElement('button');
btn.className = 'page-btn' + (active ? ' active' : '');
btn.innerHTML = text;
btn.disabled = disabled;
if (!disabled && !active) {
btn.onclick = () => {
currentPage = targetPage;
renderList(document.getElementById('searchInput').value, false);
window.scrollTo({ top: 0, behavior: 'smooth' }); // 페이지 이동 시 맨 위로
};
}
return btn;
};
// 처음, 이전 버튼
container.appendChild(createBtn('«', 1, currentPage === 1));
container.appendChild(createBtn('‹', currentPage - 1, currentPage === 1));
// 페이지 숫자 목록 (현재 페이지 기준으로 +- 2개씩 표시, 최대 5개)
let startPage = Math.max(1, currentPage - 2);
let endPage = Math.min(totalPages, startPage + 4);
if (endPage - startPage < 4) {
startPage = Math.max(1, endPage - 4);
}
for (let i = startPage; i <= endPage; i++) {
container.appendChild(createBtn(i, i, false, i === currentPage));
}
// 다음, 마지막 버튼
container.appendChild(createBtn('›', currentPage + 1, currentPage === totalPages));
container.appendChild(createBtn('»', totalPages, currentPage === totalPages));
}
function saveWithUndo(newList, successMsg) {
chrome.storage.local.get({ bookList: [] }, (data) => {
chrome.storage.local.set({ backupList: data.bookList }, () => {
chrome.storage.local.set({ bookList: newList }, () => {
if (successMsg) showInfoToast(successMsg);
// 수정/삭제 후 현재 페이지 유지 (false 전달)
renderList(document.getElementById('searchInput').value, false);
const undoBtn = document.getElementById('undoBtn');
undoBtn.style.display = 'block';
setTimeout(() => { undoBtn.style.display = 'none'; }, 15000);
});
});
});
}
document.getElementById('undoBtn').onclick = () => {
chrome.storage.local.get({ backupList: null }, (data) => {
if (data.backupList) {
chrome.storage.local.set({ bookList: data.backupList }, () => {
showInfoToast('⏪ 방금 전 작업이 완벽하게 취소(복구)되었습니다.');
renderList(document.getElementById('searchInput').value, false);
document.getElementById('undoBtn').style.display = 'none';
});
}
});
};
document.getElementById('batchUpdateBtn').onclick = () => {
const targetType = document.getElementById('batchTypeSelect').value;
const filter = document.getElementById('searchInput').value.toLowerCase();
const normalizedFilter = filter.replace(/[^a-zA-Z0-9가-힣ㄱ-ㅎㅏ-ㅣ\sぁ-んァ-ヶー一-龥]/g, '').trim().replace(/\s+/g, '');
let typeNameKOR = targetType === 'exclude' ? '제외' : (targetType === 'complete' ? '완결' : '미완');
if(!confirm(`현재 검색된 모든 항목을 [${typeNameKOR}] 타입으로 변경하시겠습니까?`)) return;
chrome.storage.local.get({ bookList: [] }, (data) => {
let list = Array.isArray(data.bookList) ? data.bookList : [];
const today = new Date().toISOString();
const updatedList = list.map(book => {
if (book && book.title) {
const lowerTitle = book.title.toLowerCase();
const matchOriginal = lowerTitle.includes(filter);
let matchNormalized = false;
if (!matchOriginal && normalizedFilter) {
const normalizedTitle = lowerTitle.replace(/[^a-zA-Z0-9가-힣ㄱ-ㅎㅏ-ㅣ\sぁ-んァ-ヶー一-龥]/g, '').trim().replace(/\s+/g, '');
matchNormalized = normalizedTitle.includes(normalizedFilter);
}
if (matchOriginal || matchNormalized) {
return { ...book, type: targetType, date: today };
}
}
return book;
});
saveWithUndo(updatedList, '일괄 수정이 완료되었습니다.');
});
};
// ============================================================================
// [수정됨] 백업 (내보내기) 로직: 도서 목록 + 사이트 설정 + 금지어 설정 모두 포함
// ============================================================================
document.getElementById('exportBtn').onclick = () => {
// 저장소에서 3가지 데이터를 모두 불러옵니다.
chrome.storage.local.get({ bookList: [], allowedSites: [], filterWords: [] }, (data) => {
// 객체(Object) 형태로 데이터를 묶어서 백업
const exportData = {
bookList: data.bookList,
allowedSites: data.allowedSites,
filterWords: data.filterWords
};
const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'book_manager_backup.json';
a.click();
URL.revokeObjectURL(url);
const now = new Date();
const backupTime = now.toLocaleString('ko-KR');
chrome.storage.local.set({ lastBackup: backupTime }, () => {
const timeSpan = document.getElementById('lastBackupTime');
if(timeSpan) timeSpan.innerText = `최근 백업: ${backupTime}`;
});
});
};
document.getElementById('importBtn').onclick = () => document.getElementById('fileInput').click();
// ============================================================================
// [수정됨] 복구 (불러오기) 로직: 신규 포맷 및 구버전 포맷(하위 호환) 완벽 지원
// ============================================================================
document.getElementById('fileInput').onchange = (e) => {
const file = e.target.files[0];
if (!file) return;
if (!confirm('경고: 파일의 데이터가 기존 데이터를 완전히 덮어씁니다. 계속하시겠습니까?\n(오류 시 우측 하단의 실행 취소 버튼으로 되돌릴 수 있습니다)')) {
e.target.value = '';
return;
}
const reader = new FileReader();
reader.onload = (event) => {
try {
const importedData = JSON.parse(event.target.result);
// 1. 신규 포맷 검사 (객체 형태: 도서 목록 + 사이트 설정 + 금지어)
if (importedData && typeof importedData === 'object' && !Array.isArray(importedData)) {
let hasSettings = false;
// 사이트 설정이 존재하면 복구 및 화면 갱신
if (Array.isArray(importedData.allowedSites)) {
chrome.storage.local.set({ allowedSites: importedData.allowedSites }, renderSites);
hasSettings = true;
}
// 필터(금지어) 설정이 존재하면 복구 및 화면 갱신
if (Array.isArray(importedData.filterWords)) {
chrome.storage.local.set({ filterWords: importedData.filterWords }, renderFilters);
hasSettings = true;
}
// 도서 목록이 존재하면 복구 (기존 saveWithUndo 재활용하여 취소 기능 유지)
if (Array.isArray(importedData.bookList)) {
saveWithUndo(importedData.bookList, '✅ 도서 목록 및 추가 설정 복구가 완료되었습니다.');
} else if (hasSettings) {
showInfoToast('✅ 추가 설정(사이트/금지어) 복구가 완료되었습니다.');
} else {
showInfoToast('❌ 유효한 백업 데이터가 없습니다.', true);
}
}
// 2. 구버전 포맷 검사 (배열 형태: 과거에 도서 목록만 백업했던 파일)
else if (Array.isArray(importedData)) {
saveWithUndo(importedData, '✅ 도서 목록 복구가 완료되었습니다. (구버전 백업 파일 호환 적용)');
}
else {
showInfoToast('❌ 올바른 백업 파일 형식이 아닙니다.', true);
}
} catch (err) {
showInfoToast('❌ 파일을 읽는 중 오류가 발생했습니다. (JSON 파싱 에러)', true);
}
e.target.value = '';
};
reader.readAsText(file);
};
// ============================================================================
// [신규 추가] 타임머신 스냅샷 렌더링 및 복원 로직
// ============================================================================
async function renderSnapshots() {
const container = document.getElementById('snapshotList');
if (!container) return;
try {
const snapshots = await db.snapshots.orderBy('timestamp').reverse().toArray();
if (snapshots.length === 0) {
container.innerHTML = '<li style="font-size: 13px; color: var(--text-muted);">저장된 스냅샷이 없습니다. (자동 백업은 1일 뒤부터 생성됩니다)</li>';
return;
}
container.innerHTML = snapshots.map(snap => {
const date = new Date(snap.timestamp);
const displayTime = `${date.getFullYear()}년 ${date.getMonth()+1}월 ${date.getDate()}일 ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
const bookCount = snap.data && snap.data.bookList ? snap.data.bookList.length : 0;
return `
<li style="display:flex; justify-content:space-between; align-items:center; background:var(--input-bg); border:1px solid var(--border); padding:10px 15px; border-radius:6px;">
<div>
<strong style="color:var(--text); font-size:13px;">📅 ${snap.dateStr} 자동 백업</strong><br>
<span style="color:var(--text-muted); font-size:11px;">저장 시간: ${displayTime} | 도서 데이터: ${bookCount}건</span>
</div>
<button class="btn-restore-snap" data-id="${snap.id}" style="background:#fd7e14; padding:5px 12px; font-size:12px; border:none;">이 시점으로 복원</button>
</li>`;
}).join('');
document.querySelectorAll('.btn-restore-snap').forEach(btn => {
btn.onclick = async (e) => {
const id = parseInt(e.target.dataset.id, 10);
if (confirm('정말로 이 시점의 데이터로 되돌리시겠습니까?\n현재 저장된 모든 데이터는 해당 시점의 데이터로 덮어씌워집니다.')) {
const snap = await db.snapshots.get(id);
if (snap && snap.data) {
let hasSettings = false;
if (Array.isArray(snap.data.allowedSites)) { chrome.storage.local.set({ allowedSites: snap.data.allowedSites }, renderSites); hasSettings = true; }
if (Array.isArray(snap.data.filterWords)) { chrome.storage.local.set({ filterWords: snap.data.filterWords }, renderFilters); hasSettings = true; }
if (Array.isArray(snap.data.bookList)) { saveWithUndo(snap.data.bookList, '✅ 선택한 시점으로 복원이 완료되었습니다.'); }
else if (hasSettings) { showInfoToast('✅ 추가 설정(사이트/금지어) 복구가 완료되었습니다.'); }
}
}
};
});
} catch (err) {
container.innerHTML = '<li style="font-size: 13px; color: #dc3545;">스냅샷을 불러오는 데 실패했습니다.</li>';
}
}
const bulkInput = document.getElementById('bulkInput');
const bulkPreview = document.getElementById('bulkPreview');
bulkInput.addEventListener('input', () => {
const lines = bulkInput.value.split('\n').filter(t => t.trim());
if (lines.length === 0) {
bulkPreview.style.display = 'none';
return;
}
bulkPreview.style.display = 'block';
const line = lines[0];
const resMatch = line.match(/\d{3,4}\s*px/gi);
const rangeMatch = line.match(/(\d+)\s*(?:권|화|부(?!터))?\s*[~-]\s*(\d+)/);
const singleMatch = line.match(/(\d+)\s*(?:권|완결|화|부(?!터))/);
const endNumMatch = line.match(/(\d+)\s*$/);
let parsedVol = "";
if (rangeMatch) parsedVol = parseInt(rangeMatch[2], 10).toString();
else if (singleMatch) parsedVol = parseInt(singleMatch[1], 10).toString();
else if (endNumMatch) parsedVol = parseInt(endNumMatch[1], 10).toString();
let cleanTitle = cleanSiteTitle(line)
.replace(/\d+\s*권/g, '')
.replace(/완결/g, '')
.replace(/개$/g, '')
.replace(/(\d+)?권/g, '')
.replace(/(\d+)?완/g, '')
.replace(/\s?권$/g, '')
.replace(/\s?완$/g, '')
.replace(/[^a-zA-Z0-9가-힣ㄱ-ㅎㅏ-ㅣ\sぁ-んァ-ヶー一-龥]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
let extras = lines.length > 1 ? `<span style="color:var(--text-muted); float:right;">(+ 외 ${lines.length - 1}건)</span>` : '';
bulkPreview.innerHTML = `
<span style="display:inline-block; margin-bottom:5px;"><b>👀 첫 번째 줄 파싱 결과</b> ${extras}</span><br>
📚 제목: <span style="color:#0d6efd; font-weight:bold;">${cleanTitle || '(없음)'}</span> |
📑 권수: <span style="color:#e83e8c; font-weight:bold;">${parsedVol || '(없음)'}</span> |
📺 해상도: <span style="color:#20c997; font-weight:bold;">${resMatch ? Array.from(new Set(resMatch)).join(',') : '(없음)'}</span>
`;
});
document.getElementById('saveBtn').onclick = () => {
const lines = document.getElementById('bulkInput').value.split('\n').filter(t => t.trim());
const selectedTypeSelect = document.getElementById('bulkTypeSelect');
const targetType = selectedTypeSelect ? selectedTypeSelect.value : 'exclude';
// 데이터가 많을 경우 브라우저 멈춤을 방지하기 위해 로딩 상태 표시
const btn = document.getElementById('saveBtn');
const originalBtnText = btn.innerText;
btn.innerText = "⏳ 처리 중... (잠시만 기다려주세요)";
btn.style.pointerEvents = 'none';
chrome.storage.local.set({ lastBulkType: targetType });
// UI 텍스트가 바뀔 틈을 주기 위해 setTimeout으로 비동기 실행
setTimeout(() => {
chrome.storage.local.get({ bookList: [] }, (data) => {
let currentList = Array.isArray(data.bookList) ? data.bookList : [];
let skippedCount = 0;
// [최적화 1] 검색 속도 무한대 향상 (O(N) -> O(1))
// 매번 findIndex로 찾지 않도록 기존 목록을 Map(사전) 형태로 미리 만들어 둡니다.
const titleMap = new Map();
currentList.forEach((book, idx) => {
if (book && book.title) {
const normalized = book.title.replace(/[^a-zA-Z0-9가-힣ㄱ-ㅎㅏ-ㅣ\sぁ-んァ-ヶー一-龥]/g, '').toLowerCase().trim().replace(/\s+/g, '');
titleMap.set(normalized, idx); // 제목을 키(Key)로, 인덱스를 값(Value)으로 저장
}
});
// [최적화 2] unshift 연산 제거
// 매번 배열을 뒤로 미는 대신, 임시 배열에 일단 차곡차곡 쌓습니다(push).
const newBooks = [];
lines.forEach(line => {
const resMatch = line.match(/\d{3,4}\s*px/gi);
// 이전에 수정한 부(?!터) 정규식 그대로 유지
const rangeMatch = line.match(/(\d+)\s*(?:권|화|부(?!터))?\s*[~-]\s*(\d+)/);
const singleMatch = line.match(/(\d+)\s*(?:권|완결|화|부(?!터))/);
const endNumMatch = line.match(/(\d+)\s*$/);
let parsedVol = "";
if (rangeMatch) parsedVol = parseInt(rangeMatch[2], 10).toString();
else if (singleMatch) parsedVol = parseInt(singleMatch[1], 10).toString();
else if (endNumMatch) parsedVol = parseInt(endNumMatch[1], 10).toString();
let cleanTitle = cleanSiteTitle(line)
.replace(/\d+\s*권/g, '')
.replace(/완결/g, '')
.replace(/개$/g, '')
.replace(/(\d+)?권/g, '')
.replace(/(\d+)?완/g, '')
.replace(/\s?권$/g, '')
.replace(/\s?완$/g, '')
.replace(/[^a-zA-Z0-9가-힣ㄱ-ㅎㅏ-ㅣ\sぁ-んァ-ヶー一-龥]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
if (!cleanTitle) {
skippedCount++;
return;
}
const normalizedNewTitle = cleanTitle.replace(/\s+/g, '').toLowerCase();
const bookData = {
type: targetType,
title: cleanTitle,
resolution: resMatch ? Array.from(new Set(resMatch)).join(',') : "",
lastVol: parsedVol,
date: new Date().toISOString(),
id: Date.now() + Math.random()
};
// [최적화 1 적용] Map에서 즉시(0.0001초) 찾아냅니다.
if (titleMap.has(normalizedNewTitle)) {
const existingIdx = titleMap.get(normalizedNewTitle);
currentList[existingIdx] = { ...currentList[existingIdx], ...bookData };
} else {
// [최적화 2 적용] 무거운 unshift 대신 가벼운 push 사용
newBooks.push(bookData);
// 6만 건의 새 데이터 안에서 중복이 발생할 수도 있으니 Map에도 등록
titleMap.set(normalizedNewTitle, -1);
}
});
// [최적화 3] 마지막에 배열 합치기
// 기존 unshift처럼 최신 항목이 위로 오게 하려면, 새 책들을 뒤집은(reverse) 후 기존 목록 앞에 붙이면 됩니다.
currentList = [...newBooks.reverse(), ...currentList];
let typeNameKOR = targetType === 'exclude' ? '제외' : (targetType === 'complete' ? '완결' : '미완');
let alertMsg = `✅ [${typeNameKOR}] 타입으로 일괄 저장이 완료되었습니다.`;
if (skippedCount > 0) alertMsg += `\n(단, 제목을 식별할 수 없는 ${skippedCount}개의 항목은 제외됨)`;
saveWithUndo(currentList, alertMsg);
document.getElementById('bulkInput').value = '';
const bulkPreview = document.getElementById('bulkPreview');
if (bulkPreview) bulkPreview.style.display = 'none';
// 버튼 상태 원상복구
btn.innerText = originalBtnText;
btn.style.pointerEvents = 'auto';
});
}, 50); // 렌더링에 50ms 양보
};
document.body.onclick = (e) => {
const id = parseFloat(e.target.dataset.id);
const site = e.target.dataset.site;
const filterWord = e.target.dataset.filter;
if (id && e.target.classList.contains('btn-del')) {
chrome.storage.local.get({ bookList: [] }, (data) => {
const list = Array.isArray(data.bookList) ? data.bookList : [];
saveWithUndo(list.filter(b => b.id !== id), null);
});
} else if (id && e.target.classList.contains('btn-save')) {
chrome.storage.local.get({ bookList: [] }, (data) => {
const list = Array.isArray(data.bookList) ? data.bookList : [];
const idx = list.findIndex(b => b.id === id);
const row = e.target.closest('tr');
if (idx > -1) {
const newTitle = row.querySelector('.edit-title').value.trim();
if (!newTitle) { showInfoToast('❌ 제목은 비워둘 수 없습니다!', true); return; }
list[idx] = {
...list[idx],
type: row.querySelector('.edit-type').value,
title: newTitle,
resolution: row.querySelector('.edit-res').value.trim(),
lastVol: row.querySelector('.edit-vol').value.trim(),
date: new Date().toISOString()
};
saveWithUndo(list, '✅ 수정이 완료되었습니다.');
}
});
} else if (site) {
chrome.storage.local.get({ allowedSites: [] }, (data) => {
const sites = Array.isArray(data.allowedSites) ? data.allowedSites : [];
const newSites = sites.filter(s => {
const sUrl = typeof s === 'string' ? s : s.url;
return sUrl !== site;
});
chrome.storage.local.set({ allowedSites: newSites }, renderSites);
});
} else if (filterWord) {
chrome.storage.local.get({ filterWords: [] }, (data) => {
const filters = Array.isArray(data.filterWords) ? data.filterWords : [];
const newFilters = filters.filter(f => f !== filterWord);
chrome.storage.local.set({ filterWords: newFilters }, renderFilters);
});
}
};
async function loadReleaseHistory() {
const container = document.getElementById('releaseHistoryContainer');
if (container.dataset.loaded === "true") return;
try {
const response = await fetch('https://api.github.com/repos/dongkkase/Chrome_Library_Management/releases');
if (!response.ok) throw new Error('GitHub API 응답 오류');
const releases = await response.json();
if (releases.length === 0) {
container.innerHTML = '<div style="text-align: center; color: var(--text-muted); padding: 30px;">등록된 업데이트 내역이 없습니다.</div>';
return;
}
let html = '';
releases.forEach(rel => {
const date = new Date(rel.published_at).toLocaleDateString('ko-KR');
let lines = (rel.body || '').split('\n');
let htmlLines = [];
let inList = false;
lines.forEach(line => {
let trimmedLine = line.trimRight();
let safeLine = trimmedLine.replace(/</g, '<').replace(/>/g, '>');
safeLine = safeLine.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
let h3Match = safeLine.match(/^\s*###\s+(.*)/);
let h2Match = safeLine.match(/^\s*##\s+(.*)/);
let h1Match = safeLine.match(/^\s*#\s+(.*)/);
let listMatch = safeLine.match(/^(\s*)[-*]\s+(.*)/);
if (h3Match) {
if (inList) { htmlLines.push('</ul>'); inList = false; }
htmlLines.push('<h4>' + h3Match[1] + '</h4>');
} else if (h2Match) {
if (inList) { htmlLines.push('</ul>'); inList = false; }
htmlLines.push('<h3>' + h2Match[1] + '</h3>');
} else if (h1Match) {
if (inList) { htmlLines.push('</ul>'); inList = false; }
htmlLines.push('<h3>' + h1Match[1] + '</h3>');
} else if (listMatch) {
if (!inList) { htmlLines.push('<ul>'); inList = true; }
let indent = listMatch[1].length;
let text = listMatch[2];
let liClass = indent > 0 ? ' class="sub-li"' : '';
htmlLines.push(`<li${liClass}>${text}</li>`);
} else if (safeLine.trim() === '') {
if (inList) { htmlLines.push('</ul>'); inList = false; }
} else {
if (inList) { htmlLines.push('</ul>'); inList = false; }
htmlLines.push('<p>' + safeLine + '</p>');
}
});
if (inList) htmlLines.push('</ul>');
let bodyHtml = htmlLines.join('\n');
html += `
<div class="release-item">
<div class="release-version">
<span>🏷️ ${rel.name || rel.tag_name}</span>
<span class="release-date">${date}</span>
</div>
<div class="release-body">${bodyHtml}</div>
</div>
`;
});
container.innerHTML = html;
container.dataset.loaded = "true";
} catch (error) {
container.innerHTML = `<div style="text-align: center; color: #dc3545; padding: 30px;">오류가 발생했습니다.<br>${error.message}</div>`;
}
}
document.addEventListener('DOMContentLoaded', () => {
if (window.location.hash === '#sidepanel') {
document.body.classList.add('side-panel-mode');
}
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
e.target.classList.add('active');
const targetId = e.target.getAttribute('data-target');
document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
document.getElementById(targetId).classList.add('active');
if (targetId === 'tab-history') {
loadReleaseHistory();
} else if (targetId === 'tab-backup') {
renderSnapshots(); // 백업 탭 열릴 때 스냅샷 목록 갱신
}
});
});
const themeToggle = document.getElementById('themeToggle');
const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");
chrome.storage.local.get(['darkMode'], (data) => {
let isDark = data.darkMode;
if (isDark === undefined) {
isDark = prefersDarkScheme.matches;
}
themeToggle.checked = isDark;
if (isDark) document.body.classList.add('dark-mode');
});
themeToggle.addEventListener('change', (e) => {
const isDark = e.target.checked;
if (isDark) document.body.classList.add('dark-mode');
else document.body.classList.remove('dark-mode');
chrome.storage.local.set({ darkMode: isDark });
});
chrome.storage.local.get({ lastBackup: null, sortOption: 'id_desc', lastBulkType: 'exclude' }, (data) => {
const sortSelect = document.getElementById('sortSelect');
if (sortSelect) sortSelect.value = data.sortOption;
const bulkTypeSelect = document.getElementById('bulkTypeSelect');
if (bulkTypeSelect) {
bulkTypeSelect.value = data.lastBulkType;
bulkTypeSelect.addEventListener('change', (e) => {
chrome.storage.local.set({ lastBulkType: e.target.value });
});
}
renderList('', true);
renderSites();
renderFilters();
renderSnapshots();
const timeSpan = document.getElementById('lastBackupTime');
if (timeSpan) {
if (data.lastBackup) {
timeSpan.innerText = `최근 백업: ${data.lastBackup}`;
} else {
timeSpan.innerText = `최근 백업: 기록 없음`;
}
}
});
// 라이브 타입 변경 색상 반영을 위한 이벤트 리스너
if (listBody) {
listBody.addEventListener('change', (e) => {
if (e.target.classList.contains('edit-type')) {
e.target.setAttribute('data-type', e.target.value);
}
});
}
const addSiteBtn = document.getElementById('addSiteBtn');
if (addSiteBtn) {
addSiteBtn.onclick = () => {
const siteInput = document.getElementById('siteInput');
if (!siteInput) return;
const val = siteInput.value.trim().replace(/^https?:\/\//, '').split('/')[0];
if (val) {
chrome.storage.local.get({ allowedSites: [] }, (data) => {
const currentSites = Array.isArray(data.allowedSites) ? data.allowedSites : [];
const exists = currentSites.some(s => (typeof s === 'string' ? s : s.url) === val);
if (!exists) {
chrome.storage.local.set({ allowedSites: [...currentSites, { url: val, detailSelector: "" }] }, () => {
siteInput.value = '';
renderSites();
});
} else {
showInfoToast('❌ 이미 등록된 사이트입니다.', true);
}
});
}
};
}
const addFilterBtn = document.getElementById('addFilterBtn');
if (addFilterBtn) {
addFilterBtn.onclick = () => {
const filterInput = document.getElementById('filterInput');
if (!filterInput) return;
const val = filterInput.value.trim();
if (val) {
chrome.storage.local.get({ filterWords: [] }, (data) => {
const currentFilters = Array.isArray(data.filterWords) ? data.filterWords : [];
if (!currentFilters.includes(val)) {
chrome.storage.local.set({ filterWords: [...currentFilters, val] }, () => {
filterInput.value = '';
renderFilters();
});
} else {
showInfoToast('❌ 이미 등록된 금지어입니다.', true);
}
});
}
};
}
const searchInput = document.getElementById('searchInput');
const clearSearchBtn = document.getElementById('clearSearchBtn');
let searchDebounceTimer;
if (searchInput) {
if (clearSearchBtn) {
clearSearchBtn.style.display = searchInput.value ? 'block' : 'none';
}
searchInput.oninput = (e) => {
if (clearSearchBtn) {
clearSearchBtn.style.display = e.target.value ? 'block' : 'none';
}
clearTimeout(searchDebounceTimer);
searchDebounceTimer = setTimeout(() => {
// 검색어 입력 시 1페이지로 리셋 (true 전달)
renderList(e.target.value, true);
}, 300);
};
}
if (clearSearchBtn && searchInput) {
clearSearchBtn.onclick = () => {
searchInput.value = '';
clearSearchBtn.style.display = 'none';
renderList('', true);
};
}
const sortSelect = document.getElementById('sortSelect');
if (sortSelect) {
sortSelect.onchange = (e) => {
chrome.storage.local.set({ sortOption: e.target.value }, () => {
const filter = searchInput ? searchInput.value : '';
// 💡 정렬 변경 시 1페이지로 리셋 (true 전달)
renderList(filter, true);
});
};
}
initVersionCheck();
const uiCheckbox = document.getElementById('showDownloadUICheckbox');
const confirmCheckbox = document.getElementById('autoConfirmCheckbox');
const folderCheckbox = document.getElementById('autoFolderCheckbox');
const focusLeftCheckbox = document.getElementById('focusLeftTabCheckbox');
const slidePanelCheckbox = document.getElementById('openSlidePanelCheckbox');
const connectEverythingCheckbox = document.getElementById('connectEverythingCheckbox');
const showListQuickBtnCheckbox = document.getElementById('showListQuickBtnCheckbox');
const showListQuickBtnHoverCheckbox = document.getElementById('showListQuickBtnHoverCheckbox');
const customThemeCheckbox = document.getElementById('useCustomThemeCheckbox');
const supportSingleCharCheckbox = document.getElementById('supportSingleCharCheckbox');
chrome.storage.local.get({ showDownloadUI: true, autoConfirm: true, autoFolder: true, focusLeftTab: false, openSlidePanel: false, connectEverything: false, showListQuickBtn: false, showListQuickBtnHover: false, useCustomTheme: false, supportSingleChar: false }, (data) => {
if (uiCheckbox) uiCheckbox.checked = data.showDownloadUI;
if (confirmCheckbox) confirmCheckbox.checked = data.autoConfirm;
if (folderCheckbox) folderCheckbox.checked = data.autoFolder;
if (focusLeftCheckbox) focusLeftCheckbox.checked = data.focusLeftTab;
if (slidePanelCheckbox) slidePanelCheckbox.checked = data.openSlidePanel;
if (connectEverythingCheckbox) connectEverythingCheckbox.checked = data.connectEverything;
if (showListQuickBtnCheckbox) showListQuickBtnCheckbox.checked = data.showListQuickBtn;
if (showListQuickBtnHoverCheckbox) showListQuickBtnHoverCheckbox.checked = data.showListQuickBtnHover;
if (customThemeCheckbox) customThemeCheckbox.checked = data.useCustomTheme;
if (supportSingleCharCheckbox) supportSingleCharCheckbox.checked = data.supportSingleChar;
});
// 옵션값 변경 시 저장 로직
if (uiCheckbox) {
uiCheckbox.addEventListener('change', (e) => {
chrome.storage.local.set({ showDownloadUI: e.target.checked });
});
}
if (supportSingleCharCheckbox) {
supportSingleCharCheckbox.addEventListener('change', (e) => {
chrome.storage.local.set({ supportSingleChar: e.target.checked });
});
}
if (confirmCheckbox) {
confirmCheckbox.addEventListener('change', (e) => {
chrome.storage.local.set({ autoConfirm: e.target.checked });
});
}
if (folderCheckbox) {
folderCheckbox.addEventListener('change', (e) => {
chrome.storage.local.set({ autoFolder: e.target.checked });
});
}
// 왼쪽 탭 포커스 저장 로직 추가
if (focusLeftCheckbox) {
focusLeftCheckbox.addEventListener('change', (e) => {
chrome.storage.local.set({ focusLeftTab: e.target.checked });
});
}
// 슬라이드 패널 저장 로직 수정 (레이스 컨디션 방지 및 백그라운드 이관)
if (slidePanelCheckbox) {
slidePanelCheckbox.addEventListener('change', (e) => {
const isSlide = e.target.checked;
chrome.storage.local.set({ openSlidePanel: isSlide }, () => {
if (isSlide) {
chrome.windows.getCurrent({ populate: false }, (currentWindow) => {
if (chrome.sidePanel && chrome.sidePanel.open) {
chrome.sidePanel.open({ windowId: currentWindow.id })
.then(() => {
window.close();
})
.catch((err) => {
console.error(err);
window.close();
});
} else {
window.close();
}
});
} else {