diff options
| author | Tert0 <tert0byte@gmail.com> | 2025-09-15 06:58:00 +0200 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2025-09-14 23:58:00 -0500 |
| commit | 1a42c08030c865948e9e9b6dc8a1f4e38550063a (patch) | |
| tree | c5342b8e27edc4536d0f4a19628be48de9b15651 /azalea-chat/src/translatable_component.rs | |
| parent | bcefd0213db05b4c29c82a1031f4d6e838e1fc1f (diff) | |
| download | azalea-drasl-1a42c08030c865948e9e9b6dc8a1f4e38550063a.tar.xz | |
implement translation fallback (#244)
Diffstat (limited to 'azalea-chat/src/translatable_component.rs')
| -rw-r--r-- | azalea-chat/src/translatable_component.rs | 48 |
1 files changed, 47 insertions, 1 deletions
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<String>, pub args: Vec<StringOrComponent>, } @@ -97,13 +98,33 @@ impl TranslatableComponent { Self { base: BaseComponent::new(), key, + fallback: None, + args, + } + } + + pub fn with_fallback( + key: String, + fallback: Option<String>, + args: Vec<StringOrComponent>, + ) -> Self { + Self { + base: BaseComponent::new(), + key, + fallback, args, } } /// Convert the key and args to a FormattedText. pub fn read(&self) -> Result<TextComponent, fmt::Error> { - 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() + ); + } } |
