-
-
Notifications
You must be signed in to change notification settings - Fork 878
/
nightMode.js
421 lines (367 loc) · 11.3 KB
/
nightMode.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
/* @flow */
import _ from 'lodash';
import { getTimes as getSunriseSunset } from 'suncalc';
import { $ } from '../vendor';
import { Module } from '../core/module';
import * as Init from '../core/init';
import * as Modules from '../core/modules';
import * as Options from '../core/options';
import {
appType,
Alert,
BodyClasses,
CreateElement,
currentSubreddit,
HOUR,
MINUTE,
} from '../utils';
import { Session, Storage, i18n, multicast } from '../environment';
import * as CommandLine from './commandLine';
import * as Menu from './menu';
import * as StyleTweaks from './styleTweaks';
export const module: Module<*> = new Module('nightMode');
module.moduleName = 'nightModeName';
module.category = 'appearanceCategory';
module.description = 'nightModeDesc';
module.options = {
nightModeOn: {
type: 'boolean',
value: false,
description: 'nightModeNightModeOnDesc',
title: 'nightModeNightModeOnTitle',
},
nightSwitch: {
type: 'boolean',
value: true,
description: 'nightModeNightSwitchDesc',
title: 'nightModeNightSwitchTitle',
advanced: true,
},
automaticNightMode: {
type: 'enum',
value: 'none',
values: [{
name: 'nightModeAutomaticNightModeNone',
value: 'none',
}, {
name: 'nightModeAutomaticNightModeAutomatic',
value: 'automatic',
}, {
name: 'nightModeAutomaticNightModeUser',
value: 'user',
}],
description: 'nightModeAutomaticNightModeDesc',
title: 'nightModeAutomaticNightModeTitle',
},
nightModeStart: {
type: 'text',
value: '20:00',
description: 'nightModeNightModeStartDesc',
title: 'nightModeNightModeStartTitle',
dependsOn: options => options.automaticNightMode.value === 'user',
},
nightModeEnd: {
type: 'text',
value: '6:00',
description: 'nightModeNightModeEndDesc',
title: 'nightModeNightModeEndTitle',
dependsOn: options => options.automaticNightMode.value === 'user',
},
nightModeOverrideHours: {
type: 'text',
value: '8',
description: 'nightModeNightModeOverrideHoursDesc',
title: 'nightModeNightModeOverrideHoursTitle',
dependsOn: options => options.automaticNightMode.value !== 'none',
},
useSubredditStyles: {
type: 'boolean',
value: false,
description: 'nightModeUseSubredditStylesDesc',
title: 'nightModeUseSubredditStylesTitle',
advanced: true,
},
subredditStylesWhitelist: {
type: 'list',
value: '',
listType: 'subreddits',
description: 'nightModeSubredditStylesWhitelistDesc',
title: 'nightModeSubredditStylesWhitelistTitle',
},
coloredLinks: {
type: 'boolean',
bodyClass: true,
value: false,
description: 'nightModeColoredLinksDesc',
title: 'nightModeColoredLinksTitle',
},
};
module.exclude = [
'd2x',
];
const localStorageKey = 'RES_nightMode';
const nightmodeOverrideStorage = Storage.wrap('RESmodules.nightMode.nightModeOverrideStart', (null: null | number));
module.onToggle = toggle => {
// If the module is turned off, disable night mode completely
if (!toggle) {
disableNightMode();
}
};
module.loadDynamicOptions = () => {
// To avoid the flash of unstyled content, the very first thing we should do is get a hold
// of the document object and add necessary classes...
if (typeof localStorage === 'object' && localStorage.getItem(localStorageKey)) {
addNightmodeClass();
}
};
module.beforeLoad = () => {
if (isNightModeOn()) {
addNightmodeClass();
// Set a localStorage token so that in the future we can add nightmode to the page prior to page load.
localStorage.setItem(localStorageKey, 'true');
}
};
module.always = () => {
if (!Modules.isRunning(module)) {
// Remove nightmode if the localStorage token was incorrect
localStorage.removeItem(localStorageKey);
removeNightmodeClass();
}
};
module.go = () => {
handleAutomaticNightMode();
if (module.options.nightSwitch.value) {
createNightSwitch();
}
CommandLine.registerCommand(/^(ls|ns)$/, 'ns - toggle nightSwitch',
(command, val, match) => {
if (match[1] === 'ls') {
return 'Toggle nightSwitch (deprecated, use "ns" instead).';
} else {
return 'Toggle nightSwitch';
}
}, () => {
userToggledNightMode();
}
);
};
export function isNightModeOn(): boolean {
return Modules.isRunning(module) && module.options.nightModeOn.value;
}
export async function isNightmodeCompatible(): Promise<boolean> {
await Init.loadOptions;
if (!isNightModeOn()) {
// nightmode is off
return true;
}
const subreddit = currentSubreddit();
if (!subreddit) {
// not in a subreddit, vanilla reddit is compatible
return true;
}
if (module.options.useSubredditStyles.value) {
// user has chosen to always use subreddit styles regardless of compatibility
return true;
}
if (['all', 'popular', 'friends', 'mod'].includes(subreddit)) {
// special-case subreddits are always compatible
return true;
}
const isWhitelisted = module.options.subredditStylesWhitelist.value.split(',').includes(subreddit.toLowerCase());
if (isWhitelisted) {
// This subreddit is whitelisted.
return true;
}
const cached = await Session.get(`isNightmodeCompatible.${subreddit.toLowerCase()}`);
if (cached !== undefined) {
// update the cache for next pageload
updateCache(subreddit);
return cached;
}
return updateCache(subreddit);
async function updateCache(subreddit) {
await Init.bodyReady;
// Check the sidebar for a link [](#/RES_SR_Config/NightModeCompatible) that indicates the sub is night mode compatible.
const isCompatible = !!document.querySelector('.side a[href="#/RES_SR_Config/NightModeCompatible"]');
Session.set(`isNightmodeCompatible.${subreddit.toLowerCase()}`, isCompatible);
return isCompatible;
}
}
export async function toggledSubredditStyle(toggledOn: boolean): Promise<void> {
const currSub = currentSubreddit();
if (!isNightModeOn() || !currSub) {
// nightmode is off or not in a subreddit, subreddit style toggling is irrelevant
return;
}
const subreddit = currSub.toLowerCase();
const whitelist = module.options.subredditStylesWhitelist.value.split(',');
if (toggledOn && !(await isNightmodeCompatible())) {
// toggled on and incompatible, add to whitelist
if (!whitelist.includes(subreddit)) {
whitelist.push(subreddit);
}
} else if (!toggledOn) {
// toggled off, remove from whitelist
_.pull(whitelist, subreddit);
}
Options.set(module, 'subredditStylesWhitelist', whitelist.join(','));
}
const handleAutomaticNightMode = _.once(async function check() {
if (module.options.automaticNightMode.value === 'none') {
return;
}
// Handle automatic night mode override
// Grab the override start time, if it exists
const nightModeOverrideStart = await nightmodeOverrideStorage.get();
const nightModeOverrideLength = HOUR * parseFloat(module.options.nightModeOverrideHours.value);
const nightModeOverrideEnd = (parseInt(nightModeOverrideStart, 10) || 0) + nightModeOverrideLength;
const isOverrideActive = (Date.now() <= nightModeOverrideEnd);
// Toggle is needed if night mode time is reached but night mode is
// disabled, or vice versa, *unless* override is active
const needsNightModeToggle = !isOverrideActive &&
(isNightModeOn() !== await isTimeForNightMode());
if (needsNightModeToggle) {
toggleNightMode();
}
// wait 5 minutes, then wait for the next frame (i.e. wait for the tab to be focused)
setTimeout(() => requestAnimationFrame(check), 5 * MINUTE);
});
function overrideNightMode() {
if (module.options.automaticNightMode.value === 'none') {
return;
}
// Temporarily disable automatic night mode by setting the start time
// of override
nightmodeOverrideStorage.set(Date.now());
}
/**
* Gets user's latitude and longitude using Geolocation API.
*/
function getGeolocation() {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(
position => resolve(position.coords),
reject
);
});
}
/**
* Determines night mode startind time and ending time based on user's peferences.
* If automatic mode is enabled, it will try to determine user's geolocation and use it
* to calculate sunrise and sunset times.
* If the user chose user-defined hours or the function will fail to determine user's location,
* nightModeStart and nightModeEnd values will be used.
*/
async function getNightModeTimes() {
switch (module.options.automaticNightMode.value) {
case 'automatic':
try {
const { latitude, longitude } = await getGeolocation();
const { sunrise, sunset } = getSunriseSunset(new Date(), latitude, longitude);
return { startingTime: sunset, endingTime: sunrise };
} catch (err) {
console.warn('Failed to init automatic night mode:', err);
switch (err.code) {
case err.PERMISSION_DENIED:
return Alert.open(i18n('nightModeAutomaticNightModeDenied', 'confirm'), { cancelable: true })
.then(() => {
// they clicked confirm, turn it off
Options.set(module, 'automaticNightMode', 'none');
return {
startingTime: new Date(0),
endingTime: new Date(0),
};
});
case err.POSITION_UNAVAILABLE:
case err.TIMEOUT:
case err.UNKNOWN_ERROR:
default:
throw err;
}
}
case 'user':
return {
startingTime: timeStringToDate(module.options.nightModeStart.value),
endingTime: timeStringToDate(module.options.nightModeEnd.value),
};
default:
throw new Error(`Invalid automaticNightMode value: ${module.options.automaticNightMode.value}`);
}
}
async function isTimeForNightMode() {
const currentTime = new Date();
const { startingTime, endingTime } = await getNightModeTimes();
if (startingTime <= endingTime) {
// e.g. enabled between 6am (600) and 8pm (2000)
return (startingTime <= currentTime) && (currentTime < endingTime);
} else {
// e.g. enabled between 8pm (2000) and 6am (600)
return (startingTime <= currentTime) || (currentTime < endingTime);
}
}
/**
* Converts a string of form "12:30" to the current date at that time.
*/
function timeStringToDate(timeString) {
const [hour, minute] = timeString.split(':').map(s => parseInt(s, 10));
const date = new Date();
date.setHours(hour, minute, 0 /* s */, 0 /* ms */);
return date;
}
let $nightSwitch;
function createNightSwitch() {
$nightSwitch = $('<div>', {
text: i18n('nightModeToggleText'),
title: i18n('nightModeToggleTitle'),
});
const toggle = CreateElement.toggleButton(
undefined,
'nightSwitchToggle',
isNightModeOn(),
'☽',
'☀'
);
$(toggle).appendTo($nightSwitch);
Menu.addMenuItem($nightSwitch, userToggledNightMode);
}
function updateNightSwitch(toggle) {
if (!$nightSwitch) return;
$nightSwitch.find('.toggleButton').toggleClass('enabled', toggle);
}
function userToggledNightMode(e) {
if (e) {
e.preventDefault();
}
toggleNightMode();
overrideNightMode();
}
function toggleNightMode() {
if (isNightModeOn()) {
disableNightMode();
} else {
enableNightMode();
}
StyleTweaks.toggleSubredditStyleIfNecessary();
}
const className = () => {
switch (appType()) {
case 'r2':
return 'res-nightmode';
case 'd2x':
return 'res-d2x-nightmode';
default:
throw new Error(`Impossible appType: ${appType()}`);
}
};
const addNightmodeClass = () => BodyClasses.add(className());
const removeNightmodeClass = () => BodyClasses.remove(className());
const enableNightMode = multicast(() => {
Options.set(module, 'nightModeOn', true);
addNightmodeClass();
updateNightSwitch(true);
}, { name: 'enableNightMode' });
const disableNightMode = multicast(() => {
Options.set(module, 'nightModeOn', false);
removeNightmodeClass();
updateNightSwitch(false);
}, { name: 'disableNightMode' });