-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathbackground.js
More file actions
553 lines (502 loc) · 18.4 KB
/
Copy pathbackground.js
File metadata and controls
553 lines (502 loc) · 18.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
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
// background.js
// Track tabs where we've already inserted CSS to avoid duplicates
const cssInjectedTabs = new Set();
// Import modules for pinned tabs functionality
importScripts('js/pinnedTabs.js');
importScripts('js/autoPinSync.js');
importScripts('js/datedLinks.js');
importScripts('js/customTitles.js');
// Function to update the badge based on items due today
async function updateDueTodayBadge() {
try {
console.log('[Badge] updateDueTodayBadge called');
if (typeof self.datedLinksModule === 'undefined') {
console.warn('[Badge] datedLinksModule not available');
return;
}
const datedLinks = await self.datedLinksModule.load();
console.log('[Badge] Loaded dated links:', datedLinks.length, 'items');
const today = new Date();
today.setHours(0, 0, 0, 0);
console.log('[Badge] Today is:', today.toISOString());
// Count items due exactly today (not overdue)
const dueTodayItems = datedLinks.filter(item => {
const itemDate = new Date(item.date);
itemDate.setHours(0, 0, 0, 0);
const isToday = itemDate.getTime() === today.getTime();
console.log(`[Badge] Item "${item.title}" date: ${item.date}, isToday: ${isToday}`);
return isToday;
});
const dueTodayCount = dueTodayItems.length;
console.log('[Badge] Items due today:', dueTodayCount);
if (dueTodayCount > 0) {
// Show red badge with count
await chrome.action.setBadgeText({ text: String(dueTodayCount) });
await chrome.action.setBadgeBackgroundColor({ color: '#FF4444' });
console.log(`[Badge] Set badge to ${dueTodayCount} items due today`);
} else {
// Clear badge
await chrome.action.setBadgeText({ text: '' });
console.log('[Badge] Cleared badge - no items due today');
}
} catch (error) {
console.error('[Badge] Failed to update badge:', error);
}
}
// Initialize auto-pin sync on extension startup
chrome.runtime.onStartup.addListener(() => {
if (self.autoPinSync) {
self.autoPinSync.init();
}
// Update badge on startup
updateDueTodayBadge();
});
// Also initialize on extension install
chrome.runtime.onInstalled.addListener(() => {
if (self.autoPinSync) {
self.autoPinSync.init();
}
// Update badge on install
updateDueTodayBadge();
});
async function toggleCommandBar() {
console.log('toggleCommandBar called');
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (!tab) {
console.warn('No active tab found');
return;
}
console.log('Active tab:', tab.url, 'ID:', tab.id);
// Skip restricted URLs
if (tab.url?.startsWith('chrome://') || tab.url?.startsWith('edge://') || tab.url?.startsWith('chrome-extension://')) {
console.warn('Cannot inject into restricted URL:', tab.url);
return;
}
try {
console.log('Starting injection process...');
// Insert CSS once per tab lifecycle
if (tab.id && !cssInjectedTabs.has(tab.id)) {
console.log('Injecting CSS...');
await chrome.scripting.insertCSS({
target: { tabId: tab.id },
files: ["shadow-overlay.css"]
});
cssInjectedTabs.add(tab.id);
console.log('CSS injected successfully');
}
// Inject content script (idempotent due to in-script guard)
console.log('Injecting content script...');
await chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ["content.js"]
});
console.log('Content script injected successfully');
// toggle overlay
console.log('Sending TOGGLE message...');
chrome.tabs.sendMessage(tab.id, { type: "TOGGLE" });
console.log('TOGGLE message sent');
} catch (error) {
console.error('Failed to inject content script or CSS:', error);
}
}
async function openExtensionPopup() {
try {
// Ensure there is a focused browser window; create one if none exist.
const ensureFocusedWindow = async () => {
const getLastFocused = () => new Promise((resolve) => {
chrome.windows.getLastFocused({ populate: false }, (win) => {
if (chrome.runtime.lastError) {
resolve(null);
} else {
resolve(win);
}
});
});
const focusWindow = (windowId) => new Promise((resolve) => {
chrome.windows.update(windowId, { focused: true }, () => resolve());
});
const createWindow = () => new Promise((resolve, reject) => {
chrome.windows.create({ url: 'chrome://newtab/', focused: true }, (win) => {
if (chrome.runtime.lastError || !win) {
reject(chrome.runtime.lastError || new Error('Failed to create window'));
} else {
resolve(win);
}
});
});
let win = await getLastFocused();
if (!win || win.state === 'minimized') {
win = await createWindow();
} else {
await focusWindow(win.id);
}
return win;
};
await ensureFocusedWindow();
await chrome.action.openPopup();
} catch (error) {
console.error('Failed to open extension popup:', error);
}
}
chrome.commands.onCommand.addListener(async (command) => {
if (command === "toggle-command-bar") {
await toggleCommandBar();
} else if (command === "open-extension-popup") {
await openExtensionPopup();
}
});
// Enable opening side panel on action click with modifier key
chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true }).catch(() => {});
chrome.action.onClicked.addListener(async (tab) => {
// Default behavior: toggle command bar overlay
await toggleCommandBar();
});
// Listen for tab events to update tab count and badge
chrome.tabs.onCreated.addListener(() => {
// Send message to all tabs to update their tab count
chrome.tabs.query({}, (tabs) => {
tabs.forEach(t => {
if (t.id) {
chrome.tabs.sendMessage(t.id, { type: "TAB_COUNT_CHANGED" }).catch(() => {});
}
});
});
// Update badge when tabs are created
updateDueTodayBadge();
});
chrome.tabs.onRemoved.addListener(() => {
// Send message to all tabs to update their tab count
chrome.tabs.query({}, (tabs) => {
tabs.forEach(t => {
if (t.id) {
chrome.tabs.sendMessage(t.id, { type: "TAB_COUNT_CHANGED" }).catch(() => {});
}
});
});
// Update badge when tabs are removed
updateDueTodayBadge();
});
// Clear CSS tracking when tabs close
chrome.tabs.onRemoved.addListener((tabId) => {
cssInjectedTabs.delete(tabId);
});
// handle search queries from content script
async function getBookmarkPath(node) {
const parts = [];
let current = node;
while (current && current.parentId) {
current = await chrome.bookmarks.get(current.parentId).then(arr => arr[0]).catch(() => null);
if (current && current.title) parts.unshift(current.title);
if (current && (!current.parentId || current.parentId === '0')) break;
}
return parts.join(' / ');
}
async function search(query) {
const [tabs, bookmarkTree, historyItems, customTitlesData] = await Promise.all([
chrome.tabs.query({}),
chrome.bookmarks.search({ query }),
chrome.history.search({ text: query, maxResults: 20 }),
self.customTitlesModule ? self.customTitlesModule.load() : {}
]);
// Helper function to get custom title for an item (from customTitles storage only)
const getCustomTitle = (url) => {
if (!url || !customTitlesData || Object.keys(customTitlesData).length === 0) return null;
const normalized = self.customTitlesModule ? self.customTitlesModule.normalizeUrl(url) : url;
return customTitlesData[normalized] || null;
};
// Helper function to check if item matches query (original title OR custom title)
const matchesQuery = (originalTitle, url, query) => {
const lowerQuery = query.toLowerCase();
// Check original title
if (originalTitle && originalTitle.toLowerCase().includes(lowerQuery)) return true;
// Check custom title
const customTitle = getCustomTitle(url);
if (customTitle && customTitle.toLowerCase().includes(lowerQuery)) return true;
// Check URL
if (url && url.toLowerCase().includes(lowerQuery)) return true;
return false;
};
const tabMatches = tabs.filter(t => matchesQuery(t.title, t.url, query));
// Sort tabs by windowId first, then by index to maintain proper order
tabMatches.sort((a, b) => {
if (a.windowId !== b.windowId) {
return a.windowId - b.windowId;
}
return a.index - b.index;
});
const tabResults = tabMatches.map(t => ({
id: t.id,
title: t.title,
url: t.url,
customTitle: getCustomTitle(t.url),
source: "tab",
icon: t.favIconUrl && !t.favIconUrl.startsWith('chrome://') ? t.favIconUrl : '',
type: 'tab',
windowId: t.windowId,
index: t.index,
lastAccessed: t.lastAccessed || 0
}));
// Resolve bookmark folder paths concurrently
const bookmarkResults = await Promise.all(bookmarkTree.map(async (b) => {
const folderPath = await getBookmarkPath(b);
return { id: b.id, title: b.title, url: b.url, customTitle: getCustomTitle(b.url), source: "bookmark", icon: '', folder: folderPath, type: 'bookmark', dateAdded: b.dateAdded || 0 };
}));
const historyResults = historyItems.map(h => ({
id: h.id,
title: h.title,
url: h.url,
customTitle: getCustomTitle(h.url),
source: "history",
icon: '',
lastVisitTime: h.lastVisitTime || 0,
type: 'history'
}));
return [...tabResults, ...bookmarkResults, ...historyResults];
}
async function buildRecentFromTabs(tabs, activeId) {
const filtered = activeId ? tabs.filter((t) => t.id !== activeId) : tabs;
// Load custom titles from storage
const customTitlesData = self.customTitlesModule ? await self.customTitlesModule.load() : {};
// Helper function to get custom title for an item (from customTitles storage only)
const getCustomTitle = (url) => {
if (!url || !customTitlesData || Object.keys(customTitlesData).length === 0) return null;
const normalized = self.customTitlesModule ? self.customTitlesModule.normalizeUrl(url) : url;
return customTitlesData[normalized] || null;
};
return filtered.map((t) => ({
id: t.id,
title: t.title,
url: t.url,
customTitle: getCustomTitle(t.url),
source: "tab",
icon: t.favIconUrl && !t.favIconUrl.startsWith('chrome://') ? t.favIconUrl : '',
type: 'tab',
windowId: t.windowId,
index: t.index,
lastAccessed: t.lastAccessed || 0
}));
}
async function getPinnedTabsWithStatusFromTabs(openTabs) {
if (typeof pinnedTabsModule === 'undefined') {
return [];
}
const pinnedTabs = await pinnedTabsModule.load();
const normalizedOpenTabs = openTabs
.filter((t) => pinnedTabsModule.normalizeUrl(t.url))
.map((t) => ({
tab: t,
normalizedUrl: pinnedTabsModule.normalizeUrl(t.url)
}));
return pinnedTabs
.filter((pinnedTab) => pinnedTabsModule.normalizeUrl(pinnedTab.url))
.map((pinnedTab) => {
const pinnedNormalizedUrl = pinnedTabsModule.normalizeUrl(pinnedTab.url);
const match = normalizedOpenTabs.find((t) => t.normalizedUrl === pinnedNormalizedUrl);
const activeTab = match?.tab;
return {
...pinnedTab,
isActive: Boolean(activeTab),
tabId: activeTab?.id || null,
favicon: activeTab?.favIconUrl || pinnedTab.favicon
};
});
}
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.type === "SEARCH") {
const activeId = sender.tab?.id;
search(msg.query.toLowerCase()).then(results => {
const filtered = activeId ? results.filter(r => !(r.type === 'tab' && r.id === activeId)) : results;
sendResponse(filtered);
});
return true; // async
} else if (msg.type === "GET_INITIAL_STATE") {
(async () => {
try {
const activeId = sender.tab?.id;
const tabs = await chrome.tabs.query({});
const pinnedTabsWithStatus = await getPinnedTabsWithStatusFromTabs(tabs);
const recent = await buildRecentFromTabs(tabs, activeId);
sendResponse({
success: true,
recent: recent,
tabCount: tabs.length,
pinnedTabs: pinnedTabsWithStatus
});
} catch (error) {
console.error('Failed to get initial state:', error);
sendResponse({ success: false, error: error.message });
}
})();
return true; // async
} else if (msg.type === "RECENT") {
(async () => {
try {
const allTabs = await chrome.tabs.query({});
const activeId = sender.tab?.id;
const filtered = activeId ? allTabs.filter(t => t.id !== activeId) : allTabs;
// Don't pre-sort here - let content script sort by lastAccessed
const recent = await buildRecentFromTabs(filtered, null);
sendResponse(recent);
} catch (error) {
console.error('Failed to get recent tabs:', error);
sendResponse([]);
}
})();
return true;
} else if (msg.type === "DELETE") {
const { item } = msg;
if (item.type === 'tab') {
chrome.tabs.remove(item.id);
} else if (item.type === 'bookmark') {
chrome.bookmarks.remove(item.id);
} else if (item.type === 'history') {
chrome.history.deleteUrl({ url: item.url });
}
} else if (msg.type === "OPEN") {
const { item } = msg;
if (item.source === "tab") {
chrome.tabs.update(item.id, { active: true }, (tab) => {
if (chrome.runtime.lastError || !tab) return;
chrome.windows.update(tab.windowId, { focused: true });
});
} else {
chrome.tabs.create({ url: item.url });
}
} else if (msg.type === "GET_TAB_COUNT") {
chrome.tabs.query({}, (tabs) => {
sendResponse({ count: tabs.length });
});
return true; // async
} else if (msg.type === "RENAME_BOOKMARK") {
const { bookmarkId, newTitle } = msg;
chrome.bookmarks.update(bookmarkId, { title: newTitle }, (result) => {
if (chrome.runtime.lastError) {
console.error('Failed to rename bookmark:', chrome.runtime.lastError);
sendResponse({ success: false, error: chrome.runtime.lastError.message });
} else {
sendResponse({ success: true, result });
}
});
return true; // async
} else if (msg.type === "MOVE_BOOKMARK") {
const { bookmarkId, destinationId } = msg;
chrome.bookmarks.move(bookmarkId, { parentId: destinationId }, (result) => {
if (chrome.runtime.lastError) {
console.error('Failed to move bookmark:', chrome.runtime.lastError);
sendResponse({ success: false, error: chrome.runtime.lastError.message });
} else {
sendResponse({ success: true, result });
}
});
return true; // async
} else if (msg.type === "GET_BOOKMARK_TREE") {
chrome.bookmarks.getTree((tree) => {
if (chrome.runtime.lastError) {
console.error('Failed to get bookmark tree:', chrome.runtime.lastError);
sendResponse({ success: false, error: chrome.runtime.lastError.message });
} else {
sendResponse(tree);
}
});
return true; // async
} else if (msg.type === "CREATE_BOOKMARK") {
const { bookmarkData } = msg;
chrome.bookmarks.create(bookmarkData, (result) => {
if (chrome.runtime.lastError) {
console.error('Failed to create bookmark:', chrome.runtime.lastError);
sendResponse({ success: false, error: chrome.runtime.lastError.message });
} else {
sendResponse({ success: true, result });
}
});
return true; // async
} else if (msg.type === "GET_PINNED_TABS") {
(async () => {
try {
const tabs = await chrome.tabs.query({});
const pinnedTabsWithStatus = await getPinnedTabsWithStatusFromTabs(tabs);
sendResponse({ success: true, pinnedTabs: pinnedTabsWithStatus });
} catch (error) {
console.error('Failed to get pinned tabs:', error);
sendResponse({ success: false, error: error.message });
}
})();
return true; // async
} else if (msg.type === "ADD_PINNED_TAB") {
const { tabData } = msg;
// Use centralized storage for adding pinned tabs
if (typeof pinnedTabsModule !== 'undefined') {
(async () => {
try {
const success = await pinnedTabsModule.addPinnedTab(tabData);
if (success) {
sendResponse({ success: true });
} else {
sendResponse({ success: false, error: 'Failed to add pinned tab (may already exist or limit reached)' });
}
} catch (error) {
console.error('Failed to add pinned tab:', error);
sendResponse({ success: false, error: error.message });
}
})();
} else {
sendResponse({ success: false, error: 'Pinned tabs module not available' });
}
return true; // async
} else if (msg.type === "REMOVE_PINNED_TAB") {
const { url } = msg;
// Use centralized storage for removing pinned tabs
if (typeof pinnedTabsModule !== 'undefined') {
(async () => {
try {
const success = await pinnedTabsModule.removePinnedTab(url);
if (success) {
sendResponse({ success: true });
} else {
sendResponse({ success: false, error: 'Pinned tab not found' });
}
} catch (error) {
console.error('Failed to remove pinned tab:', error);
sendResponse({ success: false, error: error.message });
}
})();
} else {
sendResponse({ success: false, error: 'Pinned tabs module not available' });
}
return true; // async
} else if (msg.type === "CLOSE_PINNED_TAB") {
const { tabId } = msg;
chrome.tabs.remove(tabId, () => {
sendResponse({ success: true });
});
return true; // async
} else if (msg.type === "OPEN_PINNED_TAB") {
const { url } = msg;
chrome.tabs.create({ url, active: true, pinned: true }, (tab) => {
if (chrome.runtime.lastError) {
sendResponse({ success: false, error: chrome.runtime.lastError.message });
} else {
sendResponse({ success: true, tabId: tab.id });
}
});
return true; // async
} else if (msg.type === "ACTIVATE_TAB") {
const { tabId } = msg;
chrome.tabs.update(tabId, { active: true }, (tab) => {
if (chrome.runtime.lastError || !tab) {
sendResponse({ success: false });
return;
}
chrome.windows.update(tab.windowId, { focused: true });
sendResponse({ success: true });
});
return true; // async
}
});
// Listen for storage changes to update badge when dated links are modified
chrome.storage.onChanged.addListener((changes, namespace) => {
if (namespace === 'local' && changes.datedLinks) {
console.log('[Badge] Dated links changed, updating badge');
updateDueTodayBadge();
}
});