forked from JetBrains/toolbox-browser-extension
-
Notifications
You must be signed in to change notification settings - Fork 0
/
github.js
442 lines (383 loc) · 13.8 KB
/
github.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
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
import 'whatwg-fetch';
import {observe} from 'selector-observer';
import gh from 'github-url-to-object';
import {
SUPPORTED_LANGUAGES,
SUPPORTED_TOOLS,
USAGE_THRESHOLD,
HUNDRED_PERCENT,
MAX_DECIMALS,
MIN_VALID_HTTP_STATUS,
MAX_VALID_HTTP_STATUS,
DEFAULT_LANGUAGE,
DEFAULT_LANGUAGE_SET,
CLONE_PROTOCOLS
} from './constants';
import {
getToolboxURN,
getToolboxNavURN,
callToolbox
} from './api/toolbox';
const CLONE_BUTTON_GROUP_JS_CSS_CLASS = 'js-toolbox-clone-button-group';
const OPEN_BUTTON_JS_CSS_CLASS = 'js-toolbox-open-button';
const OPEN_MENU_ITEM_JS_CSS_CLASS = 'js-toolbox-open-menu-item';
const fetchMetadata = () => new Promise((resolve, reject) => {
const metadata = gh(window.location.toString(), {enterprise: true});
if (metadata) {
resolve(metadata);
} else {
reject();
}
});
const checkResponseStatus = response => new Promise((resolve, reject) => {
if (response.status >= MIN_VALID_HTTP_STATUS && response.status <= MAX_VALID_HTTP_STATUS) {
resolve(response);
} else {
reject();
}
});
const parseResponse = response => new Promise((resolve, reject) => {
response.json().then(result => {
if (Object.keys(result).length > 0) {
resolve(result);
} else {
reject();
}
}).catch(() => {
reject();
});
});
const convertBytesToPercents = languages => new Promise(resolve => {
const totalBytes = Object.
values(languages).
reduce((total, bytes) => total + bytes, 0);
Object.
keys(languages).
forEach(key => {
const percentFloat = languages[key] / totalBytes * HUNDRED_PERCENT;
const percentString = percentFloat.toFixed(MAX_DECIMALS);
languages[key] = parseFloat(percentString);
});
resolve(languages);
});
const extractLanguagesFromPage = githubMetadata => new Promise(resolve => {
// TBX-4762: private repos don't let use API, load root page and scrape languages off it
fetch(githubMetadata.clone_url).
then(response => response.text()).
then(htmlString => {
const parser = new DOMParser();
const htmlDocument = parser.parseFromString(htmlString, 'text/html');
const languageElements = htmlDocument.querySelectorAll('.repository-lang-stats-numbers .lang');
if (languageElements.length === 0) {
// see if it's new UI as of 24.06.20
const newLanguageElements = htmlDocument.querySelectorAll(
'[data-ga-click="Repository, language stats search click, location:repo overview"]'
);
if (newLanguageElements.length > 0) {
const allLanguages = Array.from(newLanguageElements).reduce((acc, el) => {
const langEl = el.querySelector('span');
const percentEl = langEl.nextElementSibling;
acc[langEl.textContent] = percentEl ? parseFloat(percentEl.textContent) : USAGE_THRESHOLD + 1;
return acc;
}, {});
if (Object.keys(allLanguages).length > 0) {
resolve(allLanguages);
} else {
resolve(DEFAULT_LANGUAGE_SET);
}
} else {
resolve(DEFAULT_LANGUAGE_SET);
}
} else {
const allLanguages = Array.from(languageElements).reduce((acc, el) => {
const percentEl = el.nextElementSibling;
acc[el.textContent] = percentEl ? parseFloat(percentEl.textContent) : USAGE_THRESHOLD + 1;
return acc;
}, {});
resolve(allLanguages);
}
}).
catch(() => {
resolve(DEFAULT_LANGUAGE_SET);
});
});
const fetchLanguages = githubMetadata => new Promise(resolve => {
fetch(`${githubMetadata.api_url}/languages`).
then(checkResponseStatus).
then(parseResponse).
then(convertBytesToPercents).
then(resolve).
catch(() => {
extractLanguagesFromPage(githubMetadata).
then(resolve);
});
});
const selectTools = languages => new Promise(resolve => {
const overallPoints = Object.
values(languages).
reduce((overall, current) => overall + current, 0);
const filterLang = language =>
SUPPORTED_LANGUAGES[language.toLowerCase()] && languages[language] / overallPoints > USAGE_THRESHOLD;
const selectedToolIds = Object.
keys(languages).
filter(filterLang).
reduce((acc, key) => {
acc.push(...SUPPORTED_LANGUAGES[key.toLowerCase()]);
return acc;
}, []);
const normalizedToolIds = selectedToolIds.length > 0
? Array.from(new Set(selectedToolIds))
: SUPPORTED_LANGUAGES[DEFAULT_LANGUAGE];
const tools = normalizedToolIds.
sort().
map(toolId => SUPPORTED_TOOLS[toolId]);
resolve(tools);
});
const fetchTools = githubMetadata => fetchLanguages(githubMetadata).then(selectTools);
const getHttpsCloneUrl = githubMetadata => `${githubMetadata.clone_url}.git`;
const getSshCloneUrl =
githubMetadata => `git@${githubMetadata.host}:${githubMetadata.user}/${githubMetadata.repo}.git`;
let handleMessage = null;
const renderPageAction = githubMetadata => new Promise(resolve => {
if (handleMessage && chrome.runtime.onMessage.hasListener(handleMessage)) {
chrome.runtime.onMessage.removeListener(handleMessage);
}
handleMessage = (message, sender, sendResponse) => {
switch (message.type) {
case 'get-tools':
fetchTools(githubMetadata).then(sendResponse);
return true;
case 'perform-action':
const toolboxAction = getToolboxURN(message.toolTag, message.cloneUrl);
callToolbox(toolboxAction);
break;
// no default
}
return undefined;
};
chrome.runtime.onMessage.addListener(handleMessage);
resolve();
});
const removeCloneButtons = () => {
const cloneButtonGroup = document.querySelector(`.${CLONE_BUTTON_GROUP_JS_CSS_CLASS}`);
if (cloneButtonGroup) {
cloneButtonGroup.parentElement.removeChild(cloneButtonGroup);
}
};
const addCloneButtonEventHandler = (btn, githubMetadata) => {
btn.addEventListener('click', e => {
e.preventDefault();
const {toolTag} = e.currentTarget.dataset;
chrome.runtime.sendMessage({type: 'get-protocol'}, ({protocol}) => {
const cloneUrl = protocol === CLONE_PROTOCOLS.HTTPS
? getHttpsCloneUrl(githubMetadata)
: getSshCloneUrl(githubMetadata);
const action = getToolboxURN(toolTag, cloneUrl);
callToolbox(action);
});
});
};
const createCloneButton = (tool, githubMetadata, small = true) => {
const button = document.createElement('a');
button.setAttribute(
'class',
`btn ${small ? 'btn-sm' : ''} tooltipped tooltipped-s tooltipped-multiline BtnGroup-item d-flex`
);
button.setAttribute('href', '#');
button.setAttribute('aria-label', `Clone in ${tool.name}`);
button.setAttribute('style', 'align-items:center');
button.dataset.toolTag = tool.tag;
const buttonIcon = document.createElement('img');
buttonIcon.setAttribute('alt', tool.name);
buttonIcon.setAttribute('src', tool.icon);
buttonIcon.setAttribute('width', '16');
buttonIcon.setAttribute('height', '16');
buttonIcon.setAttribute('style', 'vertical-align:text-top');
button.appendChild(buttonIcon);
addCloneButtonEventHandler(button, githubMetadata);
return button;
};
const renderCloneButtons = (tools, githubMetadata) => {
let getRepoController = document.querySelector('.BtnGroup + .d-flex > get-repo-controller');
getRepoController = getRepoController
? getRepoController.parentElement
: document.querySelector('.js-get-repo-select-menu');
if (getRepoController) {
// the buttons still exist on the previous page after clicking on the 'Back' button;
// only create them if they are absent
let toolboxCloneButtonGroup = document.querySelector(`.${CLONE_BUTTON_GROUP_JS_CSS_CLASS}`);
if (!toolboxCloneButtonGroup) {
toolboxCloneButtonGroup = document.createElement('div');
toolboxCloneButtonGroup.setAttribute('class', `BtnGroup ml-2 d-flex ${CLONE_BUTTON_GROUP_JS_CSS_CLASS}`);
tools.forEach(tool => {
const btn = createCloneButton(tool, githubMetadata);
toolboxCloneButtonGroup.appendChild(btn);
});
getRepoController.insertAdjacentElement('beforebegin', toolboxCloneButtonGroup);
}
} else {
// new UI as of 24.06.20
getRepoController = document.querySelector('get-repo');
if (getRepoController) {
// the buttons still exist on the previous page after clicking on the 'Back' button;
// only create them if they are absent
let toolboxCloneButtonGroup = document.querySelector(`.${CLONE_BUTTON_GROUP_JS_CSS_CLASS}`);
if (!toolboxCloneButtonGroup) {
toolboxCloneButtonGroup = document.createElement('div');
toolboxCloneButtonGroup.setAttribute('class', `BtnGroup mr-2 d-flex ${CLONE_BUTTON_GROUP_JS_CSS_CLASS}`);
tools.forEach(tool => {
const btn = createCloneButton(tool, githubMetadata, false);
toolboxCloneButtonGroup.appendChild(btn);
});
getRepoController.insertAdjacentElement('beforebegin', toolboxCloneButtonGroup);
}
}
}
};
const addOpenButtonEventHandler = (domElement, tool, githubMetadata) => {
domElement.addEventListener('click', e => {
e.preventDefault();
const {user, repo, branch} = githubMetadata;
const normalizedBranch = branch.split('/').shift();
const filePath = location.pathname.replace(`/${user}/${repo}/blob/${normalizedBranch}/`, '');
let lineNumber = location.hash.replace('#L', '');
if (lineNumber === '') {
lineNumber = null;
}
callToolbox(getToolboxNavURN(tool.tag, repo, filePath, lineNumber));
});
};
// when navigating with back and forward buttons
// we have to re-create open actions b/c their click handlers got lost somehow
const removeOpenButtons = () => {
const actions = document.querySelectorAll(`.${OPEN_BUTTON_JS_CSS_CLASS}`);
actions.forEach(action => {
action.parentElement.removeChild(action);
});
const menuItems = document.querySelectorAll(`.${OPEN_MENU_ITEM_JS_CSS_CLASS}`);
menuItems.forEach(item => {
item.parentElement.removeChild(item);
});
};
const removePageButtons = () => {
removeCloneButtons();
removeOpenButtons();
};
const createOpenButton = (tool, githubMetadata) => {
const action = document.createElement('a');
action.setAttribute('class', `btn-octicon tooltipped tooltipped-nw ${OPEN_BUTTON_JS_CSS_CLASS}`);
action.setAttribute('aria-label', `Open this file in ${tool.name}`);
action.setAttribute('href', '#');
const actionIcon = document.createElement('img');
actionIcon.setAttribute('alt', tool.name);
actionIcon.setAttribute('src', tool.icon);
actionIcon.setAttribute('width', '16');
actionIcon.setAttribute('height', '16');
action.appendChild(actionIcon);
addOpenButtonEventHandler(action, tool, githubMetadata);
return action;
};
const createOpenMenuItem = (tool, first, githubMetadata) => {
const menuItem = document.createElement('a');
menuItem.setAttribute('class', 'dropdown-item');
menuItem.setAttribute('role', 'menu-item');
menuItem.setAttribute('href', '#');
if (first) {
menuItem.style.borderTop = '1px solid #eaecef';
}
menuItem.textContent = `Open in ${tool.name}`;
addOpenButtonEventHandler(menuItem, tool, githubMetadata);
menuItem.addEventListener('click', () => {
const blobToolbar = document.querySelector('.BlobToolbar');
if (blobToolbar) {
blobToolbar.removeAttribute('open');
}
});
const menuItemContainer = document.createElement('li');
menuItemContainer.setAttribute('class', OPEN_MENU_ITEM_JS_CSS_CLASS);
menuItemContainer.appendChild(menuItem);
return menuItemContainer;
};
const renderOpenButtons = (tools, githubMetadata) => {
const actionAnchorElement = document.querySelector('.repository-content .Box-header .BtnGroup + div');
const actionAnchorFragment = document.createDocumentFragment();
const blobToolbarDropdown = document.querySelector('.BlobToolbar-dropdown');
tools.forEach((tool, toolIndex) => {
if (actionAnchorElement) {
const action = createOpenButton(tool, githubMetadata);
actionAnchorFragment.appendChild(action);
}
if (blobToolbarDropdown) {
const menuItem = createOpenMenuItem(tool, toolIndex === 0, githubMetadata);
blobToolbarDropdown.appendChild(menuItem);
}
});
if (actionAnchorElement) {
actionAnchorElement.prepend(actionAnchorFragment);
}
};
const renderPageButtons = githubMetadata => {
fetchTools(githubMetadata).
then(tools => {
renderCloneButtons(tools, githubMetadata);
renderOpenButtons(tools, githubMetadata);
}).
catch(() => {
// do nothing
});
};
const startTrackingDOMChanges = githubMetadata =>
observe('.new-discussion-timeline', {
add() {
renderPageButtons(githubMetadata);
},
remove() {
removePageButtons();
}
});
const stopTrackingDOMChanges = observer => {
if (observer) {
observer.abort();
}
};
const enablePageAction = githubMetadata => {
chrome.runtime.sendMessage({
type: 'enable-page-action',
project: githubMetadata.repo,
https: getHttpsCloneUrl(githubMetadata),
ssh: getSshCloneUrl(githubMetadata)
});
};
const disablePageAction = () => {
chrome.runtime.sendMessage({type: 'disable-page-action'});
};
const toolboxify = () => {
fetchMetadata().
then(metadata => {
renderPageAction(metadata).then(() => {
enablePageAction(metadata);
});
chrome.runtime.sendMessage({type: 'get-modify-pages'}, data => {
let DOMObserver = null;
if (data.allow) {
DOMObserver = startTrackingDOMChanges(metadata);
}
chrome.runtime.onMessage.addListener(message => {
switch (message.type) {
case 'modify-pages-changed':
if (message.newValue) {
DOMObserver = startTrackingDOMChanges(metadata);
} else {
stopTrackingDOMChanges(DOMObserver);
}
break;
// no default
}
});
});
}).
catch(() => {
disablePageAction();
});
};
export default toolboxify;