From 13d7118c0683e0943856e898ad9ce9f79a314185 Mon Sep 17 00:00:00 2001 From: Mist Date: Thu, 25 Apr 2024 15:49:44 +0800 Subject: [PATCH] [Perf] add comments for highlight logic --- generator/src/code.rs | 26 +++++++++++++------------- generator/src/highlight.rs | 34 ++++++++++++++++++++++------------ 2 files changed, 35 insertions(+), 25 deletions(-) diff --git a/generator/src/code.rs b/generator/src/code.rs index c1e6cde..e4bbf3f 100644 --- a/generator/src/code.rs +++ b/generator/src/code.rs @@ -10,6 +10,8 @@ fn min_width(width: f32) -> f32 { } } +// Because the code block is input by users, we need to calculate the width and height +// to make sure render the width and height of the "editor" shape correctly pub fn calc_wh(text: &str, char_wdith: f32, line_height: f32) -> (f32, f32) { let trimmed_text = prepare_code(text); let lines = trimmed_text.lines(); @@ -41,22 +43,20 @@ fn trim_space(text: &str) -> String { let head_spaces = Regex::new(r"^(\s*)").unwrap().find(first_line); match head_spaces { - Some(head_spaces) => { - return lines - .into_iter() - .map(|line| { - Regex::new(format!("^{}", head_spaces.as_str()).as_ref()) - .unwrap() - .replace(line, "") - .to_string() - }) - .collect::>() - .join("\n"); - } + Some(head_spaces) => lines + .into_iter() + .map(|line| { + Regex::new(format!("^{}", head_spaces.as_str()).as_ref()) + .unwrap() + .replace(line, "") + .to_string() + }) + .collect::>() + .join("\n"), None => text.to_string(), } } pub fn prepare_code(code: &str) -> String { - replace_tab_to_space(&trim_space(&code)) + trim_space(&replace_tab_to_space(&code)) } diff --git a/generator/src/highlight.rs b/generator/src/highlight.rs index 3d2096f..3df50e1 100644 --- a/generator/src/highlight.rs +++ b/generator/src/highlight.rs @@ -53,6 +53,9 @@ impl Highlight { ))?, }; + // The Syntect clearly distinguish between PHP and PHP Source + // Should use PHP as highlight language if the source content contains " attrs.weight(Weight::BOLD), + FontStyle::ITALIC => attrs.style(Style::Italic), + FontStyle::UNDERLINE => attrs.style(Style::Normal), + _ => attrs, + }; + + (str, attrs.color(cosmic_text::Color::rgb(r, g, b))) + }) + .collect::() + }) .fold(vec![], |acc, cur| [acc, cur].concat()) .into_iter() - .map(move |(style, str)| { - let syntect::highlighting::Color { r, g, b, a: _ } = style.foreground; - let attrs = match style.font_style { - FontStyle::BOLD => attrs.weight(Weight::BOLD), - FontStyle::ITALIC => attrs.style(Style::Italic), - FontStyle::UNDERLINE => attrs.style(Style::Normal), - _ => attrs, - }; - - (str, attrs.color(cosmic_text::Color::rgb(r, g, b))) - }) .collect::()) } }