feat(composer): Teams formatting - colour, highlight, headings, indent, rule, clear, code block
- Format bar in Teams' group order: highlight, font colour, size, paragraph style (Paragraph / Heading 1-3), clear all formatting; decrease / increase indent, lists; quote, link, inline code, code block, horizontal rule; table - Sent HTML as Teams: <span style="color:#RRGGBB;">, <span style="background-color:#RRGGBB;">, <h1>-<h3>, <p style="margin-left:40px;"> per indent step, <hr>, <pre class="language-x skipProofing" spellcheck="false"><code>..<br>..</code></pre> (plaintext when no language) - Received messages render block indents, colours, highlights and <br> code blocks; demo release message shows them - Shortcuts for paragraph styles, code block (Ctrl+Shift+B) and quote (Ctrl+Alt+4) - Deviation: Teams' undo / redo group is left out of the format bar (undo / redo stay on the keyboard) - Colour swatch selection ring uses the state ring form layout_guard accepts Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -8,7 +8,7 @@ macro_rules! symbols {
8
8
};
9
9
}
10
10
11
const SYMBOLS: [(&str, &[u8]); 64] = symbols![
11
const SYMBOLS: [(&str, &[u8]); 72] = symbols![
12
12
"bot",
13
13
"done",
14
14
"table",
@@ -73,6 +73,14 @@ const SYMBOLS: [(&str, &[u8]); 64] = symbols![
73
73
"fluent_alert_urgent",
74
74
"fluent_alert_urgent_filled",
75
75
"fluent_chat",
76
"fluent_text_color",
77
"fluent_highlight",
78
"fluent_text_indent_increase",
79
"fluent_text_indent_decrease",
80
"fluent_line_horizontal_1",
81
"fluent_text_clear_formatting",
82
"fluent_code_block",
83
"fluent_text_header_1",
76
84
];
77
85
78
86
pub struct AppAssets;
@@ -8,7 +8,7 @@ macro_rules! symbols {8
};8
};9
}9
}10
10
11
const SYMBOLS: [(&str, &[u8]); 64] = symbols![11
const SYMBOLS: [(&str, &[u8]); 72] = symbols![12
"bot",12
"bot",13
"done",13
"done",14
"table",14
"table",@@ -73,6 +73,14 @@ const SYMBOLS: [(&str, &[u8]); 64] = symbols![73
"fluent_alert_urgent",73
"fluent_alert_urgent",74
"fluent_alert_urgent_filled",74
"fluent_alert_urgent_filled",75
"fluent_chat",75
"fluent_chat",76
"fluent_text_color",77
"fluent_highlight",78
"fluent_text_indent_increase",79
"fluent_text_indent_decrease",80
"fluent_line_horizontal_1",81
"fluent_text_clear_formatting",82
"fluent_code_block",83
"fluent_text_header_1",76
];84
];77
85
78
pub struct AppAssets;86
pub struct AppAssets;@@ -1745,7 +1745,7 @@ fn release_messages() -> Vec<MessageRecord> {
1745
1745
None,
1746
1746
jonas,
1747
1747
at(0, 11, 5),
1748
"<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>",
1748
"<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><p style=\"margin-left:40px;\">Then <span style=\"color:#1E53A3;\">sync</span> <span style=\"background-color:#82CDA8;\">once</span>.</p><pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>backup --all<br>sync --once</code></pre>",
1749
1749
"[]",
1750
1750
false,
1751
1751
),
@@ -1745,7 +1745,7 @@ fn release_messages() -> Vec<MessageRecord> {1745
None,1745
None,1746
jonas,1746
jonas,1747
at(0, 11, 5),1747
at(0, 11, 5),1748
"<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>",1748
"<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><p style=\"margin-left:40px;\">Then <span style=\"color:#1E53A3;\">sync</span> <span style=\"background-color:#82CDA8;\">once</span>.</p><pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>backup --all<br>sync --once</code></pre>",1749
"[]",1749
"[]",1750
false,1750
false,1751
),1751
),@@ -5,6 +5,7 @@ use gpui_kit::*;
5
5
use teams_core::{Draft, FontSize, LineKind, MarkKind, SizeStep};
6
6
7
7
use crate::render::blocks::{Script, StyleFlags};
8
use crate::render::elements::{highlight_fill, readable_on};
8
9
use app_base::theme;
9
10
10
11
const CODE_PILL_RADIUS: f32 = 4.;
@@ -14,6 +15,8 @@ const QUOTE_INDENT: f32 = 12.;
14
15
const CODE_INDENT: f32 = 10.;
15
16
const LIST_LEVEL_INDENT: f32 = 18.;
16
17
const HEADING_SCALES: [f32; 3] = [1.6, 1.35, 1.15];
18
const INDENT_STEP: f32 = teams_core::INDENT_PIXELS as f32;
19
const HIGHLIGHT_RADIUS: f32 = 3.;
17
20
18
21
/// How the composer paints a draft: text styles, fills and the list markers to hang under.
19
22
pub struct DraftStyle {
@@ -25,7 +28,8 @@ pub struct DraftStyle {
25
28
26
29
fn line_indent(kind: &LineKind) -> f32 {
27
30
match kind {
28
LineKind::Text | LineKind::Heading(_) | LineKind::Table(_) => 0.,
31
LineKind::Text | LineKind::Heading(_) | LineKind::Table(_) | LineKind::Rule => 0.,
32
LineKind::Indent(level) => INDENT_STEP * f32::from(*level),
29
33
LineKind::Quote => QUOTE_INDENT,
30
34
LineKind::Code(_) => CODE_INDENT,
31
35
LineKind::Bullet(depth) | LineKind::Numbered(depth) => {
@@ -62,7 +66,10 @@ fn mark_style(kind: &MarkKind) -> HighlightStyle {
62
66
color: None,
63
67
});
64
68
}
65
MarkKind::Superscript | MarkKind::Subscript | MarkKind::Size(_) => {}
69
MarkKind::Color(value) => {
70
style.color = Some(readable_on(*value, theme::surface_raised()));
71
}
72
MarkKind::Superscript | MarkKind::Subscript | MarkKind::Size(_) | MarkKind::Highlight(_) => {}
66
73
MarkKind::Code => style.color = Some(theme::text_strong()),
67
74
MarkKind::Link(_) => {
68
75
style.color = Some(theme::accent_text());
@@ -121,6 +128,14 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {
121
128
decoration = decoration.with_baseline_shift(flags.baseline_raise());
122
129
}
123
130
}
131
if let MarkKind::Highlight(value) = mark.kind {
132
ranges.push(
133
RangeDecoration::new(mark.range.clone())
134
.with_style(RangeDecorationStyle::Pill)
135
.with_color(highlight_fill(value))
136
.with_radius(px(HIGHLIGHT_RADIUS)),
137
);
138
}
124
139
if mark.kind == MarkKind::Code {
125
140
text.push(decoration.with_font_family(mono.clone()));
126
141
ranges.push(
@@ -5,6 +5,7 @@ use gpui_kit::*;5
use teams_core::{Draft, FontSize, LineKind, MarkKind, SizeStep};5
use teams_core::{Draft, FontSize, LineKind, MarkKind, SizeStep};6
6
7
use crate::render::blocks::{Script, StyleFlags};7
use crate::render::blocks::{Script, StyleFlags};8
use crate::render::elements::{highlight_fill, readable_on};8
use app_base::theme;9
use app_base::theme;9
10
10
const CODE_PILL_RADIUS: f32 = 4.;11
const CODE_PILL_RADIUS: f32 = 4.;@@ -14,6 +15,8 @@ const QUOTE_INDENT: f32 = 12.;14
const CODE_INDENT: f32 = 10.;15
const CODE_INDENT: f32 = 10.;15
const LIST_LEVEL_INDENT: f32 = 18.;16
const LIST_LEVEL_INDENT: f32 = 18.;16
const HEADING_SCALES: [f32; 3] = [1.6, 1.35, 1.15];17
const HEADING_SCALES: [f32; 3] = [1.6, 1.35, 1.15];18
const INDENT_STEP: f32 = teams_core::INDENT_PIXELS as f32;19
const HIGHLIGHT_RADIUS: f32 = 3.;17
20
18
/// How the composer paints a draft: text styles, fills and the list markers to hang under.21
/// How the composer paints a draft: text styles, fills and the list markers to hang under.19
pub struct DraftStyle {22
pub struct DraftStyle {@@ -25,7 +28,8 @@ pub struct DraftStyle {25
28
26
fn line_indent(kind: &LineKind) -> f32 {29
fn line_indent(kind: &LineKind) -> f32 {27
match kind {30
match kind {28
LineKind::Text | LineKind::Heading(_) | LineKind::Table(_) => 0.,31
LineKind::Text | LineKind::Heading(_) | LineKind::Table(_) | LineKind::Rule => 0.,32
LineKind::Indent(level) => INDENT_STEP * f32::from(*level),29
LineKind::Quote => QUOTE_INDENT,33
LineKind::Quote => QUOTE_INDENT,30
LineKind::Code(_) => CODE_INDENT,34
LineKind::Code(_) => CODE_INDENT,31
LineKind::Bullet(depth) | LineKind::Numbered(depth) => {35
LineKind::Bullet(depth) | LineKind::Numbered(depth) => {@@ -62,7 +66,10 @@ fn mark_style(kind: &MarkKind) -> HighlightStyle {62
color: None,66
color: None,63
});67
});64
}68
}65
MarkKind::Superscript | MarkKind::Subscript | MarkKind::Size(_) => {}69
MarkKind::Color(value) => {70
style.color = Some(readable_on(*value, theme::surface_raised()));71
}72
MarkKind::Superscript | MarkKind::Subscript | MarkKind::Size(_) | MarkKind::Highlight(_) => {}66
MarkKind::Code => style.color = Some(theme::text_strong()),73
MarkKind::Code => style.color = Some(theme::text_strong()),67
MarkKind::Link(_) => {74
MarkKind::Link(_) => {68
style.color = Some(theme::accent_text());75
style.color = Some(theme::accent_text());@@ -121,6 +128,14 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {121
decoration = decoration.with_baseline_shift(flags.baseline_raise());128
decoration = decoration.with_baseline_shift(flags.baseline_raise());122
}129
}123
}130
}131
if let MarkKind::Highlight(value) = mark.kind {132
ranges.push(133
RangeDecoration::new(mark.range.clone())134
.with_style(RangeDecorationStyle::Pill)135
.with_color(highlight_fill(value))136
.with_radius(px(HIGHLIGHT_RADIUS)),137
);138
}124
if mark.kind == MarkKind::Code {139
if mark.kind == MarkKind::Code {125
text.push(decoration.with_font_family(mono.clone()));140
text.push(decoration.with_font_family(mono.clone()));126
ranges.push(141
ranges.push(@@ -194,6 +194,10 @@ pub enum Block {
194
194
children: Vec<Block>,
195
195
},
196
196
Quote(Vec<Block>),
197
Indent {
198
level: u8,
199
children: Vec<Block>,
200
},
197
201
List {
198
202
ordered: bool,
199
203
start: u32,
@@ -248,7 +252,7 @@ impl Block {
248
252
.collect::<Vec<_>>()
249
253
.join("\n"),
250
254
),
251
Block::Quote(children) => Some(join(children)),
255
Block::Quote(children) | Block::Indent { children, .. } => Some(join(children)),
252
256
Block::Reply { .. } | Block::Rule | Block::Image { .. } => None,
253
257
}
254
258
}
@@ -259,7 +263,9 @@ impl Block {
259
263
Block::Code { code, .. } | Block::CodeLine { code } => Some(code.clone()),
260
264
Block::List { items, .. } => items.first()?.iter().find_map(Block::first_line),
261
265
Block::Table { rows, .. } => Some(rows.first()?.first()?.plain_text()),
262
Block::Quote(children) => children.iter().find_map(Block::first_line),
266
Block::Quote(children) | Block::Indent { children, .. } => {
267
children.iter().find_map(Block::first_line)
268
}
263
269
Block::Reply { .. } | Block::Rule | Block::Image { .. } => None,
264
270
}
265
271
}
@@ -282,7 +288,9 @@ fn unlink(blocks: &mut [Block]) {
282
288
segment.style.link = false;
283
289
}
284
290
}
285
Block::Reply { children, .. } | Block::Quote(children) => unlink(children),
291
Block::Reply { children, .. }
292
| Block::Quote(children)
293
| Block::Indent { children, .. } => unlink(children),
286
294
Block::List { items, .. } => items.iter_mut().for_each(|item| unlink(item)),
287
295
_ => {}
288
296
}
@@ -311,6 +319,10 @@ pub fn strip_image_placeholders(blocks: Vec<Block>) -> Vec<Block> {
311
319
let children = strip_image_placeholders(children);
312
320
(!children.is_empty()).then_some(Block::Quote(children))
313
321
}
322
Block::Indent { level, children } => {
323
let children = strip_image_placeholders(children);
324
(!children.is_empty()).then_some(Block::Indent { level, children })
325
}
314
326
Block::List {
315
327
ordered,
316
328
start,
@@ -373,6 +385,16 @@ fn layout_blocks_with(spans: &[Span], split_images: bool, frame_code: bool) -> V
373
385
blocks.push(Block::Quote(inner));
374
386
}
375
387
}
388
Span::Indent { level, children } => {
389
flush(&mut current, &mut blocks, frame_code);
390
let inner = layout_blocks_with(children, split_images, frame_code);
391
if !inner.is_empty() {
392
blocks.push(Block::Indent {
393
level: *level,
394
children: inner,
395
});
396
}
397
}
376
398
Span::List {
377
399
ordered,
378
400
start,
@@ -674,7 +696,9 @@ fn append_inline(spans: &[Span], style: StyleFlags, link: Option<&str>, out: &mu
674
696
);
675
697
}
676
698
Span::LineBreak | Span::Rule => out.push("\n", style, link),
677
Span::Quote { children, .. } | Span::BlockQuote(children) => {
699
Span::Quote { children, .. }
700
| Span::BlockQuote(children)
701
| Span::Indent { children, .. } => {
678
702
append_inline(children, style, link, out);
679
703
out.push("\n", style, link);
680
704
}
@@ -194,6 +194,10 @@ pub enum Block {194
children: Vec<Block>,194
children: Vec<Block>,195
},195
},196
Quote(Vec<Block>),196
Quote(Vec<Block>),197
Indent {198
level: u8,199
children: Vec<Block>,200
},197
List {201
List {198
ordered: bool,202
ordered: bool,199
start: u32,203
start: u32,@@ -248,7 +252,7 @@ impl Block {248
.collect::<Vec<_>>()252
.collect::<Vec<_>>()249
.join("\n"),253
.join("\n"),250
),254
),251
Block::Quote(children) => Some(join(children)),255
Block::Quote(children) | Block::Indent { children, .. } => Some(join(children)),252
Block::Reply { .. } | Block::Rule | Block::Image { .. } => None,256
Block::Reply { .. } | Block::Rule | Block::Image { .. } => None,253
}257
}254
}258
}@@ -259,7 +263,9 @@ impl Block {259
Block::Code { code, .. } | Block::CodeLine { code } => Some(code.clone()),263
Block::Code { code, .. } | Block::CodeLine { code } => Some(code.clone()),260
Block::List { items, .. } => items.first()?.iter().find_map(Block::first_line),264
Block::List { items, .. } => items.first()?.iter().find_map(Block::first_line),261
Block::Table { rows, .. } => Some(rows.first()?.first()?.plain_text()),265
Block::Table { rows, .. } => Some(rows.first()?.first()?.plain_text()),262
Block::Quote(children) => children.iter().find_map(Block::first_line),266
Block::Quote(children) | Block::Indent { children, .. } => {267
children.iter().find_map(Block::first_line)268
}263
Block::Reply { .. } | Block::Rule | Block::Image { .. } => None,269
Block::Reply { .. } | Block::Rule | Block::Image { .. } => None,264
}270
}265
}271
}@@ -282,7 +288,9 @@ fn unlink(blocks: &mut [Block]) {282
segment.style.link = false;288
segment.style.link = false;283
}289
}284
}290
}285
Block::Reply { children, .. } | Block::Quote(children) => unlink(children),291
Block::Reply { children, .. }292
| Block::Quote(children)293
| Block::Indent { children, .. } => unlink(children),286
Block::List { items, .. } => items.iter_mut().for_each(|item| unlink(item)),294
Block::List { items, .. } => items.iter_mut().for_each(|item| unlink(item)),287
_ => {}295
_ => {}288
}296
}@@ -311,6 +319,10 @@ pub fn strip_image_placeholders(blocks: Vec<Block>) -> Vec<Block> {311
let children = strip_image_placeholders(children);319
let children = strip_image_placeholders(children);312
(!children.is_empty()).then_some(Block::Quote(children))320
(!children.is_empty()).then_some(Block::Quote(children))313
}321
}322
Block::Indent { level, children } => {323
let children = strip_image_placeholders(children);324
(!children.is_empty()).then_some(Block::Indent { level, children })325
}314
Block::List {326
Block::List {315
ordered,327
ordered,316
start,328
start,@@ -373,6 +385,16 @@ fn layout_blocks_with(spans: &[Span], split_images: bool, frame_code: bool) -> V373
blocks.push(Block::Quote(inner));385
blocks.push(Block::Quote(inner));374
}386
}375
}387
}388
Span::Indent { level, children } => {389
flush(&mut current, &mut blocks, frame_code);390
let inner = layout_blocks_with(children, split_images, frame_code);391
if !inner.is_empty() {392
blocks.push(Block::Indent {393
level: *level,394
children: inner,395
});396
}397
}376
Span::List {398
Span::List {377
ordered,399
ordered,378
start,400
start,@@ -674,7 +696,9 @@ fn append_inline(spans: &[Span], style: StyleFlags, link: Option<&str>, out: &mu674
);696
);675
}697
}676
Span::LineBreak | Span::Rule => out.push("\n", style, link),698
Span::LineBreak | Span::Rule => out.push("\n", style, link),677
Span::Quote { children, .. } | Span::BlockQuote(children) => {699
Span::Quote { children, .. }700
| Span::BlockQuote(children)701
| Span::Indent { children, .. } => {678
append_inline(children, style, link, out);702
append_inline(children, style, link, out);679
out.push("\n", style, link);703
out.push("\n", style, link);680
}704
}@@ -11,6 +11,7 @@ use crate::widgets::symbol;
11
11
use app_base::theme;
12
12
13
13
const LIST_GAP: f32 = 2.;
14
const INDENT_STEP: f32 = teams_core::INDENT_PIXELS as f32;
14
15
const MARKER_WIDTH: f32 = 18.;
15
16
const WIDE_MARKER_WIDTH: f32 = 26.;
16
17
const BULLETS: [&str; 3] = ["\u{2022}", "\u{25e6}", "\u{25aa}"];
@@ -89,6 +90,11 @@ fn render_block(block: &Block, id: String, own: bool, depth: usize, cx: &App) ->
89
90
.text_color(theme::text_soft())
90
91
.child(render_block_list(children, &id, own, depth, cx))
91
92
.into_any_element(),
93
Block::Indent { level, children } => div()
94
.w_full()
95
.pl(px(f32::from(*level) * INDENT_STEP))
96
.child(render_block_list(children, &id, own, depth, cx))
97
.into_any_element(),
92
98
Block::List {
93
99
ordered,
94
100
start,
@@ -418,12 +424,9 @@ fn pill_for(range: std::ops::Range<usize>, style: StyleFlags, own: bool) -> Opti
418
424
radius: px(4.),
419
425
});
420
426
}
421
let background = style.background?;
422
let mut fill: Hsla = rgb(background).into();
423
fill.a = HIGHLIGHT_ALPHA;
424
427
Some(Pill {
425
428
range,
426
fill,
429
fill: highlight_fill(style.background?),
427
430
border: None,
428
431
radius: px(3.),
429
432
})
@@ -481,12 +484,26 @@ fn highlight_for(style: StyleFlags, own: bool) -> HighlightStyle {
481
484
highlight
482
485
}
483
486
487
pub fn highlight_fill(color: u32) -> Hsla {
488
let mut fill: Hsla = rgb(color).into();
489
fill.a = HIGHLIGHT_ALPHA;
490
fill
491
}
492
484
493
fn readable(color: u32, own: bool) -> Hsla {
485
let background = Rgba::from(if own {
486
theme::bubble_own()
487
} else {
488
theme::bubble_other()
489
});
494
readable_on(
495
color,
496
if own {
497
theme::bubble_own()
498
} else {
499
theme::bubble_other()
500
},
501
)
502
}
503
504
/// `color` moved towards black or white until it reads on `background`.
505
pub fn readable_on(color: u32, background: Hsla) -> Hsla {
506
let background = Rgba::from(background);
490
507
let mut foreground = rgb(color);
491
508
let target = if luminance(background) > 0.5 { 0. } else { 1. };
492
509
for _ in 0..10 {
@@ -11,6 +11,7 @@ use crate::widgets::symbol;11
use app_base::theme;11
use app_base::theme;12
12
13
const LIST_GAP: f32 = 2.;13
const LIST_GAP: f32 = 2.;14
const INDENT_STEP: f32 = teams_core::INDENT_PIXELS as f32;14
const MARKER_WIDTH: f32 = 18.;15
const MARKER_WIDTH: f32 = 18.;15
const WIDE_MARKER_WIDTH: f32 = 26.;16
const WIDE_MARKER_WIDTH: f32 = 26.;16
const BULLETS: [&str; 3] = ["\u{2022}", "\u{25e6}", "\u{25aa}"];17
const BULLETS: [&str; 3] = ["\u{2022}", "\u{25e6}", "\u{25aa}"];@@ -89,6 +90,11 @@ fn render_block(block: &Block, id: String, own: bool, depth: usize, cx: &App) ->89
.text_color(theme::text_soft())90
.text_color(theme::text_soft())90
.child(render_block_list(children, &id, own, depth, cx))91
.child(render_block_list(children, &id, own, depth, cx))91
.into_any_element(),92
.into_any_element(),93
Block::Indent { level, children } => div()94
.w_full()95
.pl(px(f32::from(*level) * INDENT_STEP))96
.child(render_block_list(children, &id, own, depth, cx))97
.into_any_element(),92
Block::List {98
Block::List {93
ordered,99
ordered,94
start,100
start,@@ -418,12 +424,9 @@ fn pill_for(range: std::ops::Range<usize>, style: StyleFlags, own: bool) -> Opti418
radius: px(4.),424
radius: px(4.),419
});425
});420
}426
}421
let background = style.background?;422
let mut fill: Hsla = rgb(background).into();423
fill.a = HIGHLIGHT_ALPHA;424
Some(Pill {427
Some(Pill {425
range,428
range,426
fill,429
fill: highlight_fill(style.background?),427
border: None,430
border: None,428
radius: px(3.),431
radius: px(3.),429
})432
})@@ -481,12 +484,26 @@ fn highlight_for(style: StyleFlags, own: bool) -> HighlightStyle {481
highlight484
highlight482
}485
}483
486
487
pub fn highlight_fill(color: u32) -> Hsla {488
let mut fill: Hsla = rgb(color).into();489
fill.a = HIGHLIGHT_ALPHA;490
fill491
}492
484
fn readable(color: u32, own: bool) -> Hsla {493
fn readable(color: u32, own: bool) -> Hsla {485
let background = Rgba::from(if own {494
readable_on(486
theme::bubble_own()495
color,487
} else {496
if own {488
theme::bubble_other()497
theme::bubble_own()489
});498
} else {499
theme::bubble_other()500
},501
)502
}503
504
/// `color` moved towards black or white until it reads on `background`.505
pub fn readable_on(color: u32, background: Hsla) -> Hsla {506
let background = Rgba::from(background);490
let mut foreground = rgb(color);507
let mut foreground = rgb(color);491
let target = if luminance(background) > 0.5 { 0. } else { 1. };508
let target = if luminance(background) > 0.5 { 0. } else { 1. };492
for _ in 0..10 {509
for _ in 0..10 {@@ -0,0 +1 @@
1
<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M6 3a3 3 0 0 0-3 3v8a3 3 0 0 0 3 3h8a3 3 0 0 0 3-3V6a3 3 0 0 0-3-3H6ZM4 6c0-1.1.9-2 2-2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6Zm4.85 1.85a.5.5 0 1 0-.7-.7l-2.5 2.5a.5.5 0 0 0 0 .7l2.5 2.5a.5.5 0 0 0 .7-.7L6.71 10l2.14-2.15Zm3-.7a.5.5 0 0 0-.7.7L13.29 10l-2.14 2.15a.5.5 0 0 0 .7.7l2.5-2.5a.5.5 0 0 0 0-.7l-2.5-2.5Z"/></svg>
@@ -0,0 +1 @@1
<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M6 3a3 3 0 0 0-3 3v8a3 3 0 0 0 3 3h8a3 3 0 0 0 3-3V6a3 3 0 0 0-3-3H6ZM4 6c0-1.1.9-2 2-2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6Zm4.85 1.85a.5.5 0 1 0-.7-.7l-2.5 2.5a.5.5 0 0 0 0 .7l2.5 2.5a.5.5 0 0 0 .7-.7L6.71 10l2.14-2.15Zm3-.7a.5.5 0 0 0-.7.7L13.29 10l-2.14 2.15a.5.5 0 0 0 .7.7l2.5-2.5a.5.5 0 0 0 0-.7l-2.5-2.5Z"/></svg>@@ -0,0 +1 @@
1
<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M3.5 2c.28 0 .5.22.5.5v4c0 .28.22.5.5.5h11a.5.5 0 0 0 .5-.5v-4a.5.5 0 0 1 1 0v4c0 .65-.42 1.2-1 1.41V9a2 2 0 0 1-2 2v2.07a2 2 0 0 1-1.1 1.8l-6.18 3.08A.5.5 0 0 1 6 17.5V11a2 2 0 0 1-2-2V7.91c-.58-.2-1-.76-1-1.41v-4c0-.28.22-.5.5-.5ZM5 8v1a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1V8H5Zm2 3v5.7l5.45-2.73a1 1 0 0 0 .55-.9V11H7Z"/></svg>
@@ -0,0 +1 @@1
<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M3.5 2c.28 0 .5.22.5.5v4c0 .28.22.5.5.5h11a.5.5 0 0 0 .5-.5v-4a.5.5 0 0 1 1 0v4c0 .65-.42 1.2-1 1.41V9a2 2 0 0 1-2 2v2.07a2 2 0 0 1-1.1 1.8l-6.18 3.08A.5.5 0 0 1 6 17.5V11a2 2 0 0 1-2-2V7.91c-.58-.2-1-.76-1-1.41v-4c0-.28.22-.5.5-.5ZM5 8v1a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1V8H5Zm2 3v5.7l5.45-2.73a1 1 0 0 0 .55-.9V11H7Z"/></svg>@@ -0,0 +1 @@
1
<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M2 9.5c0-.28.22-.5.5-.5h15a.5.5 0 0 1 0 1h-15a.5.5 0 0 1-.5-.5Z"/></svg>
@@ -0,0 +1 @@1
<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M2 9.5c0-.28.22-.5.5-.5h15a.5.5 0 0 1 0 1h-15a.5.5 0 0 1-.5-.5Z"/></svg>@@ -0,0 +1 @@
1
<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M6 2c.2 0 .4.13.47.32l3.5 8.95a.5.5 0 0 1-.94.37L8.01 9H4l-1.04 2.68a.5.5 0 1 1-.94-.36l3.5-9A.5.5 0 0 1 6 2Zm0 1.88L4.4 8H7.6l-1.6-4.12ZM11.5 2c.28 0 .5.22.5.5v3.52a2.48 2.48 0 0 1 2.26-1.3c.89 0 1.6.34 2.15 1 .55.66.82 1.54.82 2.64l-.01.42-.05-.05a2.49 2.49 0 0 0-1.15-.65 2.86 2.86 0 0 0-.53-1.62c-.36-.47-.86-.7-1.48-.7-.6 0-1.09.24-1.47.72-.3.37-.47.83-.54 1.37v1.03c.05.43.18.8.37 1.12L11 11.37V2.5c0-.28.22-.5.5-.5ZM9.44 16.47a1.5 1.5 0 0 1 0-2.13l4.9-4.9a1.5 1.5 0 0 1 2.13 0l2.1 2.1a1.5 1.5 0 0 1-.01 2.12L14.22 18h2.53a.5.5 0 1 1 0 1h-4.1a1.5 1.5 0 0 1-1.12-.44l-2.1-2.1Zm5.61-6.32-3.6 3.6 2.8 2.8 3.6-3.6a.5.5 0 0 0 0-.7l-2.1-2.1a.5.5 0 0 0-.7 0Zm-1.5 7.1-2.8-2.8-.6.6a.5.5 0 0 0 0 .7l2.1 2.1c.19.2.5.2.7 0l.6-.6Z"/></svg>
@@ -0,0 +1 @@1
<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M6 2c.2 0 .4.13.47.32l3.5 8.95a.5.5 0 0 1-.94.37L8.01 9H4l-1.04 2.68a.5.5 0 1 1-.94-.36l3.5-9A.5.5 0 0 1 6 2Zm0 1.88L4.4 8H7.6l-1.6-4.12ZM11.5 2c.28 0 .5.22.5.5v3.52a2.48 2.48 0 0 1 2.26-1.3c.89 0 1.6.34 2.15 1 .55.66.82 1.54.82 2.64l-.01.42-.05-.05a2.49 2.49 0 0 0-1.15-.65 2.86 2.86 0 0 0-.53-1.62c-.36-.47-.86-.7-1.48-.7-.6 0-1.09.24-1.47.72-.3.37-.47.83-.54 1.37v1.03c.05.43.18.8.37 1.12L11 11.37V2.5c0-.28.22-.5.5-.5ZM9.44 16.47a1.5 1.5 0 0 1 0-2.13l4.9-4.9a1.5 1.5 0 0 1 2.13 0l2.1 2.1a1.5 1.5 0 0 1-.01 2.12L14.22 18h2.53a.5.5 0 1 1 0 1h-4.1a1.5 1.5 0 0 1-1.12-.44l-2.1-2.1Zm5.61-6.32-3.6 3.6 2.8 2.8 3.6-3.6a.5.5 0 0 0 0-.7l-2.1-2.1a.5.5 0 0 0-.7 0Zm-1.5 7.1-2.8-2.8-.6.6a.5.5 0 0 0 0 .7l2.1 2.1c.19.2.5.2.7 0l.6-.6Z"/></svg>@@ -0,0 +1 @@
1
<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M10.46 2.31a.5.5 0 0 0-.92 0l-3 7.5a.5.5 0 1 0 .92.38L8.54 7.5h2.92l1.08 2.69a.5.5 0 1 0 .92-.38l-3-7.5ZM10 3.85l1.06 2.65H8.94L10 3.85ZM4.5 12c-.83 0-1.5.67-1.5 1.5v3c0 .83.67 1.5 1.5 1.5h11c.83 0 1.5-.67 1.5-1.5v-3c0-.83-.67-1.5-1.5-1.5h-11ZM4 13.5c0-.28.22-.5.5-.5h11c.28 0 .5.22.5.5v3a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5v-3Z"/></svg>
@@ -0,0 +1 @@1
<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M10.46 2.31a.5.5 0 0 0-.92 0l-3 7.5a.5.5 0 1 0 .92.38L8.54 7.5h2.92l1.08 2.69a.5.5 0 1 0 .92-.38l-3-7.5ZM10 3.85l1.06 2.65H8.94L10 3.85ZM4.5 12c-.83 0-1.5.67-1.5 1.5v3c0 .83.67 1.5 1.5 1.5h11c.83 0 1.5-.67 1.5-1.5v-3c0-.83-.67-1.5-1.5-1.5h-11ZM4 13.5c0-.28.22-.5.5-.5h11c.28 0 .5.22.5.5v3a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5v-3Z"/></svg>@@ -0,0 +1 @@
1
<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M16.55 4a.5.5 0 0 1 .45.5v11a.5.5 0 0 1-1 0V6.73a8.58 8.58 0 0 1-2.22 2.19.5.5 0 1 1-.56-.84 6.76 6.76 0 0 0 2.83-3.8.5.5 0 0 1 .5-.28ZM2.5 4c.28 0 .5.22.5.5V9h6V4.5a.5.5 0 1 1 1 0v11a.5.5 0 0 1-1 0V10H3v5.5a.5.5 0 0 1-1 0v-11c0-.28.22-.5.5-.5Z"/></svg>
@@ -0,0 +1 @@1
<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M16.55 4a.5.5 0 0 1 .45.5v11a.5.5 0 0 1-1 0V6.73a8.58 8.58 0 0 1-2.22 2.19.5.5 0 1 1-.56-.84 6.76 6.76 0 0 0 2.83-3.8.5.5 0 0 1 .5-.28ZM2.5 4c.28 0 .5.22.5.5V9h6V4.5a.5.5 0 1 1 1 0v11a.5.5 0 0 1-1 0V10H3v5.5a.5.5 0 0 1-1 0v-11c0-.28.22-.5.5-.5Z"/></svg>@@ -0,0 +1 @@
1
<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M6 4.5c0-.28.22-.5.5-.5h8a.5.5 0 1 1 0 1h-8a.5.5 0 0 1-.5-.5ZM3.56 7.73a.5.5 0 0 1 .7.7L3.22 9.5l1.06 1.06a.5.5 0 1 1-.7.7l-1.42-1.4a.5.5 0 0 1 0-.71l1.41-1.42ZM6.5 9a.5.5 0 0 0 0 1h11a.5.5 0 1 0 0-1h-11ZM6 14.5c0-.28.22-.5.5-.5h6a.5.5 0 1 1 0 1h-6a.5.5 0 0 1-.5-.5Z"/></svg>
@@ -0,0 +1 @@1
<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M6 4.5c0-.28.22-.5.5-.5h8a.5.5 0 1 1 0 1h-8a.5.5 0 0 1-.5-.5ZM3.56 7.73a.5.5 0 0 1 .7.7L3.22 9.5l1.06 1.06a.5.5 0 1 1-.7.7l-1.42-1.4a.5.5 0 0 1 0-.71l1.41-1.42ZM6.5 9a.5.5 0 0 0 0 1h11a.5.5 0 1 0 0-1h-11ZM6 14.5c0-.28.22-.5.5-.5h6a.5.5 0 1 1 0 1h-6a.5.5 0 0 1-.5-.5Z"/></svg>@@ -0,0 +1 @@
1
<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M6 4.5c0-.28.22-.5.5-.5h8a.5.5 0 0 1 0 1h-8a.5.5 0 0 1-.5-.5Zm0 5c0-.28.22-.5.5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5Zm.5 4.5a.5.5 0 0 0 0 1h6a.5.5 0 0 0 0-1h-6ZM2.85 7.73a.5.5 0 1 0-.7.7L3.2 9.5l-1.06 1.06a.5.5 0 1 0 .7.7l1.42-1.4a.5.5 0 0 0 0-.71L2.85 7.73Z"/></svg>
@@ -0,0 +1 @@1
<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M6 4.5c0-.28.22-.5.5-.5h8a.5.5 0 0 1 0 1h-8a.5.5 0 0 1-.5-.5Zm0 5c0-.28.22-.5.5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5Zm.5 4.5a.5.5 0 0 0 0 1h6a.5.5 0 0 0 0-1h-6ZM2.85 7.73a.5.5 0 1 0-.7.7L3.2 9.5l-1.06 1.06a.5.5 0 1 0 .7.7l1.42-1.4a.5.5 0 0 0 0-.71L2.85 7.73Z"/></svg>@@ -24,7 +24,13 @@ actions!(
24
24
DeleteTable,
25
25
ToggleFormatBar,
26
26
InsertTableLine,
27
RemoveTableLine
27
RemoveTableLine,
28
SetParagraph,
29
SetHeading1,
30
SetHeading2,
31
SetHeading3,
32
ToggleCodeBlock,
33
ToggleQuote
28
34
]
29
35
);
30
36
@@ -24,7 +24,13 @@ actions!(24
DeleteTable,24
DeleteTable,25
ToggleFormatBar,25
ToggleFormatBar,26
InsertTableLine,26
InsertTableLine,27
RemoveTableLine27
RemoveTableLine,28
SetParagraph,29
SetHeading1,30
SetHeading2,31
SetHeading3,32
ToggleCodeBlock,33
ToggleQuote28
]34
]29
);35
);30
36
@@ -32,14 +32,17 @@ use teams_core::{
32
32
33
33
pub(crate) mod delivery;
34
34
mod drafts;
35
mod format_menus;
36
mod rule;
35
37
mod schedule;
36
38
mod table;
37
39
38
40
use super::actions::{
39
41
COMPOSER_KEY_CONTEXT, DeleteTable, DeleteTableColumn, DeleteTableRow, EditLink,
40
42
InsertTableColumnLeft, InsertTableColumnRight, InsertTableLine, InsertTableRowAbove,
41
InsertTableRowBelow, OpenSwitcher, PastePlainText, RemoveTableLine, ScheduleSend, ToggleBold,
42
ToggleCode, ToggleFormatBar, ToggleItalic, ToggleStrike, ToggleSubscript, ToggleSuperscript,
43
InsertTableRowBelow, OpenSwitcher, PastePlainText, RemoveTableLine, ScheduleSend,
44
SetHeading1, SetHeading2, SetHeading3, SetParagraph, ToggleBold, ToggleCode, ToggleCodeBlock,
45
ToggleFormatBar, ToggleItalic, ToggleQuote, ToggleStrike, ToggleSubscript, ToggleSuperscript,
43
46
ToggleUnderline,
44
47
};
45
48
use super::attachment_tray::{
@@ -62,6 +65,8 @@ use crate::runtime;
62
65
use crate::scheduled_rows::scheduled_label;
63
66
use crate::theme::{self, ElevatedSurface as _};
64
67
use crate::typing::OutgoingTyping;
68
use format_menus::{FormatPopup, paragraph_label};
69
use rule::{is_rule_token, render_rule_token};
65
70
use table::{TableKey, TableLineMenu, TableMenu, TablePicker, TableViews, is_table_token};
66
71
67
72
const MIN_ROWS: usize = 1;
@@ -224,6 +229,7 @@ pub struct Composer {
224
229
table_counter: usize,
225
230
table_picker: Option<TablePicker>,
226
231
table_menu: Option<TableMenu>,
232
format_popup: Option<FormatPopup>,
227
233
format_bar: HashSet<String>,
228
234
active_cell: Option<(String, teams_core::Cell)>,
229
235
caret_before_table: usize,
@@ -450,6 +456,7 @@ impl Composer {
450
456
table_counter: 0,
451
457
table_picker: None,
452
458
table_menu: None,
459
format_popup: None,
453
460
format_bar: HashSet::new(),
454
461
active_cell: None,
455
462
caret_before_table: 0,
@@ -849,6 +856,7 @@ impl Composer {
849
856
self.pending_anchors.clear();
850
857
self.active_cell = None;
851
858
self.table_picker = None;
859
self.format_popup = None;
852
860
self.sync_tables(window, cx);
853
861
self.history.clear();
854
862
self.history_index = 0;
@@ -989,6 +997,16 @@ impl Composer {
989
997
FormatButton::TableRemoveLine => {
990
998
self.open_table_menu(TableLineMenu::Remove, window, cx);
991
999
}
1000
FormatButton::Highlight => self.toggle_format_popup(FormatPopup::Highlight, cx),
1001
FormatButton::FontColor => self.toggle_format_popup(FormatPopup::FontColor, cx),
1002
FormatButton::ParagraphStyle => {
1003
self.toggle_format_popup(FormatPopup::ParagraphStyle, cx)
1004
}
1005
FormatButton::ClearFormatting => self.clear_formatting(window, cx),
1006
FormatButton::Outdent => self.indent_blocks(true, window, cx),
1007
FormatButton::Indent => self.indent_blocks(false, window, cx),
1008
FormatButton::CodeBlock => self.toggle_code_block(window, cx),
1009
FormatButton::Rule => self.insert_rule(window, cx),
992
1010
}
993
1011
}
994
1012
@@ -1068,6 +1086,25 @@ impl Composer {
1068
1086
FormatButton::Table | FormatButton::TableInsertLine | FormatButton::TableRemoveLine => {
1069
1087
FormatState::Off
1070
1088
}
1089
FormatButton::Highlight if self.format_popup == Some(FormatPopup::Highlight) => {
1090
FormatState::On
1091
}
1092
FormatButton::FontColor if self.format_popup == Some(FormatPopup::FontColor) => {
1093
FormatState::On
1094
}
1095
FormatButton::ParagraphStyle
1096
if self.format_popup == Some(FormatPopup::ParagraphStyle) =>
1097
{
1098
FormatState::On
1099
}
1100
FormatButton::CodeBlock => self.draft.line_state(range, &LineKind::Code(None)),
1101
FormatButton::Highlight
1102
| FormatButton::FontColor
1103
| FormatButton::ParagraphStyle
1104
| FormatButton::ClearFormatting
1105
| FormatButton::Outdent
1106
| FormatButton::Indent
1107
| FormatButton::Rule => FormatState::Off,
1071
1108
}
1072
1109
}
1073
1110
@@ -1081,12 +1118,19 @@ impl Composer {
1081
1118
let enabled = match button {
1082
1119
FormatButton::TableInsertLine | FormatButton::TableRemoveLine => in_table,
1083
1120
FormatButton::Table => true,
1121
FormatButton::Outdent => !in_table && self.draft.can_outdent(selection.clone()),
1084
1122
_ => !in_table,
1085
1123
};
1086
if enabled {
1124
let state = if enabled {
1087
1125
ButtonState::enabled(self.format_state(button, selection))
1088
1126
} else {
1089
1127
ButtonState::disabled()
1128
};
1129
match button {
1130
FormatButton::ParagraphStyle => {
1131
state.with_label(paragraph_label(self.draft.heading_at(selection.start)))
1132
}
1133
_ => state,
1090
1134
}
1091
1135
}
1092
1136
@@ -1103,6 +1147,7 @@ impl Composer {
1103
1147
self.format_bar.remove(&key);
1104
1148
self.table_picker = None;
1105
1149
self.table_menu = None;
1150
self.format_popup = None;
1106
1151
}
1107
1152
cx.notify();
1108
1153
}
@@ -1660,6 +1705,7 @@ impl Composer {
1660
1705
self.schedule = None;
1661
1706
self.table_picker = None;
1662
1707
self.table_menu = None;
1708
self.format_popup = None;
1663
1709
self.reset_importance();
1664
1710
if !carry {
1665
1711
self.load_stored_draft(conversation_id, window, cx);
@@ -2531,6 +2577,11 @@ impl Composer {
2531
2577
FormatButton::Table => self.render_table_picker(cx),
2532
2578
FormatButton::TableInsertLine => self.render_table_menu(TableLineMenu::Insert, cx),
2533
2579
FormatButton::TableRemoveLine => self.render_table_menu(TableLineMenu::Remove, cx),
2580
FormatButton::Highlight => self.render_format_popup(FormatPopup::Highlight, cx),
2581
FormatButton::FontColor => self.render_format_popup(FormatPopup::FontColor, cx),
2582
FormatButton::ParagraphStyle => {
2583
self.render_format_popup(FormatPopup::ParagraphStyle, cx)
2584
}
2534
2585
_ => None,
2535
2586
};
2536
2587
let row = format_toolbar::render_format_bar(&state_of, on_press, &mut overlay);
@@ -2807,6 +2858,13 @@ impl Render for Composer {
2807
2858
.unwrap_or(false)
2808
2859
})
2809
2860
.token(move |context, _, cx| {
2861
if context.is_block() && is_rule_token(context.token()) {
2862
return render_rule_token(
2863
context.available_width(),
2864
context.line_height(),
2865
context.is_selected(),
2866
);
2867
}
2810
2868
if context.is_block() && is_table_token(context.token()) {
2811
2869
let token_id = context.token().id().to_string();
2812
2870
let width = context.available_width();
@@ -2968,6 +3026,26 @@ impl Render for Composer {
2968
3026
.on_action(cx.listener(|this, _: &RemoveTableLine, window, cx| {
2969
3027
this.open_table_menu(TableLineMenu::Remove, window, cx);
2970
3028
}))
3029
.on_action(cx.listener(|this, _: &SetParagraph, window, cx| {
3030
this.set_paragraph_style(None, window, cx)
3031
}))
3032
.on_action(cx.listener(|this, _: &SetHeading1, window, cx| {
3033
this.set_paragraph_style(Some(1), window, cx)
3034
}))
3035
.on_action(cx.listener(|this, _: &SetHeading2, window, cx| {
3036
this.set_paragraph_style(Some(2), window, cx)
3037
}))
3038
.on_action(cx.listener(|this, _: &SetHeading3, window, cx| {
3039
this.set_paragraph_style(Some(3), window, cx)
3040
}))
3041
.on_action(cx.listener(|this, _: &ToggleCodeBlock, window, cx| {
3042
this.toggle_code_block(window, cx)
3043
}))
3044
.on_action(cx.listener(|this, _: &ToggleQuote, window, cx| {
3045
if !this.cell_has_focus(window, cx) {
3046
this.toggle_lines(LineKind::Quote, window, cx)
3047
}
3048
}))
2971
3049
.capture_action(cx.listener(|this, _: &Undo, window, cx| {
2972
3050
if this.link_editor.is_none() {
2973
3051
this.step_history(true, window, cx);
@@ -4316,7 +4394,7 @@ mod tests {
4316
4394
typist.press("enter");
4317
4395
typist.type_text("b");
4318
4396
typist.press("up end delete");
4319
assert_eq!(typist.outgoing().html(), "<pre>ab</pre>");
4397
assert_eq!(typist.outgoing().html(), "<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>ab</code></pre>");
4320
4398
}
4321
4399
4322
4400
#[gpui_kit::test]
@@ -4474,7 +4552,7 @@ mod tests {
4474
4552
.update(|cx| composer.read(cx).paste_hint.is_none())
4475
4553
);
4476
4554
let outgoing = typist.outgoing();
4477
assert_eq!(outgoing.html(), "<pre>:) **x**</pre>");
4555
assert_eq!(outgoing.html(), "<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>:) **x**</code></pre>");
4478
4556
}
4479
4557
4480
4558
#[gpui_kit::test]
@@ -32,14 +32,17 @@ use teams_core::{32
32
33
pub(crate) mod delivery;33
pub(crate) mod delivery;34
mod drafts;34
mod drafts;35
mod format_menus;36
mod rule;35
mod schedule;37
mod schedule;36
mod table;38
mod table;37
39
38
use super::actions::{40
use super::actions::{39
COMPOSER_KEY_CONTEXT, DeleteTable, DeleteTableColumn, DeleteTableRow, EditLink,41
COMPOSER_KEY_CONTEXT, DeleteTable, DeleteTableColumn, DeleteTableRow, EditLink,40
InsertTableColumnLeft, InsertTableColumnRight, InsertTableLine, InsertTableRowAbove,42
InsertTableColumnLeft, InsertTableColumnRight, InsertTableLine, InsertTableRowAbove,41
InsertTableRowBelow, OpenSwitcher, PastePlainText, RemoveTableLine, ScheduleSend, ToggleBold,43
InsertTableRowBelow, OpenSwitcher, PastePlainText, RemoveTableLine, ScheduleSend,42
ToggleCode, ToggleFormatBar, ToggleItalic, ToggleStrike, ToggleSubscript, ToggleSuperscript,44
SetHeading1, SetHeading2, SetHeading3, SetParagraph, ToggleBold, ToggleCode, ToggleCodeBlock,45
ToggleFormatBar, ToggleItalic, ToggleQuote, ToggleStrike, ToggleSubscript, ToggleSuperscript,43
ToggleUnderline,46
ToggleUnderline,44
};47
};45
use super::attachment_tray::{48
use super::attachment_tray::{@@ -62,6 +65,8 @@ use crate::runtime;62
use crate::scheduled_rows::scheduled_label;65
use crate::scheduled_rows::scheduled_label;63
use crate::theme::{self, ElevatedSurface as _};66
use crate::theme::{self, ElevatedSurface as _};64
use crate::typing::OutgoingTyping;67
use crate::typing::OutgoingTyping;68
use format_menus::{FormatPopup, paragraph_label};69
use rule::{is_rule_token, render_rule_token};65
use table::{TableKey, TableLineMenu, TableMenu, TablePicker, TableViews, is_table_token};70
use table::{TableKey, TableLineMenu, TableMenu, TablePicker, TableViews, is_table_token};66
71
67
const MIN_ROWS: usize = 1;72
const MIN_ROWS: usize = 1;@@ -224,6 +229,7 @@ pub struct Composer {224
table_counter: usize,229
table_counter: usize,225
table_picker: Option<TablePicker>,230
table_picker: Option<TablePicker>,226
table_menu: Option<TableMenu>,231
table_menu: Option<TableMenu>,232
format_popup: Option<FormatPopup>,227
format_bar: HashSet<String>,233
format_bar: HashSet<String>,228
active_cell: Option<(String, teams_core::Cell)>,234
active_cell: Option<(String, teams_core::Cell)>,229
caret_before_table: usize,235
caret_before_table: usize,@@ -450,6 +456,7 @@ impl Composer {450
table_counter: 0,456
table_counter: 0,451
table_picker: None,457
table_picker: None,452
table_menu: None,458
table_menu: None,459
format_popup: None,453
format_bar: HashSet::new(),460
format_bar: HashSet::new(),454
active_cell: None,461
active_cell: None,455
caret_before_table: 0,462
caret_before_table: 0,@@ -849,6 +856,7 @@ impl Composer {849
self.pending_anchors.clear();856
self.pending_anchors.clear();850
self.active_cell = None;857
self.active_cell = None;851
self.table_picker = None;858
self.table_picker = None;859
self.format_popup = None;852
self.sync_tables(window, cx);860
self.sync_tables(window, cx);853
self.history.clear();861
self.history.clear();854
self.history_index = 0;862
self.history_index = 0;@@ -989,6 +997,16 @@ impl Composer {989
FormatButton::TableRemoveLine => {997
FormatButton::TableRemoveLine => {990
self.open_table_menu(TableLineMenu::Remove, window, cx);998
self.open_table_menu(TableLineMenu::Remove, window, cx);991
}999
}1000
FormatButton::Highlight => self.toggle_format_popup(FormatPopup::Highlight, cx),1001
FormatButton::FontColor => self.toggle_format_popup(FormatPopup::FontColor, cx),1002
FormatButton::ParagraphStyle => {1003
self.toggle_format_popup(FormatPopup::ParagraphStyle, cx)1004
}1005
FormatButton::ClearFormatting => self.clear_formatting(window, cx),1006
FormatButton::Outdent => self.indent_blocks(true, window, cx),1007
FormatButton::Indent => self.indent_blocks(false, window, cx),1008
FormatButton::CodeBlock => self.toggle_code_block(window, cx),1009
FormatButton::Rule => self.insert_rule(window, cx),992
}1010
}993
}1011
}994
1012
@@ -1068,6 +1086,25 @@ impl Composer {1068
FormatButton::Table | FormatButton::TableInsertLine | FormatButton::TableRemoveLine => {1086
FormatButton::Table | FormatButton::TableInsertLine | FormatButton::TableRemoveLine => {1069
FormatState::Off1087
FormatState::Off1070
}1088
}1089
FormatButton::Highlight if self.format_popup == Some(FormatPopup::Highlight) => {1090
FormatState::On1091
}1092
FormatButton::FontColor if self.format_popup == Some(FormatPopup::FontColor) => {1093
FormatState::On1094
}1095
FormatButton::ParagraphStyle1096
if self.format_popup == Some(FormatPopup::ParagraphStyle) =>1097
{1098
FormatState::On1099
}1100
FormatButton::CodeBlock => self.draft.line_state(range, &LineKind::Code(None)),1101
FormatButton::Highlight1102
| FormatButton::FontColor1103
| FormatButton::ParagraphStyle1104
| FormatButton::ClearFormatting1105
| FormatButton::Outdent1106
| FormatButton::Indent1107
| FormatButton::Rule => FormatState::Off,1071
}1108
}1072
}1109
}1073
1110
@@ -1081,12 +1118,19 @@ impl Composer {1081
let enabled = match button {1118
let enabled = match button {1082
FormatButton::TableInsertLine | FormatButton::TableRemoveLine => in_table,1119
FormatButton::TableInsertLine | FormatButton::TableRemoveLine => in_table,1083
FormatButton::Table => true,1120
FormatButton::Table => true,1121
FormatButton::Outdent => !in_table && self.draft.can_outdent(selection.clone()),1084
_ => !in_table,1122
_ => !in_table,1085
};1123
};1086
if enabled {1124
let state = if enabled {1087
ButtonState::enabled(self.format_state(button, selection))1125
ButtonState::enabled(self.format_state(button, selection))1088
} else {1126
} else {1089
ButtonState::disabled()1127
ButtonState::disabled()1128
};1129
match button {1130
FormatButton::ParagraphStyle => {1131
state.with_label(paragraph_label(self.draft.heading_at(selection.start)))1132
}1133
_ => state,1090
}1134
}1091
}1135
}1092
1136
@@ -1103,6 +1147,7 @@ impl Composer {1103
self.format_bar.remove(&key);1147
self.format_bar.remove(&key);1104
self.table_picker = None;1148
self.table_picker = None;1105
self.table_menu = None;1149
self.table_menu = None;1150
self.format_popup = None;1106
}1151
}1107
cx.notify();1152
cx.notify();1108
}1153
}@@ -1660,6 +1705,7 @@ impl Composer {1660
self.schedule = None;1705
self.schedule = None;1661
self.table_picker = None;1706
self.table_picker = None;1662
self.table_menu = None;1707
self.table_menu = None;1708
self.format_popup = None;1663
self.reset_importance();1709
self.reset_importance();1664
if !carry {1710
if !carry {1665
self.load_stored_draft(conversation_id, window, cx);1711
self.load_stored_draft(conversation_id, window, cx);@@ -2531,6 +2577,11 @@ impl Composer {2531
FormatButton::Table => self.render_table_picker(cx),2577
FormatButton::Table => self.render_table_picker(cx),2532
FormatButton::TableInsertLine => self.render_table_menu(TableLineMenu::Insert, cx),2578
FormatButton::TableInsertLine => self.render_table_menu(TableLineMenu::Insert, cx),2533
FormatButton::TableRemoveLine => self.render_table_menu(TableLineMenu::Remove, cx),2579
FormatButton::TableRemoveLine => self.render_table_menu(TableLineMenu::Remove, cx),2580
FormatButton::Highlight => self.render_format_popup(FormatPopup::Highlight, cx),2581
FormatButton::FontColor => self.render_format_popup(FormatPopup::FontColor, cx),2582
FormatButton::ParagraphStyle => {2583
self.render_format_popup(FormatPopup::ParagraphStyle, cx)2584
}2534
_ => None,2585
_ => None,2535
};2586
};2536
let row = format_toolbar::render_format_bar(&state_of, on_press, &mut overlay);2587
let row = format_toolbar::render_format_bar(&state_of, on_press, &mut overlay);@@ -2807,6 +2858,13 @@ impl Render for Composer {2807
.unwrap_or(false)2858
.unwrap_or(false)2808
})2859
})2809
.token(move |context, _, cx| {2860
.token(move |context, _, cx| {2861
if context.is_block() && is_rule_token(context.token()) {2862
return render_rule_token(2863
context.available_width(),2864
context.line_height(),2865
context.is_selected(),2866
);2867
}2810
if context.is_block() && is_table_token(context.token()) {2868
if context.is_block() && is_table_token(context.token()) {2811
let token_id = context.token().id().to_string();2869
let token_id = context.token().id().to_string();2812
let width = context.available_width();2870
let width = context.available_width();@@ -2968,6 +3026,26 @@ impl Render for Composer {2968
.on_action(cx.listener(|this, _: &RemoveTableLine, window, cx| {3026
.on_action(cx.listener(|this, _: &RemoveTableLine, window, cx| {2969
this.open_table_menu(TableLineMenu::Remove, window, cx);3027
this.open_table_menu(TableLineMenu::Remove, window, cx);2970
}))3028
}))3029
.on_action(cx.listener(|this, _: &SetParagraph, window, cx| {3030
this.set_paragraph_style(None, window, cx)3031
}))3032
.on_action(cx.listener(|this, _: &SetHeading1, window, cx| {3033
this.set_paragraph_style(Some(1), window, cx)3034
}))3035
.on_action(cx.listener(|this, _: &SetHeading2, window, cx| {3036
this.set_paragraph_style(Some(2), window, cx)3037
}))3038
.on_action(cx.listener(|this, _: &SetHeading3, window, cx| {3039
this.set_paragraph_style(Some(3), window, cx)3040
}))3041
.on_action(cx.listener(|this, _: &ToggleCodeBlock, window, cx| {3042
this.toggle_code_block(window, cx)3043
}))3044
.on_action(cx.listener(|this, _: &ToggleQuote, window, cx| {3045
if !this.cell_has_focus(window, cx) {3046
this.toggle_lines(LineKind::Quote, window, cx)3047
}3048
}))2971
.capture_action(cx.listener(|this, _: &Undo, window, cx| {3049
.capture_action(cx.listener(|this, _: &Undo, window, cx| {2972
if this.link_editor.is_none() {3050
if this.link_editor.is_none() {2973
this.step_history(true, window, cx);3051
this.step_history(true, window, cx);@@ -4316,7 +4394,7 @@ mod tests {4316
typist.press("enter");4394
typist.press("enter");4317
typist.type_text("b");4395
typist.type_text("b");4318
typist.press("up end delete");4396
typist.press("up end delete");4319
assert_eq!(typist.outgoing().html(), "<pre>ab</pre>");4397
assert_eq!(typist.outgoing().html(), "<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>ab</code></pre>");4320
}4398
}4321
4399
4322
#[gpui_kit::test]4400
#[gpui_kit::test]@@ -4474,7 +4552,7 @@ mod tests {4474
.update(|cx| composer.read(cx).paste_hint.is_none())4552
.update(|cx| composer.read(cx).paste_hint.is_none())4475
);4553
);4476
let outgoing = typist.outgoing();4554
let outgoing = typist.outgoing();4477
assert_eq!(outgoing.html(), "<pre>:) **x**</pre>");4555
assert_eq!(outgoing.html(), "<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>:) **x**</code></pre>");4478
}4556
}4479
4557
4480
#[gpui_kit::test]4558
#[gpui_kit::test]@@ -0,0 +1,63 @@
1
use gpui_kit::component::input::InlineToken;
2
use gpui_kit::prelude::FluentBuilder as _;
3
use gpui_kit::*;
4
use teams_core::{LineKind, RULE_MARK};
5
6
use super::Composer;
7
use crate::theme;
8
9
const TOKEN_PREFIX: &str = "rule-";
10
pub(super) const RULE_TOKEN_TAG: &str = "composer/rule";
11
12
fn token(number: usize) -> InlineToken {
13
InlineToken::new(format!("{TOKEN_PREFIX}{number}"), RULE_MARK.to_string()).block()
14
}
15
16
pub(super) fn is_rule_token(token: &InlineToken) -> bool {
17
token.id().starts_with(TOKEN_PREFIX)
18
}
19
20
/// A horizontal rule line across the composer, like Teams' `ck-horizontal-line`.
21
pub(super) fn render_rule_token(width: Pixels, height: Pixels, selected: bool) -> AnyElement {
22
div()
23
.debug_selector(|| RULE_TOKEN_TAG.into())
24
.w(width)
25
.h(height)
26
.flex()
27
.items_center()
28
.rounded(px(4.))
29
.when(selected, |rule| rule.bg(theme::selection()))
30
.child(div().w_full().h(px(1.)).bg(theme::border_strong()))
31
.into_any_element()
32
}
33
34
impl Composer {
35
/// Every rule line gets its block token.
36
pub(super) fn sync_rules(&mut self, window: &mut Window, cx: &mut Context<Self>) {
37
if self.input.read(cx).value().as_ref() != self.draft.text() {
38
return;
39
}
40
let tokens: Vec<_> = self
41
.input
42
.read(cx)
43
.tokens()
44
.iter()
45
.filter(|span| is_rule_token(span.token()))
46
.map(|span| span.range())
47
.collect();
48
let ranges = self.draft.line_ranges();
49
for (index, line) in ranges.into_iter().enumerate() {
50
if self.draft.lines()[index] != LineKind::Rule || tokens.contains(&line) {
51
continue;
52
}
53
self.table_counter += 1;
54
let token = token(self.table_counter);
55
self.input.update(cx, |state, cx| {
56
let selection = state.selected_range();
57
if state.replace_range_with_token(line, token, window, cx).is_ok() {
58
state.set_selected_range(selection, cx);
59
}
60
});
61
}
62
}
63
}
@@ -0,0 +1,63 @@1
use gpui_kit::component::input::InlineToken;2
use gpui_kit::prelude::FluentBuilder as _;3
use gpui_kit::*;4
use teams_core::{LineKind, RULE_MARK};5
6
use super::Composer;7
use crate::theme;8
9
const TOKEN_PREFIX: &str = "rule-";10
pub(super) const RULE_TOKEN_TAG: &str = "composer/rule";11
12
fn token(number: usize) -> InlineToken {13
InlineToken::new(format!("{TOKEN_PREFIX}{number}"), RULE_MARK.to_string()).block()14
}15
16
pub(super) fn is_rule_token(token: &InlineToken) -> bool {17
token.id().starts_with(TOKEN_PREFIX)18
}19
20
/// A horizontal rule line across the composer, like Teams' `ck-horizontal-line`.21
pub(super) fn render_rule_token(width: Pixels, height: Pixels, selected: bool) -> AnyElement {22
div()23
.debug_selector(|| RULE_TOKEN_TAG.into())24
.w(width)25
.h(height)26
.flex()27
.items_center()28
.rounded(px(4.))29
.when(selected, |rule| rule.bg(theme::selection()))30
.child(div().w_full().h(px(1.)).bg(theme::border_strong()))31
.into_any_element()32
}33
34
impl Composer {35
/// Every rule line gets its block token.36
pub(super) fn sync_rules(&mut self, window: &mut Window, cx: &mut Context<Self>) {37
if self.input.read(cx).value().as_ref() != self.draft.text() {38
return;39
}40
let tokens: Vec<_> = self41
.input42
.read(cx)43
.tokens()44
.iter()45
.filter(|span| is_rule_token(span.token()))46
.map(|span| span.range())47
.collect();48
let ranges = self.draft.line_ranges();49
for (index, line) in ranges.into_iter().enumerate() {50
if self.draft.lines()[index] != LineKind::Rule || tokens.contains(&line) {51
continue;52
}53
self.table_counter += 1;54
let token = token(self.table_counter);55
self.input.update(cx, |state, cx| {56
let selection = state.selected_range();57
if state.replace_range_with_token(line, token, window, cx).is_ok() {58
state.set_selected_range(selection, cx);59
}60
});61
}62
}63
}@@ -170,6 +170,7 @@ impl Composer {
170
170
};
171
171
self.sync_table_view(&id, &table, window, cx);
172
172
}
173
self.sync_rules(window, cx);
173
174
}
174
175
175
176
fn sync_table_view(
@@ -170,6 +170,7 @@ impl Composer {170
};170
};171
self.sync_table_view(&id, &table, window, cx);171
self.sync_table_view(&id, &table, window, cx);172
}172
}173
self.sync_rules(window, cx);173
}174
}174
175
175
fn sync_table_view(176
fn sync_table_view(@@ -3,10 +3,11 @@ use std::rc::Rc;
3
3
use gpui_kit::component::input::{Input, InputState};
4
4
use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
5
5
use gpui_kit::prelude::FluentBuilder as _;
6
use gpui_kit::assets::IconName;
6
7
use gpui_kit::*;
7
8
use teams_core::FormatState;
8
9
9
use super::widgets::symbol;
10
use super::widgets::{icon, symbol};
10
11
use crate::theme::{self, ElevatedSurface as _};
11
12
12
13
const PADDING: f32 = 4.;
@@ -46,6 +47,14 @@ pub enum FormatButton {
46
47
Table,
47
48
TableInsertLine,
48
49
TableRemoveLine,
50
Highlight,
51
FontColor,
52
ParagraphStyle,
53
ClearFormatting,
54
Outdent,
55
Indent,
56
CodeBlock,
57
Rule,
49
58
}
50
59
51
60
const STYLE_GROUP: &[FormatButton] = &[
@@ -72,6 +81,29 @@ const TABLE_GROUP: &[FormatButton] = &[
72
81
FormatButton::TableRemoveLine,
73
82
];
74
83
84
const FONT_GROUP: &[FormatButton] = &[
85
FormatButton::Highlight,
86
FormatButton::FontColor,
87
FormatButton::SizeSmall,
88
FormatButton::SizeNormal,
89
FormatButton::SizeLarge,
90
FormatButton::ParagraphStyle,
91
FormatButton::ClearFormatting,
92
];
93
const PARAGRAPH_GROUP: &[FormatButton] = &[
94
FormatButton::Outdent,
95
FormatButton::Indent,
96
FormatButton::Bulleted,
97
FormatButton::Numbered,
98
];
99
const INSERT_GROUP: &[FormatButton] = &[
100
FormatButton::Quote,
101
FormatButton::Link,
102
FormatButton::Code,
103
FormatButton::CodeBlock,
104
FormatButton::Rule,
105
];
106
75
107
/// The floating bar over a selection: text formats only, tables live in the format bar.
76
108
pub const SELECTION_GROUPS: [&[FormatButton]; 5] = [
77
109
STYLE_GROUP,
@@ -81,16 +113,19 @@ pub const SELECTION_GROUPS: [&[FormatButton]; 5] = [
81
113
LINE_GROUP,
82
114
];
83
115
84
/// The format bar the Format button opens, table group second to last like Teams.
116
/// The format bar the Format button opens, in Teams' group order; Teams' last group (undo,
117
/// redo) is left out, so the table group ends the bar.
85
118
pub const BAR_GROUPS: [&[FormatButton]; 6] = [
86
119
STYLE_GROUP,
87
120
SCRIPT_GROUP,
88
SIZE_GROUP,
89
INLINE_GROUP,
121
FONT_GROUP,
122
PARAGRAPH_GROUP,
123
INSERT_GROUP,
90
124
TABLE_GROUP,
91
LINE_GROUP,
92
125
];
93
126
127
pub const PARAGRAPH_STYLE_WIDTH: f32 = 104.;
128
94
129
pub const TOGGLE_SHORTCUT: &str = "Ctrl+Shift+X";
95
130
96
131
pub fn toggle_tooltip(open: bool) -> String {
@@ -114,6 +149,7 @@ pub fn toggle_symbol(open: bool) -> &'static str {
114
149
pub struct ButtonState {
115
150
pub format: FormatState,
116
151
pub enabled: bool,
152
pub label: Option<&'static str>,
117
153
}
118
154
119
155
impl ButtonState {
@@ -121,6 +157,7 @@ impl ButtonState {
121
157
ButtonState {
122
158
format,
123
159
enabled: true,
160
label: None,
124
161
}
125
162
}
126
163
@@ -128,6 +165,14 @@ impl ButtonState {
128
165
ButtonState {
129
166
format: FormatState::Off,
130
167
enabled: false,
168
label: None,
169
}
170
}
171
172
pub fn with_label(self, label: &'static str) -> Self {
173
ButtonState {
174
label: Some(label),
175
..self
131
176
}
132
177
}
133
178
}
@@ -148,14 +193,22 @@ impl FormatButton {
148
193
FormatButton::Link => "Link (Ctrl+K)",
149
194
FormatButton::Bulleted => "Bulleted list",
150
195
FormatButton::Numbered => "Numbered list",
151
FormatButton::Quote => "Quote",
196
FormatButton::Quote => "Quote (Ctrl+Alt+4)",
152
197
FormatButton::Table => "Insert table",
153
198
FormatButton::TableInsertLine => "Insert column or row (Ctrl+Alt+=)",
154
199
FormatButton::TableRemoveLine => "Delete column, row, or table (Ctrl+Alt+-)",
200
FormatButton::Highlight => "Text highlight colour",
201
FormatButton::FontColor => "Font colour",
202
FormatButton::ParagraphStyle => "Rich style",
203
FormatButton::ClearFormatting => "Clear all formatting",
204
FormatButton::Outdent => "Decrease indent",
205
FormatButton::Indent => "Increase indent",
206
FormatButton::CodeBlock => "Code block (Ctrl+Shift+B)",
207
FormatButton::Rule => "Insert horizontal rule",
155
208
}
156
209
}
157
210
158
fn content(self, color: Hsla) -> AnyElement {
211
fn content(self, color: Hsla, label: Option<&'static str>) -> AnyElement {
159
212
let letter = |text: &'static str| div().text_size(px(15.)).text_color(color).child(text);
160
213
match self {
161
214
FormatButton::Bold => letter("B").font_weight(FontWeight::BOLD).into_any_element(),
@@ -179,6 +232,37 @@ impl FormatButton {
179
232
FormatButton::TableRemoveLine => {
180
233
symbol("fluent_table_dismiss", 20., color).into_any_element()
181
234
}
235
FormatButton::Highlight => symbol("fluent_highlight", 20., color).into_any_element(),
236
FormatButton::FontColor => symbol("fluent_text_color", 20., color).into_any_element(),
237
FormatButton::ParagraphStyle => h_flex()
238
.w_full()
239
.px(px(6.))
240
.gap(px(4.))
241
.items_center()
242
.justify_between()
243
.text_size(px(13.))
244
.text_color(color)
245
.child(label.unwrap_or_default())
246
.child(icon(IconName::ChevronDown, 12., color))
247
.into_any_element(),
248
FormatButton::ClearFormatting => {
249
symbol("fluent_text_clear_formatting", 20., color).into_any_element()
250
}
251
FormatButton::Outdent => {
252
symbol("fluent_text_indent_decrease", 20., color).into_any_element()
253
}
254
FormatButton::Indent => {
255
symbol("fluent_text_indent_increase", 20., color).into_any_element()
256
}
257
FormatButton::CodeBlock => symbol("fluent_code_block", 20., color).into_any_element(),
258
FormatButton::Rule => symbol("fluent_line_horizontal_1", 20., color).into_any_element(),
259
}
260
}
261
262
fn width(self) -> f32 {
263
match self {
264
FormatButton::ParagraphStyle => PARAGRAPH_STYLE_WIDTH,
265
_ => BUTTON,
182
266
}
183
267
}
184
268
}
@@ -271,14 +355,15 @@ fn button(
271
355
div()
272
356
.id(ElementId::Name(format!("format-{format:?}").into()))
273
357
.relative()
274
.size(px(BUTTON))
358
.w(px(format.width()))
359
.h(px(BUTTON))
275
360
.flex()
276
361
.flex_none()
277
362
.items_center()
278
363
.justify_center()
279
364
.rounded(px(6.))
280
365
.tooltip(move |window, cx| Tooltip::new(format.tooltip()).build(window, cx))
281
.child(format.content(color))
366
.child(format.content(color, state.label))
282
367
.on_mouse_down(MouseButton::Left, |_, window, cx| {
283
368
window.prevent_default();
284
369
cx.stop_propagation();
@@ -521,18 +606,31 @@ mod tests {
521
606
}
522
607
523
608
#[test]
524
fn the_format_bar_has_the_teams_table_group_second_to_last() {
525
let table_group = BAR_GROUPS[BAR_GROUPS.len() - 2];
609
fn the_format_bar_follows_the_teams_groups_and_keeps_every_selection_format() {
526
610
assert_eq!(
527
table_group,
611
BAR_GROUPS[BAR_GROUPS.len() - 1],
528
612
&[
529
613
FormatButton::Table,
530
614
FormatButton::TableInsertLine,
531
615
FormatButton::TableRemoveLine
532
616
][..]
533
617
);
534
for group in SELECTION_GROUPS {
535
assert!(BAR_GROUPS.contains(&group));
618
assert_eq!(
619
BAR_GROUPS[2][..2],
620
[FormatButton::Highlight, FormatButton::FontColor]
621
);
622
assert_eq!(
623
BAR_GROUPS[3],
624
&[
625
FormatButton::Outdent,
626
FormatButton::Indent,
627
FormatButton::Bulleted,
628
FormatButton::Numbered
629
][..]
630
);
631
assert_eq!(BAR_GROUPS[4].last(), Some(&FormatButton::Rule));
632
for button in SELECTION_GROUPS.iter().flat_map(|group| group.iter()) {
633
assert!(BAR_GROUPS.iter().any(|group| group.contains(button)));
536
634
}
537
635
}
538
636
@@ -3,10 +3,11 @@ use std::rc::Rc;3
use gpui_kit::component::input::{Input, InputState};3
use gpui_kit::component::input::{Input, InputState};4
use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};4
use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};5
use gpui_kit::prelude::FluentBuilder as _;5
use gpui_kit::prelude::FluentBuilder as _;6
use gpui_kit::assets::IconName;6
use gpui_kit::*;7
use gpui_kit::*;7
use teams_core::FormatState;8
use teams_core::FormatState;8
9
9
use super::widgets::symbol;10
use super::widgets::{icon, symbol};10
use crate::theme::{self, ElevatedSurface as _};11
use crate::theme::{self, ElevatedSurface as _};11
12
12
const PADDING: f32 = 4.;13
const PADDING: f32 = 4.;@@ -46,6 +47,14 @@ pub enum FormatButton {46
Table,47
Table,47
TableInsertLine,48
TableInsertLine,48
TableRemoveLine,49
TableRemoveLine,50
Highlight,51
FontColor,52
ParagraphStyle,53
ClearFormatting,54
Outdent,55
Indent,56
CodeBlock,57
Rule,49
}58
}50
59
51
const STYLE_GROUP: &[FormatButton] = &[60
const STYLE_GROUP: &[FormatButton] = &[@@ -72,6 +81,29 @@ const TABLE_GROUP: &[FormatButton] = &[72
FormatButton::TableRemoveLine,81
FormatButton::TableRemoveLine,73
];82
];74
83
84
const FONT_GROUP: &[FormatButton] = &[85
FormatButton::Highlight,86
FormatButton::FontColor,87
FormatButton::SizeSmall,88
FormatButton::SizeNormal,89
FormatButton::SizeLarge,90
FormatButton::ParagraphStyle,91
FormatButton::ClearFormatting,92
];93
const PARAGRAPH_GROUP: &[FormatButton] = &[94
FormatButton::Outdent,95
FormatButton::Indent,96
FormatButton::Bulleted,97
FormatButton::Numbered,98
];99
const INSERT_GROUP: &[FormatButton] = &[100
FormatButton::Quote,101
FormatButton::Link,102
FormatButton::Code,103
FormatButton::CodeBlock,104
FormatButton::Rule,105
];106
75
/// The floating bar over a selection: text formats only, tables live in the format bar.107
/// The floating bar over a selection: text formats only, tables live in the format bar.76
pub const SELECTION_GROUPS: [&[FormatButton]; 5] = [108
pub const SELECTION_GROUPS: [&[FormatButton]; 5] = [77
STYLE_GROUP,109
STYLE_GROUP,@@ -81,16 +113,19 @@ pub const SELECTION_GROUPS: [&[FormatButton]; 5] = [81
LINE_GROUP,113
LINE_GROUP,82
];114
];83
115
84
/// The format bar the Format button opens, table group second to last like Teams.116
/// The format bar the Format button opens, in Teams' group order; Teams' last group (undo,117
/// redo) is left out, so the table group ends the bar.85
pub const BAR_GROUPS: [&[FormatButton]; 6] = [118
pub const BAR_GROUPS: [&[FormatButton]; 6] = [86
STYLE_GROUP,119
STYLE_GROUP,87
SCRIPT_GROUP,120
SCRIPT_GROUP,88
SIZE_GROUP,121
FONT_GROUP,89
INLINE_GROUP,122
PARAGRAPH_GROUP,123
INSERT_GROUP,90
TABLE_GROUP,124
TABLE_GROUP,91
LINE_GROUP,92
];125
];93
126
127
pub const PARAGRAPH_STYLE_WIDTH: f32 = 104.;128
94
pub const TOGGLE_SHORTCUT: &str = "Ctrl+Shift+X";129
pub const TOGGLE_SHORTCUT: &str = "Ctrl+Shift+X";95
130
96
pub fn toggle_tooltip(open: bool) -> String {131
pub fn toggle_tooltip(open: bool) -> String {@@ -114,6 +149,7 @@ pub fn toggle_symbol(open: bool) -> &'static str {114
pub struct ButtonState {149
pub struct ButtonState {115
pub format: FormatState,150
pub format: FormatState,116
pub enabled: bool,151
pub enabled: bool,152
pub label: Option<&'static str>,117
}153
}118
154
119
impl ButtonState {155
impl ButtonState {@@ -121,6 +157,7 @@ impl ButtonState {121
ButtonState {157
ButtonState {122
format,158
format,123
enabled: true,159
enabled: true,160
label: None,124
}161
}125
}162
}126
163
@@ -128,6 +165,14 @@ impl ButtonState {128
ButtonState {165
ButtonState {129
format: FormatState::Off,166
format: FormatState::Off,130
enabled: false,167
enabled: false,168
label: None,169
}170
}171
172
pub fn with_label(self, label: &'static str) -> Self {173
ButtonState {174
label: Some(label),175
..self131
}176
}132
}177
}133
}178
}@@ -148,14 +193,22 @@ impl FormatButton {148
FormatButton::Link => "Link (Ctrl+K)",193
FormatButton::Link => "Link (Ctrl+K)",149
FormatButton::Bulleted => "Bulleted list",194
FormatButton::Bulleted => "Bulleted list",150
FormatButton::Numbered => "Numbered list",195
FormatButton::Numbered => "Numbered list",151
FormatButton::Quote => "Quote",196
FormatButton::Quote => "Quote (Ctrl+Alt+4)",152
FormatButton::Table => "Insert table",197
FormatButton::Table => "Insert table",153
FormatButton::TableInsertLine => "Insert column or row (Ctrl+Alt+=)",198
FormatButton::TableInsertLine => "Insert column or row (Ctrl+Alt+=)",154
FormatButton::TableRemoveLine => "Delete column, row, or table (Ctrl+Alt+-)",199
FormatButton::TableRemoveLine => "Delete column, row, or table (Ctrl+Alt+-)",200
FormatButton::Highlight => "Text highlight colour",201
FormatButton::FontColor => "Font colour",202
FormatButton::ParagraphStyle => "Rich style",203
FormatButton::ClearFormatting => "Clear all formatting",204
FormatButton::Outdent => "Decrease indent",205
FormatButton::Indent => "Increase indent",206
FormatButton::CodeBlock => "Code block (Ctrl+Shift+B)",207
FormatButton::Rule => "Insert horizontal rule",155
}208
}156
}209
}157
210
158
fn content(self, color: Hsla) -> AnyElement {211
fn content(self, color: Hsla, label: Option<&'static str>) -> AnyElement {159
let letter = |text: &'static str| div().text_size(px(15.)).text_color(color).child(text);212
let letter = |text: &'static str| div().text_size(px(15.)).text_color(color).child(text);160
match self {213
match self {161
FormatButton::Bold => letter("B").font_weight(FontWeight::BOLD).into_any_element(),214
FormatButton::Bold => letter("B").font_weight(FontWeight::BOLD).into_any_element(),@@ -179,6 +232,37 @@ impl FormatButton {179
FormatButton::TableRemoveLine => {232
FormatButton::TableRemoveLine => {180
symbol("fluent_table_dismiss", 20., color).into_any_element()233
symbol("fluent_table_dismiss", 20., color).into_any_element()181
}234
}235
FormatButton::Highlight => symbol("fluent_highlight", 20., color).into_any_element(),236
FormatButton::FontColor => symbol("fluent_text_color", 20., color).into_any_element(),237
FormatButton::ParagraphStyle => h_flex()238
.w_full()239
.px(px(6.))240
.gap(px(4.))241
.items_center()242
.justify_between()243
.text_size(px(13.))244
.text_color(color)245
.child(label.unwrap_or_default())246
.child(icon(IconName::ChevronDown, 12., color))247
.into_any_element(),248
FormatButton::ClearFormatting => {249
symbol("fluent_text_clear_formatting", 20., color).into_any_element()250
}251
FormatButton::Outdent => {252
symbol("fluent_text_indent_decrease", 20., color).into_any_element()253
}254
FormatButton::Indent => {255
symbol("fluent_text_indent_increase", 20., color).into_any_element()256
}257
FormatButton::CodeBlock => symbol("fluent_code_block", 20., color).into_any_element(),258
FormatButton::Rule => symbol("fluent_line_horizontal_1", 20., color).into_any_element(),259
}260
}261
262
fn width(self) -> f32 {263
match self {264
FormatButton::ParagraphStyle => PARAGRAPH_STYLE_WIDTH,265
_ => BUTTON,182
}266
}183
}267
}184
}268
}@@ -271,14 +355,15 @@ fn button(271
div()355
div()272
.id(ElementId::Name(format!("format-{format:?}").into()))356
.id(ElementId::Name(format!("format-{format:?}").into()))273
.relative()357
.relative()274
.size(px(BUTTON))358
.w(px(format.width()))359
.h(px(BUTTON))275
.flex()360
.flex()276
.flex_none()361
.flex_none()277
.items_center()362
.items_center()278
.justify_center()363
.justify_center()279
.rounded(px(6.))364
.rounded(px(6.))280
.tooltip(move |window, cx| Tooltip::new(format.tooltip()).build(window, cx))365
.tooltip(move |window, cx| Tooltip::new(format.tooltip()).build(window, cx))281
.child(format.content(color))366
.child(format.content(color, state.label))282
.on_mouse_down(MouseButton::Left, |_, window, cx| {367
.on_mouse_down(MouseButton::Left, |_, window, cx| {283
window.prevent_default();368
window.prevent_default();284
cx.stop_propagation();369
cx.stop_propagation();@@ -521,18 +606,31 @@ mod tests {521
}606
}522
607
523
#[test]608
#[test]524
fn the_format_bar_has_the_teams_table_group_second_to_last() {609
fn the_format_bar_follows_the_teams_groups_and_keeps_every_selection_format() {525
let table_group = BAR_GROUPS[BAR_GROUPS.len() - 2];526
assert_eq!(610
assert_eq!(527
table_group,611
BAR_GROUPS[BAR_GROUPS.len() - 1],528
&[612
&[529
FormatButton::Table,613
FormatButton::Table,530
FormatButton::TableInsertLine,614
FormatButton::TableInsertLine,531
FormatButton::TableRemoveLine615
FormatButton::TableRemoveLine532
][..]616
][..]533
);617
);534
for group in SELECTION_GROUPS {618
assert_eq!(535
assert!(BAR_GROUPS.contains(&group));619
BAR_GROUPS[2][..2],620
[FormatButton::Highlight, FormatButton::FontColor]621
);622
assert_eq!(623
BAR_GROUPS[3],624
&[625
FormatButton::Outdent,626
FormatButton::Indent,627
FormatButton::Bulleted,628
FormatButton::Numbered629
][..]630
);631
assert_eq!(BAR_GROUPS[4].last(), Some(&FormatButton::Rule));632
for button in SELECTION_GROUPS.iter().flat_map(|group| group.iter()) {633
assert!(BAR_GROUPS.iter().any(|group| group.contains(button)));536
}634
}537
}635
}538
636
@@ -4,7 +4,8 @@ use super::actions::{
4
4
COMPOSER_KEY_CONTEXT as COMPOSER_CONTEXT, EditLink, InsertTableLine, NewChat, OpenSwitcher,
5
5
PastePlainText, RemoveTableLine, ReplyToHovered, ScheduleSend, ToggleBold, ToggleCallMute,
6
6
ToggleCode, ToggleFormatBar, ToggleItalic, ToggleStrike, ToggleSubscript, ToggleSuperscript,
7
ToggleUnderline,
7
ToggleUnderline, SetParagraph, SetHeading1, SetHeading2, SetHeading3, ToggleCodeBlock,
8
ToggleQuote,
8
9
};
9
10
10
11
const TEXT_FIELD_CONTEXT: &str = "Input";
@@ -158,6 +159,12 @@ pub const SHORTCUTS: &[Shortcut] = &[
158
159
shortcut!(Composer, Composer, "Schedule send", "ctrl-shift-enter", None, ScheduleSend),
159
160
shortcut!(Composer, Composer, "Insert column or row", "ctrl-alt-=", None, InsertTableLine),
160
161
shortcut!(Composer, Composer, "Delete column, row, or table", "ctrl-alt--", None, RemoveTableLine),
162
shortcut!(Composer, Composer, "Code block", "ctrl-shift-b", None, ToggleCodeBlock),
163
shortcut!(Composer, Composer, "Quote", "ctrl-alt-4", None, ToggleQuote),
164
shortcut!(Composer, Composer, "Heading 1", "ctrl-alt-1", None, SetHeading1),
165
shortcut!(Composer, Composer, "Heading 2", "ctrl-alt-2", None, SetHeading2),
166
shortcut!(Composer, Composer, "Heading 3", "ctrl-alt-3", None, SetHeading3),
167
shortcut!(Composer, Composer, "Paragraph", "ctrl-alt-p", None, SetParagraph),
161
168
shortcut!(Calls, GlobalOverTextFields, "Accept incoming call", "ctrl-shift-a", Some("cmd-shift-a"), AcceptCall),
162
169
shortcut!(Calls, GlobalOverTextFields, "Decline incoming call", "ctrl-shift-d", Some("cmd-shift-d"), DeclineCall),
163
170
shortcut!(Calls, GlobalOverTextFields, "Join the meeting from its reminder", "ctrl-shift-j", Some("cmd-shift-j"), JoinMeetingFromToast),
@@ -440,6 +447,11 @@ mod tests {
440
447
("ctrl-alt-=", "Insert column or row"),
441
448
("ctrl-alt-+", "Insert column or row"),
442
449
("ctrl-alt--", "Delete column, row, or table"),
450
("ctrl-shift-b", "Code block"),
451
("ctrl-alt-4", "Quote"),
452
("ctrl-alt-1", "Heading 1"),
453
("ctrl-alt-3", "Heading 3"),
454
("ctrl-alt-p", "Paragraph"),
443
455
] {
444
456
assert_eq!(
445
457
bound_action(cx, keys, &typing),
@@ -4,7 +4,8 @@ use super::actions::{4
COMPOSER_KEY_CONTEXT as COMPOSER_CONTEXT, EditLink, InsertTableLine, NewChat, OpenSwitcher,4
COMPOSER_KEY_CONTEXT as COMPOSER_CONTEXT, EditLink, InsertTableLine, NewChat, OpenSwitcher,5
PastePlainText, RemoveTableLine, ReplyToHovered, ScheduleSend, ToggleBold, ToggleCallMute,5
PastePlainText, RemoveTableLine, ReplyToHovered, ScheduleSend, ToggleBold, ToggleCallMute,6
ToggleCode, ToggleFormatBar, ToggleItalic, ToggleStrike, ToggleSubscript, ToggleSuperscript,6
ToggleCode, ToggleFormatBar, ToggleItalic, ToggleStrike, ToggleSubscript, ToggleSuperscript,7
ToggleUnderline,7
ToggleUnderline, SetParagraph, SetHeading1, SetHeading2, SetHeading3, ToggleCodeBlock,8
ToggleQuote,8
};9
};9
10
10
const TEXT_FIELD_CONTEXT: &str = "Input";11
const TEXT_FIELD_CONTEXT: &str = "Input";@@ -158,6 +159,12 @@ pub const SHORTCUTS: &[Shortcut] = &[158
shortcut!(Composer, Composer, "Schedule send", "ctrl-shift-enter", None, ScheduleSend),159
shortcut!(Composer, Composer, "Schedule send", "ctrl-shift-enter", None, ScheduleSend),159
shortcut!(Composer, Composer, "Insert column or row", "ctrl-alt-=", None, InsertTableLine),160
shortcut!(Composer, Composer, "Insert column or row", "ctrl-alt-=", None, InsertTableLine),160
shortcut!(Composer, Composer, "Delete column, row, or table", "ctrl-alt--", None, RemoveTableLine),161
shortcut!(Composer, Composer, "Delete column, row, or table", "ctrl-alt--", None, RemoveTableLine),162
shortcut!(Composer, Composer, "Code block", "ctrl-shift-b", None, ToggleCodeBlock),163
shortcut!(Composer, Composer, "Quote", "ctrl-alt-4", None, ToggleQuote),164
shortcut!(Composer, Composer, "Heading 1", "ctrl-alt-1", None, SetHeading1),165
shortcut!(Composer, Composer, "Heading 2", "ctrl-alt-2", None, SetHeading2),166
shortcut!(Composer, Composer, "Heading 3", "ctrl-alt-3", None, SetHeading3),167
shortcut!(Composer, Composer, "Paragraph", "ctrl-alt-p", None, SetParagraph),161
shortcut!(Calls, GlobalOverTextFields, "Accept incoming call", "ctrl-shift-a", Some("cmd-shift-a"), AcceptCall),168
shortcut!(Calls, GlobalOverTextFields, "Accept incoming call", "ctrl-shift-a", Some("cmd-shift-a"), AcceptCall),162
shortcut!(Calls, GlobalOverTextFields, "Decline incoming call", "ctrl-shift-d", Some("cmd-shift-d"), DeclineCall),169
shortcut!(Calls, GlobalOverTextFields, "Decline incoming call", "ctrl-shift-d", Some("cmd-shift-d"), DeclineCall),163
shortcut!(Calls, GlobalOverTextFields, "Join the meeting from its reminder", "ctrl-shift-j", Some("cmd-shift-j"), JoinMeetingFromToast),170
shortcut!(Calls, GlobalOverTextFields, "Join the meeting from its reminder", "ctrl-shift-j", Some("cmd-shift-j"), JoinMeetingFromToast),@@ -440,6 +447,11 @@ mod tests {440
("ctrl-alt-=", "Insert column or row"),447
("ctrl-alt-=", "Insert column or row"),441
("ctrl-alt-+", "Insert column or row"),448
("ctrl-alt-+", "Insert column or row"),442
("ctrl-alt--", "Delete column, row, or table"),449
("ctrl-alt--", "Delete column, row, or table"),450
("ctrl-shift-b", "Code block"),451
("ctrl-alt-4", "Quote"),452
("ctrl-alt-1", "Heading 1"),453
("ctrl-alt-3", "Heading 3"),454
("ctrl-alt-p", "Paragraph"),443
] {455
] {444
assert_eq!(456
assert_eq!(445
bound_action(cx, keys, &typing),457
bound_action(cx, keys, &typing),@@ -11,12 +11,17 @@ use crate::table::{TABLE_MARK, Table, markdown_table};
11
11
pub const MAX_DEPTH: u8 = 2;
12
12
pub const MAX_HEADING: u8 = 3;
13
13
pub const OBJECT_MARK: char = '\u{FFFC}';
14
pub const RULE_MARK: char = '\u{FFFA}';
15
pub const MAX_INDENT: u8 = 8;
16
pub const INDENT_PIXELS: u32 = 40;
17
pub const RULE_HTML: &str = "<hr>";
14
18
const BULLETS: [&str; 3] = ["•", "◦", "▪"];
15
19
const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "];
16
20
const LINK_SCHEMES: [&str; 3] = ["http://", "https://", "mailto:"];
17
21
const AUTOLINK_PREFIXES: [&str; 4] = ["http://", "https://", "www.", "mailto:"];
18
22
const AUTOLINK_TRAILING: &str = ".,;:!?'\"";
19
23
const FENCE: &str = "```";
24
const PLAIN_LANGUAGE: &str = "plaintext";
20
25
const MARKDOWN_INDENT: usize = 2;
21
26
22
27
static TYPED_LINK: LazyLock<Regex> =
@@ -49,6 +54,8 @@ pub enum MarkKind {
49
54
Superscript,
50
55
Subscript,
51
56
Size(SizeStep),
57
Color(u32),
58
Highlight(u32),
52
59
Code,
53
60
}
54
61
@@ -60,6 +67,8 @@ impl MarkKind {
60
67
fn covers(&self, other: &MarkKind) -> bool {
61
68
match (self, other) {
62
69
(MarkKind::Size(left), MarkKind::Size(right)) => left == right,
70
(MarkKind::Color(left), MarkKind::Color(right)) => left == right,
71
(MarkKind::Highlight(left), MarkKind::Highlight(right)) => left == right,
63
72
_ => self.same_format(other),
64
73
}
65
74
}
@@ -82,6 +91,8 @@ impl MarkKind {
82
91
| MarkKind::Superscript
83
92
| MarkKind::Subscript
84
93
| MarkKind::Size(_)
94
| MarkKind::Color(_)
95
| MarkKind::Highlight(_)
85
96
)
86
97
}
87
98
@@ -95,6 +106,10 @@ impl MarkKind {
95
106
MarkKind::Superscript => "<sup>".to_owned(),
96
107
MarkKind::Subscript => "<sub>".to_owned(),
97
108
MarkKind::Size(step) => format!("<span style=\"font-size:{};\">", step.css()),
109
MarkKind::Color(color) => format!("<span style=\"color:{};\">", hex_color(*color)),
110
MarkKind::Highlight(color) => {
111
format!("<span style=\"background-color:{};\">", hex_color(*color))
112
}
98
113
MarkKind::Code => "<code>".to_owned(),
99
114
}
100
115
}
@@ -108,7 +123,7 @@ impl MarkKind {
108
123
MarkKind::Strike => "</s>",
109
124
MarkKind::Superscript => "</sup>",
110
125
MarkKind::Subscript => "</sub>",
111
MarkKind::Size(_) => "</span>",
126
MarkKind::Size(_) | MarkKind::Color(_) | MarkKind::Highlight(_) => "</span>",
112
127
MarkKind::Code => "</code>",
113
128
}
114
129
}
@@ -123,12 +138,14 @@ pub struct Mark {
123
138
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
124
139
pub enum LineKind {
125
140
Text,
141
Indent(u8),
126
142
Bullet(u8),
127
143
Numbered(u8),
128
144
Quote,
129
145
Code(Option<String>),
130
146
Heading(u8),
131
147
Table(Table),
148
Rule,
132
149
}
133
150
134
151
impl LineKind {
@@ -140,6 +157,15 @@ impl LineKind {
140
157
matches!(self, LineKind::Table(_))
141
158
}
142
159
160
/// A line that holds one object mark alone: a table or a horizontal rule.
161
pub fn object_mark(&self) -> Option<char> {
162
match self {
163
LineKind::Table(_) => Some(TABLE_MARK),
164
LineKind::Rule => Some(RULE_MARK),
165
_ => None,
166
}
167
}
168
143
169
pub fn depth(&self) -> u8 {
144
170
match self {
145
171
LineKind::Bullet(depth) | LineKind::Numbered(depth) => *depth,
@@ -216,15 +242,44 @@ impl TypingStyle {
216
242
217
243
/// `None` is the normal size.
218
244
pub fn set_size(&mut self, size: Option<SizeStep>, active: &[MarkKind]) {
219
let marker = MarkKind::Size(SizeStep::Small);
245
self.set_exclusive(
246
MarkKind::Size(SizeStep::Small),
247
size.map(MarkKind::Size),
248
active,
249
);
250
}
251
252
/// `None` is Automatic.
253
pub fn set_color(&mut self, color: Option<u32>, active: &[MarkKind]) {
254
self.set_exclusive(MarkKind::Color(0), color.map(MarkKind::Color), active);
255
}
256
257
/// `None` is No highlight.
258
pub fn set_highlight(&mut self, color: Option<u32>, active: &[MarkKind]) {
259
self.set_exclusive(
260
MarkKind::Highlight(0),
261
color.map(MarkKind::Highlight),
262
active,
263
);
264
}
265
266
/// Text typed next drops every format but a link.
267
pub fn clear(&mut self, active: &[MarkKind]) {
268
self.add.clear();
269
self.remove = active
270
.iter()
271
.filter(|kind| !matches!(kind, MarkKind::Link(_)))
272
.cloned()
273
.collect();
274
}
275
276
fn set_exclusive(&mut self, marker: MarkKind, value: Option<MarkKind>, active: &[MarkKind]) {
220
277
self.add.retain(|added| !added.same_format(&marker));
221
278
self.remove.retain(|removed| !removed.same_format(&marker));
222
279
if active.iter().any(|existing| existing.same_format(&marker)) {
223
280
self.remove.push(marker);
224
281
}
225
if let Some(step) = size {
226
self.add.push(MarkKind::Size(step));
227
}
282
self.add.extend(value);
228
283
}
229
284
230
285
pub fn is_empty(&self) -> bool {
@@ -440,6 +495,7 @@ impl Draft {
440
495
.into_iter()
441
496
.map(|line| match &line.kind {
442
497
LineKind::Table(table) => table.plain_text(),
498
LineKind::Rule => String::new(),
443
499
_ => line.content,
444
500
})
445
501
.collect::<Vec<_>>()
@@ -579,11 +635,66 @@ impl Draft {
579
635
580
636
/// `None` is the normal size: any size mark on `range` is removed.
581
637
pub fn set_size(&mut self, range: Range<usize>, size: Option<SizeStep>) {
638
self.set_exclusive(
639
range,
640
&MarkKind::Size(SizeStep::Small),
641
size.map(MarkKind::Size),
642
);
643
}
644
645
/// `None` is Automatic: the font colour on `range` is removed.
646
pub fn set_color(&mut self, range: Range<usize>, color: Option<u32>) {
647
self.set_exclusive(range, &MarkKind::Color(0), color.map(MarkKind::Color));
648
}
649
650
/// `None` is No highlight.
651
pub fn set_highlight(&mut self, range: Range<usize>, color: Option<u32>) {
652
self.set_exclusive(
653
range,
654
&MarkKind::Highlight(0),
655
color.map(MarkKind::Highlight),
656
);
657
}
658
659
/// The colour of `marker`'s kind that covers all of `range`.
660
pub fn color_in(&self, range: Range<usize>, marker: &MarkKind) -> Option<u32> {
661
self.marks
662
.iter()
663
.filter(|mark| mark.kind.same_format(marker))
664
.find(|mark| self.state(range.clone(), &mark.kind) == FormatState::On)
665
.and_then(|mark| match mark.kind {
666
MarkKind::Color(color) | MarkKind::Highlight(color) => Some(color),
667
_ => None,
668
})
669
}
670
671
/// Teams' Clear all formatting: every inline format but links, and the block indent.
672
pub fn clear_formatting(&mut self, range: Range<usize>) {
582
673
self.journal = Journal::default();
583
self.remove_marks(range.clone(), &MarkKind::Size(SizeStep::Small));
584
if let Some(step) = size {
674
let kinds: Vec<MarkKind> = self
675
.marks
676
.iter()
677
.filter(|mark| {
678
!matches!(mark.kind, MarkKind::Link(_)) && overlaps(&mark.range, &range)
679
})
680
.map(|mark| mark.kind.clone())
681
.collect();
682
for kind in kinds {
683
self.remove_marks(range.clone(), &kind);
684
}
685
for index in self.selected_lines(&range) {
686
if matches!(self.lines[index], LineKind::Indent(_)) {
687
self.lines[index] = LineKind::Text;
688
}
689
}
690
}
691
692
fn set_exclusive(&mut self, range: Range<usize>, marker: &MarkKind, value: Option<MarkKind>) {
693
self.journal = Journal::default();
694
self.remove_marks(range.clone(), marker);
695
if let Some(kind) = value {
585
696
for part in self.content_parts(range) {
586
self.add_mark(part, MarkKind::Size(step));
697
self.add_mark(part, kind.clone());
587
698
}
588
699
}
589
700
}
@@ -773,7 +884,13 @@ impl Draft {
773
884
self.splice(content.clone(), "", &[]);
774
885
Some(self.set_line_kind(index, LineKind::Code(language), None, content.start))
775
886
}
776
LineKind::Heading(_) | LineKind::Table(_) => None,
887
LineKind::Heading(_) | LineKind::Table(_) | LineKind::Rule => None,
888
LineKind::Indent(_) if !shift => None,
889
LineKind::Indent(_) => {
890
self.splice(cursor..cursor, "\n", &[]);
891
self.lines[index + 1] = kind;
892
Some(cursor + 1)
893
}
777
894
LineKind::Quote if content.is_empty() && !shift => {
778
895
self.lines[index] = LineKind::Text;
779
896
Some(cursor)
@@ -841,6 +958,11 @@ impl Draft {
841
958
if self.lines[index + 1].is_table() {
842
959
return Some(cursor);
843
960
}
961
if self.lines[index + 1] == LineKind::Rule {
962
let rule = self.line_ranges()[index + 1].clone();
963
self.splice(cursor..rule.end, "", &[]);
964
return Some(self.repair(cursor));
965
}
844
966
let next_marker = self.marker_range(index + 1);
845
967
if next_marker.is_empty() {
846
968
return None;
@@ -856,8 +978,14 @@ impl Draft {
856
978
let kind = self.lines[index].clone();
857
979
let line = self.line_ranges()[index].clone();
858
980
let content = self.content_range(index);
981
if cursor == line.start && index > 0 && self.lines[index - 1] == LineKind::Rule {
982
let rule = self.line_ranges()[index - 1].clone();
983
self.splice(rule.start..line.start, "", &[]);
984
self.lines[index - 1] = kind;
985
return Some(self.repair(rule.start));
986
}
859
987
match &kind {
860
LineKind::Text => None,
988
LineKind::Text | LineKind::Indent(_) | LineKind::Rule => None,
861
989
LineKind::Code(_) => {
862
990
let first_of_block = index == 0 || self.lines[index - 1] != kind;
863
991
(cursor == line.start && first_of_block).then(|| {
@@ -919,6 +1047,85 @@ impl Draft {
919
1047
true
920
1048
}
921
1049
1050
/// Teams' Increase / Decrease indent: list items nest or lift, paragraphs move by one
1051
/// block indent step.
1052
pub fn indent_blocks(&mut self, range: Range<usize>, outdent: bool) {
1053
self.journal = Journal::default();
1054
for index in self.selected_lines(&range) {
1055
let kind = self.lines[index].clone();
1056
let target = match (&kind, outdent) {
1057
(list, _) if list.is_list() => match (outdent, list.depth()) {
1058
(true, 0) => LineKind::Text,
1059
(true, depth) => list.with_depth(depth - 1),
1060
(false, depth) => list.with_depth((depth + 1).min(MAX_DEPTH)),
1061
},
1062
(LineKind::Text, false) => LineKind::Indent(1),
1063
(LineKind::Indent(level), false) => LineKind::Indent((level + 1).min(MAX_INDENT)),
1064
(LineKind::Indent(1), true) => LineKind::Text,
1065
(LineKind::Indent(level), true) => LineKind::Indent(level - 1),
1066
_ => continue,
1067
};
1068
self.set_line_kind(index, target, None, 0);
1069
}
1070
self.repair(0);
1071
}
1072
1073
/// Decrease indent has something to lift: a list item or an indented paragraph.
1074
pub fn can_outdent(&self, range: Range<usize>) -> bool {
1075
self.selected_lines(&range)
1076
.any(|index| self.lines[index].is_list() || matches!(self.lines[index], LineKind::Indent(_)))
1077
}
1078
1079
/// Teams' paragraph style: `None` is Paragraph, otherwise Heading 1 to 3.
1080
pub fn set_heading(&mut self, range: Range<usize>, level: Option<u8>) {
1081
self.journal = Journal::default();
1082
let target = level.map_or(LineKind::Text, |level| {
1083
LineKind::Heading(level.clamp(1, MAX_HEADING))
1084
});
1085
for index in self.selected_lines(&range) {
1086
let current = &self.lines[index];
1087
if current.object_mark().is_some() || matches!(current, LineKind::Code(_)) {
1088
continue;
1089
}
1090
if *current != target {
1091
self.set_line_kind(index, target.clone(), None, 0);
1092
}
1093
}
1094
self.repair(0);
1095
}
1096
1097
/// The paragraph style of the cursor's line: `None` for Paragraph.
1098
pub fn heading_at(&self, offset: usize) -> Option<u8> {
1099
match self.lines[self.line_at(offset)] {
1100
LineKind::Heading(level) => Some(level),
1101
_ => None,
1102
}
1103
}
1104
1105
/// The rule goes in place of an empty text line, otherwise below the cursor's line; the
1106
/// cursor goes to the text line after it, added when the rule ends the draft.
1107
pub fn insert_rule(&mut self, cursor: usize) -> usize {
1108
self.journal = Journal::default();
1109
let index = self.line_at(cursor);
1110
let line = self.line_ranges()[index].clone();
1111
let mark = RULE_MARK.to_string();
1112
let replaces_line = self.lines[index] == LineKind::Text && line.is_empty();
1113
let rule_index = if replaces_line {
1114
self.splice(line, &mark, &[]);
1115
index
1116
} else {
1117
self.splice(line.end..line.end, &format!("\n{mark}"), &[]);
1118
index + 1
1119
};
1120
self.lines[rule_index] = LineKind::Rule;
1121
if rule_index + 1 == self.lines.len() {
1122
let end = self.text.len();
1123
self.splice(end..end, "\n", &[]);
1124
self.lines[rule_index + 1] = LineKind::Text;
1125
}
1126
self.line_ranges()[rule_index + 1].start
1127
}
1128
922
1129
/// All selected lines `kind` already: back to text. Otherwise all become `kind`.
923
1130
pub fn toggle_lines(&mut self, range: Range<usize>, kind: LineKind) {
924
1131
self.journal = Journal::default();
@@ -1220,6 +1427,17 @@ impl Draft {
1220
1427
html.push_str(&format!("<h{level}>{inline}</h{level}>"));
1221
1428
}
1222
1429
}
1430
LineKind::Indent(_) => {
1431
for line in run {
1432
let level = match line.kind {
1433
LineKind::Indent(level) => u32::from(level.clamp(1, MAX_INDENT)),
1434
_ => 1,
1435
};
1436
let inline = inline_html(&line.content, &line.marks);
1437
let margin = level * INDENT_PIXELS;
1438
html.push_str(&format!("<p style=\"margin-left:{margin}px;\">{inline}</p>"));
1439
}
1440
}
1223
1441
LineKind::Table(_) => {
1224
1442
for line in run {
1225
1443
if let LineKind::Table(table) = &line.kind {
@@ -1227,21 +1445,20 @@ impl Draft {
1227
1445
}
1228
1446
}
1229
1447
}
1448
LineKind::Rule => html.push_str(&RULE_HTML.repeat(run.len())),
1230
1449
LineKind::Code(language) => {
1231
match language {
1232
Some(language) => html.push_str(&format!(
1233
"<pre class=\"language-{}\">",
1234
escape_html(language)
1235
)),
1236
None => html.push_str("<pre>"),
1237
}
1450
let language = language.as_deref().unwrap_or(PLAIN_LANGUAGE);
1451
html.push_str(&format!(
1452
"<pre class=\"language-{} skipProofing\" spellcheck=\"false\"><code>",
1453
escape_html(&language.to_ascii_lowercase())
1454
));
1238
1455
let code = run
1239
1456
.iter()
1240
1457
.map(|line| escape_html(&line.content))
1241
1458
.collect::<Vec<_>>()
1242
.join("\n");
1459
.join("<br>");
1243
1460
html.push_str(&code);
1244
html.push_str("</pre>");
1461
html.push_str("</code></pre>");
1245
1462
}
1246
1463
_ => html.push_str(&list_html(run)),
1247
1464
}
@@ -1532,36 +1749,43 @@ impl Draft {
1532
1749
}
1533
1750
}
1534
1751
1535
/// A table line holds its mark alone: text typed next to it moves to its own line, a mark
1536
/// without its table is dropped and a table without its mark becomes text.
1537
fn repair_tables(&mut self, mut cursor: usize) -> usize {
1538
let mark_length = TABLE_MARK.len_utf8();
1752
/// A table or rule line holds its mark alone: text typed next to it moves to its own
1753
/// line, a mark without its line kind is dropped and a line without its mark becomes text.
1754
fn repair_objects(&mut self, mut cursor: usize) -> usize {
1539
1755
let mut index = 0;
1540
1756
while index < self.lines.len() {
1541
1757
let line = self.line_ranges()[index].clone();
1542
let found = self.text[line.clone()].find(TABLE_MARK);
1543
match (self.lines[index].clone(), found) {
1544
(LineKind::Table(_), None) => self.lines[index] = LineKind::Text,
1545
(LineKind::Table(table), Some(at)) if at > 0 => {
1758
let kind = self.lines[index].clone();
1759
let expected = kind.object_mark();
1760
let stray = self.text[line.clone()].char_indices().find(|(_, character)| {
1761
[TABLE_MARK, RULE_MARK].contains(character) && Some(*character) != expected
1762
});
1763
if let Some((at, character)) = stray {
1764
let mark = line.start + at..line.start + at + character.len_utf8();
1765
self.splice(mark.clone(), "", &[]);
1766
cursor = map_offset(&[(mark, String::new())], cursor);
1767
continue;
1768
}
1769
let Some(object_mark) = expected else {
1770
index += 1;
1771
continue;
1772
};
1773
let mark_length = object_mark.len_utf8();
1774
match self.text[line.clone()].find(object_mark) {
1775
None => self.lines[index] = LineKind::Text,
1776
Some(at) if at > 0 => {
1546
1777
let split = line.start + at;
1547
1778
self.splice(split..split, "\n", &[]);
1548
1779
self.lines[index] = LineKind::Text;
1549
self.lines[index + 1] = LineKind::Table(table);
1780
self.lines[index + 1] = kind;
1550
1781
cursor += usize::from(cursor > split);
1551
1782
}
1552
(LineKind::Table(_), Some(_)) if line.len() > mark_length => {
1783
Some(_) if line.len() > mark_length => {
1553
1784
let split = line.start + mark_length;
1554
1785
self.splice(split..split, "\n", &[]);
1555
1786
cursor += usize::from(cursor > split);
1556
1787
}
1557
(LineKind::Table(_), Some(_)) => {}
1558
(_, Some(at)) => {
1559
let mark = line.start + at..line.start + at + mark_length;
1560
self.splice(mark.clone(), "", &[]);
1561
cursor = map_offset(&[(mark, String::new())], cursor);
1562
continue;
1563
}
1564
(_, None) => {}
1788
Some(_) => {}
1565
1789
}
1566
1790
index += 1;
1567
1791
}
@@ -1570,7 +1794,7 @@ impl Draft {
1570
1794
1571
1795
/// List items whose marker was edited away become text; numbered items are renumbered.
1572
1796
fn repair(&mut self, cursor: usize) -> usize {
1573
let mut cursor = self.repair_tables(cursor);
1797
let mut cursor = self.repair_objects(cursor);
1574
1798
for index in 0..self.lines.len() {
1575
1799
let kind = self.lines[index].clone();
1576
1800
if !kind.is_list() {
@@ -1594,6 +1818,10 @@ impl Draft {
1594
1818
}
1595
1819
}
1596
1820
1821
fn hex_color(color: u32) -> String {
1822
format!("#{:06X}", color & 0xFF_FFFF)
1823
}
1824
1597
1825
fn overlaps(left: &Range<usize>, right: &Range<usize>) -> bool {
1598
1826
left.start < right.end && right.start < left.end
1599
1827
}
@@ -1607,10 +1835,12 @@ fn marker_text(kind: &LineKind, number: u32) -> String {
1607
1835
LineKind::Bullet(depth) => bullet_marker(*depth),
1608
1836
LineKind::Numbered(_) => format!("{number}. "),
1609
1837
LineKind::Text
1838
| LineKind::Indent(_)
1610
1839
| LineKind::Quote
1611
1840
| LineKind::Code(_)
1612
1841
| LineKind::Heading(_)
1613
| LineKind::Table(_) => String::new(),
1842
| LineKind::Table(_)
1843
| LineKind::Rule => String::new(),
1614
1844
}
1615
1845
}
1616
1846
@@ -2160,6 +2390,8 @@ impl SpanLines {
2160
2390
| Span::CodeBlock { .. }
2161
2391
| Span::Heading { .. }
2162
2392
| Span::Table { .. }
2393
| Span::Rule
2394
| Span::Indent { .. }
2163
2395
)
2164
2396
);
2165
2397
match span {
@@ -2179,7 +2411,16 @@ impl SpanLines {
2179
2411
self.walk(children, kind, &with(MarkKind::Size(SizeStep::Large)))
2180
2412
}
2181
2413
Span::Sized(_, children) => self.walk(children, kind, marks),
2182
Span::Colored { children, .. } => self.walk(children, kind, marks),
2414
Span::Colored {
2415
color,
2416
background,
2417
children,
2418
} => {
2419
let mut colored = marks.to_vec();
2420
colored.extend(color.map(MarkKind::Color));
2421
colored.extend(background.map(MarkKind::Highlight));
2422
self.walk(children, kind, &colored)
2423
}
2183
2424
Span::Code(text) => self.append(text, kind, &with(MarkKind::Code)),
2184
2425
Span::Link { url, children } => {
2185
2426
self.walk(children, kind, &with(MarkKind::Link(url.clone())))
@@ -2187,10 +2428,31 @@ impl SpanLines {
2187
2428
Span::Mention { name, .. } => {
2188
2429
self.append(&format!("@{}", name.trim_start_matches('@')), kind, marks)
2189
2430
}
2431
Span::Rule if *kind == LineKind::Text => {
2432
self.lines.push(DraftLine {
2433
kind: LineKind::Rule,
2434
number: None,
2435
content: RULE_MARK.to_string(),
2436
marks: Vec::new(),
2437
});
2438
self.open = false;
2439
}
2440
Span::Indent { level, children }
2441
if *kind == LineKind::Text
2442
&& !children
2443
.iter()
2444
.any(|child| matches!(child, Span::Heading { .. })) =>
2445
{
2446
let indent = LineKind::Indent((*level).clamp(1, MAX_INDENT));
2447
self.start_line(&indent, None);
2448
self.walk(children, &indent, marks);
2449
self.open = false;
2450
}
2451
Span::Indent { children, .. } => self.walk(children, kind, marks),
2190
2452
Span::LineBreak | Span::Rule if !self.open || block_follows => {}
2191
2453
Span::LineBreak | Span::Rule => {
2192
2454
let continued = match kind {
2193
LineKind::Quote | LineKind::Code(_) => kind.clone(),
2455
LineKind::Quote | LineKind::Code(_) | LineKind::Indent(_) => kind.clone(),
2194
2456
_ => LineKind::Text,
2195
2457
};
2196
2458
self.start_line(&continued, None);
@@ -2707,7 +2969,7 @@ mod tests {
2707
2969
assert_eq!(draft.lines()[1], LineKind::Text);
2708
2970
assert_eq!(
2709
2971
draft.to_html(),
2710
"<pre class=\"language-rust\">fn x() {}</pre>"
2972
"<pre class=\"language-rust skipProofing\" spellcheck=\"false\"><code>fn x() {}</code></pre>"
2711
2973
);
2712
2974
}
2713
2975
@@ -2742,7 +3004,7 @@ mod tests {
2742
3004
<blockquote>q1<br>q2</blockquote>\
2743
3005
<ul><li>a<ul><li>b</li></ul></li></ul>\
2744
3006
<ol><li>x</li><li>y</li></ol>\
2745
<pre class=\"language-py\">print(1)</pre>"
3007
<pre class=\"language-py skipProofing\" spellcheck=\"false\"><code>print(1)</code></pre>"
2746
3008
);
2747
3009
}
2748
3010
@@ -2947,7 +3209,7 @@ mod tests {
2947
3209
fn code_lines_hold_only_their_content() {
2948
3210
let mut draft = Draft::from_markdown("```\nlet a = 1;\n\u{2003}b\n```");
2949
3211
assert_eq!(draft.text(), "let a = 1;\n\u{2003}b");
2950
assert_eq!(draft.to_html(), "<pre>let a = 1;\n\u{2003}b</pre>");
3212
assert_eq!(draft.to_html(), "<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>let a = 1;<br>\u{2003}b</code></pre>");
2951
3213
assert_eq!(draft.backspace_at_start(draft.line_ranges()[1].start), None);
2952
3214
assert_eq!(draft.backspace_at_start(0), Some(0));
2953
3215
assert_eq!(draft.lines()[0], LineKind::Text);
@@ -2972,12 +3234,12 @@ mod tests {
2972
3234
draft.apply_edit(&next, cursor + pasted.len(), None);
2973
3235
assert_eq!(
2974
3236
draft.to_html(),
2975
"<pre class=\"language-py\">def f():\n return 1</pre>"
3237
"<pre class=\"language-py skipProofing\" spellcheck=\"false\"><code>def f():<br> return 1</code></pre>"
2976
3238
);
2977
3239
let mut split = Draft::from_markdown("```\n a b\n```");
2978
3240
let after_a = " a".len();
2979
3241
split.break_line(after_a, false).unwrap();
2980
assert_eq!(split.to_html(), "<pre> a\n b</pre>");
3242
assert_eq!(split.to_html(), "<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code> a<br> b</code></pre>");
2981
3243
}
2982
3244
2983
3245
#[test]
@@ -11,12 +11,17 @@ use crate::table::{TABLE_MARK, Table, markdown_table};11
pub const MAX_DEPTH: u8 = 2;11
pub const MAX_DEPTH: u8 = 2;12
pub const MAX_HEADING: u8 = 3;12
pub const MAX_HEADING: u8 = 3;13
pub const OBJECT_MARK: char = '\u{FFFC}';13
pub const OBJECT_MARK: char = '\u{FFFC}';14
pub const RULE_MARK: char = '\u{FFFA}';15
pub const MAX_INDENT: u8 = 8;16
pub const INDENT_PIXELS: u32 = 40;17
pub const RULE_HTML: &str = "<hr>";14
const BULLETS: [&str; 3] = ["•", "◦", "▪"];18
const BULLETS: [&str; 3] = ["•", "◦", "▪"];15
const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "];19
const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "];16
const LINK_SCHEMES: [&str; 3] = ["http://", "https://", "mailto:"];20
const LINK_SCHEMES: [&str; 3] = ["http://", "https://", "mailto:"];17
const AUTOLINK_PREFIXES: [&str; 4] = ["http://", "https://", "www.", "mailto:"];21
const AUTOLINK_PREFIXES: [&str; 4] = ["http://", "https://", "www.", "mailto:"];18
const AUTOLINK_TRAILING: &str = ".,;:!?'\"";22
const AUTOLINK_TRAILING: &str = ".,;:!?'\"";19
const FENCE: &str = "```";23
const FENCE: &str = "```";24
const PLAIN_LANGUAGE: &str = "plaintext";20
const MARKDOWN_INDENT: usize = 2;25
const MARKDOWN_INDENT: usize = 2;21
26
22
static TYPED_LINK: LazyLock<Regex> =27
static TYPED_LINK: LazyLock<Regex> =@@ -49,6 +54,8 @@ pub enum MarkKind {49
Superscript,54
Superscript,50
Subscript,55
Subscript,51
Size(SizeStep),56
Size(SizeStep),57
Color(u32),58
Highlight(u32),52
Code,59
Code,53
}60
}54
61
@@ -60,6 +67,8 @@ impl MarkKind {60
fn covers(&self, other: &MarkKind) -> bool {67
fn covers(&self, other: &MarkKind) -> bool {61
match (self, other) {68
match (self, other) {62
(MarkKind::Size(left), MarkKind::Size(right)) => left == right,69
(MarkKind::Size(left), MarkKind::Size(right)) => left == right,70
(MarkKind::Color(left), MarkKind::Color(right)) => left == right,71
(MarkKind::Highlight(left), MarkKind::Highlight(right)) => left == right,63
_ => self.same_format(other),72
_ => self.same_format(other),64
}73
}65
}74
}@@ -82,6 +91,8 @@ impl MarkKind {82
| MarkKind::Superscript91
| MarkKind::Superscript83
| MarkKind::Subscript92
| MarkKind::Subscript84
| MarkKind::Size(_)93
| MarkKind::Size(_)94
| MarkKind::Color(_)95
| MarkKind::Highlight(_)85
)96
)86
}97
}87
98
@@ -95,6 +106,10 @@ impl MarkKind {95
MarkKind::Superscript => "<sup>".to_owned(),106
MarkKind::Superscript => "<sup>".to_owned(),96
MarkKind::Subscript => "<sub>".to_owned(),107
MarkKind::Subscript => "<sub>".to_owned(),97
MarkKind::Size(step) => format!("<span style=\"font-size:{};\">", step.css()),108
MarkKind::Size(step) => format!("<span style=\"font-size:{};\">", step.css()),109
MarkKind::Color(color) => format!("<span style=\"color:{};\">", hex_color(*color)),110
MarkKind::Highlight(color) => {111
format!("<span style=\"background-color:{};\">", hex_color(*color))112
}98
MarkKind::Code => "<code>".to_owned(),113
MarkKind::Code => "<code>".to_owned(),99
}114
}100
}115
}@@ -108,7 +123,7 @@ impl MarkKind {108
MarkKind::Strike => "</s>",123
MarkKind::Strike => "</s>",109
MarkKind::Superscript => "</sup>",124
MarkKind::Superscript => "</sup>",110
MarkKind::Subscript => "</sub>",125
MarkKind::Subscript => "</sub>",111
MarkKind::Size(_) => "</span>",126
MarkKind::Size(_) | MarkKind::Color(_) | MarkKind::Highlight(_) => "</span>",112
MarkKind::Code => "</code>",127
MarkKind::Code => "</code>",113
}128
}114
}129
}@@ -123,12 +138,14 @@ pub struct Mark {123
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]138
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]124
pub enum LineKind {139
pub enum LineKind {125
Text,140
Text,141
Indent(u8),126
Bullet(u8),142
Bullet(u8),127
Numbered(u8),143
Numbered(u8),128
Quote,144
Quote,129
Code(Option<String>),145
Code(Option<String>),130
Heading(u8),146
Heading(u8),131
Table(Table),147
Table(Table),148
Rule,132
}149
}133
150
134
impl LineKind {151
impl LineKind {@@ -140,6 +157,15 @@ impl LineKind {140
matches!(self, LineKind::Table(_))157
matches!(self, LineKind::Table(_))141
}158
}142
159
160
/// A line that holds one object mark alone: a table or a horizontal rule.161
pub fn object_mark(&self) -> Option<char> {162
match self {163
LineKind::Table(_) => Some(TABLE_MARK),164
LineKind::Rule => Some(RULE_MARK),165
_ => None,166
}167
}168
143
pub fn depth(&self) -> u8 {169
pub fn depth(&self) -> u8 {144
match self {170
match self {145
LineKind::Bullet(depth) | LineKind::Numbered(depth) => *depth,171
LineKind::Bullet(depth) | LineKind::Numbered(depth) => *depth,@@ -216,15 +242,44 @@ impl TypingStyle {216
242
217
/// `None` is the normal size.243
/// `None` is the normal size.218
pub fn set_size(&mut self, size: Option<SizeStep>, active: &[MarkKind]) {244
pub fn set_size(&mut self, size: Option<SizeStep>, active: &[MarkKind]) {219
let marker = MarkKind::Size(SizeStep::Small);245
self.set_exclusive(246
MarkKind::Size(SizeStep::Small),247
size.map(MarkKind::Size),248
active,249
);250
}251
252
/// `None` is Automatic.253
pub fn set_color(&mut self, color: Option<u32>, active: &[MarkKind]) {254
self.set_exclusive(MarkKind::Color(0), color.map(MarkKind::Color), active);255
}256
257
/// `None` is No highlight.258
pub fn set_highlight(&mut self, color: Option<u32>, active: &[MarkKind]) {259
self.set_exclusive(260
MarkKind::Highlight(0),261
color.map(MarkKind::Highlight),262
active,263
);264
}265
266
/// Text typed next drops every format but a link.267
pub fn clear(&mut self, active: &[MarkKind]) {268
self.add.clear();269
self.remove = active270
.iter()271
.filter(|kind| !matches!(kind, MarkKind::Link(_)))272
.cloned()273
.collect();274
}275
276
fn set_exclusive(&mut self, marker: MarkKind, value: Option<MarkKind>, active: &[MarkKind]) {220
self.add.retain(|added| !added.same_format(&marker));277
self.add.retain(|added| !added.same_format(&marker));221
self.remove.retain(|removed| !removed.same_format(&marker));278
self.remove.retain(|removed| !removed.same_format(&marker));222
if active.iter().any(|existing| existing.same_format(&marker)) {279
if active.iter().any(|existing| existing.same_format(&marker)) {223
self.remove.push(marker);280
self.remove.push(marker);224
}281
}225
if let Some(step) = size {282
self.add.extend(value);226
self.add.push(MarkKind::Size(step));227
}228
}283
}229
284
230
pub fn is_empty(&self) -> bool {285
pub fn is_empty(&self) -> bool {@@ -440,6 +495,7 @@ impl Draft {440
.into_iter()495
.into_iter()441
.map(|line| match &line.kind {496
.map(|line| match &line.kind {442
LineKind::Table(table) => table.plain_text(),497
LineKind::Table(table) => table.plain_text(),498
LineKind::Rule => String::new(),443
_ => line.content,499
_ => line.content,444
})500
})445
.collect::<Vec<_>>()501
.collect::<Vec<_>>()@@ -579,11 +635,66 @@ impl Draft {579
635
580
/// `None` is the normal size: any size mark on `range` is removed.636
/// `None` is the normal size: any size mark on `range` is removed.581
pub fn set_size(&mut self, range: Range<usize>, size: Option<SizeStep>) {637
pub fn set_size(&mut self, range: Range<usize>, size: Option<SizeStep>) {638
self.set_exclusive(639
range,640
&MarkKind::Size(SizeStep::Small),641
size.map(MarkKind::Size),642
);643
}644
645
/// `None` is Automatic: the font colour on `range` is removed.646
pub fn set_color(&mut self, range: Range<usize>, color: Option<u32>) {647
self.set_exclusive(range, &MarkKind::Color(0), color.map(MarkKind::Color));648
}649
650
/// `None` is No highlight.651
pub fn set_highlight(&mut self, range: Range<usize>, color: Option<u32>) {652
self.set_exclusive(653
range,654
&MarkKind::Highlight(0),655
color.map(MarkKind::Highlight),656
);657
}658
659
/// The colour of `marker`'s kind that covers all of `range`.660
pub fn color_in(&self, range: Range<usize>, marker: &MarkKind) -> Option<u32> {661
self.marks662
.iter()663
.filter(|mark| mark.kind.same_format(marker))664
.find(|mark| self.state(range.clone(), &mark.kind) == FormatState::On)665
.and_then(|mark| match mark.kind {666
MarkKind::Color(color) | MarkKind::Highlight(color) => Some(color),667
_ => None,668
})669
}670
671
/// Teams' Clear all formatting: every inline format but links, and the block indent.672
pub fn clear_formatting(&mut self, range: Range<usize>) {582
self.journal = Journal::default();673
self.journal = Journal::default();583
self.remove_marks(range.clone(), &MarkKind::Size(SizeStep::Small));674
let kinds: Vec<MarkKind> = self584
if let Some(step) = size {675
.marks676
.iter()677
.filter(|mark| {678
!matches!(mark.kind, MarkKind::Link(_)) && overlaps(&mark.range, &range)679
})680
.map(|mark| mark.kind.clone())681
.collect();682
for kind in kinds {683
self.remove_marks(range.clone(), &kind);684
}685
for index in self.selected_lines(&range) {686
if matches!(self.lines[index], LineKind::Indent(_)) {687
self.lines[index] = LineKind::Text;688
}689
}690
}691
692
fn set_exclusive(&mut self, range: Range<usize>, marker: &MarkKind, value: Option<MarkKind>) {693
self.journal = Journal::default();694
self.remove_marks(range.clone(), marker);695
if let Some(kind) = value {585
for part in self.content_parts(range) {696
for part in self.content_parts(range) {586
self.add_mark(part, MarkKind::Size(step));697
self.add_mark(part, kind.clone());587
}698
}588
}699
}589
}700
}@@ -773,7 +884,13 @@ impl Draft {773
self.splice(content.clone(), "", &[]);884
self.splice(content.clone(), "", &[]);774
Some(self.set_line_kind(index, LineKind::Code(language), None, content.start))885
Some(self.set_line_kind(index, LineKind::Code(language), None, content.start))775
}886
}776
LineKind::Heading(_) | LineKind::Table(_) => None,887
LineKind::Heading(_) | LineKind::Table(_) | LineKind::Rule => None,888
LineKind::Indent(_) if !shift => None,889
LineKind::Indent(_) => {890
self.splice(cursor..cursor, "\n", &[]);891
self.lines[index + 1] = kind;892
Some(cursor + 1)893
}777
LineKind::Quote if content.is_empty() && !shift => {894
LineKind::Quote if content.is_empty() && !shift => {778
self.lines[index] = LineKind::Text;895
self.lines[index] = LineKind::Text;779
Some(cursor)896
Some(cursor)@@ -841,6 +958,11 @@ impl Draft {841
if self.lines[index + 1].is_table() {958
if self.lines[index + 1].is_table() {842
return Some(cursor);959
return Some(cursor);843
}960
}961
if self.lines[index + 1] == LineKind::Rule {962
let rule = self.line_ranges()[index + 1].clone();963
self.splice(cursor..rule.end, "", &[]);964
return Some(self.repair(cursor));965
}844
let next_marker = self.marker_range(index + 1);966
let next_marker = self.marker_range(index + 1);845
if next_marker.is_empty() {967
if next_marker.is_empty() {846
return None;968
return None;@@ -856,8 +978,14 @@ impl Draft {856
let kind = self.lines[index].clone();978
let kind = self.lines[index].clone();857
let line = self.line_ranges()[index].clone();979
let line = self.line_ranges()[index].clone();858
let content = self.content_range(index);980
let content = self.content_range(index);981
if cursor == line.start && index > 0 && self.lines[index - 1] == LineKind::Rule {982
let rule = self.line_ranges()[index - 1].clone();983
self.splice(rule.start..line.start, "", &[]);984
self.lines[index - 1] = kind;985
return Some(self.repair(rule.start));986
}859
match &kind {987
match &kind {860
LineKind::Text => None,988
LineKind::Text | LineKind::Indent(_) | LineKind::Rule => None,861
LineKind::Code(_) => {989
LineKind::Code(_) => {862
let first_of_block = index == 0 || self.lines[index - 1] != kind;990
let first_of_block = index == 0 || self.lines[index - 1] != kind;863
(cursor == line.start && first_of_block).then(|| {991
(cursor == line.start && first_of_block).then(|| {@@ -919,6 +1047,85 @@ impl Draft {919
true1047
true920
}1048
}921
1049
1050
/// Teams' Increase / Decrease indent: list items nest or lift, paragraphs move by one1051
/// block indent step.1052
pub fn indent_blocks(&mut self, range: Range<usize>, outdent: bool) {1053
self.journal = Journal::default();1054
for index in self.selected_lines(&range) {1055
let kind = self.lines[index].clone();1056
let target = match (&kind, outdent) {1057
(list, _) if list.is_list() => match (outdent, list.depth()) {1058
(true, 0) => LineKind::Text,1059
(true, depth) => list.with_depth(depth - 1),1060
(false, depth) => list.with_depth((depth + 1).min(MAX_DEPTH)),1061
},1062
(LineKind::Text, false) => LineKind::Indent(1),1063
(LineKind::Indent(level), false) => LineKind::Indent((level + 1).min(MAX_INDENT)),1064
(LineKind::Indent(1), true) => LineKind::Text,1065
(LineKind::Indent(level), true) => LineKind::Indent(level - 1),1066
_ => continue,1067
};1068
self.set_line_kind(index, target, None, 0);1069
}1070
self.repair(0);1071
}1072
1073
/// Decrease indent has something to lift: a list item or an indented paragraph.1074
pub fn can_outdent(&self, range: Range<usize>) -> bool {1075
self.selected_lines(&range)1076
.any(|index| self.lines[index].is_list() || matches!(self.lines[index], LineKind::Indent(_)))1077
}1078
1079
/// Teams' paragraph style: `None` is Paragraph, otherwise Heading 1 to 3.1080
pub fn set_heading(&mut self, range: Range<usize>, level: Option<u8>) {1081
self.journal = Journal::default();1082
let target = level.map_or(LineKind::Text, |level| {1083
LineKind::Heading(level.clamp(1, MAX_HEADING))1084
});1085
for index in self.selected_lines(&range) {1086
let current = &self.lines[index];1087
if current.object_mark().is_some() || matches!(current, LineKind::Code(_)) {1088
continue;1089
}1090
if *current != target {1091
self.set_line_kind(index, target.clone(), None, 0);1092
}1093
}1094
self.repair(0);1095
}1096
1097
/// The paragraph style of the cursor's line: `None` for Paragraph.1098
pub fn heading_at(&self, offset: usize) -> Option<u8> {1099
match self.lines[self.line_at(offset)] {1100
LineKind::Heading(level) => Some(level),1101
_ => None,1102
}1103
}1104
1105
/// The rule goes in place of an empty text line, otherwise below the cursor's line; the1106
/// cursor goes to the text line after it, added when the rule ends the draft.1107
pub fn insert_rule(&mut self, cursor: usize) -> usize {1108
self.journal = Journal::default();1109
let index = self.line_at(cursor);1110
let line = self.line_ranges()[index].clone();1111
let mark = RULE_MARK.to_string();1112
let replaces_line = self.lines[index] == LineKind::Text && line.is_empty();1113
let rule_index = if replaces_line {1114
self.splice(line, &mark, &[]);1115
index1116
} else {1117
self.splice(line.end..line.end, &format!("\n{mark}"), &[]);1118
index + 11119
};1120
self.lines[rule_index] = LineKind::Rule;1121
if rule_index + 1 == self.lines.len() {1122
let end = self.text.len();1123
self.splice(end..end, "\n", &[]);1124
self.lines[rule_index + 1] = LineKind::Text;1125
}1126
self.line_ranges()[rule_index + 1].start1127
}1128
922
/// All selected lines `kind` already: back to text. Otherwise all become `kind`.1129
/// All selected lines `kind` already: back to text. Otherwise all become `kind`.923
pub fn toggle_lines(&mut self, range: Range<usize>, kind: LineKind) {1130
pub fn toggle_lines(&mut self, range: Range<usize>, kind: LineKind) {924
self.journal = Journal::default();1131
self.journal = Journal::default();@@ -1220,6 +1427,17 @@ impl Draft {1220
html.push_str(&format!("<h{level}>{inline}</h{level}>"));1427
html.push_str(&format!("<h{level}>{inline}</h{level}>"));1221
}1428
}1222
}1429
}1430
LineKind::Indent(_) => {1431
for line in run {1432
let level = match line.kind {1433
LineKind::Indent(level) => u32::from(level.clamp(1, MAX_INDENT)),1434
_ => 1,1435
};1436
let inline = inline_html(&line.content, &line.marks);1437
let margin = level * INDENT_PIXELS;1438
html.push_str(&format!("<p style=\"margin-left:{margin}px;\">{inline}</p>"));1439
}1440
}1223
LineKind::Table(_) => {1441
LineKind::Table(_) => {1224
for line in run {1442
for line in run {1225
if let LineKind::Table(table) = &line.kind {1443
if let LineKind::Table(table) = &line.kind {@@ -1227,21 +1445,20 @@ impl Draft {1227
}1445
}1228
}1446
}1229
}1447
}1448
LineKind::Rule => html.push_str(&RULE_HTML.repeat(run.len())),1230
LineKind::Code(language) => {1449
LineKind::Code(language) => {1231
match language {1450
let language = language.as_deref().unwrap_or(PLAIN_LANGUAGE);1232
Some(language) => html.push_str(&format!(1451
html.push_str(&format!(1233
"<pre class=\"language-{}\">",1452
"<pre class=\"language-{} skipProofing\" spellcheck=\"false\"><code>",1234
escape_html(language)1453
escape_html(&language.to_ascii_lowercase())1235
)),1454
));1236
None => html.push_str("<pre>"),1237
}1238
let code = run1455
let code = run1239
.iter()1456
.iter()1240
.map(|line| escape_html(&line.content))1457
.map(|line| escape_html(&line.content))1241
.collect::<Vec<_>>()1458
.collect::<Vec<_>>()1242
.join("\n");1459
.join("<br>");1243
html.push_str(&code);1460
html.push_str(&code);1244
html.push_str("</pre>");1461
html.push_str("</code></pre>");1245
}1462
}1246
_ => html.push_str(&list_html(run)),1463
_ => html.push_str(&list_html(run)),1247
}1464
}@@ -1532,36 +1749,43 @@ impl Draft {1532
}1749
}1533
}1750
}1534
1751
1535
/// A table line holds its mark alone: text typed next to it moves to its own line, a mark1752
/// A table or rule line holds its mark alone: text typed next to it moves to its own1536
/// without its table is dropped and a table without its mark becomes text.1753
/// line, a mark without its line kind is dropped and a line without its mark becomes text.1537
fn repair_tables(&mut self, mut cursor: usize) -> usize {1754
fn repair_objects(&mut self, mut cursor: usize) -> usize {1538
let mark_length = TABLE_MARK.len_utf8();1539
let mut index = 0;1755
let mut index = 0;1540
while index < self.lines.len() {1756
while index < self.lines.len() {1541
let line = self.line_ranges()[index].clone();1757
let line = self.line_ranges()[index].clone();1542
let found = self.text[line.clone()].find(TABLE_MARK);1758
let kind = self.lines[index].clone();1543
match (self.lines[index].clone(), found) {1759
let expected = kind.object_mark();1544
(LineKind::Table(_), None) => self.lines[index] = LineKind::Text,1760
let stray = self.text[line.clone()].char_indices().find(|(_, character)| {1545
(LineKind::Table(table), Some(at)) if at > 0 => {1761
[TABLE_MARK, RULE_MARK].contains(character) && Some(*character) != expected1762
});1763
if let Some((at, character)) = stray {1764
let mark = line.start + at..line.start + at + character.len_utf8();1765
self.splice(mark.clone(), "", &[]);1766
cursor = map_offset(&[(mark, String::new())], cursor);1767
continue;1768
}1769
let Some(object_mark) = expected else {1770
index += 1;1771
continue;1772
};1773
let mark_length = object_mark.len_utf8();1774
match self.text[line.clone()].find(object_mark) {1775
None => self.lines[index] = LineKind::Text,1776
Some(at) if at > 0 => {1546
let split = line.start + at;1777
let split = line.start + at;1547
self.splice(split..split, "\n", &[]);1778
self.splice(split..split, "\n", &[]);1548
self.lines[index] = LineKind::Text;1779
self.lines[index] = LineKind::Text;1549
self.lines[index + 1] = LineKind::Table(table);1780
self.lines[index + 1] = kind;1550
cursor += usize::from(cursor > split);1781
cursor += usize::from(cursor > split);1551
}1782
}1552
(LineKind::Table(_), Some(_)) if line.len() > mark_length => {1783
Some(_) if line.len() > mark_length => {1553
let split = line.start + mark_length;1784
let split = line.start + mark_length;1554
self.splice(split..split, "\n", &[]);1785
self.splice(split..split, "\n", &[]);1555
cursor += usize::from(cursor > split);1786
cursor += usize::from(cursor > split);1556
}1787
}1557
(LineKind::Table(_), Some(_)) => {}1788
Some(_) => {}1558
(_, Some(at)) => {1559
let mark = line.start + at..line.start + at + mark_length;1560
self.splice(mark.clone(), "", &[]);1561
cursor = map_offset(&[(mark, String::new())], cursor);1562
continue;1563
}1564
(_, None) => {}1565
}1789
}1566
index += 1;1790
index += 1;1567
}1791
}@@ -1570,7 +1794,7 @@ impl Draft {1570
1794
1571
/// List items whose marker was edited away become text; numbered items are renumbered.1795
/// List items whose marker was edited away become text; numbered items are renumbered.1572
fn repair(&mut self, cursor: usize) -> usize {1796
fn repair(&mut self, cursor: usize) -> usize {1573
let mut cursor = self.repair_tables(cursor);1797
let mut cursor = self.repair_objects(cursor);1574
for index in 0..self.lines.len() {1798
for index in 0..self.lines.len() {1575
let kind = self.lines[index].clone();1799
let kind = self.lines[index].clone();1576
if !kind.is_list() {1800
if !kind.is_list() {@@ -1594,6 +1818,10 @@ impl Draft {1594
}1818
}1595
}1819
}1596
1820
1821
fn hex_color(color: u32) -> String {1822
format!("#{:06X}", color & 0xFF_FFFF)1823
}1824
1597
fn overlaps(left: &Range<usize>, right: &Range<usize>) -> bool {1825
fn overlaps(left: &Range<usize>, right: &Range<usize>) -> bool {1598
left.start < right.end && right.start < left.end1826
left.start < right.end && right.start < left.end1599
}1827
}@@ -1607,10 +1835,12 @@ fn marker_text(kind: &LineKind, number: u32) -> String {1607
LineKind::Bullet(depth) => bullet_marker(*depth),1835
LineKind::Bullet(depth) => bullet_marker(*depth),1608
LineKind::Numbered(_) => format!("{number}. "),1836
LineKind::Numbered(_) => format!("{number}. "),1609
LineKind::Text1837
LineKind::Text1838
| LineKind::Indent(_)1610
| LineKind::Quote1839
| LineKind::Quote1611
| LineKind::Code(_)1840
| LineKind::Code(_)1612
| LineKind::Heading(_)1841
| LineKind::Heading(_)1613
| LineKind::Table(_) => String::new(),1842
| LineKind::Table(_)1843
| LineKind::Rule => String::new(),1614
}1844
}1615
}1845
}1616
1846
@@ -2160,6 +2390,8 @@ impl SpanLines {2160
| Span::CodeBlock { .. }2390
| Span::CodeBlock { .. }2161
| Span::Heading { .. }2391
| Span::Heading { .. }2162
| Span::Table { .. }2392
| Span::Table { .. }2393
| Span::Rule2394
| Span::Indent { .. }2163
)2395
)2164
);2396
);2165
match span {2397
match span {@@ -2179,7 +2411,16 @@ impl SpanLines {2179
self.walk(children, kind, &with(MarkKind::Size(SizeStep::Large)))2411
self.walk(children, kind, &with(MarkKind::Size(SizeStep::Large)))2180
}2412
}2181
Span::Sized(_, children) => self.walk(children, kind, marks),2413
Span::Sized(_, children) => self.walk(children, kind, marks),2182
Span::Colored { children, .. } => self.walk(children, kind, marks),2414
Span::Colored {2415
color,2416
background,2417
children,2418
} => {2419
let mut colored = marks.to_vec();2420
colored.extend(color.map(MarkKind::Color));2421
colored.extend(background.map(MarkKind::Highlight));2422
self.walk(children, kind, &colored)2423
}2183
Span::Code(text) => self.append(text, kind, &with(MarkKind::Code)),2424
Span::Code(text) => self.append(text, kind, &with(MarkKind::Code)),2184
Span::Link { url, children } => {2425
Span::Link { url, children } => {2185
self.walk(children, kind, &with(MarkKind::Link(url.clone())))2426
self.walk(children, kind, &with(MarkKind::Link(url.clone())))@@ -2187,10 +2428,31 @@ impl SpanLines {2187
Span::Mention { name, .. } => {2428
Span::Mention { name, .. } => {2188
self.append(&format!("@{}", name.trim_start_matches('@')), kind, marks)2429
self.append(&format!("@{}", name.trim_start_matches('@')), kind, marks)2189
}2430
}2431
Span::Rule if *kind == LineKind::Text => {2432
self.lines.push(DraftLine {2433
kind: LineKind::Rule,2434
number: None,2435
content: RULE_MARK.to_string(),2436
marks: Vec::new(),2437
});2438
self.open = false;2439
}2440
Span::Indent { level, children }2441
if *kind == LineKind::Text2442
&& !children2443
.iter()2444
.any(|child| matches!(child, Span::Heading { .. })) =>2445
{2446
let indent = LineKind::Indent((*level).clamp(1, MAX_INDENT));2447
self.start_line(&indent, None);2448
self.walk(children, &indent, marks);2449
self.open = false;2450
}2451
Span::Indent { children, .. } => self.walk(children, kind, marks),2190
Span::LineBreak | Span::Rule if !self.open || block_follows => {}2452
Span::LineBreak | Span::Rule if !self.open || block_follows => {}2191
Span::LineBreak | Span::Rule => {2453
Span::LineBreak | Span::Rule => {2192
let continued = match kind {2454
let continued = match kind {2193
LineKind::Quote | LineKind::Code(_) => kind.clone(),2455
LineKind::Quote | LineKind::Code(_) | LineKind::Indent(_) => kind.clone(),2194
_ => LineKind::Text,2456
_ => LineKind::Text,2195
};2457
};2196
self.start_line(&continued, None);2458
self.start_line(&continued, None);@@ -2707,7 +2969,7 @@ mod tests {2707
assert_eq!(draft.lines()[1], LineKind::Text);2969
assert_eq!(draft.lines()[1], LineKind::Text);2708
assert_eq!(2970
assert_eq!(2709
draft.to_html(),2971
draft.to_html(),2710
"<pre class=\"language-rust\">fn x() {}</pre>"2972
"<pre class=\"language-rust skipProofing\" spellcheck=\"false\"><code>fn x() {}</code></pre>"2711
);2973
);2712
}2974
}2713
2975
@@ -2742,7 +3004,7 @@ mod tests {2742
<blockquote>q1<br>q2</blockquote>\3004
<blockquote>q1<br>q2</blockquote>\2743
<ul><li>a<ul><li>b</li></ul></li></ul>\3005
<ul><li>a<ul><li>b</li></ul></li></ul>\2744
<ol><li>x</li><li>y</li></ol>\3006
<ol><li>x</li><li>y</li></ol>\2745
<pre class=\"language-py\">print(1)</pre>"3007
<pre class=\"language-py skipProofing\" spellcheck=\"false\"><code>print(1)</code></pre>"2746
);3008
);2747
}3009
}2748
3010
@@ -2947,7 +3209,7 @@ mod tests {2947
fn code_lines_hold_only_their_content() {3209
fn code_lines_hold_only_their_content() {2948
let mut draft = Draft::from_markdown("```\nlet a = 1;\n\u{2003}b\n```");3210
let mut draft = Draft::from_markdown("```\nlet a = 1;\n\u{2003}b\n```");2949
assert_eq!(draft.text(), "let a = 1;\n\u{2003}b");3211
assert_eq!(draft.text(), "let a = 1;\n\u{2003}b");2950
assert_eq!(draft.to_html(), "<pre>let a = 1;\n\u{2003}b</pre>");3212
assert_eq!(draft.to_html(), "<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>let a = 1;<br>\u{2003}b</code></pre>");2951
assert_eq!(draft.backspace_at_start(draft.line_ranges()[1].start), None);3213
assert_eq!(draft.backspace_at_start(draft.line_ranges()[1].start), None);2952
assert_eq!(draft.backspace_at_start(0), Some(0));3214
assert_eq!(draft.backspace_at_start(0), Some(0));2953
assert_eq!(draft.lines()[0], LineKind::Text);3215
assert_eq!(draft.lines()[0], LineKind::Text);@@ -2972,12 +3234,12 @@ mod tests {2972
draft.apply_edit(&next, cursor + pasted.len(), None);3234
draft.apply_edit(&next, cursor + pasted.len(), None);2973
assert_eq!(3235
assert_eq!(2974
draft.to_html(),3236
draft.to_html(),2975
"<pre class=\"language-py\">def f():\n return 1</pre>"3237
"<pre class=\"language-py skipProofing\" spellcheck=\"false\"><code>def f():<br> return 1</code></pre>"2976
);3238
);2977
let mut split = Draft::from_markdown("```\n a b\n```");3239
let mut split = Draft::from_markdown("```\n a b\n```");2978
let after_a = " a".len();3240
let after_a = " a".len();2979
split.break_line(after_a, false).unwrap();3241
split.break_line(after_a, false).unwrap();2980
assert_eq!(split.to_html(), "<pre> a\n b</pre>");3242
assert_eq!(split.to_html(), "<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code> a<br> b</code></pre>");2981
}3243
}2982
3244
2983
#[test]3245
#[test]@@ -124,7 +124,8 @@ pub use default_reactions::{
124
124
};
125
125
pub use download::LibraryFile;
126
126
pub use draft::{
127
Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,
127
Draft, DraftLine, Edit, FormatState, INDENT_PIXELS, LineKind, MAX_DEPTH, MAX_INDENT, Mark,
128
MarkKind, OBJECT_MARK, RULE_MARK,
128
129
SizeStep, TypingStyle, changed_span, has_markdown, link_url, map_offset, reverse_edits,
129
130
};
130
131
pub use emoticon_tags::{EmoticonTag, emoticon_tags};
@@ -124,7 +124,8 @@ pub use default_reactions::{124
};124
};125
pub use download::LibraryFile;125
pub use download::LibraryFile;126
pub use draft::{126
pub use draft::{127
Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,127
Draft, DraftLine, Edit, FormatState, INDENT_PIXELS, LineKind, MAX_DEPTH, MAX_INDENT, Mark,128
MarkKind, OBJECT_MARK, RULE_MARK,128
SizeStep, TypingStyle, changed_span, has_markdown, link_url, map_offset, reverse_edits,129
SizeStep, TypingStyle, changed_span, has_markdown, link_url, map_offset, reverse_edits,129
};130
};130
pub use emoticon_tags::{EmoticonTag, emoticon_tags};131
pub use emoticon_tags::{EmoticonTag, emoticon_tags};@@ -124,6 +124,7 @@ fn collect(spans: &[Span], parts: &mut BodyParts) {
124
124
| Span::Sized(_, children)
125
125
| Span::Underline(children)
126
126
| Span::Colored { children, .. }
127
| Span::Indent { children, .. }
127
128
| Span::Link { children, .. } => collect(children, parts),
128
129
Span::Heading { children, .. } | Span::BlockQuote(children) => {
129
130
parts.text.push(' ');
@@ -124,6 +124,7 @@ fn collect(spans: &[Span], parts: &mut BodyParts) {124
| Span::Sized(_, children)124
| Span::Sized(_, children)125
| Span::Underline(children)125
| Span::Underline(children)126
| Span::Colored { children, .. }126
| Span::Colored { children, .. }127
| Span::Indent { children, .. }127
| Span::Link { children, .. } => collect(children, parts),128
| Span::Link { children, .. } => collect(children, parts),128
Span::Heading { children, .. } | Span::BlockQuote(children) => {129
Span::Heading { children, .. } | Span::BlockQuote(children) => {129
parts.text.push(' ');130
parts.text.push(' ');@@ -61,6 +61,10 @@ pub enum Span {
61
61
children: Vec<Span>,
62
62
},
63
63
BlockQuote(Vec<Span>),
64
Indent {
65
level: u8,
66
children: Vec<Span>,
67
},
64
68
}
65
69
66
70
const BLOCK_ELEMENTS: [&str; 12] = [
@@ -73,6 +77,10 @@ const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";
73
77
const MAX_HEADING_LEVEL: u8 = 3;
74
78
const MARK_BACKGROUND: u32 = 0xffff00;
75
79
const MAX_CONSECUTIVE_BREAKS: usize = 2;
80
const INDENTED_ELEMENTS: [&str; 8] = ["p", "div", "h1", "h2", "h3", "h4", "h5", "h6"];
81
const INDENT_STEP_PIXELS: f32 = 40.;
82
const MAX_INDENT_LEVEL: u8 = 8;
83
const PLAIN_LANGUAGE: &str = "plaintext";
76
84
77
85
pub fn html_to_spans(html: &str) -> Vec<Span> {
78
86
let fragment = Html::parse_fragment(html);
@@ -119,6 +127,29 @@ fn convert_element(element: ElementRef<'_>, spans: &mut Vec<Span>) {
119
127
if SKIPPED_ELEMENTS.contains(&name) {
120
128
return;
121
129
}
130
match block_indent(element) {
131
Some(level) => {
132
let mut children = Vec::new();
133
convert_unindented(element, &mut children);
134
spans.push(Span::Indent { level, children });
135
}
136
None => convert_unindented(element, spans),
137
}
138
}
139
140
fn block_indent(element: ElementRef<'_>) -> Option<u8> {
141
let value = element.value();
142
if !INDENTED_ELEMENTS.contains(&value.name()) {
143
return None;
144
}
145
let margin = style_value(value.attr("style")?, "margin-left")?;
146
let pixels: f32 = margin.trim().strip_suffix("px")?.trim().parse().ok()?;
147
let level = (pixels / INDENT_STEP_PIXELS).round();
148
(level >= 1.).then(|| level.min(f32::from(MAX_INDENT_LEVEL)) as u8)
149
}
150
151
fn convert_unindented(element: ElementRef<'_>, spans: &mut Vec<Span>) {
152
let name = element.value().name();
122
153
match name {
123
154
"b" | "strong" => spans.push(Span::Bold(convert_children(element))),
124
155
"h1" | "h2" | "h3" | "h4" | "h5" | "h6" => spans.push(Span::Heading {
@@ -344,9 +375,21 @@ fn code_block(element: ElementRef<'_>) -> Span {
344
375
.find_map(language_of)
345
376
});
346
377
Span::CodeBlock {
347
language,
348
code: raw_text(element).trim_end_matches('\n').to_owned(),
378
language: language.filter(|language| language != PLAIN_LANGUAGE),
379
code: code_text(element).trim_end_matches('\n').to_owned(),
380
}
381
}
382
383
fn code_text(element: ElementRef<'_>) -> String {
384
let mut text = String::new();
385
for node in element.descendants() {
386
match node.value() {
387
Node::Text(piece) => text.push_str(piece),
388
Node::Element(child) if child.name() == "br" => text.push('\n'),
389
_ => {}
390
}
349
391
}
392
text
350
393
}
351
394
352
395
fn language_of(element: ElementRef<'_>) -> Option<String> {
@@ -426,6 +469,7 @@ fn tidy(spans: &mut Vec<Span>) {
426
469
| Span::Heading { children, .. }
427
470
| Span::Quote { children, .. }
428
471
| Span::BlockQuote(children)
472
| Span::Indent { children, .. }
429
473
| Span::Link { children, .. } => tidy(children),
430
474
Span::List { items, .. } => items.iter_mut().for_each(tidy),
431
475
Span::Table { rows, .. } => rows.iter_mut().flatten().for_each(tidy),
@@ -457,6 +501,7 @@ fn collapse_whitespace(spans: &mut Vec<Span>) {
457
501
| Span::Heading { .. }
458
502
| Span::Quote { .. }
459
503
| Span::BlockQuote(_)
504
| Span::Indent { .. }
460
505
)
461
506
)
462
507
};
@@ -61,6 +61,10 @@ pub enum Span {61
children: Vec<Span>,61
children: Vec<Span>,62
},62
},63
BlockQuote(Vec<Span>),63
BlockQuote(Vec<Span>),64
Indent {65
level: u8,66
children: Vec<Span>,67
},64
}68
}65
69
66
const BLOCK_ELEMENTS: [&str; 12] = [70
const BLOCK_ELEMENTS: [&str; 12] = [@@ -73,6 +77,10 @@ const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";73
const MAX_HEADING_LEVEL: u8 = 3;77
const MAX_HEADING_LEVEL: u8 = 3;74
const MARK_BACKGROUND: u32 = 0xffff00;78
const MARK_BACKGROUND: u32 = 0xffff00;75
const MAX_CONSECUTIVE_BREAKS: usize = 2;79
const MAX_CONSECUTIVE_BREAKS: usize = 2;80
const INDENTED_ELEMENTS: [&str; 8] = ["p", "div", "h1", "h2", "h3", "h4", "h5", "h6"];81
const INDENT_STEP_PIXELS: f32 = 40.;82
const MAX_INDENT_LEVEL: u8 = 8;83
const PLAIN_LANGUAGE: &str = "plaintext";76
84
77
pub fn html_to_spans(html: &str) -> Vec<Span> {85
pub fn html_to_spans(html: &str) -> Vec<Span> {78
let fragment = Html::parse_fragment(html);86
let fragment = Html::parse_fragment(html);@@ -119,6 +127,29 @@ fn convert_element(element: ElementRef<'_>, spans: &mut Vec<Span>) {119
if SKIPPED_ELEMENTS.contains(&name) {127
if SKIPPED_ELEMENTS.contains(&name) {120
return;128
return;121
}129
}130
match block_indent(element) {131
Some(level) => {132
let mut children = Vec::new();133
convert_unindented(element, &mut children);134
spans.push(Span::Indent { level, children });135
}136
None => convert_unindented(element, spans),137
}138
}139
140
fn block_indent(element: ElementRef<'_>) -> Option<u8> {141
let value = element.value();142
if !INDENTED_ELEMENTS.contains(&value.name()) {143
return None;144
}145
let margin = style_value(value.attr("style")?, "margin-left")?;146
let pixels: f32 = margin.trim().strip_suffix("px")?.trim().parse().ok()?;147
let level = (pixels / INDENT_STEP_PIXELS).round();148
(level >= 1.).then(|| level.min(f32::from(MAX_INDENT_LEVEL)) as u8)149
}150
151
fn convert_unindented(element: ElementRef<'_>, spans: &mut Vec<Span>) {152
let name = element.value().name();122
match name {153
match name {123
"b" | "strong" => spans.push(Span::Bold(convert_children(element))),154
"b" | "strong" => spans.push(Span::Bold(convert_children(element))),124
"h1" | "h2" | "h3" | "h4" | "h5" | "h6" => spans.push(Span::Heading {155
"h1" | "h2" | "h3" | "h4" | "h5" | "h6" => spans.push(Span::Heading {@@ -344,9 +375,21 @@ fn code_block(element: ElementRef<'_>) -> Span {344
.find_map(language_of)375
.find_map(language_of)345
});376
});346
Span::CodeBlock {377
Span::CodeBlock {347
language,378
language: language.filter(|language| language != PLAIN_LANGUAGE),348
code: raw_text(element).trim_end_matches('\n').to_owned(),379
code: code_text(element).trim_end_matches('\n').to_owned(),380
}381
}382
383
fn code_text(element: ElementRef<'_>) -> String {384
let mut text = String::new();385
for node in element.descendants() {386
match node.value() {387
Node::Text(piece) => text.push_str(piece),388
Node::Element(child) if child.name() == "br" => text.push('\n'),389
_ => {}390
}349
}391
}392
text350
}393
}351
394
352
fn language_of(element: ElementRef<'_>) -> Option<String> {395
fn language_of(element: ElementRef<'_>) -> Option<String> {@@ -426,6 +469,7 @@ fn tidy(spans: &mut Vec<Span>) {426
| Span::Heading { children, .. }469
| Span::Heading { children, .. }427
| Span::Quote { children, .. }470
| Span::Quote { children, .. }428
| Span::BlockQuote(children)471
| Span::BlockQuote(children)472
| Span::Indent { children, .. }429
| Span::Link { children, .. } => tidy(children),473
| Span::Link { children, .. } => tidy(children),430
Span::List { items, .. } => items.iter_mut().for_each(tidy),474
Span::List { items, .. } => items.iter_mut().for_each(tidy),431
Span::Table { rows, .. } => rows.iter_mut().flatten().for_each(tidy),475
Span::Table { rows, .. } => rows.iter_mut().flatten().for_each(tidy),@@ -457,6 +501,7 @@ fn collapse_whitespace(spans: &mut Vec<Span>) {457
| Span::Heading { .. }501
| Span::Heading { .. }458
| Span::Quote { .. }502
| Span::Quote { .. }459
| Span::BlockQuote(_)503
| Span::BlockQuote(_)504
| Span::Indent { .. }460
)505
)461
)506
)462
};507
};@@ -488,6 +488,7 @@ pub(crate) fn push_plain(text: &mut String, spans: &[Span]) {
488
488
| Span::Sized(_, children)
489
489
| Span::Underline(children)
490
490
| Span::Colored { children, .. }
491
| Span::Indent { children, .. }
491
492
| Span::Quote { children, .. }
492
493
| Span::BlockQuote(children)
493
494
| Span::Link { children, .. } => push_plain(text, children),
@@ -617,6 +618,7 @@ fn link_user_mentions(spans: &mut [Span], infos: &[MentionInfo]) {
617
618
| Span::Sized(_, children)
618
619
| Span::Underline(children)
619
620
| Span::Colored { children, .. }
621
| Span::Indent { children, .. }
620
622
| Span::Heading { children, .. }
621
623
| Span::Quote { children, .. }
622
624
| Span::BlockQuote(children)
@@ -710,6 +712,7 @@ fn collect_user_mentions(spans: &[Span], infos: &[MentionInfo], inputs: &mut Vec
710
712
| Span::Sized(_, children)
711
713
| Span::Underline(children)
712
714
| Span::Colored { children, .. }
715
| Span::Indent { children, .. }
713
716
| Span::Heading { children, .. }
714
717
| Span::Quote { children, .. }
715
718
| Span::BlockQuote(children)
@@ -756,6 +759,7 @@ fn merge_split_mentions(spans: &mut Vec<Span>, mentions: &[MentionInfo]) {
756
759
| Span::Sized(_, children)
757
760
| Span::Underline(children)
758
761
| Span::Colored { children, .. }
762
| Span::Indent { children, .. }
759
763
| Span::Heading { children, .. }
760
764
| Span::Quote { children, .. }
761
765
| Span::BlockQuote(children)
@@ -488,6 +488,7 @@ pub(crate) fn push_plain(text: &mut String, spans: &[Span]) {488
| Span::Sized(_, children)488
| Span::Sized(_, children)489
| Span::Underline(children)489
| Span::Underline(children)490
| Span::Colored { children, .. }490
| Span::Colored { children, .. }491
| Span::Indent { children, .. }491
| Span::Quote { children, .. }492
| Span::Quote { children, .. }492
| Span::BlockQuote(children)493
| Span::BlockQuote(children)493
| Span::Link { children, .. } => push_plain(text, children),494
| Span::Link { children, .. } => push_plain(text, children),@@ -617,6 +618,7 @@ fn link_user_mentions(spans: &mut [Span], infos: &[MentionInfo]) {617
| Span::Sized(_, children)618
| Span::Sized(_, children)618
| Span::Underline(children)619
| Span::Underline(children)619
| Span::Colored { children, .. }620
| Span::Colored { children, .. }621
| Span::Indent { children, .. }620
| Span::Heading { children, .. }622
| Span::Heading { children, .. }621
| Span::Quote { children, .. }623
| Span::Quote { children, .. }622
| Span::BlockQuote(children)624
| Span::BlockQuote(children)@@ -710,6 +712,7 @@ fn collect_user_mentions(spans: &[Span], infos: &[MentionInfo], inputs: &mut Vec710
| Span::Sized(_, children)712
| Span::Sized(_, children)711
| Span::Underline(children)713
| Span::Underline(children)712
| Span::Colored { children, .. }714
| Span::Colored { children, .. }715
| Span::Indent { children, .. }713
| Span::Heading { children, .. }716
| Span::Heading { children, .. }714
| Span::Quote { children, .. }717
| Span::Quote { children, .. }715
| Span::BlockQuote(children)718
| Span::BlockQuote(children)@@ -756,6 +759,7 @@ fn merge_split_mentions(spans: &mut Vec<Span>, mentions: &[MentionInfo]) {756
| Span::Sized(_, children)759
| Span::Sized(_, children)757
| Span::Underline(children)760
| Span::Underline(children)758
| Span::Colored { children, .. }761
| Span::Colored { children, .. }762
| Span::Indent { children, .. }759
| Span::Heading { children, .. }763
| Span::Heading { children, .. }760
| Span::Quote { children, .. }764
| Span::Quote { children, .. }761
| Span::BlockQuote(children)765
| Span::BlockQuote(children)@@ -1,5 +1,6 @@
1
1
use teams_core::{
2
Draft, DraftLine, LineKind, Mark, MarkKind, TABLE_MARK, Table, TypingStyle, html_to_spans,
2
Draft, DraftLine, LineKind, Mark, MarkKind, RULE_MARK, TABLE_MARK, Table, TypingStyle,
3
html_to_spans,
3
4
};
4
5
5
6
fn typed(draft: &mut Draft, text: &str) {
@@ -291,7 +292,7 @@ fn pasted_markdown_becomes_headings_lists_quotes_code_and_tables() {
291
292
assert!(html.contains("<b>bold</b>, <i>it</i>, <s>gone</s>, <code>code</code>"));
292
293
assert!(html.contains("<a href=\"https://x.de\">docs</a>"));
293
294
assert!(html.contains("<blockquote>quoted</blockquote>"));
294
assert!(html.contains("<pre class=\"language-rust\">fn x() {}</pre>"));
295
assert!(html.contains("<pre class=\"language-rust skipProofing\" spellcheck=\"false\"><code>fn x() {}</code></pre>"));
295
296
assert!(
296
297
html.ends_with("<td>1</td><td>2</td></tr></tbody></table></figure>"),
297
298
"{html}"
@@ -353,3 +354,186 @@ fn a_table_as_chatsvc_stores_it_reads_back_into_the_sent_table() {
353
354
assert!(received.rows[2][1].trim().is_empty());
354
355
assert_eq!(received.to_html(), table.to_html());
355
356
}
357
358
#[test]
359
fn font_colour_and_highlight_send_teams_spans() {
360
let mut draft = Draft::plain("red and marked");
361
draft.set_color(0..3, Some(0xB6424C));
362
draft.set_highlight(8..14, Some(0xFDD472));
363
assert_eq!(
364
draft.to_html(),
365
"<span style=\"color:#B6424C;\">red</span> and \
366
<span style=\"background-color:#FDD472;\">marked</span>"
367
);
368
draft.set_color(1..3, Some(0x1E53A3));
369
assert_eq!(draft.color_in(0..1, &MarkKind::Color(0)), Some(0xB6424C));
370
assert_eq!(draft.color_in(1..3, &MarkKind::Color(0)), Some(0x1E53A3));
371
draft.set_color(0..3, None);
372
assert_eq!(draft.color_in(0..3, &MarkKind::Color(0)), None);
373
}
374
375
#[test]
376
fn received_colours_come_back_as_marks() {
377
let html = "<p><span style=\"color:#B6424C;\">a</span> \
378
<span style=\"background-color: rgb(253, 212, 114)\">b</span></p>";
379
let draft = Draft::from_spans(&html_to_spans(html));
380
assert_eq!(draft.text(), "a b");
381
assert!(draft.marks().contains(&Mark {
382
range: 0..1,
383
kind: MarkKind::Color(0xB6424C)
384
}));
385
assert!(draft.marks().contains(&Mark {
386
range: 2..3,
387
kind: MarkKind::Highlight(0xFDD472)
388
}));
389
}
390
391
#[test]
392
fn typing_style_picks_and_drops_a_colour() {
393
let mut typing = TypingStyle::default();
394
typing.set_color(Some(0x2B9B62), &[MarkKind::Color(0xB6424C), MarkKind::Bold]);
395
assert_eq!(
396
typing.apply(vec![MarkKind::Color(0xB6424C), MarkKind::Bold]),
397
[MarkKind::Bold, MarkKind::Color(0x2B9B62)]
398
);
399
typing.clear(&[MarkKind::Bold, MarkKind::Link("https://x.de".into())]);
400
assert_eq!(
401
typing.apply(vec![MarkKind::Bold, MarkKind::Link("https://x.de".into())]),
402
[MarkKind::Link("https://x.de".into())]
403
);
404
}
405
406
#[test]
407
fn clear_formatting_keeps_links_and_drops_the_indent() {
408
let mut draft = Draft::from_markdown("**bold** [l](https://x.de)");
409
draft.set_highlight(0..4, Some(0xDF9299));
410
draft.indent_blocks(0..0, false);
411
let length = draft.text().len();
412
draft.clear_formatting(0..length);
413
assert_eq!(draft.lines(), [LineKind::Text]);
414
assert_eq!(
415
draft.marks(),
416
[Mark {
417
range: 5..6,
418
kind: MarkKind::Link("https://x.de".into())
419
}]
420
);
421
}
422
423
#[test]
424
fn indent_moves_paragraphs_by_teams_block_steps_and_nests_lists() {
425
let mut draft = Draft::plain("a\nb");
426
draft.indent_blocks(0..0, false);
427
draft.indent_blocks(0..0, false);
428
draft.indent_blocks(2..3, false);
429
assert_eq!(draft.lines(), [LineKind::Indent(2), LineKind::Indent(1)]);
430
assert_eq!(
431
draft.to_html(),
432
"<p style=\"margin-left:80px;\">a</p><p style=\"margin-left:40px;\">b</p>"
433
);
434
assert!(draft.can_outdent(0..0));
435
draft.indent_blocks(0..3, true);
436
assert_eq!(draft.lines(), [LineKind::Indent(1), LineKind::Text]);
437
assert!(!draft.can_outdent(2..3));
438
let mut list = Draft::from_markdown("- x");
439
list.indent_blocks(0..0, false);
440
assert_eq!(list.lines(), [LineKind::Bullet(1)]);
441
}
442
443
#[test]
444
fn shift_enter_keeps_the_indent_and_enter_is_left_to_send() {
445
let mut draft = Draft::plain("a");
446
draft.indent_blocks(0..0, false);
447
assert_eq!(enter(&mut draft, 1, false), None);
448
assert_eq!(enter(&mut draft, 1, true), Some(2));
449
assert_eq!(draft.lines(), [LineKind::Indent(1), LineKind::Indent(1)]);
450
}
451
452
#[test]
453
fn received_margins_become_indent_levels() {
454
let draft = Draft::from_spans(&html_to_spans(
455
"<p style=\"margin-left:80px\">deep</p><p>flat</p><p style=\"margin-left: 40px;\">one</p>",
456
));
457
assert_eq!(
458
draft.lines(),
459
[LineKind::Indent(2), LineKind::Text, LineKind::Indent(1)]
460
);
461
assert_eq!(draft.text(), "deep\nflat\none");
462
}
463
464
#[test]
465
fn a_rule_is_its_own_line_sent_as_hr() {
466
let mut draft = Draft::plain("a");
467
let cursor = draft.insert_rule(1);
468
draft.take_edits();
469
assert_eq!(draft.text(), format!("a\n{RULE_MARK}\n"));
470
assert_eq!(cursor, draft.text().len());
471
assert_eq!(
472
draft.lines(),
473
[LineKind::Text, LineKind::Rule, LineKind::Text]
474
);
475
assert_eq!(draft.trimmed().to_html(), "a<hr>");
476
assert_eq!(draft.plain_text(), "a\n\n");
477
assert_eq!(draft.backspace_at_start(cursor), Some(2));
478
assert_eq!(draft.text(), "a\n");
479
assert_eq!(draft.lines(), [LineKind::Text, LineKind::Text]);
480
}
481
482
#[test]
483
fn text_typed_onto_a_rule_line_moves_off_it() {
484
let mut draft = Draft::default();
485
draft.insert_rule(0);
486
let mut next = draft.text().to_owned();
487
next.insert(0, 'x');
488
draft.apply_edit(&next, 1, None);
489
assert_eq!(draft.text(), format!("x\n{RULE_MARK}\n"));
490
assert_eq!(draft.lines()[1], LineKind::Rule);
491
}
492
493
#[test]
494
fn received_rules_come_back_as_rule_lines() {
495
let draft = Draft::from_spans(&html_to_spans("<p>a</p><hr><p>b</p>"));
496
assert_eq!(
497
draft.lines(),
498
[LineKind::Text, LineKind::Rule, LineKind::Text]
499
);
500
assert_eq!(draft.to_html(), "a<hr>b");
501
}
502
503
#[test]
504
fn paragraph_style_sets_and_clears_headings() {
505
let mut draft = Draft::plain("title\nbody");
506
draft.set_heading(0..0, Some(2));
507
assert_eq!(draft.heading_at(0), Some(2));
508
assert_eq!(draft.to_html(), "<h2>title</h2>body");
509
draft.set_heading(0..8, Some(1));
510
assert_eq!(draft.lines(), [LineKind::Heading(1), LineKind::Heading(1)]);
511
draft.set_heading(0..0, None);
512
assert_eq!(draft.lines(), [LineKind::Text, LineKind::Heading(1)]);
513
}
514
515
#[test]
516
fn code_blocks_send_the_teams_pre_code_shape_and_read_back_line_breaks() {
517
let draft = Draft::from_lines(&[
518
DraftLine {
519
kind: LineKind::Code(None),
520
number: None,
521
content: "a < b".into(),
522
marks: Vec::new(),
523
},
524
DraftLine {
525
kind: LineKind::Code(None),
526
number: None,
527
content: " c".into(),
528
marks: Vec::new(),
529
},
530
]);
531
let html = draft.to_html();
532
assert_eq!(
533
html,
534
"<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>a < b<br> c</code></pre>"
535
);
536
let back = Draft::from_spans(&html_to_spans(&html));
537
assert_eq!(back.lines(), [LineKind::Code(None), LineKind::Code(None)]);
538
assert_eq!(back.text(), "a < b\n c");
539
}
@@ -1,5 +1,6 @@1
use teams_core::{1
use teams_core::{2
Draft, DraftLine, LineKind, Mark, MarkKind, TABLE_MARK, Table, TypingStyle, html_to_spans,2
Draft, DraftLine, LineKind, Mark, MarkKind, RULE_MARK, TABLE_MARK, Table, TypingStyle,3
html_to_spans,3
};4
};4
5
5
fn typed(draft: &mut Draft, text: &str) {6
fn typed(draft: &mut Draft, text: &str) {@@ -291,7 +292,7 @@ fn pasted_markdown_becomes_headings_lists_quotes_code_and_tables() {291
assert!(html.contains("<b>bold</b>, <i>it</i>, <s>gone</s>, <code>code</code>"));292
assert!(html.contains("<b>bold</b>, <i>it</i>, <s>gone</s>, <code>code</code>"));292
assert!(html.contains("<a href=\"https://x.de\">docs</a>"));293
assert!(html.contains("<a href=\"https://x.de\">docs</a>"));293
assert!(html.contains("<blockquote>quoted</blockquote>"));294
assert!(html.contains("<blockquote>quoted</blockquote>"));294
assert!(html.contains("<pre class=\"language-rust\">fn x() {}</pre>"));295
assert!(html.contains("<pre class=\"language-rust skipProofing\" spellcheck=\"false\"><code>fn x() {}</code></pre>"));295
assert!(296
assert!(296
html.ends_with("<td>1</td><td>2</td></tr></tbody></table></figure>"),297
html.ends_with("<td>1</td><td>2</td></tr></tbody></table></figure>"),297
"{html}"298
"{html}"@@ -353,3 +354,186 @@ fn a_table_as_chatsvc_stores_it_reads_back_into_the_sent_table() {353
assert!(received.rows[2][1].trim().is_empty());354
assert!(received.rows[2][1].trim().is_empty());354
assert_eq!(received.to_html(), table.to_html());355
assert_eq!(received.to_html(), table.to_html());355
}356
}357
358
#[test]359
fn font_colour_and_highlight_send_teams_spans() {360
let mut draft = Draft::plain("red and marked");361
draft.set_color(0..3, Some(0xB6424C));362
draft.set_highlight(8..14, Some(0xFDD472));363
assert_eq!(364
draft.to_html(),365
"<span style=\"color:#B6424C;\">red</span> and \366
<span style=\"background-color:#FDD472;\">marked</span>"367
);368
draft.set_color(1..3, Some(0x1E53A3));369
assert_eq!(draft.color_in(0..1, &MarkKind::Color(0)), Some(0xB6424C));370
assert_eq!(draft.color_in(1..3, &MarkKind::Color(0)), Some(0x1E53A3));371
draft.set_color(0..3, None);372
assert_eq!(draft.color_in(0..3, &MarkKind::Color(0)), None);373
}374
375
#[test]376
fn received_colours_come_back_as_marks() {377
let html = "<p><span style=\"color:#B6424C;\">a</span> \378
<span style=\"background-color: rgb(253, 212, 114)\">b</span></p>";379
let draft = Draft::from_spans(&html_to_spans(html));380
assert_eq!(draft.text(), "a b");381
assert!(draft.marks().contains(&Mark {382
range: 0..1,383
kind: MarkKind::Color(0xB6424C)384
}));385
assert!(draft.marks().contains(&Mark {386
range: 2..3,387
kind: MarkKind::Highlight(0xFDD472)388
}));389
}390
391
#[test]392
fn typing_style_picks_and_drops_a_colour() {393
let mut typing = TypingStyle::default();394
typing.set_color(Some(0x2B9B62), &[MarkKind::Color(0xB6424C), MarkKind::Bold]);395
assert_eq!(396
typing.apply(vec![MarkKind::Color(0xB6424C), MarkKind::Bold]),397
[MarkKind::Bold, MarkKind::Color(0x2B9B62)]398
);399
typing.clear(&[MarkKind::Bold, MarkKind::Link("https://x.de".into())]);400
assert_eq!(401
typing.apply(vec![MarkKind::Bold, MarkKind::Link("https://x.de".into())]),402
[MarkKind::Link("https://x.de".into())]403
);404
}405
406
#[test]407
fn clear_formatting_keeps_links_and_drops_the_indent() {408
let mut draft = Draft::from_markdown("**bold** [l](https://x.de)");409
draft.set_highlight(0..4, Some(0xDF9299));410
draft.indent_blocks(0..0, false);411
let length = draft.text().len();412
draft.clear_formatting(0..length);413
assert_eq!(draft.lines(), [LineKind::Text]);414
assert_eq!(415
draft.marks(),416
[Mark {417
range: 5..6,418
kind: MarkKind::Link("https://x.de".into())419
}]420
);421
}422
423
#[test]424
fn indent_moves_paragraphs_by_teams_block_steps_and_nests_lists() {425
let mut draft = Draft::plain("a\nb");426
draft.indent_blocks(0..0, false);427
draft.indent_blocks(0..0, false);428
draft.indent_blocks(2..3, false);429
assert_eq!(draft.lines(), [LineKind::Indent(2), LineKind::Indent(1)]);430
assert_eq!(431
draft.to_html(),432
"<p style=\"margin-left:80px;\">a</p><p style=\"margin-left:40px;\">b</p>"433
);434
assert!(draft.can_outdent(0..0));435
draft.indent_blocks(0..3, true);436
assert_eq!(draft.lines(), [LineKind::Indent(1), LineKind::Text]);437
assert!(!draft.can_outdent(2..3));438
let mut list = Draft::from_markdown("- x");439
list.indent_blocks(0..0, false);440
assert_eq!(list.lines(), [LineKind::Bullet(1)]);441
}442
443
#[test]444
fn shift_enter_keeps_the_indent_and_enter_is_left_to_send() {445
let mut draft = Draft::plain("a");446
draft.indent_blocks(0..0, false);447
assert_eq!(enter(&mut draft, 1, false), None);448
assert_eq!(enter(&mut draft, 1, true), Some(2));449
assert_eq!(draft.lines(), [LineKind::Indent(1), LineKind::Indent(1)]);450
}451
452
#[test]453
fn received_margins_become_indent_levels() {454
let draft = Draft::from_spans(&html_to_spans(455
"<p style=\"margin-left:80px\">deep</p><p>flat</p><p style=\"margin-left: 40px;\">one</p>",456
));457
assert_eq!(458
draft.lines(),459
[LineKind::Indent(2), LineKind::Text, LineKind::Indent(1)]460
);461
assert_eq!(draft.text(), "deep\nflat\none");462
}463
464
#[test]465
fn a_rule_is_its_own_line_sent_as_hr() {466
let mut draft = Draft::plain("a");467
let cursor = draft.insert_rule(1);468
draft.take_edits();469
assert_eq!(draft.text(), format!("a\n{RULE_MARK}\n"));470
assert_eq!(cursor, draft.text().len());471
assert_eq!(472
draft.lines(),473
[LineKind::Text, LineKind::Rule, LineKind::Text]474
);475
assert_eq!(draft.trimmed().to_html(), "a<hr>");476
assert_eq!(draft.plain_text(), "a\n\n");477
assert_eq!(draft.backspace_at_start(cursor), Some(2));478
assert_eq!(draft.text(), "a\n");479
assert_eq!(draft.lines(), [LineKind::Text, LineKind::Text]);480
}481
482
#[test]483
fn text_typed_onto_a_rule_line_moves_off_it() {484
let mut draft = Draft::default();485
draft.insert_rule(0);486
let mut next = draft.text().to_owned();487
next.insert(0, 'x');488
draft.apply_edit(&next, 1, None);489
assert_eq!(draft.text(), format!("x\n{RULE_MARK}\n"));490
assert_eq!(draft.lines()[1], LineKind::Rule);491
}492
493
#[test]494
fn received_rules_come_back_as_rule_lines() {495
let draft = Draft::from_spans(&html_to_spans("<p>a</p><hr><p>b</p>"));496
assert_eq!(497
draft.lines(),498
[LineKind::Text, LineKind::Rule, LineKind::Text]499
);500
assert_eq!(draft.to_html(), "a<hr>b");501
}502
503
#[test]504
fn paragraph_style_sets_and_clears_headings() {505
let mut draft = Draft::plain("title\nbody");506
draft.set_heading(0..0, Some(2));507
assert_eq!(draft.heading_at(0), Some(2));508
assert_eq!(draft.to_html(), "<h2>title</h2>body");509
draft.set_heading(0..8, Some(1));510
assert_eq!(draft.lines(), [LineKind::Heading(1), LineKind::Heading(1)]);511
draft.set_heading(0..0, None);512
assert_eq!(draft.lines(), [LineKind::Text, LineKind::Heading(1)]);513
}514
515
#[test]516
fn code_blocks_send_the_teams_pre_code_shape_and_read_back_line_breaks() {517
let draft = Draft::from_lines(&[518
DraftLine {519
kind: LineKind::Code(None),520
number: None,521
content: "a < b".into(),522
marks: Vec::new(),523
},524
DraftLine {525
kind: LineKind::Code(None),526
number: None,527
content: " c".into(),528
marks: Vec::new(),529
},530
]);531
let html = draft.to_html();532
assert_eq!(533
html,534
"<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>a < b<br> c</code></pre>"535
);536
let back = Draft::from_spans(&html_to_spans(&html));537
assert_eq!(back.lines(), [LineKind::Code(None), LineKind::Code(None)]);538
assert_eq!(back.text(), "a < b\n c");539
}@@ -479,3 +479,38 @@ fn sized_text_nests_with_bold_and_color() {
479
479
)]
480
480
);
481
481
}
482
483
#[test]
484
fn margin_left_paragraphs_become_indent_levels() {
485
assert_eq!(
486
html_to_spans("<p style=\"margin-left:40px;\">a</p><div style=\"margin-left: 120px\">b</div>"),
487
vec![
488
Span::Indent {
489
level: 1,
490
children: vec![text("a")],
491
},
492
Span::LineBreak,
493
Span::Indent {
494
level: 3,
495
children: vec![text("b")],
496
},
497
]
498
);
499
assert_eq!(
500
html_to_spans("<p style=\"margin-left:10px\">a</p>"),
501
vec![text("a")]
502
);
503
}
504
505
#[test]
506
fn teams_code_blocks_keep_their_line_breaks() {
507
assert_eq!(
508
html_to_spans(
509
"<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>a<br> b</code></pre>"
510
),
511
vec![Span::CodeBlock {
512
language: None,
513
code: "a\n\u{a0} b".to_owned(),
514
}]
515
);
516
}
@@ -479,3 +479,38 @@ fn sized_text_nests_with_bold_and_color() {479
)]479
)]480
);480
);481
}481
}482
483
#[test]484
fn margin_left_paragraphs_become_indent_levels() {485
assert_eq!(486
html_to_spans("<p style=\"margin-left:40px;\">a</p><div style=\"margin-left: 120px\">b</div>"),487
vec![488
Span::Indent {489
level: 1,490
children: vec![text("a")],491
},492
Span::LineBreak,493
Span::Indent {494
level: 3,495
children: vec![text("b")],496
},497
]498
);499
assert_eq!(500
html_to_spans("<p style=\"margin-left:10px\">a</p>"),501
vec![text("a")]502
);503
}504
505
#[test]506
fn teams_code_blocks_keep_their_line_breaks() {507
assert_eq!(508
html_to_spans(509
"<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>a<br> b</code></pre>"510
),511
vec![Span::CodeBlock {512
language: None,513
code: "a\n\u{a0} b".to_owned(),514
}]515
);516
}