1use std::fmt::{self, Display};
2
3use azalea_codec::Codec;
4
5use crate::{
6 FormattedText,
7 component::{base::BaseComponent, text::TextComponent},
8};
9
10#[derive(Clone, Debug, PartialEq, Codec)]
12pub struct TranslatableComponent {
13 #[codec(rename = "translate")]
14 pub key: String,
15 #[codec(optional)]
16 pub fallback: Option<String>,
17 #[codec(optional, rename = "with")]
18 pub args: Vec<PrimitiveOrComponent>,
19 #[codec(flatten)]
20 pub base: BaseComponent,
21}
22
23#[derive(Clone, Debug, PartialEq, Codec)]
24pub enum PrimitiveOrComponent {
25 Short(i16),
26 Integer(i32),
27 Long(i64),
28 Float(f32),
29 Double(f64),
30 Boolean(bool),
31 String(String),
32 FormattedText(FormattedText),
33}
34
35impl TranslatableComponent {
36 pub fn new(key: String, args: Vec<PrimitiveOrComponent>) -> Self {
37 Self {
38 base: BaseComponent::new(),
39 key,
40 fallback: None,
41 args,
42 }
43 }
44
45 pub fn with_fallback(
46 key: String,
47 fallback: Option<String>,
48 args: Vec<PrimitiveOrComponent>,
49 ) -> Self {
50 Self {
51 base: BaseComponent::new(),
52 key,
53 fallback,
54 args,
55 }
56 }
57
58 pub fn into_text_component(self) -> Result<TextComponent, fmt::Error> {
61 let template = azalea_language::get(&self.key).unwrap_or_else(|| {
62 if let Some(fallback) = &self.fallback {
63 fallback.as_str()
64 } else {
65 &self.key
66 }
67 });
68 let mut matched = 0;
71
72 let mut built_text = String::new();
75 let mut components = Vec::new();
76
77 let mut chars = template.chars();
78 while let Some(char) = chars.next() {
79 if char != '%' {
80 built_text.push(char);
81 continue;
82 }
83
84 let mut chars_preview = chars.clone();
85 let Some(char_after) = chars_preview.next() else {
86 built_text.push('%');
87 break;
88 };
89 match char_after {
90 '%' => {
91 chars.next();
92
93 built_text.push('%');
94 }
95 's' => {
96 chars.next();
97
98 let arg_component = self
99 .args
100 .get(matched)
101 .cloned()
102 .unwrap_or_else(|| PrimitiveOrComponent::String("".to_owned()));
103
104 components.push(TextComponent::new(built_text.clone()));
105 built_text.clear();
106 components.push(TextComponent::from(arg_component));
107 matched += 1;
108 }
109 '0'..='9' if let Some(d) = char_after.to_digit(10) => {
110 chars.next();
111 let Some('$') = chars.next() else {
113 return Err(fmt::Error);
114 };
115 let Some('s') = chars.next() else {
116 return Err(fmt::Error);
117 };
118 built_text.push_str(
119 &self
120 .args
121 .get((d - 1) as usize)
122 .unwrap_or(&PrimitiveOrComponent::String("".to_owned()))
123 .to_string(),
124 );
125 }
126 _ => {
127 built_text.push('%');
128 }
129 }
130 }
131
132 components.push(TextComponent::new(built_text));
133
134 Ok(
135 TextComponent::empty_with_text_component_siblings(components)
136 .with_style(*self.base.style)
137 .with_additional_siblings(self.base.siblings),
138 )
139 }
140
141 #[doc(hidden)]
142 #[deprecated = "renamed to `to_text_component`"]
143 pub fn read(&self) -> Result<TextComponent, fmt::Error> {
144 Self::into_text_component(self.clone())
145 }
146}
147
148impl Display for TranslatableComponent {
149 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150 FormattedText::Translatable(self.clone()).fmt(f)
151 }
152}
153
154impl Display for PrimitiveOrComponent {
155 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
156 match self {
157 PrimitiveOrComponent::Boolean(value) => write!(f, "{value}"),
158 PrimitiveOrComponent::Short(value) => write!(f, "{value}"),
159 PrimitiveOrComponent::Integer(value) => write!(f, "{value}"),
160 PrimitiveOrComponent::Long(value) => write!(f, "{value}"),
161 PrimitiveOrComponent::Float(value) => write!(f, "{value}"),
162 PrimitiveOrComponent::Double(value) => write!(f, "{value}"),
163 PrimitiveOrComponent::String(value) => write!(f, "{value}"),
164 PrimitiveOrComponent::FormattedText(value) => write!(f, "{value}"),
165 }
166 }
167}
168
169impl From<PrimitiveOrComponent> for TextComponent {
170 fn from(soc: PrimitiveOrComponent) -> Self {
171 match soc {
172 PrimitiveOrComponent::String(value) => TextComponent::new(value),
173 PrimitiveOrComponent::Boolean(value) => TextComponent::new(value.to_string()),
174 PrimitiveOrComponent::Short(value) => TextComponent::new(value.to_string()),
175 PrimitiveOrComponent::Integer(value) => TextComponent::new(value.to_string()),
176 PrimitiveOrComponent::Long(value) => TextComponent::new(value.to_string()),
177 PrimitiveOrComponent::Float(value) => TextComponent::new(value.to_string()),
178 PrimitiveOrComponent::Double(value) => TextComponent::new(value.to_string()),
179 PrimitiveOrComponent::FormattedText(value) => TextComponent::new(value.to_string()),
180 }
181 }
182}
183impl From<&str> for TranslatableComponent {
184 fn from(s: &str) -> Self {
185 TranslatableComponent::new(s.to_owned(), vec![])
186 }
187}
188impl From<TranslatableComponent> for FormattedText {
189 fn from(c: TranslatableComponent) -> Self {
190 FormattedText::Translatable(c)
191 }
192}
193
194#[cfg(test)]
195mod tests {
196 use super::*;
197
198 #[test]
199 fn test_none() {
200 let c = TranslatableComponent::new("translation.test.none".to_owned(), vec![]);
201 assert_eq!(
202 c.into_text_component().unwrap().to_string(),
203 "Hello, world!".to_owned()
204 );
205 }
206 #[test]
207 fn test_complex() {
208 let c = TranslatableComponent::new(
209 "translation.test.complex".to_owned(),
210 vec![
211 PrimitiveOrComponent::String("a".to_owned()),
212 PrimitiveOrComponent::String("b".to_owned()),
213 PrimitiveOrComponent::String("c".to_owned()),
214 PrimitiveOrComponent::String("d".to_owned()),
215 ],
216 );
217 assert_eq!(
219 c.into_text_component().unwrap().to_string(),
220 "Prefix, ab again b and a lastly c and also a again!".to_owned()
221 );
222 }
223 #[test]
224 fn test_escape() {
225 let c = TranslatableComponent::new(
226 "translation.test.escape".to_owned(),
227 vec![
228 PrimitiveOrComponent::String("a".to_owned()),
229 PrimitiveOrComponent::String("b".to_owned()),
230 PrimitiveOrComponent::String("c".to_owned()),
231 PrimitiveOrComponent::String("d".to_owned()),
232 ],
233 );
234 assert_eq!(
235 c.into_text_component().unwrap().to_string(),
236 "%s %a %%s %%b".to_owned()
237 );
238 }
239 #[test]
240 fn test_invalid() {
241 let c = TranslatableComponent::new(
242 "translation.test.invalid".to_owned(),
243 vec![
244 PrimitiveOrComponent::String("a".to_owned()),
245 PrimitiveOrComponent::String("b".to_owned()),
246 PrimitiveOrComponent::String("c".to_owned()),
247 PrimitiveOrComponent::String("d".to_owned()),
248 ],
249 );
250 assert_eq!(c.to_string(), "hi %".to_owned());
251 }
252 #[test]
253 fn test_invalid2() {
254 let c = TranslatableComponent::new(
255 "translation.test.invalid2".to_owned(),
256 vec![
257 PrimitiveOrComponent::String("a".to_owned()),
258 PrimitiveOrComponent::String("b".to_owned()),
259 PrimitiveOrComponent::String("c".to_owned()),
260 PrimitiveOrComponent::String("d".to_owned()),
261 ],
262 );
263 assert_eq!(c.to_string(), "hi % s".to_owned());
264 }
265
266 #[test]
267 fn test_undefined() {
268 let c = TranslatableComponent::new(
269 "translation.test.undefined".to_owned(),
270 vec![PrimitiveOrComponent::String("a".to_owned())],
271 );
272 assert_eq!(c.to_string(), "translation.test.undefined".to_owned());
273 }
274
275 #[test]
276 fn test_undefined_with_fallback() {
277 let c = TranslatableComponent::with_fallback(
278 "translation.test.undefined".to_owned(),
279 Some("translation fallback: %s".to_owned()),
280 vec![PrimitiveOrComponent::String("a".to_owned())],
281 );
282 assert_eq!(c.to_string(), "translation fallback: a".to_owned());
283 }
284}