BlueGit

ict rusty-teams

Merge remote-tracking branch 'origin/main' into fix/title-search-center

metis Daniel Däschle · pushed by metis

Authored 2026-10-17 · 6 weeks ago

Hash
f1c8be21ba0c113c7b920c2f4666c87e51b64131
28 files changed +2281 −132
crates/app-base/src/assets.rs +2 −1
@@ -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
11const SYMBOLS: [(&str, &[u8]); 54] = symbols![
11const 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",
crates/app-ui-kit/src/draft_style.rs +13 −1
@@ -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.;
13const QUOTE_INDENT: f32 = 12.;
13const QUOTE_INDENT: f32 = 12.;
14const CODE_INDENT: f32 = 10.;
14const CODE_INDENT: f32 = 10.;
15const LIST_LEVEL_INDENT: f32 = 18.;
15const LIST_LEVEL_INDENT: f32 = 18.;
16const 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.
18pub struct DraftStyle {
19pub struct DraftStyle {
@@ -24,7 +25,7 @@ pub struct DraftStyle {
24
25
25fn line_indent(kind: &LineKind) -> f32 {
26fn 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 flags
84 flags
84}
85}
85
86
87fn 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 cover
97/// From the start of the first line of `lines` to the end of the last; Block and Bar cover
87/// 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.
88fn block_range(draft: &Draft, lines: Range<usize>) -> Range<usize> {
99fn 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 }
crates/app/assets/symbols/table.svg added +1 −0
@@ -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>
crates/app/src/layout_guard.rs +131 −0
@@ -176,6 +176,7 @@ mod frames {
176 176 use crate::user_activity::UserInput;
177 177 use crate::views::call_transcript::TranscriptPanel;
178 178 use crate::views::call_view::CHAT_PANEL_TAG;
179 use crate::views::composer::{COMPOSER_BOX_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG};
179 180 use crate::views::message_row::BUBBLE_TAGS;
180 181 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
181 182 use crate::views::reaction_proposal_pill::REACTION_PILL;
@@ -935,6 +936,66 @@ mod frames {
935 936 }
936 937 }
937 938
939 fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {
940 collect(visual, Some(COMPOSER_SEND_TAG));
941 let mut bounds_of = |path: &'static str| {
942 visual
943 .debug_bounds(path)
944 .unwrap_or_else(|| panic!("{path} rendered"))
945 };
946 let composer = bounds_of(COMPOSER_BOX_TAG);
947 let leading = bounds_of(COMPOSER_LEADING_TAG);
948 let send = bounds_of(COMPOSER_SEND_TAG);
949 [
950 f32::from(leading.left() - composer.left()),
951 f32::from(leading.top() - composer.top()),
952 f32::from(composer.bottom() - leading.bottom()),
953 f32::from(composer.right() - send.right()),
954 f32::from(send.top() - composer.top()),
955 f32::from(composer.bottom() - send.bottom()),
956 ]
957 }
958
959 #[gpui_kit::test]
960 fn composer_buttons_keep_equal_insets(cx: &mut TestAppContext) {
961 let (handle, _) = mount(cx);
962 let mut visual = VisualTestContext::from_window(handle, cx);
963 visual.simulate_resize(size(px(1280.), px(800.)));
964 let single_line = composer_button_insets(&mut visual);
965 let left = single_line[0];
966 assert!(
967 single_line
968 .iter()
969 .all(|inset| (inset - left).abs() < TOLERANCE),
970 "single line: insets left, top, bottom of the first button and right, top, bottom of send {single_line:?}"
971 );
972 let leading = visual
973 .debug_bounds(COMPOSER_LEADING_TAG)
974 .expect("leading buttons");
975 let send = visual.debug_bounds(COMPOSER_SEND_TAG).expect("send button");
976 visual.simulate_click(
977 point((leading.right() + send.left()) / 2., send.center().y),
978 Default::default(),
979 );
980 visual.simulate_keystrokes("o n e shift-enter t w o shift-enter t h r e e");
981 let three_lines = composer_button_insets(&mut visual);
982 assert!(
983 three_lines[1] > single_line[1] + 30.,
984 "three lines did not grow the composer: {three_lines:?}"
985 );
986 for inset in [
987 three_lines[0],
988 three_lines[2],
989 three_lines[3],
990 three_lines[5],
991 ] {
992 assert!(
993 (inset - left).abs() < TOLERANCE,
994 "three lines: insets left, top, bottom of the first button and right, top, bottom of send {three_lines:?}, expected {left}"
995 );
996 }
997 }
998
938 999 #[gpui_kit::test]
939 1000 fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {
940 1001 let (handle, state) = mount_with(cx, true);
@@ -997,3 +1058,73 @@ fn lines_are_solid() {
997 1058 .collect();
998 1059 assert!(violations.is_empty(), "{}", violations.join("\n"));
999 1060 }
1061
1062 fn indentation(line: &str) -> usize {
1063 line.len() - line.trim_start().len()
1064 }
1065
1066 fn chain_lines<'a>(lines: &[&'a str], index: usize) -> Vec<&'a str> {
1067 let indent = indentation(lines[index]);
1068 let belongs = |line: &&str| line.trim().is_empty() || indentation(line) >= indent;
1069 let start = lines[..index]
1070 .iter()
1071 .rposition(|line| !belongs(line))
1072 .map_or(0, |position| position + 1);
1073 let end = lines[index..]
1074 .iter()
1075 .position(|line| !belongs(line))
1076 .map_or(lines.len(), |position| index + position);
1077 lines[start..end]
1078 .iter()
1079 .filter(|line| indentation(line) == indent)
1080 .copied()
1081 .collect()
1082 }
1083
1084 fn shrinking_rows(row_height: &Regex, source: &str) -> Vec<usize> {
1085 let lines: Vec<&str> = source.lines().collect();
1086 (0..lines.len())
1087 .filter(|&index| row_height.is_match(lines[index]))
1088 .filter(|&index| {
1089 !chain_lines(&lines, index).iter().any(|line| {
1090 let line = line.trim();
1091 line.starts_with(".flex_none()") || line.starts_with(".flex_shrink_0()")
1092 })
1093 })
1094 .map(|index| index + 1)
1095 .collect()
1096 }
1097
1098 fn row_height_pattern() -> Regex {
1099 Regex::new(r"^\s*\.h\(px\(((\w+_)?(ROW|ENTRY)_HEIGHT|row_height)\)\)").expect("pattern")
1100 }
1101
1102 #[test]
1103 fn matcher_finds_rows_without_flex_none() {
1104 let source = "fn rows() {\n h_flex()\n .h(px(ROW_HEIGHT))\n .child(\n div()\n .flex_none(),\n );\n div()\n .id(1)\n .h(px(OWN_ROW_HEIGHT))\n .flex_none();\n}\n";
1105 assert_eq!(shrinking_rows(&row_height_pattern(), source), [3]);
1106 }
1107
1108 #[test]
1109 fn fixed_height_rows_never_shrink() {
1110 let row_height = row_height_pattern();
1111 let mut files = Vec::new();
1112 for root in source_roots() {
1113 source_files(&root, &mut files);
1114 }
1115 let violations: Vec<String> = files
1116 .iter()
1117 .filter(|file| !file.ends_with("layout_guard.rs"))
1118 .flat_map(|file| {
1119 let source = fs::read_to_string(file).expect("read source file");
1120 shrinking_rows(&row_height, &source)
1121 .into_iter()
1122 .map(|line| format!("{}:{line}", file.display()))
1123 .collect::<Vec<_>>()
1124 })
1125 .collect();
1126 assert!(
1127 violations.is_empty(),
1128 "a fixed-height row needs .flex_none(), or a max_h scroll list shrinks it to its content: {violations:?}"
1129 );
1130 }
@@ -176,6 +176,7 @@ mod frames {
176 use crate::user_activity::UserInput;
176 use crate::user_activity::UserInput;
177 use crate::views::call_transcript::TranscriptPanel;
177 use crate::views::call_transcript::TranscriptPanel;
178 use crate::views::call_view::CHAT_PANEL_TAG;
178 use crate::views::call_view::CHAT_PANEL_TAG;
179 use crate::views::composer::{COMPOSER_BOX_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG};
179 use crate::views::message_row::BUBBLE_TAGS;
180 use crate::views::message_row::BUBBLE_TAGS;
180 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
181 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
181 use crate::views::reaction_proposal_pill::REACTION_PILL;
182 use crate::views::reaction_proposal_pill::REACTION_PILL;
@@ -935,6 +936,66 @@ mod frames {
935 }
936 }
936 }
937 }
937
938
939 fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {
940 collect(visual, Some(COMPOSER_SEND_TAG));
941 let mut bounds_of = |path: &'static str| {
942 visual
943 .debug_bounds(path)
944 .unwrap_or_else(|| panic!("{path} rendered"))
945 };
946 let composer = bounds_of(COMPOSER_BOX_TAG);
947 let leading = bounds_of(COMPOSER_LEADING_TAG);
948 let send = bounds_of(COMPOSER_SEND_TAG);
949 [
950 f32::from(leading.left() - composer.left()),
951 f32::from(leading.top() - composer.top()),
952 f32::from(composer.bottom() - leading.bottom()),
953 f32::from(composer.right() - send.right()),
954 f32::from(send.top() - composer.top()),
955 f32::from(composer.bottom() - send.bottom()),
956 ]
957 }
958
959 #[gpui_kit::test]
960 fn composer_buttons_keep_equal_insets(cx: &mut TestAppContext) {
961 let (handle, _) = mount(cx);
962 let mut visual = VisualTestContext::from_window(handle, cx);
963 visual.simulate_resize(size(px(1280.), px(800.)));
964 let single_line = composer_button_insets(&mut visual);
965 let left = single_line[0];
966 assert!(
967 single_line
968 .iter()
969 .all(|inset| (inset - left).abs() < TOLERANCE),
970 "single line: insets left, top, bottom of the first button and right, top, bottom of send {single_line:?}"
971 );
972 let leading = visual
973 .debug_bounds(COMPOSER_LEADING_TAG)
974 .expect("leading buttons");
975 let send = visual.debug_bounds(COMPOSER_SEND_TAG).expect("send button");
976 visual.simulate_click(
977 point((leading.right() + send.left()) / 2., send.center().y),
978 Default::default(),
979 );
980 visual.simulate_keystrokes("o n e shift-enter t w o shift-enter t h r e e");
981 let three_lines = composer_button_insets(&mut visual);
982 assert!(
983 three_lines[1] > single_line[1] + 30.,
984 "three lines did not grow the composer: {three_lines:?}"
985 );
986 for inset in [
987 three_lines[0],
988 three_lines[2],
989 three_lines[3],
990 three_lines[5],
991 ] {
992 assert!(
993 (inset - left).abs() < TOLERANCE,
994 "three lines: insets left, top, bottom of the first button and right, top, bottom of send {three_lines:?}, expected {left}"
995 );
996 }
997 }
998
938 #[gpui_kit::test]
999 #[gpui_kit::test]
939 fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {
1000 fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {
940 let (handle, state) = mount_with(cx, true);
1001 let (handle, state) = mount_with(cx, true);
@@ -997,3 +1058,73 @@ fn lines_are_solid() {
997 .collect();
1058 .collect();
998 assert!(violations.is_empty(), "{}", violations.join("\n"));
1059 assert!(violations.is_empty(), "{}", violations.join("\n"));
999}
1060}
1061
1062fn indentation(line: &str) -> usize {
1063 line.len() - line.trim_start().len()
1064}
1065
1066fn chain_lines<'a>(lines: &[&'a str], index: usize) -> Vec<&'a str> {
1067 let indent = indentation(lines[index]);
1068 let belongs = |line: &&str| line.trim().is_empty() || indentation(line) >= indent;
1069 let start = lines[..index]
1070 .iter()
1071 .rposition(|line| !belongs(line))
1072 .map_or(0, |position| position + 1);
1073 let end = lines[index..]
1074 .iter()
1075 .position(|line| !belongs(line))
1076 .map_or(lines.len(), |position| index + position);
1077 lines[start..end]
1078 .iter()
1079 .filter(|line| indentation(line) == indent)
1080 .copied()
1081 .collect()
1082}
1083
1084fn shrinking_rows(row_height: &Regex, source: &str) -> Vec<usize> {
1085 let lines: Vec<&str> = source.lines().collect();
1086 (0..lines.len())
1087 .filter(|&index| row_height.is_match(lines[index]))
1088 .filter(|&index| {
1089 !chain_lines(&lines, index).iter().any(|line| {
1090 let line = line.trim();
1091 line.starts_with(".flex_none()") || line.starts_with(".flex_shrink_0()")
1092 })
1093 })
1094 .map(|index| index + 1)
1095 .collect()
1096}
1097
1098fn row_height_pattern() -> Regex {
1099 Regex::new(r"^\s*\.h\(px\(((\w+_)?(ROW|ENTRY)_HEIGHT|row_height)\)\)").expect("pattern")
1100}
1101
1102#[test]
1103fn matcher_finds_rows_without_flex_none() {
1104 let source = "fn rows() {\n h_flex()\n .h(px(ROW_HEIGHT))\n .child(\n div()\n .flex_none(),\n );\n div()\n .id(1)\n .h(px(OWN_ROW_HEIGHT))\n .flex_none();\n}\n";
1105 assert_eq!(shrinking_rows(&row_height_pattern(), source), [3]);
1106}
1107
1108#[test]
1109fn fixed_height_rows_never_shrink() {
1110 let row_height = row_height_pattern();
1111 let mut files = Vec::new();
1112 for root in source_roots() {
1113 source_files(&root, &mut files);
1114 }
1115 let violations: Vec<String> = files
1116 .iter()
1117 .filter(|file| !file.ends_with("layout_guard.rs"))
1118 .flat_map(|file| {
1119 let source = fs::read_to_string(file).expect("read source file");
1120 shrinking_rows(&row_height, &source)
1121 .into_iter()
1122 .map(|line| format!("{}:{line}", file.display()))
1123 .collect::<Vec<_>>()
1124 })
1125 .collect();
1126 assert!(
1127 violations.is_empty(),
1128 "a fixed-height row needs .flex_none(), or a max_h scroll list shrinks it to its content: {violations:?}"
1129 );
1130}
crates/app/src/views/actions.rs +13 −2
@@ -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 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
20actions!(teams, [ReplyToHovered, OpenSwitcher, NewChat, ToggleCallMute]);
28actions!(
29 teams,
30 [ReplyToHovered, OpenSwitcher, NewChat, ToggleCallMute]
31);
crates/app/src/views/calls_tab.rs +2 −0
@@ -62,6 +62,7 @@ fn call_row(
62 62 .id(SharedString::from(format!("call-{}", row.key)))
63 63 .mx(px(6.))
64 64 .h(px(CALL_ROW_HEIGHT))
65 .flex_none()
65 66 .px(px(10.))
66 67 .gap(px(12.))
67 68 .items_center()
@@ -336,6 +337,7 @@ fn agenda_row(
336 337 .id(SharedString::from(format!("agenda-{}", row.key)))
337 338 .mx(px(6.))
338 339 .h(px(AGENDA_ROW_HEIGHT))
340 .flex_none()
339 341 .px(px(10.))
340 342 .gap(px(12.))
341 343 .items_center()
@@ -62,6 +62,7 @@ fn call_row(
62 .id(SharedString::from(format!("call-{}", row.key)))
62 .id(SharedString::from(format!("call-{}", row.key)))
63 .mx(px(6.))
63 .mx(px(6.))
64 .h(px(CALL_ROW_HEIGHT))
64 .h(px(CALL_ROW_HEIGHT))
65 .flex_none()
65 .px(px(10.))
66 .px(px(10.))
66 .gap(px(12.))
67 .gap(px(12.))
67 .items_center()
68 .items_center()
@@ -336,6 +337,7 @@ fn agenda_row(
336 .id(SharedString::from(format!("agenda-{}", row.key)))
337 .id(SharedString::from(format!("agenda-{}", row.key)))
337 .mx(px(6.))
338 .mx(px(6.))
338 .h(px(AGENDA_ROW_HEIGHT))
339 .h(px(AGENDA_ROW_HEIGHT))
340 .flex_none()
339 .px(px(10.))
341 .px(px(10.))
340 .gap(px(12.))
342 .gap(px(12.))
341 .items_center()
343 .items_center()
crates/app/src/views/chat_members.rs +9 −1
@@ -22,6 +22,7 @@ const LIST_MAX_HEIGHT: f32 = 300.;
22 22 const POPUP_OFFSET: f32 = 16.;
23 23 const SECTION_HEIGHT: f32 = 24.;
24 24 const ROW_HEIGHT: f32 = 40.;
25 const OWN_ROW_HEIGHT: f32 = 43.;
25 26 const AVATAR_SIZE: f32 = 32.;
26 27 const EDGE_PADDING: f32 = 12.;
27 28 const ACTION_HEIGHT: f32 = 36.;
@@ -75,6 +76,7 @@ fn members_panel(
75 76 .child(
76 77 div()
77 78 .h(px(SECTION_HEIGHT))
79 .flex_none()
78 80 .px(px(EDGE_PADDING))
79 81 .flex()
80 82 .items_center()
@@ -148,10 +150,16 @@ fn member_row(
148 150 None => avatar,
149 151 };
150 152 let opens_chat = user_id.filter(|_| !row.is_self).map(str::to_owned);
153 let row_height = if row.is_self {
154 OWN_ROW_HEIGHT
155 } else {
156 ROW_HEIGHT
157 };
151 158 h_flex()
152 159 .id(("chat-member", index))
153 160 .group(group.clone())
154 .h(px(ROW_HEIGHT))
161 .h(px(row_height))
162 .flex_none()
155 163 .px(px(EDGE_PADDING))
156 164 .gap(px(8.))
157 165 .items_center()
@@ -22,6 +22,7 @@ const LIST_MAX_HEIGHT: f32 = 300.;
22const POPUP_OFFSET: f32 = 16.;
22const POPUP_OFFSET: f32 = 16.;
23const SECTION_HEIGHT: f32 = 24.;
23const SECTION_HEIGHT: f32 = 24.;
24const ROW_HEIGHT: f32 = 40.;
24const ROW_HEIGHT: f32 = 40.;
25const OWN_ROW_HEIGHT: f32 = 43.;
25const AVATAR_SIZE: f32 = 32.;
26const AVATAR_SIZE: f32 = 32.;
26const EDGE_PADDING: f32 = 12.;
27const EDGE_PADDING: f32 = 12.;
27const ACTION_HEIGHT: f32 = 36.;
28const ACTION_HEIGHT: f32 = 36.;
@@ -75,6 +76,7 @@ fn members_panel(
75 .child(
76 .child(
76 div()
77 div()
77 .h(px(SECTION_HEIGHT))
78 .h(px(SECTION_HEIGHT))
79 .flex_none()
78 .px(px(EDGE_PADDING))
80 .px(px(EDGE_PADDING))
79 .flex()
81 .flex()
80 .items_center()
82 .items_center()
@@ -148,10 +150,16 @@ fn member_row(
148 None => avatar,
150 None => avatar,
149 };
151 };
150 let opens_chat = user_id.filter(|_| !row.is_self).map(str::to_owned);
152 let opens_chat = user_id.filter(|_| !row.is_self).map(str::to_owned);
153 let row_height = if row.is_self {
154 OWN_ROW_HEIGHT
155 } else {
156 ROW_HEIGHT
157 };
151 h_flex()
158 h_flex()
152 .id(("chat-member", index))
159 .id(("chat-member", index))
153 .group(group.clone())
160 .group(group.clone())
154 .h(px(ROW_HEIGHT))
161 .h(px(row_height))
162 .flex_none()
155 .px(px(EDGE_PADDING))
163 .px(px(EDGE_PADDING))
156 .gap(px(8.))
164 .gap(px(8.))
157 .items_center()
165 .items_center()
crates/app/src/views/composer.rs +383 −54
@@ -13,8 +13,9 @@ use gpui_kit::component::{
13 13 h_flex,
14 14 input::{
15 15 Backspace, Copy, Cut, Delete, Enter, Escape, IndentInline, InlineToken, InputContent,
16 InputEvent, InputState, MoveDown, MoveUp, OutdentInline, RangeDecorationCollection, Redo,
17 TextDecorationCollection, Textarea, TextareaMode, TextareaState, Undo,
16 InputEvent, InputState, MoveDown, MoveRight, MoveUp, OutdentInline,
17 RangeDecorationCollection, Redo, TextDecorationCollection, Textarea, TextareaMode,
18 TextareaState, Undo,
18 19 },
19 20 popover::Popover,
20 21 tooltip::Tooltip,
@@ -24,21 +25,24 @@ use gpui_kit::prelude::FluentBuilder as _;
24 25 use gpui_kit::*;
25 26 use teams_core::{
26 27 Draft, DraftLine, Edit, FileReference, FormatState, LineKind, LinkPreview, MarkKind,
27 MentionCandidate, MentionInput, OBJECT_MARK, SizeStep, TypingStyle,
28 MentionCandidate, MentionInput, OBJECT_MARK, SizeStep, TABLE_MARK, TableEdit, TypingStyle,
28 29 UploadedFile, changed_span, has_markdown, link_url, map_offset, reverse_edits,
29 30 };
30 31
31 32 mod drafts;
32 33 mod schedule;
34 mod table;
33 35
34 36 use super::actions::{
35 COMPOSER_KEY_CONTEXT, EditLink, OpenSwitcher, ScheduleSend, ToggleBold, ToggleCode, ToggleItalic,
36 ToggleStrike, ToggleSubscript, ToggleSuperscript, ToggleUnderline,
37 COMPOSER_KEY_CONTEXT, DeleteTable, DeleteTableColumn, DeleteTableRow, EditLink,
38 InsertTableColumnLeft, InsertTableColumnRight, InsertTableRowAbove, InsertTableRowBelow,
39 OpenSwitcher, PastePlainText, ScheduleSend, ToggleBold, ToggleCode, ToggleItalic, ToggleStrike,
40 ToggleSubscript, ToggleSuperscript, ToggleUnderline,
37 41 };
38 42 use super::attachment_tray::{
39 AttachmentTray, DoneFile, JobKind, LoadedFile, MAX_ATTACHMENTS,
40 PasteAction, UploadJob, UploadResult, discard_uploaded, inline_preview, names_of, paste_action,
41 pasted_image_name, prepare_pasted_image, read_attachment, render_tray,
43 AttachmentTray, DoneFile, JobKind, LoadedFile, MAX_ATTACHMENTS, PasteAction, UploadJob,
44 UploadResult, discard_uploaded, inline_preview, names_of, paste_action, pasted_image_name,
45 prepare_pasted_image, read_attachment, render_tray,
42 46 };
43 47 use super::avatar::{person_avatar, square_avatar};
44 48 use super::draft_style::draft_style;
@@ -55,6 +59,7 @@ use crate::runtime;
55 59 use crate::scheduled_rows::scheduled_label;
56 60 use crate::theme::{self, ElevatedSurface as _};
57 61 use crate::typing::OutgoingTyping;
62 use table::{TableKey, TablePicker, TableViews, is_table_token};
58 63
59 64 const MIN_ROWS: usize = 1;
60 65 const MAX_ROWS: usize = 8;
@@ -67,6 +72,11 @@ const POPUP_WIDTH: f32 = 380.;
67 72 const POPUP_ROW_HEIGHT: f32 = 44.;
68 73 const DEMO_UPLOAD_STEPS: u8 = 10;
69 74 const COMPOSER_ICON_SIZE: f32 = 20.;
75 const COMPOSER_BUTTON_SIZE: f32 = 32.;
76 const COMPOSER_BUTTON_INSET: f32 = 6.;
77 pub const COMPOSER_BOX_TAG: &str = "composer";
78 pub const COMPOSER_LEADING_TAG: &str = "composer/leading";
79 pub const COMPOSER_SEND_TAG: &str = "composer/send";
70 80 /// gpui-kit draws a `Size::Size` button's icon at this fraction of the button size.
71 81 const BUTTON_ICON_SCALE: f32 = 0.75;
72 82 const DEMO_UPLOAD_STEP: Duration = Duration::from_millis(120);
@@ -126,8 +136,19 @@ struct Conversion {
126 136
127 137 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
128 138 enum StepKind {
129 Typing { at: usize, after_space: bool },
130 Deleting { start: usize, end: usize },
139 Typing {
140 at: usize,
141 after_space: bool,
142 },
143 Deleting {
144 start: usize,
145 end: usize,
146 },
147 CellTyping {
148 table: usize,
149 row: usize,
150 column: usize,
151 },
131 152 Other,
132 153 }
133 154
@@ -192,6 +213,12 @@ pub struct Composer {
192 213 pending_anchors: HashMap<u64, usize>,
193 214 link: ComposeLink,
194 215 fun_picker: Entity<FunPicker>,
216 tables: TableViews,
217 table_counter: usize,
218 table_picker: Option<TablePicker>,
219 active_cell: Option<(String, teams_core::Cell)>,
220 caret_before_table: usize,
221 caret_text: String,
195 222 _subscriptions: [Subscription; 4],
196 223 }
197 224
@@ -292,6 +319,9 @@ fn continues(last: &HistoryStep, kind: StepKind) -> bool {
292 319 (StepKind::Deleting { .. }, StepKind::Deleting { start, end }) => {
293 320 caret.is_empty() && (caret.start == end || caret.start == start)
294 321 }
322 (previous @ StepKind::CellTyping { .. }, next @ StepKind::CellTyping { .. }) => {
323 previous == next
324 }
295 325 _ => false,
296 326 }
297 327 }
@@ -328,7 +358,10 @@ impl Composer {
328 358 .placeholder("Type a message")
329 359 });
330 360 let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
331 let observer = cx.observe(&input, |_, _, cx| cx.notify());
361 let observer = cx.observe_in(&input, window, |this, _, window, cx| {
362 this.redirect_caret_from_table(window, cx);
363 cx.notify();
364 });
332 365 let image_observer = cx.observe(&app, |this, _, cx| {
333 366 if this.link_image_pending(cx) {
334 367 cx.notify();
@@ -389,6 +422,12 @@ impl Composer {
389 422 pending_anchors: HashMap::new(),
390 423 link: ComposeLink::default(),
391 424 fun_picker,
425 tables: TableViews::default(),
426 table_counter: 0,
427 table_picker: None,
428 active_cell: None,
429 caret_before_table: 0,
430 caret_text: String::new(),
392 431 _subscriptions: [subscription, observer, image_observer, picker_subscription],
393 432 }
394 433 }
@@ -640,6 +679,7 @@ impl Composer {
640 679 }
641 680 self.previous_value = value;
642 681 self.refresh_style(cx);
682 self.sync_tables(window, cx);
643 683 }
644 684
645 685 fn shift_anchors(&mut self, start: usize, old_end: usize, new_end: usize) {
@@ -737,6 +777,7 @@ impl Composer {
737 777 self.conversion = None;
738 778 self.paste_hint = None;
739 779 self.refresh_style(cx);
780 self.sync_tables(window, cx);
740 781 self.update_emoji(cx);
741 782 self.update_mention(cx);
742 783 self.schedule_draft_save(cx);
@@ -775,6 +816,9 @@ impl Composer {
775 816 self.link_editor = None;
776 817 self.toolbar_dismissed = None;
777 818 self.pending_anchors.clear();
819 self.active_cell = None;
820 self.table_picker = None;
821 self.sync_tables(window, cx);
778 822 self.history.clear();
779 823 self.history_index = 0;
780 824 self.record(StepKind::Other, cx);
@@ -1064,6 +1108,64 @@ impl Composer {
1064 1108 }
1065 1109 }
1066 1110
1111 fn leave_quote(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
1112 let selection = self.selection(cx);
1113 if !selection.is_empty() || self.input.read(cx).value().as_ref() != self.draft.text() {
1114 return false;
1115 }
1116 match self.draft.leave_quote_at_end(selection.start) {
1117 Some(cursor) => {
1118 self.commit(Some(cursor), window, cx);
1119 true
1120 }
1121 None => false,
1122 }
1123 }
1124
1125 /// Backspace right after a table or Delete right before one goes into it instead of
1126 /// joining the line with the table's.
1127 fn enter_table_beside(
1128 &mut self,
1129 after: bool,
1130 window: &mut Window,
1131 cx: &mut Context<Self>,
1132 ) -> bool {
1133 let selection = self.selection(cx);
1134 if !selection.is_empty() || self.input.read(cx).value().as_ref() != self.draft.text() {
1135 return false;
1136 }
1137 let found = if after {
1138 self.draft.table_before(selection.start)
1139 } else {
1140 self.draft.table_after(selection.start)
1141 };
1142 let Some(index) = found else {
1143 return false;
1144 };
1145 self.focus_table_line(index, after, window, cx);
1146 true
1147 }
1148
1149 fn cell_has_focus(&self, window: &Window, cx: &App) -> bool {
1150 self.focused_cell(window, cx).is_some()
1151 }
1152
1153 fn paste_plain(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1154 let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) else {
1155 return;
1156 };
1157 let text = text
1158 .replace("\r\n", "\n")
1159 .replace([OBJECT_MARK, TABLE_MARK], "");
1160 if let Some(input) = self.focused_cell_input(window, cx) {
1161 input.update(cx, |state, cx| state.replace(text, window, cx));
1162 return;
1163 }
1164 self.pasted_markdown = None;
1165 self.input
1166 .update(cx, |state, cx| state.replace(text, window, cx));
1167 }
1168
1067 1169 fn indent(&mut self, outdent: bool, window: &mut Window, cx: &mut Context<Self>) -> bool {
1068 1170 let selection = self.selection(cx);
1069 1171 if !self.draft.indent(selection, outdent) {
@@ -1079,12 +1181,16 @@ impl Composer {
1079 1181 return false;
1080 1182 }
1081 1183 let selected = &self.draft.text()[selection.clone()];
1082 let text = selected.replace(OBJECT_MARK, "");
1083 1184 let lines = if selected.contains(OBJECT_MARK) {
1084 1185 self.draft.slice_without_objects(selection)
1085 1186 } else {
1086 1187 self.draft.slice(selection)
1087 1188 };
1189 let text = if selected.contains(TABLE_MARK) {
1190 Draft::from_lines(&lines).plain_text()
1191 } else {
1192 selected.replace(OBJECT_MARK, "")
1193 };
1088 1194 if text.is_empty() {
1089 1195 return true;
1090 1196 }
@@ -1150,8 +1256,8 @@ impl Composer {
1150 1256 }
1151 1257 let matches = emoji::search(&query, &self.recent_emoji.glyphs(), emoji_popup::LIMIT);
1152 1258 let skin_tone = teams_core::skin_tone(&self.app.read(cx).store);
1153 self.emoji_popup = (!matches.is_empty())
1154 .then(|| EmojiPopup::new(range, query, matches, skin_tone));
1259 self.emoji_popup =
1260 (!matches.is_empty()).then(|| EmojiPopup::new(range, query, matches, skin_tone));
1155 1261 }
1156 1262
1157 1263 fn accept_emoji(&mut self, window: &mut Window, cx: &mut Context<Self>) {
@@ -1764,8 +1870,8 @@ impl Composer {
1764 1870 let Some(text) = item.text() else {
1765 1871 return false;
1766 1872 };
1767 if text.contains(OBJECT_MARK) {
1768 let cleaned = text.replace(OBJECT_MARK, "");
1873 if text.contains([OBJECT_MARK, TABLE_MARK]) {
1874 let cleaned = text.replace([OBJECT_MARK, TABLE_MARK], "");
1769 1875 self.input
1770 1876 .update(cx, |state, cx| state.replace(cleaned, window, cx));
1771 1877 return true;
@@ -2107,6 +2213,7 @@ impl Composer {
2107 2213 .mx(px(6.))
2108 2214 .px(px(6.))
2109 2215 .h(px(POPUP_ROW_HEIGHT))
2216 .flex_none()
2110 2217 .gap(px(8.))
2111 2218 .items_center()
2112 2219 .rounded(px(6.))
@@ -2396,8 +2503,9 @@ impl Render for Composer {
2396 2503 let can_attach = self.editing.is_none();
2397 2504 let send = div()
2398 2505 .id("composer-send")
2399 .size(px(32.))
2400 .ml(px(6.))
2506 .debug_selector(|| COMPOSER_SEND_TAG.into())
2507 .size(px(COMPOSER_BUTTON_SIZE))
2508 .ml(px(COMPOSER_BUTTON_INSET))
2401 2509 .flex_none()
2402 2510 .flex()
2403 2511 .items_center()
@@ -2431,7 +2539,7 @@ impl Render for Composer {
2431 2539 )
2432 2540 .rounded(px(8.))
2433 2541 .with_size(px(COMPOSER_ICON_SIZE / BUTTON_ICON_SCALE))
2434 .size(px(32.))
2542 .size(px(COMPOSER_BUTTON_SIZE))
2435 2543 .tooltip("Emoji, GIFs und Sticker")
2436 2544 .icon(symbol("mood", COMPOSER_ICON_SIZE, theme::text_muted())),
2437 2545 )
@@ -2449,7 +2557,7 @@ impl Render for Composer {
2449 2557 let attach = can_attach.then(|| {
2450 2558 div()
2451 2559 .id("composer-attach")
2452 .size(px(32.))
2560 .size(px(COMPOSER_BUTTON_SIZE))
2453 2561 .flex_none()
2454 2562 .flex()
2455 2563 .items_center()
@@ -2465,9 +2573,28 @@ impl Render for Composer {
2465 2573 ))
2466 2574 .on_click(cx.listener(|this, _, window, cx| this.open_picker(window, cx)))
2467 2575 });
2576 let table_button = can_attach.then(|| {
2577 div()
2578 .id("composer-table")
2579 .size(px(COMPOSER_BUTTON_SIZE))
2580 .flex_none()
2581 .flex()
2582 .items_center()
2583 .justify_center()
2584 .rounded(px(8.))
2585 .cursor_pointer()
2586 .hover(|button| button.bg(theme::popup_hover()))
2587 .when(self.table_picker.is_some(), |button| {
2588 button.bg(theme::popup_hover())
2589 })
2590 .tooltip(|window, cx| Tooltip::new("Insert table").build(window, cx))
2591 .child(symbol("table", COMPOSER_ICON_SIZE, theme::text_muted()))
2592 .on_click(cx.listener(|this, _, _, cx| this.open_table_picker(cx)))
2593 });
2468 2594 let composer = cx.weak_entity();
2469 2595 let tokens_composer = composer.clone();
2470 2596 let input = Textarea::new(&self.input)
2597 .line_box_height(px(COMPOSER_BUTTON_SIZE))
2471 2598 .appearance(false)
2472 2599 .bordered(false)
2473 2600 .on_paste(move |item, window, cx| {
@@ -2476,6 +2603,17 @@ impl Render for Composer {
2476 2603 .unwrap_or(false)
2477 2604 })
2478 2605 .token(move |context, _, cx| {
2606 if context.is_block() && is_table_token(context.token()) {
2607 let token_id = context.token().id().to_string();
2608 let width = context.available_width();
2609 if let Some(table) = tokens_composer
2610 .read_with(cx, |this, _| this.render_table_token(&token_id, width))
2611 .ok()
2612 .flatten()
2613 {
2614 return table;
2615 }
2616 }
2479 2617 if let Some(id) = context
2480 2618 .is_block()
2481 2619 .then(|| image_id(context.token()))
@@ -2549,42 +2687,70 @@ impl Render for Composer {
2549 2687 .pt(px(top))
2550 2688 .pb(px(bottom))
2551 2689 .key_context(COMPOSER_KEY_CONTEXT)
2552 .on_action(cx.listener(|this, _: &ToggleBold, _, cx| {
2553 if this.link_editor.is_none() {
2690 .on_action(cx.listener(|this, _: &ToggleBold, window, cx| {
2691 if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
2554 2692 this.toggle_mark(MarkKind::Bold, cx);
2555 2693 }
2556 2694 }))
2557 .on_action(cx.listener(|this, _: &ToggleItalic, _, cx| {
2558 if this.link_editor.is_none() {
2695 .on_action(cx.listener(|this, _: &ToggleItalic, window, cx| {
2696 if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
2559 2697 this.toggle_mark(MarkKind::Italic, cx);
2560 2698 }
2561 2699 }))
2562 .on_action(cx.listener(|this, _: &ToggleUnderline, _, cx| {
2563 if this.link_editor.is_none() {
2700 .on_action(cx.listener(|this, _: &ToggleUnderline, window, cx| {
2701 if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
2564 2702 this.toggle_mark(MarkKind::Underline, cx);
2565 2703 }
2566 2704 }))
2567 .on_action(cx.listener(|this, _: &ToggleStrike, _, cx| {
2568 if this.link_editor.is_none() {
2705 .on_action(cx.listener(|this, _: &ToggleStrike, window, cx| {
2706 if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
2569 2707 this.toggle_mark(MarkKind::Strike, cx);
2570 2708 }
2571 2709 }))
2572 .on_action(cx.listener(|this, _: &ToggleSuperscript, _, cx| {
2573 if this.link_editor.is_none() {
2710 .on_action(cx.listener(|this, _: &ToggleSuperscript, window, cx| {
2711 if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
2574 2712 this.toggle_mark(MarkKind::Superscript, cx);
2575 2713 }
2576 2714 }))
2577 .on_action(cx.listener(|this, _: &ToggleSubscript, _, cx| {
2578 if this.link_editor.is_none() {
2715 .on_action(cx.listener(|this, _: &ToggleSubscript, window, cx| {
2716 if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
2579 2717 this.toggle_mark(MarkKind::Subscript, cx);
2580 2718 }
2581 2719 }))
2582 .on_action(cx.listener(|this, _: &ToggleCode, _, cx| {
2583 if this.link_editor.is_none() {
2720 .on_action(cx.listener(|this, _: &ToggleCode, window, cx| {
2721 if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
2584 2722 this.toggle_mark(MarkKind::Code, cx);
2585 2723 }
2586 2724 }))
2587 .on_action(cx.listener(|this, _: &EditLink, window, cx| this.edit_link(window, cx)))
2725 .on_action(cx.listener(|this, _: &EditLink, window, cx| {
2726 if !this.cell_has_focus(window, cx) {
2727 this.edit_link(window, cx);
2728 }
2729 }))
2730 .on_action(
2731 cx.listener(|this, _: &PastePlainText, window, cx| this.paste_plain(window, cx)),
2732 )
2733 .on_action(cx.listener(|this, _: &InsertTableRowAbove, window, cx| {
2734 this.edit_table(TableEdit::InsertRowAbove, window, cx)
2735 }))
2736 .on_action(cx.listener(|this, _: &InsertTableRowBelow, window, cx| {
2737 this.edit_table(TableEdit::InsertRowBelow, window, cx)
2738 }))
2739 .on_action(cx.listener(|this, _: &InsertTableColumnLeft, window, cx| {
2740 this.edit_table(TableEdit::InsertColumnLeft, window, cx)
2741 }))
2742 .on_action(cx.listener(|this, _: &InsertTableColumnRight, window, cx| {
2743 this.edit_table(TableEdit::InsertColumnRight, window, cx)
2744 }))
2745 .on_action(cx.listener(|this, _: &DeleteTableRow, window, cx| {
2746 this.edit_table(TableEdit::DeleteRow, window, cx)
2747 }))
2748 .on_action(cx.listener(|this, _: &DeleteTableColumn, window, cx| {
2749 this.edit_table(TableEdit::DeleteColumn, window, cx)
2750 }))
2751 .on_action(cx.listener(|this, _: &DeleteTable, window, cx| {
2752 this.edit_table(TableEdit::DeleteTable, window, cx)
2753 }))
2588 2754 .on_action(cx.listener(|this, _: &ScheduleSend, _, cx| this.open_schedule_picker(cx)))
2589 2755 .capture_action(cx.listener(|this, _: &Undo, window, cx| {
2590 2756 if this.link_editor.is_none() {
@@ -2598,20 +2764,30 @@ impl Render for Composer {
2598 2764 cx.stop_propagation();
2599 2765 }
2600 2766 }))
2601 .capture_action(cx.listener(|this, _: &Copy, _, cx| {
2602 if this.link_editor.is_none() && this.copy_selection(cx) {
2767 .capture_action(cx.listener(|this, _: &Copy, window, cx| {
2768 if this.link_editor.is_none()
2769 && !this.cell_has_focus(window, cx)
2770 && this.copy_selection(cx)
2771 {
2603 2772 cx.stop_propagation();
2604 2773 }
2605 2774 }))
2606 2775 .capture_action(cx.listener(|this, _: &Cut, window, cx| {
2607 if this.link_editor.is_none() && this.copy_selection(cx) {
2776 if this.link_editor.is_none()
2777 && !this.cell_has_focus(window, cx)
2778 && this.copy_selection(cx)
2779 {
2608 2780 this.input
2609 2781 .update(cx, |state, cx| state.replace("", window, cx));
2610 2782 cx.stop_propagation();
2611 2783 }
2612 2784 }))
2613 2785 .capture_action(cx.listener(|this, _: &MoveUp, window, cx| {
2614 if this.link_editor.is_some() {
2786 if this.cell_has_focus(window, cx) {
2787 if this.table_key(TableKey::Up, window, cx) {
2788 cx.stop_propagation();
2789 }
2790 } else if this.link_editor.is_some() {
2615 2791 } else if this.schedule.is_some() {
2616 2792 this.move_schedule_highlight(-1, window, cx);
2617 2793 cx.stop_propagation();
@@ -2624,17 +2800,32 @@ impl Render for Composer {
2624 2800 }
2625 2801 }))
2626 2802 .capture_action(cx.listener(|this, _: &MoveDown, window, cx| {
2627 if this.link_editor.is_some() {
2803 if this.cell_has_focus(window, cx) {
2804 if this.table_key(TableKey::Down, window, cx) {
2805 cx.stop_propagation();
2806 }
2807 } else if this.link_editor.is_some() {
2628 2808 } else if this.schedule.is_some() {
2629 2809 this.move_schedule_highlight(1, window, cx);
2630 2810 cx.stop_propagation();
2631 2811 } else if this.popup_is_open() {
2632 2812 this.move_highlight(1, cx);
2633 2813 cx.stop_propagation();
2814 } else if this.leave_quote(window, cx) {
2815 cx.stop_propagation();
2816 }
2817 }))
2818 .capture_action(cx.listener(|this, _: &MoveRight, window, cx| {
2819 if this.link_editor.is_none()
2820 && !this.cell_has_focus(window, cx)
2821 && this.leave_quote(window, cx)
2822 {
2823 cx.stop_propagation();
2634 2824 }
2635 2825 }))
2636 2826 .capture_action(cx.listener(|this, action: &Enter, window, cx| {
2637 if this.link_editor.is_some() {
2827 if this.cell_has_focus(window, cx) {
2828 } else if this.link_editor.is_some() {
2638 2829 this.apply_link(window, cx);
2639 2830 cx.stop_propagation();
2640 2831 } else if this.schedule.is_some() {
@@ -2648,7 +2839,9 @@ impl Render for Composer {
2648 2839 }
2649 2840 }))
2650 2841 .capture_action(cx.listener(|this, _: &IndentInline, window, cx| {
2651 if this.link_editor.is_some() {
2842 if this.table_key(TableKey::Next, window, cx) {
2843 cx.stop_propagation();
2844 } else if this.link_editor.is_some() {
2652 2845 } else if this.popup_is_open() {
2653 2846 this.accept_popup(window, cx);
2654 2847 cx.stop_propagation();
@@ -2657,23 +2850,37 @@ impl Render for Composer {
2657 2850 }
2658 2851 }))
2659 2852 .capture_action(cx.listener(|this, _: &OutdentInline, window, cx| {
2660 if this.link_editor.is_none() && this.indent(true, window, cx) {
2853 if this.table_key(TableKey::Previous, window, cx)
2854 || (this.link_editor.is_none() && this.indent(true, window, cx))
2855 {
2661 2856 cx.stop_propagation();
2662 2857 }
2663 2858 }))
2664 2859 .capture_action(cx.listener(|this, _: &Backspace, window, cx| {
2665 2860 if this.link_editor.is_none()
2666 && (this.undo_conversion(window, cx) || this.backspace_at_start(window, cx))
2861 && !this.cell_has_focus(window, cx)
2862 && (this.undo_conversion(window, cx)
2863 || this.backspace_at_start(window, cx)
2864 || this.enter_table_beside(true, window, cx))
2667 2865 {
2668 2866 cx.stop_propagation();
2669 2867 }
2670 2868 }))
2671 2869 .capture_action(cx.listener(|this, _: &Delete, window, cx| {
2672 if this.link_editor.is_none() && this.delete_forward(window, cx) {
2870 if this.link_editor.is_none()
2871 && !this.cell_has_focus(window, cx)
2872 && (this.enter_table_beside(false, window, cx)
2873 || this.delete_forward(window, cx))
2874 {
2673 2875 cx.stop_propagation();
2674 2876 }
2675 2877 }))
2676 2878 .capture_action(cx.listener(|this, _: &Escape, window, cx| {
2879 if this.table_picker.take().is_some() {
2880 cx.notify();
2881 cx.stop_propagation();
2882 return;
2883 }
2677 2884 if this.schedule.is_some() {
2678 2885 this.close_schedule(window, cx);
2679 2886 cx.stop_propagation();
@@ -2715,8 +2922,10 @@ impl Render for Composer {
2715 2922 .children(self.render_emoji_popup(window, cx))
2716 2923 .children(self.render_toolbar(focused, cx))
2717 2924 .children(self.render_schedule(cx))
2925 .children(self.render_table_picker(cx))
2718 2926 .child(
2719 2927 v_flex()
2928 .debug_selector(|| COMPOSER_BOX_TAG.into())
2720 2929 .relative()
2721 2930 .w_full()
2722 2931 .rounded(px(12.))
@@ -2746,16 +2955,22 @@ impl Render for Composer {
2746 2955 row.items_end()
2747 2956 }
2748 2957 })
2749 .py(px(6.))
2750 .pl(px(if can_attach { 6. } else { 12. }))
2751 .pr(px(6.))
2958 .py(px(COMPOSER_BUTTON_INSET))
2959 .pl(px(if can_attach {
2960 COMPOSER_BUTTON_INSET
2961 } else {
2962 12.
2963 }))
2964 .pr(px(COMPOSER_BUTTON_INSET))
2752 2965 .when(can_attach, |row| {
2753 2966 row.child(
2754 2967 h_flex()
2968 .debug_selector(|| COMPOSER_LEADING_TAG.into())
2755 2969 .flex_none()
2756 .gap(px(6.))
2970 .gap(px(COMPOSER_BUTTON_INSET))
2757 2971 .children(fun)
2758 .children(attach),
2972 .children(attach)
2973 .children(table_button),
2759 2974 )
2760 2975 })
2761 2976 .child(
@@ -2925,7 +3140,10 @@ mod tests {
2925 3140 })
2926 3141 }
2927 3142
2928 fn outgoing_with(text: &str, images: Vec<crate::outgoing::OutgoingImage>) -> crate::outgoing::Outgoing {
3143 fn outgoing_with(
3144 text: &str,
3145 images: Vec<crate::outgoing::OutgoingImage>,
3146 ) -> crate::outgoing::Outgoing {
2929 3147 crate::outgoing::Outgoing {
2930 3148 draft: teams_core::Draft::plain(text),
2931 3149 subject: None,
@@ -2983,7 +3201,10 @@ mod tests {
2983 3201 #[test]
2984 3202 fn a_sticker_carries_the_sticker_itemtype() {
2985 3203 let sticker = super::RemoteImage::sticker(crate::stickers::popular()[0]);
2986 let outgoing = outgoing_with("\u{FFFC}", vec![crate::outgoing::OutgoingImage::Remote(sticker)]);
3204 let outgoing = outgoing_with(
3205 "\u{FFFC}",
3206 vec![crate::outgoing::OutgoingImage::Remote(sticker)],
3207 );
2987 3208 assert!(
2988 3209 outgoing
2989 3210 .html()
@@ -3394,7 +3615,9 @@ mod tests {
3394 3615 excerpt: "question".into(),
3395 3616 };
3396 3617 typist.act(|_, cx| {
3397 composer.update(cx, |composer, cx| composer.set_reply(Some(reply.clone()), cx));
3618 composer.update(cx, |composer, cx| {
3619 composer.set_reply(Some(reply.clone()), cx)
3620 });
3398 3621 });
3399 3622 load(&mut typist, &entry);
3400 3623 let tokens = image_tokens(&mut typist);
@@ -3990,7 +4213,7 @@ mod tests {
3990 4213 #[gpui_kit::test]
3991 4214 fn quotes_continue_on_shift_enter_and_send_as_blockquote(cx: &mut TestAppContext) {
3992 4215 let mut typist = typist(cx);
3993 typist.type_text("> quoted");
4216 typist.type_text(">quoted");
3994 4217 typist.press("shift-enter");
3995 4218 typist.type_text("more");
3996 4219 let outgoing = typist.outgoing();
@@ -3998,6 +4221,112 @@ mod tests {
3998 4221 assert_eq!(outgoing.text(), "quoted\nmore");
3999 4222 }
4000 4223
4224 #[gpui_kit::test]
4225 fn enter_in_a_quote_adds_a_line_and_enter_on_the_empty_one_leaves_it(
4226 cx: &mut TestAppContext,
4227 ) {
4228 let mut typist = typist(cx);
4229 typist.type_text(">quoted");
4230 typist.press("enter");
4231 typist.type_text("more");
4232 typist.press("enter enter");
4233 typist.type_text("after");
4234 assert_eq!(typist.value(), "quoted\nmore\nafter");
4235 assert_eq!(
4236 typist.outgoing().html(),
4237 "<blockquote>quoted<br>more</blockquote>after"
4238 );
4239 }
4240
4241 #[gpui_kit::test]
4242 fn down_at_the_end_of_a_quote_leaves_it(cx: &mut TestAppContext) {
4243 let mut typist = typist(cx);
4244 typist.type_text(">quoted");
4245 typist.press("down");
4246 typist.type_text("after");
4247 assert_eq!(
4248 typist.outgoing().html(),
4249 "<blockquote>quoted</blockquote>after"
4250 );
4251 }
4252
4253 fn insert_table(typist: &mut Typist<'_>, rows: usize, columns: usize) {
4254 let composer = typist.composer.clone();
4255 typist.act(|window, cx| {
4256 composer.update(cx, |composer, cx| {
4257 composer.insert_table(rows, columns, window, cx)
4258 });
4259 window.render_frame(cx);
4260 });
4261 }
4262
4263 #[gpui_kit::test]
4264 fn a_table_takes_tab_grows_a_row_at_the_end_and_sends_as_teams_html(
4265 cx: &mut TestAppContext,
4266 ) {
4267 let mut typist = typist(cx);
4268 typist.type_text("before");
4269 insert_table(&mut typist, 1, 2);
4270 typist.type_text("a");
4271 typist.press("tab");
4272 typist.type_text("b");
4273 typist.press("tab");
4274 typist.act(|window, cx| window.render_frame(cx));
4275 typist.type_text("c");
4276 typist.press("down");
4277 typist.type_text("after");
4278 assert_eq!(
4279 typist.outgoing().html(),
4280 "before<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\
4281 <tr><td>a</td><td>b</td></tr><tr><td>c</td><td>&nbsp;</td></tr>\
4282 </tbody></table></figure>after"
4283 );
4284 }
4285
4286 #[gpui_kit::test]
4287 fn deleting_the_last_column_deletes_the_table(cx: &mut TestAppContext) {
4288 let mut typist = typist(cx);
4289 insert_table(&mut typist, 1, 1);
4290 let composer = typist.composer.clone();
4291 typist.act(|window, cx| {
4292 composer.update(cx, |composer, cx| {
4293 composer.edit_table(teams_core::TableEdit::DeleteColumn, window, cx)
4294 });
4295 });
4296 assert!(typist.draft().lines().iter().all(|kind| !kind.is_table()));
4297 }
4298
4299 #[gpui_kit::test]
4300 fn a_pasted_markdown_table_becomes_a_table(cx: &mut TestAppContext) {
4301 let mut typist = typist(cx);
4302 typist
4303 .cx
4304 .write_to_clipboard(gpui_kit::ClipboardItem::new_string(
4305 "| A | B |\n|---|---|\n| 1 | 2 |".to_owned(),
4306 ));
4307 typist.press("ctrl-v");
4308 assert!(typist.draft().lines()[0].is_table());
4309 assert_eq!(
4310 typist.outgoing().html(),
4311 "<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\
4312 <tr><td>A</td><td>B</td></tr><tr><td>1</td><td>2</td></tr>\
4313 </tbody></table></figure>"
4314 );
4315 }
4316
4317 #[gpui_kit::test]
4318 fn ctrl_shift_v_pastes_markdown_as_plain_text(cx: &mut TestAppContext) {
4319 let mut typist = typist(cx);
4320 typist
4321 .cx
4322 .write_to_clipboard(gpui_kit::ClipboardItem::new_string(
4323 "**hi** there".to_owned(),
4324 ));
4325 typist.press("ctrl-shift-v");
4326 assert_eq!(typist.value(), "**hi** there");
4327 assert!(typist.draft().marks().is_empty());
4328 }
4329
4001 4330 #[gpui_kit::test]
4002 4331 fn demo_upload_runs_to_done_and_a_file_alone_can_be_sent(cx: &mut TestAppContext) {
4003 4332 cx.update(gpui_kit::init);
@@ -13,8 +13,9 @@ use gpui_kit::component::{
13 h_flex,
13 h_flex,
14 input::{
14 input::{
15 Backspace, Copy, Cut, Delete, Enter, Escape, IndentInline, InlineToken, InputContent,
15 Backspace, Copy, Cut, Delete, Enter, Escape, IndentInline, InlineToken, InputContent,
16 InputEvent, InputState, MoveDown, MoveUp, OutdentInline, RangeDecorationCollection, Redo,
16 InputEvent, InputState, MoveDown, MoveRight, MoveUp, OutdentInline,
17 TextDecorationCollection, Textarea, TextareaMode, TextareaState, Undo,
17 RangeDecorationCollection, Redo, TextDecorationCollection, Textarea, TextareaMode,
18 TextareaState, Undo,
18 },
19 },
19 popover::Popover,
20 popover::Popover,
20 tooltip::Tooltip,
21 tooltip::Tooltip,
@@ -24,21 +25,24 @@ use gpui_kit::prelude::FluentBuilder as _;
24use gpui_kit::*;
25use gpui_kit::*;
25use teams_core::{
26use 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
31mod drafts;
32mod drafts;
32mod schedule;
33mod schedule;
34mod table;
33
35
34use super::actions::{
36use 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};
38use super::attachment_tray::{
42use 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};
43use super::avatar::{person_avatar, square_avatar};
47use super::avatar::{person_avatar, square_avatar};
44use super::draft_style::draft_style;
48use super::draft_style::draft_style;
@@ -55,6 +59,7 @@ use crate::runtime;
55use crate::scheduled_rows::scheduled_label;
59use crate::scheduled_rows::scheduled_label;
56use crate::theme::{self, ElevatedSurface as _};
60use crate::theme::{self, ElevatedSurface as _};
57use crate::typing::OutgoingTyping;
61use crate::typing::OutgoingTyping;
62use table::{TableKey, TablePicker, TableViews, is_table_token};
58
63
59const MIN_ROWS: usize = 1;
64const MIN_ROWS: usize = 1;
60const MAX_ROWS: usize = 8;
65const MAX_ROWS: usize = 8;
@@ -67,6 +72,11 @@ const POPUP_WIDTH: f32 = 380.;
67const POPUP_ROW_HEIGHT: f32 = 44.;
72const POPUP_ROW_HEIGHT: f32 = 44.;
68const DEMO_UPLOAD_STEPS: u8 = 10;
73const DEMO_UPLOAD_STEPS: u8 = 10;
69const COMPOSER_ICON_SIZE: f32 = 20.;
74const COMPOSER_ICON_SIZE: f32 = 20.;
75const COMPOSER_BUTTON_SIZE: f32 = 32.;
76const COMPOSER_BUTTON_INSET: f32 = 6.;
77pub const COMPOSER_BOX_TAG: &str = "composer";
78pub const COMPOSER_LEADING_TAG: &str = "composer/leading";
79pub const COMPOSER_SEND_TAG: &str = "composer/send";
70/// gpui-kit draws a `Size::Size` button's icon at this fraction of the button size.
80/// gpui-kit draws a `Size::Size` button's icon at this fraction of the button size.
71const BUTTON_ICON_SCALE: f32 = 0.75;
81const BUTTON_ICON_SCALE: f32 = 0.75;
72const DEMO_UPLOAD_STEP: Duration = Duration::from_millis(120);
82const DEMO_UPLOAD_STEP: Duration = Duration::from_millis(120);
@@ -126,8 +136,19 @@ struct Conversion {
126
136
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
137#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128enum StepKind {
138enum StepKind {
129 Typing { at: usize, after_space: bool },
139 Typing {
130 Deleting { start: usize, end: usize },
140 at: usize,
141 after_space: bool,
142 },
143 Deleting {
144 start: usize,
145 end: usize,
146 },
147 CellTyping {
148 table: usize,
149 row: usize,
150 column: usize,
151 },
131 Other,
152 Other,
132}
153}
133
154
@@ -192,6 +213,12 @@ pub struct Composer {
192 pending_anchors: HashMap<u64, usize>,
213 pending_anchors: HashMap<u64, usize>,
193 link: ComposeLink,
214 link: ComposeLink,
194 fun_picker: Entity<FunPicker>,
215 fun_picker: Entity<FunPicker>,
216 tables: TableViews,
217 table_counter: usize,
218 table_picker: Option<TablePicker>,
219 active_cell: Option<(String, teams_core::Cell)>,
220 caret_before_table: usize,
221 caret_text: String,
195 _subscriptions: [Subscription; 4],
222 _subscriptions: [Subscription; 4],
196}
223}
197
224
@@ -292,6 +319,9 @@ fn continues(last: &HistoryStep, kind: StepKind) -> bool {
292 (StepKind::Deleting { .. }, StepKind::Deleting { start, end }) => {
319 (StepKind::Deleting { .. }, StepKind::Deleting { start, end }) => {
293 caret.is_empty() && (caret.start == end || caret.start == start)
320 caret.is_empty() && (caret.start == end || caret.start == start)
294 }
321 }
322 (previous @ StepKind::CellTyping { .. }, next @ StepKind::CellTyping { .. }) => {
323 previous == next
324 }
295 _ => false,
325 _ => false,
296 }
326 }
297}
327}
@@ -328,7 +358,10 @@ impl Composer {
328 .placeholder("Type a message")
358 .placeholder("Type a message")
329 });
359 });
330 let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
360 let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
331 let observer = cx.observe(&input, |_, _, cx| cx.notify());
361 let observer = cx.observe_in(&input, window, |this, _, window, cx| {
362 this.redirect_caret_from_table(window, cx);
363 cx.notify();
364 });
332 let image_observer = cx.observe(&app, |this, _, cx| {
365 let image_observer = cx.observe(&app, |this, _, cx| {
333 if this.link_image_pending(cx) {
366 if this.link_image_pending(cx) {
334 cx.notify();
367 cx.notify();
@@ -389,6 +422,12 @@ impl Composer {
389 pending_anchors: HashMap::new(),
422 pending_anchors: HashMap::new(),
390 link: ComposeLink::default(),
423 link: ComposeLink::default(),
391 fun_picker,
424 fun_picker,
425 tables: TableViews::default(),
426 table_counter: 0,
427 table_picker: None,
428 active_cell: None,
429 caret_before_table: 0,
430 caret_text: String::new(),
392 _subscriptions: [subscription, observer, image_observer, picker_subscription],
431 _subscriptions: [subscription, observer, image_observer, picker_subscription],
393 }
432 }
394 }
433 }
@@ -640,6 +679,7 @@ impl Composer {
640 }
679 }
641 self.previous_value = value;
680 self.previous_value = value;
642 self.refresh_style(cx);
681 self.refresh_style(cx);
682 self.sync_tables(window, cx);
643 }
683 }
644
684
645 fn shift_anchors(&mut self, start: usize, old_end: usize, new_end: usize) {
685 fn shift_anchors(&mut self, start: usize, old_end: usize, new_end: usize) {
@@ -737,6 +777,7 @@ impl Composer {
737 self.conversion = None;
777 self.conversion = None;
738 self.paste_hint = None;
778 self.paste_hint = None;
739 self.refresh_style(cx);
779 self.refresh_style(cx);
780 self.sync_tables(window, cx);
740 self.update_emoji(cx);
781 self.update_emoji(cx);
741 self.update_mention(cx);
782 self.update_mention(cx);
742 self.schedule_draft_save(cx);
783 self.schedule_draft_save(cx);
@@ -775,6 +816,9 @@ impl Composer {
775 self.link_editor = None;
816 self.link_editor = None;
776 self.toolbar_dismissed = None;
817 self.toolbar_dismissed = None;
777 self.pending_anchors.clear();
818 self.pending_anchors.clear();
819 self.active_cell = None;
820 self.table_picker = None;
821 self.sync_tables(window, cx);
778 self.history.clear();
822 self.history.clear();
779 self.history_index = 0;
823 self.history_index = 0;
780 self.record(StepKind::Other, cx);
824 self.record(StepKind::Other, cx);
@@ -1064,6 +1108,64 @@ impl Composer {
1064 }
1108 }
1065 }
1109 }
1066
1110
1111 fn leave_quote(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
1112 let selection = self.selection(cx);
1113 if !selection.is_empty() || self.input.read(cx).value().as_ref() != self.draft.text() {
1114 return false;
1115 }
1116 match self.draft.leave_quote_at_end(selection.start) {
1117 Some(cursor) => {
1118 self.commit(Some(cursor), window, cx);
1119 true
1120 }
1121 None => false,
1122 }
1123 }
1124
1125 /// Backspace right after a table or Delete right before one goes into it instead of
1126 /// joining the line with the table's.
1127 fn enter_table_beside(
1128 &mut self,
1129 after: bool,
1130 window: &mut Window,
1131 cx: &mut Context<Self>,
1132 ) -> bool {
1133 let selection = self.selection(cx);
1134 if !selection.is_empty() || self.input.read(cx).value().as_ref() != self.draft.text() {
1135 return false;
1136 }
1137 let found = if after {
1138 self.draft.table_before(selection.start)
1139 } else {
1140 self.draft.table_after(selection.start)
1141 };
1142 let Some(index) = found else {
1143 return false;
1144 };
1145 self.focus_table_line(index, after, window, cx);
1146 true
1147 }
1148
1149 fn cell_has_focus(&self, window: &Window, cx: &App) -> bool {
1150 self.focused_cell(window, cx).is_some()
1151 }
1152
1153 fn paste_plain(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1154 let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) else {
1155 return;
1156 };
1157 let text = text
1158 .replace("\r\n", "\n")
1159 .replace([OBJECT_MARK, TABLE_MARK], "");
1160 if let Some(input) = self.focused_cell_input(window, cx) {
1161 input.update(cx, |state, cx| state.replace(text, window, cx));
1162 return;
1163 }
1164 self.pasted_markdown = None;
1165 self.input
1166 .update(cx, |state, cx| state.replace(text, window, cx));
1167 }
1168
1067 fn indent(&mut self, outdent: bool, window: &mut Window, cx: &mut Context<Self>) -> bool {
1169 fn indent(&mut self, outdent: bool, window: &mut Window, cx: &mut Context<Self>) -> bool {
1068 let selection = self.selection(cx);
1170 let selection = self.selection(cx);
1069 if !self.draft.indent(selection, outdent) {
1171 if !self.draft.indent(selection, outdent) {
@@ -1079,12 +1181,16 @@ impl Composer {
1079 return false;
1181 return false;
1080 }
1182 }
1081 let selected = &self.draft.text()[selection.clone()];
1183 let selected = &self.draft.text()[selection.clone()];
1082 let text = selected.replace(OBJECT_MARK, "");
1083 let lines = if selected.contains(OBJECT_MARK) {
1184 let lines = if selected.contains(OBJECT_MARK) {
1084 self.draft.slice_without_objects(selection)
1185 self.draft.slice_without_objects(selection)
1085 } else {
1186 } else {
1086 self.draft.slice(selection)
1187 self.draft.slice(selection)
1087 };
1188 };
1189 let text = if selected.contains(TABLE_MARK) {
1190 Draft::from_lines(&lines).plain_text()
1191 } else {
1192 selected.replace(OBJECT_MARK, "")
1193 };
1088 if text.is_empty() {
1194 if text.is_empty() {
1089 return true;
1195 return true;
1090 }
1196 }
@@ -1150,8 +1256,8 @@ impl Composer {
1150 }
1256 }
1151 let matches = emoji::search(&query, &self.recent_emoji.glyphs(), emoji_popup::LIMIT);
1257 let matches = emoji::search(&query, &self.recent_emoji.glyphs(), emoji_popup::LIMIT);
1152 let skin_tone = teams_core::skin_tone(&self.app.read(cx).store);
1258 let skin_tone = teams_core::skin_tone(&self.app.read(cx).store);
1153 self.emoji_popup = (!matches.is_empty())
1259 self.emoji_popup =
1154 .then(|| EmojiPopup::new(range, query, matches, skin_tone));
1260 (!matches.is_empty()).then(|| EmojiPopup::new(range, query, matches, skin_tone));
1155 }
1261 }
1156
1262
1157 fn accept_emoji(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1263 fn accept_emoji(&mut self, window: &mut Window, cx: &mut Context<Self>) {
@@ -1764,8 +1870,8 @@ impl Composer {
1764 let Some(text) = item.text() else {
1870 let Some(text) = item.text() else {
1765 return false;
1871 return false;
1766 };
1872 };
1767 if text.contains(OBJECT_MARK) {
1873 if text.contains([OBJECT_MARK, TABLE_MARK]) {
1768 let cleaned = text.replace(OBJECT_MARK, "");
1874 let cleaned = text.replace([OBJECT_MARK, TABLE_MARK], "");
1769 self.input
1875 self.input
1770 .update(cx, |state, cx| state.replace(cleaned, window, cx));
1876 .update(cx, |state, cx| state.replace(cleaned, window, cx));
1771 return true;
1877 return true;
@@ -2107,6 +2213,7 @@ impl Composer {
2107 .mx(px(6.))
2213 .mx(px(6.))
2108 .px(px(6.))
2214 .px(px(6.))
2109 .h(px(POPUP_ROW_HEIGHT))
2215 .h(px(POPUP_ROW_HEIGHT))
2216 .flex_none()
2110 .gap(px(8.))
2217 .gap(px(8.))
2111 .items_center()
2218 .items_center()
2112 .rounded(px(6.))
2219 .rounded(px(6.))
@@ -2396,8 +2503,9 @@ impl Render for Composer {
2396 let can_attach = self.editing.is_none();
2503 let can_attach = self.editing.is_none();
2397 let send = div()
2504 let send = div()
2398 .id("composer-send")
2505 .id("composer-send")
2399 .size(px(32.))
2506 .debug_selector(|| COMPOSER_SEND_TAG.into())
2400 .ml(px(6.))
2507 .size(px(COMPOSER_BUTTON_SIZE))
2508 .ml(px(COMPOSER_BUTTON_INSET))
2401 .flex_none()
2509 .flex_none()
2402 .flex()
2510 .flex()
2403 .items_center()
2511 .items_center()
@@ -2431,7 +2539,7 @@ impl Render for Composer {
2431 )
2539 )
2432 .rounded(px(8.))
2540 .rounded(px(8.))
2433 .with_size(px(COMPOSER_ICON_SIZE / BUTTON_ICON_SCALE))
2541 .with_size(px(COMPOSER_ICON_SIZE / BUTTON_ICON_SCALE))
2434 .size(px(32.))
2542 .size(px(COMPOSER_BUTTON_SIZE))
2435 .tooltip("Emoji, GIFs und Sticker")
2543 .tooltip("Emoji, GIFs und Sticker")
2436 .icon(symbol("mood", COMPOSER_ICON_SIZE, theme::text_muted())),
2544 .icon(symbol("mood", COMPOSER_ICON_SIZE, theme::text_muted())),
2437 )
2545 )
@@ -2449,7 +2557,7 @@ impl Render for Composer {
2449 let attach = can_attach.then(|| {
2557 let attach = can_attach.then(|| {
2450 div()
2558 div()
2451 .id("composer-attach")
2559 .id("composer-attach")
2452 .size(px(32.))
2560 .size(px(COMPOSER_BUTTON_SIZE))
2453 .flex_none()
2561 .flex_none()
2454 .flex()
2562 .flex()
2455 .items_center()
2563 .items_center()
@@ -2465,9 +2573,28 @@ impl Render for Composer {
2465 ))
2573 ))
2466 .on_click(cx.listener(|this, _, window, cx| this.open_picker(window, cx)))
2574 .on_click(cx.listener(|this, _, window, cx| this.open_picker(window, cx)))
2467 });
2575 });
2576 let table_button = can_attach.then(|| {
2577 div()
2578 .id("composer-table")
2579 .size(px(COMPOSER_BUTTON_SIZE))
2580 .flex_none()
2581 .flex()
2582 .items_center()
2583 .justify_center()
2584 .rounded(px(8.))
2585 .cursor_pointer()
2586 .hover(|button| button.bg(theme::popup_hover()))
2587 .when(self.table_picker.is_some(), |button| {
2588 button.bg(theme::popup_hover())
2589 })
2590 .tooltip(|window, cx| Tooltip::new("Insert table").build(window, cx))
2591 .child(symbol("table", COMPOSER_ICON_SIZE, theme::text_muted()))
2592 .on_click(cx.listener(|this, _, _, cx| this.open_table_picker(cx)))
2593 });
2468 let composer = cx.weak_entity();
2594 let composer = cx.weak_entity();
2469 let tokens_composer = composer.clone();
2595 let tokens_composer = composer.clone();
2470 let input = Textarea::new(&self.input)
2596 let input = Textarea::new(&self.input)
2597 .line_box_height(px(COMPOSER_BUTTON_SIZE))
2471 .appearance(false)
2598 .appearance(false)
2472 .bordered(false)
2599 .bordered(false)
2473 .on_paste(move |item, window, cx| {
2600 .on_paste(move |item, window, cx| {
@@ -2476,6 +2603,17 @@ impl Render for Composer {
2476 .unwrap_or(false)
2603 .unwrap_or(false)
2477 })
2604 })
2478 .token(move |context, _, cx| {
2605 .token(move |context, _, cx| {
2606 if context.is_block() && is_table_token(context.token()) {
2607 let token_id = context.token().id().to_string();
2608 let width = context.available_width();
2609 if let Some(table) = tokens_composer
2610 .read_with(cx, |this, _| this.render_table_token(&token_id, width))
2611 .ok()
2612 .flatten()
2613 {
2614 return table;
2615 }
2616 }
2479 if let Some(id) = context
2617 if let Some(id) = context
2480 .is_block()
2618 .is_block()
2481 .then(|| image_id(context.token()))
2619 .then(|| image_id(context.token()))
@@ -2549,42 +2687,70 @@ impl Render for Composer {
2549 .pt(px(top))
2687 .pt(px(top))
2550 .pb(px(bottom))
2688 .pb(px(bottom))
2551 .key_context(COMPOSER_KEY_CONTEXT)
2689 .key_context(COMPOSER_KEY_CONTEXT)
2552 .on_action(cx.listener(|this, _: &ToggleBold, _, cx| {
2690 .on_action(cx.listener(|this, _: &ToggleBold, window, cx| {
2553 if this.link_editor.is_none() {
2691 if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
2554 this.toggle_mark(MarkKind::Bold, cx);
2692 this.toggle_mark(MarkKind::Bold, cx);
2555 }
2693 }
2556 }))
2694 }))
2557 .on_action(cx.listener(|this, _: &ToggleItalic, _, cx| {
2695 .on_action(cx.listener(|this, _: &ToggleItalic, window, cx| {
2558 if this.link_editor.is_none() {
2696 if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
2559 this.toggle_mark(MarkKind::Italic, cx);
2697 this.toggle_mark(MarkKind::Italic, cx);
2560 }
2698 }
2561 }))
2699 }))
2562 .on_action(cx.listener(|this, _: &ToggleUnderline, _, cx| {
2700 .on_action(cx.listener(|this, _: &ToggleUnderline, window, cx| {
2563 if this.link_editor.is_none() {
2701 if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
2564 this.toggle_mark(MarkKind::Underline, cx);
2702 this.toggle_mark(MarkKind::Underline, cx);
2565 }
2703 }
2566 }))
2704 }))
2567 .on_action(cx.listener(|this, _: &ToggleStrike, _, cx| {
2705 .on_action(cx.listener(|this, _: &ToggleStrike, window, cx| {
2568 if this.link_editor.is_none() {
2706 if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
2569 this.toggle_mark(MarkKind::Strike, cx);
2707 this.toggle_mark(MarkKind::Strike, cx);
2570 }
2708 }
2571 }))
2709 }))
2572 .on_action(cx.listener(|this, _: &ToggleSuperscript, _, cx| {
2710 .on_action(cx.listener(|this, _: &ToggleSuperscript, window, cx| {
2573 if this.link_editor.is_none() {
2711 if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
2574 this.toggle_mark(MarkKind::Superscript, cx);
2712 this.toggle_mark(MarkKind::Superscript, cx);
2575 }
2713 }
2576 }))
2714 }))
2577 .on_action(cx.listener(|this, _: &ToggleSubscript, _, cx| {
2715 .on_action(cx.listener(|this, _: &ToggleSubscript, window, cx| {
2578 if this.link_editor.is_none() {
2716 if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
2579 this.toggle_mark(MarkKind::Subscript, cx);
2717 this.toggle_mark(MarkKind::Subscript, cx);
2580 }
2718 }
2581 }))
2719 }))
2582 .on_action(cx.listener(|this, _: &ToggleCode, _, cx| {
2720 .on_action(cx.listener(|this, _: &ToggleCode, window, cx| {
2583 if this.link_editor.is_none() {
2721 if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
2584 this.toggle_mark(MarkKind::Code, cx);
2722 this.toggle_mark(MarkKind::Code, cx);
2585 }
2723 }
2586 }))
2724 }))
2587 .on_action(cx.listener(|this, _: &EditLink, window, cx| this.edit_link(window, cx)))
2725 .on_action(cx.listener(|this, _: &EditLink, window, cx| {
2726 if !this.cell_has_focus(window, cx) {
2727 this.edit_link(window, cx);
2728 }
2729 }))
2730 .on_action(
2731 cx.listener(|this, _: &PastePlainText, window, cx| this.paste_plain(window, cx)),
2732 )
2733 .on_action(cx.listener(|this, _: &InsertTableRowAbove, window, cx| {
2734 this.edit_table(TableEdit::InsertRowAbove, window, cx)
2735 }))
2736 .on_action(cx.listener(|this, _: &InsertTableRowBelow, window, cx| {
2737 this.edit_table(TableEdit::InsertRowBelow, window, cx)
2738 }))
2739 .on_action(cx.listener(|this, _: &InsertTableColumnLeft, window, cx| {
2740 this.edit_table(TableEdit::InsertColumnLeft, window, cx)
2741 }))
2742 .on_action(cx.listener(|this, _: &InsertTableColumnRight, window, cx| {
2743 this.edit_table(TableEdit::InsertColumnRight, window, cx)
2744 }))
2745 .on_action(cx.listener(|this, _: &DeleteTableRow, window, cx| {
2746 this.edit_table(TableEdit::DeleteRow, window, cx)
2747 }))
2748 .on_action(cx.listener(|this, _: &DeleteTableColumn, window, cx| {
2749 this.edit_table(TableEdit::DeleteColumn, window, cx)
2750 }))
2751 .on_action(cx.listener(|this, _: &DeleteTable, window, cx| {
2752 this.edit_table(TableEdit::DeleteTable, window, cx)
2753 }))
2588 .on_action(cx.listener(|this, _: &ScheduleSend, _, cx| this.open_schedule_picker(cx)))
2754 .on_action(cx.listener(|this, _: &ScheduleSend, _, cx| this.open_schedule_picker(cx)))
2589 .capture_action(cx.listener(|this, _: &Undo, window, cx| {
2755 .capture_action(cx.listener(|this, _: &Undo, window, cx| {
2590 if this.link_editor.is_none() {
2756 if this.link_editor.is_none() {
@@ -2598,20 +2764,30 @@ impl Render for Composer {
2598 cx.stop_propagation();
2764 cx.stop_propagation();
2599 }
2765 }
2600 }))
2766 }))
2601 .capture_action(cx.listener(|this, _: &Copy, _, cx| {
2767 .capture_action(cx.listener(|this, _: &Copy, window, cx| {
2602 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 {
2603 cx.stop_propagation();
2772 cx.stop_propagation();
2604 }
2773 }
2605 }))
2774 }))
2606 .capture_action(cx.listener(|this, _: &Cut, window, cx| {
2775 .capture_action(cx.listener(|this, _: &Cut, window, cx| {
2607 if this.link_editor.is_none() && this.copy_selection(cx) {
2776 if this.link_editor.is_none()
2777 && !this.cell_has_focus(window, cx)
2778 && this.copy_selection(cx)
2779 {
2608 this.input
2780 this.input
2609 .update(cx, |state, cx| state.replace("", window, cx));
2781 .update(cx, |state, cx| state.replace("", window, cx));
2610 cx.stop_propagation();
2782 cx.stop_propagation();
2611 }
2783 }
2612 }))
2784 }))
2613 .capture_action(cx.listener(|this, _: &MoveUp, window, cx| {
2785 .capture_action(cx.listener(|this, _: &MoveUp, window, cx| {
2614 if this.link_editor.is_some() {
2786 if this.cell_has_focus(window, cx) {
2787 if this.table_key(TableKey::Up, window, cx) {
2788 cx.stop_propagation();
2789 }
2790 } else if this.link_editor.is_some() {
2615 } else if this.schedule.is_some() {
2791 } else if this.schedule.is_some() {
2616 this.move_schedule_highlight(-1, window, cx);
2792 this.move_schedule_highlight(-1, window, cx);
2617 cx.stop_propagation();
2793 cx.stop_propagation();
@@ -2624,17 +2800,32 @@ impl Render for Composer {
2624 }
2800 }
2625 }))
2801 }))
2626 .capture_action(cx.listener(|this, _: &MoveDown, window, cx| {
2802 .capture_action(cx.listener(|this, _: &MoveDown, window, cx| {
2627 if this.link_editor.is_some() {
2803 if this.cell_has_focus(window, cx) {
2804 if this.table_key(TableKey::Down, window, cx) {
2805 cx.stop_propagation();
2806 }
2807 } else if this.link_editor.is_some() {
2628 } else if this.schedule.is_some() {
2808 } else if this.schedule.is_some() {
2629 this.move_schedule_highlight(1, window, cx);
2809 this.move_schedule_highlight(1, window, cx);
2630 cx.stop_propagation();
2810 cx.stop_propagation();
2631 } else if this.popup_is_open() {
2811 } else if this.popup_is_open() {
2632 this.move_highlight(1, cx);
2812 this.move_highlight(1, cx);
2633 cx.stop_propagation();
2813 cx.stop_propagation();
2814 } else if this.leave_quote(window, cx) {
2815 cx.stop_propagation();
2816 }
2817 }))
2818 .capture_action(cx.listener(|this, _: &MoveRight, window, cx| {
2819 if this.link_editor.is_none()
2820 && !this.cell_has_focus(window, cx)
2821 && this.leave_quote(window, cx)
2822 {
2823 cx.stop_propagation();
2634 }
2824 }
2635 }))
2825 }))
2636 .capture_action(cx.listener(|this, action: &Enter, window, cx| {
2826 .capture_action(cx.listener(|this, action: &Enter, window, cx| {
2637 if this.link_editor.is_some() {
2827 if this.cell_has_focus(window, cx) {
2828 } else if this.link_editor.is_some() {
2638 this.apply_link(window, cx);
2829 this.apply_link(window, cx);
2639 cx.stop_propagation();
2830 cx.stop_propagation();
2640 } else if this.schedule.is_some() {
2831 } else if this.schedule.is_some() {
@@ -2648,7 +2839,9 @@ impl Render for Composer {
2648 }
2839 }
2649 }))
2840 }))
2650 .capture_action(cx.listener(|this, _: &IndentInline, window, cx| {
2841 .capture_action(cx.listener(|this, _: &IndentInline, window, cx| {
2651 if this.link_editor.is_some() {
2842 if this.table_key(TableKey::Next, window, cx) {
2843 cx.stop_propagation();
2844 } else if this.link_editor.is_some() {
2652 } else if this.popup_is_open() {
2845 } else if this.popup_is_open() {
2653 this.accept_popup(window, cx);
2846 this.accept_popup(window, cx);
2654 cx.stop_propagation();
2847 cx.stop_propagation();
@@ -2657,23 +2850,37 @@ impl Render for Composer {
2657 }
2850 }
2658 }))
2851 }))
2659 .capture_action(cx.listener(|this, _: &OutdentInline, window, cx| {
2852 .capture_action(cx.listener(|this, _: &OutdentInline, window, cx| {
2660 if this.link_editor.is_none() && this.indent(true, window, cx) {
2853 if this.table_key(TableKey::Previous, window, cx)
2854 || (this.link_editor.is_none() && this.indent(true, window, cx))
2855 {
2661 cx.stop_propagation();
2856 cx.stop_propagation();
2662 }
2857 }
2663 }))
2858 }))
2664 .capture_action(cx.listener(|this, _: &Backspace, window, cx| {
2859 .capture_action(cx.listener(|this, _: &Backspace, window, cx| {
2665 if this.link_editor.is_none()
2860 if this.link_editor.is_none()
2666 && (this.undo_conversion(window, cx) || this.backspace_at_start(window, cx))
2861 && !this.cell_has_focus(window, cx)
2862 && (this.undo_conversion(window, cx)
2863 || this.backspace_at_start(window, cx)
2864 || this.enter_table_beside(true, window, cx))
2667 {
2865 {
2668 cx.stop_propagation();
2866 cx.stop_propagation();
2669 }
2867 }
2670 }))
2868 }))
2671 .capture_action(cx.listener(|this, _: &Delete, window, cx| {
2869 .capture_action(cx.listener(|this, _: &Delete, window, cx| {
2672 if this.link_editor.is_none() && this.delete_forward(window, cx) {
2870 if this.link_editor.is_none()
2871 && !this.cell_has_focus(window, cx)
2872 && (this.enter_table_beside(false, window, cx)
2873 || this.delete_forward(window, cx))
2874 {
2673 cx.stop_propagation();
2875 cx.stop_propagation();
2674 }
2876 }
2675 }))
2877 }))
2676 .capture_action(cx.listener(|this, _: &Escape, window, cx| {
2878 .capture_action(cx.listener(|this, _: &Escape, window, cx| {
2879 if this.table_picker.take().is_some() {
2880 cx.notify();
2881 cx.stop_propagation();
2882 return;
2883 }
2677 if this.schedule.is_some() {
2884 if this.schedule.is_some() {
2678 this.close_schedule(window, cx);
2885 this.close_schedule(window, cx);
2679 cx.stop_propagation();
2886 cx.stop_propagation();
@@ -2715,8 +2922,10 @@ impl Render for Composer {
2715 .children(self.render_emoji_popup(window, cx))
2922 .children(self.render_emoji_popup(window, cx))
2716 .children(self.render_toolbar(focused, cx))
2923 .children(self.render_toolbar(focused, cx))
2717 .children(self.render_schedule(cx))
2924 .children(self.render_schedule(cx))
2925 .children(self.render_table_picker(cx))
2718 .child(
2926 .child(
2719 v_flex()
2927 v_flex()
2928 .debug_selector(|| COMPOSER_BOX_TAG.into())
2720 .relative()
2929 .relative()
2721 .w_full()
2930 .w_full()
2722 .rounded(px(12.))
2931 .rounded(px(12.))
@@ -2746,16 +2955,22 @@ impl Render for Composer {
2746 row.items_end()
2955 row.items_end()
2747 }
2956 }
2748 })
2957 })
2749 .py(px(6.))
2958 .py(px(COMPOSER_BUTTON_INSET))
2750 .pl(px(if can_attach { 6. } else { 12. }))
2959 .pl(px(if can_attach {
2751 .pr(px(6.))
2960 COMPOSER_BUTTON_INSET
2961 } else {
2962 12.
2963 }))
2964 .pr(px(COMPOSER_BUTTON_INSET))
2752 .when(can_attach, |row| {
2965 .when(can_attach, |row| {
2753 row.child(
2966 row.child(
2754 h_flex()
2967 h_flex()
2968 .debug_selector(|| COMPOSER_LEADING_TAG.into())
2755 .flex_none()
2969 .flex_none()
2756 .gap(px(6.))
2970 .gap(px(COMPOSER_BUTTON_INSET))
2757 .children(fun)
2971 .children(fun)
2758 .children(attach),
2972 .children(attach)
2973 .children(table_button),
2759 )
2974 )
2760 })
2975 })
2761 .child(
2976 .child(
@@ -2925,7 +3140,10 @@ mod tests {
2925 })
3140 })
2926 }
3141 }
2927
3142
2928 fn outgoing_with(text: &str, images: Vec<crate::outgoing::OutgoingImage>) -> crate::outgoing::Outgoing {
3143 fn outgoing_with(
3144 text: &str,
3145 images: Vec<crate::outgoing::OutgoingImage>,
3146 ) -> crate::outgoing::Outgoing {
2929 crate::outgoing::Outgoing {
3147 crate::outgoing::Outgoing {
2930 draft: teams_core::Draft::plain(text),
3148 draft: teams_core::Draft::plain(text),
2931 subject: None,
3149 subject: None,
@@ -2983,7 +3201,10 @@ mod tests {
2983 #[test]
3201 #[test]
2984 fn a_sticker_carries_the_sticker_itemtype() {
3202 fn a_sticker_carries_the_sticker_itemtype() {
2985 let sticker = super::RemoteImage::sticker(crate::stickers::popular()[0]);
3203 let sticker = super::RemoteImage::sticker(crate::stickers::popular()[0]);
2986 let outgoing = outgoing_with("\u{FFFC}", vec![crate::outgoing::OutgoingImage::Remote(sticker)]);
3204 let outgoing = outgoing_with(
3205 "\u{FFFC}",
3206 vec![crate::outgoing::OutgoingImage::Remote(sticker)],
3207 );
2987 assert!(
3208 assert!(
2988 outgoing
3209 outgoing
2989 .html()
3210 .html()
@@ -3394,7 +3615,9 @@ mod tests {
3394 excerpt: "question".into(),
3615 excerpt: "question".into(),
3395 };
3616 };
3396 typist.act(|_, cx| {
3617 typist.act(|_, cx| {
3397 composer.update(cx, |composer, cx| composer.set_reply(Some(reply.clone()), cx));
3618 composer.update(cx, |composer, cx| {
3619 composer.set_reply(Some(reply.clone()), cx)
3620 });
3398 });
3621 });
3399 load(&mut typist, &entry);
3622 load(&mut typist, &entry);
3400 let tokens = image_tokens(&mut typist);
3623 let tokens = image_tokens(&mut typist);
@@ -3990,7 +4213,7 @@ mod tests {
3990 #[gpui_kit::test]
4213 #[gpui_kit::test]
3991 fn quotes_continue_on_shift_enter_and_send_as_blockquote(cx: &mut TestAppContext) {
4214 fn quotes_continue_on_shift_enter_and_send_as_blockquote(cx: &mut TestAppContext) {
3992 let mut typist = typist(cx);
4215 let mut typist = typist(cx);
3993 typist.type_text("> quoted");
4216 typist.type_text(">quoted");
3994 typist.press("shift-enter");
4217 typist.press("shift-enter");
3995 typist.type_text("more");
4218 typist.type_text("more");
3996 let outgoing = typist.outgoing();
4219 let outgoing = typist.outgoing();
@@ -3998,6 +4221,112 @@ mod tests {
3998 assert_eq!(outgoing.text(), "quoted\nmore");
4221 assert_eq!(outgoing.text(), "quoted\nmore");
3999 }
4222 }
4000
4223
4224 #[gpui_kit::test]
4225 fn enter_in_a_quote_adds_a_line_and_enter_on_the_empty_one_leaves_it(
4226 cx: &mut TestAppContext,
4227 ) {
4228 let mut typist = typist(cx);
4229 typist.type_text(">quoted");
4230 typist.press("enter");
4231 typist.type_text("more");
4232 typist.press("enter enter");
4233 typist.type_text("after");
4234 assert_eq!(typist.value(), "quoted\nmore\nafter");
4235 assert_eq!(
4236 typist.outgoing().html(),
4237 "<blockquote>quoted<br>more</blockquote>after"
4238 );
4239 }
4240
4241 #[gpui_kit::test]
4242 fn down_at_the_end_of_a_quote_leaves_it(cx: &mut TestAppContext) {
4243 let mut typist = typist(cx);
4244 typist.type_text(">quoted");
4245 typist.press("down");
4246 typist.type_text("after");
4247 assert_eq!(
4248 typist.outgoing().html(),
4249 "<blockquote>quoted</blockquote>after"
4250 );
4251 }
4252
4253 fn insert_table(typist: &mut Typist<'_>, rows: usize, columns: usize) {
4254 let composer = typist.composer.clone();
4255 typist.act(|window, cx| {
4256 composer.update(cx, |composer, cx| {
4257 composer.insert_table(rows, columns, window, cx)
4258 });
4259 window.render_frame(cx);
4260 });
4261 }
4262
4263 #[gpui_kit::test]
4264 fn a_table_takes_tab_grows_a_row_at_the_end_and_sends_as_teams_html(
4265 cx: &mut TestAppContext,
4266 ) {
4267 let mut typist = typist(cx);
4268 typist.type_text("before");
4269 insert_table(&mut typist, 1, 2);
4270 typist.type_text("a");
4271 typist.press("tab");
4272 typist.type_text("b");
4273 typist.press("tab");
4274 typist.act(|window, cx| window.render_frame(cx));
4275 typist.type_text("c");
4276 typist.press("down");
4277 typist.type_text("after");
4278 assert_eq!(
4279 typist.outgoing().html(),
4280 "before<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\
4281 <tr><td>a</td><td>b</td></tr><tr><td>c</td><td>&nbsp;</td></tr>\
4282 </tbody></table></figure>after"
4283 );
4284 }
4285
4286 #[gpui_kit::test]
4287 fn deleting_the_last_column_deletes_the_table(cx: &mut TestAppContext) {
4288 let mut typist = typist(cx);
4289 insert_table(&mut typist, 1, 1);
4290 let composer = typist.composer.clone();
4291 typist.act(|window, cx| {
4292 composer.update(cx, |composer, cx| {
4293 composer.edit_table(teams_core::TableEdit::DeleteColumn, window, cx)
4294 });
4295 });
4296 assert!(typist.draft().lines().iter().all(|kind| !kind.is_table()));
4297 }
4298
4299 #[gpui_kit::test]
4300 fn a_pasted_markdown_table_becomes_a_table(cx: &mut TestAppContext) {
4301 let mut typist = typist(cx);
4302 typist
4303 .cx
4304 .write_to_clipboard(gpui_kit::ClipboardItem::new_string(
4305 "| A | B |\n|---|---|\n| 1 | 2 |".to_owned(),
4306 ));
4307 typist.press("ctrl-v");
4308 assert!(typist.draft().lines()[0].is_table());
4309 assert_eq!(
4310 typist.outgoing().html(),
4311 "<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\
4312 <tr><td>A</td><td>B</td></tr><tr><td>1</td><td>2</td></tr>\
4313 </tbody></table></figure>"
4314 );
4315 }
4316
4317 #[gpui_kit::test]
4318 fn ctrl_shift_v_pastes_markdown_as_plain_text(cx: &mut TestAppContext) {
4319 let mut typist = typist(cx);
4320 typist
4321 .cx
4322 .write_to_clipboard(gpui_kit::ClipboardItem::new_string(
4323 "**hi** there".to_owned(),
4324 ));
4325 typist.press("ctrl-shift-v");
4326 assert_eq!(typist.value(), "**hi** there");
4327 assert!(typist.draft().marks().is_empty());
4328 }
4329
4001 #[gpui_kit::test]
4330 #[gpui_kit::test]
4002 fn demo_upload_runs_to_done_and_a_file_alone_can_be_sent(cx: &mut TestAppContext) {
4331 fn demo_upload_runs_to_done_and_a_file_alone_can_be_sent(cx: &mut TestAppContext) {
4003 cx.update(gpui_kit::init);
4332 cx.update(gpui_kit::init);
crates/app/src/views/composer/schedule.rs +1 −0
@@ -57,6 +57,7 @@ fn menu_row(id: ElementId, highlighted: bool) -> Stateful<Div> {
57 57 h_flex()
58 58 .id(id)
59 59 .h(px(ROW_HEIGHT))
60 .flex_none()
60 61 .px(px(10.))
61 62 .gap(px(10.))
62 63 .items_center()
@@ -57,6 +57,7 @@ fn menu_row(id: ElementId, highlighted: bool) -> Stateful<Div> {
57 h_flex()
57 h_flex()
58 .id(id)
58 .id(id)
59 .h(px(ROW_HEIGHT))
59 .h(px(ROW_HEIGHT))
60 .flex_none()
60 .px(px(10.))
61 .px(px(10.))
61 .gap(px(10.))
62 .gap(px(10.))
62 .items_center()
63 .items_center()
crates/app/src/views/composer/table.rs added +633 −0
@@ -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 @@
1use std::collections::HashMap;
2use std::ops::Range;
3
4use gpui_kit::component::input::{
5 Copy, Cut, InlineToken, InputEvent, Paste, Textarea, TextareaState,
6};
7use gpui_kit::component::native_menu::NativeMenu;
8use gpui_kit::component::{Sizable as _, h_flex, v_flex};
9use gpui_kit::prelude::FluentBuilder as _;
10use gpui_kit::*;
11use teams_core::{Cell, PICKER_COLUMNS, PICKER_ROWS, TABLE_MARK, Table, TableEdit};
12
13use super::{Composer, StepKind};
14use crate::theme::{self, ElevatedSurface as _};
15use crate::views::actions::{
16 DeleteTable, DeleteTableColumn, DeleteTableRow, InsertTableColumnLeft, InsertTableColumnRight,
17 InsertTableRowAbove, InsertTableRowBelow,
18};
19
20pub(super) const TOKEN_PREFIX: &str = "table-";
21const CELL_MAX_ROWS: usize = 12;
22const PICKER_SQUARE: f32 = 16.;
23const PICKER_GAP: f32 = 3.;
24const TABLE_MARGIN: f32 = 4.;
25const CELL_PADDING_X: f32 = 2.;
26const CELL_PADDING_Y: f32 = 3.;
27
28pub(super) struct TableView {
29 cells: Vec<Vec<Entity<TextareaState>>>,
30 _subscriptions: Vec<Subscription>,
31}
32
33impl 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.
40pub(super) struct TablePicker {
41 rows: usize,
42 columns: usize,
43}
44
45pub(super) fn token(number: usize) -> InlineToken {
46 InlineToken::new(format!("{TOKEN_PREFIX}{number}"), TABLE_MARK.to_string()).block()
47}
48
49pub(super) fn is_table_token(token: &InlineToken) -> bool {
50 token.id().starts_with(TOKEN_PREFIX)
51}
52
53fn token_number(id: &str) -> usize {
54 id.strip_prefix(TOKEN_PREFIX)
55 .and_then(|number| number.parse().ok())
56 .unwrap_or_default()
57}
58
59fn caret_on_first_line(state: &TextareaState) -> bool {
60 !state.value()[..state.cursor()].contains('\n')
61}
62
63fn caret_on_last_line(state: &TextareaState) -> bool {
64 !state.value()[state.cursor()..].contains('\n')
65}
66
67impl 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
595fn 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)]
614pub(super) enum TableKey {
615 Next,
616 Previous,
617 Up,
618 Down,
619}
620
621fn 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
633pub(super) type TableViews = HashMap<String, TableView>;
crates/app/src/views/new_chat.rs +1 −0
@@ -474,6 +474,7 @@ impl NewChatDraft {
474 474 .id(ElementId::Name(format!("new-chat-result-{index}").into()))
475 475 .px(px(6.))
476 476 .h(px(POPUP_ROW_HEIGHT))
477 .flex_none()
477 478 .gap(px(8.))
478 479 .items_center()
479 480 .rounded(px(6.))
@@ -474,6 +474,7 @@ impl NewChatDraft {
474 .id(ElementId::Name(format!("new-chat-result-{index}").into()))
474 .id(ElementId::Name(format!("new-chat-result-{index}").into()))
475 .px(px(6.))
475 .px(px(6.))
476 .h(px(POPUP_ROW_HEIGHT))
476 .h(px(POPUP_ROW_HEIGHT))
477 .flex_none()
477 .gap(px(8.))
478 .gap(px(8.))
478 .items_center()
479 .items_center()
479 .rounded(px(6.))
480 .rounded(px(6.))
crates/app/src/views/reaction_pills.rs +1 −0
@@ -197,6 +197,7 @@ fn tab_button(tab: &ReactionTab, active: bool, select_tab: SelectTab) -> Statefu
197 197 fn entry_row(entry: &ReactionEntry, directory: &Directory) -> Div {
198 198 h_flex()
199 199 .h(px(ENTRY_HEIGHT))
200 .flex_none()
200 201 .px(px(8.))
201 202 .gap(px(8.))
202 203 .items_center()
@@ -197,6 +197,7 @@ fn tab_button(tab: &ReactionTab, active: bool, select_tab: SelectTab) -> Statefu
197fn entry_row(entry: &ReactionEntry, directory: &Directory) -> Div {
197fn entry_row(entry: &ReactionEntry, directory: &Directory) -> Div {
198 h_flex()
198 h_flex()
199 .h(px(ENTRY_HEIGHT))
199 .h(px(ENTRY_HEIGHT))
200 .flex_none()
200 .px(px(8.))
201 .px(px(8.))
201 .gap(px(8.))
202 .gap(px(8.))
202 .items_center()
203 .items_center()
crates/app/src/views/shared_tab.rs +1 −0
@@ -348,6 +348,7 @@ fn skeleton_rows() -> impl IntoElement {
348 348 ))
349 349 .w_full()
350 350 .h(px(ROW_HEIGHT))
351 .flex_none()
351 352 .px(px(SIDE_PADDING))
352 353 .gap(px(12.))
353 354 .items_center()
@@ -348,6 +348,7 @@ fn skeleton_rows() -> impl IntoElement {
348 ))
348 ))
349 .w_full()
349 .w_full()
350 .h(px(ROW_HEIGHT))
350 .h(px(ROW_HEIGHT))
351 .flex_none()
351 .px(px(SIDE_PADDING))
352 .px(px(SIDE_PADDING))
352 .gap(px(12.))
353 .gap(px(12.))
353 .items_center()
354 .items_center()
crates/app/src/views/shortcuts.rs +10 −4
@@ -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 @@
1use gpui_kit::*;
1use gpui_kit::*;
2
2
3use super::actions::{
3use 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
9const TEXT_FIELD_CONTEXT: &str = "Input";
9const 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_KEYS
168 .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)))
crates/app/src/views/sidebar.rs +5 −0
@@ -746,6 +746,7 @@ impl SidebarView {
746 746 .id("new-chat-draft")
747 747 .mx(px(6.))
748 748 .h(px(ROW_HEIGHT))
749 .flex_none()
749 750 .px(px(10.))
750 751 .gap(px(12.))
751 752 .items_center()
@@ -1010,6 +1011,7 @@ impl SidebarView {
1010 1011 .id(SharedString::from(format!("chat-{}", item.id)))
1011 1012 .mx(px(6.))
1012 1013 .h(px(ROW_HEIGHT))
1014 .flex_none()
1013 1015 .px(px(10.))
1014 1016 .gap(px(12.))
1015 1017 .items_center()
@@ -1327,6 +1329,7 @@ impl SidebarView {
1327 1329 .id(SharedString::from(format!("team-{team_id}")))
1328 1330 .mx(px(6.))
1329 1331 .h(px(TEAM_ROW_HEIGHT))
1332 .flex_none()
1330 1333 .px(px(10.))
1331 1334 .gap(px(8.))
1332 1335 .items_center()
@@ -1426,6 +1429,7 @@ impl SidebarView {
1426 1429 .id(id)
1427 1430 .mx(px(6.))
1428 1431 .h(px(REVEAL_ROW_HEIGHT))
1432 .flex_none()
1429 1433 .pl(px(indent))
1430 1434 .pr(px(10.))
1431 1435 .gap(px(8.))
@@ -1466,6 +1470,7 @@ impl SidebarView {
1466 1470 .id(SharedString::from(format!("channel-{}", channel.id)))
1467 1471 .mx(px(6.))
1468 1472 .h(px(TEAM_ROW_HEIGHT))
1473 .flex_none()
1469 1474 .pl(px(40.))
1470 1475 .pr(px(10.))
1471 1476 .gap(px(8.))
@@ -746,6 +746,7 @@ impl SidebarView {
746 .id("new-chat-draft")
746 .id("new-chat-draft")
747 .mx(px(6.))
747 .mx(px(6.))
748 .h(px(ROW_HEIGHT))
748 .h(px(ROW_HEIGHT))
749 .flex_none()
749 .px(px(10.))
750 .px(px(10.))
750 .gap(px(12.))
751 .gap(px(12.))
751 .items_center()
752 .items_center()
@@ -1010,6 +1011,7 @@ impl SidebarView {
1010 .id(SharedString::from(format!("chat-{}", item.id)))
1011 .id(SharedString::from(format!("chat-{}", item.id)))
1011 .mx(px(6.))
1012 .mx(px(6.))
1012 .h(px(ROW_HEIGHT))
1013 .h(px(ROW_HEIGHT))
1014 .flex_none()
1013 .px(px(10.))
1015 .px(px(10.))
1014 .gap(px(12.))
1016 .gap(px(12.))
1015 .items_center()
1017 .items_center()
@@ -1327,6 +1329,7 @@ impl SidebarView {
1327 .id(SharedString::from(format!("team-{team_id}")))
1329 .id(SharedString::from(format!("team-{team_id}")))
1328 .mx(px(6.))
1330 .mx(px(6.))
1329 .h(px(TEAM_ROW_HEIGHT))
1331 .h(px(TEAM_ROW_HEIGHT))
1332 .flex_none()
1330 .px(px(10.))
1333 .px(px(10.))
1331 .gap(px(8.))
1334 .gap(px(8.))
1332 .items_center()
1335 .items_center()
@@ -1426,6 +1429,7 @@ impl SidebarView {
1426 .id(id)
1429 .id(id)
1427 .mx(px(6.))
1430 .mx(px(6.))
1428 .h(px(REVEAL_ROW_HEIGHT))
1431 .h(px(REVEAL_ROW_HEIGHT))
1432 .flex_none()
1429 .pl(px(indent))
1433 .pl(px(indent))
1430 .pr(px(10.))
1434 .pr(px(10.))
1431 .gap(px(8.))
1435 .gap(px(8.))
@@ -1466,6 +1470,7 @@ impl SidebarView {
1466 .id(SharedString::from(format!("channel-{}", channel.id)))
1470 .id(SharedString::from(format!("channel-{}", channel.id)))
1467 .mx(px(6.))
1471 .mx(px(6.))
1468 .h(px(TEAM_ROW_HEIGHT))
1472 .h(px(TEAM_ROW_HEIGHT))
1473 .flex_none()
1469 .pl(px(40.))
1474 .pl(px(40.))
1470 .pr(px(10.))
1475 .pr(px(10.))
1471 .gap(px(8.))
1476 .gap(px(8.))
crates/core/src/draft.rs +285 −26
@@ -6,8 +6,10 @@ use serde::{Deserialize, Serialize};
6 6
7 7 use crate::markdown::escape_html;
8 8 use crate::spans::{FontSize, Span};
9 use crate::table::{TABLE_MARK, Table, markdown_table};
9 10
10 11 pub const MAX_DEPTH: u8 = 2;
12 pub const MAX_HEADING: u8 = 3;
11 13 pub const OBJECT_MARK: char = '\u{FFFC}';
12 14 const BULLETS: [&str; 3] = ["•", "◦", "▪"];
13 15 const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "];
@@ -125,6 +127,8 @@ pub enum LineKind {
125 127 Numbered(u8),
126 128 Quote,
127 129 Code(Option<String>),
130 Heading(u8),
131 Table(Table),
128 132 }
129 133
130 134 impl LineKind {
@@ -132,6 +136,10 @@ impl LineKind {
132 136 matches!(self, LineKind::Bullet(_) | LineKind::Numbered(_))
133 137 }
134 138
139 pub fn is_table(&self) -> bool {
140 matches!(self, LineKind::Table(_))
141 }
142
135 143 pub fn depth(&self) -> u8 {
136 144 match self {
137 145 LineKind::Bullet(depth) | LineKind::Numbered(depth) => *depth,
@@ -430,7 +438,10 @@ impl Draft {
430 438 pub fn plain_text(&self) -> String {
431 439 self.slice(0..self.text.len())
432 440 .into_iter()
433 .map(|line| line.content)
441 .map(|line| match &line.kind {
442 LineKind::Table(table) => table.plain_text(),
443 _ => line.content,
444 })
434 445 .collect::<Vec<_>>()
435 446 .join("\n")
436 447 .replace(&format!(" {OBJECT_MARK} "), " ")
@@ -762,7 +773,11 @@ impl Draft {
762 773 self.splice(content.clone(), "", &[]);
763 774 Some(self.set_line_kind(index, LineKind::Code(language), None, content.start))
764 775 }
765 LineKind::Quote if !shift => None,
776 LineKind::Heading(_) | LineKind::Table(_) => None,
777 LineKind::Quote if content.is_empty() && !shift => {
778 self.lines[index] = LineKind::Text;
779 Some(cursor)
780 }
766 781 LineKind::Quote => {
767 782 self.splice(cursor..cursor, "\n", &[]);
768 783 self.lines[index] = LineKind::Quote;
@@ -823,6 +838,9 @@ impl Draft {
823 838 if cursor != line.end || index + 1 >= self.lines.len() {
824 839 return None;
825 840 }
841 if self.lines[index + 1].is_table() {
842 return Some(cursor);
843 }
826 844 let next_marker = self.marker_range(index + 1);
827 845 if next_marker.is_empty() {
828 846 return None;
@@ -847,11 +865,22 @@ impl Draft {
847 865 cursor
848 866 })
849 867 }
868 LineKind::Table(_) => None,
869 LineKind::Heading(_) => (cursor == line.start).then(|| {
870 self.lines[index] = LineKind::Text;
871 cursor
872 }),
850 873 LineKind::Quote
851 874 if cursor == line.start && (index == 0 || self.lines[index - 1] != kind) =>
852 875 {
853 self.lines[index] = LineKind::Text;
854 Some(cursor)
876 let joins_previous =
877 index > 0 && !content.is_empty() && !self.lines[index - 1].is_table();
878 if !joins_previous {
879 self.lines[index] = LineKind::Text;
880 return Some(cursor);
881 }
882 self.splice(line.start - 1..line.start, "", &[]);
883 Some(self.repair(line.start - 1))
855 884 }
856 885 _ if cursor == line.start && index > 0 => {
857 886 self.splice(line.start - 1..content.start, "", &[]);
@@ -899,6 +928,9 @@ impl Draft {
899 928 .all(|index| self.lines[index].same_format(&kind));
900 929 for index in lines {
901 930 let current = self.lines[index].clone();
931 if current.is_table() {
932 continue;
933 }
902 934 let target = if all {
903 935 LineKind::Text
904 936 } else if current.same_format(&kind) {
@@ -915,6 +947,120 @@ impl Draft {
915 947 self.repair(0);
916 948 }
917 949
950 pub fn table(&self, index: usize) -> Option<&Table> {
951 match self.lines.get(index)? {
952 LineKind::Table(table) => Some(table),
953 _ => None,
954 }
955 }
956
957 /// Cell edits change no text, so the journal stays as it is.
958 pub fn set_table(&mut self, index: usize, table: Table) {
959 if let Some(kind @ LineKind::Table(_)) = self.lines.get_mut(index) {
960 *kind = LineKind::Table(table);
961 }
962 }
963
964 /// The table goes in place of an empty text line, otherwise below the cursor's line, and
965 /// a text line follows it. Returns the table's line.
966 pub fn insert_table(&mut self, cursor: usize, table: Table) -> usize {
967 self.journal = Journal::default();
968 let index = self.line_at(cursor);
969 let line = self.line_ranges()[index].clone();
970 let mark = TABLE_MARK.to_string();
971 let replaces_line = self.lines[index] == LineKind::Text && line.is_empty();
972 let table_index = if replaces_line {
973 self.splice(line, &mark, &[]);
974 index
975 } else {
976 self.splice(line.end..line.end, &format!("\n{mark}"), &[]);
977 index + 1
978 };
979 self.lines[table_index] = LineKind::Table(table);
980 if table_index + 1 == self.lines.len() {
981 let end = self.text.len();
982 self.splice(end..end, "\n", &[]);
983 self.lines[table_index + 1] = LineKind::Text;
984 }
985 table_index
986 }
987
988 /// Returns where the cursor goes: the start of the line that took the table's place.
989 pub fn remove_table(&mut self, index: usize) -> usize {
990 self.journal = Journal::default();
991 let ranges = self.line_ranges();
992 let line = ranges[index].clone();
993 if let Some(next) = ranges.get(index + 1) {
994 let next_kind = self.lines[index + 1].clone();
995 self.splice(line.start..next.start, "", &[]);
996 self.lines[index] = next_kind;
997 return self.repair(line.start);
998 }
999 if index > 0 {
1000 let start = ranges[index - 1].end;
1001 self.splice(start..line.end, "", &[]);
1002 return self.repair(start);
1003 }
1004 self.splice(line, "", &[]);
1005 self.lines[index] = LineKind::Text;
1006 0
1007 }
1008
1009 /// Where the cursor lands when it leaves table `index` downwards or upwards; a text line
1010 /// is added when the table is the last or the first line.
1011 pub fn line_beside_table(&mut self, index: usize, below: bool) -> usize {
1012 self.journal = Journal::default();
1013 let ranges = self.line_ranges();
1014 if below {
1015 if let Some(next) = ranges.get(index + 1) {
1016 return next.start;
1017 }
1018 let end = self.text.len();
1019 self.splice(end..end, "\n", &[]);
1020 self.lines[index + 1] = LineKind::Text;
1021 return end + 1;
1022 }
1023 if index > 0 {
1024 return ranges[index - 1].end;
1025 }
1026 self.splice(0..0, "\n", &[]);
1027 self.lines[0] = LineKind::Text;
1028 0
1029 }
1030
1031 pub fn table_at(&self, offset: usize) -> Option<usize> {
1032 let index = self.line_at(offset);
1033 self.lines[index].is_table().then_some(index)
1034 }
1035
1036 /// The table right above, when `cursor` is at the start of its line.
1037 pub fn table_before(&self, cursor: usize) -> Option<usize> {
1038 let index = self.line_at(cursor);
1039 let at_start = self.line_ranges()[index].start == cursor;
1040 (at_start && index > 0 && self.lines[index - 1].is_table()).then(|| index - 1)
1041 }
1042
1043 /// The table right below, when `cursor` is at the end of its line.
1044 pub fn table_after(&self, cursor: usize) -> Option<usize> {
1045 let index = self.line_at(cursor);
1046 let at_end = self.line_ranges()[index].end == cursor;
1047 (at_end && self.lines.get(index + 1).is_some_and(LineKind::is_table)).then_some(index + 1)
1048 }
1049
1050 /// Down or Right at the very end of a quote that ends the draft: a text line below it,
1051 /// like the empty paragraph Teams keeps after a quote.
1052 pub fn leave_quote_at_end(&mut self, cursor: usize) -> Option<usize> {
1053 self.journal = Journal::default();
1054 let end = self.text.len();
1055 let last = self.lines.len() - 1;
1056 if cursor != end || self.lines[last] != LineKind::Quote {
1057 return None;
1058 }
1059 self.splice(end..end, "\n", &[]);
1060 self.lines[last + 1] = LineKind::Text;
1061 Some(end + 1)
1062 }
1063
918 1064 pub fn slice(&self, range: Range<usize>) -> Vec<DraftLine> {
919 1065 let mut lines = Vec::new();
920 1066 for (index, line) in self.line_ranges().into_iter().enumerate() {
@@ -981,6 +1127,13 @@ impl Draft {
981 1127 let line_was_empty = self.lines[index] == LineKind::Text
982 1128 && range.start == content.start
983 1129 && range.end >= tail_end;
1130 let separated;
1131 let lines = if !line_was_empty && lines.first().is_some_and(|line| line.kind.is_table()) {
1132 separated = [&[DraftLine::text("")][..], lines].concat();
1133 &separated[..]
1134 } else {
1135 lines
1136 };
984 1137 let joined = lines
985 1138 .iter()
986 1139 .map(|line| line.content.as_str())
@@ -1057,6 +1210,23 @@ impl Draft {
1057 1210 html.push_str(&joined_inline(run));
1058 1211 html.push_str("</blockquote>");
1059 1212 }
1213 LineKind::Heading(_) => {
1214 for line in run {
1215 let level = match line.kind {
1216 LineKind::Heading(level) => level.clamp(1, MAX_HEADING),
1217 _ => 1,
1218 };
1219 let inline = inline_html(&line.content, &line.marks);
1220 html.push_str(&format!("<h{level}>{inline}</h{level}>"));
1221 }
1222 }
1223 LineKind::Table(_) => {
1224 for line in run {
1225 if let LineKind::Table(table) = &line.kind {
1226 html.push_str(&table.to_html());
1227 }
1228 }
1229 }
1060 1230 LineKind::Code(language) => {
1061 1231 match language {
1062 1232 Some(language) => html.push_str(&format!(
@@ -1362,8 +1532,45 @@ impl Draft {
1362 1532 }
1363 1533 }
1364 1534
1535 /// A table line holds its mark alone: text typed next to it moves to its own line, a mark
1536 /// without its table is dropped and a table without its mark becomes text.
1537 fn repair_tables(&mut self, mut cursor: usize) -> usize {
1538 let mark_length = TABLE_MARK.len_utf8();
1539 let mut index = 0;
1540 while index < self.lines.len() {
1541 let line = self.line_ranges()[index].clone();
1542 let found = self.text[line.clone()].find(TABLE_MARK);
1543 match (self.lines[index].clone(), found) {
1544 (LineKind::Table(_), None) => self.lines[index] = LineKind::Text,
1545 (LineKind::Table(table), Some(at)) if at > 0 => {
1546 let split = line.start + at;
1547 self.splice(split..split, "\n", &[]);
1548 self.lines[index] = LineKind::Text;
1549 self.lines[index + 1] = LineKind::Table(table);
1550 cursor += usize::from(cursor > split);
1551 }
1552 (LineKind::Table(_), Some(_)) if line.len() > mark_length => {
1553 let split = line.start + mark_length;
1554 self.splice(split..split, "\n", &[]);
1555 cursor += usize::from(cursor > split);
1556 }
1557 (LineKind::Table(_), Some(_)) => {}
1558 (_, Some(at)) => {
1559 let mark = line.start + at..line.start + at + mark_length;
1560 self.splice(mark.clone(), "", &[]);
1561 cursor = map_offset(&[(mark, String::new())], cursor);
1562 continue;
1563 }
1564 (_, None) => {}
1565 }
1566 index += 1;
1567 }
1568 cursor
1569 }
1570
1365 1571 /// List items whose marker was edited away become text; numbered items are renumbered.
1366 fn repair(&mut self, mut cursor: usize) -> usize {
1572 fn repair(&mut self, cursor: usize) -> usize {
1573 let mut cursor = self.repair_tables(cursor);
1367 1574 for index in 0..self.lines.len() {
1368 1575 let kind = self.lines[index].clone();
1369 1576 if !kind.is_list() {
@@ -1399,7 +1606,11 @@ fn marker_text(kind: &LineKind, number: u32) -> String {
1399 1606 match kind {
1400 1607 LineKind::Bullet(depth) => bullet_marker(*depth),
1401 1608 LineKind::Numbered(_) => format!("{number}. "),
1402 LineKind::Text | LineKind::Quote | LineKind::Code(_) => String::new(),
1609 LineKind::Text
1610 | LineKind::Quote
1611 | LineKind::Code(_)
1612 | LineKind::Heading(_)
1613 | LineKind::Table(_) => String::new(),
1403 1614 }
1404 1615 }
1405 1616
@@ -1430,7 +1641,9 @@ fn numbered_marker(line: &str) -> Option<(usize, u32)> {
1430 1641 fn line_shortcut(before: &str) -> Option<(LineKind, u32)> {
1431 1642 match before {
1432 1643 "- " | "* " => Some((LineKind::Bullet(0), 1)),
1433 "> " => Some((LineKind::Quote, 1)),
1644 ">" => Some((LineKind::Quote, 1)),
1645 _ if before.starts_with('#') => heading_prefix(before)
1646 .and_then(|(level, rest)| rest.is_empty().then_some((LineKind::Heading(level), 1))),
1434 1647 _ => {
1435 1648 let digits = before.strip_suffix(". ")?;
1436 1649 let all_digits = !digits.is_empty()
@@ -1540,7 +1753,7 @@ fn typed_inline(before: &str) -> Option<(Range<usize>, Range<usize>, MarkKind)>
1540 1753 let usable = !body[open + 1..].trim().is_empty() && !body[..open].ends_with('`');
1541 1754 return usable.then(|| (open..open + 1, body.len()..end, MarkKind::Code));
1542 1755 }
1543 for marker in ['*', '_'] {
1756 for (marker, kind) in [('*', MarkKind::Bold), ('_', MarkKind::Italic)] {
1544 1757 if let Some(body) = before.strip_suffix(marker) {
1545 1758 if body.ends_with(marker) {
1546 1759 return None;
@@ -1548,7 +1761,7 @@ fn typed_inline(before: &str) -> Option<(Range<usize>, Range<usize>, MarkKind)>
1548 1761 let open = body.rfind(marker)?;
1549 1762 let opening_ok = !word_before(&body[..open]) && !body[..open].ends_with(marker);
1550 1763 return (opening_ok && valid_inner(&body[open + 1..]))
1551 .then(|| (open..open + 1, body.len()..end, MarkKind::Italic));
1764 .then(|| (open..open + 1, body.len()..end, kind));
1552 1765 }
1553 1766 }
1554 1767 None
@@ -1702,10 +1915,16 @@ pub fn has_markdown(text: &str) -> bool {
1702 1915 }
1703 1916
1704 1917 fn markdown_lines(text: &str) -> Vec<DraftLine> {
1918 let sources: Vec<&str> = text
1919 .split('\n')
1920 .map(|raw| raw.strip_suffix('\r').unwrap_or(raw))
1921 .collect();
1705 1922 let mut lines = Vec::new();
1706 1923 let mut code: Option<Option<String>> = None;
1707 for raw in text.split('\n') {
1708 let raw = raw.strip_suffix('\r').unwrap_or(raw);
1924 let mut position = 0;
1925 while position < sources.len() {
1926 let raw = sources[position];
1927 position += 1;
1709 1928 let trimmed = raw.trim_start();
1710 1929 if let Some(language) = &code {
1711 1930 if trimmed.starts_with(FENCE) && trimmed.trim_end() == FENCE {
@@ -1727,12 +1946,23 @@ fn markdown_lines(text: &str) -> Vec<DraftLine> {
1727 1946 code = Some(language);
1728 1947 continue;
1729 1948 }
1949 if let Some((rows, consumed)) = markdown_table(&sources[position - 1..]) {
1950 let rows = rows
1951 .into_iter()
1952 .map(|row| row.iter().map(|cell| parse_inline(cell).0).collect())
1953 .collect();
1954 lines.push(table_line(Table::from_rows(rows)));
1955 position += consumed - 1;
1956 continue;
1957 }
1730 1958 let indent: usize = raw[..raw.len() - trimmed.len()]
1731 1959 .chars()
1732 1960 .map(|character| if character == '\t' { 4 } else { 1 })
1733 1961 .sum();
1734 1962 let depth = ((indent / MARKDOWN_INDENT) as u8).min(MAX_DEPTH);
1735 let (kind, number, content) = if let Some(rest) = PASTED_BULLETS
1963 let (kind, number, content) = if let Some((level, rest)) = heading_prefix(trimmed) {
1964 (LineKind::Heading(level), None, rest)
1965 } else if let Some(rest) = PASTED_BULLETS
1736 1966 .iter()
1737 1967 .find_map(|bullet| trimmed.strip_prefix(bullet))
1738 1968 {
@@ -1758,6 +1988,24 @@ fn markdown_lines(text: &str) -> Vec<DraftLine> {
1758 1988 lines
1759 1989 }
1760 1990
1991 fn table_line(table: Table) -> DraftLine {
1992 DraftLine {
1993 kind: LineKind::Table(table),
1994 number: None,
1995 content: TABLE_MARK.to_string(),
1996 marks: Vec::new(),
1997 }
1998 }
1999
2000 /// `# ` to `###### `: the level, capped at the three Teams offers, and the rest of the line.
2001 fn heading_prefix(line: &str) -> Option<(u8, &str)> {
2002 let hashes = line.bytes().take_while(|byte| *byte == b'#').count();
2003 let rest = line[hashes..].strip_prefix(' ')?;
2004 (1..=6)
2005 .contains(&hashes)
2006 .then(|| ((hashes as u8).min(MAX_HEADING), rest))
2007 }
2008
1761 2009 fn parse_inline(source: &str) -> (String, Vec<Mark>) {
1762 2010 let mut text = String::with_capacity(source.len());
1763 2011 let mut marks = Vec::new();
@@ -1849,6 +2097,17 @@ fn inline_at(rest: &str, previous: Option<char>) -> Option<(&str, usize, MarkKin
1849 2097 None
1850 2098 }
1851 2099
2100 fn cell_text(spans: &[Span]) -> String {
2101 let mut builder = SpanLines::default();
2102 builder.walk(spans, &LineKind::Text, &[]);
2103 builder
2104 .finish()
2105 .into_iter()
2106 .map(|line| line.content)
2107 .collect::<Vec<_>>()
2108 .join("\n")
2109 }
2110
1852 2111 #[derive(Default)]
1853 2112 struct SpanLines {
1854 2113 lines: Vec<DraftLine>,
@@ -1936,9 +2195,10 @@ impl SpanLines {
1936 2195 };
1937 2196 self.start_line(&continued, None);
1938 2197 }
1939 Span::Heading { children, .. } => {
1940 self.start_line(&LineKind::Text, None);
1941 self.walk(children, &LineKind::Text, &with(MarkKind::Bold));
2198 Span::Heading { level, children } => {
2199 let heading = LineKind::Heading((*level).clamp(1, MAX_HEADING));
2200 self.start_line(&heading, None);
2201 self.walk(children, &heading, marks);
1942 2202 self.open = false;
1943 2203 }
1944 2204 Span::CodeBlock { language, code } => {
@@ -1977,15 +2237,11 @@ impl SpanLines {
1977 2237 self.open = false;
1978 2238 }
1979 2239 Span::Table { rows, .. } => {
1980 for row in rows {
1981 self.start_line(&LineKind::Text, None);
1982 for (position, cell) in row.iter().enumerate() {
1983 if position > 0 {
1984 self.append(" | ", &LineKind::Text, &[]);
1985 }
1986 self.walk(cell, &LineKind::Text, marks);
1987 }
1988 }
2240 let rows = rows
2241 .iter()
2242 .map(|row| row.iter().map(|cell| cell_text(cell)).collect())
2243 .collect();
2244 self.lines.push(table_line(Table::from_rows(rows)));
1989 2245 self.open = false;
1990 2246 }
1991 2247 Span::Image { .. } | Span::Quote { .. } => {}
@@ -2081,7 +2337,7 @@ mod tests {
2081 2337 draft.marks(),
2082 2338 [
2083 2339 mark(2..6, MarkKind::Bold),
2084 mark(11..13, MarkKind::Italic),
2340 mark(11..13, MarkKind::Bold),
2085 2341 mark(17..19, MarkKind::Italic),
2086 2342 mark(20..24, MarkKind::Strike),
2087 2343 mark(25..29, MarkKind::Code),
@@ -2357,9 +2613,12 @@ mod tests {
2357 2613 let numbered = typed_draft("1. one");
2358 2614 assert_eq!(numbered.text(), "1. one");
2359 2615 assert_eq!(numbered.lines(), [LineKind::Numbered(0)]);
2360 let quote = typed_draft("> said");
2616 let quote = typed_draft(">said");
2361 2617 assert_eq!(quote.text(), "said");
2362 2618 assert_eq!(quote.lines(), [LineKind::Quote]);
2619 let spaced = typed_draft("> said");
2620 assert_eq!(spaced.text(), " said");
2621 assert_eq!(spaced.lines(), [LineKind::Quote]);
2363 2622 }
2364 2623
2365 2624 #[test]
@@ -6,8 +6,10 @@ use serde::{Deserialize, Serialize};
6
6
7use crate::markdown::escape_html;
7use crate::markdown::escape_html;
8use crate::spans::{FontSize, Span};
8use crate::spans::{FontSize, Span};
9use crate::table::{TABLE_MARK, Table, markdown_table};
9
10
10pub const MAX_DEPTH: u8 = 2;
11pub const MAX_DEPTH: u8 = 2;
12pub const MAX_HEADING: u8 = 3;
11pub const OBJECT_MARK: char = '\u{FFFC}';
13pub const OBJECT_MARK: char = '\u{FFFC}';
12const BULLETS: [&str; 3] = ["•", "◦", "▪"];
14const BULLETS: [&str; 3] = ["•", "◦", "▪"];
13const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "];
15const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "];
@@ -125,6 +127,8 @@ pub enum LineKind {
125 Numbered(u8),
127 Numbered(u8),
126 Quote,
128 Quote,
127 Code(Option<String>),
129 Code(Option<String>),
130 Heading(u8),
131 Table(Table),
128}
132}
129
133
130impl LineKind {
134impl LineKind {
@@ -132,6 +136,10 @@ impl LineKind {
132 matches!(self, LineKind::Bullet(_) | LineKind::Numbered(_))
136 matches!(self, LineKind::Bullet(_) | LineKind::Numbered(_))
133 }
137 }
134
138
139 pub fn is_table(&self) -> bool {
140 matches!(self, LineKind::Table(_))
141 }
142
135 pub fn depth(&self) -> u8 {
143 pub fn depth(&self) -> u8 {
136 match self {
144 match self {
137 LineKind::Bullet(depth) | LineKind::Numbered(depth) => *depth,
145 LineKind::Bullet(depth) | LineKind::Numbered(depth) => *depth,
@@ -430,7 +438,10 @@ impl Draft {
430 pub fn plain_text(&self) -> String {
438 pub fn plain_text(&self) -> String {
431 self.slice(0..self.text.len())
439 self.slice(0..self.text.len())
432 .into_iter()
440 .into_iter()
433 .map(|line| line.content)
441 .map(|line| match &line.kind {
442 LineKind::Table(table) => table.plain_text(),
443 _ => line.content,
444 })
434 .collect::<Vec<_>>()
445 .collect::<Vec<_>>()
435 .join("\n")
446 .join("\n")
436 .replace(&format!(" {OBJECT_MARK} "), " ")
447 .replace(&format!(" {OBJECT_MARK} "), " ")
@@ -762,7 +773,11 @@ impl Draft {
762 self.splice(content.clone(), "", &[]);
773 self.splice(content.clone(), "", &[]);
763 Some(self.set_line_kind(index, LineKind::Code(language), None, content.start))
774 Some(self.set_line_kind(index, LineKind::Code(language), None, content.start))
764 }
775 }
765 LineKind::Quote if !shift => None,
776 LineKind::Heading(_) | LineKind::Table(_) => None,
777 LineKind::Quote if content.is_empty() && !shift => {
778 self.lines[index] = LineKind::Text;
779 Some(cursor)
780 }
766 LineKind::Quote => {
781 LineKind::Quote => {
767 self.splice(cursor..cursor, "\n", &[]);
782 self.splice(cursor..cursor, "\n", &[]);
768 self.lines[index] = LineKind::Quote;
783 self.lines[index] = LineKind::Quote;
@@ -823,6 +838,9 @@ impl Draft {
823 if cursor != line.end || index + 1 >= self.lines.len() {
838 if cursor != line.end || index + 1 >= self.lines.len() {
824 return None;
839 return None;
825 }
840 }
841 if self.lines[index + 1].is_table() {
842 return Some(cursor);
843 }
826 let next_marker = self.marker_range(index + 1);
844 let next_marker = self.marker_range(index + 1);
827 if next_marker.is_empty() {
845 if next_marker.is_empty() {
828 return None;
846 return None;
@@ -847,11 +865,22 @@ impl Draft {
847 cursor
865 cursor
848 })
866 })
849 }
867 }
868 LineKind::Table(_) => None,
869 LineKind::Heading(_) => (cursor == line.start).then(|| {
870 self.lines[index] = LineKind::Text;
871 cursor
872 }),
850 LineKind::Quote
873 LineKind::Quote
851 if cursor == line.start && (index == 0 || self.lines[index - 1] != kind) =>
874 if cursor == line.start && (index == 0 || self.lines[index - 1] != kind) =>
852 {
875 {
853 self.lines[index] = LineKind::Text;
876 let joins_previous =
854 Some(cursor)
877 index > 0 && !content.is_empty() && !self.lines[index - 1].is_table();
878 if !joins_previous {
879 self.lines[index] = LineKind::Text;
880 return Some(cursor);
881 }
882 self.splice(line.start - 1..line.start, "", &[]);
883 Some(self.repair(line.start - 1))
855 }
884 }
856 _ if cursor == line.start && index > 0 => {
885 _ if cursor == line.start && index > 0 => {
857 self.splice(line.start - 1..content.start, "", &[]);
886 self.splice(line.start - 1..content.start, "", &[]);
@@ -899,6 +928,9 @@ impl Draft {
899 .all(|index| self.lines[index].same_format(&kind));
928 .all(|index| self.lines[index].same_format(&kind));
900 for index in lines {
929 for index in lines {
901 let current = self.lines[index].clone();
930 let current = self.lines[index].clone();
931 if current.is_table() {
932 continue;
933 }
902 let target = if all {
934 let target = if all {
903 LineKind::Text
935 LineKind::Text
904 } else if current.same_format(&kind) {
936 } else if current.same_format(&kind) {
@@ -915,6 +947,120 @@ impl Draft {
915 self.repair(0);
947 self.repair(0);
916 }
948 }
917
949
950 pub fn table(&self, index: usize) -> Option<&Table> {
951 match self.lines.get(index)? {
952 LineKind::Table(table) => Some(table),
953 _ => None,
954 }
955 }
956
957 /// Cell edits change no text, so the journal stays as it is.
958 pub fn set_table(&mut self, index: usize, table: Table) {
959 if let Some(kind @ LineKind::Table(_)) = self.lines.get_mut(index) {
960 *kind = LineKind::Table(table);
961 }
962 }
963
964 /// The table goes in place of an empty text line, otherwise below the cursor's line, and
965 /// a text line follows it. Returns the table's line.
966 pub fn insert_table(&mut self, cursor: usize, table: Table) -> usize {
967 self.journal = Journal::default();
968 let index = self.line_at(cursor);
969 let line = self.line_ranges()[index].clone();
970 let mark = TABLE_MARK.to_string();
971 let replaces_line = self.lines[index] == LineKind::Text && line.is_empty();
972 let table_index = if replaces_line {
973 self.splice(line, &mark, &[]);
974 index
975 } else {
976 self.splice(line.end..line.end, &format!("\n{mark}"), &[]);
977 index + 1
978 };
979 self.lines[table_index] = LineKind::Table(table);
980 if table_index + 1 == self.lines.len() {
981 let end = self.text.len();
982 self.splice(end..end, "\n", &[]);
983 self.lines[table_index + 1] = LineKind::Text;
984 }
985 table_index
986 }
987
988 /// Returns where the cursor goes: the start of the line that took the table's place.
989 pub fn remove_table(&mut self, index: usize) -> usize {
990 self.journal = Journal::default();
991 let ranges = self.line_ranges();
992 let line = ranges[index].clone();
993 if let Some(next) = ranges.get(index + 1) {
994 let next_kind = self.lines[index + 1].clone();
995 self.splice(line.start..next.start, "", &[]);
996 self.lines[index] = next_kind;
997 return self.repair(line.start);
998 }
999 if index > 0 {
1000 let start = ranges[index - 1].end;
1001 self.splice(start..line.end, "", &[]);
1002 return self.repair(start);
1003 }
1004 self.splice(line, "", &[]);
1005 self.lines[index] = LineKind::Text;
1006 0
1007 }
1008
1009 /// Where the cursor lands when it leaves table `index` downwards or upwards; a text line
1010 /// is added when the table is the last or the first line.
1011 pub fn line_beside_table(&mut self, index: usize, below: bool) -> usize {
1012 self.journal = Journal::default();
1013 let ranges = self.line_ranges();
1014 if below {
1015 if let Some(next) = ranges.get(index + 1) {
1016 return next.start;
1017 }
1018 let end = self.text.len();
1019 self.splice(end..end, "\n", &[]);
1020 self.lines[index + 1] = LineKind::Text;
1021 return end + 1;
1022 }
1023 if index > 0 {
1024 return ranges[index - 1].end;
1025 }
1026 self.splice(0..0, "\n", &[]);
1027 self.lines[0] = LineKind::Text;
1028 0
1029 }
1030
1031 pub fn table_at(&self, offset: usize) -> Option<usize> {
1032 let index = self.line_at(offset);
1033 self.lines[index].is_table().then_some(index)
1034 }
1035
1036 /// The table right above, when `cursor` is at the start of its line.
1037 pub fn table_before(&self, cursor: usize) -> Option<usize> {
1038 let index = self.line_at(cursor);
1039 let at_start = self.line_ranges()[index].start == cursor;
1040 (at_start && index > 0 && self.lines[index - 1].is_table()).then(|| index - 1)
1041 }
1042
1043 /// The table right below, when `cursor` is at the end of its line.
1044 pub fn table_after(&self, cursor: usize) -> Option<usize> {
1045 let index = self.line_at(cursor);
1046 let at_end = self.line_ranges()[index].end == cursor;
1047 (at_end && self.lines.get(index + 1).is_some_and(LineKind::is_table)).then_some(index + 1)
1048 }
1049
1050 /// Down or Right at the very end of a quote that ends the draft: a text line below it,
1051 /// like the empty paragraph Teams keeps after a quote.
1052 pub fn leave_quote_at_end(&mut self, cursor: usize) -> Option<usize> {
1053 self.journal = Journal::default();
1054 let end = self.text.len();
1055 let last = self.lines.len() - 1;
1056 if cursor != end || self.lines[last] != LineKind::Quote {
1057 return None;
1058 }
1059 self.splice(end..end, "\n", &[]);
1060 self.lines[last + 1] = LineKind::Text;
1061 Some(end + 1)
1062 }
1063
918 pub fn slice(&self, range: Range<usize>) -> Vec<DraftLine> {
1064 pub fn slice(&self, range: Range<usize>) -> Vec<DraftLine> {
919 let mut lines = Vec::new();
1065 let mut lines = Vec::new();
920 for (index, line) in self.line_ranges().into_iter().enumerate() {
1066 for (index, line) in self.line_ranges().into_iter().enumerate() {
@@ -981,6 +1127,13 @@ impl Draft {
981 let line_was_empty = self.lines[index] == LineKind::Text
1127 let line_was_empty = self.lines[index] == LineKind::Text
982 && range.start == content.start
1128 && range.start == content.start
983 && range.end >= tail_end;
1129 && range.end >= tail_end;
1130 let separated;
1131 let lines = if !line_was_empty && lines.first().is_some_and(|line| line.kind.is_table()) {
1132 separated = [&[DraftLine::text("")][..], lines].concat();
1133 &separated[..]
1134 } else {
1135 lines
1136 };
984 let joined = lines
1137 let joined = lines
985 .iter()
1138 .iter()
986 .map(|line| line.content.as_str())
1139 .map(|line| line.content.as_str())
@@ -1057,6 +1210,23 @@ impl Draft {
1057 html.push_str(&joined_inline(run));
1210 html.push_str(&joined_inline(run));
1058 html.push_str("</blockquote>");
1211 html.push_str("</blockquote>");
1059 }
1212 }
1213 LineKind::Heading(_) => {
1214 for line in run {
1215 let level = match line.kind {
1216 LineKind::Heading(level) => level.clamp(1, MAX_HEADING),
1217 _ => 1,
1218 };
1219 let inline = inline_html(&line.content, &line.marks);
1220 html.push_str(&format!("<h{level}>{inline}</h{level}>"));
1221 }
1222 }
1223 LineKind::Table(_) => {
1224 for line in run {
1225 if let LineKind::Table(table) = &line.kind {
1226 html.push_str(&table.to_html());
1227 }
1228 }
1229 }
1060 LineKind::Code(language) => {
1230 LineKind::Code(language) => {
1061 match language {
1231 match language {
1062 Some(language) => html.push_str(&format!(
1232 Some(language) => html.push_str(&format!(
@@ -1362,8 +1532,45 @@ impl Draft {
1362 }
1532 }
1363 }
1533 }
1364
1534
1535 /// A table line holds its mark alone: text typed next to it moves to its own line, a mark
1536 /// without its table is dropped and a table without its mark becomes text.
1537 fn repair_tables(&mut self, mut cursor: usize) -> usize {
1538 let mark_length = TABLE_MARK.len_utf8();
1539 let mut index = 0;
1540 while index < self.lines.len() {
1541 let line = self.line_ranges()[index].clone();
1542 let found = self.text[line.clone()].find(TABLE_MARK);
1543 match (self.lines[index].clone(), found) {
1544 (LineKind::Table(_), None) => self.lines[index] = LineKind::Text,
1545 (LineKind::Table(table), Some(at)) if at > 0 => {
1546 let split = line.start + at;
1547 self.splice(split..split, "\n", &[]);
1548 self.lines[index] = LineKind::Text;
1549 self.lines[index + 1] = LineKind::Table(table);
1550 cursor += usize::from(cursor > split);
1551 }
1552 (LineKind::Table(_), Some(_)) if line.len() > mark_length => {
1553 let split = line.start + mark_length;
1554 self.splice(split..split, "\n", &[]);
1555 cursor += usize::from(cursor > split);
1556 }
1557 (LineKind::Table(_), Some(_)) => {}
1558 (_, Some(at)) => {
1559 let mark = line.start + at..line.start + at + mark_length;
1560 self.splice(mark.clone(), "", &[]);
1561 cursor = map_offset(&[(mark, String::new())], cursor);
1562 continue;
1563 }
1564 (_, None) => {}
1565 }
1566 index += 1;
1567 }
1568 cursor
1569 }
1570
1365 /// List items whose marker was edited away become text; numbered items are renumbered.
1571 /// List items whose marker was edited away become text; numbered items are renumbered.
1366 fn repair(&mut self, mut cursor: usize) -> usize {
1572 fn repair(&mut self, cursor: usize) -> usize {
1573 let mut cursor = self.repair_tables(cursor);
1367 for index in 0..self.lines.len() {
1574 for index in 0..self.lines.len() {
1368 let kind = self.lines[index].clone();
1575 let kind = self.lines[index].clone();
1369 if !kind.is_list() {
1576 if !kind.is_list() {
@@ -1399,7 +1606,11 @@ fn marker_text(kind: &LineKind, number: u32) -> String {
1399 match kind {
1606 match kind {
1400 LineKind::Bullet(depth) => bullet_marker(*depth),
1607 LineKind::Bullet(depth) => bullet_marker(*depth),
1401 LineKind::Numbered(_) => format!("{number}. "),
1608 LineKind::Numbered(_) => format!("{number}. "),
1402 LineKind::Text | LineKind::Quote | LineKind::Code(_) => String::new(),
1609 LineKind::Text
1610 | LineKind::Quote
1611 | LineKind::Code(_)
1612 | LineKind::Heading(_)
1613 | LineKind::Table(_) => String::new(),
1403 }
1614 }
1404}
1615}
1405
1616
@@ -1430,7 +1641,9 @@ fn numbered_marker(line: &str) -> Option<(usize, u32)> {
1430fn line_shortcut(before: &str) -> Option<(LineKind, u32)> {
1641fn line_shortcut(before: &str) -> Option<(LineKind, u32)> {
1431 match before {
1642 match before {
1432 "- " | "* " => Some((LineKind::Bullet(0), 1)),
1643 "- " | "* " => Some((LineKind::Bullet(0), 1)),
1433 "> " => Some((LineKind::Quote, 1)),
1644 ">" => Some((LineKind::Quote, 1)),
1645 _ if before.starts_with('#') => heading_prefix(before)
1646 .and_then(|(level, rest)| rest.is_empty().then_some((LineKind::Heading(level), 1))),
1434 _ => {
1647 _ => {
1435 let digits = before.strip_suffix(". ")?;
1648 let digits = before.strip_suffix(". ")?;
1436 let all_digits = !digits.is_empty()
1649 let all_digits = !digits.is_empty()
@@ -1540,7 +1753,7 @@ fn typed_inline(before: &str) -> Option<(Range<usize>, Range<usize>, MarkKind)>
1540 let usable = !body[open + 1..].trim().is_empty() && !body[..open].ends_with('`');
1753 let usable = !body[open + 1..].trim().is_empty() && !body[..open].ends_with('`');
1541 return usable.then(|| (open..open + 1, body.len()..end, MarkKind::Code));
1754 return usable.then(|| (open..open + 1, body.len()..end, MarkKind::Code));
1542 }
1755 }
1543 for marker in ['*', '_'] {
1756 for (marker, kind) in [('*', MarkKind::Bold), ('_', MarkKind::Italic)] {
1544 if let Some(body) = before.strip_suffix(marker) {
1757 if let Some(body) = before.strip_suffix(marker) {
1545 if body.ends_with(marker) {
1758 if body.ends_with(marker) {
1546 return None;
1759 return None;
@@ -1548,7 +1761,7 @@ fn typed_inline(before: &str) -> Option<(Range<usize>, Range<usize>, MarkKind)>
1548 let open = body.rfind(marker)?;
1761 let open = body.rfind(marker)?;
1549 let opening_ok = !word_before(&body[..open]) && !body[..open].ends_with(marker);
1762 let opening_ok = !word_before(&body[..open]) && !body[..open].ends_with(marker);
1550 return (opening_ok && valid_inner(&body[open + 1..]))
1763 return (opening_ok && valid_inner(&body[open + 1..]))
1551 .then(|| (open..open + 1, body.len()..end, MarkKind::Italic));
1764 .then(|| (open..open + 1, body.len()..end, kind));
1552 }
1765 }
1553 }
1766 }
1554 None
1767 None
@@ -1702,10 +1915,16 @@ pub fn has_markdown(text: &str) -> bool {
1702}
1915}
1703
1916
1704fn markdown_lines(text: &str) -> Vec<DraftLine> {
1917fn markdown_lines(text: &str) -> Vec<DraftLine> {
1918 let sources: Vec<&str> = text
1919 .split('\n')
1920 .map(|raw| raw.strip_suffix('\r').unwrap_or(raw))
1921 .collect();
1705 let mut lines = Vec::new();
1922 let mut lines = Vec::new();
1706 let mut code: Option<Option<String>> = None;
1923 let mut code: Option<Option<String>> = None;
1707 for raw in text.split('\n') {
1924 let mut position = 0;
1708 let raw = raw.strip_suffix('\r').unwrap_or(raw);
1925 while position < sources.len() {
1926 let raw = sources[position];
1927 position += 1;
1709 let trimmed = raw.trim_start();
1928 let trimmed = raw.trim_start();
1710 if let Some(language) = &code {
1929 if let Some(language) = &code {
1711 if trimmed.starts_with(FENCE) && trimmed.trim_end() == FENCE {
1930 if trimmed.starts_with(FENCE) && trimmed.trim_end() == FENCE {
@@ -1727,12 +1946,23 @@ fn markdown_lines(text: &str) -> Vec<DraftLine> {
1727 code = Some(language);
1946 code = Some(language);
1728 continue;
1947 continue;
1729 }
1948 }
1949 if let Some((rows, consumed)) = markdown_table(&sources[position - 1..]) {
1950 let rows = rows
1951 .into_iter()
1952 .map(|row| row.iter().map(|cell| parse_inline(cell).0).collect())
1953 .collect();
1954 lines.push(table_line(Table::from_rows(rows)));
1955 position += consumed - 1;
1956 continue;
1957 }
1730 let indent: usize = raw[..raw.len() - trimmed.len()]
1958 let indent: usize = raw[..raw.len() - trimmed.len()]
1731 .chars()
1959 .chars()
1732 .map(|character| if character == '\t' { 4 } else { 1 })
1960 .map(|character| if character == '\t' { 4 } else { 1 })
1733 .sum();
1961 .sum();
1734 let depth = ((indent / MARKDOWN_INDENT) as u8).min(MAX_DEPTH);
1962 let depth = ((indent / MARKDOWN_INDENT) as u8).min(MAX_DEPTH);
1735 let (kind, number, content) = if let Some(rest) = PASTED_BULLETS
1963 let (kind, number, content) = if let Some((level, rest)) = heading_prefix(trimmed) {
1964 (LineKind::Heading(level), None, rest)
1965 } else if let Some(rest) = PASTED_BULLETS
1736 .iter()
1966 .iter()
1737 .find_map(|bullet| trimmed.strip_prefix(bullet))
1967 .find_map(|bullet| trimmed.strip_prefix(bullet))
1738 {
1968 {
@@ -1758,6 +1988,24 @@ fn markdown_lines(text: &str) -> Vec<DraftLine> {
1758 lines
1988 lines
1759}
1989}
1760
1990
1991fn table_line(table: Table) -> DraftLine {
1992 DraftLine {
1993 kind: LineKind::Table(table),
1994 number: None,
1995 content: TABLE_MARK.to_string(),
1996 marks: Vec::new(),
1997 }
1998}
1999
2000/// `# ` to `###### `: the level, capped at the three Teams offers, and the rest of the line.
2001fn heading_prefix(line: &str) -> Option<(u8, &str)> {
2002 let hashes = line.bytes().take_while(|byte| *byte == b'#').count();
2003 let rest = line[hashes..].strip_prefix(' ')?;
2004 (1..=6)
2005 .contains(&hashes)
2006 .then(|| ((hashes as u8).min(MAX_HEADING), rest))
2007}
2008
1761fn parse_inline(source: &str) -> (String, Vec<Mark>) {
2009fn parse_inline(source: &str) -> (String, Vec<Mark>) {
1762 let mut text = String::with_capacity(source.len());
2010 let mut text = String::with_capacity(source.len());
1763 let mut marks = Vec::new();
2011 let mut marks = Vec::new();
@@ -1849,6 +2097,17 @@ fn inline_at(rest: &str, previous: Option<char>) -> Option<(&str, usize, MarkKin
1849 None
2097 None
1850}
2098}
1851
2099
2100fn cell_text(spans: &[Span]) -> String {
2101 let mut builder = SpanLines::default();
2102 builder.walk(spans, &LineKind::Text, &[]);
2103 builder
2104 .finish()
2105 .into_iter()
2106 .map(|line| line.content)
2107 .collect::<Vec<_>>()
2108 .join("\n")
2109}
2110
1852#[derive(Default)]
2111#[derive(Default)]
1853struct SpanLines {
2112struct SpanLines {
1854 lines: Vec<DraftLine>,
2113 lines: Vec<DraftLine>,
@@ -1936,9 +2195,10 @@ impl SpanLines {
1936 };
2195 };
1937 self.start_line(&continued, None);
2196 self.start_line(&continued, None);
1938 }
2197 }
1939 Span::Heading { children, .. } => {
2198 Span::Heading { level, children } => {
1940 self.start_line(&LineKind::Text, None);
2199 let heading = LineKind::Heading((*level).clamp(1, MAX_HEADING));
1941 self.walk(children, &LineKind::Text, &with(MarkKind::Bold));
2200 self.start_line(&heading, None);
2201 self.walk(children, &heading, marks);
1942 self.open = false;
2202 self.open = false;
1943 }
2203 }
1944 Span::CodeBlock { language, code } => {
2204 Span::CodeBlock { language, code } => {
@@ -1977,15 +2237,11 @@ impl SpanLines {
1977 self.open = false;
2237 self.open = false;
1978 }
2238 }
1979 Span::Table { rows, .. } => {
2239 Span::Table { rows, .. } => {
1980 for row in rows {
2240 let rows = rows
1981 self.start_line(&LineKind::Text, None);
2241 .iter()
1982 for (position, cell) in row.iter().enumerate() {
2242 .map(|row| row.iter().map(|cell| cell_text(cell)).collect())
1983 if position > 0 {
2243 .collect();
1984 self.append(" | ", &LineKind::Text, &[]);
2244 self.lines.push(table_line(Table::from_rows(rows)));
1985 }
1986 self.walk(cell, &LineKind::Text, marks);
1987 }
1988 }
1989 self.open = false;
2245 self.open = false;
1990 }
2246 }
1991 Span::Image { .. } | Span::Quote { .. } => {}
2247 Span::Image { .. } | Span::Quote { .. } => {}
@@ -2081,7 +2337,7 @@ mod tests {
2081 draft.marks(),
2337 draft.marks(),
2082 [
2338 [
2083 mark(2..6, MarkKind::Bold),
2339 mark(2..6, MarkKind::Bold),
2084 mark(11..13, MarkKind::Italic),
2340 mark(11..13, MarkKind::Bold),
2085 mark(17..19, MarkKind::Italic),
2341 mark(17..19, MarkKind::Italic),
2086 mark(20..24, MarkKind::Strike),
2342 mark(20..24, MarkKind::Strike),
2087 mark(25..29, MarkKind::Code),
2343 mark(25..29, MarkKind::Code),
@@ -2357,9 +2613,12 @@ mod tests {
2357 let numbered = typed_draft("1. one");
2613 let numbered = typed_draft("1. one");
2358 assert_eq!(numbered.text(), "1. one");
2614 assert_eq!(numbered.text(), "1. one");
2359 assert_eq!(numbered.lines(), [LineKind::Numbered(0)]);
2615 assert_eq!(numbered.lines(), [LineKind::Numbered(0)]);
2360 let quote = typed_draft("> said");
2616 let quote = typed_draft(">said");
2361 assert_eq!(quote.text(), "said");
2617 assert_eq!(quote.text(), "said");
2362 assert_eq!(quote.lines(), [LineKind::Quote]);
2618 assert_eq!(quote.lines(), [LineKind::Quote]);
2619 let spaced = typed_draft("> said");
2620 assert_eq!(spaced.text(), " said");
2621 assert_eq!(spaced.lines(), [LineKind::Quote]);
2363 }
2622 }
2364
2623
2365 #[test]
2624 #[test]
crates/core/src/lib.rs +11 −10
@@ -48,12 +48,13 @@ mod receipts;
48 48 mod recording_rights;
49 49 mod remote;
50 50 mod scheduled;
51 mod skin_tone;
52 51 mod search;
53 52 mod server_search;
54 53 mod sidebar_sync;
54 mod skin_tone;
55 55 mod spans;
56 56 mod stored;
57 mod table;
57 58 mod time_zone;
58 59 mod translate_sync;
59 60 mod translation;
@@ -67,8 +68,7 @@ pub use adaptive_card::{
67 68 };
68 69 pub use avatars::Avatar;
69 70 pub use call_event::{
70 CallEvent, CallPhase, CallType, Recording, call_event, format_duration,
71 parse_duration_seconds,
71 CallEvent, CallPhase, CallType, Recording, call_event, format_duration, parse_duration_seconds,
72 72 };
73 73 pub use card_actions::{CardActionOutcome, DialogIdentity, TaskDialog, TaskDialogKind};
74 74 pub use card_chart::{
@@ -118,6 +118,10 @@ pub use folders::{
118 118 BoxFuture, ChatFolder, ChatsvcFolderSource, FolderChange, FolderKind, FolderSource,
119 119 store_section_settings, stored_section_settings,
120 120 };
121 pub use forwarded::{
122 FORWARD_LOADING_TEXT, FORWARD_UNAVAILABLE_TEXT, FORWARDED_CONTENT_TYPE, ForwardHeader,
123 ForwardInfo, ForwardState, forwarded_texts, forwards, is_forwarded,
124 };
121 125 pub use graph::{
122 126 DriveEntry, DriveFolder, FileReference, HostedImage, KeptAttachment, MentionTarget,
123 127 MessageExtras, SharedFile, UploadedFile,
@@ -144,19 +148,16 @@ pub use receipts::{ReceiptReader, ReceiptState};
144 148 pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};
145 149 pub use scheduled::NOTES_CHAT_ID;
146 150 pub use skin_tone::{skin_tone, store_account_skin_tone};
147 pub use forwarded::{
148 FORWARD_LOADING_TEXT, FORWARD_UNAVAILABLE_TEXT, FORWARDED_CONTENT_TYPE, ForwardHeader,
149 ForwardInfo, ForwardState, forwarded_texts, forwards, is_forwarded,
150 };
151 151 pub use spans::{FontSize, Span, html_to_spans};
152 152 pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};
153 153 pub use stored::{
154 154 AttachmentInfo, FileCard, FileKind, ImageKind, ImageRef, MentionInfo, PROFILE_LINK_PREFIX,
155 155 QuoteInfo, ReactionInfo, ReactionSummary, adaptive_cards, attachments, can_delete, can_edit,
156 card_texts, copy_text, files, images, linked_message_spans, linked_message_spans_with, mentions, message_quote,
157 message_spans, quote_html, quotes, reaction_summaries, reactions, readable_text, translated_spans,
158 user_mention_inputs,
156 card_texts, copy_text, files, images, linked_message_spans, linked_message_spans_with,
157 mentions, message_quote, message_spans, quote_html, quotes, reaction_summaries, reactions,
158 readable_text, translated_spans, user_mention_inputs,
159 159 };
160 pub use table::{Cell, PICKER_COLUMNS, PICKER_ROWS, TABLE_MARK, Table, TableEdit};
160 161 pub use time_zone::local_time;
161 162 pub use translation::{
162 163 FALLBACK_TARGET, LanguageStamp, confident_language, default_target, language_name, min_chars,
@@ -48,12 +48,13 @@ mod receipts;
48mod recording_rights;
48mod recording_rights;
49mod remote;
49mod remote;
50mod scheduled;
50mod scheduled;
51mod skin_tone;
52mod search;
51mod search;
53mod server_search;
52mod server_search;
54mod sidebar_sync;
53mod sidebar_sync;
54mod skin_tone;
55mod spans;
55mod spans;
56mod stored;
56mod stored;
57mod table;
57mod time_zone;
58mod time_zone;
58mod translate_sync;
59mod translate_sync;
59mod translation;
60mod translation;
@@ -67,8 +68,7 @@ pub use adaptive_card::{
67};
68};
68pub use avatars::Avatar;
69pub use avatars::Avatar;
69pub use call_event::{
70pub use call_event::{
70 CallEvent, CallPhase, CallType, Recording, call_event, format_duration,
71 CallEvent, CallPhase, CallType, Recording, call_event, format_duration, parse_duration_seconds,
71 parse_duration_seconds,
72};
72};
73pub use card_actions::{CardActionOutcome, DialogIdentity, TaskDialog, TaskDialogKind};
73pub use card_actions::{CardActionOutcome, DialogIdentity, TaskDialog, TaskDialogKind};
74pub use card_chart::{
74pub use card_chart::{
@@ -118,6 +118,10 @@ pub use folders::{
118 BoxFuture, ChatFolder, ChatsvcFolderSource, FolderChange, FolderKind, FolderSource,
118 BoxFuture, ChatFolder, ChatsvcFolderSource, FolderChange, FolderKind, FolderSource,
119 store_section_settings, stored_section_settings,
119 store_section_settings, stored_section_settings,
120};
120};
121pub use forwarded::{
122 FORWARD_LOADING_TEXT, FORWARD_UNAVAILABLE_TEXT, FORWARDED_CONTENT_TYPE, ForwardHeader,
123 ForwardInfo, ForwardState, forwarded_texts, forwards, is_forwarded,
124};
121pub use graph::{
125pub use graph::{
122 DriveEntry, DriveFolder, FileReference, HostedImage, KeptAttachment, MentionTarget,
126 DriveEntry, DriveFolder, FileReference, HostedImage, KeptAttachment, MentionTarget,
123 MessageExtras, SharedFile, UploadedFile,
127 MessageExtras, SharedFile, UploadedFile,
@@ -144,19 +148,16 @@ pub use receipts::{ReceiptReader, ReceiptState};
144pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};
148pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};
145pub use scheduled::NOTES_CHAT_ID;
149pub use scheduled::NOTES_CHAT_ID;
146pub use skin_tone::{skin_tone, store_account_skin_tone};
150pub use skin_tone::{skin_tone, store_account_skin_tone};
147pub use forwarded::{
148 FORWARD_LOADING_TEXT, FORWARD_UNAVAILABLE_TEXT, FORWARDED_CONTENT_TYPE, ForwardHeader,
149 ForwardInfo, ForwardState, forwarded_texts, forwards, is_forwarded,
150};
151pub use spans::{FontSize, Span, html_to_spans};
151pub use spans::{FontSize, Span, html_to_spans};
152pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};
152pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};
153pub use stored::{
153pub use stored::{
154 AttachmentInfo, FileCard, FileKind, ImageKind, ImageRef, MentionInfo, PROFILE_LINK_PREFIX,
154 AttachmentInfo, FileCard, FileKind, ImageKind, ImageRef, MentionInfo, PROFILE_LINK_PREFIX,
155 QuoteInfo, ReactionInfo, ReactionSummary, adaptive_cards, attachments, can_delete, can_edit,
155 QuoteInfo, ReactionInfo, ReactionSummary, adaptive_cards, attachments, can_delete, can_edit,
156 card_texts, copy_text, files, images, linked_message_spans, linked_message_spans_with, mentions, message_quote,
156 card_texts, copy_text, files, images, linked_message_spans, linked_message_spans_with,
157 message_spans, quote_html, quotes, reaction_summaries, reactions, readable_text, translated_spans,
157 mentions, message_quote, message_spans, quote_html, quotes, reaction_summaries, reactions,
158 user_mention_inputs,
158 readable_text, translated_spans, user_mention_inputs,
159};
159};
160pub use table::{Cell, PICKER_COLUMNS, PICKER_ROWS, TABLE_MARK, Table, TableEdit};
160pub use time_zone::local_time;
161pub use time_zone::local_time;
161pub use translation::{
162pub use translation::{
162 FALLBACK_TARGET, LanguageStamp, confident_language, default_target, language_name, min_chars,
163 FALLBACK_TARGET, LanguageStamp, confident_language, default_target, language_name, min_chars,
crates/core/src/mapping.rs +25 −12
@@ -10,8 +10,6 @@ use crate::markdown::plain_text_to_html;
10 10 use crate::preview::OwnedPreview;
11 11 use crate::stored::{AttachmentInfo, MentionInfo, QuoteInfo, ReactionInfo};
12 12
13 const NO_NAME: &str = "?";
14
15 13 pub fn graph_hidden(chat: &Chat) -> bool {
16 14 chat.viewpoint
17 15 .as_ref()
@@ -49,7 +47,7 @@ pub fn chat_record(chat: &Chat, my_user_id: &str) -> ChatRecord {
49 47 title: chat.title(my_user_id),
50 48 member_summary: others
51 49 .iter()
52 .map(|member| member_name(member))
50 .map(|member| member.name())
53 51 .collect::<Vec<_>>()
54 52 .join(", "),
55 53 last_message_at,
@@ -62,7 +60,7 @@ pub fn chat_record(chat: &Chat, my_user_id: &str) -> ChatRecord {
62 60 .iter()
63 61 .map(|member| MemberRecord {
64 62 user_id: member.user_id.clone(),
65 display_name: member_name(member).to_owned(),
63 display_name: member.name().to_owned(),
66 64 })
67 65 .collect(),
68 66 last_message_deleted: preview.as_ref().is_some_and(|preview| preview.deleted),
@@ -78,14 +76,6 @@ pub fn chat_record(chat: &Chat, my_user_id: &str) -> ChatRecord {
78 76 }
79 77 }
80 78
81 fn member_name(member: &graph::Member) -> &str {
82 member
83 .display_name
84 .as_deref()
85 .or(member.email.as_deref())
86 .unwrap_or(NO_NAME)
87 }
88
89 79 fn is_unread(
90 80 last_message: Option<DateTime<Utc>>,
91 81 last_read: Option<DateTime<Utc>>,
@@ -350,6 +340,29 @@ mod tests {
350 340 assert!(!record.last_event_system);
351 341 }
352 342
343 #[test]
344 fn a_member_without_name_or_email_is_an_unknown_user() {
345 let chat: Chat = serde_json::from_value(json!({
346 "id": "19:group@thread.v2",
347 "chatType": "group",
348 "members": [
349 {"userId": "me", "displayName": "Daniel"},
350 {"userId": "gone", "displayName": null, "email": ""},
351 {"userId": "mail", "displayName": " ", "email": "anna@example.com"},
352 ],
353 }))
354 .unwrap();
355 let record = chat_record(&chat, "me");
356 let names: Vec<&str> = record
357 .members
358 .iter()
359 .map(|member| member.display_name.as_str())
360 .collect();
361 assert_eq!(names, ["Daniel", "Unknown User", "anna@example.com"]);
362 assert_eq!(record.title, "Unknown User, anna@example.com");
363 assert_eq!(graph::UNKNOWN_USER_NAME, store::UNKNOWN_USER_NAME);
364 }
365
353 366 fn record_with_subject(subject: serde_json::Value) -> Option<String> {
354 367 let message: Message = serde_json::from_value(json!({
355 368 "id": "1",
@@ -10,8 +10,6 @@ use crate::markdown::plain_text_to_html;
10use crate::preview::OwnedPreview;
10use crate::preview::OwnedPreview;
11use crate::stored::{AttachmentInfo, MentionInfo, QuoteInfo, ReactionInfo};
11use crate::stored::{AttachmentInfo, MentionInfo, QuoteInfo, ReactionInfo};
12
12
13const NO_NAME: &str = "?";
14
15pub fn graph_hidden(chat: &Chat) -> bool {
13pub fn graph_hidden(chat: &Chat) -> bool {
16 chat.viewpoint
14 chat.viewpoint
17 .as_ref()
15 .as_ref()
@@ -49,7 +47,7 @@ pub fn chat_record(chat: &Chat, my_user_id: &str) -> ChatRecord {
49 title: chat.title(my_user_id),
47 title: chat.title(my_user_id),
50 member_summary: others
48 member_summary: others
51 .iter()
49 .iter()
52 .map(|member| member_name(member))
50 .map(|member| member.name())
53 .collect::<Vec<_>>()
51 .collect::<Vec<_>>()
54 .join(", "),
52 .join(", "),
55 last_message_at,
53 last_message_at,
@@ -62,7 +60,7 @@ pub fn chat_record(chat: &Chat, my_user_id: &str) -> ChatRecord {
62 .iter()
60 .iter()
63 .map(|member| MemberRecord {
61 .map(|member| MemberRecord {
64 user_id: member.user_id.clone(),
62 user_id: member.user_id.clone(),
65 display_name: member_name(member).to_owned(),
63 display_name: member.name().to_owned(),
66 })
64 })
67 .collect(),
65 .collect(),
68 last_message_deleted: preview.as_ref().is_some_and(|preview| preview.deleted),
66 last_message_deleted: preview.as_ref().is_some_and(|preview| preview.deleted),
@@ -78,14 +76,6 @@ pub fn chat_record(chat: &Chat, my_user_id: &str) -> ChatRecord {
78 }
76 }
79}
77}
80
78
81fn member_name(member: &graph::Member) -> &str {
82 member
83 .display_name
84 .as_deref()
85 .or(member.email.as_deref())
86 .unwrap_or(NO_NAME)
87}
88
89fn is_unread(
79fn is_unread(
90 last_message: Option<DateTime<Utc>>,
80 last_message: Option<DateTime<Utc>>,
91 last_read: Option<DateTime<Utc>>,
81 last_read: Option<DateTime<Utc>>,
@@ -350,6 +340,29 @@ mod tests {
350 assert!(!record.last_event_system);
340 assert!(!record.last_event_system);
351 }
341 }
352
342
343 #[test]
344 fn a_member_without_name_or_email_is_an_unknown_user() {
345 let chat: Chat = serde_json::from_value(json!({
346 "id": "19:group@thread.v2",
347 "chatType": "group",
348 "members": [
349 {"userId": "me", "displayName": "Daniel"},
350 {"userId": "gone", "displayName": null, "email": ""},
351 {"userId": "mail", "displayName": " ", "email": "anna@example.com"},
352 ],
353 }))
354 .unwrap();
355 let record = chat_record(&chat, "me");
356 let names: Vec<&str> = record
357 .members
358 .iter()
359 .map(|member| member.display_name.as_str())
360 .collect();
361 assert_eq!(names, ["Daniel", "Unknown User", "anna@example.com"]);
362 assert_eq!(record.title, "Unknown User, anna@example.com");
363 assert_eq!(graph::UNKNOWN_USER_NAME, store::UNKNOWN_USER_NAME);
364 }
365
353 fn record_with_subject(subject: serde_json::Value) -> Option<String> {
366 fn record_with_subject(subject: serde_json::Value) -> Option<String> {
354 let message: Message = serde_json::from_value(json!({
367 let message: Message = serde_json::from_value(json!({
355 "id": "1",
368 "id": "1",
crates/core/src/table.rs added +353 −0
@@ -0,0 +1,353 @@
1 use serde::{Deserialize, Serialize};
2
3 use crate::markdown::escape_html;
4
5 pub const TABLE_MARK: char = '\u{FFFB}';
6 pub const PICKER_COLUMNS: usize = 7;
7 pub const PICKER_ROWS: usize = 5;
8 const EMPTY_CELL: &str = "&nbsp;";
9
10 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11 pub struct Cell {
12 pub row: usize,
13 pub column: usize,
14 }
15
16 impl Cell {
17 pub fn new(row: usize, column: usize) -> Cell {
18 Cell { row, column }
19 }
20 }
21
22 /// A composer table: plain text cells, every row as wide as the first.
23 #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
24 pub struct Table {
25 pub rows: Vec<Vec<String>>,
26 }
27
28 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
29 pub enum TableEdit {
30 InsertRowAbove,
31 InsertRowBelow,
32 InsertColumnLeft,
33 InsertColumnRight,
34 DeleteRow,
35 DeleteColumn,
36 DeleteTable,
37 }
38
39 impl TableEdit {
40 pub const INSERTS: [TableEdit; 4] = [
41 TableEdit::InsertRowAbove,
42 TableEdit::InsertRowBelow,
43 TableEdit::InsertColumnLeft,
44 TableEdit::InsertColumnRight,
45 ];
46 pub const DELETES: [TableEdit; 3] = [
47 TableEdit::DeleteRow,
48 TableEdit::DeleteColumn,
49 TableEdit::DeleteTable,
50 ];
51
52 pub fn label(self) -> &'static str {
53 match self {
54 TableEdit::InsertRowAbove => "Insert row above",
55 TableEdit::InsertRowBelow => "Insert row below",
56 TableEdit::InsertColumnLeft => "Insert column to the left",
57 TableEdit::InsertColumnRight => "Insert column to the right",
58 TableEdit::DeleteRow => "Delete row",
59 TableEdit::DeleteColumn => "Delete column",
60 TableEdit::DeleteTable => "Delete table",
61 }
62 }
63 }
64
65 impl Table {
66 pub fn new(rows: usize, columns: usize) -> Table {
67 Table {
68 rows: vec![vec![String::new(); columns.max(1)]; rows.max(1)],
69 }
70 }
71
72 /// Short rows are filled up to the widest one.
73 pub fn from_rows(mut rows: Vec<Vec<String>>) -> Table {
74 rows.retain(|row| !row.is_empty());
75 let columns = rows.iter().map(Vec::len).max().unwrap_or(1);
76 for row in &mut rows {
77 row.resize(columns, String::new());
78 }
79 if rows.is_empty() {
80 return Table::new(1, 1);
81 }
82 Table { rows }
83 }
84
85 pub fn row_count(&self) -> usize {
86 self.rows.len()
87 }
88
89 pub fn column_count(&self) -> usize {
90 self.rows.first().map_or(0, Vec::len)
91 }
92
93 pub fn cell(&self, cell: Cell) -> Option<&str> {
94 self.rows
95 .get(cell.row)?
96 .get(cell.column)
97 .map(String::as_str)
98 }
99
100 pub fn set_cell(&mut self, cell: Cell, text: &str) {
101 if let Some(slot) = self
102 .rows
103 .get_mut(cell.row)
104 .and_then(|row| row.get_mut(cell.column))
105 {
106 *slot = text.to_owned();
107 }
108 }
109
110 pub fn last_cell(&self) -> Cell {
111 Cell::new(self.row_count() - 1, self.column_count() - 1)
112 }
113
114 /// Tab: the next cell, and past the last one a new row (`true`) like Teams.
115 pub fn next_cell(&mut self, cell: Cell) -> (Cell, bool) {
116 if cell.column + 1 < self.column_count() {
117 return (Cell::new(cell.row, cell.column + 1), false);
118 }
119 if cell.row + 1 < self.row_count() {
120 return (Cell::new(cell.row + 1, 0), false);
121 }
122 self.rows.push(vec![String::new(); self.column_count()]);
123 (Cell::new(cell.row + 1, 0), true)
124 }
125
126 /// Shift+Tab: the previous cell; the first cell stays.
127 pub fn previous_cell(&self, cell: Cell) -> Cell {
128 match (cell.row, cell.column) {
129 (_, column) if column > 0 => Cell::new(cell.row, column - 1),
130 (0, _) => cell,
131 (row, _) => Cell::new(row - 1, self.column_count() - 1),
132 }
133 }
134
135 /// The cell to focus afterwards; `None` when the table is gone.
136 pub fn apply(&mut self, edit: TableEdit, cell: Cell) -> Option<Cell> {
137 let columns = self.column_count();
138 match edit {
139 TableEdit::InsertRowAbove => {
140 self.rows.insert(cell.row, vec![String::new(); columns]);
141 Some(Cell::new(cell.row, cell.column))
142 }
143 TableEdit::InsertRowBelow => {
144 self.rows.insert(cell.row + 1, vec![String::new(); columns]);
145 Some(Cell::new(cell.row + 1, cell.column))
146 }
147 TableEdit::InsertColumnLeft => {
148 for row in &mut self.rows {
149 row.insert(cell.column, String::new());
150 }
151 Some(Cell::new(cell.row, cell.column))
152 }
153 TableEdit::InsertColumnRight => {
154 for row in &mut self.rows {
155 row.insert(cell.column + 1, String::new());
156 }
157 Some(Cell::new(cell.row, cell.column + 1))
158 }
159 TableEdit::DeleteRow if self.row_count() > 1 => {
160 self.rows.remove(cell.row);
161 Some(Cell::new(cell.row.min(self.row_count() - 1), cell.column))
162 }
163 TableEdit::DeleteColumn if columns > 1 => {
164 for row in &mut self.rows {
165 row.remove(cell.column);
166 }
167 Some(Cell::new(
168 cell.row,
169 cell.column.min(self.column_count() - 1),
170 ))
171 }
172 TableEdit::DeleteRow | TableEdit::DeleteColumn | TableEdit::DeleteTable => None,
173 }
174 }
175
176 pub fn is_blank(&self) -> bool {
177 self.rows
178 .iter()
179 .flatten()
180 .all(|cell| cell.trim().is_empty())
181 }
182
183 /// Rows on lines, cells split by tabs: what a spreadsheet pastes.
184 pub fn plain_text(&self) -> String {
185 self.rows
186 .iter()
187 .map(|row| row.join("\t").replace('\n', " "))
188 .collect::<Vec<_>>()
189 .join("\n")
190 }
191
192 /// The table Teams sends: CKEditor's `figure.table`, `copy-paste-table` on the table, a one
193 /// line cell without `<p>`, every line of a longer cell in its own `<p>`, empty `&nbsp;`.
194 pub fn to_html(&self) -> String {
195 let mut html =
196 String::from("<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>");
197 for row in &self.rows {
198 html.push_str("<tr>");
199 for cell in row {
200 html.push_str("<td>");
201 if cell.trim().is_empty() {
202 html.push_str(EMPTY_CELL);
203 } else if !cell.contains('\n') {
204 html.push_str(&escape_html(cell));
205 } else {
206 for line in cell.split('\n') {
207 html.push_str("<p>");
208 if line.trim().is_empty() {
209 html.push_str(EMPTY_CELL);
210 } else {
211 html.push_str(&escape_html(line));
212 }
213 html.push_str("</p>");
214 }
215 }
216 html.push_str("</td>");
217 }
218 html.push_str("</tr>");
219 }
220 html.push_str("</tbody></table></figure>");
221 html
222 }
223 }
224
225 fn split_row(line: &str) -> Option<Vec<String>> {
226 let trimmed = line.trim();
227 if !trimmed.contains('|') {
228 return None;
229 }
230 let inner = trimmed.strip_prefix('|').unwrap_or(trimmed);
231 let inner = inner.strip_suffix('|').unwrap_or(inner);
232 let mut cells = Vec::new();
233 let mut current = String::new();
234 let mut characters = inner.chars().peekable();
235 while let Some(character) = characters.next() {
236 match character {
237 '\\' if characters.peek() == Some(&'|') => {
238 current.push('|');
239 characters.next();
240 }
241 '|' => cells.push(std::mem::take(&mut current).trim().to_owned()),
242 other => current.push(other),
243 }
244 }
245 cells.push(current.trim().to_owned());
246 Some(cells)
247 }
248
249 fn is_delimiter_row(line: &str) -> bool {
250 split_row(line).is_some_and(|cells| {
251 cells.iter().all(|cell| {
252 let dashes = cell.trim_start_matches(':').trim_end_matches(':');
253 !dashes.is_empty() && dashes.chars().all(|character| character == '-')
254 })
255 })
256 }
257
258 /// A GitHub markdown table at the start of `lines`: header, delimiter row, body rows.
259 /// Returns the raw cell sources and how many lines it spans.
260 pub(crate) fn markdown_table(lines: &[&str]) -> Option<(Vec<Vec<String>>, usize)> {
261 let header = split_row(lines.first()?)?;
262 if !lines.get(1).is_some_and(|line| is_delimiter_row(line)) {
263 return None;
264 }
265 let delimiter_columns = split_row(lines[1])?.len();
266 if delimiter_columns != header.len() {
267 return None;
268 }
269 let mut rows = vec![header];
270 let mut consumed = 2;
271 for line in &lines[2..] {
272 match split_row(line) {
273 Some(cells) if !line.trim().is_empty() => rows.push(cells),
274 _ => break,
275 }
276 consumed += 1;
277 }
278 Some((rows, consumed))
279 }
280
281 #[cfg(test)]
282 mod tests {
283 use super::*;
284
285 #[test]
286 fn tab_walks_the_cells_and_adds_a_row_after_the_last() {
287 let mut table = Table::new(2, 2);
288 assert_eq!(table.next_cell(Cell::new(0, 0)), (Cell::new(0, 1), false));
289 assert_eq!(table.next_cell(Cell::new(0, 1)), (Cell::new(1, 0), false));
290 assert_eq!(table.next_cell(Cell::new(1, 1)), (Cell::new(2, 0), true));
291 assert_eq!(table.row_count(), 3);
292 assert_eq!(table.column_count(), 2);
293 }
294
295 #[test]
296 fn shift_tab_walks_back_and_stops_at_the_first_cell() {
297 let table = Table::new(2, 3);
298 assert_eq!(table.previous_cell(Cell::new(1, 0)), Cell::new(0, 2));
299 assert_eq!(table.previous_cell(Cell::new(0, 1)), Cell::new(0, 0));
300 assert_eq!(table.previous_cell(Cell::new(0, 0)), Cell::new(0, 0));
301 }
302
303 #[test]
304 fn rows_and_columns_insert_and_delete_around_the_cell() {
305 let mut table = Table::from_rows(vec![
306 vec!["a".into(), "b".into()],
307 vec!["c".into(), "d".into()],
308 ]);
309 assert_eq!(
310 table.apply(TableEdit::InsertRowAbove, Cell::new(1, 1)),
311 Some(Cell::new(1, 1))
312 );
313 assert_eq!(table.rows[1], ["", ""]);
314 assert_eq!(
315 table.apply(TableEdit::InsertColumnRight, Cell::new(0, 0)),
316 Some(Cell::new(0, 1))
317 );
318 assert_eq!(table.rows[0], ["a", "", "b"]);
319 table.apply(TableEdit::DeleteColumn, Cell::new(0, 1));
320 table.apply(TableEdit::DeleteRow, Cell::new(1, 0));
321 assert_eq!(table.rows, [["a", "b"], ["c", "d"]]);
322 assert_eq!(table.apply(TableEdit::DeleteTable, Cell::new(0, 0)), None);
323 }
324
325 #[test]
326 fn deleting_the_last_row_or_column_deletes_the_table() {
327 let mut table = Table::new(1, 2);
328 assert_eq!(table.apply(TableEdit::DeleteRow, Cell::new(0, 0)), None);
329 let mut table = Table::new(2, 1);
330 assert_eq!(table.apply(TableEdit::DeleteColumn, Cell::new(0, 0)), None);
331 }
332
333 #[test]
334 fn html_is_the_copy_paste_table_teams_sends() {
335 let table = Table::from_rows(vec![vec!["a<b".into(), String::new()], vec!["x\ny".into()]]);
336 assert_eq!(
337 table.to_html(),
338 "<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\
339 <tr><td>a&lt;b</td><td>&nbsp;</td></tr>\
340 <tr><td><p>x</p><p>y</p></td><td>&nbsp;</td></tr></tbody></table></figure>"
341 );
342 }
343
344 #[test]
345 fn markdown_tables_need_a_delimiter_row() {
346 let lines = ["| A | B |", "|---|:-:|", "| 1 | 2 \\| 3 |", "", "after"];
347 let (rows, consumed) = markdown_table(&lines).unwrap();
348 assert_eq!(consumed, 3);
349 assert_eq!(rows, [["A", "B"], ["1", "2 | 3"]]);
350 assert!(markdown_table(&["a | b", "c | d"]).is_none());
351 assert!(markdown_table(&["| a | b |", "|---|"]).is_none());
352 }
353 }
@@ -0,0 +1,353 @@
1use serde::{Deserialize, Serialize};
2
3use crate::markdown::escape_html;
4
5pub const TABLE_MARK: char = '\u{FFFB}';
6pub const PICKER_COLUMNS: usize = 7;
7pub const PICKER_ROWS: usize = 5;
8const EMPTY_CELL: &str = "&nbsp;";
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11pub struct Cell {
12 pub row: usize,
13 pub column: usize,
14}
15
16impl Cell {
17 pub fn new(row: usize, column: usize) -> Cell {
18 Cell { row, column }
19 }
20}
21
22/// A composer table: plain text cells, every row as wide as the first.
23#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
24pub struct Table {
25 pub rows: Vec<Vec<String>>,
26}
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum TableEdit {
30 InsertRowAbove,
31 InsertRowBelow,
32 InsertColumnLeft,
33 InsertColumnRight,
34 DeleteRow,
35 DeleteColumn,
36 DeleteTable,
37}
38
39impl TableEdit {
40 pub const INSERTS: [TableEdit; 4] = [
41 TableEdit::InsertRowAbove,
42 TableEdit::InsertRowBelow,
43 TableEdit::InsertColumnLeft,
44 TableEdit::InsertColumnRight,
45 ];
46 pub const DELETES: [TableEdit; 3] = [
47 TableEdit::DeleteRow,
48 TableEdit::DeleteColumn,
49 TableEdit::DeleteTable,
50 ];
51
52 pub fn label(self) -> &'static str {
53 match self {
54 TableEdit::InsertRowAbove => "Insert row above",
55 TableEdit::InsertRowBelow => "Insert row below",
56 TableEdit::InsertColumnLeft => "Insert column to the left",
57 TableEdit::InsertColumnRight => "Insert column to the right",
58 TableEdit::DeleteRow => "Delete row",
59 TableEdit::DeleteColumn => "Delete column",
60 TableEdit::DeleteTable => "Delete table",
61 }
62 }
63}
64
65impl Table {
66 pub fn new(rows: usize, columns: usize) -> Table {
67 Table {
68 rows: vec![vec![String::new(); columns.max(1)]; rows.max(1)],
69 }
70 }
71
72 /// Short rows are filled up to the widest one.
73 pub fn from_rows(mut rows: Vec<Vec<String>>) -> Table {
74 rows.retain(|row| !row.is_empty());
75 let columns = rows.iter().map(Vec::len).max().unwrap_or(1);
76 for row in &mut rows {
77 row.resize(columns, String::new());
78 }
79 if rows.is_empty() {
80 return Table::new(1, 1);
81 }
82 Table { rows }
83 }
84
85 pub fn row_count(&self) -> usize {
86 self.rows.len()
87 }
88
89 pub fn column_count(&self) -> usize {
90 self.rows.first().map_or(0, Vec::len)
91 }
92
93 pub fn cell(&self, cell: Cell) -> Option<&str> {
94 self.rows
95 .get(cell.row)?
96 .get(cell.column)
97 .map(String::as_str)
98 }
99
100 pub fn set_cell(&mut self, cell: Cell, text: &str) {
101 if let Some(slot) = self
102 .rows
103 .get_mut(cell.row)
104 .and_then(|row| row.get_mut(cell.column))
105 {
106 *slot = text.to_owned();
107 }
108 }
109
110 pub fn last_cell(&self) -> Cell {
111 Cell::new(self.row_count() - 1, self.column_count() - 1)
112 }
113
114 /// Tab: the next cell, and past the last one a new row (`true`) like Teams.
115 pub fn next_cell(&mut self, cell: Cell) -> (Cell, bool) {
116 if cell.column + 1 < self.column_count() {
117 return (Cell::new(cell.row, cell.column + 1), false);
118 }
119 if cell.row + 1 < self.row_count() {
120 return (Cell::new(cell.row + 1, 0), false);
121 }
122 self.rows.push(vec![String::new(); self.column_count()]);
123 (Cell::new(cell.row + 1, 0), true)
124 }
125
126 /// Shift+Tab: the previous cell; the first cell stays.
127 pub fn previous_cell(&self, cell: Cell) -> Cell {
128 match (cell.row, cell.column) {
129 (_, column) if column > 0 => Cell::new(cell.row, column - 1),
130 (0, _) => cell,
131 (row, _) => Cell::new(row - 1, self.column_count() - 1),
132 }
133 }
134
135 /// The cell to focus afterwards; `None` when the table is gone.
136 pub fn apply(&mut self, edit: TableEdit, cell: Cell) -> Option<Cell> {
137 let columns = self.column_count();
138 match edit {
139 TableEdit::InsertRowAbove => {
140 self.rows.insert(cell.row, vec![String::new(); columns]);
141 Some(Cell::new(cell.row, cell.column))
142 }
143 TableEdit::InsertRowBelow => {
144 self.rows.insert(cell.row + 1, vec![String::new(); columns]);
145 Some(Cell::new(cell.row + 1, cell.column))
146 }
147 TableEdit::InsertColumnLeft => {
148 for row in &mut self.rows {
149 row.insert(cell.column, String::new());
150 }
151 Some(Cell::new(cell.row, cell.column))
152 }
153 TableEdit::InsertColumnRight => {
154 for row in &mut self.rows {
155 row.insert(cell.column + 1, String::new());
156 }
157 Some(Cell::new(cell.row, cell.column + 1))
158 }
159 TableEdit::DeleteRow if self.row_count() > 1 => {
160 self.rows.remove(cell.row);
161 Some(Cell::new(cell.row.min(self.row_count() - 1), cell.column))
162 }
163 TableEdit::DeleteColumn if columns > 1 => {
164 for row in &mut self.rows {
165 row.remove(cell.column);
166 }
167 Some(Cell::new(
168 cell.row,
169 cell.column.min(self.column_count() - 1),
170 ))
171 }
172 TableEdit::DeleteRow | TableEdit::DeleteColumn | TableEdit::DeleteTable => None,
173 }
174 }
175
176 pub fn is_blank(&self) -> bool {
177 self.rows
178 .iter()
179 .flatten()
180 .all(|cell| cell.trim().is_empty())
181 }
182
183 /// Rows on lines, cells split by tabs: what a spreadsheet pastes.
184 pub fn plain_text(&self) -> String {
185 self.rows
186 .iter()
187 .map(|row| row.join("\t").replace('\n', " "))
188 .collect::<Vec<_>>()
189 .join("\n")
190 }
191
192 /// The table Teams sends: CKEditor's `figure.table`, `copy-paste-table` on the table, a one
193 /// line cell without `<p>`, every line of a longer cell in its own `<p>`, empty `&nbsp;`.
194 pub fn to_html(&self) -> String {
195 let mut html =
196 String::from("<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>");
197 for row in &self.rows {
198 html.push_str("<tr>");
199 for cell in row {
200 html.push_str("<td>");
201 if cell.trim().is_empty() {
202 html.push_str(EMPTY_CELL);
203 } else if !cell.contains('\n') {
204 html.push_str(&escape_html(cell));
205 } else {
206 for line in cell.split('\n') {
207 html.push_str("<p>");
208 if line.trim().is_empty() {
209 html.push_str(EMPTY_CELL);
210 } else {
211 html.push_str(&escape_html(line));
212 }
213 html.push_str("</p>");
214 }
215 }
216 html.push_str("</td>");
217 }
218 html.push_str("</tr>");
219 }
220 html.push_str("</tbody></table></figure>");
221 html
222 }
223}
224
225fn split_row(line: &str) -> Option<Vec<String>> {
226 let trimmed = line.trim();
227 if !trimmed.contains('|') {
228 return None;
229 }
230 let inner = trimmed.strip_prefix('|').unwrap_or(trimmed);
231 let inner = inner.strip_suffix('|').unwrap_or(inner);
232 let mut cells = Vec::new();
233 let mut current = String::new();
234 let mut characters = inner.chars().peekable();
235 while let Some(character) = characters.next() {
236 match character {
237 '\\' if characters.peek() == Some(&'|') => {
238 current.push('|');
239 characters.next();
240 }
241 '|' => cells.push(std::mem::take(&mut current).trim().to_owned()),
242 other => current.push(other),
243 }
244 }
245 cells.push(current.trim().to_owned());
246 Some(cells)
247}
248
249fn is_delimiter_row(line: &str) -> bool {
250 split_row(line).is_some_and(|cells| {
251 cells.iter().all(|cell| {
252 let dashes = cell.trim_start_matches(':').trim_end_matches(':');
253 !dashes.is_empty() && dashes.chars().all(|character| character == '-')
254 })
255 })
256}
257
258/// A GitHub markdown table at the start of `lines`: header, delimiter row, body rows.
259/// Returns the raw cell sources and how many lines it spans.
260pub(crate) fn markdown_table(lines: &[&str]) -> Option<(Vec<Vec<String>>, usize)> {
261 let header = split_row(lines.first()?)?;
262 if !lines.get(1).is_some_and(|line| is_delimiter_row(line)) {
263 return None;
264 }
265 let delimiter_columns = split_row(lines[1])?.len();
266 if delimiter_columns != header.len() {
267 return None;
268 }
269 let mut rows = vec![header];
270 let mut consumed = 2;
271 for line in &lines[2..] {
272 match split_row(line) {
273 Some(cells) if !line.trim().is_empty() => rows.push(cells),
274 _ => break,
275 }
276 consumed += 1;
277 }
278 Some((rows, consumed))
279}
280
281#[cfg(test)]
282mod tests {
283 use super::*;
284
285 #[test]
286 fn tab_walks_the_cells_and_adds_a_row_after_the_last() {
287 let mut table = Table::new(2, 2);
288 assert_eq!(table.next_cell(Cell::new(0, 0)), (Cell::new(0, 1), false));
289 assert_eq!(table.next_cell(Cell::new(0, 1)), (Cell::new(1, 0), false));
290 assert_eq!(table.next_cell(Cell::new(1, 1)), (Cell::new(2, 0), true));
291 assert_eq!(table.row_count(), 3);
292 assert_eq!(table.column_count(), 2);
293 }
294
295 #[test]
296 fn shift_tab_walks_back_and_stops_at_the_first_cell() {
297 let table = Table::new(2, 3);
298 assert_eq!(table.previous_cell(Cell::new(1, 0)), Cell::new(0, 2));
299 assert_eq!(table.previous_cell(Cell::new(0, 1)), Cell::new(0, 0));
300 assert_eq!(table.previous_cell(Cell::new(0, 0)), Cell::new(0, 0));
301 }
302
303 #[test]
304 fn rows_and_columns_insert_and_delete_around_the_cell() {
305 let mut table = Table::from_rows(vec![
306 vec!["a".into(), "b".into()],
307 vec!["c".into(), "d".into()],
308 ]);
309 assert_eq!(
310 table.apply(TableEdit::InsertRowAbove, Cell::new(1, 1)),
311 Some(Cell::new(1, 1))
312 );
313 assert_eq!(table.rows[1], ["", ""]);
314 assert_eq!(
315 table.apply(TableEdit::InsertColumnRight, Cell::new(0, 0)),
316 Some(Cell::new(0, 1))
317 );
318 assert_eq!(table.rows[0], ["a", "", "b"]);
319 table.apply(TableEdit::DeleteColumn, Cell::new(0, 1));
320 table.apply(TableEdit::DeleteRow, Cell::new(1, 0));
321 assert_eq!(table.rows, [["a", "b"], ["c", "d"]]);
322 assert_eq!(table.apply(TableEdit::DeleteTable, Cell::new(0, 0)), None);
323 }
324
325 #[test]
326 fn deleting_the_last_row_or_column_deletes_the_table() {
327 let mut table = Table::new(1, 2);
328 assert_eq!(table.apply(TableEdit::DeleteRow, Cell::new(0, 0)), None);
329 let mut table = Table::new(2, 1);
330 assert_eq!(table.apply(TableEdit::DeleteColumn, Cell::new(0, 0)), None);
331 }
332
333 #[test]
334 fn html_is_the_copy_paste_table_teams_sends() {
335 let table = Table::from_rows(vec![vec!["a<b".into(), String::new()], vec!["x\ny".into()]]);
336 assert_eq!(
337 table.to_html(),
338 "<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\
339 <tr><td>a&lt;b</td><td>&nbsp;</td></tr>\
340 <tr><td><p>x</p><p>y</p></td><td>&nbsp;</td></tr></tbody></table></figure>"
341 );
342 }
343
344 #[test]
345 fn markdown_tables_need_a_delimiter_row() {
346 let lines = ["| A | B |", "|---|:-:|", "| 1 | 2 \\| 3 |", "", "after"];
347 let (rows, consumed) = markdown_table(&lines).unwrap();
348 assert_eq!(consumed, 3);
349 assert_eq!(rows, [["A", "B"], ["1", "2 | 3"]]);
350 assert!(markdown_table(&["a | b", "c | d"]).is_none());
351 assert!(markdown_table(&["| a | b |", "|---|"]).is_none());
352 }
353}
crates/core/tests/composer_blocks.rs added +341 −0
@@ -0,0 +1,341 @@
1 use teams_core::{
2 Draft, DraftLine, LineKind, Mark, MarkKind, TABLE_MARK, Table, TypingStyle, html_to_spans,
3 };
4
5 fn typed(draft: &mut Draft, text: &str) {
6 let mut typing: Option<TypingStyle> = None;
7 for character in text.chars() {
8 let cursor = draft.text().len();
9 let mut next = draft.text().to_owned();
10 next.push(character);
11 let cursor = draft.apply_edit(&next, cursor + character.len_utf8(), typing.as_ref());
12 typing = draft.convert_typed(cursor).map(|(_, style)| style);
13 draft.take_edits();
14 }
15 }
16
17 fn typed_draft(text: &str) -> Draft {
18 let mut draft = Draft::default();
19 typed(&mut draft, text);
20 draft
21 }
22
23 fn enter(draft: &mut Draft, cursor: usize, shift: bool) -> Option<usize> {
24 let result = draft.break_line(cursor, shift);
25 draft.take_edits();
26 result
27 }
28
29 fn table_of(rows: &[&[&str]]) -> Table {
30 Table::from_rows(
31 rows.iter()
32 .map(|row| row.iter().map(|cell| (*cell).to_owned()).collect())
33 .collect(),
34 )
35 }
36
37 #[test]
38 fn enter_in_a_quote_adds_a_quote_line_and_enter_on_the_empty_one_leaves() {
39 let mut draft = typed_draft(">abc");
40 let cursor = enter(&mut draft, 3, false).unwrap();
41 assert_eq!(draft.text(), "abc\n");
42 assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Quote]);
43 let cursor = enter(&mut draft, cursor, false).unwrap();
44 assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Text]);
45 assert_eq!(cursor, 4);
46 assert_eq!(enter(&mut draft, cursor, false), None);
47 assert_eq!(draft.to_html(), "<blockquote>abc</blockquote>");
48 }
49
50 #[test]
51 fn enter_on_an_empty_quote_line_in_the_middle_splits_the_quote() {
52 let mut draft = Draft::from_markdown("> a\n> \n> b");
53 enter(&mut draft, 2, false).unwrap();
54 assert_eq!(
55 draft.lines(),
56 [LineKind::Quote, LineKind::Text, LineKind::Quote]
57 );
58 }
59
60 #[test]
61 fn shift_enter_keeps_breaking_inside_the_quote() {
62 let mut draft = typed_draft(">a");
63 let cursor = enter(&mut draft, 1, true).unwrap();
64 let cursor = enter(&mut draft, cursor, true).unwrap();
65 assert_eq!(cursor, 3);
66 assert_eq!(
67 draft.lines(),
68 [LineKind::Quote, LineKind::Quote, LineKind::Quote]
69 );
70 }
71
72 #[test]
73 fn backspace_at_the_start_of_a_quote_leaves_it_or_joins_the_line_above() {
74 let mut empty = typed_draft(">");
75 assert_eq!(empty.backspace_at_start(0), Some(0));
76 assert_eq!(empty.lines(), [LineKind::Text]);
77
78 let mut joined = Draft::from_markdown("x\n> abc");
79 assert_eq!(joined.backspace_at_start(2), Some(1));
80 assert_eq!(joined.text(), "xabc");
81 assert_eq!(joined.lines(), [LineKind::Text]);
82
83 let mut inner = Draft::from_markdown("> a\n> b");
84 assert_eq!(inner.backspace_at_start(2), Some(1));
85 assert_eq!(inner.text(), "ab");
86 assert_eq!(inner.lines(), [LineKind::Quote]);
87 }
88
89 #[test]
90 fn down_at_the_end_of_a_closing_quote_opens_a_text_line_below() {
91 let mut draft = typed_draft(">abc");
92 assert_eq!(draft.leave_quote_at_end(1), None);
93 assert_eq!(draft.leave_quote_at_end(3), Some(4));
94 assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Text]);
95 assert_eq!(Draft::plain("x").leave_quote_at_end(1), None);
96 }
97
98 #[test]
99 fn teams_shortcuts_make_headings_bold_italic_and_code() {
100 let heading = typed_draft("## Plan");
101 assert_eq!(heading.text(), "Plan");
102 assert_eq!(heading.lines(), [LineKind::Heading(2)]);
103 assert_eq!(heading.to_html(), "<h2>Plan</h2>");
104 assert_eq!(typed_draft("#### deep").lines(), [LineKind::Heading(3)]);
105 assert_eq!(typed_draft("#nope").lines(), [LineKind::Text]);
106
107 let inline = typed_draft("*b* _i_ `c`");
108 assert_eq!(inline.text(), "b i c");
109 assert_eq!(
110 inline.marks(),
111 [
112 Mark {
113 range: 0..1,
114 kind: MarkKind::Bold
115 },
116 Mark {
117 range: 2..3,
118 kind: MarkKind::Italic
119 },
120 Mark {
121 range: 4..5,
122 kind: MarkKind::Code
123 },
124 ]
125 );
126 }
127
128 #[test]
129 fn enter_in_a_heading_is_left_to_send_and_backspace_makes_it_text() {
130 let mut draft = typed_draft("# a");
131 assert_eq!(enter(&mut draft, 1, false), None);
132 assert_eq!(draft.backspace_at_start(0), Some(0));
133 assert_eq!(draft.lines(), [LineKind::Text]);
134 }
135
136 #[test]
137 fn an_inserted_table_takes_an_empty_line_and_gets_a_line_after_it() {
138 let mut draft = Draft::default();
139 let index = draft.insert_table(0, Table::new(2, 3));
140 assert_eq!(index, 0);
141 assert_eq!(draft.text(), format!("{TABLE_MARK}\n"));
142 assert!(draft.lines()[0].is_table());
143 assert_eq!(draft.lines()[1], LineKind::Text);
144
145 let mut below = Draft::plain("hello");
146 assert_eq!(below.insert_table(2, Table::new(1, 1)), 1);
147 assert_eq!(below.text(), format!("hello\n{TABLE_MARK}\n"));
148 }
149
150 #[test]
151 fn a_table_is_sent_as_teams_html_between_the_text() {
152 let mut draft = Draft::plain("before");
153 let index = draft.insert_table(6, Table::new(1, 2));
154 draft.set_table(index, table_of(&[&["a", "b"]]));
155 let end = draft.text().len();
156 let mut text = draft.text().to_owned();
157 text.push_str("after");
158 draft.apply_edit(&text, end + 5, None);
159 assert_eq!(
160 draft.trimmed().to_html(),
161 "before<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\
162 <tr><td>a</td><td>b</td></tr></tbody></table></figure>after"
163 );
164 assert_eq!(draft.plain_text(), "before\na\tb\nafter");
165 assert!(
166 !Draft::from_lines(&[DraftLine {
167 kind: LineKind::Table(Table::new(1, 1)),
168 number: None,
169 content: TABLE_MARK.to_string(),
170 marks: Vec::new(),
171 }])
172 .plain_text()
173 .contains(TABLE_MARK)
174 );
175 }
176
177 #[test]
178 fn text_typed_next_to_a_table_moves_to_its_own_line() {
179 let mut draft = Draft::default();
180 draft.insert_table(0, Table::new(1, 1));
181 let mark = TABLE_MARK.len_utf8();
182 let mut text = draft.text().to_owned();
183 text.insert(mark, 'x');
184 let cursor = draft.apply_edit(&text, mark + 1, None);
185 assert_eq!(draft.text(), format!("{TABLE_MARK}\nx\n"));
186 assert_eq!(cursor, mark + 2);
187 assert!(draft.lines()[0].is_table());
188 assert_eq!(draft.lines()[1], LineKind::Text);
189
190 let mut text = draft.text().to_owned();
191 text.insert(0, 'y');
192 let cursor = draft.apply_edit(&text, 1, None);
193 assert_eq!(draft.text(), format!("y\n{TABLE_MARK}\nx\n"));
194 assert_eq!(cursor, 1);
195 assert!(draft.lines()[1].is_table());
196 }
197
198 #[test]
199 fn deleting_the_mark_drops_the_table() {
200 let mut draft = Draft::plain("a");
201 draft.insert_table(1, Table::new(1, 1));
202 draft.apply_edit("a\n\n", 2, None);
203 assert!(draft.lines().iter().all(|kind| !kind.is_table()));
204 }
205
206 #[test]
207 fn delete_before_a_table_and_backspace_after_it_find_the_table() {
208 let mut draft = Draft::plain("a");
209 let index = draft.insert_table(1, Table::new(1, 1));
210 assert_eq!(draft.table_after(1), Some(index));
211 assert_eq!(draft.delete_forward(1), Some(1));
212 assert!(draft.lines()[index].is_table());
213 let after = draft.text().len();
214 assert_eq!(draft.table_before(after), Some(index));
215 assert_eq!(draft.table_before(0), None);
216 }
217
218 #[test]
219 fn leaving_a_table_lands_beside_it_and_adds_a_line_when_needed() {
220 let mut draft = Draft::default();
221 draft.insert_table(0, Table::new(1, 1));
222 assert_eq!(draft.line_beside_table(0, false), 0);
223 assert_eq!(draft.lines()[0], LineKind::Text);
224 assert!(draft.lines()[1].is_table());
225 let below = draft.line_beside_table(1, true);
226 assert_eq!(draft.line_at(below), 2);
227 }
228
229 #[test]
230 fn removing_a_table_keeps_the_lines_around_it() {
231 let mut draft = Draft::from_markdown("> a");
232 let index = draft.insert_table(3, Table::new(1, 1));
233 let end = draft.text().len();
234 let mut text = draft.text().to_owned();
235 text.push('z');
236 draft.apply_edit(&text, end + 1, None);
237 let cursor = draft.remove_table(index);
238 assert_eq!(draft.text(), "a\nz");
239 assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Text]);
240 assert_eq!(cursor, 2);
241 }
242
243 #[test]
244 fn quote_and_list_buttons_leave_a_table_alone() {
245 let mut draft = Draft::plain("a");
246 let index = draft.insert_table(1, Table::new(1, 1));
247 let end = draft.text().len();
248 draft.toggle_lines(0..end, LineKind::Quote);
249 assert!(draft.lines()[index].is_table());
250 }
251
252 #[test]
253 fn a_copied_table_pastes_into_the_middle_of_a_line() {
254 let mut source = Draft::default();
255 let index = source.insert_table(0, table_of(&[&["1", "2"]]));
256 let copied = source.slice(0..TABLE_MARK.len_utf8());
257 let mut draft = Draft::plain("abcd");
258 draft.insert_lines(2..2, &copied);
259 assert_eq!(draft.text(), format!("ab\n{TABLE_MARK}\ncd"));
260 assert_eq!(draft.table(1), source.table(index));
261 }
262
263 #[test]
264 fn pasted_markdown_becomes_headings_lists_quotes_code_and_tables() {
265 let markdown = "# Title\n\nSome **bold**, *it*, ~~gone~~, `code` and [docs](https://x.de)\n\n\
266 1. one\n 1. nested\n2. two\n- dot\n - inner\n\n> quoted\n\n```rust\nfn x() {}\n```\n\n\
267 | A | B |\n|---|---|\n| **1** | 2 |\n";
268 let draft = Draft::from_markdown(markdown);
269 let kinds: Vec<LineKind> = draft
270 .lines()
271 .iter()
272 .filter(|kind| **kind != LineKind::Text)
273 .cloned()
274 .collect();
275 assert_eq!(
276 kinds,
277 [
278 LineKind::Heading(1),
279 LineKind::Numbered(0),
280 LineKind::Numbered(1),
281 LineKind::Numbered(0),
282 LineKind::Bullet(0),
283 LineKind::Bullet(1),
284 LineKind::Quote,
285 LineKind::Code(Some("rust".into())),
286 LineKind::Table(table_of(&[&["A", "B"], &["1", "2"]])),
287 ]
288 );
289 let html = draft.trimmed().to_html();
290 assert!(html.starts_with("<h1>Title</h1>"), "{html}");
291 assert!(html.contains("<b>bold</b>, <i>it</i>, <s>gone</s>, <code>code</code>"));
292 assert!(html.contains("<a href=\"https://x.de\">docs</a>"));
293 assert!(html.contains("<blockquote>quoted</blockquote>"));
294 assert!(html.contains("<pre class=\"language-rust\">fn x() {}</pre>"));
295 assert!(
296 html.ends_with("<td>1</td><td>2</td></tr></tbody></table></figure>"),
297 "{html}"
298 );
299 }
300
301 #[test]
302 fn text_with_pipes_but_no_delimiter_row_stays_text() {
303 assert!(!teams_core::has_markdown("a | b\nc | d"));
304 assert!(teams_core::has_markdown("| a | b |\n| - | - |"));
305 assert!(teams_core::has_markdown("## Heading"));
306 }
307
308 #[test]
309 fn received_tables_and_headings_edit_as_tables_and_headings() {
310 let spans = html_to_spans(
311 "<h2>Notes</h2><table><tbody><tr><td><p>a</p></td><td>b<br>c</td></tr></tbody></table><p>end</p>",
312 );
313 let draft = Draft::from_spans(&spans);
314 assert_eq!(draft.lines()[0], LineKind::Heading(2));
315 assert_eq!(
316 draft.lines()[1],
317 LineKind::Table(table_of(&[&["a", "b\nc"]]))
318 );
319 assert_eq!(draft.lines()[2], LineKind::Text);
320 }
321
322 #[test]
323 fn pasting_markdown_with_a_table_leaves_the_cursor_after_the_paste() {
324 let markdown = "## Plan\n- dot\n> quoted\n\n| Area | Owner |\n|---|---|\n| Sync | Priya |\nend";
325 let lines = Draft::from_markdown(markdown).slice(0..usize::MAX);
326 let mut draft = Draft::default();
327 let cursor = draft.insert_lines(0..0, &lines);
328 assert_eq!(cursor, draft.text().len(), "{:?}", draft.text());
329 }
330
331 #[test]
332 fn a_sent_table_edits_back_into_the_same_table() {
333 let table = table_of(&[&["a", "x\ny"], &["", "b"]]);
334 let draft = Draft::from_spans(&html_to_spans(&table.to_html()));
335 let LineKind::Table(received) = &draft.lines()[0] else {
336 panic!("{:?}", draft.lines());
337 };
338 assert_eq!(received.rows[0], ["a", "x\ny"]);
339 assert!(received.rows[1][0].trim().is_empty());
340 assert_eq!(received.to_html(), table.to_html());
341 }
@@ -0,0 +1,341 @@
1use teams_core::{
2 Draft, DraftLine, LineKind, Mark, MarkKind, TABLE_MARK, Table, TypingStyle, html_to_spans,
3};
4
5fn typed(draft: &mut Draft, text: &str) {
6 let mut typing: Option<TypingStyle> = None;
7 for character in text.chars() {
8 let cursor = draft.text().len();
9 let mut next = draft.text().to_owned();
10 next.push(character);
11 let cursor = draft.apply_edit(&next, cursor + character.len_utf8(), typing.as_ref());
12 typing = draft.convert_typed(cursor).map(|(_, style)| style);
13 draft.take_edits();
14 }
15}
16
17fn typed_draft(text: &str) -> Draft {
18 let mut draft = Draft::default();
19 typed(&mut draft, text);
20 draft
21}
22
23fn enter(draft: &mut Draft, cursor: usize, shift: bool) -> Option<usize> {
24 let result = draft.break_line(cursor, shift);
25 draft.take_edits();
26 result
27}
28
29fn table_of(rows: &[&[&str]]) -> Table {
30 Table::from_rows(
31 rows.iter()
32 .map(|row| row.iter().map(|cell| (*cell).to_owned()).collect())
33 .collect(),
34 )
35}
36
37#[test]
38fn enter_in_a_quote_adds_a_quote_line_and_enter_on_the_empty_one_leaves() {
39 let mut draft = typed_draft(">abc");
40 let cursor = enter(&mut draft, 3, false).unwrap();
41 assert_eq!(draft.text(), "abc\n");
42 assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Quote]);
43 let cursor = enter(&mut draft, cursor, false).unwrap();
44 assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Text]);
45 assert_eq!(cursor, 4);
46 assert_eq!(enter(&mut draft, cursor, false), None);
47 assert_eq!(draft.to_html(), "<blockquote>abc</blockquote>");
48}
49
50#[test]
51fn enter_on_an_empty_quote_line_in_the_middle_splits_the_quote() {
52 let mut draft = Draft::from_markdown("> a\n> \n> b");
53 enter(&mut draft, 2, false).unwrap();
54 assert_eq!(
55 draft.lines(),
56 [LineKind::Quote, LineKind::Text, LineKind::Quote]
57 );
58}
59
60#[test]
61fn shift_enter_keeps_breaking_inside_the_quote() {
62 let mut draft = typed_draft(">a");
63 let cursor = enter(&mut draft, 1, true).unwrap();
64 let cursor = enter(&mut draft, cursor, true).unwrap();
65 assert_eq!(cursor, 3);
66 assert_eq!(
67 draft.lines(),
68 [LineKind::Quote, LineKind::Quote, LineKind::Quote]
69 );
70}
71
72#[test]
73fn backspace_at_the_start_of_a_quote_leaves_it_or_joins_the_line_above() {
74 let mut empty = typed_draft(">");
75 assert_eq!(empty.backspace_at_start(0), Some(0));
76 assert_eq!(empty.lines(), [LineKind::Text]);
77
78 let mut joined = Draft::from_markdown("x\n> abc");
79 assert_eq!(joined.backspace_at_start(2), Some(1));
80 assert_eq!(joined.text(), "xabc");
81 assert_eq!(joined.lines(), [LineKind::Text]);
82
83 let mut inner = Draft::from_markdown("> a\n> b");
84 assert_eq!(inner.backspace_at_start(2), Some(1));
85 assert_eq!(inner.text(), "ab");
86 assert_eq!(inner.lines(), [LineKind::Quote]);
87}
88
89#[test]
90fn down_at_the_end_of_a_closing_quote_opens_a_text_line_below() {
91 let mut draft = typed_draft(">abc");
92 assert_eq!(draft.leave_quote_at_end(1), None);
93 assert_eq!(draft.leave_quote_at_end(3), Some(4));
94 assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Text]);
95 assert_eq!(Draft::plain("x").leave_quote_at_end(1), None);
96}
97
98#[test]
99fn teams_shortcuts_make_headings_bold_italic_and_code() {
100 let heading = typed_draft("## Plan");
101 assert_eq!(heading.text(), "Plan");
102 assert_eq!(heading.lines(), [LineKind::Heading(2)]);
103 assert_eq!(heading.to_html(), "<h2>Plan</h2>");
104 assert_eq!(typed_draft("#### deep").lines(), [LineKind::Heading(3)]);
105 assert_eq!(typed_draft("#nope").lines(), [LineKind::Text]);
106
107 let inline = typed_draft("*b* _i_ `c`");
108 assert_eq!(inline.text(), "b i c");
109 assert_eq!(
110 inline.marks(),
111 [
112 Mark {
113 range: 0..1,
114 kind: MarkKind::Bold
115 },
116 Mark {
117 range: 2..3,
118 kind: MarkKind::Italic
119 },
120 Mark {
121 range: 4..5,
122 kind: MarkKind::Code
123 },
124 ]
125 );
126}
127
128#[test]
129fn enter_in_a_heading_is_left_to_send_and_backspace_makes_it_text() {
130 let mut draft = typed_draft("# a");
131 assert_eq!(enter(&mut draft, 1, false), None);
132 assert_eq!(draft.backspace_at_start(0), Some(0));
133 assert_eq!(draft.lines(), [LineKind::Text]);
134}
135
136#[test]
137fn an_inserted_table_takes_an_empty_line_and_gets_a_line_after_it() {
138 let mut draft = Draft::default();
139 let index = draft.insert_table(0, Table::new(2, 3));
140 assert_eq!(index, 0);
141 assert_eq!(draft.text(), format!("{TABLE_MARK}\n"));
142 assert!(draft.lines()[0].is_table());
143 assert_eq!(draft.lines()[1], LineKind::Text);
144
145 let mut below = Draft::plain("hello");
146 assert_eq!(below.insert_table(2, Table::new(1, 1)), 1);
147 assert_eq!(below.text(), format!("hello\n{TABLE_MARK}\n"));
148}
149
150#[test]
151fn a_table_is_sent_as_teams_html_between_the_text() {
152 let mut draft = Draft::plain("before");
153 let index = draft.insert_table(6, Table::new(1, 2));
154 draft.set_table(index, table_of(&[&["a", "b"]]));
155 let end = draft.text().len();
156 let mut text = draft.text().to_owned();
157 text.push_str("after");
158 draft.apply_edit(&text, end + 5, None);
159 assert_eq!(
160 draft.trimmed().to_html(),
161 "before<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\
162 <tr><td>a</td><td>b</td></tr></tbody></table></figure>after"
163 );
164 assert_eq!(draft.plain_text(), "before\na\tb\nafter");
165 assert!(
166 !Draft::from_lines(&[DraftLine {
167 kind: LineKind::Table(Table::new(1, 1)),
168 number: None,
169 content: TABLE_MARK.to_string(),
170 marks: Vec::new(),
171 }])
172 .plain_text()
173 .contains(TABLE_MARK)
174 );
175}
176
177#[test]
178fn text_typed_next_to_a_table_moves_to_its_own_line() {
179 let mut draft = Draft::default();
180 draft.insert_table(0, Table::new(1, 1));
181 let mark = TABLE_MARK.len_utf8();
182 let mut text = draft.text().to_owned();
183 text.insert(mark, 'x');
184 let cursor = draft.apply_edit(&text, mark + 1, None);
185 assert_eq!(draft.text(), format!("{TABLE_MARK}\nx\n"));
186 assert_eq!(cursor, mark + 2);
187 assert!(draft.lines()[0].is_table());
188 assert_eq!(draft.lines()[1], LineKind::Text);
189
190 let mut text = draft.text().to_owned();
191 text.insert(0, 'y');
192 let cursor = draft.apply_edit(&text, 1, None);
193 assert_eq!(draft.text(), format!("y\n{TABLE_MARK}\nx\n"));
194 assert_eq!(cursor, 1);
195 assert!(draft.lines()[1].is_table());
196}
197
198#[test]
199fn deleting_the_mark_drops_the_table() {
200 let mut draft = Draft::plain("a");
201 draft.insert_table(1, Table::new(1, 1));
202 draft.apply_edit("a\n\n", 2, None);
203 assert!(draft.lines().iter().all(|kind| !kind.is_table()));
204}
205
206#[test]
207fn delete_before_a_table_and_backspace_after_it_find_the_table() {
208 let mut draft = Draft::plain("a");
209 let index = draft.insert_table(1, Table::new(1, 1));
210 assert_eq!(draft.table_after(1), Some(index));
211 assert_eq!(draft.delete_forward(1), Some(1));
212 assert!(draft.lines()[index].is_table());
213 let after = draft.text().len();
214 assert_eq!(draft.table_before(after), Some(index));
215 assert_eq!(draft.table_before(0), None);
216}
217
218#[test]
219fn leaving_a_table_lands_beside_it_and_adds_a_line_when_needed() {
220 let mut draft = Draft::default();
221 draft.insert_table(0, Table::new(1, 1));
222 assert_eq!(draft.line_beside_table(0, false), 0);
223 assert_eq!(draft.lines()[0], LineKind::Text);
224 assert!(draft.lines()[1].is_table());
225 let below = draft.line_beside_table(1, true);
226 assert_eq!(draft.line_at(below), 2);
227}
228
229#[test]
230fn removing_a_table_keeps_the_lines_around_it() {
231 let mut draft = Draft::from_markdown("> a");
232 let index = draft.insert_table(3, Table::new(1, 1));
233 let end = draft.text().len();
234 let mut text = draft.text().to_owned();
235 text.push('z');
236 draft.apply_edit(&text, end + 1, None);
237 let cursor = draft.remove_table(index);
238 assert_eq!(draft.text(), "a\nz");
239 assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Text]);
240 assert_eq!(cursor, 2);
241}
242
243#[test]
244fn quote_and_list_buttons_leave_a_table_alone() {
245 let mut draft = Draft::plain("a");
246 let index = draft.insert_table(1, Table::new(1, 1));
247 let end = draft.text().len();
248 draft.toggle_lines(0..end, LineKind::Quote);
249 assert!(draft.lines()[index].is_table());
250}
251
252#[test]
253fn a_copied_table_pastes_into_the_middle_of_a_line() {
254 let mut source = Draft::default();
255 let index = source.insert_table(0, table_of(&[&["1", "2"]]));
256 let copied = source.slice(0..TABLE_MARK.len_utf8());
257 let mut draft = Draft::plain("abcd");
258 draft.insert_lines(2..2, &copied);
259 assert_eq!(draft.text(), format!("ab\n{TABLE_MARK}\ncd"));
260 assert_eq!(draft.table(1), source.table(index));
261}
262
263#[test]
264fn pasted_markdown_becomes_headings_lists_quotes_code_and_tables() {
265 let markdown = "# Title\n\nSome **bold**, *it*, ~~gone~~, `code` and [docs](https://x.de)\n\n\
266 1. one\n 1. nested\n2. two\n- dot\n - inner\n\n> quoted\n\n```rust\nfn x() {}\n```\n\n\
267 | A | B |\n|---|---|\n| **1** | 2 |\n";
268 let draft = Draft::from_markdown(markdown);
269 let kinds: Vec<LineKind> = draft
270 .lines()
271 .iter()
272 .filter(|kind| **kind != LineKind::Text)
273 .cloned()
274 .collect();
275 assert_eq!(
276 kinds,
277 [
278 LineKind::Heading(1),
279 LineKind::Numbered(0),
280 LineKind::Numbered(1),
281 LineKind::Numbered(0),
282 LineKind::Bullet(0),
283 LineKind::Bullet(1),
284 LineKind::Quote,
285 LineKind::Code(Some("rust".into())),
286 LineKind::Table(table_of(&[&["A", "B"], &["1", "2"]])),
287 ]
288 );
289 let html = draft.trimmed().to_html();
290 assert!(html.starts_with("<h1>Title</h1>"), "{html}");
291 assert!(html.contains("<b>bold</b>, <i>it</i>, <s>gone</s>, <code>code</code>"));
292 assert!(html.contains("<a href=\"https://x.de\">docs</a>"));
293 assert!(html.contains("<blockquote>quoted</blockquote>"));
294 assert!(html.contains("<pre class=\"language-rust\">fn x() {}</pre>"));
295 assert!(
296 html.ends_with("<td>1</td><td>2</td></tr></tbody></table></figure>"),
297 "{html}"
298 );
299}
300
301#[test]
302fn text_with_pipes_but_no_delimiter_row_stays_text() {
303 assert!(!teams_core::has_markdown("a | b\nc | d"));
304 assert!(teams_core::has_markdown("| a | b |\n| - | - |"));
305 assert!(teams_core::has_markdown("## Heading"));
306}
307
308#[test]
309fn received_tables_and_headings_edit_as_tables_and_headings() {
310 let spans = html_to_spans(
311 "<h2>Notes</h2><table><tbody><tr><td><p>a</p></td><td>b<br>c</td></tr></tbody></table><p>end</p>",
312 );
313 let draft = Draft::from_spans(&spans);
314 assert_eq!(draft.lines()[0], LineKind::Heading(2));
315 assert_eq!(
316 draft.lines()[1],
317 LineKind::Table(table_of(&[&["a", "b\nc"]]))
318 );
319 assert_eq!(draft.lines()[2], LineKind::Text);
320}
321
322#[test]
323fn pasting_markdown_with_a_table_leaves_the_cursor_after_the_paste() {
324 let markdown = "## Plan\n- dot\n> quoted\n\n| Area | Owner |\n|---|---|\n| Sync | Priya |\nend";
325 let lines = Draft::from_markdown(markdown).slice(0..usize::MAX);
326 let mut draft = Draft::default();
327 let cursor = draft.insert_lines(0..0, &lines);
328 assert_eq!(cursor, draft.text().len(), "{:?}", draft.text());
329}
330
331#[test]
332fn a_sent_table_edits_back_into_the_same_table() {
333 let table = table_of(&[&["a", "x\ny"], &["", "b"]]);
334 let draft = Draft::from_spans(&html_to_spans(&table.to_html()));
335 let LineKind::Table(received) = &draft.lines()[0] else {
336 panic!("{:?}", draft.lines());
337 };
338 assert_eq!(received.rows[0], ["a", "x\ny"]);
339 assert!(received.rows[1][0].trim().is_empty());
340 assert_eq!(received.to_html(), table.to_html());
341}
crates/graph/src/lib.rs +1 −1
@@ -23,7 +23,7 @@ pub use files::{
23 23 pub use library::DriveEntry;
24 24 pub use models::{
25 25 Attachment, Body, Channel, Chat, ChatViewpoint, Identity, Member, Mention, Message, Photo,
26 Presence, Reaction, Sender, Team, User,
26 Presence, Reaction, Sender, Team, UNKNOWN_USER_NAME, User,
27 27 };
28 28 pub use outgoing::{
29 29 FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, OutgoingMention,
@@ -23,7 +23,7 @@ pub use files::{
23pub use library::DriveEntry;
23pub use library::DriveEntry;
24pub use models::{
24pub use models::{
25 Attachment, Body, Channel, Chat, ChatViewpoint, Identity, Member, Mention, Message, Photo,
25 Attachment, Body, Channel, Chat, ChatViewpoint, Identity, Member, Mention, Message, Photo,
26 Presence, Reaction, Sender, Team, User,
26 Presence, Reaction, Sender, Team, UNKNOWN_USER_NAME, User,
27};
27};
28pub use outgoing::{
28pub use outgoing::{
29 FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, OutgoingMention,
29 FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, OutgoingMention,
crates/graph/src/models.rs +14 −7
@@ -1,6 +1,8 @@
1 1 use chrono::{DateTime, Utc};
2 2 use serde::Deserialize;
3 3
4 pub const UNKNOWN_USER_NAME: &str = "Unknown User";
5
4 6 #[derive(Debug, Clone, Deserialize, PartialEq)]
5 7 #[serde(rename_all = "camelCase")]
6 8 pub struct User {
@@ -22,6 +24,17 @@ pub struct Member {
22 24 pub email: Option<String>,
23 25 }
24 26
27 impl Member {
28 pub fn name(&self) -> &str {
29 [&self.display_name, &self.email]
30 .into_iter()
31 .flatten()
32 .map(|name| name.trim())
33 .find(|name| !name.is_empty())
34 .unwrap_or(UNKNOWN_USER_NAME)
35 }
36 }
37
25 38 #[derive(Debug, Clone, Deserialize, PartialEq)]
26 39 #[serde(rename_all = "camelCase")]
27 40 pub struct Identity {
@@ -160,13 +173,7 @@ impl Chat {
160 173 .members
161 174 .iter()
162 175 .filter(|member| member.user_id.as_deref() != Some(my_user_id))
163 .map(|member| {
164 member
165 .display_name
166 .as_deref()
167 .or(member.email.as_deref())
168 .unwrap_or("?")
169 })
176 .map(Member::name)
170 177 .collect();
171 178 if names.is_empty() {
172 179 self.preview_sender_name(my_user_id)
@@ -1,6 +1,8 @@
1use chrono::{DateTime, Utc};
1use chrono::{DateTime, Utc};
2use serde::Deserialize;
2use serde::Deserialize;
3
3
4pub const UNKNOWN_USER_NAME: &str = "Unknown User";
5
4#[derive(Debug, Clone, Deserialize, PartialEq)]
6#[derive(Debug, Clone, Deserialize, PartialEq)]
5#[serde(rename_all = "camelCase")]
7#[serde(rename_all = "camelCase")]
6pub struct User {
8pub struct User {
@@ -22,6 +24,17 @@ pub struct Member {
22 pub email: Option<String>,
24 pub email: Option<String>,
23}
25}
24
26
27impl Member {
28 pub fn name(&self) -> &str {
29 [&self.display_name, &self.email]
30 .into_iter()
31 .flatten()
32 .map(|name| name.trim())
33 .find(|name| !name.is_empty())
34 .unwrap_or(UNKNOWN_USER_NAME)
35 }
36}
37
25#[derive(Debug, Clone, Deserialize, PartialEq)]
38#[derive(Debug, Clone, Deserialize, PartialEq)]
26#[serde(rename_all = "camelCase")]
39#[serde(rename_all = "camelCase")]
27pub struct Identity {
40pub struct Identity {
@@ -160,13 +173,7 @@ impl Chat {
160 .members
173 .members
161 .iter()
174 .iter()
162 .filter(|member| member.user_id.as_deref() != Some(my_user_id))
175 .filter(|member| member.user_id.as_deref() != Some(my_user_id))
163 .map(|member| {
176 .map(Member::name)
164 member
165 .display_name
166 .as_deref()
167 .or(member.email.as_deref())
168 .unwrap_or("?")
169 })
170 .collect();
177 .collect();
171 if names.is_empty() {
178 if names.is_empty() {
172 self.preview_sender_name(my_user_id)
179 self.preview_sender_name(my_user_id)
crates/store/src/lib.rs +1 −1
@@ -31,7 +31,7 @@ pub use models::{
31 31 ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord,
32 32 ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord,
33 33 OutboxRecord, OutboxState, OutboxTarget, ReadHorizonRecord, RecentScope, SearchHit, Sidebar,
34 SidebarTeam, SyncState, TeamLayoutRecord, TeamRecord, is_bot_id,
34 SidebarTeam, SyncState, TeamLayoutRecord, TeamRecord, UNKNOWN_USER_NAME, is_bot_id,
35 35 };
36 36 pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};
37 37 pub use store::{DATA_DIR_NAME, Store, default_database_path};
@@ -31,7 +31,7 @@ pub use models::{
31 ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord,
31 ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord,
32 ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord,
32 ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord,
33 OutboxRecord, OutboxState, OutboxTarget, ReadHorizonRecord, RecentScope, SearchHit, Sidebar,
33 OutboxRecord, OutboxState, OutboxTarget, ReadHorizonRecord, RecentScope, SearchHit, Sidebar,
34 SidebarTeam, SyncState, TeamLayoutRecord, TeamRecord, is_bot_id,
34 SidebarTeam, SyncState, TeamLayoutRecord, TeamRecord, UNKNOWN_USER_NAME, is_bot_id,
35};
35};
36pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};
36pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};
37pub use store::{DATA_DIR_NAME, Store, default_database_path};
37pub use store::{DATA_DIR_NAME, Store, default_database_path};
crates/store/src/messages.rs +3 −3
@@ -4,7 +4,7 @@ use chrono::{DateTime, Utc};
4 4 use rusqlite::{OptionalExtension, Row, params, params_from_iter};
5 5
6 6 use crate::error::Result;
7 use crate::models::{MessageRecord, RecentScope};
7 use crate::models::{MessageRecord, RecentScope, UNKNOWN_USER_NAME};
8 8 use crate::search::index_message;
9 9 use crate::store::Store;
10 10 use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis};
@@ -370,14 +370,14 @@ impl Store {
370 370 let mut statement = connection.prepare_cached(
371 371 "SELECT value, COALESCE(
372 372 (SELECT display_name FROM chat_members
373 WHERE user_id = value AND display_name <> '' LIMIT 1),
373 WHERE user_id = value AND display_name NOT IN ('', ?2) LIMIT 1),
374 374 (SELECT sender_name FROM messages
375 375 WHERE sender_id = value AND sender_name <> ''
376 376 ORDER BY created_at DESC LIMIT 1))
377 377 FROM json_each(?1)",
378 378 )?;
379 379 let ids = serde_json::to_string(user_ids).unwrap_or_else(|_| "[]".to_owned());
380 let rows = statement.query_map([ids], |row| {
380 let rows = statement.query_map(params![ids, UNKNOWN_USER_NAME], |row| {
381 381 Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?))
382 382 })?;
383 383 let mut names = HashMap::new();
@@ -4,7 +4,7 @@ use chrono::{DateTime, Utc};
4use rusqlite::{OptionalExtension, Row, params, params_from_iter};
4use rusqlite::{OptionalExtension, Row, params, params_from_iter};
5
5
6use crate::error::Result;
6use crate::error::Result;
7use crate::models::{MessageRecord, RecentScope};
7use crate::models::{MessageRecord, RecentScope, UNKNOWN_USER_NAME};
8use crate::search::index_message;
8use crate::search::index_message;
9use crate::store::Store;
9use crate::store::Store;
10use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis};
10use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis};
@@ -370,14 +370,14 @@ impl Store {
370 let mut statement = connection.prepare_cached(
370 let mut statement = connection.prepare_cached(
371 "SELECT value, COALESCE(
371 "SELECT value, COALESCE(
372 (SELECT display_name FROM chat_members
372 (SELECT display_name FROM chat_members
373 WHERE user_id = value AND display_name <> '' LIMIT 1),
373 WHERE user_id = value AND display_name NOT IN ('', ?2) LIMIT 1),
374 (SELECT sender_name FROM messages
374 (SELECT sender_name FROM messages
375 WHERE sender_id = value AND sender_name <> ''
375 WHERE sender_id = value AND sender_name <> ''
376 ORDER BY created_at DESC LIMIT 1))
376 ORDER BY created_at DESC LIMIT 1))
377 FROM json_each(?1)",
377 FROM json_each(?1)",
378 )?;
378 )?;
379 let ids = serde_json::to_string(user_ids).unwrap_or_else(|_| "[]".to_owned());
379 let ids = serde_json::to_string(user_ids).unwrap_or_else(|_| "[]".to_owned());
380 let rows = statement.query_map([ids], |row| {
380 let rows = statement.query_map(params![ids, UNKNOWN_USER_NAME], |row| {
381 Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?))
381 Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?))
382 })?;
382 })?;
383 let mut names = HashMap::new();
383 let mut names = HashMap::new();
crates/store/src/models.rs +1 −0
@@ -3,6 +3,7 @@ use std::collections::HashMap;
3 3 use chrono::{DateTime, Utc};
4 4
5 5 pub const BOT_MRI_PREFIX: &str = "28:";
6 pub const UNKNOWN_USER_NAME: &str = "Unknown User";
6 7
7 8 pub fn is_bot_id(user_id: &str) -> bool {
8 9 user_id.starts_with(BOT_MRI_PREFIX)
@@ -3,6 +3,7 @@ use std::collections::HashMap;
3use chrono::{DateTime, Utc};
3use chrono::{DateTime, Utc};
4
4
5pub const BOT_MRI_PREFIX: &str = "28:";
5pub const BOT_MRI_PREFIX: &str = "28:";
6pub const UNKNOWN_USER_NAME: &str = "Unknown User";
6
7
7pub fn is_bot_id(user_id: &str) -> bool {
8pub fn is_bot_id(user_id: &str) -> bool {
8 user_id.starts_with(BOT_MRI_PREFIX)
9 user_id.starts_with(BOT_MRI_PREFIX)
crates/store/tests/store.rs +9 −2
@@ -4,7 +4,7 @@ use store::{
4 4 AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications,
5 5 ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord, MemberRecord,
6 6 MessageRecord, ReadHorizonRecord, RecentScope, Store, SyncState, TeamLayoutRecord,
7 TeamRecord,
7 TeamRecord, UNKNOWN_USER_NAME,
8 8 };
9 9
10 10 #[test]
@@ -1176,8 +1176,15 @@ fn activity_prune_drops_only_older_rows() {
1176 1176 #[test]
1177 1177 fn display_names_prefer_members_then_latest_sender_name() {
1178 1178 let store = Store::open_in_memory().unwrap();
1179 let unnamed_member = ChatRecord {
1180 members: vec![MemberRecord {
1181 user_id: Some("user-sam".to_owned()),
1182 display_name: UNKNOWN_USER_NAME.to_owned(),
1183 }],
1184 ..chat("chat-2", "Review", Some(at(6)))
1185 };
1179 1186 store
1180 .upsert_chats(&[chat("chat-1", "Planning", Some(at(5)))])
1187 .upsert_chats(&[chat("chat-1", "Planning", Some(at(5))), unnamed_member])
1181 1188 .unwrap();
1182 1189 let sent_by = |message_id: &str, minute: u32, sender: &str, name: Option<&str>| MessageRecord {
1183 1190 sender_id: Some(sender.to_owned()),
@@ -4,7 +4,7 @@ use store::{
4 AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications,
4 AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications,
5 ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord, MemberRecord,
5 ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord, MemberRecord,
6 MessageRecord, ReadHorizonRecord, RecentScope, Store, SyncState, TeamLayoutRecord,
6 MessageRecord, ReadHorizonRecord, RecentScope, Store, SyncState, TeamLayoutRecord,
7 TeamRecord,
7 TeamRecord, UNKNOWN_USER_NAME,
8};
8};
9
9
10#[test]
10#[test]
@@ -1176,8 +1176,15 @@ fn activity_prune_drops_only_older_rows() {
1176#[test]
1176#[test]
1177fn display_names_prefer_members_then_latest_sender_name() {
1177fn display_names_prefer_members_then_latest_sender_name() {
1178 let store = Store::open_in_memory().unwrap();
1178 let store = Store::open_in_memory().unwrap();
1179 let unnamed_member = ChatRecord {
1180 members: vec![MemberRecord {
1181 user_id: Some("user-sam".to_owned()),
1182 display_name: UNKNOWN_USER_NAME.to_owned(),
1183 }],
1184 ..chat("chat-2", "Review", Some(at(6)))
1185 };
1179 store
1186 store
1180 .upsert_chats(&[chat("chat-1", "Planning", Some(at(5)))])
1187 .upsert_chats(&[chat("chat-1", "Planning", Some(at(5))), unnamed_member])
1181 .unwrap();
1188 .unwrap();
1182 let sent_by = |message_id: &str, minute: u32, sender: &str, name: Option<&str>| MessageRecord {
1189 let sent_by = |message_id: &str, minute: u32, sender: &str, name: Option<&str>| MessageRecord {
1183 sender_id: Some(sender.to_owned()),
1190 sender_id: Some(sender.to_owned()),
vendor/gpui-component/src/input/input.rs +18 −5
@@ -3,9 +3,9 @@ use std::rc::Rc;
3 3 use gpui::prelude::FluentBuilder as _;
4 4 use gpui::{
5 5 AccessibleAction, AnyElement, App, DefiniteLength, Edges, ElementId, Entity, Hsla,
6 InteractiveElement as _, IntoElement, ParentElement as _, Rems, RenderOnce, Role, SharedString,
7 StatefulInteractiveElement as _, StyleRefinement, Styled, TextAlign, TouchPhase, Window, div,
8 px, relative,
6 InteractiveElement as _, IntoElement, ParentElement as _, Pixels, Rems, RenderOnce, Role,
7 SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, TextAlign, TouchPhase,
8 Window, div, px, relative,
9 9 };
10 10
11 11 use crate::button::{Button, ButtonRounded, ButtonVariants as _};
@@ -119,6 +119,7 @@ pub struct Input {
119 119 prefix: Option<AnyElement>,
120 120 suffix: Option<AnyElement>,
121 121 height: Option<DefiniteLength>,
122 line_box_height: Option<Pixels>,
122 123 appearance: bool,
123 124 cleanable: bool,
124 125 mask_toggle: bool,
@@ -246,6 +247,7 @@ impl Input {
246 247 aria_label: None,
247 248 context_menu_builder: None,
248 249 paste_handler: None,
250 line_box_height: None,
249 251 token_renderer: None,
250 252 token_click_listener: None,
251 253 token_hover_listener: None,
@@ -295,6 +297,14 @@ impl Input {
295 297 self
296 298 }
297 299
300 /// Center each text line of a multi-line input in a box this tall, in
301 /// place of the size's vertical padding, so a single line is exactly this
302 /// tall and lines up with controls of the same height beside it.
303 pub fn line_box_height(mut self, height: Pixels) -> Self {
304 self.line_box_height = Some(height);
305 self
306 }
307
298 308 /// Set the appearance of the input field, if false the input field will no border, background.
299 309 pub fn appearance(mut self, appearance: bool) -> Self {
300 310 self.appearance = appearance;
@@ -588,12 +598,15 @@ impl RenderOnce for Input {
588 598 },
589 599 cx,
590 600 );
601 let padding_y = self.line_box_height.map_or(self.size.input_py(), |height| {
602 ((height - LINE_HEIGHT.to_pixels(window.rem_size())) / 2.).max(px(0.))
603 });
591 604 state.set_editor_paddings(
592 605 if state.presentation(cx).is_multi_line() {
593 606 Edges {
594 top: self.size.input_py(),
607 top: padding_y,
595 608 right: self.size.input_px(),
596 bottom: self.size.input_py(),
609 bottom: padding_y,
597 610 left: if state.presentation(cx).is_code_editor() {
598 611 self.size.input_px().min(px(6.))
599 612 } else {
@@ -3,9 +3,9 @@ use std::rc::Rc;
3use gpui::prelude::FluentBuilder as _;
3use gpui::prelude::FluentBuilder as _;
4use gpui::{
4use gpui::{
5 AccessibleAction, AnyElement, App, DefiniteLength, Edges, ElementId, Entity, Hsla,
5 AccessibleAction, AnyElement, App, DefiniteLength, Edges, ElementId, Entity, Hsla,
6 InteractiveElement as _, IntoElement, ParentElement as _, Rems, RenderOnce, Role, SharedString,
6 InteractiveElement as _, IntoElement, ParentElement as _, Pixels, Rems, RenderOnce, Role,
7 StatefulInteractiveElement as _, StyleRefinement, Styled, TextAlign, TouchPhase, Window, div,
7 SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, TextAlign, TouchPhase,
8 px, relative,
8 Window, div, px, relative,
9};
9};
10
10
11use crate::button::{Button, ButtonRounded, ButtonVariants as _};
11use crate::button::{Button, ButtonRounded, ButtonVariants as _};
@@ -119,6 +119,7 @@ pub struct Input {
119 prefix: Option<AnyElement>,
119 prefix: Option<AnyElement>,
120 suffix: Option<AnyElement>,
120 suffix: Option<AnyElement>,
121 height: Option<DefiniteLength>,
121 height: Option<DefiniteLength>,
122 line_box_height: Option<Pixels>,
122 appearance: bool,
123 appearance: bool,
123 cleanable: bool,
124 cleanable: bool,
124 mask_toggle: bool,
125 mask_toggle: bool,
@@ -246,6 +247,7 @@ impl Input {
246 aria_label: None,
247 aria_label: None,
247 context_menu_builder: None,
248 context_menu_builder: None,
248 paste_handler: None,
249 paste_handler: None,
250 line_box_height: None,
249 token_renderer: None,
251 token_renderer: None,
250 token_click_listener: None,
252 token_click_listener: None,
251 token_hover_listener: None,
253 token_hover_listener: None,
@@ -295,6 +297,14 @@ impl Input {
295 self
297 self
296 }
298 }
297
299
300 /// Center each text line of a multi-line input in a box this tall, in
301 /// place of the size's vertical padding, so a single line is exactly this
302 /// tall and lines up with controls of the same height beside it.
303 pub fn line_box_height(mut self, height: Pixels) -> Self {
304 self.line_box_height = Some(height);
305 self
306 }
307
298 /// Set the appearance of the input field, if false the input field will no border, background.
308 /// Set the appearance of the input field, if false the input field will no border, background.
299 pub fn appearance(mut self, appearance: bool) -> Self {
309 pub fn appearance(mut self, appearance: bool) -> Self {
300 self.appearance = appearance;
310 self.appearance = appearance;
@@ -588,12 +598,15 @@ impl RenderOnce for Input {
588 },
598 },
589 cx,
599 cx,
590 );
600 );
601 let padding_y = self.line_box_height.map_or(self.size.input_py(), |height| {
602 ((height - LINE_HEIGHT.to_pixels(window.rem_size())) / 2.).max(px(0.))
603 });
591 state.set_editor_paddings(
604 state.set_editor_paddings(
592 if state.presentation(cx).is_multi_line() {
605 if state.presentation(cx).is_multi_line() {
593 Edges {
606 Edges {
594 top: self.size.input_py(),
607 top: padding_y,
595 right: self.size.input_px(),
608 right: self.size.input_px(),
596 bottom: self.size.input_py(),
609 bottom: padding_y,
597 left: if state.presentation(cx).is_code_editor() {
610 left: if state.presentation(cx).is_code_editor() {
598 self.size.input_px().min(px(6.))
611 self.size.input_px().min(px(6.))
599 } else {
612 } else {
vendor/gpui-component/src/input/textarea.rs +13 −2
@@ -1,8 +1,8 @@
1 1 use std::rc::Rc;
2 2
3 3 use gpui::{
4 App, DefiniteLength, Entity, IntoElement, RenderOnce, SharedString, StyleRefinement, Styled,
5 Window, prelude::FluentBuilder as _,
4 App, DefiniteLength, Entity, IntoElement, Pixels, RenderOnce, SharedString, StyleRefinement,
5 Styled, Window, prelude::FluentBuilder as _,
6 6 };
7 7
8 8 use super::{Input, TextareaState};
@@ -19,6 +19,7 @@ pub struct Textarea {
19 19 style: StyleRefinement,
20 20 size: Size,
21 21 height: Option<DefiniteLength>,
22 line_box_height: Option<Pixels>,
22 23 appearance: bool,
23 24 bordered: bool,
24 25 disabled: bool,
@@ -73,6 +74,7 @@ impl Textarea {
73 74 style: StyleRefinement::default(),
74 75 size: Size::default(),
75 76 height: None,
77 line_box_height: None,
76 78 appearance: true,
77 79 bordered: true,
78 80 disabled: false,
@@ -94,6 +96,12 @@ impl Textarea {
94 96 self
95 97 }
96 98
99 /// See [`Input::line_box_height`].
100 pub fn line_box_height(mut self, height: Pixels) -> Self {
101 self.line_box_height = Some(height);
102 self
103 }
104
97 105 pub fn appearance(mut self, appearance: bool) -> Self {
98 106 self.appearance = appearance;
99 107 self
@@ -204,6 +212,9 @@ impl Textarea {
204 212 .role(self.role)
205 213 .with_size(self.size)
206 214 .when_some(self.height, |this, height| this.h(height))
215 .when_some(self.line_box_height, |this, height| {
216 this.line_box_height(height)
217 })
207 218 .when_some(self.accessibility_id, |this, id| this.accessibility_id(id))
208 219 .when_some(self.aria_label, |this, label| this.aria_label(label))
209 220 .when_some(self.context_menu_builder, |this, build| {
@@ -1,8 +1,8 @@
1use std::rc::Rc;
1use std::rc::Rc;
2
2
3use gpui::{
3use gpui::{
4 App, DefiniteLength, Entity, IntoElement, RenderOnce, SharedString, StyleRefinement, Styled,
4 App, DefiniteLength, Entity, IntoElement, Pixels, RenderOnce, SharedString, StyleRefinement,
5 Window, prelude::FluentBuilder as _,
5 Styled, Window, prelude::FluentBuilder as _,
6};
6};
7
7
8use super::{Input, TextareaState};
8use super::{Input, TextareaState};
@@ -19,6 +19,7 @@ pub struct Textarea {
19 style: StyleRefinement,
19 style: StyleRefinement,
20 size: Size,
20 size: Size,
21 height: Option<DefiniteLength>,
21 height: Option<DefiniteLength>,
22 line_box_height: Option<Pixels>,
22 appearance: bool,
23 appearance: bool,
23 bordered: bool,
24 bordered: bool,
24 disabled: bool,
25 disabled: bool,
@@ -73,6 +74,7 @@ impl Textarea {
73 style: StyleRefinement::default(),
74 style: StyleRefinement::default(),
74 size: Size::default(),
75 size: Size::default(),
75 height: None,
76 height: None,
77 line_box_height: None,
76 appearance: true,
78 appearance: true,
77 bordered: true,
79 bordered: true,
78 disabled: false,
80 disabled: false,
@@ -94,6 +96,12 @@ impl Textarea {
94 self
96 self
95 }
97 }
96
98
99 /// See [`Input::line_box_height`].
100 pub fn line_box_height(mut self, height: Pixels) -> Self {
101 self.line_box_height = Some(height);
102 self
103 }
104
97 pub fn appearance(mut self, appearance: bool) -> Self {
105 pub fn appearance(mut self, appearance: bool) -> Self {
98 self.appearance = appearance;
106 self.appearance = appearance;
99 self
107 self
@@ -204,6 +212,9 @@ impl Textarea {
204 .role(self.role)
212 .role(self.role)
205 .with_size(self.size)
213 .with_size(self.size)
206 .when_some(self.height, |this, height| this.h(height))
214 .when_some(self.height, |this, height| this.h(height))
215 .when_some(self.line_box_height, |this, height| {
216 this.line_box_height(height)
217 })
207 .when_some(self.accessibility_id, |this, id| this.accessibility_id(id))
218 .when_some(self.accessibility_id, |this, id| this.accessibility_id(id))
208 .when_some(self.aria_label, |this, label| this.aria_label(label))
219 .when_some(self.aria_label, |this, label| this.aria_label(label))
209 .when_some(self.context_menu_builder, |this, build| {
220 .when_some(self.context_menu_builder, |this, build| {