azalea_chat/component/
text.rs1use std::{
2 fmt::{self, Display},
3 mem,
4};
5
6use azalea_codec::Codec;
7
8use crate::{
9 FormattedText,
10 component::base::BaseComponent,
11 style::{ChatFormatting, Style, TextColor},
12};
13
14#[derive(Clone, Debug, Default, PartialEq)]
16pub struct TextComponent {
17 pub text: String,
18 pub base: BaseComponent,
19}
20
21#[derive(Clone, Debug, Default, PartialEq, Codec)]
22struct TextComponentCodec {
23 text: String,
24 #[codec(flatten)]
25 base: BaseComponent,
26}
27impl<O: azalea_codec::Ops> Codec<O> for TextComponent {
28 fn codec_read(ops: &O) -> azalea_codec::error::ReadResult<Self> {
29 let r = if let Ok(text) = String::codec_read(ops) {
30 TextComponentCodec {
31 text,
32 base: Default::default(),
33 }
34 } else {
35 TextComponentCodec::codec_read(ops)?
36 };
37
38 let legacy_formatted = Self::new(r.text);
41
42 if legacy_formatted.base.is_default() {
43 return Ok(legacy_formatted.with_base(r.base));
44 }
45
46 let mut siblings = vec![legacy_formatted.into()];
51 siblings.extend(r.base.siblings);
52
53 Ok(TextComponent::empty_with_siblings(siblings).with_style(*r.base.style))
54 }
55
56 fn codec_write(&self) -> azalea_codec::error::WriteResult<O> {
57 if self.base.is_default() {
58 return self.text.codec_write();
59 }
60
61 TextComponentCodec {
62 text: self.text.clone(),
63 base: self.base.clone(),
64 }
65 .codec_write()
66 }
67}
68
69pub const LEGACY_FORMATTING_CODE_SYMBOL: char = '§';
70
71pub fn legacy_color_code_to_text_component(legacy_color_code: &str) -> TextComponent {
75 if legacy_color_code.is_empty() {
76 return TextComponent::new("");
77 }
78
79 let mut sections: Vec<TextComponent> = Vec::with_capacity(1);
81
82 let mut components: Vec<TextComponent> = Vec::with_capacity(1);
83 let mut cur_component = TextComponent::new("");
88
89 let mut i = 0;
92 while i < legacy_color_code.chars().count() {
93 if legacy_color_code.chars().nth(i).unwrap() == LEGACY_FORMATTING_CODE_SYMBOL {
94 let formatting_code = legacy_color_code.chars().nth(i + 1);
95 let Some(formatting_code) = formatting_code else {
96 i += 1;
97 continue;
98 };
99 if formatting_code == '#' {
100 let color = legacy_color_code
101 .chars()
102 .skip(i + 1)
103 .take(7)
105 .collect::<String>();
106
107 if !cur_component.text.is_empty() {
108 components.push(cur_component.clone());
110 cur_component.text = "".to_owned();
111 };
112 cur_component.base.style.color = TextColor::parse(&color);
113
114 i += 6;
115 } else if let Some(formatter) = ChatFormatting::from_code(formatting_code) {
116 if !cur_component.text.is_empty() {
117 components.push(cur_component.clone());
119 cur_component.text = "".to_owned();
120 }
121 if formatter == ChatFormatting::Reset {
122 sections.push(TextComponent::empty_with_text_component_siblings(
123 mem::take(&mut components),
124 ));
125 }
126 cur_component.base.style.apply_formatting(&formatter);
127 }
128 i += 1;
129 } else {
130 cur_component
131 .text
132 .push(legacy_color_code.chars().nth(i).unwrap());
133 };
134 i += 1;
135 }
136
137 components.push(cur_component);
138 sections.push(TextComponent::empty_with_text_component_siblings(
139 components,
140 ));
141
142 if sections.len() == 1 {
143 return sections.into_iter().next().unwrap();
144 }
145
146 TextComponent::empty_with_text_component_siblings(sections)
147}
148
149impl TextComponent {
150 pub fn new(text: impl Into<String>) -> Self {
151 let text = text.into();
152 if text.contains(LEGACY_FORMATTING_CODE_SYMBOL) {
154 legacy_color_code_to_text_component(&text)
155 } else {
156 Self {
157 base: BaseComponent::new(),
158 text,
159 }
160 }
161 }
162 pub fn empty_with_siblings(siblings: Vec<FormattedText>) -> Self {
163 Self {
164 text: "".into(),
165 base: BaseComponent {
166 siblings,
167 ..Default::default()
168 },
169 }
170 }
171 pub fn empty_with_text_component_siblings(siblings: Vec<TextComponent>) -> Self {
172 Self::empty_with_siblings(siblings.into_iter().map(|t| t.into()).collect())
173 }
174
175 pub fn into_formatted_text(self) -> FormattedText {
177 FormattedText::Text(self)
178 }
179
180 pub fn with_base(mut self, base: BaseComponent) -> Self {
181 self.base = base;
182 self
183 }
184 pub fn with_style(mut self, style: Style) -> Self {
185 *self.base.style = style;
186 self
187 }
188 pub fn with_additional_siblings(
189 mut self,
190 siblings: impl IntoIterator<Item = FormattedText>,
191 ) -> Self {
192 self.base.siblings.extend(siblings);
193 self
194 }
195}
196
197impl Display for TextComponent {
198 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199 FormattedText::Text(self.clone()).fmt(f)
200 }
201}
202
203impl From<TextComponent> for FormattedText {
204 fn from(c: TextComponent) -> Self {
205 FormattedText::Text(c)
206 }
207}
208
209#[cfg(test)]
210mod tests {
211 use super::*;
212 use crate::style::Ansi;
213
214 #[test]
215 fn test_hypixel_motd_ansi() {
216 let component =
217 TextComponent::new("§aHypixel Network §c[1.8-1.18]\n§b§lHAPPY HOLIDAYS".to_owned())
218 .into_formatted_text();
219 assert_eq!(
220 component.to_ansi(),
221 format!(
222 "{GREEN}Hypixel Network {RED}[1.8-1.18]\n{BOLD}{AQUA}HAPPY HOLIDAYS{RESET}",
223 GREEN = Ansi::rgb(ChatFormatting::Green.color().unwrap()),
224 RED = Ansi::rgb(ChatFormatting::Red.color().unwrap()),
225 AQUA = Ansi::rgb(ChatFormatting::Aqua.color().unwrap()),
226 BOLD = Ansi::BOLD,
227 RESET = Ansi::RESET
228 )
229 );
230 }
231
232 #[test]
233 fn test_hypixel_motd_html() {
234 let component =
235 TextComponent::new("§aHypixel Network §c[1.8-1.18]\n§b§lHAPPY HOLIDAYS".to_owned())
236 .into_formatted_text();
237
238 assert_eq!(
239 component.to_html(),
240 format!(
241 "{GREEN}Hypixel Network {END_SPAN}{RED}[1.8-1.18]<br>{END_SPAN}{BOLD_AQUA}HAPPY HOLIDAYS{END_SPAN}",
242 END_SPAN = "</span>",
243 GREEN = "<span style=\"color:#55FF55;\">",
244 RED = "<span style=\"color:#FF5555;\">",
245 BOLD_AQUA = "<span style=\"color:#55FFFF;font-weight:bold;\">",
246 )
247 );
248 }
249
250 #[test]
251 fn test_xss_html() {
252 let component = TextComponent::new("§a<b>&\n§b</b>".to_owned()).into_formatted_text();
253
254 assert_eq!(
255 component.to_html(),
256 format!(
257 "{GREEN}<b>&<br>{END_SPAN}{AQUA}</b>{END_SPAN}",
258 END_SPAN = "</span>",
259 GREEN = "<span style=\"color:#55FF55;\">",
260 AQUA = "<span style=\"color:#55FFFF;\">",
261 )
262 );
263 }
264
265 #[test]
266 fn test_legacy_color_code_to_component() {
267 let component =
268 TextComponent::new("§lHello §r§1w§2o§3r§4l§5d".to_owned()).into_formatted_text();
269
270 let attempt = component.to_ansi();
271 let solution = format!(
272 "{BOLD}{WHITE}Hello {RESET}{DARK_BLUE}w{DARK_GREEN}o{DARK_AQUA}r{DARK_RED}l{DARK_PURPLE}d{RESET}",
273 BOLD = Ansi::BOLD,
274 WHITE = Ansi::rgb(ChatFormatting::White.color().unwrap()),
275 RESET = Ansi::RESET,
276 DARK_BLUE = Ansi::rgb(ChatFormatting::DarkBlue.color().unwrap()),
277 DARK_GREEN = Ansi::rgb(ChatFormatting::DarkGreen.color().unwrap()),
278 DARK_AQUA = Ansi::rgb(ChatFormatting::DarkAqua.color().unwrap()),
279 DARK_RED = Ansi::rgb(ChatFormatting::DarkRed.color().unwrap()),
280 DARK_PURPLE = Ansi::rgb(ChatFormatting::DarkPurple.color().unwrap())
281 );
282
283 assert_eq!(attempt, solution);
284 }
285
286 #[test]
287 fn test_legacy_color_code_with_rgb() {
288 let component =
289 TextComponent::new("§#Ff0000This is a test message".to_owned()).into_formatted_text();
290 assert_eq!(
291 component.to_ansi(),
292 format!(
293 "{RED}This is a test message{RESET}",
294 RED = Ansi::rgb(0xff0000),
295 RESET = Ansi::RESET
296 )
297 );
298 }
299
300 #[test]
301 fn test_serialize_to_json() {
302 let component = TextComponent::new("Hello §aworld".to_owned()).into_formatted_text();
303
304 let value: serde_json::Value = component.codec_write().unwrap();
305
306 assert_eq!(
307 serde_json::to_string(&value).unwrap(),
308 "{\"text\":\"\",\"extra\":[\"Hello \",{\"text\":\"world\",\"color\":\"#55FF55\"}]}"
309 );
310 }
311}