Add background styling to span / rich text

This commit is contained in:
Cory Forsstrom 2024-07-23 13:36:40 -07:00 committed by Héctor Ramón Jiménez
parent 23a7e9f981
commit ddcf02f9d0
No known key found for this signature in database
GPG key ID: 7CC46565708259A7
7 changed files with 141 additions and 16 deletions

View file

@ -2,7 +2,7 @@
use crate::core;
use crate::core::alignment;
use crate::core::text::{Hit, Shaping, Span, Text};
use crate::core::{Font, Point, Size};
use crate::core::{Font, Point, Rectangle, Size};
use crate::text;
use std::fmt;
@ -251,6 +251,57 @@ impl core::text::Paragraph for Paragraph {
Some(glyph.metadata)
}
fn span_bounds(&self, index: usize) -> Vec<Rectangle> {
let internal = self.internal();
let mut current_bounds = None;
let mut bounds = internal
.buffer
.layout_runs()
.flat_map(|run| {
let line_top = run.line_top;
let line_height = run.line_height;
run.glyphs
.iter()
.map(move |glyph| (line_top, line_height, glyph))
})
.skip_while(|(_, _, glyph)| glyph.metadata != index)
.take_while(|(_, _, glyph)| glyph.metadata == index)
.fold(vec![], |mut spans, (line_top, line_height, glyph)| {
let y = line_top + glyph.y;
let new_bounds = || {
Rectangle::new(
Point::new(glyph.x, y),
Size::new(
glyph.w,
glyph.line_height_opt.unwrap_or(line_height),
),
)
};
match current_bounds.as_mut() {
None => {
current_bounds = Some(new_bounds());
}
Some(bounds) if y != bounds.y => {
spans.push(*bounds);
*bounds = new_bounds();
}
Some(bounds) => {
bounds.width += glyph.w;
}
}
spans
});
bounds.extend(current_bounds);
bounds
}
fn grapheme_position(&self, line: usize, index: usize) -> Option<Point> {
use unicode_segmentation::UnicodeSegmentation;