feat(composer): insert and edit tables, leave quotes, paste plain text
- table button with 7x5 size picker, cell inputs, Tab/Shift+Tab/Up/Down - right-click menu: insert row/column, delete row/column/table (Teams strings) - ArrowDown/Right at the end of a closing quote leaves it - Ctrl+Shift+V pastes as plain text - headings drawn at 1.6/1.35/1.15 scale Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -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>@@ -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
);@@ -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;
@@ -126,8 +131,19 @@ struct Conversion {
126
131
127
132
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128
133
enum StepKind {
129
Typing { at: usize, after_space: bool },
130
Deleting { start: usize, end: usize },
134
Typing {
135
at: usize,
136
after_space: bool,
137
},
138
Deleting {
139
start: usize,
140
end: usize,
141
},
142
CellTyping {
143
table: usize,
144
row: usize,
145
column: usize,
146
},
131
147
Other,
132
148
}
133
149
@@ -192,6 +208,12 @@ pub struct Composer {
192
208
pending_anchors: HashMap<u64, usize>,
193
209
link: ComposeLink,
194
210
fun_picker: Entity<FunPicker>,
211
tables: TableViews,
212
table_counter: usize,
213
table_picker: Option<TablePicker>,
214
active_cell: Option<(String, teams_core::Cell)>,
215
caret_before_table: usize,
216
caret_text: String,
195
217
_subscriptions: [Subscription; 4],
196
218
}
197
219
@@ -292,6 +314,9 @@ fn continues(last: &HistoryStep, kind: StepKind) -> bool {
292
314
(StepKind::Deleting { .. }, StepKind::Deleting { start, end }) => {
293
315
caret.is_empty() && (caret.start == end || caret.start == start)
294
316
}
317
(previous @ StepKind::CellTyping { .. }, next @ StepKind::CellTyping { .. }) => {
318
previous == next
319
}
295
320
_ => false,
296
321
}
297
322
}
@@ -328,7 +353,10 @@ impl Composer {
328
353
.placeholder("Type a message")
329
354
});
330
355
let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
331
let observer = cx.observe(&input, |_, _, cx| cx.notify());
356
let observer = cx.observe_in(&input, window, |this, _, window, cx| {
357
this.redirect_caret_from_table(window, cx);
358
cx.notify();
359
});
332
360
let image_observer = cx.observe(&app, |this, _, cx| {
333
361
if this.link_image_pending(cx) {
334
362
cx.notify();
@@ -389,6 +417,12 @@ impl Composer {
389
417
pending_anchors: HashMap::new(),
390
418
link: ComposeLink::default(),
391
419
fun_picker,
420
tables: TableViews::default(),
421
table_counter: 0,
422
table_picker: None,
423
active_cell: None,
424
caret_before_table: 0,
425
caret_text: String::new(),
392
426
_subscriptions: [subscription, observer, image_observer, picker_subscription],
393
427
}
394
428
}
@@ -640,6 +674,7 @@ impl Composer {
640
674
}
641
675
self.previous_value = value;
642
676
self.refresh_style(cx);
677
self.sync_tables(window, cx);
643
678
}
644
679
645
680
fn shift_anchors(&mut self, start: usize, old_end: usize, new_end: usize) {
@@ -737,6 +772,7 @@ impl Composer {
737
772
self.conversion = None;
738
773
self.paste_hint = None;
739
774
self.refresh_style(cx);
775
self.sync_tables(window, cx);
740
776
self.update_emoji(cx);
741
777
self.update_mention(cx);
742
778
self.schedule_draft_save(cx);
@@ -775,6 +811,9 @@ impl Composer {
775
811
self.link_editor = None;
776
812
self.toolbar_dismissed = None;
777
813
self.pending_anchors.clear();
814
self.active_cell = None;
815
self.table_picker = None;
816
self.sync_tables(window, cx);
778
817
self.history.clear();
779
818
self.history_index = 0;
780
819
self.record(StepKind::Other, cx);
@@ -1064,6 +1103,64 @@ impl Composer {
1064
1103
}
1065
1104
}
1066
1105
1106
fn leave_quote(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
1107
let selection = self.selection(cx);
1108
if !selection.is_empty() || self.input.read(cx).value().as_ref() != self.draft.text() {
1109
return false;
1110
}
1111
match self.draft.leave_quote_at_end(selection.start) {
1112
Some(cursor) => {
1113
self.commit(Some(cursor), window, cx);
1114
true
1115
}
1116
None => false,
1117
}
1118
}
1119
1120
/// Backspace right after a table or Delete right before one goes into it instead of
1121
/// joining the line with the table's.
1122
fn enter_table_beside(
1123
&mut self,
1124
after: bool,
1125
window: &mut Window,
1126
cx: &mut Context<Self>,
1127
) -> bool {
1128
let selection = self.selection(cx);
1129
if !selection.is_empty() || self.input.read(cx).value().as_ref() != self.draft.text() {
1130
return false;
1131
}
1132
let found = if after {
1133
self.draft.table_before(selection.start)
1134
} else {
1135
self.draft.table_after(selection.start)
1136
};
1137
let Some(index) = found else {
1138
return false;
1139
};
1140
self.focus_table_line(index, after, window, cx);
1141
true
1142
}
1143
1144
fn cell_has_focus(&self, window: &Window, cx: &App) -> bool {
1145
self.focused_cell(window, cx).is_some()
1146
}
1147
1148
fn paste_plain(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1149
let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) else {
1150
return;
1151
};
1152
let text = text
1153
.replace("\r\n", "\n")
1154
.replace([OBJECT_MARK, TABLE_MARK], "");
1155
if let Some(input) = self.focused_cell_input(window, cx) {
1156
input.update(cx, |state, cx| state.replace(text, window, cx));
1157
return;
1158
}
1159
self.pasted_markdown = None;
1160
self.input
1161
.update(cx, |state, cx| state.replace(text, window, cx));
1162
}
1163
1067
1164
fn indent(&mut self, outdent: bool, window: &mut Window, cx: &mut Context<Self>) -> bool {
1068
1165
let selection = self.selection(cx);
1069
1166
if !self.draft.indent(selection, outdent) {
@@ -1079,12 +1176,16 @@ impl Composer {
1079
1176
return false;
1080
1177
}
1081
1178
let selected = &self.draft.text()[selection.clone()];
1082
let text = selected.replace(OBJECT_MARK, "");
1083
1179
let lines = if selected.contains(OBJECT_MARK) {
1084
1180
self.draft.slice_without_objects(selection)
1085
1181
} else {
1086
1182
self.draft.slice(selection)
1087
1183
};
1184
let text = if selected.contains(TABLE_MARK) {
1185
Draft::from_lines(&lines).plain_text()
1186
} else {
1187
selected.replace(OBJECT_MARK, "")
1188
};
1088
1189
if text.is_empty() {
1089
1190
return true;
1090
1191
}
@@ -1150,8 +1251,8 @@ impl Composer {
1150
1251
}
1151
1252
let matches = emoji::search(&query, &self.recent_emoji.glyphs(), emoji_popup::LIMIT);
1152
1253
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));
1254
self.emoji_popup =
1255
(!matches.is_empty()).then(|| EmojiPopup::new(range, query, matches, skin_tone));
1155
1256
}
1156
1257
1157
1258
fn accept_emoji(&mut self, window: &mut Window, cx: &mut Context<Self>) {
@@ -1764,8 +1865,8 @@ impl Composer {
1764
1865
let Some(text) = item.text() else {
1765
1866
return false;
1766
1867
};
1767
if text.contains(OBJECT_MARK) {
1768
let cleaned = text.replace(OBJECT_MARK, "");
1868
if text.contains([OBJECT_MARK, TABLE_MARK]) {
1869
let cleaned = text.replace([OBJECT_MARK, TABLE_MARK], "");
1769
1870
self.input
1770
1871
.update(cx, |state, cx| state.replace(cleaned, window, cx));
1771
1872
return true;
@@ -2465,6 +2566,24 @@ impl Render for Composer {
2465
2566
))
2466
2567
.on_click(cx.listener(|this, _, window, cx| this.open_picker(window, cx)))
2467
2568
});
2569
let table_button = can_attach.then(|| {
2570
div()
2571
.id("composer-table")
2572
.size(px(32.))
2573
.flex_none()
2574
.flex()
2575
.items_center()
2576
.justify_center()
2577
.rounded(px(8.))
2578
.cursor_pointer()
2579
.hover(|button| button.bg(theme::popup_hover()))
2580
.when(self.table_picker.is_some(), |button| {
2581
button.bg(theme::popup_hover())
2582
})
2583
.tooltip(|window, cx| Tooltip::new("Insert table").build(window, cx))
2584
.child(symbol("table", COMPOSER_ICON_SIZE, theme::text_muted()))
2585
.on_click(cx.listener(|this, _, _, cx| this.open_table_picker(cx)))
2586
});
2468
2587
let composer = cx.weak_entity();
2469
2588
let tokens_composer = composer.clone();
2470
2589
let input = Textarea::new(&self.input)
@@ -2476,6 +2595,17 @@ impl Render for Composer {
2476
2595
.unwrap_or(false)
2477
2596
})
2478
2597
.token(move |context, _, cx| {
2598
if context.is_block() && is_table_token(context.token()) {
2599
let token_id = context.token().id().to_string();
2600
let width = context.available_width();
2601
if let Some(table) = tokens_composer
2602
.read_with(cx, |this, _| this.render_table_token(&token_id, width))
2603
.ok()
2604
.flatten()
2605
{
2606
return table;
2607
}
2608
}
2479
2609
if let Some(id) = context
2480
2610
.is_block()
2481
2611
.then(|| image_id(context.token()))
@@ -2549,42 +2679,70 @@ impl Render for Composer {
2549
2679
.pt(px(top))
2550
2680
.pb(px(bottom))
2551
2681
.key_context(COMPOSER_KEY_CONTEXT)
2552
.on_action(cx.listener(|this, _: &ToggleBold, _, cx| {
2553
if this.link_editor.is_none() {
2682
.on_action(cx.listener(|this, _: &ToggleBold, window, cx| {
2683
if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
2554
2684
this.toggle_mark(MarkKind::Bold, cx);
2555
2685
}
2556
2686
}))
2557
.on_action(cx.listener(|this, _: &ToggleItalic, _, cx| {
2558
if this.link_editor.is_none() {
2687
.on_action(cx.listener(|this, _: &ToggleItalic, window, cx| {
2688
if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
2559
2689
this.toggle_mark(MarkKind::Italic, cx);
2560
2690
}
2561
2691
}))
2562
.on_action(cx.listener(|this, _: &ToggleUnderline, _, cx| {
2563
if this.link_editor.is_none() {
2692
.on_action(cx.listener(|this, _: &ToggleUnderline, window, cx| {
2693
if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
2564
2694
this.toggle_mark(MarkKind::Underline, cx);
2565
2695
}
2566
2696
}))
2567
.on_action(cx.listener(|this, _: &ToggleStrike, _, cx| {
2568
if this.link_editor.is_none() {
2697
.on_action(cx.listener(|this, _: &ToggleStrike, window, cx| {
2698
if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
2569
2699
this.toggle_mark(MarkKind::Strike, cx);
2570
2700
}
2571
2701
}))
2572
.on_action(cx.listener(|this, _: &ToggleSuperscript, _, cx| {
2573
if this.link_editor.is_none() {
2702
.on_action(cx.listener(|this, _: &ToggleSuperscript, window, cx| {
2703
if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
2574
2704
this.toggle_mark(MarkKind::Superscript, cx);
2575
2705
}
2576
2706
}))
2577
.on_action(cx.listener(|this, _: &ToggleSubscript, _, cx| {
2578
if this.link_editor.is_none() {
2707
.on_action(cx.listener(|this, _: &ToggleSubscript, window, cx| {
2708
if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
2579
2709
this.toggle_mark(MarkKind::Subscript, cx);
2580
2710
}
2581
2711
}))
2582
.on_action(cx.listener(|this, _: &ToggleCode, _, cx| {
2583
if this.link_editor.is_none() {
2712
.on_action(cx.listener(|this, _: &ToggleCode, window, cx| {
2713
if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
2584
2714
this.toggle_mark(MarkKind::Code, cx);
2585
2715
}
2586
2716
}))
2587
.on_action(cx.listener(|this, _: &EditLink, window, cx| this.edit_link(window, cx)))
2717
.on_action(cx.listener(|this, _: &EditLink, window, cx| {
2718
if !this.cell_has_focus(window, cx) {
2719
this.edit_link(window, cx);
2720
}
2721
}))
2722
.on_action(
2723
cx.listener(|this, _: &PastePlainText, window, cx| this.paste_plain(window, cx)),
2724
)
2725
.on_action(cx.listener(|this, _: &InsertTableRowAbove, window, cx| {
2726
this.edit_table(TableEdit::InsertRowAbove, window, cx)
2727
}))
2728
.on_action(cx.listener(|this, _: &InsertTableRowBelow, window, cx| {
2729
this.edit_table(TableEdit::InsertRowBelow, window, cx)
2730
}))
2731
.on_action(cx.listener(|this, _: &InsertTableColumnLeft, window, cx| {
2732
this.edit_table(TableEdit::InsertColumnLeft, window, cx)
2733
}))
2734
.on_action(cx.listener(|this, _: &InsertTableColumnRight, window, cx| {
2735
this.edit_table(TableEdit::InsertColumnRight, window, cx)
2736
}))
2737
.on_action(cx.listener(|this, _: &DeleteTableRow, window, cx| {
2738
this.edit_table(TableEdit::DeleteRow, window, cx)
2739
}))
2740
.on_action(cx.listener(|this, _: &DeleteTableColumn, window, cx| {
2741
this.edit_table(TableEdit::DeleteColumn, window, cx)
2742
}))
2743
.on_action(cx.listener(|this, _: &DeleteTable, window, cx| {
2744
this.edit_table(TableEdit::DeleteTable, window, cx)
2745
}))
2588
2746
.on_action(cx.listener(|this, _: &ScheduleSend, _, cx| this.open_schedule_picker(cx)))
2589
2747
.capture_action(cx.listener(|this, _: &Undo, window, cx| {
2590
2748
if this.link_editor.is_none() {
@@ -2598,20 +2756,30 @@ impl Render for Composer {
2598
2756
cx.stop_propagation();
2599
2757
}
2600
2758
}))
2601
.capture_action(cx.listener(|this, _: &Copy, _, cx| {
2602
if this.link_editor.is_none() && this.copy_selection(cx) {
2759
.capture_action(cx.listener(|this, _: &Copy, window, cx| {
2760
if this.link_editor.is_none()
2761
&& !this.cell_has_focus(window, cx)
2762
&& this.copy_selection(cx)
2763
{
2603
2764
cx.stop_propagation();
2604
2765
}
2605
2766
}))
2606
2767
.capture_action(cx.listener(|this, _: &Cut, window, cx| {
2607
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
{
2608
2772
this.input
2609
2773
.update(cx, |state, cx| state.replace("", window, cx));
2610
2774
cx.stop_propagation();
2611
2775
}
2612
2776
}))
2613
2777
.capture_action(cx.listener(|this, _: &MoveUp, window, cx| {
2614
if this.link_editor.is_some() {
2778
if this.cell_has_focus(window, cx) {
2779
if this.table_key(TableKey::Up, window, cx) {
2780
cx.stop_propagation();
2781
}
2782
} else if this.link_editor.is_some() {
2615
2783
} else if this.schedule.is_some() {
2616
2784
this.move_schedule_highlight(-1, window, cx);
2617
2785
cx.stop_propagation();
@@ -2624,17 +2792,32 @@ impl Render for Composer {
2624
2792
}
2625
2793
}))
2626
2794
.capture_action(cx.listener(|this, _: &MoveDown, window, cx| {
2627
if this.link_editor.is_some() {
2795
if this.cell_has_focus(window, cx) {
2796
if this.table_key(TableKey::Down, window, cx) {
2797
cx.stop_propagation();
2798
}
2799
} else if this.link_editor.is_some() {
2628
2800
} else if this.schedule.is_some() {
2629
2801
this.move_schedule_highlight(1, window, cx);
2630
2802
cx.stop_propagation();
2631
2803
} else if this.popup_is_open() {
2632
2804
this.move_highlight(1, cx);
2633
2805
cx.stop_propagation();
2806
} else if this.leave_quote(window, cx) {
2807
cx.stop_propagation();
2808
}
2809
}))
2810
.capture_action(cx.listener(|this, _: &MoveRight, window, cx| {
2811
if this.link_editor.is_none()
2812
&& !this.cell_has_focus(window, cx)
2813
&& this.leave_quote(window, cx)
2814
{
2815
cx.stop_propagation();
2634
2816
}
2635
2817
}))
2636
2818
.capture_action(cx.listener(|this, action: &Enter, window, cx| {
2637
if this.link_editor.is_some() {
2819
if this.cell_has_focus(window, cx) {
2820
} else if this.link_editor.is_some() {
2638
2821
this.apply_link(window, cx);
2639
2822
cx.stop_propagation();
2640
2823
} else if this.schedule.is_some() {
@@ -2648,7 +2831,9 @@ impl Render for Composer {
2648
2831
}
2649
2832
}))
2650
2833
.capture_action(cx.listener(|this, _: &IndentInline, window, cx| {
2651
if this.link_editor.is_some() {
2834
if this.table_key(TableKey::Next, window, cx) {
2835
cx.stop_propagation();
2836
} else if this.link_editor.is_some() {
2652
2837
} else if this.popup_is_open() {
2653
2838
this.accept_popup(window, cx);
2654
2839
cx.stop_propagation();
@@ -2657,23 +2842,37 @@ impl Render for Composer {
2657
2842
}
2658
2843
}))
2659
2844
.capture_action(cx.listener(|this, _: &OutdentInline, window, cx| {
2660
if this.link_editor.is_none() && this.indent(true, window, cx) {
2845
if this.table_key(TableKey::Previous, window, cx)
2846
|| (this.link_editor.is_none() && this.indent(true, window, cx))
2847
{
2661
2848
cx.stop_propagation();
2662
2849
}
2663
2850
}))
2664
2851
.capture_action(cx.listener(|this, _: &Backspace, window, cx| {
2665
2852
if this.link_editor.is_none()
2666
&& (this.undo_conversion(window, cx) || this.backspace_at_start(window, cx))
2853
&& !this.cell_has_focus(window, cx)
2854
&& (this.undo_conversion(window, cx)
2855
|| this.backspace_at_start(window, cx)
2856
|| this.enter_table_beside(true, window, cx))
2667
2857
{
2668
2858
cx.stop_propagation();
2669
2859
}
2670
2860
}))
2671
2861
.capture_action(cx.listener(|this, _: &Delete, window, cx| {
2672
if this.link_editor.is_none() && this.delete_forward(window, cx) {
2862
if this.link_editor.is_none()
2863
&& !this.cell_has_focus(window, cx)
2864
&& (this.enter_table_beside(false, window, cx)
2865
|| this.delete_forward(window, cx))
2866
{
2673
2867
cx.stop_propagation();
2674
2868
}
2675
2869
}))
2676
2870
.capture_action(cx.listener(|this, _: &Escape, window, cx| {
2871
if this.table_picker.take().is_some() {
2872
cx.notify();
2873
cx.stop_propagation();
2874
return;
2875
}
2677
2876
if this.schedule.is_some() {
2678
2877
this.close_schedule(window, cx);
2679
2878
cx.stop_propagation();
@@ -2715,6 +2914,7 @@ impl Render for Composer {
2715
2914
.children(self.render_emoji_popup(window, cx))
2716
2915
.children(self.render_toolbar(focused, cx))
2717
2916
.children(self.render_schedule(cx))
2917
.children(self.render_table_picker(cx))
2718
2918
.child(
2719
2919
v_flex()
2720
2920
.relative()
@@ -2755,7 +2955,8 @@ impl Render for Composer {
2755
2955
.flex_none()
2756
2956
.gap(px(6.))
2757
2957
.children(fun)
2758
.children(attach),
2958
.children(attach)
2959
.children(table_button),
2759
2960
)
2760
2961
})
2761
2962
.child(
@@ -2925,7 +3126,10 @@ mod tests {
2925
3126
})
2926
3127
}
2927
3128
2928
fn outgoing_with(text: &str, images: Vec<crate::outgoing::OutgoingImage>) -> crate::outgoing::Outgoing {
3129
fn outgoing_with(
3130
text: &str,
3131
images: Vec<crate::outgoing::OutgoingImage>,
3132
) -> crate::outgoing::Outgoing {
2929
3133
crate::outgoing::Outgoing {
2930
3134
draft: teams_core::Draft::plain(text),
2931
3135
subject: None,
@@ -2983,7 +3187,10 @@ mod tests {
2983
3187
#[test]
2984
3188
fn a_sticker_carries_the_sticker_itemtype() {
2985
3189
let sticker = super::RemoteImage::sticker(crate::stickers::popular()[0]);
2986
let outgoing = outgoing_with("\u{FFFC}", vec![crate::outgoing::OutgoingImage::Remote(sticker)]);
3190
let outgoing = outgoing_with(
3191
"\u{FFFC}",
3192
vec![crate::outgoing::OutgoingImage::Remote(sticker)],
3193
);
2987
3194
assert!(
2988
3195
outgoing
2989
3196
.html()
@@ -3394,7 +3601,9 @@ mod tests {
3394
3601
excerpt: "question".into(),
3395
3602
};
3396
3603
typist.act(|_, cx| {
3397
composer.update(cx, |composer, cx| composer.set_reply(Some(reply.clone()), cx));
3604
composer.update(cx, |composer, cx| {
3605
composer.set_reply(Some(reply.clone()), cx)
3606
});
3398
3607
});
3399
3608
load(&mut typist, &entry);
3400
3609
let tokens = image_tokens(&mut typist);
@@ -3990,7 +4199,7 @@ mod tests {
3990
4199
#[gpui_kit::test]
3991
4200
fn quotes_continue_on_shift_enter_and_send_as_blockquote(cx: &mut TestAppContext) {
3992
4201
let mut typist = typist(cx);
3993
typist.type_text("> quoted");
4202
typist.type_text(">quoted");
3994
4203
typist.press("shift-enter");
3995
4204
typist.type_text("more");
3996
4205
let outgoing = typist.outgoing();
@@ -3998,6 +4207,112 @@ mod tests {
3998
4207
assert_eq!(outgoing.text(), "quoted\nmore");
3999
4208
}
4000
4209
4210
#[gpui_kit::test]
4211
fn enter_in_a_quote_adds_a_line_and_enter_on_the_empty_one_leaves_it(
4212
cx: &mut TestAppContext,
4213
) {
4214
let mut typist = typist(cx);
4215
typist.type_text(">quoted");
4216
typist.press("enter");
4217
typist.type_text("more");
4218
typist.press("enter enter");
4219
typist.type_text("after");
4220
assert_eq!(typist.value(), "quoted\nmore\nafter");
4221
assert_eq!(
4222
typist.outgoing().html(),
4223
"<blockquote>quoted<br>more</blockquote>after"
4224
);
4225
}
4226
4227
#[gpui_kit::test]
4228
fn down_at_the_end_of_a_quote_leaves_it(cx: &mut TestAppContext) {
4229
let mut typist = typist(cx);
4230
typist.type_text(">quoted");
4231
typist.press("down");
4232
typist.type_text("after");
4233
assert_eq!(
4234
typist.outgoing().html(),
4235
"<blockquote>quoted</blockquote>after"
4236
);
4237
}
4238
4239
fn insert_table(typist: &mut Typist<'_>, rows: usize, columns: usize) {
4240
let composer = typist.composer.clone();
4241
typist.act(|window, cx| {
4242
composer.update(cx, |composer, cx| {
4243
composer.insert_table(rows, columns, window, cx)
4244
});
4245
window.render_frame(cx);
4246
});
4247
}
4248
4249
#[gpui_kit::test]
4250
fn a_table_takes_tab_grows_a_row_at_the_end_and_sends_as_teams_html(
4251
cx: &mut TestAppContext,
4252
) {
4253
let mut typist = typist(cx);
4254
typist.type_text("before");
4255
insert_table(&mut typist, 1, 2);
4256
typist.type_text("a");
4257
typist.press("tab");
4258
typist.type_text("b");
4259
typist.press("tab");
4260
typist.act(|window, cx| window.render_frame(cx));
4261
typist.type_text("c");
4262
typist.press("down");
4263
typist.type_text("after");
4264
assert_eq!(
4265
typist.outgoing().html(),
4266
"before<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\
4267
<tr><td>a</td><td>b</td></tr><tr><td>c</td><td> </td></tr>\
4268
</tbody></table></figure>after"
4269
);
4270
}
4271
4272
#[gpui_kit::test]
4273
fn deleting_the_last_column_deletes_the_table(cx: &mut TestAppContext) {
4274
let mut typist = typist(cx);
4275
insert_table(&mut typist, 1, 1);
4276
let composer = typist.composer.clone();
4277
typist.act(|window, cx| {
4278
composer.update(cx, |composer, cx| {
4279
composer.edit_table(teams_core::TableEdit::DeleteColumn, window, cx)
4280
});
4281
});
4282
assert!(typist.draft().lines().iter().all(|kind| !kind.is_table()));
4283
}
4284
4285
#[gpui_kit::test]
4286
fn a_pasted_markdown_table_becomes_a_table(cx: &mut TestAppContext) {
4287
let mut typist = typist(cx);
4288
typist
4289
.cx
4290
.write_to_clipboard(gpui_kit::ClipboardItem::new_string(
4291
"| A | B |\n|---|---|\n| 1 | 2 |".to_owned(),
4292
));
4293
typist.press("ctrl-v");
4294
assert!(typist.draft().lines()[0].is_table());
4295
assert_eq!(
4296
typist.outgoing().html(),
4297
"<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\
4298
<tr><td>A</td><td>B</td></tr><tr><td>1</td><td>2</td></tr>\
4299
</tbody></table></figure>"
4300
);
4301
}
4302
4303
#[gpui_kit::test]
4304
fn ctrl_shift_v_pastes_markdown_as_plain_text(cx: &mut TestAppContext) {
4305
let mut typist = typist(cx);
4306
typist
4307
.cx
4308
.write_to_clipboard(gpui_kit::ClipboardItem::new_string(
4309
"**hi** there".to_owned(),
4310
));
4311
typist.press("ctrl-shift-v");
4312
assert_eq!(typist.value(), "**hi** there");
4313
assert!(typist.draft().marks().is_empty());
4314
}
4315
4001
4316
#[gpui_kit::test]
4002
4317
fn demo_upload_runs_to_done_and_a_file_alone_can_be_sent(cx: &mut TestAppContext) {
4003
4318
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;@@ -126,8 +131,19 @@ struct Conversion {126
131
127
#[derive(Debug, Clone, Copy, PartialEq, Eq)]132
#[derive(Debug, Clone, Copy, PartialEq, Eq)]128
enum StepKind {133
enum StepKind {129
Typing { at: usize, after_space: bool },134
Typing {130
Deleting { start: usize, end: usize },135
at: usize,136
after_space: bool,137
},138
Deleting {139
start: usize,140
end: usize,141
},142
CellTyping {143
table: usize,144
row: usize,145
column: usize,146
},131
Other,147
Other,132
}148
}133
149
@@ -192,6 +208,12 @@ pub struct Composer {192
pending_anchors: HashMap<u64, usize>,208
pending_anchors: HashMap<u64, usize>,193
link: ComposeLink,209
link: ComposeLink,194
fun_picker: Entity<FunPicker>,210
fun_picker: Entity<FunPicker>,211
tables: TableViews,212
table_counter: usize,213
table_picker: Option<TablePicker>,214
active_cell: Option<(String, teams_core::Cell)>,215
caret_before_table: usize,216
caret_text: String,195
_subscriptions: [Subscription; 4],217
_subscriptions: [Subscription; 4],196
}218
}197
219
@@ -292,6 +314,9 @@ fn continues(last: &HistoryStep, kind: StepKind) -> bool {292
(StepKind::Deleting { .. }, StepKind::Deleting { start, end }) => {314
(StepKind::Deleting { .. }, StepKind::Deleting { start, end }) => {293
caret.is_empty() && (caret.start == end || caret.start == start)315
caret.is_empty() && (caret.start == end || caret.start == start)294
}316
}317
(previous @ StepKind::CellTyping { .. }, next @ StepKind::CellTyping { .. }) => {318
previous == next319
}295
_ => false,320
_ => false,296
}321
}297
}322
}@@ -328,7 +353,10 @@ impl Composer {328
.placeholder("Type a message")353
.placeholder("Type a message")329
});354
});330
let subscription = cx.subscribe_in(&input, window, Self::on_input_event);355
let subscription = cx.subscribe_in(&input, window, Self::on_input_event);331
let observer = cx.observe(&input, |_, _, cx| cx.notify());356
let observer = cx.observe_in(&input, window, |this, _, window, cx| {357
this.redirect_caret_from_table(window, cx);358
cx.notify();359
});332
let image_observer = cx.observe(&app, |this, _, cx| {360
let image_observer = cx.observe(&app, |this, _, cx| {333
if this.link_image_pending(cx) {361
if this.link_image_pending(cx) {334
cx.notify();362
cx.notify();@@ -389,6 +417,12 @@ impl Composer {389
pending_anchors: HashMap::new(),417
pending_anchors: HashMap::new(),390
link: ComposeLink::default(),418
link: ComposeLink::default(),391
fun_picker,419
fun_picker,420
tables: TableViews::default(),421
table_counter: 0,422
table_picker: None,423
active_cell: None,424
caret_before_table: 0,425
caret_text: String::new(),392
_subscriptions: [subscription, observer, image_observer, picker_subscription],426
_subscriptions: [subscription, observer, image_observer, picker_subscription],393
}427
}394
}428
}@@ -640,6 +674,7 @@ impl Composer {640
}674
}641
self.previous_value = value;675
self.previous_value = value;642
self.refresh_style(cx);676
self.refresh_style(cx);677
self.sync_tables(window, cx);643
}678
}644
679
645
fn shift_anchors(&mut self, start: usize, old_end: usize, new_end: usize) {680
fn shift_anchors(&mut self, start: usize, old_end: usize, new_end: usize) {@@ -737,6 +772,7 @@ impl Composer {737
self.conversion = None;772
self.conversion = None;738
self.paste_hint = None;773
self.paste_hint = None;739
self.refresh_style(cx);774
self.refresh_style(cx);775
self.sync_tables(window, cx);740
self.update_emoji(cx);776
self.update_emoji(cx);741
self.update_mention(cx);777
self.update_mention(cx);742
self.schedule_draft_save(cx);778
self.schedule_draft_save(cx);@@ -775,6 +811,9 @@ impl Composer {775
self.link_editor = None;811
self.link_editor = None;776
self.toolbar_dismissed = None;812
self.toolbar_dismissed = None;777
self.pending_anchors.clear();813
self.pending_anchors.clear();814
self.active_cell = None;815
self.table_picker = None;816
self.sync_tables(window, cx);778
self.history.clear();817
self.history.clear();779
self.history_index = 0;818
self.history_index = 0;780
self.record(StepKind::Other, cx);819
self.record(StepKind::Other, cx);@@ -1064,6 +1103,64 @@ impl Composer {1064
}1103
}1065
}1104
}1066
1105
1106
fn leave_quote(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {1107
let selection = self.selection(cx);1108
if !selection.is_empty() || self.input.read(cx).value().as_ref() != self.draft.text() {1109
return false;1110
}1111
match self.draft.leave_quote_at_end(selection.start) {1112
Some(cursor) => {1113
self.commit(Some(cursor), window, cx);1114
true1115
}1116
None => false,1117
}1118
}1119
1120
/// Backspace right after a table or Delete right before one goes into it instead of1121
/// joining the line with the table's.1122
fn enter_table_beside(1123
&mut self,1124
after: bool,1125
window: &mut Window,1126
cx: &mut Context<Self>,1127
) -> bool {1128
let selection = self.selection(cx);1129
if !selection.is_empty() || self.input.read(cx).value().as_ref() != self.draft.text() {1130
return false;1131
}1132
let found = if after {1133
self.draft.table_before(selection.start)1134
} else {1135
self.draft.table_after(selection.start)1136
};1137
let Some(index) = found else {1138
return false;1139
};1140
self.focus_table_line(index, after, window, cx);1141
true1142
}1143
1144
fn cell_has_focus(&self, window: &Window, cx: &App) -> bool {1145
self.focused_cell(window, cx).is_some()1146
}1147
1148
fn paste_plain(&mut self, window: &mut Window, cx: &mut Context<Self>) {1149
let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) else {1150
return;1151
};1152
let text = text1153
.replace("\r\n", "\n")1154
.replace([OBJECT_MARK, TABLE_MARK], "");1155
if let Some(input) = self.focused_cell_input(window, cx) {1156
input.update(cx, |state, cx| state.replace(text, window, cx));1157
return;1158
}1159
self.pasted_markdown = None;1160
self.input1161
.update(cx, |state, cx| state.replace(text, window, cx));1162
}1163
1067
fn indent(&mut self, outdent: bool, window: &mut Window, cx: &mut Context<Self>) -> bool {1164
fn indent(&mut self, outdent: bool, window: &mut Window, cx: &mut Context<Self>) -> bool {1068
let selection = self.selection(cx);1165
let selection = self.selection(cx);1069
if !self.draft.indent(selection, outdent) {1166
if !self.draft.indent(selection, outdent) {@@ -1079,12 +1176,16 @@ impl Composer {1079
return false;1176
return false;1080
}1177
}1081
let selected = &self.draft.text()[selection.clone()];1178
let selected = &self.draft.text()[selection.clone()];1082
let text = selected.replace(OBJECT_MARK, "");1083
let lines = if selected.contains(OBJECT_MARK) {1179
let lines = if selected.contains(OBJECT_MARK) {1084
self.draft.slice_without_objects(selection)1180
self.draft.slice_without_objects(selection)1085
} else {1181
} else {1086
self.draft.slice(selection)1182
self.draft.slice(selection)1087
};1183
};1184
let text = if selected.contains(TABLE_MARK) {1185
Draft::from_lines(&lines).plain_text()1186
} else {1187
selected.replace(OBJECT_MARK, "")1188
};1088
if text.is_empty() {1189
if text.is_empty() {1089
return true;1190
return true;1090
}1191
}@@ -1150,8 +1251,8 @@ impl Composer {1150
}1251
}1151
let matches = emoji::search(&query, &self.recent_emoji.glyphs(), emoji_popup::LIMIT);1252
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);1253
let skin_tone = teams_core::skin_tone(&self.app.read(cx).store);1153
self.emoji_popup = (!matches.is_empty())1254
self.emoji_popup =1154
.then(|| EmojiPopup::new(range, query, matches, skin_tone));1255
(!matches.is_empty()).then(|| EmojiPopup::new(range, query, matches, skin_tone));1155
}1256
}1156
1257
1157
fn accept_emoji(&mut self, window: &mut Window, cx: &mut Context<Self>) {1258
fn accept_emoji(&mut self, window: &mut Window, cx: &mut Context<Self>) {@@ -1764,8 +1865,8 @@ impl Composer {1764
let Some(text) = item.text() else {1865
let Some(text) = item.text() else {1765
return false;1866
return false;1766
};1867
};1767
if text.contains(OBJECT_MARK) {1868
if text.contains([OBJECT_MARK, TABLE_MARK]) {1768
let cleaned = text.replace(OBJECT_MARK, "");1869
let cleaned = text.replace([OBJECT_MARK, TABLE_MARK], "");1769
self.input1870
self.input1770
.update(cx, |state, cx| state.replace(cleaned, window, cx));1871
.update(cx, |state, cx| state.replace(cleaned, window, cx));1771
return true;1872
return true;@@ -2465,6 +2566,24 @@ impl Render for Composer {2465
))2566
))2466
.on_click(cx.listener(|this, _, window, cx| this.open_picker(window, cx)))2567
.on_click(cx.listener(|this, _, window, cx| this.open_picker(window, cx)))2467
});2568
});2569
let table_button = can_attach.then(|| {2570
div()2571
.id("composer-table")2572
.size(px(32.))2573
.flex_none()2574
.flex()2575
.items_center()2576
.justify_center()2577
.rounded(px(8.))2578
.cursor_pointer()2579
.hover(|button| button.bg(theme::popup_hover()))2580
.when(self.table_picker.is_some(), |button| {2581
button.bg(theme::popup_hover())2582
})2583
.tooltip(|window, cx| Tooltip::new("Insert table").build(window, cx))2584
.child(symbol("table", COMPOSER_ICON_SIZE, theme::text_muted()))2585
.on_click(cx.listener(|this, _, _, cx| this.open_table_picker(cx)))2586
});2468
let composer = cx.weak_entity();2587
let composer = cx.weak_entity();2469
let tokens_composer = composer.clone();2588
let tokens_composer = composer.clone();2470
let input = Textarea::new(&self.input)2589
let input = Textarea::new(&self.input)@@ -2476,6 +2595,17 @@ impl Render for Composer {2476
.unwrap_or(false)2595
.unwrap_or(false)2477
})2596
})2478
.token(move |context, _, cx| {2597
.token(move |context, _, cx| {2598
if context.is_block() && is_table_token(context.token()) {2599
let token_id = context.token().id().to_string();2600
let width = context.available_width();2601
if let Some(table) = tokens_composer2602
.read_with(cx, |this, _| this.render_table_token(&token_id, width))2603
.ok()2604
.flatten()2605
{2606
return table;2607
}2608
}2479
if let Some(id) = context2609
if let Some(id) = context2480
.is_block()2610
.is_block()2481
.then(|| image_id(context.token()))2611
.then(|| image_id(context.token()))@@ -2549,42 +2679,70 @@ impl Render for Composer {2549
.pt(px(top))2679
.pt(px(top))2550
.pb(px(bottom))2680
.pb(px(bottom))2551
.key_context(COMPOSER_KEY_CONTEXT)2681
.key_context(COMPOSER_KEY_CONTEXT)2552
.on_action(cx.listener(|this, _: &ToggleBold, _, cx| {2682
.on_action(cx.listener(|this, _: &ToggleBold, window, cx| {2553
if this.link_editor.is_none() {2683
if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {2554
this.toggle_mark(MarkKind::Bold, cx);2684
this.toggle_mark(MarkKind::Bold, cx);2555
}2685
}2556
}))2686
}))2557
.on_action(cx.listener(|this, _: &ToggleItalic, _, cx| {2687
.on_action(cx.listener(|this, _: &ToggleItalic, window, cx| {2558
if this.link_editor.is_none() {2688
if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {2559
this.toggle_mark(MarkKind::Italic, cx);2689
this.toggle_mark(MarkKind::Italic, cx);2560
}2690
}2561
}))2691
}))2562
.on_action(cx.listener(|this, _: &ToggleUnderline, _, cx| {2692
.on_action(cx.listener(|this, _: &ToggleUnderline, window, cx| {2563
if this.link_editor.is_none() {2693
if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {2564
this.toggle_mark(MarkKind::Underline, cx);2694
this.toggle_mark(MarkKind::Underline, cx);2565
}2695
}2566
}))2696
}))2567
.on_action(cx.listener(|this, _: &ToggleStrike, _, cx| {2697
.on_action(cx.listener(|this, _: &ToggleStrike, window, cx| {2568
if this.link_editor.is_none() {2698
if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {2569
this.toggle_mark(MarkKind::Strike, cx);2699
this.toggle_mark(MarkKind::Strike, cx);2570
}2700
}2571
}))2701
}))2572
.on_action(cx.listener(|this, _: &ToggleSuperscript, _, cx| {2702
.on_action(cx.listener(|this, _: &ToggleSuperscript, window, cx| {2573
if this.link_editor.is_none() {2703
if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {2574
this.toggle_mark(MarkKind::Superscript, cx);2704
this.toggle_mark(MarkKind::Superscript, cx);2575
}2705
}2576
}))2706
}))2577
.on_action(cx.listener(|this, _: &ToggleSubscript, _, cx| {2707
.on_action(cx.listener(|this, _: &ToggleSubscript, window, cx| {2578
if this.link_editor.is_none() {2708
if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {2579
this.toggle_mark(MarkKind::Subscript, cx);2709
this.toggle_mark(MarkKind::Subscript, cx);2580
}2710
}2581
}))2711
}))2582
.on_action(cx.listener(|this, _: &ToggleCode, _, cx| {2712
.on_action(cx.listener(|this, _: &ToggleCode, window, cx| {2583
if this.link_editor.is_none() {2713
if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {2584
this.toggle_mark(MarkKind::Code, cx);2714
this.toggle_mark(MarkKind::Code, cx);2585
}2715
}2586
}))2716
}))2587
.on_action(cx.listener(|this, _: &EditLink, window, cx| this.edit_link(window, cx)))2717
.on_action(cx.listener(|this, _: &EditLink, window, cx| {2718
if !this.cell_has_focus(window, cx) {2719
this.edit_link(window, cx);2720
}2721
}))2722
.on_action(2723
cx.listener(|this, _: &PastePlainText, window, cx| this.paste_plain(window, cx)),2724
)2725
.on_action(cx.listener(|this, _: &InsertTableRowAbove, window, cx| {2726
this.edit_table(TableEdit::InsertRowAbove, window, cx)2727
}))2728
.on_action(cx.listener(|this, _: &InsertTableRowBelow, window, cx| {2729
this.edit_table(TableEdit::InsertRowBelow, window, cx)2730
}))2731
.on_action(cx.listener(|this, _: &InsertTableColumnLeft, window, cx| {2732
this.edit_table(TableEdit::InsertColumnLeft, window, cx)2733
}))2734
.on_action(cx.listener(|this, _: &InsertTableColumnRight, window, cx| {2735
this.edit_table(TableEdit::InsertColumnRight, window, cx)2736
}))2737
.on_action(cx.listener(|this, _: &DeleteTableRow, window, cx| {2738
this.edit_table(TableEdit::DeleteRow, window, cx)2739
}))2740
.on_action(cx.listener(|this, _: &DeleteTableColumn, window, cx| {2741
this.edit_table(TableEdit::DeleteColumn, window, cx)2742
}))2743
.on_action(cx.listener(|this, _: &DeleteTable, window, cx| {2744
this.edit_table(TableEdit::DeleteTable, window, cx)2745
}))2588
.on_action(cx.listener(|this, _: &ScheduleSend, _, cx| this.open_schedule_picker(cx)))2746
.on_action(cx.listener(|this, _: &ScheduleSend, _, cx| this.open_schedule_picker(cx)))2589
.capture_action(cx.listener(|this, _: &Undo, window, cx| {2747
.capture_action(cx.listener(|this, _: &Undo, window, cx| {2590
if this.link_editor.is_none() {2748
if this.link_editor.is_none() {@@ -2598,20 +2756,30 @@ impl Render for Composer {2598
cx.stop_propagation();2756
cx.stop_propagation();2599
}2757
}2600
}))2758
}))2601
.capture_action(cx.listener(|this, _: &Copy, _, cx| {2759
.capture_action(cx.listener(|this, _: &Copy, window, cx| {2602
if this.link_editor.is_none() && this.copy_selection(cx) {2760
if this.link_editor.is_none()2761
&& !this.cell_has_focus(window, cx)2762
&& this.copy_selection(cx)2763
{2603
cx.stop_propagation();2764
cx.stop_propagation();2604
}2765
}2605
}))2766
}))2606
.capture_action(cx.listener(|this, _: &Cut, window, cx| {2767
.capture_action(cx.listener(|this, _: &Cut, window, cx| {2607
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
{2608
this.input2772
this.input2609
.update(cx, |state, cx| state.replace("", window, cx));2773
.update(cx, |state, cx| state.replace("", window, cx));2610
cx.stop_propagation();2774
cx.stop_propagation();2611
}2775
}2612
}))2776
}))2613
.capture_action(cx.listener(|this, _: &MoveUp, window, cx| {2777
.capture_action(cx.listener(|this, _: &MoveUp, window, cx| {2614
if this.link_editor.is_some() {2778
if this.cell_has_focus(window, cx) {2779
if this.table_key(TableKey::Up, window, cx) {2780
cx.stop_propagation();2781
}2782
} else if this.link_editor.is_some() {2615
} else if this.schedule.is_some() {2783
} else if this.schedule.is_some() {2616
this.move_schedule_highlight(-1, window, cx);2784
this.move_schedule_highlight(-1, window, cx);2617
cx.stop_propagation();2785
cx.stop_propagation();@@ -2624,17 +2792,32 @@ impl Render for Composer {2624
}2792
}2625
}))2793
}))2626
.capture_action(cx.listener(|this, _: &MoveDown, window, cx| {2794
.capture_action(cx.listener(|this, _: &MoveDown, window, cx| {2627
if this.link_editor.is_some() {2795
if this.cell_has_focus(window, cx) {2796
if this.table_key(TableKey::Down, window, cx) {2797
cx.stop_propagation();2798
}2799
} else if this.link_editor.is_some() {2628
} else if this.schedule.is_some() {2800
} else if this.schedule.is_some() {2629
this.move_schedule_highlight(1, window, cx);2801
this.move_schedule_highlight(1, window, cx);2630
cx.stop_propagation();2802
cx.stop_propagation();2631
} else if this.popup_is_open() {2803
} else if this.popup_is_open() {2632
this.move_highlight(1, cx);2804
this.move_highlight(1, cx);2633
cx.stop_propagation();2805
cx.stop_propagation();2806
} else if this.leave_quote(window, cx) {2807
cx.stop_propagation();2808
}2809
}))2810
.capture_action(cx.listener(|this, _: &MoveRight, window, cx| {2811
if this.link_editor.is_none()2812
&& !this.cell_has_focus(window, cx)2813
&& this.leave_quote(window, cx)2814
{2815
cx.stop_propagation();2634
}2816
}2635
}))2817
}))2636
.capture_action(cx.listener(|this, action: &Enter, window, cx| {2818
.capture_action(cx.listener(|this, action: &Enter, window, cx| {2637
if this.link_editor.is_some() {2819
if this.cell_has_focus(window, cx) {2820
} else if this.link_editor.is_some() {2638
this.apply_link(window, cx);2821
this.apply_link(window, cx);2639
cx.stop_propagation();2822
cx.stop_propagation();2640
} else if this.schedule.is_some() {2823
} else if this.schedule.is_some() {@@ -2648,7 +2831,9 @@ impl Render for Composer {2648
}2831
}2649
}))2832
}))2650
.capture_action(cx.listener(|this, _: &IndentInline, window, cx| {2833
.capture_action(cx.listener(|this, _: &IndentInline, window, cx| {2651
if this.link_editor.is_some() {2834
if this.table_key(TableKey::Next, window, cx) {2835
cx.stop_propagation();2836
} else if this.link_editor.is_some() {2652
} else if this.popup_is_open() {2837
} else if this.popup_is_open() {2653
this.accept_popup(window, cx);2838
this.accept_popup(window, cx);2654
cx.stop_propagation();2839
cx.stop_propagation();@@ -2657,23 +2842,37 @@ impl Render for Composer {2657
}2842
}2658
}))2843
}))2659
.capture_action(cx.listener(|this, _: &OutdentInline, window, cx| {2844
.capture_action(cx.listener(|this, _: &OutdentInline, window, cx| {2660
if this.link_editor.is_none() && this.indent(true, window, cx) {2845
if this.table_key(TableKey::Previous, window, cx)2846
|| (this.link_editor.is_none() && this.indent(true, window, cx))2847
{2661
cx.stop_propagation();2848
cx.stop_propagation();2662
}2849
}2663
}))2850
}))2664
.capture_action(cx.listener(|this, _: &Backspace, window, cx| {2851
.capture_action(cx.listener(|this, _: &Backspace, window, cx| {2665
if this.link_editor.is_none()2852
if this.link_editor.is_none()2666
&& (this.undo_conversion(window, cx) || this.backspace_at_start(window, cx))2853
&& !this.cell_has_focus(window, cx)2854
&& (this.undo_conversion(window, cx)2855
|| this.backspace_at_start(window, cx)2856
|| this.enter_table_beside(true, window, cx))2667
{2857
{2668
cx.stop_propagation();2858
cx.stop_propagation();2669
}2859
}2670
}))2860
}))2671
.capture_action(cx.listener(|this, _: &Delete, window, cx| {2861
.capture_action(cx.listener(|this, _: &Delete, window, cx| {2672
if this.link_editor.is_none() && this.delete_forward(window, cx) {2862
if this.link_editor.is_none()2863
&& !this.cell_has_focus(window, cx)2864
&& (this.enter_table_beside(false, window, cx)2865
|| this.delete_forward(window, cx))2866
{2673
cx.stop_propagation();2867
cx.stop_propagation();2674
}2868
}2675
}))2869
}))2676
.capture_action(cx.listener(|this, _: &Escape, window, cx| {2870
.capture_action(cx.listener(|this, _: &Escape, window, cx| {2871
if this.table_picker.take().is_some() {2872
cx.notify();2873
cx.stop_propagation();2874
return;2875
}2677
if this.schedule.is_some() {2876
if this.schedule.is_some() {2678
this.close_schedule(window, cx);2877
this.close_schedule(window, cx);2679
cx.stop_propagation();2878
cx.stop_propagation();@@ -2715,6 +2914,7 @@ impl Render for Composer {2715
.children(self.render_emoji_popup(window, cx))2914
.children(self.render_emoji_popup(window, cx))2716
.children(self.render_toolbar(focused, cx))2915
.children(self.render_toolbar(focused, cx))2717
.children(self.render_schedule(cx))2916
.children(self.render_schedule(cx))2917
.children(self.render_table_picker(cx))2718
.child(2918
.child(2719
v_flex()2919
v_flex()2720
.relative()2920
.relative()@@ -2755,7 +2955,8 @@ impl Render for Composer {2755
.flex_none()2955
.flex_none()2756
.gap(px(6.))2956
.gap(px(6.))2757
.children(fun)2957
.children(fun)2758
.children(attach),2958
.children(attach)2959
.children(table_button),2759
)2960
)2760
})2961
})2761
.child(2962
.child(@@ -2925,7 +3126,10 @@ mod tests {2925
})3126
})2926
}3127
}2927
3128
2928
fn outgoing_with(text: &str, images: Vec<crate::outgoing::OutgoingImage>) -> crate::outgoing::Outgoing {3129
fn outgoing_with(3130
text: &str,3131
images: Vec<crate::outgoing::OutgoingImage>,3132
) -> crate::outgoing::Outgoing {2929
crate::outgoing::Outgoing {3133
crate::outgoing::Outgoing {2930
draft: teams_core::Draft::plain(text),3134
draft: teams_core::Draft::plain(text),2931
subject: None,3135
subject: None,@@ -2983,7 +3187,10 @@ mod tests {2983
#[test]3187
#[test]2984
fn a_sticker_carries_the_sticker_itemtype() {3188
fn a_sticker_carries_the_sticker_itemtype() {2985
let sticker = super::RemoteImage::sticker(crate::stickers::popular()[0]);3189
let sticker = super::RemoteImage::sticker(crate::stickers::popular()[0]);2986
let outgoing = outgoing_with("\u{FFFC}", vec![crate::outgoing::OutgoingImage::Remote(sticker)]);3190
let outgoing = outgoing_with(3191
"\u{FFFC}",3192
vec![crate::outgoing::OutgoingImage::Remote(sticker)],3193
);2987
assert!(3194
assert!(2988
outgoing3195
outgoing2989
.html()3196
.html()@@ -3394,7 +3601,9 @@ mod tests {3394
excerpt: "question".into(),3601
excerpt: "question".into(),3395
};3602
};3396
typist.act(|_, cx| {3603
typist.act(|_, cx| {3397
composer.update(cx, |composer, cx| composer.set_reply(Some(reply.clone()), cx));3604
composer.update(cx, |composer, cx| {3605
composer.set_reply(Some(reply.clone()), cx)3606
});3398
});3607
});3399
load(&mut typist, &entry);3608
load(&mut typist, &entry);3400
let tokens = image_tokens(&mut typist);3609
let tokens = image_tokens(&mut typist);@@ -3990,7 +4199,7 @@ mod tests {3990
#[gpui_kit::test]4199
#[gpui_kit::test]3991
fn quotes_continue_on_shift_enter_and_send_as_blockquote(cx: &mut TestAppContext) {4200
fn quotes_continue_on_shift_enter_and_send_as_blockquote(cx: &mut TestAppContext) {3992
let mut typist = typist(cx);4201
let mut typist = typist(cx);3993
typist.type_text("> quoted");4202
typist.type_text(">quoted");3994
typist.press("shift-enter");4203
typist.press("shift-enter");3995
typist.type_text("more");4204
typist.type_text("more");3996
let outgoing = typist.outgoing();4205
let outgoing = typist.outgoing();@@ -3998,6 +4207,112 @@ mod tests {3998
assert_eq!(outgoing.text(), "quoted\nmore");4207
assert_eq!(outgoing.text(), "quoted\nmore");3999
}4208
}4000
4209
4210
#[gpui_kit::test]4211
fn enter_in_a_quote_adds_a_line_and_enter_on_the_empty_one_leaves_it(4212
cx: &mut TestAppContext,4213
) {4214
let mut typist = typist(cx);4215
typist.type_text(">quoted");4216
typist.press("enter");4217
typist.type_text("more");4218
typist.press("enter enter");4219
typist.type_text("after");4220
assert_eq!(typist.value(), "quoted\nmore\nafter");4221
assert_eq!(4222
typist.outgoing().html(),4223
"<blockquote>quoted<br>more</blockquote>after"4224
);4225
}4226
4227
#[gpui_kit::test]4228
fn down_at_the_end_of_a_quote_leaves_it(cx: &mut TestAppContext) {4229
let mut typist = typist(cx);4230
typist.type_text(">quoted");4231
typist.press("down");4232
typist.type_text("after");4233
assert_eq!(4234
typist.outgoing().html(),4235
"<blockquote>quoted</blockquote>after"4236
);4237
}4238
4239
fn insert_table(typist: &mut Typist<'_>, rows: usize, columns: usize) {4240
let composer = typist.composer.clone();4241
typist.act(|window, cx| {4242
composer.update(cx, |composer, cx| {4243
composer.insert_table(rows, columns, window, cx)4244
});4245
window.render_frame(cx);4246
});4247
}4248
4249
#[gpui_kit::test]4250
fn a_table_takes_tab_grows_a_row_at_the_end_and_sends_as_teams_html(4251
cx: &mut TestAppContext,4252
) {4253
let mut typist = typist(cx);4254
typist.type_text("before");4255
insert_table(&mut typist, 1, 2);4256
typist.type_text("a");4257
typist.press("tab");4258
typist.type_text("b");4259
typist.press("tab");4260
typist.act(|window, cx| window.render_frame(cx));4261
typist.type_text("c");4262
typist.press("down");4263
typist.type_text("after");4264
assert_eq!(4265
typist.outgoing().html(),4266
"before<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\4267
<tr><td>a</td><td>b</td></tr><tr><td>c</td><td> </td></tr>\4268
</tbody></table></figure>after"4269
);4270
}4271
4272
#[gpui_kit::test]4273
fn deleting_the_last_column_deletes_the_table(cx: &mut TestAppContext) {4274
let mut typist = typist(cx);4275
insert_table(&mut typist, 1, 1);4276
let composer = typist.composer.clone();4277
typist.act(|window, cx| {4278
composer.update(cx, |composer, cx| {4279
composer.edit_table(teams_core::TableEdit::DeleteColumn, window, cx)4280
});4281
});4282
assert!(typist.draft().lines().iter().all(|kind| !kind.is_table()));4283
}4284
4285
#[gpui_kit::test]4286
fn a_pasted_markdown_table_becomes_a_table(cx: &mut TestAppContext) {4287
let mut typist = typist(cx);4288
typist4289
.cx4290
.write_to_clipboard(gpui_kit::ClipboardItem::new_string(4291
"| A | B |\n|---|---|\n| 1 | 2 |".to_owned(),4292
));4293
typist.press("ctrl-v");4294
assert!(typist.draft().lines()[0].is_table());4295
assert_eq!(4296
typist.outgoing().html(),4297
"<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\4298
<tr><td>A</td><td>B</td></tr><tr><td>1</td><td>2</td></tr>\4299
</tbody></table></figure>"4300
);4301
}4302
4303
#[gpui_kit::test]4304
fn ctrl_shift_v_pastes_markdown_as_plain_text(cx: &mut TestAppContext) {4305
let mut typist = typist(cx);4306
typist4307
.cx4308
.write_to_clipboard(gpui_kit::ClipboardItem::new_string(4309
"**hi** there".to_owned(),4310
));4311
typist.press("ctrl-shift-v");4312
assert_eq!(typist.value(), "**hi** there");4313
assert!(typist.draft().marks().is_empty());4314
}4315
4001
#[gpui_kit::test]4316
#[gpui_kit::test]4002
fn demo_upload_runs_to_done_and_a_file_alone_can_be_sent(cx: &mut TestAppContext) {4317
fn demo_upload_runs_to_done_and_a_file_alone_can_be_sent(cx: &mut TestAppContext) {4003
cx.update(gpui_kit::init);4318
cx.update(gpui_kit::init);@@ -0,0 +1,633 @@
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::prelude::FluentBuilder as _;
10
use gpui_kit::*;
11
use teams_core::{Cell, PICKER_COLUMNS, PICKER_ROWS, TABLE_MARK, Table, TableEdit};
12
13
use super::{Composer, StepKind};
14
use crate::theme::{self, ElevatedSurface as _};
15
use crate::views::actions::{
16
DeleteTable, DeleteTableColumn, DeleteTableRow, InsertTableColumnLeft, InsertTableColumnRight,
17
InsertTableRowAbove, InsertTableRowBelow,
18
};
19
20
pub(super) const TOKEN_PREFIX: &str = "table-";
21
const CELL_MAX_ROWS: usize = 12;
22
const PICKER_SQUARE: f32 = 16.;
23
const PICKER_GAP: f32 = 3.;
24
const TABLE_MARGIN: f32 = 4.;
25
const CELL_PADDING_X: f32 = 2.;
26
const CELL_PADDING_Y: f32 = 3.;
27
28
pub(super) struct TableView {
29
cells: Vec<Vec<Entity<TextareaState>>>,
30
_subscriptions: Vec<Subscription>,
31
}
32
33
impl TableView {
34
fn shape(&self) -> (usize, usize) {
35
(self.cells.len(), self.cells.first().map_or(0, Vec::len))
36
}
37
}
38
39
/// The rows and columns the pointer covers in the size picker.
40
pub(super) struct TablePicker {
41
rows: usize,
42
columns: usize,
43
}
44
45
pub(super) fn token(number: usize) -> InlineToken {
46
InlineToken::new(format!("{TOKEN_PREFIX}{number}"), TABLE_MARK.to_string()).block()
47
}
48
49
pub(super) fn is_table_token(token: &InlineToken) -> bool {
50
token.id().starts_with(TOKEN_PREFIX)
51
}
52
53
fn token_number(id: &str) -> usize {
54
id.strip_prefix(TOKEN_PREFIX)
55
.and_then(|number| number.parse().ok())
56
.unwrap_or_default()
57
}
58
59
fn caret_on_first_line(state: &TextareaState) -> bool {
60
!state.value()[..state.cursor()].contains('\n')
61
}
62
63
fn caret_on_last_line(state: &TextareaState) -> bool {
64
!state.value()[state.cursor()..].contains('\n')
65
}
66
67
impl Composer {
68
fn table_tokens(&self, cx: &App) -> Vec<(Range<usize>, String)> {
69
self.input
70
.read(cx)
71
.tokens()
72
.iter()
73
.filter(|span| is_table_token(span.token()))
74
.map(|span| (span.range(), span.token().id().to_string()))
75
.collect()
76
}
77
78
fn table_line(&self, token_id: &str, cx: &App) -> Option<usize> {
79
let (range, _) = self
80
.table_tokens(cx)
81
.into_iter()
82
.find(|(_, id)| id == token_id)?;
83
let index = self.draft.line_at(range.start);
84
self.draft.table(index).is_some().then_some(index)
85
}
86
87
/// Every table line gets its token and cell inputs; inputs follow the draft's cells.
88
pub(super) fn sync_tables(&mut self, window: &mut Window, cx: &mut Context<Self>) {
89
if self.input.read(cx).value().as_ref() != self.draft.text() {
90
return;
91
}
92
let ranges = self.draft.line_ranges();
93
let tokens = self.table_tokens(cx);
94
for (index, line) in ranges.iter().enumerate() {
95
if self.draft.table(index).is_none() || tokens.iter().any(|(range, _)| range == line) {
96
continue;
97
}
98
self.table_counter += 1;
99
let token = token(self.table_counter);
100
self.input.update(cx, |state, cx| {
101
let selection = state.selected_range();
102
if state
103
.replace_range_with_token(line.clone(), token, window, cx)
104
.is_ok()
105
{
106
state.set_selected_range(selection, cx);
107
}
108
});
109
}
110
let tokens = self.table_tokens(cx);
111
self.tables
112
.retain(|id, _| tokens.iter().any(|(_, token_id)| token_id == id));
113
for (range, id) in tokens {
114
let Some(table) = self.draft.table(self.draft.line_at(range.start)).cloned() else {
115
continue;
116
};
117
self.sync_table_view(&id, &table, window, cx);
118
}
119
}
120
121
fn sync_table_view(
122
&mut self,
123
token_id: &str,
124
table: &Table,
125
window: &mut Window,
126
cx: &mut Context<Self>,
127
) {
128
let shape = (table.row_count(), table.column_count());
129
if self
130
.tables
131
.get(token_id)
132
.is_some_and(|view| view.shape() == shape)
133
{
134
let cells = self.tables[token_id].cells.clone();
135
for (row, inputs) in cells.iter().enumerate() {
136
for (column, input) in inputs.iter().enumerate() {
137
let text = table.cell(Cell::new(row, column)).unwrap_or_default();
138
if input.read(cx).value().as_ref() != text {
139
let text = text.to_owned();
140
input.update(cx, |state, cx| state.set_value(text, window, cx));
141
}
142
}
143
}
144
return;
145
}
146
let mut subscriptions = Vec::new();
147
let cells = table
148
.rows
149
.iter()
150
.enumerate()
151
.map(|(row, texts)| {
152
texts
153
.iter()
154
.enumerate()
155
.map(|(column, text)| {
156
let text = text.clone();
157
let input = cx.new(|cx| {
158
TextareaState::new(window, cx)
159
.auto_grow(1, CELL_MAX_ROWS)
160
.default_value(text)
161
});
162
let id = token_id.to_owned();
163
let cell = Cell::new(row, column);
164
subscriptions.push(cx.subscribe_in(
165
&input,
166
window,
167
move |this, _, event: &InputEvent, window, cx| {
168
this.on_cell_event(&id, cell, event, window, cx)
169
},
170
));
171
input
172
})
173
.collect()
174
})
175
.collect();
176
self.tables.insert(
177
token_id.to_owned(),
178
TableView {
179
cells,
180
_subscriptions: subscriptions,
181
},
182
);
183
}
184
185
fn on_cell_event(
186
&mut self,
187
token_id: &str,
188
cell: Cell,
189
event: &InputEvent,
190
_: &mut Window,
191
cx: &mut Context<Self>,
192
) {
193
match event {
194
InputEvent::Focus => {
195
self.active_cell = Some((token_id.to_owned(), cell));
196
self.table_picker = None;
197
}
198
InputEvent::Change => {
199
let Some(index) = self.table_line(token_id, cx) else {
200
return;
201
};
202
let Some(input) = self.cell_input(token_id, cell) else {
203
return;
204
};
205
let text = input.read(cx).value().to_string();
206
let Some(mut table) = self.draft.table(index).cloned() else {
207
return;
208
};
209
if table.cell(cell) == Some(text.as_str()) {
210
return;
211
}
212
table.set_cell(cell, &text);
213
self.draft.set_table(index, table);
214
self.record(
215
StepKind::CellTyping {
216
table: token_number(token_id),
217
row: cell.row,
218
column: cell.column,
219
},
220
cx,
221
);
222
self.schedule_draft_save(cx);
223
}
224
_ => {}
225
}
226
cx.notify();
227
}
228
229
fn cell_input(&self, token_id: &str, cell: Cell) -> Option<Entity<TextareaState>> {
230
self.tables
231
.get(token_id)?
232
.cells
233
.get(cell.row)?
234
.get(cell.column)
235
.cloned()
236
}
237
238
pub(super) fn focused_cell_input(
239
&self,
240
window: &Window,
241
cx: &App,
242
) -> Option<Entity<TextareaState>> {
243
let (token_id, cell) = self.focused_cell(window, cx)?;
244
self.cell_input(&token_id, cell)
245
}
246
247
/// The cell that has the keyboard, if any.
248
pub(super) fn focused_cell(&self, window: &Window, cx: &App) -> Option<(String, Cell)> {
249
self.tables.iter().find_map(|(id, view)| {
250
view.cells.iter().enumerate().find_map(|(row, inputs)| {
251
inputs.iter().enumerate().find_map(|(column, input)| {
252
input
253
.focus_handle(cx)
254
.is_focused(window)
255
.then(|| (id.clone(), Cell::new(row, column)))
256
})
257
})
258
})
259
}
260
261
pub(super) fn focus_cell(
262
&mut self,
263
token_id: &str,
264
cell: Cell,
265
window: &mut Window,
266
cx: &mut Context<Self>,
267
) {
268
let Some(input) = self.cell_input(token_id, cell) else {
269
return;
270
};
271
input.update(cx, |state, cx| {
272
let end = state.value().len();
273
state.focus(window, cx);
274
state.set_selected_range(end..end, cx);
275
});
276
self.active_cell = Some((token_id.to_owned(), cell));
277
cx.notify();
278
}
279
280
fn token_at_line(&self, index: usize, cx: &App) -> Option<String> {
281
let line = self.draft.line_ranges().get(index)?.clone();
282
self.table_tokens(cx)
283
.into_iter()
284
.find(|(range, _)| *range == line)
285
.map(|(_, id)| id)
286
}
287
288
pub(super) fn focus_table_line(
289
&mut self,
290
index: usize,
291
last: bool,
292
window: &mut Window,
293
cx: &mut Context<Self>,
294
) {
295
let Some(token_id) = self.token_at_line(index, cx) else {
296
return;
297
};
298
let Some(table) = self.draft.table(index) else {
299
return;
300
};
301
let cell = if last {
302
table.last_cell()
303
} else {
304
Cell::new(0, 0)
305
};
306
self.focus_cell(&token_id, cell, window, cx);
307
}
308
309
pub(super) fn insert_table(
310
&mut self,
311
rows: usize,
312
columns: usize,
313
window: &mut Window,
314
cx: &mut Context<Self>,
315
) {
316
self.table_picker = None;
317
let cursor = match self.focused_cell(window, cx) {
318
Some((token_id, _)) => self
319
.table_line(&token_id, cx)
320
.map_or(self.selection(cx).end, |index| {
321
self.draft.line_ranges()[index].end
322
}),
323
None => self.selection(cx).end,
324
};
325
let index = self.draft.insert_table(cursor, Table::new(rows, columns));
326
let after = self.draft.line_ranges()[index].end;
327
self.commit(Some(after), window, cx);
328
self.focus_table_line(index, false, window, cx);
329
}
330
331
fn leave_table(
332
&mut self,
333
token_id: &str,
334
below: bool,
335
window: &mut Window,
336
cx: &mut Context<Self>,
337
) {
338
let Some(index) = self.table_line(token_id, cx) else {
339
return;
340
};
341
let cursor = self.draft.line_beside_table(index, below);
342
self.active_cell = None;
343
self.focus(window, cx);
344
self.commit(Some(cursor), window, cx);
345
}
346
347
/// Tab, Shift+Tab, Up and Down while a cell has the keyboard. `false` leaves the key to
348
/// the cell.
349
pub(super) fn table_key(
350
&mut self,
351
key: TableKey,
352
window: &mut Window,
353
cx: &mut Context<Self>,
354
) -> bool {
355
let Some((token_id, cell)) = self.focused_cell(window, cx) else {
356
return false;
357
};
358
let Some(index) = self.table_line(&token_id, cx) else {
359
return false;
360
};
361
let Some(mut table) = self.draft.table(index).cloned() else {
362
return false;
363
};
364
let Some(input) = self.cell_input(&token_id, cell) else {
365
return false;
366
};
367
let target = match key {
368
TableKey::Next => {
369
let (next, added_row) = table.next_cell(cell);
370
if added_row {
371
self.draft.set_table(index, table);
372
self.record(StepKind::Other, cx);
373
self.sync_tables(window, cx);
374
self.schedule_draft_save(cx);
375
}
376
next
377
}
378
TableKey::Previous => table.previous_cell(cell),
379
TableKey::Down if !caret_on_last_line(input.read(cx)) => return false,
380
TableKey::Up if !caret_on_first_line(input.read(cx)) => return false,
381
TableKey::Down if cell.row + 1 == table.row_count() => {
382
self.leave_table(&token_id, true, window, cx);
383
return true;
384
}
385
TableKey::Up if cell.row == 0 => {
386
self.leave_table(&token_id, false, window, cx);
387
return true;
388
}
389
TableKey::Down => Cell::new(cell.row + 1, cell.column),
390
TableKey::Up => Cell::new(cell.row - 1, cell.column),
391
};
392
self.focus_cell(&token_id, target, window, cx);
393
true
394
}
395
396
pub(super) fn edit_table(
397
&mut self,
398
edit: TableEdit,
399
window: &mut Window,
400
cx: &mut Context<Self>,
401
) {
402
let Some((token_id, cell)) = self
403
.focused_cell(window, cx)
404
.or_else(|| self.active_cell.clone())
405
else {
406
return;
407
};
408
let Some(index) = self.table_line(&token_id, cx) else {
409
return;
410
};
411
let Some(mut table) = self.draft.table(index).cloned() else {
412
return;
413
};
414
match table.apply(edit, cell) {
415
Some(target) => {
416
self.draft.set_table(index, table);
417
self.record(StepKind::Other, cx);
418
self.sync_tables(window, cx);
419
self.schedule_draft_save(cx);
420
self.focus_cell(&token_id, target, window, cx);
421
}
422
None => {
423
let cursor = self.draft.remove_table(index);
424
self.active_cell = None;
425
self.focus(window, cx);
426
self.commit(Some(cursor), window, cx);
427
}
428
}
429
cx.notify();
430
}
431
432
/// The caret never rests on a table's line: coming from above it enters the first
433
/// cell, from below the first cell of the last row. Only a move without an edit
434
/// counts, so a paste that passes the table on its way does not enter it.
435
pub(super) fn redirect_caret_from_table(
436
&mut self,
437
window: &mut Window,
438
cx: &mut Context<Self>,
439
) {
440
let state = self.input.read(cx);
441
let selection = state.selected_range();
442
let focused = state.focus_handle(cx).is_focused(window);
443
let value = state.value();
444
if value.as_ref() != self.caret_text {
445
self.caret_text = value.to_string();
446
self.caret_before_table = selection.start;
447
return;
448
}
449
if !focused || !selection.is_empty() || value.as_ref() != self.draft.text() {
450
return;
451
}
452
let Some(index) = self.draft.table_at(selection.start) else {
453
self.caret_before_table = selection.start;
454
return;
455
};
456
let line = self.draft.line_ranges()[index].clone();
457
let from_below = self.caret_before_table > line.end;
458
let resting = if from_below {
459
self.draft
460
.line_ranges()
461
.get(index + 1)
462
.map_or(line.end, |next| next.start)
463
} else {
464
line.start.saturating_sub(1)
465
};
466
self.input.update(cx, |state, cx| {
467
state.set_selected_range(resting..resting, cx)
468
});
469
self.caret_before_table = resting;
470
let token = self.token_at_line(index, cx);
471
let Some(token_id) = token else {
472
return;
473
};
474
let row = if from_below {
475
self.draft
476
.table(index)
477
.map_or(0, |table| table.row_count() - 1)
478
} else {
479
0
480
};
481
self.focus_cell(&token_id, Cell::new(row, 0), window, cx);
482
}
483
484
pub(super) fn open_table_picker(&mut self, cx: &mut Context<Self>) {
485
self.table_picker = Some(TablePicker {
486
rows: 1,
487
columns: 1,
488
});
489
cx.notify();
490
}
491
492
pub(super) fn render_table_picker(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
493
let picker = self.table_picker.as_ref()?;
494
let grid = v_flex()
495
.gap(px(PICKER_GAP))
496
.children((1..=PICKER_ROWS).map(|row| {
497
h_flex()
498
.gap(px(PICKER_GAP))
499
.children((1..=PICKER_COLUMNS).map(|column| {
500
let covered = row <= picker.rows && column <= picker.columns;
501
div()
502
.id(ElementId::Name(format!("table-size-{row}-{column}").into()))
503
.size(px(PICKER_SQUARE))
504
.rounded(px(2.))
505
.border_1()
506
.border_color(if covered {
507
theme::accent()
508
} else {
509
theme::border_strong()
510
})
511
.when(covered, |square| square.bg(theme::accent().opacity(0.25)))
512
.cursor_pointer()
513
.on_hover(cx.listener(move |this, hovered: &bool, _, cx| {
514
if *hovered && let Some(picker) = this.table_picker.as_mut() {
515
picker.rows = row;
516
picker.columns = column;
517
cx.notify();
518
}
519
}))
520
.on_click(cx.listener(move |this, _, window, cx| {
521
this.insert_table(row, column, window, cx)
522
}))
523
}))
524
}));
525
Some(
526
v_flex()
527
.id("table-picker")
528
.absolute()
529
.bottom(relative(1.))
530
.left_0()
531
.mb(px(6.))
532
.p(px(10.))
533
.gap(px(8.))
534
.rounded(px(10.))
535
.flyout_surface()
536
.occlude()
537
.on_mouse_down_out(cx.listener(|this, _, _, cx| {
538
this.table_picker = None;
539
cx.notify();
540
}))
541
.child(
542
div()
543
.text_size(px(12.))
544
.text_color(theme::text_muted())
545
.child(format!("Insert {}x{} table", picker.columns, picker.rows)),
546
)
547
.child(grid)
548
.into_any_element(),
549
)
550
}
551
552
/// The table token: a grid of cell inputs over the full width, solid lines like Teams.
553
pub(super) fn render_table_token(&self, token_id: &str, width: Pixels) -> Option<AnyElement> {
554
let view = self.tables.get(token_id)?;
555
let rows = view.cells.iter().map(|inputs| {
556
h_flex()
557
.w_full()
558
.items_stretch()
559
.children(inputs.iter().map(|input| {
560
div()
561
.flex_1()
562
.min_w_0()
563
.px(px(CELL_PADDING_X))
564
.py(px(CELL_PADDING_Y))
565
.border_r_1()
566
.border_b_1()
567
.border_color(theme::border_strong())
568
.child(
569
Textarea::new(input)
570
.appearance(false)
571
.bordered(false)
572
.small()
573
.context_menu(|menu, _, _| table_menu(menu)),
574
)
575
}))
576
});
577
Some(
578
v_flex()
579
.id(ElementId::Name(format!("composer-{token_id}").into()))
580
.w(width)
581
.my(px(TABLE_MARGIN))
582
.border_t_1()
583
.border_l_1()
584
.border_color(theme::border_strong())
585
.on_any_mouse_down(|_, window, cx| {
586
window.prevent_default();
587
cx.stop_propagation();
588
})
589
.children(rows)
590
.into_any_element(),
591
)
592
}
593
}
594
595
fn table_menu(menu: NativeMenu) -> NativeMenu {
596
let menu = TableEdit::INSERTS
597
.into_iter()
598
.fold(menu, |menu, edit| {
599
menu.menu(edit.label(), edit_action(edit))
600
})
601
.separator();
602
TableEdit::DELETES
603
.into_iter()
604
.fold(menu, |menu, edit| {
605
menu.menu(edit.label(), edit_action(edit))
606
})
607
.separator()
608
.menu("Cut", Box::new(Cut))
609
.menu("Copy", Box::new(Copy))
610
.menu("Paste", Box::new(Paste))
611
}
612
613
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
614
pub(super) enum TableKey {
615
Next,
616
Previous,
617
Up,
618
Down,
619
}
620
621
fn edit_action(edit: TableEdit) -> Box<dyn Action> {
622
match edit {
623
TableEdit::InsertRowAbove => Box::new(InsertTableRowAbove),
624
TableEdit::InsertRowBelow => Box::new(InsertTableRowBelow),
625
TableEdit::InsertColumnLeft => Box::new(InsertTableColumnLeft),
626
TableEdit::InsertColumnRight => Box::new(InsertTableColumnRight),
627
TableEdit::DeleteRow => Box::new(DeleteTableRow),
628
TableEdit::DeleteColumn => Box::new(DeleteTableColumn),
629
TableEdit::DeleteTable => Box::new(DeleteTable),
630
}
631
}
632
633
pub(super) type TableViews = HashMap<String, TableView>;
@@ -0,0 +1,633 @@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::prelude::FluentBuilder as _;10
use gpui_kit::*;11
use teams_core::{Cell, PICKER_COLUMNS, PICKER_ROWS, TABLE_MARK, Table, TableEdit};12
13
use super::{Composer, StepKind};14
use crate::theme::{self, ElevatedSurface as _};15
use crate::views::actions::{16
DeleteTable, DeleteTableColumn, DeleteTableRow, InsertTableColumnLeft, InsertTableColumnRight,17
InsertTableRowAbove, InsertTableRowBelow,18
};19
20
pub(super) const TOKEN_PREFIX: &str = "table-";21
const CELL_MAX_ROWS: usize = 12;22
const PICKER_SQUARE: f32 = 16.;23
const PICKER_GAP: f32 = 3.;24
const TABLE_MARGIN: f32 = 4.;25
const CELL_PADDING_X: f32 = 2.;26
const CELL_PADDING_Y: f32 = 3.;27
28
pub(super) struct TableView {29
cells: Vec<Vec<Entity<TextareaState>>>,30
_subscriptions: Vec<Subscription>,31
}32
33
impl TableView {34
fn shape(&self) -> (usize, usize) {35
(self.cells.len(), self.cells.first().map_or(0, Vec::len))36
}37
}38
39
/// The rows and columns the pointer covers in the size picker.40
pub(super) struct TablePicker {41
rows: usize,42
columns: usize,43
}44
45
pub(super) fn token(number: usize) -> InlineToken {46
InlineToken::new(format!("{TOKEN_PREFIX}{number}"), TABLE_MARK.to_string()).block()47
}48
49
pub(super) fn is_table_token(token: &InlineToken) -> bool {50
token.id().starts_with(TOKEN_PREFIX)51
}52
53
fn token_number(id: &str) -> usize {54
id.strip_prefix(TOKEN_PREFIX)55
.and_then(|number| number.parse().ok())56
.unwrap_or_default()57
}58
59
fn caret_on_first_line(state: &TextareaState) -> bool {60
!state.value()[..state.cursor()].contains('\n')61
}62
63
fn caret_on_last_line(state: &TextareaState) -> bool {64
!state.value()[state.cursor()..].contains('\n')65
}66
67
impl Composer {68
fn table_tokens(&self, cx: &App) -> Vec<(Range<usize>, String)> {69
self.input70
.read(cx)71
.tokens()72
.iter()73
.filter(|span| is_table_token(span.token()))74
.map(|span| (span.range(), span.token().id().to_string()))75
.collect()76
}77
78
fn table_line(&self, token_id: &str, cx: &App) -> Option<usize> {79
let (range, _) = self80
.table_tokens(cx)81
.into_iter()82
.find(|(_, id)| id == token_id)?;83
let index = self.draft.line_at(range.start);84
self.draft.table(index).is_some().then_some(index)85
}86
87
/// Every table line gets its token and cell inputs; inputs follow the draft's cells.88
pub(super) fn sync_tables(&mut self, window: &mut Window, cx: &mut Context<Self>) {89
if self.input.read(cx).value().as_ref() != self.draft.text() {90
return;91
}92
let ranges = self.draft.line_ranges();93
let tokens = self.table_tokens(cx);94
for (index, line) in ranges.iter().enumerate() {95
if self.draft.table(index).is_none() || tokens.iter().any(|(range, _)| range == line) {96
continue;97
}98
self.table_counter += 1;99
let token = token(self.table_counter);100
self.input.update(cx, |state, cx| {101
let selection = state.selected_range();102
if state103
.replace_range_with_token(line.clone(), token, window, cx)104
.is_ok()105
{106
state.set_selected_range(selection, cx);107
}108
});109
}110
let tokens = self.table_tokens(cx);111
self.tables112
.retain(|id, _| tokens.iter().any(|(_, token_id)| token_id == id));113
for (range, id) in tokens {114
let Some(table) = self.draft.table(self.draft.line_at(range.start)).cloned() else {115
continue;116
};117
self.sync_table_view(&id, &table, window, cx);118
}119
}120
121
fn sync_table_view(122
&mut self,123
token_id: &str,124
table: &Table,125
window: &mut Window,126
cx: &mut Context<Self>,127
) {128
let shape = (table.row_count(), table.column_count());129
if self130
.tables131
.get(token_id)132
.is_some_and(|view| view.shape() == shape)133
{134
let cells = self.tables[token_id].cells.clone();135
for (row, inputs) in cells.iter().enumerate() {136
for (column, input) in inputs.iter().enumerate() {137
let text = table.cell(Cell::new(row, column)).unwrap_or_default();138
if input.read(cx).value().as_ref() != text {139
let text = text.to_owned();140
input.update(cx, |state, cx| state.set_value(text, window, cx));141
}142
}143
}144
return;145
}146
let mut subscriptions = Vec::new();147
let cells = table148
.rows149
.iter()150
.enumerate()151
.map(|(row, texts)| {152
texts153
.iter()154
.enumerate()155
.map(|(column, text)| {156
let text = text.clone();157
let input = cx.new(|cx| {158
TextareaState::new(window, cx)159
.auto_grow(1, CELL_MAX_ROWS)160
.default_value(text)161
});162
let id = token_id.to_owned();163
let cell = Cell::new(row, column);164
subscriptions.push(cx.subscribe_in(165
&input,166
window,167
move |this, _, event: &InputEvent, window, cx| {168
this.on_cell_event(&id, cell, event, window, cx)169
},170
));171
input172
})173
.collect()174
})175
.collect();176
self.tables.insert(177
token_id.to_owned(),178
TableView {179
cells,180
_subscriptions: subscriptions,181
},182
);183
}184
185
fn on_cell_event(186
&mut self,187
token_id: &str,188
cell: Cell,189
event: &InputEvent,190
_: &mut Window,191
cx: &mut Context<Self>,192
) {193
match event {194
InputEvent::Focus => {195
self.active_cell = Some((token_id.to_owned(), cell));196
self.table_picker = None;197
}198
InputEvent::Change => {199
let Some(index) = self.table_line(token_id, cx) else {200
return;201
};202
let Some(input) = self.cell_input(token_id, cell) else {203
return;204
};205
let text = input.read(cx).value().to_string();206
let Some(mut table) = self.draft.table(index).cloned() else {207
return;208
};209
if table.cell(cell) == Some(text.as_str()) {210
return;211
}212
table.set_cell(cell, &text);213
self.draft.set_table(index, table);214
self.record(215
StepKind::CellTyping {216
table: token_number(token_id),217
row: cell.row,218
column: cell.column,219
},220
cx,221
);222
self.schedule_draft_save(cx);223
}224
_ => {}225
}226
cx.notify();227
}228
229
fn cell_input(&self, token_id: &str, cell: Cell) -> Option<Entity<TextareaState>> {230
self.tables231
.get(token_id)?232
.cells233
.get(cell.row)?234
.get(cell.column)235
.cloned()236
}237
238
pub(super) fn focused_cell_input(239
&self,240
window: &Window,241
cx: &App,242
) -> Option<Entity<TextareaState>> {243
let (token_id, cell) = self.focused_cell(window, cx)?;244
self.cell_input(&token_id, cell)245
}246
247
/// The cell that has the keyboard, if any.248
pub(super) fn focused_cell(&self, window: &Window, cx: &App) -> Option<(String, Cell)> {249
self.tables.iter().find_map(|(id, view)| {250
view.cells.iter().enumerate().find_map(|(row, inputs)| {251
inputs.iter().enumerate().find_map(|(column, input)| {252
input253
.focus_handle(cx)254
.is_focused(window)255
.then(|| (id.clone(), Cell::new(row, column)))256
})257
})258
})259
}260
261
pub(super) fn focus_cell(262
&mut self,263
token_id: &str,264
cell: Cell,265
window: &mut Window,266
cx: &mut Context<Self>,267
) {268
let Some(input) = self.cell_input(token_id, cell) else {269
return;270
};271
input.update(cx, |state, cx| {272
let end = state.value().len();273
state.focus(window, cx);274
state.set_selected_range(end..end, cx);275
});276
self.active_cell = Some((token_id.to_owned(), cell));277
cx.notify();278
}279
280
fn token_at_line(&self, index: usize, cx: &App) -> Option<String> {281
let line = self.draft.line_ranges().get(index)?.clone();282
self.table_tokens(cx)283
.into_iter()284
.find(|(range, _)| *range == line)285
.map(|(_, id)| id)286
}287
288
pub(super) fn focus_table_line(289
&mut self,290
index: usize,291
last: bool,292
window: &mut Window,293
cx: &mut Context<Self>,294
) {295
let Some(token_id) = self.token_at_line(index, cx) else {296
return;297
};298
let Some(table) = self.draft.table(index) else {299
return;300
};301
let cell = if last {302
table.last_cell()303
} else {304
Cell::new(0, 0)305
};306
self.focus_cell(&token_id, cell, window, cx);307
}308
309
pub(super) fn insert_table(310
&mut self,311
rows: usize,312
columns: usize,313
window: &mut Window,314
cx: &mut Context<Self>,315
) {316
self.table_picker = None;317
let cursor = match self.focused_cell(window, cx) {318
Some((token_id, _)) => self319
.table_line(&token_id, cx)320
.map_or(self.selection(cx).end, |index| {321
self.draft.line_ranges()[index].end322
}),323
None => self.selection(cx).end,324
};325
let index = self.draft.insert_table(cursor, Table::new(rows, columns));326
let after = self.draft.line_ranges()[index].end;327
self.commit(Some(after), window, cx);328
self.focus_table_line(index, false, window, cx);329
}330
331
fn leave_table(332
&mut self,333
token_id: &str,334
below: bool,335
window: &mut Window,336
cx: &mut Context<Self>,337
) {338
let Some(index) = self.table_line(token_id, cx) else {339
return;340
};341
let cursor = self.draft.line_beside_table(index, below);342
self.active_cell = None;343
self.focus(window, cx);344
self.commit(Some(cursor), window, cx);345
}346
347
/// Tab, Shift+Tab, Up and Down while a cell has the keyboard. `false` leaves the key to348
/// the cell.349
pub(super) fn table_key(350
&mut self,351
key: TableKey,352
window: &mut Window,353
cx: &mut Context<Self>,354
) -> bool {355
let Some((token_id, cell)) = self.focused_cell(window, cx) else {356
return false;357
};358
let Some(index) = self.table_line(&token_id, cx) else {359
return false;360
};361
let Some(mut table) = self.draft.table(index).cloned() else {362
return false;363
};364
let Some(input) = self.cell_input(&token_id, cell) else {365
return false;366
};367
let target = match key {368
TableKey::Next => {369
let (next, added_row) = table.next_cell(cell);370
if added_row {371
self.draft.set_table(index, table);372
self.record(StepKind::Other, cx);373
self.sync_tables(window, cx);374
self.schedule_draft_save(cx);375
}376
next377
}378
TableKey::Previous => table.previous_cell(cell),379
TableKey::Down if !caret_on_last_line(input.read(cx)) => return false,380
TableKey::Up if !caret_on_first_line(input.read(cx)) => return false,381
TableKey::Down if cell.row + 1 == table.row_count() => {382
self.leave_table(&token_id, true, window, cx);383
return true;384
}385
TableKey::Up if cell.row == 0 => {386
self.leave_table(&token_id, false, window, cx);387
return true;388
}389
TableKey::Down => Cell::new(cell.row + 1, cell.column),390
TableKey::Up => Cell::new(cell.row - 1, cell.column),391
};392
self.focus_cell(&token_id, target, window, cx);393
true394
}395
396
pub(super) fn edit_table(397
&mut self,398
edit: TableEdit,399
window: &mut Window,400
cx: &mut Context<Self>,401
) {402
let Some((token_id, cell)) = self403
.focused_cell(window, cx)404
.or_else(|| self.active_cell.clone())405
else {406
return;407
};408
let Some(index) = self.table_line(&token_id, cx) else {409
return;410
};411
let Some(mut table) = self.draft.table(index).cloned() else {412
return;413
};414
match table.apply(edit, cell) {415
Some(target) => {416
self.draft.set_table(index, table);417
self.record(StepKind::Other, cx);418
self.sync_tables(window, cx);419
self.schedule_draft_save(cx);420
self.focus_cell(&token_id, target, window, cx);421
}422
None => {423
let cursor = self.draft.remove_table(index);424
self.active_cell = None;425
self.focus(window, cx);426
self.commit(Some(cursor), window, cx);427
}428
}429
cx.notify();430
}431
432
/// The caret never rests on a table's line: coming from above it enters the first433
/// cell, from below the first cell of the last row. Only a move without an edit434
/// counts, so a paste that passes the table on its way does not enter it.435
pub(super) fn redirect_caret_from_table(436
&mut self,437
window: &mut Window,438
cx: &mut Context<Self>,439
) {440
let state = self.input.read(cx);441
let selection = state.selected_range();442
let focused = state.focus_handle(cx).is_focused(window);443
let value = state.value();444
if value.as_ref() != self.caret_text {445
self.caret_text = value.to_string();446
self.caret_before_table = selection.start;447
return;448
}449
if !focused || !selection.is_empty() || value.as_ref() != self.draft.text() {450
return;451
}452
let Some(index) = self.draft.table_at(selection.start) else {453
self.caret_before_table = selection.start;454
return;455
};456
let line = self.draft.line_ranges()[index].clone();457
let from_below = self.caret_before_table > line.end;458
let resting = if from_below {459
self.draft460
.line_ranges()461
.get(index + 1)462
.map_or(line.end, |next| next.start)463
} else {464
line.start.saturating_sub(1)465
};466
self.input.update(cx, |state, cx| {467
state.set_selected_range(resting..resting, cx)468
});469
self.caret_before_table = resting;470
let token = self.token_at_line(index, cx);471
let Some(token_id) = token else {472
return;473
};474
let row = if from_below {475
self.draft476
.table(index)477
.map_or(0, |table| table.row_count() - 1)478
} else {479
0480
};481
self.focus_cell(&token_id, Cell::new(row, 0), window, cx);482
}483
484
pub(super) fn open_table_picker(&mut self, cx: &mut Context<Self>) {485
self.table_picker = Some(TablePicker {486
rows: 1,487
columns: 1,488
});489
cx.notify();490
}491
492
pub(super) fn render_table_picker(&self, cx: &mut Context<Self>) -> Option<AnyElement> {493
let picker = self.table_picker.as_ref()?;494
let grid = v_flex()495
.gap(px(PICKER_GAP))496
.children((1..=PICKER_ROWS).map(|row| {497
h_flex()498
.gap(px(PICKER_GAP))499
.children((1..=PICKER_COLUMNS).map(|column| {500
let covered = row <= picker.rows && column <= picker.columns;501
div()502
.id(ElementId::Name(format!("table-size-{row}-{column}").into()))503
.size(px(PICKER_SQUARE))504
.rounded(px(2.))505
.border_1()506
.border_color(if covered {507
theme::accent()508
} else {509
theme::border_strong()510
})511
.when(covered, |square| square.bg(theme::accent().opacity(0.25)))512
.cursor_pointer()513
.on_hover(cx.listener(move |this, hovered: &bool, _, cx| {514
if *hovered && let Some(picker) = this.table_picker.as_mut() {515
picker.rows = row;516
picker.columns = column;517
cx.notify();518
}519
}))520
.on_click(cx.listener(move |this, _, window, cx| {521
this.insert_table(row, column, window, cx)522
}))523
}))524
}));525
Some(526
v_flex()527
.id("table-picker")528
.absolute()529
.bottom(relative(1.))530
.left_0()531
.mb(px(6.))532
.p(px(10.))533
.gap(px(8.))534
.rounded(px(10.))535
.flyout_surface()536
.occlude()537
.on_mouse_down_out(cx.listener(|this, _, _, cx| {538
this.table_picker = None;539
cx.notify();540
}))541
.child(542
div()543
.text_size(px(12.))544
.text_color(theme::text_muted())545
.child(format!("Insert {}x{} table", picker.columns, picker.rows)),546
)547
.child(grid)548
.into_any_element(),549
)550
}551
552
/// The table token: a grid of cell inputs over the full width, solid lines like Teams.553
pub(super) fn render_table_token(&self, token_id: &str, width: Pixels) -> Option<AnyElement> {554
let view = self.tables.get(token_id)?;555
let rows = view.cells.iter().map(|inputs| {556
h_flex()557
.w_full()558
.items_stretch()559
.children(inputs.iter().map(|input| {560
div()561
.flex_1()562
.min_w_0()563
.px(px(CELL_PADDING_X))564
.py(px(CELL_PADDING_Y))565
.border_r_1()566
.border_b_1()567
.border_color(theme::border_strong())568
.child(569
Textarea::new(input)570
.appearance(false)571
.bordered(false)572
.small()573
.context_menu(|menu, _, _| table_menu(menu)),574
)575
}))576
});577
Some(578
v_flex()579
.id(ElementId::Name(format!("composer-{token_id}").into()))580
.w(width)581
.my(px(TABLE_MARGIN))582
.border_t_1()583
.border_l_1()584
.border_color(theme::border_strong())585
.on_any_mouse_down(|_, window, cx| {586
window.prevent_default();587
cx.stop_propagation();588
})589
.children(rows)590
.into_any_element(),591
)592
}593
}594
595
fn table_menu(menu: NativeMenu) -> NativeMenu {596
let menu = TableEdit::INSERTS597
.into_iter()598
.fold(menu, |menu, edit| {599
menu.menu(edit.label(), edit_action(edit))600
})601
.separator();602
TableEdit::DELETES603
.into_iter()604
.fold(menu, |menu, edit| {605
menu.menu(edit.label(), edit_action(edit))606
})607
.separator()608
.menu("Cut", Box::new(Cut))609
.menu("Copy", Box::new(Copy))610
.menu("Paste", Box::new(Paste))611
}612
613
#[derive(Debug, Clone, Copy, PartialEq, Eq)]614
pub(super) enum TableKey {615
Next,616
Previous,617
Up,618
Down,619
}620
621
fn edit_action(edit: TableEdit) -> Box<dyn Action> {622
match edit {623
TableEdit::InsertRowAbove => Box::new(InsertTableRowAbove),624
TableEdit::InsertRowBelow => Box::new(InsertTableRowBelow),625
TableEdit::InsertColumnLeft => Box::new(InsertTableColumnLeft),626
TableEdit::InsertColumnRight => Box::new(InsertTableColumnRight),627
TableEdit::DeleteRow => Box::new(DeleteTableRow),628
TableEdit::DeleteColumn => Box::new(DeleteTableColumn),629
TableEdit::DeleteTable => Box::new(DeleteTable),630
}631
}632
633
pub(super) type TableViews = HashMap<String, TableView>;@@ -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)))