-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
background.js
235 lines (190 loc) · 5.65 KB
/
background.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
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
const config = { enabled: true, disabledTabIds: new Set() };
const storage = {
get: async (key) => (await chrome.storage.sync.get([key]))[key],
};
const COMMANDS = {
"toggle-all-tabs": toggleAllTabs,
"toggle-current-tab": toggleCurrentTab,
};
const CONTEXT_MENU = {
"chrome-show-tab-numbers-toggle-all-tabs": {
title: "Toggle tab numbering for all tabs",
callback: toggleAllTabs,
},
"chrome-show-tab-numbers-toggle-current-tab": {
title: "Toggle tab numbering for current tab",
callback: toggleCurrentTab,
},
};
createContextMenu();
chrome.storage.onChanged.addListener(requestToUpdateAll);
chrome.tabGroups.onCreated.addListener(requestToUpdateAll);
chrome.tabGroups.onMoved.addListener(requestToUpdateAll);
chrome.tabGroups.onRemoved.addListener(requestToUpdateAll);
chrome.tabGroups.onUpdated.addListener(requestToUpdateAll);
chrome.tabs.onActivated.addListener(requestToUpdateAll);
chrome.tabs.onCreated.addListener(requestToUpdateAll);
chrome.tabs.onMoved.addListener(requestToUpdateAll);
chrome.tabs.onRemoved.addListener(requestToUpdateAll);
chrome.tabs.onUpdated.addListener(requestToUpdateAll);
chrome.tabs.onRemoved.addListener(onTabRemoved);
chrome.commands.onCommand.addListener(onCommand);
chrome.contextMenus.onClicked.addListener(onMenuClicked);
const VALID_PROTOCOLS = new Set(["https:", "http:"]);
const INVALID_HOSTNAMES = new Set(["chrome.google.com"]);
let timer = -1;
function requestToUpdateAll() {
if (!config.enabled) {
return;
}
clearTimeout(timer);
timer = setTimeout(updateAll, 300);
}
async function updateAll() {
const tabs = await chrome.tabs.query({ currentWindow: true });
const collapsedTabGroups = await findCollapsedTabGroups();
const collapsedTabGroupIds = new Set(
collapsedTabGroups.map((tabGroup) => tabGroup.id),
);
tabs.sort((tab1, tab2) => tab1.index - tab2.index);
const useRelativeNumber = await storage.get("useRelativeNumber");
if (useRelativeNumber) {
await updateRelativeNumbers(tabs, { collapsedTabGroupIds });
} else {
updateAbsoluteNumbers(tabs, { collapsedTabGroupIds });
}
}
async function findCollapsedTabGroups() {
try {
return await chrome.tabGroups.query({
windowId: chrome.windows.WINDOW_ID_CURRENT,
collapsed: true,
});
} catch (error) {
if (error.message.includes("Grouping is not supported by tabs")) {
return [];
}
}
}
async function updateRelativeNumbers(tabs, { collapsedTabGroupIds }) {
let relativeNumber = 0;
for (const tab of tabs) {
if (tab.active) {
break;
} else {
if (!collapsedTabGroupIds.has(tab.groupId)) {
relativeNumber--;
}
}
}
const useRelativeNumberSign = await storage.get("useRelativeNumberSign");
let absoluteNumber = 1;
for (const tab of tabs) {
if (collapsedTabGroupIds.has(tab.groupId)) {
continue;
}
if (isValidUrl(tab.url)) {
if (tab.active) {
requestToUpdateOne({ tab, number: absoluteNumber });
} else {
const number = useRelativeNumberSign
? `${relativeNumber < 0 ? "" : "+"}${relativeNumber}`
: Math.abs(relativeNumber);
requestToUpdateOne({ tab, number });
}
}
absoluteNumber++;
relativeNumber++;
}
}
function updateAbsoluteNumbers(tabs, { collapsedTabGroupIds }) {
let number = 1;
for (const tab of tabs) {
if (collapsedTabGroupIds.has(tab.groupId)) {
continue;
}
if (isValidUrl(tab.url)) {
requestToUpdateOne({ tab, number });
}
number++;
}
}
function isValidUrl(urlString) {
if (urlString === "") {
return false;
}
const url = new URL(urlString);
return (
VALID_PROTOCOLS.has(url.protocol) && !INVALID_HOSTNAMES.has(url.hostname)
);
}
function requestToUpdateOne({ tab, number }) {
const isEnabled = config.enabled && !config.disabledTabIds.has(tab.id);
const tabName = tab.title;
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: updateOne,
args: [{ isEnabled, number, tabName }],
});
}
function updateOne({ isEnabled, number, tabName }) {
const cache = document.showTabNumbers ?? {};
const isCacheAvailable =
isEnabled === cache.enabled &&
number === cache.number &&
tabName === cache.numberedTitle;
if (isCacheAvailable) {
return;
}
const NUMBERED_PATTERN = /^[-+]?\d+\. ?/;
const NOTIFICATION_COUNT_PATTERN = /^(\(\d+\)) [-+]?\d+\. (?:\(\d+\) )?/;
const unnumberedTitle = tabName
.replace(NUMBERED_PATTERN, "")
.replace(NOTIFICATION_COUNT_PATTERN, "$1 ");
cache.enabled = isEnabled;
cache.number = number;
cache.numberedTitle = (
cache.enabled ? `${number}. ${unnumberedTitle}` : unnumberedTitle
).trim();
document.title = cache.numberedTitle;
document.showTabNumbers = cache;
}
function toggleAllTabs() {
config.enabled = !config.enabled;
updateAll();
}
async function toggleCurrentTab() {
const [currentTab] = await chrome.tabs.query({
active: true,
lastFocusedWindow: true,
});
const isDisabled = config.disabledTabIds.has(currentTab.id);
if (isDisabled) {
config.disabledTabIds.delete(currentTab.id);
} else {
config.disabledTabIds.add(currentTab.id);
}
updateAll();
}
function onTabRemoved(tabId) {
const isDisabled = config.disabledTabIds.has(tabId);
if (isDisabled) {
config.disabledTabIds.delete(tabId);
}
}
function onCommand(command) {
COMMANDS[command]();
}
function createContextMenu() {
chrome.contextMenus.removeAll();
for (const menuItemId in CONTEXT_MENU) {
chrome.contextMenus.create({
contexts: ["action"],
id: menuItemId,
title: CONTEXT_MENU[menuItemId].title,
});
}
}
function onMenuClicked(info) {
CONTEXT_MENU[info.menuItemId].callback();
}