diff --git a/blocksuite/crates/playground/src/overlays/view_table_cell/controls_tests.rs b/blocksuite/crates/playground/src/overlays/view_table_cell/controls_tests.rs index edc51862b1..fddb1467c3 100644 --- a/blocksuite/crates/playground/src/overlays/view_table_cell/controls_tests.rs +++ b/blocksuite/crates/playground/src/overlays/view_table_cell/controls_tests.rs @@ -272,3 +272,115 @@ fn short_desktop_table_axis_menus_scroll_to_delete() { ); } } + +#[test] +fn table_cell_formats_and_wraps_selection_in_single_undo_steps() { + use ui::{EntityInputHandler, KeyDownEvent, Keystroke, Modifiers, PlatformInput}; + use y_octo::{Any, TextDeltaOp}; + + for (theme, name) in [ + (PlaygroundTheme::Light, "light"), + (PlaygroundTheme::Dark, "dark"), + ] { + let session = open_table( + 1280, + 800, + PlaygroundOptions { + theme, + ..Default::default() + }, + ); + let (x, y) = cell_point(&session, 0, 60.0, 18.0); + session.press(x, y, 3); + session.release(x, y); + let text = || { + table_data(&session).cells[&("row-0".into(), "col-0".into())] + .text + .clone() + }; + let has_mark = |mark| { + text().delta.iter().any(|op| matches!( + op, + TextDeltaOp::Insert { format: Some(attrs), .. } if attrs.get(mark) == Some(&Any::True) + )) + }; + save_evidence(&session, &format!("before-table-{name}.png")); + for (key, shift, mark) in [ + ("b", false, "bold"), + ("i", false, "italic"), + ("u", false, "underline"), + ("s", true, "strike"), + ("e", false, "code"), + ] { + let shortcut = || { + session + .headless + .dispatch_input(PlatformInput::KeyDown(KeyDownEvent { + keystroke: Keystroke { + key: key.into(), + modifiers: Modifiers { + platform: true, + control: true, + shift, + ..Default::default() + }, + key_char: None, + }, + is_held: false, + prefer_character_input: false, + })); + session.settle(); + }; + shortcut(); + assert!(has_mark(mark), "{mark}"); + shortcut(); + assert!(!has_mark(mark), "{mark} toggles off"); + session.undo(); + assert!(has_mark(mark), "{mark} returns in one undo"); + } + session.settle(); + save_evidence(&session, &format!("after-table-{name}.png")); + for (open, close) in [ + ("(", ")"), + ("[", "]"), + ("{", "}"), + ("\"", "\""), + ("'", "'"), + ("`", "`"), + ] { + session.view(|view, _| view.table_cell.as_mut().unwrap().input.select_all()); + session.key(open); + assert_eq!(text().plain, format!("{open}Item{close}")); + assert_eq!( + session.view(|view, _| view.active_table_cell().unwrap().input.selection.clone()), + 1..5 + ); + assert!(has_mark("bold")); + assert!(has_mark("code")); + session.undo(); + assert_eq!(text().plain, "Item"); + } + + session.app.update(|cx| { + session + .window + .update(cx, |view, window, cx| { + view.table_cell.as_mut().unwrap().input.select_all(); + view.replace_and_mark_text_in_range(None, "[", Some(1..1), window, cx); + }) + .unwrap(); + }); + session.key("["); + assert_eq!(text().plain, "Item", "preedit must not write a pair"); + session.key("escape"); + session.view(|view, _| view.table_cell.as_mut().unwrap().input.select(4..4)); + session.type_text("[["); + assert_eq!(text().plain, "Item@"); + assert!( + session + .settle() + .elements + .contains_key("overlay.linked_doc_menu") + ); + } +} diff --git a/blocksuite/crates/playground/src/overlays/view_table_cell/mod.rs b/blocksuite/crates/playground/src/overlays/view_table_cell/mod.rs index f5cc2a643d..94b76109bd 100644 --- a/blocksuite/crates/playground/src/overlays/view_table_cell/mod.rs +++ b/blocksuite/crates/playground/src/overlays/view_table_cell/mod.rs @@ -5,6 +5,7 @@ mod axis_drag; mod navigation; mod paint; mod pointer; +mod rich_edit; mod structure; mod toolbar; mod toolbar_popovers; diff --git a/blocksuite/crates/playground/src/overlays/view_table_cell/navigation.rs b/blocksuite/crates/playground/src/overlays/view_table_cell/navigation.rs index 006597755a..e989fa6577 100644 --- a/blocksuite/crates/playground/src/overlays/view_table_cell/navigation.rs +++ b/blocksuite/crates/playground/src/overlays/view_table_cell/navigation.rs @@ -36,6 +36,9 @@ impl PlaygroundView { } return false; } + if self.table_cell_rich_key(e, window, cx).is_some() { + return true; + } if m.shift && !cmd && !m.alt diff --git a/blocksuite/crates/playground/src/overlays/view_table_cell/rich_edit.rs b/blocksuite/crates/playground/src/overlays/view_table_cell/rich_edit.rs new file mode 100644 index 0000000000..bbd5804f8f --- /dev/null +++ b/blocksuite/crates/playground/src/overlays/view_table_cell/rich_edit.rs @@ -0,0 +1,121 @@ +use blocksuite_playground_doc::{read::BlockContent, session::split_delta}; +use ui::{Context, KeyDownEvent, Window}; +use y_octo::{Any, TextAttributes, TextDeltaOp, TextInsert}; + +use crate::PlaygroundView; + +impl PlaygroundView { + pub(super) fn table_cell_rich_key( + &mut self, + event: &KeyDownEvent, + window: &mut Window, + cx: &mut Context, + ) -> Option<()> { + let cell = self.table_cell.as_ref()?; + let selection = cell.input.selection.clone(); + if cell.area.is_some() || selection.is_empty() { + return None; + } + let stroke = &event.keystroke; + let modifiers = stroke.modifiers; + let command = modifiers.secondary(cx); + let block = cell.block_id.clone(); + let row = cell.row_id.clone(); + let column = cell.column_id.clone(); + let start = selection.start as u64; + let len = selection.len() as u64; + let mut delta = Vec::with_capacity(4); + if start > 0 { + delta.push(TextDeltaOp::Retain { + retain: start, + format: None, + }); + } + + let wrapped = if command && !modifiers.alt { + let mark = match (stroke.key.as_str(), modifiers.shift) { + ("b", false) => "bold", + ("i", false) => "italic", + ("u", false) => "underline", + ("s", true) => "strike", + ("e", false) => "code", + _ => return None, + }; + if self.table_is_readonly() { + return Some(()); + } + let BlockContent::Table(table) = &self.page_snapshot()?.block(&block)?.content else { + return None; + }; + let text = &table.cells.get(&(row.clone(), column.clone()))?.text; + let (_, tail) = split_delta(&text.delta, start).ok()?; + let (selected, _) = split_delta(&tail, len).ok()?; + let marked = selected.iter().all(|op| { + matches!( + op, + TextDeltaOp::Insert { format: Some(format), .. } + if format.get(mark) == Some(&Any::True) + ) + }); + let value = if marked { Any::Null } else { Any::True }; + delta.push(TextDeltaOp::Retain { + retain: len, + format: Some(TextAttributes::from([(mark.to_owned(), value)])), + }); + false + } else if !modifiers.platform && !modifiers.control && !self.table_is_readonly() { + let open = stroke.key_char.as_deref().unwrap_or(&stroke.key); + let close = match open { + "(" => ")", + "[" => "]", + "{" => "}", + "\"" | "'" | "`" => open, + _ => return None, + }; + delta.extend([ + TextDeltaOp::Insert { + insert: TextInsert::Text(open.into()), + format: None, + }, + TextDeltaOp::Retain { + retain: len, + format: None, + }, + TextDeltaOp::Insert { + insert: TextInsert::Text(close.into()), + format: None, + }, + ]); + true + } else { + return None; + }; + + let reversed = cell.input.reversed; + let now = self.now_ms(cx) as u64; + let result = self.page_mut().and_then(|page| { + page.stop_capturing()?; + let commit = page.apply_table_cell_text_delta(&block, &row, &column, &delta, now); + page.stop_capturing()?; + commit + }); + match result { + Ok(Some(commit)) => { + self.did_table_cell_commit(&block, commit); + self.sync_table_cell_from_snapshot(); + if wrapped { + self.table_cell_input(window, cx, |cell| { + cell.input.select(selection.start + 1..selection.end + 1); + cell.input.reversed = reversed; + }); + } else { + self.reset_caret_blink(cx); + cx.notify(); + } + } + Ok(None) => {} + Err(error) => eprintln!("table cell edit: {error}"), + } + Some(()) + } +} diff --git a/blocksuite/crates/playground/src/page_outline.rs b/blocksuite/crates/playground/src/page_outline.rs index e5d7f35e57..3bfa3908b4 100644 --- a/blocksuite/crates/playground/src/page_outline.rs +++ b/blocksuite/crates/playground/src/page_outline.rs @@ -1,6 +1,6 @@ //! Reading position of the Page outline: the heading that the outline marks as active. -use blocksuite_playground_doc::schema::ParagraphType; +use blocksuite_playground_doc::{read::BlockContent, schema::ParagraphType}; use crate::{PlaygroundMode, PlaygroundView, block_flow::FlowKind}; @@ -16,21 +16,91 @@ pub(crate) struct OutlinePin { scroll_y: Option, } -fn is_heading(kind: &FlowKind) -> bool { +fn is_heading_type(kind: ParagraphType) -> bool { matches!( kind, - FlowKind::Paragraph( - ParagraphType::H1 - | ParagraphType::H2 - | ParagraphType::H3 - | ParagraphType::H4 - | ParagraphType::H5 - | ParagraphType::H6 - ) + ParagraphType::H1 + | ParagraphType::H2 + | ParagraphType::H3 + | ParagraphType::H4 + | ParagraphType::H5 + | ParagraphType::H6 ) } +fn is_heading(kind: &FlowKind) -> bool { + matches!(kind, FlowKind::Paragraph(kind) if is_heading_type(*kind)) +} + impl PlaygroundView { + /// Move a Page outline heading and its children to the target heading's sibling list. + pub fn move_outline_heading( + &mut self, + source: &str, + target: &str, + after: bool, + cx: &mut ui::Context, + ) { + if source == target || self.page_readonly() || self.mode != PlaygroundMode::Page { + return; + } + let Some(root) = self.page_snapshot().and_then(|page| page.root.as_ref()) else { + return; + }; + let heading_location = |id: &str| { + root.children + .iter() + .filter(|node| node.is_page_visible_note()) + .flat_map(|note| note.walk()) + .find_map(|parent| { + parent + .children + .iter() + .enumerate() + .find_map(|(index, child)| { + (child.id == id + && matches!(child.content, BlockContent::Paragraph { kind, .. } + if is_heading_type(kind))) + .then_some((parent, index, child)) + }) + }) + }; + let Some((old_parent, source_index, heading)) = heading_location(source) else { + return; + }; + let Some((parent, target_index, _)) = heading_location(target) else { + return; + }; + if heading.walk().any(|node| node.id == parent.id) { + return; + } + let mut index = target_index + usize::from(after); + if old_parent.id == parent.id { + index -= usize::from(source_index < index); + if index == source_index { + return; + } + } + let (old_parent, parent) = (old_parent.id.clone(), parent.id.clone()); + let now = self.now_ms(cx) as u64; + let commit = self + .page_mut() + .and_then(|page| page.reparent_block(source, &old_parent, &parent, index as u64, now)); + match commit { + Ok(Some(commit)) => { + if let Some(id) = self.page_id.clone() { + self.send_page_update(&id, commit.update); + } + self.capture_reading_anchor(); + self.refresh_document(); + self.resolve_remote_selection(cx); + cx.notify(); + } + Ok(None) => {} + Err(error) => eprintln!("outline move: {error}"), + } + } + /// Scroll the page to an outline entry: the title (`None`) to the top, a heading to /// 24 px below the top edge. The entry stays active until the page scrolls again. pub fn reveal_outline_heading(&mut self, heading: Option, cx: &mut ui::Context) { diff --git a/packages/frontend/desktop/src/views_extra/right_sidebar/frame_panel.rs b/packages/frontend/desktop/src/views_extra/right_sidebar/frame_panel.rs index bd6778a00f..2d4ce4952e 100644 --- a/packages/frontend/desktop/src/views_extra/right_sidebar/frame_panel.rs +++ b/packages/frontend/desktop/src/views_extra/right_sidebar/frame_panel.rs @@ -3,6 +3,7 @@ use std::{ rc::Rc, }; +use super::{FrameTitleInput, ReorderList, frame_order_updates, write_frame_order}; use blocksuite_editor::{ block_flow::FormFactor, edgeless::{ @@ -12,7 +13,11 @@ use blocksuite_editor::{ }, scroll::{ScrollAxis, wheel_delta}, }; -use blocksuite_playground_doc::read::{BlockContent, PageSnapshot}; +use blocksuite_playground_doc::{ + DocResult, + read::{BlockContent, PageSnapshot}, + session::PageDocSession, +}; use playground::{PlaygroundMode, PlaygroundView, edgeless::PRESENTATION_ICON}; use ui::{ App, Bounds, ContentMask, Context, Direction, ElementId, Entity, EntityId, FontWeight, @@ -66,6 +71,7 @@ struct PanelState { preview: Option>, scroll: f32, viewport_height: Option, + title: Option<(String, Entity)>, } impl PanelState { @@ -172,6 +178,51 @@ impl Target { (editor.read(app).active_doc_id() == Some(self.doc.as_str())).then_some(editor) } + fn writable_editor( + &self, + shell: &DesktopShellView, + app: &App, + ) -> Option> { + let editor = self.active_editor(shell, app)?; + let view = editor.read(app); + (!shell.state.store.is_readonly_sqlite() + && !view.edgeless_readonly() + && !view.page_readonly()) + .then_some(editor) + } + + fn edit( + &self, + shell: &Entity, + app: &mut App, + prepare: impl FnOnce(&PageSnapshot) -> DocResult>, + edit: impl FnOnce(T, &mut PageDocSession) -> DocResult, + ) { + let Some(editor) = self.writable_editor(shell.read(app), app) else { + return; + }; + editor.update(app, |view, cx| { + let Some(snapshot) = view.page_snapshot() else { + return; + }; + let prepared = match prepare(snapshot) { + Ok(Some(prepared)) => prepared, + Ok(None) => return, + Err(error) => { + eprintln!("frame edit: {error}"); + return; + } + }; + view.edit_document(cx, |doc| { + if let Some(page) = doc.workspace.page_mut(&self.doc) + && let Err(error) = edit(prepared, page) + { + eprintln!("frame edit: {error}"); + } + }); + }); + } + fn switch_mode( shell: &mut DesktopShellView, editor: &Entity, @@ -325,10 +376,20 @@ fn frame_list( target: &Target, shell: &Entity, palette: DesktopPalette, - window: &Window, - app: &App, + window: &mut Window, + app: &mut App, ) -> impl IntoElement { + let reorder = window.use_keyed_state( + ElementId::NamedInteger( + "inspector-frame-reorder".into(), + ui::hash(&(&target.workspace, &target.doc, target.pane, target.tab)), + ), + app, + |_, cx| ReorderList::new(cx), + ); + let reorder = reorder.read(app); let data = state.read(app); + let writable = target.writable_editor(shell.read(app), app).is_some(); let editor = target.active_editor(shell.read(app), app); let selection = editor .as_ref() @@ -348,7 +409,7 @@ fn frame_list( .flex_col(); for index in slice.visible_range { let frame = &data.frames[index]; - rows = rows.child(div().h(px(ROW_STRIDE)).flex_shrink(0.0).child(frame_card( + let card = frame_card( frame, index, selection.is_some_and(|selection| selection.contains(&frame.id)), @@ -356,13 +417,41 @@ fn frame_list( palette, target.clone(), shell.clone(), - ))); + writable.then_some(state), + data.title + .as_ref() + .filter(|(id, _)| id == &frame.id) + .map(|(_, input)| input), + ); + let mut row = div() + .id(("frame-order", ui::hash(&frame.id))) + .h(px(ROW_STRIDE)) + .flex_shrink(0.0) + .child(card); + if writable && data.title.is_none() { + let (id, target, shell) = (frame.id.clone(), target.clone(), shell.clone()); + row = reorder.row( + row, + &frame.id, + palette.accent, + move |source, after, _, app| { + target.edit( + &shell, + app, + |snapshot| frame_order_updates(snapshot, source, &id, after), + write_frame_order, + ); + }, + ); + } + rows = rows.child(row); } let measure_state = state.clone(); let scroll_state = state.clone(); let total_height = list.total_height(); let (target, shell) = (target.clone(), shell.clone()); - div() + reorder + .container(div()) .id(LIST_ID) .snapshot(LIST_ID, Some("desktop.inspector")) .relative() @@ -422,6 +511,7 @@ fn frame_list( ) } +#[allow(clippy::too_many_arguments)] fn frame_card( frame: &PresentationFrame, index: usize, @@ -430,6 +520,8 @@ fn frame_card( palette: DesktopPalette, target: Target, shell: Entity, + state: Option<&Entity>, + input: Option<&Entity>, ) -> impl IntoElement { let id = frame.id.clone(); let key = ui::snap_id!("desktop.inspector.frame.item.{id}"); @@ -438,6 +530,68 @@ fn frame_card( } else { SharedString::new(&frame.title) }; + let title_element = if let Some(input) = input { + input.clone().into_any_element() + } else { + let mut label = div() + .min_w_0() + .text_ellipsis() + .id(("frame-title", ui::hash(&id))) + .snapshot( + ui::snap_id!("desktop.inspector.frame.title.{id}"), + Some(LIST_ID), + ) + .child(title.clone()); + if let Some(state) = state { + let (target, shell, state) = (target.clone(), shell.clone(), state.clone()); + let (id, original) = (id.clone(), frame.title.clone()); + label = label.on_click(move |event, window, app| { + if event.click_count() < 2 || target.writable_editor(shell.read(app), app).is_none() + { + return; + } + app.stop_propagation(); + let (target, shell, id, original) = + (target.clone(), shell.clone(), id.clone(), original.clone()); + let active_id = id.clone(); + let panel = state.downgrade(); + let input = FrameTitleInput::open( + original.clone(), + palette, + window, + app, + move |value, app| { + let _ = panel.update(app, |state, cx| { + state.title = None; + cx.notify(); + }); + if let Some(value) = value.filter(|value| *value != original) { + target.edit( + &shell, + app, + |snapshot| { + Ok(matches!( + snapshot.block(&id).map(|node| &node.content), + Some(BlockContent::Frame { .. }) + ) + .then_some(value)) + }, + |value, page| { + page.set_block_title_text(&id, &value, 0)?; + Ok(()) + }, + ); + } + }, + ); + state.update(app, |state, cx| { + state.title = Some((active_id, input)); + cx.notify(); + }); + }); + } + label.into_any_element() + }; super::max_width(div(), px(284.0)) .id(SharedString::from(format!("frame-item-{id}"))) .snapshot(key, Some(LIST_ID)) @@ -471,7 +625,7 @@ fn frame_card( .font_weight(FontWeight::MEDIUM) .child((index + 1).to_string()), ) - .child(div().min_w_0().text_ellipsis().child(title)), + .child(title_element), ) .child( div() diff --git a/packages/frontend/desktop/src/views_extra/right_sidebar/mod.rs b/packages/frontend/desktop/src/views_extra/right_sidebar/mod.rs index 1f4822c502..48eef75388 100644 --- a/packages/frontend/desktop/src/views_extra/right_sidebar/mod.rs +++ b/packages/frontend/desktop/src/views_extra/right_sidebar/mod.rs @@ -6,14 +6,29 @@ mod tests; pub(crate) use properties::render_doc_info_body; +use std::ops::Range; + +use blocksuite_editor::{ + edgeless::{PresentationFrame, presentation_frames}, + inline_input::{Utf16ImeBuffer, utf16_len, utf16_to_byte}, +}; +use blocksuite_playground_doc::{ + DocError, DocResult, + fractional_index::{generate_key_between, generate_n_keys_between}, + read::PageSnapshot, + session::PageDocSession, +}; use ui::{ - AppContext as _, Context, Div, FontWeight, Hsla, InteractiveElement, IntoElement, - ParentElement, Stateful, StatefulInteractiveElement, Styled, Window, div, px, svg, + AppContext as _, Bounds, ClipboardItem, Context, Div, ElementInputHandler, Entity, FocusHandle, + FontWeight, Hsla, InteractiveElement, IntoElement, KeyDownEvent, MouseButton, ParentElement, + Pixels, Point, ShapedLine, Stateful, StatefulInteractiveElement, Styled, Subscription, + TextAlign, TextRun, UTF16Selection, Window, canvas, div, fill, point, px, size, svg, }; use ui_tokens::{ FONT_SANS, ThemeMode, icons::{BULLETED_LIST, FRAME}, }; +use y_octo::{Any, SessionValue}; #[cfg(test)] pub(super) use super::FALLBACK_TAG_RGB; @@ -274,3 +289,506 @@ pub(super) fn section_title(label: &'static str, palette: DesktopPalette) -> Div .text_color(palette.text_primary) .child(label) } + +#[derive(Clone)] +struct ReorderList { + focus: ui::FocusHandle, + active: std::rc::Rc>, + previous_focus: std::rc::Rc>>, +} + +struct ReorderDrag { + source: String, + list: ReorderList, +} + +impl ui::Render for ReorderDrag { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div() + } +} + +impl ReorderList { + fn new(app: &ui::App) -> Self { + Self { + focus: app.focus_handle(), + active: Default::default(), + previous_focus: Default::default(), + } + } + + fn stop(&self, window: &mut Window, app: &mut ui::App) -> bool { + if !self.active.replace(false) { + return false; + } + let previous = self.previous_focus.take(); + if self.focus.is_focused(window) { + if let Some(previous) = previous { + previous.focus(window, app); + } else { + window.blur(app); + } + } + true + } + + fn container(&self, element: Div) -> Div { + let escape = self.clone(); + let outside = self.clone(); + let inside = self.clone(); + let focus = div() + .absolute() + .size(px(0.0)) + .track_focus(&self.focus) + .on_key_down(move |event, window, app| { + if event.keystroke.key == "escape" + && app.has_active_drag() + && escape.stop(window, app) + { + app.stop_propagation(); + window.prevent_default(); + } + }); + element + .child(focus) + .on_mouse_up_out(MouseButton::Left, move |_, window, app| { + outside.stop(window, app); + }) + .on_mouse_up(MouseButton::Left, move |_, window, app| { + inside.stop(window, app); + }) + } + + fn row( + &self, + element: Stateful
, + id: &str, + color: Hsla, + drop: impl Fn(&str, bool, &mut Window, &mut ui::App) + 'static, + ) -> Stateful
{ + let center = std::rc::Rc::new(std::cell::Cell::new(px(0.0))); + let center_measure = center.clone(); + let center_drop = center.clone(); + let target = id.to_owned(); + let owner = self.active.clone(); + let accepts = move |drag: &ReorderDrag| { + drag.source != target && owner.get() && std::rc::Rc::ptr_eq(&owner, &drag.list.active) + }; + let same_list = self.active.clone(); + let target = id.to_owned(); + let mut element = element.relative().child( + ui::canvas( + move |bounds, _, _| center_measure.set(bounds.center().y), + |_, (), _, _| {}, + ) + .absolute() + .inset_0(), + ); + element.interactivity().on_drag( + ReorderDrag { + source: id.to_owned(), + list: self.clone(), + }, + |drag, _, window, app| { + drag.list.active.set(true); + drag.list.previous_focus.replace(window.focused(app)); + drag.list.focus.focus(window, app); + app.new(|_| ReorderDrag { + source: drag.source.clone(), + list: drag.list.clone(), + }) + }, + ); + element + .drag_over::(move |style, drag, window, _| { + if !accepts(drag) { + return style; + } + let style = if window.mouse_position().y < center.get() { + style.border_t(px(2.0)) + } else { + style.border_b(px(2.0)) + }; + style.border_color(color) + }) + .on_drop(move |drag: &ReorderDrag, window, app| { + if std::rc::Rc::ptr_eq(&same_list, &drag.list.active) + && drag.list.stop(window, app) + && drag.source != target + { + drop( + &drag.source, + window.mouse_position().y >= center_drop.get(), + window, + app, + ); + } + }) + } +} + +struct FrameTitleInput { + buffer: Utf16ImeBuffer, + bounds: Option>, + focus: FocusHandle, + previous_focus: Option, + palette: DesktopPalette, + finish: Option, + blur: Option, +} + +type FinishFrameTitle = Box, &mut ui::App)>; + +impl FrameTitleInput { + fn open( + original: String, + palette: DesktopPalette, + window: &mut Window, + app: &mut ui::App, + finish: impl FnOnce(Option, &mut ui::App) + 'static, + ) -> Entity { + let focus = app.focus_handle(); + let previous_focus = window.focused(app); + let mut buffer = Utf16ImeBuffer::new(original, false); + buffer.select_all(); + let input = app.new(|cx: &mut Context| { + let blur = cx.on_focus_out(&focus, window, |input, _, _, cx| input.finish(true, cx)); + Self { + buffer, + bounds: None, + focus: focus.clone(), + previous_focus, + palette, + finish: Some(Box::new(finish)), + blur: Some(blur), + } + }); + focus.focus(window, app); + input + } + + fn finish(&mut self, commit: bool, cx: &mut Context) { + self.blur.take(); + if let Some(finish) = self.finish.take() { + let text = commit.then(|| std::mem::take(&mut self.buffer).into_committed_text()); + finish(text, cx); + } + } + + fn line(&self, bounds: Bounds, window: &Window) -> (ShapedLine, Point) { + let text = self.buffer.display_text(); + let (selection, reversed) = self.buffer.shown_selection(); + let caret = if reversed { + selection.start + } else { + selection.end + }; + let byte = utf16_to_byte(&text, caret); + let mut font = ui::font(ui_tokens::FONT_SANS); + font.fallbacks = Some(blocksuite_editor::default_font_fallbacks()); + let run = TextRun { + len: text.len(), + font, + color: self.palette.text_primary, + background_color: None, + underline: None, + strikethrough: None, + }; + let line = window + .text_system() + .shape_line(text.into(), px(14.0), &[run], None); + let overflow = (line.x_for_index(byte) + px(1.0) - bounds.size.width).max(px(0.0)); + let origin = point(bounds.origin.x - overflow, bounds.origin.y); + (line, origin) + } + + fn index_at(&self, cursor: Point, window: &Window) -> Option { + let (line, origin) = self.line(self.bounds?, window); + let byte = line.closest_index_for_x(cursor.x - origin.x); + Some(utf16_len(&line.text[..byte])) + } + + fn handle_key(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context) { + let key = event.keystroke.key.as_str(); + let mods = event.keystroke.modifiers; + if key == "escape" || (key == "enter" && !self.buffer.composing()) { + self.finish(key == "enter", cx); + if let Some(previous) = self.previous_focus.take() { + previous.focus(window, cx); + } else { + window.blur(cx); + } + } else if self.buffer.composing() { + cx.stop_propagation(); + return; + } else if (mods.control || mods.platform) && key == "v" { + let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) else { + return; + }; + self.buffer.replace(None, &text); + } else if (mods.control || mods.platform) && matches!(key, "a" | "c" | "x") { + if key == "a" { + self.buffer.select_all(); + } else if !self.buffer.selected_text().is_empty() { + cx.write_to_clipboard(ClipboardItem::new_string( + self.buffer.selected_text().to_owned(), + )); + if key == "x" { + self.buffer.replace(None, ""); + } + } + } else if self + .buffer + .key(key, mods.shift, mods.alt || mods.control) + .is_none() + { + cx.stop_propagation(); + return; + } + window.prevent_default(); + cx.stop_propagation(); + self.changed(window, cx); + } + + fn changed(&self, window: &Window, cx: &mut Context) { + window.notify_text_input_changed(&self.focus); + window.notify_text_selection_changed(&self.focus); + cx.notify(); + } +} + +impl ui::Render for FrameTitleInput { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + let entity = cx.entity(); + let focus = self.focus.clone(); + let palette = self.palette; + let (selection, reversed) = self.buffer.shown_selection(); + let bounds_entity = entity.clone(); + let width = self.line(Bounds::default(), window).0.width() + px(12.0); + div() + .id("desktop.inspector.frame.title_input") + .snapshot( + "desktop.inspector.frame.title_input", + Some("desktop.inspector"), + ) + .snapshot_focused(self.focus.is_focused(window)) + .snapshot_text(self.buffer.display_text()) + .track_focus(&self.focus) + .on_key_down(cx.listener(Self::handle_key)) + .on_mouse_down_out(cx.listener(|input, _, window, cx| { + if input.focus.is_focused(window) { + input.finish(true, cx); + window.blur(cx); + } + })) + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, event: &ui::MouseDownEvent, window, cx| { + if let Some(index) = this.index_at(event.position, window) { + this.buffer.unmark(); + this.buffer.move_caret(index, event.modifiers.shift); + this.changed(window, cx); + } + cx.stop_propagation(); + }), + ) + .cursor(ui::CursorStyle::IBeam) + .w(width) + .min_w(px(8.0)) + .h(px(20.0)) + .bg(palette.bg_canvas) + .relative() + .rounded(px(4.0)) + .border_1() + .border_color(palette.accent) + .overflow_hidden() + .child( + canvas( + move |bounds, window, cx| bounds_entity.read(cx).line(bounds, window), + move |bounds, (line, origin), window, cx| { + entity.update(cx, |input, _| input.bounds = Some(bounds)); + window.handle_input(&focus, ElementInputHandler::new(bounds, entity), cx); + let from = utf16_to_byte(&line.text, selection.start); + let to = utf16_to_byte(&line.text, selection.end); + if selection.is_empty() { + let x = line.x_for_index(if reversed { from } else { to }); + window.paint_quad(fill( + Bounds::new( + point(origin.x + x, bounds.origin.y + px(4.0)), + size(px(1.0), bounds.size.height - px(8.0)), + ), + palette.accent, + )); + } else { + for rect in line.selection_rects_for_range(from..to) { + window.paint_quad(fill( + Bounds::new( + point(origin.x + rect.origin.x, bounds.origin.y), + size(rect.size.width, bounds.size.height), + ), + palette.accent_soft, + )); + } + } + let _ = line.paint( + origin, + bounds.size.height, + TextAlign::Left, + None, + window, + cx, + ); + }, + ) + .absolute() + .top_0() + .bottom(px(0.0)) + .left(px(5.0)) + .right(px(5.0)), + ) + } +} + +impl ui::EntityInputHandler for FrameTitleInput { + fn text_for_range( + &mut self, + range: Range, + adjusted: &mut Option>, + _: &mut Window, + _: &mut Context, + ) -> Option { + let (text, range) = self.buffer.text_for_range(range); + *adjusted = Some(range); + Some(text) + } + + fn selected_text_range( + &mut self, + _: bool, + _: &mut Window, + _: &mut Context, + ) -> Option { + let (range, reversed) = self.buffer.shown_selection(); + Some(UTF16Selection { range, reversed }) + } + + fn marked_text_range(&self, _: &mut Window, _: &mut Context) -> Option> { + self.buffer.marked_range() + } + + fn unmark_text(&mut self, window: &mut Window, cx: &mut Context) { + self.buffer.unmark(); + self.changed(window, cx); + } + + fn replace_text_in_range( + &mut self, + range: Option>, + text: &str, + window: &mut Window, + cx: &mut Context, + ) { + self.buffer.replace(range, text); + self.changed(window, cx); + } + + fn replace_and_mark_text_in_range( + &mut self, + range: Option>, + text: &str, + selection: Option>, + window: &mut Window, + cx: &mut Context, + ) { + self.buffer.mark(range, text, selection); + self.changed(window, cx); + } + + fn bounds_for_range( + &mut self, + range: Range, + bounds: Bounds, + window: &mut Window, + _: &mut Context, + ) -> Option> { + let (line, origin) = self.line(bounds, window); + let x = |index| origin.x + line.x_for_index(utf16_to_byte(&line.text, index)); + let left = x(range.start).clamp(bounds.left(), bounds.right()); + let right = x(range.end).clamp(left, bounds.right()); + Some(Bounds::new( + point(left, bounds.top()), + size((right - left).max(px(1.0)), bounds.size.height), + )) + } + + fn character_index_for_point( + &mut self, + cursor: Point, + window: &mut Window, + _: &mut Context, + ) -> Option { + self.index_at(cursor, window) + } +} + +fn frame_order_updates( + snapshot: &PageSnapshot, + source: &str, + target: &str, + after: bool, +) -> DocResult>> { + let mut frames = presentation_frames(snapshot); + let Some(from) = frames.iter().position(|frame| frame.id == source) else { + return Ok(None); + }; + let Some(to) = frames.iter().position(|frame| frame.id == target) else { + return Ok(None); + }; + let to = to + usize::from(after) - usize::from(from < to + usize::from(after)); + if from == to { + return Ok(None); + } + let frame = frames.remove(from); + let key = |frame: &PresentationFrame| { + snapshot + .block(&frame.id)? + .props + .get("prop:presentationIndex")? + .as_str() + .filter(|key| !key.is_empty()) + }; + let lower = to.checked_sub(1).and_then(|index| frames.get(index)); + let upper = frames.get(to); + let lo = lower.and_then(key); + let hi = upper.and_then(key); + let updates = if (lower.is_none() || lo.is_some()) + && (upper.is_none() || hi.is_some()) + && let Ok(index) = generate_key_between(lo, hi) + { + vec![(frame.id, index)] + } else { + frames.insert(to, frame); + generate_n_keys_between(None, None, frames.len()) + .map_err(DocError::InvalidState)? + .into_iter() + .zip(frames) + .map(|(index, frame)| (frame.id, index)) + .collect() + }; + Ok(Some(updates)) +} + +fn write_frame_order(updates: Vec<(String, String)>, page: &mut PageDocSession) -> DocResult { + page.structural_edit(0, |page| { + for (id, index) in &updates { + page.set_block_prop( + id, + "prop:presentationIndex", + SessionValue::Any(Any::String(index.clone())), + 0, + )?; + } + Ok(()) + })?; + Ok(()) +} diff --git a/packages/frontend/desktop/src/views_extra/right_sidebar/outline.rs b/packages/frontend/desktop/src/views_extra/right_sidebar/outline.rs index 7d72b76aa2..30d680f247 100644 --- a/packages/frontend/desktop/src/views_extra/right_sidebar/outline.rs +++ b/packages/frontend/desktop/src/views_extra/right_sidebar/outline.rs @@ -7,7 +7,7 @@ use ui::{ }; use ui_kit::{VirtualList, VirtualWindow}; -use super::section_title; +use super::{ReorderList, section_title}; use crate::{DesktopPalette, doc_store::OutlineHeading, workbench::DesktopShellView}; const EMPTY_OUTLINE_MESSAGE: &str = "Use headings to create a table of contents."; @@ -124,6 +124,26 @@ impl RenderOnce for OutlinePanel { } }; + let pane = self.shell.read(app).state.split.active(); + let pane_id = pane.id; + let tab_id = pane.active_tab().id; + let editor = self.shell.read(app).editor_host().pane_entity(pane_id); + let writable = editor.as_ref().is_some_and(|editor| { + let view = editor.read(app); + view.active_doc_id() == Some(self.doc.as_str()) + && view.mode() == playground::PlaygroundMode::Page + && !view.page_readonly() + }) && !self.shell.read(app).state.store.is_readonly_sqlite(); + let reorder = window.use_keyed_state( + ElementId::NamedInteger( + SharedString::new_static("inspector-outline-reorder"), + ui::hash(&(&self.workspace, &self.doc, pane_id, tab_id)), + ), + app, + |_, cx| ReorderList::new(cx), + ); + let reorder = reorder.read(app).clone(); + let count = rows.len(); let headings_height = if count == 0 { 0.0 @@ -210,6 +230,10 @@ impl RenderOnce for OutlinePanel { let doc_id = Rc::clone(&doc_id); let workspace_id = Rc::clone(&workspace_id); let block_id = h.block_id.clone(); + let reorder_target = block_id.clone(); + let reorder_doc = doc_id.clone(); + let reorder_workspace = workspace_id.clone(); + let reorder_shell = shell.clone(); let indent = (h.level.saturating_sub(1) as f32) * 12.0; let mut row = div() .id(ElementId::NamedInteger( @@ -262,6 +286,28 @@ impl RenderOnce for OutlinePanel { }); }) .child(h.text.clone()); + if writable { + let id = reorder_target.clone(); + row = reorder.row(row, &id, palette.accent, move |source, after, _, app| { + let shell = reorder_shell.read(app); + let pane = shell.state.split.active(); + if pane.id != pane_id + || pane.active_tab().id != tab_id + || pane.active_route().doc_id() != Some(reorder_doc.as_ref()) + || shell.state.store.active_workspace().id != reorder_workspace.as_ref() + || shell.state.store.is_readonly_sqlite() + { + return; + } + if let Some(editor) = shell.editor_host().pane_entity(pane_id) + && editor.read(app).active_doc_id() == Some(reorder_doc.as_ref()) + { + editor.update(app, |view, cx| { + view.move_outline_heading(source, &reorder_target, after, cx); + }); + } + }); + } if index + 1 < count { row = row.mb(px(HEADING_ROW_GAP)); } @@ -299,7 +345,7 @@ impl RenderOnce for OutlinePanel { ) .absolute() .inset_0(); - body = body.child(items.child(measure_top)); + body = body.child(reorder.container(items.child(measure_top))); } let measured_limit = Rc::new(Cell::new(0.0_f32)); diff --git a/packages/frontend/desktop/src/views_extra/right_sidebar/tests.rs b/packages/frontend/desktop/src/views_extra/right_sidebar/tests.rs index 7fed6b4843..eda8f04930 100644 --- a/packages/frontend/desktop/src/views_extra/right_sidebar/tests.rs +++ b/packages/frontend/desktop/src/views_extra/right_sidebar/tests.rs @@ -787,6 +787,249 @@ mod frame_regressions { } } + impl FramePanelTest { + fn start_drag(&self, source: ui::Point, target: ui::Point) { + self.window + .dispatch_input(PlatformInput::MouseMove(ui::MouseMoveEvent { + position: source, + pressed_button: None, + modifiers: Default::default(), + })); + self.window + .dispatch_input(PlatformInput::MouseDown(ui::MouseDownEvent { + button: ui::MouseButton::Left, + position: source, + modifiers: Default::default(), + click_count: 1, + first_mouse: false, + })); + for position in [point(source.x, source.y + px(8.0)), target] { + self.window + .dispatch_input(PlatformInput::MouseMove(ui::MouseMoveEvent { + position, + pressed_button: Some(ui::MouseButton::Left), + modifiers: Default::default(), + })); + self.frame(); + } + } + + fn end_drag(&self, position: ui::Point) { + self.window + .dispatch_input(PlatformInput::MouseUp(ui::MouseUpEvent { + button: ui::MouseButton::Left, + position, + modifiers: Default::default(), + click_count: 1, + })); + self.frame(); + } + + fn key(&self, key: &str) { + self.window + .dispatch_input(PlatformInput::KeyDown(ui::KeyDownEvent { + keystroke: ui::Keystroke { + key: key.into(), + ..Default::default() + }, + is_held: false, + prefer_character_input: false, + })); + self.frame(); + } + + fn evidence(&self, name: &str) { + let Some(dir) = std::env::var_os("INSPECTOR_EVIDENCE_DIR") else { + return; + }; + self.inspect(|_, window, _| { + window + .render_to_image() + .unwrap() + .save(std::path::Path::new(&dir).join(format!("{name}.png"))) + .unwrap(); + }); + } + + fn undo(&self, doc: &str) { + self.inspect(|shell, _, cx| { + let editor = shell + .editor_host() + .pane_entity(shell.state.split.active().id) + .unwrap(); + editor.update(cx, |view, cx| { + view.edit_document(cx, |state| { + assert!( + state + .workspace + .page_mut(doc) + .unwrap() + .undo() + .unwrap() + .is_some() + ); + }); + }); + }); + self.frame(); + } + } + + #[test] + fn frame_panel_reorders_and_renames_frames_with_input_and_cancel() { + use ui::PlatformWindow; + + for (theme, name) in [(ThemeMode::Light, "light"), (ThemeMode::Dark, "dark")] { + let mut state = DesktopAppState::seed_showcase(theme, "2026-12-02"); + state.open_doc_in_active_pane(TEXT_DOC); + state.inspector_tab = Some(DocInspectorTab::Frame); + let entry = state.store.docs.get_mut(TEXT_DOC).unwrap(); + for (id, title, order) in [ + ("first", "First frame", "a0"), + ("second", "Second frame", "a1"), + ] { + entry + .session + .add_block( + id, + BlockSpec::Frame { + title: title.into(), + xywh: Some("[700,50,320,180]".into()), + presentation_index: Some(order.into()), + }, + Some("surface-sync"), + None, + 2_000, + ) + .unwrap(); + } + entry.snapshot = entry.session.read_page_snapshot().unwrap(); + entry.revision = entry.session.revision(); + let test = FramePanelTest::open(state, 1280); + let order = || { + test.inspect(|shell, _, _| { + blocksuite_editor::edgeless::presentation_frames( + &shell.state.store.docs[TEXT_DOC].snapshot, + ) + .into_iter() + .map(|frame| frame.id) + .collect::>() + }) + }; + let first = test.preview_center("desktop.inspector.frame.item.first"); + let second = test.preview_center("desktop.inspector.frame.item.second"); + let destination = point(first.x, first.y - px(24.0)); + test.evidence(&format!("before-frame-{name}")); + test.start_drag(second, destination); + test.key("escape"); + test.end_drag(destination); + assert_eq!(order(), ["first", "second"]); + test.start_drag(second, destination); + test.evidence(&format!("frame-drop-{name}")); + test.end_drag(destination); + assert_eq!(order(), ["second", "first"]); + test.evidence(&format!("after-frame-{name}")); + test.undo(TEXT_DOC); + assert_eq!(order(), ["first", "second"]); + + let start_rename = || { + test.press(test.center("desktop.inspector.frame.title.first"), false, 2); + assert!(test.inspect(|_, window, _| { + window + .frame_snapshot() + .elements + .contains_key("desktop.inspector.frame.title_input") + })); + }; + let set_text = |value: &str| { + let mut host = test.window.clone(); + let mut input = host.take_input_handler().unwrap(); + input.replace_and_mark_text_in_range(None, "zhong", Some(5..5)); + input.replace_text_in_range(None, value); + host.set_input_handler(input); + test.frame(); + }; + let title = || { + test.inspect(|shell, _, _| { + let snapshot = &shell.state.store.docs[TEXT_DOC].snapshot; + let Some(blocksuite_playground_doc::read::BlockContent::Frame { + title, .. + }) = snapshot.block("first").map(|node| &node.content) + else { + panic!("missing Frame"); + }; + title.plain.clone() + }) + }; + start_rename(); + set_text("取消"); + test.key("escape"); + assert_eq!(title(), "First frame"); + start_rename(); + set_text("项目 🧭"); + test.key("enter"); + assert_eq!(title(), "项目 🧭"); + start_rename(); + set_text("路线图"); + test.evidence(&format!("frame-title-{name}")); + test.window.simulate_click(point(px(900.0), px(80.0))); + test.frame(); + assert_eq!(title(), "路线图"); + test.undo(TEXT_DOC); + assert_eq!(title(), "项目 🧭"); + } + } + + #[test] + fn outline_reorders_headings_with_single_undo_and_respects_read_only() { + for (theme, name) in [(ThemeMode::Light, "light"), (ThemeMode::Dark, "dark")] { + let mut state = DesktopAppState::seed_showcase(theme, "2026-12-02"); + state.inspector_tab = Some(DocInspectorTab::Outline); + let doc = state + .split + .active() + .active_route() + .doc_id() + .unwrap() + .to_owned(); + let test = FramePanelTest::open(state, 1280); + let order = || { + let first = test.center("desktop.inspector.heading.h1-1"); + let second = test.center("desktop.inspector.heading.h2-1"); + first.y < second.y + }; + assert!(order()); + let first = test.center("desktop.inspector.heading.h1-1"); + let second = test.center("desktop.inspector.heading.h2-1"); + let destination = point(first.x, first.y - px(5.0)); + test.evidence(&format!("before-outline-{name}")); + test.start_drag(second, destination); + test.key("escape"); + test.end_drag(destination); + assert!(order()); + test.start_drag(second, destination); + test.evidence(&format!("outline-drop-{name}")); + test.end_drag(destination); + assert!(!order()); + test.evidence(&format!("after-outline-{name}")); + test.undo(&doc); + assert!(order()); + test.inspect(|shell, _, cx| { + shell.state.store.sqlite_backing = + Some(crate::sqlite_loader::SqliteLazyBacking::new( + "readonly-outline.affine", + "ws-readonly-outline", + 0, + )); + cx.notify(); + }); + test.frame(); + test.start_drag(second, destination); + test.end_drag(destination); + assert!(order()); + } + } + #[test] fn frame_panel_only_previews_select_and_fit_and_blank_clicks_clear_selection() { let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02");