-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpopup.js
More file actions
575 lines (496 loc) · 18.1 KB
/
popup.js
File metadata and controls
575 lines (496 loc) · 18.1 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
// 팝업 스크립트
// 검색 입력창에 포커스를 주는 함수
function focusSearchInput() {
const searchInput = document.getElementById('searchInput');
if (searchInput) {
searchInput.focus();
searchInput.select(); // 기존 텍스트가 있으면 선택
}
}
document.addEventListener('DOMContentLoaded', () => {
loadHistory();
setupTabs();
setupSettings();
setupSearch();
// 팝업이 열리면 즉시 검색창에 포커싱
focusSearchInput();
// 로딩 지연 대비 추가 포커싱
setTimeout(focusSearchInput, 50);
setTimeout(focusSearchInput, 100);
// 이벤트 리스너
document.getElementById('refresh').addEventListener('click', () => {
const activeTab = document.querySelector('.tab-button.active').dataset.tab;
if (activeTab === 'all') {
loadHistory();
}
});
document.getElementById('clearHistory').addEventListener('click', clearHistory);
});
// 탭 설정
function setupTabs() {
const tabButtons = document.querySelectorAll('.tab-button');
const tabContents = document.querySelectorAll('.tab-content');
tabButtons.forEach(button => {
button.addEventListener('click', () => {
// 모든 탭 비활성화
tabButtons.forEach(btn => btn.classList.remove('active'));
tabContents.forEach(content => content.classList.remove('active'));
// 선택한 탭 활성화
button.classList.add('active');
const tabId = `tab-${button.dataset.tab}`;
document.getElementById(tabId).classList.add('active');
// 해당 탭 데이터 로드
if (button.dataset.tab === 'all') {
loadHistory();
// "내가 입력한 프롬프트" 탭으로 전환 시 검색창에 포커싱
setTimeout(() => {
const searchInput = document.getElementById('searchInput');
if (searchInput) {
searchInput.focus();
}
}, 100);
}
});
});
}
// 히스토리 불러오기
function loadHistory() {
const historyList = document.getElementById('historyList');
const emptyState = document.getElementById('emptyState');
historyList.innerHTML = '<div class="loading">불러오는 중...</div>';
emptyState.style.display = 'none';
// 채팅 데이터와 프롬프트 히스토리를 모두 가져옴
chrome.storage.local.get(['chatData', 'promptHistory'], (result) => {
const chatData = result.chatData || {};
const promptHistory = result.promptHistory || [];
if (Object.keys(chatData).length === 0 && promptHistory.length === 0) {
historyList.innerHTML = '';
emptyState.style.display = 'block';
return;
}
// 채팅 데이터를 기반으로 그룹화
const groupedHistory = groupByChatData(chatData, promptHistory);
historyList.innerHTML = groupedHistory.map((group, groupIndex) => {
const date = new Date(group.lastUpdated);
const timeString = formatTime(date);
const siteHtml = group.site ? `<span class="site-badge site-${group.site}">${getSiteLabel(group.site)}</span>` : '';
return `
<div class="history-group" data-group-index="${groupIndex}">
<div class="group-header">
<div class="group-prompt">${escapeHtml(group.chatTitle)}</div>
<div class="group-info">
<div class="group-info-box">
<span class="duplicate-count">${group.qnaPairs.length}개의 질문</span>
${siteHtml}
</div>
<div class="group-info-box">
<span class="group-time">${timeString}</span>
<button class="group-toggle">펼치기</button>
</div>
</div>
</div>
<div class="group-items" style="display: none;">
${group.qnaPairs.map((qna, qnaIndex) => {
return `
<div class="group-item" data-chat-url="${group.chatUrl}" data-prompt-text="${escapeHtml(qna.question)}">
<div class="item-header">
<span class="item-number">#${qnaIndex + 1}</span>
</div>
<div class="item-content">
<div class="question-text">${escapeHtml(qna.question.substring(0, 150))}${qna.question.length > 150 ? '...' : ''}</div>
${qna.answerPreview ? `<div class="answer-preview">${escapeHtml(qna.answerPreview)}</div>` : '<div class="answer-preview">답변 대기중...</div>'}
</div>
<div class="history-item-actions">
<button class="action-btn copy-btn" data-text="${escapeHtml(qna.question)}">📋 복사</button>
<button class="action-btn navigate-btn" data-chat-url="${group.chatUrl}" data-prompt-text="${escapeHtml(qna.question)}">📍 이동</button>
</div>
</div>
`;
}).join('')}
</div>
</div>
`;
}).join('');
// 복사 버튼 이벤트
document.querySelectorAll('.copy-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
e.stopPropagation();
const text = btn.dataset.text;
navigator.clipboard.writeText(text).then(() => {
btn.textContent = '✅ 복사됨';
setTimeout(() => {
btn.textContent = '📋 복사';
}, 1500);
});
});
});
// 이동 버튼 이벤트 (전체 URL)
document.querySelectorAll('.open-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
e.stopPropagation();
const url = btn.dataset.url;
if (url) {
chrome.tabs.create({ url });
}
});
});
// 특정 프롬프트로 이동 버튼 이벤트
document.querySelectorAll('.navigate-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
e.stopPropagation();
const chatUrl = btn.dataset.chatUrl;
const promptText = btn.dataset.promptText;
if (chatUrl && promptText) {
navigateToPromptInChat(chatUrl, promptText);
}
});
});
// 그룹 토글 이벤트
document.querySelectorAll('.group-toggle').forEach(btn => {
btn.addEventListener('click', (e) => {
e.stopPropagation();
const group = btn.closest('.history-group');
const items = group.querySelector('.group-items');
const isOpen = items.style.display !== 'none';
items.style.display = isOpen ? 'none' : 'block';
btn.textContent = isOpen ? '펼치기' : '접기';
});
});
});
}
// 설정 기능 초기화
function setupSettings() {
const showCurrentQuestionToggle = document.getElementById('showCurrentQuestion');
const autoShowOnEntryToggle = document.getElementById('autoShowOnEntry');
const questionLinesRange = document.getElementById('questionLines');
const questionLinesValue = document.getElementById('questionLinesValue');
const themeSelect = document.getElementById('themeSelect');
const scrollSpeedRange = document.getElementById('scrollSpeed');
const scrollSpeedValue = document.getElementById('scrollSpeedValue');
const disableScrollAnimationToggle = document.getElementById('disableScrollAnimation');
const scrollSpeedSetting = document.getElementById('scrollSpeedSetting');
// 스크롤 속도 라벨 매핑
const speedLabels = {
1: '매우 빠름',
2: '빠름',
3: '보통',
4: '느림',
5: '매우 느림'
};
// 설정 불러오기
chrome.storage.local.get(['showCurrentQuestion', 'autoShowOnEntry', 'questionLines', 'theme', 'scrollSpeed', 'disableScrollAnimation'], (result) => {
showCurrentQuestionToggle.checked = result.showCurrentQuestion !== false; // 기본값은 true
autoShowOnEntryToggle.checked = result.autoShowOnEntry !== false; // 기본값은 true
const lines = result.questionLines || 4; // 기본값은 4줄
questionLinesRange.value = lines;
questionLinesValue.textContent = `${lines}줄`;
themeSelect.value = result.theme || 'system'; // 기본값은 시스템 설정 따르기
const speed = result.scrollSpeed || 3; // 기본값은 3 (보통)
scrollSpeedRange.value = speed;
scrollSpeedValue.textContent = speedLabels[speed] || '보통';
disableScrollAnimationToggle.checked = result.disableScrollAnimation === true; // 기본값은 false
// 애니메이션 비활성화 상태에 따라 속도 설정 활성화/비활성화
updateScrollSpeedSetting();
// 현재 질문 표시 상태에 따라 자동 표시 설정 활성화/비활성화
updateAutoShowOnEntryState();
});
// 현재 질문 표시 설정 변경 시 저장
showCurrentQuestionToggle.addEventListener('change', () => {
chrome.storage.local.set({
showCurrentQuestion: showCurrentQuestionToggle.checked
});
// 자동 표시 설정 항목 활성화/비활성화
updateAutoShowOnEntryState();
// content script에 설정 변경 알림
chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
if (tabs[0]) {
chrome.tabs.sendMessage(tabs[0].id, {
action: 'updateSettings',
showCurrentQuestion: showCurrentQuestionToggle.checked
});
}
});
});
// 채팅창 진입 시 자동 표시 설정 변경 시 저장
autoShowOnEntryToggle.addEventListener('change', () => {
chrome.storage.local.set({
autoShowOnEntry: autoShowOnEntryToggle.checked
});
// content script에 설정 변경 알림
chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
if (tabs[0]) {
chrome.tabs.sendMessage(tabs[0].id, {
action: 'updateSettings',
autoShowOnEntry: autoShowOnEntryToggle.checked
});
}
});
});
// 질문 줄 수 설정 변경 시 저장
questionLinesRange.addEventListener('input', () => {
const lines = parseInt(questionLinesRange.value);
questionLinesValue.textContent = `${lines}줄`;
chrome.storage.local.set({
questionLines: lines
});
// content script에 설정 변경 알림
chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
if (tabs[0]) {
chrome.tabs.sendMessage(tabs[0].id, {
action: 'updateSettings',
questionLines: lines
});
}
});
});
// 테마 설정 변경 시 저장
themeSelect.addEventListener('change', () => {
const theme = themeSelect.value;
chrome.storage.local.set({
theme: theme
});
// content script에 설정 변경 알림
chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
if (tabs[0]) {
chrome.tabs.sendMessage(tabs[0].id, {
action: 'updateSettings',
theme: theme
});
}
});
});
// 스크롤 속도 설정 변경 시 저장
scrollSpeedRange.addEventListener('input', () => {
const speed = parseInt(scrollSpeedRange.value);
scrollSpeedValue.textContent = speedLabels[speed] || '보통';
chrome.storage.local.set({
scrollSpeed: speed
});
// content script에 설정 변경 알림
chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
if (tabs[0]) {
chrome.tabs.sendMessage(tabs[0].id, {
action: 'updateSettings',
scrollSpeed: speed
});
}
});
});
// 애니메이션 비활성화 설정 변경 시 저장
disableScrollAnimationToggle.addEventListener('change', () => {
const disabled = disableScrollAnimationToggle.checked;
chrome.storage.local.set({
disableScrollAnimation: disabled
});
// 속도 설정 활성화/비활성화
updateScrollSpeedSetting();
// content script에 설정 변경 알림
chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
if (tabs[0]) {
chrome.tabs.sendMessage(tabs[0].id, {
action: 'updateSettings',
disableScrollAnimation: disabled
});
}
});
});
// 스크롤 속도 설정 활성화/비활성화 함수
function updateScrollSpeedSetting() {
if (disableScrollAnimationToggle.checked) {
scrollSpeedSetting.classList.add('disabled');
} else {
scrollSpeedSetting.classList.remove('disabled');
}
}
// 자동 표시 설정 활성화/비활성화 함수
function updateAutoShowOnEntryState() {
const autoShowSetting = document.getElementById('autoShowOnEntrySetting');
if (showCurrentQuestionToggle.checked) {
autoShowSetting.classList.remove('disabled');
} else {
autoShowSetting.classList.add('disabled');
// 현재 질문 표시가 꺼지면 자동 표시도 꺼짐
autoShowOnEntryToggle.checked = false;
chrome.storage.local.set({ autoShowOnEntry: false });
}
}
}
// 검색 기능 초기화
function setupSearch() {
const searchInput = document.getElementById('searchInput');
let searchTimeout;
searchInput.addEventListener('input', () => {
clearTimeout(searchTimeout);
searchTimeout = setTimeout(() => {
filterHistory(searchInput.value);
}, 300);
});
}
// 히스토리 필터링
function filterHistory(searchTerm) {
const historyItems = document.querySelectorAll('.history-item, .history-group');
if (!searchTerm.trim()) {
// 검색어가 없으면 모든 항목 표시
historyItems.forEach(item => {
item.style.display = '';
});
return;
}
try {
const regex = new RegExp(searchTerm, 'i');
historyItems.forEach(item => {
const textContent = item.textContent;
if (regex.test(textContent)) {
item.style.display = '';
} else {
item.style.display = 'none';
}
});
} catch (e) {
// 잘못된 정규식인 경우 모든 항목 표시
historyItems.forEach(item => {
item.style.display = '';
});
}
}
// 히스토리 삭제
function clearHistory() {
if (confirm('모든 프롬프트 히스토리를 삭제하시겠습니까?')) {
chrome.runtime.sendMessage({ action: 'clearHistory' }, (response) => {
if (response.success) {
loadHistory();
}
});
}
}
// 시간 포맷팅
function formatTime(date) {
const now = new Date();
const diff = now - date;
const seconds = Math.floor(diff / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
if (days > 0) {
return `${days}일 전`;
} else if (hours > 0) {
return `${hours}시간 전`;
} else if (minutes > 0) {
return `${minutes}분 전`;
} else {
return '방금 전';
}
}
// HTML 이스케이프
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// 도구 라벨 변환
function getToolLabel(tool) {
const toolMap = {
'dalle': '🎨 이미지',
'browser': '🌐 웹',
'python': '🐍 코드',
'search': '🔍 검색',
'deep_research': '📚 심층'
};
return toolMap[tool] || tool;
}
// 상태 HTML 생성
function getStatusHtml(status, responsePreview = '') {
if (!status || status === 'success') return '';
const statusMap = {
'pending': '⏳ 대기중',
'timeout': '⏰ 시간초과',
'error': '❌ 실패'
};
const statusText = statusMap[status] || status;
if (status === 'success' && responsePreview) {
return `<div class="response-preview">${escapeHtml(responsePreview)}...</div>`;
}
return `<div class="status-indicator status-${status}">${statusText}</div>`;
}
// 상태 텍스트 변환
function getStatusText(status) {
const statusMap = {
'pending': '⏳ 대기중',
'timeout': '⏰ 시간초과',
'error': '❌ 실패',
'success': '✅ 완료'
};
return statusMap[status] || status;
}
// 채팅 데이터 기반 그룹화
function groupByChatData(chatData, promptHistory) {
const groups = [];
// 채팅 데이터를 최신순으로 정렬
const sortedChats = Object.values(chatData).sort((a, b) =>
new Date(b.lastUpdated) - new Date(a.lastUpdated)
);
sortedChats.forEach(chat => {
const group = {
chatId: chat.chatId,
chatTitle: chat.chatTitle,
chatUrl: chat.url,
site: chat.site,
qnaPairs: chat.qnaPairs || [],
lastUpdated: chat.lastUpdated
};
groups.push(group);
});
return groups;
}
// 채팅 URL에서 채팅 ID 추출
function extractChatId(url) {
if (!url) return 'unknown';
const match = url.match(/\/c\/([a-f0-9-]+)/);
return match ? match[1] : 'unknown';
}
// 채팅 제목 가져오기 (저장된 히스토리에서 추출)
function getChatTitle(chatId) {
if (chatId === 'unknown') return '알 수 없는 채팅';
// 임시로 chatId 기반 제목 생성 (실제로는 히스토리에서 chatTitle 사용)
return `채팅 ${chatId.substring(0, 8)}...`;
}
// 사이트 라벨 변환 (ChatGPT만 지원)
function getSiteLabel(site) {
const siteMap = {
'chatgpt': '🤖 ChatGPT'
};
return siteMap[site] || site;
}
// 특정 채팅의 특정 프롬프트로 이동
function navigateToPromptInChat(chatUrl, promptText) {
// 현재 활성 탭의 URL 확인
chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
const currentTab = tabs[0];
const currentUrl = currentTab.url;
// 현재 탭의 URL과 목적지 URL이 같은지 확인
if (currentUrl === chatUrl) {
// 같은 탭에서 스크롤만 이동
chrome.tabs.sendMessage(currentTab.id, {
action: 'scrollToPrompt',
promptText: promptText
});
} else {
// 다른 URL이므로 새 탭에서 열기
chrome.tabs.create({ url: chatUrl }, (tab) => {
// 탭이 로드되면 특정 프롬프트로 스크롤하도록 메시지 전송
chrome.tabs.onUpdated.addListener(function listener(tabId, info) {
if (tabId === tab.id && info.status === 'complete') {
chrome.tabs.onUpdated.removeListener(listener);
// content script에 특정 프롬프트로 스크롤하라는 메시지 전송
setTimeout(() => {
chrome.tabs.sendMessage(tab.id, {
action: 'scrollToPrompt',
promptText: promptText
});
}, 1000); // 1초 후 실행 (페이지 완전 로드 대기)
}
});
});
}
});
}