Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
224 lines (198 loc) · 7.06 KB
/
Copy pathbackground.js
File metadata and controls
224 lines (198 loc) · 7.06 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
// background.js - Click & Bookmark
let rebuildTimeout = null;
// Serializes rebuilds: every rebuild waits for the previous one to fully
// finish (including its create callbacks), so a removeAll can never
// interleave with another rebuild's in-flight creates.
let rebuildQueue = Promise.resolve();
// Build the menu on install or startup
chrome.runtime.onInstalled.addListener(() => {
debouncedRebuild();
});
chrome.runtime.onStartup.addListener(() => {
debouncedRebuild();
});
// Listen for changes in Chrome Bookmarks to keep the menu synced.
// The menu only lists folders, so page-bookmark saves/edits/moves are skipped
// to avoid a full context-menu rebuild on every bookmark action.
chrome.bookmarks.onCreated.addListener((id, node) => maybeRebuild(node));
chrome.bookmarks.onRemoved.addListener((id, removeInfo) => maybeRebuild(removeInfo && removeInfo.node));
chrome.bookmarks.onChanged.addListener((id) => resolveNode(id));
chrome.bookmarks.onMoved.addListener((id) => resolveNode(id));
function resolveNode(id) {
chrome.bookmarks.get(id, (nodes) => {
if (chrome.runtime.lastError) {
// Node is already gone; rebuild to be safe.
debouncedRebuild();
return;
}
maybeRebuild(nodes && nodes[0]);
});
}
function maybeRebuild(node) {
if (node && node.url) return; // a page bookmark, not a folder
debouncedRebuild();
}
// Listen for settings changes to automatically rebuild the menu
chrome.storage.onChanged.addListener((changes, areaName) => {
if (areaName === 'local') {
debouncedRebuild();
}
});
function debouncedRebuild() {
if (rebuildTimeout) clearTimeout(rebuildTimeout);
rebuildTimeout = setTimeout(() => {
rebuildTimeout = null;
rebuildQueue = rebuildQueue
.then(rebuildContextMenus)
.catch((err) => console.error("Menu rebuild failed:", err));
}, 100);
}
async function rebuildContextMenus() {
const [treeNodes, settings] = await Promise.all([
chrome.bookmarks.getTree(),
chrome.storage.local.get({ showSystemFolders: false, showNotifications: true })
]);
await chrome.contextMenus.removeAll();
await buildMenus(treeNodes, settings);
}
function createMenuItem(props) {
return new Promise((resolve) => {
chrome.contextMenus.create(props, () => {
const err = chrome.runtime.lastError;
if (err) {
// A duplicate means the item is already in the menu (a create from an
// earlier rebuild can land after our removeAll); the menu ends up
// correct either way, so only warn about other failures.
if (!err.message.includes("duplicate id")) {
console.warn("Context menu error:", err.message);
}
}
resolve();
});
});
}
async function buildMenus(treeNodes, settings) {
// Create main menu item
await createMenuItem({
id: "pagesaver-root",
title: "Save page in...",
contexts: ["page"]
});
const folderList = [];
// Traverse the tree to filter only folders, checking the settings for system roots
function extractFolders(nodes, depth = 0) {
nodes.forEach(node => {
if (!node.url && node.id !== "0") {
const isSystemRoot = node.id === "1" || node.id === "2" || node.id === "3";
if (!isSystemRoot || settings.showSystemFolders) {
folderList.push({
id: node.id,
title: node.title || "Unnamed folder",
depth: depth
});
}
}
if (node.children) {
// Depth tracks generations below the root regardless of whether system
// folders are displayed, so subfolders indent consistently in both modes.
let nextDepth = depth;
if (node.id !== "0") {
nextDepth = depth + 1;
}
extractFolders(node.children, nextDepth);
}
});
}
extractFolders(treeNodes);
// Filter out empty, unnamed, or duplicate folders
const seen = new Set();
const validFolders = folderList.filter((f) => {
if (f.title.trim() === "" || seen.has(f.id)) return false;
seen.add(f.id);
return true;
});
if (validFolders.length === 0) {
// CASE: No folders have been created by the user yet
// Option 1: Save directly to the root folder (Bookmarks Bar / id '1')
await createMenuItem({
id: "save-to-bm-1",
parentId: "pagesaver-root",
title: "Main Folder (Bookmarks Bar)",
contexts: ["page"]
});
// Separator line between save options and actions
await createMenuItem({
id: "separator-1",
parentId: "pagesaver-root",
type: "separator",
contexts: ["page"]
});
// Disabled informational label
await createMenuItem({
id: "info-label",
parentId: "pagesaver-root",
title: "Open bookmarks sidebar/manager to add folders",
enabled: false,
contexts: ["page"]
});
// Option 2: Button to open the Bookmarks Manager page
await createMenuItem({
id: "open-bookmarks-manager",
parentId: "pagesaver-root",
title: "Open Bookmarks Manager (Ctrl+Shift+O)",
contexts: ["page"]
});
} else {
// CASE: Folders are present
// Creates are awaited one by one: each callback fires after Chrome has
// applied the item, so a later rebuild's removeAll can never race ahead
// of an unapplied create.
for (const folder of validFolders) {
const prefix = "— ".repeat(Math.max(0, folder.depth - 1));
await createMenuItem({
id: `save-to-bm-${folder.id}`,
parentId: "pagesaver-root",
title: prefix + folder.title,
contexts: ["page"]
});
}
}
}
// Listener for clicks on menu items
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (!tab) return;
// Action 1: Open Chrome Bookmarks manager in a new tab
if (info.menuItemId === "open-bookmarks-manager") {
chrome.tabs.create({ url: "chrome://bookmarks/" });
return;
}
// Action 2: Save bookmark in the selected folder
if (tab.url && info.menuItemId.startsWith("save-to-bm-")) {
const targetFolderId = info.menuItemId.replace("save-to-bm-", "");
chrome.bookmarks.create({
parentId: targetFolderId,
title: tab.title || "Untitled page",
url: tab.url
}, (newBookmark) => {
if (chrome.runtime.lastError) {
console.error("Error saving bookmark:", chrome.runtime.lastError.message);
return;
}
// Check if notifications are enabled before showing alert
chrome.storage.local.get({ showNotifications: true }, (items) => {
if (items.showNotifications) {
chrome.notifications.create({
type: "basic",
iconUrl: "icons/icon-128.png",
title: "Saved Bookmark",
message: `Saved page: "${newBookmark.title || tab.title}"`
}, () => {
if (chrome.runtime.lastError) {
console.warn("Notification error:", chrome.runtime.lastError.message);
}
});
}
});
});
}
});