Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
168 lines (145 loc) · 5.06 KB
/
Copy pathbackground.js
File metadata and controls
168 lines (145 loc) · 5.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
// Background service worker for Bookmark Alphabetizer
let sortingFolders = new Set(); // Track folders currently being sorted
let pendingSorts = new Map(); // Map of parentId to timeout ID
/**
* Sorts bookmarks alphabetically within a folder
* @param {string} parentId - The ID of the folder to sort
*/
async function sortBookmarks(parentId) {
// Prevent concurrent sorting of the same folder
if (sortingFolders.has(parentId)) {
console.log(`Skipping sort for ${parentId} - already in progress`);
return;
}
sortingFolders.add(parentId);
try {
const children = await chrome.bookmarks.getChildren(parentId);
if (!children || children.length <= 1) {
return;
}
// Separate folders and bookmarks
const folders = children.filter(child => child.url === undefined);
const bookmarks = children.filter(child => child.url !== undefined);
// Sort both arrays alphabetically by title (case-insensitive)
folders.sort((a, b) => a.title.toLowerCase().localeCompare(b.title.toLowerCase()));
bookmarks.sort((a, b) => a.title.toLowerCase().localeCompare(b.title.toLowerCase()));
// Combine: folders first, then bookmarks
const sortedChildren = [...folders, ...bookmarks];
// Check if reordering is needed
let needsReordering = false;
for (let i = 0; i < sortedChildren.length; i++) {
if (sortedChildren[i].id !== children[i].id) {
needsReordering = true;
break;
}
}
// Reorder bookmarks sequentially if needed (prevents race conditions)
if (needsReordering) {
for (let i = 0; i < sortedChildren.length; i++) {
const child = sortedChildren[i];
// Only move if the position actually changed
if (children[i]?.id !== child.id) {
try {
await chrome.bookmarks.move(child.id, {
parentId: parentId,
index: i
});
} catch (error) {
console.error(`Failed to move bookmark ${child.id}:`, error);
// Continue with other bookmarks even if one fails
}
}
}
}
// Recursively sort folders sequentially
for (const folder of folders) {
await sortBookmarks(folder.id);
}
} catch (error) {
console.error(`Error sorting bookmarks in folder ${parentId}:`, error);
} finally {
// Always clean up tracking state
sortingFolders.delete(parentId);
}
}
/**
* Sorts all bookmarks in the entire bookmark tree
*/
async function sortAllBookmarks() {
try {
const bookmarkTreeNodes = await chrome.bookmarks.getTree();
if (bookmarkTreeNodes && bookmarkTreeNodes.length > 0) {
const rootNode = bookmarkTreeNodes[0];
if (rootNode.children) {
for (const child of rootNode.children) {
await sortBookmarks(child.id);
}
}
}
console.log('All bookmarks sorted successfully');
} catch (error) {
console.error('Error sorting all bookmarks:', error);
}
}
/**
* Debounce function to prevent too many sorts
* @param {string} parentId - The folder ID to sort
* @param {number} delay - Delay in milliseconds before sorting
*/
function debouncedSort(parentId, delay = 800) {
// Clear any existing timeout for this folder
if (pendingSorts.has(parentId)) {
clearTimeout(pendingSorts.get(parentId));
}
// Schedule new sort
const timeoutId = setTimeout(async () => {
pendingSorts.delete(parentId);
await sortBookmarks(parentId);
}, delay);
pendingSorts.set(parentId, timeoutId);
}
// Listen for bookmark creation
chrome.bookmarks.onCreated.addListener(function(id, bookmark) {
if (bookmark.parentId && !sortingFolders.has(bookmark.parentId)) {
debouncedSort(bookmark.parentId);
}
});
// Listen for bookmark moves
chrome.bookmarks.onMoved.addListener(function(id, moveInfo) {
// Don't re-sort if we're currently sorting these folders
if (!sortingFolders.has(moveInfo.oldParentId) && moveInfo.oldParentId) {
debouncedSort(moveInfo.oldParentId);
}
if (!sortingFolders.has(moveInfo.parentId) &&
moveInfo.parentId &&
moveInfo.parentId !== moveInfo.oldParentId) {
debouncedSort(moveInfo.parentId);
}
});
// Listen for bookmark title/URL changes
chrome.bookmarks.onChanged.addListener(async function(id, changeInfo) {
try {
const bookmarks = await chrome.bookmarks.get(id);
if (bookmarks && bookmarks[0] && bookmarks[0].parentId) {
const parentId = bookmarks[0].parentId;
if (!sortingFolders.has(parentId)) {
debouncedSort(parentId);
}
}
} catch (error) {
console.error('Error handling bookmark change:', error);
}
});
// Listen for bookmark removal
chrome.bookmarks.onRemoved.addListener(function(id, removeInfo) {
if (removeInfo.parentId && !sortingFolders.has(removeInfo.parentId)) {
debouncedSort(removeInfo.parentId);
}
});
// Sort all bookmarks when extension is installed or updated
chrome.runtime.onInstalled.addListener(async function() {
console.log('Bookmark Alphabetizer installed. Sorting all bookmarks...');
await sortAllBookmarks();
});
// Sort all bookmarks when the service worker starts
sortAllBookmarks();