-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathsyncmark.js
More file actions
413 lines (336 loc) · 12 KB
/
syncmark.js
File metadata and controls
413 lines (336 loc) · 12 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
//
// syncmark.js
// To use this, open up chrome-extension://pcdogalliibjgamnojnpbmbabghfijak/sidebar.html
//
// Utility functions to handle defaults
// chrome.runtime.onInstalled.addListener(setup);
// chrome.runtime.onStartup.addListener(setup);
// Returns the string value of the variable name (black magic...).
const v = (nameObject) => { for (let varName in nameObject) { return varName; } }
function getDefault(key, fallback) {
let value = localStorage.getItem(key);
if (value == undefined) return fallback;
return JSON.parse(value);
}
function setDefault(key, value) {
localStorage.setItem(key, JSON.stringify(value));
}
// Global Variables and startup
const BOOKMARK_FOLDER_TITLE = "Tab Groups";
const BOOMARK_ROOT_PARENT = '1';
const USE_BOOKMARKS_BAR = false;
const BOOKMARK_ROOT_KEY = 'bookmarkRoot'
// Maps tabGroup.id to bookmarkFolder.id.
// Created at startup, used to track whether group changes.
let existingGroupsToFolders = {}
// Created at startup, tracks which tabs are in which group.
let existingTabToGroup = {}
// Global monitoring state -- if state
let shouldMonitorTabChanges = true;
let currentBookmarkRootId = getDefault('bookmarkRoot');
let ignoreNextTabMove = false;
let allFolders = [];
var Groups = function(vnode) {
return {
view: function(vnode) {
return m('div.group', allFolders.map(f => {
if (f.url) return null;
return m('div.folder', {onclick:restoreGroupWithBookmark.bind(null, f.id)}, f.title);
}));
}
}
}
let tabsToDiscard = {}
async function restoreGroupWithBookmark(bookmarkId) {
let folder = (await chrome.bookmarks.get(bookmarkId)).pop()
let info = infoForFolderTitle(folder.title)
let color = info.color;
let title = info.title;
console.log('restoreGroupWithBookmark', info);
let existing = (await chrome.tabGroups.query({title: title, color:color})).pop();
if (existing) {
let tabs = await tabsForGroup(existing);
chrome.tabs.update(tabs[0].id, {active:true})
return;
}
let children = await chrome.bookmarks.getChildren(bookmarkId)
let promises = children.map((bookmark, i) => {
// Ignore metadata bookmarks
//if (bookmark.url.startsWith("chrome-extension://")) return;
let promise = chrome.tabs.create({url: bookmark.url, selected:false, active:false})
// Discard tabs that are not focused
if (i > 0) promise = promise.then(t => { tabsToDiscard[t.id] = true; return t;})
return promise;
})
shouldMonitorTabChanges = false;
Promise.all(promises).then (tabs => {
return chrome.tabs.group({tabIds:tabs.map(t => t.id), createProperties:{windowId: tabs[0].windowId}})
.then(async (gid) => {
await chrome.tabs.update(tabs[0].id, { active: true });
return chrome.tabGroups.update(gid, {title:title, color:color})
})
.then(() => {
shouldMonitorTabChanges = true;
})
})
}
//////////////////////////////////////////////////////////////////////
// Tab state saving.
async function initializeTabGroupMapping() {
const tabs = await chrome.tabs.query({});
for (const tab of tabs) {
if (tab.groupId != -1) {
existingTabToGroup[tab.id] = tab.groupId
}
}
}
// Syncs all groups to the bookmark folders.
async function updateAllFoldersAndGroups() {
let rootId = await getBookmarkRoot();
let groups = await chrome.tabGroups.query({});
let folders = await chrome.bookmarks.getChildren(rootId);
console.log('updateAllFoldersAndGroups', {rootId, groups, folders})
allFolders = folders;
for (let group of groups) {
let title = folderTitleForGroup(group);
let folder = folders.find(f => f.title == title);
const tabs = await tabsForGroup(group);
if (!folder) {
console.log('Creating folder', title);
folder = await chrome.bookmarks.create({parentId: rootId, title: title, index: 0});
}
updateFolderWithTabs(folder, group, tabs);
existingGroupsToFolders[group.id] = folder.id;
}
m.redraw();
}
async function updateFolderWithTabs(folder, group, tabs) {
let children = await chrome.bookmarks.getChildren(folder.id)
for (const [index, tab] of tabs.entries()) {
let child = children.find(c => c.url == tab.url);
if (!child) {
chrome.bookmarks.create({parentId: folder.id, title: tab.title, url: tab.url, index});
continue;
} else if (child.index != index) {
chrome.bookmarks.move(child.id, {index})
}
children.splice(children.indexOf(child), 1);
}
if (children.length) {
console.log("Removing orphans:", children);
children.forEach(child => chrome.bookmarks.remove(child.id));
}
}
async function tabsForGroup(group) { // There is a bug in tab.query for groupIds, so...
let w = await chrome.windows.get(group.windowId, {populate:true});
return w.tabs.filter(t => t.groupId == group.id)
}
// Returns true if the bookmark root exists, false if it doesn't.
async function doesCurrentBookmarkRootExist() {
if (!currentBookmarkRootId) {
return false;
}
return chrome.bookmarks.get(currentBookmarkRootId)
.then(() => { return true })
.catch(() => { return false })
}
// Returns id of the bookmark folder with the name 'Tab Groups'. Returns 0 if it isn't found.
async function getTabGroupsBookmark() {
let results = await chrome.bookmarks.search({title:BOOKMARK_FOLDER_TITLE})
if (results && results.length > 0) {
return results[0].id;
}
return 0;
}
// Returns the id for the bookmark root object.
//
// It will guarantee the bookmark root exists, even if
// the bookmark root is deleted by the user.
async function getBookmarkRoot() {
if (USE_BOOKMARKS_BAR) {
return BOOMARK_ROOT_PARENT;
}
// Return the current bookmark id if it still exists.
if (await doesCurrentBookmarkRootExist()) {
return currentBookmarkRootId;
}
// Check if the bookmark root exists but was moved somewher else
const existingTabGroupId = await getTabGroupsBookmark();
if (existingTabGroupId) {
setDefault(BOOKMARK_ROOT_KEY, existingTabGroupId)
currentBookmarkRootId = existingTabGroupId;
return currentBookmarkRootId;
}
// Nothing exists, create a new one at the root node.
const newBookmarkRoot = await chrome.bookmarks.create({
parentId: BOOMARK_ROOT_PARENT,
title: BOOKMARK_FOLDER_TITLE,
index: 0
});
setDefault(BOOKMARK_ROOT_KEY, newBookmarkRoot.id);
currentBookmarkRootId = existingTabGroupId;
return currentBookmarkRootId;
}
const COLOR_EMOJIS = { grey: "⚪️", blue: "🔵", red: "🔴", yellow: "🟠", green: "🟢", pink: "🌸", purple: "🟣", cyan: "🌐" }
const EMOJI_COLORS = Object.assign({}, ...Object.entries(COLOR_EMOJIS).map(([a,b]) => ({[b]: a})))
function folderTitleForGroup(group) {
return `${COLOR_EMOJIS[group.color]} ${group.title || group.color}`;
}
function infoForFolderTitle(string) {
let match = string.match(/(?<color>\S+) (?<title>.*)/);
let info = match.groups;
info.color = EMOJI_COLORS[info.color];
return info
}
// Returns the bookmark folder for a tab group.
async function folderForGroup(group) {
let rootId = await getBookmarkRoot();
let children = await chrome.bookmarks.getChildren(rootId);
let title = folderTitleForGroup(group)
let folder = children.find(c => c.title == title);
if (!folder) {
console.log('Creating group', title, group);
folder = await chrome.bookmarks.create({
parentId: rootId,
title: title,
index:0});
existingGroupsToFolders[group.id] = folder.id;
}
return folder;
}
//////////////////////////////////////////////////////////////////////
// Tab and Tab Group event handling
// Called when properties of the group changes like the color or name.
async function groupUpdated(group) {
if (!shouldMonitorTabChanges) {
return;
}
console.log('groupUpdated', group);
const folderId = existingGroupsToFolders[group.id];
let title = folderTitleForGroup(group);
if (folderId) {
// Sync group changes to the folder if it exsts.
chrome.bookmarks.update(folderId, {title});
} else {
// Create the folder if it doesn't exist.
await folderForGroup(group)
}
}
function tabCreated(tab) {
if (!shouldMonitorTabChanges) {
return;
}
console.log("tabCreated", tab)
}
function tabRemoved(tab) {
if (!shouldMonitorTabChanges) {
return;
}
console.log("tabRemoved", tab);
}
async function tabMoved(id, change) {
if (!shouldMonitorTabChanges) {
return;
}
console.log('tabMoved', {id, change})
let w = await chrome.windows.get(change.windowId, {populate:true});
let tab = w.tabs.find(t => t.id == id);
if (!tab || tab.groupId == -1) {
return;
}
let groupId = tab.groupId;
let group = await chrome.tabGroups.get(groupId);
let tabs = await tabsForGroup(group);
let folder = await folderForGroup(group);
updateFolderWithTabs(folder, group, tabs);
}
async function tabUpdated(id, change, tab) {
if (!shouldMonitorTabChanges) {
return;
}
console.log('tabUpdated', {id, change, tab})
if (tabsToDiscard[id] == true && change.title) {
chrome.tabs.discard(id);
delete tabsToDiscard[id];
}
// Tab moved groups.
if (change && typeof change.groupId !== 'undefined') {
tabDidChangeGroups(id, change, tab);
} else if (change && (change.status || change.title)) {
// Ignore loading status changes.
} else if (tab.groupId > -1) {
// if tab.groupId == -1, that means it's not in a group.
tabDidChangeProperties(id, change, tab);
}
}
async function tabDidChangeGroups(id, change, tab) {
if (change.groupId == -1 && tab.discared) {
// Tab is removed from group and deleted at the same time.
// This probably means the group is being removed.
} else if (change.groupId == -1) {
const previousGroupId = existingTabToGroup[tab.id];
if (typeof previousGroupId !== 'undefined' && previousGroupId != -1) {
chrome.tabGroups.get(previousGroupId).then(async group => {
const tabs = await tabsForGroup(group);
const folder = await folderForGroup(group);
updateFolderWithTabs(folder, group, tabs)
delete existingTabToGroup[id]
})
.catch(() => {
// Group doesn't exist any more.
delete existingTabToGroup[id]
})
}
} else {
// Tab moved groups, also move it in the folders.
// TODO: Need to find the previous bookmark group id to remove it.
let group = await chrome.tabGroups.get(tab.groupId);
let tabs = await tabsForGroup(group);
let folder = await folderForGroup(group);
updateFolderWithTabs(folder, group, tabs)
existingTabToGroup[id] = tab.groupId;
}
}
// Handle changes of the tab that are not moving groups.
async function tabDidChangeProperties(id, change, tab) {
let group = await chrome.tabGroups.get(tab.groupId);
let tabs = await tabsForGroup(group);
let folder = await folderForGroup(group);
let index = tabs.findIndex(t => t.id == id);
let children = await chrome.bookmarks.getChildren(folder.id);
let bookmark = children[index];
chrome.bookmarks.update(bookmark.id, {title: tab.title, url: tab.url});
}
//
// Initializer
//
async function onStartup() {
console.log('Startup');
await updateAllFoldersAndGroups();
await initializeTabGroupMapping();
m.mount(document.body, Groups)
}
onStartup();
// Tabstrip Event handling
chrome.tabGroups.onUpdated.addListener(groupUpdated);
chrome.tabs.onCreated.addListener(tabCreated);
chrome.tabs.onMoved.addListener(tabMoved);
chrome.tabs.onUpdated.addListener(tabUpdated);
chrome.tabs.onRemoved.addListener(tabRemoved);
// chrome.tabs.onAttached.addListener()
// chrome.tabs.onDetached.addListener()
// Bookmark Event handling
// TBD, needs to avoid cycles
chrome.bookmarks.onChildrenReordered.addListener(bookmarkDidMove)
async function bookmarkDidMove(id,moveInfo) {
console.debug('bookmarkDidMove', {id}, moveInfo)
// chrome.tabs.query({}, function(results) {
// var tab = results[moveInfo.oldIndex]
// chrome.tabs.move(tab.id, {windowId:undefined, index:moveInfo.index}, function(){
// })
// });
}
chrome.bookmarks.onChanged.addListener(bookmarkDidChange)
async function bookmarkDidChange(id, changeInfo) {
console.debug('bookmarkDidChange', {id}, changeInfo)
}