-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsharedUtils.ts
326 lines (303 loc) · 8.64 KB
/
sharedUtils.ts
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
import {
SessionStorageKey,
TabGroupType,
AreaName,
tabGroupTypes,
sessionStorageKeys,
MessageType,
stubPagePathName,
protocolsEligibleForEncoding,
LocalStorageKey,
localStorageKeys,
bookmarkerDetails,
CurrentlyNavigatedTabId,
newTabNavigatedTabId,
navigationBoxPathName,
AntecedentTabInfo,
} from "./constants";
export async function getStorageData<T = unknown>(
key: SessionStorageKey | LocalStorageKey
) {
const areaName = key.split("-")[0] as AreaName;
return (await chrome.storage[areaName].get(key))[key] as T | undefined;
}
export async function setStorageData<T = unknown>(
key: SessionStorageKey | LocalStorageKey,
value: T
) {
const areaName = key.split("-")[0] as AreaName;
chrome.storage[areaName].set({ [key]: value });
}
export async function removeStorageData(
key: SessionStorageKey | LocalStorageKey
) {
const areaName = key.split("-")[0] as AreaName;
chrome.storage[areaName].remove(key);
}
export async function subscribeToStorageData<T = unknown>(
key: SessionStorageKey | LocalStorageKey,
fn: (changes: { newValue: T | undefined; oldValue: T | undefined }) => void
) {
chrome.storage.onChanged.addListener((changes, areaName) => {
const keyAreaName = key.split("-")[0] as AreaName;
if (areaName === keyAreaName) {
const newStorageData = changes[key]?.newValue;
const oldStorageData = changes[key]?.oldValue;
if (newStorageData !== undefined || oldStorageData !== undefined) {
fn({ newValue: newStorageData, oldValue: oldStorageData });
}
}
});
}
export type TabGroupTreeData = (chrome.tabGroups.TabGroup & {
type?: TabGroupType;
icon?: string;
tabs: chrome.tabs.Tab[];
})[];
export async function reinitializePinnedTabs() {
// @maybe
await setStorageData(sessionStorageKeys.sessionLoading, true);
const oldPinnedTabs = await chrome.tabs.query({ pinned: true });
for (const tab of oldPinnedTabs) {
try {
await setStorageData(sessionStorageKeys.currentlyRemovedTabId, tab.id);
await chrome.tabs.remove(tab.id!);
} catch (error) {
console.error(error);
}
}
const pinnedTabGroupBookmarkNodeId = await getStorageData<
chrome.bookmarks.BookmarkTreeNode["id"]
>(localStorageKeys.pinnedTabGroupBookmarkNodeId);
if (pinnedTabGroupBookmarkNodeId) {
const pinnedTabGroupBookmarkNodeChildren =
await chrome.bookmarks.getChildren(pinnedTabGroupBookmarkNodeId);
for (const tabData of pinnedTabGroupBookmarkNodeChildren) {
if (
tabData.title === bookmarkerDetails.title &&
tabData.url === bookmarkerDetails.url
) {
continue;
}
const url = encodeTabDataAsUrl({
title: tabData.title,
url: tabData.url || "",
});
await chrome.tabs.create({
url,
pinned: true,
active: false,
});
}
} else {
// @error
}
await setStorageData(sessionStorageKeys.sessionLoading, false);
}
export async function sendMessage(
message: { type: MessageType; data?: any },
fn?: (response: any) => void
) {
chrome.runtime.sendMessage(
{
type: message.type,
data: message.data,
},
// @ts-ignore. looks like `chrome.runtime.sendMessage` was typed incorrectly
fn
);
}
export function subscribeToMessage(
messageType: MessageType,
fn: (
data: any,
sender: chrome.runtime.MessageSender,
sendResponse: (response: any) => void
) => void
) {
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message?.type && message.type === messageType) {
fn(message.data, sender, sendResponse);
}
return undefined;
// not being used currently because of errors. only use if you plan to send a response
// TODO: revise this (if necessary)
// return true;
});
}
export async function saveCurrentSessionDataIntoBookmarkNode(
bookmarkNodeId: chrome.bookmarks.BookmarkTreeNode["id"]
) {
const tabGroupTreeData =
(await getStorageData<TabGroupTreeData>(
sessionStorageKeys.tabGroupTreeData
)) ?? [];
for (const tabGroup of tabGroupTreeData) {
if (tabGroup.type === tabGroupTypes.pinned) {
continue;
}
const tabGroupDataId = (
await chrome.bookmarks.create({
parentId: bookmarkNodeId,
title: tabGroup.icon
? tabGroup.title
: `${tabGroup.color}-${tabGroup.title}`,
})
).id;
for (const tab of tabGroup.tabs) {
await chrome.bookmarks.create({
parentId: tabGroupDataId,
title: tab.title,
url: tab.url,
});
}
}
}
export function getFaviconUrl(pageUrl: string | null | undefined) {
const url = new URL(chrome.runtime.getURL("/_favicon/"));
url.searchParams.set("pageUrl", pageUrl ?? "null");
url.searchParams.set("size", "32");
return url.toString();
}
export function encodeTabDataAsUrl(options: {
title: string;
url: string;
active?: boolean;
}) {
const urlFromUrl = new URL(options.url);
if (protocolsEligibleForEncoding.includes(urlFromUrl.protocol)) {
return `${stubPagePathName}?title=${encodeURIComponent(
options.title ?? ""
)}&url=${encodeURIComponent(options.url ?? "")}${
options.active ? "&active=true" : ""
}`;
} else {
return options.url;
}
}
export function debounce<T>(callback: (args?: T) => void, timeout: number) {
let timeoutId: number | undefined | NodeJS.Timeout;
return (args?: T, newTimeout?: number) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
callback(args);
}, newTimeout ?? timeout);
};
}
export function executeAndBounceOff<T>(
callback: (args?: T) => void,
timeout: number
) {
let timeoutId: number | undefined | NodeJS.Timeout;
let bounceOff: boolean = false;
return (args?: T, newTimeout?: number) => {
if (!bounceOff) {
callback(args);
bounceOff = true;
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
bounceOff = false;
}, newTimeout ?? timeout);
}
};
}
export async function insertBookmarker(
bookmarkNodeId: chrome.bookmarks.BookmarkTreeNode["id"]
) {
// @maybe the error shouldn't be handled here
try {
await chrome.bookmarks.create({
title: bookmarkerDetails.title,
url: bookmarkerDetails.url,
parentId: bookmarkNodeId,
index: 0,
});
} catch (error) {
console.error(error);
}
}
export async function migrateAndDedupe(
bookmarkNodes: Array<chrome.bookmarks.BookmarkTreeNode>,
masterBookmarkNodeId: chrome.bookmarks.BookmarkTreeNode["id"]
) {
// @maybe the error shouldn't be handled here
try {
for (const bookmarkNode of bookmarkNodes) {
if (bookmarkNode.id !== masterBookmarkNodeId) {
const bookmarkNodeChildren = await chrome.bookmarks.getChildren(
bookmarkNode.id
);
for (const bookmarkNode of bookmarkNodeChildren) {
await chrome.bookmarks.move(bookmarkNode.id, {
parentId: masterBookmarkNodeId,
});
}
await chrome.bookmarks.remove(bookmarkNode.id);
}
}
} catch (error) {
console.error(error);
}
}
export function wait(timeout?: number) {
return new Promise((resolve) => {
setTimeout(resolve, timeout);
});
}
export async function withError<T>(
promise: Promise<T>
): Promise<[undefined, T] | [Error]> {
return promise
.then((data) => {
return [undefined, data] as [undefined, T];
})
.catch((error) => {
return [error];
});
}
export async function openNavigationBox<
T extends {
active?: boolean;
pinned?: boolean;
newWindow?: boolean;
navigatedTabId?: chrome.tabs.Tab["id"];
precedentTabId: chrome.tabs.Tab["id"];
group?: boolean;
}
>(
options: T
): Promise<
T["newWindow"] extends true
? chrome.windows.Window | undefined
: chrome.tabs.Tab | undefined
> {
const [error] = await withError(
setStorageData<AntecedentTabInfo>(sessionStorageKeys.antecedentTabInfo, {
precedentTabId: options.precedentTabId,
})
);
if (error) {
// @handle
}
await setStorageData<CurrentlyNavigatedTabId>(
sessionStorageKeys.currentlyNavigatedTabId,
options?.navigatedTabId ?? newTabNavigatedTabId
);
if (options?.newWindow) {
return (await chrome.windows.create({
url: navigationBoxPathName,
focused: true,
type: "normal",
})) as T["newWindow"] extends true
? chrome.windows.Window | undefined
: chrome.tabs.Tab | undefined;
} else {
return (await chrome.tabs.create({
url: `${navigationBoxPathName}${options?.group ? "?group=true" : ""}`,
active: options?.active,
pinned: options?.pinned,
})) as T["newWindow"] extends true
? chrome.windows.Window | undefined
: chrome.tabs.Tab | undefined;
}
}