use std::{
ops::Range,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
};
use parking_lot::Mutex;
use super::{
names,
recipe::{Case, Name, Recipe, ResolvedPart, ResolvedRecipe},
theme::{Themed, current_theme},
};
use crate::{
app::{
component::Component,
ctx::Ctx,
theme::{BorderSize, PaletteColor, Theme, TypographyStyle},
},
components::TextHighlight,
core::ElementRef,
layout::{
quad::RichTextSpan,
text_style::{FontWeight, TextStyle},
},
node::{BackgroundColor, Element, Node, NodeUpdate, TextColor, border::Border},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum HighlightPart {
Root,
Mark,
Current,
}
names!(HighlightPart {
Root => "root",
Mark => "mark",
Current => "current",
});
pub type HighlightRenderer = Arc<dyn Fn(HighlightView) -> Element + Send + Sync>;
#[derive(Clone)]
pub struct Highlight {
text: Arc<str>,
marks: Vec<Range<usize>>,
current: Option<usize>,
keep_weight: bool,
states: Vec<Name>,
rules: Recipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl Highlight {
pub fn new(text: &str) -> Self {
Self {
text: Arc::from(text),
marks: Vec::new(),
current: None,
keep_weight: false,
states: Vec::new(),
rules: Recipe::new(),
id: None,
key: None,
}
}
pub fn mark(mut self, range: Range<usize>) -> Self {
self.marks.push(range);
self
}
pub fn marks(mut self, ranges: impl IntoIterator<Item = Range<usize>>) -> Self {
self.marks.extend(ranges);
self
}
pub fn current(mut self, current: Option<usize>) -> Self {
self.current = current;
self
}
pub fn keep_weight(mut self, keep: bool) -> Self {
self.keep_weight = keep;
self
}
pub fn state(mut self, state: impl Into<Name>, on: bool) -> Self {
let state = state.into();
self.states.retain(|held| *held != state);
if on {
self.states.push(state);
}
self
}
pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(super::PartStyle) -> super::PartStyle) -> Self {
self.rules = self.rules.base(part, style);
self
}
pub fn rules(mut self, rules: &Recipe) -> Self {
self.rules = self.rules.extend(rules);
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
fn current_range(&self) -> Option<Range<usize>> {
self.current.and_then(|index| self.marks.get(index).cloned())
}
pub fn mount(self, ctx: &mut Ctx) -> Element {
let key = self.key.clone();
let mut element = ctx.mount::<HighlightHost>(HighlightProps { highlight: self });
if let Some(key) = key {
element = element.key(key);
}
element
}
pub fn build(self, theme: &Theme) -> Element {
self.view(theme, None)
}
pub(crate) fn fills_in(self, theme: &Theme) -> Vec<TextHighlight> {
let view = HighlightView {
text: self.text,
marks: self.marks,
current: self.current,
keep_weight: true,
recipe: theme.resolve::<Highlight>(&Case::new().breakpoint(super::current_breakpoint()), Some(&self.rules)),
text_ref: None,
id: None,
key: None,
};
view.fills()
}
fn view(self, theme: &Theme, text_ref: Option<ElementRef>) -> Element {
let mut case = Case::new().breakpoint(super::current_breakpoint());
for state in &self.states {
case = case.state(state.clone(), true);
}
let view = HighlightView {
text: self.text,
marks: self.marks,
current: self.current,
keep_weight: self.keep_weight,
recipe: theme
.resolve::<Highlight>(&case, Some(&self.rules))
.owned_by(self.id.as_ref()),
text_ref,
id: self.id,
key: self.key,
};
match theme.renderer::<Highlight>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
impl From<Highlight> for Element {
fn from(highlight: Highlight) -> Self {
highlight.build(¤t_theme())
}
}
#[derive(Clone)]
struct HighlightProps {
highlight: Highlight,
}
impl PartialEq for HighlightProps {
fn eq(&self, _: &Self) -> bool {
false
}
}
impl crate::app::component::DevtoolsInspectable for HighlightProps {}
struct HighlightHost {
shown: Mutex<Option<Range<usize>>>,
rendered: AtomicBool,
text: ElementRef,
}
impl Component for HighlightHost {
type Props = HighlightProps;
fn create(_: &mut Ctx) -> Self {
Self {
shown: Mutex::new(None),
rendered: AtomicBool::new(false),
text: ElementRef::new(),
}
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
let HighlightProps { highlight } = ctx.props::<HighlightProps>().clone();
let current = highlight.current_range();
let first = !self.rendered.swap(true, Ordering::Relaxed);
let changed = {
let mut shown = self.shown.lock();
let changed = *shown != current;
shown.clone_from(¤t);
changed
};
if changed
&& !first
&& let Some(range) = current
{
ctx.scroll_range_into_view(&self.text, range);
}
highlight.view(¤t_theme(), Some(self.text.clone()))
}
}
pub struct HighlightView {
pub text: Arc<str>,
pub marks: Vec<Range<usize>>,
pub current: Option<usize>,
pub keep_weight: bool,
pub recipe: ResolvedRecipe,
text_ref: Option<ElementRef>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl HighlightView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn fill(&self, range: Range<usize>, part: impl Into<Name>) -> Option<TextHighlight> {
fill_of(&self.part(part), range)
}
pub fn fills(&self) -> Vec<TextHighlight> {
self
.marks
.iter()
.enumerate()
.filter_map(|(index, range)| {
let part = if Some(index) == self.current {
HighlightPart::Current
} else {
HighlightPart::Mark
};
self.fill(range.clone(), part)
})
.collect()
}
fn weight_of(&self, index: usize, text: FontWeight) -> Option<FontWeight> {
if self.keep_weight {
return None;
}
let part = if Some(index) == self.current {
HighlightPart::Current
} else {
HighlightPart::Mark
};
self.part(part).rest().text.weight.filter(|weight| *weight != text)
}
pub fn runs(&self, style: &TextStyle) -> Option<Vec<RichTextSpan>> {
let mut marks: Vec<(Range<usize>, FontWeight)> = self
.marks
.iter()
.enumerate()
.filter_map(|(index, range)| Some((range.clone(), self.weight_of(index, style.weight)?)))
.filter(|(range, _)| {
range.start < range.end
&& range.end <= self.text.len()
&& self.text.is_char_boundary(range.start)
&& self.text.is_char_boundary(range.end)
})
.collect();
if marks.is_empty() {
return None;
}
marks.sort_by_key(|(range, _)| range.start);
let run = |text: &str, weight: FontWeight| RichTextSpan {
text: text.to_owned(),
style: TextStyle {
weight,
..style.clone()
},
};
let mut runs = Vec::new();
let mut at = 0;
for (range, weight) in marks {
let start = range.start.max(at);
if start >= range.end {
continue;
}
if at < start {
runs.push(run(&self.text[at..start], style.weight));
}
runs.push(run(&self.text[start..range.end], weight));
at = range.end;
}
if at < self.text.len() {
runs.push(run(&self.text[at..], style.weight));
}
Some(runs)
}
pub fn render(self) -> Element {
let part = self.part(HighlightPart::Root);
let style = part.rest().text.resolve(self.theme());
if let Some(runs) = self.runs(&style) {
let mut node = Node::rich_text(runs);
part.apply(&mut node);
node.set_text_highlights(self.fills());
if let Some(reference) = &self.text_ref {
NodeUpdate::ref_element(&mut node, reference.clone());
}
if let Some(id) = &self.id {
node = node.id(id.clone());
}
let mut element = Element::from_node(node);
if let Some(key) = &self.key {
element = element.key(key.clone());
}
return element;
}
let mut text = part.text(&self.text).part(&part).highlights(self.fills());
if let Some(reference) = &self.text_ref {
text = text.ref_element(reference.clone());
}
if let Some(id) = &self.id {
text = text.id(id.clone());
}
let mut element: Element = text.into();
if let Some(key) = &self.key {
element = element.key(key.clone());
}
element
}
}
pub(crate) fn fill_of(part: &ResolvedPart, range: Range<usize>) -> Option<TextHighlight> {
let theme = part.theme();
let style = part.rest();
let as_text = |color: BackgroundColor| match color {
BackgroundColor::Color(color) => TextColor::Color(color),
BackgroundColor::Palette(role) => TextColor::Palette(role),
BackgroundColor::CurrentForeground => TextColor::Palette(PaletteColor::Foreground),
};
let color = as_text(style.background.clone()?);
let radius = style
.radius
.map(|radius| radius.resolve(&theme.radii()).top_left)
.unwrap_or(0.0);
let spacing = theme.spacing();
let [top, end, _, start] = style.paddings();
let pad = |side: Option<crate::node::SpacingValue>| side.map_or(0.0, |side| side.resolve(&spacing, 0.0));
let mut fill = TextHighlight::new(range, color)
.radius(radius)
.padding(pad(start).max(pad(end)), pad(top));
if let Some(edge) = &style.border {
let width = edge.width.resolve(&theme.border_sizes());
fill = fill.border(width, as_text(edge.color.clone()));
}
Some(fill)
}
impl crate::ui::Styled for Highlight {
type Component = Self;
fn rules(self, rules: &crate::ui::Recipe) -> Self {
Self::rules(self, rules)
}
fn state(self, state: impl Into<crate::ui::Name>, on: bool) -> Self {
Self::state(self, state, on)
}
}
impl Themed for Highlight {
const NAME: &'static str = "highlight";
type Renderer = HighlightRenderer;
fn parts() -> crate::ui::Declared {
HighlightPart::declared()
}
fn recipe() -> Recipe {
use HighlightPart::{Current, Mark, Root};
use PaletteColor::{Foreground, Warning, WarningMuted};
let mark = |s: super::PartStyle| {
s.background(WarningMuted)
.radius(2.0)
.padding_x(3.0)
.padding_y(1.0)
.weight(FontWeight::Medium)
};
Recipe::new()
.base(Root, |s| s.typography(TypographyStyle::Body).foreground(Foreground))
.base(Mark, mark)
.base(Current, |s| mark(s).border(Border::inside(BorderSize::Md, Warning)))
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct FindOptions {
pub match_case: bool,
pub whole_word: bool,
pub regex: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FindError {
InvalidPattern(String),
RegexUnavailable,
}
impl std::fmt::Display for FindError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::InvalidPattern(why) => write!(formatter, "not a regular expression: {why}"),
Self::RegexUnavailable => formatter.write_str("lurq was built without the `regex` feature"),
}
}
}
impl std::error::Error for FindError {}
pub fn find_matches(text: &str, query: &str, options: FindOptions) -> Result<Vec<Range<usize>>, FindError> {
if query.is_empty() {
return Ok(Vec::new());
}
if options.regex {
return find_pattern(text, query, options);
}
let mut found = Vec::new();
let mut at = 0;
while at < text.len() {
match match_at(text, at, query, options.match_case) {
Some(end) if !options.whole_word || whole_word(text, at, end) => {
found.push(at..end);
at = end;
}
_ => at += text[at..].chars().next().map_or(1, char::len_utf8),
}
}
Ok(found)
}
fn match_at(text: &str, at: usize, query: &str, match_case: bool) -> Option<usize> {
let mut rest = text[at..].char_indices();
let mut end = at;
for wanted in query.chars() {
let (offset, found) = rest.next()?;
let same = if match_case {
found == wanted
} else {
found == wanted || found.to_lowercase().eq(wanted.to_lowercase())
};
if !same {
return None;
}
end = at + offset + found.len_utf8();
}
Some(end)
}
fn whole_word(text: &str, start: usize, end: usize) -> bool {
let wordy = |c: char| c.is_alphanumeric() || c == '_';
!text[..start].chars().next_back().is_some_and(wordy) && !text[end..].chars().next().is_some_and(wordy)
}
#[cfg(feature = "regex")]
fn find_pattern(text: &str, query: &str, options: FindOptions) -> Result<Vec<Range<usize>>, FindError> {
let pattern = regex::RegexBuilder::new(query)
.case_insensitive(!options.match_case)
.build()
.map_err(|error| FindError::InvalidPattern(error.to_string()))?;
Ok(
pattern
.find_iter(text)
.filter(|found| !found.is_empty())
.filter(|found| !options.whole_word || whole_word(text, found.start(), found.end()))
.map(|found| found.range())
.collect(),
)
}
#[cfg(not(feature = "regex"))]
fn find_pattern(_: &str, _: &str, _: FindOptions) -> Result<Vec<Range<usize>>, FindError> {
Err(FindError::RegexUnavailable)
}