From 1a42c08030c865948e9e9b6dc8a1f4e38550063a Mon Sep 17 00:00:00 2001 From: Tert0 Date: Mon, 15 Sep 2025 06:58:00 +0200 Subject: implement translation fallback (#244) --- azalea-chat/src/translatable_component.rs | 48 ++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) (limited to 'azalea-chat/src/translatable_component.rs') diff --git a/azalea-chat/src/translatable_component.rs b/azalea-chat/src/translatable_component.rs index 10c502a8..28700366 100644 --- a/azalea-chat/src/translatable_component.rs +++ b/azalea-chat/src/translatable_component.rs @@ -28,6 +28,7 @@ impl simdnbt::ToNbtTag for StringOrComponent { pub struct TranslatableComponent { pub base: BaseComponent, pub key: String, + pub fallback: Option, pub args: Vec, } @@ -97,13 +98,33 @@ impl TranslatableComponent { Self { base: BaseComponent::new(), key, + fallback: None, + args, + } + } + + pub fn with_fallback( + key: String, + fallback: Option, + args: Vec, + ) -> Self { + Self { + base: BaseComponent::new(), + key, + fallback, args, } } /// Convert the key and args to a FormattedText. pub fn read(&self) -> Result { - let template = azalea_language::get(&self.key).unwrap_or(&self.key); + let template = azalea_language::get(&self.key).unwrap_or_else(|| { + if let Some(fallback) = &self.fallback { + fallback.as_str() + } else { + &self.key + } + }); // decode the % things let mut i = 0; @@ -293,4 +314,29 @@ mod tests { ); assert_eq!(c.read().unwrap().to_string(), "hi % s".to_string()); } + + #[test] + fn test_undefined() { + let c = TranslatableComponent::new( + "translation.test.undefined".to_string(), + vec![StringOrComponent::String("a".to_string())], + ); + assert_eq!( + c.read().unwrap().to_string(), + "translation.test.undefined".to_string() + ); + } + + #[test] + fn test_undefined_with_fallback() { + let c = TranslatableComponent::with_fallback( + "translation.test.undefined".to_string(), + Some("translation fallback: %s".to_string()), + vec![StringOrComponent::String("a".to_string())], + ); + assert_eq!( + c.read().unwrap().to_string(), + "translation fallback: a".to_string() + ); + } } -- cgit v1.2.3