BlueGit

ict rusty-teams

feat(core): draft tables, headings and Teams quote keys

- Table model with Tab walk, row/column edits, GFM table parser
- Teams table HTML: figure.table + copy-paste-table, empty cell  
- LineKind::Heading (h1-h3) and LineKind::Table in the draft
- quote like Teams: `>` converts at once, Enter on empty line leaves, Backspace joins
- `*x*` types bold like Teams; pasted markdown headings and tables
- deviation: quote and text lines still joined with <br>, Teams uses <p>

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-17 · 6 weeks ago

Hash
743b347d5d9941dcc447abc28935db5e5bf35af1
Parent
1c2a98df
4 files changed +989 −35
crates/core/src/draft.rs +285 −26
@@ -6,8 +6,10 @@ use serde::{Deserialize, Serialize};
6 6
7 7 use crate::markdown::escape_html;
8 8 use crate::spans::{FontSize, Span};
9 use crate::table::{TABLE_MARK, Table, markdown_table};
9 10
10 11 pub const MAX_DEPTH: u8 = 2;
12 pub const MAX_HEADING: u8 = 3;
11 13 pub const OBJECT_MARK: char = '\u{FFFC}';
12 14 const BULLETS: [&str; 3] = ["•", "◦", "▪"];
13 15 const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "];
@@ -125,6 +127,8 @@ pub enum LineKind {
125 127 Numbered(u8),
126 128 Quote,
127 129 Code(Option<String>),
130 Heading(u8),
131 Table(Table),
128 132 }
129 133
130 134 impl LineKind {
@@ -132,6 +136,10 @@ impl LineKind {
132 136 matches!(self, LineKind::Bullet(_) | LineKind::Numbered(_))
133 137 }
134 138
139 pub fn is_table(&self) -> bool {
140 matches!(self, LineKind::Table(_))
141 }
142
135 143 pub fn depth(&self) -> u8 {
136 144 match self {
137 145 LineKind::Bullet(depth) | LineKind::Numbered(depth) => *depth,
@@ -430,7 +438,10 @@ impl Draft {
430 438 pub fn plain_text(&self) -> String {
431 439 self.slice(0..self.text.len())
432 440 .into_iter()
433 .map(|line| line.content)
441 .map(|line| match &line.kind {
442 LineKind::Table(table) => table.plain_text(),
443 _ => line.content,
444 })
434 445 .collect::<Vec<_>>()
435 446 .join("\n")
436 447 .replace(&format!(" {OBJECT_MARK} "), " ")
@@ -762,7 +773,11 @@ impl Draft {
762 773 self.splice(content.clone(), "", &[]);
763 774 Some(self.set_line_kind(index, LineKind::Code(language), None, content.start))
764 775 }
765 LineKind::Quote if !shift => None,
776 LineKind::Heading(_) | LineKind::Table(_) => None,
777 LineKind::Quote if content.is_empty() && !shift => {
778 self.lines[index] = LineKind::Text;
779 Some(cursor)
780 }
766 781 LineKind::Quote => {
767 782 self.splice(cursor..cursor, "\n", &[]);
768 783 self.lines[index] = LineKind::Quote;
@@ -823,6 +838,9 @@ impl Draft {
823 838 if cursor != line.end || index + 1 >= self.lines.len() {
824 839 return None;
825 840 }
841 if self.lines[index + 1].is_table() {
842 return Some(cursor);
843 }
826 844 let next_marker = self.marker_range(index + 1);
827 845 if next_marker.is_empty() {
828 846 return None;
@@ -847,11 +865,22 @@ impl Draft {
847 865 cursor
848 866 })
849 867 }
868 LineKind::Table(_) => None,
869 LineKind::Heading(_) => (cursor == line.start).then(|| {
870 self.lines[index] = LineKind::Text;
871 cursor
872 }),
850 873 LineKind::Quote
851 874 if cursor == line.start && (index == 0 || self.lines[index - 1] != kind) =>
852 875 {
853 self.lines[index] = LineKind::Text;
854 Some(cursor)
876 let joins_previous =
877 index > 0 && !content.is_empty() && !self.lines[index - 1].is_table();
878 if !joins_previous {
879 self.lines[index] = LineKind::Text;
880 return Some(cursor);
881 }
882 self.splice(line.start - 1..line.start, "", &[]);
883 Some(self.repair(line.start - 1))
855 884 }
856 885 _ if cursor == line.start && index > 0 => {
857 886 self.splice(line.start - 1..content.start, "", &[]);
@@ -899,6 +928,9 @@ impl Draft {
899 928 .all(|index| self.lines[index].same_format(&kind));
900 929 for index in lines {
901 930 let current = self.lines[index].clone();
931 if current.is_table() {
932 continue;
933 }
902 934 let target = if all {
903 935 LineKind::Text
904 936 } else if current.same_format(&kind) {
@@ -915,6 +947,120 @@ impl Draft {
915 947 self.repair(0);
916 948 }
917 949
950 pub fn table(&self, index: usize) -> Option<&Table> {
951 match self.lines.get(index)? {
952 LineKind::Table(table) => Some(table),
953 _ => None,
954 }
955 }
956
957 /// Cell edits change no text, so the journal stays as it is.
958 pub fn set_table(&mut self, index: usize, table: Table) {
959 if let Some(kind @ LineKind::Table(_)) = self.lines.get_mut(index) {
960 *kind = LineKind::Table(table);
961 }
962 }
963
964 /// The table goes in place of an empty text line, otherwise below the cursor's line, and
965 /// a text line follows it. Returns the table's line.
966 pub fn insert_table(&mut self, cursor: usize, table: Table) -> usize {
967 self.journal = Journal::default();
968 let index = self.line_at(cursor);
969 let line = self.line_ranges()[index].clone();
970 let mark = TABLE_MARK.to_string();
971 let replaces_line = self.lines[index] == LineKind::Text && line.is_empty();
972 let table_index = if replaces_line {
973 self.splice(line, &mark, &[]);
974 index
975 } else {
976 self.splice(line.end..line.end, &format!("\n{mark}"), &[]);
977 index + 1
978 };
979 self.lines[table_index] = LineKind::Table(table);
980 if table_index + 1 == self.lines.len() {
981 let end = self.text.len();
982 self.splice(end..end, "\n", &[]);
983 self.lines[table_index + 1] = LineKind::Text;
984 }
985 table_index
986 }
987
988 /// Returns where the cursor goes: the start of the line that took the table's place.
989 pub fn remove_table(&mut self, index: usize) -> usize {
990 self.journal = Journal::default();
991 let ranges = self.line_ranges();
992 let line = ranges[index].clone();
993 if let Some(next) = ranges.get(index + 1) {
994 let next_kind = self.lines[index + 1].clone();
995 self.splice(line.start..next.start, "", &[]);
996 self.lines[index] = next_kind;
997 return self.repair(line.start);
998 }
999 if index > 0 {
1000 let start = ranges[index - 1].end;
1001 self.splice(start..line.end, "", &[]);
1002 return self.repair(start);
1003 }
1004 self.splice(line, "", &[]);
1005 self.lines[index] = LineKind::Text;
1006 0
1007 }
1008
1009 /// Where the cursor lands when it leaves table `index` downwards or upwards; a text line
1010 /// is added when the table is the last or the first line.
1011 pub fn line_beside_table(&mut self, index: usize, below: bool) -> usize {
1012 self.journal = Journal::default();
1013 let ranges = self.line_ranges();
1014 if below {
1015 if let Some(next) = ranges.get(index + 1) {
1016 return next.start;
1017 }
1018 let end = self.text.len();
1019 self.splice(end..end, "\n", &[]);
1020 self.lines[index + 1] = LineKind::Text;
1021 return end + 1;
1022 }
1023 if index > 0 {
1024 return ranges[index - 1].end;
1025 }
1026 self.splice(0..0, "\n", &[]);
1027 self.lines[0] = LineKind::Text;
1028 0
1029 }
1030
1031 pub fn table_at(&self, offset: usize) -> Option<usize> {
1032 let index = self.line_at(offset);
1033 self.lines[index].is_table().then_some(index)
1034 }
1035
1036 /// The table right above, when `cursor` is at the start of its line.
1037 pub fn table_before(&self, cursor: usize) -> Option<usize> {
1038 let index = self.line_at(cursor);
1039 let at_start = self.line_ranges()[index].start == cursor;
1040 (at_start && index > 0 && self.lines[index - 1].is_table()).then(|| index - 1)
1041 }
1042
1043 /// The table right below, when `cursor` is at the end of its line.
1044 pub fn table_after(&self, cursor: usize) -> Option<usize> {
1045 let index = self.line_at(cursor);
1046 let at_end = self.line_ranges()[index].end == cursor;
1047 (at_end && self.lines.get(index + 1).is_some_and(LineKind::is_table)).then_some(index + 1)
1048 }
1049
1050 /// Down or Right at the very end of a quote that ends the draft: a text line below it,
1051 /// like the empty paragraph Teams keeps after a quote.
1052 pub fn leave_quote_at_end(&mut self, cursor: usize) -> Option<usize> {
1053 self.journal = Journal::default();
1054 let end = self.text.len();
1055 let last = self.lines.len() - 1;
1056 if cursor != end || self.lines[last] != LineKind::Quote {
1057 return None;
1058 }
1059 self.splice(end..end, "\n", &[]);
1060 self.lines[last + 1] = LineKind::Text;
1061 Some(end + 1)
1062 }
1063
918 1064 pub fn slice(&self, range: Range<usize>) -> Vec<DraftLine> {
919 1065 let mut lines = Vec::new();
920 1066 for (index, line) in self.line_ranges().into_iter().enumerate() {
@@ -981,6 +1127,13 @@ impl Draft {
981 1127 let line_was_empty = self.lines[index] == LineKind::Text
982 1128 && range.start == content.start
983 1129 && range.end >= tail_end;
1130 let separated;
1131 let lines = if !line_was_empty && lines.first().is_some_and(|line| line.kind.is_table()) {
1132 separated = [&[DraftLine::text("")][..], lines].concat();
1133 &separated[..]
1134 } else {
1135 lines
1136 };
984 1137 let joined = lines
985 1138 .iter()
986 1139 .map(|line| line.content.as_str())
@@ -1057,6 +1210,23 @@ impl Draft {
1057 1210 html.push_str(&joined_inline(run));
1058 1211 html.push_str("</blockquote>");
1059 1212 }
1213 LineKind::Heading(_) => {
1214 for line in run {
1215 let level = match line.kind {
1216 LineKind::Heading(level) => level.clamp(1, MAX_HEADING),
1217 _ => 1,
1218 };
1219 let inline = inline_html(&line.content, &line.marks);
1220 html.push_str(&format!("<h{level}>{inline}</h{level}>"));
1221 }
1222 }
1223 LineKind::Table(_) => {
1224 for line in run {
1225 if let LineKind::Table(table) = &line.kind {
1226 html.push_str(&table.to_html());
1227 }
1228 }
1229 }
1060 1230 LineKind::Code(language) => {
1061 1231 match language {
1062 1232 Some(language) => html.push_str(&format!(
@@ -1362,8 +1532,45 @@ impl Draft {
1362 1532 }
1363 1533 }
1364 1534
1535 /// A table line holds its mark alone: text typed next to it moves to its own line, a mark
1536 /// without its table is dropped and a table without its mark becomes text.
1537 fn repair_tables(&mut self, mut cursor: usize) -> usize {
1538 let mark_length = TABLE_MARK.len_utf8();
1539 let mut index = 0;
1540 while index < self.lines.len() {
1541 let line = self.line_ranges()[index].clone();
1542 let found = self.text[line.clone()].find(TABLE_MARK);
1543 match (self.lines[index].clone(), found) {
1544 (LineKind::Table(_), None) => self.lines[index] = LineKind::Text,
1545 (LineKind::Table(table), Some(at)) if at > 0 => {
1546 let split = line.start + at;
1547 self.splice(split..split, "\n", &[]);
1548 self.lines[index] = LineKind::Text;
1549 self.lines[index + 1] = LineKind::Table(table);
1550 cursor += usize::from(cursor > split);
1551 }
1552 (LineKind::Table(_), Some(_)) if line.len() > mark_length => {
1553 let split = line.start + mark_length;
1554 self.splice(split..split, "\n", &[]);
1555 cursor += usize::from(cursor > split);
1556 }
1557 (LineKind::Table(_), Some(_)) => {}
1558 (_, Some(at)) => {
1559 let mark = line.start + at..line.start + at + mark_length;
1560 self.splice(mark.clone(), "", &[]);
1561 cursor = map_offset(&[(mark, String::new())], cursor);
1562 continue;
1563 }
1564 (_, None) => {}
1565 }
1566 index += 1;
1567 }
1568 cursor
1569 }
1570
1365 1571 /// List items whose marker was edited away become text; numbered items are renumbered.
1366 fn repair(&mut self, mut cursor: usize) -> usize {
1572 fn repair(&mut self, cursor: usize) -> usize {
1573 let mut cursor = self.repair_tables(cursor);
1367 1574 for index in 0..self.lines.len() {
1368 1575 let kind = self.lines[index].clone();
1369 1576 if !kind.is_list() {
@@ -1399,7 +1606,11 @@ fn marker_text(kind: &LineKind, number: u32) -> String {
1399 1606 match kind {
1400 1607 LineKind::Bullet(depth) => bullet_marker(*depth),
1401 1608 LineKind::Numbered(_) => format!("{number}. "),
1402 LineKind::Text | LineKind::Quote | LineKind::Code(_) => String::new(),
1609 LineKind::Text
1610 | LineKind::Quote
1611 | LineKind::Code(_)
1612 | LineKind::Heading(_)
1613 | LineKind::Table(_) => String::new(),
1403 1614 }
1404 1615 }
1405 1616
@@ -1430,7 +1641,9 @@ fn numbered_marker(line: &str) -> Option<(usize, u32)> {
1430 1641 fn line_shortcut(before: &str) -> Option<(LineKind, u32)> {
1431 1642 match before {
1432 1643 "- " | "* " => Some((LineKind::Bullet(0), 1)),
1433 "> " => Some((LineKind::Quote, 1)),
1644 ">" => Some((LineKind::Quote, 1)),
1645 _ if before.starts_with('#') => heading_prefix(before)
1646 .and_then(|(level, rest)| rest.is_empty().then_some((LineKind::Heading(level), 1))),
1434 1647 _ => {
1435 1648 let digits = before.strip_suffix(". ")?;
1436 1649 let all_digits = !digits.is_empty()
@@ -1540,7 +1753,7 @@ fn typed_inline(before: &str) -> Option<(Range<usize>, Range<usize>, MarkKind)>
1540 1753 let usable = !body[open + 1..].trim().is_empty() && !body[..open].ends_with('`');
1541 1754 return usable.then(|| (open..open + 1, body.len()..end, MarkKind::Code));
1542 1755 }
1543 for marker in ['*', '_'] {
1756 for (marker, kind) in [('*', MarkKind::Bold), ('_', MarkKind::Italic)] {
1544 1757 if let Some(body) = before.strip_suffix(marker) {
1545 1758 if body.ends_with(marker) {
1546 1759 return None;
@@ -1548,7 +1761,7 @@ fn typed_inline(before: &str) -> Option<(Range<usize>, Range<usize>, MarkKind)>
1548 1761 let open = body.rfind(marker)?;
1549 1762 let opening_ok = !word_before(&body[..open]) && !body[..open].ends_with(marker);
1550 1763 return (opening_ok && valid_inner(&body[open + 1..]))
1551 .then(|| (open..open + 1, body.len()..end, MarkKind::Italic));
1764 .then(|| (open..open + 1, body.len()..end, kind));
1552 1765 }
1553 1766 }
1554 1767 None
@@ -1702,10 +1915,16 @@ pub fn has_markdown(text: &str) -> bool {
1702 1915 }
1703 1916
1704 1917 fn markdown_lines(text: &str) -> Vec<DraftLine> {
1918 let sources: Vec<&str> = text
1919 .split('\n')
1920 .map(|raw| raw.strip_suffix('\r').unwrap_or(raw))
1921 .collect();
1705 1922 let mut lines = Vec::new();
1706 1923 let mut code: Option<Option<String>> = None;
1707 for raw in text.split('\n') {
1708 let raw = raw.strip_suffix('\r').unwrap_or(raw);
1924 let mut position = 0;
1925 while position < sources.len() {
1926 let raw = sources[position];
1927 position += 1;
1709 1928 let trimmed = raw.trim_start();
1710 1929 if let Some(language) = &code {
1711 1930 if trimmed.starts_with(FENCE) && trimmed.trim_end() == FENCE {
@@ -1727,12 +1946,23 @@ fn markdown_lines(text: &str) -> Vec<DraftLine> {
1727 1946 code = Some(language);
1728 1947 continue;
1729 1948 }
1949 if let Some((rows, consumed)) = markdown_table(&sources[position - 1..]) {
1950 let rows = rows
1951 .into_iter()
1952 .map(|row| row.iter().map(|cell| parse_inline(cell).0).collect())
1953 .collect();
1954 lines.push(table_line(Table::from_rows(rows)));
1955 position += consumed - 1;
1956 continue;
1957 }
1730 1958 let indent: usize = raw[..raw.len() - trimmed.len()]
1731 1959 .chars()
1732 1960 .map(|character| if character == '\t' { 4 } else { 1 })
1733 1961 .sum();
1734 1962 let depth = ((indent / MARKDOWN_INDENT) as u8).min(MAX_DEPTH);
1735 let (kind, number, content) = if let Some(rest) = PASTED_BULLETS
1963 let (kind, number, content) = if let Some((level, rest)) = heading_prefix(trimmed) {
1964 (LineKind::Heading(level), None, rest)
1965 } else if let Some(rest) = PASTED_BULLETS
1736 1966 .iter()
1737 1967 .find_map(|bullet| trimmed.strip_prefix(bullet))
1738 1968 {
@@ -1758,6 +1988,24 @@ fn markdown_lines(text: &str) -> Vec<DraftLine> {
1758 1988 lines
1759 1989 }
1760 1990
1991 fn table_line(table: Table) -> DraftLine {
1992 DraftLine {
1993 kind: LineKind::Table(table),
1994 number: None,
1995 content: TABLE_MARK.to_string(),
1996 marks: Vec::new(),
1997 }
1998 }
1999
2000 /// `# ` to `###### `: the level, capped at the three Teams offers, and the rest of the line.
2001 fn heading_prefix(line: &str) -> Option<(u8, &str)> {
2002 let hashes = line.bytes().take_while(|byte| *byte == b'#').count();
2003 let rest = line[hashes..].strip_prefix(' ')?;
2004 (1..=6)
2005 .contains(&hashes)
2006 .then(|| ((hashes as u8).min(MAX_HEADING), rest))
2007 }
2008
1761 2009 fn parse_inline(source: &str) -> (String, Vec<Mark>) {
1762 2010 let mut text = String::with_capacity(source.len());
1763 2011 let mut marks = Vec::new();
@@ -1849,6 +2097,17 @@ fn inline_at(rest: &str, previous: Option<char>) -> Option<(&str, usize, MarkKin
1849 2097 None
1850 2098 }
1851 2099
2100 fn cell_text(spans: &[Span]) -> String {
2101 let mut builder = SpanLines::default();
2102 builder.walk(spans, &LineKind::Text, &[]);
2103 builder
2104 .finish()
2105 .into_iter()
2106 .map(|line| line.content)
2107 .collect::<Vec<_>>()
2108 .join("\n")
2109 }
2110
1852 2111 #[derive(Default)]
1853 2112 struct SpanLines {
1854 2113 lines: Vec<DraftLine>,
@@ -1936,9 +2195,10 @@ impl SpanLines {
1936 2195 };
1937 2196 self.start_line(&continued, None);
1938 2197 }
1939 Span::Heading { children, .. } => {
1940 self.start_line(&LineKind::Text, None);
1941 self.walk(children, &LineKind::Text, &with(MarkKind::Bold));
2198 Span::Heading { level, children } => {
2199 let heading = LineKind::Heading((*level).clamp(1, MAX_HEADING));
2200 self.start_line(&heading, None);
2201 self.walk(children, &heading, marks);
1942 2202 self.open = false;
1943 2203 }
1944 2204 Span::CodeBlock { language, code } => {
@@ -1977,15 +2237,11 @@ impl SpanLines {
1977 2237 self.open = false;
1978 2238 }
1979 2239 Span::Table { rows, .. } => {
1980 for row in rows {
1981 self.start_line(&LineKind::Text, None);
1982 for (position, cell) in row.iter().enumerate() {
1983 if position > 0 {
1984 self.append(" | ", &LineKind::Text, &[]);
1985 }
1986 self.walk(cell, &LineKind::Text, marks);
1987 }
1988 }
2240 let rows = rows
2241 .iter()
2242 .map(|row| row.iter().map(|cell| cell_text(cell)).collect())
2243 .collect();
2244 self.lines.push(table_line(Table::from_rows(rows)));
1989 2245 self.open = false;
1990 2246 }
1991 2247 Span::Image { .. } | Span::Quote { .. } => {}
@@ -2081,7 +2337,7 @@ mod tests {
2081 2337 draft.marks(),
2082 2338 [
2083 2339 mark(2..6, MarkKind::Bold),
2084 mark(11..13, MarkKind::Italic),
2340 mark(11..13, MarkKind::Bold),
2085 2341 mark(17..19, MarkKind::Italic),
2086 2342 mark(20..24, MarkKind::Strike),
2087 2343 mark(25..29, MarkKind::Code),
@@ -2357,9 +2613,12 @@ mod tests {
2357 2613 let numbered = typed_draft("1. one");
2358 2614 assert_eq!(numbered.text(), "1. one");
2359 2615 assert_eq!(numbered.lines(), [LineKind::Numbered(0)]);
2360 let quote = typed_draft("> said");
2616 let quote = typed_draft(">said");
2361 2617 assert_eq!(quote.text(), "said");
2362 2618 assert_eq!(quote.lines(), [LineKind::Quote]);
2619 let spaced = typed_draft("> said");
2620 assert_eq!(spaced.text(), " said");
2621 assert_eq!(spaced.lines(), [LineKind::Quote]);
2363 2622 }
2364 2623
2365 2624 #[test]
@@ -6,8 +6,10 @@ use serde::{Deserialize, Serialize};
6
6
7use crate::markdown::escape_html;
7use crate::markdown::escape_html;
8use crate::spans::{FontSize, Span};
8use crate::spans::{FontSize, Span};
9use crate::table::{TABLE_MARK, Table, markdown_table};
9
10
10pub const MAX_DEPTH: u8 = 2;
11pub const MAX_DEPTH: u8 = 2;
12pub const MAX_HEADING: u8 = 3;
11pub const OBJECT_MARK: char = '\u{FFFC}';
13pub const OBJECT_MARK: char = '\u{FFFC}';
12const BULLETS: [&str; 3] = ["•", "◦", "▪"];
14const BULLETS: [&str; 3] = ["•", "◦", "▪"];
13const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "];
15const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "];
@@ -125,6 +127,8 @@ pub enum LineKind {
125 Numbered(u8),
127 Numbered(u8),
126 Quote,
128 Quote,
127 Code(Option<String>),
129 Code(Option<String>),
130 Heading(u8),
131 Table(Table),
128}
132}
129
133
130impl LineKind {
134impl LineKind {
@@ -132,6 +136,10 @@ impl LineKind {
132 matches!(self, LineKind::Bullet(_) | LineKind::Numbered(_))
136 matches!(self, LineKind::Bullet(_) | LineKind::Numbered(_))
133 }
137 }
134
138
139 pub fn is_table(&self) -> bool {
140 matches!(self, LineKind::Table(_))
141 }
142
135 pub fn depth(&self) -> u8 {
143 pub fn depth(&self) -> u8 {
136 match self {
144 match self {
137 LineKind::Bullet(depth) | LineKind::Numbered(depth) => *depth,
145 LineKind::Bullet(depth) | LineKind::Numbered(depth) => *depth,
@@ -430,7 +438,10 @@ impl Draft {
430 pub fn plain_text(&self) -> String {
438 pub fn plain_text(&self) -> String {
431 self.slice(0..self.text.len())
439 self.slice(0..self.text.len())
432 .into_iter()
440 .into_iter()
433 .map(|line| line.content)
441 .map(|line| match &line.kind {
442 LineKind::Table(table) => table.plain_text(),
443 _ => line.content,
444 })
434 .collect::<Vec<_>>()
445 .collect::<Vec<_>>()
435 .join("\n")
446 .join("\n")
436 .replace(&format!(" {OBJECT_MARK} "), " ")
447 .replace(&format!(" {OBJECT_MARK} "), " ")
@@ -762,7 +773,11 @@ impl Draft {
762 self.splice(content.clone(), "", &[]);
773 self.splice(content.clone(), "", &[]);
763 Some(self.set_line_kind(index, LineKind::Code(language), None, content.start))
774 Some(self.set_line_kind(index, LineKind::Code(language), None, content.start))
764 }
775 }
765 LineKind::Quote if !shift => None,
776 LineKind::Heading(_) | LineKind::Table(_) => None,
777 LineKind::Quote if content.is_empty() && !shift => {
778 self.lines[index] = LineKind::Text;
779 Some(cursor)
780 }
766 LineKind::Quote => {
781 LineKind::Quote => {
767 self.splice(cursor..cursor, "\n", &[]);
782 self.splice(cursor..cursor, "\n", &[]);
768 self.lines[index] = LineKind::Quote;
783 self.lines[index] = LineKind::Quote;
@@ -823,6 +838,9 @@ impl Draft {
823 if cursor != line.end || index + 1 >= self.lines.len() {
838 if cursor != line.end || index + 1 >= self.lines.len() {
824 return None;
839 return None;
825 }
840 }
841 if self.lines[index + 1].is_table() {
842 return Some(cursor);
843 }
826 let next_marker = self.marker_range(index + 1);
844 let next_marker = self.marker_range(index + 1);
827 if next_marker.is_empty() {
845 if next_marker.is_empty() {
828 return None;
846 return None;
@@ -847,11 +865,22 @@ impl Draft {
847 cursor
865 cursor
848 })
866 })
849 }
867 }
868 LineKind::Table(_) => None,
869 LineKind::Heading(_) => (cursor == line.start).then(|| {
870 self.lines[index] = LineKind::Text;
871 cursor
872 }),
850 LineKind::Quote
873 LineKind::Quote
851 if cursor == line.start && (index == 0 || self.lines[index - 1] != kind) =>
874 if cursor == line.start && (index == 0 || self.lines[index - 1] != kind) =>
852 {
875 {
853 self.lines[index] = LineKind::Text;
876 let joins_previous =
854 Some(cursor)
877 index > 0 && !content.is_empty() && !self.lines[index - 1].is_table();
878 if !joins_previous {
879 self.lines[index] = LineKind::Text;
880 return Some(cursor);
881 }
882 self.splice(line.start - 1..line.start, "", &[]);
883 Some(self.repair(line.start - 1))
855 }
884 }
856 _ if cursor == line.start && index > 0 => {
885 _ if cursor == line.start && index > 0 => {
857 self.splice(line.start - 1..content.start, "", &[]);
886 self.splice(line.start - 1..content.start, "", &[]);
@@ -899,6 +928,9 @@ impl Draft {
899 .all(|index| self.lines[index].same_format(&kind));
928 .all(|index| self.lines[index].same_format(&kind));
900 for index in lines {
929 for index in lines {
901 let current = self.lines[index].clone();
930 let current = self.lines[index].clone();
931 if current.is_table() {
932 continue;
933 }
902 let target = if all {
934 let target = if all {
903 LineKind::Text
935 LineKind::Text
904 } else if current.same_format(&kind) {
936 } else if current.same_format(&kind) {
@@ -915,6 +947,120 @@ impl Draft {
915 self.repair(0);
947 self.repair(0);
916 }
948 }
917
949
950 pub fn table(&self, index: usize) -> Option<&Table> {
951 match self.lines.get(index)? {
952 LineKind::Table(table) => Some(table),
953 _ => None,
954 }
955 }
956
957 /// Cell edits change no text, so the journal stays as it is.
958 pub fn set_table(&mut self, index: usize, table: Table) {
959 if let Some(kind @ LineKind::Table(_)) = self.lines.get_mut(index) {
960 *kind = LineKind::Table(table);
961 }
962 }
963
964 /// The table goes in place of an empty text line, otherwise below the cursor's line, and
965 /// a text line follows it. Returns the table's line.
966 pub fn insert_table(&mut self, cursor: usize, table: Table) -> usize {
967 self.journal = Journal::default();
968 let index = self.line_at(cursor);
969 let line = self.line_ranges()[index].clone();
970 let mark = TABLE_MARK.to_string();
971 let replaces_line = self.lines[index] == LineKind::Text && line.is_empty();
972 let table_index = if replaces_line {
973 self.splice(line, &mark, &[]);
974 index
975 } else {
976 self.splice(line.end..line.end, &format!("\n{mark}"), &[]);
977 index + 1
978 };
979 self.lines[table_index] = LineKind::Table(table);
980 if table_index + 1 == self.lines.len() {
981 let end = self.text.len();
982 self.splice(end..end, "\n", &[]);
983 self.lines[table_index + 1] = LineKind::Text;
984 }
985 table_index
986 }
987
988 /// Returns where the cursor goes: the start of the line that took the table's place.
989 pub fn remove_table(&mut self, index: usize) -> usize {
990 self.journal = Journal::default();
991 let ranges = self.line_ranges();
992 let line = ranges[index].clone();
993 if let Some(next) = ranges.get(index + 1) {
994 let next_kind = self.lines[index + 1].clone();
995 self.splice(line.start..next.start, "", &[]);
996 self.lines[index] = next_kind;
997 return self.repair(line.start);
998 }
999 if index > 0 {
1000 let start = ranges[index - 1].end;
1001 self.splice(start..line.end, "", &[]);
1002 return self.repair(start);
1003 }
1004 self.splice(line, "", &[]);
1005 self.lines[index] = LineKind::Text;
1006 0
1007 }
1008
1009 /// Where the cursor lands when it leaves table `index` downwards or upwards; a text line
1010 /// is added when the table is the last or the first line.
1011 pub fn line_beside_table(&mut self, index: usize, below: bool) -> usize {
1012 self.journal = Journal::default();
1013 let ranges = self.line_ranges();
1014 if below {
1015 if let Some(next) = ranges.get(index + 1) {
1016 return next.start;
1017 }
1018 let end = self.text.len();
1019 self.splice(end..end, "\n", &[]);
1020 self.lines[index + 1] = LineKind::Text;
1021 return end + 1;
1022 }
1023 if index > 0 {
1024 return ranges[index - 1].end;
1025 }
1026 self.splice(0..0, "\n", &[]);
1027 self.lines[0] = LineKind::Text;
1028 0
1029 }
1030
1031 pub fn table_at(&self, offset: usize) -> Option<usize> {
1032 let index = self.line_at(offset);
1033 self.lines[index].is_table().then_some(index)
1034 }
1035
1036 /// The table right above, when `cursor` is at the start of its line.
1037 pub fn table_before(&self, cursor: usize) -> Option<usize> {
1038 let index = self.line_at(cursor);
1039 let at_start = self.line_ranges()[index].start == cursor;
1040 (at_start && index > 0 && self.lines[index - 1].is_table()).then(|| index - 1)
1041 }
1042
1043 /// The table right below, when `cursor` is at the end of its line.
1044 pub fn table_after(&self, cursor: usize) -> Option<usize> {
1045 let index = self.line_at(cursor);
1046 let at_end = self.line_ranges()[index].end == cursor;
1047 (at_end && self.lines.get(index + 1).is_some_and(LineKind::is_table)).then_some(index + 1)
1048 }
1049
1050 /// Down or Right at the very end of a quote that ends the draft: a text line below it,
1051 /// like the empty paragraph Teams keeps after a quote.
1052 pub fn leave_quote_at_end(&mut self, cursor: usize) -> Option<usize> {
1053 self.journal = Journal::default();
1054 let end = self.text.len();
1055 let last = self.lines.len() - 1;
1056 if cursor != end || self.lines[last] != LineKind::Quote {
1057 return None;
1058 }
1059 self.splice(end..end, "\n", &[]);
1060 self.lines[last + 1] = LineKind::Text;
1061 Some(end + 1)
1062 }
1063
918 pub fn slice(&self, range: Range<usize>) -> Vec<DraftLine> {
1064 pub fn slice(&self, range: Range<usize>) -> Vec<DraftLine> {
919 let mut lines = Vec::new();
1065 let mut lines = Vec::new();
920 for (index, line) in self.line_ranges().into_iter().enumerate() {
1066 for (index, line) in self.line_ranges().into_iter().enumerate() {
@@ -981,6 +1127,13 @@ impl Draft {
981 let line_was_empty = self.lines[index] == LineKind::Text
1127 let line_was_empty = self.lines[index] == LineKind::Text
982 && range.start == content.start
1128 && range.start == content.start
983 && range.end >= tail_end;
1129 && range.end >= tail_end;
1130 let separated;
1131 let lines = if !line_was_empty && lines.first().is_some_and(|line| line.kind.is_table()) {
1132 separated = [&[DraftLine::text("")][..], lines].concat();
1133 &separated[..]
1134 } else {
1135 lines
1136 };
984 let joined = lines
1137 let joined = lines
985 .iter()
1138 .iter()
986 .map(|line| line.content.as_str())
1139 .map(|line| line.content.as_str())
@@ -1057,6 +1210,23 @@ impl Draft {
1057 html.push_str(&joined_inline(run));
1210 html.push_str(&joined_inline(run));
1058 html.push_str("</blockquote>");
1211 html.push_str("</blockquote>");
1059 }
1212 }
1213 LineKind::Heading(_) => {
1214 for line in run {
1215 let level = match line.kind {
1216 LineKind::Heading(level) => level.clamp(1, MAX_HEADING),
1217 _ => 1,
1218 };
1219 let inline = inline_html(&line.content, &line.marks);
1220 html.push_str(&format!("<h{level}>{inline}</h{level}>"));
1221 }
1222 }
1223 LineKind::Table(_) => {
1224 for line in run {
1225 if let LineKind::Table(table) = &line.kind {
1226 html.push_str(&table.to_html());
1227 }
1228 }
1229 }
1060 LineKind::Code(language) => {
1230 LineKind::Code(language) => {
1061 match language {
1231 match language {
1062 Some(language) => html.push_str(&format!(
1232 Some(language) => html.push_str(&format!(
@@ -1362,8 +1532,45 @@ impl Draft {
1362 }
1532 }
1363 }
1533 }
1364
1534
1535 /// A table line holds its mark alone: text typed next to it moves to its own line, a mark
1536 /// without its table is dropped and a table without its mark becomes text.
1537 fn repair_tables(&mut self, mut cursor: usize) -> usize {
1538 let mark_length = TABLE_MARK.len_utf8();
1539 let mut index = 0;
1540 while index < self.lines.len() {
1541 let line = self.line_ranges()[index].clone();
1542 let found = self.text[line.clone()].find(TABLE_MARK);
1543 match (self.lines[index].clone(), found) {
1544 (LineKind::Table(_), None) => self.lines[index] = LineKind::Text,
1545 (LineKind::Table(table), Some(at)) if at > 0 => {
1546 let split = line.start + at;
1547 self.splice(split..split, "\n", &[]);
1548 self.lines[index] = LineKind::Text;
1549 self.lines[index + 1] = LineKind::Table(table);
1550 cursor += usize::from(cursor > split);
1551 }
1552 (LineKind::Table(_), Some(_)) if line.len() > mark_length => {
1553 let split = line.start + mark_length;
1554 self.splice(split..split, "\n", &[]);
1555 cursor += usize::from(cursor > split);
1556 }
1557 (LineKind::Table(_), Some(_)) => {}
1558 (_, Some(at)) => {
1559 let mark = line.start + at..line.start + at + mark_length;
1560 self.splice(mark.clone(), "", &[]);
1561 cursor = map_offset(&[(mark, String::new())], cursor);
1562 continue;
1563 }
1564 (_, None) => {}
1565 }
1566 index += 1;
1567 }
1568 cursor
1569 }
1570
1365 /// List items whose marker was edited away become text; numbered items are renumbered.
1571 /// List items whose marker was edited away become text; numbered items are renumbered.
1366 fn repair(&mut self, mut cursor: usize) -> usize {
1572 fn repair(&mut self, cursor: usize) -> usize {
1573 let mut cursor = self.repair_tables(cursor);
1367 for index in 0..self.lines.len() {
1574 for index in 0..self.lines.len() {
1368 let kind = self.lines[index].clone();
1575 let kind = self.lines[index].clone();
1369 if !kind.is_list() {
1576 if !kind.is_list() {
@@ -1399,7 +1606,11 @@ fn marker_text(kind: &LineKind, number: u32) -> String {
1399 match kind {
1606 match kind {
1400 LineKind::Bullet(depth) => bullet_marker(*depth),
1607 LineKind::Bullet(depth) => bullet_marker(*depth),
1401 LineKind::Numbered(_) => format!("{number}. "),
1608 LineKind::Numbered(_) => format!("{number}. "),
1402 LineKind::Text | LineKind::Quote | LineKind::Code(_) => String::new(),
1609 LineKind::Text
1610 | LineKind::Quote
1611 | LineKind::Code(_)
1612 | LineKind::Heading(_)
1613 | LineKind::Table(_) => String::new(),
1403 }
1614 }
1404}
1615}
1405
1616
@@ -1430,7 +1641,9 @@ fn numbered_marker(line: &str) -> Option<(usize, u32)> {
1430fn line_shortcut(before: &str) -> Option<(LineKind, u32)> {
1641fn line_shortcut(before: &str) -> Option<(LineKind, u32)> {
1431 match before {
1642 match before {
1432 "- " | "* " => Some((LineKind::Bullet(0), 1)),
1643 "- " | "* " => Some((LineKind::Bullet(0), 1)),
1433 "> " => Some((LineKind::Quote, 1)),
1644 ">" => Some((LineKind::Quote, 1)),
1645 _ if before.starts_with('#') => heading_prefix(before)
1646 .and_then(|(level, rest)| rest.is_empty().then_some((LineKind::Heading(level), 1))),
1434 _ => {
1647 _ => {
1435 let digits = before.strip_suffix(". ")?;
1648 let digits = before.strip_suffix(". ")?;
1436 let all_digits = !digits.is_empty()
1649 let all_digits = !digits.is_empty()
@@ -1540,7 +1753,7 @@ fn typed_inline(before: &str) -> Option<(Range<usize>, Range<usize>, MarkKind)>
1540 let usable = !body[open + 1..].trim().is_empty() && !body[..open].ends_with('`');
1753 let usable = !body[open + 1..].trim().is_empty() && !body[..open].ends_with('`');
1541 return usable.then(|| (open..open + 1, body.len()..end, MarkKind::Code));
1754 return usable.then(|| (open..open + 1, body.len()..end, MarkKind::Code));
1542 }
1755 }
1543 for marker in ['*', '_'] {
1756 for (marker, kind) in [('*', MarkKind::Bold), ('_', MarkKind::Italic)] {
1544 if let Some(body) = before.strip_suffix(marker) {
1757 if let Some(body) = before.strip_suffix(marker) {
1545 if body.ends_with(marker) {
1758 if body.ends_with(marker) {
1546 return None;
1759 return None;
@@ -1548,7 +1761,7 @@ fn typed_inline(before: &str) -> Option<(Range<usize>, Range<usize>, MarkKind)>
1548 let open = body.rfind(marker)?;
1761 let open = body.rfind(marker)?;
1549 let opening_ok = !word_before(&body[..open]) && !body[..open].ends_with(marker);
1762 let opening_ok = !word_before(&body[..open]) && !body[..open].ends_with(marker);
1550 return (opening_ok && valid_inner(&body[open + 1..]))
1763 return (opening_ok && valid_inner(&body[open + 1..]))
1551 .then(|| (open..open + 1, body.len()..end, MarkKind::Italic));
1764 .then(|| (open..open + 1, body.len()..end, kind));
1552 }
1765 }
1553 }
1766 }
1554 None
1767 None
@@ -1702,10 +1915,16 @@ pub fn has_markdown(text: &str) -> bool {
1702}
1915}
1703
1916
1704fn markdown_lines(text: &str) -> Vec<DraftLine> {
1917fn markdown_lines(text: &str) -> Vec<DraftLine> {
1918 let sources: Vec<&str> = text
1919 .split('\n')
1920 .map(|raw| raw.strip_suffix('\r').unwrap_or(raw))
1921 .collect();
1705 let mut lines = Vec::new();
1922 let mut lines = Vec::new();
1706 let mut code: Option<Option<String>> = None;
1923 let mut code: Option<Option<String>> = None;
1707 for raw in text.split('\n') {
1924 let mut position = 0;
1708 let raw = raw.strip_suffix('\r').unwrap_or(raw);
1925 while position < sources.len() {
1926 let raw = sources[position];
1927 position += 1;
1709 let trimmed = raw.trim_start();
1928 let trimmed = raw.trim_start();
1710 if let Some(language) = &code {
1929 if let Some(language) = &code {
1711 if trimmed.starts_with(FENCE) && trimmed.trim_end() == FENCE {
1930 if trimmed.starts_with(FENCE) && trimmed.trim_end() == FENCE {
@@ -1727,12 +1946,23 @@ fn markdown_lines(text: &str) -> Vec<DraftLine> {
1727 code = Some(language);
1946 code = Some(language);
1728 continue;
1947 continue;
1729 }
1948 }
1949 if let Some((rows, consumed)) = markdown_table(&sources[position - 1..]) {
1950 let rows = rows
1951 .into_iter()
1952 .map(|row| row.iter().map(|cell| parse_inline(cell).0).collect())
1953 .collect();
1954 lines.push(table_line(Table::from_rows(rows)));
1955 position += consumed - 1;
1956 continue;
1957 }
1730 let indent: usize = raw[..raw.len() - trimmed.len()]
1958 let indent: usize = raw[..raw.len() - trimmed.len()]
1731 .chars()
1959 .chars()
1732 .map(|character| if character == '\t' { 4 } else { 1 })
1960 .map(|character| if character == '\t' { 4 } else { 1 })
1733 .sum();
1961 .sum();
1734 let depth = ((indent / MARKDOWN_INDENT) as u8).min(MAX_DEPTH);
1962 let depth = ((indent / MARKDOWN_INDENT) as u8).min(MAX_DEPTH);
1735 let (kind, number, content) = if let Some(rest) = PASTED_BULLETS
1963 let (kind, number, content) = if let Some((level, rest)) = heading_prefix(trimmed) {
1964 (LineKind::Heading(level), None, rest)
1965 } else if let Some(rest) = PASTED_BULLETS
1736 .iter()
1966 .iter()
1737 .find_map(|bullet| trimmed.strip_prefix(bullet))
1967 .find_map(|bullet| trimmed.strip_prefix(bullet))
1738 {
1968 {
@@ -1758,6 +1988,24 @@ fn markdown_lines(text: &str) -> Vec<DraftLine> {
1758 lines
1988 lines
1759}
1989}
1760
1990
1991fn table_line(table: Table) -> DraftLine {
1992 DraftLine {
1993 kind: LineKind::Table(table),
1994 number: None,
1995 content: TABLE_MARK.to_string(),
1996 marks: Vec::new(),
1997 }
1998}
1999
2000/// `# ` to `###### `: the level, capped at the three Teams offers, and the rest of the line.
2001fn heading_prefix(line: &str) -> Option<(u8, &str)> {
2002 let hashes = line.bytes().take_while(|byte| *byte == b'#').count();
2003 let rest = line[hashes..].strip_prefix(' ')?;
2004 (1..=6)
2005 .contains(&hashes)
2006 .then(|| ((hashes as u8).min(MAX_HEADING), rest))
2007}
2008
1761fn parse_inline(source: &str) -> (String, Vec<Mark>) {
2009fn parse_inline(source: &str) -> (String, Vec<Mark>) {
1762 let mut text = String::with_capacity(source.len());
2010 let mut text = String::with_capacity(source.len());
1763 let mut marks = Vec::new();
2011 let mut marks = Vec::new();
@@ -1849,6 +2097,17 @@ fn inline_at(rest: &str, previous: Option<char>) -> Option<(&str, usize, MarkKin
1849 None
2097 None
1850}
2098}
1851
2099
2100fn cell_text(spans: &[Span]) -> String {
2101 let mut builder = SpanLines::default();
2102 builder.walk(spans, &LineKind::Text, &[]);
2103 builder
2104 .finish()
2105 .into_iter()
2106 .map(|line| line.content)
2107 .collect::<Vec<_>>()
2108 .join("\n")
2109}
2110
1852#[derive(Default)]
2111#[derive(Default)]
1853struct SpanLines {
2112struct SpanLines {
1854 lines: Vec<DraftLine>,
2113 lines: Vec<DraftLine>,
@@ -1936,9 +2195,10 @@ impl SpanLines {
1936 };
2195 };
1937 self.start_line(&continued, None);
2196 self.start_line(&continued, None);
1938 }
2197 }
1939 Span::Heading { children, .. } => {
2198 Span::Heading { level, children } => {
1940 self.start_line(&LineKind::Text, None);
2199 let heading = LineKind::Heading((*level).clamp(1, MAX_HEADING));
1941 self.walk(children, &LineKind::Text, &with(MarkKind::Bold));
2200 self.start_line(&heading, None);
2201 self.walk(children, &heading, marks);
1942 self.open = false;
2202 self.open = false;
1943 }
2203 }
1944 Span::CodeBlock { language, code } => {
2204 Span::CodeBlock { language, code } => {
@@ -1977,15 +2237,11 @@ impl SpanLines {
1977 self.open = false;
2237 self.open = false;
1978 }
2238 }
1979 Span::Table { rows, .. } => {
2239 Span::Table { rows, .. } => {
1980 for row in rows {
2240 let rows = rows
1981 self.start_line(&LineKind::Text, None);
2241 .iter()
1982 for (position, cell) in row.iter().enumerate() {
2242 .map(|row| row.iter().map(|cell| cell_text(cell)).collect())
1983 if position > 0 {
2243 .collect();
1984 self.append(" | ", &LineKind::Text, &[]);
2244 self.lines.push(table_line(Table::from_rows(rows)));
1985 }
1986 self.walk(cell, &LineKind::Text, marks);
1987 }
1988 }
1989 self.open = false;
2245 self.open = false;
1990 }
2246 }
1991 Span::Image { .. } | Span::Quote { .. } => {}
2247 Span::Image { .. } | Span::Quote { .. } => {}
@@ -2081,7 +2337,7 @@ mod tests {
2081 draft.marks(),
2337 draft.marks(),
2082 [
2338 [
2083 mark(2..6, MarkKind::Bold),
2339 mark(2..6, MarkKind::Bold),
2084 mark(11..13, MarkKind::Italic),
2340 mark(11..13, MarkKind::Bold),
2085 mark(17..19, MarkKind::Italic),
2341 mark(17..19, MarkKind::Italic),
2086 mark(20..24, MarkKind::Strike),
2342 mark(20..24, MarkKind::Strike),
2087 mark(25..29, MarkKind::Code),
2343 mark(25..29, MarkKind::Code),
@@ -2357,9 +2613,12 @@ mod tests {
2357 let numbered = typed_draft("1. one");
2613 let numbered = typed_draft("1. one");
2358 assert_eq!(numbered.text(), "1. one");
2614 assert_eq!(numbered.text(), "1. one");
2359 assert_eq!(numbered.lines(), [LineKind::Numbered(0)]);
2615 assert_eq!(numbered.lines(), [LineKind::Numbered(0)]);
2360 let quote = typed_draft("> said");
2616 let quote = typed_draft(">said");
2361 assert_eq!(quote.text(), "said");
2617 assert_eq!(quote.text(), "said");
2362 assert_eq!(quote.lines(), [LineKind::Quote]);
2618 assert_eq!(quote.lines(), [LineKind::Quote]);
2619 let spaced = typed_draft("> said");
2620 assert_eq!(spaced.text(), " said");
2621 assert_eq!(spaced.lines(), [LineKind::Quote]);
2363 }
2622 }
2364
2623
2365 #[test]
2624 #[test]
crates/core/src/lib.rs +10 −9
@@ -48,11 +48,12 @@ 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 sidebar_sync;
53 mod skin_tone;
54 54 mod spans;
55 55 mod stored;
56 mod table;
56 57 mod time_zone;
57 58 mod translate_sync;
58 59 mod translation;
@@ -66,8 +67,7 @@ pub use adaptive_card::{
66 67 };
67 68 pub use avatars::Avatar;
68 69 pub use call_event::{
69 CallEvent, CallPhase, CallType, Recording, call_event, format_duration,
70 parse_duration_seconds,
70 CallEvent, CallPhase, CallType, Recording, call_event, format_duration, parse_duration_seconds,
71 71 };
72 72 pub use card_actions::{CardActionOutcome, DialogIdentity, TaskDialog, TaskDialogKind};
73 73 pub use card_chart::{
@@ -116,6 +116,9 @@ pub use folders::{
116 116 BoxFuture, ChatFolder, ChatsvcFolderSource, FolderChange, FolderKind, FolderSource,
117 117 store_section_settings, stored_section_settings,
118 118 };
119 pub use forwarded::{
120 FORWARDED_CONTENT_TYPE, ForwardHeader, ForwardInfo, forwarded_texts, forwards, is_forwarded,
121 };
119 122 pub use graph::{
120 123 DriveEntry, DriveFolder, FileReference, HostedImage, KeptAttachment, MentionTarget,
121 124 MessageExtras, SharedFile, UploadedFile,
@@ -142,18 +145,16 @@ pub use receipts::{ReceiptReader, ReceiptState};
142 145 pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};
143 146 pub use scheduled::NOTES_CHAT_ID;
144 147 pub use skin_tone::{skin_tone, store_account_skin_tone};
145 pub use forwarded::{
146 FORWARDED_CONTENT_TYPE, ForwardHeader, ForwardInfo, forwarded_texts, forwards, is_forwarded,
147 };
148 148 pub use spans::{FontSize, Span, html_to_spans};
149 149 pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};
150 150 pub use stored::{
151 151 AttachmentInfo, FileCard, FileKind, ImageKind, ImageRef, MentionInfo, PROFILE_LINK_PREFIX,
152 152 QuoteInfo, ReactionInfo, ReactionSummary, adaptive_cards, attachments, can_delete, can_edit,
153 card_texts, copy_text, files, images, linked_message_spans, linked_message_spans_with, mentions, message_quote,
154 message_spans, quote_html, quotes, reaction_summaries, reactions, readable_text, translated_spans,
155 user_mention_inputs,
153 card_texts, copy_text, files, images, linked_message_spans, linked_message_spans_with,
154 mentions, message_quote, message_spans, quote_html, quotes, reaction_summaries, reactions,
155 readable_text, translated_spans, user_mention_inputs,
156 156 };
157 pub use table::{Cell, PICKER_COLUMNS, PICKER_ROWS, TABLE_MARK, Table, TableEdit};
157 158 pub use time_zone::local_time;
158 159 pub use translation::{
159 160 FALLBACK_TARGET, LanguageStamp, confident_language, default_target, language_name, min_chars,
@@ -48,11 +48,12 @@ mod receipts;
48mod recording_rights;
48mod recording_rights;
49mod remote;
49mod remote;
50mod scheduled;
50mod scheduled;
51mod skin_tone;
52mod search;
51mod search;
53mod sidebar_sync;
52mod sidebar_sync;
53mod skin_tone;
54mod spans;
54mod spans;
55mod stored;
55mod stored;
56mod table;
56mod time_zone;
57mod time_zone;
57mod translate_sync;
58mod translate_sync;
58mod translation;
59mod translation;
@@ -66,8 +67,7 @@ pub use adaptive_card::{
66};
67};
67pub use avatars::Avatar;
68pub use avatars::Avatar;
68pub use call_event::{
69pub use call_event::{
69 CallEvent, CallPhase, CallType, Recording, call_event, format_duration,
70 CallEvent, CallPhase, CallType, Recording, call_event, format_duration, parse_duration_seconds,
70 parse_duration_seconds,
71};
71};
72pub use card_actions::{CardActionOutcome, DialogIdentity, TaskDialog, TaskDialogKind};
72pub use card_actions::{CardActionOutcome, DialogIdentity, TaskDialog, TaskDialogKind};
73pub use card_chart::{
73pub use card_chart::{
@@ -116,6 +116,9 @@ pub use folders::{
116 BoxFuture, ChatFolder, ChatsvcFolderSource, FolderChange, FolderKind, FolderSource,
116 BoxFuture, ChatFolder, ChatsvcFolderSource, FolderChange, FolderKind, FolderSource,
117 store_section_settings, stored_section_settings,
117 store_section_settings, stored_section_settings,
118};
118};
119pub use forwarded::{
120 FORWARDED_CONTENT_TYPE, ForwardHeader, ForwardInfo, forwarded_texts, forwards, is_forwarded,
121};
119pub use graph::{
122pub use graph::{
120 DriveEntry, DriveFolder, FileReference, HostedImage, KeptAttachment, MentionTarget,
123 DriveEntry, DriveFolder, FileReference, HostedImage, KeptAttachment, MentionTarget,
121 MessageExtras, SharedFile, UploadedFile,
124 MessageExtras, SharedFile, UploadedFile,
@@ -142,18 +145,16 @@ pub use receipts::{ReceiptReader, ReceiptState};
142pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};
145pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};
143pub use scheduled::NOTES_CHAT_ID;
146pub use scheduled::NOTES_CHAT_ID;
144pub use skin_tone::{skin_tone, store_account_skin_tone};
147pub use skin_tone::{skin_tone, store_account_skin_tone};
145pub use forwarded::{
146 FORWARDED_CONTENT_TYPE, ForwardHeader, ForwardInfo, forwarded_texts, forwards, is_forwarded,
147};
148pub use spans::{FontSize, Span, html_to_spans};
148pub use spans::{FontSize, Span, html_to_spans};
149pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};
149pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};
150pub use stored::{
150pub use stored::{
151 AttachmentInfo, FileCard, FileKind, ImageKind, ImageRef, MentionInfo, PROFILE_LINK_PREFIX,
151 AttachmentInfo, FileCard, FileKind, ImageKind, ImageRef, MentionInfo, PROFILE_LINK_PREFIX,
152 QuoteInfo, ReactionInfo, ReactionSummary, adaptive_cards, attachments, can_delete, can_edit,
152 QuoteInfo, ReactionInfo, ReactionSummary, adaptive_cards, attachments, can_delete, can_edit,
153 card_texts, copy_text, files, images, linked_message_spans, linked_message_spans_with, mentions, message_quote,
153 card_texts, copy_text, files, images, linked_message_spans, linked_message_spans_with,
154 message_spans, quote_html, quotes, reaction_summaries, reactions, readable_text, translated_spans,
154 mentions, message_quote, message_spans, quote_html, quotes, reaction_summaries, reactions,
155 user_mention_inputs,
155 readable_text, translated_spans, user_mention_inputs,
156};
156};
157pub use table::{Cell, PICKER_COLUMNS, PICKER_ROWS, TABLE_MARK, Table, TableEdit};
157pub use time_zone::local_time;
158pub use time_zone::local_time;
158pub use translation::{
159pub use translation::{
159 FALLBACK_TARGET, LanguageStamp, confident_language, default_target, language_name, min_chars,
160 FALLBACK_TARGET, LanguageStamp, confident_language, default_target, language_name, min_chars,
crates/core/src/table.rs added +353 −0
@@ -0,0 +1,353 @@
1 use serde::{Deserialize, Serialize};
2
3 use crate::markdown::escape_html;
4
5 pub const TABLE_MARK: char = '\u{FFFB}';
6 pub const PICKER_COLUMNS: usize = 7;
7 pub const PICKER_ROWS: usize = 5;
8 const EMPTY_CELL: &str = "&nbsp;";
9
10 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11 pub struct Cell {
12 pub row: usize,
13 pub column: usize,
14 }
15
16 impl Cell {
17 pub fn new(row: usize, column: usize) -> Cell {
18 Cell { row, column }
19 }
20 }
21
22 /// A composer table: plain text cells, every row as wide as the first.
23 #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
24 pub struct Table {
25 pub rows: Vec<Vec<String>>,
26 }
27
28 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
29 pub enum TableEdit {
30 InsertRowAbove,
31 InsertRowBelow,
32 InsertColumnLeft,
33 InsertColumnRight,
34 DeleteRow,
35 DeleteColumn,
36 DeleteTable,
37 }
38
39 impl TableEdit {
40 pub const INSERTS: [TableEdit; 4] = [
41 TableEdit::InsertRowAbove,
42 TableEdit::InsertRowBelow,
43 TableEdit::InsertColumnLeft,
44 TableEdit::InsertColumnRight,
45 ];
46 pub const DELETES: [TableEdit; 3] = [
47 TableEdit::DeleteRow,
48 TableEdit::DeleteColumn,
49 TableEdit::DeleteTable,
50 ];
51
52 pub fn label(self) -> &'static str {
53 match self {
54 TableEdit::InsertRowAbove => "Insert row above",
55 TableEdit::InsertRowBelow => "Insert row below",
56 TableEdit::InsertColumnLeft => "Insert column to the left",
57 TableEdit::InsertColumnRight => "Insert column to the right",
58 TableEdit::DeleteRow => "Delete row",
59 TableEdit::DeleteColumn => "Delete column",
60 TableEdit::DeleteTable => "Delete table",
61 }
62 }
63 }
64
65 impl Table {
66 pub fn new(rows: usize, columns: usize) -> Table {
67 Table {
68 rows: vec![vec![String::new(); columns.max(1)]; rows.max(1)],
69 }
70 }
71
72 /// Short rows are filled up to the widest one.
73 pub fn from_rows(mut rows: Vec<Vec<String>>) -> Table {
74 rows.retain(|row| !row.is_empty());
75 let columns = rows.iter().map(Vec::len).max().unwrap_or(1);
76 for row in &mut rows {
77 row.resize(columns, String::new());
78 }
79 if rows.is_empty() {
80 return Table::new(1, 1);
81 }
82 Table { rows }
83 }
84
85 pub fn row_count(&self) -> usize {
86 self.rows.len()
87 }
88
89 pub fn column_count(&self) -> usize {
90 self.rows.first().map_or(0, Vec::len)
91 }
92
93 pub fn cell(&self, cell: Cell) -> Option<&str> {
94 self.rows
95 .get(cell.row)?
96 .get(cell.column)
97 .map(String::as_str)
98 }
99
100 pub fn set_cell(&mut self, cell: Cell, text: &str) {
101 if let Some(slot) = self
102 .rows
103 .get_mut(cell.row)
104 .and_then(|row| row.get_mut(cell.column))
105 {
106 *slot = text.to_owned();
107 }
108 }
109
110 pub fn last_cell(&self) -> Cell {
111 Cell::new(self.row_count() - 1, self.column_count() - 1)
112 }
113
114 /// Tab: the next cell, and past the last one a new row (`true`) like Teams.
115 pub fn next_cell(&mut self, cell: Cell) -> (Cell, bool) {
116 if cell.column + 1 < self.column_count() {
117 return (Cell::new(cell.row, cell.column + 1), false);
118 }
119 if cell.row + 1 < self.row_count() {
120 return (Cell::new(cell.row + 1, 0), false);
121 }
122 self.rows.push(vec![String::new(); self.column_count()]);
123 (Cell::new(cell.row + 1, 0), true)
124 }
125
126 /// Shift+Tab: the previous cell; the first cell stays.
127 pub fn previous_cell(&self, cell: Cell) -> Cell {
128 match (cell.row, cell.column) {
129 (_, column) if column > 0 => Cell::new(cell.row, column - 1),
130 (0, _) => cell,
131 (row, _) => Cell::new(row - 1, self.column_count() - 1),
132 }
133 }
134
135 /// The cell to focus afterwards; `None` when the table is gone.
136 pub fn apply(&mut self, edit: TableEdit, cell: Cell) -> Option<Cell> {
137 let columns = self.column_count();
138 match edit {
139 TableEdit::InsertRowAbove => {
140 self.rows.insert(cell.row, vec![String::new(); columns]);
141 Some(Cell::new(cell.row, cell.column))
142 }
143 TableEdit::InsertRowBelow => {
144 self.rows.insert(cell.row + 1, vec![String::new(); columns]);
145 Some(Cell::new(cell.row + 1, cell.column))
146 }
147 TableEdit::InsertColumnLeft => {
148 for row in &mut self.rows {
149 row.insert(cell.column, String::new());
150 }
151 Some(Cell::new(cell.row, cell.column))
152 }
153 TableEdit::InsertColumnRight => {
154 for row in &mut self.rows {
155 row.insert(cell.column + 1, String::new());
156 }
157 Some(Cell::new(cell.row, cell.column + 1))
158 }
159 TableEdit::DeleteRow if self.row_count() > 1 => {
160 self.rows.remove(cell.row);
161 Some(Cell::new(cell.row.min(self.row_count() - 1), cell.column))
162 }
163 TableEdit::DeleteColumn if columns > 1 => {
164 for row in &mut self.rows {
165 row.remove(cell.column);
166 }
167 Some(Cell::new(
168 cell.row,
169 cell.column.min(self.column_count() - 1),
170 ))
171 }
172 TableEdit::DeleteRow | TableEdit::DeleteColumn | TableEdit::DeleteTable => None,
173 }
174 }
175
176 pub fn is_blank(&self) -> bool {
177 self.rows
178 .iter()
179 .flatten()
180 .all(|cell| cell.trim().is_empty())
181 }
182
183 /// Rows on lines, cells split by tabs: what a spreadsheet pastes.
184 pub fn plain_text(&self) -> String {
185 self.rows
186 .iter()
187 .map(|row| row.join("\t").replace('\n', " "))
188 .collect::<Vec<_>>()
189 .join("\n")
190 }
191
192 /// The table Teams sends: CKEditor's `figure.table`, `copy-paste-table` on the table, a one
193 /// line cell without `<p>`, every line of a longer cell in its own `<p>`, empty `&nbsp;`.
194 pub fn to_html(&self) -> String {
195 let mut html =
196 String::from("<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>");
197 for row in &self.rows {
198 html.push_str("<tr>");
199 for cell in row {
200 html.push_str("<td>");
201 if cell.trim().is_empty() {
202 html.push_str(EMPTY_CELL);
203 } else if !cell.contains('\n') {
204 html.push_str(&escape_html(cell));
205 } else {
206 for line in cell.split('\n') {
207 html.push_str("<p>");
208 if line.trim().is_empty() {
209 html.push_str(EMPTY_CELL);
210 } else {
211 html.push_str(&escape_html(line));
212 }
213 html.push_str("</p>");
214 }
215 }
216 html.push_str("</td>");
217 }
218 html.push_str("</tr>");
219 }
220 html.push_str("</tbody></table></figure>");
221 html
222 }
223 }
224
225 fn split_row(line: &str) -> Option<Vec<String>> {
226 let trimmed = line.trim();
227 if !trimmed.contains('|') {
228 return None;
229 }
230 let inner = trimmed.strip_prefix('|').unwrap_or(trimmed);
231 let inner = inner.strip_suffix('|').unwrap_or(inner);
232 let mut cells = Vec::new();
233 let mut current = String::new();
234 let mut characters = inner.chars().peekable();
235 while let Some(character) = characters.next() {
236 match character {
237 '\\' if characters.peek() == Some(&'|') => {
238 current.push('|');
239 characters.next();
240 }
241 '|' => cells.push(std::mem::take(&mut current).trim().to_owned()),
242 other => current.push(other),
243 }
244 }
245 cells.push(current.trim().to_owned());
246 Some(cells)
247 }
248
249 fn is_delimiter_row(line: &str) -> bool {
250 split_row(line).is_some_and(|cells| {
251 cells.iter().all(|cell| {
252 let dashes = cell.trim_start_matches(':').trim_end_matches(':');
253 !dashes.is_empty() && dashes.chars().all(|character| character == '-')
254 })
255 })
256 }
257
258 /// A GitHub markdown table at the start of `lines`: header, delimiter row, body rows.
259 /// Returns the raw cell sources and how many lines it spans.
260 pub(crate) fn markdown_table(lines: &[&str]) -> Option<(Vec<Vec<String>>, usize)> {
261 let header = split_row(lines.first()?)?;
262 if !lines.get(1).is_some_and(|line| is_delimiter_row(line)) {
263 return None;
264 }
265 let delimiter_columns = split_row(lines[1])?.len();
266 if delimiter_columns != header.len() {
267 return None;
268 }
269 let mut rows = vec![header];
270 let mut consumed = 2;
271 for line in &lines[2..] {
272 match split_row(line) {
273 Some(cells) if !line.trim().is_empty() => rows.push(cells),
274 _ => break,
275 }
276 consumed += 1;
277 }
278 Some((rows, consumed))
279 }
280
281 #[cfg(test)]
282 mod tests {
283 use super::*;
284
285 #[test]
286 fn tab_walks_the_cells_and_adds_a_row_after_the_last() {
287 let mut table = Table::new(2, 2);
288 assert_eq!(table.next_cell(Cell::new(0, 0)), (Cell::new(0, 1), false));
289 assert_eq!(table.next_cell(Cell::new(0, 1)), (Cell::new(1, 0), false));
290 assert_eq!(table.next_cell(Cell::new(1, 1)), (Cell::new(2, 0), true));
291 assert_eq!(table.row_count(), 3);
292 assert_eq!(table.column_count(), 2);
293 }
294
295 #[test]
296 fn shift_tab_walks_back_and_stops_at_the_first_cell() {
297 let table = Table::new(2, 3);
298 assert_eq!(table.previous_cell(Cell::new(1, 0)), Cell::new(0, 2));
299 assert_eq!(table.previous_cell(Cell::new(0, 1)), Cell::new(0, 0));
300 assert_eq!(table.previous_cell(Cell::new(0, 0)), Cell::new(0, 0));
301 }
302
303 #[test]
304 fn rows_and_columns_insert_and_delete_around_the_cell() {
305 let mut table = Table::from_rows(vec![
306 vec!["a".into(), "b".into()],
307 vec!["c".into(), "d".into()],
308 ]);
309 assert_eq!(
310 table.apply(TableEdit::InsertRowAbove, Cell::new(1, 1)),
311 Some(Cell::new(1, 1))
312 );
313 assert_eq!(table.rows[1], ["", ""]);
314 assert_eq!(
315 table.apply(TableEdit::InsertColumnRight, Cell::new(0, 0)),
316 Some(Cell::new(0, 1))
317 );
318 assert_eq!(table.rows[0], ["a", "", "b"]);
319 table.apply(TableEdit::DeleteColumn, Cell::new(0, 1));
320 table.apply(TableEdit::DeleteRow, Cell::new(1, 0));
321 assert_eq!(table.rows, [["a", "b"], ["c", "d"]]);
322 assert_eq!(table.apply(TableEdit::DeleteTable, Cell::new(0, 0)), None);
323 }
324
325 #[test]
326 fn deleting_the_last_row_or_column_deletes_the_table() {
327 let mut table = Table::new(1, 2);
328 assert_eq!(table.apply(TableEdit::DeleteRow, Cell::new(0, 0)), None);
329 let mut table = Table::new(2, 1);
330 assert_eq!(table.apply(TableEdit::DeleteColumn, Cell::new(0, 0)), None);
331 }
332
333 #[test]
334 fn html_is_the_copy_paste_table_teams_sends() {
335 let table = Table::from_rows(vec![vec!["a<b".into(), String::new()], vec!["x\ny".into()]]);
336 assert_eq!(
337 table.to_html(),
338 "<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\
339 <tr><td>a&lt;b</td><td>&nbsp;</td></tr>\
340 <tr><td><p>x</p><p>y</p></td><td>&nbsp;</td></tr></tbody></table></figure>"
341 );
342 }
343
344 #[test]
345 fn markdown_tables_need_a_delimiter_row() {
346 let lines = ["| A | B |", "|---|:-:|", "| 1 | 2 \\| 3 |", "", "after"];
347 let (rows, consumed) = markdown_table(&lines).unwrap();
348 assert_eq!(consumed, 3);
349 assert_eq!(rows, [["A", "B"], ["1", "2 | 3"]]);
350 assert!(markdown_table(&["a | b", "c | d"]).is_none());
351 assert!(markdown_table(&["| a | b |", "|---|"]).is_none());
352 }
353 }
@@ -0,0 +1,353 @@
1use serde::{Deserialize, Serialize};
2
3use crate::markdown::escape_html;
4
5pub const TABLE_MARK: char = '\u{FFFB}';
6pub const PICKER_COLUMNS: usize = 7;
7pub const PICKER_ROWS: usize = 5;
8const EMPTY_CELL: &str = "&nbsp;";
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11pub struct Cell {
12 pub row: usize,
13 pub column: usize,
14}
15
16impl Cell {
17 pub fn new(row: usize, column: usize) -> Cell {
18 Cell { row, column }
19 }
20}
21
22/// A composer table: plain text cells, every row as wide as the first.
23#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
24pub struct Table {
25 pub rows: Vec<Vec<String>>,
26}
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum TableEdit {
30 InsertRowAbove,
31 InsertRowBelow,
32 InsertColumnLeft,
33 InsertColumnRight,
34 DeleteRow,
35 DeleteColumn,
36 DeleteTable,
37}
38
39impl TableEdit {
40 pub const INSERTS: [TableEdit; 4] = [
41 TableEdit::InsertRowAbove,
42 TableEdit::InsertRowBelow,
43 TableEdit::InsertColumnLeft,
44 TableEdit::InsertColumnRight,
45 ];
46 pub const DELETES: [TableEdit; 3] = [
47 TableEdit::DeleteRow,
48 TableEdit::DeleteColumn,
49 TableEdit::DeleteTable,
50 ];
51
52 pub fn label(self) -> &'static str {
53 match self {
54 TableEdit::InsertRowAbove => "Insert row above",
55 TableEdit::InsertRowBelow => "Insert row below",
56 TableEdit::InsertColumnLeft => "Insert column to the left",
57 TableEdit::InsertColumnRight => "Insert column to the right",
58 TableEdit::DeleteRow => "Delete row",
59 TableEdit::DeleteColumn => "Delete column",
60 TableEdit::DeleteTable => "Delete table",
61 }
62 }
63}
64
65impl Table {
66 pub fn new(rows: usize, columns: usize) -> Table {
67 Table {
68 rows: vec![vec![String::new(); columns.max(1)]; rows.max(1)],
69 }
70 }
71
72 /// Short rows are filled up to the widest one.
73 pub fn from_rows(mut rows: Vec<Vec<String>>) -> Table {
74 rows.retain(|row| !row.is_empty());
75 let columns = rows.iter().map(Vec::len).max().unwrap_or(1);
76 for row in &mut rows {
77 row.resize(columns, String::new());
78 }
79 if rows.is_empty() {
80 return Table::new(1, 1);
81 }
82 Table { rows }
83 }
84
85 pub fn row_count(&self) -> usize {
86 self.rows.len()
87 }
88
89 pub fn column_count(&self) -> usize {
90 self.rows.first().map_or(0, Vec::len)
91 }
92
93 pub fn cell(&self, cell: Cell) -> Option<&str> {
94 self.rows
95 .get(cell.row)?
96 .get(cell.column)
97 .map(String::as_str)
98 }
99
100 pub fn set_cell(&mut self, cell: Cell, text: &str) {
101 if let Some(slot) = self
102 .rows
103 .get_mut(cell.row)
104 .and_then(|row| row.get_mut(cell.column))
105 {
106 *slot = text.to_owned();
107 }
108 }
109
110 pub fn last_cell(&self) -> Cell {
111 Cell::new(self.row_count() - 1, self.column_count() - 1)
112 }
113
114 /// Tab: the next cell, and past the last one a new row (`true`) like Teams.
115 pub fn next_cell(&mut self, cell: Cell) -> (Cell, bool) {
116 if cell.column + 1 < self.column_count() {
117 return (Cell::new(cell.row, cell.column + 1), false);
118 }
119 if cell.row + 1 < self.row_count() {
120 return (Cell::new(cell.row + 1, 0), false);
121 }
122 self.rows.push(vec![String::new(); self.column_count()]);
123 (Cell::new(cell.row + 1, 0), true)
124 }
125
126 /// Shift+Tab: the previous cell; the first cell stays.
127 pub fn previous_cell(&self, cell: Cell) -> Cell {
128 match (cell.row, cell.column) {
129 (_, column) if column > 0 => Cell::new(cell.row, column - 1),
130 (0, _) => cell,
131 (row, _) => Cell::new(row - 1, self.column_count() - 1),
132 }
133 }
134
135 /// The cell to focus afterwards; `None` when the table is gone.
136 pub fn apply(&mut self, edit: TableEdit, cell: Cell) -> Option<Cell> {
137 let columns = self.column_count();
138 match edit {
139 TableEdit::InsertRowAbove => {
140 self.rows.insert(cell.row, vec![String::new(); columns]);
141 Some(Cell::new(cell.row, cell.column))
142 }
143 TableEdit::InsertRowBelow => {
144 self.rows.insert(cell.row + 1, vec![String::new(); columns]);
145 Some(Cell::new(cell.row + 1, cell.column))
146 }
147 TableEdit::InsertColumnLeft => {
148 for row in &mut self.rows {
149 row.insert(cell.column, String::new());
150 }
151 Some(Cell::new(cell.row, cell.column))
152 }
153 TableEdit::InsertColumnRight => {
154 for row in &mut self.rows {
155 row.insert(cell.column + 1, String::new());
156 }
157 Some(Cell::new(cell.row, cell.column + 1))
158 }
159 TableEdit::DeleteRow if self.row_count() > 1 => {
160 self.rows.remove(cell.row);
161 Some(Cell::new(cell.row.min(self.row_count() - 1), cell.column))
162 }
163 TableEdit::DeleteColumn if columns > 1 => {
164 for row in &mut self.rows {
165 row.remove(cell.column);
166 }
167 Some(Cell::new(
168 cell.row,
169 cell.column.min(self.column_count() - 1),
170 ))
171 }
172 TableEdit::DeleteRow | TableEdit::DeleteColumn | TableEdit::DeleteTable => None,
173 }
174 }
175
176 pub fn is_blank(&self) -> bool {
177 self.rows
178 .iter()
179 .flatten()
180 .all(|cell| cell.trim().is_empty())
181 }
182
183 /// Rows on lines, cells split by tabs: what a spreadsheet pastes.
184 pub fn plain_text(&self) -> String {
185 self.rows
186 .iter()
187 .map(|row| row.join("\t").replace('\n', " "))
188 .collect::<Vec<_>>()
189 .join("\n")
190 }
191
192 /// The table Teams sends: CKEditor's `figure.table`, `copy-paste-table` on the table, a one
193 /// line cell without `<p>`, every line of a longer cell in its own `<p>`, empty `&nbsp;`.
194 pub fn to_html(&self) -> String {
195 let mut html =
196 String::from("<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>");
197 for row in &self.rows {
198 html.push_str("<tr>");
199 for cell in row {
200 html.push_str("<td>");
201 if cell.trim().is_empty() {
202 html.push_str(EMPTY_CELL);
203 } else if !cell.contains('\n') {
204 html.push_str(&escape_html(cell));
205 } else {
206 for line in cell.split('\n') {
207 html.push_str("<p>");
208 if line.trim().is_empty() {
209 html.push_str(EMPTY_CELL);
210 } else {
211 html.push_str(&escape_html(line));
212 }
213 html.push_str("</p>");
214 }
215 }
216 html.push_str("</td>");
217 }
218 html.push_str("</tr>");
219 }
220 html.push_str("</tbody></table></figure>");
221 html
222 }
223}
224
225fn split_row(line: &str) -> Option<Vec<String>> {
226 let trimmed = line.trim();
227 if !trimmed.contains('|') {
228 return None;
229 }
230 let inner = trimmed.strip_prefix('|').unwrap_or(trimmed);
231 let inner = inner.strip_suffix('|').unwrap_or(inner);
232 let mut cells = Vec::new();
233 let mut current = String::new();
234 let mut characters = inner.chars().peekable();
235 while let Some(character) = characters.next() {
236 match character {
237 '\\' if characters.peek() == Some(&'|') => {
238 current.push('|');
239 characters.next();
240 }
241 '|' => cells.push(std::mem::take(&mut current).trim().to_owned()),
242 other => current.push(other),
243 }
244 }
245 cells.push(current.trim().to_owned());
246 Some(cells)
247}
248
249fn is_delimiter_row(line: &str) -> bool {
250 split_row(line).is_some_and(|cells| {
251 cells.iter().all(|cell| {
252 let dashes = cell.trim_start_matches(':').trim_end_matches(':');
253 !dashes.is_empty() && dashes.chars().all(|character| character == '-')
254 })
255 })
256}
257
258/// A GitHub markdown table at the start of `lines`: header, delimiter row, body rows.
259/// Returns the raw cell sources and how many lines it spans.
260pub(crate) fn markdown_table(lines: &[&str]) -> Option<(Vec<Vec<String>>, usize)> {
261 let header = split_row(lines.first()?)?;
262 if !lines.get(1).is_some_and(|line| is_delimiter_row(line)) {
263 return None;
264 }
265 let delimiter_columns = split_row(lines[1])?.len();
266 if delimiter_columns != header.len() {
267 return None;
268 }
269 let mut rows = vec![header];
270 let mut consumed = 2;
271 for line in &lines[2..] {
272 match split_row(line) {
273 Some(cells) if !line.trim().is_empty() => rows.push(cells),
274 _ => break,
275 }
276 consumed += 1;
277 }
278 Some((rows, consumed))
279}
280
281#[cfg(test)]
282mod tests {
283 use super::*;
284
285 #[test]
286 fn tab_walks_the_cells_and_adds_a_row_after_the_last() {
287 let mut table = Table::new(2, 2);
288 assert_eq!(table.next_cell(Cell::new(0, 0)), (Cell::new(0, 1), false));
289 assert_eq!(table.next_cell(Cell::new(0, 1)), (Cell::new(1, 0), false));
290 assert_eq!(table.next_cell(Cell::new(1, 1)), (Cell::new(2, 0), true));
291 assert_eq!(table.row_count(), 3);
292 assert_eq!(table.column_count(), 2);
293 }
294
295 #[test]
296 fn shift_tab_walks_back_and_stops_at_the_first_cell() {
297 let table = Table::new(2, 3);
298 assert_eq!(table.previous_cell(Cell::new(1, 0)), Cell::new(0, 2));
299 assert_eq!(table.previous_cell(Cell::new(0, 1)), Cell::new(0, 0));
300 assert_eq!(table.previous_cell(Cell::new(0, 0)), Cell::new(0, 0));
301 }
302
303 #[test]
304 fn rows_and_columns_insert_and_delete_around_the_cell() {
305 let mut table = Table::from_rows(vec![
306 vec!["a".into(), "b".into()],
307 vec!["c".into(), "d".into()],
308 ]);
309 assert_eq!(
310 table.apply(TableEdit::InsertRowAbove, Cell::new(1, 1)),
311 Some(Cell::new(1, 1))
312 );
313 assert_eq!(table.rows[1], ["", ""]);
314 assert_eq!(
315 table.apply(TableEdit::InsertColumnRight, Cell::new(0, 0)),
316 Some(Cell::new(0, 1))
317 );
318 assert_eq!(table.rows[0], ["a", "", "b"]);
319 table.apply(TableEdit::DeleteColumn, Cell::new(0, 1));
320 table.apply(TableEdit::DeleteRow, Cell::new(1, 0));
321 assert_eq!(table.rows, [["a", "b"], ["c", "d"]]);
322 assert_eq!(table.apply(TableEdit::DeleteTable, Cell::new(0, 0)), None);
323 }
324
325 #[test]
326 fn deleting_the_last_row_or_column_deletes_the_table() {
327 let mut table = Table::new(1, 2);
328 assert_eq!(table.apply(TableEdit::DeleteRow, Cell::new(0, 0)), None);
329 let mut table = Table::new(2, 1);
330 assert_eq!(table.apply(TableEdit::DeleteColumn, Cell::new(0, 0)), None);
331 }
332
333 #[test]
334 fn html_is_the_copy_paste_table_teams_sends() {
335 let table = Table::from_rows(vec![vec!["a<b".into(), String::new()], vec!["x\ny".into()]]);
336 assert_eq!(
337 table.to_html(),
338 "<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\
339 <tr><td>a&lt;b</td><td>&nbsp;</td></tr>\
340 <tr><td><p>x</p><p>y</p></td><td>&nbsp;</td></tr></tbody></table></figure>"
341 );
342 }
343
344 #[test]
345 fn markdown_tables_need_a_delimiter_row() {
346 let lines = ["| A | B |", "|---|:-:|", "| 1 | 2 \\| 3 |", "", "after"];
347 let (rows, consumed) = markdown_table(&lines).unwrap();
348 assert_eq!(consumed, 3);
349 assert_eq!(rows, [["A", "B"], ["1", "2 | 3"]]);
350 assert!(markdown_table(&["a | b", "c | d"]).is_none());
351 assert!(markdown_table(&["| a | b |", "|---|"]).is_none());
352 }
353}
crates/core/tests/composer_blocks.rs added +341 −0
@@ -0,0 +1,341 @@
1 use teams_core::{
2 Draft, DraftLine, LineKind, Mark, MarkKind, TABLE_MARK, Table, TypingStyle, html_to_spans,
3 };
4
5 fn typed(draft: &mut Draft, text: &str) {
6 let mut typing: Option<TypingStyle> = None;
7 for character in text.chars() {
8 let cursor = draft.text().len();
9 let mut next = draft.text().to_owned();
10 next.push(character);
11 let cursor = draft.apply_edit(&next, cursor + character.len_utf8(), typing.as_ref());
12 typing = draft.convert_typed(cursor).map(|(_, style)| style);
13 draft.take_edits();
14 }
15 }
16
17 fn typed_draft(text: &str) -> Draft {
18 let mut draft = Draft::default();
19 typed(&mut draft, text);
20 draft
21 }
22
23 fn enter(draft: &mut Draft, cursor: usize, shift: bool) -> Option<usize> {
24 let result = draft.break_line(cursor, shift);
25 draft.take_edits();
26 result
27 }
28
29 fn table_of(rows: &[&[&str]]) -> Table {
30 Table::from_rows(
31 rows.iter()
32 .map(|row| row.iter().map(|cell| (*cell).to_owned()).collect())
33 .collect(),
34 )
35 }
36
37 #[test]
38 fn enter_in_a_quote_adds_a_quote_line_and_enter_on_the_empty_one_leaves() {
39 let mut draft = typed_draft(">abc");
40 let cursor = enter(&mut draft, 3, false).unwrap();
41 assert_eq!(draft.text(), "abc\n");
42 assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Quote]);
43 let cursor = enter(&mut draft, cursor, false).unwrap();
44 assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Text]);
45 assert_eq!(cursor, 4);
46 assert_eq!(enter(&mut draft, cursor, false), None);
47 assert_eq!(draft.to_html(), "<blockquote>abc</blockquote>");
48 }
49
50 #[test]
51 fn enter_on_an_empty_quote_line_in_the_middle_splits_the_quote() {
52 let mut draft = Draft::from_markdown("> a\n> \n> b");
53 enter(&mut draft, 2, false).unwrap();
54 assert_eq!(
55 draft.lines(),
56 [LineKind::Quote, LineKind::Text, LineKind::Quote]
57 );
58 }
59
60 #[test]
61 fn shift_enter_keeps_breaking_inside_the_quote() {
62 let mut draft = typed_draft(">a");
63 let cursor = enter(&mut draft, 1, true).unwrap();
64 let cursor = enter(&mut draft, cursor, true).unwrap();
65 assert_eq!(cursor, 3);
66 assert_eq!(
67 draft.lines(),
68 [LineKind::Quote, LineKind::Quote, LineKind::Quote]
69 );
70 }
71
72 #[test]
73 fn backspace_at_the_start_of_a_quote_leaves_it_or_joins_the_line_above() {
74 let mut empty = typed_draft(">");
75 assert_eq!(empty.backspace_at_start(0), Some(0));
76 assert_eq!(empty.lines(), [LineKind::Text]);
77
78 let mut joined = Draft::from_markdown("x\n> abc");
79 assert_eq!(joined.backspace_at_start(2), Some(1));
80 assert_eq!(joined.text(), "xabc");
81 assert_eq!(joined.lines(), [LineKind::Text]);
82
83 let mut inner = Draft::from_markdown("> a\n> b");
84 assert_eq!(inner.backspace_at_start(2), Some(1));
85 assert_eq!(inner.text(), "ab");
86 assert_eq!(inner.lines(), [LineKind::Quote]);
87 }
88
89 #[test]
90 fn down_at_the_end_of_a_closing_quote_opens_a_text_line_below() {
91 let mut draft = typed_draft(">abc");
92 assert_eq!(draft.leave_quote_at_end(1), None);
93 assert_eq!(draft.leave_quote_at_end(3), Some(4));
94 assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Text]);
95 assert_eq!(Draft::plain("x").leave_quote_at_end(1), None);
96 }
97
98 #[test]
99 fn teams_shortcuts_make_headings_bold_italic_and_code() {
100 let heading = typed_draft("## Plan");
101 assert_eq!(heading.text(), "Plan");
102 assert_eq!(heading.lines(), [LineKind::Heading(2)]);
103 assert_eq!(heading.to_html(), "<h2>Plan</h2>");
104 assert_eq!(typed_draft("#### deep").lines(), [LineKind::Heading(3)]);
105 assert_eq!(typed_draft("#nope").lines(), [LineKind::Text]);
106
107 let inline = typed_draft("*b* _i_ `c`");
108 assert_eq!(inline.text(), "b i c");
109 assert_eq!(
110 inline.marks(),
111 [
112 Mark {
113 range: 0..1,
114 kind: MarkKind::Bold
115 },
116 Mark {
117 range: 2..3,
118 kind: MarkKind::Italic
119 },
120 Mark {
121 range: 4..5,
122 kind: MarkKind::Code
123 },
124 ]
125 );
126 }
127
128 #[test]
129 fn enter_in_a_heading_is_left_to_send_and_backspace_makes_it_text() {
130 let mut draft = typed_draft("# a");
131 assert_eq!(enter(&mut draft, 1, false), None);
132 assert_eq!(draft.backspace_at_start(0), Some(0));
133 assert_eq!(draft.lines(), [LineKind::Text]);
134 }
135
136 #[test]
137 fn an_inserted_table_takes_an_empty_line_and_gets_a_line_after_it() {
138 let mut draft = Draft::default();
139 let index = draft.insert_table(0, Table::new(2, 3));
140 assert_eq!(index, 0);
141 assert_eq!(draft.text(), format!("{TABLE_MARK}\n"));
142 assert!(draft.lines()[0].is_table());
143 assert_eq!(draft.lines()[1], LineKind::Text);
144
145 let mut below = Draft::plain("hello");
146 assert_eq!(below.insert_table(2, Table::new(1, 1)), 1);
147 assert_eq!(below.text(), format!("hello\n{TABLE_MARK}\n"));
148 }
149
150 #[test]
151 fn a_table_is_sent_as_teams_html_between_the_text() {
152 let mut draft = Draft::plain("before");
153 let index = draft.insert_table(6, Table::new(1, 2));
154 draft.set_table(index, table_of(&[&["a", "b"]]));
155 let end = draft.text().len();
156 let mut text = draft.text().to_owned();
157 text.push_str("after");
158 draft.apply_edit(&text, end + 5, None);
159 assert_eq!(
160 draft.trimmed().to_html(),
161 "before<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\
162 <tr><td>a</td><td>b</td></tr></tbody></table></figure>after"
163 );
164 assert_eq!(draft.plain_text(), "before\na\tb\nafter");
165 assert!(
166 !Draft::from_lines(&[DraftLine {
167 kind: LineKind::Table(Table::new(1, 1)),
168 number: None,
169 content: TABLE_MARK.to_string(),
170 marks: Vec::new(),
171 }])
172 .plain_text()
173 .contains(TABLE_MARK)
174 );
175 }
176
177 #[test]
178 fn text_typed_next_to_a_table_moves_to_its_own_line() {
179 let mut draft = Draft::default();
180 draft.insert_table(0, Table::new(1, 1));
181 let mark = TABLE_MARK.len_utf8();
182 let mut text = draft.text().to_owned();
183 text.insert(mark, 'x');
184 let cursor = draft.apply_edit(&text, mark + 1, None);
185 assert_eq!(draft.text(), format!("{TABLE_MARK}\nx\n"));
186 assert_eq!(cursor, mark + 2);
187 assert!(draft.lines()[0].is_table());
188 assert_eq!(draft.lines()[1], LineKind::Text);
189
190 let mut text = draft.text().to_owned();
191 text.insert(0, 'y');
192 let cursor = draft.apply_edit(&text, 1, None);
193 assert_eq!(draft.text(), format!("y\n{TABLE_MARK}\nx\n"));
194 assert_eq!(cursor, 1);
195 assert!(draft.lines()[1].is_table());
196 }
197
198 #[test]
199 fn deleting_the_mark_drops_the_table() {
200 let mut draft = Draft::plain("a");
201 draft.insert_table(1, Table::new(1, 1));
202 draft.apply_edit("a\n\n", 2, None);
203 assert!(draft.lines().iter().all(|kind| !kind.is_table()));
204 }
205
206 #[test]
207 fn delete_before_a_table_and_backspace_after_it_find_the_table() {
208 let mut draft = Draft::plain("a");
209 let index = draft.insert_table(1, Table::new(1, 1));
210 assert_eq!(draft.table_after(1), Some(index));
211 assert_eq!(draft.delete_forward(1), Some(1));
212 assert!(draft.lines()[index].is_table());
213 let after = draft.text().len();
214 assert_eq!(draft.table_before(after), Some(index));
215 assert_eq!(draft.table_before(0), None);
216 }
217
218 #[test]
219 fn leaving_a_table_lands_beside_it_and_adds_a_line_when_needed() {
220 let mut draft = Draft::default();
221 draft.insert_table(0, Table::new(1, 1));
222 assert_eq!(draft.line_beside_table(0, false), 0);
223 assert_eq!(draft.lines()[0], LineKind::Text);
224 assert!(draft.lines()[1].is_table());
225 let below = draft.line_beside_table(1, true);
226 assert_eq!(draft.line_at(below), 2);
227 }
228
229 #[test]
230 fn removing_a_table_keeps_the_lines_around_it() {
231 let mut draft = Draft::from_markdown("> a");
232 let index = draft.insert_table(3, Table::new(1, 1));
233 let end = draft.text().len();
234 let mut text = draft.text().to_owned();
235 text.push('z');
236 draft.apply_edit(&text, end + 1, None);
237 let cursor = draft.remove_table(index);
238 assert_eq!(draft.text(), "a\nz");
239 assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Text]);
240 assert_eq!(cursor, 2);
241 }
242
243 #[test]
244 fn quote_and_list_buttons_leave_a_table_alone() {
245 let mut draft = Draft::plain("a");
246 let index = draft.insert_table(1, Table::new(1, 1));
247 let end = draft.text().len();
248 draft.toggle_lines(0..end, LineKind::Quote);
249 assert!(draft.lines()[index].is_table());
250 }
251
252 #[test]
253 fn a_copied_table_pastes_into_the_middle_of_a_line() {
254 let mut source = Draft::default();
255 let index = source.insert_table(0, table_of(&[&["1", "2"]]));
256 let copied = source.slice(0..TABLE_MARK.len_utf8());
257 let mut draft = Draft::plain("abcd");
258 draft.insert_lines(2..2, &copied);
259 assert_eq!(draft.text(), format!("ab\n{TABLE_MARK}\ncd"));
260 assert_eq!(draft.table(1), source.table(index));
261 }
262
263 #[test]
264 fn pasted_markdown_becomes_headings_lists_quotes_code_and_tables() {
265 let markdown = "# Title\n\nSome **bold**, *it*, ~~gone~~, `code` and [docs](https://x.de)\n\n\
266 1. one\n 1. nested\n2. two\n- dot\n - inner\n\n> quoted\n\n```rust\nfn x() {}\n```\n\n\
267 | A | B |\n|---|---|\n| **1** | 2 |\n";
268 let draft = Draft::from_markdown(markdown);
269 let kinds: Vec<LineKind> = draft
270 .lines()
271 .iter()
272 .filter(|kind| **kind != LineKind::Text)
273 .cloned()
274 .collect();
275 assert_eq!(
276 kinds,
277 [
278 LineKind::Heading(1),
279 LineKind::Numbered(0),
280 LineKind::Numbered(1),
281 LineKind::Numbered(0),
282 LineKind::Bullet(0),
283 LineKind::Bullet(1),
284 LineKind::Quote,
285 LineKind::Code(Some("rust".into())),
286 LineKind::Table(table_of(&[&["A", "B"], &["1", "2"]])),
287 ]
288 );
289 let html = draft.trimmed().to_html();
290 assert!(html.starts_with("<h1>Title</h1>"), "{html}");
291 assert!(html.contains("<b>bold</b>, <i>it</i>, <s>gone</s>, <code>code</code>"));
292 assert!(html.contains("<a href=\"https://x.de\">docs</a>"));
293 assert!(html.contains("<blockquote>quoted</blockquote>"));
294 assert!(html.contains("<pre class=\"language-rust\">fn x() {}</pre>"));
295 assert!(
296 html.ends_with("<td>1</td><td>2</td></tr></tbody></table></figure>"),
297 "{html}"
298 );
299 }
300
301 #[test]
302 fn text_with_pipes_but_no_delimiter_row_stays_text() {
303 assert!(!teams_core::has_markdown("a | b\nc | d"));
304 assert!(teams_core::has_markdown("| a | b |\n| - | - |"));
305 assert!(teams_core::has_markdown("## Heading"));
306 }
307
308 #[test]
309 fn received_tables_and_headings_edit_as_tables_and_headings() {
310 let spans = html_to_spans(
311 "<h2>Notes</h2><table><tbody><tr><td><p>a</p></td><td>b<br>c</td></tr></tbody></table><p>end</p>",
312 );
313 let draft = Draft::from_spans(&spans);
314 assert_eq!(draft.lines()[0], LineKind::Heading(2));
315 assert_eq!(
316 draft.lines()[1],
317 LineKind::Table(table_of(&[&["a", "b\nc"]]))
318 );
319 assert_eq!(draft.lines()[2], LineKind::Text);
320 }
321
322 #[test]
323 fn pasting_markdown_with_a_table_leaves_the_cursor_after_the_paste() {
324 let markdown = "## Plan\n- dot\n> quoted\n\n| Area | Owner |\n|---|---|\n| Sync | Priya |\nend";
325 let lines = Draft::from_markdown(markdown).slice(0..usize::MAX);
326 let mut draft = Draft::default();
327 let cursor = draft.insert_lines(0..0, &lines);
328 assert_eq!(cursor, draft.text().len(), "{:?}", draft.text());
329 }
330
331 #[test]
332 fn a_sent_table_edits_back_into_the_same_table() {
333 let table = table_of(&[&["a", "x\ny"], &["", "b"]]);
334 let draft = Draft::from_spans(&html_to_spans(&table.to_html()));
335 let LineKind::Table(received) = &draft.lines()[0] else {
336 panic!("{:?}", draft.lines());
337 };
338 assert_eq!(received.rows[0], ["a", "x\ny"]);
339 assert!(received.rows[1][0].trim().is_empty());
340 assert_eq!(received.to_html(), table.to_html());
341 }
@@ -0,0 +1,341 @@
1use teams_core::{
2 Draft, DraftLine, LineKind, Mark, MarkKind, TABLE_MARK, Table, TypingStyle, html_to_spans,
3};
4
5fn typed(draft: &mut Draft, text: &str) {
6 let mut typing: Option<TypingStyle> = None;
7 for character in text.chars() {
8 let cursor = draft.text().len();
9 let mut next = draft.text().to_owned();
10 next.push(character);
11 let cursor = draft.apply_edit(&next, cursor + character.len_utf8(), typing.as_ref());
12 typing = draft.convert_typed(cursor).map(|(_, style)| style);
13 draft.take_edits();
14 }
15}
16
17fn typed_draft(text: &str) -> Draft {
18 let mut draft = Draft::default();
19 typed(&mut draft, text);
20 draft
21}
22
23fn enter(draft: &mut Draft, cursor: usize, shift: bool) -> Option<usize> {
24 let result = draft.break_line(cursor, shift);
25 draft.take_edits();
26 result
27}
28
29fn table_of(rows: &[&[&str]]) -> Table {
30 Table::from_rows(
31 rows.iter()
32 .map(|row| row.iter().map(|cell| (*cell).to_owned()).collect())
33 .collect(),
34 )
35}
36
37#[test]
38fn enter_in_a_quote_adds_a_quote_line_and_enter_on_the_empty_one_leaves() {
39 let mut draft = typed_draft(">abc");
40 let cursor = enter(&mut draft, 3, false).unwrap();
41 assert_eq!(draft.text(), "abc\n");
42 assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Quote]);
43 let cursor = enter(&mut draft, cursor, false).unwrap();
44 assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Text]);
45 assert_eq!(cursor, 4);
46 assert_eq!(enter(&mut draft, cursor, false), None);
47 assert_eq!(draft.to_html(), "<blockquote>abc</blockquote>");
48}
49
50#[test]
51fn enter_on_an_empty_quote_line_in_the_middle_splits_the_quote() {
52 let mut draft = Draft::from_markdown("> a\n> \n> b");
53 enter(&mut draft, 2, false).unwrap();
54 assert_eq!(
55 draft.lines(),
56 [LineKind::Quote, LineKind::Text, LineKind::Quote]
57 );
58}
59
60#[test]
61fn shift_enter_keeps_breaking_inside_the_quote() {
62 let mut draft = typed_draft(">a");
63 let cursor = enter(&mut draft, 1, true).unwrap();
64 let cursor = enter(&mut draft, cursor, true).unwrap();
65 assert_eq!(cursor, 3);
66 assert_eq!(
67 draft.lines(),
68 [LineKind::Quote, LineKind::Quote, LineKind::Quote]
69 );
70}
71
72#[test]
73fn backspace_at_the_start_of_a_quote_leaves_it_or_joins_the_line_above() {
74 let mut empty = typed_draft(">");
75 assert_eq!(empty.backspace_at_start(0), Some(0));
76 assert_eq!(empty.lines(), [LineKind::Text]);
77
78 let mut joined = Draft::from_markdown("x\n> abc");
79 assert_eq!(joined.backspace_at_start(2), Some(1));
80 assert_eq!(joined.text(), "xabc");
81 assert_eq!(joined.lines(), [LineKind::Text]);
82
83 let mut inner = Draft::from_markdown("> a\n> b");
84 assert_eq!(inner.backspace_at_start(2), Some(1));
85 assert_eq!(inner.text(), "ab");
86 assert_eq!(inner.lines(), [LineKind::Quote]);
87}
88
89#[test]
90fn down_at_the_end_of_a_closing_quote_opens_a_text_line_below() {
91 let mut draft = typed_draft(">abc");
92 assert_eq!(draft.leave_quote_at_end(1), None);
93 assert_eq!(draft.leave_quote_at_end(3), Some(4));
94 assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Text]);
95 assert_eq!(Draft::plain("x").leave_quote_at_end(1), None);
96}
97
98#[test]
99fn teams_shortcuts_make_headings_bold_italic_and_code() {
100 let heading = typed_draft("## Plan");
101 assert_eq!(heading.text(), "Plan");
102 assert_eq!(heading.lines(), [LineKind::Heading(2)]);
103 assert_eq!(heading.to_html(), "<h2>Plan</h2>");
104 assert_eq!(typed_draft("#### deep").lines(), [LineKind::Heading(3)]);
105 assert_eq!(typed_draft("#nope").lines(), [LineKind::Text]);
106
107 let inline = typed_draft("*b* _i_ `c`");
108 assert_eq!(inline.text(), "b i c");
109 assert_eq!(
110 inline.marks(),
111 [
112 Mark {
113 range: 0..1,
114 kind: MarkKind::Bold
115 },
116 Mark {
117 range: 2..3,
118 kind: MarkKind::Italic
119 },
120 Mark {
121 range: 4..5,
122 kind: MarkKind::Code
123 },
124 ]
125 );
126}
127
128#[test]
129fn enter_in_a_heading_is_left_to_send_and_backspace_makes_it_text() {
130 let mut draft = typed_draft("# a");
131 assert_eq!(enter(&mut draft, 1, false), None);
132 assert_eq!(draft.backspace_at_start(0), Some(0));
133 assert_eq!(draft.lines(), [LineKind::Text]);
134}
135
136#[test]
137fn an_inserted_table_takes_an_empty_line_and_gets_a_line_after_it() {
138 let mut draft = Draft::default();
139 let index = draft.insert_table(0, Table::new(2, 3));
140 assert_eq!(index, 0);
141 assert_eq!(draft.text(), format!("{TABLE_MARK}\n"));
142 assert!(draft.lines()[0].is_table());
143 assert_eq!(draft.lines()[1], LineKind::Text);
144
145 let mut below = Draft::plain("hello");
146 assert_eq!(below.insert_table(2, Table::new(1, 1)), 1);
147 assert_eq!(below.text(), format!("hello\n{TABLE_MARK}\n"));
148}
149
150#[test]
151fn a_table_is_sent_as_teams_html_between_the_text() {
152 let mut draft = Draft::plain("before");
153 let index = draft.insert_table(6, Table::new(1, 2));
154 draft.set_table(index, table_of(&[&["a", "b"]]));
155 let end = draft.text().len();
156 let mut text = draft.text().to_owned();
157 text.push_str("after");
158 draft.apply_edit(&text, end + 5, None);
159 assert_eq!(
160 draft.trimmed().to_html(),
161 "before<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\
162 <tr><td>a</td><td>b</td></tr></tbody></table></figure>after"
163 );
164 assert_eq!(draft.plain_text(), "before\na\tb\nafter");
165 assert!(
166 !Draft::from_lines(&[DraftLine {
167 kind: LineKind::Table(Table::new(1, 1)),
168 number: None,
169 content: TABLE_MARK.to_string(),
170 marks: Vec::new(),
171 }])
172 .plain_text()
173 .contains(TABLE_MARK)
174 );
175}
176
177#[test]
178fn text_typed_next_to_a_table_moves_to_its_own_line() {
179 let mut draft = Draft::default();
180 draft.insert_table(0, Table::new(1, 1));
181 let mark = TABLE_MARK.len_utf8();
182 let mut text = draft.text().to_owned();
183 text.insert(mark, 'x');
184 let cursor = draft.apply_edit(&text, mark + 1, None);
185 assert_eq!(draft.text(), format!("{TABLE_MARK}\nx\n"));
186 assert_eq!(cursor, mark + 2);
187 assert!(draft.lines()[0].is_table());
188 assert_eq!(draft.lines()[1], LineKind::Text);
189
190 let mut text = draft.text().to_owned();
191 text.insert(0, 'y');
192 let cursor = draft.apply_edit(&text, 1, None);
193 assert_eq!(draft.text(), format!("y\n{TABLE_MARK}\nx\n"));
194 assert_eq!(cursor, 1);
195 assert!(draft.lines()[1].is_table());
196}
197
198#[test]
199fn deleting_the_mark_drops_the_table() {
200 let mut draft = Draft::plain("a");
201 draft.insert_table(1, Table::new(1, 1));
202 draft.apply_edit("a\n\n", 2, None);
203 assert!(draft.lines().iter().all(|kind| !kind.is_table()));
204}
205
206#[test]
207fn delete_before_a_table_and_backspace_after_it_find_the_table() {
208 let mut draft = Draft::plain("a");
209 let index = draft.insert_table(1, Table::new(1, 1));
210 assert_eq!(draft.table_after(1), Some(index));
211 assert_eq!(draft.delete_forward(1), Some(1));
212 assert!(draft.lines()[index].is_table());
213 let after = draft.text().len();
214 assert_eq!(draft.table_before(after), Some(index));
215 assert_eq!(draft.table_before(0), None);
216}
217
218#[test]
219fn leaving_a_table_lands_beside_it_and_adds_a_line_when_needed() {
220 let mut draft = Draft::default();
221 draft.insert_table(0, Table::new(1, 1));
222 assert_eq!(draft.line_beside_table(0, false), 0);
223 assert_eq!(draft.lines()[0], LineKind::Text);
224 assert!(draft.lines()[1].is_table());
225 let below = draft.line_beside_table(1, true);
226 assert_eq!(draft.line_at(below), 2);
227}
228
229#[test]
230fn removing_a_table_keeps_the_lines_around_it() {
231 let mut draft = Draft::from_markdown("> a");
232 let index = draft.insert_table(3, Table::new(1, 1));
233 let end = draft.text().len();
234 let mut text = draft.text().to_owned();
235 text.push('z');
236 draft.apply_edit(&text, end + 1, None);
237 let cursor = draft.remove_table(index);
238 assert_eq!(draft.text(), "a\nz");
239 assert_eq!(draft.lines(), [LineKind::Quote, LineKind::Text]);
240 assert_eq!(cursor, 2);
241}
242
243#[test]
244fn quote_and_list_buttons_leave_a_table_alone() {
245 let mut draft = Draft::plain("a");
246 let index = draft.insert_table(1, Table::new(1, 1));
247 let end = draft.text().len();
248 draft.toggle_lines(0..end, LineKind::Quote);
249 assert!(draft.lines()[index].is_table());
250}
251
252#[test]
253fn a_copied_table_pastes_into_the_middle_of_a_line() {
254 let mut source = Draft::default();
255 let index = source.insert_table(0, table_of(&[&["1", "2"]]));
256 let copied = source.slice(0..TABLE_MARK.len_utf8());
257 let mut draft = Draft::plain("abcd");
258 draft.insert_lines(2..2, &copied);
259 assert_eq!(draft.text(), format!("ab\n{TABLE_MARK}\ncd"));
260 assert_eq!(draft.table(1), source.table(index));
261}
262
263#[test]
264fn pasted_markdown_becomes_headings_lists_quotes_code_and_tables() {
265 let markdown = "# Title\n\nSome **bold**, *it*, ~~gone~~, `code` and [docs](https://x.de)\n\n\
266 1. one\n 1. nested\n2. two\n- dot\n - inner\n\n> quoted\n\n```rust\nfn x() {}\n```\n\n\
267 | A | B |\n|---|---|\n| **1** | 2 |\n";
268 let draft = Draft::from_markdown(markdown);
269 let kinds: Vec<LineKind> = draft
270 .lines()
271 .iter()
272 .filter(|kind| **kind != LineKind::Text)
273 .cloned()
274 .collect();
275 assert_eq!(
276 kinds,
277 [
278 LineKind::Heading(1),
279 LineKind::Numbered(0),
280 LineKind::Numbered(1),
281 LineKind::Numbered(0),
282 LineKind::Bullet(0),
283 LineKind::Bullet(1),
284 LineKind::Quote,
285 LineKind::Code(Some("rust".into())),
286 LineKind::Table(table_of(&[&["A", "B"], &["1", "2"]])),
287 ]
288 );
289 let html = draft.trimmed().to_html();
290 assert!(html.starts_with("<h1>Title</h1>"), "{html}");
291 assert!(html.contains("<b>bold</b>, <i>it</i>, <s>gone</s>, <code>code</code>"));
292 assert!(html.contains("<a href=\"https://x.de\">docs</a>"));
293 assert!(html.contains("<blockquote>quoted</blockquote>"));
294 assert!(html.contains("<pre class=\"language-rust\">fn x() {}</pre>"));
295 assert!(
296 html.ends_with("<td>1</td><td>2</td></tr></tbody></table></figure>"),
297 "{html}"
298 );
299}
300
301#[test]
302fn text_with_pipes_but_no_delimiter_row_stays_text() {
303 assert!(!teams_core::has_markdown("a | b\nc | d"));
304 assert!(teams_core::has_markdown("| a | b |\n| - | - |"));
305 assert!(teams_core::has_markdown("## Heading"));
306}
307
308#[test]
309fn received_tables_and_headings_edit_as_tables_and_headings() {
310 let spans = html_to_spans(
311 "<h2>Notes</h2><table><tbody><tr><td><p>a</p></td><td>b<br>c</td></tr></tbody></table><p>end</p>",
312 );
313 let draft = Draft::from_spans(&spans);
314 assert_eq!(draft.lines()[0], LineKind::Heading(2));
315 assert_eq!(
316 draft.lines()[1],
317 LineKind::Table(table_of(&[&["a", "b\nc"]]))
318 );
319 assert_eq!(draft.lines()[2], LineKind::Text);
320}
321
322#[test]
323fn pasting_markdown_with_a_table_leaves_the_cursor_after_the_paste() {
324 let markdown = "## Plan\n- dot\n> quoted\n\n| Area | Owner |\n|---|---|\n| Sync | Priya |\nend";
325 let lines = Draft::from_markdown(markdown).slice(0..usize::MAX);
326 let mut draft = Draft::default();
327 let cursor = draft.insert_lines(0..0, &lines);
328 assert_eq!(cursor, draft.text().len(), "{:?}", draft.text());
329}
330
331#[test]
332fn a_sent_table_edits_back_into_the_same_table() {
333 let table = table_of(&[&["a", "x\ny"], &["", "b"]]);
334 let draft = Draft::from_spans(&html_to_spans(&table.to_html()));
335 let LineKind::Table(received) = &draft.lines()[0] else {
336 panic!("{:?}", draft.lines());
337 };
338 assert_eq!(received.rows[0], ["a", "x\ny"]);
339 assert!(received.rows[1][0].trim().is_empty());
340 assert_eq!(received.to_html(), table.to_html());
341}