| 1 | use std::ops::Range; |
| 2 | |
| 3 | use gpui_kit::component::input::{RangeDecoration, RangeDecorationStyle, TextDecoration}; |
| 4 | use gpui_kit::*; |
| 5 | use teams_core::{Draft, FontSize, LineKind, MarkKind, SizeStep}; |
| 6 | |
| 7 | use crate::render::blocks::{Script, StyleFlags}; |
| 8 | use crate::render::elements::{highlight_fill, readable_on, token_style}; |
| 9 | use crate::render::syntax; |
| 10 | use app_base::theme; |
| 11 | |
| 12 | const CODE_PILL_RADIUS: f32 = 4.; |
| 13 | const CODE_BLOCK_RADIUS: f32 = 6.; |
| 14 | const QUOTE_BAR_WIDTH: f32 = 3.; |
| 15 | const QUOTE_INDENT: f32 = 12.; |
| 16 | /// Room before code lines: the line numbers sit in it. |
| 17 | pub const CODE_INDENT: f32 = 36.; |
| 18 | const LIST_LEVEL_INDENT: f32 = 18.; |
| 19 | const HEADING_SCALES: [f32; 3] = [1.6, 1.35, 1.15]; |
| 20 | const INDENT_STEP: f32 = teams_core::INDENT_PIXELS as f32; |
| 21 | const HIGHLIGHT_RADIUS: f32 = 3.; |
| 22 | |
| 23 | /// How the composer paints a draft: text styles, fills and the list markers to hang under. |
| 24 | pub struct DraftStyle { |
| 25 | pub text: Vec<TextDecoration>, |
| 26 | pub ranges: Vec<RangeDecoration>, |
| 27 | pub markers: Vec<Range<usize>>, |
| 28 | pub indents: Vec<(usize, Pixels)>, |
| 29 | /// Code line numbers, each before the start of its line's content. |
| 30 | pub labels: Vec<(usize, SharedString)>, |
| 31 | } |
| 32 | |
| 33 | fn line_indent(kind: &LineKind) -> f32 { |
| 34 | match kind { |
| 35 | LineKind::Text | LineKind::Heading(_) | LineKind::Table(_) | LineKind::Rule => 0., |
| 36 | LineKind::Indent(level) => INDENT_STEP * f32::from(*level), |
| 37 | LineKind::Quote => QUOTE_INDENT, |
| 38 | LineKind::Code(_) => CODE_INDENT, |
| 39 | LineKind::Bullet(depth) | LineKind::Numbered(depth) => { |
| 40 | LIST_LEVEL_INDENT * f32::from(*depth) |
| 41 | } |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | fn color(color: Hsla) -> HighlightStyle { |
| 46 | HighlightStyle { |
| 47 | color: Some(color), |
| 48 | ..Default::default() |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | fn underline(color: Option<Hsla>) -> UnderlineStyle { |
| 53 | UnderlineStyle { |
| 54 | thickness: px(1.), |
| 55 | color, |
| 56 | wavy: false, |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | fn mark_style(kind: &MarkKind) -> HighlightStyle { |
| 61 | let mut style = HighlightStyle::default(); |
| 62 | match kind { |
| 63 | MarkKind::Bold => style.font_weight = Some(FontWeight::BOLD), |
| 64 | MarkKind::Italic => style.font_style = Some(FontStyle::Italic), |
| 65 | MarkKind::Underline => style.underline = Some(underline(None)), |
| 66 | MarkKind::Strike => { |
| 67 | style.color = Some(theme::text_muted()); |
| 68 | style.strikethrough = Some(StrikethroughStyle { |
| 69 | thickness: px(1.), |
| 70 | color: None, |
| 71 | }); |
| 72 | } |
| 73 | MarkKind::Color(value) => { |
| 74 | style.color = Some(readable_on(*value, theme::surface_raised())); |
| 75 | } |
| 76 | MarkKind::Superscript |
| 77 | | MarkKind::Subscript |
| 78 | | MarkKind::Size(_) |
| 79 | | MarkKind::Highlight(_) => {} |
| 80 | MarkKind::Code => style.color = Some(theme::text_strong()), |
| 81 | MarkKind::Link(_) => { |
| 82 | style.color = Some(theme::accent_text()); |
| 83 | style.underline = Some(underline(Some(theme::accent_text()))); |
| 84 | } |
| 85 | } |
| 86 | style |
| 87 | } |
| 88 | |
| 89 | fn size_flags(kind: &MarkKind) -> StyleFlags { |
| 90 | let mut flags = StyleFlags::default(); |
| 91 | match kind { |
| 92 | MarkKind::Superscript => flags.script = Some(Script::Super), |
| 93 | MarkKind::Subscript => flags.script = Some(Script::Sub), |
| 94 | MarkKind::Size(SizeStep::Small) => flags.size = Some(FontSize::Small), |
| 95 | MarkKind::Size(SizeStep::Large) => flags.size = Some(FontSize::Large), |
| 96 | _ => {} |
| 97 | } |
| 98 | flags |
| 99 | } |
| 100 | |
| 101 | fn heading_decoration(content: Range<usize>, level: u8) -> TextDecoration { |
| 102 | let scale = HEADING_SCALES[usize::from(level.clamp(1, 3) - 1)]; |
| 103 | let style = HighlightStyle { |
| 104 | font_weight: Some(FontWeight::BOLD), |
| 105 | color: Some(theme::text_strong()), |
| 106 | ..Default::default() |
| 107 | }; |
| 108 | TextDecoration::new(content, style).with_font_scale(scale) |
| 109 | } |
| 110 | |
| 111 | /// From the start of the first line of `lines` to the end of the last; Block and Bar cover |
| 112 | /// every line starting inside it, ends included, so empty lines count too. |
| 113 | fn block_range(draft: &Draft, lines: Range<usize>) -> Range<usize> { |
| 114 | let line_ranges = draft.line_ranges(); |
| 115 | line_ranges[lines.start].start..line_ranges[lines.end - 1].end |
| 116 | } |
| 117 | |
| 118 | /// A code line cut where its tokens start and end, so no two decorations overlap: the |
| 119 | /// input does not say which of two overlapping ones in a collection wins. |
| 120 | fn code_pieces( |
| 121 | line: Range<usize>, |
| 122 | tokens: &[(Range<usize>, HighlightStyle)], |
| 123 | ) -> impl Iterator<Item = (Range<usize>, HighlightStyle)> { |
| 124 | let plain = color(theme::text_strong()); |
| 125 | let mut pieces = Vec::new(); |
| 126 | let mut at = line.start; |
| 127 | for (range, style) in tokens { |
| 128 | let range = range.start.max(line.start)..range.end.min(line.end); |
| 129 | if range.start >= range.end || range.start < at { |
| 130 | continue; |
| 131 | } |
| 132 | if at < range.start { |
| 133 | pieces.push((at..range.start, plain)); |
| 134 | } |
| 135 | let mut style = *style; |
| 136 | style.color = style.color.or(plain.color); |
| 137 | pieces.push((range.clone(), style)); |
| 138 | at = range.end; |
| 139 | } |
| 140 | if at < line.end { |
| 141 | pieces.push((at..line.end, plain)); |
| 142 | } |
| 143 | pieces.into_iter() |
| 144 | } |
| 145 | |
| 146 | pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle { |
| 147 | let mut text = Vec::new(); |
| 148 | let mut ranges = Vec::new(); |
| 149 | let mut markers = Vec::new(); |
| 150 | let indents = draft |
| 151 | .line_ranges() |
| 152 | .into_iter() |
| 153 | .zip(draft.lines()) |
| 154 | .map(|(line, kind)| (line.start, px(line_indent(kind)))) |
| 155 | .filter(|(_, indent)| *indent > px(0.)) |
| 156 | .collect(); |
| 157 | for mark in draft.marks() { |
| 158 | let mut decoration = TextDecoration::new(mark.range.clone(), mark_style(&mark.kind)); |
| 159 | let flags = size_flags(&mark.kind); |
| 160 | if flags.is_flowed() { |
| 161 | decoration = decoration.with_font_scale(flags.font_scale()); |
| 162 | if flags.baseline_raise() != 0. { |
| 163 | decoration = decoration.with_baseline_shift(flags.baseline_raise()); |
| 164 | } |
| 165 | } |
| 166 | if let MarkKind::Highlight(value) = mark.kind { |
| 167 | ranges.push( |
| 168 | RangeDecoration::new(mark.range.clone()) |
| 169 | .with_style(RangeDecorationStyle::Pill) |
| 170 | .with_color(highlight_fill(value)) |
| 171 | .with_radius(px(HIGHLIGHT_RADIUS)), |
| 172 | ); |
| 173 | } |
| 174 | if mark.kind == MarkKind::Code { |
| 175 | text.push(decoration.with_font_family(mono.clone())); |
| 176 | ranges.push( |
| 177 | RangeDecoration::new(mark.range.clone()) |
| 178 | .with_style(RangeDecorationStyle::Pill) |
| 179 | .with_color(theme::inline_code_fill(false)) |
| 180 | .with_border(theme::inline_code_border()) |
| 181 | .with_radius(px(CODE_PILL_RADIUS)), |
| 182 | ); |
| 183 | } else { |
| 184 | text.push(decoration); |
| 185 | } |
| 186 | } |
| 187 | let mut labels = Vec::new(); |
| 188 | let kinds = draft.lines(); |
| 189 | let mut index = 0; |
| 190 | while index < kinds.len() { |
| 191 | let kind = &kinds[index]; |
| 192 | let run_end = index |
| 193 | + kinds[index..] |
| 194 | .iter() |
| 195 | .take_while(|other| *other == kind) |
| 196 | .count(); |
| 197 | // From after the header mark, so line one reads as a line start. |
| 198 | let tokens: Vec<(Range<usize>, HighlightStyle)> = match kind { |
| 199 | LineKind::Code(Some(language)) => { |
| 200 | let block = |
| 201 | draft.content_range(index).start..block_range(draft, index..run_end).end; |
| 202 | syntax::highlight(&draft.text()[block.clone()], language) |
| 203 | .unwrap_or_default() |
| 204 | .into_iter() |
| 205 | .map(|(range, token)| { |
| 206 | ( |
| 207 | block.start + range.start..block.start + range.end, |
| 208 | token_style(token), |
| 209 | ) |
| 210 | }) |
| 211 | .collect() |
| 212 | } |
| 213 | _ => Vec::new(), |
| 214 | }; |
| 215 | for line in index..run_end { |
| 216 | let marker = draft.marker_range(line); |
| 217 | let content = draft.content_range(line); |
| 218 | if matches!(kind, LineKind::Code(_)) { |
| 219 | labels.push((content.start, (line - index + 1).to_string().into())); |
| 220 | } |
| 221 | // A code block's header sits on its own row, so it hangs nothing. |
| 222 | if !marker.is_empty() && !matches!(kind, LineKind::Code(_)) { |
| 223 | markers.push(marker.clone()); |
| 224 | if kind.is_list() { |
| 225 | text.push(TextDecoration::new(marker, color(theme::text_soft()))); |
| 226 | } |
| 227 | } |
| 228 | if content.is_empty() { |
| 229 | continue; |
| 230 | } |
| 231 | match kind { |
| 232 | LineKind::Quote => { |
| 233 | text.push(TextDecoration::new(content, color(theme::text_soft()))) |
| 234 | } |
| 235 | LineKind::Code(_) => { |
| 236 | text.extend(code_pieces(content, &tokens).map(|(range, style)| { |
| 237 | TextDecoration::new(range, style).with_font_family(mono.clone()) |
| 238 | })) |
| 239 | } |
| 240 | LineKind::Heading(level) => text.push(heading_decoration(content, *level)), |
| 241 | _ => {} |
| 242 | } |
| 243 | } |
| 244 | let block = match kind { |
| 245 | LineKind::Code(_) => Some( |
| 246 | RangeDecoration::new(block_range(draft, index..run_end)) |
| 247 | .with_style(RangeDecorationStyle::Block) |
| 248 | .with_color(theme::code_surface()) |
| 249 | .with_border(theme::code_frame()) |
| 250 | .with_radius(px(CODE_BLOCK_RADIUS)), |
| 251 | ), |
| 252 | LineKind::Quote => Some( |
| 253 | RangeDecoration::new(block_range(draft, index..run_end)) |
| 254 | .with_style(RangeDecorationStyle::Bar) |
| 255 | .with_color(theme::border_strong()) |
| 256 | .with_radius(px(QUOTE_BAR_WIDTH)), |
| 257 | ), |
| 258 | _ => None, |
| 259 | }; |
| 260 | ranges.extend(block); |
| 261 | index = run_end; |
| 262 | } |
| 263 | DraftStyle { |
| 264 | text, |
| 265 | ranges, |
| 266 | markers, |
| 267 | indents, |
| 268 | labels, |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | #[cfg(test)] |
| 273 | mod tests { |
| 274 | use gpui_kit::component::input::RangeDecorationStyle; |
| 275 | use teams_core::{Draft, DraftLine, LineKind}; |
| 276 | |
| 277 | use super::{block_range, draft_style}; |
| 278 | |
| 279 | fn line(kind: LineKind, content: &str) -> DraftLine { |
| 280 | DraftLine { |
| 281 | kind, |
| 282 | number: None, |
| 283 | content: content.into(), |
| 284 | marks: Vec::new(), |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | #[test] |
| 289 | fn list_markers_hang_and_code_gets_a_pill() { |
| 290 | let draft = Draft::from_markdown("- one `x`\n```\nfn\n```"); |
| 291 | let style = draft_style(&draft, "Mono".into()); |
| 292 | assert_eq!(style.markers, [draft.marker_range(0)]); |
| 293 | assert_eq!( |
| 294 | style |
| 295 | .ranges |
| 296 | .iter() |
| 297 | .map(|range| range.style()) |
| 298 | .collect::<Vec<_>>(), |
| 299 | [RangeDecorationStyle::Pill, RangeDecorationStyle::Block] |
| 300 | ); |
| 301 | } |
| 302 | |
| 303 | #[test] |
| 304 | fn nesting_quotes_and_code_become_line_indents() { |
| 305 | let draft = Draft::from_markdown("- a\n - b\n> q\n```\nx\n```"); |
| 306 | let style = draft_style(&draft, "Mono".into()); |
| 307 | let starts = draft.line_ranges(); |
| 308 | assert_eq!( |
| 309 | style.indents, |
| 310 | [ |
| 311 | (starts[1].start, gpui_kit::px(18.)), |
| 312 | (starts[2].start, gpui_kit::px(12.)), |
| 313 | (starts[3].start, gpui_kit::px(36.)), |
| 314 | ] |
| 315 | ); |
| 316 | assert!(!draft.text().contains('\u{2003}')); |
| 317 | } |
| 318 | |
| 319 | #[test] |
| 320 | fn a_code_block_covers_its_empty_last_line_before_text() { |
| 321 | let draft = Draft::from_lines(&[ |
| 322 | line(LineKind::Code(None), "x"), |
| 323 | line(LineKind::Code(None), ""), |
| 324 | line(LineKind::Text, "after"), |
| 325 | ]); |
| 326 | let block = block_range(&draft, 0..2); |
| 327 | let empty_line_start = draft.line_ranges()[1].start; |
| 328 | assert!(block.contains(&empty_line_start) || block.end == empty_line_start); |
| 329 | assert!(block.end < draft.line_ranges()[2].start); |
| 330 | } |
| 331 | |
| 332 | #[test] |
| 333 | fn code_with_a_language_is_highlighted_while_typing() { |
| 334 | let draft = Draft::from_lines(&[ |
| 335 | line(LineKind::Code(Some("go".into())), "x // y"), |
| 336 | line(LineKind::Code(Some("go".into())), "z"), |
| 337 | ]); |
| 338 | let style = draft_style(&draft, "Mono".into()); |
| 339 | let ranges: Vec<_> = style.text.iter().map(|d| d.range.clone()).collect(); |
| 340 | // "x " plain, the comment, then "z": all after the 3-byte header mark. |
| 341 | assert_eq!(ranges[..2], [3..5, 5..9]); |
| 342 | assert_eq!( |
| 343 | draft_style( |
| 344 | &Draft::from_lines(&[line(LineKind::Code(None), "x // y")]), |
| 345 | "Mono".into() |
| 346 | ) |
| 347 | .text |
| 348 | .len(), |
| 349 | 1 |
| 350 | ); |
| 351 | } |
| 352 | |
| 353 | #[test] |
| 354 | fn the_first_code_line_starts_a_line_for_the_highlighter() { |
| 355 | let draft = Draft::from_lines(&[line(LineKind::Code(Some("markdown".into())), "# h")]); |
| 356 | let style = draft_style(&draft, "Mono".into()); |
| 357 | assert_eq!(&draft.text()[style.text[0].range.clone()], "# h"); |
| 358 | } |
| 359 | |
| 360 | #[test] |
| 361 | fn python_keywords_are_highlighted_in_the_composer() { |
| 362 | let draft = Draft::from_lines(&[ |
| 363 | line(LineKind::Code(Some("python".into())), "def f():"), |
| 364 | line(LineKind::Code(Some("python".into())), "class A:"), |
| 365 | ]); |
| 366 | let style = draft_style(&draft, "Mono".into()); |
| 367 | let words: Vec<_> = style |
| 368 | .text |
| 369 | .iter() |
| 370 | .map(|d| &draft.text()[d.range.clone()]) |
| 371 | .collect(); |
| 372 | assert!( |
| 373 | words.contains(&"def") && words.contains(&"class"), |
| 374 | "{words:?}" |
| 375 | ); |
| 376 | let mut ranges: Vec<_> = style.text.iter().map(|d| d.range.clone()).collect(); |
| 377 | ranges.sort_by_key(|range| range.start); |
| 378 | assert!( |
| 379 | ranges.windows(2).all(|pair| pair[0].end <= pair[1].start), |
| 380 | "{ranges:?}" |
| 381 | ); |
| 382 | } |
| 383 | |
| 384 | #[test] |
| 385 | fn a_lone_code_line_still_gets_a_block() { |
| 386 | let draft = Draft::from_lines(&[line(LineKind::Code(None), "")]); |
| 387 | let style = draft_style(&draft, "Mono".into()); |
| 388 | assert_eq!(style.ranges.len(), 1); |
| 389 | assert_eq!(style.ranges[0].style(), RangeDecorationStyle::Block); |
| 390 | } |
| 391 | } |