-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathfeature-manager.tsx
More file actions
246 lines (202 loc) · 7.5 KB
/
feature-manager.tsx
File metadata and controls
246 lines (202 loc) · 7.5 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
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
/* eslint-disable no-await-in-loop -- Event loops */
import React from 'dom-chef';
import domLoaded from 'dom-loaded';
import * as pageDetect from 'github-url-detection';
import oneEvent from 'one-event';
import {elementExists} from 'select-dom';
import stripIndent from 'strip-indent';
import type {Promisable} from 'type-fest';
import {isWebPage} from 'webext-detect';
import {messageRuntime} from 'webext-msg';
import asyncForEach from './helpers/async-for-each.js';
import bisectFeatures from './helpers/bisect.js';
import {catchErrors, disableErrorLogging} from './helpers/errors.js';
import {
getFeatureId, listenToAjaxedLoad, log, shortcutMap,
} from './helpers/feature-helpers.js';
import {isFeaturePrivate, type RunConditions, shouldFeatureRun} from './helpers/feature-utils.js';
import {
applyStyleHotfixes,
brokenFeatures,
getLocalHotfixesAsOptions,
preloadSyncLocalStrings,
} from './helpers/hotfix.js';
import ArrayMap from './helpers/map-of-arrays.js';
import waitFor from './helpers/wait-for.js';
import optionsStorage, {isFeatureDisabled, type RghOptions} from './options-storage.js';
import {contentScriptToggle} from './options/reload-without.js';
type FeatureInitResult = void | false;
type FeatureInit = (signal: AbortSignal) => Promisable<FeatureInitResult>;
type FeatureLoader = RunConditions & {
/** This only adds the shortcut to the help screen, it doesn't enable it. @default {} */
shortcuts?: Record<string, string>;
/** Whether to wait for DOM ready before running `init`. By default, it runs `init` as soon as `body` is found. @default false */
awaitDomReady?: true;
/**
When pressing the back button, DOM changes and listeners are still there. Using a selector here would use the integrated deduplication logic, but it cannot be used with `delegate` and it shouldn't use `has-rgh` and `has-rgh-inner` anymore. #5871
@deprecated
@default false
*/
deduplicate?: string;
init: Arrayable<FeatureInit>;
};
const currentFeatureControllers = new ArrayMap<FeatureId, AbortController>();
// eslint-disable-next-line no-async-promise-executor -- Rule assumes we don't want to leave it pending
const globalReady = new Promise<RghOptions>(async resolve => {
if (!isWebPage()) {
throw new Error('This script should only be run on web pages');
}
listenToAjaxedLoad();
const [options, contentScripts, localHotfixes, bisectedFeatures] = await Promise.all([
optionsStorage.getAll(),
contentScriptToggle.get(),
getLocalHotfixesAsOptions(),
bisectFeatures(),
preloadSyncLocalStrings(),
]);
if (!contentScripts) {
await contentScriptToggle.remove();
const message = 'Refined GitHub: scripts were disabled for this load, but CSS can’t be disabled this way.';
console.warn(message);
alert(message);
return;
}
log.setup(options);
await waitFor(() => document.body);
if (pageDetect.is500() || pageDetect.isPasswordConfirmation()) {
return;
}
if (elementExists('[refined-github]')) {
console.warn(stripIndent(`
Refined GitHub has been loaded twice. This may be because:
• You loaded the developer version, or
• The extension just updated
If you see this at every load, please open an issue mentioning the browser you're using and the URL where this appears.
`));
return;
}
document.documentElement.setAttribute('refined-github', '');
// Request in the background page to avoid showing a 404 request in the console
// https://github.com/refined-github/refined-github/issues/6433
// eslint-disable-next-line promise/prefer-await-to-then -- Reads as a callback
void messageRuntime<string>({getStyleHotfixes: true}).then(applyStyleHotfixes);
if (options.customCss.trim().length > 0) {
// Review #5857 and #5493 before making changes
document.head.append(<style>{options.customCss}</style>);
}
if (bisectedFeatures) {
Object.assign(options, bisectedFeatures);
} else {
// If features are remotely marked as "seriously breaking" by the maintainers, disable them without having to wait for proper updates to propagate #3529
void brokenFeatures.get();
Object.assign(options, localHotfixes);
}
if (elementExists('body.logged-out')) {
console.warn('Refined GitHub is only expected to work when you’re logged in to GitHub. Errors will not be shown.');
disableErrorLogging();
} else {
catchErrors();
}
// Detect unload via two events to catch both clicks and history navigation
// https://github.com/refined-github/refined-github/issues/6437#issuecomment-1489921988
document.addEventListener('turbo:before-fetch-request', unloadAll); // Clicks
document.addEventListener('turbo:visit', unloadAll); // Back/forward button
resolve(options);
});
function castArray<Item>(value: Arrayable<Item>): Item[] {
return Array.isArray(value) ? value : [value];
}
async function add(url: string, ...loaders: FeatureLoader[]): Promise<void> {
const id = getFeatureId(url);
/* Feature filtering and running */
const options = await globalReady;
// Skip disabled features, unless the feature is private
if (isFeatureDisabled(options, id) && !isFeaturePrivate(id)) {
if (loaders.length === 0) {
// CSS-only https://github.com/refined-github/refined-github/issues/7944
// GitHub cleans up the CSS disabling attributes after navigation.
// https://github.com/refined-github/refined-github/issues/8172
do {
document.documentElement.setAttribute('rgh-OFF-' + id, '');
log.info('↩️', 'Skipping', id);
} while (await oneEvent(document, 'turbo:render'));
} else {
log.info('↩️', 'Skipping', id);
}
return;
}
if (loaders.length === 0) {
// CSS-only
return;
}
void asyncForEach(loaders, async loader => {
// Input defaults and validation
const {
shortcuts = {},
asLongAs,
include,
exclude,
init,
awaitDomReady = false,
deduplicate = false,
} = loader;
if (include?.length === 0) {
throw new Error(`${id}: \`include\` cannot be an empty array, it means "run nowhere"`);
}
// 404 pages should only run 404-only features
if (pageDetect.is404() && !include?.includes(pageDetect.is404) && !asLongAs?.includes(pageDetect.is404)) {
return;
}
let firstLoop = true;
do {
if (awaitDomReady) {
await domLoaded;
}
if (firstLoop) {
firstLoop = false;
} else if (deduplicate && elementExists(deduplicate)) {
continue;
}
if (!await shouldFeatureRun({asLongAs, include, exclude})) {
continue;
}
const featureController = new AbortController();
currentFeatureControllers.append(id, featureController);
// Do not await, or else an error on a page will break the feature completely until a reload
void asyncForEach(castArray(init), async init => {
const result = await init(featureController.signal);
// Features can return `false` when they decide not to run on the current page
if (result !== false && !isFeaturePrivate(id)) {
log.info('✅', id);
// Register feature shortcuts
for (const [hotkey, description] of Object.entries(shortcuts)) {
shortcutMap.set(hotkey, description);
}
}
});
} while (await oneEvent(document, 'turbo:render'));
});
}
async function addCssFeature(url: string): Promise<void> {
void add(url);
}
function unload(featureUrl: string): void {
const id = getFeatureId(featureUrl);
for (const controller of currentFeatureControllers.get(id) ?? []) {
controller.abort();
}
}
function unloadAll(): void {
for (const feature of currentFeatureControllers.values()) {
for (const controller of feature) {
controller.abort();
}
}
currentFeatureControllers.clear();
}
const features = {
add,
unload,
addCssFeature,
};
export default features;