Merge remote-tracking branch 'origin/main' into feat/appearance-themes
# Conflicts: # crates/app/src/views/title_bar.rs
@@ -8,9 +8,10 @@ macro_rules! symbols {
8
8
};
9
9
}
10
10
11
const SYMBOLS: [(&str, &[u8]); 54] = symbols![
11
const SYMBOLS: [(&str, &[u8]); 55] = symbols![
12
12
"bot",
13
13
"done",
14
"table",
14
15
"done_all",
15
16
"keyboard_return",
16
17
"schedule",
@@ -8,9 +8,10 @@ macro_rules! symbols {8
};8
};9
}9
}10
10
11
const SYMBOLS: [(&str, &[u8]); 54] = symbols![11
const SYMBOLS: [(&str, &[u8]); 55] = symbols![12
"bot",12
"bot",13
"done",13
"done",14
"table",14
"done_all",15
"done_all",15
"keyboard_return",16
"keyboard_return",16
"schedule",17
"schedule",@@ -9,7 +9,7 @@ use teams_core::EmoticonTag;
9
9
pub use strip::{StripImages, StripLoader, StripSource, split_strip};
10
10
11
11
const CATALOG: &str = include_str!("../../../app/assets/emoticons.tsv");
12
const ASSET_BASE: &str = "https://statics.teams.cdn.office.net/evergreen-assets/personal-expressions/v2/assets/emoticons";
12
const ASSET_BASE: &str = chatsvc::teams_cdn::EMOTICON_BASE_URL;
13
13
const ASSET_SIZE: u32 = 100;
14
14
const FRAMES_PER_SECOND: u64 = 24;
15
15
const VARIATION_SELECTOR: char = '\u{fe0f}';
@@ -9,7 +9,7 @@ use teams_core::EmoticonTag;9
pub use strip::{StripImages, StripLoader, StripSource, split_strip};9
pub use strip::{StripImages, StripLoader, StripSource, split_strip};10
10
11
const CATALOG: &str = include_str!("../../../app/assets/emoticons.tsv");11
const CATALOG: &str = include_str!("../../../app/assets/emoticons.tsv");12
const ASSET_BASE: &str = "https://statics.teams.cdn.office.net/evergreen-assets/personal-expressions/v2/assets/emoticons";12
const ASSET_BASE: &str = chatsvc::teams_cdn::EMOTICON_BASE_URL;13
const ASSET_SIZE: u32 = 100;13
const ASSET_SIZE: u32 = 100;14
const FRAMES_PER_SECOND: u64 = 24;14
const FRAMES_PER_SECOND: u64 = 24;15
const VARIATION_SELECTOR: char = '\u{fe0f}';15
const VARIATION_SELECTOR: char = '\u{fe0f}';@@ -8,8 +8,7 @@ use gpui_kit::App;
8
8
9
9
use super::platform;
10
10
11
pub const TEAMS_SOUND_BASE_URL: &str =
12
"https://statics.teams.cdn.office.net/evergreen-assets/audio/";
11
pub const TEAMS_SOUND_BASE_URL: &str = chatsvc::teams_cdn::SOUND_BASE_URL;
13
12
const SOUND_DIRECTORY: &str = "sounds";
14
13
const PARTIAL_SUFFIX: &str = ".partial";
15
14
@@ -8,8 +8,7 @@ use gpui_kit::App;8
8
9
use super::platform;9
use super::platform;10
10
11
pub const TEAMS_SOUND_BASE_URL: &str =11
pub const TEAMS_SOUND_BASE_URL: &str = chatsvc::teams_cdn::SOUND_BASE_URL;12
"https://statics.teams.cdn.office.net/evergreen-assets/audio/";13
const SOUND_DIRECTORY: &str = "sounds";12
const SOUND_DIRECTORY: &str = "sounds";14
const PARTIAL_SUFFIX: &str = ".partial";13
const PARTIAL_SUFFIX: &str = ".partial";15
14
@@ -1,7 +1,7 @@
1
1
use std::sync::OnceLock;
2
2
3
3
const CATALOG: &str = include_str!("../../app/assets/stickers.tsv");
4
const IMAGE_BASE: &str = "https://statics.teams.cdn.office.net/evergreen-assets/stickerassets";
4
const IMAGE_BASE: &str = chatsvc::teams_cdn::STICKER_BASE_URL;
5
5
const IMAGE_VERSION: u32 = 5;
6
6
const POPULAR_IDS: [&str; 6] = [
7
7
"Clippy_HelloThere",
@@ -1,7 +1,7 @@1
use std::sync::OnceLock;1
use std::sync::OnceLock;2
2
3
const CATALOG: &str = include_str!("../../app/assets/stickers.tsv");3
const CATALOG: &str = include_str!("../../app/assets/stickers.tsv");4
const IMAGE_BASE: &str = "https://statics.teams.cdn.office.net/evergreen-assets/stickerassets";4
const IMAGE_BASE: &str = chatsvc::teams_cdn::STICKER_BASE_URL;5
const IMAGE_VERSION: u32 = 5;5
const IMAGE_VERSION: u32 = 5;6
const POPULAR_IDS: [&str; 6] = [6
const POPULAR_IDS: [&str; 6] = [7
"Clippy_HelloThere",7
"Clippy_HelloThere",@@ -13,6 +13,7 @@ const QUOTE_BAR_WIDTH: f32 = 3.;
13
13
const QUOTE_INDENT: f32 = 12.;
14
14
const CODE_INDENT: f32 = 10.;
15
15
const LIST_LEVEL_INDENT: f32 = 18.;
16
const HEADING_SCALES: [f32; 3] = [1.6, 1.35, 1.15];
16
17
17
18
/// How the composer paints a draft: text styles, fills and the list markers to hang under.
18
19
pub struct DraftStyle {
@@ -24,7 +25,7 @@ pub struct DraftStyle {
24
25
25
26
fn line_indent(kind: &LineKind) -> f32 {
26
27
match kind {
27
LineKind::Text => 0.,
28
LineKind::Text | LineKind::Heading(_) | LineKind::Table(_) => 0.,
28
29
LineKind::Quote => QUOTE_INDENT,
29
30
LineKind::Code(_) => CODE_INDENT,
30
31
LineKind::Bullet(depth) | LineKind::Numbered(depth) => {
@@ -83,6 +84,16 @@ fn size_flags(kind: &MarkKind) -> StyleFlags {
83
84
flags
84
85
}
85
86
87
fn heading_decoration(content: Range<usize>, level: u8) -> TextDecoration {
88
let scale = HEADING_SCALES[usize::from(level.clamp(1, 3) - 1)];
89
let style = HighlightStyle {
90
font_weight: Some(FontWeight::BOLD),
91
color: Some(theme::text_strong()),
92
..Default::default()
93
};
94
TextDecoration::new(content, style).with_font_scale(scale)
95
}
96
86
97
/// From the start of the first line of `lines` to the end of the last; Block and Bar cover
87
98
/// every line starting inside it, ends included, so empty lines count too.
88
99
fn block_range(draft: &Draft, lines: Range<usize>) -> Range<usize> {
@@ -152,6 +163,7 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {
152
163
TextDecoration::new(content, color(theme::text_strong()))
153
164
.with_font_family(mono.clone()),
154
165
),
166
LineKind::Heading(level) => text.push(heading_decoration(content, *level)),
155
167
_ => {}
156
168
}
157
169
}
@@ -13,6 +13,7 @@ const QUOTE_BAR_WIDTH: f32 = 3.;13
const QUOTE_INDENT: f32 = 12.;13
const QUOTE_INDENT: f32 = 12.;14
const CODE_INDENT: f32 = 10.;14
const CODE_INDENT: f32 = 10.;15
const LIST_LEVEL_INDENT: f32 = 18.;15
const LIST_LEVEL_INDENT: f32 = 18.;16
const HEADING_SCALES: [f32; 3] = [1.6, 1.35, 1.15];16
17
17
/// How the composer paints a draft: text styles, fills and the list markers to hang under.18
/// How the composer paints a draft: text styles, fills and the list markers to hang under.18
pub struct DraftStyle {19
pub struct DraftStyle {@@ -24,7 +25,7 @@ pub struct DraftStyle {24
25
25
fn line_indent(kind: &LineKind) -> f32 {26
fn line_indent(kind: &LineKind) -> f32 {26
match kind {27
match kind {27
LineKind::Text => 0.,28
LineKind::Text | LineKind::Heading(_) | LineKind::Table(_) => 0.,28
LineKind::Quote => QUOTE_INDENT,29
LineKind::Quote => QUOTE_INDENT,29
LineKind::Code(_) => CODE_INDENT,30
LineKind::Code(_) => CODE_INDENT,30
LineKind::Bullet(depth) | LineKind::Numbered(depth) => {31
LineKind::Bullet(depth) | LineKind::Numbered(depth) => {@@ -83,6 +84,16 @@ fn size_flags(kind: &MarkKind) -> StyleFlags {83
flags84
flags84
}85
}85
86
87
fn heading_decoration(content: Range<usize>, level: u8) -> TextDecoration {88
let scale = HEADING_SCALES[usize::from(level.clamp(1, 3) - 1)];89
let style = HighlightStyle {90
font_weight: Some(FontWeight::BOLD),91
color: Some(theme::text_strong()),92
..Default::default()93
};94
TextDecoration::new(content, style).with_font_scale(scale)95
}96
86
/// From the start of the first line of `lines` to the end of the last; Block and Bar cover97
/// From the start of the first line of `lines` to the end of the last; Block and Bar cover87
/// every line starting inside it, ends included, so empty lines count too.98
/// every line starting inside it, ends included, so empty lines count too.88
fn block_range(draft: &Draft, lines: Range<usize>) -> Range<usize> {99
fn block_range(draft: &Draft, lines: Range<usize>) -> Range<usize> {@@ -152,6 +163,7 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {152
TextDecoration::new(content, color(theme::text_strong()))163
TextDecoration::new(content, color(theme::text_strong()))153
.with_font_family(mono.clone()),164
.with_font_family(mono.clone()),154
),165
),166
LineKind::Heading(level) => text.push(heading_decoration(content, *level)),155
_ => {}167
_ => {}156
}168
}157
}169
}@@ -0,0 +1 @@
1
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M200-120q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h560q33 0 56.5 23.5T840-760v560q0 33-23.5 56.5T760-120H200Zm240-240H200v160h240v-160Zm80 0v160h240v-160H520Zm-80-80v-160H200v160h240Zm80 0h240v-160H520v160ZM200-680h560v-80H200v80Z"/></svg>
@@ -0,0 +1 @@1
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M200-120q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h560q33 0 56.5 23.5T840-760v560q0 33-23.5 56.5T760-120H200Zm240-240H200v160h240v-160Zm80 0v160h240v-160H520Zm-80-80v-160H200v160h240Zm80 0h240v-160H520v160ZM200-680h560v-80H200v80Z"/></svg>@@ -177,6 +177,7 @@ mod frames {
177
177
use crate::views::call_transcript::TranscriptPanel;
178
178
use crate::views::call_view::CHAT_PANEL_TAG;
179
179
use crate::views::conversation::MEMBERS_BUTTON;
180
use crate::views::composer::{COMPOSER_BOX_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG};
180
181
use crate::views::message_row::BUBBLE_TAGS;
181
182
use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
182
183
use crate::views::reaction_proposal_pill::REACTION_PILL;
@@ -929,6 +930,76 @@ mod frames {
929
930
.join("\n")
930
931
);
931
932
}
933
const TITLE_SEARCH: &str = "shell/title-bar/search";
934
const TITLE_NEIGHBOURS: &[&str] = &[
935
"shell/title-bar/leading",
936
"shell/title-bar/mode-pill",
937
"shell/title-bar/trailing",
938
"shell/title-bar/update",
939
OWN_STATUS,
940
];
941
const TITLE_SEARCH_SIZES: [(f32, f32, bool); 3] = [
942
(1920., 1080., true),
943
(1280., 800., true),
944
(640., 480., false),
945
];
946
947
#[gpui_kit::test]
948
fn title_search_is_centered_on_the_window(cx: &mut TestAppContext) {
949
let (handle, _) = mount(cx);
950
let mut visual = VisualTestContext::from_window(handle, cx);
951
let shell = visual.update(|window, cx| {
952
window
953
.root::<gpui_kit::base::Root>()
954
.flatten()
955
.and_then(|root| root.read(cx).view().clone().downcast::<AppShell>().ok())
956
.expect("app shell is the root view")
957
});
958
visual.update(|_, cx| {
959
shell.update(cx, |shell, cx| {
960
shell.set_update_status(crate::updater::UpdateStatus::Ready, cx)
961
})
962
});
963
let mut found = Vec::new();
964
for (width, height, centered) in TITLE_SEARCH_SIZES {
965
visual.simulate_resize(size(px(width), px(height)));
966
collect(&mut visual, Some(TITLE_SEARCH));
967
let search = visual
968
.debug_bounds(TITLE_SEARCH)
969
.expect("title search rendered");
970
let search_center = f32::from(search.center().x);
971
eprintln!(
972
"title search @{width}x{height}: {} center {search_center:.1}, window center {:.1}",
973
describe(search),
974
width / 2.
975
);
976
if centered && (search_center - width / 2.).abs() > 1. {
977
found.push(format!(
978
"@{width}x{height}: search center {search_center:.1} is not the window center {:.1}",
979
width / 2.
980
));
981
}
982
if !contains(rectangle(0., 0., width, height), search) {
983
found.push(format!(
984
"@{width}x{height}: search {} leaves the window",
985
describe(search)
986
));
987
}
988
for neighbour in TITLE_NEIGHBOURS {
989
match visual.debug_bounds(neighbour) {
990
None => found.push(format!("@{width}x{height}: {neighbour} was not rendered")),
991
Some(bounds) if overlaps(search, bounds) => found.push(format!(
992
"@{width}x{height}: search {} overlaps {neighbour} {}",
993
describe(search),
994
describe(bounds)
995
)),
996
Some(_) => {}
997
}
998
}
999
}
1000
assert!(found.is_empty(), "{}", found.join("\n"));
1001
}
1002
932
1003
#[gpui_kit::test]
933
1004
fn call_chat_bubbles_stay_inside_the_panel(cx: &mut TestAppContext) {
934
1005
let (handle, app) = mount(cx);
@@ -1112,6 +1183,66 @@ mod frames {
1112
1183
}
1113
1184
}
1114
1185
1186
fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {
1187
collect(visual, Some(COMPOSER_SEND_TAG));
1188
let mut bounds_of = |path: &'static str| {
1189
visual
1190
.debug_bounds(path)
1191
.unwrap_or_else(|| panic!("{path} rendered"))
1192
};
1193
let composer = bounds_of(COMPOSER_BOX_TAG);
1194
let leading = bounds_of(COMPOSER_LEADING_TAG);
1195
let send = bounds_of(COMPOSER_SEND_TAG);
1196
[
1197
f32::from(leading.left() - composer.left()),
1198
f32::from(leading.top() - composer.top()),
1199
f32::from(composer.bottom() - leading.bottom()),
1200
f32::from(composer.right() - send.right()),
1201
f32::from(send.top() - composer.top()),
1202
f32::from(composer.bottom() - send.bottom()),
1203
]
1204
}
1205
1206
#[gpui_kit::test]
1207
fn composer_buttons_keep_equal_insets(cx: &mut TestAppContext) {
1208
let (handle, _) = mount(cx);
1209
let mut visual = VisualTestContext::from_window(handle, cx);
1210
visual.simulate_resize(size(px(1280.), px(800.)));
1211
let single_line = composer_button_insets(&mut visual);
1212
let left = single_line[0];
1213
assert!(
1214
single_line
1215
.iter()
1216
.all(|inset| (inset - left).abs() < TOLERANCE),
1217
"single line: insets left, top, bottom of the first button and right, top, bottom of send {single_line:?}"
1218
);
1219
let leading = visual
1220
.debug_bounds(COMPOSER_LEADING_TAG)
1221
.expect("leading buttons");
1222
let send = visual.debug_bounds(COMPOSER_SEND_TAG).expect("send button");
1223
visual.simulate_click(
1224
point((leading.right() + send.left()) / 2., send.center().y),
1225
Default::default(),
1226
);
1227
visual.simulate_keystrokes("o n e shift-enter t w o shift-enter t h r e e");
1228
let three_lines = composer_button_insets(&mut visual);
1229
assert!(
1230
three_lines[1] > single_line[1] + 30.,
1231
"three lines did not grow the composer: {three_lines:?}"
1232
);
1233
for inset in [
1234
three_lines[0],
1235
three_lines[2],
1236
three_lines[3],
1237
three_lines[5],
1238
] {
1239
assert!(
1240
(inset - left).abs() < TOLERANCE,
1241
"three lines: insets left, top, bottom of the first button and right, top, bottom of send {three_lines:?}, expected {left}"
1242
);
1243
}
1244
}
1245
1115
1246
#[gpui_kit::test]
1116
1247
fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {
1117
1248
let (handle, state) = mount_with(cx, true);
@@ -1415,3 +1546,73 @@ fn surfaces_are_soft() {
1415
1546
let report: Vec<String> = violations.into_iter().chain(stale).collect();
1416
1547
assert!(report.is_empty(), "{}", report.join("\n"));
1417
1548
}
1549
1550
fn indentation(line: &str) -> usize {
1551
line.len() - line.trim_start().len()
1552
}
1553
1554
fn chain_lines<'a>(lines: &[&'a str], index: usize) -> Vec<&'a str> {
1555
let indent = indentation(lines[index]);
1556
let belongs = |line: &&str| line.trim().is_empty() || indentation(line) >= indent;
1557
let start = lines[..index]
1558
.iter()
1559
.rposition(|line| !belongs(line))
1560
.map_or(0, |position| position + 1);
1561
let end = lines[index..]
1562
.iter()
1563
.position(|line| !belongs(line))
1564
.map_or(lines.len(), |position| index + position);
1565
lines[start..end]
1566
.iter()
1567
.filter(|line| indentation(line) == indent)
1568
.copied()
1569
.collect()
1570
}
1571
1572
fn shrinking_rows(row_height: &Regex, source: &str) -> Vec<usize> {
1573
let lines: Vec<&str> = source.lines().collect();
1574
(0..lines.len())
1575
.filter(|&index| row_height.is_match(lines[index]))
1576
.filter(|&index| {
1577
!chain_lines(&lines, index).iter().any(|line| {
1578
let line = line.trim();
1579
line.starts_with(".flex_none()") || line.starts_with(".flex_shrink_0()")
1580
})
1581
})
1582
.map(|index| index + 1)
1583
.collect()
1584
}
1585
1586
fn row_height_pattern() -> Regex {
1587
Regex::new(r"^\s*\.h\(px\(((\w+_)?(ROW|ENTRY)_HEIGHT|row_height)\)\)").expect("pattern")
1588
}
1589
1590
#[test]
1591
fn matcher_finds_rows_without_flex_none() {
1592
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";
1593
assert_eq!(shrinking_rows(&row_height_pattern(), source), [3]);
1594
}
1595
1596
#[test]
1597
fn fixed_height_rows_never_shrink() {
1598
let row_height = row_height_pattern();
1599
let mut files = Vec::new();
1600
for root in source_roots() {
1601
source_files(&root, &mut files);
1602
}
1603
let violations: Vec<String> = files
1604
.iter()
1605
.filter(|file| !file.ends_with("layout_guard.rs"))
1606
.flat_map(|file| {
1607
let source = fs::read_to_string(file).expect("read source file");
1608
shrinking_rows(&row_height, &source)
1609
.into_iter()
1610
.map(|line| format!("{}:{line}", file.display()))
1611
.collect::<Vec<_>>()
1612
})
1613
.collect();
1614
assert!(
1615
violations.is_empty(),
1616
"a fixed-height row needs .flex_none(), or a max_h scroll list shrinks it to its content: {violations:?}"
1617
);
1618
}
@@ -177,6 +177,7 @@ mod frames {177
use crate::views::call_transcript::TranscriptPanel;177
use crate::views::call_transcript::TranscriptPanel;178
use crate::views::call_view::CHAT_PANEL_TAG;178
use crate::views::call_view::CHAT_PANEL_TAG;179
use crate::views::conversation::MEMBERS_BUTTON;179
use crate::views::conversation::MEMBERS_BUTTON;180
use crate::views::composer::{COMPOSER_BOX_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG};180
use crate::views::message_row::BUBBLE_TAGS;181
use crate::views::message_row::BUBBLE_TAGS;181
use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};182
use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};182
use crate::views::reaction_proposal_pill::REACTION_PILL;183
use crate::views::reaction_proposal_pill::REACTION_PILL;@@ -929,6 +930,76 @@ mod frames {929
.join("\n")930
.join("\n")930
);931
);931
}932
}933
const TITLE_SEARCH: &str = "shell/title-bar/search";934
const TITLE_NEIGHBOURS: &[&str] = &[935
"shell/title-bar/leading",936
"shell/title-bar/mode-pill",937
"shell/title-bar/trailing",938
"shell/title-bar/update",939
OWN_STATUS,940
];941
const TITLE_SEARCH_SIZES: [(f32, f32, bool); 3] = [942
(1920., 1080., true),943
(1280., 800., true),944
(640., 480., false),945
];946
947
#[gpui_kit::test]948
fn title_search_is_centered_on_the_window(cx: &mut TestAppContext) {949
let (handle, _) = mount(cx);950
let mut visual = VisualTestContext::from_window(handle, cx);951
let shell = visual.update(|window, cx| {952
window953
.root::<gpui_kit::base::Root>()954
.flatten()955
.and_then(|root| root.read(cx).view().clone().downcast::<AppShell>().ok())956
.expect("app shell is the root view")957
});958
visual.update(|_, cx| {959
shell.update(cx, |shell, cx| {960
shell.set_update_status(crate::updater::UpdateStatus::Ready, cx)961
})962
});963
let mut found = Vec::new();964
for (width, height, centered) in TITLE_SEARCH_SIZES {965
visual.simulate_resize(size(px(width), px(height)));966
collect(&mut visual, Some(TITLE_SEARCH));967
let search = visual968
.debug_bounds(TITLE_SEARCH)969
.expect("title search rendered");970
let search_center = f32::from(search.center().x);971
eprintln!(972
"title search @{width}x{height}: {} center {search_center:.1}, window center {:.1}",973
describe(search),974
width / 2.975
);976
if centered && (search_center - width / 2.).abs() > 1. {977
found.push(format!(978
"@{width}x{height}: search center {search_center:.1} is not the window center {:.1}",979
width / 2.980
));981
}982
if !contains(rectangle(0., 0., width, height), search) {983
found.push(format!(984
"@{width}x{height}: search {} leaves the window",985
describe(search)986
));987
}988
for neighbour in TITLE_NEIGHBOURS {989
match visual.debug_bounds(neighbour) {990
None => found.push(format!("@{width}x{height}: {neighbour} was not rendered")),991
Some(bounds) if overlaps(search, bounds) => found.push(format!(992
"@{width}x{height}: search {} overlaps {neighbour} {}",993
describe(search),994
describe(bounds)995
)),996
Some(_) => {}997
}998
}999
}1000
assert!(found.is_empty(), "{}", found.join("\n"));1001
}1002
932
#[gpui_kit::test]1003
#[gpui_kit::test]933
fn call_chat_bubbles_stay_inside_the_panel(cx: &mut TestAppContext) {1004
fn call_chat_bubbles_stay_inside_the_panel(cx: &mut TestAppContext) {934
let (handle, app) = mount(cx);1005
let (handle, app) = mount(cx);@@ -1112,6 +1183,66 @@ mod frames {1112
}1183
}1113
}1184
}1114
1185
1186
fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {1187
collect(visual, Some(COMPOSER_SEND_TAG));1188
let mut bounds_of = |path: &'static str| {1189
visual1190
.debug_bounds(path)1191
.unwrap_or_else(|| panic!("{path} rendered"))1192
};1193
let composer = bounds_of(COMPOSER_BOX_TAG);1194
let leading = bounds_of(COMPOSER_LEADING_TAG);1195
let send = bounds_of(COMPOSER_SEND_TAG);1196
[1197
f32::from(leading.left() - composer.left()),1198
f32::from(leading.top() - composer.top()),1199
f32::from(composer.bottom() - leading.bottom()),1200
f32::from(composer.right() - send.right()),1201
f32::from(send.top() - composer.top()),1202
f32::from(composer.bottom() - send.bottom()),1203
]1204
}1205
1206
#[gpui_kit::test]1207
fn composer_buttons_keep_equal_insets(cx: &mut TestAppContext) {1208
let (handle, _) = mount(cx);1209
let mut visual = VisualTestContext::from_window(handle, cx);1210
visual.simulate_resize(size(px(1280.), px(800.)));1211
let single_line = composer_button_insets(&mut visual);1212
let left = single_line[0];1213
assert!(1214
single_line1215
.iter()1216
.all(|inset| (inset - left).abs() < TOLERANCE),1217
"single line: insets left, top, bottom of the first button and right, top, bottom of send {single_line:?}"1218
);1219
let leading = visual1220
.debug_bounds(COMPOSER_LEADING_TAG)1221
.expect("leading buttons");1222
let send = visual.debug_bounds(COMPOSER_SEND_TAG).expect("send button");1223
visual.simulate_click(1224
point((leading.right() + send.left()) / 2., send.center().y),1225
Default::default(),1226
);1227
visual.simulate_keystrokes("o n e shift-enter t w o shift-enter t h r e e");1228
let three_lines = composer_button_insets(&mut visual);1229
assert!(1230
three_lines[1] > single_line[1] + 30.,1231
"three lines did not grow the composer: {three_lines:?}"1232
);1233
for inset in [1234
three_lines[0],1235
three_lines[2],1236
three_lines[3],1237
three_lines[5],1238
] {1239
assert!(1240
(inset - left).abs() < TOLERANCE,1241
"three lines: insets left, top, bottom of the first button and right, top, bottom of send {three_lines:?}, expected {left}"1242
);1243
}1244
}1245
1115
#[gpui_kit::test]1246
#[gpui_kit::test]1116
fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {1247
fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {1117
let (handle, state) = mount_with(cx, true);1248
let (handle, state) = mount_with(cx, true);@@ -1415,3 +1546,73 @@ fn surfaces_are_soft() {1415
let report: Vec<String> = violations.into_iter().chain(stale).collect();1546
let report: Vec<String> = violations.into_iter().chain(stale).collect();1416
assert!(report.is_empty(), "{}", report.join("\n"));1547
assert!(report.is_empty(), "{}", report.join("\n"));1417
}1548
}1549
1550
fn indentation(line: &str) -> usize {1551
line.len() - line.trim_start().len()1552
}1553
1554
fn chain_lines<'a>(lines: &[&'a str], index: usize) -> Vec<&'a str> {1555
let indent = indentation(lines[index]);1556
let belongs = |line: &&str| line.trim().is_empty() || indentation(line) >= indent;1557
let start = lines[..index]1558
.iter()1559
.rposition(|line| !belongs(line))1560
.map_or(0, |position| position + 1);1561
let end = lines[index..]1562
.iter()1563
.position(|line| !belongs(line))1564
.map_or(lines.len(), |position| index + position);1565
lines[start..end]1566
.iter()1567
.filter(|line| indentation(line) == indent)1568
.copied()1569
.collect()1570
}1571
1572
fn shrinking_rows(row_height: &Regex, source: &str) -> Vec<usize> {1573
let lines: Vec<&str> = source.lines().collect();1574
(0..lines.len())1575
.filter(|&index| row_height.is_match(lines[index]))1576
.filter(|&index| {1577
!chain_lines(&lines, index).iter().any(|line| {1578
let line = line.trim();1579
line.starts_with(".flex_none()") || line.starts_with(".flex_shrink_0()")1580
})1581
})1582
.map(|index| index + 1)1583
.collect()1584
}1585
1586
fn row_height_pattern() -> Regex {1587
Regex::new(r"^\s*\.h\(px\(((\w+_)?(ROW|ENTRY)_HEIGHT|row_height)\)\)").expect("pattern")1588
}1589
1590
#[test]1591
fn matcher_finds_rows_without_flex_none() {1592
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";1593
assert_eq!(shrinking_rows(&row_height_pattern(), source), [3]);1594
}1595
1596
#[test]1597
fn fixed_height_rows_never_shrink() {1598
let row_height = row_height_pattern();1599
let mut files = Vec::new();1600
for root in source_roots() {1601
source_files(&root, &mut files);1602
}1603
let violations: Vec<String> = files1604
.iter()1605
.filter(|file| !file.ends_with("layout_guard.rs"))1606
.flat_map(|file| {1607
let source = fs::read_to_string(file).expect("read source file");1608
shrinking_rows(&row_height, &source)1609
.into_iter()1610
.map(|line| format!("{}:{line}", file.display()))1611
.collect::<Vec<_>>()1612
})1613
.collect();1614
assert!(1615
violations.is_empty(),1616
"a fixed-height row needs .flex_none(), or a max_h scroll list shrinks it to its content: {violations:?}"1617
);1618
}@@ -13,8 +13,19 @@ actions!(
13
13
ToggleSubscript,
14
14
ToggleCode,
15
15
EditLink,
16
ScheduleSend
16
ScheduleSend,
17
PastePlainText,
18
InsertTableRowAbove,
19
InsertTableRowBelow,
20
InsertTableColumnLeft,
21
InsertTableColumnRight,
22
DeleteTableRow,
23
DeleteTableColumn,
24
DeleteTable
17
25
]
18
26
);
19
27
20
actions!(teams, [ReplyToHovered, OpenSwitcher, NewChat, ToggleCallMute]);
28
actions!(
29
teams,
30
[ReplyToHovered, OpenSwitcher, NewChat, ToggleCallMute]
31
);
@@ -13,8 +13,19 @@ actions!(13
ToggleSubscript,13
ToggleSubscript,14
ToggleCode,14
ToggleCode,15
EditLink,15
EditLink,16
ScheduleSend16
ScheduleSend,17
PastePlainText,18
InsertTableRowAbove,19
InsertTableRowBelow,20
InsertTableColumnLeft,21
InsertTableColumnRight,22
DeleteTableRow,23
DeleteTableColumn,24
DeleteTable17
]25
]18
);26
);19
27
20
actions!(teams, [ReplyToHovered, OpenSwitcher, NewChat, ToggleCallMute]);28
actions!(29
teams,30
[ReplyToHovered, OpenSwitcher, NewChat, ToggleCallMute]31
);@@ -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()@@ -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()
@@ -154,10 +156,16 @@ fn member_row(
154
156
None => avatar,
155
157
};
156
158
let opens_chat = user_id.filter(|_| !row.is_self).map(str::to_owned);
159
let row_height = if row.is_self {
160
OWN_ROW_HEIGHT
161
} else {
162
ROW_HEIGHT
163
};
157
164
h_flex()
158
165
.id(("chat-member", index))
159
166
.group(group.clone())
160
.h(px(ROW_HEIGHT))
167
.h(px(row_height))
168
.flex_none()
161
169
.px(px(EDGE_PADDING))
162
170
.gap(px(8.))
163
171
.items_center()
@@ -22,6 +22,7 @@ const LIST_MAX_HEIGHT: f32 = 300.;22
const POPUP_OFFSET: f32 = 16.;22
const POPUP_OFFSET: f32 = 16.;23
const SECTION_HEIGHT: f32 = 24.;23
const SECTION_HEIGHT: f32 = 24.;24
const ROW_HEIGHT: f32 = 40.;24
const ROW_HEIGHT: f32 = 40.;25
const OWN_ROW_HEIGHT: f32 = 43.;25
const AVATAR_SIZE: f32 = 32.;26
const AVATAR_SIZE: f32 = 32.;26
const EDGE_PADDING: f32 = 12.;27
const EDGE_PADDING: f32 = 12.;27
const ACTION_HEIGHT: f32 = 36.;28
const 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()@@ -154,10 +156,16 @@ fn member_row(154
None => avatar,156
None => avatar,155
};157
};156
let opens_chat = user_id.filter(|_| !row.is_self).map(str::to_owned);158
let opens_chat = user_id.filter(|_| !row.is_self).map(str::to_owned);159
let row_height = if row.is_self {160
OWN_ROW_HEIGHT161
} else {162
ROW_HEIGHT163
};157
h_flex()164
h_flex()158
.id(("chat-member", index))165
.id(("chat-member", index))159
.group(group.clone())166
.group(group.clone())160
.h(px(ROW_HEIGHT))167
.h(px(row_height))168
.flex_none()161
.px(px(EDGE_PADDING))169
.px(px(EDGE_PADDING))162
.gap(px(8.))170
.gap(px(8.))163
.items_center()171
.items_center()@@ -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> </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 _;24
use gpui_kit::*;25
use gpui_kit::*;25
use teams_core::{26
use teams_core::{26
Draft, DraftLine, Edit, FileReference, FormatState, LineKind, LinkPreview, MarkKind,27
Draft, DraftLine, Edit, FileReference, FormatState, LineKind, LinkPreview, MarkKind,27
MentionCandidate, MentionInput, OBJECT_MARK, SizeStep, TypingStyle,28
MentionCandidate, MentionInput, OBJECT_MARK, SizeStep, TABLE_MARK, TableEdit, TypingStyle,28
UploadedFile, changed_span, has_markdown, link_url, map_offset, reverse_edits,29
UploadedFile, changed_span, has_markdown, link_url, map_offset, reverse_edits,29
};30
};30
31
31
mod drafts;32
mod drafts;32
mod schedule;33
mod schedule;34
mod table;33
35
34
use super::actions::{36
use super::actions::{35
COMPOSER_KEY_CONTEXT, EditLink, OpenSwitcher, ScheduleSend, ToggleBold, ToggleCode, ToggleItalic,37
COMPOSER_KEY_CONTEXT, DeleteTable, DeleteTableColumn, DeleteTableRow, EditLink,36
ToggleStrike, ToggleSubscript, ToggleSuperscript, ToggleUnderline,38
InsertTableColumnLeft, InsertTableColumnRight, InsertTableRowAbove, InsertTableRowBelow,39
OpenSwitcher, PastePlainText, ScheduleSend, ToggleBold, ToggleCode, ToggleItalic, ToggleStrike,40
ToggleSubscript, ToggleSuperscript, ToggleUnderline,37
};41
};38
use super::attachment_tray::{42
use super::attachment_tray::{39
AttachmentTray, DoneFile, JobKind, LoadedFile, MAX_ATTACHMENTS,43
AttachmentTray, DoneFile, JobKind, LoadedFile, MAX_ATTACHMENTS, PasteAction, UploadJob,40
PasteAction, UploadJob, UploadResult, discard_uploaded, inline_preview, names_of, paste_action,44
UploadResult, discard_uploaded, inline_preview, names_of, paste_action, pasted_image_name,41
pasted_image_name, prepare_pasted_image, read_attachment, render_tray,45
prepare_pasted_image, read_attachment, render_tray,42
};46
};43
use super::avatar::{person_avatar, square_avatar};47
use super::avatar::{person_avatar, square_avatar};44
use super::draft_style::draft_style;48
use super::draft_style::draft_style;@@ -55,6 +59,7 @@ use crate::runtime;55
use crate::scheduled_rows::scheduled_label;59
use crate::scheduled_rows::scheduled_label;56
use crate::theme::{self, ElevatedSurface as _};60
use crate::theme::{self, ElevatedSurface as _};57
use crate::typing::OutgoingTyping;61
use crate::typing::OutgoingTyping;62
use table::{TableKey, TablePicker, TableViews, is_table_token};58
63
59
const MIN_ROWS: usize = 1;64
const MIN_ROWS: usize = 1;60
const MAX_ROWS: usize = 8;65
const MAX_ROWS: usize = 8;@@ -67,6 +72,11 @@ const POPUP_WIDTH: f32 = 380.;67
const POPUP_ROW_HEIGHT: f32 = 44.;72
const POPUP_ROW_HEIGHT: f32 = 44.;68
const DEMO_UPLOAD_STEPS: u8 = 10;73
const DEMO_UPLOAD_STEPS: u8 = 10;69
const COMPOSER_ICON_SIZE: f32 = 20.;74
const COMPOSER_ICON_SIZE: f32 = 20.;75
const COMPOSER_BUTTON_SIZE: f32 = 32.;76
const COMPOSER_BUTTON_INSET: f32 = 6.;77
pub const COMPOSER_BOX_TAG: &str = "composer";78
pub const COMPOSER_LEADING_TAG: &str = "composer/leading";79
pub const COMPOSER_SEND_TAG: &str = "composer/send";70
/// gpui-kit draws a `Size::Size` button's icon at this fraction of the button size.80
/// gpui-kit draws a `Size::Size` button's icon at this fraction of the button size.71
const BUTTON_ICON_SCALE: f32 = 0.75;81
const BUTTON_ICON_SCALE: f32 = 0.75;72
const DEMO_UPLOAD_STEP: Duration = Duration::from_millis(120);82
const DEMO_UPLOAD_STEP: Duration = Duration::from_millis(120);@@ -126,8 +136,19 @@ struct Conversion {126
136
127
#[derive(Debug, Clone, Copy, PartialEq, Eq)]137
#[derive(Debug, Clone, Copy, PartialEq, Eq)]128
enum StepKind {138
enum StepKind {129
Typing { at: usize, after_space: bool },139
Typing {130
Deleting { start: usize, end: usize },140
at: usize,141
after_space: bool,142
},143
Deleting {144
start: usize,145
end: usize,146
},147
CellTyping {148
table: usize,149
row: usize,150
column: usize,151
},131
Other,152
Other,132
}153
}133
154
@@ -192,6 +213,12 @@ pub struct Composer {192
pending_anchors: HashMap<u64, usize>,213
pending_anchors: HashMap<u64, usize>,193
link: ComposeLink,214
link: ComposeLink,194
fun_picker: Entity<FunPicker>,215
fun_picker: Entity<FunPicker>,216
tables: TableViews,217
table_counter: usize,218
table_picker: Option<TablePicker>,219
active_cell: Option<(String, teams_core::Cell)>,220
caret_before_table: usize,221
caret_text: String,195
_subscriptions: [Subscription; 4],222
_subscriptions: [Subscription; 4],196
}223
}197
224
@@ -292,6 +319,9 @@ fn continues(last: &HistoryStep, kind: StepKind) -> bool {292
(StepKind::Deleting { .. }, StepKind::Deleting { start, end }) => {319
(StepKind::Deleting { .. }, StepKind::Deleting { start, end }) => {293
caret.is_empty() && (caret.start == end || caret.start == start)320
caret.is_empty() && (caret.start == end || caret.start == start)294
}321
}322
(previous @ StepKind::CellTyping { .. }, next @ StepKind::CellTyping { .. }) => {323
previous == next324
}295
_ => false,325
_ => false,296
}326
}297
}327
}@@ -328,7 +358,10 @@ impl Composer {328
.placeholder("Type a message")358
.placeholder("Type a message")329
});359
});330
let subscription = cx.subscribe_in(&input, window, Self::on_input_event);360
let subscription = cx.subscribe_in(&input, window, Self::on_input_event);331
let observer = cx.observe(&input, |_, _, cx| cx.notify());361
let observer = cx.observe_in(&input, window, |this, _, window, cx| {362
this.redirect_caret_from_table(window, cx);363
cx.notify();364
});332
let image_observer = cx.observe(&app, |this, _, cx| {365
let image_observer = cx.observe(&app, |this, _, cx| {333
if this.link_image_pending(cx) {366
if this.link_image_pending(cx) {334
cx.notify();367
cx.notify();@@ -389,6 +422,12 @@ impl Composer {389
pending_anchors: HashMap::new(),422
pending_anchors: HashMap::new(),390
link: ComposeLink::default(),423
link: ComposeLink::default(),391
fun_picker,424
fun_picker,425
tables: TableViews::default(),426
table_counter: 0,427
table_picker: None,428
active_cell: None,429
caret_before_table: 0,430
caret_text: String::new(),392
_subscriptions: [subscription, observer, image_observer, picker_subscription],431
_subscriptions: [subscription, observer, image_observer, picker_subscription],393
}432
}394
}433
}@@ -640,6 +679,7 @@ impl Composer {640
}679
}641
self.previous_value = value;680
self.previous_value = value;642
self.refresh_style(cx);681
self.refresh_style(cx);682
self.sync_tables(window, cx);643
}683
}644
684
645
fn shift_anchors(&mut self, start: usize, old_end: usize, new_end: usize) {685
fn shift_anchors(&mut self, start: usize, old_end: usize, new_end: usize) {@@ -737,6 +777,7 @@ impl Composer {737
self.conversion = None;777
self.conversion = None;738
self.paste_hint = None;778
self.paste_hint = None;739
self.refresh_style(cx);779
self.refresh_style(cx);780
self.sync_tables(window, cx);740
self.update_emoji(cx);781
self.update_emoji(cx);741
self.update_mention(cx);782
self.update_mention(cx);742
self.schedule_draft_save(cx);783
self.schedule_draft_save(cx);@@ -775,6 +816,9 @@ impl Composer {775
self.link_editor = None;816
self.link_editor = None;776
self.toolbar_dismissed = None;817
self.toolbar_dismissed = None;777
self.pending_anchors.clear();818
self.pending_anchors.clear();819
self.active_cell = None;820
self.table_picker = None;821
self.sync_tables(window, cx);778
self.history.clear();822
self.history.clear();779
self.history_index = 0;823
self.history_index = 0;780
self.record(StepKind::Other, cx);824
self.record(StepKind::Other, cx);@@ -1064,6 +1108,64 @@ impl Composer {1064
}1108
}1065
}1109
}1066
1110
1111
fn leave_quote(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {1112
let selection = self.selection(cx);1113
if !selection.is_empty() || self.input.read(cx).value().as_ref() != self.draft.text() {1114
return false;1115
}1116
match self.draft.leave_quote_at_end(selection.start) {1117
Some(cursor) => {1118
self.commit(Some(cursor), window, cx);1119
true1120
}1121
None => false,1122
}1123
}1124
1125
/// Backspace right after a table or Delete right before one goes into it instead of1126
/// joining the line with the table's.1127
fn enter_table_beside(1128
&mut self,1129
after: bool,1130
window: &mut Window,1131
cx: &mut Context<Self>,1132
) -> bool {1133
let selection = self.selection(cx);1134
if !selection.is_empty() || self.input.read(cx).value().as_ref() != self.draft.text() {1135
return false;1136
}1137
let found = if after {1138
self.draft.table_before(selection.start)1139
} else {1140
self.draft.table_after(selection.start)1141
};1142
let Some(index) = found else {1143
return false;1144
};1145
self.focus_table_line(index, after, window, cx);1146
true1147
}1148
1149
fn cell_has_focus(&self, window: &Window, cx: &App) -> bool {1150
self.focused_cell(window, cx).is_some()1151
}1152
1153
fn paste_plain(&mut self, window: &mut Window, cx: &mut Context<Self>) {1154
let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) else {1155
return;1156
};1157
let text = text1158
.replace("\r\n", "\n")1159
.replace([OBJECT_MARK, TABLE_MARK], "");1160
if let Some(input) = self.focused_cell_input(window, cx) {1161
input.update(cx, |state, cx| state.replace(text, window, cx));1162
return;1163
}1164
self.pasted_markdown = None;1165
self.input1166
.update(cx, |state, cx| state.replace(text, window, cx));1167
}1168
1067
fn indent(&mut self, outdent: bool, window: &mut Window, cx: &mut Context<Self>) -> bool {1169
fn indent(&mut self, outdent: bool, window: &mut Window, cx: &mut Context<Self>) -> bool {1068
let selection = self.selection(cx);1170
let selection = self.selection(cx);1069
if !self.draft.indent(selection, outdent) {1171
if !self.draft.indent(selection, outdent) {@@ -1079,12 +1181,16 @@ impl Composer {1079
return false;1181
return false;1080
}1182
}1081
let selected = &self.draft.text()[selection.clone()];1183
let selected = &self.draft.text()[selection.clone()];1082
let text = selected.replace(OBJECT_MARK, "");1083
let lines = if selected.contains(OBJECT_MARK) {1184
let lines = if selected.contains(OBJECT_MARK) {1084
self.draft.slice_without_objects(selection)1185
self.draft.slice_without_objects(selection)1085
} else {1186
} else {1086
self.draft.slice(selection)1187
self.draft.slice(selection)1087
};1188
};1189
let text = if selected.contains(TABLE_MARK) {1190
Draft::from_lines(&lines).plain_text()1191
} else {1192
selected.replace(OBJECT_MARK, "")1193
};1088
if text.is_empty() {1194
if text.is_empty() {1089
return true;1195
return true;1090
}1196
}@@ -1150,8 +1256,8 @@ impl Composer {1150
}1256
}1151
let matches = emoji::search(&query, &self.recent_emoji.glyphs(), emoji_popup::LIMIT);1257
let matches = emoji::search(&query, &self.recent_emoji.glyphs(), emoji_popup::LIMIT);1152
let skin_tone = teams_core::skin_tone(&self.app.read(cx).store);1258
let skin_tone = teams_core::skin_tone(&self.app.read(cx).store);1153
self.emoji_popup = (!matches.is_empty())1259
self.emoji_popup =1154
.then(|| EmojiPopup::new(range, query, matches, skin_tone));1260
(!matches.is_empty()).then(|| EmojiPopup::new(range, query, matches, skin_tone));1155
}1261
}1156
1262
1157
fn accept_emoji(&mut self, window: &mut Window, cx: &mut Context<Self>) {1263
fn accept_emoji(&mut self, window: &mut Window, cx: &mut Context<Self>) {@@ -1764,8 +1870,8 @@ impl Composer {1764
let Some(text) = item.text() else {1870
let Some(text) = item.text() else {1765
return false;1871
return false;1766
};1872
};1767
if text.contains(OBJECT_MARK) {1873
if text.contains([OBJECT_MARK, TABLE_MARK]) {1768
let cleaned = text.replace(OBJECT_MARK, "");1874
let cleaned = text.replace([OBJECT_MARK, TABLE_MARK], "");1769
self.input1875
self.input1770
.update(cx, |state, cx| state.replace(cleaned, window, cx));1876
.update(cx, |state, cx| state.replace(cleaned, window, cx));1771
return true;1877
return true;@@ -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_composer2610
.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) = context2617
if let Some(id) = context2480
.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.input2780
this.input2609
.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_INSET2961
} 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
outgoing3209
outgoing2989
.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> </td></tr>\4282
</tbody></table></figure>after"4283
);4284
}4285
4286
#[gpui_kit::test]4287
fn deleting_the_last_column_deletes_the_table(cx: &mut TestAppContext) {4288
let mut typist = typist(cx);4289
insert_table(&mut typist, 1, 1);4290
let composer = typist.composer.clone();4291
typist.act(|window, cx| {4292
composer.update(cx, |composer, cx| {4293
composer.edit_table(teams_core::TableEdit::DeleteColumn, window, cx)4294
});4295
});4296
assert!(typist.draft().lines().iter().all(|kind| !kind.is_table()));4297
}4298
4299
#[gpui_kit::test]4300
fn a_pasted_markdown_table_becomes_a_table(cx: &mut TestAppContext) {4301
let mut typist = typist(cx);4302
typist4303
.cx4304
.write_to_clipboard(gpui_kit::ClipboardItem::new_string(4305
"| A | B |\n|---|---|\n| 1 | 2 |".to_owned(),4306
));4307
typist.press("ctrl-v");4308
assert!(typist.draft().lines()[0].is_table());4309
assert_eq!(4310
typist.outgoing().html(),4311
"<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\4312
<tr><td>A</td><td>B</td></tr><tr><td>1</td><td>2</td></tr>\4313
</tbody></table></figure>"4314
);4315
}4316
4317
#[gpui_kit::test]4318
fn ctrl_shift_v_pastes_markdown_as_plain_text(cx: &mut TestAppContext) {4319
let mut typist = typist(cx);4320
typist4321
.cx4322
.write_to_clipboard(gpui_kit::ClipboardItem::new_string(4323
"**hi** there".to_owned(),4324
));4325
typist.press("ctrl-shift-v");4326
assert_eq!(typist.value(), "**hi** there");4327
assert!(typist.draft().marks().is_empty());4328
}4329
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);@@ -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()@@ -0,0 +1,630 @@
1
use std::collections::HashMap;
2
use std::ops::Range;
3
4
use gpui_kit::component::input::{
5
Copy, Cut, InlineToken, InputEvent, Paste, Textarea, TextareaState,
6
};
7
use gpui_kit::component::native_menu::NativeMenu;
8
use gpui_kit::component::{Sizable as _, h_flex, v_flex};
9
use gpui_kit::*;
10
use teams_core::{Cell, PICKER_COLUMNS, PICKER_ROWS, TABLE_MARK, Table, TableEdit};
11
12
use super::{Composer, StepKind};
13
use crate::theme::{self, ElevatedSurface as _};
14
use crate::views::actions::{
15
DeleteTable, DeleteTableColumn, DeleteTableRow, InsertTableColumnLeft, InsertTableColumnRight,
16
InsertTableRowAbove, InsertTableRowBelow,
17
};
18
19
pub(super) const TOKEN_PREFIX: &str = "table-";
20
const CELL_MAX_ROWS: usize = 12;
21
const PICKER_SQUARE: f32 = 16.;
22
const PICKER_GAP: f32 = 3.;
23
const TABLE_MARGIN: f32 = 4.;
24
const CELL_PADDING_X: f32 = 2.;
25
const CELL_PADDING_Y: f32 = 3.;
26
27
pub(super) struct TableView {
28
cells: Vec<Vec<Entity<TextareaState>>>,
29
_subscriptions: Vec<Subscription>,
30
}
31
32
impl TableView {
33
fn shape(&self) -> (usize, usize) {
34
(self.cells.len(), self.cells.first().map_or(0, Vec::len))
35
}
36
}
37
38
/// The rows and columns the pointer covers in the size picker.
39
pub(super) struct TablePicker {
40
rows: usize,
41
columns: usize,
42
}
43
44
pub(super) fn token(number: usize) -> InlineToken {
45
InlineToken::new(format!("{TOKEN_PREFIX}{number}"), TABLE_MARK.to_string()).block()
46
}
47
48
pub(super) fn is_table_token(token: &InlineToken) -> bool {
49
token.id().starts_with(TOKEN_PREFIX)
50
}
51
52
fn token_number(id: &str) -> usize {
53
id.strip_prefix(TOKEN_PREFIX)
54
.and_then(|number| number.parse().ok())
55
.unwrap_or_default()
56
}
57
58
fn caret_on_first_line(state: &TextareaState) -> bool {
59
!state.value()[..state.cursor()].contains('\n')
60
}
61
62
fn caret_on_last_line(state: &TextareaState) -> bool {
63
!state.value()[state.cursor()..].contains('\n')
64
}
65
66
impl Composer {
67
fn table_tokens(&self, cx: &App) -> Vec<(Range<usize>, String)> {
68
self.input
69
.read(cx)
70
.tokens()
71
.iter()
72
.filter(|span| is_table_token(span.token()))
73
.map(|span| (span.range(), span.token().id().to_string()))
74
.collect()
75
}
76
77
fn table_line(&self, token_id: &str, cx: &App) -> Option<usize> {
78
let (range, _) = self
79
.table_tokens(cx)
80
.into_iter()
81
.find(|(_, id)| id == token_id)?;
82
let index = self.draft.line_at(range.start);
83
self.draft.table(index).is_some().then_some(index)
84
}
85
86
/// Every table line gets its token and cell inputs; inputs follow the draft's cells.
87
pub(super) fn sync_tables(&mut self, window: &mut Window, cx: &mut Context<Self>) {
88
if self.input.read(cx).value().as_ref() != self.draft.text() {
89
return;
90
}
91
let ranges = self.draft.line_ranges();
92
let tokens = self.table_tokens(cx);
93
for (index, line) in ranges.iter().enumerate() {
94
if self.draft.table(index).is_none() || tokens.iter().any(|(range, _)| range == line) {
95
continue;
96
}
97
self.table_counter += 1;
98
let token = token(self.table_counter);
99
self.input.update(cx, |state, cx| {
100
let selection = state.selected_range();
101
if state
102
.replace_range_with_token(line.clone(), token, window, cx)
103
.is_ok()
104
{
105
state.set_selected_range(selection, cx);
106
}
107
});
108
}
109
let tokens = self.table_tokens(cx);
110
self.tables
111
.retain(|id, _| tokens.iter().any(|(_, token_id)| token_id == id));
112
for (range, id) in tokens {
113
let Some(table) = self.draft.table(self.draft.line_at(range.start)).cloned() else {
114
continue;
115
};
116
self.sync_table_view(&id, &table, window, cx);
117
}
118
}
119
120
fn sync_table_view(
121
&mut self,
122
token_id: &str,
123
table: &Table,
124
window: &mut Window,
125
cx: &mut Context<Self>,
126
) {
127
let shape = (table.row_count(), table.column_count());
128
if self
129
.tables
130
.get(token_id)
131
.is_some_and(|view| view.shape() == shape)
132
{
133
let cells = self.tables[token_id].cells.clone();
134
for (row, inputs) in cells.iter().enumerate() {
135
for (column, input) in inputs.iter().enumerate() {
136
let text = table.cell(Cell::new(row, column)).unwrap_or_default();
137
if input.read(cx).value().as_ref() != text {
138
let text = text.to_owned();
139
input.update(cx, |state, cx| state.set_value(text, window, cx));
140
}
141
}
142
}
143
return;
144
}
145
let mut subscriptions = Vec::new();
146
let cells = table
147
.rows
148
.iter()
149
.enumerate()
150
.map(|(row, texts)| {
151
texts
152
.iter()
153
.enumerate()
154
.map(|(column, text)| {
155
let text = text.clone();
156
let input = cx.new(|cx| {
157
TextareaState::new(window, cx)
158
.auto_grow(1, CELL_MAX_ROWS)
159
.default_value(text)
160
});
161
let id = token_id.to_owned();
162
let cell = Cell::new(row, column);
163
subscriptions.push(cx.subscribe_in(
164
&input,
165
window,
166
move |this, _, event: &InputEvent, window, cx| {
167
this.on_cell_event(&id, cell, event, window, cx)
168
},
169
));
170
input
171
})
172
.collect()
173
})
174
.collect();
175
self.tables.insert(
176
token_id.to_owned(),
177
TableView {
178
cells,
179
_subscriptions: subscriptions,
180
},
181
);
182
}
183
184
fn on_cell_event(
185
&mut self,
186
token_id: &str,
187
cell: Cell,
188
event: &InputEvent,
189
_: &mut Window,
190
cx: &mut Context<Self>,
191
) {
192
match event {
193
InputEvent::Focus => {
194
self.active_cell = Some((token_id.to_owned(), cell));
195
self.table_picker = None;
196
}
197
InputEvent::Change => {
198
let Some(index) = self.table_line(token_id, cx) else {
199
return;
200
};
201
let Some(input) = self.cell_input(token_id, cell) else {
202
return;
203
};
204
let text = input.read(cx).value().to_string();
205
let Some(mut table) = self.draft.table(index).cloned() else {
206
return;
207
};
208
if table.cell(cell) == Some(text.as_str()) {
209
return;
210
}
211
table.set_cell(cell, &text);
212
self.draft.set_table(index, table);
213
self.record(
214
StepKind::CellTyping {
215
table: token_number(token_id),
216
row: cell.row,
217
column: cell.column,
218
},
219
cx,
220
);
221
self.schedule_draft_save(cx);
222
}
223
_ => {}
224
}
225
cx.notify();
226
}
227
228
fn cell_input(&self, token_id: &str, cell: Cell) -> Option<Entity<TextareaState>> {
229
self.tables
230
.get(token_id)?
231
.cells
232
.get(cell.row)?
233
.get(cell.column)
234
.cloned()
235
}
236
237
pub(super) fn focused_cell_input(
238
&self,
239
window: &Window,
240
cx: &App,
241
) -> Option<Entity<TextareaState>> {
242
let (token_id, cell) = self.focused_cell(window, cx)?;
243
self.cell_input(&token_id, cell)
244
}
245
246
/// The cell that has the keyboard, if any.
247
pub(super) fn focused_cell(&self, window: &Window, cx: &App) -> Option<(String, Cell)> {
248
self.tables.iter().find_map(|(id, view)| {
249
view.cells.iter().enumerate().find_map(|(row, inputs)| {
250
inputs.iter().enumerate().find_map(|(column, input)| {
251
input
252
.focus_handle(cx)
253
.is_focused(window)
254
.then(|| (id.clone(), Cell::new(row, column)))
255
})
256
})
257
})
258
}
259
260
pub(super) fn focus_cell(
261
&mut self,
262
token_id: &str,
263
cell: Cell,
264
window: &mut Window,
265
cx: &mut Context<Self>,
266
) {
267
let Some(input) = self.cell_input(token_id, cell) else {
268
return;
269
};
270
input.update(cx, |state, cx| {
271
let end = state.value().len();
272
state.focus(window, cx);
273
state.set_selected_range(end..end, cx);
274
});
275
self.active_cell = Some((token_id.to_owned(), cell));
276
cx.notify();
277
}
278
279
fn token_at_line(&self, index: usize, cx: &App) -> Option<String> {
280
let line = self.draft.line_ranges().get(index)?.clone();
281
self.table_tokens(cx)
282
.into_iter()
283
.find(|(range, _)| *range == line)
284
.map(|(_, id)| id)
285
}
286
287
pub(super) fn focus_table_line(
288
&mut self,
289
index: usize,
290
last: bool,
291
window: &mut Window,
292
cx: &mut Context<Self>,
293
) {
294
let Some(token_id) = self.token_at_line(index, cx) else {
295
return;
296
};
297
let Some(table) = self.draft.table(index) else {
298
return;
299
};
300
let cell = if last {
301
table.last_cell()
302
} else {
303
Cell::new(0, 0)
304
};
305
self.focus_cell(&token_id, cell, window, cx);
306
}
307
308
pub(super) fn insert_table(
309
&mut self,
310
rows: usize,
311
columns: usize,
312
window: &mut Window,
313
cx: &mut Context<Self>,
314
) {
315
self.table_picker = None;
316
let cursor = match self.focused_cell(window, cx) {
317
Some((token_id, _)) => self
318
.table_line(&token_id, cx)
319
.map_or(self.selection(cx).end, |index| {
320
self.draft.line_ranges()[index].end
321
}),
322
None => self.selection(cx).end,
323
};
324
let index = self.draft.insert_table(cursor, Table::new(rows, columns));
325
let after = self.draft.line_ranges()[index].end;
326
self.commit(Some(after), window, cx);
327
self.focus_table_line(index, false, window, cx);
328
}
329
330
fn leave_table(
331
&mut self,
332
token_id: &str,
333
below: bool,
334
window: &mut Window,
335
cx: &mut Context<Self>,
336
) {
337
let Some(index) = self.table_line(token_id, cx) else {
338
return;
339
};
340
let cursor = self.draft.line_beside_table(index, below);
341
self.active_cell = None;
342
self.focus(window, cx);
343
self.commit(Some(cursor), window, cx);
344
}
345
346
/// Tab, Shift+Tab, Up and Down while a cell has the keyboard. `false` leaves the key to
347
/// the cell.
348
pub(super) fn table_key(
349
&mut self,
350
key: TableKey,
351
window: &mut Window,
352
cx: &mut Context<Self>,
353
) -> bool {
354
let Some((token_id, cell)) = self.focused_cell(window, cx) else {
355
return false;
356
};
357
let Some(index) = self.table_line(&token_id, cx) else {
358
return false;
359
};
360
let Some(mut table) = self.draft.table(index).cloned() else {
361
return false;
362
};
363
let Some(input) = self.cell_input(&token_id, cell) else {
364
return false;
365
};
366
let target = match key {
367
TableKey::Next => {
368
let (next, added_row) = table.next_cell(cell);
369
if added_row {
370
self.draft.set_table(index, table);
371
self.record(StepKind::Other, cx);
372
self.sync_tables(window, cx);
373
self.schedule_draft_save(cx);
374
}
375
next
376
}
377
TableKey::Previous => table.previous_cell(cell),
378
TableKey::Down if !caret_on_last_line(input.read(cx)) => return false,
379
TableKey::Up if !caret_on_first_line(input.read(cx)) => return false,
380
TableKey::Down if cell.row + 1 == table.row_count() => {
381
self.leave_table(&token_id, true, window, cx);
382
return true;
383
}
384
TableKey::Up if cell.row == 0 => {
385
self.leave_table(&token_id, false, window, cx);
386
return true;
387
}
388
TableKey::Down => Cell::new(cell.row + 1, cell.column),
389
TableKey::Up => Cell::new(cell.row - 1, cell.column),
390
};
391
self.focus_cell(&token_id, target, window, cx);
392
true
393
}
394
395
pub(super) fn edit_table(
396
&mut self,
397
edit: TableEdit,
398
window: &mut Window,
399
cx: &mut Context<Self>,
400
) {
401
let Some((token_id, cell)) = self
402
.focused_cell(window, cx)
403
.or_else(|| self.active_cell.clone())
404
else {
405
return;
406
};
407
let Some(index) = self.table_line(&token_id, cx) else {
408
return;
409
};
410
let Some(mut table) = self.draft.table(index).cloned() else {
411
return;
412
};
413
match table.apply(edit, cell) {
414
Some(target) => {
415
self.draft.set_table(index, table);
416
self.record(StepKind::Other, cx);
417
self.sync_tables(window, cx);
418
self.schedule_draft_save(cx);
419
self.focus_cell(&token_id, target, window, cx);
420
}
421
None => {
422
let cursor = self.draft.remove_table(index);
423
self.active_cell = None;
424
self.focus(window, cx);
425
self.commit(Some(cursor), window, cx);
426
}
427
}
428
cx.notify();
429
}
430
431
/// The caret never rests on a table's line: coming from above it enters the first
432
/// cell, from below the first cell of the last row. Only a move without an edit
433
/// counts, so a paste that passes the table on its way does not enter it.
434
pub(super) fn redirect_caret_from_table(
435
&mut self,
436
window: &mut Window,
437
cx: &mut Context<Self>,
438
) {
439
let state = self.input.read(cx);
440
let selection = state.selected_range();
441
let focused = state.focus_handle(cx).is_focused(window);
442
let value = state.value();
443
if value.as_ref() != self.caret_text {
444
self.caret_text = value.to_string();
445
self.caret_before_table = selection.start;
446
return;
447
}
448
if !focused || !selection.is_empty() || value.as_ref() != self.draft.text() {
449
return;
450
}
451
let Some(index) = self.draft.table_at(selection.start) else {
452
self.caret_before_table = selection.start;
453
return;
454
};
455
let line = self.draft.line_ranges()[index].clone();
456
let from_below = self.caret_before_table > line.end;
457
let resting = if from_below {
458
self.draft
459
.line_ranges()
460
.get(index + 1)
461
.map_or(line.end, |next| next.start)
462
} else {
463
line.start.saturating_sub(1)
464
};
465
self.input.update(cx, |state, cx| {
466
state.set_selected_range(resting..resting, cx)
467
});
468
self.caret_before_table = resting;
469
let token = self.token_at_line(index, cx);
470
let Some(token_id) = token else {
471
return;
472
};
473
let row = if from_below {
474
self.draft
475
.table(index)
476
.map_or(0, |table| table.row_count() - 1)
477
} else {
478
0
479
};
480
self.focus_cell(&token_id, Cell::new(row, 0), window, cx);
481
}
482
483
pub(super) fn open_table_picker(&mut self, cx: &mut Context<Self>) {
484
self.table_picker = Some(TablePicker {
485
rows: 1,
486
columns: 1,
487
});
488
cx.notify();
489
}
490
491
pub(super) fn render_table_picker(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
492
let picker = self.table_picker.as_ref()?;
493
let grid = v_flex()
494
.gap(px(PICKER_GAP))
495
.children((1..=PICKER_ROWS).map(|row| {
496
h_flex()
497
.gap(px(PICKER_GAP))
498
.children((1..=PICKER_COLUMNS).map(|column| {
499
let covered = row <= picker.rows && column <= picker.columns;
500
div()
501
.id(ElementId::Name(format!("table-size-{row}-{column}").into()))
502
.size(px(PICKER_SQUARE))
503
.rounded(px(2.))
504
.bg(if covered {
505
theme::accent().opacity(0.6)
506
} else {
507
theme::border_strong()
508
})
509
.cursor_pointer()
510
.on_hover(cx.listener(move |this, hovered: &bool, _, cx| {
511
if *hovered && let Some(picker) = this.table_picker.as_mut() {
512
picker.rows = row;
513
picker.columns = column;
514
cx.notify();
515
}
516
}))
517
.on_click(cx.listener(move |this, _, window, cx| {
518
this.insert_table(row, column, window, cx)
519
}))
520
}))
521
}));
522
Some(
523
v_flex()
524
.id("table-picker")
525
.absolute()
526
.bottom(relative(1.))
527
.left_0()
528
.mb(px(6.))
529
.p(px(10.))
530
.gap(px(8.))
531
.rounded(px(10.))
532
.flyout_surface()
533
.occlude()
534
.on_mouse_down_out(cx.listener(|this, _, _, cx| {
535
this.table_picker = None;
536
cx.notify();
537
}))
538
.child(
539
div()
540
.text_size(px(12.))
541
.text_color(theme::text_muted())
542
.child(format!("Insert {}x{} table", picker.columns, picker.rows)),
543
)
544
.child(grid)
545
.into_any_element(),
546
)
547
}
548
549
/// The table token: a grid of cell inputs over the full width, solid lines like Teams.
550
pub(super) fn render_table_token(&self, token_id: &str, width: Pixels) -> Option<AnyElement> {
551
let view = self.tables.get(token_id)?;
552
let rows = view.cells.iter().map(|inputs| {
553
h_flex()
554
.w_full()
555
.items_stretch()
556
.children(inputs.iter().map(|input| {
557
div()
558
.flex_1()
559
.min_w_0()
560
.px(px(CELL_PADDING_X))
561
.py(px(CELL_PADDING_Y))
562
.border_r_1()
563
.border_b_1()
564
.border_color(theme::border_strong())
565
.child(
566
Textarea::new(input)
567
.appearance(false)
568
.bordered(false)
569
.small()
570
.context_menu(|menu, _, _| table_menu(menu)),
571
)
572
}))
573
});
574
Some(
575
v_flex()
576
.id(ElementId::Name(format!("composer-{token_id}").into()))
577
.w(width)
578
.my(px(TABLE_MARGIN))
579
.border_t_1()
580
.border_l_1()
581
.border_color(theme::border_strong())
582
.on_any_mouse_down(|_, window, cx| {
583
window.prevent_default();
584
cx.stop_propagation();
585
})
586
.children(rows)
587
.into_any_element(),
588
)
589
}
590
}
591
592
fn table_menu(menu: NativeMenu) -> NativeMenu {
593
let menu = TableEdit::INSERTS
594
.into_iter()
595
.fold(menu, |menu, edit| {
596
menu.menu(edit.label(), edit_action(edit))
597
})
598
.separator();
599
TableEdit::DELETES
600
.into_iter()
601
.fold(menu, |menu, edit| {
602
menu.menu(edit.label(), edit_action(edit))
603
})
604
.separator()
605
.menu("Cut", Box::new(Cut))
606
.menu("Copy", Box::new(Copy))
607
.menu("Paste", Box::new(Paste))
608
}
609
610
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
611
pub(super) enum TableKey {
612
Next,
613
Previous,
614
Up,
615
Down,
616
}
617
618
fn edit_action(edit: TableEdit) -> Box<dyn Action> {
619
match edit {
620
TableEdit::InsertRowAbove => Box::new(InsertTableRowAbove),
621
TableEdit::InsertRowBelow => Box::new(InsertTableRowBelow),
622
TableEdit::InsertColumnLeft => Box::new(InsertTableColumnLeft),
623
TableEdit::InsertColumnRight => Box::new(InsertTableColumnRight),
624
TableEdit::DeleteRow => Box::new(DeleteTableRow),
625
TableEdit::DeleteColumn => Box::new(DeleteTableColumn),
626
TableEdit::DeleteTable => Box::new(DeleteTable),
627
}
628
}
629
630
pub(super) type TableViews = HashMap<String, TableView>;
@@ -0,0 +1,630 @@1
use std::collections::HashMap;2
use std::ops::Range;3
4
use gpui_kit::component::input::{5
Copy, Cut, InlineToken, InputEvent, Paste, Textarea, TextareaState,6
};7
use gpui_kit::component::native_menu::NativeMenu;8
use gpui_kit::component::{Sizable as _, h_flex, v_flex};9
use gpui_kit::*;10
use teams_core::{Cell, PICKER_COLUMNS, PICKER_ROWS, TABLE_MARK, Table, TableEdit};11
12
use super::{Composer, StepKind};13
use crate::theme::{self, ElevatedSurface as _};14
use crate::views::actions::{15
DeleteTable, DeleteTableColumn, DeleteTableRow, InsertTableColumnLeft, InsertTableColumnRight,16
InsertTableRowAbove, InsertTableRowBelow,17
};18
19
pub(super) const TOKEN_PREFIX: &str = "table-";20
const CELL_MAX_ROWS: usize = 12;21
const PICKER_SQUARE: f32 = 16.;22
const PICKER_GAP: f32 = 3.;23
const TABLE_MARGIN: f32 = 4.;24
const CELL_PADDING_X: f32 = 2.;25
const CELL_PADDING_Y: f32 = 3.;26
27
pub(super) struct TableView {28
cells: Vec<Vec<Entity<TextareaState>>>,29
_subscriptions: Vec<Subscription>,30
}31
32
impl TableView {33
fn shape(&self) -> (usize, usize) {34
(self.cells.len(), self.cells.first().map_or(0, Vec::len))35
}36
}37
38
/// The rows and columns the pointer covers in the size picker.39
pub(super) struct TablePicker {40
rows: usize,41
columns: usize,42
}43
44
pub(super) fn token(number: usize) -> InlineToken {45
InlineToken::new(format!("{TOKEN_PREFIX}{number}"), TABLE_MARK.to_string()).block()46
}47
48
pub(super) fn is_table_token(token: &InlineToken) -> bool {49
token.id().starts_with(TOKEN_PREFIX)50
}51
52
fn token_number(id: &str) -> usize {53
id.strip_prefix(TOKEN_PREFIX)54
.and_then(|number| number.parse().ok())55
.unwrap_or_default()56
}57
58
fn caret_on_first_line(state: &TextareaState) -> bool {59
!state.value()[..state.cursor()].contains('\n')60
}61
62
fn caret_on_last_line(state: &TextareaState) -> bool {63
!state.value()[state.cursor()..].contains('\n')64
}65
66
impl Composer {67
fn table_tokens(&self, cx: &App) -> Vec<(Range<usize>, String)> {68
self.input69
.read(cx)70
.tokens()71
.iter()72
.filter(|span| is_table_token(span.token()))73
.map(|span| (span.range(), span.token().id().to_string()))74
.collect()75
}76
77
fn table_line(&self, token_id: &str, cx: &App) -> Option<usize> {78
let (range, _) = self79
.table_tokens(cx)80
.into_iter()81
.find(|(_, id)| id == token_id)?;82
let index = self.draft.line_at(range.start);83
self.draft.table(index).is_some().then_some(index)84
}85
86
/// Every table line gets its token and cell inputs; inputs follow the draft's cells.87
pub(super) fn sync_tables(&mut self, window: &mut Window, cx: &mut Context<Self>) {88
if self.input.read(cx).value().as_ref() != self.draft.text() {89
return;90
}91
let ranges = self.draft.line_ranges();92
let tokens = self.table_tokens(cx);93
for (index, line) in ranges.iter().enumerate() {94
if self.draft.table(index).is_none() || tokens.iter().any(|(range, _)| range == line) {95
continue;96
}97
self.table_counter += 1;98
let token = token(self.table_counter);99
self.input.update(cx, |state, cx| {100
let selection = state.selected_range();101
if state102
.replace_range_with_token(line.clone(), token, window, cx)103
.is_ok()104
{105
state.set_selected_range(selection, cx);106
}107
});108
}109
let tokens = self.table_tokens(cx);110
self.tables111
.retain(|id, _| tokens.iter().any(|(_, token_id)| token_id == id));112
for (range, id) in tokens {113
let Some(table) = self.draft.table(self.draft.line_at(range.start)).cloned() else {114
continue;115
};116
self.sync_table_view(&id, &table, window, cx);117
}118
}119
120
fn sync_table_view(121
&mut self,122
token_id: &str,123
table: &Table,124
window: &mut Window,125
cx: &mut Context<Self>,126
) {127
let shape = (table.row_count(), table.column_count());128
if self129
.tables130
.get(token_id)131
.is_some_and(|view| view.shape() == shape)132
{133
let cells = self.tables[token_id].cells.clone();134
for (row, inputs) in cells.iter().enumerate() {135
for (column, input) in inputs.iter().enumerate() {136
let text = table.cell(Cell::new(row, column)).unwrap_or_default();137
if input.read(cx).value().as_ref() != text {138
let text = text.to_owned();139
input.update(cx, |state, cx| state.set_value(text, window, cx));140
}141
}142
}143
return;144
}145
let mut subscriptions = Vec::new();146
let cells = table147
.rows148
.iter()149
.enumerate()150
.map(|(row, texts)| {151
texts152
.iter()153
.enumerate()154
.map(|(column, text)| {155
let text = text.clone();156
let input = cx.new(|cx| {157
TextareaState::new(window, cx)158
.auto_grow(1, CELL_MAX_ROWS)159
.default_value(text)160
});161
let id = token_id.to_owned();162
let cell = Cell::new(row, column);163
subscriptions.push(cx.subscribe_in(164
&input,165
window,166
move |this, _, event: &InputEvent, window, cx| {167
this.on_cell_event(&id, cell, event, window, cx)168
},169
));170
input171
})172
.collect()173
})174
.collect();175
self.tables.insert(176
token_id.to_owned(),177
TableView {178
cells,179
_subscriptions: subscriptions,180
},181
);182
}183
184
fn on_cell_event(185
&mut self,186
token_id: &str,187
cell: Cell,188
event: &InputEvent,189
_: &mut Window,190
cx: &mut Context<Self>,191
) {192
match event {193
InputEvent::Focus => {194
self.active_cell = Some((token_id.to_owned(), cell));195
self.table_picker = None;196
}197
InputEvent::Change => {198
let Some(index) = self.table_line(token_id, cx) else {199
return;200
};201
let Some(input) = self.cell_input(token_id, cell) else {202
return;203
};204
let text = input.read(cx).value().to_string();205
let Some(mut table) = self.draft.table(index).cloned() else {206
return;207
};208
if table.cell(cell) == Some(text.as_str()) {209
return;210
}211
table.set_cell(cell, &text);212
self.draft.set_table(index, table);213
self.record(214
StepKind::CellTyping {215
table: token_number(token_id),216
row: cell.row,217
column: cell.column,218
},219
cx,220
);221
self.schedule_draft_save(cx);222
}223
_ => {}224
}225
cx.notify();226
}227
228
fn cell_input(&self, token_id: &str, cell: Cell) -> Option<Entity<TextareaState>> {229
self.tables230
.get(token_id)?231
.cells232
.get(cell.row)?233
.get(cell.column)234
.cloned()235
}236
237
pub(super) fn focused_cell_input(238
&self,239
window: &Window,240
cx: &App,241
) -> Option<Entity<TextareaState>> {242
let (token_id, cell) = self.focused_cell(window, cx)?;243
self.cell_input(&token_id, cell)244
}245
246
/// The cell that has the keyboard, if any.247
pub(super) fn focused_cell(&self, window: &Window, cx: &App) -> Option<(String, Cell)> {248
self.tables.iter().find_map(|(id, view)| {249
view.cells.iter().enumerate().find_map(|(row, inputs)| {250
inputs.iter().enumerate().find_map(|(column, input)| {251
input252
.focus_handle(cx)253
.is_focused(window)254
.then(|| (id.clone(), Cell::new(row, column)))255
})256
})257
})258
}259
260
pub(super) fn focus_cell(261
&mut self,262
token_id: &str,263
cell: Cell,264
window: &mut Window,265
cx: &mut Context<Self>,266
) {267
let Some(input) = self.cell_input(token_id, cell) else {268
return;269
};270
input.update(cx, |state, cx| {271
let end = state.value().len();272
state.focus(window, cx);273
state.set_selected_range(end..end, cx);274
});275
self.active_cell = Some((token_id.to_owned(), cell));276
cx.notify();277
}278
279
fn token_at_line(&self, index: usize, cx: &App) -> Option<String> {280
let line = self.draft.line_ranges().get(index)?.clone();281
self.table_tokens(cx)282
.into_iter()283
.find(|(range, _)| *range == line)284
.map(|(_, id)| id)285
}286
287
pub(super) fn focus_table_line(288
&mut self,289
index: usize,290
last: bool,291
window: &mut Window,292
cx: &mut Context<Self>,293
) {294
let Some(token_id) = self.token_at_line(index, cx) else {295
return;296
};297
let Some(table) = self.draft.table(index) else {298
return;299
};300
let cell = if last {301
table.last_cell()302
} else {303
Cell::new(0, 0)304
};305
self.focus_cell(&token_id, cell, window, cx);306
}307
308
pub(super) fn insert_table(309
&mut self,310
rows: usize,311
columns: usize,312
window: &mut Window,313
cx: &mut Context<Self>,314
) {315
self.table_picker = None;316
let cursor = match self.focused_cell(window, cx) {317
Some((token_id, _)) => self318
.table_line(&token_id, cx)319
.map_or(self.selection(cx).end, |index| {320
self.draft.line_ranges()[index].end321
}),322
None => self.selection(cx).end,323
};324
let index = self.draft.insert_table(cursor, Table::new(rows, columns));325
let after = self.draft.line_ranges()[index].end;326
self.commit(Some(after), window, cx);327
self.focus_table_line(index, false, window, cx);328
}329
330
fn leave_table(331
&mut self,332
token_id: &str,333
below: bool,334
window: &mut Window,335
cx: &mut Context<Self>,336
) {337
let Some(index) = self.table_line(token_id, cx) else {338
return;339
};340
let cursor = self.draft.line_beside_table(index, below);341
self.active_cell = None;342
self.focus(window, cx);343
self.commit(Some(cursor), window, cx);344
}345
346
/// Tab, Shift+Tab, Up and Down while a cell has the keyboard. `false` leaves the key to347
/// the cell.348
pub(super) fn table_key(349
&mut self,350
key: TableKey,351
window: &mut Window,352
cx: &mut Context<Self>,353
) -> bool {354
let Some((token_id, cell)) = self.focused_cell(window, cx) else {355
return false;356
};357
let Some(index) = self.table_line(&token_id, cx) else {358
return false;359
};360
let Some(mut table) = self.draft.table(index).cloned() else {361
return false;362
};363
let Some(input) = self.cell_input(&token_id, cell) else {364
return false;365
};366
let target = match key {367
TableKey::Next => {368
let (next, added_row) = table.next_cell(cell);369
if added_row {370
self.draft.set_table(index, table);371
self.record(StepKind::Other, cx);372
self.sync_tables(window, cx);373
self.schedule_draft_save(cx);374
}375
next376
}377
TableKey::Previous => table.previous_cell(cell),378
TableKey::Down if !caret_on_last_line(input.read(cx)) => return false,379
TableKey::Up if !caret_on_first_line(input.read(cx)) => return false,380
TableKey::Down if cell.row + 1 == table.row_count() => {381
self.leave_table(&token_id, true, window, cx);382
return true;383
}384
TableKey::Up if cell.row == 0 => {385
self.leave_table(&token_id, false, window, cx);386
return true;387
}388
TableKey::Down => Cell::new(cell.row + 1, cell.column),389
TableKey::Up => Cell::new(cell.row - 1, cell.column),390
};391
self.focus_cell(&token_id, target, window, cx);392
true393
}394
395
pub(super) fn edit_table(396
&mut self,397
edit: TableEdit,398
window: &mut Window,399
cx: &mut Context<Self>,400
) {401
let Some((token_id, cell)) = self402
.focused_cell(window, cx)403
.or_else(|| self.active_cell.clone())404
else {405
return;406
};407
let Some(index) = self.table_line(&token_id, cx) else {408
return;409
};410
let Some(mut table) = self.draft.table(index).cloned() else {411
return;412
};413
match table.apply(edit, cell) {414
Some(target) => {415
self.draft.set_table(index, table);416
self.record(StepKind::Other, cx);417
self.sync_tables(window, cx);418
self.schedule_draft_save(cx);419
self.focus_cell(&token_id, target, window, cx);420
}421
None => {422
let cursor = self.draft.remove_table(index);423
self.active_cell = None;424
self.focus(window, cx);425
self.commit(Some(cursor), window, cx);426
}427
}428
cx.notify();429
}430
431
/// The caret never rests on a table's line: coming from above it enters the first432
/// cell, from below the first cell of the last row. Only a move without an edit433
/// counts, so a paste that passes the table on its way does not enter it.434
pub(super) fn redirect_caret_from_table(435
&mut self,436
window: &mut Window,437
cx: &mut Context<Self>,438
) {439
let state = self.input.read(cx);440
let selection = state.selected_range();441
let focused = state.focus_handle(cx).is_focused(window);442
let value = state.value();443
if value.as_ref() != self.caret_text {444
self.caret_text = value.to_string();445
self.caret_before_table = selection.start;446
return;447
}448
if !focused || !selection.is_empty() || value.as_ref() != self.draft.text() {449
return;450
}451
let Some(index) = self.draft.table_at(selection.start) else {452
self.caret_before_table = selection.start;453
return;454
};455
let line = self.draft.line_ranges()[index].clone();456
let from_below = self.caret_before_table > line.end;457
let resting = if from_below {458
self.draft459
.line_ranges()460
.get(index + 1)461
.map_or(line.end, |next| next.start)462
} else {463
line.start.saturating_sub(1)464
};465
self.input.update(cx, |state, cx| {466
state.set_selected_range(resting..resting, cx)467
});468
self.caret_before_table = resting;469
let token = self.token_at_line(index, cx);470
let Some(token_id) = token else {471
return;472
};473
let row = if from_below {474
self.draft475
.table(index)476
.map_or(0, |table| table.row_count() - 1)477
} else {478
0479
};480
self.focus_cell(&token_id, Cell::new(row, 0), window, cx);481
}482
483
pub(super) fn open_table_picker(&mut self, cx: &mut Context<Self>) {484
self.table_picker = Some(TablePicker {485
rows: 1,486
columns: 1,487
});488
cx.notify();489
}490
491
pub(super) fn render_table_picker(&self, cx: &mut Context<Self>) -> Option<AnyElement> {492
let picker = self.table_picker.as_ref()?;493
let grid = v_flex()494
.gap(px(PICKER_GAP))495
.children((1..=PICKER_ROWS).map(|row| {496
h_flex()497
.gap(px(PICKER_GAP))498
.children((1..=PICKER_COLUMNS).map(|column| {499
let covered = row <= picker.rows && column <= picker.columns;500
div()501
.id(ElementId::Name(format!("table-size-{row}-{column}").into()))502
.size(px(PICKER_SQUARE))503
.rounded(px(2.))504
.bg(if covered {505
theme::accent().opacity(0.6)506
} else {507
theme::border_strong()508
})509
.cursor_pointer()510
.on_hover(cx.listener(move |this, hovered: &bool, _, cx| {511
if *hovered && let Some(picker) = this.table_picker.as_mut() {512
picker.rows = row;513
picker.columns = column;514
cx.notify();515
}516
}))517
.on_click(cx.listener(move |this, _, window, cx| {518
this.insert_table(row, column, window, cx)519
}))520
}))521
}));522
Some(523
v_flex()524
.id("table-picker")525
.absolute()526
.bottom(relative(1.))527
.left_0()528
.mb(px(6.))529
.p(px(10.))530
.gap(px(8.))531
.rounded(px(10.))532
.flyout_surface()533
.occlude()534
.on_mouse_down_out(cx.listener(|this, _, _, cx| {535
this.table_picker = None;536
cx.notify();537
}))538
.child(539
div()540
.text_size(px(12.))541
.text_color(theme::text_muted())542
.child(format!("Insert {}x{} table", picker.columns, picker.rows)),543
)544
.child(grid)545
.into_any_element(),546
)547
}548
549
/// The table token: a grid of cell inputs over the full width, solid lines like Teams.550
pub(super) fn render_table_token(&self, token_id: &str, width: Pixels) -> Option<AnyElement> {551
let view = self.tables.get(token_id)?;552
let rows = view.cells.iter().map(|inputs| {553
h_flex()554
.w_full()555
.items_stretch()556
.children(inputs.iter().map(|input| {557
div()558
.flex_1()559
.min_w_0()560
.px(px(CELL_PADDING_X))561
.py(px(CELL_PADDING_Y))562
.border_r_1()563
.border_b_1()564
.border_color(theme::border_strong())565
.child(566
Textarea::new(input)567
.appearance(false)568
.bordered(false)569
.small()570
.context_menu(|menu, _, _| table_menu(menu)),571
)572
}))573
});574
Some(575
v_flex()576
.id(ElementId::Name(format!("composer-{token_id}").into()))577
.w(width)578
.my(px(TABLE_MARGIN))579
.border_t_1()580
.border_l_1()581
.border_color(theme::border_strong())582
.on_any_mouse_down(|_, window, cx| {583
window.prevent_default();584
cx.stop_propagation();585
})586
.children(rows)587
.into_any_element(),588
)589
}590
}591
592
fn table_menu(menu: NativeMenu) -> NativeMenu {593
let menu = TableEdit::INSERTS594
.into_iter()595
.fold(menu, |menu, edit| {596
menu.menu(edit.label(), edit_action(edit))597
})598
.separator();599
TableEdit::DELETES600
.into_iter()601
.fold(menu, |menu, edit| {602
menu.menu(edit.label(), edit_action(edit))603
})604
.separator()605
.menu("Cut", Box::new(Cut))606
.menu("Copy", Box::new(Copy))607
.menu("Paste", Box::new(Paste))608
}609
610
#[derive(Debug, Clone, Copy, PartialEq, Eq)]611
pub(super) enum TableKey {612
Next,613
Previous,614
Up,615
Down,616
}617
618
fn edit_action(edit: TableEdit) -> Box<dyn Action> {619
match edit {620
TableEdit::InsertRowAbove => Box::new(InsertTableRowAbove),621
TableEdit::InsertRowBelow => Box::new(InsertTableRowBelow),622
TableEdit::InsertColumnLeft => Box::new(InsertTableColumnLeft),623
TableEdit::InsertColumnRight => Box::new(InsertTableColumnRight),624
TableEdit::DeleteRow => Box::new(DeleteTableRow),625
TableEdit::DeleteColumn => Box::new(DeleteTableColumn),626
TableEdit::DeleteTable => Box::new(DeleteTable),627
}628
}629
630
pub(super) type TableViews = HashMap<String, TableView>;@@ -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.))@@ -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) -> Statefu197
fn entry_row(entry: &ReactionEntry, directory: &Directory) -> Div {197
fn 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()@@ -143,6 +143,12 @@ pub struct AppShell {
143
143
}
144
144
145
145
impl AppShell {
146
#[cfg(test)]
147
pub(crate) fn set_update_status(&mut self, update: UpdateStatus, cx: &mut Context<Self>) {
148
self.update = update;
149
cx.notify();
150
}
151
146
152
fn sync_call_chat(
147
153
&mut self,
148
154
thread: Option<String>,
@@ -143,6 +143,12 @@ pub struct AppShell {143
}143
}144
144
145
impl AppShell {145
impl AppShell {146
#[cfg(test)]147
pub(crate) fn set_update_status(&mut self, update: UpdateStatus, cx: &mut Context<Self>) {148
self.update = update;149
cx.notify();150
}151
146
fn sync_call_chat(152
fn sync_call_chat(147
&mut self,153
&mut self,148
thread: Option<String>,154
thread: Option<String>,@@ -1,9 +1,9 @@
1
1
use gpui_kit::*;
2
2
3
3
use super::actions::{
4
COMPOSER_KEY_CONTEXT as COMPOSER_CONTEXT, EditLink, NewChat, OpenSwitcher, ReplyToHovered,
5
ScheduleSend, ToggleBold, ToggleCode, ToggleItalic, ToggleStrike, ToggleSubscript,
6
ToggleSuperscript, ToggleUnderline, ToggleCallMute,
4
COMPOSER_KEY_CONTEXT as COMPOSER_CONTEXT, EditLink, NewChat, OpenSwitcher, PastePlainText,
5
ReplyToHovered, ScheduleSend, ToggleBold, ToggleCallMute, ToggleCode, ToggleItalic,
6
ToggleStrike, ToggleSubscript, ToggleSuperscript, ToggleUnderline,
7
7
};
8
8
9
9
const TEXT_FIELD_CONTEXT: &str = "Input";
@@ -122,6 +122,7 @@ pub const SHORTCUTS: &[Shortcut] = &[
122
122
shortcut!(Composer, Composer, "Subscript", "ctrl-=", None, ToggleSubscript),
123
123
shortcut!(Composer, Composer, "Code", "ctrl-shift-c", None, ToggleCode),
124
124
shortcut!(Composer, Composer, "Insert link", "ctrl-k", Some("cmd-k"), EditLink),
125
shortcut!(Composer, Composer, "Paste as plain text", "ctrl-shift-v", Some("cmd-shift-v"), PastePlainText),
125
126
shortcut!(Composer, Composer, "Schedule send", "ctrl-shift-enter", None, ScheduleSend),
126
127
shortcut!(Calls, GlobalOverTextFields, "Accept incoming call", "ctrl-shift-a", Some("cmd-shift-a"), AcceptCall),
127
128
shortcut!(Calls, GlobalOverTextFields, "Decline incoming call", "ctrl-shift-d", Some("cmd-shift-d"), DeclineCall),
@@ -162,7 +163,12 @@ impl Shortcut {
162
163
Scope::Composer => &[Some(COMPOSER_CONTEXT)],
163
164
};
164
165
let mut keys = vec![self.keys];
165
keys.extend(ALTERNATE_KEYS.iter().filter(|(primary, _)| *primary == self.keys).map(|(_, alternate)| *alternate));
166
keys.extend(
167
ALTERNATE_KEYS
168
.iter()
169
.filter(|(primary, _)| *primary == self.keys)
170
.map(|(_, alternate)| *alternate),
171
);
166
172
keys.extend(self.mac_keys.filter(|_| cfg!(target_os = "macos")));
167
173
keys.iter()
168
174
.flat_map(|keys| contexts.iter().map(|context| (self.bind)(keys, *context)))
@@ -1,9 +1,9 @@1
use gpui_kit::*;1
use gpui_kit::*;2
2
3
use super::actions::{3
use super::actions::{4
COMPOSER_KEY_CONTEXT as COMPOSER_CONTEXT, EditLink, NewChat, OpenSwitcher, ReplyToHovered,4
COMPOSER_KEY_CONTEXT as COMPOSER_CONTEXT, EditLink, NewChat, OpenSwitcher, PastePlainText,5
ScheduleSend, ToggleBold, ToggleCode, ToggleItalic, ToggleStrike, ToggleSubscript,5
ReplyToHovered, ScheduleSend, ToggleBold, ToggleCallMute, ToggleCode, ToggleItalic,6
ToggleSuperscript, ToggleUnderline, ToggleCallMute,6
ToggleStrike, ToggleSubscript, ToggleSuperscript, ToggleUnderline,7
};7
};8
8
9
const TEXT_FIELD_CONTEXT: &str = "Input";9
const TEXT_FIELD_CONTEXT: &str = "Input";@@ -122,6 +122,7 @@ pub const SHORTCUTS: &[Shortcut] = &[122
shortcut!(Composer, Composer, "Subscript", "ctrl-=", None, ToggleSubscript),122
shortcut!(Composer, Composer, "Subscript", "ctrl-=", None, ToggleSubscript),123
shortcut!(Composer, Composer, "Code", "ctrl-shift-c", None, ToggleCode),123
shortcut!(Composer, Composer, "Code", "ctrl-shift-c", None, ToggleCode),124
shortcut!(Composer, Composer, "Insert link", "ctrl-k", Some("cmd-k"), EditLink),124
shortcut!(Composer, Composer, "Insert link", "ctrl-k", Some("cmd-k"), EditLink),125
shortcut!(Composer, Composer, "Paste as plain text", "ctrl-shift-v", Some("cmd-shift-v"), PastePlainText),125
shortcut!(Composer, Composer, "Schedule send", "ctrl-shift-enter", None, ScheduleSend),126
shortcut!(Composer, Composer, "Schedule send", "ctrl-shift-enter", None, ScheduleSend),126
shortcut!(Calls, GlobalOverTextFields, "Accept incoming call", "ctrl-shift-a", Some("cmd-shift-a"), AcceptCall),127
shortcut!(Calls, GlobalOverTextFields, "Accept incoming call", "ctrl-shift-a", Some("cmd-shift-a"), AcceptCall),127
shortcut!(Calls, GlobalOverTextFields, "Decline incoming call", "ctrl-shift-d", Some("cmd-shift-d"), DeclineCall),128
shortcut!(Calls, GlobalOverTextFields, "Decline incoming call", "ctrl-shift-d", Some("cmd-shift-d"), DeclineCall),@@ -162,7 +163,12 @@ impl Shortcut {162
Scope::Composer => &[Some(COMPOSER_CONTEXT)],163
Scope::Composer => &[Some(COMPOSER_CONTEXT)],163
};164
};164
let mut keys = vec![self.keys];165
let mut keys = vec![self.keys];165
keys.extend(ALTERNATE_KEYS.iter().filter(|(primary, _)| *primary == self.keys).map(|(_, alternate)| *alternate));166
keys.extend(167
ALTERNATE_KEYS168
.iter()169
.filter(|(primary, _)| *primary == self.keys)170
.map(|(_, alternate)| *alternate),171
);166
keys.extend(self.mac_keys.filter(|_| cfg!(target_os = "macos")));172
keys.extend(self.mac_keys.filter(|_| cfg!(target_os = "macos")));167
keys.iter()173
keys.iter()168
.flat_map(|keys| contexts.iter().map(|context| (self.bind)(keys, *context)))174
.flat_map(|keys| contexts.iter().map(|context| (self.bind)(keys, *context)))@@ -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.))@@ -13,6 +13,11 @@ use crate::updater::UpdateStatus;
13
13
14
14
pub const TITLE_BAR_HEIGHT: f32 = 40.;
15
15
const SEARCH_WIDTH: f32 = 380.;
16
const SEARCH_MIN_WIDTH: f32 = 240.;
17
const SEARCH_MIN_VISIBLE_WIDTH: f32 = 36.;
18
const SEARCH_HEIGHT: f32 = 28.;
19
const SEARCH_GAP: f32 = 8.;
20
const SHORTCUT_MIN_WIDTH: f32 = 200.;
16
21
const SEARCH_HINT: &str = "Search chats, people and channels";
17
22
const SHORTCUT_HINT: &str = "Ctrl K";
18
23
const APP_ICON_SIZE: f32 = 18.;
@@ -94,6 +99,41 @@ pub fn update_button(
94
99
)
95
100
}
96
101
102
#[derive(Clone, Copy, Debug, PartialEq)]
103
struct SearchSpan {
104
left: f32,
105
width: f32,
106
}
107
108
fn search_span(window_width: f32, leading_end: f32, trailing_start: f32) -> Option<SearchSpan> {
109
let start = leading_end + SEARCH_GAP;
110
let end = trailing_start - SEARCH_GAP;
111
let room = end - start;
112
if room < SEARCH_MIN_VISIBLE_WIDTH {
113
return None;
114
}
115
let center = window_width / 2.;
116
let centered_width = (2. * (center - start).min(end - center)).min(SEARCH_WIDTH);
117
let width = centered_width.max(SEARCH_MIN_WIDTH).min(room);
118
let left = (center - width / 2.).clamp(start, end - width);
119
Some(SearchSpan { left, width })
120
}
121
122
#[derive(Clone, Copy, PartialEq)]
123
struct Reserved {
124
leading_end: f32,
125
trailing_from_right: f32,
126
}
127
128
#[derive(IntoElement)]
129
struct TitleBarRow {
130
app_icon: AppIcon,
131
mode_label: Option<&'static str>,
132
update: Option<AnyElement>,
133
own: Option<AnyElement>,
134
on_search: Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>,
135
}
136
97
137
pub fn render_title_bar(
98
138
app_icon: AppIcon,
99
139
mode_label: Option<&'static str>,
@@ -101,63 +141,166 @@ pub fn render_title_bar(
101
141
own: Option<AnyElement>,
102
142
on_search: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
103
143
) -> impl IntoElement {
104
let search = h_flex()
144
TitleBarRow {
145
app_icon,
146
mode_label,
147
update,
148
own,
149
on_search: Box::new(on_search),
150
}
151
}
152
153
fn search_box(
154
span: SearchSpan,
155
on_search: Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>,
156
) -> impl IntoElement {
157
h_flex()
105
158
.id("title-search")
106
159
.debug_selector(|| "shell/title-bar/search".into())
107
160
.occlude()
108
.w(px(SEARCH_WIDTH))
109
.h(px(28.))
161
.absolute()
162
.top(px((TITLE_BAR_HEIGHT - SEARCH_HEIGHT) / 2.))
163
.left(px(span.left))
164
.w(px(span.width))
165
.h(px(SEARCH_HEIGHT))
110
166
.px(px(10.))
111
167
.gap(px(8.))
112
168
.items_center()
169
.overflow_hidden()
113
170
.rounded(px(6.))
114
171
.bg(theme::surface())
115
172
.cursor_pointer()
116
173
.text_size(px(12.))
117
174
.text_color(theme::text_muted())
118
.child(icon(IconName::Search, 14., theme::text_muted()))
119
.child(div().flex_1().child(SEARCH_HINT))
120
175
.child(
121
176
div()
122
.px(px(6.))
123
.py(px(1.))
124
.rounded(px(4.))
125
.bg(theme::surface_raised())
126
.text_size(px(11.))
127
.child(SHORTCUT_HINT),
177
.flex_none()
178
.child(icon(IconName::Search, 14., theme::text_muted())),
128
179
)
129
.on_click(on_search);
130
let bar = TitleBar::new()
131
.h(px(TITLE_BAR_HEIGHT))
132
.border_b_0()
133
.bg(theme::background())
134
.child(
135
h_flex()
136
.flex_1()
137
.h_full()
138
.gap(px(12.))
139
.items_center()
140
.child(
141
img(app_icon_image(app_icon))
142
.size(px(APP_ICON_SIZE))
143
.flex_none(),
144
)
145
.child(
146
div()
147
.text_size(px(13.))
148
.font_weight(FontWeight::SEMIBOLD)
149
.text_color(theme::text())
150
.child(app_base::APP_NAME),
151
)
152
.children(mode_label.map(mode_pill))
153
.child(div().flex_1().flex().justify_center().child(search))
154
.children(update)
155
.children(own)
156
.child(div().w(px(4.))),
157
);
158
div()
159
.debug_selector(|| "shell/title-bar".into())
160
.flex_none()
161
.w_full()
162
.child(bar)
180
.child(div().flex_1().min_w_0().truncate().child(SEARCH_HINT))
181
.when(span.width >= SHORTCUT_MIN_WIDTH, |search| {
182
search.child(
183
div()
184
.flex_none()
185
.px(px(6.))
186
.py(px(1.))
187
.rounded(px(4.))
188
.bg(theme::surface_raised())
189
.text_size(px(11.))
190
.child(SHORTCUT_HINT),
191
)
192
})
193
.on_click(move |event, window, cx| on_search(event, window, cx))
194
}
195
196
impl RenderOnce for TitleBarRow {
197
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
198
let reserved = window.use_keyed_state("title-bar-reserved", cx, |_, _| None::<Reserved>);
199
let window_width = f32::from(window.viewport_size().width);
200
let span = (*reserved.read(cx)).and_then(|reserved| {
201
search_span(
202
window_width,
203
reserved.leading_end,
204
window_width - reserved.trailing_from_right,
205
)
206
});
207
let leading = h_flex()
208
.debug_selector(|| "shell/title-bar/leading".into())
209
.flex_none()
210
.h_full()
211
.gap(px(12.))
212
.items_center()
213
.child(
214
img(app_icon_image(self.app_icon))
215
.size(px(APP_ICON_SIZE))
216
.flex_none(),
217
)
218
.child(
219
div()
220
.text_size(px(13.))
221
.font_weight(FontWeight::SEMIBOLD)
222
.text_color(theme::text())
223
.child(app_base::APP_NAME),
224
)
225
.children(self.mode_label.map(mode_pill));
226
let trailing = h_flex()
227
.debug_selector(|| "shell/title-bar/trailing".into())
228
.flex_none()
229
.h_full()
230
.gap(px(12.))
231
.items_center()
232
.children(self.update)
233
.children(self.own)
234
.child(div().w(px(4.)));
235
let row = h_flex()
236
.flex_1()
237
.h_full()
238
.gap(px(12.))
239
.items_center()
240
.child(leading)
241
.child(div().flex_1())
242
.child(trailing)
243
.on_children_prepainted(move |children, window, cx| {
244
let [leading, _, trailing] = children[..] else {
245
return;
246
};
247
let measured = Reserved {
248
leading_end: f32::from(leading.right()),
249
trailing_from_right: f32::from(window.viewport_size().width - trailing.left()),
250
};
251
reserved.update(cx, |current, cx| {
252
let unchanged = current.is_some_and(|current| {
253
(current.leading_end - measured.leading_end).abs() < 0.5
254
&& (current.trailing_from_right - measured.trailing_from_right).abs()
255
< 0.5
256
});
257
if !unchanged {
258
*current = Some(measured);
259
cx.notify();
260
}
261
});
262
});
263
let bar = TitleBar::new()
264
.h(px(TITLE_BAR_HEIGHT))
265
.border_b_0()
266
.bg(theme::background())
267
.child(row);
268
let on_search = self.on_search;
269
div()
270
.debug_selector(|| "shell/title-bar".into())
271
.relative()
272
.flex_none()
273
.w_full()
274
.child(bar)
275
.children(span.map(|span| search_box(span, on_search)))
276
}
277
}
278
279
#[cfg(test)]
280
mod tests {
281
use super::{SEARCH_MIN_WIDTH, SEARCH_WIDTH, search_span};
282
283
#[test]
284
fn search_stays_centered_while_it_fits() {
285
let span = search_span(1280., 200., 1080.).expect("visible");
286
assert_eq!(span.width, SEARCH_WIDTH);
287
assert_eq!(span.left + span.width / 2., 640.);
288
}
289
290
#[test]
291
fn search_shrinks_centered_before_it_shifts() {
292
let span = search_span(800., 200., 580.).expect("visible");
293
assert_eq!(span.left + span.width / 2., 400.);
294
assert_eq!(span.width, 344.);
295
let shifted = search_span(800., 200., 500.).expect("visible");
296
assert_eq!(shifted.width, SEARCH_MIN_WIDTH);
297
assert_eq!(shifted.left + shifted.width, 492.);
298
}
299
300
#[test]
301
fn search_takes_the_room_left_and_hides_without_any() {
302
let span = search_span(640., 200., 400.).expect("visible");
303
assert_eq!((span.left, span.width), (208., 184.));
304
assert_eq!(search_span(640., 300., 340.), None);
305
}
163
306
}
@@ -13,6 +13,11 @@ use crate::updater::UpdateStatus;13
13
14
pub const TITLE_BAR_HEIGHT: f32 = 40.;14
pub const TITLE_BAR_HEIGHT: f32 = 40.;15
const SEARCH_WIDTH: f32 = 380.;15
const SEARCH_WIDTH: f32 = 380.;16
const SEARCH_MIN_WIDTH: f32 = 240.;17
const SEARCH_MIN_VISIBLE_WIDTH: f32 = 36.;18
const SEARCH_HEIGHT: f32 = 28.;19
const SEARCH_GAP: f32 = 8.;20
const SHORTCUT_MIN_WIDTH: f32 = 200.;16
const SEARCH_HINT: &str = "Search chats, people and channels";21
const SEARCH_HINT: &str = "Search chats, people and channels";17
const SHORTCUT_HINT: &str = "Ctrl K";22
const SHORTCUT_HINT: &str = "Ctrl K";18
const APP_ICON_SIZE: f32 = 18.;23
const APP_ICON_SIZE: f32 = 18.;@@ -94,6 +99,41 @@ pub fn update_button(94
)99
)95
}100
}96
101
102
#[derive(Clone, Copy, Debug, PartialEq)]103
struct SearchSpan {104
left: f32,105
width: f32,106
}107
108
fn search_span(window_width: f32, leading_end: f32, trailing_start: f32) -> Option<SearchSpan> {109
let start = leading_end + SEARCH_GAP;110
let end = trailing_start - SEARCH_GAP;111
let room = end - start;112
if room < SEARCH_MIN_VISIBLE_WIDTH {113
return None;114
}115
let center = window_width / 2.;116
let centered_width = (2. * (center - start).min(end - center)).min(SEARCH_WIDTH);117
let width = centered_width.max(SEARCH_MIN_WIDTH).min(room);118
let left = (center - width / 2.).clamp(start, end - width);119
Some(SearchSpan { left, width })120
}121
122
#[derive(Clone, Copy, PartialEq)]123
struct Reserved {124
leading_end: f32,125
trailing_from_right: f32,126
}127
128
#[derive(IntoElement)]129
struct TitleBarRow {130
app_icon: AppIcon,131
mode_label: Option<&'static str>,132
update: Option<AnyElement>,133
own: Option<AnyElement>,134
on_search: Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>,135
}136
97
pub fn render_title_bar(137
pub fn render_title_bar(98
app_icon: AppIcon,138
app_icon: AppIcon,99
mode_label: Option<&'static str>,139
mode_label: Option<&'static str>,@@ -101,63 +141,166 @@ pub fn render_title_bar(101
own: Option<AnyElement>,141
own: Option<AnyElement>,102
on_search: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,142
on_search: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,103
) -> impl IntoElement {143
) -> impl IntoElement {104
let search = h_flex()144
TitleBarRow {145
app_icon,146
mode_label,147
update,148
own,149
on_search: Box::new(on_search),150
}151
}152
153
fn search_box(154
span: SearchSpan,155
on_search: Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>,156
) -> impl IntoElement {157
h_flex()105
.id("title-search")158
.id("title-search")106
.debug_selector(|| "shell/title-bar/search".into())159
.debug_selector(|| "shell/title-bar/search".into())107
.occlude()160
.occlude()108
.w(px(SEARCH_WIDTH))161
.absolute()109
.h(px(28.))162
.top(px((TITLE_BAR_HEIGHT - SEARCH_HEIGHT) / 2.))163
.left(px(span.left))164
.w(px(span.width))165
.h(px(SEARCH_HEIGHT))110
.px(px(10.))166
.px(px(10.))111
.gap(px(8.))167
.gap(px(8.))112
.items_center()168
.items_center()169
.overflow_hidden()113
.rounded(px(6.))170
.rounded(px(6.))114
.bg(theme::surface())171
.bg(theme::surface())115
.cursor_pointer()172
.cursor_pointer()116
.text_size(px(12.))173
.text_size(px(12.))117
.text_color(theme::text_muted())174
.text_color(theme::text_muted())118
.child(icon(IconName::Search, 14., theme::text_muted()))119
.child(div().flex_1().child(SEARCH_HINT))120
.child(175
.child(121
div()176
div()122
.px(px(6.))177
.flex_none()123
.py(px(1.))178
.child(icon(IconName::Search, 14., theme::text_muted())),124
.rounded(px(4.))125
.bg(theme::surface_raised())126
.text_size(px(11.))127
.child(SHORTCUT_HINT),128
)179
)129
.on_click(on_search);180
.child(div().flex_1().min_w_0().truncate().child(SEARCH_HINT))130
let bar = TitleBar::new()181
.when(span.width >= SHORTCUT_MIN_WIDTH, |search| {131
.h(px(TITLE_BAR_HEIGHT))182
search.child(132
.border_b_0()183
div()133
.bg(theme::background())184
.flex_none()134
.child(185
.px(px(6.))135
h_flex()186
.py(px(1.))136
.flex_1()187
.rounded(px(4.))137
.h_full()188
.bg(theme::surface_raised())138
.gap(px(12.))189
.text_size(px(11.))139
.items_center()190
.child(SHORTCUT_HINT),140
.child(191
)141
img(app_icon_image(app_icon))192
})142
.size(px(APP_ICON_SIZE))193
.on_click(move |event, window, cx| on_search(event, window, cx))143
.flex_none(),194
}144
)195
145
.child(196
impl RenderOnce for TitleBarRow {146
div()197
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {147
.text_size(px(13.))198
let reserved = window.use_keyed_state("title-bar-reserved", cx, |_, _| None::<Reserved>);148
.font_weight(FontWeight::SEMIBOLD)199
let window_width = f32::from(window.viewport_size().width);149
.text_color(theme::text())200
let span = (*reserved.read(cx)).and_then(|reserved| {150
.child(app_base::APP_NAME),201
search_span(151
)202
window_width,152
.children(mode_label.map(mode_pill))203
reserved.leading_end,153
.child(div().flex_1().flex().justify_center().child(search))204
window_width - reserved.trailing_from_right,154
.children(update)205
)155
.children(own)206
});156
.child(div().w(px(4.))),207
let leading = h_flex()157
);208
.debug_selector(|| "shell/title-bar/leading".into())158
div()209
.flex_none()159
.debug_selector(|| "shell/title-bar".into())210
.h_full()160
.flex_none()211
.gap(px(12.))161
.w_full()212
.items_center()162
.child(bar)213
.child(214
img(app_icon_image(self.app_icon))215
.size(px(APP_ICON_SIZE))216
.flex_none(),217
)218
.child(219
div()220
.text_size(px(13.))221
.font_weight(FontWeight::SEMIBOLD)222
.text_color(theme::text())223
.child(app_base::APP_NAME),224
)225
.children(self.mode_label.map(mode_pill));226
let trailing = h_flex()227
.debug_selector(|| "shell/title-bar/trailing".into())228
.flex_none()229
.h_full()230
.gap(px(12.))231
.items_center()232
.children(self.update)233
.children(self.own)234
.child(div().w(px(4.)));235
let row = h_flex()236
.flex_1()237
.h_full()238
.gap(px(12.))239
.items_center()240
.child(leading)241
.child(div().flex_1())242
.child(trailing)243
.on_children_prepainted(move |children, window, cx| {244
let [leading, _, trailing] = children[..] else {245
return;246
};247
let measured = Reserved {248
leading_end: f32::from(leading.right()),249
trailing_from_right: f32::from(window.viewport_size().width - trailing.left()),250
};251
reserved.update(cx, |current, cx| {252
let unchanged = current.is_some_and(|current| {253
(current.leading_end - measured.leading_end).abs() < 0.5254
&& (current.trailing_from_right - measured.trailing_from_right).abs()255
< 0.5256
});257
if !unchanged {258
*current = Some(measured);259
cx.notify();260
}261
});262
});263
let bar = TitleBar::new()264
.h(px(TITLE_BAR_HEIGHT))265
.border_b_0()266
.bg(theme::background())267
.child(row);268
let on_search = self.on_search;269
div()270
.debug_selector(|| "shell/title-bar".into())271
.relative()272
.flex_none()273
.w_full()274
.child(bar)275
.children(span.map(|span| search_box(span, on_search)))276
}277
}278
279
#[cfg(test)]280
mod tests {281
use super::{SEARCH_MIN_WIDTH, SEARCH_WIDTH, search_span};282
283
#[test]284
fn search_stays_centered_while_it_fits() {285
let span = search_span(1280., 200., 1080.).expect("visible");286
assert_eq!(span.width, SEARCH_WIDTH);287
assert_eq!(span.left + span.width / 2., 640.);288
}289
290
#[test]291
fn search_shrinks_centered_before_it_shifts() {292
let span = search_span(800., 200., 580.).expect("visible");293
assert_eq!(span.left + span.width / 2., 400.);294
assert_eq!(span.width, 344.);295
let shifted = search_span(800., 200., 500.).expect("visible");296
assert_eq!(shifted.width, SEARCH_MIN_WIDTH);297
assert_eq!(shifted.left + shifted.width, 492.);298
}299
300
#[test]301
fn search_takes_the_room_left_and_hides_without_any() {302
let span = search_span(640., 200., 400.).expect("visible");303
assert_eq!((span.left, span.width), (208., 184.));304
assert_eq!(search_span(640., 300., 340.), None);305
}163
}306
}@@ -6,8 +6,8 @@ use session::{Request, Scope, Session};
6
6
7
7
use crate::error::{Error, Result};
8
8
9
pub const CATALOG_URL: &str = "https://statics.teams.cdn.office.net/evergreen-assets/backgroundimages/config.json?v=7";
10
pub const CDN_ROOT: &str = "https://statics.teams.cdn.office.net";
9
pub const CATALOG_URL: &str = chatsvc::teams_cdn::BACKGROUND_CATALOG_URL;
10
pub const CDN_ROOT: &str = chatsvc::teams_cdn::ROOT;
11
11
const FETCH_SCOPE: &str = "Chat.Read";
12
12
const MAX_SIDE: u32 = 1920;
13
13
const CATALOG_FILE: &str = "config.json";
@@ -6,8 +6,8 @@ use session::{Request, Scope, Session};6
6
7
use crate::error::{Error, Result};7
use crate::error::{Error, Result};8
8
9
pub const CATALOG_URL: &str = "https://statics.teams.cdn.office.net/evergreen-assets/backgroundimages/config.json?v=7";9
pub const CATALOG_URL: &str = chatsvc::teams_cdn::BACKGROUND_CATALOG_URL;10
pub const CDN_ROOT: &str = "https://statics.teams.cdn.office.net";10
pub const CDN_ROOT: &str = chatsvc::teams_cdn::ROOT;11
const FETCH_SCOPE: &str = "Chat.Read";11
const FETCH_SCOPE: &str = "Chat.Read";12
const MAX_SIDE: u32 = 1920;12
const MAX_SIDE: u32 = 1920;13
const CATALOG_FILE: &str = "config.json";13
const CATALOG_FILE: &str = "config.json";@@ -97,10 +97,7 @@ pub fn live_meeting(thread_id: &str, properties: &Value, now_unix: i64) -> Optio
97
97
}
98
98
99
99
pub async fn fetch_live_meeting(session: &Session, thread_id: &str) -> Result<Option<LiveMeeting>> {
100
let url = format!(
101
"https://teams.cloud.microsoft/api/chatsvc/{CHATSVC_REGION}/v1/users/ME/conversations/{}?view=msnp24Equivalent",
102
thread_id.replace(':', "%3A").replace('@', "%40")
103
);
100
let url = chatsvc::conversations::thread_url(CHATSVC_REGION, thread_id);
104
101
let response = session.send(Request::get(url), &ic3_scope()).await?;
105
102
let now = std::time::SystemTime::now()
106
103
.duration_since(std::time::UNIX_EPOCH)
@@ -97,10 +97,7 @@ pub fn live_meeting(thread_id: &str, properties: &Value, now_unix: i64) -> Optio97
}97
}98
98
99
pub async fn fetch_live_meeting(session: &Session, thread_id: &str) -> Result<Option<LiveMeeting>> {99
pub async fn fetch_live_meeting(session: &Session, thread_id: &str) -> Result<Option<LiveMeeting>> {100
let url = format!(100
let url = chatsvc::conversations::thread_url(CHATSVC_REGION, thread_id);101
"https://teams.cloud.microsoft/api/chatsvc/{CHATSVC_REGION}/v1/users/ME/conversations/{}?view=msnp24Equivalent",102
thread_id.replace(':', "%3A").replace('@', "%40")103
);104
let response = session.send(Request::get(url), &ic3_scope()).await?;101
let response = session.send(Request::get(url), &ic3_scope()).await?;105
let now = std::time::SystemTime::now()102
let now = std::time::SystemTime::now()106
.duration_since(std::time::UNIX_EPOCH)103
.duration_since(std::time::UNIX_EPOCH)@@ -1062,10 +1062,7 @@ pub async fn find_echo_bot_thread(session: &Session, self_object_id: &str) -> Re
1062
1062
format!("19:{self_object_id}_{bot_id}@unq.gbl.spaces"),
1063
1063
format!("19:{bot_id}_{self_object_id}@unq.gbl.spaces"),
1064
1064
] {
1065
let url = format!(
1066
"https://teams.cloud.microsoft/api/chatsvc/{CHATSVC_REGION}/v1/users/ME/conversations/{}?view=msnp24Equivalent",
1067
thread_id.replace(':', "%3A").replace('@', "%40")
1068
);
1065
let url = chatsvc::conversations::thread_url(CHATSVC_REGION, &thread_id);
1069
1066
let response = session.batch(&[Request::get(url)], &ic3_scope()).await?.remove(0);
1070
1067
if response.is_success() {
1071
1068
return Ok(Some(thread_id));
@@ -1062,10 +1062,7 @@ pub async fn find_echo_bot_thread(session: &Session, self_object_id: &str) -> Re1062
format!("19:{self_object_id}_{bot_id}@unq.gbl.spaces"),1062
format!("19:{self_object_id}_{bot_id}@unq.gbl.spaces"),1063
format!("19:{bot_id}_{self_object_id}@unq.gbl.spaces"),1063
format!("19:{bot_id}_{self_object_id}@unq.gbl.spaces"),1064
] {1064
] {1065
let url = format!(1065
let url = chatsvc::conversations::thread_url(CHATSVC_REGION, &thread_id);1066
"https://teams.cloud.microsoft/api/chatsvc/{CHATSVC_REGION}/v1/users/ME/conversations/{}?view=msnp24Equivalent",1067
thread_id.replace(':', "%3A").replace('@', "%40")1068
);1069
let response = session.batch(&[Request::get(url)], &ic3_scope()).await?.remove(0);1066
let response = session.batch(&[Request::get(url)], &ic3_scope()).await?.remove(0);1070
if response.is_success() {1067
if response.is_success() {1071
return Ok(Some(thread_id));1068
return Ok(Some(thread_id));@@ -118,6 +118,14 @@ impl<T: MessageTransport> Conversations<T> {
118
118
}
119
119
}
120
120
121
/// One conversation with its thread properties, as Teams reads a meeting or 1:1 thread.
122
pub fn thread_url(region: &str, thread_id: &str) -> String {
123
format!(
124
"https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/conversations/{}?view=msnp24Equivalent",
125
thread_id.replace(':', "%3A").replace('@', "%40")
126
)
127
}
128
121
129
fn backward_link(body: &Value) -> Option<String> {
122
130
body.pointer("/_metadata/backwardLink")
123
131
.and_then(Value::as_str)
@@ -208,6 +216,14 @@ mod tests {
208
216
209
217
const BASE: &str = "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations";
210
218
219
#[test]
220
fn thread_url_escapes_the_thread_id() {
221
assert_eq!(
222
thread_url("emea", "19:meeting_a@thread.v2"),
223
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations/19%3Ameeting_a%40thread.v2?view=msnp24Equivalent"
224
);
225
}
226
211
227
#[tokio::test]
212
228
async fn mute_states_pair_every_conversation_with_its_flag() {
213
229
let transport = canned(vec![(
@@ -118,6 +118,14 @@ impl<T: MessageTransport> Conversations<T> {118
}118
}119
}119
}120
120
121
/// One conversation with its thread properties, as Teams reads a meeting or 1:1 thread.122
pub fn thread_url(region: &str, thread_id: &str) -> String {123
format!(124
"https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/conversations/{}?view=msnp24Equivalent",125
thread_id.replace(':', "%3A").replace('@', "%40")126
)127
}128
121
fn backward_link(body: &Value) -> Option<String> {129
fn backward_link(body: &Value) -> Option<String> {122
body.pointer("/_metadata/backwardLink")130
body.pointer("/_metadata/backwardLink")123
.and_then(Value::as_str)131
.and_then(Value::as_str)@@ -208,6 +216,14 @@ mod tests {208
216
209
const BASE: &str = "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations";217
const BASE: &str = "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations";210
218
219
#[test]220
fn thread_url_escapes_the_thread_id() {221
assert_eq!(222
thread_url("emea", "19:meeting_a@thread.v2"),223
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations/19%3Ameeting_a%40thread.v2?view=msnp24Equivalent"224
);225
}226
211
#[tokio::test]227
#[tokio::test]212
async fn mute_states_pair_every_conversation_with_its_flag() {228
async fn mute_states_pair_every_conversation_with_its_flag() {213
let transport = canned(vec![(229
let transport = canned(vec![(@@ -27,6 +27,7 @@ pub mod settings;
27
27
pub mod sound_settings;
28
28
pub mod sounds;
29
29
pub mod substrate_search;
30
pub mod teams_cdn;
30
31
pub mod transcripts;
31
32
pub mod translate;
32
33
pub mod window;
@@ -59,8 +60,9 @@ pub use pins::{
59
60
PinnedMessage, Pins, TeamLayout,
60
61
};
61
62
pub use presence::{
62
ActivityReporting, ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote,
63
WorkLocation, WorkLocationKind, WorkLocationSource, error_status, is_endpoint_missing,
63
ActivityReporting, ForcedAvailability, ForcedKind, PresenceLookup, PresenceService,
64
PresenceStatus, StatusNote, UserPresence, WorkLocation, WorkLocationKind, WorkLocationSource,
65
error_status, is_endpoint_missing,
64
66
};
65
67
pub use reactions::{
66
68
emotion_glyph, emotion_key, emotion_keys, insert_skin_tone, reaction_glyph_for_key,
@@ -27,6 +27,7 @@ pub mod settings;27
pub mod sound_settings;27
pub mod sound_settings;28
pub mod sounds;28
pub mod sounds;29
pub mod substrate_search;29
pub mod substrate_search;30
pub mod teams_cdn;30
pub mod transcripts;31
pub mod transcripts;31
pub mod translate;32
pub mod translate;32
pub mod window;33
pub mod window;@@ -59,8 +60,9 @@ pub use pins::{59
PinnedMessage, Pins, TeamLayout,60
PinnedMessage, Pins, TeamLayout,60
};61
};61
pub use presence::{62
pub use presence::{62
ActivityReporting, ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote,63
ActivityReporting, ForcedAvailability, ForcedKind, PresenceLookup, PresenceService,63
WorkLocation, WorkLocationKind, WorkLocationSource, error_status, is_endpoint_missing,64
PresenceStatus, StatusNote, UserPresence, WorkLocation, WorkLocationKind, WorkLocationSource,65
error_status, is_endpoint_missing,64
};66
};65
pub use reactions::{67
pub use reactions::{66
emotion_glyph, emotion_key, emotion_keys, insert_skin_tone, reaction_glyph_for_key,68
emotion_glyph, emotion_key, emotion_keys, insert_skin_tone, reaction_glyph_for_key,@@ -7,7 +7,7 @@ use crate::error::{Error, Result};
7
7
use crate::messages::{ConversationRef, MessageTransport, Messages, encode, ensure_success};
8
8
9
9
const URLP_BASE: &str = "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url";
10
const IMAGE_HOST_SUFFIX: &str = ".asyncgw.teams.microsoft.com";
10
pub const LINK_PROXY_HOST_SUFFIX: &str = ".asyncgw.teams.microsoft.com";
11
11
const LIST_VIEW: &str = "msnp24Equivalent";
12
12
13
13
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -36,7 +36,7 @@ pub struct LinkImage {
36
36
pub fn is_link_image_url(url: &str) -> bool {
37
37
url.strip_prefix("https://")
38
38
.and_then(|rest| rest.split(['/', '?', '#']).next())
39
.is_some_and(|host| host.ends_with(IMAGE_HOST_SUFFIX))
39
.is_some_and(|host| host.ends_with(LINK_PROXY_HOST_SUFFIX))
40
40
}
41
41
42
42
pub fn parse_message_links(body: &Value) -> Vec<MessageLinks> {
@@ -7,7 +7,7 @@ use crate::error::{Error, Result};7
use crate::messages::{ConversationRef, MessageTransport, Messages, encode, ensure_success};7
use crate::messages::{ConversationRef, MessageTransport, Messages, encode, ensure_success};8
8
9
const URLP_BASE: &str = "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url";9
const URLP_BASE: &str = "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url";10
const IMAGE_HOST_SUFFIX: &str = ".asyncgw.teams.microsoft.com";10
pub const LINK_PROXY_HOST_SUFFIX: &str = ".asyncgw.teams.microsoft.com";11
const LIST_VIEW: &str = "msnp24Equivalent";11
const LIST_VIEW: &str = "msnp24Equivalent";12
12
13
#[derive(Debug, Clone, PartialEq, Eq)]13
#[derive(Debug, Clone, PartialEq, Eq)]@@ -36,7 +36,7 @@ pub struct LinkImage {36
pub fn is_link_image_url(url: &str) -> bool {36
pub fn is_link_image_url(url: &str) -> bool {37
url.strip_prefix("https://")37
url.strip_prefix("https://")38
.and_then(|rest| rest.split(['/', '?', '#']).next())38
.and_then(|rest| rest.split(['/', '?', '#']).next())39
.is_some_and(|host| host.ends_with(IMAGE_HOST_SUFFIX))39
.is_some_and(|host| host.ends_with(LINK_PROXY_HOST_SUFFIX))40
}40
}41
41
42
pub fn parse_message_links(body: &Value) -> Vec<MessageLinks> {42
pub fn parse_message_links(body: &Value) -> Vec<MessageLinks> {@@ -6,6 +6,10 @@ use uuid::Uuid;
6
6
use crate::cards::{CardTransport, SessionCardTransport};
7
7
use crate::error::{Error, Result};
8
8
9
mod lookup;
10
11
pub use lookup::{MAX_PRESENCE_IDS, PresenceLookup, UserPresence};
12
9
13
const BASE_URL: &str = "https://presence.teams.microsoft.com/v1";
10
14
const PRESENCE_SCOPE: &str = "user_impersonation";
11
15
const CLIENT_VERSION: &str = "1415/26091712213";
@@ -6,6 +6,10 @@ use uuid::Uuid;6
use crate::cards::{CardTransport, SessionCardTransport};6
use crate::cards::{CardTransport, SessionCardTransport};7
use crate::error::{Error, Result};7
use crate::error::{Error, Result};8
8
9
mod lookup;10
11
pub use lookup::{MAX_PRESENCE_IDS, PresenceLookup, UserPresence};12
9
const BASE_URL: &str = "https://presence.teams.microsoft.com/v1";13
const BASE_URL: &str = "https://presence.teams.microsoft.com/v1";10
const PRESENCE_SCOPE: &str = "user_impersonation";14
const PRESENCE_SCOPE: &str = "user_impersonation";11
const CLIENT_VERSION: &str = "1415/26091712213";15
const CLIENT_VERSION: &str = "1415/26091712213";@@ -0,0 +1,187 @@
1
use serde_json::{Value, json};
2
use session::{Method, PRESENCE, Request, Scope, Session};
3
use uuid::Uuid;
4
5
use crate::error::Result;
6
7
pub const MAX_PRESENCE_IDS: usize = 650;
8
pub const MAX_SUBSCRIBE_IDS: usize = 200;
9
const PRESENCE_SERVICE_URL: &str = "https://presence.teams.microsoft.com/v1/presence/getpresence/";
10
const PRESENCE_SERVICE_SCOPE: &str = "user_impersonation";
11
const PRESENCE_SUBSCRIBE_URL: &str =
12
"https://presence.teams.microsoft.com/v1/pubsub/subscriptions/";
13
const PRESENCE_CLIENT_VERSION: &str = "1415/26091712213";
14
const ORGID_PREFIX: &str = "8:orgid:";
15
16
#[derive(Debug, Clone, PartialEq, Eq)]
17
pub struct UserPresence {
18
pub user_id: String,
19
pub availability: String,
20
pub activity: Option<String>,
21
}
22
23
pub struct PresenceLookup {
24
session: Session,
25
}
26
27
impl PresenceLookup {
28
pub fn new(session: &Session) -> Self {
29
PresenceLookup {
30
session: session.clone(),
31
}
32
}
33
34
/// Graph `Presence.Read.All` is not in the web app tokens.
35
pub async fn presences(&self, user_ids: &[String]) -> Result<Vec<UserPresence>> {
36
let scope = Scope::new(PRESENCE, PRESENCE_SERVICE_SCOPE);
37
let mut presences = Vec::with_capacity(user_ids.len());
38
for chunk in user_ids.chunks(MAX_PRESENCE_IDS) {
39
let body: Vec<Value> = chunk
40
.iter()
41
.map(|user_id| json!({"mri": format!("{ORGID_PREFIX}{user_id}")}))
42
.collect();
43
let answer = self
44
.session
45
.request(
46
Method::Post,
47
PRESENCE_SERVICE_URL,
48
&scope,
49
Some(Value::Array(body)),
50
)
51
.await?;
52
presences.extend(parse_service_presences(&answer.body));
53
}
54
Ok(presences)
55
}
56
57
pub async fn subscribe(
58
&self,
59
endpoint_id: &str,
60
trouter_uri: &str,
61
user_ids: &[String],
62
purge: bool,
63
) -> Result<()> {
64
let scope = Scope::new(PRESENCE, PRESENCE_SERVICE_SCOPE);
65
let url = format!("{PRESENCE_SUBSCRIBE_URL}{endpoint_id}");
66
for (index, chunk) in user_ids.chunks(MAX_SUBSCRIBE_IDS).enumerate() {
67
let request = Request {
68
method: Method::Post,
69
headers: subscribe_headers(endpoint_id),
70
body: Some(subscribe_body(trouter_uri, chunk, purge && index == 0)),
71
..Request::get(url.clone())
72
};
73
let answer = self.session.send(request, &scope).await?;
74
if !(200..300).contains(&answer.status) {
75
return Err(session::Error::api(answer.status, &url, answer.body).into());
76
}
77
}
78
Ok(())
79
}
80
}
81
82
// The service answers 400 naming each of the three x-ms-* client headers when one is missing.
83
fn subscribe_headers(endpoint_id: &str) -> Vec<(String, String)> {
84
vec![
85
("x-ms-client-user-agent".into(), "Teams-V2-Web".into()),
86
("x-ms-correlation-id".into(), Uuid::new_v4().to_string()),
87
("x-ms-client-version".into(), PRESENCE_CLIENT_VERSION.into()),
88
("x-ms-endpoint-id".into(), endpoint_id.into()),
89
("x-ms-client-type".into(), "cdlworker".into()),
90
]
91
}
92
93
fn subscribe_body(trouter_uri: &str, user_ids: &[String], purge: bool) -> Value {
94
let additions: Vec<Value> = user_ids
95
.iter()
96
.map(|user_id| json!({"mri": format!("{ORGID_PREFIX}{user_id}"), "source": "ups"}))
97
.collect();
98
json!({
99
"trouterUri": trouter_uri,
100
"shouldPurgePreviousSubscriptions": purge,
101
"subscriptionsToAdd": additions,
102
"subscriptionsToRemove": [],
103
})
104
}
105
106
fn parse_service_presences(body: &Value) -> Vec<UserPresence> {
107
body.as_array()
108
.into_iter()
109
.flatten()
110
.filter_map(|entry| {
111
let mri = entry.get("mri")?.as_str()?;
112
let presence = entry.get("presence")?;
113
Some(UserPresence {
114
user_id: mri.strip_prefix(ORGID_PREFIX).unwrap_or(mri).to_owned(),
115
availability: presence.get("availability")?.as_str()?.to_owned(),
116
activity: if presence
117
.pointer("/calendarData/isOutOfOffice")
118
.and_then(Value::as_bool)
119
.unwrap_or(false)
120
{
121
Some("OutOfOffice".to_owned())
122
} else {
123
presence
124
.get("activity")
125
.and_then(Value::as_str)
126
.map(str::to_owned)
127
},
128
})
129
})
130
.collect()
131
}
132
133
#[cfg(test)]
134
mod tests {
135
use super::*;
136
137
#[test]
138
fn subscribe_body_carries_mris_and_purge_flag() {
139
let body = subscribe_body("https://t/unifiedPresenceService", &["a".into()], true);
140
assert_eq!(
141
body,
142
json!({
143
"trouterUri": "https://t/unifiedPresenceService",
144
"shouldPurgePreviousSubscriptions": true,
145
"subscriptionsToAdd": [{"mri": "8:orgid:a", "source": "ups"}],
146
"subscriptionsToRemove": [],
147
})
148
);
149
}
150
151
#[test]
152
fn subscribe_headers_use_a_fresh_correlation_id() {
153
let correlation = |headers: &[(String, String)]| {
154
headers
155
.iter()
156
.find(|(name, _)| name == "x-ms-correlation-id")
157
.map(|(_, value)| value.clone())
158
};
159
let first = subscribe_headers("e");
160
assert_ne!(correlation(&first), correlation(&subscribe_headers("e")));
161
assert!(
162
first
163
.iter()
164
.any(|(name, value)| name == "x-ms-endpoint-id" && value == "e")
165
);
166
}
167
168
#[test]
169
fn service_presences_strip_the_mri_prefix() {
170
let parsed = parse_service_presences(&json!([
171
{"mri": "8:orgid:a", "presence": {"availability": "Away", "activity": "Away"}},
172
{"mri": "8:orgid:b"}
173
]));
174
assert_eq!(parsed.len(), 1);
175
assert_eq!(parsed[0].user_id, "a");
176
}
177
178
#[test]
179
fn out_of_office_from_the_calendar_becomes_the_activity() {
180
let parsed = parse_service_presences(&json!([
181
{"mri": "8:orgid:a", "presence": {"availability": "Offline", "activity": "OffWork", "calendarData": {"isOutOfOffice": true}}},
182
{"mri": "8:orgid:b", "presence": {"availability": "Available", "activity": "Available", "calendarData": {"isOutOfOffice": false}}}
183
]));
184
assert_eq!(parsed[0].activity.as_deref(), Some("OutOfOffice"));
185
assert_eq!(parsed[1].activity.as_deref(), Some("Available"));
186
}
187
}
@@ -0,0 +1,187 @@1
use serde_json::{Value, json};2
use session::{Method, PRESENCE, Request, Scope, Session};3
use uuid::Uuid;4
5
use crate::error::Result;6
7
pub const MAX_PRESENCE_IDS: usize = 650;8
pub const MAX_SUBSCRIBE_IDS: usize = 200;9
const PRESENCE_SERVICE_URL: &str = "https://presence.teams.microsoft.com/v1/presence/getpresence/";10
const PRESENCE_SERVICE_SCOPE: &str = "user_impersonation";11
const PRESENCE_SUBSCRIBE_URL: &str =12
"https://presence.teams.microsoft.com/v1/pubsub/subscriptions/";13
const PRESENCE_CLIENT_VERSION: &str = "1415/26091712213";14
const ORGID_PREFIX: &str = "8:orgid:";15
16
#[derive(Debug, Clone, PartialEq, Eq)]17
pub struct UserPresence {18
pub user_id: String,19
pub availability: String,20
pub activity: Option<String>,21
}22
23
pub struct PresenceLookup {24
session: Session,25
}26
27
impl PresenceLookup {28
pub fn new(session: &Session) -> Self {29
PresenceLookup {30
session: session.clone(),31
}32
}33
34
/// Graph `Presence.Read.All` is not in the web app tokens.35
pub async fn presences(&self, user_ids: &[String]) -> Result<Vec<UserPresence>> {36
let scope = Scope::new(PRESENCE, PRESENCE_SERVICE_SCOPE);37
let mut presences = Vec::with_capacity(user_ids.len());38
for chunk in user_ids.chunks(MAX_PRESENCE_IDS) {39
let body: Vec<Value> = chunk40
.iter()41
.map(|user_id| json!({"mri": format!("{ORGID_PREFIX}{user_id}")}))42
.collect();43
let answer = self44
.session45
.request(46
Method::Post,47
PRESENCE_SERVICE_URL,48
&scope,49
Some(Value::Array(body)),50
)51
.await?;52
presences.extend(parse_service_presences(&answer.body));53
}54
Ok(presences)55
}56
57
pub async fn subscribe(58
&self,59
endpoint_id: &str,60
trouter_uri: &str,61
user_ids: &[String],62
purge: bool,63
) -> Result<()> {64
let scope = Scope::new(PRESENCE, PRESENCE_SERVICE_SCOPE);65
let url = format!("{PRESENCE_SUBSCRIBE_URL}{endpoint_id}");66
for (index, chunk) in user_ids.chunks(MAX_SUBSCRIBE_IDS).enumerate() {67
let request = Request {68
method: Method::Post,69
headers: subscribe_headers(endpoint_id),70
body: Some(subscribe_body(trouter_uri, chunk, purge && index == 0)),71
..Request::get(url.clone())72
};73
let answer = self.session.send(request, &scope).await?;74
if !(200..300).contains(&answer.status) {75
return Err(session::Error::api(answer.status, &url, answer.body).into());76
}77
}78
Ok(())79
}80
}81
82
// The service answers 400 naming each of the three x-ms-* client headers when one is missing.83
fn subscribe_headers(endpoint_id: &str) -> Vec<(String, String)> {84
vec![85
("x-ms-client-user-agent".into(), "Teams-V2-Web".into()),86
("x-ms-correlation-id".into(), Uuid::new_v4().to_string()),87
("x-ms-client-version".into(), PRESENCE_CLIENT_VERSION.into()),88
("x-ms-endpoint-id".into(), endpoint_id.into()),89
("x-ms-client-type".into(), "cdlworker".into()),90
]91
}92
93
fn subscribe_body(trouter_uri: &str, user_ids: &[String], purge: bool) -> Value {94
let additions: Vec<Value> = user_ids95
.iter()96
.map(|user_id| json!({"mri": format!("{ORGID_PREFIX}{user_id}"), "source": "ups"}))97
.collect();98
json!({99
"trouterUri": trouter_uri,100
"shouldPurgePreviousSubscriptions": purge,101
"subscriptionsToAdd": additions,102
"subscriptionsToRemove": [],103
})104
}105
106
fn parse_service_presences(body: &Value) -> Vec<UserPresence> {107
body.as_array()108
.into_iter()109
.flatten()110
.filter_map(|entry| {111
let mri = entry.get("mri")?.as_str()?;112
let presence = entry.get("presence")?;113
Some(UserPresence {114
user_id: mri.strip_prefix(ORGID_PREFIX).unwrap_or(mri).to_owned(),115
availability: presence.get("availability")?.as_str()?.to_owned(),116
activity: if presence117
.pointer("/calendarData/isOutOfOffice")118
.and_then(Value::as_bool)119
.unwrap_or(false)120
{121
Some("OutOfOffice".to_owned())122
} else {123
presence124
.get("activity")125
.and_then(Value::as_str)126
.map(str::to_owned)127
},128
})129
})130
.collect()131
}132
133
#[cfg(test)]134
mod tests {135
use super::*;136
137
#[test]138
fn subscribe_body_carries_mris_and_purge_flag() {139
let body = subscribe_body("https://t/unifiedPresenceService", &["a".into()], true);140
assert_eq!(141
body,142
json!({143
"trouterUri": "https://t/unifiedPresenceService",144
"shouldPurgePreviousSubscriptions": true,145
"subscriptionsToAdd": [{"mri": "8:orgid:a", "source": "ups"}],146
"subscriptionsToRemove": [],147
})148
);149
}150
151
#[test]152
fn subscribe_headers_use_a_fresh_correlation_id() {153
let correlation = |headers: &[(String, String)]| {154
headers155
.iter()156
.find(|(name, _)| name == "x-ms-correlation-id")157
.map(|(_, value)| value.clone())158
};159
let first = subscribe_headers("e");160
assert_ne!(correlation(&first), correlation(&subscribe_headers("e")));161
assert!(162
first163
.iter()164
.any(|(name, value)| name == "x-ms-endpoint-id" && value == "e")165
);166
}167
168
#[test]169
fn service_presences_strip_the_mri_prefix() {170
let parsed = parse_service_presences(&json!([171
{"mri": "8:orgid:a", "presence": {"availability": "Away", "activity": "Away"}},172
{"mri": "8:orgid:b"}173
]));174
assert_eq!(parsed.len(), 1);175
assert_eq!(parsed[0].user_id, "a");176
}177
178
#[test]179
fn out_of_office_from_the_calendar_becomes_the_activity() {180
let parsed = parse_service_presences(&json!([181
{"mri": "8:orgid:a", "presence": {"availability": "Offline", "activity": "OffWork", "calendarData": {"isOutOfOffice": true}}},182
{"mri": "8:orgid:b", "presence": {"availability": "Available", "activity": "Available", "calendarData": {"isOutOfOffice": false}}}183
]));184
assert_eq!(parsed[0].activity.as_deref(), Some("OutOfOffice"));185
assert_eq!(parsed[1].activity.as_deref(), Some("Available"));186
}187
}@@ -0,0 +1,29 @@
1
pub const HOST: &str = "statics.teams.cdn.office.net";
2
pub const ROOT: &str = "https://statics.teams.cdn.office.net";
3
pub const SOUND_BASE_URL: &str = "https://statics.teams.cdn.office.net/evergreen-assets/audio/";
4
pub const STICKER_BASE_URL: &str =
5
"https://statics.teams.cdn.office.net/evergreen-assets/stickerassets";
6
pub const EMOTICON_BASE_URL: &str = "https://statics.teams.cdn.office.net/evergreen-assets/personal-expressions/v2/assets/emoticons";
7
pub const BACKGROUND_CATALOG_URL: &str =
8
"https://statics.teams.cdn.office.net/evergreen-assets/backgroundimages/config.json?v=7";
9
10
#[cfg(test)]
11
mod tests {
12
use super::*;
13
14
#[test]
15
fn every_url_lives_on_the_cdn_root() {
16
assert_eq!(ROOT, format!("https://{HOST}"));
17
for url in [
18
SOUND_BASE_URL,
19
STICKER_BASE_URL,
20
EMOTICON_BASE_URL,
21
BACKGROUND_CATALOG_URL,
22
] {
23
assert!(
24
url.starts_with(&format!("{ROOT}/evergreen-assets/")),
25
"{url}"
26
);
27
}
28
}
29
}
@@ -0,0 +1,29 @@1
pub const HOST: &str = "statics.teams.cdn.office.net";2
pub const ROOT: &str = "https://statics.teams.cdn.office.net";3
pub const SOUND_BASE_URL: &str = "https://statics.teams.cdn.office.net/evergreen-assets/audio/";4
pub const STICKER_BASE_URL: &str =5
"https://statics.teams.cdn.office.net/evergreen-assets/stickerassets";6
pub const EMOTICON_BASE_URL: &str = "https://statics.teams.cdn.office.net/evergreen-assets/personal-expressions/v2/assets/emoticons";7
pub const BACKGROUND_CATALOG_URL: &str =8
"https://statics.teams.cdn.office.net/evergreen-assets/backgroundimages/config.json?v=7";9
10
#[cfg(test)]11
mod tests {12
use super::*;13
14
#[test]15
fn every_url_lives_on_the_cdn_root() {16
assert_eq!(ROOT, format!("https://{HOST}"));17
for url in [18
SOUND_BASE_URL,19
STICKER_BASE_URL,20
EMOTICON_BASE_URL,21
BACKGROUND_CATALOG_URL,22
] {23
assert!(24
url.starts_with(&format!("{ROOT}/evergreen-assets/")),25
"{url}"26
);27
}28
}29
}@@ -0,0 +1,123 @@
1
use std::fs;
2
use std::path::{Path, PathBuf};
3
4
const NON_GRAPH_HOSTS: &[&str] = &[
5
"cloud.microsoft",
6
"microsoft.com",
7
"office.com",
8
"office.net",
9
"skype.com",
10
"live.com",
11
"sharepoint.com",
12
"microsoftonline.com",
13
"microsoft365.com",
14
"giphy.com",
15
];
16
17
const NOT_A_SERVICE: &[&str] = &["graph.microsoft.com", "schema.skype.com"];
18
19
const ALLOWED_PATHS: &[(&str, &str)] = &[
20
("chatsvc/", "Teams service clients, one module per service"),
21
("calling/src/signaling.rs", "call signaling and flightproxy"),
22
("calling/src/relay.rs", "TURN relay tokens"),
23
("calling/src/meeting_options.rs", "meeting options MT"),
24
("calling/src/whiteboard.rs", "meeting whiteboard MT"),
25
("calling/src/breakout.rs", "breakout room join link parsing"),
26
("calling/assets/", "in-page caption bot command"),
27
(
28
"session/",
29
"sign-in, token refresh, page hosts, token audiences",
30
),
31
("browser/", "headless browser page targets"),
32
("webview/", "WebView2 page hosts"),
33
("app-base/src/task_dialog/sdk.rs", "task dialog host origin"),
34
("core/src/links.rs", "link classification"),
35
("core/src/meeting_join.rs", "meeting join link parsing"),
36
("core/src/message_link.rs", "message link parsing"),
37
("core/src/call_event.rs", "recording link host check"),
38
("core/src/external_image.rs", "GIF host check"),
39
("app-call-model/src/agenda.rs", "demo join link"),
40
("app-call-model/src/demo.rs", "demo data"),
41
("app-state/src/demo.rs", "demo data"),
42
("app-base/src/demo_", "demo data"),
43
("app/src/layout_guard.rs", "layout test fixture"),
44
("graph/src/tabs.rs", "channel tab web links"),
45
];
46
47
#[test]
48
fn non_graph_hosts_stay_in_their_service_modules() {
49
let crates_directory = Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
50
let mut files = Vec::new();
51
source_files(&crates_directory, &mut files);
52
let mut offenders = Vec::new();
53
for file in files {
54
let relative = file
55
.strip_prefix(&crates_directory)
56
.expect("file below crates")
57
.to_string_lossy()
58
.replace('\\', "/");
59
if ALLOWED_PATHS
60
.iter()
61
.any(|(prefix, _)| relative.starts_with(prefix))
62
{
63
continue;
64
}
65
let source = fs::read_to_string(&file).expect("read source file");
66
for (index, line) in production_lines(&source) {
67
if names_non_graph_host(line) {
68
offenders.push(format!("{relative}:{}: {}", index + 1, line.trim()));
69
}
70
}
71
}
72
assert!(
73
offenders.is_empty(),
74
"non-Graph hosts outside their service modules (move them or extend ALLOWED_PATHS and docs/research/internal-endpoints.md):\n{}",
75
offenders.join("\n")
76
);
77
}
78
79
fn source_files(directory: &Path, files: &mut Vec<PathBuf>) {
80
for entry in fs::read_dir(directory).expect("read source directory") {
81
let path = entry.expect("directory entry").path();
82
let name = path
83
.file_name()
84
.and_then(|name| name.to_str())
85
.unwrap_or("");
86
if path.is_dir() {
87
if !matches!(name, "tests" | "examples" | "target" | "benches") {
88
source_files(&path, files);
89
}
90
} else if (name.ends_with(".rs") || name.ends_with(".js")) && name != "tests.rs" {
91
files.push(path);
92
}
93
}
94
}
95
96
fn production_lines(source: &str) -> impl Iterator<Item = (usize, &str)> {
97
source
98
.lines()
99
.enumerate()
100
.take_while(|(_, line)| line.trim() != "#[cfg(test)]")
101
.filter(|(_, line)| !line.trim_start().starts_with("//"))
102
}
103
104
fn names_non_graph_host(line: &str) -> bool {
105
let mut cleaned = line.to_owned();
106
for host in NOT_A_SERVICE {
107
cleaned = cleaned.replace(host, "");
108
}
109
NON_GRAPH_HOSTS.iter().any(|host| cleaned.contains(host))
110
}
111
112
#[test]
113
fn host_check_ignores_graph_and_markup() {
114
assert!(!names_non_graph_host(
115
r#"const GRAPH: &str = "https://graph.microsoft.com";"#
116
));
117
assert!(!names_non_graph_host(
118
r#"itemtype="http://schema.skype.com/Mention""#
119
));
120
assert!(names_non_graph_host(
121
r#"format!("https://teams.cloud.microsoft/api/mt/{region}")"#
122
));
123
}
@@ -0,0 +1,123 @@1
use std::fs;2
use std::path::{Path, PathBuf};3
4
const NON_GRAPH_HOSTS: &[&str] = &[5
"cloud.microsoft",6
"microsoft.com",7
"office.com",8
"office.net",9
"skype.com",10
"live.com",11
"sharepoint.com",12
"microsoftonline.com",13
"microsoft365.com",14
"giphy.com",15
];16
17
const NOT_A_SERVICE: &[&str] = &["graph.microsoft.com", "schema.skype.com"];18
19
const ALLOWED_PATHS: &[(&str, &str)] = &[20
("chatsvc/", "Teams service clients, one module per service"),21
("calling/src/signaling.rs", "call signaling and flightproxy"),22
("calling/src/relay.rs", "TURN relay tokens"),23
("calling/src/meeting_options.rs", "meeting options MT"),24
("calling/src/whiteboard.rs", "meeting whiteboard MT"),25
("calling/src/breakout.rs", "breakout room join link parsing"),26
("calling/assets/", "in-page caption bot command"),27
(28
"session/",29
"sign-in, token refresh, page hosts, token audiences",30
),31
("browser/", "headless browser page targets"),32
("webview/", "WebView2 page hosts"),33
("app-base/src/task_dialog/sdk.rs", "task dialog host origin"),34
("core/src/links.rs", "link classification"),35
("core/src/meeting_join.rs", "meeting join link parsing"),36
("core/src/message_link.rs", "message link parsing"),37
("core/src/call_event.rs", "recording link host check"),38
("core/src/external_image.rs", "GIF host check"),39
("app-call-model/src/agenda.rs", "demo join link"),40
("app-call-model/src/demo.rs", "demo data"),41
("app-state/src/demo.rs", "demo data"),42
("app-base/src/demo_", "demo data"),43
("app/src/layout_guard.rs", "layout test fixture"),44
("graph/src/tabs.rs", "channel tab web links"),45
];46
47
#[test]48
fn non_graph_hosts_stay_in_their_service_modules() {49
let crates_directory = Path::new(env!("CARGO_MANIFEST_DIR")).join("..");50
let mut files = Vec::new();51
source_files(&crates_directory, &mut files);52
let mut offenders = Vec::new();53
for file in files {54
let relative = file55
.strip_prefix(&crates_directory)56
.expect("file below crates")57
.to_string_lossy()58
.replace('\\', "/");59
if ALLOWED_PATHS60
.iter()61
.any(|(prefix, _)| relative.starts_with(prefix))62
{63
continue;64
}65
let source = fs::read_to_string(&file).expect("read source file");66
for (index, line) in production_lines(&source) {67
if names_non_graph_host(line) {68
offenders.push(format!("{relative}:{}: {}", index + 1, line.trim()));69
}70
}71
}72
assert!(73
offenders.is_empty(),74
"non-Graph hosts outside their service modules (move them or extend ALLOWED_PATHS and docs/research/internal-endpoints.md):\n{}",75
offenders.join("\n")76
);77
}78
79
fn source_files(directory: &Path, files: &mut Vec<PathBuf>) {80
for entry in fs::read_dir(directory).expect("read source directory") {81
let path = entry.expect("directory entry").path();82
let name = path83
.file_name()84
.and_then(|name| name.to_str())85
.unwrap_or("");86
if path.is_dir() {87
if !matches!(name, "tests" | "examples" | "target" | "benches") {88
source_files(&path, files);89
}90
} else if (name.ends_with(".rs") || name.ends_with(".js")) && name != "tests.rs" {91
files.push(path);92
}93
}94
}95
96
fn production_lines(source: &str) -> impl Iterator<Item = (usize, &str)> {97
source98
.lines()99
.enumerate()100
.take_while(|(_, line)| line.trim() != "#[cfg(test)]")101
.filter(|(_, line)| !line.trim_start().starts_with("//"))102
}103
104
fn names_non_graph_host(line: &str) -> bool {105
let mut cleaned = line.to_owned();106
for host in NOT_A_SERVICE {107
cleaned = cleaned.replace(host, "");108
}109
NON_GRAPH_HOSTS.iter().any(|host| cleaned.contains(host))110
}111
112
#[test]113
fn host_check_ignores_graph_and_markup() {114
assert!(!names_non_graph_host(115
r#"const GRAPH: &str = "https://graph.microsoft.com";"#116
));117
assert!(!names_non_graph_host(118
r#"itemtype="http://schema.skype.com/Mention""#119
));120
assert!(names_non_graph_host(121
r#"format!("https://teams.cloud.microsoft/api/mt/{region}")"#122
));123
}@@ -6,8 +6,10 @@ use serde::{Deserialize, Serialize};
6
6
7
7
use crate::markdown::escape_html;
8
8
use crate::spans::{FontSize, Span};
9
use crate::table::{TABLE_MARK, Table, markdown_table};
9
10
10
11
pub const MAX_DEPTH: u8 = 2;
12
pub const MAX_HEADING: u8 = 3;
11
13
pub const OBJECT_MARK: char = '\u{FFFC}';
12
14
const BULLETS: [&str; 3] = ["•", "◦", "▪"];
13
15
const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "];
@@ -125,6 +127,8 @@ pub enum LineKind {
125
127
Numbered(u8),
126
128
Quote,
127
129
Code(Option<String>),
130
Heading(u8),
131
Table(Table),
128
132
}
129
133
130
134
impl LineKind {
@@ -132,6 +136,10 @@ impl LineKind {
132
136
matches!(self, LineKind::Bullet(_) | LineKind::Numbered(_))
133
137
}
134
138
139
pub fn is_table(&self) -> bool {
140
matches!(self, LineKind::Table(_))
141
}
142
135
143
pub fn depth(&self) -> u8 {
136
144
match self {
137
145
LineKind::Bullet(depth) | LineKind::Numbered(depth) => *depth,
@@ -430,7 +438,10 @@ impl Draft {
430
438
pub fn plain_text(&self) -> String {
431
439
self.slice(0..self.text.len())
432
440
.into_iter()
433
.map(|line| line.content)
441
.map(|line| match &line.kind {
442
LineKind::Table(table) => table.plain_text(),
443
_ => line.content,
444
})
434
445
.collect::<Vec<_>>()
435
446
.join("\n")
436
447
.replace(&format!(" {OBJECT_MARK} "), " ")
@@ -762,7 +773,11 @@ impl Draft {
762
773
self.splice(content.clone(), "", &[]);
763
774
Some(self.set_line_kind(index, LineKind::Code(language), None, content.start))
764
775
}
765
LineKind::Quote if !shift => None,
776
LineKind::Heading(_) | LineKind::Table(_) => None,
777
LineKind::Quote if content.is_empty() && !shift => {
778
self.lines[index] = LineKind::Text;
779
Some(cursor)
780
}
766
781
LineKind::Quote => {
767
782
self.splice(cursor..cursor, "\n", &[]);
768
783
self.lines[index] = LineKind::Quote;
@@ -823,6 +838,9 @@ impl Draft {
823
838
if cursor != line.end || index + 1 >= self.lines.len() {
824
839
return None;
825
840
}
841
if self.lines[index + 1].is_table() {
842
return Some(cursor);
843
}
826
844
let next_marker = self.marker_range(index + 1);
827
845
if next_marker.is_empty() {
828
846
return None;
@@ -847,11 +865,22 @@ impl Draft {
847
865
cursor
848
866
})
849
867
}
868
LineKind::Table(_) => None,
869
LineKind::Heading(_) => (cursor == line.start).then(|| {
870
self.lines[index] = LineKind::Text;
871
cursor
872
}),
850
873
LineKind::Quote
851
874
if cursor == line.start && (index == 0 || self.lines[index - 1] != kind) =>
852
875
{
853
self.lines[index] = LineKind::Text;
854
Some(cursor)
876
let joins_previous =
877
index > 0 && !content.is_empty() && !self.lines[index - 1].is_table();
878
if !joins_previous {
879
self.lines[index] = LineKind::Text;
880
return Some(cursor);
881
}
882
self.splice(line.start - 1..line.start, "", &[]);
883
Some(self.repair(line.start - 1))
855
884
}
856
885
_ if cursor == line.start && index > 0 => {
857
886
self.splice(line.start - 1..content.start, "", &[]);
@@ -899,6 +928,9 @@ impl Draft {
899
928
.all(|index| self.lines[index].same_format(&kind));
900
929
for index in lines {
901
930
let current = self.lines[index].clone();
931
if current.is_table() {
932
continue;
933
}
902
934
let target = if all {
903
935
LineKind::Text
904
936
} else if current.same_format(&kind) {
@@ -915,6 +947,120 @@ impl Draft {
915
947
self.repair(0);
916
948
}
917
949
950
pub fn table(&self, index: usize) -> Option<&Table> {
951
match self.lines.get(index)? {
952
LineKind::Table(table) => Some(table),
953
_ => None,
954
}
955
}
956
957
/// Cell edits change no text, so the journal stays as it is.
958
pub fn set_table(&mut self, index: usize, table: Table) {
959
if let Some(kind @ LineKind::Table(_)) = self.lines.get_mut(index) {
960
*kind = LineKind::Table(table);
961
}
962
}
963
964
/// The table goes in place of an empty text line, otherwise below the cursor's line, and
965
/// a text line follows it. Returns the table's line.
966
pub fn insert_table(&mut self, cursor: usize, table: Table) -> usize {
967
self.journal = Journal::default();
968
let index = self.line_at(cursor);
969
let line = self.line_ranges()[index].clone();
970
let mark = TABLE_MARK.to_string();
971
let replaces_line = self.lines[index] == LineKind::Text && line.is_empty();
972
let table_index = if replaces_line {
973
self.splice(line, &mark, &[]);
974
index
975
} else {
976
self.splice(line.end..line.end, &format!("\n{mark}"), &[]);
977
index + 1
978
};
979
self.lines[table_index] = LineKind::Table(table);
980
if table_index + 1 == self.lines.len() {
981
let end = self.text.len();
982
self.splice(end..end, "\n", &[]);
983
self.lines[table_index + 1] = LineKind::Text;
984
}
985
table_index
986
}
987
988
/// Returns where the cursor goes: the start of the line that took the table's place.
989
pub fn remove_table(&mut self, index: usize) -> usize {
990
self.journal = Journal::default();
991
let ranges = self.line_ranges();
992
let line = ranges[index].clone();
993
if let Some(next) = ranges.get(index + 1) {
994
let next_kind = self.lines[index + 1].clone();
995
self.splice(line.start..next.start, "", &[]);
996
self.lines[index] = next_kind;
997
return self.repair(line.start);
998
}
999
if index > 0 {
1000
let start = ranges[index - 1].end;
1001
self.splice(start..line.end, "", &[]);
1002
return self.repair(start);
1003
}
1004
self.splice(line, "", &[]);
1005
self.lines[index] = LineKind::Text;
1006
0
1007
}
1008
1009
/// Where the cursor lands when it leaves table `index` downwards or upwards; a text line
1010
/// is added when the table is the last or the first line.
1011
pub fn line_beside_table(&mut self, index: usize, below: bool) -> usize {
1012
self.journal = Journal::default();
1013
let ranges = self.line_ranges();
1014
if below {
1015
if let Some(next) = ranges.get(index + 1) {
1016
return next.start;
1017
}
1018
let end = self.text.len();
1019
self.splice(end..end, "\n", &[]);
1020
self.lines[index + 1] = LineKind::Text;
1021
return end + 1;
1022
}
1023
if index > 0 {
1024
return ranges[index - 1].end;
1025
}
1026
self.splice(0..0, "\n", &[]);
1027
self.lines[0] = LineKind::Text;
1028
0
1029
}
1030
1031
pub fn table_at(&self, offset: usize) -> Option<usize> {
1032
let index = self.line_at(offset);
1033
self.lines[index].is_table().then_some(index)
1034
}
1035
1036
/// The table right above, when `cursor` is at the start of its line.
1037
pub fn table_before(&self, cursor: usize) -> Option<usize> {
1038
let index = self.line_at(cursor);
1039
let at_start = self.line_ranges()[index].start == cursor;
1040
(at_start && index > 0 && self.lines[index - 1].is_table()).then(|| index - 1)
1041
}
1042
1043
/// The table right below, when `cursor` is at the end of its line.
1044
pub fn table_after(&self, cursor: usize) -> Option<usize> {
1045
let index = self.line_at(cursor);
1046
let at_end = self.line_ranges()[index].end == cursor;
1047
(at_end && self.lines.get(index + 1).is_some_and(LineKind::is_table)).then_some(index + 1)
1048
}
1049
1050
/// Down or Right at the very end of a quote that ends the draft: a text line below it,
1051
/// like the empty paragraph Teams keeps after a quote.
1052
pub fn leave_quote_at_end(&mut self, cursor: usize) -> Option<usize> {
1053
self.journal = Journal::default();
1054
let end = self.text.len();
1055
let last = self.lines.len() - 1;
1056
if cursor != end || self.lines[last] != LineKind::Quote {
1057
return None;
1058
}
1059
self.splice(end..end, "\n", &[]);
1060
self.lines[last + 1] = LineKind::Text;
1061
Some(end + 1)
1062
}
1063
918
1064
pub fn slice(&self, range: Range<usize>) -> Vec<DraftLine> {
919
1065
let mut lines = Vec::new();
920
1066
for (index, line) in self.line_ranges().into_iter().enumerate() {
@@ -981,6 +1127,13 @@ impl Draft {
981
1127
let line_was_empty = self.lines[index] == LineKind::Text
982
1128
&& range.start == content.start
983
1129
&& range.end >= tail_end;
1130
let separated;
1131
let lines = if !line_was_empty && lines.first().is_some_and(|line| line.kind.is_table()) {
1132
separated = [&[DraftLine::text("")][..], lines].concat();
1133
&separated[..]
1134
} else {
1135
lines
1136
};
984
1137
let joined = lines
985
1138
.iter()
986
1139
.map(|line| line.content.as_str())
@@ -1057,6 +1210,23 @@ impl Draft {
1057
1210
html.push_str(&joined_inline(run));
1058
1211
html.push_str("</blockquote>");
1059
1212
}
1213
LineKind::Heading(_) => {
1214
for line in run {
1215
let level = match line.kind {
1216
LineKind::Heading(level) => level.clamp(1, MAX_HEADING),
1217
_ => 1,
1218
};
1219
let inline = inline_html(&line.content, &line.marks);
1220
html.push_str(&format!("<h{level}>{inline}</h{level}>"));
1221
}
1222
}
1223
LineKind::Table(_) => {
1224
for line in run {
1225
if let LineKind::Table(table) = &line.kind {
1226
html.push_str(&table.to_html());
1227
}
1228
}
1229
}
1060
1230
LineKind::Code(language) => {
1061
1231
match language {
1062
1232
Some(language) => html.push_str(&format!(
@@ -1362,8 +1532,45 @@ impl Draft {
1362
1532
}
1363
1533
}
1364
1534
1535
/// A table line holds its mark alone: text typed next to it moves to its own line, a mark
1536
/// without its table is dropped and a table without its mark becomes text.
1537
fn repair_tables(&mut self, mut cursor: usize) -> usize {
1538
let mark_length = TABLE_MARK.len_utf8();
1539
let mut index = 0;
1540
while index < self.lines.len() {
1541
let line = self.line_ranges()[index].clone();
1542
let found = self.text[line.clone()].find(TABLE_MARK);
1543
match (self.lines[index].clone(), found) {
1544
(LineKind::Table(_), None) => self.lines[index] = LineKind::Text,
1545
(LineKind::Table(table), Some(at)) if at > 0 => {
1546
let split = line.start + at;
1547
self.splice(split..split, "\n", &[]);
1548
self.lines[index] = LineKind::Text;
1549
self.lines[index + 1] = LineKind::Table(table);
1550
cursor += usize::from(cursor > split);
1551
}
1552
(LineKind::Table(_), Some(_)) if line.len() > mark_length => {
1553
let split = line.start + mark_length;
1554
self.splice(split..split, "\n", &[]);
1555
cursor += usize::from(cursor > split);
1556
}
1557
(LineKind::Table(_), Some(_)) => {}
1558
(_, Some(at)) => {
1559
let mark = line.start + at..line.start + at + mark_length;
1560
self.splice(mark.clone(), "", &[]);
1561
cursor = map_offset(&[(mark, String::new())], cursor);
1562
continue;
1563
}
1564
(_, None) => {}
1565
}
1566
index += 1;
1567
}
1568
cursor
1569
}
1570
1365
1571
/// List items whose marker was edited away become text; numbered items are renumbered.
1366
fn repair(&mut self, mut cursor: usize) -> usize {
1572
fn repair(&mut self, cursor: usize) -> usize {
1573
let mut cursor = self.repair_tables(cursor);
1367
1574
for index in 0..self.lines.len() {
1368
1575
let kind = self.lines[index].clone();
1369
1576
if !kind.is_list() {
@@ -1399,7 +1606,11 @@ fn marker_text(kind: &LineKind, number: u32) -> String {
1399
1606
match kind {
1400
1607
LineKind::Bullet(depth) => bullet_marker(*depth),
1401
1608
LineKind::Numbered(_) => format!("{number}. "),
1402
LineKind::Text | LineKind::Quote | LineKind::Code(_) => String::new(),
1609
LineKind::Text
1610
| LineKind::Quote
1611
| LineKind::Code(_)
1612
| LineKind::Heading(_)
1613
| LineKind::Table(_) => String::new(),
1403
1614
}
1404
1615
}
1405
1616
@@ -1430,7 +1641,9 @@ fn numbered_marker(line: &str) -> Option<(usize, u32)> {
1430
1641
fn line_shortcut(before: &str) -> Option<(LineKind, u32)> {
1431
1642
match before {
1432
1643
"- " | "* " => Some((LineKind::Bullet(0), 1)),
1433
"> " => Some((LineKind::Quote, 1)),
1644
">" => Some((LineKind::Quote, 1)),
1645
_ if before.starts_with('#') => heading_prefix(before)
1646
.and_then(|(level, rest)| rest.is_empty().then_some((LineKind::Heading(level), 1))),
1434
1647
_ => {
1435
1648
let digits = before.strip_suffix(". ")?;
1436
1649
let all_digits = !digits.is_empty()
@@ -1540,7 +1753,7 @@ fn typed_inline(before: &str) -> Option<(Range<usize>, Range<usize>, MarkKind)>
1540
1753
let usable = !body[open + 1..].trim().is_empty() && !body[..open].ends_with('`');
1541
1754
return usable.then(|| (open..open + 1, body.len()..end, MarkKind::Code));
1542
1755
}
1543
for marker in ['*', '_'] {
1756
for (marker, kind) in [('*', MarkKind::Bold), ('_', MarkKind::Italic)] {
1544
1757
if let Some(body) = before.strip_suffix(marker) {
1545
1758
if body.ends_with(marker) {
1546
1759
return None;
@@ -1548,7 +1761,7 @@ fn typed_inline(before: &str) -> Option<(Range<usize>, Range<usize>, MarkKind)>
1548
1761
let open = body.rfind(marker)?;
1549
1762
let opening_ok = !word_before(&body[..open]) && !body[..open].ends_with(marker);
1550
1763
return (opening_ok && valid_inner(&body[open + 1..]))
1551
.then(|| (open..open + 1, body.len()..end, MarkKind::Italic));
1764
.then(|| (open..open + 1, body.len()..end, kind));
1552
1765
}
1553
1766
}
1554
1767
None
@@ -1702,10 +1915,16 @@ pub fn has_markdown(text: &str) -> bool {
1702
1915
}
1703
1916
1704
1917
fn markdown_lines(text: &str) -> Vec<DraftLine> {
1918
let sources: Vec<&str> = text
1919
.split('\n')
1920
.map(|raw| raw.strip_suffix('\r').unwrap_or(raw))
1921
.collect();
1705
1922
let mut lines = Vec::new();
1706
1923
let mut code: Option<Option<String>> = None;
1707
for raw in text.split('\n') {
1708
let raw = raw.strip_suffix('\r').unwrap_or(raw);
1924
let mut position = 0;
1925
while position < sources.len() {
1926
let raw = sources[position];
1927
position += 1;
1709
1928
let trimmed = raw.trim_start();
1710
1929
if let Some(language) = &code {
1711
1930
if trimmed.starts_with(FENCE) && trimmed.trim_end() == FENCE {
@@ -1727,12 +1946,23 @@ fn markdown_lines(text: &str) -> Vec<DraftLine> {
1727
1946
code = Some(language);
1728
1947
continue;
1729
1948
}
1949
if let Some((rows, consumed)) = markdown_table(&sources[position - 1..]) {
1950
let rows = rows
1951
.into_iter()
1952
.map(|row| row.iter().map(|cell| parse_inline(cell).0).collect())
1953
.collect();
1954
lines.push(table_line(Table::from_rows(rows)));
1955
position += consumed - 1;
1956
continue;
1957
}
1730
1958
let indent: usize = raw[..raw.len() - trimmed.len()]
1731
1959
.chars()
1732
1960
.map(|character| if character == '\t' { 4 } else { 1 })
1733
1961
.sum();
1734
1962
let depth = ((indent / MARKDOWN_INDENT) as u8).min(MAX_DEPTH);
1735
let (kind, number, content) = if let Some(rest) = PASTED_BULLETS
1963
let (kind, number, content) = if let Some((level, rest)) = heading_prefix(trimmed) {
1964
(LineKind::Heading(level), None, rest)
1965
} else if let Some(rest) = PASTED_BULLETS
1736
1966
.iter()
1737
1967
.find_map(|bullet| trimmed.strip_prefix(bullet))
1738
1968
{
@@ -1758,6 +1988,24 @@ fn markdown_lines(text: &str) -> Vec<DraftLine> {
1758
1988
lines
1759
1989
}
1760
1990
1991
fn table_line(table: Table) -> DraftLine {
1992
DraftLine {
1993
kind: LineKind::Table(table),
1994
number: None,
1995
content: TABLE_MARK.to_string(),
1996
marks: Vec::new(),
1997
}
1998
}
1999
2000
/// `# ` to `###### `: the level, capped at the three Teams offers, and the rest of the line.
2001
fn heading_prefix(line: &str) -> Option<(u8, &str)> {
2002
let hashes = line.bytes().take_while(|byte| *byte == b'#').count();
2003
let rest = line[hashes..].strip_prefix(' ')?;
2004
(1..=6)
2005
.contains(&hashes)
2006
.then(|| ((hashes as u8).min(MAX_HEADING), rest))
2007
}
2008
1761
2009
fn parse_inline(source: &str) -> (String, Vec<Mark>) {
1762
2010
let mut text = String::with_capacity(source.len());
1763
2011
let mut marks = Vec::new();
@@ -1849,6 +2097,17 @@ fn inline_at(rest: &str, previous: Option<char>) -> Option<(&str, usize, MarkKin
1849
2097
None
1850
2098
}
1851
2099
2100
fn cell_text(spans: &[Span]) -> String {
2101
let mut builder = SpanLines::default();
2102
builder.walk(spans, &LineKind::Text, &[]);
2103
builder
2104
.finish()
2105
.into_iter()
2106
.map(|line| line.content)
2107
.collect::<Vec<_>>()
2108
.join("\n")
2109
}
2110
1852
2111
#[derive(Default)]
1853
2112
struct SpanLines {
1854
2113
lines: Vec<DraftLine>,
@@ -1936,9 +2195,10 @@ impl SpanLines {
1936
2195
};
1937
2196
self.start_line(&continued, None);
1938
2197
}
1939
Span::Heading { children, .. } => {
1940
self.start_line(&LineKind::Text, None);
1941
self.walk(children, &LineKind::Text, &with(MarkKind::Bold));
2198
Span::Heading { level, children } => {
2199
let heading = LineKind::Heading((*level).clamp(1, MAX_HEADING));
2200
self.start_line(&heading, None);
2201
self.walk(children, &heading, marks);
1942
2202
self.open = false;
1943
2203
}
1944
2204
Span::CodeBlock { language, code } => {
@@ -1977,15 +2237,11 @@ impl SpanLines {
1977
2237
self.open = false;
1978
2238
}
1979
2239
Span::Table { rows, .. } => {
1980
for row in rows {
1981
self.start_line(&LineKind::Text, None);
1982
for (position, cell) in row.iter().enumerate() {
1983
if position > 0 {
1984
self.append(" | ", &LineKind::Text, &[]);
1985
}
1986
self.walk(cell, &LineKind::Text, marks);
1987
}
1988
}
2240
let rows = rows
2241
.iter()
2242
.map(|row| row.iter().map(|cell| cell_text(cell)).collect())
2243
.collect();
2244
self.lines.push(table_line(Table::from_rows(rows)));
1989
2245
self.open = false;
1990
2246
}
1991
2247
Span::Image { .. } | Span::Quote { .. } => {}
@@ -2081,7 +2337,7 @@ mod tests {
2081
2337
draft.marks(),
2082
2338
[
2083
2339
mark(2..6, MarkKind::Bold),
2084
mark(11..13, MarkKind::Italic),
2340
mark(11..13, MarkKind::Bold),
2085
2341
mark(17..19, MarkKind::Italic),
2086
2342
mark(20..24, MarkKind::Strike),
2087
2343
mark(25..29, MarkKind::Code),
@@ -2357,9 +2613,12 @@ mod tests {
2357
2613
let numbered = typed_draft("1. one");
2358
2614
assert_eq!(numbered.text(), "1. one");
2359
2615
assert_eq!(numbered.lines(), [LineKind::Numbered(0)]);
2360
let quote = typed_draft("> said");
2616
let quote = typed_draft(">said");
2361
2617
assert_eq!(quote.text(), "said");
2362
2618
assert_eq!(quote.lines(), [LineKind::Quote]);
2619
let spaced = typed_draft("> said");
2620
assert_eq!(spaced.text(), " said");
2621
assert_eq!(spaced.lines(), [LineKind::Quote]);
2363
2622
}
2364
2623
2365
2624
#[test]
@@ -6,8 +6,10 @@ use serde::{Deserialize, Serialize};6
6
7
use crate::markdown::escape_html;7
use crate::markdown::escape_html;8
use crate::spans::{FontSize, Span};8
use crate::spans::{FontSize, Span};9
use crate::table::{TABLE_MARK, Table, markdown_table};9
10
10
pub const MAX_DEPTH: u8 = 2;11
pub const MAX_DEPTH: u8 = 2;12
pub const MAX_HEADING: u8 = 3;11
pub const OBJECT_MARK: char = '\u{FFFC}';13
pub const OBJECT_MARK: char = '\u{FFFC}';12
const BULLETS: [&str; 3] = ["•", "◦", "▪"];14
const BULLETS: [&str; 3] = ["•", "◦", "▪"];13
const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "];15
const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "];@@ -125,6 +127,8 @@ pub enum LineKind {125
Numbered(u8),127
Numbered(u8),126
Quote,128
Quote,127
Code(Option<String>),129
Code(Option<String>),130
Heading(u8),131
Table(Table),128
}132
}129
133
130
impl LineKind {134
impl LineKind {@@ -132,6 +136,10 @@ impl LineKind {132
matches!(self, LineKind::Bullet(_) | LineKind::Numbered(_))136
matches!(self, LineKind::Bullet(_) | LineKind::Numbered(_))133
}137
}134
138
139
pub fn is_table(&self) -> bool {140
matches!(self, LineKind::Table(_))141
}142
135
pub fn depth(&self) -> u8 {143
pub fn depth(&self) -> u8 {136
match self {144
match self {137
LineKind::Bullet(depth) | LineKind::Numbered(depth) => *depth,145
LineKind::Bullet(depth) | LineKind::Numbered(depth) => *depth,@@ -430,7 +438,10 @@ impl Draft {430
pub fn plain_text(&self) -> String {438
pub fn plain_text(&self) -> String {431
self.slice(0..self.text.len())439
self.slice(0..self.text.len())432
.into_iter()440
.into_iter()433
.map(|line| line.content)441
.map(|line| match &line.kind {442
LineKind::Table(table) => table.plain_text(),443
_ => line.content,444
})434
.collect::<Vec<_>>()445
.collect::<Vec<_>>()435
.join("\n")446
.join("\n")436
.replace(&format!(" {OBJECT_MARK} "), " ")447
.replace(&format!(" {OBJECT_MARK} "), " ")@@ -762,7 +773,11 @@ impl Draft {762
self.splice(content.clone(), "", &[]);773
self.splice(content.clone(), "", &[]);763
Some(self.set_line_kind(index, LineKind::Code(language), None, content.start))774
Some(self.set_line_kind(index, LineKind::Code(language), None, content.start))764
}775
}765
LineKind::Quote if !shift => None,776
LineKind::Heading(_) | LineKind::Table(_) => None,777
LineKind::Quote if content.is_empty() && !shift => {778
self.lines[index] = LineKind::Text;779
Some(cursor)780
}766
LineKind::Quote => {781
LineKind::Quote => {767
self.splice(cursor..cursor, "\n", &[]);782
self.splice(cursor..cursor, "\n", &[]);768
self.lines[index] = LineKind::Quote;783
self.lines[index] = LineKind::Quote;@@ -823,6 +838,9 @@ impl Draft {823
if cursor != line.end || index + 1 >= self.lines.len() {838
if cursor != line.end || index + 1 >= self.lines.len() {824
return None;839
return None;825
}840
}841
if self.lines[index + 1].is_table() {842
return Some(cursor);843
}826
let next_marker = self.marker_range(index + 1);844
let next_marker = self.marker_range(index + 1);827
if next_marker.is_empty() {845
if next_marker.is_empty() {828
return None;846
return None;@@ -847,11 +865,22 @@ impl Draft {847
cursor865
cursor848
})866
})849
}867
}868
LineKind::Table(_) => None,869
LineKind::Heading(_) => (cursor == line.start).then(|| {870
self.lines[index] = LineKind::Text;871
cursor872
}),850
LineKind::Quote873
LineKind::Quote851
if cursor == line.start && (index == 0 || self.lines[index - 1] != kind) =>874
if cursor == line.start && (index == 0 || self.lines[index - 1] != kind) =>852
{875
{853
self.lines[index] = LineKind::Text;876
let joins_previous =854
Some(cursor)877
index > 0 && !content.is_empty() && !self.lines[index - 1].is_table();878
if !joins_previous {879
self.lines[index] = LineKind::Text;880
return Some(cursor);881
}882
self.splice(line.start - 1..line.start, "", &[]);883
Some(self.repair(line.start - 1))855
}884
}856
_ if cursor == line.start && index > 0 => {885
_ if cursor == line.start && index > 0 => {857
self.splice(line.start - 1..content.start, "", &[]);886
self.splice(line.start - 1..content.start, "", &[]);@@ -899,6 +928,9 @@ impl Draft {899
.all(|index| self.lines[index].same_format(&kind));928
.all(|index| self.lines[index].same_format(&kind));900
for index in lines {929
for index in lines {901
let current = self.lines[index].clone();930
let current = self.lines[index].clone();931
if current.is_table() {932
continue;933
}902
let target = if all {934
let target = if all {903
LineKind::Text935
LineKind::Text904
} else if current.same_format(&kind) {936
} else if current.same_format(&kind) {@@ -915,6 +947,120 @@ impl Draft {915
self.repair(0);947
self.repair(0);916
}948
}917
949
950
pub fn table(&self, index: usize) -> Option<&Table> {951
match self.lines.get(index)? {952
LineKind::Table(table) => Some(table),953
_ => None,954
}955
}956
957
/// Cell edits change no text, so the journal stays as it is.958
pub fn set_table(&mut self, index: usize, table: Table) {959
if let Some(kind @ LineKind::Table(_)) = self.lines.get_mut(index) {960
*kind = LineKind::Table(table);961
}962
}963
964
/// The table goes in place of an empty text line, otherwise below the cursor's line, and965
/// a text line follows it. Returns the table's line.966
pub fn insert_table(&mut self, cursor: usize, table: Table) -> usize {967
self.journal = Journal::default();968
let index = self.line_at(cursor);969
let line = self.line_ranges()[index].clone();970
let mark = TABLE_MARK.to_string();971
let replaces_line = self.lines[index] == LineKind::Text && line.is_empty();972
let table_index = if replaces_line {973
self.splice(line, &mark, &[]);974
index975
} else {976
self.splice(line.end..line.end, &format!("\n{mark}"), &[]);977
index + 1978
};979
self.lines[table_index] = LineKind::Table(table);980
if table_index + 1 == self.lines.len() {981
let end = self.text.len();982
self.splice(end..end, "\n", &[]);983
self.lines[table_index + 1] = LineKind::Text;984
}985
table_index986
}987
988
/// Returns where the cursor goes: the start of the line that took the table's place.989
pub fn remove_table(&mut self, index: usize) -> usize {990
self.journal = Journal::default();991
let ranges = self.line_ranges();992
let line = ranges[index].clone();993
if let Some(next) = ranges.get(index + 1) {994
let next_kind = self.lines[index + 1].clone();995
self.splice(line.start..next.start, "", &[]);996
self.lines[index] = next_kind;997
return self.repair(line.start);998
}999
if index > 0 {1000
let start = ranges[index - 1].end;1001
self.splice(start..line.end, "", &[]);1002
return self.repair(start);1003
}1004
self.splice(line, "", &[]);1005
self.lines[index] = LineKind::Text;1006
01007
}1008
1009
/// Where the cursor lands when it leaves table `index` downwards or upwards; a text line1010
/// is added when the table is the last or the first line.1011
pub fn line_beside_table(&mut self, index: usize, below: bool) -> usize {1012
self.journal = Journal::default();1013
let ranges = self.line_ranges();1014
if below {1015
if let Some(next) = ranges.get(index + 1) {1016
return next.start;1017
}1018
let end = self.text.len();1019
self.splice(end..end, "\n", &[]);1020
self.lines[index + 1] = LineKind::Text;1021
return end + 1;1022
}1023
if index > 0 {1024
return ranges[index - 1].end;1025
}1026
self.splice(0..0, "\n", &[]);1027
self.lines[0] = LineKind::Text;1028
01029
}1030
1031
pub fn table_at(&self, offset: usize) -> Option<usize> {1032
let index = self.line_at(offset);1033
self.lines[index].is_table().then_some(index)1034
}1035
1036
/// The table right above, when `cursor` is at the start of its line.1037
pub fn table_before(&self, cursor: usize) -> Option<usize> {1038
let index = self.line_at(cursor);1039
let at_start = self.line_ranges()[index].start == cursor;1040
(at_start && index > 0 && self.lines[index - 1].is_table()).then(|| index - 1)1041
}1042
1043
/// The table right below, when `cursor` is at the end of its line.1044
pub fn table_after(&self, cursor: usize) -> Option<usize> {1045
let index = self.line_at(cursor);1046
let at_end = self.line_ranges()[index].end == cursor;1047
(at_end && self.lines.get(index + 1).is_some_and(LineKind::is_table)).then_some(index + 1)1048
}1049
1050
/// Down or Right at the very end of a quote that ends the draft: a text line below it,1051
/// like the empty paragraph Teams keeps after a quote.1052
pub fn leave_quote_at_end(&mut self, cursor: usize) -> Option<usize> {1053
self.journal = Journal::default();1054
let end = self.text.len();1055
let last = self.lines.len() - 1;1056
if cursor != end || self.lines[last] != LineKind::Quote {1057
return None;1058
}1059
self.splice(end..end, "\n", &[]);1060
self.lines[last + 1] = LineKind::Text;1061
Some(end + 1)1062
}1063
918
pub fn slice(&self, range: Range<usize>) -> Vec<DraftLine> {1064
pub fn slice(&self, range: Range<usize>) -> Vec<DraftLine> {919
let mut lines = Vec::new();1065
let mut lines = Vec::new();920
for (index, line) in self.line_ranges().into_iter().enumerate() {1066
for (index, line) in self.line_ranges().into_iter().enumerate() {@@ -981,6 +1127,13 @@ impl Draft {981
let line_was_empty = self.lines[index] == LineKind::Text1127
let line_was_empty = self.lines[index] == LineKind::Text982
&& range.start == content.start1128
&& range.start == content.start983
&& range.end >= tail_end;1129
&& range.end >= tail_end;1130
let separated;1131
let lines = if !line_was_empty && lines.first().is_some_and(|line| line.kind.is_table()) {1132
separated = [&[DraftLine::text("")][..], lines].concat();1133
&separated[..]1134
} else {1135
lines1136
};984
let joined = lines1137
let joined = lines985
.iter()1138
.iter()986
.map(|line| line.content.as_str())1139
.map(|line| line.content.as_str())@@ -1057,6 +1210,23 @@ impl Draft {1057
html.push_str(&joined_inline(run));1210
html.push_str(&joined_inline(run));1058
html.push_str("</blockquote>");1211
html.push_str("</blockquote>");1059
}1212
}1213
LineKind::Heading(_) => {1214
for line in run {1215
let level = match line.kind {1216
LineKind::Heading(level) => level.clamp(1, MAX_HEADING),1217
_ => 1,1218
};1219
let inline = inline_html(&line.content, &line.marks);1220
html.push_str(&format!("<h{level}>{inline}</h{level}>"));1221
}1222
}1223
LineKind::Table(_) => {1224
for line in run {1225
if let LineKind::Table(table) = &line.kind {1226
html.push_str(&table.to_html());1227
}1228
}1229
}1060
LineKind::Code(language) => {1230
LineKind::Code(language) => {1061
match language {1231
match language {1062
Some(language) => html.push_str(&format!(1232
Some(language) => html.push_str(&format!(@@ -1362,8 +1532,45 @@ impl Draft {1362
}1532
}1363
}1533
}1364
1534
1535
/// A table line holds its mark alone: text typed next to it moves to its own line, a mark1536
/// without its table is dropped and a table without its mark becomes text.1537
fn repair_tables(&mut self, mut cursor: usize) -> usize {1538
let mark_length = TABLE_MARK.len_utf8();1539
let mut index = 0;1540
while index < self.lines.len() {1541
let line = self.line_ranges()[index].clone();1542
let found = self.text[line.clone()].find(TABLE_MARK);1543
match (self.lines[index].clone(), found) {1544
(LineKind::Table(_), None) => self.lines[index] = LineKind::Text,1545
(LineKind::Table(table), Some(at)) if at > 0 => {1546
let split = line.start + at;1547
self.splice(split..split, "\n", &[]);1548
self.lines[index] = LineKind::Text;1549
self.lines[index + 1] = LineKind::Table(table);1550
cursor += usize::from(cursor > split);1551
}1552
(LineKind::Table(_), Some(_)) if line.len() > mark_length => {1553
let split = line.start + mark_length;1554
self.splice(split..split, "\n", &[]);1555
cursor += usize::from(cursor > split);1556
}1557
(LineKind::Table(_), Some(_)) => {}1558
(_, Some(at)) => {1559
let mark = line.start + at..line.start + at + mark_length;1560
self.splice(mark.clone(), "", &[]);1561
cursor = map_offset(&[(mark, String::new())], cursor);1562
continue;1563
}1564
(_, None) => {}1565
}1566
index += 1;1567
}1568
cursor1569
}1570
1365
/// List items whose marker was edited away become text; numbered items are renumbered.1571
/// List items whose marker was edited away become text; numbered items are renumbered.1366
fn repair(&mut self, mut cursor: usize) -> usize {1572
fn repair(&mut self, cursor: usize) -> usize {1573
let mut cursor = self.repair_tables(cursor);1367
for index in 0..self.lines.len() {1574
for index in 0..self.lines.len() {1368
let kind = self.lines[index].clone();1575
let kind = self.lines[index].clone();1369
if !kind.is_list() {1576
if !kind.is_list() {@@ -1399,7 +1606,11 @@ fn marker_text(kind: &LineKind, number: u32) -> String {1399
match kind {1606
match kind {1400
LineKind::Bullet(depth) => bullet_marker(*depth),1607
LineKind::Bullet(depth) => bullet_marker(*depth),1401
LineKind::Numbered(_) => format!("{number}. "),1608
LineKind::Numbered(_) => format!("{number}. "),1402
LineKind::Text | LineKind::Quote | LineKind::Code(_) => String::new(),1609
LineKind::Text1610
| LineKind::Quote1611
| LineKind::Code(_)1612
| LineKind::Heading(_)1613
| LineKind::Table(_) => String::new(),1403
}1614
}1404
}1615
}1405
1616
@@ -1430,7 +1641,9 @@ fn numbered_marker(line: &str) -> Option<(usize, u32)> {1430
fn line_shortcut(before: &str) -> Option<(LineKind, u32)> {1641
fn line_shortcut(before: &str) -> Option<(LineKind, u32)> {1431
match before {1642
match before {1432
"- " | "* " => Some((LineKind::Bullet(0), 1)),1643
"- " | "* " => Some((LineKind::Bullet(0), 1)),1433
"> " => Some((LineKind::Quote, 1)),1644
">" => Some((LineKind::Quote, 1)),1645
_ if before.starts_with('#') => heading_prefix(before)1646
.and_then(|(level, rest)| rest.is_empty().then_some((LineKind::Heading(level), 1))),1434
_ => {1647
_ => {1435
let digits = before.strip_suffix(". ")?;1648
let digits = before.strip_suffix(". ")?;1436
let all_digits = !digits.is_empty()1649
let all_digits = !digits.is_empty()@@ -1540,7 +1753,7 @@ fn typed_inline(before: &str) -> Option<(Range<usize>, Range<usize>, MarkKind)>1540
let usable = !body[open + 1..].trim().is_empty() && !body[..open].ends_with('`');1753
let usable = !body[open + 1..].trim().is_empty() && !body[..open].ends_with('`');1541
return usable.then(|| (open..open + 1, body.len()..end, MarkKind::Code));1754
return usable.then(|| (open..open + 1, body.len()..end, MarkKind::Code));1542
}1755
}1543
for marker in ['*', '_'] {1756
for (marker, kind) in [('*', MarkKind::Bold), ('_', MarkKind::Italic)] {1544
if let Some(body) = before.strip_suffix(marker) {1757
if let Some(body) = before.strip_suffix(marker) {1545
if body.ends_with(marker) {1758
if body.ends_with(marker) {1546
return None;1759
return None;@@ -1548,7 +1761,7 @@ fn typed_inline(before: &str) -> Option<(Range<usize>, Range<usize>, MarkKind)>1548
let open = body.rfind(marker)?;1761
let open = body.rfind(marker)?;1549
let opening_ok = !word_before(&body[..open]) && !body[..open].ends_with(marker);1762
let opening_ok = !word_before(&body[..open]) && !body[..open].ends_with(marker);1550
return (opening_ok && valid_inner(&body[open + 1..]))1763
return (opening_ok && valid_inner(&body[open + 1..]))1551
.then(|| (open..open + 1, body.len()..end, MarkKind::Italic));1764
.then(|| (open..open + 1, body.len()..end, kind));1552
}1765
}1553
}1766
}1554
None1767
None@@ -1702,10 +1915,16 @@ pub fn has_markdown(text: &str) -> bool {1702
}1915
}1703
1916
1704
fn markdown_lines(text: &str) -> Vec<DraftLine> {1917
fn markdown_lines(text: &str) -> Vec<DraftLine> {1918
let sources: Vec<&str> = text1919
.split('\n')1920
.map(|raw| raw.strip_suffix('\r').unwrap_or(raw))1921
.collect();1705
let mut lines = Vec::new();1922
let mut lines = Vec::new();1706
let mut code: Option<Option<String>> = None;1923
let mut code: Option<Option<String>> = None;1707
for raw in text.split('\n') {1924
let mut position = 0;1708
let raw = raw.strip_suffix('\r').unwrap_or(raw);1925
while position < sources.len() {1926
let raw = sources[position];1927
position += 1;1709
let trimmed = raw.trim_start();1928
let trimmed = raw.trim_start();1710
if let Some(language) = &code {1929
if let Some(language) = &code {1711
if trimmed.starts_with(FENCE) && trimmed.trim_end() == FENCE {1930
if trimmed.starts_with(FENCE) && trimmed.trim_end() == FENCE {@@ -1727,12 +1946,23 @@ fn markdown_lines(text: &str) -> Vec<DraftLine> {1727
code = Some(language);1946
code = Some(language);1728
continue;1947
continue;1729
}1948
}1949
if let Some((rows, consumed)) = markdown_table(&sources[position - 1..]) {1950
let rows = rows1951
.into_iter()1952
.map(|row| row.iter().map(|cell| parse_inline(cell).0).collect())1953
.collect();1954
lines.push(table_line(Table::from_rows(rows)));1955
position += consumed - 1;1956
continue;1957
}1730
let indent: usize = raw[..raw.len() - trimmed.len()]1958
let indent: usize = raw[..raw.len() - trimmed.len()]1731
.chars()1959
.chars()1732
.map(|character| if character == '\t' { 4 } else { 1 })1960
.map(|character| if character == '\t' { 4 } else { 1 })1733
.sum();1961
.sum();1734
let depth = ((indent / MARKDOWN_INDENT) as u8).min(MAX_DEPTH);1962
let depth = ((indent / MARKDOWN_INDENT) as u8).min(MAX_DEPTH);1735
let (kind, number, content) = if let Some(rest) = PASTED_BULLETS1963
let (kind, number, content) = if let Some((level, rest)) = heading_prefix(trimmed) {1964
(LineKind::Heading(level), None, rest)1965
} else if let Some(rest) = PASTED_BULLETS1736
.iter()1966
.iter()1737
.find_map(|bullet| trimmed.strip_prefix(bullet))1967
.find_map(|bullet| trimmed.strip_prefix(bullet))1738
{1968
{@@ -1758,6 +1988,24 @@ fn markdown_lines(text: &str) -> Vec<DraftLine> {1758
lines1988
lines1759
}1989
}1760
1990
1991
fn table_line(table: Table) -> DraftLine {1992
DraftLine {1993
kind: LineKind::Table(table),1994
number: None,1995
content: TABLE_MARK.to_string(),1996
marks: Vec::new(),1997
}1998
}1999
2000
/// `# ` to `###### `: the level, capped at the three Teams offers, and the rest of the line.2001
fn heading_prefix(line: &str) -> Option<(u8, &str)> {2002
let hashes = line.bytes().take_while(|byte| *byte == b'#').count();2003
let rest = line[hashes..].strip_prefix(' ')?;2004
(1..=6)2005
.contains(&hashes)2006
.then(|| ((hashes as u8).min(MAX_HEADING), rest))2007
}2008
1761
fn parse_inline(source: &str) -> (String, Vec<Mark>) {2009
fn parse_inline(source: &str) -> (String, Vec<Mark>) {1762
let mut text = String::with_capacity(source.len());2010
let mut text = String::with_capacity(source.len());1763
let mut marks = Vec::new();2011
let mut marks = Vec::new();@@ -1849,6 +2097,17 @@ fn inline_at(rest: &str, previous: Option<char>) -> Option<(&str, usize, MarkKin1849
None2097
None1850
}2098
}1851
2099
2100
fn cell_text(spans: &[Span]) -> String {2101
let mut builder = SpanLines::default();2102
builder.walk(spans, &LineKind::Text, &[]);2103
builder2104
.finish()2105
.into_iter()2106
.map(|line| line.content)2107
.collect::<Vec<_>>()2108
.join("\n")2109
}2110
1852
#[derive(Default)]2111
#[derive(Default)]1853
struct SpanLines {2112
struct SpanLines {1854
lines: Vec<DraftLine>,2113
lines: Vec<DraftLine>,@@ -1936,9 +2195,10 @@ impl SpanLines {1936
};2195
};1937
self.start_line(&continued, None);2196
self.start_line(&continued, None);1938
}2197
}1939
Span::Heading { children, .. } => {2198
Span::Heading { level, children } => {1940
self.start_line(&LineKind::Text, None);2199
let heading = LineKind::Heading((*level).clamp(1, MAX_HEADING));1941
self.walk(children, &LineKind::Text, &with(MarkKind::Bold));2200
self.start_line(&heading, None);2201
self.walk(children, &heading, marks);1942
self.open = false;2202
self.open = false;1943
}2203
}1944
Span::CodeBlock { language, code } => {2204
Span::CodeBlock { language, code } => {@@ -1977,15 +2237,11 @@ impl SpanLines {1977
self.open = false;2237
self.open = false;1978
}2238
}1979
Span::Table { rows, .. } => {2239
Span::Table { rows, .. } => {1980
for row in rows {2240
let rows = rows1981
self.start_line(&LineKind::Text, None);2241
.iter()1982
for (position, cell) in row.iter().enumerate() {2242
.map(|row| row.iter().map(|cell| cell_text(cell)).collect())1983
if position > 0 {2243
.collect();1984
self.append(" | ", &LineKind::Text, &[]);2244
self.lines.push(table_line(Table::from_rows(rows)));1985
}1986
self.walk(cell, &LineKind::Text, marks);1987
}1988
}1989
self.open = false;2245
self.open = false;1990
}2246
}1991
Span::Image { .. } | Span::Quote { .. } => {}2247
Span::Image { .. } | Span::Quote { .. } => {}@@ -2081,7 +2337,7 @@ mod tests {2081
draft.marks(),2337
draft.marks(),2082
[2338
[2083
mark(2..6, MarkKind::Bold),2339
mark(2..6, MarkKind::Bold),2084
mark(11..13, MarkKind::Italic),2340
mark(11..13, MarkKind::Bold),2085
mark(17..19, MarkKind::Italic),2341
mark(17..19, MarkKind::Italic),2086
mark(20..24, MarkKind::Strike),2342
mark(20..24, MarkKind::Strike),2087
mark(25..29, MarkKind::Code),2343
mark(25..29, MarkKind::Code),@@ -2357,9 +2613,12 @@ mod tests {2357
let numbered = typed_draft("1. one");2613
let numbered = typed_draft("1. one");2358
assert_eq!(numbered.text(), "1. one");2614
assert_eq!(numbered.text(), "1. one");2359
assert_eq!(numbered.lines(), [LineKind::Numbered(0)]);2615
assert_eq!(numbered.lines(), [LineKind::Numbered(0)]);2360
let quote = typed_draft("> said");2616
let quote = typed_draft(">said");2361
assert_eq!(quote.text(), "said");2617
assert_eq!(quote.text(), "said");2362
assert_eq!(quote.lines(), [LineKind::Quote]);2618
assert_eq!(quote.lines(), [LineKind::Quote]);2619
let spaced = typed_draft("> said");2620
assert_eq!(spaced.text(), " said");2621
assert_eq!(spaced.lines(), [LineKind::Quote]);2363
}2622
}2364
2623
2365
#[test]2624
#[test]@@ -1,9 +1,9 @@
1
1
use url::Url;
2
2
3
3
const PROXY_PATH: &str = "/urlp/v1/url/content";
4
const PROXY_HOST_SUFFIX: &str = ".asyncgw.teams.microsoft.com";
4
const PROXY_HOST_SUFFIX: &str = chatsvc::links::LINK_PROXY_HOST_SUFFIX;
5
5
const GIPHY_HOST: &str = "giphy.com";
6
const TEAMS_CDN_HOST: &str = "statics.teams.cdn.office.net";
6
const TEAMS_CDN_HOST: &str = chatsvc::teams_cdn::HOST;
7
7
8
8
/// The direct URL of a GIF or sticker image, `None` when `src` is not one of the known public hosts.
9
9
pub fn external_image_url(src: &str) -> Option<String> {
@@ -1,9 +1,9 @@1
use url::Url;1
use url::Url;2
2
3
const PROXY_PATH: &str = "/urlp/v1/url/content";3
const PROXY_PATH: &str = "/urlp/v1/url/content";4
const PROXY_HOST_SUFFIX: &str = ".asyncgw.teams.microsoft.com";4
const PROXY_HOST_SUFFIX: &str = chatsvc::links::LINK_PROXY_HOST_SUFFIX;5
const GIPHY_HOST: &str = "giphy.com";5
const GIPHY_HOST: &str = "giphy.com";6
const TEAMS_CDN_HOST: &str = "statics.teams.cdn.office.net";6
const TEAMS_CDN_HOST: &str = chatsvc::teams_cdn::HOST;7
7
8
/// The direct URL of a GIF or sticker image, `None` when `src` is not one of the known public hosts.8
/// The direct URL of a GIF or sticker image, `None` when `src` is not one of the known public hosts.9
pub fn external_image_url(src: &str) -> Option<String> {9
pub fn external_image_url(src: &str) -> Option<String> {@@ -48,12 +48,13 @@ mod receipts;
48
48
mod recording_rights;
49
49
mod remote;
50
50
mod scheduled;
51
mod skin_tone;
52
51
mod search;
53
52
mod server_search;
54
53
mod sidebar_sync;
54
mod skin_tone;
55
55
mod spans;
56
56
mod stored;
57
mod table;
57
58
mod time_zone;
58
59
mod translate_sync;
59
60
mod translation;
@@ -67,8 +68,7 @@ pub use adaptive_card::{
67
68
};
68
69
pub use avatars::Avatar;
69
70
pub use call_event::{
70
CallEvent, CallPhase, CallType, Recording, call_event, format_duration,
71
parse_duration_seconds,
71
CallEvent, CallPhase, CallType, Recording, call_event, format_duration, parse_duration_seconds,
72
72
};
73
73
pub use card_actions::{CardActionOutcome, DialogIdentity, TaskDialog, TaskDialogKind};
74
74
pub use card_chart::{
@@ -118,6 +118,10 @@ pub use folders::{
118
118
BoxFuture, ChatFolder, ChatsvcFolderSource, FolderChange, FolderKind, FolderSource,
119
119
store_section_settings, stored_section_settings,
120
120
};
121
pub use forwarded::{
122
FORWARD_LOADING_TEXT, FORWARD_UNAVAILABLE_TEXT, FORWARDED_CONTENT_TYPE, ForwardHeader,
123
ForwardInfo, ForwardState, forwarded_texts, forwards, is_forwarded,
124
};
121
125
pub use graph::{
122
126
DriveEntry, DriveFolder, FileReference, HostedImage, KeptAttachment, MentionTarget,
123
127
MessageExtras, SharedFile, UploadedFile,
@@ -144,19 +148,16 @@ pub use receipts::{ReceiptReader, ReceiptState};
144
148
pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};
145
149
pub use scheduled::NOTES_CHAT_ID;
146
150
pub use skin_tone::{skin_tone, store_account_skin_tone};
147
pub use forwarded::{
148
FORWARD_LOADING_TEXT, FORWARD_UNAVAILABLE_TEXT, FORWARDED_CONTENT_TYPE, ForwardHeader,
149
ForwardInfo, ForwardState, forwarded_texts, forwards, is_forwarded,
150
};
151
151
pub use spans::{FontSize, Span, html_to_spans};
152
152
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};
153
153
pub use stored::{
154
154
AttachmentInfo, FileCard, FileKind, ImageKind, ImageRef, MentionInfo, PROFILE_LINK_PREFIX,
155
155
QuoteInfo, ReactionInfo, ReactionSummary, adaptive_cards, attachments, can_delete, can_edit,
156
card_texts, copy_text, files, images, linked_message_spans, linked_message_spans_with, mentions, message_quote,
157
message_spans, quote_html, quotes, reaction_summaries, reactions, readable_text, translated_spans,
158
user_mention_inputs,
156
card_texts, copy_text, files, images, linked_message_spans, linked_message_spans_with,
157
mentions, message_quote, message_spans, quote_html, quotes, reaction_summaries, reactions,
158
readable_text, translated_spans, user_mention_inputs,
159
159
};
160
pub use table::{Cell, PICKER_COLUMNS, PICKER_ROWS, TABLE_MARK, Table, TableEdit};
160
161
pub use time_zone::local_time;
161
162
pub use translation::{
162
163
FALLBACK_TARGET, LanguageStamp, confident_language, default_target, language_name, min_chars,
@@ -48,12 +48,13 @@ mod receipts;48
mod recording_rights;48
mod recording_rights;49
mod remote;49
mod remote;50
mod scheduled;50
mod scheduled;51
mod skin_tone;52
mod search;51
mod search;53
mod server_search;52
mod server_search;54
mod sidebar_sync;53
mod sidebar_sync;54
mod skin_tone;55
mod spans;55
mod spans;56
mod stored;56
mod stored;57
mod table;57
mod time_zone;58
mod time_zone;58
mod translate_sync;59
mod translate_sync;59
mod translation;60
mod translation;@@ -67,8 +68,7 @@ pub use adaptive_card::{67
};68
};68
pub use avatars::Avatar;69
pub use avatars::Avatar;69
pub use call_event::{70
pub use call_event::{70
CallEvent, CallPhase, CallType, Recording, call_event, format_duration,71
CallEvent, CallPhase, CallType, Recording, call_event, format_duration, parse_duration_seconds,71
parse_duration_seconds,72
};72
};73
pub use card_actions::{CardActionOutcome, DialogIdentity, TaskDialog, TaskDialogKind};73
pub use card_actions::{CardActionOutcome, DialogIdentity, TaskDialog, TaskDialogKind};74
pub use card_chart::{74
pub use card_chart::{@@ -118,6 +118,10 @@ pub use folders::{118
BoxFuture, ChatFolder, ChatsvcFolderSource, FolderChange, FolderKind, FolderSource,118
BoxFuture, ChatFolder, ChatsvcFolderSource, FolderChange, FolderKind, FolderSource,119
store_section_settings, stored_section_settings,119
store_section_settings, stored_section_settings,120
};120
};121
pub use forwarded::{122
FORWARD_LOADING_TEXT, FORWARD_UNAVAILABLE_TEXT, FORWARDED_CONTENT_TYPE, ForwardHeader,123
ForwardInfo, ForwardState, forwarded_texts, forwards, is_forwarded,124
};121
pub use graph::{125
pub use graph::{122
DriveEntry, DriveFolder, FileReference, HostedImage, KeptAttachment, MentionTarget,126
DriveEntry, DriveFolder, FileReference, HostedImage, KeptAttachment, MentionTarget,123
MessageExtras, SharedFile, UploadedFile,127
MessageExtras, SharedFile, UploadedFile,@@ -144,19 +148,16 @@ pub use receipts::{ReceiptReader, ReceiptState};144
pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};148
pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};145
pub use scheduled::NOTES_CHAT_ID;149
pub use scheduled::NOTES_CHAT_ID;146
pub use skin_tone::{skin_tone, store_account_skin_tone};150
pub use skin_tone::{skin_tone, store_account_skin_tone};147
pub use forwarded::{148
FORWARD_LOADING_TEXT, FORWARD_UNAVAILABLE_TEXT, FORWARDED_CONTENT_TYPE, ForwardHeader,149
ForwardInfo, ForwardState, forwarded_texts, forwards, is_forwarded,150
};151
pub use spans::{FontSize, Span, html_to_spans};151
pub use spans::{FontSize, Span, html_to_spans};152
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};152
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};153
pub use stored::{153
pub use stored::{154
AttachmentInfo, FileCard, FileKind, ImageKind, ImageRef, MentionInfo, PROFILE_LINK_PREFIX,154
AttachmentInfo, FileCard, FileKind, ImageKind, ImageRef, MentionInfo, PROFILE_LINK_PREFIX,155
QuoteInfo, ReactionInfo, ReactionSummary, adaptive_cards, attachments, can_delete, can_edit,155
QuoteInfo, ReactionInfo, ReactionSummary, adaptive_cards, attachments, can_delete, can_edit,156
card_texts, copy_text, files, images, linked_message_spans, linked_message_spans_with, mentions, message_quote,156
card_texts, copy_text, files, images, linked_message_spans, linked_message_spans_with,157
message_spans, quote_html, quotes, reaction_summaries, reactions, readable_text, translated_spans,157
mentions, message_quote, message_spans, quote_html, quotes, reaction_summaries, reactions,158
user_mention_inputs,158
readable_text, translated_spans, user_mention_inputs,159
};159
};160
pub use table::{Cell, PICKER_COLUMNS, PICKER_ROWS, TABLE_MARK, Table, TableEdit};160
pub use time_zone::local_time;161
pub use time_zone::local_time;161
pub use translation::{162
pub use translation::{162
FALLBACK_TARGET, LanguageStamp, confident_language, default_target, language_name, min_chars,163
FALLBACK_TARGET, LanguageStamp, confident_language, default_target, language_name, min_chars,@@ -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;10
use crate::preview::OwnedPreview;10
use crate::preview::OwnedPreview;11
use crate::stored::{AttachmentInfo, MentionInfo, QuoteInfo, ReactionInfo};11
use crate::stored::{AttachmentInfo, MentionInfo, QuoteInfo, ReactionInfo};12
12
13
const NO_NAME: &str = "?";14
15
pub fn graph_hidden(chat: &Chat) -> bool {13
pub fn graph_hidden(chat: &Chat) -> bool {16
chat.viewpoint14
chat.viewpoint17
.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: others48
member_summary: others51
.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
81
fn member_name(member: &graph::Member) -> &str {82
member83
.display_name84
.as_deref()85
.or(member.email.as_deref())86
.unwrap_or(NO_NAME)87
}88
89
fn is_unread(79
fn 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> = record357
.members358
.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",@@ -1,8 +1,8 @@
1
use chatsvc::presence::MAX_PRESENCE_IDS;
1
2
use chatsvc::{
2
3
ForcedAvailability, PresenceStatus, PresenceUpdate, StatusNote, TrouterEndpoint,
3
4
WorkLocationKind,
4
5
};
5
use graph::MAX_PRESENCE_IDS;
6
6
7
7
use chrono::{DateTime, Utc};
8
8
@@ -1,8 +1,8 @@1
use chatsvc::presence::MAX_PRESENCE_IDS;1
use chatsvc::{2
use chatsvc::{2
ForcedAvailability, PresenceStatus, PresenceUpdate, StatusNote, TrouterEndpoint,3
ForcedAvailability, PresenceStatus, PresenceUpdate, StatusNote, TrouterEndpoint,3
WorkLocationKind,4
WorkLocationKind,4
};5
};5
use graph::MAX_PRESENCE_IDS;6
6
7
use chrono::{DateTime, Utc};7
use chrono::{DateTime, Utc};8
8
@@ -1,16 +1,16 @@
1
use chatsvc::{
2
BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef, ConversationState,
3
Conversations,
4
ForcedAvailability, ForwardResult, Gif, Gifs, InvokeRequest, InvokeResponse, Language,
5
LanguageSettings, LanguageSettingsClient, LinkInfo, MemberHorizon, MessageLanguage,
6
MessageEmotions, MessageLinks, MessageWindow, Messages, PinnedMessage, Pins, PresenceService, PresenceStatus,
7
Receipts, RecordingPolicy, SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote, TranslateRequest,
8
Translation, TranslationTrigger, Translator, WindowDirection, WorkLocationKind,
9
};
10
1
use chatsvc::sound_settings::{SoundSettings, SoundSettingsClient};
11
2
use chatsvc::substrate_search::{
12
3
QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,
13
4
};
5
use chatsvc::{
6
BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,
7
ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, InvokeRequest,
8
InvokeResponse, Language, LanguageSettings, LanguageSettingsClient, LinkInfo, MemberHorizon,
9
MessageEmotions, MessageLanguage, MessageLinks, MessageWindow, Messages, PinnedMessage, Pins,
10
PresenceLookup, PresenceService, PresenceStatus, Receipts, RecordingPolicy, SavedMessage,
11
ScheduledDraft, ScheduledDrafts, StatusNote, TranslateRequest, Translation, TranslationTrigger,
12
Translator, WindowDirection, WorkLocationKind,
13
};
14
14
use chrono::{DateTime, Utc};
15
15
use graph::{
16
16
Channel, Chat, DriveEntry, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,
@@ -875,7 +875,17 @@ impl Remote for Graph {
875
875
}
876
876
877
877
async fn presences(&self, user_ids: &[String]) -> Result<Vec<Presence>> {
878
Ok(Graph::presences(self, user_ids).await?)
878
let found = PresenceLookup::new(self.session())
879
.presences(user_ids)
880
.await?;
881
Ok(found
882
.into_iter()
883
.map(|presence| Presence {
884
user_id: presence.user_id,
885
availability: presence.availability,
886
activity: presence.activity,
887
})
888
.collect())
879
889
}
880
890
881
891
async fn person_profile(&self, user_id: &str) -> Result<PersonProfile> {
@@ -893,7 +903,9 @@ impl Remote for Graph {
893
903
user_ids: &[String],
894
904
purge: bool,
895
905
) -> Result<()> {
896
Ok(Graph::subscribe_presence(self, endpoint_id, trouter_uri, user_ids, purge).await?)
906
Ok(PresenceLookup::new(self.session())
907
.subscribe(endpoint_id, trouter_uri, user_ids, purge)
908
.await?)
897
909
}
898
910
899
911
async fn own_status(&self, user_id: &str) -> Result<PresenceStatus> {
@@ -1032,7 +1044,11 @@ impl Remote for Graph {
1032
1044
page_size: usize,
1033
1045
) -> Result<Vec<MessageEmotions>> {
1034
1046
Ok(Messages::new(self.session())
1035
.message_emotions(&conversation.conversation_id(), newest_message_id, page_size)
1047
.message_emotions(
1048
&conversation.conversation_id(),
1049
newest_message_id,
1050
page_size,
1051
)
1036
1052
.await?)
1037
1053
}
1038
1054
@@ -1,16 +1,16 @@1
use chatsvc::{2
BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef, ConversationState,3
Conversations,4
ForcedAvailability, ForwardResult, Gif, Gifs, InvokeRequest, InvokeResponse, Language,5
LanguageSettings, LanguageSettingsClient, LinkInfo, MemberHorizon, MessageLanguage,6
MessageEmotions, MessageLinks, MessageWindow, Messages, PinnedMessage, Pins, PresenceService, PresenceStatus,7
Receipts, RecordingPolicy, SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote, TranslateRequest,8
Translation, TranslationTrigger, Translator, WindowDirection, WorkLocationKind,9
};10
use chatsvc::sound_settings::{SoundSettings, SoundSettingsClient};1
use chatsvc::sound_settings::{SoundSettings, SoundSettingsClient};11
use chatsvc::substrate_search::{2
use chatsvc::substrate_search::{12
QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,3
QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,13
};4
};5
use chatsvc::{6
BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,7
ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, InvokeRequest,8
InvokeResponse, Language, LanguageSettings, LanguageSettingsClient, LinkInfo, MemberHorizon,9
MessageEmotions, MessageLanguage, MessageLinks, MessageWindow, Messages, PinnedMessage, Pins,10
PresenceLookup, PresenceService, PresenceStatus, Receipts, RecordingPolicy, SavedMessage,11
ScheduledDraft, ScheduledDrafts, StatusNote, TranslateRequest, Translation, TranslationTrigger,12
Translator, WindowDirection, WorkLocationKind,13
};14
use chrono::{DateTime, Utc};14
use chrono::{DateTime, Utc};15
use graph::{15
use graph::{16
Channel, Chat, DriveEntry, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,16
Channel, Chat, DriveEntry, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,@@ -875,7 +875,17 @@ impl Remote for Graph {875
}875
}876
876
877
async fn presences(&self, user_ids: &[String]) -> Result<Vec<Presence>> {877
async fn presences(&self, user_ids: &[String]) -> Result<Vec<Presence>> {878
Ok(Graph::presences(self, user_ids).await?)878
let found = PresenceLookup::new(self.session())879
.presences(user_ids)880
.await?;881
Ok(found882
.into_iter()883
.map(|presence| Presence {884
user_id: presence.user_id,885
availability: presence.availability,886
activity: presence.activity,887
})888
.collect())879
}889
}880
890
881
async fn person_profile(&self, user_id: &str) -> Result<PersonProfile> {891
async fn person_profile(&self, user_id: &str) -> Result<PersonProfile> {@@ -893,7 +903,9 @@ impl Remote for Graph {893
user_ids: &[String],903
user_ids: &[String],894
purge: bool,904
purge: bool,895
) -> Result<()> {905
) -> Result<()> {896
Ok(Graph::subscribe_presence(self, endpoint_id, trouter_uri, user_ids, purge).await?)906
Ok(PresenceLookup::new(self.session())907
.subscribe(endpoint_id, trouter_uri, user_ids, purge)908
.await?)897
}909
}898
910
899
async fn own_status(&self, user_id: &str) -> Result<PresenceStatus> {911
async fn own_status(&self, user_id: &str) -> Result<PresenceStatus> {@@ -1032,7 +1044,11 @@ impl Remote for Graph {1032
page_size: usize,1044
page_size: usize,1033
) -> Result<Vec<MessageEmotions>> {1045
) -> Result<Vec<MessageEmotions>> {1034
Ok(Messages::new(self.session())1046
Ok(Messages::new(self.session())1035
.message_emotions(&conversation.conversation_id(), newest_message_id, page_size)1047
.message_emotions(1048
&conversation.conversation_id(),1049
newest_message_id,1050
page_size,1051
)1036
.await?)1052
.await?)1037
}1053
}1038
1054
@@ -0,0 +1,353 @@
1
use serde::{Deserialize, Serialize};
2
3
use crate::markdown::escape_html;
4
5
pub const TABLE_MARK: char = '\u{FFFB}';
6
pub const PICKER_COLUMNS: usize = 7;
7
pub const PICKER_ROWS: usize = 5;
8
const EMPTY_CELL: &str = " ";
9
10
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11
pub struct Cell {
12
pub row: usize,
13
pub column: usize,
14
}
15
16
impl Cell {
17
pub fn new(row: usize, column: usize) -> Cell {
18
Cell { row, column }
19
}
20
}
21
22
/// A composer table: plain text cells, every row as wide as the first.
23
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
24
pub struct Table {
25
pub rows: Vec<Vec<String>>,
26
}
27
28
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29
pub enum TableEdit {
30
InsertRowAbove,
31
InsertRowBelow,
32
InsertColumnLeft,
33
InsertColumnRight,
34
DeleteRow,
35
DeleteColumn,
36
DeleteTable,
37
}
38
39
impl TableEdit {
40
pub const INSERTS: [TableEdit; 4] = [
41
TableEdit::InsertRowAbove,
42
TableEdit::InsertRowBelow,
43
TableEdit::InsertColumnLeft,
44
TableEdit::InsertColumnRight,
45
];
46
pub const DELETES: [TableEdit; 3] = [
47
TableEdit::DeleteRow,
48
TableEdit::DeleteColumn,
49
TableEdit::DeleteTable,
50
];
51
52
pub fn label(self) -> &'static str {
53
match self {
54
TableEdit::InsertRowAbove => "Insert row above",
55
TableEdit::InsertRowBelow => "Insert row below",
56
TableEdit::InsertColumnLeft => "Insert column to the left",
57
TableEdit::InsertColumnRight => "Insert column to the right",
58
TableEdit::DeleteRow => "Delete row",
59
TableEdit::DeleteColumn => "Delete column",
60
TableEdit::DeleteTable => "Delete table",
61
}
62
}
63
}
64
65
impl Table {
66
pub fn new(rows: usize, columns: usize) -> Table {
67
Table {
68
rows: vec![vec![String::new(); columns.max(1)]; rows.max(1)],
69
}
70
}
71
72
/// Short rows are filled up to the widest one.
73
pub fn from_rows(mut rows: Vec<Vec<String>>) -> Table {
74
rows.retain(|row| !row.is_empty());
75
let columns = rows.iter().map(Vec::len).max().unwrap_or(1);
76
for row in &mut rows {
77
row.resize(columns, String::new());
78
}
79
if rows.is_empty() {
80
return Table::new(1, 1);
81
}
82
Table { rows }
83
}
84
85
pub fn row_count(&self) -> usize {
86
self.rows.len()
87
}
88
89
pub fn column_count(&self) -> usize {
90
self.rows.first().map_or(0, Vec::len)
91
}
92
93
pub fn cell(&self, cell: Cell) -> Option<&str> {
94
self.rows
95
.get(cell.row)?
96
.get(cell.column)
97
.map(String::as_str)
98
}
99
100
pub fn set_cell(&mut self, cell: Cell, text: &str) {
101
if let Some(slot) = self
102
.rows
103
.get_mut(cell.row)
104
.and_then(|row| row.get_mut(cell.column))
105
{
106
*slot = text.to_owned();
107
}
108
}
109
110
pub fn last_cell(&self) -> Cell {
111
Cell::new(self.row_count() - 1, self.column_count() - 1)
112
}
113
114
/// Tab: the next cell, and past the last one a new row (`true`) like Teams.
115
pub fn next_cell(&mut self, cell: Cell) -> (Cell, bool) {
116
if cell.column + 1 < self.column_count() {
117
return (Cell::new(cell.row, cell.column + 1), false);
118
}
119
if cell.row + 1 < self.row_count() {
120
return (Cell::new(cell.row + 1, 0), false);
121
}
122
self.rows.push(vec![String::new(); self.column_count()]);
123
(Cell::new(cell.row + 1, 0), true)
124
}
125
126
/// Shift+Tab: the previous cell; the first cell stays.
127
pub fn previous_cell(&self, cell: Cell) -> Cell {
128
match (cell.row, cell.column) {
129
(_, column) if column > 0 => Cell::new(cell.row, column - 1),
130
(0, _) => cell,
131
(row, _) => Cell::new(row - 1, self.column_count() - 1),
132
}
133
}
134
135
/// The cell to focus afterwards; `None` when the table is gone.
136
pub fn apply(&mut self, edit: TableEdit, cell: Cell) -> Option<Cell> {
137
let columns = self.column_count();
138
match edit {
139
TableEdit::InsertRowAbove => {
140
self.rows.insert(cell.row, vec![String::new(); columns]);
141
Some(Cell::new(cell.row, cell.column))
142
}
143
TableEdit::InsertRowBelow => {
144
self.rows.insert(cell.row + 1, vec![String::new(); columns]);
145
Some(Cell::new(cell.row + 1, cell.column))
146
}
147
TableEdit::InsertColumnLeft => {
148
for row in &mut self.rows {
149
row.insert(cell.column, String::new());
150
}
151
Some(Cell::new(cell.row, cell.column))
152
}
153
TableEdit::InsertColumnRight => {
154
for row in &mut self.rows {
155
row.insert(cell.column + 1, String::new());
156
}
157
Some(Cell::new(cell.row, cell.column + 1))
158
}
159
TableEdit::DeleteRow if self.row_count() > 1 => {
160
self.rows.remove(cell.row);
161
Some(Cell::new(cell.row.min(self.row_count() - 1), cell.column))
162
}
163
TableEdit::DeleteColumn if columns > 1 => {
164
for row in &mut self.rows {
165
row.remove(cell.column);
166
}
167
Some(Cell::new(
168
cell.row,
169
cell.column.min(self.column_count() - 1),
170
))
171
}
172
TableEdit::DeleteRow | TableEdit::DeleteColumn | TableEdit::DeleteTable => None,
173
}
174
}
175
176
pub fn is_blank(&self) -> bool {
177
self.rows
178
.iter()
179
.flatten()
180
.all(|cell| cell.trim().is_empty())
181
}
182
183
/// Rows on lines, cells split by tabs: what a spreadsheet pastes.
184
pub fn plain_text(&self) -> String {
185
self.rows
186
.iter()
187
.map(|row| row.join("\t").replace('\n', " "))
188
.collect::<Vec<_>>()
189
.join("\n")
190
}
191
192
/// The table Teams sends: CKEditor's `figure.table`, `copy-paste-table` on the table, a one
193
/// line cell without `<p>`, every line of a longer cell in its own `<p>`, empty ` `.
194
pub fn to_html(&self) -> String {
195
let mut html =
196
String::from("<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>");
197
for row in &self.rows {
198
html.push_str("<tr>");
199
for cell in row {
200
html.push_str("<td>");
201
if cell.trim().is_empty() {
202
html.push_str(EMPTY_CELL);
203
} else if !cell.contains('\n') {
204
html.push_str(&escape_html(cell));
205
} else {
206
for line in cell.split('\n') {
207
html.push_str("<p>");
208
if line.trim().is_empty() {
209
html.push_str(EMPTY_CELL);
210
} else {
211
html.push_str(&escape_html(line));
212
}
213
html.push_str("</p>");
214
}
215
}
216
html.push_str("</td>");
217
}
218
html.push_str("</tr>");
219
}
220
html.push_str("</tbody></table></figure>");
221
html
222
}
223
}
224
225
fn split_row(line: &str) -> Option<Vec<String>> {
226
let trimmed = line.trim();
227
if !trimmed.contains('|') {
228
return None;
229
}
230
let inner = trimmed.strip_prefix('|').unwrap_or(trimmed);
231
let inner = inner.strip_suffix('|').unwrap_or(inner);
232
let mut cells = Vec::new();
233
let mut current = String::new();
234
let mut characters = inner.chars().peekable();
235
while let Some(character) = characters.next() {
236
match character {
237
'\\' if characters.peek() == Some(&'|') => {
238
current.push('|');
239
characters.next();
240
}
241
'|' => cells.push(std::mem::take(&mut current).trim().to_owned()),
242
other => current.push(other),
243
}
244
}
245
cells.push(current.trim().to_owned());
246
Some(cells)
247
}
248
249
fn is_delimiter_row(line: &str) -> bool {
250
split_row(line).is_some_and(|cells| {
251
cells.iter().all(|cell| {
252
let dashes = cell.trim_start_matches(':').trim_end_matches(':');
253
!dashes.is_empty() && dashes.chars().all(|character| character == '-')
254
})
255
})
256
}
257
258
/// A GitHub markdown table at the start of `lines`: header, delimiter row, body rows.
259
/// Returns the raw cell sources and how many lines it spans.
260
pub(crate) fn markdown_table(lines: &[&str]) -> Option<(Vec<Vec<String>>, usize)> {
261
let header = split_row(lines.first()?)?;
262
if !lines.get(1).is_some_and(|line| is_delimiter_row(line)) {
263
return None;
264
}
265
let delimiter_columns = split_row(lines[1])?.len();
266
if delimiter_columns != header.len() {
267
return None;
268
}
269
let mut rows = vec![header];
270
let mut consumed = 2;
271
for line in &lines[2..] {
272
match split_row(line) {
273
Some(cells) if !line.trim().is_empty() => rows.push(cells),
274
_ => break,
275
}
276
consumed += 1;
277
}
278
Some((rows, consumed))
279
}
280
281
#[cfg(test)]
282
mod tests {
283
use super::*;
284
285
#[test]
286
fn tab_walks_the_cells_and_adds_a_row_after_the_last() {
287
let mut table = Table::new(2, 2);
288
assert_eq!(table.next_cell(Cell::new(0, 0)), (Cell::new(0, 1), false));
289
assert_eq!(table.next_cell(Cell::new(0, 1)), (Cell::new(1, 0), false));
290
assert_eq!(table.next_cell(Cell::new(1, 1)), (Cell::new(2, 0), true));
291
assert_eq!(table.row_count(), 3);
292
assert_eq!(table.column_count(), 2);
293
}
294
295
#[test]
296
fn shift_tab_walks_back_and_stops_at_the_first_cell() {
297
let table = Table::new(2, 3);
298
assert_eq!(table.previous_cell(Cell::new(1, 0)), Cell::new(0, 2));
299
assert_eq!(table.previous_cell(Cell::new(0, 1)), Cell::new(0, 0));
300
assert_eq!(table.previous_cell(Cell::new(0, 0)), Cell::new(0, 0));
301
}
302
303
#[test]
304
fn rows_and_columns_insert_and_delete_around_the_cell() {
305
let mut table = Table::from_rows(vec![
306
vec!["a".into(), "b".into()],
307
vec!["c".into(), "d".into()],
308
]);
309
assert_eq!(
310
table.apply(TableEdit::InsertRowAbove, Cell::new(1, 1)),
311
Some(Cell::new(1, 1))
312
);
313
assert_eq!(table.rows[1], ["", ""]);
314
assert_eq!(
315
table.apply(TableEdit::InsertColumnRight, Cell::new(0, 0)),
316
Some(Cell::new(0, 1))
317
);
318
assert_eq!(table.rows[0], ["a", "", "b"]);
319
table.apply(TableEdit::DeleteColumn, Cell::new(0, 1));
320
table.apply(TableEdit::DeleteRow, Cell::new(1, 0));
321
assert_eq!(table.rows, [["a", "b"], ["c", "d"]]);
322
assert_eq!(table.apply(TableEdit::DeleteTable, Cell::new(0, 0)), None);
323
}
324
325
#[test]
326
fn deleting_the_last_row_or_column_deletes_the_table() {
327
let mut table = Table::new(1, 2);
328
assert_eq!(table.apply(TableEdit::DeleteRow, Cell::new(0, 0)), None);
329
let mut table = Table::new(2, 1);
330
assert_eq!(table.apply(TableEdit::DeleteColumn, Cell::new(0, 0)), None);
331
}
332
333
#[test]
334
fn html_is_the_copy_paste_table_teams_sends() {
335
let table = Table::from_rows(vec![vec!["a<b".into(), String::new()], vec!["x\ny".into()]]);
336
assert_eq!(
337
table.to_html(),
338
"<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\
339
<tr><td>a<b</td><td> </td></tr>\
340
<tr><td><p>x</p><p>y</p></td><td> </td></tr></tbody></table></figure>"
341
);
342
}
343
344
#[test]
345
fn markdown_tables_need_a_delimiter_row() {
346
let lines = ["| A | B |", "|---|:-:|", "| 1 | 2 \\| 3 |", "", "after"];
347
let (rows, consumed) = markdown_table(&lines).unwrap();
348
assert_eq!(consumed, 3);
349
assert_eq!(rows, [["A", "B"], ["1", "2 | 3"]]);
350
assert!(markdown_table(&["a | b", "c | d"]).is_none());
351
assert!(markdown_table(&["| a | b |", "|---|"]).is_none());
352
}
353
}
@@ -0,0 +1,353 @@1
use serde::{Deserialize, Serialize};2
3
use crate::markdown::escape_html;4
5
pub const TABLE_MARK: char = '\u{FFFB}';6
pub const PICKER_COLUMNS: usize = 7;7
pub const PICKER_ROWS: usize = 5;8
const EMPTY_CELL: &str = " ";9
10
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]11
pub struct Cell {12
pub row: usize,13
pub column: usize,14
}15
16
impl Cell {17
pub fn new(row: usize, column: usize) -> Cell {18
Cell { row, column }19
}20
}21
22
/// A composer table: plain text cells, every row as wide as the first.23
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]24
pub struct Table {25
pub rows: Vec<Vec<String>>,26
}27
28
#[derive(Debug, Clone, Copy, PartialEq, Eq)]29
pub enum TableEdit {30
InsertRowAbove,31
InsertRowBelow,32
InsertColumnLeft,33
InsertColumnRight,34
DeleteRow,35
DeleteColumn,36
DeleteTable,37
}38
39
impl TableEdit {40
pub const INSERTS: [TableEdit; 4] = [41
TableEdit::InsertRowAbove,42
TableEdit::InsertRowBelow,43
TableEdit::InsertColumnLeft,44
TableEdit::InsertColumnRight,45
];46
pub const DELETES: [TableEdit; 3] = [47
TableEdit::DeleteRow,48
TableEdit::DeleteColumn,49
TableEdit::DeleteTable,50
];51
52
pub fn label(self) -> &'static str {53
match self {54
TableEdit::InsertRowAbove => "Insert row above",55
TableEdit::InsertRowBelow => "Insert row below",56
TableEdit::InsertColumnLeft => "Insert column to the left",57
TableEdit::InsertColumnRight => "Insert column to the right",58
TableEdit::DeleteRow => "Delete row",59
TableEdit::DeleteColumn => "Delete column",60
TableEdit::DeleteTable => "Delete table",61
}62
}63
}64
65
impl Table {66
pub fn new(rows: usize, columns: usize) -> Table {67
Table {68
rows: vec![vec![String::new(); columns.max(1)]; rows.max(1)],69
}70
}71
72
/// Short rows are filled up to the widest one.73
pub fn from_rows(mut rows: Vec<Vec<String>>) -> Table {74
rows.retain(|row| !row.is_empty());75
let columns = rows.iter().map(Vec::len).max().unwrap_or(1);76
for row in &mut rows {77
row.resize(columns, String::new());78
}79
if rows.is_empty() {80
return Table::new(1, 1);81
}82
Table { rows }83
}84
85
pub fn row_count(&self) -> usize {86
self.rows.len()87
}88
89
pub fn column_count(&self) -> usize {90
self.rows.first().map_or(0, Vec::len)91
}92
93
pub fn cell(&self, cell: Cell) -> Option<&str> {94
self.rows95
.get(cell.row)?96
.get(cell.column)97
.map(String::as_str)98
}99
100
pub fn set_cell(&mut self, cell: Cell, text: &str) {101
if let Some(slot) = self102
.rows103
.get_mut(cell.row)104
.and_then(|row| row.get_mut(cell.column))105
{106
*slot = text.to_owned();107
}108
}109
110
pub fn last_cell(&self) -> Cell {111
Cell::new(self.row_count() - 1, self.column_count() - 1)112
}113
114
/// Tab: the next cell, and past the last one a new row (`true`) like Teams.115
pub fn next_cell(&mut self, cell: Cell) -> (Cell, bool) {116
if cell.column + 1 < self.column_count() {117
return (Cell::new(cell.row, cell.column + 1), false);118
}119
if cell.row + 1 < self.row_count() {120
return (Cell::new(cell.row + 1, 0), false);121
}122
self.rows.push(vec![String::new(); self.column_count()]);123
(Cell::new(cell.row + 1, 0), true)124
}125
126
/// Shift+Tab: the previous cell; the first cell stays.127
pub fn previous_cell(&self, cell: Cell) -> Cell {128
match (cell.row, cell.column) {129
(_, column) if column > 0 => Cell::new(cell.row, column - 1),130
(0, _) => cell,131
(row, _) => Cell::new(row - 1, self.column_count() - 1),132
}133
}134
135
/// The cell to focus afterwards; `None` when the table is gone.136
pub fn apply(&mut self, edit: TableEdit, cell: Cell) -> Option<Cell> {137
let columns = self.column_count();138
match edit {139
TableEdit::InsertRowAbove => {140
self.rows.insert(cell.row, vec![String::new(); columns]);141
Some(Cell::new(cell.row, cell.column))142
}143
TableEdit::InsertRowBelow => {144
self.rows.insert(cell.row + 1, vec![String::new(); columns]);145
Some(Cell::new(cell.row + 1, cell.column))146
}147
TableEdit::InsertColumnLeft => {148
for row in &mut self.rows {149
row.insert(cell.column, String::new());150
}151
Some(Cell::new(cell.row, cell.column))152
}153
TableEdit::InsertColumnRight => {154
for row in &mut self.rows {155
row.insert(cell.column + 1, String::new());156
}157
Some(Cell::new(cell.row, cell.column + 1))158
}159
TableEdit::DeleteRow if self.row_count() > 1 => {160
self.rows.remove(cell.row);161
Some(Cell::new(cell.row.min(self.row_count() - 1), cell.column))162
}163
TableEdit::DeleteColumn if columns > 1 => {164
for row in &mut self.rows {165
row.remove(cell.column);166
}167
Some(Cell::new(168
cell.row,169
cell.column.min(self.column_count() - 1),170
))171
}172
TableEdit::DeleteRow | TableEdit::DeleteColumn | TableEdit::DeleteTable => None,173
}174
}175
176
pub fn is_blank(&self) -> bool {177
self.rows178
.iter()179
.flatten()180
.all(|cell| cell.trim().is_empty())181
}182
183
/// Rows on lines, cells split by tabs: what a spreadsheet pastes.184
pub fn plain_text(&self) -> String {185
self.rows186
.iter()187
.map(|row| row.join("\t").replace('\n', " "))188
.collect::<Vec<_>>()189
.join("\n")190
}191
192
/// The table Teams sends: CKEditor's `figure.table`, `copy-paste-table` on the table, a one193
/// line cell without `<p>`, every line of a longer cell in its own `<p>`, empty ` `.194
pub fn to_html(&self) -> String {195
let mut html =196
String::from("<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>");197
for row in &self.rows {198
html.push_str("<tr>");199
for cell in row {200
html.push_str("<td>");201
if cell.trim().is_empty() {202
html.push_str(EMPTY_CELL);203
} else if !cell.contains('\n') {204
html.push_str(&escape_html(cell));205
} else {206
for line in cell.split('\n') {207
html.push_str("<p>");208
if line.trim().is_empty() {209
html.push_str(EMPTY_CELL);210
} else {211
html.push_str(&escape_html(line));212
}213
html.push_str("</p>");214
}215
}216
html.push_str("</td>");217
}218
html.push_str("</tr>");219
}220
html.push_str("</tbody></table></figure>");221
html222
}223
}224
225
fn split_row(line: &str) -> Option<Vec<String>> {226
let trimmed = line.trim();227
if !trimmed.contains('|') {228
return None;229
}230
let inner = trimmed.strip_prefix('|').unwrap_or(trimmed);231
let inner = inner.strip_suffix('|').unwrap_or(inner);232
let mut cells = Vec::new();233
let mut current = String::new();234
let mut characters = inner.chars().peekable();235
while let Some(character) = characters.next() {236
match character {237
'\\' if characters.peek() == Some(&'|') => {238
current.push('|');239
characters.next();240
}241
'|' => cells.push(std::mem::take(&mut current).trim().to_owned()),242
other => current.push(other),243
}244
}245
cells.push(current.trim().to_owned());246
Some(cells)247
}248
249
fn is_delimiter_row(line: &str) -> bool {250
split_row(line).is_some_and(|cells| {251
cells.iter().all(|cell| {252
let dashes = cell.trim_start_matches(':').trim_end_matches(':');253
!dashes.is_empty() && dashes.chars().all(|character| character == '-')254
})255
})256
}257
258
/// A GitHub markdown table at the start of `lines`: header, delimiter row, body rows.259
/// Returns the raw cell sources and how many lines it spans.260
pub(crate) fn markdown_table(lines: &[&str]) -> Option<(Vec<Vec<String>>, usize)> {261
let header = split_row(lines.first()?)?;262
if !lines.get(1).is_some_and(|line| is_delimiter_row(line)) {263
return None;264
}265
let delimiter_columns = split_row(lines[1])?.len();266
if delimiter_columns != header.len() {267
return None;268
}269
let mut rows = vec![header];270
let mut consumed = 2;271
for line in &lines[2..] {272
match split_row(line) {273
Some(cells) if !line.trim().is_empty() => rows.push(cells),274
_ => break,275
}276
consumed += 1;277
}278
Some((rows, consumed))279
}280
281
#[cfg(test)]282
mod tests {283
use super::*;284
285
#[test]286
fn tab_walks_the_cells_and_adds_a_row_after_the_last() {287
let mut table = Table::new(2, 2);288
assert_eq!(table.next_cell(Cell::new(0, 0)), (Cell::new(0, 1), false));289
assert_eq!(table.next_cell(Cell::new(0, 1)), (Cell::new(1, 0), false));290
assert_eq!(table.next_cell(Cell::new(1, 1)), (Cell::new(2, 0), true));291
assert_eq!(table.row_count(), 3);292
assert_eq!(table.column_count(), 2);293
}294
295
#[test]296
fn shift_tab_walks_back_and_stops_at_the_first_cell() {297
let table = Table::new(2, 3);298
assert_eq!(table.previous_cell(Cell::new(1, 0)), Cell::new(0, 2));299
assert_eq!(table.previous_cell(Cell::new(0, 1)), Cell::new(0, 0));300
assert_eq!(table.previous_cell(Cell::new(0, 0)), Cell::new(0, 0));301
}302
303
#[test]304
fn rows_and_columns_insert_and_delete_around_the_cell() {305
let mut table = Table::from_rows(vec![306
vec!["a".into(), "b".into()],307
vec!["c".into(), "d".into()],308
]);309
assert_eq!(310
table.apply(TableEdit::InsertRowAbove, Cell::new(1, 1)),311
Some(Cell::new(1, 1))312
);313
assert_eq!(table.rows[1], ["", ""]);314
assert_eq!(315
table.apply(TableEdit::InsertColumnRight, Cell::new(0, 0)),316
Some(Cell::new(0, 1))317
);318
assert_eq!(table.rows[0], ["a", "", "b"]);319
table.apply(TableEdit::DeleteColumn, Cell::new(0, 1));320
table.apply(TableEdit::DeleteRow, Cell::new(1, 0));321
assert_eq!(table.rows, [["a", "b"], ["c", "d"]]);322
assert_eq!(table.apply(TableEdit::DeleteTable, Cell::new(0, 0)), None);323
}324
325
#[test]326
fn deleting_the_last_row_or_column_deletes_the_table() {327
let mut table = Table::new(1, 2);328
assert_eq!(table.apply(TableEdit::DeleteRow, Cell::new(0, 0)), None);329
let mut table = Table::new(2, 1);330
assert_eq!(table.apply(TableEdit::DeleteColumn, Cell::new(0, 0)), None);331
}332
333
#[test]334
fn html_is_the_copy_paste_table_teams_sends() {335
let table = Table::from_rows(vec![vec!["a<b".into(), String::new()], vec!["x\ny".into()]]);336
assert_eq!(337
table.to_html(),338
"<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\339
<tr><td>a<b</td><td> </td></tr>\340
<tr><td><p>x</p><p>y</p></td><td> </td></tr></tbody></table></figure>"341
);342
}343
344
#[test]345
fn markdown_tables_need_a_delimiter_row() {346
let lines = ["| A | B |", "|---|:-:|", "| 1 | 2 \\| 3 |", "", "after"];347
let (rows, consumed) = markdown_table(&lines).unwrap();348
assert_eq!(consumed, 3);349
assert_eq!(rows, [["A", "B"], ["1", "2 | 3"]]);350
assert!(markdown_table(&["a | b", "c | d"]).is_none());351
assert!(markdown_table(&["| a | b |", "|---|"]).is_none());352
}353
}@@ -0,0 +1,341 @@
1
use teams_core::{
2
Draft, DraftLine, LineKind, Mark, MarkKind, TABLE_MARK, Table, TypingStyle, html_to_spans,
3
};
4
5
fn typed(draft: &mut Draft, text: &str) {
6
let mut typing: Option<TypingStyle> = None;
7
for character in text.chars() {
8
let cursor = draft.text().len();
9
let mut next = draft.text().to_owned();
10
next.push(character);
11
let cursor = draft.apply_edit(&next, cursor + character.len_utf8(), typing.as_ref());
12
typing = draft.convert_typed(cursor).map(|(_, style)| style);
13
draft.take_edits();
14
}
15
}
16
17
fn typed_draft(text: &str) -> Draft {
18
let mut draft = Draft::default();
19
typed(&mut draft, text);
20
draft
21
}
22
23
fn enter(draft: &mut Draft, cursor: usize, shift: bool) -> Option<usize> {
24
let result = draft.break_line(cursor, shift);
25
draft.take_edits();
26
result
27
}
28
29
fn table_of(rows: &[&[&str]]) -> Table {
30
Table::from_rows(
31
rows.iter()
32
.map(|row| row.iter().map(|cell| (*cell).to_owned()).collect())
33
.collect(),
34
)
35
}
36
37
#[test]
38
fn enter_in_a_quote_adds_a_quote_line_and_enter_on_the_empty_one_leaves() {
39
let mut draft = typed_draft(">abc");
40
let cursor = enter(&mut draft, 3, false).unwrap();
41
assert_eq!(draft.text(), "abc\n");
42
assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Quote]);
43
let cursor = enter(&mut draft, cursor, false).unwrap();
44
assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Text]);
45
assert_eq!(cursor, 4);
46
assert_eq!(enter(&mut draft, cursor, false), None);
47
assert_eq!(draft.to_html(), "<blockquote>abc</blockquote>");
48
}
49
50
#[test]
51
fn enter_on_an_empty_quote_line_in_the_middle_splits_the_quote() {
52
let mut draft = Draft::from_markdown("> a\n> \n> b");
53
enter(&mut draft, 2, false).unwrap();
54
assert_eq!(
55
draft.lines(),
56
[LineKind::Quote, LineKind::Text, LineKind::Quote]
57
);
58
}
59
60
#[test]
61
fn shift_enter_keeps_breaking_inside_the_quote() {
62
let mut draft = typed_draft(">a");
63
let cursor = enter(&mut draft, 1, true).unwrap();
64
let cursor = enter(&mut draft, cursor, true).unwrap();
65
assert_eq!(cursor, 3);
66
assert_eq!(
67
draft.lines(),
68
[LineKind::Quote, LineKind::Quote, LineKind::Quote]
69
);
70
}
71
72
#[test]
73
fn backspace_at_the_start_of_a_quote_leaves_it_or_joins_the_line_above() {
74
let mut empty = typed_draft(">");
75
assert_eq!(empty.backspace_at_start(0), Some(0));
76
assert_eq!(empty.lines(), [LineKind::Text]);
77
78
let mut joined = Draft::from_markdown("x\n> abc");
79
assert_eq!(joined.backspace_at_start(2), Some(1));
80
assert_eq!(joined.text(), "xabc");
81
assert_eq!(joined.lines(), [LineKind::Text]);
82
83
let mut inner = Draft::from_markdown("> a\n> b");
84
assert_eq!(inner.backspace_at_start(2), Some(1));
85
assert_eq!(inner.text(), "ab");
86
assert_eq!(inner.lines(), [LineKind::Quote]);
87
}
88
89
#[test]
90
fn down_at_the_end_of_a_closing_quote_opens_a_text_line_below() {
91
let mut draft = typed_draft(">abc");
92
assert_eq!(draft.leave_quote_at_end(1), None);
93
assert_eq!(draft.leave_quote_at_end(3), Some(4));
94
assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Text]);
95
assert_eq!(Draft::plain("x").leave_quote_at_end(1), None);
96
}
97
98
#[test]
99
fn teams_shortcuts_make_headings_bold_italic_and_code() {
100
let heading = typed_draft("## Plan");
101
assert_eq!(heading.text(), "Plan");
102
assert_eq!(heading.lines(), [LineKind::Heading(2)]);
103
assert_eq!(heading.to_html(), "<h2>Plan</h2>");
104
assert_eq!(typed_draft("#### deep").lines(), [LineKind::Heading(3)]);
105
assert_eq!(typed_draft("#nope").lines(), [LineKind::Text]);
106
107
let inline = typed_draft("*b* _i_ `c`");
108
assert_eq!(inline.text(), "b i c");
109
assert_eq!(
110
inline.marks(),
111
[
112
Mark {
113
range: 0..1,
114
kind: MarkKind::Bold
115
},
116
Mark {
117
range: 2..3,
118
kind: MarkKind::Italic
119
},
120
Mark {
121
range: 4..5,
122
kind: MarkKind::Code
123
},
124
]
125
);
126
}
127
128
#[test]
129
fn enter_in_a_heading_is_left_to_send_and_backspace_makes_it_text() {
130
let mut draft = typed_draft("# a");
131
assert_eq!(enter(&mut draft, 1, false), None);
132
assert_eq!(draft.backspace_at_start(0), Some(0));
133
assert_eq!(draft.lines(), [LineKind::Text]);
134
}
135
136
#[test]
137
fn an_inserted_table_takes_an_empty_line_and_gets_a_line_after_it() {
138
let mut draft = Draft::default();
139
let index = draft.insert_table(0, Table::new(2, 3));
140
assert_eq!(index, 0);
141
assert_eq!(draft.text(), format!("{TABLE_MARK}\n"));
142
assert!(draft.lines()[0].is_table());
143
assert_eq!(draft.lines()[1], LineKind::Text);
144
145
let mut below = Draft::plain("hello");
146
assert_eq!(below.insert_table(2, Table::new(1, 1)), 1);
147
assert_eq!(below.text(), format!("hello\n{TABLE_MARK}\n"));
148
}
149
150
#[test]
151
fn a_table_is_sent_as_teams_html_between_the_text() {
152
let mut draft = Draft::plain("before");
153
let index = draft.insert_table(6, Table::new(1, 2));
154
draft.set_table(index, table_of(&[&["a", "b"]]));
155
let end = draft.text().len();
156
let mut text = draft.text().to_owned();
157
text.push_str("after");
158
draft.apply_edit(&text, end + 5, None);
159
assert_eq!(
160
draft.trimmed().to_html(),
161
"before<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\
162
<tr><td>a</td><td>b</td></tr></tbody></table></figure>after"
163
);
164
assert_eq!(draft.plain_text(), "before\na\tb\nafter");
165
assert!(
166
!Draft::from_lines(&[DraftLine {
167
kind: LineKind::Table(Table::new(1, 1)),
168
number: None,
169
content: TABLE_MARK.to_string(),
170
marks: Vec::new(),
171
}])
172
.plain_text()
173
.contains(TABLE_MARK)
174
);
175
}
176
177
#[test]
178
fn text_typed_next_to_a_table_moves_to_its_own_line() {
179
let mut draft = Draft::default();
180
draft.insert_table(0, Table::new(1, 1));
181
let mark = TABLE_MARK.len_utf8();
182
let mut text = draft.text().to_owned();
183
text.insert(mark, 'x');
184
let cursor = draft.apply_edit(&text, mark + 1, None);
185
assert_eq!(draft.text(), format!("{TABLE_MARK}\nx\n"));
186
assert_eq!(cursor, mark + 2);
187
assert!(draft.lines()[0].is_table());
188
assert_eq!(draft.lines()[1], LineKind::Text);
189
190
let mut text = draft.text().to_owned();
191
text.insert(0, 'y');
192
let cursor = draft.apply_edit(&text, 1, None);
193
assert_eq!(draft.text(), format!("y\n{TABLE_MARK}\nx\n"));
194
assert_eq!(cursor, 1);
195
assert!(draft.lines()[1].is_table());
196
}
197
198
#[test]
199
fn deleting_the_mark_drops_the_table() {
200
let mut draft = Draft::plain("a");
201
draft.insert_table(1, Table::new(1, 1));
202
draft.apply_edit("a\n\n", 2, None);
203
assert!(draft.lines().iter().all(|kind| !kind.is_table()));
204
}
205
206
#[test]
207
fn delete_before_a_table_and_backspace_after_it_find_the_table() {
208
let mut draft = Draft::plain("a");
209
let index = draft.insert_table(1, Table::new(1, 1));
210
assert_eq!(draft.table_after(1), Some(index));
211
assert_eq!(draft.delete_forward(1), Some(1));
212
assert!(draft.lines()[index].is_table());
213
let after = draft.text().len();
214
assert_eq!(draft.table_before(after), Some(index));
215
assert_eq!(draft.table_before(0), None);
216
}
217
218
#[test]
219
fn leaving_a_table_lands_beside_it_and_adds_a_line_when_needed() {
220
let mut draft = Draft::default();
221
draft.insert_table(0, Table::new(1, 1));
222
assert_eq!(draft.line_beside_table(0, false), 0);
223
assert_eq!(draft.lines()[0], LineKind::Text);
224
assert!(draft.lines()[1].is_table());
225
let below = draft.line_beside_table(1, true);
226
assert_eq!(draft.line_at(below), 2);
227
}
228
229
#[test]
230
fn removing_a_table_keeps_the_lines_around_it() {
231
let mut draft = Draft::from_markdown("> a");
232
let index = draft.insert_table(3, Table::new(1, 1));
233
let end = draft.text().len();
234
let mut text = draft.text().to_owned();
235
text.push('z');
236
draft.apply_edit(&text, end + 1, None);
237
let cursor = draft.remove_table(index);
238
assert_eq!(draft.text(), "a\nz");
239
assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Text]);
240
assert_eq!(cursor, 2);
241
}
242
243
#[test]
244
fn quote_and_list_buttons_leave_a_table_alone() {
245
let mut draft = Draft::plain("a");
246
let index = draft.insert_table(1, Table::new(1, 1));
247
let end = draft.text().len();
248
draft.toggle_lines(0..end, LineKind::Quote);
249
assert!(draft.lines()[index].is_table());
250
}
251
252
#[test]
253
fn a_copied_table_pastes_into_the_middle_of_a_line() {
254
let mut source = Draft::default();
255
let index = source.insert_table(0, table_of(&[&["1", "2"]]));
256
let copied = source.slice(0..TABLE_MARK.len_utf8());
257
let mut draft = Draft::plain("abcd");
258
draft.insert_lines(2..2, &copied);
259
assert_eq!(draft.text(), format!("ab\n{TABLE_MARK}\ncd"));
260
assert_eq!(draft.table(1), source.table(index));
261
}
262
263
#[test]
264
fn pasted_markdown_becomes_headings_lists_quotes_code_and_tables() {
265
let markdown = "# Title\n\nSome **bold**, *it*, ~~gone~~, `code` and [docs](https://x.de)\n\n\
266
1. one\n 1. nested\n2. two\n- dot\n - inner\n\n> quoted\n\n```rust\nfn x() {}\n```\n\n\
267
| A | B |\n|---|---|\n| **1** | 2 |\n";
268
let draft = Draft::from_markdown(markdown);
269
let kinds: Vec<LineKind> = draft
270
.lines()
271
.iter()
272
.filter(|kind| **kind != LineKind::Text)
273
.cloned()
274
.collect();
275
assert_eq!(
276
kinds,
277
[
278
LineKind::Heading(1),
279
LineKind::Numbered(0),
280
LineKind::Numbered(1),
281
LineKind::Numbered(0),
282
LineKind::Bullet(0),
283
LineKind::Bullet(1),
284
LineKind::Quote,
285
LineKind::Code(Some("rust".into())),
286
LineKind::Table(table_of(&[&["A", "B"], &["1", "2"]])),
287
]
288
);
289
let html = draft.trimmed().to_html();
290
assert!(html.starts_with("<h1>Title</h1>"), "{html}");
291
assert!(html.contains("<b>bold</b>, <i>it</i>, <s>gone</s>, <code>code</code>"));
292
assert!(html.contains("<a href=\"https://x.de\">docs</a>"));
293
assert!(html.contains("<blockquote>quoted</blockquote>"));
294
assert!(html.contains("<pre class=\"language-rust\">fn x() {}</pre>"));
295
assert!(
296
html.ends_with("<td>1</td><td>2</td></tr></tbody></table></figure>"),
297
"{html}"
298
);
299
}
300
301
#[test]
302
fn text_with_pipes_but_no_delimiter_row_stays_text() {
303
assert!(!teams_core::has_markdown("a | b\nc | d"));
304
assert!(teams_core::has_markdown("| a | b |\n| - | - |"));
305
assert!(teams_core::has_markdown("## Heading"));
306
}
307
308
#[test]
309
fn received_tables_and_headings_edit_as_tables_and_headings() {
310
let spans = html_to_spans(
311
"<h2>Notes</h2><table><tbody><tr><td><p>a</p></td><td>b<br>c</td></tr></tbody></table><p>end</p>",
312
);
313
let draft = Draft::from_spans(&spans);
314
assert_eq!(draft.lines()[0], LineKind::Heading(2));
315
assert_eq!(
316
draft.lines()[1],
317
LineKind::Table(table_of(&[&["a", "b\nc"]]))
318
);
319
assert_eq!(draft.lines()[2], LineKind::Text);
320
}
321
322
#[test]
323
fn pasting_markdown_with_a_table_leaves_the_cursor_after_the_paste() {
324
let markdown = "## Plan\n- dot\n> quoted\n\n| Area | Owner |\n|---|---|\n| Sync | Priya |\nend";
325
let lines = Draft::from_markdown(markdown).slice(0..usize::MAX);
326
let mut draft = Draft::default();
327
let cursor = draft.insert_lines(0..0, &lines);
328
assert_eq!(cursor, draft.text().len(), "{:?}", draft.text());
329
}
330
331
#[test]
332
fn a_sent_table_edits_back_into_the_same_table() {
333
let table = table_of(&[&["a", "x\ny"], &["", "b"]]);
334
let draft = Draft::from_spans(&html_to_spans(&table.to_html()));
335
let LineKind::Table(received) = &draft.lines()[0] else {
336
panic!("{:?}", draft.lines());
337
};
338
assert_eq!(received.rows[0], ["a", "x\ny"]);
339
assert!(received.rows[1][0].trim().is_empty());
340
assert_eq!(received.to_html(), table.to_html());
341
}
@@ -0,0 +1,341 @@1
use teams_core::{2
Draft, DraftLine, LineKind, Mark, MarkKind, TABLE_MARK, Table, TypingStyle, html_to_spans,3
};4
5
fn typed(draft: &mut Draft, text: &str) {6
let mut typing: Option<TypingStyle> = None;7
for character in text.chars() {8
let cursor = draft.text().len();9
let mut next = draft.text().to_owned();10
next.push(character);11
let cursor = draft.apply_edit(&next, cursor + character.len_utf8(), typing.as_ref());12
typing = draft.convert_typed(cursor).map(|(_, style)| style);13
draft.take_edits();14
}15
}16
17
fn typed_draft(text: &str) -> Draft {18
let mut draft = Draft::default();19
typed(&mut draft, text);20
draft21
}22
23
fn enter(draft: &mut Draft, cursor: usize, shift: bool) -> Option<usize> {24
let result = draft.break_line(cursor, shift);25
draft.take_edits();26
result27
}28
29
fn table_of(rows: &[&[&str]]) -> Table {30
Table::from_rows(31
rows.iter()32
.map(|row| row.iter().map(|cell| (*cell).to_owned()).collect())33
.collect(),34
)35
}36
37
#[test]38
fn enter_in_a_quote_adds_a_quote_line_and_enter_on_the_empty_one_leaves() {39
let mut draft = typed_draft(">abc");40
let cursor = enter(&mut draft, 3, false).unwrap();41
assert_eq!(draft.text(), "abc\n");42
assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Quote]);43
let cursor = enter(&mut draft, cursor, false).unwrap();44
assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Text]);45
assert_eq!(cursor, 4);46
assert_eq!(enter(&mut draft, cursor, false), None);47
assert_eq!(draft.to_html(), "<blockquote>abc</blockquote>");48
}49
50
#[test]51
fn enter_on_an_empty_quote_line_in_the_middle_splits_the_quote() {52
let mut draft = Draft::from_markdown("> a\n> \n> b");53
enter(&mut draft, 2, false).unwrap();54
assert_eq!(55
draft.lines(),56
[LineKind::Quote, LineKind::Text, LineKind::Quote]57
);58
}59
60
#[test]61
fn shift_enter_keeps_breaking_inside_the_quote() {62
let mut draft = typed_draft(">a");63
let cursor = enter(&mut draft, 1, true).unwrap();64
let cursor = enter(&mut draft, cursor, true).unwrap();65
assert_eq!(cursor, 3);66
assert_eq!(67
draft.lines(),68
[LineKind::Quote, LineKind::Quote, LineKind::Quote]69
);70
}71
72
#[test]73
fn backspace_at_the_start_of_a_quote_leaves_it_or_joins_the_line_above() {74
let mut empty = typed_draft(">");75
assert_eq!(empty.backspace_at_start(0), Some(0));76
assert_eq!(empty.lines(), [LineKind::Text]);77
78
let mut joined = Draft::from_markdown("x\n> abc");79
assert_eq!(joined.backspace_at_start(2), Some(1));80
assert_eq!(joined.text(), "xabc");81
assert_eq!(joined.lines(), [LineKind::Text]);82
83
let mut inner = Draft::from_markdown("> a\n> b");84
assert_eq!(inner.backspace_at_start(2), Some(1));85
assert_eq!(inner.text(), "ab");86
assert_eq!(inner.lines(), [LineKind::Quote]);87
}88
89
#[test]90
fn down_at_the_end_of_a_closing_quote_opens_a_text_line_below() {91
let mut draft = typed_draft(">abc");92
assert_eq!(draft.leave_quote_at_end(1), None);93
assert_eq!(draft.leave_quote_at_end(3), Some(4));94
assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Text]);95
assert_eq!(Draft::plain("x").leave_quote_at_end(1), None);96
}97
98
#[test]99
fn teams_shortcuts_make_headings_bold_italic_and_code() {100
let heading = typed_draft("## Plan");101
assert_eq!(heading.text(), "Plan");102
assert_eq!(heading.lines(), [LineKind::Heading(2)]);103
assert_eq!(heading.to_html(), "<h2>Plan</h2>");104
assert_eq!(typed_draft("#### deep").lines(), [LineKind::Heading(3)]);105
assert_eq!(typed_draft("#nope").lines(), [LineKind::Text]);106
107
let inline = typed_draft("*b* _i_ `c`");108
assert_eq!(inline.text(), "b i c");109
assert_eq!(110
inline.marks(),111
[112
Mark {113
range: 0..1,114
kind: MarkKind::Bold115
},116
Mark {117
range: 2..3,118
kind: MarkKind::Italic119
},120
Mark {121
range: 4..5,122
kind: MarkKind::Code123
},124
]125
);126
}127
128
#[test]129
fn enter_in_a_heading_is_left_to_send_and_backspace_makes_it_text() {130
let mut draft = typed_draft("# a");131
assert_eq!(enter(&mut draft, 1, false), None);132
assert_eq!(draft.backspace_at_start(0), Some(0));133
assert_eq!(draft.lines(), [LineKind::Text]);134
}135
136
#[test]137
fn an_inserted_table_takes_an_empty_line_and_gets_a_line_after_it() {138
let mut draft = Draft::default();139
let index = draft.insert_table(0, Table::new(2, 3));140
assert_eq!(index, 0);141
assert_eq!(draft.text(), format!("{TABLE_MARK}\n"));142
assert!(draft.lines()[0].is_table());143
assert_eq!(draft.lines()[1], LineKind::Text);144
145
let mut below = Draft::plain("hello");146
assert_eq!(below.insert_table(2, Table::new(1, 1)), 1);147
assert_eq!(below.text(), format!("hello\n{TABLE_MARK}\n"));148
}149
150
#[test]151
fn a_table_is_sent_as_teams_html_between_the_text() {152
let mut draft = Draft::plain("before");153
let index = draft.insert_table(6, Table::new(1, 2));154
draft.set_table(index, table_of(&[&["a", "b"]]));155
let end = draft.text().len();156
let mut text = draft.text().to_owned();157
text.push_str("after");158
draft.apply_edit(&text, end + 5, None);159
assert_eq!(160
draft.trimmed().to_html(),161
"before<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\162
<tr><td>a</td><td>b</td></tr></tbody></table></figure>after"163
);164
assert_eq!(draft.plain_text(), "before\na\tb\nafter");165
assert!(166
!Draft::from_lines(&[DraftLine {167
kind: LineKind::Table(Table::new(1, 1)),168
number: None,169
content: TABLE_MARK.to_string(),170
marks: Vec::new(),171
}])172
.plain_text()173
.contains(TABLE_MARK)174
);175
}176
177
#[test]178
fn text_typed_next_to_a_table_moves_to_its_own_line() {179
let mut draft = Draft::default();180
draft.insert_table(0, Table::new(1, 1));181
let mark = TABLE_MARK.len_utf8();182
let mut text = draft.text().to_owned();183
text.insert(mark, 'x');184
let cursor = draft.apply_edit(&text, mark + 1, None);185
assert_eq!(draft.text(), format!("{TABLE_MARK}\nx\n"));186
assert_eq!(cursor, mark + 2);187
assert!(draft.lines()[0].is_table());188
assert_eq!(draft.lines()[1], LineKind::Text);189
190
let mut text = draft.text().to_owned();191
text.insert(0, 'y');192
let cursor = draft.apply_edit(&text, 1, None);193
assert_eq!(draft.text(), format!("y\n{TABLE_MARK}\nx\n"));194
assert_eq!(cursor, 1);195
assert!(draft.lines()[1].is_table());196
}197
198
#[test]199
fn deleting_the_mark_drops_the_table() {200
let mut draft = Draft::plain("a");201
draft.insert_table(1, Table::new(1, 1));202
draft.apply_edit("a\n\n", 2, None);203
assert!(draft.lines().iter().all(|kind| !kind.is_table()));204
}205
206
#[test]207
fn delete_before_a_table_and_backspace_after_it_find_the_table() {208
let mut draft = Draft::plain("a");209
let index = draft.insert_table(1, Table::new(1, 1));210
assert_eq!(draft.table_after(1), Some(index));211
assert_eq!(draft.delete_forward(1), Some(1));212
assert!(draft.lines()[index].is_table());213
let after = draft.text().len();214
assert_eq!(draft.table_before(after), Some(index));215
assert_eq!(draft.table_before(0), None);216
}217
218
#[test]219
fn leaving_a_table_lands_beside_it_and_adds_a_line_when_needed() {220
let mut draft = Draft::default();221
draft.insert_table(0, Table::new(1, 1));222
assert_eq!(draft.line_beside_table(0, false), 0);223
assert_eq!(draft.lines()[0], LineKind::Text);224
assert!(draft.lines()[1].is_table());225
let below = draft.line_beside_table(1, true);226
assert_eq!(draft.line_at(below), 2);227
}228
229
#[test]230
fn removing_a_table_keeps_the_lines_around_it() {231
let mut draft = Draft::from_markdown("> a");232
let index = draft.insert_table(3, Table::new(1, 1));233
let end = draft.text().len();234
let mut text = draft.text().to_owned();235
text.push('z');236
draft.apply_edit(&text, end + 1, None);237
let cursor = draft.remove_table(index);238
assert_eq!(draft.text(), "a\nz");239
assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Text]);240
assert_eq!(cursor, 2);241
}242
243
#[test]244
fn quote_and_list_buttons_leave_a_table_alone() {245
let mut draft = Draft::plain("a");246
let index = draft.insert_table(1, Table::new(1, 1));247
let end = draft.text().len();248
draft.toggle_lines(0..end, LineKind::Quote);249
assert!(draft.lines()[index].is_table());250
}251
252
#[test]253
fn a_copied_table_pastes_into_the_middle_of_a_line() {254
let mut source = Draft::default();255
let index = source.insert_table(0, table_of(&[&["1", "2"]]));256
let copied = source.slice(0..TABLE_MARK.len_utf8());257
let mut draft = Draft::plain("abcd");258
draft.insert_lines(2..2, &copied);259
assert_eq!(draft.text(), format!("ab\n{TABLE_MARK}\ncd"));260
assert_eq!(draft.table(1), source.table(index));261
}262
263
#[test]264
fn pasted_markdown_becomes_headings_lists_quotes_code_and_tables() {265
let markdown = "# Title\n\nSome **bold**, *it*, ~~gone~~, `code` and [docs](https://x.de)\n\n\266
1. one\n 1. nested\n2. two\n- dot\n - inner\n\n> quoted\n\n```rust\nfn x() {}\n```\n\n\267
| A | B |\n|---|---|\n| **1** | 2 |\n";268
let draft = Draft::from_markdown(markdown);269
let kinds: Vec<LineKind> = draft270
.lines()271
.iter()272
.filter(|kind| **kind != LineKind::Text)273
.cloned()274
.collect();275
assert_eq!(276
kinds,277
[278
LineKind::Heading(1),279
LineKind::Numbered(0),280
LineKind::Numbered(1),281
LineKind::Numbered(0),282
LineKind::Bullet(0),283
LineKind::Bullet(1),284
LineKind::Quote,285
LineKind::Code(Some("rust".into())),286
LineKind::Table(table_of(&[&["A", "B"], &["1", "2"]])),287
]288
);289
let html = draft.trimmed().to_html();290
assert!(html.starts_with("<h1>Title</h1>"), "{html}");291
assert!(html.contains("<b>bold</b>, <i>it</i>, <s>gone</s>, <code>code</code>"));292
assert!(html.contains("<a href=\"https://x.de\">docs</a>"));293
assert!(html.contains("<blockquote>quoted</blockquote>"));294
assert!(html.contains("<pre class=\"language-rust\">fn x() {}</pre>"));295
assert!(296
html.ends_with("<td>1</td><td>2</td></tr></tbody></table></figure>"),297
"{html}"298
);299
}300
301
#[test]302
fn text_with_pipes_but_no_delimiter_row_stays_text() {303
assert!(!teams_core::has_markdown("a | b\nc | d"));304
assert!(teams_core::has_markdown("| a | b |\n| - | - |"));305
assert!(teams_core::has_markdown("## Heading"));306
}307
308
#[test]309
fn received_tables_and_headings_edit_as_tables_and_headings() {310
let spans = html_to_spans(311
"<h2>Notes</h2><table><tbody><tr><td><p>a</p></td><td>b<br>c</td></tr></tbody></table><p>end</p>",312
);313
let draft = Draft::from_spans(&spans);314
assert_eq!(draft.lines()[0], LineKind::Heading(2));315
assert_eq!(316
draft.lines()[1],317
LineKind::Table(table_of(&[&["a", "b\nc"]]))318
);319
assert_eq!(draft.lines()[2], LineKind::Text);320
}321
322
#[test]323
fn pasting_markdown_with_a_table_leaves_the_cursor_after_the_paste() {324
let markdown = "## Plan\n- dot\n> quoted\n\n| Area | Owner |\n|---|---|\n| Sync | Priya |\nend";325
let lines = Draft::from_markdown(markdown).slice(0..usize::MAX);326
let mut draft = Draft::default();327
let cursor = draft.insert_lines(0..0, &lines);328
assert_eq!(cursor, draft.text().len(), "{:?}", draft.text());329
}330
331
#[test]332
fn a_sent_table_edits_back_into_the_same_table() {333
let table = table_of(&[&["a", "x\ny"], &["", "b"]]);334
let draft = Draft::from_spans(&html_to_spans(&table.to_html()));335
let LineKind::Table(received) = &draft.lines()[0] else {336
panic!("{:?}", draft.lines());337
};338
assert_eq!(received.rows[0], ["a", "x\ny"]);339
assert!(received.rows[1][0].trim().is_empty());340
assert_eq!(received.to_html(), table.to_html());341
}@@ -69,22 +69,6 @@ async fn main() {
69
69
}
70
70
Err(error) => println!("photos failed: {}", status_of(&error)),
71
71
}
72
73
let started = Instant::now();
74
match graph.presences(&user_ids).await {
75
Ok(found) => {
76
let mut counts: BTreeMap<String, usize> = BTreeMap::new();
77
for presence in &found {
78
*counts.entry(presence.availability.clone()).or_default() += 1;
79
}
80
println!(
81
"teams presence ok {} {counts:?} in {} ms",
82
found.len(),
83
started.elapsed().as_millis()
84
);
85
}
86
Err(error) => println!("teams presence failed: {}", status_of(&error)),
87
}
88
72
}
89
73
90
74
fn status_of(error: &graph::Error) -> String {
@@ -69,22 +69,6 @@ async fn main() {69
}69
}70
Err(error) => println!("photos failed: {}", status_of(&error)),70
Err(error) => println!("photos failed: {}", status_of(&error)),71
}71
}72
73
let started = Instant::now();74
match graph.presences(&user_ids).await {75
Ok(found) => {76
let mut counts: BTreeMap<String, usize> = BTreeMap::new();77
for presence in &found {78
*counts.entry(presence.availability.clone()).or_default() += 1;79
}80
println!(81
"teams presence ok {} {counts:?} in {} ms",82
found.len(),83
started.elapsed().as_millis()84
);85
}86
Err(error) => println!("teams presence failed: {}", status_of(&error)),87
}88
}72
}89
73
90
fn status_of(error: &graph::Error) -> String {74
fn status_of(error: &graph::Error) -> String {@@ -23,13 +23,12 @@ 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,
30
30
hosted_image_order,
31
31
};
32
32
pub use page::Page;
33
pub use people::MAX_PRESENCE_IDS;
34
33
pub use profile::{OrgPerson, ProfileDetails, UserProfile};
35
34
pub use target::MessageTarget;
@@ -23,13 +23,12 @@ pub use files::{23
pub use library::DriveEntry;23
pub use library::DriveEntry;24
pub use models::{24
pub 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
};28
pub use outgoing::{28
pub use outgoing::{29
FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, OutgoingMention,29
FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, OutgoingMention,30
hosted_image_order,30
hosted_image_order,31
};31
};32
pub use page::Page;32
pub use page::Page;33
pub use people::MAX_PRESENCE_IDS;34
pub use profile::{OrgPerson, ProfileDetails, UserProfile};33
pub use profile::{OrgPerson, ProfileDetails, UserProfile};35
pub use target::MessageTarget;34
pub use target::MessageTarget;@@ -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 @@1
use chrono::{DateTime, Utc};1
use chrono::{DateTime, Utc};2
use serde::Deserialize;2
use serde::Deserialize;3
3
4
pub 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")]6
pub struct User {8
pub struct User {@@ -22,6 +24,17 @@ pub struct Member {22
pub email: Option<String>,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
#[derive(Debug, Clone, Deserialize, PartialEq)]38
#[derive(Debug, Clone, Deserialize, PartialEq)]26
#[serde(rename_all = "camelCase")]39
#[serde(rename_all = "camelCase")]27
pub struct Identity {40
pub struct Identity {@@ -160,13 +173,7 @@ impl Chat {160
.members173
.members161
.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
member165
.display_name166
.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)@@ -1,24 +1,14 @@
1
1
use base64::Engine as _;
2
2
use base64::engine::general_purpose::STANDARD;
3
3
use serde::Deserialize;
4
use serde_json::{Value, json};
5
use session::{ApiResponse, Method, PRESENCE, Request, Scope};
6
use uuid::Uuid;
4
use session::{ApiResponse, Request, Scope};
7
5
8
6
use crate::client::{BATCH_SIZE, Graph};
9
7
use crate::error::{Error, Result};
10
use crate::models::{Photo, Presence};
8
use crate::models::Photo;
11
9
use crate::urls;
12
10
13
pub const MAX_PRESENCE_IDS: usize = 650;
14
pub const MAX_SUBSCRIBE_IDS: usize = 200;
15
11
const PHOTO_SCOPE: &str = "User.ReadBasic.All";
16
const PRESENCE_SERVICE_URL: &str = "https://presence.teams.microsoft.com/v1/presence/getpresence/";
17
const PRESENCE_SERVICE_SCOPE: &str = "user_impersonation";
18
const PRESENCE_SUBSCRIBE_URL: &str =
19
"https://presence.teams.microsoft.com/v1/pubsub/subscriptions/";
20
const PRESENCE_CLIENT_VERSION: &str = "1415/26091712213";
21
const ORGID_PREFIX: &str = "8:orgid:";
22
12
23
13
#[derive(Debug, Deserialize)]
24
14
struct BinaryBody {
@@ -47,77 +37,6 @@ impl Graph {
47
37
}
48
38
Ok(photos)
49
39
}
50
51
/// Teams presence service. Graph `Presence.Read.All` is not in the web app tokens.
52
pub async fn presences(&self, user_ids: &[String]) -> Result<Vec<Presence>> {
53
let scope = Scope::new(PRESENCE, PRESENCE_SERVICE_SCOPE);
54
let mut presences = Vec::with_capacity(user_ids.len());
55
for chunk in user_ids.chunks(MAX_PRESENCE_IDS) {
56
let body: Vec<Value> = chunk
57
.iter()
58
.map(|user_id| json!({"mri": format!("{ORGID_PREFIX}{user_id}")}))
59
.collect();
60
let answer = self
61
.session()
62
.request(
63
Method::Post,
64
PRESENCE_SERVICE_URL,
65
&scope,
66
Some(Value::Array(body)),
67
)
68
.await?;
69
presences.extend(parse_service_presences(&answer.body));
70
}
71
Ok(presences)
72
}
73
74
pub async fn subscribe_presence(
75
&self,
76
endpoint_id: &str,
77
trouter_uri: &str,
78
user_ids: &[String],
79
purge: bool,
80
) -> Result<()> {
81
let scope = Scope::new(PRESENCE, PRESENCE_SERVICE_SCOPE);
82
let url = format!("{PRESENCE_SUBSCRIBE_URL}{endpoint_id}");
83
for (index, chunk) in user_ids.chunks(MAX_SUBSCRIBE_IDS).enumerate() {
84
let request = Request {
85
method: Method::Post,
86
headers: subscribe_headers(endpoint_id),
87
body: Some(subscribe_body(trouter_uri, chunk, purge && index == 0)),
88
..Request::get(url.clone())
89
};
90
let answer = self.session().send(request, &scope).await?;
91
if !(200..300).contains(&answer.status) {
92
return Err(session::Error::api(answer.status, &url, answer.body).into());
93
}
94
}
95
Ok(())
96
}
97
}
98
99
// The service answers 400 naming each of the three x-ms-* client headers when one is missing.
100
fn subscribe_headers(endpoint_id: &str) -> Vec<(String, String)> {
101
vec![
102
("x-ms-client-user-agent".into(), "Teams-V2-Web".into()),
103
("x-ms-correlation-id".into(), Uuid::new_v4().to_string()),
104
("x-ms-client-version".into(), PRESENCE_CLIENT_VERSION.into()),
105
("x-ms-endpoint-id".into(), endpoint_id.into()),
106
("x-ms-client-type".into(), "cdlworker".into()),
107
]
108
}
109
110
fn subscribe_body(trouter_uri: &str, user_ids: &[String], purge: bool) -> Value {
111
let additions: Vec<Value> = user_ids
112
.iter()
113
.map(|user_id| json!({"mri": format!("{ORGID_PREFIX}{user_id}"), "source": "ups"}))
114
.collect();
115
json!({
116
"trouterUri": trouter_uri,
117
"shouldPurgePreviousSubscriptions": purge,
118
"subscriptionsToAdd": additions,
119
"subscriptionsToRemove": [],
120
})
121
40
}
122
41
123
42
fn parse_photo(url: &str, answer: ApiResponse) -> Result<Option<Photo>> {
@@ -143,35 +62,10 @@ pub(crate) fn decode_binary(url: &str, answer: ApiResponse) -> Result<Photo> {
143
62
}
144
63
}
145
64
146
fn parse_service_presences(body: &Value) -> Vec<Presence> {
147
body.as_array()
148
.into_iter()
149
.flatten()
150
.filter_map(|entry| {
151
let mri = entry.get("mri")?.as_str()?;
152
let presence = entry.get("presence")?;
153
Some(Presence {
154
user_id: mri.strip_prefix(ORGID_PREFIX).unwrap_or(mri).to_owned(),
155
availability: presence.get("availability")?.as_str()?.to_owned(),
156
activity: if presence
157
.pointer("/calendarData/isOutOfOffice")
158
.and_then(Value::as_bool)
159
.unwrap_or(false)
160
{
161
Some("OutOfOffice".to_owned())
162
} else {
163
presence
164
.get("activity")
165
.and_then(Value::as_str)
166
.map(str::to_owned)
167
},
168
})
169
})
170
.collect()
171
}
172
173
65
#[cfg(test)]
174
66
mod tests {
67
use serde_json::{Value, json};
68
175
69
use super::*;
176
70
177
71
fn answer(status: u16, body: Value) -> ApiResponse {
@@ -195,55 +89,4 @@ mod tests {
195
89
assert!(parse_photo("u", answer(404, json!("x"))).unwrap().is_none());
196
90
assert!(parse_photo("u", answer(403, json!("x"))).is_err());
197
91
}
198
199
#[test]
200
fn subscribe_body_carries_mris_and_purge_flag() {
201
let body = subscribe_body("https://t/unifiedPresenceService", &["a".into()], true);
202
assert_eq!(
203
body,
204
json!({
205
"trouterUri": "https://t/unifiedPresenceService",
206
"shouldPurgePreviousSubscriptions": true,
207
"subscriptionsToAdd": [{"mri": "8:orgid:a", "source": "ups"}],
208
"subscriptionsToRemove": [],
209
})
210
);
211
}
212
213
#[test]
214
fn subscribe_headers_use_a_fresh_correlation_id() {
215
let correlation = |headers: &[(String, String)]| {
216
headers
217
.iter()
218
.find(|(name, _)| name == "x-ms-correlation-id")
219
.map(|(_, value)| value.clone())
220
};
221
let first = subscribe_headers("e");
222
assert_ne!(correlation(&first), correlation(&subscribe_headers("e")));
223
assert!(
224
first
225
.iter()
226
.any(|(name, value)| name == "x-ms-endpoint-id" && value == "e")
227
);
228
}
229
230
#[test]
231
fn service_presences_strip_the_mri_prefix() {
232
let parsed = parse_service_presences(&json!([
233
{"mri": "8:orgid:a", "presence": {"availability": "Away", "activity": "Away"}},
234
{"mri": "8:orgid:b"}
235
]));
236
assert_eq!(parsed.len(), 1);
237
assert_eq!(parsed[0].user_id, "a");
238
}
239
240
#[test]
241
fn out_of_office_from_the_calendar_becomes_the_activity() {
242
let parsed = parse_service_presences(&json!([
243
{"mri": "8:orgid:a", "presence": {"availability": "Offline", "activity": "OffWork", "calendarData": {"isOutOfOffice": true}}},
244
{"mri": "8:orgid:b", "presence": {"availability": "Available", "activity": "Available", "calendarData": {"isOutOfOffice": false}}}
245
]));
246
assert_eq!(parsed[0].activity.as_deref(), Some("OutOfOffice"));
247
assert_eq!(parsed[1].activity.as_deref(), Some("Available"));
248
}
249
92
}
@@ -1,24 +1,14 @@1
use base64::Engine as _;1
use base64::Engine as _;2
use base64::engine::general_purpose::STANDARD;2
use base64::engine::general_purpose::STANDARD;3
use serde::Deserialize;3
use serde::Deserialize;4
use serde_json::{Value, json};4
use session::{ApiResponse, Request, Scope};5
use session::{ApiResponse, Method, PRESENCE, Request, Scope};6
use uuid::Uuid;7
5
8
use crate::client::{BATCH_SIZE, Graph};6
use crate::client::{BATCH_SIZE, Graph};9
use crate::error::{Error, Result};7
use crate::error::{Error, Result};10
use crate::models::{Photo, Presence};8
use crate::models::Photo;11
use crate::urls;9
use crate::urls;12
10
13
pub const MAX_PRESENCE_IDS: usize = 650;14
pub const MAX_SUBSCRIBE_IDS: usize = 200;15
const PHOTO_SCOPE: &str = "User.ReadBasic.All";11
const PHOTO_SCOPE: &str = "User.ReadBasic.All";16
const PRESENCE_SERVICE_URL: &str = "https://presence.teams.microsoft.com/v1/presence/getpresence/";17
const PRESENCE_SERVICE_SCOPE: &str = "user_impersonation";18
const PRESENCE_SUBSCRIBE_URL: &str =19
"https://presence.teams.microsoft.com/v1/pubsub/subscriptions/";20
const PRESENCE_CLIENT_VERSION: &str = "1415/26091712213";21
const ORGID_PREFIX: &str = "8:orgid:";22
12
23
#[derive(Debug, Deserialize)]13
#[derive(Debug, Deserialize)]24
struct BinaryBody {14
struct BinaryBody {@@ -47,77 +37,6 @@ impl Graph {47
}37
}48
Ok(photos)38
Ok(photos)49
}39
}50
51
/// Teams presence service. Graph `Presence.Read.All` is not in the web app tokens.52
pub async fn presences(&self, user_ids: &[String]) -> Result<Vec<Presence>> {53
let scope = Scope::new(PRESENCE, PRESENCE_SERVICE_SCOPE);54
let mut presences = Vec::with_capacity(user_ids.len());55
for chunk in user_ids.chunks(MAX_PRESENCE_IDS) {56
let body: Vec<Value> = chunk57
.iter()58
.map(|user_id| json!({"mri": format!("{ORGID_PREFIX}{user_id}")}))59
.collect();60
let answer = self61
.session()62
.request(63
Method::Post,64
PRESENCE_SERVICE_URL,65
&scope,66
Some(Value::Array(body)),67
)68
.await?;69
presences.extend(parse_service_presences(&answer.body));70
}71
Ok(presences)72
}73
74
pub async fn subscribe_presence(75
&self,76
endpoint_id: &str,77
trouter_uri: &str,78
user_ids: &[String],79
purge: bool,80
) -> Result<()> {81
let scope = Scope::new(PRESENCE, PRESENCE_SERVICE_SCOPE);82
let url = format!("{PRESENCE_SUBSCRIBE_URL}{endpoint_id}");83
for (index, chunk) in user_ids.chunks(MAX_SUBSCRIBE_IDS).enumerate() {84
let request = Request {85
method: Method::Post,86
headers: subscribe_headers(endpoint_id),87
body: Some(subscribe_body(trouter_uri, chunk, purge && index == 0)),88
..Request::get(url.clone())89
};90
let answer = self.session().send(request, &scope).await?;91
if !(200..300).contains(&answer.status) {92
return Err(session::Error::api(answer.status, &url, answer.body).into());93
}94
}95
Ok(())96
}97
}98
99
// The service answers 400 naming each of the three x-ms-* client headers when one is missing.100
fn subscribe_headers(endpoint_id: &str) -> Vec<(String, String)> {101
vec![102
("x-ms-client-user-agent".into(), "Teams-V2-Web".into()),103
("x-ms-correlation-id".into(), Uuid::new_v4().to_string()),104
("x-ms-client-version".into(), PRESENCE_CLIENT_VERSION.into()),105
("x-ms-endpoint-id".into(), endpoint_id.into()),106
("x-ms-client-type".into(), "cdlworker".into()),107
]108
}109
110
fn subscribe_body(trouter_uri: &str, user_ids: &[String], purge: bool) -> Value {111
let additions: Vec<Value> = user_ids112
.iter()113
.map(|user_id| json!({"mri": format!("{ORGID_PREFIX}{user_id}"), "source": "ups"}))114
.collect();115
json!({116
"trouterUri": trouter_uri,117
"shouldPurgePreviousSubscriptions": purge,118
"subscriptionsToAdd": additions,119
"subscriptionsToRemove": [],120
})121
}40
}122
41
123
fn parse_photo(url: &str, answer: ApiResponse) -> Result<Option<Photo>> {42
fn parse_photo(url: &str, answer: ApiResponse) -> Result<Option<Photo>> {@@ -143,35 +62,10 @@ pub(crate) fn decode_binary(url: &str, answer: ApiResponse) -> Result<Photo> {143
}62
}144
}63
}145
64
146
fn parse_service_presences(body: &Value) -> Vec<Presence> {147
body.as_array()148
.into_iter()149
.flatten()150
.filter_map(|entry| {151
let mri = entry.get("mri")?.as_str()?;152
let presence = entry.get("presence")?;153
Some(Presence {154
user_id: mri.strip_prefix(ORGID_PREFIX).unwrap_or(mri).to_owned(),155
availability: presence.get("availability")?.as_str()?.to_owned(),156
activity: if presence157
.pointer("/calendarData/isOutOfOffice")158
.and_then(Value::as_bool)159
.unwrap_or(false)160
{161
Some("OutOfOffice".to_owned())162
} else {163
presence164
.get("activity")165
.and_then(Value::as_str)166
.map(str::to_owned)167
},168
})169
})170
.collect()171
}172
173
#[cfg(test)]65
#[cfg(test)]174
mod tests {66
mod tests {67
use serde_json::{Value, json};68
175
use super::*;69
use super::*;176
70
177
fn answer(status: u16, body: Value) -> ApiResponse {71
fn answer(status: u16, body: Value) -> ApiResponse {@@ -195,55 +89,4 @@ mod tests {195
assert!(parse_photo("u", answer(404, json!("x"))).unwrap().is_none());89
assert!(parse_photo("u", answer(404, json!("x"))).unwrap().is_none());196
assert!(parse_photo("u", answer(403, json!("x"))).is_err());90
assert!(parse_photo("u", answer(403, json!("x"))).is_err());197
}91
}198
199
#[test]200
fn subscribe_body_carries_mris_and_purge_flag() {201
let body = subscribe_body("https://t/unifiedPresenceService", &["a".into()], true);202
assert_eq!(203
body,204
json!({205
"trouterUri": "https://t/unifiedPresenceService",206
"shouldPurgePreviousSubscriptions": true,207
"subscriptionsToAdd": [{"mri": "8:orgid:a", "source": "ups"}],208
"subscriptionsToRemove": [],209
})210
);211
}212
213
#[test]214
fn subscribe_headers_use_a_fresh_correlation_id() {215
let correlation = |headers: &[(String, String)]| {216
headers217
.iter()218
.find(|(name, _)| name == "x-ms-correlation-id")219
.map(|(_, value)| value.clone())220
};221
let first = subscribe_headers("e");222
assert_ne!(correlation(&first), correlation(&subscribe_headers("e")));223
assert!(224
first225
.iter()226
.any(|(name, value)| name == "x-ms-endpoint-id" && value == "e")227
);228
}229
230
#[test]231
fn service_presences_strip_the_mri_prefix() {232
let parsed = parse_service_presences(&json!([233
{"mri": "8:orgid:a", "presence": {"availability": "Away", "activity": "Away"}},234
{"mri": "8:orgid:b"}235
]));236
assert_eq!(parsed.len(), 1);237
assert_eq!(parsed[0].user_id, "a");238
}239
240
#[test]241
fn out_of_office_from_the_calendar_becomes_the_activity() {242
let parsed = parse_service_presences(&json!([243
{"mri": "8:orgid:a", "presence": {"availability": "Offline", "activity": "OffWork", "calendarData": {"isOutOfOffice": true}}},244
{"mri": "8:orgid:b", "presence": {"availability": "Available", "activity": "Available", "calendarData": {"isOutOfOffice": false}}}245
]));246
assert_eq!(parsed[0].activity.as_deref(), Some("OutOfOffice"));247
assert_eq!(parsed[1].activity.as_deref(), Some("Available"));248
}249
}92
}@@ -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
};36
pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};36
pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};37
pub use store::{DATA_DIR_NAME, Store, default_database_path};37
pub use store::{DATA_DIR_NAME, Store, default_database_path};@@ -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};4
use rusqlite::{OptionalExtension, Row, params, params_from_iter};4
use rusqlite::{OptionalExtension, Row, params, params_from_iter};5
5
6
use crate::error::Result;6
use crate::error::Result;7
use crate::models::{MessageRecord, RecentScope};7
use crate::models::{MessageRecord, RecentScope, UNKNOWN_USER_NAME};8
use crate::search::index_message;8
use crate::search::index_message;9
use crate::store::Store;9
use crate::store::Store;10
use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis};10
use 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_members372
(SELECT display_name FROM chat_members373
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 messages374
(SELECT sender_name FROM messages375
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();@@ -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;3
use chrono::{DateTime, Utc};3
use chrono::{DateTime, Utc};4
4
5
pub const BOT_MRI_PREFIX: &str = "28:";5
pub const BOT_MRI_PREFIX: &str = "28:";6
pub const UNKNOWN_USER_NAME: &str = "Unknown User";6
7
7
pub fn is_bot_id(user_id: &str) -> bool {8
pub fn is_bot_id(user_id: &str) -> bool {8
user_id.starts_with(BOT_MRI_PREFIX)9
user_id.starts_with(BOT_MRI_PREFIX)@@ -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]1177
fn display_names_prefer_members_then_latest_sender_name() {1177
fn 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
store1186
store1180
.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()),@@ -3,9 +3,9 @@ use std::rc::Rc;
3
3
use gpui::prelude::FluentBuilder as _;
4
4
use gpui::{
5
5
AccessibleAction, AnyElement, App, DefiniteLength, Edges, ElementId, Entity, Hsla,
6
InteractiveElement as _, IntoElement, ParentElement as _, Rems, RenderOnce, Role, SharedString,
7
StatefulInteractiveElement as _, StyleRefinement, Styled, TextAlign, TouchPhase, Window, div,
8
px, relative,
6
InteractiveElement as _, IntoElement, ParentElement as _, Pixels, Rems, RenderOnce, Role,
7
SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, TextAlign, TouchPhase,
8
Window, div, px, relative,
9
9
};
10
10
11
11
use crate::button::{Button, ButtonRounded, ButtonVariants as _};
@@ -119,6 +119,7 @@ pub struct Input {
119
119
prefix: Option<AnyElement>,
120
120
suffix: Option<AnyElement>,
121
121
height: Option<DefiniteLength>,
122
line_box_height: Option<Pixels>,
122
123
appearance: bool,
123
124
cleanable: bool,
124
125
mask_toggle: bool,
@@ -246,6 +247,7 @@ impl Input {
246
247
aria_label: None,
247
248
context_menu_builder: None,
248
249
paste_handler: None,
250
line_box_height: None,
249
251
token_renderer: None,
250
252
token_click_listener: None,
251
253
token_hover_listener: None,
@@ -295,6 +297,14 @@ impl Input {
295
297
self
296
298
}
297
299
300
/// Center each text line of a multi-line input in a box this tall, in
301
/// place of the size's vertical padding, so a single line is exactly this
302
/// tall and lines up with controls of the same height beside it.
303
pub fn line_box_height(mut self, height: Pixels) -> Self {
304
self.line_box_height = Some(height);
305
self
306
}
307
298
308
/// Set the appearance of the input field, if false the input field will no border, background.
299
309
pub fn appearance(mut self, appearance: bool) -> Self {
300
310
self.appearance = appearance;
@@ -588,12 +598,15 @@ impl RenderOnce for Input {
588
598
},
589
599
cx,
590
600
);
601
let padding_y = self.line_box_height.map_or(self.size.input_py(), |height| {
602
((height - LINE_HEIGHT.to_pixels(window.rem_size())) / 2.).max(px(0.))
603
});
591
604
state.set_editor_paddings(
592
605
if state.presentation(cx).is_multi_line() {
593
606
Edges {
594
top: self.size.input_py(),
607
top: padding_y,
595
608
right: self.size.input_px(),
596
bottom: self.size.input_py(),
609
bottom: padding_y,
597
610
left: if state.presentation(cx).is_code_editor() {
598
611
self.size.input_px().min(px(6.))
599
612
} else {
@@ -3,9 +3,9 @@ use std::rc::Rc;3
use gpui::prelude::FluentBuilder as _;3
use gpui::prelude::FluentBuilder as _;4
use gpui::{4
use gpui::{5
AccessibleAction, AnyElement, App, DefiniteLength, Edges, ElementId, Entity, Hsla,5
AccessibleAction, AnyElement, App, DefiniteLength, Edges, ElementId, Entity, Hsla,6
InteractiveElement as _, IntoElement, ParentElement as _, Rems, RenderOnce, Role, SharedString,6
InteractiveElement as _, IntoElement, ParentElement as _, Pixels, Rems, RenderOnce, Role,7
StatefulInteractiveElement as _, StyleRefinement, Styled, TextAlign, TouchPhase, Window, div,7
SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, TextAlign, TouchPhase,8
px, relative,8
Window, div, px, relative,9
};9
};10
10
11
use crate::button::{Button, ButtonRounded, ButtonVariants as _};11
use crate::button::{Button, ButtonRounded, ButtonVariants as _};@@ -119,6 +119,7 @@ pub struct Input {119
prefix: Option<AnyElement>,119
prefix: Option<AnyElement>,120
suffix: Option<AnyElement>,120
suffix: Option<AnyElement>,121
height: Option<DefiniteLength>,121
height: Option<DefiniteLength>,122
line_box_height: Option<Pixels>,122
appearance: bool,123
appearance: bool,123
cleanable: bool,124
cleanable: bool,124
mask_toggle: bool,125
mask_toggle: bool,@@ -246,6 +247,7 @@ impl Input {246
aria_label: None,247
aria_label: None,247
context_menu_builder: None,248
context_menu_builder: None,248
paste_handler: None,249
paste_handler: None,250
line_box_height: None,249
token_renderer: None,251
token_renderer: None,250
token_click_listener: None,252
token_click_listener: None,251
token_hover_listener: None,253
token_hover_listener: None,@@ -295,6 +297,14 @@ impl Input {295
self297
self296
}298
}297
299
300
/// Center each text line of a multi-line input in a box this tall, in301
/// place of the size's vertical padding, so a single line is exactly this302
/// tall and lines up with controls of the same height beside it.303
pub fn line_box_height(mut self, height: Pixels) -> Self {304
self.line_box_height = Some(height);305
self306
}307
298
/// Set the appearance of the input field, if false the input field will no border, background.308
/// Set the appearance of the input field, if false the input field will no border, background.299
pub fn appearance(mut self, appearance: bool) -> Self {309
pub fn appearance(mut self, appearance: bool) -> Self {300
self.appearance = appearance;310
self.appearance = appearance;@@ -588,12 +598,15 @@ impl RenderOnce for Input {588
},598
},589
cx,599
cx,590
);600
);601
let padding_y = self.line_box_height.map_or(self.size.input_py(), |height| {602
((height - LINE_HEIGHT.to_pixels(window.rem_size())) / 2.).max(px(0.))603
});591
state.set_editor_paddings(604
state.set_editor_paddings(592
if state.presentation(cx).is_multi_line() {605
if state.presentation(cx).is_multi_line() {593
Edges {606
Edges {594
top: self.size.input_py(),607
top: padding_y,595
right: self.size.input_px(),608
right: self.size.input_px(),596
bottom: self.size.input_py(),609
bottom: padding_y,597
left: if state.presentation(cx).is_code_editor() {610
left: if state.presentation(cx).is_code_editor() {598
self.size.input_px().min(px(6.))611
self.size.input_px().min(px(6.))599
} else {612
} else {@@ -1,8 +1,8 @@
1
1
use std::rc::Rc;
2
2
3
3
use gpui::{
4
App, DefiniteLength, Entity, IntoElement, RenderOnce, SharedString, StyleRefinement, Styled,
5
Window, prelude::FluentBuilder as _,
4
App, DefiniteLength, Entity, IntoElement, Pixels, RenderOnce, SharedString, StyleRefinement,
5
Styled, Window, prelude::FluentBuilder as _,
6
6
};
7
7
8
8
use super::{Input, TextareaState};
@@ -19,6 +19,7 @@ pub struct Textarea {
19
19
style: StyleRefinement,
20
20
size: Size,
21
21
height: Option<DefiniteLength>,
22
line_box_height: Option<Pixels>,
22
23
appearance: bool,
23
24
bordered: bool,
24
25
disabled: bool,
@@ -73,6 +74,7 @@ impl Textarea {
73
74
style: StyleRefinement::default(),
74
75
size: Size::default(),
75
76
height: None,
77
line_box_height: None,
76
78
appearance: true,
77
79
bordered: true,
78
80
disabled: false,
@@ -94,6 +96,12 @@ impl Textarea {
94
96
self
95
97
}
96
98
99
/// See [`Input::line_box_height`].
100
pub fn line_box_height(mut self, height: Pixels) -> Self {
101
self.line_box_height = Some(height);
102
self
103
}
104
97
105
pub fn appearance(mut self, appearance: bool) -> Self {
98
106
self.appearance = appearance;
99
107
self
@@ -204,6 +212,9 @@ impl Textarea {
204
212
.role(self.role)
205
213
.with_size(self.size)
206
214
.when_some(self.height, |this, height| this.h(height))
215
.when_some(self.line_box_height, |this, height| {
216
this.line_box_height(height)
217
})
207
218
.when_some(self.accessibility_id, |this, id| this.accessibility_id(id))
208
219
.when_some(self.aria_label, |this, label| this.aria_label(label))
209
220
.when_some(self.context_menu_builder, |this, build| {
@@ -1,8 +1,8 @@1
use std::rc::Rc;1
use std::rc::Rc;2
2
3
use gpui::{3
use gpui::{4
App, DefiniteLength, Entity, IntoElement, RenderOnce, SharedString, StyleRefinement, Styled,4
App, DefiniteLength, Entity, IntoElement, Pixels, RenderOnce, SharedString, StyleRefinement,5
Window, prelude::FluentBuilder as _,5
Styled, Window, prelude::FluentBuilder as _,6
};6
};7
7
8
use super::{Input, TextareaState};8
use super::{Input, TextareaState};@@ -19,6 +19,7 @@ pub struct Textarea {19
style: StyleRefinement,19
style: StyleRefinement,20
size: Size,20
size: Size,21
height: Option<DefiniteLength>,21
height: Option<DefiniteLength>,22
line_box_height: Option<Pixels>,22
appearance: bool,23
appearance: bool,23
bordered: bool,24
bordered: bool,24
disabled: bool,25
disabled: bool,@@ -73,6 +74,7 @@ impl Textarea {73
style: StyleRefinement::default(),74
style: StyleRefinement::default(),74
size: Size::default(),75
size: Size::default(),75
height: None,76
height: None,77
line_box_height: None,76
appearance: true,78
appearance: true,77
bordered: true,79
bordered: true,78
disabled: false,80
disabled: false,@@ -94,6 +96,12 @@ impl Textarea {94
self96
self95
}97
}96
98
99
/// See [`Input::line_box_height`].100
pub fn line_box_height(mut self, height: Pixels) -> Self {101
self.line_box_height = Some(height);102
self103
}104
97
pub fn appearance(mut self, appearance: bool) -> Self {105
pub fn appearance(mut self, appearance: bool) -> Self {98
self.appearance = appearance;106
self.appearance = appearance;99
self107
self@@ -204,6 +212,9 @@ impl Textarea {204
.role(self.role)212
.role(self.role)205
.with_size(self.size)213
.with_size(self.size)206
.when_some(self.height, |this, height| this.h(height))214
.when_some(self.height, |this, height| this.h(height))215
.when_some(self.line_box_height, |this, height| {216
this.line_box_height(height)217
})207
.when_some(self.accessibility_id, |this, id| this.accessibility_id(id))218
.when_some(self.accessibility_id, |this, id| this.accessibility_id(id))208
.when_some(self.aria_label, |this, label| this.aria_label(label))219
.when_some(self.aria_label, |this, label| this.aria_label(label))209
.when_some(self.context_menu_builder, |this, build| {220
.when_some(self.context_menu_builder, |this, build| {