BlueGit

ict rusty-teams

feat(app): rich text in messages - code, lists, tables, headings

- Code block: tinted surface from the bubble, language + copy header, syntax colors
- Inline code: mono pill instead of a black background
- Lists: one block, nested levels, numbered with start
- Headings, strike, underline, tables, rules, block quotes, highlight and text color

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-07 · 7 weeks ago

Hash
17f687f4871771fe669eb8bd338aaa238f330dbf
Parent
dc16b784
15 files changed +1556 −102
ROADMAP.md +5 −1
@@ -64,7 +64,11 @@ Feature parity with the Microsoft Teams desktop client.
64 64
65 65 | Feature | State | Note |
66 66 |---|---|---|
67 | Text formatting: bold, italic, code, code block, lists, links | Done | |
67 | Text formatting: bold, italic, strike, underline, headings, links | Done | |
68 | Code: inline pill, block with language, copy and syntax colors | Done | |
69 | Lists: nested, numbered with start | Done | |
70 | Tables, rules, block quotes, highlight and text color | Done | |
71 | Superscript, subscript, font size | Missing | Shown as plain text |
68 72 | Quotes and replies | Done | |
69 73 | Reactions shown | Done | |
70 74 | Edited and deleted markers | Done | |
@@ -64,7 +64,11 @@ Feature parity with the Microsoft Teams desktop client.
64
64
65| Feature | State | Note |
65| Feature | State | Note |
66|---|---|---|
66|---|---|---|
67| Text formatting: bold, italic, code, code block, lists, links | Done | |
67| Text formatting: bold, italic, strike, underline, headings, links | Done | |
68| Code: inline pill, block with language, copy and syntax colors | Done | |
69| Lists: nested, numbered with start | Done | |
70| Tables, rules, block quotes, highlight and text color | Done | |
71| Superscript, subscript, font size | Missing | Shown as plain text |
68| Quotes and replies | Done | |
72| Quotes and replies | Done | |
69| Reactions shown | Done | |
73| Reactions shown | Done | |
70| Edited and deleted markers | Done | |
74| Edited and deleted markers | Done | |
crates/app/assets/symbols/content_copy.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M360-240q-33 0-56.5-23.5T280-320v-480q0-33 23.5-56.5T360-880h360q33 0 56.5 23.5T800-800v480q0 33-23.5 56.5T720-240H360Zm0-80h360v-480H360v480ZM200-80q-33 0-56.5-23.5T120-160v-560h80v560h440v80H200Zm160-240v-480 480Z"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M360-240q-33 0-56.5-23.5T280-320v-480q0-33 23.5-56.5T360-880h360q33 0 56.5 23.5T800-800v480q0 33-23.5 56.5T720-240H360Zm0-80h360v-480H360v480ZM200-80q-33 0-56.5-23.5T120-160v-560h80v560h440v80H200Zm160-240v-480 480Z"/></svg>
crates/app/src/assets.rs +2 −1
@@ -8,7 +8,7 @@ macro_rules! symbols {
8 8 };
9 9 }
10 10
11 const SYMBOLS: [(&str, &[u8]); 12] = symbols![
11 const SYMBOLS: [(&str, &[u8]); 13] = symbols![
12 12 "done",
13 13 "done_all",
14 14 "keyboard_return",
@@ -21,6 +21,7 @@ const SYMBOLS: [(&str, &[u8]); 12] = symbols![
21 21 "check_circle",
22 22 "error",
23 23 "notifications",
24 "content_copy",
24 25 ];
25 26
26 27 pub struct AppAssets;
@@ -8,7 +8,7 @@ macro_rules! symbols {
8 };
8 };
9}
9}
10
10
11const SYMBOLS: [(&str, &[u8]); 12] = symbols![
11const SYMBOLS: [(&str, &[u8]); 13] = symbols![
12 "done",
12 "done",
13 "done_all",
13 "done_all",
14 "keyboard_return",
14 "keyboard_return",
@@ -21,6 +21,7 @@ const SYMBOLS: [(&str, &[u8]); 12] = symbols![
21 "check_circle",
21 "check_circle",
22 "error",
22 "error",
23 "notifications",
23 "notifications",
24 "content_copy",
24];
25];
25
26
26pub struct AppAssets;
27pub struct AppAssets;
crates/app/src/demo.rs +22 −2
@@ -627,7 +627,7 @@ fn release_messages() -> Vec<MessageRecord> {
627 627 None,
628 628 jonas,
629 629 at(0, 10, 14),
630 "<p><at id=\"0\">Mara Lindqvist</at> can you take a quick look at this?</p><pre><code>fn freeze(branch: &amp;str) -&gt; bool {\n branch.starts_with(\"release/\")\n}</code></pre>",
630 "<p><at id=\"0\">Mara Lindqvist</at> can you take a quick look at this? It runs before <code>cargo test</code>.</p><pre><code class=\"language-rust\">// only release branches\nfn freeze(branch: &amp;str) -&gt; bool {\n branch.starts_with(\"release/\")\n}</code></pre>",
631 631 "[]",
632 632 false,
633 633 ),
@@ -637,10 +637,30 @@ fn release_messages() -> Vec<MessageRecord> {
637 637 None,
638 638 mara,
639 639 at(0, 10, 31),
640 "<blockquote><b>Jonas Ortega</b><br>can you take a quick look at this?</blockquote><p>Looks good. Small thing: the name could say what it checks.</p>",
640 "<blockquote itemscope=\"\" itemtype=\"http://schema.skype.com/Reply\" itemid=\"m4\"><strong itemprop=\"mri\">Jonas Ortega</strong><p itemprop=\"preview\">can you take a quick look at this?</p></blockquote><p>Looks good. Small thing: the name could say what it checks.</p>",
641 641 &hearts,
642 642 true,
643 643 ),
644 message(
645 chat,
646 "m5b",
647 None,
648 mara,
649 at(0, 10, 40),
650 "<p>Rollout for Friday:</p><ul><li>Freeze the release branch</li><li>Run the smoke tests on staging, then post the results in the channel</li><li>Ship<ul><li>Windows installer</li><li>Linux <code>.AppImage</code></li></ul></li></ul><p>Order:</p><ol><li>Tag</li><li>Build</li><li>Announce</li></ol>",
651 "[]",
652 false,
653 ),
654 message(
655 chat,
656 "m5c",
657 None,
658 jonas,
659 at(0, 11, 5),
660 "<h2>Release notes 0.2</h2><p>The <s>old sync path</s> <u>is gone</u>.</p><table><thead><tr><th>Area</th><th>Owner</th></tr></thead><tbody><tr><td>Sync</td><td>Priya</td></tr><tr><td>Render</td><td>Jonas</td></tr></tbody></table><hr><blockquote>Measure twice, cut once.</blockquote><p><span style=\"background-color: rgb(255, 255, 0)\">Important:</span> <span style=\"color: #c00000\">backup first</span>.</p>",
661 "[]",
662 false,
663 ),
644 664 message(
645 665 chat,
646 666 "m6",
@@ -627,7 +627,7 @@ fn release_messages() -> Vec<MessageRecord> {
627 None,
627 None,
628 jonas,
628 jonas,
629 at(0, 10, 14),
629 at(0, 10, 14),
630 "<p><at id=\"0\">Mara Lindqvist</at> can you take a quick look at this?</p><pre><code>fn freeze(branch: &amp;str) -&gt; bool {\n branch.starts_with(\"release/\")\n}</code></pre>",
630 "<p><at id=\"0\">Mara Lindqvist</at> can you take a quick look at this? It runs before <code>cargo test</code>.</p><pre><code class=\"language-rust\">// only release branches\nfn freeze(branch: &amp;str) -&gt; bool {\n branch.starts_with(\"release/\")\n}</code></pre>",
631 "[]",
631 "[]",
632 false,
632 false,
633 ),
633 ),
@@ -637,10 +637,30 @@ fn release_messages() -> Vec<MessageRecord> {
637 None,
637 None,
638 mara,
638 mara,
639 at(0, 10, 31),
639 at(0, 10, 31),
640 "<blockquote><b>Jonas Ortega</b><br>can you take a quick look at this?</blockquote><p>Looks good. Small thing: the name could say what it checks.</p>",
640 "<blockquote itemscope=\"\" itemtype=\"http://schema.skype.com/Reply\" itemid=\"m4\"><strong itemprop=\"mri\">Jonas Ortega</strong><p itemprop=\"preview\">can you take a quick look at this?</p></blockquote><p>Looks good. Small thing: the name could say what it checks.</p>",
641 &hearts,
641 &hearts,
642 true,
642 true,
643 ),
643 ),
644 message(
645 chat,
646 "m5b",
647 None,
648 mara,
649 at(0, 10, 40),
650 "<p>Rollout for Friday:</p><ul><li>Freeze the release branch</li><li>Run the smoke tests on staging, then post the results in the channel</li><li>Ship<ul><li>Windows installer</li><li>Linux <code>.AppImage</code></li></ul></li></ul><p>Order:</p><ol><li>Tag</li><li>Build</li><li>Announce</li></ol>",
651 "[]",
652 false,
653 ),
654 message(
655 chat,
656 "m5c",
657 None,
658 jonas,
659 at(0, 11, 5),
660 "<h2>Release notes 0.2</h2><p>The <s>old sync path</s> <u>is gone</u>.</p><table><thead><tr><th>Area</th><th>Owner</th></tr></thead><tbody><tr><td>Sync</td><td>Priya</td></tr><tr><td>Render</td><td>Jonas</td></tr></tbody></table><hr><blockquote>Measure twice, cut once.</blockquote><p><span style=\"background-color: rgb(255, 255, 0)\">Important:</span> <span style=\"color: #c00000\">backup first</span>.</p>",
661 "[]",
662 false,
663 ),
644 message(
664 message(
645 chat,
665 chat,
646 "m6",
666 "m6",
crates/app/src/render/blocks.rs +357 −21
@@ -3,6 +3,7 @@ use std::ops::Range;
3 3 use teams_core::Span;
4 4
5 5 pub const IMAGE_PLACEHOLDER: &str = "[image]";
6 pub const CODE_PADDING: &str = "\u{200a}";
6 7 const URL_PREFIXES: [&str; 3] = ["https://", "http://", "www."];
7 8 const TRAILING_PUNCTUATION: &str = ".,;:!?'\"";
8 9
@@ -13,6 +14,10 @@ pub struct StyleFlags {
13 14 pub code: bool,
14 15 pub mention: bool,
15 16 pub link: bool,
17 pub strike: bool,
18 pub underline: bool,
19 pub color: Option<u32>,
20 pub background: Option<u32>,
16 21 }
17 22
18 23 impl StyleFlags {
@@ -117,9 +122,89 @@ impl Inline {
117 122 #[derive(Debug, Clone, PartialEq, Eq)]
118 123 pub enum Block {
119 124 Paragraph(Inline),
120 Code(String),
125 Heading {
126 level: u8,
127 inline: Inline,
128 },
129 Code {
130 language: Option<String>,
131 code: String,
132 },
133 Reply(Vec<Block>),
121 134 Quote(Vec<Block>),
122 ListItem(Inline),
135 List {
136 ordered: bool,
137 start: u32,
138 items: Vec<Vec<Block>>,
139 },
140 Table {
141 header: bool,
142 rows: Vec<Vec<Inline>>,
143 },
144 Rule,
145 }
146
147 impl Block {
148 pub fn markdown(&self) -> Option<String> {
149 let join = |blocks: &[Block]| {
150 blocks
151 .iter()
152 .filter_map(Block::markdown)
153 .collect::<Vec<_>>()
154 .join("\n")
155 };
156 match self {
157 Block::Paragraph(inline) | Block::Heading { inline, .. } => Some(inline.text.clone()),
158 Block::Code { code, .. } => Some(format!("```\n{code}\n```")),
159 Block::List {
160 ordered,
161 start,
162 items,
163 } => Some(
164 items
165 .iter()
166 .enumerate()
167 .map(|(offset, item)| match ordered {
168 true => format!("{}. {}", *start as usize + offset, join(item)),
169 false => format!("- {}", join(item)),
170 })
171 .collect::<Vec<_>>()
172 .join("\n"),
173 ),
174 Block::Table { rows, .. } => Some(
175 rows.iter()
176 .map(|row| {
177 row.iter()
178 .map(|cell| cell.text.as_str())
179 .collect::<Vec<_>>()
180 .join(" | ")
181 })
182 .collect::<Vec<_>>()
183 .join("\n"),
184 ),
185 Block::Quote(children) => Some(join(children)),
186 Block::Reply(_) | Block::Rule => None,
187 }
188 }
189
190 pub fn first_line(&self) -> Option<String> {
191 match self {
192 Block::Paragraph(inline) | Block::Heading { inline, .. } => Some(inline.text.clone()),
193 Block::Code { code, .. } => Some(code.clone()),
194 Block::List { items, .. } => items.first()?.iter().find_map(Block::first_line),
195 Block::Table { rows, .. } => Some(rows.first()?.first()?.text.clone()),
196 Block::Quote(children) => children.iter().find_map(Block::first_line),
197 Block::Reply(_) | Block::Rule => None,
198 }
199 }
200
201 pub fn last_inline_mut(&mut self) -> Option<&mut Inline> {
202 match self {
203 Block::Paragraph(inline) => Some(inline),
204 Block::List { items, .. } => items.last_mut()?.last_mut()?.last_inline_mut(),
205 _ => None,
206 }
207 }
123 208 }
124 209
125 210 pub fn strip_image_placeholders(blocks: Vec<Block>) -> Vec<Block> {
@@ -130,10 +215,30 @@ pub fn strip_image_placeholders(blocks: Vec<Block>) -> Vec<Block> {
130 215 let stripped = inline.without(IMAGE_PLACEHOLDER);
131 216 (!stripped.is_blank()).then_some(Block::Paragraph(stripped))
132 217 }
218 Block::Reply(children) => {
219 let children = strip_image_placeholders(children);
220 (!children.is_empty()).then_some(Block::Reply(children))
221 }
133 222 Block::Quote(children) => {
134 223 let children = strip_image_placeholders(children);
135 224 (!children.is_empty()).then_some(Block::Quote(children))
136 225 }
226 Block::List {
227 ordered,
228 start,
229 items,
230 } => {
231 let items: Vec<Vec<Block>> = items
232 .into_iter()
233 .map(strip_image_placeholders)
234 .filter(|item| !item.is_empty())
235 .collect();
236 (!items.is_empty()).then_some(Block::List {
237 ordered,
238 start,
239 items,
240 })
241 }
137 242 other => Some(other),
138 243 })
139 244 .collect()
@@ -144,23 +249,68 @@ pub fn layout_blocks(spans: &[Span]) -> Vec<Block> {
144 249 let mut current = Inline::default();
145 250 for span in spans {
146 251 match span {
147 Span::CodeBlock { code, .. } => {
252 Span::CodeBlock { language, code } => {
148 253 flush(&mut current, &mut blocks, Block::Paragraph);
149 blocks.push(Block::Code(code.trim_end_matches('\n').to_owned()));
254 blocks.push(Block::Code {
255 language: language.clone(),
256 code: code.trim_end_matches('\n').to_owned(),
257 });
150 258 }
151 Span::Quote(children) => {
259 Span::Quote(children) | Span::BlockQuote(children) => {
152 260 flush(&mut current, &mut blocks, Block::Paragraph);
153 261 let inner = layout_blocks(children);
154 262 if !inner.is_empty() {
155 blocks.push(Block::Quote(inner));
263 blocks.push(match span {
264 Span::Quote(_) => Block::Reply(inner),
265 _ => Block::Quote(inner),
266 });
267 }
268 }
269 Span::List {
270 ordered,
271 start,
272 items,
273 } => {
274 flush(&mut current, &mut blocks, Block::Paragraph);
275 let items: Vec<Vec<Block>> = items
276 .iter()
277 .map(|item| layout_blocks(item))
278 .filter(|item| !item.is_empty())
279 .collect();
280 if !items.is_empty() {
281 blocks.push(Block::List {
282 ordered: *ordered,
283 start: *start,
284 items,
285 });
286 }
287 }
288 Span::Table { header, rows } => {
289 flush(&mut current, &mut blocks, Block::Paragraph);
290 let rows: Vec<Vec<Inline>> = rows
291 .iter()
292 .map(|row| row.iter().map(|cell| inline_of(cell)).collect())
293 .collect();
294 if !rows.is_empty() {
295 blocks.push(Block::Table {
296 header: *header,
297 rows,
298 });
156 299 }
157 300 }
158 Span::ListItem(children) => {
301 Span::Heading { level, children } => {
159 302 flush(&mut current, &mut blocks, Block::Paragraph);
160 let mut item = Inline::default();
161 append_inline(children, StyleFlags::default(), None, &mut item);
162 item.trim_end();
163 blocks.push(Block::ListItem(item));
303 let inline = inline_of(children);
304 if !inline.is_blank() {
305 blocks.push(Block::Heading {
306 level: *level,
307 inline,
308 });
309 }
310 }
311 Span::Rule => {
312 flush(&mut current, &mut blocks, Block::Paragraph);
313 blocks.push(Block::Rule);
164 314 }
165 315 other => append_inline(
166 316 std::slice::from_ref(other),
@@ -174,6 +324,13 @@ pub fn layout_blocks(spans: &[Span]) -> Vec<Block> {
174 324 blocks
175 325 }
176 326
327 fn inline_of(spans: &[Span]) -> Inline {
328 let mut inline = Inline::default();
329 append_inline(spans, StyleFlags::default(), None, &mut inline);
330 inline.trim_end();
331 pad_code(inline)
332 }
333
177 334 fn flush(current: &mut Inline, blocks: &mut Vec<Block>, make: fn(Inline) -> Block) {
178 335 let mut inline = std::mem::take(current);
179 336 inline.trim_end();
@@ -187,8 +344,40 @@ fn flush(current: &mut Inline, blocks: &mut Vec<Block>, make: fn(Inline) -> Bloc
187 344 });
188 345 }
189 346 if !inline.is_blank() {
190 blocks.push(make(inline));
347 blocks.push(make(pad_code(inline)));
348 }
349 }
350
351 fn pad_code(inline: Inline) -> Inline {
352 if !inline.segments.iter().any(|segment| segment.style.code) {
353 return inline;
354 }
355 let mut padded = Inline::default();
356 for (index, segment) in inline.segments.iter().enumerate() {
357 let text = &inline.text[segment.range.clone()];
358 let touches = |neighbour: Option<&Segment>, at_end: bool| {
359 neighbour.is_some_and(|neighbour| {
360 let neighbour_text = &inline.text[neighbour.range.clone()];
361 let edge = if at_end {
362 neighbour_text.chars().next()
363 } else {
364 neighbour_text.chars().next_back()
365 };
366 !neighbour.style.code && edge.is_some_and(|edge| !edge.is_whitespace())
367 })
368 };
369 let previous = index
370 .checked_sub(1)
371 .and_then(|previous| inline.segments.get(previous));
372 if segment.style.code && touches(previous, false) {
373 padded.push(CODE_PADDING, StyleFlags::default(), None);
374 }
375 padded.push(text, segment.style, segment.link.as_deref());
376 if segment.style.code && touches(inline.segments.get(index + 1), true) {
377 padded.push(CODE_PADDING, StyleFlags::default(), None);
378 }
191 379 }
380 padded
192 381 }
193 382
194 383 fn append_inline(spans: &[Span], style: StyleFlags, link: Option<&str>, out: &mut Inline) {
@@ -216,6 +405,50 @@ fn append_inline(spans: &[Span], style: StyleFlags, link: Option<&str>, out: &mu
216 405 link,
217 406 out,
218 407 ),
408 Span::Strike(children) => append_inline(
409 children,
410 StyleFlags {
411 strike: true,
412 ..style
413 },
414 link,
415 out,
416 ),
417 Span::Underline(children) => append_inline(
418 children,
419 StyleFlags {
420 underline: true,
421 ..style
422 },
423 link,
424 out,
425 ),
426 Span::Colored {
427 color,
428 background,
429 children,
430 } => append_inline(
431 children,
432 StyleFlags {
433 color: color.or(style.color),
434 background: background.or(style.background),
435 ..style
436 },
437 link,
438 out,
439 ),
440 Span::Heading { children, .. } => {
441 append_inline(
442 children,
443 StyleFlags {
444 bold: true,
445 ..style
446 },
447 link,
448 out,
449 );
450 out.push("\n", style, link);
451 }
219 452 Span::Code(text) => out.push(
220 453 text,
221 454 StyleFlags {
@@ -252,11 +485,28 @@ fn append_inline(spans: &[Span], style: StyleFlags, link: Option<&str>, out: &mu
252 485 link,
253 486 );
254 487 }
255 Span::LineBreak => out.push("\n", style, link),
256 Span::ListItem(children) | Span::Quote(children) => {
488 Span::LineBreak | Span::Rule => out.push("\n", style, link),
489 Span::Quote(children) | Span::BlockQuote(children) => {
257 490 append_inline(children, style, link, out);
258 491 out.push("\n", style, link);
259 492 }
493 Span::List { items, .. } => {
494 for item in items {
495 append_inline(item, style, link, out);
496 out.push("\n", style, link);
497 }
498 }
499 Span::Table { rows, .. } => {
500 for row in rows {
501 for (index, cell) in row.iter().enumerate() {
502 if index > 0 {
503 out.push(" ", style, link);
504 }
505 append_inline(cell, style, link, out);
506 }
507 out.push("\n", style, link);
508 }
509 }
260 510 Span::Image { .. } => out.push(IMAGE_PLACEHOLDER, style, link),
261 511 }
262 512 }
@@ -467,29 +717,115 @@ mod tests {
467 717 blocks,
468 718 vec![
469 719 Block::Paragraph(Inline::plain("before")),
470 Block::Code("let x = 1;".into()),
720 Block::Code {
721 language: None,
722 code: "let x = 1;".into()
723 },
471 724 Block::Paragraph(Inline::plain("after")),
472 725 ]
473 726 );
474 727 }
475 728
476 729 #[test]
477 fn list_items_and_quotes_are_blocks() {
730 fn lists_nest_and_quotes_are_blocks() {
478 731 let blocks = layout_blocks(&[
479 Span::ListItem(vec![text("one")]),
480 Span::ListItem(vec![text("two")]),
732 Span::List {
733 ordered: true,
734 start: 3,
735 items: vec![
736 vec![text("one")],
737 vec![
738 text("two"),
739 Span::List {
740 ordered: false,
741 start: 1,
742 items: vec![vec![text("inner")]],
743 },
744 ],
745 ],
746 },
481 747 Span::Quote(vec![text("quoted")]),
482 748 ]);
483 749 assert_eq!(
484 750 blocks,
485 751 vec![
486 Block::ListItem(Inline::plain("one")),
487 Block::ListItem(Inline::plain("two")),
488 Block::Quote(vec![Block::Paragraph(Inline::plain("quoted"))]),
752 Block::List {
753 ordered: true,
754 start: 3,
755 items: vec![
756 vec![Block::Paragraph(Inline::plain("one"))],
757 vec![
758 Block::Paragraph(Inline::plain("two")),
759 Block::List {
760 ordered: false,
761 start: 1,
762 items: vec![vec![Block::Paragraph(Inline::plain("inner"))]],
763 },
764 ],
765 ],
766 },
767 Block::Reply(vec![Block::Paragraph(Inline::plain("quoted"))]),
489 768 ]
490 769 );
491 770 }
492 771
772 #[test]
773 fn heading_rule_and_table_are_blocks() {
774 let blocks = layout_blocks(&[
775 Span::Heading {
776 level: 2,
777 children: vec![text("Title")],
778 },
779 Span::Rule,
780 Span::Table {
781 header: true,
782 rows: vec![vec![vec![text("a")], vec![text("b")]]],
783 },
784 ]);
785 assert_eq!(
786 blocks,
787 vec![
788 Block::Heading {
789 level: 2,
790 inline: Inline::plain("Title")
791 },
792 Block::Rule,
793 Block::Table {
794 header: true,
795 rows: vec![vec![Inline::plain("a"), Inline::plain("b")]],
796 },
797 ]
798 );
799 }
800
801 #[test]
802 fn strike_underline_and_color_become_flags() {
803 let inline = paragraph_inline(&[
804 Span::Strike(vec![text("old")]),
805 Span::Underline(vec![text("u")]),
806 Span::Colored {
807 color: Some(0xff0000),
808 background: Some(0xffff00),
809 children: vec![text("c")],
810 },
811 ]);
812 assert!(inline.segments[0].style.strike);
813 assert!(inline.segments[1].style.underline);
814 assert_eq!(inline.segments[2].style.color, Some(0xff0000));
815 assert_eq!(inline.segments[2].style.background, Some(0xffff00));
816 }
817
818 #[test]
819 fn inline_code_gets_room_only_next_to_text() {
820 let inline = paragraph_inline(&[
821 text("run "),
822 Span::Code("x".into()),
823 text(". "),
824 Span::Code("y".into()),
825 ]);
826 assert_eq!(inline.text, "run x\u{200a}. y");
827 }
828
493 829 #[test]
494 830 fn image_becomes_placeholder() {
495 831 let blocks = layout_blocks(&[Span::Image {
@@ -3,6 +3,7 @@ use std::ops::Range;
3use teams_core::Span;
3use teams_core::Span;
4
4
5pub const IMAGE_PLACEHOLDER: &str = "[image]";
5pub const IMAGE_PLACEHOLDER: &str = "[image]";
6pub const CODE_PADDING: &str = "\u{200a}";
6const URL_PREFIXES: [&str; 3] = ["https://", "http://", "www."];
7const URL_PREFIXES: [&str; 3] = ["https://", "http://", "www."];
7const TRAILING_PUNCTUATION: &str = ".,;:!?'\"";
8const TRAILING_PUNCTUATION: &str = ".,;:!?'\"";
8
9
@@ -13,6 +14,10 @@ pub struct StyleFlags {
13 pub code: bool,
14 pub code: bool,
14 pub mention: bool,
15 pub mention: bool,
15 pub link: bool,
16 pub link: bool,
17 pub strike: bool,
18 pub underline: bool,
19 pub color: Option<u32>,
20 pub background: Option<u32>,
16}
21}
17
22
18impl StyleFlags {
23impl StyleFlags {
@@ -117,9 +122,89 @@ impl Inline {
117#[derive(Debug, Clone, PartialEq, Eq)]
122#[derive(Debug, Clone, PartialEq, Eq)]
118pub enum Block {
123pub enum Block {
119 Paragraph(Inline),
124 Paragraph(Inline),
120 Code(String),
125 Heading {
126 level: u8,
127 inline: Inline,
128 },
129 Code {
130 language: Option<String>,
131 code: String,
132 },
133 Reply(Vec<Block>),
121 Quote(Vec<Block>),
134 Quote(Vec<Block>),
122 ListItem(Inline),
135 List {
136 ordered: bool,
137 start: u32,
138 items: Vec<Vec<Block>>,
139 },
140 Table {
141 header: bool,
142 rows: Vec<Vec<Inline>>,
143 },
144 Rule,
145}
146
147impl Block {
148 pub fn markdown(&self) -> Option<String> {
149 let join = |blocks: &[Block]| {
150 blocks
151 .iter()
152 .filter_map(Block::markdown)
153 .collect::<Vec<_>>()
154 .join("\n")
155 };
156 match self {
157 Block::Paragraph(inline) | Block::Heading { inline, .. } => Some(inline.text.clone()),
158 Block::Code { code, .. } => Some(format!("```\n{code}\n```")),
159 Block::List {
160 ordered,
161 start,
162 items,
163 } => Some(
164 items
165 .iter()
166 .enumerate()
167 .map(|(offset, item)| match ordered {
168 true => format!("{}. {}", *start as usize + offset, join(item)),
169 false => format!("- {}", join(item)),
170 })
171 .collect::<Vec<_>>()
172 .join("\n"),
173 ),
174 Block::Table { rows, .. } => Some(
175 rows.iter()
176 .map(|row| {
177 row.iter()
178 .map(|cell| cell.text.as_str())
179 .collect::<Vec<_>>()
180 .join(" | ")
181 })
182 .collect::<Vec<_>>()
183 .join("\n"),
184 ),
185 Block::Quote(children) => Some(join(children)),
186 Block::Reply(_) | Block::Rule => None,
187 }
188 }
189
190 pub fn first_line(&self) -> Option<String> {
191 match self {
192 Block::Paragraph(inline) | Block::Heading { inline, .. } => Some(inline.text.clone()),
193 Block::Code { code, .. } => Some(code.clone()),
194 Block::List { items, .. } => items.first()?.iter().find_map(Block::first_line),
195 Block::Table { rows, .. } => Some(rows.first()?.first()?.text.clone()),
196 Block::Quote(children) => children.iter().find_map(Block::first_line),
197 Block::Reply(_) | Block::Rule => None,
198 }
199 }
200
201 pub fn last_inline_mut(&mut self) -> Option<&mut Inline> {
202 match self {
203 Block::Paragraph(inline) => Some(inline),
204 Block::List { items, .. } => items.last_mut()?.last_mut()?.last_inline_mut(),
205 _ => None,
206 }
207 }
123}
208}
124
209
125pub fn strip_image_placeholders(blocks: Vec<Block>) -> Vec<Block> {
210pub fn strip_image_placeholders(blocks: Vec<Block>) -> Vec<Block> {
@@ -130,10 +215,30 @@ pub fn strip_image_placeholders(blocks: Vec<Block>) -> Vec<Block> {
130 let stripped = inline.without(IMAGE_PLACEHOLDER);
215 let stripped = inline.without(IMAGE_PLACEHOLDER);
131 (!stripped.is_blank()).then_some(Block::Paragraph(stripped))
216 (!stripped.is_blank()).then_some(Block::Paragraph(stripped))
132 }
217 }
218 Block::Reply(children) => {
219 let children = strip_image_placeholders(children);
220 (!children.is_empty()).then_some(Block::Reply(children))
221 }
133 Block::Quote(children) => {
222 Block::Quote(children) => {
134 let children = strip_image_placeholders(children);
223 let children = strip_image_placeholders(children);
135 (!children.is_empty()).then_some(Block::Quote(children))
224 (!children.is_empty()).then_some(Block::Quote(children))
136 }
225 }
226 Block::List {
227 ordered,
228 start,
229 items,
230 } => {
231 let items: Vec<Vec<Block>> = items
232 .into_iter()
233 .map(strip_image_placeholders)
234 .filter(|item| !item.is_empty())
235 .collect();
236 (!items.is_empty()).then_some(Block::List {
237 ordered,
238 start,
239 items,
240 })
241 }
137 other => Some(other),
242 other => Some(other),
138 })
243 })
139 .collect()
244 .collect()
@@ -144,23 +249,68 @@ pub fn layout_blocks(spans: &[Span]) -> Vec<Block> {
144 let mut current = Inline::default();
249 let mut current = Inline::default();
145 for span in spans {
250 for span in spans {
146 match span {
251 match span {
147 Span::CodeBlock { code, .. } => {
252 Span::CodeBlock { language, code } => {
148 flush(&mut current, &mut blocks, Block::Paragraph);
253 flush(&mut current, &mut blocks, Block::Paragraph);
149 blocks.push(Block::Code(code.trim_end_matches('\n').to_owned()));
254 blocks.push(Block::Code {
255 language: language.clone(),
256 code: code.trim_end_matches('\n').to_owned(),
257 });
150 }
258 }
151 Span::Quote(children) => {
259 Span::Quote(children) | Span::BlockQuote(children) => {
152 flush(&mut current, &mut blocks, Block::Paragraph);
260 flush(&mut current, &mut blocks, Block::Paragraph);
153 let inner = layout_blocks(children);
261 let inner = layout_blocks(children);
154 if !inner.is_empty() {
262 if !inner.is_empty() {
155 blocks.push(Block::Quote(inner));
263 blocks.push(match span {
264 Span::Quote(_) => Block::Reply(inner),
265 _ => Block::Quote(inner),
266 });
267 }
268 }
269 Span::List {
270 ordered,
271 start,
272 items,
273 } => {
274 flush(&mut current, &mut blocks, Block::Paragraph);
275 let items: Vec<Vec<Block>> = items
276 .iter()
277 .map(|item| layout_blocks(item))
278 .filter(|item| !item.is_empty())
279 .collect();
280 if !items.is_empty() {
281 blocks.push(Block::List {
282 ordered: *ordered,
283 start: *start,
284 items,
285 });
286 }
287 }
288 Span::Table { header, rows } => {
289 flush(&mut current, &mut blocks, Block::Paragraph);
290 let rows: Vec<Vec<Inline>> = rows
291 .iter()
292 .map(|row| row.iter().map(|cell| inline_of(cell)).collect())
293 .collect();
294 if !rows.is_empty() {
295 blocks.push(Block::Table {
296 header: *header,
297 rows,
298 });
156 }
299 }
157 }
300 }
158 Span::ListItem(children) => {
301 Span::Heading { level, children } => {
159 flush(&mut current, &mut blocks, Block::Paragraph);
302 flush(&mut current, &mut blocks, Block::Paragraph);
160 let mut item = Inline::default();
303 let inline = inline_of(children);
161 append_inline(children, StyleFlags::default(), None, &mut item);
304 if !inline.is_blank() {
162 item.trim_end();
305 blocks.push(Block::Heading {
163 blocks.push(Block::ListItem(item));
306 level: *level,
307 inline,
308 });
309 }
310 }
311 Span::Rule => {
312 flush(&mut current, &mut blocks, Block::Paragraph);
313 blocks.push(Block::Rule);
164 }
314 }
165 other => append_inline(
315 other => append_inline(
166 std::slice::from_ref(other),
316 std::slice::from_ref(other),
@@ -174,6 +324,13 @@ pub fn layout_blocks(spans: &[Span]) -> Vec<Block> {
174 blocks
324 blocks
175}
325}
176
326
327fn inline_of(spans: &[Span]) -> Inline {
328 let mut inline = Inline::default();
329 append_inline(spans, StyleFlags::default(), None, &mut inline);
330 inline.trim_end();
331 pad_code(inline)
332}
333
177fn flush(current: &mut Inline, blocks: &mut Vec<Block>, make: fn(Inline) -> Block) {
334fn flush(current: &mut Inline, blocks: &mut Vec<Block>, make: fn(Inline) -> Block) {
178 let mut inline = std::mem::take(current);
335 let mut inline = std::mem::take(current);
179 inline.trim_end();
336 inline.trim_end();
@@ -187,8 +344,40 @@ fn flush(current: &mut Inline, blocks: &mut Vec<Block>, make: fn(Inline) -> Bloc
187 });
344 });
188 }
345 }
189 if !inline.is_blank() {
346 if !inline.is_blank() {
190 blocks.push(make(inline));
347 blocks.push(make(pad_code(inline)));
348 }
349}
350
351fn pad_code(inline: Inline) -> Inline {
352 if !inline.segments.iter().any(|segment| segment.style.code) {
353 return inline;
354 }
355 let mut padded = Inline::default();
356 for (index, segment) in inline.segments.iter().enumerate() {
357 let text = &inline.text[segment.range.clone()];
358 let touches = |neighbour: Option<&Segment>, at_end: bool| {
359 neighbour.is_some_and(|neighbour| {
360 let neighbour_text = &inline.text[neighbour.range.clone()];
361 let edge = if at_end {
362 neighbour_text.chars().next()
363 } else {
364 neighbour_text.chars().next_back()
365 };
366 !neighbour.style.code && edge.is_some_and(|edge| !edge.is_whitespace())
367 })
368 };
369 let previous = index
370 .checked_sub(1)
371 .and_then(|previous| inline.segments.get(previous));
372 if segment.style.code && touches(previous, false) {
373 padded.push(CODE_PADDING, StyleFlags::default(), None);
374 }
375 padded.push(text, segment.style, segment.link.as_deref());
376 if segment.style.code && touches(inline.segments.get(index + 1), true) {
377 padded.push(CODE_PADDING, StyleFlags::default(), None);
378 }
191 }
379 }
380 padded
192}
381}
193
382
194fn append_inline(spans: &[Span], style: StyleFlags, link: Option<&str>, out: &mut Inline) {
383fn append_inline(spans: &[Span], style: StyleFlags, link: Option<&str>, out: &mut Inline) {
@@ -216,6 +405,50 @@ fn append_inline(spans: &[Span], style: StyleFlags, link: Option<&str>, out: &mu
216 link,
405 link,
217 out,
406 out,
218 ),
407 ),
408 Span::Strike(children) => append_inline(
409 children,
410 StyleFlags {
411 strike: true,
412 ..style
413 },
414 link,
415 out,
416 ),
417 Span::Underline(children) => append_inline(
418 children,
419 StyleFlags {
420 underline: true,
421 ..style
422 },
423 link,
424 out,
425 ),
426 Span::Colored {
427 color,
428 background,
429 children,
430 } => append_inline(
431 children,
432 StyleFlags {
433 color: color.or(style.color),
434 background: background.or(style.background),
435 ..style
436 },
437 link,
438 out,
439 ),
440 Span::Heading { children, .. } => {
441 append_inline(
442 children,
443 StyleFlags {
444 bold: true,
445 ..style
446 },
447 link,
448 out,
449 );
450 out.push("\n", style, link);
451 }
219 Span::Code(text) => out.push(
452 Span::Code(text) => out.push(
220 text,
453 text,
221 StyleFlags {
454 StyleFlags {
@@ -252,11 +485,28 @@ fn append_inline(spans: &[Span], style: StyleFlags, link: Option<&str>, out: &mu
252 link,
485 link,
253 );
486 );
254 }
487 }
255 Span::LineBreak => out.push("\n", style, link),
488 Span::LineBreak | Span::Rule => out.push("\n", style, link),
256 Span::ListItem(children) | Span::Quote(children) => {
489 Span::Quote(children) | Span::BlockQuote(children) => {
257 append_inline(children, style, link, out);
490 append_inline(children, style, link, out);
258 out.push("\n", style, link);
491 out.push("\n", style, link);
259 }
492 }
493 Span::List { items, .. } => {
494 for item in items {
495 append_inline(item, style, link, out);
496 out.push("\n", style, link);
497 }
498 }
499 Span::Table { rows, .. } => {
500 for row in rows {
501 for (index, cell) in row.iter().enumerate() {
502 if index > 0 {
503 out.push(" ", style, link);
504 }
505 append_inline(cell, style, link, out);
506 }
507 out.push("\n", style, link);
508 }
509 }
260 Span::Image { .. } => out.push(IMAGE_PLACEHOLDER, style, link),
510 Span::Image { .. } => out.push(IMAGE_PLACEHOLDER, style, link),
261 }
511 }
262 }
512 }
@@ -467,29 +717,115 @@ mod tests {
467 blocks,
717 blocks,
468 vec![
718 vec![
469 Block::Paragraph(Inline::plain("before")),
719 Block::Paragraph(Inline::plain("before")),
470 Block::Code("let x = 1;".into()),
720 Block::Code {
721 language: None,
722 code: "let x = 1;".into()
723 },
471 Block::Paragraph(Inline::plain("after")),
724 Block::Paragraph(Inline::plain("after")),
472 ]
725 ]
473 );
726 );
474 }
727 }
475
728
476 #[test]
729 #[test]
477 fn list_items_and_quotes_are_blocks() {
730 fn lists_nest_and_quotes_are_blocks() {
478 let blocks = layout_blocks(&[
731 let blocks = layout_blocks(&[
479 Span::ListItem(vec![text("one")]),
732 Span::List {
480 Span::ListItem(vec![text("two")]),
733 ordered: true,
734 start: 3,
735 items: vec![
736 vec![text("one")],
737 vec![
738 text("two"),
739 Span::List {
740 ordered: false,
741 start: 1,
742 items: vec![vec![text("inner")]],
743 },
744 ],
745 ],
746 },
481 Span::Quote(vec![text("quoted")]),
747 Span::Quote(vec![text("quoted")]),
482 ]);
748 ]);
483 assert_eq!(
749 assert_eq!(
484 blocks,
750 blocks,
485 vec![
751 vec![
486 Block::ListItem(Inline::plain("one")),
752 Block::List {
487 Block::ListItem(Inline::plain("two")),
753 ordered: true,
488 Block::Quote(vec![Block::Paragraph(Inline::plain("quoted"))]),
754 start: 3,
755 items: vec![
756 vec![Block::Paragraph(Inline::plain("one"))],
757 vec![
758 Block::Paragraph(Inline::plain("two")),
759 Block::List {
760 ordered: false,
761 start: 1,
762 items: vec![vec![Block::Paragraph(Inline::plain("inner"))]],
763 },
764 ],
765 ],
766 },
767 Block::Reply(vec![Block::Paragraph(Inline::plain("quoted"))]),
489 ]
768 ]
490 );
769 );
491 }
770 }
492
771
772 #[test]
773 fn heading_rule_and_table_are_blocks() {
774 let blocks = layout_blocks(&[
775 Span::Heading {
776 level: 2,
777 children: vec![text("Title")],
778 },
779 Span::Rule,
780 Span::Table {
781 header: true,
782 rows: vec![vec![vec![text("a")], vec![text("b")]]],
783 },
784 ]);
785 assert_eq!(
786 blocks,
787 vec![
788 Block::Heading {
789 level: 2,
790 inline: Inline::plain("Title")
791 },
792 Block::Rule,
793 Block::Table {
794 header: true,
795 rows: vec![vec![Inline::plain("a"), Inline::plain("b")]],
796 },
797 ]
798 );
799 }
800
801 #[test]
802 fn strike_underline_and_color_become_flags() {
803 let inline = paragraph_inline(&[
804 Span::Strike(vec![text("old")]),
805 Span::Underline(vec![text("u")]),
806 Span::Colored {
807 color: Some(0xff0000),
808 background: Some(0xffff00),
809 children: vec![text("c")],
810 },
811 ]);
812 assert!(inline.segments[0].style.strike);
813 assert!(inline.segments[1].style.underline);
814 assert_eq!(inline.segments[2].style.color, Some(0xff0000));
815 assert_eq!(inline.segments[2].style.background, Some(0xffff00));
816 }
817
818 #[test]
819 fn inline_code_gets_room_only_next_to_text() {
820 let inline = paragraph_inline(&[
821 text("run "),
822 Span::Code("x".into()),
823 text(". "),
824 Span::Code("y".into()),
825 ]);
826 assert_eq!(inline.text, "run x\u{200a}. y");
827 }
828
493 #[test]
829 #[test]
494 fn image_becomes_placeholder() {
830 fn image_becomes_placeholder() {
495 let blocks = layout_blocks(&[Span::Image {
831 let blocks = layout_blocks(&[Span::Image {
crates/app/src/render/elements.rs +375 −35
@@ -1,11 +1,27 @@
1 1 use gpui_kit::component::{h_flex, v_flex};
2 use gpui_kit::prelude::FluentBuilder as _;
2 3 use gpui_kit::*;
3 4
4 5 use super::blocks::{Block, Inline, StyleFlags};
5 use super::selectable::SelectableRichText;
6 use super::selectable::{Pill, SelectableRichText};
7 use super::syntax::{self, Token};
6 8 use crate::theme;
9 use crate::views::widgets::symbol;
10
11 const LIST_GAP: f32 = 2.;
12 const MARKER_WIDTH: f32 = 18.;
13 const WIDE_MARKER_WIDTH: f32 = 26.;
14 const BULLETS: [&str; 3] = ["\u{2022}", "\u{25e6}", "\u{25aa}"];
15 const CODE_HEADER_MIN_LINES: usize = 3;
16 const PLAIN_LANGUAGE: &str = "text";
17 const MIN_CONTRAST: f32 = 4.5;
18 const HIGHLIGHT_ALPHA: f32 = 0.3;
7 19
8 20 pub fn render_blocks(blocks: &[Block], id: &str, own: bool, cx: &App) -> AnyElement {
21 render_block_list(blocks, id, own, 0, cx)
22 }
23
24 fn render_block_list(blocks: &[Block], id: &str, own: bool, depth: usize, cx: &App) -> AnyElement {
9 25 v_flex()
10 26 .w_full()
11 27 .gap(px(6.))
@@ -13,33 +29,23 @@ pub fn render_blocks(blocks: &[Block], id: &str, own: bool, cx: &App) -> AnyElem
13 29 blocks
14 30 .iter()
15 31 .enumerate()
16 .map(|(index, block)| render_block(block, format!("{id}-{index}"), own, cx)),
32 .map(|(index, block)| render_block(block, format!("{id}-{index}"), own, depth, cx)),
17 33 )
18 34 .into_any_element()
19 35 }
20 36
21 fn render_block(block: &Block, id: String, own: bool, cx: &App) -> AnyElement {
37 fn render_block(block: &Block, id: String, own: bool, depth: usize, cx: &App) -> AnyElement {
22 38 match block {
23 Block::Paragraph(inline) => render_inline(inline, id, own),
24 Block::Code(code) => div()
39 Block::Paragraph(inline) => render_inline(inline, id, own, cx),
40 Block::Heading { level, inline } => div()
25 41 .w_full()
26 .px(px(10.))
27 .py(px(8.))
28 .rounded(px(6.))
29 .bg(theme::code_background())
30 .border_1()
31 .border_color(theme::border_strong())
32 .text_color(theme::text_strong())
33 .font_family(code_font(cx))
34 .text_size(px(12.5))
35 .line_height(relative(1.5))
36 .child(SelectableRichText::new(
37 ElementId::Name(id.into()),
38 code.clone(),
39 Vec::new(),
40 ))
42 .text_size(px(heading_size(*level)))
43 .line_height(relative(1.3))
44 .font_weight(FontWeight::BOLD)
45 .child(render_inline(inline, id, own, cx))
41 46 .into_any_element(),
42 Block::Quote(children) => div()
47 Block::Code { language, code } => render_code(language.as_deref(), code, id, own, cx),
48 Block::Reply(children) => div()
43 49 .w_full()
44 50 .px(px(8.))
45 51 .py(px(3.))
@@ -47,45 +53,295 @@ fn render_block(block: &Block, id: String, own: bool, cx: &App) -> AnyElement {
47 53 .border_color(theme::accent())
48 54 .text_size(px(12.5))
49 55 .text_color(theme::text_muted())
50 .child(render_blocks(children, &id, own, cx))
56 .child(render_block_list(children, &id, own, depth, cx))
57 .into_any_element(),
58 Block::Quote(children) => div()
59 .w_full()
60 .px(px(8.))
61 .py(px(2.))
62 .border_l(px(3.))
63 .border_color(theme::border_strong())
64 .text_color(theme::text_soft())
65 .child(render_block_list(children, &id, own, depth, cx))
51 66 .into_any_element(),
52 Block::ListItem(inline) => h_flex()
67 Block::List {
68 ordered,
69 start,
70 items,
71 } => render_list(*ordered, *start, items, &id, own, depth, cx),
72 Block::Table { header, rows } => render_table(*header, rows, &id, own, cx),
73 Block::Rule => div()
53 74 .w_full()
54 .gap(px(8.))
55 .items_start()
56 .child(div().child("\u{2022}"))
57 .child(
58 div()
59 .flex_1()
60 .min_w_0()
61 .child(render_inline(inline, id, own)),
62 )
75 .h(px(1.))
76 .my(px(2.))
77 .bg(theme::rule(own))
63 78 .into_any_element(),
64 79 }
65 80 }
66 81
82 fn heading_size(level: u8) -> f32 {
83 match level {
84 1 => 18.,
85 2 => 16.,
86 _ => 14.,
87 }
88 }
89
90 fn render_code(language: Option<&str>, code: &str, id: String, own: bool, cx: &App) -> AnyElement {
91 let highlights = language
92 .and_then(|language| syntax::highlight(code, language))
93 .unwrap_or_default()
94 .into_iter()
95 .map(|(range, token)| (range, token_style(token)))
96 .collect();
97 let body = div()
98 .w_full()
99 .px(px(10.))
100 .py(px(8.))
101 .child(SelectableRichText::new(
102 ElementId::Name(id.clone().into()),
103 code.to_owned(),
104 highlights,
105 ));
106 let show_header = language.is_some() || code.lines().count() >= CODE_HEADER_MIN_LINES;
107 v_flex()
108 .w_full()
109 .rounded(px(8.))
110 .overflow_hidden()
111 .bg(theme::code_surface())
112 .text_color(theme::text_strong())
113 .font_family(code_font(cx))
114 .text_size(px(12.5))
115 .line_height(relative(1.5))
116 .when(show_header, |container| {
117 container.child(code_header(
118 language.unwrap_or(PLAIN_LANGUAGE),
119 code,
120 &id,
121 own,
122 ))
123 })
124 .child(body)
125 .into_any_element()
126 }
127
128 fn code_header(language: &str, code: &str, id: &str, own: bool) -> Div {
129 let muted = if own {
130 theme::own_meta()
131 } else {
132 theme::text_muted()
133 };
134 let code = code.to_owned();
135 h_flex()
136 .w_full()
137 .h(px(26.))
138 .pl(px(10.))
139 .pr(px(6.))
140 .justify_between()
141 .items_center()
142 .border_b_1()
143 .border_color(theme::code_header_border())
144 .font_family(theme::font_family())
145 .text_size(px(11.))
146 .text_color(muted)
147 .child(language.to_owned())
148 .child(
149 h_flex()
150 .id(ElementId::Name(format!("{id}-copy").into()))
151 .h(px(20.))
152 .px(px(6.))
153 .gap(px(4.))
154 .items_center()
155 .rounded(px(4.))
156 .cursor_pointer()
157 .hover(|button| button.bg(theme::inline_code_fill(false)))
158 .on_click(move |_, _, cx| {
159 cx.write_to_clipboard(ClipboardItem::new_string(code.clone()))
160 })
161 .child(symbol("content_copy", 13., muted))
162 .child("Copy"),
163 )
164 }
165
166 fn token_style(token: Token) -> HighlightStyle {
167 match token {
168 Token::Keyword => HighlightStyle {
169 color: Some(theme::accent_text()),
170 ..Default::default()
171 },
172 Token::String | Token::Number => HighlightStyle {
173 color: Some(theme::accent_soft()),
174 ..Default::default()
175 },
176 Token::Comment => HighlightStyle {
177 color: Some(theme::text_faint()),
178 font_style: Some(FontStyle::Italic),
179 ..Default::default()
180 },
181 }
182 }
183
184 fn render_list(
185 ordered: bool,
186 start: u32,
187 items: &[Vec<Block>],
188 id: &str,
189 own: bool,
190 depth: usize,
191 cx: &App,
192 ) -> AnyElement {
193 let last_number = start as usize + items.len().saturating_sub(1);
194 let marker_width = if ordered && last_number >= 10 {
195 WIDE_MARKER_WIDTH
196 } else {
197 MARKER_WIDTH
198 };
199 let marker_color = if own {
200 theme::own_meta()
201 } else {
202 theme::text_muted()
203 };
204 v_flex()
205 .w_full()
206 .gap(px(LIST_GAP))
207 .children(items.iter().enumerate().map(|(index, item)| {
208 let marker = if ordered {
209 format!("{}.", start as usize + index)
210 } else {
211 BULLETS[depth.min(BULLETS.len() - 1)].to_owned()
212 };
213 h_flex()
214 .w_full()
215 .items_start()
216 .child(
217 div()
218 .flex_none()
219 .w(px(marker_width))
220 .when(ordered, |marker| marker.pr(px(4.)).text_right())
221 .text_color(marker_color)
222 .child(marker),
223 )
224 .child(div().flex_1().min_w_0().child(render_list_item(
225 item,
226 &format!("{id}-{index}"),
227 own,
228 depth + 1,
229 cx,
230 )))
231 }))
232 .into_any_element()
233 }
234
235 fn render_list_item(blocks: &[Block], id: &str, own: bool, depth: usize, cx: &App) -> AnyElement {
236 v_flex()
237 .w_full()
238 .gap(px(LIST_GAP))
239 .children(
240 blocks
241 .iter()
242 .enumerate()
243 .map(|(index, block)| render_block(block, format!("{id}-{index}"), own, depth, cx)),
244 )
245 .into_any_element()
246 }
247
248 fn render_table(header: bool, rows: &[Vec<Inline>], id: &str, own: bool, cx: &App) -> AnyElement {
249 let columns = rows.iter().map(Vec::len).max().unwrap_or(0);
250 v_flex()
251 .w_full()
252 .border_t_1()
253 .border_l_1()
254 .border_color(theme::border_strong())
255 .text_size(px(13.))
256 .children(rows.iter().enumerate().map(|(row_index, row)| {
257 let is_header = header && row_index == 0;
258 h_flex()
259 .w_full()
260 .items_stretch()
261 .when(is_header, |line| {
262 line.bg(theme::table_header())
263 .font_weight(FontWeight::SEMIBOLD)
264 .text_color(theme::text_strong())
265 })
266 .children((0..columns).map(|column| {
267 let cell = div()
268 .flex_1()
269 .min_w_0()
270 .px(px(8.))
271 .py(px(4.))
272 .border_r_1()
273 .border_b_1()
274 .border_color(theme::border_strong());
275 match row.get(column) {
276 Some(inline) => cell.child(render_inline(
277 inline,
278 format!("{id}-{row_index}-{column}"),
279 own,
280 cx,
281 )),
282 None => cell,
283 }
284 }))
285 }))
286 .into_any_element()
287 }
288
67 289 fn code_font(cx: &App) -> SharedString {
68 290 use gpui_kit::component::ActiveTheme as _;
69 291 cx.theme().mono_font_family.clone()
70 292 }
71 293
72 fn render_inline(inline: &Inline, id: String, own: bool) -> AnyElement {
294 fn render_inline(inline: &Inline, id: String, own: bool, cx: &App) -> AnyElement {
73 295 let highlights = inline
74 296 .segments
75 297 .iter()
76 298 .filter(|segment| !segment.style.is_plain())
77 299 .map(|segment| (segment.range.clone(), highlight_for(segment.style, own)))
78 300 .collect::<Vec<_>>();
301 let mono = code_font(cx);
302 let font_overrides = inline
303 .segments
304 .iter()
305 .filter(|segment| segment.style.code)
306 .map(|segment| (segment.range.clone(), mono.clone()))
307 .collect();
308 let pills = inline
309 .segments
310 .iter()
311 .filter_map(|segment| pill_for(segment.range.clone(), segment.style, own))
312 .collect();
79 313 div()
80 314 .w_full()
81 315 .text_color(theme::text())
82 316 .child(
83 317 SelectableRichText::new(ElementId::Name(id.into()), inline.text.clone(), highlights)
84 .links(inline.links()),
318 .links(inline.links())
319 .font_overrides(font_overrides)
320 .pills(pills),
85 321 )
86 322 .into_any_element()
87 323 }
88 324
325 fn pill_for(range: std::ops::Range<usize>, style: StyleFlags, own: bool) -> Option<Pill> {
326 if style.code {
327 return Some(Pill {
328 range,
329 fill: theme::inline_code_fill(own),
330 border: Some(theme::inline_code_border()),
331 radius: px(4.),
332 });
333 }
334 let background = style.background?;
335 let mut fill: Hsla = rgb(background).into();
336 fill.a = HIGHLIGHT_ALPHA;
337 Some(Pill {
338 range,
339 fill,
340 border: None,
341 radius: px(3.),
342 })
343 }
344
89 345 fn highlight_for(style: StyleFlags, own: bool) -> HighlightStyle {
90 346 let mut highlight = HighlightStyle::default();
91 347 if style.bold {
@@ -94,8 +350,33 @@ fn highlight_for(style: StyleFlags, own: bool) -> HighlightStyle {
94 350 if style.italic {
95 351 highlight.font_style = Some(FontStyle::Italic);
96 352 }
353 if let Some(color) = style.color {
354 highlight.color = Some(readable(color, own));
355 }
97 356 if style.code {
98 highlight.background_color = Some(theme::code_background());
357 highlight.color = Some(if own {
358 theme::accent_soft()
359 } else {
360 theme::text_strong()
361 });
362 }
363 if style.underline {
364 highlight.underline = Some(UnderlineStyle {
365 thickness: px(1.),
366 color: None,
367 wavy: false,
368 });
369 }
370 if style.strike {
371 highlight.color = Some(if own {
372 theme::own_meta()
373 } else {
374 theme::text_muted()
375 });
376 highlight.strikethrough = Some(StrikethroughStyle {
377 thickness: px(1.),
378 color: None,
379 });
99 380 }
100 381 let accent = if own {
101 382 theme::accent_soft()
@@ -116,3 +397,62 @@ fn highlight_for(style: StyleFlags, own: bool) -> HighlightStyle {
116 397 }
117 398 highlight
118 399 }
400
401 fn readable(color: u32, own: bool) -> Hsla {
402 let background = Rgba::from(if own {
403 theme::bubble_own()
404 } else {
405 theme::bubble_other()
406 });
407 let mut foreground = rgb(color);
408 for _ in 0..10 {
409 if contrast(foreground, background) >= MIN_CONTRAST {
410 break;
411 }
412 foreground = Rgba {
413 r: foreground.r + (1. - foreground.r) * 0.2,
414 g: foreground.g + (1. - foreground.g) * 0.2,
415 b: foreground.b + (1. - foreground.b) * 0.2,
416 a: 1.,
417 };
418 }
419 foreground.into()
420 }
421
422 fn contrast(first: Rgba, second: Rgba) -> f32 {
423 let (lighter, darker) = {
424 let (a, b) = (luminance(first), luminance(second));
425 if a > b { (a, b) } else { (b, a) }
426 };
427 (lighter + 0.05) / (darker + 0.05)
428 }
429
430 fn luminance(color: Rgba) -> f32 {
431 let channel = |value: f32| {
432 if value <= 0.03928 {
433 value / 12.92
434 } else {
435 ((value + 0.055) / 1.055).powf(2.4)
436 }
437 };
438 0.2126 * channel(color.r) + 0.7152 * channel(color.g) + 0.0722 * channel(color.b)
439 }
440
441 #[cfg(test)]
442 mod tests {
443 use gpui_kit::{Rgba, rgb};
444
445 use super::{MIN_CONTRAST, contrast, readable};
446 use crate::theme;
447
448 #[test]
449 fn dark_text_color_is_lifted_to_readable_contrast() {
450 let lifted = Rgba::from(readable(0x000080, false));
451 assert!(contrast(lifted, Rgba::from(theme::bubble_other())) >= MIN_CONTRAST);
452 }
453
454 #[test]
455 fn light_text_color_stays_as_sent() {
456 assert_eq!(Rgba::from(readable(0xffd700, false)), rgb(0xffd700));
457 }
458 }
@@ -1,11 +1,27 @@
1use gpui_kit::component::{h_flex, v_flex};
1use gpui_kit::component::{h_flex, v_flex};
2use gpui_kit::prelude::FluentBuilder as _;
2use gpui_kit::*;
3use gpui_kit::*;
3
4
4use super::blocks::{Block, Inline, StyleFlags};
5use super::blocks::{Block, Inline, StyleFlags};
5use super::selectable::SelectableRichText;
6use super::selectable::{Pill, SelectableRichText};
7use super::syntax::{self, Token};
6use crate::theme;
8use crate::theme;
9use crate::views::widgets::symbol;
10
11const LIST_GAP: f32 = 2.;
12const MARKER_WIDTH: f32 = 18.;
13const WIDE_MARKER_WIDTH: f32 = 26.;
14const BULLETS: [&str; 3] = ["\u{2022}", "\u{25e6}", "\u{25aa}"];
15const CODE_HEADER_MIN_LINES: usize = 3;
16const PLAIN_LANGUAGE: &str = "text";
17const MIN_CONTRAST: f32 = 4.5;
18const HIGHLIGHT_ALPHA: f32 = 0.3;
7
19
8pub fn render_blocks(blocks: &[Block], id: &str, own: bool, cx: &App) -> AnyElement {
20pub fn render_blocks(blocks: &[Block], id: &str, own: bool, cx: &App) -> AnyElement {
21 render_block_list(blocks, id, own, 0, cx)
22}
23
24fn render_block_list(blocks: &[Block], id: &str, own: bool, depth: usize, cx: &App) -> AnyElement {
9 v_flex()
25 v_flex()
10 .w_full()
26 .w_full()
11 .gap(px(6.))
27 .gap(px(6.))
@@ -13,33 +29,23 @@ pub fn render_blocks(blocks: &[Block], id: &str, own: bool, cx: &App) -> AnyElem
13 blocks
29 blocks
14 .iter()
30 .iter()
15 .enumerate()
31 .enumerate()
16 .map(|(index, block)| render_block(block, format!("{id}-{index}"), own, cx)),
32 .map(|(index, block)| render_block(block, format!("{id}-{index}"), own, depth, cx)),
17 )
33 )
18 .into_any_element()
34 .into_any_element()
19}
35}
20
36
21fn render_block(block: &Block, id: String, own: bool, cx: &App) -> AnyElement {
37fn render_block(block: &Block, id: String, own: bool, depth: usize, cx: &App) -> AnyElement {
22 match block {
38 match block {
23 Block::Paragraph(inline) => render_inline(inline, id, own),
39 Block::Paragraph(inline) => render_inline(inline, id, own, cx),
24 Block::Code(code) => div()
40 Block::Heading { level, inline } => div()
25 .w_full()
41 .w_full()
26 .px(px(10.))
42 .text_size(px(heading_size(*level)))
27 .py(px(8.))
43 .line_height(relative(1.3))
28 .rounded(px(6.))
44 .font_weight(FontWeight::BOLD)
29 .bg(theme::code_background())
45 .child(render_inline(inline, id, own, cx))
30 .border_1()
31 .border_color(theme::border_strong())
32 .text_color(theme::text_strong())
33 .font_family(code_font(cx))
34 .text_size(px(12.5))
35 .line_height(relative(1.5))
36 .child(SelectableRichText::new(
37 ElementId::Name(id.into()),
38 code.clone(),
39 Vec::new(),
40 ))
41 .into_any_element(),
46 .into_any_element(),
42 Block::Quote(children) => div()
47 Block::Code { language, code } => render_code(language.as_deref(), code, id, own, cx),
48 Block::Reply(children) => div()
43 .w_full()
49 .w_full()
44 .px(px(8.))
50 .px(px(8.))
45 .py(px(3.))
51 .py(px(3.))
@@ -47,45 +53,295 @@ fn render_block(block: &Block, id: String, own: bool, cx: &App) -> AnyElement {
47 .border_color(theme::accent())
53 .border_color(theme::accent())
48 .text_size(px(12.5))
54 .text_size(px(12.5))
49 .text_color(theme::text_muted())
55 .text_color(theme::text_muted())
50 .child(render_blocks(children, &id, own, cx))
56 .child(render_block_list(children, &id, own, depth, cx))
57 .into_any_element(),
58 Block::Quote(children) => div()
59 .w_full()
60 .px(px(8.))
61 .py(px(2.))
62 .border_l(px(3.))
63 .border_color(theme::border_strong())
64 .text_color(theme::text_soft())
65 .child(render_block_list(children, &id, own, depth, cx))
51 .into_any_element(),
66 .into_any_element(),
52 Block::ListItem(inline) => h_flex()
67 Block::List {
68 ordered,
69 start,
70 items,
71 } => render_list(*ordered, *start, items, &id, own, depth, cx),
72 Block::Table { header, rows } => render_table(*header, rows, &id, own, cx),
73 Block::Rule => div()
53 .w_full()
74 .w_full()
54 .gap(px(8.))
75 .h(px(1.))
55 .items_start()
76 .my(px(2.))
56 .child(div().child("\u{2022}"))
77 .bg(theme::rule(own))
57 .child(
58 div()
59 .flex_1()
60 .min_w_0()
61 .child(render_inline(inline, id, own)),
62 )
63 .into_any_element(),
78 .into_any_element(),
64 }
79 }
65}
80}
66
81
82fn heading_size(level: u8) -> f32 {
83 match level {
84 1 => 18.,
85 2 => 16.,
86 _ => 14.,
87 }
88}
89
90fn render_code(language: Option<&str>, code: &str, id: String, own: bool, cx: &App) -> AnyElement {
91 let highlights = language
92 .and_then(|language| syntax::highlight(code, language))
93 .unwrap_or_default()
94 .into_iter()
95 .map(|(range, token)| (range, token_style(token)))
96 .collect();
97 let body = div()
98 .w_full()
99 .px(px(10.))
100 .py(px(8.))
101 .child(SelectableRichText::new(
102 ElementId::Name(id.clone().into()),
103 code.to_owned(),
104 highlights,
105 ));
106 let show_header = language.is_some() || code.lines().count() >= CODE_HEADER_MIN_LINES;
107 v_flex()
108 .w_full()
109 .rounded(px(8.))
110 .overflow_hidden()
111 .bg(theme::code_surface())
112 .text_color(theme::text_strong())
113 .font_family(code_font(cx))
114 .text_size(px(12.5))
115 .line_height(relative(1.5))
116 .when(show_header, |container| {
117 container.child(code_header(
118 language.unwrap_or(PLAIN_LANGUAGE),
119 code,
120 &id,
121 own,
122 ))
123 })
124 .child(body)
125 .into_any_element()
126}
127
128fn code_header(language: &str, code: &str, id: &str, own: bool) -> Div {
129 let muted = if own {
130 theme::own_meta()
131 } else {
132 theme::text_muted()
133 };
134 let code = code.to_owned();
135 h_flex()
136 .w_full()
137 .h(px(26.))
138 .pl(px(10.))
139 .pr(px(6.))
140 .justify_between()
141 .items_center()
142 .border_b_1()
143 .border_color(theme::code_header_border())
144 .font_family(theme::font_family())
145 .text_size(px(11.))
146 .text_color(muted)
147 .child(language.to_owned())
148 .child(
149 h_flex()
150 .id(ElementId::Name(format!("{id}-copy").into()))
151 .h(px(20.))
152 .px(px(6.))
153 .gap(px(4.))
154 .items_center()
155 .rounded(px(4.))
156 .cursor_pointer()
157 .hover(|button| button.bg(theme::inline_code_fill(false)))
158 .on_click(move |_, _, cx| {
159 cx.write_to_clipboard(ClipboardItem::new_string(code.clone()))
160 })
161 .child(symbol("content_copy", 13., muted))
162 .child("Copy"),
163 )
164}
165
166fn token_style(token: Token) -> HighlightStyle {
167 match token {
168 Token::Keyword => HighlightStyle {
169 color: Some(theme::accent_text()),
170 ..Default::default()
171 },
172 Token::String | Token::Number => HighlightStyle {
173 color: Some(theme::accent_soft()),
174 ..Default::default()
175 },
176 Token::Comment => HighlightStyle {
177 color: Some(theme::text_faint()),
178 font_style: Some(FontStyle::Italic),
179 ..Default::default()
180 },
181 }
182}
183
184fn render_list(
185 ordered: bool,
186 start: u32,
187 items: &[Vec<Block>],
188 id: &str,
189 own: bool,
190 depth: usize,
191 cx: &App,
192) -> AnyElement {
193 let last_number = start as usize + items.len().saturating_sub(1);
194 let marker_width = if ordered && last_number >= 10 {
195 WIDE_MARKER_WIDTH
196 } else {
197 MARKER_WIDTH
198 };
199 let marker_color = if own {
200 theme::own_meta()
201 } else {
202 theme::text_muted()
203 };
204 v_flex()
205 .w_full()
206 .gap(px(LIST_GAP))
207 .children(items.iter().enumerate().map(|(index, item)| {
208 let marker = if ordered {
209 format!("{}.", start as usize + index)
210 } else {
211 BULLETS[depth.min(BULLETS.len() - 1)].to_owned()
212 };
213 h_flex()
214 .w_full()
215 .items_start()
216 .child(
217 div()
218 .flex_none()
219 .w(px(marker_width))
220 .when(ordered, |marker| marker.pr(px(4.)).text_right())
221 .text_color(marker_color)
222 .child(marker),
223 )
224 .child(div().flex_1().min_w_0().child(render_list_item(
225 item,
226 &format!("{id}-{index}"),
227 own,
228 depth + 1,
229 cx,
230 )))
231 }))
232 .into_any_element()
233}
234
235fn render_list_item(blocks: &[Block], id: &str, own: bool, depth: usize, cx: &App) -> AnyElement {
236 v_flex()
237 .w_full()
238 .gap(px(LIST_GAP))
239 .children(
240 blocks
241 .iter()
242 .enumerate()
243 .map(|(index, block)| render_block(block, format!("{id}-{index}"), own, depth, cx)),
244 )
245 .into_any_element()
246}
247
248fn render_table(header: bool, rows: &[Vec<Inline>], id: &str, own: bool, cx: &App) -> AnyElement {
249 let columns = rows.iter().map(Vec::len).max().unwrap_or(0);
250 v_flex()
251 .w_full()
252 .border_t_1()
253 .border_l_1()
254 .border_color(theme::border_strong())
255 .text_size(px(13.))
256 .children(rows.iter().enumerate().map(|(row_index, row)| {
257 let is_header = header && row_index == 0;
258 h_flex()
259 .w_full()
260 .items_stretch()
261 .when(is_header, |line| {
262 line.bg(theme::table_header())
263 .font_weight(FontWeight::SEMIBOLD)
264 .text_color(theme::text_strong())
265 })
266 .children((0..columns).map(|column| {
267 let cell = div()
268 .flex_1()
269 .min_w_0()
270 .px(px(8.))
271 .py(px(4.))
272 .border_r_1()
273 .border_b_1()
274 .border_color(theme::border_strong());
275 match row.get(column) {
276 Some(inline) => cell.child(render_inline(
277 inline,
278 format!("{id}-{row_index}-{column}"),
279 own,
280 cx,
281 )),
282 None => cell,
283 }
284 }))
285 }))
286 .into_any_element()
287}
288
67fn code_font(cx: &App) -> SharedString {
289fn code_font(cx: &App) -> SharedString {
68 use gpui_kit::component::ActiveTheme as _;
290 use gpui_kit::component::ActiveTheme as _;
69 cx.theme().mono_font_family.clone()
291 cx.theme().mono_font_family.clone()
70}
292}
71
293
72fn render_inline(inline: &Inline, id: String, own: bool) -> AnyElement {
294fn render_inline(inline: &Inline, id: String, own: bool, cx: &App) -> AnyElement {
73 let highlights = inline
295 let highlights = inline
74 .segments
296 .segments
75 .iter()
297 .iter()
76 .filter(|segment| !segment.style.is_plain())
298 .filter(|segment| !segment.style.is_plain())
77 .map(|segment| (segment.range.clone(), highlight_for(segment.style, own)))
299 .map(|segment| (segment.range.clone(), highlight_for(segment.style, own)))
78 .collect::<Vec<_>>();
300 .collect::<Vec<_>>();
301 let mono = code_font(cx);
302 let font_overrides = inline
303 .segments
304 .iter()
305 .filter(|segment| segment.style.code)
306 .map(|segment| (segment.range.clone(), mono.clone()))
307 .collect();
308 let pills = inline
309 .segments
310 .iter()
311 .filter_map(|segment| pill_for(segment.range.clone(), segment.style, own))
312 .collect();
79 div()
313 div()
80 .w_full()
314 .w_full()
81 .text_color(theme::text())
315 .text_color(theme::text())
82 .child(
316 .child(
83 SelectableRichText::new(ElementId::Name(id.into()), inline.text.clone(), highlights)
317 SelectableRichText::new(ElementId::Name(id.into()), inline.text.clone(), highlights)
84 .links(inline.links()),
318 .links(inline.links())
319 .font_overrides(font_overrides)
320 .pills(pills),
85 )
321 )
86 .into_any_element()
322 .into_any_element()
87}
323}
88
324
325fn pill_for(range: std::ops::Range<usize>, style: StyleFlags, own: bool) -> Option<Pill> {
326 if style.code {
327 return Some(Pill {
328 range,
329 fill: theme::inline_code_fill(own),
330 border: Some(theme::inline_code_border()),
331 radius: px(4.),
332 });
333 }
334 let background = style.background?;
335 let mut fill: Hsla = rgb(background).into();
336 fill.a = HIGHLIGHT_ALPHA;
337 Some(Pill {
338 range,
339 fill,
340 border: None,
341 radius: px(3.),
342 })
343}
344
89fn highlight_for(style: StyleFlags, own: bool) -> HighlightStyle {
345fn highlight_for(style: StyleFlags, own: bool) -> HighlightStyle {
90 let mut highlight = HighlightStyle::default();
346 let mut highlight = HighlightStyle::default();
91 if style.bold {
347 if style.bold {
@@ -94,8 +350,33 @@ fn highlight_for(style: StyleFlags, own: bool) -> HighlightStyle {
94 if style.italic {
350 if style.italic {
95 highlight.font_style = Some(FontStyle::Italic);
351 highlight.font_style = Some(FontStyle::Italic);
96 }
352 }
353 if let Some(color) = style.color {
354 highlight.color = Some(readable(color, own));
355 }
97 if style.code {
356 if style.code {
98 highlight.background_color = Some(theme::code_background());
357 highlight.color = Some(if own {
358 theme::accent_soft()
359 } else {
360 theme::text_strong()
361 });
362 }
363 if style.underline {
364 highlight.underline = Some(UnderlineStyle {
365 thickness: px(1.),
366 color: None,
367 wavy: false,
368 });
369 }
370 if style.strike {
371 highlight.color = Some(if own {
372 theme::own_meta()
373 } else {
374 theme::text_muted()
375 });
376 highlight.strikethrough = Some(StrikethroughStyle {
377 thickness: px(1.),
378 color: None,
379 });
99 }
380 }
100 let accent = if own {
381 let accent = if own {
101 theme::accent_soft()
382 theme::accent_soft()
@@ -116,3 +397,62 @@ fn highlight_for(style: StyleFlags, own: bool) -> HighlightStyle {
116 }
397 }
117 highlight
398 highlight
118}
399}
400
401fn readable(color: u32, own: bool) -> Hsla {
402 let background = Rgba::from(if own {
403 theme::bubble_own()
404 } else {
405 theme::bubble_other()
406 });
407 let mut foreground = rgb(color);
408 for _ in 0..10 {
409 if contrast(foreground, background) >= MIN_CONTRAST {
410 break;
411 }
412 foreground = Rgba {
413 r: foreground.r + (1. - foreground.r) * 0.2,
414 g: foreground.g + (1. - foreground.g) * 0.2,
415 b: foreground.b + (1. - foreground.b) * 0.2,
416 a: 1.,
417 };
418 }
419 foreground.into()
420}
421
422fn contrast(first: Rgba, second: Rgba) -> f32 {
423 let (lighter, darker) = {
424 let (a, b) = (luminance(first), luminance(second));
425 if a > b { (a, b) } else { (b, a) }
426 };
427 (lighter + 0.05) / (darker + 0.05)
428}
429
430fn luminance(color: Rgba) -> f32 {
431 let channel = |value: f32| {
432 if value <= 0.03928 {
433 value / 12.92
434 } else {
435 ((value + 0.055) / 1.055).powf(2.4)
436 }
437 };
438 0.2126 * channel(color.r) + 0.7152 * channel(color.g) + 0.0722 * channel(color.b)
439}
440
441#[cfg(test)]
442mod tests {
443 use gpui_kit::{Rgba, rgb};
444
445 use super::{MIN_CONTRAST, contrast, readable};
446 use crate::theme;
447
448 #[test]
449 fn dark_text_color_is_lifted_to_readable_contrast() {
450 let lifted = Rgba::from(readable(0x000080, false));
451 assert!(contrast(lifted, Rgba::from(theme::bubble_other())) >= MIN_CONTRAST);
452 }
453
454 #[test]
455 fn light_text_color_stays_as_sent() {
456 assert_eq!(Rgba::from(readable(0xffd700, false)), rgb(0xffd700));
457 }
458}
crates/app/src/render/mod.rs +1 −0
@@ -1,6 +1,7 @@
1 1 pub mod blocks;
2 2 pub mod elements;
3 3 mod selectable;
4 mod syntax;
4 5
5 6 pub use blocks::{Block, layout_blocks};
6 7 pub use elements::render_blocks;
@@ -1,6 +1,7 @@
1pub mod blocks;
1pub mod blocks;
2pub mod elements;
2pub mod elements;
3mod selectable;
3mod selectable;
4mod syntax;
4
5
5pub use blocks::{Block, layout_blocks};
6pub use blocks::{Block, layout_blocks};
6pub use elements::render_blocks;
7pub use elements::render_blocks;
crates/app/src/render/selectable.rs +64 −1
@@ -7,6 +7,8 @@ use gpui_kit::base::{
7 7 };
8 8 use gpui_kit::*;
9 9
10 use super::blocks::CODE_PADDING;
11
10 12 const TIME_ROOM: char = '\u{2007}';
11 13 const HIT_SLOP: f32 = 12.;
12 14
@@ -16,12 +18,24 @@ pub struct Participant {
16 18 copied: Rc<RefCell<String>>,
17 19 }
18 20
21 const PILL_OUTSET: f32 = 3.;
22 const PILL_INSET_Y: f32 = 1.;
23
24 #[derive(Clone, Debug)]
25 pub struct Pill {
26 pub range: Range<usize>,
27 pub fill: Hsla,
28 pub border: Option<Hsla>,
29 pub radius: Pixels,
30 }
31
19 32 /// Styled text that takes part in the window text selection, with clickable link ranges.
20 33 pub struct SelectableRichText {
21 34 id: ElementId,
22 35 text: SharedString,
23 36 styled_text: StyledText,
24 37 links: Vec<(Range<usize>, String)>,
38 pills: Vec<Pill>,
25 39 }
26 40
27 41 impl SelectableRichText {
@@ -36,6 +50,7 @@ impl SelectableRichText {
36 50 styled_text: StyledText::new(text.clone()).with_highlights(highlights),
37 51 text,
38 52 links: Vec::new(),
53 pills: Vec::new(),
39 54 }
40 55 }
41 56
@@ -43,6 +58,53 @@ impl SelectableRichText {
43 58 self.links = links;
44 59 self
45 60 }
61
62 pub fn font_overrides(mut self, overrides: Vec<(Range<usize>, SharedString)>) -> Self {
63 if !overrides.is_empty() {
64 let styled_text = std::mem::replace(&mut self.styled_text, StyledText::new(""));
65 self.styled_text = styled_text.with_font_family_overrides(overrides);
66 }
67 self
68 }
69
70 pub fn pills(mut self, pills: Vec<Pill>) -> Self {
71 self.pills = pills;
72 self
73 }
74 }
75
76 fn paint_pills(pills: &[Pill], layout: &TextLayout, window: &mut Window) {
77 let line_height = layout.line_height();
78 let bounds = layout.bounds();
79 for pill in pills {
80 let (Some(start), Some(end)) = (
81 layout.position_for_index(pill.range.start),
82 layout.position_for_index(pill.range.end),
83 ) else {
84 continue;
85 };
86 for line in selection_quads(start, end, bounds, line_height) {
87 let line = Bounds::from_corners(
88 point(line.left() - px(PILL_OUTSET), line.top() + px(PILL_INSET_Y)),
89 point(
90 line.right() + px(PILL_OUTSET),
91 line.top() + line_height - px(PILL_INSET_Y),
92 ),
93 );
94 let (border_width, border_color) = match pill.border {
95 Some(color) => (px(1.), color),
96 None => (px(0.), transparent_black()),
97 };
98 window.paint_quad(quad(
99 line,
100 pill.radius,
101 pill.fill,
102 border_width,
103 border_color,
104 BorderStyle::Solid,
105 ));
106 }
107 }
46 108 }
47 109
48 110 fn link_at(
@@ -180,6 +242,7 @@ impl Element for SelectableRichText {
180 242 if selected_before != TextSelection::selected_text(window, cx) {
181 243 window.refresh();
182 244 }
245 paint_pills(&self.pills, &layout, window);
183 246 let color = Theme::global(cx).tokens.colors.selection;
184 247 let content_end = self.text.trim_end_matches(TIME_ROOM).len();
185 248 let mut copied = String::new();
@@ -188,7 +251,7 @@ impl Element for SelectableRichText {
188 251 if end_index <= range.start {
189 252 continue;
190 253 }
191 copied.push_str(&self.text[range.start..end_index]);
254 copied.push_str(&self.text[range.start..end_index].replace(CODE_PADDING, ""));
192 255 let (Some(start), Some(end)) = (
193 256 layout.position_for_index(range.start),
194 257 layout.position_for_index(end_index),
@@ -7,6 +7,8 @@ use gpui_kit::base::{
7};
7};
8use gpui_kit::*;
8use gpui_kit::*;
9
9
10use super::blocks::CODE_PADDING;
11
10const TIME_ROOM: char = '\u{2007}';
12const TIME_ROOM: char = '\u{2007}';
11const HIT_SLOP: f32 = 12.;
13const HIT_SLOP: f32 = 12.;
12
14
@@ -16,12 +18,24 @@ pub struct Participant {
16 copied: Rc<RefCell<String>>,
18 copied: Rc<RefCell<String>>,
17}
19}
18
20
21const PILL_OUTSET: f32 = 3.;
22const PILL_INSET_Y: f32 = 1.;
23
24#[derive(Clone, Debug)]
25pub struct Pill {
26 pub range: Range<usize>,
27 pub fill: Hsla,
28 pub border: Option<Hsla>,
29 pub radius: Pixels,
30}
31
19/// Styled text that takes part in the window text selection, with clickable link ranges.
32/// Styled text that takes part in the window text selection, with clickable link ranges.
20pub struct SelectableRichText {
33pub struct SelectableRichText {
21 id: ElementId,
34 id: ElementId,
22 text: SharedString,
35 text: SharedString,
23 styled_text: StyledText,
36 styled_text: StyledText,
24 links: Vec<(Range<usize>, String)>,
37 links: Vec<(Range<usize>, String)>,
38 pills: Vec<Pill>,
25}
39}
26
40
27impl SelectableRichText {
41impl SelectableRichText {
@@ -36,6 +50,7 @@ impl SelectableRichText {
36 styled_text: StyledText::new(text.clone()).with_highlights(highlights),
50 styled_text: StyledText::new(text.clone()).with_highlights(highlights),
37 text,
51 text,
38 links: Vec::new(),
52 links: Vec::new(),
53 pills: Vec::new(),
39 }
54 }
40 }
55 }
41
56
@@ -43,6 +58,53 @@ impl SelectableRichText {
43 self.links = links;
58 self.links = links;
44 self
59 self
45 }
60 }
61
62 pub fn font_overrides(mut self, overrides: Vec<(Range<usize>, SharedString)>) -> Self {
63 if !overrides.is_empty() {
64 let styled_text = std::mem::replace(&mut self.styled_text, StyledText::new(""));
65 self.styled_text = styled_text.with_font_family_overrides(overrides);
66 }
67 self
68 }
69
70 pub fn pills(mut self, pills: Vec<Pill>) -> Self {
71 self.pills = pills;
72 self
73 }
74}
75
76fn paint_pills(pills: &[Pill], layout: &TextLayout, window: &mut Window) {
77 let line_height = layout.line_height();
78 let bounds = layout.bounds();
79 for pill in pills {
80 let (Some(start), Some(end)) = (
81 layout.position_for_index(pill.range.start),
82 layout.position_for_index(pill.range.end),
83 ) else {
84 continue;
85 };
86 for line in selection_quads(start, end, bounds, line_height) {
87 let line = Bounds::from_corners(
88 point(line.left() - px(PILL_OUTSET), line.top() + px(PILL_INSET_Y)),
89 point(
90 line.right() + px(PILL_OUTSET),
91 line.top() + line_height - px(PILL_INSET_Y),
92 ),
93 );
94 let (border_width, border_color) = match pill.border {
95 Some(color) => (px(1.), color),
96 None => (px(0.), transparent_black()),
97 };
98 window.paint_quad(quad(
99 line,
100 pill.radius,
101 pill.fill,
102 border_width,
103 border_color,
104 BorderStyle::Solid,
105 ));
106 }
107 }
46}
108}
47
109
48fn link_at(
110fn link_at(
@@ -180,6 +242,7 @@ impl Element for SelectableRichText {
180 if selected_before != TextSelection::selected_text(window, cx) {
242 if selected_before != TextSelection::selected_text(window, cx) {
181 window.refresh();
243 window.refresh();
182 }
244 }
245 paint_pills(&self.pills, &layout, window);
183 let color = Theme::global(cx).tokens.colors.selection;
246 let color = Theme::global(cx).tokens.colors.selection;
184 let content_end = self.text.trim_end_matches(TIME_ROOM).len();
247 let content_end = self.text.trim_end_matches(TIME_ROOM).len();
185 let mut copied = String::new();
248 let mut copied = String::new();
@@ -188,7 +251,7 @@ impl Element for SelectableRichText {
188 if end_index <= range.start {
251 if end_index <= range.start {
189 continue;
252 continue;
190 }
253 }
191 copied.push_str(&self.text[range.start..end_index]);
254 copied.push_str(&self.text[range.start..end_index].replace(CODE_PADDING, ""));
192 let (Some(start), Some(end)) = (
255 let (Some(start), Some(end)) = (
193 layout.position_for_index(range.start),
256 layout.position_for_index(range.start),
194 layout.position_for_index(end_index),
257 layout.position_for_index(end_index),
crates/app/src/render/syntax.rs added +310 −0
@@ -0,0 +1,310 @@
1 use std::ops::Range;
2
3 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
4 pub enum Token {
5 Keyword,
6 String,
7 Number,
8 Comment,
9 }
10
11 struct Grammar {
12 line_comments: &'static [&'static str],
13 block_comment: Option<(&'static str, &'static str)>,
14 keywords: &'static [&'static str],
15 char_quotes: bool,
16 }
17
18 const C_LIKE_KEYWORDS: &[&str] = &[
19 "abstract",
20 "as",
21 "async",
22 "await",
23 "break",
24 "case",
25 "catch",
26 "class",
27 "const",
28 "continue",
29 "default",
30 "do",
31 "else",
32 "enum",
33 "export",
34 "extends",
35 "false",
36 "final",
37 "finally",
38 "fn",
39 "for",
40 "from",
41 "func",
42 "function",
43 "go",
44 "if",
45 "impl",
46 "import",
47 "in",
48 "interface",
49 "let",
50 "loop",
51 "match",
52 "mod",
53 "mut",
54 "namespace",
55 "new",
56 "null",
57 "override",
58 "package",
59 "private",
60 "protected",
61 "pub",
62 "public",
63 "readonly",
64 "return",
65 "self",
66 "static",
67 "struct",
68 "super",
69 "switch",
70 "this",
71 "throw",
72 "trait",
73 "true",
74 "try",
75 "type",
76 "typeof",
77 "use",
78 "using",
79 "var",
80 "void",
81 "where",
82 "while",
83 "yield",
84 ];
85 const PYTHON_KEYWORDS: &[&str] = &[
86 "and", "as", "async", "await", "break", "class", "continue", "def", "del", "elif", "else",
87 "except", "False", "finally", "for", "from", "if", "import", "in", "is", "lambda", "None",
88 "not", "or", "pass", "raise", "return", "True", "try", "while", "with", "yield",
89 ];
90 const SHELL_KEYWORDS: &[&str] = &[
91 "case", "do", "done", "elif", "else", "esac", "export", "fi", "for", "function", "if", "in",
92 "local", "return", "then", "while",
93 ];
94 const SQL_KEYWORDS: &[&str] = &[
95 "and", "as", "by", "create", "delete", "from", "group", "insert", "into", "join", "left",
96 "not", "null", "on", "or", "order", "select", "set", "table", "update", "values", "where",
97 ];
98
99 const C_LIKE: Grammar = Grammar {
100 line_comments: &["//"],
101 block_comment: Some(("/*", "*/")),
102 keywords: C_LIKE_KEYWORDS,
103 char_quotes: false,
104 };
105 const CHAR_LIKE: Grammar = Grammar {
106 char_quotes: true,
107 ..C_LIKE
108 };
109 const HASH: Grammar = Grammar {
110 line_comments: &["#"],
111 block_comment: None,
112 keywords: PYTHON_KEYWORDS,
113 char_quotes: false,
114 };
115 const SHELL: Grammar = Grammar {
116 line_comments: &["#"],
117 block_comment: None,
118 keywords: SHELL_KEYWORDS,
119 char_quotes: false,
120 };
121 const SQL: Grammar = Grammar {
122 line_comments: &["--"],
123 block_comment: Some(("/*", "*/")),
124 keywords: SQL_KEYWORDS,
125 char_quotes: false,
126 };
127 const MARKUP: Grammar = Grammar {
128 line_comments: &[],
129 block_comment: Some(("<!--", "-->")),
130 keywords: &[],
131 char_quotes: false,
132 };
133
134 fn grammar_for(language: &str) -> Option<&'static Grammar> {
135 match language.to_ascii_lowercase().as_str() {
136 "rust" | "rs" | "c" | "cpp" | "c++" | "csharp" | "cs" | "c#" | "java" | "go" | "kotlin"
137 | "scala" => Some(&CHAR_LIKE),
138 "javascript" | "js" | "jsx" | "typescript" | "ts" | "tsx" | "swift" | "php" | "json"
139 | "css" | "scss" | "less" | "dart" => Some(&C_LIKE),
140 "python" | "py" | "ruby" | "rb" | "yaml" | "yml" | "toml" | "r" | "perl" | "dockerfile"
141 | "makefile" => Some(&HASH),
142 "bash" | "sh" | "shell" | "zsh" | "powershell" | "ps1" => Some(&SHELL),
143 "sql" | "tsql" | "plsql" | "lua" => Some(&SQL),
144 "html" | "xml" | "svg" | "markdown" | "md" => Some(&MARKUP),
145 _ => None,
146 }
147 }
148
149 pub fn highlight(code: &str, language: &str) -> Option<Vec<(Range<usize>, Token)>> {
150 let grammar = grammar_for(language)?;
151 let sql = grammar.keywords == SQL_KEYWORDS;
152 let mut tokens = Vec::new();
153 let mut index = 0;
154 while index < code.len() {
155 let rest = &code[index..];
156 if let Some((open, close)) = grammar.block_comment
157 && rest.starts_with(open)
158 {
159 let end = rest[open.len()..].find(close).map_or(code.len(), |offset| {
160 index + open.len() + offset + close.len()
161 });
162 tokens.push((index..end, Token::Comment));
163 index = end;
164 continue;
165 }
166 if grammar
167 .line_comments
168 .iter()
169 .any(|marker| rest.starts_with(marker))
170 {
171 let end = rest.find('\n').map_or(code.len(), |offset| index + offset);
172 tokens.push((index..end, Token::Comment));
173 index = end;
174 continue;
175 }
176 let character = rest.chars().next().unwrap_or_default();
177 if character == '\'' && grammar.char_quotes && !is_char_literal(rest) {
178 index += 1;
179 continue;
180 }
181 if matches!(character, '"' | '\'' | '`') {
182 let end = string_end(code, index, character);
183 tokens.push((index..end, Token::String));
184 index = end;
185 continue;
186 }
187 if character.is_ascii_digit() {
188 let length = rest
189 .find(|next: char| !(next.is_ascii_alphanumeric() || next == '.' || next == '_'))
190 .unwrap_or(rest.len());
191 tokens.push((index..index + length, Token::Number));
192 index += length;
193 continue;
194 }
195 if character.is_alphabetic() || character == '_' {
196 let length = rest
197 .find(|next: char| !(next.is_alphanumeric() || next == '_'))
198 .unwrap_or(rest.len());
199 let word = &rest[..length];
200 let is_keyword = if sql {
201 grammar
202 .keywords
203 .iter()
204 .any(|keyword| keyword.eq_ignore_ascii_case(word))
205 } else {
206 grammar.keywords.contains(&word)
207 };
208 if is_keyword {
209 tokens.push((index..index + length, Token::Keyword));
210 }
211 index += length;
212 continue;
213 }
214 index += character.len_utf8();
215 }
216 Some(tokens)
217 }
218
219 fn is_char_literal(rest: &str) -> bool {
220 let mut characters = rest.chars().skip(1);
221 match characters.next() {
222 Some('\\') => characters.take(9).any(|character| character == '\''),
223 Some('\n') | None => false,
224 Some(_) => characters.next() == Some('\''),
225 }
226 }
227
228 fn string_end(code: &str, start: usize, quote: char) -> usize {
229 let mut escaped = false;
230 for (offset, character) in code[start + quote.len_utf8()..].char_indices() {
231 if character == '\n' && quote != '`' {
232 return start + quote.len_utf8() + offset;
233 }
234 if escaped {
235 escaped = false;
236 } else if character == '\\' {
237 escaped = true;
238 } else if character == quote {
239 return start + quote.len_utf8() + offset + character.len_utf8();
240 }
241 }
242 code.len()
243 }
244
245 #[cfg(test)]
246 mod tests {
247 use super::*;
248
249 fn kinds<'a>(code: &'a str, language: &str) -> Vec<(&'a str, Token)> {
250 highlight(code, language)
251 .unwrap()
252 .into_iter()
253 .map(|(range, token)| (&code[range], token))
254 .collect()
255 }
256
257 #[test]
258 fn rust_keywords_strings_and_comments() {
259 assert_eq!(
260 kinds("// x\nfn a() { \"b\" }", "rust"),
261 vec![
262 ("// x", Token::Comment),
263 ("fn", Token::Keyword),
264 ("\"b\"", Token::String),
265 ]
266 );
267 }
268
269 #[test]
270 fn escaped_quote_stays_in_string() {
271 assert_eq!(kinds(r#""a\"b" 1"#, "js")[0].0, r#""a\"b""#);
272 }
273
274 #[test]
275 fn unterminated_string_stops_at_line_end() {
276 assert_eq!(
277 kinds("x = 'abc\nreturn", "python"),
278 vec![("'abc", Token::String), ("return", Token::Keyword)]
279 );
280 }
281
282 #[test]
283 fn rust_lifetime_is_not_a_string() {
284 assert_eq!(
285 kinds("fn a<'b>(x: &'b str) -> char { 'c' }", "rust"),
286 vec![("fn", Token::Keyword), ("'c'", Token::String),]
287 );
288 assert_eq!(kinds(r"'\n'", "rust"), vec![(r"'\n'", Token::String)]);
289 }
290
291 #[test]
292 fn sql_keywords_ignore_case() {
293 assert_eq!(kinds("SELECT 1", "sql")[0], ("SELECT", Token::Keyword));
294 }
295
296 #[test]
297 fn unknown_language_has_no_highlight() {
298 assert!(highlight("x", "brainfuck").is_none());
299 }
300
301 #[test]
302 fn identifier_with_digits_is_not_a_number() {
303 assert!(kinds("let x1 = 2;", "rust").contains(&("2", Token::Number)));
304 assert!(
305 !kinds("let x1 = 2;", "rust")
306 .iter()
307 .any(|(text, _)| *text == "1")
308 );
309 }
310 }
@@ -0,0 +1,310 @@
1use std::ops::Range;
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4pub enum Token {
5 Keyword,
6 String,
7 Number,
8 Comment,
9}
10
11struct Grammar {
12 line_comments: &'static [&'static str],
13 block_comment: Option<(&'static str, &'static str)>,
14 keywords: &'static [&'static str],
15 char_quotes: bool,
16}
17
18const C_LIKE_KEYWORDS: &[&str] = &[
19 "abstract",
20 "as",
21 "async",
22 "await",
23 "break",
24 "case",
25 "catch",
26 "class",
27 "const",
28 "continue",
29 "default",
30 "do",
31 "else",
32 "enum",
33 "export",
34 "extends",
35 "false",
36 "final",
37 "finally",
38 "fn",
39 "for",
40 "from",
41 "func",
42 "function",
43 "go",
44 "if",
45 "impl",
46 "import",
47 "in",
48 "interface",
49 "let",
50 "loop",
51 "match",
52 "mod",
53 "mut",
54 "namespace",
55 "new",
56 "null",
57 "override",
58 "package",
59 "private",
60 "protected",
61 "pub",
62 "public",
63 "readonly",
64 "return",
65 "self",
66 "static",
67 "struct",
68 "super",
69 "switch",
70 "this",
71 "throw",
72 "trait",
73 "true",
74 "try",
75 "type",
76 "typeof",
77 "use",
78 "using",
79 "var",
80 "void",
81 "where",
82 "while",
83 "yield",
84];
85const PYTHON_KEYWORDS: &[&str] = &[
86 "and", "as", "async", "await", "break", "class", "continue", "def", "del", "elif", "else",
87 "except", "False", "finally", "for", "from", "if", "import", "in", "is", "lambda", "None",
88 "not", "or", "pass", "raise", "return", "True", "try", "while", "with", "yield",
89];
90const SHELL_KEYWORDS: &[&str] = &[
91 "case", "do", "done", "elif", "else", "esac", "export", "fi", "for", "function", "if", "in",
92 "local", "return", "then", "while",
93];
94const SQL_KEYWORDS: &[&str] = &[
95 "and", "as", "by", "create", "delete", "from", "group", "insert", "into", "join", "left",
96 "not", "null", "on", "or", "order", "select", "set", "table", "update", "values", "where",
97];
98
99const C_LIKE: Grammar = Grammar {
100 line_comments: &["//"],
101 block_comment: Some(("/*", "*/")),
102 keywords: C_LIKE_KEYWORDS,
103 char_quotes: false,
104};
105const CHAR_LIKE: Grammar = Grammar {
106 char_quotes: true,
107 ..C_LIKE
108};
109const HASH: Grammar = Grammar {
110 line_comments: &["#"],
111 block_comment: None,
112 keywords: PYTHON_KEYWORDS,
113 char_quotes: false,
114};
115const SHELL: Grammar = Grammar {
116 line_comments: &["#"],
117 block_comment: None,
118 keywords: SHELL_KEYWORDS,
119 char_quotes: false,
120};
121const SQL: Grammar = Grammar {
122 line_comments: &["--"],
123 block_comment: Some(("/*", "*/")),
124 keywords: SQL_KEYWORDS,
125 char_quotes: false,
126};
127const MARKUP: Grammar = Grammar {
128 line_comments: &[],
129 block_comment: Some(("<!--", "-->")),
130 keywords: &[],
131 char_quotes: false,
132};
133
134fn grammar_for(language: &str) -> Option<&'static Grammar> {
135 match language.to_ascii_lowercase().as_str() {
136 "rust" | "rs" | "c" | "cpp" | "c++" | "csharp" | "cs" | "c#" | "java" | "go" | "kotlin"
137 | "scala" => Some(&CHAR_LIKE),
138 "javascript" | "js" | "jsx" | "typescript" | "ts" | "tsx" | "swift" | "php" | "json"
139 | "css" | "scss" | "less" | "dart" => Some(&C_LIKE),
140 "python" | "py" | "ruby" | "rb" | "yaml" | "yml" | "toml" | "r" | "perl" | "dockerfile"
141 | "makefile" => Some(&HASH),
142 "bash" | "sh" | "shell" | "zsh" | "powershell" | "ps1" => Some(&SHELL),
143 "sql" | "tsql" | "plsql" | "lua" => Some(&SQL),
144 "html" | "xml" | "svg" | "markdown" | "md" => Some(&MARKUP),
145 _ => None,
146 }
147}
148
149pub fn highlight(code: &str, language: &str) -> Option<Vec<(Range<usize>, Token)>> {
150 let grammar = grammar_for(language)?;
151 let sql = grammar.keywords == SQL_KEYWORDS;
152 let mut tokens = Vec::new();
153 let mut index = 0;
154 while index < code.len() {
155 let rest = &code[index..];
156 if let Some((open, close)) = grammar.block_comment
157 && rest.starts_with(open)
158 {
159 let end = rest[open.len()..].find(close).map_or(code.len(), |offset| {
160 index + open.len() + offset + close.len()
161 });
162 tokens.push((index..end, Token::Comment));
163 index = end;
164 continue;
165 }
166 if grammar
167 .line_comments
168 .iter()
169 .any(|marker| rest.starts_with(marker))
170 {
171 let end = rest.find('\n').map_or(code.len(), |offset| index + offset);
172 tokens.push((index..end, Token::Comment));
173 index = end;
174 continue;
175 }
176 let character = rest.chars().next().unwrap_or_default();
177 if character == '\'' && grammar.char_quotes && !is_char_literal(rest) {
178 index += 1;
179 continue;
180 }
181 if matches!(character, '"' | '\'' | '`') {
182 let end = string_end(code, index, character);
183 tokens.push((index..end, Token::String));
184 index = end;
185 continue;
186 }
187 if character.is_ascii_digit() {
188 let length = rest
189 .find(|next: char| !(next.is_ascii_alphanumeric() || next == '.' || next == '_'))
190 .unwrap_or(rest.len());
191 tokens.push((index..index + length, Token::Number));
192 index += length;
193 continue;
194 }
195 if character.is_alphabetic() || character == '_' {
196 let length = rest
197 .find(|next: char| !(next.is_alphanumeric() || next == '_'))
198 .unwrap_or(rest.len());
199 let word = &rest[..length];
200 let is_keyword = if sql {
201 grammar
202 .keywords
203 .iter()
204 .any(|keyword| keyword.eq_ignore_ascii_case(word))
205 } else {
206 grammar.keywords.contains(&word)
207 };
208 if is_keyword {
209 tokens.push((index..index + length, Token::Keyword));
210 }
211 index += length;
212 continue;
213 }
214 index += character.len_utf8();
215 }
216 Some(tokens)
217}
218
219fn is_char_literal(rest: &str) -> bool {
220 let mut characters = rest.chars().skip(1);
221 match characters.next() {
222 Some('\\') => characters.take(9).any(|character| character == '\''),
223 Some('\n') | None => false,
224 Some(_) => characters.next() == Some('\''),
225 }
226}
227
228fn string_end(code: &str, start: usize, quote: char) -> usize {
229 let mut escaped = false;
230 for (offset, character) in code[start + quote.len_utf8()..].char_indices() {
231 if character == '\n' && quote != '`' {
232 return start + quote.len_utf8() + offset;
233 }
234 if escaped {
235 escaped = false;
236 } else if character == '\\' {
237 escaped = true;
238 } else if character == quote {
239 return start + quote.len_utf8() + offset + character.len_utf8();
240 }
241 }
242 code.len()
243}
244
245#[cfg(test)]
246mod tests {
247 use super::*;
248
249 fn kinds<'a>(code: &'a str, language: &str) -> Vec<(&'a str, Token)> {
250 highlight(code, language)
251 .unwrap()
252 .into_iter()
253 .map(|(range, token)| (&code[range], token))
254 .collect()
255 }
256
257 #[test]
258 fn rust_keywords_strings_and_comments() {
259 assert_eq!(
260 kinds("// x\nfn a() { \"b\" }", "rust"),
261 vec![
262 ("// x", Token::Comment),
263 ("fn", Token::Keyword),
264 ("\"b\"", Token::String),
265 ]
266 );
267 }
268
269 #[test]
270 fn escaped_quote_stays_in_string() {
271 assert_eq!(kinds(r#""a\"b" 1"#, "js")[0].0, r#""a\"b""#);
272 }
273
274 #[test]
275 fn unterminated_string_stops_at_line_end() {
276 assert_eq!(
277 kinds("x = 'abc\nreturn", "python"),
278 vec![("'abc", Token::String), ("return", Token::Keyword)]
279 );
280 }
281
282 #[test]
283 fn rust_lifetime_is_not_a_string() {
284 assert_eq!(
285 kinds("fn a<'b>(x: &'b str) -> char { 'c' }", "rust"),
286 vec![("fn", Token::Keyword), ("'c'", Token::String),]
287 );
288 assert_eq!(kinds(r"'\n'", "rust"), vec![(r"'\n'", Token::String)]);
289 }
290
291 #[test]
292 fn sql_keywords_ignore_case() {
293 assert_eq!(kinds("SELECT 1", "sql")[0], ("SELECT", Token::Keyword));
294 }
295
296 #[test]
297 fn unknown_language_has_no_highlight() {
298 assert!(highlight("x", "brainfuck").is_none());
299 }
300
301 #[test]
302 fn identifier_with_digits_is_not_a_number() {
303 assert!(kinds("let x1 = 2;", "rust").contains(&("2", Token::Number)));
304 assert!(
305 !kinds("let x1 = 2;", "rust")
306 .iter()
307 .any(|(text, _)| *text == "1")
308 );
309 }
310}
crates/app/src/rows.rs +3 −12
@@ -300,12 +300,7 @@ pub fn message_text(record: &MessageRecord) -> String {
300 300 .collect();
301 301 strip_image_placeholders(layout_blocks(&own_spans))
302 302 .into_iter()
303 .filter_map(|block| match block {
304 Block::Paragraph(inline) => Some(inline.text),
305 Block::ListItem(inline) => Some(format!("- {}", inline.text)),
306 Block::Code(code) => Some(format!("```\n{code}\n```")),
307 Block::Quote(_) => None,
308 })
303 .filter_map(|block| block.markdown())
309 304 .collect::<Vec<_>>()
310 305 .join("\n")
311 306 }
@@ -317,11 +312,7 @@ pub fn reply_excerpt(record: &MessageRecord) -> String {
317 312 .collect();
318 313 let text = strip_image_placeholders(layout_blocks(&own_spans))
319 314 .into_iter()
320 .find_map(|block| match block {
321 Block::Paragraph(inline) | Block::ListItem(inline) => Some(inline.text),
322 Block::Code(code) => Some(code),
323 Block::Quote(_) => None,
324 })
315 .find_map(|block| block.first_line())
325 316 .unwrap_or_default();
326 317 let first_line = text.lines().map(str::trim).find(|line| !line.is_empty());
327 318 let excerpt = match first_line {
@@ -604,7 +595,7 @@ mod tests {
604 595 text.body_html = "<p>first line</p><p>second</p>".into();
605 596 assert_eq!(reply_excerpt(&text), "first line");
606 597 let mut quoted = record("q", None, 8, 6);
607 quoted.body_html = "<blockquote>Jonas<br>old text</blockquote><p>my answer</p>".into();
598 quoted.body_html = r#"<blockquote itemtype="http://schema.skype.com/Reply">Jonas<br>old text</blockquote><p>my answer</p>"#.into();
608 599 assert_eq!(reply_excerpt(&quoted), "my answer");
609 600 let mut image = record("b", None, 8, 6);
610 601 image.body_html = "<img src=\"u\">".into();
@@ -300,12 +300,7 @@ pub fn message_text(record: &MessageRecord) -> String {
300 .collect();
300 .collect();
301 strip_image_placeholders(layout_blocks(&own_spans))
301 strip_image_placeholders(layout_blocks(&own_spans))
302 .into_iter()
302 .into_iter()
303 .filter_map(|block| match block {
303 .filter_map(|block| block.markdown())
304 Block::Paragraph(inline) => Some(inline.text),
305 Block::ListItem(inline) => Some(format!("- {}", inline.text)),
306 Block::Code(code) => Some(format!("```\n{code}\n```")),
307 Block::Quote(_) => None,
308 })
309 .collect::<Vec<_>>()
304 .collect::<Vec<_>>()
310 .join("\n")
305 .join("\n")
311}
306}
@@ -317,11 +312,7 @@ pub fn reply_excerpt(record: &MessageRecord) -> String {
317 .collect();
312 .collect();
318 let text = strip_image_placeholders(layout_blocks(&own_spans))
313 let text = strip_image_placeholders(layout_blocks(&own_spans))
319 .into_iter()
314 .into_iter()
320 .find_map(|block| match block {
315 .find_map(|block| block.first_line())
321 Block::Paragraph(inline) | Block::ListItem(inline) => Some(inline.text),
322 Block::Code(code) => Some(code),
323 Block::Quote(_) => None,
324 })
325 .unwrap_or_default();
316 .unwrap_or_default();
326 let first_line = text.lines().map(str::trim).find(|line| !line.is_empty());
317 let first_line = text.lines().map(str::trim).find(|line| !line.is_empty());
327 let excerpt = match first_line {
318 let excerpt = match first_line {
@@ -604,7 +595,7 @@ mod tests {
604 text.body_html = "<p>first line</p><p>second</p>".into();
595 text.body_html = "<p>first line</p><p>second</p>".into();
605 assert_eq!(reply_excerpt(&text), "first line");
596 assert_eq!(reply_excerpt(&text), "first line");
606 let mut quoted = record("q", None, 8, 6);
597 let mut quoted = record("q", None, 8, 6);
607 quoted.body_html = "<blockquote>Jonas<br>old text</blockquote><p>my answer</p>".into();
598 quoted.body_html = r#"<blockquote itemtype="http://schema.skype.com/Reply">Jonas<br>old text</blockquote><p>my answer</p>"#.into();
608 assert_eq!(reply_excerpt(&quoted), "my answer");
599 assert_eq!(reply_excerpt(&quoted), "my answer");
609 let mut image = record("b", None, 8, 6);
600 let mut image = record("b", None, 8, 6);
610 image.body_html = "<img src=\"u\">".into();
601 image.body_html = "<img src=\"u\">".into();
crates/app/src/theme.rs +41 −3
@@ -37,7 +37,13 @@ const OWN_META: u32 = 0xc9a28c;
37 37 const OWN_READ: u32 = 0xf5c4a5;
38 38 const DROP_BACKGROUND: u32 = 0xce6a3b14;
39 39 const SELECTION: u32 = 0xce6a3b66;
40 const CODE_BACKGROUND: u32 = 0x0b0b0c;
40 const CODE_SURFACE: u32 = 0x0000003d;
41 const CODE_HEADER_BORDER: u32 = 0xffffff0f;
42 const INLINE_CODE_FILL: u32 = 0xffffff14;
43 const INLINE_CODE_FILL_OWN: u32 = 0x0000003d;
44 const INLINE_CODE_BORDER: u32 = 0xffffff1a;
45 const TABLE_HEADER: u32 = 0xffffff0d;
46 const RULE_OWN: u32 = 0x6a3a25;
41 47 const BADGE_MUTED: u32 = 0x3f3f42;
42 48 const TOAST_MENTION: u32 = 0x2e1d15;
43 49 const GREEN: u32 = 0x22c55e;
@@ -129,6 +135,10 @@ pub fn apply(cx: &mut App) {
129 135 });
130 136 }
131 137
138 pub fn font_family() -> SharedString {
139 FONT_FAMILY.into()
140 }
141
132 142 pub fn background() -> Hsla {
133 143 color(BACKGROUND)
134 144 }
@@ -229,8 +239,36 @@ pub fn drop_background() -> Hsla {
229 239 color_with_alpha(DROP_BACKGROUND)
230 240 }
231 241
232 pub fn code_background() -> Hsla {
233 color(CODE_BACKGROUND)
242 pub fn code_surface() -> Hsla {
243 color_with_alpha(CODE_SURFACE)
244 }
245
246 pub fn code_header_border() -> Hsla {
247 color_with_alpha(CODE_HEADER_BORDER)
248 }
249
250 pub fn inline_code_fill(own: bool) -> Hsla {
251 color_with_alpha(if own {
252 INLINE_CODE_FILL_OWN
253 } else {
254 INLINE_CODE_FILL
255 })
256 }
257
258 pub fn inline_code_border() -> Hsla {
259 color_with_alpha(INLINE_CODE_BORDER)
260 }
261
262 pub fn table_header() -> Hsla {
263 color_with_alpha(TABLE_HEADER)
264 }
265
266 pub fn rule(own: bool) -> Hsla {
267 if own {
268 color(RULE_OWN)
269 } else {
270 border_strong()
271 }
234 272 }
235 273
236 274 pub fn badge_muted() -> Hsla {
@@ -37,7 +37,13 @@ const OWN_META: u32 = 0xc9a28c;
37const OWN_READ: u32 = 0xf5c4a5;
37const OWN_READ: u32 = 0xf5c4a5;
38const DROP_BACKGROUND: u32 = 0xce6a3b14;
38const DROP_BACKGROUND: u32 = 0xce6a3b14;
39const SELECTION: u32 = 0xce6a3b66;
39const SELECTION: u32 = 0xce6a3b66;
40const CODE_BACKGROUND: u32 = 0x0b0b0c;
40const CODE_SURFACE: u32 = 0x0000003d;
41const CODE_HEADER_BORDER: u32 = 0xffffff0f;
42const INLINE_CODE_FILL: u32 = 0xffffff14;
43const INLINE_CODE_FILL_OWN: u32 = 0x0000003d;
44const INLINE_CODE_BORDER: u32 = 0xffffff1a;
45const TABLE_HEADER: u32 = 0xffffff0d;
46const RULE_OWN: u32 = 0x6a3a25;
41const BADGE_MUTED: u32 = 0x3f3f42;
47const BADGE_MUTED: u32 = 0x3f3f42;
42const TOAST_MENTION: u32 = 0x2e1d15;
48const TOAST_MENTION: u32 = 0x2e1d15;
43const GREEN: u32 = 0x22c55e;
49const GREEN: u32 = 0x22c55e;
@@ -129,6 +135,10 @@ pub fn apply(cx: &mut App) {
129 });
135 });
130}
136}
131
137
138pub fn font_family() -> SharedString {
139 FONT_FAMILY.into()
140}
141
132pub fn background() -> Hsla {
142pub fn background() -> Hsla {
133 color(BACKGROUND)
143 color(BACKGROUND)
134}
144}
@@ -229,8 +239,36 @@ pub fn drop_background() -> Hsla {
229 color_with_alpha(DROP_BACKGROUND)
239 color_with_alpha(DROP_BACKGROUND)
230}
240}
231
241
232pub fn code_background() -> Hsla {
242pub fn code_surface() -> Hsla {
233 color(CODE_BACKGROUND)
243 color_with_alpha(CODE_SURFACE)
244}
245
246pub fn code_header_border() -> Hsla {
247 color_with_alpha(CODE_HEADER_BORDER)
248}
249
250pub fn inline_code_fill(own: bool) -> Hsla {
251 color_with_alpha(if own {
252 INLINE_CODE_FILL_OWN
253 } else {
254 INLINE_CODE_FILL
255 })
256}
257
258pub fn inline_code_border() -> Hsla {
259 color_with_alpha(INLINE_CODE_BORDER)
260}
261
262pub fn table_header() -> Hsla {
263 color_with_alpha(TABLE_HEADER)
264}
265
266pub fn rule(own: bool) -> Hsla {
267 if own {
268 color(RULE_OWN)
269 } else {
270 border_strong()
271 }
234}
272}
235
273
236pub fn badge_muted() -> Hsla {
274pub fn badge_muted() -> Hsla {
crates/app/src/views/message_row.rs +3 −7
@@ -317,13 +317,9 @@ fn meta_room(row: &MessageRow, own: bool) -> usize {
317 317
318 318 fn with_meta_room(blocks: &[Block], room: usize) -> Option<Vec<Block>> {
319 319 let mut padded = blocks.to_vec();
320 match padded.last_mut()? {
321 Block::Paragraph(inline) | Block::ListItem(inline) => {
322 *inline = inline.with_trailing_room(room);
323 Some(padded)
324 }
325 Block::Code(_) | Block::Quote(_) => None,
326 }
320 let inline = padded.last_mut()?.last_inline_mut()?;
321 *inline = inline.with_trailing_room(room);
322 Some(padded)
327 323 }
328 324
329 325 fn has_text(row: &MessageRow) -> bool {
@@ -317,13 +317,9 @@ fn meta_room(row: &MessageRow, own: bool) -> usize {
317
317
318fn with_meta_room(blocks: &[Block], room: usize) -> Option<Vec<Block>> {
318fn with_meta_room(blocks: &[Block], room: usize) -> Option<Vec<Block>> {
319 let mut padded = blocks.to_vec();
319 let mut padded = blocks.to_vec();
320 match padded.last_mut()? {
320 let inline = padded.last_mut()?.last_inline_mut()?;
321 Block::Paragraph(inline) | Block::ListItem(inline) => {
321 *inline = inline.with_trailing_room(room);
322 *inline = inline.with_trailing_room(room);
322 Some(padded)
323 Some(padded)
324 }
325 Block::Code(_) | Block::Quote(_) => None,
326 }
327}
323}
328
324
329fn has_text(row: &MessageRow) -> bool {
325fn has_text(row: &MessageRow) -> bool {
crates/core/src/spans.rs +212 −9
@@ -17,12 +17,33 @@ pub enum Span {
17 17 Mention {
18 18 name: String,
19 19 },
20 Strike(Vec<Span>),
21 Underline(Vec<Span>),
22 Colored {
23 color: Option<u32>,
24 background: Option<u32>,
25 children: Vec<Span>,
26 },
27 Heading {
28 level: u8,
29 children: Vec<Span>,
30 },
20 31 LineBreak,
21 ListItem(Vec<Span>),
32 Rule,
33 List {
34 ordered: bool,
35 start: u32,
36 items: Vec<Vec<Span>>,
37 },
38 Table {
39 header: bool,
40 rows: Vec<Vec<Vec<Span>>>,
41 },
22 42 Image {
23 43 hosted_content_url: String,
24 44 },
25 45 Quote(Vec<Span>),
46 BlockQuote(Vec<Span>),
26 47 }
27 48
28 49 const BLOCK_ELEMENTS: [&str; 12] = [
@@ -31,6 +52,9 @@ const BLOCK_ELEMENTS: [&str; 12] = [
31 52 const SKIPPED_ELEMENTS: [&str; 4] = ["script", "style", "attachment", "head"];
32 53 const LANGUAGE_PREFIX: &str = "language-";
33 54 const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";
55 const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";
56 const MAX_HEADING_LEVEL: u8 = 3;
57 const MARK_BACKGROUND: u32 = 0xffff00;
34 58 const MAX_CONSECUTIVE_BREAKS: usize = 2;
35 59
36 60 pub fn html_to_spans(html: &str) -> Vec<Span> {
@@ -79,25 +103,190 @@ fn convert_element(element: ElementRef<'_>, spans: &mut Vec<Span>) {
79 103 return;
80 104 }
81 105 match name {
82 "b" | "strong" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => {
83 spans.push(Span::Bold(convert_children(element)))
84 }
106 "b" | "strong" => spans.push(Span::Bold(convert_children(element))),
107 "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => spans.push(Span::Heading {
108 level: name[1..].parse::<u8>().unwrap_or(1).min(MAX_HEADING_LEVEL),
109 children: convert_children(element),
110 }),
85 111 "i" | "em" => spans.push(Span::Italic(convert_children(element))),
112 "s" | "strike" | "del" => spans.push(Span::Strike(convert_children(element))),
113 "u" | "ins" => spans.push(Span::Underline(convert_children(element))),
114 "span" | "font" | "mark" => push_colored(element, spans),
115 "ul" | "ol" => spans.push(list(element)),
116 "table" => spans.push(table(element)),
86 117 "code" => spans.push(Span::Code(raw_text(element))),
87 118 "pre" | "codeblock" => spans.push(code_block(element)),
88 119 "a" => push_link(element, spans),
89 120 "at" => spans.push(Span::Mention {
90 121 name: raw_text(element).trim().to_owned(),
91 122 }),
92 "br" | "hr" => spans.push(Span::LineBreak),
93 "li" => spans.push(Span::ListItem(convert_children(element))),
94 "blockquote" => spans.push(Span::Quote(convert_children(element))),
123 "br" => spans.push(Span::LineBreak),
124 "hr" => spans.push(Span::Rule),
125 "li" => spans.push(Span::List {
126 ordered: false,
127 start: 1,
128 items: vec![convert_children(element)],
129 }),
130 "blockquote" if is_reply(element) => spans.push(Span::Quote(convert_children(element))),
131 "blockquote" => spans.push(Span::BlockQuote(convert_children(element))),
95 132 "emoji" => push_emoji(element, spans),
96 133 "img" => push_image(element, spans),
97 134 _ => spans.extend(convert_children(element)),
98 135 }
99 136 }
100 137
138 fn is_reply(element: ElementRef<'_>) -> bool {
139 element
140 .value()
141 .attr("itemtype")
142 .is_some_and(|itemtype| itemtype.contains(REPLY_ITEMTYPE))
143 }
144
145 fn list(element: ElementRef<'_>) -> Span {
146 let mut items: Vec<Vec<Span>> = Vec::new();
147 for child in element.children().filter_map(ElementRef::wrap) {
148 match child.value().name() {
149 "li" => items.push(convert_children(child)),
150 "ul" | "ol" => match items.last_mut() {
151 Some(previous) => previous.push(list(child)),
152 None => items.push(vec![list(child)]),
153 },
154 _ => {}
155 }
156 }
157 Span::List {
158 ordered: element.value().name() == "ol",
159 start: element
160 .value()
161 .attr("start")
162 .and_then(|start| start.trim().parse().ok())
163 .unwrap_or(1),
164 items,
165 }
166 }
167
168 fn table(element: ElementRef<'_>) -> Span {
169 let rows: Vec<ElementRef<'_>> = element
170 .descendants()
171 .filter_map(ElementRef::wrap)
172 .filter(|row| row.value().name() == "tr" && belongs_to(*row, element))
173 .collect();
174 let header = rows.first().is_some_and(|row| {
175 let in_head = row
176 .parent()
177 .and_then(ElementRef::wrap)
178 .is_some_and(|parent| parent.value().name() == "thead");
179 let mut cells = cells_of(*row).peekable();
180 in_head || (cells.peek().is_some() && cells.all(|cell| cell.value().name() == "th"))
181 });
182 Span::Table {
183 header,
184 rows: rows
185 .into_iter()
186 .map(|row| cells_of(row).map(convert_children).collect())
187 .filter(|cells: &Vec<Vec<Span>>| !cells.is_empty())
188 .collect(),
189 }
190 }
191
192 fn belongs_to(row: ElementRef<'_>, table: ElementRef<'_>) -> bool {
193 row.ancestors()
194 .filter_map(ElementRef::wrap)
195 .find(|ancestor| ancestor.value().name() == "table")
196 .is_some_and(|owner| owner.id() == table.id())
197 }
198
199 fn cells_of<'a>(row: ElementRef<'a>) -> impl Iterator<Item = ElementRef<'a>> {
200 row.children()
201 .filter_map(ElementRef::wrap)
202 .filter(|cell| matches!(cell.value().name(), "td" | "th"))
203 }
204
205 fn push_colored(element: ElementRef<'_>, spans: &mut Vec<Span>) {
206 let value = element.value();
207 let style = value.attr("style").unwrap_or_default();
208 let color = style_value(style, "color")
209 .or_else(|| value.attr("color"))
210 .and_then(parse_color);
211 let background = style_value(style, "background-color")
212 .or_else(|| style_value(style, "background"))
213 .and_then(parse_color)
214 .or((value.name() == "mark").then_some(MARK_BACKGROUND));
215 let children = convert_children(element);
216 if color.is_none() && background.is_none() {
217 spans.extend(children);
218 } else {
219 spans.push(Span::Colored {
220 color,
221 background,
222 children,
223 });
224 }
225 }
226
227 fn style_value<'a>(style: &'a str, property: &str) -> Option<&'a str> {
228 style.split(';').find_map(|declaration| {
229 let (name, value) = declaration.split_once(':')?;
230 (name.trim().eq_ignore_ascii_case(property)).then(|| value.trim())
231 })
232 }
233
234 pub fn parse_color(value: &str) -> Option<u32> {
235 let value = value.trim().to_ascii_lowercase();
236 if let Some(hex) = value.strip_prefix('#') {
237 return match hex.len() {
238 3 => {
239 let expanded: String = hex.chars().flat_map(|digit| [digit, digit]).collect();
240 u32::from_str_radix(&expanded, 16).ok()
241 }
242 6 => u32::from_str_radix(hex, 16).ok(),
243 _ => None,
244 };
245 }
246 if let Some(arguments) = value
247 .strip_prefix("rgba(")
248 .or_else(|| value.strip_prefix("rgb("))
249 .and_then(|rest| rest.strip_suffix(')'))
250 {
251 let channels: Vec<u32> = arguments
252 .split(',')
253 .take(3)
254 .map(|channel| {
255 channel
256 .trim()
257 .parse::<f32>()
258 .ok()
259 .map(|level| level.clamp(0., 255.) as u32)
260 })
261 .collect::<Option<_>>()?;
262 let [red, green, blue] = channels[..] else {
263 return None;
264 };
265 return Some(red << 16 | green << 8 | blue);
266 }
267 NAMED_COLORS
268 .iter()
269 .find(|(name, _)| *name == value)
270 .map(|(_, hex)| *hex)
271 }
272
273 const NAMED_COLORS: [(&str, u32); 14] = [
274 ("black", 0x000000),
275 ("white", 0xffffff),
276 ("red", 0xff0000),
277 ("green", 0x008000),
278 ("lime", 0x00ff00),
279 ("blue", 0x0000ff),
280 ("yellow", 0xffff00),
281 ("orange", 0xffa500),
282 ("purple", 0x800080),
283 ("fuchsia", 0xff00ff),
284 ("aqua", 0x00ffff),
285 ("teal", 0x008080),
286 ("gray", 0x808080),
287 ("grey", 0x808080),
288 ];
289
101 290 fn code_block(element: ElementRef<'_>) -> Span {
102 291 let language = language_of(element).or_else(|| {
103 292 element
@@ -179,9 +368,15 @@ fn tidy(spans: &mut Vec<Span>) {
179 368 match span {
180 369 Span::Bold(children)
181 370 | Span::Italic(children)
182 | Span::ListItem(children)
371 | Span::Strike(children)
372 | Span::Underline(children)
373 | Span::Colored { children, .. }
374 | Span::Heading { children, .. }
183 375 | Span::Quote(children)
376 | Span::BlockQuote(children)
184 377 | Span::Link { children, .. } => tidy(children),
378 Span::List { items, .. } => items.iter_mut().for_each(tidy),
379 Span::Table { rows, .. } => rows.iter_mut().flatten().for_each(tidy),
185 380 _ => {}
186 381 }
187 382 }
@@ -202,7 +397,15 @@ fn collapse_whitespace(spans: &mut Vec<Span>) {
202 397 let at_edge = |neighbour: Option<&Span>| {
203 398 matches!(
204 399 neighbour,
205 None | Some(Span::LineBreak | Span::ListItem(_) | Span::Quote(_))
400 None | Some(
401 Span::LineBreak
402 | Span::Rule
403 | Span::List { .. }
404 | Span::Table { .. }
405 | Span::Heading { .. }
406 | Span::Quote(_)
407 | Span::BlockQuote(_)
408 )
206 409 )
207 410 };
208 411 if at_edge(collapsed.last()) {
@@ -17,12 +17,33 @@ pub enum Span {
17 Mention {
17 Mention {
18 name: String,
18 name: String,
19 },
19 },
20 Strike(Vec<Span>),
21 Underline(Vec<Span>),
22 Colored {
23 color: Option<u32>,
24 background: Option<u32>,
25 children: Vec<Span>,
26 },
27 Heading {
28 level: u8,
29 children: Vec<Span>,
30 },
20 LineBreak,
31 LineBreak,
21 ListItem(Vec<Span>),
32 Rule,
33 List {
34 ordered: bool,
35 start: u32,
36 items: Vec<Vec<Span>>,
37 },
38 Table {
39 header: bool,
40 rows: Vec<Vec<Vec<Span>>>,
41 },
22 Image {
42 Image {
23 hosted_content_url: String,
43 hosted_content_url: String,
24 },
44 },
25 Quote(Vec<Span>),
45 Quote(Vec<Span>),
46 BlockQuote(Vec<Span>),
26}
47}
27
48
28const BLOCK_ELEMENTS: [&str; 12] = [
49const BLOCK_ELEMENTS: [&str; 12] = [
@@ -31,6 +52,9 @@ const BLOCK_ELEMENTS: [&str; 12] = [
31const SKIPPED_ELEMENTS: [&str; 4] = ["script", "style", "attachment", "head"];
52const SKIPPED_ELEMENTS: [&str; 4] = ["script", "style", "attachment", "head"];
32const LANGUAGE_PREFIX: &str = "language-";
53const LANGUAGE_PREFIX: &str = "language-";
33const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";
54const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";
55const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";
56const MAX_HEADING_LEVEL: u8 = 3;
57const MARK_BACKGROUND: u32 = 0xffff00;
34const MAX_CONSECUTIVE_BREAKS: usize = 2;
58const MAX_CONSECUTIVE_BREAKS: usize = 2;
35
59
36pub fn html_to_spans(html: &str) -> Vec<Span> {
60pub fn html_to_spans(html: &str) -> Vec<Span> {
@@ -79,25 +103,190 @@ fn convert_element(element: ElementRef<'_>, spans: &mut Vec<Span>) {
79 return;
103 return;
80 }
104 }
81 match name {
105 match name {
82 "b" | "strong" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => {
106 "b" | "strong" => spans.push(Span::Bold(convert_children(element))),
83 spans.push(Span::Bold(convert_children(element)))
107 "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => spans.push(Span::Heading {
84 }
108 level: name[1..].parse::<u8>().unwrap_or(1).min(MAX_HEADING_LEVEL),
109 children: convert_children(element),
110 }),
85 "i" | "em" => spans.push(Span::Italic(convert_children(element))),
111 "i" | "em" => spans.push(Span::Italic(convert_children(element))),
112 "s" | "strike" | "del" => spans.push(Span::Strike(convert_children(element))),
113 "u" | "ins" => spans.push(Span::Underline(convert_children(element))),
114 "span" | "font" | "mark" => push_colored(element, spans),
115 "ul" | "ol" => spans.push(list(element)),
116 "table" => spans.push(table(element)),
86 "code" => spans.push(Span::Code(raw_text(element))),
117 "code" => spans.push(Span::Code(raw_text(element))),
87 "pre" | "codeblock" => spans.push(code_block(element)),
118 "pre" | "codeblock" => spans.push(code_block(element)),
88 "a" => push_link(element, spans),
119 "a" => push_link(element, spans),
89 "at" => spans.push(Span::Mention {
120 "at" => spans.push(Span::Mention {
90 name: raw_text(element).trim().to_owned(),
121 name: raw_text(element).trim().to_owned(),
91 }),
122 }),
92 "br" | "hr" => spans.push(Span::LineBreak),
123 "br" => spans.push(Span::LineBreak),
93 "li" => spans.push(Span::ListItem(convert_children(element))),
124 "hr" => spans.push(Span::Rule),
94 "blockquote" => spans.push(Span::Quote(convert_children(element))),
125 "li" => spans.push(Span::List {
126 ordered: false,
127 start: 1,
128 items: vec![convert_children(element)],
129 }),
130 "blockquote" if is_reply(element) => spans.push(Span::Quote(convert_children(element))),
131 "blockquote" => spans.push(Span::BlockQuote(convert_children(element))),
95 "emoji" => push_emoji(element, spans),
132 "emoji" => push_emoji(element, spans),
96 "img" => push_image(element, spans),
133 "img" => push_image(element, spans),
97 _ => spans.extend(convert_children(element)),
134 _ => spans.extend(convert_children(element)),
98 }
135 }
99}
136}
100
137
138fn is_reply(element: ElementRef<'_>) -> bool {
139 element
140 .value()
141 .attr("itemtype")
142 .is_some_and(|itemtype| itemtype.contains(REPLY_ITEMTYPE))
143}
144
145fn list(element: ElementRef<'_>) -> Span {
146 let mut items: Vec<Vec<Span>> = Vec::new();
147 for child in element.children().filter_map(ElementRef::wrap) {
148 match child.value().name() {
149 "li" => items.push(convert_children(child)),
150 "ul" | "ol" => match items.last_mut() {
151 Some(previous) => previous.push(list(child)),
152 None => items.push(vec![list(child)]),
153 },
154 _ => {}
155 }
156 }
157 Span::List {
158 ordered: element.value().name() == "ol",
159 start: element
160 .value()
161 .attr("start")
162 .and_then(|start| start.trim().parse().ok())
163 .unwrap_or(1),
164 items,
165 }
166}
167
168fn table(element: ElementRef<'_>) -> Span {
169 let rows: Vec<ElementRef<'_>> = element
170 .descendants()
171 .filter_map(ElementRef::wrap)
172 .filter(|row| row.value().name() == "tr" && belongs_to(*row, element))
173 .collect();
174 let header = rows.first().is_some_and(|row| {
175 let in_head = row
176 .parent()
177 .and_then(ElementRef::wrap)
178 .is_some_and(|parent| parent.value().name() == "thead");
179 let mut cells = cells_of(*row).peekable();
180 in_head || (cells.peek().is_some() && cells.all(|cell| cell.value().name() == "th"))
181 });
182 Span::Table {
183 header,
184 rows: rows
185 .into_iter()
186 .map(|row| cells_of(row).map(convert_children).collect())
187 .filter(|cells: &Vec<Vec<Span>>| !cells.is_empty())
188 .collect(),
189 }
190}
191
192fn belongs_to(row: ElementRef<'_>, table: ElementRef<'_>) -> bool {
193 row.ancestors()
194 .filter_map(ElementRef::wrap)
195 .find(|ancestor| ancestor.value().name() == "table")
196 .is_some_and(|owner| owner.id() == table.id())
197}
198
199fn cells_of<'a>(row: ElementRef<'a>) -> impl Iterator<Item = ElementRef<'a>> {
200 row.children()
201 .filter_map(ElementRef::wrap)
202 .filter(|cell| matches!(cell.value().name(), "td" | "th"))
203}
204
205fn push_colored(element: ElementRef<'_>, spans: &mut Vec<Span>) {
206 let value = element.value();
207 let style = value.attr("style").unwrap_or_default();
208 let color = style_value(style, "color")
209 .or_else(|| value.attr("color"))
210 .and_then(parse_color);
211 let background = style_value(style, "background-color")
212 .or_else(|| style_value(style, "background"))
213 .and_then(parse_color)
214 .or((value.name() == "mark").then_some(MARK_BACKGROUND));
215 let children = convert_children(element);
216 if color.is_none() && background.is_none() {
217 spans.extend(children);
218 } else {
219 spans.push(Span::Colored {
220 color,
221 background,
222 children,
223 });
224 }
225}
226
227fn style_value<'a>(style: &'a str, property: &str) -> Option<&'a str> {
228 style.split(';').find_map(|declaration| {
229 let (name, value) = declaration.split_once(':')?;
230 (name.trim().eq_ignore_ascii_case(property)).then(|| value.trim())
231 })
232}
233
234pub fn parse_color(value: &str) -> Option<u32> {
235 let value = value.trim().to_ascii_lowercase();
236 if let Some(hex) = value.strip_prefix('#') {
237 return match hex.len() {
238 3 => {
239 let expanded: String = hex.chars().flat_map(|digit| [digit, digit]).collect();
240 u32::from_str_radix(&expanded, 16).ok()
241 }
242 6 => u32::from_str_radix(hex, 16).ok(),
243 _ => None,
244 };
245 }
246 if let Some(arguments) = value
247 .strip_prefix("rgba(")
248 .or_else(|| value.strip_prefix("rgb("))
249 .and_then(|rest| rest.strip_suffix(')'))
250 {
251 let channels: Vec<u32> = arguments
252 .split(',')
253 .take(3)
254 .map(|channel| {
255 channel
256 .trim()
257 .parse::<f32>()
258 .ok()
259 .map(|level| level.clamp(0., 255.) as u32)
260 })
261 .collect::<Option<_>>()?;
262 let [red, green, blue] = channels[..] else {
263 return None;
264 };
265 return Some(red << 16 | green << 8 | blue);
266 }
267 NAMED_COLORS
268 .iter()
269 .find(|(name, _)| *name == value)
270 .map(|(_, hex)| *hex)
271}
272
273const NAMED_COLORS: [(&str, u32); 14] = [
274 ("black", 0x000000),
275 ("white", 0xffffff),
276 ("red", 0xff0000),
277 ("green", 0x008000),
278 ("lime", 0x00ff00),
279 ("blue", 0x0000ff),
280 ("yellow", 0xffff00),
281 ("orange", 0xffa500),
282 ("purple", 0x800080),
283 ("fuchsia", 0xff00ff),
284 ("aqua", 0x00ffff),
285 ("teal", 0x008080),
286 ("gray", 0x808080),
287 ("grey", 0x808080),
288];
289
101fn code_block(element: ElementRef<'_>) -> Span {
290fn code_block(element: ElementRef<'_>) -> Span {
102 let language = language_of(element).or_else(|| {
291 let language = language_of(element).or_else(|| {
103 element
292 element
@@ -179,9 +368,15 @@ fn tidy(spans: &mut Vec<Span>) {
179 match span {
368 match span {
180 Span::Bold(children)
369 Span::Bold(children)
181 | Span::Italic(children)
370 | Span::Italic(children)
182 | Span::ListItem(children)
371 | Span::Strike(children)
372 | Span::Underline(children)
373 | Span::Colored { children, .. }
374 | Span::Heading { children, .. }
183 | Span::Quote(children)
375 | Span::Quote(children)
376 | Span::BlockQuote(children)
184 | Span::Link { children, .. } => tidy(children),
377 | Span::Link { children, .. } => tidy(children),
378 Span::List { items, .. } => items.iter_mut().for_each(tidy),
379 Span::Table { rows, .. } => rows.iter_mut().flatten().for_each(tidy),
185 _ => {}
380 _ => {}
186 }
381 }
187 }
382 }
@@ -202,7 +397,15 @@ fn collapse_whitespace(spans: &mut Vec<Span>) {
202 let at_edge = |neighbour: Option<&Span>| {
397 let at_edge = |neighbour: Option<&Span>| {
203 matches!(
398 matches!(
204 neighbour,
399 neighbour,
205 None | Some(Span::LineBreak | Span::ListItem(_) | Span::Quote(_))
400 None | Some(
401 Span::LineBreak
402 | Span::Rule
403 | Span::List { .. }
404 | Span::Table { .. }
405 | Span::Heading { .. }
406 | Span::Quote(_)
407 | Span::BlockQuote(_)
408 )
206 )
409 )
207 };
410 };
208 if at_edge(collapsed.last()) {
411 if at_edge(collapsed.last()) {
crates/core/src/stored.rs +37 −8
@@ -202,19 +202,48 @@ fn push_plain(text: &mut String, spans: &[Span]) {
202 202 text.push_str(code);
203 203 text.push('\n');
204 204 }
205 Span::Bold(children) | Span::Italic(children) | Span::Quote(children) => {
206 push_plain(text, children)
205 Span::Bold(children)
206 | Span::Italic(children)
207 | Span::Strike(children)
208 | Span::Underline(children)
209 | Span::Colored { children, .. }
210 | Span::Quote(children)
211 | Span::BlockQuote(children)
212 | Span::Link { children, .. } => push_plain(text, children),
213 Span::Heading { children, .. } => {
214 push_plain(text, children);
215 text.push('\n');
207 216 }
208 Span::Link { children, .. } => push_plain(text, children),
209 217 Span::Mention { name } => {
210 218 text.push('@');
211 219 text.push_str(name);
212 220 }
213 Span::LineBreak => text.push('\n'),
214 Span::ListItem(children) => {
215 text.push_str("- ");
216 push_plain(text, children);
217 text.push('\n');
221 Span::LineBreak | Span::Rule => text.push('\n'),
222 Span::List {
223 ordered,
224 start,
225 items,
226 } => {
227 for (offset, item) in items.iter().enumerate() {
228 if *ordered {
229 text.push_str(&format!("{}. ", *start as usize + offset));
230 } else {
231 text.push_str("- ");
232 }
233 push_plain(text, item);
234 text.push('\n');
235 }
236 }
237 Span::Table { rows, .. } => {
238 for row in rows {
239 for (index, cell) in row.iter().enumerate() {
240 if index > 0 {
241 text.push('\t');
242 }
243 push_plain(text, cell);
244 }
245 text.push('\n');
246 }
218 247 }
219 248 Span::Image { .. } => {}
220 249 }
@@ -202,19 +202,48 @@ fn push_plain(text: &mut String, spans: &[Span]) {
202 text.push_str(code);
202 text.push_str(code);
203 text.push('\n');
203 text.push('\n');
204 }
204 }
205 Span::Bold(children) | Span::Italic(children) | Span::Quote(children) => {
205 Span::Bold(children)
206 push_plain(text, children)
206 | Span::Italic(children)
207 | Span::Strike(children)
208 | Span::Underline(children)
209 | Span::Colored { children, .. }
210 | Span::Quote(children)
211 | Span::BlockQuote(children)
212 | Span::Link { children, .. } => push_plain(text, children),
213 Span::Heading { children, .. } => {
214 push_plain(text, children);
215 text.push('\n');
207 }
216 }
208 Span::Link { children, .. } => push_plain(text, children),
209 Span::Mention { name } => {
217 Span::Mention { name } => {
210 text.push('@');
218 text.push('@');
211 text.push_str(name);
219 text.push_str(name);
212 }
220 }
213 Span::LineBreak => text.push('\n'),
221 Span::LineBreak | Span::Rule => text.push('\n'),
214 Span::ListItem(children) => {
222 Span::List {
215 text.push_str("- ");
223 ordered,
216 push_plain(text, children);
224 start,
217 text.push('\n');
225 items,
226 } => {
227 for (offset, item) in items.iter().enumerate() {
228 if *ordered {
229 text.push_str(&format!("{}. ", *start as usize + offset));
230 } else {
231 text.push_str("- ");
232 }
233 push_plain(text, item);
234 text.push('\n');
235 }
236 }
237 Span::Table { rows, .. } => {
238 for row in rows {
239 for (index, cell) in row.iter().enumerate() {
240 if index > 0 {
241 text.push('\t');
242 }
243 push_plain(text, cell);
244 }
245 text.push('\n');
246 }
218 }
247 }
219 Span::Image { .. } => {}
248 Span::Image { .. } => {}
220 }
249 }
crates/core/tests/spans.rs +123 −2
@@ -181,9 +181,130 @@ fn reply_quote() {
181 181 fn list_items() {
182 182 assert_eq!(
183 183 html_to_spans("<ul>\n<li>one</li>\n<li>two <b>b</b></li>\n</ul>"),
184 vec![Span::List {
185 ordered: false,
186 start: 1,
187 items: vec![
188 vec![text("one")],
189 vec![text("two "), Span::Bold(vec![text("b")])],
190 ],
191 }]
192 );
193 }
194
195 #[test]
196 fn ordered_list_keeps_start_and_nesting() {
197 assert_eq!(
198 html_to_spans(r#"<ol start="9"><li>a<ul><li>b</li></ul></li><li>c</li></ol>"#),
199 vec![Span::List {
200 ordered: true,
201 start: 9,
202 items: vec![
203 vec![
204 text("a"),
205 Span::LineBreak,
206 Span::List {
207 ordered: false,
208 start: 1,
209 items: vec![vec![text("b")]],
210 },
211 ],
212 vec![text("c")],
213 ],
214 }]
215 );
216 }
217
218 #[test]
219 fn list_nested_directly_in_list_joins_the_previous_item() {
220 let spans = html_to_spans("<ul><li>a</li><ul><li>b</li></ul></ul>");
221 let [Span::List { items, .. }] = &spans[..] else {
222 panic!("one list expected")
223 };
224 assert_eq!(items.len(), 1);
225 assert!(matches!(items[0].last(), Some(Span::List { .. })));
226 }
227
228 #[test]
229 fn headings_keep_their_level_up_to_three() {
230 assert_eq!(
231 html_to_spans("<h2>Title</h2><h5>Small</h5>"),
232 vec![
233 Span::Heading {
234 level: 2,
235 children: vec![text("Title")]
236 },
237 Span::LineBreak,
238 Span::Heading {
239 level: 3,
240 children: vec![text("Small")]
241 },
242 ]
243 );
244 }
245
246 #[test]
247 fn strike_underline_and_rule() {
248 assert_eq!(
249 html_to_spans("<p><s>old</s> <u>new</u></p><hr>"),
250 vec![
251 Span::Strike(vec![text("old")]),
252 text(" "),
253 Span::Underline(vec![text("new")]),
254 Span::LineBreak,
255 Span::Rule,
256 ]
257 );
258 }
259
260 #[test]
261 fn table_rows_and_header() {
262 assert_eq!(
263 html_to_spans(
264 "<table><thead><tr><th>Area</th><th>Owner</th></tr></thead><tbody><tr><td>Sync</td><td>Priya</td></tr></tbody></table>"
265 ),
266 vec![Span::Table {
267 header: true,
268 rows: vec![
269 vec![vec![text("Area")], vec![text("Owner")]],
270 vec![vec![text("Sync")], vec![text("Priya")]],
271 ],
272 }]
273 );
274 }
275
276 #[test]
277 fn table_without_header_cells_has_no_header() {
278 let spans = html_to_spans("<table><tr><td>a</td></tr></table>");
279 assert!(matches!(&spans[..], [Span::Table { header: false, .. }]));
280 }
281
282 #[test]
283 fn plain_blockquote_is_not_a_reply() {
284 assert_eq!(
285 html_to_spans("<blockquote>wise words</blockquote>"),
286 vec![Span::BlockQuote(vec![text("wise words")])]
287 );
288 }
289
290 #[test]
291 fn span_colors_are_parsed() {
292 assert_eq!(
293 html_to_spans(
294 r#"<span style="color: #F00; background-color: rgb(255, 255, 0)">x</span><span>y</span><mark>z</mark>"#
295 ),
184 296 vec![
185 Span::ListItem(vec![text("one")]),
186 Span::ListItem(vec![text("two "), Span::Bold(vec![text("b")])]),
297 Span::Colored {
298 color: Some(0xff0000),
299 background: Some(0xffff00),
300 children: vec![text("x")],
301 },
302 text("y"),
303 Span::Colored {
304 color: None,
305 background: Some(0xffff00),
306 children: vec![text("z")],
307 },
187 308 ]
188 309 );
189 310 }
@@ -181,9 +181,130 @@ fn reply_quote() {
181fn list_items() {
181fn list_items() {
182 assert_eq!(
182 assert_eq!(
183 html_to_spans("<ul>\n<li>one</li>\n<li>two <b>b</b></li>\n</ul>"),
183 html_to_spans("<ul>\n<li>one</li>\n<li>two <b>b</b></li>\n</ul>"),
184 vec![Span::List {
185 ordered: false,
186 start: 1,
187 items: vec![
188 vec![text("one")],
189 vec![text("two "), Span::Bold(vec![text("b")])],
190 ],
191 }]
192 );
193}
194
195#[test]
196fn ordered_list_keeps_start_and_nesting() {
197 assert_eq!(
198 html_to_spans(r#"<ol start="9"><li>a<ul><li>b</li></ul></li><li>c</li></ol>"#),
199 vec![Span::List {
200 ordered: true,
201 start: 9,
202 items: vec![
203 vec![
204 text("a"),
205 Span::LineBreak,
206 Span::List {
207 ordered: false,
208 start: 1,
209 items: vec![vec![text("b")]],
210 },
211 ],
212 vec![text("c")],
213 ],
214 }]
215 );
216}
217
218#[test]
219fn list_nested_directly_in_list_joins_the_previous_item() {
220 let spans = html_to_spans("<ul><li>a</li><ul><li>b</li></ul></ul>");
221 let [Span::List { items, .. }] = &spans[..] else {
222 panic!("one list expected")
223 };
224 assert_eq!(items.len(), 1);
225 assert!(matches!(items[0].last(), Some(Span::List { .. })));
226}
227
228#[test]
229fn headings_keep_their_level_up_to_three() {
230 assert_eq!(
231 html_to_spans("<h2>Title</h2><h5>Small</h5>"),
232 vec![
233 Span::Heading {
234 level: 2,
235 children: vec![text("Title")]
236 },
237 Span::LineBreak,
238 Span::Heading {
239 level: 3,
240 children: vec![text("Small")]
241 },
242 ]
243 );
244}
245
246#[test]
247fn strike_underline_and_rule() {
248 assert_eq!(
249 html_to_spans("<p><s>old</s> <u>new</u></p><hr>"),
250 vec![
251 Span::Strike(vec![text("old")]),
252 text(" "),
253 Span::Underline(vec![text("new")]),
254 Span::LineBreak,
255 Span::Rule,
256 ]
257 );
258}
259
260#[test]
261fn table_rows_and_header() {
262 assert_eq!(
263 html_to_spans(
264 "<table><thead><tr><th>Area</th><th>Owner</th></tr></thead><tbody><tr><td>Sync</td><td>Priya</td></tr></tbody></table>"
265 ),
266 vec![Span::Table {
267 header: true,
268 rows: vec![
269 vec![vec![text("Area")], vec![text("Owner")]],
270 vec![vec![text("Sync")], vec![text("Priya")]],
271 ],
272 }]
273 );
274}
275
276#[test]
277fn table_without_header_cells_has_no_header() {
278 let spans = html_to_spans("<table><tr><td>a</td></tr></table>");
279 assert!(matches!(&spans[..], [Span::Table { header: false, .. }]));
280}
281
282#[test]
283fn plain_blockquote_is_not_a_reply() {
284 assert_eq!(
285 html_to_spans("<blockquote>wise words</blockquote>"),
286 vec![Span::BlockQuote(vec![text("wise words")])]
287 );
288}
289
290#[test]
291fn span_colors_are_parsed() {
292 assert_eq!(
293 html_to_spans(
294 r#"<span style="color: #F00; background-color: rgb(255, 255, 0)">x</span><span>y</span><mark>z</mark>"#
295 ),
184 vec![
296 vec![
185 Span::ListItem(vec![text("one")]),
297 Span::Colored {
186 Span::ListItem(vec![text("two "), Span::Bold(vec![text("b")])]),
298 color: Some(0xff0000),
299 background: Some(0xffff00),
300 children: vec![text("x")],
301 },
302 text("y"),
303 Span::Colored {
304 color: None,
305 background: Some(0xffff00),
306 children: vec![text("z")],
307 },
187 ]
308 ]
188 );
309 );
189}
310}