1use yog_sync::RwLock;
12
13const LINK: &str = "#2f5fbf";
15const KEY_OPEN: &str = "{key|";
17const CLOSE: char = '}';
18
19pub type KeyNamer = fn(&str) -> Option<String>;
22
23static KEY_NAMER: RwLock<Option<KeyNamer>> = RwLock::new(None);
24
25pub fn set_key_namer(f: KeyNamer) {
27 *KEY_NAMER.write() = Some(f);
28}
29
30fn keys(text: &str) -> String {
32 let mut out = String::with_capacity(text.len());
33 let mut rest = text;
34 while let Some(at) = rest.find(KEY_OPEN) {
35 let after = &rest[at + KEY_OPEN.len()..];
36 let Some(end) = after.find(CLOSE) else { break };
37 let binding = &after[..end];
38 let name = (*KEY_NAMER.read()).and_then(|f| f(binding)).unwrap_or_else(|| binding.to_owned());
39 out.push_str(&rest[..at]);
40 out.push_str(&name.replace('{', "{{").replace('}', "}}"));
41 rest = &after[end + 1..];
42 }
43 out.push_str(rest);
44 out
45}
46
47pub fn resolve(text: &str, accent: &str) -> String {
49 yog_ui::rich::map_attrs(&keys(text), |w| match w {
50 "accent" => Some(accent.to_string()),
51 w if w.starts_with("link=") => Some(format!("u {LINK}")),
52 _ => None,
53 })
54}
55
56#[cfg(test)]
57mod tests {
58 use super::*;
59
60 #[test]
61 fn resolves_the_books_words() {
62 let r = resolve(
63 "{accent|Media} is {b|{link=hexcasting:staff|staves}} {{x}}",
64 "#8d6acc",
65 );
66 assert_eq!(r, "{#8d6acc|Media} is {b|{u #2f5fbf|staves}} {{x}}");
67 let runs = yog_ui::rich::runs(&r);
68 assert_eq!(runs[0].1.color, Some(0x8d6acc));
69 assert!(
70 runs.iter()
71 .any(|(t, s)| t == "staves" && s.bold && s.underline)
72 );
73 }
74
75 #[test]
76 fn a_key_is_named_as_the_game_binds_it() {
77 assert_eq!(resolve("hold {key|sprint}.", "#000000"), "hold sprint.");
78 set_key_namer(|b| (b == "sprint").then(|| "Left Control".to_owned()));
79 assert_eq!(resolve("hold {key|sprint}.", "#000000"), "hold Left Control.");
80 }
81}