Merge pull request #176 from rdbtCVS/t3code/fix-screenshot-seed-actions
Fix screenshot, seed, and locate chat click actions
This commit is contained in:
@@ -9,9 +9,13 @@ use crate::{
|
||||
hud::{HudAtlas, HudBatch},
|
||||
hud_layout::{self, GuiDraw, PoseOp},
|
||||
screen_draw::{self as d, Draw, Measure, TextField},
|
||||
text::{self, Style, Text},
|
||||
text::{self, ClickEvent, Style, Text},
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "chat_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
/// GuiMessageTag.systemSinglePlayer's indicator colour.
|
||||
pub const SYSTEM_INDICATOR: u32 = 0xD0D0D0;
|
||||
|
||||
@@ -293,6 +297,35 @@ impl Chat {
|
||||
let draws = self.layout(batch.height as i32, ticks, focused);
|
||||
hud_layout::paint(batch, atlas, &draws);
|
||||
}
|
||||
/// The click action under a GUI-space cursor while chat is focused.
|
||||
pub fn click_at(
|
||||
&self,
|
||||
font: &crate::font::Font,
|
||||
height: i32,
|
||||
x: f64,
|
||||
y: f64,
|
||||
) -> Option<ClickEvent> {
|
||||
let scale = self.options.scale as f32;
|
||||
let mut x = x / f64::from(scale) - 4.0;
|
||||
let bottom = hud_layout::floor((height - 40) as f32 / scale);
|
||||
let from_bottom = f64::from(bottom) - y / f64::from(scale);
|
||||
if x < 0.0 || x >= f64::from(self.max_width()) || from_bottom <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let row = (from_bottom / f64::from(self.options.line_height())).ceil() as usize - 1;
|
||||
if row >= self.lines_per_page(true) {
|
||||
return None;
|
||||
}
|
||||
let line = self.lines.get(self.scroll + row)?;
|
||||
let content = line.content.resolve_legacy();
|
||||
for (c, style) in content.chars() {
|
||||
x -= f64::from(font.advance(c, style));
|
||||
if x < 0.0 {
|
||||
return style.click.clone();
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
/// Plain text of the newest messages (for tests and the control socket).
|
||||
pub fn recent_lines(&self, n: usize) -> Vec<String> {
|
||||
self.messages
|
||||
@@ -420,6 +453,11 @@ impl ChatScreen {
|
||||
pub fn value(&self) -> &str {
|
||||
&self.input.value
|
||||
}
|
||||
/// Replace the input for a suggest-command link and refresh completions.
|
||||
pub fn suggest_command(&mut self, m: &Measure, c: &Commands, command: &str) {
|
||||
self.input.set_value(m, command);
|
||||
self.edited(m, c);
|
||||
}
|
||||
/// `ChatScreen.resize`: a new screen with the current text.
|
||||
pub fn resize(&mut self, m: &Measure, c: &Commands, width: i32, height: i32) {
|
||||
if (width, height) != (self.width, self.height) {
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
use super::*;
|
||||
use crate::{font::Font, hud::Rect};
|
||||
use std::{collections::HashMap, path::Path};
|
||||
|
||||
fn font() -> Font {
|
||||
// The missing-glyph metrics let these tests run without game assets.
|
||||
Font::load(
|
||||
Path::new("/nonexistent-horizon-chat-test-resources"),
|
||||
&HashMap::new(),
|
||||
&[],
|
||||
(1, 1),
|
||||
(0, 0),
|
||||
Rect {
|
||||
u0: 0.0,
|
||||
v0: 0.0,
|
||||
u1: 1.0,
|
||||
v1: 1.0,
|
||||
w: 1,
|
||||
h: 1,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn add(chat: &mut Chat, font: &Font, content: Text) {
|
||||
for content in font.wrap_components(&content, chat.max_width()) {
|
||||
chat.lines.insert(
|
||||
0,
|
||||
Line {
|
||||
added: 0,
|
||||
content,
|
||||
indicator: None,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicking_seed_copies_the_raw_value_only_inside_the_link() {
|
||||
let font = font();
|
||||
for seed in [1, -42, i64::MIN, i64::MAX] {
|
||||
let mut chat = Chat::default();
|
||||
let seed_text = Text::copyable(seed.to_string()).with_color(text::GOLD);
|
||||
assert_eq!(seed_text.plain(), format!("[{seed}]"));
|
||||
assert_eq!(seed_text.spans[0].style.color, Some(text::GOLD));
|
||||
assert_eq!(seed_text.spans[1].style.color, Some(text::GREEN));
|
||||
assert_eq!(seed_text.spans[2].style.color, Some(text::GOLD));
|
||||
add(&mut chat, &font, Text::literal("Seed: ").append(seed_text));
|
||||
let expected = Some(ClickEvent::CopyToClipboard(seed.to_string()));
|
||||
let start = 4.0 + f64::from(font.width("Seed: ["));
|
||||
let end = start + f64::from(font.width(&seed.to_string()));
|
||||
assert_eq!(chat.click_at(&font, 360, start, 315.0), expected);
|
||||
assert_eq!(chat.click_at(&font, 360, end - 0.5, 315.0), expected);
|
||||
for (x, y) in [
|
||||
(start - 0.5, 315.0),
|
||||
(end, 315.0),
|
||||
(3.0, 315.0),
|
||||
(start, 320.0),
|
||||
(start, 310.0),
|
||||
] {
|
||||
assert_eq!(chat.click_at(&font, 360, x, y), None, "{x}, {y}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn click_targets_match_rendered_spans_when_scaled_wrapped_and_scrolled() {
|
||||
let font = font();
|
||||
let screenshot = ClickEvent::OpenFile("/tmp/My screenshots/世界.png".into());
|
||||
for scale in [0.5, 0.75, 1.0] {
|
||||
for line_spacing in [0.0, 0.5, 1.0] {
|
||||
let mut chat = Chat::default();
|
||||
chat.options.scale = scale;
|
||||
chat.options.width = 0.0;
|
||||
chat.options.line_spacing = line_spacing;
|
||||
for _ in 0..20 {
|
||||
add(
|
||||
&mut chat,
|
||||
&font,
|
||||
Text::literal("Saved screenshot as ").append(Text::styled(
|
||||
"2026-10-14_18.55.14.png",
|
||||
Style {
|
||||
click: Some(screenshot.clone()),
|
||||
bold: Some(true),
|
||||
underlined: Some(true),
|
||||
..Style::default()
|
||||
},
|
||||
)),
|
||||
);
|
||||
}
|
||||
for scroll in [0, 3, 12] {
|
||||
chat.scroll = scroll;
|
||||
let mut links = 0;
|
||||
for draw in chat.layout(361, 0, true) {
|
||||
if let GuiDraw::Text { text, x, y, .. } = draw {
|
||||
let mut at = x as f64;
|
||||
for (c, style) in text.chars() {
|
||||
let width = f64::from(font.advance(c, style));
|
||||
let cursor_x = (4.0 + at + width / 2.0) * scale;
|
||||
let cursor_y = (y as f64 + 3.0) * scale;
|
||||
assert_eq!(
|
||||
chat.click_at(&font, 361, cursor_x, cursor_y),
|
||||
style.click,
|
||||
"scale={scale}, spacing={line_spacing}, scroll={scroll}, char={c}"
|
||||
);
|
||||
links += usize::from(style.click.is_some());
|
||||
at += width;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(links > 0);
|
||||
// The history above the focused viewport is not clickable.
|
||||
let top = ((361 - 40) as f64 / scale).floor()
|
||||
- chat.lines_per_page(true) as f64 * chat.options.line_height() as f64;
|
||||
assert_eq!(
|
||||
chat.click_at(&font, 361, 10.0 * scale, (top - 1.0) * scale),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locate_coordinates_fill_chat_with_teleport_without_submitting() {
|
||||
let font = font();
|
||||
let m = Measure(&font);
|
||||
let registries = Registries::default();
|
||||
let commands = Commands {
|
||||
dispatcher: crate::command::vanilla::game_dispatcher(),
|
||||
registries: ®istries,
|
||||
};
|
||||
// Structures and POIs use relative Y; biome results include absolute Y.
|
||||
for (y, expected) in [
|
||||
(None, "/tp @s -1136 ~ 848"),
|
||||
(Some(73), "/tp @s -1136 73 848"),
|
||||
] {
|
||||
let link = Text::teleport_link(-1136, y, 848);
|
||||
assert_eq!(link.component()["click_event"]["action"], "suggest_command");
|
||||
assert_eq!(link.component()["click_event"]["command"], expected);
|
||||
let mut chat = Chat::default();
|
||||
add(&mut chat, &font, Text::literal("Found at ").append(link));
|
||||
let mut screen = ChatScreen::new(&m, &commands, "draft", 0, 640, 360);
|
||||
let x = 4.0 + f64::from(font.width("Found at "));
|
||||
assert!(!screen.click(&m, &commands, x, 315.0));
|
||||
let Some(ClickEvent::SuggestCommand(command)) = chat.click_at(&font, 360, x, 315.0) else {
|
||||
panic!("locate coordinates must suggest a command");
|
||||
};
|
||||
screen.suggest_command(&m, &commands, &command);
|
||||
assert_eq!(screen.value(), expected);
|
||||
assert_eq!(screen.input.cursor, expected.chars().count());
|
||||
assert_eq!(screen.input.highlight, screen.input.cursor);
|
||||
// Submission is a separate, explicit Enter press.
|
||||
assert_eq!(
|
||||
screen.key(
|
||||
&m,
|
||||
&commands,
|
||||
&[],
|
||||
winit::keyboard::KeyCode::Enter,
|
||||
false,
|
||||
false
|
||||
),
|
||||
ChatAction::Submit(expected.to_owned())
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ use horizon_client::{
|
||||
gamerules::GameRules,
|
||||
hud::{HudBatch, rgba},
|
||||
screen_draw::Measure,
|
||||
text::Text,
|
||||
text::{ClickEvent, Style, Text},
|
||||
};
|
||||
use std::collections::BTreeMap;
|
||||
use winit::{
|
||||
@@ -78,8 +78,8 @@ pub struct UiState {
|
||||
pub hide_gui: bool,
|
||||
/// Death message key set by the cause of death (e.g. /kill).
|
||||
pub death_cause: Option<String>,
|
||||
/// File name of an F2 screenshot waiting for its frame.
|
||||
pub screenshot_message: Option<String>,
|
||||
/// Path of an F2 screenshot waiting for its frame.
|
||||
pub screenshot_message: Option<std::path::PathBuf>,
|
||||
/// The options screens.
|
||||
pub options: horizon_client::options_ui::OptionsUi,
|
||||
/// The prepared resources before resource packs are layered on.
|
||||
@@ -538,14 +538,37 @@ impl Game<'_> {
|
||||
let height = self.renderer.as_ref().map_or(720.0, |r| {
|
||||
HudBatch::new([r.config.width, r.config.height]).height
|
||||
});
|
||||
let _ = height;
|
||||
let m = Measure(&self.res.atlas.font);
|
||||
let c = Commands {
|
||||
dispatcher: vanilla::game_dispatcher(),
|
||||
registries: &self.ui.registries,
|
||||
};
|
||||
if let Some(screen) = self.ui.chat_screen.as_mut() {
|
||||
screen.click(&m, &c, cursor.0 as f64, cursor.1 as f64);
|
||||
if screen.click(&m, &c, cursor.0 as f64, cursor.1 as f64) {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
match self.ui.chat.click_at(
|
||||
&self.res.atlas.font,
|
||||
height as i32,
|
||||
cursor.0 as f64,
|
||||
cursor.1 as f64,
|
||||
) {
|
||||
Some(ClickEvent::CopyToClipboard(value)) => {
|
||||
use horizon_client::clipboard::Clipboard;
|
||||
self.clipboard.set(&value);
|
||||
}
|
||||
Some(ClickEvent::OpenFile(path)) => {
|
||||
super::packs::open_folder(std::path::Path::new(&path));
|
||||
}
|
||||
Some(ClickEvent::SuggestCommand(command)) => {
|
||||
if let Some(screen) = self.ui.chat_screen.as_mut() {
|
||||
screen.suggest_command(&m, &c, &command);
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
/// Chat lines over the HUD (focused while the chat screen is open).
|
||||
@@ -745,16 +768,28 @@ impl Game<'_> {
|
||||
let Some(renderer) = self.renderer.as_mut() else {
|
||||
return;
|
||||
};
|
||||
renderer.screenshot = Some(dir.join(&name));
|
||||
self.ui.screenshot_message = Some(name);
|
||||
let path = dir.join(name);
|
||||
renderer.screenshot = Some(path.clone());
|
||||
self.ui.screenshot_message = Some(path);
|
||||
}
|
||||
/// After a frame: report a finished F2 screenshot in chat.
|
||||
pub(super) fn finish_screenshot(&mut self, result: &std::result::Result<[u32; 2], String>) {
|
||||
let Some(name) = self.ui.screenshot_message.take() else {
|
||||
let Some(path) = self.ui.screenshot_message.take() else {
|
||||
return;
|
||||
};
|
||||
let message = match result {
|
||||
Ok(_) => Text::translate("screenshot.success", &[Text::literal(name).underlined()]),
|
||||
Ok(_) => {
|
||||
let name = path.file_name().unwrap_or_default().to_string_lossy();
|
||||
let link = Text::styled(
|
||||
name,
|
||||
Style {
|
||||
underlined: Some(true),
|
||||
click: Some(ClickEvent::OpenFile(path.to_string_lossy().into_owned())),
|
||||
..Style::default()
|
||||
},
|
||||
);
|
||||
Text::translate("screenshot.success", &[link])
|
||||
}
|
||||
Err(e) => Text::translate("screenshot.failure", &[Text::literal(e.clone())]),
|
||||
};
|
||||
let focused = self.screen == Screen::Chat;
|
||||
|
||||
@@ -109,7 +109,7 @@ impl Game<'_> {
|
||||
let Some(input) = &e.input else { return };
|
||||
let cursor = e.cursor.min(input.len());
|
||||
let suggest = Style {
|
||||
suggest: Some(format!("/{command}")),
|
||||
click: Some(text::ClickEvent::SuggestCommand(format!("/{command}"))),
|
||||
..Style::default()
|
||||
};
|
||||
let mut context = Text::empty();
|
||||
@@ -569,14 +569,7 @@ impl Game<'_> {
|
||||
"difficulty" => self.cmd_difficulty(ctx),
|
||||
"seed" => {
|
||||
let seed = self.level.seed.to_string();
|
||||
let green = Style {
|
||||
color: Some(text::GREEN),
|
||||
suggest: None,
|
||||
..Style::default()
|
||||
};
|
||||
let value = Text::literal("[")
|
||||
.append(Text::styled(seed.clone(), green))
|
||||
.append("]");
|
||||
let value = Text::copyable(seed);
|
||||
self.system_message(Text::translate("commands.seed.success", &[value]));
|
||||
Ok(self.level.seed as i32)
|
||||
}
|
||||
@@ -2342,22 +2335,7 @@ impl Game<'_> {
|
||||
&[&poi],
|
||||
)));
|
||||
};
|
||||
let coords = Text::translate(
|
||||
"chat.coordinates",
|
||||
&[
|
||||
Text::literal(p[0].to_string()),
|
||||
Text::literal("~"),
|
||||
Text::literal(p[2].to_string()),
|
||||
],
|
||||
);
|
||||
let link = Text::literal("[")
|
||||
.append(coords)
|
||||
.append("]")
|
||||
.with_style(&Style {
|
||||
color: Some(text::GREEN),
|
||||
suggest: Some(format!("/tp @s {} ~ {}", p[0], p[2])),
|
||||
..Style::default()
|
||||
});
|
||||
let link = Text::teleport_link(p[0], None, p[2]);
|
||||
let (dx, dz) = (p[0] - from[0], p[2] - from[2]);
|
||||
let distance = ((dx * dx + dz * dz) as f32).sqrt().floor() as i32;
|
||||
let shown = if poi.starts_with('#') {
|
||||
@@ -2413,15 +2391,7 @@ impl Game<'_> {
|
||||
} else {
|
||||
biome.clone()
|
||||
};
|
||||
let coords = Text::tr("chat.coordinates", &[&p[0], &p[1], &p[2]]);
|
||||
let link = Text::literal("[")
|
||||
.append(coords)
|
||||
.append("]")
|
||||
.with_style(&Style {
|
||||
color: Some(text::GREEN),
|
||||
suggest: Some(format!("/tp @s {} {} {}", p[0], p[1], p[2])),
|
||||
..Style::default()
|
||||
});
|
||||
let link = Text::teleport_link(p[0], Some(p[1]), p[2]);
|
||||
let distance = (d2 as f32).sqrt().floor() as i32;
|
||||
self.feedback(Text::translate(
|
||||
"commands.locate.biome.success",
|
||||
@@ -2449,22 +2419,7 @@ impl Game<'_> {
|
||||
&[&s],
|
||||
)));
|
||||
};
|
||||
let coords = Text::translate(
|
||||
"chat.coordinates",
|
||||
&[
|
||||
Text::literal(p[0].to_string()),
|
||||
Text::literal("~"),
|
||||
Text::literal(p[2].to_string()),
|
||||
],
|
||||
);
|
||||
let link = Text::literal("[")
|
||||
.append(coords)
|
||||
.append("]")
|
||||
.with_style(&Style {
|
||||
color: Some(text::GREEN),
|
||||
suggest: Some(format!("/tp @s {} ~ {}", p[0], p[2])),
|
||||
..Style::default()
|
||||
});
|
||||
let link = Text::teleport_link(p[0], None, p[2]);
|
||||
let (dx, dz) = (f64::from(p[0] - from[0]), f64::from(p[2] - from[2]));
|
||||
let distance = (dx * dx + dz * dz).sqrt().floor() as i32;
|
||||
let shown = if s.starts_with('#') {
|
||||
|
||||
@@ -320,10 +320,10 @@ impl Game<'_> {
|
||||
let color = self.waypoint_icon(*t).color.unwrap_or(-1) as u32 & 0xFF_FFFF;
|
||||
let style = Style {
|
||||
color: Some(color),
|
||||
suggest: Some(format!(
|
||||
click: Some(text::ClickEvent::SuggestCommand(format!(
|
||||
"/execute in {dimension} run tp @s {} {} {}",
|
||||
pos[0], pos[1], pos[2]
|
||||
)),
|
||||
))),
|
||||
hover: Some(Box::new(Text::translate("chat.coordinates.tooltip", &[]))),
|
||||
..Style::default()
|
||||
};
|
||||
@@ -701,7 +701,7 @@ impl Game<'_> {
|
||||
let mut t = Text::translate("chat.square_brackets", &[inner]);
|
||||
if let Some(cmd) = run {
|
||||
t = t.with_style(&Style {
|
||||
suggest: None,
|
||||
click: None,
|
||||
..Style::default()
|
||||
});
|
||||
let _ = cmd;
|
||||
|
||||
@@ -328,7 +328,7 @@ impl Game<'_> {
|
||||
let message = self.expand_selectors(&raw);
|
||||
let hover = text::Style {
|
||||
hover: Some(Box::new(Text::translate("chat.type.team.hover", &[]))),
|
||||
suggest: Some("/teammsg ".into()),
|
||||
click: Some(text::ClickEvent::SuggestCommand("/teammsg ".into())),
|
||||
..text::Style::default()
|
||||
};
|
||||
let team_name = team.formatted_display_name().with_style(&hover);
|
||||
|
||||
@@ -535,7 +535,9 @@ impl Game<'_> {
|
||||
let hint = if enabled { "disable" } else { "enable" };
|
||||
let style = text::Style {
|
||||
color: Some(if enabled { text::GREEN } else { text::RED }),
|
||||
suggest: Some(format!("/datapack {hint} \"{id}\"")),
|
||||
click: Some(text::ClickEvent::SuggestCommand(format!(
|
||||
"/datapack {hint} \"{id}\""
|
||||
))),
|
||||
..text::Style::default()
|
||||
};
|
||||
let description = self
|
||||
|
||||
@@ -533,7 +533,7 @@ impl Team {
|
||||
/// `PlayerTeam.getFormattedDisplayName`.
|
||||
pub fn formatted_display_name(&self) -> Text {
|
||||
let inner = hover_name(comp_text(&self.display_name), &self.name).with_style(&Style {
|
||||
suggest: None,
|
||||
click: None,
|
||||
..Style::default()
|
||||
});
|
||||
self.apply_color(bracketed(inner))
|
||||
|
||||
@@ -39,6 +39,16 @@ pub fn named_color(name: &str) -> Option<u32> {
|
||||
COLORS.iter().find(|c| c.1 == name).map(|c| c.2)
|
||||
}
|
||||
|
||||
/// Click actions carried by locally constructed text components.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum ClickEvent {
|
||||
SuggestCommand(String),
|
||||
CopyToClipboard(String),
|
||||
/// A local file to open with the system handler.
|
||||
/// Only allow this in locally constructed messages, never server/LAN text.
|
||||
OpenFile(String),
|
||||
}
|
||||
|
||||
/// Text style; `None` fields inherit from the enclosing style.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Style {
|
||||
@@ -48,8 +58,7 @@ pub struct Style {
|
||||
pub underlined: Option<bool>,
|
||||
pub strikethrough: Option<bool>,
|
||||
pub obfuscated: Option<bool>,
|
||||
/// ClickEvent.SuggestCommand: clicking puts this into the chat box.
|
||||
pub suggest: Option<String>,
|
||||
pub click: Option<ClickEvent>,
|
||||
/// Hover text.
|
||||
pub hover: Option<Box<Text>>,
|
||||
}
|
||||
@@ -68,8 +77,8 @@ impl Style {
|
||||
self.underlined = self.underlined.or(base.underlined);
|
||||
self.strikethrough = self.strikethrough.or(base.strikethrough);
|
||||
self.obfuscated = self.obfuscated.or(base.obfuscated);
|
||||
if self.suggest.is_none() {
|
||||
self.suggest.clone_from(&base.suggest);
|
||||
if self.click.is_none() {
|
||||
self.click.clone_from(&base.click);
|
||||
}
|
||||
if self.hover.is_none() {
|
||||
self.hover.clone_from(&base.hover);
|
||||
@@ -134,6 +143,34 @@ impl Text {
|
||||
pub fn colored(s: impl Into<String>, color: u32) -> Self {
|
||||
Self::styled(s, Style::color(color))
|
||||
}
|
||||
/// ComponentUtils.copyOnClickText: a green, bracketed clipboard link.
|
||||
pub fn copyable(s: impl Into<String>) -> Self {
|
||||
let s = s.into();
|
||||
Self::literal("[")
|
||||
.append(Self::styled(
|
||||
s.clone(),
|
||||
Style {
|
||||
click: Some(ClickEvent::CopyToClipboard(s)),
|
||||
hover: Some(Box::new(Self::translate("chat.copy.click", &[]))),
|
||||
..Style::color(GREEN)
|
||||
},
|
||||
))
|
||||
.append("]")
|
||||
}
|
||||
/// LocateCommand's coordinate link: suggest a teleport without executing it.
|
||||
/// Structure and POI results preserve the player's current height (`~`).
|
||||
pub fn teleport_link(x: i32, y: Option<i32>, z: i32) -> Self {
|
||||
let y = y.map_or_else(|| "~".to_owned(), |y| y.to_string());
|
||||
let coords = Self::tr("chat.coordinates", &[&x, &y, &z]);
|
||||
Self::literal("[")
|
||||
.append(coords)
|
||||
.append("]")
|
||||
.with_style(&Style {
|
||||
click: Some(ClickEvent::SuggestCommand(format!("/tp @s {x} {y} {z}"))),
|
||||
hover: Some(Box::new(Self::translate("chat.coordinates.tooltip", &[]))),
|
||||
..Style::color(GREEN)
|
||||
})
|
||||
}
|
||||
/// Component.translatable(key, args) in the current language.
|
||||
pub fn translate(key: &str, args: &[Text]) -> Self {
|
||||
let mut t = format_translation(&lang::get(key), args);
|
||||
@@ -423,11 +460,17 @@ fn style_json(style: &Style) -> Vec<(String, Value)> {
|
||||
out.push((key.to_owned(), f.into()));
|
||||
}
|
||||
}
|
||||
if let Some(command) = &style.suggest {
|
||||
out.push((
|
||||
"click_event".to_owned(),
|
||||
json!({ "action": "suggest_command", "command": command }),
|
||||
));
|
||||
if let Some(click) = &style.click {
|
||||
let event = match click {
|
||||
ClickEvent::SuggestCommand(command) => {
|
||||
json!({ "action": "suggest_command", "command": command })
|
||||
}
|
||||
ClickEvent::CopyToClipboard(value) => {
|
||||
json!({ "action": "copy_to_clipboard", "value": value })
|
||||
}
|
||||
ClickEvent::OpenFile(path) => json!({ "action": "open_file", "path": path }),
|
||||
};
|
||||
out.push(("click_event".to_owned(), event));
|
||||
}
|
||||
if let Some(hover) = &style.hover {
|
||||
out.push((
|
||||
@@ -516,6 +559,41 @@ pub fn format_translation(template: &str, args: &[Text]) -> Text {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn click_events_serialize_and_inherit_as_one_style_field() {
|
||||
for (event, json) in [
|
||||
(
|
||||
ClickEvent::SuggestCommand("/seed".into()),
|
||||
json!({"action": "suggest_command", "command": "/seed"}),
|
||||
),
|
||||
(
|
||||
ClickEvent::CopyToClipboard("-9223372036854775808".into()),
|
||||
json!({"action": "copy_to_clipboard", "value": "-9223372036854775808"}),
|
||||
),
|
||||
(
|
||||
ClickEvent::OpenFile("/tmp/My screenshots/世界.png".into()),
|
||||
json!({"action": "open_file", "path": "/tmp/My screenshots/世界.png"}),
|
||||
),
|
||||
] {
|
||||
let style = Style {
|
||||
click: Some(event.clone()),
|
||||
..Style::default()
|
||||
};
|
||||
let text = Text::literal("link").with_style(&style);
|
||||
assert_eq!(text.component()["click_event"], json);
|
||||
assert_eq!(text.spans[0].style.click, Some(event));
|
||||
let child = Text::copyable("42").with_style(&style);
|
||||
assert_eq!(
|
||||
child.spans[1].style.click,
|
||||
Some(ClickEvent::CopyToClipboard("42".into()))
|
||||
);
|
||||
assert_eq!(
|
||||
child.component()["extra"][0]["click_event"],
|
||||
json!({"action": "copy_to_clipboard", "value": "42"})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formats_like_translatable_contents() {
|
||||
let a = [Text::literal("Steve"), Text::colored("Zombie", RED)];
|
||||
|
||||
Reference in New Issue
Block a user