-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
265 lines (244 loc) · 10.7 KB
/
content.js
File metadata and controls
265 lines (244 loc) · 10.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
const FAVORITES_KEY = 'dropdownHelperFavorites';
const lastSearchMap = new WeakMap();
let settings = {
language: 'auto',
minOptions: 5,
defaultSort: 'asc',
caseSensitive: false
};
let favorites = {};
let currentHelperWindow = null;
let currentLang = chrome.i18n.getUILanguage().substring(0, 2);
function i18n(key) {
return chrome.i18n.getMessage(key);
}
function refreshAllHelperButtons() {
document.querySelectorAll('select').forEach(selectEl => {
const existingButton = selectEl.nextElementSibling;
const shouldShow = selectEl.options.length > settings.minOptions;
if (shouldShow && !existingButton?.classList.contains('select-helper-trigger-btn')) {
addHelperButton(selectEl);
} else if (!shouldShow && existingButton?.classList.contains('select-helper-trigger-btn')) {
existingButton.remove();
}
});
}
function addHelperButton(selectElement) {
const button = document.createElement('button');
button.className = 'select-helper-trigger-btn';
button.textContent = '🔍';
button.title = i18n('helperButtonTitle');
button.addEventListener('click', (e) => {
e.stopPropagation();
e.preventDefault();
createHelperWindow(selectElement);
});
selectElement.parentNode.insertBefore(button, selectElement.nextSibling);
}
function createHelperWindow(targetSelect) {
closeHelperWindow();
const helperWindow = document.createElement('div');
helperWindow.id = 'select-helper-window';
currentHelperWindow = helperWindow;
let highlightedIndex = 0;
const topArea = document.createElement('div');
topArea.className = 'top-area';
const searchInput = document.createElement('input');
searchInput.type = 'text';
searchInput.placeholder = i18n('searchInputPlaceholder');
const resultCounter = document.createElement('span');
resultCounter.className = 'result-counter';
const copyButton = document.createElement('button');
copyButton.className = 'copy-button';
copyButton.title = i18n('copyButtonTitle');
copyButton.innerHTML = i18n('copyButtonText');
topArea.append(searchInput, resultCounter);
const optionsList = document.createElement('div');
optionsList.id = 'select-helper-options-list';
let options = Array.from(targetSelect.options);
options.sort((a, b) => {
const aIsFav = favorites[a.value] === a.textContent;
const bIsFav = favorites[b.value] === b.textContent;
if (aIsFav && !bIsFav) return -1;
if (!aIsFav && bIsFav) return 1;
if (settings.defaultSort === 'asc') return a.textContent.localeCompare(b.textContent, currentLang);
if (settings.defaultSort === 'desc') return b.textContent.localeCompare(a.textContent, currentLang);
return 0;
});
options.forEach(opt => {
const optionItem = document.createElement('div');
optionItem.className = 'select-helper-option';
optionItem.dataset.value = opt.value;
const star = document.createElement('span');
star.className = 'favorite-star';
const isFavorite = favorites[opt.value] === opt.textContent;
star.textContent = isFavorite ? '⭐' : '☆';
if (isFavorite) optionItem.classList.add('is-favorite');
const textNode = document.createElement('span');
textNode.className = 'option-text';
textNode.textContent = opt.textContent;
optionItem.append(star, textNode);
if (opt.selected) optionItem.classList.add('selected');
optionsList.appendChild(optionItem);
});
helperWindow.append(topArea, optionsList, copyButton);
document.body.appendChild(helperWindow);
const rect = targetSelect.getBoundingClientRect();
helperWindow.style.top = `${window.scrollY + rect.bottom + 2}px`;
helperWindow.style.left = `${window.scrollX + rect.left}px`;
helperWindow.style.minWidth = `${rect.width}px`;
searchInput.focus();
function updateHighlight() {
const visibleItems = Array.from(optionsList.querySelectorAll('.select-helper-option')).filter(item => item.style.display !== 'none');
if (highlightedIndex >= visibleItems.length) highlightedIndex = 0;
if (visibleItems.length > 0 && highlightedIndex < 0) highlightedIndex = 0;
visibleItems.forEach((item, index) => {
if (index === highlightedIndex) {
item.classList.add('keyboard-highlight');
item.scrollIntoView({ block: 'nearest' });
} else {
item.classList.remove('keyboard-highlight');
}
});
}
function filterAndRenderList() {
highlightedIndex = 0;
const keyword = searchInput.value;
const regex = new RegExp(keyword, settings.caseSensitive ? 'g' : 'gi');
let visibleCount = 0;
optionsList.querySelectorAll('.select-helper-option').forEach(item => {
const textNode = item.querySelector('.option-text');
if (!textNode) return;
const text = textNode.textContent;
const textToCompare = settings.caseSensitive ? text : text.toLowerCase();
const keywordToCompare = settings.caseSensitive ? keyword : keyword.toLowerCase();
if (textToCompare.includes(keywordToCompare)) {
item.style.display = 'flex';
visibleCount++;
if (keyword) {
textNode.innerHTML = text.replace(regex, match => `<span class="highlight">${match}</span>`);
} else {
textNode.innerHTML = text;
}
} else {
item.style.display = 'none';
}
});
resultCounter.textContent = `${visibleCount} ${i18n('itemCounterSuffix')}`;
updateHighlight();
}
const lastKeyword = lastSearchMap.get(targetSelect) || '';
searchInput.value = lastKeyword;
filterAndRenderList();
searchInput.addEventListener('keyup', (e) => {
if (['ArrowDown', 'ArrowUp', 'Enter', 'Escape'].includes(e.key)) return;
lastSearchMap.set(targetSelect, searchInput.value);
filterAndRenderList();
});
searchInput.addEventListener('keydown', (e) => {
const visibleItems = Array.from(optionsList.querySelectorAll('.select-helper-option')).filter(item => item.style.display !== 'none');
if (visibleItems.length === 0) return;
switch (e.key) {
case 'ArrowDown': e.preventDefault(); highlightedIndex = (highlightedIndex < visibleItems.length - 1) ? highlightedIndex + 1 : 0; updateHighlight(); break;
case 'ArrowUp': e.preventDefault(); highlightedIndex = (highlightedIndex > 0) ? highlightedIndex - 1 : visibleItems.length - 1; updateHighlight(); break;
case 'Enter': e.preventDefault(); if (highlightedIndex >= 0) { visibleItems[highlightedIndex].click(); } break;
case 'Escape': e.preventDefault(); closeHelperWindow(); break;
}
});
optionsList.addEventListener('click', e => {
const targetItem = e.target.closest('.select-helper-option');
if (!targetItem) return;
if (e.target.classList.contains('favorite-star')) {
const value = targetItem.dataset.value;
const text = targetItem.querySelector('.option-text').textContent;
const star = e.target;
if (favorites[value] === text) {
delete favorites[value];
star.textContent = '☆';
targetItem.classList.remove('is-favorite');
} else {
favorites[value] = text;
star.textContent = '⭐';
targetItem.classList.add('is-favorite');
}
chrome.storage.sync.set({ [FAVORITES_KEY]: favorites });
} else {
targetSelect.value = targetItem.dataset.value;
targetSelect.dispatchEvent(new Event('change', { bubbles: true }));
closeHelperWindow();
}
});
copyButton.addEventListener('click', () => {
const visibleItems = Array.from(optionsList.querySelectorAll('.select-helper-option'))
.filter(item => item.style.display !== 'none')
.map(item => item.querySelector('.option-text').textContent)
.join('\n');
navigator.clipboard.writeText(visibleItems).then(() => {
copyButton.innerHTML = i18n('copyButtonSuccess');
setTimeout(() => { copyButton.innerHTML = i18n('copyButtonText'); }, 1200);
});
});
}
function closeHelperWindow() {
if (currentHelperWindow) {
currentHelperWindow.remove();
currentHelperWindow = null;
}
}
document.addEventListener('click', event => {
if (currentHelperWindow && !currentHelperWindow.contains(event.target)) {
closeHelperWindow();
}
});
// --- ✅ 변경된 부분: 실행 순서 수정 ---
// 1. 저장된 설정을 먼저 불러옵니다.
chrome.storage.sync.get([
'language', 'minOptions', 'defaultSort', 'caseSensitive', FAVORITES_KEY
], (data) => {
settings = data;
if (settings.language !== 'auto') {
currentLang = settings.language;
}
favorites = data[FAVORITES_KEY] || {};
// 설정이 로드된 후, 페이지에 이미 있는 드롭다운들을 스캔합니다.
refreshAllHelperButtons();
});
// 2. 설정 변경을 감지하는 리스너는 독립적으로 실행됩니다.
chrome.storage.onChanged.addListener((changes, namespace) => {
let languageChanged = false;
for (let key in changes) {
if (settings.hasOwnProperty(key)) {
settings[key] = changes[key].newValue;
}
if (key === 'language') {
languageChanged = true;
}
}
if (changes[FAVORITES_KEY]) {
favorites = changes[FAVORITES_KEY].newValue || {};
}
if (languageChanged) {
if (settings.language !== 'auto') {
currentLang = settings.language;
} else {
currentLang = chrome.i18n.getUILanguage().substring(0, 2);
}
closeHelperWindow();
}
refreshAllHelperButtons();
});
// 3. 페이지의 동적 변화를 감지하는 옵저버도 독립적으로 즉시 실행됩니다.
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
mutation.addedNodes.forEach((node) => {
if (node.nodeType === 1) {
if (node.tagName === 'SELECT') { // 새로 추가된 노드가 select 자체일 경우
refreshAllHelperButtons(); // 간단하게 전체를 다시 스캔
} else if (node.querySelectorAll('select').length > 0) { // 새로 추가된 노드 안에 select가 있을 경우
refreshAllHelperButtons();
}
}
});
});
});
observer.observe(document.body, { childList: true, subtree: true });