fix(edgeless): support Page controls in active notes

Map Page block controls, table editing, and block moves through
the Active Note camera. Share the database view state between
the Page flow and the Note paint pass.

Place database popovers within the editor pane. Use window
coordinates for paint, pointer hits, scrolling, and IME.
Position popover hitbox elements relative to the pane.

Support media and caption editing inside active notes. Capture
mouse moves and release during image resize as soon as the drag
starts. Keep database and media writes behind read-only gates.
This commit is contained in:
DarkSky committed 2026-12-02 15:10:56 +09:00
1 parent 3b972c667a
commit 4e2ad7d416
31 files changed
+4651 -397

No files matched your search

+2 -2
View File
@@ -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`), a `RecordSheet` bottom sheet that desktop shows as a centered record peek (on a writable page, clicking its title edits it in place, splicing each keystroke into the live row title `Y.Text` like a `title` cell so peer edits merge and one undo removes only the local typing, while `Enter`, `Escape`, an outside click, or closing the peek only end the edit and write nothing; clicking a checkbox flips it in one undo step; a double click on a Calendar event edits its title in place only right after its first click opened the peek), and `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.<id>.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); all captioned blocks (`affine:image`, `affine:code`, `affine:bookmark`, `affine:attachment`, `affine:embed-linked-doc`, `affine:embed-synced-doc`, `affine:embed-*`, and `affine:surface-ref`) edit `prop:caption` directly in place via `AnchoredInlineInput` + `Utf16ImeBuffer` + `finish_inline_targets` (centered below content with `Write a caption` placeholder when empty, live untrimmed writes storing `""` within the 500 ms undo window, Page-mode `Enter` splitting into a sibling `affine:paragraph` in one `structural_edit`, `Escape`/blur hiding empty slots, and `page_readonly` visible read-only; no detached caption prompt). Desktop `affine:code` blocks show zero top-bar chrome at rest and reveal a borderless hover-only icon toolbar (`page.block.<id>.toolbar`, `.language`, optional `[Code | Preview]` segmented switcher `.preview_code`/`.preview`, uniform `28 × 28` `.copy` swapping `CopyIcon` → `DoneIcon` for 1.5 s with `context_toast`, `.collapse`, `.caption_btn` with `CaptionIcon`, and `.more` opening `overlay.code_more_menu` with `Wrap` and `Line number` switches, `Duplicate`, and hover-red `Delete`; 0 ms enter / 250 ms leave delay / 100 ms fade, hidden on non-collapsed text selections; on Phone/Tablet/touch hosts, code blocks use `12 px` padding and line numbers default off via `code_line_number_default`, and focusing or selecting a code block docks a horizontally scrollable `>= 44 × 44 pt` bottom context toolbar via `place_touch_docked_toolbar` above `KeyboardToolbar` exposing `.language`, conditional `.preview`, `.copy`, `.caption_btn`, `.wrap`, `.line_number`, `.collapse`, `.duplicate`, and pinned `.delete`, plus an `80 px` collapsed fade with `padding-bottom: 0`). Selected `affine:image`, `affine:bookmark`, embed, and `affine:callout` blocks mount toolbars on the shared `ToolbarChrome`: `overlay.image_toolbar` (`Download` when the host can save the blob, `Caption`, `Align Left` / `Align Center` / `Align Right`, and `.more_menu` with `Copy`, `Duplicate`, `Turn into card view`, and `Delete`; 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` (`.open`, a `Card view` dropdown `.view_menu` with `Inline view` / `Card view` / host-validated `Embed view`, a Page-mode `.style` dropdown `.style_menu` with `Large horizontal` / `Small horizontal`, `.caption`, and `.more_menu` with `Copy`, `Duplicate`, and `Delete`, plus inline `overlay.url_paste_menu` on plain URL paste), `overlay.embed_toolbar` (`.open`, `.preview`, `.view` / `.view_menu`, `.style` / `.style_menu`, `.caption`, and `.more_menu`), and `overlay.callout_toolbar` (`.icon` opening `overlay.callout_icon_picker` with `{"type":"emoji","unicode":...}` `IconData` Map items and `.remove`, a `Background` dropdown `.color` / `.color_menu` with 9 `0.27.5` semantic swatches `.bg.<name>`, and `.more_menu` with `Delete`), 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`).
- **Block controls & block toolbars**: `page.block.<id>.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); all captioned blocks (`affine:image`, `affine:code`, `affine:bookmark`, `affine:attachment`, `affine:embed-linked-doc`, `affine:embed-synced-doc`, `affine:embed-*`, and `affine:surface-ref`) edit `prop:caption` directly in place via `AnchoredInlineInput` + `Utf16ImeBuffer` + `finish_inline_targets` (centered below content with `Write a caption` placeholder when empty, live untrimmed writes storing `""` within the 500 ms undo window, Page-mode `Enter` splitting into a sibling `affine:paragraph` in one `structural_edit`, `Escape`/blur hiding empty slots, and `page_readonly` visible read-only; no detached caption prompt). Desktop `affine:code` blocks show zero top-bar chrome at rest and reveal a borderless hover-only icon toolbar (`page.block.<id>.toolbar`, `.language`, optional `[Code | Preview]` segmented switcher `.preview_code`/`.preview`, uniform `28 × 28` `.copy` swapping `CopyIcon` → `DoneIcon` for 1.5 s with `context_toast`, `.collapse`, `.caption_btn` with `CaptionIcon`, and `.more` opening `overlay.code_more_menu` with `Wrap` and `Line number` switches, `Duplicate`, and hover-red `Delete`; 0 ms enter / 250 ms leave delay / 100 ms fade, hidden on non-collapsed text selections; on Phone/Tablet/touch hosts, code blocks use `12 px` padding and line numbers default off via `code_line_number_default`, and focusing or selecting a code block docks a horizontally scrollable `>= 44 × 44 pt` bottom context toolbar via `place_touch_docked_toolbar` above `KeyboardToolbar` exposing `.language`, conditional `.preview`, `.copy`, `.caption_btn`, `.wrap`, `.line_number`, `.collapse`, `.duplicate`, and pinned `.delete`, plus an `80 px` collapsed fade with `padding-bottom: 0`). Selected `affine:image`, `affine:bookmark`, embed, and `affine:callout` blocks mount toolbars on the shared `ToolbarChrome`: `overlay.image_toolbar` (`Download` when the host can save the blob, `Caption`, `Align Left` / `Align Center` / `Align Right`, and `.more_menu` with `Copy`, `Duplicate`, `Turn into card view`, and `Delete`; 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` (`.open`, a `Card view` dropdown `.view_menu` with `Inline view` / `Card view` / host-validated `Embed view`, a Page-mode `.style` dropdown `.style_menu` with `Large horizontal` / `Small horizontal`, `.caption`, and `.more_menu` with `Copy`, `Duplicate`, and `Delete`, plus inline `overlay.url_paste_menu` on plain URL paste), `overlay.embed_toolbar` (`.open`, `.preview`, `.view` / `.view_menu`, `.style` / `.style_menu`, `.caption`, and `.more_menu`), and `overlay.callout_toolbar` (`.icon` opening `overlay.callout_icon_picker` with `{"type":"emoji","unicode":...}` `IconData` Map items and `.remove`, a `Background` dropdown `.color` / `.color_menu` with 9 `0.27.5` semantic swatches `.bg.<name>`, and `.more_menu` with `Delete`), docking cleanly as horizontally scrollable `>= 44 × 44 pt` bottom context bars on touch viewports down to `360 pt`. A mouse image resize owns the pointer until the release, so the toolbar inside the image never takes the move or the release. 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 (touch host controls `>= 44 pt` height). Desktop floating toolbars share `ToolbarChrome` (`toolbar_chrome/`): a 36 px tall bar with a 0.5 px border, 8 px radius, 24 × 24 px buttons with 20 px icons and 4 px radius, groups split by 4 px separator slots, a 10 px offset from the anchor, 8 px dropdown panels with 30 px rows, and tooltips 8 px above the hovered button after the shared 500 ms enter / 250 ms leave hover delay (none while a toolbar dropdown is open). On viewports `>= 460 px` the formatting toolbar shows every group (`Turn into`, `Align`, seven inline marks, `Highlight`, `Create Table` when allowed, `Create Linked Doc`, `More`) with 8 px group gaps and 6 px side padding: 490 px wide with `Create Table`, 462 px without. On viewports `< 460 px` it shows the `FormatAction::COMPACT` set (`Turn into`, `Align`, `Bold`, `Italic`, `Underline`, `Strike`, `Code`, `Link`, `Highlight`) with 4 px group gaps and 4 px side padding, 296 px wide, so it fits a 320 px window between its 8 px margins. All floating popovers and toolbars fade opacity monotonically in place over 150 ms with zero entrance/exit coordinate drift.
- **Verification**: `bs-harness render --state <name>` 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 <dir>` 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.
@@ -57,7 +57,7 @@ These crates belong to the client Cargo workspace rooted at `packages/frontend/C
### Edgeless spatial canvas and interactive authoring
- **Spatial camera & canvas (`edgeless/`)**: `edgeless/camera.rs` (`EdgelessCamera`) manages pan/zoom (`[0.1, 6.0]`), cursor-anchored wheel zoom, and fit-to-bounds (initialized before building `chrome.edgeless_zoom` so Frame 1 displays the fitted zoom percentage). Clicking zoom bar buttons (`-` / `100%` / `+` / `Fit`, firing on pointer release with additive `±0.25` zoom steps and `>= 44 pt` touch targets on touch form factors) runs a closed-form 170 ms ease-out `CameraTransition` anchored on the world viewport center with smooth mid-flight retargeting (cancelled immediately by wheel, pinch, pan, or direct camera updates), and `chrome.edgeless_toolbar.shape_picker` opens and closes with a 230 ms ease-out slide-out (`12px -> 0px`) and fade (`ShapePickerPresence`, interactive from Frame 1). `edgeless/scene.rs` and `edgeless/canvas_paint.rs` prepare and render Surface-parented Frames and EdgelessText and root-parented Notes in a single snapshot pass. Note dimensions are world units. Layout uses the logical width divided by scale. Collapsed notes clip to the stored world height, which already includes scale. The canvas merges the block and vector paint streams by fractional index and Frame/Group ancestry (`prop:childElementIds` treats every present key as a frame member, and equal indices preserve source enumeration order within each stream — live incremental sync and independent multi-author merged updates follow `(Reverse(client), clock)` integration order, whereas a late-join single V1 snapshot with cross-client causal edits among equal-index overlapping elements can invert their tie-break paint/pick order until `y-octo` exposes per-map integration order). Equal indices continue the active stream, with blocks first at the start. Notes reuse their cached `BlockFlow::layout_nodes` during pan/zoom. All items paint under `edgeless.viewport`, with bottom-centered creation toolbar (`chrome.edgeless_toolbar`), logical bottom-start screen-space zoom controls (`chrome.edgeless_zoom`: `[FitIcon] [−] [100%] [+]`, mirrored in RTL and stacked cleanly above `chrome.edgeless_toolbar` on narrow viewports `< 660 px`), and floating selection property bar (`edgeless.element_toolbar` for Note, Shape, Connector, Brush, Highlighter, SurfaceText, EdgelessText, Frame, and Group styling). `bs-harness render --mode edgeless [--zoom <f32>] [--pan <x>,<y>]` renders spatial states, `bs-harness audit-states` audits Edgeless default + `0.5x` + `2.0x` + authoring states (`edgeless_selected`, `edgeless_marquee`, `edgeless_inline_edit`, `edgeless_authoring`) in Light/Dark at `1280` and `320` px, and `bs-harness bench` measures `edgeless_1k_pan_zoom_frame_ms` and asserts `edgeless_1k_pan_zoom_blocks_relayout == 0`.
- **Edgeless interactive authoring & inline IME editing (`edgeless/{toolbar,hit_test,overlay,label_editor,inline_edit,gestures,commit,commands}.rs`)**: `chrome.edgeless_toolbar` provides Select (`V`/`Escape`), Hand (`H` or holding `Space`), Note (`N`), Shape (`S` with rect/ellipse/diamond/triangle/rounded-rect picker), Connector (`C` with cardinal port snapping and live connector preview), Brush (`P`), Highlighter, Text (`T`), and Frame (`F`, populating `prop:childElementIds`). World-space hit-testing walks exact reverse paint order (inverse-rotated OBBs for shapes/texts, routed polyline distance from `SurfaceLayout` for connectors/strokes, exact `layout_inline` title pill and border for frames). Selection renders a screen-crisp `edgeless.selection_box`, 8 resize handles (`edgeless.handle.nw..w`), four `12px` outer-corner rotation hit zones (`edgeless.handle.rotate`, `rotate_nw`, `rotate_se`, `rotate_sw`, `15°` snap with `Shift`), and `2×3` 6-dot `14px` Edgeless `gfx` drag handle (`edgeless.drag_handle`) on selected blocks; resize and rotation handles are suppressed while inline label editing is active, and the underlying static label is hidden until commit. Dragging, resizing, rotating, deleting (`Backspace`/`Delete`), and z-reordering (`[`/`]` via `fractional-indexing@3.2.0` keys in `blocksuite/blocksuite/crates/doc/src/fractional_index.rs`) commit single atomic undo steps on `PageDocSession` and broadcast over `RoomProtocol`. Double-clicking a Note or EdgelessText edits rich text inline via `EditorSession` + `EntityInputHandler` with camera-mapped `bounds_for_range`; double-clicking a Shape, Connector, SurfaceText, or Frame title edits its `Y.Text` inline (`edgeless.inline_edit`) with full UTF-16 + IME preedit support (clicking inside an active inline label commits any in-flight composition via `unmark` into its original replacement range before placing the caret, while body `change_selection` clears in-flight composition on click).
- **Edgeless interactive authoring & inline IME editing (`edgeless/{toolbar,hit_test,overlay,label_editor,inline_edit,gestures,commit,commands}.rs`)**: `chrome.edgeless_toolbar` provides Select (`V`/`Escape`), Hand (`H` or holding `Space`), Note (`N`), Shape (`S` with rect/ellipse/diamond/triangle/rounded-rect picker), Connector (`C` with cardinal port snapping and live connector preview), Brush (`P`), Highlighter, Text (`T`), and Frame (`F`, populating `prop:childElementIds`). World-space hit-testing walks exact reverse paint order (inverse-rotated OBBs for shapes/texts, routed polyline distance from `SurfaceLayout` for connectors/strokes, exact `layout_inline` title pill and border for frames). Selection renders a screen-crisp `edgeless.selection_box`, 8 resize handles (`edgeless.handle.nw..w`), four `12px` outer-corner rotation hit zones (`edgeless.handle.rotate`, `rotate_nw`, `rotate_se`, `rotate_sw`, `15°` snap with `Shift`), and `2×3` 6-dot `14px` Edgeless `gfx` drag handle (`edgeless.drag_handle`) on selected blocks; resize and rotation handles are suppressed while inline label editing is active, and the underlying static label is hidden until commit. Dragging, resizing, rotating, deleting (`Backspace`/`Delete`), and z-reordering (`[`/`]` via `fractional-indexing@3.2.0` keys in `blocksuite/blocksuite/crates/doc/src/fractional_index.rs`) commit single atomic undo steps on `PageDocSession` and broadcast over `RoomProtocol`. Double-clicking a Note or EdgelessText edits rich text inline via `EditorSession` + `EntityInputHandler` with camera-mapped `bounds_for_range`; double-clicking a Shape, Connector, SurfaceText, or Frame title edits its `Y.Text` inline (`edgeless.inline_edit`) with full UTF-16 + IME preedit support (clicking inside an active inline label commits any in-flight composition via `unmark` into its original replacement range before placing the caret, while body `change_selection` clears in-flight composition on click). Inside an edited Note (Active Note), Page block controls, Simple Table cells and controls, database popovers and in-cell inputs, captions, and the block drag handle use the Page code paths through one camera mapping (`active_overlay_target`'s `OverlayScreenTransform`; `None` in Page mode), and the Page `BlockFlow` lays the Note out again for database hit caches only when the Note holds a database and its document, view state, width, theme, or direction changed. The canvas paints the edited Note with the same database view state (`EdgelessCanvasState::sync_note_database_state`), so a view switch, search, or collapsed group changes the painted Note and its hits together. That Note pass and a Page pass each drop the other's cached layout, because they share one `BlockFlow`. The camera transform maps into the window, and the overlays and popovers take it relative to the view, so an embedded view at a nonzero window position keeps pointer hits and painted controls aligned. On a touch host or in a viewport narrower than 600 px, a focused Active Note table cell docks the Page `overlay.table_toolbar` in place of the desktop table controls and `chrome.edgeless_toolbar`.
- **Canvas media blocks (`edgeless/canvas.rs`, `playground/src/overlays/view_caption/paint.rs`, `playground/src/edgeless/element_toolbar_media_actions.rs`)**: Image, bookmark, attachment, and embed blocks on the canvas paint their content top-aligned and clipped to `prop:xywh`, and their caption below that frame (`canvas_caption_shift`). An edited canvas caption draws `edgeless.caption_focus` and `edgeless.caption_caret`, takes every key before the canvas shortcuts, places the caret on a press inside its slot, and closes on `Enter`, `Escape`, a press outside it, a mode switch, or the deletion of its block. A card `Style` change and a `Card` / `Embed` view switch write the BlockSuite standard frame (`embed_card_size`) with the new style or block in one undo step, and the selection follows a replaced block. Z-order actions on a selection that already ends its paint stream (blocks or canvas elements) write nothing. Quick-connect clones step around shapes, notes, blocks, and brush or highlighter strokes. Both Page and canvas media downloads flow through `ImageStore`'s single `set_on_blob_download` host channel (or browser `<a download>` on Web), and canvas `Image`/`Attachment` toolbars show `Download` only when `ImageStore::can_deliver_downloads()` is true and the block's `source_id` has non-empty cached bytes (`has_blob_bytes`).
### Surface reading and painting
@@ -122,6 +122,10 @@ pub struct EdgelessCanvasState {
pub(super) surface_block_flows: HashMap<String, CachedNoteFlow>,
/// Caption being edited in place, laid out into the canvas block it belongs to.
pub caption_draft: Option<CaptionDraft>,
/// Live `(block_id, width, height)` of an image being resized inside an edited Note.
pub image_resize_preview: Option<(String, f32, f32)>,
/// Note id and host database view revision last given by [`Self::sync_note_database_state`].
note_database_rev: Option<(String, u64)>,
/// Number of block bodies laid out during the most recent Edgeless frame.
pub last_frame_relayouts: u64,
}
@@ -295,6 +299,30 @@ impl EdgelessCanvasState {
}
}
/// Give the cached flow of Note `note_id` the host's database view state (active view,
/// search, collapsed groups, authoring previews), so the canvas paints the view that the
/// host's database hit targets describe. The Note lays out again only when that state
/// changed.
pub fn sync_note_database_state(
&mut self,
note_id: &str,
state: &crate::database::DatabaseFlowState,
) {
let rev = (note_id.to_string(), state.revision());
if self.note_database_rev.as_ref() == Some(&rev) {
return;
}
let Some(entry) = self.note_flows.get_mut(note_id) else {
return;
};
entry.flow.database_state = state.clone();
// No document has this revision, so the next frame lays the Note out again, and the
// hit and selection geometry follows the new height.
entry.key.0 = u64::MAX;
self.surfaces = None;
self.note_database_rev = Some(rev);
}
/// Cached flow of a canvas media block (`image`, bookmark, attachment, or embed card).
pub fn cached_surface_block_layout(&self, block_id: &str) -> Option<Rc<FlowLayout>> {
self.surface_block_flows
@@ -146,6 +146,10 @@ pub fn prepare_edgeless_scene(
});
entry.flow.local_collapsed =
input.local_collapsed.cloned().unwrap_or_default();
entry
.flow
.image_resize_preview
.clone_from(&state.image_resize_preview);
let laid_out =
entry
.flow
@@ -0,0 +1,654 @@
//! Edgeless Active Note interactive Page-layer controls: block-level collapse/todo/toggle,
//! media/embed cards, captions, and inline LaTeX chips mapped through camera pan + zoom.
use blocksuite_editor::{
block_flow::{
FlowInput, FlowKind, FlowRect, PAGE_SURFACE_ID, heading_marker_rect_for_direction,
paint_chevron, paragraph_spec,
},
edgeless::NOTE_CARD_PADDING,
overlays::{
CONTROL_HIT_SIZE, EquationTarget, OverlayEvent, OverlayScreenTransform, PdfViewerEvent,
},
rich_text::DecorationKind,
theme::{IconPaint, Palette},
};
use blocksuite_playground_doc::{
read::BlockContent,
schema::{ListType, ParagraphType},
};
use ui::{
AnyElement, ClickEvent, Context, MouseButton, MouseDownEvent, SharedString, Window, canvas,
div, point, prelude::*, px, size,
};
use crate::{PlaygroundView, overlays::TablePaintFrame};
pub(super) fn place_rect(rect: FlowRect) -> ui::Div {
div()
.absolute()
.left(px(rect.x))
.top(px(rect.y))
.w(px(rect.w))
.h(px(rect.h))
}
pub(super) fn to_viewport(
transform: OverlayScreenTransform,
vp_origin: (f32, f32),
rect: &FlowRect,
) -> FlowRect {
let s = transform.rect_to_screen(rect);
FlowRect::new(s.x - vp_origin.0, s.y - vp_origin.1, s.w, s.h)
}
pub(super) fn intersects_viewport(rect: &FlowRect, vp_w: f32, vp_h: f32) -> bool {
rect.bottom() > 0.0 && rect.y < vp_h && rect.right() > 0.0 && rect.x < vp_w
}
pub(super) fn fully_visible_in_viewport(rect: &FlowRect, vp_w: f32, vp_h: f32) -> bool {
rect.y >= 0.0 && rect.bottom() <= vp_h && rect.x >= 0.0 && rect.right() <= vp_w
}
pub(super) fn icon_el(name: &'static str, side: f32, color: ui::Hsla) -> impl IntoElement {
let icon = IconPaint::named(name);
canvas(
|_, _, _| (),
move |bounds, _, window, cx| icon.paint(bounds, color, window, cx),
)
.flex_none()
.w(px(side))
.h(px(side))
}
/// Inputs of the last Page-flow pass over the edited Note's blocks, so the pass runs again only
/// when one of them changes.
#[derive(Default)]
pub(crate) struct ActiveNoteFlowCache {
key: Option<ActiveNoteFlowKey>,
/// Number of passes run, for tests.
pub(crate) passes: u64,
}
impl ActiveNoteFlowCache {
/// Forget the last pass, after a Page pass replaced the shared flow's caches.
pub(crate) fn invalidate(&mut self) {
self.key = None;
}
}
#[derive(PartialEq)]
struct ActiveNoteFlowKey {
editing_id: String,
snapshot_rev: u64,
database_rev: u64,
env_rev: u64,
inner_width_bits: u32,
theme: crate::PlaygroundTheme,
direction: ui::Direction,
}
impl PlaygroundView {
/// Window position of this view's top-left corner: the Active Note camera transform maps
/// into the window, and overlays and popovers place themselves relative to this view.
pub(crate) fn view_window_offset(&self) -> (f32, f32) {
let origin = self.canvas_origin();
(
f32::from(origin.x),
f32::from(origin.y) - self.topbar_height(),
)
}
/// Lay the edited Note's blocks out with the Page `BlockFlow` when the Note holds a
/// database, so the database hit, anchor, and active-cell caches the `database_authoring`
/// dispatchers read describe that Note. Runs again only when the Note, the document, the
/// database view state, the width, the theme, or the direction changed.
pub(crate) fn sync_active_note_flow(&mut self, editing_id: &str, window: &Window) {
let Some(snapshot) = self.snapshot.clone() else {
return;
};
let has_database = self
.edgeless
.cached_block_layout(editing_id, true)
.is_some_and(|l| l.blocks.iter().any(|b| b.body.kind == FlowKind::Database));
let (Some(note_node), Some(info), true) = (
snapshot.block(editing_id),
self.edgeless
.authoring
.painted_items
.iter()
.find(|i| i.id == editing_id),
has_database,
) else {
self.active_note_flow.key = None;
return;
};
let inner_width = (info.rect.w / info.scale - 2.0 * NOTE_CARD_PADDING).max(60.0);
let key = ActiveNoteFlowKey {
editing_id: editing_id.to_string(),
snapshot_rev: self.page().map_or(0, |p| p.revision()),
database_rev: self.flow.database_state.revision(),
env_rev: self.env_rev,
inner_width_bits: inner_width.to_bits(),
theme: self.theme,
direction: window.layout_direction(),
};
if self.active_note_flow.key.as_ref() == Some(&key) {
return;
}
let offset_at = self.utc_offset_resolver();
let doc_dir: &dyn crate::directory::WorkspaceDocDirectory = self
.custom_doc_directory
.as_deref()
.unwrap_or(&self.default_doc_directory);
let flow_input = FlowInput {
snapshot: &snapshot,
width: inner_width,
theme: self.theme,
page_titles: &self.page_titles,
images: &self.images,
pdf_previews: Some(&self.pdf_previews),
doc_directory: Some(doc_dir),
equation_draft: None,
env_rev: self.env_rev,
direction: key.direction,
form_factor: self.form_factor,
utc_offset_minutes: 0,
utc_offset_at: Some(&offset_at),
};
self.flow
.layout_nodes(&note_node.children, &flow_input, window);
// The pass replaced the Page bodies and hit caches, so the Page lays out again.
self.layout = None;
self.active_note_flow.key = Some(key);
self.active_note_flow.passes += 1;
}
/// Build interactive Page-layer controls, Simple Table overlays, and media/caption hitboxes
/// for an Active Note in Edgeless mode, mapped accurately through camera pan + zoom.
pub(crate) fn render_active_note_controls(
&mut self,
palette: &Palette,
viewport_width: f32,
viewport_height: f32,
window: &mut Window,
cx: &mut Context<Self>,
) -> Vec<AnyElement> {
let Some((editing_id, true)) = self
.edgeless
.authoring
.editing_spatial_block()
.map(|(id, is_note)| (id.to_string(), is_note))
else {
return Vec::new();
};
self.sync_active_note_flow(&editing_id, window);
let Some((snapshot, layout, Some(transform))) = self.active_overlay_target() else {
return Vec::new();
};
let now_ms = self.now_ms(cx);
let origin = self.canvas_origin();
let vp_origin = (f32::from(origin.x), f32::from(origin.y));
let direction = window.layout_direction();
let readonly = self.edgeless_readonly;
let single_sel = (self.editor.block_selection.len() == 1)
.then(|| self.editor.block_selection[0].as_str());
let selected_image = self.selected_image_block_id(&layout).map(str::to_string);
let selected_bookmark = self.selected_bookmark_block_id(&layout).map(str::to_string);
let selected_attachment = single_sel
.and_then(|id| layout.block(id))
.filter(|b| matches!(b.body.kind, FlowKind::Attachment))
.map(|b| b.block_id.clone());
let selected_embed = self.selected_embed_block_id(&layout).map(str::to_string);
let selected_latex = single_sel
.and_then(|id| layout.block(id))
.filter(|b| matches!(b.body.kind, FlowKind::Latex))
.map(|b| b.block_id.clone());
let hovered_block = self.overlays.hovered_block().map(str::to_string);
let mut elements = Vec::new();
for block in &layout.blocks {
let rect = block.rect();
let block_vp = to_viewport(transform, vp_origin, &rect);
if !intersects_viewport(&block_vp, viewport_width, viewport_height) {
continue;
}
let hovered = hovered_block.as_deref() == Some(block.block_id.as_str());
if block.has_gutter_chevron {
let own_marker = block.body.chevron();
if own_marker.is_some() || hovered {
let line_height = match block.body.kind {
FlowKind::Paragraph(p) => paragraph_spec(p).line_height,
_ => paragraph_spec(ParagraphType::Text).line_height,
};
let marker = heading_marker_rect_for_direction(line_height, rect.w, direction);
let target = FlowRect::new(
rect.x + marker.x + (marker.w - CONTROL_HIT_SIZE) * 0.5,
rect.y + marker.y + (marker.h - CONTROL_HIT_SIZE) * 0.5,
CONTROL_HIT_SIZE,
CONTROL_HIT_SIZE,
);
let target_vp = to_viewport(transform, vp_origin, &target);
let bid = block.block_id.clone();
let hover_bg = palette.hover;
let mut el = place_rect(target_vp)
.id(SharedString::from(format!("an-collapse-{bid}")))
.rounded(px(4.0))
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, _: &ClickEvent, w, cx| {
this.dispatch_overlay(
OverlayEvent::ToggleCollapsed(bid.clone()),
w,
cx,
);
}));
if fully_visible_in_viewport(&target_vp, viewport_width, viewport_height) {
el = el.snapshot(
format_args!("{}.collapse", block.snapshot_id()),
Some(PAGE_SURFACE_ID),
);
}
if own_marker.is_none() {
let color = palette.icon;
let inset = (target_vp.w - marker.w * transform.scale).max(0.0) * 0.5;
let mw = marker.w * transform.scale;
let mh = marker.h * transform.scale;
el = el.child(
canvas(
|_, _, _| (),
move |bounds, _, window, cx| {
let glyph = ui::Bounds::new(
point(
bounds.origin.x + px(inset),
bounds.origin.y + px(inset),
),
size(px(mw), px(mh)),
);
paint_chevron(glyph, 1.0, color, window, cx);
},
)
.size_full(),
);
}
elements.push(el.into_any_element());
}
}
match block.body.kind {
FlowKind::List(kind @ (ListType::Todo | ListType::Toggle)) => {
if let Some(prefix) = block.body.prefix {
let target_x = match direction {
ui::Direction::Ltr => rect.x,
ui::Direction::Rtl => rect.right() - CONTROL_HIT_SIZE,
};
let target = FlowRect::new(
target_x,
rect.y + prefix.y + (prefix.h - CONTROL_HIT_SIZE) * 0.5,
CONTROL_HIT_SIZE,
CONTROL_HIT_SIZE,
);
let target_vp = to_viewport(transform, vp_origin, &target);
let bid = block.block_id.clone();
let (suffix, is_todo) = match kind {
ListType::Todo => ("checkbox", true),
_ => ("toggle", false),
};
let mut el = place_rect(target_vp)
.id(SharedString::from(format!("an-{suffix}-{bid}")))
.cursor_pointer()
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, _: &ClickEvent, w, cx| {
let ev = if is_todo {
OverlayEvent::ToggleChecked(bid.clone())
} else {
OverlayEvent::ToggleCollapsed(bid.clone())
};
this.dispatch_overlay(ev, w, cx);
}));
if fully_visible_in_viewport(&target_vp, viewport_width, viewport_height) {
el = el.snapshot(
format_args!("{}.{suffix}", block.snapshot_id()),
Some(PAGE_SURFACE_ID),
);
}
elements.push(el.into_any_element());
}
}
FlowKind::Code => {
self.push_active_note_code_toolbar(
block,
&layout,
&snapshot,
transform,
vp_origin,
viewport_width,
viewport_height,
hovered,
readonly,
palette,
cx,
&mut elements,
);
}
FlowKind::Image => {
self.push_active_note_image_controls(
block,
transform,
vp_origin,
viewport_width,
viewport_height,
selected_image.as_deref() == Some(block.block_id.as_str()),
readonly,
palette,
cx,
&mut elements,
);
}
FlowKind::Bookmark => {
if let Some(BlockContent::Bookmark { url, .. }) =
snapshot.block(&block.block_id).map(|n| &n.content)
{
let selected =
selected_bookmark.as_deref() == Some(block.block_id.as_str());
let bid = block.block_id.clone();
let url = url.clone();
let mut card = place_rect(block_vp)
.id(SharedString::from(format!("an-bookmark-{bid}")))
.rounded(px(8.0))
.cursor_pointer()
.when(selected, |el| el.border_1().border_color(palette.brand))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, ev: &ClickEvent, w, cx| {
let event = if ev.click_count() >= 2 || readonly {
OverlayEvent::OpenBookmarkUrl(url.clone())
} else {
OverlayEvent::SelectBlock(bid.clone())
};
this.dispatch_overlay(event, w, cx);
}));
if fully_visible_in_viewport(&block_vp, viewport_width, viewport_height) {
card = card
.snapshot(
format_args!("{}.bookmark_card", block.snapshot_id()),
Some(PAGE_SURFACE_ID),
)
.snapshot_focused(selected);
}
elements.push(card.into_any_element());
}
}
FlowKind::Attachment => {
let selected = selected_attachment.as_deref() == Some(block.block_id.as_str());
let can_open_pdf = block.body.pdf_controls.is_some()
|| snapshot.block(&block.block_id).is_some_and(|n| {
matches!(
&n.content,
BlockContent::Attachment {
name,
mime_type,
source_id,
..
} if !source_id.is_empty()
&& (mime_type.eq_ignore_ascii_case("application/pdf")
|| name.to_ascii_lowercase().ends_with(".pdf"))
)
});
let bid = block.block_id.clone();
let mut card = place_rect(block_vp)
.id(SharedString::from(format!("an-attachment-{bid}")))
.cursor_pointer()
.when(selected, |el| {
el.rounded(px(8.0)).border_2().border_color(palette.brand)
})
.on_mouse_down(
MouseButton::Left,
cx.listener(move |this, ev: &MouseDownEvent, w, cx| {
cx.stop_propagation();
let event = if can_open_pdf && ev.click_count >= 2 {
OverlayEvent::PdfViewer(PdfViewerEvent::Open {
block_id: bid.clone(),
})
} else {
OverlayEvent::SelectAttachmentBlock(bid.clone())
};
this.dispatch_overlay(event, w, cx);
}),
);
if fully_visible_in_viewport(&block_vp, viewport_width, viewport_height) {
card = card
.snapshot(
format_args!("{}.attachment_card", block.snapshot_id()),
Some(PAGE_SURFACE_ID),
)
.snapshot_focused(selected);
}
elements.push(card.into_any_element());
}
FlowKind::EmbedLinkedDoc | FlowKind::EmbedSyncedDoc => {
// Open the doc like the canvas card does: a linked card with `params`
// (`mode`, `blockIds`, `elementIds`) opens its full card URL.
let node = snapshot.block(&block.block_id);
let params = node
.and_then(|n| n.props.get("prop:params"))
.filter(|v| v.as_object().is_some_and(|p| !p.is_empty()));
let open = match node.map(|n| &n.content) {
Some(BlockContent::EmbedLinkedDoc { page_id, .. }) if params.is_some() => {
Some(OverlayEvent::OpenBookmarkUrl(
crate::edgeless::linked_card_url(
self.state.workspace.room(),
page_id,
params,
),
))
}
Some(
BlockContent::EmbedLinkedDoc { page_id, .. }
| BlockContent::EmbedSyncedDoc { page_id, .. },
) => Some(OverlayEvent::OpenEmbedDoc {
page_id: page_id.clone(),
}),
_ => None,
};
if let Some(open) = open {
let selected = selected_embed.as_deref() == Some(block.block_id.as_str());
let bid = block.block_id.clone();
let mut card = place_rect(block_vp)
.id(SharedString::from(format!("an-embed-{bid}")))
.rounded(px(8.0))
.cursor_pointer()
.when(selected, |el| el.border_1().border_color(palette.brand))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, ev: &ClickEvent, w, cx| {
let event = if ev.click_count() >= 2 || readonly {
open.clone()
} else {
OverlayEvent::SelectBlock(bid.clone())
};
this.dispatch_overlay(event, w, cx);
}));
if fully_visible_in_viewport(&block_vp, viewport_width, viewport_height) {
card = card
.snapshot(
format_args!("{}.embed_card", block.snapshot_id()),
Some(PAGE_SURFACE_ID),
)
.snapshot_focused(selected);
}
elements.push(card.into_any_element());
}
}
FlowKind::ExternalEmbed => {
let bid = block.block_id.clone();
let mut shield = place_rect(block_vp)
.id(SharedString::from(format!("an-ext-embed-{bid}")))
.cursor_pointer()
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, ev: &ClickEvent, w, cx| {
this.dispatch_overlay(
OverlayEvent::ExternalEmbedInteract {
block_id: bid.clone(),
activate: ev.click_count() >= 2,
},
w,
cx,
);
}));
if fully_visible_in_viewport(&block_vp, viewport_width, viewport_height) {
shield = shield.snapshot(
format_args!("{}.embed_shield", block.snapshot_id()),
Some(PAGE_SURFACE_ID),
);
}
elements.push(shield.into_any_element());
}
FlowKind::Latex => {
let initial = snapshot
.block(&block.block_id)
.and_then(|n| match &n.content {
BlockContent::Latex { latex } => Some(latex.clone()),
_ => None,
})
.unwrap_or_default();
let already_selected =
selected_latex.as_deref() == Some(block.block_id.as_str());
let bid = block.block_id.clone();
let hover_bg = palette.hover;
elements.push(
place_rect(block_vp)
.id(SharedString::from(format!("an-latex-{bid}")))
.rounded(px(4.0))
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, ev: &ClickEvent, w, cx| {
let event = if already_selected || ev.click_count() >= 2 {
OverlayEvent::OpenEquationEditor {
target: EquationTarget::Block {
block_id: bid.clone(),
},
initial: initial.clone(),
}
} else {
OverlayEvent::SelectBlock(bid.clone())
};
this.dispatch_overlay(event, w, cx);
}))
.into_any_element(),
);
}
_ => {}
}
if !readonly && let Some(slot) = block.body.caption_slot.as_ref() {
let cap_world = slot.rect.translated(rect.x, rect.y);
let cap_vp = to_viewport(transform, vp_origin, &cap_world);
if intersects_viewport(&cap_vp, viewport_width, viewport_height) {
let bid = block.block_id.clone();
let mut cap = place_rect(cap_vp)
.id(SharedString::from(format!("an-caption-{bid}")))
.cursor(ui::CursorStyle::IBeam)
.on_mouse_down(
MouseButton::Left,
cx.listener(move |this, ev: &MouseDownEvent, w, cx| {
cx.stop_propagation();
this.dispatch_overlay(
OverlayEvent::CaptionMouseDown {
block_id: bid.clone(),
screen_pos: (
f32::from(ev.position.x),
f32::from(ev.position.y),
),
click_count: ev.click_count,
shift: ev.modifiers.shift,
},
w,
cx,
);
}),
);
if fully_visible_in_viewport(&cap_vp, viewport_width, viewport_height) {
cap = cap.snapshot(
format_args!("{}.caption", block.snapshot_id()),
Some(PAGE_SURFACE_ID),
);
}
elements.push(cap.into_any_element());
}
}
if let Some(body_text) = &block.body.text {
for (deco_idx, deco) in body_text.layout.decorations().iter().enumerate() {
if let DecorationKind::LatexChip(latex) = &deco.kind {
let chip_world = FlowRect::new(
rect.x + body_text.x + f32::from(deco.bounds.origin.x),
rect.y + body_text.y + f32::from(deco.bounds.origin.y),
f32::from(deco.bounds.size.width),
f32::from(deco.bounds.size.height),
);
let chip_vp = to_viewport(transform, vp_origin, &chip_world);
if !intersects_viewport(&chip_vp, viewport_width, viewport_height) {
continue;
}
let bid = block.block_id.clone();
let utf16_offset = deco.source_utf16.start;
let initial = latex.clone();
let hover_bg = palette.hover;
elements.push(
place_rect(chip_vp)
.id(SharedString::from(format!(
"an-inline-latex-{bid}-{utf16_offset}-{deco_idx}"
)))
.rounded(px(4.0))
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, _: &ClickEvent, w, cx| {
this.dispatch_overlay(
OverlayEvent::OpenEquationEditor {
target: EquationTarget::Inline {
block_id: bid.clone(),
utf16_offset,
},
initial: initial.clone(),
},
w,
cx,
);
}))
.into_any_element(),
);
}
}
}
}
self.push_active_note_drag_handle(
&layout,
transform,
vp_origin,
viewport_width,
viewport_height,
direction,
readonly,
palette,
cx,
&mut elements,
);
elements.extend(self.active_note_table_elements(
&layout,
TablePaintFrame::Note {
transform,
vp_origin,
width: viewport_width,
height: viewport_height,
},
palette,
self.caret_blink_alpha(now_ms),
cx,
));
elements
}
}
@@ -0,0 +1,519 @@
//! Active Note controls for Code toolbars, Image selection/resize handles,
//! and block-level `+ |` drag handles.
use blocksuite_editor::{
block_flow::{FlowBlock, FlowKind, FlowLayout, FlowRect, PAGE_SURFACE_ID},
overlays::{
ADD_BLOCK_BUTTON_GAP, ADD_BLOCK_BUTTON_SIZE, CONTROL_HIT_SIZE, DRAG_HANDLE_SIZE,
DROP_INDICATOR_THICKNESS, ImageResizeSide, OverlayEvent, OverlayScreenTransform,
},
theme::Palette,
};
use blocksuite_playground_doc::read::{BlockContent, PageSnapshot};
use ui::{
AnyElement, ClickEvent, Context, MouseButton, MouseDownEvent, SharedString, div, prelude::*, px,
};
use crate::PlaygroundView;
use super::active_note::{
fully_visible_in_viewport, icon_el, intersects_viewport, place_rect, to_viewport,
};
impl PlaygroundView {
#[allow(clippy::too_many_arguments)]
pub(super) fn push_active_note_code_toolbar(
&self,
block: &FlowBlock,
layout: &FlowLayout,
snapshot: &PageSnapshot,
transform: OverlayScreenTransform,
vp_origin: (f32, f32),
vp_w: f32,
vp_h: f32,
hovered: bool,
readonly: bool,
palette: &Palette,
cx: &mut Context<Self>,
elements: &mut Vec<AnyElement>,
) {
let focused = self.focused_code_block_id(layout) == Some(block.block_id.as_str());
let picker_open = self
.overlays
.code_lang_picker()
.is_some_and(|p| p.block_id == block.block_id)
|| self
.overlays
.code_more_menu()
.is_some_and(|m| m.block_id == block.block_id);
if !hovered && !focused && !picker_open {
return;
}
let code_lang = snapshot
.block(&block.block_id)
.and_then(|n| match &n.content {
BlockContent::Code { language, .. } => Some(language.as_str()),
_ => None,
})
.unwrap_or("Plain Text");
let lang_display = if code_lang.trim().is_empty() {
"Plain Text".to_string()
} else {
code_lang.to_string()
};
let vp_rect = to_viewport(transform, vp_origin, &block.rect());
let pad_x = (12.0 * transform.scale).clamp(6.0, 20.0);
let bar_rect = FlowRect::new(
vp_rect.x + pad_x,
vp_rect.y + 4.0,
(vp_rect.w - 2.0 * pad_x).max(120.0),
28.0,
);
if !intersects_viewport(&bar_rect, vp_w, vp_h) {
return;
}
let bid_lang = block.block_id.clone();
let bid_copy = block.block_id.clone();
let bid_cap = block.block_id.clone();
let bid_more = block.block_id.clone();
let hover_bg = palette.hover;
let btn_bg = palette
.theme
.css_var("--affine-v2-button-secondary")
.unwrap_or(palette.panel);
let more_anchor = FlowRect::new(
bar_rect.right() - 28.0,
bar_rect.y + self.topbar_height(),
28.0,
28.0,
);
let mut lang_btn = div()
.id(SharedString::from(format!("an-code-lang-{bid_lang}")))
.flex_none()
.h(px(28.0))
.px(px(6.0))
.rounded(px(4.0))
.bg(btn_bg)
.flex()
.items_center()
.gap(px(2.0))
.text_size(px(12.0))
.text_color(palette.text_secondary)
.child(lang_display);
if !readonly {
lang_btn = lang_btn
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, _: &ClickEvent, w, cx| {
this.dispatch_overlay(
OverlayEvent::OpenCodeLangPicker(bid_lang.clone()),
w,
cx,
);
}))
.child(icon_el("ArrowDownSmallIcon", 14.0, palette.icon));
}
if fully_visible_in_viewport(&bar_rect, vp_w, vp_h) {
lang_btn = lang_btn.snapshot(
format_args!("{}.toolbar.language", block.snapshot_id()),
Some(PAGE_SURFACE_ID),
);
}
let copy_btn = div()
.id(SharedString::from(format!("an-code-copy-{bid_copy}")))
.flex_none()
.w(px(28.0))
.h(px(28.0))
.rounded(px(4.0))
.bg(btn_bg)
.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(cx.listener(move |this, _: &ClickEvent, w, cx| {
this.dispatch_overlay(OverlayEvent::CopyCode(bid_copy.clone()), w, cx);
}))
.child(icon_el("CopyIcon", 16.0, palette.icon));
let cap_btn = div()
.id(SharedString::from(format!("an-code-cap-{bid_cap}")))
.flex_none()
.w(px(28.0))
.h(px(28.0))
.rounded(px(4.0))
.bg(btn_bg)
.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(cx.listener(move |this, _: &ClickEvent, w, cx| {
this.dispatch_overlay(
OverlayEvent::EditCaption {
block_id: bid_cap.clone(),
},
w,
cx,
);
}))
.child(icon_el("CaptionIcon", 16.0, palette.icon));
let more_btn = div()
.id(SharedString::from(format!("an-code-more-{bid_more}")))
.flex_none()
.w(px(28.0))
.h(px(28.0))
.rounded(px(4.0))
.bg(btn_bg)
.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(cx.listener(move |this, _: &ClickEvent, w, cx| {
this.dispatch_overlay(
OverlayEvent::ToggleCodeMoreMenu {
block_id: bid_more.clone(),
anchor: more_anchor,
},
w,
cx,
);
}))
.child(icon_el("MoreVerticalIcon", 16.0, palette.icon));
let mut bar = place_rect(bar_rect)
.id(SharedString::from(format!(
"an-code-toolbar-{}",
block.block_id
)))
.flex()
.items_center()
.gap(px(4.0))
.child(lang_btn)
.child(div().flex_1())
.child(
div()
.flex()
.items_center()
.gap(px(4.0))
.child(copy_btn)
.when(!readonly, |el| el.child(cap_btn).child(more_btn)),
);
if fully_visible_in_viewport(&bar_rect, vp_w, vp_h) {
bar = bar.snapshot(
format_args!("{}.toolbar", block.snapshot_id()),
Some(PAGE_SURFACE_ID),
);
}
elements.push(bar.into_any_element());
}
#[allow(clippy::too_many_arguments)]
pub(super) fn push_active_note_image_controls(
&self,
block: &FlowBlock,
transform: OverlayScreenTransform,
vp_origin: (f32, f32),
vp_w: f32,
vp_h: f32,
selected: bool,
readonly: bool,
palette: &Palette,
cx: &mut Context<Self>,
elements: &mut Vec<AnyElement>,
) {
let Some(img_local) = block.body.image_box() else {
return;
};
let rect = block.rect();
let img_vp = to_viewport(transform, vp_origin, &img_local.translated(rect.x, rect.y));
if !intersects_viewport(&img_vp, vp_w, vp_h) {
return;
}
let show_frame = selected && block.body.is_resizable_image();
let resizable = show_frame && !readonly;
let bid = block.block_id.clone();
let can_lightbox = block.body.is_resizable_image();
let mut card = place_rect(img_vp)
.id(SharedString::from(format!("an-img-{bid}")))
.cursor_pointer()
.when(show_frame, |el| el.border_2().border_color(palette.brand))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, ev: &ClickEvent, w, cx| {
let event = if ev.click_count() >= 2 && can_lightbox {
OverlayEvent::OpenImageLightbox(bid.clone())
} else {
OverlayEvent::SelectImageBlock(bid.clone())
};
this.dispatch_overlay(event, w, cx);
}));
if fully_visible_in_viewport(&img_vp, vp_w, vp_h) {
card = card
.snapshot(
format_args!("{}.image_card", block.snapshot_id()),
Some(PAGE_SURFACE_ID),
)
.snapshot_focused(selected);
}
elements.push(card.into_any_element());
if resizable {
for (suffix, cx_vp, cy_vp, side, cursor) in [
(
"resize_nw",
img_vp.x,
img_vp.y,
ImageResizeSide::Left,
ui::CursorStyle::ResizeUpLeftDownRight,
),
(
"resize_ne",
img_vp.right(),
img_vp.y,
ImageResizeSide::Right,
ui::CursorStyle::ResizeUpRightDownLeft,
),
(
"resize_sw",
img_vp.x,
img_vp.bottom(),
ImageResizeSide::Left,
ui::CursorStyle::ResizeUpRightDownLeft,
),
(
"resize_se",
img_vp.right(),
img_vp.bottom(),
ImageResizeSide::Right,
ui::CursorStyle::ResizeUpLeftDownRight,
),
] {
let h_rect = FlowRect::new(
(cx_vp - CONTROL_HIT_SIZE * 0.5).round(),
(cy_vp - CONTROL_HIT_SIZE * 0.5).round(),
CONTROL_HIT_SIZE,
CONTROL_HIT_SIZE,
);
let bid = block.block_id.clone();
let knob = div()
.flex_none()
.w(px(10.0))
.h(px(10.0))
.rounded(px(5.0))
.bg(palette.panel)
.border_2()
.border_color(palette.brand);
let mut handle = place_rect(h_rect)
.id(SharedString::from(format!("an-{suffix}-{bid}")))
.flex()
.items_center()
.justify_center()
.cursor(cursor)
.on_mouse_down(
MouseButton::Left,
cx.listener(move |this, ev: &MouseDownEvent, w, cx| {
cx.stop_propagation();
this.dispatch_overlay(
OverlayEvent::ImageResizeStart {
block_id: bid.clone(),
side,
start_x: f32::from(ev.position.x),
},
w,
cx,
);
}),
)
.child(knob);
if fully_visible_in_viewport(&h_rect, vp_w, vp_h) {
handle = handle.snapshot(
format_args!("{}.{suffix}", block.snapshot_id()),
Some(PAGE_SURFACE_ID),
);
}
elements.push(handle.into_any_element());
}
}
}
#[allow(clippy::too_many_arguments)]
pub(super) fn push_active_note_drag_handle(
&self,
layout: &FlowLayout,
transform: OverlayScreenTransform,
vp_origin: (f32, f32),
vp_w: f32,
vp_h: f32,
direction: ui::Direction,
readonly: bool,
palette: &Palette,
cx: &mut Context<Self>,
elements: &mut Vec<AnyElement>,
) {
if readonly {
return;
}
let dragging = self.overlays.dragged_block().is_some();
let handle_block = self
.overlays
.dragged_block()
.or_else(|| self.overlays.hovered_block())
.and_then(|id| layout.block(id));
if let Some(block) = handle_block
&& block.body.kind != FlowKind::Title
{
let center_y = match &block.body.text {
Some(text) if block.body.kind != FlowKind::Code => {
text.y + text.layout.line_height() * 0.5
}
_ => (block.body.height * 0.5).min(18.0),
};
let anchor_x = match direction {
ui::Direction::Ltr => {
block.x
- if block.has_gutter_chevron {
CONTROL_HIT_SIZE
} else {
0.0
}
}
ui::Direction::Rtl => {
block.rect().right()
+ if block.has_gutter_chevron {
CONTROL_HIT_SIZE
} else {
0.0
}
}
};
let anchor_vp = to_viewport(
transform,
vp_origin,
&FlowRect::new(anchor_x, block.y + center_y, 0.0, 0.0),
);
let handle_x = match direction {
ui::Direction::Ltr => (anchor_vp.x - DRAG_HANDLE_SIZE).max(4.0),
ui::Direction::Rtl => anchor_vp.x.min(vp_w - 4.0 - DRAG_HANDLE_SIZE),
};
let handle_rect = FlowRect::new(
handle_x.round(),
(anchor_vp.y - DRAG_HANDLE_SIZE * 0.5).round(),
DRAG_HANDLE_SIZE,
DRAG_HANDLE_SIZE,
);
if intersects_viewport(&handle_rect, vp_w, vp_h) {
if !dragging {
let plus_x = match direction {
ui::Direction::Ltr => {
handle_rect.x - ADD_BLOCK_BUTTON_GAP - ADD_BLOCK_BUTTON_SIZE
}
ui::Direction::Rtl => handle_rect.right() + ADD_BLOCK_BUTTON_GAP,
};
if plus_x >= 4.0 && plus_x + ADD_BLOCK_BUTTON_SIZE <= vp_w - 4.0 {
let plus_rect = FlowRect::new(
plus_x.round(),
(handle_rect.y + (handle_rect.h - ADD_BLOCK_BUTTON_SIZE) * 0.5).round(),
ADD_BLOCK_BUTTON_SIZE,
ADD_BLOCK_BUTTON_SIZE,
);
let add_id = block.block_id.clone();
let hover_bg = palette.hover;
let mut plus = place_rect(plus_rect)
.id(SharedString::from(format!("an-add-block-{add_id}")))
.rounded(px(4.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(cx.listener(move |this, _: &ClickEvent, w, cx| {
this.dispatch_overlay(
OverlayEvent::AddBlockBelow(add_id.clone()),
w,
cx,
);
}))
.child(icon_el("PlusIcon", 14.0, palette.icon));
if fully_visible_in_viewport(&plus_rect, vp_w, vp_h) {
plus = plus
.snapshot("overlay.add_block_button", Some(PAGE_SURFACE_ID))
.snapshot_text(block.block_id.clone());
}
elements.push(plus.into_any_element());
}
}
let bid = block.block_id.clone();
let grip_w = if dragging { 2.0_f32 } else { 4.0_f32 };
let grip_color = if dragging {
palette.icon
} else {
palette.placeholder
};
let mut handle = place_rect(handle_rect)
.id("an-drag-handle")
.flex()
.items_center()
.justify_center()
.cursor_grab()
.on_mouse_down(
MouseButton::Left,
cx.listener(move |this, ev: &MouseDownEvent, w, cx| {
cx.stop_propagation();
this.dispatch_overlay(
OverlayEvent::DragHandlePress {
block_id: bid.clone(),
anchor: (f32::from(ev.position.x), f32::from(ev.position.y)),
},
w,
cx,
);
}),
)
.child(
div()
.flex_none()
.w(px(grip_w))
.h(px(12.0))
.rounded(px(1.0))
.bg(grip_color),
);
if fully_visible_in_viewport(&handle_rect, vp_w, vp_h) {
handle = handle
.snapshot("overlay.drag_handle", Some(PAGE_SURFACE_ID))
.snapshot_focused(dragging)
.snapshot_text(block.block_id.clone());
}
elements.push(handle.into_any_element());
}
}
if let Some(slot) = self.overlays.tree_drop_target()
&& dragging
{
let line_world = FlowRect::new(
slot.indicator_world_x,
slot.indicator_world_y - DROP_INDICATOR_THICKNESS * 0.5,
slot.indicator_world_width.max(0.0),
DROP_INDICATOR_THICKNESS,
);
let line_vp = to_viewport(transform, vp_origin, &line_world);
if intersects_viewport(&line_vp, vp_w, vp_h) {
elements.push(
place_rect(line_vp)
.bg(palette.brand)
.snapshot("overlay.drop_indicator", Some(PAGE_SURFACE_ID))
.into_any_element(),
);
}
}
}
}
+23 -5
View File
@@ -1,5 +1,9 @@
mod active_note;
mod active_note_controls;
mod topbar;
pub(crate) use active_note::ActiveNoteFlowCache;
use ui::{AnyElement, FontWeight, MouseButton, Window, canvas, div, point, prelude::*, px, size};
use crate::{
@@ -288,9 +292,19 @@ impl PlaygroundView {
self.step_edgeless_fling(now_ms, window);
self.step_edgeless_camera_transition(now_ms, vp_size, window);
self.flow.database_state.mobile_readonly = self.database_readonly;
self.flow.database_state.clock_ms = self.local_calendar_now(cx).0;
self.edgeless
.caption_draft
.clone_from(&self.flow.caption_draft);
self.edgeless
.image_resize_preview
.clone_from(&self.flow.image_resize_preview);
if let Some((note_id, true)) = self.edgeless.authoring.editing_spatial_block() {
let note_id = note_id.to_string();
self.edgeless
.sync_note_database_state(&note_id, &self.flow.database_state);
}
let render_snapshot = self
.preedit_snapshot()
.map(Rc::new)
@@ -346,7 +360,7 @@ impl PlaygroundView {
};
edgeless::prepare_edgeless_scene(&mut self.edgeless, &prep_input, window)
};
let (zoom_controls, toolbar) = self.step_edgeless_controls_and_toolbar(
let (zoom_controls, mut toolbar) = self.step_edgeless_controls_and_toolbar(
vp_origin,
vp_size,
viewport_width,
@@ -354,6 +368,9 @@ impl PlaygroundView {
window,
cx,
);
if self.active_note_touch_table_bar(viewport_width) {
toolbar = None;
}
let doc_dir: &dyn crate::directory::WorkspaceDocDirectory = self
.custom_doc_directory
.as_deref()
@@ -404,6 +421,8 @@ impl PlaygroundView {
.absolute()
.size_full()
});
let active_note_controls =
self.render_active_note_controls(palette, viewport_width, viewport_height, window, cx);
let caption_elements =
self.edgeless_caption_elements(window, palette, self.caret_blink_alpha(now_ms));
@@ -451,8 +470,9 @@ impl PlaygroundView {
cx.listener(Self::on_edgeless_pan_start),
)
.child(layer)
.children(caption_elements)
.children(input_overlay)
.children(active_note_controls)
.children(caption_elements)
.into_any_element()
}
}
@@ -551,9 +571,7 @@ impl ui::Render for PlaygroundView {
#[cfg(target_arch = "wasm32")]
self.reconcile_wasm_html_embeds(viewport_width, viewport_height);
let mut popovers = Vec::new();
if self.mode == PlaygroundMode::Page
&& let Some(layout) = self.flow_layout()
{
if let Some((_, layout, _)) = self.active_overlay_target() {
popovers.extend(self.database_popover_elements(&layout, window, cx));
popovers.extend(self.database_dnd_overlay_elements(window, cx));
}
@@ -7,7 +7,7 @@ use blocksuite_playground_doc::{
schema::DatabaseCellSpec,
session::DatabaseRowGroupUpdate,
};
use ui::Context;
use ui::{Context, CursorStyle};
use crate::PlaygroundView;
@@ -98,6 +98,20 @@ pub(crate) enum DatabaseDragState {
},
}
impl DatabaseDragState {
pub(super) fn cursor(&self) -> CursorStyle {
match self {
Self::ColumnResize { .. }
| Self::ProgressScrub { .. }
| Self::CalendarResize { .. } => CursorStyle::ResizeLeftRight,
Self::CalendarReschedule { .. }
| Self::KanbanMoveCard { .. }
| Self::TableRowReorder { .. }
| Self::TableColumnReorder { .. } => CursorStyle::ClosedHand,
}
}
}
impl PlaygroundView {
pub(super) fn commit_grouped_database_row_move(
&mut self,
@@ -1,11 +1,12 @@
//! Screen-space geometry, IME preedit snapshot patching, pointer hit-testing, and first-cell
//! focus helpers for [`super::DatabaseInlineSession`].
use std::ops::Range;
use std::{ops::Range, rc::Rc};
use blocksuite_editor::{
block_flow::FlowRect,
block_flow::{FlowBlock, FlowLayout, FlowRect},
database::{self, initial_cell_draft},
overlays::OverlayScreenTransform,
theme::TYPOGRAPHY,
};
use blocksuite_playground_doc::{
@@ -54,23 +55,13 @@ impl PlaygroundView {
where
F: Fn(&database::DatabaseAuthoringHitKind) -> bool,
{
let layout = self.flow_layout()?;
let block = layout.block(block_id)?;
let geom = self.current_page_geometry(f32::from(window.viewport_size().width));
let scroll_x = block
.body
.code_scroll
.map_or(0.0, |cs| self.overlays.code_scroll_x_for(block_id, cs));
let hit = self
.flow
.database_authoring_hits(block_id)
.iter()
.find(|h| pred(&h.kind))?;
let origin = self.canvas_origin();
let sx = f32::from(origin.x) + geom.column_x + block.x + (hit.rect.x + hit.rect.w * 0.5)
- if hit.scrolls_x { scroll_x } else { 0.0 };
let sy = f32::from(origin.y) + block.y + (hit.rect.y + hit.rect.h * 0.5) - self.scroll_y;
Some((sx, sy))
let r = self.database_local_rect_to_screen(block_id, hit.rect, hit.scrolls_x, window)?;
Some((r.x + r.w * 0.5, r.y + r.h * 0.5))
}
/// Splice any active database `LiveRichCell` IME preedit into a cloned snapshot via
@@ -177,6 +168,36 @@ impl PlaygroundView {
)
}
/// Flow layout holding the database blocks and its screen mapping: the Page column, or the
/// edited Edgeless Note through the camera.
pub(crate) fn database_flow_transform(
&self,
window: &Window,
) -> Option<(Rc<FlowLayout>, OverlayScreenTransform)> {
let (_, layout, transform) = self.active_overlay_target()?;
let transform = transform.unwrap_or_else(|| {
let (origin, canvas_size) = self.canvas_rect(window);
let geom = self.current_page_geometry(f32::from(canvas_size.width));
OverlayScreenTransform {
origin: (
f32::from(origin.x) + geom.column_x,
f32::from(origin.y) - self.scroll_y,
),
pivot: (0.0, 0.0),
scale: 1.0,
rotate_deg: 0.0,
}
});
Some((layout, transform))
}
fn database_scroll_x(&self, block: &FlowBlock, scrolls_x: bool) -> f32 {
match block.body.code_scroll {
Some(cs) if scrolls_x => self.overlays.code_scroll_x_for(&block.block_id, cs),
_ => 0.0,
}
}
pub(crate) fn database_local_rect_to_screen(
&self,
block_id: &str,
@@ -184,24 +205,10 @@ impl PlaygroundView {
scrolls_x: bool,
window: &Window,
) -> Option<FlowRect> {
let layout = self.flow_layout()?;
let (layout, t) = self.database_flow_transform(window)?;
let block = layout.block(block_id)?;
let scroll_x = if scrolls_x {
block
.body
.code_scroll
.map_or(0.0, |cs| self.overlays.code_scroll_x_for(block_id, cs))
} else {
0.0
};
let (origin, canvas_size) = self.canvas_rect(window);
let geom = self.current_page_geometry(f32::from(canvas_size.width));
Some(FlowRect::new(
f32::from(origin.x) + geom.column_x + block.x + local_rect.x - scroll_x,
f32::from(origin.y) + block.y + local_rect.y - self.scroll_y,
local_rect.w,
local_rect.h,
))
let scroll_x = self.database_scroll_x(block, scrolls_x);
Some(t.rect_to_screen(&local_rect.translated(block.x - scroll_x, block.y)))
}
pub(super) fn table_rect_scrolls(&self, block_id: &str, rect: FlowRect) -> bool {
@@ -222,22 +229,20 @@ impl PlaygroundView {
window: &Window,
) -> Option<FlowRect> {
let raw = self.database_local_rect_to_screen(block_id, local_rect, scrolls_x, window)?;
let layout = self.flow_layout()?;
let (layout, t) = self.database_flow_transform(window)?;
let block = layout.block(block_id)?;
let geom = self.current_page_geometry(f32::from(window.viewport_size().width));
let (vis_left, vis_right) = if let Some(cs) = block.body.code_scroll {
(
geom.column_x + block.x + if scrolls_x { cs.area.x } else { 8.0 },
geom.column_x + block.x + cs.area.right(),
)
} else {
(
geom.column_x + block.x + 8.0,
geom.column_x + block.x + (block.body.width - 8.0).max(9.0),
)
let (vis_left, vis_right) = match block.body.code_scroll {
Some(cs) => (if scrolls_x { cs.area.x } else { 8.0 }, cs.area.right()),
None => (8.0, (block.body.width - 8.0).max(9.0)),
};
let left = raw.x.max(vis_left);
let right = raw.right().min(vis_right);
let vis = t.rect_to_screen(&FlowRect::new(
block.x + vis_left,
block.y,
vis_right - vis_left,
0.0,
));
let left = raw.x.max(vis.x);
let right = raw.right().min(vis.right());
(right > left).then(|| FlowRect::new(left, raw.y, right - left, raw.h))
}
@@ -322,7 +327,7 @@ impl PlaygroundView {
_ => {}
}
}
let layout = self.flow_layout()?;
let (_, layout, _) = self.active_overlay_target()?;
if session.target.is_popover_field() {
let (_, overlay) = self.database_popover_overlay(&layout, w)?;
return Some((overlay.text_input_rect?, POPOVER_FIELD_FONT));
@@ -354,26 +359,16 @@ impl PlaygroundView {
_ => None,
};
if let Some((target_row, target_col)) = target_ids
&& let Some(layout) = self.flow_layout()
&& let Some((layout, t)) = self.database_flow_transform(w)
&& let Some(block) = layout.block(block_id)
&& let Some((_, scrolls_x)) = self.flow.database_active_cell_rect(block_id)
&& let Some(hit) = self.flow.database_active_cell_rich(block_id)
&& hit.row_id == target_row
&& hit.column_id == target_col
{
let scroll_x = if scrolls_x {
block
.body
.code_scroll
.map_or(0.0, |cs| self.overlays.code_scroll_x_for(block_id, cs))
} else {
0.0
};
let (origin, canvas_size) = self.canvas_rect(w);
let geom = self.current_page_geometry(f32::from(canvas_size.width));
let local_x =
f32::from(p.x) - f32::from(origin.x) - geom.column_x - block.x + scroll_x;
let local_y = f32::from(p.y) - f32::from(origin.y) + self.scroll_y - block.y;
let (fx, fy) = t.screen_to_local(f32::from(p.x), f32::from(p.y));
let local_x = fx - block.x + self.database_scroll_x(block, scrolls_x);
let local_y = fy - block.y;
return hit.rect.contains(local_x, local_y).then(|| {
hit.hit_text(local_x, local_y, &session.anchored.input.display_text())
.utf16_offset as usize
@@ -429,28 +424,20 @@ impl PlaygroundView {
let session = self.database_input.as_ref()?;
if self.database_record_sheet.is_none() && !session.target.is_popover_field() {
let block_id = session.target.block_id();
if let Some(layout) = self.flow_layout()
if let Some((layout, t)) = self.database_flow_transform(w)
&& let Some(block) = layout.block(block_id)
&& let Some((_, scrolls_x)) = self.flow.database_active_cell_rect(block_id)
&& let Some(hit) = self.flow.database_active_cell_rich(block_id)
{
let scroll_x = if scrolls_x {
block
.body
.code_scroll
.map_or(0.0, |cs| self.overlays.code_scroll_x_for(block_id, cs))
} else {
0.0
};
let (origin, canvas_size) = self.canvas_rect(w);
let geom = self.current_page_geometry(f32::from(canvas_size.width));
let lh = hit.text.line_height();
let (cx_off, line) = hit.text.caret(r.start);
let wx = block.x + hit.text_origin.0 - scroll_x + cx_off;
let wy = block.y + hit.text_origin.1 + line as f32 * lh;
let sx = f32::from(origin.x) + geom.column_x + wx;
let sy = f32::from(origin.y) + wy - self.scroll_y;
return Some(FlowRect::new(sx, sy, 2.0, lh).bounds(point(px(0.0), px(0.0))));
let caret = FlowRect::new(
block.x + hit.text_origin.0 - self.database_scroll_x(block, scrolls_x) + cx_off,
block.y + hit.text_origin.1 + line as f32 * lh,
2.0,
lh,
);
return Some(t.rect_to_screen(&caret).bounds(point(px(0.0), px(0.0))));
}
}
let (rect, (font_size, weight)) = self.database_inline_screen_box(w)?;
@@ -16,10 +16,7 @@ use ui::{Context, CursorStyle, Window};
use crate::{PlaygroundMode, PlaygroundView};
use super::{
DatabaseDragState,
dnd_table::{collect_table_column_rects, collect_table_row_rects},
};
use super::dnd_table::{collect_table_column_rects, collect_table_row_rects};
/// Hovered sub-control on a Table row.
#[derive(Clone, Debug, PartialEq)]
@@ -192,18 +189,6 @@ pub(crate) fn link_cell_edit_rect(cell_rect: FlowRect) -> FlowRect {
)
}
fn active_drag_cursor(drag: &DatabaseDragState) -> CursorStyle {
match drag {
DatabaseDragState::ColumnResize { .. }
| DatabaseDragState::ProgressScrub { .. }
| DatabaseDragState::CalendarResize { .. } => CursorStyle::ResizeLeftRight,
DatabaseDragState::CalendarReschedule { .. }
| DatabaseDragState::KanbanMoveCard { .. }
| DatabaseDragState::TableRowReorder { .. }
| DatabaseDragState::TableColumnReorder { .. } => CursorStyle::ClosedHand,
}
}
impl PlaygroundView {
/// Active mouse cursor requested by the database hover or drag state (Page mode).
pub(crate) fn database_hover_cursor(&self) -> Option<CursorStyle> {
@@ -211,7 +196,7 @@ impl PlaygroundView {
return None;
}
if let Some(drag) = &self.database_drag {
return Some(active_drag_cursor(drag));
return Some(drag.cursor());
}
self.database_hover.cursor
}
@@ -258,10 +243,12 @@ impl PlaygroundView {
return;
};
let (origin, canvas_size) = self.canvas_rect(window);
if self.mode != PlaygroundMode::Page
|| self.database_hover_suppressed_by_modal_or_menu()
if self.database_hover_suppressed_by_modal_or_menu()
|| pos_y < f32::from(origin.y)
|| self.overlays.shields_point(pos_x, pos_y)
|| {
let (x, y) = self.point_in_view(ui::point(ui::px(pos_x), ui::px(pos_y)));
self.overlays.shields_point(x, y)
}
|| self
.doc_panel_screen_rect(window)
.is_some_and(|r| r.contains(pos_x, pos_y))
@@ -270,7 +257,7 @@ impl PlaygroundView {
return;
}
if let Some(drag) = &self.database_drag {
let next_cursor = Some(active_drag_cursor(drag));
let next_cursor = Some(drag.cursor());
if self.database_hover.target.is_some() || self.database_hover.cursor != next_cursor {
self.database_hover.target = None;
self.database_hover.cursor = next_cursor;
@@ -279,7 +266,7 @@ impl PlaygroundView {
return;
}
let Some(layout) = self.flow_layout() else {
let Some((_, layout, _)) = self.active_overlay_target() else {
self.clear_database_hover(cx);
return;
};
@@ -315,6 +302,10 @@ impl PlaygroundView {
return;
}
if self.mode != PlaygroundMode::Page {
self.clear_database_hover(cx);
return;
}
// 2. Locate the database block under `(world_x, world_y)`.
let geom = self.current_page_geometry(f32::from(canvas_size.width));
let world_x = pos_x - f32::from(origin.x) - geom.column_x;
@@ -110,11 +110,13 @@ pub(crate) enum RecordSlot<'a> {
impl PlaygroundView {
/// Unified read-only gate for all `affine:database` write and authoring controls:
/// true when either database-level readonly (mobile Stage-1) or Page-level readonly is active.
/// true when database-level readonly (mobile Stage-1), Page-level readonly, or Edgeless
/// readonly is active.
pub(crate) fn is_database_write_readonly(&self) -> bool {
self.database_readonly
|| self.flow.database_state.mobile_readonly
|| (self.mode == crate::PlaygroundMode::Page && self.page_readonly)
|| (self.mode == crate::PlaygroundMode::Edgeless && self.edgeless_readonly)
}
/// Dismiss open database popovers and drag previews on every database block except `keep_block`.
@@ -198,14 +200,10 @@ impl PlaygroundView {
pos_y: f32,
window: &Window,
) -> Option<(f32, f32)> {
let layout = self.flow_layout()?;
let (_, canvas_size) = self.canvas_rect(window);
let geometry = self.current_page_geometry(f32::from(canvas_size.width));
let (world_x, world_y) =
self.window_to_page_world(ui::point(ui::px(pos_x), ui::px(pos_y)), geometry.column_x);
let block = layout.block(block_id)?;
let r = block.rect();
Some((world_x - r.x, world_y - r.y))
let (layout, transform) = self.database_flow_transform(window)?;
let (fx, fy) = transform.screen_to_local(pos_x, pos_y);
let r = layout.block(block_id)?.rect();
Some((fx - r.x, fy - r.y))
}
pub(super) fn sync_after_database_mutation(
@@ -465,6 +465,7 @@ impl PlaygroundView {
let bounds = overlay.bounds;
let prims = overlay.prims;
let palette = self.theme.palette();
let (dx, dy) = self.view_window_offset();
let mut out = Vec::new();
// Over a record peek, a press outside the popover closes only the popover, never the peek.
@@ -505,10 +506,17 @@ impl PlaygroundView {
{
let mut shield = div()
.absolute()
.left(px(rect.x))
.top(px(rect.y))
.left(px(rect.x - dx))
.top(px(rect.y - dy))
.w(px(rect.w))
.h(px(rect.h))
.occlude()
.when_some(self.database_hover.cursor, |el, cursor| el.cursor(cursor))
.on_mouse_move(cx.listener(|this, event: &ui::MouseMoveEvent, window, cx| {
let x = f32::from(event.position.x);
let y = f32::from(event.position.y);
this.update_database_hover(Some((x, y)), window, cx);
}))
.on_mouse_down(
ui::MouseButton::Left,
cx.listener(|this, event: &ui::MouseDownEvent, window, cx| {
@@ -521,15 +529,12 @@ impl PlaygroundView {
cx.stop_propagation();
}
}),
);
if self.database_record_sheet.is_some() {
shield = shield.occlude().on_scroll(cx.listener(
|this, event: &ui::ScrollEvent, w, cx| {
this.try_scroll_database_popover(event, w, cx);
cx.stop_propagation();
},
));
}
)
.on_scroll(cx.listener(|this, event: &ui::ScrollEvent, w, cx| {
this.try_scroll_database_popover(event, w, cx);
this.refresh_database_hover(w, cx);
cx.stop_propagation();
}));
if idx == 0 {
shield = shield.snapshot("overlay.database_popover", None);
}
@@ -645,7 +650,7 @@ impl PlaygroundView {
&session.anchored.input,
&session.scroll_x,
&session.laid_cache,
input_rect,
input_rect.translated(-dx, -dy),
POPOVER_FIELD_FONT.0,
POPOVER_FIELD_FONT.1,
&palette,
@@ -667,7 +672,7 @@ impl PlaygroundView {
window: &mut Window,
cx: &mut Context<Self>,
) -> bool {
let Some(layout) = self.flow_layout() else {
let Some((_, layout, _)) = self.active_overlay_target() else {
return false;
};
let Some((block_id, overlay)) = self.database_popover_overlay(&layout, window) else {
@@ -1,12 +1,18 @@
use crate::PlaygroundView;
use blocksuite_editor::{
block_flow::FlowLayout,
database::{self, DatabasePopoverOverlay, layout_database_popover_overlay},
block_flow::{FlowLayout, FlowRect},
database::{self, DatabasePopoverOverlay, DatabasePrim, layout_database_popover_overlay},
};
use blocksuite_playground_doc::read::BlockContent;
use ui::Window;
use ui::{Pixels, Point, Window, point, px};
impl PlaygroundView {
/// Compute the active screen-space [`DatabasePopoverOverlay`] (`ColumnMenu`, `SelectPicker`,
pub(crate) fn point_in_view(&self, window_pt: Point<Pixels>) -> (f32, f32) {
let (x, y) = self.view_window_offset();
(f32::from(window_pt.x) - x, f32::from(window_pt.y) - y)
}
/// Compute the active window-space [`DatabasePopoverOverlay`] (`ColumnMenu`, `SelectPicker`,
/// or `ToolbarPanel`) if any writable database block currently has one open.
pub(crate) fn database_popover_overlay(
&self,
@@ -15,7 +21,15 @@ impl PlaygroundView {
) -> Option<(String, DatabasePopoverOverlay)> {
let block_id = self.active_database_authoring_block()?;
let ui_state = self.flow.database_state.state_for(&block_id);
let block = layout.block(&block_id)?;
// In an Edgeless Active Note the database lives in the Note flow, mapped by the camera.
let note = (self.mode == crate::PlaygroundMode::Edgeless)
.then(|| self.active_overlay_target())
.flatten()
.and_then(|(_, note_layout, t)| Some((note_layout, t?)));
let block = match &note {
Some((note_layout, _)) => note_layout.block(&block_id)?,
None => layout.block(&block_id)?,
};
let data =
self.snapshot
.as_ref()
@@ -28,11 +42,19 @@ impl PlaygroundView {
let geom = self.current_page_geometry(f32::from(canvas_size.width));
let paint_scroll_y =
blocksuite_editor::scroll::snap_device_pixel(self.scroll_y, window.scale_factor());
let block_screen_origin = (geom.column_x + block.x, topbar + block.y - paint_scroll_y);
let scale = note.as_ref().map_or(1.0, |(_, t)| t.scale);
let block_screen_origin = match &note {
Some((_, t)) => {
let s = t.rect_to_screen(&block.rect());
self.point_in_view(point(px(s.x), px(s.y)))
}
None => (geom.column_x + block.x, topbar + block.y - paint_scroll_y),
};
let scroll_x = block
.body
.code_scroll
.map_or(0.0, |cs| self.overlays.code_scroll_x_for(&block_id, cs));
.map_or(0.0, |cs| self.overlays.code_scroll_x_for(&block_id, cs))
* scale;
let record_anchor = self.database_record_sheet.as_ref().and_then(|sheet| {
if sheet.block_id != block_id {
return None;
@@ -54,14 +76,23 @@ impl PlaygroundView {
scrolls_x: false,
})
});
let anchor = record_anchor.or_else(|| self.flow.database_popover_anchor(&block_id));
let anchor = record_anchor.or_else(|| {
let mut anchor = self.flow.database_popover_anchor(&block_id)?;
anchor.rect = FlowRect::new(
anchor.rect.x * scale,
anchor.rect.y * scale,
anchor.rect.w * scale,
anchor.rect.h * scale,
);
Some(anchor)
});
let overflow_tabs = self.flow.database_overflow_tabs(&block_id);
let offset_at = self.utc_offset_resolver();
let overlay = layout_database_popover_overlay(
let mut overlay = layout_database_popover_overlay(
data,
&ui_state,
block_screen_origin,
block.body.width,
block.body.width * scale,
scroll_x,
anchor,
overflow_tabs,
@@ -76,6 +107,31 @@ impl PlaygroundView {
&self.page_titles,
window,
)?;
// Clamp placement within the view, then put every hit and paint primitive in the
// same window coordinates as GPUI mouse events, touch gestures, and IME bounds.
let (dx, dy) = self.view_window_offset();
if (dx, dy) != (0.0, 0.0) {
let to_window = |rect: FlowRect| rect.translated(dx, dy);
overlay.bounds = to_window(overlay.bounds);
overlay.submenu_bounds = overlay.submenu_bounds.map(to_window);
overlay.text_input_rect = overlay.text_input_rect.map(to_window);
for hit in &mut overlay.hits {
hit.rect = to_window(hit.rect);
}
for prim in &mut overlay.prims {
match prim {
DatabasePrim::Quad { rect, .. }
| DatabasePrim::Icon { rect, .. }
| DatabasePrim::Chevron { rect, .. } => *rect = to_window(*rect),
DatabasePrim::Text { x, y, clip, .. }
| DatabasePrim::Rich { x, y, clip, .. } => {
*x += dx;
*y += dy;
*clip = clip.map(to_window);
}
}
}
}
Some((block_id, overlay))
}
}
@@ -0,0 +1,605 @@
//! End-to-end tests for databases inside an Edgeless Active Note: a view switch repaints the
//! Note and moves its hits, the shared Page flow survives Page and Edgeless round trips, and a
//! column resize under zoom writes back while an open popover keeps the blocks under it
//! unhovered. In an embedded Page or Active Note, a Status picker takes window input.
use blocksuite_editor::{
block_flow::FlowRect,
database::{DatabaseAuthoringHitKind, DatabaseHitKind},
};
use blocksuite_playground_doc::read::BlockContent;
use ui::{AppContext, Modifiers, div, point, prelude::*, px};
use y_octo::{Any, SessionValue};
use crate::{
HOME_PAGE_ID, PlaygroundMode, PlaygroundOptions, PlaygroundTheme, PlaygroundView,
showcase::seed_showcase_doc,
};
use super::{
active_note_interaction_tests::{
TestHandles, click_pt, enter_note_edit, first_note_id, is_editing_note, mouse,
spawn_edgeless_view, undo,
},
edgeless_canvas_media_tests::{frame, save_evidence},
};
const DB: &str = "showcase-database";
struct EmbeddedDatabaseHost {
editor: ui::Entity<PlaygroundView>,
origin: (f32, f32),
}
impl ui::Render for EmbeddedDatabaseHost {
fn render(&mut self, _: &mut ui::Window, _: &mut ui::Context<Self>) -> impl IntoElement {
div().relative().size_full().child(
div()
.absolute()
.left(px(self.origin.0))
.top(px(self.origin.1))
.w(px(1040.0))
.h(px(714.0))
.child(self.editor.clone()),
)
}
}
#[test]
fn embedded_database_status_picker_scrolls_and_selects_with_one_undo() {
const ROW: &str = "showcase-db-row-1";
const COLUMN: &str = "col-status";
const OPTION: &str = "opt-todo";
let mut reference = None;
for (mode, origin, scrollable) in [
(PlaygroundMode::Edgeless, (0.0, 0.0), false),
(PlaygroundMode::Edgeless, (240.0, 86.0), false),
(PlaygroundMode::Page, (240.0, 86.0), true),
(PlaygroundMode::Edgeless, (240.0, 86.0), true),
] {
let mut doc = seed_showcase_doc().unwrap();
if scrollable {
let page = doc.workspace.page_mut(HOME_PAGE_ID).unwrap();
for i in 0..12 {
page.upsert_database_select_option(
DB,
COLUMN,
&format!("status-{i}"),
&format!("Status {i}"),
"red",
9_000,
)
.unwrap();
}
}
let platform = ui::HeadlessPlatform::new(1440, 900, 1.0);
let app = ui::Application::with_platform(platform.clone()).run_embedded(|cx| {
crate::register_bundled_fonts(cx).unwrap();
});
let win = app.update(|cx| {
let bounds = ui::Bounds::new(point(px(0.0), px(0.0)), ui::size(px(1440.0), px(900.0)));
let options = ui::WindowOptions {
window_bounds: Some(ui::WindowBounds::Windowed(bounds)),
..Default::default()
};
cx.open_window(options, |_, cx| {
let editor = cx.new(|cx| {
let mut view = PlaygroundView::with_options(
PlaygroundOptions {
mode,
hide_chrome: true,
..Default::default()
},
cx,
);
view.set_document(doc, cx);
view
});
cx.new(|_| EmbeddedDatabaseHost { editor, origin })
})
.unwrap()
});
let hw = platform.windows().into_iter().next().unwrap();
let editor = app.update(|cx| win.read(cx).unwrap().editor.clone());
let draw = || {
hw.request_frame();
app.update(|cx| {
win.update(cx, |_, w, _| w.frame_snapshot().clone())
.unwrap()
})
};
draw();
draw();
let note_id = "showcase-note";
app.update(|cx| {
win.update(cx, |_, w, cx| {
editor.update(cx, |view, cx| {
assert_eq!(view.view_window_offset(), origin);
if mode == PlaygroundMode::Edgeless {
view.set_edgeless_camera(-80.0, -60.0, 1.0, cx);
assert!(view.edgeless_begin_inline_edit(note_id, w, cx));
} else {
view.scroll_y = view.flow_layout().unwrap().block(DB).unwrap().y - 80.0;
cx.notify();
}
});
})
.unwrap();
});
draw();
if mode == PlaygroundMode::Edgeless {
app.update(|cx| {
editor.update(cx, |view, cx| {
let layout = view.flow_layout().unwrap();
let note = view
.edgeless
.authoring
.painted_items
.iter()
.find(|item| item.id == note_id)
.unwrap()
.rect;
view.set_edgeless_camera(
note.x - 60.0,
note.y + layout.block(DB).unwrap().y - 80.0,
1.0,
cx,
);
});
});
draw();
}
let cell =
app.update(|cx| {
win.update(cx, |_, w, cx| {
editor.read(cx).database_authoring_hit_screen_center(DB, w, |kind| {
matches!(kind, DatabaseAuthoringHitKind::EditCell { row_id, column_id, .. }
if row_id == ROW && column_id == COLUMN)
})
})
.unwrap()
.expect("Status cell")
});
let read_status = || {
app.update(|cx| {
let bytes = editor.read(cx).page().unwrap().encode_update_v1().unwrap();
let mut reopened =
blocksuite_playground_doc::session::PageDocSession::new(HOME_PAGE_ID, 918)
.unwrap();
reopened.apply_remote_update_v1(&bytes).unwrap();
let snapshot = reopened.read_page_snapshot().unwrap();
let BlockContent::Database(db) = &snapshot.block(DB).unwrap().content else {
unreachable!();
};
db.cells[&(ROW.into(), COLUMN.into())]
.as_str()
.unwrap()
.to_owned()
})
};
assert_eq!(read_status(), "opt-doing");
click_pt(&platform, &hw, cell.0, cell.1, 1, Modifiers::default());
let rendered = draw().elements["overlay.database_popover"].bounds;
if scrollable {
let (x, y) = super::active_note_interaction_tests::center(&rendered);
for (delta, expected_scrolled) in [(-96.0, true), (96.0, false)] {
hw.dispatch_input(ui::PlatformInput::Scroll(ui::ScrollEvent {
position: point(px(x), px(y)),
delta: ui::ScrollDelta::Pixels(point(px(0.0), px(delta))),
..Default::default()
}));
draw();
let scroll = app.update(|cx| {
editor
.read(cx)
.flow
.database_state
.state_for(DB)
.authoring
.select_scroll_y
});
assert_eq!(scroll > 0.0, expected_scrolled, "{mode:?}");
}
}
let (x, y) = app.update(|cx| {
win.update(cx, |_, w, cx| {
let view = editor.read(cx);
let (_, overlay) = view.database_popover_overlay(&view.flow_layout().unwrap(), w).unwrap();
assert_eq!((overlay.bounds.x, overlay.bounds.y), (rendered.x, rendered.y));
let option = overlay.hits.iter().find(|hit| {
matches!(&hit.kind, DatabaseAuthoringHitKind::SelectToggleOption { option_id, .. } if option_id == OPTION)
}).unwrap().rect;
(
rendered.x + (option.x - overlay.bounds.x) + option.w * 0.5,
rendered.y + (option.y - overlay.bounds.y) + option.h * 0.5,
)
}).unwrap()
});
if !scrollable {
let image = app
.update(|cx| win.update(cx, |_, w, _| w.render_to_image()))
.unwrap()
.unwrap();
if let Ok(dir) = std::env::var("EDGELESS_EVIDENCE_DIR") {
let file = std::path::Path::new(&dir).join(format!("after-pane-{}.png", origin.0));
image.save(file).unwrap();
}
let crop = image::imageops::crop_imm(
&image,
rendered.x as u32 + 8,
rendered.y as u32 + 8,
rendered.width as u32 - 16,
rendered.height as u32 - 16,
)
.to_image();
let point = (x - origin.0, y - origin.1);
if let Some((reference_point, reference_crop)) = &reference {
assert_eq!(point, *reference_point);
assert!(crop == *reference_crop, "painted picker follows the pane");
} else {
reference = Some((point, crop));
}
eprintln!(
"pane {origin:?}: picker ({}, {}), option ({x}, {y})",
rendered.x, rendered.y
);
}
mouse(&hw, &platform, "move", x, y);
assert_eq!(
app.update(|cx| editor.read(cx).database_hover.cursor),
Some(ui::CursorStyle::PointingHand)
);
click_pt(&platform, &hw, x, y, 1, Modifiers::default());
assert_eq!(read_status(), OPTION, "{mode:?}");
app.update(|cx| {
editor.update(cx, |view, cx| {
view.page_mut().unwrap().undo().unwrap();
view.refresh_document();
cx.notify();
});
});
assert_eq!(read_status(), "opt-doing", "{mode:?}");
}
}
/// Edit Note `note_id` at `zoom` with the showcase database in view.
fn edit_database_note_at(handles: &TestHandles, note_id: &str, zoom: f32) {
let (platform, app, win, hw) = handles;
enter_note_edit(app, *win, hw, platform, note_id, (-80.0, -60.0), zoom);
app.update(|cx| {
win.update(cx, |v, _, cx| {
let (_, layout, _) = v.active_overlay_target().unwrap();
let db_y = layout.block(DB).unwrap().y;
let items = &v.edgeless.authoring.painted_items;
let rect = items.iter().find(|i| i.id == note_id).unwrap().rect;
v.set_edgeless_camera(rect.x - 60.0, rect.y + db_y - 80.0 / zoom, zoom, cx);
})
.unwrap();
});
platform.run_until_parked();
let _ = frame(app, *win, hw);
}
/// Edit the showcase Note, `note_width` wide, at `zoom` with its database in view.
fn edit_database_note_of(note_width: Option<f32>, zoom: f32) -> (TestHandles, String) {
let mut doc = seed_showcase_doc().unwrap();
if let Some(w) = note_width {
let page = doc.workspace.page_mut(HOME_PAGE_ID).unwrap();
let xywh = SessionValue::Any(Any::String(format!("[0,0,{w},1180]")));
page.set_block_prop("showcase-note", "prop:xywh", xywh, 9_000)
.unwrap();
}
let handles = spawn_edgeless_view(doc, PlaygroundTheme::Light);
let note_id = first_note_id(&handles.1, handles.2);
edit_database_note_at(&handles, &note_id, zoom);
(handles, note_id)
}
fn edit_database_note(zoom: f32) -> (TestHandles, String) {
edit_database_note_of(None, zoom)
}
/// Screen center of the first database view hit matching `pred`.
fn database_hit_screen(
app: &ui::ApplicationHandle,
win: ui::WindowHandle<PlaygroundView>,
pred: impl Fn(&DatabaseHitKind) -> bool,
) -> Option<(f32, f32)> {
app.update(|cx| {
let v = win.read(cx).unwrap();
let (_, layout, transform) = v.active_overlay_target()?;
let b = layout.block(DB)?;
let hit = v.database_hits(DB).iter().find(|h| pred(&h.kind))?;
let s = transform?.rect_to_screen(&hit.rect.translated(b.x, b.y));
Some((s.x + s.w * 0.5, s.y + s.h * 0.5))
})
}
/// Height and screen rect of the database block the canvas paints in the edited Note.
fn painted_database(
app: &ui::ApplicationHandle,
win: ui::WindowHandle<PlaygroundView>,
) -> (f32, FlowRect) {
app.update(|cx| {
let v = win.read(cx).unwrap();
let (_, layout, transform) = v.active_overlay_target().unwrap();
let r = layout.block(DB).unwrap().rect();
(r.h, transform.unwrap().rect_to_screen(&r))
})
}
fn rendered(
app: &ui::ApplicationHandle,
win: ui::WindowHandle<PlaygroundView>,
) -> image::RgbaImage {
app.update(|cx| win.update(cx, |_, w, _| w.render_to_image()))
.unwrap()
.expect("render_to_image")
}
fn region_differs(a: &image::RgbaImage, b: &image::RgbaImage, r: FlowRect) -> bool {
let x0 = r.x.max(0.0) as u32;
let y0 = r.y.max(0.0) as u32;
let x1 = (r.right() as u32).min(a.width()).min(b.width());
let y1 = (r.bottom() as u32).min(a.height()).min(b.height());
(y0..y1).any(|y| (x0..x1).any(|x| a.get_pixel(x, y) != b.get_pixel(x, y)))
}
#[test]
fn active_note_database_view_switch_repaints_the_note_and_moves_its_hits() {
let ((platform, app, win, hw), note_id) = edit_database_note(1.0);
let (table_h, table_rect) = painted_database(&app, win);
let note_h = || {
app.update(|cx| {
let items = &win.read(cx).unwrap().edgeless.authoring.painted_items;
items.iter().find(|i| i.id == note_id).unwrap().rect.h
})
};
let table_note_h = note_h();
let before = rendered(&app, win);
save_evidence(&app, win, "active-note-database-table-light.png");
let (sx, sy) = database_hit_screen(
&app,
win,
|k| matches!(k, DatabaseHitKind::SwitchView { view_id } if view_id == "view-calendar"),
)
.expect("Calendar View tab");
click_pt(&platform, &hw, sx, sy, 1, Modifiers::default());
let _ = frame(&app, win, &hw);
assert!(is_editing_note(&app, win));
let (calendar_h, _) = painted_database(&app, win);
assert!(
calendar_h > table_h + 40.0,
"the canvas paints the Calendar view: {table_h} -> {calendar_h}"
);
assert!(
region_differs(&before, &rendered(&app, win), table_rect),
"the painted Note changes with the view"
);
save_evidence(&app, win, "active-note-database-calendar-light.png");
assert!(
note_h() > table_note_h + 100.0,
"the Note hit and selection box grow with the painted Note"
);
let days: Vec<FlowRect> = app.update(|cx| {
let v = win.read(cx).unwrap();
v.database_hits(DB)
.iter()
.filter(|h| matches!(h.kind, DatabaseHitKind::CalendarSelectDay { .. }))
.map(|h| h.rect)
.collect()
});
assert!(days.len() >= 28, "the hits are the Calendar day cells");
assert!(
days.iter().all(|r| r.bottom() <= calendar_h + 0.5),
"every day hit lies inside the painted block"
);
// A day in the last row, below the Table height, still lands inside the edited Note.
let last = days.iter().map(|r| r.y).fold(0.0_f32, f32::max);
let (sx, sy) = app
.update(|cx| {
let v = win.read(cx).unwrap();
let (_, layout, transform) = v.active_overlay_target()?;
let b = layout.block(DB)?;
let hit = v.database_hits(DB).iter().find(|h| {
matches!(h.kind, DatabaseHitKind::CalendarSelectDay { .. }) && h.rect.y == last
})?;
let s = transform?.rect_to_screen(&hit.rect.translated(b.x, b.y));
Some((s.x + s.w * 0.5, s.y + s.h * 0.5))
})
.expect("last-row day hit");
assert!(
sy > table_rect.bottom(),
"the day lies below the Table view"
);
click_pt(&platform, &hw, sx, sy, 1, Modifiers::default());
let _ = frame(&app, win, &hw);
assert!(
is_editing_note(&app, win),
"the press stays in the edited Note"
);
}
#[test]
fn database_hits_survive_page_edgeless_page_edgeless_round_trip() {
// `set_mode_immediate` dismisses the database popovers on the way, which moves the view
// revision; a bare mode change keeps every layout key except the shared flow's contents.
for full_switch in [true, false] {
// A Note narrower than the Page column, so its database hits differ from the Page's.
let (handles, note_id) = edit_database_note_of(Some(520.0), 1.0);
let (platform, app, win, hw) = (&handles.0, &handles.1, handles.2, &handles.3);
let set_mode = |mode: PlaygroundMode| {
app.update(|cx| {
win.update(cx, |v, _, cx| {
if full_switch {
v.set_mode_immediate(mode, cx);
} else {
v.mode = mode;
cx.notify();
}
})
.unwrap()
});
platform.run_until_parked();
let _ = frame(app, win, hw);
};
let hits_and_width = || {
app.update(|cx| {
let v = win.read(cx).unwrap();
let hits = v.database_authoring_hits(DB);
let right = hits.iter().map(|h| h.rect.right()).fold(0.0_f32, f32::max);
let width = v.flow_layout().unwrap().block(DB).unwrap().body.width;
(hits.len(), right, width)
})
};
let note = hits_and_width();
set_mode(PlaygroundMode::Page);
let page = hits_and_width();
assert!(
page.0 > 0 && page.2 >= note.2 + 100.0,
"{full_switch}: Page lays out {page:?}"
);
set_mode(PlaygroundMode::Edgeless);
if full_switch {
edit_database_note_at(&handles, &note_id, 1.0);
}
assert_eq!(
hits_and_width(),
note,
"{full_switch}: the hits describe the Note"
);
set_mode(PlaygroundMode::Page);
assert_eq!(
hits_and_width(),
page,
"{full_switch}: the Page hits come back in full"
);
set_mode(PlaygroundMode::Edgeless);
if full_switch {
edit_database_note_at(&handles, &note_id, 1.0);
}
assert_eq!(
hits_and_width(),
note,
"{full_switch}: the hits describe the Note"
);
let (sx, sy) = app
.update(|cx| {
win.update(cx, |v, w, _| {
v.database_authoring_hit_screen_center(DB, w, |k| {
matches!(k, DatabaseAuthoringHitKind::EditCell { col_type, .. } if col_type == "select")
})
})
.unwrap()
})
.expect("status cell hit in the Note");
click_pt(platform, hw, sx, sy, 1, Modifiers::default());
let snap = frame(app, win, hw);
assert!(
snap.elements.contains_key("overlay.database_popover"),
"{full_switch}: the Note database opens its popover"
);
assert!(is_editing_note(app, win));
}
}
#[test]
fn active_note_database_column_resize_under_zoom_and_popover_shields_block_hover() {
let ((platform, app, win, hw), _) = edit_database_note(1.5);
let width_of = |column: &str| {
app.update(|cx| {
match &win
.read(cx)
.unwrap()
.page_snapshot()
.unwrap()
.block(DB)
.unwrap()
.content
{
BlockContent::Database(db) => db.views[0]
.columns
.iter()
.find(|c| c.id == column)
.and_then(|c| c.width),
_ => unreachable!(),
}
})
};
let (column, sx, sy) = app
.update(|cx| {
win.update(cx, |v, w, _| {
let column = v
.database_authoring_hits(DB)
.iter()
.find_map(|h| match &h.kind {
DatabaseAuthoringHitKind::ResizeColumnHandle { column_id, .. }
if column_id == "col-status" =>
{
Some(column_id.clone())
}
_ => None,
})?;
let (sx, sy) = v.database_authoring_hit_screen_center(DB, w, |k| {
matches!(k, DatabaseAuthoringHitKind::ResizeColumnHandle { column_id, .. }
if *column_id == column)
})?;
Some((column, sx, sy))
})
.unwrap()
})
.expect("Status column resize handle");
let start = width_of(&column).expect("stored width");
mouse(&hw, &platform, "down", sx, sy);
mouse(&hw, &platform, "drag", sx + 30.0, sy);
mouse(&hw, &platform, "drag", sx + 60.0, sy);
mouse(&hw, &platform, "up", sx + 60.0, sy);
assert!(is_editing_note(&app, win));
assert_eq!(
width_of(&column),
Some(start + 40.0),
"60 screen px at 1.5x widen the column by 40"
);
undo(&app, win);
assert_eq!(width_of(&column), Some(start));
let _ = frame(&app, win, &hw);
let (cx_, cy_) = app
.update(|cx| {
win.update(cx, |v, w, _| {
v.database_authoring_hit_screen_center(DB, w, |k| {
matches!(k, DatabaseAuthoringHitKind::EditCell { col_type, .. } if col_type == "select")
})
})
.unwrap()
})
.expect("status cell hit");
click_pt(&platform, &hw, cx_, cy_, 1, Modifiers::default());
let _ = frame(&app, win, &hw);
let (px_, py_) = app
.update(|cx| {
win.update(cx, |v, w, _| {
let (_, layout, _) = v.active_overlay_target()?;
let (_, overlay) = v.database_popover_overlay(&layout, w)?;
let b = overlay.bounds;
Some((b.x + b.w * 0.5, b.y + b.h * 0.5))
})
.unwrap()
})
.expect("open popover");
mouse(&hw, &platform, "move", px_, py_);
let snap = frame(&app, win, &hw);
assert!(
app.update(|cx| win.read(cx).unwrap().overlays.hovered_block().is_none()),
"the popover keeps the Note blocks under it unhovered"
);
assert!(
!snap
.elements
.keys()
.any(|k| k.starts_with("overlay.drag_handle"))
);
}
@@ -0,0 +1,348 @@
//! Pointer down/hover dispatch inside an Edgeless Active Note (or EdgelessText):
//! Database authoring & popovers, Simple Table cell focus & split-brain prevention,
//! non-editable media/embed block selection, inline link/`@ref` clicks, and text carets.
use blocksuite_editor::{
block_flow::{FlowBlock, FlowKind, FlowRect},
overlays::{LinkPopupTarget, OverlayEvent},
rich_text::DecorationKind,
};
use ui::{Context, MouseDownEvent, Window};
use crate::{
PlaygroundView,
editor_session::{DocPoint, DocumentSelection},
overlays::InlineTargetEnd,
};
use super::{NOTE_CARD_PADDING, point_in_rotated_rect, rotate_point_around};
impl PlaygroundView {
/// Dismiss every Active Note overlay state (table cell and table hover drags, database
/// authoring and record peek, block selection, image resize, text drag, menus, link
/// popup, hover) when the Note stops being edited.
pub(super) fn clear_active_note_overlays(
&mut self,
window: Option<&mut Window>,
cx: &mut Context<Self>,
) {
self.finish_inline_targets(InlineTargetEnd::CommitPreedit, window, Some(cx));
self.clear_block_selection_fields();
self.dismiss_all_database_authoring(None, cx);
self.cancel_image_resize_drag();
self.editor.selection = None;
self.editor.dragging = false;
self.editor.slash_trigger = None;
self.editor.linked_doc_trigger = None;
self.last_link_popup_caret = None;
self.database_record_sheet = None;
self.overlays.table_hover = Default::default();
let now_ms = self.now_ms(cx);
self.overlays.pointer_pressed(now_ms);
self.overlays.hide_hover();
}
/// Route a primary pointer down when an Edgeless Note or EdgelessText is actively being
/// edited. Returns `true` when the press was consumed inside the Active Note (or an open
/// Database popover extending outside the Note card) so the caller stays in Active Note mode.
pub(super) fn handle_active_note_left_down(
&mut self,
event: &MouseDownEvent,
wx: f32,
wy: f32,
window: &mut Window,
cx: &mut Context<Self>,
) -> bool {
let sx = f32::from(event.position.x);
let sy = f32::from(event.position.y);
if self.try_click_database_popover(sx, sy, window, cx) {
return true;
}
let Some((editing_id, is_note)) = self
.edgeless
.authoring
.editing_spatial_block()
.map(|(id, n)| (id.to_string(), n))
else {
return false;
};
let Some(info) = self
.edgeless
.authoring
.painted_items
.iter()
.find(|i| i.id == editing_id)
.cloned()
else {
return false;
};
if !point_in_rotated_rect(wx, wy, info.rect, info.rotate_deg) {
return false;
}
let (cx_w, cy_w) = info.rect.center();
let (lx, ly) = rotate_point_around(wx, wy, cx_w, cy_w, -info.rotate_deg);
let pad = if is_note { NOTE_CARD_PADDING } else { 0.0 };
let flow_x = (lx - info.rect.x) / info.scale - pad;
let flow_y = (ly - info.rect.y) / info.scale - pad;
let now_ms = self.now_ms(cx);
if is_note {
self.sync_active_note_flow(&editing_id, window);
}
let Some(layout) = self.edgeless.cached_block_layout(&editing_id, is_note) else {
return false;
};
// 1. Database block inside Active Note: dispatch authoring/view clicks without exiting Note.
if is_note
&& let Some((block_id, local_x, local_y)) = layout.blocks.iter().find_map(|block| {
let r = block.rect();
(block.body.kind == FlowKind::Database
&& flow_y >= r.y
&& flow_y <= r.bottom()
&& flow_x >= r.x - 20.0
&& flow_x <= r.right())
.then(|| (block.block_id.clone(), flow_x - r.x, flow_y - r.y))
})
{
self.finish_inline_targets(InlineTargetEnd::CommitPreedit, Some(window), Some(cx));
self.clear_block_selection_fields();
self.dismiss_all_database_authoring(Some(&block_id), cx);
let consumed = self.dispatch_database_page_mouse_down(
&block_id,
local_x,
local_y,
event.click_count,
false,
window,
cx,
);
self.show_database_readonly_toast_once(cx);
if self.database_input.is_none() {
self.editor.selection = None;
self.editor_focus.focus(window, cx);
if !consumed && self.database_readonly {
self.set_block_selection(vec![block_id], false, window, cx);
}
} else {
self.editor_focus.focus(window, cx);
}
self.editor.dragging = false;
cx.notify();
return true;
}
self.dismiss_all_database_authoring(None, cx);
// 2. Simple Table cell inside Active Note: route directly to `focus_table_cell_pointer`.
if is_note
&& let Some((bid, rid, cid)) = layout.blocks.iter().find_map(|block| {
if block.body.kind != FlowKind::Table {
return None;
}
let r = block.rect();
if flow_y < r.y || flow_y > r.bottom() {
return None;
}
let scroll_x = self.overlays.code_scroll_x(&block.block_id);
let tx = flow_x - r.x + scroll_x;
let ty = flow_y - r.y;
block
.body
.table_cells
.iter()
.find(|c| c.rect.contains(tx, ty))
.map(|c| {
(
block.block_id.clone(),
c.row_id.clone(),
c.column_id.clone(),
)
})
})
{
self.clear_block_selection_fields();
self.focus_table_cell_pointer(
bid,
rid,
cid,
Some((sx, sy)),
event.click_count,
event.modifiers.shift,
window,
cx,
);
return true;
}
// 3. Any click outside a Simple Table cell clears `table_cell` (prevents cursor/input split-brain).
self.finish_inline_targets(InlineTargetEnd::CommitPreedit, Some(window), Some(cx));
self.overlays.pointer_pressed(now_ms);
self.cancel_image_resize_drag();
self.editor.slash_trigger = None;
self.editor.linked_doc_trigger = None;
self.clear_block_selection_fields();
// 4. Non-editable blocks (Image, Bookmark, Attachment, Embed, Divider, Callout, Latex).
if is_note
&& let Some((block_id, kind, can_lightbox)) = layout.blocks.iter().find_map(|block| {
(!block.editable()
&& (block.rect().contains(flow_x, flow_y)
|| (flow_y >= block.rect().y && flow_y <= block.rect().bottom())))
.then(|| {
(
block.block_id.clone(),
block.body.kind,
block.body.is_resizable_image(),
)
})
})
{
self.editor_focus.focus(window, cx);
if matches!(kind, FlowKind::Callout)
&& self.focus_or_create_callout_child(&block_id, window, cx)
{
return true;
}
if matches!(kind, FlowKind::Image) && event.click_count >= 2 && can_lightbox {
self.dispatch_overlay(OverlayEvent::OpenImageLightbox(block_id), window, cx);
return true;
}
self.set_block_selection(vec![block_id], false, window, cx);
return true;
}
// 5. Inline link / `@reference` hit inside Active Note text blocks.
let clicked_popup = if is_note && event.click_count == 1 && !event.modifiers.shift {
self.hit_active_note_link_or_ref(&layout, flow_x, flow_y)
} else {
None
};
if let Some((LinkPopupTarget::Reference { page_id, .. }, _)) = &clicked_popup
&& event.modifiers.secondary(cx)
{
self.open_linked_doc(page_id, Some(window), cx);
return true;
}
if !self.is_touch_host()
&& !event.modifiers.alt
&& let Some((LinkPopupTarget::Link { url, .. }, _)) = &clicked_popup
&& let Some(clean) = blocksuite_editor::clipboard::sanitize::sanitize_url(url)
.filter(|u| !u.starts_with('#'))
{
self.overlays.close_link_popup(now_ms);
self.open_editor_url(clean, cx);
cx.notify();
return true;
}
// 6. Standard text caret / word / line / shift selection inside the Note/EdgelessText.
if let Some(pt) = Self::hit_test_flow_layout(&layout, flow_x, flow_y) {
let mut sel = DocumentSelection::caret(pt.clone());
if event.click_count >= 2 {
let s = self.block_text(&pt.block_id).unwrap_or("");
let range = if event.click_count == 2 {
crate::editor_session::word_range(s, pt.offset())
} else {
0..s.encode_utf16().count() as u64
};
sel.anchor = DocPoint::new(&pt.block_id, range.start);
sel.focus = DocPoint::new(&pt.block_id, range.end);
self.editor.dragging = false;
} else if event.modifiers.shift
&& let Some(old) = &self.editor.selection
{
sel.anchor = old.anchor.clone();
self.editor.dragging = true;
} else {
self.editor.dragging = true;
}
self.change_selection(sel, window, cx);
if let Some((target, anchor_world)) = clicked_popup {
self.overlays
.open_link_popup(target, anchor_world, false, now_ms);
let rev = self.page().map_or(0, |p| p.revision());
self.last_link_popup_caret = self
.editor
.selection
.as_ref()
.map(|s| (s.focus.clone(), rev));
cx.notify();
}
return true;
}
// Click landed in Note padding: keep Active Note open without jumping out.
true
}
fn hit_active_note_link_or_ref(
&self,
layout: &blocksuite_editor::block_flow::FlowLayout,
flow_x: f32,
flow_y: f32,
) -> Option<(LinkPopupTarget, FlowRect)> {
let block = layout
.blocks
.iter()
.find(|b| b.rect().contains(flow_x, flow_y))?;
self.active_note_link_in_block(block, flow_x, flow_y)
}
fn active_note_link_in_block(
&self,
block: &FlowBlock,
flow_x: f32,
flow_y: f32,
) -> Option<(LinkPopupTarget, FlowRect)> {
let text = block.body.text.as_ref()?;
let lx = flow_x - (block.x + text.x);
let ly = flow_y - (block.y + text.y);
for deco in text.layout.decorations() {
let b = deco.bounds;
let bx = f32::from(b.origin.x);
let by = f32::from(b.origin.y);
let bw = f32::from(b.size.width);
let bh = f32::from(b.size.height);
if lx < bx || lx > bx + bw || ly < by || ly > by + bh {
continue;
}
let anchor = FlowRect::new(block.x + text.x + bx, block.y + text.y + by, bw, bh);
match &deco.kind {
DecorationKind::Link(url) => {
return Some((
LinkPopupTarget::Link {
block_id: block.block_id.clone(),
start_utf16: deco.source_utf16.start as usize,
end_utf16: deco.source_utf16.end as usize,
url: url.clone(),
},
anchor,
));
}
DecorationKind::ReferenceChip(inline_ref) => {
let page_id = inline_ref.page_id.clone();
let title = self
.page_titles
.get(&page_id)
.cloned()
.unwrap_or_else(|| "Untitled".to_string());
return Some((
LinkPopupTarget::Reference {
block_id: block.block_id.clone(),
utf16_offset: deco.source_utf16.start as usize,
page_id,
title,
can_convert: true,
can_embed: true,
},
anchor,
));
}
_ => {}
}
}
None
}
}
@@ -0,0 +1,793 @@
//! End-to-end tests for Edgeless Active Note interactions under camera zoom and pan, and the
//! shared harness the Active Note media tests reuse:
//! - Page controls (to-do, code language picker, inline link popup)
//! - Simple Table pointer mapping, drag selection, controls, and focus release
//! - Database `Status` popover and `+ New record` writes, V1 reopen, and one-step undo
use std::time::Duration;
use blocksuite_editor::{
block_flow::FlowRect,
database::{DatabaseAuthoringHitKind, DatabaseHitKind},
};
use blocksuite_playground_doc::{
read::BlockContent,
schema::{BlockSpec, ListType, ParagraphType},
session::WorkspaceSession,
};
use ui::{
AppContext, Application, HeadlessPlatform, Modifiers, MouseButton, MouseDownEvent,
MouseMoveEvent, MouseUpEvent, PlatformInput, WindowOptions, point, px,
};
use y_octo::{Any, TextAttributes};
use crate::{
HOME_PAGE_ID, PlaygroundMode, PlaygroundOptions, PlaygroundTheme, PlaygroundView,
room_client::DocState, showcase::seed_showcase_doc,
};
use super::edgeless_canvas_media_tests::{frame, keystroke, save_evidence};
pub(super) type TestHandles = (
std::rc::Rc<HeadlessPlatform>,
ui::ApplicationHandle,
ui::WindowHandle<PlaygroundView>,
ui::HeadlessWindow,
);
pub(super) fn is_editing_note(
app: &ui::ApplicationHandle,
win: ui::WindowHandle<PlaygroundView>,
) -> bool {
app.update(|cx| {
win.read(cx)
.unwrap()
.edgeless
.authoring
.editing_spatial_block()
.is_some()
})
}
pub(super) fn spawn_edgeless_view(doc: DocState, theme: PlaygroundTheme) -> TestHandles {
spawn_edgeless_view_with(doc, theme, false)
}
pub(super) fn spawn_edgeless_view_with(
doc: DocState,
theme: PlaygroundTheme,
edgeless_readonly: bool,
) -> TestHandles {
let platform = HeadlessPlatform::new(1280, 800, 1.0);
let app = Application::with_platform(platform.clone()).run_embedded(|cx| {
crate::register_bundled_fonts(cx).unwrap();
});
let win = app
.update(|cx| {
cx.open_window(WindowOptions::default(), |_window, cx| {
cx.new(|cx| {
let mut view = PlaygroundView::with_options(
PlaygroundOptions {
theme,
mode: PlaygroundMode::Edgeless,
edgeless_readonly,
..Default::default()
},
cx,
);
view.set_document(doc, cx);
view
})
})
})
.unwrap();
let hw = platform.windows().into_iter().next().unwrap();
platform.run_until_parked();
let _ = frame(&app, win, &hw);
(platform, app, win, hw)
}
pub(super) fn click_pt(
platform: &HeadlessPlatform,
hw: &ui::HeadlessWindow,
x: f32,
y: f32,
click_count: usize,
modifiers: Modifiers,
) {
let pos = point(px(x), px(y));
hw.dispatch_input(PlatformInput::MouseDown(MouseDownEvent {
button: MouseButton::Left,
position: pos,
modifiers,
click_count,
first_mouse: false,
}));
hw.dispatch_input(PlatformInput::MouseUp(MouseUpEvent {
button: MouseButton::Left,
position: pos,
modifiers,
click_count,
}));
platform.run_until_parked();
}
pub(super) fn mouse(
hw: &ui::HeadlessWindow,
platform: &HeadlessPlatform,
kind: &str,
x: f32,
y: f32,
) {
let position = point(px(x), px(y));
let modifiers = Modifiers::default();
hw.dispatch_input(match kind {
"down" => PlatformInput::MouseDown(MouseDownEvent {
button: MouseButton::Left,
position,
modifiers,
click_count: 1,
first_mouse: false,
}),
"up" => PlatformInput::MouseUp(MouseUpEvent {
button: MouseButton::Left,
position,
modifiers,
click_count: 1,
}),
pressed => PlatformInput::MouseMove(MouseMoveEvent {
position,
pressed_button: (pressed == "drag").then_some(MouseButton::Left),
modifiers,
}),
});
platform.run_until_parked();
}
pub(super) fn center(b: &ui::SnapshotRect) -> (f32, f32) {
(b.x + b.width * 0.5, b.y + b.height * 0.5)
}
pub(super) fn undo(app: &ui::ApplicationHandle, win: ui::WindowHandle<PlaygroundView>) {
app.update(|cx| {
win.update(cx, |v, _, cx| {
let _ = v.page_mut().unwrap().undo();
v.refresh_document();
cx.notify();
})
.unwrap();
});
}
pub(super) fn reopen_v1(
app: &ui::ApplicationHandle,
win: ui::WindowHandle<PlaygroundView>,
) -> blocksuite_playground_doc::read::PageSnapshot {
let v1 = app.update(|cx| {
win.read(cx)
.unwrap()
.page()
.unwrap()
.encode_update_v1()
.unwrap()
});
let mut reopened = WorkspaceSession::new("reopen", 97).unwrap();
let page = reopened.ensure_page(HOME_PAGE_ID).unwrap();
page.apply_remote_update_v1(&v1).unwrap();
page.read_page_snapshot().unwrap()
}
pub(super) fn child_ids(
app: &ui::ApplicationHandle,
win: ui::WindowHandle<PlaygroundView>,
id: &str,
) -> Vec<String> {
app.update(|cx| {
let snap = win.read(cx).unwrap().page_snapshot().unwrap().clone();
snap.block(id)
.unwrap()
.children
.iter()
.map(|c| c.id.clone())
.collect()
})
}
pub(super) fn first_note_id(
app: &ui::ApplicationHandle,
win: ui::WindowHandle<PlaygroundView>,
) -> String {
app.update(|cx| {
win.read(cx)
.unwrap()
.page_snapshot()
.unwrap()
.root
.as_ref()
.unwrap()
.children
.iter()
.find(|c| matches!(c.content, BlockContent::Note { .. }))
.map(|c| c.id.clone())
.unwrap()
})
}
pub(super) fn type_ascii(
app: &ui::ApplicationHandle,
win: ui::WindowHandle<PlaygroundView>,
hw: &ui::HeadlessWindow,
platform: &HeadlessPlatform,
text: &str,
) {
for ch in text.chars() {
keystroke(
app,
win,
hw,
platform,
&ch.to_string(),
Modifiers::default(),
);
}
}
pub(super) fn new_page_doc(room: &str, client_id: u64) -> DocState {
let mut doc = DocState::new(room, client_id).unwrap();
doc.workspace
.create_page(HOME_PAGE_ID, "Active Note Test", 1)
.unwrap();
let page = doc.workspace.ensure_page(HOME_PAGE_ID).unwrap();
let _ = page.add_block(
"root",
BlockSpec::Page {
title: "Active Note Test".into(),
},
None,
None,
1,
);
doc
}
pub(super) fn enter_note_edit(
app: &ui::ApplicationHandle,
win: ui::WindowHandle<PlaygroundView>,
hw: &ui::HeadlessWindow,
platform: &HeadlessPlatform,
note_id: &str,
pan: (f32, f32),
zoom: f32,
) {
app.update(|cx| {
win.update(cx, |v, w, cx| {
v.set_edgeless_camera(pan.0, pan.1, zoom, cx);
assert!(v.edgeless_begin_inline_edit(note_id, w, cx));
})
.unwrap();
});
platform.run_until_parked();
let _ = frame(app, win, hw);
}
#[test]
fn active_note_controls_at_multiple_zooms_and_pan() {
let mut doc = new_page_doc("active-note-zoom", 51);
let _ = doc
.workspace
.page_mut(HOME_PAGE_ID)
.unwrap()
.structural_edit(100, |p| {
p.add_block(
"note-1",
BlockSpec::Note {
xywh: Some("[0,0,640,480]".into()),
},
Some("root"),
None,
100,
)?;
p.add_block(
"todo-1",
BlockSpec::List {
list_type: ListType::Todo,
text: "Ship Active Note".into(),
checked: false,
order: None,
},
Some("note-1"),
None,
100,
)?;
p.add_block(
"code-1",
BlockSpec::Code {
language: Some("Rust".into()),
text: "fn main() {}".into(),
caption: String::new(),
},
Some("note-1"),
None,
100,
)?;
p.add_block(
"link-p",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: "Visit AFFiNE".into(),
},
Some("note-1"),
None,
100,
)?;
let mut attrs = TextAttributes::new();
attrs.insert("link".into(), Any::String("https://affine.pro".into()));
p.format_text("link-p", "prop:text", 6, 6, attrs, 100)?;
Ok(())
});
let (platform, app, win, hw) = spawn_edgeless_view(doc, PlaygroundTheme::Light);
let mut expected_checked = false;
for (idx, (zoom, pan_x, pan_y)) in [
(0.75_f32, -140.0_f32, -90.0_f32),
(1.0_f32, -40.0_f32, -30.0_f32),
(1.5_f32, -30.0_f32, -20.0_f32),
]
.into_iter()
.enumerate()
{
enter_note_edit(&app, win, &hw, &platform, "note-1", (pan_x, pan_y), zoom);
let snap = frame(&app, win, &hw);
let cb = snap
.elements
.get("page.block.todo-1.checkbox")
.unwrap_or_else(|| panic!("missing todo checkbox at zoom={zoom}"))
.bounds;
click_pt(
&platform,
&hw,
cb.x + cb.width * 0.5,
cb.y + cb.height * 0.5,
1,
Modifiers::default(),
);
expected_checked = !expected_checked;
let v1_bytes = app.update(|cx| {
win.read(cx)
.unwrap()
.page()
.unwrap()
.encode_update_v1()
.unwrap()
});
let mut reopened = WorkspaceSession::new("reopen", 99).unwrap();
let reopened_page = reopened.ensure_page(HOME_PAGE_ID).unwrap();
reopened_page.apply_remote_update_v1(&v1_bytes).unwrap();
match &reopened_page
.read_page_snapshot()
.unwrap()
.block("todo-1")
.unwrap()
.content
{
BlockContent::List { checked, .. } => {
assert_eq!(*checked, expected_checked, "todo mismatch at zoom={zoom}");
}
other => panic!("expected List, got {other:?}"),
}
let code_screen = app
.update(|cx| {
win.read(cx)
.unwrap()
.active_overlay_target()
.and_then(|(_, l, t)| Some(t?.rect_to_screen(&l.block("code-1")?.rect())))
})
.expect("code rect");
hw.dispatch_input(PlatformInput::MouseMove(MouseMoveEvent {
position: point(px(code_screen.x + 40.0), px(code_screen.y + 18.0)),
pressed_button: None,
modifiers: Modifiers::default(),
}));
platform.run_until_parked();
let snap = frame(&app, win, &hw);
let lang_b = snap
.elements
.get("page.block.code-1.toolbar.language")
.unwrap_or_else(|| panic!("missing code language button at zoom={zoom}"))
.bounds;
click_pt(
&platform,
&hw,
lang_b.x + lang_b.width * 0.5,
lang_b.y + lang_b.height * 0.5,
1,
Modifiers::default(),
);
platform.advance_clock(Duration::from_millis(200));
let _ = frame(&app, win, &hw);
assert!(
app.update(|cx| {
win.read(cx)
.unwrap()
.overlays()
.code_lang_picker()
.is_some()
}),
"code lang picker should open at zoom={zoom}"
);
if idx == 0 {
save_evidence(&app, win, "active-note-controls-zoom075-light.png");
} else if idx == 1 {
save_evidence(&app, win, "active-note-controls-zoom100-light.png");
app.update(|cx| {
win.update(cx, |v, _, cx| v.set_theme(PlaygroundTheme::Dark, cx))
.unwrap();
});
platform.run_until_parked();
let _ = frame(&app, win, &hw);
save_evidence(&app, win, "active-note-controls-zoom100-dark.png");
app.update(|cx| {
win.update(cx, |v, _, cx| v.set_theme(PlaygroundTheme::Light, cx))
.unwrap();
});
platform.run_until_parked();
}
keystroke(&app, win, &hw, &platform, "escape", Modifiers::default());
let _ = frame(&app, win, &hw);
let link_screen = app
.update(|cx| {
win.read(cx)
.unwrap()
.active_overlay_target()
.and_then(|(_, l, t)| {
let b = l.block("link-p")?;
let txt = b.body.text.as_ref()?;
let deco = txt.layout.decorations().first()?;
Some(t?.rect_to_screen(&FlowRect::new(
b.x + txt.x + f32::from(deco.bounds.origin.x),
b.y + txt.y + f32::from(deco.bounds.origin.y),
f32::from(deco.bounds.size.width),
f32::from(deco.bounds.size.height),
)))
})
})
.expect("link rect");
click_pt(
&platform,
&hw,
link_screen.x + link_screen.w * 0.5,
link_screen.y + link_screen.h * 0.5,
1,
Modifiers {
alt: true,
..Modifiers::default()
},
);
let _ = frame(&app, win, &hw);
assert!(
app.update(|cx| win.read(cx).unwrap().overlays().link_popup().is_some()),
"link popup should open on Alt-click at zoom={zoom}"
);
}
}
#[test]
fn active_note_simple_table_maps_pointer_through_camera_and_releases_focus_outside() {
let mut doc = new_page_doc("active-note-table", 52);
let _ = doc
.workspace
.page_mut(HOME_PAGE_ID)
.unwrap()
.structural_edit(200, |p| {
p.add_block(
"note-tbl",
BlockSpec::Note {
xywh: Some("[0,0,640,420]".into()),
},
Some("root"),
None,
200,
)?;
p.add_block(
"tbl-1",
BlockSpec::Table {
rows: vec![
vec!["Hello World".into(), "".into()],
vec!["".into(), "".into()],
],
},
Some("note-tbl"),
None,
200,
)?;
p.add_block(
"para-after",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: "Outside ".into(),
},
Some("note-tbl"),
None,
200,
)?;
Ok(())
});
let (platform, app, win, hw) = spawn_edgeless_view(doc, PlaygroundTheme::Light);
enter_note_edit(&app, win, &hw, &platform, "note-tbl", (-60.0, -40.0), 0.75);
// Screen point of UTF-16 offset `off` in the first cell, through the camera.
let caret_screen = |off: usize| {
app.update(|cx| {
let v = win.read(cx).unwrap();
let (_, l, t) = v.active_overlay_target()?;
let b = l.block("tbl-1")?;
let c = b.body.table_cells.first()?;
let (x, line) = c.text.caret(off);
let lh = c.text.line_height();
let r = t?.rect_to_screen(&FlowRect::new(
b.x + c.text_origin.0 + x,
b.y + c.text_origin.1 + line as f32 * lh + lh * 0.5,
0.0,
0.0,
));
Some((r.x, r.y, c.row_id.clone(), c.column_id.clone()))
})
.expect("table cell")
};
let selection = || {
app.update(|cx| {
win.read(cx)
.unwrap()
.active_table_cell()
.map(|c| c.input.shown_selection().0)
})
};
// Click lands on the clicked character, not on Page-column geometry.
let (x5, y5, row_id, col_id) = caret_screen(5);
click_pt(&platform, &hw, x5, y5, 1, Modifiers::default());
assert_eq!(selection(), Some(5..5));
// A drag across the text selects it all.
let (x0, y0, ..) = caret_screen(0);
let (x11, y11, ..) = caret_screen(11);
mouse(&hw, &platform, "down", x0 + 0.5, y0);
mouse(&hw, &platform, "drag", (x0 + x11) * 0.5, y11);
mouse(&hw, &platform, "drag", x11 + 2.0, y11);
mouse(&hw, &platform, "up", x11 + 2.0, y11);
assert_eq!(selection(), Some(0..11));
let snap = frame(&app, win, &hw);
for id in [
"page.table_cell_focus",
"page.selection",
"overlay.table_hover.add_row",
"overlay.table_hover.add_col",
"overlay.table_hover.add_corner",
"overlay.table_hover.col_pill",
"overlay.table_hover.row_pill",
] {
assert!(snap.elements.contains_key(id), "missing {id}");
}
save_evidence(&app, win, "active-note-table-zoom075-light.png");
// The add-row bar appends one row in one undo step.
let rows = |app: &ui::ApplicationHandle| {
app.update(|cx| {
match &win
.read(cx)
.unwrap()
.page_snapshot()
.unwrap()
.block("tbl-1")
.unwrap()
.content
{
BlockContent::Table(t) => t.rows.len(),
other => panic!("expected Table, got {other:?}"),
}
})
};
let (ax, ay) = center(&snap.elements["overlay.table_hover.add_row"].bounds);
click_pt(&platform, &hw, ax, ay, 1, Modifiers::default());
assert_eq!(rows(&app), 3);
undo(&app, win);
assert_eq!(rows(&app), 2);
// A click outside the table releases the cell so typing goes to the paragraph.
let _ = frame(&app, win, &hw);
let (px_o, py_o) = app
.update(|cx| {
let v = win.read(cx).unwrap();
let (_, l, t) = v.active_overlay_target()?;
let r = t?.rect_to_screen(&l.block("para-after")?.rect());
Some((r.x + r.w - 4.0, r.y + r.h * 0.5))
})
.expect("para rect");
click_pt(&platform, &hw, px_o, py_o, 1, Modifiers::default());
assert!(app.update(|cx| win.read(cx).unwrap().active_table_cell().is_none()));
type_ascii(&app, win, &hw, &platform, "OK");
let _ = frame(&app, win, &hw);
let (cell_text, para_text) = app.update(|cx| {
let snap = win.read(cx).unwrap().page_snapshot().unwrap();
let cell_text = match &snap.block("tbl-1").unwrap().content {
BlockContent::Table(t) => t
.cells
.get(&(row_id.clone(), col_id.clone()))
.map(|c| c.text.plain.clone())
.unwrap_or_default(),
other => panic!("expected Table, got {other:?}"),
};
let para_text = match &snap.block("para-after").unwrap().content {
BlockContent::Paragraph { text, .. } => text.plain.clone(),
other => panic!("expected Paragraph, got {other:?}"),
};
(cell_text, para_text)
});
assert_eq!(cell_text, "Hello World");
assert!(para_text.contains("OK"));
}
#[test]
fn active_note_database_status_and_new_record_persist_and_undo_in_one_step() {
let (platform, app, win, hw) =
spawn_edgeless_view(seed_showcase_doc().unwrap(), PlaygroundTheme::Light);
let note_id = first_note_id(&app, win);
enter_note_edit(&app, win, &hw, &platform, &note_id, (-80.0, -60.0), 1.0);
app.update(|cx| {
win.update(cx, |v, _, cx| {
if let Some((_, layout, _)) = v.active_overlay_target()
&& let Some(db_block) = layout.block("showcase-database")
&& let Some(info) = v
.edgeless
.authoring
.painted_items
.iter()
.find(|i| i.id == note_id)
{
v.set_edgeless_camera(info.rect.x - 60.0, info.rect.y + db_block.y - 80.0, 1.0, cx);
}
})
.unwrap();
});
platform.run_until_parked();
let _ = frame(&app, win, &hw);
let db = |app: &ui::ApplicationHandle| {
app.update(|cx| {
match &win
.read(cx)
.unwrap()
.page_snapshot()
.unwrap()
.block("showcase-database")
.unwrap()
.content
{
BlockContent::Database(db) => db.clone(),
_ => unreachable!(),
}
})
};
let (sx, sy, row_id, column_id) = app
.update(|cx| {
win.update(cx, |v, w, _| {
let (row_id, column_id) = v
.database_authoring_hits("showcase-database")
.iter()
.find_map(|h| match &h.kind {
DatabaseAuthoringHitKind::EditCell {
row_id,
column_id,
col_type,
} if col_type == "select" => Some((row_id.clone(), column_id.clone())),
_ => None,
})?;
let (sx, sy) = v.database_authoring_hit_screen_center("showcase-database", w, |k| {
matches!(k, DatabaseAuthoringHitKind::EditCell { col_type, .. } if col_type == "select")
})?;
Some((sx, sy, row_id, column_id))
})
.unwrap()
})
.expect("status cell hit");
click_pt(&platform, &hw, sx, sy, 1, Modifiers::default());
let snap_pop = frame(&app, win, &hw);
assert!(snap_pop.elements.contains_key("overlay.database_popover"));
assert!(is_editing_note(&app, win));
save_evidence(&app, win, "active-note-database-popover-light.png");
let before = db(&app)
.cells
.get(&(row_id.clone(), column_id.clone()))
.cloned();
let (ox, oy, popover_top) = app
.update(|cx| {
win.update(cx, |v, w, _| {
let (_, layout, _) = v.active_overlay_target()?;
let (_, overlay) = v.database_popover_overlay(&layout, w)?;
let opt = overlay.hits.iter().find(|h| {
matches!(&h.kind, DatabaseAuthoringHitKind::SelectToggleOption { option_id, .. }
if !format!("{before:?}").contains(option_id.as_str()))
})?;
Some((
opt.rect.x + opt.rect.w * 0.5,
opt.rect.y + opt.rect.h * 0.5,
overlay.bounds.y,
))
})
.unwrap()
})
.expect("select option");
assert!(
popover_top >= sy - 40.0,
"popover anchors at the cell, not the Page column"
);
click_pt(&platform, &hw, ox, oy, 1, Modifiers::default());
let _ = frame(&app, win, &hw);
assert!(is_editing_note(&app, win));
let after = db(&app)
.cells
.get(&(row_id.clone(), column_id.clone()))
.cloned();
assert_ne!(after, before, "picking an option writes the cell");
match &reopen_v1(&app, win)
.block("showcase-database")
.unwrap()
.content
{
BlockContent::Database(d) => {
assert_eq!(
d.cells.get(&(row_id.clone(), column_id.clone())),
after.as_ref()
);
}
_ => unreachable!(),
}
undo(&app, win);
assert_eq!(
db(&app)
.cells
.get(&(row_id.clone(), column_id.clone()))
.cloned(),
before,
"one undo restores the cell"
);
let _ = frame(&app, win, &hw);
let rows_before = db(&app).rows.len();
let (ax, ay) = app
.update(|cx| {
let v = win.read(cx).unwrap();
let (_, layout, transform) = v.active_overlay_target()?;
let db_block = layout.block("showcase-database")?;
let hit = v
.database_hits("showcase-database")
.iter()
.find(|h| matches!(h.kind, DatabaseHitKind::AddRow))?;
let s = transform?.rect_to_screen(&hit.rect.translated(db_block.x, db_block.y));
Some((s.x + s.w * 0.5, s.y + s.h * 0.5))
})
.expect("+ New record hit");
click_pt(&platform, &hw, ax, ay, 1, Modifiers::default());
let _ = frame(&app, win, &hw);
assert_eq!(db(&app).rows.len(), rows_before + 1);
assert!(is_editing_note(&app, win));
match &reopen_v1(&app, win)
.block("showcase-database")
.unwrap()
.content
{
BlockContent::Database(d) => assert_eq!(d.rows.len(), rows_before + 1),
_ => unreachable!(),
}
undo(&app, win);
platform.run_until_parked();
assert_eq!(db(&app).rows.len(), rows_before);
}
@@ -0,0 +1,703 @@
//! End-to-end tests for Edgeless Active Note media, structure, and gates under camera zoom and
//! pan: image resize preview and write-back from every corner, caption editing and the lightbox,
//! read-only gates, block drag-handle reordering, linked-doc card `params`, the Page-flow pass
//! that only database Notes pay for, table carets in an embedded view, and the phone table bar.
use std::{sync::Arc, time::Duration};
use blocksuite_editor::block_flow::FlowRect;
use blocksuite_playground_doc::{
read::BlockContent,
schema::{BlockSpec, ParagraphType},
};
use ui::{AppContext, Modifiers};
use y_octo::{Any, SessionValue};
use crate::{
HOME_PAGE_ID, PlaygroundMode, PlaygroundTheme, PlaygroundView, room_client::DocState,
showcase::seed_showcase_doc,
};
use super::{
active_note_interaction_tests::{
TestHandles, center, child_ids, click_pt, enter_note_edit, first_note_id, is_editing_note,
mouse, new_page_doc, spawn_edgeless_view, spawn_edgeless_view_with, type_ascii, undo,
},
edgeless_canvas_media_tests::{frame, save_evidence},
};
fn image_note_doc(room: &str, client_id: u64) -> DocState {
let mut doc = new_page_doc(room, client_id);
let png_bytes: Vec<u8> = vec![
0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, b'I', b'H', b'D',
b'R', 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x02, 0x00, 0x00, 0x00, 0x90,
0x77, 0x53, 0xDE, 0x00, 0x00, 0x00, 0x0C, b'I', b'D', b'A', b'T', 0x08, 0xD7, 0x63, 0xF8,
0xCF, 0xC0, 0x00, 0x00, 0x03, 0x01, 0x01, 0x00, 0x18, 0xDD, 0x8D, 0xB0, 0x00, 0x00, 0x00,
0x00, b'I', b'E', b'N', b'D', 0xAE, 0x42, 0x60, 0x82,
];
doc.blobs.insert("img-blob-1".into(), Arc::new(png_bytes));
let _ = doc
.workspace
.page_mut(HOME_PAGE_ID)
.unwrap()
.structural_edit(300, |p| {
p.add_block(
"note-img",
BlockSpec::Note {
xywh: Some("[0,0,640,480]".into()),
},
Some("root"),
None,
300,
)?;
p.add_block(
"img-1",
BlockSpec::Image {
source_id: "img-blob-1".into(),
caption: "Initial caption".into(),
width: 320.0,
height: 180.0,
xywh: None,
},
Some("note-img"),
None,
300,
)?;
p.add_block(
"callout-1",
BlockSpec::Callout {
icon: String::new(),
background_color: None,
},
Some("note-img"),
None,
300,
)?;
Ok(())
});
doc
}
fn image_width(app: &ui::ApplicationHandle, win: ui::WindowHandle<PlaygroundView>) -> f64 {
app.update(|cx| {
win.read(cx)
.unwrap()
.page_snapshot()
.unwrap()
.block("img-1")
.unwrap()
.props
.get("prop:width")
.and_then(|v| v.as_f64())
.unwrap_or_default()
})
}
#[test]
fn active_note_image_resize_caption_and_lightbox() {
let (platform, app, win, hw) = spawn_edgeless_view(
image_note_doc("active-note-media", 53),
PlaygroundTheme::Light,
);
enter_note_edit(&app, win, &hw, &platform, "note-img", (-80.0, -50.0), 1.5);
let snap = frame(&app, win, &hw);
let (ix, iy) = center(&snap.elements["page.block.img-1.image_card"].bounds);
click_pt(&platform, &hw, ix, iy, 1, Modifiers::default());
let snap_sel = frame(&app, win, &hw);
for suffix in ["resize_nw", "resize_ne", "resize_sw", "resize_se"] {
assert!(
snap_sel
.elements
.contains_key(&format!("page.block.img-1.{suffix}"))
);
}
save_evidence(&app, win, "active-note-image-selected-light.png");
// Resize from the south-east corner: the Note shows the live width, and the release writes
// exactly that width.
let (hx, hy) = center(&snap_sel.elements["page.block.img-1.resize_se"].bounds);
mouse(&hw, &platform, "down", hx, hy);
mouse(&hw, &platform, "drag", hx + 30.0, hy + 30.0);
mouse(&hw, &platform, "drag", hx + 60.0, hy + 60.0);
let _ = frame(&app, win, &hw);
let (preview_w, painted_w) = app.update(|cx| {
let v = win.read(cx).unwrap();
let preview = v.image_resize_drag.as_ref().unwrap().preview_w;
let (_, layout, _) = v.active_overlay_target().unwrap();
let painted = layout.block("img-1").unwrap().body.image_box().unwrap().w;
(preview, painted)
});
assert!(preview_w > 320.0, "the drag grows the image");
assert_eq!(painted_w, preview_w, "the Note paints the live width");
mouse(&hw, &platform, "up", hx + 60.0, hy + 60.0);
assert_eq!(image_width(&app, win), f64::from(preview_w));
undo(&app, win);
assert_eq!(image_width(&app, win), 320.0);
let snap_sel = frame(&app, win, &hw);
let cap_b = snap_sel.elements["page.block.img-1.caption"].bounds;
click_pt(
&platform,
&hw,
cap_b.x + cap_b.width - 4.0,
cap_b.y + cap_b.height * 0.5,
1,
Modifiers::default(),
);
assert!(app.update(|cx| win.read(cx).unwrap().caption_editor.is_some()));
type_ascii(&app, win, &hw, &platform, "!");
let _ = frame(&app, win, &hw);
let cap_after = app.update(|cx| {
match &win
.read(cx)
.unwrap()
.page_snapshot()
.unwrap()
.block("img-1")
.unwrap()
.content
{
BlockContent::Image { caption, .. } => caption.clone(),
_ => unreachable!(),
}
});
assert_eq!(cap_after, "Initial caption!");
let snap = frame(&app, win, &hw);
let (ix, iy) = center(&snap.elements["page.block.img-1.image_card"].bounds);
click_pt(&platform, &hw, ix, iy, 2, Modifiers::default());
platform.advance_clock(Duration::from_millis(200));
let snap_lb = frame(&app, win, &hw);
assert!(snap_lb.elements.contains_key("overlay.image_lightbox"));
assert!(
app.update(|cx| win.read(cx).unwrap().caption_editor.is_none()),
"the lightbox ends the caption edit under it"
);
assert!(!snap_lb.elements.contains_key("edgeless.caption_caret"));
save_evidence(&app, win, "active-note-image-lightbox-light.png");
app.update(|cx| {
win.update(cx, |v, _, cx| v.set_theme(PlaygroundTheme::Dark, cx))
.unwrap();
});
platform.run_until_parked();
let _ = frame(&app, win, &hw);
save_evidence(&app, win, "active-note-image-lightbox-dark.png");
}
#[test]
fn active_note_edgeless_readonly_blocks_database_image_resize_and_callout_writes() {
let (platform, app, win, _hw) = spawn_edgeless_view_with(
image_note_doc("active-note-readonly", 55),
PlaygroundTheme::Light,
true,
);
let blocks_before = child_ids(&app, win, "note-img");
type Gate = fn(&mut PlaygroundView, &mut ui::Window, &mut ui::Context<PlaygroundView>) -> bool;
let gates: [(&str, Gate); 3] = [
("database writes", |v, _, _| v.is_database_write_readonly()),
("callout child", |v, w, cx| {
!v.focus_or_create_callout_child("callout-1", w, cx)
}),
("image resize", |v, w, cx| {
v.image_resize_drag = Some(crate::ImageResizeDrag {
block_id: "img-1".into(),
side: crate::overlays::ImageResizeSide::Right,
start_x: 0.0,
start_w: 320.0,
start_h: 180.0,
max_w: 600.0,
aspect: 180.0 / 320.0,
align: blocksuite_playground_doc::read::TextAlign::Left,
preview_w: 400.0,
preview_h: 225.0,
moved: true,
via_touch: false,
});
v.finish_image_resize_drag(w, cx);
v.page_snapshot()
.and_then(|s| s.block("img-1"))
.and_then(|n| n.props.get("prop:width"))
.and_then(|w| w.as_f64())
== Some(320.0)
}),
];
for (name, gate) in gates {
let held = app.update(|cx| win.update(cx, |v, w, cx| gate(v, w, cx)).unwrap());
platform.run_until_parked();
assert!(held, "edgeless read-only must block {name}");
}
assert_eq!(child_ids(&app, win, "note-img"), blocks_before);
}
#[test]
fn active_note_drag_handle_reorders_blocks_in_one_undo_step() {
let mut doc = new_page_doc("active-note-dnd", 56);
let _ = doc
.workspace
.page_mut(HOME_PAGE_ID)
.unwrap()
.structural_edit(400, |p| {
p.add_block(
"note-dnd",
BlockSpec::Note {
xywh: Some("[0,0,640,360]".into()),
},
Some("root"),
None,
400,
)?;
for (id, text) in [("p-a", "Alpha"), ("p-b", "Bravo"), ("p-c", "Charlie")] {
p.add_block(
id,
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: text.into(),
},
Some("note-dnd"),
None,
400,
)?;
}
Ok(())
});
let (platform, app, win, hw) = spawn_edgeless_view(doc, PlaygroundTheme::Light);
enter_note_edit(&app, win, &hw, &platform, "note-dnd", (-120.0, -60.0), 1.25);
let screen = |id: &str| {
app.update(|cx| {
let v = win.read(cx).unwrap();
let (_, l, t) = v.active_overlay_target()?;
Some(t?.rect_to_screen(&l.block(id)?.rect()))
})
.expect("block rect")
};
let a = screen("p-a");
mouse(&hw, &platform, "move", a.x + 20.0, a.y + a.h * 0.5);
let snap = frame(&app, win, &hw);
let handle = snap
.elements
.get("overlay.drag_handle")
.expect("drag handle on the hovered Note block")
.bounds;
let (hx, hy) = center(&handle);
let c = screen("p-c");
mouse(&hw, &platform, "down", hx, hy);
mouse(&hw, &platform, "drag", hx + 4.0, hy + 20.0);
mouse(&hw, &platform, "drag", c.x + 20.0, c.bottom() - 2.0);
let snap = frame(&app, win, &hw);
assert!(snap.elements.contains_key("overlay.drop_indicator"));
mouse(&hw, &platform, "up", c.x + 20.0, c.bottom() - 2.0);
assert_eq!(child_ids(&app, win, "note-dnd"), ["p-b", "p-c", "p-a"]);
assert!(is_editing_note(&app, win));
undo(&app, win);
assert_eq!(child_ids(&app, win, "note-dnd"), ["p-a", "p-b", "p-c"]);
}
#[test]
fn active_note_linked_doc_card_opens_with_its_params() {
let mut doc = new_page_doc("active-note-embed", 57);
let page = doc.workspace.page_mut(HOME_PAGE_ID).unwrap();
let _ = page.structural_edit(500, |p| {
p.add_block(
"note-embed",
BlockSpec::Note {
xywh: Some("[0,0,640,360]".into()),
},
Some("root"),
None,
500,
)?;
p.add_block(
"embed-1",
BlockSpec::EmbedLinkedDoc {
page_id: "doc-target".into(),
style: "horizontal".into(),
caption: String::new(),
},
Some("note-embed"),
None,
500,
)?;
Ok(())
});
page.set_block_prop(
"embed-1",
"prop:params",
SessionValue::Any(Any::Object(Box::new(
[
("mode".to_string(), Any::String("edgeless".into())),
(
"elementIds".to_string(),
Any::Array(vec![Any::String("e1".into())]),
),
]
.into_iter()
.collect(),
))),
501,
)
.unwrap();
let (platform, app, win, hw) = spawn_edgeless_view(doc, PlaygroundTheme::Light);
enter_note_edit(
&app,
win,
&hw,
&platform,
"note-embed",
(-80.0, -50.0),
0.75,
);
let snap = frame(&app, win, &hw);
let (ex, ey) = center(&snap.elements["page.block.embed-1.embed_card"].bounds);
click_pt(&platform, &hw, ex, ey, 2, Modifiers::default());
let url = app
.update(|cx| win.read(cx).unwrap().last_opened_link_url.clone())
.expect("the card opens its URL");
assert!(url.contains("/doc-target?"), "{url}");
assert!(url.contains("mode=edgeless"), "{url}");
assert!(url.contains("elementIds=e1"), "{url}");
}
#[test]
fn active_note_page_flow_pass_runs_only_for_database_notes_and_only_on_change() {
let cases: [(&str, Option<&str>, u64); 2] = [
("plain note", None, 0),
("database note", Some("showcase-database"), 1),
];
for (name, database, expected) in cases {
let (doc, note_id) = match database {
None => {
let mut doc = new_page_doc("active-note-flow", 58);
let _ = doc
.workspace
.page_mut(HOME_PAGE_ID)
.unwrap()
.structural_edit(600, |p| {
p.add_block(
"note-plain",
BlockSpec::Note {
xywh: Some("[0,0,640,360]".into()),
},
Some("root"),
None,
600,
)?;
p.add_block(
"p-1",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: "Plain".into(),
},
Some("note-plain"),
None,
600,
)?;
Ok(())
});
(doc, "note-plain".to_string())
}
Some(_) => (seed_showcase_doc().unwrap(), String::new()),
};
let (platform, app, win, hw) = spawn_edgeless_view(doc, PlaygroundTheme::Light);
let note_id = if note_id.is_empty() {
first_note_id(&app, win)
} else {
note_id
};
enter_note_edit(&app, win, &hw, &platform, &note_id, (-40.0, -30.0), 1.0);
if let Some(db) = database {
let has_db = app.update(|cx| {
let v = win.read(cx).unwrap();
v.active_overlay_target()
.is_some_and(|(_, l, _)| l.block(db).is_some())
});
assert!(has_db, "{name}: the edited Note holds the database");
}
for _ in 0..3 {
let _ = frame(&app, win, &hw);
}
mouse(&hw, &platform, "move", 300.0, 300.0);
let _ = frame(&app, win, &hw);
let passes = app.update(|cx| win.read(cx).unwrap().active_note_flow.passes);
assert_eq!(passes, expected, "{name}");
}
}
fn table_note_doc(room: &str, client_id: u64) -> DocState {
let mut doc = new_page_doc(room, client_id);
let _ = doc
.workspace
.page_mut(HOME_PAGE_ID)
.unwrap()
.structural_edit(700, |p| {
p.add_block(
"note-tbl",
BlockSpec::Note {
xywh: Some("[0,0,640,420]".into()),
},
Some("root"),
None,
700,
)?;
p.add_block(
"tbl-1",
BlockSpec::Table {
rows: vec![
vec!["Hello World".into(), "".into()],
vec!["".into(), "".into()],
],
},
Some("note-tbl"),
None,
700,
)?;
Ok(())
});
doc
}
/// Window point of UTF-16 offset `off` in the first table cell, mapped through the camera
/// into a canvas whose top-left corner is at window point `canvas`.
fn first_cell_caret(
app: &ui::ApplicationHandle,
win: ui::WindowHandle<PlaygroundView>,
off: usize,
canvas: (f32, f32),
) -> (f32, f32) {
app.update(|cx| {
let v = win.read(cx).unwrap();
let layout = v.edgeless.cached_block_layout("note-tbl", true).unwrap();
let info = v.edgeless.authoring.painted_items.iter();
let info = info.clone().find(|i| i.id == "note-tbl").unwrap();
let b = layout.block("tbl-1").unwrap();
let c = b.body.table_cells.first().unwrap();
let (x, _) = c.text.caret(off);
let lh = c.text.line_height();
let pad = blocksuite_editor::edgeless::NOTE_CARD_PADDING;
let wx = info.rect.x + (pad + b.x + c.text_origin.0 + x) * info.scale;
let wy = info.rect.y + (pad + b.y + c.text_origin.1 + lh * 0.5) * info.scale;
let s = v.edgeless.camera.world_to_screen(
ui::point(ui::px(wx), ui::px(wy)),
ui::point(ui::px(canvas.0), ui::px(canvas.1)),
);
(f32::from(s.x), f32::from(s.y))
})
}
#[test]
fn active_note_table_caret_aligns_in_an_embedded_view() {
let (platform, app, win, hw) = spawn_edgeless_view(
table_note_doc("active-note-embedded", 61),
PlaygroundTheme::Light,
);
enter_note_edit(&app, win, &hw, &platform, "note-tbl", (-60.0, -40.0), 0.75);
// The host places the view at (240, 86) of its window, without the top bar.
app.update(|cx| {
win.update(cx, |v, _, _| {
v.hide_chrome = true;
v.embedded_probe.set(Some((240.0, 86.0, 1040.0, 714.0)));
})
.unwrap();
});
let (sx, sy) = first_cell_caret(&app, win, 5, (240.0, 86.0));
let selection = app.update(|cx| {
win.update(cx, |v, w, cx| {
let event = ui::MouseDownEvent {
button: ui::MouseButton::Left,
position: ui::point(ui::px(sx), ui::px(sy)),
modifiers: Modifiers::default(),
click_count: 1,
first_mouse: false,
};
v.on_edgeless_left_down(&event, w, cx);
v.active_table_cell().map(|c| c.input.shown_selection().0)
})
.unwrap()
});
assert_eq!(
selection,
Some(5..5),
"the press lands on the pressed character"
);
let t = app.update(|cx| {
win.read(cx)
.unwrap()
.active_overlay_target()
.unwrap()
.2
.unwrap()
});
let (lx, ly) = t.screen_to_local(sx, sy);
let back = t.rect_to_screen(&FlowRect::new(lx, ly, 0.0, 0.0));
assert!((back.x - sx).abs() < 0.01 && (back.y - sy).abs() < 0.01);
}
fn spawn_phone_edgeless_view(doc: DocState) -> TestHandles {
let platform = ui::HeadlessPlatform::new(390, 844, 1.0);
let app = ui::Application::with_platform(platform.clone()).run_embedded(|cx| {
crate::register_bundled_fonts(cx).unwrap();
});
let win = app
.update(|cx| {
cx.open_window(ui::WindowOptions::default(), |_window, cx| {
cx.new(|cx| {
let mut view = PlaygroundView::with_options(
crate::PlaygroundOptions {
mode: PlaygroundMode::Edgeless,
form_factor: crate::FormFactor::Phone,
..Default::default()
},
cx,
);
view.set_document(doc, cx);
view
})
})
})
.unwrap();
let hw = platform.windows().into_iter().next().unwrap();
platform.run_until_parked();
let _ = frame(&app, win, &hw);
(platform, app, win, hw)
}
#[test]
fn phone_active_note_table_cell_focus_docks_the_page_touch_table_bar() {
let (platform, app, win, hw) =
spawn_phone_edgeless_view(table_note_doc("active-note-phone", 62));
enter_note_edit(&app, win, &hw, &platform, "note-tbl", (-20.0, -40.0), 0.75);
let snap = frame(&app, win, &hw);
assert!(snap.elements.contains_key("chrome.edgeless_toolbar"));
let (sx, sy) = first_cell_caret(&app, win, 5, {
let o = app.update(|cx| win.read(cx).unwrap().canvas_origin());
(f32::from(o.x), f32::from(o.y))
});
click_pt(&platform, &hw, sx, sy, 1, Modifiers::default());
let snap = frame(&app, win, &hw);
assert!(app.update(|cx| win.read(cx).unwrap().active_table_cell().is_some()));
for id in ["overlay.table_toolbar", "overlay.table_toolbar.add_row"] {
assert!(snap.elements.contains_key(id), "missing {id}");
}
assert!(!snap.elements.contains_key("chrome.edgeless_toolbar"));
assert!(
!snap
.elements
.keys()
.any(|k| k.starts_with("overlay.table_hover."))
);
save_evidence(&app, win, "phone-active-note-table-bar-light.png");
}
#[test]
fn image_ne_corner_drag_resizes_in_page_and_active_note() {
for (mode, zoom) in [("page", 1.0), ("note", 0.75), ("note", 1.0), ("note", 1.5)] {
let (platform, app, win, hw) = spawn_edgeless_view(
image_note_doc("image-ne-corner", 63),
PlaygroundTheme::Light,
);
if mode == "page" {
app.update(|cx| {
win.update(cx, |v, _, cx| {
v.set_mode_immediate(PlaygroundMode::Page, cx)
})
.unwrap()
});
platform.run_until_parked();
} else {
enter_note_edit(&app, win, &hw, &platform, "note-img", (-80.0, -50.0), zoom);
}
let snap = frame(&app, win, &hw);
let (ix, iy) = center(&snap.elements["page.block.img-1.image_card"].bounds);
click_pt(&platform, &hw, ix, iy, 1, Modifiers::default());
let snap = frame(&app, win, &hw);
let (hx, hy) = center(&snap.elements["page.block.img-1.resize_ne"].bounds);
mouse(&hw, &platform, "move", hx, hy);
let _ = frame(&app, win, &hw);
// The image is centered, so each edge moves half of the width change.
let dx = 32.0 * zoom;
mouse(&hw, &platform, "down", hx, hy);
let _ = frame(&app, win, &hw);
mouse(&hw, &platform, "drag", hx - dx * 0.5, hy + 4.0);
mouse(&hw, &platform, "drag", hx - dx, hy + 8.0);
// The release lands on the `More` chip of the toolbar inside the image.
let snap = frame(&app, win, &hw);
let (mx, my) = center(&snap.elements["overlay.image_toolbar.more"].bounds);
mouse(&hw, &platform, "up", mx, my);
assert_eq!(image_width(&app, win), 256.0, "{mode} at {zoom}x");
undo(&app, win);
assert_eq!(image_width(&app, win), 320.0, "{mode} at {zoom}x");
}
}
#[test]
fn active_note_image_resize_owns_mouse_from_press_to_release_with_or_without_a_frame() {
for zoom in [0.75, 1.0, 1.5] {
for corner in ["nw", "ne", "sw", "se"] {
let timings: &[(bool, bool)] = if corner == "ne" {
&[(false, false), (true, false), (false, true), (true, true)]
} else {
&[(false, false), (false, true)]
};
for &(hover_before_press, draw_after_press) in timings {
let case = format!(
"{corner} at {zoom}x, frame before press: {hover_before_press}, after press: {draw_after_press}"
);
let (platform, app, win, hw) = spawn_edgeless_view(
image_note_doc("image-resize-event-order", 76),
PlaygroundTheme::Light,
);
enter_note_edit(&app, win, &hw, &platform, "note-img", (-80.0, -50.0), zoom);
let snap = frame(&app, win, &hw);
let (ix, iy) = center(&snap.elements["page.block.img-1.image_card"].bounds);
click_pt(&platform, &hw, ix, iy, 1, Modifiers::default());
let snap = frame(&app, win, &hw);
let (x, y) =
center(&snap.elements[&format!("page.block.img-1.resize_{corner}")].bounds);
let dx = if corner.ends_with('w') { 32.0 } else { -32.0 } * zoom;
let dy = if corner.starts_with('n') { 18.0 } else { -18.0 } * zoom;
let position = |step| ui::point(ui::px(x + dx * step), ui::px(y + dy * step));
if hover_before_press {
mouse(&hw, &platform, "move", x, y);
let _ = frame(&app, win, &hw);
}
hw.dispatch_input(ui::PlatformInput::MouseDown(ui::MouseDownEvent {
position: position(0.0),
button: ui::MouseButton::Left,
click_count: 1,
modifiers: Modifiers::default(),
first_mouse: false,
}));
if draw_after_press {
let _ = frame(&app, win, &hw);
}
for step in [0.5, 1.0] {
hw.dispatch_input(ui::PlatformInput::MouseMove(ui::MouseMoveEvent {
position: position(step),
pressed_button: Some(ui::MouseButton::Left),
modifiers: Modifiers::default(),
}));
}
hw.dispatch_input(ui::PlatformInput::MouseUp(ui::MouseUpEvent {
position: position(1.0),
button: ui::MouseButton::Left,
click_count: 1,
modifiers: Modifiers::default(),
}));
platform.run_until_parked();
let width = || {
super::active_note_interaction_tests::reopen_v1(&app, win)
.block("img-1")
.unwrap()
.props["prop:width"]
.as_f64()
.unwrap()
};
assert_eq!(width(), 256.0, "{case}");
undo(&app, win);
assert_eq!(width(), 320.0, "{case}");
}
}
}
}
@@ -8,7 +8,7 @@ use crate::{PlaygroundView, editor_session::DocumentSelection};
use super::{
EdgelessGesture, EdgelessTool, HandleKind, NOTE_CARD_PADDING, SpatialItemKind, normalized_rect,
point_in_rotated_rect, rotate_point_around,
rotate_point_around,
};
impl PlaygroundView {
@@ -56,52 +56,10 @@ impl PlaygroundView {
return;
}
// If currently inline-editing a Note/EdgelessText and clicking inside it, route to EditorSession.
if let Some((editing_id, is_note)) = self.edgeless.authoring.editing_spatial_block() {
let editing_id = editing_id.to_string();
if let Some(info) = self
.edgeless
.authoring
.painted_items
.iter()
.find(|i| i.id == editing_id)
.cloned()
&& point_in_rotated_rect(wx, wy, info.rect, info.rotate_deg)
{
let (cx_w, cy_w) = info.rect.center();
let (lx, ly) = rotate_point_around(wx, wy, cx_w, cy_w, -info.rotate_deg);
let pad = if is_note { NOTE_CARD_PADDING } else { 0.0 };
let flow_x = (lx - info.rect.x) / info.scale - pad;
let flow_y = (ly - info.rect.y) / info.scale - pad;
if let Some(layout) = self.edgeless.cached_block_layout(&editing_id, is_note)
&& let Some(pt) = Self::hit_test_flow_layout(&layout, flow_x, flow_y)
{
self.overlays.pointer_pressed(now_ms);
self.editor.slash_trigger = None;
let mut sel = DocumentSelection::caret(pt.clone());
if event.click_count >= 2 {
let s = self.block_text(&pt.block_id).unwrap_or("");
let range = if event.click_count == 2 {
crate::editor_session::word_range(s, pt.offset())
} else {
0..s.encode_utf16().count() as u64
};
sel.anchor =
crate::editor_session::DocPoint::new(&pt.block_id, range.start);
sel.focus = crate::editor_session::DocPoint::new(&pt.block_id, range.end);
self.editor.dragging = false;
} else if event.modifiers.shift
&& let Some(old) = &self.editor.selection
{
sel.anchor = old.anchor.clone();
self.editor.dragging = true;
} else {
self.editor.dragging = true;
}
self.change_selection(sel, window, cx);
return;
}
}
// If currently inline-editing a Note/EdgelessText (or clicking an open Active Note
// Database popover), dispatch through the Active Note interaction router.
if self.handle_active_note_left_down(event, wx, wy, window, cx) {
return;
}
// If currently inline-editing a label (Shape/Connector/SurfaceText/Frame) and clicking
@@ -318,13 +318,7 @@ impl PlaygroundView {
self.did_edgeless_doc_commit(commit, cx);
}
}
self.editor.selection = None;
self.editor.slash_trigger = None;
self.editor.linked_doc_trigger = None;
let now_ms = self.now_ms(cx);
self.overlays.close_slash(now_ms);
self.overlays.close_linked_doc(now_ms);
self.overlays.close_link_field();
self.clear_active_note_overlays(window.as_deref_mut(), cx);
self.announce_selection(cx);
if let Some(w) = window {
w.notify_text_input_changed(&self.editor_focus);
@@ -681,19 +675,19 @@ impl PlaygroundView {
.iter()
.find(|i| i.id == editing_id)?;
let pad = if is_note { NOTE_CARD_PADDING } else { 0.0 };
let topbar = point(px(0.0), px(self.topbar_height()));
let (vp_origin, _) = self.canvas_rect_cached();
let origin_screen = self.edgeless.camera.world_to_screen(
point(
px(info.rect.x + pad * info.scale),
px(info.rect.y + pad * info.scale),
),
topbar,
vp_origin,
);
let (cx, cy) = info.rect.center();
let pivot_screen = self
.edgeless
.camera
.world_to_screen(point(px(cx), px(cy)), topbar);
.world_to_screen(point(px(cx), px(cy)), vp_origin);
Some((
snapshot,
layout,
@@ -1,5 +1,12 @@
//! PlaygroundView glue for `blocksuite_editor::edgeless`.
#[cfg(test)]
mod active_note_database_tests;
mod active_note_gestures;
#[cfg(test)]
mod active_note_interaction_tests;
#[cfg(test)]
mod active_note_media_tests;
mod align_ops;
#[cfg(test)]
mod canvas_interaction_tests;
@@ -583,6 +583,7 @@ impl PlaygroundView {
.custom_doc_directory
.as_deref()
.unwrap_or(&self.default_doc_directory);
self.active_note_flow.invalidate();
let layout = Rc::new(self.flow.layout_changed(
&FlowInput {
snapshot: &snapshot,
+3
View File
@@ -257,6 +257,8 @@ pub struct PlaygroundView {
open_block_link: Option<block_link::OpenBlockLink>,
pub(crate) last_opened_link_url: Option<String>,
pub(crate) last_link_popup_caret: Option<(editor_session::DocPoint, u64)>,
/// Inputs of the last Page-flow pass over the edited Edgeless Note's database blocks.
pub(crate) active_note_flow: chrome::ActiveNoteFlowCache,
pub(crate) overlays: Overlays,
pub(crate) equation_snapshot: Option<blocksuite_playground_doc::session::SelectionSnapshot>,
pub(crate) calendar_clock: Option<CalendarClockFn>,
@@ -438,6 +440,7 @@ impl PlaygroundView {
open_block_link: None,
last_opened_link_url: None,
last_link_popup_caret: None,
active_note_flow: Default::default(),
overlays: Overlays::new(),
equation_snapshot: None,
calendar_clock: None,
@@ -65,7 +65,7 @@ pub(crate) use view_caption::normalize_caption_paste;
pub(crate) use view_context_menu::{ContextTargetKind, ContextTargetSnapshot};
pub(crate) use view_link_popup::LinkHoverPending;
pub use view_share_ingest::{SharedNoteBlockItem, SharedNoteBlockKind};
pub(crate) use view_table_cell::InlineTargetEnd;
pub(crate) use view_table_cell::{InlineTargetEnd, TablePaintFrame};
impl OverlayHost for crate::PlaygroundView {
fn block_url(&self, doc_id: &str, block_id: &str) -> String {
@@ -57,6 +57,12 @@ impl PlaygroundView {
let avail_win_h =
(self.window_size.1 - self.ime_insets.last_bottom).max(self.topbar_height());
let bottom_toolbar_inset = self.overlays.keyboard_toolbar_reserved_height(avail_win_h);
let (dx, dy) = self.view_window_offset();
let screen_transform = screen_transform.map(|t| OverlayScreenTransform {
origin: (t.origin.0 - dx, t.origin.1 - dy),
pivot: (t.pivot.0 - dx, t.pivot.1 - dy),
..t
});
OverlayScene {
snapshot,
layout,
@@ -153,6 +159,8 @@ impl PlaygroundView {
match &event {
OverlayEvent::OpenImageLightbox(_) => {
self.dismiss_all_database_authoring(None, cx);
// The modal lightbox ends any caption or cell edit under it.
self.finish_inline_targets(InlineTargetEnd::CommitPreedit, Some(window), Some(cx));
}
OverlayEvent::SetSelection(selection) => {
self.editor.dragging = false;
@@ -264,15 +264,28 @@ impl PlaygroundView {
cx: &mut Context<Self>,
) -> bool {
let (sx, sy) = (f32::from(event.position.x), f32::from(event.position.y));
let hit = self
.edgeless
.authoring
.painted_items
.iter()
.rev()
.filter(|item| item.kind == SpatialItemKind::SurfaceBlock && !item.locked)
.find(|item| self.caption_slot_contains(&item.id, sx, sy, window))
.map(|item| item.id.clone());
let active_note_hit =
self.edgeless
.authoring
.editing_spatial_block()
.and_then(|(editing_id, is_note)| {
let layout = self.edgeless.cached_block_layout(editing_id, is_note)?;
layout.blocks.iter().find_map(|block| {
(block.body.caption_slot.is_some()
&& self.caption_slot_contains(&block.block_id, sx, sy, window))
.then(|| block.block_id.clone())
})
});
let hit = active_note_hit.or_else(|| {
self.edgeless
.authoring
.painted_items
.iter()
.rev()
.filter(|item| item.kind == SpatialItemKind::SurfaceBlock && !item.locked)
.find(|item| self.caption_slot_contains(&item.id, sx, sy, window))
.map(|item| item.id.clone())
});
match hit {
Some(block_id) if !self.edgeless_readonly => {
self.focus_caption(
@@ -184,6 +184,7 @@ impl PlaygroundView {
if !drag.moved
|| unchanged
|| (self.mode == crate::PlaygroundMode::Page && self.page_readonly)
|| (self.mode == crate::PlaygroundMode::Edgeless && self.edgeless_readonly)
{
cx.notify();
return;
@@ -223,7 +224,9 @@ impl PlaygroundView {
) -> blocksuite_playground_doc::DocResult {
use blocksuite_playground_doc::{DocError, schema::BlockSpec};
if self.mode == crate::PlaygroundMode::Page && self.page_readonly {
if (self.mode == crate::PlaygroundMode::Page && self.page_readonly)
|| (self.mode == crate::PlaygroundMode::Edgeless && self.edgeless_readonly)
{
return Ok(());
}
let snapshot = self
@@ -535,7 +538,9 @@ impl PlaygroundView {
side,
start_x,
} => {
if self.mode == crate::PlaygroundMode::Page && self.page_readonly {
if (self.mode == crate::PlaygroundMode::Page && self.page_readonly)
|| (self.mode == crate::PlaygroundMode::Edgeless && self.edgeless_readonly)
{
return true;
}
let Some(layout) = self.flow_layout() else {
@@ -374,7 +374,9 @@ impl PlaygroundView {
window: &mut Window,
cx: &mut Context<Self>,
) -> bool {
if self.page_readonly {
if self.page_readonly
|| (self.mode == crate::PlaygroundMode::Edgeless && self.edgeless_readonly)
{
return false;
}
let first_child = self
@@ -1,7 +1,10 @@
//! PlaygroundView glue for desktop Page-mode thin scrollbar thumb dragging, track clicks,
//! and window-root pointer move/up dispatch.
use ui::{AnyElement, Context, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Window};
use ui::{
AnyElement, Context, DispatchPhase, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
Window, prelude::*,
};
use crate::{PlaygroundMode, PlaygroundView, theme::Palette};
@@ -14,7 +17,24 @@ impl PlaygroundView {
window: &mut Window,
cx: &mut Context<Self>,
) {
if self.mode == PlaygroundMode::Page {
if let Some(drag) = self.mouse_image_resize() {
let scale = self
.active_overlay_target()
.and_then(|(_, _, transform)| transform)
.map_or(1.0, |t| t.scale.max(0.1));
let x = drag.start_x + (f32::from(event.position.x) - drag.start_x) / scale;
if self.update_image_resize_drag(x, event.pressed_button == Some(MouseButton::Left), cx)
{
return;
}
}
let active_note = self.mode == PlaygroundMode::Edgeless
&& self
.edgeless
.authoring
.editing_spatial_block()
.is_some_and(|(_, n)| n);
if self.mode == PlaygroundMode::Page || active_note {
if self.database_authoring_mouse_move(event, window, cx) {
return;
}
@@ -25,6 +45,8 @@ impl PlaygroundView {
}
return;
}
}
if self.mode == PlaygroundMode::Page {
if event.pressed_button != Some(MouseButton::Left) {
if self.scrollbar_drag.take().is_some() {
cx.notify();
@@ -57,18 +79,23 @@ impl PlaygroundView {
return;
}
if self.mode == PlaygroundMode::Edgeless {
// An Active Note block drag moves through `PointerMoved` above, which resolves the
// drop slot through the Note's camera transform; the canvas must not see it.
if self.overlays.dragged_block().is_some() {
return;
}
if self.overlays.table_hover.add_drag.is_some()
|| self
.table_cell
.as_ref()
.is_some_and(|c| c.dragging || c.col_resize_drag.is_some())
{
self.table_cell_mouse_move(event, window, cx);
return;
}
self.on_edgeless_pointer_move(event, window, cx);
return;
}
if self.mode == PlaygroundMode::Page
&& self
.image_resize_drag
.as_ref()
.is_some_and(|d| !d.via_touch)
&& self.update_image_resize_drag(mx, pressed, cx)
{
return;
}
if self.mode == PlaygroundMode::Page
&& self.overlays.dragged_block().is_none()
&& !self.overlays.marquee_active()
@@ -96,8 +123,8 @@ impl PlaygroundView {
if self.database_record_sheet.is_some() {
return true;
}
self.flow_layout()
.is_some_and(|layout| self.database_popover_overlay(&layout, window).is_some())
self.active_overlay_target()
.is_some_and(|(_, layout, _)| self.database_popover_overlay(&layout, window).is_some())
}
pub(crate) fn root_mouse_up(
@@ -110,11 +137,7 @@ impl PlaygroundView {
cx.notify();
}
let _ = self.database_authoring_mouse_up(window, cx);
if self
.image_resize_drag
.as_ref()
.is_some_and(|d| !d.via_touch)
{
if self.mouse_image_resize().is_some() {
self.finish_image_resize_drag(window, cx);
}
self.finish_table_add_drag(window, cx);
@@ -125,7 +148,7 @@ impl PlaygroundView {
if let Some(ed) = self.caption_editor.as_mut() {
ed.dragging = false;
}
if self.mode == PlaygroundMode::Edgeless {
if self.mode == PlaygroundMode::Edgeless && self.overlays.dragged_block().is_none() {
self.on_edgeless_left_up(event, window, cx);
}
self.editor.drag_moved = false;
@@ -239,6 +262,13 @@ impl PlaygroundView {
self.editor.slash_trigger = None;
}
let mut els = self.overlays.popovers(&scene, palette, now_ms, window, cx);
els.extend(self.overlays.render_lightbox(
&scene,
&self.images,
palette,
now_ms,
cx,
));
els.extend(self.render_edgeless_table_toolbar(&layout, transform, palette, cx));
els
} else {
@@ -260,6 +290,29 @@ impl PlaygroundView {
));
out
}
} else if self.mode == PlaygroundMode::Edgeless
&& self.overlays.image_lightbox().is_some()
&& let Some(snapshot) = self.snapshot.clone()
{
let empty_layout = crate::block_flow::FlowLayout {
blocks: Vec::new(),
width: 0.0,
height: 0.0,
direction: window.layout_direction(),
stats: Default::default(),
};
let scene = self.overlay_scene_with_transform(
&snapshot,
&empty_layout,
window.layout_direction(),
None,
None,
&local_collapsed,
);
self.overlays
.render_lightbox(&scene, &self.images, palette, now_ms, cx)
.into_iter()
.collect()
} else {
Vec::new()
};
@@ -270,6 +323,46 @@ impl PlaygroundView {
window,
cx,
));
elements.push(Self::image_resize_pointer_capture(cx));
elements
}
fn mouse_image_resize(&self) -> Option<&crate::ImageResizeDrag> {
self.image_resize_drag
.as_ref()
.filter(|drag| !drag.via_touch)
}
fn image_resize_pointer_capture(cx: &Context<Self>) -> AnyElement {
let on_move = cx.listener(|this, event: &MouseMoveEvent, window, cx| {
if this.mouse_image_resize().is_some() {
this.root_mouse_move(event, window, cx);
cx.stop_propagation();
}
});
let on_up = cx.listener(|this, event: &MouseUpEvent, window, cx| {
if this.mouse_image_resize().is_some() {
this.root_mouse_up(event, window, cx);
cx.stop_propagation();
}
});
// Listen before the resize starts so the current frame can route the next event.
ui::canvas(
|_, _, _| (),
move |_, (), window, _| {
window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
if phase == DispatchPhase::Capture {
on_move(event, window, cx);
}
});
window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
if phase == DispatchPhase::Capture && event.button == MouseButton::Left {
on_up(event, window, cx);
}
});
},
)
.absolute()
.into_any_element()
}
}
@@ -7,6 +7,8 @@ mod structure;
mod toolbar;
mod touch_bar;
pub(crate) use pointer::TablePaintFrame;
use std::rc::Rc;
use blocksuite_editor::inline_input::{TextSplice, utf16_len};
@@ -176,20 +178,27 @@ impl PlaygroundView {
let _ = page.stop_capturing();
}
if let Some((sx, sy)) = screen_pos {
let (origin, canvas_size) = self.canvas_rect(window);
let geom = self.current_page_geometry(f32::from(canvas_size.width));
if let Some(layout) = self.ensure_layout(geom.column_width, window)
let target = match self.active_note_table_target() {
Some((layout, t)) => Some((layout, Some(t))),
None => {
let (_, canvas_size) = self.canvas_rect(window);
let geom = self.current_page_geometry(f32::from(canvas_size.width));
self.ensure_layout(geom.column_width, window)
.map(|layout| (layout, None))
}
};
if let Some((layout, transform)) = target
&& let Some((bx, by, hit)) =
Self::find_table_cell_hit(&layout, &block_id, &row_id, &column_id)
&& let Some(cell) = self.table_cell.as_mut()
{
let local_x = sx - f32::from(origin.x) - geom.column_x - bx
+ self.overlays.code_scroll_x(&block_id);
let local_y = sy - f32::from(origin.y) + self.scroll_y - by;
let off = hit
.hit_text(local_x, local_y, &cell.input.text)
.utf16_offset as usize;
apply_pointer_sel(cell, off, true);
let (local_x, local_y) =
self.table_cell_local_point(transform, &block_id, (bx, by), sx, sy, window);
if let Some(cell) = self.table_cell.as_mut() {
let off = hit
.hit_text(local_x, local_y, &cell.input.text)
.utf16_offset as usize;
apply_pointer_sel(cell, off, true);
}
}
} else if let Some(cell) = self.table_cell.as_mut() {
cell.dragging = false;
@@ -225,8 +234,12 @@ impl PlaygroundView {
.unwrap_or_default();
let mut cell = InlineTableCell::new(block_id, row_id, column_id, initial.clone());
let target = match self.active_note_table_target() {
Some((layout, t)) => Some((layout, Some(t))),
None => self.flow_layout().map(|layout| (layout, None)),
};
if let Some((sx, sy)) = screen_pos
&& let Some(layout) = self.flow_layout()
&& let Some((layout, transform)) = target
&& let Some((bx, by, hit)) = Self::find_table_cell_hit(
&layout,
&cell.block_id,
@@ -234,11 +247,14 @@ impl PlaygroundView {
&cell.column_id,
)
{
let (origin, canvas_size) = self.canvas_rect(window);
let geom = self.current_page_geometry(f32::from(canvas_size.width));
let local_x = sx - f32::from(origin.x) - geom.column_x - bx
+ self.overlays.code_scroll_x(&cell.block_id);
let local_y = sy - f32::from(origin.y) + self.scroll_y - by;
let (local_x, local_y) = self.table_cell_local_point(
transform,
&cell.block_id,
(bx, by),
sx,
sy,
window,
);
let off = hit.hit_text(local_x, local_y, &initial).utf16_offset as usize;
apply_pointer_sel(&mut cell, off, false);
}
@@ -1,14 +1,14 @@
//! Table cell preedit snapshot patching, hit-testing, IME bounds, and focus/caret/selection painting.
use std::ops::Range;
//! Table cell preedit snapshot patching, focus/caret/selection painting, axis previews, and the
//! Active Note table controls.
use blocksuite_playground_doc::{
read::{BlockContent, TableCell},
session::split_delta,
};
use ui::{Bounds, Pixels, Point, Window, div, prelude::*, px};
use ui::{div, prelude::*, px};
use y_octo::{TextDeltaOp, TextInsert};
use super::TablePaintFrame;
use crate::{
PlaygroundView,
block_flow::{FlowLayout, FlowRect, PAGE_SURFACE_ID, PageViewport},
@@ -77,6 +77,25 @@ impl PlaygroundView {
viewport: PageViewport,
width: f32,
palette: &Palette,
) -> Option<ui::AnyElement> {
let height = viewport.height;
self.table_axis_preview_in(
block,
TablePaintFrame::Page(viewport),
width,
height,
palette,
)
}
/// Axis highlight and add/trim preview of `block`, clipped to the `width` × `height` layer.
pub(super) fn table_axis_preview_in(
&self,
block: &crate::block_flow::FlowBlock,
frame: TablePaintFrame,
width: f32,
height: f32,
palette: &Palette,
) -> Option<ui::AnyElement> {
use blocksuite_editor::overlays::TableAxisMenu;
@@ -96,8 +115,7 @@ impl PlaygroundView {
}
let cells = &block.body.table_cells;
let first = cells.first()?;
let ox = viewport.column_x + block.x - self.overlays.code_scroll_x(&block.block_id);
let oy = block.y - viewport.scroll_y;
let scroll_x = self.overlays.code_scroll_x(&block.block_id);
let mut rects = Vec::new();
let mut dashed = false;
let mut id = "overlay.table_toolbar.axis_selection";
@@ -144,7 +162,7 @@ impl PlaygroundView {
} else {
id = "overlay.table_hover.grow_preview";
dashed = true;
let rtl = self.flow_layout()?.direction == ui::Direction::Rtl;
let rtl = self.active_overlay_target()?.1.direction == ui::Direction::Rtl;
let added_width = cols as f32 * 120.0;
let offset = if rtl { added_width } else { 0.0 };
let start = if rtl { first.rect.x } else { last.rect.right() };
@@ -169,21 +187,18 @@ impl PlaygroundView {
}
}
}
let left = (viewport.column_x + block.x).max(0.0);
let body = frame.map(FlowRect::new(block.x, block.y, block.body.width, 0.0));
let left = body.x.max(0.0);
let right = if dashed {
width
} else {
width.min(viewport.column_x + block.x + block.body.width)
width.min(body.right())
};
rects.retain_mut(|r| {
let x = (ox + r.x).max(left);
let y = (oy + r.y).max(0.0);
*r = FlowRect::new(
x,
y,
(ox + r.right()).min(right) - x,
(oy + r.bottom()).min(viewport.height) - y,
);
let m = frame.map(r.translated(block.x - scroll_x, block.y));
let x = m.x.max(left);
let y = m.y.max(0.0);
*r = FlowRect::new(x, y, m.right().min(right) - x, m.bottom().min(height) - y);
r.w > 0.0 && r.h > 0.0
});
let first = rects.first()?;
@@ -235,7 +250,10 @@ impl PlaygroundView {
cx: &mut ui::Context<Self>,
) -> Vec<ui::AnyElement> {
let mut out = Vec::new();
if self.table_is_readonly() || self.database_record_sheet.is_some() {
if self.table_is_readonly()
|| self.database_record_sheet.is_some()
|| self.active_note_touch_table_bar(self.window_size.0)
{
return out;
}
let Some(cell) = self.table_cell.as_ref() else {
@@ -251,10 +269,11 @@ impl PlaygroundView {
return out;
};
let screen = t.rect_to_screen(&FlowRect::new(block.x, block.y, block.body.width, 40.0));
let (dx, dy) = self.view_window_offset();
out.push(self.build_table_axis_menu(
axis_menu,
screen.x,
(screen.y + 8.0).max(self.topbar_height() + 8.0),
screen.x - dx,
(screen.y - dy + 8.0).max(self.topbar_height() + 8.0),
self.window_size.1,
self.window_size.0,
palette,
@@ -263,6 +282,294 @@ impl PlaygroundView {
out
}
/// Whether the edited Note shows the touch table bar of the Page in place of the desktop
/// table controls and the canvas toolbar: a writable table cell is focused on a touch host
/// or in a viewport narrower than 600 px.
pub(crate) fn active_note_touch_table_bar(&self, viewport_width: f32) -> bool {
(self.is_touch_host() || viewport_width < 600.0)
&& self.table_cell.is_some()
&& !self.table_is_readonly()
&& self.database_record_sheet.is_none()
&& self.active_note_table_target().is_some()
}
/// Focus ring, selection, caret, axis preview, add bars with corner, column resize
/// dividers, and axis pills of the table being edited inside an Edgeless Active Note, all
/// mapped through `frame` (controls keep their screen size at every zoom).
pub(crate) fn active_note_table_elements(
&self,
layout: &FlowLayout,
frame: TablePaintFrame,
palette: &Palette,
caret_alpha: f32,
cx: &mut ui::Context<Self>,
) -> Vec<ui::AnyElement> {
use blocksuite_editor::overlays::{
TableAddDrag, TableAddDragKind, TableAxisMenu, TableColResizeDrag,
};
use ui::{CursorStyle, MouseButton, MouseDownEvent, SharedString};
let mut out = self.table_cell_paint(layout, frame, palette, caret_alpha);
let Some((width, height)) = frame.extent() else {
return out;
};
let cell = self.table_cell.as_ref();
let Some(block_id) = self
.overlays
.table_hover
.add_drag
.as_ref()
.map(|d| d.block_id.as_str())
.or_else(|| cell.map(|c| c.block_id.as_str()))
else {
return out;
};
let Some(block) = layout.block(block_id) else {
return out;
};
out.extend(self.table_axis_preview_in(block, frame, width, height, palette));
if self.table_is_readonly() || block.body.table_cells.is_empty() {
return out;
}
if self.active_note_touch_table_bar(width) {
let v = PageViewport {
column_x: 0.0,
height,
scroll_y: 0.0,
};
out.push(self.build_touch_table_toolbar(v, width, palette, cx));
return out;
}
let scroll_x = self.overlays.code_scroll_x(block_id);
let cells = &block.body.table_cells;
let (l, t, r, b) = cells.iter().fold(
(f32::INFINITY, f32::INFINITY, f32::MIN, f32::MIN),
|(l, t, r, b), c| {
(
l.min(c.rect.x),
t.min(c.rect.y),
r.max(c.rect.right()),
b.max(c.rect.bottom()),
)
},
);
let at = |x: f32, y: f32, w: f32, h: f32| {
div()
.absolute()
.left(px(x.round()))
.top(px(y.round()))
.w(px(w))
.h(px(h))
};
let table = frame.map(FlowRect::new(
block.x + l - scroll_x,
block.y + t,
r - l,
b - t,
));
let scale = match frame {
TablePaintFrame::Note { transform, .. } => transform.scale,
TablePaintFrame::Page(_) => 1.0,
};
let blue = palette
.theme
.css_var("--affine-v2-table-indicator-activated")
.unwrap_or(palette.brand);
// Column resize dividers on the first row's right borders.
let first_row = cells[0].row_id.clone();
for hit in cells.iter().filter(|c| c.row_id == first_row) {
let drag = cell
.and_then(|c| c.col_resize_drag.as_ref())
.filter(|d| d.column_id == hit.column_id);
let shift = drag.map_or(0.0, |d| (d.preview_width - d.start_width) * scale);
let edge = frame
.map(FlowRect::new(
block.x + hit.rect.right() - scroll_x,
block.y,
0.0,
0.0,
))
.x
+ shift;
let (bid, rid, col_id, col_w) = (
block_id.to_string(),
first_row.clone(),
hit.column_id.clone(),
hit.rect.w,
);
out.push(
at(edge - 2.5, table.y, 5.0, table.h)
.id(SharedString::from(format!("an-tbl-col-resize-{col_id}")))
.flex()
.justify_center()
.cursor(CursorStyle::ResizeLeftRight)
.on_mouse_down(
MouseButton::Left,
cx.listener(move |this, ev: &MouseDownEvent, win, cx| {
cx.stop_propagation();
if this.table_cell.as_ref().is_none_or(|c| c.block_id != bid) {
let (b, r, c) = (bid.clone(), rid.clone(), col_id.clone());
this.focus_table_cell(b, r, c, None, win, cx);
}
if let Some(cell) = this.table_cell.as_mut() {
cell.col_resize_drag = Some(TableColResizeDrag {
column_id: col_id.clone(),
start_screen_x: f32::from(ev.position.x),
start_width: col_w,
preview_width: col_w,
});
}
cx.notify();
}),
)
.child(
div()
.w(px(2.0))
.h(px(table.h))
.when(drag.is_some(), |d| d.bg(blue))
.snapshot(
SharedString::from(format!(
"overlay.table_col_resize.{}",
hit.column_id
)),
Some("root.canvas"),
),
)
.into_any_element(),
);
}
// Add bars: right (columns), bottom (rows), and the corner (both).
let bar_bg = palette
.theme
.css_var("--affine-v2-table-indicator-hover")
.unwrap_or(palette.hover);
for (kind, rect, snap, cursor) in [
(
TableAddDragKind::Column,
FlowRect::new(table.right() + 2.0, table.y, 16.0, table.h),
"overlay.table_hover.add_col",
CursorStyle::ResizeLeftRight,
),
(
TableAddDragKind::Row,
FlowRect::new(table.x, table.bottom() + 2.0, table.w, 16.0),
"overlay.table_hover.add_row",
CursorStyle::ResizeUpDown,
),
(
TableAddDragKind::Both,
FlowRect::new(table.right() + 2.0, table.bottom() + 2.0, 16.0, 16.0),
"overlay.table_hover.add_corner",
CursorStyle::ResizeUpLeftDownRight,
),
] {
if rect.right() > width || rect.bottom() > height {
continue;
}
let bid = block_id.to_string();
let (rows, cols) = match kind {
TableAddDragKind::Row => (1, 0),
TableAddDragKind::Column => (0, 1),
TableAddDragKind::Both => (1, 1),
};
out.push(
at(rect.x, rect.y, rect.w, rect.h)
.id(snap)
.rounded(px(4.0))
.bg(bar_bg)
.flex()
.items_center()
.justify_center()
.cursor(cursor)
.text_size(px(12.0))
.text_color(palette.text_secondary)
.on_mouse_down(
MouseButton::Left,
cx.listener(move |this, ev: &MouseDownEvent, _, cx| {
cx.stop_propagation();
this.overlays.table_hover.add_drag = Some(TableAddDrag {
block_id: bid.clone(),
kind,
start_screen: (f32::from(ev.position.x), f32::from(ev.position.y)),
preview_rows: rows,
preview_cols: cols,
moved: false,
});
cx.notify();
}),
)
.snapshot(snap, Some("root.canvas"))
.snapshot_text("+")
.child("+")
.into_any_element(),
);
}
// Three-dot axis pills beside the focused cell's column and row.
let Some(cell) = cell.filter(|c| c.block_id == block_id) else {
return out;
};
let Some(hit) = cells
.iter()
.find(|c| c.row_id == cell.row_id && c.column_id == cell.column_id)
else {
return out;
};
let focus = frame.map(hit.rect.translated(block.x - scroll_x, block.y));
for (axis, rect, snap) in [
(
TableAxisMenu::Column,
FlowRect::new(focus.x + focus.w * 0.5 - 14.0, table.y - 18.0, 28.0, 16.0),
"overlay.table_hover.col_pill",
),
(
TableAxisMenu::Row,
FlowRect::new(table.x - 18.0, focus.y + focus.h * 0.5 - 14.0, 16.0, 28.0),
"overlay.table_hover.row_pill",
),
] {
let (bid, rid, cid) = (
block_id.to_string(),
cell.row_id.clone(),
cell.column_id.clone(),
);
let dot = || {
div()
.w(px(3.0))
.h(px(3.0))
.rounded(px(1.5))
.bg(palette.icon)
};
out.push(
at(rect.x, rect.y, rect.w, rect.h)
.id(snap)
.rounded(px(8.0))
.bg(palette.panel)
.border_1()
.border_color(palette.border)
.flex()
.when(axis == TableAxisMenu::Row, |d| d.flex_col())
.items_center()
.justify_center()
.gap(px(2.5))
.cursor_pointer()
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, _, win, cx| {
let (b, r, c) = (bid.clone(), rid.clone(), cid.clone());
this.open_table_axis_menu_for(b, r, c, axis, win, cx);
}))
.snapshot(snap, Some("root.canvas"))
.child(dot())
.child(dot())
.child(dot())
.into_any_element(),
);
}
out
}
/// Splice any active table cell IME preedit into a cloned snapshot using `split_delta` so
/// all existing formatting marks (bold, code, link, chips) left and right of the preedit
/// stay 100% intact.
@@ -287,7 +594,7 @@ impl PlaygroundView {
block_id: &str,
row_id: &str,
column_id: &str,
rep: &Range<usize>,
rep: &std::ops::Range<usize>,
pre_text: &str,
display: &str,
) -> bool {
@@ -346,62 +653,6 @@ impl PlaygroundView {
)
}
/// Map a screen-space pointer location to a UTF-16 offset inside the focused table cell,
/// accounting for any horizontal scroll offset of a wide table.
pub(crate) fn table_cell_character_index_for_point(
&self,
p: Point<Pixels>,
w: &Window,
) -> Option<usize> {
let cell = self.table_cell.as_ref()?;
let layout = self.flow_layout()?;
let (bx, by, hit) =
Self::find_table_cell_hit(&layout, &cell.block_id, &cell.row_id, &cell.column_id)?;
let scroll_x = self.overlays.code_scroll_x(&cell.block_id);
let (origin, canvas_size) = self.canvas_rect(w);
let geom = self.current_page_geometry(f32::from(canvas_size.width));
let local_x = f32::from(p.x) - f32::from(origin.x) - geom.column_x - bx + scroll_x;
let local_y = f32::from(p.y) - f32::from(origin.y) + self.scroll_y - by;
hit.rect.contains(local_x, local_y).then(|| {
hit.hit_text(local_x, local_y, &cell.input.display_text())
.utf16_offset as usize
})
}
/// Screen-space IME candidate bounds for the focused table cell, accounting for horizontal
/// table scroll.
pub(crate) fn table_cell_selection_bounds(
&self,
r: Range<usize>,
layout: &FlowLayout,
w: &Window,
) -> Vec<Bounds<Pixels>> {
let Some((scroll_x, bx, by, hit)) = self.table_cell.as_ref().and_then(|cell| {
let scroll_x = self.overlays.code_scroll_x(&cell.block_id);
let (bx, by, hit) =
Self::find_table_cell_hit(layout, &cell.block_id, &cell.row_id, &cell.column_id)?;
Some((scroll_x, bx, by, hit))
}) else {
return Vec::new();
};
let (lh, ox, oy) = (
hit.text.line_height(),
bx + hit.text_origin.0 - scroll_x,
by + hit.text_origin.1,
);
let mut rects: Vec<FlowRect> = hit
.text
.selection_spans(r.start, r.end)
.into_iter()
.map(|(line, a, b)| FlowRect::new(ox + a, oy + line as f32 * lh, (b - a).max(1.0), lh))
.collect();
if rects.is_empty() {
let (cx, line) = hit.text.caret(r.start);
rects.push(FlowRect::new(ox + cx, oy + line as f32 * lh, 1.5, lh));
}
rects.into_iter().map(|r| self.screen_rect(r, w)).collect()
}
/// In-place visual elements for a focused table cell: 1.5px brand focus border,
/// selection highlight band, IME preedit underline, and live caret (shifted by any
/// horizontal table scroll and clipped to the table viewport width).
@@ -411,6 +662,16 @@ impl PlaygroundView {
v: PageViewport,
palette: &Palette,
caret_alpha: f32,
) -> Vec<ui::AnyElement> {
self.table_cell_paint(layout, TablePaintFrame::Page(v), palette, caret_alpha)
}
fn table_cell_paint(
&self,
layout: &FlowLayout,
frame: TablePaintFrame,
palette: &Palette,
caret_alpha: f32,
) -> Vec<ui::AnyElement> {
let mut out = Vec::new();
let Some(cell) = self.table_cell.as_ref() else {
@@ -432,21 +693,32 @@ impl PlaygroundView {
let right = r.right().min(vis_right);
(right > left).then(|| FlowRect::new(left, r.y, right - left, r.h))
};
let place = |r: FlowRect| {
let m = frame.map(r);
div()
.absolute()
.left(px(m.x))
.top(px(m.y))
.w(px(m.w))
.h(px(m.h))
};
let line = |r: FlowRect, h: f32| {
let m = frame.map(r);
div()
.absolute()
.left(px(m.x))
.top(px(m.bottom() - h))
.w(px(m.w))
.h(px(h))
};
let cell_world = hit.rect.translated(bx - scroll_x, by);
if cell_world.bottom() < v.scroll_y || cell_world.y > v.scroll_y + v.height {
if !frame.intersects(&cell_world) {
return out;
}
if let Some(clipped) = clip_x(cell_world) {
let mut ring = div()
.absolute()
.left(px(v.column_x + clipped.x))
.top(px(clipped.y - v.scroll_y))
.w(px(clipped.w))
.h(px(clipped.h))
.border(px(1.5))
.border_color(palette.brand);
if v.fully_visible(&clipped) {
let mut ring = place(clipped).border(px(1.5)).border_color(palette.brand);
if frame.fully_visible(&clipped) {
ring = ring
.snapshot("page.table_cell_focus", Some(PAGE_SURFACE_ID))
.snapshot_focused(true)
@@ -462,67 +734,39 @@ impl PlaygroundView {
let marked = cell.input.marked_range();
if let Some(marked) = &marked {
for (line, a, b) in hit.text.selection_spans(marked.start, marked.end) {
let y = oy + line as f32 * lh + lh - 1.0;
if let Some(clipped) = clip_x(FlowRect::new(ox + a, y, (b - a).max(1.0), 1.0)) {
for (line_idx, a, b) in hit.text.selection_spans(marked.start, marked.end) {
let span = FlowRect::new(ox + a, oy + line_idx as f32 * lh, (b - a).max(1.0), lh);
if let Some(clipped) = clip_x(span) {
out.push(
div()
.absolute()
.left(px(v.column_x + clipped.x))
.top(px(clipped.y - v.scroll_y))
.w(px(clipped.w))
.h(px(1.0))
line(clipped, 1.0)
.bg(palette.text_secondary)
.into_any_element(),
);
}
}
if !sel.is_empty() {
for (line, a, b) in hit.text.selection_spans(sel.start, sel.end) {
let span = FlowRect::new(ox + a, oy + line as f32 * lh, (b - a).max(1.0), lh);
for (line_idx, a, b) in hit.text.selection_spans(sel.start, sel.end) {
let span =
FlowRect::new(ox + a, oy + line_idx as f32 * lh, (b - a).max(1.0), lh);
if let Some(c) = clip_x(span) {
out.push(
div()
.absolute()
.left(px(v.column_x + c.x))
.top(px(c.y - v.scroll_y))
.w(px(c.w))
.h(px(c.h))
.bg(palette.brand.opacity(0.18))
.into_any_element(),
);
out.push(
div()
.absolute()
.left(px(v.column_x + c.x))
.top(px(c.y + c.h - 2.0 - v.scroll_y))
.w(px(c.w))
.h(px(2.0))
.bg(palette.brand)
.into_any_element(),
);
out.push(place(c).bg(palette.brand.opacity(0.18)).into_any_element());
out.push(line(c, 2.0).bg(palette.brand).into_any_element());
}
}
}
} else if !sel.is_empty() {
let mut first = true;
for (line, a, b) in hit.text.selection_spans(sel.start, sel.end) {
for (line_idx, a, b) in hit.text.selection_spans(sel.start, sel.end) {
let Some(r) = clip_x(FlowRect::new(
ox + a,
oy + line as f32 * lh,
oy + line_idx as f32 * lh,
(b - a).max(1.0),
lh,
)) else {
continue;
};
let mut d = div()
.absolute()
.left(px(v.column_x + r.x))
.top(px(r.y - v.scroll_y))
.w(px(r.w))
.h(px(r.h))
.bg(palette.brand.opacity(0.22));
if v.fully_visible(&r) && std::mem::take(&mut first) {
let mut d = place(r).bg(palette.brand.opacity(0.22));
if frame.fully_visible(&r) && std::mem::take(&mut first) {
d = d.snapshot("page.selection", Some(PAGE_SURFACE_ID));
}
out.push(d.into_any_element());
@@ -530,21 +774,16 @@ impl PlaygroundView {
}
let caret_u16 = if reversed { sel.start } else { sel.end };
let (cx_local, line) = hit.text.caret(caret_u16);
let caret_rect = FlowRect::new(ox + cx_local, oy + line as f32 * lh, 1.5, lh);
if caret_rect.bottom() >= v.scroll_y
&& caret_rect.y <= v.scroll_y + v.height
let (cx_local, line_idx) = hit.text.caret(caret_u16);
let caret_rect = FlowRect::new(ox + cx_local, oy + line_idx as f32 * lh, 1.5, lh);
if frame.intersects(&caret_rect)
&& caret_rect.right() > vis_left
&& caret_rect.x < vis_right
{
let mut caret_el = div()
.absolute()
.left(px(v.column_x + caret_rect.x))
.top(px(caret_rect.y - v.scroll_y))
let mut caret_el = place(caret_rect)
.w(px(1.5))
.h(px(caret_rect.h))
.bg(palette.brand.opacity(caret_alpha));
if v.fully_visible(&caret_rect) {
if frame.fully_visible(&caret_rect) {
caret_el = caret_el.snapshot("page.table_cell_caret", Some(PAGE_SURFACE_ID));
}
out.push(caret_el.into_any_element());
@@ -1,15 +1,135 @@
//! Pointer drag selection and horizontal/vertical viewport reveal for focused `affine:table` cells.
//! Pointer mapping (Page column or Active Note camera), hit-testing, IME bounds, drag selection,
//! and horizontal/vertical viewport reveal for focused `affine:table` cells.
use ui::{Context, MouseButton, MouseMoveEvent, Window};
use std::{ops::Range, rc::Rc};
use ui::{Bounds, Context, MouseButton, MouseMoveEvent, Pixels, Point, Window, point, px};
use y_octo::{Any, TextAttributes, TextDeltaOp, TextInsert};
use super::{TableAddDragKind as Kind, TableCellDragMode};
use crate::{
PlaygroundView,
overlays::{LinkedDocMenuState, Presence},
PlaygroundMode, PlaygroundView,
block_flow::{FlowLayout, FlowRect, PageViewport},
overlays::{LinkedDocMenuState, OverlayScreenTransform, Presence},
};
impl PlaygroundView {
/// Layout holding the edited Edgeless Note's tables and its camera mapping, while a Note is
/// edited; `None` in Page mode, where tables live in the Page column.
pub(crate) fn active_note_table_target(
&self,
) -> Option<(Rc<FlowLayout>, OverlayScreenTransform)> {
if self.mode != PlaygroundMode::Edgeless {
return None;
}
let (_, layout, transform) = self.active_overlay_target()?;
Some((layout, transform?))
}
/// Map a screen point into the flow coordinates of `transform`'s Note, or of the Page column.
pub(super) fn table_screen_to_flow(
&self,
transform: Option<OverlayScreenTransform>,
sx: f32,
sy: f32,
window: &Window,
) -> (f32, f32) {
if let Some(t) = transform {
return t.screen_to_local(sx, sy);
}
let (origin, canvas_size) = self.canvas_rect(window);
let geom = self.current_page_geometry(f32::from(canvas_size.width));
(
sx - f32::from(origin.x) - geom.column_x,
sy - f32::from(origin.y) + self.scroll_y,
)
}
/// Cell-local point of the focused-cell `hit` of the table at `(bx, by)` under `(sx, sy)`.
#[allow(clippy::too_many_arguments)]
pub(super) fn table_cell_local_point(
&self,
transform: Option<OverlayScreenTransform>,
block_id: &str,
(bx, by): (f32, f32),
sx: f32,
sy: f32,
window: &Window,
) -> (f32, f32) {
let (fx, fy) = self.table_screen_to_flow(transform, sx, sy, window);
(fx - bx + self.overlays.code_scroll_x(block_id), fy - by)
}
/// Map a screen-space pointer location to a UTF-16 offset inside the focused table cell,
/// accounting for any horizontal scroll offset of a wide table.
pub(crate) fn table_cell_character_index_for_point(
&self,
p: Point<Pixels>,
w: &Window,
) -> Option<usize> {
let cell = self.table_cell.as_ref()?;
let (layout, transform) = match self.active_note_table_target() {
Some((layout, t)) => (layout, Some(t)),
None => (self.flow_layout()?, None),
};
let (bx, by, hit) =
Self::find_table_cell_hit(&layout, &cell.block_id, &cell.row_id, &cell.column_id)?;
let (local_x, local_y) = self.table_cell_local_point(
transform,
&cell.block_id,
(bx, by),
f32::from(p.x),
f32::from(p.y),
w,
);
hit.rect.contains(local_x, local_y).then(|| {
hit.hit_text(local_x, local_y, &cell.input.display_text())
.utf16_offset as usize
})
}
/// Screen-space IME candidate bounds for the focused table cell, accounting for horizontal
/// table scroll and, inside an Active Note, the camera.
pub(crate) fn table_cell_selection_bounds(
&self,
r: Range<usize>,
layout: &FlowLayout,
w: &Window,
) -> Vec<Bounds<Pixels>> {
let note = self.active_note_table_target();
let layout = note.as_ref().map_or(layout, |(l, _)| l.as_ref());
let Some((scroll_x, bx, by, hit)) = self.table_cell.as_ref().and_then(|cell| {
let scroll_x = self.overlays.code_scroll_x(&cell.block_id);
let (bx, by, hit) =
Self::find_table_cell_hit(layout, &cell.block_id, &cell.row_id, &cell.column_id)?;
Some((scroll_x, bx, by, hit))
}) else {
return Vec::new();
};
let (lh, ox, oy) = (
hit.text.line_height(),
bx + hit.text_origin.0 - scroll_x,
by + hit.text_origin.1,
);
let mut rects: Vec<FlowRect> = hit
.text
.selection_spans(r.start, r.end)
.into_iter()
.map(|(line, a, b)| FlowRect::new(ox + a, oy + line as f32 * lh, (b - a).max(1.0), lh))
.collect();
if rects.is_empty() {
let (cx, line) = hit.text.caret(r.start);
rects.push(FlowRect::new(ox + cx, oy + line as f32 * lh, 1.5, lh));
}
rects
.into_iter()
.map(|r| match &note {
Some((_, t)) => t.rect_to_screen(&r).bounds(point(px(0.0), px(0.0))),
None => self.screen_rect(r, w),
})
.collect()
}
/// Detect `@`, `[[`, or `【【` typed into the focused table cell and open or sync the
/// `@` linked-document picker anchored to the cell caret.
pub(super) fn handle_table_cell_at_trigger(
@@ -298,9 +418,13 @@ impl PlaygroundView {
}
return;
}
// Drag distances are measured in flow units: an Active Note divides out the camera.
let scale = self
.active_note_table_target()
.map_or(1.0, |(_, t)| t.scale.max(0.05));
if let Some(drag) = self.overlays.table_hover.add_drag.as_mut() {
let dx = f32::from(event.position.x) - drag.start_screen.0;
let dy = f32::from(event.position.y) - drag.start_screen.1;
let dx = (f32::from(event.position.x) - drag.start_screen.0) / scale;
let dy = (f32::from(event.position.y) - drag.start_screen.1) / scale;
drag.moved |= match drag.kind {
Kind::Row => dy.abs() > 4.0,
Kind::Column => dx.abs() > 4.0,
@@ -352,7 +476,7 @@ impl PlaygroundView {
if let Some(cell) = self.table_cell.as_mut()
&& let Some(drag) = cell.col_resize_drag.as_mut()
{
let delta = f32::from(event.position.x) - drag.start_screen_x;
let delta = (f32::from(event.position.x) - drag.start_screen_x) / scale;
let next = (drag.start_width + delta).clamp(60.0, 960.0).round();
if (drag.preview_width - next).abs() >= 0.5 {
drag.preview_width = next;
@@ -373,19 +497,26 @@ impl PlaygroundView {
else {
return;
};
let Some(layout) = self.flow_layout() else {
return;
let (layout, transform) = match self.active_note_table_target() {
Some((layout, t)) => (layout, Some(t)),
None => match self.flow_layout() {
Some(layout) => (layout, None),
None => return,
},
};
let Some((bx, by, hit)) =
Self::find_table_cell_hit(&layout, &block_id, &row_id, &column_id)
else {
return;
};
let (origin, canvas_size) = self.canvas_rect(window);
let geom = self.current_page_geometry(f32::from(canvas_size.width));
let local_x = f32::from(event.position.x) - f32::from(origin.x) - geom.column_x - bx
+ self.overlays.code_scroll_x(&block_id);
let local_y = f32::from(event.position.y) - f32::from(origin.y) + self.scroll_y - by;
let (local_x, local_y) = self.table_cell_local_point(
transform,
&block_id,
(bx, by),
f32::from(event.position.x),
f32::from(event.position.y),
window,
);
let off = hit.hit_text(local_x, local_y, &text).utf16_offset as usize;
if let Some(cell) = self.table_cell.as_mut() {
match drag_mode {
@@ -481,3 +612,64 @@ impl PlaygroundView {
cx.notify();
}
}
/// Where table geometry in flow coordinates lands inside the element layer that paints it.
#[derive(Clone, Copy)]
pub(crate) enum TablePaintFrame {
/// The Page column inside the page viewport element.
Page(PageViewport),
/// The edited Edgeless Note, mapped through the camera into the canvas layer at window
/// position `vp_origin` (`width` × `height`).
Note {
transform: OverlayScreenTransform,
vp_origin: (f32, f32),
width: f32,
height: f32,
},
}
impl TablePaintFrame {
pub(super) fn map(&self, r: FlowRect) -> FlowRect {
match self {
Self::Page(v) => FlowRect::new(v.column_x + r.x, r.y - v.scroll_y, r.w, r.h),
Self::Note {
transform,
vp_origin,
..
} => {
let s = transform.rect_to_screen(&r);
FlowRect::new(s.x - vp_origin.0, s.y - vp_origin.1, s.w, s.h)
}
}
}
/// Layer-local `(width, height)` of the visible area.
pub(super) fn extent(&self) -> Option<(f32, f32)> {
match self {
Self::Page(_) => None,
Self::Note { width, height, .. } => Some((*width, *height)),
}
}
pub(super) fn intersects(&self, r: &FlowRect) -> bool {
match (self, self.extent()) {
(Self::Page(v), _) => r.bottom() >= v.scroll_y && r.y <= v.scroll_y + v.height,
(_, Some((w, h))) => {
let m = self.map(*r);
m.bottom() >= 0.0 && m.y <= h && m.right() >= 0.0 && m.x <= w
}
_ => false,
}
}
pub(super) fn fully_visible(&self, r: &FlowRect) -> bool {
match (self, self.extent()) {
(Self::Page(v), _) => v.fully_visible(r),
(_, Some((w, h))) => {
let m = self.map(*r);
m.x >= 0.0 && m.y >= 0.0 && m.right() <= w && m.bottom() <= h
}
_ => false,
}
}
}
@@ -62,7 +62,7 @@ impl PlaygroundView {
window: &Window,
cx: &mut Context<Self>,
) -> bool {
let Some(layout) = self.flow_layout() else {
let Some((_, layout, _)) = self.active_overlay_target() else {
return false;
};
let Some((_block_id, overlay)) = self.database_popover_overlay(&layout, window) else {