-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontent_script.js
283 lines (252 loc) · 9.25 KB
/
content_script.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
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
const SHOULD_INTERCEPT = "kangaroo-intercept";
const TRUE = "true";
const FALSE = "false";
const DEVELOPMENT_URL = "http://localhost:3000";
const PRODUCTION_URL = "https://kangarooos.com";
const BASE_URL = DEVELOPMENT_URL;
const DEFAULT_ICON_URL = chrome.runtime.getURL("assets/file_icon.png");
const onClick = async (event) => {
// Don't interact with https://kangarooos.com
const href = window.location.href;
if (href.startsWith(DEVELOPMENT_URL) || href.startsWith(PRODUCTION_URL)) return
// Track clicks on file inputs
const input = event.target;
if (input.getAttribute(SHOULD_INTERCEPT) === TRUE) {
event.stopImmediatePropagation();
event.preventDefault();
// Open custom file dialogue and provide files from the Kangaroo Cloud
await createCustomUploadDialog(event);
input.setAttribute(SHOULD_INTERCEPT, FALSE);
} else if (input.getAttribute(SHOULD_INTERCEPT) === FALSE) {
// Reset for next time
input.setAttribute(SHOULD_INTERCEPT, TRUE);
}
};
// High level loading files from Kangaroo to file input if user picked files from Kangaroo's file dialogue
const onChange = async (event) => {
// Don't interact with https://kangarooos.com
const href = window.location.href;
if (href.startsWith(DEVELOPMENT_URL) || href.startsWith(PRODUCTION_URL)) return
const input = event.target;
if (input.getAttribute(SHOULD_INTERCEPT) === TRUE) {
event.stopImmediatePropagation();
event.preventDefault();
await loadKangarooFilesToInput(
event,
await retrieveFromLocalStorage("selectedFileIds")
);
input.setAttribute(SHOULD_INTERCEPT, FALSE);
input.dispatchEvent(new Event("change", event));
} else if (input.getAttribute(SHOULD_INTERCEPT) === FALSE) {
// Reset for next time
input.setAttribute(SHOULD_INTERCEPT, TRUE);
}
};
const createCustomUploadDialog = async (event) => {
const acceptedExtensions = event.target.getAttribute("accept");
const qualifyingFileData = await getQualifyingFileData(acceptedExtensions);
await createFileSelectionModal(event, qualifyingFileData);
};
// Lower level loading files from Kangaroo to file input if user picked files from Kangaroo's file dialogue
const loadKangarooFilesToInput = async (event, fileIds) => {
const input = event.target;
const dT = new DataTransfer();
const downloadedFiles = await Promise.all(
fileIds.map(async (id) => {
const response = await chrome.runtime.sendMessage({
event: "cloud-file-detected",
fileId: id,
});
if (response.status === "ok") {
const res = await fetch(response.url);
const blob = await res.blob();
const fileFromS3 = new File([blob], response.name, {
type: response.fileType,
});
return fileFromS3;
}
})
);
downloadedFiles.forEach((file) => dT.items.add(file));
for (let i = 0; i < input.files.length; i++) {
dT.items.add(input.files[i]);
}
input.files = dT.files;
};
const getQualifyingFileData = async (listOfExtensions = []) => {
// TODO retrieve files with qualifying extensions
const res = await chrome.runtime.sendMessage({
event: "get-file-list",
});
return res.files;
};
const createFileSelectionModal = async (ogClickEvent, files = []) => {
const uploadModalRes = await fetch(
chrome.runtime.getURL("upload_modal.html")
);
const uploadModalHTML = await uploadModalRes.text();
// Add stylesheet
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = chrome.runtime.getURL("upload_modal.css");
document.head.appendChild(link);
// Add modal
const div = document.createElement("div");
div.innerHTML = uploadModalHTML;
div.id = "modal-background";
document.body.insertBefore(div, document.body.firstChild);
const fileDivs = files.map(({ name, id }) => createFileDiv(name, id));
fileDivs.forEach((div) => {
div.addEventListener("click", async (clickEvent) => {
await handleFileClick(ogClickEvent, clickEvent, div)
});
});
document
.getElementById("upload-from-computer-btn")
.addEventListener("click", async () => {
await saveSelectionAndOpenNativeModal(ogClickEvent);
});
document.getElementById("open-files").addEventListener("click", async () => {
await saveSelectionAndUpload(ogClickEvent);
});
document.getElementById("cancel").addEventListener("click", () => {
document.getElementById("modal-background").remove();
ogClickEvent.dispatchEvent(new Event("click", ogClickEvent));
});
};
// Handle selecting files from the modal
// Single click highlights file
// Double click selects file
const handleFileClick = async (ogClickEvent, clickEvent, div) => {
const clickedTimes = parseInt(div.getAttribute('clicks') ?? 0) + 1
div.setAttribute('clicks', clickedTimes.toString());
setTimeout(async () => {
const currentClicks = parseInt(div.getAttribute('clicks') ?? 0)
if (currentClicks === 1) {
if (!clickEvent.shiftKey) {
document.getElementById("modal-background")
.querySelectorAll("div .selected")
.forEach((node) => node.classList.remove("selected"));
}
div.classList.toggle("selected");
} else if (currentClicks >= 2) {
if (!div.classList.contains("selected")) {
document.getElementById("modal-background")
.querySelectorAll("div .selected")
.forEach((node) => node.classList.remove("selected"));
div.classList.toggle("selected");
}
await saveSelectionAndUpload(ogClickEvent);
}
div.setAttribute('clicks', 0)
}, 250);
}
// User wants to upload from native file dialogue
const saveSelectionAndOpenNativeModal = async (ogClickEvent) => {
const selectedFileIds = [...document.querySelectorAll("div .selected")].map(
(node) => node.id
);
document.getElementById("modal-background").remove();
await saveToLocalStorage("selectedFileIds", selectedFileIds);
ogClickEvent.target.dispatchEvent(new PointerEvent("click", ogClickEvent));
// Continue onto native file dialog...
};
// Find all selected files and upload them
const saveSelectionAndUpload = async (ogClickEvent) => {
const selectedFileIds = [...document.querySelectorAll("div .selected")].map(
(node) => node.id
);
document.getElementById("modal-background").remove();
await saveToLocalStorage("selectedFileIds", selectedFileIds);
ogClickEvent.target.setAttribute(SHOULD_INTERCEPT, TRUE);
ogClickEvent.target.dispatchEvent(new Event("change", ogClickEvent));
// End of the line...
};
const saveToLocalStorage = async (key, value) => {
const obj = {};
obj[key] = value;
return chrome.storage.local.set(obj);
};
const retrieveFromLocalStorage = async (key) => {
const storage = await chrome.storage.local.get(key);
return storage[key];
};
const isFileInput = (elem) => {
return elem.nodeName === "INPUT" && elem.type === "file";
};
const hasFiles = (input) => {
return input.files.length > 0;
};
// Create the file icon view for file dialogue
const createFileDiv = (name, id, iconUrl = DEFAULT_ICON_URL) => {
const div = document.createElement("div");
const img = document.createElement("img");
const p = document.createElement("p");
div.id = id;
div.classList.add("file-container");
div.appendChild(img);
div.appendChild(p);
img.classList.add("file-icon");
img.src = iconUrl;
img.draggable = false;
p.classList.add("file-name");
p.innerText = truncateText(name, 21);
document.getElementById("file-display").appendChild(div);
return div;
};
const truncateText = (text, maxLength) => {
if (text.length > maxLength) {
return text.substring(0, maxLength) + "...";
}
return text;
};
// <- TRACK KEYS START ->
KEYS_TO_TRACK = ['Shift', 'Meta', 'S']
const pressedKeys = {
}
const handleKeyDown = (e) => {
// Only track keys that we need
if (KEYS_TO_TRACK.includes(e.key)) {
pressedKeys[e.code] = true
chrome.runtime.sendMessage({
event: 'key-pressed',
key: e.code
})
}
}
const handleKeyUp = (e) => {
if (pressedKeys[e.code]) {
delete pressedKeys[e.code]
chrome.runtime.sendMessage({
event: 'key-released',
key: e.code
})
}
}
// <- TRACK KEYS END ->
// Keep track of listeners and then remove and reapply once HTML changes (MutationObserver)
window.onload = async () => {
const targetNode = document.querySelector("html");
// Options for the observer (which mutations to observe)
const config = { attributes: false, childList: true, subtree: true };
// Add listeners to new input[type=file] buttons
const addListeners = () => {
inputButtons = document.querySelectorAll("input[type='file']");
inputButtons.forEach((inputElem) => {
if (inputElem.getAttribute(SHOULD_INTERCEPT) === null) {
inputElem.setAttribute(SHOULD_INTERCEPT, TRUE);
inputElem.addEventListener("click", (event) => onClick(event), true);
inputElem.addEventListener("change", (event) => onChange(event), true);
}
});
};
const callback = function (mutationsList, observer) {
addListeners();
};
// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
document.addEventListener("keydown", handleKeyDown, true)
document.addEventListener("keyup", handleKeyUp, true)
};