forked from codesandbox/codesandbox-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdefine-theme.js
More file actions
107 lines (86 loc) · 2.23 KB
/
define-theme.js
File metadata and controls
107 lines (86 loc) · 2.23 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
import Color from 'color';
import { notificationState } from '@codesandbox/common/lib/utils/notifications';
import { NotificationStatus } from '@codesandbox/notifications';
const sanitizeColor = color => {
if (!color) {
return color;
}
if (/#......$/.test(color) || /#........$/.test(color)) {
return color;
}
try {
return new Color(color).hexString();
} catch (e) {
return '#FF0000';
}
};
const colorsAllowed = ({ foreground, background }) => {
if (foreground === 'inherit' || background === 'inherit') {
return false;
}
return true;
};
const getTheme = theme => {
const { tokenColors = [], colors = {} } = theme;
const rules = tokenColors
.filter(t => t.settings && t.scope && colorsAllowed(t.settings))
.reduce((acc, token) => {
const settings = {
foreground: sanitizeColor(token.settings.foreground),
background: sanitizeColor(token.settings.background),
fontStyle: token.settings.fontStyle,
};
const scope =
typeof token.scope === 'string'
? token.scope.split(',').map(a => a.trim())
: token.scope;
scope.map(s =>
acc.push({
token: s,
...settings,
})
);
return acc;
}, []);
const newColors = colors;
Object.keys(colors).forEach(c => {
if (newColors[c]) return c;
delete newColors[c];
return c;
});
return {
colors: newColors,
rules,
type: theme.type,
};
};
const getBase = type => {
if (type === 'dark') {
return 'vs-dark';
}
if (type === 'hc') {
return 'hc-black';
}
return 'vs';
};
const defineTheme = (monaco, theme) => {
if (theme && monaco.editor.defineTheme) {
const transformedTheme = getTheme(theme);
try {
monaco.editor.defineTheme('CodeSandbox', {
base: getBase(transformedTheme.type),
inherit: true,
colors: transformedTheme.colors,
rules: transformedTheme.rules,
});
monaco.editor.setTheme('CodeSandbox');
} catch (e) {
console.error(e);
notificationState.addNotification({
message: `Problem initializing template in editor: ${e.message}`,
status: NotificationStatus.ERROR,
});
}
}
};
export default defineTheme;