use std::num::{NonZeroU16, NonZeroU32};
use std::ops::Range;
use crate::console_api::map_render_error;
use crate::layout::render_options;
use crate::{
Doc, HumanLayoutError, HumanLayoutOptions, PreparedDoc, Theme, TokenId, TokenStyle, tokens,
};
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StyledRun {
text: String,
token: TokenId,
style: TokenStyle,
}
impl StyledRun {
pub fn text(&self) -> &str {
&self.text
}
pub const fn token(&self) -> &TokenId {
&self.token
}
pub const fn style(&self) -> TokenStyle {
self.style
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct StyledLine {
runs: Vec<StyledRun>,
}
impl StyledLine {
pub fn runs(&self) -> &[StyledRun] {
&self.runs
}
pub fn text(&self) -> String {
self.runs.iter().map(StyledRun::text).collect()
}
}
impl Doc {
pub fn render_styled(
&self,
width: NonZeroU16,
theme: &Theme,
options: HumanLayoutOptions,
) -> Result<Vec<StyledLine>, HumanLayoutError> {
self.prepare()?.render_styled(width, theme, options)
}
}
impl PreparedDoc {
pub fn render_styled(
&self,
width: NonZeroU16,
theme: &Theme,
options: HumanLayoutOptions,
) -> Result<Vec<StyledLine>, HumanLayoutError> {
let mut workspace = laidout::RenderWorkspace::growable();
let rendered = laidout::render_into(
self.inner(),
render_options(NonZeroU32::from(width), options),
&mut workspace,
)
.map_err(map_render_error)?;
let resolved: Vec<(Range<usize>, &TokenId)> = rendered
.resolved_spans()
.map(|(span, token)| (span.range.clone(), token))
.collect();
Ok(build_lines(rendered.text(), &resolved, theme))
}
}
fn build_lines(text: &str, spans: &[(Range<usize>, &TokenId)], theme: &Theme) -> Vec<StyledLine> {
let mut lines = vec![StyledLine::default()];
if text.is_empty() {
return lines;
}
let mut boundaries = Vec::with_capacity(spans.len().saturating_mul(2).saturating_add(2));
boundaries.push(0);
boundaries.push(text.len());
for (range, _) in spans {
boundaries.push(range.start);
boundaries.push(range.end);
}
boundaries.sort_unstable();
boundaries.dedup();
for pair in boundaries.windows(2) {
let segment = pair[0]..pair[1];
if segment.is_empty() {
continue;
}
let mut covering: Vec<(usize, &Range<usize>, &TokenId)> = spans
.iter()
.enumerate()
.filter(|(_, (range, _))| range.start <= segment.start && segment.end <= range.end)
.map(|(index, (range, token))| (index, range, *token))
.collect();
covering.sort_by(|left, right| {
left.1
.start
.cmp(&right.1.start)
.then(right.1.end.cmp(&left.1.end))
.then(left.0.cmp(&right.0))
});
let style = theme.resolve_stack(covering.iter().map(|(_, _, token)| *token));
let token = covering
.last()
.map_or(tokens::TEXT, |(_, _, token)| (*token).clone());
let mut remainder = &text[segment];
loop {
match remainder.split_once('\n') {
Some((piece, rest)) => {
push_run(
lines.last_mut().expect("line list is never empty"),
piece,
&token,
style,
);
lines.push(StyledLine::default());
remainder = rest;
}
None => {
push_run(
lines.last_mut().expect("line list is never empty"),
remainder,
&token,
style,
);
break;
}
}
}
}
lines
}
fn push_run(line: &mut StyledLine, text: &str, token: &TokenId, style: TokenStyle) {
if text.is_empty() {
return;
}
if let Some(last) = line.runs.last_mut()
&& last.token == *token
&& last.style == style
{
last.text.push_str(text);
return;
}
line.runs.push(StyledRun {
text: text.to_owned(),
token: token.clone(),
style,
});
}