Merge remote-tracking branch 'origin/main' into docs/internal-endpoints
@@ -8,9 +8,10 @@ macro_rules! symbols {
8
8
};
9
9
}
10
10
11
const SYMBOLS: [(&str, &[u8]); 54] = symbols![
11
const SYMBOLS: [(&str, &[u8]); 55] = symbols![
12
12
"bot",
13
13
"done",
14
"table",
14
15
"done_all",
15
16
"keyboard_return",
16
17
"schedule",
@@ -8,9 +8,10 @@ macro_rules! symbols {8
};8
};9
}9
}10
10
11
const SYMBOLS: [(&str, &[u8]); 54] = symbols![11
const SYMBOLS: [(&str, &[u8]); 55] = symbols![12
"bot",12
"bot",13
"done",13
"done",14
"table",14
"done_all",15
"done_all",15
"keyboard_return",16
"keyboard_return",16
"schedule",17
"schedule",@@ -13,6 +13,7 @@ const QUOTE_BAR_WIDTH: f32 = 3.;
13
13
const QUOTE_INDENT: f32 = 12.;
14
14
const CODE_INDENT: f32 = 10.;
15
15
const LIST_LEVEL_INDENT: f32 = 18.;
16
const HEADING_SCALES: [f32; 3] = [1.6, 1.35, 1.15];
16
17
17
18
/// How the composer paints a draft: text styles, fills and the list markers to hang under.
18
19
pub struct DraftStyle {
@@ -24,7 +25,7 @@ pub struct DraftStyle {
24
25
25
26
fn line_indent(kind: &LineKind) -> f32 {
26
27
match kind {
27
LineKind::Text => 0.,
28
LineKind::Text | LineKind::Heading(_) | LineKind::Table(_) => 0.,
28
29
LineKind::Quote => QUOTE_INDENT,
29
30
LineKind::Code(_) => CODE_INDENT,
30
31
LineKind::Bullet(depth) | LineKind::Numbered(depth) => {
@@ -83,6 +84,16 @@ fn size_flags(kind: &MarkKind) -> StyleFlags {
83
84
flags
84
85
}
85
86
87
fn heading_decoration(content: Range<usize>, level: u8) -> TextDecoration {
88
let scale = HEADING_SCALES[usize::from(level.clamp(1, 3) - 1)];
89
let style = HighlightStyle {
90
font_weight: Some(FontWeight::BOLD),
91
color: Some(theme::text_strong()),
92
..Default::default()
93
};
94
TextDecoration::new(content, style).with_font_scale(scale)
95
}
96
86
97
/// From the start of the first line of `lines` to the end of the last; Block and Bar cover
87
98
/// every line starting inside it, ends included, so empty lines count too.
88
99
fn block_range(draft: &Draft, lines: Range<usize>) -> Range<usize> {
@@ -152,6 +163,7 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {
152
163
TextDecoration::new(content, color(theme::text_strong()))
153
164
.with_font_family(mono.clone()),
154
165
),
166
LineKind::Heading(level) => text.push(heading_decoration(content, *level)),
155
167
_ => {}
156
168
}
157
169
}
@@ -13,6 +13,7 @@ const QUOTE_BAR_WIDTH: f32 = 3.;13
const QUOTE_INDENT: f32 = 12.;13
const QUOTE_INDENT: f32 = 12.;14
const CODE_INDENT: f32 = 10.;14
const CODE_INDENT: f32 = 10.;15
const LIST_LEVEL_INDENT: f32 = 18.;15
const LIST_LEVEL_INDENT: f32 = 18.;16
const HEADING_SCALES: [f32; 3] = [1.6, 1.35, 1.15];16
17
17
/// How the composer paints a draft: text styles, fills and the list markers to hang under.18
/// How the composer paints a draft: text styles, fills and the list markers to hang under.18
pub struct DraftStyle {19
pub struct DraftStyle {@@ -24,7 +25,7 @@ pub struct DraftStyle {24
25
25
fn line_indent(kind: &LineKind) -> f32 {26
fn line_indent(kind: &LineKind) -> f32 {26
match kind {27
match kind {27
LineKind::Text => 0.,28
LineKind::Text | LineKind::Heading(_) | LineKind::Table(_) => 0.,28
LineKind::Quote => QUOTE_INDENT,29
LineKind::Quote => QUOTE_INDENT,29
LineKind::Code(_) => CODE_INDENT,30
LineKind::Code(_) => CODE_INDENT,30
LineKind::Bullet(depth) | LineKind::Numbered(depth) => {31
LineKind::Bullet(depth) | LineKind::Numbered(depth) => {@@ -83,6 +84,16 @@ fn size_flags(kind: &MarkKind) -> StyleFlags {83
flags84
flags84
}85
}85
86
87
fn heading_decoration(content: Range<usize>, level: u8) -> TextDecoration {88
let scale = HEADING_SCALES[usize::from(level.clamp(1, 3) - 1)];89
let style = HighlightStyle {90
font_weight: Some(FontWeight::BOLD),91
color: Some(theme::text_strong()),92
..Default::default()93
};94
TextDecoration::new(content, style).with_font_scale(scale)95
}96
86
/// From the start of the first line of `lines` to the end of the last; Block and Bar cover97
/// From the start of the first line of `lines` to the end of the last; Block and Bar cover87
/// every line starting inside it, ends included, so empty lines count too.98
/// every line starting inside it, ends included, so empty lines count too.88
fn block_range(draft: &Draft, lines: Range<usize>) -> Range<usize> {99
fn block_range(draft: &Draft, lines: Range<usize>) -> Range<usize> {@@ -152,6 +163,7 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {152
TextDecoration::new(content, color(theme::text_strong()))163
TextDecoration::new(content, color(theme::text_strong()))153
.with_font_family(mono.clone()),164
.with_font_family(mono.clone()),154
),165
),166
LineKind::Heading(level) => text.push(heading_decoration(content, *level)),155
_ => {}167
_ => {}156
}168
}157
}169
}@@ -0,0 +1 @@
1
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M200-120q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h560q33 0 56.5 23.5T840-760v560q0 33-23.5 56.5T760-120H200Zm240-240H200v160h240v-160Zm80 0v160h240v-160H520Zm-80-80v-160H200v160h240Zm80 0h240v-160H520v160ZM200-680h560v-80H200v80Z"/></svg>
@@ -0,0 +1 @@1
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M200-120q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h560q33 0 56.5 23.5T840-760v560q0 33-23.5 56.5T760-120H200Zm240-240H200v160h240v-160Zm80 0v160h240v-160H520Zm-80-80v-160H200v160h240Zm80 0h240v-160H520v160ZM200-680h560v-80H200v80Z"/></svg>@@ -158,8 +158,8 @@ mod frames {
158
158
159
159
use gpui_kit::test::TestWindowExt as _;
160
160
use gpui_kit::{
161
AppContext as _, Bounds, Pixels, TestAppContext, VisualTestContext, WindowOptions, point,
162
px, size,
161
AppContext as _, Bounds, Pixels, ScrollDelta, ScrollWheelEvent, TestAppContext,
162
VisualTestContext, WindowOptions, point, px, size,
163
163
};
164
164
use store::Store;
165
165
@@ -169,19 +169,25 @@ mod frames {
169
169
use gpui_kit::Entity;
170
170
171
171
use crate::app_state::{AppHandle, AppState, Mode, Selection};
172
use crate::settings::metrics;
173
use crate::settings_section::SettingsSection;
174
172
use crate::call::{ActiveCall, CallModel, ConsultCall};
175
173
use crate::demo;
174
use crate::settings::metrics;
175
use crate::settings_section::SettingsSection;
176
176
use crate::user_activity::UserInput;
177
177
use crate::views::call_transcript::TranscriptPanel;
178
178
use crate::views::call_view::CHAT_PANEL_TAG;
179
use crate::views::conversation::MEMBERS_BUTTON;
180
use crate::views::composer::{COMPOSER_BOX_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG};
179
181
use crate::views::message_row::BUBBLE_TAGS;
180
182
use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
181
183
use crate::views::reaction_proposal_pill::REACTION_PILL;
182
184
use crate::views::recap_tab::RECAP_REGION;
183
use crate::views::shell::{AppShell, Startup, bind_keys, install_globals, sidebar_hidden_in_call};
184
use crate::views::shortcuts::{OpenActivity, OpenAgents, OpenCallsTab, OpenChannelsTab, OpenSaved};
185
use crate::views::shell::{
186
AppShell, Startup, bind_keys, install_globals, sidebar_hidden_in_call,
187
};
188
use crate::views::shortcuts::{
189
OpenActivity, OpenAgents, OpenCallsTab, OpenChannelsTab, OpenSaved,
190
};
185
191
186
192
const GUARDED: &[&str] = &[
187
193
"shell",
@@ -249,10 +255,41 @@ mod frames {
249
255
const SETTINGS_TAGS: &[&str] = &[
250
256
"settings",
251
257
"settings/nav",
258
"settings/nav/divider",
259
"settings/nav/about",
252
260
"settings/main",
253
261
"settings/main/header",
262
"settings/main/header/close",
254
263
"settings/main/body",
255
264
];
265
const SETTINGS_BODY: &str = "settings/main/body";
266
const SETTINGS_CONTENT: &str = "settings/main/body/content";
267
const MEMBERS_TAGS: &[&str] = &["chat-members-popup", "chat-members-popup/divider"];
268
const MEMBERS_CHAT: &str = "demo-chat-release";
269
const DIVIDER_SEGMENT: &str = "divider";
270
const DIVIDER_THICKNESS: f32 = 1.;
271
const INSET_TOLERANCE: f32 = 1.;
272
const INSET_RULES: &[InsetRule] = &[
273
InsetRule {
274
panel: "settings/nav",
275
content: "settings/nav/about",
276
edges: &[Edge::Left, Edge::Right, Edge::Bottom],
277
},
278
InsetRule {
279
panel: "settings/main",
280
content: "settings/main/header/close",
281
edges: &[Edge::Top, Edge::Right],
282
},
283
];
284
const SCROLLED_INSET_RULE: InsetRule = InsetRule {
285
panel: SETTINGS_BODY,
286
content: SETTINGS_CONTENT,
287
edges: &[Edge::Left, Edge::Bottom],
288
};
289
const SCROLLED_INSET_ALLOWLIST: &[(SettingsSection, &str)] = &[(
290
SettingsSection::Agents,
291
"Agents pages carry their own PAGE_PADDING side inset, the body narrows its side padding to keep the text edge",
292
)];
256
293
const SETTINGS_SECTIONS: [SettingsSection; 8] = [
257
294
SettingsSection::General,
258
295
SettingsSection::Notifications,
@@ -269,6 +306,108 @@ mod frames {
269
306
270
307
type Tag = (&'static str, Bounds<Pixels>);
271
308
309
#[derive(Clone, Copy, Debug)]
310
enum Edge {
311
Top,
312
Right,
313
Bottom,
314
Left,
315
}
316
317
struct InsetRule {
318
panel: &'static str,
319
content: &'static str,
320
edges: &'static [Edge],
321
}
322
323
fn inset(panel: Bounds<Pixels>, content: Bounds<Pixels>, edge: Edge) -> f32 {
324
f32::from(match edge {
325
Edge::Top => content.top() - panel.top(),
326
Edge::Right => panel.right() - content.right(),
327
Edge::Bottom => panel.bottom() - content.bottom(),
328
Edge::Left => content.left() - panel.left(),
329
})
330
}
331
332
fn inset_violation(
333
rule: &InsetRule,
334
panel: Bounds<Pixels>,
335
content: Bounds<Pixels>,
336
) -> Option<(String, String)> {
337
let insets: Vec<(Edge, f32)> = rule
338
.edges
339
.iter()
340
.map(|edge| (*edge, inset(panel, content, *edge)))
341
.collect();
342
let values = insets.iter().map(|(_, value)| *value);
343
let spread = values.clone().fold(f32::MIN, f32::max) - values.fold(f32::MAX, f32::min);
344
(spread > INSET_TOLERANCE).then(|| {
345
(
346
format!("{}:uneven-inset", rule.panel),
347
format!(
348
"{} insets {} by {insets:?}, they must match",
349
rule.panel, rule.content
350
),
351
)
352
})
353
}
354
355
fn inset_violations(tags: &[Tag], rules: &[InsetRule]) -> Vec<(String, String)> {
356
let bounds_of = |path: &str| {
357
tags.iter()
358
.find(|(tag, _)| *tag == path)
359
.map(|(_, bounds)| *bounds)
360
};
361
rules
362
.iter()
363
.filter_map(
364
|rule| match (bounds_of(rule.panel), bounds_of(rule.content)) {
365
(Some(panel), Some(content)) => inset_violation(rule, panel, content),
366
_ => None,
367
},
368
)
369
.collect()
370
}
371
372
fn divider_violations(tags: &[Tag]) -> Vec<(String, String)> {
373
let mut found = Vec::new();
374
for (path, bounds) in tags {
375
let Some((parent, segment)) = path.rsplit_once('/') else {
376
continue;
377
};
378
if !segment.starts_with(DIVIDER_SEGMENT) {
379
continue;
380
}
381
let Some((_, panel)) = tags.iter().find(|(tag, _)| *tag == parent) else {
382
found.push((
383
format!("{path}:no-panel"),
384
format!("{path} needs its panel {parent} tagged"),
385
));
386
continue;
387
};
388
let thin = |length: Pixels| f32::from(length) <= DIVIDER_THICKNESS + TOLERANCE;
389
let near = |first: Pixels, second: Pixels| f32::from(first - second).abs() <= TOLERANCE;
390
let spans = if thin(bounds.size.height) {
391
near(bounds.left(), panel.left()) && near(bounds.right(), panel.right())
392
} else if thin(bounds.size.width) {
393
near(bounds.top(), panel.top()) && near(bounds.bottom(), panel.bottom())
394
} else {
395
false
396
};
397
if !spans {
398
found.push((
399
format!("{path}:short-divider"),
400
format!(
401
"{path} {} must be a {DIVIDER_THICKNESS} px line from edge to edge of {parent} {}",
402
describe(*bounds),
403
describe(*panel)
404
),
405
));
406
}
407
}
408
found
409
}
410
272
411
enum Screen {
273
412
Tab(&'static str, Option<fn(&mut VisualTestContext)>),
274
413
StatusMenu,
@@ -376,6 +515,7 @@ mod frames {
376
515
}
377
516
}
378
517
}
518
found.extend(divider_violations(tags));
379
519
found
380
520
}
381
521
@@ -412,13 +552,15 @@ mod frames {
412
552
])
413
553
.chain(&AGENT_TAGS)
414
554
.chain(SETTINGS_TAGS)
555
.chain(MEMBERS_TAGS)
415
556
.filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
416
557
.collect()
417
558
}
418
559
419
560
fn sharing_call() -> ActiveCall {
420
561
let mut call = gallery_call();
421
call.model.apply(CallUpdate::ScreenShare(Some("8:orgid:guard-1".to_owned())));
562
call.model
563
.apply(CallUpdate::ScreenShare(Some("8:orgid:guard-1".to_owned())));
422
564
call.share_stage.view.step_in((800., 450.));
423
565
call
424
566
}
@@ -460,7 +602,10 @@ mod frames {
460
602
let held = connected(1, "Christopher Montgomery-Lindqvist", "8:orgid:guard-held");
461
603
let mut consult = connected(2, "Jonas Ortega", "8:orgid:guard-consult");
462
604
consult.consult = Some(ConsultCall::new(
463
("8:orgid:guard-consult".to_owned(), "Jonas Ortega".to_owned()),
605
(
606
"8:orgid:guard-consult".to_owned(),
607
"Jonas Ortega".to_owned(),
608
),
464
609
held.model.peer_name.clone(),
465
610
));
466
611
(consult, held)
@@ -528,6 +673,37 @@ mod frames {
528
673
.into_iter()
529
674
.map(|(key, _)| key)
530
675
.collect();
676
let line_tags: Vec<Tag> = vec![
677
("panel", rectangle(0., 0., 100., 100.)),
678
("panel/divider", rectangle(0., 50., 100., 1.)),
679
("panel/divider-inset", rectangle(12., 60., 76., 1.)),
680
("panel/divider-side", rectangle(40., 0., 1., 100.)),
681
("panel/about", rectangle(12., 76., 76., 12.)),
682
("panel/footer", rectangle(12., 64., 76., 12.)),
683
];
684
let line_keys: Vec<String> = divider_violations(&line_tags)
685
.into_iter()
686
.chain(inset_violations(
687
&line_tags,
688
&[
689
InsetRule {
690
panel: "panel",
691
content: "panel/about",
692
edges: &[Edge::Left, Edge::Right, Edge::Bottom],
693
},
694
InsetRule {
695
panel: "panel",
696
content: "panel/footer",
697
edges: &[Edge::Left, Edge::Bottom],
698
},
699
],
700
))
701
.map(|(key, _)| key)
702
.collect();
703
assert_eq!(
704
line_keys,
705
["panel/divider-inset:short-divider", "panel:uneven-inset"]
706
);
531
707
assert_eq!(
532
708
keys,
533
709
[
@@ -753,6 +929,76 @@ mod frames {
753
929
.join("\n")
754
930
);
755
931
}
932
const TITLE_SEARCH: &str = "shell/title-bar/search";
933
const TITLE_NEIGHBOURS: &[&str] = &[
934
"shell/title-bar/leading",
935
"shell/title-bar/mode-pill",
936
"shell/title-bar/trailing",
937
"shell/title-bar/update",
938
OWN_STATUS,
939
];
940
const TITLE_SEARCH_SIZES: [(f32, f32, bool); 3] = [
941
(1920., 1080., true),
942
(1280., 800., true),
943
(640., 480., false),
944
];
945
946
#[gpui_kit::test]
947
fn title_search_is_centered_on_the_window(cx: &mut TestAppContext) {
948
let (handle, _) = mount(cx);
949
let mut visual = VisualTestContext::from_window(handle, cx);
950
let shell = visual.update(|window, cx| {
951
window
952
.root::<gpui_kit::base::Root>()
953
.flatten()
954
.and_then(|root| root.read(cx).view().clone().downcast::<AppShell>().ok())
955
.expect("app shell is the root view")
956
});
957
visual.update(|_, cx| {
958
shell.update(cx, |shell, cx| {
959
shell.set_update_status(crate::updater::UpdateStatus::Ready, cx)
960
})
961
});
962
let mut found = Vec::new();
963
for (width, height, centered) in TITLE_SEARCH_SIZES {
964
visual.simulate_resize(size(px(width), px(height)));
965
collect(&mut visual, Some(TITLE_SEARCH));
966
let search = visual
967
.debug_bounds(TITLE_SEARCH)
968
.expect("title search rendered");
969
let search_center = f32::from(search.center().x);
970
eprintln!(
971
"title search @{width}x{height}: {} center {search_center:.1}, window center {:.1}",
972
describe(search),
973
width / 2.
974
);
975
if centered && (search_center - width / 2.).abs() > 1. {
976
found.push(format!(
977
"@{width}x{height}: search center {search_center:.1} is not the window center {:.1}",
978
width / 2.
979
));
980
}
981
if !contains(rectangle(0., 0., width, height), search) {
982
found.push(format!(
983
"@{width}x{height}: search {} leaves the window",
984
describe(search)
985
));
986
}
987
for neighbour in TITLE_NEIGHBOURS {
988
match visual.debug_bounds(neighbour) {
989
None => found.push(format!("@{width}x{height}: {neighbour} was not rendered")),
990
Some(bounds) if overlaps(search, bounds) => found.push(format!(
991
"@{width}x{height}: search {} overlaps {neighbour} {}",
992
describe(search),
993
describe(bounds)
994
)),
995
Some(_) => {}
996
}
997
}
998
}
999
assert!(found.is_empty(), "{}", found.join("\n"));
1000
}
1001
756
1002
#[gpui_kit::test]
757
1003
fn call_chat_bubbles_stay_inside_the_panel(cx: &mut TestAppContext) {
758
1004
let (handle, app) = mount(cx);
@@ -840,17 +1086,28 @@ mod frames {
840
1086
};
841
1087
let inset = metrics(width, height).inset;
842
1088
for section in SETTINGS_SECTIONS {
843
visual.update(|_, cx| {
844
state.update(cx, |state, cx| state.open_settings(section, cx))
845
});
1089
visual
1090
.update(|_, cx| state.update(cx, |state, cx| state.open_settings(section, cx)));
846
1091
let tags = collect(&mut visual, Some(SETTINGS_TAGS[0]));
847
let found: Vec<String> = violations(&tags, window, SETTINGS_TAGS)
1092
let mut found: Vec<(String, String)> = violations(&tags, window, SETTINGS_TAGS)
848
1093
.into_iter()
849
1094
.filter(|(key, _)| key.starts_with("settings"))
1095
.chain(inset_violations(&tags, INSET_RULES))
1096
.collect();
1097
let scrolled_exempt = SCROLLED_INSET_ALLOWLIST
1098
.iter()
1099
.any(|(exempt, _)| *exempt == section);
1100
if !scrolled_exempt {
1101
found.extend(scrolled_inset_violation(&mut visual));
1102
}
1103
let found: Vec<String> = found
1104
.into_iter()
850
1105
.map(|(key, message)| format!("{section:?}@{width}x{height}:{key}: {message}"))
851
1106
.collect();
852
1107
assert!(found.is_empty(), "{}", found.join("\n"));
853
let dialog = visual.debug_bounds(SETTINGS_TAGS[0]).expect("settings dialog");
1108
let dialog = visual
1109
.debug_bounds(SETTINGS_TAGS[0])
1110
.expect("settings dialog");
854
1111
let edges = [
855
1112
f32::from(dialog.left()),
856
1113
f32::from(dialog.top()),
@@ -865,6 +1122,115 @@ mod frames {
865
1122
}
866
1123
}
867
1124
1125
fn scrolled_inset_violation(visual: &mut VisualTestContext) -> Option<(String, String)> {
1126
let body = visual.debug_bounds(SETTINGS_BODY)?;
1127
let content = visual.debug_bounds(SETTINGS_CONTENT)?;
1128
if content.bottom() <= body.bottom() {
1129
return None;
1130
}
1131
visual.simulate_event(ScrollWheelEvent {
1132
position: body.center(),
1133
delta: ScrollDelta::Pixels(point(px(0.), px(-100_000.))),
1134
..Default::default()
1135
});
1136
collect(visual, None);
1137
let body = visual.debug_bounds(SETTINGS_BODY)?;
1138
let content = visual.debug_bounds(SETTINGS_CONTENT)?;
1139
inset_violation(&SCROLLED_INSET_RULE, body, content)
1140
}
1141
1142
#[gpui_kit::test]
1143
fn members_popup_lines_reach_the_edges(cx: &mut TestAppContext) {
1144
let (handle, state) = mount(cx);
1145
let mut visual = VisualTestContext::from_window(handle, cx);
1146
for (width, height) in SIZES {
1147
visual.simulate_resize(size(px(width), px(height)));
1148
let window = Bounds {
1149
origin: point(px(0.), px(0.)),
1150
size: size(px(width), px(height)),
1151
};
1152
visual.update(|_, cx| {
1153
state.update(cx, |state, cx| {
1154
state.select(Selection::Chat(MEMBERS_CHAT.to_owned()), cx)
1155
})
1156
});
1157
collect(&mut visual, Some(MEMBERS_BUTTON));
1158
let button = visual
1159
.debug_bounds(MEMBERS_BUTTON)
1160
.expect("members button rendered");
1161
visual.simulate_click(button.center(), Default::default());
1162
let tags = collect(&mut visual, Some(MEMBERS_TAGS[0]));
1163
let found: Vec<String> = violations(&tags, window, MEMBERS_TAGS)
1164
.into_iter()
1165
.filter(|(key, _)| key.starts_with("chat-members"))
1166
.map(|(key, message)| format!("members@{width}x{height}:{key}: {message}"))
1167
.collect();
1168
visual.simulate_keystrokes("escape");
1169
visual.run_until_parked();
1170
assert!(found.is_empty(), "{}", found.join("\n"));
1171
}
1172
}
1173
1174
fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {
1175
collect(visual, Some(COMPOSER_SEND_TAG));
1176
let mut bounds_of = |path: &'static str| {
1177
visual
1178
.debug_bounds(path)
1179
.unwrap_or_else(|| panic!("{path} rendered"))
1180
};
1181
let composer = bounds_of(COMPOSER_BOX_TAG);
1182
let leading = bounds_of(COMPOSER_LEADING_TAG);
1183
let send = bounds_of(COMPOSER_SEND_TAG);
1184
[
1185
f32::from(leading.left() - composer.left()),
1186
f32::from(leading.top() - composer.top()),
1187
f32::from(composer.bottom() - leading.bottom()),
1188
f32::from(composer.right() - send.right()),
1189
f32::from(send.top() - composer.top()),
1190
f32::from(composer.bottom() - send.bottom()),
1191
]
1192
}
1193
1194
#[gpui_kit::test]
1195
fn composer_buttons_keep_equal_insets(cx: &mut TestAppContext) {
1196
let (handle, _) = mount(cx);
1197
let mut visual = VisualTestContext::from_window(handle, cx);
1198
visual.simulate_resize(size(px(1280.), px(800.)));
1199
let single_line = composer_button_insets(&mut visual);
1200
let left = single_line[0];
1201
assert!(
1202
single_line
1203
.iter()
1204
.all(|inset| (inset - left).abs() < TOLERANCE),
1205
"single line: insets left, top, bottom of the first button and right, top, bottom of send {single_line:?}"
1206
);
1207
let leading = visual
1208
.debug_bounds(COMPOSER_LEADING_TAG)
1209
.expect("leading buttons");
1210
let send = visual.debug_bounds(COMPOSER_SEND_TAG).expect("send button");
1211
visual.simulate_click(
1212
point((leading.right() + send.left()) / 2., send.center().y),
1213
Default::default(),
1214
);
1215
visual.simulate_keystrokes("o n e shift-enter t w o shift-enter t h r e e");
1216
let three_lines = composer_button_insets(&mut visual);
1217
assert!(
1218
three_lines[1] > single_line[1] + 30.,
1219
"three lines did not grow the composer: {three_lines:?}"
1220
);
1221
for inset in [
1222
three_lines[0],
1223
three_lines[2],
1224
three_lines[3],
1225
three_lines[5],
1226
] {
1227
assert!(
1228
(inset - left).abs() < TOLERANCE,
1229
"three lines: insets left, top, bottom of the first button and right, top, bottom of send {three_lines:?}, expected {left}"
1230
);
1231
}
1232
}
1233
868
1234
#[gpui_kit::test]
869
1235
fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {
870
1236
let (handle, state) = mount_with(cx, true);
@@ -928,6 +1294,247 @@ fn lines_are_solid() {
928
1294
assert!(violations.is_empty(), "{}", violations.join("\n"));
929
1295
}
930
1296
1297
const STATE_RING_COLORS: &[&str] = &[
1298
"if focused",
1299
"if selected",
1300
"if speaking",
1301
"if current",
1302
"if open",
1303
"if state.failed",
1304
];
1305
const OUTLINE_ALLOWLIST: &[(&str, &str, &str)] = &[
1306
(
1307
"notify/ring_view.rs",
1308
"theme::green()",
1309
"OS toast window: no compositor shadow, the edge separates it from the desktop; accent = Teams state",
1310
),
1311
(
1312
"notify/meeting_view.rs",
1313
"theme::accent()",
1314
"OS toast window: no compositor shadow, the edge separates it from the desktop; accent = Teams state",
1315
),
1316
(
1317
"notify/meeting_view.rs",
1318
"theme::border_strong()",
1319
"outlined button, not a surface",
1320
),
1321
(
1322
"notify/toast.rs",
1323
"border)",
1324
"OS toast window: no compositor shadow, the edge separates it from the desktop; accent = Teams state",
1325
),
1326
(
1327
"notify/toast.rs",
1328
"theme::border_strong()",
1329
"OS toast window: no compositor shadow, the edge separates it from the desktop; accent = Teams state",
1330
),
1331
(
1332
"settings/mcp.rs",
1333
"theme::border_strong()",
1334
"outlined button, not a surface",
1335
),
1336
(
1337
"settings/rows.rs",
1338
"theme::border_strong()",
1339
"outlined button, not a surface",
1340
),
1341
(
1342
"views/card_widgets.rs",
1343
"border)",
1344
"message content drawn as Teams renders it",
1345
),
1346
(
1347
"views/card_widgets.rs",
1348
"theme::border_strong()",
1349
"message content drawn as Teams renders it",
1350
),
1351
("views/shared_tab.rs", "theme::accent()", "input field"),
1352
("views/card_input.rs", "if error.is_some()", "input field"),
1353
("views/format_toolbar.rs", "if refused", "input field"),
1354
(
1355
"views/card_code_block.rs",
1356
"theme::code_header_border()",
1357
"message content drawn as Teams renders it",
1358
),
1359
("views/call_transcript.rs", "theme::border()", "input field"),
1360
(
1361
"views/conversation.rs",
1362
"theme::accent()",
1363
"state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1364
),
1365
(
1366
"views/attachment_tray.rs",
1367
"theme::accent()",
1368
"state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1369
),
1370
(
1371
"views/card_carousel.rs",
1372
"theme::border_strong()",
1373
"message content drawn as Teams renders it",
1374
),
1375
(
1376
"views/card_table.rs",
1377
"grid_color",
1378
"message content drawn as Teams renders it",
1379
),
1380
(
1381
"views/activity_panel.rs",
1382
"theme::surface()",
1383
"cutout ring in the background color, invisible against its surface",
1384
),
1385
(
1386
"views/avatar.rs",
1387
"theme::surface()",
1388
"cutout ring in the background color, invisible against its surface",
1389
),
1390
(
1391
"views/avatar.rs",
1392
"theme::text_muted()",
1393
"offline presence glyph, Teams icon",
1394
),
1395
(
1396
"views/message_row.rs",
1397
"theme::border_strong()",
1398
"deleted message placeholder, Teams look",
1399
),
1400
(
1401
"views/message_row.rs",
1402
"theme::red()",
1403
"state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1404
),
1405
(
1406
"views/message_row.rs",
1407
"if row.delivery",
1408
"state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1409
),
1410
(
1411
"views/new_meeting_dialog.rs",
1412
"theme::border()",
1413
"input field",
1414
),
1415
(
1416
"views/call_mini_window.rs",
1417
"theme::border_strong()",
1418
"self view over live video, needs an edge on any picture",
1419
),
1420
("views/transfer_picker.rs", "theme::border()", "input field"),
1421
(
1422
"views/call_notice.rs",
1423
"theme::border_strong()",
1424
"outlined button, not a surface",
1425
),
1426
(
1427
"views/composer/schedule.rs",
1428
"theme::accent()",
1429
"input field",
1430
),
1431
(
1432
"views/call_mini.rs",
1433
"border)",
1434
"state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1435
),
1436
(
1437
"views/sidebar.rs",
1438
"theme::accent()",
1439
"state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1440
),
1441
(
1442
"views/adaptive_card.rs",
1443
"theme::border()",
1444
"message content drawn as Teams renders it",
1445
),
1446
(
1447
"views/adaptive_card.rs",
1448
"border)",
1449
"message content drawn as Teams renders it",
1450
),
1451
(
1452
"views/share_bar.rs",
1453
"theme::red()",
1454
"state signal (speaking, sharing, drag, drop, failed), not a resting outline",
1455
),
1456
("settings_controls.rs", "if invalid", "input field"),
1457
];
1458
1459
fn outlines(source: &str) -> Vec<(usize, String)> {
1460
let pattern = Regex::new(r"\.border(_1\(\)|_2\(\)|\(px)").expect("pattern");
1461
pattern
1462
.find_iter(source)
1463
.map(|found| {
1464
let line_number = source[..found.start()].matches('\n').count() + 1;
1465
let after = &source[found.end()..];
1466
let color = after
1467
.find(".border_color(")
1468
.filter(|position| *position < 120)
1469
.map(|position| {
1470
let start = &after[position + ".border_color(".len()..];
1471
start
1472
.lines()
1473
.map(str::trim)
1474
.find(|line| !line.is_empty())
1475
.unwrap_or_default()
1476
.to_owned()
1477
})
1478
.unwrap_or_default();
1479
(line_number, color)
1480
})
1481
.collect()
1482
}
1483
1484
#[test]
1485
fn outline_matcher_reads_the_border_color() {
1486
let source = "div()\n .border_1()\n .border_color(theme::amber())\n .border_t_1()\n";
1487
assert_eq!(outlines(source), [(2, "theme::amber())".to_owned())]);
1488
}
1489
1490
#[test]
1491
fn surfaces_are_soft() {
1492
let mut matched_allowlist = HashSet::new();
1493
let mut violations = Vec::new();
1494
for root in source_roots() {
1495
let mut files = Vec::new();
1496
source_files(&root, &mut files);
1497
for file in files {
1498
let relative = file
1499
.strip_prefix(&root)
1500
.expect("inside src")
1501
.to_string_lossy()
1502
.replace('\\', "/");
1503
if relative == "layout_guard.rs" {
1504
continue;
1505
}
1506
let source = fs::read_to_string(&file).expect("read source file");
1507
for (line_number, color) in outlines(&source) {
1508
if STATE_RING_COLORS
1509
.iter()
1510
.any(|prefix| color.starts_with(prefix))
1511
{
1512
continue;
1513
}
1514
match OUTLINE_ALLOWLIST.iter().position(|(allowed_file, prefix, _)| {
1515
*allowed_file == relative && color.starts_with(prefix)
1516
}) {
1517
Some(position) => {
1518
matched_allowlist.insert(position);
1519
}
1520
None => violations.push(format!(
1521
"{relative}:{line_number}: hard outline on a surface, use a soft fill or shadow (border_color {color})"
1522
)),
1523
}
1524
}
1525
}
1526
}
1527
let stale = OUTLINE_ALLOWLIST
1528
.iter()
1529
.enumerate()
1530
.filter(|(position, _)| !matched_allowlist.contains(position))
1531
.map(|(_, (file, prefix, _))| {
1532
format!("stale outline allowlist entry, remove it: {file} {prefix}")
1533
});
1534
let report: Vec<String> = violations.into_iter().chain(stale).collect();
1535
assert!(report.is_empty(), "{}", report.join("\n"));
1536
}
1537
931
1538
fn indentation(line: &str) -> usize {
932
1539
line.len() - line.trim_start().len()
933
1540
}
@@ -158,8 +158,8 @@ mod frames {158
158
159
use gpui_kit::test::TestWindowExt as _;159
use gpui_kit::test::TestWindowExt as _;160
use gpui_kit::{160
use gpui_kit::{161
AppContext as _, Bounds, Pixels, TestAppContext, VisualTestContext, WindowOptions, point,161
AppContext as _, Bounds, Pixels, ScrollDelta, ScrollWheelEvent, TestAppContext,162
px, size,162
VisualTestContext, WindowOptions, point, px, size,163
};163
};164
use store::Store;164
use store::Store;165
165
@@ -169,19 +169,25 @@ mod frames {169
use gpui_kit::Entity;169
use gpui_kit::Entity;170
170
171
use crate::app_state::{AppHandle, AppState, Mode, Selection};171
use crate::app_state::{AppHandle, AppState, Mode, Selection};172
use crate::settings::metrics;173
use crate::settings_section::SettingsSection;174
use crate::call::{ActiveCall, CallModel, ConsultCall};172
use crate::call::{ActiveCall, CallModel, ConsultCall};175
use crate::demo;173
use crate::demo;174
use crate::settings::metrics;175
use crate::settings_section::SettingsSection;176
use crate::user_activity::UserInput;176
use crate::user_activity::UserInput;177
use crate::views::call_transcript::TranscriptPanel;177
use crate::views::call_transcript::TranscriptPanel;178
use crate::views::call_view::CHAT_PANEL_TAG;178
use crate::views::call_view::CHAT_PANEL_TAG;179
use crate::views::conversation::MEMBERS_BUTTON;180
use crate::views::composer::{COMPOSER_BOX_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG};179
use crate::views::message_row::BUBBLE_TAGS;181
use crate::views::message_row::BUBBLE_TAGS;180
use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};182
use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};181
use crate::views::reaction_proposal_pill::REACTION_PILL;183
use crate::views::reaction_proposal_pill::REACTION_PILL;182
use crate::views::recap_tab::RECAP_REGION;184
use crate::views::recap_tab::RECAP_REGION;183
use crate::views::shell::{AppShell, Startup, bind_keys, install_globals, sidebar_hidden_in_call};185
use crate::views::shell::{184
use crate::views::shortcuts::{OpenActivity, OpenAgents, OpenCallsTab, OpenChannelsTab, OpenSaved};186
AppShell, Startup, bind_keys, install_globals, sidebar_hidden_in_call,187
};188
use crate::views::shortcuts::{189
OpenActivity, OpenAgents, OpenCallsTab, OpenChannelsTab, OpenSaved,190
};185
191
186
const GUARDED: &[&str] = &[192
const GUARDED: &[&str] = &[187
"shell",193
"shell",@@ -249,10 +255,41 @@ mod frames {249
const SETTINGS_TAGS: &[&str] = &[255
const SETTINGS_TAGS: &[&str] = &[250
"settings",256
"settings",251
"settings/nav",257
"settings/nav",258
"settings/nav/divider",259
"settings/nav/about",252
"settings/main",260
"settings/main",253
"settings/main/header",261
"settings/main/header",262
"settings/main/header/close",254
"settings/main/body",263
"settings/main/body",255
];264
];265
const SETTINGS_BODY: &str = "settings/main/body";266
const SETTINGS_CONTENT: &str = "settings/main/body/content";267
const MEMBERS_TAGS: &[&str] = &["chat-members-popup", "chat-members-popup/divider"];268
const MEMBERS_CHAT: &str = "demo-chat-release";269
const DIVIDER_SEGMENT: &str = "divider";270
const DIVIDER_THICKNESS: f32 = 1.;271
const INSET_TOLERANCE: f32 = 1.;272
const INSET_RULES: &[InsetRule] = &[273
InsetRule {274
panel: "settings/nav",275
content: "settings/nav/about",276
edges: &[Edge::Left, Edge::Right, Edge::Bottom],277
},278
InsetRule {279
panel: "settings/main",280
content: "settings/main/header/close",281
edges: &[Edge::Top, Edge::Right],282
},283
];284
const SCROLLED_INSET_RULE: InsetRule = InsetRule {285
panel: SETTINGS_BODY,286
content: SETTINGS_CONTENT,287
edges: &[Edge::Left, Edge::Bottom],288
};289
const SCROLLED_INSET_ALLOWLIST: &[(SettingsSection, &str)] = &[(290
SettingsSection::Agents,291
"Agents pages carry their own PAGE_PADDING side inset, the body narrows its side padding to keep the text edge",292
)];256
const SETTINGS_SECTIONS: [SettingsSection; 8] = [293
const SETTINGS_SECTIONS: [SettingsSection; 8] = [257
SettingsSection::General,294
SettingsSection::General,258
SettingsSection::Notifications,295
SettingsSection::Notifications,@@ -269,6 +306,108 @@ mod frames {269
306
270
type Tag = (&'static str, Bounds<Pixels>);307
type Tag = (&'static str, Bounds<Pixels>);271
308
309
#[derive(Clone, Copy, Debug)]310
enum Edge {311
Top,312
Right,313
Bottom,314
Left,315
}316
317
struct InsetRule {318
panel: &'static str,319
content: &'static str,320
edges: &'static [Edge],321
}322
323
fn inset(panel: Bounds<Pixels>, content: Bounds<Pixels>, edge: Edge) -> f32 {324
f32::from(match edge {325
Edge::Top => content.top() - panel.top(),326
Edge::Right => panel.right() - content.right(),327
Edge::Bottom => panel.bottom() - content.bottom(),328
Edge::Left => content.left() - panel.left(),329
})330
}331
332
fn inset_violation(333
rule: &InsetRule,334
panel: Bounds<Pixels>,335
content: Bounds<Pixels>,336
) -> Option<(String, String)> {337
let insets: Vec<(Edge, f32)> = rule338
.edges339
.iter()340
.map(|edge| (*edge, inset(panel, content, *edge)))341
.collect();342
let values = insets.iter().map(|(_, value)| *value);343
let spread = values.clone().fold(f32::MIN, f32::max) - values.fold(f32::MAX, f32::min);344
(spread > INSET_TOLERANCE).then(|| {345
(346
format!("{}:uneven-inset", rule.panel),347
format!(348
"{} insets {} by {insets:?}, they must match",349
rule.panel, rule.content350
),351
)352
})353
}354
355
fn inset_violations(tags: &[Tag], rules: &[InsetRule]) -> Vec<(String, String)> {356
let bounds_of = |path: &str| {357
tags.iter()358
.find(|(tag, _)| *tag == path)359
.map(|(_, bounds)| *bounds)360
};361
rules362
.iter()363
.filter_map(364
|rule| match (bounds_of(rule.panel), bounds_of(rule.content)) {365
(Some(panel), Some(content)) => inset_violation(rule, panel, content),366
_ => None,367
},368
)369
.collect()370
}371
372
fn divider_violations(tags: &[Tag]) -> Vec<(String, String)> {373
let mut found = Vec::new();374
for (path, bounds) in tags {375
let Some((parent, segment)) = path.rsplit_once('/') else {376
continue;377
};378
if !segment.starts_with(DIVIDER_SEGMENT) {379
continue;380
}381
let Some((_, panel)) = tags.iter().find(|(tag, _)| *tag == parent) else {382
found.push((383
format!("{path}:no-panel"),384
format!("{path} needs its panel {parent} tagged"),385
));386
continue;387
};388
let thin = |length: Pixels| f32::from(length) <= DIVIDER_THICKNESS + TOLERANCE;389
let near = |first: Pixels, second: Pixels| f32::from(first - second).abs() <= TOLERANCE;390
let spans = if thin(bounds.size.height) {391
near(bounds.left(), panel.left()) && near(bounds.right(), panel.right())392
} else if thin(bounds.size.width) {393
near(bounds.top(), panel.top()) && near(bounds.bottom(), panel.bottom())394
} else {395
false396
};397
if !spans {398
found.push((399
format!("{path}:short-divider"),400
format!(401
"{path} {} must be a {DIVIDER_THICKNESS} px line from edge to edge of {parent} {}",402
describe(*bounds),403
describe(*panel)404
),405
));406
}407
}408
found409
}410
272
enum Screen {411
enum Screen {273
Tab(&'static str, Option<fn(&mut VisualTestContext)>),412
Tab(&'static str, Option<fn(&mut VisualTestContext)>),274
StatusMenu,413
StatusMenu,@@ -376,6 +515,7 @@ mod frames {376
}515
}377
}516
}378
}517
}518
found.extend(divider_violations(tags));379
found519
found380
}520
}381
521
@@ -412,13 +552,15 @@ mod frames {412
])552
])413
.chain(&AGENT_TAGS)553
.chain(&AGENT_TAGS)414
.chain(SETTINGS_TAGS)554
.chain(SETTINGS_TAGS)555
.chain(MEMBERS_TAGS)415
.filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))556
.filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))416
.collect()557
.collect()417
}558
}418
559
419
fn sharing_call() -> ActiveCall {560
fn sharing_call() -> ActiveCall {420
let mut call = gallery_call();561
let mut call = gallery_call();421
call.model.apply(CallUpdate::ScreenShare(Some("8:orgid:guard-1".to_owned())));562
call.model563
.apply(CallUpdate::ScreenShare(Some("8:orgid:guard-1".to_owned())));422
call.share_stage.view.step_in((800., 450.));564
call.share_stage.view.step_in((800., 450.));423
call565
call424
}566
}@@ -460,7 +602,10 @@ mod frames {460
let held = connected(1, "Christopher Montgomery-Lindqvist", "8:orgid:guard-held");602
let held = connected(1, "Christopher Montgomery-Lindqvist", "8:orgid:guard-held");461
let mut consult = connected(2, "Jonas Ortega", "8:orgid:guard-consult");603
let mut consult = connected(2, "Jonas Ortega", "8:orgid:guard-consult");462
consult.consult = Some(ConsultCall::new(604
consult.consult = Some(ConsultCall::new(463
("8:orgid:guard-consult".to_owned(), "Jonas Ortega".to_owned()),605
(606
"8:orgid:guard-consult".to_owned(),607
"Jonas Ortega".to_owned(),608
),464
held.model.peer_name.clone(),609
held.model.peer_name.clone(),465
));610
));466
(consult, held)611
(consult, held)@@ -528,6 +673,37 @@ mod frames {528
.into_iter()673
.into_iter()529
.map(|(key, _)| key)674
.map(|(key, _)| key)530
.collect();675
.collect();676
let line_tags: Vec<Tag> = vec![677
("panel", rectangle(0., 0., 100., 100.)),678
("panel/divider", rectangle(0., 50., 100., 1.)),679
("panel/divider-inset", rectangle(12., 60., 76., 1.)),680
("panel/divider-side", rectangle(40., 0., 1., 100.)),681
("panel/about", rectangle(12., 76., 76., 12.)),682
("panel/footer", rectangle(12., 64., 76., 12.)),683
];684
let line_keys: Vec<String> = divider_violations(&line_tags)685
.into_iter()686
.chain(inset_violations(687
&line_tags,688
&[689
InsetRule {690
panel: "panel",691
content: "panel/about",692
edges: &[Edge::Left, Edge::Right, Edge::Bottom],693
},694
InsetRule {695
panel: "panel",696
content: "panel/footer",697
edges: &[Edge::Left, Edge::Bottom],698
},699
],700
))701
.map(|(key, _)| key)702
.collect();703
assert_eq!(704
line_keys,705
["panel/divider-inset:short-divider", "panel:uneven-inset"]706
);531
assert_eq!(707
assert_eq!(532
keys,708
keys,533
[709
[@@ -753,6 +929,76 @@ mod frames {753
.join("\n")929
.join("\n")754
);930
);755
}931
}932
const TITLE_SEARCH: &str = "shell/title-bar/search";933
const TITLE_NEIGHBOURS: &[&str] = &[934
"shell/title-bar/leading",935
"shell/title-bar/mode-pill",936
"shell/title-bar/trailing",937
"shell/title-bar/update",938
OWN_STATUS,939
];940
const TITLE_SEARCH_SIZES: [(f32, f32, bool); 3] = [941
(1920., 1080., true),942
(1280., 800., true),943
(640., 480., false),944
];945
946
#[gpui_kit::test]947
fn title_search_is_centered_on_the_window(cx: &mut TestAppContext) {948
let (handle, _) = mount(cx);949
let mut visual = VisualTestContext::from_window(handle, cx);950
let shell = visual.update(|window, cx| {951
window952
.root::<gpui_kit::base::Root>()953
.flatten()954
.and_then(|root| root.read(cx).view().clone().downcast::<AppShell>().ok())955
.expect("app shell is the root view")956
});957
visual.update(|_, cx| {958
shell.update(cx, |shell, cx| {959
shell.set_update_status(crate::updater::UpdateStatus::Ready, cx)960
})961
});962
let mut found = Vec::new();963
for (width, height, centered) in TITLE_SEARCH_SIZES {964
visual.simulate_resize(size(px(width), px(height)));965
collect(&mut visual, Some(TITLE_SEARCH));966
let search = visual967
.debug_bounds(TITLE_SEARCH)968
.expect("title search rendered");969
let search_center = f32::from(search.center().x);970
eprintln!(971
"title search @{width}x{height}: {} center {search_center:.1}, window center {:.1}",972
describe(search),973
width / 2.974
);975
if centered && (search_center - width / 2.).abs() > 1. {976
found.push(format!(977
"@{width}x{height}: search center {search_center:.1} is not the window center {:.1}",978
width / 2.979
));980
}981
if !contains(rectangle(0., 0., width, height), search) {982
found.push(format!(983
"@{width}x{height}: search {} leaves the window",984
describe(search)985
));986
}987
for neighbour in TITLE_NEIGHBOURS {988
match visual.debug_bounds(neighbour) {989
None => found.push(format!("@{width}x{height}: {neighbour} was not rendered")),990
Some(bounds) if overlaps(search, bounds) => found.push(format!(991
"@{width}x{height}: search {} overlaps {neighbour} {}",992
describe(search),993
describe(bounds)994
)),995
Some(_) => {}996
}997
}998
}999
assert!(found.is_empty(), "{}", found.join("\n"));1000
}1001
756
#[gpui_kit::test]1002
#[gpui_kit::test]757
fn call_chat_bubbles_stay_inside_the_panel(cx: &mut TestAppContext) {1003
fn call_chat_bubbles_stay_inside_the_panel(cx: &mut TestAppContext) {758
let (handle, app) = mount(cx);1004
let (handle, app) = mount(cx);@@ -840,17 +1086,28 @@ mod frames {840
};1086
};841
let inset = metrics(width, height).inset;1087
let inset = metrics(width, height).inset;842
for section in SETTINGS_SECTIONS {1088
for section in SETTINGS_SECTIONS {843
visual.update(|_, cx| {1089
visual844
state.update(cx, |state, cx| state.open_settings(section, cx))1090
.update(|_, cx| state.update(cx, |state, cx| state.open_settings(section, cx)));845
});846
let tags = collect(&mut visual, Some(SETTINGS_TAGS[0]));1091
let tags = collect(&mut visual, Some(SETTINGS_TAGS[0]));847
let found: Vec<String> = violations(&tags, window, SETTINGS_TAGS)1092
let mut found: Vec<(String, String)> = violations(&tags, window, SETTINGS_TAGS)848
.into_iter()1093
.into_iter()849
.filter(|(key, _)| key.starts_with("settings"))1094
.filter(|(key, _)| key.starts_with("settings"))1095
.chain(inset_violations(&tags, INSET_RULES))1096
.collect();1097
let scrolled_exempt = SCROLLED_INSET_ALLOWLIST1098
.iter()1099
.any(|(exempt, _)| *exempt == section);1100
if !scrolled_exempt {1101
found.extend(scrolled_inset_violation(&mut visual));1102
}1103
let found: Vec<String> = found1104
.into_iter()850
.map(|(key, message)| format!("{section:?}@{width}x{height}:{key}: {message}"))1105
.map(|(key, message)| format!("{section:?}@{width}x{height}:{key}: {message}"))851
.collect();1106
.collect();852
assert!(found.is_empty(), "{}", found.join("\n"));1107
assert!(found.is_empty(), "{}", found.join("\n"));853
let dialog = visual.debug_bounds(SETTINGS_TAGS[0]).expect("settings dialog");1108
let dialog = visual1109
.debug_bounds(SETTINGS_TAGS[0])1110
.expect("settings dialog");854
let edges = [1111
let edges = [855
f32::from(dialog.left()),1112
f32::from(dialog.left()),856
f32::from(dialog.top()),1113
f32::from(dialog.top()),@@ -865,6 +1122,115 @@ mod frames {865
}1122
}866
}1123
}867
1124
1125
fn scrolled_inset_violation(visual: &mut VisualTestContext) -> Option<(String, String)> {1126
let body = visual.debug_bounds(SETTINGS_BODY)?;1127
let content = visual.debug_bounds(SETTINGS_CONTENT)?;1128
if content.bottom() <= body.bottom() {1129
return None;1130
}1131
visual.simulate_event(ScrollWheelEvent {1132
position: body.center(),1133
delta: ScrollDelta::Pixels(point(px(0.), px(-100_000.))),1134
..Default::default()1135
});1136
collect(visual, None);1137
let body = visual.debug_bounds(SETTINGS_BODY)?;1138
let content = visual.debug_bounds(SETTINGS_CONTENT)?;1139
inset_violation(&SCROLLED_INSET_RULE, body, content)1140
}1141
1142
#[gpui_kit::test]1143
fn members_popup_lines_reach_the_edges(cx: &mut TestAppContext) {1144
let (handle, state) = mount(cx);1145
let mut visual = VisualTestContext::from_window(handle, cx);1146
for (width, height) in SIZES {1147
visual.simulate_resize(size(px(width), px(height)));1148
let window = Bounds {1149
origin: point(px(0.), px(0.)),1150
size: size(px(width), px(height)),1151
};1152
visual.update(|_, cx| {1153
state.update(cx, |state, cx| {1154
state.select(Selection::Chat(MEMBERS_CHAT.to_owned()), cx)1155
})1156
});1157
collect(&mut visual, Some(MEMBERS_BUTTON));1158
let button = visual1159
.debug_bounds(MEMBERS_BUTTON)1160
.expect("members button rendered");1161
visual.simulate_click(button.center(), Default::default());1162
let tags = collect(&mut visual, Some(MEMBERS_TAGS[0]));1163
let found: Vec<String> = violations(&tags, window, MEMBERS_TAGS)1164
.into_iter()1165
.filter(|(key, _)| key.starts_with("chat-members"))1166
.map(|(key, message)| format!("members@{width}x{height}:{key}: {message}"))1167
.collect();1168
visual.simulate_keystrokes("escape");1169
visual.run_until_parked();1170
assert!(found.is_empty(), "{}", found.join("\n"));1171
}1172
}1173
1174
fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {1175
collect(visual, Some(COMPOSER_SEND_TAG));1176
let mut bounds_of = |path: &'static str| {1177
visual1178
.debug_bounds(path)1179
.unwrap_or_else(|| panic!("{path} rendered"))1180
};1181
let composer = bounds_of(COMPOSER_BOX_TAG);1182
let leading = bounds_of(COMPOSER_LEADING_TAG);1183
let send = bounds_of(COMPOSER_SEND_TAG);1184
[1185
f32::from(leading.left() - composer.left()),1186
f32::from(leading.top() - composer.top()),1187
f32::from(composer.bottom() - leading.bottom()),1188
f32::from(composer.right() - send.right()),1189
f32::from(send.top() - composer.top()),1190
f32::from(composer.bottom() - send.bottom()),1191
]1192
}1193
1194
#[gpui_kit::test]1195
fn composer_buttons_keep_equal_insets(cx: &mut TestAppContext) {1196
let (handle, _) = mount(cx);1197
let mut visual = VisualTestContext::from_window(handle, cx);1198
visual.simulate_resize(size(px(1280.), px(800.)));1199
let single_line = composer_button_insets(&mut visual);1200
let left = single_line[0];1201
assert!(1202
single_line1203
.iter()1204
.all(|inset| (inset - left).abs() < TOLERANCE),1205
"single line: insets left, top, bottom of the first button and right, top, bottom of send {single_line:?}"1206
);1207
let leading = visual1208
.debug_bounds(COMPOSER_LEADING_TAG)1209
.expect("leading buttons");1210
let send = visual.debug_bounds(COMPOSER_SEND_TAG).expect("send button");1211
visual.simulate_click(1212
point((leading.right() + send.left()) / 2., send.center().y),1213
Default::default(),1214
);1215
visual.simulate_keystrokes("o n e shift-enter t w o shift-enter t h r e e");1216
let three_lines = composer_button_insets(&mut visual);1217
assert!(1218
three_lines[1] > single_line[1] + 30.,1219
"three lines did not grow the composer: {three_lines:?}"1220
);1221
for inset in [1222
three_lines[0],1223
three_lines[2],1224
three_lines[3],1225
three_lines[5],1226
] {1227
assert!(1228
(inset - left).abs() < TOLERANCE,1229
"three lines: insets left, top, bottom of the first button and right, top, bottom of send {three_lines:?}, expected {left}"1230
);1231
}1232
}1233
868
#[gpui_kit::test]1234
#[gpui_kit::test]869
fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {1235
fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {870
let (handle, state) = mount_with(cx, true);1236
let (handle, state) = mount_with(cx, true);@@ -928,6 +1294,247 @@ fn lines_are_solid() {928
assert!(violations.is_empty(), "{}", violations.join("\n"));1294
assert!(violations.is_empty(), "{}", violations.join("\n"));929
}1295
}930
1296
1297
const STATE_RING_COLORS: &[&str] = &[1298
"if focused",1299
"if selected",1300
"if speaking",1301
"if current",1302
"if open",1303
"if state.failed",1304
];1305
const OUTLINE_ALLOWLIST: &[(&str, &str, &str)] = &[1306
(1307
"notify/ring_view.rs",1308
"theme::green()",1309
"OS toast window: no compositor shadow, the edge separates it from the desktop; accent = Teams state",1310
),1311
(1312
"notify/meeting_view.rs",1313
"theme::accent()",1314
"OS toast window: no compositor shadow, the edge separates it from the desktop; accent = Teams state",1315
),1316
(1317
"notify/meeting_view.rs",1318
"theme::border_strong()",1319
"outlined button, not a surface",1320
),1321
(1322
"notify/toast.rs",1323
"border)",1324
"OS toast window: no compositor shadow, the edge separates it from the desktop; accent = Teams state",1325
),1326
(1327
"notify/toast.rs",1328
"theme::border_strong()",1329
"OS toast window: no compositor shadow, the edge separates it from the desktop; accent = Teams state",1330
),1331
(1332
"settings/mcp.rs",1333
"theme::border_strong()",1334
"outlined button, not a surface",1335
),1336
(1337
"settings/rows.rs",1338
"theme::border_strong()",1339
"outlined button, not a surface",1340
),1341
(1342
"views/card_widgets.rs",1343
"border)",1344
"message content drawn as Teams renders it",1345
),1346
(1347
"views/card_widgets.rs",1348
"theme::border_strong()",1349
"message content drawn as Teams renders it",1350
),1351
("views/shared_tab.rs", "theme::accent()", "input field"),1352
("views/card_input.rs", "if error.is_some()", "input field"),1353
("views/format_toolbar.rs", "if refused", "input field"),1354
(1355
"views/card_code_block.rs",1356
"theme::code_header_border()",1357
"message content drawn as Teams renders it",1358
),1359
("views/call_transcript.rs", "theme::border()", "input field"),1360
(1361
"views/conversation.rs",1362
"theme::accent()",1363
"state signal (speaking, sharing, drag, drop, failed), not a resting outline",1364
),1365
(1366
"views/attachment_tray.rs",1367
"theme::accent()",1368
"state signal (speaking, sharing, drag, drop, failed), not a resting outline",1369
),1370
(1371
"views/card_carousel.rs",1372
"theme::border_strong()",1373
"message content drawn as Teams renders it",1374
),1375
(1376
"views/card_table.rs",1377
"grid_color",1378
"message content drawn as Teams renders it",1379
),1380
(1381
"views/activity_panel.rs",1382
"theme::surface()",1383
"cutout ring in the background color, invisible against its surface",1384
),1385
(1386
"views/avatar.rs",1387
"theme::surface()",1388
"cutout ring in the background color, invisible against its surface",1389
),1390
(1391
"views/avatar.rs",1392
"theme::text_muted()",1393
"offline presence glyph, Teams icon",1394
),1395
(1396
"views/message_row.rs",1397
"theme::border_strong()",1398
"deleted message placeholder, Teams look",1399
),1400
(1401
"views/message_row.rs",1402
"theme::red()",1403
"state signal (speaking, sharing, drag, drop, failed), not a resting outline",1404
),1405
(1406
"views/message_row.rs",1407
"if row.delivery",1408
"state signal (speaking, sharing, drag, drop, failed), not a resting outline",1409
),1410
(1411
"views/new_meeting_dialog.rs",1412
"theme::border()",1413
"input field",1414
),1415
(1416
"views/call_mini_window.rs",1417
"theme::border_strong()",1418
"self view over live video, needs an edge on any picture",1419
),1420
("views/transfer_picker.rs", "theme::border()", "input field"),1421
(1422
"views/call_notice.rs",1423
"theme::border_strong()",1424
"outlined button, not a surface",1425
),1426
(1427
"views/composer/schedule.rs",1428
"theme::accent()",1429
"input field",1430
),1431
(1432
"views/call_mini.rs",1433
"border)",1434
"state signal (speaking, sharing, drag, drop, failed), not a resting outline",1435
),1436
(1437
"views/sidebar.rs",1438
"theme::accent()",1439
"state signal (speaking, sharing, drag, drop, failed), not a resting outline",1440
),1441
(1442
"views/adaptive_card.rs",1443
"theme::border()",1444
"message content drawn as Teams renders it",1445
),1446
(1447
"views/adaptive_card.rs",1448
"border)",1449
"message content drawn as Teams renders it",1450
),1451
(1452
"views/share_bar.rs",1453
"theme::red()",1454
"state signal (speaking, sharing, drag, drop, failed), not a resting outline",1455
),1456
("settings_controls.rs", "if invalid", "input field"),1457
];1458
1459
fn outlines(source: &str) -> Vec<(usize, String)> {1460
let pattern = Regex::new(r"\.border(_1\(\)|_2\(\)|\(px)").expect("pattern");1461
pattern1462
.find_iter(source)1463
.map(|found| {1464
let line_number = source[..found.start()].matches('\n').count() + 1;1465
let after = &source[found.end()..];1466
let color = after1467
.find(".border_color(")1468
.filter(|position| *position < 120)1469
.map(|position| {1470
let start = &after[position + ".border_color(".len()..];1471
start1472
.lines()1473
.map(str::trim)1474
.find(|line| !line.is_empty())1475
.unwrap_or_default()1476
.to_owned()1477
})1478
.unwrap_or_default();1479
(line_number, color)1480
})1481
.collect()1482
}1483
1484
#[test]1485
fn outline_matcher_reads_the_border_color() {1486
let source = "div()\n .border_1()\n .border_color(theme::amber())\n .border_t_1()\n";1487
assert_eq!(outlines(source), [(2, "theme::amber())".to_owned())]);1488
}1489
1490
#[test]1491
fn surfaces_are_soft() {1492
let mut matched_allowlist = HashSet::new();1493
let mut violations = Vec::new();1494
for root in source_roots() {1495
let mut files = Vec::new();1496
source_files(&root, &mut files);1497
for file in files {1498
let relative = file1499
.strip_prefix(&root)1500
.expect("inside src")1501
.to_string_lossy()1502
.replace('\\', "/");1503
if relative == "layout_guard.rs" {1504
continue;1505
}1506
let source = fs::read_to_string(&file).expect("read source file");1507
for (line_number, color) in outlines(&source) {1508
if STATE_RING_COLORS1509
.iter()1510
.any(|prefix| color.starts_with(prefix))1511
{1512
continue;1513
}1514
match OUTLINE_ALLOWLIST.iter().position(|(allowed_file, prefix, _)| {1515
*allowed_file == relative && color.starts_with(prefix)1516
}) {1517
Some(position) => {1518
matched_allowlist.insert(position);1519
}1520
None => violations.push(format!(1521
"{relative}:{line_number}: hard outline on a surface, use a soft fill or shadow (border_color {color})"1522
)),1523
}1524
}1525
}1526
}1527
let stale = OUTLINE_ALLOWLIST1528
.iter()1529
.enumerate()1530
.filter(|(position, _)| !matched_allowlist.contains(position))1531
.map(|(_, (file, prefix, _))| {1532
format!("stale outline allowlist entry, remove it: {file} {prefix}")1533
});1534
let report: Vec<String> = violations.into_iter().chain(stale).collect();1535
assert!(report.is_empty(), "{}", report.join("\n"));1536
}1537
931
fn indentation(line: &str) -> usize {1538
fn indentation(line: &str) -> usize {932
line.len() - line.trim_start().len()1539
line.len() - line.trim_start().len()933
}1540
}@@ -177,6 +177,7 @@ impl SettingsDialog {
177
177
.child(
178
178
div()
179
179
.id("settings-close")
180
.debug_selector(|| "settings/main/header/close".into())
180
181
.size(px(CLOSE_SIZE))
181
182
.flex_none()
182
183
.flex()
@@ -226,6 +227,7 @@ impl Render for SettingsDialog {
226
227
.pb(px(metrics.padding))
227
228
.child(
228
229
div()
230
.debug_selector(|| "settings/main/body/content".into())
229
231
.w_full()
230
232
.max_w(px(CONTENT_MAX_WIDTH))
231
233
.child(self.content(cx)),
@@ -177,6 +177,7 @@ impl SettingsDialog {177
.child(177
.child(178
div()178
div()179
.id("settings-close")179
.id("settings-close")180
.debug_selector(|| "settings/main/header/close".into())180
.size(px(CLOSE_SIZE))181
.size(px(CLOSE_SIZE))181
.flex_none()182
.flex_none()182
.flex()183
.flex()@@ -226,6 +227,7 @@ impl Render for SettingsDialog {226
.pb(px(metrics.padding))227
.pb(px(metrics.padding))227
.child(228
.child(228
div()229
div()230
.debug_selector(|| "settings/main/body/content".into())229
.w_full()231
.w_full()230
.max_w(px(CONTENT_MAX_WIDTH))232
.max_w(px(CONTENT_MAX_WIDTH))231
.child(self.content(cx)),233
.child(self.content(cx)),@@ -833,9 +833,7 @@ impl McpView {
833
833
.p(px(6.))
834
834
.gap(px(4.))
835
835
.rounded(px(8.))
836
.bg(theme::popup())
837
.border_1()
838
.border_color(theme::border())
836
.bg(theme::surface_raised())
839
837
.child(
840
838
h_flex()
841
839
.h(px(30.))
@@ -833,9 +833,7 @@ impl McpView {833
.p(px(6.))833
.p(px(6.))834
.gap(px(4.))834
.gap(px(4.))835
.rounded(px(8.))835
.rounded(px(8.))836
.bg(theme::popup())836
.bg(theme::surface_raised())837
.border_1()838
.border_color(theme::border())839
.child(837
.child(840
h_flex()838
h_flex()841
.h(px(30.))839
.h(px(30.))@@ -13,8 +13,19 @@ actions!(
13
13
ToggleSubscript,
14
14
ToggleCode,
15
15
EditLink,
16
ScheduleSend
16
ScheduleSend,
17
PastePlainText,
18
InsertTableRowAbove,
19
InsertTableRowBelow,
20
InsertTableColumnLeft,
21
InsertTableColumnRight,
22
DeleteTableRow,
23
DeleteTableColumn,
24
DeleteTable
17
25
]
18
26
);
19
27
20
actions!(teams, [ReplyToHovered, OpenSwitcher, NewChat, ToggleCallMute]);
28
actions!(
29
teams,
30
[ReplyToHovered, OpenSwitcher, NewChat, ToggleCallMute]
31
);
@@ -13,8 +13,19 @@ actions!(13
ToggleSubscript,13
ToggleSubscript,14
ToggleCode,14
ToggleCode,15
EditLink,15
EditLink,16
ScheduleSend16
ScheduleSend,17
PastePlainText,18
InsertTableRowAbove,19
InsertTableRowBelow,20
InsertTableColumnLeft,21
InsertTableColumnRight,22
DeleteTableRow,23
DeleteTableColumn,24
DeleteTable17
]25
]18
);26
);19
27
20
actions!(teams, [ReplyToHovered, OpenSwitcher, NewChat, ToggleCallMute]);28
actions!(29
teams,30
[ReplyToHovered, OpenSwitcher, NewChat, ToggleCallMute]31
);@@ -21,7 +21,7 @@ use crate::call::{
21
21
ActiveCall, CallModel, OptionsDialog, PeopleSections, PersonRow, people_sections,
22
22
};
23
23
use crate::notice::truncated;
24
use crate::theme;
24
use crate::theme::{self, ElevatedSurface as _};
25
25
use calling::MeetingOptions;
26
26
27
27
const HEADER_HEIGHT: f32 = 48.;
@@ -652,11 +652,8 @@ pub fn options_dialog(app: &Entity<AppState>, call: &ActiveCall) -> Option<AnyEl
652
652
.p(px(16.))
653
653
.gap(px(12.))
654
654
.rounded(px(12.))
655
.bg(theme::background())
656
.border_1()
657
.border_color(theme::border_strong())
655
.dialog_surface()
658
656
.text_color(theme::text())
659
.shadow(theme::dialog_shadow())
660
657
.occlude()
661
658
.child(
662
659
div()
@@ -21,7 +21,7 @@ use crate::call::{21
ActiveCall, CallModel, OptionsDialog, PeopleSections, PersonRow, people_sections,21
ActiveCall, CallModel, OptionsDialog, PeopleSections, PersonRow, people_sections,22
};22
};23
use crate::notice::truncated;23
use crate::notice::truncated;24
use crate::theme;24
use crate::theme::{self, ElevatedSurface as _};25
use calling::MeetingOptions;25
use calling::MeetingOptions;26
26
27
const HEADER_HEIGHT: f32 = 48.;27
const HEADER_HEIGHT: f32 = 48.;@@ -652,11 +652,8 @@ pub fn options_dialog(app: &Entity<AppState>, call: &ActiveCall) -> Option<AnyEl652
.p(px(16.))652
.p(px(16.))653
.gap(px(12.))653
.gap(px(12.))654
.rounded(px(12.))654
.rounded(px(12.))655
.bg(theme::background())655
.dialog_surface()656
.border_1()657
.border_color(theme::border_strong())658
.text_color(theme::text())656
.text_color(theme::text())659
.shadow(theme::dialog_shadow())660
.occlude()657
.occlude()661
.child(658
.child(662
div()659
div()@@ -94,7 +94,13 @@ fn members_panel(
94
94
.child(list)
95
95
.when(is_member, |panel| {
96
96
panel
97
.child(div().h(px(1.)).w_full().bg(theme::border()))
97
.child(
98
div()
99
.debug_selector(|| "chat-members-popup/divider".into())
100
.h(px(1.))
101
.w_full()
102
.bg(theme::border()),
103
)
98
104
.child(
99
105
v_flex()
100
106
.py(px(4.))
@@ -94,7 +94,13 @@ fn members_panel(94
.child(list)94
.child(list)95
.when(is_member, |panel| {95
.when(is_member, |panel| {96
panel96
panel97
.child(div().h(px(1.)).w_full().bg(theme::border()))97
.child(98
div()99
.debug_selector(|| "chat-members-popup/divider".into())100
.h(px(1.))101
.w_full()102
.bg(theme::border()),103
)98
.child(104
.child(99
v_flex()105
v_flex()100
.py(px(4.))106
.py(px(4.))@@ -13,8 +13,9 @@ use gpui_kit::component::{
13
13
h_flex,
14
14
input::{
15
15
Backspace, Copy, Cut, Delete, Enter, Escape, IndentInline, InlineToken, InputContent,
16
InputEvent, InputState, MoveDown, MoveUp, OutdentInline, RangeDecorationCollection, Redo,
17
TextDecorationCollection, Textarea, TextareaMode, TextareaState, Undo,
16
InputEvent, InputState, MoveDown, MoveRight, MoveUp, OutdentInline,
17
RangeDecorationCollection, Redo, TextDecorationCollection, Textarea, TextareaMode,
18
TextareaState, Undo,
18
19
},
19
20
popover::Popover,
20
21
tooltip::Tooltip,
@@ -24,21 +25,24 @@ use gpui_kit::prelude::FluentBuilder as _;
24
25
use gpui_kit::*;
25
26
use teams_core::{
26
27
Draft, DraftLine, Edit, FileReference, FormatState, LineKind, LinkPreview, MarkKind,
27
MentionCandidate, MentionInput, OBJECT_MARK, SizeStep, TypingStyle,
28
MentionCandidate, MentionInput, OBJECT_MARK, SizeStep, TABLE_MARK, TableEdit, TypingStyle,
28
29
UploadedFile, changed_span, has_markdown, link_url, map_offset, reverse_edits,
29
30
};
30
31
31
32
mod drafts;
32
33
mod schedule;
34
mod table;
33
35
34
36
use super::actions::{
35
COMPOSER_KEY_CONTEXT, EditLink, OpenSwitcher, ScheduleSend, ToggleBold, ToggleCode, ToggleItalic,
36
ToggleStrike, ToggleSubscript, ToggleSuperscript, ToggleUnderline,
37
COMPOSER_KEY_CONTEXT, DeleteTable, DeleteTableColumn, DeleteTableRow, EditLink,
38
InsertTableColumnLeft, InsertTableColumnRight, InsertTableRowAbove, InsertTableRowBelow,
39
OpenSwitcher, PastePlainText, ScheduleSend, ToggleBold, ToggleCode, ToggleItalic, ToggleStrike,
40
ToggleSubscript, ToggleSuperscript, ToggleUnderline,
37
41
};
38
42
use super::attachment_tray::{
39
AttachmentTray, DoneFile, JobKind, LoadedFile, MAX_ATTACHMENTS,
40
PasteAction, UploadJob, UploadResult, discard_uploaded, inline_preview, names_of, paste_action,
41
pasted_image_name, prepare_pasted_image, read_attachment, render_tray,
43
AttachmentTray, DoneFile, JobKind, LoadedFile, MAX_ATTACHMENTS, PasteAction, UploadJob,
44
UploadResult, discard_uploaded, inline_preview, names_of, paste_action, pasted_image_name,
45
prepare_pasted_image, read_attachment, render_tray,
42
46
};
43
47
use super::avatar::{person_avatar, square_avatar};
44
48
use super::draft_style::draft_style;
@@ -55,6 +59,7 @@ use crate::runtime;
55
59
use crate::scheduled_rows::scheduled_label;
56
60
use crate::theme::{self, ElevatedSurface as _};
57
61
use crate::typing::OutgoingTyping;
62
use table::{TableKey, TablePicker, TableViews, is_table_token};
58
63
59
64
const MIN_ROWS: usize = 1;
60
65
const MAX_ROWS: usize = 8;
@@ -67,6 +72,11 @@ const POPUP_WIDTH: f32 = 380.;
67
72
const POPUP_ROW_HEIGHT: f32 = 44.;
68
73
const DEMO_UPLOAD_STEPS: u8 = 10;
69
74
const COMPOSER_ICON_SIZE: f32 = 20.;
75
const COMPOSER_BUTTON_SIZE: f32 = 32.;
76
const COMPOSER_BUTTON_INSET: f32 = 6.;
77
pub const COMPOSER_BOX_TAG: &str = "composer";
78
pub const COMPOSER_LEADING_TAG: &str = "composer/leading";
79
pub const COMPOSER_SEND_TAG: &str = "composer/send";
70
80
/// gpui-kit draws a `Size::Size` button's icon at this fraction of the button size.
71
81
const BUTTON_ICON_SCALE: f32 = 0.75;
72
82
const DEMO_UPLOAD_STEP: Duration = Duration::from_millis(120);
@@ -126,8 +136,19 @@ struct Conversion {
126
136
127
137
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128
138
enum StepKind {
129
Typing { at: usize, after_space: bool },
130
Deleting { start: usize, end: usize },
139
Typing {
140
at: usize,
141
after_space: bool,
142
},
143
Deleting {
144
start: usize,
145
end: usize,
146
},
147
CellTyping {
148
table: usize,
149
row: usize,
150
column: usize,
151
},
131
152
Other,
132
153
}
133
154
@@ -192,6 +213,12 @@ pub struct Composer {
192
213
pending_anchors: HashMap<u64, usize>,
193
214
link: ComposeLink,
194
215
fun_picker: Entity<FunPicker>,
216
tables: TableViews,
217
table_counter: usize,
218
table_picker: Option<TablePicker>,
219
active_cell: Option<(String, teams_core::Cell)>,
220
caret_before_table: usize,
221
caret_text: String,
195
222
_subscriptions: [Subscription; 4],
196
223
}
197
224
@@ -292,6 +319,9 @@ fn continues(last: &HistoryStep, kind: StepKind) -> bool {
292
319
(StepKind::Deleting { .. }, StepKind::Deleting { start, end }) => {
293
320
caret.is_empty() && (caret.start == end || caret.start == start)
294
321
}
322
(previous @ StepKind::CellTyping { .. }, next @ StepKind::CellTyping { .. }) => {
323
previous == next
324
}
295
325
_ => false,
296
326
}
297
327
}
@@ -328,7 +358,10 @@ impl Composer {
328
358
.placeholder("Type a message")
329
359
});
330
360
let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
331
let observer = cx.observe(&input, |_, _, cx| cx.notify());
361
let observer = cx.observe_in(&input, window, |this, _, window, cx| {
362
this.redirect_caret_from_table(window, cx);
363
cx.notify();
364
});
332
365
let image_observer = cx.observe(&app, |this, _, cx| {
333
366
if this.link_image_pending(cx) {
334
367
cx.notify();
@@ -389,6 +422,12 @@ impl Composer {
389
422
pending_anchors: HashMap::new(),
390
423
link: ComposeLink::default(),
391
424
fun_picker,
425
tables: TableViews::default(),
426
table_counter: 0,
427
table_picker: None,
428
active_cell: None,
429
caret_before_table: 0,
430
caret_text: String::new(),
392
431
_subscriptions: [subscription, observer, image_observer, picker_subscription],
393
432
}
394
433
}
@@ -640,6 +679,7 @@ impl Composer {
640
679
}
641
680
self.previous_value = value;
642
681
self.refresh_style(cx);
682
self.sync_tables(window, cx);
643
683
}
644
684
645
685
fn shift_anchors(&mut self, start: usize, old_end: usize, new_end: usize) {
@@ -737,6 +777,7 @@ impl Composer {
737
777
self.conversion = None;
738
778
self.paste_hint = None;
739
779
self.refresh_style(cx);
780
self.sync_tables(window, cx);
740
781
self.update_emoji(cx);
741
782
self.update_mention(cx);
742
783
self.schedule_draft_save(cx);
@@ -775,6 +816,9 @@ impl Composer {
775
816
self.link_editor = None;
776
817
self.toolbar_dismissed = None;
777
818
self.pending_anchors.clear();
819
self.active_cell = None;
820
self.table_picker = None;
821
self.sync_tables(window, cx);
778
822
self.history.clear();
779
823
self.history_index = 0;
780
824
self.record(StepKind::Other, cx);
@@ -1064,6 +1108,64 @@ impl Composer {
1064
1108
}
1065
1109
}
1066
1110
1111
fn leave_quote(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
1112
let selection = self.selection(cx);
1113
if !selection.is_empty() || self.input.read(cx).value().as_ref() != self.draft.text() {
1114
return false;
1115
}
1116
match self.draft.leave_quote_at_end(selection.start) {
1117
Some(cursor) => {
1118
self.commit(Some(cursor), window, cx);
1119
true
1120
}
1121
None => false,
1122
}
1123
}
1124
1125
/// Backspace right after a table or Delete right before one goes into it instead of
1126
/// joining the line with the table's.
1127
fn enter_table_beside(
1128
&mut self,
1129
after: bool,
1130
window: &mut Window,
1131
cx: &mut Context<Self>,
1132
) -> bool {
1133
let selection = self.selection(cx);
1134
if !selection.is_empty() || self.input.read(cx).value().as_ref() != self.draft.text() {
1135
return false;
1136
}
1137
let found = if after {
1138
self.draft.table_before(selection.start)
1139
} else {
1140
self.draft.table_after(selection.start)
1141
};
1142
let Some(index) = found else {
1143
return false;
1144
};
1145
self.focus_table_line(index, after, window, cx);
1146
true
1147
}
1148
1149
fn cell_has_focus(&self, window: &Window, cx: &App) -> bool {
1150
self.focused_cell(window, cx).is_some()
1151
}
1152
1153
fn paste_plain(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1154
let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) else {
1155
return;
1156
};
1157
let text = text
1158
.replace("\r\n", "\n")
1159
.replace([OBJECT_MARK, TABLE_MARK], "");
1160
if let Some(input) = self.focused_cell_input(window, cx) {
1161
input.update(cx, |state, cx| state.replace(text, window, cx));
1162
return;
1163
}
1164
self.pasted_markdown = None;
1165
self.input
1166
.update(cx, |state, cx| state.replace(text, window, cx));
1167
}
1168
1067
1169
fn indent(&mut self, outdent: bool, window: &mut Window, cx: &mut Context<Self>) -> bool {
1068
1170
let selection = self.selection(cx);
1069
1171
if !self.draft.indent(selection, outdent) {
@@ -1079,12 +1181,16 @@ impl Composer {
1079
1181
return false;
1080
1182
}
1081
1183
let selected = &self.draft.text()[selection.clone()];
1082
let text = selected.replace(OBJECT_MARK, "");
1083
1184
let lines = if selected.contains(OBJECT_MARK) {
1084
1185
self.draft.slice_without_objects(selection)
1085
1186
} else {
1086
1187
self.draft.slice(selection)
1087
1188
};
1189
let text = if selected.contains(TABLE_MARK) {
1190
Draft::from_lines(&lines).plain_text()
1191
} else {
1192
selected.replace(OBJECT_MARK, "")
1193
};
1088
1194
if text.is_empty() {
1089
1195
return true;
1090
1196
}
@@ -1150,8 +1256,8 @@ impl Composer {
1150
1256
}
1151
1257
let matches = emoji::search(&query, &self.recent_emoji.glyphs(), emoji_popup::LIMIT);
1152
1258
let skin_tone = teams_core::skin_tone(&self.app.read(cx).store);
1153
self.emoji_popup = (!matches.is_empty())
1154
.then(|| EmojiPopup::new(range, query, matches, skin_tone));
1259
self.emoji_popup =
1260
(!matches.is_empty()).then(|| EmojiPopup::new(range, query, matches, skin_tone));
1155
1261
}
1156
1262
1157
1263
fn accept_emoji(&mut self, window: &mut Window, cx: &mut Context<Self>) {
@@ -1764,8 +1870,8 @@ impl Composer {
1764
1870
let Some(text) = item.text() else {
1765
1871
return false;
1766
1872
};
1767
if text.contains(OBJECT_MARK) {
1768
let cleaned = text.replace(OBJECT_MARK, "");
1873
if text.contains([OBJECT_MARK, TABLE_MARK]) {
1874
let cleaned = text.replace([OBJECT_MARK, TABLE_MARK], "");
1769
1875
self.input
1770
1876
.update(cx, |state, cx| state.replace(cleaned, window, cx));
1771
1877
return true;
@@ -2397,8 +2503,9 @@ impl Render for Composer {
2397
2503
let can_attach = self.editing.is_none();
2398
2504
let send = div()
2399
2505
.id("composer-send")
2400
.size(px(32.))
2401
.ml(px(6.))
2506
.debug_selector(|| COMPOSER_SEND_TAG.into())
2507
.size(px(COMPOSER_BUTTON_SIZE))
2508
.ml(px(COMPOSER_BUTTON_INSET))
2402
2509
.flex_none()
2403
2510
.flex()
2404
2511
.items_center()
@@ -2432,7 +2539,7 @@ impl Render for Composer {
2432
2539
)
2433
2540
.rounded(px(8.))
2434
2541
.with_size(px(COMPOSER_ICON_SIZE / BUTTON_ICON_SCALE))
2435
.size(px(32.))
2542
.size(px(COMPOSER_BUTTON_SIZE))
2436
2543
.tooltip("Emoji, GIFs und Sticker")
2437
2544
.icon(symbol("mood", COMPOSER_ICON_SIZE, theme::text_muted())),
2438
2545
)
@@ -2450,7 +2557,7 @@ impl Render for Composer {
2450
2557
let attach = can_attach.then(|| {
2451
2558
div()
2452
2559
.id("composer-attach")
2453
.size(px(32.))
2560
.size(px(COMPOSER_BUTTON_SIZE))
2454
2561
.flex_none()
2455
2562
.flex()
2456
2563
.items_center()
@@ -2466,9 +2573,28 @@ impl Render for Composer {
2466
2573
))
2467
2574
.on_click(cx.listener(|this, _, window, cx| this.open_picker(window, cx)))
2468
2575
});
2576
let table_button = can_attach.then(|| {
2577
div()
2578
.id("composer-table")
2579
.size(px(COMPOSER_BUTTON_SIZE))
2580
.flex_none()
2581
.flex()
2582
.items_center()
2583
.justify_center()
2584
.rounded(px(8.))
2585
.cursor_pointer()
2586
.hover(|button| button.bg(theme::popup_hover()))
2587
.when(self.table_picker.is_some(), |button| {
2588
button.bg(theme::popup_hover())
2589
})
2590
.tooltip(|window, cx| Tooltip::new("Insert table").build(window, cx))
2591
.child(symbol("table", COMPOSER_ICON_SIZE, theme::text_muted()))
2592
.on_click(cx.listener(|this, _, _, cx| this.open_table_picker(cx)))
2593
});
2469
2594
let composer = cx.weak_entity();
2470
2595
let tokens_composer = composer.clone();
2471
2596
let input = Textarea::new(&self.input)
2597
.line_box_height(px(COMPOSER_BUTTON_SIZE))
2472
2598
.appearance(false)
2473
2599
.bordered(false)
2474
2600
.on_paste(move |item, window, cx| {
@@ -2477,6 +2603,17 @@ impl Render for Composer {
2477
2603
.unwrap_or(false)
2478
2604
})
2479
2605
.token(move |context, _, cx| {
2606
if context.is_block() && is_table_token(context.token()) {
2607
let token_id = context.token().id().to_string();
2608
let width = context.available_width();
2609
if let Some(table) = tokens_composer
2610
.read_with(cx, |this, _| this.render_table_token(&token_id, width))
2611
.ok()
2612
.flatten()
2613
{
2614
return table;
2615
}
2616
}
2480
2617
if let Some(id) = context
2481
2618
.is_block()
2482
2619
.then(|| image_id(context.token()))
@@ -2550,42 +2687,70 @@ impl Render for Composer {
2550
2687
.pt(px(top))
2551
2688
.pb(px(bottom))
2552
2689
.key_context(COMPOSER_KEY_CONTEXT)
2553
.on_action(cx.listener(|this, _: &ToggleBold, _, cx| {
2554
if this.link_editor.is_none() {
2690
.on_action(cx.listener(|this, _: &ToggleBold, window, cx| {
2691
if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
2555
2692
this.toggle_mark(MarkKind::Bold, cx);
2556
2693
}
2557
2694
}))
2558
.on_action(cx.listener(|this, _: &ToggleItalic, _, cx| {
2559
if this.link_editor.is_none() {
2695
.on_action(cx.listener(|this, _: &ToggleItalic, window, cx| {
2696
if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
2560
2697
this.toggle_mark(MarkKind::Italic, cx);
2561
2698
}
2562
2699
}))
2563
.on_action(cx.listener(|this, _: &ToggleUnderline, _, cx| {
2564
if this.link_editor.is_none() {
2700
.on_action(cx.listener(|this, _: &ToggleUnderline, window, cx| {
2701
if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
2565
2702
this.toggle_mark(MarkKind::Underline, cx);
2566
2703
}
2567
2704
}))
2568
.on_action(cx.listener(|this, _: &ToggleStrike, _, cx| {
2569
if this.link_editor.is_none() {
2705
.on_action(cx.listener(|this, _: &ToggleStrike, window, cx| {
2706
if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
2570
2707
this.toggle_mark(MarkKind::Strike, cx);
2571
2708
}
2572
2709
}))
2573
.on_action(cx.listener(|this, _: &ToggleSuperscript, _, cx| {
2574
if this.link_editor.is_none() {
2710
.on_action(cx.listener(|this, _: &ToggleSuperscript, window, cx| {
2711
if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
2575
2712
this.toggle_mark(MarkKind::Superscript, cx);
2576
2713
}
2577
2714
}))
2578
.on_action(cx.listener(|this, _: &ToggleSubscript, _, cx| {
2579
if this.link_editor.is_none() {
2715
.on_action(cx.listener(|this, _: &ToggleSubscript, window, cx| {
2716
if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
2580
2717
this.toggle_mark(MarkKind::Subscript, cx);
2581
2718
}
2582
2719
}))
2583
.on_action(cx.listener(|this, _: &ToggleCode, _, cx| {
2584
if this.link_editor.is_none() {
2720
.on_action(cx.listener(|this, _: &ToggleCode, window, cx| {
2721
if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
2585
2722
this.toggle_mark(MarkKind::Code, cx);
2586
2723
}
2587
2724
}))
2588
.on_action(cx.listener(|this, _: &EditLink, window, cx| this.edit_link(window, cx)))
2725
.on_action(cx.listener(|this, _: &EditLink, window, cx| {
2726
if !this.cell_has_focus(window, cx) {
2727
this.edit_link(window, cx);
2728
}
2729
}))
2730
.on_action(
2731
cx.listener(|this, _: &PastePlainText, window, cx| this.paste_plain(window, cx)),
2732
)
2733
.on_action(cx.listener(|this, _: &InsertTableRowAbove, window, cx| {
2734
this.edit_table(TableEdit::InsertRowAbove, window, cx)
2735
}))
2736
.on_action(cx.listener(|this, _: &InsertTableRowBelow, window, cx| {
2737
this.edit_table(TableEdit::InsertRowBelow, window, cx)
2738
}))
2739
.on_action(cx.listener(|this, _: &InsertTableColumnLeft, window, cx| {
2740
this.edit_table(TableEdit::InsertColumnLeft, window, cx)
2741
}))
2742
.on_action(cx.listener(|this, _: &InsertTableColumnRight, window, cx| {
2743
this.edit_table(TableEdit::InsertColumnRight, window, cx)
2744
}))
2745
.on_action(cx.listener(|this, _: &DeleteTableRow, window, cx| {
2746
this.edit_table(TableEdit::DeleteRow, window, cx)
2747
}))
2748
.on_action(cx.listener(|this, _: &DeleteTableColumn, window, cx| {
2749
this.edit_table(TableEdit::DeleteColumn, window, cx)
2750
}))
2751
.on_action(cx.listener(|this, _: &DeleteTable, window, cx| {
2752
this.edit_table(TableEdit::DeleteTable, window, cx)
2753
}))
2589
2754
.on_action(cx.listener(|this, _: &ScheduleSend, _, cx| this.open_schedule_picker(cx)))
2590
2755
.capture_action(cx.listener(|this, _: &Undo, window, cx| {
2591
2756
if this.link_editor.is_none() {
@@ -2599,20 +2764,30 @@ impl Render for Composer {
2599
2764
cx.stop_propagation();
2600
2765
}
2601
2766
}))
2602
.capture_action(cx.listener(|this, _: &Copy, _, cx| {
2603
if this.link_editor.is_none() && this.copy_selection(cx) {
2767
.capture_action(cx.listener(|this, _: &Copy, window, cx| {
2768
if this.link_editor.is_none()
2769
&& !this.cell_has_focus(window, cx)
2770
&& this.copy_selection(cx)
2771
{
2604
2772
cx.stop_propagation();
2605
2773
}
2606
2774
}))
2607
2775
.capture_action(cx.listener(|this, _: &Cut, window, cx| {
2608
if this.link_editor.is_none() && this.copy_selection(cx) {
2776
if this.link_editor.is_none()
2777
&& !this.cell_has_focus(window, cx)
2778
&& this.copy_selection(cx)
2779
{
2609
2780
this.input
2610
2781
.update(cx, |state, cx| state.replace("", window, cx));
2611
2782
cx.stop_propagation();
2612
2783
}
2613
2784
}))
2614
2785
.capture_action(cx.listener(|this, _: &MoveUp, window, cx| {
2615
if this.link_editor.is_some() {
2786
if this.cell_has_focus(window, cx) {
2787
if this.table_key(TableKey::Up, window, cx) {
2788
cx.stop_propagation();
2789
}
2790
} else if this.link_editor.is_some() {
2616
2791
} else if this.schedule.is_some() {
2617
2792
this.move_schedule_highlight(-1, window, cx);
2618
2793
cx.stop_propagation();
@@ -2625,17 +2800,32 @@ impl Render for Composer {
2625
2800
}
2626
2801
}))
2627
2802
.capture_action(cx.listener(|this, _: &MoveDown, window, cx| {
2628
if this.link_editor.is_some() {
2803
if this.cell_has_focus(window, cx) {
2804
if this.table_key(TableKey::Down, window, cx) {
2805
cx.stop_propagation();
2806
}
2807
} else if this.link_editor.is_some() {
2629
2808
} else if this.schedule.is_some() {
2630
2809
this.move_schedule_highlight(1, window, cx);
2631
2810
cx.stop_propagation();
2632
2811
} else if this.popup_is_open() {
2633
2812
this.move_highlight(1, cx);
2634
2813
cx.stop_propagation();
2814
} else if this.leave_quote(window, cx) {
2815
cx.stop_propagation();
2816
}
2817
}))
2818
.capture_action(cx.listener(|this, _: &MoveRight, window, cx| {
2819
if this.link_editor.is_none()
2820
&& !this.cell_has_focus(window, cx)
2821
&& this.leave_quote(window, cx)
2822
{
2823
cx.stop_propagation();
2635
2824
}
2636
2825
}))
2637
2826
.capture_action(cx.listener(|this, action: &Enter, window, cx| {
2638
if this.link_editor.is_some() {
2827
if this.cell_has_focus(window, cx) {
2828
} else if this.link_editor.is_some() {
2639
2829
this.apply_link(window, cx);
2640
2830
cx.stop_propagation();
2641
2831
} else if this.schedule.is_some() {
@@ -2649,7 +2839,9 @@ impl Render for Composer {
2649
2839
}
2650
2840
}))
2651
2841
.capture_action(cx.listener(|this, _: &IndentInline, window, cx| {
2652
if this.link_editor.is_some() {
2842
if this.table_key(TableKey::Next, window, cx) {
2843
cx.stop_propagation();
2844
} else if this.link_editor.is_some() {
2653
2845
} else if this.popup_is_open() {
2654
2846
this.accept_popup(window, cx);
2655
2847
cx.stop_propagation();
@@ -2658,23 +2850,37 @@ impl Render for Composer {
2658
2850
}
2659
2851
}))
2660
2852
.capture_action(cx.listener(|this, _: &OutdentInline, window, cx| {
2661
if this.link_editor.is_none() && this.indent(true, window, cx) {
2853
if this.table_key(TableKey::Previous, window, cx)
2854
|| (this.link_editor.is_none() && this.indent(true, window, cx))
2855
{
2662
2856
cx.stop_propagation();
2663
2857
}
2664
2858
}))
2665
2859
.capture_action(cx.listener(|this, _: &Backspace, window, cx| {
2666
2860
if this.link_editor.is_none()
2667
&& (this.undo_conversion(window, cx) || this.backspace_at_start(window, cx))
2861
&& !this.cell_has_focus(window, cx)
2862
&& (this.undo_conversion(window, cx)
2863
|| this.backspace_at_start(window, cx)
2864
|| this.enter_table_beside(true, window, cx))
2668
2865
{
2669
2866
cx.stop_propagation();
2670
2867
}
2671
2868
}))
2672
2869
.capture_action(cx.listener(|this, _: &Delete, window, cx| {
2673
if this.link_editor.is_none() && this.delete_forward(window, cx) {
2870
if this.link_editor.is_none()
2871
&& !this.cell_has_focus(window, cx)
2872
&& (this.enter_table_beside(false, window, cx)
2873
|| this.delete_forward(window, cx))
2874
{
2674
2875
cx.stop_propagation();
2675
2876
}
2676
2877
}))
2677
2878
.capture_action(cx.listener(|this, _: &Escape, window, cx| {
2879
if this.table_picker.take().is_some() {
2880
cx.notify();
2881
cx.stop_propagation();
2882
return;
2883
}
2678
2884
if this.schedule.is_some() {
2679
2885
this.close_schedule(window, cx);
2680
2886
cx.stop_propagation();
@@ -2716,8 +2922,10 @@ impl Render for Composer {
2716
2922
.children(self.render_emoji_popup(window, cx))
2717
2923
.children(self.render_toolbar(focused, cx))
2718
2924
.children(self.render_schedule(cx))
2925
.children(self.render_table_picker(cx))
2719
2926
.child(
2720
2927
v_flex()
2928
.debug_selector(|| COMPOSER_BOX_TAG.into())
2721
2929
.relative()
2722
2930
.w_full()
2723
2931
.rounded(px(12.))
@@ -2747,16 +2955,22 @@ impl Render for Composer {
2747
2955
row.items_end()
2748
2956
}
2749
2957
})
2750
.py(px(6.))
2751
.pl(px(if can_attach { 6. } else { 12. }))
2752
.pr(px(6.))
2958
.py(px(COMPOSER_BUTTON_INSET))
2959
.pl(px(if can_attach {
2960
COMPOSER_BUTTON_INSET
2961
} else {
2962
12.
2963
}))
2964
.pr(px(COMPOSER_BUTTON_INSET))
2753
2965
.when(can_attach, |row| {
2754
2966
row.child(
2755
2967
h_flex()
2968
.debug_selector(|| COMPOSER_LEADING_TAG.into())
2756
2969
.flex_none()
2757
.gap(px(6.))
2970
.gap(px(COMPOSER_BUTTON_INSET))
2758
2971
.children(fun)
2759
.children(attach),
2972
.children(attach)
2973
.children(table_button),
2760
2974
)
2761
2975
})
2762
2976
.child(
@@ -2926,7 +3140,10 @@ mod tests {
2926
3140
})
2927
3141
}
2928
3142
2929
fn outgoing_with(text: &str, images: Vec<crate::outgoing::OutgoingImage>) -> crate::outgoing::Outgoing {
3143
fn outgoing_with(
3144
text: &str,
3145
images: Vec<crate::outgoing::OutgoingImage>,
3146
) -> crate::outgoing::Outgoing {
2930
3147
crate::outgoing::Outgoing {
2931
3148
draft: teams_core::Draft::plain(text),
2932
3149
subject: None,
@@ -2984,7 +3201,10 @@ mod tests {
2984
3201
#[test]
2985
3202
fn a_sticker_carries_the_sticker_itemtype() {
2986
3203
let sticker = super::RemoteImage::sticker(crate::stickers::popular()[0]);
2987
let outgoing = outgoing_with("\u{FFFC}", vec![crate::outgoing::OutgoingImage::Remote(sticker)]);
3204
let outgoing = outgoing_with(
3205
"\u{FFFC}",
3206
vec![crate::outgoing::OutgoingImage::Remote(sticker)],
3207
);
2988
3208
assert!(
2989
3209
outgoing
2990
3210
.html()
@@ -3395,7 +3615,9 @@ mod tests {
3395
3615
excerpt: "question".into(),
3396
3616
};
3397
3617
typist.act(|_, cx| {
3398
composer.update(cx, |composer, cx| composer.set_reply(Some(reply.clone()), cx));
3618
composer.update(cx, |composer, cx| {
3619
composer.set_reply(Some(reply.clone()), cx)
3620
});
3399
3621
});
3400
3622
load(&mut typist, &entry);
3401
3623
let tokens = image_tokens(&mut typist);
@@ -3991,7 +4213,7 @@ mod tests {
3991
4213
#[gpui_kit::test]
3992
4214
fn quotes_continue_on_shift_enter_and_send_as_blockquote(cx: &mut TestAppContext) {
3993
4215
let mut typist = typist(cx);
3994
typist.type_text("> quoted");
4216
typist.type_text(">quoted");
3995
4217
typist.press("shift-enter");
3996
4218
typist.type_text("more");
3997
4219
let outgoing = typist.outgoing();
@@ -3999,6 +4221,112 @@ mod tests {
3999
4221
assert_eq!(outgoing.text(), "quoted\nmore");
4000
4222
}
4001
4223
4224
#[gpui_kit::test]
4225
fn enter_in_a_quote_adds_a_line_and_enter_on_the_empty_one_leaves_it(
4226
cx: &mut TestAppContext,
4227
) {
4228
let mut typist = typist(cx);
4229
typist.type_text(">quoted");
4230
typist.press("enter");
4231
typist.type_text("more");
4232
typist.press("enter enter");
4233
typist.type_text("after");
4234
assert_eq!(typist.value(), "quoted\nmore\nafter");
4235
assert_eq!(
4236
typist.outgoing().html(),
4237
"<blockquote>quoted<br>more</blockquote>after"
4238
);
4239
}
4240
4241
#[gpui_kit::test]
4242
fn down_at_the_end_of_a_quote_leaves_it(cx: &mut TestAppContext) {
4243
let mut typist = typist(cx);
4244
typist.type_text(">quoted");
4245
typist.press("down");
4246
typist.type_text("after");
4247
assert_eq!(
4248
typist.outgoing().html(),
4249
"<blockquote>quoted</blockquote>after"
4250
);
4251
}
4252
4253
fn insert_table(typist: &mut Typist<'_>, rows: usize, columns: usize) {
4254
let composer = typist.composer.clone();
4255
typist.act(|window, cx| {
4256
composer.update(cx, |composer, cx| {
4257
composer.insert_table(rows, columns, window, cx)
4258
});
4259
window.render_frame(cx);
4260
});
4261
}
4262
4263
#[gpui_kit::test]
4264
fn a_table_takes_tab_grows_a_row_at_the_end_and_sends_as_teams_html(
4265
cx: &mut TestAppContext,
4266
) {
4267
let mut typist = typist(cx);
4268
typist.type_text("before");
4269
insert_table(&mut typist, 1, 2);
4270
typist.type_text("a");
4271
typist.press("tab");
4272
typist.type_text("b");
4273
typist.press("tab");
4274
typist.act(|window, cx| window.render_frame(cx));
4275
typist.type_text("c");
4276
typist.press("down");
4277
typist.type_text("after");
4278
assert_eq!(
4279
typist.outgoing().html(),
4280
"before<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\
4281
<tr><td>a</td><td>b</td></tr><tr><td>c</td><td> </td></tr>\
4282
</tbody></table></figure>after"
4283
);
4284
}
4285
4286
#[gpui_kit::test]
4287
fn deleting_the_last_column_deletes_the_table(cx: &mut TestAppContext) {
4288
let mut typist = typist(cx);
4289
insert_table(&mut typist, 1, 1);
4290
let composer = typist.composer.clone();
4291
typist.act(|window, cx| {
4292
composer.update(cx, |composer, cx| {
4293
composer.edit_table(teams_core::TableEdit::DeleteColumn, window, cx)
4294
});
4295
});
4296
assert!(typist.draft().lines().iter().all(|kind| !kind.is_table()));
4297
}
4298
4299
#[gpui_kit::test]
4300
fn a_pasted_markdown_table_becomes_a_table(cx: &mut TestAppContext) {
4301
let mut typist = typist(cx);
4302
typist
4303
.cx
4304
.write_to_clipboard(gpui_kit::ClipboardItem::new_string(
4305
"| A | B |\n|---|---|\n| 1 | 2 |".to_owned(),
4306
));
4307
typist.press("ctrl-v");
4308
assert!(typist.draft().lines()[0].is_table());
4309
assert_eq!(
4310
typist.outgoing().html(),
4311
"<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\
4312
<tr><td>A</td><td>B</td></tr><tr><td>1</td><td>2</td></tr>\
4313
</tbody></table></figure>"
4314
);
4315
}
4316
4317
#[gpui_kit::test]
4318
fn ctrl_shift_v_pastes_markdown_as_plain_text(cx: &mut TestAppContext) {
4319
let mut typist = typist(cx);
4320
typist
4321
.cx
4322
.write_to_clipboard(gpui_kit::ClipboardItem::new_string(
4323
"**hi** there".to_owned(),
4324
));
4325
typist.press("ctrl-shift-v");
4326
assert_eq!(typist.value(), "**hi** there");
4327
assert!(typist.draft().marks().is_empty());
4328
}
4329
4002
4330
#[gpui_kit::test]
4003
4331
fn demo_upload_runs_to_done_and_a_file_alone_can_be_sent(cx: &mut TestAppContext) {
4004
4332
cx.update(gpui_kit::init);
@@ -13,8 +13,9 @@ use gpui_kit::component::{13
h_flex,13
h_flex,14
input::{14
input::{15
Backspace, Copy, Cut, Delete, Enter, Escape, IndentInline, InlineToken, InputContent,15
Backspace, Copy, Cut, Delete, Enter, Escape, IndentInline, InlineToken, InputContent,16
InputEvent, InputState, MoveDown, MoveUp, OutdentInline, RangeDecorationCollection, Redo,16
InputEvent, InputState, MoveDown, MoveRight, MoveUp, OutdentInline,17
TextDecorationCollection, Textarea, TextareaMode, TextareaState, Undo,17
RangeDecorationCollection, Redo, TextDecorationCollection, Textarea, TextareaMode,18
TextareaState, Undo,18
},19
},19
popover::Popover,20
popover::Popover,20
tooltip::Tooltip,21
tooltip::Tooltip,@@ -24,21 +25,24 @@ use gpui_kit::prelude::FluentBuilder as _;24
use gpui_kit::*;25
use gpui_kit::*;25
use teams_core::{26
use teams_core::{26
Draft, DraftLine, Edit, FileReference, FormatState, LineKind, LinkPreview, MarkKind,27
Draft, DraftLine, Edit, FileReference, FormatState, LineKind, LinkPreview, MarkKind,27
MentionCandidate, MentionInput, OBJECT_MARK, SizeStep, TypingStyle,28
MentionCandidate, MentionInput, OBJECT_MARK, SizeStep, TABLE_MARK, TableEdit, TypingStyle,28
UploadedFile, changed_span, has_markdown, link_url, map_offset, reverse_edits,29
UploadedFile, changed_span, has_markdown, link_url, map_offset, reverse_edits,29
};30
};30
31
31
mod drafts;32
mod drafts;32
mod schedule;33
mod schedule;34
mod table;33
35
34
use super::actions::{36
use super::actions::{35
COMPOSER_KEY_CONTEXT, EditLink, OpenSwitcher, ScheduleSend, ToggleBold, ToggleCode, ToggleItalic,37
COMPOSER_KEY_CONTEXT, DeleteTable, DeleteTableColumn, DeleteTableRow, EditLink,36
ToggleStrike, ToggleSubscript, ToggleSuperscript, ToggleUnderline,38
InsertTableColumnLeft, InsertTableColumnRight, InsertTableRowAbove, InsertTableRowBelow,39
OpenSwitcher, PastePlainText, ScheduleSend, ToggleBold, ToggleCode, ToggleItalic, ToggleStrike,40
ToggleSubscript, ToggleSuperscript, ToggleUnderline,37
};41
};38
use super::attachment_tray::{42
use super::attachment_tray::{39
AttachmentTray, DoneFile, JobKind, LoadedFile, MAX_ATTACHMENTS,43
AttachmentTray, DoneFile, JobKind, LoadedFile, MAX_ATTACHMENTS, PasteAction, UploadJob,40
PasteAction, UploadJob, UploadResult, discard_uploaded, inline_preview, names_of, paste_action,44
UploadResult, discard_uploaded, inline_preview, names_of, paste_action, pasted_image_name,41
pasted_image_name, prepare_pasted_image, read_attachment, render_tray,45
prepare_pasted_image, read_attachment, render_tray,42
};46
};43
use super::avatar::{person_avatar, square_avatar};47
use super::avatar::{person_avatar, square_avatar};44
use super::draft_style::draft_style;48
use super::draft_style::draft_style;@@ -55,6 +59,7 @@ use crate::runtime;55
use crate::scheduled_rows::scheduled_label;59
use crate::scheduled_rows::scheduled_label;56
use crate::theme::{self, ElevatedSurface as _};60
use crate::theme::{self, ElevatedSurface as _};57
use crate::typing::OutgoingTyping;61
use crate::typing::OutgoingTyping;62
use table::{TableKey, TablePicker, TableViews, is_table_token};58
63
59
const MIN_ROWS: usize = 1;64
const MIN_ROWS: usize = 1;60
const MAX_ROWS: usize = 8;65
const MAX_ROWS: usize = 8;@@ -67,6 +72,11 @@ const POPUP_WIDTH: f32 = 380.;67
const POPUP_ROW_HEIGHT: f32 = 44.;72
const POPUP_ROW_HEIGHT: f32 = 44.;68
const DEMO_UPLOAD_STEPS: u8 = 10;73
const DEMO_UPLOAD_STEPS: u8 = 10;69
const COMPOSER_ICON_SIZE: f32 = 20.;74
const COMPOSER_ICON_SIZE: f32 = 20.;75
const COMPOSER_BUTTON_SIZE: f32 = 32.;76
const COMPOSER_BUTTON_INSET: f32 = 6.;77
pub const COMPOSER_BOX_TAG: &str = "composer";78
pub const COMPOSER_LEADING_TAG: &str = "composer/leading";79
pub const COMPOSER_SEND_TAG: &str = "composer/send";70
/// gpui-kit draws a `Size::Size` button's icon at this fraction of the button size.80
/// gpui-kit draws a `Size::Size` button's icon at this fraction of the button size.71
const BUTTON_ICON_SCALE: f32 = 0.75;81
const BUTTON_ICON_SCALE: f32 = 0.75;72
const DEMO_UPLOAD_STEP: Duration = Duration::from_millis(120);82
const DEMO_UPLOAD_STEP: Duration = Duration::from_millis(120);@@ -126,8 +136,19 @@ struct Conversion {126
136
127
#[derive(Debug, Clone, Copy, PartialEq, Eq)]137
#[derive(Debug, Clone, Copy, PartialEq, Eq)]128
enum StepKind {138
enum StepKind {129
Typing { at: usize, after_space: bool },139
Typing {130
Deleting { start: usize, end: usize },140
at: usize,141
after_space: bool,142
},143
Deleting {144
start: usize,145
end: usize,146
},147
CellTyping {148
table: usize,149
row: usize,150
column: usize,151
},131
Other,152
Other,132
}153
}133
154
@@ -192,6 +213,12 @@ pub struct Composer {192
pending_anchors: HashMap<u64, usize>,213
pending_anchors: HashMap<u64, usize>,193
link: ComposeLink,214
link: ComposeLink,194
fun_picker: Entity<FunPicker>,215
fun_picker: Entity<FunPicker>,216
tables: TableViews,217
table_counter: usize,218
table_picker: Option<TablePicker>,219
active_cell: Option<(String, teams_core::Cell)>,220
caret_before_table: usize,221
caret_text: String,195
_subscriptions: [Subscription; 4],222
_subscriptions: [Subscription; 4],196
}223
}197
224
@@ -292,6 +319,9 @@ fn continues(last: &HistoryStep, kind: StepKind) -> bool {292
(StepKind::Deleting { .. }, StepKind::Deleting { start, end }) => {319
(StepKind::Deleting { .. }, StepKind::Deleting { start, end }) => {293
caret.is_empty() && (caret.start == end || caret.start == start)320
caret.is_empty() && (caret.start == end || caret.start == start)294
}321
}322
(previous @ StepKind::CellTyping { .. }, next @ StepKind::CellTyping { .. }) => {323
previous == next324
}295
_ => false,325
_ => false,296
}326
}297
}327
}@@ -328,7 +358,10 @@ impl Composer {328
.placeholder("Type a message")358
.placeholder("Type a message")329
});359
});330
let subscription = cx.subscribe_in(&input, window, Self::on_input_event);360
let subscription = cx.subscribe_in(&input, window, Self::on_input_event);331
let observer = cx.observe(&input, |_, _, cx| cx.notify());361
let observer = cx.observe_in(&input, window, |this, _, window, cx| {362
this.redirect_caret_from_table(window, cx);363
cx.notify();364
});332
let image_observer = cx.observe(&app, |this, _, cx| {365
let image_observer = cx.observe(&app, |this, _, cx| {333
if this.link_image_pending(cx) {366
if this.link_image_pending(cx) {334
cx.notify();367
cx.notify();@@ -389,6 +422,12 @@ impl Composer {389
pending_anchors: HashMap::new(),422
pending_anchors: HashMap::new(),390
link: ComposeLink::default(),423
link: ComposeLink::default(),391
fun_picker,424
fun_picker,425
tables: TableViews::default(),426
table_counter: 0,427
table_picker: None,428
active_cell: None,429
caret_before_table: 0,430
caret_text: String::new(),392
_subscriptions: [subscription, observer, image_observer, picker_subscription],431
_subscriptions: [subscription, observer, image_observer, picker_subscription],393
}432
}394
}433
}@@ -640,6 +679,7 @@ impl Composer {640
}679
}641
self.previous_value = value;680
self.previous_value = value;642
self.refresh_style(cx);681
self.refresh_style(cx);682
self.sync_tables(window, cx);643
}683
}644
684
645
fn shift_anchors(&mut self, start: usize, old_end: usize, new_end: usize) {685
fn shift_anchors(&mut self, start: usize, old_end: usize, new_end: usize) {@@ -737,6 +777,7 @@ impl Composer {737
self.conversion = None;777
self.conversion = None;738
self.paste_hint = None;778
self.paste_hint = None;739
self.refresh_style(cx);779
self.refresh_style(cx);780
self.sync_tables(window, cx);740
self.update_emoji(cx);781
self.update_emoji(cx);741
self.update_mention(cx);782
self.update_mention(cx);742
self.schedule_draft_save(cx);783
self.schedule_draft_save(cx);@@ -775,6 +816,9 @@ impl Composer {775
self.link_editor = None;816
self.link_editor = None;776
self.toolbar_dismissed = None;817
self.toolbar_dismissed = None;777
self.pending_anchors.clear();818
self.pending_anchors.clear();819
self.active_cell = None;820
self.table_picker = None;821
self.sync_tables(window, cx);778
self.history.clear();822
self.history.clear();779
self.history_index = 0;823
self.history_index = 0;780
self.record(StepKind::Other, cx);824
self.record(StepKind::Other, cx);@@ -1064,6 +1108,64 @@ impl Composer {1064
}1108
}1065
}1109
}1066
1110
1111
fn leave_quote(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {1112
let selection = self.selection(cx);1113
if !selection.is_empty() || self.input.read(cx).value().as_ref() != self.draft.text() {1114
return false;1115
}1116
match self.draft.leave_quote_at_end(selection.start) {1117
Some(cursor) => {1118
self.commit(Some(cursor), window, cx);1119
true1120
}1121
None => false,1122
}1123
}1124
1125
/// Backspace right after a table or Delete right before one goes into it instead of1126
/// joining the line with the table's.1127
fn enter_table_beside(1128
&mut self,1129
after: bool,1130
window: &mut Window,1131
cx: &mut Context<Self>,1132
) -> bool {1133
let selection = self.selection(cx);1134
if !selection.is_empty() || self.input.read(cx).value().as_ref() != self.draft.text() {1135
return false;1136
}1137
let found = if after {1138
self.draft.table_before(selection.start)1139
} else {1140
self.draft.table_after(selection.start)1141
};1142
let Some(index) = found else {1143
return false;1144
};1145
self.focus_table_line(index, after, window, cx);1146
true1147
}1148
1149
fn cell_has_focus(&self, window: &Window, cx: &App) -> bool {1150
self.focused_cell(window, cx).is_some()1151
}1152
1153
fn paste_plain(&mut self, window: &mut Window, cx: &mut Context<Self>) {1154
let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) else {1155
return;1156
};1157
let text = text1158
.replace("\r\n", "\n")1159
.replace([OBJECT_MARK, TABLE_MARK], "");1160
if let Some(input) = self.focused_cell_input(window, cx) {1161
input.update(cx, |state, cx| state.replace(text, window, cx));1162
return;1163
}1164
self.pasted_markdown = None;1165
self.input1166
.update(cx, |state, cx| state.replace(text, window, cx));1167
}1168
1067
fn indent(&mut self, outdent: bool, window: &mut Window, cx: &mut Context<Self>) -> bool {1169
fn indent(&mut self, outdent: bool, window: &mut Window, cx: &mut Context<Self>) -> bool {1068
let selection = self.selection(cx);1170
let selection = self.selection(cx);1069
if !self.draft.indent(selection, outdent) {1171
if !self.draft.indent(selection, outdent) {@@ -1079,12 +1181,16 @@ impl Composer {1079
return false;1181
return false;1080
}1182
}1081
let selected = &self.draft.text()[selection.clone()];1183
let selected = &self.draft.text()[selection.clone()];1082
let text = selected.replace(OBJECT_MARK, "");1083
let lines = if selected.contains(OBJECT_MARK) {1184
let lines = if selected.contains(OBJECT_MARK) {1084
self.draft.slice_without_objects(selection)1185
self.draft.slice_without_objects(selection)1085
} else {1186
} else {1086
self.draft.slice(selection)1187
self.draft.slice(selection)1087
};1188
};1189
let text = if selected.contains(TABLE_MARK) {1190
Draft::from_lines(&lines).plain_text()1191
} else {1192
selected.replace(OBJECT_MARK, "")1193
};1088
if text.is_empty() {1194
if text.is_empty() {1089
return true;1195
return true;1090
}1196
}@@ -1150,8 +1256,8 @@ impl Composer {1150
}1256
}1151
let matches = emoji::search(&query, &self.recent_emoji.glyphs(), emoji_popup::LIMIT);1257
let matches = emoji::search(&query, &self.recent_emoji.glyphs(), emoji_popup::LIMIT);1152
let skin_tone = teams_core::skin_tone(&self.app.read(cx).store);1258
let skin_tone = teams_core::skin_tone(&self.app.read(cx).store);1153
self.emoji_popup = (!matches.is_empty())1259
self.emoji_popup =1154
.then(|| EmojiPopup::new(range, query, matches, skin_tone));1260
(!matches.is_empty()).then(|| EmojiPopup::new(range, query, matches, skin_tone));1155
}1261
}1156
1262
1157
fn accept_emoji(&mut self, window: &mut Window, cx: &mut Context<Self>) {1263
fn accept_emoji(&mut self, window: &mut Window, cx: &mut Context<Self>) {@@ -1764,8 +1870,8 @@ impl Composer {1764
let Some(text) = item.text() else {1870
let Some(text) = item.text() else {1765
return false;1871
return false;1766
};1872
};1767
if text.contains(OBJECT_MARK) {1873
if text.contains([OBJECT_MARK, TABLE_MARK]) {1768
let cleaned = text.replace(OBJECT_MARK, "");1874
let cleaned = text.replace([OBJECT_MARK, TABLE_MARK], "");1769
self.input1875
self.input1770
.update(cx, |state, cx| state.replace(cleaned, window, cx));1876
.update(cx, |state, cx| state.replace(cleaned, window, cx));1771
return true;1877
return true;@@ -2397,8 +2503,9 @@ impl Render for Composer {2397
let can_attach = self.editing.is_none();2503
let can_attach = self.editing.is_none();2398
let send = div()2504
let send = div()2399
.id("composer-send")2505
.id("composer-send")2400
.size(px(32.))2506
.debug_selector(|| COMPOSER_SEND_TAG.into())2401
.ml(px(6.))2507
.size(px(COMPOSER_BUTTON_SIZE))2508
.ml(px(COMPOSER_BUTTON_INSET))2402
.flex_none()2509
.flex_none()2403
.flex()2510
.flex()2404
.items_center()2511
.items_center()@@ -2432,7 +2539,7 @@ impl Render for Composer {2432
)2539
)2433
.rounded(px(8.))2540
.rounded(px(8.))2434
.with_size(px(COMPOSER_ICON_SIZE / BUTTON_ICON_SCALE))2541
.with_size(px(COMPOSER_ICON_SIZE / BUTTON_ICON_SCALE))2435
.size(px(32.))2542
.size(px(COMPOSER_BUTTON_SIZE))2436
.tooltip("Emoji, GIFs und Sticker")2543
.tooltip("Emoji, GIFs und Sticker")2437
.icon(symbol("mood", COMPOSER_ICON_SIZE, theme::text_muted())),2544
.icon(symbol("mood", COMPOSER_ICON_SIZE, theme::text_muted())),2438
)2545
)@@ -2450,7 +2557,7 @@ impl Render for Composer {2450
let attach = can_attach.then(|| {2557
let attach = can_attach.then(|| {2451
div()2558
div()2452
.id("composer-attach")2559
.id("composer-attach")2453
.size(px(32.))2560
.size(px(COMPOSER_BUTTON_SIZE))2454
.flex_none()2561
.flex_none()2455
.flex()2562
.flex()2456
.items_center()2563
.items_center()@@ -2466,9 +2573,28 @@ impl Render for Composer {2466
))2573
))2467
.on_click(cx.listener(|this, _, window, cx| this.open_picker(window, cx)))2574
.on_click(cx.listener(|this, _, window, cx| this.open_picker(window, cx)))2468
});2575
});2576
let table_button = can_attach.then(|| {2577
div()2578
.id("composer-table")2579
.size(px(COMPOSER_BUTTON_SIZE))2580
.flex_none()2581
.flex()2582
.items_center()2583
.justify_center()2584
.rounded(px(8.))2585
.cursor_pointer()2586
.hover(|button| button.bg(theme::popup_hover()))2587
.when(self.table_picker.is_some(), |button| {2588
button.bg(theme::popup_hover())2589
})2590
.tooltip(|window, cx| Tooltip::new("Insert table").build(window, cx))2591
.child(symbol("table", COMPOSER_ICON_SIZE, theme::text_muted()))2592
.on_click(cx.listener(|this, _, _, cx| this.open_table_picker(cx)))2593
});2469
let composer = cx.weak_entity();2594
let composer = cx.weak_entity();2470
let tokens_composer = composer.clone();2595
let tokens_composer = composer.clone();2471
let input = Textarea::new(&self.input)2596
let input = Textarea::new(&self.input)2597
.line_box_height(px(COMPOSER_BUTTON_SIZE))2472
.appearance(false)2598
.appearance(false)2473
.bordered(false)2599
.bordered(false)2474
.on_paste(move |item, window, cx| {2600
.on_paste(move |item, window, cx| {@@ -2477,6 +2603,17 @@ impl Render for Composer {2477
.unwrap_or(false)2603
.unwrap_or(false)2478
})2604
})2479
.token(move |context, _, cx| {2605
.token(move |context, _, cx| {2606
if context.is_block() && is_table_token(context.token()) {2607
let token_id = context.token().id().to_string();2608
let width = context.available_width();2609
if let Some(table) = tokens_composer2610
.read_with(cx, |this, _| this.render_table_token(&token_id, width))2611
.ok()2612
.flatten()2613
{2614
return table;2615
}2616
}2480
if let Some(id) = context2617
if let Some(id) = context2481
.is_block()2618
.is_block()2482
.then(|| image_id(context.token()))2619
.then(|| image_id(context.token()))@@ -2550,42 +2687,70 @@ impl Render for Composer {2550
.pt(px(top))2687
.pt(px(top))2551
.pb(px(bottom))2688
.pb(px(bottom))2552
.key_context(COMPOSER_KEY_CONTEXT)2689
.key_context(COMPOSER_KEY_CONTEXT)2553
.on_action(cx.listener(|this, _: &ToggleBold, _, cx| {2690
.on_action(cx.listener(|this, _: &ToggleBold, window, cx| {2554
if this.link_editor.is_none() {2691
if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {2555
this.toggle_mark(MarkKind::Bold, cx);2692
this.toggle_mark(MarkKind::Bold, cx);2556
}2693
}2557
}))2694
}))2558
.on_action(cx.listener(|this, _: &ToggleItalic, _, cx| {2695
.on_action(cx.listener(|this, _: &ToggleItalic, window, cx| {2559
if this.link_editor.is_none() {2696
if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {2560
this.toggle_mark(MarkKind::Italic, cx);2697
this.toggle_mark(MarkKind::Italic, cx);2561
}2698
}2562
}))2699
}))2563
.on_action(cx.listener(|this, _: &ToggleUnderline, _, cx| {2700
.on_action(cx.listener(|this, _: &ToggleUnderline, window, cx| {2564
if this.link_editor.is_none() {2701
if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {2565
this.toggle_mark(MarkKind::Underline, cx);2702
this.toggle_mark(MarkKind::Underline, cx);2566
}2703
}2567
}))2704
}))2568
.on_action(cx.listener(|this, _: &ToggleStrike, _, cx| {2705
.on_action(cx.listener(|this, _: &ToggleStrike, window, cx| {2569
if this.link_editor.is_none() {2706
if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {2570
this.toggle_mark(MarkKind::Strike, cx);2707
this.toggle_mark(MarkKind::Strike, cx);2571
}2708
}2572
}))2709
}))2573
.on_action(cx.listener(|this, _: &ToggleSuperscript, _, cx| {2710
.on_action(cx.listener(|this, _: &ToggleSuperscript, window, cx| {2574
if this.link_editor.is_none() {2711
if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {2575
this.toggle_mark(MarkKind::Superscript, cx);2712
this.toggle_mark(MarkKind::Superscript, cx);2576
}2713
}2577
}))2714
}))2578
.on_action(cx.listener(|this, _: &ToggleSubscript, _, cx| {2715
.on_action(cx.listener(|this, _: &ToggleSubscript, window, cx| {2579
if this.link_editor.is_none() {2716
if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {2580
this.toggle_mark(MarkKind::Subscript, cx);2717
this.toggle_mark(MarkKind::Subscript, cx);2581
}2718
}2582
}))2719
}))2583
.on_action(cx.listener(|this, _: &ToggleCode, _, cx| {2720
.on_action(cx.listener(|this, _: &ToggleCode, window, cx| {2584
if this.link_editor.is_none() {2721
if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {2585
this.toggle_mark(MarkKind::Code, cx);2722
this.toggle_mark(MarkKind::Code, cx);2586
}2723
}2587
}))2724
}))2588
.on_action(cx.listener(|this, _: &EditLink, window, cx| this.edit_link(window, cx)))2725
.on_action(cx.listener(|this, _: &EditLink, window, cx| {2726
if !this.cell_has_focus(window, cx) {2727
this.edit_link(window, cx);2728
}2729
}))2730
.on_action(2731
cx.listener(|this, _: &PastePlainText, window, cx| this.paste_plain(window, cx)),2732
)2733
.on_action(cx.listener(|this, _: &InsertTableRowAbove, window, cx| {2734
this.edit_table(TableEdit::InsertRowAbove, window, cx)2735
}))2736
.on_action(cx.listener(|this, _: &InsertTableRowBelow, window, cx| {2737
this.edit_table(TableEdit::InsertRowBelow, window, cx)2738
}))2739
.on_action(cx.listener(|this, _: &InsertTableColumnLeft, window, cx| {2740
this.edit_table(TableEdit::InsertColumnLeft, window, cx)2741
}))2742
.on_action(cx.listener(|this, _: &InsertTableColumnRight, window, cx| {2743
this.edit_table(TableEdit::InsertColumnRight, window, cx)2744
}))2745
.on_action(cx.listener(|this, _: &DeleteTableRow, window, cx| {2746
this.edit_table(TableEdit::DeleteRow, window, cx)2747
}))2748
.on_action(cx.listener(|this, _: &DeleteTableColumn, window, cx| {2749
this.edit_table(TableEdit::DeleteColumn, window, cx)2750
}))2751
.on_action(cx.listener(|this, _: &DeleteTable, window, cx| {2752
this.edit_table(TableEdit::DeleteTable, window, cx)2753
}))2589
.on_action(cx.listener(|this, _: &ScheduleSend, _, cx| this.open_schedule_picker(cx)))2754
.on_action(cx.listener(|this, _: &ScheduleSend, _, cx| this.open_schedule_picker(cx)))2590
.capture_action(cx.listener(|this, _: &Undo, window, cx| {2755
.capture_action(cx.listener(|this, _: &Undo, window, cx| {2591
if this.link_editor.is_none() {2756
if this.link_editor.is_none() {@@ -2599,20 +2764,30 @@ impl Render for Composer {2599
cx.stop_propagation();2764
cx.stop_propagation();2600
}2765
}2601
}))2766
}))2602
.capture_action(cx.listener(|this, _: &Copy, _, cx| {2767
.capture_action(cx.listener(|this, _: &Copy, window, cx| {2603
if this.link_editor.is_none() && this.copy_selection(cx) {2768
if this.link_editor.is_none()2769
&& !this.cell_has_focus(window, cx)2770
&& this.copy_selection(cx)2771
{2604
cx.stop_propagation();2772
cx.stop_propagation();2605
}2773
}2606
}))2774
}))2607
.capture_action(cx.listener(|this, _: &Cut, window, cx| {2775
.capture_action(cx.listener(|this, _: &Cut, window, cx| {2608
if this.link_editor.is_none() && this.copy_selection(cx) {2776
if this.link_editor.is_none()2777
&& !this.cell_has_focus(window, cx)2778
&& this.copy_selection(cx)2779
{2609
this.input2780
this.input2610
.update(cx, |state, cx| state.replace("", window, cx));2781
.update(cx, |state, cx| state.replace("", window, cx));2611
cx.stop_propagation();2782
cx.stop_propagation();2612
}2783
}2613
}))2784
}))2614
.capture_action(cx.listener(|this, _: &MoveUp, window, cx| {2785
.capture_action(cx.listener(|this, _: &MoveUp, window, cx| {2615
if this.link_editor.is_some() {2786
if this.cell_has_focus(window, cx) {2787
if this.table_key(TableKey::Up, window, cx) {2788
cx.stop_propagation();2789
}2790
} else if this.link_editor.is_some() {2616
} else if this.schedule.is_some() {2791
} else if this.schedule.is_some() {2617
this.move_schedule_highlight(-1, window, cx);2792
this.move_schedule_highlight(-1, window, cx);2618
cx.stop_propagation();2793
cx.stop_propagation();@@ -2625,17 +2800,32 @@ impl Render for Composer {2625
}2800
}2626
}))2801
}))2627
.capture_action(cx.listener(|this, _: &MoveDown, window, cx| {2802
.capture_action(cx.listener(|this, _: &MoveDown, window, cx| {2628
if this.link_editor.is_some() {2803
if this.cell_has_focus(window, cx) {2804
if this.table_key(TableKey::Down, window, cx) {2805
cx.stop_propagation();2806
}2807
} else if this.link_editor.is_some() {2629
} else if this.schedule.is_some() {2808
} else if this.schedule.is_some() {2630
this.move_schedule_highlight(1, window, cx);2809
this.move_schedule_highlight(1, window, cx);2631
cx.stop_propagation();2810
cx.stop_propagation();2632
} else if this.popup_is_open() {2811
} else if this.popup_is_open() {2633
this.move_highlight(1, cx);2812
this.move_highlight(1, cx);2634
cx.stop_propagation();2813
cx.stop_propagation();2814
} else if this.leave_quote(window, cx) {2815
cx.stop_propagation();2816
}2817
}))2818
.capture_action(cx.listener(|this, _: &MoveRight, window, cx| {2819
if this.link_editor.is_none()2820
&& !this.cell_has_focus(window, cx)2821
&& this.leave_quote(window, cx)2822
{2823
cx.stop_propagation();2635
}2824
}2636
}))2825
}))2637
.capture_action(cx.listener(|this, action: &Enter, window, cx| {2826
.capture_action(cx.listener(|this, action: &Enter, window, cx| {2638
if this.link_editor.is_some() {2827
if this.cell_has_focus(window, cx) {2828
} else if this.link_editor.is_some() {2639
this.apply_link(window, cx);2829
this.apply_link(window, cx);2640
cx.stop_propagation();2830
cx.stop_propagation();2641
} else if this.schedule.is_some() {2831
} else if this.schedule.is_some() {@@ -2649,7 +2839,9 @@ impl Render for Composer {2649
}2839
}2650
}))2840
}))2651
.capture_action(cx.listener(|this, _: &IndentInline, window, cx| {2841
.capture_action(cx.listener(|this, _: &IndentInline, window, cx| {2652
if this.link_editor.is_some() {2842
if this.table_key(TableKey::Next, window, cx) {2843
cx.stop_propagation();2844
} else if this.link_editor.is_some() {2653
} else if this.popup_is_open() {2845
} else if this.popup_is_open() {2654
this.accept_popup(window, cx);2846
this.accept_popup(window, cx);2655
cx.stop_propagation();2847
cx.stop_propagation();@@ -2658,23 +2850,37 @@ impl Render for Composer {2658
}2850
}2659
}))2851
}))2660
.capture_action(cx.listener(|this, _: &OutdentInline, window, cx| {2852
.capture_action(cx.listener(|this, _: &OutdentInline, window, cx| {2661
if this.link_editor.is_none() && this.indent(true, window, cx) {2853
if this.table_key(TableKey::Previous, window, cx)2854
|| (this.link_editor.is_none() && this.indent(true, window, cx))2855
{2662
cx.stop_propagation();2856
cx.stop_propagation();2663
}2857
}2664
}))2858
}))2665
.capture_action(cx.listener(|this, _: &Backspace, window, cx| {2859
.capture_action(cx.listener(|this, _: &Backspace, window, cx| {2666
if this.link_editor.is_none()2860
if this.link_editor.is_none()2667
&& (this.undo_conversion(window, cx) || this.backspace_at_start(window, cx))2861
&& !this.cell_has_focus(window, cx)2862
&& (this.undo_conversion(window, cx)2863
|| this.backspace_at_start(window, cx)2864
|| this.enter_table_beside(true, window, cx))2668
{2865
{2669
cx.stop_propagation();2866
cx.stop_propagation();2670
}2867
}2671
}))2868
}))2672
.capture_action(cx.listener(|this, _: &Delete, window, cx| {2869
.capture_action(cx.listener(|this, _: &Delete, window, cx| {2673
if this.link_editor.is_none() && this.delete_forward(window, cx) {2870
if this.link_editor.is_none()2871
&& !this.cell_has_focus(window, cx)2872
&& (this.enter_table_beside(false, window, cx)2873
|| this.delete_forward(window, cx))2874
{2674
cx.stop_propagation();2875
cx.stop_propagation();2675
}2876
}2676
}))2877
}))2677
.capture_action(cx.listener(|this, _: &Escape, window, cx| {2878
.capture_action(cx.listener(|this, _: &Escape, window, cx| {2879
if this.table_picker.take().is_some() {2880
cx.notify();2881
cx.stop_propagation();2882
return;2883
}2678
if this.schedule.is_some() {2884
if this.schedule.is_some() {2679
this.close_schedule(window, cx);2885
this.close_schedule(window, cx);2680
cx.stop_propagation();2886
cx.stop_propagation();@@ -2716,8 +2922,10 @@ impl Render for Composer {2716
.children(self.render_emoji_popup(window, cx))2922
.children(self.render_emoji_popup(window, cx))2717
.children(self.render_toolbar(focused, cx))2923
.children(self.render_toolbar(focused, cx))2718
.children(self.render_schedule(cx))2924
.children(self.render_schedule(cx))2925
.children(self.render_table_picker(cx))2719
.child(2926
.child(2720
v_flex()2927
v_flex()2928
.debug_selector(|| COMPOSER_BOX_TAG.into())2721
.relative()2929
.relative()2722
.w_full()2930
.w_full()2723
.rounded(px(12.))2931
.rounded(px(12.))@@ -2747,16 +2955,22 @@ impl Render for Composer {2747
row.items_end()2955
row.items_end()2748
}2956
}2749
})2957
})2750
.py(px(6.))2958
.py(px(COMPOSER_BUTTON_INSET))2751
.pl(px(if can_attach { 6. } else { 12. }))2959
.pl(px(if can_attach {2752
.pr(px(6.))2960
COMPOSER_BUTTON_INSET2961
} else {2962
12.2963
}))2964
.pr(px(COMPOSER_BUTTON_INSET))2753
.when(can_attach, |row| {2965
.when(can_attach, |row| {2754
row.child(2966
row.child(2755
h_flex()2967
h_flex()2968
.debug_selector(|| COMPOSER_LEADING_TAG.into())2756
.flex_none()2969
.flex_none()2757
.gap(px(6.))2970
.gap(px(COMPOSER_BUTTON_INSET))2758
.children(fun)2971
.children(fun)2759
.children(attach),2972
.children(attach)2973
.children(table_button),2760
)2974
)2761
})2975
})2762
.child(2976
.child(@@ -2926,7 +3140,10 @@ mod tests {2926
})3140
})2927
}3141
}2928
3142
2929
fn outgoing_with(text: &str, images: Vec<crate::outgoing::OutgoingImage>) -> crate::outgoing::Outgoing {3143
fn outgoing_with(3144
text: &str,3145
images: Vec<crate::outgoing::OutgoingImage>,3146
) -> crate::outgoing::Outgoing {2930
crate::outgoing::Outgoing {3147
crate::outgoing::Outgoing {2931
draft: teams_core::Draft::plain(text),3148
draft: teams_core::Draft::plain(text),2932
subject: None,3149
subject: None,@@ -2984,7 +3201,10 @@ mod tests {2984
#[test]3201
#[test]2985
fn a_sticker_carries_the_sticker_itemtype() {3202
fn a_sticker_carries_the_sticker_itemtype() {2986
let sticker = super::RemoteImage::sticker(crate::stickers::popular()[0]);3203
let sticker = super::RemoteImage::sticker(crate::stickers::popular()[0]);2987
let outgoing = outgoing_with("\u{FFFC}", vec![crate::outgoing::OutgoingImage::Remote(sticker)]);3204
let outgoing = outgoing_with(3205
"\u{FFFC}",3206
vec![crate::outgoing::OutgoingImage::Remote(sticker)],3207
);2988
assert!(3208
assert!(2989
outgoing3209
outgoing2990
.html()3210
.html()@@ -3395,7 +3615,9 @@ mod tests {3395
excerpt: "question".into(),3615
excerpt: "question".into(),3396
};3616
};3397
typist.act(|_, cx| {3617
typist.act(|_, cx| {3398
composer.update(cx, |composer, cx| composer.set_reply(Some(reply.clone()), cx));3618
composer.update(cx, |composer, cx| {3619
composer.set_reply(Some(reply.clone()), cx)3620
});3399
});3621
});3400
load(&mut typist, &entry);3622
load(&mut typist, &entry);3401
let tokens = image_tokens(&mut typist);3623
let tokens = image_tokens(&mut typist);@@ -3991,7 +4213,7 @@ mod tests {3991
#[gpui_kit::test]4213
#[gpui_kit::test]3992
fn quotes_continue_on_shift_enter_and_send_as_blockquote(cx: &mut TestAppContext) {4214
fn quotes_continue_on_shift_enter_and_send_as_blockquote(cx: &mut TestAppContext) {3993
let mut typist = typist(cx);4215
let mut typist = typist(cx);3994
typist.type_text("> quoted");4216
typist.type_text(">quoted");3995
typist.press("shift-enter");4217
typist.press("shift-enter");3996
typist.type_text("more");4218
typist.type_text("more");3997
let outgoing = typist.outgoing();4219
let outgoing = typist.outgoing();@@ -3999,6 +4221,112 @@ mod tests {3999
assert_eq!(outgoing.text(), "quoted\nmore");4221
assert_eq!(outgoing.text(), "quoted\nmore");4000
}4222
}4001
4223
4224
#[gpui_kit::test]4225
fn enter_in_a_quote_adds_a_line_and_enter_on_the_empty_one_leaves_it(4226
cx: &mut TestAppContext,4227
) {4228
let mut typist = typist(cx);4229
typist.type_text(">quoted");4230
typist.press("enter");4231
typist.type_text("more");4232
typist.press("enter enter");4233
typist.type_text("after");4234
assert_eq!(typist.value(), "quoted\nmore\nafter");4235
assert_eq!(4236
typist.outgoing().html(),4237
"<blockquote>quoted<br>more</blockquote>after"4238
);4239
}4240
4241
#[gpui_kit::test]4242
fn down_at_the_end_of_a_quote_leaves_it(cx: &mut TestAppContext) {4243
let mut typist = typist(cx);4244
typist.type_text(">quoted");4245
typist.press("down");4246
typist.type_text("after");4247
assert_eq!(4248
typist.outgoing().html(),4249
"<blockquote>quoted</blockquote>after"4250
);4251
}4252
4253
fn insert_table(typist: &mut Typist<'_>, rows: usize, columns: usize) {4254
let composer = typist.composer.clone();4255
typist.act(|window, cx| {4256
composer.update(cx, |composer, cx| {4257
composer.insert_table(rows, columns, window, cx)4258
});4259
window.render_frame(cx);4260
});4261
}4262
4263
#[gpui_kit::test]4264
fn a_table_takes_tab_grows_a_row_at_the_end_and_sends_as_teams_html(4265
cx: &mut TestAppContext,4266
) {4267
let mut typist = typist(cx);4268
typist.type_text("before");4269
insert_table(&mut typist, 1, 2);4270
typist.type_text("a");4271
typist.press("tab");4272
typist.type_text("b");4273
typist.press("tab");4274
typist.act(|window, cx| window.render_frame(cx));4275
typist.type_text("c");4276
typist.press("down");4277
typist.type_text("after");4278
assert_eq!(4279
typist.outgoing().html(),4280
"before<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\4281
<tr><td>a</td><td>b</td></tr><tr><td>c</td><td> </td></tr>\4282
</tbody></table></figure>after"4283
);4284
}4285
4286
#[gpui_kit::test]4287
fn deleting_the_last_column_deletes_the_table(cx: &mut TestAppContext) {4288
let mut typist = typist(cx);4289
insert_table(&mut typist, 1, 1);4290
let composer = typist.composer.clone();4291
typist.act(|window, cx| {4292
composer.update(cx, |composer, cx| {4293
composer.edit_table(teams_core::TableEdit::DeleteColumn, window, cx)4294
});4295
});4296
assert!(typist.draft().lines().iter().all(|kind| !kind.is_table()));4297
}4298
4299
#[gpui_kit::test]4300
fn a_pasted_markdown_table_becomes_a_table(cx: &mut TestAppContext) {4301
let mut typist = typist(cx);4302
typist4303
.cx4304
.write_to_clipboard(gpui_kit::ClipboardItem::new_string(4305
"| A | B |\n|---|---|\n| 1 | 2 |".to_owned(),4306
));4307
typist.press("ctrl-v");4308
assert!(typist.draft().lines()[0].is_table());4309
assert_eq!(4310
typist.outgoing().html(),4311
"<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\4312
<tr><td>A</td><td>B</td></tr><tr><td>1</td><td>2</td></tr>\4313
</tbody></table></figure>"4314
);4315
}4316
4317
#[gpui_kit::test]4318
fn ctrl_shift_v_pastes_markdown_as_plain_text(cx: &mut TestAppContext) {4319
let mut typist = typist(cx);4320
typist4321
.cx4322
.write_to_clipboard(gpui_kit::ClipboardItem::new_string(4323
"**hi** there".to_owned(),4324
));4325
typist.press("ctrl-shift-v");4326
assert_eq!(typist.value(), "**hi** there");4327
assert!(typist.draft().marks().is_empty());4328
}4329
4002
#[gpui_kit::test]4330
#[gpui_kit::test]4003
fn demo_upload_runs_to_done_and_a_file_alone_can_be_sent(cx: &mut TestAppContext) {4331
fn demo_upload_runs_to_done_and_a_file_alone_can_be_sent(cx: &mut TestAppContext) {4004
cx.update(gpui_kit::init);4332
cx.update(gpui_kit::init);@@ -0,0 +1,630 @@
1
use std::collections::HashMap;
2
use std::ops::Range;
3
4
use gpui_kit::component::input::{
5
Copy, Cut, InlineToken, InputEvent, Paste, Textarea, TextareaState,
6
};
7
use gpui_kit::component::native_menu::NativeMenu;
8
use gpui_kit::component::{Sizable as _, h_flex, v_flex};
9
use gpui_kit::*;
10
use teams_core::{Cell, PICKER_COLUMNS, PICKER_ROWS, TABLE_MARK, Table, TableEdit};
11
12
use super::{Composer, StepKind};
13
use crate::theme::{self, ElevatedSurface as _};
14
use crate::views::actions::{
15
DeleteTable, DeleteTableColumn, DeleteTableRow, InsertTableColumnLeft, InsertTableColumnRight,
16
InsertTableRowAbove, InsertTableRowBelow,
17
};
18
19
pub(super) const TOKEN_PREFIX: &str = "table-";
20
const CELL_MAX_ROWS: usize = 12;
21
const PICKER_SQUARE: f32 = 16.;
22
const PICKER_GAP: f32 = 3.;
23
const TABLE_MARGIN: f32 = 4.;
24
const CELL_PADDING_X: f32 = 2.;
25
const CELL_PADDING_Y: f32 = 3.;
26
27
pub(super) struct TableView {
28
cells: Vec<Vec<Entity<TextareaState>>>,
29
_subscriptions: Vec<Subscription>,
30
}
31
32
impl TableView {
33
fn shape(&self) -> (usize, usize) {
34
(self.cells.len(), self.cells.first().map_or(0, Vec::len))
35
}
36
}
37
38
/// The rows and columns the pointer covers in the size picker.
39
pub(super) struct TablePicker {
40
rows: usize,
41
columns: usize,
42
}
43
44
pub(super) fn token(number: usize) -> InlineToken {
45
InlineToken::new(format!("{TOKEN_PREFIX}{number}"), TABLE_MARK.to_string()).block()
46
}
47
48
pub(super) fn is_table_token(token: &InlineToken) -> bool {
49
token.id().starts_with(TOKEN_PREFIX)
50
}
51
52
fn token_number(id: &str) -> usize {
53
id.strip_prefix(TOKEN_PREFIX)
54
.and_then(|number| number.parse().ok())
55
.unwrap_or_default()
56
}
57
58
fn caret_on_first_line(state: &TextareaState) -> bool {
59
!state.value()[..state.cursor()].contains('\n')
60
}
61
62
fn caret_on_last_line(state: &TextareaState) -> bool {
63
!state.value()[state.cursor()..].contains('\n')
64
}
65
66
impl Composer {
67
fn table_tokens(&self, cx: &App) -> Vec<(Range<usize>, String)> {
68
self.input
69
.read(cx)
70
.tokens()
71
.iter()
72
.filter(|span| is_table_token(span.token()))
73
.map(|span| (span.range(), span.token().id().to_string()))
74
.collect()
75
}
76
77
fn table_line(&self, token_id: &str, cx: &App) -> Option<usize> {
78
let (range, _) = self
79
.table_tokens(cx)
80
.into_iter()
81
.find(|(_, id)| id == token_id)?;
82
let index = self.draft.line_at(range.start);
83
self.draft.table(index).is_some().then_some(index)
84
}
85
86
/// Every table line gets its token and cell inputs; inputs follow the draft's cells.
87
pub(super) fn sync_tables(&mut self, window: &mut Window, cx: &mut Context<Self>) {
88
if self.input.read(cx).value().as_ref() != self.draft.text() {
89
return;
90
}
91
let ranges = self.draft.line_ranges();
92
let tokens = self.table_tokens(cx);
93
for (index, line) in ranges.iter().enumerate() {
94
if self.draft.table(index).is_none() || tokens.iter().any(|(range, _)| range == line) {
95
continue;
96
}
97
self.table_counter += 1;
98
let token = token(self.table_counter);
99
self.input.update(cx, |state, cx| {
100
let selection = state.selected_range();
101
if state
102
.replace_range_with_token(line.clone(), token, window, cx)
103
.is_ok()
104
{
105
state.set_selected_range(selection, cx);
106
}
107
});
108
}
109
let tokens = self.table_tokens(cx);
110
self.tables
111
.retain(|id, _| tokens.iter().any(|(_, token_id)| token_id == id));
112
for (range, id) in tokens {
113
let Some(table) = self.draft.table(self.draft.line_at(range.start)).cloned() else {
114
continue;
115
};
116
self.sync_table_view(&id, &table, window, cx);
117
}
118
}
119
120
fn sync_table_view(
121
&mut self,
122
token_id: &str,
123
table: &Table,
124
window: &mut Window,
125
cx: &mut Context<Self>,
126
) {
127
let shape = (table.row_count(), table.column_count());
128
if self
129
.tables
130
.get(token_id)
131
.is_some_and(|view| view.shape() == shape)
132
{
133
let cells = self.tables[token_id].cells.clone();
134
for (row, inputs) in cells.iter().enumerate() {
135
for (column, input) in inputs.iter().enumerate() {
136
let text = table.cell(Cell::new(row, column)).unwrap_or_default();
137
if input.read(cx).value().as_ref() != text {
138
let text = text.to_owned();
139
input.update(cx, |state, cx| state.set_value(text, window, cx));
140
}
141
}
142
}
143
return;
144
}
145
let mut subscriptions = Vec::new();
146
let cells = table
147
.rows
148
.iter()
149
.enumerate()
150
.map(|(row, texts)| {
151
texts
152
.iter()
153
.enumerate()
154
.map(|(column, text)| {
155
let text = text.clone();
156
let input = cx.new(|cx| {
157
TextareaState::new(window, cx)
158
.auto_grow(1, CELL_MAX_ROWS)
159
.default_value(text)
160
});
161
let id = token_id.to_owned();
162
let cell = Cell::new(row, column);
163
subscriptions.push(cx.subscribe_in(
164
&input,
165
window,
166
move |this, _, event: &InputEvent, window, cx| {
167
this.on_cell_event(&id, cell, event, window, cx)
168
},
169
));
170
input
171
})
172
.collect()
173
})
174
.collect();
175
self.tables.insert(
176
token_id.to_owned(),
177
TableView {
178
cells,
179
_subscriptions: subscriptions,
180
},
181
);
182
}
183
184
fn on_cell_event(
185
&mut self,
186
token_id: &str,
187
cell: Cell,
188
event: &InputEvent,
189
_: &mut Window,
190
cx: &mut Context<Self>,
191
) {
192
match event {
193
InputEvent::Focus => {
194
self.active_cell = Some((token_id.to_owned(), cell));
195
self.table_picker = None;
196
}
197
InputEvent::Change => {
198
let Some(index) = self.table_line(token_id, cx) else {
199
return;
200
};
201
let Some(input) = self.cell_input(token_id, cell) else {
202
return;
203
};
204
let text = input.read(cx).value().to_string();
205
let Some(mut table) = self.draft.table(index).cloned() else {
206
return;
207
};
208
if table.cell(cell) == Some(text.as_str()) {
209
return;
210
}
211
table.set_cell(cell, &text);
212
self.draft.set_table(index, table);
213
self.record(
214
StepKind::CellTyping {
215
table: token_number(token_id),
216
row: cell.row,
217
column: cell.column,
218
},
219
cx,
220
);
221
self.schedule_draft_save(cx);
222
}
223
_ => {}
224
}
225
cx.notify();
226
}
227
228
fn cell_input(&self, token_id: &str, cell: Cell) -> Option<Entity<TextareaState>> {
229
self.tables
230
.get(token_id)?
231
.cells
232
.get(cell.row)?
233
.get(cell.column)
234
.cloned()
235
}
236
237
pub(super) fn focused_cell_input(
238
&self,
239
window: &Window,
240
cx: &App,
241
) -> Option<Entity<TextareaState>> {
242
let (token_id, cell) = self.focused_cell(window, cx)?;
243
self.cell_input(&token_id, cell)
244
}
245
246
/// The cell that has the keyboard, if any.
247
pub(super) fn focused_cell(&self, window: &Window, cx: &App) -> Option<(String, Cell)> {
248
self.tables.iter().find_map(|(id, view)| {
249
view.cells.iter().enumerate().find_map(|(row, inputs)| {
250
inputs.iter().enumerate().find_map(|(column, input)| {
251
input
252
.focus_handle(cx)
253
.is_focused(window)
254
.then(|| (id.clone(), Cell::new(row, column)))
255
})
256
})
257
})
258
}
259
260
pub(super) fn focus_cell(
261
&mut self,
262
token_id: &str,
263
cell: Cell,
264
window: &mut Window,
265
cx: &mut Context<Self>,
266
) {
267
let Some(input) = self.cell_input(token_id, cell) else {
268
return;
269
};
270
input.update(cx, |state, cx| {
271
let end = state.value().len();
272
state.focus(window, cx);
273
state.set_selected_range(end..end, cx);
274
});
275
self.active_cell = Some((token_id.to_owned(), cell));
276
cx.notify();
277
}
278
279
fn token_at_line(&self, index: usize, cx: &App) -> Option<String> {
280
let line = self.draft.line_ranges().get(index)?.clone();
281
self.table_tokens(cx)
282
.into_iter()
283
.find(|(range, _)| *range == line)
284
.map(|(_, id)| id)
285
}
286
287
pub(super) fn focus_table_line(
288
&mut self,
289
index: usize,
290
last: bool,
291
window: &mut Window,
292
cx: &mut Context<Self>,
293
) {
294
let Some(token_id) = self.token_at_line(index, cx) else {
295
return;
296
};
297
let Some(table) = self.draft.table(index) else {
298
return;
299
};
300
let cell = if last {
301
table.last_cell()
302
} else {
303
Cell::new(0, 0)
304
};
305
self.focus_cell(&token_id, cell, window, cx);
306
}
307
308
pub(super) fn insert_table(
309
&mut self,
310
rows: usize,
311
columns: usize,
312
window: &mut Window,
313
cx: &mut Context<Self>,
314
) {
315
self.table_picker = None;
316
let cursor = match self.focused_cell(window, cx) {
317
Some((token_id, _)) => self
318
.table_line(&token_id, cx)
319
.map_or(self.selection(cx).end, |index| {
320
self.draft.line_ranges()[index].end
321
}),
322
None => self.selection(cx).end,
323
};
324
let index = self.draft.insert_table(cursor, Table::new(rows, columns));
325
let after = self.draft.line_ranges()[index].end;
326
self.commit(Some(after), window, cx);
327
self.focus_table_line(index, false, window, cx);
328
}
329
330
fn leave_table(
331
&mut self,
332
token_id: &str,
333
below: bool,
334
window: &mut Window,
335
cx: &mut Context<Self>,
336
) {
337
let Some(index) = self.table_line(token_id, cx) else {
338
return;
339
};
340
let cursor = self.draft.line_beside_table(index, below);
341
self.active_cell = None;
342
self.focus(window, cx);
343
self.commit(Some(cursor), window, cx);
344
}
345
346
/// Tab, Shift+Tab, Up and Down while a cell has the keyboard. `false` leaves the key to
347
/// the cell.
348
pub(super) fn table_key(
349
&mut self,
350
key: TableKey,
351
window: &mut Window,
352
cx: &mut Context<Self>,
353
) -> bool {
354
let Some((token_id, cell)) = self.focused_cell(window, cx) else {
355
return false;
356
};
357
let Some(index) = self.table_line(&token_id, cx) else {
358
return false;
359
};
360
let Some(mut table) = self.draft.table(index).cloned() else {
361
return false;
362
};
363
let Some(input) = self.cell_input(&token_id, cell) else {
364
return false;
365
};
366
let target = match key {
367
TableKey::Next => {
368
let (next, added_row) = table.next_cell(cell);
369
if added_row {
370
self.draft.set_table(index, table);
371
self.record(StepKind::Other, cx);
372
self.sync_tables(window, cx);
373
self.schedule_draft_save(cx);
374
}
375
next
376
}
377
TableKey::Previous => table.previous_cell(cell),
378
TableKey::Down if !caret_on_last_line(input.read(cx)) => return false,
379
TableKey::Up if !caret_on_first_line(input.read(cx)) => return false,
380
TableKey::Down if cell.row + 1 == table.row_count() => {
381
self.leave_table(&token_id, true, window, cx);
382
return true;
383
}
384
TableKey::Up if cell.row == 0 => {
385
self.leave_table(&token_id, false, window, cx);
386
return true;
387
}
388
TableKey::Down => Cell::new(cell.row + 1, cell.column),
389
TableKey::Up => Cell::new(cell.row - 1, cell.column),
390
};
391
self.focus_cell(&token_id, target, window, cx);
392
true
393
}
394
395
pub(super) fn edit_table(
396
&mut self,
397
edit: TableEdit,
398
window: &mut Window,
399
cx: &mut Context<Self>,
400
) {
401
let Some((token_id, cell)) = self
402
.focused_cell(window, cx)
403
.or_else(|| self.active_cell.clone())
404
else {
405
return;
406
};
407
let Some(index) = self.table_line(&token_id, cx) else {
408
return;
409
};
410
let Some(mut table) = self.draft.table(index).cloned() else {
411
return;
412
};
413
match table.apply(edit, cell) {
414
Some(target) => {
415
self.draft.set_table(index, table);
416
self.record(StepKind::Other, cx);
417
self.sync_tables(window, cx);
418
self.schedule_draft_save(cx);
419
self.focus_cell(&token_id, target, window, cx);
420
}
421
None => {
422
let cursor = self.draft.remove_table(index);
423
self.active_cell = None;
424
self.focus(window, cx);
425
self.commit(Some(cursor), window, cx);
426
}
427
}
428
cx.notify();
429
}
430
431
/// The caret never rests on a table's line: coming from above it enters the first
432
/// cell, from below the first cell of the last row. Only a move without an edit
433
/// counts, so a paste that passes the table on its way does not enter it.
434
pub(super) fn redirect_caret_from_table(
435
&mut self,
436
window: &mut Window,
437
cx: &mut Context<Self>,
438
) {
439
let state = self.input.read(cx);
440
let selection = state.selected_range();
441
let focused = state.focus_handle(cx).is_focused(window);
442
let value = state.value();
443
if value.as_ref() != self.caret_text {
444
self.caret_text = value.to_string();
445
self.caret_before_table = selection.start;
446
return;
447
}
448
if !focused || !selection.is_empty() || value.as_ref() != self.draft.text() {
449
return;
450
}
451
let Some(index) = self.draft.table_at(selection.start) else {
452
self.caret_before_table = selection.start;
453
return;
454
};
455
let line = self.draft.line_ranges()[index].clone();
456
let from_below = self.caret_before_table > line.end;
457
let resting = if from_below {
458
self.draft
459
.line_ranges()
460
.get(index + 1)
461
.map_or(line.end, |next| next.start)
462
} else {
463
line.start.saturating_sub(1)
464
};
465
self.input.update(cx, |state, cx| {
466
state.set_selected_range(resting..resting, cx)
467
});
468
self.caret_before_table = resting;
469
let token = self.token_at_line(index, cx);
470
let Some(token_id) = token else {
471
return;
472
};
473
let row = if from_below {
474
self.draft
475
.table(index)
476
.map_or(0, |table| table.row_count() - 1)
477
} else {
478
0
479
};
480
self.focus_cell(&token_id, Cell::new(row, 0), window, cx);
481
}
482
483
pub(super) fn open_table_picker(&mut self, cx: &mut Context<Self>) {
484
self.table_picker = Some(TablePicker {
485
rows: 1,
486
columns: 1,
487
});
488
cx.notify();
489
}
490
491
pub(super) fn render_table_picker(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
492
let picker = self.table_picker.as_ref()?;
493
let grid = v_flex()
494
.gap(px(PICKER_GAP))
495
.children((1..=PICKER_ROWS).map(|row| {
496
h_flex()
497
.gap(px(PICKER_GAP))
498
.children((1..=PICKER_COLUMNS).map(|column| {
499
let covered = row <= picker.rows && column <= picker.columns;
500
div()
501
.id(ElementId::Name(format!("table-size-{row}-{column}").into()))
502
.size(px(PICKER_SQUARE))
503
.rounded(px(2.))
504
.bg(if covered {
505
theme::accent().opacity(0.6)
506
} else {
507
theme::border_strong()
508
})
509
.cursor_pointer()
510
.on_hover(cx.listener(move |this, hovered: &bool, _, cx| {
511
if *hovered && let Some(picker) = this.table_picker.as_mut() {
512
picker.rows = row;
513
picker.columns = column;
514
cx.notify();
515
}
516
}))
517
.on_click(cx.listener(move |this, _, window, cx| {
518
this.insert_table(row, column, window, cx)
519
}))
520
}))
521
}));
522
Some(
523
v_flex()
524
.id("table-picker")
525
.absolute()
526
.bottom(relative(1.))
527
.left_0()
528
.mb(px(6.))
529
.p(px(10.))
530
.gap(px(8.))
531
.rounded(px(10.))
532
.flyout_surface()
533
.occlude()
534
.on_mouse_down_out(cx.listener(|this, _, _, cx| {
535
this.table_picker = None;
536
cx.notify();
537
}))
538
.child(
539
div()
540
.text_size(px(12.))
541
.text_color(theme::text_muted())
542
.child(format!("Insert {}x{} table", picker.columns, picker.rows)),
543
)
544
.child(grid)
545
.into_any_element(),
546
)
547
}
548
549
/// The table token: a grid of cell inputs over the full width, solid lines like Teams.
550
pub(super) fn render_table_token(&self, token_id: &str, width: Pixels) -> Option<AnyElement> {
551
let view = self.tables.get(token_id)?;
552
let rows = view.cells.iter().map(|inputs| {
553
h_flex()
554
.w_full()
555
.items_stretch()
556
.children(inputs.iter().map(|input| {
557
div()
558
.flex_1()
559
.min_w_0()
560
.px(px(CELL_PADDING_X))
561
.py(px(CELL_PADDING_Y))
562
.border_r_1()
563
.border_b_1()
564
.border_color(theme::border_strong())
565
.child(
566
Textarea::new(input)
567
.appearance(false)
568
.bordered(false)
569
.small()
570
.context_menu(|menu, _, _| table_menu(menu)),
571
)
572
}))
573
});
574
Some(
575
v_flex()
576
.id(ElementId::Name(format!("composer-{token_id}").into()))
577
.w(width)
578
.my(px(TABLE_MARGIN))
579
.border_t_1()
580
.border_l_1()
581
.border_color(theme::border_strong())
582
.on_any_mouse_down(|_, window, cx| {
583
window.prevent_default();
584
cx.stop_propagation();
585
})
586
.children(rows)
587
.into_any_element(),
588
)
589
}
590
}
591
592
fn table_menu(menu: NativeMenu) -> NativeMenu {
593
let menu = TableEdit::INSERTS
594
.into_iter()
595
.fold(menu, |menu, edit| {
596
menu.menu(edit.label(), edit_action(edit))
597
})
598
.separator();
599
TableEdit::DELETES
600
.into_iter()
601
.fold(menu, |menu, edit| {
602
menu.menu(edit.label(), edit_action(edit))
603
})
604
.separator()
605
.menu("Cut", Box::new(Cut))
606
.menu("Copy", Box::new(Copy))
607
.menu("Paste", Box::new(Paste))
608
}
609
610
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
611
pub(super) enum TableKey {
612
Next,
613
Previous,
614
Up,
615
Down,
616
}
617
618
fn edit_action(edit: TableEdit) -> Box<dyn Action> {
619
match edit {
620
TableEdit::InsertRowAbove => Box::new(InsertTableRowAbove),
621
TableEdit::InsertRowBelow => Box::new(InsertTableRowBelow),
622
TableEdit::InsertColumnLeft => Box::new(InsertTableColumnLeft),
623
TableEdit::InsertColumnRight => Box::new(InsertTableColumnRight),
624
TableEdit::DeleteRow => Box::new(DeleteTableRow),
625
TableEdit::DeleteColumn => Box::new(DeleteTableColumn),
626
TableEdit::DeleteTable => Box::new(DeleteTable),
627
}
628
}
629
630
pub(super) type TableViews = HashMap<String, TableView>;
@@ -0,0 +1,630 @@1
use std::collections::HashMap;2
use std::ops::Range;3
4
use gpui_kit::component::input::{5
Copy, Cut, InlineToken, InputEvent, Paste, Textarea, TextareaState,6
};7
use gpui_kit::component::native_menu::NativeMenu;8
use gpui_kit::component::{Sizable as _, h_flex, v_flex};9
use gpui_kit::*;10
use teams_core::{Cell, PICKER_COLUMNS, PICKER_ROWS, TABLE_MARK, Table, TableEdit};11
12
use super::{Composer, StepKind};13
use crate::theme::{self, ElevatedSurface as _};14
use crate::views::actions::{15
DeleteTable, DeleteTableColumn, DeleteTableRow, InsertTableColumnLeft, InsertTableColumnRight,16
InsertTableRowAbove, InsertTableRowBelow,17
};18
19
pub(super) const TOKEN_PREFIX: &str = "table-";20
const CELL_MAX_ROWS: usize = 12;21
const PICKER_SQUARE: f32 = 16.;22
const PICKER_GAP: f32 = 3.;23
const TABLE_MARGIN: f32 = 4.;24
const CELL_PADDING_X: f32 = 2.;25
const CELL_PADDING_Y: f32 = 3.;26
27
pub(super) struct TableView {28
cells: Vec<Vec<Entity<TextareaState>>>,29
_subscriptions: Vec<Subscription>,30
}31
32
impl TableView {33
fn shape(&self) -> (usize, usize) {34
(self.cells.len(), self.cells.first().map_or(0, Vec::len))35
}36
}37
38
/// The rows and columns the pointer covers in the size picker.39
pub(super) struct TablePicker {40
rows: usize,41
columns: usize,42
}43
44
pub(super) fn token(number: usize) -> InlineToken {45
InlineToken::new(format!("{TOKEN_PREFIX}{number}"), TABLE_MARK.to_string()).block()46
}47
48
pub(super) fn is_table_token(token: &InlineToken) -> bool {49
token.id().starts_with(TOKEN_PREFIX)50
}51
52
fn token_number(id: &str) -> usize {53
id.strip_prefix(TOKEN_PREFIX)54
.and_then(|number| number.parse().ok())55
.unwrap_or_default()56
}57
58
fn caret_on_first_line(state: &TextareaState) -> bool {59
!state.value()[..state.cursor()].contains('\n')60
}61
62
fn caret_on_last_line(state: &TextareaState) -> bool {63
!state.value()[state.cursor()..].contains('\n')64
}65
66
impl Composer {67
fn table_tokens(&self, cx: &App) -> Vec<(Range<usize>, String)> {68
self.input69
.read(cx)70
.tokens()71
.iter()72
.filter(|span| is_table_token(span.token()))73
.map(|span| (span.range(), span.token().id().to_string()))74
.collect()75
}76
77
fn table_line(&self, token_id: &str, cx: &App) -> Option<usize> {78
let (range, _) = self79
.table_tokens(cx)80
.into_iter()81
.find(|(_, id)| id == token_id)?;82
let index = self.draft.line_at(range.start);83
self.draft.table(index).is_some().then_some(index)84
}85
86
/// Every table line gets its token and cell inputs; inputs follow the draft's cells.87
pub(super) fn sync_tables(&mut self, window: &mut Window, cx: &mut Context<Self>) {88
if self.input.read(cx).value().as_ref() != self.draft.text() {89
return;90
}91
let ranges = self.draft.line_ranges();92
let tokens = self.table_tokens(cx);93
for (index, line) in ranges.iter().enumerate() {94
if self.draft.table(index).is_none() || tokens.iter().any(|(range, _)| range == line) {95
continue;96
}97
self.table_counter += 1;98
let token = token(self.table_counter);99
self.input.update(cx, |state, cx| {100
let selection = state.selected_range();101
if state102
.replace_range_with_token(line.clone(), token, window, cx)103
.is_ok()104
{105
state.set_selected_range(selection, cx);106
}107
});108
}109
let tokens = self.table_tokens(cx);110
self.tables111
.retain(|id, _| tokens.iter().any(|(_, token_id)| token_id == id));112
for (range, id) in tokens {113
let Some(table) = self.draft.table(self.draft.line_at(range.start)).cloned() else {114
continue;115
};116
self.sync_table_view(&id, &table, window, cx);117
}118
}119
120
fn sync_table_view(121
&mut self,122
token_id: &str,123
table: &Table,124
window: &mut Window,125
cx: &mut Context<Self>,126
) {127
let shape = (table.row_count(), table.column_count());128
if self129
.tables130
.get(token_id)131
.is_some_and(|view| view.shape() == shape)132
{133
let cells = self.tables[token_id].cells.clone();134
for (row, inputs) in cells.iter().enumerate() {135
for (column, input) in inputs.iter().enumerate() {136
let text = table.cell(Cell::new(row, column)).unwrap_or_default();137
if input.read(cx).value().as_ref() != text {138
let text = text.to_owned();139
input.update(cx, |state, cx| state.set_value(text, window, cx));140
}141
}142
}143
return;144
}145
let mut subscriptions = Vec::new();146
let cells = table147
.rows148
.iter()149
.enumerate()150
.map(|(row, texts)| {151
texts152
.iter()153
.enumerate()154
.map(|(column, text)| {155
let text = text.clone();156
let input = cx.new(|cx| {157
TextareaState::new(window, cx)158
.auto_grow(1, CELL_MAX_ROWS)159
.default_value(text)160
});161
let id = token_id.to_owned();162
let cell = Cell::new(row, column);163
subscriptions.push(cx.subscribe_in(164
&input,165
window,166
move |this, _, event: &InputEvent, window, cx| {167
this.on_cell_event(&id, cell, event, window, cx)168
},169
));170
input171
})172
.collect()173
})174
.collect();175
self.tables.insert(176
token_id.to_owned(),177
TableView {178
cells,179
_subscriptions: subscriptions,180
},181
);182
}183
184
fn on_cell_event(185
&mut self,186
token_id: &str,187
cell: Cell,188
event: &InputEvent,189
_: &mut Window,190
cx: &mut Context<Self>,191
) {192
match event {193
InputEvent::Focus => {194
self.active_cell = Some((token_id.to_owned(), cell));195
self.table_picker = None;196
}197
InputEvent::Change => {198
let Some(index) = self.table_line(token_id, cx) else {199
return;200
};201
let Some(input) = self.cell_input(token_id, cell) else {202
return;203
};204
let text = input.read(cx).value().to_string();205
let Some(mut table) = self.draft.table(index).cloned() else {206
return;207
};208
if table.cell(cell) == Some(text.as_str()) {209
return;210
}211
table.set_cell(cell, &text);212
self.draft.set_table(index, table);213
self.record(214
StepKind::CellTyping {215
table: token_number(token_id),216
row: cell.row,217
column: cell.column,218
},219
cx,220
);221
self.schedule_draft_save(cx);222
}223
_ => {}224
}225
cx.notify();226
}227
228
fn cell_input(&self, token_id: &str, cell: Cell) -> Option<Entity<TextareaState>> {229
self.tables230
.get(token_id)?231
.cells232
.get(cell.row)?233
.get(cell.column)234
.cloned()235
}236
237
pub(super) fn focused_cell_input(238
&self,239
window: &Window,240
cx: &App,241
) -> Option<Entity<TextareaState>> {242
let (token_id, cell) = self.focused_cell(window, cx)?;243
self.cell_input(&token_id, cell)244
}245
246
/// The cell that has the keyboard, if any.247
pub(super) fn focused_cell(&self, window: &Window, cx: &App) -> Option<(String, Cell)> {248
self.tables.iter().find_map(|(id, view)| {249
view.cells.iter().enumerate().find_map(|(row, inputs)| {250
inputs.iter().enumerate().find_map(|(column, input)| {251
input252
.focus_handle(cx)253
.is_focused(window)254
.then(|| (id.clone(), Cell::new(row, column)))255
})256
})257
})258
}259
260
pub(super) fn focus_cell(261
&mut self,262
token_id: &str,263
cell: Cell,264
window: &mut Window,265
cx: &mut Context<Self>,266
) {267
let Some(input) = self.cell_input(token_id, cell) else {268
return;269
};270
input.update(cx, |state, cx| {271
let end = state.value().len();272
state.focus(window, cx);273
state.set_selected_range(end..end, cx);274
});275
self.active_cell = Some((token_id.to_owned(), cell));276
cx.notify();277
}278
279
fn token_at_line(&self, index: usize, cx: &App) -> Option<String> {280
let line = self.draft.line_ranges().get(index)?.clone();281
self.table_tokens(cx)282
.into_iter()283
.find(|(range, _)| *range == line)284
.map(|(_, id)| id)285
}286
287
pub(super) fn focus_table_line(288
&mut self,289
index: usize,290
last: bool,291
window: &mut Window,292
cx: &mut Context<Self>,293
) {294
let Some(token_id) = self.token_at_line(index, cx) else {295
return;296
};297
let Some(table) = self.draft.table(index) else {298
return;299
};300
let cell = if last {301
table.last_cell()302
} else {303
Cell::new(0, 0)304
};305
self.focus_cell(&token_id, cell, window, cx);306
}307
308
pub(super) fn insert_table(309
&mut self,310
rows: usize,311
columns: usize,312
window: &mut Window,313
cx: &mut Context<Self>,314
) {315
self.table_picker = None;316
let cursor = match self.focused_cell(window, cx) {317
Some((token_id, _)) => self318
.table_line(&token_id, cx)319
.map_or(self.selection(cx).end, |index| {320
self.draft.line_ranges()[index].end321
}),322
None => self.selection(cx).end,323
};324
let index = self.draft.insert_table(cursor, Table::new(rows, columns));325
let after = self.draft.line_ranges()[index].end;326
self.commit(Some(after), window, cx);327
self.focus_table_line(index, false, window, cx);328
}329
330
fn leave_table(331
&mut self,332
token_id: &str,333
below: bool,334
window: &mut Window,335
cx: &mut Context<Self>,336
) {337
let Some(index) = self.table_line(token_id, cx) else {338
return;339
};340
let cursor = self.draft.line_beside_table(index, below);341
self.active_cell = None;342
self.focus(window, cx);343
self.commit(Some(cursor), window, cx);344
}345
346
/// Tab, Shift+Tab, Up and Down while a cell has the keyboard. `false` leaves the key to347
/// the cell.348
pub(super) fn table_key(349
&mut self,350
key: TableKey,351
window: &mut Window,352
cx: &mut Context<Self>,353
) -> bool {354
let Some((token_id, cell)) = self.focused_cell(window, cx) else {355
return false;356
};357
let Some(index) = self.table_line(&token_id, cx) else {358
return false;359
};360
let Some(mut table) = self.draft.table(index).cloned() else {361
return false;362
};363
let Some(input) = self.cell_input(&token_id, cell) else {364
return false;365
};366
let target = match key {367
TableKey::Next => {368
let (next, added_row) = table.next_cell(cell);369
if added_row {370
self.draft.set_table(index, table);371
self.record(StepKind::Other, cx);372
self.sync_tables(window, cx);373
self.schedule_draft_save(cx);374
}375
next376
}377
TableKey::Previous => table.previous_cell(cell),378
TableKey::Down if !caret_on_last_line(input.read(cx)) => return false,379
TableKey::Up if !caret_on_first_line(input.read(cx)) => return false,380
TableKey::Down if cell.row + 1 == table.row_count() => {381
self.leave_table(&token_id, true, window, cx);382
return true;383
}384
TableKey::Up if cell.row == 0 => {385
self.leave_table(&token_id, false, window, cx);386
return true;387
}388
TableKey::Down => Cell::new(cell.row + 1, cell.column),389
TableKey::Up => Cell::new(cell.row - 1, cell.column),390
};391
self.focus_cell(&token_id, target, window, cx);392
true393
}394
395
pub(super) fn edit_table(396
&mut self,397
edit: TableEdit,398
window: &mut Window,399
cx: &mut Context<Self>,400
) {401
let Some((token_id, cell)) = self402
.focused_cell(window, cx)403
.or_else(|| self.active_cell.clone())404
else {405
return;406
};407
let Some(index) = self.table_line(&token_id, cx) else {408
return;409
};410
let Some(mut table) = self.draft.table(index).cloned() else {411
return;412
};413
match table.apply(edit, cell) {414
Some(target) => {415
self.draft.set_table(index, table);416
self.record(StepKind::Other, cx);417
self.sync_tables(window, cx);418
self.schedule_draft_save(cx);419
self.focus_cell(&token_id, target, window, cx);420
}421
None => {422
let cursor = self.draft.remove_table(index);423
self.active_cell = None;424
self.focus(window, cx);425
self.commit(Some(cursor), window, cx);426
}427
}428
cx.notify();429
}430
431
/// The caret never rests on a table's line: coming from above it enters the first432
/// cell, from below the first cell of the last row. Only a move without an edit433
/// counts, so a paste that passes the table on its way does not enter it.434
pub(super) fn redirect_caret_from_table(435
&mut self,436
window: &mut Window,437
cx: &mut Context<Self>,438
) {439
let state = self.input.read(cx);440
let selection = state.selected_range();441
let focused = state.focus_handle(cx).is_focused(window);442
let value = state.value();443
if value.as_ref() != self.caret_text {444
self.caret_text = value.to_string();445
self.caret_before_table = selection.start;446
return;447
}448
if !focused || !selection.is_empty() || value.as_ref() != self.draft.text() {449
return;450
}451
let Some(index) = self.draft.table_at(selection.start) else {452
self.caret_before_table = selection.start;453
return;454
};455
let line = self.draft.line_ranges()[index].clone();456
let from_below = self.caret_before_table > line.end;457
let resting = if from_below {458
self.draft459
.line_ranges()460
.get(index + 1)461
.map_or(line.end, |next| next.start)462
} else {463
line.start.saturating_sub(1)464
};465
self.input.update(cx, |state, cx| {466
state.set_selected_range(resting..resting, cx)467
});468
self.caret_before_table = resting;469
let token = self.token_at_line(index, cx);470
let Some(token_id) = token else {471
return;472
};473
let row = if from_below {474
self.draft475
.table(index)476
.map_or(0, |table| table.row_count() - 1)477
} else {478
0479
};480
self.focus_cell(&token_id, Cell::new(row, 0), window, cx);481
}482
483
pub(super) fn open_table_picker(&mut self, cx: &mut Context<Self>) {484
self.table_picker = Some(TablePicker {485
rows: 1,486
columns: 1,487
});488
cx.notify();489
}490
491
pub(super) fn render_table_picker(&self, cx: &mut Context<Self>) -> Option<AnyElement> {492
let picker = self.table_picker.as_ref()?;493
let grid = v_flex()494
.gap(px(PICKER_GAP))495
.children((1..=PICKER_ROWS).map(|row| {496
h_flex()497
.gap(px(PICKER_GAP))498
.children((1..=PICKER_COLUMNS).map(|column| {499
let covered = row <= picker.rows && column <= picker.columns;500
div()501
.id(ElementId::Name(format!("table-size-{row}-{column}").into()))502
.size(px(PICKER_SQUARE))503
.rounded(px(2.))504
.bg(if covered {505
theme::accent().opacity(0.6)506
} else {507
theme::border_strong()508
})509
.cursor_pointer()510
.on_hover(cx.listener(move |this, hovered: &bool, _, cx| {511
if *hovered && let Some(picker) = this.table_picker.as_mut() {512
picker.rows = row;513
picker.columns = column;514
cx.notify();515
}516
}))517
.on_click(cx.listener(move |this, _, window, cx| {518
this.insert_table(row, column, window, cx)519
}))520
}))521
}));522
Some(523
v_flex()524
.id("table-picker")525
.absolute()526
.bottom(relative(1.))527
.left_0()528
.mb(px(6.))529
.p(px(10.))530
.gap(px(8.))531
.rounded(px(10.))532
.flyout_surface()533
.occlude()534
.on_mouse_down_out(cx.listener(|this, _, _, cx| {535
this.table_picker = None;536
cx.notify();537
}))538
.child(539
div()540
.text_size(px(12.))541
.text_color(theme::text_muted())542
.child(format!("Insert {}x{} table", picker.columns, picker.rows)),543
)544
.child(grid)545
.into_any_element(),546
)547
}548
549
/// The table token: a grid of cell inputs over the full width, solid lines like Teams.550
pub(super) fn render_table_token(&self, token_id: &str, width: Pixels) -> Option<AnyElement> {551
let view = self.tables.get(token_id)?;552
let rows = view.cells.iter().map(|inputs| {553
h_flex()554
.w_full()555
.items_stretch()556
.children(inputs.iter().map(|input| {557
div()558
.flex_1()559
.min_w_0()560
.px(px(CELL_PADDING_X))561
.py(px(CELL_PADDING_Y))562
.border_r_1()563
.border_b_1()564
.border_color(theme::border_strong())565
.child(566
Textarea::new(input)567
.appearance(false)568
.bordered(false)569
.small()570
.context_menu(|menu, _, _| table_menu(menu)),571
)572
}))573
});574
Some(575
v_flex()576
.id(ElementId::Name(format!("composer-{token_id}").into()))577
.w(width)578
.my(px(TABLE_MARGIN))579
.border_t_1()580
.border_l_1()581
.border_color(theme::border_strong())582
.on_any_mouse_down(|_, window, cx| {583
window.prevent_default();584
cx.stop_propagation();585
})586
.children(rows)587
.into_any_element(),588
)589
}590
}591
592
fn table_menu(menu: NativeMenu) -> NativeMenu {593
let menu = TableEdit::INSERTS594
.into_iter()595
.fold(menu, |menu, edit| {596
menu.menu(edit.label(), edit_action(edit))597
})598
.separator();599
TableEdit::DELETES600
.into_iter()601
.fold(menu, |menu, edit| {602
menu.menu(edit.label(), edit_action(edit))603
})604
.separator()605
.menu("Cut", Box::new(Cut))606
.menu("Copy", Box::new(Copy))607
.menu("Paste", Box::new(Paste))608
}609
610
#[derive(Debug, Clone, Copy, PartialEq, Eq)]611
pub(super) enum TableKey {612
Next,613
Previous,614
Up,615
Down,616
}617
618
fn edit_action(edit: TableEdit) -> Box<dyn Action> {619
match edit {620
TableEdit::InsertRowAbove => Box::new(InsertTableRowAbove),621
TableEdit::InsertRowBelow => Box::new(InsertTableRowBelow),622
TableEdit::InsertColumnLeft => Box::new(InsertTableColumnLeft),623
TableEdit::InsertColumnRight => Box::new(InsertTableColumnRight),624
TableEdit::DeleteRow => Box::new(DeleteTableRow),625
TableEdit::DeleteColumn => Box::new(DeleteTableColumn),626
TableEdit::DeleteTable => Box::new(DeleteTable),627
}628
}629
630
pub(super) type TableViews = HashMap<String, TableView>;@@ -27,8 +27,6 @@ pub fn render_connection_banner(
27
27
.gap(px(8.))
28
28
.items_center()
29
29
.rounded(px(8.))
30
.border_1()
31
.border_color(theme::amber().opacity(0.45))
32
30
.bg(theme::amber().opacity(0.14))
33
31
.text_size(px(BANNER_TEXT_SIZE))
34
32
.text_color(theme::text())
@@ -27,8 +27,6 @@ pub fn render_connection_banner(27
.gap(px(8.))27
.gap(px(8.))28
.items_center()28
.items_center()29
.rounded(px(8.))29
.rounded(px(8.))30
.border_1()31
.border_color(theme::amber().opacity(0.45))32
.bg(theme::amber().opacity(0.14))30
.bg(theme::amber().opacity(0.14))33
.text_size(px(BANNER_TEXT_SIZE))31
.text_size(px(BANNER_TEXT_SIZE))34
.text_color(theme::text())32
.text_color(theme::text())@@ -86,6 +86,7 @@ use mcp::ReactionProposal;
86
86
use render_env::RenderEnv;
87
87
use shared::SharedState;
88
88
89
pub const MEMBERS_BUTTON: &str = "shell/islands/main/members-button";
89
90
const CHAT_OPEN_LIMIT: usize = 60;
90
91
const CHANNEL_OPEN_LIMIT: usize = 300;
91
92
const GROWTH_HEADROOM: usize = 20;
@@ -3271,7 +3272,8 @@ impl ConversationView {
3271
3272
stack = Some(members_popover(
3272
3273
&self.app,
3273
3274
chat_id,
3274
member_stack(directory, &shown, shown.len(), false),
3275
member_stack(directory, &shown, shown.len(), false)
3276
.debug_selector(|| MEMBERS_BUTTON.into()),
3275
3277
));
3276
3278
}
3277
3279
}
@@ -86,6 +86,7 @@ use mcp::ReactionProposal;86
use render_env::RenderEnv;86
use render_env::RenderEnv;87
use shared::SharedState;87
use shared::SharedState;88
88
89
pub const MEMBERS_BUTTON: &str = "shell/islands/main/members-button";89
const CHAT_OPEN_LIMIT: usize = 60;90
const CHAT_OPEN_LIMIT: usize = 60;90
const CHANNEL_OPEN_LIMIT: usize = 300;91
const CHANNEL_OPEN_LIMIT: usize = 300;91
const GROWTH_HEADROOM: usize = 20;92
const GROWTH_HEADROOM: usize = 20;@@ -3271,7 +3272,8 @@ impl ConversationView {3271
stack = Some(members_popover(3272
stack = Some(members_popover(3272
&self.app,3273
&self.app,3273
chat_id,3274
chat_id,3274
member_stack(directory, &shown, shown.len(), false),3275
member_stack(directory, &shown, shown.len(), false)3276
.debug_selector(|| MEMBERS_BUTTON.into()),3275
));3277
));3276
}3278
}3277
}3279
}@@ -95,8 +95,6 @@ pub fn render_pin_banner(data: PinBannerData, actions: PinBannerActions) -> AnyE
95
95
.gap(px(8.))
96
96
.items_center()
97
97
.rounded(px(8.))
98
.border_1()
99
.border_color(theme::border())
100
98
.bg(theme::row_hover())
101
99
.shadow(theme::toast_shadow())
102
100
.cursor_pointer()
@@ -95,8 +95,6 @@ pub fn render_pin_banner(data: PinBannerData, actions: PinBannerActions) -> AnyE95
.gap(px(8.))95
.gap(px(8.))96
.items_center()96
.items_center()97
.rounded(px(8.))97
.rounded(px(8.))98
.border_1()99
.border_color(theme::border())100
.bg(theme::row_hover())98
.bg(theme::row_hover())101
.shadow(theme::toast_shadow())99
.shadow(theme::toast_shadow())102
.cursor_pointer()100
.cursor_pointer()@@ -143,6 +143,12 @@ pub struct AppShell {
143
143
}
144
144
145
145
impl AppShell {
146
#[cfg(test)]
147
pub(crate) fn set_update_status(&mut self, update: UpdateStatus, cx: &mut Context<Self>) {
148
self.update = update;
149
cx.notify();
150
}
151
146
152
fn sync_call_chat(
147
153
&mut self,
148
154
thread: Option<String>,
@@ -143,6 +143,12 @@ pub struct AppShell {143
}143
}144
144
145
impl AppShell {145
impl AppShell {146
#[cfg(test)]147
pub(crate) fn set_update_status(&mut self, update: UpdateStatus, cx: &mut Context<Self>) {148
self.update = update;149
cx.notify();150
}151
146
fn sync_call_chat(152
fn sync_call_chat(147
&mut self,153
&mut self,148
thread: Option<String>,154
thread: Option<String>,@@ -1,9 +1,9 @@
1
1
use gpui_kit::*;
2
2
3
3
use super::actions::{
4
COMPOSER_KEY_CONTEXT as COMPOSER_CONTEXT, EditLink, NewChat, OpenSwitcher, ReplyToHovered,
5
ScheduleSend, ToggleBold, ToggleCode, ToggleItalic, ToggleStrike, ToggleSubscript,
6
ToggleSuperscript, ToggleUnderline, ToggleCallMute,
4
COMPOSER_KEY_CONTEXT as COMPOSER_CONTEXT, EditLink, NewChat, OpenSwitcher, PastePlainText,
5
ReplyToHovered, ScheduleSend, ToggleBold, ToggleCallMute, ToggleCode, ToggleItalic,
6
ToggleStrike, ToggleSubscript, ToggleSuperscript, ToggleUnderline,
7
7
};
8
8
9
9
const TEXT_FIELD_CONTEXT: &str = "Input";
@@ -122,6 +122,7 @@ pub const SHORTCUTS: &[Shortcut] = &[
122
122
shortcut!(Composer, Composer, "Subscript", "ctrl-=", None, ToggleSubscript),
123
123
shortcut!(Composer, Composer, "Code", "ctrl-shift-c", None, ToggleCode),
124
124
shortcut!(Composer, Composer, "Insert link", "ctrl-k", Some("cmd-k"), EditLink),
125
shortcut!(Composer, Composer, "Paste as plain text", "ctrl-shift-v", Some("cmd-shift-v"), PastePlainText),
125
126
shortcut!(Composer, Composer, "Schedule send", "ctrl-shift-enter", None, ScheduleSend),
126
127
shortcut!(Calls, GlobalOverTextFields, "Accept incoming call", "ctrl-shift-a", Some("cmd-shift-a"), AcceptCall),
127
128
shortcut!(Calls, GlobalOverTextFields, "Decline incoming call", "ctrl-shift-d", Some("cmd-shift-d"), DeclineCall),
@@ -162,7 +163,12 @@ impl Shortcut {
162
163
Scope::Composer => &[Some(COMPOSER_CONTEXT)],
163
164
};
164
165
let mut keys = vec![self.keys];
165
keys.extend(ALTERNATE_KEYS.iter().filter(|(primary, _)| *primary == self.keys).map(|(_, alternate)| *alternate));
166
keys.extend(
167
ALTERNATE_KEYS
168
.iter()
169
.filter(|(primary, _)| *primary == self.keys)
170
.map(|(_, alternate)| *alternate),
171
);
166
172
keys.extend(self.mac_keys.filter(|_| cfg!(target_os = "macos")));
167
173
keys.iter()
168
174
.flat_map(|keys| contexts.iter().map(|context| (self.bind)(keys, *context)))
@@ -1,9 +1,9 @@1
use gpui_kit::*;1
use gpui_kit::*;2
2
3
use super::actions::{3
use super::actions::{4
COMPOSER_KEY_CONTEXT as COMPOSER_CONTEXT, EditLink, NewChat, OpenSwitcher, ReplyToHovered,4
COMPOSER_KEY_CONTEXT as COMPOSER_CONTEXT, EditLink, NewChat, OpenSwitcher, PastePlainText,5
ScheduleSend, ToggleBold, ToggleCode, ToggleItalic, ToggleStrike, ToggleSubscript,5
ReplyToHovered, ScheduleSend, ToggleBold, ToggleCallMute, ToggleCode, ToggleItalic,6
ToggleSuperscript, ToggleUnderline, ToggleCallMute,6
ToggleStrike, ToggleSubscript, ToggleSuperscript, ToggleUnderline,7
};7
};8
8
9
const TEXT_FIELD_CONTEXT: &str = "Input";9
const TEXT_FIELD_CONTEXT: &str = "Input";@@ -122,6 +122,7 @@ pub const SHORTCUTS: &[Shortcut] = &[122
shortcut!(Composer, Composer, "Subscript", "ctrl-=", None, ToggleSubscript),122
shortcut!(Composer, Composer, "Subscript", "ctrl-=", None, ToggleSubscript),123
shortcut!(Composer, Composer, "Code", "ctrl-shift-c", None, ToggleCode),123
shortcut!(Composer, Composer, "Code", "ctrl-shift-c", None, ToggleCode),124
shortcut!(Composer, Composer, "Insert link", "ctrl-k", Some("cmd-k"), EditLink),124
shortcut!(Composer, Composer, "Insert link", "ctrl-k", Some("cmd-k"), EditLink),125
shortcut!(Composer, Composer, "Paste as plain text", "ctrl-shift-v", Some("cmd-shift-v"), PastePlainText),125
shortcut!(Composer, Composer, "Schedule send", "ctrl-shift-enter", None, ScheduleSend),126
shortcut!(Composer, Composer, "Schedule send", "ctrl-shift-enter", None, ScheduleSend),126
shortcut!(Calls, GlobalOverTextFields, "Accept incoming call", "ctrl-shift-a", Some("cmd-shift-a"), AcceptCall),127
shortcut!(Calls, GlobalOverTextFields, "Accept incoming call", "ctrl-shift-a", Some("cmd-shift-a"), AcceptCall),127
shortcut!(Calls, GlobalOverTextFields, "Decline incoming call", "ctrl-shift-d", Some("cmd-shift-d"), DeclineCall),128
shortcut!(Calls, GlobalOverTextFields, "Decline incoming call", "ctrl-shift-d", Some("cmd-shift-d"), DeclineCall),@@ -162,7 +163,12 @@ impl Shortcut {162
Scope::Composer => &[Some(COMPOSER_CONTEXT)],163
Scope::Composer => &[Some(COMPOSER_CONTEXT)],163
};164
};164
let mut keys = vec![self.keys];165
let mut keys = vec![self.keys];165
keys.extend(ALTERNATE_KEYS.iter().filter(|(primary, _)| *primary == self.keys).map(|(_, alternate)| *alternate));166
keys.extend(167
ALTERNATE_KEYS168
.iter()169
.filter(|(primary, _)| *primary == self.keys)170
.map(|(_, alternate)| *alternate),171
);166
keys.extend(self.mac_keys.filter(|_| cfg!(target_os = "macos")));172
keys.extend(self.mac_keys.filter(|_| cfg!(target_os = "macos")));167
keys.iter()173
keys.iter()168
.flat_map(|keys| contexts.iter().map(|context| (self.bind)(keys, *context)))174
.flat_map(|keys| contexts.iter().map(|context| (self.bind)(keys, *context)))@@ -12,6 +12,11 @@ use crate::updater::UpdateStatus;
12
12
13
13
pub const TITLE_BAR_HEIGHT: f32 = 40.;
14
14
const SEARCH_WIDTH: f32 = 380.;
15
const SEARCH_MIN_WIDTH: f32 = 240.;
16
const SEARCH_MIN_VISIBLE_WIDTH: f32 = 36.;
17
const SEARCH_HEIGHT: f32 = 28.;
18
const SEARCH_GAP: f32 = 8.;
19
const SHORTCUT_MIN_WIDTH: f32 = 200.;
15
20
const SEARCH_HINT: &str = "Search chats, people and channels";
16
21
const SHORTCUT_HINT: &str = "Ctrl K";
17
22
const APP_ICON_SIZE: f32 = 18.;
@@ -32,8 +37,6 @@ fn mode_pill(label: &'static str) -> Div {
32
37
.flex()
33
38
.items_center()
34
39
.rounded_full()
35
.border_1()
36
.border_color(theme::amber().opacity(0.5))
37
40
.bg(theme::amber().opacity(0.14))
38
41
.text_size(px(11.))
39
42
.font_weight(FontWeight::SEMIBOLD)
@@ -90,65 +93,201 @@ pub fn update_button(
90
93
)
91
94
}
92
95
96
#[derive(Clone, Copy, Debug, PartialEq)]
97
struct SearchSpan {
98
left: f32,
99
width: f32,
100
}
101
102
fn search_span(window_width: f32, leading_end: f32, trailing_start: f32) -> Option<SearchSpan> {
103
let start = leading_end + SEARCH_GAP;
104
let end = trailing_start - SEARCH_GAP;
105
let room = end - start;
106
if room < SEARCH_MIN_VISIBLE_WIDTH {
107
return None;
108
}
109
let center = window_width / 2.;
110
let centered_width = (2. * (center - start).min(end - center)).min(SEARCH_WIDTH);
111
let width = centered_width.max(SEARCH_MIN_WIDTH).min(room);
112
let left = (center - width / 2.).clamp(start, end - width);
113
Some(SearchSpan { left, width })
114
}
115
116
#[derive(Clone, Copy, PartialEq)]
117
struct Reserved {
118
leading_end: f32,
119
trailing_from_right: f32,
120
}
121
122
#[derive(IntoElement)]
123
struct TitleBarRow {
124
mode_label: Option<&'static str>,
125
update: Option<AnyElement>,
126
own: Option<AnyElement>,
127
on_search: Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>,
128
}
129
93
130
pub fn render_title_bar(
94
131
mode_label: Option<&'static str>,
95
132
update: Option<AnyElement>,
96
133
own: Option<AnyElement>,
97
134
on_search: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
98
135
) -> impl IntoElement {
99
let search = h_flex()
136
TitleBarRow {
137
mode_label,
138
update,
139
own,
140
on_search: Box::new(on_search),
141
}
142
}
143
144
fn search_box(
145
span: SearchSpan,
146
on_search: Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>,
147
) -> impl IntoElement {
148
h_flex()
100
149
.id("title-search")
101
150
.debug_selector(|| "shell/title-bar/search".into())
102
151
.occlude()
103
.w(px(SEARCH_WIDTH))
104
.h(px(28.))
152
.absolute()
153
.top(px((TITLE_BAR_HEIGHT - SEARCH_HEIGHT) / 2.))
154
.left(px(span.left))
155
.w(px(span.width))
156
.h(px(SEARCH_HEIGHT))
105
157
.px(px(10.))
106
158
.gap(px(8.))
107
159
.items_center()
160
.overflow_hidden()
108
161
.rounded(px(6.))
109
162
.bg(theme::surface())
110
163
.cursor_pointer()
111
164
.text_size(px(12.))
112
165
.text_color(theme::text_muted())
113
.child(icon(IconName::Search, 14., theme::text_muted()))
114
.child(div().flex_1().child(SEARCH_HINT))
115
166
.child(
116
167
div()
117
.px(px(6.))
118
.py(px(1.))
119
.rounded(px(4.))
120
.bg(theme::surface_raised())
121
.text_size(px(11.))
122
.child(SHORTCUT_HINT),
168
.flex_none()
169
.child(icon(IconName::Search, 14., theme::text_muted())),
123
170
)
124
.on_click(on_search);
125
let bar = TitleBar::new()
126
.h(px(TITLE_BAR_HEIGHT))
127
.border_b_0()
128
.bg(theme::background())
129
.child(
130
h_flex()
131
.flex_1()
132
.h_full()
133
.gap(px(12.))
134
.items_center()
135
.child(img(app_icon()).size(px(APP_ICON_SIZE)).flex_none())
136
.child(
137
div()
138
.text_size(px(13.))
139
.font_weight(FontWeight::SEMIBOLD)
140
.text_color(theme::text())
141
.child(app_base::APP_NAME),
142
)
143
.children(mode_label.map(mode_pill))
144
.child(div().flex_1().flex().justify_center().child(search))
145
.children(update)
146
.children(own)
147
.child(div().w(px(4.))),
148
);
149
div()
150
.debug_selector(|| "shell/title-bar".into())
151
.flex_none()
152
.w_full()
153
.child(bar)
171
.child(div().flex_1().min_w_0().truncate().child(SEARCH_HINT))
172
.when(span.width >= SHORTCUT_MIN_WIDTH, |search| {
173
search.child(
174
div()
175
.flex_none()
176
.px(px(6.))
177
.py(px(1.))
178
.rounded(px(4.))
179
.bg(theme::surface_raised())
180
.text_size(px(11.))
181
.child(SHORTCUT_HINT),
182
)
183
})
184
.on_click(move |event, window, cx| on_search(event, window, cx))
185
}
186
187
impl RenderOnce for TitleBarRow {
188
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
189
let reserved = window.use_keyed_state("title-bar-reserved", cx, |_, _| None::<Reserved>);
190
let window_width = f32::from(window.viewport_size().width);
191
let span = (*reserved.read(cx)).and_then(|reserved| {
192
search_span(
193
window_width,
194
reserved.leading_end,
195
window_width - reserved.trailing_from_right,
196
)
197
});
198
let leading = h_flex()
199
.debug_selector(|| "shell/title-bar/leading".into())
200
.flex_none()
201
.h_full()
202
.gap(px(12.))
203
.items_center()
204
.child(img(app_icon()).size(px(APP_ICON_SIZE)).flex_none())
205
.child(
206
div()
207
.text_size(px(13.))
208
.font_weight(FontWeight::SEMIBOLD)
209
.text_color(theme::text())
210
.child(app_base::APP_NAME),
211
)
212
.children(self.mode_label.map(mode_pill));
213
let trailing = h_flex()
214
.debug_selector(|| "shell/title-bar/trailing".into())
215
.flex_none()
216
.h_full()
217
.gap(px(12.))
218
.items_center()
219
.children(self.update)
220
.children(self.own)
221
.child(div().w(px(4.)));
222
let row = h_flex()
223
.flex_1()
224
.h_full()
225
.gap(px(12.))
226
.items_center()
227
.child(leading)
228
.child(div().flex_1())
229
.child(trailing)
230
.on_children_prepainted(move |children, window, cx| {
231
let [leading, _, trailing] = children[..] else {
232
return;
233
};
234
let measured = Reserved {
235
leading_end: f32::from(leading.right()),
236
trailing_from_right: f32::from(window.viewport_size().width - trailing.left()),
237
};
238
reserved.update(cx, |current, cx| {
239
let unchanged = current.is_some_and(|current| {
240
(current.leading_end - measured.leading_end).abs() < 0.5
241
&& (current.trailing_from_right - measured.trailing_from_right).abs()
242
< 0.5
243
});
244
if !unchanged {
245
*current = Some(measured);
246
cx.notify();
247
}
248
});
249
});
250
let bar = TitleBar::new()
251
.h(px(TITLE_BAR_HEIGHT))
252
.border_b_0()
253
.bg(theme::background())
254
.child(row);
255
let on_search = self.on_search;
256
div()
257
.debug_selector(|| "shell/title-bar".into())
258
.relative()
259
.flex_none()
260
.w_full()
261
.child(bar)
262
.children(span.map(|span| search_box(span, on_search)))
263
}
264
}
265
266
#[cfg(test)]
267
mod tests {
268
use super::{SEARCH_MIN_WIDTH, SEARCH_WIDTH, search_span};
269
270
#[test]
271
fn search_stays_centered_while_it_fits() {
272
let span = search_span(1280., 200., 1080.).expect("visible");
273
assert_eq!(span.width, SEARCH_WIDTH);
274
assert_eq!(span.left + span.width / 2., 640.);
275
}
276
277
#[test]
278
fn search_shrinks_centered_before_it_shifts() {
279
let span = search_span(800., 200., 580.).expect("visible");
280
assert_eq!(span.left + span.width / 2., 400.);
281
assert_eq!(span.width, 344.);
282
let shifted = search_span(800., 200., 500.).expect("visible");
283
assert_eq!(shifted.width, SEARCH_MIN_WIDTH);
284
assert_eq!(shifted.left + shifted.width, 492.);
285
}
286
287
#[test]
288
fn search_takes_the_room_left_and_hides_without_any() {
289
let span = search_span(640., 200., 400.).expect("visible");
290
assert_eq!((span.left, span.width), (208., 184.));
291
assert_eq!(search_span(640., 300., 340.), None);
292
}
154
293
}
@@ -12,6 +12,11 @@ use crate::updater::UpdateStatus;12
12
13
pub const TITLE_BAR_HEIGHT: f32 = 40.;13
pub const TITLE_BAR_HEIGHT: f32 = 40.;14
const SEARCH_WIDTH: f32 = 380.;14
const SEARCH_WIDTH: f32 = 380.;15
const SEARCH_MIN_WIDTH: f32 = 240.;16
const SEARCH_MIN_VISIBLE_WIDTH: f32 = 36.;17
const SEARCH_HEIGHT: f32 = 28.;18
const SEARCH_GAP: f32 = 8.;19
const SHORTCUT_MIN_WIDTH: f32 = 200.;15
const SEARCH_HINT: &str = "Search chats, people and channels";20
const SEARCH_HINT: &str = "Search chats, people and channels";16
const SHORTCUT_HINT: &str = "Ctrl K";21
const SHORTCUT_HINT: &str = "Ctrl K";17
const APP_ICON_SIZE: f32 = 18.;22
const APP_ICON_SIZE: f32 = 18.;@@ -32,8 +37,6 @@ fn mode_pill(label: &'static str) -> Div {32
.flex()37
.flex()33
.items_center()38
.items_center()34
.rounded_full()39
.rounded_full()35
.border_1()36
.border_color(theme::amber().opacity(0.5))37
.bg(theme::amber().opacity(0.14))40
.bg(theme::amber().opacity(0.14))38
.text_size(px(11.))41
.text_size(px(11.))39
.font_weight(FontWeight::SEMIBOLD)42
.font_weight(FontWeight::SEMIBOLD)@@ -90,65 +93,201 @@ pub fn update_button(90
)93
)91
}94
}92
95
96
#[derive(Clone, Copy, Debug, PartialEq)]97
struct SearchSpan {98
left: f32,99
width: f32,100
}101
102
fn search_span(window_width: f32, leading_end: f32, trailing_start: f32) -> Option<SearchSpan> {103
let start = leading_end + SEARCH_GAP;104
let end = trailing_start - SEARCH_GAP;105
let room = end - start;106
if room < SEARCH_MIN_VISIBLE_WIDTH {107
return None;108
}109
let center = window_width / 2.;110
let centered_width = (2. * (center - start).min(end - center)).min(SEARCH_WIDTH);111
let width = centered_width.max(SEARCH_MIN_WIDTH).min(room);112
let left = (center - width / 2.).clamp(start, end - width);113
Some(SearchSpan { left, width })114
}115
116
#[derive(Clone, Copy, PartialEq)]117
struct Reserved {118
leading_end: f32,119
trailing_from_right: f32,120
}121
122
#[derive(IntoElement)]123
struct TitleBarRow {124
mode_label: Option<&'static str>,125
update: Option<AnyElement>,126
own: Option<AnyElement>,127
on_search: Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>,128
}129
93
pub fn render_title_bar(130
pub fn render_title_bar(94
mode_label: Option<&'static str>,131
mode_label: Option<&'static str>,95
update: Option<AnyElement>,132
update: Option<AnyElement>,96
own: Option<AnyElement>,133
own: Option<AnyElement>,97
on_search: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,134
on_search: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,98
) -> impl IntoElement {135
) -> impl IntoElement {99
let search = h_flex()136
TitleBarRow {137
mode_label,138
update,139
own,140
on_search: Box::new(on_search),141
}142
}143
144
fn search_box(145
span: SearchSpan,146
on_search: Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>,147
) -> impl IntoElement {148
h_flex()100
.id("title-search")149
.id("title-search")101
.debug_selector(|| "shell/title-bar/search".into())150
.debug_selector(|| "shell/title-bar/search".into())102
.occlude()151
.occlude()103
.w(px(SEARCH_WIDTH))152
.absolute()104
.h(px(28.))153
.top(px((TITLE_BAR_HEIGHT - SEARCH_HEIGHT) / 2.))154
.left(px(span.left))155
.w(px(span.width))156
.h(px(SEARCH_HEIGHT))105
.px(px(10.))157
.px(px(10.))106
.gap(px(8.))158
.gap(px(8.))107
.items_center()159
.items_center()160
.overflow_hidden()108
.rounded(px(6.))161
.rounded(px(6.))109
.bg(theme::surface())162
.bg(theme::surface())110
.cursor_pointer()163
.cursor_pointer()111
.text_size(px(12.))164
.text_size(px(12.))112
.text_color(theme::text_muted())165
.text_color(theme::text_muted())113
.child(icon(IconName::Search, 14., theme::text_muted()))114
.child(div().flex_1().child(SEARCH_HINT))115
.child(166
.child(116
div()167
div()117
.px(px(6.))168
.flex_none()118
.py(px(1.))169
.child(icon(IconName::Search, 14., theme::text_muted())),119
.rounded(px(4.))120
.bg(theme::surface_raised())121
.text_size(px(11.))122
.child(SHORTCUT_HINT),123
)170
)124
.on_click(on_search);171
.child(div().flex_1().min_w_0().truncate().child(SEARCH_HINT))125
let bar = TitleBar::new()172
.when(span.width >= SHORTCUT_MIN_WIDTH, |search| {126
.h(px(TITLE_BAR_HEIGHT))173
search.child(127
.border_b_0()174
div()128
.bg(theme::background())175
.flex_none()129
.child(176
.px(px(6.))130
h_flex()177
.py(px(1.))131
.flex_1()178
.rounded(px(4.))132
.h_full()179
.bg(theme::surface_raised())133
.gap(px(12.))180
.text_size(px(11.))134
.items_center()181
.child(SHORTCUT_HINT),135
.child(img(app_icon()).size(px(APP_ICON_SIZE)).flex_none())182
)136
.child(183
})137
div()184
.on_click(move |event, window, cx| on_search(event, window, cx))138
.text_size(px(13.))185
}139
.font_weight(FontWeight::SEMIBOLD)186
140
.text_color(theme::text())187
impl RenderOnce for TitleBarRow {141
.child(app_base::APP_NAME),188
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {142
)189
let reserved = window.use_keyed_state("title-bar-reserved", cx, |_, _| None::<Reserved>);143
.children(mode_label.map(mode_pill))190
let window_width = f32::from(window.viewport_size().width);144
.child(div().flex_1().flex().justify_center().child(search))191
let span = (*reserved.read(cx)).and_then(|reserved| {145
.children(update)192
search_span(146
.children(own)193
window_width,147
.child(div().w(px(4.))),194
reserved.leading_end,148
);195
window_width - reserved.trailing_from_right,149
div()196
)150
.debug_selector(|| "shell/title-bar".into())197
});151
.flex_none()198
let leading = h_flex()152
.w_full()199
.debug_selector(|| "shell/title-bar/leading".into())153
.child(bar)200
.flex_none()201
.h_full()202
.gap(px(12.))203
.items_center()204
.child(img(app_icon()).size(px(APP_ICON_SIZE)).flex_none())205
.child(206
div()207
.text_size(px(13.))208
.font_weight(FontWeight::SEMIBOLD)209
.text_color(theme::text())210
.child(app_base::APP_NAME),211
)212
.children(self.mode_label.map(mode_pill));213
let trailing = h_flex()214
.debug_selector(|| "shell/title-bar/trailing".into())215
.flex_none()216
.h_full()217
.gap(px(12.))218
.items_center()219
.children(self.update)220
.children(self.own)221
.child(div().w(px(4.)));222
let row = h_flex()223
.flex_1()224
.h_full()225
.gap(px(12.))226
.items_center()227
.child(leading)228
.child(div().flex_1())229
.child(trailing)230
.on_children_prepainted(move |children, window, cx| {231
let [leading, _, trailing] = children[..] else {232
return;233
};234
let measured = Reserved {235
leading_end: f32::from(leading.right()),236
trailing_from_right: f32::from(window.viewport_size().width - trailing.left()),237
};238
reserved.update(cx, |current, cx| {239
let unchanged = current.is_some_and(|current| {240
(current.leading_end - measured.leading_end).abs() < 0.5241
&& (current.trailing_from_right - measured.trailing_from_right).abs()242
< 0.5243
});244
if !unchanged {245
*current = Some(measured);246
cx.notify();247
}248
});249
});250
let bar = TitleBar::new()251
.h(px(TITLE_BAR_HEIGHT))252
.border_b_0()253
.bg(theme::background())254
.child(row);255
let on_search = self.on_search;256
div()257
.debug_selector(|| "shell/title-bar".into())258
.relative()259
.flex_none()260
.w_full()261
.child(bar)262
.children(span.map(|span| search_box(span, on_search)))263
}264
}265
266
#[cfg(test)]267
mod tests {268
use super::{SEARCH_MIN_WIDTH, SEARCH_WIDTH, search_span};269
270
#[test]271
fn search_stays_centered_while_it_fits() {272
let span = search_span(1280., 200., 1080.).expect("visible");273
assert_eq!(span.width, SEARCH_WIDTH);274
assert_eq!(span.left + span.width / 2., 640.);275
}276
277
#[test]278
fn search_shrinks_centered_before_it_shifts() {279
let span = search_span(800., 200., 580.).expect("visible");280
assert_eq!(span.left + span.width / 2., 400.);281
assert_eq!(span.width, 344.);282
let shifted = search_span(800., 200., 500.).expect("visible");283
assert_eq!(shifted.width, SEARCH_MIN_WIDTH);284
assert_eq!(shifted.left + shifted.width, 492.);285
}286
287
#[test]288
fn search_takes_the_room_left_and_hides_without_any() {289
let span = search_span(640., 200., 400.).expect("visible");290
assert_eq!((span.left, span.width), (208., 184.));291
assert_eq!(search_span(640., 300., 340.), None);292
}154
}293
}@@ -14,7 +14,7 @@ use super::widgets::icon;
14
14
use crate::app_state::AppState;
15
15
use crate::call::TransferCandidate;
16
16
use crate::fuzzy;
17
use crate::theme;
17
use crate::theme::{self, ElevatedSurface as _};
18
18
19
19
const MAX_RESULTS: usize = 6;
20
20
const CARD_WIDTH: f32 = 440.;
@@ -267,11 +267,8 @@ impl Render for TransferPicker {
267
267
.p(px(CARD_PADDING))
268
268
.gap(px(SECTION_GAP))
269
269
.rounded(px(CARD_RADIUS))
270
.bg(theme::background())
271
.border_1()
272
.border_color(theme::border_strong())
270
.dialog_surface()
273
271
.text_color(theme::text())
274
.shadow(theme::dialog_shadow())
275
272
.occlude()
276
273
.on_key_down(cx.listener(Self::on_key_down))
277
274
.child(
@@ -14,7 +14,7 @@ use super::widgets::icon;14
use crate::app_state::AppState;14
use crate::app_state::AppState;15
use crate::call::TransferCandidate;15
use crate::call::TransferCandidate;16
use crate::fuzzy;16
use crate::fuzzy;17
use crate::theme;17
use crate::theme::{self, ElevatedSurface as _};18
18
19
const MAX_RESULTS: usize = 6;19
const MAX_RESULTS: usize = 6;20
const CARD_WIDTH: f32 = 440.;20
const CARD_WIDTH: f32 = 440.;@@ -267,11 +267,8 @@ impl Render for TransferPicker {267
.p(px(CARD_PADDING))267
.p(px(CARD_PADDING))268
.gap(px(SECTION_GAP))268
.gap(px(SECTION_GAP))269
.rounded(px(CARD_RADIUS))269
.rounded(px(CARD_RADIUS))270
.bg(theme::background())270
.dialog_surface()271
.border_1()272
.border_color(theme::border_strong())273
.text_color(theme::text())271
.text_color(theme::text())274
.shadow(theme::dialog_shadow())275
.occlude()272
.occlude()276
.on_key_down(cx.listener(Self::on_key_down))273
.on_key_down(cx.listener(Self::on_key_down))277
.child(274
.child(@@ -6,8 +6,10 @@ use serde::{Deserialize, Serialize};
6
6
7
7
use crate::markdown::escape_html;
8
8
use crate::spans::{FontSize, Span};
9
use crate::table::{TABLE_MARK, Table, markdown_table};
9
10
10
11
pub const MAX_DEPTH: u8 = 2;
12
pub const MAX_HEADING: u8 = 3;
11
13
pub const OBJECT_MARK: char = '\u{FFFC}';
12
14
const BULLETS: [&str; 3] = ["•", "◦", "▪"];
13
15
const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "];
@@ -125,6 +127,8 @@ pub enum LineKind {
125
127
Numbered(u8),
126
128
Quote,
127
129
Code(Option<String>),
130
Heading(u8),
131
Table(Table),
128
132
}
129
133
130
134
impl LineKind {
@@ -132,6 +136,10 @@ impl LineKind {
132
136
matches!(self, LineKind::Bullet(_) | LineKind::Numbered(_))
133
137
}
134
138
139
pub fn is_table(&self) -> bool {
140
matches!(self, LineKind::Table(_))
141
}
142
135
143
pub fn depth(&self) -> u8 {
136
144
match self {
137
145
LineKind::Bullet(depth) | LineKind::Numbered(depth) => *depth,
@@ -430,7 +438,10 @@ impl Draft {
430
438
pub fn plain_text(&self) -> String {
431
439
self.slice(0..self.text.len())
432
440
.into_iter()
433
.map(|line| line.content)
441
.map(|line| match &line.kind {
442
LineKind::Table(table) => table.plain_text(),
443
_ => line.content,
444
})
434
445
.collect::<Vec<_>>()
435
446
.join("\n")
436
447
.replace(&format!(" {OBJECT_MARK} "), " ")
@@ -762,7 +773,11 @@ impl Draft {
762
773
self.splice(content.clone(), "", &[]);
763
774
Some(self.set_line_kind(index, LineKind::Code(language), None, content.start))
764
775
}
765
LineKind::Quote if !shift => None,
776
LineKind::Heading(_) | LineKind::Table(_) => None,
777
LineKind::Quote if content.is_empty() && !shift => {
778
self.lines[index] = LineKind::Text;
779
Some(cursor)
780
}
766
781
LineKind::Quote => {
767
782
self.splice(cursor..cursor, "\n", &[]);
768
783
self.lines[index] = LineKind::Quote;
@@ -823,6 +838,9 @@ impl Draft {
823
838
if cursor != line.end || index + 1 >= self.lines.len() {
824
839
return None;
825
840
}
841
if self.lines[index + 1].is_table() {
842
return Some(cursor);
843
}
826
844
let next_marker = self.marker_range(index + 1);
827
845
if next_marker.is_empty() {
828
846
return None;
@@ -847,11 +865,22 @@ impl Draft {
847
865
cursor
848
866
})
849
867
}
868
LineKind::Table(_) => None,
869
LineKind::Heading(_) => (cursor == line.start).then(|| {
870
self.lines[index] = LineKind::Text;
871
cursor
872
}),
850
873
LineKind::Quote
851
874
if cursor == line.start && (index == 0 || self.lines[index - 1] != kind) =>
852
875
{
853
self.lines[index] = LineKind::Text;
854
Some(cursor)
876
let joins_previous =
877
index > 0 && !content.is_empty() && !self.lines[index - 1].is_table();
878
if !joins_previous {
879
self.lines[index] = LineKind::Text;
880
return Some(cursor);
881
}
882
self.splice(line.start - 1..line.start, "", &[]);
883
Some(self.repair(line.start - 1))
855
884
}
856
885
_ if cursor == line.start && index > 0 => {
857
886
self.splice(line.start - 1..content.start, "", &[]);
@@ -899,6 +928,9 @@ impl Draft {
899
928
.all(|index| self.lines[index].same_format(&kind));
900
929
for index in lines {
901
930
let current = self.lines[index].clone();
931
if current.is_table() {
932
continue;
933
}
902
934
let target = if all {
903
935
LineKind::Text
904
936
} else if current.same_format(&kind) {
@@ -915,6 +947,120 @@ impl Draft {
915
947
self.repair(0);
916
948
}
917
949
950
pub fn table(&self, index: usize) -> Option<&Table> {
951
match self.lines.get(index)? {
952
LineKind::Table(table) => Some(table),
953
_ => None,
954
}
955
}
956
957
/// Cell edits change no text, so the journal stays as it is.
958
pub fn set_table(&mut self, index: usize, table: Table) {
959
if let Some(kind @ LineKind::Table(_)) = self.lines.get_mut(index) {
960
*kind = LineKind::Table(table);
961
}
962
}
963
964
/// The table goes in place of an empty text line, otherwise below the cursor's line, and
965
/// a text line follows it. Returns the table's line.
966
pub fn insert_table(&mut self, cursor: usize, table: Table) -> usize {
967
self.journal = Journal::default();
968
let index = self.line_at(cursor);
969
let line = self.line_ranges()[index].clone();
970
let mark = TABLE_MARK.to_string();
971
let replaces_line = self.lines[index] == LineKind::Text && line.is_empty();
972
let table_index = if replaces_line {
973
self.splice(line, &mark, &[]);
974
index
975
} else {
976
self.splice(line.end..line.end, &format!("\n{mark}"), &[]);
977
index + 1
978
};
979
self.lines[table_index] = LineKind::Table(table);
980
if table_index + 1 == self.lines.len() {
981
let end = self.text.len();
982
self.splice(end..end, "\n", &[]);
983
self.lines[table_index + 1] = LineKind::Text;
984
}
985
table_index
986
}
987
988
/// Returns where the cursor goes: the start of the line that took the table's place.
989
pub fn remove_table(&mut self, index: usize) -> usize {
990
self.journal = Journal::default();
991
let ranges = self.line_ranges();
992
let line = ranges[index].clone();
993
if let Some(next) = ranges.get(index + 1) {
994
let next_kind = self.lines[index + 1].clone();
995
self.splice(line.start..next.start, "", &[]);
996
self.lines[index] = next_kind;
997
return self.repair(line.start);
998
}
999
if index > 0 {
1000
let start = ranges[index - 1].end;
1001
self.splice(start..line.end, "", &[]);
1002
return self.repair(start);
1003
}
1004
self.splice(line, "", &[]);
1005
self.lines[index] = LineKind::Text;
1006
0
1007
}
1008
1009
/// Where the cursor lands when it leaves table `index` downwards or upwards; a text line
1010
/// is added when the table is the last or the first line.
1011
pub fn line_beside_table(&mut self, index: usize, below: bool) -> usize {
1012
self.journal = Journal::default();
1013
let ranges = self.line_ranges();
1014
if below {
1015
if let Some(next) = ranges.get(index + 1) {
1016
return next.start;
1017
}
1018
let end = self.text.len();
1019
self.splice(end..end, "\n", &[]);
1020
self.lines[index + 1] = LineKind::Text;
1021
return end + 1;
1022
}
1023
if index > 0 {
1024
return ranges[index - 1].end;
1025
}
1026
self.splice(0..0, "\n", &[]);
1027
self.lines[0] = LineKind::Text;
1028
0
1029
}
1030
1031
pub fn table_at(&self, offset: usize) -> Option<usize> {
1032
let index = self.line_at(offset);
1033
self.lines[index].is_table().then_some(index)
1034
}
1035
1036
/// The table right above, when `cursor` is at the start of its line.
1037
pub fn table_before(&self, cursor: usize) -> Option<usize> {
1038
let index = self.line_at(cursor);
1039
let at_start = self.line_ranges()[index].start == cursor;
1040
(at_start && index > 0 && self.lines[index - 1].is_table()).then(|| index - 1)
1041
}
1042
1043
/// The table right below, when `cursor` is at the end of its line.
1044
pub fn table_after(&self, cursor: usize) -> Option<usize> {
1045
let index = self.line_at(cursor);
1046
let at_end = self.line_ranges()[index].end == cursor;
1047
(at_end && self.lines.get(index + 1).is_some_and(LineKind::is_table)).then_some(index + 1)
1048
}
1049
1050
/// Down or Right at the very end of a quote that ends the draft: a text line below it,
1051
/// like the empty paragraph Teams keeps after a quote.
1052
pub fn leave_quote_at_end(&mut self, cursor: usize) -> Option<usize> {
1053
self.journal = Journal::default();
1054
let end = self.text.len();
1055
let last = self.lines.len() - 1;
1056
if cursor != end || self.lines[last] != LineKind::Quote {
1057
return None;
1058
}
1059
self.splice(end..end, "\n", &[]);
1060
self.lines[last + 1] = LineKind::Text;
1061
Some(end + 1)
1062
}
1063
918
1064
pub fn slice(&self, range: Range<usize>) -> Vec<DraftLine> {
919
1065
let mut lines = Vec::new();
920
1066
for (index, line) in self.line_ranges().into_iter().enumerate() {
@@ -981,6 +1127,13 @@ impl Draft {
981
1127
let line_was_empty = self.lines[index] == LineKind::Text
982
1128
&& range.start == content.start
983
1129
&& range.end >= tail_end;
1130
let separated;
1131
let lines = if !line_was_empty && lines.first().is_some_and(|line| line.kind.is_table()) {
1132
separated = [&[DraftLine::text("")][..], lines].concat();
1133
&separated[..]
1134
} else {
1135
lines
1136
};
984
1137
let joined = lines
985
1138
.iter()
986
1139
.map(|line| line.content.as_str())
@@ -1057,6 +1210,23 @@ impl Draft {
1057
1210
html.push_str(&joined_inline(run));
1058
1211
html.push_str("</blockquote>");
1059
1212
}
1213
LineKind::Heading(_) => {
1214
for line in run {
1215
let level = match line.kind {
1216
LineKind::Heading(level) => level.clamp(1, MAX_HEADING),
1217
_ => 1,
1218
};
1219
let inline = inline_html(&line.content, &line.marks);
1220
html.push_str(&format!("<h{level}>{inline}</h{level}>"));
1221
}
1222
}
1223
LineKind::Table(_) => {
1224
for line in run {
1225
if let LineKind::Table(table) = &line.kind {
1226
html.push_str(&table.to_html());
1227
}
1228
}
1229
}
1060
1230
LineKind::Code(language) => {
1061
1231
match language {
1062
1232
Some(language) => html.push_str(&format!(
@@ -1362,8 +1532,45 @@ impl Draft {
1362
1532
}
1363
1533
}
1364
1534
1535
/// A table line holds its mark alone: text typed next to it moves to its own line, a mark
1536
/// without its table is dropped and a table without its mark becomes text.
1537
fn repair_tables(&mut self, mut cursor: usize) -> usize {
1538
let mark_length = TABLE_MARK.len_utf8();
1539
let mut index = 0;
1540
while index < self.lines.len() {
1541
let line = self.line_ranges()[index].clone();
1542
let found = self.text[line.clone()].find(TABLE_MARK);
1543
match (self.lines[index].clone(), found) {
1544
(LineKind::Table(_), None) => self.lines[index] = LineKind::Text,
1545
(LineKind::Table(table), Some(at)) if at > 0 => {
1546
let split = line.start + at;
1547
self.splice(split..split, "\n", &[]);
1548
self.lines[index] = LineKind::Text;
1549
self.lines[index + 1] = LineKind::Table(table);
1550
cursor += usize::from(cursor > split);
1551
}
1552
(LineKind::Table(_), Some(_)) if line.len() > mark_length => {
1553
let split = line.start + mark_length;
1554
self.splice(split..split, "\n", &[]);
1555
cursor += usize::from(cursor > split);
1556
}
1557
(LineKind::Table(_), Some(_)) => {}
1558
(_, Some(at)) => {
1559
let mark = line.start + at..line.start + at + mark_length;
1560
self.splice(mark.clone(), "", &[]);
1561
cursor = map_offset(&[(mark, String::new())], cursor);
1562
continue;
1563
}
1564
(_, None) => {}
1565
}
1566
index += 1;
1567
}
1568
cursor
1569
}
1570
1365
1571
/// List items whose marker was edited away become text; numbered items are renumbered.
1366
fn repair(&mut self, mut cursor: usize) -> usize {
1572
fn repair(&mut self, cursor: usize) -> usize {
1573
let mut cursor = self.repair_tables(cursor);
1367
1574
for index in 0..self.lines.len() {
1368
1575
let kind = self.lines[index].clone();
1369
1576
if !kind.is_list() {
@@ -1399,7 +1606,11 @@ fn marker_text(kind: &LineKind, number: u32) -> String {
1399
1606
match kind {
1400
1607
LineKind::Bullet(depth) => bullet_marker(*depth),
1401
1608
LineKind::Numbered(_) => format!("{number}. "),
1402
LineKind::Text | LineKind::Quote | LineKind::Code(_) => String::new(),
1609
LineKind::Text
1610
| LineKind::Quote
1611
| LineKind::Code(_)
1612
| LineKind::Heading(_)
1613
| LineKind::Table(_) => String::new(),
1403
1614
}
1404
1615
}
1405
1616
@@ -1430,7 +1641,9 @@ fn numbered_marker(line: &str) -> Option<(usize, u32)> {
1430
1641
fn line_shortcut(before: &str) -> Option<(LineKind, u32)> {
1431
1642
match before {
1432
1643
"- " | "* " => Some((LineKind::Bullet(0), 1)),
1433
"> " => Some((LineKind::Quote, 1)),
1644
">" => Some((LineKind::Quote, 1)),
1645
_ if before.starts_with('#') => heading_prefix(before)
1646
.and_then(|(level, rest)| rest.is_empty().then_some((LineKind::Heading(level), 1))),
1434
1647
_ => {
1435
1648
let digits = before.strip_suffix(". ")?;
1436
1649
let all_digits = !digits.is_empty()
@@ -1540,7 +1753,7 @@ fn typed_inline(before: &str) -> Option<(Range<usize>, Range<usize>, MarkKind)>
1540
1753
let usable = !body[open + 1..].trim().is_empty() && !body[..open].ends_with('`');
1541
1754
return usable.then(|| (open..open + 1, body.len()..end, MarkKind::Code));
1542
1755
}
1543
for marker in ['*', '_'] {
1756
for (marker, kind) in [('*', MarkKind::Bold), ('_', MarkKind::Italic)] {
1544
1757
if let Some(body) = before.strip_suffix(marker) {
1545
1758
if body.ends_with(marker) {
1546
1759
return None;
@@ -1548,7 +1761,7 @@ fn typed_inline(before: &str) -> Option<(Range<usize>, Range<usize>, MarkKind)>
1548
1761
let open = body.rfind(marker)?;
1549
1762
let opening_ok = !word_before(&body[..open]) && !body[..open].ends_with(marker);
1550
1763
return (opening_ok && valid_inner(&body[open + 1..]))
1551
.then(|| (open..open + 1, body.len()..end, MarkKind::Italic));
1764
.then(|| (open..open + 1, body.len()..end, kind));
1552
1765
}
1553
1766
}
1554
1767
None
@@ -1702,10 +1915,16 @@ pub fn has_markdown(text: &str) -> bool {
1702
1915
}
1703
1916
1704
1917
fn markdown_lines(text: &str) -> Vec<DraftLine> {
1918
let sources: Vec<&str> = text
1919
.split('\n')
1920
.map(|raw| raw.strip_suffix('\r').unwrap_or(raw))
1921
.collect();
1705
1922
let mut lines = Vec::new();
1706
1923
let mut code: Option<Option<String>> = None;
1707
for raw in text.split('\n') {
1708
let raw = raw.strip_suffix('\r').unwrap_or(raw);
1924
let mut position = 0;
1925
while position < sources.len() {
1926
let raw = sources[position];
1927
position += 1;
1709
1928
let trimmed = raw.trim_start();
1710
1929
if let Some(language) = &code {
1711
1930
if trimmed.starts_with(FENCE) && trimmed.trim_end() == FENCE {
@@ -1727,12 +1946,23 @@ fn markdown_lines(text: &str) -> Vec<DraftLine> {
1727
1946
code = Some(language);
1728
1947
continue;
1729
1948
}
1949
if let Some((rows, consumed)) = markdown_table(&sources[position - 1..]) {
1950
let rows = rows
1951
.into_iter()
1952
.map(|row| row.iter().map(|cell| parse_inline(cell).0).collect())
1953
.collect();
1954
lines.push(table_line(Table::from_rows(rows)));
1955
position += consumed - 1;
1956
continue;
1957
}
1730
1958
let indent: usize = raw[..raw.len() - trimmed.len()]
1731
1959
.chars()
1732
1960
.map(|character| if character == '\t' { 4 } else { 1 })
1733
1961
.sum();
1734
1962
let depth = ((indent / MARKDOWN_INDENT) as u8).min(MAX_DEPTH);
1735
let (kind, number, content) = if let Some(rest) = PASTED_BULLETS
1963
let (kind, number, content) = if let Some((level, rest)) = heading_prefix(trimmed) {
1964
(LineKind::Heading(level), None, rest)
1965
} else if let Some(rest) = PASTED_BULLETS
1736
1966
.iter()
1737
1967
.find_map(|bullet| trimmed.strip_prefix(bullet))
1738
1968
{
@@ -1758,6 +1988,24 @@ fn markdown_lines(text: &str) -> Vec<DraftLine> {
1758
1988
lines
1759
1989
}
1760
1990
1991
fn table_line(table: Table) -> DraftLine {
1992
DraftLine {
1993
kind: LineKind::Table(table),
1994
number: None,
1995
content: TABLE_MARK.to_string(),
1996
marks: Vec::new(),
1997
}
1998
}
1999
2000
/// `# ` to `###### `: the level, capped at the three Teams offers, and the rest of the line.
2001
fn heading_prefix(line: &str) -> Option<(u8, &str)> {
2002
let hashes = line.bytes().take_while(|byte| *byte == b'#').count();
2003
let rest = line[hashes..].strip_prefix(' ')?;
2004
(1..=6)
2005
.contains(&hashes)
2006
.then(|| ((hashes as u8).min(MAX_HEADING), rest))
2007
}
2008
1761
2009
fn parse_inline(source: &str) -> (String, Vec<Mark>) {
1762
2010
let mut text = String::with_capacity(source.len());
1763
2011
let mut marks = Vec::new();
@@ -1849,6 +2097,17 @@ fn inline_at(rest: &str, previous: Option<char>) -> Option<(&str, usize, MarkKin
1849
2097
None
1850
2098
}
1851
2099
2100
fn cell_text(spans: &[Span]) -> String {
2101
let mut builder = SpanLines::default();
2102
builder.walk(spans, &LineKind::Text, &[]);
2103
builder
2104
.finish()
2105
.into_iter()
2106
.map(|line| line.content)
2107
.collect::<Vec<_>>()
2108
.join("\n")
2109
}
2110
1852
2111
#[derive(Default)]
1853
2112
struct SpanLines {
1854
2113
lines: Vec<DraftLine>,
@@ -1936,9 +2195,10 @@ impl SpanLines {
1936
2195
};
1937
2196
self.start_line(&continued, None);
1938
2197
}
1939
Span::Heading { children, .. } => {
1940
self.start_line(&LineKind::Text, None);
1941
self.walk(children, &LineKind::Text, &with(MarkKind::Bold));
2198
Span::Heading { level, children } => {
2199
let heading = LineKind::Heading((*level).clamp(1, MAX_HEADING));
2200
self.start_line(&heading, None);
2201
self.walk(children, &heading, marks);
1942
2202
self.open = false;
1943
2203
}
1944
2204
Span::CodeBlock { language, code } => {
@@ -1977,15 +2237,11 @@ impl SpanLines {
1977
2237
self.open = false;
1978
2238
}
1979
2239
Span::Table { rows, .. } => {
1980
for row in rows {
1981
self.start_line(&LineKind::Text, None);
1982
for (position, cell) in row.iter().enumerate() {
1983
if position > 0 {
1984
self.append(" | ", &LineKind::Text, &[]);
1985
}
1986
self.walk(cell, &LineKind::Text, marks);
1987
}
1988
}
2240
let rows = rows
2241
.iter()
2242
.map(|row| row.iter().map(|cell| cell_text(cell)).collect())
2243
.collect();
2244
self.lines.push(table_line(Table::from_rows(rows)));
1989
2245
self.open = false;
1990
2246
}
1991
2247
Span::Image { .. } | Span::Quote { .. } => {}
@@ -2081,7 +2337,7 @@ mod tests {
2081
2337
draft.marks(),
2082
2338
[
2083
2339
mark(2..6, MarkKind::Bold),
2084
mark(11..13, MarkKind::Italic),
2340
mark(11..13, MarkKind::Bold),
2085
2341
mark(17..19, MarkKind::Italic),
2086
2342
mark(20..24, MarkKind::Strike),
2087
2343
mark(25..29, MarkKind::Code),
@@ -2357,9 +2613,12 @@ mod tests {
2357
2613
let numbered = typed_draft("1. one");
2358
2614
assert_eq!(numbered.text(), "1. one");
2359
2615
assert_eq!(numbered.lines(), [LineKind::Numbered(0)]);
2360
let quote = typed_draft("> said");
2616
let quote = typed_draft(">said");
2361
2617
assert_eq!(quote.text(), "said");
2362
2618
assert_eq!(quote.lines(), [LineKind::Quote]);
2619
let spaced = typed_draft("> said");
2620
assert_eq!(spaced.text(), " said");
2621
assert_eq!(spaced.lines(), [LineKind::Quote]);
2363
2622
}
2364
2623
2365
2624
#[test]
@@ -6,8 +6,10 @@ use serde::{Deserialize, Serialize};6
6
7
use crate::markdown::escape_html;7
use crate::markdown::escape_html;8
use crate::spans::{FontSize, Span};8
use crate::spans::{FontSize, Span};9
use crate::table::{TABLE_MARK, Table, markdown_table};9
10
10
pub const MAX_DEPTH: u8 = 2;11
pub const MAX_DEPTH: u8 = 2;12
pub const MAX_HEADING: u8 = 3;11
pub const OBJECT_MARK: char = '\u{FFFC}';13
pub const OBJECT_MARK: char = '\u{FFFC}';12
const BULLETS: [&str; 3] = ["•", "◦", "▪"];14
const BULLETS: [&str; 3] = ["•", "◦", "▪"];13
const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "];15
const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "];@@ -125,6 +127,8 @@ pub enum LineKind {125
Numbered(u8),127
Numbered(u8),126
Quote,128
Quote,127
Code(Option<String>),129
Code(Option<String>),130
Heading(u8),131
Table(Table),128
}132
}129
133
130
impl LineKind {134
impl LineKind {@@ -132,6 +136,10 @@ impl LineKind {132
matches!(self, LineKind::Bullet(_) | LineKind::Numbered(_))136
matches!(self, LineKind::Bullet(_) | LineKind::Numbered(_))133
}137
}134
138
139
pub fn is_table(&self) -> bool {140
matches!(self, LineKind::Table(_))141
}142
135
pub fn depth(&self) -> u8 {143
pub fn depth(&self) -> u8 {136
match self {144
match self {137
LineKind::Bullet(depth) | LineKind::Numbered(depth) => *depth,145
LineKind::Bullet(depth) | LineKind::Numbered(depth) => *depth,@@ -430,7 +438,10 @@ impl Draft {430
pub fn plain_text(&self) -> String {438
pub fn plain_text(&self) -> String {431
self.slice(0..self.text.len())439
self.slice(0..self.text.len())432
.into_iter()440
.into_iter()433
.map(|line| line.content)441
.map(|line| match &line.kind {442
LineKind::Table(table) => table.plain_text(),443
_ => line.content,444
})434
.collect::<Vec<_>>()445
.collect::<Vec<_>>()435
.join("\n")446
.join("\n")436
.replace(&format!(" {OBJECT_MARK} "), " ")447
.replace(&format!(" {OBJECT_MARK} "), " ")@@ -762,7 +773,11 @@ impl Draft {762
self.splice(content.clone(), "", &[]);773
self.splice(content.clone(), "", &[]);763
Some(self.set_line_kind(index, LineKind::Code(language), None, content.start))774
Some(self.set_line_kind(index, LineKind::Code(language), None, content.start))764
}775
}765
LineKind::Quote if !shift => None,776
LineKind::Heading(_) | LineKind::Table(_) => None,777
LineKind::Quote if content.is_empty() && !shift => {778
self.lines[index] = LineKind::Text;779
Some(cursor)780
}766
LineKind::Quote => {781
LineKind::Quote => {767
self.splice(cursor..cursor, "\n", &[]);782
self.splice(cursor..cursor, "\n", &[]);768
self.lines[index] = LineKind::Quote;783
self.lines[index] = LineKind::Quote;@@ -823,6 +838,9 @@ impl Draft {823
if cursor != line.end || index + 1 >= self.lines.len() {838
if cursor != line.end || index + 1 >= self.lines.len() {824
return None;839
return None;825
}840
}841
if self.lines[index + 1].is_table() {842
return Some(cursor);843
}826
let next_marker = self.marker_range(index + 1);844
let next_marker = self.marker_range(index + 1);827
if next_marker.is_empty() {845
if next_marker.is_empty() {828
return None;846
return None;@@ -847,11 +865,22 @@ impl Draft {847
cursor865
cursor848
})866
})849
}867
}868
LineKind::Table(_) => None,869
LineKind::Heading(_) => (cursor == line.start).then(|| {870
self.lines[index] = LineKind::Text;871
cursor872
}),850
LineKind::Quote873
LineKind::Quote851
if cursor == line.start && (index == 0 || self.lines[index - 1] != kind) =>874
if cursor == line.start && (index == 0 || self.lines[index - 1] != kind) =>852
{875
{853
self.lines[index] = LineKind::Text;876
let joins_previous =854
Some(cursor)877
index > 0 && !content.is_empty() && !self.lines[index - 1].is_table();878
if !joins_previous {879
self.lines[index] = LineKind::Text;880
return Some(cursor);881
}882
self.splice(line.start - 1..line.start, "", &[]);883
Some(self.repair(line.start - 1))855
}884
}856
_ if cursor == line.start && index > 0 => {885
_ if cursor == line.start && index > 0 => {857
self.splice(line.start - 1..content.start, "", &[]);886
self.splice(line.start - 1..content.start, "", &[]);@@ -899,6 +928,9 @@ impl Draft {899
.all(|index| self.lines[index].same_format(&kind));928
.all(|index| self.lines[index].same_format(&kind));900
for index in lines {929
for index in lines {901
let current = self.lines[index].clone();930
let current = self.lines[index].clone();931
if current.is_table() {932
continue;933
}902
let target = if all {934
let target = if all {903
LineKind::Text935
LineKind::Text904
} else if current.same_format(&kind) {936
} else if current.same_format(&kind) {@@ -915,6 +947,120 @@ impl Draft {915
self.repair(0);947
self.repair(0);916
}948
}917
949
950
pub fn table(&self, index: usize) -> Option<&Table> {951
match self.lines.get(index)? {952
LineKind::Table(table) => Some(table),953
_ => None,954
}955
}956
957
/// Cell edits change no text, so the journal stays as it is.958
pub fn set_table(&mut self, index: usize, table: Table) {959
if let Some(kind @ LineKind::Table(_)) = self.lines.get_mut(index) {960
*kind = LineKind::Table(table);961
}962
}963
964
/// The table goes in place of an empty text line, otherwise below the cursor's line, and965
/// a text line follows it. Returns the table's line.966
pub fn insert_table(&mut self, cursor: usize, table: Table) -> usize {967
self.journal = Journal::default();968
let index = self.line_at(cursor);969
let line = self.line_ranges()[index].clone();970
let mark = TABLE_MARK.to_string();971
let replaces_line = self.lines[index] == LineKind::Text && line.is_empty();972
let table_index = if replaces_line {973
self.splice(line, &mark, &[]);974
index975
} else {976
self.splice(line.end..line.end, &format!("\n{mark}"), &[]);977
index + 1978
};979
self.lines[table_index] = LineKind::Table(table);980
if table_index + 1 == self.lines.len() {981
let end = self.text.len();982
self.splice(end..end, "\n", &[]);983
self.lines[table_index + 1] = LineKind::Text;984
}985
table_index986
}987
988
/// Returns where the cursor goes: the start of the line that took the table's place.989
pub fn remove_table(&mut self, index: usize) -> usize {990
self.journal = Journal::default();991
let ranges = self.line_ranges();992
let line = ranges[index].clone();993
if let Some(next) = ranges.get(index + 1) {994
let next_kind = self.lines[index + 1].clone();995
self.splice(line.start..next.start, "", &[]);996
self.lines[index] = next_kind;997
return self.repair(line.start);998
}999
if index > 0 {1000
let start = ranges[index - 1].end;1001
self.splice(start..line.end, "", &[]);1002
return self.repair(start);1003
}1004
self.splice(line, "", &[]);1005
self.lines[index] = LineKind::Text;1006
01007
}1008
1009
/// Where the cursor lands when it leaves table `index` downwards or upwards; a text line1010
/// is added when the table is the last or the first line.1011
pub fn line_beside_table(&mut self, index: usize, below: bool) -> usize {1012
self.journal = Journal::default();1013
let ranges = self.line_ranges();1014
if below {1015
if let Some(next) = ranges.get(index + 1) {1016
return next.start;1017
}1018
let end = self.text.len();1019
self.splice(end..end, "\n", &[]);1020
self.lines[index + 1] = LineKind::Text;1021
return end + 1;1022
}1023
if index > 0 {1024
return ranges[index - 1].end;1025
}1026
self.splice(0..0, "\n", &[]);1027
self.lines[0] = LineKind::Text;1028
01029
}1030
1031
pub fn table_at(&self, offset: usize) -> Option<usize> {1032
let index = self.line_at(offset);1033
self.lines[index].is_table().then_some(index)1034
}1035
1036
/// The table right above, when `cursor` is at the start of its line.1037
pub fn table_before(&self, cursor: usize) -> Option<usize> {1038
let index = self.line_at(cursor);1039
let at_start = self.line_ranges()[index].start == cursor;1040
(at_start && index > 0 && self.lines[index - 1].is_table()).then(|| index - 1)1041
}1042
1043
/// The table right below, when `cursor` is at the end of its line.1044
pub fn table_after(&self, cursor: usize) -> Option<usize> {1045
let index = self.line_at(cursor);1046
let at_end = self.line_ranges()[index].end == cursor;1047
(at_end && self.lines.get(index + 1).is_some_and(LineKind::is_table)).then_some(index + 1)1048
}1049
1050
/// Down or Right at the very end of a quote that ends the draft: a text line below it,1051
/// like the empty paragraph Teams keeps after a quote.1052
pub fn leave_quote_at_end(&mut self, cursor: usize) -> Option<usize> {1053
self.journal = Journal::default();1054
let end = self.text.len();1055
let last = self.lines.len() - 1;1056
if cursor != end || self.lines[last] != LineKind::Quote {1057
return None;1058
}1059
self.splice(end..end, "\n", &[]);1060
self.lines[last + 1] = LineKind::Text;1061
Some(end + 1)1062
}1063
918
pub fn slice(&self, range: Range<usize>) -> Vec<DraftLine> {1064
pub fn slice(&self, range: Range<usize>) -> Vec<DraftLine> {919
let mut lines = Vec::new();1065
let mut lines = Vec::new();920
for (index, line) in self.line_ranges().into_iter().enumerate() {1066
for (index, line) in self.line_ranges().into_iter().enumerate() {@@ -981,6 +1127,13 @@ impl Draft {981
let line_was_empty = self.lines[index] == LineKind::Text1127
let line_was_empty = self.lines[index] == LineKind::Text982
&& range.start == content.start1128
&& range.start == content.start983
&& range.end >= tail_end;1129
&& range.end >= tail_end;1130
let separated;1131
let lines = if !line_was_empty && lines.first().is_some_and(|line| line.kind.is_table()) {1132
separated = [&[DraftLine::text("")][..], lines].concat();1133
&separated[..]1134
} else {1135
lines1136
};984
let joined = lines1137
let joined = lines985
.iter()1138
.iter()986
.map(|line| line.content.as_str())1139
.map(|line| line.content.as_str())@@ -1057,6 +1210,23 @@ impl Draft {1057
html.push_str(&joined_inline(run));1210
html.push_str(&joined_inline(run));1058
html.push_str("</blockquote>");1211
html.push_str("</blockquote>");1059
}1212
}1213
LineKind::Heading(_) => {1214
for line in run {1215
let level = match line.kind {1216
LineKind::Heading(level) => level.clamp(1, MAX_HEADING),1217
_ => 1,1218
};1219
let inline = inline_html(&line.content, &line.marks);1220
html.push_str(&format!("<h{level}>{inline}</h{level}>"));1221
}1222
}1223
LineKind::Table(_) => {1224
for line in run {1225
if let LineKind::Table(table) = &line.kind {1226
html.push_str(&table.to_html());1227
}1228
}1229
}1060
LineKind::Code(language) => {1230
LineKind::Code(language) => {1061
match language {1231
match language {1062
Some(language) => html.push_str(&format!(1232
Some(language) => html.push_str(&format!(@@ -1362,8 +1532,45 @@ impl Draft {1362
}1532
}1363
}1533
}1364
1534
1535
/// A table line holds its mark alone: text typed next to it moves to its own line, a mark1536
/// without its table is dropped and a table without its mark becomes text.1537
fn repair_tables(&mut self, mut cursor: usize) -> usize {1538
let mark_length = TABLE_MARK.len_utf8();1539
let mut index = 0;1540
while index < self.lines.len() {1541
let line = self.line_ranges()[index].clone();1542
let found = self.text[line.clone()].find(TABLE_MARK);1543
match (self.lines[index].clone(), found) {1544
(LineKind::Table(_), None) => self.lines[index] = LineKind::Text,1545
(LineKind::Table(table), Some(at)) if at > 0 => {1546
let split = line.start + at;1547
self.splice(split..split, "\n", &[]);1548
self.lines[index] = LineKind::Text;1549
self.lines[index + 1] = LineKind::Table(table);1550
cursor += usize::from(cursor > split);1551
}1552
(LineKind::Table(_), Some(_)) if line.len() > mark_length => {1553
let split = line.start + mark_length;1554
self.splice(split..split, "\n", &[]);1555
cursor += usize::from(cursor > split);1556
}1557
(LineKind::Table(_), Some(_)) => {}1558
(_, Some(at)) => {1559
let mark = line.start + at..line.start + at + mark_length;1560
self.splice(mark.clone(), "", &[]);1561
cursor = map_offset(&[(mark, String::new())], cursor);1562
continue;1563
}1564
(_, None) => {}1565
}1566
index += 1;1567
}1568
cursor1569
}1570
1365
/// List items whose marker was edited away become text; numbered items are renumbered.1571
/// List items whose marker was edited away become text; numbered items are renumbered.1366
fn repair(&mut self, mut cursor: usize) -> usize {1572
fn repair(&mut self, cursor: usize) -> usize {1573
let mut cursor = self.repair_tables(cursor);1367
for index in 0..self.lines.len() {1574
for index in 0..self.lines.len() {1368
let kind = self.lines[index].clone();1575
let kind = self.lines[index].clone();1369
if !kind.is_list() {1576
if !kind.is_list() {@@ -1399,7 +1606,11 @@ fn marker_text(kind: &LineKind, number: u32) -> String {1399
match kind {1606
match kind {1400
LineKind::Bullet(depth) => bullet_marker(*depth),1607
LineKind::Bullet(depth) => bullet_marker(*depth),1401
LineKind::Numbered(_) => format!("{number}. "),1608
LineKind::Numbered(_) => format!("{number}. "),1402
LineKind::Text | LineKind::Quote | LineKind::Code(_) => String::new(),1609
LineKind::Text1610
| LineKind::Quote1611
| LineKind::Code(_)1612
| LineKind::Heading(_)1613
| LineKind::Table(_) => String::new(),1403
}1614
}1404
}1615
}1405
1616
@@ -1430,7 +1641,9 @@ fn numbered_marker(line: &str) -> Option<(usize, u32)> {1430
fn line_shortcut(before: &str) -> Option<(LineKind, u32)> {1641
fn line_shortcut(before: &str) -> Option<(LineKind, u32)> {1431
match before {1642
match before {1432
"- " | "* " => Some((LineKind::Bullet(0), 1)),1643
"- " | "* " => Some((LineKind::Bullet(0), 1)),1433
"> " => Some((LineKind::Quote, 1)),1644
">" => Some((LineKind::Quote, 1)),1645
_ if before.starts_with('#') => heading_prefix(before)1646
.and_then(|(level, rest)| rest.is_empty().then_some((LineKind::Heading(level), 1))),1434
_ => {1647
_ => {1435
let digits = before.strip_suffix(". ")?;1648
let digits = before.strip_suffix(". ")?;1436
let all_digits = !digits.is_empty()1649
let all_digits = !digits.is_empty()@@ -1540,7 +1753,7 @@ fn typed_inline(before: &str) -> Option<(Range<usize>, Range<usize>, MarkKind)>1540
let usable = !body[open + 1..].trim().is_empty() && !body[..open].ends_with('`');1753
let usable = !body[open + 1..].trim().is_empty() && !body[..open].ends_with('`');1541
return usable.then(|| (open..open + 1, body.len()..end, MarkKind::Code));1754
return usable.then(|| (open..open + 1, body.len()..end, MarkKind::Code));1542
}1755
}1543
for marker in ['*', '_'] {1756
for (marker, kind) in [('*', MarkKind::Bold), ('_', MarkKind::Italic)] {1544
if let Some(body) = before.strip_suffix(marker) {1757
if let Some(body) = before.strip_suffix(marker) {1545
if body.ends_with(marker) {1758
if body.ends_with(marker) {1546
return None;1759
return None;@@ -1548,7 +1761,7 @@ fn typed_inline(before: &str) -> Option<(Range<usize>, Range<usize>, MarkKind)>1548
let open = body.rfind(marker)?;1761
let open = body.rfind(marker)?;1549
let opening_ok = !word_before(&body[..open]) && !body[..open].ends_with(marker);1762
let opening_ok = !word_before(&body[..open]) && !body[..open].ends_with(marker);1550
return (opening_ok && valid_inner(&body[open + 1..]))1763
return (opening_ok && valid_inner(&body[open + 1..]))1551
.then(|| (open..open + 1, body.len()..end, MarkKind::Italic));1764
.then(|| (open..open + 1, body.len()..end, kind));1552
}1765
}1553
}1766
}1554
None1767
None@@ -1702,10 +1915,16 @@ pub fn has_markdown(text: &str) -> bool {1702
}1915
}1703
1916
1704
fn markdown_lines(text: &str) -> Vec<DraftLine> {1917
fn markdown_lines(text: &str) -> Vec<DraftLine> {1918
let sources: Vec<&str> = text1919
.split('\n')1920
.map(|raw| raw.strip_suffix('\r').unwrap_or(raw))1921
.collect();1705
let mut lines = Vec::new();1922
let mut lines = Vec::new();1706
let mut code: Option<Option<String>> = None;1923
let mut code: Option<Option<String>> = None;1707
for raw in text.split('\n') {1924
let mut position = 0;1708
let raw = raw.strip_suffix('\r').unwrap_or(raw);1925
while position < sources.len() {1926
let raw = sources[position];1927
position += 1;1709
let trimmed = raw.trim_start();1928
let trimmed = raw.trim_start();1710
if let Some(language) = &code {1929
if let Some(language) = &code {1711
if trimmed.starts_with(FENCE) && trimmed.trim_end() == FENCE {1930
if trimmed.starts_with(FENCE) && trimmed.trim_end() == FENCE {@@ -1727,12 +1946,23 @@ fn markdown_lines(text: &str) -> Vec<DraftLine> {1727
code = Some(language);1946
code = Some(language);1728
continue;1947
continue;1729
}1948
}1949
if let Some((rows, consumed)) = markdown_table(&sources[position - 1..]) {1950
let rows = rows1951
.into_iter()1952
.map(|row| row.iter().map(|cell| parse_inline(cell).0).collect())1953
.collect();1954
lines.push(table_line(Table::from_rows(rows)));1955
position += consumed - 1;1956
continue;1957
}1730
let indent: usize = raw[..raw.len() - trimmed.len()]1958
let indent: usize = raw[..raw.len() - trimmed.len()]1731
.chars()1959
.chars()1732
.map(|character| if character == '\t' { 4 } else { 1 })1960
.map(|character| if character == '\t' { 4 } else { 1 })1733
.sum();1961
.sum();1734
let depth = ((indent / MARKDOWN_INDENT) as u8).min(MAX_DEPTH);1962
let depth = ((indent / MARKDOWN_INDENT) as u8).min(MAX_DEPTH);1735
let (kind, number, content) = if let Some(rest) = PASTED_BULLETS1963
let (kind, number, content) = if let Some((level, rest)) = heading_prefix(trimmed) {1964
(LineKind::Heading(level), None, rest)1965
} else if let Some(rest) = PASTED_BULLETS1736
.iter()1966
.iter()1737
.find_map(|bullet| trimmed.strip_prefix(bullet))1967
.find_map(|bullet| trimmed.strip_prefix(bullet))1738
{1968
{@@ -1758,6 +1988,24 @@ fn markdown_lines(text: &str) -> Vec<DraftLine> {1758
lines1988
lines1759
}1989
}1760
1990
1991
fn table_line(table: Table) -> DraftLine {1992
DraftLine {1993
kind: LineKind::Table(table),1994
number: None,1995
content: TABLE_MARK.to_string(),1996
marks: Vec::new(),1997
}1998
}1999
2000
/// `# ` to `###### `: the level, capped at the three Teams offers, and the rest of the line.2001
fn heading_prefix(line: &str) -> Option<(u8, &str)> {2002
let hashes = line.bytes().take_while(|byte| *byte == b'#').count();2003
let rest = line[hashes..].strip_prefix(' ')?;2004
(1..=6)2005
.contains(&hashes)2006
.then(|| ((hashes as u8).min(MAX_HEADING), rest))2007
}2008
1761
fn parse_inline(source: &str) -> (String, Vec<Mark>) {2009
fn parse_inline(source: &str) -> (String, Vec<Mark>) {1762
let mut text = String::with_capacity(source.len());2010
let mut text = String::with_capacity(source.len());1763
let mut marks = Vec::new();2011
let mut marks = Vec::new();@@ -1849,6 +2097,17 @@ fn inline_at(rest: &str, previous: Option<char>) -> Option<(&str, usize, MarkKin1849
None2097
None1850
}2098
}1851
2099
2100
fn cell_text(spans: &[Span]) -> String {2101
let mut builder = SpanLines::default();2102
builder.walk(spans, &LineKind::Text, &[]);2103
builder2104
.finish()2105
.into_iter()2106
.map(|line| line.content)2107
.collect::<Vec<_>>()2108
.join("\n")2109
}2110
1852
#[derive(Default)]2111
#[derive(Default)]1853
struct SpanLines {2112
struct SpanLines {1854
lines: Vec<DraftLine>,2113
lines: Vec<DraftLine>,@@ -1936,9 +2195,10 @@ impl SpanLines {1936
};2195
};1937
self.start_line(&continued, None);2196
self.start_line(&continued, None);1938
}2197
}1939
Span::Heading { children, .. } => {2198
Span::Heading { level, children } => {1940
self.start_line(&LineKind::Text, None);2199
let heading = LineKind::Heading((*level).clamp(1, MAX_HEADING));1941
self.walk(children, &LineKind::Text, &with(MarkKind::Bold));2200
self.start_line(&heading, None);2201
self.walk(children, &heading, marks);1942
self.open = false;2202
self.open = false;1943
}2203
}1944
Span::CodeBlock { language, code } => {2204
Span::CodeBlock { language, code } => {@@ -1977,15 +2237,11 @@ impl SpanLines {1977
self.open = false;2237
self.open = false;1978
}2238
}1979
Span::Table { rows, .. } => {2239
Span::Table { rows, .. } => {1980
for row in rows {2240
let rows = rows1981
self.start_line(&LineKind::Text, None);2241
.iter()1982
for (position, cell) in row.iter().enumerate() {2242
.map(|row| row.iter().map(|cell| cell_text(cell)).collect())1983
if position > 0 {2243
.collect();1984
self.append(" | ", &LineKind::Text, &[]);2244
self.lines.push(table_line(Table::from_rows(rows)));1985
}1986
self.walk(cell, &LineKind::Text, marks);1987
}1988
}1989
self.open = false;2245
self.open = false;1990
}2246
}1991
Span::Image { .. } | Span::Quote { .. } => {}2247
Span::Image { .. } | Span::Quote { .. } => {}@@ -2081,7 +2337,7 @@ mod tests {2081
draft.marks(),2337
draft.marks(),2082
[2338
[2083
mark(2..6, MarkKind::Bold),2339
mark(2..6, MarkKind::Bold),2084
mark(11..13, MarkKind::Italic),2340
mark(11..13, MarkKind::Bold),2085
mark(17..19, MarkKind::Italic),2341
mark(17..19, MarkKind::Italic),2086
mark(20..24, MarkKind::Strike),2342
mark(20..24, MarkKind::Strike),2087
mark(25..29, MarkKind::Code),2343
mark(25..29, MarkKind::Code),@@ -2357,9 +2613,12 @@ mod tests {2357
let numbered = typed_draft("1. one");2613
let numbered = typed_draft("1. one");2358
assert_eq!(numbered.text(), "1. one");2614
assert_eq!(numbered.text(), "1. one");2359
assert_eq!(numbered.lines(), [LineKind::Numbered(0)]);2615
assert_eq!(numbered.lines(), [LineKind::Numbered(0)]);2360
let quote = typed_draft("> said");2616
let quote = typed_draft(">said");2361
assert_eq!(quote.text(), "said");2617
assert_eq!(quote.text(), "said");2362
assert_eq!(quote.lines(), [LineKind::Quote]);2618
assert_eq!(quote.lines(), [LineKind::Quote]);2619
let spaced = typed_draft("> said");2620
assert_eq!(spaced.text(), " said");2621
assert_eq!(spaced.lines(), [LineKind::Quote]);2363
}2622
}2364
2623
2365
#[test]2624
#[test]@@ -48,12 +48,13 @@ mod receipts;
48
48
mod recording_rights;
49
49
mod remote;
50
50
mod scheduled;
51
mod skin_tone;
52
51
mod search;
53
52
mod server_search;
54
53
mod sidebar_sync;
54
mod skin_tone;
55
55
mod spans;
56
56
mod stored;
57
mod table;
57
58
mod time_zone;
58
59
mod translate_sync;
59
60
mod translation;
@@ -67,8 +68,7 @@ pub use adaptive_card::{
67
68
};
68
69
pub use avatars::Avatar;
69
70
pub use call_event::{
70
CallEvent, CallPhase, CallType, Recording, call_event, format_duration,
71
parse_duration_seconds,
71
CallEvent, CallPhase, CallType, Recording, call_event, format_duration, parse_duration_seconds,
72
72
};
73
73
pub use card_actions::{CardActionOutcome, DialogIdentity, TaskDialog, TaskDialogKind};
74
74
pub use card_chart::{
@@ -118,6 +118,10 @@ pub use folders::{
118
118
BoxFuture, ChatFolder, ChatsvcFolderSource, FolderChange, FolderKind, FolderSource,
119
119
store_section_settings, stored_section_settings,
120
120
};
121
pub use forwarded::{
122
FORWARD_LOADING_TEXT, FORWARD_UNAVAILABLE_TEXT, FORWARDED_CONTENT_TYPE, ForwardHeader,
123
ForwardInfo, ForwardState, forwarded_texts, forwards, is_forwarded,
124
};
121
125
pub use graph::{
122
126
DriveEntry, DriveFolder, FileReference, HostedImage, KeptAttachment, MentionTarget,
123
127
MessageExtras, SharedFile, UploadedFile,
@@ -144,19 +148,16 @@ pub use receipts::{ReceiptReader, ReceiptState};
144
148
pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};
145
149
pub use scheduled::NOTES_CHAT_ID;
146
150
pub use skin_tone::{skin_tone, store_account_skin_tone};
147
pub use forwarded::{
148
FORWARD_LOADING_TEXT, FORWARD_UNAVAILABLE_TEXT, FORWARDED_CONTENT_TYPE, ForwardHeader,
149
ForwardInfo, ForwardState, forwarded_texts, forwards, is_forwarded,
150
};
151
151
pub use spans::{FontSize, Span, html_to_spans};
152
152
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};
153
153
pub use stored::{
154
154
AttachmentInfo, FileCard, FileKind, ImageKind, ImageRef, MentionInfo, PROFILE_LINK_PREFIX,
155
155
QuoteInfo, ReactionInfo, ReactionSummary, adaptive_cards, attachments, can_delete, can_edit,
156
card_texts, copy_text, files, images, linked_message_spans, linked_message_spans_with, mentions, message_quote,
157
message_spans, quote_html, quotes, reaction_summaries, reactions, readable_text, translated_spans,
158
user_mention_inputs,
156
card_texts, copy_text, files, images, linked_message_spans, linked_message_spans_with,
157
mentions, message_quote, message_spans, quote_html, quotes, reaction_summaries, reactions,
158
readable_text, translated_spans, user_mention_inputs,
159
159
};
160
pub use table::{Cell, PICKER_COLUMNS, PICKER_ROWS, TABLE_MARK, Table, TableEdit};
160
161
pub use time_zone::local_time;
161
162
pub use translation::{
162
163
FALLBACK_TARGET, LanguageStamp, confident_language, default_target, language_name, min_chars,
@@ -48,12 +48,13 @@ mod receipts;48
mod recording_rights;48
mod recording_rights;49
mod remote;49
mod remote;50
mod scheduled;50
mod scheduled;51
mod skin_tone;52
mod search;51
mod search;53
mod server_search;52
mod server_search;54
mod sidebar_sync;53
mod sidebar_sync;54
mod skin_tone;55
mod spans;55
mod spans;56
mod stored;56
mod stored;57
mod table;57
mod time_zone;58
mod time_zone;58
mod translate_sync;59
mod translate_sync;59
mod translation;60
mod translation;@@ -67,8 +68,7 @@ pub use adaptive_card::{67
};68
};68
pub use avatars::Avatar;69
pub use avatars::Avatar;69
pub use call_event::{70
pub use call_event::{70
CallEvent, CallPhase, CallType, Recording, call_event, format_duration,71
CallEvent, CallPhase, CallType, Recording, call_event, format_duration, parse_duration_seconds,71
parse_duration_seconds,72
};72
};73
pub use card_actions::{CardActionOutcome, DialogIdentity, TaskDialog, TaskDialogKind};73
pub use card_actions::{CardActionOutcome, DialogIdentity, TaskDialog, TaskDialogKind};74
pub use card_chart::{74
pub use card_chart::{@@ -118,6 +118,10 @@ pub use folders::{118
BoxFuture, ChatFolder, ChatsvcFolderSource, FolderChange, FolderKind, FolderSource,118
BoxFuture, ChatFolder, ChatsvcFolderSource, FolderChange, FolderKind, FolderSource,119
store_section_settings, stored_section_settings,119
store_section_settings, stored_section_settings,120
};120
};121
pub use forwarded::{122
FORWARD_LOADING_TEXT, FORWARD_UNAVAILABLE_TEXT, FORWARDED_CONTENT_TYPE, ForwardHeader,123
ForwardInfo, ForwardState, forwarded_texts, forwards, is_forwarded,124
};121
pub use graph::{125
pub use graph::{122
DriveEntry, DriveFolder, FileReference, HostedImage, KeptAttachment, MentionTarget,126
DriveEntry, DriveFolder, FileReference, HostedImage, KeptAttachment, MentionTarget,123
MessageExtras, SharedFile, UploadedFile,127
MessageExtras, SharedFile, UploadedFile,@@ -144,19 +148,16 @@ pub use receipts::{ReceiptReader, ReceiptState};144
pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};148
pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};145
pub use scheduled::NOTES_CHAT_ID;149
pub use scheduled::NOTES_CHAT_ID;146
pub use skin_tone::{skin_tone, store_account_skin_tone};150
pub use skin_tone::{skin_tone, store_account_skin_tone};147
pub use forwarded::{148
FORWARD_LOADING_TEXT, FORWARD_UNAVAILABLE_TEXT, FORWARDED_CONTENT_TYPE, ForwardHeader,149
ForwardInfo, ForwardState, forwarded_texts, forwards, is_forwarded,150
};151
pub use spans::{FontSize, Span, html_to_spans};151
pub use spans::{FontSize, Span, html_to_spans};152
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};152
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};153
pub use stored::{153
pub use stored::{154
AttachmentInfo, FileCard, FileKind, ImageKind, ImageRef, MentionInfo, PROFILE_LINK_PREFIX,154
AttachmentInfo, FileCard, FileKind, ImageKind, ImageRef, MentionInfo, PROFILE_LINK_PREFIX,155
QuoteInfo, ReactionInfo, ReactionSummary, adaptive_cards, attachments, can_delete, can_edit,155
QuoteInfo, ReactionInfo, ReactionSummary, adaptive_cards, attachments, can_delete, can_edit,156
card_texts, copy_text, files, images, linked_message_spans, linked_message_spans_with, mentions, message_quote,156
card_texts, copy_text, files, images, linked_message_spans, linked_message_spans_with,157
message_spans, quote_html, quotes, reaction_summaries, reactions, readable_text, translated_spans,157
mentions, message_quote, message_spans, quote_html, quotes, reaction_summaries, reactions,158
user_mention_inputs,158
readable_text, translated_spans, user_mention_inputs,159
};159
};160
pub use table::{Cell, PICKER_COLUMNS, PICKER_ROWS, TABLE_MARK, Table, TableEdit};160
pub use time_zone::local_time;161
pub use time_zone::local_time;161
pub use translation::{162
pub use translation::{162
FALLBACK_TARGET, LanguageStamp, confident_language, default_target, language_name, min_chars,163
FALLBACK_TARGET, LanguageStamp, confident_language, default_target, language_name, min_chars,@@ -0,0 +1,353 @@
1
use serde::{Deserialize, Serialize};
2
3
use crate::markdown::escape_html;
4
5
pub const TABLE_MARK: char = '\u{FFFB}';
6
pub const PICKER_COLUMNS: usize = 7;
7
pub const PICKER_ROWS: usize = 5;
8
const EMPTY_CELL: &str = " ";
9
10
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11
pub struct Cell {
12
pub row: usize,
13
pub column: usize,
14
}
15
16
impl Cell {
17
pub fn new(row: usize, column: usize) -> Cell {
18
Cell { row, column }
19
}
20
}
21
22
/// A composer table: plain text cells, every row as wide as the first.
23
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
24
pub struct Table {
25
pub rows: Vec<Vec<String>>,
26
}
27
28
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29
pub enum TableEdit {
30
InsertRowAbove,
31
InsertRowBelow,
32
InsertColumnLeft,
33
InsertColumnRight,
34
DeleteRow,
35
DeleteColumn,
36
DeleteTable,
37
}
38
39
impl TableEdit {
40
pub const INSERTS: [TableEdit; 4] = [
41
TableEdit::InsertRowAbove,
42
TableEdit::InsertRowBelow,
43
TableEdit::InsertColumnLeft,
44
TableEdit::InsertColumnRight,
45
];
46
pub const DELETES: [TableEdit; 3] = [
47
TableEdit::DeleteRow,
48
TableEdit::DeleteColumn,
49
TableEdit::DeleteTable,
50
];
51
52
pub fn label(self) -> &'static str {
53
match self {
54
TableEdit::InsertRowAbove => "Insert row above",
55
TableEdit::InsertRowBelow => "Insert row below",
56
TableEdit::InsertColumnLeft => "Insert column to the left",
57
TableEdit::InsertColumnRight => "Insert column to the right",
58
TableEdit::DeleteRow => "Delete row",
59
TableEdit::DeleteColumn => "Delete column",
60
TableEdit::DeleteTable => "Delete table",
61
}
62
}
63
}
64
65
impl Table {
66
pub fn new(rows: usize, columns: usize) -> Table {
67
Table {
68
rows: vec![vec![String::new(); columns.max(1)]; rows.max(1)],
69
}
70
}
71
72
/// Short rows are filled up to the widest one.
73
pub fn from_rows(mut rows: Vec<Vec<String>>) -> Table {
74
rows.retain(|row| !row.is_empty());
75
let columns = rows.iter().map(Vec::len).max().unwrap_or(1);
76
for row in &mut rows {
77
row.resize(columns, String::new());
78
}
79
if rows.is_empty() {
80
return Table::new(1, 1);
81
}
82
Table { rows }
83
}
84
85
pub fn row_count(&self) -> usize {
86
self.rows.len()
87
}
88
89
pub fn column_count(&self) -> usize {
90
self.rows.first().map_or(0, Vec::len)
91
}
92
93
pub fn cell(&self, cell: Cell) -> Option<&str> {
94
self.rows
95
.get(cell.row)?
96
.get(cell.column)
97
.map(String::as_str)
98
}
99
100
pub fn set_cell(&mut self, cell: Cell, text: &str) {
101
if let Some(slot) = self
102
.rows
103
.get_mut(cell.row)
104
.and_then(|row| row.get_mut(cell.column))
105
{
106
*slot = text.to_owned();
107
}
108
}
109
110
pub fn last_cell(&self) -> Cell {
111
Cell::new(self.row_count() - 1, self.column_count() - 1)
112
}
113
114
/// Tab: the next cell, and past the last one a new row (`true`) like Teams.
115
pub fn next_cell(&mut self, cell: Cell) -> (Cell, bool) {
116
if cell.column + 1 < self.column_count() {
117
return (Cell::new(cell.row, cell.column + 1), false);
118
}
119
if cell.row + 1 < self.row_count() {
120
return (Cell::new(cell.row + 1, 0), false);
121
}
122
self.rows.push(vec![String::new(); self.column_count()]);
123
(Cell::new(cell.row + 1, 0), true)
124
}
125
126
/// Shift+Tab: the previous cell; the first cell stays.
127
pub fn previous_cell(&self, cell: Cell) -> Cell {
128
match (cell.row, cell.column) {
129
(_, column) if column > 0 => Cell::new(cell.row, column - 1),
130
(0, _) => cell,
131
(row, _) => Cell::new(row - 1, self.column_count() - 1),
132
}
133
}
134
135
/// The cell to focus afterwards; `None` when the table is gone.
136
pub fn apply(&mut self, edit: TableEdit, cell: Cell) -> Option<Cell> {
137
let columns = self.column_count();
138
match edit {
139
TableEdit::InsertRowAbove => {
140
self.rows.insert(cell.row, vec![String::new(); columns]);
141
Some(Cell::new(cell.row, cell.column))
142
}
143
TableEdit::InsertRowBelow => {
144
self.rows.insert(cell.row + 1, vec![String::new(); columns]);
145
Some(Cell::new(cell.row + 1, cell.column))
146
}
147
TableEdit::InsertColumnLeft => {
148
for row in &mut self.rows {
149
row.insert(cell.column, String::new());
150
}
151
Some(Cell::new(cell.row, cell.column))
152
}
153
TableEdit::InsertColumnRight => {
154
for row in &mut self.rows {
155
row.insert(cell.column + 1, String::new());
156
}
157
Some(Cell::new(cell.row, cell.column + 1))
158
}
159
TableEdit::DeleteRow if self.row_count() > 1 => {
160
self.rows.remove(cell.row);
161
Some(Cell::new(cell.row.min(self.row_count() - 1), cell.column))
162
}
163
TableEdit::DeleteColumn if columns > 1 => {
164
for row in &mut self.rows {
165
row.remove(cell.column);
166
}
167
Some(Cell::new(
168
cell.row,
169
cell.column.min(self.column_count() - 1),
170
))
171
}
172
TableEdit::DeleteRow | TableEdit::DeleteColumn | TableEdit::DeleteTable => None,
173
}
174
}
175
176
pub fn is_blank(&self) -> bool {
177
self.rows
178
.iter()
179
.flatten()
180
.all(|cell| cell.trim().is_empty())
181
}
182
183
/// Rows on lines, cells split by tabs: what a spreadsheet pastes.
184
pub fn plain_text(&self) -> String {
185
self.rows
186
.iter()
187
.map(|row| row.join("\t").replace('\n', " "))
188
.collect::<Vec<_>>()
189
.join("\n")
190
}
191
192
/// The table Teams sends: CKEditor's `figure.table`, `copy-paste-table` on the table, a one
193
/// line cell without `<p>`, every line of a longer cell in its own `<p>`, empty ` `.
194
pub fn to_html(&self) -> String {
195
let mut html =
196
String::from("<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>");
197
for row in &self.rows {
198
html.push_str("<tr>");
199
for cell in row {
200
html.push_str("<td>");
201
if cell.trim().is_empty() {
202
html.push_str(EMPTY_CELL);
203
} else if !cell.contains('\n') {
204
html.push_str(&escape_html(cell));
205
} else {
206
for line in cell.split('\n') {
207
html.push_str("<p>");
208
if line.trim().is_empty() {
209
html.push_str(EMPTY_CELL);
210
} else {
211
html.push_str(&escape_html(line));
212
}
213
html.push_str("</p>");
214
}
215
}
216
html.push_str("</td>");
217
}
218
html.push_str("</tr>");
219
}
220
html.push_str("</tbody></table></figure>");
221
html
222
}
223
}
224
225
fn split_row(line: &str) -> Option<Vec<String>> {
226
let trimmed = line.trim();
227
if !trimmed.contains('|') {
228
return None;
229
}
230
let inner = trimmed.strip_prefix('|').unwrap_or(trimmed);
231
let inner = inner.strip_suffix('|').unwrap_or(inner);
232
let mut cells = Vec::new();
233
let mut current = String::new();
234
let mut characters = inner.chars().peekable();
235
while let Some(character) = characters.next() {
236
match character {
237
'\\' if characters.peek() == Some(&'|') => {
238
current.push('|');
239
characters.next();
240
}
241
'|' => cells.push(std::mem::take(&mut current).trim().to_owned()),
242
other => current.push(other),
243
}
244
}
245
cells.push(current.trim().to_owned());
246
Some(cells)
247
}
248
249
fn is_delimiter_row(line: &str) -> bool {
250
split_row(line).is_some_and(|cells| {
251
cells.iter().all(|cell| {
252
let dashes = cell.trim_start_matches(':').trim_end_matches(':');
253
!dashes.is_empty() && dashes.chars().all(|character| character == '-')
254
})
255
})
256
}
257
258
/// A GitHub markdown table at the start of `lines`: header, delimiter row, body rows.
259
/// Returns the raw cell sources and how many lines it spans.
260
pub(crate) fn markdown_table(lines: &[&str]) -> Option<(Vec<Vec<String>>, usize)> {
261
let header = split_row(lines.first()?)?;
262
if !lines.get(1).is_some_and(|line| is_delimiter_row(line)) {
263
return None;
264
}
265
let delimiter_columns = split_row(lines[1])?.len();
266
if delimiter_columns != header.len() {
267
return None;
268
}
269
let mut rows = vec![header];
270
let mut consumed = 2;
271
for line in &lines[2..] {
272
match split_row(line) {
273
Some(cells) if !line.trim().is_empty() => rows.push(cells),
274
_ => break,
275
}
276
consumed += 1;
277
}
278
Some((rows, consumed))
279
}
280
281
#[cfg(test)]
282
mod tests {
283
use super::*;
284
285
#[test]
286
fn tab_walks_the_cells_and_adds_a_row_after_the_last() {
287
let mut table = Table::new(2, 2);
288
assert_eq!(table.next_cell(Cell::new(0, 0)), (Cell::new(0, 1), false));
289
assert_eq!(table.next_cell(Cell::new(0, 1)), (Cell::new(1, 0), false));
290
assert_eq!(table.next_cell(Cell::new(1, 1)), (Cell::new(2, 0), true));
291
assert_eq!(table.row_count(), 3);
292
assert_eq!(table.column_count(), 2);
293
}
294
295
#[test]
296
fn shift_tab_walks_back_and_stops_at_the_first_cell() {
297
let table = Table::new(2, 3);
298
assert_eq!(table.previous_cell(Cell::new(1, 0)), Cell::new(0, 2));
299
assert_eq!(table.previous_cell(Cell::new(0, 1)), Cell::new(0, 0));
300
assert_eq!(table.previous_cell(Cell::new(0, 0)), Cell::new(0, 0));
301
}
302
303
#[test]
304
fn rows_and_columns_insert_and_delete_around_the_cell() {
305
let mut table = Table::from_rows(vec![
306
vec!["a".into(), "b".into()],
307
vec!["c".into(), "d".into()],
308
]);
309
assert_eq!(
310
table.apply(TableEdit::InsertRowAbove, Cell::new(1, 1)),
311
Some(Cell::new(1, 1))
312
);
313
assert_eq!(table.rows[1], ["", ""]);
314
assert_eq!(
315
table.apply(TableEdit::InsertColumnRight, Cell::new(0, 0)),
316
Some(Cell::new(0, 1))
317
);
318
assert_eq!(table.rows[0], ["a", "", "b"]);
319
table.apply(TableEdit::DeleteColumn, Cell::new(0, 1));
320
table.apply(TableEdit::DeleteRow, Cell::new(1, 0));
321
assert_eq!(table.rows, [["a", "b"], ["c", "d"]]);
322
assert_eq!(table.apply(TableEdit::DeleteTable, Cell::new(0, 0)), None);
323
}
324
325
#[test]
326
fn deleting_the_last_row_or_column_deletes_the_table() {
327
let mut table = Table::new(1, 2);
328
assert_eq!(table.apply(TableEdit::DeleteRow, Cell::new(0, 0)), None);
329
let mut table = Table::new(2, 1);
330
assert_eq!(table.apply(TableEdit::DeleteColumn, Cell::new(0, 0)), None);
331
}
332
333
#[test]
334
fn html_is_the_copy_paste_table_teams_sends() {
335
let table = Table::from_rows(vec![vec!["a<b".into(), String::new()], vec!["x\ny".into()]]);
336
assert_eq!(
337
table.to_html(),
338
"<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\
339
<tr><td>a<b</td><td> </td></tr>\
340
<tr><td><p>x</p><p>y</p></td><td> </td></tr></tbody></table></figure>"
341
);
342
}
343
344
#[test]
345
fn markdown_tables_need_a_delimiter_row() {
346
let lines = ["| A | B |", "|---|:-:|", "| 1 | 2 \\| 3 |", "", "after"];
347
let (rows, consumed) = markdown_table(&lines).unwrap();
348
assert_eq!(consumed, 3);
349
assert_eq!(rows, [["A", "B"], ["1", "2 | 3"]]);
350
assert!(markdown_table(&["a | b", "c | d"]).is_none());
351
assert!(markdown_table(&["| a | b |", "|---|"]).is_none());
352
}
353
}
@@ -0,0 +1,353 @@1
use serde::{Deserialize, Serialize};2
3
use crate::markdown::escape_html;4
5
pub const TABLE_MARK: char = '\u{FFFB}';6
pub const PICKER_COLUMNS: usize = 7;7
pub const PICKER_ROWS: usize = 5;8
const EMPTY_CELL: &str = " ";9
10
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]11
pub struct Cell {12
pub row: usize,13
pub column: usize,14
}15
16
impl Cell {17
pub fn new(row: usize, column: usize) -> Cell {18
Cell { row, column }19
}20
}21
22
/// A composer table: plain text cells, every row as wide as the first.23
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]24
pub struct Table {25
pub rows: Vec<Vec<String>>,26
}27
28
#[derive(Debug, Clone, Copy, PartialEq, Eq)]29
pub enum TableEdit {30
InsertRowAbove,31
InsertRowBelow,32
InsertColumnLeft,33
InsertColumnRight,34
DeleteRow,35
DeleteColumn,36
DeleteTable,37
}38
39
impl TableEdit {40
pub const INSERTS: [TableEdit; 4] = [41
TableEdit::InsertRowAbove,42
TableEdit::InsertRowBelow,43
TableEdit::InsertColumnLeft,44
TableEdit::InsertColumnRight,45
];46
pub const DELETES: [TableEdit; 3] = [47
TableEdit::DeleteRow,48
TableEdit::DeleteColumn,49
TableEdit::DeleteTable,50
];51
52
pub fn label(self) -> &'static str {53
match self {54
TableEdit::InsertRowAbove => "Insert row above",55
TableEdit::InsertRowBelow => "Insert row below",56
TableEdit::InsertColumnLeft => "Insert column to the left",57
TableEdit::InsertColumnRight => "Insert column to the right",58
TableEdit::DeleteRow => "Delete row",59
TableEdit::DeleteColumn => "Delete column",60
TableEdit::DeleteTable => "Delete table",61
}62
}63
}64
65
impl Table {66
pub fn new(rows: usize, columns: usize) -> Table {67
Table {68
rows: vec![vec![String::new(); columns.max(1)]; rows.max(1)],69
}70
}71
72
/// Short rows are filled up to the widest one.73
pub fn from_rows(mut rows: Vec<Vec<String>>) -> Table {74
rows.retain(|row| !row.is_empty());75
let columns = rows.iter().map(Vec::len).max().unwrap_or(1);76
for row in &mut rows {77
row.resize(columns, String::new());78
}79
if rows.is_empty() {80
return Table::new(1, 1);81
}82
Table { rows }83
}84
85
pub fn row_count(&self) -> usize {86
self.rows.len()87
}88
89
pub fn column_count(&self) -> usize {90
self.rows.first().map_or(0, Vec::len)91
}92
93
pub fn cell(&self, cell: Cell) -> Option<&str> {94
self.rows95
.get(cell.row)?96
.get(cell.column)97
.map(String::as_str)98
}99
100
pub fn set_cell(&mut self, cell: Cell, text: &str) {101
if let Some(slot) = self102
.rows103
.get_mut(cell.row)104
.and_then(|row| row.get_mut(cell.column))105
{106
*slot = text.to_owned();107
}108
}109
110
pub fn last_cell(&self) -> Cell {111
Cell::new(self.row_count() - 1, self.column_count() - 1)112
}113
114
/// Tab: the next cell, and past the last one a new row (`true`) like Teams.115
pub fn next_cell(&mut self, cell: Cell) -> (Cell, bool) {116
if cell.column + 1 < self.column_count() {117
return (Cell::new(cell.row, cell.column + 1), false);118
}119
if cell.row + 1 < self.row_count() {120
return (Cell::new(cell.row + 1, 0), false);121
}122
self.rows.push(vec![String::new(); self.column_count()]);123
(Cell::new(cell.row + 1, 0), true)124
}125
126
/// Shift+Tab: the previous cell; the first cell stays.127
pub fn previous_cell(&self, cell: Cell) -> Cell {128
match (cell.row, cell.column) {129
(_, column) if column > 0 => Cell::new(cell.row, column - 1),130
(0, _) => cell,131
(row, _) => Cell::new(row - 1, self.column_count() - 1),132
}133
}134
135
/// The cell to focus afterwards; `None` when the table is gone.136
pub fn apply(&mut self, edit: TableEdit, cell: Cell) -> Option<Cell> {137
let columns = self.column_count();138
match edit {139
TableEdit::InsertRowAbove => {140
self.rows.insert(cell.row, vec![String::new(); columns]);141
Some(Cell::new(cell.row, cell.column))142
}143
TableEdit::InsertRowBelow => {144
self.rows.insert(cell.row + 1, vec![String::new(); columns]);145
Some(Cell::new(cell.row + 1, cell.column))146
}147
TableEdit::InsertColumnLeft => {148
for row in &mut self.rows {149
row.insert(cell.column, String::new());150
}151
Some(Cell::new(cell.row, cell.column))152
}153
TableEdit::InsertColumnRight => {154
for row in &mut self.rows {155
row.insert(cell.column + 1, String::new());156
}157
Some(Cell::new(cell.row, cell.column + 1))158
}159
TableEdit::DeleteRow if self.row_count() > 1 => {160
self.rows.remove(cell.row);161
Some(Cell::new(cell.row.min(self.row_count() - 1), cell.column))162
}163
TableEdit::DeleteColumn if columns > 1 => {164
for row in &mut self.rows {165
row.remove(cell.column);166
}167
Some(Cell::new(168
cell.row,169
cell.column.min(self.column_count() - 1),170
))171
}172
TableEdit::DeleteRow | TableEdit::DeleteColumn | TableEdit::DeleteTable => None,173
}174
}175
176
pub fn is_blank(&self) -> bool {177
self.rows178
.iter()179
.flatten()180
.all(|cell| cell.trim().is_empty())181
}182
183
/// Rows on lines, cells split by tabs: what a spreadsheet pastes.184
pub fn plain_text(&self) -> String {185
self.rows186
.iter()187
.map(|row| row.join("\t").replace('\n', " "))188
.collect::<Vec<_>>()189
.join("\n")190
}191
192
/// The table Teams sends: CKEditor's `figure.table`, `copy-paste-table` on the table, a one193
/// line cell without `<p>`, every line of a longer cell in its own `<p>`, empty ` `.194
pub fn to_html(&self) -> String {195
let mut html =196
String::from("<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>");197
for row in &self.rows {198
html.push_str("<tr>");199
for cell in row {200
html.push_str("<td>");201
if cell.trim().is_empty() {202
html.push_str(EMPTY_CELL);203
} else if !cell.contains('\n') {204
html.push_str(&escape_html(cell));205
} else {206
for line in cell.split('\n') {207
html.push_str("<p>");208
if line.trim().is_empty() {209
html.push_str(EMPTY_CELL);210
} else {211
html.push_str(&escape_html(line));212
}213
html.push_str("</p>");214
}215
}216
html.push_str("</td>");217
}218
html.push_str("</tr>");219
}220
html.push_str("</tbody></table></figure>");221
html222
}223
}224
225
fn split_row(line: &str) -> Option<Vec<String>> {226
let trimmed = line.trim();227
if !trimmed.contains('|') {228
return None;229
}230
let inner = trimmed.strip_prefix('|').unwrap_or(trimmed);231
let inner = inner.strip_suffix('|').unwrap_or(inner);232
let mut cells = Vec::new();233
let mut current = String::new();234
let mut characters = inner.chars().peekable();235
while let Some(character) = characters.next() {236
match character {237
'\\' if characters.peek() == Some(&'|') => {238
current.push('|');239
characters.next();240
}241
'|' => cells.push(std::mem::take(&mut current).trim().to_owned()),242
other => current.push(other),243
}244
}245
cells.push(current.trim().to_owned());246
Some(cells)247
}248
249
fn is_delimiter_row(line: &str) -> bool {250
split_row(line).is_some_and(|cells| {251
cells.iter().all(|cell| {252
let dashes = cell.trim_start_matches(':').trim_end_matches(':');253
!dashes.is_empty() && dashes.chars().all(|character| character == '-')254
})255
})256
}257
258
/// A GitHub markdown table at the start of `lines`: header, delimiter row, body rows.259
/// Returns the raw cell sources and how many lines it spans.260
pub(crate) fn markdown_table(lines: &[&str]) -> Option<(Vec<Vec<String>>, usize)> {261
let header = split_row(lines.first()?)?;262
if !lines.get(1).is_some_and(|line| is_delimiter_row(line)) {263
return None;264
}265
let delimiter_columns = split_row(lines[1])?.len();266
if delimiter_columns != header.len() {267
return None;268
}269
let mut rows = vec![header];270
let mut consumed = 2;271
for line in &lines[2..] {272
match split_row(line) {273
Some(cells) if !line.trim().is_empty() => rows.push(cells),274
_ => break,275
}276
consumed += 1;277
}278
Some((rows, consumed))279
}280
281
#[cfg(test)]282
mod tests {283
use super::*;284
285
#[test]286
fn tab_walks_the_cells_and_adds_a_row_after_the_last() {287
let mut table = Table::new(2, 2);288
assert_eq!(table.next_cell(Cell::new(0, 0)), (Cell::new(0, 1), false));289
assert_eq!(table.next_cell(Cell::new(0, 1)), (Cell::new(1, 0), false));290
assert_eq!(table.next_cell(Cell::new(1, 1)), (Cell::new(2, 0), true));291
assert_eq!(table.row_count(), 3);292
assert_eq!(table.column_count(), 2);293
}294
295
#[test]296
fn shift_tab_walks_back_and_stops_at_the_first_cell() {297
let table = Table::new(2, 3);298
assert_eq!(table.previous_cell(Cell::new(1, 0)), Cell::new(0, 2));299
assert_eq!(table.previous_cell(Cell::new(0, 1)), Cell::new(0, 0));300
assert_eq!(table.previous_cell(Cell::new(0, 0)), Cell::new(0, 0));301
}302
303
#[test]304
fn rows_and_columns_insert_and_delete_around_the_cell() {305
let mut table = Table::from_rows(vec![306
vec!["a".into(), "b".into()],307
vec!["c".into(), "d".into()],308
]);309
assert_eq!(310
table.apply(TableEdit::InsertRowAbove, Cell::new(1, 1)),311
Some(Cell::new(1, 1))312
);313
assert_eq!(table.rows[1], ["", ""]);314
assert_eq!(315
table.apply(TableEdit::InsertColumnRight, Cell::new(0, 0)),316
Some(Cell::new(0, 1))317
);318
assert_eq!(table.rows[0], ["a", "", "b"]);319
table.apply(TableEdit::DeleteColumn, Cell::new(0, 1));320
table.apply(TableEdit::DeleteRow, Cell::new(1, 0));321
assert_eq!(table.rows, [["a", "b"], ["c", "d"]]);322
assert_eq!(table.apply(TableEdit::DeleteTable, Cell::new(0, 0)), None);323
}324
325
#[test]326
fn deleting_the_last_row_or_column_deletes_the_table() {327
let mut table = Table::new(1, 2);328
assert_eq!(table.apply(TableEdit::DeleteRow, Cell::new(0, 0)), None);329
let mut table = Table::new(2, 1);330
assert_eq!(table.apply(TableEdit::DeleteColumn, Cell::new(0, 0)), None);331
}332
333
#[test]334
fn html_is_the_copy_paste_table_teams_sends() {335
let table = Table::from_rows(vec![vec!["a<b".into(), String::new()], vec!["x\ny".into()]]);336
assert_eq!(337
table.to_html(),338
"<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\339
<tr><td>a<b</td><td> </td></tr>\340
<tr><td><p>x</p><p>y</p></td><td> </td></tr></tbody></table></figure>"341
);342
}343
344
#[test]345
fn markdown_tables_need_a_delimiter_row() {346
let lines = ["| A | B |", "|---|:-:|", "| 1 | 2 \\| 3 |", "", "after"];347
let (rows, consumed) = markdown_table(&lines).unwrap();348
assert_eq!(consumed, 3);349
assert_eq!(rows, [["A", "B"], ["1", "2 | 3"]]);350
assert!(markdown_table(&["a | b", "c | d"]).is_none());351
assert!(markdown_table(&["| a | b |", "|---|"]).is_none());352
}353
}@@ -0,0 +1,341 @@
1
use teams_core::{
2
Draft, DraftLine, LineKind, Mark, MarkKind, TABLE_MARK, Table, TypingStyle, html_to_spans,
3
};
4
5
fn typed(draft: &mut Draft, text: &str) {
6
let mut typing: Option<TypingStyle> = None;
7
for character in text.chars() {
8
let cursor = draft.text().len();
9
let mut next = draft.text().to_owned();
10
next.push(character);
11
let cursor = draft.apply_edit(&next, cursor + character.len_utf8(), typing.as_ref());
12
typing = draft.convert_typed(cursor).map(|(_, style)| style);
13
draft.take_edits();
14
}
15
}
16
17
fn typed_draft(text: &str) -> Draft {
18
let mut draft = Draft::default();
19
typed(&mut draft, text);
20
draft
21
}
22
23
fn enter(draft: &mut Draft, cursor: usize, shift: bool) -> Option<usize> {
24
let result = draft.break_line(cursor, shift);
25
draft.take_edits();
26
result
27
}
28
29
fn table_of(rows: &[&[&str]]) -> Table {
30
Table::from_rows(
31
rows.iter()
32
.map(|row| row.iter().map(|cell| (*cell).to_owned()).collect())
33
.collect(),
34
)
35
}
36
37
#[test]
38
fn enter_in_a_quote_adds_a_quote_line_and_enter_on_the_empty_one_leaves() {
39
let mut draft = typed_draft(">abc");
40
let cursor = enter(&mut draft, 3, false).unwrap();
41
assert_eq!(draft.text(), "abc\n");
42
assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Quote]);
43
let cursor = enter(&mut draft, cursor, false).unwrap();
44
assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Text]);
45
assert_eq!(cursor, 4);
46
assert_eq!(enter(&mut draft, cursor, false), None);
47
assert_eq!(draft.to_html(), "<blockquote>abc</blockquote>");
48
}
49
50
#[test]
51
fn enter_on_an_empty_quote_line_in_the_middle_splits_the_quote() {
52
let mut draft = Draft::from_markdown("> a\n> \n> b");
53
enter(&mut draft, 2, false).unwrap();
54
assert_eq!(
55
draft.lines(),
56
[LineKind::Quote, LineKind::Text, LineKind::Quote]
57
);
58
}
59
60
#[test]
61
fn shift_enter_keeps_breaking_inside_the_quote() {
62
let mut draft = typed_draft(">a");
63
let cursor = enter(&mut draft, 1, true).unwrap();
64
let cursor = enter(&mut draft, cursor, true).unwrap();
65
assert_eq!(cursor, 3);
66
assert_eq!(
67
draft.lines(),
68
[LineKind::Quote, LineKind::Quote, LineKind::Quote]
69
);
70
}
71
72
#[test]
73
fn backspace_at_the_start_of_a_quote_leaves_it_or_joins_the_line_above() {
74
let mut empty = typed_draft(">");
75
assert_eq!(empty.backspace_at_start(0), Some(0));
76
assert_eq!(empty.lines(), [LineKind::Text]);
77
78
let mut joined = Draft::from_markdown("x\n> abc");
79
assert_eq!(joined.backspace_at_start(2), Some(1));
80
assert_eq!(joined.text(), "xabc");
81
assert_eq!(joined.lines(), [LineKind::Text]);
82
83
let mut inner = Draft::from_markdown("> a\n> b");
84
assert_eq!(inner.backspace_at_start(2), Some(1));
85
assert_eq!(inner.text(), "ab");
86
assert_eq!(inner.lines(), [LineKind::Quote]);
87
}
88
89
#[test]
90
fn down_at_the_end_of_a_closing_quote_opens_a_text_line_below() {
91
let mut draft = typed_draft(">abc");
92
assert_eq!(draft.leave_quote_at_end(1), None);
93
assert_eq!(draft.leave_quote_at_end(3), Some(4));
94
assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Text]);
95
assert_eq!(Draft::plain("x").leave_quote_at_end(1), None);
96
}
97
98
#[test]
99
fn teams_shortcuts_make_headings_bold_italic_and_code() {
100
let heading = typed_draft("## Plan");
101
assert_eq!(heading.text(), "Plan");
102
assert_eq!(heading.lines(), [LineKind::Heading(2)]);
103
assert_eq!(heading.to_html(), "<h2>Plan</h2>");
104
assert_eq!(typed_draft("#### deep").lines(), [LineKind::Heading(3)]);
105
assert_eq!(typed_draft("#nope").lines(), [LineKind::Text]);
106
107
let inline = typed_draft("*b* _i_ `c`");
108
assert_eq!(inline.text(), "b i c");
109
assert_eq!(
110
inline.marks(),
111
[
112
Mark {
113
range: 0..1,
114
kind: MarkKind::Bold
115
},
116
Mark {
117
range: 2..3,
118
kind: MarkKind::Italic
119
},
120
Mark {
121
range: 4..5,
122
kind: MarkKind::Code
123
},
124
]
125
);
126
}
127
128
#[test]
129
fn enter_in_a_heading_is_left_to_send_and_backspace_makes_it_text() {
130
let mut draft = typed_draft("# a");
131
assert_eq!(enter(&mut draft, 1, false), None);
132
assert_eq!(draft.backspace_at_start(0), Some(0));
133
assert_eq!(draft.lines(), [LineKind::Text]);
134
}
135
136
#[test]
137
fn an_inserted_table_takes_an_empty_line_and_gets_a_line_after_it() {
138
let mut draft = Draft::default();
139
let index = draft.insert_table(0, Table::new(2, 3));
140
assert_eq!(index, 0);
141
assert_eq!(draft.text(), format!("{TABLE_MARK}\n"));
142
assert!(draft.lines()[0].is_table());
143
assert_eq!(draft.lines()[1], LineKind::Text);
144
145
let mut below = Draft::plain("hello");
146
assert_eq!(below.insert_table(2, Table::new(1, 1)), 1);
147
assert_eq!(below.text(), format!("hello\n{TABLE_MARK}\n"));
148
}
149
150
#[test]
151
fn a_table_is_sent_as_teams_html_between_the_text() {
152
let mut draft = Draft::plain("before");
153
let index = draft.insert_table(6, Table::new(1, 2));
154
draft.set_table(index, table_of(&[&["a", "b"]]));
155
let end = draft.text().len();
156
let mut text = draft.text().to_owned();
157
text.push_str("after");
158
draft.apply_edit(&text, end + 5, None);
159
assert_eq!(
160
draft.trimmed().to_html(),
161
"before<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\
162
<tr><td>a</td><td>b</td></tr></tbody></table></figure>after"
163
);
164
assert_eq!(draft.plain_text(), "before\na\tb\nafter");
165
assert!(
166
!Draft::from_lines(&[DraftLine {
167
kind: LineKind::Table(Table::new(1, 1)),
168
number: None,
169
content: TABLE_MARK.to_string(),
170
marks: Vec::new(),
171
}])
172
.plain_text()
173
.contains(TABLE_MARK)
174
);
175
}
176
177
#[test]
178
fn text_typed_next_to_a_table_moves_to_its_own_line() {
179
let mut draft = Draft::default();
180
draft.insert_table(0, Table::new(1, 1));
181
let mark = TABLE_MARK.len_utf8();
182
let mut text = draft.text().to_owned();
183
text.insert(mark, 'x');
184
let cursor = draft.apply_edit(&text, mark + 1, None);
185
assert_eq!(draft.text(), format!("{TABLE_MARK}\nx\n"));
186
assert_eq!(cursor, mark + 2);
187
assert!(draft.lines()[0].is_table());
188
assert_eq!(draft.lines()[1], LineKind::Text);
189
190
let mut text = draft.text().to_owned();
191
text.insert(0, 'y');
192
let cursor = draft.apply_edit(&text, 1, None);
193
assert_eq!(draft.text(), format!("y\n{TABLE_MARK}\nx\n"));
194
assert_eq!(cursor, 1);
195
assert!(draft.lines()[1].is_table());
196
}
197
198
#[test]
199
fn deleting_the_mark_drops_the_table() {
200
let mut draft = Draft::plain("a");
201
draft.insert_table(1, Table::new(1, 1));
202
draft.apply_edit("a\n\n", 2, None);
203
assert!(draft.lines().iter().all(|kind| !kind.is_table()));
204
}
205
206
#[test]
207
fn delete_before_a_table_and_backspace_after_it_find_the_table() {
208
let mut draft = Draft::plain("a");
209
let index = draft.insert_table(1, Table::new(1, 1));
210
assert_eq!(draft.table_after(1), Some(index));
211
assert_eq!(draft.delete_forward(1), Some(1));
212
assert!(draft.lines()[index].is_table());
213
let after = draft.text().len();
214
assert_eq!(draft.table_before(after), Some(index));
215
assert_eq!(draft.table_before(0), None);
216
}
217
218
#[test]
219
fn leaving_a_table_lands_beside_it_and_adds_a_line_when_needed() {
220
let mut draft = Draft::default();
221
draft.insert_table(0, Table::new(1, 1));
222
assert_eq!(draft.line_beside_table(0, false), 0);
223
assert_eq!(draft.lines()[0], LineKind::Text);
224
assert!(draft.lines()[1].is_table());
225
let below = draft.line_beside_table(1, true);
226
assert_eq!(draft.line_at(below), 2);
227
}
228
229
#[test]
230
fn removing_a_table_keeps_the_lines_around_it() {
231
let mut draft = Draft::from_markdown("> a");
232
let index = draft.insert_table(3, Table::new(1, 1));
233
let end = draft.text().len();
234
let mut text = draft.text().to_owned();
235
text.push('z');
236
draft.apply_edit(&text, end + 1, None);
237
let cursor = draft.remove_table(index);
238
assert_eq!(draft.text(), "a\nz");
239
assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Text]);
240
assert_eq!(cursor, 2);
241
}
242
243
#[test]
244
fn quote_and_list_buttons_leave_a_table_alone() {
245
let mut draft = Draft::plain("a");
246
let index = draft.insert_table(1, Table::new(1, 1));
247
let end = draft.text().len();
248
draft.toggle_lines(0..end, LineKind::Quote);
249
assert!(draft.lines()[index].is_table());
250
}
251
252
#[test]
253
fn a_copied_table_pastes_into_the_middle_of_a_line() {
254
let mut source = Draft::default();
255
let index = source.insert_table(0, table_of(&[&["1", "2"]]));
256
let copied = source.slice(0..TABLE_MARK.len_utf8());
257
let mut draft = Draft::plain("abcd");
258
draft.insert_lines(2..2, &copied);
259
assert_eq!(draft.text(), format!("ab\n{TABLE_MARK}\ncd"));
260
assert_eq!(draft.table(1), source.table(index));
261
}
262
263
#[test]
264
fn pasted_markdown_becomes_headings_lists_quotes_code_and_tables() {
265
let markdown = "# Title\n\nSome **bold**, *it*, ~~gone~~, `code` and [docs](https://x.de)\n\n\
266
1. one\n 1. nested\n2. two\n- dot\n - inner\n\n> quoted\n\n```rust\nfn x() {}\n```\n\n\
267
| A | B |\n|---|---|\n| **1** | 2 |\n";
268
let draft = Draft::from_markdown(markdown);
269
let kinds: Vec<LineKind> = draft
270
.lines()
271
.iter()
272
.filter(|kind| **kind != LineKind::Text)
273
.cloned()
274
.collect();
275
assert_eq!(
276
kinds,
277
[
278
LineKind::Heading(1),
279
LineKind::Numbered(0),
280
LineKind::Numbered(1),
281
LineKind::Numbered(0),
282
LineKind::Bullet(0),
283
LineKind::Bullet(1),
284
LineKind::Quote,
285
LineKind::Code(Some("rust".into())),
286
LineKind::Table(table_of(&[&["A", "B"], &["1", "2"]])),
287
]
288
);
289
let html = draft.trimmed().to_html();
290
assert!(html.starts_with("<h1>Title</h1>"), "{html}");
291
assert!(html.contains("<b>bold</b>, <i>it</i>, <s>gone</s>, <code>code</code>"));
292
assert!(html.contains("<a href=\"https://x.de\">docs</a>"));
293
assert!(html.contains("<blockquote>quoted</blockquote>"));
294
assert!(html.contains("<pre class=\"language-rust\">fn x() {}</pre>"));
295
assert!(
296
html.ends_with("<td>1</td><td>2</td></tr></tbody></table></figure>"),
297
"{html}"
298
);
299
}
300
301
#[test]
302
fn text_with_pipes_but_no_delimiter_row_stays_text() {
303
assert!(!teams_core::has_markdown("a | b\nc | d"));
304
assert!(teams_core::has_markdown("| a | b |\n| - | - |"));
305
assert!(teams_core::has_markdown("## Heading"));
306
}
307
308
#[test]
309
fn received_tables_and_headings_edit_as_tables_and_headings() {
310
let spans = html_to_spans(
311
"<h2>Notes</h2><table><tbody><tr><td><p>a</p></td><td>b<br>c</td></tr></tbody></table><p>end</p>",
312
);
313
let draft = Draft::from_spans(&spans);
314
assert_eq!(draft.lines()[0], LineKind::Heading(2));
315
assert_eq!(
316
draft.lines()[1],
317
LineKind::Table(table_of(&[&["a", "b\nc"]]))
318
);
319
assert_eq!(draft.lines()[2], LineKind::Text);
320
}
321
322
#[test]
323
fn pasting_markdown_with_a_table_leaves_the_cursor_after_the_paste() {
324
let markdown = "## Plan\n- dot\n> quoted\n\n| Area | Owner |\n|---|---|\n| Sync | Priya |\nend";
325
let lines = Draft::from_markdown(markdown).slice(0..usize::MAX);
326
let mut draft = Draft::default();
327
let cursor = draft.insert_lines(0..0, &lines);
328
assert_eq!(cursor, draft.text().len(), "{:?}", draft.text());
329
}
330
331
#[test]
332
fn a_sent_table_edits_back_into_the_same_table() {
333
let table = table_of(&[&["a", "x\ny"], &["", "b"]]);
334
let draft = Draft::from_spans(&html_to_spans(&table.to_html()));
335
let LineKind::Table(received) = &draft.lines()[0] else {
336
panic!("{:?}", draft.lines());
337
};
338
assert_eq!(received.rows[0], ["a", "x\ny"]);
339
assert!(received.rows[1][0].trim().is_empty());
340
assert_eq!(received.to_html(), table.to_html());
341
}
@@ -0,0 +1,341 @@1
use teams_core::{2
Draft, DraftLine, LineKind, Mark, MarkKind, TABLE_MARK, Table, TypingStyle, html_to_spans,3
};4
5
fn typed(draft: &mut Draft, text: &str) {6
let mut typing: Option<TypingStyle> = None;7
for character in text.chars() {8
let cursor = draft.text().len();9
let mut next = draft.text().to_owned();10
next.push(character);11
let cursor = draft.apply_edit(&next, cursor + character.len_utf8(), typing.as_ref());12
typing = draft.convert_typed(cursor).map(|(_, style)| style);13
draft.take_edits();14
}15
}16
17
fn typed_draft(text: &str) -> Draft {18
let mut draft = Draft::default();19
typed(&mut draft, text);20
draft21
}22
23
fn enter(draft: &mut Draft, cursor: usize, shift: bool) -> Option<usize> {24
let result = draft.break_line(cursor, shift);25
draft.take_edits();26
result27
}28
29
fn table_of(rows: &[&[&str]]) -> Table {30
Table::from_rows(31
rows.iter()32
.map(|row| row.iter().map(|cell| (*cell).to_owned()).collect())33
.collect(),34
)35
}36
37
#[test]38
fn enter_in_a_quote_adds_a_quote_line_and_enter_on_the_empty_one_leaves() {39
let mut draft = typed_draft(">abc");40
let cursor = enter(&mut draft, 3, false).unwrap();41
assert_eq!(draft.text(), "abc\n");42
assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Quote]);43
let cursor = enter(&mut draft, cursor, false).unwrap();44
assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Text]);45
assert_eq!(cursor, 4);46
assert_eq!(enter(&mut draft, cursor, false), None);47
assert_eq!(draft.to_html(), "<blockquote>abc</blockquote>");48
}49
50
#[test]51
fn enter_on_an_empty_quote_line_in_the_middle_splits_the_quote() {52
let mut draft = Draft::from_markdown("> a\n> \n> b");53
enter(&mut draft, 2, false).unwrap();54
assert_eq!(55
draft.lines(),56
[LineKind::Quote, LineKind::Text, LineKind::Quote]57
);58
}59
60
#[test]61
fn shift_enter_keeps_breaking_inside_the_quote() {62
let mut draft = typed_draft(">a");63
let cursor = enter(&mut draft, 1, true).unwrap();64
let cursor = enter(&mut draft, cursor, true).unwrap();65
assert_eq!(cursor, 3);66
assert_eq!(67
draft.lines(),68
[LineKind::Quote, LineKind::Quote, LineKind::Quote]69
);70
}71
72
#[test]73
fn backspace_at_the_start_of_a_quote_leaves_it_or_joins_the_line_above() {74
let mut empty = typed_draft(">");75
assert_eq!(empty.backspace_at_start(0), Some(0));76
assert_eq!(empty.lines(), [LineKind::Text]);77
78
let mut joined = Draft::from_markdown("x\n> abc");79
assert_eq!(joined.backspace_at_start(2), Some(1));80
assert_eq!(joined.text(), "xabc");81
assert_eq!(joined.lines(), [LineKind::Text]);82
83
let mut inner = Draft::from_markdown("> a\n> b");84
assert_eq!(inner.backspace_at_start(2), Some(1));85
assert_eq!(inner.text(), "ab");86
assert_eq!(inner.lines(), [LineKind::Quote]);87
}88
89
#[test]90
fn down_at_the_end_of_a_closing_quote_opens_a_text_line_below() {91
let mut draft = typed_draft(">abc");92
assert_eq!(draft.leave_quote_at_end(1), None);93
assert_eq!(draft.leave_quote_at_end(3), Some(4));94
assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Text]);95
assert_eq!(Draft::plain("x").leave_quote_at_end(1), None);96
}97
98
#[test]99
fn teams_shortcuts_make_headings_bold_italic_and_code() {100
let heading = typed_draft("## Plan");101
assert_eq!(heading.text(), "Plan");102
assert_eq!(heading.lines(), [LineKind::Heading(2)]);103
assert_eq!(heading.to_html(), "<h2>Plan</h2>");104
assert_eq!(typed_draft("#### deep").lines(), [LineKind::Heading(3)]);105
assert_eq!(typed_draft("#nope").lines(), [LineKind::Text]);106
107
let inline = typed_draft("*b* _i_ `c`");108
assert_eq!(inline.text(), "b i c");109
assert_eq!(110
inline.marks(),111
[112
Mark {113
range: 0..1,114
kind: MarkKind::Bold115
},116
Mark {117
range: 2..3,118
kind: MarkKind::Italic119
},120
Mark {121
range: 4..5,122
kind: MarkKind::Code123
},124
]125
);126
}127
128
#[test]129
fn enter_in_a_heading_is_left_to_send_and_backspace_makes_it_text() {130
let mut draft = typed_draft("# a");131
assert_eq!(enter(&mut draft, 1, false), None);132
assert_eq!(draft.backspace_at_start(0), Some(0));133
assert_eq!(draft.lines(), [LineKind::Text]);134
}135
136
#[test]137
fn an_inserted_table_takes_an_empty_line_and_gets_a_line_after_it() {138
let mut draft = Draft::default();139
let index = draft.insert_table(0, Table::new(2, 3));140
assert_eq!(index, 0);141
assert_eq!(draft.text(), format!("{TABLE_MARK}\n"));142
assert!(draft.lines()[0].is_table());143
assert_eq!(draft.lines()[1], LineKind::Text);144
145
let mut below = Draft::plain("hello");146
assert_eq!(below.insert_table(2, Table::new(1, 1)), 1);147
assert_eq!(below.text(), format!("hello\n{TABLE_MARK}\n"));148
}149
150
#[test]151
fn a_table_is_sent_as_teams_html_between_the_text() {152
let mut draft = Draft::plain("before");153
let index = draft.insert_table(6, Table::new(1, 2));154
draft.set_table(index, table_of(&[&["a", "b"]]));155
let end = draft.text().len();156
let mut text = draft.text().to_owned();157
text.push_str("after");158
draft.apply_edit(&text, end + 5, None);159
assert_eq!(160
draft.trimmed().to_html(),161
"before<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\162
<tr><td>a</td><td>b</td></tr></tbody></table></figure>after"163
);164
assert_eq!(draft.plain_text(), "before\na\tb\nafter");165
assert!(166
!Draft::from_lines(&[DraftLine {167
kind: LineKind::Table(Table::new(1, 1)),168
number: None,169
content: TABLE_MARK.to_string(),170
marks: Vec::new(),171
}])172
.plain_text()173
.contains(TABLE_MARK)174
);175
}176
177
#[test]178
fn text_typed_next_to_a_table_moves_to_its_own_line() {179
let mut draft = Draft::default();180
draft.insert_table(0, Table::new(1, 1));181
let mark = TABLE_MARK.len_utf8();182
let mut text = draft.text().to_owned();183
text.insert(mark, 'x');184
let cursor = draft.apply_edit(&text, mark + 1, None);185
assert_eq!(draft.text(), format!("{TABLE_MARK}\nx\n"));186
assert_eq!(cursor, mark + 2);187
assert!(draft.lines()[0].is_table());188
assert_eq!(draft.lines()[1], LineKind::Text);189
190
let mut text = draft.text().to_owned();191
text.insert(0, 'y');192
let cursor = draft.apply_edit(&text, 1, None);193
assert_eq!(draft.text(), format!("y\n{TABLE_MARK}\nx\n"));194
assert_eq!(cursor, 1);195
assert!(draft.lines()[1].is_table());196
}197
198
#[test]199
fn deleting_the_mark_drops_the_table() {200
let mut draft = Draft::plain("a");201
draft.insert_table(1, Table::new(1, 1));202
draft.apply_edit("a\n\n", 2, None);203
assert!(draft.lines().iter().all(|kind| !kind.is_table()));204
}205
206
#[test]207
fn delete_before_a_table_and_backspace_after_it_find_the_table() {208
let mut draft = Draft::plain("a");209
let index = draft.insert_table(1, Table::new(1, 1));210
assert_eq!(draft.table_after(1), Some(index));211
assert_eq!(draft.delete_forward(1), Some(1));212
assert!(draft.lines()[index].is_table());213
let after = draft.text().len();214
assert_eq!(draft.table_before(after), Some(index));215
assert_eq!(draft.table_before(0), None);216
}217
218
#[test]219
fn leaving_a_table_lands_beside_it_and_adds_a_line_when_needed() {220
let mut draft = Draft::default();221
draft.insert_table(0, Table::new(1, 1));222
assert_eq!(draft.line_beside_table(0, false), 0);223
assert_eq!(draft.lines()[0], LineKind::Text);224
assert!(draft.lines()[1].is_table());225
let below = draft.line_beside_table(1, true);226
assert_eq!(draft.line_at(below), 2);227
}228
229
#[test]230
fn removing_a_table_keeps_the_lines_around_it() {231
let mut draft = Draft::from_markdown("> a");232
let index = draft.insert_table(3, Table::new(1, 1));233
let end = draft.text().len();234
let mut text = draft.text().to_owned();235
text.push('z');236
draft.apply_edit(&text, end + 1, None);237
let cursor = draft.remove_table(index);238
assert_eq!(draft.text(), "a\nz");239
assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Text]);240
assert_eq!(cursor, 2);241
}242
243
#[test]244
fn quote_and_list_buttons_leave_a_table_alone() {245
let mut draft = Draft::plain("a");246
let index = draft.insert_table(1, Table::new(1, 1));247
let end = draft.text().len();248
draft.toggle_lines(0..end, LineKind::Quote);249
assert!(draft.lines()[index].is_table());250
}251
252
#[test]253
fn a_copied_table_pastes_into_the_middle_of_a_line() {254
let mut source = Draft::default();255
let index = source.insert_table(0, table_of(&[&["1", "2"]]));256
let copied = source.slice(0..TABLE_MARK.len_utf8());257
let mut draft = Draft::plain("abcd");258
draft.insert_lines(2..2, &copied);259
assert_eq!(draft.text(), format!("ab\n{TABLE_MARK}\ncd"));260
assert_eq!(draft.table(1), source.table(index));261
}262
263
#[test]264
fn pasted_markdown_becomes_headings_lists_quotes_code_and_tables() {265
let markdown = "# Title\n\nSome **bold**, *it*, ~~gone~~, `code` and [docs](https://x.de)\n\n\266
1. one\n 1. nested\n2. two\n- dot\n - inner\n\n> quoted\n\n```rust\nfn x() {}\n```\n\n\267
| A | B |\n|---|---|\n| **1** | 2 |\n";268
let draft = Draft::from_markdown(markdown);269
let kinds: Vec<LineKind> = draft270
.lines()271
.iter()272
.filter(|kind| **kind != LineKind::Text)273
.cloned()274
.collect();275
assert_eq!(276
kinds,277
[278
LineKind::Heading(1),279
LineKind::Numbered(0),280
LineKind::Numbered(1),281
LineKind::Numbered(0),282
LineKind::Bullet(0),283
LineKind::Bullet(1),284
LineKind::Quote,285
LineKind::Code(Some("rust".into())),286
LineKind::Table(table_of(&[&["A", "B"], &["1", "2"]])),287
]288
);289
let html = draft.trimmed().to_html();290
assert!(html.starts_with("<h1>Title</h1>"), "{html}");291
assert!(html.contains("<b>bold</b>, <i>it</i>, <s>gone</s>, <code>code</code>"));292
assert!(html.contains("<a href=\"https://x.de\">docs</a>"));293
assert!(html.contains("<blockquote>quoted</blockquote>"));294
assert!(html.contains("<pre class=\"language-rust\">fn x() {}</pre>"));295
assert!(296
html.ends_with("<td>1</td><td>2</td></tr></tbody></table></figure>"),297
"{html}"298
);299
}300
301
#[test]302
fn text_with_pipes_but_no_delimiter_row_stays_text() {303
assert!(!teams_core::has_markdown("a | b\nc | d"));304
assert!(teams_core::has_markdown("| a | b |\n| - | - |"));305
assert!(teams_core::has_markdown("## Heading"));306
}307
308
#[test]309
fn received_tables_and_headings_edit_as_tables_and_headings() {310
let spans = html_to_spans(311
"<h2>Notes</h2><table><tbody><tr><td><p>a</p></td><td>b<br>c</td></tr></tbody></table><p>end</p>",312
);313
let draft = Draft::from_spans(&spans);314
assert_eq!(draft.lines()[0], LineKind::Heading(2));315
assert_eq!(316
draft.lines()[1],317
LineKind::Table(table_of(&[&["a", "b\nc"]]))318
);319
assert_eq!(draft.lines()[2], LineKind::Text);320
}321
322
#[test]323
fn pasting_markdown_with_a_table_leaves_the_cursor_after_the_paste() {324
let markdown = "## Plan\n- dot\n> quoted\n\n| Area | Owner |\n|---|---|\n| Sync | Priya |\nend";325
let lines = Draft::from_markdown(markdown).slice(0..usize::MAX);326
let mut draft = Draft::default();327
let cursor = draft.insert_lines(0..0, &lines);328
assert_eq!(cursor, draft.text().len(), "{:?}", draft.text());329
}330
331
#[test]332
fn a_sent_table_edits_back_into_the_same_table() {333
let table = table_of(&[&["a", "x\ny"], &["", "b"]]);334
let draft = Draft::from_spans(&html_to_spans(&table.to_html()));335
let LineKind::Table(received) = &draft.lines()[0] else {336
panic!("{:?}", draft.lines());337
};338
assert_eq!(received.rows[0], ["a", "x\ny"]);339
assert!(received.rows[1][0].trim().is_empty());340
assert_eq!(received.to_html(), table.to_html());341
}@@ -3,9 +3,9 @@ use std::rc::Rc;
3
3
use gpui::prelude::FluentBuilder as _;
4
4
use gpui::{
5
5
AccessibleAction, AnyElement, App, DefiniteLength, Edges, ElementId, Entity, Hsla,
6
InteractiveElement as _, IntoElement, ParentElement as _, Rems, RenderOnce, Role, SharedString,
7
StatefulInteractiveElement as _, StyleRefinement, Styled, TextAlign, TouchPhase, Window, div,
8
px, relative,
6
InteractiveElement as _, IntoElement, ParentElement as _, Pixels, Rems, RenderOnce, Role,
7
SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, TextAlign, TouchPhase,
8
Window, div, px, relative,
9
9
};
10
10
11
11
use crate::button::{Button, ButtonRounded, ButtonVariants as _};
@@ -119,6 +119,7 @@ pub struct Input {
119
119
prefix: Option<AnyElement>,
120
120
suffix: Option<AnyElement>,
121
121
height: Option<DefiniteLength>,
122
line_box_height: Option<Pixels>,
122
123
appearance: bool,
123
124
cleanable: bool,
124
125
mask_toggle: bool,
@@ -246,6 +247,7 @@ impl Input {
246
247
aria_label: None,
247
248
context_menu_builder: None,
248
249
paste_handler: None,
250
line_box_height: None,
249
251
token_renderer: None,
250
252
token_click_listener: None,
251
253
token_hover_listener: None,
@@ -295,6 +297,14 @@ impl Input {
295
297
self
296
298
}
297
299
300
/// Center each text line of a multi-line input in a box this tall, in
301
/// place of the size's vertical padding, so a single line is exactly this
302
/// tall and lines up with controls of the same height beside it.
303
pub fn line_box_height(mut self, height: Pixels) -> Self {
304
self.line_box_height = Some(height);
305
self
306
}
307
298
308
/// Set the appearance of the input field, if false the input field will no border, background.
299
309
pub fn appearance(mut self, appearance: bool) -> Self {
300
310
self.appearance = appearance;
@@ -588,12 +598,15 @@ impl RenderOnce for Input {
588
598
},
589
599
cx,
590
600
);
601
let padding_y = self.line_box_height.map_or(self.size.input_py(), |height| {
602
((height - LINE_HEIGHT.to_pixels(window.rem_size())) / 2.).max(px(0.))
603
});
591
604
state.set_editor_paddings(
592
605
if state.presentation(cx).is_multi_line() {
593
606
Edges {
594
top: self.size.input_py(),
607
top: padding_y,
595
608
right: self.size.input_px(),
596
bottom: self.size.input_py(),
609
bottom: padding_y,
597
610
left: if state.presentation(cx).is_code_editor() {
598
611
self.size.input_px().min(px(6.))
599
612
} else {
@@ -3,9 +3,9 @@ use std::rc::Rc;3
use gpui::prelude::FluentBuilder as _;3
use gpui::prelude::FluentBuilder as _;4
use gpui::{4
use gpui::{5
AccessibleAction, AnyElement, App, DefiniteLength, Edges, ElementId, Entity, Hsla,5
AccessibleAction, AnyElement, App, DefiniteLength, Edges, ElementId, Entity, Hsla,6
InteractiveElement as _, IntoElement, ParentElement as _, Rems, RenderOnce, Role, SharedString,6
InteractiveElement as _, IntoElement, ParentElement as _, Pixels, Rems, RenderOnce, Role,7
StatefulInteractiveElement as _, StyleRefinement, Styled, TextAlign, TouchPhase, Window, div,7
SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, TextAlign, TouchPhase,8
px, relative,8
Window, div, px, relative,9
};9
};10
10
11
use crate::button::{Button, ButtonRounded, ButtonVariants as _};11
use crate::button::{Button, ButtonRounded, ButtonVariants as _};@@ -119,6 +119,7 @@ pub struct Input {119
prefix: Option<AnyElement>,119
prefix: Option<AnyElement>,120
suffix: Option<AnyElement>,120
suffix: Option<AnyElement>,121
height: Option<DefiniteLength>,121
height: Option<DefiniteLength>,122
line_box_height: Option<Pixels>,122
appearance: bool,123
appearance: bool,123
cleanable: bool,124
cleanable: bool,124
mask_toggle: bool,125
mask_toggle: bool,@@ -246,6 +247,7 @@ impl Input {246
aria_label: None,247
aria_label: None,247
context_menu_builder: None,248
context_menu_builder: None,248
paste_handler: None,249
paste_handler: None,250
line_box_height: None,249
token_renderer: None,251
token_renderer: None,250
token_click_listener: None,252
token_click_listener: None,251
token_hover_listener: None,253
token_hover_listener: None,@@ -295,6 +297,14 @@ impl Input {295
self297
self296
}298
}297
299
300
/// Center each text line of a multi-line input in a box this tall, in301
/// place of the size's vertical padding, so a single line is exactly this302
/// tall and lines up with controls of the same height beside it.303
pub fn line_box_height(mut self, height: Pixels) -> Self {304
self.line_box_height = Some(height);305
self306
}307
298
/// Set the appearance of the input field, if false the input field will no border, background.308
/// Set the appearance of the input field, if false the input field will no border, background.299
pub fn appearance(mut self, appearance: bool) -> Self {309
pub fn appearance(mut self, appearance: bool) -> Self {300
self.appearance = appearance;310
self.appearance = appearance;@@ -588,12 +598,15 @@ impl RenderOnce for Input {588
},598
},589
cx,599
cx,590
);600
);601
let padding_y = self.line_box_height.map_or(self.size.input_py(), |height| {602
((height - LINE_HEIGHT.to_pixels(window.rem_size())) / 2.).max(px(0.))603
});591
state.set_editor_paddings(604
state.set_editor_paddings(592
if state.presentation(cx).is_multi_line() {605
if state.presentation(cx).is_multi_line() {593
Edges {606
Edges {594
top: self.size.input_py(),607
top: padding_y,595
right: self.size.input_px(),608
right: self.size.input_px(),596
bottom: self.size.input_py(),609
bottom: padding_y,597
left: if state.presentation(cx).is_code_editor() {610
left: if state.presentation(cx).is_code_editor() {598
self.size.input_px().min(px(6.))611
self.size.input_px().min(px(6.))599
} else {612
} else {@@ -1,8 +1,8 @@
1
1
use std::rc::Rc;
2
2
3
3
use gpui::{
4
App, DefiniteLength, Entity, IntoElement, RenderOnce, SharedString, StyleRefinement, Styled,
5
Window, prelude::FluentBuilder as _,
4
App, DefiniteLength, Entity, IntoElement, Pixels, RenderOnce, SharedString, StyleRefinement,
5
Styled, Window, prelude::FluentBuilder as _,
6
6
};
7
7
8
8
use super::{Input, TextareaState};
@@ -19,6 +19,7 @@ pub struct Textarea {
19
19
style: StyleRefinement,
20
20
size: Size,
21
21
height: Option<DefiniteLength>,
22
line_box_height: Option<Pixels>,
22
23
appearance: bool,
23
24
bordered: bool,
24
25
disabled: bool,
@@ -73,6 +74,7 @@ impl Textarea {
73
74
style: StyleRefinement::default(),
74
75
size: Size::default(),
75
76
height: None,
77
line_box_height: None,
76
78
appearance: true,
77
79
bordered: true,
78
80
disabled: false,
@@ -94,6 +96,12 @@ impl Textarea {
94
96
self
95
97
}
96
98
99
/// See [`Input::line_box_height`].
100
pub fn line_box_height(mut self, height: Pixels) -> Self {
101
self.line_box_height = Some(height);
102
self
103
}
104
97
105
pub fn appearance(mut self, appearance: bool) -> Self {
98
106
self.appearance = appearance;
99
107
self
@@ -204,6 +212,9 @@ impl Textarea {
204
212
.role(self.role)
205
213
.with_size(self.size)
206
214
.when_some(self.height, |this, height| this.h(height))
215
.when_some(self.line_box_height, |this, height| {
216
this.line_box_height(height)
217
})
207
218
.when_some(self.accessibility_id, |this, id| this.accessibility_id(id))
208
219
.when_some(self.aria_label, |this, label| this.aria_label(label))
209
220
.when_some(self.context_menu_builder, |this, build| {
@@ -1,8 +1,8 @@1
use std::rc::Rc;1
use std::rc::Rc;2
2
3
use gpui::{3
use gpui::{4
App, DefiniteLength, Entity, IntoElement, RenderOnce, SharedString, StyleRefinement, Styled,4
App, DefiniteLength, Entity, IntoElement, Pixels, RenderOnce, SharedString, StyleRefinement,5
Window, prelude::FluentBuilder as _,5
Styled, Window, prelude::FluentBuilder as _,6
};6
};7
7
8
use super::{Input, TextareaState};8
use super::{Input, TextareaState};@@ -19,6 +19,7 @@ pub struct Textarea {19
style: StyleRefinement,19
style: StyleRefinement,20
size: Size,20
size: Size,21
height: Option<DefiniteLength>,21
height: Option<DefiniteLength>,22
line_box_height: Option<Pixels>,22
appearance: bool,23
appearance: bool,23
bordered: bool,24
bordered: bool,24
disabled: bool,25
disabled: bool,@@ -73,6 +74,7 @@ impl Textarea {73
style: StyleRefinement::default(),74
style: StyleRefinement::default(),74
size: Size::default(),75
size: Size::default(),75
height: None,76
height: None,77
line_box_height: None,76
appearance: true,78
appearance: true,77
bordered: true,79
bordered: true,78
disabled: false,80
disabled: false,@@ -94,6 +96,12 @@ impl Textarea {94
self96
self95
}97
}96
98
99
/// See [`Input::line_box_height`].100
pub fn line_box_height(mut self, height: Pixels) -> Self {101
self.line_box_height = Some(height);102
self103
}104
97
pub fn appearance(mut self, appearance: bool) -> Self {105
pub fn appearance(mut self, appearance: bool) -> Self {98
self.appearance = appearance;106
self.appearance = appearance;99
self107
self@@ -204,6 +212,9 @@ impl Textarea {204
.role(self.role)212
.role(self.role)205
.with_size(self.size)213
.with_size(self.size)206
.when_some(self.height, |this, height| this.h(height))214
.when_some(self.height, |this, height| this.h(height))215
.when_some(self.line_box_height, |this, height| {216
this.line_box_height(height)217
})207
.when_some(self.accessibility_id, |this, id| this.accessibility_id(id))218
.when_some(self.accessibility_id, |this, id| this.accessibility_id(id))208
.when_some(self.aria_label, |this, label| this.aria_label(label))219
.when_some(self.aria_label, |this, label| this.aria_label(label))209
.when_some(self.context_menu_builder, |this, build| {220
.when_some(self.context_menu_builder, |this, build| {