Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
278 changes: 213 additions & 65 deletions Cargo.lock

Large diffs are not rendered by default.

20 changes: 13 additions & 7 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ categories = [
custom = []
nbt = ["dep:simdnbt"]
serde = ["dep:serde"]
ownable = ["dep:ownable"]
databake = ["dep:databake"]
minimessage = ["ownable"]
build = [
"dep:heck",
"dep:proc-macro2",
Expand All @@ -31,22 +34,25 @@ build = [
]

[dependencies]
colored = "3.1"
rand = { version = "0.10", default-features = false, features = [
"std",
"thread_rng",
] }
serde = { version = "1.0.228", features = ["derive"], optional = true }
serde = { version = "1.0", features = ["derive"], optional = true }
simdnbt = { version = "0.10", optional = true }
uuid = { version = "1.23", features = ["v4", "serde"] }
supports-hyperlinks = "3.2"
# Build dependencies
heck = { version = "0.5.0", optional = true }
heck = { version = "0.5", optional = true }
proc-macro2 = { version = "1.0", optional = true }
quote = { version = "1.0", optional = true }
rustc-hash = { version = "2.1", optional = true }
serde_json = { version = "1.0.149", optional = true }
uuid = { version = "1.23", features = ["v4", "serde"] }
supports-hyperlinks = "3.2.0"
serde_json = { version = "1.0", optional = true }
memchr = "2.8"
smallvec = "1.15"
ownable = { version = "1.0", optional = true }
databake = { git = "https://github.com/suprohub/databake", optional = true, features = ["derive", "uuid"] }

[dev-dependencies]
chrono = "0.4"
serde_json = "1.0.149"
serde_json = "1.0"
18 changes: 13 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ component.resolve(resolutor).serialize(serializer);

### Displaying TextComponents

TextComponent implements Display for easy logging, as you can see, a component
TextComponent implements ToString for easy logging, as you can see, a component
needs to be resolved before building it into any format, by default it uses a static
reference to NoResolutor, but can be changed to a custom one with:\
(Resolutor must be static, or made inside the function call)
Expand All @@ -55,12 +55,20 @@ reference to NoResolutor, but can be changed to a custom one with:\
set_display_resolutor(&Resolutor);
```


A text component can be printed like a string like this:

```rs
println!("{}", component);
// With format (pretty):
println!("{:p}", component);
println!("{}", component.to_string());
// With format (colorful):
println!("{}", component.log());
```

If you want the log display format different to be able to parse it later, it can be done through `set_display_builder`,
which will need a function returning the built string, this is an example with the PrettyTextBuilder (the default one):

```rs
set_display_builder(|component, resolutor| component.build(resolutor, PrettyTextBuilder))
```

### Roadmap
Expand All @@ -73,7 +81,7 @@ println!("{:p}", component);
- [x] Terminal integration
- [x] Serde integration
- [x] SimdNbt integration
- [ ] MiniMessages integration
- [x] MiniMessage integration
- [ ] Extensibility integration

### Test
Expand Down
57 changes: 31 additions & 26 deletions examples/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use text_components::custom::{CustomContent, CustomData, CustomRegistry, Payload
#[cfg(feature = "nbt")]
use text_components::nbt::{NbtBuilder, ToSNBT};
use text_components::{
Modifier, TextComponent,
Modifier, RawTextComponent,
content::{NbtSource, ObjectPlayer, Resolvable},
fmt::set_display_resolutor,
format::Color,
Expand All @@ -23,7 +23,7 @@ use text_components::{
use uuid::Uuid;

struct EmptyResolutor;
impl TextResolutor for EmptyResolutor {
impl<'a> TextResolutor<'a> for EmptyResolutor {
fn translate(&self, key: &str) -> Option<String> {
match key {
"content" => Some(String::from(
Expand All @@ -38,10 +38,10 @@ impl TextResolutor for EmptyResolutor {
_ => None,
}
}
fn resolve_content(&self, resolvable: &Resolvable) -> TextComponent {
fn resolve_content(&self, resolvable: &Resolvable) -> RawTextComponent<'a> {
match resolvable {
Resolvable::Scoreboard { .. } => TextComponent::plain("5"),
Resolvable::Entity { .. } => TextComponent::plain("MrMelther")
Resolvable::Scoreboard { .. } => RawTextComponent::plain("5"),
Resolvable::Entity { .. } => RawTextComponent::plain("MrMelther")
.insertion("MrMelther")
.click_event(ClickEvent::suggest_command("/msg MrMelther "))
.hover_event(HoverEvent::show_entity(
Expand All @@ -50,7 +50,7 @@ impl TextResolutor for EmptyResolutor {
Some("MrMelther"),
)),
#[cfg(feature = "nbt")]
Resolvable::NBT { .. } => TextComponent::plain(
Resolvable::NBT { .. } => RawTextComponent::plain(
Nbt::Some(BaseNbt::new(
"",
NbtCompound::from_values(vec![
Expand All @@ -65,27 +65,27 @@ impl TextResolutor for EmptyResolutor {
),
#[cfg(not(feature = "nbt"))]
Resolvable::NBT { .. } => {
TextComponent::plain("{base:3.0d,id:\"minecraft:entity_interaction_range\"}")
RawTextComponent::plain("{base:3.0d,id:\"minecraft:entity_interaction_range\"}")
}
}
}
#[cfg(feature = "custom")]
fn resolve_custom(&self, data: &CustomData) -> Option<TextComponent> {
fn resolve_custom(&self, data: &CustomData) -> Option<RawTextComponent<'a>> {
if data.id == "time" {
return Some(TimeContent.resolve((), Payload::Empty));
}
None
}
}
#[cfg(feature = "custom")]
impl CustomRegistry for EmptyResolutor {
impl<'a> CustomRegistry<'a> for EmptyResolutor {
type Data = ();

fn register_content<T: CustomContent>(&mut self, _id: &'static str, _content: T) {
fn register_content<T: CustomContent<'a>>(&mut self, _id: &'a str, _content: T) {
todo!()
}

fn get_content(&self, _id: String) -> Box<dyn CustomContent<Reg = Self>> {
fn get_content(&self, _id: String) -> Box<dyn CustomContent<'_, Reg = Self>> {
Box::new(TimeContent)
}
}
Expand All @@ -96,35 +96,32 @@ const RESOLUBLE: Translation<4> = Translation("resoluble");
#[cfg(feature = "custom")]
struct TimeContent;
#[cfg(feature = "custom")]
impl CustomContent for TimeContent {
impl<'a> CustomContent<'a> for TimeContent {
type Reg = EmptyResolutor;

fn as_data(&self) -> CustomData {
fn as_data(&self) -> CustomData<'a> {
CustomData {
id: std::borrow::Cow::Borrowed("time"),
payload: Payload::Empty,
}
}

fn resolve(&self, _data: (), _payload: Payload) -> TextComponent {
TextComponent::plain(Utc::now().format("%H:%M").to_string())
fn resolve(&self, _data: (), _payload: Payload) -> RawTextComponent<'a> {
RawTextComponent::plain(Utc::now().format("%H:%M").to_string())
}
}

fn main() {
set_display_resolutor(&EmptyResolutor);
let mut resolubles = RESOLUBLE
let resolubles = RESOLUBLE
.message([
ObjectPlayer::name("MrMelther").reset(),
TextComponent::scoreboard("MrMelther", "objective").reset(),
TextComponent::entity("@p", None).reset(),
TextComponent::nbt("attributes[2]", NbtSource::entity("@p"), false, None).reset(),
RawTextComponent::scoreboard("MrMelther", "objective").reset(),
RawTextComponent::entity("@p", None).reset(),
RawTextComponent::nbt("attributes[2]", NbtSource::entity("@p"), false, None).reset(),
])
.color_hex("#6f00ff");

#[cfg(feature = "custom")]
(&mut resolubles).add_children(vec!["\n Custom: ".into(), TimeContent.reset()]);

let component = CONTENT
.message([
"This text is Blue!".reset().color(Color::Blue),
Expand All @@ -144,8 +141,16 @@ fn main() {
.reset(),
])
.color(Color::Green)
.bold(true)
.add_child(resolubles);
.bold(true);

let component = cfg_select! {
feature = "custom" => {
component.add_child(resolubles.add_children(vec!["\n Custom: ".into(), TimeContent.reset()]))
}
_ => {
component
}
};

println!("\nDebug:\n{:?}", component);
#[cfg(feature = "serde")]
Expand All @@ -161,6 +166,6 @@ fn main() {
"\nNBT (SNBT):\ntellraw @a {}",
component.build(&EmptyResolutor, NbtBuilder).to_snbt()
);
println!("\nText:\n{}", component);
println!("\nPretty Text:\n{:p}", component);
println!("\nText:\n{}", component.to_string());
println!("\nPretty Text:\n{}", component.log());
}
12 changes: 6 additions & 6 deletions examples/nbt.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use simdnbt::owned::{BaseNbt, Nbt, NbtCompound, NbtTag};
use text_components::{
Modifier, TextComponent,
Modifier, RawTextComponent,
format::Color,
interactivity::{ClickEvent, HoverEvent},
nbt::{NbtBuilder, ToSNBT},
Expand All @@ -19,12 +19,12 @@ fn main() -> Result<(), String> {
("string".into(), NbtTag::String("This is a text".into())),
]),
));
let component = TextComponent::nbt_display(nbt);
let component = RawTextComponent::nbt_display(nbt);
println!(
"tellraw @p {}",
component.build(&NoResolutor, NbtBuilder).to_snbt()
);
println!("{:p}", component);
println!("{}", component.log());

let nbt = "Holly molly I can get TextComponents from NBTs!"
.color(Color::Red)
Expand All @@ -38,9 +38,9 @@ fn main() -> Result<(), String> {
])
.build(&NoResolutor, NbtBuilder);
println!("{:?}", nbt);
let component =
TextComponent::from_nbt(&nbt).ok_or(String::from("Cannot recompose the TextComponent!"))?;
let component = RawTextComponent::from_nbt(&nbt)
.ok_or(String::from("Cannot recompose the TextComponent!"))?;
println!("{:?}", component);
println!("{:p}", component);
println!("{}", component.log());
Ok(())
}
8 changes: 4 additions & 4 deletions examples/serde.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
use text_components::{Modifier, TextComponent, format::Color, translation::TranslatedMessage};
use text_components::{Modifier, RawTextComponent, format::Color, translation::TranslatedMessage};

fn main() {
let component: TextComponent = TranslatedMessage::new("key", None)
let component: RawTextComponent = TranslatedMessage::new("key", None)
.color(Color::Blue)
.bold(true);
println!("{}", serde_json::to_string_pretty(&component).unwrap());
let component: TextComponent = serde_json::from_str(
let component: RawTextComponent = serde_json::from_str(
"{
\"text\": \"This is a Serde test\",
\"color\": \"blue\",
\"bold\": true
}",
)
.unwrap();
println!("{:p}", component)
println!("{}", component.log())
}
6 changes: 3 additions & 3 deletions examples/snbt.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use text_components::TextComponent;
use text_components::RawTextComponent;

fn main() {
use std::io::{Write, stdin, stdout};
Expand All @@ -14,11 +14,11 @@ fn main() {
if let Some('\r') = s.chars().next_back() {
s.pop();
}
let component = TextComponent::from_snbt(&s);
let component = RawTextComponent::from_snbt(&s);
match component {
Ok(component) => {
println!("{:?}", component);
println!("{:p}", component)
println!("{}", component.log())
}
Err(e) => eprintln!("{}", e),
}
Expand Down
1 change: 1 addition & 0 deletions src/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ pub fn build_translations(path: &str) -> TokenStream {
let const_name = Ident::new(&const_name_str, Span::call_site());

stream.extend(quote! {
#[doc = #text]
pub static #const_name: Translation<#param_count> = Translation(#key);
});
}
Expand Down
Loading
Loading