From c828d67d4e76070d048027839f40be7489b7928d Mon Sep 17 00:00:00 2001 From: DarkSky Date: Sat, 5 Dec 2026 07:23:50 +0900 Subject: [PATCH] fix(editor,playground): outline frame swatches and carry table copy cells in text/html - Unify Edgeless color dot rendering via paint_color_dot (dark-mode 1px border ring, transparent diagonal slash, and default transparent Frame without prop:background). - Encode Database table copies in real clipboard text/html (data-affine-database-table) via shared write_text_and_html and Web native paste event without side-table state, preserving comma-containing option labels across tabs while splitting external plain-text copies. --- blocksuite/crates/editor/src/clipboard/mod.rs | 15 +- .../crates/editor/src/clipboard/table_html.rs | 2 +- .../src/edgeless/element_toolbar/bar_items.rs | 23 +-- .../edgeless/element_toolbar/color_popover.rs | 41 ++--- .../element_toolbar/note_style_panel.rs | 43 ++--- .../src/edgeless/element_toolbar/render.rs | 1 - .../src/edgeless/element_toolbar/summary.rs | 23 ++- .../src/edgeless/element_toolbar/widgets.rs | 67 +++++++ .../src/database_authoring/clipboard.rs | 166 +++++++++++++----- .../playground/src/database_authoring/keys.rs | 2 +- .../tests_table_clipboard.rs | 150 ++++++++++++++++ .../tests_title_menus_and_keys.rs | 9 +- .../src/editor_session/input_handler.rs | 3 + 13 files changed, 404 insertions(+), 141 deletions(-) diff --git a/blocksuite/crates/editor/src/clipboard/mod.rs b/blocksuite/crates/editor/src/clipboard/mod.rs index ceb2bc3cf6..2efffd278a 100644 --- a/blocksuite/crates/editor/src/clipboard/mod.rs +++ b/blocksuite/crates/editor/src/clipboard/mod.rs @@ -18,6 +18,7 @@ use y_octo::{TextDeltaOp, TextInsert}; use html::{blocks_html, parse_html_blocks}; pub use html::{decode_html_snapshot, encode_html_snapshot}; +pub use table_html::table_area_html; pub const SNAPSHOT_MIME: &str = "application/x-blocksuite-snapshot"; @@ -634,11 +635,15 @@ fn table_area_tsv(rows: &[Vec]) -> String { .join("\n") } -pub fn write_table_area(rows: &[Vec], _cx: &mut ui::App) { - let plain = table_area_tsv(rows); - let html = table_html::table_area_html(rows); +pub fn write_table_area(rows: &[Vec], cx: &mut ui::App) { + write_text_and_html(table_area_tsv(rows), table_area_html(rows), cx); +} + +/// Write `text/plain` and `text/html`. A paste reads the HTML from the +/// `text/html` key of the item metadata on every platform. +pub fn write_text_and_html(plain: String, html: String, _cx: &mut ui::App) { #[cfg(target_family = "wasm")] - browser::write_table_area(&plain, &html); + browser::write_text_and_html(&plain, &html); #[cfg(not(target_family = "wasm"))] _cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata( plain, @@ -675,7 +680,7 @@ export function writeSliceClipboard(plain, html, md, json) { #[wasm_bindgen(js_name=writeSliceClipboard)] fn write_slice(plain: &str, html: &str, md: &str, json: &str); } - pub(super) fn write_table_area(plain: &str, html: &str) { + pub(super) fn write_text_and_html(plain: &str, html: &str) { write_slice(plain, html, "", ""); } diff --git a/blocksuite/crates/editor/src/clipboard/table_html.rs b/blocksuite/crates/editor/src/clipboard/table_html.rs index fef1a05284..47be8a597d 100644 --- a/blocksuite/crates/editor/src/clipboard/table_html.rs +++ b/blocksuite/crates/editor/src/clipboard/table_html.rs @@ -70,7 +70,7 @@ impl TableBlock { } } -pub(super) fn table_area_html(rows: &[Vec]) -> String { +pub fn table_area_html(rows: &[Vec]) -> String { let mut html = String::from(""); for row in rows { html.push_str(""); diff --git a/blocksuite/crates/editor/src/edgeless/element_toolbar/bar_items.rs b/blocksuite/crates/editor/src/edgeless/element_toolbar/bar_items.rs index 17cb5e194d..7b6c474d13 100644 --- a/blocksuite/crates/editor/src/edgeless/element_toolbar/bar_items.rs +++ b/blocksuite/crates/editor/src/edgeless/element_toolbar/bar_items.rs @@ -7,13 +7,13 @@ use crate::theme::Palette; use super::{ EdgelessElementAction, EdgelessElementToolbarHost, ElementColorSlot, ElementSubMenu, - ElementToolbarSummary, ShapePreset, + ElementToolbarSummary, ShapePreset, is_transparent_color, media_toolbar::append_media_toolbar_items, render::ToolbarRow, typography::font_trigger_widths, widgets::{ - BTN_SIZE, align_action_btn, icon_action_btn, stroke_style_btn, swatch_btn, text_action_btn, - text_color_btn, + BTN_SIZE, ColorDotTokens, align_action_btn, icon_action_btn, paint_color_dot, + stroke_style_btn, swatch_btn, text_action_btn, text_color_btn, }, }; @@ -52,7 +52,6 @@ pub(super) fn append_per_type_items( compact: bool, palette: &Palette, panel_bg: Hsla, - border_col: Hsla, cx: &mut Context, ) { let show_tooltips = open_sub.is_none() && open_color_picker.is_none(); @@ -227,6 +226,8 @@ pub(super) fn append_per_type_items( if summary.has_fill { let active = open_color_picker == Some(ElementColorSlot::Fill); let fill = summary.fill_color; + let fill_transparent = is_transparent_color(&summary.fill_color_value); + let dot_tokens = ColorDotTokens::new(palette, palette.theme); row.color( ElementColorSlot::Fill, BTN_SIZE, @@ -239,19 +240,7 @@ pub(super) fn append_per_type_items( palette, ElementColorSlot::Fill, move |bounds, window| { - let inset = 3.0; - let side = (f32::from(bounds.size.width) - 2.0 * inset).max(10.0); - window.paint_quad(ui::quad( - Bounds::new( - point(bounds.origin.x + px(inset), bounds.origin.y + px(inset)), - size(px(side), px(side)), - ), - Corners::all(px(side * 0.5)), - fill, - Edges::all(px(0.5)), - border_col, - BorderStyle::Solid, - )); + paint_color_dot(bounds, 16.0, fill, fill_transparent, dot_tokens, window); }, cx, ), diff --git a/blocksuite/crates/editor/src/edgeless/element_toolbar/color_popover.rs b/blocksuite/crates/editor/src/edgeless/element_toolbar/color_popover.rs index a653827499..e5d817ea57 100644 --- a/blocksuite/crates/editor/src/edgeless/element_toolbar/color_popover.rs +++ b/blocksuite/crates/editor/src/edgeless/element_toolbar/color_popover.rs @@ -16,7 +16,7 @@ use super::{ EDGELESS_VIEWPORT_ID, EdgelessAuthoringState, EdgelessElementAction, EdgelessElementToolbarHost, ElementColorSlot, ElementToolbarSummary, color_value_matches_swatch, palette_for_slot, parse_custom_hex_color, - widgets::{isolate_floating_chrome, toolbar_chrome_tokens}, + widgets::{ColorDotTokens, isolate_floating_chrome, paint_color_dot, toolbar_chrome_tokens}, }; #[allow(clippy::too_many_arguments)] @@ -63,9 +63,7 @@ pub(super) fn build_color_picker_pill( let hover_bg = palette.hover; let brand_col = palette.brand; - let slash_col = theme - .css_color("--affine-error-color") - .unwrap_or(palette.brand); + let dot_tokens = ColorDotTokens::new(palette, theme); let slot_tag = match slot { ElementColorSlot::Fill => "fill", ElementColorSlot::Stroke => "stroke", @@ -102,13 +100,6 @@ pub(super) fn build_color_picker_pill( let selected = color_value_matches_swatch(current_val, swatch, theme, ignore_alpha); let wire_val = swatch.to_color_value(); let el_id = SharedString::from(format!("el-tb-swatch-{slot_tag}-{}", swatch.key)); - let swatch_bg = if is_transparent { panel_bg } else { color }; - let dark_swatch = theme == PlaygroundTheme::Dark && color.l < 0.3; - let stroke = if dark_swatch { - palette.text_secondary - } else { - border_col - }; row = row.child( div() .id(el_id) @@ -161,26 +152,14 @@ pub(super) fn build_color_picker_pill( BorderStyle::Solid, )); } - let dot = 16.0_f32; - window.paint_quad(ui::quad( - Bounds::new( - point(px(cx_b - dot * 0.5), px(cy_b - dot * 0.5)), - size(px(dot), px(dot)), - ), - Corners::all(px(dot * 0.5)), - swatch_bg, - Edges::all(px(if dark_swatch { 1.0 } else { 0.5 })), - stroke, - BorderStyle::Solid, - )); - if is_transparent { - let mut slash = ui::PathBuilder::stroke(px(1.25)); - slash.move_to(point(px(cx_b - 5.0), px(cy_b + 5.0))); - slash.line_to(point(px(cx_b + 5.0), px(cy_b - 5.0))); - if let Ok(path) = slash.build() { - window.paint_path(path, slash_col); - } - } + paint_color_dot( + bounds, + 16.0, + color, + is_transparent, + dot_tokens, + window, + ); }, ) .w(px(cell)) diff --git a/blocksuite/crates/editor/src/edgeless/element_toolbar/note_style_panel.rs b/blocksuite/crates/editor/src/edgeless/element_toolbar/note_style_panel.rs index adad29d28e..cfdb23b36a 100644 --- a/blocksuite/crates/editor/src/edgeless/element_toolbar/note_style_panel.rs +++ b/blocksuite/crates/editor/src/edgeless/element_toolbar/note_style_panel.rs @@ -22,7 +22,7 @@ use super::{ EDGELESS_VIEWPORT_ID, EdgelessElementAction, EdgelessElementToolbarHost, ElementColorSlot, ElementToolbarSummary, NOTE_BACKGROUND_PALETTES, NOTE_BORDER_SIZES, NOTE_CORNER_RADII, NOTE_SCALE_PRESETS, NOTE_SHADOW_PRESETS, color_value_matches_swatch, - widgets::{isolate_floating_chrome, toolbar_chrome_tokens}, + widgets::{ColorDotTokens, isolate_floating_chrome, paint_color_dot, toolbar_chrome_tokens}, }; fn section_title(label: &'static str, palette: &Palette) -> ui::Div { @@ -46,9 +46,6 @@ pub(super) fn build_note_style_panel( let (panel_bg, border_col, shadows) = toolbar_chrome_tokens(palette, theme); let hover_bg = palette.hover; let brand = palette.brand; - let slash_col = theme - .css_color("--affine-error-color") - .unwrap_or(palette.brand); const PANEL_W: f32 = 274.0; const PANEL_H: f32 = 316.0; @@ -84,22 +81,13 @@ pub(super) fn build_note_style_panel( // 1. Background color swatches (9 Note colors). panel = panel.child(section_title("Background", palette)); - let swatch_border = if theme == PlaygroundTheme::Dark { - palette.text_secondary - } else { - border_col - }; + let dot_tokens = ColorDotTokens::new(palette, theme); let mut color_row = div().flex().items_center().gap(px(4.0)); for swatch in NOTE_BACKGROUND_PALETTES { let color = swatch.resolve_hsla(theme); let is_transparent = swatch.is_transparent(); let selected = color_value_matches_swatch(&summary.fill_color_value, swatch, theme, false); let wire_val = swatch.to_color_value(); - let swatch_bg = if is_transparent { - ui::Hsla::white() - } else { - color - }; color_row = color_row.child( div() .id(SharedString::from(format!("el-tb-note-bg-{}", swatch.key))) @@ -153,25 +141,14 @@ pub(super) fn build_note_style_panel( BorderStyle::Solid, )); } - window.paint_quad(ui::quad( - Bounds::new( - point(px(ox + dx), px(oy + dy)), - size(px(side), px(side)), - ), - Corners::all(px(side * 0.5)), - swatch_bg, - Edges::all(px(1.0)), - swatch_border, - BorderStyle::Solid, - )); - if is_transparent { - let mut pb = ui::PathBuilder::stroke(px(1.5)); - pb.move_to(point(px(ox + dx + 3.0), px(oy + dy + side - 3.0))); - pb.line_to(point(px(ox + dx + side - 3.0), px(oy + dy + 3.0))); - if let Ok(path) = pb.build() { - window.paint_path(path, slash_col); - } - } + paint_color_dot( + bounds, + side, + color, + is_transparent, + dot_tokens, + window, + ); }, ) .w(px(24.0)) diff --git a/blocksuite/crates/editor/src/edgeless/element_toolbar/render.rs b/blocksuite/crates/editor/src/edgeless/element_toolbar/render.rs index ea3cd5cdb8..21ab32875b 100644 --- a/blocksuite/crates/editor/src/edgeless/element_toolbar/render.rs +++ b/blocksuite/crates/editor/src/edgeless/element_toolbar/render.rs @@ -271,7 +271,6 @@ pub fn build_edgeless_element_toolbar( compact, palette, panel_bg, - border_col, cx, ); if row.items.len() == type_start { diff --git a/blocksuite/crates/editor/src/edgeless/element_toolbar/summary.rs b/blocksuite/crates/editor/src/edgeless/element_toolbar/summary.rs index 1fbc5efe1b..54a39c33bc 100644 --- a/blocksuite/crates/editor/src/edgeless/element_toolbar/summary.rs +++ b/blocksuite/crates/editor/src/edgeless/element_toolbar/summary.rs @@ -1,5 +1,7 @@ use std::collections::HashSet; +use serde_json::Value as JsonValue; + use blocksuite_playground_doc::read::{ BlockContent, ColorValue, ConnectorMode, EndpointStyle, NoteDisplayMode, PageSnapshot, ShapeStyle, ShapeType, StrokeStyle, SurfaceElementKind, TextAlign, @@ -459,17 +461,20 @@ pub fn summarize_element_toolbar( if super::prop_bool(node, "prop:lockedBySelf", false) { is_locked = true; } - if matches!(item.kind, SpatialItemKind::Note | SpatialItemKind::Frame) - && !got_fill - && let Some(bg) = node.props.get("prop:background") + if matches!(item.kind, SpatialItemKind::Note | SpatialItemKind::Frame) && !got_fill { - if let Some(c) = resolve_edgeless_color(bg, theme) { - fill_color = Some(c); + // A frame without a stored background is transparent (`FrameBlockModel`). + let frame_default = (item.kind == SpatialItemKind::Frame) + .then(|| JsonValue::String("transparent".into())); + if let Some(bg) = node.props.get("prop:background").or(frame_default.as_ref()) { + if let Some(c) = resolve_edgeless_color(bg, theme) { + fill_color = Some(c); + } + if let Some(cv) = json_to_color_value(bg) { + fill_color_value = Some(cv); + } + got_fill = true; } - if let Some(cv) = json_to_color_value(bg) { - fill_color_value = Some(cv); - } - got_fill = true; } if matches!( item.kind, diff --git a/blocksuite/crates/editor/src/edgeless/element_toolbar/widgets.rs b/blocksuite/crates/editor/src/edgeless/element_toolbar/widgets.rs index 88552b673b..8bb143917b 100644 --- a/blocksuite/crates/editor/src/edgeless/element_toolbar/widgets.rs +++ b/blocksuite/crates/editor/src/edgeless/element_toolbar/widgets.rs @@ -86,6 +86,73 @@ pub(super) fn toolbar_chrome_tokens( (panel_bg, border_col, shadows) } +/// Theme colors shared by every palette dot of the element toolbar and its color popovers. +#[derive(Clone, Copy)] +pub(super) struct ColorDotTokens { + panel_bg: Hsla, + border: Hsla, + dark_ring: Hsla, + slash: Hsla, + dark: bool, +} + +impl ColorDotTokens { + pub(super) fn new(palette: &Palette, theme: PlaygroundTheme) -> Self { + let (panel_bg, border, _) = toolbar_chrome_tokens(palette, theme); + Self { + panel_bg, + border, + dark_ring: palette.text_secondary, + slash: theme + .css_color("--affine-error-color") + .unwrap_or(palette.brand), + dark: theme == PlaygroundTheme::Dark, + } + } +} + +/// Paints a round palette dot of `diameter` centered in `bounds`. A dot that would merge into +/// the dark panel gets a 1 px ring, and a transparent color shows the panel crossed by a +/// diagonal slash. +pub(super) fn paint_color_dot( + bounds: Bounds, + diameter: f32, + color: Hsla, + transparent: bool, + tokens: ColorDotTokens, + window: &mut Window, +) { + let cx = f32::from(bounds.origin.x) + f32::from(bounds.size.width) * 0.5; + let cy = f32::from(bounds.origin.y) + f32::from(bounds.size.height) * 0.5; + let fill = if transparent { tokens.panel_bg } else { color }; + let dark_dot = tokens.dark && fill.l < 0.3; + let (ring_w, ring) = if dark_dot { + (1.0, tokens.dark_ring) + } else { + (0.5, tokens.border) + }; + window.paint_quad(ui::quad( + Bounds::new( + point(px(cx - diameter * 0.5), px(cy - diameter * 0.5)), + size(px(diameter), px(diameter)), + ), + Corners::all(px(diameter * 0.5)), + fill, + Edges::all(px(ring_w)), + ring, + BorderStyle::Solid, + )); + if transparent { + let half = diameter * 5.0 / 16.0; + let mut slash = ui::PathBuilder::stroke(px(1.25)); + slash.move_to(point(px(cx - half), px(cy + half))); + slash.line_to(point(px(cx + half), px(cy - half))); + if let Ok(path) = slash.build() { + window.paint_path(path, tokens.slash); + } + } +} + /// Stop left/right/middle mouse presses and wheel scroll from leaking through floating chrome. pub(super) fn isolate_floating_chrome(el: ui::Div) -> ui::Div { el.cursor_default() diff --git a/blocksuite/crates/playground/src/database_authoring/clipboard.rs b/blocksuite/crates/playground/src/database_authoring/clipboard.rs index f9855539ce..34c57ff1e6 100644 --- a/blocksuite/crates/playground/src/database_authoring/clipboard.rs +++ b/blocksuite/crates/playground/src/database_authoring/clipboard.rs @@ -1,7 +1,11 @@ -use blocksuite_editor::database::{self, TableClipboardCell}; +use blocksuite_editor::{ + clipboard::{decode_html_snapshot, encode_html_snapshot, table_area_html, write_text_and_html}, + database::{self, TableClipboardCell}, +}; use ui::{ClipboardEntry, ClipboardItem, Context}; use serde::{Deserialize, Serialize}; +use serde_json::Value; use crate::PlaygroundView; @@ -32,32 +36,45 @@ impl PlaygroundView { &self.page_titles, &offset, ) { - cx.write_to_clipboard(TableClipboard::new_item(rows)); + let (plain, html) = TableClipboard::encode(rows); + write_text_and_html(plain, html, cx); } } else if let Some(item) = cx.read_from_clipboard() { self.paste_database_cells(block_id, &item, cx); } else { - let read = cx.read_from_clipboard_async(); - let page_id = self.page_id.clone(); - let block_id = block_id.to_string(); - cx.spawn(async move |view, cx| { - if let Ok(Some(item)) = read.await { - let _ = view.update(cx, |view, cx| { - if view.page_id == page_id - && view.database_input.is_none() - && view.active_database_authoring_block().as_deref() == Some(&block_id) - && view.flow.database_state.state_for(&block_id) == expected - { - view.paste_database_cells(&block_id, &item, cx); - } - }); - } - }) - .detach(); + // The Web clipboard reads only in a `paste` event, which brings the + // item to `paste_into_focused_database_cell`. + return false; } true } + /// Paste into the focused Table cell of the active database. Return false + /// when no Table cell has the focus. + pub(crate) fn paste_into_focused_database_cell( + &mut self, + item: &ClipboardItem, + cx: &mut Context, + ) -> bool { + let Some(block_id) = self.active_database_authoring_block() else { + return false; + }; + if self.database_input.is_some() + || !self.database_navigation_ready(&block_id) + || self.database_focused_cell(&block_id).is_none() + || !self + .flow + .database_state + .state_for(&block_id) + .selected_rows + .is_empty() + { + return false; + } + self.paste_database_cells(&block_id, item, cx); + true + } + fn paste_database_cells( &mut self, block_id: &str, @@ -105,17 +122,36 @@ impl PlaygroundView { } } +/// The `text/html` attribute that keeps the copied cells. A `Select` label +/// that contains a comma then stays one label. Text that another app wrote has +/// no such attribute and follows the BlockSuite `fromString` comma rule. +const TABLE_ATTR: &str = "data-affine-database-table"; + #[derive(Deserialize, Serialize)] struct TableClipboard { database_table: Vec>, } impl TableClipboard { - fn new_item(database_table: Vec>) -> ClipboardItem { - ClipboardItem::new_string_with_json_metadata( - encode_tsv(&database_table), - Self { database_table }, - ) + /// Encode the cells as TSV `text/plain` and as an HTML table that keeps + /// the cells in [`TABLE_ATTR`]. + fn encode(database_table: Vec>) -> (String, String) { + let text = encode_tsv(&database_table); + let plain: Vec> = database_table + .iter() + .map(|row| { + row.iter() + .map(|cell| cell.plain_text().into_owned()) + .collect() + }) + .collect(); + let json = serde_json::to_string(&Self { database_table }).unwrap_or_default(); + let html = format!( + "
{}
", + encode_html_snapshot(&json), + table_area_html(&plain) + ); + (text, html) } fn from_item(item: &ClipboardItem) -> Option>> { @@ -125,16 +161,26 @@ impl TableClipboard { .any(|entry| matches!(entry, ClipboardEntry::String(_))) .then(String::new) })?; - if let Some(metadata) = item.metadata() - && let Ok(Self { database_table }) = serde_json::from_str(metadata) - && let Some(width) = database_table.first().map(Vec::len) - && width > 0 + let html = item + .metadata() + .and_then(|metadata| serde_json::from_str::(metadata).ok()) + .and_then(|metadata| Some(metadata.get("text/html")?.as_str()?.to_owned())); + Some( + html.and_then(|html| Self::from_html(&html, &text)) + .unwrap_or_else(|| decode_tsv(&text)), + ) + } + + /// 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 width = database_table.first().map(Vec::len)?; + (width > 0 && database_table.iter().all(|row| row.len() == width) - && encode_tsv(&database_table) == text - { - return Some(database_table); - } - Some(decode_tsv(&text)) + && encode_tsv(&database_table) == text) + .then_some(database_table) } } @@ -203,8 +249,13 @@ fn decode_tsv(text: &str) -> Vec> { #[cfg(test)] mod tests { use super::{TableClipboard, TableClipboardCell, decode_tsv, encode_tsv}; + use serde_json::json; use ui::ClipboardItem; + fn html_item(text: &str, html: &str) -> ClipboardItem { + ClipboardItem::new_string_with_json_metadata(text.into(), json!({ "text/html": html })) + } + fn plain(rows: &[Vec]) -> Vec> { rows.iter() .map(|row| { @@ -255,18 +306,51 @@ mod tests { plain(&TableClipboard::from_item(&plain_item).unwrap()), input ); - let item = TableClipboard::new_item(rows); - assert_eq!(item.text().unwrap_or_default(), text); + let (encoded, html) = TableClipboard::encode(rows); + assert_eq!(encoded, text); + let item = html_item(&text, &html); assert_eq!(plain(&TableClipboard::from_item(&item).unwrap()), input); - - let stale = ClipboardItem::new_string_with_json_metadata( - "New text".into(), - serde_json::from_str::(item.metadata().unwrap()).unwrap(), - ); assert_eq!( - plain(&TableClipboard::from_item(&stale).unwrap()), + plain(&TableClipboard::from_item(&html_item("New text", &html)).unwrap()), [["New text"]] ); } } + + #[test] + fn html_cells_keep_comma_labels_and_other_html_follows_the_text() { + let label = TableClipboardCell::Options { + ids: vec!["o1".into()], + labels: vec!["Sales, APAC".into()], + source: None, + }; + let (text, html) = TableClipboard::encode(vec![vec![label]]); + assert_eq!(text, "Sales, APAC"); + let corrupt = html.replacen( + "data-affine-database-table=\"", + "data-affine-database-table=\"!", + 1, + ); + // (item, expected cells: `Options` labels or `Text`) + for (item, expected) in [ + (html_item(&text, &html), Ok(vec!["Sales, APAC"])), + (ClipboardItem::new_string(text.clone()), Err("Sales, APAC")), + (html_item(&text, "

Sales, APAC

"), Err("Sales, APAC")), + (html_item(&text, &corrupt), Err("Sales, APAC")), + (html_item("Sales", &html), Err("Sales")), + ] { + let rows = TableClipboard::from_item(&item).unwrap(); + let actual = match &rows[..] { + [row] => match &row[..] { + [TableClipboardCell::Options { labels, .. }] => { + Ok(labels.iter().map(String::as_str).collect()) + } + [TableClipboardCell::Text(text)] => Err(text.as_str()), + _ => panic!("one cell"), + }, + _ => panic!("one row"), + }; + assert_eq!(actual, expected); + } + } } diff --git a/blocksuite/crates/playground/src/database_authoring/keys.rs b/blocksuite/crates/playground/src/database_authoring/keys.rs index f9918befcb..62f017e346 100644 --- a/blocksuite/crates/playground/src/database_authoring/keys.rs +++ b/blocksuite/crates/playground/src/database_authoring/keys.rs @@ -286,7 +286,7 @@ impl PlaygroundView { /// Whether `block_id` has a focused Table cell or checked rows and no popover that takes /// the keys first. - fn database_navigation_ready(&self, block_id: &str) -> bool { + pub(super) fn database_navigation_ready(&self, block_id: &str) -> bool { let st = self.flow.database_state.state_for(block_id); let a = &st.authoring; self.flow.database_state.has_table_focus(block_id) diff --git a/blocksuite/crates/playground/src/database_authoring/tests_table_clipboard.rs b/blocksuite/crates/playground/src/database_authoring/tests_table_clipboard.rs index 935bdd52f1..31cf21895b 100644 --- a/blocksuite/crates/playground/src/database_authoring/tests_table_clipboard.rs +++ b/blocksuite/crates/playground/src/database_authoring/tests_table_clipboard.rs @@ -362,3 +362,153 @@ fn cross_column_paste_matches_visible_labels_and_undoes_new_options() { assert_eq!(restored.columns, before.columns); } } + +/// Add a `source` column with `source_labels` (all set on `r1`) and an empty +/// `target` column. +fn comma_label_table(source_type: &str, target_type: &str, source_labels: &[&str]) -> Table { + let (mut doc, db) = fixture(); + let page = doc.workspace.page_mut(HOME_PAGE_ID).unwrap(); + let options: Vec<_> = source_labels + .iter() + .enumerate() + .map(|(i, label)| json!({"id": format!("o{i}"), "value": label, "color": "blue"})) + .collect(); + for (index, (id, column_type, options)) in [ + ("source", source_type, options), + ("target", target_type, Vec::new()), + ] + .into_iter() + .enumerate() + { + page.add_database_column( + &db, + Some("v-table"), + DatabaseColumnSpec { + id: id.into(), + column_type: column_type.into(), + name: id.into(), + data: json!({ "options": options }), + }, + Some(index + 1), + 24, + ) + .unwrap(); + } + let ids: Vec = (0..source_labels.len()).map(|i| format!("o{i}")).collect(); + let source = if source_type == "select" { + DatabaseCellSpec::Text(ids[0].clone()) + } else { + DatabaseCellSpec::MultiSelect(ids) + }; + page.set_database_cell_value(&db, "r1", "source", source, 25) + .unwrap(); + page.stop_capturing().unwrap(); + Table::open(doc, db, 800) +} + +/// Read the labels of the `r2` `target` cell and the `target` option count. +fn target_labels(table: &Table) -> (Vec, usize) { + let data = table.read(); + let options = data + .columns + .iter() + .find(|column| column.id == "target") + .unwrap() + .select_options(); + let labels = data + .cells + .get(&("r2".into(), "target".into())) + .map(|cell| { + cell.as_string_list() + .iter() + .map(|id| { + options + .iter() + .find(|option| option.id == *id) + .unwrap() + .value + .clone() + }) + .collect() + }) + .unwrap_or_default(); + (labels, options.len()) +} + +#[test] +fn comma_labels_paste_into_columns_without_the_option_as_one_label() { + // (source type, target type, source labels) + for (source_type, target_type, source_labels) in [ + ("select", "select", &["Sales, APAC"][..]), + ("select", "multi-select", &["Sales, APAC"][..]), + ("multi-select", "multi-select", &["Sales, APAC"][..]), + ("multi-select", "select", &["Sales, APAC"][..]), + ("multi-select", "multi-select", &["Design", "Rust"][..]), + ("multi-select", "multi-select", &["Sales, APAC", "Rust"][..]), + ] { + let table = comma_label_table(source_type, target_type, source_labels); + let before = table.read(); + table.select_cell("r1", "source"); + table.key("c", undo_modifiers()); + table.select_cell("r2", "target"); + table.key("v", undo_modifiers()); + let expected = if target_type == "select" { + &source_labels[..1] + } else { + source_labels + }; + assert_eq!( + target_labels(&table), + ( + expected.iter().map(|label| label.to_string()).collect(), + expected.len() + ), + "{source_type} -> {target_type}" + ); + table.undo(); + let restored = table.read(); + assert_eq!(restored.cells, before.cells); + assert_eq!(restored.columns, before.columns); + } +} + +#[test] +fn table_copy_keeps_a_comma_label_and_later_foreign_text_splits_it() { + let table = comma_label_table("select", "multi-select", &["Sales, APAC"]); + let before = table.read(); + table.select_cell("r1", "source"); + table.key("c", undo_modifiers()); + let copied = table.clipboard(|cx| cx.read_from_clipboard().unwrap()); + let one = (vec!["Sales, APAC".to_string()], 1); + let two = (vec!["Sales".to_string(), "APAC".to_string()], 2); + let foreign_html = ClipboardItem::new_string_with_json_metadata( + "Sales, APAC".into(), + json!({ "text/html": "

Sales, APAC

" }), + ); + // Each step pastes into `r2` `target`, then one undo restores the table. + // A paste event is how the Web brings the clipboard item. + for (step, item, paste_event, expected) in [ + ("table copy, key", copied.clone(), false, &one), + ("table copy, paste event", copied, true, &one), + ( + "foreign text, key", + ClipboardItem::new_string("Sales, APAC".into()), + false, + &two, + ), + ("foreign HTML, paste event", foreign_html, true, &two), + ] { + table.select_cell("r2", "target"); + if paste_event { + table.paste_event(item); + } else { + table.clipboard(|cx| cx.write_to_clipboard(item)); + table.key("v", undo_modifiers()); + } + assert_eq!(&target_labels(&table), expected, "{step}"); + table.undo(); + let restored = table.read(); + assert_eq!(restored.cells, before.cells, "{step}"); + assert_eq!(restored.columns, before.columns, "{step}"); + } +} diff --git a/blocksuite/crates/playground/src/database_authoring/tests_title_menus_and_keys.rs b/blocksuite/crates/playground/src/database_authoring/tests_title_menus_and_keys.rs index f0e0d897a7..e1d63e838a 100644 --- a/blocksuite/crates/playground/src/database_authoring/tests_title_menus_and_keys.rs +++ b/blocksuite/crates/playground/src/database_authoring/tests_title_menus_and_keys.rs @@ -129,8 +129,8 @@ impl Table { self.key("z", undo_modifiers()); } - pub(super) fn clipboard(&self, f: impl FnOnce(&mut App)) { - self.app.update(f); + pub(super) fn clipboard(&self, f: impl FnOnce(&mut App) -> R) -> R { + self.app.update(f) } pub(super) fn select_cell(&self, row: &str, column: &str) { @@ -141,6 +141,11 @@ impl Table { self.key("escape", Modifiers::default()); } + /// Paste `item` the way a browser `paste` event brings it. + pub(super) fn paste_event(&self, item: ClipboardItem) { + self.update(|view, window, cx| view.paste(item, window, cx)); + } + pub(super) fn paste_text(&self, text: &str) { self.clipboard(|cx| cx.write_to_clipboard(ClipboardItem::new_string(text.into()))); self.key("v", undo_modifiers()); diff --git a/blocksuite/crates/playground/src/editor_session/input_handler.rs b/blocksuite/crates/playground/src/editor_session/input_handler.rs index aac7619161..6d9a1b1398 100644 --- a/blocksuite/crates/playground/src/editor_session/input_handler.rs +++ b/blocksuite/crates/playground/src/editor_session/input_handler.rs @@ -50,6 +50,9 @@ impl EntityInputHandler for PlaygroundView { } return; } + if self.paste_into_focused_database_cell(&item, cx) { + return; + } if self.mode == crate::PlaygroundMode::Page && self.page_readonly { return; }