feat(database): add title editing, view menus, and table commands

This commit is contained in:
DarkSky committed 2026-12-05 01:20:23 +09:00
1 parent f8e5ff6ea1
commit 4ed954fb1d
30 files changed
+3503 -713

No files matched your search

@@ -11,11 +11,15 @@ use blocksuite_playground_doc::{
use crate::block_flow::FlowRect;
pub(super) use super::authoring_hits::{DatabaseAuthoringHit, DatabaseAuthoringHitKind};
use super::{
DatabaseFlowState,
authoring_dispatch::handle_authoring_hit,
cell_editor::{ParsedCellInput, next_editable_cell, next_tag_color, parse_cell_draft},
column_ops, eval_database_filter_with_titles, sort_database_rows_with_titles,
column_ops, eval_database_filter_with_titles,
filter_sort_bar::FilterDraftState,
sort_database_rows_with_titles,
};
/// Block-local anchor rectangle for an open floating database popover, translated into screen
@@ -76,24 +80,6 @@ pub enum ActiveToolbarPanel {
AddGroup,
}
/// Transient draft rule inside the Filter panel before clicking Apply.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct FilterDraftState {
pub column_id: String,
pub function: String,
pub value: String,
}
impl Default for FilterDraftState {
fn default() -> Self {
Self {
column_id: String::new(),
function: "is".to_string(),
value: String::new(),
}
}
}
/// Active Calendar cross-day event reschedule drag preview.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct CalendarDragState {
@@ -113,6 +99,9 @@ pub struct KanbanDragState {
/// All transient authoring UI state for one `affine:database` block.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct DatabaseAuthoringState {
pub number_format_open: bool,
pub title_editing: bool,
pub view_menu: Option<super::ViewMenuState>,
pub column_menu: Option<ColumnMenuState>,
pub row_menu: Option<super::RowMenuState>,
pub lane_menu: Option<super::LaneMenuState>,
@@ -126,6 +115,7 @@ pub struct DatabaseAuthoringState {
pub toolbar_scroll_y: f32,
pub toolbar_panel: Option<ActiveToolbarPanel>,
pub filter_draft: FilterDraftState,
pub(super) pending_filter: Option<serde_json::Value>,
pub calendar_drag: Option<CalendarDragState>,
pub calendar_resize_end: Option<bool>,
pub kanban_drag: Option<KanbanDragState>,
@@ -139,6 +129,9 @@ pub struct DatabaseAuthoringState {
impl DatabaseAuthoringState {
pub fn dismiss_popovers(&mut self) {
self.number_format_open = false;
self.title_editing = false;
self.view_menu = None;
self.column_menu = None;
self.row_menu = None;
self.lane_menu = None;
@@ -147,200 +140,13 @@ impl DatabaseAuthoringState {
self.select_scroll_y = 0.0;
self.toolbar_scroll_y = 0.0;
self.toolbar_panel = None;
self.pending_filter = None;
self.date_picker_month = None;
self.calc_menu = None;
self.group_name_draft.clear();
}
}
/// Interactive authoring hit target emitted by Table / Kanban / Calendar renderers.
#[derive(Clone, Debug, PartialEq)]
pub enum DatabaseAuthoringHitKind {
AddColumn,
CreateProperty {
column_type: String,
},
OpenColumnMenu {
column_id: String,
},
ResizeColumnHandle {
column_id: String,
current_width_px: i32,
},
ColumnMenuRenameInput,
ColumnMenuToggleTypeSubmenu,
ColumnMenuSelectType {
column_id: String,
target_type: String,
},
ColumnMenuInsertLeft {
column_id: String,
},
ColumnMenuInsertRight {
column_id: String,
},
ColumnMenuMoveLeft {
column_id: String,
},
ColumnMenuMoveRight {
column_id: String,
},
ColumnMenuHide {
column_id: String,
},
ColumnMenuDelete {
column_id: String,
},
EditCell {
row_id: String,
column_id: String,
col_type: String,
},
SetProgress {
row_id: String,
column_id: String,
},
SelectToggleOption {
row_id: String,
column_id: String,
option_id: String,
},
SelectCreateOption {
row_id: String,
column_id: String,
label: String,
color: String,
},
SelectOptionMenu {
option_id: String,
},
SelectSaveOption {
color: Option<String>,
},
SelectDeleteOption {
column_id: String,
option_id: String,
},
ToolbarToggleFilter,
ToolbarToggleSort,
ToolbarToggleGroupBy,
ToolbarRemoveFilter {
index: usize,
},
ToolbarToggleSortDir {
index: usize,
},
ToolbarRemoveSort {
index: usize,
},
ToolbarAddOrFlipSort {
column_id: String,
},
ToolbarSetGroupBy {
column_id: Option<String>,
},
FilterDraftCycleColumn,
FilterDraftCycleOp,
FilterDraftToggleOption {
option_id: String,
},
FilterDraftApply,
KanbanAddRowInGroup {
column_id: String,
seed_value: Option<blocksuite_playground_doc::schema::DatabaseCellSpec>,
},
KanbanCardDragRegion {
row_id: String,
column_id: String,
origin_bucket_key: String,
},
KanbanLaneDropTarget {
column_id: String,
bucket_key: String,
seed_value: Option<blocksuite_playground_doc::schema::DatabaseCellSpec>,
},
CalendarAddRowOnDay {
day_index: i64,
},
CalendarDragEventStart {
row_id: String,
day_index: i64,
},
CalendarDayDropTarget {
day_index: i64,
},
SwitchView {
view_id: String,
},
AddView,
CreateView {
mode: blocksuite_playground_doc::read::DatabaseViewMode,
},
ToolbarProperties,
SetColumnHidden {
column_id: String,
hidden: bool,
},
ReorderProperty {
column_id: String,
to_index: usize,
},
OpenRowPeek {
row_id: String,
},
OpenRowMenu {
row_id: String,
is_kanban: bool,
},
RowMenuInsertAbove {
row_id: String,
},
RowMenuInsertBelow {
row_id: String,
},
RowMenuDuplicate {
row_id: String,
},
RowMenuDelete {
row_id: String,
},
OpenLinkUrl {
url: String,
},
KanbanAddRowAtStart {
column_id: String,
seed_value: Option<blocksuite_playground_doc::schema::DatabaseCellSpec>,
},
KanbanLaneMenu {
column_id: String,
bucket_key: String,
},
KanbanLaneMenuAddCard {
column_id: String,
bucket_key: String,
},
KanbanLaneCards {
column_id: String,
bucket_key: String,
rows: Vec<String>,
delete: bool,
},
CalendarResizeEvent {
row_id: String,
day_index: i64,
is_end: bool,
},
View(super::DatabaseViewAction),
}
/// One positioned authoring hit target in block-local coordinates.
#[derive(Clone, Debug, PartialEq)]
pub struct DatabaseAuthoringHit {
pub rect: FlowRect,
pub kind: DatabaseAuthoringHitKind,
pub scrolls_x: bool,
}
/// Keyboard input routed to an active database authoring target.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DatabaseAuthoringKey {
@@ -365,11 +171,7 @@ pub(super) fn resolve_active_view<'a>(
block_id: &str,
) -> Option<&'a DatabaseView> {
let ui_state = flow_state.state_for(block_id);
ui_state
.active_view_id
.as_deref()
.and_then(|id| data.views.iter().find(|v| v.id == id))
.or_else(|| data.views.first())
super::view_tabs::active_render_view(data, ui_state.active_view_id.as_deref())
}
/// Handle a keyboard event while a database column menu, in-place cell editor, or filter panel
@@ -701,7 +503,9 @@ pub fn handle_authoring_key(
if flow_state.state_for(block_id).authoring.toolbar_panel == Some(ActiveToolbarPanel::Filter) {
match key {
DatabaseAuthoringKey::Escape => {
flow_state.authoring_mut(block_id).toolbar_panel = None;
let auth = flow_state.authoring_mut(block_id);
auth.toolbar_panel = None;
auth.pending_filter = None;
return Ok(AuthoringActionResult {
handled: true,
doc_mutated: false,
@@ -11,16 +11,16 @@ use super::{
DatabaseFlowState,
authoring::{
ActiveCellEditor, ActiveToolbarPanel, AuthoringActionResult, CalendarDragState,
ColumnMenuState, DatabaseAuthoringHit, DatabaseAuthoringHitKind, resolve_active_view,
DatabaseAuthoringHit, DatabaseAuthoringHitKind, resolve_active_view,
},
authoring_id::fresh_database_id,
calendar_edit::{create_calendar_row_on_day, reschedule_calendar_row_to_day},
cell_editor::{is_editable_column_type, progress_from_bar_x},
column_ops::{insert_column_relative, make_new_column_spec, resolve_visible_columns},
filter_sort_bar::{
FilterRuleItem, append_filter_rule_json, build_group_by_for_column,
default_operator_for_column_type, operators_for_column_type, remove_filter_condition_json,
remove_sort_rule_json, toggle_sort_rule_dir_json, upsert_sort_rule_json,
build_group_by_for_column, default_operator_for_column_type, operators_for_column_type,
remove_filter_condition_json, remove_sort_rule_json, toggle_sort_rule_dir_json,
upsert_sort_rule_json,
},
};
@@ -42,6 +42,16 @@ pub fn handle_authoring_hit(
doc_mutated: false,
});
}
if hit.kind == DatabaseAuthoringHitKind::EditDatabaseTitle {
flow_state.clear_table_focus(block_id);
let auth = flow_state.authoring_mut(block_id);
auth.dismiss_popovers();
auth.title_editing = true;
return Ok(AuthoringActionResult {
handled: true,
doc_mutated: false,
});
}
let Some(view) = resolve_active_view(data, flow_state, block_id).cloned() else {
return Ok(AuthoringActionResult {
handled: false,
@@ -50,6 +60,17 @@ pub fn handle_authoring_hit(
};
match &hit.kind {
DatabaseAuthoringHitKind::OpenViewMenu { view_id } => Ok(super::view_tabs::open_view_menu(
flow_state, block_id, data, view_id,
)),
DatabaseAuthoringHitKind::ViewMenu(action) => {
super::view_tabs::handle_view_menu(page, flow_state, block_id, data, action, now_ms)
}
DatabaseAuthoringHitKind::ColumnAction(action) => {
super::column_actions::handle_column_action(
page, flow_state, block_id, data, &view, action, now_ms,
)
}
DatabaseAuthoringHitKind::AddColumn | DatabaseAuthoringHitKind::CreateProperty { .. } => {
let column_type = match &hit.kind {
DatabaseAuthoringHitKind::CreateProperty { column_type } => column_type.as_str(),
@@ -65,35 +86,13 @@ pub fn handle_authoring_hit(
doc_mutated: commit.is_some(),
})
}
DatabaseAuthoringHitKind::OpenColumnMenu { column_id } => {
let col_name = data
.columns
.iter()
.find(|c| c.id == *column_id)
.map(|c| c.name.clone())
.unwrap_or_else(|| "Title".to_string());
let auth = flow_state.authoring_mut(block_id);
if auth
.column_menu
.as_ref()
.is_some_and(|m| m.column_id == *column_id)
{
auth.column_menu = None;
} else {
auth.dismiss_popovers();
auth.column_menu = Some(ColumnMenuState {
column_id: column_id.clone(),
rename_draft: col_name,
type_submenu_open: false,
});
}
Ok(AuthoringActionResult {
handled: true,
doc_mutated: false,
})
}
DatabaseAuthoringHitKind::OpenColumnMenu { column_id } => Ok(
super::column_actions::open_column_menu(flow_state, block_id, data, column_id),
),
DatabaseAuthoringHitKind::ColumnMenuToggleTypeSubmenu => {
if let Some(menu) = flow_state.authoring_mut(block_id).column_menu.as_mut() {
let auth = flow_state.authoring_mut(block_id);
auth.number_format_open = false;
if let Some(menu) = auth.column_menu.as_mut() {
menu.type_submenu_open = !menu.type_submenu_open;
}
Ok(AuthoringActionResult {
@@ -392,6 +391,7 @@ pub fn handle_authoring_hit(
let auth = flow_state.authoring_mut(block_id);
if auth.toolbar_panel == Some(ActiveToolbarPanel::Filter) {
auth.toolbar_panel = None;
auth.pending_filter = None;
} else {
auth.dismiss_popovers();
auth.toolbar_panel = Some(ActiveToolbarPanel::Filter);
@@ -504,49 +504,15 @@ pub fn handle_authoring_hit(
doc_mutated: false,
})
}
DatabaseAuthoringHitKind::FilterDraftApply => {
let draft = flow_state.authoring_mut(block_id).filter_draft.clone();
let col_id = if draft.column_id.is_empty() {
data.columns
.first()
.map(|c| c.id.clone())
.unwrap_or_else(|| "title".to_string())
} else {
draft.column_id
};
let col_type = data
.columns
.iter()
.find(|c| c.id == col_id)
.map_or("title", |c| c.column_type.as_str());
let norm_op =
super::normalize_operator_for_column_type(col_type, &draft.function, &draft.value);
if !super::filter_op_takes_no_arg(&norm_op) && draft.value.trim().is_empty() {
flow_state.authoring_mut(block_id).toolbar_panel = None;
return Ok(AuthoringActionResult {
handled: true,
doc_mutated: false,
});
}
let json = append_filter_rule_json(
view.filter.as_ref(),
&FilterRuleItem {
column_id: col_id,
function: draft.function,
value: draft.value,
},
&data.columns,
offset_at_ms,
);
let commit = page.set_database_view_filter(block_id, &view.id, Some(json), now_ms)?;
let auth = flow_state.authoring_mut(block_id);
auth.filter_draft.value.clear();
auth.toolbar_panel = None;
Ok(AuthoringActionResult {
handled: true,
doc_mutated: commit.is_some(),
})
}
DatabaseAuthoringHitKind::FilterDraftApply => super::filter_actions::apply_filter_draft(
page,
flow_state.authoring_mut(block_id),
block_id,
data,
&view,
offset_at_ms,
now_ms,
),
DatabaseAuthoringHitKind::ToolbarRemoveFilter { index } => {
if let Some(json) = remove_filter_condition_json(view.filter.as_ref(), *index) {
let commit =
@@ -764,7 +730,8 @@ pub fn handle_authoring_hit(
offset_at_ms,
now_ms,
),
DatabaseAuthoringHitKind::ColumnMenuRenameInput
DatabaseAuthoringHitKind::EditDatabaseTitle
| DatabaseAuthoringHitKind::ColumnMenuRenameInput
| DatabaseAuthoringHitKind::ResizeColumnHandle { .. }
| DatabaseAuthoringHitKind::OpenRowPeek { .. }
| DatabaseAuthoringHitKind::OpenLinkUrl { .. }
@@ -0,0 +1,195 @@
use crate::block_flow::FlowRect;
/// Interactive authoring hit target emitted by Table / Kanban / Calendar renderers.
#[derive(Clone, Debug, PartialEq)]
pub enum DatabaseAuthoringHitKind {
EditDatabaseTitle,
OpenViewMenu {
view_id: String,
},
ViewMenu(super::ViewMenuAction),
ColumnAction(super::ColumnAction),
AddColumn,
CreateProperty {
column_type: String,
},
OpenColumnMenu {
column_id: String,
},
ResizeColumnHandle {
column_id: String,
current_width_px: i32,
},
ColumnMenuRenameInput,
ColumnMenuToggleTypeSubmenu,
ColumnMenuSelectType {
column_id: String,
target_type: String,
},
ColumnMenuInsertLeft {
column_id: String,
},
ColumnMenuInsertRight {
column_id: String,
},
ColumnMenuMoveLeft {
column_id: String,
},
ColumnMenuMoveRight {
column_id: String,
},
ColumnMenuHide {
column_id: String,
},
ColumnMenuDelete {
column_id: String,
},
EditCell {
row_id: String,
column_id: String,
col_type: String,
},
SetProgress {
row_id: String,
column_id: String,
},
SelectToggleOption {
row_id: String,
column_id: String,
option_id: String,
},
SelectCreateOption {
row_id: String,
column_id: String,
label: String,
color: String,
},
SelectOptionMenu {
option_id: String,
},
SelectSaveOption {
color: Option<String>,
},
SelectDeleteOption {
column_id: String,
option_id: String,
},
ToolbarToggleFilter,
ToolbarToggleSort,
ToolbarToggleGroupBy,
ToolbarRemoveFilter {
index: usize,
},
ToolbarToggleSortDir {
index: usize,
},
ToolbarRemoveSort {
index: usize,
},
ToolbarAddOrFlipSort {
column_id: String,
},
ToolbarSetGroupBy {
column_id: Option<String>,
},
FilterDraftCycleColumn,
FilterDraftCycleOp,
FilterDraftToggleOption {
option_id: String,
},
FilterDraftApply,
KanbanAddRowInGroup {
column_id: String,
seed_value: Option<blocksuite_playground_doc::schema::DatabaseCellSpec>,
},
KanbanCardDragRegion {
row_id: String,
column_id: String,
origin_bucket_key: String,
},
KanbanLaneDropTarget {
column_id: String,
bucket_key: String,
seed_value: Option<blocksuite_playground_doc::schema::DatabaseCellSpec>,
},
CalendarAddRowOnDay {
day_index: i64,
},
CalendarDragEventStart {
row_id: String,
day_index: i64,
},
CalendarDayDropTarget {
day_index: i64,
},
SwitchView {
view_id: String,
},
AddView,
CreateView {
mode: blocksuite_playground_doc::read::DatabaseViewMode,
},
ToolbarProperties,
SetColumnHidden {
column_id: String,
hidden: bool,
},
ReorderProperty {
column_id: String,
to_index: usize,
},
OpenRowPeek {
row_id: String,
},
OpenRowMenu {
row_id: String,
is_kanban: bool,
},
RowMenuInsertAbove {
row_id: String,
},
RowMenuInsertBelow {
row_id: String,
},
RowMenuDuplicate {
row_id: String,
},
RowMenuDelete {
row_id: String,
},
OpenLinkUrl {
url: String,
},
KanbanAddRowAtStart {
column_id: String,
seed_value: Option<blocksuite_playground_doc::schema::DatabaseCellSpec>,
},
KanbanLaneMenu {
column_id: String,
bucket_key: String,
},
KanbanLaneMenuAddCard {
column_id: String,
bucket_key: String,
},
KanbanLaneCards {
column_id: String,
bucket_key: String,
rows: Vec<String>,
delete: bool,
},
CalendarResizeEvent {
row_id: String,
day_index: i64,
is_end: bool,
},
View(super::DatabaseViewAction),
}
/// One positioned authoring hit target in block-local coordinates.
#[derive(Clone, Debug, PartialEq)]
pub struct DatabaseAuthoringHit {
pub rect: FlowRect,
pub kind: DatabaseAuthoringHitKind,
pub scrolls_x: bool,
}
@@ -0,0 +1,335 @@
use blocksuite_playground_doc::{
DocResult,
read::{DatabaseColumn, DatabaseData, DatabaseView},
schema::{DatabaseCellSpec, DatabaseColumnSpec, json_to_session_value},
session::PageDocSession,
};
use serde_json::{Value, json};
use y_octo::{Any, SessionReadValue, SessionValue, TypePath, TypeTarget};
use super::{
ActiveToolbarPanel, AuthoringActionResult, ColumnMenuState, DatabaseFlowState,
FilterDraftState,
authoring_id::fresh_database_id,
column_ops::resolve_visible_columns,
filter_sort_bar::default_operator_for_column_type,
wire_entries::{copy_value, database_field, field, find_entry, set_entry_field},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NumberFormat {
Number,
WithCommas,
Percent,
Currency,
}
impl NumberFormat {
pub(super) const ALL: [(Self, &str, &str); 4] = [
(Self::Number, "Number", "#"),
(Self::WithCommas, "With Commas", "#"),
(Self::Percent, "Percent", "%"),
(Self::Currency, "Currency", "$"),
];
pub(super) fn wire(self) -> &'static str {
match self {
Self::Number => "number",
Self::WithCommas => "numberWithCommas",
Self::Percent => "percent",
Self::Currency => "currencyUSD",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ColumnAction {
ToggleNumberFormat,
SetNumberFormat(NumberFormat),
Duplicate,
Filter,
Sort { descending: bool },
}
fn set_number_format(
page: &mut PageDocSession,
block_id: &str,
column: &DatabaseColumn,
format: NumberFormat,
now_ms: u64,
) -> DocResult<bool> {
let format = format.wire();
if column
.data
.get("format")
.and_then(Value::as_str)
.unwrap_or("number")
== format
{
return Ok(false);
}
page.structural_edit(now_ms, |page| {
let array = database_field(block_id, "prop:columns");
let entries = page.inner().read_array(&array)?;
let Some(i) = find_entry(page, &entries, &column.id)? else {
return Ok(());
};
let wire = Any::String(format.to_string());
match field(page, &entries[i], "data")? {
Some(SessionReadValue::Map(id)) => {
page.inner_mut().map_set(
&TypeTarget::Identity(id),
"format".to_string(),
SessionValue::Any(wire),
)?;
}
Some(SessionReadValue::Any(Any::Object(mut props))) => {
props.insert("format".to_string(), wire);
set_entry_field(
page,
&array,
i,
&entries[i],
"data",
SessionValue::Any(Any::Object(props)),
)?;
}
_ => {
let props = json!({ "format": format });
set_entry_field(
page,
&array,
i,
&entries[i],
"data",
json_to_session_value(&props),
)?;
}
}
Ok(())
})
.map(|commit| commit.is_some())
}
fn duplicate_column(
page: &mut PageDocSession,
block_id: &str,
data: &DatabaseData,
view: &DatabaseView,
column: &DatabaseColumn,
now_ms: u64,
) -> DocResult<bool> {
let id = fresh_database_id(page, data, "col");
let mut names = (1..).map(|i| format!("{}({i})", column.name));
let Some(name) = names.find(|name| data.columns.iter().all(|col| col.name != *name)) else {
return Ok(false);
};
let after = resolve_visible_columns(view, data)
.iter()
.position(|col| col.id == column.id)
.map(|i| i + 1);
let spec = DatabaseColumnSpec {
id: id.clone(),
column_type: column.column_type.clone(),
name,
data: column.data.clone(),
};
page.structural_edit(now_ms, |page| {
page.add_database_column(block_id, Some(&view.id), spec, after, now_ms)?;
let db_target = TypeTarget::Path(TypePath::root("blocks").key(block_id));
let Some(cells) = page.inner().get_map_value(&db_target, "prop:cells")? else {
return Ok(());
};
for row in &data.rows {
let Some(row_cells) = field(page, &cells, &row.row_id)? else {
continue;
};
let Some(cell) = field(page, &row_cells, &column.id)? else {
continue;
};
let mut copy = match copy_value(page, cell)? {
SessionValue::Map(fields) => fields,
SessionValue::Any(Any::Object(fields)) => fields
.into_iter()
.map(|(key, value)| (key, SessionValue::Any(value)))
.collect(),
_ => continue,
};
copy.retain(|(key, _)| key != "columnId");
copy.push((
"columnId".into(),
SessionValue::Any(Any::String(id.clone())),
));
let row_target = match row_cells {
SessionReadValue::Map(identity) => TypeTarget::Identity(identity),
_ => {
page.set_database_cell_value(
block_id,
&row.row_id,
&id,
DatabaseCellSpec::Null,
now_ms,
)?;
TypeTarget::Path(
TypePath::root("blocks")
.key(block_id)
.key("prop:cells")
.key(&row.row_id),
)
}
};
page.inner_mut()
.map_set(&row_target, id.clone(), SessionValue::Map(copy))?;
}
Ok(())
})
.map(|commit| commit.is_some())
}
fn set_sort(
page: &mut PageDocSession,
block_id: &str,
view: &DatabaseView,
column_id: &str,
descending: bool,
now_ms: u64,
) -> DocResult<bool> {
let mut sort = view
.sort
.as_ref()
.and_then(Value::as_object)
.cloned()
.unwrap_or_default();
let mut rules = sort
.remove("sortBy")
.and_then(|rules| rules.as_array().cloned())
.unwrap_or_default();
if let Some(existing) = rules
.iter_mut()
.find(|rule| rule["ref"]["name"] == column_id)
.and_then(Value::as_object_mut)
{
if existing
.get("desc")
.and_then(Value::as_bool)
.unwrap_or(false)
== descending
{
return Ok(false);
}
existing.insert("desc".into(), json!(descending));
} else {
rules.push(json!({ "ref": { "type": "ref", "name": column_id }, "desc": descending }));
}
sort.insert("sortBy".into(), Value::Array(rules));
page.set_database_view_sort(block_id, &view.id, Some(Value::Object(sort)), now_ms)
.map(|commit| commit.is_some())
}
pub(super) fn handle_column_action(
page: &mut PageDocSession,
flow: &mut DatabaseFlowState,
block_id: &str,
data: &DatabaseData,
view: &DatabaseView,
action: &ColumnAction,
now_ms: u64,
) -> DocResult<AuthoringActionResult> {
let auth = flow.authoring_mut(block_id);
let Some(menu) = &mut auth.column_menu else {
return Ok(AuthoringActionResult {
handled: false,
doc_mutated: false,
});
};
let column_id = menu.column_id.clone();
let column = data.columns.iter().find(|col| col.id == column_id);
let col_type = column.map_or("title", |col| col.column_type.as_str());
let changed = match *action {
ColumnAction::ToggleNumberFormat if col_type == "number" => {
auth.number_format_open = !auth.number_format_open;
menu.type_submenu_open = false;
false
}
ColumnAction::SetNumberFormat(format) if col_type == "number" => {
auth.dismiss_popovers();
if let Some(column) = column {
set_number_format(page, block_id, column, format, now_ms)?
} else {
false
}
}
ColumnAction::Duplicate if col_type != "title" => {
auth.dismiss_popovers();
if let Some(column) = column {
duplicate_column(page, block_id, data, view, column, now_ms)?
} else {
false
}
}
ColumnAction::Filter => {
auth.dismiss_popovers();
auth.toolbar_panel = Some(ActiveToolbarPanel::Filter);
let function = default_operator_for_column_type(col_type);
let condition = serde_json::json!({
"type": "filter",
"left": {"type": "ref", "name": column_id},
"function": function,
"args": [],
});
let filter = super::filter_sort_bar::insert_filter_condition(
view.filter.as_ref(),
condition.clone(),
true,
);
let commit = page.set_database_view_filter(block_id, &view.id, Some(filter), now_ms)?;
auth.pending_filter = Some(condition);
auth.filter_draft = FilterDraftState {
column_id,
function: function.into(),
value: String::new(),
};
commit.is_some()
}
ColumnAction::Sort { descending } => {
auth.dismiss_popovers();
set_sort(page, block_id, view, &column_id, descending, now_ms)?
}
_ => false,
};
Ok(AuthoringActionResult {
handled: true,
doc_mutated: changed,
})
}
pub(super) fn open_column_menu(
flow_state: &mut DatabaseFlowState,
block_id: &str,
data: &DatabaseData,
column_id: &str,
) -> AuthoringActionResult {
let col_name = data
.columns
.iter()
.find(|c| c.id == column_id)
.map(|c| c.name.clone())
.unwrap_or_else(|| "Title".to_string());
let auth = flow_state.authoring_mut(block_id);
let open = auth
.column_menu
.as_ref()
.is_none_or(|menu| menu.column_id != column_id);
auth.dismiss_popovers();
if open {
auth.column_menu = Some(ColumnMenuState {
column_id: column_id.to_string(),
rename_draft: col_name,
type_submenu_open: false,
});
}
AuthoringActionResult {
handled: true,
doc_mutated: false,
}
}
@@ -226,13 +226,13 @@ pub fn insert_column_relative(
}
fn column_menu_rows(
ctx: &DbRenderCtx<'_>,
data: &DatabaseData,
menu: &ColumnMenuState,
) -> (
bool,
Vec<(&'static str, &'static str, DatabaseAuthoringHitKind, bool)>,
) {
let col = ctx.data.columns.iter().find(|c| c.id == menu.column_id);
let col = data.columns.iter().find(|c| c.id == menu.column_id);
let is_title = col.is_some_and(|c| c.column_type == "title") || menu.column_id == "title";
let mut rows = Vec::new();
if !is_title {
@@ -243,6 +243,34 @@ fn column_menu_rows(
false,
));
}
if col.is_some_and(|col| col.column_type == "number") {
rows.push((
"NumberFormat",
"Number Format",
DatabaseAuthoringHitKind::ColumnAction(super::ColumnAction::ToggleNumberFormat),
false,
));
}
for (tag, label, action) in [
("Filter", "Filter", super::ColumnAction::Filter),
(
"SortAsc",
"Sort Ascending",
super::ColumnAction::Sort { descending: false },
),
(
"SortDesc",
"Sort Descending",
super::ColumnAction::Sort { descending: true },
),
] {
rows.push((
tag,
label,
DatabaseAuthoringHitKind::ColumnAction(action),
false,
));
}
rows.push((
"InsertLeft",
"Insert left",
@@ -284,6 +312,12 @@ fn column_menu_rows(
},
false,
));
rows.push((
"Duplicate",
"Duplicate",
DatabaseAuthoringHitKind::ColumnAction(super::ColumnAction::Duplicate),
false,
));
rows.push((
"Delete",
"Delete column",
@@ -296,17 +330,28 @@ fn column_menu_rows(
(is_title, rows)
}
/// Compute screen-space `(width, height)` of the column header action menu popover.
const COLUMN_MENU_ROW_HEIGHT: f32 = 28.0;
const COLUMN_MENU_FIXED_HEIGHT: f32 = 48.0;
fn column_menu_visible_rows(height: f32) -> usize {
((height - COLUMN_MENU_FIXED_HEIGHT).max(0.0) / COLUMN_MENU_ROW_HEIGHT).floor() as usize
}
pub(super) fn measure_column_menu_size(
ctx: &DbRenderCtx<'_>,
data: &DatabaseData,
menu: &ColumnMenuState,
viewport_height: f32,
) -> (f32, f32) {
let (_, rows) = column_menu_rows(ctx, menu);
let pad = 6.0_f32;
let input_h = 28.0_f32;
let row_h = 28.0_f32;
let menu_h = pad * 2.0 + input_h + 8.0 + rows.len() as f32 * row_h;
(216.0, menu_h)
let (_, rows) = column_menu_rows(data, menu);
let available = (viewport_height - 16.0).max(1.0);
let visible = rows.len().min(column_menu_visible_rows(available));
let height = COLUMN_MENU_FIXED_HEIGHT + visible as f32 * COLUMN_MENU_ROW_HEIGHT;
(216.0, height.min(available))
}
pub fn column_menu_scroll_limit(data: &DatabaseData, menu: &ColumnMenuState, height: f32) -> f32 {
let (_, rows) = column_menu_rows(data, menu);
rows.len().saturating_sub(column_menu_visible_rows(height)) as f32 * COLUMN_MENU_ROW_HEIGHT
}
/// Render the column header action menu (and optional type-picker submenu) at `menu_rect` in
@@ -321,10 +366,10 @@ pub(super) fn render_column_menu_at(
) -> (FlowRect, Option<(FlowRect, usize)>) {
let col = ctx.data.columns.iter().find(|c| c.id == menu.column_id);
let current_type = col.map_or("rich-text", |c| c.column_type.as_str());
let (is_title, rows) = column_menu_rows(ctx, menu);
let (is_title, rows) = column_menu_rows(ctx.data, menu);
let pad = 6.0_f32;
let row_h = 28.0_f32;
let row_h = COLUMN_MENU_ROW_HEIGHT;
let input_h = 28.0_f32;
prims.push(DatabasePrim::Quad {
@@ -386,31 +431,40 @@ pub(super) fn render_column_menu_at(
});
let mut ry = div_y + 4.0;
let mut type_row_y = ry;
for (tag, label, hit_kind, is_danger) in rows {
let mut submenu_y = None;
let visible = column_menu_visible_rows(menu_rect.h);
let max_skip = rows.len().saturating_sub(visible);
let skip = (ctx.ui_state.authoring.toolbar_scroll_y / row_h).floor() as usize;
for (tag, label, hit_kind, is_danger) in rows.into_iter().skip(skip.min(max_skip)).take(visible)
{
let row_rect = FlowRect::new(
menu_rect.x + pad,
ry,
(menu_rect.w - 2.0 * pad).max(1.0),
row_h,
);
if tag == "ToggleTypeSubmenu" {
type_row_y = ry;
if menu.type_submenu_open {
prims.push(DatabasePrim::Quad {
rect: row_rect,
fill: Some(ctx.palette.hover),
border: None,
radius: 4.0,
dashed: false,
});
}
if (tag == "ToggleTypeSubmenu" && menu.type_submenu_open)
|| (tag == "NumberFormat" && ctx.ui_state.authoring.number_format_open)
{
submenu_y = Some(ry);
prims.push(DatabasePrim::Quad {
rect: row_rect,
fill: Some(ctx.palette.hover),
border: None,
radius: 4.0,
dashed: false,
});
}
let icon = match tag {
"ToggleTypeSubmenu" => IconPaint::named(column_icon_name(current_type)),
"InsertLeft" | "InsertRight" => IconPaint::from_def(&ui_tokens::icons::PLUS),
"MoveLeft" => IconPaint::from_def(&ui_tokens::icons::MOVE_LEFT),
"MoveRight" => IconPaint::from_def(&ui_tokens::icons::MOVE_RIGHT),
"Duplicate" => IconPaint::from_def(&ui_tokens::icons::DUPLICATE),
"NumberFormat" => IconPaint::named(column_icon_name("number")),
"Filter" => IconPaint::named("GroupingIcon"),
"SortAsc" => IconPaint::named("ArrowUpBigIcon"),
"SortDesc" => IconPaint::named("ArrowDownBigIcon"),
"Hide" => IconPaint::from_def(&ui_tokens::icons::INVISIBLE),
"Delete" => IconPaint::from_def(&ui_tokens::icons::DELETE),
_ => IconPaint::from_def(&ui_tokens::icons::SQUARE),
@@ -441,6 +495,17 @@ pub(super) fn render_column_menu_at(
row_h,
InlineAlign::Left,
));
if tag == "NumberFormat" {
prims.push(ctx.single_line_clipped(
"›",
InlineStyle::new(FONT_SANS, 14.0, 500.0, ctx.palette.text_secondary),
row_rect.right() - 14.0,
row_rect.y,
12.0,
row_h,
InlineAlign::Left,
));
}
if tag == "ToggleTypeSubmenu" {
let type_badge = format!("{} ›", column_type_label(current_type));
prims.push(ctx.single_line_clipped(
@@ -467,21 +532,62 @@ pub(super) fn render_column_menu_at(
}
let mut submenu_rect = None;
if menu.type_submenu_open && !is_title {
let format_open = current_type == "number" && ctx.ui_state.authoring.number_format_open;
if let Some(submenu_y) = submenu_y
&& (format_open || (menu.type_submenu_open && !is_title))
{
let sub_w = 164.0_f32;
let sub_types: Vec<(&str, &str)> = COLUMN_TYPES
.iter()
.copied()
.filter(|(id, _)| *id != "title")
.collect();
let sub_h = pad * 2.0 + sub_types.len() as f32 * 26.0;
let right_x = menu_rect.right() + 4.0;
let sub_x = if right_x + sub_w <= viewport.right() - 8.0 {
right_x
let items: Vec<_> = if format_open {
let selected = ctx
.data
.columns
.iter()
.find(|col| col.id == menu.column_id)
.and_then(|col| col.data.get("format"))
.and_then(serde_json::Value::as_str)
.unwrap_or("number");
super::NumberFormat::ALL
.into_iter()
.map(|(format, label, symbol)| {
(
label,
symbol,
format.wire() == selected,
DatabaseAuthoringHitKind::ColumnAction(
super::ColumnAction::SetNumberFormat(format),
),
)
})
.collect()
} else {
(menu_rect.x - sub_w - 4.0).max(viewport.x + 8.0)
COLUMN_TYPES
.iter()
.copied()
.filter(|(id, _)| *id != "title")
.map(|(type_id, label)| {
(
label,
column_icon_name(type_id),
type_id == current_type,
DatabaseAuthoringHitKind::ColumnMenuSelectType {
column_id: menu.column_id.clone(),
target_type: type_id.to_string(),
},
)
})
.collect()
};
let sub_y = (type_row_y - 2.0)
let sub_h = pad * 2.0 + items.len() as f32 * 26.0;
let right_x = menu_rect.right() + 4.0;
let left_x = menu_rect.x - sub_w - 4.0;
let (sub_x, sub_top) = if right_x + sub_w <= viewport.right() - 8.0 {
(right_x, submenu_y - 2.0)
} else if left_x >= viewport.x + 8.0 {
(left_x, submenu_y - 2.0)
} else {
(viewport.x + 8.0, menu_rect.bottom() - sub_h)
};
let sub_y = sub_top
.min((viewport.bottom() - 8.0 - sub_h).max(viewport.y + 8.0))
.max(viewport.y + 8.0);
let sub_rect = FlowRect::new(sub_x, sub_y, sub_w, sub_h);
@@ -494,8 +600,7 @@ pub(super) fn render_column_menu_at(
dashed: false,
});
let mut sy = sub_rect.y + pad;
for (type_id, type_label) in sub_types {
let active = type_id == current_type;
for (label, icon, active, kind) in items {
let item_rect = FlowRect::new(sub_rect.x + pad, sy, (sub_w - 2.0 * pad).max(1.0), 26.0);
if active {
prims.push(DatabasePrim::Quad {
@@ -506,17 +611,30 @@ pub(super) fn render_column_menu_at(
dashed: false,
});
}
prims.push(DatabasePrim::Icon {
rect: FlowRect::new(item_rect.x + 6.0, item_rect.y + 6.0, 14.0, 14.0),
icon: IconPaint::named(column_icon_name(type_id)),
color: if active {
ctx.palette.brand
} else {
ctx.palette.icon
},
});
let ink = if active {
ctx.palette.brand
} else {
ctx.palette.icon
};
if format_open {
prims.push(ctx.single_line_clipped(
icon,
InlineStyle::new(FONT_SANS, 14.0, 500.0, ink),
item_rect.x + 6.0,
item_rect.y,
16.0,
26.0,
InlineAlign::Left,
));
} else {
prims.push(DatabasePrim::Icon {
rect: FlowRect::new(item_rect.x + 6.0, item_rect.y + 6.0, 14.0, 14.0),
icon: IconPaint::named(icon),
color: ink,
});
}
prims.push(ctx.single_line_clipped(
type_label,
label,
InlineStyle::new(
FONT_SANS,
TYPOGRAPHY.font_xs_px + 1.0,
@@ -535,10 +653,7 @@ pub(super) fn render_column_menu_at(
));
hits.push(DatabaseAuthoringHit {
rect: item_rect,
kind: DatabaseAuthoringHitKind::ColumnMenuSelectType {
column_id: menu.column_id.clone(),
target_type: type_id.to_string(),
},
kind,
scrolls_x: false,
});
sy += 26.0;
@@ -69,11 +69,21 @@ pub fn database_authoring_hit_cursor(
CursorStyle::PointingHand
}
}
DatabaseAuthoringHitKind::ColumnMenuRenameInput => CursorStyle::IBeam,
DatabaseAuthoringHitKind::ColumnMenuRenameInput
| DatabaseAuthoringHitKind::EditDatabaseTitle => {
if readonly {
CursorStyle::Arrow
} else {
CursorStyle::IBeam
}
}
DatabaseAuthoringHitKind::OpenLinkUrl { .. }
| DatabaseAuthoringHitKind::OpenRowPeek { .. }
| DatabaseAuthoringHitKind::SwitchView { .. } => CursorStyle::PointingHand,
DatabaseAuthoringHitKind::AddColumn
DatabaseAuthoringHitKind::OpenViewMenu { .. }
| DatabaseAuthoringHitKind::ViewMenu(_)
| DatabaseAuthoringHitKind::ColumnAction(_)
| DatabaseAuthoringHitKind::AddColumn
| DatabaseAuthoringHitKind::View(_)
| DatabaseAuthoringHitKind::CreateProperty { .. }
| DatabaseAuthoringHitKind::ToolbarProperties
@@ -0,0 +1,76 @@
use blocksuite_playground_doc::{
DocResult,
read::{DatabaseData, DatabaseView},
session::PageDocSession,
};
use super::{
authoring::{AuthoringActionResult, DatabaseAuthoringState},
filter_sort_bar::{
FilterRuleItem, append_filter_rule_json, filter_op_takes_no_arg,
normalize_operator_for_column_type, rule_to_condition_json,
},
};
pub(super) fn apply_filter_draft(
page: &mut PageDocSession,
auth: &mut DatabaseAuthoringState,
block_id: &str,
data: &DatabaseData,
view: &DatabaseView,
offset_at_ms: &dyn Fn(i64) -> i32,
now_ms: u64,
) -> DocResult<AuthoringActionResult> {
let draft = &auth.filter_draft;
let column_id = if draft.column_id.is_empty() {
data.columns
.first()
.map_or("title", |column| column.id.as_str())
} else {
&draft.column_id
};
let col_type = data
.columns
.iter()
.find(|column| column.id == column_id)
.map_or("title", |column| column.column_type.as_str());
let operator = normalize_operator_for_column_type(col_type, &draft.function, &draft.value);
let pending = auth.pending_filter.take();
auth.toolbar_panel = None;
let mut doc_mutated = false;
if filter_op_takes_no_arg(&operator) || !draft.value.trim().is_empty() {
let rule = FilterRuleItem {
column_id: column_id.to_string(),
function: draft.function.clone(),
value: draft.value.clone(),
};
let mut filter = view.filter.clone();
let first = filter
.as_mut()
.and_then(|filter| filter.get_mut("conditions"))
.and_then(serde_json::Value::as_array_mut)
.and_then(|conditions| conditions.first_mut());
if let (Some(first), Some(pending)) = (first, pending)
&& *first == pending
{
*first = rule_to_condition_json(&rule, &data.columns, offset_at_ms);
} else {
filter = Some(append_filter_rule_json(
view.filter.as_ref(),
&rule,
&data.columns,
offset_at_ms,
));
}
if filter != view.filter {
doc_mutated = page
.set_database_view_filter(block_id, &view.id, filter, now_ms)?
.is_some();
}
auth.filter_draft.value.clear();
}
Ok(AuthoringActionResult {
handled: true,
doc_mutated,
})
}
@@ -347,7 +347,18 @@ pub fn append_filter_rule_json(
columns: &[DatabaseColumn],
offset_at_ms: &dyn Fn(i64) -> i32,
) -> JsonValue {
let new_cond = rule_to_condition_json(rule, columns, offset_at_ms);
insert_filter_condition(
existing,
rule_to_condition_json(rule, columns, offset_at_ms),
false,
)
}
pub(in crate::database) fn insert_filter_condition(
existing: Option<&JsonValue>,
new_cond: JsonValue,
prepend: bool,
) -> JsonValue {
if let Some(JsonValue::Object(map)) = existing {
let op = map.get("op").and_then(JsonValue::as_str).unwrap_or("and");
let existing_conds = map
@@ -365,15 +376,22 @@ pub fn append_filter_rule_json(
return JsonValue::Object(next);
}
if op == "or" {
let group = JsonValue::Object(map.clone());
let conditions = if prepend {
[new_cond, group]
} else {
[group, new_cond]
};
return json!({
"type": "group",
"op": "and",
"conditions": [JsonValue::Object(map.clone()), new_cond],
"conditions": conditions,
});
}
let mut next = map.clone();
let mut conds = existing_conds;
conds.push(new_cond);
let index = if prepend { 0 } else { conds.len() };
conds.insert(index, new_cond);
next.insert("conditions".to_string(), JsonValue::Array(conds));
return JsonValue::Object(next);
}
@@ -20,6 +20,7 @@ use super::{
resolve_tag_color,
};
pub(super) use json_ops::insert_filter_condition;
use json_ops::parse_filter_chips;
pub use json_ops::{
FilterRuleItem, SortRuleItem, append_filter_rule_json, build_group_by_for_column,
@@ -30,6 +31,24 @@ pub use json_ops::{
};
use panels::{column_name_for, toolbar_buttons};
/// Transient draft rule inside the Filter panel before clicking Apply.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct FilterDraftState {
pub column_id: String,
pub function: String,
pub value: String,
}
impl Default for FilterDraftState {
fn default() -> Self {
Self {
column_id: String::new(),
function: "is".to_string(),
value: String::new(),
}
}
}
/// Render right-aligned borderless `Filter` / `Sort` / `Group by` triggers on the same horizontal
/// toolbar row as the desktop view-switcher tabs (`databaseToolbarRowStyles`).
///
+23 -9
View File
@@ -5,14 +5,18 @@
mod add_group;
mod authoring;
mod authoring_dispatch;
mod authoring_hits;
mod authoring_id;
mod calculate;
mod calendar;
mod calendar_edit;
mod cell_editor;
mod column_actions;
mod column_ops;
pub use column_actions::{ColumnAction, NumberFormat};
mod cursor;
mod date_picker;
mod filter_actions;
mod filter_sort_bar;
mod format;
mod group;
@@ -30,9 +34,16 @@ mod search;
mod select_popover;
mod sort_key;
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};
mod view_action;
mod view_config;
mod view_tabs;
mod wire_entries;
pub use column_ops::column_menu_scroll_limit;
pub use view_tabs::{ViewMenuAction, ViewMenuState, rename_view};
use std::collections::{BTreeSet, HashMap};
@@ -40,11 +51,12 @@ use crate::block_flow::FlowRect;
pub use authoring::{
ActiveCellEditor, ActiveToolbarPanel, AuthoringActionResult, CalendarDragState,
ColumnMenuState, ColumnResizePreview, DatabaseAuthoringHit, DatabaseAuthoringHitKind,
DatabaseAuthoringKey, DatabaseAuthoringState, DatabasePopoverAnchor, FilterDraftState,
KanbanDragState, ProgressScrubPreview, commit_column_resize, handle_authoring_key,
ColumnMenuState, ColumnResizePreview, DatabaseAuthoringKey, DatabaseAuthoringState,
DatabasePopoverAnchor, KanbanDragState, ProgressScrubPreview, commit_column_resize,
handle_authoring_key,
};
pub use authoring_dispatch::handle_authoring_hit;
pub use authoring_hits::{DatabaseAuthoringHit, DatabaseAuthoringHitKind};
pub use calculate::{STAT_CALC_TYPES, compute_stat, stat_calc_label};
pub use calendar::{
CalendarDayLayout, CalendarEntry, CalendarMonthLayout, CalendarRangeSegment,
@@ -66,11 +78,11 @@ pub use column_ops::{
};
pub use cursor::{database_authoring_hit_cursor, database_hit_cursor};
pub use filter_sort_bar::{
FilterRuleItem, SortRuleItem, append_filter_rule_json, build_group_by_for_column,
default_operator_for_column_type, filter_op_label, filter_op_takes_no_arg,
normalize_operator_for_column_type, operators_for_column_type, panel_row_count,
parse_sort_rules, remove_filter_condition_json, remove_sort_rule_json, rule_to_condition_json,
toggle_sort_rule_dir_json, upsert_sort_rule_json,
FilterDraftState, FilterRuleItem, SortRuleItem, append_filter_rule_json,
build_group_by_for_column, default_operator_for_column_type, filter_op_label,
filter_op_takes_no_arg, normalize_operator_for_column_type, operators_for_column_type,
panel_row_count, parse_sort_rules, remove_filter_condition_json, remove_sort_rule_json,
rule_to_condition_json, toggle_sort_rule_dir_json, upsert_sort_rule_json,
};
pub use format::{
BidiIsolation, column_icon_name, format_database_created_time, format_database_date,
@@ -88,7 +100,7 @@ pub use row_ops::{LaneMenuState, RowMenuState, resize_calendar_event_day};
pub use search::row_matches_search;
pub use select_popover::{SELECT_POPOVER_MAX_HEIGHT, select_popover_max_scroll};
pub use table_selection::{
DatabaseNavKey, ROW_SELECT_GUTTER_W, delete_rows, handle_navigation_key,
CellRange, DatabaseNavKey, ROW_SELECT_GUTTER_W, delete_rows, handle_navigation_key,
};
pub use view_action::{DatabaseViewAction, handle_view_popover_key};
pub use view_config::set_database_view_stat_calc;
@@ -185,6 +197,7 @@ pub struct DatabaseUiState {
/// Group of [`Self::focused_cell`] in a grouped Table, where a multi-select row shows in
/// each group of its tags. `None` stands for the first group that shows the row.
pub focused_group: Option<String>,
pub cell_range: Option<table_selection::CellRange>,
/// Live search query of the toolbar `Search` field. It filters the visible rows only.
pub search_query: String,
/// Transient desktop/writable authoring state (column menu, in-place cell editor, toolbar
@@ -260,6 +273,7 @@ impl DatabaseFlowState {
entry.reveal_active_tab = true;
entry.selected_rows.clear();
entry.focused_cell = None;
entry.cell_range = None;
entry.focused_group = None;
entry.search_query.clear();
}
@@ -102,7 +102,8 @@ pub fn layout_database_popover_overlay(
.as_ref()
.is_some_and(|e| matches!(e.col_type.as_str(), "select" | "multi-select" | "date"));
let has_writable_popover = !mobile_readonly
&& (auth.column_menu.is_some()
&& (auth.view_menu.is_some()
|| auth.column_menu.is_some()
|| auth.row_menu.is_some()
|| auth.lane_menu.is_some()
|| auth.calc_menu.is_some()
@@ -190,9 +191,13 @@ pub fn layout_database_popover_overlay(
};
let (bounds, submenu_bounds, text_input_rect) = if !mobile_readonly
&& let Some(menu) = &auth.column_menu
&& let Some(menu) = &auth.view_menu
{
let size = column_ops::measure_column_menu_size(&ctx, menu);
let bounds = place(super::view_tabs::measure_view_menu(data, menu));
let input = super::view_tabs::render_view_menu(&ctx, menu, bounds, &mut prims, &mut hits);
(bounds, None, Some(input))
} else if !mobile_readonly && let Some(menu) = &auth.column_menu {
let size = column_ops::measure_column_menu_size(data, menu, viewport.h);
let placed = place_popover(
anchor_screen,
size,
+76 -69
View File
@@ -16,9 +16,10 @@ pub(super) use super::render_types::DbRenderCtx;
pub use super::render_types::{DatabaseLayoutOutput, DatabasePrim};
use super::view_tabs::{partition_desktop_view_tabs, tab_label_for};
use super::{
DatabaseHitKind, DatabaseHitTarget, DatabasePopoverAnchor, DatabaseUiState, InlineAxis,
MOBILE_DATABASE_READONLY_NOTICE, filter_search_and_sort_view_rows, filter_sort_bar,
render_calendar, render_kanban, render_table, render_table_parts, table_selection,
DatabaseAuthoringHit, DatabaseAuthoringHitKind, DatabaseHitKind, DatabaseHitTarget,
DatabasePopoverAnchor, DatabaseUiState, InlineAxis, MOBILE_DATABASE_READONLY_NOTICE,
filter_search_and_sort_view_rows, filter_sort_bar, render_calendar, render_kanban,
render_table, render_table_parts, table_selection,
};
/// Lay out an `affine:database` block with its header, view-switcher tabs, optional mobile
@@ -42,64 +43,26 @@ pub fn layout_database_block(
let mut prims = Vec::new();
let mut hits = Vec::new();
// Resolve active view (fallback to first view, or synthesize a default Table view).
let fallback_view = DatabaseView {
id: "default-table".to_string(),
name: "Table View".to_string(),
mode: DatabaseViewMode::Table,
columns: Vec::new(),
filter: None,
sort: None,
group_by: None,
group_properties: Vec::new(),
header: None,
date: None,
card: None,
ui: None,
extra: Default::default(),
};
let active_view = ui_state
.active_view_id
.as_deref()
.and_then(|id| data.views.iter().find(|v| v.id == id))
.or_else(|| data.views.first())
.unwrap_or(&fallback_view);
// 1. Database title row (`databaseTitleRowStyles`).
let mut y = 8.0_f32;
let title_text = if data.title.plain.trim().is_empty() {
"Untitled Database"
} else {
data.title.plain.trim()
};
let title_style = InlineStyle::new(
FONT_SANS,
TYPOGRAPHY.font_base_px + 2.0,
600.0,
palette.text_primary,
);
let title_align = if direction.is_rtl() {
InlineAlign::Right
} else {
InlineAlign::Left
};
let title_layout = Rc::new(layout_inline(
title_text,
&title_style,
(width - 16.0).max(1.0),
26.0,
InlineBaseline::Of(&title_style),
title_align,
window,
));
prims.push(DatabasePrim::Text {
x: 8.0,
y,
layout: title_layout,
clip: Some(FlowRect::new(8.0, y, (width - 16.0).max(1.0), 26.0)),
});
y += 32.0;
let fallback_view = super::view_tabs::default_table_view();
let active_view =
super::view_tabs::active_render_view(data, ui_state.active_view_id.as_deref())
.unwrap_or(&fallback_view);
let title_rect = FlowRect::new(0.0, 8.0, width, 28.0);
let title_text = super::title::display_text(&data.title.plain);
let title_align = super::title::text_align(direction);
let title_editing = ui_state.authoring.title_editing && !mobile_readonly;
if !title_editing {
super::title::paint_title(
title_text,
title_rect,
title_align,
&palette,
window,
&mut prims,
);
}
let mut y = 40.0_f32;
// 2. View switcher tabs (single-row horizontal scroll on Phone/Tablet with fade hint;
// inline + `"N More"` overflow dropdown on Desktop). Zero CRDT writeback.
let views_to_show: Vec<&DatabaseView> = if data.views.is_empty() {
@@ -128,6 +91,7 @@ pub fn layout_database_block(
struct MeasuredTab<'a> {
view: &'a DatabaseView,
is_active: bool,
manage: bool,
w: f32,
layout: Rc<InlineLayout>,
}
@@ -168,6 +132,7 @@ pub fn layout_database_block(
InlineAlign::Left,
window,
);
let manage = is_active && !mobile_readonly && !data.views.is_empty();
let tab_w = (measured.content_width().ceil() + 34.0).clamp(64.0, max_tab_w);
let text_w = (tab_w - 34.0).max(1.0);
let layout = if measured.content_width() <= text_w + 0.25 {
@@ -178,6 +143,7 @@ pub fn layout_database_block(
measured_tabs.push(MeasuredTab {
view,
is_active,
manage,
w: tab_w,
layout,
});
@@ -208,16 +174,22 @@ pub fn layout_database_block(
dashed: false,
});
}
let (inset, icon_size) = if tab.manage { (3.0, 12.0) } else { (8.0, 14.0) };
let icon_x = if direction.is_rtl() {
visual_rect.right() - 22.0
visual_rect.right() - inset - icon_size
} else {
visual_rect.x + 8.0
visual_rect.x + inset
};
let icon_visible =
clip_strip.is_none_or(|c| icon_x >= c.x && icon_x + 14.0 <= c.right());
clip_strip.is_none_or(|c| icon_x >= c.x && icon_x + icon_size <= c.right());
if icon_visible {
prims.push(DatabasePrim::Icon {
rect: FlowRect::new(icon_x, visual_rect.y + (tab_h - 14.0) * 0.5, 14.0, 14.0),
rect: FlowRect::new(
icon_x,
visual_rect.y + (tab_h - icon_size) * 0.5,
icon_size,
icon_size,
),
icon: IconPaint::named(icon_for(&tab.view.mode)),
color: if tab.is_active {
palette.text_primary
@@ -226,12 +198,24 @@ pub fn layout_database_block(
},
});
}
let text_x = if direction.is_rtl() {
visual_rect.x + 8.0
let text_inset = if tab.manage {
17.0
} else if direction.is_rtl() {
8.0
} else {
visual_rect.x + 26.0
26.0
};
let text_x = visual_rect.x + text_inset;
let text_w = (visual_rect.w - 34.0).max(1.0);
if tab.manage {
super::view_tabs::render_more_icon(
visual_rect,
clip_strip,
direction,
palette.icon,
&mut prims,
);
}
let raw_clip = FlowRect::new(text_x, visual_rect.y, text_w, tab_h);
let text_clip = if let Some(clip) = clip_strip {
let cx0 = raw_clip.x.max(clip.x);
@@ -258,6 +242,13 @@ pub fn layout_database_block(
};
let mut authoring_hits = Vec::new();
if !mobile_readonly {
authoring_hits.push(DatabaseAuthoringHit {
rect: title_rect,
kind: DatabaseAuthoringHitKind::EditDatabaseTitle,
scrolls_x: false,
});
}
let mut inline_toolbar_anchor: Option<FlowRect> = None;
let mut more_views_anchor: Option<FlowRect> = None;
let mut wrap_toolbar_below = false;
@@ -611,7 +602,15 @@ pub fn layout_database_block(
hits.extend(view_hits);
authoring_hits.extend(view_auth_hits);
let popover_anchor = if ui_state.authoring.column_menu.is_some()
let active_tab = super::view_tabs::view_menu_trigger(
&hits,
active_view,
!mobile_readonly && !data.views.is_empty(),
&mut authoring_hits,
);
let popover_anchor = if ui_state.authoring.view_menu.is_some() {
active_tab
} else if ui_state.authoring.column_menu.is_some()
|| ui_state.authoring.row_menu.is_some()
|| ui_state.authoring.lane_menu.is_some()
|| ui_state.authoring.calc_menu.is_some()
@@ -759,7 +758,15 @@ pub fn layout_database_block(
hits,
authoring_hits,
popover_anchor,
active_cell,
active_cell: if title_editing {
Some(super::DatabaseActiveCellLayout {
rect: title_rect,
scrolls_x: false,
rich_hit: None,
})
} else {
active_cell
},
overflow_tabs,
view_tabs_scroll_px,
view_tabs_max_scroll_px,
@@ -233,6 +233,7 @@ pub(super) fn render_table_view(
&ordered_col_indices,
row,
focus_slot,
Some(bucket.key.as_str()),
start_x,
y,
&mut prims,
@@ -287,6 +288,7 @@ pub(super) fn render_table_view(
&ordered_col_indices,
row,
true,
None,
start_x,
y,
&mut prims,
@@ -380,6 +382,7 @@ fn render_table_row(
ordered_col_indices: &[usize],
row: &DatabaseRow,
focus_slot: bool,
group_key: Option<&str>,
start_x: f32,
y: f32,
prims: &mut Vec<DatabasePrim>,
@@ -755,9 +758,14 @@ fn render_table_row(
scrolls_x: true,
});
}
if focus_slot {
push_focus_outline(ctx, &row.row_id, &col.id, cell_rect, prims);
}
push_focus_outline(
ctx,
(&row.row_id, &col.id),
group_key,
focus_slot,
cell_rect,
prims,
);
cell_x += col.width;
}
if ctx.mobile_readonly {
@@ -250,21 +250,27 @@ pub(super) fn render_selection_bar(
/// Outline the focused cell `(row_id, column_id)` when no inline editor is open on it.
pub(super) fn push_focus_outline(
ctx: &DbRenderCtx<'_>,
row_id: &str,
column_id: &str,
(row_id, column_id): (&str, &str),
group_key: Option<&str>,
focus_slot: bool,
cell_rect: FlowRect,
prims: &mut Vec<DatabasePrim>,
) {
let focused = ctx
.ui_state
.focused_cell
.as_ref()
.is_some_and(|(r, c)| r == row_id && c == column_id);
if focused && ctx.ui_state.authoring.active_cell.is_none() && !ctx.mobile_readonly {
let focused = focus_slot
&& ctx
.ui_state
.focused_cell
.as_ref()
.is_some_and(|(r, c)| r == row_id && c == column_id);
let selected = ctx.ui_state.cell_range.as_ref().is_some_and(|range| {
range.columns.contains(column_id) && range.contains_row(group_key, row_id)
});
if (focused || selected) && ctx.ui_state.authoring.active_cell.is_none() && !ctx.mobile_readonly
{
prims.push(DatabasePrim::Quad {
rect: cell_rect,
fill: None,
border: Some(ctx.palette.brand),
fill: selected.then(|| ctx.palette.brand.opacity(0.16)),
border: focused.then_some(ctx.palette.brand),
radius: 0.0,
dashed: false,
});
@@ -0,0 +1,361 @@
use std::{
borrow::Cow,
collections::{BTreeMap, BTreeSet},
};
use blocksuite_playground_doc::{
DocResult,
read::{DatabaseCellValue, DatabaseData, DatabaseSelectOption},
schema::DatabaseCellSpec,
session::PageDocSession,
};
use serde::{Deserialize, Serialize};
use super::{
DatabaseFlowState, DatabaseUiState, ParsedCellInput, is_editable_column_type, parse_cell_draft,
resolve_initial_cell_draft,
table_selection::{RowSlot, focused_position, grid_position, table_grid},
};
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum TableClipboardCell {
Text(String),
Options {
ids: Vec<String>,
labels: Vec<String>,
},
}
impl TableClipboardCell {
pub fn plain_text(&self) -> Cow<'_, str> {
match self {
Self::Text(value) => Cow::Borrowed(value),
Self::Options { labels, .. } => Cow::Owned(labels.join(",")),
}
}
}
static EMPTY_CELL: TableClipboardCell = TableClipboardCell::Text(String::new());
fn selected_axes(
ui: &DatabaseUiState,
rows: &[RowSlot],
columns: &[(String, String)],
) -> Option<(Vec<usize>, Vec<usize>)> {
if let Some(range) = &ui.cell_range {
let row_indices = rows
.iter()
.enumerate()
.filter_map(|(i, (group, row))| range.contains_row(group.as_deref(), row).then_some(i))
.collect();
let column_indices = columns
.iter()
.enumerate()
.filter_map(|(i, (id, _))| range.columns.contains(id).then_some(i))
.collect();
return Some((row_indices, column_indices));
}
let (row, col) = grid_position(rows, columns, &focused_position(ui)?)?;
Some((vec![row], vec![col]))
}
pub fn copy_table_cells(
state: &DatabaseFlowState,
block_id: &str,
data: &DatabaseData,
titles: &BTreeMap<String, String>,
offset: &dyn Fn(i64) -> i32,
) -> Option<Vec<Vec<TableClipboardCell>>> {
let (rows, columns) = table_grid(state, block_id, data, titles, offset)?;
let (selected_rows, selected_cols) =
selected_axes(&state.state_for(block_id), &rows, &columns)?;
let by_id: BTreeMap<_, _> = data.rows.iter().map(|r| (r.row_id.as_str(), r)).collect();
Some(
selected_rows
.into_iter()
.filter_map(|r| {
let row = by_id.get(rows[r].1.as_str())?;
Some(
selected_cols
.iter()
.map(|&c| {
let (id, ty) = &columns[c];
let value = data.cells.get(&(row.row_id.clone(), id.clone()));
match ty.as_str() {
"checkbox" => TableClipboardCell::Text(match value {
Some(DatabaseCellValue::Bool(value)) => value.to_string(),
_ => String::new(),
}),
"select" | "multi-select" => {
let options = data
.columns
.iter()
.find(|column| column.id == *id)
.map(|column| column.select_options())
.unwrap_or_default();
let ids = match value {
Some(DatabaseCellValue::MultiSelect(ids)) => ids.clone(),
Some(DatabaseCellValue::Text(id)) => vec![id.clone()],
_ => Vec::new(),
};
let labels = ids
.iter()
.map(|id| {
options
.iter()
.find(|option| option.id == *id)
.map_or_else(String::new, |option| {
option.value.clone()
})
})
.collect();
TableClipboardCell::Options { ids, labels }
}
_ => TableClipboardCell::Text(resolve_initial_cell_draft(
data, row, id, ty, offset,
)),
}
})
.collect(),
)
})
.collect(),
)
}
#[allow(clippy::too_many_arguments)]
pub fn paste_table_cells(
page: &mut PageDocSession,
state: &DatabaseFlowState,
block_id: &str,
data: &DatabaseData,
titles: &BTreeMap<String, String>,
offset: &dyn Fn(i64) -> i32,
input: &[Vec<TableClipboardCell>],
now_ms: u64,
) -> DocResult<bool> {
let Some((rows, columns)) = table_grid(state, block_id, data, titles, offset) else {
return Ok(false);
};
let Some((selected_rows, selected_cols)) =
selected_axes(&state.state_for(block_id), &rows, &columns)
else {
return Ok(false);
};
let source_width = input.first().map_or(0, Vec::len);
if source_width == 0 || selected_rows.is_empty() || selected_cols.is_empty() {
return Ok(false);
}
let (target_rows, target_cols) = if selected_rows.len() == 1 && selected_cols.len() == 1 {
let row = selected_rows[0];
let col = selected_cols[0];
(
(row..rows.len()).take(input.len()).collect(),
(col..columns.len()).take(source_width).collect(),
)
} else {
(selected_rows, selected_cols)
};
let cells = target_rows.iter().enumerate().flat_map(|(i, &r)| {
let row = &rows[r].1;
let source = &input[i % input.len()];
let columns = &columns;
target_cols.iter().enumerate().map(move |(j, &c)| {
let (column, ty) = &columns[c];
let value = Some(source.get(j % source_width).unwrap_or(&EMPTY_CELL));
(row.as_str(), column.as_str(), ty.as_str(), value)
})
});
write_cells(page, block_id, data, cells, offset, now_ms)
}
pub(super) fn clear_table_cells(
page: &mut PageDocSession,
state: &DatabaseFlowState,
block_id: &str,
data: &DatabaseData,
titles: &BTreeMap<String, String>,
offset: &dyn Fn(i64) -> i32,
now_ms: u64,
) -> DocResult<bool> {
let Some((rows, columns)) = table_grid(state, block_id, data, titles, offset) else {
return Ok(false);
};
let Some((selected_rows, selected_cols)) =
selected_axes(&state.state_for(block_id), &rows, &columns)
else {
return Ok(false);
};
let cells = selected_rows.iter().flat_map(|&r| {
let row = &rows[r].1;
selected_cols.iter().map(|&c| {
let (column, ty) = &columns[c];
(row.as_str(), column.as_str(), ty.as_str(), None)
})
});
write_cells(page, block_id, data, cells, offset, now_ms)
}
fn write_cells<'a>(
page: &mut PageDocSession,
block_id: &str,
data: &DatabaseData,
cells: impl Iterator<Item = (&'a str, &'a str, &'a str, Option<&'a TableClipboardCell>)>,
offset: &dyn Fn(i64) -> i32,
now_ms: u64,
) -> DocResult<bool> {
let mut seen = BTreeSet::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
.iter()
.find(|item| item.row_id == row)?
.title
.plain;
if old == value.as_ref() {
return None;
}
ParsedCellInput::RowTitle(value.to_string())
} else if value.is_empty()
&& (option_ids.is_none() || !matches!(ty, "select" | "multi-select"))
{
let spec = match ty {
"rich-text" if cell.is_some() => {
if data
.cells
.get(&(row.to_string(), column.to_string()))
.and_then(DatabaseCellValue::as_str)
== Some("")
{
return None;
}
DatabaseCellSpec::RichText(String::new())
}
ty => {
let old = data.cells.get(&(row.to_string(), column.to_string()))?;
if matches!(old, DatabaseCellValue::Null) {
return None;
}
if ty == "multi-select" {
DatabaseCellSpec::MultiSelect(Vec::new())
} else {
DatabaseCellSpec::Null
}
}
};
ParsedCellInput::Cell(spec)
} else {
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")?,
};
if ids.is_empty() {
return None;
}
if ty == "select" {
DatabaseCellSpec::Text(ids.into_iter().next()?)
} else {
DatabaseCellSpec::MultiSelect(ids)
}
}
_ => match parse_cell_draft(ty, &value, offset).ok()? {
ParsedCellInput::Cell(spec) => spec,
ParsedCellInput::RowTitle(_) => return None,
},
};
ParsedCellInput::Cell(spec)
};
Some((row, column, parsed))
})
.collect();
if changes.is_empty() {
return Ok(false);
}
page.structural_edit(now_ms, move |page| {
for (row, column, value) in changes {
match value {
ParsedCellInput::RowTitle(title) => {
page.set_database_row_title(block_id, row, &title, now_ms)?;
}
ParsedCellInput::Cell(spec) => {
page.set_database_cell_value(block_id, row, column, spec, now_ms)?;
}
}
}
Ok(())
})
.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());
}
}
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();
while !remaining.is_empty() {
let (matched, rest) = remaining
.match_indices(',')
.map(|(end, _)| (&remaining[..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());
remaining = rest.trim_start();
}
Some(ids)
}
@@ -30,6 +30,12 @@ pub enum DatabaseNavKey {
Right,
Tab,
ShiftTab,
ExtendUp,
ExtendDown,
ExtendLeft,
ExtendRight,
InsertBelow,
SelectAll,
Enter,
Delete,
Escape,
@@ -85,6 +91,7 @@ impl DatabaseFlowState {
.is_some_and(|(row, _)| !shown.contains(row))
{
entry.focused_cell = None;
entry.cell_range = None;
entry.focused_group = None;
}
if before != (entry.selected_rows.len(), entry.focused_cell.is_some()) {
@@ -102,6 +109,7 @@ impl DatabaseFlowState {
}
entry.selected_rows.clear();
entry.focused_cell = None;
entry.cell_range = None;
entry.focused_group = None;
self.mark_dirty(block_id);
true
@@ -129,9 +137,12 @@ impl DatabaseFlowState {
return;
};
let cell = (ed.row_id.clone(), ed.column_id.clone());
if is_table && entry.focused_cell.as_ref() != Some(&cell) {
if is_table && (entry.focused_cell.as_ref() != Some(&cell) || entry.cell_range.is_some()) {
entry.cell_range = None;
if group_key.is_some() || entry.focused_cell.as_ref() != Some(&cell) {
entry.focused_group = group_key.map(str::to_string);
}
entry.focused_cell = Some(cell);
entry.focused_group = group_key.map(str::to_string);
self.mark_dirty(block_id);
}
}
@@ -147,6 +158,22 @@ impl DatabaseFlowState {
/// One shown Table row: the group it shows in (`None` when the view is not grouped) and its
/// row id. A multi-select grouping shows one row in each group of its tags.
pub(super) type RowSlot = (Option<String>, String);
type CellPosition = (RowSlot, String);
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CellRange {
anchor: CellPosition,
rows: BTreeMap<String, BTreeSet<Option<String>>>,
pub(super) columns: BTreeSet<String>,
}
impl CellRange {
pub(super) fn contains_row(&self, group: Option<&str>, row: &str) -> bool {
self.rows
.get(row)
.is_some_and(|groups| groups.iter().any(|key| key.as_deref() == group))
}
}
/// The rows that the Table view `view` shows, in display order. `rows` are the rows that its
/// filter and search let through. A grouped view shows only the rows of each group that
@@ -302,7 +329,7 @@ pub fn delete_rows(
}
/// Shown Table row slots and columns `(id, type)` in display order.
fn table_grid(
pub(super) fn table_grid(
flow_state: &DatabaseFlowState,
block_id: &str,
data: &DatabaseData,
@@ -317,6 +344,23 @@ fn table_grid(
Some((slots, cols))
}
pub(super) fn grid_position(
rows: &[RowSlot],
cols: &[(String, String)],
((group, row), col): &CellPosition,
) -> Option<(usize, usize)> {
let index = rows
.iter()
.position(|(g, r)| r == row && g == group)
.or_else(|| rows.iter().position(|(_, r)| r == row))?;
Some((index, cols.iter().position(|(c, _)| c == col)?))
}
pub(super) fn focused_position(ui: &super::DatabaseUiState) -> Option<CellPosition> {
let (row, col) = ui.focused_cell.clone()?;
Some(((ui.focused_group.clone(), row), col))
}
/// Handle a navigation key for the focused Table cell of `block_id`: arrows and `Tab` move the
/// focus, `Enter` edits the focused cell (or flips a checkbox), `Delete` removes the checked
/// rows the view shows, and `Escape` clears the selection, then the focus.
@@ -348,6 +392,10 @@ pub fn handle_navigation_key(
.ui_states
.entry(block_id.to_string())
.or_default();
if entry.cell_range.take().is_some() {
flow_state.mark_dirty(block_id);
return Ok(done(false));
}
if entry.selected_rows.is_empty() {
entry.focused_cell = None;
entry.focused_group = None;
@@ -358,18 +406,23 @@ pub fn handle_navigation_key(
return Ok(done(false));
}
DatabaseNavKey::Delete => {
let shown = shown_table_rows(flow_state, block_id, data, page_titles, offset_at_ms);
let rows: Vec<String> = ui
.selected_rows
.iter()
.filter(|id| shown.contains(*id))
.cloned()
.collect();
if rows.is_empty() {
return Ok(done(false));
if ui.selected_rows.is_empty() {
return super::table_clipboard::clear_table_cells(
page,
flow_state,
block_id,
data,
page_titles,
offset_at_ms,
now_ms,
)
.map(done);
}
let shown = shown_table_rows(flow_state, block_id, data, page_titles, offset_at_ms);
let rows: Vec<String> = ui.selected_rows.intersection(&shown).cloned().collect();
return delete_rows(page, flow_state, block_id, data, &rows, now_ms).map(done);
}
DatabaseNavKey::InsertBelow if !ui.selected_rows.is_empty() => return Ok(done(false)),
_ => {}
}
let Some((rows, cols)) = table_grid(flow_state, block_id, data, page_titles, offset_at_ms)
@@ -379,16 +432,20 @@ pub fn handle_navigation_key(
if rows.is_empty() || cols.is_empty() {
return Ok(done(false));
}
// The focused slot: the row in the focused group, else the first slot of the row.
let position = ui.focused_cell.as_ref().and_then(|(row, col)| {
let in_group = rows
.iter()
.position(|(g, r)| r == row && *g == ui.focused_group);
Some((
in_group.or_else(|| rows.iter().position(|(_, r)| r == row))?,
cols.iter().position(|(c, _)| c == col)?,
))
});
if key == DatabaseNavKey::SelectAll {
let entry = flow_state
.ui_states
.entry(block_id.to_string())
.or_default();
entry.selected_rows = selectable_row_ids(&rows).into_iter().collect();
entry.cell_range = None;
flow_state.mark_dirty(block_id);
return Ok(done(false));
}
let focused = focused_position(&ui);
let position = focused
.as_ref()
.and_then(|cell| grid_position(&rows, &cols, cell));
let Some((r, c)) = position else {
let entry = flow_state
.ui_states
@@ -399,13 +456,25 @@ pub fn handle_navigation_key(
flow_state.mark_dirty(block_id);
return Ok(done(false));
};
if key == DatabaseNavKey::InsertBelow {
return super::row_ops::handle_row_menu_action(
page,
flow_state,
block_id,
data,
&DatabaseAuthoringHitKind::RowMenuInsertBelow {
row_id: rows[r].1.clone(),
},
now_ms,
);
}
let last_c = cols.len() - 1;
let last_r = rows.len() - 1;
let (next_r, next_c) = match key {
DatabaseNavKey::Up => (r.saturating_sub(1), c),
DatabaseNavKey::Down => ((r + 1).min(last_r), c),
DatabaseNavKey::Left => (r, c.saturating_sub(1)),
DatabaseNavKey::Right => (r, (c + 1).min(last_c)),
DatabaseNavKey::Up | DatabaseNavKey::ExtendUp => (r.saturating_sub(1), c),
DatabaseNavKey::Down | DatabaseNavKey::ExtendDown => ((r + 1).min(last_r), c),
DatabaseNavKey::Left | DatabaseNavKey::ExtendLeft => (r, c.saturating_sub(1)),
DatabaseNavKey::Right | DatabaseNavKey::ExtendRight => (r, (c + 1).min(last_c)),
DatabaseNavKey::Tab if c == last_c => {
((r + 1).min(last_r), if r == last_r { c } else { 0 })
}
@@ -416,11 +485,46 @@ pub fn handle_navigation_key(
DatabaseNavKey::ShiftTab => (r, c - 1),
_ => (r, c),
};
let extending = matches!(
key,
DatabaseNavKey::ExtendUp
| DatabaseNavKey::ExtendDown
| DatabaseNavKey::ExtendLeft
| DatabaseNavKey::ExtendRight
);
let range = if extending {
let anchor = ui.cell_range.map_or_else(
|| (rows[r].clone(), cols[c].0.clone()),
|range| range.anchor,
);
let (ar, ac) = grid_position(&rows, &cols, &anchor).unwrap_or((r, c));
let mut selected_rows = BTreeMap::<_, BTreeSet<_>>::new();
for (group, row) in &rows[ar.min(next_r)..=ar.max(next_r)] {
selected_rows
.entry(row.clone())
.or_default()
.insert(group.clone());
}
Some(CellRange {
anchor,
rows: selected_rows,
columns: cols[ac.min(next_c)..=ac.max(next_c)]
.iter()
.map(|(id, _)| id.clone())
.collect(),
})
} else {
None
};
if key != DatabaseNavKey::Enter {
let entry = flow_state
.ui_states
.entry(block_id.to_string())
.or_default();
entry.cell_range = range;
if extending {
entry.selected_rows.clear();
}
entry.focused_cell = Some((rows[next_r].1.clone(), cols[next_c].0.clone()));
entry.focused_group = rows[next_r].0.clone();
flow_state.mark_dirty(block_id);
@@ -0,0 +1,56 @@
use std::rc::Rc;
use ui::{Direction, Window};
use crate::{
block_flow::{FlowRect, InlineAlign, InlineBaseline, InlineStyle, layout_inline},
theme::{FONT_SANS, Palette},
};
use super::DatabasePrim;
pub const DATABASE_TITLE_FONT: (f32, f32) = (20.0, 600.0);
pub(super) fn display_text(text: &str) -> &str {
if text.is_empty() { "Untitled" } else { text }
}
pub(super) fn text_align(direction: Direction) -> InlineAlign {
if direction.is_rtl() {
InlineAlign::Right
} else {
InlineAlign::Left
}
}
pub(super) fn paint_title(
text: &str,
rect: FlowRect,
align: InlineAlign,
palette: &Palette,
window: &Window,
prims: &mut Vec<DatabasePrim>,
) {
let style = InlineStyle::new(
FONT_SANS,
DATABASE_TITLE_FONT.0,
DATABASE_TITLE_FONT.1,
palette.text_primary,
);
let content = FlowRect::new(rect.x + 8.0, rect.y, (rect.w - 16.0).max(1.0), rect.h);
let layout = layout_inline(
text,
&style,
content.w,
content.h,
InlineBaseline::Of(&style),
align,
window,
);
prims.push(DatabasePrim::Text {
x: content.x,
y: content.y,
layout: Rc::new(layout),
clip: Some(content),
});
}
@@ -51,3 +51,374 @@ pub(super) fn partition_desktop_view_tabs(
}
(visible, overflow)
}
use blocksuite_playground_doc::{DocResult, read::DatabaseData, session::PageDocSession};
use y_octo::{Any, SessionReadValue, SessionValue};
use crate::{
block_flow::{FlowRect, InlineAlign, InlineStyle},
theme::{FONT_SANS, TYPOGRAPHY},
};
use super::{
AuthoringActionResult, DatabaseAuthoringHit, DatabaseAuthoringHitKind, DatabaseFlowState,
DatabasePrim,
authoring_id::fresh_database_id,
render::DbRenderCtx,
wire_entries::{copy_value, database_field, field, find_entry, set_entry_field},
};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ViewMenuState {
pub view_id: String,
pub name_draft: String,
initial_name: String,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ViewMenuAction {
MoveLeft,
MoveRight,
Duplicate,
Delete,
}
pub fn rename_view(
page: &mut PageDocSession,
block_id: &str,
view_id: &str,
name: &str,
now_ms: u64,
) -> DocResult<bool> {
page.structural_edit(now_ms, |page| {
let array = database_field(block_id, "prop:views");
let entries = page.inner().read_array(&array)?;
if let Some(i) = find_entry(page, &entries, view_id)?
&& !matches!(field(page, &entries[i], "name")?, Some(SessionReadValue::Any(Any::String(old))) if old == name)
{
set_entry_field(page, &array, i, &entries[i], "name", SessionValue::Any(Any::String(name.to_string())))?;
}
Ok(())
}).map(|commit| commit.is_some())
}
pub(super) fn handle_view_menu(
page: &mut PageDocSession,
flow: &mut DatabaseFlowState,
block_id: &str,
data: &DatabaseData,
action: &ViewMenuAction,
now_ms: u64,
) -> DocResult<AuthoringActionResult> {
let Some(menu) = flow.authoring_mut(block_id).view_menu.take() else {
return Ok(AuthoringActionResult {
handled: false,
doc_mutated: false,
});
};
let new_id =
(*action == ViewMenuAction::Duplicate).then(|| fresh_database_id(page, data, "view"));
let changed = page
.structural_edit(now_ms, |page| {
let array = database_field(block_id, "prop:views");
let entries = page.inner().read_array(&array)?;
let Some(i) = find_entry(page, &entries, &menu.view_id)? else {
return Ok(());
};
match action {
ViewMenuAction::Delete if entries.len() > 1 => {
page.inner_mut().array_remove(&array, i as u64, 1)?;
}
ViewMenuAction::Duplicate => {
let original = copy_view(page, entries[i].clone(), &menu)?;
if menu.name_draft != menu.initial_name {
set_entry_field(
page,
&array,
i,
&entries[i],
"name",
SessionValue::Any(Any::String(menu.name_draft.clone())),
)?;
}
if let (SessionValue::Map(mut fields), Some(id)) = (original, &new_id) {
fields.retain(|(key, _)| key != "id");
fields.push(("id".into(), SessionValue::Any(Any::String(id.clone()))));
page.inner_mut().array_insert(
&array,
i as u64 + 1,
vec![SessionValue::Map(fields)],
)?;
}
}
ViewMenuAction::MoveLeft | ViewMenuAction::MoveRight => {
let target = match action {
ViewMenuAction::MoveLeft if i > 0 => i - 1,
ViewMenuAction::MoveRight if i + 1 < entries.len() => i + 1,
_ => return Ok(()),
};
let value = copy_view(page, entries[i].clone(), &menu)?;
page.inner_mut().array_remove(&array, i as u64, 1)?;
page.inner_mut()
.array_insert(&array, target as u64, vec![value])?;
}
_ => {}
}
Ok(())
})?
.is_some();
if changed && let Some(new_id) = new_id {
flow.set_active_view(block_id, new_id);
} else if changed
&& *action == ViewMenuAction::Delete
&& let Some(first) = data.views.iter().find(|view| view.id != menu.view_id)
{
flow.set_active_view(block_id, first.id.clone());
}
Ok(AuthoringActionResult {
handled: true,
doc_mutated: changed,
})
}
fn copy_view(
page: &PageDocSession,
entry: SessionReadValue,
menu: &ViewMenuState,
) -> DocResult<SessionValue> {
let mut value = match entry {
SessionReadValue::Any(Any::Object(fields)) => SessionValue::Map(
fields
.into_iter()
.map(|(key, value)| (key, SessionValue::Any(value)))
.collect(),
),
other => copy_value(page, other)?,
};
if menu.name_draft != menu.initial_name
&& let SessionValue::Map(fields) = &mut value
{
fields.retain(|(key, _)| key != "name");
fields.push((
"name".into(),
SessionValue::Any(Any::String(menu.name_draft.clone())),
));
}
Ok(value)
}
fn view_menu_rows(
data: &DatabaseData,
menu: &ViewMenuState,
) -> impl Iterator<Item = (ViewMenuAction, &'static str, &'static str)> {
let position = data.views.iter().position(|view| view.id == menu.view_id);
[
(
position.is_some_and(|i| i > 0),
ViewMenuAction::MoveLeft,
"Move Left",
"MoveLeftIcon",
),
(
position.is_some_and(|i| i + 1 < data.views.len()),
ViewMenuAction::MoveRight,
"Move Right",
"MoveRightIcon",
),
(
true,
ViewMenuAction::Duplicate,
"Duplicate",
"DuplicateIcon",
),
(
data.views.len() > 1,
ViewMenuAction::Delete,
"Delete",
"DeleteIcon",
),
]
.into_iter()
.filter_map(|(show, action, label, icon)| show.then_some((action, label, icon)))
}
pub(super) fn measure_view_menu(data: &DatabaseData, menu: &ViewMenuState) -> (f32, f32) {
(
200.0,
44.0 + 28.0 * view_menu_rows(data, menu).count() as f32,
)
}
pub(super) fn render_view_menu(
ctx: &DbRenderCtx<'_>,
menu: &ViewMenuState,
bounds: FlowRect,
prims: &mut Vec<DatabasePrim>,
hits: &mut Vec<DatabaseAuthoringHit>,
) -> FlowRect {
prims.push(DatabasePrim::Quad {
rect: bounds,
fill: Some(ctx.palette.panel),
border: Some(ctx.palette.border),
radius: 8.0,
dashed: false,
});
let input = FlowRect::new(bounds.x + 6.0, bounds.y + 6.0, bounds.w - 12.0, 28.0);
prims.push(DatabasePrim::Quad {
rect: input,
fill: Some(ctx.palette.background),
border: Some(ctx.palette.brand),
radius: 4.0,
dashed: false,
});
let font = TYPOGRAPHY.font_xs_px + 1.0;
if menu.name_draft.is_empty() {
prims.push(ctx.single_line_clipped(
"View name",
InlineStyle::new(FONT_SANS, font, 400.0, ctx.palette.placeholder),
input.x + 8.0,
input.y,
input.w - 16.0,
input.h,
InlineAlign::Left,
));
}
for (index, (action, label, icon)) in view_menu_rows(ctx.data, menu).enumerate() {
let rect = FlowRect::new(
input.x,
input.bottom() + 4.0 + 28.0 * index as f32,
input.w,
28.0,
);
let ink = if action == ViewMenuAction::Delete {
ctx.theme
.css_var("--affine-v2-status-error")
.unwrap_or(ctx.palette.text_primary)
} else {
ctx.palette.text_primary
};
prims.push(DatabasePrim::Icon {
rect: FlowRect::new(rect.x + 6.0, rect.y + 7.0, 14.0, 14.0),
icon: crate::theme::IconPaint::named(icon),
color: if action == ViewMenuAction::Delete {
ink
} else {
ctx.palette.icon
},
});
prims.push(ctx.single_line_clipped(
label,
InlineStyle::new(FONT_SANS, font, 400.0, ink),
rect.x + 26.0,
rect.y,
rect.w - 30.0,
rect.h,
InlineAlign::Left,
));
hits.push(DatabaseAuthoringHit {
rect,
kind: DatabaseAuthoringHitKind::ViewMenu(action),
scrolls_x: false,
});
}
input
}
pub(super) fn view_menu_trigger(
hits: &[super::DatabaseHitTarget],
active: &DatabaseView,
writable: bool,
authoring: &mut Vec<DatabaseAuthoringHit>,
) -> Option<super::DatabasePopoverAnchor> {
if !writable {
return None;
}
let tab = hits.iter().find(|hit| {
matches!(&hit.kind,
super::DatabaseHitKind::SwitchView { view_id } if view_id == &active.id)
})?;
authoring.push(DatabaseAuthoringHit {
rect: tab.rect,
kind: DatabaseAuthoringHitKind::OpenViewMenu {
view_id: active.id.clone(),
},
scrolls_x: false,
});
Some(super::DatabasePopoverAnchor {
rect: tab.rect,
scrolls_x: false,
})
}
pub(super) fn render_more_icon(
tab: FlowRect,
clip: Option<FlowRect>,
direction: ui::Direction,
ink: ui::Hsla,
prims: &mut Vec<DatabasePrim>,
) {
let x = if direction.is_rtl() {
tab.x + 3.0
} else {
tab.right() - 15.0
};
if clip.is_none_or(|clip| x >= clip.x && x + 12.0 <= clip.right()) {
prims.push(DatabasePrim::Icon {
rect: FlowRect::new(x, tab.y + (tab.h - 12.0) * 0.5, 12.0, 12.0),
icon: crate::theme::IconPaint::from_def(&ui_tokens::icons::MORE_HORIZONTAL),
color: ink,
});
}
}
pub(super) fn open_view_menu(
flow: &mut DatabaseFlowState,
block_id: &str,
data: &DatabaseData,
view_id: &str,
) -> AuthoringActionResult {
let auth = flow.authoring_mut(block_id);
let open = auth
.view_menu
.as_ref()
.is_none_or(|menu| menu.view_id != view_id);
auth.dismiss_popovers();
if open && let Some(view) = data.views.iter().find(|view| view.id == view_id) {
auth.view_menu = Some(ViewMenuState {
view_id: view.id.clone(),
name_draft: view.name.clone(),
initial_name: view.name.clone(),
});
}
AuthoringActionResult {
handled: true,
doc_mutated: false,
}
}
pub(super) fn default_table_view() -> DatabaseView {
DatabaseView {
id: "default-table".to_string(),
name: "Table View".to_string(),
mode: DatabaseViewMode::Table,
columns: Vec::new(),
filter: None,
sort: None,
group_by: None,
group_properties: Vec::new(),
header: None,
date: None,
card: None,
ui: None,
extra: Default::default(),
}
}
pub(super) fn active_render_view<'a>(
data: &'a DatabaseData,
active_view_id: Option<&str>,
) -> Option<&'a DatabaseView> {
active_view_id
.and_then(|id| data.views.iter().find(|view| view.id == id))
.or_else(|| data.views.first())
}
@@ -0,0 +1,92 @@
use blocksuite_playground_doc::{DocError, DocResult, session::PageDocSession};
use y_octo::{Any, SessionReadValue, SessionValue, TypePath, TypeTarget};
pub(super) fn database_field(block_id: &str, field: &str) -> TypeTarget {
TypeTarget::Path(TypePath::root("blocks").key(block_id).key(field))
}
pub(super) fn field(
page: &PageDocSession,
value: &SessionReadValue,
key: &str,
) -> DocResult<Option<SessionReadValue>> {
match value {
SessionReadValue::Map(id) => Ok(page
.inner()
.get_map_value(&TypeTarget::Identity(id.clone()), key)?),
SessionReadValue::Any(Any::Object(entries)) => {
Ok(entries.get(key).cloned().map(SessionReadValue::Any))
}
_ => Ok(None),
}
}
pub(super) fn find_entry(
page: &PageDocSession,
items: &[SessionReadValue],
id: &str,
) -> DocResult<Option<usize>> {
for (index, item) in items.iter().enumerate() {
if matches!(field(page, item, "id")?, Some(SessionReadValue::Any(Any::String(key))) if key == id)
{
return Ok(Some(index));
}
}
Ok(None)
}
pub(super) fn copy_value(
page: &PageDocSession,
value: SessionReadValue,
) -> DocResult<SessionValue> {
Ok(match value {
SessionReadValue::Any(value) => SessionValue::Any(value),
SessionReadValue::Text(id) => {
SessionValue::Text(page.inner().read_text_delta(&TypeTarget::Identity(id))?)
}
SessionReadValue::Array(id) => SessionValue::Array(
page.inner()
.read_array(&TypeTarget::Identity(id))?
.into_iter()
.map(|item| copy_value(page, item))
.collect::<DocResult<_>>()?,
),
SessionReadValue::Map(id) => SessionValue::Map(
page.inner()
.read_map(&TypeTarget::Identity(id))?
.into_iter()
.map(|(key, value)| Ok((key, copy_value(page, value)?)))
.collect::<DocResult<_>>()?,
),
_ => return Err(DocError::InvalidState("Unsupported database value".into())),
})
}
pub(super) fn set_entry_field(
page: &mut PageDocSession,
array: &TypeTarget,
index: usize,
entry: &SessionReadValue,
key: &str,
value: SessionValue,
) -> DocResult<()> {
match entry {
SessionReadValue::Map(id) => {
page.inner_mut()
.map_set(&TypeTarget::Identity(id.clone()), key.to_string(), value)?;
}
SessionReadValue::Any(Any::Object(entries)) => {
let mut entries: Vec<_> = entries
.iter()
.filter(|(name, _)| name.as_str() != key)
.map(|(name, value)| (name.clone(), SessionValue::Any(value.clone())))
.collect();
entries.push((key.to_string(), value));
page.inner_mut().array_remove(array, index as u64, 1)?;
page.inner_mut()
.array_insert(array, index as u64, vec![SessionValue::Map(entries)])?;
}
_ => {}
}
Ok(())
}
@@ -0,0 +1,256 @@
use blocksuite_editor::database::{self, TableClipboardCell};
use ui::{ClipboardEntry, ClipboardItem, Context};
use serde::{Deserialize, Serialize};
use crate::PlaygroundView;
impl PlaygroundView {
pub(super) fn database_clipboard_key(
&mut self,
block_id: &str,
key: &str,
cx: &mut Context<Self>,
) -> bool {
let Some(data) = self.database_data(block_id) else {
return false;
};
let expected = self.flow.database_state.state_for(block_id);
if !expected.selected_rows.is_empty() {
return false;
}
if key == "c" {
let offset = self.utc_offset_resolver();
if let Some(rows) = database::copy_table_cells(
&self.flow.database_state,
block_id,
data,
&self.page_titles,
&offset,
) {
cx.write_to_clipboard(TableClipboard::new_item(rows));
}
} 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();
}
true
}
fn paste_database_cells(
&mut self,
block_id: &str,
item: &ClipboardItem,
cx: &mut Context<Self>,
) {
if self.is_database_write_readonly() {
return;
}
let Some(rows) = TableClipboard::from_item(item) else {
return;
};
let snap = self.snapshot.clone();
let Some(data) = snap
.as_deref()
.and_then(|snap| super::snapshot_database(snap, block_id))
else {
return;
};
let before = self
.page()
.and_then(|page| page.encode_state_vector_v1().ok());
let now_ms = self.now_ms(cx) as u64;
let offset = self.utc_offset_resolver();
let changed = self
.page_id
.as_deref()
.and_then(|id| self.state.workspace.page_mut(id))
.is_some_and(|page| {
database::paste_table_cells(
page,
&self.flow.database_state,
block_id,
data,
&self.page_titles,
&offset,
&rows,
now_ms,
)
.unwrap_or_default()
});
if changed {
self.sync_after_database_mutation(before, cx);
}
}
}
#[derive(Deserialize, Serialize)]
struct TableClipboard {
database_table: Vec<Vec<TableClipboardCell>>,
}
impl TableClipboard {
fn new_item(database_table: Vec<Vec<TableClipboardCell>>) -> ClipboardItem {
ClipboardItem::new_string_with_json_metadata(
encode_tsv(&database_table),
Self { database_table },
)
}
fn from_item(item: &ClipboardItem) -> Option<Vec<Vec<TableClipboardCell>>> {
let text = item.text().or_else(|| {
item.entries()
.iter()
.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
&& database_table.iter().all(|row| row.len() == width)
&& encode_tsv(&database_table) == text
{
return Some(database_table);
}
Some(decode_tsv(&text))
}
}
fn encode_tsv(rows: &[Vec<TableClipboardCell>]) -> String {
let mut text = String::new();
for (r, row) in rows.iter().enumerate() {
if r > 0 {
text.push('\n');
}
for (c, cell) in row.iter().enumerate() {
if c > 0 {
text.push('\t');
}
let cell = cell.plain_text();
if cell.contains(['\t', '\n', '\r', '"']) {
text.push('"');
text.push_str(&cell.replace('"', "\"\""));
text.push('"');
} else {
text.push_str(&cell);
}
}
}
text
}
fn decode_tsv(text: &str) -> Vec<Vec<TableClipboardCell>> {
let mut chars = text.chars().peekable();
let mut rows = Vec::new();
let mut row = Vec::new();
let mut cell = String::new();
let mut quoted = false;
let mut at_start = true;
while let Some(ch) = chars.next() {
match ch {
'"' if quoted => {
if chars.next_if_eq(&'"').is_some() {
cell.push('"');
} else {
quoted = false;
}
}
'"' if at_start => quoted = true,
'\t' | '\n' | '\r' if !quoted => {
row.push(TableClipboardCell::Text(std::mem::take(&mut cell)));
at_start = true;
if ch != '\t' {
if ch == '\r' {
chars.next_if_eq(&'\n');
}
rows.push(std::mem::take(&mut row));
}
continue;
}
_ => cell.push(ch),
}
at_start = false;
}
if !at_start || !row.is_empty() || rows.is_empty() {
row.push(TableClipboardCell::Text(cell));
rows.push(row);
}
rows
}
#[cfg(test)]
mod tests {
use super::{TableClipboard, TableClipboardCell, decode_tsv, encode_tsv};
use ui::ClipboardItem;
fn plain(rows: &[Vec<TableClipboardCell>]) -> Vec<Vec<String>> {
rows.iter()
.map(|row| {
row.iter()
.map(|cell| cell.plain_text().into_owned())
.collect()
})
.collect()
}
#[test]
fn quoted_tsv_and_clipboard_metadata_preserve_empty_fields() {
for (text, expected) in [
("", vec![vec![""]]),
("A\n\n", vec![vec!["A"], vec![""]]),
("a\tb\r\n\tc\r\n", vec![vec!["a", "b"], vec!["", "c"]]),
(
"\"Tab\tvalue\"\t\"Line\nbreak\"\t\"Quote \"\"value\"\"\"",
vec![vec!["Tab\tvalue", "Line\nbreak", "Quote \"value\""]],
),
] {
assert_eq!(plain(&decode_tsv(text)), expected);
}
for input in [
vec![vec!["A"], vec![""]],
vec![vec![""]],
vec![vec!["A", ""], vec!["", ""]],
] {
let rows: Vec<_> = input
.iter()
.map(|row| {
row.iter()
.map(|text| TableClipboardCell::Text((*text).to_string()))
.collect()
})
.collect();
let text = encode_tsv(&rows);
let item = TableClipboard::new_item(rows);
assert_eq!(item.text().unwrap_or_default(), text);
assert_eq!(plain(&TableClipboard::from_item(&item).unwrap()), input);
let stale = ClipboardItem::new_string_with_json_metadata(
"New text".into(),
serde_json::from_str::<serde_json::Value>(item.metadata().unwrap()).unwrap(),
);
assert_eq!(
plain(&TableClipboard::from_item(&stale).unwrap()),
[["New text"]]
);
}
}
}
@@ -326,6 +326,17 @@ impl PlaygroundView {
/// scroll.
pub(crate) fn database_inline_screen_box(&self, w: &Window) -> Option<(FlowRect, (f32, f32))> {
let session = self.database_input.as_ref()?;
if matches!(session.target, DatabaseInlineTarget::DatabaseTitle { .. }) {
let block_id = session.target.block_id();
let hit = self
.flow
.database_authoring_hits(block_id)
.iter()
.find(|hit| hit.kind == database::DatabaseAuthoringHitKind::EditDatabaseTitle)?;
let rect = self.database_local_rect_to_screen(block_id, hit.rect, false, w)?;
let (font, weight) = database::DATABASE_TITLE_FONT;
return Some((rect, (font * rect.h / hit.rect.h, weight)));
}
if matches!(session.target, DatabaseInlineTarget::RecordTitle { .. }) {
return self.record_title_screen_box(w);
}
@@ -10,238 +10,17 @@ use std::{
use blocksuite_editor::{
block_flow::InlineLayout,
database::{
ActiveToolbarPanel, ParsedCellInput, filter_op_takes_no_arg,
self, ActiveToolbarPanel, ParsedCellInput, filter_op_takes_no_arg,
normalize_operator_for_column_type, parse_cell_draft,
},
inline_input::{AnchoredInlineInput, TextSplice},
};
use blocksuite_playground_doc::read::BlockContent;
use blocksuite_playground_doc::session::PageDocSession;
use ui::{Context, Window};
use y_octo::{RelativePosition, SessionReadValue, TypePath, TypeTarget};
use crate::{PlaygroundView, overlays::InlineTargetEnd};
/// Which database text field currently owns the unified [`AnchoredInlineInput`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum DatabaseInlineTarget {
/// Live `Y.Text` cell (`title` or `rich-text`): incremental UTF-16 splice preserving marks
/// and `@reference` embeds, `Shift+Enter` newline, and 0 CRDT writes on no-op.
LiveRichCell {
block_id: String,
row_id: String,
column_id: String,
is_title: bool,
},
/// Validated scalar cell (`number`, `date`, `progress`, `link`).
ScalarCell {
block_id: String,
row_id: String,
column_id: String,
col_type: String,
initial: String,
},
RecordBody {
block_id: String,
row_id: String,
child_id: String,
},
ColumnRename {
block_id: String,
column_id: String,
initial: String,
},
SelectFilter {
block_id: String,
row_id: String,
column_id: String,
},
FilterValue {
block_id: String,
},
/// Title of the row shown in the open record peek, edited in its live `Y.Text` like a
/// `LiveRichCell` title.
RecordTitle {
block_id: String,
row_id: String,
},
/// Text field of a toolbar popover that writes view state only.
ViewField {
block_id: String,
field: ViewTextField,
},
}
/// Field of a [`DatabaseInlineTarget::ViewField`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ViewTextField {
Search,
GroupName,
}
impl DatabaseInlineTarget {
pub(crate) fn block_id(&self) -> &str {
match self {
Self::LiveRichCell { block_id, .. }
| Self::RecordBody { block_id, .. }
| Self::ScalarCell { block_id, .. }
| Self::ColumnRename { block_id, .. }
| Self::SelectFilter { block_id, .. }
| Self::FilterValue { block_id }
| Self::RecordTitle { block_id, .. }
| Self::ViewField { block_id, .. } => block_id,
}
}
/// The live `Y.Text` that each keystroke splices into, as `(block_id, row_id, column_id,
/// is_title)`.
pub(crate) fn live_text(&self) -> Option<(&str, &str, &str, bool)> {
match self {
Self::LiveRichCell {
block_id,
row_id,
column_id,
is_title,
} => Some((block_id, row_id, column_id, *is_title)),
Self::RecordTitle { block_id, row_id } => Some((block_id, row_id, "", true)),
_ => None,
}
}
pub(super) fn tracks_text(&self) -> bool {
matches!(self, Self::RecordBody { .. }) || self.live_text().is_some()
}
fn paragraph_text(&self, page: &PageDocSession) -> Option<TypeTarget> {
let Self::RecordBody { child_id, .. } = self else {
return None;
};
let block = TypeTarget::Path(TypePath::root("blocks").key(child_id.as_str()));
match page.inner().get_map_value(&block, "prop:text").ok()?? {
SessionReadValue::Text(id) => Some(TypeTarget::Identity(id)),
_ => None,
}
}
pub(super) fn encode_anchor(
&self,
page: &PageDocSession,
offset: usize,
) -> Option<RelativePosition> {
if let Some((block, row, col, title)) = self.live_text() {
return page
.encode_database_cell_relative_position(block, row, col, title, offset as u64)
.ok()
.flatten();
}
let target = self.paragraph_text(page)?;
let len = page.inner().read_text_len(&target).ok()?;
page.inner()
.create_relative_position(&target, len.min(offset as u64), -1)
.ok()
}
pub(super) fn resolve_anchor(
&self,
page: &PageDocSession,
pos: &RelativePosition,
) -> Option<usize> {
if let Some((block, row, col, title)) = self.live_text() {
return page
.resolve_database_cell_relative_position(block, row, col, title, pos)
.ok()
.flatten()
.map(|i| i as usize);
}
let target = self.paragraph_text(page)?;
let absolute = page.inner().resolve_relative_position(pos, true)?;
(target == TypeTarget::Identity(absolute.r#type)).then_some(absolute.index as usize)
}
pub(crate) fn is_popover_field(&self) -> bool {
matches!(
self,
Self::ColumnRename { .. }
| Self::SelectFilter { .. }
| Self::FilterValue { .. }
| Self::RecordBody { .. }
| Self::RecordTitle { .. }
| Self::ViewField { .. }
)
}
pub(crate) fn same_slot(&self, other: &Self) -> bool {
match (self, other) {
(
Self::LiveRichCell {
block_id: b1,
row_id: r1,
column_id: c1,
is_title: t1,
},
Self::LiveRichCell {
block_id: b2,
row_id: r2,
column_id: c2,
is_title: t2,
},
) => b1 == b2 && r1 == r2 && c1 == c2 && t1 == t2,
(
Self::ScalarCell {
block_id: b1,
row_id: r1,
column_id: c1,
col_type: ty1,
..
},
Self::ScalarCell {
block_id: b2,
row_id: r2,
column_id: c2,
col_type: ty2,
..
},
) => b1 == b2 && r1 == r2 && c1 == c2 && ty1 == ty2,
(
Self::ColumnRename {
block_id: b1,
column_id: c1,
..
},
Self::ColumnRename {
block_id: b2,
column_id: c2,
..
},
) => b1 == b2 && c1 == c2,
(
Self::SelectFilter {
block_id: b1,
row_id: r1,
column_id: c1,
},
Self::SelectFilter {
block_id: b2,
row_id: r2,
column_id: c2,
},
) => b1 == b2 && r1 == r2 && c1 == c2,
(Self::FilterValue { block_id: b1 }, Self::FilterValue { block_id: b2 }) => b1 == b2,
(
Self::RecordTitle {
block_id: b1,
row_id: r1,
},
Self::RecordTitle {
block_id: b2,
row_id: r2,
},
) => b1 == b2 && r1 == r2,
(Self::RecordBody { .. }, Self::RecordBody { .. })
| (Self::ViewField { .. }, Self::ViewField { .. }) => self == other,
_ => false,
}
}
}
pub(crate) use super::inline_target::{DatabaseInlineTarget, ViewTextField};
pub(crate) type InlineLayoutCacheKey = (String, bool, u32, u32, u32, u32, [u32; 4]);
@@ -336,7 +115,9 @@ impl PlaygroundView {
}
for (block_id, st) in self.flow.database_state.states() {
let a = &st.authoring;
if a.column_menu.is_some()
if a.title_editing
|| a.view_menu.is_some()
|| a.column_menu.is_some()
|| a.row_menu.is_some()
|| a.lane_menu.is_some()
|| a.calc_menu.is_some()
@@ -394,6 +175,34 @@ impl PlaygroundView {
}
for (block_id, st) in self.flow.database_state.states() {
let a = &st.authoring;
if a.title_editing {
let title = self.database_data(block_id)?.title.plain.clone();
return Some((
DatabaseInlineTarget::DatabaseTitle {
block_id: block_id.clone(),
},
title,
false,
));
}
if let Some(menu) = &a.view_menu {
let name = self
.database_data(block_id)?
.views
.iter()
.find(|view| view.id == menu.view_id)?
.name
.clone();
return Some((
DatabaseInlineTarget::ViewRename {
block_id: block_id.clone(),
view_id: menu.view_id.clone(),
initial: name,
},
menu.name_draft.clone(),
false,
));
}
if let Some(menu) = &a.column_menu {
return Some((
DatabaseInlineTarget::ColumnRename {
@@ -664,7 +473,20 @@ impl PlaygroundView {
.group_name_draft = display;
}
},
DatabaseInlineTarget::RecordBody { .. } | DatabaseInlineTarget::RecordTitle { .. } => {}
DatabaseInlineTarget::ViewRename { block_id, .. } => {
if let Some(menu) = self
.flow
.database_state
.authoring_mut(block_id)
.view_menu
.as_mut()
{
menu.name_draft = display;
}
}
DatabaseInlineTarget::DatabaseTitle { .. }
| DatabaseInlineTarget::RecordBody { .. }
| DatabaseInlineTarget::RecordTitle { .. } => {}
}
self.reset_caret_blink(cx);
@@ -711,7 +533,8 @@ impl PlaygroundView {
.max(1);
let offset_at = self.utc_offset_resolver();
match &session.target {
DatabaseInlineTarget::LiveRichCell { .. }
DatabaseInlineTarget::DatabaseTitle { .. }
| DatabaseInlineTarget::LiveRichCell { .. }
| DatabaseInlineTarget::RecordBody { .. }
| DatabaseInlineTarget::RecordTitle { .. } => {
if let Some((start, del, insert)) = unmark_splice {
@@ -756,6 +579,28 @@ impl PlaygroundView {
}
}
}
DatabaseInlineTarget::ViewRename {
block_id,
view_id,
initial,
} => {
let name = session.anchored.input.text();
if name != initial {
let before = self
.page()
.and_then(|page| page.encode_state_vector_v1().ok());
if self.page_mut().is_ok_and(|page| {
database::rename_view(page, block_id, view_id, name, now_ms)
.is_ok_and(|changed| changed)
}) {
if let Some(cx) = cx {
self.sync_after_database_mutation(before, cx);
} else {
self.refresh_document();
}
}
}
}
DatabaseInlineTarget::ColumnRename {
block_id,
column_id,
@@ -1,5 +1,9 @@
//! Splicing the edits of the database inline input into the live `Y.Text` it edits.
use blocksuite_editor::rich_text::TextBiIndex;
use blocksuite_playground_doc::session::PageDocSession;
use y_octo::{Any, SessionReadValue, SessionValue, TextDeltaOp, TextInsert, TypePath, TypeTarget};
use crate::PlaygroundView;
use super::inline::DatabaseInlineTarget;
@@ -19,6 +23,11 @@ impl PlaygroundView {
{
return self.splice_record_note(row_id, child_id, start, del, insert, now_ms);
}
if let DatabaseInlineTarget::DatabaseTitle { block_id } = target {
return self.page_mut().is_ok_and(|page| {
splice_title(page, block_id, start as u64, del as u64, insert, now_ms)
});
}
let Some((block_id, row_id, column_id, is_title)) = target.live_text() else {
return false;
};
@@ -47,3 +56,43 @@ impl PlaygroundView {
})
}
}
fn splice_title(
page: &mut PageDocSession,
block_id: &str,
start: u64,
len: u64,
insert: &str,
now_ms: u64,
) -> bool {
let block = TypeTarget::Path(TypePath::root("blocks").key(block_id));
let field = page.inner().get_map_value(&block, "prop:title");
let mut title = match field {
Ok(Some(SessionReadValue::Text(_))) => {
return page
.splice_block_title_text(block_id, start, len, insert, now_ms)
.ok()
.flatten()
.is_some();
}
Ok(Some(SessionReadValue::Any(Any::String(title)))) => title,
Ok(None | Some(SessionReadValue::Any(Any::Null))) => String::new(),
_ => return false,
};
let index = TextBiIndex::new(&title);
let first = index.utf16_to_utf8_clamped(start);
let end = index.utf16_to_utf8_clamped(start.saturating_add(len));
title.replace_range(first..end, insert);
let delta = if title.is_empty() {
Vec::new()
} else {
vec![TextDeltaOp::Insert {
insert: TextInsert::Text(title),
format: None,
}]
};
page.set_block_prop(block_id, "prop:title", SessionValue::Text(delta), now_ms)
.ok()
.flatten()
.is_some()
}
@@ -0,0 +1,250 @@
use blocksuite_playground_doc::session::PageDocSession;
use y_octo::{RelativePosition, SessionReadValue, TypePath, TypeTarget};
/// Which database text field currently owns the unified [`AnchoredInlineInput`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum DatabaseInlineTarget {
DatabaseTitle {
block_id: String,
},
ViewRename {
block_id: String,
view_id: String,
initial: String,
},
/// Live `Y.Text` cell (`title` or `rich-text`): incremental UTF-16 splice preserving marks
/// and `@reference` embeds, `Shift+Enter` newline, and 0 CRDT writes on no-op.
LiveRichCell {
block_id: String,
row_id: String,
column_id: String,
is_title: bool,
},
/// Validated scalar cell (`number`, `date`, `progress`, `link`).
ScalarCell {
block_id: String,
row_id: String,
column_id: String,
col_type: String,
initial: String,
},
RecordBody {
block_id: String,
row_id: String,
child_id: String,
},
ColumnRename {
block_id: String,
column_id: String,
initial: String,
},
SelectFilter {
block_id: String,
row_id: String,
column_id: String,
},
FilterValue {
block_id: String,
},
/// Title of the row shown in the open record peek, edited in its live `Y.Text` like a
/// `LiveRichCell` title.
RecordTitle {
block_id: String,
row_id: String,
},
/// Text field of a toolbar popover that writes view state only.
ViewField {
block_id: String,
field: ViewTextField,
},
}
/// Field of a [`DatabaseInlineTarget::ViewField`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ViewTextField {
Search,
GroupName,
}
impl DatabaseInlineTarget {
pub(crate) fn block_id(&self) -> &str {
match self {
Self::DatabaseTitle { block_id }
| Self::ViewRename { block_id, .. }
| Self::LiveRichCell { block_id, .. }
| Self::RecordBody { block_id, .. }
| Self::ScalarCell { block_id, .. }
| Self::ColumnRename { block_id, .. }
| Self::SelectFilter { block_id, .. }
| Self::FilterValue { block_id }
| Self::RecordTitle { block_id, .. }
| Self::ViewField { block_id, .. } => block_id,
}
}
/// The live `Y.Text` that each keystroke splices into, as `(block_id, row_id, column_id,
/// is_title)`.
pub(crate) fn live_text(&self) -> Option<(&str, &str, &str, bool)> {
match self {
Self::LiveRichCell {
block_id,
row_id,
column_id,
is_title,
} => Some((block_id, row_id, column_id, *is_title)),
Self::RecordTitle { block_id, row_id } => Some((block_id, row_id, "", true)),
_ => None,
}
}
pub(super) fn tracks_text(&self) -> bool {
matches!(self, Self::RecordBody { .. } | Self::DatabaseTitle { .. })
|| self.live_text().is_some()
}
fn paragraph_text(&self, page: &PageDocSession) -> Option<TypeTarget> {
let (block_id, prop) = match self {
Self::RecordBody { child_id, .. } => (child_id, "prop:text"),
Self::DatabaseTitle { block_id } => (block_id, "prop:title"),
_ => return None,
};
let block = TypeTarget::Path(TypePath::root("blocks").key(block_id));
match page.inner().get_map_value(&block, prop).ok()?? {
SessionReadValue::Text(id) => Some(TypeTarget::Identity(id)),
_ => None,
}
}
pub(super) fn encode_anchor(
&self,
page: &PageDocSession,
offset: usize,
) -> Option<RelativePosition> {
if let Some((block, row, col, title)) = self.live_text() {
return page
.encode_database_cell_relative_position(block, row, col, title, offset as u64)
.ok()
.flatten();
}
let target = self.paragraph_text(page)?;
let len = page.inner().read_text_len(&target).ok()?;
page.inner()
.create_relative_position(&target, len.min(offset as u64), -1)
.ok()
}
pub(super) fn resolve_anchor(
&self,
page: &PageDocSession,
pos: &RelativePosition,
) -> Option<usize> {
if let Some((block, row, col, title)) = self.live_text() {
return page
.resolve_database_cell_relative_position(block, row, col, title, pos)
.ok()
.flatten()
.map(|i| i as usize);
}
let target = self.paragraph_text(page)?;
let absolute = page.inner().resolve_relative_position(pos, true)?;
(target == TypeTarget::Identity(absolute.r#type)).then_some(absolute.index as usize)
}
pub(crate) fn is_popover_field(&self) -> bool {
matches!(
self,
Self::ViewRename { .. }
| Self::ColumnRename { .. }
| Self::SelectFilter { .. }
| Self::FilterValue { .. }
| Self::RecordBody { .. }
| Self::RecordTitle { .. }
| Self::ViewField { .. }
)
}
pub(crate) fn same_slot(&self, other: &Self) -> bool {
match (self, other) {
(
Self::LiveRichCell {
block_id: b1,
row_id: r1,
column_id: c1,
is_title: t1,
},
Self::LiveRichCell {
block_id: b2,
row_id: r2,
column_id: c2,
is_title: t2,
},
) => b1 == b2 && r1 == r2 && c1 == c2 && t1 == t2,
(
Self::ScalarCell {
block_id: b1,
row_id: r1,
column_id: c1,
col_type: ty1,
..
},
Self::ScalarCell {
block_id: b2,
row_id: r2,
column_id: c2,
col_type: ty2,
..
},
) => b1 == b2 && r1 == r2 && c1 == c2 && ty1 == ty2,
(
Self::ColumnRename {
block_id: b1,
column_id: c1,
..
},
Self::ColumnRename {
block_id: b2,
column_id: c2,
..
},
) => b1 == b2 && c1 == c2,
(
Self::SelectFilter {
block_id: b1,
row_id: r1,
column_id: c1,
},
Self::SelectFilter {
block_id: b2,
row_id: r2,
column_id: c2,
},
) => b1 == b2 && r1 == r2 && c1 == c2,
(Self::FilterValue { block_id: b1 }, Self::FilterValue { block_id: b2 }) => b1 == b2,
(
Self::RecordTitle {
block_id: b1,
row_id: r1,
},
Self::RecordTitle {
block_id: b2,
row_id: r2,
},
) => b1 == b2 && r1 == r2,
(
Self::ViewRename {
block_id: b1,
view_id: v1,
..
},
Self::ViewRename {
block_id: b2,
view_id: v2,
..
},
) => b1 == b2 && v1 == v2,
(Self::DatabaseTitle { .. }, Self::DatabaseTitle { .. })
| (Self::RecordBody { .. }, Self::RecordBody { .. })
| (Self::ViewField { .. }, Self::ViewField { .. }) => self == other,
_ => false,
}
}
}
@@ -61,17 +61,24 @@ impl PlaygroundView {
{
return self.database_authoring_input_edit(window, cx, |a| a.input.replace(None, "\n"));
}
if cmd && key == "a" {
if cmd && key == "a" && self.database_input.is_some() {
return self.database_authoring_input_edit(window, cx, |a| {
a.input.select_all();
None
});
}
if self.database_input.is_none()
&& let Some(nav) = navigation_key(key, m.shift)
&& self.database_navigation_ready(&block_id)
{
return self.dispatch_database_navigation(&block_id, nav, window, cx);
if self.database_input.is_none() && self.database_navigation_ready(&block_id) {
if cmd && matches!(key, "c" | "v") && self.database_focused_cell(&block_id).is_some() {
return self.database_clipboard_key(&block_id, key, cx);
}
let nav = if cmd && key == "a" {
Some(DatabaseNavKey::SelectAll)
} else {
navigation_key(key, m.shift)
};
if let Some(nav) = nav {
return self.dispatch_database_navigation(&block_id, nav, window, cx);
}
}
if matches!(
key,
@@ -96,9 +103,11 @@ impl PlaygroundView {
if self.database_input.as_ref().is_some_and(|d| {
matches!(
d.target,
DatabaseInlineTarget::LiveRichCell { .. }
DatabaseInlineTarget::DatabaseTitle { .. }
| DatabaseInlineTarget::LiveRichCell { .. }
| DatabaseInlineTarget::RecordBody { .. }
| DatabaseInlineTarget::RecordTitle { .. }
| DatabaseInlineTarget::ViewRename { .. }
)
}) && auth_key == DatabaseAuthoringKey::Enter
{
@@ -171,9 +180,11 @@ impl PlaygroundView {
if self.database_input.as_ref().is_some_and(|d| {
matches!(
d.target,
DatabaseInlineTarget::LiveRichCell { .. }
DatabaseInlineTarget::DatabaseTitle { .. }
| DatabaseInlineTarget::LiveRichCell { .. }
| DatabaseInlineTarget::RecordBody { .. }
| DatabaseInlineTarget::RecordTitle { .. }
| DatabaseInlineTarget::ViewRename { .. }
)
}) {
return self.finish_inline_targets(
@@ -280,6 +291,8 @@ impl PlaygroundView {
let a = &st.authoring;
self.flow.database_state.has_table_focus(block_id)
&& !st.more_views_open
&& !a.title_editing
&& a.view_menu.is_none()
&& a.column_menu.is_none()
&& a.row_menu.is_none()
&& a.lane_menu.is_none()
@@ -385,6 +398,12 @@ impl PlaygroundView {
.database_state
.prune_row_selection(&bid, &db, &self.page_titles, &offset_at);
let a = self.flow.database_state.authoring_mut(&bid);
if a.view_menu
.as_ref()
.is_some_and(|menu| !db.views.iter().any(|view| view.id == menu.view_id))
{
a.view_menu = None;
}
if let Some(cm) = &a.column_menu
&& cm.column_id != "title"
&& !db.columns.iter().any(|c| c.id == cm.column_id)
@@ -463,12 +482,17 @@ impl PlaygroundView {
/// The Table navigation key that `key` (with `shift`) stands for.
fn navigation_key(key: &str, shift: bool) -> Option<DatabaseNavKey> {
Some(match key {
"up" if shift => DatabaseNavKey::ExtendUp,
"up" => DatabaseNavKey::Up,
"down" if shift => DatabaseNavKey::ExtendDown,
"down" => DatabaseNavKey::Down,
"left" if shift => DatabaseNavKey::ExtendLeft,
"left" => DatabaseNavKey::Left,
"right" if shift => DatabaseNavKey::ExtendRight,
"right" => DatabaseNavKey::Right,
"tab" if shift => DatabaseNavKey::ShiftTab,
"tab" => DatabaseNavKey::Tab,
"enter" if shift => DatabaseNavKey::InsertBelow,
"enter" => DatabaseNavKey::Enter,
"backspace" | "delete" => DatabaseNavKey::Delete,
"escape" => DatabaseNavKey::Escape,
@@ -1,6 +1,7 @@
//! Desktop interactive mouse, drag, keyboard, and IME wiring between [`PlaygroundView`]
//! and `blocksuite_editor::database` authoring controllers.
mod clipboard;
mod date_cell;
mod dnd;
mod dnd_grouped;
@@ -10,6 +11,7 @@ mod hover;
mod hover_ops;
mod inline;
mod inline_splice;
mod inline_target;
mod kanban_lane_drag;
mod keys;
mod paint;
@@ -51,6 +53,8 @@ mod tests_scalar_edgeless_calendar;
#[cfg(test)]
mod tests_sideways_scroll_controls;
#[cfg(test)]
mod tests_title_menus_and_keys;
#[cfg(test)]
mod tests_view_controls;
#[cfg(test)]
mod tests_view_controls_board;
@@ -155,6 +159,8 @@ impl PlaygroundView {
let st = self.flow.database_state.state_for(&id);
let a = &st.authoring;
if st.more_views_open
|| a.title_editing
|| a.view_menu.is_some()
|| a.column_menu.is_some()
|| a.row_menu.is_some()
|| a.lane_menu.is_some()
@@ -381,7 +387,9 @@ impl PlaygroundView {
.active_cell
.as_ref()
.is_some_and(|ed| ed.calendar_day_index.is_some());
if st.authoring.column_menu.is_some()
if st.authoring.title_editing
|| st.authoring.view_menu.is_some()
|| st.authoring.column_menu.is_some()
|| st.authoring.row_menu.is_some()
|| st.authoring.lane_menu.is_some()
|| st.authoring.calc_menu.is_some()
@@ -52,7 +52,7 @@ impl InlineBoxLayout {
let display = buf.display_text();
let style = InlineStyle::new(FONT_SANS, font_size, font_weight, palette.text_primary);
let inner_w = (rect.w - 16.0).max(INLINE_CARET_WIDTH_PX);
let single_line = rect.h <= 34.5;
let single_line = !buf.multiline || rect.h <= 34.5;
let lh = if single_line { rect.h } else { 20.0 };
let wrap_w = if single_line { f32::INFINITY } else { inner_w };
let c = palette.text_primary;
@@ -324,14 +324,17 @@ impl PlaygroundView {
return out;
}
let clipped = FlowRect::new(left, cell_world.y, right - left, cell_world.h);
let title = matches!(
session.target,
super::inline::DatabaseInlineTarget::DatabaseTitle { .. }
);
let mut ring = div()
.absolute()
.left(px(v.column_x + clipped.x))
.top(px(clipped.y - v.scroll_y))
.w(px(clipped.w))
.h(px(clipped.h))
.border(px(1.5))
.border_color(palette.brand);
.when(!title, |el| el.border(px(1.5)).border_color(palette.brand));
if v.fully_visible(&clipped) {
ring = ring
.snapshot("page.database_cell_focus", Some(PAGE_SURFACE_ID))
@@ -421,7 +424,11 @@ impl PlaygroundView {
clipped.w,
cell_world.h,
);
let (font_px, weight) = inline_cell_font(&session.target, cell_world.h);
let (font_px, weight) = if title {
blocksuite_editor::database::DATABASE_TITLE_FONT
} else {
inline_cell_font(&session.target, cell_world.h)
};
out.extend(paint_inline_box_elements(
&session.anchored.input,
&session.scroll_x,
@@ -450,6 +457,28 @@ impl PlaygroundView {
if self.database_record_sheet.is_some() {
return Vec::new();
}
if self.mode == crate::PlaygroundMode::Edgeless
&& let Some(session) = self.database_input.as_ref()
&& matches!(
session.target,
super::inline::DatabaseInlineTarget::DatabaseTitle { .. }
)
&& let Some((rect, (font, weight))) = self.database_inline_screen_box(window)
{
let (dx, dy) = self.view_window_offset();
return paint_inline_box_elements(
&session.anchored.input,
&session.scroll_x,
&session.laid_cache,
rect.translated(-dx, -dy),
font,
weight,
&self.theme.palette(),
self.caret_blink_alpha(self.now_ms(cx)),
None,
window,
);
}
self.record_picker_elements(layout, window, cx)
}
@@ -20,11 +20,8 @@ impl PlaygroundView {
return false;
};
let state = self.flow.database_state.state_for(&block_id);
let Some(panel) = state.authoring.toolbar_panel else {
if state.authoring.column_menu.is_none() && state.authoring.toolbar_panel.is_none() {
return self.scroll_open_select_popover(dy, cx);
};
if panel == database::ActiveToolbarPanel::Filter {
return false;
}
let snap = self.snapshot.clone();
let Some(db) = snap
@@ -33,13 +30,24 @@ impl PlaygroundView {
else {
return false;
};
let max = (36.0 + 28.0 * database::panel_row_count(db.columns.len(), panel) as f32
- height)
.max(0.0);
let max = if let Some(menu) = &state.authoring.column_menu {
database::column_menu_scroll_limit(db, menu, height)
} else if let Some(panel) = state.authoring.toolbar_panel
&& panel != database::ActiveToolbarPanel::Filter
{
(36.0 + 28.0 * database::panel_row_count(db.columns.len(), panel) as f32 - height)
.max(0.0)
} else {
return false;
};
let auth = self.flow.database_state.authoring_mut(&block_id);
let mut axis = blocksuite_editor::scroll::ScrollAxis::new(auth.toolbar_scroll_y, max);
if axis.apply(dy) {
auth.toolbar_scroll_y = axis.offset;
if let Some(menu) = &mut auth.column_menu {
menu.type_submenu_open = false;
auth.number_format_open = false;
}
cx.notify();
return true;
}
@@ -331,6 +339,16 @@ impl PlaygroundView {
};
let hit = &overlay.hits[index];
if matches!(
hit.kind,
DatabaseAuthoringHitKind::ViewMenu(
database::ViewMenuAction::MoveLeft
| database::ViewMenuAction::MoveRight
| database::ViewMenuAction::Duplicate
)
) {
let _ = self.database_authoring_input_edit(window, cx, |a| a.input.unmark());
}
if let database::DatabaseAuthoringHitKind::SwitchView { view_id } = &hit.kind {
self.set_database_active_view(&block_id, view_id, cx);
self.editor_focus.focus(window, cx);
@@ -232,6 +232,7 @@ impl PlaygroundView {
.is_some_and(|st| {
let a = &st.authoring;
st.more_views_open
|| a.view_menu.is_some()
|| a.column_menu.is_some()
|| a.row_menu.is_some()
|| a.lane_menu.is_some()
@@ -0,0 +1,736 @@
use blocksuite_editor::database::{
ColumnAction, DatabaseAuthoringHitKind as Hit, NumberFormat, ViewMenuAction,
};
use blocksuite_playground_doc::{
read::{DatabaseCellValue, DatabaseData},
schema::{DatabaseCellSpec, DatabaseColumnSpec},
};
use serde_json::json;
use ui::{
App, ClipboardItem, EntityInputHandler, Modifiers, PlatformInput, ScrollDelta, ScrollEvent,
ScrollSource, TouchPhase, Window, point, px,
};
use crate::{HOME_PAGE_ID, PlaygroundOptions, PlaygroundView, room_client::DocState};
use super::{
tests::{build_e2e_database_doc, key_event, read_db, screen_pt_for_auth_hit, undo_modifiers},
tests_inline_and_popovers::open_authoring_window,
};
pub(super) fn fixture() -> (DocState, String) {
let (mut doc, db) = build_e2e_database_doc();
let page = doc.workspace.page_mut(HOME_PAGE_ID).unwrap();
page.add_database_column(
&db,
Some("v-table"),
DatabaseColumnSpec {
id: "amount".into(),
column_type: "number".into(),
name: "Amount".into(),
data: json!({"format": "number", "decimal": 2, "extension": "keep"}),
},
Some(2),
10,
)
.unwrap();
page.set_database_cell_value(&db, "r1", "amount", DatabaseCellSpec::Number(1250.25), 11)
.unwrap();
page.set_database_cell_value(
&db,
"r1",
"c-note",
DatabaseCellSpec::RichText("Initial note".into()),
12,
)
.unwrap();
page.add_database_row_with_cells(
&db,
"r2",
"Review design",
vec![
("amount".into(), DatabaseCellSpec::Number(75.5)),
("c-note".into(), DatabaseCellSpec::RichText("Ready".into())),
],
13,
)
.unwrap();
page.stop_capturing().unwrap();
(doc, db)
}
struct Table {
platform: std::rc::Rc<ui::HeadlessPlatform>,
app: ui::ApplicationHandle,
win: ui::WindowHandle<PlaygroundView>,
input: ui::HeadlessWindow,
db: String,
}
impl Table {
fn new() -> Self {
let (doc, db) = fixture();
Self::open(doc, db, 800)
}
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 {
platform,
app,
win,
input,
db,
};
table.frame();
table
}
fn frame(&self) {
self.platform.run_until_parked();
self.input.request_frame();
self.platform.run_until_parked();
}
fn read(&self) -> DatabaseData {
self.app
.update(|cx| read_db(self.win.read(cx).unwrap(), &self.db))
}
fn click(&self, kind: impl Fn(&Hit) -> bool) {
let point = self.app.update(|cx| {
self.win
.update(cx, |view, window, _| {
screen_pt_for_auth_hit(view, window, &self.db, kind)
})
.unwrap()
});
self.input.simulate_click(point);
self.frame();
}
fn update<R>(
&self,
f: impl FnOnce(&mut PlaygroundView, &mut Window, &mut ui::Context<PlaygroundView>) -> R,
) -> R {
let result = self.app.update(|cx| self.win.update(cx, f).unwrap());
self.frame();
result
}
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) {
self.key("z", undo_modifiers());
}
fn clipboard(&self, f: impl FnOnce(&mut App)) {
self.app.update(f);
}
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)
});
self.key("escape", Modifiers::default());
}
fn paste_text(&self, text: &str) {
self.clipboard(|cx| cx.write_to_clipboard(ClipboardItem::new_string(text.into())));
self.key("v", undo_modifiers());
}
fn open_number_menu(&self) {
self.click(|hit| matches!(hit, Hit::OpenColumnMenu { column_id } if column_id == "amount"));
}
fn open_view_menu(&self) {
self.click(|hit| matches!(hit, Hit::OpenViewMenu { .. }));
}
}
#[test]
fn database_header_title_edit_and_view_menu_actions_undo() {
let table = Table::new();
table.click(|hit| matches!(hit, Hit::EditDatabaseTitle));
table.update(|view, window, cx| {
view.replace_and_mark_text_in_range(Some(0..11), "huà", None, window, cx);
assert_eq!(view.marked_text_range(window, cx), Some(0..3));
assert_eq!(read_db(view, &table.db).title.plain, "E2E Roadmap");
view.replace_text_in_range(None, "计划🧭", window, cx);
});
table.key("enter", Modifiers::default());
assert_eq!(table.read().title.plain, "计划🧭");
table.undo();
assert_eq!(table.read().title.plain, "E2E Roadmap");
table.open_view_menu();
table.key("a", undo_modifiers());
table.update(|view, window, cx| view.replace_text_in_range(None, "Delivery", window, cx));
table.key("enter", Modifiers::default());
assert_eq!(table.read().views[0].name, "Delivery");
table.undo();
assert_eq!(table.read().views[0].name, "Table");
for (action, first, count) in [
(ViewMenuAction::MoveRight, "v-cal", 2),
(ViewMenuAction::Duplicate, "v-table", 3),
(ViewMenuAction::Delete, "v-cal", 1),
] {
table.open_view_menu();
table.click(|hit| *hit == Hit::ViewMenu(action));
let db = table.read();
assert_eq!(db.views.len(), count);
assert_eq!(db.views[0].id, first);
if action == ViewMenuAction::Delete {
table.open_view_menu();
table.update(|view, window, _| {
let layout = view.flow_layout().unwrap();
let (_, overlay) = view.database_popover_overlay(&layout, window).unwrap();
assert!(
!overlay
.hits
.iter()
.any(|hit| hit.kind == Hit::ViewMenu(ViewMenuAction::Delete))
);
});
table.key("escape", Modifiers::default());
}
table.undo();
assert_eq!(table.read().views.len(), 2);
table.update(|view, _, cx| view.set_database_active_view(&table.db, "v-table", cx));
}
table.update(|view, _, cx| view.set_page_readonly(true, cx));
table.update(|view, window, cx| {
let hit = view
.database_authoring_hits(&table.db)
.iter()
.find(|hit| hit.kind == Hit::EditDatabaseTitle)
.cloned()
.unwrap();
assert!(!view.try_click_database_authoring(
&table.db,
hit.rect.x + 2.0,
hit.rect.y + 2.0,
1,
Some(window),
cx
));
assert!(view.database_input.is_none());
});
}
#[test]
fn number_menu_preserves_cell_values_and_applies_column_actions() {
let table = Table::new();
for (format, wire) in [
(NumberFormat::Percent, "percent"),
(NumberFormat::WithCommas, "numberWithCommas"),
(NumberFormat::Currency, "currencyUSD"),
(NumberFormat::Number, "number"),
] {
table.open_number_menu();
table.click(|hit| *hit == Hit::ColumnAction(ColumnAction::ToggleNumberFormat));
table.click(|hit| *hit == Hit::ColumnAction(ColumnAction::SetNumberFormat(format)));
let db = table.read();
let amount = db.columns.iter().find(|col| col.id == "amount").unwrap();
assert_eq!(
amount.data,
json!({"format": wire, "decimal": 2, "extension": "keep"})
);
assert_eq!(
db.cells[&("r1".into(), "amount".into())].as_f64(),
Some(1250.25)
);
}
table.undo();
assert_eq!(
table
.read()
.columns
.iter()
.find(|col| col.id == "amount")
.unwrap()
.data["format"],
"currencyUSD"
);
table.open_number_menu();
table.click(|hit| *hit == Hit::ColumnAction(ColumnAction::Duplicate));
let db = table.read();
let duplicate = db
.columns
.iter()
.find(|col| col.name == "Amount(1)")
.unwrap();
assert_eq!(duplicate.data["format"], "currencyUSD");
assert_eq!(
db.cells[&("r2".into(), duplicate.id.clone())].as_f64(),
Some(75.5)
);
table.undo();
assert!(
!table
.read()
.columns
.iter()
.any(|col| col.name == "Amount(1)")
);
for descending in [true, false] {
table.open_number_menu();
table.click(|hit| *hit == Hit::ColumnAction(ColumnAction::Sort { descending }));
let view = &table.read().views[0];
let sort = view.sort.as_ref().unwrap();
assert_eq!(sort["sortBy"][0]["ref"]["name"], "amount");
assert_eq!(sort["sortBy"][0]["desc"], descending);
}
let before = table.read().views[0].filter.clone();
table.open_number_menu();
table.click(|hit| *hit == Hit::ColumnAction(ColumnAction::Filter));
let read = table.read();
let rules = read.views[0].filter.as_ref().unwrap()["conditions"]
.as_array()
.unwrap();
assert_eq!(rules.len(), 1);
assert_eq!(
rules[0],
json!({
"type": "filter",
"left": {"type": "ref", "name": "amount"},
"function": blocksuite_editor::database::default_operator_for_column_type("number"),
"args": [],
})
);
table.update(|view, _, _| {
let auth = view.flow.database_state.state_for(&table.db).authoring;
assert_eq!(auth.filter_draft.column_id, "amount");
assert_eq!(
auth.toolbar_panel,
Some(blocksuite_editor::database::ActiveToolbarPanel::Filter)
);
});
table.undo();
assert_eq!(table.read().views[0].filter, before);
}
#[test]
fn keyboard_range_copy_paste_clear_select_all_and_insert_row() {
let table = Table::new();
table.click(|hit| matches!(hit, Hit::EditCell { row_id, column_id, .. } if row_id == "r1" && column_id == "amount"));
table.key("escape", Modifiers::default());
let shift = Modifiers {
shift: true,
..Default::default()
};
table.key("right", shift);
table.key("down", shift);
table.key("c", undo_modifiers());
table.clipboard(|cx| {
assert_eq!(
cx.read_from_clipboard()
.and_then(|item| item.text())
.as_deref(),
Some("1250.25\tInitial note\n75.5\tReady")
)
});
table.clipboard(|cx| {
cx.write_to_clipboard(ClipboardItem::new_string("1\tStart\n2\tFinish".into()))
});
table.key("v", undo_modifiers());
for (row, number, note) in [("r1", 1.0, "Start"), ("r2", 2.0, "Finish")] {
let db = table.read();
assert_eq!(
db.cells[&(row.into(), "amount".into())].as_f64(),
Some(number)
);
assert_eq!(
db.cells[&(row.into(), "c-note".into())].as_str(),
Some(note)
);
}
table.key("backspace", Modifiers::default());
let db = table.read();
for row in ["r1", "r2"] {
for col in ["amount", "c-note"] {
assert!(
db.cells
.get(&(row.into(), col.into()))
.is_none_or(|value| *value == DatabaseCellValue::Null)
);
}
}
table.undo();
assert_eq!(
table.read().cells[&("r2".into(), "amount".into())].as_f64(),
Some(2.0)
);
table.undo();
assert_eq!(
table.read().cells[&("r2".into(), "amount".into())].as_f64(),
Some(75.5)
);
table.key("enter", shift);
let db = table.read();
assert_eq!(db.rows.len(), 3);
let inserted = &db.rows[2].row_id;
table.update(|view, _, _| {
assert_eq!(
view.database_focused_cell(&table.db),
Some((inserted.as_str(), "title"))
)
});
table.key("escape", Modifiers::default());
table.key("a", undo_modifiers());
table.update(|view, _, _| {
assert_eq!(
view.flow
.database_state
.state_for(&table.db)
.selected_rows
.len(),
3
)
});
table.undo();
assert_eq!(table.read().rows.len(), 2);
}
#[test]
fn view_menu_actions_commit_unsubmitted_name_in_one_undo_step() {
let table = Table::new();
for (view_id, action, position, shadow) in [
("v-table", ViewMenuAction::MoveRight, 1, None),
("v-cal", ViewMenuAction::MoveLeft, 0, None),
("v-table", ViewMenuAction::Duplicate, 1, Some(0)),
] {
table.update(|view, _, cx| view.set_database_active_view(&table.db, view_id, cx));
let before = table.read().views;
table.open_view_menu();
table.key("a", undo_modifiers());
table.update(|view, window, cx| view.replace_text_in_range(None, "Milestones", window, cx));
assert_eq!(table.read().views, before);
table.click(|hit| *hit == Hit::ViewMenu(action));
let after = table.read().views;
assert_eq!(after[position].name, "Milestones");
if let Some(original) = shadow {
assert_eq!(after[original].id, view_id);
assert_eq!(after[original].name, "Milestones");
assert_ne!(after[position].id, view_id);
} else {
assert_eq!(after[position].id, view_id);
}
table.undo();
assert_eq!(table.read().views, before);
}
}
#[test]
fn paste_grows_from_focus_and_clips_or_tiles_rectangles_in_one_undo_step() {
let table = Table::new();
let before = table.read().cells;
let shift = Modifiers {
shift: true,
..Default::default()
};
for (extension, source, numbers, notes) in [
(
&[][..],
"1\tChanged A\n2\tChanged B",
[1.0, 2.0],
["Changed A", "Changed B"],
),
(
&["down"][..],
"1\tChanged A\n2\tChanged B",
[1.0, 2.0],
["Initial note", "Ready"],
),
(&["right", "down"][..], "7", [7.0, 7.0], ["7", "7"]),
] {
table.select_cell("r1", "amount");
for direction in extension {
table.key(direction, shift);
}
table.paste_text(source);
let after = table.read().cells;
for (i, row) in ["r1", "r2"].into_iter().enumerate() {
assert_eq!(
after[&(row.into(), "amount".into())].as_f64(),
Some(numbers[i])
);
assert_eq!(
after[&(row.into(), "c-note".into())].as_str(),
Some(notes[i])
);
}
table.undo();
assert_eq!(table.read().cells, before);
}
}
#[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();
let table = Table::open(doc, db, 360);
table.open_number_menu();
let position = table.update(|view, window, _| {
let layout = view.flow_layout().unwrap();
let (_, overlay) = view.database_popover_overlay(&layout, window).unwrap();
assert_eq!(f32::from(window.viewport_size().height), 360.0);
assert!(overlay.bounds.bottom() <= 360.0);
assert!(
!overlay
.hits
.iter()
.any(|hit| hit.kind == Hit::ColumnAction(ColumnAction::Duplicate))
);
point(
px(overlay.bounds.x + 45.0),
px(overlay.bounds.bottom() - 18.0),
)
});
for _ in 0..4 {
table
.input
.dispatch_input(PlatformInput::Scroll(ScrollEvent {
position,
delta: ScrollDelta::Pixels(point(px(0.0), px(-48.0))),
modifiers: Modifiers::default(),
touch_phase: TouchPhase::Moved,
source: ScrollSource::Pointer,
}));
table.frame();
}
table.update(|view, window, _| {
let layout = view.flow_layout().unwrap();
let (_, overlay) = view.database_popover_overlay(&layout, window).unwrap();
assert!(
overlay
.hits
.iter()
.any(|hit| matches!(hit.kind, Hit::ColumnMenuDelete { .. })
&& hit.rect.bottom() <= 360.0)
);
});
table.click(|hit| *hit == Hit::ColumnAction(ColumnAction::Duplicate));
assert!(
table
.read()
.columns
.iter()
.any(|column| column.name == "Amount(1)")
);
}