-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.js
More file actions
163 lines (139 loc) · 5.12 KB
/
Copy pathworker.js
File metadata and controls
163 lines (139 loc) · 5.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
const OFF = 'Code Copy (inactive — click to activate)';
const ON = 'Code Copy (active — click to deactivate)';
const TAB_ACTIVE = 'tabActive';
const INJECTED = 'injected';
const LOCAL = /^https?:\/\/(localhost|127\.0\.0\.1|0\.0\.0\.0)(:\d+)?(\/|$)/;
const BLOCKED = {
'chromewebstore.google.com': () => true,
'chrome.google.com': ({ pathname }) => pathname.startsWith('/webstore'),
};
const SIZES = [16, 32, 48, 128];
const iconCache = { on: null, off: null };
const injectable = (url) => {
try {
const u = new URL(url);
if (!['http:', 'https:'].includes(u.protocol) || LOCAL.test(url)) return false;
return !BLOCKED[u.hostname]?.(u);
} catch { return false; }
};
const tryScript = async (fn) => {
try { await fn(); return true; } catch { return false; }
};
const tabKey = (id) => String(id);
const maps = () => chrome.storage.session.get([TAB_ACTIVE, INJECTED]).then((d) => ({
tabActive: d[TAB_ACTIVE] ?? {},
injected: d[INJECTED] ?? {},
}));
const patchSession = async (patch) => {
const data = await maps();
await chrome.storage.session.set({
[TAB_ACTIVE]: patch.tabActive ?? data.tabActive,
[INJECTED]: patch.injected ?? data.injected,
});
};
const tabOn = (m, id) => Boolean(m[tabKey(id)]);
const setTabOn = async (id, on) => {
const { tabActive } = await maps();
const k = tabKey(id);
const next = { ...tabActive };
if (on) next[k] = true;
else delete next[k];
await patchSession({ tabActive: next });
};
const markInjected = async (id) => {
const { injected } = await maps();
await patchSession({ injected: { ...injected, [tabKey(id)]: true } });
};
const clearTab = async (id) => {
const { tabActive, injected } = await maps();
const k = tabKey(id);
const nextActive = { ...tabActive };
const nextInjected = { ...injected };
delete nextActive[k];
delete nextInjected[k];
await patchSession({ tabActive: nextActive, injected: nextInjected });
};
const raster = async (size, gray) => {
const url = chrome.runtime.getURL(`icons/icon${size}.png`);
const bmp = await createImageBitmap(await (await fetch(url)).blob());
const canvas = new OffscreenCanvas(bmp.width, bmp.height);
const ctx = canvas.getContext('2d');
ctx.drawImage(bmp, 0, 0);
const img = ctx.getImageData(0, 0, bmp.width, bmp.height);
if (!gray) return img;
const d = img.data;
for (let i = 0; i < d.length; i += 4) {
const g = (d[i] * 77 + d[i + 1] * 150 + d[i + 2] * 29) >> 8;
d[i] = d[i + 1] = d[i + 2] = g;
}
return img;
};
const icons = async (on) => {
const key = on ? 'on' : 'off';
if (iconCache[key]) return iconCache[key];
iconCache[key] = Object.fromEntries(await Promise.all(SIZES.map(async (n) => [n, await raster(n, !on)])));
return iconCache[key];
};
const syncIcon = async (on) => {
chrome.action.setTitle({ title: on ? ON : OFF });
await chrome.action.setIcon({ imageData: await icons(on) });
};
const setPage = (tabId, on, toast = false) => tryScript(() =>
chrome.scripting.executeScript({
target: { tabId },
func: (active, show) => globalThis.__codecopyApply?.(active, show),
args: [on, toast],
}),
);
const injectTab = (tabId) => tryScript(async () => {
const target = { tabId };
await chrome.scripting.insertCSS({ target, files: ['content.css'] });
await chrome.scripting.executeScript({ target, files: ['content.js'] });
if (!await setPage(tabId, true, true)) throw 0;
});
const activeTab = () => chrome.tabs.query({ active: true, currentWindow: true }).then(([t]) => t);
const refreshIcon = async () => {
const tab = await activeTab();
if (!tab?.id || !injectable(tab.url)) return syncIcon(false);
const { tabActive } = await maps();
return syncIcon(tabOn(tabActive, tab.id));
};
const deactivate = (id) => setTabOn(id, false).then(() => syncIcon(false));
const onToggle = async () => {
const tab = await activeTab();
if (!tab?.id || !injectable(tab.url)) return;
const { tabActive, injected } = await maps();
const next = !tabOn(tabActive, tab.id);
await setTabOn(tab.id, next);
await syncIcon(next);
const first = next && !tabOn(injected, tab.id);
if (first && await injectTab(tab.id)) return markInjected(tab.id);
if (first) return deactivate(tab.id);
return setPage(tab.id, next, true);
};
chrome.action.setBadgeText({ text: '' });
refreshIcon();
chrome.runtime.onInstalled.addListener(async ({ reason }) => {
if (reason === 'install') await chrome.windows.create({ url: chrome.runtime.getURL('welcome.html') });
await refreshIcon();
});
chrome.runtime.onStartup.addListener(refreshIcon);
chrome.action.onClicked.addListener(onToggle);
chrome.commands.onCommand.addListener(async (cmd) => {
if (cmd !== 'toggle') return;
await onToggle();
});
chrome.tabs.onActivated.addListener(async ({ tabId }) => {
const tab = await chrome.tabs.get(tabId).catch(() => null);
if (!tab || !injectable(tab.url)) return syncIcon(false);
const { tabActive } = await maps();
await syncIcon(tabOn(tabActive, tabId));
});
chrome.tabs.onRemoved.addListener((tabId) => clearTab(tabId));
chrome.tabs.onUpdated.addListener(async (tabId, info, tab) => {
if (info.status !== 'complete' || !injectable(tab.url)) return;
const { injected } = await maps();
if (!tabOn(injected, tabId)) return;
await clearTab(tabId);
if (tab.active) await syncIcon(false);
});