-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.tsx
230 lines (209 loc) · 8.05 KB
/
index.tsx
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
/*
* Vencord, a Discord client mod
* Copyright (c) 2024 Vendicated and contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
import "./styles.css";
import ErrorBoundary from "@components/ErrorBoundary";
import definePlugin, { StartAt } from "@utils/types";
import { React } from "@webpack/common";
import type { ReactElement } from "react";
import { BlockDisplayType, ColorType, regex, RenderType, replaceRegexp, settings } from "./constants";
interface ParsedColorInfo {
type: "color";
color: string;
colorType: ColorType;
text: string;
}
const requiredFirstCharacters = ["r", "h", "#"].flatMap(v => [v, v.toUpperCase()]);
export default definePlugin({
authors: [{
id: 279266228151779329n,
name: "Hen",
}],
name: "MessageColors",
description: "Displays color codes like #FF0042 inside of messages",
settings,
patches: [
// Create a new markdown rule, so it parses just like any other features
// Like bolding, spoilers, mentions, etc
{
find: "roleMention:{order:",
group: true,
replacement: {
match: /roleMention:\{order:(\i\.\i\.order)/,
replace: "color:$self.getColor($1),$&"
}
},
// Changes text md rule regex, so it stops right before hsl( | rgb(
// Without it discord will try to pass a string without those to color rule
{
find: ".defaultRules.text,match:",
group: true,
replacement: {
// $)/)
match: /\$\)\//,
// hsl(|rgb(|$&
replace: requiredFirstCharacters.join("|") + "|$&"
}
},
{
find: "parseInlineCodeChildContent:",
replacement: {
match: /parseInlineCodeChildContent:/,
replace: "isInsideOfLink:true,$&"
}
},
// Discord just requires it to be here
// Or it explodes (bad)
{
find: "Unknown markdown rule:",
group: true,
replacement: {
match: /roleMention:{type:/,
replace: "color:{type:\"inlineObject\"},$&",
}
},
],
start() {
const amount = settings.store.enableShortHexCodes ? "{1,2}" : "{2}";
regex.push({
reg: new RegExp("#(?:[0-9a-fA-F]{3})" + amount, "g"),
type: ColorType.HEX
});
},
// Needed to load all regex before patching
startAt: StartAt.Init,
getColor(order: number) {
const source = regex.map(r => r.reg.source).join("|");
const matchAllRegExp = new RegExp(`^(${source})`, "i");
return {
order,
// Don't even try to match if the message chunk doesn't start with...
requiredFirstCharacters,
// Match -> Parse -> React
// Result of previous action is dropped as a first argument of the next one
match(content: string) {
return matchAllRegExp.exec(content);
},
parse(matchedContent: RegExpExecArray, _, parseProps: Record<string, any>):
ParsedColorInfo | ({ type: "text", content: string; }) {
// This check makes sure that it doesn't try to parse color
// When typing/editing message
//
// Discord doesn't know how to deal with color and crashes
if (!parseProps.messageId || parseProps.isInsideOfLink) return {
type: "text",
content: matchedContent[0]
};
const content = matchedContent[0];
try {
const type = getColorType(content);
return {
type: "color",
colorType: type,
color: parseColor(content, type),
text: content
};
} catch (e) {
console.error(e);
return {
type: "text",
content: matchedContent[0]
};
}
},
react: ErrorBoundary.wrap(({ text, colorType, color }: ParsedColorInfo) => {
if (settings.store.renderType === RenderType.FOREGROUND) {
return <span style={{ color: color }}>{text}</span>;
}
const styles = {
"--color": color
} as React.CSSProperties;
if (settings.store.renderType === RenderType.BACKGROUND) {
const isDark = isColorDark(color, colorType);
const className = `vc-color-bg ${!isDark ? "vc-color-bg-invert" : ""}`;
return <span className={className} style={styles}>{text}</span>;
}
// Only block display left
const margin = "2px";
switch (settings.store.blockView) {
case BlockDisplayType.LEFT:
styles.marginRight = margin;
return <><span className="vc-color-block" style={styles} />{text}</>;
case BlockDisplayType.RIGHT:
styles.marginLeft = margin;
return <>{text}<span className="vc-color-block" style={styles} /></>;
case BlockDisplayType.BOTH:
styles.marginLeft = margin;
styles.marginRight = margin;
return <>
<span className="vc-color-block" style={styles} />
{text}
<span className="vc-color-block" style={styles} />
</>;
}
}, {
fallback: data => {
const child = data.children as ReactElement<any>;
return <>{child.props?.text}</>;
}
})
};
}
});
// https://en.wikipedia.org/wiki/Relative_luminance
const calcRGBLightness = (r: number, g: number, b: number) => {
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
};
const isColorDark = (color: string, type: ColorType): boolean => {
const border = 115;
switch (type) {
case ColorType.RGBA:
case ColorType.RGB: {
const match = color.match(/\d+/g)!;
const lightness = calcRGBLightness(+match[0], +match[1], +match[2]);
return lightness < border;
}
case ColorType.HEX: {
color = color.substring(1);
if (color.length === 3) {
color = color.split("").flatMap(v => [v, v]).join("");
}
const rgb = parseInt(color, 16);
const r = (rgb >> 16) & 0xff;
const g = (rgb >> 8) & 0xff;
const b = (rgb >> 0) & 0xff;
const lightness = calcRGBLightness(r, g, b);
return lightness < border;
}
case ColorType.HSL: {
const match = color.match(/\d+/g)!;
const lightness = +match[2];
return lightness < (border / 255 * 100);
}
}
};
const getColorType = (color: string): ColorType => {
color = color.toLowerCase().trim();
if (color.startsWith("#")) return ColorType.HEX;
if (color.startsWith("hsl")) return ColorType.HSL;
if (color.startsWith("rgba")) return ColorType.RGBA;
if (color.startsWith("rgb")) return ColorType.RGB;
throw new Error(`Can't resolve color type of ${color}`);
};
function parseColor(str: string, type: ColorType): string {
str = str.toLowerCase().trim().replaceAll(/(\s|,)+/g, " ");
switch (type) {
case ColorType.RGB:
return str;
case ColorType.RGBA:
if (!str.includes("/"))
return str.replaceAll(replaceRegexp(/\f(?=\s*?\))/.source), "/$&");
return str;
case ColorType.HEX:
return str[0] === "#" ? str : `#${str}`;
case ColorType.HSL:
return str.replace("°", "");
}
}