-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
362 lines (312 loc) · 10.4 KB
/
popup.js
File metadata and controls
362 lines (312 loc) · 10.4 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
/**
* TabSave - popup.js
* 核心逻辑:加载标签页、读取书签树、检测重复、批量保存、i18n
*/
// ===== i18n 辅助 =====
function t(key, substitutions) {
return chrome.i18n.getMessage(key, substitutions) || key;
}
/** 扫描 DOM 中 data-i18n / data-i18n-placeholder 属性并替换文本 */
function applyI18n() {
document.querySelectorAll('[data-i18n]').forEach(el => {
const key = el.getAttribute('data-i18n');
const msg = t(key);
if (msg) el.textContent = msg;
});
document.querySelectorAll('[data-i18n-placeholder]').forEach(el => {
const key = el.getAttribute('data-i18n-placeholder');
const msg = t(key);
if (msg) el.placeholder = msg;
});
}
// ===== DOM 引用 =====
const tabCountEl = document.getElementById('tab-count');
const tabListEl = document.getElementById('tab-list');
const folderSelect = document.getElementById('folder-select');
const toggleNewBtn = document.getElementById('toggle-new-folder');
const newFolderArea = document.getElementById('new-folder-area');
const newFolderName = document.getElementById('new-folder-name');
const newFolderParent= document.getElementById('new-folder-parent');
const dupSection = document.getElementById('duplicate-section');
const dupListEl = document.getElementById('duplicate-list');
const resultBar = document.getElementById('result-bar');
const saveBtn = document.getElementById('save-btn');
// ===== 状态 =====
let allTabs = [];
let bookmarkTree = [];
let folderMap = {};
let duplicates = [];
// ===== 初始化 =====
document.addEventListener('DOMContentLoaded', async () => {
applyI18n();
await Promise.all([loadTabs(), loadBookmarks()]);
checkDuplicates();
updateSaveBtn();
});
// ===== 加载标签页 =====
async function loadTabs() {
const tabs = await chrome.tabs.query({ currentWindow: true });
allTabs = tabs.filter(tab => tab.url && /^https?:\/\//i.test(tab.url));
tabCountEl.textContent = t('tabCount', [String(allTabs.length)]);
if (allTabs.length === 0) {
tabListEl.innerHTML = '';
const emptyDiv = document.createElement('div');
emptyDiv.className = 'loading';
emptyDiv.textContent = t('noTabs');
tabListEl.appendChild(emptyDiv);
return;
}
tabListEl.innerHTML = '';
allTabs.forEach(tab => {
const item = document.createElement('div');
item.className = 'tab-item';
if (tab.favIconUrl && tab.favIconUrl.startsWith('http')) {
const img = document.createElement('img');
img.className = 'tab-favicon';
img.src = tab.favIconUrl;
img.alt = '';
img.onerror = () => { img.style.display = 'none'; };
item.appendChild(img);
} else {
const placeholder = document.createElement('div');
placeholder.className = 'tab-favicon-placeholder';
item.appendChild(placeholder);
}
const title = tab.title || tab.url;
const url = tab.url;
const info = document.createElement('div');
info.className = 'tab-info';
const titleEl = document.createElement('div');
titleEl.className = 'tab-title';
titleEl.title = title;
titleEl.textContent = title;
const urlEl = document.createElement('div');
urlEl.className = 'tab-url';
urlEl.title = url;
urlEl.textContent = url;
info.appendChild(titleEl);
info.appendChild(urlEl);
item.appendChild(info);
tabListEl.appendChild(item);
});
}
// ===== 加载书签树 =====
async function loadBookmarks() {
const tree = await chrome.bookmarks.getTree();
bookmarkTree = tree;
folderMap = {};
collectFolders(tree, folderMap);
folderSelect.innerHTML = '';
const defOpt = document.createElement('option');
defOpt.value = '';
defOpt.textContent = t('folderPlaceholder');
folderSelect.appendChild(defOpt);
newFolderParent.innerHTML = '';
const rootOpt = document.createElement('option');
rootOpt.value = '';
rootOpt.textContent = t('parentFolderRoot');
newFolderParent.appendChild(rootOpt);
buildFolderOptions(tree, folderSelect, 0);
buildFolderOptions(tree, newFolderParent, 0);
}
function collectFolders(nodes, map) {
nodes.forEach(node => {
if (!node.url) {
map[node.id] = node;
if (node.children) collectFolders(node.children, map);
}
});
}
function buildFolderOptions(nodes, selectEl, depth) {
nodes.forEach(node => {
if (!node.url) {
if (node.id === '0') {
if (node.children) buildFolderOptions(node.children, selectEl, depth);
return;
}
const indent = '\u00A0\u00A0'.repeat(depth);
const option = document.createElement('option');
option.value = node.id;
option.textContent = indent + (depth > 0 ? '\uD83D\uDCC1 ' : '') + (node.title || t('noTitle'));
selectEl.appendChild(option);
if (node.children) buildFolderOptions(node.children, selectEl, depth + 1);
}
});
}
// ===== 新建文件夹切换 =====
toggleNewBtn.addEventListener('click', () => {
const isHidden = newFolderArea.classList.contains('hidden');
newFolderArea.classList.toggle('hidden', !isHidden);
toggleNewBtn.textContent = isHidden ? t('cancelNewFolder') : t('newFolder');
if (!isHidden) {
checkDuplicates();
} else {
hideDuplicates();
}
updateSaveBtn();
});
// ===== 检测重复 =====
folderSelect.addEventListener('change', () => {
// 文件夹变了,重置 saveSucceeded 允许再次保存
saveSucceeded = false;
checkDuplicates();
updateSaveBtn();
});
newFolderName.addEventListener('input', () => {
saveSucceeded = false;
updateSaveBtn();
});
let checkVersion = 0;
async function checkDuplicates() {
const folderId = folderSelect.value;
const usingNewFolder = !newFolderArea.classList.contains('hidden');
if (!folderId || usingNewFolder) {
hideDuplicates();
return;
}
const version = ++checkVersion;
const children = await chrome.bookmarks.getChildren(folderId);
if (version !== checkVersion) return;
const existingUrls = {};
children.forEach(bm => {
if (bm.url) existingUrls[bm.url] = bm;
});
duplicates = allTabs
.filter(tab => existingUrls[tab.url])
.map(tab => ({ tab, existing: existingUrls[tab.url] }));
if (duplicates.length === 0) {
hideDuplicates();
return;
}
dupListEl.innerHTML = '';
duplicates.forEach(({ tab }) => {
const item = document.createElement('div');
item.className = 'dup-item';
const icon = document.createElement('span');
icon.className = 'dup-icon';
icon.textContent = '\u26A0';
const titleEl = document.createElement('span');
titleEl.className = 'dup-title';
titleEl.title = tab.url;
titleEl.textContent = tab.title || tab.url;
item.appendChild(icon);
item.appendChild(titleEl);
dupListEl.appendChild(item);
});
dupSection.classList.remove('hidden');
}
function hideDuplicates() {
duplicates = [];
dupSection.classList.add('hidden');
}
// ===== 更新保存按钮状态 =====
function updateSaveBtn() {
if (saveSucceeded) {
saveBtn.disabled = true;
return;
}
if (allTabs.length === 0) {
saveBtn.disabled = true;
return;
}
const usingNewFolder = !newFolderArea.classList.contains('hidden');
if (usingNewFolder) {
saveBtn.disabled = newFolderName.value.trim() === '';
} else {
saveBtn.disabled = folderSelect.value === '';
}
}
// ===== 按钮 SVG 模板 =====
const SAVE_BTN_SVG = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M17 3H7C5.9 3 5 3.9 5 5V21L12 18L19 21V5C19 3.9 18.1 3 17 3Z" fill="white"/></svg>';
function setSaveBtnText(msgKey) {
saveBtn.innerHTML = '';
const svgWrapper = document.createElement('span');
svgWrapper.innerHTML = SAVE_BTN_SVG;
saveBtn.appendChild(svgWrapper.firstChild);
const span = document.createElement('span');
span.textContent = t(msgKey);
saveBtn.appendChild(span);
}
let saveSucceeded = false;
// ===== 保存逻辑 =====
saveBtn.addEventListener('click', async () => {
if (saveSucceeded) return;
saveBtn.disabled = true;
saveBtn.classList.add('saving');
setSaveBtnText('saving');
resultBar.classList.add('hidden');
let succeeded = false;
try {
let targetFolderId = folderSelect.value;
const usingNewFolder = !newFolderArea.classList.contains('hidden');
if (usingNewFolder) {
const name = newFolderName.value.trim();
if (!name) {
showResult('error', t('errorNoName'));
return;
}
const parentId = newFolderParent.value || undefined;
const newFolder = await chrome.bookmarks.create({ parentId, title: name });
targetFolderId = newFolder.id;
await loadBookmarks();
folderSelect.value = newFolder.id;
newFolderArea.classList.add('hidden');
toggleNewBtn.textContent = t('newFolder');
}
if (!targetFolderId) {
showResult('error', t('errorNoFolder'));
return;
}
const children = await chrome.bookmarks.getChildren(targetFolderId);
const existingMap = {};
children.forEach(bm => {
if (bm.url) existingMap[bm.url] = bm;
});
const dupAction = document.querySelector('input[name="dup-action"]:checked')?.value || 'skip';
let savedCount = 0;
let skippedCount = 0;
let overwriteCount = 0;
for (const tab of allTabs) {
const existing = existingMap[tab.url];
if (existing) {
if (dupAction === 'skip') {
skippedCount++;
} else if (dupAction === 'overwrite') {
await chrome.bookmarks.update(existing.id, { title: tab.title || tab.url });
overwriteCount++;
}
continue;
}
await chrome.bookmarks.create({
parentId: targetFolderId,
title: tab.title || tab.url,
url: tab.url,
});
savedCount++;
}
const parts = [];
if (savedCount > 0) parts.push(t('resultSaved', [String(savedCount)]));
if (overwriteCount > 0) parts.push(t('resultUpdated', [String(overwriteCount)]));
if (skippedCount > 0) parts.push(t('resultSkipped', [String(skippedCount)]));
const msg = parts.length > 0 ? parts.join(t('resultJoiner')) : t('resultNone');
showResult('success', msg);
succeeded = true;
saveSucceeded = true;
hideDuplicates();
} catch (err) {
showResult('error', t('errorSaveFailed', [err.message]));
} finally {
saveBtn.classList.remove('saving');
setSaveBtnText('saveBtn');
if (succeeded) {
saveBtn.disabled = true;
} else {
updateSaveBtn();
}
}
});
// ===== 工具函数 =====
function showResult(type, message) {
resultBar.textContent = message;
resultBar.className = `result-bar ${type}`;
}