From 51365c4b46797d405633fc873bfa186271cbbf2a Mon Sep 17 00:00:00 2001 From: vyPal Date: Sat, 30 Nov 2024 19:19:48 +0100 Subject: [PATCH] Text component children + fix nbt serialization for sequences of maps (#349) * Fix list serialization when elements are maps * Add extra field and add_child method to TextComponent --- pumpkin-core/src/text/mod.rs | 24 ++++++++++++++++++++++++ pumpkin-nbt/src/serializer.rs | 8 +++++++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/pumpkin-core/src/text/mod.rs b/pumpkin-core/src/text/mod.rs index e10f868d8..8081a2ad0 100644 --- a/pumpkin-core/src/text/mod.rs +++ b/pumpkin-core/src/text/mod.rs @@ -31,6 +31,8 @@ pub struct TextComponent<'a> { /// Also has `ClickEvent #[serde(flatten)] pub style: Style<'a>, + /// Extra text components + pub extra: Vec>, } impl<'a> TextComponent<'a> { @@ -38,6 +40,7 @@ impl<'a> TextComponent<'a> { Self { content: TextContent::Text { text: text.into() }, style: Style::default(), + extra: vec![], } } @@ -45,9 +48,15 @@ impl<'a> TextComponent<'a> { Self { content: TextContent::Text { text: text.into() }, style: Style::default(), + extra: vec![], } } + pub fn add_child(mut self, child: TextComponent<'a>) -> Self { + self.extra.push(child); + self + } + pub fn to_pretty_console(self) -> String { let style = self.style; let color = style.color; @@ -174,12 +183,27 @@ impl<'a> TextComponent<'a> { text: &'a TextContent<'a>, #[serde(flatten)] style: &'a Style<'a>, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[serde(rename = "extra")] + extra: Vec<&'a TempStruct<'a>>, } + let temp_extra: Vec = self + .extra + .iter() + .map(|x| TempStruct { + text: &x.content, + style: &x.style, + extra: vec![], + }) + .collect(); + let temp_extra_refs: Vec<&TempStruct> = temp_extra.iter().collect(); let astruct = TempStruct { text: &self.content, style: &self.style, + extra: temp_extra_refs, }; // dbg!(&serde_json::to_string(&astruct)); + // dbg!(pumpkin_nbt::serializer::to_bytes_unnamed(&astruct).unwrap().to_vec()); // TODO pumpkin_nbt::serializer::to_bytes_unnamed(&astruct) diff --git a/pumpkin-nbt/src/serializer.rs b/pumpkin-nbt/src/serializer.rs index 5ab8913f7..75a69502d 100644 --- a/pumpkin-nbt/src/serializer.rs +++ b/pumpkin-nbt/src/serializer.rs @@ -327,7 +327,13 @@ impl ser::Serializer for &mut Serializer { } fn serialize_map(self, _len: Option) -> Result { - self.output.put_u8(COMPOUND_ID); + if let State::FirstListElement { .. } = self.state { + self.parse_state(COMPOUND_ID)?; + } else if let State::ListElement = self.state { + return Ok(self); + } else { + self.output.put_u8(COMPOUND_ID); + } Ok(self) }