fix(database): preserve clipboard cells and select labels

Write empty text to the Web clipboard. Quote empty cells in single-column TSV rows.

Match pasted select options by their labels. Add missing options and write cells in one undo step.
This commit is contained in:
DarkSky committed 2026-12-05 02:19:08 +09:00
1 parent 9afd009dea
commit cacab32acd
8 files changed
+563 -307

No files matched your search

@@ -11,33 +11,55 @@ pub(super) fn fresh_database_id(
data: &DatabaseData,
prefix: &str,
) -> String {
let mut used: HashSet<&str> = HashSet::new();
for col in &data.columns {
used.insert(&col.id);
if let Some(opts) = col.data.get("options").and_then(|v| v.as_array()) {
used.extend(
opts.iter()
.filter_map(|opt| opt.get("id").and_then(|v| v.as_str())),
);
}
}
used.extend(data.views.iter().map(|view| view.id.as_str()));
used.extend(data.rows.iter().map(|row| row.row_id.as_str()));
let exists_in_page = |candidate: &str| {
prefix == "row"
&& page
.inner()
.get_map_value(page.blocks_target(), candidate)
.is_ok_and(|value| value.is_some())
};
let client_id = page.client_id();
let mut seq = page.revision().saturating_add(1);
let mut ids = DatabaseIdAllocator::new(page, data);
loop {
let candidate = format!("{prefix}-{client_id:x}-{seq:x}");
if !used.contains(candidate.as_str()) && !exists_in_page(&candidate) {
let candidate = ids.next(prefix);
if prefix != "row"
|| !page
.inner()
.get_map_value(page.blocks_target(), &candidate)
.is_ok_and(|value| value.is_some())
{
return candidate;
}
seq = seq.wrapping_add(1);
}
}
pub(super) struct DatabaseIdAllocator<'a> {
used: HashSet<&'a str>,
client_id: u64,
seq: u64,
}
impl<'a> DatabaseIdAllocator<'a> {
pub(super) fn new(page: &PageDocSession, data: &'a DatabaseData) -> Self {
let mut used: HashSet<&str> = HashSet::new();
for col in &data.columns {
used.insert(&col.id);
if let Some(opts) = col.data.get("options").and_then(|v| v.as_array()) {
used.extend(
opts.iter()
.filter_map(|opt| opt.get("id").and_then(|v| v.as_str())),
);
}
}
used.extend(data.views.iter().map(|view| view.id.as_str()));
used.extend(data.rows.iter().map(|row| row.row_id.as_str()));
Self {
used,
client_id: page.client_id(),
seq: page.revision().saturating_add(1),
}
}
pub(super) fn next(&mut self, prefix: &str) -> String {
loop {
let candidate = format!("{prefix}-{:x}-{:x}", self.client_id, self.seq);
self.seq = self.seq.wrapping_add(1);
if !self.used.contains(candidate.as_str()) {
return candidate;
}
}
}
}
+3 -1
View File
@@ -37,7 +37,9 @@ mod table_selection;
mod title;
pub use title::DATABASE_TITLE_FONT;
mod table_clipboard;
pub use table_clipboard::{TableClipboardCell, copy_table_cells, paste_table_cells};
pub use table_clipboard::{
TableClipboardCell, TableClipboardColumn, copy_table_cells, paste_table_cells,
};
mod view_action;
mod view_config;
mod view_tabs;
@@ -13,8 +13,9 @@ use blocksuite_playground_doc::{
use serde::{Deserialize, Serialize};
use super::{
DatabaseFlowState, DatabaseUiState, ParsedCellInput, is_editable_column_type, parse_cell_draft,
resolve_initial_cell_draft,
DatabaseFlowState, DatabaseUiState, ParsedCellInput,
authoring_id::DatabaseIdAllocator,
is_editable_column_type, next_tag_color, parse_cell_draft, resolve_initial_cell_draft,
table_selection::{RowSlot, focused_position, grid_position, table_grid},
};
@@ -25,9 +26,18 @@ pub enum TableClipboardCell {
Options {
ids: Vec<String>,
labels: Vec<String>,
#[serde(default)]
source: Option<TableClipboardColumn>,
},
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct TableClipboardColumn {
page: String,
block: String,
column: String,
}
impl TableClipboardCell {
pub fn plain_text(&self) -> Cow<'_, str> {
match self {
@@ -62,6 +72,7 @@ fn selected_axes(
}
pub fn copy_table_cells(
page_guid: &str,
state: &DatabaseFlowState,
block_id: &str,
data: &DatabaseData,
@@ -111,7 +122,15 @@ pub fn copy_table_cells(
})
})
.collect();
TableClipboardCell::Options { ids, labels }
TableClipboardCell::Options {
ids,
labels,
source: Some(TableClipboardColumn {
page: page_guid.to_string(),
block: block_id.to_string(),
column: id.clone(),
}),
}
}
_ => TableClipboardCell::Text(resolve_initial_cell_draft(
data, row, id, ty, offset,
@@ -207,18 +226,15 @@ fn write_cells<'a>(
now_ms: u64,
) -> DocResult<bool> {
let mut seen = BTreeSet::new();
let mut option_ids = None;
let mut column_options = BTreeMap::new();
let mut new_options = Vec::new();
let changes: Vec<_> = cells
.filter_map(|(row, column, ty, cell)| {
if !is_editable_column_type(ty) || !seen.insert((row, column)) {
return None;
}
let value = cell.map(TableClipboardCell::plain_text).unwrap_or_default();
let option_ids = match cell {
Some(TableClipboardCell::Options { ids, labels }) if !ids.is_empty() => {
Some((ids, labels))
}
_ => None,
};
let parsed = if ty == "title" {
let old = &data
.rows
@@ -230,9 +246,7 @@ fn write_cells<'a>(
return None;
}
ParsedCellInput::RowTitle(value.to_string())
} else if value.is_empty()
&& (option_ids.is_none() || !matches!(ty, "select" | "multi-select"))
{
} else if value.is_empty() {
let spec = match ty {
"rich-text" if cell.is_some() => {
if data
@@ -262,20 +276,72 @@ fn write_cells<'a>(
let spec = match ty {
"checkbox" => DatabaseCellSpec::Bool(value.parse().ok()?),
"select" | "multi-select" => {
let options = data
.columns
.iter()
.find(|col| col.id == column)?
.select_options();
let ids = match option_ids {
Some((ids, labels)) => match_copied_options(ids, labels, &options),
None => decode_options(&value, &options, ty == "multi-select")?,
let schema = data.columns.iter().find(|col| col.id == column)?;
let options = column_options
.entry(column)
.or_insert_with(|| schema.select_options());
let labels = match cell {
Some(TableClipboardCell::Options {
ids,
labels,
source,
}) => {
let same_column = source.as_ref().is_some_and(|source| {
source.page == page.guid()
&& source.block == block_id
&& source.column == column
});
labels
.iter()
.enumerate()
.filter(|(_, label)| !label.is_empty())
.map(|(index, label)| {
let id = ids.get(index).filter(|_| same_column);
(label.as_str(), id.map(String::as_str))
})
.collect()
}
_ => option_labels_from_text(&value, options)
.into_iter()
.map(|label| (label, None))
.collect::<Vec<_>>(),
};
if ids.is_empty() {
return None;
let mut ids = Vec::new();
for (label, preferred_id) in labels {
let existing = preferred_id
.and_then(|id| {
options
.iter()
.find(|opt| opt.id == id && opt.value == label)
})
.or_else(|| options.iter().find(|opt| opt.value == label));
let id = if let Some(option) = existing {
option.id.clone()
} else {
let option = DatabaseSelectOption {
id: option_ids
.get_or_insert_with(|| DatabaseIdAllocator::new(page, data))
.next("opt"),
value: label.to_string(),
color: next_tag_color(options.len()).to_string(),
};
let id = option.id.clone();
options.push(option.clone());
new_options.push((column, option));
id
};
if ty == "select" {
ids.push(id);
break;
}
if !ids.contains(&id) {
ids.push(id);
}
}
if ty == "select" {
DatabaseCellSpec::Text(ids.into_iter().next()?)
} else if ids.is_empty() {
return None;
} else {
DatabaseCellSpec::MultiSelect(ids)
}
@@ -294,6 +360,16 @@ fn write_cells<'a>(
return Ok(false);
}
page.structural_edit(now_ms, move |page| {
for (column, option) in new_options {
page.upsert_database_select_option(
block_id,
column,
&option.id,
&option.value,
&option.color,
now_ms,
)?;
}
for (row, column, value) in changes {
match value {
ParsedCellInput::RowTitle(title) => {
@@ -309,53 +385,25 @@ fn write_cells<'a>(
.map(|commit| commit.is_some())
}
fn match_copied_options(
ids: &[String],
labels: &[String],
options: &[DatabaseSelectOption],
) -> Vec<String> {
let mut matched = Vec::new();
for (id, label) in ids.iter().zip(labels) {
if let Some(option) = options
.iter()
.find(|option| option.id == *id)
.or_else(|| options.iter().find(|option| option.value == *label))
&& !matched.contains(&option.id)
{
matched.push(option.id.clone());
}
fn option_labels_from_text<'a>(value: &'a str, options: &[DatabaseSelectOption]) -> Vec<&'a str> {
if options.iter().any(|option| option.value == value) {
return vec![value];
}
matched
}
fn decode_options(
value: &str,
options: &[DatabaseSelectOption],
multiple: bool,
) -> Option<Vec<String>> {
let lookup = |name: &str| {
options
.iter()
.find(|option| option.value == name)
.or_else(|| options.iter().find(|option| option.id == name))
};
if let Some(option) = lookup(value) {
return Some(vec![option.id.clone()]);
}
if !multiple {
return None;
}
let mut remaining = value.trim();
let mut ids = Vec::new();
let mut labels = Vec::new();
while !remaining.is_empty() {
let (matched, rest) = remaining
let (label, rest) = remaining
.match_indices(',')
.map(|(end, _)| (&remaining[..end], &remaining[end + 1..]))
.map(|(end, _)| (remaining[..end].trim_end(), &remaining[end + 1..]))
.chain(std::iter::once((remaining, "")))
.filter_map(|(name, rest)| lookup(name.trim_end()).map(|option| (option, rest)))
.next_back()?;
ids.push(matched.id.clone());
.rfind(|(label, _)| options.iter().any(|opt| opt.value == *label))
.unwrap_or_else(|| remaining.split_once(',').unwrap_or((remaining, "")));
let label = label.trim_end();
if !label.is_empty() {
labels.push(label);
}
remaining = rest.trim_start();
}
Some(ids)
labels
}
@@ -20,8 +20,12 @@ impl PlaygroundView {
return false;
}
if key == "c" {
let Some(page) = self.page() else {
return false;
};
let offset = self.utc_offset_resolver();
if let Some(rows) = database::copy_table_cells(
page.guid(),
&self.flow.database_state,
block_id,
data,
@@ -145,7 +149,7 @@ fn encode_tsv(rows: &[Vec<TableClipboardCell>]) -> String {
text.push('\t');
}
let cell = cell.plain_text();
if cell.contains(['\t', '\n', '\r', '"']) {
if (row.len() == 1 && cell.is_empty()) || cell.contains(['\t', '\n', '\r', '"']) {
text.push('"');
text.push_str(&cell.replace('"', "\"\""));
text.push('"');
@@ -212,7 +216,7 @@ mod tests {
}
#[test]
fn quoted_tsv_and_clipboard_metadata_preserve_empty_fields() {
fn tsv_and_clipboard_metadata_preserve_empty_fields() {
for (text, expected) in [
("", vec![vec![""]]),
("A\n\n", vec![vec!["A"], vec![""]]),
@@ -225,10 +229,16 @@ mod tests {
assert_eq!(plain(&decode_tsv(text)), expected);
}
for input in [
vec![vec!["A"], vec![""]],
vec![vec![""]],
vec![vec!["A", ""], vec!["", ""]],
for (input, expected_text) in [
(vec![vec!["Ready"]], "Ready"),
(vec![vec![""]], "\"\""),
(vec![vec!["A"], vec![""]], "A\n\"\""),
(vec![vec![""], vec!["B"]], "\"\"\nB"),
(vec![vec!["A"], vec![""], vec![""]], "A\n\"\"\n\"\""),
(vec![vec![""], vec![""]], "\"\"\n\"\""),
(vec![vec!["", ""], vec!["", ""]], "\t\n\t"),
(vec![vec!["A", ""], vec!["", ""]], "A\t\n\t"),
(vec![vec!["A", "B"], vec!["C", "D"]], "A\tB\nC\tD"),
] {
let rows: Vec<_> = input
.iter()
@@ -239,6 +249,12 @@ mod tests {
})
.collect();
let text = encode_tsv(&rows);
assert_eq!(text, expected_text);
let plain_item = ClipboardItem::new_string(text.clone());
assert_eq!(
plain(&TableClipboard::from_item(&plain_item).unwrap()),
input
);
let item = TableClipboard::new_item(rows);
assert_eq!(item.text().unwrap_or_default(), text);
assert_eq!(plain(&TableClipboard::from_item(&item).unwrap()), input);
@@ -53,6 +53,8 @@ mod tests_scalar_edgeless_calendar;
#[cfg(test)]
mod tests_sideways_scroll_controls;
#[cfg(test)]
mod tests_table_clipboard;
#[cfg(test)]
mod tests_title_menus_and_keys;
#[cfg(test)]
mod tests_view_controls;
@@ -0,0 +1,364 @@
use blocksuite_playground_doc::{
read::DatabaseCellValue,
schema::{DatabaseCellSpec, DatabaseColumnSpec},
};
use serde_json::json;
use ui::{ClipboardItem, Modifiers};
use crate::HOME_PAGE_ID;
use super::{
tests::undo_modifiers,
tests_title_menus_and_keys::{Table, fixture},
};
#[test]
fn table_clipboard_roundtrips_empty_cells_and_restores_them_in_one_undo() {
let (mut doc, db) = fixture();
let page = doc.workspace.page_mut(HOME_PAGE_ID).unwrap();
page.add_database_column(
&db,
Some("v-table"),
DatabaseColumnSpec {
id: "source".into(),
column_type: "rich-text".into(),
name: "Source".into(),
data: json!({}),
},
Some(1),
24,
)
.unwrap();
page.set_database_cell_value(
&db,
"r1",
"source",
DatabaseCellSpec::RichText("A".into()),
25,
)
.unwrap();
page.set_database_cell_value(
&db,
"r2",
"source",
DatabaseCellSpec::RichText(String::new()),
26,
)
.unwrap();
page.stop_capturing().unwrap();
let table = Table::open(doc, db, 800);
let before = table.read().cells;
let shift = Modifiers {
shift: true,
..Default::default()
};
for (target_row, target_range, plain_text, text, expected) in [
("r1", true, true, "A\n\"\"", ["A", ""]),
("r1", false, false, "A\n\"\"", ["A", ""]),
("r2", false, true, "\"\"", ["Initial note", ""]),
("r2", false, false, "\"\"", ["Initial note", ""]),
] {
table.select_cell("r2", "c-note");
table.key("c", undo_modifiers());
table.clipboard(|cx| {
assert_eq!(
cx.read_from_clipboard().unwrap().text().as_deref(),
Some("Ready")
);
});
table.select_cell(target_row, "source");
if target_row == "r1" {
table.key("down", shift);
}
table.key("c", undo_modifiers());
table.clipboard(|cx| {
let item = cx.read_from_clipboard().unwrap();
assert_eq!(item.text().as_deref(), Some(text));
assert!(item.metadata().is_some());
if plain_text {
cx.write_to_clipboard(ClipboardItem::new_string(item.text().unwrap()));
}
});
table.select_cell(target_row, "c-note");
if target_range {
table.key("down", shift);
}
table.key("v", undo_modifiers());
let after = table.read().cells;
for (row, note) in ["r1", "r2"].into_iter().zip(expected) {
assert_eq!(after[&(row.into(), "c-note".into())].as_str(), Some(note));
}
table.undo();
assert_eq!(table.read().cells, before);
}
}
#[test]
fn select_and_multi_select_clipboard_preserve_comma_labels_and_option_ids() {
for column_type in ["select", "multi-select"] {
let (mut doc, db) = fixture();
let page = doc.workspace.page_mut(HOME_PAGE_ID).unwrap();
page.add_database_column(
&db,
Some("v-table"),
DatabaseColumnSpec {
id: "sales".into(),
column_type: column_type.into(),
name: "Region".into(),
data: json!({"options": [
{"id": "combined", "value": "Sales, APAC", "color": "blue"},
{"id": "sales", "value": "Sales", "color": "red"},
{"id": "apac", "value": "APAC", "color": "green"},
]}),
},
Some(1),
25,
)
.unwrap();
page.add_database_column(
&db,
Some("v-table"),
DatabaseColumnSpec {
id: "destination".into(),
column_type: column_type.into(),
name: "Destination".into(),
data: json!({"options": [
{"id": "target-combined", "value": "Sales, APAC", "color": "blue"},
{"id": "target-sales", "value": "Sales", "color": "red"},
{"id": "target-apac", "value": "APAC", "color": "green"},
]}),
},
Some(2),
26,
)
.unwrap();
let (source, target) = if column_type == "multi-select" {
(
DatabaseCellSpec::MultiSelect(vec!["combined".into()]),
DatabaseCellSpec::MultiSelect(vec!["sales".into(), "apac".into()]),
)
} else {
(
DatabaseCellSpec::Text("combined".into()),
DatabaseCellSpec::Text("apac".into()),
)
};
page.set_database_cell_value(&db, "r1", "sales", source, 26)
.unwrap();
page.set_database_cell_value(&db, "r2", "sales", target, 27)
.unwrap();
page.stop_capturing().unwrap();
let table = Table::open(doc, db, 800);
let before = table.read().cells;
for (src, dst) in [("r1", "r2"), ("r2", "r1")] {
table.select_cell(src, "sales");
table.key("c", undo_modifiers());
table.select_cell(dst, "sales");
table.key("v", undo_modifiers());
assert_eq!(
table.read().cells[&(dst.into(), "sales".into())],
before[&(src.into(), "sales".into())]
);
table.undo();
assert_eq!(table.read().cells, before);
}
for (src, text, ids) in [
("r1", "Sales, APAC", vec!["target-combined".to_string()]),
(
"r2",
if column_type == "multi-select" {
"Sales,APAC"
} else {
"APAC"
},
if column_type == "multi-select" {
vec!["target-sales".to_string(), "target-apac".to_string()]
} else {
vec!["target-apac".to_string()]
},
),
] {
table.select_cell(src, "sales");
table.key("c", undo_modifiers());
table.clipboard(|cx| {
let item = cx.read_from_clipboard().unwrap();
assert_eq!(item.text().as_deref(), Some(text));
assert!(item.metadata().is_some());
});
table.select_cell("r2", "destination");
table.key("v", undo_modifiers());
let value = if column_type == "multi-select" {
DatabaseCellValue::MultiSelect(ids)
} else {
DatabaseCellValue::Text(ids[0].clone())
};
assert_eq!(
table.read().cells[&("r2".into(), "destination".into())],
value
);
table.undo();
assert_eq!(table.read().cells, before);
table.select_cell("r2", "destination");
table.paste_text(text);
assert_eq!(
table.read().cells[&("r2".into(), "destination".into())],
value
);
table.undo();
assert_eq!(table.read().cells, before);
}
table.select_cell("r2", "sales");
table.paste_text("Sales, APAC");
assert_eq!(
table.read().cells[&("r2".into(), "sales".into())],
before[&("r1".into(), "sales".into())]
);
}
}
#[test]
fn cross_column_paste_matches_visible_labels_and_undoes_new_options() {
for (source_type, target_type, target_has_design, plain_text, expected) in [
(
"multi-select",
"multi-select",
true,
false,
&["Design", "Research"][..],
),
(
"multi-select",
"multi-select",
true,
true,
&["Design", "Research"][..],
),
(
"multi-select",
"multi-select",
false,
false,
&["Design", "Research"][..],
),
("select", "multi-select", false, true, &["Design"][..]),
("multi-select", "select", false, false, &["Design"][..]),
("select", "select", false, false, &["Design"][..]),
] {
let (mut doc, db) = fixture();
let page = doc.workspace.page_mut(HOME_PAGE_ID).unwrap();
let mut target_options =
vec![json!({"id": "shared", "value": "Archived", "color": "gray"})];
if target_has_design {
target_options.push(json!({"id": "target-design", "value": "Design", "color": "red"}));
}
for (index, (id, column_type, options)) in [
(
"source",
source_type,
vec![
json!({"id": "shared", "value": "Design", "color": "blue"}),
json!({"id": "research", "value": "Research", "color": "green"}),
],
),
("target", target_type, target_options),
]
.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, "extension": "keep"}),
},
Some(index + 1),
24,
)
.unwrap();
}
let source = if source_type == "select" {
DatabaseCellSpec::Text("shared".into())
} else {
DatabaseCellSpec::MultiSelect(vec!["shared".into(), "research".into()])
};
page.set_database_cell_value(&db, "r1", "source", source, 25)
.unwrap();
let old_target = || {
if target_type == "select" {
DatabaseCellSpec::Text("shared".into())
} else {
DatabaseCellSpec::MultiSelect(vec!["shared".into()])
}
};
for row in ["r1", "r2"] {
page.set_database_cell_value(&db, row, "target", old_target(), 26)
.unwrap();
}
page.stop_capturing().unwrap();
let table = Table::open(doc, db, 800);
let before = table.read();
table.select_cell("r1", "source");
table.key("c", undo_modifiers());
table.clipboard(|cx| {
let item = cx.read_from_clipboard().unwrap();
let text = item.text().unwrap();
assert_eq!(
text,
if source_type == "select" {
"Design"
} else {
"Design,Research"
}
);
if plain_text {
cx.write_to_clipboard(ClipboardItem::new_string(text));
}
});
table.select_cell("r1", "target");
table.key(
"down",
Modifiers {
shift: true,
..Default::default()
},
);
table.key("v", undo_modifiers());
let after = table.read();
let target_column = after
.columns
.iter()
.find(|column| column.id == "target")
.unwrap();
let options = target_column.select_options();
assert_eq!(options.len(), 1 + expected.len());
assert_eq!(options[0].value, "Archived");
assert_eq!(target_column.data["extension"], "keep");
for row in ["r1", "r2"] {
let ids = after.cells[&(row.into(), "target".into())].as_string_list();
let labels: Vec<_> = ids
.iter()
.map(|id| {
options
.iter()
.find(|option| option.id == *id)
.unwrap()
.value
.as_str()
})
.collect();
assert_eq!(labels, expected);
if target_has_design {
assert_eq!(ids[0], "target-design");
}
}
table.undo();
let restored = table.read();
assert_eq!(restored.cells, before.cells);
assert_eq!(restored.columns, before.columns);
}
}
@@ -59,7 +59,7 @@ pub(super) fn fixture() -> (DocState, String) {
(doc, db)
}
struct Table {
pub(super) struct Table {
platform: std::rc::Rc<ui::HeadlessPlatform>,
app: ui::ApplicationHandle,
win: ui::WindowHandle<PlaygroundView>,
@@ -73,7 +73,7 @@ impl Table {
Self::open(doc, db, 800)
}
fn open(doc: DocState, db: String, height: u32) -> Self {
pub(super) fn open(doc: DocState, db: String, height: u32) -> Self {
let (platform, app, win, input) =
open_authoring_window(1280, height, PlaygroundOptions::default(), doc);
let table = Self {
@@ -93,7 +93,7 @@ impl Table {
self.platform.run_until_parked();
}
fn read(&self) -> DatabaseData {
pub(super) fn read(&self) -> DatabaseData {
self.app
.update(|cx| read_db(self.win.read(cx).unwrap(), &self.db))
}
@@ -119,21 +119,21 @@ impl Table {
result
}
fn key(&self, key: &str, modifiers: Modifiers) {
pub(super) fn key(&self, key: &str, modifiers: Modifiers) {
self.update(|view, window, cx| {
view.editor_key_down(&key_event(key, None, modifiers), window, cx)
});
}
fn undo(&self) {
pub(super) fn undo(&self) {
self.key("z", undo_modifiers());
}
fn clipboard(&self, f: impl FnOnce(&mut App)) {
pub(super) fn clipboard(&self, f: impl FnOnce(&mut App)) {
self.app.update(f);
}
fn select_cell(&self, row: &str, column: &str) {
pub(super) fn select_cell(&self, row: &str, column: &str) {
self.click(|hit| {
matches!(hit, Hit::EditCell { row_id, column_id, .. }
if row_id == row && column_id == column)
@@ -141,7 +141,7 @@ impl Table {
self.key("escape", Modifiers::default());
}
fn paste_text(&self, text: &str) {
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());
}
@@ -477,210 +477,6 @@ fn paste_grows_from_focus_and_clips_or_tiles_rectangles_in_one_undo_step() {
}
}
#[test]
fn table_clipboard_roundtrips_empty_cells_and_restores_them_in_one_undo() {
let (mut doc, db) = fixture();
let page = doc.workspace.page_mut(HOME_PAGE_ID).unwrap();
page.add_database_column(
&db,
Some("v-table"),
DatabaseColumnSpec {
id: "source".into(),
column_type: "rich-text".into(),
name: "Source".into(),
data: json!({}),
},
Some(1),
24,
)
.unwrap();
page.set_database_cell_value(
&db,
"r1",
"source",
DatabaseCellSpec::RichText("A".into()),
25,
)
.unwrap();
page.set_database_cell_value(
&db,
"r2",
"source",
DatabaseCellSpec::RichText(String::new()),
26,
)
.unwrap();
page.stop_capturing().unwrap();
let table = Table::open(doc, db, 800);
let before = table.read().cells;
let shift = Modifiers {
shift: true,
..Default::default()
};
for (source, target_row, target_range, expected) in [
(None, "r1", true, ["A", ""]),
(None, "r1", false, ["A", ""]),
(None, "r2", false, ["Initial note", ""]),
(Some("A\n\n"), "r1", false, ["A", ""]),
(Some(""), "r2", false, ["Initial note", ""]),
] {
if source.is_none() {
table.select_cell(target_row, "source");
if target_row == "r1" {
table.key("down", shift);
}
table.key("c", undo_modifiers());
table.clipboard(|cx| {
let item = cx.read_from_clipboard().unwrap();
assert_eq!(
item.text().unwrap_or_default(),
if target_row == "r1" { "A\n" } else { "" }
);
assert!(item.metadata().is_some());
});
}
table.select_cell(target_row, "c-note");
if target_range {
table.key("down", shift);
}
if let Some(text) = source {
table.paste_text(text);
} else {
table.key("v", undo_modifiers());
}
let after = table.read().cells;
for (row, note) in ["r1", "r2"].into_iter().zip(expected) {
assert_eq!(after[&(row.into(), "c-note".into())].as_str(), Some(note));
}
table.undo();
assert_eq!(table.read().cells, before);
}
}
#[test]
fn select_and_multi_select_clipboard_preserve_comma_labels_and_option_ids() {
for column_type in ["select", "multi-select"] {
let (mut doc, db) = fixture();
let page = doc.workspace.page_mut(HOME_PAGE_ID).unwrap();
page.add_database_column(
&db,
Some("v-table"),
DatabaseColumnSpec {
id: "sales".into(),
column_type: column_type.into(),
name: "Region".into(),
data: json!({"options": [
{"id": "combined", "value": "Sales, APAC", "color": "blue"},
{"id": "sales", "value": "Sales", "color": "red"},
{"id": "apac", "value": "APAC", "color": "green"},
]}),
},
Some(1),
25,
)
.unwrap();
page.add_database_column(
&db,
Some("v-table"),
DatabaseColumnSpec {
id: "destination".into(),
column_type: column_type.into(),
name: "Destination".into(),
data: json!({"options": [
{"id": "target-combined", "value": "Sales, APAC", "color": "blue"},
{"id": "target-sales", "value": "Sales", "color": "red"},
{"id": "target-apac", "value": "APAC", "color": "green"},
]}),
},
Some(2),
26,
)
.unwrap();
let (source, target) = if column_type == "multi-select" {
(
DatabaseCellSpec::MultiSelect(vec!["combined".into()]),
DatabaseCellSpec::MultiSelect(vec!["sales".into(), "apac".into()]),
)
} else {
(
DatabaseCellSpec::Text("combined".into()),
DatabaseCellSpec::Text("apac".into()),
)
};
page.set_database_cell_value(&db, "r1", "sales", source, 26)
.unwrap();
page.set_database_cell_value(&db, "r2", "sales", target, 27)
.unwrap();
page.stop_capturing().unwrap();
let table = Table::open(doc, db, 800);
let before = table.read().cells;
for (src, dst) in [("r1", "r2"), ("r2", "r1")] {
table.select_cell(src, "sales");
table.key("c", undo_modifiers());
table.select_cell(dst, "sales");
table.key("v", undo_modifiers());
assert_eq!(
table.read().cells[&(dst.into(), "sales".into())],
before[&(src.into(), "sales".into())]
);
table.undo();
assert_eq!(table.read().cells, before);
}
for (src, text, ids) in [
("r1", "Sales, APAC", vec!["target-combined".to_string()]),
(
"r2",
if column_type == "multi-select" {
"Sales,APAC"
} else {
"APAC"
},
if column_type == "multi-select" {
vec!["target-sales".to_string(), "target-apac".to_string()]
} else {
vec!["target-apac".to_string()]
},
),
] {
table.select_cell(src, "sales");
table.key("c", undo_modifiers());
table.clipboard(|cx| {
let item = cx.read_from_clipboard().unwrap();
assert_eq!(item.text().as_deref(), Some(text));
assert!(item.metadata().is_some());
});
table.select_cell("r2", "destination");
table.key("v", undo_modifiers());
let value = if column_type == "multi-select" {
DatabaseCellValue::MultiSelect(ids)
} else {
DatabaseCellValue::Text(ids[0].clone())
};
assert_eq!(
table.read().cells[&("r2".into(), "destination".into())],
value
);
table.undo();
assert_eq!(table.read().cells, before);
table.select_cell("r2", "destination");
table.paste_text(text);
assert_eq!(
table.read().cells[&("r2".into(), "destination".into())],
value
);
table.undo();
assert_eq!(table.read().cells, before);
}
table.select_cell("r2", "sales");
table.paste_text("Sales, APAC");
assert_eq!(
table.read().cells[&("r2".into(), "sales".into())],
before[&("r1".into(), "sales".into())]
);
}
}
#[test]
fn short_window_column_menu_scrolls_to_duplicate_and_delete() {
let (doc, db) = fixture();
+7 -1
View File
@@ -621,7 +621,13 @@ impl Platform for WebPlatform {
}
fn write_to_clipboard(&self, item: ClipboardItem) {
if let Some(text) = item.text()
let text = item.text().or_else(|| {
item.entries()
.iter()
.any(|entry| matches!(entry, ClipboardEntry::String(_)))
.then(String::new)
});
if let Some(text) = text
&& let Some(window) = web_sys::window()
{
// Fire-and-forget; called synchronously inside the user's input