Skip to main content

FormattedText

Enum FormattedText 

Source
pub enum FormattedText {
    Text(TextComponent),
    Translatable(TranslatableComponent),
    Keybind(KeybindComponent),
    Score(ScoreComponent),
    Selector(SelectorComponent),
    Nbt(NbtComponent),
    Object(ObjectComponent),
}
Expand description

A chat component, basically anything you can see in chat.

Variants§

Implementations§

Source§

impl FormattedText

A chat component

Source

pub fn get_base_mut(&mut self) -> &mut BaseComponent

Source

pub fn get_base(&self) -> &BaseComponent

Source

pub fn append(&mut self, sibling: FormattedText)

Add a component as a sibling of this one.

Source

pub fn extend(&mut self, siblings: impl IntoIterator<Item = FormattedText>)

Source

pub fn to_custom_format<F, S, C>( &self, style_formatter: F, text_formatter: S, cleanup_formatter: C, default_style: &Style, ) -> String
where F: FnMut(&Style, &Style) -> (String, String), S: FnMut(&str) -> String, C: FnMut(&Style) -> String,

Render all components into a single String, using your custom closures to drive styling, text transformation, and final cleanup.

§Type parameters
  • F: (running, component, default) -> (prefix, suffix) for per-component styling
  • S: &str -> String for text tweaks (escaping, mapping, etc.)
  • C: &final_running_style -> String for any trailing cleanup
§Arguments
  • style_formatter: how to open/close each component’s style
  • text_formatter: how to turn raw text into output text
  • cleanup_formatter: emit after all components (e.g. reset codes)
  • default_style: where to reset when a component’s reset is true
§Example
use azalea_chat::{FormattedText, DEFAULT_STYLE};
use serde::de::Deserialize;

let component = FormattedText::deserialize(&serde_json::json!({
   "text": "Hello, world!",
   "color": "red",
})).unwrap();

let ansi = component.to_custom_format(
    |running, new| (running.compare_ansi(new), "".to_owned()),
    |text| text.to_string(),
    |style| {
        if !style.is_empty() {
            "\u{1b}[m".to_owned()
        } else {
            "".to_owned()
        }
    },
    &DEFAULT_STYLE,
);
println!("{ansi}");
Source

pub fn to_ansi_with_custom_style(&self, default_style: &Style) -> String

Convert this component into an ANSI string.

This is the same as FormattedText::to_ansi, but you can specify a default Style to use.

Source

pub fn to_ansi(&self) -> String

Convert this component into an ANSI string, so you can print it to your terminal and get styling.

This is technically a shortcut for FormattedText::to_ansi_with_custom_style with a default Style colored white.

If you don’t want the result to be styled at all, use Self::to_string.

§Examples
use azalea_chat::FormattedText;
use serde::de::Deserialize;

let component = FormattedText::deserialize(&serde_json::json!({
   "text": "Hello, world!",
   "color": "red",
})).unwrap();

println!("{}", component.to_ansi());
Examples found in repository?
azalea/examples/testbot/main.rs (line 234)
225async fn swarm_handle(_swarm: Swarm, event: SwarmEvent, _state: SwarmState) -> eyre::Result<()> {
226    match &event {
227        SwarmEvent::Disconnect(account, _join_opts) => {
228            println!("bot got kicked! {}", account.username());
229        }
230        SwarmEvent::Chat(chat) => {
231            if chat.message().to_string() == "The particle was not visible for anybody" {
232                return Ok(());
233            }
234            println!("{}", chat.message().to_ansi());
235        }
236        _ => {}
237    }
238
239    Ok(())
240}
Source

pub fn to_html(&self) -> String

Similar to Self::to_ansi but renders the result as HTML instead.

Trait Implementations§

Source§

impl AzBuf for FormattedText

Available on crate features azalea-buf and simdnbt only.
Source§

fn azalea_read( _ctx: Ctx<'_>, buf: &mut Cursor<&[u8]>, ) -> Result<Self, BufReadError>

Source§

fn azalea_write(&self, ctx: Ctx<'_>, buf: &mut impl Write) -> Result<()>

Source§

impl Clone for FormattedText

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<O: Ops> Codec<O> for FormattedText

Source§

type Incomplete = IncompleteFormattedText<O>

Source§

fn codec_read(ops: &O) -> ReadResult<Self>

Convert from a data format to a data structure.
Source§

fn codec_write(&self) -> WriteResult<O>

Convert from a data structure to a data format.
Source§

impl Debug for FormattedText

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for FormattedText

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<O: Ops> Defaultable<O> for FormattedText

Source§

impl<'de> Deserialize<'de> for FormattedText

Source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for FormattedText

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Render the text in the component but without any formatting/styling.

If you want the text to be styled, consider using Self::to_ansi or Self::to_html.

Source§

impl From<&str> for FormattedText

Source§

fn from(s: &str) -> Self

Converts to this type from the input type.
Source§

impl From<String> for FormattedText

Source§

fn from(s: String) -> Self

Converts to this type from the input type.
Source§

impl From<TextComponent> for FormattedText

Source§

fn from(c: TextComponent) -> Self

Converts to this type from the input type.
Source§

impl From<TranslatableComponent> for FormattedText

Source§

fn from(c: TranslatableComponent) -> Self

Converts to this type from the input type.
Source§

impl IntoIterator for FormattedText

Source§

fn into_iter(self) -> Self::IntoIter

Recursively call the function for every component in this component

Source§

type Item = FormattedText

The type of the elements being iterated over.
Source§

type IntoIter = IntoIter<<FormattedText as IntoIterator>::Item>

Which kind of iterator are we turning this into?
Source§

impl PartialEq for FormattedText

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl Serialize for FormattedText

Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for FormattedText

Auto Trait Implementations§

§

impl Forget for FormattedText

§

impl Freeze for FormattedText

§

impl Move for FormattedText

§

impl RefUnwindSafe for FormattedText

§

impl Send for FormattedText
where RawVecInner: Send, BoxRaw<Style>: Send, BoxRaw<FormattedText>: Send, NonZero<usize>: Send, BoxRaw<str>: Send, &'static str: Send,

§

impl Sync for FormattedText
where RawVecInner: Sync, BoxRaw<Style>: Sync, BoxRaw<FormattedText>: Sync, NonZero<usize>: Sync, BoxRaw<str>: Sync,

§

impl Unpin for FormattedText

§

impl UnsafeUnpin for FormattedText

§

impl UnwindSafe for FormattedText
where RawVecInner: UnwindSafe, BoxRaw<Style>: UnwindSafe, BoxRaw<FormattedText>: UnwindSafe, NonZero<usize>: UnwindSafe, BoxRaw<str>: UnwindSafe, &'static str: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
§

impl<T> ConditionalSend for T
where T: Send,

Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

§

impl<T> Downcast for T
where T: Any,

§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
§

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
§

impl<T> DowncastSend for T
where T: Any + Send,

§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> FromTemplate for T
where T: Clone + Default + Unpin,

§

type Template = T

The [Template] for this type.
§

impl<T> FromWorld for T
where T: Default,

§

fn from_world(_world: &mut World) -> T

Creates Self using default().

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<A, B> Interchangeable<A> for B
where A: From<B>, B: From<A>,

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> IntoResult<T> for T

§

fn into_result(self) -> Result<T, RunSystemError>

Converts this type into the system output type.
§

impl<A> Is for A
where A: Any,

§

fn is<T>() -> bool
where T: Any,

Checks if the current type “is” another type, using a TypeId equality comparison. This is most useful in the context of generic logic. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> Serialize for T
where T: Serialize + ?Sized,

Source§

fn erased_serialize(&self, serializer: &mut dyn Serializer) -> Result<(), Error>

Source§

fn do_erased_serialize( &self, serializer: &mut dyn Serializer, ) -> Result<(), ErrorImpl>

§

impl<T> Template for T
where T: Clone + Unpin,

§

type Output = T

The type of value produced by this [Template].
§

fn build_template( &self, _context: &mut TemplateContext<'_, '_>, ) -> Result<<T as Template>::Output, BevyError>

Uses this template and the given entity context to produce a [Template::Output].
§

fn clone_template(&self) -> T

Clones this template. See Clone.
§

impl<T> ToCompactString for T
where T: Display,

§

fn try_to_compact_string(&self) -> Result<CompactString, ToCompactStringError>

Fallible version of [ToCompactString::to_compact_string()] Read more
§

fn to_compact_string(&self) -> CompactString

Converts the given value to a [CompactString]. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> TypeData for T
where T: 'static + Send + Sync + Clone,

§

fn clone_type_data(&self) -> Box<dyn TypeData>

Creates a type-erased clone of self.
§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more