rho-coding-agent 3.10.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Hyperlinks carried through text layout. Renderers build [`LinkedRun`]s,
//! wrap them into rows, and record where each link landed as [`RowLink`]s:
//! a row and the display columns it covers there. The history pane turns
//! visible row links into the screen links the terminal backend writes as
//! OSC 8 hyperlinks. Nothing here knows what a link points at.

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;

/// A run of styled text, part of a link when `link` is set.
#[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),
        }
    }
}

/// `runs` as spans, and the links over their concatenated text.
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))
}

/// A link over a byte range of a text that is about to be wrapped.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct TextLink {
    pub(super) bytes: Range<usize>,
    pub(super) url: Arc<str>,
}

/// The links over the concatenated text of `runs`, joining neighbouring
/// runs of one link (a path's folders, name, and line) into one.
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
}

/// A link on one rendered row: `columns` are display columns of that row.
#[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 {
    /// This link moved `rows` down and `columns` right.
    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),
        }
    }
}

/// Rendered rows and the links on them.
#[derive(Clone, Debug, Default)]
pub(super) struct LinkedLines {
    pub(super) lines: Vec<Line<'static>>,
    pub(super) links: Vec<RowLink>,
}

impl LinkedLines {
    /// Puts `other`'s rows after these.
    pub(super) fn append(&mut self, other: Self) {
        other.push_into(&mut self.lines, &mut self.links);
    }

    /// Appends these rows to `lines`, and their links, moved down to the
    /// rows they now sit on, to `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);
    }

    /// The links on rows `rows`, by row from `rows.start`.
    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()
    }
}

/// Records in `out` the parts of `links` on a row that shows
/// `text[row_bytes]` from display column `first_column`.
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),
        });
    }
}