use std::{ops::Range, rc::Rc, sync::Arc};
use crate::{ParagraphStyle, SpanStyle};
#[derive(Clone)]
pub enum LinkAnnotation {
Url(String),
Clickable {
tag: String,
handler: Rc<dyn Fn()>,
},
}
impl std::fmt::Debug for LinkAnnotation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Url(url) => f.debug_tuple("Url").field(url).finish(),
Self::Clickable { tag, .. } => f.debug_struct("Clickable").field("tag", tag).finish(),
}
}
}
impl PartialEq for LinkAnnotation {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Url(a), Self::Url(b)) => a == b,
(
Self::Clickable {
tag: ta,
handler: ha,
},
Self::Clickable {
tag: tb,
handler: hb,
},
) => ta == tb && Rc::ptr_eq(ha, hb),
_ => false,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct StringAnnotation {
pub tag: String,
pub annotation: String,
}
#[derive(Debug, Clone, PartialEq)]
pub enum LinkKey {
Url(String),
Clickable(String),
}
#[derive(Debug, Clone)]
pub struct RenderString {
text: String,
span_styles: Box<[RangeStyle<SpanStyle>]>,
extras: Option<Box<RenderExtras>>,
hash: u64,
}
#[derive(Debug, Clone, Default, PartialEq)]
struct RenderExtras {
paragraph_styles: Box<[RangeStyle<ParagraphStyle>]>,
string_annotations: Box<[RangeStyle<StringAnnotation>]>,
links: Box<[RangeStyle<LinkKey>]>,
}
impl Default for RenderString {
fn default() -> Self {
Self::plain(String::new())
}
}
impl PartialEq for RenderString {
fn eq(&self, other: &Self) -> bool {
self.hash == other.hash
&& self.text == other.text
&& self.span_styles == other.span_styles
&& self.extras == other.extras
}
}
const _: () = {
fn assert_send<T: Send + Sync>() {}
#[expect(dead_code, reason = "a compile-time check that is never called")]
fn assert_render_string_is_send_sync() {
assert_send::<RenderString>();
}
};
impl RenderString {
fn from_parts(
text: String,
span_styles: Vec<RangeStyle<SpanStyle>>,
paragraph_styles: Vec<RangeStyle<ParagraphStyle>>,
string_annotations: Vec<RangeStyle<StringAnnotation>>,
links: Vec<RangeStyle<LinkKey>>,
) -> Self {
let hash = render_hash_impl(&text, &span_styles, ¶graph_styles);
let extras =
(!paragraph_styles.is_empty() || !string_annotations.is_empty() || !links.is_empty())
.then(|| {
Box::new(RenderExtras {
paragraph_styles: paragraph_styles.into_boxed_slice(),
string_annotations: string_annotations.into_boxed_slice(),
links: links.into_boxed_slice(),
})
});
Self {
text,
span_styles: span_styles.into_boxed_slice(),
extras,
hash,
}
}
pub(crate) fn plain(text: String) -> Self {
let hash = render_hash_impl(&text, &[], &[]);
Self {
text,
span_styles: Box::default(),
extras: None,
hash,
}
}
pub(crate) fn plain_capacity(&self) -> Option<usize> {
(self.span_styles.is_empty() && self.extras.is_none()).then_some(self.text.capacity())
}
pub(crate) fn refill_plain(&mut self, text: &str) {
self.text.clear();
self.text.push_str(text);
self.hash = render_hash_impl(&self.text, &[], &[]);
}
pub fn text(&self) -> &str {
&self.text
}
pub fn span_styles(&self) -> &[RangeStyle<SpanStyle>] {
&self.span_styles
}
pub fn paragraph_styles(&self) -> &[RangeStyle<ParagraphStyle>] {
self.extras
.as_deref()
.map_or(&[], |extras| &extras.paragraph_styles)
}
pub fn string_annotations(&self) -> &[RangeStyle<StringAnnotation>] {
self.extras
.as_deref()
.map_or(&[], |extras| &extras.string_annotations)
}
pub fn links(&self) -> &[RangeStyle<LinkKey>] {
self.extras.as_deref().map_or(&[], |extras| &extras.links)
}
pub fn len(&self) -> usize {
self.text.len()
}
pub fn is_empty(&self) -> bool {
self.text.is_empty()
}
pub fn span_boundaries(&self) -> SpanBoundaries {
span_boundaries_impl(&self.text, &self.span_styles)
}
pub fn render_hash(&self) -> u64 {
self.hash
}
pub fn subsequence(&self, range: Range<usize>) -> Self {
let start = range.start.min(self.text.len());
let end = range.end.max(start).min(self.text.len());
if start == end {
return Self::default();
}
Self::from_parts(
self.text[start..end].to_string(),
clip_range_styles(&self.span_styles, start, end),
clip_range_styles(self.paragraph_styles(), start, end),
clip_range_styles(self.string_annotations(), start, end),
clip_range_styles(self.links(), start, end),
)
}
}
fn intersect(a: &Range<usize>, b: &Range<usize>) -> bool {
a.start.max(b.start) < a.end.min(b.end) || contains(a, b) || contains(b, a)
}
fn contains(base: &Range<usize>, target: &Range<usize>) -> bool {
base.start <= target.start
&& target.end <= base.end
&& (base.end != target.end || (target.start == target.end) == (base.start == base.end))
}
fn clip_range_styles<T: Clone>(
styles: &[RangeStyle<T>],
start: usize,
end: usize,
) -> Vec<RangeStyle<T>> {
let mut clipped = Vec::new();
for style in styles {
let intersection_start = style.range.start.max(start);
let intersection_end = style.range.end.min(end);
if intersection_start < intersection_end {
clipped.push(RangeStyle {
item: style.item.clone(),
range: (intersection_start - start)..(intersection_end - start),
});
}
}
clipped
}
pub type SpanBoundaries = smallvec::SmallVec<[usize; 8]>;
fn span_boundaries_impl(text: &str, span_styles: &[RangeStyle<SpanStyle>]) -> SpanBoundaries {
let mut boundaries: SpanBoundaries = smallvec::smallvec![0, text.len()];
for span in span_styles {
boundaries.push(span.range.start);
boundaries.push(span.range.end);
}
boundaries.sort_unstable();
boundaries.dedup();
boundaries.retain(|boundary| *boundary <= text.len() && text.is_char_boundary(*boundary));
boundaries
}
fn render_hash_impl(
text: &str,
span_styles: &[RangeStyle<SpanStyle>],
paragraph_styles: &[RangeStyle<ParagraphStyle>],
) -> u64 {
use std::hash::{Hash, Hasher};
let mut hasher = cranpose_ui_graphics::FxHasher::default();
text.hash(&mut hasher);
span_styles.len().hash(&mut hasher);
for span in span_styles {
span.range.start.hash(&mut hasher);
span.range.end.hash(&mut hasher);
span.item.render_hash().hash(&mut hasher);
}
paragraph_styles.len().hash(&mut hasher);
for paragraph in paragraph_styles {
paragraph.range.start.hash(&mut hasher);
paragraph.range.end.hash(&mut hasher);
paragraph.item.render_hash().hash(&mut hasher);
}
hasher.finish()
}
type LinkHandler = Rc<dyn Fn()>;
static EMPTY: std::sync::LazyLock<Arc<RenderString>> =
std::sync::LazyLock::new(|| Arc::new(RenderString::plain(String::new())));
#[derive(Clone)]
pub struct AnnotatedString {
content: Arc<RenderString>,
handlers: Option<Rc<[LinkHandler]>>,
}
impl Default for AnnotatedString {
fn default() -> Self {
Self {
content: Arc::clone(&EMPTY),
handlers: None,
}
}
}
impl std::fmt::Debug for AnnotatedString {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AnnotatedString")
.field("content", &self.content)
.field(
"handlers",
&self.handlers.as_ref().map_or(0, |handlers| handlers.len()),
)
.finish()
}
}
impl PartialEq for AnnotatedString {
fn eq(&self, other: &Self) -> bool {
let same_handlers = match (&self.handlers, &other.handlers) {
(None, None) => true,
(Some(a), Some(b)) => {
a.len() == b.len() && a.iter().zip(b.iter()).all(|(a, b)| Rc::ptr_eq(a, b))
}
_ => false,
};
(Arc::ptr_eq(&self.content, &other.content) || *self.content == *other.content)
&& same_handlers
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct RangeStyle<T> {
pub item: T,
pub range: Range<usize>,
}
impl AnnotatedString {
pub(crate) fn into_plain_content(self) -> Option<Arc<RenderString>> {
self.handlers.is_none().then_some(self.content)
}
pub fn new(text: String) -> Self {
if text.is_empty() {
return Self::default();
}
Self {
content: Arc::new(RenderString::plain(text)),
handlers: None,
}
}
fn of_parts(content: RenderString, handlers: Vec<LinkHandler>) -> Self {
Self {
content: Arc::new(content),
handlers: (!handlers.is_empty()).then(|| Rc::from(handlers)),
}
}
pub fn builder() -> Builder {
Builder::new()
}
pub fn text(&self) -> &str {
&self.content.text
}
pub fn is_plain(&self, text: &str) -> bool {
self.handlers.is_none()
&& self.content.span_styles.is_empty()
&& self.content.extras.is_none()
&& self.content.text == text
}
pub fn span_styles(&self) -> &[RangeStyle<SpanStyle>] {
&self.content.span_styles
}
pub fn paragraph_styles(&self) -> &[RangeStyle<ParagraphStyle>] {
self.content.paragraph_styles()
}
pub fn string_annotations(&self) -> &[RangeStyle<StringAnnotation>] {
self.content.string_annotations()
}
pub fn has_link_annotations(&self, start: usize, end: usize) -> bool {
self.content
.links()
.iter()
.any(|link| intersect(&link.range, &(start..end)))
}
pub fn len(&self) -> usize {
self.content.text.len()
}
pub fn is_empty(&self) -> bool {
self.content.text.is_empty()
}
pub fn span_boundaries(&self) -> SpanBoundaries {
self.content.span_boundaries()
}
pub fn render_string(&self) -> &Arc<RenderString> {
&self.content
}
pub fn span_measurement_hash(&self) -> u64 {
use std::hash::Hasher;
let spans = self.span_styles();
let mut hasher = cranpose_ui_graphics::FxHasher::default();
hasher.write_usize(spans.len());
for span in spans {
hasher.write_usize(span.range.start);
hasher.write_usize(span.range.end);
crate::style::hash_span_measurement(&span.item, &mut hasher);
}
hasher.finish()
}
pub fn render_hash(&self) -> u64 {
self.content.hash
}
pub fn map_span_styles(&self, mut map: impl FnMut(&mut SpanStyle)) -> Self {
let mut content = RenderString::clone(&self.content);
for span in &mut content.span_styles {
map(&mut span.item);
}
content.hash = render_hash_impl(
&content.text,
&content.span_styles,
content.paragraph_styles(),
);
Self {
content: Arc::new(content),
handlers: self.handlers.clone(),
}
}
pub fn subsequence(&self, range: Range<usize>) -> Self {
let range = clamp_subsequence_range(self.text(), range);
if range.is_empty() {
return Self::default();
}
Builder::new()
.append_annotated_subsequence(self, range)
.to_annotated_string()
}
pub fn get_string_annotations(
&self,
tag: &str,
start: usize,
end: usize,
) -> Vec<&RangeStyle<StringAnnotation>> {
self.string_annotations()
.iter()
.filter(|ann| ann.item.tag == tag && intersect(&ann.range, &(start..end)))
.collect()
}
pub fn get_link_annotations(
&self,
start: usize,
end: usize,
) -> Vec<RangeStyle<LinkAnnotation>> {
self.link_annotations()
.filter(|ann| intersect(&ann.range, &(start..end)))
.collect()
}
fn link_annotations(&self) -> impl Iterator<Item = RangeStyle<LinkAnnotation>> + '_ {
let mut handlers = self.handlers.iter().flat_map(|handlers| handlers.iter());
self.content.links().iter().map(move |link| RangeStyle {
item: match &link.item {
LinkKey::Url(url) => LinkAnnotation::Url(url.clone()),
LinkKey::Clickable(tag) => LinkAnnotation::Clickable {
tag: tag.clone(),
handler: Rc::clone(
handlers.next().expect("a clickable link holds its handler"),
),
},
},
range: link.range.clone(),
})
}
}
impl From<String> for AnnotatedString {
fn from(text: String) -> Self {
Self::new(text)
}
}
impl From<Arc<RenderString>> for AnnotatedString {
fn from(content: Arc<RenderString>) -> Self {
Self {
content,
handlers: None,
}
}
}
impl From<&str> for AnnotatedString {
fn from(text: &str) -> Self {
Self::new(text.to_owned())
}
}
impl From<&String> for AnnotatedString {
fn from(text: &String) -> Self {
Self::new(text.clone())
}
}
impl From<&mut String> for AnnotatedString {
fn from(text: &mut String) -> Self {
Self::new(text.clone())
}
}
#[derive(Debug, Default, Clone)]
pub struct Builder {
text: String,
span_styles: Vec<MutableRange<SpanStyle>>,
paragraph_styles: Vec<MutableRange<ParagraphStyle>>,
string_annotations: Vec<MutableRange<StringAnnotation>>,
link_annotations: Vec<MutableRange<LinkAnnotation>>,
style_stack: Vec<StyleStackRecord>,
}
#[derive(Debug, Clone)]
struct MutableRange<T> {
item: T,
start: usize,
end: usize,
}
#[derive(Debug, Clone)]
struct StyleStackRecord {
style_type: StyleType,
index: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum StyleType {
Span,
Paragraph,
StringAnnotation,
LinkAnnotation,
}
fn clamp_subsequence_range(text: &str, range: Range<usize>) -> Range<usize> {
let start = range.start.min(text.len());
let end = range.end.max(start).min(text.len());
start..end
}
fn finished_ranges<T>(ranges: Vec<MutableRange<T>>) -> Vec<RangeStyle<T>> {
ranges
.into_iter()
.map(|range| RangeStyle {
item: range.item,
range: range.start..range.end,
})
.collect()
}
fn append_clipped_ranges<T: Clone>(
target: &mut Vec<MutableRange<T>>,
source: &[RangeStyle<T>],
source_range: Range<usize>,
target_offset: usize,
) {
for style in source {
let intersection_start = style.range.start.max(source_range.start);
let intersection_end = style.range.end.min(source_range.end);
if intersection_start < intersection_end {
target.push(MutableRange {
item: style.item.clone(),
start: (intersection_start - source_range.start) + target_offset,
end: (intersection_end - source_range.start) + target_offset,
});
}
}
}
impl Builder {
pub fn new() -> Self {
Self::default()
}
pub fn append(mut self, text: &str) -> Self {
self.text.push_str(text);
self
}
pub fn append_annotated(self, annotated: &AnnotatedString) -> Self {
self.append_annotated_subsequence(annotated, 0..annotated.len())
}
pub fn append_annotated_subsequence(
mut self,
annotated: &AnnotatedString,
range: Range<usize>,
) -> Self {
let range = clamp_subsequence_range(annotated.text(), range);
if range.is_empty() {
return self;
}
debug_assert!(
annotated.text().is_char_boundary(range.start),
"the clamped range starts on a character"
);
debug_assert!(
annotated.text().is_char_boundary(range.end),
"the clamped range ends on a character"
);
let target_offset = self.text.len();
self.text.push_str(&annotated.text()[range.clone()]);
append_clipped_ranges(
&mut self.span_styles,
annotated.span_styles(),
range.clone(),
target_offset,
);
append_clipped_ranges(
&mut self.paragraph_styles,
annotated.paragraph_styles(),
range.clone(),
target_offset,
);
append_clipped_ranges(
&mut self.string_annotations,
annotated.string_annotations(),
range.clone(),
target_offset,
);
for link in annotated.link_annotations() {
let start = link.range.start.max(range.start);
let end = link.range.end.min(range.end);
if start < end {
self.link_annotations.push(MutableRange {
item: link.item,
start: start - range.start + target_offset,
end: end - range.start + target_offset,
});
}
}
self
}
pub fn push_style(mut self, style: SpanStyle) -> Self {
let index = self.span_styles.len();
self.span_styles.push(MutableRange {
item: style,
start: self.text.len(),
end: usize::MAX,
});
self.style_stack.push(StyleStackRecord {
style_type: StyleType::Span,
index,
});
self
}
pub fn push_paragraph_style(mut self, style: ParagraphStyle) -> Self {
let index = self.paragraph_styles.len();
self.paragraph_styles.push(MutableRange {
item: style,
start: self.text.len(),
end: usize::MAX,
});
self.style_stack.push(StyleStackRecord {
style_type: StyleType::Paragraph,
index,
});
self
}
pub fn push_string_annotation(mut self, tag: &str, annotation: &str) -> Self {
let index = self.string_annotations.len();
self.string_annotations.push(MutableRange {
item: StringAnnotation {
tag: tag.to_string(),
annotation: annotation.to_string(),
},
start: self.text.len(),
end: usize::MAX,
});
self.style_stack.push(StyleStackRecord {
style_type: StyleType::StringAnnotation,
index,
});
self
}
pub fn push_link(mut self, link: LinkAnnotation) -> Self {
let index = self.link_annotations.len();
self.link_annotations.push(MutableRange {
item: link,
start: self.text.len(),
end: usize::MAX,
});
self.style_stack.push(StyleStackRecord {
style_type: StyleType::LinkAnnotation,
index,
});
self
}
pub fn with_link(self, link: LinkAnnotation, block: impl FnOnce(Self) -> Self) -> Self {
let b = self.push_link(link);
let b = block(b);
b.pop()
}
pub fn pop(mut self) -> Self {
if let Some(record) = self.style_stack.pop() {
match record.style_type {
StyleType::Span => {
self.span_styles[record.index].end = self.text.len();
}
StyleType::Paragraph => {
self.paragraph_styles[record.index].end = self.text.len();
}
StyleType::StringAnnotation => {
self.string_annotations[record.index].end = self.text.len();
}
StyleType::LinkAnnotation => {
self.link_annotations[record.index].end = self.text.len();
}
}
}
self
}
pub fn to_annotated_string(mut self) -> AnnotatedString {
while let Some(record) = self.style_stack.pop() {
match record.style_type {
StyleType::Span => {
self.span_styles[record.index].end = self.text.len();
}
StyleType::Paragraph => {
self.paragraph_styles[record.index].end = self.text.len();
}
StyleType::StringAnnotation => {
self.string_annotations[record.index].end = self.text.len();
}
StyleType::LinkAnnotation => {
self.link_annotations[record.index].end = self.text.len();
}
}
}
let mut handlers = Vec::new();
let links = self
.link_annotations
.into_iter()
.map(|link| RangeStyle {
item: match link.item {
LinkAnnotation::Url(url) => LinkKey::Url(url),
LinkAnnotation::Clickable { tag, handler } => {
handlers.push(handler);
LinkKey::Clickable(tag)
}
},
range: link.start..link.end,
})
.collect();
AnnotatedString::of_parts(
RenderString::from_parts(
self.text,
finished_ranges(self.span_styles),
finished_ranges(self.paragraph_styles),
finished_ranges(self.string_annotations),
links,
),
handlers,
)
}
pub fn add_style(mut self, style: SpanStyle, range: Range<usize>) -> Self {
self.span_styles.push(MutableRange {
item: style,
start: range.start,
end: range.end,
});
self
}
}
#[cfg(test)]
#[path = "tests/annotated_string_tests.rs"]
mod tests;