Skip to main content

azalea_chat/component/
mod.rs

1pub mod base;
2pub mod common;
3pub mod keybind;
4pub mod nbt;
5pub mod object;
6pub mod score;
7pub mod selector;
8pub mod text;
9pub mod translatable;
10
11#[cfg(all(feature = "azalea-buf", feature = "simdnbt"))]
12use std::io::{self, Cursor, Write};
13use std::{
14    fmt::{self, Display},
15    sync::LazyLock,
16};
17
18#[cfg(all(feature = "azalea-buf", feature = "simdnbt"))]
19use azalea_buf::{AzBuf, BufReadError};
20use azalea_codec::Codec;
21#[cfg(all(feature = "azalea-buf", feature = "simdnbt"))]
22use simdnbt::owned::NbtTag;
23
24use crate::{
25    component::{
26        base::BaseComponent, keybind::KeybindComponent, nbt::NbtComponent, object::ObjectComponent,
27        score::ScoreComponent, selector::SelectorComponent, text::TextComponent,
28        translatable::TranslatableComponent,
29    },
30    style::{ChatFormatting, Style},
31};
32
33/// A chat component, basically anything you can see in chat.
34#[derive(Clone, Debug, PartialEq)]
35pub enum FormattedText {
36    Text(TextComponent),
37    Translatable(TranslatableComponent),
38    Keybind(KeybindComponent),
39    Score(ScoreComponent),
40    Selector(SelectorComponent),
41    Nbt(NbtComponent),
42    Object(ObjectComponent),
43}
44azalea_codec::impl_codec_from!(FormattedText, FormattedTextCodec, struct IncompleteFormattedText);
45
46#[derive(Codec)]
47enum FormattedTextCodec {
48    List(#[codec(with = CompactListCodec::<_>)] Vec<FormattedTextCodec>),
49    Text(TextComponent),
50    Translatable(TranslatableComponent),
51    Keybind(KeybindComponent),
52    Score(ScoreComponent),
53    Selector(SelectorComponent),
54    Nbt(NbtComponent),
55    Object(ObjectComponent),
56}
57impl From<FormattedTextCodec> for FormattedText {
58    fn from(c: FormattedTextCodec) -> Self {
59        type C = FormattedTextCodec;
60        match c {
61            C::List(c) => {
62                let num_components = c.len();
63                let mut iter = c.into_iter().map(|c| c.into());
64                let Some(first) = iter.next() else {
65                    // an empty array is parsed as an empty string component
66                    return Self::default();
67                };
68                if num_components == 1 {
69                    // putting a single component in a list just unwraps it
70                    return first;
71                }
72
73                let style = first.get_base().style.clone();
74                // put them all as siblings of an empty component, but copying
75                // the style of the first component
76                TextComponent::empty_with_siblings(vec![first])
77                    .with_additional_siblings(iter)
78                    .with_style(*style)
79                    .into()
80            }
81            C::Text(c) => Self::Text(c),
82            C::Translatable(c) => Self::Translatable(c),
83            C::Keybind(c) => Self::Keybind(c),
84            C::Score(c) => Self::Score(c),
85            C::Selector(c) => Self::Selector(c),
86            C::Nbt(c) => Self::Nbt(c),
87            C::Object(c) => Self::Object(c),
88        }
89    }
90}
91impl From<FormattedText> for FormattedTextCodec {
92    fn from(c: FormattedText) -> Self {
93        type C = FormattedText;
94        match c {
95            C::Text(c) => Self::Text(c),
96            C::Translatable(c) => Self::Translatable(c),
97            C::Keybind(c) => Self::Keybind(c),
98            C::Score(c) => Self::Score(c),
99            C::Selector(c) => Self::Selector(c),
100            C::Nbt(c) => Self::Nbt(c),
101            C::Object(c) => Self::Object(c),
102        }
103    }
104}
105
106pub static DEFAULT_STYLE: LazyLock<Style> = LazyLock::new(|| Style {
107    color: Some(ChatFormatting::White.try_into().unwrap()),
108    ..Style::default()
109});
110
111/// A chat component
112impl FormattedText {
113    pub fn get_base_mut(&mut self) -> &mut BaseComponent {
114        match self {
115            Self::Text(c) => &mut c.base,
116            Self::Translatable(c) => &mut c.base,
117            Self::Keybind(c) => &mut c.base,
118            Self::Score(c) => &mut c.base,
119            Self::Selector(c) => &mut c.base,
120            Self::Nbt(c) => &mut c.base,
121            Self::Object(c) => &mut c.base,
122        }
123    }
124
125    pub fn get_base(&self) -> &BaseComponent {
126        match self {
127            Self::Text(c) => &c.base,
128            Self::Translatable(c) => &c.base,
129            Self::Keybind(c) => &c.base,
130            Self::Score(c) => &c.base,
131            Self::Selector(c) => &c.base,
132            Self::Nbt(c) => &c.base,
133            Self::Object(c) => &c.base,
134        }
135    }
136
137    /// Add a component as a sibling of this one.
138    pub fn append(&mut self, sibling: FormattedText) {
139        self.extend([sibling]);
140    }
141    pub fn extend(&mut self, siblings: impl IntoIterator<Item = FormattedText>) {
142        self.get_base_mut().siblings.extend(siblings);
143    }
144
145    /// Render all components into a single `String`, using your custom
146    /// closures to drive styling, text transformation, and final cleanup.
147    ///
148    /// # Type parameters
149    ///
150    /// - `F`: `(running, component, default) -> (prefix, suffix)` for
151    ///   per-component styling
152    /// - `S`: `&str -> String` for text tweaks (escaping, mapping, etc.)
153    /// - `C`: `&final_running_style -> String` for any trailing cleanup
154    ///
155    /// # Arguments
156    ///
157    /// - `style_formatter`: how to open/close each component's style
158    /// - `text_formatter`: how to turn raw text into output text
159    /// - `cleanup_formatter`: emit after all components (e.g. reset codes)
160    /// - `default_style`: where to reset when a component's `reset` is true
161    ///
162    /// # Example
163    ///
164    /// ```rust
165    /// use azalea_chat::{FormattedText, DEFAULT_STYLE};
166    /// use serde::de::Deserialize;
167    ///
168    /// let component = FormattedText::deserialize(&serde_json::json!({
169    ///    "text": "Hello, world!",
170    ///    "color": "red",
171    /// })).unwrap();
172    ///
173    /// let ansi = component.to_custom_format(
174    ///     |running, new| (running.compare_ansi(new), "".to_owned()),
175    ///     |text| text.to_string(),
176    ///     |style| {
177    ///         if !style.is_empty() {
178    ///             "\u{1b}[m".to_owned()
179    ///         } else {
180    ///             "".to_owned()
181    ///         }
182    ///     },
183    ///     &DEFAULT_STYLE,
184    /// );
185    /// println!("{ansi}");
186    /// ```
187    pub fn to_custom_format<F, S, C>(
188        &self,
189        mut style_formatter: F,
190        mut text_formatter: S,
191        mut cleanup_formatter: C,
192        default_style: &Style,
193    ) -> String
194    where
195        F: FnMut(&Style, &Style) -> (String, String),
196        S: FnMut(&str) -> String,
197        C: FnMut(&Style) -> String,
198    {
199        let mut output = String::new();
200
201        let mut running_style = Style::default();
202        self.clone().into_custom_format_recursive(
203            &mut output,
204            &mut style_formatter,
205            &mut text_formatter,
206            &default_style.clone(),
207            &mut running_style,
208        );
209        output.push_str(&cleanup_formatter(&running_style));
210
211        output
212    }
213
214    fn into_custom_format_recursive<F, S>(
215        self,
216        output: &mut String,
217        style_formatter: &mut F,
218        text_formatter: &mut S,
219        parent_style: &Style,
220        last_style: &mut Style,
221    ) where
222        F: FnMut(&Style, &Style) -> (String, String),
223        S: FnMut(&str) -> String,
224    {
225        let mut expected_style = parent_style.clone();
226
227        // convert it into a TextComponent
228        let c = match self {
229            FormattedText::Text(c) => c,
230            FormattedText::Translatable(c) => c.into_text_component().unwrap_or_default(),
231            FormattedText::Keybind(c) => c.into_text_component(),
232            FormattedText::Score(c) => c.into_text_component(),
233            FormattedText::Selector(c) => c.into_text_component(),
234            FormattedText::Nbt(c) => c.into_text_component(),
235            FormattedText::Object(c) => c.into_text_component(),
236        };
237
238        let text = &c.text;
239        expected_style = expected_style.merged_with(&c.base.style);
240
241        if !text.is_empty() {
242            let (formatted_style_prefix, formatted_style_suffix) =
243                style_formatter(last_style, &expected_style);
244            let formatted_text = text_formatter(text);
245
246            output.push_str(&formatted_style_prefix);
247            output.push_str(&formatted_text);
248            output.push_str(&formatted_style_suffix);
249
250            *last_style = expected_style.clone();
251        }
252
253        for sibling in c.base.siblings {
254            sibling.into_custom_format_recursive(
255                output,
256                style_formatter,
257                text_formatter,
258                &expected_style,
259                last_style,
260            )
261        }
262    }
263
264    /// Convert this component into an
265    /// [ANSI string](https://en.wikipedia.org/wiki/ANSI_escape_code).
266    ///
267    /// This is the same as [`FormattedText::to_ansi`], but you can specify a
268    /// default [`Style`] to use.
269    pub fn to_ansi_with_custom_style(&self, default_style: &Style) -> String {
270        self.to_custom_format(
271            |running, new| (running.compare_ansi(new), "".to_owned()),
272            |text| text.to_owned(),
273            |style| if !style.is_empty() { "\x1b[m" } else { "" }.to_owned(),
274            default_style,
275        )
276    }
277
278    /// Convert this component into an
279    /// [ANSI string](https://en.wikipedia.org/wiki/ANSI_escape_code), so you
280    /// can print it to your terminal and get styling.
281    ///
282    /// This is technically a shortcut for
283    /// [`FormattedText::to_ansi_with_custom_style`] with a default [`Style`]
284    /// colored white.
285    ///
286    /// If you don't want the result to be styled at all, use
287    /// [`Self::to_string`](#method.fmt-1).
288    ///
289    /// # Examples
290    ///
291    /// ```rust
292    /// use azalea_chat::FormattedText;
293    /// use serde::de::Deserialize;
294    ///
295    /// let component = FormattedText::deserialize(&serde_json::json!({
296    ///    "text": "Hello, world!",
297    ///    "color": "red",
298    /// })).unwrap();
299    ///
300    /// println!("{}", component.to_ansi());
301    /// ```
302    pub fn to_ansi(&self) -> String {
303        self.to_ansi_with_custom_style(&DEFAULT_STYLE)
304    }
305
306    /// Similar to [`Self::to_ansi`] but renders the result as HTML instead.
307    pub fn to_html(&self) -> String {
308        self.to_custom_format(
309            |running, new| {
310                (
311                    format!(
312                        "<span style=\"{}\">",
313                        running.merged_with(new).get_html_style()
314                    ),
315                    "</span>".to_owned(),
316                )
317            },
318            |text| {
319                text.replace("&", "&amp;")
320                    .replace("<", "&lt;")
321                    // usually unnecessary but good for compatibility
322                    .replace(">", "&gt;")
323                    .replace("\n", "<br>")
324            },
325            |_| "".to_owned(),
326            &DEFAULT_STYLE,
327        )
328    }
329}
330
331impl IntoIterator for FormattedText {
332    type Item = FormattedText;
333    type IntoIter = std::vec::IntoIter<Self::Item>;
334
335    /// Recursively call the function for every component in this component
336    fn into_iter(self) -> Self::IntoIter {
337        let base = self.get_base();
338        let siblings = base.siblings.clone();
339        let mut v: Vec<FormattedText> = Vec::with_capacity(siblings.len() + 1);
340        v.push(self);
341        for sibling in siblings {
342            v.extend(sibling);
343        }
344
345        v.into_iter()
346    }
347}
348
349#[cfg(all(feature = "azalea-buf", feature = "simdnbt"))]
350impl AzBuf for FormattedText {
351    fn azalea_read(_ctx: azalea_buf::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
352        let Some(nbt) = simdnbt::borrow::read_optional_tag(buf)? else {
353            return Ok(FormattedText::default());
354        };
355
356        FormattedText::codec_read(&nbt.as_tag().to_owned())
357            .map_err(|e| BufReadError::custom(e.to_string()))
358    }
359    fn azalea_write(&self, ctx: azalea_buf::Ctx, buf: &mut impl Write) -> io::Result<()> {
360        let nbt: NbtTag = self.codec_write().map_err(io::Error::other)?;
361        nbt.azalea_write(ctx, buf)?;
362        Ok(())
363    }
364}
365
366impl From<String> for FormattedText {
367    fn from(s: String) -> Self {
368        FormattedText::Text(TextComponent {
369            text: s,
370            base: BaseComponent::default(),
371        })
372    }
373}
374impl From<&str> for FormattedText {
375    fn from(s: &str) -> Self {
376        Self::from(s.to_owned())
377    }
378}
379
380impl Display for FormattedText {
381    /// Render the text in the component but without any formatting/styling.
382    ///
383    /// If you want the text to be styled, consider using [`Self::to_ansi`] or
384    /// [`Self::to_html`].
385    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
386        let s = self.to_custom_format(
387            |_, _| ("".to_owned(), "".to_owned()),
388            |text| text.to_owned(),
389            |_| "".to_owned(),
390            &Style::default(),
391        );
392        f.write_str(&s)
393    }
394}
395
396impl Default for FormattedText {
397    fn default() -> Self {
398        FormattedText::Text(TextComponent::default())
399    }
400}
401
402azalea_codec::impl_serde!(FormattedText);
403azalea_codec::impl_defaultable!(FormattedText);
404
405#[cfg(test)]
406mod tests {
407    use serde::Deserialize;
408    use serde_json::Value;
409
410    use super::*;
411    use crate::{component::translatable::PrimitiveOrComponent, style::TextColor};
412
413    #[test]
414    fn deserialize_translation() {
415        let j: Value =
416            serde_json::from_str(r#"{"translate": "translation.test.args", "with": ["a", "b"]}"#)
417                .unwrap();
418        let component = FormattedText::deserialize(&j).unwrap();
419        assert_eq!(
420            component,
421            FormattedText::Translatable(TranslatableComponent::new(
422                "translation.test.args".to_owned(),
423                vec![
424                    PrimitiveOrComponent::String("a".to_owned()),
425                    PrimitiveOrComponent::String("b".to_owned())
426                ]
427            ))
428        );
429    }
430
431    #[test]
432    fn deserialize_translation_invalid_arguments() {
433        let j: Value =
434            serde_json::from_str(r#"{"translate": "translation.test.args", "with": {}}"#).unwrap();
435        let res = FormattedText::deserialize(&j);
436        assert!(res.is_err());
437    }
438
439    #[test]
440    fn deserialize_translation_fallback() {
441        let j: Value = serde_json::from_str(r#"{"translate": "translation.test.undefined", "fallback": "fallback: %s", "with": ["a"]}"#).unwrap();
442        let component = FormattedText::deserialize(&j).unwrap();
443        assert_eq!(
444            component,
445            FormattedText::Translatable(TranslatableComponent::with_fallback(
446                "translation.test.undefined".to_owned(),
447                Some("fallback: %s".to_owned()),
448                vec![PrimitiveOrComponent::String("a".to_owned())]
449            ))
450        );
451    }
452
453    #[test]
454    fn deserialize_translation_invalid_fallback() {
455        let j: Value = serde_json::from_str(
456            r#"{"translate": "translation.test.undefined", "fallback": {"text": "invalid"}}"#,
457        )
458        .unwrap();
459        assert!(FormattedText::deserialize(&j).is_err());
460    }
461    #[test]
462    fn deserialize_translation_primitive_args() {
463        let j: Value = serde_json::from_str(
464            r#"{"translate":"commands.list.players", "with": [1, 65536, "<players>", {"text": "unused", "color": "red"}]}"#,
465        )
466        .unwrap();
467        assert_eq!(
468            FormattedText::deserialize(&j).unwrap(),
469            FormattedText::Translatable(TranslatableComponent::new(
470                "commands.list.players".to_owned(),
471                vec![
472                    PrimitiveOrComponent::Short(1),
473                    PrimitiveOrComponent::Integer(65536),
474                    PrimitiveOrComponent::String("<players>".to_owned()),
475                    PrimitiveOrComponent::FormattedText(FormattedText::Text(
476                        TextComponent::new("unused")
477                            .with_style(Style::new().color(Some(TextColor::parse("red").unwrap())))
478                    ))
479                ]
480            ))
481        );
482    }
483
484    #[test]
485    fn test_translatable_with_color_inheritance() {
486        let json = serde_json::json!({
487            "translate": "advancements.story.smelt_iron.title",
488            "color": "green",
489            "with": [{"text": "Acquire Hardware"}]
490        });
491        let component = FormattedText::deserialize(&json).unwrap();
492        let ansi = component.to_ansi();
493        assert!(ansi.contains("\u{1b}[38;2;85;255;85m"));
494    }
495}