-
Notifications
You must be signed in to change notification settings - Fork 1
/
bookmarks.js
97 lines (79 loc) · 2.34 KB
/
bookmarks.js
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
import con from "/console.js";
const {bookmarks} = browser;
export async function getAll() {
const [node] = await bookmarks.getTree();
return node;
}
export async function getNode(id) {
const [node] = await bookmarks.get(id);
if (!node.children) node.children = await bookmarks.getChildren(id);
return node;
}
export async function findAncestor(id, predicate) {
let curId = id;
while (curId) {
const [node] = await bookmarks.get(curId);
if (predicate(node)) return node;
({parentId: curId} = node);
}
return null;
}
export async function exists(id) {
try {
const [_node] = await bookmarks.get(id);
return true;
} catch (_e) {
return false;
}
}
export function move(id, destination) {
return bookmarks.move(id, destination);
}
export const onChanged = new Set();
function emitChanged(id) {
for (const func of onChanged) func(id);
}
const bookmarksListeners = new Map([
[
bookmarks.onCreated,
(_id, node) => {
con.log("Node created:", node);
emitChanged(node.parentId);
},
],
[
bookmarks.onRemoved,
(_id, node) => {
con.log("Node removed:", node);
emitChanged(node.parentId);
},
],
[
bookmarks.onChanged,
async (id, _changeInfo) => {
const [node] = await bookmarks.get(id);
if (!node) return;
con.log("Node changed:", node);
emitChanged(node.parentId);
},
],
[
bookmarks.onMoved,
(id, info) => {
// FIXME: This gets fired when we move bookmarks.
// I don't think it's guaranteed that we see the event before we "exit" the node,
// so reacting to moves within a folder may lead to infinite looping.
if (info.parentId === info.oldParentId) return;
con.log("Node moved:", id);
emitChanged(info.parentId);
},
],
]);
let tracking = false;
export function setTracking(enabled) {
if (tracking === enabled) return;
if (enabled) for (const [ev, l] of bookmarksListeners.entries()) ev.addListener(l);
else for (const [ev, l] of bookmarksListeners.entries()) ev.removeListener(l);
con.log("Bookmarks tracking %s", enabled ? "enabled" : "disabled");
tracking = enabled;
}