Merge remote-tracking branch 'origin/main' into feat/share-mentions
@@ -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]); 73] = symbols![
12
12
"bot",
13
13
"done",
14
14
"table",
@@ -73,6 +73,15 @@ 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",
84
"fluent_text_font_size",
76
85
];
77
86
78
87
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]); 73] = symbols![12
"bot",12
"bot",13
"done",13
"done",14
"table",14
"table",@@ -73,6 +73,15 @@ 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",84
"fluent_text_font_size",76
];85
];77
86
78
pub struct AppAssets;87
pub struct AppAssets;@@ -1757,7 +1757,7 @@ fn release_messages() -> Vec<MessageRecord> {
1757
1757
None,
1758
1758
jonas,
1759
1759
at(0, 11, 5),
1760
"<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>",
1760
"<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>",
1761
1761
"[]",
1762
1762
false,
1763
1763
),
@@ -1757,7 +1757,7 @@ fn release_messages() -> Vec<MessageRecord> {1757
None,1757
None,1758
jonas,1758
jonas,1759
at(0, 11, 5),1759
at(0, 11, 5),1760
"<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>",1760
"<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>",1761
"[]",1761
"[]",1762
false,1762
false,1763
),1763
),@@ -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="M13 3.5c.2 0 .4.13.47.32l3 8v.02l1.5 3.98a.5.5 0 1 1-.94.36l-1.38-3.68h-5.3l-1.38 3.68a.5.5 0 0 1-.93 0L6.96 13.5H4.04l-1.08 2.69a.5.5 0 1 1-.92-.38l1.2-2.98v-.03l1.8-4.49a.5.5 0 0 1 .92 0l1.8 4.5v.02l.73 1.79 1.04-2.78v-.03l3-7.99A.5.5 0 0 1 13 3.5Zm-2.28 8h4.56L13 5.42l-2.28 6.08Zm-4.16 1L5.5 9.85 4.44 12.5h2.12Z"/></svg>
@@ -0,0 +1 @@1
<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M13 3.5c.2 0 .4.13.47.32l3 8v.02l1.5 3.98a.5.5 0 1 1-.94.36l-1.38-3.68h-5.3l-1.38 3.68a.5.5 0 0 1-.93 0L6.96 13.5H4.04l-1.08 2.69a.5.5 0 1 1-.92-.38l1.2-2.98v-.03l1.8-4.49a.5.5 0 0 1 .92 0l1.8 4.5v.02l.73 1.79 1.04-2.78v-.03l3-7.99A.5.5 0 0 1 13 3.5Zm-2.28 8h4.56L13 5.42l-2.28 6.08Zm-4.16 1L5.5 9.85 4.44 12.5h2.12Z"/></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::{
@@ -63,6 +66,8 @@ use crate::runtime;
63
66
use crate::scheduled_rows::scheduled_label;
64
67
use crate::theme::{self, ElevatedSurface as _};
65
68
use crate::typing::OutgoingTyping;
69
use format_menus::{FormatPopup, paragraph_label};
70
use rule::{is_rule_token, render_rule_token};
66
71
use table::{TableKey, TableLineMenu, TableMenu, TablePicker, TableViews, is_table_token};
67
72
68
73
const MIN_ROWS: usize = 1;
@@ -225,6 +230,8 @@ pub struct Composer {
225
230
table_counter: usize,
226
231
table_picker: Option<TablePicker>,
227
232
table_menu: Option<TableMenu>,
233
format_popup: Option<FormatPopup>,
234
format_overflow: bool,
228
235
format_bar: HashSet<String>,
229
236
active_cell: Option<(String, teams_core::Cell)>,
230
237
caret_before_table: usize,
@@ -480,6 +487,8 @@ impl Composer {
480
487
table_counter: 0,
481
488
table_picker: None,
482
489
table_menu: None,
490
format_popup: None,
491
format_overflow: false,
483
492
format_bar: HashSet::new(),
484
493
active_cell: None,
485
494
caret_before_table: 0,
@@ -879,6 +888,8 @@ impl Composer {
879
888
self.pending_anchors.clear();
880
889
self.active_cell = None;
881
890
self.table_picker = None;
891
self.format_popup = None;
892
self.format_overflow = false;
882
893
self.sync_tables(window, cx);
883
894
self.history.clear();
884
895
self.history_index = 0;
@@ -993,6 +1004,9 @@ impl Composer {
993
1004
}
994
1005
995
1006
fn press_format(&mut self, button: FormatButton, window: &mut Window, cx: &mut Context<Self>) {
1007
if !button.opens_popup() {
1008
self.format_overflow = false;
1009
}
996
1010
match button {
997
1011
FormatButton::Bold => self.toggle_mark(MarkKind::Bold, cx),
998
1012
FormatButton::Italic => self.toggle_mark(MarkKind::Italic, cx),
@@ -1019,6 +1033,18 @@ impl Composer {
1019
1033
FormatButton::TableRemoveLine => {
1020
1034
self.open_table_menu(TableLineMenu::Remove, window, cx);
1021
1035
}
1036
FormatButton::Highlight => self.toggle_format_popup(FormatPopup::Highlight, cx),
1037
FormatButton::FontColor => self.toggle_format_popup(FormatPopup::FontColor, cx),
1038
FormatButton::ParagraphStyle => {
1039
self.toggle_format_popup(FormatPopup::ParagraphStyle, cx)
1040
}
1041
FormatButton::ClearFormatting => self.clear_formatting(window, cx),
1042
FormatButton::Outdent => self.indent_blocks(true, window, cx),
1043
FormatButton::Indent => self.indent_blocks(false, window, cx),
1044
FormatButton::CodeBlock => self.toggle_code_block(window, cx),
1045
FormatButton::Rule => self.insert_rule(window, cx),
1046
FormatButton::FontSize => self.toggle_format_popup(FormatPopup::FontSize, cx),
1047
FormatButton::More => self.toggle_format_overflow(cx),
1022
1048
}
1023
1049
}
1024
1050
@@ -1098,6 +1124,31 @@ impl Composer {
1098
1124
FormatButton::Table | FormatButton::TableInsertLine | FormatButton::TableRemoveLine => {
1099
1125
FormatState::Off
1100
1126
}
1127
FormatButton::Highlight if self.format_popup == Some(FormatPopup::Highlight) => {
1128
FormatState::On
1129
}
1130
FormatButton::FontColor if self.format_popup == Some(FormatPopup::FontColor) => {
1131
FormatState::On
1132
}
1133
FormatButton::ParagraphStyle
1134
if self.format_popup == Some(FormatPopup::ParagraphStyle) =>
1135
{
1136
FormatState::On
1137
}
1138
FormatButton::FontSize if self.format_popup == Some(FormatPopup::FontSize) => {
1139
FormatState::On
1140
}
1141
FormatButton::More if self.format_overflow => FormatState::On,
1142
FormatButton::CodeBlock => self.draft.line_state(range, &LineKind::Code(None)),
1143
FormatButton::Highlight
1144
| FormatButton::FontColor
1145
| FormatButton::FontSize
1146
| FormatButton::More
1147
| FormatButton::ParagraphStyle
1148
| FormatButton::ClearFormatting
1149
| FormatButton::Outdent
1150
| FormatButton::Indent
1151
| FormatButton::Rule => FormatState::Off,
1101
1152
}
1102
1153
}
1103
1154
@@ -1110,13 +1161,20 @@ impl Composer {
1110
1161
) -> ButtonState {
1111
1162
let enabled = match button {
1112
1163
FormatButton::TableInsertLine | FormatButton::TableRemoveLine => in_table,
1113
FormatButton::Table => true,
1164
FormatButton::Table | FormatButton::More => true,
1165
FormatButton::Outdent => !in_table && self.draft.can_outdent(selection.clone()),
1114
1166
_ => !in_table,
1115
1167
};
1116
if enabled {
1168
let state = if enabled {
1117
1169
ButtonState::enabled(self.format_state(button, selection))
1118
1170
} else {
1119
1171
ButtonState::disabled()
1172
};
1173
match button {
1174
FormatButton::ParagraphStyle => {
1175
state.with_label(paragraph_label(self.draft.heading_at(selection.start)))
1176
}
1177
_ => state,
1120
1178
}
1121
1179
}
1122
1180
@@ -1133,6 +1191,8 @@ impl Composer {
1133
1191
self.format_bar.remove(&key);
1134
1192
self.table_picker = None;
1135
1193
self.table_menu = None;
1194
self.format_popup = None;
1195
self.format_overflow = false;
1136
1196
}
1137
1197
cx.notify();
1138
1198
}
@@ -1690,6 +1750,8 @@ impl Composer {
1690
1750
self.schedule = None;
1691
1751
self.table_picker = None;
1692
1752
self.table_menu = None;
1753
self.format_popup = None;
1754
self.format_overflow = false;
1693
1755
self.reset_importance();
1694
1756
if !carry {
1695
1757
self.load_stored_draft(conversation_id, window, cx);
@@ -2526,6 +2588,10 @@ impl Composer {
2526
2588
),
2527
2589
None => {
2528
2590
let state_of = |button| ButtonState::enabled(self.format_state(button, &range));
2591
let mut overlay = |button| match button {
2592
FormatButton::FontSize => self.render_format_popup(FormatPopup::FontSize, cx),
2593
_ => None,
2594
};
2529
2595
format_toolbar::render(
2530
2596
placement,
2531
2597
format_toolbar::Mode::Bar {
@@ -2535,6 +2601,7 @@ impl Composer {
2535
2601
.update(cx, |this, cx| this.press_format(button, window, cx))
2536
2602
.ok();
2537
2603
}),
2604
overlay: &mut overlay,
2538
2605
},
2539
2606
)
2540
2607
}
@@ -2542,23 +2609,65 @@ impl Composer {
2542
2609
Some(element)
2543
2610
}
2544
2611
2545
fn render_format_bar(&self, window: &Window, cx: &mut Context<Self>) -> AnyElement {
2546
let selection = self.selection(cx);
2547
let in_table = self.in_table(window, cx);
2548
let state_of = |button| self.button_state(button, &selection, in_table);
2612
fn format_press_handler(&self, cx: &mut Context<Self>) -> format_toolbar::PressHandler {
2549
2613
let composer = cx.weak_entity();
2550
let on_press: format_toolbar::PressHandler = Rc::new(move |button, window, cx| {
2614
Rc::new(move |button, window, cx| {
2551
2615
composer
2552
2616
.update(cx, |this, cx| this.press_format(button, window, cx))
2553
2617
.ok();
2618
})
2619
}
2620
2621
fn format_bar_fit(&self) -> format_toolbar::BarFit {
2622
let available = self.composer_bounds.get().map_or(f32::INFINITY, |bounds| {
2623
f32::from(bounds.size.width) - 2. * (COMPOSER_BUTTON_INSET + 1.)
2554
2624
});
2555
let mut overlay = |button| match button {
2625
format_toolbar::fit_groups(available, &format_toolbar::BAR_GROUPS)
2626
}
2627
2628
fn render_format_overlay(
2629
&self,
2630
button: FormatButton,
2631
overflow: &[Vec<FormatButton>],
2632
window: &Window,
2633
cx: &mut Context<Self>,
2634
) -> Option<AnyElement> {
2635
match button {
2556
2636
FormatButton::Table => self.render_table_picker(cx),
2557
2637
FormatButton::TableInsertLine => self.render_table_menu(TableLineMenu::Insert, cx),
2558
2638
FormatButton::TableRemoveLine => self.render_table_menu(TableLineMenu::Remove, cx),
2639
FormatButton::Highlight => self.render_format_popup(FormatPopup::Highlight, cx),
2640
FormatButton::FontColor => self.render_format_popup(FormatPopup::FontColor, cx),
2641
FormatButton::FontSize => self.render_format_popup(FormatPopup::FontSize, cx),
2642
FormatButton::ParagraphStyle => {
2643
self.render_format_popup(FormatPopup::ParagraphStyle, cx)
2644
}
2645
FormatButton::More if self.format_overflow => {
2646
let selection = self.selection(cx);
2647
let in_table = self.in_table(window, cx);
2648
let state_of = |button| self.button_state(button, &selection, in_table);
2649
let on_press = self.format_press_handler(cx);
2650
let mut overlay = |button| self.render_format_overlay(button, &[], window, cx);
2651
let menu = format_toolbar::render_overflow_menu(
2652
overflow,
2653
&state_of,
2654
on_press,
2655
&mut overlay,
2656
);
2657
Some(self.render_overflow_surface(menu, cx))
2658
}
2559
2659
_ => None,
2560
};
2561
let row = format_toolbar::render_format_bar(&state_of, on_press, &mut overlay);
2660
}
2661
}
2662
2663
fn render_format_bar(&self, window: &Window, cx: &mut Context<Self>) -> AnyElement {
2664
let selection = self.selection(cx);
2665
let in_table = self.in_table(window, cx);
2666
let state_of = |button| self.button_state(button, &selection, in_table);
2667
let on_press = self.format_press_handler(cx);
2668
let fit = self.format_bar_fit();
2669
let mut overlay = |button| self.render_format_overlay(button, &fit.overflow, window, cx);
2670
let row = format_toolbar::render_format_bar(&fit, &state_of, on_press, &mut overlay);
2562
2671
v_flex()
2563
2672
.debug_selector(|| COMPOSER_FORMAT_BAR_TAG.into())
2564
2673
.w_full()
@@ -2832,6 +2941,13 @@ impl Render for Composer {
2832
2941
.unwrap_or(false)
2833
2942
})
2834
2943
.token(move |context, _, cx| {
2944
if context.is_block() && is_rule_token(context.token()) {
2945
return render_rule_token(
2946
context.available_width(),
2947
context.line_height(),
2948
context.is_selected(),
2949
);
2950
}
2835
2951
if context.is_block() && is_table_token(context.token()) {
2836
2952
let token_id = context.token().id().to_string();
2837
2953
let width = context.available_width();
@@ -2993,6 +3109,26 @@ impl Render for Composer {
2993
3109
.on_action(cx.listener(|this, _: &RemoveTableLine, window, cx| {
2994
3110
this.open_table_menu(TableLineMenu::Remove, window, cx);
2995
3111
}))
3112
.on_action(cx.listener(|this, _: &SetParagraph, window, cx| {
3113
this.set_paragraph_style(None, window, cx)
3114
}))
3115
.on_action(cx.listener(|this, _: &SetHeading1, window, cx| {
3116
this.set_paragraph_style(Some(1), window, cx)
3117
}))
3118
.on_action(cx.listener(|this, _: &SetHeading2, window, cx| {
3119
this.set_paragraph_style(Some(2), window, cx)
3120
}))
3121
.on_action(cx.listener(|this, _: &SetHeading3, window, cx| {
3122
this.set_paragraph_style(Some(3), window, cx)
3123
}))
3124
.on_action(cx.listener(|this, _: &ToggleCodeBlock, window, cx| {
3125
this.toggle_code_block(window, cx)
3126
}))
3127
.on_action(cx.listener(|this, _: &ToggleQuote, window, cx| {
3128
if !this.cell_has_focus(window, cx) {
3129
this.toggle_lines(LineKind::Quote, window, cx)
3130
}
3131
}))
2996
3132
.capture_action(cx.listener(|this, _: &Undo, window, cx| {
2997
3133
if this.link_editor.is_none() {
2998
3134
this.step_history(true, window, cx);
@@ -3208,7 +3344,14 @@ impl Render for Composer {
3208
3344
})
3209
3345
.child(
3210
3346
canvas(
3211
move |bounds, _, _| composer_bounds.set(Some(bounds)),
3347
move |bounds, window, _| {
3348
let previous = composer_bounds.replace(Some(bounds));
3349
if previous.map(|previous| previous.size.width)
3350
!= Some(bounds.size.width)
3351
{
3352
window.refresh();
3353
}
3354
},
3212
3355
|_, _, _, _| {},
3213
3356
)
3214
3357
.absolute()
@@ -4341,7 +4484,7 @@ mod tests {
4341
4484
typist.press("enter");
4342
4485
typist.type_text("b");
4343
4486
typist.press("up end delete");
4344
assert_eq!(typist.outgoing().html(), "<pre>ab</pre>");
4487
assert_eq!(typist.outgoing().html(), "<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>ab</code></pre>");
4345
4488
}
4346
4489
4347
4490
#[gpui_kit::test]
@@ -4499,7 +4642,7 @@ mod tests {
4499
4642
.update(|cx| composer.read(cx).paste_hint.is_none())
4500
4643
);
4501
4644
let outgoing = typist.outgoing();
4502
assert_eq!(outgoing.html(), "<pre>:) **x**</pre>");
4645
assert_eq!(outgoing.html(), "<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>:) **x**</code></pre>");
4503
4646
}
4504
4647
4505
4648
#[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::{@@ -63,6 +66,8 @@ use crate::runtime;63
use crate::scheduled_rows::scheduled_label;66
use crate::scheduled_rows::scheduled_label;64
use crate::theme::{self, ElevatedSurface as _};67
use crate::theme::{self, ElevatedSurface as _};65
use crate::typing::OutgoingTyping;68
use crate::typing::OutgoingTyping;69
use format_menus::{FormatPopup, paragraph_label};70
use rule::{is_rule_token, render_rule_token};66
use table::{TableKey, TableLineMenu, TableMenu, TablePicker, TableViews, is_table_token};71
use table::{TableKey, TableLineMenu, TableMenu, TablePicker, TableViews, is_table_token};67
72
68
const MIN_ROWS: usize = 1;73
const MIN_ROWS: usize = 1;@@ -225,6 +230,8 @@ pub struct Composer {225
table_counter: usize,230
table_counter: usize,226
table_picker: Option<TablePicker>,231
table_picker: Option<TablePicker>,227
table_menu: Option<TableMenu>,232
table_menu: Option<TableMenu>,233
format_popup: Option<FormatPopup>,234
format_overflow: bool,228
format_bar: HashSet<String>,235
format_bar: HashSet<String>,229
active_cell: Option<(String, teams_core::Cell)>,236
active_cell: Option<(String, teams_core::Cell)>,230
caret_before_table: usize,237
caret_before_table: usize,@@ -480,6 +487,8 @@ impl Composer {480
table_counter: 0,487
table_counter: 0,481
table_picker: None,488
table_picker: None,482
table_menu: None,489
table_menu: None,490
format_popup: None,491
format_overflow: false,483
format_bar: HashSet::new(),492
format_bar: HashSet::new(),484
active_cell: None,493
active_cell: None,485
caret_before_table: 0,494
caret_before_table: 0,@@ -879,6 +888,8 @@ impl Composer {879
self.pending_anchors.clear();888
self.pending_anchors.clear();880
self.active_cell = None;889
self.active_cell = None;881
self.table_picker = None;890
self.table_picker = None;891
self.format_popup = None;892
self.format_overflow = false;882
self.sync_tables(window, cx);893
self.sync_tables(window, cx);883
self.history.clear();894
self.history.clear();884
self.history_index = 0;895
self.history_index = 0;@@ -993,6 +1004,9 @@ impl Composer {993
}1004
}994
1005
995
fn press_format(&mut self, button: FormatButton, window: &mut Window, cx: &mut Context<Self>) {1006
fn press_format(&mut self, button: FormatButton, window: &mut Window, cx: &mut Context<Self>) {1007
if !button.opens_popup() {1008
self.format_overflow = false;1009
}996
match button {1010
match button {997
FormatButton::Bold => self.toggle_mark(MarkKind::Bold, cx),1011
FormatButton::Bold => self.toggle_mark(MarkKind::Bold, cx),998
FormatButton::Italic => self.toggle_mark(MarkKind::Italic, cx),1012
FormatButton::Italic => self.toggle_mark(MarkKind::Italic, cx),@@ -1019,6 +1033,18 @@ impl Composer {1019
FormatButton::TableRemoveLine => {1033
FormatButton::TableRemoveLine => {1020
self.open_table_menu(TableLineMenu::Remove, window, cx);1034
self.open_table_menu(TableLineMenu::Remove, window, cx);1021
}1035
}1036
FormatButton::Highlight => self.toggle_format_popup(FormatPopup::Highlight, cx),1037
FormatButton::FontColor => self.toggle_format_popup(FormatPopup::FontColor, cx),1038
FormatButton::ParagraphStyle => {1039
self.toggle_format_popup(FormatPopup::ParagraphStyle, cx)1040
}1041
FormatButton::ClearFormatting => self.clear_formatting(window, cx),1042
FormatButton::Outdent => self.indent_blocks(true, window, cx),1043
FormatButton::Indent => self.indent_blocks(false, window, cx),1044
FormatButton::CodeBlock => self.toggle_code_block(window, cx),1045
FormatButton::Rule => self.insert_rule(window, cx),1046
FormatButton::FontSize => self.toggle_format_popup(FormatPopup::FontSize, cx),1047
FormatButton::More => self.toggle_format_overflow(cx),1022
}1048
}1023
}1049
}1024
1050
@@ -1098,6 +1124,31 @@ impl Composer {1098
FormatButton::Table | FormatButton::TableInsertLine | FormatButton::TableRemoveLine => {1124
FormatButton::Table | FormatButton::TableInsertLine | FormatButton::TableRemoveLine => {1099
FormatState::Off1125
FormatState::Off1100
}1126
}1127
FormatButton::Highlight if self.format_popup == Some(FormatPopup::Highlight) => {1128
FormatState::On1129
}1130
FormatButton::FontColor if self.format_popup == Some(FormatPopup::FontColor) => {1131
FormatState::On1132
}1133
FormatButton::ParagraphStyle1134
if self.format_popup == Some(FormatPopup::ParagraphStyle) =>1135
{1136
FormatState::On1137
}1138
FormatButton::FontSize if self.format_popup == Some(FormatPopup::FontSize) => {1139
FormatState::On1140
}1141
FormatButton::More if self.format_overflow => FormatState::On,1142
FormatButton::CodeBlock => self.draft.line_state(range, &LineKind::Code(None)),1143
FormatButton::Highlight1144
| FormatButton::FontColor1145
| FormatButton::FontSize1146
| FormatButton::More1147
| FormatButton::ParagraphStyle1148
| FormatButton::ClearFormatting1149
| FormatButton::Outdent1150
| FormatButton::Indent1151
| FormatButton::Rule => FormatState::Off,1101
}1152
}1102
}1153
}1103
1154
@@ -1110,13 +1161,20 @@ impl Composer {1110
) -> ButtonState {1161
) -> ButtonState {1111
let enabled = match button {1162
let enabled = match button {1112
FormatButton::TableInsertLine | FormatButton::TableRemoveLine => in_table,1163
FormatButton::TableInsertLine | FormatButton::TableRemoveLine => in_table,1113
FormatButton::Table => true,1164
FormatButton::Table | FormatButton::More => true,1165
FormatButton::Outdent => !in_table && self.draft.can_outdent(selection.clone()),1114
_ => !in_table,1166
_ => !in_table,1115
};1167
};1116
if enabled {1168
let state = if enabled {1117
ButtonState::enabled(self.format_state(button, selection))1169
ButtonState::enabled(self.format_state(button, selection))1118
} else {1170
} else {1119
ButtonState::disabled()1171
ButtonState::disabled()1172
};1173
match button {1174
FormatButton::ParagraphStyle => {1175
state.with_label(paragraph_label(self.draft.heading_at(selection.start)))1176
}1177
_ => state,1120
}1178
}1121
}1179
}1122
1180
@@ -1133,6 +1191,8 @@ impl Composer {1133
self.format_bar.remove(&key);1191
self.format_bar.remove(&key);1134
self.table_picker = None;1192
self.table_picker = None;1135
self.table_menu = None;1193
self.table_menu = None;1194
self.format_popup = None;1195
self.format_overflow = false;1136
}1196
}1137
cx.notify();1197
cx.notify();1138
}1198
}@@ -1690,6 +1750,8 @@ impl Composer {1690
self.schedule = None;1750
self.schedule = None;1691
self.table_picker = None;1751
self.table_picker = None;1692
self.table_menu = None;1752
self.table_menu = None;1753
self.format_popup = None;1754
self.format_overflow = false;1693
self.reset_importance();1755
self.reset_importance();1694
if !carry {1756
if !carry {1695
self.load_stored_draft(conversation_id, window, cx);1757
self.load_stored_draft(conversation_id, window, cx);@@ -2526,6 +2588,10 @@ impl Composer {2526
),2588
),2527
None => {2589
None => {2528
let state_of = |button| ButtonState::enabled(self.format_state(button, &range));2590
let state_of = |button| ButtonState::enabled(self.format_state(button, &range));2591
let mut overlay = |button| match button {2592
FormatButton::FontSize => self.render_format_popup(FormatPopup::FontSize, cx),2593
_ => None,2594
};2529
format_toolbar::render(2595
format_toolbar::render(2530
placement,2596
placement,2531
format_toolbar::Mode::Bar {2597
format_toolbar::Mode::Bar {@@ -2535,6 +2601,7 @@ impl Composer {2535
.update(cx, |this, cx| this.press_format(button, window, cx))2601
.update(cx, |this, cx| this.press_format(button, window, cx))2536
.ok();2602
.ok();2537
}),2603
}),2604
overlay: &mut overlay,2538
},2605
},2539
)2606
)2540
}2607
}@@ -2542,23 +2609,65 @@ impl Composer {2542
Some(element)2609
Some(element)2543
}2610
}2544
2611
2545
fn render_format_bar(&self, window: &Window, cx: &mut Context<Self>) -> AnyElement {2612
fn format_press_handler(&self, cx: &mut Context<Self>) -> format_toolbar::PressHandler {2546
let selection = self.selection(cx);2547
let in_table = self.in_table(window, cx);2548
let state_of = |button| self.button_state(button, &selection, in_table);2549
let composer = cx.weak_entity();2613
let composer = cx.weak_entity();2550
let on_press: format_toolbar::PressHandler = Rc::new(move |button, window, cx| {2614
Rc::new(move |button, window, cx| {2551
composer2615
composer2552
.update(cx, |this, cx| this.press_format(button, window, cx))2616
.update(cx, |this, cx| this.press_format(button, window, cx))2553
.ok();2617
.ok();2618
})2619
}2620
2621
fn format_bar_fit(&self) -> format_toolbar::BarFit {2622
let available = self.composer_bounds.get().map_or(f32::INFINITY, |bounds| {2623
f32::from(bounds.size.width) - 2. * (COMPOSER_BUTTON_INSET + 1.)2554
});2624
});2555
let mut overlay = |button| match button {2625
format_toolbar::fit_groups(available, &format_toolbar::BAR_GROUPS)2626
}2627
2628
fn render_format_overlay(2629
&self,2630
button: FormatButton,2631
overflow: &[Vec<FormatButton>],2632
window: &Window,2633
cx: &mut Context<Self>,2634
) -> Option<AnyElement> {2635
match button {2556
FormatButton::Table => self.render_table_picker(cx),2636
FormatButton::Table => self.render_table_picker(cx),2557
FormatButton::TableInsertLine => self.render_table_menu(TableLineMenu::Insert, cx),2637
FormatButton::TableInsertLine => self.render_table_menu(TableLineMenu::Insert, cx),2558
FormatButton::TableRemoveLine => self.render_table_menu(TableLineMenu::Remove, cx),2638
FormatButton::TableRemoveLine => self.render_table_menu(TableLineMenu::Remove, cx),2639
FormatButton::Highlight => self.render_format_popup(FormatPopup::Highlight, cx),2640
FormatButton::FontColor => self.render_format_popup(FormatPopup::FontColor, cx),2641
FormatButton::FontSize => self.render_format_popup(FormatPopup::FontSize, cx),2642
FormatButton::ParagraphStyle => {2643
self.render_format_popup(FormatPopup::ParagraphStyle, cx)2644
}2645
FormatButton::More if self.format_overflow => {2646
let selection = self.selection(cx);2647
let in_table = self.in_table(window, cx);2648
let state_of = |button| self.button_state(button, &selection, in_table);2649
let on_press = self.format_press_handler(cx);2650
let mut overlay = |button| self.render_format_overlay(button, &[], window, cx);2651
let menu = format_toolbar::render_overflow_menu(2652
overflow,2653
&state_of,2654
on_press,2655
&mut overlay,2656
);2657
Some(self.render_overflow_surface(menu, cx))2658
}2559
_ => None,2659
_ => None,2560
};2660
}2561
let row = format_toolbar::render_format_bar(&state_of, on_press, &mut overlay);2661
}2662
2663
fn render_format_bar(&self, window: &Window, cx: &mut Context<Self>) -> AnyElement {2664
let selection = self.selection(cx);2665
let in_table = self.in_table(window, cx);2666
let state_of = |button| self.button_state(button, &selection, in_table);2667
let on_press = self.format_press_handler(cx);2668
let fit = self.format_bar_fit();2669
let mut overlay = |button| self.render_format_overlay(button, &fit.overflow, window, cx);2670
let row = format_toolbar::render_format_bar(&fit, &state_of, on_press, &mut overlay);2562
v_flex()2671
v_flex()2563
.debug_selector(|| COMPOSER_FORMAT_BAR_TAG.into())2672
.debug_selector(|| COMPOSER_FORMAT_BAR_TAG.into())2564
.w_full()2673
.w_full()@@ -2832,6 +2941,13 @@ impl Render for Composer {2832
.unwrap_or(false)2941
.unwrap_or(false)2833
})2942
})2834
.token(move |context, _, cx| {2943
.token(move |context, _, cx| {2944
if context.is_block() && is_rule_token(context.token()) {2945
return render_rule_token(2946
context.available_width(),2947
context.line_height(),2948
context.is_selected(),2949
);2950
}2835
if context.is_block() && is_table_token(context.token()) {2951
if context.is_block() && is_table_token(context.token()) {2836
let token_id = context.token().id().to_string();2952
let token_id = context.token().id().to_string();2837
let width = context.available_width();2953
let width = context.available_width();@@ -2993,6 +3109,26 @@ impl Render for Composer {2993
.on_action(cx.listener(|this, _: &RemoveTableLine, window, cx| {3109
.on_action(cx.listener(|this, _: &RemoveTableLine, window, cx| {2994
this.open_table_menu(TableLineMenu::Remove, window, cx);3110
this.open_table_menu(TableLineMenu::Remove, window, cx);2995
}))3111
}))3112
.on_action(cx.listener(|this, _: &SetParagraph, window, cx| {3113
this.set_paragraph_style(None, window, cx)3114
}))3115
.on_action(cx.listener(|this, _: &SetHeading1, window, cx| {3116
this.set_paragraph_style(Some(1), window, cx)3117
}))3118
.on_action(cx.listener(|this, _: &SetHeading2, window, cx| {3119
this.set_paragraph_style(Some(2), window, cx)3120
}))3121
.on_action(cx.listener(|this, _: &SetHeading3, window, cx| {3122
this.set_paragraph_style(Some(3), window, cx)3123
}))3124
.on_action(cx.listener(|this, _: &ToggleCodeBlock, window, cx| {3125
this.toggle_code_block(window, cx)3126
}))3127
.on_action(cx.listener(|this, _: &ToggleQuote, window, cx| {3128
if !this.cell_has_focus(window, cx) {3129
this.toggle_lines(LineKind::Quote, window, cx)3130
}3131
}))2996
.capture_action(cx.listener(|this, _: &Undo, window, cx| {3132
.capture_action(cx.listener(|this, _: &Undo, window, cx| {2997
if this.link_editor.is_none() {3133
if this.link_editor.is_none() {2998
this.step_history(true, window, cx);3134
this.step_history(true, window, cx);@@ -3208,7 +3344,14 @@ impl Render for Composer {3208
})3344
})3209
.child(3345
.child(3210
canvas(3346
canvas(3211
move |bounds, _, _| composer_bounds.set(Some(bounds)),3347
move |bounds, window, _| {3348
let previous = composer_bounds.replace(Some(bounds));3349
if previous.map(|previous| previous.size.width)3350
!= Some(bounds.size.width)3351
{3352
window.refresh();3353
}3354
},3212
|_, _, _, _| {},3355
|_, _, _, _| {},3213
)3356
)3214
.absolute()3357
.absolute()@@ -4341,7 +4484,7 @@ mod tests {4341
typist.press("enter");4484
typist.press("enter");4342
typist.type_text("b");4485
typist.type_text("b");4343
typist.press("up end delete");4486
typist.press("up end delete");4344
assert_eq!(typist.outgoing().html(), "<pre>ab</pre>");4487
assert_eq!(typist.outgoing().html(), "<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>ab</code></pre>");4345
}4488
}4346
4489
4347
#[gpui_kit::test]4490
#[gpui_kit::test]@@ -4499,7 +4642,7 @@ mod tests {4499
.update(|cx| composer.read(cx).paste_hint.is_none())4642
.update(|cx| composer.read(cx).paste_hint.is_none())4500
);4643
);4501
let outgoing = typist.outgoing();4644
let outgoing = typist.outgoing();4502
assert_eq!(outgoing.html(), "<pre>:) **x**</pre>");4645
assert_eq!(outgoing.html(), "<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>:) **x**</code></pre>");4503
}4646
}4504
4647
4505
#[gpui_kit::test]4648
#[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(@@ -1,12 +1,14 @@
1
1
use std::rc::Rc;
2
2
3
3
use gpui_kit::component::input::{Input, InputState};
4
use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
4
use gpui_kit::component::tooltip::PopupTriggerTooltip as _;
5
use gpui_kit::component::{h_flex, v_flex};
5
6
use gpui_kit::prelude::FluentBuilder as _;
7
use gpui_kit::assets::IconName;
6
8
use gpui_kit::*;
7
9
use teams_core::FormatState;
8
10
9
use super::widgets::symbol;
11
use super::widgets::{icon, symbol};
10
12
use crate::theme::{self, ElevatedSurface as _};
11
13
12
14
const PADDING: f32 = 4.;
@@ -46,6 +48,16 @@ pub enum FormatButton {
46
48
Table,
47
49
TableInsertLine,
48
50
TableRemoveLine,
51
Highlight,
52
FontColor,
53
ParagraphStyle,
54
ClearFormatting,
55
Outdent,
56
Indent,
57
CodeBlock,
58
Rule,
59
FontSize,
60
More,
49
61
}
50
62
51
63
const STYLE_GROUP: &[FormatButton] = &[
@@ -55,11 +67,7 @@ const STYLE_GROUP: &[FormatButton] = &[
55
67
FormatButton::Strike,
56
68
];
57
69
const SCRIPT_GROUP: &[FormatButton] = &[FormatButton::Superscript, FormatButton::Subscript];
58
const SIZE_GROUP: &[FormatButton] = &[
59
FormatButton::SizeSmall,
60
FormatButton::SizeNormal,
61
FormatButton::SizeLarge,
62
];
70
const SIZE_GROUP: &[FormatButton] = &[FormatButton::FontSize];
63
71
const INLINE_GROUP: &[FormatButton] = &[FormatButton::Code, FormatButton::Link];
64
72
const LINE_GROUP: &[FormatButton] = &[
65
73
FormatButton::Bulleted,
@@ -72,6 +80,27 @@ const TABLE_GROUP: &[FormatButton] = &[
72
80
FormatButton::TableRemoveLine,
73
81
];
74
82
83
const FONT_GROUP: &[FormatButton] = &[
84
FormatButton::Highlight,
85
FormatButton::FontColor,
86
FormatButton::FontSize,
87
FormatButton::ParagraphStyle,
88
FormatButton::ClearFormatting,
89
];
90
const PARAGRAPH_GROUP: &[FormatButton] = &[
91
FormatButton::Outdent,
92
FormatButton::Indent,
93
FormatButton::Bulleted,
94
FormatButton::Numbered,
95
];
96
const INSERT_GROUP: &[FormatButton] = &[
97
FormatButton::Quote,
98
FormatButton::Link,
99
FormatButton::Code,
100
FormatButton::CodeBlock,
101
FormatButton::Rule,
102
];
103
75
104
/// The floating bar over a selection: text formats only, tables live in the format bar.
76
105
pub const SELECTION_GROUPS: [&[FormatButton]; 5] = [
77
106
STYLE_GROUP,
@@ -81,16 +110,70 @@ pub const SELECTION_GROUPS: [&[FormatButton]; 5] = [
81
110
LINE_GROUP,
82
111
];
83
112
84
/// The format bar the Format button opens, table group second to last like Teams.
113
/// The format bar the Format button opens, in Teams' group order; Teams' last group (undo,
114
/// redo) is left out, so the table group ends the bar.
85
115
pub const BAR_GROUPS: [&[FormatButton]; 6] = [
86
116
STYLE_GROUP,
87
117
SCRIPT_GROUP,
88
SIZE_GROUP,
89
INLINE_GROUP,
118
FONT_GROUP,
119
PARAGRAPH_GROUP,
120
INSERT_GROUP,
90
121
TABLE_GROUP,
91
LINE_GROUP,
92
122
];
93
123
124
pub const PARAGRAPH_STYLE_WIDTH: f32 = 104.;
125
const SEPARATOR_WIDTH: f32 = 1. + 2. * SEPARATOR_MARGIN;
126
const MENU_ROW_HEIGHT: f32 = 32.;
127
const MENU_ROW_PADDING_X: f32 = 10.;
128
const MENU_PADDING: f32 = 4.;
129
const MENU_WIDTH: f32 = 220.;
130
131
/// The format bar split like Teams' overflow: buttons leave from the end into More options,
132
/// each side keeps the group boundaries of its own buttons.
133
#[derive(Debug, Clone, PartialEq, Eq)]
134
pub struct BarFit {
135
pub visible: Vec<Vec<FormatButton>>,
136
pub overflow: Vec<Vec<FormatButton>>,
137
}
138
139
fn groups_width<G: AsRef<[FormatButton]>>(groups: &[G]) -> f32 {
140
let buttons = groups.iter().flat_map(|group| group.as_ref().iter());
141
let widths: f32 = buttons.clone().map(|button| button.width()).sum();
142
let gaps = buttons.count().saturating_sub(1) as f32 * BUTTON_GAP;
143
let separators = groups.len().saturating_sub(1) as f32 * (SEPARATOR_WIDTH + BUTTON_GAP);
144
widths + gaps + separators
145
}
146
147
fn split_groups(groups: &[&[FormatButton]], count: usize) -> BarFit {
148
let mut visible = Vec::new();
149
let mut overflow = Vec::new();
150
let mut taken = 0;
151
for group in groups {
152
let shown = group.len().min(count - taken.min(count));
153
taken += group.len();
154
if shown > 0 {
155
visible.push(group[..shown].to_vec());
156
}
157
if shown < group.len() {
158
overflow.push(group[shown..].to_vec());
159
}
160
}
161
BarFit { visible, overflow }
162
}
163
164
pub fn fit_groups(available: f32, groups: &[&[FormatButton]]) -> BarFit {
165
let total: usize = groups.iter().map(|group| group.len()).sum();
166
if groups_width(groups) <= available {
167
return split_groups(groups, total);
168
}
169
let more = BUTTON_GAP + FormatButton::More.width();
170
let count = (0..total)
171
.rev()
172
.find(|count| groups_width(&split_groups(groups, *count).visible) + more <= available)
173
.unwrap_or(0);
174
split_groups(groups, count)
175
}
176
94
177
pub const TOGGLE_SHORTCUT: &str = "Ctrl+Shift+X";
95
178
96
179
pub fn toggle_tooltip(open: bool) -> String {
@@ -114,6 +197,7 @@ pub fn toggle_symbol(open: bool) -> &'static str {
114
197
pub struct ButtonState {
115
198
pub format: FormatState,
116
199
pub enabled: bool,
200
pub label: Option<&'static str>,
117
201
}
118
202
119
203
impl ButtonState {
@@ -121,6 +205,7 @@ impl ButtonState {
121
205
ButtonState {
122
206
format,
123
207
enabled: true,
208
label: None,
124
209
}
125
210
}
126
211
@@ -128,6 +213,14 @@ impl ButtonState {
128
213
ButtonState {
129
214
format: FormatState::Off,
130
215
enabled: false,
216
label: None,
217
}
218
}
219
220
pub fn with_label(self, label: &'static str) -> Self {
221
ButtonState {
222
label: Some(label),
223
..self
131
224
}
132
225
}
133
226
}
@@ -148,14 +241,44 @@ impl FormatButton {
148
241
FormatButton::Link => "Link (Ctrl+K)",
149
242
FormatButton::Bulleted => "Bulleted list",
150
243
FormatButton::Numbered => "Numbered list",
151
FormatButton::Quote => "Quote",
244
FormatButton::Quote => "Quote (Ctrl+Alt+4)",
152
245
FormatButton::Table => "Insert table",
153
246
FormatButton::TableInsertLine => "Insert column or row (Ctrl+Alt+=)",
154
247
FormatButton::TableRemoveLine => "Delete column, row, or table (Ctrl+Alt+-)",
248
FormatButton::Highlight => "Text highlight colour",
249
FormatButton::FontColor => "Font colour",
250
FormatButton::ParagraphStyle => "Rich style",
251
FormatButton::ClearFormatting => "Clear all formatting",
252
FormatButton::Outdent => "Decrease indent",
253
FormatButton::Indent => "Increase indent",
254
FormatButton::CodeBlock => "Code block (Ctrl+Shift+B)",
255
FormatButton::Rule => "Insert horizontal rule",
256
FormatButton::FontSize => "Font size",
257
FormatButton::More => "More options",
155
258
}
156
259
}
157
260
158
fn content(self, color: Hsla) -> AnyElement {
261
pub fn menu_label(self) -> &'static str {
262
let tooltip = self.tooltip();
263
tooltip.split(" (").next().unwrap_or(tooltip)
264
}
265
266
/// Opens a picker or menu below itself instead of acting at once.
267
pub fn opens_popup(self) -> bool {
268
matches!(
269
self,
270
FormatButton::Highlight
271
| FormatButton::FontColor
272
| FormatButton::FontSize
273
| FormatButton::ParagraphStyle
274
| FormatButton::Table
275
| FormatButton::TableInsertLine
276
| FormatButton::TableRemoveLine
277
| FormatButton::More
278
)
279
}
280
281
fn content(self, color: Hsla, label: Option<&'static str>) -> AnyElement {
159
282
let letter = |text: &'static str| div().text_size(px(15.)).text_color(color).child(text);
160
283
match self {
161
284
FormatButton::Bold => letter("B").font_weight(FontWeight::BOLD).into_any_element(),
@@ -179,6 +302,41 @@ impl FormatButton {
179
302
FormatButton::TableRemoveLine => {
180
303
symbol("fluent_table_dismiss", 20., color).into_any_element()
181
304
}
305
FormatButton::Highlight => symbol("fluent_highlight", 20., color).into_any_element(),
306
FormatButton::FontColor => symbol("fluent_text_color", 20., color).into_any_element(),
307
FormatButton::ParagraphStyle => h_flex()
308
.w_full()
309
.px(px(6.))
310
.gap(px(4.))
311
.items_center()
312
.justify_between()
313
.text_size(px(13.))
314
.text_color(color)
315
.child(label.unwrap_or_default())
316
.child(icon(IconName::ChevronDown, 12., color))
317
.into_any_element(),
318
FormatButton::ClearFormatting => {
319
symbol("fluent_text_clear_formatting", 20., color).into_any_element()
320
}
321
FormatButton::Outdent => {
322
symbol("fluent_text_indent_decrease", 20., color).into_any_element()
323
}
324
FormatButton::Indent => {
325
symbol("fluent_text_indent_increase", 20., color).into_any_element()
326
}
327
FormatButton::CodeBlock => symbol("fluent_code_block", 20., color).into_any_element(),
328
FormatButton::Rule => symbol("fluent_line_horizontal_1", 20., color).into_any_element(),
329
FormatButton::FontSize => {
330
symbol("fluent_text_font_size", 20., color).into_any_element()
331
}
332
FormatButton::More => icon(IconName::Ellipsis, 18., color).into_any_element(),
333
}
334
}
335
336
fn width(self) -> f32 {
337
match self {
338
FormatButton::ParagraphStyle => PARAGRAPH_STYLE_WIDTH,
339
_ => BUTTON,
182
340
}
183
341
}
184
342
}
@@ -207,11 +365,7 @@ fn sized_letter(size: f32, color: Hsla) -> AnyElement {
207
365
}
208
366
209
367
pub fn bar_width() -> f32 {
210
let groups = SELECTION_GROUPS;
211
let buttons: usize = groups.iter().map(|group| group.len()).sum();
212
let gaps: usize = groups.iter().map(|group| group.len() - 1).sum();
213
let separators = (groups.len() - 1) as f32 * (1. + 2. * SEPARATOR_MARGIN);
214
2. * PADDING + buttons as f32 * BUTTON + gaps as f32 * BUTTON_GAP + separators
368
2. * PADDING + groups_width(&SELECTION_GROUPS)
215
369
}
216
370
217
371
pub fn link_width() -> f32 {
@@ -248,6 +402,7 @@ pub enum Mode<'a> {
248
402
Bar {
249
403
state: &'a dyn Fn(FormatButton) -> ButtonState,
250
404
on_press: PressHandler,
405
overlay: &'a mut dyn FnMut(FormatButton) -> Option<AnyElement>,
251
406
},
252
407
Link {
253
408
field: &'a Entity<InputState>,
@@ -271,14 +426,15 @@ fn button(
271
426
div()
272
427
.id(ElementId::Name(format!("format-{format:?}").into()))
273
428
.relative()
274
.size(px(BUTTON))
429
.w(px(format.width()))
430
.h(px(BUTTON))
275
431
.flex()
276
432
.flex_none()
277
433
.items_center()
278
434
.justify_center()
279
435
.rounded(px(6.))
280
.tooltip(move |window, cx| Tooltip::new(format.tooltip()).build(window, cx))
281
.child(format.content(color))
436
.popup_trigger_tooltip_text(format.opens_popup() && on, format.tooltip())
437
.child(format.content(color, state.label))
282
438
.on_mouse_down(MouseButton::Left, |_, window, cx| {
283
439
window.prevent_default();
284
440
cx.stop_propagation();
@@ -305,16 +461,18 @@ fn button(
305
461
})
306
462
.on_click(move |_, window, cx| on_press(format, window, cx))
307
463
})
308
.children(overlay.map(|overlay| {
309
div().absolute().top(px(BUTTON + GAP / 2.)).left_0().child(
310
deferred(
311
anchored()
312
.snap_to_window_with_margin(px(GAP))
313
.child(overlay),
314
)
315
.with_priority(2),
316
)
317
}))
464
.children(overlay.map(|overlay| overlay_below(overlay, BUTTON + GAP / 2.)))
465
}
466
467
fn overlay_below(overlay: AnyElement, offset: f32) -> Div {
468
div().absolute().top(px(offset)).left_0().child(
469
deferred(
470
anchored()
471
.snap_to_window_with_margin(px(GAP))
472
.child(overlay),
473
)
474
.with_priority(2),
475
)
318
476
}
319
477
320
478
fn separator() -> Div {
@@ -325,18 +483,18 @@ fn separator() -> Div {
325
483
.bg(theme::popup_hover())
326
484
}
327
485
328
fn groups_row(
329
groups: &[&[FormatButton]],
486
fn groups_row<G: AsRef<[FormatButton]>>(
487
groups: &[G],
330
488
state: &dyn Fn(FormatButton) -> ButtonState,
331
489
on_press: PressHandler,
332
490
overlay: &mut dyn FnMut(FormatButton) -> Option<AnyElement>,
333
491
) -> Div {
334
let mut row = h_flex().flex_wrap().gap(px(BUTTON_GAP)).items_center();
492
let mut row = h_flex().gap(px(BUTTON_GAP)).items_center();
335
493
for (index, group) in groups.iter().enumerate() {
336
494
if index > 0 {
337
495
row = row.child(separator());
338
496
}
339
for format in group.iter().copied() {
497
for format in group.as_ref().iter().copied() {
340
498
row = row.child(button(
341
499
format,
342
500
state(format),
@@ -348,17 +506,111 @@ fn groups_row(
348
506
row
349
507
}
350
508
351
fn bar(state: &dyn Fn(FormatButton) -> ButtonState, on_press: PressHandler) -> Div {
352
groups_row(&SELECTION_GROUPS, state, on_press, &mut |_| None)
509
fn bar(
510
state: &dyn Fn(FormatButton) -> ButtonState,
511
on_press: PressHandler,
512
overlay: &mut dyn FnMut(FormatButton) -> Option<AnyElement>,
513
) -> Div {
514
groups_row(&SELECTION_GROUPS, state, on_press, overlay)
353
515
}
354
516
355
/// The format bar inside the composer box. `overlay` hangs a popup under a button.
517
/// The format bar inside the composer box. `overlay` hangs a popup under a button; the
518
/// More button's popup is the overflow menu, built with `render_overflow_menu`.
356
519
pub fn render_format_bar(
520
fit: &BarFit,
357
521
state: &dyn Fn(FormatButton) -> ButtonState,
358
522
on_press: PressHandler,
359
523
overlay: &mut dyn FnMut(FormatButton) -> Option<AnyElement>,
360
524
) -> Div {
361
groups_row(&BAR_GROUPS, state, on_press, overlay)
525
let row = groups_row(&fit.visible, state, on_press.clone(), overlay);
526
if fit.overflow.is_empty() {
527
return row;
528
}
529
row.child(button(
530
FormatButton::More,
531
state(FormatButton::More),
532
on_press,
533
overlay(FormatButton::More),
534
))
535
}
536
537
/// The groups that do not fit, as menu rows with a divider between groups.
538
pub fn render_overflow_menu(
539
groups: &[Vec<FormatButton>],
540
state: &dyn Fn(FormatButton) -> ButtonState,
541
on_press: PressHandler,
542
overlay: &mut dyn FnMut(FormatButton) -> Option<AnyElement>,
543
) -> Div {
544
let mut menu = v_flex().w(px(MENU_WIDTH)).py(px(MENU_PADDING));
545
for (index, group) in groups.iter().enumerate() {
546
if index > 0 {
547
menu = menu.child(
548
div()
549
.w_full()
550
.h(px(1.))
551
.my(px(MENU_PADDING))
552
.bg(theme::popup_hover()),
553
);
554
}
555
for format in group.iter().copied() {
556
menu = menu.child(menu_row(
557
format,
558
state(format),
559
on_press.clone(),
560
overlay(format),
561
));
562
}
563
}
564
menu
565
}
566
567
fn menu_row(
568
format: FormatButton,
569
state: ButtonState,
570
on_press: PressHandler,
571
overlay: Option<AnyElement>,
572
) -> impl IntoElement {
573
let on = state.enabled && state.format == FormatState::On;
574
let color = if on {
575
theme::accent_soft()
576
} else {
577
theme::text_soft()
578
};
579
let content = match format {
580
FormatButton::ParagraphStyle => symbol("fluent_text_header_1", 20., color).into_any_element(),
581
_ => format.content(color, None),
582
};
583
div()
584
.id(ElementId::Name(format!("format-overflow-{format:?}").into()))
585
.relative()
586
.mx(px(MENU_PADDING))
587
.h(px(MENU_ROW_HEIGHT))
588
.flex_none()
589
.px(px(MENU_ROW_PADDING_X))
590
.flex()
591
.items_center()
592
.gap(px(GAP))
593
.rounded(px(6.))
594
.child(div().w(px(BUTTON)).flex().justify_center().child(content))
595
.child(
596
div()
597
.flex_1()
598
.text_size(px(13.))
599
.text_color(theme::text())
600
.child(format.menu_label()),
601
)
602
.on_mouse_down(MouseButton::Left, |_, window, cx| {
603
window.prevent_default();
604
cx.stop_propagation();
605
})
606
.when(!state.enabled, |row| row.opacity(DISABLED_OPACITY))
607
.when(state.enabled, |row| {
608
row.cursor_pointer()
609
.when(on, |row| row.bg(theme::accent().opacity(ACTIVE_ALPHA)))
610
.hover(|row| row.bg(theme::popup_hover()))
611
.on_click(move |_, window, cx| on_press(format, window, cx))
612
})
613
.children(overlay.map(|overlay| overlay_below(overlay, MENU_ROW_HEIGHT)))
362
614
}
363
615
364
616
fn link_editor(field: &Entity<InputState>, refused: bool, on_apply: ApplyHandler) -> Div {
@@ -440,7 +692,11 @@ fn arrow(offset: Pixels) -> impl IntoElement {
440
692
441
693
pub fn render(placement: Placement, mode: Mode<'_>) -> AnyElement {
442
694
let content = match mode {
443
Mode::Bar { state, on_press } => bar(state, on_press),
695
Mode::Bar {
696
state,
697
on_press,
698
overlay,
699
} => bar(state, on_press, overlay),
444
700
Mode::Link {
445
701
field,
446
702
refused,
@@ -474,10 +730,11 @@ mod tests {
474
730
use gpui_kit::px;
475
731
476
732
use super::{
477
ARROW_MARGIN, BAR_GROUPS, BUTTON, FormatButton, SELECTION_GROUPS, bar_width, place,
478
toggle_symbol, toggle_tooltip,
733
ARROW_MARGIN, BAR_GROUPS, BUTTON, FormatButton, SELECTION_GROUPS, bar_width, fit_groups,
734
groups_width, place, toggle_symbol, toggle_tooltip,
479
735
};
480
736
737
481
738
#[test]
482
739
fn the_bar_centers_over_the_selection() {
483
740
let placement = place(px(400.), px(300.), (px(100.), px(900.)), 200.);
@@ -510,32 +767,101 @@ mod tests {
510
767
.iter()
511
768
.map(|group| group.len())
512
769
.sum::<usize>(),
513
14
770
12
514
771
);
515
772
assert!(
516
773
SELECTION_GROUPS
517
774
.iter()
518
775
.all(|group| !group.contains(&FormatButton::Table))
519
776
);
520
assert!(bar_width() > 14. * BUTTON);
777
assert!(SELECTION_GROUPS.iter().any(|group| group == &[FormatButton::FontSize]));
778
assert!(bar_width() > 12. * BUTTON);
521
779
}
522
780
523
781
#[test]
524
fn the_format_bar_has_the_teams_table_group_second_to_last() {
525
let table_group = BAR_GROUPS[BAR_GROUPS.len() - 2];
782
fn the_format_bar_follows_the_teams_groups_and_keeps_every_selection_format() {
526
783
assert_eq!(
527
table_group,
784
BAR_GROUPS[BAR_GROUPS.len() - 1],
528
785
&[
529
786
FormatButton::Table,
530
787
FormatButton::TableInsertLine,
531
788
FormatButton::TableRemoveLine
532
789
][..]
533
790
);
534
for group in SELECTION_GROUPS {
535
assert!(BAR_GROUPS.contains(&group));
791
assert_eq!(
792
BAR_GROUPS[2][..3],
793
[
794
FormatButton::Highlight,
795
FormatButton::FontColor,
796
FormatButton::FontSize
797
]
798
);
799
assert_eq!(
800
BAR_GROUPS[3],
801
&[
802
FormatButton::Outdent,
803
FormatButton::Indent,
804
FormatButton::Bulleted,
805
FormatButton::Numbered
806
][..]
807
);
808
assert_eq!(BAR_GROUPS[4].last(), Some(&FormatButton::Rule));
809
for button in SELECTION_GROUPS.iter().flat_map(|group| group.iter()) {
810
assert!(BAR_GROUPS.iter().any(|group| group.contains(button)));
536
811
}
537
812
}
538
813
814
fn flat(groups: &[Vec<FormatButton>]) -> Vec<FormatButton> {
815
groups.iter().flatten().copied().collect()
816
}
817
818
#[test]
819
fn a_wide_bar_shows_every_button_without_more_options() {
820
let fit = fit_groups(groups_width(&BAR_GROUPS), &BAR_GROUPS);
821
assert_eq!(fit.visible.len(), BAR_GROUPS.len());
822
assert!(fit.overflow.is_empty());
823
}
824
825
#[test]
826
fn single_buttons_leave_from_the_end_and_keep_their_groups() {
827
let all: Vec<FormatButton> = BAR_GROUPS.iter().flat_map(|group| group.iter()).copied().collect();
828
let fit = fit_groups(groups_width(&BAR_GROUPS) - 1., &BAR_GROUPS);
829
assert_eq!(flat(&fit.overflow), all[all.len() - 2..]);
830
assert_eq!(fit.overflow, vec![vec![FormatButton::TableInsertLine, FormatButton::TableRemoveLine]]);
831
assert_eq!(fit.visible.last(), Some(&vec![FormatButton::Table]));
832
let mut both = flat(&fit.visible);
833
both.extend(flat(&fit.overflow));
834
assert_eq!(both, all);
835
}
836
837
#[test]
838
fn a_cut_between_groups_leaves_no_empty_group_on_either_side() {
839
let two = groups_width(&BAR_GROUPS[..2]);
840
let fit = fit_groups(two + 2. + BUTTON, &BAR_GROUPS);
841
assert_eq!(fit.visible, vec![BAR_GROUPS[0].to_vec(), BAR_GROUPS[1].to_vec()]);
842
assert_eq!(fit.overflow.len(), BAR_GROUPS.len() - 2);
843
assert!(fit.overflow.iter().chain(&fit.visible).all(|group| !group.is_empty()));
844
let fit = fit_groups(two + 2. + BUTTON - 1., &BAR_GROUPS);
845
assert_eq!(fit.visible.len(), 2);
846
assert_eq!(fit.visible[1], vec![FormatButton::Superscript]);
847
assert_eq!(fit.overflow[0], vec![FormatButton::Subscript]);
848
}
849
850
#[test]
851
fn a_tiny_bar_keeps_only_more_options() {
852
let fit = fit_groups(BUTTON, &BAR_GROUPS);
853
assert!(fit.visible.is_empty());
854
assert_eq!(fit.overflow.len(), BAR_GROUPS.len());
855
}
856
857
#[test]
858
fn overflow_rows_read_without_the_shortcut() {
859
assert_eq!(FormatButton::CodeBlock.menu_label(), "Code block");
860
assert_eq!(FormatButton::Rule.menu_label(), "Insert horizontal rule");
861
assert_eq!(FormatButton::More.tooltip(), "More options");
862
assert_eq!(FormatButton::FontSize.tooltip(), "Font size");
863
}
864
539
865
#[test]
540
866
fn the_format_toggle_reads_like_teams() {
541
867
assert_eq!(
@@ -1,12 +1,14 @@1
use std::rc::Rc;1
use std::rc::Rc;2
2
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::tooltip::PopupTriggerTooltip as _;5
use gpui_kit::component::{h_flex, v_flex};5
use gpui_kit::prelude::FluentBuilder as _;6
use gpui_kit::prelude::FluentBuilder as _;7
use gpui_kit::assets::IconName;6
use gpui_kit::*;8
use gpui_kit::*;7
use teams_core::FormatState;9
use teams_core::FormatState;8
10
9
use super::widgets::symbol;11
use super::widgets::{icon, symbol};10
use crate::theme::{self, ElevatedSurface as _};12
use crate::theme::{self, ElevatedSurface as _};11
13
12
const PADDING: f32 = 4.;14
const PADDING: f32 = 4.;@@ -46,6 +48,16 @@ pub enum FormatButton {46
Table,48
Table,47
TableInsertLine,49
TableInsertLine,48
TableRemoveLine,50
TableRemoveLine,51
Highlight,52
FontColor,53
ParagraphStyle,54
ClearFormatting,55
Outdent,56
Indent,57
CodeBlock,58
Rule,59
FontSize,60
More,49
}61
}50
62
51
const STYLE_GROUP: &[FormatButton] = &[63
const STYLE_GROUP: &[FormatButton] = &[@@ -55,11 +67,7 @@ const STYLE_GROUP: &[FormatButton] = &[55
FormatButton::Strike,67
FormatButton::Strike,56
];68
];57
const SCRIPT_GROUP: &[FormatButton] = &[FormatButton::Superscript, FormatButton::Subscript];69
const SCRIPT_GROUP: &[FormatButton] = &[FormatButton::Superscript, FormatButton::Subscript];58
const SIZE_GROUP: &[FormatButton] = &[70
const SIZE_GROUP: &[FormatButton] = &[FormatButton::FontSize];59
FormatButton::SizeSmall,60
FormatButton::SizeNormal,61
FormatButton::SizeLarge,62
];63
const INLINE_GROUP: &[FormatButton] = &[FormatButton::Code, FormatButton::Link];71
const INLINE_GROUP: &[FormatButton] = &[FormatButton::Code, FormatButton::Link];64
const LINE_GROUP: &[FormatButton] = &[72
const LINE_GROUP: &[FormatButton] = &[65
FormatButton::Bulleted,73
FormatButton::Bulleted,@@ -72,6 +80,27 @@ const TABLE_GROUP: &[FormatButton] = &[72
FormatButton::TableRemoveLine,80
FormatButton::TableRemoveLine,73
];81
];74
82
83
const FONT_GROUP: &[FormatButton] = &[84
FormatButton::Highlight,85
FormatButton::FontColor,86
FormatButton::FontSize,87
FormatButton::ParagraphStyle,88
FormatButton::ClearFormatting,89
];90
const PARAGRAPH_GROUP: &[FormatButton] = &[91
FormatButton::Outdent,92
FormatButton::Indent,93
FormatButton::Bulleted,94
FormatButton::Numbered,95
];96
const INSERT_GROUP: &[FormatButton] = &[97
FormatButton::Quote,98
FormatButton::Link,99
FormatButton::Code,100
FormatButton::CodeBlock,101
FormatButton::Rule,102
];103
75
/// The floating bar over a selection: text formats only, tables live in the format bar.104
/// The floating bar over a selection: text formats only, tables live in the format bar.76
pub const SELECTION_GROUPS: [&[FormatButton]; 5] = [105
pub const SELECTION_GROUPS: [&[FormatButton]; 5] = [77
STYLE_GROUP,106
STYLE_GROUP,@@ -81,16 +110,70 @@ pub const SELECTION_GROUPS: [&[FormatButton]; 5] = [81
LINE_GROUP,110
LINE_GROUP,82
];111
];83
112
84
/// The format bar the Format button opens, table group second to last like Teams.113
/// The format bar the Format button opens, in Teams' group order; Teams' last group (undo,114
/// redo) is left out, so the table group ends the bar.85
pub const BAR_GROUPS: [&[FormatButton]; 6] = [115
pub const BAR_GROUPS: [&[FormatButton]; 6] = [86
STYLE_GROUP,116
STYLE_GROUP,87
SCRIPT_GROUP,117
SCRIPT_GROUP,88
SIZE_GROUP,118
FONT_GROUP,89
INLINE_GROUP,119
PARAGRAPH_GROUP,120
INSERT_GROUP,90
TABLE_GROUP,121
TABLE_GROUP,91
LINE_GROUP,92
];122
];93
123
124
pub const PARAGRAPH_STYLE_WIDTH: f32 = 104.;125
const SEPARATOR_WIDTH: f32 = 1. + 2. * SEPARATOR_MARGIN;126
const MENU_ROW_HEIGHT: f32 = 32.;127
const MENU_ROW_PADDING_X: f32 = 10.;128
const MENU_PADDING: f32 = 4.;129
const MENU_WIDTH: f32 = 220.;130
131
/// The format bar split like Teams' overflow: buttons leave from the end into More options,132
/// each side keeps the group boundaries of its own buttons.133
#[derive(Debug, Clone, PartialEq, Eq)]134
pub struct BarFit {135
pub visible: Vec<Vec<FormatButton>>,136
pub overflow: Vec<Vec<FormatButton>>,137
}138
139
fn groups_width<G: AsRef<[FormatButton]>>(groups: &[G]) -> f32 {140
let buttons = groups.iter().flat_map(|group| group.as_ref().iter());141
let widths: f32 = buttons.clone().map(|button| button.width()).sum();142
let gaps = buttons.count().saturating_sub(1) as f32 * BUTTON_GAP;143
let separators = groups.len().saturating_sub(1) as f32 * (SEPARATOR_WIDTH + BUTTON_GAP);144
widths + gaps + separators145
}146
147
fn split_groups(groups: &[&[FormatButton]], count: usize) -> BarFit {148
let mut visible = Vec::new();149
let mut overflow = Vec::new();150
let mut taken = 0;151
for group in groups {152
let shown = group.len().min(count - taken.min(count));153
taken += group.len();154
if shown > 0 {155
visible.push(group[..shown].to_vec());156
}157
if shown < group.len() {158
overflow.push(group[shown..].to_vec());159
}160
}161
BarFit { visible, overflow }162
}163
164
pub fn fit_groups(available: f32, groups: &[&[FormatButton]]) -> BarFit {165
let total: usize = groups.iter().map(|group| group.len()).sum();166
if groups_width(groups) <= available {167
return split_groups(groups, total);168
}169
let more = BUTTON_GAP + FormatButton::More.width();170
let count = (0..total)171
.rev()172
.find(|count| groups_width(&split_groups(groups, *count).visible) + more <= available)173
.unwrap_or(0);174
split_groups(groups, count)175
}176
94
pub const TOGGLE_SHORTCUT: &str = "Ctrl+Shift+X";177
pub const TOGGLE_SHORTCUT: &str = "Ctrl+Shift+X";95
178
96
pub fn toggle_tooltip(open: bool) -> String {179
pub fn toggle_tooltip(open: bool) -> String {@@ -114,6 +197,7 @@ pub fn toggle_symbol(open: bool) -> &'static str {114
pub struct ButtonState {197
pub struct ButtonState {115
pub format: FormatState,198
pub format: FormatState,116
pub enabled: bool,199
pub enabled: bool,200
pub label: Option<&'static str>,117
}201
}118
202
119
impl ButtonState {203
impl ButtonState {@@ -121,6 +205,7 @@ impl ButtonState {121
ButtonState {205
ButtonState {122
format,206
format,123
enabled: true,207
enabled: true,208
label: None,124
}209
}125
}210
}126
211
@@ -128,6 +213,14 @@ impl ButtonState {128
ButtonState {213
ButtonState {129
format: FormatState::Off,214
format: FormatState::Off,130
enabled: false,215
enabled: false,216
label: None,217
}218
}219
220
pub fn with_label(self, label: &'static str) -> Self {221
ButtonState {222
label: Some(label),223
..self131
}224
}132
}225
}133
}226
}@@ -148,14 +241,44 @@ impl FormatButton {148
FormatButton::Link => "Link (Ctrl+K)",241
FormatButton::Link => "Link (Ctrl+K)",149
FormatButton::Bulleted => "Bulleted list",242
FormatButton::Bulleted => "Bulleted list",150
FormatButton::Numbered => "Numbered list",243
FormatButton::Numbered => "Numbered list",151
FormatButton::Quote => "Quote",244
FormatButton::Quote => "Quote (Ctrl+Alt+4)",152
FormatButton::Table => "Insert table",245
FormatButton::Table => "Insert table",153
FormatButton::TableInsertLine => "Insert column or row (Ctrl+Alt+=)",246
FormatButton::TableInsertLine => "Insert column or row (Ctrl+Alt+=)",154
FormatButton::TableRemoveLine => "Delete column, row, or table (Ctrl+Alt+-)",247
FormatButton::TableRemoveLine => "Delete column, row, or table (Ctrl+Alt+-)",248
FormatButton::Highlight => "Text highlight colour",249
FormatButton::FontColor => "Font colour",250
FormatButton::ParagraphStyle => "Rich style",251
FormatButton::ClearFormatting => "Clear all formatting",252
FormatButton::Outdent => "Decrease indent",253
FormatButton::Indent => "Increase indent",254
FormatButton::CodeBlock => "Code block (Ctrl+Shift+B)",255
FormatButton::Rule => "Insert horizontal rule",256
FormatButton::FontSize => "Font size",257
FormatButton::More => "More options",155
}258
}156
}259
}157
260
158
fn content(self, color: Hsla) -> AnyElement {261
pub fn menu_label(self) -> &'static str {262
let tooltip = self.tooltip();263
tooltip.split(" (").next().unwrap_or(tooltip)264
}265
266
/// Opens a picker or menu below itself instead of acting at once.267
pub fn opens_popup(self) -> bool {268
matches!(269
self,270
FormatButton::Highlight271
| FormatButton::FontColor272
| FormatButton::FontSize273
| FormatButton::ParagraphStyle274
| FormatButton::Table275
| FormatButton::TableInsertLine276
| FormatButton::TableRemoveLine277
| FormatButton::More278
)279
}280
281
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);282
let letter = |text: &'static str| div().text_size(px(15.)).text_color(color).child(text);160
match self {283
match self {161
FormatButton::Bold => letter("B").font_weight(FontWeight::BOLD).into_any_element(),284
FormatButton::Bold => letter("B").font_weight(FontWeight::BOLD).into_any_element(),@@ -179,6 +302,41 @@ impl FormatButton {179
FormatButton::TableRemoveLine => {302
FormatButton::TableRemoveLine => {180
symbol("fluent_table_dismiss", 20., color).into_any_element()303
symbol("fluent_table_dismiss", 20., color).into_any_element()181
}304
}305
FormatButton::Highlight => symbol("fluent_highlight", 20., color).into_any_element(),306
FormatButton::FontColor => symbol("fluent_text_color", 20., color).into_any_element(),307
FormatButton::ParagraphStyle => h_flex()308
.w_full()309
.px(px(6.))310
.gap(px(4.))311
.items_center()312
.justify_between()313
.text_size(px(13.))314
.text_color(color)315
.child(label.unwrap_or_default())316
.child(icon(IconName::ChevronDown, 12., color))317
.into_any_element(),318
FormatButton::ClearFormatting => {319
symbol("fluent_text_clear_formatting", 20., color).into_any_element()320
}321
FormatButton::Outdent => {322
symbol("fluent_text_indent_decrease", 20., color).into_any_element()323
}324
FormatButton::Indent => {325
symbol("fluent_text_indent_increase", 20., color).into_any_element()326
}327
FormatButton::CodeBlock => symbol("fluent_code_block", 20., color).into_any_element(),328
FormatButton::Rule => symbol("fluent_line_horizontal_1", 20., color).into_any_element(),329
FormatButton::FontSize => {330
symbol("fluent_text_font_size", 20., color).into_any_element()331
}332
FormatButton::More => icon(IconName::Ellipsis, 18., color).into_any_element(),333
}334
}335
336
fn width(self) -> f32 {337
match self {338
FormatButton::ParagraphStyle => PARAGRAPH_STYLE_WIDTH,339
_ => BUTTON,182
}340
}183
}341
}184
}342
}@@ -207,11 +365,7 @@ fn sized_letter(size: f32, color: Hsla) -> AnyElement {207
}365
}208
366
209
pub fn bar_width() -> f32 {367
pub fn bar_width() -> f32 {210
let groups = SELECTION_GROUPS;368
2. * PADDING + groups_width(&SELECTION_GROUPS)211
let buttons: usize = groups.iter().map(|group| group.len()).sum();212
let gaps: usize = groups.iter().map(|group| group.len() - 1).sum();213
let separators = (groups.len() - 1) as f32 * (1. + 2. * SEPARATOR_MARGIN);214
2. * PADDING + buttons as f32 * BUTTON + gaps as f32 * BUTTON_GAP + separators215
}369
}216
370
217
pub fn link_width() -> f32 {371
pub fn link_width() -> f32 {@@ -248,6 +402,7 @@ pub enum Mode<'a> {248
Bar {402
Bar {249
state: &'a dyn Fn(FormatButton) -> ButtonState,403
state: &'a dyn Fn(FormatButton) -> ButtonState,250
on_press: PressHandler,404
on_press: PressHandler,405
overlay: &'a mut dyn FnMut(FormatButton) -> Option<AnyElement>,251
},406
},252
Link {407
Link {253
field: &'a Entity<InputState>,408
field: &'a Entity<InputState>,@@ -271,14 +426,15 @@ fn button(271
div()426
div()272
.id(ElementId::Name(format!("format-{format:?}").into()))427
.id(ElementId::Name(format!("format-{format:?}").into()))273
.relative()428
.relative()274
.size(px(BUTTON))429
.w(px(format.width()))430
.h(px(BUTTON))275
.flex()431
.flex()276
.flex_none()432
.flex_none()277
.items_center()433
.items_center()278
.justify_center()434
.justify_center()279
.rounded(px(6.))435
.rounded(px(6.))280
.tooltip(move |window, cx| Tooltip::new(format.tooltip()).build(window, cx))436
.popup_trigger_tooltip_text(format.opens_popup() && on, format.tooltip())281
.child(format.content(color))437
.child(format.content(color, state.label))282
.on_mouse_down(MouseButton::Left, |_, window, cx| {438
.on_mouse_down(MouseButton::Left, |_, window, cx| {283
window.prevent_default();439
window.prevent_default();284
cx.stop_propagation();440
cx.stop_propagation();@@ -305,16 +461,18 @@ fn button(305
})461
})306
.on_click(move |_, window, cx| on_press(format, window, cx))462
.on_click(move |_, window, cx| on_press(format, window, cx))307
})463
})308
.children(overlay.map(|overlay| {464
.children(overlay.map(|overlay| overlay_below(overlay, BUTTON + GAP / 2.)))309
div().absolute().top(px(BUTTON + GAP / 2.)).left_0().child(465
}310
deferred(466
311
anchored()467
fn overlay_below(overlay: AnyElement, offset: f32) -> Div {312
.snap_to_window_with_margin(px(GAP))468
div().absolute().top(px(offset)).left_0().child(313
.child(overlay),469
deferred(314
)470
anchored()315
.with_priority(2),471
.snap_to_window_with_margin(px(GAP))316
)472
.child(overlay),317
}))473
)474
.with_priority(2),475
)318
}476
}319
477
320
fn separator() -> Div {478
fn separator() -> Div {@@ -325,18 +483,18 @@ fn separator() -> Div {325
.bg(theme::popup_hover())483
.bg(theme::popup_hover())326
}484
}327
485
328
fn groups_row(486
fn groups_row<G: AsRef<[FormatButton]>>(329
groups: &[&[FormatButton]],487
groups: &[G],330
state: &dyn Fn(FormatButton) -> ButtonState,488
state: &dyn Fn(FormatButton) -> ButtonState,331
on_press: PressHandler,489
on_press: PressHandler,332
overlay: &mut dyn FnMut(FormatButton) -> Option<AnyElement>,490
overlay: &mut dyn FnMut(FormatButton) -> Option<AnyElement>,333
) -> Div {491
) -> Div {334
let mut row = h_flex().flex_wrap().gap(px(BUTTON_GAP)).items_center();492
let mut row = h_flex().gap(px(BUTTON_GAP)).items_center();335
for (index, group) in groups.iter().enumerate() {493
for (index, group) in groups.iter().enumerate() {336
if index > 0 {494
if index > 0 {337
row = row.child(separator());495
row = row.child(separator());338
}496
}339
for format in group.iter().copied() {497
for format in group.as_ref().iter().copied() {340
row = row.child(button(498
row = row.child(button(341
format,499
format,342
state(format),500
state(format),@@ -348,17 +506,111 @@ fn groups_row(348
row506
row349
}507
}350
508
351
fn bar(state: &dyn Fn(FormatButton) -> ButtonState, on_press: PressHandler) -> Div {509
fn bar(352
groups_row(&SELECTION_GROUPS, state, on_press, &mut |_| None)510
state: &dyn Fn(FormatButton) -> ButtonState,511
on_press: PressHandler,512
overlay: &mut dyn FnMut(FormatButton) -> Option<AnyElement>,513
) -> Div {514
groups_row(&SELECTION_GROUPS, state, on_press, overlay)353
}515
}354
516
355
/// The format bar inside the composer box. `overlay` hangs a popup under a button.517
/// The format bar inside the composer box. `overlay` hangs a popup under a button; the518
/// More button's popup is the overflow menu, built with `render_overflow_menu`.356
pub fn render_format_bar(519
pub fn render_format_bar(520
fit: &BarFit,357
state: &dyn Fn(FormatButton) -> ButtonState,521
state: &dyn Fn(FormatButton) -> ButtonState,358
on_press: PressHandler,522
on_press: PressHandler,359
overlay: &mut dyn FnMut(FormatButton) -> Option<AnyElement>,523
overlay: &mut dyn FnMut(FormatButton) -> Option<AnyElement>,360
) -> Div {524
) -> Div {361
groups_row(&BAR_GROUPS, state, on_press, overlay)525
let row = groups_row(&fit.visible, state, on_press.clone(), overlay);526
if fit.overflow.is_empty() {527
return row;528
}529
row.child(button(530
FormatButton::More,531
state(FormatButton::More),532
on_press,533
overlay(FormatButton::More),534
))535
}536
537
/// The groups that do not fit, as menu rows with a divider between groups.538
pub fn render_overflow_menu(539
groups: &[Vec<FormatButton>],540
state: &dyn Fn(FormatButton) -> ButtonState,541
on_press: PressHandler,542
overlay: &mut dyn FnMut(FormatButton) -> Option<AnyElement>,543
) -> Div {544
let mut menu = v_flex().w(px(MENU_WIDTH)).py(px(MENU_PADDING));545
for (index, group) in groups.iter().enumerate() {546
if index > 0 {547
menu = menu.child(548
div()549
.w_full()550
.h(px(1.))551
.my(px(MENU_PADDING))552
.bg(theme::popup_hover()),553
);554
}555
for format in group.iter().copied() {556
menu = menu.child(menu_row(557
format,558
state(format),559
on_press.clone(),560
overlay(format),561
));562
}563
}564
menu565
}566
567
fn menu_row(568
format: FormatButton,569
state: ButtonState,570
on_press: PressHandler,571
overlay: Option<AnyElement>,572
) -> impl IntoElement {573
let on = state.enabled && state.format == FormatState::On;574
let color = if on {575
theme::accent_soft()576
} else {577
theme::text_soft()578
};579
let content = match format {580
FormatButton::ParagraphStyle => symbol("fluent_text_header_1", 20., color).into_any_element(),581
_ => format.content(color, None),582
};583
div()584
.id(ElementId::Name(format!("format-overflow-{format:?}").into()))585
.relative()586
.mx(px(MENU_PADDING))587
.h(px(MENU_ROW_HEIGHT))588
.flex_none()589
.px(px(MENU_ROW_PADDING_X))590
.flex()591
.items_center()592
.gap(px(GAP))593
.rounded(px(6.))594
.child(div().w(px(BUTTON)).flex().justify_center().child(content))595
.child(596
div()597
.flex_1()598
.text_size(px(13.))599
.text_color(theme::text())600
.child(format.menu_label()),601
)602
.on_mouse_down(MouseButton::Left, |_, window, cx| {603
window.prevent_default();604
cx.stop_propagation();605
})606
.when(!state.enabled, |row| row.opacity(DISABLED_OPACITY))607
.when(state.enabled, |row| {608
row.cursor_pointer()609
.when(on, |row| row.bg(theme::accent().opacity(ACTIVE_ALPHA)))610
.hover(|row| row.bg(theme::popup_hover()))611
.on_click(move |_, window, cx| on_press(format, window, cx))612
})613
.children(overlay.map(|overlay| overlay_below(overlay, MENU_ROW_HEIGHT)))362
}614
}363
615
364
fn link_editor(field: &Entity<InputState>, refused: bool, on_apply: ApplyHandler) -> Div {616
fn link_editor(field: &Entity<InputState>, refused: bool, on_apply: ApplyHandler) -> Div {@@ -440,7 +692,11 @@ fn arrow(offset: Pixels) -> impl IntoElement {440
692
441
pub fn render(placement: Placement, mode: Mode<'_>) -> AnyElement {693
pub fn render(placement: Placement, mode: Mode<'_>) -> AnyElement {442
let content = match mode {694
let content = match mode {443
Mode::Bar { state, on_press } => bar(state, on_press),695
Mode::Bar {696
state,697
on_press,698
overlay,699
} => bar(state, on_press, overlay),444
Mode::Link {700
Mode::Link {445
field,701
field,446
refused,702
refused,@@ -474,10 +730,11 @@ mod tests {474
use gpui_kit::px;730
use gpui_kit::px;475
731
476
use super::{732
use super::{477
ARROW_MARGIN, BAR_GROUPS, BUTTON, FormatButton, SELECTION_GROUPS, bar_width, place,733
ARROW_MARGIN, BAR_GROUPS, BUTTON, FormatButton, SELECTION_GROUPS, bar_width, fit_groups,478
toggle_symbol, toggle_tooltip,734
groups_width, place, toggle_symbol, toggle_tooltip,479
};735
};480
736
737
481
#[test]738
#[test]482
fn the_bar_centers_over_the_selection() {739
fn the_bar_centers_over_the_selection() {483
let placement = place(px(400.), px(300.), (px(100.), px(900.)), 200.);740
let placement = place(px(400.), px(300.), (px(100.), px(900.)), 200.);@@ -510,32 +767,101 @@ mod tests {510
.iter()767
.iter()511
.map(|group| group.len())768
.map(|group| group.len())512
.sum::<usize>(),769
.sum::<usize>(),513
14770
12514
);771
);515
assert!(772
assert!(516
SELECTION_GROUPS773
SELECTION_GROUPS517
.iter()774
.iter()518
.all(|group| !group.contains(&FormatButton::Table))775
.all(|group| !group.contains(&FormatButton::Table))519
);776
);520
assert!(bar_width() > 14. * BUTTON);777
assert!(SELECTION_GROUPS.iter().any(|group| group == &[FormatButton::FontSize]));778
assert!(bar_width() > 12. * BUTTON);521
}779
}522
780
523
#[test]781
#[test]524
fn the_format_bar_has_the_teams_table_group_second_to_last() {782
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!(783
assert_eq!(527
table_group,784
BAR_GROUPS[BAR_GROUPS.len() - 1],528
&[785
&[529
FormatButton::Table,786
FormatButton::Table,530
FormatButton::TableInsertLine,787
FormatButton::TableInsertLine,531
FormatButton::TableRemoveLine788
FormatButton::TableRemoveLine532
][..]789
][..]533
);790
);534
for group in SELECTION_GROUPS {791
assert_eq!(535
assert!(BAR_GROUPS.contains(&group));792
BAR_GROUPS[2][..3],793
[794
FormatButton::Highlight,795
FormatButton::FontColor,796
FormatButton::FontSize797
]798
);799
assert_eq!(800
BAR_GROUPS[3],801
&[802
FormatButton::Outdent,803
FormatButton::Indent,804
FormatButton::Bulleted,805
FormatButton::Numbered806
][..]807
);808
assert_eq!(BAR_GROUPS[4].last(), Some(&FormatButton::Rule));809
for button in SELECTION_GROUPS.iter().flat_map(|group| group.iter()) {810
assert!(BAR_GROUPS.iter().any(|group| group.contains(button)));536
}811
}537
}812
}538
813
814
fn flat(groups: &[Vec<FormatButton>]) -> Vec<FormatButton> {815
groups.iter().flatten().copied().collect()816
}817
818
#[test]819
fn a_wide_bar_shows_every_button_without_more_options() {820
let fit = fit_groups(groups_width(&BAR_GROUPS), &BAR_GROUPS);821
assert_eq!(fit.visible.len(), BAR_GROUPS.len());822
assert!(fit.overflow.is_empty());823
}824
825
#[test]826
fn single_buttons_leave_from_the_end_and_keep_their_groups() {827
let all: Vec<FormatButton> = BAR_GROUPS.iter().flat_map(|group| group.iter()).copied().collect();828
let fit = fit_groups(groups_width(&BAR_GROUPS) - 1., &BAR_GROUPS);829
assert_eq!(flat(&fit.overflow), all[all.len() - 2..]);830
assert_eq!(fit.overflow, vec![vec![FormatButton::TableInsertLine, FormatButton::TableRemoveLine]]);831
assert_eq!(fit.visible.last(), Some(&vec![FormatButton::Table]));832
let mut both = flat(&fit.visible);833
both.extend(flat(&fit.overflow));834
assert_eq!(both, all);835
}836
837
#[test]838
fn a_cut_between_groups_leaves_no_empty_group_on_either_side() {839
let two = groups_width(&BAR_GROUPS[..2]);840
let fit = fit_groups(two + 2. + BUTTON, &BAR_GROUPS);841
assert_eq!(fit.visible, vec![BAR_GROUPS[0].to_vec(), BAR_GROUPS[1].to_vec()]);842
assert_eq!(fit.overflow.len(), BAR_GROUPS.len() - 2);843
assert!(fit.overflow.iter().chain(&fit.visible).all(|group| !group.is_empty()));844
let fit = fit_groups(two + 2. + BUTTON - 1., &BAR_GROUPS);845
assert_eq!(fit.visible.len(), 2);846
assert_eq!(fit.visible[1], vec![FormatButton::Superscript]);847
assert_eq!(fit.overflow[0], vec![FormatButton::Subscript]);848
}849
850
#[test]851
fn a_tiny_bar_keeps_only_more_options() {852
let fit = fit_groups(BUTTON, &BAR_GROUPS);853
assert!(fit.visible.is_empty());854
assert_eq!(fit.overflow.len(), BAR_GROUPS.len());855
}856
857
#[test]858
fn overflow_rows_read_without_the_shortcut() {859
assert_eq!(FormatButton::CodeBlock.menu_label(), "Code block");860
assert_eq!(FormatButton::Rule.menu_label(), "Insert horizontal rule");861
assert_eq!(FormatButton::More.tooltip(), "More options");862
assert_eq!(FormatButton::FontSize.tooltip(), "Font size");863
}864
539
#[test]865
#[test]540
fn the_format_toggle_reads_like_teams() {866
fn the_format_toggle_reads_like_teams() {541
assert_eq!(867
assert_eq!(@@ -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
};@@ -495,6 +495,7 @@ pub(crate) fn push_plain(text: &mut String, spans: &[Span]) {
495
495
| Span::Sized(_, children)
496
496
| Span::Underline(children)
497
497
| Span::Colored { children, .. }
498
| Span::Indent { children, .. }
498
499
| Span::Quote { children, .. }
499
500
| Span::BlockQuote(children)
500
501
| Span::Link { children, .. } => push_plain(text, children),
@@ -624,6 +625,7 @@ fn link_user_mentions(spans: &mut [Span], infos: &[MentionInfo]) {
624
625
| Span::Sized(_, children)
625
626
| Span::Underline(children)
626
627
| Span::Colored { children, .. }
628
| Span::Indent { children, .. }
627
629
| Span::Heading { children, .. }
628
630
| Span::Quote { children, .. }
629
631
| Span::BlockQuote(children)
@@ -717,6 +719,7 @@ fn collect_user_mentions(spans: &[Span], infos: &[MentionInfo], inputs: &mut Vec
717
719
| Span::Sized(_, children)
718
720
| Span::Underline(children)
719
721
| Span::Colored { children, .. }
722
| Span::Indent { children, .. }
720
723
| Span::Heading { children, .. }
721
724
| Span::Quote { children, .. }
722
725
| Span::BlockQuote(children)
@@ -763,6 +766,7 @@ fn merge_split_mentions(spans: &mut Vec<Span>, mentions: &[MentionInfo]) {
763
766
| Span::Sized(_, children)
764
767
| Span::Underline(children)
765
768
| Span::Colored { children, .. }
769
| Span::Indent { children, .. }
766
770
| Span::Heading { children, .. }
767
771
| Span::Quote { children, .. }
768
772
| Span::BlockQuote(children)
@@ -495,6 +495,7 @@ pub(crate) fn push_plain(text: &mut String, spans: &[Span]) {495
| Span::Sized(_, children)495
| Span::Sized(_, children)496
| Span::Underline(children)496
| Span::Underline(children)497
| Span::Colored { children, .. }497
| Span::Colored { children, .. }498
| Span::Indent { children, .. }498
| Span::Quote { children, .. }499
| Span::Quote { children, .. }499
| Span::BlockQuote(children)500
| Span::BlockQuote(children)500
| Span::Link { children, .. } => push_plain(text, children),501
| Span::Link { children, .. } => push_plain(text, children),@@ -624,6 +625,7 @@ fn link_user_mentions(spans: &mut [Span], infos: &[MentionInfo]) {624
| Span::Sized(_, children)625
| Span::Sized(_, children)625
| Span::Underline(children)626
| Span::Underline(children)626
| Span::Colored { children, .. }627
| Span::Colored { children, .. }628
| Span::Indent { children, .. }627
| Span::Heading { children, .. }629
| Span::Heading { children, .. }628
| Span::Quote { children, .. }630
| Span::Quote { children, .. }629
| Span::BlockQuote(children)631
| Span::BlockQuote(children)@@ -717,6 +719,7 @@ fn collect_user_mentions(spans: &[Span], infos: &[MentionInfo], inputs: &mut Vec717
| Span::Sized(_, children)719
| Span::Sized(_, children)718
| Span::Underline(children)720
| Span::Underline(children)719
| Span::Colored { children, .. }721
| Span::Colored { children, .. }722
| Span::Indent { children, .. }720
| Span::Heading { children, .. }723
| Span::Heading { children, .. }721
| Span::Quote { children, .. }724
| Span::Quote { children, .. }722
| Span::BlockQuote(children)725
| Span::BlockQuote(children)@@ -763,6 +766,7 @@ fn merge_split_mentions(spans: &mut Vec<Span>, mentions: &[MentionInfo]) {763
| Span::Sized(_, children)766
| Span::Sized(_, children)764
| Span::Underline(children)767
| Span::Underline(children)765
| Span::Colored { children, .. }768
| Span::Colored { children, .. }769
| Span::Indent { children, .. }766
| Span::Heading { children, .. }770
| Span::Heading { children, .. }767
| Span::Quote { children, .. }771
| Span::Quote { children, .. }768
| Span::BlockQuote(children)772
| 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
}