forked from darkreader/darkreader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdynamic-theme.ts
More file actions
79 lines (69 loc) · 2.5 KB
/
Copy pathdynamic-theme.ts
File metadata and controls
79 lines (69 loc) · 2.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
import {formatSitesFixesConfig} from './utils/format';
import {parseSitesFixesConfig} from './utils/parse';
import {parseArray, formatArray} from '../utils/text';
import {compareURLPatterns, isURLInList} from '../utils/url';
import {DynamicThemeFix} from '../definitions';
const dynamicThemeFixesCommands = {
'INVERT': 'invert',
'CSS': 'css',
};
export function parseDynamicThemeFixes(text: string) {
return parseSitesFixesConfig<DynamicThemeFix>(text, {
commands: Object.keys(dynamicThemeFixesCommands),
getCommandPropName: (command) => dynamicThemeFixesCommands[command] || null,
parseCommandValue: (command, value) => {
if (command === 'CSS') {
return value.trim();
}
return parseArray(value);
},
});
}
export function formatDynamicThemeFixes(dynamicThemeFixes: DynamicThemeFix[]) {
const fixes = dynamicThemeFixes.slice().sort((a, b) => compareURLPatterns(a.url[0], b.url[0]));
return formatSitesFixesConfig(fixes, {
props: Object.values(dynamicThemeFixesCommands),
getPropCommandName: (prop) => Object.entries(dynamicThemeFixesCommands).find(([, p]) => p === prop)[0],
formatPropValue: (prop, value) => {
if (prop === 'css') {
return value.trim();
}
return formatArray(value).trim();
},
shouldIgnoreProp: (prop, value) => {
if (prop === 'css') {
return !value;
}
return !(Array.isArray(value) && value.length > 0);
},
});
}
export function getDynamicThemeFixesFor(url: string, frameURL: string, fixes: DynamicThemeFix[]) {
if (fixes.length === 0 || fixes[0].url[0] !== '*') {
return null;
}
const common = {
url: fixes[0].url,
invert: fixes[0].invert || [],
css: fixes[0].css || [],
};
const sortedBySpecificity = fixes
.slice(1)
.map((theme) => {
return {
specificity: isURLInList(frameURL || url, theme.url) ? theme.url[0].length : 0,
theme
};
})
.filter(({specificity}) => specificity > 0)
.sort((a, b) => b.specificity - a.specificity);
if (sortedBySpecificity.length === 0) {
return common;
}
const match = sortedBySpecificity[0].theme;
return {
url: match.url,
invert: common.invert.concat(match.invert || []),
css: [common.css, match.css].filter((s) => s).join('\n'),
};
}