diff --git a/blocksuite/crates/playground/src/database_authoring/clipboard.rs b/blocksuite/crates/playground/src/database_authoring/clipboard.rs index 34c57ff1e6..a4520a7bd0 100644 --- a/blocksuite/crates/playground/src/database_authoring/clipboard.rs +++ b/blocksuite/crates/playground/src/database_authoring/clipboard.rs @@ -1,5 +1,8 @@ use blocksuite_editor::{ - clipboard::{decode_html_snapshot, encode_html_snapshot, table_area_html, write_text_and_html}, + clipboard::{ + decode_html_snapshot, encode_html_snapshot, sanitize::decode_html_entities_attr, + table_area_html, write_text_and_html, + }, database::{self, TableClipboardCell}, }; use ui::{ClipboardEntry, ClipboardItem, Context}; @@ -173,9 +176,15 @@ impl TableClipboard { /// Read the cells from [`TABLE_ATTR`] when they still give `text`. fn from_html(html: &str, text: &str) -> Option>> { - let (_, after) = html.split_once(&format!("{TABLE_ATTR}=\""))?; - let (encoded, _) = after.split_once('"')?; - let Self { database_table } = serde_json::from_str(&decode_html_snapshot(encoded)?).ok()?; + let value = decode_html_entities_attr(table_attribute(html)?); + let decoded; + let json = if value.trim_start().starts_with('{') { + value.as_ref() + } else { + decoded = decode_html_snapshot(&value)?; + &decoded + }; + let Self { database_table } = serde_json::from_str(json).ok()?; let width = database_table.first().map(Vec::len)?; (width > 0 && database_table.iter().all(|row| row.len() == width) @@ -184,6 +193,309 @@ impl TableClipboard { } } +#[derive(Clone, Copy)] +enum ForeignNamespace { + Svg, + Math, +} + +enum Integration { + None, + Html, + MathText, +} + +enum Scope<'a> { + Div(Option<&'a str>), + Template, + Html(&'a str), + Foreign { + tag: &'a str, + namespace: ForeignNamespace, + integration: Integration, + }, +} + +fn tag_is(tag: &str, names: &[&str]) -> bool { + names.iter().any(|name| tag.eq_ignore_ascii_case(name)) +} + +fn exits_foreign_content(tag: &str, closing: bool, font_format: bool) -> bool { + if closing { + tag_is(tag, &["br", "p"]) + } else { + font_format + || tag_is( + tag, + &[ + "b", + "big", + "blockquote", + "body", + "br", + "center", + "code", + "dd", + "div", + "dl", + "dt", + "em", + "embed", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "head", + "hr", + "i", + "img", + "li", + "listing", + "menu", + "meta", + "nobr", + "ol", + "p", + "pre", + "ruby", + "s", + "small", + "span", + "strong", + "strike", + "sub", + "sup", + "table", + "tt", + "u", + "ul", + "var", + ], + ) + } +} + +fn table_attribute(mut html: &str) -> Option<&str> { + let space = |ch| matches!(ch, ' ' | '\t' | '\n' | '\r' | '\x0c'); + let mut scopes = Vec::new(); + 'tags: while let Some((_, head)) = html.split_once('<') { + html = head; + if let Some(comment) = head.strip_prefix("!--") { + html = comment.split_once("-->")?.1; + continue; + } + if matches!(scopes.last(), Some(Scope::Foreign { .. })) + && let Some(cdata) = head.strip_prefix("![CDATA[") + { + html = cdata.split_once("]]>")?.1; + continue; + } + if head.starts_with(['!', '?']) { + html = head.split_once('>')?.1; + continue; + } + let closing = head.starts_with('/'); + let head = head.strip_prefix('/').unwrap_or(head); + if !head.starts_with(|ch: char| ch.is_ascii_alphabetic()) { + continue; + } + let end = head.find(|ch| space(ch) || matches!(ch, '/' | '>' | '<'))?; + let (tag, mut attrs) = head.split_at(end); + let table = tag.eq_ignore_ascii_case("table"); + let div = tag.eq_ignore_ascii_case("div"); + let template = tag.eq_ignore_ascii_case("template"); + let svg = tag.eq_ignore_ascii_case("svg"); + let math = tag.eq_ignore_ascii_case("math"); + let annotation = tag.eq_ignore_ascii_case("annotation-xml"); + let font = tag.eq_ignore_ascii_case("font"); + let mut value = None; + let mut encoding = None; + let mut font_format = false; + let mut self_closing = false; + loop { + attrs = attrs.trim_start_matches(space); + if let Some(rest) = attrs.strip_prefix('/') { + attrs = rest; + self_closing = attrs.starts_with('>'); + continue; + } + if let Some(rest) = attrs.strip_prefix('>') { + html = rest; + break; + } + if attrs.starts_with('<') { + html = attrs; + continue 'tags; + } + let name_start = usize::from(attrs.starts_with('=')); + let end = name_start + + attrs[name_start..] + .find(|ch| space(ch) || matches!(ch, '=' | '/' | '>' | '<'))?; + let (name, rest) = attrs.split_at(end); + attrs = rest.trim_start_matches(space); + let attr = if let Some(rest) = attrs.strip_prefix('=') { + attrs = rest.trim_start_matches(space); + let (raw, rest) = match *attrs.as_bytes().first()? { + quote @ (b'\'' | b'"') => attrs[1..].split_once(char::from(quote))?, + _ => attrs.split_at(attrs.find(|ch| space(ch) || ch == '>')?), + }; + attrs = rest; + raw + } else { + "" + }; + if !closing && (table || div) && name.eq_ignore_ascii_case(TABLE_ATTR) { + value.get_or_insert(attr); + } + if annotation && name.eq_ignore_ascii_case("encoding") { + encoding.get_or_insert(attr); + } + font_format |= font && tag_is(name, &["color", "face", "size"]); + } + let mut foreign = match scopes.last() { + Some(Scope::Foreign { + namespace, + integration, + .. + }) if closing + || matches!(integration, Integration::None) + || (matches!(integration, Integration::MathText) + && tag_is(tag, &["mglyph", "malignmark"])) => + { + Some(*namespace) + } + _ => None, + }; + // The HTML parser can pop foreign elements before it inserts a tag. + if foreign.is_some() && exits_foreign_content(tag, closing, font_format) { + while matches!( + scopes.last(), + Some(Scope::Foreign { + integration: Integration::None, + .. + }) + ) { + scopes.pop(); + } + foreign = None; + } + if closing { + let mut scan_foreign = foreign.is_some(); + let mut integration_boundary = false; + for (index, scope) in scopes.iter().enumerate().rev() { + let matches = match scope { + Scope::Foreign { + tag: open, + integration, + .. + } if scan_foreign => { + integration_boundary |= !matches!(integration, Integration::None); + open.eq_ignore_ascii_case(tag) + } + Scope::Foreign { .. } => break, + _ if integration_boundary => break, + Scope::Div(_) => div, + Scope::Template if !template => break, + Scope::Template => true, + Scope::Html(open) => open.eq_ignore_ascii_case(tag), + }; + if matches { + scopes.truncate(index); + break; + } + scan_foreign &= matches!(scope, Scope::Foreign { .. }); + } + continue; + } + let namespace = match foreign { + Some(ForeignNamespace::Math) + if svg + && matches!(scopes.last(), Some(Scope::Foreign { tag, .. }) + if tag.eq_ignore_ascii_case("annotation-xml")) => + { + Some(ForeignNamespace::Svg) + } + Some(namespace) => Some(namespace), + None if svg => Some(ForeignNamespace::Svg), + None if math => Some(ForeignNamespace::Math), + None => None, + }; + if let Some(namespace) = namespace { + if !self_closing { + let integration = match namespace { + ForeignNamespace::Svg if tag_is(tag, &["foreignobject", "desc", "title"]) => { + Integration::Html + } + ForeignNamespace::Math if tag_is(tag, &["mi", "mo", "mn", "ms", "mtext"]) => { + Integration::MathText + } + ForeignNamespace::Math + if annotation + && encoding.is_some_and(|encoding| { + let encoding = decode_html_entities_attr(encoding); + tag_is(&encoding, &["text/html", "application/xhtml+xml"]) + }) => + { + Integration::Html + } + _ => Integration::None, + }; + scopes.push(Scope::Foreign { + tag, + namespace, + integration, + }); + } + continue; + } + if tag.eq_ignore_ascii_case("plaintext") { + return None; + } + if tag_is( + tag, + &[ + "script", "style", "title", "textarea", "xmp", "iframe", "noembed", "noframes", + ], + ) { + html = html.match_indices("')); + (name.eq_ignore_ascii_case(tag) && boundary).then_some(&html[start..]) + })?; + continue; + } + if template { + scopes.push(Scope::Template); + } else if div { + scopes.push(Scope::Div(value)); + } else if table && !scopes.iter().any(|scope| matches!(scope, Scope::Template)) { + return value.or_else(|| { + scopes.iter().rev().find_map(|scope| match scope { + Scope::Div(value) => *value, + _ => None, + }) + }); + } else if scopes + .iter() + .any(|scope| matches!(scope, Scope::Foreign { .. })) + && !tag_is( + tag, + &[ + "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", + "param", "source", "track", "wbr", + ], + ) + { + scopes.push(Scope::Html(tag)); + } + } + None +} + fn encode_tsv(rows: &[Vec]) -> String { let mut text = String::new(); for (r, row) in rows.iter().enumerate() { @@ -248,7 +560,10 @@ fn decode_tsv(text: &str) -> Vec> { #[cfg(test)] mod tests { - use super::{TableClipboard, TableClipboardCell, decode_tsv, encode_tsv}; + use super::{ + TABLE_ATTR, TableClipboard, TableClipboardCell, decode_tsv, encode_html_snapshot, + encode_tsv, + }; use serde_json::json; use ui::ClipboardItem; @@ -353,4 +668,259 @@ mod tests { assert_eq!(actual, expected); } } + + #[test] + fn html_attribute_syntax_preserves_one_comma_label() { + let payload = encode_html_snapshot( + r#"{"database_table":[[{"ids":["o1"],"labels":["Sales, APAC"],"source":null}]]}"#, + ); + for head in [ + format!(""), + format!("
"), + format!("
"), + format!("
"), + format!("
"), + format!( + "
\">
\" x-{TABLE_ATTR}=fake {TABLE_ATTR}-extra=fake {TABLE_ATTR}='{payload}'>" + ), + format!( + "<table>" + ), + ] { + let rows = TableClipboard::from_item(&html_item("Sales, APAC", &head)).unwrap(); + assert!( + matches!(&rows[..], [row] if matches!(&row[..], + [TableClipboardCell::Options { labels, .. }] if labels == &["Sales, APAC"])), + "{head}" + ); + } + } + + #[test] + fn html_attribute_uses_the_first_body_table_and_its_open_divs() { + let text = "Sales, APAC"; + let payload = encode_html_snapshot( + r#"{"database_table":[[{"ids":["o1"],"labels":["Sales, APAC"]}]]}"#, + ); + let wrapper = format!("
"); + let table = "
Sales, APAC
"; + for html in [ + format!( + "{wrapper}{table}" + ), + format!( + "{wrapper}{table}" + ), + format!( + "{wrapper}{table}" + ), + format!("{wrapper}{table}"), + format!( + "{wrapper}
{table}
" + ), + format!( + "{wrapper}{table}" + ), + format!("{wrapper}
{table}"), + format!("
{wrapper}{table}
"), + ] { + let rows = TableClipboard::from_item(&html_item(text, &html)).unwrap(); + assert!( + matches!(&rows[..], [row] if matches!(&row[..], + [TableClipboardCell::Options { labels, .. }] if labels == &[text])), + "{html}" + ); + } + } + + #[test] + fn database_paste_uses_the_body_table_after_foreign_content() { + use super::super::tests_title_menus_and_keys::{Table, fixture}; + use blocksuite_playground_doc::schema::DatabaseColumnSpec; + + let (mut doc, db) = fixture(); + let page = doc.workspace.page_mut(crate::HOME_PAGE_ID).unwrap(); + page.add_database_column( + &db, + Some("v-table"), + DatabaseColumnSpec { + id: "target".into(), + column_type: "multi-select".into(), + name: "Region".into(), + data: json!({ "options": [] }), + }, + Some(1), + 24, + ) + .unwrap(); + page.stop_capturing().unwrap(); + let table = Table::open(doc, db, 800); + let before = table.read(); + + let (text, body) = TableClipboard::encode(vec![vec![TableClipboardCell::Options { + ids: vec!["o1".into()], + labels: vec!["Sales, APAC".into()], + source: None, + }]]); + for prefix in [ + r#""#, + r#""#, + "", + "", + "", + r#""#, + r#"<table>decoy</table>"#, + "<table>decoy</table>", + "", + "<table data-affine-database-table=decoy></table></svg>", + "", + "", + "", + "", + "
", + ] { + table.select_cell("r2", "target"); + table.paste_event(html_item(&text, &format!("{prefix}{body}"))); + let data = table.read(); + let options = data + .columns + .iter() + .find(|column| column.id == "target") + .unwrap() + .select_options(); + let [option] = options.as_slice() else { + panic!("{prefix}: expected one option, got {}", options.len()); + }; + assert_eq!(option.value, "Sales, APAC", "{prefix}"); + assert_eq!( + data.cells[&("r2".into(), "target".into())].as_string_list(), + [option.id.as_str()], + "{prefix}" + ); + table.undo(); + let restored = table.read(); + assert_eq!(restored.cells, before.cells, "{prefix}"); + assert_eq!(restored.columns, before.columns, "{prefix}"); + } + } + + #[test] + fn html_integration_points_keep_tables_and_their_html_ancestors() { + use super::table_attribute; + + for (html, expected) in [ + ( + "
", + Some("inner"), + ), + ( + "
", + Some("outer"), + ), + ( + "
", + Some("inner"), + ), + ( + "<table>decoy</table>
", + Some("inner"), + ), + ( + "", + Some("inner/"), + ), + ( + "
", + Some("inner"), + ), + ( + "
", + Some("inner"), + ), + ( + "
", + None, + ), + ( + "
", + Some("first"), + ), + ] { + assert_eq!(table_attribute(html), expected, "{html}"); + } + for name in ["mi", "mo", "mn", "ms", "mtext"] { + let html = format!( + "<{name}>decoy
" + ); + assert_eq!(table_attribute(&html), Some("first"), "{html}"); + } + for name in ["mglyph", "malignmark"] { + let html = format!( + "<{name}></{name}><table data-affine-database-table=first></table></mtext></math>" + ); + assert_eq!(table_attribute(&html), Some("first"), "{html}"); + } + } + + #[test] + fn html_tables_can_end_foreign_content() { + use super::table_attribute; + + let table = "<table data-affine-database-table=first></table>"; + for html in [ + format!("<math><mrow>{table}</mrow></math>"), + format!("<svg><g>{table}</g></svg>"), + format!("<svg><style>/* {table} */</style></svg>"), + format!("<svg><g><b><title/><table>ignored</table>{table}"), + format!( + "<table>ignored</table>{table}" + ), + ] { + assert_eq!(table_attribute(&html), Some("first"), "{html}"); + } + } + + #[test] + fn html_attribute_entities_restore_labels_and_keep_text_validation() { + let text = r#""Sales, APAC & 'A' ""B""""#; + let label = r#"Sales, APAC & 'A' "B""#; + for quote in [""", """, """] { + let json = r#"{"database_table":[[{"ids":["o1"],"labels":["Sales, APAC & <team> 'A' \"B\""],"source":null}]]}"#; + let html = format!("", json.replace('"', quote)); + let rows = TableClipboard::from_item(&html_item(text, &html)).unwrap(); + assert!( + matches!(&rows[..], [row] if matches!(&row[..], + [TableClipboardCell::Options { labels, .. }] if labels == &[label])), + "{quote}" + ); + let rows = TableClipboard::from_item(&html_item("Edited", &html)).unwrap(); + assert!(matches!(&rows[..], [row] if matches!(&row[..], + [TableClipboardCell::Text(value)] if value == "Edited"))); + } + } + + #[test] + fn html_attribute_ignores_decoys_and_invalid_cells() { + let text = "Sales, APAC"; + let payload = encode_html_snapshot( + r#"{"database_table":[[{"ids":["o1"],"labels":["Sales, APAC"]}]]}"#, + ); + for html in [ + format!("
"), + format!("
"), + format!("
"), + format!("
{TABLE_ATTR}=\"{payload}\"
"), + format!("
"), + format!(""), + format!("
"), + ] { + let rows = TableClipboard::from_item(&html_item(text, &html)).unwrap(); + assert!( + matches!(&rows[..], [row] if matches!(&row[..], + [TableClipboardCell::Text(value)] if value == text)), + "{html}" + ); + } + } }