Implementing your own custom parser
The ComponentParser and ComponentSerializer traits are designed for extensibility. In case you need to support a different markup format (e.g., a custom Markdown-like syntax, or integration with another rich text system), these traits come in handy.
At a high level:
-
The
ComponentParsertrait defines how to convert a string representation of a text component into aComponentenum. Its primary method is#![allow(unused)] fn main() { fn from_string(input: impl AsRef<str>) -> Result<Component, Self::Err>; } -
The
ComponentSerializertrait defines how to convert aComponentenum back into a string representation. Its primary method is:#![allow(unused)] fn main() { fn to_string(component: &Component) -> Result<String, Self::Err>; }
The input type in from_string is deliberately generic to allow you to provide multiple types, such as:
&strString&StringBox<str>Cow<'_, str>without restrictions.
- Define your parser/serializer struct: Create a new struct (like
MyCustomParser). - Implement
ComponentParser:- Implement the
from_stringmethod, which will contain your logic to parse the input string and construct aComponentobject. This often involves tokenizing the input, managing a style stack, and buildingComponents based on your format’s rules.
- Implement the
- Implement
ComponentSerializer(optional):- Implement the
to_stringmethod, which will traverse aComponentobject and convert it into your desired string format.
- Implement the
Both traits have an Err associated type for your serialization errors. You have to define one, but it can be any type, including () as a placeholder.
The minimessage.rs source file is an excellent reference for how to implement these traits. By following this pattern, you can integrate kyori-component-json with virtually any rich text input or output format.
You can find more about these traits on docs.rs: