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
|
import 'webext-base-css/webext-base.css';
import './options.css';
import React from 'dom-chef';
import domify from 'doma';
import select from 'select-dom';
import fitTextarea from 'fit-textarea';
import prettyBytes from 'pretty-bytes';
import {assertError} from 'ts-extras';
import * as indentTextarea from 'indent-textarea';
import delegate, {DelegateEvent} from 'delegate-it';
import {isChrome, isFirefox} from 'webext-detect-page';
import {isEnterprise} from 'github-url-detection';
import featureLink from './helpers/feature-link.js';
import clearCacheHandler from './helpers/clear-cache-handler.js';
import {getLocalHotfixes, styleHotfixes} from './helpers/hotfix.js';
import {createRghIssueLink} from './helpers/rgh-issue-link.js';
import {importedFeatures, featuresMeta} from '../readme.md';
import getStorageBytesInUse from './helpers/used-storage.js';
import {perDomainOptions} from './options-storage.js';
import isDevelopmentVersion from './helpers/is-development-version.js';
import {doesBrowserActionOpenOptions} from './helpers/feature-utils.js';
import {state as bisectState} from './helpers/bisect.js';
type Status = {
error?: true;
text?: string;
scopes?: string[];
};
const {version} = browser.runtime.getManifest();
function reportStatus({error, text, scopes}: Status): void {
const tokenStatus = select('#validation')!;
tokenStatus.textContent = text ?? '';
if (error) {
tokenStatus.dataset.validation = 'invalid';
} else {
delete tokenStatus.dataset.validation;
}
for (const scope of select.all('[data-scope]')) {
if (scopes) {
scope.dataset.validation = scopes.includes(scope.dataset.scope!) ? 'valid' : 'invalid';
} else {
scope.dataset.validation = '';
}
}
}
async function getTokenScopes(personalToken: string): Promise<string[]> {
const tokenLink = select('a#personal-token-link')!;
const url = tokenLink.host === 'github.com'
? 'https://api.github.com/'
: `${tokenLink.origin}/api/v3/`;
const response = await fetch(url, {
cache: 'no-store',
headers: {
'User-Agent': 'Refined GitHub',
Accept: 'application/vnd.github.v3+json',
Authorization: `token ${personalToken}`,
},
});
if (!response.ok) {
const details = await response.json();
throw new Error(details.message);
}
const scopes = response.headers.get('X-OAuth-Scopes')!.split(', ');
scopes.push('valid_token');
if (scopes.includes('repo')) {
scopes.push('public_repo');
}
if (scopes.includes('project')) {
scopes.push('read:project');
}
return scopes;
}
function expandTokenSection(): void {
select('details#token')!.open = true;
}
async function updateStorageUsage(area: 'sync' | 'local'): Promise<void> {
const storage = browser.storage[area];
const used = await getStorageBytesInUse(area);
const available = storage.QUOTA_BYTES - used;
for (const output of select.all(`.storage-${area}`)) {
output.textContent = available < 1000
? 'FULL!'
: (available < 100_000
? `Only ${prettyBytes(available)} available`
: `${prettyBytes(used)} used`);
}
}
async function validateToken(): Promise<void> {
reportStatus({});
const tokenField = select('input[name="personalToken"]')!;
if (tokenField.value.startsWith('github_pat_')) {
// Validation not supported yet https://github.com/refined-github/refined-github/issues/6092
return;
}
if (!tokenField.validity.valid || tokenField.value.length === 0) {
// The Chrome options iframe auto-sizer causes the "scrollIntoView" function to scroll incorrectly unless you wait a bit
// https://github.com/refined-github/refined-github/issues/6807
setTimeout(expandTokenSection, 100);
return;
}
reportStatus({text: 'Validating…'});
try {
reportStatus({
scopes: await getTokenScopes(tokenField.value),
});
} catch (error) {
assertError(error);
reportStatus({error: true, text: error.message});
expandTokenSection();
throw error;
}
}
function moveDisabledFeaturesToTop(): void {
const container = select('.js-features')!;
for (const unchecked of select.all('.feature-checkbox:not(:checked)', container).reverse()) {
// .reverse() needed to preserve alphabetical order while prepending
container.prepend(unchecked.closest('.feature')!);
}
}
function buildFeatureCheckbox({id, description, screenshot}: FeatureMeta): HTMLElement {
return (
<div className="feature" data-text={`${id} ${description}`.toLowerCase()}>
<input type="checkbox" name={`feature:${id}`} id={id} className="feature-checkbox"/>
<div className="info">
<label className="feature-name" htmlFor={id}>{id}</label>
{' '}
<a href={featureLink(id)} className="feature-link">
source
</a>
<input hidden type="checkbox" className="screenshot-toggle"/>
{screenshot && (
<a href={screenshot} className="screenshot-link">
screenshot
</a>
)}
<p className="description">{domify(description)}</p>
{screenshot && (
<img hidden data-src={screenshot} className="screenshot"/>
)}
</div>
</div>
);
}
async function findFeatureHandler(event: Event): Promise<void> {
// TODO: Add support for GHE
const options = await perDomainOptions.getOptionsForOrigin().getAll();
const enabledFeatures = importedFeatures.filter(featureId => options['feature:' + featureId]);
await bisectState.set(enabledFeatures);
const button = event.target as HTMLButtonElement;
button.disabled = true;
setTimeout(() => {
button.disabled = false;
}, 10_000);
select('#find-feature-message')!.hidden = false;
}
function summaryHandler(event: DelegateEvent<MouseEvent>): void {
if (event.ctrlKey || event.metaKey || event.shiftKey) {
return;
}
event.preventDefault();
if (event.altKey) {
for (const screenshotLink of select.all('.screenshot-link')) {
toggleScreenshot(screenshotLink.parentElement!);
}
} else {
const feature = event.delegateTarget.parentElement!;
toggleScreenshot(feature);
}
}
function toggleScreenshot(feature: Element): void {
const toggle = feature.querySelector('input.screenshot-toggle')!;
toggle.checked = !toggle.checked;
// Lazy-load image
const screenshot = feature.querySelector('img.screenshot')!;
screenshot.src = screenshot.dataset.src!;
}
function featuresFilterHandler(event: Event): void {
const keywords = (event.currentTarget as HTMLInputElement).value.toLowerCase()
.replaceAll(/\W/g, ' ')
.split(/\s+/)
.filter(Boolean); // Ignore empty strings
for (const feature of select.all('.feature')) {
feature.hidden = !keywords.every(word => feature.dataset.text!.includes(word));
}
}
function focusFirstField({delegateTarget: section}: DelegateEvent<Event, HTMLDetailsElement>): void {
// @ts-expect-error No Firefox support https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoViewIfNeeded
(section.scrollIntoViewIfNeeded ?? section.scrollIntoView).call(section);
if (section.open) {
const field = select('input, textarea', section);
if (field) {
field.focus();
if (field instanceof HTMLTextAreaElement) {
// #6404
fitTextarea(field);
}
}
}
}
async function markLocalHotfixes(): Promise<void> {
for (const [feature, relatedIssue] of await getLocalHotfixes()) {
if (importedFeatures.includes(feature)) {
const input = select<HTMLInputElement>('#' + feature)!;
input.disabled = true;
input.removeAttribute('name');
select(`.feature-name[for="${feature}"]`)!.after(
<span className="hotfix-notice"> (Disabled due to {createRghIssueLink(relatedIssue)})</span>,
);
}
}
}
function updateRateLink(): void {
if (isChrome()) {
return;
}
select('a#rate-link')!.href = isFirefox() ? 'https://addons.mozilla.org/en-US/firefox/addon/refined-github-' : 'https://apps.apple.com/app/id1519867270?action=write-review';
}
async function showStoredCssHotfixes(): Promise<void> {
const cachedCSS = await styleHotfixes.getCached(version);
select('#hotfixes-field')!.textContent
= isDevelopmentVersion()
? 'Hotfixes are not applied in the development version.'
: isEnterprise()
? 'Hotfixes are not applied on GitHub Enterprise.'
: cachedCSS ?? 'No CSS found in cache.';
}
async function generateDom(): Promise<void> {
// Generate list
select('.js-features')!.append(...featuresMeta
.filter(feature => importedFeatures.includes(feature.id))
.map(feature => buildFeatureCheckbox(feature)),
);
// Add notice for features disabled via hotfix
await markLocalHotfixes();
// Update list from saved options
await perDomainOptions.syncForm('form');
// Decorate list
moveDisabledFeaturesToTop();
// Enable token validation
void validateToken();
// Add feature count. CSS-only features are added approximately
select('.features-header')!.append(` (${featuresMeta.length + 25})`);
// Update rate link if necessary
updateRateLink();
// Update storage usage info
void updateStorageUsage('local');
void updateStorageUsage('sync');
// Hide non-applicable "Button link" section
if (doesBrowserActionOpenOptions) {
select('#action')!.hidden = true;
}
// Show stored CSS hotfixes
void showStoredCssHotfixes();
}
function addEventListeners(): void {
// Update domain-dependent page content when the domain is changed
select('.OptionsSyncPerDomain-picker select')?.addEventListener('change', ({currentTarget: dropdown}) => {
const host = (dropdown as HTMLSelectElement).value;
select('a#personal-token-link')!.host = host === 'default' ? 'github.com' : host;
// Delay validating to let options load first
setTimeout(validateToken, 100);
});
// Refresh page when permissions are changed (because the dropdown selector needs to be regenerated)
browser.permissions.onRemoved.addListener(() => {
location.reload();
});
browser.permissions.onAdded.addListener(() => {
location.reload();
});
// Update storage usage info
browser.storage.onChanged.addListener((_, areaName) => {
void updateStorageUsage(areaName as 'sync' | 'local');
});
// Improve textareas editing
fitTextarea.watch('textarea');
indentTextarea.watch('textarea');
// Load screenshots
delegate('.screenshot-link', 'click', summaryHandler);
// Automatically focus field when a section is toggled open
delegate('details', 'toggle', focusFirstField, {capture: true});
// Filter feature list
select('#filter-features')!.addEventListener('input', featuresFilterHandler);
// Add cache clearer
select('#clear-cache')!.addEventListener('click', clearCacheHandler);
// Add bisect tool
select('#find-feature')!.addEventListener('click', findFeatureHandler);
// Add token validation
select('[name="personalToken"]')!.addEventListener('input', validateToken);
}
async function init(): Promise<void> {
await generateDom();
addEventListeners();
// TODO: Storage cleanup #6421, Drop in June 2023
void browser.storage.local.remove('featuresAlreadySeen');
}
void init();
|