-
Notifications
You must be signed in to change notification settings - Fork 0
/
popup.js
475 lines (414 loc) · 16 KB
/
popup.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
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
// 弹出窗口脚本逻辑
document.addEventListener('DOMContentLoaded', function() {
console.log("DOM fully loaded and parsed");
// 获取所有待分组的插件
chrome.management.getAll(function(extensions) {
console.log("Retrieved all extensions:", extensions.length);
const allPluginsContainer = document.getElementById('extensions-list');
if (!allPluginsContainer) {
console.error("Could not find #extensions-list element");
return;
}
extensions.forEach(function(extension) {
const pluginIcon = createPluginIcon(extension);
allPluginsContainer.appendChild(pluginIcon);
});
console.log("Added all plugin icons to the container");
// 为所有插件图标添加点击事件监听器
document.querySelectorAll('.plugin-icon').forEach(addPluginIconClickListener);
// 加载保存的分组信息
loadGroups().then(() => {
console.log("Groups loaded successfully");
// 在加载完成后,保存一次分组信息,以确保所有数据都是最新的
saveGroups();
}).catch(error => {
console.error("Error loading groups:", error);
});
});
// 更新这里的按钮 ID
const createGroupButton = document.getElementById('create-group');
if (createGroupButton) {
createGroupButton.addEventListener('click', function() {
createGroup();
});
} else {
console.error("Could not find #create-group button");
}
// 添加保存按钮的事件监听器
const saveButton = document.getElementById('save-groups');
saveButton.addEventListener('click', function() {
saveGroups().then(() => {
showSaveConfirmation();
}).catch(error => {
console.error('Error saving groups:', error);
});
});
// 添加帮助图标的事件监听器
const helpIcon = document.getElementById('help-icon');
const helpPopup = document.getElementById('help-popup');
const closeHelpButton = document.getElementById('close-help');
helpIcon.addEventListener('click', function() {
helpPopup.classList.remove('hidden');
});
closeHelpButton.addEventListener('click', function() {
helpPopup.classList.add('hidden');
});
// 点击弹出窗口外部也可以关闭
helpPopup.addEventListener('click', function(event) {
if (event.target === helpPopup) {
helpPopup.classList.add('hidden');
}
});
// 实现拖放功能
implementDragAndDrop();
// 更新页面标题
document.title = chrome.i18n.getMessage("extName");
// 更新页面中的静态文本
document.querySelector('h1').textContent = chrome.i18n.getMessage("extName");
document.querySelector('#create-group').textContent = chrome.i18n.getMessage("createGroup");
document.querySelector('#save-groups').textContent = chrome.i18n.getMessage("saveGroups");
document.querySelector('#ungrouped-plugins h2').textContent = chrome.i18n.getMessage("ungroupedPlugins");
document.querySelector('#help-popup h3').textContent = chrome.i18n.getMessage("helpTitle");
document.querySelector('#help-popup p').textContent = chrome.i18n.getMessage("helpAbout");
document.querySelector('#close-help').textContent = chrome.i18n.getMessage("close");
// 更新帮助内容
const helpList = document.querySelector('#help-popup ol');
helpList.innerHTML = `
<li>${chrome.i18n.getMessage("helpContent1")}</li>
<li>${chrome.i18n.getMessage("helpContent2")}</li>
<li>${chrome.i18n.getMessage("helpContent3")}</li>
<li>${chrome.i18n.getMessage("helpContent4")}</li>
<li>${chrome.i18n.getMessage("helpContent5")}</li>
`;
// 初始化所有分组的展开/折叠按钮文本
document.querySelectorAll('.group').forEach(group => {
const toggleButton = group.querySelector('.toggle-button');
if (toggleButton) {
toggleButton.textContent = chrome.i18n.getMessage("collapse") || '折叠';
}
});
});
function createPluginIcon(extension) {
console.log("Creating plugin icon for:", extension.name, "with id:", extension.id);
const icon = document.createElement('div');
icon.className = 'plugin-icon';
icon.classList.add(`plugin-${extension.id}`);
icon.classList.add(extension.enabled ? 'enabled' : 'disabled');
icon.draggable = true;
icon.dataset.id = extension.id;
icon.title = chrome.i18n.getMessage(extension.name) || extension.name;
const img = document.createElement('img');
img.src = extension.icons && extension.icons.length > 0 ? extension.icons[0].url : 'default-icon.png';
img.draggable = false;
icon.appendChild(img);
const statusIndicator = document.createElement('div');
statusIndicator.className = 'status-indicator';
icon.appendChild(statusIndicator);
addPluginIconClickListener(icon);
return icon;
}
function addPluginIconClickListener(icon) {
icon.addEventListener('click', function(event) {
event.preventDefault(); // 防止触发拖拽
const pluginId = this.dataset.id;
const isEnabled = this.classList.contains('enabled');
togglePlugin(pluginId, !isEnabled);
});
}
function createGroup(name = chrome.i18n.getMessage("newGroup")) {
console.log("Creating new group");
const groupsContainer = document.getElementById('groups-container');
if (!groupsContainer) {
console.error("Could not find #groups-container element");
return;
}
const group = document.createElement('div');
group.className = 'group';
group.draggable = true;
const header = document.createElement('div');
header.className = 'group-header';
header.draggable = true; // 使整个头部可拖动
const groupName = document.createElement('span');
groupName.textContent = chrome.i18n.getMessage(name) || name;
groupName.contentEditable = true;
groupName.addEventListener('blur', function() {
if (this.textContent.trim() === '') {
this.textContent = chrome.i18n.getMessage("newGroup");
}
saveGroups();
});
header.appendChild(groupName);
const buttonContainer = document.createElement('div');
buttonContainer.className = 'group-buttons';
// 修改切换按钮
const toggleButton = document.createElement('button');
toggleButton.textContent = chrome.i18n.getMessage("collapse") || '折叠';
toggleButton.className = 'toggle-button';
toggleButton.addEventListener('click', function() {
toggleGroupContent(group);
});
buttonContainer.appendChild(toggleButton);
const enableAllButton = document.createElement('button');
enableAllButton.textContent = chrome.i18n.getMessage("enableAll");
enableAllButton.className = 'enable-all-button';
enableAllButton.addEventListener('click', function() {
enableAllInGroup(group.querySelector('.group-content'));
});
buttonContainer.appendChild(enableAllButton);
const dissolveButton = document.createElement('button');
dissolveButton.textContent = chrome.i18n.getMessage("dissolveGroup");
dissolveButton.className = 'dissolve-button';
dissolveButton.addEventListener('click', function() {
dissolveGroup(group);
});
buttonContainer.appendChild(dissolveButton);
header.appendChild(buttonContainer);
const content = document.createElement('div');
content.className = 'group-content';
group.appendChild(header);
group.appendChild(content);
groupsContainer.appendChild(group);
console.log("New group added to the container");
saveGroups();
return group;
}
// 修改切换分组内容的函数
function toggleGroupContent(group) {
const content = group.querySelector('.group-content');
const toggleButton = group.querySelector('.toggle-button');
if (content.style.display === 'none') {
content.style.display = 'flex';
toggleButton.textContent = chrome.i18n.getMessage("collapse") || '折叠';
} else {
content.style.display = 'none';
toggleButton.textContent = chrome.i18n.getMessage("expand") || '展开';
}
}
function dissolveGroup(group) {
const allPluginsContainer = document.getElementById('extensions-list');
const plugins = group.querySelectorAll('.plugin-icon');
plugins.forEach(plugin => {
allPluginsContainer.appendChild(plugin);
});
group.remove();
saveGroups();
}
function implementDragAndDrop() {
let draggedElement = null;
document.addEventListener('dragstart', function(event) {
if (event.target.classList.contains('plugin-icon')) {
draggedElement = event.target;
event.dataTransfer.setData('text/plain', 'plugin');
} else if (event.target.closest('.group-header')) {
draggedElement = event.target.closest('.group');
event.dataTransfer.setData('text/plain', 'group');
}
if (draggedElement) {
draggedElement.style.opacity = '0.5';
}
});
document.addEventListener('dragend', function(event) {
if (draggedElement) {
draggedElement.style.opacity = '1';
draggedElement = null;
}
});
document.addEventListener('dragover', function(event) {
event.preventDefault();
const target = event.target.closest('.group-content') || event.target.closest('.group') || event.target.closest('#extensions-list');
if (target) {
event.dataTransfer.dropEffect = 'move';
}
});
document.addEventListener('drop', function(event) {
event.preventDefault();
if (!draggedElement) return;
const target = event.target.closest('.group-content') || event.target.closest('.group') || event.target.closest('#extensions-list');
if (!target) return;
const dragType = event.dataTransfer.getData('text/plain');
if (dragType === 'plugin') {
if (target.classList.contains('group-content') || target.id === 'extensions-list') {
target.appendChild(draggedElement);
}
} else if (dragType === 'group') {
const groupsContainer = document.getElementById('groups-container');
if (target.classList.contains('group') && target !== draggedElement) {
if (isBeforeTarget(event, target)) {
groupsContainer.insertBefore(draggedElement, target);
} else {
groupsContainer.insertBefore(draggedElement, target.nextSibling);
}
}
}
saveGroups();
});
}
function isBeforeTarget(event, target) {
const targetRect = target.getBoundingClientRect();
const mouseY = event.clientY;
const threshold = targetRect.top + targetRect.height / 2;
return mouseY < threshold;
}
function togglePlugin(id, enable) {
chrome.management.setEnabled(id, enable, function() {
if (chrome.runtime.lastError) {
console.error('Error toggling plugin:', chrome.runtime.lastError);
} else {
const icon = document.querySelector(`.plugin-icon[data-id="${id}"]`);
if (icon) {
icon.classList.toggle('enabled', enable);
icon.classList.toggle('disabled', !enable);
console.log(`Plugin ${id} ${enable ? 'enabled' : 'disabled'}`);
saveGroups();
}
}
});
}
function enableAllInGroup(groupContent) {
const plugins = groupContent.querySelectorAll('.plugin-icon');
plugins.forEach(plugin => {
const pluginId = plugin.dataset.id;
chrome.management.setEnabled(pluginId, true, function() {
if (chrome.runtime.lastError) {
console.error('Error enabling plugin:', chrome.runtime.lastError);
} else {
plugin.classList.add('enabled');
plugin.classList.remove('disabled');
console.log(`Plugin ${pluginId} enabled`);
}
});
});
saveGroups();
}
// 保存分组信息
const debouncedSaveGroups = debounce(function() {
const groups = document.querySelectorAll('.group');
const groupsData = Array.from(groups).map(group => {
const name = group.querySelector('.group-header span').textContent;
const plugins = Array.from(group.querySelectorAll('.plugin-icon')).map(plugin => plugin.dataset.id);
return { name, plugins };
});
console.log("Groups data to be saved:", groupsData);
chrome.storage.local.set({ groups: groupsData }, function() {
if (chrome.runtime.lastError) {
console.error('Error saving groups:', chrome.runtime.lastError);
} else {
console.log('Groups saved successfully');
validateSavedGroups();
}
});
}, 300);
function saveGroups() {
console.log("Saving groups");
debouncedSaveGroups();
}
// 加载分组信息
function loadGroups() {
console.log("Attempting to load groups");
return new Promise((resolve, reject) => {
chrome.storage.local.get('groups', function(data) {
if (chrome.runtime.lastError) {
console.error('Error loading groups:', chrome.runtime.lastError);
reject(chrome.runtime.lastError);
} else {
console.log("Retrieved data from storage:", data);
if (data.groups && Array.isArray(data.groups) && data.groups.length > 0) {
console.log(`Found ${data.groups.length} saved groups`);
const groupsContainer = document.getElementById('groups-container');
if (!groupsContainer) {
console.error("Could not find #groups-container element");
reject(new Error("Could not find #groups-container element"));
return;
}
groupsContainer.innerHTML = ''; // Clear existing groups
data.groups.forEach((groupData, index) => {
console.log(`Creating group ${index + 1}:`, groupData);
const group = createGroup(groupData.name);
const groupContent = group.querySelector('.group-content');
groupData.plugins.forEach(pluginId => {
const pluginElement = document.querySelector(`.plugin-icon[data-id="${pluginId}"]`);
if (pluginElement) {
groupContent.appendChild(pluginElement);
} else {
console.warn(`Plugin with id ${pluginId} not found`);
}
});
});
} else {
console.log("No valid saved groups found");
}
resolve();
}
});
});
}
function validateSavedGroups() {
chrome.storage.local.get('groups', function(data) {
if (chrome.runtime.lastError) {
console.error('Error validating groups:', chrome.runtime.lastError);
} else {
console.log("Validating saved groups:", data.groups);
if (data.groups && Array.isArray(data.groups)) {
data.groups.forEach((group, index) => {
console.log(`Group ${index + 1}: ${group.name}`);
console.log(` Plugins: ${group.plugins.length}`);
group.plugins.forEach((pluginId, pluginIndex) => {
console.log(` Plugin ${pluginIndex + 1}: ${pluginId}`);
});
});
} else {
console.warn("No valid groups data found");
}
}
});
}
// 如果你想保留这个函数以便将来使用,可以这样修改:
function removeEmptyGroups() {
const groupsContainer = document.getElementById('groups-container');
const groups = Array.from(groupsContainer.children);
groups.forEach((group, index) => {
const pluginCount = group.querySelectorAll('.group-content .plugin-icon').length;
console.log(`Checking group ${index + 1}: ${pluginCount} plugins`);
// 不再删除空分组,只记录日志
if (pluginCount === 0) {
console.log(`Group ${index + 1} is empty`);
}
});
// 不再自动保存,因为我们没有做任何更改
// saveGroups();
}
// 添加保存确认提示函数
function showSaveConfirmation() {
const saveButton = document.getElementById('save-groups');
const originalText = saveButton.textContent;
saveButton.textContent = '已保存';
saveButton.disabled = true;
setTimeout(() => {
saveButton.textContent = originalText;
saveButton.disabled = false;
}, 2000);
}
window.onerror = function(message, source, lineno, colno, error) {
console.error("Global error:", message, "at", source, ":", lineno, ":", colno);
console.error("Error object:", error);
};
chrome.runtime.onInstalled.addListener(function() {
chrome.storage.local.get('groups', function(data) {
if (!data.groups) {
chrome.storage.local.set({groups: []}, function() {
console.log('Initialized empty groups array');
});
}
});
});