1use serde::{Deserialize, Serialize};
6
7pub use crate::text_color::ColorSpan;
8pub use crate::text_time::TimeSpan;
9
10#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
11#[serde(tag = "kind", rename_all = "lowercase")]
12pub enum TextSpan {
13 Color(ColorSpan),
14 Time(TimeSpan),
15}
16
17impl TextSpan {
18 pub fn to_tag_parts(&self) -> Vec<String> {
20 match self {
21 TextSpan::Color(s) => s.to_tag_parts(),
22 TextSpan::Time(s) => s.to_tag_parts(),
23 }
24 }
25
26}
27
28fn collect<'a>(tags: impl Iterator<Item = Vec<&'a str>>, content: &str) -> Vec<TextSpan> {
31 let len = std::cell::OnceCell::new();
32 let chars = std::cell::OnceCell::new();
33 let mut out: Vec<TextSpan> = Vec::new();
34 for parts in tags {
35 let span = match parts.first().copied() {
36 Some(crate::text_color::TAG) => {
37 ColorSpan::from_parts(&parts, *len.get_or_init(|| content.chars().count() as u32)).map(TextSpan::Color)
38 }
39 Some(crate::text_time::TAG) => {
40 let chars = chars.get_or_init(|| content.chars().collect::<Vec<char>>());
41 TimeSpan::from_parts(&parts, chars)
42 .filter(|t| !out.iter().any(|s| matches!(s, TextSpan::Time(o) if o.from == t.from)))
43 .map(TextSpan::Time)
44 }
45 _ => None,
46 };
47 out.extend(span);
48 if out.len() == 128 {
49 break;
50 }
51 }
52 out
53}
54
55pub fn extract_own(content: &str) -> (String, Vec<TextSpan>) {
58 let (plain, mut spans) = extract(content);
59 if !crate::badges::has_text_effects() {
60 spans.retain(|s| !matches!(s, TextSpan::Color(_)));
61 }
62 (plain, spans)
63}
64
65pub fn extract(content: &str) -> (String, Vec<TextSpan>) {
68 let (plain, colors) = crate::text_color::extract(content);
69 let (mut seen, mut seen_chars) = (0usize, 0u32);
71 let tokens: Vec<_> = crate::text_time::tokens(&plain)
72 .into_iter()
73 .filter(|&(start, end, ..)| {
74 seen_chars += plain[seen..start].chars().count() as u32;
75 seen = start;
76 let (s, e) = (seen_chars, seen_chars + plain[start..end].chars().count() as u32);
77 !colors.iter().any(|c| (c.from > s && c.from < e) || (c.to > s && c.to < e))
78 })
79 .collect();
80 let mut spans: Vec<TextSpan> = Vec::with_capacity(colors.len() + tokens.len());
81 if tokens.is_empty() {
82 spans.extend(colors.into_iter().map(TextSpan::Color));
83 return (plain, spans);
84 }
85 let mut out = String::with_capacity(plain.len() + tokens.len() * 8);
87 let mut shifts: Vec<(u32, i64)> = Vec::with_capacity(tokens.len());
88 let mut times = Vec::with_capacity(tokens.len());
89 let (mut pos, mut chars, mut delta) = (0usize, 0u32, 0i64);
90 for (start, end, unix, style) in tokens {
91 let before = &plain[pos..start];
92 out.push_str(before);
93 chars += before.chars().count() as u32;
94 let token_chars = plain[start..end].chars().count() as u32;
95 let text = crate::text_time::fallback(unix).expect("tokens only yield times in range");
96 let text_chars = text.chars().count() as u32;
97 times.push(TimeSpan { from: chars, to: chars + text_chars, unix, style });
98 out.push_str(&text);
99 let original_end = (chars as i64 - delta) as u32 + token_chars;
100 delta += text_chars as i64 - token_chars as i64;
101 shifts.push((original_end, delta));
102 chars += text_chars;
103 pos = end;
104 }
105 out.push_str(&plain[pos..]);
106 let shift = |p: u32| -> u32 {
107 let d = shifts.iter().rev().find(|&&(at, _)| p >= at).map_or(0, |&(_, d)| d);
108 (p as i64 + d) as u32
109 };
110 spans.extend(colors.into_iter().map(|c| TextSpan::Color(ColorSpan { from: shift(c.from), to: shift(c.to), ..c })));
111 spans.extend(times.into_iter().map(TextSpan::Time));
112 (out, spans)
113}
114
115pub fn from_tags<'a, I>(tags: I, content: &str) -> Vec<TextSpan>
117where
118 I: IntoIterator<Item = &'a nostr_sdk::prelude::Tag>,
119{
120 let tags = tags.into_iter().filter(|t| is_span_tag(t.as_slice().first().map(|s| s.as_str())));
121 collect(tags.map(|t| t.as_slice().iter().map(|s| s.as_str()).collect()), content)
122}
123
124pub fn from_stored(tags: &[Vec<String>], content: &str) -> Vec<TextSpan> {
126 let tags = tags.iter().filter(|t| is_span_tag(t.first().map(|s| s.as_str())));
127 collect(tags.map(|t| t.iter().map(|s| s.as_str()).collect()), content)
128}
129
130fn is_span_tag(name: Option<&str>) -> bool {
131 matches!(name, Some(crate::text_color::TAG | crate::text_time::TAG))
132}
133
134pub fn to_nostr_tags(spans: &[TextSpan]) -> impl Iterator<Item = nostr_sdk::prelude::Tag> + '_ {
136 spans.iter().map(|s| {
137 let mut parts = s.to_tag_parts();
138 parts.remove(0);
139 let name = match s {
140 TextSpan::Color(_) => crate::text_color::TAG,
141 TextSpan::Time(_) => crate::text_time::TAG,
142 };
143 nostr_sdk::prelude::Tag::custom(name, parts)
144 })
145}
146
147#[cfg(test)]
148mod tests {
149 use super::*;
150 use crate::text_color::Effect;
151
152 #[test]
153 fn times_and_colours_extract_together() {
154 let (plain, spans) = extract("<rainbow>Party</rainbow> at <t:1618953600:F>, <color pink>be there</color> <t:0:R>!");
155 assert_eq!(plain, "Party at 2021-04-20 21:20 UTC, be there 1970-01-01 00:00 UTC!");
156 assert_eq!(spans, vec![
157 TextSpan::Color(ColorSpan { from: 0, to: 5, effect: Effect::Rainbow, colors: vec![] }),
158 TextSpan::Color(ColorSpan { from: 31, to: 39, effect: Effect::Solid, colors: vec!["#f472b6".into()] }),
159 TextSpan::Time(TimeSpan { from: 9, to: 29, unix: 1_618_953_600, style: 'F' }),
160 TextSpan::Time(TimeSpan { from: 40, to: 60, unix: 0, style: 'R' }),
161 ]);
162 let chars: Vec<char> = plain.chars().collect();
163 assert_eq!(chars[31..39].iter().collect::<String>(), "be there", "colour shifted past the time");
164 }
165
166 #[test]
167 fn a_colour_around_a_time_stretches_with_it() {
168 let (plain, spans) = extract("<color teal>doors <t:1618953600:t></color>");
169 assert_eq!(plain, "doors 2021-04-20 21:20 UTC");
170 assert_eq!(spans[0], TextSpan::Color(ColorSpan { from: 0, to: 26, effect: Effect::Solid, colors: vec!["#2dd4bf".into()] }));
171 }
172
173 #[test]
174 fn tags_round_trip_through_the_wire() {
175 let (plain, spans) = extract("go <t:1618953630:R> <rainbow>now</rainbow>");
176 let tags: Vec<nostr_sdk::prelude::Tag> = to_nostr_tags(&spans).collect();
177 let mut back = from_tags(tags.iter(), &plain);
178 let mut want = spans.clone();
179 back.sort_by_key(|s| format!("{s:?}"));
180 want.sort_by_key(|s| format!("{s:?}"));
181 assert_eq!(back, want);
182 let stored: Vec<Vec<String>> = spans.iter().map(|s| s.to_tag_parts()).collect();
183 assert_eq!(from_stored(&stored, &plain).len(), 2);
184 let doubled: Vec<Vec<String>> = stored.iter().chain(stored.iter()).cloned().collect();
185 assert_eq!(from_stored(&doubled, &plain).iter().filter(|s| matches!(s, TextSpan::Time(_))).count(), 1, "one chip per range");
186 assert!(from_tags(tags.iter(), "something else entirely").iter().all(|s| matches!(s, TextSpan::Color(_))), "a time can't cover other text");
187 }
188
189 #[test]
192 fn shared_cases_match_the_js_extractor() {
193 let cases: Vec<serde_json::Value> = serde_json::from_str(include_str!("text_spans_cases.json")).unwrap();
194 for case in cases {
195 let input = case["input"].as_str().unwrap();
196 let (plain, spans) = extract(input);
197 assert_eq!(plain, case["plain"].as_str().unwrap(), "plain of {input:?}");
198 assert_eq!(serde_json::to_value(&spans).unwrap(), case["spans"], "spans of {input:?}");
199 }
200 }
201
202 #[test]
203 fn serde_names_the_kind() {
204 let json = serde_json::to_string(&TextSpan::Time(TimeSpan { from: 1, to: 2, unix: 3, style: 'R' })).unwrap();
205 assert_eq!(json, r#"{"kind":"time","from":1,"to":2,"unix":3,"style":"R"}"#);
206 let json = serde_json::to_string(&TextSpan::Color(ColorSpan { from: 0, to: 1, effect: Effect::Rainbow, colors: vec![] })).unwrap();
207 assert_eq!(json, r#"{"kind":"color","from":0,"to":1,"effect":"rainbow"}"#);
208 }
209}