mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-05 11:15:01 +03:00
fix(editor): trim table tails by physical position
Use physical row and column positions for trim previews and commits. Keep cells shared with the remaining rows and columns. Move table axis menus into their own module and use static swatch strings. Keep fragments on pasted canvas links and share the mobile search offset helper.
This commit is contained in:
1 parent
00b3fd2337
commit
0f2537a376
8 files changed
+916
-375
No files matched your search
@@ -1,14 +1,26 @@
|
||||
//! Growing an `affine:table` at its end: new rows after the last row and new columns after the
|
||||
//! last column, with their cells, in one undo step.
|
||||
//! Append, trim, and duplicate table axes and their cells in one undo step.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
|
||||
use y_octo::{Any, SessionValue, TypePath, TypeTarget};
|
||||
use y_octo::{Any, SessionReadValue, SessionValue, TypePath, TypeTarget};
|
||||
|
||||
use crate::{DocError, DocResult, read::TableData};
|
||||
|
||||
use super::{PageCommit, PageDocSession};
|
||||
|
||||
#[derive(Default)]
|
||||
struct TableAxisEntry {
|
||||
logical_id: String,
|
||||
order: String,
|
||||
}
|
||||
|
||||
fn table_axis_string(value: Option<&SessionReadValue>) -> Option<&str> {
|
||||
match value {
|
||||
Some(SessionReadValue::Any(Any::String(value))) => Some(value),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn reject_duplicate_axis_ids(
|
||||
kind: &str,
|
||||
mut seen: HashSet<String>,
|
||||
@@ -138,7 +150,7 @@ impl PageDocSession {
|
||||
})
|
||||
}
|
||||
|
||||
/// Recheck the current document on release before removing empty trailing axes.
|
||||
/// Recheck the current document on release and remove the physical trailing axes.
|
||||
pub fn trim_empty_table_tail(
|
||||
&mut self,
|
||||
block_id: &str,
|
||||
@@ -149,26 +161,177 @@ impl PageDocSession {
|
||||
let Some(table) = self.read_table_block(block_id)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let rows = rows.min(table.empty_table_tail(true));
|
||||
let cols = cols.min(table.empty_table_tail(false));
|
||||
self.remove_table_axes(
|
||||
block_id,
|
||||
table
|
||||
.rows
|
||||
let rows = if rows == 0 {
|
||||
0
|
||||
} else {
|
||||
rows.min(table.empty_table_tail(true))
|
||||
};
|
||||
let cols = if cols == 0 {
|
||||
0
|
||||
} else {
|
||||
cols.min(table.empty_table_tail(false))
|
||||
};
|
||||
if rows == 0 && cols == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let block = TypeTarget::Path(TypePath::root("blocks").key(block_id));
|
||||
let entries: BTreeMap<_, _> = self.session.read_map(&block)?.into_iter().collect();
|
||||
let nested = |group| match entries.get(group) {
|
||||
Some(SessionReadValue::Map(id)) => Some(TypeTarget::Identity(id.clone())),
|
||||
_ => None,
|
||||
};
|
||||
let mut removals: Vec<(TypeTarget, Vec<String>)> = Vec::new();
|
||||
let mut flat = Vec::new();
|
||||
let mut unused_rows = HashSet::new();
|
||||
let mut unused_cols = HashSet::new();
|
||||
for (group, field, count, unused) in [
|
||||
("prop:rows", "rowId", rows, &mut unused_rows),
|
||||
("prop:columns", "columnId", cols, &mut unused_cols),
|
||||
] {
|
||||
if count == 0 {
|
||||
continue;
|
||||
}
|
||||
let prefix = format!("{group}.");
|
||||
let mut flat_axes = BTreeMap::<_, TableAxisEntry>::new();
|
||||
for (key, value) in entries.range(prefix.clone()..) {
|
||||
let Some(rest) = key.strip_prefix(&prefix) else {
|
||||
break;
|
||||
};
|
||||
let Some((physical, attr)) = rest.rsplit_once('.') else {
|
||||
continue;
|
||||
};
|
||||
let axis = flat_axes
|
||||
.entry(physical.to_owned())
|
||||
.or_insert_with(|| TableAxisEntry {
|
||||
logical_id: physical.to_owned(),
|
||||
..TableAxisEntry::default()
|
||||
});
|
||||
match (attr, table_axis_string(Some(value))) {
|
||||
(attr, Some(id)) if attr == field && !id.is_empty() => {
|
||||
axis.logical_id = id.into()
|
||||
}
|
||||
("order", Some(order)) => axis.order = order.into(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let target = nested(group);
|
||||
let flat_is_active = !flat_axes.is_empty();
|
||||
let mut nested_axes = Vec::new();
|
||||
if let Some(target) = &target {
|
||||
for (physical, value) in self.session.read_map(target)? {
|
||||
let SessionReadValue::Map(item) = value else {
|
||||
continue;
|
||||
};
|
||||
let item = TypeTarget::Identity(item);
|
||||
let id = self.session.get_map_value(&item, field)?;
|
||||
let logical_id = table_axis_string(id.as_ref())
|
||||
.filter(|id| !id.is_empty())
|
||||
.unwrap_or(&physical)
|
||||
.to_owned();
|
||||
let order = if flat_is_active {
|
||||
String::new()
|
||||
} else {
|
||||
let order = self.session.get_map_value(&item, "order")?;
|
||||
table_axis_string(order.as_ref())
|
||||
.unwrap_or_default()
|
||||
.to_owned()
|
||||
};
|
||||
nested_axes.push((physical, TableAxisEntry { logical_id, order }));
|
||||
}
|
||||
}
|
||||
let (mut active, shadowed) = if flat_is_active {
|
||||
(flat_axes.into_iter().collect::<Vec<_>>(), nested_axes)
|
||||
} else {
|
||||
(nested_axes, Vec::new())
|
||||
};
|
||||
// Match the table reader's stable sort, including ties in order and logical ID.
|
||||
active.sort_by(|(_, a), (_, b)| {
|
||||
a.order
|
||||
.cmp(&b.order)
|
||||
.then_with(|| a.logical_id.cmp(&b.logical_id))
|
||||
});
|
||||
let count = count.min(active.len().saturating_sub(1));
|
||||
if count == 0 {
|
||||
continue;
|
||||
}
|
||||
let (kept, removed) = active.split_at(active.len() - count);
|
||||
let kept_ids: HashSet<_> = kept
|
||||
.iter()
|
||||
.rev()
|
||||
.take(rows)
|
||||
.map(|r| r.row_id.as_str())
|
||||
.collect(),
|
||||
table
|
||||
.columns
|
||||
.iter()
|
||||
.rev()
|
||||
.take(cols)
|
||||
.map(|c| c.column_id.as_str())
|
||||
.collect(),
|
||||
now_ms,
|
||||
)
|
||||
.map(|(_, axis)| axis.logical_id.as_str())
|
||||
.collect();
|
||||
unused.extend(
|
||||
removed
|
||||
.iter()
|
||||
.map(|(_, axis)| &axis.logical_id)
|
||||
.filter(|id| !kept_ids.contains(id.as_str()))
|
||||
.cloned(),
|
||||
);
|
||||
|
||||
if flat_is_active {
|
||||
let removed: HashSet<_> = removed.iter().map(|(key, _)| key.as_str()).collect();
|
||||
flat.extend(
|
||||
entries
|
||||
.range(prefix.clone()..)
|
||||
.map_while(|(key, _)| key.strip_prefix(&prefix).map(|rest| (key, rest)))
|
||||
.filter_map(|(key, rest)| {
|
||||
let (physical, _) = rest.rsplit_once('.')?;
|
||||
removed.contains(physical).then(|| key.clone())
|
||||
}),
|
||||
);
|
||||
}
|
||||
if let Some(target) = target {
|
||||
let keys = if flat_is_active {
|
||||
shadowed
|
||||
.into_iter()
|
||||
.filter_map(|(key, axis)| unused.contains(&axis.logical_id).then_some(key))
|
||||
.collect()
|
||||
} else {
|
||||
removed.iter().map(|(key, _)| key.clone()).collect()
|
||||
};
|
||||
removals.push((target, keys));
|
||||
}
|
||||
}
|
||||
|
||||
if !unused_rows.is_empty() || !unused_cols.is_empty() {
|
||||
let unused_cell = |key: &str| {
|
||||
key.split_once(':').is_some_and(|(row, col)| {
|
||||
unused_rows.contains(row) || unused_cols.contains(col)
|
||||
})
|
||||
};
|
||||
flat.extend(
|
||||
entries
|
||||
.keys()
|
||||
.filter(|key| {
|
||||
key.strip_prefix("prop:cells.")
|
||||
.and_then(|rest| rest.rsplit_once('.'))
|
||||
.is_some_and(|(cell, _)| unused_cell(cell))
|
||||
})
|
||||
.cloned(),
|
||||
);
|
||||
if let Some(target) = nested("prop:cells") {
|
||||
let keys = self
|
||||
.session
|
||||
.read_map(&target)?
|
||||
.into_iter()
|
||||
.filter_map(|(key, _)| unused_cell(&key).then_some(key))
|
||||
.collect();
|
||||
removals.push((target, keys));
|
||||
}
|
||||
}
|
||||
if flat.is_empty() && removals.iter().all(|(_, keys)| keys.is_empty()) {
|
||||
return Ok(None);
|
||||
}
|
||||
removals.push((block, flat));
|
||||
self.structural_edit(now_ms, |page| {
|
||||
for (target, keys) in &removals {
|
||||
for key in keys {
|
||||
page.session.map_remove(target, key)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Copy one axis, its dimensions, colors and rich cell text into the adjacent slot.
|
||||
@@ -299,6 +462,212 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::schema::BlockSpec;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Storage {
|
||||
Flat,
|
||||
Nested,
|
||||
Mixed,
|
||||
}
|
||||
|
||||
fn import_trim_table(storage: Storage, row_ids: &[&str], col_ids: &[&str]) -> PageDocSession {
|
||||
let string = |s: &str| SessionValue::Any(Any::String(s.into()));
|
||||
let mut props = Vec::new();
|
||||
for (group, id_attr, ids) in [("rows", "rowId", row_ids), ("columns", "columnId", col_ids)]
|
||||
{
|
||||
let mut nested = vec![("scalar".into(), string("ignored"))];
|
||||
for (index, &id) in ids.iter().enumerate() {
|
||||
let physical = format!("p.{}", ids.len() - index);
|
||||
let attrs = [
|
||||
(id_attr, string(id)),
|
||||
("order", string(&format!("a{index}"))),
|
||||
(
|
||||
"backgroundColor",
|
||||
string(if index == 0 { "blue" } else { "red" }),
|
||||
),
|
||||
("width", SessionValue::Any(Any::Integer(185 + index as i32))),
|
||||
];
|
||||
if storage != Storage::Nested {
|
||||
props.extend(attrs.iter().map(|(field, value)| {
|
||||
(format!("prop:{group}.{physical}.{field}"), value.clone())
|
||||
}));
|
||||
}
|
||||
nested.push((
|
||||
physical,
|
||||
SessionValue::Map(
|
||||
attrs
|
||||
.into_iter()
|
||||
.map(|(key, value)| (key.into(), value))
|
||||
.collect(),
|
||||
),
|
||||
));
|
||||
}
|
||||
if storage != Storage::Flat {
|
||||
props.push((format!("prop:{group}"), SessionValue::Map(nested)));
|
||||
}
|
||||
}
|
||||
let mut nested_cells = Vec::new();
|
||||
let rows: std::collections::BTreeSet<_> = row_ids.iter().copied().collect();
|
||||
let cols: std::collections::BTreeSet<_> = col_ids.iter().copied().collect();
|
||||
for row in rows {
|
||||
for &col in &cols {
|
||||
let key = format!("{row}:{col}");
|
||||
if storage != Storage::Nested {
|
||||
props.push((
|
||||
format!("prop:cells.{key}.text"),
|
||||
SessionValue::Text(Vec::new()),
|
||||
));
|
||||
}
|
||||
if storage != Storage::Flat {
|
||||
nested_cells.push((
|
||||
key,
|
||||
SessionValue::Map(vec![("text".into(), SessionValue::Text(Vec::new()))]),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
if storage != Storage::Flat {
|
||||
props.push(("prop:cells".into(), SessionValue::Map(nested_cells)));
|
||||
}
|
||||
|
||||
let mut page = PageDocSession::new("table-trim", 17).unwrap();
|
||||
page.add_block(
|
||||
"root",
|
||||
BlockSpec::Page {
|
||||
title: "Table".into(),
|
||||
},
|
||||
None,
|
||||
None,
|
||||
1,
|
||||
)
|
||||
.unwrap();
|
||||
page.add_block(
|
||||
"note",
|
||||
BlockSpec::Note { xywh: None },
|
||||
Some("root"),
|
||||
None,
|
||||
2,
|
||||
)
|
||||
.unwrap();
|
||||
page.add_raw_block("tbl", "affine:table", 1, props, Some("note"), None, 3)
|
||||
.unwrap();
|
||||
page
|
||||
}
|
||||
|
||||
fn reload_trim_table(page: &PageDocSession) -> PageDocSession {
|
||||
let mut reader = PageDocSession::new("table-trim", 18).unwrap();
|
||||
reader
|
||||
.apply_remote_update_v1(&page.encode_update_v1().unwrap())
|
||||
.unwrap();
|
||||
reader
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_table_tail_preserves_physical_prefix_and_shared_cells_through_undo() {
|
||||
let rows = &["A", "B", "C", "A"];
|
||||
let cols = &["C1", "C2", "C3", "C4"];
|
||||
for storage in [Storage::Flat, Storage::Nested, Storage::Mixed] {
|
||||
for (row_ids, col_ids, trim, kept) in [
|
||||
(&rows[..], &cols[..], (1, 0), (3, 4)),
|
||||
(&["A", "A"][..], &cols[..], (1, 0), (1, 4)),
|
||||
(&["A", "A"][..], &cols[..], (2, 0), (1, 4)),
|
||||
(&rows[..], &["C1", "C2", "C1"][..], (0, 1), (4, 2)),
|
||||
(&rows[..], &["C1", "C1"][..], (0, 1), (4, 1)),
|
||||
(&rows[..], &["C1", "C1"][..], (0, 2), (4, 1)),
|
||||
(&rows[..], &["C1", "C2", "C1"][..], (2, 1), (2, 2)),
|
||||
] {
|
||||
let mut page = import_trim_table(storage, row_ids, col_ids);
|
||||
let before = page.read_table_block("tbl").unwrap().unwrap();
|
||||
assert_eq!(before.rows[0].background_color.as_deref(), Some("blue"));
|
||||
assert_eq!(before.columns[0].width, Some(185.0));
|
||||
let mut expected = before.clone();
|
||||
expected.rows.truncate(kept.0);
|
||||
expected.columns.truncate(kept.1);
|
||||
expected.cells.retain(|(r, c), _| {
|
||||
row_ids[..kept.0].contains(&r.as_str())
|
||||
&& col_ids[..kept.1].contains(&c.as_str())
|
||||
});
|
||||
|
||||
page.trim_empty_table_tail("tbl", trim.0, trim.1, 4)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let reader = reload_trim_table(&page);
|
||||
assert_eq!(
|
||||
reader.read_table_block("tbl").unwrap().unwrap(),
|
||||
expected,
|
||||
"{storage:?}, {row_ids:?}, {col_ids:?}, {trim:?}"
|
||||
);
|
||||
let block = TypeTarget::Path(TypePath::root("blocks").key("tbl"));
|
||||
let raw: BTreeMap<_, _> = reader
|
||||
.inner()
|
||||
.read_map(&block)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.collect();
|
||||
for (group, ids, kept) in [
|
||||
("prop:rows", row_ids, kept.0),
|
||||
("prop:columns", col_ids, kept.1),
|
||||
] {
|
||||
let map = raw.get(group).and_then(|value| match value {
|
||||
SessionReadValue::Map(id) => Some(TypeTarget::Identity(id.clone())),
|
||||
_ => None,
|
||||
});
|
||||
for (index, id) in ids.iter().enumerate() {
|
||||
let key = format!("p.{}", ids.len() - index);
|
||||
if storage != Storage::Nested {
|
||||
assert_eq!(
|
||||
raw.contains_key(&format!("{group}.{key}.order")),
|
||||
index < kept
|
||||
);
|
||||
}
|
||||
if let Some(map) = &map {
|
||||
let remains = if storage == Storage::Nested {
|
||||
index < kept
|
||||
} else {
|
||||
ids[..kept].contains(id)
|
||||
};
|
||||
assert_eq!(
|
||||
reader.inner().get_map_value(map, &key).unwrap().is_some(),
|
||||
remains
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
page.undo().unwrap().unwrap();
|
||||
assert_eq!(
|
||||
reload_trim_table(&page)
|
||||
.read_table_block("tbl")
|
||||
.unwrap()
|
||||
.unwrap(),
|
||||
before
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_table_tail_rechecks_occupied_axes_at_commit() {
|
||||
let mut page = import_trim_table(Storage::Flat, &["A", "A"], &["C", "C"]);
|
||||
let preview = page.read_table_block("tbl").unwrap().unwrap();
|
||||
assert_eq!(
|
||||
(
|
||||
preview.empty_table_tail(true),
|
||||
preview.empty_table_tail(false)
|
||||
),
|
||||
(1, 1)
|
||||
);
|
||||
|
||||
page.splice_table_cell_text("tbl", "A", "C", 0, 0, "arrived", 4)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let before = page.encode_update_v1().unwrap();
|
||||
assert!(
|
||||
page.trim_empty_table_tail("tbl", 1, 1, 5)
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
assert_eq!(page.encode_update_v1().unwrap(), before);
|
||||
}
|
||||
|
||||
fn seed_table() -> PageDocSession {
|
||||
let mut page = PageDocSession::new("page-table-dup", 17).expect("page");
|
||||
page.add_block(
|
||||
|
||||
@@ -99,6 +99,7 @@ pub(super) fn canvas_url_card(
|
||||
}
|
||||
let (scheme, authority, path, query) = split_url(&url)?;
|
||||
let is_http = scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https");
|
||||
// A linked document card cannot store a URL fragment.
|
||||
if let Some(path) = path.trim_end_matches('/').strip_prefix("/workspace/")
|
||||
&& let Some((room, doc)) = path.split_once('/')
|
||||
&& !doc.contains('/')
|
||||
@@ -106,6 +107,7 @@ pub(super) fn canvas_url_card(
|
||||
&& !authority.contains(['@', '\\'])
|
||||
&& (scheme.eq_ignore_ascii_case("affine")
|
||||
|| is_http
|
||||
&& !url.contains('#')
|
||||
&& BlockLink::server_origin(&url)
|
||||
.is_some_and(|candidate| candidate == BlockLink::workspace_origin(origin)))
|
||||
&& let Some(room) = decode_component(room)
|
||||
@@ -232,6 +234,27 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canvas_bookmarks_keep_url_fragments() {
|
||||
for (raw, expected) in [
|
||||
("http://example.com/#section", "http://example.com/#section"),
|
||||
(
|
||||
" https://example.com/guide?lang=en#part%202?x=y ",
|
||||
"https://example.com/guide?lang=en#part%202?x=y",
|
||||
),
|
||||
(
|
||||
"https://app.affine.pro/workspace/w/d?blockIds=b#section",
|
||||
"https://app.affine.pro/workspace/w/d?blockIds=b#section",
|
||||
),
|
||||
] {
|
||||
let card = canvas_url_card(raw, None, "w").expect("URL card");
|
||||
let BlockSpec::Bookmark { url, .. } = card.block else {
|
||||
panic!("expected a bookmark for {raw}");
|
||||
};
|
||||
assert_eq!(url, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canvas_url_card_filters_empty_reference_ids() {
|
||||
let url = "https://team.example/workspace/w/d?blockIds=&elementIds=";
|
||||
|
||||
@@ -5,6 +5,7 @@ mod paint;
|
||||
mod pointer;
|
||||
mod structure;
|
||||
mod toolbar;
|
||||
mod toolbar_popovers;
|
||||
mod touch_bar;
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
//! Table axis highlights and clipped grow and trim previews.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use blocksuite_playground_doc::read::{BlockContent, TableData};
|
||||
use ui::{div, prelude::*, px};
|
||||
|
||||
@@ -66,6 +64,7 @@ impl PlaygroundView {
|
||||
}
|
||||
} else if let Some(drag) = drag {
|
||||
let (rows, cols) = (drag.preview_rows, drag.preview_cols);
|
||||
let rtl = self.active_overlay_target()?.1.direction == ui::Direction::Rtl;
|
||||
if rows < 0 || cols < 0 {
|
||||
preview_kind = 1;
|
||||
let BlockContent::Table(t) =
|
||||
@@ -76,15 +75,14 @@ impl PlaygroundView {
|
||||
rects = collect_trim_preview_rects(
|
||||
cells,
|
||||
t,
|
||||
rows.unsigned_abs(),
|
||||
cols.unsigned_abs(),
|
||||
(rows.unsigned_abs(), cols.unsigned_abs()),
|
||||
rtl,
|
||||
frame,
|
||||
origin,
|
||||
bounds,
|
||||
);
|
||||
} else {
|
||||
preview_kind = 2;
|
||||
let rtl = self.active_overlay_target()?.1.direction == ui::Direction::Rtl;
|
||||
collect_grow_preview_rects(
|
||||
cells, rows, cols, rtl, frame, origin, bounds, &mut rects,
|
||||
);
|
||||
@@ -143,54 +141,33 @@ impl PlaygroundView {
|
||||
fn collect_trim_preview_rects(
|
||||
cells: &[TableCellHit],
|
||||
table: &TableData,
|
||||
rows: usize,
|
||||
cols: usize,
|
||||
(rows, cols): (usize, usize),
|
||||
rtl: bool,
|
||||
frame: TablePaintFrame,
|
||||
origin: (f32, f32),
|
||||
bounds: (f32, f32, f32),
|
||||
) -> Vec<FlowRect> {
|
||||
let Some(first) = cells.first() else {
|
||||
let row_width = table.columns.len();
|
||||
if row_width == 0 || !cells.len().is_multiple_of(row_width) {
|
||||
return Vec::new();
|
||||
};
|
||||
// The table layout emits one cell for each column in every row.
|
||||
let row_width = cells
|
||||
.iter()
|
||||
.take_while(|cell| cell.row_id == first.row_id)
|
||||
.count();
|
||||
let rows = &table.rows[table.rows.len().saturating_sub(rows)..];
|
||||
let cols = &table.columns[table.columns.len().saturating_sub(cols)..];
|
||||
let row_ids = (rows.len() > 4).then(|| {
|
||||
rows.iter()
|
||||
.map(|row| row.row_id.as_str())
|
||||
.collect::<HashSet<_>>()
|
||||
});
|
||||
let col_ids = (cols.len() > 4).then(|| {
|
||||
cols.iter()
|
||||
.map(|col| col.column_id.as_str())
|
||||
.collect::<HashSet<_>>()
|
||||
});
|
||||
|
||||
let col_ids = col_ids.as_ref();
|
||||
}
|
||||
// Each laid-out row has one cell per column. RTL reverses their visual order.
|
||||
let kept_rows = table.rows.len().saturating_sub(rows);
|
||||
let kept_cols = row_width.saturating_sub(cols);
|
||||
let trimmed_cols = row_width - kept_cols;
|
||||
let first_row = if trimmed_cols == 0 { kept_rows } else { 0 };
|
||||
cells
|
||||
.chunks(row_width)
|
||||
.flat_map(|row| {
|
||||
let row_id = row[0].row_id.as_str();
|
||||
let row_matches = row_ids.as_ref().map_or_else(
|
||||
|| rows.iter().any(|row| row.row_id == row_id),
|
||||
|ids| ids.contains(row_id),
|
||||
);
|
||||
let cells = if row_matches || !cols.is_empty() {
|
||||
.chunks_exact(row_width)
|
||||
.enumerate()
|
||||
.skip(first_row)
|
||||
.flat_map(|(index, row)| {
|
||||
if index >= kept_rows {
|
||||
row
|
||||
} else if rtl {
|
||||
&row[..trimmed_cols]
|
||||
} else {
|
||||
&[]
|
||||
};
|
||||
cells.iter().filter(move |cell| {
|
||||
row_matches
|
||||
|| col_ids.map_or_else(
|
||||
|| cols.iter().any(|col| col.column_id == cell.column_id),
|
||||
|ids| ids.contains(cell.column_id.as_str()),
|
||||
)
|
||||
})
|
||||
&row[kept_cols..]
|
||||
}
|
||||
})
|
||||
.filter_map(|cell| clip_rect(frame, origin, bounds, cell.rect))
|
||||
.collect()
|
||||
@@ -405,7 +382,15 @@ mod tests {
|
||||
|
||||
assert!(!expected.is_empty(), "{name}, {rows} rows, {cols} columns");
|
||||
assert_eq!(
|
||||
collect_trim_preview_rects(&cells, &table, rows, cols, frame, origin, bounds),
|
||||
collect_trim_preview_rects(
|
||||
&cells,
|
||||
&table,
|
||||
(rows, cols),
|
||||
false,
|
||||
frame,
|
||||
origin,
|
||||
bounds
|
||||
),
|
||||
expected,
|
||||
"{name}, {rows} rows, {cols} columns",
|
||||
);
|
||||
@@ -413,6 +398,75 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_preview_uses_physical_axes_when_imported_ids_repeat() {
|
||||
use blocksuite_playground_doc::read::{TableColumn, TableRow};
|
||||
|
||||
let mut cells = make_cells(2, 4);
|
||||
let mut table = TableData {
|
||||
rows: vec![
|
||||
TableRow {
|
||||
row_id: String::new(),
|
||||
order: String::new(),
|
||||
background_color: None,
|
||||
};
|
||||
2
|
||||
],
|
||||
columns: (0..4)
|
||||
.map(|c| TableColumn {
|
||||
column_id: format!("c{c}"),
|
||||
order: String::new(),
|
||||
width: None,
|
||||
background_color: None,
|
||||
})
|
||||
.collect(),
|
||||
..TableData::default()
|
||||
};
|
||||
let frame = TablePaintFrame::Page(PageViewport {
|
||||
column_x: 0.0,
|
||||
scroll_y: 0.0,
|
||||
height: 72.0,
|
||||
});
|
||||
for id in ["", "duplicate"] {
|
||||
for cell in &mut cells {
|
||||
cell.row_id = id.into();
|
||||
}
|
||||
for row in &mut table.rows {
|
||||
row.row_id = id.into();
|
||||
}
|
||||
table.columns[0].column_id = id.into();
|
||||
table.columns[3].column_id = id.into();
|
||||
for (rtl, (rows, cols), indices) in [
|
||||
(false, (1, 0), &[4, 5, 6, 7][..]),
|
||||
(false, (0, 1), &[3, 7][..]),
|
||||
(false, (1, 1), &[3, 4, 5, 6, 7][..]),
|
||||
(true, (0, 1), &[0, 4][..]),
|
||||
(true, (1, 1), &[0, 4, 5, 6, 7][..]),
|
||||
] {
|
||||
for row in cells.chunks_exact_mut(4) {
|
||||
for (index, cell) in row.iter_mut().enumerate() {
|
||||
let col = if rtl { 3 - index } else { index };
|
||||
cell.column_id.clone_from(&table.columns[col].column_id);
|
||||
}
|
||||
}
|
||||
let expected: Vec<_> = indices.iter().map(|&index| cells[index].rect).collect();
|
||||
assert_eq!(
|
||||
collect_trim_preview_rects(
|
||||
&cells,
|
||||
&table,
|
||||
(rows, cols),
|
||||
rtl,
|
||||
frame,
|
||||
(0.0, 0.0),
|
||||
(0.0, 400.0, 72.0)
|
||||
),
|
||||
expected,
|
||||
"axis ID {id:?}, rtl {rtl}, {rows} trimmed rows, {cols} trimmed columns",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn reference_grow_preview(
|
||||
cells: &[TableCellHit],
|
||||
first: &TableCellHit,
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
//! Simple Table (`affine:table`) desktop hover affordances (16 px add-column/add-row bars and
|
||||
//! corner drag-to-add, 28 × 16 / 16 × 28 three-dot axis pills, 5 px `ew-resize` column dividers,
|
||||
//! and axis action menus) plus mobile touch table toolbar.
|
||||
|
||||
use std::{cell::Cell, rc::Rc};
|
||||
//! and axis menu triggers).
|
||||
|
||||
use ui::{
|
||||
AnyElement, CursorStyle, FontWeight, MouseButton, MouseDownEvent, SharedString, div,
|
||||
@@ -10,13 +8,11 @@ use ui::{
|
||||
};
|
||||
|
||||
use crate::{
|
||||
PlaygroundMode, PlaygroundView,
|
||||
PlaygroundView,
|
||||
block_flow::{FlowLayout, FlowRect, PageViewport},
|
||||
overlays::{
|
||||
TOOLBAR_CHROME_BORDER, TOOLBAR_CHROME_RADIUS, TOOLBAR_MENU_MIN_W, TOOLBAR_MENU_PADDING,
|
||||
TOOLBAR_MENU_ROW_H, TableAddDrag, TableAddDragKind, TableAxisMenu, TableColResizeDrag,
|
||||
chrome_border_color, chrome_error_bg, chrome_error_fg, chrome_panel_bg,
|
||||
menu_horizontal_separator,
|
||||
TOOLBAR_CHROME_BORDER, TableAddDrag, TableAddDragKind, TableAxisMenu, TableColResizeDrag,
|
||||
chrome_border_color, chrome_panel_bg,
|
||||
},
|
||||
theme::{Palette, TYPOGRAPHY},
|
||||
};
|
||||
@@ -539,258 +535,4 @@ impl PlaygroundView {
|
||||
}
|
||||
Some(layer.into_any_element())
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn build_table_axis_menu(
|
||||
&self,
|
||||
axis: TableAxisMenu,
|
||||
x: f32,
|
||||
y: f32,
|
||||
viewport_h: f32,
|
||||
viewport_w: f32,
|
||||
palette: &Palette,
|
||||
cx: &mut ui::Context<Self>,
|
||||
) -> AnyElement {
|
||||
let is_row = axis == TableAxisMenu::Row;
|
||||
let menu_w = TOOLBAR_MENU_MIN_W.max(196.0);
|
||||
let max_height = (viewport_h - 16.0).max(120.0);
|
||||
let menu_h = (292.0 + TOOLBAR_MENU_ROW_H).min(max_height);
|
||||
let left = x.clamp(8.0, (viewport_w - menu_w - 8.0).max(8.0)).round();
|
||||
let top = y.clamp(8.0, (viewport_h - menu_h - 8.0).max(8.0)).round();
|
||||
let menu = div()
|
||||
.id("table-axis-menu")
|
||||
.absolute()
|
||||
.left(px(left))
|
||||
.top(px(top))
|
||||
.w(px(menu_w))
|
||||
.p(px(TOOLBAR_MENU_PADDING))
|
||||
.rounded(px(TOOLBAR_CHROME_RADIUS))
|
||||
.bg(chrome_panel_bg(palette))
|
||||
.border(px(TOOLBAR_CHROME_BORDER))
|
||||
.border_color(chrome_border_color(palette))
|
||||
.shadow(palette.theme.shadows("--affine-overlay-shadow").into())
|
||||
.flex()
|
||||
.flex_col()
|
||||
.occlude()
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_mouse_down_out(cx.listener(|this, _, _, cx| {
|
||||
if let Some(cell) = this.table_cell.as_mut()
|
||||
&& cell.axis_menu.take().is_some()
|
||||
{
|
||||
cx.notify();
|
||||
}
|
||||
}))
|
||||
.snapshot(
|
||||
format_args!("overlay.table_toolbar.axis_menu"),
|
||||
Some("root.canvas"),
|
||||
);
|
||||
let mut contents = div()
|
||||
.relative()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.flex_none()
|
||||
.child(
|
||||
div()
|
||||
.px(px(8.0))
|
||||
.py(px(2.0))
|
||||
.text_size(px(TYPOGRAPHY.font_xs_px))
|
||||
.font_weight(FontWeight::MEDIUM)
|
||||
.text_color(palette.text_secondary)
|
||||
.child("Background color"),
|
||||
)
|
||||
.child(table_axis_swatches(is_row, palette, cx))
|
||||
.child(menu_horizontal_separator(palette));
|
||||
let pick = |row, column| if is_row { row } else { column };
|
||||
let actions = [
|
||||
(
|
||||
"insert_before",
|
||||
"PlusIcon",
|
||||
pick("Insert Above", "Insert Left"),
|
||||
),
|
||||
(
|
||||
"insert_after",
|
||||
"PlusIcon",
|
||||
pick("Insert Below", "Insert Right"),
|
||||
),
|
||||
(
|
||||
"move_earlier",
|
||||
pick("ArrowUpBigIcon", "MoveLeftIcon"),
|
||||
pick("Move Up", "Move Left"),
|
||||
),
|
||||
(
|
||||
"move_later",
|
||||
pick("ArrowDownBigIcon", "MoveRightIcon"),
|
||||
pick("Move Down", "Move Right"),
|
||||
),
|
||||
(
|
||||
"duplicate",
|
||||
"DuplicateIcon",
|
||||
pick("Duplicate row", "Duplicate column"),
|
||||
),
|
||||
(
|
||||
"clear",
|
||||
"MinusIcon",
|
||||
pick("Clear row contents", "Clear column contents"),
|
||||
),
|
||||
("delete", "DeleteIcon", pick("Delete Row", "Delete Column")),
|
||||
];
|
||||
for (op, (snap, icon, label)) in actions.into_iter().enumerate() {
|
||||
if snap == "clear" {
|
||||
contents = contents.child(menu_horizontal_separator(palette));
|
||||
}
|
||||
let (h_bg, h_fg) = if snap == "delete" {
|
||||
(chrome_error_bg(palette), chrome_error_fg(palette))
|
||||
} else {
|
||||
(palette.hover, palette.text_primary)
|
||||
};
|
||||
contents = contents.child(
|
||||
div()
|
||||
.id(snap)
|
||||
.w_full()
|
||||
.h(px(TOOLBAR_MENU_ROW_H))
|
||||
.px(px(8.0))
|
||||
.rounded(px(4.0))
|
||||
.flex()
|
||||
.items_center()
|
||||
.cursor_pointer()
|
||||
.text_size(px(TYPOGRAPHY.font_sm_px))
|
||||
.text_color(palette.text_primary)
|
||||
.hover(move |s| s.bg(h_bg).text_color(h_fg))
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(cx.listener(move |this, _, win, cx| {
|
||||
if let Some(cell) = this.table_cell.as_mut() {
|
||||
cell.axis_menu = None;
|
||||
}
|
||||
match (op, is_row) {
|
||||
(0, true) => _ = this.table_insert_row_before(win, cx),
|
||||
(0, false) => _ = this.table_insert_column_before(win, cx),
|
||||
(1, true) => _ = this.table_insert_row_after(win, cx),
|
||||
(1, false) => _ = this.table_insert_column_after(win, cx),
|
||||
(2, _) => _ = this.table_move_axis(is_row, true, win, cx),
|
||||
(3, _) => _ = this.table_move_axis(is_row, false, win, cx),
|
||||
(4, _) => this.duplicate_table_axis(is_row, win, cx),
|
||||
(5, _) => _ = this.table_clear_axis(is_row, win, cx),
|
||||
(6, true) => _ = this.table_delete_focused_row(win, cx),
|
||||
(6, false) => _ = this.table_delete_focused_column(win, cx),
|
||||
_ => {}
|
||||
}
|
||||
cx.notify();
|
||||
}))
|
||||
.snapshot(
|
||||
format_args!("overlay.table_toolbar.axis_menu.{snap}"),
|
||||
Some("overlay.table_toolbar.axis_menu"),
|
||||
)
|
||||
.snapshot_text(label)
|
||||
.gap(px(8.0))
|
||||
.child(
|
||||
ui::canvas(
|
||||
|_, _, _| (),
|
||||
move |bounds, _, win, cx| {
|
||||
crate::theme::IconPaint::named(icon).paint(bounds, h_fg, win, cx);
|
||||
},
|
||||
)
|
||||
.w(px(16.0))
|
||||
.h(px(16.0)),
|
||||
)
|
||||
.child(label),
|
||||
);
|
||||
}
|
||||
if self.mode != PlaygroundMode::Page || self.uses_touch_table_bar(viewport_w) {
|
||||
return menu.child(contents).into_any_element();
|
||||
}
|
||||
let visible = max_height - 2.0 * (TOOLBAR_MENU_PADDING + TOOLBAR_CHROME_BORDER.ceil());
|
||||
let offset = self.overlays.table_axis_scroll.clone();
|
||||
let max_scroll = Rc::new(Cell::new(0.0));
|
||||
let measured = max_scroll.clone();
|
||||
let scroll_position = offset.clone();
|
||||
let contents = contents.top(px(-offset.get())).child(
|
||||
ui::canvas(
|
||||
move |bounds, window, _| {
|
||||
let limit = (f32::from(bounds.size.height) - visible).max(0.0);
|
||||
measured.set(limit);
|
||||
if scroll_position.get() > limit {
|
||||
scroll_position.set(limit);
|
||||
window.refresh();
|
||||
}
|
||||
},
|
||||
|_, (), _, _| {},
|
||||
)
|
||||
.absolute()
|
||||
.inset_0(),
|
||||
);
|
||||
let mut clip = div()
|
||||
.overflow_hidden()
|
||||
.on_scroll(cx.listener(move |_, event, _, cx| {
|
||||
let dy = blocksuite_editor::scroll::wheel_delta(event, visible).1;
|
||||
let next = (offset.get() - dy).clamp(0.0, max_scroll.get());
|
||||
cx.stop_propagation();
|
||||
if next != offset.replace(next) {
|
||||
cx.notify();
|
||||
}
|
||||
}));
|
||||
clip.style().max_size.height = Some(px(visible).into());
|
||||
menu.child(clip.child(contents)).into_any_element()
|
||||
}
|
||||
}
|
||||
|
||||
fn table_axis_swatches(
|
||||
is_row: bool,
|
||||
palette: &Palette,
|
||||
cx: &ui::Context<PlaygroundView>,
|
||||
) -> ui::Div {
|
||||
const SWATCHES: [(&str, &str); 9] = [
|
||||
("Default", "default"),
|
||||
("Blue", "blue"),
|
||||
("Green", "green"),
|
||||
("Grey", "grey"),
|
||||
("Orange", "orange"),
|
||||
("Purple", "purple"),
|
||||
("Red", "red"),
|
||||
("Teal", "teal"),
|
||||
("Yellow", "yellow"),
|
||||
];
|
||||
let swatches = SWATCHES.into_iter().filter_map(|(name, slug)| {
|
||||
let key = format!("var(--affine-v2-table-headerBackground-{slug})");
|
||||
let value = (slug != "default").then_some(key);
|
||||
let fill = match value.as_deref() {
|
||||
Some(key) => palette.theme.css_color(key)?,
|
||||
None => palette
|
||||
.theme
|
||||
.css_var("--affine-v2-layer-background-primary")?,
|
||||
};
|
||||
Some((name, slug, fill, value))
|
||||
});
|
||||
swatches.fold(
|
||||
div()
|
||||
.flex_none()
|
||||
.flex()
|
||||
.flex_wrap()
|
||||
.items_center()
|
||||
.gap(px(4.0))
|
||||
.px(px(6.0))
|
||||
.py(px(4.0)),
|
||||
|row, (name, slug, fill, value)| {
|
||||
row.child(
|
||||
div()
|
||||
.id(SharedString::from(format!("tbl-bg-{name}")))
|
||||
.flex_none()
|
||||
.w(px(24.0))
|
||||
.h(px(24.0))
|
||||
.rounded(px(4.0))
|
||||
.bg(fill)
|
||||
.border_1()
|
||||
.border_color(palette.border)
|
||||
.cursor_pointer()
|
||||
.on_mouse_down(ui::MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(cx.listener(move |this, _, win, cx| {
|
||||
let _ = this.table_set_axis_background(is_row, value.as_deref(), win, cx);
|
||||
}))
|
||||
.snapshot(
|
||||
format_args!("overlay.table_toolbar.axis_menu.bg_{slug}"),
|
||||
Some("overlay.table_toolbar.axis_menu"),
|
||||
)
|
||||
.snapshot_text(name),
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
//! Table axis action menu and color swatches.
|
||||
|
||||
use std::{cell::Cell, rc::Rc};
|
||||
|
||||
use ui::{AnyElement, FontWeight, MouseButton, div, prelude::*, px};
|
||||
|
||||
use crate::{
|
||||
PlaygroundMode, PlaygroundView,
|
||||
overlays::{
|
||||
TOOLBAR_CHROME_BORDER, TOOLBAR_CHROME_RADIUS, TOOLBAR_MENU_MIN_W, TOOLBAR_MENU_PADDING,
|
||||
TOOLBAR_MENU_ROW_H, TableAxisMenu, chrome_border_color, chrome_error_bg, chrome_error_fg,
|
||||
chrome_panel_bg, menu_horizontal_separator,
|
||||
},
|
||||
theme::{Palette, TYPOGRAPHY},
|
||||
};
|
||||
|
||||
const SWATCHES: [(&str, &str, &str, &str); 9] = [
|
||||
(
|
||||
"Default",
|
||||
"default",
|
||||
"tbl-bg-Default",
|
||||
"var(--affine-v2-table-headerBackground-default)",
|
||||
),
|
||||
(
|
||||
"Blue",
|
||||
"blue",
|
||||
"tbl-bg-Blue",
|
||||
"var(--affine-v2-table-headerBackground-blue)",
|
||||
),
|
||||
(
|
||||
"Green",
|
||||
"green",
|
||||
"tbl-bg-Green",
|
||||
"var(--affine-v2-table-headerBackground-green)",
|
||||
),
|
||||
(
|
||||
"Grey",
|
||||
"grey",
|
||||
"tbl-bg-Grey",
|
||||
"var(--affine-v2-table-headerBackground-grey)",
|
||||
),
|
||||
(
|
||||
"Orange",
|
||||
"orange",
|
||||
"tbl-bg-Orange",
|
||||
"var(--affine-v2-table-headerBackground-orange)",
|
||||
),
|
||||
(
|
||||
"Purple",
|
||||
"purple",
|
||||
"tbl-bg-Purple",
|
||||
"var(--affine-v2-table-headerBackground-purple)",
|
||||
),
|
||||
(
|
||||
"Red",
|
||||
"red",
|
||||
"tbl-bg-Red",
|
||||
"var(--affine-v2-table-headerBackground-red)",
|
||||
),
|
||||
(
|
||||
"Teal",
|
||||
"teal",
|
||||
"tbl-bg-Teal",
|
||||
"var(--affine-v2-table-headerBackground-teal)",
|
||||
),
|
||||
(
|
||||
"Yellow",
|
||||
"yellow",
|
||||
"tbl-bg-Yellow",
|
||||
"var(--affine-v2-table-headerBackground-yellow)",
|
||||
),
|
||||
];
|
||||
|
||||
impl PlaygroundView {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn build_table_axis_menu(
|
||||
&self,
|
||||
axis: TableAxisMenu,
|
||||
x: f32,
|
||||
y: f32,
|
||||
viewport_h: f32,
|
||||
viewport_w: f32,
|
||||
palette: &Palette,
|
||||
cx: &mut ui::Context<Self>,
|
||||
) -> AnyElement {
|
||||
let is_row = axis == TableAxisMenu::Row;
|
||||
let menu_w = TOOLBAR_MENU_MIN_W.max(196.0);
|
||||
let max_height = (viewport_h - 16.0).max(120.0);
|
||||
let menu_h = (292.0 + TOOLBAR_MENU_ROW_H).min(max_height);
|
||||
let left = x.clamp(8.0, (viewport_w - menu_w - 8.0).max(8.0)).round();
|
||||
let top = y.clamp(8.0, (viewport_h - menu_h - 8.0).max(8.0)).round();
|
||||
let menu = div()
|
||||
.id("table-axis-menu")
|
||||
.absolute()
|
||||
.left(px(left))
|
||||
.top(px(top))
|
||||
.w(px(menu_w))
|
||||
.p(px(TOOLBAR_MENU_PADDING))
|
||||
.rounded(px(TOOLBAR_CHROME_RADIUS))
|
||||
.bg(chrome_panel_bg(palette))
|
||||
.border(px(TOOLBAR_CHROME_BORDER))
|
||||
.border_color(chrome_border_color(palette))
|
||||
.shadow(palette.theme.shadows("--affine-overlay-shadow").into())
|
||||
.flex()
|
||||
.flex_col()
|
||||
.occlude()
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_mouse_down_out(cx.listener(|this, _, _, cx| {
|
||||
if let Some(cell) = this.table_cell.as_mut()
|
||||
&& cell.axis_menu.take().is_some()
|
||||
{
|
||||
cx.notify();
|
||||
}
|
||||
}))
|
||||
.snapshot(
|
||||
format_args!("overlay.table_toolbar.axis_menu"),
|
||||
Some("root.canvas"),
|
||||
);
|
||||
let mut contents = div()
|
||||
.relative()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.flex_none()
|
||||
.child(
|
||||
div()
|
||||
.px(px(8.0))
|
||||
.py(px(2.0))
|
||||
.text_size(px(TYPOGRAPHY.font_xs_px))
|
||||
.font_weight(FontWeight::MEDIUM)
|
||||
.text_color(palette.text_secondary)
|
||||
.child("Background color"),
|
||||
)
|
||||
.child(table_axis_swatches(is_row, palette, cx))
|
||||
.child(menu_horizontal_separator(palette));
|
||||
let pick = |row, column| if is_row { row } else { column };
|
||||
let actions = [
|
||||
(
|
||||
"insert_before",
|
||||
"PlusIcon",
|
||||
pick("Insert Above", "Insert Left"),
|
||||
),
|
||||
(
|
||||
"insert_after",
|
||||
"PlusIcon",
|
||||
pick("Insert Below", "Insert Right"),
|
||||
),
|
||||
(
|
||||
"move_earlier",
|
||||
pick("ArrowUpBigIcon", "MoveLeftIcon"),
|
||||
pick("Move Up", "Move Left"),
|
||||
),
|
||||
(
|
||||
"move_later",
|
||||
pick("ArrowDownBigIcon", "MoveRightIcon"),
|
||||
pick("Move Down", "Move Right"),
|
||||
),
|
||||
(
|
||||
"duplicate",
|
||||
"DuplicateIcon",
|
||||
pick("Duplicate row", "Duplicate column"),
|
||||
),
|
||||
(
|
||||
"clear",
|
||||
"MinusIcon",
|
||||
pick("Clear row contents", "Clear column contents"),
|
||||
),
|
||||
("delete", "DeleteIcon", pick("Delete Row", "Delete Column")),
|
||||
];
|
||||
for (op, (snap, icon, label)) in actions.into_iter().enumerate() {
|
||||
if snap == "clear" {
|
||||
contents = contents.child(menu_horizontal_separator(palette));
|
||||
}
|
||||
let (h_bg, h_fg) = if snap == "delete" {
|
||||
(chrome_error_bg(palette), chrome_error_fg(palette))
|
||||
} else {
|
||||
(palette.hover, palette.text_primary)
|
||||
};
|
||||
contents = contents.child(
|
||||
div()
|
||||
.id(snap)
|
||||
.w_full()
|
||||
.h(px(TOOLBAR_MENU_ROW_H))
|
||||
.px(px(8.0))
|
||||
.rounded(px(4.0))
|
||||
.flex()
|
||||
.items_center()
|
||||
.cursor_pointer()
|
||||
.text_size(px(TYPOGRAPHY.font_sm_px))
|
||||
.text_color(palette.text_primary)
|
||||
.hover(move |s| s.bg(h_bg).text_color(h_fg))
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(cx.listener(move |this, _, win, cx| {
|
||||
if let Some(cell) = this.table_cell.as_mut() {
|
||||
cell.axis_menu = None;
|
||||
}
|
||||
match (op, is_row) {
|
||||
(0, true) => _ = this.table_insert_row_before(win, cx),
|
||||
(0, false) => _ = this.table_insert_column_before(win, cx),
|
||||
(1, true) => _ = this.table_insert_row_after(win, cx),
|
||||
(1, false) => _ = this.table_insert_column_after(win, cx),
|
||||
(2, _) => _ = this.table_move_axis(is_row, true, win, cx),
|
||||
(3, _) => _ = this.table_move_axis(is_row, false, win, cx),
|
||||
(4, _) => this.duplicate_table_axis(is_row, win, cx),
|
||||
(5, _) => _ = this.table_clear_axis(is_row, win, cx),
|
||||
(6, true) => _ = this.table_delete_focused_row(win, cx),
|
||||
(6, false) => _ = this.table_delete_focused_column(win, cx),
|
||||
_ => {}
|
||||
}
|
||||
cx.notify();
|
||||
}))
|
||||
.snapshot(
|
||||
format_args!("overlay.table_toolbar.axis_menu.{snap}"),
|
||||
Some("overlay.table_toolbar.axis_menu"),
|
||||
)
|
||||
.snapshot_text(label)
|
||||
.gap(px(8.0))
|
||||
.child(
|
||||
ui::canvas(
|
||||
|_, _, _| (),
|
||||
move |bounds, _, win, cx| {
|
||||
crate::theme::IconPaint::named(icon).paint(bounds, h_fg, win, cx);
|
||||
},
|
||||
)
|
||||
.w(px(16.0))
|
||||
.h(px(16.0)),
|
||||
)
|
||||
.child(label),
|
||||
);
|
||||
}
|
||||
if self.mode != PlaygroundMode::Page || self.uses_touch_table_bar(viewport_w) {
|
||||
return menu.child(contents).into_any_element();
|
||||
}
|
||||
let visible = max_height - 2.0 * (TOOLBAR_MENU_PADDING + TOOLBAR_CHROME_BORDER.ceil());
|
||||
let offset = self.overlays.table_axis_scroll.clone();
|
||||
let max_scroll = Rc::new(Cell::new(0.0));
|
||||
let measured = max_scroll.clone();
|
||||
let scroll_position = offset.clone();
|
||||
let contents = contents.top(px(-offset.get())).child(
|
||||
ui::canvas(
|
||||
move |bounds, window, _| {
|
||||
let limit = (f32::from(bounds.size.height) - visible).max(0.0);
|
||||
measured.set(limit);
|
||||
if scroll_position.get() > limit {
|
||||
scroll_position.set(limit);
|
||||
window.refresh();
|
||||
}
|
||||
},
|
||||
|_, (), _, _| {},
|
||||
)
|
||||
.absolute()
|
||||
.inset_0(),
|
||||
);
|
||||
let mut clip = div()
|
||||
.overflow_hidden()
|
||||
.on_scroll(cx.listener(move |_, event, _, cx| {
|
||||
let dy = blocksuite_editor::scroll::wheel_delta(event, visible).1;
|
||||
let next = (offset.get() - dy).clamp(0.0, max_scroll.get());
|
||||
cx.stop_propagation();
|
||||
if next != offset.replace(next) {
|
||||
cx.notify();
|
||||
}
|
||||
}));
|
||||
clip.style().max_size.height = Some(px(visible).into());
|
||||
menu.child(clip.child(contents)).into_any_element()
|
||||
}
|
||||
}
|
||||
|
||||
fn table_axis_swatches(
|
||||
is_row: bool,
|
||||
palette: &Palette,
|
||||
cx: &ui::Context<PlaygroundView>,
|
||||
) -> ui::Div {
|
||||
let swatches = SWATCHES.into_iter().filter_map(|(name, slug, id, key)| {
|
||||
let value = (slug != "default").then_some(key);
|
||||
let fill = match value {
|
||||
Some(key) => palette.theme.css_color(key)?,
|
||||
None => palette
|
||||
.theme
|
||||
.css_var("--affine-v2-layer-background-primary")?,
|
||||
};
|
||||
Some((name, slug, id, fill, value))
|
||||
});
|
||||
swatches.fold(
|
||||
div()
|
||||
.flex_none()
|
||||
.flex()
|
||||
.flex_wrap()
|
||||
.items_center()
|
||||
.gap(px(4.0))
|
||||
.px(px(6.0))
|
||||
.py(px(4.0)),
|
||||
|row, (name, slug, id, fill, value)| {
|
||||
row.child(
|
||||
div()
|
||||
.id(id)
|
||||
.flex_none()
|
||||
.w(px(24.0))
|
||||
.h(px(24.0))
|
||||
.rounded(px(4.0))
|
||||
.bg(fill)
|
||||
.border_1()
|
||||
.border_color(palette.border)
|
||||
.cursor_pointer()
|
||||
.on_mouse_down(ui::MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(cx.listener(move |this, _, win, cx| {
|
||||
let _ = this.table_set_axis_background(is_row, value, win, cx);
|
||||
}))
|
||||
.snapshot(
|
||||
format_args!("overlay.table_toolbar.axis_menu.bg_{slug}"),
|
||||
Some("overlay.table_toolbar.axis_menu"),
|
||||
)
|
||||
.snapshot_text(name),
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::SWATCHES;
|
||||
|
||||
#[test]
|
||||
fn table_axis_swatches_keep_control_ids_and_color_tokens() {
|
||||
assert_eq!(
|
||||
SWATCHES.map(|(_, slug, _, _)| slug),
|
||||
[
|
||||
"default", "blue", "green", "grey", "orange", "purple", "red", "teal", "yellow",
|
||||
]
|
||||
);
|
||||
for (name, slug, id, key) in SWATCHES {
|
||||
assert_eq!(name.to_ascii_lowercase(), slug);
|
||||
assert_eq!(id, format!("tbl-bg-{name}"));
|
||||
assert_eq!(
|
||||
key,
|
||||
format!("var(--affine-v2-table-headerBackground-{slug})")
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -251,17 +251,6 @@ impl MobileShellView {
|
||||
now.saturating_duration_since(origin).as_secs_f64() * 1000.0
|
||||
}
|
||||
|
||||
fn utf16_to_byte(text: &str, utf16_offset: usize) -> usize {
|
||||
let mut units = 0usize;
|
||||
for (byte_idx, ch) in text.char_indices() {
|
||||
if units >= utf16_offset {
|
||||
return byte_idx;
|
||||
}
|
||||
units += ch.len_utf16();
|
||||
}
|
||||
text.len()
|
||||
}
|
||||
|
||||
/// Control-key handler for `Search` (`Backspace`, `Delete`, `Escape`).
|
||||
/// Printable character insertion flows exclusively through [`EntityInputHandler`] so
|
||||
/// physical keyboard events never duplicate characters on Web or native hosts.
|
||||
@@ -281,12 +270,12 @@ impl MobileShellView {
|
||||
let start = self.state.search_selection.start.min(total);
|
||||
let end = self.state.search_selection.end.min(total).max(start);
|
||||
if end > start {
|
||||
let bs = Self::utf16_to_byte(&self.state.search_query, start);
|
||||
let be = Self::utf16_to_byte(&self.state.search_query, end);
|
||||
let bs = utf16_to_byte(&self.state.search_query, start);
|
||||
let be = utf16_to_byte(&self.state.search_query, end);
|
||||
self.state.search_query.replace_range(bs..be, "");
|
||||
self.state.search_selection = start..start;
|
||||
} else if start > 0 {
|
||||
let be = Self::utf16_to_byte(&self.state.search_query, start);
|
||||
let be = utf16_to_byte(&self.state.search_query, start);
|
||||
if let Some((prev_b, prev_ch)) =
|
||||
self.state.search_query[..be].char_indices().next_back()
|
||||
{
|
||||
@@ -304,12 +293,12 @@ impl MobileShellView {
|
||||
let start = self.state.search_selection.start.min(total);
|
||||
let end = self.state.search_selection.end.min(total).max(start);
|
||||
if end > start {
|
||||
let bs = Self::utf16_to_byte(&self.state.search_query, start);
|
||||
let be = Self::utf16_to_byte(&self.state.search_query, end);
|
||||
let bs = utf16_to_byte(&self.state.search_query, start);
|
||||
let be = utf16_to_byte(&self.state.search_query, end);
|
||||
self.state.search_query.replace_range(bs..be, "");
|
||||
self.state.search_selection = start..start;
|
||||
} else if start < total {
|
||||
let bs = Self::utf16_to_byte(&self.state.search_query, start);
|
||||
let bs = utf16_to_byte(&self.state.search_query, start);
|
||||
if let Some(next_ch) = self.state.search_query[bs..].chars().next() {
|
||||
let be = bs + next_ch.len_utf8();
|
||||
self.state.search_query.replace_range(bs..be, "");
|
||||
@@ -346,8 +335,8 @@ impl EntityInputHandler for MobileShellView {
|
||||
let s = range.start.min(total);
|
||||
let e = range.end.min(total).max(s);
|
||||
*adjusted_range = Some(s..e);
|
||||
let bs = Self::utf16_to_byte(&self.state.search_query, s);
|
||||
let be = Self::utf16_to_byte(&self.state.search_query, e);
|
||||
let bs = utf16_to_byte(&self.state.search_query, s);
|
||||
let be = utf16_to_byte(&self.state.search_query, e);
|
||||
Some(self.state.search_query[bs..be].to_string())
|
||||
}
|
||||
|
||||
@@ -396,8 +385,8 @@ impl EntityInputHandler for MobileShellView {
|
||||
});
|
||||
let start_u16 = target.start.min(total);
|
||||
let end_u16 = target.end.min(total).max(start_u16);
|
||||
let bs = Self::utf16_to_byte(&self.state.search_query, start_u16);
|
||||
let be = Self::utf16_to_byte(&self.state.search_query, end_u16);
|
||||
let bs = utf16_to_byte(&self.state.search_query, start_u16);
|
||||
let be = utf16_to_byte(&self.state.search_query, end_u16);
|
||||
self.state.search_query.replace_range(bs..be, text);
|
||||
let new_caret = start_u16 + text.encode_utf16().count();
|
||||
self.state.search_selection = new_caret..new_caret;
|
||||
@@ -423,8 +412,8 @@ impl EntityInputHandler for MobileShellView {
|
||||
});
|
||||
let start_u16 = target.start.min(total);
|
||||
let end_u16 = target.end.min(total).max(start_u16);
|
||||
let bs = Self::utf16_to_byte(&self.state.search_query, start_u16);
|
||||
let be = Self::utf16_to_byte(&self.state.search_query, end_u16);
|
||||
let bs = utf16_to_byte(&self.state.search_query, start_u16);
|
||||
let be = utf16_to_byte(&self.state.search_query, end_u16);
|
||||
self.state.search_query.replace_range(bs..be, new_text);
|
||||
let inserted_len = new_text.encode_utf16().count();
|
||||
self.state.search_preedit = if inserted_len > 0 {
|
||||
@@ -713,3 +702,38 @@ impl Render for MobileShellView {
|
||||
root
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert a UTF-16 offset to a UTF-8 boundary. Round up inside a surrogate pair.
|
||||
fn utf16_to_byte(text: &str, utf16_offset: usize) -> usize {
|
||||
let mut units = 0usize;
|
||||
for (byte_idx, ch) in text.char_indices() {
|
||||
if units >= utf16_offset {
|
||||
return byte_idx;
|
||||
}
|
||||
units += ch.len_utf16();
|
||||
}
|
||||
text.len()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod utf16_tests {
|
||||
use super::utf16_to_byte;
|
||||
|
||||
#[test]
|
||||
fn utf16_offsets_round_up_inside_surrogate_pairs() {
|
||||
for (text, offsets) in [
|
||||
("A😀B", &[0, 1, 5, 5, 6, 6][..]),
|
||||
("😀", &[0, 4, 4, 4][..]),
|
||||
("é中", &[0, 2, 5, 5][..]),
|
||||
("", &[0, 0][..]),
|
||||
] {
|
||||
for (offset, &expected) in offsets.iter().enumerate() {
|
||||
assert_eq!(
|
||||
utf16_to_byte(text, offset),
|
||||
expected,
|
||||
"{text:?} at {offset}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ use crate::{state::MobileAppState, strings::MobileStrings};
|
||||
|
||||
use super::{
|
||||
A11yBoundsMap, CLOSE_ICON_SVG, MobileFlexExt, MobilePalette, MobileShellView, SEARCH_ICON_SVG,
|
||||
a11y_bounds_probe, row_dir,
|
||||
a11y_bounds_probe, row_dir, utf16_to_byte,
|
||||
};
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -58,8 +58,8 @@ pub(super) fn render_search(
|
||||
);
|
||||
} else if let Some(pre) = state.search_preedit.clone() {
|
||||
let total = state.search_query.encode_utf16().count();
|
||||
let s = utf16_to_byte_offset(&state.search_query, pre.start.min(total));
|
||||
let e = utf16_to_byte_offset(
|
||||
let s = utf16_to_byte(&state.search_query, pre.start.min(total));
|
||||
let e = utf16_to_byte(
|
||||
&state.search_query,
|
||||
pre.end.min(total).max(pre.start.min(total)),
|
||||
);
|
||||
@@ -393,17 +393,6 @@ fn render_highlighted_line(
|
||||
row
|
||||
}
|
||||
|
||||
fn utf16_to_byte_offset(text: &str, utf16_target: usize) -> usize {
|
||||
let mut units = 0usize;
|
||||
for (byte_idx, ch) in text.char_indices() {
|
||||
if units >= utf16_target {
|
||||
return byte_idx;
|
||||
}
|
||||
units += ch.len_utf16();
|
||||
}
|
||||
text.len()
|
||||
}
|
||||
|
||||
fn byte_to_utf16_offset(text: &str, byte_target: usize) -> usize {
|
||||
text[..byte_target.min(text.len())].encode_utf16().count()
|
||||
}
|
||||
@@ -437,11 +426,11 @@ pub(crate) fn snippet_window_utf16(
|
||||
(0, max_utf16.min(total_utf16))
|
||||
};
|
||||
|
||||
let mut b_start = utf16_to_byte_offset(text, raw_start);
|
||||
let mut b_end = utf16_to_byte_offset(text, raw_end);
|
||||
let mut b_start = utf16_to_byte(text, raw_start);
|
||||
let mut b_end = utf16_to_byte(text, raw_end);
|
||||
|
||||
let hit_b_start = first_hit.map(|(hs, _)| utf16_to_byte_offset(text, hs));
|
||||
let hit_b_end = first_hit.map(|(_, he)| utf16_to_byte_offset(text, he));
|
||||
let hit_b_start = first_hit.map(|(hs, _)| utf16_to_byte(text, hs));
|
||||
let hit_b_end = first_hit.map(|(_, he)| utf16_to_byte(text, he));
|
||||
if b_start > 0 {
|
||||
if let Some(rel) = text[b_start..b_end].find(' ') {
|
||||
let candidate = b_start + rel + 1;
|
||||
@@ -496,8 +485,8 @@ fn split_utf16_highlights_mode(
|
||||
let mut byte_spans: Vec<(usize, usize)> = spans
|
||||
.iter()
|
||||
.map(|&(u_start, u_end)| {
|
||||
let mut b_start = utf16_to_byte_offset(text, u_start);
|
||||
let mut b_end = utf16_to_byte_offset(text, u_end).max(b_start);
|
||||
let mut b_start = utf16_to_byte(text, u_start);
|
||||
let mut b_end = utf16_to_byte(text, u_end).max(b_start);
|
||||
if expand_to_word_boundaries && b_end > b_start {
|
||||
b_start = text[..b_start]
|
||||
.rfind(char::is_whitespace)
|
||||
|
||||
Reference in new issue
Block a user