use std::{ops::Range, sync::Arc};
use ratatui::{
style::Style,
text::{Line, Span},
};
use super::render::display_width;
#[cfg(test)]
#[path = "text_links_tests.rs"]
mod tests;
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct LinkedRun {
pub(super) text: String,
pub(super) style: Style,
pub(super) link: Option<Arc<str>>,
}
impl LinkedRun {
pub(super) fn plain(text: impl Into<String>, style: Style) -> Self {
Self {
text: text.into(),
style,
link: None,
}
}
pub(super) fn linked(text: impl Into<String>, style: Style, link: Arc<str>) -> Self {
Self {
text: text.into(),
style,
link: Some(link),
}
}
}
pub(super) fn spans_and_links(runs: &[LinkedRun]) -> (Vec<Span<'static>>, Vec<TextLink>) {
let spans = runs
.iter()
.map(|run| Span::styled(run.text.clone(), run.style))
.collect();
(spans, text_links(runs))
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct TextLink {
pub(super) bytes: Range<usize>,
pub(super) url: Arc<str>,
}
fn text_links(runs: &[LinkedRun]) -> Vec<TextLink> {
let mut links: Vec<TextLink> = Vec::new();
let mut offset = 0;
for run in runs {
let bytes = offset..offset + run.text.len();
offset = bytes.end;
let Some(url) = &run.link else {
continue;
};
match links.last_mut() {
Some(last) if last.bytes.end == bytes.start && last.url == *url => {
last.bytes.end = bytes.end;
}
_ => links.push(TextLink {
bytes,
url: Arc::clone(url),
}),
}
}
links
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct RowLink {
pub(super) row: usize,
pub(super) columns: Range<usize>,
pub(super) url: Arc<str>,
}
impl RowLink {
pub(super) fn shifted(&self, rows: usize, columns: usize) -> Self {
Self {
row: self.row + rows,
columns: self.columns.start + columns..self.columns.end + columns,
url: Arc::clone(&self.url),
}
}
}
#[derive(Clone, Debug, Default)]
pub(super) struct LinkedLines {
pub(super) lines: Vec<Line<'static>>,
pub(super) links: Vec<RowLink>,
}
impl LinkedLines {
pub(super) fn append(&mut self, other: Self) {
other.push_into(&mut self.lines, &mut self.links);
}
pub(super) fn push_into(self, lines: &mut Vec<Line<'static>>, links: &mut Vec<RowLink>) {
let top = lines.len();
links.extend(self.links.iter().map(|link| link.shifted(top, 0)));
lines.extend(self.lines);
}
pub(super) fn links_in(&self, rows: Range<usize>) -> Vec<RowLink> {
self.links
.iter()
.filter(|link| rows.contains(&link.row))
.map(|link| RowLink {
row: link.row - rows.start,
..link.clone()
})
.collect()
}
}
pub(super) fn place_on_row(
links: &[TextLink],
text: &str,
row_bytes: Range<usize>,
row: usize,
first_column: usize,
out: &mut Vec<RowLink>,
) {
for link in links {
let start = link.bytes.start.max(row_bytes.start);
let end = link.bytes.end.min(row_bytes.end);
if start >= end {
continue;
}
let left = first_column + display_width(&text[row_bytes.start..start]);
let right = left + display_width(&text[start..end]);
out.push(RowLink {
row,
columns: left..right,
url: Arc::clone(&link.url),
});
}
}