-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
330 lines (279 loc) · 9.14 KB
/
Copy pathbackground.js
File metadata and controls
330 lines (279 loc) · 9.14 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
import { groupByDomain } from "./utils/domainGrouping.js";
import { buildBookmarkTree, flattenBookmarkTree } from "./utils/treeBuilder.js";
import { defaultStore, getStore, migrateLegacyStorage, setStore } from "./utils/storage.js";
let reindexTimer = null;
/**
* @returns {Promise<{bookmarks: Array<{id: string, title: string, url: string, path: string, usageCount: number, pinned: boolean}>, usageStats: Record<string, number>, pinned: string[]}>}
*/
async function loadStore() {
await migrateLegacyStorage();
const store = await getStore();
return {
...defaultStore(),
...store
};
}
/**
* Rebuilds flattened bookmark index from Chrome tree while preserving usage + pin state.
*/
async function reindexBookmarks() {
const store = await loadStore();
const tree = await chrome.bookmarks.getTree();
const builtTree = buildBookmarkTree(tree, store.usageStats, new Set(store.pinned));
const bookmarks = flattenBookmarkTree(builtTree);
await setStore({
...store,
bookmarks
});
}
/**
* Schedules coalesced reindexing for bookmark mutation bursts.
* @param {number} delayMs
*/
function scheduleReindex(delayMs = 200) {
if (reindexTimer) {
clearTimeout(reindexTimer);
}
reindexTimer = setTimeout(async () => {
reindexTimer = null;
try {
await reindexBookmarks();
} catch (error) {
console.error("Failed to reindex bookmarks", error);
}
}, delayMs);
}
/**
* @param {string} url
* @param {"new-tab" | "current-tab" | "background-tab"} disposition
*/
async function openWithDisposition(url, disposition) {
if (disposition === "background-tab") {
await chrome.tabs.create({ url, active: false });
return;
}
if (disposition === "current-tab") {
const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (activeTab?.id != null) {
await chrome.tabs.update(activeTab.id, { url, active: true });
return;
}
}
await chrome.tabs.create({ url, active: true });
}
/**
* @param {string} bookmarkId
* @param {"new-tab" | "current-tab" | "background-tab"} disposition
* @returns {Promise<{ok: boolean, usageCount?: number, message?: string}>}
*/
async function openBookmarkAndTrack(bookmarkId, disposition) {
const store = await loadStore();
let bookmarks = store.bookmarks;
if (!bookmarks.length) {
await reindexBookmarks();
const refreshed = await loadStore();
bookmarks = refreshed.bookmarks;
store.bookmarks = bookmarks;
}
const bookmark = bookmarks.find((item) => item.id === bookmarkId);
if (!bookmark?.url) {
return { ok: false, message: "Bookmark not found." };
}
const nextUsageCount = (Number(store.usageStats[bookmarkId]) || 0) + 1;
store.usageStats[bookmarkId] = nextUsageCount;
bookmark.usageCount = nextUsageCount;
await setStore(store);
await openWithDisposition(bookmark.url, disposition);
return { ok: true, usageCount: nextUsageCount };
}
/**
* @param {string} bookmarkId
* @returns {Promise<{ok: boolean, pinned?: boolean, message?: string}>}
*/
async function togglePin(bookmarkId) {
const store = await loadStore();
const pinnedSet = new Set(store.pinned);
let pinned = false;
if (pinnedSet.has(bookmarkId)) {
pinnedSet.delete(bookmarkId);
} else {
pinnedSet.add(bookmarkId);
pinned = true;
}
store.pinned = [...pinnedSet];
store.bookmarks = store.bookmarks.map((bookmark) =>
bookmark.id === bookmarkId ? { ...bookmark, pinned } : bookmark
);
await setStore(store);
return { ok: true, pinned };
}
/**
* @returns {Promise<{ok: true, tree: import("./utils/treeBuilder.js").BookmarkNode[], bookmarks: Array<{id: string, title: string, url: string, path: string, usageCount: number, pinned: boolean}>}>}
*/
async function getTreeData() {
const store = await loadStore();
const tree = await chrome.bookmarks.getTree();
const builtTree = buildBookmarkTree(tree, store.usageStats, new Set(store.pinned));
const bookmarks = flattenBookmarkTree(builtTree);
if (bookmarks.length !== store.bookmarks.length) {
await setStore({ ...store, bookmarks });
}
return { ok: true, tree: builtTree, bookmarks };
}
/**
* @param {string[]} bookmarkIds
* @returns {Promise<{ok: boolean, deletedCount?: number, message?: string}>}
*/
async function deleteBookmarks(bookmarkIds) {
const ids = [...new Set(bookmarkIds.map((id) => String(id)).filter(Boolean))];
if (!ids.length) {
return { ok: false, message: "No bookmark IDs provided." };
}
for (const id of ids) {
try {
await chrome.bookmarks.remove(id);
} catch (error) {
console.warn(`Failed to delete bookmark ${id}`, error);
}
}
await reindexBookmarks();
return { ok: true, deletedCount: ids.length };
}
/**
* @returns {Promise<{ok: true, analytics: {
* totalBookmarks: number,
* mostUsedBookmark: string,
* mostUsedDomain: string,
* mostUsedFolder: string,
* topBookmarks: Array<{title: string, url: string, usageCount: number, path: string}>,
* topDomains: Array<{domain: string, usageCount: number, bookmarkCount: number}>
* }}>}
*/
async function getAnalyticsData() {
const store = await loadStore();
const bookmarks = store.bookmarks;
const topBookmarks = [...bookmarks]
.sort((a, b) => (b.usageCount || 0) - (a.usageCount || 0))
.slice(0, 10)
.map((bookmark) => ({
title: bookmark.title,
url: bookmark.url,
usageCount: Number(bookmark.usageCount) || 0,
path: bookmark.path
}));
const mostUsedBookmark = topBookmarks[0]?.title || "N/A";
const folderUsageMap = new Map();
for (const bookmark of bookmarks) {
const key = bookmark.path || "(Root)";
folderUsageMap.set(key, (folderUsageMap.get(key) || 0) + (Number(bookmark.usageCount) || 0));
}
const mostUsedFolder = [...folderUsageMap.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] || "N/A";
const grouped = groupByDomain(bookmarks);
const topDomains = grouped
.map((group) => ({
domain: group.domain,
bookmarkCount: group.count,
usageCount: group.items.reduce((sum, item) => sum + (Number(item.usageCount) || 0), 0)
}))
.sort((a, b) => b.usageCount - a.usageCount || b.bookmarkCount - a.bookmarkCount)
.slice(0, 5);
const mostUsedDomain = topDomains[0]?.domain || "N/A";
return {
ok: true,
analytics: {
totalBookmarks: bookmarks.length,
mostUsedBookmark,
mostUsedDomain,
mostUsedFolder,
topBookmarks,
topDomains
}
};
}
chrome.runtime.onInstalled.addListener(() => {
scheduleReindex(0);
});
chrome.runtime.onStartup.addListener(() => {
scheduleReindex(0);
});
chrome.bookmarks.onCreated.addListener(() => {
scheduleReindex();
});
chrome.bookmarks.onChanged.addListener(() => {
scheduleReindex();
});
chrome.bookmarks.onMoved.addListener(() => {
scheduleReindex();
});
chrome.bookmarks.onRemoved.addListener(() => {
scheduleReindex();
});
chrome.bookmarks.onImportEnded.addListener(() => {
scheduleReindex(500);
});
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
(async () => {
if (message?.type === "getBookmarks") {
const store = await loadStore();
if (!store.bookmarks.length) {
await reindexBookmarks();
}
const refreshedStore = await loadStore();
sendResponse({ ok: true, bookmarks: refreshedStore.bookmarks });
return;
}
if (message?.type === "openBookmark") {
const bookmarkId = String(message.bookmarkId || "");
const requestedDisposition = String(message.disposition || "new-tab");
const disposition =
requestedDisposition === "current-tab" ||
requestedDisposition === "background-tab" ||
requestedDisposition === "new-tab"
? requestedDisposition
: "new-tab";
const result = await openBookmarkAndTrack(bookmarkId, disposition);
sendResponse(result);
return;
}
if (message?.type === "togglePin") {
const bookmarkId = String(message.bookmarkId || "");
if (!bookmarkId) {
sendResponse({ ok: false, message: "Missing bookmark ID." });
return;
}
const response = await togglePin(bookmarkId);
sendResponse(response);
return;
}
if (message?.type === "openTreeView") {
await chrome.tabs.create({ url: chrome.runtime.getURL("tree.html") });
sendResponse({ ok: true });
return;
}
if (message?.type === "openAnalytics") {
await chrome.tabs.create({ url: chrome.runtime.getURL("analytics.html") });
sendResponse({ ok: true });
return;
}
if (message?.type === "getTreeData") {
const response = await getTreeData();
sendResponse(response);
return;
}
if (message?.type === "deleteBookmarks") {
const response = await deleteBookmarks(Array.isArray(message.bookmarkIds) ? message.bookmarkIds : []);
sendResponse(response);
return;
}
if (message?.type === "getAnalyticsData") {
const response = await getAnalyticsData();
sendResponse(response);
return;
}
sendResponse({ ok: false, message: "Unknown message type." });
})().catch((error) => {
console.error("Message handling failed", error);
sendResponse({ ok: false, message: "Internal error." });
});
return true;
});