feat(composer): superscript, subscript and font size
- Composer: x2 / x_2 buttons (Ctrl+Shift+= / Ctrl+=) and Small / Normal / Large. Sends <sup>, <sub> and the font-size spans Teams uses (xx-small, x-large). - Received sup/sub/sized text renders at real size with a baseline shift through a flow renderer; other messages keep the existing one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -468,7 +468,10 @@ pub fn activity_entries() -> Vec<Entry> {
468
468
RELEASE_CHAT,
469
469
Kind::Reaction,
470
470
"m3",
471
vec![actor(PRIYA_ID, "Priya Nair"), actor(LEA_ID, "Lea Schneider")],
471
vec![
472
actor(PRIYA_ID, "Priya Nair"),
473
actor(LEA_ID, "Lea Schneider"),
474
],
472
475
"I'll take the changelog.",
473
476
2,
474
477
at(0, 13, 20),
@@ -480,7 +483,10 @@ pub fn activity_entries() -> Vec<Entry> {
480
483
UNREAD_CHAT,
481
484
Kind::Messages,
482
485
"u3",
483
vec![actor(LEA_ID, "Lea Schneider"), actor(PRIYA_ID, "Priya Nair")],
486
vec![
487
actor(LEA_ID, "Lea Schneider"),
488
actor(PRIYA_ID, "Priya Nair"),
489
],
484
490
"Who is taking the review?",
485
491
3,
486
492
at(0, 13, 12),
@@ -1057,6 +1063,16 @@ fn release_messages() -> Vec<MessageRecord> {
1057
1063
&many,
1058
1064
false,
1059
1065
),
1066
message(
1067
chat,
1068
"m8",
1069
None,
1070
jonas,
1071
at(0, 13, 40),
1072
"<p>Formula check: H<sub>2</sub>O and x<sup>2</sup> + y<sup>2</sup>. <span style=\"font-size:xx-small;\">Small print, reviewed by <at id=\"0\">Mara Lindqvist</at>.</span> <span style=\"font-size:x-large;\">Big news:</span> the <span style=\"font-size:x-large;\"><a href=\"https://example.com/notes\">release notes</a></span> are out.</p>",
1073
"[]",
1074
false,
1075
),
1060
1076
]
1061
1077
}
1062
1078
@@ -468,7 +468,10 @@ pub fn activity_entries() -> Vec<Entry> {468
RELEASE_CHAT,468
RELEASE_CHAT,469
Kind::Reaction,469
Kind::Reaction,470
"m3",470
"m3",471
vec![actor(PRIYA_ID, "Priya Nair"), actor(LEA_ID, "Lea Schneider")],471
vec![472
actor(PRIYA_ID, "Priya Nair"),473
actor(LEA_ID, "Lea Schneider"),474
],472
"I'll take the changelog.",475
"I'll take the changelog.",473
2,476
2,474
at(0, 13, 20),477
at(0, 13, 20),@@ -480,7 +483,10 @@ pub fn activity_entries() -> Vec<Entry> {480
UNREAD_CHAT,483
UNREAD_CHAT,481
Kind::Messages,484
Kind::Messages,482
"u3",485
"u3",483
vec![actor(LEA_ID, "Lea Schneider"), actor(PRIYA_ID, "Priya Nair")],486
vec![487
actor(LEA_ID, "Lea Schneider"),488
actor(PRIYA_ID, "Priya Nair"),489
],484
"Who is taking the review?",490
"Who is taking the review?",485
3,491
3,486
at(0, 13, 12),492
at(0, 13, 12),@@ -1057,6 +1063,16 @@ fn release_messages() -> Vec<MessageRecord> {1057
&many,1063
&many,1058
false,1064
false,1059
),1065
),1066
message(1067
chat,1068
"m8",1069
None,1070
jonas,1071
at(0, 13, 40),1072
"<p>Formula check: H<sub>2</sub>O and x<sup>2</sup> + y<sup>2</sup>. <span style=\"font-size:xx-small;\">Small print, reviewed by <at id=\"0\">Mara Lindqvist</at>.</span> <span style=\"font-size:x-large;\">Big news:</span> the <span style=\"font-size:x-large;\"><a href=\"https://example.com/notes\">release notes</a></span> are out.</p>",1073
"[]",1074
false,1075
),1060
]1076
]1061
}1077
}1062
1078
@@ -1,11 +1,23 @@
1
1
use std::ops::Range;
2
2
3
use teams_core::Span;
3
use teams_core::{FontSize, Span};
4
4
5
5
pub const IMAGE_PLACEHOLDER: &str = "[image]";
6
6
pub const CODE_PADDING: &str = "\u{2004}";
7
7
const URL_PREFIXES: [&str; 3] = ["https://", "http://", "www."];
8
8
const TRAILING_PUNCTUATION: &str = ".,;:!?'\"";
9
const BASE_FONT_PIXELS: f32 = 14.;
10
const SMALL_SCALE: f32 = 0.75;
11
const LARGE_SCALE: f32 = 1.5;
12
const SCRIPT_SCALE: f32 = 0.75;
13
const SUPERSCRIPT_RAISE: f32 = 0.35;
14
const SUBSCRIPT_DROP: f32 = 0.2;
15
16
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17
pub enum Script {
18
Super,
19
Sub,
20
}
9
21
10
22
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
11
23
pub struct StyleFlags {
@@ -16,6 +28,8 @@ pub struct StyleFlags {
16
28
pub link: bool,
17
29
pub strike: bool,
18
30
pub underline: bool,
31
pub script: Option<Script>,
32
pub size: Option<FontSize>,
19
33
pub color: Option<u32>,
20
34
pub background: Option<u32>,
21
35
}
@@ -24,6 +38,31 @@ impl StyleFlags {
24
38
pub fn is_plain(&self) -> bool {
25
39
*self == StyleFlags::default()
26
40
}
41
42
pub fn is_flowed(&self) -> bool {
43
self.script.is_some() || self.size.is_some()
44
}
45
46
pub fn baseline_raise(&self) -> f32 {
47
match self.script {
48
Some(Script::Super) => SUPERSCRIPT_RAISE,
49
Some(Script::Sub) => -SUBSCRIPT_DROP,
50
None => 0.,
51
}
52
}
53
54
pub fn font_scale(&self) -> f32 {
55
let size = match self.size {
56
Some(FontSize::Small) => SMALL_SCALE,
57
Some(FontSize::Large) => LARGE_SCALE,
58
Some(FontSize::Pixels(pixels)) => f32::from(pixels) / BASE_FONT_PIXELS,
59
Some(FontSize::Hidden) | None => 1.,
60
};
61
match self.script {
62
Some(_) => size * SCRIPT_SCALE,
63
None => size,
64
}
65
}
27
66
}
28
67
29
68
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -432,6 +471,34 @@ fn append_inline(spans: &[Span], style: StyleFlags, link: Option<&str>, out: &mu
432
471
link,
433
472
out,
434
473
),
474
Span::Superscript(children) => append_inline(
475
children,
476
StyleFlags {
477
script: Some(Script::Super),
478
..style
479
},
480
link,
481
out,
482
),
483
Span::Subscript(children) => append_inline(
484
children,
485
StyleFlags {
486
script: Some(Script::Sub),
487
..style
488
},
489
link,
490
out,
491
),
492
Span::Sized(FontSize::Hidden, _) => {}
493
Span::Sized(size, children) => append_inline(
494
children,
495
StyleFlags {
496
size: Some(*size),
497
..style
498
},
499
link,
500
out,
501
),
435
502
Span::Colored {
436
503
color,
437
504
background,
@@ -811,6 +878,29 @@ mod tests {
811
878
);
812
879
}
813
880
881
#[test]
882
fn script_and_size_become_flags_with_a_font_scale() {
883
let inline = paragraph_inline(&[
884
Span::Superscript(vec![text("2")]),
885
Span::Sized(FontSize::Large, vec![text("big")]),
886
Span::Sized(FontSize::Small, vec![Span::Subscript(vec![text("s")])]),
887
Span::Sized(FontSize::Pixels(21), vec![text("p")]),
888
Span::Sized(FontSize::Hidden, vec![text("secret")]),
889
]);
890
let styles: Vec<StyleFlags> = inline
891
.segments
892
.iter()
893
.map(|segment| segment.style)
894
.collect();
895
assert_eq!(inline.text, "2bigsp");
896
assert_eq!(styles[0].script, Some(Script::Super));
897
assert_eq!(styles[0].font_scale(), 0.75);
898
assert_eq!(styles[1].font_scale(), 1.5);
899
assert_eq!(styles[2].script, Some(Script::Sub));
900
assert_eq!(styles[2].font_scale(), 0.5625);
901
assert_eq!(styles[3].font_scale(), 1.5);
902
}
903
814
904
#[test]
815
905
fn strike_underline_and_color_become_flags() {
816
906
let inline = paragraph_inline(&[
@@ -1,11 +1,23 @@1
use std::ops::Range;1
use std::ops::Range;2
2
3
use teams_core::Span;3
use teams_core::{FontSize, Span};4
4
5
pub const IMAGE_PLACEHOLDER: &str = "[image]";5
pub const IMAGE_PLACEHOLDER: &str = "[image]";6
pub const CODE_PADDING: &str = "\u{2004}";6
pub const CODE_PADDING: &str = "\u{2004}";7
const URL_PREFIXES: [&str; 3] = ["https://", "http://", "www."];7
const URL_PREFIXES: [&str; 3] = ["https://", "http://", "www."];8
const TRAILING_PUNCTUATION: &str = ".,;:!?'\"";8
const TRAILING_PUNCTUATION: &str = ".,;:!?'\"";9
const BASE_FONT_PIXELS: f32 = 14.;10
const SMALL_SCALE: f32 = 0.75;11
const LARGE_SCALE: f32 = 1.5;12
const SCRIPT_SCALE: f32 = 0.75;13
const SUPERSCRIPT_RAISE: f32 = 0.35;14
const SUBSCRIPT_DROP: f32 = 0.2;15
16
#[derive(Debug, Clone, Copy, PartialEq, Eq)]17
pub enum Script {18
Super,19
Sub,20
}9
21
10
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]22
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]11
pub struct StyleFlags {23
pub struct StyleFlags {@@ -16,6 +28,8 @@ pub struct StyleFlags {16
pub link: bool,28
pub link: bool,17
pub strike: bool,29
pub strike: bool,18
pub underline: bool,30
pub underline: bool,31
pub script: Option<Script>,32
pub size: Option<FontSize>,19
pub color: Option<u32>,33
pub color: Option<u32>,20
pub background: Option<u32>,34
pub background: Option<u32>,21
}35
}@@ -24,6 +38,31 @@ impl StyleFlags {24
pub fn is_plain(&self) -> bool {38
pub fn is_plain(&self) -> bool {25
*self == StyleFlags::default()39
*self == StyleFlags::default()26
}40
}41
42
pub fn is_flowed(&self) -> bool {43
self.script.is_some() || self.size.is_some()44
}45
46
pub fn baseline_raise(&self) -> f32 {47
match self.script {48
Some(Script::Super) => SUPERSCRIPT_RAISE,49
Some(Script::Sub) => -SUBSCRIPT_DROP,50
None => 0.,51
}52
}53
54
pub fn font_scale(&self) -> f32 {55
let size = match self.size {56
Some(FontSize::Small) => SMALL_SCALE,57
Some(FontSize::Large) => LARGE_SCALE,58
Some(FontSize::Pixels(pixels)) => f32::from(pixels) / BASE_FONT_PIXELS,59
Some(FontSize::Hidden) | None => 1.,60
};61
match self.script {62
Some(_) => size * SCRIPT_SCALE,63
None => size,64
}65
}27
}66
}28
67
29
#[derive(Debug, Clone, PartialEq, Eq)]68
#[derive(Debug, Clone, PartialEq, Eq)]@@ -432,6 +471,34 @@ fn append_inline(spans: &[Span], style: StyleFlags, link: Option<&str>, out: &mu432
link,471
link,433
out,472
out,434
),473
),474
Span::Superscript(children) => append_inline(475
children,476
StyleFlags {477
script: Some(Script::Super),478
..style479
},480
link,481
out,482
),483
Span::Subscript(children) => append_inline(484
children,485
StyleFlags {486
script: Some(Script::Sub),487
..style488
},489
link,490
out,491
),492
Span::Sized(FontSize::Hidden, _) => {}493
Span::Sized(size, children) => append_inline(494
children,495
StyleFlags {496
size: Some(*size),497
..style498
},499
link,500
out,501
),435
Span::Colored {502
Span::Colored {436
color,503
color,437
background,504
background,@@ -811,6 +878,29 @@ mod tests {811
);878
);812
}879
}813
880
881
#[test]882
fn script_and_size_become_flags_with_a_font_scale() {883
let inline = paragraph_inline(&[884
Span::Superscript(vec![text("2")]),885
Span::Sized(FontSize::Large, vec![text("big")]),886
Span::Sized(FontSize::Small, vec![Span::Subscript(vec![text("s")])]),887
Span::Sized(FontSize::Pixels(21), vec![text("p")]),888
Span::Sized(FontSize::Hidden, vec![text("secret")]),889
]);890
let styles: Vec<StyleFlags> = inline891
.segments892
.iter()893
.map(|segment| segment.style)894
.collect();895
assert_eq!(inline.text, "2bigsp");896
assert_eq!(styles[0].script, Some(Script::Super));897
assert_eq!(styles[0].font_scale(), 0.75);898
assert_eq!(styles[1].font_scale(), 1.5);899
assert_eq!(styles[2].script, Some(Script::Sub));900
assert_eq!(styles[2].font_scale(), 0.5625);901
assert_eq!(styles[3].font_scale(), 1.5);902
}903
814
#[test]904
#[test]815
fn strike_underline_and_color_become_flags() {905
fn strike_underline_and_color_become_flags() {816
let inline = paragraph_inline(&[906
let inline = paragraph_inline(&[@@ -3,6 +3,7 @@ use gpui_kit::prelude::FluentBuilder as _;
3
3
use gpui_kit::*;
4
4
5
5
use super::blocks::{Block, Inline, StyleFlags};
6
use super::flow_text::{FlowSegment, FlowText};
6
7
use super::selectable::{Pill, SelectableRichText};
7
8
use super::syntax::{self, Token};
8
9
use crate::theme;
@@ -315,6 +316,32 @@ fn render_inline(inline: &Inline, id: String, own: bool, cx: &App) -> AnyElement
315
316
.iter()
316
317
.filter_map(|segment| pill_for(segment.range.clone(), segment.style, own))
317
318
.collect();
319
if inline
320
.segments
321
.iter()
322
.any(|segment| segment.style.is_flowed())
323
{
324
let segments = inline
325
.segments
326
.iter()
327
.map(|segment| FlowSegment {
328
range: segment.range.clone(),
329
highlight: highlight_for(segment.style, own),
330
family: segment.style.code.then(|| mono.clone()),
331
scale: segment.style.font_scale(),
332
raise: segment.style.baseline_raise(),
333
})
334
.collect();
335
return div()
336
.w_full()
337
.text_color(theme::text())
338
.child(
339
FlowText::new(ElementId::Name(id.into()), inline.text.clone(), segments)
340
.links(inline.links())
341
.pills(pills),
342
)
343
.into_any_element();
344
}
318
345
div()
319
346
.w_full()
320
347
.text_color(theme::text())
@@ -3,6 +3,7 @@ use gpui_kit::prelude::FluentBuilder as _;3
use gpui_kit::*;3
use gpui_kit::*;4
4
5
use super::blocks::{Block, Inline, StyleFlags};5
use super::blocks::{Block, Inline, StyleFlags};6
use super::flow_text::{FlowSegment, FlowText};6
use super::selectable::{Pill, SelectableRichText};7
use super::selectable::{Pill, SelectableRichText};7
use super::syntax::{self, Token};8
use super::syntax::{self, Token};8
use crate::theme;9
use crate::theme;@@ -315,6 +316,32 @@ fn render_inline(inline: &Inline, id: String, own: bool, cx: &App) -> AnyElement315
.iter()316
.iter()316
.filter_map(|segment| pill_for(segment.range.clone(), segment.style, own))317
.filter_map(|segment| pill_for(segment.range.clone(), segment.style, own))317
.collect();318
.collect();319
if inline320
.segments321
.iter()322
.any(|segment| segment.style.is_flowed())323
{324
let segments = inline325
.segments326
.iter()327
.map(|segment| FlowSegment {328
range: segment.range.clone(),329
highlight: highlight_for(segment.style, own),330
family: segment.style.code.then(|| mono.clone()),331
scale: segment.style.font_scale(),332
raise: segment.style.baseline_raise(),333
})334
.collect();335
return div()336
.w_full()337
.text_color(theme::text())338
.child(339
FlowText::new(ElementId::Name(id.into()), inline.text.clone(), segments)340
.links(inline.links())341
.pills(pills),342
)343
.into_any_element();344
}318
div()345
div()319
.w_full()346
.w_full()320
.text_color(theme::text())347
.text_color(theme::text())@@ -0,0 +1,937 @@
1
use std::cell::RefCell;
2
use std::ops::Range;
3
use std::rc::Rc;
4
5
use gpui_kit::base::{TextSelection, TextSelectionRegistration, TextSelectionRun, Theme};
6
use gpui_kit::*;
7
8
use super::blocks::CODE_PADDING;
9
use super::selectable::{HIT_SLOP, PILL_INSET_Y, PILL_OUTSET, Participant, Pill, TIME_ROOM};
10
11
const WRAP_TOLERANCE: f32 = 0.5;
12
13
#[derive(Clone)]
14
pub struct FlowSegment {
15
pub range: Range<usize>,
16
pub highlight: HighlightStyle,
17
pub family: Option<SharedString>,
18
pub scale: f32,
19
pub raise: f32,
20
}
21
22
#[derive(Debug, Clone, Copy, PartialEq)]
23
struct Measured {
24
width: Pixels,
25
baseline: Pixels,
26
}
27
28
#[derive(Debug, Clone, PartialEq)]
29
struct Piece {
30
range: Range<usize>,
31
scale: f32,
32
raise: f32,
33
width: Pixels,
34
baseline: Pixels,
35
height: Pixels,
36
}
37
38
#[derive(Debug, Clone, PartialEq)]
39
struct Fragment {
40
range: Range<usize>,
41
scale: f32,
42
origin: Point<Pixels>,
43
size: Size<Pixels>,
44
line: usize,
45
}
46
47
#[derive(Debug, Clone, PartialEq)]
48
struct Line {
49
top: Pixels,
50
height: Pixels,
51
}
52
53
#[derive(Debug, Clone, PartialEq, Default)]
54
struct FlowLayout {
55
fragments: Vec<Fragment>,
56
lines: Vec<Line>,
57
size: Size<Pixels>,
58
wrap_width: Option<Pixels>,
59
}
60
61
#[derive(Clone)]
62
struct Typography {
63
style: TextStyle,
64
font_size: Pixels,
65
line_height: Pixels,
66
rem_size: Pixels,
67
}
68
69
impl Typography {
70
fn capture(window: &Window) -> Typography {
71
let style = window.text_style();
72
let rem_size = window.rem_size();
73
Typography {
74
font_size: style.font_size.to_pixels(rem_size),
75
line_height: style.line_height.to_pixels(style.font_size, rem_size),
76
rem_size,
77
style,
78
}
79
}
80
}
81
82
struct Atom {
83
word: Range<usize>,
84
space: Range<usize>,
85
}
86
87
fn hard_lines(text: &str) -> Vec<Range<usize>> {
88
let mut lines = Vec::new();
89
let mut start = 0;
90
for (newline, _) in text.match_indices('\n') {
91
lines.push(start..newline);
92
start = newline + 1;
93
}
94
lines.push(start..text.len());
95
lines
96
}
97
98
fn atoms(text: &str, line: Range<usize>) -> Vec<Atom> {
99
let mut atoms = Vec::new();
100
let mut index = line.start;
101
while index < line.end {
102
let word_end = text[index..line.end]
103
.find(' ')
104
.map_or(line.end, |offset| index + offset);
105
let space_end = word_end
106
+ text[word_end..line.end]
107
.bytes()
108
.take_while(|byte| *byte == b' ')
109
.count();
110
atoms.push(Atom {
111
word: index..word_end,
112
space: word_end..space_end,
113
});
114
index = space_end;
115
}
116
atoms
117
}
118
119
fn style_spans(segments: &[FlowSegment], range: &Range<usize>) -> Vec<(Range<usize>, f32, f32)> {
120
let mut spans: Vec<(Range<usize>, f32, f32)> = Vec::new();
121
for segment in segments {
122
let start = segment.range.start.max(range.start);
123
let end = segment.range.end.min(range.end);
124
if start >= end {
125
continue;
126
}
127
match spans.last_mut() {
128
Some((last, scale, raise))
129
if *scale == segment.scale && *raise == segment.raise && last.end == start =>
130
{
131
last.end = end;
132
}
133
_ => spans.push((start..end, segment.scale, segment.raise)),
134
}
135
}
136
spans
137
}
138
139
fn build_lines(
140
text: &str,
141
segments: &[FlowSegment],
142
wrap_width: Option<Pixels>,
143
base_line_height: Pixels,
144
measure: &mut impl FnMut(&Range<usize>, f32) -> Measured,
145
) -> Vec<Vec<Piece>> {
146
let mut pieces_of = |range: &Range<usize>| -> Vec<Piece> {
147
style_spans(segments, range)
148
.into_iter()
149
.map(|(range, scale, raise)| {
150
let measured = measure(&range, scale);
151
Piece {
152
range,
153
scale,
154
raise,
155
width: measured.width,
156
baseline: measured.baseline,
157
height: base_line_height * scale,
158
}
159
})
160
.collect()
161
};
162
let mut lines = Vec::new();
163
for hard_line in hard_lines(text) {
164
let mut line: Vec<Piece> = Vec::new();
165
let mut width = Pixels::ZERO;
166
for atom in atoms(text, hard_line) {
167
let word = pieces_of(&atom.word);
168
let space = pieces_of(&atom.space);
169
let word_width: Pixels = word.iter().map(|piece| piece.width).sum();
170
let space_width: Pixels = space.iter().map(|piece| piece.width).sum();
171
let overflows =
172
wrap_width.is_some_and(|limit| width + word_width > limit + px(WRAP_TOLERANCE));
173
if overflows && !line.is_empty() {
174
lines.push(std::mem::take(&mut line));
175
width = Pixels::ZERO;
176
}
177
line.extend(word);
178
line.extend(space);
179
width += word_width + space_width;
180
}
181
lines.push(line);
182
}
183
lines
184
}
185
186
fn place(
187
lines: Vec<Vec<Piece>>,
188
base: Measured,
189
base_line_height: Pixels,
190
base_font_size: Pixels,
191
wrap_width: Option<Pixels>,
192
) -> FlowLayout {
193
let mut layout = FlowLayout {
194
wrap_width,
195
..FlowLayout::default()
196
};
197
let mut top = Pixels::ZERO;
198
for (line_index, pieces) in lines.into_iter().enumerate() {
199
let mut ascent = base.baseline;
200
let mut descent = base_line_height - base.baseline;
201
for piece in &pieces {
202
let raise = base_font_size * piece.raise;
203
ascent = ascent.max(piece.baseline + raise);
204
descent = descent.max(piece.height - piece.baseline - raise);
205
}
206
let mut x = Pixels::ZERO;
207
let mut fragments: Vec<(Fragment, f32)> = Vec::new();
208
for piece in pieces {
209
let raise = base_font_size * piece.raise;
210
match fragments.last_mut() {
211
Some((fragment, last_raise))
212
if fragment.scale == piece.scale
213
&& *last_raise == piece.raise
214
&& fragment.range.end == piece.range.start =>
215
{
216
fragment.range.end = piece.range.end;
217
fragment.size.width += piece.width;
218
}
219
_ => fragments.push((
220
Fragment {
221
range: piece.range.clone(),
222
scale: piece.scale,
223
origin: point(x, top + ascent - piece.baseline - raise),
224
size: size(piece.width, piece.height),
225
line: line_index,
226
},
227
piece.raise,
228
)),
229
}
230
x += piece.width;
231
}
232
layout.size.width = layout.size.width.max(x);
233
layout.lines.push(Line {
234
top,
235
height: ascent + descent,
236
});
237
layout
238
.fragments
239
.extend(fragments.into_iter().map(|(fragment, _)| fragment));
240
top += ascent + descent;
241
}
242
layout.size.height = top;
243
if let Some(limit) = wrap_width {
244
layout.size.width = layout.size.width.min(limit);
245
}
246
layout
247
}
248
249
fn text_runs(style: &TextStyle, segments: &[FlowSegment], range: &Range<usize>) -> Vec<TextRun> {
250
let mut runs = Vec::new();
251
let mut covered = range.start;
252
for segment in segments {
253
let start = segment.range.start.max(range.start);
254
let end = segment.range.end.min(range.end);
255
if start >= end {
256
continue;
257
}
258
if covered < start {
259
runs.push(style.clone().to_run(start - covered));
260
}
261
let mut run = style
262
.clone()
263
.highlight(segment.highlight)
264
.to_run(end - start);
265
if let Some(family) = &segment.family {
266
run.font.family = family.clone();
267
}
268
runs.push(run);
269
covered = end;
270
}
271
if covered < range.end {
272
runs.push(style.clone().to_run(range.end - covered));
273
}
274
runs
275
}
276
277
fn compute_layout(
278
text: &str,
279
segments: &[FlowSegment],
280
typography: &Typography,
281
wrap_width: Option<Pixels>,
282
window: &mut Window,
283
) -> FlowLayout {
284
let mut measure = |range: &Range<usize>, scale: f32| {
285
let runs = text_runs(&typography.style, segments, range);
286
let line = window.text_system().shape_line(
287
SharedString::from(text[range.clone()].to_owned()),
288
typography.font_size * scale,
289
&runs,
290
None,
291
);
292
let height = typography.line_height * scale;
293
Measured {
294
width: line.width(),
295
baseline: (height - line.ascent - line.descent) / 2. + line.ascent,
296
}
297
};
298
let strut = {
299
let runs = vec![typography.style.clone().to_run(1)];
300
let line = window
301
.text_system()
302
.shape_line(" ".into(), typography.font_size, &runs, None);
303
Measured {
304
width: Pixels::ZERO,
305
baseline: (typography.line_height - line.ascent - line.descent) / 2. + line.ascent,
306
}
307
};
308
let lines = build_lines(
309
text,
310
segments,
311
wrap_width,
312
typography.line_height,
313
&mut measure,
314
);
315
place(
316
lines,
317
strut,
318
typography.line_height,
319
typography.font_size,
320
wrap_width,
321
)
322
}
323
324
pub struct FlowText {
325
id: ElementId,
326
text: SharedString,
327
segments: Vec<FlowSegment>,
328
links: Vec<(Range<usize>, String)>,
329
pills: Vec<Pill>,
330
}
331
332
impl FlowText {
333
pub fn new(
334
id: impl Into<ElementId>,
335
text: impl Into<SharedString>,
336
segments: Vec<FlowSegment>,
337
) -> Self {
338
FlowText {
339
id: id.into(),
340
text: text.into(),
341
segments,
342
links: Vec::new(),
343
pills: Vec::new(),
344
}
345
}
346
347
pub fn links(mut self, links: Vec<(Range<usize>, String)>) -> Self {
348
self.links = links;
349
self
350
}
351
352
pub fn pills(mut self, pills: Vec<Pill>) -> Self {
353
self.pills = pills;
354
self
355
}
356
}
357
358
pub struct FlowRequest {
359
participant: Participant,
360
typography: Typography,
361
measured: Rc<RefCell<Option<Rc<FlowLayout>>>>,
362
}
363
364
struct PaintedFragment {
365
element: AnyElement,
366
layout: TextLayout,
367
fragment: Fragment,
368
bounds: Bounds<Pixels>,
369
band: Bounds<Pixels>,
370
}
371
372
pub struct FlowPrepaint {
373
hitbox: Hitbox,
374
fragments: Vec<PaintedFragment>,
375
lines: Vec<Line>,
376
}
377
378
impl IntoElement for FlowText {
379
type Element = Self;
380
381
fn into_element(self) -> Self::Element {
382
self
383
}
384
}
385
386
impl FlowText {
387
fn fragment_text(&self, fragment: &Fragment) -> SharedString {
388
SharedString::from(self.text[fragment.range.clone()].to_owned())
389
}
390
391
fn fragment_styled_text(&self, fragment: &Fragment) -> StyledText {
392
let mut highlights = Vec::new();
393
let mut families = Vec::new();
394
for segment in &self.segments {
395
let start = segment.range.start.max(fragment.range.start);
396
let end = segment.range.end.min(fragment.range.end);
397
if start >= end {
398
continue;
399
}
400
let local = start - fragment.range.start..end - fragment.range.start;
401
if segment.highlight != HighlightStyle::default() {
402
highlights.push((local.clone(), segment.highlight));
403
}
404
if let Some(family) = &segment.family {
405
families.push((local, family.clone()));
406
}
407
}
408
let styled = StyledText::new(self.fragment_text(fragment)).with_highlights(highlights);
409
if families.is_empty() {
410
styled
411
} else {
412
styled.with_font_family_overrides(families)
413
}
414
}
415
416
fn lay_out_fragment(
417
&self,
418
fragment: &Fragment,
419
area: Bounds<Pixels>,
420
typography: &Typography,
421
window: &mut Window,
422
cx: &mut App,
423
) -> (AnyElement, TextLayout) {
424
let styled = self.fragment_styled_text(fragment);
425
let text_layout = styled.layout().clone();
426
let mut element = styled.into_any_element();
427
let mut style = typography.style.clone();
428
style.font_size = (typography.font_size * fragment.scale).into();
429
style.line_height = area.size.height.into();
430
style.white_space = WhiteSpace::Nowrap;
431
window.with_rem_size(Some(typography.rem_size), |window| {
432
window.with_text_style(Some(style.subtract(&Default::default())), |window| {
433
element.prepaint_as_root(
434
area.origin,
435
size(
436
AvailableSpace::Definite(area.size.width),
437
AvailableSpace::Definite(area.size.height),
438
),
439
window,
440
cx,
441
);
442
});
443
});
444
(element, text_layout)
445
}
446
447
fn link_at(
448
prepaint: &[PaintedFragment],
449
links: &[(Range<usize>, String)],
450
position: Point<Pixels>,
451
) -> Option<String> {
452
prepaint.iter().find_map(|painted| {
453
let index = painted.layout.index_for_position(position).ok()?;
454
let global = painted.fragment.range.start + index;
455
links
456
.iter()
457
.find(|(range, _)| range.contains(&global))
458
.map(|(_, url)| url.clone())
459
})
460
}
461
462
fn paint_pills(&self, prepaint: &[PaintedFragment], window: &mut Window) {
463
for pill in &self.pills {
464
for painted in prepaint {
465
let start = pill.range.start.max(painted.fragment.range.start);
466
let end = pill.range.end.min(painted.fragment.range.end);
467
if start >= end {
468
continue;
469
}
470
let offset = painted.fragment.range.start;
471
let (Some(from), Some(to)) = (
472
painted.layout.position_for_index(start - offset),
473
painted.layout.position_for_index(end - offset),
474
) else {
475
continue;
476
};
477
let left = if start == pill.range.start {
478
from.x - px(PILL_OUTSET)
479
} else {
480
from.x
481
};
482
let right = if end == pill.range.end {
483
to.x + px(PILL_OUTSET)
484
} else {
485
to.x
486
};
487
let area = Bounds::from_corners(
488
point(left, painted.bounds.top() + px(PILL_INSET_Y)),
489
point(right, painted.bounds.bottom() - px(PILL_INSET_Y)),
490
);
491
let (border_width, border_color) = match pill.border {
492
Some(color) => (px(1.), color),
493
None => (px(0.), transparent_black()),
494
};
495
window.paint_quad(quad(
496
area,
497
pill.radius,
498
pill.fill,
499
border_width,
500
border_color,
501
BorderStyle::Solid,
502
));
503
}
504
}
505
}
506
}
507
508
impl Element for FlowText {
509
type RequestLayoutState = FlowRequest;
510
type PrepaintState = FlowPrepaint;
511
512
fn id(&self) -> Option<ElementId> {
513
Some(self.id.clone())
514
}
515
516
fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
517
None
518
}
519
520
fn request_layout(
521
&mut self,
522
global_id: Option<&GlobalElementId>,
523
_inspector_id: Option<&InspectorElementId>,
524
window: &mut Window,
525
cx: &mut App,
526
) -> (LayoutId, Self::RequestLayoutState) {
527
let participant = Participant::retained(global_id, &self.text, window, cx);
528
let typography = Typography::capture(window);
529
let measured: Rc<RefCell<Option<Rc<FlowLayout>>>> = Rc::default();
530
let text = self.text.clone();
531
let segments = self.segments.clone();
532
let layout_id = window.request_measured_layout(Default::default(), {
533
let typography = typography.clone();
534
let measured = measured.clone();
535
move |known_dimensions, available_space, window, _| {
536
let wrap_width = known_dimensions.width.or(match available_space.width {
537
AvailableSpace::Definite(width) => Some(width),
538
_ => None,
539
});
540
let layout = compute_layout(&text, &segments, &typography, wrap_width, window);
541
let size = layout.size;
542
*measured.borrow_mut() = Some(Rc::new(layout));
543
size
544
}
545
});
546
(
547
layout_id,
548
FlowRequest {
549
participant,
550
typography,
551
measured,
552
},
553
)
554
}
555
556
fn prepaint(
557
&mut self,
558
_global_id: Option<&GlobalElementId>,
559
_inspector_id: Option<&InspectorElementId>,
560
bounds: Bounds<Pixels>,
561
request: &mut Self::RequestLayoutState,
562
window: &mut Window,
563
cx: &mut App,
564
) -> Self::PrepaintState {
565
let typography = request.typography.clone();
566
let measured = request.measured.borrow().clone();
567
let layout = match measured {
568
Some(layout)
569
if layout.wrap_width.is_some_and(|width| {
570
(width - bounds.size.width).abs() < px(WRAP_TOLERANCE)
571
}) =>
572
{
573
layout
574
}
575
_ => Rc::new(compute_layout(
576
&self.text,
577
&self.segments,
578
&typography,
579
Some(bounds.size.width),
580
window,
581
)),
582
};
583
let mut fragments = Vec::with_capacity(layout.fragments.len());
584
for fragment in &layout.fragments {
585
let band = Bounds::new(
586
point(
587
bounds.origin.x + fragment.origin.x,
588
bounds.origin.y + layout.lines[fragment.line].top,
589
),
590
size(fragment.size.width, layout.lines[fragment.line].height),
591
);
592
let origin = bounds.origin + fragment.origin;
593
let glyphs = Bounds::new(origin, fragment.size);
594
let (element, _) = self.lay_out_fragment(fragment, glyphs, &typography, window, cx);
595
let (_, layout) = self.lay_out_fragment(fragment, band, &typography, window, cx);
596
fragments.push(PaintedFragment {
597
element,
598
layout,
599
fragment: fragment.clone(),
600
bounds: glyphs,
601
band,
602
});
603
}
604
let slop = Edges {
605
left: px(HIT_SLOP),
606
right: px(HIT_SLOP),
607
..Default::default()
608
};
609
let hitbox = window.insert_hitbox(bounds.extend(slop), HitboxBehavior::Normal);
610
let registration = TextSelectionRegistration::new(hitbox.clone(), bounds)
611
.with_text_bounds(fragments.iter().map(|painted| painted.band).collect())
612
.with_rendered_element(&request.participant.handle, window, cx);
613
request
614
.participant
615
.handle
616
.register(registration, window, cx);
617
FlowPrepaint {
618
hitbox,
619
fragments,
620
lines: layout.lines.clone(),
621
}
622
}
623
624
fn paint(
625
&mut self,
626
_global_id: Option<&GlobalElementId>,
627
_inspector_id: Option<&InspectorElementId>,
628
bounds: Bounds<Pixels>,
629
request: &mut Self::RequestLayoutState,
630
prepaint: &mut Self::PrepaintState,
631
window: &mut Window,
632
cx: &mut App,
633
) {
634
let participant = &request.participant;
635
let selected_before = TextSelection::selected_text(window, cx);
636
let runs: Vec<TextSelectionRun> = prepaint
637
.fragments
638
.iter()
639
.enumerate()
640
.map(|(order, painted)| {
641
TextSelectionRun::new(
642
self.fragment_text(&painted.fragment),
643
painted.layout.clone(),
644
painted.band,
645
)
646
.with_document_order(order as u64)
647
})
648
.collect();
649
let projection = participant.handle.update_runs(&runs, cx);
650
if selected_before != TextSelection::selected_text(window, cx) {
651
window.refresh();
652
}
653
self.paint_pills(&prepaint.fragments, window);
654
655
let color = Theme::global(cx).tokens.colors.selection;
656
let content_end = self.text.trim_end_matches(TIME_ROOM).len();
657
let ranges = projection.ranges();
658
let mut copied = String::new();
659
let mut previous_end: Option<usize> = None;
660
for (index, painted) in prepaint.fragments.iter().enumerate() {
661
let Some(Some(range)) = ranges.get(index) else {
662
continue;
663
};
664
let offset = painted.fragment.range.start;
665
let end_index = (offset + range.end).min(content_end);
666
let start_index = offset + range.start;
667
if end_index <= start_index {
668
continue;
669
}
670
if let Some(end) = previous_end
671
&& self.text[end..start_index].contains('\n')
672
{
673
copied.push('\n');
674
}
675
previous_end = Some(end_index);
676
copied.push_str(&self.text[start_index..end_index].replace(CODE_PADDING, ""));
677
let (Some(from), Some(to)) = (
678
painted.layout.position_for_index(range.start),
679
painted.layout.position_for_index(end_index - offset),
680
) else {
681
continue;
682
};
683
let line = &prepaint.lines[painted.fragment.line];
684
let top = bounds.top() + line.top;
685
let reaches_line_end = end_index >= painted.fragment.range.end
686
&& prepaint
687
.fragments
688
.get(index + 1)
689
.is_some_and(|next| next.fragment.line != painted.fragment.line)
690
&& ranges.iter().skip(index + 1).any(Option::is_some);
691
let right = if reaches_line_end {
692
bounds.right()
693
} else {
694
to.x
695
};
696
window.paint_quad(fill(
697
Bounds::from_corners(point(from.x, top), point(right, top + line.height)),
698
color,
699
));
700
}
701
*participant.copied.borrow_mut() = copied;
702
703
for painted in prepaint.fragments.iter_mut() {
704
painted.element.paint(window, cx);
705
}
706
707
let hovered_link = prepaint.hitbox.is_hovered(window)
708
&& Self::link_at(&prepaint.fragments, &self.links, window.mouse_position()).is_some();
709
let cursor = if hovered_link {
710
CursorStyle::PointingHand
711
} else {
712
CursorStyle::IBeam
713
};
714
window.set_cursor_style(cursor, &prepaint.hitbox);
715
window.on_mouse_event(|event: &MouseMoveEvent, phase, window, _| {
716
if phase.bubble() && event.pressed_button == Some(MouseButton::Left) {
717
window.refresh();
718
}
719
});
720
if self.links.is_empty() {
721
return;
722
}
723
let links = std::mem::take(&mut self.links);
724
let hitbox = prepaint.hitbox.clone();
725
let layouts: Vec<(TextLayout, usize)> = prepaint
726
.fragments
727
.iter()
728
.map(|painted| (painted.layout.clone(), painted.fragment.range.start))
729
.collect();
730
window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
731
if !phase.bubble() || event.button != MouseButton::Left || !hitbox.is_hovered(window) {
732
return;
733
}
734
if !TextSelection::selected_text(window, cx).is_empty() {
735
return;
736
}
737
let url = layouts.iter().find_map(|(layout, offset)| {
738
let index = layout.index_for_position(event.position).ok()?;
739
links
740
.iter()
741
.find(|(range, _)| range.contains(&(offset + index)))
742
.map(|(_, url)| url.clone())
743
});
744
if let Some(url) = url {
745
cx.open_url(&url);
746
}
747
});
748
}
749
}
750
751
#[cfg(test)]
752
mod tests {
753
use std::ops::Range;
754
755
use gpui_kit::base::TextSelection;
756
use gpui_kit::test::TestWindowExt as _;
757
use gpui_kit::{
758
AnyWindowHandle, AppContext as _, Bounds, Context, HighlightStyle, IntoElement,
759
ParentElement as _, Pixels, Point, Render, Styled as _, TestAppContext, Window,
760
WindowBounds, WindowOptions, div, point, px, size,
761
};
762
763
use super::{FlowLayout, FlowSegment, FlowText, Measured, build_lines, place};
764
765
const BASE_HEIGHT: f32 = 20.;
766
767
fn segment(range: Range<usize>, scale: f32, raise: f32) -> FlowSegment {
768
FlowSegment {
769
range,
770
highlight: HighlightStyle::default(),
771
family: None,
772
scale,
773
raise,
774
}
775
}
776
777
fn measure(range: &Range<usize>, scale: f32) -> Measured {
778
Measured {
779
width: px(range.len() as f32 * 10. * scale),
780
baseline: px(BASE_HEIGHT * scale * 0.8),
781
}
782
}
783
784
fn layout(text: &str, segments: &[FlowSegment], wrap: Option<f32>) -> FlowLayout {
785
let wrap_width = wrap.map(px);
786
let lines = build_lines(text, segments, wrap_width, px(BASE_HEIGHT), &mut measure);
787
place(
788
lines,
789
Measured {
790
width: Pixels::ZERO,
791
baseline: px(BASE_HEIGHT * 0.8),
792
},
793
px(BASE_HEIGHT),
794
px(14.),
795
wrap_width,
796
)
797
}
798
799
#[test]
800
fn words_wrap_at_the_width_and_keep_their_trailing_space_on_the_line() {
801
let text = "aaa bbb ccc";
802
let flow = layout(text, &[segment(0..11, 1., 0.)], Some(75.));
803
let ranges: Vec<_> = flow.fragments.iter().map(|f| f.range.clone()).collect();
804
assert_eq!(ranges, vec![0..8, 8..11]);
805
assert_eq!(flow.fragments[1].origin.y, px(BASE_HEIGHT));
806
assert_eq!(flow.size.height, px(2. * BASE_HEIGHT));
807
}
808
809
#[test]
810
fn a_word_is_never_split_across_scale_changes_when_wrapping() {
811
let text = "aa H2O";
812
let segments = [
813
segment(0..4, 1., 0.),
814
segment(4..5, 0.75, -0.2),
815
segment(5..6, 1., 0.),
816
];
817
let flow = layout(text, &segments, Some(45.));
818
let lines: Vec<_> = flow.fragments.iter().map(|f| f.line).collect();
819
assert_eq!(lines, vec![0, 1, 1, 1]);
820
}
821
822
#[test]
823
fn a_subscript_hangs_below_the_baseline_and_a_superscript_rises_above_it() {
824
let text = "x2";
825
let sub = layout(
826
text,
827
&[segment(0..1, 1., 0.), segment(1..2, 0.75, -0.2)],
828
None,
829
);
830
let sup = layout(
831
text,
832
&[segment(0..1, 1., 0.), segment(1..2, 0.75, 0.35)],
833
None,
834
);
835
let baseline = |flow: &FlowLayout, index: usize, scale: f32| {
836
flow.fragments[index].origin.y + px(BASE_HEIGHT * scale * 0.8)
837
};
838
assert!(baseline(&sub, 1, 0.75) > baseline(&sub, 0, 1.));
839
assert!(baseline(&sup, 1, 0.75) < baseline(&sup, 0, 1.));
840
assert!(sup.size.height >= px(BASE_HEIGHT));
841
}
842
843
#[test]
844
fn large_text_makes_its_line_taller_and_small_text_does_not_shrink_it() {
845
let text = "ab";
846
let large = layout(text, &[segment(0..1, 1., 0.), segment(1..2, 1.5, 0.)], None);
847
let small = layout(
848
text,
849
&[segment(0..1, 1., 0.), segment(1..2, 0.75, 0.)],
850
None,
851
);
852
assert_eq!(large.size.height, px(BASE_HEIGHT * 1.5));
853
assert_eq!(small.size.height, px(BASE_HEIGHT));
854
}
855
856
#[test]
857
fn a_newline_starts_a_line_and_belongs_to_no_fragment() {
858
let flow = layout("ab\ncd", &[segment(0..5, 1., 0.)], None);
859
let ranges: Vec<_> = flow.fragments.iter().map(|f| f.range.clone()).collect();
860
assert_eq!(ranges, vec![0..2, 3..5]);
861
assert_eq!(flow.lines.len(), 2);
862
}
863
864
struct Message;
865
866
const TEXT: &str = "H2O big link end";
867
868
impl Render for Message {
869
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
870
div().w(px(400.)).text_size(px(14.)).child(
871
FlowText::new(
872
"flow",
873
TEXT,
874
vec![
875
segment(0..1, 1., 0.),
876
segment(1..2, 0.75, -0.2),
877
segment(2..4, 1., 0.),
878
segment(4..7, 1.5, 0.),
879
segment(7..16, 1., 0.),
880
],
881
)
882
.links(vec![(8..12, "https://example.com".to_owned())]),
883
)
884
}
885
}
886
887
fn mount(cx: &mut TestAppContext) -> AnyWindowHandle {
888
cx.update(gpui_kit::init);
889
cx.update(|cx| {
890
let options = WindowOptions {
891
window_bounds: Some(WindowBounds::Windowed(Bounds {
892
origin: Point::default(),
893
size: size(px(400.), px(100.)),
894
})),
895
..Default::default()
896
};
897
gpui_kit::open_window(options, cx, |_, cx| cx.new(|_| Message))
898
.expect("open test window")
899
.0
900
})
901
}
902
903
#[gpui_kit::test]
904
fn dragging_across_sized_fragments_selects_the_whole_text(cx: &mut TestAppContext) {
905
let handle = mount(cx);
906
let selected = cx
907
.update_window(handle, |_, window, cx| {
908
window.render_frame(cx);
909
window.drag(point(px(1.), px(8.)), point(px(399.), px(8.)), cx);
910
window.render_frame(cx);
911
TextSelection::selected_text(window, cx)
912
})
913
.unwrap();
914
assert_eq!(selected, TEXT);
915
assert_eq!(cx.opened_url(), None);
916
}
917
918
#[gpui_kit::test]
919
fn a_link_after_sized_text_opens_and_plain_text_does_not(cx: &mut TestAppContext) {
920
let handle = mount(cx);
921
let click = |x: f32, cx: &mut TestAppContext| {
922
cx.update_window(handle, |_, window, cx| {
923
window.render_frame(cx);
924
window.drag(point(px(x), px(8.)), point(px(x), px(8.)), cx);
925
})
926
.unwrap();
927
};
928
click(2., cx);
929
assert_eq!(cx.opened_url(), None);
930
let link_x = (40..400).map(|x| x as f32).find(|x| {
931
click(*x, cx);
932
cx.opened_url().is_some()
933
});
934
assert!(link_x.is_some());
935
assert_eq!(cx.opened_url().as_deref(), Some("https://example.com"));
936
}
937
}
@@ -0,0 +1,937 @@1
use std::cell::RefCell;2
use std::ops::Range;3
use std::rc::Rc;4
5
use gpui_kit::base::{TextSelection, TextSelectionRegistration, TextSelectionRun, Theme};6
use gpui_kit::*;7
8
use super::blocks::CODE_PADDING;9
use super::selectable::{HIT_SLOP, PILL_INSET_Y, PILL_OUTSET, Participant, Pill, TIME_ROOM};10
11
const WRAP_TOLERANCE: f32 = 0.5;12
13
#[derive(Clone)]14
pub struct FlowSegment {15
pub range: Range<usize>,16
pub highlight: HighlightStyle,17
pub family: Option<SharedString>,18
pub scale: f32,19
pub raise: f32,20
}21
22
#[derive(Debug, Clone, Copy, PartialEq)]23
struct Measured {24
width: Pixels,25
baseline: Pixels,26
}27
28
#[derive(Debug, Clone, PartialEq)]29
struct Piece {30
range: Range<usize>,31
scale: f32,32
raise: f32,33
width: Pixels,34
baseline: Pixels,35
height: Pixels,36
}37
38
#[derive(Debug, Clone, PartialEq)]39
struct Fragment {40
range: Range<usize>,41
scale: f32,42
origin: Point<Pixels>,43
size: Size<Pixels>,44
line: usize,45
}46
47
#[derive(Debug, Clone, PartialEq)]48
struct Line {49
top: Pixels,50
height: Pixels,51
}52
53
#[derive(Debug, Clone, PartialEq, Default)]54
struct FlowLayout {55
fragments: Vec<Fragment>,56
lines: Vec<Line>,57
size: Size<Pixels>,58
wrap_width: Option<Pixels>,59
}60
61
#[derive(Clone)]62
struct Typography {63
style: TextStyle,64
font_size: Pixels,65
line_height: Pixels,66
rem_size: Pixels,67
}68
69
impl Typography {70
fn capture(window: &Window) -> Typography {71
let style = window.text_style();72
let rem_size = window.rem_size();73
Typography {74
font_size: style.font_size.to_pixels(rem_size),75
line_height: style.line_height.to_pixels(style.font_size, rem_size),76
rem_size,77
style,78
}79
}80
}81
82
struct Atom {83
word: Range<usize>,84
space: Range<usize>,85
}86
87
fn hard_lines(text: &str) -> Vec<Range<usize>> {88
let mut lines = Vec::new();89
let mut start = 0;90
for (newline, _) in text.match_indices('\n') {91
lines.push(start..newline);92
start = newline + 1;93
}94
lines.push(start..text.len());95
lines96
}97
98
fn atoms(text: &str, line: Range<usize>) -> Vec<Atom> {99
let mut atoms = Vec::new();100
let mut index = line.start;101
while index < line.end {102
let word_end = text[index..line.end]103
.find(' ')104
.map_or(line.end, |offset| index + offset);105
let space_end = word_end106
+ text[word_end..line.end]107
.bytes()108
.take_while(|byte| *byte == b' ')109
.count();110
atoms.push(Atom {111
word: index..word_end,112
space: word_end..space_end,113
});114
index = space_end;115
}116
atoms117
}118
119
fn style_spans(segments: &[FlowSegment], range: &Range<usize>) -> Vec<(Range<usize>, f32, f32)> {120
let mut spans: Vec<(Range<usize>, f32, f32)> = Vec::new();121
for segment in segments {122
let start = segment.range.start.max(range.start);123
let end = segment.range.end.min(range.end);124
if start >= end {125
continue;126
}127
match spans.last_mut() {128
Some((last, scale, raise))129
if *scale == segment.scale && *raise == segment.raise && last.end == start =>130
{131
last.end = end;132
}133
_ => spans.push((start..end, segment.scale, segment.raise)),134
}135
}136
spans137
}138
139
fn build_lines(140
text: &str,141
segments: &[FlowSegment],142
wrap_width: Option<Pixels>,143
base_line_height: Pixels,144
measure: &mut impl FnMut(&Range<usize>, f32) -> Measured,145
) -> Vec<Vec<Piece>> {146
let mut pieces_of = |range: &Range<usize>| -> Vec<Piece> {147
style_spans(segments, range)148
.into_iter()149
.map(|(range, scale, raise)| {150
let measured = measure(&range, scale);151
Piece {152
range,153
scale,154
raise,155
width: measured.width,156
baseline: measured.baseline,157
height: base_line_height * scale,158
}159
})160
.collect()161
};162
let mut lines = Vec::new();163
for hard_line in hard_lines(text) {164
let mut line: Vec<Piece> = Vec::new();165
let mut width = Pixels::ZERO;166
for atom in atoms(text, hard_line) {167
let word = pieces_of(&atom.word);168
let space = pieces_of(&atom.space);169
let word_width: Pixels = word.iter().map(|piece| piece.width).sum();170
let space_width: Pixels = space.iter().map(|piece| piece.width).sum();171
let overflows =172
wrap_width.is_some_and(|limit| width + word_width > limit + px(WRAP_TOLERANCE));173
if overflows && !line.is_empty() {174
lines.push(std::mem::take(&mut line));175
width = Pixels::ZERO;176
}177
line.extend(word);178
line.extend(space);179
width += word_width + space_width;180
}181
lines.push(line);182
}183
lines184
}185
186
fn place(187
lines: Vec<Vec<Piece>>,188
base: Measured,189
base_line_height: Pixels,190
base_font_size: Pixels,191
wrap_width: Option<Pixels>,192
) -> FlowLayout {193
let mut layout = FlowLayout {194
wrap_width,195
..FlowLayout::default()196
};197
let mut top = Pixels::ZERO;198
for (line_index, pieces) in lines.into_iter().enumerate() {199
let mut ascent = base.baseline;200
let mut descent = base_line_height - base.baseline;201
for piece in &pieces {202
let raise = base_font_size * piece.raise;203
ascent = ascent.max(piece.baseline + raise);204
descent = descent.max(piece.height - piece.baseline - raise);205
}206
let mut x = Pixels::ZERO;207
let mut fragments: Vec<(Fragment, f32)> = Vec::new();208
for piece in pieces {209
let raise = base_font_size * piece.raise;210
match fragments.last_mut() {211
Some((fragment, last_raise))212
if fragment.scale == piece.scale213
&& *last_raise == piece.raise214
&& fragment.range.end == piece.range.start =>215
{216
fragment.range.end = piece.range.end;217
fragment.size.width += piece.width;218
}219
_ => fragments.push((220
Fragment {221
range: piece.range.clone(),222
scale: piece.scale,223
origin: point(x, top + ascent - piece.baseline - raise),224
size: size(piece.width, piece.height),225
line: line_index,226
},227
piece.raise,228
)),229
}230
x += piece.width;231
}232
layout.size.width = layout.size.width.max(x);233
layout.lines.push(Line {234
top,235
height: ascent + descent,236
});237
layout238
.fragments239
.extend(fragments.into_iter().map(|(fragment, _)| fragment));240
top += ascent + descent;241
}242
layout.size.height = top;243
if let Some(limit) = wrap_width {244
layout.size.width = layout.size.width.min(limit);245
}246
layout247
}248
249
fn text_runs(style: &TextStyle, segments: &[FlowSegment], range: &Range<usize>) -> Vec<TextRun> {250
let mut runs = Vec::new();251
let mut covered = range.start;252
for segment in segments {253
let start = segment.range.start.max(range.start);254
let end = segment.range.end.min(range.end);255
if start >= end {256
continue;257
}258
if covered < start {259
runs.push(style.clone().to_run(start - covered));260
}261
let mut run = style262
.clone()263
.highlight(segment.highlight)264
.to_run(end - start);265
if let Some(family) = &segment.family {266
run.font.family = family.clone();267
}268
runs.push(run);269
covered = end;270
}271
if covered < range.end {272
runs.push(style.clone().to_run(range.end - covered));273
}274
runs275
}276
277
fn compute_layout(278
text: &str,279
segments: &[FlowSegment],280
typography: &Typography,281
wrap_width: Option<Pixels>,282
window: &mut Window,283
) -> FlowLayout {284
let mut measure = |range: &Range<usize>, scale: f32| {285
let runs = text_runs(&typography.style, segments, range);286
let line = window.text_system().shape_line(287
SharedString::from(text[range.clone()].to_owned()),288
typography.font_size * scale,289
&runs,290
None,291
);292
let height = typography.line_height * scale;293
Measured {294
width: line.width(),295
baseline: (height - line.ascent - line.descent) / 2. + line.ascent,296
}297
};298
let strut = {299
let runs = vec![typography.style.clone().to_run(1)];300
let line = window301
.text_system()302
.shape_line(" ".into(), typography.font_size, &runs, None);303
Measured {304
width: Pixels::ZERO,305
baseline: (typography.line_height - line.ascent - line.descent) / 2. + line.ascent,306
}307
};308
let lines = build_lines(309
text,310
segments,311
wrap_width,312
typography.line_height,313
&mut measure,314
);315
place(316
lines,317
strut,318
typography.line_height,319
typography.font_size,320
wrap_width,321
)322
}323
324
pub struct FlowText {325
id: ElementId,326
text: SharedString,327
segments: Vec<FlowSegment>,328
links: Vec<(Range<usize>, String)>,329
pills: Vec<Pill>,330
}331
332
impl FlowText {333
pub fn new(334
id: impl Into<ElementId>,335
text: impl Into<SharedString>,336
segments: Vec<FlowSegment>,337
) -> Self {338
FlowText {339
id: id.into(),340
text: text.into(),341
segments,342
links: Vec::new(),343
pills: Vec::new(),344
}345
}346
347
pub fn links(mut self, links: Vec<(Range<usize>, String)>) -> Self {348
self.links = links;349
self350
}351
352
pub fn pills(mut self, pills: Vec<Pill>) -> Self {353
self.pills = pills;354
self355
}356
}357
358
pub struct FlowRequest {359
participant: Participant,360
typography: Typography,361
measured: Rc<RefCell<Option<Rc<FlowLayout>>>>,362
}363
364
struct PaintedFragment {365
element: AnyElement,366
layout: TextLayout,367
fragment: Fragment,368
bounds: Bounds<Pixels>,369
band: Bounds<Pixels>,370
}371
372
pub struct FlowPrepaint {373
hitbox: Hitbox,374
fragments: Vec<PaintedFragment>,375
lines: Vec<Line>,376
}377
378
impl IntoElement for FlowText {379
type Element = Self;380
381
fn into_element(self) -> Self::Element {382
self383
}384
}385
386
impl FlowText {387
fn fragment_text(&self, fragment: &Fragment) -> SharedString {388
SharedString::from(self.text[fragment.range.clone()].to_owned())389
}390
391
fn fragment_styled_text(&self, fragment: &Fragment) -> StyledText {392
let mut highlights = Vec::new();393
let mut families = Vec::new();394
for segment in &self.segments {395
let start = segment.range.start.max(fragment.range.start);396
let end = segment.range.end.min(fragment.range.end);397
if start >= end {398
continue;399
}400
let local = start - fragment.range.start..end - fragment.range.start;401
if segment.highlight != HighlightStyle::default() {402
highlights.push((local.clone(), segment.highlight));403
}404
if let Some(family) = &segment.family {405
families.push((local, family.clone()));406
}407
}408
let styled = StyledText::new(self.fragment_text(fragment)).with_highlights(highlights);409
if families.is_empty() {410
styled411
} else {412
styled.with_font_family_overrides(families)413
}414
}415
416
fn lay_out_fragment(417
&self,418
fragment: &Fragment,419
area: Bounds<Pixels>,420
typography: &Typography,421
window: &mut Window,422
cx: &mut App,423
) -> (AnyElement, TextLayout) {424
let styled = self.fragment_styled_text(fragment);425
let text_layout = styled.layout().clone();426
let mut element = styled.into_any_element();427
let mut style = typography.style.clone();428
style.font_size = (typography.font_size * fragment.scale).into();429
style.line_height = area.size.height.into();430
style.white_space = WhiteSpace::Nowrap;431
window.with_rem_size(Some(typography.rem_size), |window| {432
window.with_text_style(Some(style.subtract(&Default::default())), |window| {433
element.prepaint_as_root(434
area.origin,435
size(436
AvailableSpace::Definite(area.size.width),437
AvailableSpace::Definite(area.size.height),438
),439
window,440
cx,441
);442
});443
});444
(element, text_layout)445
}446
447
fn link_at(448
prepaint: &[PaintedFragment],449
links: &[(Range<usize>, String)],450
position: Point<Pixels>,451
) -> Option<String> {452
prepaint.iter().find_map(|painted| {453
let index = painted.layout.index_for_position(position).ok()?;454
let global = painted.fragment.range.start + index;455
links456
.iter()457
.find(|(range, _)| range.contains(&global))458
.map(|(_, url)| url.clone())459
})460
}461
462
fn paint_pills(&self, prepaint: &[PaintedFragment], window: &mut Window) {463
for pill in &self.pills {464
for painted in prepaint {465
let start = pill.range.start.max(painted.fragment.range.start);466
let end = pill.range.end.min(painted.fragment.range.end);467
if start >= end {468
continue;469
}470
let offset = painted.fragment.range.start;471
let (Some(from), Some(to)) = (472
painted.layout.position_for_index(start - offset),473
painted.layout.position_for_index(end - offset),474
) else {475
continue;476
};477
let left = if start == pill.range.start {478
from.x - px(PILL_OUTSET)479
} else {480
from.x481
};482
let right = if end == pill.range.end {483
to.x + px(PILL_OUTSET)484
} else {485
to.x486
};487
let area = Bounds::from_corners(488
point(left, painted.bounds.top() + px(PILL_INSET_Y)),489
point(right, painted.bounds.bottom() - px(PILL_INSET_Y)),490
);491
let (border_width, border_color) = match pill.border {492
Some(color) => (px(1.), color),493
None => (px(0.), transparent_black()),494
};495
window.paint_quad(quad(496
area,497
pill.radius,498
pill.fill,499
border_width,500
border_color,501
BorderStyle::Solid,502
));503
}504
}505
}506
}507
508
impl Element for FlowText {509
type RequestLayoutState = FlowRequest;510
type PrepaintState = FlowPrepaint;511
512
fn id(&self) -> Option<ElementId> {513
Some(self.id.clone())514
}515
516
fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {517
None518
}519
520
fn request_layout(521
&mut self,522
global_id: Option<&GlobalElementId>,523
_inspector_id: Option<&InspectorElementId>,524
window: &mut Window,525
cx: &mut App,526
) -> (LayoutId, Self::RequestLayoutState) {527
let participant = Participant::retained(global_id, &self.text, window, cx);528
let typography = Typography::capture(window);529
let measured: Rc<RefCell<Option<Rc<FlowLayout>>>> = Rc::default();530
let text = self.text.clone();531
let segments = self.segments.clone();532
let layout_id = window.request_measured_layout(Default::default(), {533
let typography = typography.clone();534
let measured = measured.clone();535
move |known_dimensions, available_space, window, _| {536
let wrap_width = known_dimensions.width.or(match available_space.width {537
AvailableSpace::Definite(width) => Some(width),538
_ => None,539
});540
let layout = compute_layout(&text, &segments, &typography, wrap_width, window);541
let size = layout.size;542
*measured.borrow_mut() = Some(Rc::new(layout));543
size544
}545
});546
(547
layout_id,548
FlowRequest {549
participant,550
typography,551
measured,552
},553
)554
}555
556
fn prepaint(557
&mut self,558
_global_id: Option<&GlobalElementId>,559
_inspector_id: Option<&InspectorElementId>,560
bounds: Bounds<Pixels>,561
request: &mut Self::RequestLayoutState,562
window: &mut Window,563
cx: &mut App,564
) -> Self::PrepaintState {565
let typography = request.typography.clone();566
let measured = request.measured.borrow().clone();567
let layout = match measured {568
Some(layout)569
if layout.wrap_width.is_some_and(|width| {570
(width - bounds.size.width).abs() < px(WRAP_TOLERANCE)571
}) =>572
{573
layout574
}575
_ => Rc::new(compute_layout(576
&self.text,577
&self.segments,578
&typography,579
Some(bounds.size.width),580
window,581
)),582
};583
let mut fragments = Vec::with_capacity(layout.fragments.len());584
for fragment in &layout.fragments {585
let band = Bounds::new(586
point(587
bounds.origin.x + fragment.origin.x,588
bounds.origin.y + layout.lines[fragment.line].top,589
),590
size(fragment.size.width, layout.lines[fragment.line].height),591
);592
let origin = bounds.origin + fragment.origin;593
let glyphs = Bounds::new(origin, fragment.size);594
let (element, _) = self.lay_out_fragment(fragment, glyphs, &typography, window, cx);595
let (_, layout) = self.lay_out_fragment(fragment, band, &typography, window, cx);596
fragments.push(PaintedFragment {597
element,598
layout,599
fragment: fragment.clone(),600
bounds: glyphs,601
band,602
});603
}604
let slop = Edges {605
left: px(HIT_SLOP),606
right: px(HIT_SLOP),607
..Default::default()608
};609
let hitbox = window.insert_hitbox(bounds.extend(slop), HitboxBehavior::Normal);610
let registration = TextSelectionRegistration::new(hitbox.clone(), bounds)611
.with_text_bounds(fragments.iter().map(|painted| painted.band).collect())612
.with_rendered_element(&request.participant.handle, window, cx);613
request614
.participant615
.handle616
.register(registration, window, cx);617
FlowPrepaint {618
hitbox,619
fragments,620
lines: layout.lines.clone(),621
}622
}623
624
fn paint(625
&mut self,626
_global_id: Option<&GlobalElementId>,627
_inspector_id: Option<&InspectorElementId>,628
bounds: Bounds<Pixels>,629
request: &mut Self::RequestLayoutState,630
prepaint: &mut Self::PrepaintState,631
window: &mut Window,632
cx: &mut App,633
) {634
let participant = &request.participant;635
let selected_before = TextSelection::selected_text(window, cx);636
let runs: Vec<TextSelectionRun> = prepaint637
.fragments638
.iter()639
.enumerate()640
.map(|(order, painted)| {641
TextSelectionRun::new(642
self.fragment_text(&painted.fragment),643
painted.layout.clone(),644
painted.band,645
)646
.with_document_order(order as u64)647
})648
.collect();649
let projection = participant.handle.update_runs(&runs, cx);650
if selected_before != TextSelection::selected_text(window, cx) {651
window.refresh();652
}653
self.paint_pills(&prepaint.fragments, window);654
655
let color = Theme::global(cx).tokens.colors.selection;656
let content_end = self.text.trim_end_matches(TIME_ROOM).len();657
let ranges = projection.ranges();658
let mut copied = String::new();659
let mut previous_end: Option<usize> = None;660
for (index, painted) in prepaint.fragments.iter().enumerate() {661
let Some(Some(range)) = ranges.get(index) else {662
continue;663
};664
let offset = painted.fragment.range.start;665
let end_index = (offset + range.end).min(content_end);666
let start_index = offset + range.start;667
if end_index <= start_index {668
continue;669
}670
if let Some(end) = previous_end671
&& self.text[end..start_index].contains('\n')672
{673
copied.push('\n');674
}675
previous_end = Some(end_index);676
copied.push_str(&self.text[start_index..end_index].replace(CODE_PADDING, ""));677
let (Some(from), Some(to)) = (678
painted.layout.position_for_index(range.start),679
painted.layout.position_for_index(end_index - offset),680
) else {681
continue;682
};683
let line = &prepaint.lines[painted.fragment.line];684
let top = bounds.top() + line.top;685
let reaches_line_end = end_index >= painted.fragment.range.end686
&& prepaint687
.fragments688
.get(index + 1)689
.is_some_and(|next| next.fragment.line != painted.fragment.line)690
&& ranges.iter().skip(index + 1).any(Option::is_some);691
let right = if reaches_line_end {692
bounds.right()693
} else {694
to.x695
};696
window.paint_quad(fill(697
Bounds::from_corners(point(from.x, top), point(right, top + line.height)),698
color,699
));700
}701
*participant.copied.borrow_mut() = copied;702
703
for painted in prepaint.fragments.iter_mut() {704
painted.element.paint(window, cx);705
}706
707
let hovered_link = prepaint.hitbox.is_hovered(window)708
&& Self::link_at(&prepaint.fragments, &self.links, window.mouse_position()).is_some();709
let cursor = if hovered_link {710
CursorStyle::PointingHand711
} else {712
CursorStyle::IBeam713
};714
window.set_cursor_style(cursor, &prepaint.hitbox);715
window.on_mouse_event(|event: &MouseMoveEvent, phase, window, _| {716
if phase.bubble() && event.pressed_button == Some(MouseButton::Left) {717
window.refresh();718
}719
});720
if self.links.is_empty() {721
return;722
}723
let links = std::mem::take(&mut self.links);724
let hitbox = prepaint.hitbox.clone();725
let layouts: Vec<(TextLayout, usize)> = prepaint726
.fragments727
.iter()728
.map(|painted| (painted.layout.clone(), painted.fragment.range.start))729
.collect();730
window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {731
if !phase.bubble() || event.button != MouseButton::Left || !hitbox.is_hovered(window) {732
return;733
}734
if !TextSelection::selected_text(window, cx).is_empty() {735
return;736
}737
let url = layouts.iter().find_map(|(layout, offset)| {738
let index = layout.index_for_position(event.position).ok()?;739
links740
.iter()741
.find(|(range, _)| range.contains(&(offset + index)))742
.map(|(_, url)| url.clone())743
});744
if let Some(url) = url {745
cx.open_url(&url);746
}747
});748
}749
}750
751
#[cfg(test)]752
mod tests {753
use std::ops::Range;754
755
use gpui_kit::base::TextSelection;756
use gpui_kit::test::TestWindowExt as _;757
use gpui_kit::{758
AnyWindowHandle, AppContext as _, Bounds, Context, HighlightStyle, IntoElement,759
ParentElement as _, Pixels, Point, Render, Styled as _, TestAppContext, Window,760
WindowBounds, WindowOptions, div, point, px, size,761
};762
763
use super::{FlowLayout, FlowSegment, FlowText, Measured, build_lines, place};764
765
const BASE_HEIGHT: f32 = 20.;766
767
fn segment(range: Range<usize>, scale: f32, raise: f32) -> FlowSegment {768
FlowSegment {769
range,770
highlight: HighlightStyle::default(),771
family: None,772
scale,773
raise,774
}775
}776
777
fn measure(range: &Range<usize>, scale: f32) -> Measured {778
Measured {779
width: px(range.len() as f32 * 10. * scale),780
baseline: px(BASE_HEIGHT * scale * 0.8),781
}782
}783
784
fn layout(text: &str, segments: &[FlowSegment], wrap: Option<f32>) -> FlowLayout {785
let wrap_width = wrap.map(px);786
let lines = build_lines(text, segments, wrap_width, px(BASE_HEIGHT), &mut measure);787
place(788
lines,789
Measured {790
width: Pixels::ZERO,791
baseline: px(BASE_HEIGHT * 0.8),792
},793
px(BASE_HEIGHT),794
px(14.),795
wrap_width,796
)797
}798
799
#[test]800
fn words_wrap_at_the_width_and_keep_their_trailing_space_on_the_line() {801
let text = "aaa bbb ccc";802
let flow = layout(text, &[segment(0..11, 1., 0.)], Some(75.));803
let ranges: Vec<_> = flow.fragments.iter().map(|f| f.range.clone()).collect();804
assert_eq!(ranges, vec![0..8, 8..11]);805
assert_eq!(flow.fragments[1].origin.y, px(BASE_HEIGHT));806
assert_eq!(flow.size.height, px(2. * BASE_HEIGHT));807
}808
809
#[test]810
fn a_word_is_never_split_across_scale_changes_when_wrapping() {811
let text = "aa H2O";812
let segments = [813
segment(0..4, 1., 0.),814
segment(4..5, 0.75, -0.2),815
segment(5..6, 1., 0.),816
];817
let flow = layout(text, &segments, Some(45.));818
let lines: Vec<_> = flow.fragments.iter().map(|f| f.line).collect();819
assert_eq!(lines, vec![0, 1, 1, 1]);820
}821
822
#[test]823
fn a_subscript_hangs_below_the_baseline_and_a_superscript_rises_above_it() {824
let text = "x2";825
let sub = layout(826
text,827
&[segment(0..1, 1., 0.), segment(1..2, 0.75, -0.2)],828
None,829
);830
let sup = layout(831
text,832
&[segment(0..1, 1., 0.), segment(1..2, 0.75, 0.35)],833
None,834
);835
let baseline = |flow: &FlowLayout, index: usize, scale: f32| {836
flow.fragments[index].origin.y + px(BASE_HEIGHT * scale * 0.8)837
};838
assert!(baseline(&sub, 1, 0.75) > baseline(&sub, 0, 1.));839
assert!(baseline(&sup, 1, 0.75) < baseline(&sup, 0, 1.));840
assert!(sup.size.height >= px(BASE_HEIGHT));841
}842
843
#[test]844
fn large_text_makes_its_line_taller_and_small_text_does_not_shrink_it() {845
let text = "ab";846
let large = layout(text, &[segment(0..1, 1., 0.), segment(1..2, 1.5, 0.)], None);847
let small = layout(848
text,849
&[segment(0..1, 1., 0.), segment(1..2, 0.75, 0.)],850
None,851
);852
assert_eq!(large.size.height, px(BASE_HEIGHT * 1.5));853
assert_eq!(small.size.height, px(BASE_HEIGHT));854
}855
856
#[test]857
fn a_newline_starts_a_line_and_belongs_to_no_fragment() {858
let flow = layout("ab\ncd", &[segment(0..5, 1., 0.)], None);859
let ranges: Vec<_> = flow.fragments.iter().map(|f| f.range.clone()).collect();860
assert_eq!(ranges, vec![0..2, 3..5]);861
assert_eq!(flow.lines.len(), 2);862
}863
864
struct Message;865
866
const TEXT: &str = "H2O big link end";867
868
impl Render for Message {869
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {870
div().w(px(400.)).text_size(px(14.)).child(871
FlowText::new(872
"flow",873
TEXT,874
vec![875
segment(0..1, 1., 0.),876
segment(1..2, 0.75, -0.2),877
segment(2..4, 1., 0.),878
segment(4..7, 1.5, 0.),879
segment(7..16, 1., 0.),880
],881
)882
.links(vec![(8..12, "https://example.com".to_owned())]),883
)884
}885
}886
887
fn mount(cx: &mut TestAppContext) -> AnyWindowHandle {888
cx.update(gpui_kit::init);889
cx.update(|cx| {890
let options = WindowOptions {891
window_bounds: Some(WindowBounds::Windowed(Bounds {892
origin: Point::default(),893
size: size(px(400.), px(100.)),894
})),895
..Default::default()896
};897
gpui_kit::open_window(options, cx, |_, cx| cx.new(|_| Message))898
.expect("open test window")899
.0900
})901
}902
903
#[gpui_kit::test]904
fn dragging_across_sized_fragments_selects_the_whole_text(cx: &mut TestAppContext) {905
let handle = mount(cx);906
let selected = cx907
.update_window(handle, |_, window, cx| {908
window.render_frame(cx);909
window.drag(point(px(1.), px(8.)), point(px(399.), px(8.)), cx);910
window.render_frame(cx);911
TextSelection::selected_text(window, cx)912
})913
.unwrap();914
assert_eq!(selected, TEXT);915
assert_eq!(cx.opened_url(), None);916
}917
918
#[gpui_kit::test]919
fn a_link_after_sized_text_opens_and_plain_text_does_not(cx: &mut TestAppContext) {920
let handle = mount(cx);921
let click = |x: f32, cx: &mut TestAppContext| {922
cx.update_window(handle, |_, window, cx| {923
window.render_frame(cx);924
window.drag(point(px(x), px(8.)), point(px(x), px(8.)), cx);925
})926
.unwrap();927
};928
click(2., cx);929
assert_eq!(cx.opened_url(), None);930
let link_x = (40..400).map(|x| x as f32).find(|x| {931
click(*x, cx);932
cx.opened_url().is_some()933
});934
assert!(link_x.is_some());935
assert_eq!(cx.opened_url().as_deref(), Some("https://example.com"));936
}937
}@@ -1,5 +1,6 @@
1
1
pub mod blocks;
2
2
pub mod elements;
3
mod flow_text;
3
4
mod selectable;
4
5
mod syntax;
5
6
@@ -1,5 +1,6 @@1
pub mod blocks;1
pub mod blocks;2
pub mod elements;2
pub mod elements;3
mod flow_text;3
mod selectable;4
mod selectable;4
mod syntax;5
mod syntax;5
6
@@ -9,17 +9,40 @@ use gpui_kit::*;
9
9
10
10
use super::blocks::CODE_PADDING;
11
11
12
const TIME_ROOM: char = '\u{2007}';
13
const HIT_SLOP: f32 = 12.;
12
pub(super) const TIME_ROOM: char = '\u{2007}';
13
pub(super) const HIT_SLOP: f32 = 12.;
14
14
15
15
#[derive(Clone)]
16
16
pub struct Participant {
17
handle: TextSelectionHandle,
18
copied: Rc<RefCell<String>>,
17
pub(super) handle: TextSelectionHandle,
18
pub(super) copied: Rc<RefCell<String>>,
19
19
}
20
20
21
const PILL_OUTSET: f32 = 3.;
22
const PILL_INSET_Y: f32 = 1.;
21
impl Participant {
22
pub(super) fn retained(
23
global_id: Option<&GlobalElementId>,
24
text: &SharedString,
25
window: &mut Window,
26
cx: &mut App,
27
) -> Participant {
28
window.with_element_state(
29
global_id.expect("selectable text has an element id"),
30
|retained: Option<Participant>, _| {
31
let participant = retained.unwrap_or_else(|| {
32
let handle = TextSelectionHandle::new(text.clone(), cx);
33
let copied = Rc::new(RefCell::new(String::new()));
34
let source = copied.clone();
35
handle.copy_with(move |_| source.borrow().clone(), cx);
36
Participant { handle, copied }
37
});
38
(participant.clone(), participant)
39
},
40
)
41
}
42
}
43
44
pub(super) const PILL_OUTSET: f32 = 3.;
45
pub(super) const PILL_INSET_Y: f32 = 1.;
23
46
24
47
#[derive(Clone, Debug)]
25
48
pub struct Pill {
@@ -219,19 +242,7 @@ impl Element for SelectableRichText {
219
242
window: &mut Window,
220
243
cx: &mut App,
221
244
) -> (LayoutId, Self::RequestLayoutState) {
222
let participant = window.with_element_state(
223
global_id.expect("SelectableRichText has an element id"),
224
|retained: Option<Participant>, _| {
225
let participant = retained.unwrap_or_else(|| {
226
let handle = TextSelectionHandle::new(self.text.clone(), cx);
227
let copied = Rc::new(RefCell::new(String::new()));
228
let source = copied.clone();
229
handle.copy_with(move |_| source.borrow().clone(), cx);
230
Participant { handle, copied }
231
});
232
(participant.clone(), participant)
233
},
234
);
245
let participant = Participant::retained(global_id, &self.text, window, cx);
235
246
let (layout_id, ()) = self
236
247
.styled_text
237
248
.request_layout(global_id, inspector_id, window, cx);
@@ -9,17 +9,40 @@ use gpui_kit::*;9
9
10
use super::blocks::CODE_PADDING;10
use super::blocks::CODE_PADDING;11
11
12
const TIME_ROOM: char = '\u{2007}';12
pub(super) const TIME_ROOM: char = '\u{2007}';13
const HIT_SLOP: f32 = 12.;13
pub(super) const HIT_SLOP: f32 = 12.;14
14
15
#[derive(Clone)]15
#[derive(Clone)]16
pub struct Participant {16
pub struct Participant {17
handle: TextSelectionHandle,17
pub(super) handle: TextSelectionHandle,18
copied: Rc<RefCell<String>>,18
pub(super) copied: Rc<RefCell<String>>,19
}19
}20
20
21
const PILL_OUTSET: f32 = 3.;21
impl Participant {22
const PILL_INSET_Y: f32 = 1.;22
pub(super) fn retained(23
global_id: Option<&GlobalElementId>,24
text: &SharedString,25
window: &mut Window,26
cx: &mut App,27
) -> Participant {28
window.with_element_state(29
global_id.expect("selectable text has an element id"),30
|retained: Option<Participant>, _| {31
let participant = retained.unwrap_or_else(|| {32
let handle = TextSelectionHandle::new(text.clone(), cx);33
let copied = Rc::new(RefCell::new(String::new()));34
let source = copied.clone();35
handle.copy_with(move |_| source.borrow().clone(), cx);36
Participant { handle, copied }37
});38
(participant.clone(), participant)39
},40
)41
}42
}43
44
pub(super) const PILL_OUTSET: f32 = 3.;45
pub(super) const PILL_INSET_Y: f32 = 1.;23
46
24
#[derive(Clone, Debug)]47
#[derive(Clone, Debug)]25
pub struct Pill {48
pub struct Pill {@@ -219,19 +242,7 @@ impl Element for SelectableRichText {219
window: &mut Window,242
window: &mut Window,220
cx: &mut App,243
cx: &mut App,221
) -> (LayoutId, Self::RequestLayoutState) {244
) -> (LayoutId, Self::RequestLayoutState) {222
let participant = window.with_element_state(245
let participant = Participant::retained(global_id, &self.text, window, cx);223
global_id.expect("SelectableRichText has an element id"),224
|retained: Option<Participant>, _| {225
let participant = retained.unwrap_or_else(|| {226
let handle = TextSelectionHandle::new(self.text.clone(), cx);227
let copied = Rc::new(RefCell::new(String::new()));228
let source = copied.clone();229
handle.copy_with(move |_| source.borrow().clone(), cx);230
Participant { handle, copied }231
});232
(participant.clone(), participant)233
},234
);235
let (layout_id, ()) = self246
let (layout_id, ()) = self236
.styled_text247
.styled_text237
.request_layout(global_id, inspector_id, window, cx);248
.request_layout(global_id, inspector_id, window, cx);@@ -21,8 +21,8 @@ use gpui_kit::prelude::FluentBuilder as _;
21
21
use gpui_kit::*;
22
22
use teams_core::{
23
23
Draft, DraftLine, Edit, FileReference, FormatState, HostedImage, LineKind, MarkKind,
24
MentionCandidate, MentionInput, MessageExtras, OBJECT_MARK, TypingStyle, UploadedFile,
25
changed_span, has_markdown, link_url, map_offset, reverse_edits,
24
MentionCandidate, MentionInput, MessageExtras, OBJECT_MARK, SizeStep, TypingStyle,
25
UploadedFile, changed_span, has_markdown, link_url, map_offset, reverse_edits,
26
26
};
27
27
28
28
use super::attachment_tray::{
@@ -63,6 +63,8 @@ actions!(
63
63
ToggleItalic,
64
64
ToggleUnderline,
65
65
ToggleStrike,
66
ToggleSuperscript,
67
ToggleSubscript,
66
68
ToggleCode,
67
69
EditLink
68
70
]
@@ -74,6 +76,8 @@ pub fn bind_keys(cx: &mut App) {
74
76
KeyBinding::new("ctrl-i", ToggleItalic, Some(KEY_CONTEXT)),
75
77
KeyBinding::new("ctrl-u", ToggleUnderline, Some(KEY_CONTEXT)),
76
78
KeyBinding::new("ctrl-shift-x", ToggleStrike, Some(KEY_CONTEXT)),
79
KeyBinding::new("ctrl-shift-=", ToggleSuperscript, Some(KEY_CONTEXT)),
80
KeyBinding::new("ctrl-=", ToggleSubscript, Some(KEY_CONTEXT)),
77
81
KeyBinding::new("ctrl-shift-c", ToggleCode, Some(KEY_CONTEXT)),
78
82
KeyBinding::new("ctrl-k", EditLink, Some(KEY_CONTEXT)),
79
83
#[cfg(target_os = "macos")]
@@ -876,6 +880,40 @@ impl Composer {
876
880
cx.notify();
877
881
}
878
882
883
fn set_size(&mut self, size: Option<SizeStep>, cx: &mut Context<Self>) {
884
let selection = self.selection(cx);
885
if selection.is_empty() {
886
let cursor = selection.start;
887
let mut pending = self
888
.pending_style
889
.take()
890
.filter(|pending| pending.at == cursor)
891
.unwrap_or(TypingStyle {
892
at: cursor,
893
..TypingStyle::default()
894
});
895
pending.set_size(size, &self.draft.style_at(cursor));
896
self.pending_style = (!pending.is_empty()).then_some(pending);
897
} else {
898
self.draft.set_size(selection, size);
899
self.draft.take_edits();
900
self.record(StepKind::Other, cx);
901
self.refresh_style(cx);
902
}
903
cx.notify();
904
}
905
906
fn normal_size_state(&self, range: Range<usize>) -> FormatState {
907
let sized = [SizeStep::Small, SizeStep::Large]
908
.into_iter()
909
.any(|step| self.draft.state(range.clone(), &MarkKind::Size(step)) != FormatState::Off);
910
if sized {
911
FormatState::Off
912
} else {
913
FormatState::On
914
}
915
}
916
879
917
fn toggle_lines(&mut self, kind: LineKind, window: &mut Window, cx: &mut Context<Self>) {
880
918
let selection = self.selection(cx);
881
919
self.draft.toggle_lines(selection, kind);
@@ -889,6 +927,11 @@ impl Composer {
889
927
FormatButton::Italic => self.toggle_mark(MarkKind::Italic, cx),
890
928
FormatButton::Underline => self.toggle_mark(MarkKind::Underline, cx),
891
929
FormatButton::Strike => self.toggle_mark(MarkKind::Strike, cx),
930
FormatButton::Superscript => self.toggle_mark(MarkKind::Superscript, cx),
931
FormatButton::Subscript => self.toggle_mark(MarkKind::Subscript, cx),
932
FormatButton::SizeSmall => self.set_size(Some(SizeStep::Small), cx),
933
FormatButton::SizeNormal => self.set_size(None, cx),
934
FormatButton::SizeLarge => self.set_size(Some(SizeStep::Large), cx),
892
935
FormatButton::Code => self.toggle_mark(MarkKind::Code, cx),
893
936
FormatButton::Link => self.open_link_editor(window, cx),
894
937
FormatButton::Bulleted => self.toggle_lines(LineKind::Bullet(0), window, cx),
@@ -904,6 +947,11 @@ impl Composer {
904
947
FormatButton::Italic => self.draft.state(range, &MarkKind::Italic),
905
948
FormatButton::Underline => self.draft.state(range, &MarkKind::Underline),
906
949
FormatButton::Strike => self.draft.state(range, &MarkKind::Strike),
950
FormatButton::Superscript => self.draft.state(range, &MarkKind::Superscript),
951
FormatButton::Subscript => self.draft.state(range, &MarkKind::Subscript),
952
FormatButton::SizeSmall => self.draft.state(range, &MarkKind::Size(SizeStep::Small)),
953
FormatButton::SizeLarge => self.draft.state(range, &MarkKind::Size(SizeStep::Large)),
954
FormatButton::SizeNormal => self.normal_size_state(range),
907
955
FormatButton::Code => self.draft.state(range, &MarkKind::Code),
908
956
FormatButton::Link => self.draft.state(range, &MarkKind::Link(String::new())),
909
957
FormatButton::Bulleted => self.draft.line_state(range, &LineKind::Bullet(0)),
@@ -2293,6 +2341,16 @@ impl Render for Composer {
2293
2341
this.toggle_mark(MarkKind::Strike, cx);
2294
2342
}
2295
2343
}))
2344
.on_action(cx.listener(|this, _: &ToggleSuperscript, _, cx| {
2345
if this.link_editor.is_none() {
2346
this.toggle_mark(MarkKind::Superscript, cx);
2347
}
2348
}))
2349
.on_action(cx.listener(|this, _: &ToggleSubscript, _, cx| {
2350
if this.link_editor.is_none() {
2351
this.toggle_mark(MarkKind::Subscript, cx);
2352
}
2353
}))
2296
2354
.on_action(cx.listener(|this, _: &ToggleCode, _, cx| {
2297
2355
if this.link_editor.is_none() {
2298
2356
this.toggle_mark(MarkKind::Code, cx);
@@ -3115,6 +3173,61 @@ mod tests {
3115
3173
assert_eq!(typist.outgoing().html(), "hello<i>!</i>");
3116
3174
}
3117
3175
3176
#[gpui_kit::test]
3177
fn script_shortcuts_exclude_each_other_and_send_teams_html(cx: &mut TestAppContext) {
3178
let mut typist = typist(cx);
3179
typist.type_text("x2");
3180
typist.press("shift-left ctrl-shift-=");
3181
assert_eq!(typist.outgoing().html(), "x<sup>2</sup>");
3182
typist.press("ctrl-=");
3183
assert_eq!(typist.outgoing().html(), "x<sub>2</sub>");
3184
}
3185
3186
#[gpui_kit::test]
3187
fn the_toolbar_state_follows_the_selection(cx: &mut TestAppContext) {
3188
use teams_core::FormatState;
3189
3190
use super::super::FormatButton;
3191
3192
let mut typist = typist(cx);
3193
typist.type_text("big small");
3194
typist.press("shift-left shift-left shift-left shift-left shift-left");
3195
let composer = typist.composer.clone();
3196
typist.act(|window, cx| {
3197
composer.update(cx, |composer, cx| {
3198
composer.press_format(FormatButton::SizeSmall, window, cx)
3199
})
3200
});
3201
let states = |typist: &mut Typist<'_>, range: std::ops::Range<usize>| {
3202
let composer = typist.composer.clone();
3203
typist.cx.update(|cx| {
3204
let composer = composer.read(cx);
3205
[
3206
FormatButton::SizeSmall,
3207
FormatButton::SizeNormal,
3208
FormatButton::SizeLarge,
3209
]
3210
.map(|button| composer.format_state(button, &range))
3211
})
3212
};
3213
assert_eq!(
3214
states(&mut typist, 4..9),
3215
[FormatState::On, FormatState::Off, FormatState::Off]
3216
);
3217
assert_eq!(
3218
states(&mut typist, 0..9),
3219
[FormatState::Mixed, FormatState::Off, FormatState::Off]
3220
);
3221
assert_eq!(
3222
states(&mut typist, 0..3),
3223
[FormatState::Off, FormatState::On, FormatState::Off]
3224
);
3225
assert_eq!(
3226
typist.outgoing().html(),
3227
"big <span style=\"font-size:xx-small;\">small</span>"
3228
);
3229
}
3230
3118
3231
#[gpui_kit::test]
3119
3232
fn pasted_markdown_converts_and_ctrl_z_restores_the_raw_text(cx: &mut TestAppContext) {
3120
3233
let mut typist = typist(cx);
@@ -21,8 +21,8 @@ use gpui_kit::prelude::FluentBuilder as _;21
use gpui_kit::*;21
use gpui_kit::*;22
use teams_core::{22
use teams_core::{23
Draft, DraftLine, Edit, FileReference, FormatState, HostedImage, LineKind, MarkKind,23
Draft, DraftLine, Edit, FileReference, FormatState, HostedImage, LineKind, MarkKind,24
MentionCandidate, MentionInput, MessageExtras, OBJECT_MARK, TypingStyle, UploadedFile,24
MentionCandidate, MentionInput, MessageExtras, OBJECT_MARK, SizeStep, TypingStyle,25
changed_span, has_markdown, link_url, map_offset, reverse_edits,25
UploadedFile, changed_span, has_markdown, link_url, map_offset, reverse_edits,26
};26
};27
27
28
use super::attachment_tray::{28
use super::attachment_tray::{@@ -63,6 +63,8 @@ actions!(63
ToggleItalic,63
ToggleItalic,64
ToggleUnderline,64
ToggleUnderline,65
ToggleStrike,65
ToggleStrike,66
ToggleSuperscript,67
ToggleSubscript,66
ToggleCode,68
ToggleCode,67
EditLink69
EditLink68
]70
]@@ -74,6 +76,8 @@ pub fn bind_keys(cx: &mut App) {74
KeyBinding::new("ctrl-i", ToggleItalic, Some(KEY_CONTEXT)),76
KeyBinding::new("ctrl-i", ToggleItalic, Some(KEY_CONTEXT)),75
KeyBinding::new("ctrl-u", ToggleUnderline, Some(KEY_CONTEXT)),77
KeyBinding::new("ctrl-u", ToggleUnderline, Some(KEY_CONTEXT)),76
KeyBinding::new("ctrl-shift-x", ToggleStrike, Some(KEY_CONTEXT)),78
KeyBinding::new("ctrl-shift-x", ToggleStrike, Some(KEY_CONTEXT)),79
KeyBinding::new("ctrl-shift-=", ToggleSuperscript, Some(KEY_CONTEXT)),80
KeyBinding::new("ctrl-=", ToggleSubscript, Some(KEY_CONTEXT)),77
KeyBinding::new("ctrl-shift-c", ToggleCode, Some(KEY_CONTEXT)),81
KeyBinding::new("ctrl-shift-c", ToggleCode, Some(KEY_CONTEXT)),78
KeyBinding::new("ctrl-k", EditLink, Some(KEY_CONTEXT)),82
KeyBinding::new("ctrl-k", EditLink, Some(KEY_CONTEXT)),79
#[cfg(target_os = "macos")]83
#[cfg(target_os = "macos")]@@ -876,6 +880,40 @@ impl Composer {876
cx.notify();880
cx.notify();877
}881
}878
882
883
fn set_size(&mut self, size: Option<SizeStep>, cx: &mut Context<Self>) {884
let selection = self.selection(cx);885
if selection.is_empty() {886
let cursor = selection.start;887
let mut pending = self888
.pending_style889
.take()890
.filter(|pending| pending.at == cursor)891
.unwrap_or(TypingStyle {892
at: cursor,893
..TypingStyle::default()894
});895
pending.set_size(size, &self.draft.style_at(cursor));896
self.pending_style = (!pending.is_empty()).then_some(pending);897
} else {898
self.draft.set_size(selection, size);899
self.draft.take_edits();900
self.record(StepKind::Other, cx);901
self.refresh_style(cx);902
}903
cx.notify();904
}905
906
fn normal_size_state(&self, range: Range<usize>) -> FormatState {907
let sized = [SizeStep::Small, SizeStep::Large]908
.into_iter()909
.any(|step| self.draft.state(range.clone(), &MarkKind::Size(step)) != FormatState::Off);910
if sized {911
FormatState::Off912
} else {913
FormatState::On914
}915
}916
879
fn toggle_lines(&mut self, kind: LineKind, window: &mut Window, cx: &mut Context<Self>) {917
fn toggle_lines(&mut self, kind: LineKind, window: &mut Window, cx: &mut Context<Self>) {880
let selection = self.selection(cx);918
let selection = self.selection(cx);881
self.draft.toggle_lines(selection, kind);919
self.draft.toggle_lines(selection, kind);@@ -889,6 +927,11 @@ impl Composer {889
FormatButton::Italic => self.toggle_mark(MarkKind::Italic, cx),927
FormatButton::Italic => self.toggle_mark(MarkKind::Italic, cx),890
FormatButton::Underline => self.toggle_mark(MarkKind::Underline, cx),928
FormatButton::Underline => self.toggle_mark(MarkKind::Underline, cx),891
FormatButton::Strike => self.toggle_mark(MarkKind::Strike, cx),929
FormatButton::Strike => self.toggle_mark(MarkKind::Strike, cx),930
FormatButton::Superscript => self.toggle_mark(MarkKind::Superscript, cx),931
FormatButton::Subscript => self.toggle_mark(MarkKind::Subscript, cx),932
FormatButton::SizeSmall => self.set_size(Some(SizeStep::Small), cx),933
FormatButton::SizeNormal => self.set_size(None, cx),934
FormatButton::SizeLarge => self.set_size(Some(SizeStep::Large), cx),892
FormatButton::Code => self.toggle_mark(MarkKind::Code, cx),935
FormatButton::Code => self.toggle_mark(MarkKind::Code, cx),893
FormatButton::Link => self.open_link_editor(window, cx),936
FormatButton::Link => self.open_link_editor(window, cx),894
FormatButton::Bulleted => self.toggle_lines(LineKind::Bullet(0), window, cx),937
FormatButton::Bulleted => self.toggle_lines(LineKind::Bullet(0), window, cx),@@ -904,6 +947,11 @@ impl Composer {904
FormatButton::Italic => self.draft.state(range, &MarkKind::Italic),947
FormatButton::Italic => self.draft.state(range, &MarkKind::Italic),905
FormatButton::Underline => self.draft.state(range, &MarkKind::Underline),948
FormatButton::Underline => self.draft.state(range, &MarkKind::Underline),906
FormatButton::Strike => self.draft.state(range, &MarkKind::Strike),949
FormatButton::Strike => self.draft.state(range, &MarkKind::Strike),950
FormatButton::Superscript => self.draft.state(range, &MarkKind::Superscript),951
FormatButton::Subscript => self.draft.state(range, &MarkKind::Subscript),952
FormatButton::SizeSmall => self.draft.state(range, &MarkKind::Size(SizeStep::Small)),953
FormatButton::SizeLarge => self.draft.state(range, &MarkKind::Size(SizeStep::Large)),954
FormatButton::SizeNormal => self.normal_size_state(range),907
FormatButton::Code => self.draft.state(range, &MarkKind::Code),955
FormatButton::Code => self.draft.state(range, &MarkKind::Code),908
FormatButton::Link => self.draft.state(range, &MarkKind::Link(String::new())),956
FormatButton::Link => self.draft.state(range, &MarkKind::Link(String::new())),909
FormatButton::Bulleted => self.draft.line_state(range, &LineKind::Bullet(0)),957
FormatButton::Bulleted => self.draft.line_state(range, &LineKind::Bullet(0)),@@ -2293,6 +2341,16 @@ impl Render for Composer {2293
this.toggle_mark(MarkKind::Strike, cx);2341
this.toggle_mark(MarkKind::Strike, cx);2294
}2342
}2295
}))2343
}))2344
.on_action(cx.listener(|this, _: &ToggleSuperscript, _, cx| {2345
if this.link_editor.is_none() {2346
this.toggle_mark(MarkKind::Superscript, cx);2347
}2348
}))2349
.on_action(cx.listener(|this, _: &ToggleSubscript, _, cx| {2350
if this.link_editor.is_none() {2351
this.toggle_mark(MarkKind::Subscript, cx);2352
}2353
}))2296
.on_action(cx.listener(|this, _: &ToggleCode, _, cx| {2354
.on_action(cx.listener(|this, _: &ToggleCode, _, cx| {2297
if this.link_editor.is_none() {2355
if this.link_editor.is_none() {2298
this.toggle_mark(MarkKind::Code, cx);2356
this.toggle_mark(MarkKind::Code, cx);@@ -3115,6 +3173,61 @@ mod tests {3115
assert_eq!(typist.outgoing().html(), "hello<i>!</i>");3173
assert_eq!(typist.outgoing().html(), "hello<i>!</i>");3116
}3174
}3117
3175
3176
#[gpui_kit::test]3177
fn script_shortcuts_exclude_each_other_and_send_teams_html(cx: &mut TestAppContext) {3178
let mut typist = typist(cx);3179
typist.type_text("x2");3180
typist.press("shift-left ctrl-shift-=");3181
assert_eq!(typist.outgoing().html(), "x<sup>2</sup>");3182
typist.press("ctrl-=");3183
assert_eq!(typist.outgoing().html(), "x<sub>2</sub>");3184
}3185
3186
#[gpui_kit::test]3187
fn the_toolbar_state_follows_the_selection(cx: &mut TestAppContext) {3188
use teams_core::FormatState;3189
3190
use super::super::FormatButton;3191
3192
let mut typist = typist(cx);3193
typist.type_text("big small");3194
typist.press("shift-left shift-left shift-left shift-left shift-left");3195
let composer = typist.composer.clone();3196
typist.act(|window, cx| {3197
composer.update(cx, |composer, cx| {3198
composer.press_format(FormatButton::SizeSmall, window, cx)3199
})3200
});3201
let states = |typist: &mut Typist<'_>, range: std::ops::Range<usize>| {3202
let composer = typist.composer.clone();3203
typist.cx.update(|cx| {3204
let composer = composer.read(cx);3205
[3206
FormatButton::SizeSmall,3207
FormatButton::SizeNormal,3208
FormatButton::SizeLarge,3209
]3210
.map(|button| composer.format_state(button, &range))3211
})3212
};3213
assert_eq!(3214
states(&mut typist, 4..9),3215
[FormatState::On, FormatState::Off, FormatState::Off]3216
);3217
assert_eq!(3218
states(&mut typist, 0..9),3219
[FormatState::Mixed, FormatState::Off, FormatState::Off]3220
);3221
assert_eq!(3222
states(&mut typist, 0..3),3223
[FormatState::Off, FormatState::On, FormatState::Off]3224
);3225
assert_eq!(3226
typist.outgoing().html(),3227
"big <span style=\"font-size:xx-small;\">small</span>"3228
);3229
}3230
3118
#[gpui_kit::test]3231
#[gpui_kit::test]3119
fn pasted_markdown_converts_and_ctrl_z_restores_the_raw_text(cx: &mut TestAppContext) {3232
fn pasted_markdown_converts_and_ctrl_z_restores_the_raw_text(cx: &mut TestAppContext) {3120
let mut typist = typist(cx);3233
let mut typist = typist(cx);@@ -2,7 +2,7 @@ use std::ops::Range;
2
2
3
3
use gpui_kit::component::input::{RangeDecoration, RangeDecorationStyle, TextDecoration};
4
4
use gpui_kit::*;
5
use teams_core::{Draft, LineKind, MarkKind};
5
use teams_core::{Draft, LineKind, MarkKind, SizeStep};
6
6
7
7
use crate::theme;
8
8
@@ -60,6 +60,10 @@ fn mark_style(kind: &MarkKind) -> HighlightStyle {
60
60
color: None,
61
61
});
62
62
}
63
MarkKind::Superscript | MarkKind::Subscript | MarkKind::Size(SizeStep::Small) => {
64
style.color = Some(theme::text_soft());
65
}
66
MarkKind::Size(SizeStep::Large) => style.font_weight = Some(FontWeight::SEMIBOLD),
63
67
MarkKind::Code => style.color = Some(theme::text_strong()),
64
68
MarkKind::Link(_) => {
65
69
style.color = Some(theme::accent_text());
@@ -2,7 +2,7 @@ use std::ops::Range;2
2
3
use gpui_kit::component::input::{RangeDecoration, RangeDecorationStyle, TextDecoration};3
use gpui_kit::component::input::{RangeDecoration, RangeDecorationStyle, TextDecoration};4
use gpui_kit::*;4
use gpui_kit::*;5
use teams_core::{Draft, LineKind, MarkKind};5
use teams_core::{Draft, LineKind, MarkKind, SizeStep};6
6
7
use crate::theme;7
use crate::theme;8
8
@@ -60,6 +60,10 @@ fn mark_style(kind: &MarkKind) -> HighlightStyle {60
color: None,60
color: None,61
});61
});62
}62
}63
MarkKind::Superscript | MarkKind::Subscript | MarkKind::Size(SizeStep::Small) => {64
style.color = Some(theme::text_soft());65
}66
MarkKind::Size(SizeStep::Large) => style.font_weight = Some(FontWeight::SEMIBOLD),63
MarkKind::Code => style.color = Some(theme::text_strong()),67
MarkKind::Code => style.color = Some(theme::text_strong()),64
MarkKind::Link(_) => {68
MarkKind::Link(_) => {65
style.color = Some(theme::accent_text());69
style.color = Some(theme::accent_text());@@ -20,6 +20,11 @@ const ARROW_MARGIN: f32 = 12.;
20
20
const LINK_FIELD_WIDTH: f32 = 240.;
21
21
const APPLY_WIDTH: f32 = 64.;
22
22
const ACTIVE_ALPHA: f32 = 0.22;
23
const SMALL_LETTER: f32 = 11.;
24
const NORMAL_LETTER: f32 = 15.;
25
const LARGE_LETTER: f32 = 19.;
26
const SCRIPT_LETTER: f32 = 10.;
27
const SCRIPT_SHIFT: f32 = 4.;
23
28
24
29
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25
30
pub enum FormatButton {
@@ -27,6 +32,11 @@ pub enum FormatButton {
27
32
Italic,
28
33
Underline,
29
34
Strike,
35
Superscript,
36
Subscript,
37
SizeSmall,
38
SizeNormal,
39
SizeLarge,
30
40
Code,
31
41
Link,
32
42
Bulleted,
@@ -34,13 +44,19 @@ pub enum FormatButton {
34
44
Quote,
35
45
}
36
46
37
pub const GROUPS: [&[FormatButton]; 3] = [
47
pub const GROUPS: [&[FormatButton]; 5] = [
38
48
&[
39
49
FormatButton::Bold,
40
50
FormatButton::Italic,
41
51
FormatButton::Underline,
42
52
FormatButton::Strike,
43
53
],
54
&[FormatButton::Superscript, FormatButton::Subscript],
55
&[
56
FormatButton::SizeSmall,
57
FormatButton::SizeNormal,
58
FormatButton::SizeLarge,
59
],
44
60
&[FormatButton::Code, FormatButton::Link],
45
61
&[
46
62
FormatButton::Bulleted,
@@ -56,6 +72,11 @@ impl FormatButton {
56
72
FormatButton::Italic => "Italic (Ctrl+I)",
57
73
FormatButton::Underline => "Underline (Ctrl+U)",
58
74
FormatButton::Strike => "Strikethrough (Ctrl+Shift+X)",
75
FormatButton::Superscript => "Superscript (Ctrl+Shift+=)",
76
FormatButton::Subscript => "Subscript (Ctrl+=)",
77
FormatButton::SizeSmall => "Small text",
78
FormatButton::SizeNormal => "Normal text",
79
FormatButton::SizeLarge => "Large text",
59
80
FormatButton::Code => "Code (Ctrl+Shift+C)",
60
81
FormatButton::Link => "Link (Ctrl+K)",
61
82
FormatButton::Bulleted => "Bulleted list",
@@ -71,6 +92,11 @@ impl FormatButton {
71
92
FormatButton::Italic => letter("I").italic().into_any_element(),
72
93
FormatButton::Underline => letter("U").underline().into_any_element(),
73
94
FormatButton::Strike => letter("S").line_through().into_any_element(),
95
FormatButton::Superscript => script("x", "2", true, color),
96
FormatButton::Subscript => script("x", "2", false, color),
97
FormatButton::SizeSmall => sized_letter(SMALL_LETTER, color),
98
FormatButton::SizeNormal => sized_letter(NORMAL_LETTER, color),
99
FormatButton::SizeLarge => sized_letter(LARGE_LETTER, color),
74
100
FormatButton::Code => symbol("code", 18., color).into_any_element(),
75
101
FormatButton::Link => symbol("link", 18., color).into_any_element(),
76
102
FormatButton::Bulleted => symbol("format_list_bulleted", 18., color).into_any_element(),
@@ -80,6 +106,29 @@ impl FormatButton {
80
106
}
81
107
}
82
108
109
fn script(base: &'static str, mark: &'static str, raised: bool, color: Hsla) -> AnyElement {
110
h_flex()
111
.items_baseline()
112
.text_color(color)
113
.child(div().text_size(px(15.)).child(base))
114
.child(
115
div()
116
.text_size(px(SCRIPT_LETTER))
117
.when(raised, |mark| mark.mb(px(SCRIPT_SHIFT)))
118
.when(!raised, |mark| mark.mt(px(SCRIPT_SHIFT)))
119
.child(mark),
120
)
121
.into_any_element()
122
}
123
124
fn sized_letter(size: f32, color: Hsla) -> AnyElement {
125
div()
126
.text_size(px(size))
127
.text_color(color)
128
.child("A")
129
.into_any_element()
130
}
131
83
132
pub fn bar_width() -> f32 {
84
133
let buttons: usize = GROUPS.iter().map(|group| group.len()).sum();
85
134
let gaps: usize = GROUPS.iter().map(|group| group.len() - 1).sum();
@@ -332,8 +381,8 @@ mod tests {
332
381
}
333
382
334
383
#[test]
335
fn the_bar_holds_nine_buttons_in_three_groups() {
336
assert_eq!(GROUPS.iter().map(|group| group.len()).sum::<usize>(), 9);
337
assert!(bar_width() > 9. * BUTTON);
384
fn the_bar_holds_fourteen_buttons_in_five_groups() {
385
assert_eq!(GROUPS.iter().map(|group| group.len()).sum::<usize>(), 14);
386
assert!(bar_width() > 14. * BUTTON);
338
387
}
339
388
}
@@ -20,6 +20,11 @@ const ARROW_MARGIN: f32 = 12.;20
const LINK_FIELD_WIDTH: f32 = 240.;20
const LINK_FIELD_WIDTH: f32 = 240.;21
const APPLY_WIDTH: f32 = 64.;21
const APPLY_WIDTH: f32 = 64.;22
const ACTIVE_ALPHA: f32 = 0.22;22
const ACTIVE_ALPHA: f32 = 0.22;23
const SMALL_LETTER: f32 = 11.;24
const NORMAL_LETTER: f32 = 15.;25
const LARGE_LETTER: f32 = 19.;26
const SCRIPT_LETTER: f32 = 10.;27
const SCRIPT_SHIFT: f32 = 4.;23
28
24
#[derive(Debug, Clone, Copy, PartialEq, Eq)]29
#[derive(Debug, Clone, Copy, PartialEq, Eq)]25
pub enum FormatButton {30
pub enum FormatButton {@@ -27,6 +32,11 @@ pub enum FormatButton {27
Italic,32
Italic,28
Underline,33
Underline,29
Strike,34
Strike,35
Superscript,36
Subscript,37
SizeSmall,38
SizeNormal,39
SizeLarge,30
Code,40
Code,31
Link,41
Link,32
Bulleted,42
Bulleted,@@ -34,13 +44,19 @@ pub enum FormatButton {34
Quote,44
Quote,35
}45
}36
46
37
pub const GROUPS: [&[FormatButton]; 3] = [47
pub const GROUPS: [&[FormatButton]; 5] = [38
&[48
&[39
FormatButton::Bold,49
FormatButton::Bold,40
FormatButton::Italic,50
FormatButton::Italic,41
FormatButton::Underline,51
FormatButton::Underline,42
FormatButton::Strike,52
FormatButton::Strike,43
],53
],54
&[FormatButton::Superscript, FormatButton::Subscript],55
&[56
FormatButton::SizeSmall,57
FormatButton::SizeNormal,58
FormatButton::SizeLarge,59
],44
&[FormatButton::Code, FormatButton::Link],60
&[FormatButton::Code, FormatButton::Link],45
&[61
&[46
FormatButton::Bulleted,62
FormatButton::Bulleted,@@ -56,6 +72,11 @@ impl FormatButton {56
FormatButton::Italic => "Italic (Ctrl+I)",72
FormatButton::Italic => "Italic (Ctrl+I)",57
FormatButton::Underline => "Underline (Ctrl+U)",73
FormatButton::Underline => "Underline (Ctrl+U)",58
FormatButton::Strike => "Strikethrough (Ctrl+Shift+X)",74
FormatButton::Strike => "Strikethrough (Ctrl+Shift+X)",75
FormatButton::Superscript => "Superscript (Ctrl+Shift+=)",76
FormatButton::Subscript => "Subscript (Ctrl+=)",77
FormatButton::SizeSmall => "Small text",78
FormatButton::SizeNormal => "Normal text",79
FormatButton::SizeLarge => "Large text",59
FormatButton::Code => "Code (Ctrl+Shift+C)",80
FormatButton::Code => "Code (Ctrl+Shift+C)",60
FormatButton::Link => "Link (Ctrl+K)",81
FormatButton::Link => "Link (Ctrl+K)",61
FormatButton::Bulleted => "Bulleted list",82
FormatButton::Bulleted => "Bulleted list",@@ -71,6 +92,11 @@ impl FormatButton {71
FormatButton::Italic => letter("I").italic().into_any_element(),92
FormatButton::Italic => letter("I").italic().into_any_element(),72
FormatButton::Underline => letter("U").underline().into_any_element(),93
FormatButton::Underline => letter("U").underline().into_any_element(),73
FormatButton::Strike => letter("S").line_through().into_any_element(),94
FormatButton::Strike => letter("S").line_through().into_any_element(),95
FormatButton::Superscript => script("x", "2", true, color),96
FormatButton::Subscript => script("x", "2", false, color),97
FormatButton::SizeSmall => sized_letter(SMALL_LETTER, color),98
FormatButton::SizeNormal => sized_letter(NORMAL_LETTER, color),99
FormatButton::SizeLarge => sized_letter(LARGE_LETTER, color),74
FormatButton::Code => symbol("code", 18., color).into_any_element(),100
FormatButton::Code => symbol("code", 18., color).into_any_element(),75
FormatButton::Link => symbol("link", 18., color).into_any_element(),101
FormatButton::Link => symbol("link", 18., color).into_any_element(),76
FormatButton::Bulleted => symbol("format_list_bulleted", 18., color).into_any_element(),102
FormatButton::Bulleted => symbol("format_list_bulleted", 18., color).into_any_element(),@@ -80,6 +106,29 @@ impl FormatButton {80
}106
}81
}107
}82
108
109
fn script(base: &'static str, mark: &'static str, raised: bool, color: Hsla) -> AnyElement {110
h_flex()111
.items_baseline()112
.text_color(color)113
.child(div().text_size(px(15.)).child(base))114
.child(115
div()116
.text_size(px(SCRIPT_LETTER))117
.when(raised, |mark| mark.mb(px(SCRIPT_SHIFT)))118
.when(!raised, |mark| mark.mt(px(SCRIPT_SHIFT)))119
.child(mark),120
)121
.into_any_element()122
}123
124
fn sized_letter(size: f32, color: Hsla) -> AnyElement {125
div()126
.text_size(px(size))127
.text_color(color)128
.child("A")129
.into_any_element()130
}131
83
pub fn bar_width() -> f32 {132
pub fn bar_width() -> f32 {84
let buttons: usize = GROUPS.iter().map(|group| group.len()).sum();133
let buttons: usize = GROUPS.iter().map(|group| group.len()).sum();85
let gaps: usize = GROUPS.iter().map(|group| group.len() - 1).sum();134
let gaps: usize = GROUPS.iter().map(|group| group.len() - 1).sum();@@ -332,8 +381,8 @@ mod tests {332
}381
}333
382
334
#[test]383
#[test]335
fn the_bar_holds_nine_buttons_in_three_groups() {384
fn the_bar_holds_fourteen_buttons_in_five_groups() {336
assert_eq!(GROUPS.iter().map(|group| group.len()).sum::<usize>(), 9);385
assert_eq!(GROUPS.iter().map(|group| group.len()).sum::<usize>(), 14);337
assert!(bar_width() > 9. * BUTTON);386
assert!(bar_width() > 14. * BUTTON);338
}387
}339
}388
}@@ -5,7 +5,7 @@ use regex::Regex;
5
5
use serde::{Deserialize, Serialize};
6
6
7
7
use crate::markdown::escape_html;
8
use crate::spans::Span;
8
use crate::spans::{FontSize, Span};
9
9
10
10
pub const MAX_DEPTH: u8 = 2;
11
11
pub const OBJECT_MARK: char = '\u{FFFC}';
@@ -22,6 +22,21 @@ static TYPED_LINK: LazyLock<Regex> =
22
22
static LINK_AT: LazyLock<Regex> =
23
23
LazyLock::new(|| Regex::new(r"^\[([^\]\n]+)\]\(([^)\s]+)\)").unwrap());
24
24
25
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
26
pub enum SizeStep {
27
Small,
28
Large,
29
}
30
31
impl SizeStep {
32
fn css(self) -> &'static str {
33
match self {
34
SizeStep::Small => "xx-small",
35
SizeStep::Large => "x-large",
36
}
37
}
38
}
39
25
40
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
26
41
pub enum MarkKind {
27
42
Link(String),
@@ -29,6 +44,9 @@ pub enum MarkKind {
29
44
Italic,
30
45
Underline,
31
46
Strike,
47
Superscript,
48
Subscript,
49
Size(SizeStep),
32
50
Code,
33
51
}
34
52
@@ -37,10 +55,31 @@ impl MarkKind {
37
55
std::mem::discriminant(self) == std::mem::discriminant(other)
38
56
}
39
57
58
fn covers(&self, other: &MarkKind) -> bool {
59
match (self, other) {
60
(MarkKind::Size(left), MarkKind::Size(right)) => left == right,
61
_ => self.same_format(other),
62
}
63
}
64
65
fn opposite_script(&self) -> Option<MarkKind> {
66
match self {
67
MarkKind::Superscript => Some(MarkKind::Subscript),
68
MarkKind::Subscript => Some(MarkKind::Superscript),
69
_ => None,
70
}
71
}
72
40
73
fn continues_at_end(&self) -> bool {
41
74
matches!(
42
75
self,
43
MarkKind::Bold | MarkKind::Italic | MarkKind::Underline | MarkKind::Strike
76
MarkKind::Bold
77
| MarkKind::Italic
78
| MarkKind::Underline
79
| MarkKind::Strike
80
| MarkKind::Superscript
81
| MarkKind::Subscript
82
| MarkKind::Size(_)
44
83
)
45
84
}
46
85
@@ -51,6 +90,9 @@ impl MarkKind {
51
90
MarkKind::Italic => "<i>".to_owned(),
52
91
MarkKind::Underline => "<u>".to_owned(),
53
92
MarkKind::Strike => "<s>".to_owned(),
93
MarkKind::Superscript => "<sup>".to_owned(),
94
MarkKind::Subscript => "<sub>".to_owned(),
95
MarkKind::Size(step) => format!("<span style=\"font-size:{};\">", step.css()),
54
96
MarkKind::Code => "<code>".to_owned(),
55
97
}
56
98
}
@@ -62,6 +104,9 @@ impl MarkKind {
62
104
MarkKind::Italic => "</i>",
63
105
MarkKind::Underline => "</u>",
64
106
MarkKind::Strike => "</s>",
107
MarkKind::Superscript => "</sup>",
108
MarkKind::Subscript => "</sub>",
109
MarkKind::Size(_) => "</span>",
65
110
MarkKind::Code => "</code>",
66
111
}
67
112
}
@@ -142,10 +187,36 @@ impl TypingStyle {
142
187
self.remove.retain(|removed| !removed.same_format(&kind));
143
188
let inherited = active.iter().any(|existing| existing.same_format(&kind));
144
189
match (is_active, inherited) {
145
(true, true) => self.remove.push(kind),
146
(false, false) => self.add.push(kind),
190
(true, true) => self.remove.push(kind.clone()),
191
(false, false) => self.add.push(kind.clone()),
147
192
_ => {}
148
193
}
194
if let Some(opposite) = kind.opposite_script()
195
&& self.add.contains(&kind)
196
{
197
self.add.retain(|added| !added.same_format(&opposite));
198
self.remove
199
.retain(|removed| !removed.same_format(&opposite));
200
if active
201
.iter()
202
.any(|existing| existing.same_format(&opposite))
203
{
204
self.remove.push(opposite);
205
}
206
}
207
}
208
209
/// `None` is the normal size.
210
pub fn set_size(&mut self, size: Option<SizeStep>, active: &[MarkKind]) {
211
let marker = MarkKind::Size(SizeStep::Small);
212
self.add.retain(|added| !added.same_format(&marker));
213
self.remove.retain(|removed| !removed.same_format(&marker));
214
if active.iter().any(|existing| existing.same_format(&marker)) {
215
self.remove.push(marker);
216
}
217
if let Some(step) = size {
218
self.add.push(MarkKind::Size(step));
219
}
149
220
}
150
221
151
222
pub fn is_empty(&self) -> bool {
@@ -417,7 +488,7 @@ impl Draft {
417
488
let mut ranges: Vec<Range<usize>> = self
418
489
.marks
419
490
.iter()
420
.filter(|mark| mark.kind.same_format(kind))
491
.filter(|mark| mark.kind.covers(kind))
421
492
.map(|mark| mark.range.start.max(part.start)..mark.range.end.min(part.end))
422
493
.filter(|range| !range.is_empty())
423
494
.collect();
@@ -482,12 +553,32 @@ impl Draft {
482
553
if self.state(range.clone(), &kind) == FormatState::On {
483
554
self.remove_marks(range, &kind);
484
555
} else {
556
if let Some(opposite) = kind.opposite_script() {
557
self.remove_marks(range.clone(), &opposite);
558
}
485
559
for part in self.content_parts(range) {
486
560
self.add_mark(part, kind.clone());
487
561
}
488
562
}
489
563
}
490
564
565
/// `None` is the normal size: any size mark on `range` is removed.
566
pub fn set_size(&mut self, range: Range<usize>, size: Option<SizeStep>) {
567
self.journal = Journal::default();
568
self.remove_marks(range.clone(), &MarkKind::Size(SizeStep::Small));
569
if let Some(step) = size {
570
for part in self.content_parts(range) {
571
self.add_mark(part, MarkKind::Size(step));
572
}
573
}
574
}
575
576
pub fn size_in(&self, range: Range<usize>) -> Option<SizeStep> {
577
[SizeStep::Small, SizeStep::Large]
578
.into_iter()
579
.find(|step| self.state(range.clone(), &MarkKind::Size(*step)) == FormatState::On)
580
}
581
491
582
/// An empty `url` removes the link; one `link_url` refuses changes nothing.
492
583
pub fn set_link(&mut self, range: Range<usize>, url: &str) {
493
584
self.journal = Journal::default();
@@ -1814,6 +1905,17 @@ impl SpanLines {
1814
1905
Span::Italic(children) => self.walk(children, kind, &with(MarkKind::Italic)),
1815
1906
Span::Strike(children) => self.walk(children, kind, &with(MarkKind::Strike)),
1816
1907
Span::Underline(children) => self.walk(children, kind, &with(MarkKind::Underline)),
1908
Span::Superscript(children) => {
1909
self.walk(children, kind, &with(MarkKind::Superscript))
1910
}
1911
Span::Subscript(children) => self.walk(children, kind, &with(MarkKind::Subscript)),
1912
Span::Sized(FontSize::Small, children) => {
1913
self.walk(children, kind, &with(MarkKind::Size(SizeStep::Small)))
1914
}
1915
Span::Sized(FontSize::Large, children) => {
1916
self.walk(children, kind, &with(MarkKind::Size(SizeStep::Large)))
1917
}
1918
Span::Sized(_, children) => self.walk(children, kind, marks),
1817
1919
Span::Colored { children, .. } => self.walk(children, kind, marks),
1818
1920
Span::Code(text) => self.append(text, kind, &with(MarkKind::Code)),
1819
1921
Span::Link { url, children } => {
@@ -2368,6 +2470,84 @@ mod tests {
2368
2470
);
2369
2471
}
2370
2472
2473
#[test]
2474
fn script_and_size_marks_export_teams_html() {
2475
let mut draft = Draft::plain("x2 H2O big tiny");
2476
draft.toggle(1..2, MarkKind::Superscript);
2477
draft.toggle(4..5, MarkKind::Subscript);
2478
draft.set_size(7..10, Some(SizeStep::Large));
2479
draft.set_size(11..15, Some(SizeStep::Small));
2480
assert_eq!(
2481
draft.to_html(),
2482
"x<sup>2</sup> H<sub>2</sub>O <span style=\"font-size:x-large;\">big</span> \
2483
<span style=\"font-size:xx-small;\">tiny</span>"
2484
);
2485
}
2486
2487
#[test]
2488
fn script_and_size_marks_round_trip_through_html() {
2489
let mut source = Draft::plain("x2 H2O big tiny");
2490
source.toggle(1..2, MarkKind::Superscript);
2491
source.toggle(4..5, MarkKind::Subscript);
2492
source.toggle(7..10, MarkKind::Bold);
2493
source.set_size(7..10, Some(SizeStep::Large));
2494
source.set_size(11..15, Some(SizeStep::Small));
2495
let back = Draft::from_spans(&html_to_spans(&source.to_html()));
2496
assert_eq!(back.text(), source.text());
2497
assert_eq!(back.marks(), source.marks());
2498
}
2499
2500
#[test]
2501
fn inherit_and_pixel_sizes_import_without_a_size_mark() {
2502
let spans = html_to_spans(
2503
"<span style=\"font-size:inherit;\">a</span><span style=\"font-size:14px\">b</span>",
2504
);
2505
assert!(Draft::from_spans(&spans).marks().is_empty());
2506
}
2507
2508
#[test]
2509
fn superscript_and_subscript_exclude_each_other() {
2510
let mut draft = Draft::plain("abcdef");
2511
draft.toggle(0..4, MarkKind::Superscript);
2512
draft.toggle(2..6, MarkKind::Subscript);
2513
assert_eq!(
2514
draft.marks(),
2515
[
2516
mark(0..2, MarkKind::Superscript),
2517
mark(2..6, MarkKind::Subscript)
2518
]
2519
);
2520
}
2521
2522
#[test]
2523
fn typing_style_switches_between_script_marks() {
2524
let mut style = TypingStyle::default();
2525
style.toggle(MarkKind::Subscript, &[MarkKind::Superscript]);
2526
assert_eq!(
2527
style.apply(vec![MarkKind::Superscript]),
2528
vec![MarkKind::Subscript]
2529
);
2530
}
2531
2532
#[test]
2533
fn size_changes_on_a_partial_range_split_the_mark() {
2534
let mut draft = Draft::plain("abcdef");
2535
draft.set_size(0..6, Some(SizeStep::Large));
2536
draft.set_size(2..4, Some(SizeStep::Small));
2537
assert_eq!(
2538
draft.marks(),
2539
[
2540
mark(2..4, MarkKind::Size(SizeStep::Small)),
2541
mark(0..2, MarkKind::Size(SizeStep::Large)),
2542
mark(4..6, MarkKind::Size(SizeStep::Large)),
2543
]
2544
);
2545
assert_eq!(draft.size_in(2..4), Some(SizeStep::Small));
2546
assert_eq!(draft.size_in(0..6), None);
2547
draft.set_size(0..6, None);
2548
assert!(draft.marks().is_empty());
2549
}
2550
2371
2551
#[test]
2372
2552
fn ordered_lists_keep_their_start() {
2373
2553
let draft = Draft::from_markdown("3. c\n4. d");
@@ -5,7 +5,7 @@ use regex::Regex;5
use serde::{Deserialize, Serialize};5
use serde::{Deserialize, Serialize};6
6
7
use crate::markdown::escape_html;7
use crate::markdown::escape_html;8
use crate::spans::Span;8
use crate::spans::{FontSize, Span};9
9
10
pub const MAX_DEPTH: u8 = 2;10
pub const MAX_DEPTH: u8 = 2;11
pub const OBJECT_MARK: char = '\u{FFFC}';11
pub const OBJECT_MARK: char = '\u{FFFC}';@@ -22,6 +22,21 @@ static TYPED_LINK: LazyLock<Regex> =22
static LINK_AT: LazyLock<Regex> =22
static LINK_AT: LazyLock<Regex> =23
LazyLock::new(|| Regex::new(r"^\[([^\]\n]+)\]\(([^)\s]+)\)").unwrap());23
LazyLock::new(|| Regex::new(r"^\[([^\]\n]+)\]\(([^)\s]+)\)").unwrap());24
24
25
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]26
pub enum SizeStep {27
Small,28
Large,29
}30
31
impl SizeStep {32
fn css(self) -> &'static str {33
match self {34
SizeStep::Small => "xx-small",35
SizeStep::Large => "x-large",36
}37
}38
}39
25
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]40
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]26
pub enum MarkKind {41
pub enum MarkKind {27
Link(String),42
Link(String),@@ -29,6 +44,9 @@ pub enum MarkKind {29
Italic,44
Italic,30
Underline,45
Underline,31
Strike,46
Strike,47
Superscript,48
Subscript,49
Size(SizeStep),32
Code,50
Code,33
}51
}34
52
@@ -37,10 +55,31 @@ impl MarkKind {37
std::mem::discriminant(self) == std::mem::discriminant(other)55
std::mem::discriminant(self) == std::mem::discriminant(other)38
}56
}39
57
58
fn covers(&self, other: &MarkKind) -> bool {59
match (self, other) {60
(MarkKind::Size(left), MarkKind::Size(right)) => left == right,61
_ => self.same_format(other),62
}63
}64
65
fn opposite_script(&self) -> Option<MarkKind> {66
match self {67
MarkKind::Superscript => Some(MarkKind::Subscript),68
MarkKind::Subscript => Some(MarkKind::Superscript),69
_ => None,70
}71
}72
40
fn continues_at_end(&self) -> bool {73
fn continues_at_end(&self) -> bool {41
matches!(74
matches!(42
self,75
self,43
MarkKind::Bold | MarkKind::Italic | MarkKind::Underline | MarkKind::Strike76
MarkKind::Bold77
| MarkKind::Italic78
| MarkKind::Underline79
| MarkKind::Strike80
| MarkKind::Superscript81
| MarkKind::Subscript82
| MarkKind::Size(_)44
)83
)45
}84
}46
85
@@ -51,6 +90,9 @@ impl MarkKind {51
MarkKind::Italic => "<i>".to_owned(),90
MarkKind::Italic => "<i>".to_owned(),52
MarkKind::Underline => "<u>".to_owned(),91
MarkKind::Underline => "<u>".to_owned(),53
MarkKind::Strike => "<s>".to_owned(),92
MarkKind::Strike => "<s>".to_owned(),93
MarkKind::Superscript => "<sup>".to_owned(),94
MarkKind::Subscript => "<sub>".to_owned(),95
MarkKind::Size(step) => format!("<span style=\"font-size:{};\">", step.css()),54
MarkKind::Code => "<code>".to_owned(),96
MarkKind::Code => "<code>".to_owned(),55
}97
}56
}98
}@@ -62,6 +104,9 @@ impl MarkKind {62
MarkKind::Italic => "</i>",104
MarkKind::Italic => "</i>",63
MarkKind::Underline => "</u>",105
MarkKind::Underline => "</u>",64
MarkKind::Strike => "</s>",106
MarkKind::Strike => "</s>",107
MarkKind::Superscript => "</sup>",108
MarkKind::Subscript => "</sub>",109
MarkKind::Size(_) => "</span>",65
MarkKind::Code => "</code>",110
MarkKind::Code => "</code>",66
}111
}67
}112
}@@ -142,10 +187,36 @@ impl TypingStyle {142
self.remove.retain(|removed| !removed.same_format(&kind));187
self.remove.retain(|removed| !removed.same_format(&kind));143
let inherited = active.iter().any(|existing| existing.same_format(&kind));188
let inherited = active.iter().any(|existing| existing.same_format(&kind));144
match (is_active, inherited) {189
match (is_active, inherited) {145
(true, true) => self.remove.push(kind),190
(true, true) => self.remove.push(kind.clone()),146
(false, false) => self.add.push(kind),191
(false, false) => self.add.push(kind.clone()),147
_ => {}192
_ => {}148
}193
}194
if let Some(opposite) = kind.opposite_script()195
&& self.add.contains(&kind)196
{197
self.add.retain(|added| !added.same_format(&opposite));198
self.remove199
.retain(|removed| !removed.same_format(&opposite));200
if active201
.iter()202
.any(|existing| existing.same_format(&opposite))203
{204
self.remove.push(opposite);205
}206
}207
}208
209
/// `None` is the normal size.210
pub fn set_size(&mut self, size: Option<SizeStep>, active: &[MarkKind]) {211
let marker = MarkKind::Size(SizeStep::Small);212
self.add.retain(|added| !added.same_format(&marker));213
self.remove.retain(|removed| !removed.same_format(&marker));214
if active.iter().any(|existing| existing.same_format(&marker)) {215
self.remove.push(marker);216
}217
if let Some(step) = size {218
self.add.push(MarkKind::Size(step));219
}149
}220
}150
221
151
pub fn is_empty(&self) -> bool {222
pub fn is_empty(&self) -> bool {@@ -417,7 +488,7 @@ impl Draft {417
let mut ranges: Vec<Range<usize>> = self488
let mut ranges: Vec<Range<usize>> = self418
.marks489
.marks419
.iter()490
.iter()420
.filter(|mark| mark.kind.same_format(kind))491
.filter(|mark| mark.kind.covers(kind))421
.map(|mark| mark.range.start.max(part.start)..mark.range.end.min(part.end))492
.map(|mark| mark.range.start.max(part.start)..mark.range.end.min(part.end))422
.filter(|range| !range.is_empty())493
.filter(|range| !range.is_empty())423
.collect();494
.collect();@@ -482,12 +553,32 @@ impl Draft {482
if self.state(range.clone(), &kind) == FormatState::On {553
if self.state(range.clone(), &kind) == FormatState::On {483
self.remove_marks(range, &kind);554
self.remove_marks(range, &kind);484
} else {555
} else {556
if let Some(opposite) = kind.opposite_script() {557
self.remove_marks(range.clone(), &opposite);558
}485
for part in self.content_parts(range) {559
for part in self.content_parts(range) {486
self.add_mark(part, kind.clone());560
self.add_mark(part, kind.clone());487
}561
}488
}562
}489
}563
}490
564
565
/// `None` is the normal size: any size mark on `range` is removed.566
pub fn set_size(&mut self, range: Range<usize>, size: Option<SizeStep>) {567
self.journal = Journal::default();568
self.remove_marks(range.clone(), &MarkKind::Size(SizeStep::Small));569
if let Some(step) = size {570
for part in self.content_parts(range) {571
self.add_mark(part, MarkKind::Size(step));572
}573
}574
}575
576
pub fn size_in(&self, range: Range<usize>) -> Option<SizeStep> {577
[SizeStep::Small, SizeStep::Large]578
.into_iter()579
.find(|step| self.state(range.clone(), &MarkKind::Size(*step)) == FormatState::On)580
}581
491
/// An empty `url` removes the link; one `link_url` refuses changes nothing.582
/// An empty `url` removes the link; one `link_url` refuses changes nothing.492
pub fn set_link(&mut self, range: Range<usize>, url: &str) {583
pub fn set_link(&mut self, range: Range<usize>, url: &str) {493
self.journal = Journal::default();584
self.journal = Journal::default();@@ -1814,6 +1905,17 @@ impl SpanLines {1814
Span::Italic(children) => self.walk(children, kind, &with(MarkKind::Italic)),1905
Span::Italic(children) => self.walk(children, kind, &with(MarkKind::Italic)),1815
Span::Strike(children) => self.walk(children, kind, &with(MarkKind::Strike)),1906
Span::Strike(children) => self.walk(children, kind, &with(MarkKind::Strike)),1816
Span::Underline(children) => self.walk(children, kind, &with(MarkKind::Underline)),1907
Span::Underline(children) => self.walk(children, kind, &with(MarkKind::Underline)),1908
Span::Superscript(children) => {1909
self.walk(children, kind, &with(MarkKind::Superscript))1910
}1911
Span::Subscript(children) => self.walk(children, kind, &with(MarkKind::Subscript)),1912
Span::Sized(FontSize::Small, children) => {1913
self.walk(children, kind, &with(MarkKind::Size(SizeStep::Small)))1914
}1915
Span::Sized(FontSize::Large, children) => {1916
self.walk(children, kind, &with(MarkKind::Size(SizeStep::Large)))1917
}1918
Span::Sized(_, children) => self.walk(children, kind, marks),1817
Span::Colored { children, .. } => self.walk(children, kind, marks),1919
Span::Colored { children, .. } => self.walk(children, kind, marks),1818
Span::Code(text) => self.append(text, kind, &with(MarkKind::Code)),1920
Span::Code(text) => self.append(text, kind, &with(MarkKind::Code)),1819
Span::Link { url, children } => {1921
Span::Link { url, children } => {@@ -2368,6 +2470,84 @@ mod tests {2368
);2470
);2369
}2471
}2370
2472
2473
#[test]2474
fn script_and_size_marks_export_teams_html() {2475
let mut draft = Draft::plain("x2 H2O big tiny");2476
draft.toggle(1..2, MarkKind::Superscript);2477
draft.toggle(4..5, MarkKind::Subscript);2478
draft.set_size(7..10, Some(SizeStep::Large));2479
draft.set_size(11..15, Some(SizeStep::Small));2480
assert_eq!(2481
draft.to_html(),2482
"x<sup>2</sup> H<sub>2</sub>O <span style=\"font-size:x-large;\">big</span> \2483
<span style=\"font-size:xx-small;\">tiny</span>"2484
);2485
}2486
2487
#[test]2488
fn script_and_size_marks_round_trip_through_html() {2489
let mut source = Draft::plain("x2 H2O big tiny");2490
source.toggle(1..2, MarkKind::Superscript);2491
source.toggle(4..5, MarkKind::Subscript);2492
source.toggle(7..10, MarkKind::Bold);2493
source.set_size(7..10, Some(SizeStep::Large));2494
source.set_size(11..15, Some(SizeStep::Small));2495
let back = Draft::from_spans(&html_to_spans(&source.to_html()));2496
assert_eq!(back.text(), source.text());2497
assert_eq!(back.marks(), source.marks());2498
}2499
2500
#[test]2501
fn inherit_and_pixel_sizes_import_without_a_size_mark() {2502
let spans = html_to_spans(2503
"<span style=\"font-size:inherit;\">a</span><span style=\"font-size:14px\">b</span>",2504
);2505
assert!(Draft::from_spans(&spans).marks().is_empty());2506
}2507
2508
#[test]2509
fn superscript_and_subscript_exclude_each_other() {2510
let mut draft = Draft::plain("abcdef");2511
draft.toggle(0..4, MarkKind::Superscript);2512
draft.toggle(2..6, MarkKind::Subscript);2513
assert_eq!(2514
draft.marks(),2515
[2516
mark(0..2, MarkKind::Superscript),2517
mark(2..6, MarkKind::Subscript)2518
]2519
);2520
}2521
2522
#[test]2523
fn typing_style_switches_between_script_marks() {2524
let mut style = TypingStyle::default();2525
style.toggle(MarkKind::Subscript, &[MarkKind::Superscript]);2526
assert_eq!(2527
style.apply(vec![MarkKind::Superscript]),2528
vec![MarkKind::Subscript]2529
);2530
}2531
2532
#[test]2533
fn size_changes_on_a_partial_range_split_the_mark() {2534
let mut draft = Draft::plain("abcdef");2535
draft.set_size(0..6, Some(SizeStep::Large));2536
draft.set_size(2..4, Some(SizeStep::Small));2537
assert_eq!(2538
draft.marks(),2539
[2540
mark(2..4, MarkKind::Size(SizeStep::Small)),2541
mark(0..2, MarkKind::Size(SizeStep::Large)),2542
mark(4..6, MarkKind::Size(SizeStep::Large)),2543
]2544
);2545
assert_eq!(draft.size_in(2..4), Some(SizeStep::Small));2546
assert_eq!(draft.size_in(0..6), None);2547
draft.set_size(0..6, None);2548
assert!(draft.marks().is_empty());2549
}2550
2371
#[test]2551
#[test]2372
fn ordered_lists_keep_their_start() {2552
fn ordered_lists_keep_their_start() {2373
let draft = Draft::from_markdown("3. c\n4. d");2553
let draft = Draft::from_markdown("3. c\n4. d");@@ -41,7 +41,7 @@ pub use card_inputs::{
41
41
pub use chatsvc::ChatApp;
42
42
pub use draft::{
43
43
Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,
44
TypingStyle, changed_span, has_markdown, link_url, map_offset, reverse_edits,
44
SizeStep, TypingStyle, changed_span, has_markdown, link_url, map_offset, reverse_edits,
45
45
};
46
46
pub use engine::{Delta, Me, SidebarSummary, SyncConfig, SyncEngine};
47
47
pub use error::{Error, Result};
@@ -60,7 +60,7 @@ pub use presence::{Availability, Presence};
60
60
pub use preview::preview_text;
61
61
pub use receipts::{ReceiptReader, ReceiptState};
62
62
pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};
63
pub use spans::{Span, html_to_spans};
63
pub use spans::{FontSize, Span, html_to_spans};
64
64
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};
65
65
pub use stored::{
66
66
AttachmentInfo, FileCard, FileKind, ImageRef, MentionInfo, QuoteInfo, ReactionInfo,
@@ -41,7 +41,7 @@ pub use card_inputs::{41
pub use chatsvc::ChatApp;41
pub use chatsvc::ChatApp;42
pub use draft::{42
pub use draft::{43
Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,43
Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,44
TypingStyle, changed_span, has_markdown, link_url, map_offset, reverse_edits,44
SizeStep, TypingStyle, changed_span, has_markdown, link_url, map_offset, reverse_edits,45
};45
};46
pub use engine::{Delta, Me, SidebarSummary, SyncConfig, SyncEngine};46
pub use engine::{Delta, Me, SidebarSummary, SyncConfig, SyncEngine};47
pub use error::{Error, Result};47
pub use error::{Error, Result};@@ -60,7 +60,7 @@ pub use presence::{Availability, Presence};60
pub use preview::preview_text;60
pub use preview::preview_text;61
pub use receipts::{ReceiptReader, ReceiptState};61
pub use receipts::{ReceiptReader, ReceiptState};62
pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};62
pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};63
pub use spans::{Span, html_to_spans};63
pub use spans::{FontSize, Span, html_to_spans};64
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};64
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};65
pub use stored::{65
pub use stored::{66
AttachmentInfo, FileCard, FileKind, ImageRef, MentionInfo, QuoteInfo, ReactionInfo,66
AttachmentInfo, FileCard, FileKind, ImageRef, MentionInfo, QuoteInfo, ReactionInfo,@@ -1,5 +1,13 @@
1
1
use scraper::{ElementRef, Html, Node};
2
2
3
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4
pub enum FontSize {
5
Small,
6
Large,
7
Hidden,
8
Pixels(u16),
9
}
10
3
11
#[derive(Debug, Clone, PartialEq, Eq)]
4
12
pub enum Span {
5
13
Text(String),
@@ -19,6 +27,9 @@ pub enum Span {
19
27
id: Option<String>,
20
28
},
21
29
Strike(Vec<Span>),
30
Superscript(Vec<Span>),
31
Subscript(Vec<Span>),
32
Sized(FontSize, Vec<Span>),
22
33
Underline(Vec<Span>),
23
34
Colored {
24
35
color: Option<u32>,
@@ -111,6 +122,8 @@ fn convert_element(element: ElementRef<'_>, spans: &mut Vec<Span>) {
111
122
}),
112
123
"i" | "em" => spans.push(Span::Italic(convert_children(element))),
113
124
"s" | "strike" | "del" => spans.push(Span::Strike(convert_children(element))),
125
"sup" => spans.push(Span::Superscript(convert_children(element))),
126
"sub" => spans.push(Span::Subscript(convert_children(element))),
114
127
"u" | "ins" => spans.push(Span::Underline(convert_children(element))),
115
128
"span" | "font" | "mark" => push_colored(element, spans),
116
129
"ul" | "ol" => spans.push(list(element)),
@@ -214,15 +227,37 @@ fn push_colored(element: ElementRef<'_>, spans: &mut Vec<Span>) {
214
227
.or_else(|| style_value(style, "background"))
215
228
.and_then(parse_color)
216
229
.or((value.name() == "mark").then_some(MARK_BACKGROUND));
217
let children = convert_children(element);
218
if color.is_none() && background.is_none() {
219
spans.extend(children);
220
} else {
221
spans.push(Span::Colored {
230
let size = style_value(style, "font-size").and_then(parse_font_size);
231
let mut children = convert_children(element);
232
if color.is_some() || background.is_some() {
233
children = vec![Span::Colored {
222
234
color,
223
235
background,
224
236
children,
225
});
237
}];
238
}
239
match size {
240
Some(size) => spans.push(Span::Sized(size, children)),
241
None => spans.extend(children),
242
}
243
}
244
245
fn parse_font_size(value: &str) -> Option<FontSize> {
246
let value = value.trim().to_ascii_lowercase();
247
match value.as_str() {
248
"xx-small" | "x-small" | "small" | "smaller" => Some(FontSize::Small),
249
"large" | "x-large" | "xx-large" | "larger" => Some(FontSize::Large),
250
"0" => Some(FontSize::Hidden),
251
_ => {
252
let pixels: f32 = value.strip_suffix("px")?.trim().parse().ok()?;
253
if pixels <= 0. {
254
Some(FontSize::Hidden)
255
} else {
256
Some(FontSize::Pixels(
257
pixels.round().min(f32::from(u16::MAX)) as u16
258
))
259
}
260
}
226
261
}
227
262
}
228
263
@@ -371,6 +406,9 @@ fn tidy(spans: &mut Vec<Span>) {
371
406
Span::Bold(children)
372
407
| Span::Italic(children)
373
408
| Span::Strike(children)
409
| Span::Superscript(children)
410
| Span::Subscript(children)
411
| Span::Sized(_, children)
374
412
| Span::Underline(children)
375
413
| Span::Colored { children, .. }
376
414
| Span::Heading { children, .. }
@@ -1,5 +1,13 @@1
use scraper::{ElementRef, Html, Node};1
use scraper::{ElementRef, Html, Node};2
2
3
#[derive(Debug, Clone, Copy, PartialEq, Eq)]4
pub enum FontSize {5
Small,6
Large,7
Hidden,8
Pixels(u16),9
}10
3
#[derive(Debug, Clone, PartialEq, Eq)]11
#[derive(Debug, Clone, PartialEq, Eq)]4
pub enum Span {12
pub enum Span {5
Text(String),13
Text(String),@@ -19,6 +27,9 @@ pub enum Span {19
id: Option<String>,27
id: Option<String>,20
},28
},21
Strike(Vec<Span>),29
Strike(Vec<Span>),30
Superscript(Vec<Span>),31
Subscript(Vec<Span>),32
Sized(FontSize, Vec<Span>),22
Underline(Vec<Span>),33
Underline(Vec<Span>),23
Colored {34
Colored {24
color: Option<u32>,35
color: Option<u32>,@@ -111,6 +122,8 @@ fn convert_element(element: ElementRef<'_>, spans: &mut Vec<Span>) {111
}),122
}),112
"i" | "em" => spans.push(Span::Italic(convert_children(element))),123
"i" | "em" => spans.push(Span::Italic(convert_children(element))),113
"s" | "strike" | "del" => spans.push(Span::Strike(convert_children(element))),124
"s" | "strike" | "del" => spans.push(Span::Strike(convert_children(element))),125
"sup" => spans.push(Span::Superscript(convert_children(element))),126
"sub" => spans.push(Span::Subscript(convert_children(element))),114
"u" | "ins" => spans.push(Span::Underline(convert_children(element))),127
"u" | "ins" => spans.push(Span::Underline(convert_children(element))),115
"span" | "font" | "mark" => push_colored(element, spans),128
"span" | "font" | "mark" => push_colored(element, spans),116
"ul" | "ol" => spans.push(list(element)),129
"ul" | "ol" => spans.push(list(element)),@@ -214,15 +227,37 @@ fn push_colored(element: ElementRef<'_>, spans: &mut Vec<Span>) {214
.or_else(|| style_value(style, "background"))227
.or_else(|| style_value(style, "background"))215
.and_then(parse_color)228
.and_then(parse_color)216
.or((value.name() == "mark").then_some(MARK_BACKGROUND));229
.or((value.name() == "mark").then_some(MARK_BACKGROUND));217
let children = convert_children(element);230
let size = style_value(style, "font-size").and_then(parse_font_size);218
if color.is_none() && background.is_none() {231
let mut children = convert_children(element);219
spans.extend(children);232
if color.is_some() || background.is_some() {220
} else {233
children = vec![Span::Colored {221
spans.push(Span::Colored {222
color,234
color,223
background,235
background,224
children,236
children,225
});237
}];238
}239
match size {240
Some(size) => spans.push(Span::Sized(size, children)),241
None => spans.extend(children),242
}243
}244
245
fn parse_font_size(value: &str) -> Option<FontSize> {246
let value = value.trim().to_ascii_lowercase();247
match value.as_str() {248
"xx-small" | "x-small" | "small" | "smaller" => Some(FontSize::Small),249
"large" | "x-large" | "xx-large" | "larger" => Some(FontSize::Large),250
"0" => Some(FontSize::Hidden),251
_ => {252
let pixels: f32 = value.strip_suffix("px")?.trim().parse().ok()?;253
if pixels <= 0. {254
Some(FontSize::Hidden)255
} else {256
Some(FontSize::Pixels(257
pixels.round().min(f32::from(u16::MAX)) as u16258
))259
}260
}226
}261
}227
}262
}228
263
@@ -371,6 +406,9 @@ fn tidy(spans: &mut Vec<Span>) {371
Span::Bold(children)406
Span::Bold(children)372
| Span::Italic(children)407
| Span::Italic(children)373
| Span::Strike(children)408
| Span::Strike(children)409
| Span::Superscript(children)410
| Span::Subscript(children)411
| Span::Sized(_, children)374
| Span::Underline(children)412
| Span::Underline(children)375
| Span::Colored { children, .. }413
| Span::Colored { children, .. }376
| Span::Heading { children, .. }414
| Span::Heading { children, .. }@@ -339,6 +339,9 @@ pub(crate) fn push_plain(text: &mut String, spans: &[Span]) {
339
339
Span::Bold(children)
340
340
| Span::Italic(children)
341
341
| Span::Strike(children)
342
| Span::Superscript(children)
343
| Span::Subscript(children)
344
| Span::Sized(_, children)
342
345
| Span::Underline(children)
343
346
| Span::Colored { children, .. }
344
347
| Span::Quote(children)
@@ -483,6 +486,9 @@ fn collect_user_mentions(spans: &[Span], infos: &[MentionInfo], inputs: &mut Vec
483
486
Span::Bold(children)
484
487
| Span::Italic(children)
485
488
| Span::Strike(children)
489
| Span::Superscript(children)
490
| Span::Subscript(children)
491
| Span::Sized(_, children)
486
492
| Span::Underline(children)
487
493
| Span::Colored { children, .. }
488
494
| Span::Heading { children, .. }
@@ -526,6 +532,9 @@ fn merge_split_mentions(spans: &mut Vec<Span>, mentions: &[MentionInfo]) {
526
532
Span::Bold(children)
527
533
| Span::Italic(children)
528
534
| Span::Strike(children)
535
| Span::Superscript(children)
536
| Span::Subscript(children)
537
| Span::Sized(_, children)
529
538
| Span::Underline(children)
530
539
| Span::Colored { children, .. }
531
540
| Span::Heading { children, .. }
@@ -339,6 +339,9 @@ pub(crate) fn push_plain(text: &mut String, spans: &[Span]) {339
Span::Bold(children)339
Span::Bold(children)340
| Span::Italic(children)340
| Span::Italic(children)341
| Span::Strike(children)341
| Span::Strike(children)342
| Span::Superscript(children)343
| Span::Subscript(children)344
| Span::Sized(_, children)342
| Span::Underline(children)345
| Span::Underline(children)343
| Span::Colored { children, .. }346
| Span::Colored { children, .. }344
| Span::Quote(children)347
| Span::Quote(children)@@ -483,6 +486,9 @@ fn collect_user_mentions(spans: &[Span], infos: &[MentionInfo], inputs: &mut Vec483
Span::Bold(children)486
Span::Bold(children)484
| Span::Italic(children)487
| Span::Italic(children)485
| Span::Strike(children)488
| Span::Strike(children)489
| Span::Superscript(children)490
| Span::Subscript(children)491
| Span::Sized(_, children)486
| Span::Underline(children)492
| Span::Underline(children)487
| Span::Colored { children, .. }493
| Span::Colored { children, .. }488
| Span::Heading { children, .. }494
| Span::Heading { children, .. }@@ -526,6 +532,9 @@ fn merge_split_mentions(spans: &mut Vec<Span>, mentions: &[MentionInfo]) {526
Span::Bold(children)532
Span::Bold(children)527
| Span::Italic(children)533
| Span::Italic(children)528
| Span::Strike(children)534
| Span::Strike(children)535
| Span::Superscript(children)536
| Span::Subscript(children)537
| Span::Sized(_, children)529
| Span::Underline(children)538
| Span::Underline(children)530
| Span::Colored { children, .. }539
| Span::Colored { children, .. }531
| Span::Heading { children, .. }540
| Span::Heading { children, .. }@@ -1,6 +1,6 @@
1
1
use serde_json::json;
2
2
use store::MessageRecord;
3
use teams_core::{Span, card_content_text, html_to_spans, message_spans};
3
use teams_core::{FontSize, Span, card_content_text, html_to_spans, message_spans};
4
4
5
5
fn text(value: &str) -> Span {
6
6
Span::Text(value.to_owned())
@@ -406,3 +406,65 @@ fn card_text_matches_the_golden_output() {
406
406
);
407
407
}
408
408
}
409
410
#[test]
411
fn superscript_and_subscript() {
412
assert_eq!(
413
html_to_spans("<p>x<sup>2</sup> H<sub>2</sub>O</p>"),
414
vec![
415
text("x"),
416
Span::Superscript(vec![text("2")]),
417
text(" H"),
418
Span::Subscript(vec![text("2")]),
419
text("O"),
420
]
421
);
422
}
423
424
#[test]
425
fn font_sizes_map_to_small_large_and_pixels() {
426
let sized =
427
|value: &str| html_to_spans(&format!("<span style=\"font-size:{value};\">t</span>"));
428
for value in ["xx-small", "x-small", "small"] {
429
assert_eq!(
430
sized(value),
431
vec![Span::Sized(FontSize::Small, vec![text("t")])]
432
);
433
}
434
for value in ["large", "x-large", "xx-large"] {
435
assert_eq!(
436
sized(value),
437
vec![Span::Sized(FontSize::Large, vec![text("t")])]
438
);
439
}
440
assert_eq!(
441
sized("12px"),
442
vec![Span::Sized(FontSize::Pixels(12), vec![text("t")])]
443
);
444
assert_eq!(
445
sized("0"),
446
vec![Span::Sized(FontSize::Hidden, vec![text("t")])]
447
);
448
assert_eq!(
449
sized("0px"),
450
vec![Span::Sized(FontSize::Hidden, vec![text("t")])]
451
);
452
for value in ["inherit", "medium"] {
453
assert_eq!(sized(value), vec![text("t")]);
454
}
455
}
456
457
#[test]
458
fn sized_text_nests_with_bold_and_color() {
459
assert_eq!(
460
html_to_spans("<span style=\"font-size:x-large;color:#ff0000\"><b>big</b></span>"),
461
vec![Span::Sized(
462
FontSize::Large,
463
vec![Span::Colored {
464
color: Some(0xff0000),
465
background: None,
466
children: vec![Span::Bold(vec![text("big")])],
467
}]
468
)]
469
);
470
}
@@ -1,6 +1,6 @@1
use serde_json::json;1
use serde_json::json;2
use store::MessageRecord;2
use store::MessageRecord;3
use teams_core::{Span, card_content_text, html_to_spans, message_spans};3
use teams_core::{FontSize, Span, card_content_text, html_to_spans, message_spans};4
4
5
fn text(value: &str) -> Span {5
fn text(value: &str) -> Span {6
Span::Text(value.to_owned())6
Span::Text(value.to_owned())@@ -406,3 +406,65 @@ fn card_text_matches_the_golden_output() {406
);406
);407
}407
}408
}408
}409
410
#[test]411
fn superscript_and_subscript() {412
assert_eq!(413
html_to_spans("<p>x<sup>2</sup> H<sub>2</sub>O</p>"),414
vec![415
text("x"),416
Span::Superscript(vec![text("2")]),417
text(" H"),418
Span::Subscript(vec![text("2")]),419
text("O"),420
]421
);422
}423
424
#[test]425
fn font_sizes_map_to_small_large_and_pixels() {426
let sized =427
|value: &str| html_to_spans(&format!("<span style=\"font-size:{value};\">t</span>"));428
for value in ["xx-small", "x-small", "small"] {429
assert_eq!(430
sized(value),431
vec![Span::Sized(FontSize::Small, vec![text("t")])]432
);433
}434
for value in ["large", "x-large", "xx-large"] {435
assert_eq!(436
sized(value),437
vec![Span::Sized(FontSize::Large, vec![text("t")])]438
);439
}440
assert_eq!(441
sized("12px"),442
vec![Span::Sized(FontSize::Pixels(12), vec![text("t")])]443
);444
assert_eq!(445
sized("0"),446
vec![Span::Sized(FontSize::Hidden, vec![text("t")])]447
);448
assert_eq!(449
sized("0px"),450
vec![Span::Sized(FontSize::Hidden, vec![text("t")])]451
);452
for value in ["inherit", "medium"] {453
assert_eq!(sized(value), vec![text("t")]);454
}455
}456
457
#[test]458
fn sized_text_nests_with_bold_and_color() {459
assert_eq!(460
html_to_spans("<span style=\"font-size:x-large;color:#ff0000\"><b>big</b></span>"),461
vec![Span::Sized(462
FontSize::Large,463
vec![Span::Colored {464
color: Some(0xff0000),465
background: None,466
children: vec![Span::Bold(vec![text("big")])],467
}]468
)]469
);470
}