From bfd7eb9eaf7bd956d5cde2fbd90ec083ff4080a8 Mon Sep 17 00:00:00 2001 From: DarkSky Date: Mon, 30 Nov 2026 20:12:04 +0900 Subject: [PATCH] fix(editor,playground,web,ios): polish block toolbars, lightbox gestures, Mermaid SVG sizing, and touch modality --- blocksuite/crates/AGENTS.md | 2 +- .../crates/editor/src/block_flow/layout.rs | 6 +- .../editor/src/block_flow/rich_blocks.rs | 6 +- .../src/database/filter_sort_bar/mod.rs | 22 +- .../crates/editor/src/overlays/block_menu.rs | 3 + .../editor/src/overlays/bookmark_toolbar.rs | 393 ++++++++++--- .../crates/editor/src/overlays/callout_bar.rs | 355 ++++++++---- .../editor/src/overlays/code_lang_picker.rs | 147 +++-- .../editor/src/overlays/context_menu.rs | 24 +- .../crates/editor/src/overlays/helpers.rs | 3 +- .../editor/src/overlays/image_lightbox.rs | 205 ++++++- .../editor/src/overlays/image_toolbar.rs | 357 +++++++++--- blocksuite/crates/editor/src/overlays/mod.rs | 27 +- .../src/overlays/paint_page/controls.rs | 176 ++++-- .../editor/src/overlays/paint_page/handle.rs | 45 +- .../editor/src/overlays/paint_page/mod.rs | 1 + .../crates/editor/src/overlays/paint_slash.rs | 2 +- .../crates/editor/src/overlays/state.rs | 33 +- .../crates/playground/src/chrome/mod.rs | 14 +- blocksuite/crates/playground/src/lib.rs | 8 +- .../src/overlays/tests_popovers_toolbars.rs | 524 +++++++++++++++++- .../crates/playground/src/overlays/view.rs | 1 + .../src/overlays/view_mobile/mod.rs | 28 +- .../playground/src/touch_interaction/mod.rs | 116 +--- .../playground/src/touch_interaction/modal.rs | 184 ++++++ blocksuite/crates/playground/src/view_room.rs | 33 +- .../crates/playground/web/preview-workers.js | 58 +- .../ios/Sources/LegacyLocalStorageProbe.swift | 4 +- .../verify-canary-dual-shell-browser.mjs | 4 +- .../hosts/web/tests/preview-workers.test.mjs | 105 ++++ 30 files changed, 2291 insertions(+), 595 deletions(-) create mode 100644 blocksuite/crates/playground/src/touch_interaction/modal.rs diff --git a/blocksuite/crates/AGENTS.md b/blocksuite/crates/AGENTS.md index b74845d930..84cd19c667 100644 --- a/blocksuite/crates/AGENTS.md +++ b/blocksuite/crates/AGENTS.md @@ -46,7 +46,7 @@ These crates belong to the client Cargo workspace rooted at `packages/frontend/C - **In-place table cell editing** (`page.table_cell_focus`): `affine:table` cells lay out and paint with `RichParagraph` (preserving bold, italic, underline, strike, inline code, links, and inline math) and carry their `FlowTextLayout` for same-source hit-testing, caret, selection, `character_index_for_point`, and IME candidate bounds. Clicking a cell focuses it directly in place (1.5 px brand border, zero floating popover, zero writeback on focus-only). Typing, deleting, and pasting splice the cell's live `Y.Text` directly via `PageDocSession::splice_table_cell_text` (applying the shared `insertion_marks_at` rule so text typed after inline code, links, references, or math never leaks into those marks, and sharing `AnchoredInlineInput` + `Utf16ImeBuffer` with `EdgelessLabelEditor`). Keystrokes coalesce within the 500 ms undo window, refresh only the table block in O(1) via `PageDocSession::read_table_block` with zero `TableData::clone()`, and mark only the table block in `dirty_text`. IME preedit splices via `split_delta` so surrounding marks keep identical pixels; clicking inside an already-focused inline target (table cell or Edgeless label) or moving body selection (`change_selection`) commits any in-flight composition via `unmark` into its original replacement range before repositioning the caret. `Enter`/`Shift+Enter` insert `\n`, `Tab`/`Shift+Tab` stay consumed inside the cell, `Up`/`Down` step across visual lines, and `Escape`, mode switches, or remote deletion exit through `finish_inline_targets` (closing the undo window without moving body selection). While a table cell is focused without a body selection, `KeyboardToolbar` mark/block buttons render disabled; explicit cell mark toggling and `pending_marks` are deferred until body and cell selections unify. - **Database authoring & mobile record sheet** (`database/{authoring,authoring_dispatch,cell_editor,column_ops,calendar_edit,filter_sort_bar,popover_overlay}.rs`, `playground/src/database_authoring/`, `overlays/view_mobile/record_sheet/`): `affine:database` (`Table`, `Kanban`, `Calendar`) supports typed `Y.Array` multi-select cells, incremental `Y.Text` splicing for row titles and rich-text cells (preserving marks and `@reference` embeds with zero writeback on no-op blur/`Enter`, unified on `AnchoredInlineInput` + `finish_inline_targets`), screen-space `Overlays` popovers (`ColumnMenu`, `SelectPicker`, `Filter`/`Sort`/`Group` panels, keeping block height invariant under `scroll_x > 0`), lossless Filter/Sort JSON patching with cascading column-delete cleanup, Kanban card title editing and type-safe lane creation, Calendar day `+` creation and reschedule drag, `@reference` (`LinkedPage`) title expansion across all four views (`resolve_rich_text_plain`), and a read-only mobile `RecordSheet` bottom sheet (`database_readonly` / `page_readonly` enforced across all mutation entry points). - **Drag handle & block menu** (`overlay.drag_handle`, `overlay.drop_indicator`, `overlay.block_menu`): mounted only for the hovered or dragged block (suppressed in `page_readonly`), 24 px left of the block and never closer than 4 px to the window edge. Inside its 24 px target it draws BlockSuite's Page-mode grabber: a 4 × 12 px vertical bar while the pointer is on the block's row, narrowing to a 2 × 12 px vertical bar once hovered or dragged (the 2 × 3 six-dot 14 px pill is reserved for Edgeless `gfx` drag handles). Clicking the handle toggles `overlay.block_menu` (`Copy`, `Duplicate` with subtree + database `prop:cells` row-key remapping, `Turn into ▸` submenu reusing `SLASH_ITEMS` on explicit `block_selection` only without expanding collapsed-heading body blocks, `Move up`, `Move down`, `Delete`) and sets `block_selection` on the target block; dragging resolves multi-level `TreeDropTarget` slots (`+24 px` horizontal indent steps reusing `Tab`'s parent-child legality predicate, moving collapsed heading sections atomically, and expanding a collapsed list parent on drop). A heading keeps the place beside its text for its collapse chevron, while non-heading `Paragraph` and `Quote` blocks with children expose a local-only disclosure chevron without writing `prop:collapsed` into CRDT. -- **Block controls & block toolbars**: `page.block..checkbox`, `.toggle` and `.collapse` are 24 px targets over the to-do box, the toggle chevron and the heading chevron (an expanded heading shows its chevron only while the pointer is on its row, and `page.block_selection` highlights merged visible nested subtrees while skipping collapsed children); `page.block..language`, `.copy`, `.wrap`, `.line_numbers`, `.fold`, and `.preview` appear on `affine:code` blocks (with `>= 44 × 44 pt` hit targets on touch hosts, searchable scrollable 25-language `overlay.code_lang_picker`, `prop:lineNumber`, and 8-line `prop:collapsed` fold with 3-band fade mask; `copy` swaps `CopyIcon` to `CheckIcon` in place for 1.5 s on the scheduler clock and shows `context_toast`). Selected `affine:image`, `affine:bookmark`, and `affine:callout` blocks mount `overlay.image_toolbar` (hidden while `overlay.image_lightbox` is open; double-clicking an image opens fullscreen `overlay.image_lightbox` with uniform aspect-preserving zoom, clipped viewport pan/wheel zoom, and modal key capture), `overlay.bookmark_toolbar` (`Inline` / active `Card` / host-validated `Embed` + Page `Wide`/`Compact` style toggle, plus inline `overlay.url_paste_menu` on plain URL paste), and `overlay.callout_toolbar` + `overlay.callout_icon_picker` (`{"type":"emoji","unicode":...}` `IconData` Map + `Remove` icon + 9 `0.27.5` semantic background swatches), docking cleanly into the bottom context-bar slot on touch viewports down to `360 pt`. Block-level `affine:latex` uses 2-step selection (first click selects block, second click opens `overlay.equation_editor`). A sideways scroll over an unwrapped code block scrolls its lines inside `BlockBody::code_scroll` instead of the page; the caret, selection, IME bounds, collaborators' carets/selections, and pointer hit-testing follow that scroll (`ScrolledCode`). +- **Block controls & block toolbars**: `page.block..checkbox`, `.toggle` and `.collapse` are 24 px targets over the to-do box, the toggle chevron and the heading chevron (an expanded heading shows its chevron only while the pointer is on its row, and `page.block_selection` highlights merged visible nested subtrees while skipping collapsed children); `page.block..language`, `.copy`, `.wrap`, `.line_number`, `.collapse`, `.caption_btn`, and `.preview` appear on `affine:code` blocks (with `>= 44 × 44 pt` hit targets on touch hosts, searchable scrollable 25-language `overlay.code_lang_picker`, `prop:lineNumber`, and 8-line `prop:collapsed` fold with 3-band fade mask; `copy` swaps `CopyIcon` to `CheckIcon` in place for 1.5 s on the scheduler clock and shows `context_toast`). Selected `affine:image`, `affine:bookmark`, and `affine:callout` blocks mount `overlay.image_toolbar` (hidden while `overlay.image_lightbox` is open; double-clicking an image opens fullscreen `overlay.image_lightbox` with uniform aspect-preserving zoom, clipped viewport drag-pan / proportional wheel & pinch zoom, and modal key capture), `overlay.bookmark_toolbar` (`Inline` / active `Card` / host-validated `Embed` + Page `Wide`/`Compact` style toggle, plus inline `overlay.url_paste_menu` on plain URL paste), and `overlay.callout_toolbar` + `overlay.callout_icon_picker` (`{"type":"emoji","unicode":...}` `IconData` Map + `Remove` icon + 9 `0.27.5` semantic background swatches), docking cleanly as horizontally scrollable `>= 44 × 44 pt` bottom context bars on touch viewports down to `360 pt`. Block-level `affine:latex` uses 2-step selection (first click selects block, second click opens `overlay.equation_editor`). A sideways scroll over an unwrapped code block scrolls its lines inside `BlockBody::code_scroll` instead of the page; the caret, selection, IME bounds, collaborators' carets/selections, and pointer hit-testing follow that scroll (`ScrolledCode`). - **Sizes and radii**: Interactive targets are at least 24 × 24 px on desktop (toolbar buttons 28 × 28, edge to edge; touch host controls `>= 44 pt` height). Rows and buttons round concentrically with their container: 8 px menu with 4 px padding and 4 px rows, 8 px toolbar with 4 px padding and 4 px buttons (`gap = 2px, pad = 4px`, compacting to 24 px `FormatAction::COMPACT` pills on viewports `< 460 px` so the toolbar fits a 320 px window between its 8 px margins; on wide desktop viewports `>= 460 px`, the 14-button toolbar is 481 px wide with three 1 px separators). All floating popovers fade opacity monotonically in place over 150 ms with zero entrance/exit coordinate drift. - **Verification**: `bs-harness render --state ` renders one overlay state of the showcase, `bs-harness audit-states` audits every state in both themes at `1280` and `320` px, and `bs-harness record-demo ` writes the frames of a 60 fps walk through typing, composition, the slash menu, the toolbar and the block controls; all drive the view through input events, the input handler and `dispatch_overlay` only. diff --git a/blocksuite/crates/editor/src/block_flow/layout.rs b/blocksuite/crates/editor/src/block_flow/layout.rs index ab202eb72a..2aaf28707a 100644 --- a/blocksuite/crates/editor/src/block_flow/layout.rs +++ b/blocksuite/crates/editor/src/block_flow/layout.rs @@ -570,9 +570,9 @@ impl<'a> FlowPass<'a> { }; if shows_children && !node.children.is_empty() { if is_callout { - // Horizontal callout layout (`callout-block-styles.ts`): - // emoji sits at `(x + 12, block_top + 10)` and child content starts on the - // SAME row at `(x + 46, block_top + 10)` with width `width - 58`. + // Horizontal callout layout (`callout-block-styles.ts:11`, `padding: 5px 10px`): + // emoji sits at `(x + 10, block_top + 5)` and child content starts on the + // SAME row at `(x + 44, block_top + 5)` with width `width - 54`. let pad_top = super::rich_blocks::CALLOUT_PAD_Y; let pad_x = super::rich_blocks::CALLOUT_PAD_X; let content_indent = pad_x diff --git a/blocksuite/crates/editor/src/block_flow/rich_blocks.rs b/blocksuite/crates/editor/src/block_flow/rich_blocks.rs index b6e05867da..ee91541402 100644 --- a/blocksuite/crates/editor/src/block_flow/rich_blocks.rs +++ b/blocksuite/crates/editor/src/block_flow/rich_blocks.rs @@ -8,11 +8,11 @@ use super::{ }; pub(super) const CALLOUT_MARGIN_Y: f32 = 8.0; -pub(super) const CALLOUT_PAD_X: f32 = 12.0; -pub(super) const CALLOUT_PAD_Y: f32 = 10.0; +pub(super) const CALLOUT_PAD_X: f32 = 10.0; +pub(super) const CALLOUT_PAD_Y: f32 = 5.0; pub(super) const CALLOUT_ICON_SLOT: f32 = 24.0; pub(super) const CALLOUT_CONTENT_GAP: f32 = 10.0; -pub(super) const CALLOUT_MIN_HEIGHT: f32 = 44.0; +pub(super) const CALLOUT_MIN_HEIGHT: f32 = 34.0; fn format_byte_size(bytes: i64) -> String { let b = bytes.max(0) as f64; diff --git a/blocksuite/crates/editor/src/database/filter_sort_bar/mod.rs b/blocksuite/crates/editor/src/database/filter_sort_bar/mod.rs index 63e98dbffe..7bc2498d5f 100644 --- a/blocksuite/crates/editor/src/database/filter_sort_bar/mod.rs +++ b/blocksuite/crates/editor/src/database/filter_sort_bar/mod.rs @@ -209,15 +209,14 @@ pub(super) fn render_active_rule_chips( let chip_border = ctx.palette.border.opacity(0.65); for chip in &filter_chips { - let label = format!("{} ×", chip.label); let style = InlineStyle::new( FONT_SANS, TYPOGRAPHY.font_xs_px, 500.0, ctx.palette.text_primary, ); - let (_, layout) = ctx.truncate_text(&label, style, 180.0, btn_h); - let chip_w = (layout.content_width().ceil() + 16.0).clamp(64.0, 200.0); + let (_, layout) = ctx.truncate_text(&chip.label, style, 166.0, btn_h); + let chip_w = (layout.content_width().ceil() + 34.0).clamp(68.0, 200.0); if cursor + chip_w > strip_right && cursor > strip_left { cursor = strip_left; y += btn_h + 4.0; @@ -237,10 +236,25 @@ pub(super) fn render_active_rule_chips( clip: Some(FlowRect::new( rect.x + 4.0, rect.y, - (rect.w - 8.0).max(1.0), + (rect.w - 26.0).max(1.0), btn_h, )), }); + let rm_rect = FlowRect::new(rect.right() - 20.0, rect.y + 2.0, 18.0, 20.0); + prims.push(ctx.single_line_clipped( + "×", + InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_xs_px, + 600.0, + ctx.palette.text_secondary, + ), + rm_rect.x, + rm_rect.y, + rm_rect.w, + rm_rect.h, + InlineAlign::Center, + )); authoring_hits.push(DatabaseAuthoringHit { rect, kind: DatabaseAuthoringHitKind::ToolbarRemoveFilter { diff --git a/blocksuite/crates/editor/src/overlays/block_menu.rs b/blocksuite/crates/editor/src/overlays/block_menu.rs index 27df02b7fc..8cf123dc21 100644 --- a/blocksuite/crates/editor/src/overlays/block_menu.rs +++ b/blocksuite/crates/editor/src/overlays/block_menu.rs @@ -469,6 +469,9 @@ impl super::Overlays { self.close_slash(now_ms); self.close_linked_doc(now_ms); self.close_context_menu(now_ms); + if let Some(toolbar) = self.open_toolbar_mut() { + toolbar.presence.close(now_ms); + } let presence = match self.block_menu.take() { Some(menu) => menu.presence.reopened(now_ms), None => Presence::opening(now_ms), diff --git a/blocksuite/crates/editor/src/overlays/bookmark_toolbar.rs b/blocksuite/crates/editor/src/overlays/bookmark_toolbar.rs index cc4d65bb73..11aa3470de 100644 --- a/blocksuite/crates/editor/src/overlays/bookmark_toolbar.rs +++ b/blocksuite/crates/editor/src/overlays/bookmark_toolbar.rs @@ -5,8 +5,8 @@ use blocksuite_playground_doc::read::BlockContent; use ui::{ - AnyElement, ClickEvent, Context, FontWeight, MouseButton, MouseDownEvent, SharedString, div, - prelude::*, px, + AnyElement, ClickEvent, Context, FontWeight, MouseButton, MouseDownEvent, ScrollEvent, + SharedString, div, prelude::*, px, }; use crate::{ @@ -115,69 +115,314 @@ impl Overlays { let can_embed = embed_view_kind_for_url(url).is_some(); let current_style = BookmarkCardStyle::from_wire(node.props.get("prop:style").and_then(|v| v.as_str())); - let touch = scene.form_factor != crate::block_flow::FormFactor::Desktop; - let btn_h = if touch { 44.0 } else { TOOLBAR_BUTTON }; + let touch = scene.is_touch || scene.form_factor != crate::block_flow::FormFactor::Desktop; let vp = scene.popover_viewport(); let pad = TOOLBAR_PADDING; + let chrome = 2.0 * (pad + POPOVER_BORDER); let max_w = (vp.w - 2.0 * POPOVER_EDGE_MARGIN).max(200.0); - let compact_touch = touch && max_w < 410.0; - let gap = if compact_touch { 1.0 } else { TOOLBAR_GAP }; - let icon_w = if compact_touch { - 34.0 - } else if touch { - 42.0 - } else { - TOOLBAR_BUTTON - }; - let desktop_raw = if can_embed { 462.0_f32 } else { 414.0_f32 }; - let width = if touch { max_w } else { desktop_raw.min(max_w) }.round(); - let height = (btn_h + 2.0 * (pad + POPOVER_BORDER)).round(); - - let rect = if touch { - FlowRect::new( - (vp.x + (vp.w - width) * 0.5).round(), - (vp.bottom() - height - POPOVER_EDGE_MARGIN).round(), - width, - height, - ) - } else { - place_popover( - scene.world_to_screen(&block_world), - (width, height), - vp, - Placement::Above, - POPOVER_GAP, - POPOVER_EDGE_MARGIN, - ) - .rect - }; - self.bookmark_toolbar_rect = Some(rect); - + let desktop_raw = if can_embed { 474.0_f32 } else { 426.0_f32 }; let hover_bg = palette.hover; let danger = palette .theme .css_var("--affine-error-color") .unwrap_or(palette.icon); + + if touch || max_w < desktop_raw { + let btn_h = if touch { 44.0_f32 } else { TOOLBAR_BUTTON }; + let icon_w = if touch { 44.0_f32 } else { TOOLBAR_BUTTON }; + let gap = 4.0_f32; + let sep_slot = 9.0_f32; + let make_touch_text = |suffix: &'static str, + label: &'static str, + w: f32, + accent: bool, + active: bool, + action: Option, + cx: &mut Context| + -> (f32, Box AnyElement>) { + let text_col = if accent || active { + palette.brand + } else { + palette.text_primary + }; + let active_bg = palette.brand.opacity(0.14); + let click_handler = action.map(|act| { + let ev = OverlayEvent::BookmarkToolbarAction { + block_id: block_id.to_string(), + action: act, + }; + emit(cx, move |_: &ClickEvent| ev.clone()) + }); + ( + w, + Box::new(move |fully_visible| { + let mut el = div() + .id(SharedString::from(format!("bm-tb-{suffix}"))) + .w(px(w)) + .h(px(btn_h)) + .px(px(8.0)) + .rounded(px(4.0)) + .flex() + .items_center() + .justify_center() + .text_size(px(TYPOGRAPHY.font_xs_px)) + .font_weight(FontWeight::MEDIUM) + .text_color(text_col) + .when(active, |el| el.bg(active_bg)) + .child(label); + if let Some(handler) = click_handler { + el = el + .cursor_pointer() + .hover(move |s| s.bg(hover_bg)) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(handler); + } + if fully_visible { + el = el + .snapshot( + SharedString::from(format!( + "overlay.bookmark_toolbar.{suffix}" + )), + Some("overlay.bookmark_toolbar"), + ) + .snapshot_focused(active) + .snapshot_text(label); + } + el.into_any_element() + }), + ) + }; + let make_touch_icon = |suffix: &'static str, + icon_name: &'static str, + active: bool, + is_danger: bool, + action: BookmarkToolbarAction, + cx: &mut Context| + -> (f32, Box AnyElement>) { + let ev = OverlayEvent::BookmarkToolbarAction { + block_id: block_id.to_string(), + action, + }; + let click_handler = emit(cx, move |_: &ClickEvent| ev.clone()); + let color = if is_danger { + danger + } else if active { + palette.brand + } else { + palette.icon + }; + let active_bg = palette.brand.opacity(0.14); + ( + icon_w, + Box::new(move |fully_visible| { + let mut el = div() + .id(SharedString::from(format!("bm-tb-{suffix}"))) + .w(px(icon_w)) + .h(px(btn_h)) + .rounded(px(4.0)) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .when(active, |el| el.bg(active_bg)) + .hover(move |s| s.bg(hover_bg)) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(click_handler) + .child(icon(icon_name, 16.0, color)); + if fully_visible { + el = el + .snapshot( + SharedString::from(format!( + "overlay.bookmark_toolbar.{suffix}" + )), + Some("overlay.bookmark_toolbar"), + ) + .snapshot_focused(active); + } + el.into_any_element() + }), + ) + }; + + let mut items: Vec<(f32, Box AnyElement>)> = vec![ + make_touch_text( + "open", + "Open \u{2197}", + 60.0, + true, + false, + Some(BookmarkToolbarAction::Open), + cx, + ), + make_touch_text( + "edit", + "Edit", + 46.0, + false, + false, + Some(BookmarkToolbarAction::Edit), + cx, + ), + make_touch_text( + "inline", + "Inline", + 52.0, + false, + false, + Some(BookmarkToolbarAction::ConvertToInline), + cx, + ), + make_touch_text("card", "Card", 48.0, false, true, None, cx), + ]; + if can_embed { + items.push(make_touch_text( + "embed", + "Embed", + 58.0, + false, + false, + Some(BookmarkToolbarAction::ConvertToEmbed), + cx, + )); + } + items.push(make_touch_text( + "style", + current_style.label(), + 68.0, + false, + false, + Some(BookmarkToolbarAction::SetStyle( + current_style.next_in_page(), + )), + cx, + )); + items.push(make_touch_icon( + "caption", + "AddTextIcon", + has_caption, + false, + BookmarkToolbarAction::Caption, + cx, + )); + items.push(make_touch_icon( + "copy", + "CopyIcon", + false, + false, + BookmarkToolbarAction::Copy, + cx, + )); + items.push(make_touch_icon( + "duplicate", + "DuplicateIcon", + false, + false, + BookmarkToolbarAction::Duplicate, + cx, + )); + + let content_w: f32 = + items.iter().map(|(w, _)| *w).sum::() + (items.len() - 1) as f32 * gap; + let pinned_right_w = sep_slot + icon_w + 2.0 * gap; + let width = (content_w + pinned_right_w + chrome).min(max_w).round(); + let height = (btn_h + chrome).round(); + let avail_w = (width - chrome - pinned_right_w).max(icon_w); + let max_scroll = (content_w - avail_w).max(0.0).ceil(); + let scroll_key = format!("bm:{block_id}"); + let scroll_x = self.sync_touch_bar_scroll(&scroll_key, max_scroll); + + let rect = if touch { + FlowRect::new( + (vp.x + (vp.w - width) * 0.5).round(), + (vp.bottom() - height - POPOVER_EDGE_MARGIN).round(), + width, + height, + ) + } else { + place_popover( + scene.world_to_screen(&block_world), + (width, height), + vp, + Placement::Above, + POPOVER_GAP, + POPOVER_EDGE_MARGIN, + ) + .rect + }; + self.bookmark_toolbar_rect = Some(rect); + + let strip = + Self::build_touch_scroll_strip(avail_w, btn_h, gap, scroll_x, palette, items); + let del_btn = make_touch_icon( + "delete", + "DeleteIcon", + false, + true, + BookmarkToolbarAction::Delete, + cx, + ) + .1(true); + + let root = place(rect) + .id("bookmark-toolbar") + .occlude() + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_mouse_down_out(|_: &MouseDownEvent, _, _| {}) + .on_scroll(emit(cx, |event: &ScrollEvent| { + let d = event.delta.pixel_delta(px(20.0)); + let dx = f32::from(d.x); + OverlayEvent::TouchContextBarScroll(if dx != 0.0 { dx } else { f32::from(d.y) }) + })) + .p(px(pad)) + .rounded(px(TOOLBAR_RADIUS)) + .bg(palette.panel) + .border_1() + .border_color(palette.border) + .shadow(palette.theme.shadows("--affine-toolbar-shadow").into()) + .flex() + .items_center() + .gap(px(gap)) + .snapshot("overlay.bookmark_toolbar", Some("root.canvas")) + .child(strip) + .child( + div() + .flex_none() + .w(px(sep_slot)) + .h(px(btn_h)) + .flex() + .items_center() + .justify_center() + .child(div().w(px(1.0)).h(px(16.0)).bg(palette.divider)), + ) + .child(del_btn); + return Some(root.into_any_element()); + } + + let width = desktop_raw.min(max_w).round(); + let height = (TOOLBAR_BUTTON + chrome).round(); + let rect = place_popover( + scene.world_to_screen(&block_world), + (width, height), + vp, + Placement::Above, + POPOVER_GAP, + POPOVER_EDGE_MARGIN, + ) + .rect; + self.bookmark_toolbar_rect = Some(rect); + let make_text_btn = |suffix: &'static str, label: &'static str, w: f32, - touch_compact_w: f32, accent: bool, active: bool, action: Option, cx: &mut Context| { - let eff_w = if compact_touch { - touch_compact_w - } else if touch { - w.max(40.0) - } else { - w - }; let mut el = div() .id(SharedString::from(format!("bm-tb-{suffix}"))) .flex_none() - .w(px(eff_w)) - .h(px(btn_h)) + .w(px(w)) + .h(px(TOOLBAR_BUTTON)) .rounded(px(4.0)) .flex() .items_center() @@ -230,8 +475,8 @@ impl Overlays { div() .id(SharedString::from(format!("bm-tb-{suffix}"))) .flex_none() - .w(px(icon_w)) - .h(px(btn_h)) + .w(px(TOOLBAR_BUTTON)) + .h(px(TOOLBAR_BUTTON)) .rounded(px(4.0)) .flex() .items_center() @@ -253,16 +498,11 @@ impl Overlays { let mut row = div() .flex() .items_center() - .gap(px(gap)) + .gap(px(TOOLBAR_GAP)) .child(make_text_btn( "open", - if compact_touch { - "Open" - } else { - "Open \u{2197}" - }, + "Open \u{2197}", 50.0, - 38.0, true, false, Some(BookmarkToolbarAction::Open), @@ -272,7 +512,6 @@ impl Overlays { "edit", "Edit", 36.0, - 32.0, false, false, Some(BookmarkToolbarAction::Edit), @@ -282,21 +521,17 @@ impl Overlays { "inline", "Inline", 40.0, - 36.0, false, false, Some(BookmarkToolbarAction::ConvertToInline), cx, )) - .child(make_text_btn( - "card", "Card", 38.0, 34.0, false, true, None, cx, - )); + .child(make_text_btn("card", "Card", 38.0, false, true, None, cx)); if can_embed { row = row.child(make_text_btn( "embed", "Embed", 46.0, - 40.0, false, false, Some(BookmarkToolbarAction::ConvertToEmbed), @@ -306,16 +541,8 @@ impl Overlays { row = row .child(make_text_btn( "style", - if compact_touch { - match current_style { - BookmarkCardStyle::List => "List", - _ => "Wide", - } - } else { - current_style.label() - }, - 56.0, - 36.0, + current_style.label(), + 68.0, false, false, Some(BookmarkToolbarAction::SetStyle( @@ -338,25 +565,23 @@ impl Overlays { false, BookmarkToolbarAction::Copy, cx, - )); - if !touch { - row = row.child(make_icon_btn( + )) + .child(make_icon_btn( "duplicate", "DuplicateIcon", false, false, BookmarkToolbarAction::Duplicate, cx, + )) + .child(make_icon_btn( + "delete", + "DeleteIcon", + false, + true, + BookmarkToolbarAction::Delete, + cx, )); - } - row = row.child(make_icon_btn( - "delete", - "DeleteIcon", - false, - true, - BookmarkToolbarAction::Delete, - cx, - )); let root = place(rect) .id("bookmark-toolbar") diff --git a/blocksuite/crates/editor/src/overlays/callout_bar.rs b/blocksuite/crates/editor/src/overlays/callout_bar.rs index eb05e34b3f..b080973dc6 100644 --- a/blocksuite/crates/editor/src/overlays/callout_bar.rs +++ b/blocksuite/crates/editor/src/overlays/callout_bar.rs @@ -3,8 +3,8 @@ use blocksuite_playground_doc::read::BlockContent; use ui::{ - AnyElement, ClickEvent, Context, FontWeight, MouseButton, MouseDownEvent, SharedString, div, - prelude::*, px, + AnyElement, ClickEvent, Context, FontWeight, MouseButton, MouseDownEvent, ScrollEvent, + SharedString, div, prelude::*, px, }; use crate::{ @@ -157,58 +157,13 @@ impl Overlays { return Vec::new(); }; - let touch = scene.form_factor != crate::block_flow::FormFactor::Desktop; + let touch = scene.is_touch || scene.form_factor != crate::block_flow::FormFactor::Desktop; let btn_h = if touch { 44.0 } else { TOOLBAR_BUTTON }; + let btn_w = if touch { 44.0 } else { TOOLBAR_BUTTON }; let vp = scene.popover_viewport(); let pad = TOOLBAR_PADDING; + let chrome = 2.0 * (pad + POPOVER_BORDER); let max_w = (vp.w - 2.0 * POPOVER_EDGE_MARGIN).max(200.0); - let compact_touch = touch && max_w < 410.0; - let btn_w = if compact_touch { - 36.0 - } else if touch { - 44.0 - } else { - TOOLBAR_BUTTON - }; - let swatch = if compact_touch { - 22.0 - } else if touch { - 26.0 - } else { - 22.0 - }; - let swatch_gap = if compact_touch { 3.0 } else { 4.0 }; - let bar_gap = if compact_touch { 4.0 } else { 6.0 }; - let raw_w = 2.0 * (pad + POPOVER_BORDER) - + btn_w - + 9.0 * swatch - + 8.0 * swatch_gap - + btn_w - + 2.0 - + 4.0 * bar_gap; - let width = if touch { max_w } else { raw_w.min(max_w) }.round(); - let height = (btn_h + 2.0 * (pad + POPOVER_BORDER)).round(); - - let rect = if touch { - FlowRect::new( - (vp.x + (vp.w - width) * 0.5).round(), - (vp.bottom() - height - POPOVER_EDGE_MARGIN).round(), - width, - height, - ) - } else { - place_popover( - scene.world_to_screen(&block_world), - (width, height), - vp, - Placement::Above, - POPOVER_GAP, - POPOVER_EDGE_MARGIN, - ) - .rect - }; - self.callout_toolbar_rect = Some(rect); - let hover_bg = palette.hover; let danger = palette .theme @@ -253,47 +208,6 @@ impl Overlays { icon_btn.child(current_icon.clone()) }; - let mut swatches = div().flex().items_center().gap(px(swatch_gap)); - for (name, css_var) in CALLOUT_BG_COLORS { - let selected = if name == "default" { - raw_bg.is_empty() || raw_bg == "default" - } else { - raw_bg == name - }; - let fill = palette - .theme - .css_var(css_var) - .unwrap_or(palette.background_secondary); - let ev = OverlayEvent::CalloutAction { - block_id: block_id_owned.clone(), - action: CalloutAction::SetBackground(name.to_string()), - }; - swatches = swatches.child( - div() - .id(SharedString::from(format!("callout-bg-{name}"))) - .flex_none() - .w(px(swatch)) - .h(px(swatch)) - .rounded(px(swatch * 0.5)) - .bg(fill) - .border_1() - .border_color(if selected { - palette.brand - } else { - palette.border - }) - .cursor_pointer() - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_click(emit(cx, move |_: &ClickEvent| ev.clone())) - .snapshot( - SharedString::from(format!("overlay.callout_toolbar.bg.{name}")), - Some("overlay.callout_toolbar"), - ) - .snapshot_focused(selected) - .snapshot_text(name), - ); - } - let del_ev = OverlayEvent::CalloutAction { block_id: block_id_owned.clone(), action: CalloutAction::Delete, @@ -318,33 +232,230 @@ impl Overlays { .child(icon("DeleteIcon", 16.0, danger)); let mut out = Vec::new(); - let bar = place(rect) - .id("callout-toolbar") - .occlude() - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_mouse_down_out(|_: &MouseDownEvent, _, _| {}) - .p(px(pad)) - .rounded(px(TOOLBAR_RADIUS)) - .bg(palette.panel) - .border_1() - .border_color(palette.border) - .shadow(palette.theme.shadows("--affine-toolbar-shadow").into()) - .flex() - .items_center() - .justify_center() - .gap(px(bar_gap)) - .snapshot("overlay.callout_toolbar", Some("root.canvas")) - .child(icon_btn) - .child(div().flex_none().w(px(1.0)).h(px(16.0)).bg(palette.divider)) - .child(swatches) - .child(div().flex_none().w(px(1.0)).h(px(16.0)).bg(palette.divider)) - .child(del_btn); - out.push(bar.into_any_element()); + let rect = if touch { + let hit_box = 44.0_f32; + let dot = 24.0_f32; + let gap = 2.0_f32; + let sep_slot = 9.0_f32; + let content_w = 9.0 * hit_box + 8.0 * gap; + let pinned_w = 2.0 * (btn_w + sep_slot) + 4.0 * gap; + let width = (content_w + pinned_w + chrome).min(max_w).round(); + let height = (btn_h + chrome).round(); + let avail_w = (width - chrome - pinned_w).max(hit_box); + let max_scroll = (content_w - avail_w).max(0.0).ceil(); + let scroll_key = format!("co:{block_id_owned}"); + let scroll_x = self.sync_touch_bar_scroll(&scroll_key, max_scroll); + + let rect = FlowRect::new( + (vp.x + (vp.w - width) * 0.5).round(), + (vp.bottom() - height - POPOVER_EDGE_MARGIN).round(), + width, + height, + ); + self.callout_toolbar_rect = Some(rect); + + let mut swatch_items: Vec<(f32, Box AnyElement>)> = Vec::new(); + for (name, css_var) in CALLOUT_BG_COLORS { + let selected = if name == "default" { + raw_bg.is_empty() || raw_bg == "default" + } else { + raw_bg == name + }; + let fill = palette + .theme + .css_var(css_var) + .unwrap_or(palette.background_secondary); + let border_col = if selected { + palette.brand + } else { + palette.border + }; + let ev = OverlayEvent::CalloutAction { + block_id: block_id_owned.clone(), + action: CalloutAction::SetBackground(name.to_string()), + }; + let click_handler = emit(cx, move |_: &ClickEvent| ev.clone()); + swatch_items.push(( + hit_box, + Box::new(move |fully_visible| { + let mut el = div() + .id(SharedString::from(format!("callout-bg-{name}"))) + .w(px(hit_box)) + .h(px(hit_box)) + .rounded(px(6.0)) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .hover(move |s| s.bg(hover_bg)) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(click_handler) + .child( + div() + .w(px(dot)) + .h(px(dot)) + .rounded(px(dot * 0.5)) + .bg(fill) + .border_1() + .border_color(border_col), + ); + if fully_visible { + el = el + .snapshot( + SharedString::from(format!( + "overlay.callout_toolbar.bg.{name}" + )), + Some("overlay.callout_toolbar"), + ) + .snapshot_focused(selected) + .snapshot_text(name); + } + el.into_any_element() + }), + )); + } + let strip = Self::build_touch_scroll_strip( + avail_w, + btn_h, + gap, + scroll_x, + palette, + swatch_items, + ); + let bar = place(rect) + .id("callout-toolbar") + .occlude() + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_mouse_down_out(|_: &MouseDownEvent, _, _| {}) + .on_scroll(emit(cx, |event: &ScrollEvent| { + let d = event.delta.pixel_delta(px(20.0)); + let dx = f32::from(d.x); + OverlayEvent::TouchContextBarScroll(if dx != 0.0 { dx } else { f32::from(d.y) }) + })) + .p(px(pad)) + .rounded(px(TOOLBAR_RADIUS)) + .bg(palette.panel) + .border_1() + .border_color(palette.border) + .shadow(palette.theme.shadows("--affine-toolbar-shadow").into()) + .flex() + .items_center() + .gap(px(gap)) + .snapshot("overlay.callout_toolbar", Some("root.canvas")) + .child(icon_btn) + .child( + div() + .flex_none() + .w(px(sep_slot)) + .h(px(btn_h)) + .flex() + .items_center() + .justify_center() + .child(div().w(px(1.0)).h(px(16.0)).bg(palette.divider)), + ) + .child(strip) + .child( + div() + .flex_none() + .w(px(sep_slot)) + .h(px(btn_h)) + .flex() + .items_center() + .justify_center() + .child(div().w(px(1.0)).h(px(16.0)).bg(palette.divider)), + ) + .child(del_btn); + out.push(bar.into_any_element()); + rect + } else { + let swatch = 22.0_f32; + let swatch_gap = 4.0_f32; + let bar_gap = 6.0_f32; + let raw_w = + chrome + btn_w + 9.0 * swatch + 8.0 * swatch_gap + btn_w + 2.0 + 4.0 * bar_gap; + let width = raw_w.min(max_w).round(); + let height = (btn_h + chrome).round(); + let rect = place_popover( + scene.world_to_screen(&block_world), + (width, height), + vp, + Placement::Above, + POPOVER_GAP, + POPOVER_EDGE_MARGIN, + ) + .rect; + self.callout_toolbar_rect = Some(rect); + + let mut swatches = div().flex().items_center().gap(px(swatch_gap)); + for (name, css_var) in CALLOUT_BG_COLORS { + let selected = if name == "default" { + raw_bg.is_empty() || raw_bg == "default" + } else { + raw_bg == name + }; + let fill = palette + .theme + .css_var(css_var) + .unwrap_or(palette.background_secondary); + let ev = OverlayEvent::CalloutAction { + block_id: block_id_owned.clone(), + action: CalloutAction::SetBackground(name.to_string()), + }; + swatches = swatches.child( + div() + .id(SharedString::from(format!("callout-bg-{name}"))) + .flex_none() + .w(px(swatch)) + .h(px(swatch)) + .rounded(px(swatch * 0.5)) + .bg(fill) + .border_1() + .border_color(if selected { + palette.brand + } else { + palette.border + }) + .cursor_pointer() + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(emit(cx, move |_: &ClickEvent| ev.clone())) + .snapshot( + SharedString::from(format!("overlay.callout_toolbar.bg.{name}")), + Some("overlay.callout_toolbar"), + ) + .snapshot_focused(selected) + .snapshot_text(name), + ); + } + let bar = place(rect) + .id("callout-toolbar") + .occlude() + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_mouse_down_out(|_: &MouseDownEvent, _, _| {}) + .p(px(pad)) + .rounded(px(TOOLBAR_RADIUS)) + .bg(palette.panel) + .border_1() + .border_color(palette.border) + .shadow(palette.theme.shadows("--affine-toolbar-shadow").into()) + .flex() + .items_center() + .justify_center() + .gap(px(bar_gap)) + .snapshot("overlay.callout_toolbar", Some("root.canvas")) + .child(icon_btn) + .child(div().flex_none().w(px(1.0)).h(px(16.0)).bg(palette.divider)) + .child(swatches) + .child(div().flex_none().w(px(1.0)).h(px(16.0)).bg(palette.divider)) + .child(del_btn); + out.push(bar.into_any_element()); + rect + }; if picker_open { - // 6 columns × 2 rows of 30px emoji tiles + Remove button row below. - let picker_w = 220.0_f32; - let picker_h = 114.0_f32; + let tile = if touch { 44.0_f32 } else { 30.0_f32 }; + let remove_h = if touch { 44.0_f32 } else { 24.0_f32 }; + let picker_w = 2.0 * (8.0 + POPOVER_BORDER) + 6.0 * tile + 5.0 * 4.0; + let picker_h = 2.0 * (8.0 + POPOVER_BORDER) + 2.0 * tile + 4.0 + 4.0 + remove_h; let pref = if touch { Placement::Above } else { @@ -361,6 +472,9 @@ impl Overlays { self.callout_icon_picker_rect = Some(placed.rect); let mut grid = div().flex().flex_wrap().gap(px(4.0)); for (idx, emoji) in CALLOUT_ICON_PRESETS.iter().enumerate() { + let is_cur_emoji = current_icon == *emoji; + let brand_tint = palette.brand.opacity(0.14); + let brand_border = palette.brand; let ev = OverlayEvent::CalloutAction { block_id: block_id_owned.clone(), action: CalloutAction::SetIcon((*emoji).to_string()), @@ -369,13 +483,16 @@ impl Overlays { div() .id(SharedString::from(format!("callout-emoji-{idx}"))) .flex_none() - .w(px(30.0)) - .h(px(30.0)) + .w(px(tile)) + .h(px(tile)) .rounded(px(4.0)) .flex() .items_center() .justify_center() .cursor_pointer() + .when(is_cur_emoji, |el| { + el.bg(brand_tint).border_1().border_color(brand_border) + }) .hover(move |s| s.bg(hover_bg)) .text_size(px(TYPOGRAPHY.font_base_px)) .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) @@ -396,7 +513,7 @@ impl Overlays { .id("callout-emoji-remove") .flex_none() .w_full() - .h(px(24.0)) + .h(px(remove_h)) .rounded(px(4.0)) .flex() .items_center() diff --git a/blocksuite/crates/editor/src/overlays/code_lang_picker.rs b/blocksuite/crates/editor/src/overlays/code_lang_picker.rs index 2e38b9ee21..29200407cc 100644 --- a/blocksuite/crates/editor/src/overlays/code_lang_picker.rs +++ b/blocksuite/crates/editor/src/overlays/code_lang_picker.rs @@ -16,7 +16,8 @@ use super::{ POPOVER_EDGE_MARGIN, Placement, Presence, TOOLBAR_RADIUS, emit, place, place_popover, }; -const VISIBLE_LANG_ROWS: usize = 8; +const VISIBLE_LANG_ROWS_DESKTOP: usize = 8; +const VISIBLE_LANG_ROWS_TOUCH: usize = 5; /// Canonical BlockSuite / Shiki language catalog `(wire_id, display_label)`. pub const CODE_LANGUAGES: &[(&str, &str)] = &[ @@ -101,25 +102,34 @@ pub fn filter_code_languages(query: &str) -> Vec<(&'static str, &'static str)> { pub struct CodeLangPicker { pub block_id: String, pub input: LinkBar, + pub last_query: String, pub selected: usize, pub scroll_offset: usize, + pub visible_rows: usize, pub presence: Presence, pub rect: Option, } impl CodeLangPicker { pub fn ensure_selected_visible(&mut self, total: usize) { + let rows = self.visible_rows; + self.ensure_selected_visible_rows(total, rows); + } + + pub fn ensure_selected_visible_rows(&mut self, total: usize, visible_rows: usize) { + let rows = visible_rows.max(1); + self.visible_rows = rows; if total == 0 { self.selected = 0; self.scroll_offset = 0; return; } self.selected = self.selected.min(total - 1); - let max_scroll = total.saturating_sub(VISIBLE_LANG_ROWS); + let max_scroll = total.saturating_sub(rows); if self.selected < self.scroll_offset { self.scroll_offset = self.selected; - } else if self.selected >= self.scroll_offset + VISIBLE_LANG_ROWS { - self.scroll_offset = self.selected + 1 - VISIBLE_LANG_ROWS; + } else if self.selected >= self.scroll_offset + rows { + self.scroll_offset = self.selected + 1 - rows; } self.scroll_offset = self.scroll_offset.min(max_scroll); } @@ -142,6 +152,21 @@ impl Overlays { /// Open (or toggle off if already open for `block_id`) the searchable code language picker. pub fn open_code_lang_picker(&mut self, block_id: String, current_lang: &str, now_ms: f64) { + self.open_code_lang_picker_with_rows( + block_id, + current_lang, + VISIBLE_LANG_ROWS_DESKTOP, + now_ms, + ); + } + + pub(super) fn open_code_lang_picker_with_rows( + &mut self, + block_id: String, + current_lang: &str, + visible_rows: usize, + now_ms: f64, + ) { if self .code_lang_picker() .is_some_and(|p| p.block_id == block_id) @@ -167,15 +192,18 @@ impl Overlays { .iter() .position(|(id, _)| *id == norm) .unwrap_or(0); + let rows = visible_rows.max(1); let mut picker = CodeLangPicker { block_id, input: LinkBar::new(String::new()), + last_query: String::new(), selected: initial_idx, scroll_offset: 0, + visible_rows: rows, presence, rect: None, }; - picker.ensure_selected_visible(CODE_LANGUAGES.len()); + picker.ensure_selected_visible_rows(CODE_LANGUAGES.len(), rows); self.code_lang_picker = Some(picker); } @@ -216,18 +244,43 @@ impl Overlays { if !scene.anchor_visible(&anchor_world) { return None; } + let touch = scene.is_touch || scene.form_factor != crate::block_flow::FormFactor::Desktop; + let visible_rows = if touch { + VISIBLE_LANG_ROWS_TOUCH + } else { + VISIBLE_LANG_ROWS_DESKTOP + }; let query = picker.input.text(); let items = filter_code_languages(&query); - picker.ensure_selected_visible(items.len()); - let max_rows = items.len().clamp(1, VISIBLE_LANG_ROWS); - let row_h = 26.0_f32; - let search_h = 28.0_f32; + let modality_changed = picker.visible_rows != visible_rows; + picker.visible_rows = visible_rows; + if query != picker.last_query { + picker.last_query = query.clone(); + picker.selected = 0; + picker.scroll_offset = 0; + } else if items.is_empty() { + picker.selected = 0; + picker.scroll_offset = 0; + } else if modality_changed { + picker.ensure_selected_visible_rows(items.len(), visible_rows); + } else { + picker.selected = picker.selected.min(items.len() - 1); + picker.scroll_offset = picker + .scroll_offset + .min(items.len().saturating_sub(visible_rows.max(1))); + } + let max_rows = items.len().clamp(1, visible_rows); + let row_h = if touch { 44.0_f32 } else { 26.0_f32 }; + let search_h = if touch { 40.0_f32 } else { 28.0_f32 }; let pad = 6.0_f32; - let width = 196.0_f32; + let width = if touch { 220.0_f32 } else { 196.0_f32 }; let height = (2.0 * (pad + POPOVER_BORDER) + search_h + 6.0 + max_rows as f32 * row_h).round(); let anchor = scene.world_to_screen(&anchor_world); - let viewport = scene.popover_viewport(); + let mut viewport = scene.popover_viewport(); + if touch { + viewport.h = (viewport.h - 60.0).max(height + 2.0 * POPOVER_EDGE_MARGIN); + } let placed = place_popover( anchor, (width, height), @@ -290,11 +343,7 @@ impl Overlays { }); let mut list = div().flex().flex_col().overflow_hidden(); - for (idx, &(wire_id, label)) in items - .iter() - .enumerate() - .skip(scroll_off) - .take(VISIBLE_LANG_ROWS) + for (idx, &(wire_id, label)) in items.iter().enumerate().skip(scroll_off).take(visible_rows) { let is_current = current_lang == wire_id; let is_sel = idx == selected_idx; @@ -383,14 +432,21 @@ impl Overlays { root = root .occlude() .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_scroll(cx.listener(|view: &mut V, ev: &ScrollEvent, w, cx| { + .on_scroll(cx.listener(move |view: &mut V, ev: &ScrollEvent, w, cx| { cx.stop_propagation(); let dy = match ev.delta { ScrollDelta::Pixels(p) => f32::from(p.y), - ScrollDelta::Lines(l) => l.y * 26.0, + ScrollDelta::Lines(l) => l.y * row_h, }; if dy.abs() > 0.1 { - let rows = if dy < 0.0 { 1 } else { -1 }; + let scaled = (-dy / row_h).round() as isize; + let rows = if scaled != 0 { + scaled.clamp(-12, 12) + } else if dy < 0.0 { + 1 + } else { + -1 + }; view.dispatch_overlay(OverlayEvent::CodeLangPickerScroll(rows), w, cx); } })) @@ -409,6 +465,21 @@ impl Overlays { effects: &mut super::OverlayEffects, ) { match event { + OverlayEvent::SetCodeLanguage { block_id, language } => { + self.close_code_lang_picker(now_ms); + effects.edits.push(super::DocEdit::SetProp { + block_id: block_id.clone(), + key: "prop:language", + value: super::helpers::normalize_code_language(language), + }); + effects.redraw = true; + } + OverlayEvent::TouchContextBarScroll(delta_x) => { + if delta_x.abs() > 0.1 { + self.touch_bar_scroll_x = (self.touch_bar_scroll_x - delta_x).max(0.0); + effects.redraw = true; + } + } OverlayEvent::OpenCodeLangPicker(block_id) => { let current_lang = scene .and_then(|s| s.snapshot.block(block_id)) @@ -419,13 +490,33 @@ impl Overlays { _ => None, }) .unwrap_or(""); - self.open_code_lang_picker(block_id.clone(), current_lang, now_ms); + let visible_rows = if scene.is_some_and(|s| { + s.is_touch || s.form_factor != crate::block_flow::FormFactor::Desktop + }) { + VISIBLE_LANG_ROWS_TOUCH + } else { + VISIBLE_LANG_ROWS_DESKTOP + }; + self.open_code_lang_picker_with_rows( + block_id.clone(), + current_lang, + visible_rows, + now_ms, + ); effects.redraw = true; } OverlayEvent::CodeLangPickerScroll(delta_rows) => { + let visible_rows = if scene.is_some_and(|s| { + s.is_touch || s.form_factor != crate::block_flow::FormFactor::Desktop + }) { + VISIBLE_LANG_ROWS_TOUCH + } else { + VISIBLE_LANG_ROWS_DESKTOP + }; if let Some(picker) = self.code_lang_picker_mut() { + picker.visible_rows = visible_rows; let total = filter_code_languages(&picker.input.text()).len(); - let max_scroll = total.saturating_sub(VISIBLE_LANG_ROWS); + let max_scroll = total.saturating_sub(visible_rows); picker.scroll_offset = picker .scroll_offset .saturating_add_signed(*delta_rows) @@ -470,19 +561,7 @@ impl Overlays { }); effects.redraw = true; } - OverlayEvent::OpenImageLightbox(block_id) => { - self.open_image_lightbox(block_id.clone(), now_ms); - effects.redraw = true; - } - OverlayEvent::ImageLightboxZoom(delta) => { - effects.redraw = self.set_image_lightbox_zoom(*delta); - } - OverlayEvent::ImageLightboxPan { dx, dy } => { - effects.redraw = self.pan_image_lightbox(*dx, *dy); - } - OverlayEvent::CloseImageLightbox => { - effects.redraw = self.close_image_lightbox(now_ms); - } + ev if self.handle_image_lightbox_event(ev, now_ms, effects) => {} OverlayEvent::CalloutAction { block_id, action } => { self.handle_callout_action(block_id, action, effects); } diff --git a/blocksuite/crates/editor/src/overlays/context_menu.rs b/blocksuite/crates/editor/src/overlays/context_menu.rs index cd4f5e155e..d974b0ab70 100644 --- a/blocksuite/crates/editor/src/overlays/context_menu.rs +++ b/blocksuite/crates/editor/src/overlays/context_menu.rs @@ -31,8 +31,6 @@ pub const CONTEXT_MENU_ROW_HEIGHT: f32 = 30.0; const CONTEXT_MENU_SEPARATOR_HEIGHT: f32 = 9.0; /// Duration of the clipboard fallback toast in milliseconds on the scheduler clock. pub const CONTEXT_TOAST_MS: u64 = 2_200; -/// Enter/exit fade and slide duration for the bottom toast. -pub const TOAST_MOTION_MS: f64 = 230.0; /// Command executed when clicking a desktop context menu item. #[derive(Clone, Debug, PartialEq, Eq)] @@ -136,12 +134,10 @@ impl ContextMenuState { } /// Transient non-blocking toast shown when Paste cannot read the platform clipboard directly. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, Eq)] pub struct ContextToast { pub message: String, pub generation: u64, - /// Scheduler-clock fade-in transition (`230ms`), seeded on first render when absent. - pub fade: Option, } /// Place a context menu anchored at `(anchor_x, anchor_y)` inside `viewport`, flipping @@ -379,18 +375,13 @@ pub(super) fn render_context_menu( } /// Render the transient clipboard shortcut hint toast centered near the bottom of the viewport, -/// avoiding soft-keyboard and mobile toolbar insets with a `230ms` fade+slide transition. +/// avoiding soft-keyboard and mobile toolbar insets. pub(super) fn render_context_toast( - toast: &mut ContextToast, + toast: &ContextToast, viewport: FlowRect, bottom_clearance: f32, - now_ms: f64, palette: &Palette, ) -> AnyElement { - let _ = toast - .fade - .get_or_insert_with(|| super::EaseOut::with_duration(1.0, 1.0, now_ms, TOAST_MOTION_MS)); - let progress = 1.0_f32; let est_w = (toast.message.chars().count() as f32 * 7.2 + 32.0).max(228.0); let width = est_w.min((viewport.w - 2.0 * POPOVER_EDGE_MARGIN).max(120.0)); let height = 34.0; @@ -414,7 +405,6 @@ pub(super) fn render_context_toast( .border_1() .border_color(palette.border) .shadow(palette.theme.shadows("--affine-toolbar-shadow").into()) - .opacity(progress) .flex() .items_center() .justify_center() @@ -483,7 +473,6 @@ impl super::Overlays { self.context_toast = Some(ContextToast { message: message.into(), generation, - fade: None, }); generation } @@ -539,10 +528,6 @@ impl super::Overlays { .block_menu .as_ref() .is_some_and(|m| m.presence.in_flight(now_ms) || m.presence.closing) - || self - .context_toast - .as_ref() - .is_some_and(|t| t.fade.is_none_or(|f| !f.is_finished(now_ms))) { window.request_animation_frame(); } @@ -563,12 +548,11 @@ impl super::Overlays { } let kb_clearance = self.keyboard_toolbar_reserved_height(window_size.1); let bottom_clearance = kb_clearance.max(48.0); - if let Some(toast) = self.context_toast.as_mut() { + if let Some(toast) = self.context_toast.as_ref() { elements.push(render_context_toast( toast, viewport, bottom_clearance, - now_ms, palette, )); } diff --git a/blocksuite/crates/editor/src/overlays/helpers.rs b/blocksuite/crates/editor/src/overlays/helpers.rs index c5f4bc3d6a..e9830c51fc 100644 --- a/blocksuite/crates/editor/src/overlays/helpers.rs +++ b/blocksuite/crates/editor/src/overlays/helpers.rs @@ -662,7 +662,8 @@ impl Overlays { }) { self.link_popup = None; } - self.sync_toolbar(scene.selection, now_ms); + let toolbar_sel = scene.selection.filter(|_| self.block_menu().is_none()); + self.sync_toolbar(toolbar_sel, now_ms); if self .toolbar .as_ref() diff --git a/blocksuite/crates/editor/src/overlays/image_lightbox.rs b/blocksuite/crates/editor/src/overlays/image_lightbox.rs index 957048c8d2..aee6634c9c 100644 --- a/blocksuite/crates/editor/src/overlays/image_lightbox.rs +++ b/blocksuite/crates/editor/src/overlays/image_lightbox.rs @@ -4,8 +4,8 @@ use blocksuite_playground_doc::read::BlockContent; use ui::{ - AnyElement, ClickEvent, Context, FontWeight, MouseButton, ScrollDelta, ScrollEvent, - SharedString, div, img, prelude::*, px, + AnyElement, ClickEvent, Context, FontWeight, MouseButton, MouseDownEvent, MouseMoveEvent, + MouseUpEvent, PinchEvent, ScrollDelta, ScrollEvent, SharedString, div, img, prelude::*, px, }; use crate::{ @@ -23,6 +23,9 @@ pub struct ImageLightboxState { pub block_id: String, pub zoom: f32, pub pan: (f32, f32), + pub drag_origin: Option<(f32, f32)>, + pub drag_last: Option<(f32, f32)>, + pub dragged: bool, pub presence: Presence, } @@ -49,6 +52,9 @@ impl Overlays { block_id, zoom: 1.0, pan: (0.0, 0.0), + drag_origin: None, + drag_last: None, + dragged: false, presence, }); } @@ -143,7 +149,7 @@ impl Overlays { return None; }; let (win_w, win_h) = scene.window; - let touch = scene.form_factor != crate::block_flow::FormFactor::Desktop; + let touch = scene.is_touch || scene.form_factor != crate::block_flow::FormFactor::Desktop; let ctrl_h = if touch { 44.0 } else { 30.0 }; let ctrl_min_w = if touch { 44.0 } else { 30.0 }; let natural = render_img.size(0); @@ -267,7 +273,7 @@ impl Overlays { )), ); - let image_el = div() + let mut image_el = div() .id("image-lightbox-viewport") .relative() .w(px(viewport_w)) @@ -278,7 +284,6 @@ impl Overlays { "overlay.image_lightbox.viewport", Some("overlay.image_lightbox"), ) - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_click(|_: &ClickEvent, _, cx| cx.stop_propagation()) .child( div() @@ -293,6 +298,22 @@ impl Overlays { ) .child(img(render_img.clone()).w(px(img_w)).h(px(img_h))), ); + if interactive { + image_el = image_el.on_mouse_down( + MouseButton::Left, + cx.listener(|view: &mut V, ev: &MouseDownEvent, w, cx| { + cx.stop_propagation(); + view.dispatch_overlay( + OverlayEvent::ImageLightboxDragStart { + x: f32::from(ev.position.x), + y: f32::from(ev.position.y), + }, + w, + cx, + ); + }), + ); + } let mut backdrop = place(FlowRect::new(0.0, 0.0, win_w, win_h)) .id("image-lightbox") @@ -322,20 +343,176 @@ impl Overlays { if interactive { backdrop = backdrop .occlude() - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_scroll(cx.listener(|view: &mut V, ev: &ScrollEvent, w, cx| { + .on_mouse_down( + MouseButton::Left, + cx.listener(|view: &mut V, ev: &MouseDownEvent, w, cx| { + cx.stop_propagation(); + view.dispatch_overlay( + OverlayEvent::ImageLightboxDragStart { + x: f32::from(ev.position.x), + y: f32::from(ev.position.y), + }, + w, + cx, + ); + }), + ) + .on_mouse_move(cx.listener(|view: &mut V, ev: &MouseMoveEvent, w, cx| { + if ev.pressed_button == Some(MouseButton::Left) { + cx.stop_propagation(); + view.dispatch_overlay( + OverlayEvent::ImageLightboxDragMove { + x: f32::from(ev.position.x), + y: f32::from(ev.position.y), + }, + w, + cx, + ); + } + })) + .on_mouse_up( + MouseButton::Left, + cx.listener(|view: &mut V, _ev: &MouseUpEvent, w, cx| { + view.dispatch_overlay(OverlayEvent::ImageLightboxDragEnd, w, cx); + }), + ) + .on_pinch(cx.listener(move |view: &mut V, ev: &PinchEvent, w, cx| { cx.stop_propagation(); - let dy = match ev.delta { - ScrollDelta::Pixels(p) => f32::from(p.y), - ScrollDelta::Lines(l) => l.y * 24.0, - }; - if dy.abs() > 0.1 { - let step = if dy > 0.0 { 0.25 } else { -0.25 }; + let step = (ev.delta * zoom).clamp(-0.5, 0.5); + if step.abs() > 0.001 { view.dispatch_overlay(OverlayEvent::ImageLightboxZoom(step), w, cx); } })) - .on_click(emit(cx, |_: &ClickEvent| OverlayEvent::CloseImageLightbox)); + .on_scroll(cx.listener(|view: &mut V, ev: &ScrollEvent, w, cx| { + cx.stop_propagation(); + if ev.source == ui::ScrollSource::Touch { + return; + } + let step = match ev.delta { + ScrollDelta::Pixels(p) => (f32::from(p.y) / 320.0).clamp(-0.25, 0.25), + ScrollDelta::Lines(l) => (l.y * 0.25).clamp(-0.5, 0.5), + }; + if step.abs() > 0.001 { + view.dispatch_overlay(OverlayEvent::ImageLightboxZoom(step), w, cx); + } + })) + .on_click(emit(cx, |_: &ClickEvent| { + OverlayEvent::ImageLightboxBackdropClick + })); } Some(backdrop.into_any_element()) } + + /// Close the topmost transient overlay for a platform Back action. + /// Returns `Some(true)` when text-input focus changed, `Some(false)` when a non-input + /// overlay closed, or `None` when no transient overlay was open. + pub fn dismiss_transient_for_back(&mut self, now_ms: f64) -> Option { + if self.close_image_lightbox(now_ms) || self.close_callout_icon_picker() { + return Some(false); + } + if self.close_code_lang_picker(now_ms) { + return Some(true); + } + if self.bookmark_prompt().is_some() { + self.close_bookmark_prompt_at(now_ms); + return Some(true); + } + if self.link_field().is_some() { + self.close_link_field(); + return Some(true); + } + if self.close_toolbar_submenu() || self.close_link_popup(now_ms) { + return Some(false); + } + if self.keyboard_toolbar_active_panel().is_some() { + self.close_keyboard_toolbar_panel(); + return Some(false); + } + if self.close_slash(now_ms) + | self.close_linked_doc(now_ms) + | self.close_context_menu(now_ms) + { + return Some(false); + } + None + } + + pub(super) fn handle_image_lightbox_event( + &mut self, + event: &OverlayEvent, + now_ms: f64, + effects: &mut super::OverlayEffects, + ) -> bool { + match event { + OverlayEvent::OpenImageLightbox(block_id) => { + self.open_image_lightbox(block_id.clone(), now_ms); + effects.redraw = true; + } + OverlayEvent::ImageLightboxZoom(delta) => { + effects.redraw = self.set_image_lightbox_zoom(*delta); + } + OverlayEvent::ImageLightboxPan { dx, dy } => { + effects.redraw = self.pan_image_lightbox(*dx, *dy); + } + OverlayEvent::ImageLightboxDragStart { x, y } => { + if let Some(lb) = self + .image_lightbox + .as_mut() + .filter(|lb| !lb.presence.closing) + { + lb.drag_origin = Some((*x, *y)); + lb.drag_last = Some((*x, *y)); + lb.dragged = false; + } + } + OverlayEvent::ImageLightboxDragMove { x, y } => { + let delta = self + .image_lightbox + .as_mut() + .filter(|lb| !lb.presence.closing) + .and_then(|lb| { + let (lx, ly) = lb.drag_last?; + let (dx, dy) = (*x - lx, *y - ly); + if dx.hypot(dy) < 0.5 { + return None; + } + lb.drag_last = Some((*x, *y)); + if lb.zoom > 1.001 + && lb + .drag_origin + .is_some_and(|(ox, oy)| (*x - ox).hypot(*y - oy) >= 4.0) + { + lb.dragged = true; + } + Some((dx, dy)) + }); + if let Some((dx, dy)) = delta { + effects.redraw = self.pan_image_lightbox(dx, dy); + } + } + OverlayEvent::ImageLightboxDragEnd => { + if let Some(lb) = self.image_lightbox.as_mut() { + lb.drag_origin = None; + lb.drag_last = None; + } + } + OverlayEvent::ImageLightboxBackdropClick => { + let was_dragged = self.image_lightbox.as_mut().is_some_and(|lb| { + let d = lb.dragged; + lb.dragged = false; + lb.drag_origin = None; + lb.drag_last = None; + d + }); + if !was_dragged { + effects.redraw = self.close_image_lightbox(now_ms); + } + } + OverlayEvent::CloseImageLightbox => { + effects.redraw = self.close_image_lightbox(now_ms); + } + _ => return false, + } + true + } } diff --git a/blocksuite/crates/editor/src/overlays/image_toolbar.rs b/blocksuite/crates/editor/src/overlays/image_toolbar.rs index 4b3c0f42ba..95dc60b6d2 100644 --- a/blocksuite/crates/editor/src/overlays/image_toolbar.rs +++ b/blocksuite/crates/editor/src/overlays/image_toolbar.rs @@ -3,7 +3,8 @@ use blocksuite_playground_doc::read::{BlockContent, TextAlign as BlockAlign}; use ui::{ - AnyElement, ClickEvent, Context, MouseButton, MouseDownEvent, SharedString, div, prelude::*, px, + AnyElement, ClickEvent, Context, MouseButton, MouseDownEvent, ScrollEvent, SharedString, div, + prelude::*, px, }; use crate::theme::Palette; @@ -33,6 +34,86 @@ pub enum ImageToolbarAction { } impl Overlays { + /// Synchronize and clamp the horizontal scroll offset of the active touch bottom context bar. + pub(super) fn sync_touch_bar_scroll(&mut self, key: &str, max_scroll: f32) -> f32 { + if self.touch_bar_block_id.as_deref() != Some(key) { + self.touch_bar_block_id = Some(key.to_string()); + self.touch_bar_scroll_x = 0.0; + } + self.touch_bar_scroll_x = self.touch_bar_scroll_x.clamp(0.0, max_scroll.max(0.0)); + self.touch_bar_scroll_x + } + + /// Build a horizontally clipped scroll strip with soft left/right edge fades when scrollable. + pub(super) fn build_touch_scroll_strip( + avail_w: f32, + height: f32, + gap: f32, + scroll_x: f32, + palette: &Palette, + items: Vec<(f32, Box AnyElement>)>, + ) -> AnyElement { + let mut content_w = 0.0_f32; + for (i, (w, _)) in items.iter().enumerate() { + if i > 0 { + content_w += gap; + } + content_w += *w; + } + let mut strip = div() + .relative() + .flex_none() + .w(px(avail_w)) + .h(px(height)) + .overflow_hidden(); + let mut cursor = 0.0_f32; + for (item_w, builder) in items { + let item_x = (cursor - scroll_x).round(); + cursor += item_w + gap; + if item_x + item_w <= 0.0 || item_x >= avail_w { + continue; + } + let fully_visible = item_x >= -0.5 && item_x + item_w <= avail_w + 0.5; + let el = builder(fully_visible); + strip = strip.child( + div() + .absolute() + .left(px(item_x)) + .top(px(0.0)) + .w(px(item_w)) + .h(px(height)) + .child(el), + ); + } + if scroll_x > 0.5 { + for (step_x, alpha) in [(0.0, 0.92), (4.0, 0.65), (8.0, 0.35), (12.0, 0.12)] { + strip = strip.child( + div() + .absolute() + .left(px(step_x)) + .top(px(0.0)) + .w(px(4.0)) + .h(px(height)) + .bg(palette.panel.opacity(alpha)), + ); + } + } + if scroll_x + avail_w < content_w - 0.5 { + for (offset_r, alpha) in [(4.0, 0.92), (8.0, 0.65), (12.0, 0.35), (16.0, 0.12)] { + strip = strip.child( + div() + .absolute() + .left(px((avail_w - offset_r).max(0.0))) + .top(px(0.0)) + .w(px(4.0)) + .h(px(height)) + .bg(palette.panel.opacity(alpha)), + ); + } + } + strip.into_any_element() + } + pub(super) fn render_image_toolbar( &mut self, scene: &OverlayScene<'_>, @@ -74,68 +155,225 @@ impl Overlays { _ => None, })?; - // Buttons: Caption | AlignLeft AlignCenter AlignRight | Copy Duplicate [CardView] Delete - let touch = scene.form_factor != crate::block_flow::FormFactor::Desktop; - let btn_h = if touch { 44.0 } else { TOOLBAR_BUTTON }; - let btn_count = if has_blob { 8usize } else { 7usize }; - let sep_count = 2usize; + let touch = scene.is_touch || scene.form_factor != crate::block_flow::FormFactor::Desktop; let vp = scene.popover_viewport(); let max_w = (vp.w - 2.0 * POPOVER_EDGE_MARGIN).max(200.0); let chrome = 2.0 * (TOOLBAR_PADDING + POPOVER_BORDER); - let sep_margin = if touch && max_w < 400.0 { - 2.0 - } else { - TOOLBAR_SEPARATOR_MARGIN - }; - let gap = if touch && max_w < 400.0 { - 1.0 - } else { - TOOLBAR_GAP - }; - let seps_w = sep_count as f32 * (2.0 * sep_margin + 1.0); - let gaps_w = (btn_count.saturating_sub(1 + sep_count)) as f32 * gap; - let btn_w = if touch { - ((max_w - chrome - seps_w - gaps_w) / btn_count as f32) - .floor() - .clamp(36.0, 44.0) - } else { - TOOLBAR_BUTTON - }; - let inner_w = btn_count as f32 * btn_w + gaps_w + seps_w; - let width = if touch { max_w } else { inner_w + chrome }; - let height = btn_h + chrome; - let anchor_screen = scene.world_to_screen(&img_world); - let block_screen = scene.world_to_screen(&flow_block.rect()); - let rect = if touch { - crate::block_flow::FlowRect::new( + let hover_bg = palette.hover; + let danger = palette + .theme + .css_var("--affine-error-color") + .unwrap_or(palette.icon); + + if touch { + let btn = 44.0_f32; + let gap = 2.0_f32; + let sep_slot = 9.0_f32; + let scroll_btn_count = if has_blob { 7usize } else { 6usize }; + let content_w = scroll_btn_count as f32 * btn + (scroll_btn_count - 1) as f32 * gap; + let pinned_right_w = sep_slot + btn + 2.0 * gap; + let width = (content_w + pinned_right_w + chrome).min(max_w).round(); + let height = (btn + chrome).round(); + let avail_w = (width - chrome - pinned_right_w).max(btn); + let max_scroll = (content_w - avail_w).max(0.0).ceil(); + let scroll_key = format!("img:{block_id}"); + let scroll_x = self.sync_touch_bar_scroll(&scroll_key, max_scroll); + + let rect = crate::block_flow::FlowRect::new( (vp.x + (vp.w - width) * 0.5).round(), (vp.bottom() - height - POPOVER_EDGE_MARGIN).round(), - width.round(), - height.round(), - ) - } else { - let mut placed = place_popover( - anchor_screen, - (width, height), - vp, - Placement::Above, - POPOVER_GAP, - POPOVER_EDGE_MARGIN, + width, + height, ); - let vp_min_x = vp.x + POPOVER_EDGE_MARGIN; - let vp_max_x = (vp.right() - POPOVER_EDGE_MARGIN - width).max(vp_min_x); - let col_min_x = block_screen.x.clamp(vp_min_x, vp_max_x); - let col_max_x = (block_screen.right() - width).clamp(col_min_x, vp_max_x); - placed.rect.x = placed.rect.x.clamp(col_min_x, col_max_x); - placed.rect - }; - self.image_toolbar_rect = Some(rect); + self.image_toolbar_rect = Some(rect); + + let make_touch_btn = |id_suffix: &'static str, + active: bool, + action: ImageToolbarAction, + glyph: AnyElement, + cx: &mut Context| + -> Box AnyElement> { + let ev = OverlayEvent::ImageToolbarAction { + block_id: block_id.to_string(), + action, + }; + let click_handler = emit(cx, move |_: &ClickEvent| ev.clone()); + let brand_bg = palette.brand.opacity(0.14); + Box::new(move |fully_visible| { + let mut el = div() + .id(SharedString::from(format!("img-tb-{id_suffix}"))) + .w(px(btn)) + .h(px(btn)) + .rounded(px(4.0)) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .bg(if active { + brand_bg + } else { + ui::transparent_black() + }) + .hover(move |s| s.bg(hover_bg)) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(click_handler) + .child(glyph); + if fully_visible { + el = el + .snapshot( + SharedString::from(format!("overlay.image_toolbar.{id_suffix}")), + Some("overlay.image_toolbar"), + ) + .snapshot_focused(active); + } + el.into_any_element() + }) + }; + + let mut items: Vec<(f32, Box AnyElement>)> = vec![( + btn, + make_touch_btn( + "caption", + has_caption, + ImageToolbarAction::Caption, + icon( + "AddTextIcon", + 16.0, + if has_caption { + palette.brand + } else { + palette.icon + }, + ) + .into_any_element(), + cx, + ), + )]; + for (id_suffix, align) in [ + ("align_left", BlockAlign::Left), + ("align_center", BlockAlign::Center), + ("align_right", BlockAlign::Right), + ] { + let active = current_align == align; + items.push(( + btn, + make_touch_btn( + id_suffix, + active, + ImageToolbarAction::Align(align), + align_glyph(align, if active { palette.brand } else { palette.icon }) + .into_any_element(), + cx, + ), + )); + } + items.push(( + btn, + make_touch_btn( + "copy", + false, + ImageToolbarAction::Copy, + icon("CopyIcon", 16.0, palette.icon).into_any_element(), + cx, + ), + )); + items.push(( + btn, + make_touch_btn( + "duplicate", + false, + ImageToolbarAction::Duplicate, + icon("DuplicateIcon", 16.0, palette.icon).into_any_element(), + cx, + ), + )); + if has_blob { + items.push(( + btn, + make_touch_btn( + "card_view", + false, + ImageToolbarAction::TurnIntoCardView, + icon("PageIcon", 16.0, palette.icon).into_any_element(), + cx, + ), + )); + } + + let strip = Self::build_touch_scroll_strip(avail_w, btn, gap, scroll_x, palette, items); + let del_btn = make_touch_btn( + "delete", + false, + ImageToolbarAction::Delete, + icon("DeleteIcon", 16.0, danger).into_any_element(), + cx, + )(true); + + let root = place(rect) + .id("image-toolbar") + .occlude() + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_mouse_down_out(|_: &MouseDownEvent, _, _| {}) + .on_scroll(emit(cx, |event: &ScrollEvent| { + let d = event.delta.pixel_delta(px(20.0)); + let dx = f32::from(d.x); + OverlayEvent::TouchContextBarScroll(if dx != 0.0 { dx } else { f32::from(d.y) }) + })) + .p(px(TOOLBAR_PADDING)) + .rounded(px(TOOLBAR_RADIUS)) + .bg(palette.panel) + .border_1() + .border_color(palette.border) + .shadow(palette.theme.shadows("--affine-toolbar-shadow").into()) + .flex() + .items_center() + .gap(px(gap)) + .snapshot("overlay.image_toolbar", Some("root.canvas")) + .child(strip) + .child( + div() + .flex_none() + .w(px(sep_slot)) + .h(px(btn)) + .flex() + .items_center() + .justify_center() + .child(div().w(px(1.0)).h(px(16.0)).bg(palette.divider)), + ) + .child(del_btn); + return Some(root.into_any_element()); + } + + // Desktop floating toolbar: exact content width = buttons + all flex gaps + separators. + let btn_count = if has_blob { 8usize } else { 7usize }; + let sep_count = 2usize; + let total_children = btn_count + sep_count; + let gaps_w = total_children.saturating_sub(1) as f32 * TOOLBAR_GAP; + let seps_w = sep_count as f32 * (2.0 * TOOLBAR_SEPARATOR_MARGIN + 1.0); + let inner_w = btn_count as f32 * TOOLBAR_BUTTON + gaps_w + seps_w; + let width = inner_w + chrome; + let height = TOOLBAR_BUTTON + chrome; + let anchor_screen = scene.world_to_screen(&img_world); + let block_screen = scene.world_to_screen(&flow_block.rect()); + let mut placed = place_popover( + anchor_screen, + (width, height), + vp, + Placement::Above, + POPOVER_GAP, + POPOVER_EDGE_MARGIN, + ); + let vp_min_x = vp.x + POPOVER_EDGE_MARGIN; + let vp_max_x = (vp.right() - POPOVER_EDGE_MARGIN - width).max(vp_min_x); + let col_min_x = block_screen.x.clamp(vp_min_x, vp_max_x); + let col_max_x = (block_screen.right() - width).clamp(col_min_x, vp_max_x); + placed.rect.x = placed.rect.x.clamp(col_min_x, col_max_x); + self.image_toolbar_rect = Some(placed.rect); - let hover_bg = palette.hover; let sep = || { div() .flex_none() - .mx(px(sep_margin)) + .mx(px(TOOLBAR_SEPARATOR_MARGIN)) .w(px(1.0)) .h(px(16.0)) .bg(palette.divider) @@ -152,8 +390,8 @@ impl Overlays { div() .id(SharedString::from(format!("img-tb-{id_suffix}"))) .flex_none() - .w(px(btn_w)) - .h(px(btn_h)) + .w(px(TOOLBAR_BUTTON)) + .h(px(TOOLBAR_BUTTON)) .rounded(px(4.0)) .flex() .items_center() @@ -176,7 +414,7 @@ impl Overlays { .into_any_element() }; - let mut row = div().flex().items_center().gap(px(gap)); + let mut row = div().flex().items_center().gap(px(TOOLBAR_GAP)); row = row.child(make_btn( "caption", has_caption, @@ -233,10 +471,6 @@ impl Overlays { cx, )); } - let danger = palette - .theme - .css_var("--affine-error-color") - .unwrap_or(palette.icon); row = row.child(make_btn( "delete", false, @@ -245,7 +479,7 @@ impl Overlays { cx, )); - let root = place(rect) + let root = place(placed.rect) .id("image-toolbar") .occlude() .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) @@ -258,7 +492,6 @@ impl Overlays { .shadow(palette.theme.shadows("--affine-toolbar-shadow").into()) .flex() .items_center() - .justify_center() .snapshot("overlay.image_toolbar", Some("root.canvas")) .child(row); Some(root.into_any_element()) diff --git a/blocksuite/crates/editor/src/overlays/mod.rs b/blocksuite/crates/editor/src/overlays/mod.rs index 053a2804e3..10992d67d2 100644 --- a/blocksuite/crates/editor/src/overlays/mod.rs +++ b/blocksuite/crates/editor/src/overlays/mod.rs @@ -42,8 +42,7 @@ pub use code_lang_picker::{ }; pub use context_menu::{ CONTEXT_MENU_PADDING, CONTEXT_MENU_RADIUS, CONTEXT_MENU_ROW_HEIGHT, CONTEXT_MENU_WIDTH, - CONTEXT_TOAST_MS, ContextMenuAction, ContextMenuState, ContextToast, TOAST_MOTION_MS, - place_context_menu, + CONTEXT_TOAST_MS, ContextMenuAction, ContextMenuState, ContextToast, place_context_menu, }; pub use drag::{ ADD_BLOCK_BUTTON_GAP, ADD_BLOCK_BUTTON_SIZE, DATABASE_HEADER_HOVER_HEIGHT, @@ -99,9 +98,7 @@ pub use toolbar::{ pub use transform::OverlayScreenTransform; pub(crate) use paint_page::align_glyph; -use paint_page::{ - caret_world_rect, drag_handle_rect, emit, hover_block, icon, icon_rotated, place, text_len, -}; +use paint_page::{caret_world_rect, emit, hover_block, icon, icon_rotated, place, text_len}; use toolbar::{FormatToolbar, utf16_to_byte}; use std::collections::{BTreeSet, HashMap}; @@ -350,6 +347,22 @@ pub enum OverlayEvent { dx: f32, dy: f32, }, + /// Begin pointer drag-pan inside the open Lightbox at window-space `(x, y)`. + ImageLightboxDragStart { + x: f32, + y: f32, + }, + /// Continue pointer drag-pan inside the open Lightbox at window-space `(x, y)`. + ImageLightboxDragMove { + x: f32, + y: f32, + }, + /// Finish pointer drag-pan inside the open Lightbox. + ImageLightboxDragEnd, + /// Click on the Lightbox backdrop (closes unless suppressed by an active drag). + ImageLightboxBackdropClick, + /// Scroll the touch bottom context bar (`image_toolbar` / `bookmark_toolbar` / `callout_toolbar`). + TouchContextBarScroll(f32), /// Close the fullscreen image Lightbox. CloseImageLightbox, /// Open a Bookmark block's external URL. @@ -577,6 +590,8 @@ pub struct OverlayScene<'a> { pub direction: ui::Direction, /// Explicit device form factor supplied by the host shell. pub form_factor: crate::block_flow::FormFactor, + /// True when either the form factor or active pointer input is touch (`is_touch_host()`). + pub is_touch: bool, /// Code block currently holding the caret or included in whole-block selection. pub focused_code_block: Option<&'a str>, /// Single `affine:image` block currently selected in whole-block selection, if any. @@ -694,6 +709,8 @@ pub struct Overlays { pub(super) callout_toolbar_rect: Option, pub(super) callout_icon_picker_block: Option, pub(super) callout_icon_picker_rect: Option, + pub(super) touch_bar_scroll_x: f32, + pub(super) touch_bar_block_id: Option, pub(super) keyboard_toolbar: KeyboardToolbarState, pub(super) context_menu: Option, pub(super) block_menu: Option, diff --git a/blocksuite/crates/editor/src/overlays/paint_page/controls.rs b/blocksuite/crates/editor/src/overlays/paint_page/controls.rs index d2f3345eb0..e141213dce 100644 --- a/blocksuite/crates/editor/src/overlays/paint_page/controls.rs +++ b/blocksuite/crates/editor/src/overlays/paint_page/controls.rs @@ -92,10 +92,16 @@ impl Overlays { let subtle = touch_browse && !hovered && !focused && !copied; // Left-top clickable language switcher button (`page.block..language`), capped on // narrow viewports so it never overlaps the first line of code or top-right buttons. - let touch_hit = scene.form_factor != crate::block_flow::FormFactor::Desktop; + let touch_hit = + scene.is_touch || scene.form_factor != crate::block_flow::FormFactor::Desktop; + let (_, pad_x) = crate::block_flow::CODE_PADDING; + let lang_w = if touch_hit && rect.w < 460.0 { + (rect.w * 0.28).clamp(64.0, 92.0) + } else { + (rect.w - 2.0 * pad_x).clamp(56.0, 124.0) + }; + let lang_right = rect.x + pad_x - 4.0 + lang_w; if !scene.page_readonly { - let (_, pad_x) = crate::block_flow::CODE_PADDING; - let lang_w = (rect.w - 2.0 * pad_x).clamp(56.0, 124.0); let lang_h = if touch_hit { 44.0 } else { 24.0 }; let lang_y = if touch_hit { (rect.y - 6.0).max(0.0) @@ -106,11 +112,12 @@ impl Overlays { if viewport.intersects(&lang_rect) { let lang_ev = OverlayEvent::OpenCodeLangPicker(block.block_id.clone()); let lang_display = super::display_code_language(code_lang); + let lang_hover = palette.text_primary.opacity(0.07); let mut lang_btn = place(viewport.to_local(&lang_rect)) .id(SharedString::from(format!("code-lang-{}", block.block_id))) .rounded(px(4.0)) .cursor_pointer() - .hover(move |s| s.bg(hover_filled)) + .hover(move |s| s.bg(lang_hover)) .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_click(emit(cx, move |_: &ClickEvent| lang_ev.clone())); if viewport.fully_visible(&lang_rect) { @@ -200,17 +207,24 @@ impl Overlays { } elements.push(element.into_any_element()); - let mut cursor_x = visual_copy.x - 4.0; + let min_left_x = if scene.page_readonly { + rect.x + 16.0 + } else { + (lang_right + 4.0).max(rect.x + 96.0) + }; + let btn_gap = if touch_hit { 2.0 } else { 4.0 }; + let hit_h = if touch_hit { 44.0 } else { COPY_BUTTON_SIZE }; + let hit_y = if touch_hit { + visual_copy.y - 8.0 + } else { + visual_copy.y + }; + let mut cursor_x = target.x - btn_gap; let wrap_w = 46.0; - if cursor_x - wrap_w >= rect.x + 96.0 { + if cursor_x - wrap_w >= min_left_x { cursor_x -= wrap_w; - let wrap_hit_h = if touch_hit { 44.0 } else { COPY_BUTTON_SIZE }; - let wrap_hit_y = if touch_hit { - visual_copy.y - 8.0 - } else { - visual_copy.y - }; - let wrap_rect = FlowRect::new(cursor_x, wrap_hit_y, wrap_w, wrap_hit_h); + let visual_wrap = FlowRect::new(cursor_x, visual_copy.y, wrap_w, COPY_BUTTON_SIZE); + let wrap_rect = FlowRect::new(cursor_x, hit_y, wrap_w, hit_h); let wrap_ev = OverlayEvent::ToggleCodeWrap(block.block_id.clone()); let wrap_pill = ui::div() .flex_none() @@ -249,7 +263,7 @@ impl Overlays { .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_click(emit(cx, move |_: &ClickEvent| wrap_ev.clone())) .child(wrap_pill); - if viewport.fully_visible(&visual_copy) { + if viewport.fully_visible(&visual_wrap) { wrap_el = wrap_el .snapshot( SharedString::from(format!("{}.wrap", block.snapshot_id)), @@ -259,19 +273,33 @@ impl Overlays { .snapshot_text("Wrap"); } elements.push(wrap_el.into_any_element()); - cursor_x -= 4.0; + cursor_x -= btn_gap; } - // Desktop-only extra code controls: Line number (`#`), 8-line Collapse/Expand, Caption. - let narrow = touch_browse || rect.w < 460.0; - if !narrow && !scene.page_readonly { - let ln_w = 28.0; - if cursor_x - ln_w >= rect.x + 132.0 { - cursor_x -= ln_w; - let ln_rect = FlowRect::new(cursor_x, target.y, ln_w, COPY_BUTTON_SIZE); + // Extra code controls: Line number (`#`), 8-line Collapse/Expand, Caption. + let narrow_desktop = !touch_browse && rect.w < 460.0; + let extra_min_x = if touch_hit { + min_left_x + } else { + min_left_x.max(rect.x + 132.0) + }; + if !narrow_desktop && !scene.page_readonly { + let ln_pill_w = 28.0; + let ln_hit_w = if touch_hit { 44.0 } else { ln_pill_w }; + if cursor_x - ln_hit_w >= extra_min_x { + cursor_x -= ln_hit_w; + let ln_visual = FlowRect::new( + cursor_x + (ln_hit_w - ln_pill_w) * 0.5, + visual_copy.y, + ln_pill_w, + COPY_BUTTON_SIZE, + ); + let ln_rect = FlowRect::new(cursor_x, hit_y, ln_hit_w, hit_h); let ln_ev = OverlayEvent::ToggleCodeLineNumber(block.block_id.clone()); - let mut ln_el = place(viewport.to_local(&ln_rect)) - .id(SharedString::from(format!("lineno-{}", block.block_id))) + let ln_pill = ui::div() + .flex_none() + .w(px(ln_pill_w)) + .h(px(COPY_BUTTON_SIZE)) .rounded(px(CODE_RADIUS - COPY_BUTTON_INSET)) .bg(if code_line_number { palette.brand.opacity(0.14) @@ -287,7 +315,6 @@ impl Overlays { .flex() .items_center() .justify_center() - .cursor_pointer() .hover(move |s| s.bg(hover_filled)) .text_size(px(11.0)) .font_weight(FontWeight::MEDIUM) @@ -296,10 +323,17 @@ impl Overlays { } else { palette.text_secondary }) + .child("#"); + let mut ln_el = place(viewport.to_local(&ln_rect)) + .id(SharedString::from(format!("lineno-{}", block.block_id))) + .flex() + .items_center() + .justify_center() + .cursor_pointer() .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_click(emit(cx, move |_: &ClickEvent| ln_ev.clone())) - .child("#"); - if viewport.fully_visible(&ln_rect) { + .child(ln_pill); + if viewport.fully_visible(&ln_visual) { ln_el = ln_el .snapshot( SharedString::from(format!("{}.line_number", block.snapshot_id)), @@ -309,18 +343,22 @@ impl Overlays { .snapshot_text("Line numbers"); } elements.push(ln_el.into_any_element()); - cursor_x -= 4.0; + cursor_x -= btn_gap; } if code_line_count > 8 || code_collapsed { let fold_w = 56.0; - if cursor_x - fold_w >= rect.x + 132.0 { + if cursor_x - fold_w >= extra_min_x { cursor_x -= fold_w; - let fold_rect = FlowRect::new(cursor_x, target.y, fold_w, COPY_BUTTON_SIZE); + let fold_visual = + FlowRect::new(cursor_x, visual_copy.y, fold_w, COPY_BUTTON_SIZE); + let fold_rect = FlowRect::new(cursor_x, hit_y, fold_w, hit_h); let fold_ev = OverlayEvent::ToggleCodeCollapsed(block.block_id.clone()); let fold_label = if code_collapsed { "Expand" } else { "Collapse" }; - let mut fold_el = place(viewport.to_local(&fold_rect)) - .id(SharedString::from(format!("fold-{}", block.block_id))) + let fold_pill = ui::div() + .flex_none() + .w(px(fold_w)) + .h(px(COPY_BUTTON_SIZE)) .rounded(px(CODE_RADIUS - COPY_BUTTON_INSET)) .bg(if code_collapsed { palette.brand.opacity(0.14) @@ -336,7 +374,6 @@ impl Overlays { .flex() .items_center() .justify_center() - .cursor_pointer() .hover(move |s| s.bg(hover_filled)) .text_size(px(11.0)) .font_weight(FontWeight::MEDIUM) @@ -345,10 +382,17 @@ impl Overlays { } else { palette.text_secondary }) + .child(fold_label); + let mut fold_el = place(viewport.to_local(&fold_rect)) + .id(SharedString::from(format!("fold-{}", block.block_id))) + .flex() + .items_center() + .justify_center() + .cursor_pointer() .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_click(emit(cx, move |_: &ClickEvent| fold_ev.clone())) - .child(fold_label); - if viewport.fully_visible(&fold_rect) { + .child(fold_pill); + if viewport.fully_visible(&fold_visual) { fold_el = fold_el .snapshot( SharedString::from(format!("{}.collapse", block.snapshot_id)), @@ -358,19 +402,28 @@ impl Overlays { .snapshot_text(fold_label); } elements.push(fold_el.into_any_element()); - cursor_x -= 4.0; + cursor_x -= btn_gap; } } - let cap_w = 28.0; - if cursor_x - cap_w >= rect.x + 132.0 { - cursor_x -= cap_w; - let cap_rect = FlowRect::new(cursor_x, target.y, cap_w, COPY_BUTTON_SIZE); + let cap_pill_w = 28.0; + let cap_hit_w = if touch_hit { 44.0 } else { cap_pill_w }; + if cursor_x - cap_hit_w >= extra_min_x { + cursor_x -= cap_hit_w; + let cap_visual = FlowRect::new( + cursor_x + (cap_hit_w - cap_pill_w) * 0.5, + visual_copy.y, + cap_pill_w, + COPY_BUTTON_SIZE, + ); + let cap_rect = FlowRect::new(cursor_x, hit_y, cap_hit_w, hit_h); let cap_ev = OverlayEvent::OpenCaptionPrompt { block_id: block.block_id.clone(), }; - let mut cap_el = place(viewport.to_local(&cap_rect)) - .id(SharedString::from(format!("code-cap-{}", block.block_id))) + let cap_pill = ui::div() + .flex_none() + .w(px(cap_pill_w)) + .h(px(COPY_BUTTON_SIZE)) .rounded(px(CODE_RADIUS - COPY_BUTTON_INSET)) .bg(if has_caption { palette.brand.opacity(0.14) @@ -386,10 +439,7 @@ impl Overlays { .flex() .items_center() .justify_center() - .cursor_pointer() .hover(move |s| s.bg(hover_filled)) - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_click(emit(cx, move |_: &ClickEvent| cap_ev.clone())) .child(icon( "AddTextIcon", 15.0, @@ -399,7 +449,16 @@ impl Overlays { palette.icon }, )); - if viewport.fully_visible(&cap_rect) { + let mut cap_el = place(viewport.to_local(&cap_rect)) + .id(SharedString::from(format!("code-cap-{}", block.block_id))) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(emit(cx, move |_: &ClickEvent| cap_ev.clone())) + .child(cap_pill); + if viewport.fully_visible(&cap_visual) { cap_el = cap_el .snapshot( SharedString::from(format!("{}.caption_btn", block.snapshot_id)), @@ -409,20 +468,23 @@ impl Overlays { .snapshot_text("Caption"); } elements.push(cap_el.into_any_element()); - cursor_x -= 4.0; + cursor_x -= btn_gap; } } if preview_kind.is_some() { let prev_w = 56.0; - if cursor_x - prev_w >= rect.x + 96.0 { + if cursor_x - prev_w >= min_left_x { cursor_x -= prev_w; - let prev_rect = FlowRect::new(cursor_x, target.y, prev_w, COPY_BUTTON_SIZE); + let prev_visual = FlowRect::new(cursor_x, visual_copy.y, prev_w, COPY_BUTTON_SIZE); + let prev_rect = FlowRect::new(cursor_x, hit_y, prev_w, hit_h); let in_preview = block.body.text.is_none(); let prev_label = if in_preview { "Code" } else { "Preview" }; let prev_ev = OverlayEvent::ToggleCodePreview(block.block_id.clone()); - let mut prev_el = place(viewport.to_local(&prev_rect)) - .id(SharedString::from(format!("preview-{}", block.block_id))) + let prev_pill = ui::div() + .flex_none() + .w(px(prev_w)) + .h(px(COPY_BUTTON_SIZE)) .rounded(px(CODE_RADIUS - COPY_BUTTON_INSET)) .bg(if in_preview { palette.brand.opacity(0.14) @@ -438,7 +500,6 @@ impl Overlays { .flex() .items_center() .justify_center() - .cursor_pointer() .hover(move |s| s.bg(hover_filled)) .text_size(px(11.0)) .font_weight(FontWeight::MEDIUM) @@ -447,10 +508,17 @@ impl Overlays { } else { palette.text_secondary }) + .child(prev_label); + let mut prev_el = place(viewport.to_local(&prev_rect)) + .id(SharedString::from(format!("preview-{}", block.block_id))) + .flex() + .items_center() + .justify_center() + .cursor_pointer() .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_click(emit(cx, move |_: &ClickEvent| prev_ev.clone())) - .child(prev_label); - if viewport.fully_visible(&prev_rect) { + .child(prev_pill); + if viewport.fully_visible(&prev_visual) { prev_el = prev_el .snapshot( SharedString::from(format!("{}.preview", block.snapshot_id)), diff --git a/blocksuite/crates/editor/src/overlays/paint_page/handle.rs b/blocksuite/crates/editor/src/overlays/paint_page/handle.rs index 4ac64f3661..208001ecfd 100644 --- a/blocksuite/crates/editor/src/overlays/paint_page/handle.rs +++ b/blocksuite/crates/editor/src/overlays/paint_page/handle.rs @@ -37,6 +37,48 @@ const TODO_PHASE2_OFFSETS: [(f32, f32); 6] = [ (-32.0, -16.0), ]; +/// Compute a block's gutter handle rect in world space, shifting Callout child blocks outside +/// the Callout card's outer border so `+⋮⋮` never overlaps the Callout's `ⓘ` / emoji icon. +pub(crate) fn effective_drag_handle_rect( + scene: &OverlayScene<'_>, + block: &crate::block_flow::FlowBlock, +) -> Option { + let mut base = drag_handle_rect( + block, + scene.geometry.column_x, + scene.window.0, + scene.direction, + )?; + if block.x <= 0.5 { + return Some(base); + } + if let Some(root) = scene.snapshot.root.as_ref() { + let mut cur = block.block_id.as_str(); + let mut outer_callout_id: Option<&str> = None; + while let Some((parent, _)) = find_parent(root, cur) { + if matches!( + parent.content, + blocksuite_playground_doc::read::BlockContent::Callout { .. } + ) { + outer_callout_id = Some(parent.id.as_str()); + } + cur = parent.id.as_str(); + } + if let Some(callout_id) = outer_callout_id + && let Some(callout_block) = scene.layout.block(callout_id) + && let Some(callout_handle) = drag_handle_rect( + callout_block, + scene.geometry.column_x, + scene.window.0, + scene.direction, + ) + { + base.x = callout_handle.x; + } + } + Some(base) +} + impl Overlays { /// Two-phase ringless 6-dot radial burst (`240ms` full-alpha shoot to `18px` + `360ms` /// fade-out to `36px`, `-90°` start angle) matching Web `components/src/icons/list.ts`. @@ -215,8 +257,7 @@ impl Overlays { if !scene.page_readonly && let Some(block) = handle_block - && let Some(target) = - drag_handle_rect(block, scene.geometry.column_x, scene.window.0, direction) + && let Some(target) = effective_drag_handle_rect(scene, block) && viewport.intersects(&target) { // `+` quick-insert button immediately outside the drag handle (hidden while dragging). diff --git a/blocksuite/crates/editor/src/overlays/paint_page/mod.rs b/blocksuite/crates/editor/src/overlays/paint_page/mod.rs index aaf9e6eabf..95e586b6c6 100644 --- a/blocksuite/crates/editor/src/overlays/paint_page/mod.rs +++ b/blocksuite/crates/editor/src/overlays/paint_page/mod.rs @@ -11,6 +11,7 @@ pub(super) use geometry::{ pub use geometry::{ block_selection_visual_rects, block_text, bounding_rect, find_parent, shared_alignment, }; +pub(super) use handle::effective_drag_handle_rect; use blocksuite_playground_doc::{read::BlockContent, schema::ListType}; use ui::{ diff --git a/blocksuite/crates/editor/src/overlays/paint_slash.rs b/blocksuite/crates/editor/src/overlays/paint_slash.rs index a78a3280b1..044eed34bc 100644 --- a/blocksuite/crates/editor/src/overlays/paint_slash.rs +++ b/blocksuite/crates/editor/src/overlays/paint_slash.rs @@ -35,7 +35,7 @@ fn slash_context_for_scene(scene: &OverlayScene<'_>, block_id: &str) -> SlashCon SlashContext { in_edgeless_text, in_edgeless_canvas, - flatten_submenus: scene.form_factor.is_touch_form_factor(), + flatten_submenus: scene.is_touch || scene.form_factor.is_touch_form_factor(), } } diff --git a/blocksuite/crates/editor/src/overlays/state.rs b/blocksuite/crates/editor/src/overlays/state.rs index f5125da137..2f2ee0ce27 100644 --- a/blocksuite/crates/editor/src/overlays/state.rs +++ b/blocksuite/crates/editor/src/overlays/state.rs @@ -195,14 +195,7 @@ impl Overlays { && hovered .as_deref() .and_then(|block_id| scene.layout.block(block_id)) - .and_then(|block| { - drag_handle_rect( - block, - scene.geometry.column_x, - scene.window.0, - scene.direction, - ) - }) + .and_then(|block| paint_page::effective_drag_handle_rect(scene, block)) .is_some_and(|handle| handle.contains(world_x, world_y)); if hovered != self.hovered || handle_hot != self.handle_hot { self.hovered = hovered; @@ -239,12 +232,7 @@ impl Overlays { }); let handle_screen_rect = scene.and_then(|s| { let block = s.layout.block(&drag.block_id)?; - let world = drag_handle_rect( - block, - s.geometry.column_x, - s.window.0, - s.direction, - )?; + let world = paint_page::effective_drag_handle_rect(s, block)?; Some(s.world_to_screen(&world)) }); effects.select_block = Some(drag.block_id.clone()); @@ -449,16 +437,8 @@ impl Overlays { OverlayEvent::ToggleCodeWrap(block_id) => { super::helpers::push_toggle_code_wrap(block_id, scene, &mut effects); } - OverlayEvent::SetCodeLanguage { block_id, language } => { - self.close_code_lang_picker(now_ms); - effects.edits.push(DocEdit::SetProp { - block_id, - key: "prop:language", - value: super::helpers::normalize_code_language(&language), - }); - effects.redraw = true; - } - OverlayEvent::OpenCodeLangPicker(_) + OverlayEvent::SetCodeLanguage { .. } + | OverlayEvent::OpenCodeLangPicker(_) | OverlayEvent::CodeLangPickerScroll(_) | OverlayEvent::CloseCodeLangPicker | OverlayEvent::ToggleCodeLineNumber(_) @@ -466,6 +446,11 @@ impl Overlays { | OverlayEvent::OpenImageLightbox(_) | OverlayEvent::ImageLightboxZoom(_) | OverlayEvent::ImageLightboxPan { .. } + | OverlayEvent::ImageLightboxDragStart { .. } + | OverlayEvent::ImageLightboxDragMove { .. } + | OverlayEvent::ImageLightboxDragEnd + | OverlayEvent::ImageLightboxBackdropClick + | OverlayEvent::TouchContextBarScroll(_) | OverlayEvent::CloseImageLightbox | OverlayEvent::CalloutAction { .. } | OverlayEvent::CloseCalloutIconPicker => { diff --git a/blocksuite/crates/playground/src/chrome/mod.rs b/blocksuite/crates/playground/src/chrome/mod.rs index e385dbc39f..03184144c3 100644 --- a/blocksuite/crates/playground/src/chrome/mod.rs +++ b/blocksuite/crates/playground/src/chrome/mod.rs @@ -437,7 +437,19 @@ impl ui::Render for PlaygroundView { let viewport_height = (f32::from(viewport.height) - TOPBAR_HEIGHT) .max(0.0) .floor(); - self.window_size = (viewport_width, f32::from(viewport.height).floor()); + let new_window_size = (viewport_width, f32::from(viewport.height).floor()); + #[cfg(target_family = "wasm")] + if self.window_size != new_window_size && self.form_factor == crate::FormFactor::Desktop { + if let Some(web_win) = web_sys::window() { + self.pointer_kind = + if crate::view_room::web_is_touch_modality(&web_win, viewport_width) { + crate::PointerKind::Touch + } else { + crate::PointerKind::Mouse + }; + } + } + self.window_size = new_window_size; let presences = self.remote_presences(&palette); let switcher_left = ((viewport_width - PILL_WIDTH) / 2.0).floor().max(0.0); diff --git a/blocksuite/crates/playground/src/lib.rs b/blocksuite/crates/playground/src/lib.rs index f1487c6418..2fd24a7ed8 100644 --- a/blocksuite/crates/playground/src/lib.rs +++ b/blocksuite/crates/playground/src/lib.rs @@ -10321,14 +10321,14 @@ pub(crate) mod tests { .find(|b| b.block_id == "b-callout-p") .expect("callout child"); assert!( - (child.rect().y - (callout.rect().y + 10.0)).abs() <= 2.0, - "callout child must sit on same row at top+10 (callout.y={}, child.y={})", + (child.rect().y - (callout.rect().y + 5.0)).abs() <= 2.0, + "callout child must sit on same row at top+5 (callout.y={}, child.y={})", callout.rect().y, child.rect().y ); assert!( - (child.rect().x - (callout.rect().x + 46.0)).abs() <= 2.0, - "callout child must start at x+46 (callout.x={}, child.x={})", + (child.rect().x - (callout.rect().x + 44.0)).abs() <= 2.0, + "callout child must start at x+44 (callout.x={}, child.x={})", callout.rect().x, child.rect().x ); diff --git a/blocksuite/crates/playground/src/overlays/tests_popovers_toolbars.rs b/blocksuite/crates/playground/src/overlays/tests_popovers_toolbars.rs index 2d921484f8..d17c4fa3d4 100644 --- a/blocksuite/crates/playground/src/overlays/tests_popovers_toolbars.rs +++ b/blocksuite/crates/playground/src/overlays/tests_popovers_toolbars.rs @@ -554,7 +554,7 @@ mod tests { Some("https://affine.pro") ); - // 4. Callout: min height >= 44px, icon picker + 9-color background, empty click focuses child. + // 4. Callout: 0.27.5 compact 34px min height (pad 5px/10px), icon picker + 9-color background, empty click focuses child. let callout_h = session.view(|v, _| { v.flow_layout() .unwrap() @@ -563,7 +563,10 @@ mod tests { .body .height }); - assert!(callout_h >= 44.0, "callout min height must be >= 44px"); + assert!( + (34.0..44.0).contains(&callout_h), + "single-line callout must match 0.27.5 34px metric, got {callout_h}" + ); session.overlay(OverlayEvent::SelectBlock("b-callout".into())); let co_frame = session.settle(); assert!(co_frame.elements.contains_key("overlay.callout_toolbar")); @@ -786,9 +789,9 @@ mod tests { } #[test] - fn r2_concurrency_marks_readonly_conversion_and_code_scroll_guards() { + fn concurrent_link_marks_readonly_capsule_and_code_picker_guards() { let session = open(1280, 800, PlaygroundTheme::Light); - let mut state = DocState::new("r2-guards", 95).unwrap(); + let mut state = DocState::new("popover-guards", 95).unwrap(); state .workspace .create_page(HOME_PAGE_ID, "Main", 1) @@ -1238,7 +1241,7 @@ mod tests { } #[test] - fn r2_lightbox_1600x1000_zoom_200_400_reset_and_phone_360_toolbars() { + fn image_lightbox_aspect_zoom_wheel_drag_pan_and_pinch() { // Build a 1600x1000 PNG with distinct concentric rings so 200% and 400% render distinct pixels. let mut rgba = image::RgbaImage::new(1600, 1000); for y in 0..1000u32 { @@ -1381,9 +1384,55 @@ mod tests { }) .unwrap(); - // Zoom to 200% (4 steps of +0.25) -> image is 2112x1320 clipped inside 1176x692 viewport! + // Real trackpad light swipe (12 × 4 px = 48 px) scales proportionally (~115%), never jumping to 400%! + for _ in 0..12 { + session + .headless + .dispatch_input(ui::PlatformInput::Scroll(ui::ScrollEvent { + position: ui::point(ui::px(600.0), ui::px(400.0)), + delta: ui::ScrollDelta::Pixels(ui::point(ui::px(0.0), ui::px(4.0))), + modifiers: ui::Modifiers::default(), + touch_phase: ui::TouchPhase::Moved, + source: ui::ScrollSource::Pointer, + })); + let _ = session.frame(); + } + let zoom_after_swipe = session.view(|v, _| v.overlays().image_lightbox().unwrap().zoom); + assert!( + zoom_after_swipe > 1.10 && zoom_after_swipe < 1.25, + "48px trackpad swipe must scale proportionally (~1.15x), got {zoom_after_swipe}" + ); + + // Real PinchEvent magnifies proportionally. + session + .headless + .dispatch_input(ui::PlatformInput::Pinch(ui::PinchEvent { + position: ui::point(ui::px(600.0), ui::px(400.0)), + delta: 0.20, + modifiers: ui::Modifiers::default(), + phase: ui::TouchPhase::Moved, + })); + let _ = session.frame(); + let zoom_after_pinch = session.view(|v, _| v.overlays().image_lightbox().unwrap().zoom); + assert!( + zoom_after_pinch > zoom_after_swipe + 0.15, + "pinch delta +0.20 must zoom in, got {zoom_after_pinch}" + ); + session.overlay(OverlayEvent::ImageLightboxZoom(0.0)); + let _ = session.frame(); + + // Zoom to 200% via 4 real discrete mouse-wheel notches (`ScrollDelta::Lines(1.0)` = +25% each). for _ in 0..4 { - session.overlay(OverlayEvent::ImageLightboxZoom(0.25)); + session + .headless + .dispatch_input(ui::PlatformInput::Scroll(ui::ScrollEvent { + position: ui::point(ui::px(600.0), ui::px(400.0)), + delta: ui::ScrollDelta::Lines(ui::point(0.0, 1.0)), + modifiers: ui::Modifiers::default(), + touch_phase: ui::TouchPhase::Moved, + source: ui::ScrollSource::Pointer, + })); + let _ = session.frame(); } let lb_200 = session.frame(); let b_200 = element(&lb_200, "overlay.image_lightbox.image").bounds; @@ -1409,7 +1458,58 @@ mod tests { }) .unwrap(); - // Zoom to 400% (8 more steps of +0.25) -> image is ~4224x2640 (strictly 2x 200%!) and pixels differ! + // Real pointer drag `(-180, -90)` at 200% pans the clipped image without closing Lightbox! + let start_x = vp_200.x + vp_200.width * 0.5; + let start_y = vp_200.y + vp_200.height * 0.5; + session + .headless + .dispatch_input(ui::PlatformInput::MouseDown(ui::MouseDownEvent { + button: ui::MouseButton::Left, + position: ui::point(ui::px(start_x), ui::px(start_y)), + modifiers: ui::Modifiers::default(), + click_count: 1, + first_mouse: false, + })); + let _ = session.frame(); + session + .headless + .dispatch_input(ui::PlatformInput::MouseMove(ui::MouseMoveEvent { + position: ui::point(ui::px(start_x - 90.0), ui::px(start_y - 45.0)), + pressed_button: Some(ui::MouseButton::Left), + modifiers: ui::Modifiers::default(), + })); + let _ = session.frame(); + session + .headless + .dispatch_input(ui::PlatformInput::MouseMove(ui::MouseMoveEvent { + position: ui::point(ui::px(start_x - 180.0), ui::px(start_y - 90.0)), + pressed_button: Some(ui::MouseButton::Left), + modifiers: ui::Modifiers::default(), + })); + let _ = session.frame(); + session + .headless + .dispatch_input(ui::PlatformInput::MouseUp(ui::MouseUpEvent { + button: ui::MouseButton::Left, + position: ui::point(ui::px(start_x - 180.0), ui::px(start_y - 90.0)), + modifiers: ui::Modifiers::default(), + click_count: 1, + })); + let lb_panned = session.frame(); + assert!( + lb_panned.elements.contains_key("overlay.image_lightbox"), + "dragging inside Lightbox must not dismiss it" + ); + let b_panned = element(&lb_panned, "overlay.image_lightbox.image").bounds; + assert!( + ((b_panned.x - b_200.x) - (-180.0)).abs() <= 1.5 + && ((b_panned.y - b_200.y) - (-90.0)).abs() <= 1.5, + "expected image origin to pan by (-180, -90), before={:?}, after={:?}", + (b_200.x, b_200.y), + (b_panned.x, b_panned.y) + ); + + // Zoom to 400% -> image is ~4224x2640 (strictly 2x 200%!) and pixels differ! for _ in 0..8 { session.overlay(OverlayEvent::ImageLightboxZoom(0.25)); } @@ -1457,8 +1557,10 @@ mod tests { "Unchanged", "keys while Lightbox is open must be captured without mutating page text" ); + } - // Phone 360x800: Callout, Bookmark, and Image bottom toolbars fit 100% inside 360pt with Delete reachable. + #[test] + fn phone_360_touch_context_bars_44pt_hit_targets_scroll_and_back() { let phone = open_with_options( 360, 800, @@ -1472,9 +1574,6 @@ mod tests { .workspace .create_page(HOME_PAGE_ID, "Phone", 1) .unwrap(); - pstate - .blobs - .insert("blob-p".into(), img_100.as_raw().clone().into()); let mut tiny_png = Vec::new(); image::RgbaImage::from_pixel(64, 48, image::Rgba([80, 140, 230, 255])) .write_to( @@ -1540,6 +1639,18 @@ mod tests { 5, ) .unwrap(); + page.add_block( + "b-code", + BlockSpec::Code { + language: Some("rust".into()), + text: "l1\nl2\nl3\nl4\nl5\nl6\nl7\nl8\nl9\nl10".into(), + caption: String::new(), + }, + Some("n"), + None, + 6, + ) + .unwrap(); } phone.app.update(|cx| { phone @@ -1547,25 +1658,41 @@ mod tests { .update(cx, |v, _, cx| v.set_document(pstate, cx)) .unwrap(); }); - let _ = phone.settle(); + let initial_phone = phone.settle(); + assert!( + ui::audit_frame_snapshot(&initial_phone).is_empty(), + "phone 360 initial code controls audit must pass" + ); + assert!( + initial_phone + .elements + .contains_key("page.block.b-code.line_number") + && initial_phone + .elements + .contains_key("page.block.b-code.collapse"), + "360pt phone code header must expose >=44pt line_number and collapse controls" + ); - for (blk, tb_id, del_id, png_name) in [ + for (blk, tb_id, del_id, scrolled_id, png_name) in [ ( "b-co", "overlay.callout_toolbar", "overlay.callout_toolbar.delete", + "overlay.callout_toolbar.bg.grey", "10-mobile-360-callout-toolbar.png", ), ( "b-bm", "overlay.bookmark_toolbar", "overlay.bookmark_toolbar.delete", + "overlay.bookmark_toolbar.duplicate", "11-mobile-360-bookmark-toolbar.png", ), ( "b-im", "overlay.image_toolbar", "overlay.image_toolbar.delete", + "overlay.image_toolbar.card_view", "12-mobile-360-image-toolbar.png", ), ] { @@ -1581,7 +1708,376 @@ mod tests { del.x >= tb.x && del.x + del.width <= tb.x + tb.width && del.height >= 44.0, "{del_id} clipped or <44pt on 360px phone viewport: del={del:?}, tb={tb:?}" ); + let prefix = format!("{tb_id}."); + for (id, el) in &pf.elements { + if id.starts_with(&prefix) { + assert!( + el.bounds.width >= 44.0 && el.bounds.height >= 44.0, + "touch control {id} below 44x44pt: {:?}", + el.bounds + ); + } + } maybe_save_evidence(&phone, png_name); + + // Real horizontal scroll on the touch bar reveals trailing 44x44pt controls. + phone + .headless + .dispatch_input(ui::PlatformInput::Scroll(ui::ScrollEvent { + position: ui::point( + ui::px(tb.x + tb.width * 0.4), + ui::px(tb.y + tb.height * 0.5), + ), + delta: ui::ScrollDelta::Pixels(ui::point(ui::px(-320.0), ui::px(0.0))), + modifiers: ui::Modifiers::default(), + touch_phase: ui::TouchPhase::Moved, + source: ui::ScrollSource::Pointer, + })); + let scrolled_frame = phone.frame(); + let trailing = element(&scrolled_frame, scrolled_id).bounds; + assert!( + trailing.width >= 44.0 && trailing.height >= 44.0, + "scrolled trailing control {scrolled_id} must be >=44x44pt: {trailing:?}" + ); } + + // Phone CodeLangPicker uses 5-row window (>=44pt rows), scrolls Go into view on Down from + // Python (row 4 -> row 5), commits Go on Enter, and closes on Android Back! + phone.overlay(OverlayEvent::SetCodeLanguage { + block_id: "b-code".into(), + language: "python".into(), + }); + let _ = phone.settle(); + phone.overlay(OverlayEvent::OpenCodeLangPicker("b-code".into())); + let picker_frame = phone.settle(); + let picker_bounds = element(&picker_frame, "overlay.code_lang_picker").bounds; + let py_row = element(&picker_frame, "overlay.code_lang_picker.item.python").bounds; + assert!( + py_row.height >= 44.0 && picker_bounds.y + picker_bounds.height <= 740.0, + "touch CodeLangPicker must use >=44pt rows and clear bottom bar: row={py_row:?}, picker={picker_bounds:?}" + ); + assert!( + !picker_frame + .elements + .contains_key("overlay.code_lang_picker.item.go"), + "Go (idx 5) starts below the 5-row touch window (0..5)" + ); + phone.key("down"); + let picker_down = phone.frame(); + assert!( + picker_down + .elements + .contains_key("overlay.code_lang_picker.item.go"), + "pressing Down from Python on 5-row touch CodeLangPicker must scroll Go into view" + ); + phone.key("enter"); + let committed_lang = phone.view(|v, _| { + v.page_snapshot() + .and_then(|s| s.block("b-code")) + .and_then(|n| match &n.content { + BlockContent::Code { language, .. } => Some(language.clone()), + _ => None, + }) + }); + assert_eq!(committed_lang.as_deref(), Some("go")); + phone.overlay(OverlayEvent::OpenCodeLangPicker("b-code".into())); + let _ = phone.settle(); + let back_consumed = phone + .app + .update(|cx| phone.window.update(cx, |v, w, cx| v.handle_back(w, cx))) + .unwrap(); + assert!(back_consumed, "handle_back must close open CodeLangPicker"); + assert!( + phone.view(|v, _| v.overlays().code_lang_picker().is_none()), + "CodeLangPicker must be closed after handle_back" + ); + + // Phone ImageLightbox: real single-finger TouchEvent pans + ScrollSource::Touch at 244% + // never zoom or scroll the underlying page; two-finger TouchEvent pinch zooms cleanly. + phone.overlay(OverlayEvent::OpenImageLightbox("b-im".into())); + let _ = phone.settle(); + phone.overlay(OverlayEvent::ImageLightboxZoom(1.44)); + let lb_before = phone.frame(); + assert_eq!( + element(&lb_before, "overlay.image_lightbox.zoom_reset") + .text + .as_deref(), + Some("244%") + ); + let page_scroll_0 = phone.view(|v, _| v.scroll_y); + for (idx, dy) in [-60.0_f32, -60.0, -60.0, 60.0, 60.0, 60.0] + .into_iter() + .enumerate() + { + phone + .headless + .dispatch_input(ui::PlatformInput::Scroll(ui::ScrollEvent { + position: ui::point(ui::px(180.0), ui::px(400.0)), + delta: ui::ScrollDelta::Pixels(ui::point(ui::px(0.0), ui::px(dy))), + modifiers: ui::Modifiers::default(), + touch_phase: ui::TouchPhase::Moved, + source: ui::ScrollSource::Touch, + })); + let tid = ui::TouchId(30 + idx as u64); + for (phase, y) in [ + (ui::TouchPhase::Started, 400.0_f32), + (ui::TouchPhase::Moved, 400.0 + dy * 0.5), + (ui::TouchPhase::Moved, 400.0 + dy), + (ui::TouchPhase::Ended, 400.0 + dy), + ] { + phone + .headless + .dispatch_input(ui::PlatformInput::Touch(ui::TouchEvent { + id: tid, + phase, + position: ui::point(ui::px(180.0), ui::px(y)), + predicted_position: None, + force: None, + })); + let _ = phone.frame(); + } + } + let lb_after_pans = phone.frame(); + assert_eq!( + element(&lb_after_pans, "overlay.image_lightbox.zoom_reset") + .text + .as_deref(), + Some("244%"), + "touch finger pans inside Lightbox must never change zoom" + ); + assert_eq!( + phone.view(|v, _| v.scroll_y), + page_scroll_0, + "touch pans inside Lightbox must never scroll underlying page" + ); + for (phase, dy) in [ + (ui::TouchPhase::Started, 40.0_f32), + (ui::TouchPhase::Moved, 55.0), + (ui::TouchPhase::Moved, 75.0), + (ui::TouchPhase::Ended, 75.0), + ] { + for (id, y) in [(ui::TouchId(90), 400.0 - dy), (ui::TouchId(91), 400.0 + dy)] { + phone + .headless + .dispatch_input(ui::PlatformInput::Touch(ui::TouchEvent { + id, + phase, + position: ui::point(ui::px(180.0), ui::px(y)), + predicted_position: None, + force: None, + })); + } + let _ = phone.frame(); + } + let lb_pinched = phone.frame(); + assert_ne!( + element(&lb_pinched, "overlay.image_lightbox.zoom_reset") + .text + .as_deref(), + Some("244%"), + "two-finger touch pinch must adjust Lightbox zoom" + ); + phone.overlay(OverlayEvent::CloseImageLightbox); + let _ = phone.settle(); + + // Desktop CodeLangPicker wheel scroll must advance scroll_offset and persist across frames + // instead of snapping back to the selected language on every repaint. + let desk = open(1280, 800, PlaygroundTheme::Light); + let mut dstate = DocState::new("desktop-code-picker-callout", 99).unwrap(); + dstate + .workspace + .create_page(HOME_PAGE_ID, "CodeCallout", 1) + .unwrap(); + { + let page = dstate.workspace.page_mut(HOME_PAGE_ID).unwrap(); + page.add_block( + "root", + BlockSpec::Page { + title: "CodeCallout".into(), + }, + None, + None, + 1, + ) + .unwrap(); + page.add_block("n", BlockSpec::Note { xywh: None }, Some("root"), None, 2) + .unwrap(); + page.add_block( + "b-code", + BlockSpec::Code { + language: Some("rust".into()), + text: "fn main() {}".into(), + caption: String::new(), + }, + Some("n"), + None, + 3, + ) + .unwrap(); + page.add_block( + "b-co", + BlockSpec::Callout { + icon: "\u{1F4A1}".into(), + background_color: None, + }, + Some("n"), + None, + 4, + ) + .unwrap(); + page.add_block( + "b-co-child", + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: "Inside callout".into(), + }, + Some("b-co"), + None, + 5, + ) + .unwrap(); + } + desk.app.update(|cx| { + desk.window + .update(cx, |v, _, cx| v.set_document(dstate, cx)) + .unwrap(); + }); + let _ = desk.settle(); + desk.overlay(OverlayEvent::OpenCodeLangPicker("b-code".into())); + let dp = desk.settle(); + let dp_bounds = element(&dp, "overlay.code_lang_picker").bounds; + let initial_offset = desk + .view(|v, _| v.overlays().code_lang_picker().map(|p| p.scroll_offset)) + .unwrap_or(0); + desk.headless + .dispatch_input(ui::PlatformInput::Scroll(ui::ScrollEvent { + position: ui::point( + ui::px(dp_bounds.x + dp_bounds.width * 0.5), + ui::px(dp_bounds.y + dp_bounds.height * 0.5), + ), + delta: ui::ScrollDelta::Pixels(ui::point(ui::px(0.0), ui::px(-140.0))), + modifiers: ui::Modifiers::default(), + touch_phase: ui::TouchPhase::Moved, + source: ui::ScrollSource::Pointer, + })); + let _ = desk.frame(); + let _ = desk.frame(); + let scrolled_offset = desk + .view(|v, _| v.overlays().code_lang_picker().map(|p| p.scroll_offset)) + .unwrap_or(0); + assert!( + scrolled_offset != initial_offset, + "CodeLangPicker wheel scroll must change scroll_offset and persist across repaints (before={initial_offset}, after={scrolled_offset})" + ); + desk.key("escape"); + + // Hovering a Callout child block must place `+⋮⋮` drag handle outside the Callout card's left edge. + let co_frame = desk.settle(); + let co_bounds = element(&co_frame, "page.block.b-co").bounds; + let child_bounds = element(&co_frame, "page.block.b-co-child").bounds; + desk.headless + .dispatch_input(ui::PlatformInput::MouseMove(ui::MouseMoveEvent { + position: ui::point( + ui::px(child_bounds.x + 20.0), + ui::px(child_bounds.y + child_bounds.height * 0.5), + ), + pressed_button: None, + modifiers: ui::Modifiers::default(), + })); + let hover_frame = desk.frame(); + let handle_el = element(&hover_frame, "overlay.drag_handle"); + assert!( + handle_el.bounds.x + handle_el.bounds.width <= co_bounds.x + 2.0, + "Callout child drag handle must sit in outer gutter, not overlapping Callout text: handle={:?}, callout={co_bounds:?}", + handle_el.bounds + ); + + // Web mobile scenario (`FormFactor::Desktop` + `PointerKind::Touch` at `390x844` without `?mobile=1`): + // Slash menu flattens H4-H6 into Basic (no `Other Headings`), and Bookmark toolbar stays <= 390px! + let web_touch = open_with_options( + 390, + 844, + PlaygroundOptions { + theme: PlaygroundTheme::Light, + form_factor: FormFactor::Desktop, + pointer_kind: crate::PointerKind::Touch, + ..PlaygroundOptions::default() + }, + ); + let mut wt_state = DocState::new("web-touch-390", 101).unwrap(); + wt_state + .workspace + .create_page(HOME_PAGE_ID, "Touch390", 1) + .unwrap(); + { + let page = wt_state.workspace.page_mut(HOME_PAGE_ID).unwrap(); + page.add_block( + "root", + BlockSpec::Page { + title: "Touch390".into(), + }, + None, + None, + 1, + ) + .unwrap(); + page.add_block("n", BlockSpec::Note { xywh: None }, Some("root"), None, 2) + .unwrap(); + page.add_block( + "p1", + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: String::new(), + }, + Some("n"), + None, + 3, + ) + .unwrap(); + page.add_block( + "b-bm", + BlockSpec::Bookmark { + url: "https://affine.pro".into(), + title: Some("AFFiNE".into()), + description: None, + }, + Some("n"), + None, + 4, + ) + .unwrap(); + } + web_touch.app.update(|cx| { + web_touch + .window + .update(cx, |v, _, cx| v.set_document(wt_state, cx)) + .unwrap(); + }); + let _ = web_touch.settle(); + web_touch.overlay(OverlayEvent::OpenSlashMenu { + block_id: "p1".into(), + utf16_offset: 0, + anchor: None, + }); + let slash_frame = web_touch.settle(); + assert!( + !slash_frame + .elements + .contains_key("overlay.slash_menu.item.other_headings"), + "PointerKind::Touch at 390x844 must flatten H4-H6 without Desktop submenu" + ); + assert!( + slash_frame + .elements + .contains_key("overlay.slash_menu.item.h4"), + "PointerKind::Touch at 390x844 must expose H4 directly in Slash menu" + ); + web_touch.overlay(OverlayEvent::SelectBlock("b-bm".into())); + let bm_frame = web_touch.settle(); + let bm_tb = element(&bm_frame, "overlay.bookmark_toolbar").bounds; + assert!( + bm_tb.x >= 0.0 && bm_tb.x + bm_tb.width <= 390.0, + "390x844 touch Bookmark toolbar must stay within viewport: {bm_tb:?}" + ); } } diff --git a/blocksuite/crates/playground/src/overlays/view.rs b/blocksuite/crates/playground/src/overlays/view.rs index d9aa57b59a..e1d73fd7fc 100644 --- a/blocksuite/crates/playground/src/overlays/view.rs +++ b/blocksuite/crates/playground/src/overlays/view.rs @@ -65,6 +65,7 @@ impl PlaygroundView { scroll_y: self.scroll_y, direction, form_factor: self.form_factor, + is_touch: self.is_touch_host(), focused_code_block, selected_image_block, selected_bookmark_block, diff --git a/blocksuite/crates/playground/src/overlays/view_mobile/mod.rs b/blocksuite/crates/playground/src/overlays/view_mobile/mod.rs index a84097a5ec..b5dc974dbd 100644 --- a/blocksuite/crates/playground/src/overlays/view_mobile/mod.rs +++ b/blocksuite/crates/playground/src/overlays/view_mobile/mod.rs @@ -665,12 +665,6 @@ impl PlaygroundView { return true; } let now_ms = self.now_ms(cx); - if self.overlays.bookmark_prompt().is_some() { - self.overlays.close_bookmark_prompt_at(now_ms); - window.notify_text_input_changed(&self.editor_focus); - cx.notify(); - return true; - } if self.overlays.equation_editor().is_some() { self.overlays.close_equation_editor_at(now_ms); self.equation_snapshot = None; @@ -678,29 +672,15 @@ impl PlaygroundView { cx.notify(); return true; } - if self.overlays.link_field().is_some() { - self.overlays.close_link_field(); - window.notify_text_input_changed(&self.editor_focus); + if let Some(sync_input) = self.overlays.dismiss_transient_for_back(now_ms) { + if sync_input { + window.notify_text_input_changed(&self.editor_focus); + } cx.notify(); return true; } - if self.overlays.close_toolbar_submenu() || self.overlays.close_link_popup(now_ms) { - cx.notify(); - return true; - } - if self.overlays.keyboard_toolbar_active_panel().is_some() { - self.overlays.close_keyboard_toolbar_panel(); - cx.notify(); - return true; - } - let mut closed = self.overlays.close_slash(now_ms) - | self.overlays.close_linked_doc(now_ms) - | self.overlays.close_context_menu(now_ms); if self.touch_selection_menu_open { self.touch_selection_menu_open = false; - closed = true; - } - if closed { cx.notify(); return true; } diff --git a/blocksuite/crates/playground/src/touch_interaction/mod.rs b/blocksuite/crates/playground/src/touch_interaction/mod.rs index c930228531..a7bf182592 100644 --- a/blocksuite/crates/playground/src/touch_interaction/mod.rs +++ b/blocksuite/crates/playground/src/touch_interaction/mod.rs @@ -1,6 +1,7 @@ //! Touch gesture handling: inertial flings, long-press drag selection & action capsule, //! expanded 44pt control hit targets, touch link/reference tap, and read-only Edgeless tap/selection. +mod modal; mod selection; use blocksuite_playground_doc::schema::ListType; @@ -43,23 +44,6 @@ impl PlaygroundView { self.edgeless_pan_fling = None; } - pub(crate) fn has_live_modal_touch_overlay( - &mut self, - window: &Window, - cx: &mut Context, - ) -> bool { - if self.database_record_sheet.is_some() { - if self.record_sheet_geometry(window).is_some() { - return true; - } - self.database_record_sheet = None; - cx.notify(); - } - self.overlays.bookmark_prompt().is_some() - || self.overlays.equation_editor().is_some() - || self.overlays.link_field().is_some() - } - pub(crate) fn handle_touch_gestures(&mut self, window: &mut Window, cx: &mut Context) { // Invoked unconditionally at the start of `PlaygroundView::render` before any // `paint_image` call, draining retired GPU atlas tiles across frame boundaries. @@ -81,106 +65,12 @@ impl PlaygroundView { None }; let modal_open = sheet_geom.is_some() + || self.overlays.image_lightbox().is_some() || self.overlays.bookmark_prompt().is_some() || self.overlays.equation_editor().is_some() || self.overlays.link_field().is_some(); if self.active_touch_owner == TouchStrokeOwner::ModalOverlay || modal_open { - self.cancel_flings(); - for gesture in window.take_touch_gestures() { - match gesture { - TouchGesture::PanStart { origin, .. } => { - self.active_touch_owner = TouchStrokeOwner::ModalOverlay; - if let Some((sheet_left, sheet_top, sheet_w, _, _)) = sheet_geom { - let (x, y) = (f32::from(origin.x), f32::from(origin.y)); - if let Some(s) = self.database_record_sheet.as_mut() { - s.scroll_fling = None; - let in_sheet_x = x >= sheet_left && x <= sheet_left + sheet_w; - if in_sheet_x && y >= sheet_top && y <= sheet_top + 68.0 { - s.grabber_drag_start_y.get_or_insert(y); - s.touch_body_drag = false; - } else if in_sheet_x && y > sheet_top + 68.0 { - s.grabber_drag_start_y = None; - s.touch_body_drag = true; - } else { - s.grabber_drag_start_y = None; - s.touch_body_drag = false; - } - } - } - } - TouchGesture::Tap { position, count: 1 } => { - if let Some((sheet_left, sheet_top, sheet_w, _, _)) = sheet_geom { - let (x, y) = (f32::from(position.x), f32::from(position.y)); - let outside = - y < sheet_top || x < sheet_left || x > sheet_left + sheet_w; - if outside { - self.close_database_record_sheet(cx); - } - } - } - TouchGesture::PanUpdate { position, .. } => { - let y = f32::from(position.y); - let start_y = self - .database_record_sheet - .as_ref() - .and_then(|s| s.grabber_drag_start_y); - if let Some(y0) = start_y - && y - y0 >= 56.0 - { - self.close_database_record_sheet(cx); - } - } - TouchGesture::PanEnd { - position, - velocity, - cancelled, - .. - } => { - self.touch_scroll_axis_lock = None; - let y = f32::from(position.y); - let vy = f32::from(velocity.y); - let header_start = self - .database_record_sheet - .as_mut() - .and_then(|s| s.grabber_drag_start_y.take()); - let was_body = self - .database_record_sheet - .as_mut() - .is_some_and(|s| std::mem::take(&mut s.touch_body_drag)); - if let Some(y0) = header_start { - if !cancelled && y - y0 >= 56.0 { - self.close_database_record_sheet(cx); - } - } else if was_body - && !cancelled - && vy.abs() >= FLING_MIN_VELOCITY - && let Some((_, _, _, _, max_scroll)) = sheet_geom - && max_scroll > 0.0 - && let Some(s) = self.database_record_sheet.as_mut() - { - s.scroll_fling = Some(InertialDecay::new( - f64::from(s.scroll_y), - -f64::from(vy), - FLING_FRICTION, - now_ms, - )); - window.request_animation_frame(); - } - } - _ => {} - } - } - if window.active_touch_count() == 0 { - if self.active_touch_owner == TouchStrokeOwner::ImageResize - && self.image_resize_drag.is_some() - { - self.cancel_image_resize_drag(); - cx.notify(); - } - self.touch_long_press_anchor = None; - self.touch_scroll_axis_lock = None; - self.active_touch_owner = TouchStrokeOwner::None; - } + self.handle_modal_touch_gestures(sheet_geom, now_ms, window, cx); return; } for gesture in window.take_touch_gestures() { diff --git a/blocksuite/crates/playground/src/touch_interaction/modal.rs b/blocksuite/crates/playground/src/touch_interaction/modal.rs new file mode 100644 index 0000000000..68482a6b52 --- /dev/null +++ b/blocksuite/crates/playground/src/touch_interaction/modal.rs @@ -0,0 +1,184 @@ +//! Modal touch-gesture routing for `database_record_sheet`, `image_lightbox`, and text-input +//! modal overlays so underlying `Page` / `Edgeless` surfaces never scroll behind an open modal. + +use ui::{Context, InertialDecay, TouchGesture, Window}; + +use crate::{PlaygroundView, overlays::OverlayEvent}; + +use super::{FLING_FRICTION, FLING_MIN_VELOCITY, TouchStrokeOwner}; + +impl PlaygroundView { + pub(crate) fn has_live_modal_touch_overlay( + &mut self, + window: &Window, + cx: &mut Context, + ) -> bool { + if self.database_record_sheet.is_some() { + if self.record_sheet_geometry(window).is_some() { + return true; + } + self.database_record_sheet = None; + cx.notify(); + } + self.overlays.image_lightbox().is_some() + || self.overlays.bookmark_prompt().is_some() + || self.overlays.equation_editor().is_some() + || self.overlays.link_field().is_some() + } + + pub(super) fn handle_modal_touch_gestures( + &mut self, + sheet_geom: Option<(f32, f32, f32, f32, f32)>, + now_ms: f64, + window: &mut Window, + cx: &mut Context, + ) { + self.cancel_flings(); + for gesture in window.take_touch_gestures() { + if self.overlays.image_lightbox().is_some() { + self.handle_lightbox_touch_gesture(gesture, window, cx); + continue; + } + match gesture { + TouchGesture::PanStart { origin, .. } => { + self.active_touch_owner = TouchStrokeOwner::ModalOverlay; + if let Some((sheet_left, sheet_top, sheet_w, _, _)) = sheet_geom { + let (x, y) = (f32::from(origin.x), f32::from(origin.y)); + if let Some(s) = self.database_record_sheet.as_mut() { + s.scroll_fling = None; + let in_sheet_x = x >= sheet_left && x <= sheet_left + sheet_w; + if in_sheet_x && y >= sheet_top && y <= sheet_top + 68.0 { + s.grabber_drag_start_y.get_or_insert(y); + s.touch_body_drag = false; + } else if in_sheet_x && y > sheet_top + 68.0 { + s.grabber_drag_start_y = None; + s.touch_body_drag = true; + } else { + s.grabber_drag_start_y = None; + s.touch_body_drag = false; + } + } + } + } + TouchGesture::Tap { position, count: 1 } => { + if let Some((sheet_left, sheet_top, sheet_w, _, _)) = sheet_geom { + let (x, y) = (f32::from(position.x), f32::from(position.y)); + let outside = y < sheet_top || x < sheet_left || x > sheet_left + sheet_w; + if outside { + self.close_database_record_sheet(cx); + } + } + } + TouchGesture::PanUpdate { position, .. } => { + let y = f32::from(position.y); + let start_y = self + .database_record_sheet + .as_ref() + .and_then(|s| s.grabber_drag_start_y); + if let Some(y0) = start_y + && y - y0 >= 56.0 + { + self.close_database_record_sheet(cx); + } + } + TouchGesture::PanEnd { + position, + velocity, + cancelled, + .. + } => { + self.touch_scroll_axis_lock = None; + let y = f32::from(position.y); + let vy = f32::from(velocity.y); + let header_start = self + .database_record_sheet + .as_mut() + .and_then(|s| s.grabber_drag_start_y.take()); + let was_body = self + .database_record_sheet + .as_mut() + .is_some_and(|s| std::mem::take(&mut s.touch_body_drag)); + if let Some(y0) = header_start { + if !cancelled && y - y0 >= 56.0 { + self.close_database_record_sheet(cx); + } + } else if was_body + && !cancelled + && vy.abs() >= FLING_MIN_VELOCITY + && let Some((_, _, _, _, max_scroll)) = sheet_geom + && max_scroll > 0.0 + && let Some(s) = self.database_record_sheet.as_mut() + { + s.scroll_fling = Some(InertialDecay::new( + f64::from(s.scroll_y), + -f64::from(vy), + FLING_FRICTION, + now_ms, + )); + window.request_animation_frame(); + } + } + _ => {} + } + } + if window.active_touch_count() == 0 { + if self.active_touch_owner == TouchStrokeOwner::ImageResize + && self.image_resize_drag.is_some() + { + self.cancel_image_resize_drag(); + cx.notify(); + } + self.touch_long_press_anchor = None; + self.touch_scroll_axis_lock = None; + self.active_touch_owner = TouchStrokeOwner::None; + } + } + + fn handle_lightbox_touch_gesture( + &mut self, + gesture: TouchGesture, + window: &mut Window, + cx: &mut Context, + ) { + match gesture { + TouchGesture::PanStart { origin, .. } => { + self.active_touch_owner = TouchStrokeOwner::ModalOverlay; + self.dispatch_overlay( + OverlayEvent::ImageLightboxDragStart { + x: f32::from(origin.x), + y: f32::from(origin.y), + }, + window, + cx, + ); + } + TouchGesture::PanUpdate { position, .. } => { + self.dispatch_overlay( + OverlayEvent::ImageLightboxDragMove { + x: f32::from(position.x), + y: f32::from(position.y), + }, + window, + cx, + ); + } + TouchGesture::PanEnd { .. } => { + self.touch_scroll_axis_lock = None; + self.dispatch_overlay(OverlayEvent::ImageLightboxDragEnd, window, cx); + } + TouchGesture::PinchStart { .. } => { + self.active_touch_owner = TouchStrokeOwner::ModalOverlay; + self.dispatch_overlay(OverlayEvent::ImageLightboxDragEnd, window, cx); + } + TouchGesture::PinchUpdate { scale_delta, .. } => { + if let Some(zoom) = self.overlays.image_lightbox().map(|lb| lb.zoom) { + let step = ((scale_delta.clamp(0.2, 5.0) - 1.0) * zoom).clamp(-0.5, 0.5); + if step.abs() > 0.001 { + self.dispatch_overlay(OverlayEvent::ImageLightboxZoom(step), window, cx); + } + } + } + _ => {} + } + } +} diff --git a/blocksuite/crates/playground/src/view_room.rs b/blocksuite/crates/playground/src/view_room.rs index 569e8cc1da..d741b15d0f 100644 --- a/blocksuite/crates/playground/src/view_room.rs +++ b/blocksuite/crates/playground/src/view_room.rs @@ -427,12 +427,41 @@ impl PlaygroundView { } } +#[cfg(target_family = "wasm")] +pub(crate) fn web_is_touch_modality(window: &web_sys::Window, viewport_width: f32) -> bool { + use wasm_bindgen::JsCast as _; + let coarse = js_sys::Reflect::get(window, &"matchMedia".into()) + .ok() + .and_then(|v| v.dyn_into::().ok()) + .and_then(|f| f.call1(window, &"(pointer: coarse)".into()).ok()) + .and_then(|mql| js_sys::Reflect::get(&mql, &"matches".into()).ok()) + .and_then(|b| b.as_bool()) + .unwrap_or(false); + if coarse { + return true; + } + let max_touch_points = js_sys::Reflect::get(window, &"navigator".into()) + .ok() + .and_then(|nav| js_sys::Reflect::get(&nav, &"maxTouchPoints".into()).ok()) + .and_then(|n| n.as_f64()) + .unwrap_or(0.0); + max_touch_points > 0.0 && viewport_width < 768.0 +} + #[cfg(target_family = "wasm")] fn web_options() -> PlaygroundOptions { let mut options = PlaygroundOptions::default(); let Some(window) = web_sys::window() else { return options; }; + let inner_w = window + .inner_width() + .ok() + .and_then(|v| v.as_f64()) + .unwrap_or(1280.0) as f32; + if web_is_touch_modality(&window, inner_w) { + options.pointer_kind = crate::PointerKind::Touch; + } let location = window.location(); let Some(params) = location .search() @@ -495,8 +524,6 @@ pub fn register_web_font(bytes: &[u8]) -> Result<(), wasm_bindgen::JsError> { .map_err(|err| wasm_bindgen::JsError::new(&format!("{err:#}"))) } -/// Opens the fullscreen playground window on the page canvas. -/// /// Generate a random 53-bit CRDT client id for a new live room session. #[cfg(not(target_family = "wasm"))] pub(crate) fn fresh_client_id() -> u64 { @@ -511,6 +538,8 @@ pub(crate) fn fresh_client_id() -> u64 { ) } +/// Opens the fullscreen playground window on the page canvas. +/// /// The standalone playground page calls this after it registered its fonts with /// [`register_web_font`]. It throws before it starts the application when the /// fonts miss a required family. The Web thin host (`/host/`) loads the same diff --git a/blocksuite/crates/playground/web/preview-workers.js b/blocksuite/crates/playground/web/preview-workers.js index 84ad1c0d43..2316319b48 100644 --- a/blocksuite/crates/playground/web/preview-workers.js +++ b/blocksuite/crates/playground/web/preview-workers.js @@ -300,6 +300,57 @@ export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.loc return pdfWorker; } + function resolveSvgIntrinsicSize(svgText) { + const openMatch = /]*>/i.exec(svgText); + if (!openMatch) { + return { svg: svgText, widthPt: null, heightPt: null }; + } + const openTag = openMatch[0]; + const parsePxAttr = (name) => { + const m = new RegExp(`\\b${name}\\s*=\\s*["']([^"']+)["']`, 'i').exec(openTag); + if (!m) return null; + const raw = m[1].trim(); + if (!raw || raw.endsWith('%')) return null; + const n = parseFloat(raw); + return Number.isFinite(n) && n > 0 ? n : null; + }; + let wPt = parsePxAttr('width'); + let hPt = parsePxAttr('height'); + const vbMatch = /\bviewBox\s*=\s*["']\s*([+-]?\d*\.?\d+)[\s,]+([+-]?\d*\.?\d+)[\s,]+([+-]?\d*\.?\d+)[\s,]+([+-]?\d*\.?\d+)\s*["']/i.exec( + openTag + ); + const vbW = vbMatch ? parseFloat(vbMatch[3]) : null; + const vbH = vbMatch ? parseFloat(vbMatch[4]) : null; + const maxWMatch = /max-width\s*:\s*([0-9.]+)px/i.exec(openTag); + const maxWPx = maxWMatch ? parseFloat(maxWMatch[1]) : null; + if (!(wPt > 0 && hPt > 0) && vbW > 0 && vbH > 0) { + if (maxWPx > 0 && maxWPx < vbW) { + wPt = maxWPx; + hPt = vbH * (maxWPx / vbW); + } else { + wPt = vbW; + hPt = vbH; + } + } + if (!(wPt > 0 && hPt > 0)) { + return { svg: svgText, widthPt: null, heightPt: null }; + } + const wAttr = Math.max(1, Math.round(wPt * 100) / 100); + const hAttr = Math.max(1, Math.round(hPt * 100) / 100); + let patchedTag = openTag + .replace(/\s+\bwidth\s*=\s*["'][^"']*["']/gi, '') + .replace(/\s+\bheight\s*=\s*["'][^"']*["']/gi, ''); + patchedTag = patchedTag.replace( + /^ { @@ -326,8 +378,8 @@ export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.loc }); URL.revokeObjectURL(url); const scale = Math.max(1, Math.min(4, req.dpr || 2)); - const wPt = Math.max(1, img.naturalWidth || 320); - const hPt = Math.max(1, img.naturalHeight || 160); + const wPt = Math.max(1, resolved.widthPt || img.naturalWidth || 320); + const hPt = Math.max(1, resolved.heightPt || img.naturalHeight || 160); const canvas = document.createElement('canvas'); canvas.width = Math.round(wPt * scale); canvas.height = Math.round(hPt * scale); diff --git a/packages/frontend/hosts/ios/Sources/LegacyLocalStorageProbe.swift b/packages/frontend/hosts/ios/Sources/LegacyLocalStorageProbe.swift index 40337062aa..35004b55a4 100644 --- a/packages/frontend/hosts/ios/Sources/LegacyLocalStorageProbe.swift +++ b/packages/frontend/hosts/ios/Sources/LegacyLocalStorageProbe.swift @@ -57,8 +57,8 @@ final class LegacyLocalStorageProbe: NSObject, WKNavigationDelegate { static let legacyOrigin = "capacitor://localhost" static let probeURLString = "capacitor://localhost/__affine_probe__" static let localWorkspaceKey = "affine-local-workspace" - nonisolated static let defaultNavigationTimeoutSeconds: TimeInterval = 30.0 - nonisolated static let defaultEvaluationTimeoutSeconds: TimeInterval = 15.0 + nonisolated static let defaultNavigationTimeoutSeconds: TimeInterval = 15.0 + nonisolated static let defaultEvaluationTimeoutSeconds: TimeInterval = 10.0 /// Shared warm WebContent process pool reused across probe calls to avoid cold XPC churn. private static let sharedProcessPool = WKProcessPool() diff --git a/packages/frontend/hosts/web/scripts/verify-canary-dual-shell-browser.mjs b/packages/frontend/hosts/web/scripts/verify-canary-dual-shell-browser.mjs index 9891447f75..34f8e66972 100644 --- a/packages/frontend/hosts/web/scripts/verify-canary-dual-shell-browser.mjs +++ b/packages/frontend/hosts/web/scripts/verify-canary-dual-shell-browser.mjs @@ -100,7 +100,8 @@ function findChromiumBinary() { function chromeEnv() { return { ...process.env, - DBUS_SESSION_BUS_ADDRESS: 'unix:path=/nonexistent/affine-no-dbus', + DBUS_SESSION_BUS_ADDRESS: 'disabled:', + DBUS_SYSTEM_BUS_ADDRESS: 'disabled:', }; } @@ -381,6 +382,7 @@ const chromeProc = spawn( '--disable-sync', '--disable-extensions', '--disable-component-update', + '--disable-dbus', '--metrics-recording-only', '--remote-debugging-port=0', `--user-data-dir=${profileDir}`, diff --git a/packages/frontend/hosts/web/tests/preview-workers.test.mjs b/packages/frontend/hosts/web/tests/preview-workers.test.mjs index 098a300ba6..5e305246b3 100644 --- a/packages/frontend/hosts/web/tests/preview-workers.test.mjs +++ b/packages/frontend/hosts/web/tests/preview-workers.test.mjs @@ -428,3 +428,108 @@ void test('pickImages and pickAttachments bind requestId, finish on change/cance env.restore(); } }); + +void test('mermaid SVG with width="100%" + viewBox rasterizes at intrinsic viewBox/max-width size instead of 300x150 browser fallback', async () => { + const env = createFakeDom(); + const originalBlob = globalThis.Blob; + const originalImage = globalThis.Image; + const createdBlobs = []; + const createdCanvases = []; + globalThis.Blob = class FakeBlob { + constructor(parts, opts) { + this.text = parts.join(''); + this.type = opts?.type || ''; + createdBlobs.push(this); + } + }; + globalThis.Image = class FakeImage { + constructor() { + // Simulate Chromium's 300x150 default when `` lacks explicit px dimensions. + this.naturalWidth = 300; + this.naturalHeight = 150; + this.onload = null; + this.onerror = null; + } + set src(_url) { + const latestSvg = createdBlobs.at(-1)?.text || ''; + const wMatch = /\bwidth="([0-9.]+)"/.exec(latestSvg); + const hMatch = /\bheight="([0-9.]+)"/.exec(latestSvg); + if (wMatch && hMatch) { + this.naturalWidth = Number(wMatch[1]); + this.naturalHeight = Number(hMatch[1]); + } + queueMicrotask(() => this.onload?.()); + } + }; + const origCreateElement = globalThis.document.createElement; + globalThis.document.createElement = tag => { + if (tag === 'canvas') { + const canvas = { + width: 0, + height: 0, + scales: [], + draws: [], + getContext() { + return { + scale(sx, sy) { + canvas.scales.push([sx, sy]); + }, + drawImage(_img, x, y, w, h) { + canvas.draws.push([x, y, w, h]); + }, + getImageData(_x, _y, w, h) { + return { data: new Uint8ClampedArray(w * h * 4) }; + }, + }; + }, + }; + createdCanvases.push(canvas); + return canvas; + } + return origCreateElement(tag); + }; + try { + const delivered = []; + installPlaygroundPreviewBridge({ + deliver_code_preview(kind, source, dark, dpr, wPt, hPt, wPx, hPx, rgba) { + delivered.push({ + kind, + source, + dark, + dpr, + wPt, + hPt, + wPx, + hPx, + bytes: rgba.byteLength, + }); + }, + }); + const bridge = globalThis.window.__playgroundPreview; + bridge.requestCodePreview('mermaid', 'flowchart LR; A-->B-->C', false, 2); + assert.equal(env.workers.length, 1); + const reqId = env.workers[0].posted[0].id; + env.workers[0].emit('message', { + data: { + id: reqId, + ok: true, + result: { + svg: '', + }, + }, + }); + await new Promise(resolve => setTimeout(resolve, 10)); + assert.equal(delivered.length, 1); + assert.equal(delivered[0].wPt, 840); + assert.equal(delivered[0].hPt, 310); + assert.equal(delivered[0].wPx, 1680); + assert.equal(delivered[0].hPx, 620); + assert.equal(createdCanvases[0].width, 1680); + assert.equal(createdCanvases[0].height, 620); + assert.match(createdBlobs.at(-1).text, /^