diff --git a/blocksuite/crates/AGENTS.md b/blocksuite/crates/AGENTS.md index 1b31524086..ee71cf40a1 100644 --- a/blocksuite/crates/AGENTS.md +++ b/blocksuite/crates/AGENTS.md @@ -39,15 +39,15 @@ These crates belong to the client Cargo workspace rooted at `packages/frontend/C - **Overlay motion**: Popovers fade over 150 ms with an ease-out cubic `EaseOut` evaluated at scheduler time. An opening popover mounts on its first frame at zero opacity so its hitboxes are live immediately; a closed popover at zero opacity is unmounted, and one fading out carries no listeners and is dropped when the fade ends. Disclosure chevrons turn over the same 150 ms. Checking an unchecked to-do box triggers a closed-form 600 ms ease-out 6-dot radial pulse (`todo_pulses`) that clears at completion. Active editing carets (Page body and in-place table cells) blink with a closed-form 500 ms on / 500 ms off scheduler-clock cycle (`caret_blink_alpha`), resetting solid for 500 ms on any click, focus, key, or edit while keeping `FrameSnapshot` geometry and opacity invariant across frame rates. Nothing here loops per frame. - **Desktop viewport scrollbar & overlay context menu**: On `FormFactor::Desktop` Page viewports (non-touch form factor, `max_scroll > 0`), `overlay.page_scrollbar` (24 px interactive gutter on the logical inline-end edge: right in LTR, left in RTL) mounts an 8 px rounded translucent `overlay.page_scrollbar.thumb` (min height 32 px) supporting thumb dragging and track page-jumps; `FormFactor::Phone` and `FormFactor::Tablet` hide the desktop scrollbar. Right-clicking on desktop Page or Edgeless inline-edit surfaces opens `overlay.context_menu` (`.copy`, `.cut`, `.paste`, plus `.open_link` and `.copy_link` when right-clicking an inline link or Bookmark block, with `Up`/`Down`/`Enter`/`Escape` keyboard navigation; Page mode resolves links strictly at the right-click coordinates, and touch form factors or mobile read-only mode suppress the desktop menu); `Paste` falls back to a 2.2 s scheduler-timed `overlay.context_menu.toast` when platform clipboard read is unavailable. - **Slash menu** (`overlay.slash_menu`, rows `overlay.slash_menu.item.`, `.group.`, `.query`, `.submenu`, `.preview`): Typing `/` at a caret in paragraph or list text, outside inline code, opens it on that character, remembered as a relative position (`EditorSession::slash_trigger`): text a peer inserts before the `/` moves the menu along. The text between the `/` and the caret is both document text and the filter (`query_in_document`); inter-word spaces are allowed (e.g. `/heading 1`, `/code block`, `/new doc`), while leading whitespace (`/ `), newlines, consecutive spaces, or trailing whitespace with no matches close the trigger, as does leaving the text or deleting/replacing the `/`; a command never runs on text it did not open on. `Escape` leaves the text as typed. `OpenSlashMenu` opens the menu with a filter of its own, shown in a query row and edited by the menu's keys. Filtering uses case- and whitespace-insensitive subsequence matching (`isFuzzyMatch`) stably sorted by `substringMatchScore`; when no items match, the popover is hidden so ordinary URLs, paths, and dates never leave a `No results` card obscuring body text below. Items live in one authoritative registry (`SLASH_ITEMS`, shared with desktop `FormatToolbar` `Turn into ▾` and mobile `KeyboardToolbar`) across 10 groups (`Basic` including `Inline equation` and `Callout`, `List`, `Align`, `Style`, `Page`, `Content & Media` including `PDF` and `Embed`/`YouTube`/`GitHub`/`Figma`/`Loom`, `Edgeless Element` with Page- and Edgeless-enabled `Frame` [1600 × 900 non-overlapping under `affine:surface` with monotonic `presentation_index`] and `Mind Map` [root + 3 branch shapes + `SurfaceRef` `ref_flavour: "mindmap"`], `Date` [`Today`/`Tomorrow`/`Yesterday` `YYYY-MM-DD`, `Now` `YYYY-MM-DD HH:MM`], `Database` [`Table View`, `Calendar View`, `Kanban View`, omitted when `database_readonly`], and `Actions` [`Move Up`/`Move Down`/`Copy`/`Duplicate`/`Delete`, each 1-step Undo]). When unfiltered on desktop, `H1–H3` stay in `Basic` and `H4–H6` collapse into `Other Headings ▸` (`overlay.slash_menu.submenu`), capped at `390 px` max height with internal scrolling; hovering or staying selected for `800 ms` schedules a one-shot wakeup to open `overlay.slash_menu.preview`. Each icon sits in a bordered 28 px box, rows are 44 px (title plus Web `0.27.5` description subtitle, with group headers hidden while filtering), and the menu has no border, only its shadow. -- **Linked-doc `@` menu & lightweight link/reference capsule** (`overlay.linked_doc_menu`, rows `overlay.linked_doc_menu.item.`, `.journal.`, `.create`, `.create_edgeless`, `.input_mask`; `overlay.link_popup`, `overlay.reference_alias_prompt`): Typing `@` anywhere in paragraph, list, or `affine:table` cell text (outside inline code), or typing `[[` or `【【` (which converts the pair into `@`), opens the linked-doc popover anchored at the caret (`EditorSession::linked_doc_trigger`), querying the active `WorkspaceDocDirectory` as the user types inside a height-capped scrollable list with keyboard auto-scroll, `More` expansion, `Journal` dynamic date entries (`Today`/`Tomorrow`/`Yesterday` showing `YYYY-MM-DD` subtitles and calendar-validated `YYYY-MM-DD` input rejecting impossible dates such as `2026-02-31`), and `New` Page/Edgeless creation. `Up`/`Down`/`Ctrl+N`/`Ctrl+P`/`Tab`/`Shift+Tab` move selection across all matched docs, Journal entries, and `New` rows without indenting the underlying block, `Enter` selects or creates the linked doc and replaces `@query` with a BlockSuite `InlineReference` (`LinkedPage`) chip in one undo step, `Escape` closes the menu while leaving the typed text intact, and selection changes (`←`/`→`, clicks, remote edits) sync `sync_linked_doc_trigger` so moving before `@` or leaving the trigger range closes the menu immediately. Hovering an inline link or `@reference` chip for 500 ms on desktop (keeping the capsule open across the hover bridge onto `overlay.link_popup`), placing the caret on it, or single-tapping in mobile edit mode (mobile read-only single-tap and desktop left-click open directly; `page_readonly` exposes only `Open ↗` and `Copy`) opens the non-focus-stealing `overlay.link_popup` capsule (`Open ↗`, `Edit` / `Alias`, `Copy`, desktop `Card` & conditional `Embed`, and `Unlink` / `Remove`). -- **Formatting toolbar** (`overlay.format_toolbar`, buttons `.turn_into`, `.bold`, `.italic`, `.underline`, `.strike`, `.code`, `.highlight`, `.link`, `.inline_equation`, `.create_linked_doc`, `.align_left|center|right`, `.more`, dropdowns `.turn_into_menu`, `.highlight_menu`, `.more_menu`, dual-field link editor `.link_text_input`, `.link_input`, `.link_apply`, `.link_remove`): shown above a finished, non-empty selection of paragraph and list text (or a whole-block `BlockSelection` covering paragraph/list blocks), while no composition runs and no slash menu is up (`FormFactor::Desktop` auto-collapses any open `KeyboardToolbar`); a selection touching only the title or code gets none. `Turn into ▾` converts blocks via the shared `SLASH_ITEMS` registry in one undo step; `Highlight` exposes 9 foreground + 9 background swatches writing BlockSuite delta `color`/`background` attributes (with Default clearing) in one undo step; `TeX` (`InlineEquation`) wraps the selection into an inline `latex` chip and opens `EquationEditor`; `CreateLinkedDoc` creates a linked page titled with the selection and replaces it with an `@reference` chip in one undo step; `More` exposes `Copy` / `Duplicate` / `Delete`. A mark button is active only when the whole selection carries the mark. Alignment goes on every paragraph and list block the selection touches (filtering out non-text blocks in `block_selection`), empty ones included, and a block that sets none reads as its nearest aligned ancestor's. The dual-field link editor (`Text` + `Link`, hiding `Remove` for new links and disabling `Apply` on invalid URLs, preserving existing non-`link` inline marks and checking `expected_prev_url` against live spans) takes text input via `EntityInputHandler` while open (`Tab` toggles `Text` <-> `Link` fields, `Escape` abandons composition before closing). +- **Linked-doc `@` menu & lightweight link/reference capsule** (`overlay.linked_doc_menu`, rows `overlay.linked_doc_menu.item.`, `.journal.`, `.create`, `.create_edgeless`, `.input_mask`; `overlay.link_popup`, `overlay.reference_alias_prompt`): Typing `@` anywhere in paragraph, list, or `affine:table` cell text (outside inline code), or typing `[[` or `【【` (which converts the pair into `@`), opens the linked-doc popover anchored at the caret (`EditorSession::linked_doc_trigger`), querying the active `WorkspaceDocDirectory` as the user types inside a height-capped scrollable list with keyboard auto-scroll, `More` expansion, `Journal` dynamic date entries (`Today`/`Tomorrow`/`Yesterday` showing `YYYY-MM-DD` subtitles and calendar-validated `YYYY-MM-DD` input rejecting impossible dates such as `2026-02-31`), and `New` Page/Edgeless creation. `Up`/`Down`/`Ctrl+N`/`Ctrl+P`/`Tab`/`Shift+Tab` move selection across all matched docs, Journal entries, and `New` rows without indenting the underlying block, `Enter` selects or creates the linked doc and replaces `@query` with a BlockSuite `InlineReference` (`LinkedPage`) chip in one undo step, `Escape` closes the menu while leaving the typed text intact, and selection changes (`←`/`→`, clicks, remote edits) sync `sync_linked_doc_trigger` so moving before `@` or leaving the trigger range closes the menu immediately. Hovering an inline link or `@reference` chip for 500 ms on desktop (keeping the capsule open across the hover bridge onto `overlay.link_popup`), placing the caret on it, or single-tapping in mobile edit mode (mobile read-only single-tap and desktop left-click open directly; `page_readonly` exposes only `Open ↗` and `Copy`) opens the non-focus-stealing `overlay.link_popup` toolbar on the shared `ToolbarChrome`: the label preview `.open`, `.copy`, `.edit` for links or `.alias` for references, a `.view` dropdown (`.view_menu`: `Inline view`, `Card view`, and conditional `Embed view`; links show it on desktop only), and `.more` (`.more_menu` with `Remove link` for links or `Delete` for references). +- **Formatting toolbar** (`overlay.format_toolbar`, buttons `.turn_into`, `.align`, `.bold`, `.italic`, `.underline`, `.strike`, `.code`, `.inline_equation`, `.link`, `.highlight`, `.create_table`, `.create_linked_doc`, `.more`, dropdowns `.turn_into_menu`, `.align_menu` with `.align_left|center|right`, `.highlight_menu`, `.more_menu`, dual-field link editor `.link_text_input`, `.link_input`, `.link_apply`, `.link_remove`): shown above a finished, non-empty selection of paragraph and list text (or a whole-block `BlockSelection` covering paragraph/list blocks), while no composition runs and no slash menu is up (`FormFactor::Desktop` auto-collapses any open `KeyboardToolbar`); a selection touching only the title or code gets none. `Turn into ▾` converts blocks via the shared `SLASH_ITEMS` registry in one undo step; `Highlight` exposes 9 foreground + 9 background swatches writing BlockSuite delta `color`/`background` attributes (with Default clearing) in one undo step; `TeX` (`InlineEquation`) wraps the selection into an inline `latex` chip and opens `EquationEditor`; `CreateLinkedDoc` creates a linked page titled with the selection and replaces it with an `@reference` chip in one undo step; `More` exposes `Copy` / `Duplicate` / `Delete`. A mark button is active only when the whole selection carries the mark. Alignment goes on every paragraph and list block the selection touches (filtering out non-text blocks in `block_selection`), empty ones included, and a block that sets none reads as its nearest aligned ancestor's. The dual-field link editor (`Text` + `Link`, hiding `Remove` for new links and disabling `Apply` on invalid URLs, preserving existing non-`link` inline marks and checking `expected_prev_url` against live spans) takes text input via `EntityInputHandler` while open (`Tab` toggles `Text` <-> `Link` fields, `Escape` abandons composition before closing). - **Equation editor** (`overlay.equation_editor`, `.input`, `.done`): opens on `$$$$ ` / `$$$$ Enter` (block `affine:latex`), `$$ ` / `$$ Enter` (empty inline equation), or clicking an existing `FlowKind::Latex` block or `DecorationKind::LatexChip`. `Enter`, clicking `Done`, and clicking outside the popover commit the current LaTeX string (including any active IME composition via `LinkBar::into_committed_text`), while unchanged content closes without writing; `Escape` cancels and closes without writing. Open inline targets track remote peer edits via a zero-width CRDT `SelectionSnapshot` identity check and auto-close if the target is deleted or replaced remotely. The input field paints syntax-colored LaTeX directly from `highlight_line` runs, supports `Up`/`Down` navigation across soft-wrapped visual lines, and maps pointer clicks (`EquationClick`) to the nearest UTF-16 offset on the clicked visual row. - **Mobile keyboard toolbar & bookmark prompt** (`overlay.keyboard_toolbar`, buttons `overlay.keyboard_toolbar.`, docked panel `overlay.keyboard_toolbar.panel..`, and `overlay.bookmark_prompt`, `.input`, `.apply`, `.cancel`): mirrors `0.27.5` `defaultKeyboardToolbarConfig` (`More` 8-group scrollable tool panel, horizontally scrollable top-level / `Aa` item strip without `...` pagination, `Aa` `textSubToolbarConfig` with `autoShow` on non-collapsed text selections, `Turn into` reusing `SLASH_ITEMS`, and `Highlight` foreground/background swatches). While `KeyboardToolbar` is visible on mobile, the floating desktop `FormatToolbar` is suppressed unless its inline link field is explicitly opened (`KeyboardToolbarAction::Link`). Date actions and `embed-linked-doc` `"Updated YYYY-MM-DD HH:MM"` card labels format against the host's local calendar timezone (`utc_offset_minutes`); `Image` opens the host file picker (`can_pick_images` hides the button on native hosts without a registered picker), queues background upload of the base64url SHA-256 content-addressed blob (retrying on scheduler backoff and reconnect until confirmed), and publishes `affine:image`; `Bookmark` opens `overlay.bookmark_prompt` and commits an `http(s)://` `affine:bookmark` block as one undo step (`Escape`, `Cancel`, outside press, empty input, or relative paths write zero blocks). - **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..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..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`, and `affine:callout` blocks mount `overlay.image_toolbar` (hidden while `overlay.image_lightbox` is open; double-clicking an image opens fullscreen `overlay.image_lightbox` with uniform aspect-preserving zoom, clipped viewport drag-pan / proportional wheel & pinch zoom, and modal key capture), `overlay.bookmark_toolbar` (`Inline` / active `Card` / host-validated `Embed` + Page `Wide`/`Compact` style toggle, plus inline `overlay.url_paste_menu` on plain URL paste), and `overlay.callout_toolbar` + `overlay.callout_icon_picker` (`{"type":"emoji","unicode":...}` `IconData` Map + `Remove` icon + 9 `0.27.5` semantic background swatches), docking cleanly as horizontally scrollable `>= 44 × 44 pt` bottom context bars on touch viewports down to `360 pt`. Block-level `affine:latex` uses 2-step selection (first click selects block, second click opens `overlay.equation_editor`). A sideways scroll over an unwrapped code block scrolls its lines inside `BlockBody::code_scroll` instead of the page; the caret, selection, IME bounds, collaborators' carets/selections, and pointer hit-testing follow that scroll (`ScrolledCode`). -- **Sizes and radii**: Interactive targets are at least 24 × 24 px on desktop (toolbar buttons 28 × 28, edge to edge; touch host controls `>= 44 pt` height). Rows and buttons round concentrically with their container: 8 px menu with 4 px padding and 4 px rows, 8 px toolbar with 4 px padding and 4 px buttons (`gap = 2px, pad = 4px`, compacting to 24 px `FormatAction::COMPACT` pills on viewports `< 460 px` so the toolbar fits a 320 px window between its 8 px margins; on wide desktop viewports `>= 460 px`, the 14-button toolbar is 481 px wide with three 1 px separators). All floating popovers fade opacity monotonically in place over 150 ms with zero entrance/exit coordinate drift. +- **Block controls & block toolbars**: `page.block..checkbox`, `.toggle` and `.collapse` are 24 px targets over the to-do box, the toggle chevron and the heading chevron (an expanded heading shows its chevron only while the pointer is on its row, and `page.block_selection` highlights merged visible nested subtrees while skipping collapsed children); 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..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.`, 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`). +- **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 ` renders one overlay state of the showcase, `bs-harness audit-states` audits every state in both themes at `1280` and `320` px, and `bs-harness record-demo ` writes the frames of a 60 fps walk through typing, composition, the slash menu, the toolbar and the block controls; all drive the view through input events, the input handler and `dispatch_overlay` only. ### Rich paragraph layout @@ -58,7 +58,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 ] [--pan ,]` 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). -- **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. Downloads reach the host only through `set_on_media_download`; the view keeps no copy of the bytes. +- **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 `` 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 @@ -77,4 +77,4 @@ These crates belong to the client Cargo workspace rooted at `packages/frontend/C - **Standalone Web preview staging (`playground/scripts/stage-web.mjs`)**: Stages `wasm-scalar-rpc.js`, `workers/preview-worker-core.js`, `workers/{math,pdf,mermaid,typst}-worker.js`, built preview `.wasm` binaries, `pkg/playground.{js,_bg.wasm}`, and the `ui-tokens` fonts (`assets/fonts/*.ttf`) into `blocksuite/crates/playground/web/` (`node blocksuite/crates/playground/scripts/stage-web.mjs [--out ]`) and validates relative ESM imports. - **Whiteboard `mindmap` & `gfx/text` `RE_RTL_CHECK` compatibility**: `SurfaceElementKind::Mindmap` decodes `layoutType` (`Right`/`Left`/`Balance`), `style` (`1..=4` `0.27.5` `StrokeColorShortMap` medium palettes), and `children` (`{ index, parent?, collapsed? }`) with zero CRDT writeback, synthesizing `0.27.5` branch and `6px` collapsed-stub connectors (`surface/mindmap.rs`) beneath child shapes and falling back to deterministic `compute_mindmap_layout` when child shapes share an unpositioned origin; Edgeless canvas clipboard paste (`edgeless/paste.rs`) imports BlockSuite surface snapshots (including `mindmap` trees with remapped child shape IDs, `parent` links, and `+24,+24` offset) in a single atomic undo step. Edgeless `SurfaceText`, `Shape` labels, and `Connector` labels evaluate `surface::is_gfx_text_rtl` (`0.27.5` non-`/u` UTF-16 `RE_RTL_CHECK`) per delta/line (`RichParagraphStyle::gfx_per_delta_rtl`), and mobile Edgeless read-only mode (`PlaygroundOptions::edgeless_readonly`, `?mobile=1` / `--edgeless-readonly`) hides `chrome.edgeless_toolbar`, suppresses mutating gestures/shortcuts, and supports 1-finger pan plus 2-finger centroid pinch-zoom. -- **Inline previews, `ExternalEmbed` cards, `doc_panel`, and block toolbars**: Native shipping entry points (`PlaygroundView::with_options`, `main.rs`) idempotently install RaTeX `MathPreviewProvider`, Hayro `PdfPageProvider`, and Merman+Typst `CodePreviewProvider` (`ensure_native_preview_providers_installed`); Web mounts worker-backed math/PDF/Mermaid/Typst providers plus `#embed-layer` HTML iframes strictly without `allow-same-origin` (reconciled per frame and shielded when overlays/text fields open). `ExternalEmbed` cards (`embed-youtube`/`figma`/`github`/`loom`/`iframe`/`html`/`web`) use real `block_selection` on click and `cx.open_url` via `Open` for `http(s)://` URLs (with `doc_panel` topbar scrollable Outline TOC & DocInfo statistics drawer, compact icon button `< 440px`, auto-collapse `< 600px`). `affine:attachment` PDF blocks (`block_flow/attachment_block.rs`, `overlays/attachment_toolbar.rs`, `overlays/pdf_viewer.rs`, `playground/src/overlays/view_pdf_viewer/`) preserve exact page aspect ratio (`min(avail_w/w_pt, max_canvas_h/h_pt)`), expand only when `embed && is_pdf` (`PDFViewerEmbedded` bottom-right `↑`/`↓`/`↗` + footer filename & `1 / N`), switch between `Card view` and `Embed view` (`prop:embed`) in 1 Undo step via `overlay.attachment_toolbar`, and open the independent virtual-scroll multi-page `CenterPeek` `PDFViewer` (`overlay.pdf_viewer` with bounded page cache, `-`/`100%`/`+` zoom, and collapsible thumbnail strip). Code blocks expose `Wrap`/`Preview`/`Copy` controls (showing `Preview` only when a real renderer supports that language via `code_preview_supported`), and focused `affine:table` blocks expose a readonly-guarded row/column toolbar (`+↑ Row`/`+ Row`/`- Row`/`+← Col`/`+ Col`/`- Col`, narrow `8 px` hover-only column-divider resize drag committing 1 atomic undo step on release with `Escape` cancel, and `Row ⋯`/`Col ⋯` axis menus with background swatches, move, clear, and delete dismissed by `Escape` or outside click, preserving both flat and nested `Y.Map` table schemas) with `stop_capturing()` on same-cell / Edgeless-label caret repositioning. +- **Inline previews, `ExternalEmbed` cards, `doc_panel`, and block toolbars**: Native shipping entry points (`PlaygroundView::with_options`, `main.rs`) idempotently install RaTeX `MathPreviewProvider`, Hayro `PdfPageProvider`, and Merman+Typst `CodePreviewProvider` (`ensure_native_preview_providers_installed`); Web mounts worker-backed math/PDF/Mermaid/Typst providers plus `#embed-layer` HTML iframes strictly without `allow-same-origin` (reconciled per frame and shielded when overlays/text fields open). `ExternalEmbed` cards (`embed-youtube`/`figma`/`github`/`loom`/`iframe`/`html`/`web`) use real `block_selection` on click and `cx.open_url` via `Open` for `http(s)://` URLs (with `doc_panel` topbar scrollable Outline TOC & DocInfo statistics drawer, compact icon button `< 440px`, auto-collapse `< 600px`). `affine:attachment` PDF blocks (`block_flow/attachment_block.rs`, `overlays/attachment_toolbar.rs`, `overlays/pdf_viewer.rs`, `playground/src/overlays/view_pdf_viewer/`) preserve exact page aspect ratio (`min(avail_w/w_pt, max_canvas_h/h_pt)`), expand only when `embed && is_pdf` (`PDFViewerEmbedded` bottom-right `↑`/`↓`/`↗` + footer filename & `1 / N`), switch between `Card view` and `Embed view` (`prop:embed`) in 1 Undo step via `overlay.attachment_toolbar`, and open the independent virtual-scroll multi-page `CenterPeek` `PDFViewer` (`overlay.pdf_viewer` with bounded page cache, `-`/`100%`/`+` zoom, and collapsible thumbnail strip). Code blocks expose `Wrap`/`Preview`/`Copy` controls (showing `Preview` only when a real renderer supports that language via `code_preview_supported`), and `affine:table` blocks expose readonly-guarded controls: on desktop, hovering the table shows 16 px add-column (`overlay.table_hover.add_col`) and add-row (`.add_row`) bars and a corner handle (`.add_corner`) that append at the end of the table on release in 1 undo step (a press without movement, or with at most 4 px of travel along the bar's axis, adds 1 row, 1 column, or both; a drag adds at least 1, then 1 per 36 px down and 1 per 80 px right, with a live `.drag_tip`, and dragging back to the press point or away from the table adds nothing), 28 × 16 / 16 × 28 three-dot axis pills (`.col_pill`, `.row_pill`) that open `overlay.table_toolbar.axis_menu` (`Background color`, `Insert Above` / `Insert Below` or `Insert Left` / `Insert Right`, move, clear contents, and delete, dismissed by `Escape` or outside click), and 5 px hover-only column dividers (`overlay.table_col_resize.`) whose resize drag commits 1 atomic undo step on release with `Escape` cancel; on touch hosts a docked `overlay.table_toolbar` exposes `+ Row` / `- Row` / `+ Col` / `- Col` and `.more`; all edits preserve both flat and nested `Y.Map` table schemas with `stop_capturing()` on same-cell / Edgeless-label caret repositioning. diff --git a/blocksuite/crates/doc/src/session/mod.rs b/blocksuite/crates/doc/src/session/mod.rs index e97eae448f..a36f468fc2 100644 --- a/blocksuite/crates/doc/src/session/mod.rs +++ b/blocksuite/crates/doc/src/session/mod.rs @@ -4,6 +4,7 @@ mod structure; mod surface; mod surface_frame; mod surface_mindmap; +mod table_append; mod table_cell; mod table_cell_ops; mod workspace; @@ -712,12 +713,8 @@ impl PageDocSession { caption: &str, now_ms: u64, ) -> DocResult>> { - self.set_block_prop( - block_id, - "prop:caption", - SessionValue::Any(Any::String(caption.to_string())), - now_ms, - ) + let value = SessionValue::Any(Any::String(caption.to_string())); + self.set_block_prop(block_id, "prop:caption", value, now_ms) } pub(super) fn unique_children_with_dups( diff --git a/blocksuite/crates/doc/src/session/table_append.rs b/blocksuite/crates/doc/src/session/table_append.rs new file mode 100644 index 0000000000..338c2c0899 --- /dev/null +++ b/blocksuite/crates/doc/src/session/table_append.rs @@ -0,0 +1,141 @@ +//! Growing an `affine:table` at its end: new rows after the last row and new columns after the +//! last column, with their cells, in one undo step. + +use y_octo::{Any, SessionValue, TypePath, TypeTarget}; + +use crate::DocResult; + +use super::{PageCommit, PageDocSession}; + +impl PageDocSession { + /// Append `row_ids` after the last row and `column_ids` after the last column of `block_id`, + /// with an empty `Y.Text` for every new cell, in one atomic undo step. Keeps the storage + /// format of the table (nested `Y.Map` or flat dotted keys). + pub fn append_table_rows_and_columns( + &mut self, + block_id: &str, + row_ids: &[String], + column_ids: &[String], + now_ms: u64, + ) -> DocResult { + if row_ids.is_empty() && column_ids.is_empty() { + return Ok(None); + } + let Some(table) = self.read_table_block(block_id)? else { + return Ok(None); + }; + let rows = self.orders_after(table.rows.last().map(|r| r.order.clone()), row_ids)?; + let columns = + self.orders_after(table.columns.last().map(|c| c.order.clone()), column_ids)?; + let all_columns: Vec<&str> = table + .columns + .iter() + .map(|c| c.column_id.as_str()) + .chain(column_ids.iter().map(String::as_str)) + .collect(); + let new_cells: Vec<(String, String)> = table + .rows + .iter() + .map(|r| r.row_id.as_str()) + .chain(row_ids.iter().map(String::as_str)) + .flat_map(|row| { + let new_row = row_ids.iter().any(|id| id == row); + all_columns + .iter() + .filter(move |col| new_row || column_ids.iter().any(|id| id == *col)) + .map(move |col| (row.to_string(), col.to_string())) + }) + .collect(); + let (rows_nested, columns_nested, cells_nested) = + self.table_nested_map_targets(block_id)?; + let block = TypeTarget::Path(TypePath::root("blocks").key(block_id)); + self.structural_edit(now_ms, move |page| { + for (id, order) in &rows { + page.set_table_axis_entry( + &block, + rows_nested.as_ref(), + "rows", + "rowId", + id, + order, + )?; + } + for (id, order) in &columns { + page.set_table_axis_entry( + &block, + columns_nested.as_ref(), + "columns", + "columnId", + id, + order, + )?; + } + for (row, col) in &new_cells { + match &cells_nested { + Some(cells) => page.session.map_set( + cells, + format!("{row}:{col}"), + SessionValue::Map(vec![( + "text".to_string(), + SessionValue::Text(Vec::new()), + )]), + )?, + None => page.session.map_set( + &block, + format!("prop:cells.{row}:{col}.text"), + SessionValue::Text(Vec::new()), + )?, + }; + } + Ok(()) + }) + } + + /// Pair each of `ids` with an order key that sorts after `last` and after the ids before it. + fn orders_after( + &self, + mut last: Option, + ids: &[String], + ) -> DocResult> { + ids.iter() + .map(|id| { + let order = self.next_jittered_order_key(last.as_deref(), None)?; + last = Some(order.clone()); + Ok((id.clone(), order)) + }) + .collect() + } + + /// Write the id and the order of one row or column in the storage format of the table. + fn set_table_axis_entry( + &mut self, + block: &TypeTarget, + nested: Option<&TypeTarget>, + axis: &str, + id_field: &str, + id: &str, + order: &str, + ) -> DocResult { + let id_value = SessionValue::Any(Any::String(id.to_string())); + let order_value = SessionValue::Any(Any::String(order.to_string())); + match nested { + Some(target) => { + self.session.map_set( + target, + id.to_string(), + SessionValue::Map(vec![ + (id_field.to_string(), id_value), + ("order".to_string(), order_value), + ]), + )?; + } + None => { + self.session + .map_set(block, format!("prop:{axis}.{id}.{id_field}"), id_value)?; + self.session + .map_set(block, format!("prop:{axis}.{id}.order"), order_value)?; + } + } + Ok(()) + } +} diff --git a/blocksuite/crates/editor/src/block_flow/body.rs b/blocksuite/crates/editor/src/block_flow/body.rs index c95f7f4765..eb498487a1 100644 --- a/blocksuite/crates/editor/src/block_flow/body.rs +++ b/blocksuite/crates/editor/src/block_flow/body.rs @@ -640,6 +640,16 @@ impl FlowInput<'_> { self.utc_offset_at .map_or(self.utc_offset_minutes, |f| f(utc_ms)) } + + /// The logical start alignment of [`FlowInput::direction`], which blocks without their own + /// `prop:textAlign` inherit. + pub(super) fn start_align(&self) -> blocksuite_playground_doc::read::TextAlign { + use blocksuite_playground_doc::read::TextAlign; + match self.direction { + ui::Direction::Ltr => TextAlign::Left, + ui::Direction::Rtl => TextAlign::Right, + } + } } /// Counters of the latest [`BlockFlow::layout`] pass. diff --git a/blocksuite/crates/editor/src/block_flow/layout.rs b/blocksuite/crates/editor/src/block_flow/layout.rs index fe3bc02540..a808b0b96b 100644 --- a/blocksuite/crates/editor/src/block_flow/layout.rs +++ b/blocksuite/crates/editor/src/block_flow/layout.rs @@ -43,6 +43,8 @@ pub struct BlockFlow { pub image_resize_preview: Option<(String, f32, f32)>, /// Transient in-place caption editing state so only the active captioned block re-lays out. pub caption_draft: Option, + /// Host memo of [`snapshot_has_math`] keyed by `(page id, document revision)`. + pub has_math_cache: Option<(Option, u64, bool)>, } pub(super) struct FlowPass<'a> { @@ -155,10 +157,7 @@ impl BlockFlow { dirty: Option<&BTreeSet>, ) -> FlowLayout { let direction = input.direction; - let default_align = match direction { - ui::Direction::Ltr => BlockAlign::Left, - ui::Direction::Rtl => BlockAlign::Right, - }; + let default_align = input.start_align(); let mut pass = FlowPass { dirty, input, @@ -272,10 +271,7 @@ impl BlockFlow { visited_embeds: BTreeSet, ) -> FlowLayout { let direction = input.direction; - let default_align = match direction { - ui::Direction::Ltr => BlockAlign::Left, - ui::Direction::Rtl => BlockAlign::Right, - }; + let default_align = input.start_align(); let mut pass = FlowPass { dirty: None, input, diff --git a/blocksuite/crates/editor/src/block_flow/mod.rs b/blocksuite/crates/editor/src/block_flow/mod.rs index d45b3e928d..9bf276585a 100644 --- a/blocksuite/crates/editor/src/block_flow/mod.rs +++ b/blocksuite/crates/editor/src/block_flow/mod.rs @@ -75,6 +75,7 @@ pub use preview::{ parse_pdf_document, parse_pdf_document_arc, parse_pdf_document_scoped, parse_pdf_renderer, preview_revision, register_math_preview_provider, register_pdf_page_provider, render_math_cached, render_pdf_page, request_pdf_page_for_ui, rgba_pixels_to_render_image, + snapshot_has_math, }; pub use surface_ref::surface_ref_target_bounds; pub use viewport::{ diff --git a/blocksuite/crates/editor/src/block_flow/preview.rs b/blocksuite/crates/editor/src/block_flow/preview.rs index 8e0548447f..6ba4172e18 100644 --- a/blocksuite/crates/editor/src/block_flow/preview.rs +++ b/blocksuite/crates/editor/src/block_flow/preview.rs @@ -102,21 +102,14 @@ fn rich_text_has_inline_latex(text: &RichText) -> bool { }) } -/// Returns [`preview_revision`] when `snapshot`, `equation_draft`, or `code_preview_blocks` -/// references any async math or code preview, and `0` otherwise so unrelated background worker -/// completions or provider registrations never invalidate documents without math/diagram blocks. -pub fn document_preview_revision( - snapshot: &blocksuite_playground_doc::read::PageSnapshot, - equation_draft: Option<&super::EquationDraft>, - code_preview_blocks: &std::collections::BTreeSet, -) -> u64 { - if equation_draft.is_some() || !code_preview_blocks.is_empty() { - return preview_revision(); - } +/// Whether `snapshot` holds any block or inline LaTeX: `affine:latex` blocks, and inline +/// equations in paragraph, list, callout, simple table cell, and database title, row title, +/// and rich-text cell text. +pub fn snapshot_has_math(snapshot: &blocksuite_playground_doc::read::PageSnapshot) -> bool { let Some(root) = snapshot.root.as_ref() else { - return 0; + return false; }; - let has_math = root.walk().any(|node| match &node.content { + root.walk().any(|node| match &node.content { BlockContent::Latex { .. } => true, BlockContent::Paragraph { text, .. } | BlockContent::List { text, .. } @@ -125,9 +118,39 @@ pub fn document_preview_revision( .cells .values() .any(|c| rich_text_has_inline_latex(&c.text)), + BlockContent::Database(db) => database_rich_texts(db).any(rich_text_has_inline_latex), _ => false, + }) +} + +/// Every rich text an `affine:database` block renders: its title, row titles, and rich-text cells. +fn database_rich_texts( + db: &blocksuite_playground_doc::read::DatabaseData, +) -> impl Iterator { + use blocksuite_playground_doc::read::DatabaseCellValue; + let cells = db.cells.values().filter_map(|cell| match cell { + DatabaseCellValue::RichText(text) => Some(text), + _ => None, }); - if has_math { preview_revision() } else { 0 } + std::iter::once(&db.title) + .chain(db.rows.iter().map(|row| &row.title)) + .chain(cells) +} + +/// Returns [`preview_revision`] when the document has math (`has_math`, see +/// [`snapshot_has_math`]), an `equation_draft`, or `code_preview_blocks`, and `0` otherwise so +/// unrelated background worker completions or provider registrations never invalidate documents +/// without math/diagram blocks. +pub fn document_preview_revision( + has_math: bool, + equation_draft: Option<&super::EquationDraft>, + code_preview_blocks: &std::collections::BTreeSet, +) -> u64 { + if has_math || equation_draft.is_some() || !code_preview_blocks.is_empty() { + preview_revision() + } else { + 0 + } } /// Returns the per-formula revision stamp for `latex` (`0` before any async worker delivery). @@ -228,6 +251,11 @@ pub(super) fn node_preview_fingerprint( hash_rich_text_inline_latex(&cell.text, &mut hasher, &mut touched); } } + BlockContent::Database(db) => { + for text in database_rich_texts(db) { + hash_rich_text_inline_latex(text, &mut hasher, &mut touched); + } + } _ => {} } @@ -628,3 +656,118 @@ impl super::FlowPass<'_> { } } } + +#[cfg(test)] +mod tests { + use std::collections::BTreeSet; + + use blocksuite_playground_doc::read::{ + DatabaseCellValue, DatabaseData, DatabaseRow, PageSnapshot, + }; + use y_octo::{Any, TextDeltaOp, TextInsert}; + + use super::*; + + fn text(latex: bool) -> RichText { + let format = latex.then(|| { + [("latex".to_string(), Any::String("x^2".to_string()))] + .into_iter() + .collect() + }); + RichText { + plain: " ".to_string(), + delta: vec![TextDeltaOp::Insert { + insert: TextInsert::Text(" ".to_string()), + format, + }], + } + } + + fn node(id: &str, content: BlockContent) -> BlockNode { + BlockNode { + id: id.to_string(), + flavour: String::new(), + version: None, + content, + props: Default::default(), + children: Vec::new(), + } + } + + fn page_with(content: BlockContent) -> PageSnapshot { + let mut root = node( + "root", + BlockContent::Page { + title: RichText::default(), + }, + ); + root.children.push(node("block", content)); + PageSnapshot { + doc_id: "doc".to_string(), + root: Some(root), + detached: Vec::new(), + } + } + + fn database(title: bool, row_title: bool, cell: bool) -> BlockContent { + BlockContent::Database(DatabaseData { + title: text(title), + rows: vec![DatabaseRow { + row_id: "row".to_string(), + title: text(row_title), + created_at: None, + }], + cells: [( + ("row".to_string(), "col".to_string()), + DatabaseCellValue::RichText(text(cell)), + )] + .into_iter() + .collect(), + ..DatabaseData::default() + }) + } + + #[test] + fn snapshot_math_detection_and_database_fingerprints_cover_every_rich_text() { + let cases = [ + ( + "latex block", + BlockContent::Latex { latex: "x".into() }, + true, + ), + ("plain database", database(false, false, false), false), + ("database title", database(true, false, false), true), + ("database row title", database(false, true, false), true), + ( + "database rich-text cell", + database(false, false, true), + true, + ), + ]; + for (name, content, has_math) in cases { + let snapshot = page_with(content); + assert_eq!(snapshot_has_math(&snapshot), has_math, "{name}"); + let block = &snapshot.root.as_ref().expect("root").children[0]; + let fingerprint = node_preview_fingerprint(block, None, None); + assert_eq!(fingerprint != 0, has_math, "{name} fingerprint"); + } + let empty = PageSnapshot { + doc_id: "doc".to_string(), + root: None, + detached: Vec::new(), + }; + assert!(!snapshot_has_math(&empty)); + } + + #[test] + fn document_preview_revision_tracks_preview_results_only_for_math_documents() { + let none = BTreeSet::new(); + assert_eq!(document_preview_revision(false, None, &none), 0); + let before = document_preview_revision(true, None, &none); + bump_preview_revision(); + assert_eq!(document_preview_revision(false, None, &none), 0); + assert!(document_preview_revision(true, None, &none) > before); + let previewed = BTreeSet::from(["code".to_string()]); + assert_ne!(document_preview_revision(false, None, &previewed), 0); + } +} diff --git a/blocksuite/crates/editor/src/edgeless/element_toolbar/media_toolbar.rs b/blocksuite/crates/editor/src/edgeless/element_toolbar/media_toolbar.rs index 8bc44b8484..8240888625 100644 --- a/blocksuite/crates/editor/src/edgeless/element_toolbar/media_toolbar.rs +++ b/blocksuite/crates/editor/src/edgeless/element_toolbar/media_toolbar.rs @@ -22,7 +22,10 @@ use super::{ }; /// Build a `SurfaceBlockToolbarSummary` from a single selected canvas media/embed `BlockNode`. -pub(super) fn summarize_surface_block(node: &BlockNode) -> Option { +pub(super) fn summarize_surface_block( + node: &BlockNode, + can_download_blob: &dyn Fn(&str) -> bool, +) -> Option { let caption = node .props .get("prop:caption") @@ -56,7 +59,7 @@ pub(super) fn summarize_surface_block(node: &BlockNode) -> Option { - !source_id.is_empty() + !source_id.is_empty() && can_download_blob(source_id) } _ => false, }; diff --git a/blocksuite/crates/editor/src/edgeless/element_toolbar/render.rs b/blocksuite/crates/editor/src/edgeless/element_toolbar/render.rs index f94ed78939..cb4389360a 100644 --- a/blocksuite/crates/editor/src/edgeless/element_toolbar/render.rs +++ b/blocksuite/crates/editor/src/edgeless/element_toolbar/render.rs @@ -36,12 +36,14 @@ pub fn build_edgeless_element_toolbar( open_color_picker: Option, palette: &Palette, theme: PlaygroundTheme, + can_download_blob: impl Fn(&str) -> bool, cx: &mut Context, ) -> Option<(AnyElement, Vec)> { if authoring.inline_edit.is_some() || authoring.gesture.is_some() { return None; } - let summary = summarize_element_toolbar(snapshot, authoring, theme, palette)?; + let summary = + summarize_element_toolbar(snapshot, authoring, theme, palette, can_download_blob)?; let sel_box = authoring.selection_world_aabb()?; let vp_origin = point(px(0.0), px(0.0)); let tl = camera.world_to_screen(point(px(sel_box.x), px(sel_box.y)), vp_origin); diff --git a/blocksuite/crates/editor/src/edgeless/element_toolbar/summary.rs b/blocksuite/crates/editor/src/edgeless/element_toolbar/summary.rs index 406a056f5e..bd9b2757c6 100644 --- a/blocksuite/crates/editor/src/edgeless/element_toolbar/summary.rs +++ b/blocksuite/crates/editor/src/edgeless/element_toolbar/summary.rs @@ -249,6 +249,7 @@ pub fn summarize_element_toolbar( authoring: &EdgelessAuthoringState, theme: PlaygroundTheme, palette: &Palette, + can_download_blob: impl Fn(&str) -> bool, ) -> Option { if authoring.selection.is_empty() { return None; @@ -472,7 +473,8 @@ pub fn summarize_element_toolbar( } } if item.kind == SpatialItemKind::SurfaceBlock && single.is_some() { - surface_block = super::media_toolbar::summarize_surface_block(node); + surface_block = + super::media_toolbar::summarize_surface_block(node, &can_download_blob); } if item.kind == SpatialItemKind::EdgelessText { if !got_stroke && let Some(col) = node.props.get("prop:color") { diff --git a/blocksuite/crates/editor/src/overlays/bookmark_toolbar.rs b/blocksuite/crates/editor/src/overlays/bookmark_toolbar.rs index f053902460..76756c2c7e 100644 --- a/blocksuite/crates/editor/src/overlays/bookmark_toolbar.rs +++ b/blocksuite/crates/editor/src/overlays/bookmark_toolbar.rs @@ -4,17 +4,22 @@ //! `Duplicate`, and `Delete`, aligned with BlockSuite `0.27.5` `bookmark/configs/toolbar.ts`. use blocksuite_playground_doc::read::BlockContent; -use ui::{ - AnyElement, ClickEvent, Context, FontWeight, MouseButton, MouseDownEvent, ScrollEvent, - SharedString, div, prelude::*, px, +use ui::{AnyElement, ClickEvent, Context, FontWeight, MouseButton, div, prelude::*, px}; + +use crate::{ + block_flow::FlowRect, + theme::{Palette, TYPOGRAPHY}, }; -use crate::theme::{Palette, TYPOGRAPHY}; - use super::{ - OverlayEvent, OverlayHost, OverlayScene, Overlays, POPOVER_BORDER, POPOVER_EDGE_MARGIN, - POPOVER_GAP, Placement, TOOLBAR_BUTTON, TOOLBAR_GAP, TOOLBAR_PADDING, TOOLBAR_RADIUS, - embed_view_kind_for_url, emit, icon, place, place_popover, + BlockToolbarSubmenu, ChromeIcon, MenuActionVariant, OverlayEvent, OverlayHost, OverlayScene, + Overlays, POPOVER_EDGE_MARGIN, Placement, TOOLBAR_CHROME_BORDER, TOOLBAR_CHROME_BTN, + TOOLBAR_CHROME_BTN_RADIUS, TOOLBAR_CHROME_GAP, TOOLBAR_CHROME_HEIGHT, TOOLBAR_CHROME_ICON, + TOOLBAR_CHROME_OFFSET, TOOLBAR_CHROME_PX, TOOLBAR_MENU_ICON, TOOLBAR_MENU_MIN_W, + TOOLBAR_MENU_PADDING, TOOLBAR_MENU_ROW_H, TOOLBAR_SEP_SLOT, append_toolbar_groups, chrome_icon, + chrome_link_color, dismiss_submenu_outside, embed_view_kind_for_url, emit, hostname_preview, + icon, menu_horizontal_separator, place_popover, toolbar_chrome_container, + toolbar_dropdown_panel, toolbar_icon_button, toolbar_menu_row, }; /// Card visual style for `affine:bookmark` (`prop:style`). @@ -87,509 +92,447 @@ impl Overlays { scene: &OverlayScene<'_>, palette: &Palette, cx: &mut Context, - ) -> Option { + ) -> Vec { self.bookmark_toolbar_rect = None; + self.bookmark_submenu_rect = None; if scene.page_readonly { - return None; + return Vec::new(); } - let block_id = scene.selected_bookmark_block?; + let Some(block_id) = scene.selected_bookmark_block else { + return Vec::new(); + }; if self .bookmark_prompt() .is_some_and(|p| p.block_id == block_id) { - return None; + return Vec::new(); } - let flow_block = scene.layout.block(block_id)?; + let Some(flow_block) = scene.layout.block(block_id) else { + return Vec::new(); + }; let block_world = flow_block.rect(); if !scene.anchor_visible(&block_world) { - return None; + return Vec::new(); } - let node = scene.snapshot.block(block_id)?; - let (url, _has_caption) = match &node.content { - BlockContent::Bookmark { url, caption, .. } => (url.as_str(), !caption.is_empty()), - _ => return None, + let Some(node) = scene.snapshot.block(block_id) else { + return Vec::new(); + }; + let url = match &node.content { + BlockContent::Bookmark { url, .. } => url.as_str(), + _ => return Vec::new(), }; let can_embed = embed_view_kind_for_url(url).is_some(); let current_style = BookmarkCardStyle::from_wire(node.props.get("prop:style").and_then(|v| v.as_str())); let touch = scene.is_touch || scene.form_factor != crate::block_flow::FormFactor::Desktop; let vp = scene.popover_viewport(); - let pad = TOOLBAR_PADDING; - let chrome = 2.0 * (pad + POPOVER_BORDER); let max_w = (vp.w - 2.0 * POPOVER_EDGE_MARGIN).max(200.0); let desktop_raw = if can_embed { 474.0_f32 } else { 426.0_f32 }; let hover_bg = palette.hover; - let danger = palette - .theme - .css_var("--affine-error-color") - .unwrap_or(palette.icon); if touch || max_w < desktop_raw { - let btn_h = if touch { 44.0_f32 } else { TOOLBAR_BUTTON }; - let icon_w = if touch { 44.0_f32 } else { TOOLBAR_BUTTON }; - let gap = 4.0_f32; - let sep_slot = 9.0_f32; - let make_touch_text = |suffix: &'static str, - label: &'static str, - w: f32, - accent: bool, - active: bool, - action: Option, - cx: &mut Context| - -> (f32, Box AnyElement>) { - let text_col = if accent || active { - palette.brand - } else { - palette.text_primary - }; - let active_bg = palette.brand.opacity(0.14); - let click_handler = action.map(|act| { - let ev = OverlayEvent::BookmarkToolbarAction { - block_id: block_id.to_string(), - action: act, - }; - emit(cx, move |_: &ClickEvent| ev.clone()) - }); - ( - w, - Box::new(move |fully_visible| { - let mut el = div() - .id(SharedString::from(format!("bm-tb-{suffix}"))) - .w(px(w)) - .h(px(btn_h)) - .px(px(8.0)) - .rounded(px(4.0)) - .flex() - .items_center() - .justify_center() - .text_size(px(TYPOGRAPHY.font_xs_px)) - .font_weight(FontWeight::MEDIUM) - .text_color(text_col) - .when(active, |el| el.bg(active_bg)) - .child(label); - if let Some(handler) = click_handler { - el = el - .cursor_pointer() - .hover(move |s| s.bg(hover_bg)) - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_click(handler); - } - if fully_visible { - el = el - .snapshot( - SharedString::from(format!( - "overlay.bookmark_toolbar.{suffix}" - )), - Some("overlay.bookmark_toolbar"), - ) - .snapshot_focused(active) - .snapshot_text(label); - } - el.into_any_element() - }), - ) - }; - let make_touch_icon = |suffix: &'static str, - icon_name: &'static str, - active: bool, - is_danger: bool, - action: BookmarkToolbarAction, - cx: &mut Context| - -> (f32, Box AnyElement>) { - let ev = OverlayEvent::BookmarkToolbarAction { - block_id: block_id.to_string(), - action, - }; - let click_handler = emit(cx, move |_: &ClickEvent| ev.clone()); - let color = if is_danger { - danger - } else if active { - palette.brand - } else { - palette.icon - }; - let active_bg = palette.brand.opacity(0.14); - ( - icon_w, - Box::new(move |fully_visible| { - let mut el = div() - .id(SharedString::from(format!("bm-tb-{suffix}"))) - .w(px(icon_w)) - .h(px(btn_h)) - .rounded(px(4.0)) - .flex() - .items_center() - .justify_center() - .cursor_pointer() - .when(active, |el| el.bg(active_bg)) - .hover(move |s| s.bg(hover_bg)) - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_click(click_handler) - .child(icon(icon_name, 16.0, color)); - if fully_visible { - el = el - .snapshot( - SharedString::from(format!( - "overlay.bookmark_toolbar.{suffix}" - )), - Some("overlay.bookmark_toolbar"), - ) - .snapshot_focused(active); - } - el.into_any_element() - }), - ) - }; - - let mut items: Vec<(f32, Box AnyElement>)> = vec![ - make_touch_text( - "open", - "Open \u{2197}", - 60.0, - true, - false, - Some(BookmarkToolbarAction::Open), - cx, - ), - make_touch_text( - "edit", - "Edit", - 46.0, - false, - false, - Some(BookmarkToolbarAction::Edit), - cx, - ), - make_touch_text( - "inline", - "Inline", - 52.0, - false, - false, - Some(BookmarkToolbarAction::ConvertToInline), - cx, - ), - make_touch_text("card", "Card", 48.0, false, true, None, cx), - ]; - if can_embed { - items.push(make_touch_text( - "embed", - "Embed", - 58.0, - false, - false, - Some(BookmarkToolbarAction::ConvertToEmbed), - cx, - )); - } - items.push(make_touch_text( - "style", - current_style.label(), - 68.0, - false, - false, - Some(BookmarkToolbarAction::SetStyle( - current_style.next_in_page(), - )), + return self.render_bookmark_touch_bar( + scene, + palette, + block_id, + can_embed, + current_style, + touch, + block_world, cx, - )); - items.push(make_touch_icon( - "caption", - "CaptionIcon", - false, - false, - BookmarkToolbarAction::Caption, - cx, - )); - items.push(make_touch_icon( - "copy", - "CopyIcon", - false, - false, - BookmarkToolbarAction::Copy, - cx, - )); - items.push(make_touch_icon( - "duplicate", - "DuplicateIcon", - false, - false, - BookmarkToolbarAction::Duplicate, - cx, - )); - - let content_w: f32 = - items.iter().map(|(w, _)| *w).sum::() + (items.len() - 1) as f32 * gap; - let pinned_right_w = sep_slot + icon_w + 2.0 * gap; - let width = (content_w + pinned_right_w + chrome).min(max_w).round(); - let height = (btn_h + chrome).round(); - let avail_w = (width - chrome - pinned_right_w).max(icon_w); - let max_scroll = (content_w - avail_w).max(0.0).ceil(); - let scroll_key = format!("bm:{block_id}"); - let scroll_x = self.sync_touch_bar_scroll(&scroll_key, max_scroll); - - let rect = if touch { - super::helpers::place_touch_docked_toolbar(vp, width, height) - } else { - place_popover( - scene.world_to_screen(&block_world), - (width, height), - vp, - Placement::Above, - POPOVER_GAP, - POPOVER_EDGE_MARGIN, - ) - .rect - }; - self.bookmark_toolbar_rect = Some(rect); - - let strip = - Self::build_touch_scroll_strip(avail_w, btn_h, gap, scroll_x, palette, items); - let del_btn = make_touch_icon( - "delete", - "DeleteIcon", - false, - true, - BookmarkToolbarAction::Delete, - cx, - ) - .1(true); - - let root = place(rect) - .id("bookmark-toolbar") - .occlude() - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_mouse_down_out(|_: &MouseDownEvent, _, _| {}) - .on_scroll(emit(cx, move |event: &ScrollEvent| { - let (dx, dy) = crate::scroll::wheel_delta(event, rect.h); - OverlayEvent::TouchContextBarScroll(crate::scroll::dominant_axis_delta(dx, dy)) - })) - .p(px(pad)) - .rounded(px(TOOLBAR_RADIUS)) - .bg(palette.panel) - .border_1() - .border_color(palette.border) - .shadow(palette.theme.shadows("--affine-toolbar-shadow").into()) - .flex() - .items_center() - .gap(px(gap)) - .snapshot("overlay.bookmark_toolbar", Some("root.canvas")) - .child(strip) - .child( - div() - .flex_none() - .w(px(sep_slot)) - .h(px(btn_h)) - .flex() - .items_center() - .justify_center() - .child(div().w(px(1.0)).h(px(16.0)).bg(palette.divider)), - ) - .child(del_btn); - return Some(root.into_any_element()); + ); } - let width = desktop_raw.min(max_w).round(); - let height = (TOOLBAR_BUTTON + chrome).round(); + // Desktop `ToolbarChrome`: [hostname preview] │ Card view ▾ │ Style ▾ │ Caption │ ⋮ More + let block_id_owned = block_id.to_string(); + let host = hostname_preview(url); + let btn = TOOLBAR_CHROME_BTN; + let group_gap = TOOLBAR_CHROME_GAP; + let sep_w = TOOLBAR_SEP_SLOT; + let preview_w = (host.chars().count() as f32 * 6.8 + 16.0).clamp(60.0, 140.0); + let view_w = 88.0_f32; + let style_w = 68.0_f32; + + let view_open = matches!( + &self.block_submenu, + Some(BlockToolbarSubmenu::BookmarkView(id)) if id == block_id + ); + let style_open = matches!( + &self.block_submenu, + Some(BlockToolbarSubmenu::BookmarkStyle(id)) if id == block_id + ); + let more_open = matches!( + &self.block_submenu, + Some(BlockToolbarSubmenu::BookmarkMore(id)) if id == block_id + ); + let group_widths = [preview_w, view_w, style_w, btn, btn]; + let inner_w = group_widths.iter().sum::() + 4.0 * sep_w + 8.0 * group_gap; + let width = (inner_w + 2.0 * (TOOLBAR_CHROME_PX + TOOLBAR_CHROME_BORDER)) + .min(max_w) + .round(); + let height = (TOOLBAR_CHROME_HEIGHT + 2.0 * TOOLBAR_CHROME_BORDER).round(); let rect = place_popover( scene.world_to_screen(&block_world), (width, height), vp, - Placement::Above, - POPOVER_GAP, + Placement::AboveStart, + TOOLBAR_CHROME_OFFSET, POPOVER_EDGE_MARGIN, ) .rect; self.bookmark_toolbar_rect = Some(rect); - let make_text_btn = |suffix: &'static str, - label: &'static str, - w: f32, - accent: bool, - active: bool, - action: Option, - cx: &mut Context| { - let mut el = div() - .id(SharedString::from(format!("bm-tb-{suffix}"))) - .flex_none() - .w(px(w)) - .h(px(TOOLBAR_BUTTON)) - .rounded(px(4.0)) - .flex() - .items_center() - .justify_center() - .text_size(px(TYPOGRAPHY.font_xs_px)) - .font_weight(FontWeight::MEDIUM) - .text_color(if accent || active { - palette.brand - } else { - palette.text_primary - }) - .when(active, |el| el.bg(palette.brand.opacity(0.14))) - .snapshot( - SharedString::from(format!("overlay.bookmark_toolbar.{suffix}")), - Some("overlay.bookmark_toolbar"), - ) - .snapshot_focused(active) - .snapshot_text(label) - .child(label); - if let Some(act) = action { - let ev = OverlayEvent::BookmarkToolbarAction { - block_id: block_id.to_string(), - action: act, - }; - el = el - .cursor_pointer() - .hover(move |s| s.bg(hover_bg)) - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_click(emit(cx, move |_: &ClickEvent| ev.clone())); - } - el.into_any_element() + let mut cursor_x = rect.x + TOOLBAR_CHROME_BORDER + TOOLBAR_CHROME_PX; + let btn_y = rect.y + (TOOLBAR_CHROME_HEIGHT - btn) * 0.5; + let open_ev = OverlayEvent::BookmarkToolbarAction { + block_id: block_id_owned.clone(), + action: BookmarkToolbarAction::Open, }; - let make_icon_btn = |suffix: &'static str, - icon_name: &'static str, - active: bool, - is_danger: bool, - action: BookmarkToolbarAction, - cx: &mut Context| { - let ev = OverlayEvent::BookmarkToolbarAction { - block_id: block_id.to_string(), - action, - }; - let color = if is_danger { - danger - } else if active { - palette.brand - } else { - palette.icon - }; - div() - .id(SharedString::from(format!("bm-tb-{suffix}"))) - .flex_none() - .w(px(TOOLBAR_BUTTON)) - .h(px(TOOLBAR_BUTTON)) - .rounded(px(4.0)) - .flex() - .items_center() - .justify_center() - .cursor_pointer() - .when(active, |el| el.bg(palette.brand.opacity(0.14))) - .hover(move |s| s.bg(hover_bg)) - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_click(emit(cx, move |_: &ClickEvent| ev.clone())) - .snapshot( - SharedString::from(format!("overlay.bookmark_toolbar.{suffix}")), - Some("overlay.bookmark_toolbar"), - ) - .snapshot_focused(active) - .child(icon(icon_name, 16.0, color)) - .into_any_element() - }; - - let mut row = div() + let preview_chip = div() + .id("bm-tb-open") + .flex_none() + .w(px(preview_w)) + .h(px(btn)) + .px(px(6.0)) + .rounded(px(TOOLBAR_CHROME_BTN_RADIUS)) + .overflow_hidden() .flex() .items_center() - .gap(px(TOOLBAR_GAP)) - .child(make_text_btn( - "open", - "Open \u{2197}", - 50.0, - true, - false, - Some(BookmarkToolbarAction::Open), - cx, - )) - .child(make_text_btn( - "edit", - "Edit", - 36.0, - false, - false, - Some(BookmarkToolbarAction::Edit), - cx, - )) - .child(make_text_btn( - "inline", - "Inline", - 40.0, - false, - false, - Some(BookmarkToolbarAction::ConvertToInline), - cx, - )) - .child(make_text_btn("card", "Card", 38.0, false, true, None, cx)); - if can_embed { - row = row.child(make_text_btn( - "embed", - "Embed", - 46.0, - false, - false, - Some(BookmarkToolbarAction::ConvertToEmbed), - cx, - )); - } - row = row - .child(make_text_btn( - "style", - current_style.label(), - 68.0, - false, - false, - Some(BookmarkToolbarAction::SetStyle( - current_style.next_in_page(), - )), - cx, - )) - .child(make_icon_btn( - "caption", - "CaptionIcon", - false, - false, - BookmarkToolbarAction::Caption, - cx, - )) - .child(make_icon_btn( - "copy", - "CopyIcon", - false, - false, - BookmarkToolbarAction::Copy, - cx, - )) - .child(make_icon_btn( - "duplicate", - "DuplicateIcon", - false, - false, - BookmarkToolbarAction::Duplicate, - cx, - )) - .child(make_icon_btn( - "delete", - "DeleteIcon", - false, - true, - BookmarkToolbarAction::Delete, - cx, - )); - - let root = place(rect) - .id("bookmark-toolbar") - .block_mouse_except_scroll() + .cursor_pointer() + .hover(move |s| s.bg(hover_bg)) + .text_size(px(TYPOGRAPHY.font_sm_px)) + .text_color(chrome_link_color(palette)) .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_mouse_down_out(|_: &MouseDownEvent, _, _| {}) - .p(px(pad)) - .rounded(px(TOOLBAR_RADIUS)) - .bg(palette.panel) - .border_1() - .border_color(palette.border) - .shadow(palette.theme.shadows("--affine-toolbar-shadow").into()) + .on_click(emit(cx, move |_: &ClickEvent| open_ev.clone())) + .snapshot( + "overlay.bookmark_toolbar.open", + Some("overlay.bookmark_toolbar"), + ) + .snapshot_text(host.clone()) + .child(host) + .into_any_element(); + cursor_x += preview_w + group_gap + sep_w + group_gap; + + let view_ink = if view_open { + palette.brand + } else { + palette.text_primary + }; + let toggle_view = OverlayEvent::ToggleBlockSubmenu(BlockToolbarSubmenu::BookmarkView( + block_id_owned.clone(), + )); + let view_btn = div() + .id("bm-tb-card") + .flex_none() + .w(px(view_w)) + .h(px(btn)) + .px(px(6.0)) + .rounded(px(TOOLBAR_CHROME_BTN_RADIUS)) .flex() .items_center() .justify_center() - .snapshot("overlay.bookmark_toolbar", Some("root.canvas")) - .child(row); - Some(root.into_any_element()) + .gap(px(4.0)) + .cursor_pointer() + .hover(move |s| s.bg(hover_bg)) + .text_size(px(TYPOGRAPHY.font_xs_px)) + .font_weight(FontWeight::MEDIUM) + .text_color(view_ink) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(emit(cx, move |_: &ClickEvent| toggle_view.clone())) + .snapshot( + "overlay.bookmark_toolbar.card", + Some("overlay.bookmark_toolbar"), + ) + .snapshot_focused(view_open) + .snapshot_text("Card view") + .child("Card view") + .child(chrome_icon(ChromeIcon::ChevronDown, 12.0, view_ink)) + .into_any_element(); + cursor_x += view_w + group_gap + sep_w + group_gap; + + let style_ink = if style_open { + palette.brand + } else { + palette.text_primary + }; + let toggle_style = OverlayEvent::ToggleBlockSubmenu(BlockToolbarSubmenu::BookmarkStyle( + block_id_owned.clone(), + )); + let style_btn = div() + .id("bm-tb-style") + .flex_none() + .w(px(style_w)) + .h(px(btn)) + .px(px(6.0)) + .rounded(px(TOOLBAR_CHROME_BTN_RADIUS)) + .flex() + .items_center() + .justify_center() + .gap(px(4.0)) + .cursor_pointer() + .hover(move |s| s.bg(hover_bg)) + .text_size(px(TYPOGRAPHY.font_xs_px)) + .font_weight(FontWeight::MEDIUM) + .text_color(style_ink) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(emit(cx, move |_: &ClickEvent| toggle_style.clone())) + .snapshot( + "overlay.bookmark_toolbar.style", + Some("overlay.bookmark_toolbar"), + ) + .snapshot_focused(style_open) + .snapshot_text("Style") + .child("Style") + .child(chrome_icon(ChromeIcon::ChevronDown, 12.0, style_ink)) + .into_any_element(); + cursor_x += style_w + group_gap + sep_w + group_gap; + + let cap_btn = toolbar_icon_button( + "bm-tb-caption", + "overlay.bookmark_toolbar.caption", + "overlay.bookmark_toolbar", + "Caption", + FlowRect::new(cursor_x, btn_y, btn, btn), + false, + true, + chrome_icon(ChromeIcon::Caption, TOOLBAR_CHROME_ICON, palette.icon), + OverlayEvent::BookmarkToolbarAction { + block_id: block_id_owned.clone(), + action: BookmarkToolbarAction::Caption, + }, + palette, + cx, + ); + cursor_x += btn + group_gap + sep_w + group_gap; + + let more_ink = if more_open { + palette.brand + } else { + palette.icon + }; + let more_btn = toolbar_icon_button( + "bm-tb-more", + "overlay.bookmark_toolbar.more", + "overlay.bookmark_toolbar", + "More", + FlowRect::new(cursor_x, btn_y, btn, btn), + more_open, + true, + chrome_icon(ChromeIcon::MoreVertical, TOOLBAR_CHROME_ICON, more_ink), + OverlayEvent::ToggleBlockSubmenu(BlockToolbarSubmenu::BookmarkMore( + block_id_owned.clone(), + )), + palette, + cx, + ); + + let root = append_toolbar_groups( + toolbar_chrome_container( + "bookmark-toolbar", + rect, + 1.0, + true, + "overlay.bookmark_toolbar", + palette, + ), + vec![ + vec![preview_chip], + vec![view_btn], + vec![style_btn], + vec![cap_btn], + vec![more_btn], + ], + palette, + ); + let mut out = vec![root.into_any_element()]; + + if view_open { + let mut rows = vec![ + ( + "inline", + "Inline view", + false, + Some(BookmarkToolbarAction::ConvertToInline), + ), + ("card", "Card view", true, None), + ]; + if can_embed { + rows.push(( + "embed", + "Embed view", + false, + Some(BookmarkToolbarAction::ConvertToEmbed), + )); + } + let menu_h = (2.0 * (TOOLBAR_MENU_PADDING + TOOLBAR_CHROME_BORDER) + + rows.len() as f32 * TOOLBAR_MENU_ROW_H) + .round(); + let menu_placed = place_popover( + rect, + (TOOLBAR_MENU_MIN_W, menu_h), + vp, + Placement::BelowStart, + 4.0, + POPOVER_EDGE_MARGIN, + ); + self.bookmark_submenu_rect = Some(menu_placed.rect); + let mut panel = toolbar_dropdown_panel( + "bm-view-menu", + menu_placed.rect, + 1.0, + true, + "overlay.bookmark_toolbar.view_menu", + "overlay.bookmark_toolbar", + palette, + ); + for (suffix, label, selected, act) in rows { + let ev = match act { + Some(action) => OverlayEvent::BookmarkToolbarAction { + block_id: block_id_owned.clone(), + action, + }, + None => OverlayEvent::ToggleBlockSubmenu(BlockToolbarSubmenu::BookmarkView( + block_id_owned.clone(), + )), + }; + panel = panel.child(toolbar_menu_row( + format!("bm-view-{suffix}"), + format!("overlay.bookmark_toolbar.{suffix}"), + "overlay.bookmark_toolbar.view_menu", + label, + chrome_icon(ChromeIcon::Bookmark, TOOLBAR_MENU_ICON, palette.icon), + selected, + MenuActionVariant::Normal, + true, + ev, + palette, + cx, + )); + } + out.push(dismiss_submenu_outside(panel, rect, cx).into_any_element()); + } else if style_open { + let rows = [ + ( + "horizontal", + "Large horizontal", + BookmarkCardStyle::Horizontal, + ), + ("list", "Small horizontal", BookmarkCardStyle::List), + ]; + let menu_h = (2.0 * (TOOLBAR_MENU_PADDING + TOOLBAR_CHROME_BORDER) + + rows.len() as f32 * TOOLBAR_MENU_ROW_H) + .round(); + let menu_placed = place_popover( + rect, + (TOOLBAR_MENU_MIN_W, menu_h), + vp, + Placement::BelowStart, + 4.0, + POPOVER_EDGE_MARGIN, + ); + self.bookmark_submenu_rect = Some(menu_placed.rect); + let mut panel = toolbar_dropdown_panel( + "bm-style-menu", + menu_placed.rect, + 1.0, + true, + "overlay.bookmark_toolbar.style_menu", + "overlay.bookmark_toolbar", + palette, + ); + for (suffix, label, style) in rows { + panel = panel.child(toolbar_menu_row( + format!("bm-style-{suffix}"), + format!("overlay.bookmark_toolbar.style.{suffix}"), + "overlay.bookmark_toolbar.style_menu", + label, + chrome_icon(ChromeIcon::Bookmark, TOOLBAR_MENU_ICON, palette.icon), + current_style == style, + MenuActionVariant::Normal, + true, + OverlayEvent::BookmarkToolbarAction { + block_id: block_id_owned.clone(), + action: BookmarkToolbarAction::SetStyle(style), + }, + palette, + cx, + )); + } + out.push(dismiss_submenu_outside(panel, rect, cx).into_any_element()); + } else if more_open { + let menu_h = (2.0 * (TOOLBAR_MENU_PADDING + TOOLBAR_CHROME_BORDER) + + 3.0 * TOOLBAR_MENU_ROW_H + + 9.0) + .round(); + let anchor = FlowRect::new( + (rect.right() - TOOLBAR_MENU_MIN_W).max(rect.x), + rect.y, + TOOLBAR_MENU_MIN_W, + rect.h, + ); + let menu_placed = place_popover( + anchor, + (TOOLBAR_MENU_MIN_W, menu_h), + vp, + Placement::BelowStart, + 4.0, + POPOVER_EDGE_MARGIN, + ); + self.bookmark_submenu_rect = Some(menu_placed.rect); + let mut panel = toolbar_dropdown_panel( + "bm-more-menu", + menu_placed.rect, + 1.0, + true, + "overlay.bookmark_toolbar.more_menu", + "overlay.bookmark_toolbar", + palette, + ); + for (suffix, label, icon_name, action) in [ + ("copy", "Copy", "CopyIcon", BookmarkToolbarAction::Copy), + ( + "duplicate", + "Duplicate", + "DuplicateIcon", + BookmarkToolbarAction::Duplicate, + ), + ] { + panel = panel.child(toolbar_menu_row( + format!("bm-more-{suffix}"), + format!("overlay.bookmark_toolbar.{suffix}"), + "overlay.bookmark_toolbar.more_menu", + label, + icon(icon_name, TOOLBAR_MENU_ICON, palette.icon).into_any_element(), + false, + MenuActionVariant::Normal, + true, + OverlayEvent::BookmarkToolbarAction { + block_id: block_id_owned.clone(), + action, + }, + palette, + cx, + )); + } + panel = panel.child(menu_horizontal_separator(palette)); + panel = panel.child(toolbar_menu_row( + "bm-more-delete", + "overlay.bookmark_toolbar.delete", + "overlay.bookmark_toolbar.more_menu", + "Delete", + icon("DeleteIcon", TOOLBAR_MENU_ICON, palette.icon).into_any_element(), + false, + MenuActionVariant::Destructive, + true, + OverlayEvent::BookmarkToolbarAction { + block_id: block_id_owned, + action: BookmarkToolbarAction::Delete, + }, + palette, + cx, + )); + out.push(dismiss_submenu_outside(panel, rect, cx).into_any_element()); + } + out } } diff --git a/blocksuite/crates/editor/src/overlays/bookmark_touch_bar.rs b/blocksuite/crates/editor/src/overlays/bookmark_touch_bar.rs new file mode 100644 index 0000000000..1ffe45e725 --- /dev/null +++ b/blocksuite/crates/editor/src/overlays/bookmark_touch_bar.rs @@ -0,0 +1,301 @@ +//! Bottom-docked touch (and narrow-window) context bar for selected `affine:bookmark` blocks +//! (`overlay.bookmark_toolbar`): a horizontally scrollable strip of `>= 44 pt` buttons with a +//! pinned `Delete`. + +use ui::{ + AnyElement, ClickEvent, Context, FontWeight, MouseButton, MouseDownEvent, ScrollEvent, + SharedString, div, prelude::*, px, +}; + +use crate::{ + block_flow::FlowRect, + theme::{Palette, TYPOGRAPHY}, +}; + +use super::{ + BookmarkCardStyle, BookmarkToolbarAction, OverlayEvent, OverlayHost, OverlayScene, Overlays, + POPOVER_BORDER, POPOVER_EDGE_MARGIN, POPOVER_GAP, Placement, TOOLBAR_BUTTON, TOOLBAR_PADDING, + TOOLBAR_RADIUS, emit, icon, place, place_popover, +}; + +impl Overlays { + #[allow(clippy::too_many_arguments)] + pub(super) fn render_bookmark_touch_bar( + &mut self, + scene: &OverlayScene<'_>, + palette: &Palette, + block_id: &str, + can_embed: bool, + current_style: BookmarkCardStyle, + touch: bool, + block_world: FlowRect, + cx: &mut Context, + ) -> Vec { + let vp = scene.popover_viewport(); + let pad = TOOLBAR_PADDING; + let chrome = 2.0 * (pad + POPOVER_BORDER); + let max_w = (vp.w - 2.0 * POPOVER_EDGE_MARGIN).max(200.0); + let hover_bg = palette.hover; + let danger = palette + .theme + .css_var("--affine-error-color") + .unwrap_or(palette.icon); + let btn_h = if touch { 44.0_f32 } else { TOOLBAR_BUTTON }; + let icon_w = if touch { 44.0_f32 } else { TOOLBAR_BUTTON }; + let gap = 4.0_f32; + let sep_slot = 9.0_f32; + let make_touch_text = |suffix: &'static str, + label: &'static str, + w: f32, + accent: bool, + active: bool, + action: Option, + cx: &mut Context| + -> (f32, Box AnyElement>) { + let text_col = if accent || active { + palette.brand + } else { + palette.text_primary + }; + let active_bg = palette.brand.opacity(0.14); + let click_handler = action.map(|act| { + let ev = OverlayEvent::BookmarkToolbarAction { + block_id: block_id.to_string(), + action: act, + }; + emit(cx, move |_: &ClickEvent| ev.clone()) + }); + ( + w, + Box::new(move |fully_visible| { + let mut el = div() + .id(SharedString::from(format!("bm-tb-{suffix}"))) + .w(px(w)) + .h(px(btn_h)) + .px(px(8.0)) + .rounded(px(4.0)) + .flex() + .items_center() + .justify_center() + .text_size(px(TYPOGRAPHY.font_xs_px)) + .font_weight(FontWeight::MEDIUM) + .text_color(text_col) + .when(active, |el| el.bg(active_bg)) + .child(label); + if let Some(handler) = click_handler { + el = el + .cursor_pointer() + .hover(move |s| s.bg(hover_bg)) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(handler); + } + if fully_visible { + el = el + .snapshot( + SharedString::from(format!("overlay.bookmark_toolbar.{suffix}")), + Some("overlay.bookmark_toolbar"), + ) + .snapshot_focused(active) + .snapshot_text(label); + } + el.into_any_element() + }), + ) + }; + let make_touch_icon = |suffix: &'static str, + icon_name: &'static str, + active: bool, + is_danger: bool, + action: BookmarkToolbarAction, + cx: &mut Context| + -> (f32, Box AnyElement>) { + let ev = OverlayEvent::BookmarkToolbarAction { + block_id: block_id.to_string(), + action, + }; + let click_handler = emit(cx, move |_: &ClickEvent| ev.clone()); + let color = if is_danger { + danger + } else if active { + palette.brand + } else { + palette.icon + }; + let active_bg = palette.brand.opacity(0.14); + ( + icon_w, + Box::new(move |fully_visible| { + let mut el = div() + .id(SharedString::from(format!("bm-tb-{suffix}"))) + .w(px(icon_w)) + .h(px(btn_h)) + .rounded(px(4.0)) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .when(active, |el| el.bg(active_bg)) + .hover(move |s| s.bg(hover_bg)) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(click_handler) + .child(icon(icon_name, 16.0, color)); + if fully_visible { + el = el + .snapshot( + SharedString::from(format!("overlay.bookmark_toolbar.{suffix}")), + Some("overlay.bookmark_toolbar"), + ) + .snapshot_focused(active); + } + el.into_any_element() + }), + ) + }; + + let mut items: Vec<(f32, Box AnyElement>)> = vec![ + make_touch_text( + "open", + "Open \u{2197}", + 60.0, + true, + false, + Some(BookmarkToolbarAction::Open), + cx, + ), + make_touch_text( + "edit", + "Edit", + 46.0, + false, + false, + Some(BookmarkToolbarAction::Edit), + cx, + ), + make_touch_text( + "inline", + "Inline", + 52.0, + false, + false, + Some(BookmarkToolbarAction::ConvertToInline), + cx, + ), + make_touch_text("card", "Card", 48.0, false, true, None, cx), + ]; + if can_embed { + items.push(make_touch_text( + "embed", + "Embed", + 58.0, + false, + false, + Some(BookmarkToolbarAction::ConvertToEmbed), + cx, + )); + } + items.push(make_touch_text( + "style", + current_style.label(), + 68.0, + false, + false, + Some(BookmarkToolbarAction::SetStyle( + current_style.next_in_page(), + )), + cx, + )); + items.push(make_touch_icon( + "caption", + "CaptionIcon", + false, + false, + BookmarkToolbarAction::Caption, + cx, + )); + items.push(make_touch_icon( + "copy", + "CopyIcon", + false, + false, + BookmarkToolbarAction::Copy, + cx, + )); + items.push(make_touch_icon( + "duplicate", + "DuplicateIcon", + false, + false, + BookmarkToolbarAction::Duplicate, + cx, + )); + + let content_w: f32 = + items.iter().map(|(w, _)| *w).sum::() + (items.len() - 1) as f32 * gap; + let pinned_right_w = sep_slot + icon_w + 2.0 * gap; + let width = (content_w + pinned_right_w + chrome).min(max_w).round(); + let height = (btn_h + chrome).round(); + let avail_w = (width - chrome - pinned_right_w).max(icon_w); + let max_scroll = (content_w - avail_w).max(0.0).ceil(); + let scroll_key = format!("bm:{block_id}"); + let scroll_x = self.sync_touch_bar_scroll(&scroll_key, max_scroll); + + let rect = if touch { + super::helpers::place_touch_docked_toolbar(vp, width, height) + } else { + place_popover( + scene.world_to_screen(&block_world), + (width, height), + vp, + Placement::Above, + POPOVER_GAP, + POPOVER_EDGE_MARGIN, + ) + .rect + }; + self.bookmark_toolbar_rect = Some(rect); + + let strip = Self::build_touch_scroll_strip(avail_w, btn_h, gap, scroll_x, palette, items); + let del_btn = make_touch_icon( + "delete", + "DeleteIcon", + false, + true, + BookmarkToolbarAction::Delete, + cx, + ) + .1(true); + + let root = place(rect) + .id("bookmark-toolbar") + .occlude() + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_mouse_down_out(|_: &MouseDownEvent, _, _| {}) + .on_scroll(emit(cx, move |event: &ScrollEvent| { + let (dx, dy) = crate::scroll::wheel_delta(event, rect.h); + OverlayEvent::TouchContextBarScroll(crate::scroll::dominant_axis_delta(dx, dy)) + })) + .p(px(pad)) + .rounded(px(TOOLBAR_RADIUS)) + .bg(palette.panel) + .border_1() + .border_color(palette.border) + .shadow(palette.theme.shadows("--affine-toolbar-shadow").into()) + .flex() + .items_center() + .gap(px(gap)) + .snapshot("overlay.bookmark_toolbar", Some("root.canvas")) + .child(strip) + .child( + div() + .flex_none() + .w(px(sep_slot)) + .h(px(btn_h)) + .flex() + .items_center() + .justify_center() + .child(div().w(px(1.0)).h(px(16.0)).bg(palette.divider)), + ) + .child(del_btn); + vec![root.into_any_element()] + } +} diff --git a/blocksuite/crates/editor/src/overlays/callout_bar.rs b/blocksuite/crates/editor/src/overlays/callout_bar.rs index db715ea24a..41f91979f7 100644 --- a/blocksuite/crates/editor/src/overlays/callout_bar.rs +++ b/blocksuite/crates/editor/src/overlays/callout_bar.rs @@ -7,12 +7,21 @@ use ui::{ SharedString, div, prelude::*, px, }; -use crate::theme::{Palette, TYPOGRAPHY}; +use crate::{ + block_flow::FlowRect, + theme::{Palette, TYPOGRAPHY}, +}; use super::{ - DocEdit, OverlayEffects, OverlayEvent, OverlayHost, OverlayScene, Overlays, POPOVER_BORDER, - POPOVER_EDGE_MARGIN, POPOVER_GAP, Placement, TOOLBAR_BUTTON, TOOLBAR_PADDING, TOOLBAR_RADIUS, - emit, icon, place, place_popover, + BlockToolbarSubmenu, ChromeIcon, DocEdit, MenuActionVariant, OverlayEffects, OverlayEvent, + OverlayHost, OverlayScene, Overlays, POPOVER_BORDER, POPOVER_EDGE_MARGIN, Placement, + TOOLBAR_BUTTON, TOOLBAR_CHROME_BORDER, TOOLBAR_CHROME_BTN, TOOLBAR_CHROME_BTN_RADIUS, + TOOLBAR_CHROME_GAP, TOOLBAR_CHROME_HEIGHT, TOOLBAR_CHROME_ICON, TOOLBAR_CHROME_OFFSET, + TOOLBAR_CHROME_PX, TOOLBAR_MENU_ICON, TOOLBAR_MENU_MIN_W, TOOLBAR_MENU_PADDING, + TOOLBAR_MENU_ROW_H, TOOLBAR_PADDING, TOOLBAR_RADIUS, TOOLBAR_SEP_SLOT, append_toolbar_groups, + chrome_border_color, chrome_icon, dismiss_submenu_outside, duotone_text_badge, emit, icon, + place, place_popover, toolbar_chrome_container, toolbar_dropdown_panel, toolbar_icon_button, + toolbar_menu_row, }; /// 9 semantic Callout background color options matching JS `0.27.5` `callout/configs/toolbar.ts:26-36`. @@ -114,6 +123,7 @@ impl Overlays { ) -> Vec { self.callout_toolbar_rect = None; self.callout_icon_picker_rect = None; + self.callout_submenu_rect = None; if scene.page_readonly { return Vec::new(); } @@ -359,86 +369,274 @@ impl Overlays { out.push(bar.into_any_element()); rect } else { - let swatch = 22.0_f32; - let swatch_gap = 4.0_f32; - let bar_gap = 6.0_f32; - let raw_w = - chrome + btn_w + 9.0 * swatch + 8.0 * swatch_gap + btn_w + 2.0 + 4.0 * bar_gap; - let width = raw_w.min(max_w).round(); - let height = (btn_h + chrome).round(); + // Desktop `ToolbarChrome`: [Emoji/Smile ▾] │ [Palette ▾] │ ⋮ More + let btn = TOOLBAR_CHROME_BTN; + let menu_btn_w = btn + 12.0; + let group_gap = TOOLBAR_CHROME_GAP; + let sep_w = TOOLBAR_SEP_SLOT; + let color_open = matches!( + &self.block_submenu, + Some(BlockToolbarSubmenu::CalloutColor(id)) if id == block_id + ); + let more_open = matches!( + &self.block_submenu, + Some(BlockToolbarSubmenu::CalloutMore(id)) if id == block_id + ); + + let group_widths = [menu_btn_w, menu_btn_w, btn]; + let seps = group_widths.len() - 1; + let items_total: f32 = group_widths.iter().sum(); + let slots = group_widths.len() + seps; + let inner_w = items_total + seps as f32 * sep_w + (slots - 1) as f32 * group_gap; + let chrome_x = 2.0 * (TOOLBAR_CHROME_PX + TOOLBAR_CHROME_BORDER); + let width = (inner_w + chrome_x).min(max_w).round(); + let height = (TOOLBAR_CHROME_HEIGHT + 2.0 * TOOLBAR_CHROME_BORDER).round(); let rect = place_popover( scene.world_to_screen(&block_world), (width, height), vp, - Placement::Above, - POPOVER_GAP, + Placement::AboveStart, + TOOLBAR_CHROME_OFFSET, POPOVER_EDGE_MARGIN, ) .rect; self.callout_toolbar_rect = Some(rect); - let mut swatches = div().flex().items_center().gap(px(swatch_gap)); - for (name, css_var) in CALLOUT_BG_COLORS { - let selected = if name == "default" { - raw_bg.is_empty() || raw_bg == "default" - } else { - raw_bg == name - }; - let fill = palette - .theme - .css_var(css_var) - .unwrap_or(palette.background_secondary); - let ev = OverlayEvent::CalloutAction { - block_id: block_id_owned.clone(), - action: CalloutAction::SetBackground(name.to_string()), - }; - swatches = swatches.child( - div() - .id(SharedString::from(format!("callout-bg-{name}"))) - .flex_none() - .w(px(swatch)) - .h(px(swatch)) - .rounded(px(swatch * 0.5)) - .bg(fill) - .border_1() - .border_color(if selected { - palette.brand - } else { - palette.border - }) - .cursor_pointer() - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_click(emit(cx, move |_: &ClickEvent| ev.clone())) - .snapshot( - SharedString::from(format!("overlay.callout_toolbar.bg.{name}")), - Some("overlay.callout_toolbar"), - ) - .snapshot_focused(selected) - .snapshot_text(name), - ); - } - let bar = place(rect) - .id("callout-toolbar") - .block_mouse_except_scroll() - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_mouse_down_out(|_: &MouseDownEvent, _, _| {}) - .p(px(pad)) - .rounded(px(TOOLBAR_RADIUS)) - .bg(palette.panel) - .border_1() - .border_color(palette.border) - .shadow(palette.theme.shadows("--affine-toolbar-shadow").into()) + let mut cursor_x = rect.x + TOOLBAR_CHROME_BORDER + TOOLBAR_CHROME_PX; + let btn_y = rect.y + (TOOLBAR_CHROME_HEIGHT - btn) * 0.5; + + let emoji_ink = if picker_open { + palette.brand + } else { + palette.icon + }; + let emoji_ev = OverlayEvent::CalloutAction { + block_id: block_id_owned.clone(), + action: CalloutAction::ToggleIconPicker, + }; + let emoji_btn = div() + .id("callout-tb-icon") + .flex_none() + .w(px(menu_btn_w)) + .h(px(btn)) + .rounded(px(TOOLBAR_CHROME_BTN_RADIUS)) .flex() .items_center() .justify_center() - .gap(px(bar_gap)) - .snapshot("overlay.callout_toolbar", Some("root.canvas")) - .child(icon_btn) - .child(div().flex_none().w(px(1.0)).h(px(16.0)).bg(palette.divider)) - .child(swatches) - .child(div().flex_none().w(px(1.0)).h(px(16.0)).bg(palette.divider)) - .child(del_btn); + .gap(px(1.0)) + .cursor_pointer() + .hover(move |s| s.bg(hover_bg)) + .text_size(px(14.0)) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(emit(cx, move |_: &ClickEvent| emoji_ev.clone())) + .snapshot( + "overlay.callout_toolbar.icon", + Some("overlay.callout_toolbar"), + ) + .snapshot_focused(picker_open) + .snapshot_text(if current_icon.is_empty() { + "Icon".to_string() + } else { + current_icon.clone() + }) + .child(if current_icon.is_empty() { + chrome_icon(ChromeIcon::Smile, TOOLBAR_CHROME_ICON, emoji_ink) + } else { + div().child(current_icon.clone()).into_any_element() + }) + .child(chrome_icon(ChromeIcon::ChevronDown, 12.0, emoji_ink)) + .into_any_element(); + cursor_x += menu_btn_w + group_gap + sep_w + group_gap; + + let color_ink = if color_open { + palette.brand + } else { + palette.icon + }; + let color_ev = OverlayEvent::ToggleBlockSubmenu(BlockToolbarSubmenu::CalloutColor( + block_id_owned.clone(), + )); + let color_btn = div() + .id("callout-tb-color") + .flex_none() + .w(px(menu_btn_w)) + .h(px(btn)) + .rounded(px(TOOLBAR_CHROME_BTN_RADIUS)) + .flex() + .items_center() + .justify_center() + .gap(px(1.0)) + .cursor_pointer() + .hover(move |s| s.bg(hover_bg)) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(emit(cx, move |_: &ClickEvent| color_ev.clone())) + .snapshot( + "overlay.callout_toolbar.color", + Some("overlay.callout_toolbar"), + ) + .snapshot_focused(color_open) + .snapshot_text("Background") + .child(chrome_icon( + ChromeIcon::Palette, + TOOLBAR_CHROME_ICON, + color_ink, + )) + .child(chrome_icon(ChromeIcon::ChevronDown, 12.0, color_ink)) + .into_any_element(); + cursor_x += menu_btn_w + group_gap + sep_w + group_gap; + + let more_ink = if more_open { + palette.brand + } else { + palette.icon + }; + let more_btn = toolbar_icon_button( + "callout-tb-more", + "overlay.callout_toolbar.more", + "overlay.callout_toolbar", + "More", + FlowRect::new(cursor_x, btn_y, btn, btn), + more_open, + true, + chrome_icon(ChromeIcon::MoreVertical, TOOLBAR_CHROME_ICON, more_ink), + OverlayEvent::ToggleBlockSubmenu(BlockToolbarSubmenu::CalloutMore( + block_id_owned.clone(), + )), + palette, + cx, + ); + + let bar = append_toolbar_groups( + toolbar_chrome_container( + "callout-toolbar", + rect, + 1.0, + true, + "overlay.callout_toolbar", + palette, + ), + vec![vec![emoji_btn], vec![color_btn], vec![more_btn]], + palette, + ); out.push(bar.into_any_element()); + + if color_open { + let heading_h = 22.0_f32; + let menu_w = 196.0_f32.min((vp.w - 2.0 * POPOVER_EDGE_MARGIN).max(160.0)); + let menu_h = (2.0 * (TOOLBAR_MENU_PADDING + TOOLBAR_CHROME_BORDER) + + heading_h + + CALLOUT_BG_COLORS.len() as f32 * TOOLBAR_MENU_ROW_H) + .min((vp.h - 2.0 * POPOVER_EDGE_MARGIN).max(180.0)) + .round(); + let placed = place_popover( + rect, + (menu_w, menu_h), + vp, + Placement::BelowStart, + 4.0, + POPOVER_EDGE_MARGIN, + ); + self.callout_submenu_rect = Some(placed.rect); + let mut panel = toolbar_dropdown_panel( + "callout-color-menu", + placed.rect, + 1.0, + true, + "overlay.callout_toolbar.color_menu", + "overlay.callout_toolbar", + palette, + ) + .child( + div() + .flex_none() + .h(px(heading_h)) + .px(px(8.0)) + .flex() + .items_center() + .text_size(px(TYPOGRAPHY.font_xs_px)) + .font_weight(FontWeight::MEDIUM) + .text_color(palette.text_secondary) + .child("Background"), + ); + let border = chrome_border_color(palette); + for (name, css_var) in CALLOUT_BG_COLORS { + let selected = if name == "default" { + raw_bg.is_empty() || raw_bg == "default" + } else { + raw_bg == name + }; + let fill = palette.theme.css_var(css_var); + let mut chars = name.chars(); + let label = match chars.next() { + Some(first) => { + format!("{}{} Background", first.to_uppercase(), chars.as_str()) + } + None => "Background".to_string(), + }; + panel = panel.child(toolbar_menu_row( + format!("callout-bg-{name}"), + format!("overlay.callout_toolbar.bg.{name}"), + "overlay.callout_toolbar.color_menu", + SharedString::from(label), + duotone_text_badge(palette.text_primary, fill, border), + selected, + MenuActionVariant::Normal, + true, + OverlayEvent::CalloutAction { + block_id: block_id_owned.clone(), + action: CalloutAction::SetBackground(name.to_string()), + }, + palette, + cx, + )); + } + out.push(dismiss_submenu_outside(panel, rect, cx).into_any_element()); + } else if more_open { + let menu_h = (2.0 * (TOOLBAR_MENU_PADDING + TOOLBAR_CHROME_BORDER) + + TOOLBAR_MENU_ROW_H) + .round(); + let anchor = FlowRect::new( + (rect.right() - TOOLBAR_MENU_MIN_W).max(rect.x), + rect.y, + TOOLBAR_MENU_MIN_W, + rect.h, + ); + let placed = place_popover( + anchor, + (TOOLBAR_MENU_MIN_W, menu_h), + vp, + Placement::BelowStart, + 4.0, + POPOVER_EDGE_MARGIN, + ); + self.callout_submenu_rect = Some(placed.rect); + let panel = toolbar_dropdown_panel( + "callout-more-menu", + placed.rect, + 1.0, + true, + "overlay.callout_toolbar.more_menu", + "overlay.callout_toolbar", + palette, + ) + .child(toolbar_menu_row( + "callout-tb-delete", + "overlay.callout_toolbar.delete", + "overlay.callout_toolbar.more_menu", + "Delete", + icon("DeleteIcon", TOOLBAR_MENU_ICON, palette.icon).into_any_element(), + false, + MenuActionVariant::Destructive, + true, + OverlayEvent::CalloutAction { + block_id: block_id_owned.clone(), + action: CalloutAction::Delete, + }, + palette, + cx, + )); + out.push(dismiss_submenu_outside(panel, rect, cx).into_any_element()); + } rect }; diff --git a/blocksuite/crates/editor/src/overlays/code_lang_picker/mod.rs b/blocksuite/crates/editor/src/overlays/code_lang_picker/mod.rs index cf27a69533..4032c74eb2 100644 --- a/blocksuite/crates/editor/src/overlays/code_lang_picker/mod.rs +++ b/blocksuite/crates/editor/src/overlays/code_lang_picker/mod.rs @@ -78,6 +78,16 @@ impl CodeLangPicker { self.scroll_offset = self.scroll_offset.clamp(0.0, self.max_scroll); } + /// Highlight the row under a resting pointer `list_y` pixels below the top of the list. + pub fn hover_list_y(&mut self, list_y: f32) { + let row_h = self.row_height.max(1.0); + let rows = ((self.max_scroll + self.list_height) / row_h).round() as usize; + let idx = ((list_y + self.scroll_offset) / row_h).floor().max(0.0) as usize; + if idx < rows { + self.selected = idx; + } + } + /// Apply a subpixel scroll delta in logical pixels via [`ScrollAxis`]. pub fn scroll_by_px(&mut self, delta_y: f32) -> bool { let mut axis = ScrollAxis::new(self.scroll_offset, self.max_scroll); @@ -217,10 +227,13 @@ impl Overlays { self.open_code_lang_picker_internal(block_id.clone(), current_lang, touch, now_ms); effects.redraw = true; } - OverlayEvent::CodeLangPickerScroll(delta_y) => { + OverlayEvent::CodeLangPickerScroll { delta_y, pointer_y } => { if let Some(picker) = self.code_lang_picker_mut() && picker.scroll_by_px(*delta_y) { + if let Some(list_y) = pointer_y { + picker.hover_list_y(*list_y); + } effects.redraw = true; } } @@ -383,6 +396,39 @@ mod tests { ); } + #[test] + fn code_lang_picker_wheel_highlights_the_row_under_the_resting_pointer() { + let mut overlays = Overlays::new(); + overlays.open_code_lang_picker("b-code".into(), "rust", 0.0); + let picker = overlays.code_lang_picker_mut().unwrap(); + picker.row_height = 32.0; + picker.list_height = 320.0; + picker.max_scroll = 1000.0; + picker.scroll_offset = 0.0; + picker.selected = 0; + // (delta, pointer, expected row): `None` keeps the highlight where it was. + for (delta_y, pointer_y, selected) in [ + (-64.0, Some(40.0), 3), + (-32.0, Some(40.0), 4), + (-32.0, None, 4), + (96.0, Some(0.0), 1), + ] { + let mut effects = super::super::OverlayEffects::default(); + overlays.handle_code_and_media_event( + &OverlayEvent::CodeLangPickerScroll { delta_y, pointer_y }, + None, + 10.0, + &mut effects, + ); + assert!(effects.redraw); + assert_eq!( + overlays.code_lang_picker().unwrap().selected, + selected, + "scroll {delta_y} with the pointer at {pointer_y:?}" + ); + } + } + #[test] fn code_lang_picker_hover_moves_single_focused_row_and_remembers_recent() { let mut overlays = Overlays::new(); diff --git a/blocksuite/crates/editor/src/overlays/code_lang_picker/render.rs b/blocksuite/crates/editor/src/overlays/code_lang_picker/render.rs index 1e438b988b..540700b547 100644 --- a/blocksuite/crates/editor/src/overlays/code_lang_picker/render.rs +++ b/blocksuite/crates/editor/src/overlays/code_lang_picker/render.rs @@ -400,6 +400,13 @@ impl Overlays { s } }; + // Screen y of the list top: border, padding, search box, and separator above it. + let list_top = placed.rect.y + + 0.5 + + PICKER_PADDING + + search_h + + 2.0 * PICKER_SEP_MARGIN + + PICKER_SEP_HEIGHT; let mut root = place(placed.rect) .id("code-lang-picker") .flex() @@ -423,9 +430,15 @@ impl Overlays { .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_scroll(cx.listener(move |view: &mut V, ev: &ScrollEvent, w, cx| { cx.stop_propagation(); - let (_, dy) = wheel_delta(ev, list_h.max(row_h)); - if dy != 0.0 { - view.dispatch_overlay(OverlayEvent::CodeLangPickerScroll(dy), w, cx); + let (_, delta_y) = wheel_delta(ev, list_h.max(row_h)); + if delta_y != 0.0 { + let list_y = f32::from(ev.position.y) - list_top; + let pointer_y = (0.0..list_h).contains(&list_y).then_some(list_y); + view.dispatch_overlay( + OverlayEvent::CodeLangPickerScroll { delta_y, pointer_y }, + w, + cx, + ); } })) .on_mouse_down_out(emit(cx, |_: &MouseDownEvent| { diff --git a/blocksuite/crates/editor/src/overlays/embed_toolbar.rs b/blocksuite/crates/editor/src/overlays/embed_toolbar.rs new file mode 100644 index 0000000000..b95b393e7d --- /dev/null +++ b/blocksuite/crates/editor/src/overlays/embed_toolbar.rs @@ -0,0 +1,551 @@ +//! Floating selection toolbar for `affine:embed-linked-doc`, `affine:embed-synced-doc`, +//! and external embed blocks (YouTube / Figma / GitHub / Loom / Web / Iframe / Html), +//! built on the shared `ToolbarChrome`. + +use blocksuite_playground_doc::read::BlockContent; +use ui::{AnyElement, ClickEvent, Context, FontWeight, MouseButton, div, prelude::*, px}; + +use crate::{ + block_flow::FlowRect, + theme::{Palette, TYPOGRAPHY}, +}; + +use super::*; + +/// Actions offered by `overlay.embed_toolbar`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum EmbedToolbarAction { + Open, + ConvertToInline, + ConvertToCard, + ConvertToEmbed, + SetStyle(BookmarkCardStyle), + Caption, + Copy, + Duplicate, + Delete, +} + +impl Overlays { + pub(super) fn render_embed_toolbar( + &mut self, + scene: &OverlayScene<'_>, + palette: &Palette, + cx: &mut Context, + ) -> Vec { + self.embed_toolbar_rect = None; + self.embed_submenu_rect = None; + if scene.page_readonly { + return Vec::new(); + } + let Some(block_id) = scene.selected_embed_block else { + return Vec::new(); + }; + if self + .bookmark_prompt() + .is_some_and(|p| p.block_id == block_id) + { + return Vec::new(); + } + let Some(flow_block) = scene.layout.block(block_id) else { + return Vec::new(); + }; + let block_world = flow_block.rect(); + if !scene.anchor_visible(&block_world) { + return Vec::new(); + } + let Some(node) = scene.snapshot.block(block_id) else { + return Vec::new(); + }; + + let (kind_tag, preview_label, has_caption, has_style) = match &node.content { + BlockContent::EmbedLinkedDoc { caption, .. } => { + let title = if !flow_block.body.plain.is_empty() { + flow_block.body.plain.clone() + } else { + node.props + .get("prop:title") + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) + .unwrap_or("Untitled") + .to_string() + }; + ("linked", title, !caption.is_empty(), true) + } + BlockContent::EmbedSyncedDoc { caption, .. } => { + ("synced", String::new(), !caption.is_empty(), false) + } + BlockContent::ExternalEmbed { url, caption, .. } => ( + "external", + hostname_preview(url), + !caption.is_empty(), + false, + ), + _ => return Vec::new(), + }; + + let current_style = + BookmarkCardStyle::from_wire(node.props.get("prop:style").and_then(|v| v.as_str())); + let block_id_owned = block_id.to_string(); + let vp = scene.popover_viewport(); + let btn = TOOLBAR_CHROME_BTN; + let group_gap = TOOLBAR_CHROME_GAP; + let sep_w = TOOLBAR_SEP_SLOT; + let hover = palette.hover; + + let view_open = matches!( + &self.block_submenu, + Some(BlockToolbarSubmenu::EmbedView(id)) if id == block_id + ); + let style_open = matches!( + &self.block_submenu, + Some(BlockToolbarSubmenu::EmbedStyle(id)) if id == block_id + ); + let more_open = matches!( + &self.block_submenu, + Some(BlockToolbarSubmenu::EmbedMore(id)) if id == block_id + ); + + let view_label = if kind_tag == "linked" { + "Card view" + } else { + "Embed view" + }; + let preview_w = if preview_label.is_empty() { + 0.0 + } else { + (preview_label.chars().count() as f32 * 6.8 + 16.0).clamp(60.0, 140.0) + }; + let open_w = if kind_tag == "external" { 0.0 } else { 62.0 }; + let view_w = 88.0_f32; + let style_w = if has_style { 68.0_f32 } else { 0.0 }; + + let mut group_widths = Vec::new(); + if open_w > 0.0 { + group_widths.push(open_w); + } + if preview_w > 0.0 { + group_widths.push(preview_w); + } + group_widths.push(view_w); + if style_w > 0.0 { + group_widths.push(style_w); + } + group_widths.push(btn); // caption + group_widths.push(btn); // more + + let seps = group_widths.len().saturating_sub(1); + let items_total: f32 = group_widths.iter().sum(); + let slots = group_widths.len() + seps; + let inner_w = + items_total + seps as f32 * sep_w + slots.saturating_sub(1) as f32 * group_gap; + let chrome_x = 2.0 * (TOOLBAR_CHROME_PX + TOOLBAR_CHROME_BORDER); + let max_w = (vp.w - 2.0 * POPOVER_EDGE_MARGIN).max(200.0); + let width = (inner_w + chrome_x).min(max_w).round(); + let height = (TOOLBAR_CHROME_HEIGHT + 2.0 * TOOLBAR_CHROME_BORDER).round(); + + let placed = place_popover( + scene.world_to_screen(&block_world), + (width, height), + vp, + Placement::AboveStart, + TOOLBAR_CHROME_OFFSET, + POPOVER_EDGE_MARGIN, + ); + self.embed_toolbar_rect = Some(placed.rect); + + let mut groups: Vec> = Vec::new(); + let mut cursor_x = placed.rect.x + TOOLBAR_CHROME_BORDER + TOOLBAR_CHROME_PX; + let btn_y = placed.rect.y + (TOOLBAR_CHROME_HEIGHT - btn) * 0.5; + + if open_w > 0.0 { + let open_ev = OverlayEvent::EmbedToolbarAction { + block_id: block_id_owned.clone(), + action: EmbedToolbarAction::Open, + }; + let el = div() + .id("embed-tb-open") + .flex_none() + .w(px(open_w)) + .h(px(btn)) + .px(px(6.0)) + .rounded(px(TOOLBAR_CHROME_BTN_RADIUS)) + .flex() + .items_center() + .justify_center() + .gap(px(4.0)) + .cursor_pointer() + .hover(move |s| s.bg(hover)) + .text_size(px(TYPOGRAPHY.font_xs_px)) + .font_weight(FontWeight::MEDIUM) + .text_color(palette.text_primary) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(emit(cx, move |_: &ClickEvent| open_ev.clone())) + .snapshot("overlay.embed_toolbar.open", Some("overlay.embed_toolbar")) + .snapshot_text("Open") + .child("Open") + .child(chrome_icon(ChromeIcon::OpenInNew, 14.0, palette.icon)) + .into_any_element(); + groups.push(vec![el]); + cursor_x += open_w + group_gap + sep_w + group_gap; + } + + if preview_w > 0.0 { + let open_ev = OverlayEvent::EmbedToolbarAction { + block_id: block_id_owned.clone(), + action: EmbedToolbarAction::Open, + }; + let link_color = if kind_tag == "external" { + chrome_link_color(palette) + } else { + palette.text_primary + }; + let el = div() + .id("embed-tb-preview") + .flex_none() + .w(px(preview_w)) + .h(px(btn)) + .px(px(6.0)) + .rounded(px(TOOLBAR_CHROME_BTN_RADIUS)) + .overflow_hidden() + .flex() + .items_center() + .cursor_pointer() + .hover(move |s| s.bg(hover)) + .text_size(px(TYPOGRAPHY.font_sm_px)) + .text_color(link_color) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(emit(cx, move |_: &ClickEvent| open_ev.clone())) + .snapshot( + "overlay.embed_toolbar.preview", + Some("overlay.embed_toolbar"), + ) + .snapshot_text(preview_label.clone()) + .child(preview_label) + .into_any_element(); + groups.push(vec![el]); + cursor_x += preview_w + group_gap + sep_w + group_gap; + } + + let toggle_view_ev = OverlayEvent::ToggleBlockSubmenu(BlockToolbarSubmenu::EmbedView( + block_id_owned.clone(), + )); + let view_ink = if view_open { + palette.brand + } else { + palette.text_primary + }; + groups.push(vec![ + div() + .id("embed-tb-view") + .flex_none() + .w(px(view_w)) + .h(px(btn)) + .px(px(6.0)) + .rounded(px(TOOLBAR_CHROME_BTN_RADIUS)) + .flex() + .items_center() + .justify_center() + .gap(px(4.0)) + .cursor_pointer() + .hover(move |s| s.bg(hover)) + .text_size(px(TYPOGRAPHY.font_xs_px)) + .font_weight(FontWeight::MEDIUM) + .text_color(view_ink) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(emit(cx, move |_: &ClickEvent| toggle_view_ev.clone())) + .snapshot("overlay.embed_toolbar.view", Some("overlay.embed_toolbar")) + .snapshot_focused(view_open) + .snapshot_text(view_label) + .child(view_label) + .child(chrome_icon(ChromeIcon::ChevronDown, 12.0, view_ink)) + .into_any_element(), + ]); + cursor_x += view_w + group_gap + sep_w + group_gap; + + if has_style { + let toggle_style_ev = OverlayEvent::ToggleBlockSubmenu( + BlockToolbarSubmenu::EmbedStyle(block_id_owned.clone()), + ); + let style_ink = if style_open { + palette.brand + } else { + palette.text_primary + }; + groups.push(vec![ + div() + .id("embed-tb-style") + .flex_none() + .w(px(style_w)) + .h(px(btn)) + .px(px(6.0)) + .rounded(px(TOOLBAR_CHROME_BTN_RADIUS)) + .flex() + .items_center() + .justify_center() + .gap(px(4.0)) + .cursor_pointer() + .hover(move |s| s.bg(hover)) + .text_size(px(TYPOGRAPHY.font_xs_px)) + .font_weight(FontWeight::MEDIUM) + .text_color(style_ink) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(emit(cx, move |_: &ClickEvent| toggle_style_ev.clone())) + .snapshot("overlay.embed_toolbar.style", Some("overlay.embed_toolbar")) + .snapshot_focused(style_open) + .snapshot_text("Style") + .child("Style") + .child(chrome_icon(ChromeIcon::ChevronDown, 12.0, style_ink)) + .into_any_element(), + ]); + cursor_x += style_w + group_gap + sep_w + group_gap; + } + + let cap_ink = if has_caption { + palette.brand + } else { + palette.icon + }; + groups.push(vec![toolbar_icon_button( + "embed-tb-caption", + "overlay.embed_toolbar.caption", + "overlay.embed_toolbar", + "Caption", + FlowRect::new(cursor_x, btn_y, btn, btn), + has_caption, + true, + chrome_icon(ChromeIcon::Caption, TOOLBAR_CHROME_ICON, cap_ink), + OverlayEvent::EmbedToolbarAction { + block_id: block_id_owned.clone(), + action: EmbedToolbarAction::Caption, + }, + palette, + cx, + )]); + cursor_x += btn + group_gap + sep_w + group_gap; + + let more_ink = if more_open { + palette.brand + } else { + palette.icon + }; + groups.push(vec![toolbar_icon_button( + "embed-tb-more", + "overlay.embed_toolbar.more", + "overlay.embed_toolbar", + "More", + FlowRect::new(cursor_x, btn_y, btn, btn), + more_open, + true, + chrome_icon(ChromeIcon::MoreVertical, TOOLBAR_CHROME_ICON, more_ink), + OverlayEvent::ToggleBlockSubmenu(BlockToolbarSubmenu::EmbedMore( + block_id_owned.clone(), + )), + palette, + cx, + )]); + + let bar = append_toolbar_groups( + toolbar_chrome_container( + "embed-toolbar", + placed.rect, + 1.0, + true, + "overlay.embed_toolbar", + palette, + ), + groups, + palette, + ); + let mut out = vec![bar.into_any_element()]; + + if view_open { + // Every view a block can convert to; the current one is the selected row. An + // external embed converts only when its URL is a web link. + let current = match kind_tag { + "linked" => EmbedToolbarAction::ConvertToCard, + _ => EmbedToolbarAction::ConvertToEmbed, + }; + let convertible = match &node.content { + BlockContent::ExternalEmbed { url, .. } => { + crate::clipboard::sanitize::sanitize_url(url) + .is_some_and(|u| !u.starts_with('#')) + } + _ => true, + }; + let rows: Vec<(&str, &str, bool, EmbedToolbarAction)> = [ + ("inline", "Inline view", EmbedToolbarAction::ConvertToInline), + ("card", "Card view", EmbedToolbarAction::ConvertToCard), + ("embed", "Embed view", EmbedToolbarAction::ConvertToEmbed), + ] + .into_iter() + .filter(|(_, _, action)| *action == current || convertible) + .map(|(suffix, label, action)| (suffix, label, action == current, action)) + .collect(); + let menu_h = (2.0 * (TOOLBAR_MENU_PADDING + TOOLBAR_CHROME_BORDER) + + rows.len() as f32 * TOOLBAR_MENU_ROW_H) + .round(); + let menu_placed = place_popover( + placed.rect, + (TOOLBAR_MENU_MIN_W, menu_h), + vp, + Placement::BelowStart, + 4.0, + POPOVER_EDGE_MARGIN, + ); + self.embed_submenu_rect = Some(menu_placed.rect); + let mut panel = toolbar_dropdown_panel( + "embed-view-menu", + menu_placed.rect, + 1.0, + true, + "overlay.embed_toolbar.view_menu", + "overlay.embed_toolbar", + palette, + ); + for (suffix, label, selected, action) in rows { + panel = panel.child(toolbar_menu_row( + format!("embed-view-{suffix}"), + format!("overlay.embed_toolbar.view.{suffix}"), + "overlay.embed_toolbar.view_menu", + label, + chrome_icon(ChromeIcon::Bookmark, TOOLBAR_MENU_ICON, palette.icon), + selected, + MenuActionVariant::Normal, + true, + OverlayEvent::EmbedToolbarAction { + block_id: block_id_owned.clone(), + action, + }, + palette, + cx, + )); + } + out.push(dismiss_submenu_outside(panel, placed.rect, cx).into_any_element()); + } else if style_open { + let rows = [ + ( + "horizontal", + "Large horizontal", + BookmarkCardStyle::Horizontal, + ), + ("list", "Small horizontal", BookmarkCardStyle::List), + ]; + let menu_h = (2.0 * (TOOLBAR_MENU_PADDING + TOOLBAR_CHROME_BORDER) + + rows.len() as f32 * TOOLBAR_MENU_ROW_H) + .round(); + let menu_placed = place_popover( + placed.rect, + (TOOLBAR_MENU_MIN_W, menu_h), + vp, + Placement::BelowStart, + 4.0, + POPOVER_EDGE_MARGIN, + ); + self.embed_submenu_rect = Some(menu_placed.rect); + let mut panel = toolbar_dropdown_panel( + "embed-style-menu", + menu_placed.rect, + 1.0, + true, + "overlay.embed_toolbar.style_menu", + "overlay.embed_toolbar", + palette, + ); + for (suffix, label, style) in rows { + panel = panel.child(toolbar_menu_row( + format!("embed-style-{suffix}"), + format!("overlay.embed_toolbar.style.{suffix}"), + "overlay.embed_toolbar.style_menu", + label, + chrome_icon(ChromeIcon::Bookmark, TOOLBAR_MENU_ICON, palette.icon), + current_style == style, + MenuActionVariant::Normal, + true, + OverlayEvent::EmbedToolbarAction { + block_id: block_id_owned.clone(), + action: EmbedToolbarAction::SetStyle(style), + }, + palette, + cx, + )); + } + out.push(dismiss_submenu_outside(panel, placed.rect, cx).into_any_element()); + } else if more_open { + let menu_h = (2.0 * (TOOLBAR_MENU_PADDING + TOOLBAR_CHROME_BORDER) + + 3.0 * TOOLBAR_MENU_ROW_H + + 9.0) + .round(); + let anchor = FlowRect::new( + (placed.rect.right() - TOOLBAR_MENU_MIN_W).max(placed.rect.x), + placed.rect.y, + TOOLBAR_MENU_MIN_W, + placed.rect.h, + ); + let menu_placed = place_popover( + anchor, + (TOOLBAR_MENU_MIN_W, menu_h), + vp, + Placement::BelowStart, + 4.0, + POPOVER_EDGE_MARGIN, + ); + self.embed_submenu_rect = Some(menu_placed.rect); + let mut panel = toolbar_dropdown_panel( + "embed-more-menu", + menu_placed.rect, + 1.0, + true, + "overlay.embed_toolbar.more_menu", + "overlay.embed_toolbar", + palette, + ); + for (suffix, label, icon_name, action) in [ + ("copy", "Copy", "CopyIcon", EmbedToolbarAction::Copy), + ( + "duplicate", + "Duplicate", + "DuplicateIcon", + EmbedToolbarAction::Duplicate, + ), + ] { + panel = panel.child(toolbar_menu_row( + format!("embed-more-{suffix}"), + format!("overlay.embed_toolbar.more.{suffix}"), + "overlay.embed_toolbar.more_menu", + label, + icon(icon_name, TOOLBAR_MENU_ICON, palette.icon).into_any_element(), + false, + MenuActionVariant::Normal, + true, + OverlayEvent::EmbedToolbarAction { + block_id: block_id_owned.clone(), + action, + }, + palette, + cx, + )); + } + panel = panel.child(menu_horizontal_separator(palette)); + panel = panel.child(toolbar_menu_row( + "embed-more-delete", + "overlay.embed_toolbar.more.delete", + "overlay.embed_toolbar.more_menu", + "Delete", + icon("DeleteIcon", TOOLBAR_MENU_ICON, palette.icon).into_any_element(), + false, + MenuActionVariant::Destructive, + true, + OverlayEvent::EmbedToolbarAction { + block_id: block_id_owned, + action: EmbedToolbarAction::Delete, + }, + palette, + cx, + )); + out.push(dismiss_submenu_outside(panel, placed.rect, cx).into_any_element()); + } + + out + } +} diff --git a/blocksuite/crates/editor/src/overlays/events.rs b/blocksuite/crates/editor/src/overlays/events.rs index e5469c8a73..5c31928ad8 100644 --- a/blocksuite/crates/editor/src/overlays/events.rs +++ b/blocksuite/crates/editor/src/overlays/events.rs @@ -4,10 +4,11 @@ use y_octo::Any; use crate::block_flow::FlowRect; use super::{ - ActiveSelection, AttachmentToolbarAction, BlockMenuAction, BookmarkToolbarAction, - CalloutAction, CodeMoreActionKind, ContextMenuAction, EquationTarget, FormatAction, - FormatMoreAction, HighlightColor, ImageResizeSide, ImageToolbarAction, KeyboardToolbarAction, - LinkEditField, LinkPopupAction, PdfViewerEvent, SlashCommand, SlashEmbedKind, + ActiveSelection, AttachmentToolbarAction, BlockMenuAction, BlockToolbarSubmenu, + BookmarkToolbarAction, CalloutAction, CodeMoreActionKind, ContextMenuAction, + EmbedToolbarAction, EquationTarget, FormatAction, FormatMoreAction, HighlightColor, + ImageResizeSide, ImageToolbarAction, KeyboardToolbarAction, LinkEditField, LinkPopupAction, + PdfViewerEvent, SlashCommand, SlashEmbedKind, ToolbarTooltip, }; /// A document edit an overlay asks the view for. The view carries each out through the @@ -60,6 +61,8 @@ pub enum DocEdit { InlineEquationFromSelection, /// Create a linked document from the current text selection and replace it with an `@reference`. CreateLinkedDocFromSelection, + /// Create a simple `affine:table` block from the current selection. + CreateTableFromSelection, /// Execute a command from the desktop formatting toolbar's `More (...)` dropdown. FormatMore(FormatMoreAction), /// Commit a LaTeX equation string to a block or inline target. @@ -115,6 +118,8 @@ pub enum OverlayEvent { SlashSubmenuHover(usize), SlashSubmenuExecute(usize), SlashScroll(f32), + /// Scroll the formatting toolbar `Highlight` dropdown by a wheel delta (logical px). + HighlightMenuScroll(f32), /// Set or clear the editor's text selection. SetSelection(Option), Format(FormatAction), @@ -145,7 +150,11 @@ pub enum OverlayEvent { /// Open or toggle the searchable code-block language picker. OpenCodeLangPicker(String), /// Scroll the searchable code-block language picker list by `delta_y` logical pixels. - CodeLangPickerScroll(f32), + /// `pointer_y` is the resting pointer below the top of the list, when it is over the list. + CodeLangPickerScroll { + delta_y: f32, + pointer_y: Option, + }, /// Synchronize the focused row index of the code-block language picker on pointer hover. CodeLangPickerHover(usize), /// Set the horizontal scroll offset of a wide code, table, or database block. @@ -394,6 +403,36 @@ pub enum OverlayEvent { CloseContextMenu, /// Execute a command from the desktop right-click context menu. ContextMenuAction(ContextMenuAction), + /// Update or clear the active hover tooltip for a toolbar button. + SetToolbarTooltip(Option), + /// Toggle a dropdown submenu on a block or inline toolbar. + ToggleBlockSubmenu(BlockToolbarSubmenu), + /// Close the open block or inline toolbar submenu after a press outside it. + CloseBlockSubmenu, + /// Execute a command from `overlay.embed_toolbar`. + EmbedToolbarAction { + block_id: String, + action: EmbedToolbarAction, + }, +} + +impl OverlayEvent { + /// Whether this event ends the open toolbar submenu: a toolbar action, a press outside the + /// submenu, the link popup closing, or a new selection. + pub fn closes_block_submenu(&self) -> bool { + matches!( + self, + Self::CloseBlockSubmenu + | Self::EmbedToolbarAction { .. } + | Self::BookmarkToolbarAction { .. } + | Self::ImageToolbarAction { .. } + | Self::CalloutAction { .. } + | Self::LinkPopupAction(_) + | Self::CloseLinkPopup + | Self::SelectBlock(_) + | Self::SetSelection(_) + ) + } } /// What the view has to do after an [`OverlayEvent`] or a key. diff --git a/blocksuite/crates/editor/src/overlays/helpers.rs b/blocksuite/crates/editor/src/overlays/helpers.rs index 989e872cb5..63f40a9072 100644 --- a/blocksuite/crates/editor/src/overlays/helpers.rs +++ b/blocksuite/crates/editor/src/overlays/helpers.rs @@ -597,6 +597,7 @@ impl Overlays { .image_lightbox .as_ref() .is_some_and(|lb| lb.presence.in_flight(now_ms) || lb.presence.closing) + || self.image_hover.next_deadline_ms().is_some() } } @@ -616,6 +617,23 @@ impl Overlays { if self.handle_stretch.is_some_and(|m| m.is_finished(now_ms)) { self.handle_stretch = None; } + let _ = self.image_hover.tick(now_ms); + if self + .image_hover + .active_target() + .is_some_and(|bid| layout.block(bid).is_none()) + { + self.image_hover.reset(); + } + self.retain_block_submenu(scene); + if self + .table_hover + .block_id + .as_deref() + .is_some_and(|bid| layout.block(bid).is_none()) + { + self.table_hover = super::TableHoverState::default(); + } if self .drop_indicator_motion .is_some_and(|m| m.progress.is_finished(now_ms)) @@ -731,52 +749,4 @@ impl Overlays { self.image_lightbox = None; } } - - pub fn new() -> Self { - Self::default() - } - - /// Reconcile popover state (formatting toolbar, slash/linked-doc fade-out) when editing - /// inside an Edgeless Note or EdgelessText where `page_layer` is not invoked. - pub fn reconcile_edgeless( - &mut self, - scene: &super::OverlayScene<'_>, - now_ms: f64, - window: &mut ui::Window, - ) { - self.reconcile(scene, now_ms); - if self.in_flight(now_ms) { - window.request_animation_frame(); - } - } - - /// Active `@` linked-document menu state, if open (not closing). - pub fn linked_doc_menu(&self) -> Option<&super::LinkedDocMenuState> { - self.linked_doc - .as_ref() - .filter(|menu| !menu.presence.closing) - } - - /// Mutable access to the open `@` linked-document menu state. - pub fn linked_doc_menu_mut(&mut self) -> Option<&mut super::LinkedDocMenuState> { - self.linked_doc - .as_mut() - .filter(|menu| !menu.presence.closing) - } - - /// Updates or clears the `@` linked-document menu state. - pub fn set_linked_doc_menu(&mut self, state: Option) { - self.linked_doc = state; - } - - /// Dismiss the `@` linked-document menu with a fade-out transition. - pub fn close_linked_doc(&mut self, now_ms: f64) -> bool { - match self.linked_doc_menu_mut() { - Some(menu) => { - menu.presence.close(now_ms); - true - } - None => false, - } - } } diff --git a/blocksuite/crates/editor/src/overlays/image_toolbar.rs b/blocksuite/crates/editor/src/overlays/image_toolbar.rs index 686a8bcdcb..7f28215955 100644 --- a/blocksuite/crates/editor/src/overlays/image_toolbar.rs +++ b/blocksuite/crates/editor/src/overlays/image_toolbar.rs @@ -3,16 +3,19 @@ use blocksuite_playground_doc::read::{BlockContent, TextAlign as BlockAlign}; use ui::{ - AnyElement, ClickEvent, Context, MouseButton, MouseDownEvent, ScrollEvent, SharedString, div, - prelude::*, px, + AnyElement, ClickEvent, Context, MouseButton, MouseDownEvent, MouseMoveEvent, ScrollEvent, + SharedString, div, prelude::*, px, }; use crate::theme::Palette; use super::{ - OverlayEvent, OverlayHost, OverlayScene, Overlays, POPOVER_BORDER, POPOVER_EDGE_MARGIN, - POPOVER_GAP, Placement, TOOLBAR_BUTTON, TOOLBAR_GAP, TOOLBAR_PADDING, TOOLBAR_RADIUS, - TOOLBAR_SEPARATOR_MARGIN, align_glyph, emit, icon, place, place_popover, + BlockToolbarSubmenu, ChromeIcon, MenuActionVariant, OverlayEvent, OverlayHost, OverlayScene, + Overlays, POPOVER_BORDER, POPOVER_EDGE_MARGIN, Placement, TOOLBAR_CHROME_BORDER, + TOOLBAR_CHROME_BTN, TOOLBAR_CHROME_BTN_RADIUS, TOOLBAR_MENU_ICON, TOOLBAR_MENU_MIN_W, + TOOLBAR_MENU_PADDING, TOOLBAR_MENU_ROW_H, TOOLBAR_PADDING, TOOLBAR_RADIUS, ToolbarTooltip, + align_glyph, chrome_icon, chrome_panel_bg, dismiss_submenu_outside, emit, icon, + menu_horizontal_separator, place, place_popover, toolbar_dropdown_panel, toolbar_menu_row, }; /// Horizontal side of an `affine:image` corner resize handle (`nw`/`sw` = `Left`, `ne`/`se` = `Right`). @@ -22,9 +25,10 @@ pub enum ImageResizeSide { Right, } -/// Actions offered by the floating `overlay.image_toolbar` above a selected `affine:image` block. +/// Actions offered by `overlay.image_toolbar` on a selected or hovered `affine:image` block. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ImageToolbarAction { + Download, Caption, Align(BlockAlign), Copy, @@ -119,43 +123,53 @@ impl Overlays { scene: &OverlayScene<'_>, palette: &Palette, cx: &mut Context, - ) -> Option { + ) -> Vec { self.image_toolbar_rect = None; + self.image_submenu_rect = None; if scene.page_readonly || self.image_lightbox().is_some() { - return None; + return Vec::new(); } - let block_id = scene.selected_image_block?; + let touch = scene.is_touch || scene.form_factor != crate::block_flow::FormFactor::Desktop; + let Some(block_id_owned) = scene.selected_image_block.map(str::to_string).or_else(|| { + (!touch) + .then(|| self.image_hover.active_target().cloned()) + .flatten() + }) else { + return Vec::new(); + }; + let block_id = block_id_owned.as_str(); if self .bookmark_prompt() .is_some_and(|p| p.block_id == block_id) { - return None; + return Vec::new(); } - let flow_block = scene.layout.block(block_id)?; - let img_local = flow_block.body.image_box()?; + let Some(flow_block) = scene.layout.block(block_id) else { + return Vec::new(); + }; + let Some(img_local) = flow_block.body.image_box() else { + return Vec::new(); + }; let img_world = img_local.translated(flow_block.x, flow_block.y); if !scene.anchor_visible(&img_world) { - return None; + return Vec::new(); } - let (_has_caption, current_align, has_blob) = - scene - .snapshot - .block(block_id) - .and_then(|n| match &n.content { - BlockContent::Image { - caption, - text_align, - source_id, - .. - } => Some(( - !caption.is_empty(), - text_align.unwrap_or(BlockAlign::Center), - !source_id.is_empty() && flow_block.body.is_resizable_image(), - )), - _ => None, - })?; + let Some((current_align, has_blob)) = scene.snapshot.block(block_id).and_then(|n| match &n + .content + { + BlockContent::Image { + text_align, + source_id, + .. + } => Some(( + text_align.unwrap_or(BlockAlign::Center), + !source_id.is_empty() && flow_block.body.is_resizable_image(), + )), + _ => None, + }) else { + return Vec::new(); + }; - let touch = scene.is_touch || scene.form_factor != crate::block_flow::FormFactor::Desktop; let vp = scene.popover_viewport(); let max_w = (vp.w - 2.0 * POPOVER_EDGE_MARGIN).max(200.0); let chrome = 2.0 * (TOOLBAR_PADDING + POPOVER_BORDER); @@ -326,150 +340,255 @@ impl Overlays { .child(div().w(px(1.0)).h(px(16.0)).bg(palette.divider)), ) .child(del_btn); - return Some(root.into_any_element()); + return vec![root.into_any_element()]; } - // Desktop floating toolbar: exact content width = buttons + all flex gaps + separators. - let btn_count = if has_blob { 8usize } else { 7usize }; - let sep_count = 2usize; - let total_children = btn_count + sep_count; - let gaps_w = total_children.saturating_sub(1) as f32 * TOOLBAR_GAP; - let seps_w = sep_count as f32 * (2.0 * TOOLBAR_SEPARATOR_MARGIN + 1.0); - let inner_w = btn_count as f32 * TOOLBAR_BUTTON + gaps_w + seps_w; - let width = inner_w + chrome; - let height = TOOLBAR_BUTTON + chrome; - let anchor_screen = scene.world_to_screen(&img_world); - let block_screen = scene.world_to_screen(&flow_block.rect()); - let mut placed = place_popover( - anchor_screen, - (width, height), - vp, - Placement::Above, - POPOVER_GAP, - POPOVER_EDGE_MARGIN, + // Desktop `placement: 'inner'`: transparent container inside top-right of the image with + // white `24 × 24` `buttonShadow` card chips (`16px` icons, `gap = 4px`, `radius = 4px`). + let more_open = matches!( + &self.block_submenu, + Some(BlockToolbarSubmenu::ImageMore(id)) if id == block_id ); - let vp_min_x = vp.x + POPOVER_EDGE_MARGIN; - let vp_max_x = (vp.right() - POPOVER_EDGE_MARGIN - width).max(vp_min_x); - let col_min_x = block_screen.x.clamp(vp_min_x, vp_max_x); - let col_max_x = (block_screen.right() - width).clamp(col_min_x, vp_max_x); - placed.rect.x = placed.rect.x.clamp(col_min_x, col_max_x); - self.image_toolbar_rect = Some(placed.rect); + let chip = TOOLBAR_CHROME_BTN; + let chip_gap = 4.0_f32; + let can_download = has_blob && scene.can_download_blobs; + let chip_count = if can_download { 6usize } else { 5usize }; + let width = chip_count as f32 * chip + (chip_count - 1) as f32 * chip_gap; + let height = chip; + let img_screen = scene.world_to_screen(&img_world); + let inset = 8.0_f32; + let x = (img_screen.right() - width - inset) + .max(img_screen.x + inset) + .clamp( + vp.x + POPOVER_EDGE_MARGIN, + (vp.right() - POPOVER_EDGE_MARGIN - width).max(vp.x + POPOVER_EDGE_MARGIN), + ) + .round(); + let y = (img_screen.y + inset) + .clamp( + vp.y + POPOVER_EDGE_MARGIN, + (vp.bottom() - POPOVER_EDGE_MARGIN - height).max(vp.y + POPOVER_EDGE_MARGIN), + ) + .round(); + let bar_rect = crate::block_flow::FlowRect::new(x, y, width, height); + self.image_toolbar_rect = Some(bar_rect); - let sep = || { - div() - .flex_none() - .mx(px(TOOLBAR_SEPARATOR_MARGIN)) - .w(px(1.0)) - .h(px(16.0)) - .bg(palette.divider) - }; - let make_btn = |id_suffix: &'static str, - active: bool, - action: ImageToolbarAction, - glyph: AnyElement, - cx: &mut Context| { - let ev = OverlayEvent::ImageToolbarAction { - block_id: block_id.to_string(), - action, + let chip_bg = chrome_panel_bg(palette); + let chip_shadow = palette.theme.shadows("--affine-button-shadow"); + let make_chip = |id_suffix: &'static str, + tooltip: &'static str, + slot_idx: usize, + active: bool, + event: OverlayEvent, + glyph: AnyElement, + cx: &mut Context| { + let cx_pos = x + slot_idx as f32 * (chip + chip_gap); + let tip = ToolbarTooltip { + label: tooltip.to_string(), + anchor_screen: crate::block_flow::FlowRect::new(cx_pos, y, chip, chip), }; div() .id(SharedString::from(format!("img-tb-{id_suffix}"))) .flex_none() - .w(px(TOOLBAR_BUTTON)) - .h(px(TOOLBAR_BUTTON)) - .rounded(px(4.0)) + .w(px(chip)) + .h(px(chip)) + .rounded(px(TOOLBAR_CHROME_BTN_RADIUS)) + .bg(chip_bg) + .shadow(chip_shadow.clone().into()) .flex() .items_center() .justify_center() .cursor_pointer() - .bg(if active { - palette.brand.opacity(0.14) - } else { - ui::transparent_black() - }) .hover(move |s| s.bg(hover_bg)) + .on_mouse_move(emit(cx, move |_: &MouseMoveEvent| { + OverlayEvent::SetToolbarTooltip(Some(tip.clone())) + })) .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_click(emit(cx, move |_: &ClickEvent| ev.clone())) + .on_click(emit(cx, move |_: &ClickEvent| event.clone())) .snapshot( SharedString::from(format!("overlay.image_toolbar.{id_suffix}")), Some("overlay.image_toolbar"), ) .snapshot_focused(active) + .snapshot_text(tooltip) .child(glyph) .into_any_element() }; - let mut row = div().flex().items_center().gap(px(TOOLBAR_GAP)); - row = row.child(make_btn( + let mut row = place(bar_rect) + .id("image-toolbar") + .block_mouse_except_scroll() + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .flex() + .items_center() + .gap(px(chip_gap)) + .snapshot("overlay.image_toolbar", Some("root.canvas")); + let mut slot = 0usize; + if can_download { + row = row.child(make_chip( + "download", + "Download", + slot, + false, + OverlayEvent::ImageToolbarAction { + block_id: block_id_owned.clone(), + action: ImageToolbarAction::Download, + }, + chrome_icon(ChromeIcon::Download, 16.0, palette.icon), + cx, + )); + slot += 1; + } + row = row.child(make_chip( "caption", + "Caption", + slot, false, - ImageToolbarAction::Caption, - icon("CaptionIcon", 16.0, palette.icon).into_any_element(), + OverlayEvent::ImageToolbarAction { + block_id: block_id_owned.clone(), + action: ImageToolbarAction::Caption, + }, + chrome_icon(ChromeIcon::Caption, 16.0, palette.icon), cx, )); - row = row.child(sep()); - for (id_suffix, align) in [ - ("align_left", BlockAlign::Left), - ("align_center", BlockAlign::Center), - ("align_right", BlockAlign::Right), + slot += 1; + for (id_suffix, label, align) in [ + ("align_left", "Align Left", BlockAlign::Left), + ("align_center", "Align Center", BlockAlign::Center), + ("align_right", "Align Right", BlockAlign::Right), ] { let active = current_align == align; - row = row.child(make_btn( + row = row.child(make_chip( id_suffix, + label, + slot, active, - ImageToolbarAction::Align(align), + OverlayEvent::ImageToolbarAction { + block_id: block_id_owned.clone(), + action: ImageToolbarAction::Align(align), + }, align_glyph(align, if active { palette.brand } else { palette.icon }) .into_any_element(), cx, )); + slot += 1; } - row = row.child(sep()); - row = row.child(make_btn( - "copy", - false, - ImageToolbarAction::Copy, - icon("CopyIcon", 16.0, palette.icon).into_any_element(), - cx, - )); - row = row.child(make_btn( - "duplicate", - false, - ImageToolbarAction::Duplicate, - icon("DuplicateIcon", 16.0, palette.icon).into_any_element(), - cx, - )); - if has_blob { - row = row.child(make_btn( - "card_view", - false, - ImageToolbarAction::TurnIntoCardView, - icon("PageIcon", 16.0, palette.icon).into_any_element(), - cx, - )); - } - row = row.child(make_btn( - "delete", - false, - ImageToolbarAction::Delete, - icon("DeleteIcon", 16.0, danger).into_any_element(), + row = row.child(make_chip( + "more", + "More", + slot, + more_open, + OverlayEvent::ToggleBlockSubmenu(BlockToolbarSubmenu::ImageMore( + block_id_owned.clone(), + )), + chrome_icon( + ChromeIcon::MoreVertical, + 16.0, + if more_open { + palette.brand + } else { + palette.icon + }, + ), cx, )); - let root = place(placed.rect) - .id("image-toolbar") - .block_mouse_except_scroll() - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_mouse_down_out(|_: &MouseDownEvent, _, _| {}) - .p(px(TOOLBAR_PADDING)) - .rounded(px(TOOLBAR_RADIUS)) - .bg(palette.panel) - .border_1() - .border_color(palette.border) - .shadow(palette.theme.shadows("--affine-toolbar-shadow").into()) - .flex() - .items_center() - .snapshot("overlay.image_toolbar", Some("root.canvas")) - .child(row); - Some(root.into_any_element()) + let mut out = vec![row.into_any_element()]; + if more_open { + let row_count = if has_blob { 4 } else { 3 }; + let sep_count = if has_blob { 2 } else { 1 }; + let menu_h = (2.0 * (TOOLBAR_MENU_PADDING + TOOLBAR_CHROME_BORDER) + + row_count as f32 * TOOLBAR_MENU_ROW_H + + sep_count as f32 * 9.0) + .round(); + let anchor = crate::block_flow::FlowRect::new( + (bar_rect.right() - TOOLBAR_MENU_MIN_W).max(vp.x + POPOVER_EDGE_MARGIN), + bar_rect.y, + TOOLBAR_MENU_MIN_W, + bar_rect.h, + ); + let placed = place_popover( + anchor, + (TOOLBAR_MENU_MIN_W, menu_h), + vp, + Placement::BelowStart, + 4.0, + POPOVER_EDGE_MARGIN, + ); + self.image_submenu_rect = Some(placed.rect); + let mut panel = toolbar_dropdown_panel( + "image-more-menu", + placed.rect, + 1.0, + true, + "overlay.image_toolbar.more_menu", + "overlay.image_toolbar", + palette, + ); + for (suffix, label, icon_name, action) in [ + ("copy", "Copy", "CopyIcon", ImageToolbarAction::Copy), + ( + "duplicate", + "Duplicate", + "DuplicateIcon", + ImageToolbarAction::Duplicate, + ), + ] { + panel = panel.child(toolbar_menu_row( + format!("img-more-{suffix}"), + format!("overlay.image_toolbar.{suffix}"), + "overlay.image_toolbar.more_menu", + label, + icon(icon_name, TOOLBAR_MENU_ICON, palette.icon).into_any_element(), + false, + MenuActionVariant::Normal, + true, + OverlayEvent::ImageToolbarAction { + block_id: block_id_owned.clone(), + action, + }, + palette, + cx, + )); + } + if has_blob { + panel = panel.child(menu_horizontal_separator(palette)); + panel = panel.child(toolbar_menu_row( + "img-more-card-view", + "overlay.image_toolbar.card_view", + "overlay.image_toolbar.more_menu", + "Turn into card view", + chrome_icon(ChromeIcon::Bookmark, TOOLBAR_MENU_ICON, palette.icon), + false, + MenuActionVariant::Normal, + true, + OverlayEvent::ImageToolbarAction { + block_id: block_id_owned.clone(), + action: ImageToolbarAction::TurnIntoCardView, + }, + palette, + cx, + )); + } + panel = panel.child(menu_horizontal_separator(palette)); + panel = panel.child(toolbar_menu_row( + "img-more-delete", + "overlay.image_toolbar.delete", + "overlay.image_toolbar.more_menu", + "Delete", + icon("DeleteIcon", TOOLBAR_MENU_ICON, palette.icon).into_any_element(), + false, + MenuActionVariant::Destructive, + true, + OverlayEvent::ImageToolbarAction { + block_id: block_id_owned, + action: ImageToolbarAction::Delete, + }, + palette, + cx, + )); + out.push(dismiss_submenu_outside(panel, bar_rect, cx).into_any_element()); + } + out } } diff --git a/blocksuite/crates/editor/src/overlays/link_popup.rs b/blocksuite/crates/editor/src/overlays/link_popup.rs index f52e3cb0f0..b60543b7f1 100644 --- a/blocksuite/crates/editor/src/overlays/link_popup.rs +++ b/blocksuite/crates/editor/src/overlays/link_popup.rs @@ -1,9 +1,11 @@ -//! Non-focus-stealing lightweight capsule for inline hyperlinks (`affine-link-popover`) -//! and `@reference` chips (`reference-popup`) on desktop and mobile. +//! Non-focus-stealing lightweight toolbar for inline hyperlinks (`affine-link-popover`) +//! and `@reference` chips (`reference-popup`) built on the shared `ToolbarChrome`. +//! +//! Positioned above the inline (`Placement::Above`, offset `10px`) with 500 ms enter / 250 ms +//! leave hover delay and safe bridge. use ui::{ - AnyElement, ClickEvent, Context, FontWeight, MouseButton, MouseDownEvent, SharedString, div, - prelude::*, px, + AnyElement, ClickEvent, Context, FontWeight, MouseButton, MouseDownEvent, div, prelude::*, px, }; use crate::{ @@ -11,14 +13,10 @@ use crate::{ theme::{Palette, TYPOGRAPHY}, }; -use super::{ - OverlayEvent, OverlayHost, OverlayScene, Overlays, POPOVER_BORDER, POPOVER_EDGE_MARGIN, - POPOVER_GAP, Placement, Presence, TOOLBAR_PADDING, TOOLBAR_RADIUS, embed_view_kind_for_url, - emit, icon, place, place_popover, -}; +use super::*; /// Desktop hover delay before opening the inline link / `@reference` floating capsule (ms). -pub const LINK_HOVER_DELAY_MS: f64 = 500.0; +pub const LINK_HOVER_DELAY_MS: f64 = HOVER_ENTER_DELAY_MS; /// Compact domain + path preview for an inline URL (`https://www.affine.pro/docs/` -> `affine.pro/docs`). pub fn domain_preview(url: &str) -> String { @@ -52,9 +50,9 @@ pub enum LinkPopupTarget { utf16_offset: usize, page_id: String, title: String, - /// False when inside `affine:table` or `affine:database` (`reference/configs/toolbar.ts:220`). + /// False when inside `affine:table` or `affine:database`. can_convert: bool, - /// False when self-referencing, targeting a node (`params`), or inside `edgeless-text` / `embed-synced-doc`. + /// False when self-referencing, targeting a node, or inside `edgeless-text` / `embed-synced-doc`. can_embed: bool, }, } @@ -68,7 +66,7 @@ impl LinkPopupTarget { pub fn display_label(&self) -> String { match self { - Self::Link { url, .. } => domain_preview(url), + Self::Link { url, .. } => hostname_preview(url), Self::Reference { title, .. } => { if title.is_empty() { "Untitled".to_string() @@ -97,10 +95,11 @@ pub enum LinkPopupAction { pub struct LinkPopupState { pub target: LinkPopupTarget, pub anchor_world: FlowRect, - /// True when opened by desktop hover (dismisses when pointer leaves anchor + capsule). + /// True when opened by desktop hover (dismisses after 250 ms leave delay outside bridge). pub from_hover: bool, pub presence: Presence, pub rect: Option, + pub submenu_rect: Option, } impl Overlays { @@ -133,17 +132,30 @@ impl Overlays { Some(prev) => prev.presence.reopened(now_ms), None => Presence::opening(now_ms), }; + if matches!( + self.block_submenu, + Some(BlockToolbarSubmenu::LinkPopupView | BlockToolbarSubmenu::LinkPopupMore) + ) { + self.block_submenu = None; + } self.link_popup = Some(LinkPopupState { target, anchor_world, from_hover, presence, rect: None, + submenu_rect: None, }); } /// Dismiss the lightweight link / reference capsule. pub fn close_link_popup(&mut self, now_ms: f64) -> bool { + if matches!( + self.block_submenu, + Some(BlockToolbarSubmenu::LinkPopupView | BlockToolbarSubmenu::LinkPopupMore) + ) { + self.block_submenu = None; + } match self .link_popup .as_mut() @@ -157,83 +169,57 @@ impl Overlays { } } - fn actions_width_for_target(target: &LinkPopupTarget, readonly: bool, touch: bool) -> f32 { - if readonly { - // Open (54) + Copy (42) + gap - return 54.0 + 42.0 + 6.0; - } - match target { - LinkPopupTarget::Reference { - can_convert, - can_embed, - .. - } => { - let mut w = 54.0 + 42.0 + 42.0 + 54.0 + 14.0; - if !touch && *can_convert { - w += 42.0 + 4.0; - if *can_embed { - w += 48.0 + 4.0; - } - } - w - } - LinkPopupTarget::Link { url, .. } => { - let mut w = 54.0 + 38.0 + 42.0 + 48.0 + 14.0; - if !touch { - w += 42.0 + 4.0; - if embed_view_kind_for_url(url).is_some() { - w += 48.0 + 4.0; - } - } - w - } - } - } - fn compute_link_popup_rect(popup: &LinkPopupState, scene: &OverlayScene<'_>) -> FlowRect { let anchor = scene.world_to_screen(&popup.anchor_world); let viewport = scene.popover_viewport(); let touch = scene.form_factor != crate::block_flow::FormFactor::Desktop; - let btn_h = if touch { 32.0 } else { 26.0 }; - let pad = TOOLBAR_PADDING; let label_text = popup.target.display_label(); - let est_label_w = (label_text.chars().count() as f32 * 7.6 + 20.0).clamp(64.0, 160.0); - let actions_w = Self::actions_width_for_target(&popup.target, scene.page_readonly, touch); - let raw_w = 2.0 * (pad + POPOVER_BORDER) + est_label_w + 13.0 + actions_w; + let label_w = (label_text.chars().count() as f32 * 6.8 + 16.0).clamp(60.0, 140.0); + let btn = TOOLBAR_CHROME_BTN; + let group_gap = TOOLBAR_CHROME_GAP; + let sep_w = TOOLBAR_SEP_SLOT; + + let mut group_widths = vec![label_w]; + if scene.page_readonly { + group_widths.push(btn); // Copy + } else { + let icon_group = match &popup.target { + LinkPopupTarget::Link { .. } => btn * 2.0 + 4.0, // Copy + Edit + LinkPopupTarget::Reference { .. } => btn * 2.0 + 4.0, // Copy + Alias + }; + group_widths.push(icon_group); + let show_view = !touch + && match &popup.target { + LinkPopupTarget::Link { .. } => true, + LinkPopupTarget::Reference { can_convert, .. } => *can_convert, + }; + if show_view { + group_widths.push(92.0); // Inline view ▾ + } + group_widths.push(btn); // ⋮ More + } + let seps = group_widths.len().saturating_sub(1); + let items_total: f32 = group_widths.iter().sum(); + let slots = group_widths.len() + seps; + let inner_w = + items_total + seps as f32 * sep_w + slots.saturating_sub(1) as f32 * group_gap; + let chrome_x = 2.0 * (TOOLBAR_CHROME_PX + TOOLBAR_CHROME_BORDER); let max_w = (viewport.w - 2.0 * POPOVER_EDGE_MARGIN).max(180.0); - let width = raw_w.min(max_w).round(); - let height = (btn_h + 2.0 * (pad + POPOVER_BORDER)).round(); + let width = (inner_w + chrome_x).min(max_w).round(); + let height = (TOOLBAR_CHROME_HEIGHT + 2.0 * TOOLBAR_CHROME_BORDER).round(); place_popover( anchor, (width, height), viewport, - Placement::BelowStart, - POPOVER_GAP, + Placement::Above, + TOOLBAR_CHROME_OFFSET, POPOVER_EDGE_MARGIN, ) .rect } - fn rect_or_bridge_contains(rect: FlowRect, anchor: FlowRect, x: f32, y: f32) -> bool { - let pad = 10.0; - let expanded = FlowRect::new( - rect.x - pad, - rect.y - pad, - rect.w + 2.0 * pad, - rect.h + 2.0 * pad, - ); - if expanded.contains(x, y) { - return true; - } - let bridge_top = anchor.y.min(rect.y) - 4.0; - let bridge_bottom = anchor.bottom().max(rect.bottom()) + 4.0; - let bridge_left = anchor.x.min(rect.x) - 4.0; - let bridge_right = anchor.right().max(rect.right()) + 4.0; - x >= bridge_left && x <= bridge_right && y >= bridge_top && y <= bridge_bottom - } - - /// True if `(x, y)` is inside the open link popup rect or the small hover bridge - /// connecting it to its anchor rect. + /// True if `(x, y)` is inside the open link popup rect, its open submenu, or the safe + /// hover bridge connecting it to its anchor rect. pub fn retain_or_reopen_link_popup_on_hover( &mut self, scene: &OverlayScene<'_>, @@ -251,7 +237,8 @@ impl Overlays { .rect .unwrap_or_else(|| Self::compute_link_popup_rect(popup, scene)); let anchor = scene.world_to_screen(&popup.anchor_world); - if !Self::rect_or_bridge_contains(rect, anchor, x, y) { + let in_sub = popup.submenu_rect.is_some_and(|r| r.contains(x, y)); + if !in_sub && !safe_bridge_contains(rect, anchor, x, y) { return false; } if popup.presence.closing { @@ -260,8 +247,7 @@ impl Overlays { true } - /// True if `(x, y)` is inside the open link popup rect or the small hover bridge - /// connecting it to its anchor rect. + /// True if `(x, y)` is inside the open link popup rect or its safe hover bridge. pub fn link_popup_contains_hover(&self, scene: &OverlayScene<'_>, x: f32, y: f32) -> bool { let Some(popup) = self.link_popup() else { return false; @@ -270,7 +256,8 @@ impl Overlays { .rect .unwrap_or_else(|| Self::compute_link_popup_rect(popup, scene)); let anchor = scene.world_to_screen(&popup.anchor_world); - Self::rect_or_bridge_contains(rect, anchor, x, y) + popup.submenu_rect.is_some_and(|r| r.contains(x, y)) + || safe_bridge_contains(rect, anchor, x, y) } pub(super) fn render_link_popup( @@ -279,19 +266,24 @@ impl Overlays { palette: &Palette, now_ms: f64, cx: &mut Context, - ) -> Option { + ) -> Vec { if self.open_toolbar().is_some() || self.slash_menu().is_some() || self.linked_doc_menu().is_some() || self.active_text_field().is_some() { - return None; + return Vec::new(); } - let popup = self.link_popup.as_mut()?; + let view_open = self.block_submenu == Some(BlockToolbarSubmenu::LinkPopupView); + let more_open = self.block_submenu == Some(BlockToolbarSubmenu::LinkPopupMore); + let Some(popup) = self.link_popup.as_mut() else { + return Vec::new(); + }; popup.rect = None; + popup.submenu_rect = None; let progress = popup.presence.progress(now_ms); if popup.presence.closing && progress <= 0.0 { - return None; + return Vec::new(); } let interactive = !popup.presence.closing; let progress = if interactive { @@ -303,229 +295,326 @@ impl Overlays { if popup.from_hover { self.link_popup = None; } - return None; + return Vec::new(); } + let touch = scene.form_factor != crate::block_flow::FormFactor::Desktop; - let btn_h = if touch { 32.0 } else { 26.0 }; - let pad = TOOLBAR_PADDING; + let vp = scene.popover_viewport(); let is_ref = matches!(popup.target, LinkPopupTarget::Reference { .. }); let label_text = popup.target.display_label(); - let actions_w = Self::actions_width_for_target(&popup.target, scene.page_readonly, touch); + let label_w = (label_text.chars().count() as f32 * 6.8 + 16.0).clamp(60.0, 140.0); let placed_rect = Self::compute_link_popup_rect(popup, scene); - let label_w = (placed_rect.w - 2.0 * (pad + POPOVER_BORDER) - 13.0 - actions_w).max(36.0); popup.rect = Some(placed_rect); let target_clone = popup.target.clone(); + let btn = TOOLBAR_CHROME_BTN; + let group_gap = TOOLBAR_CHROME_GAP; + let sep_w = TOOLBAR_SEP_SLOT; let hover_bg = palette.hover; - let make_btn = |id: &'static str, - snap_suffix: &'static str, - label: &'static str, - btn_w: f32, - action: LinkPopupAction, - cx: &mut Context| { - let mut el = div() - .id(id) - .flex_none() - .w(px(btn_w)) - .h(px(btn_h)) - .rounded(px(4.0)) - .flex() - .items_center() - .justify_center() - .text_size(px(TYPOGRAPHY.font_xs_px)) - .font_weight(FontWeight::MEDIUM) - .text_color(if action == LinkPopupAction::Open { + let mut cursor_x = placed_rect.x + TOOLBAR_CHROME_BORDER + TOOLBAR_CHROME_PX; + let btn_y = placed_rect.y + (TOOLBAR_CHROME_HEIGHT - btn) * 0.5; + + let mut preview = div() + .id("link-popup-open") + .flex_none() + .w(px(label_w)) + .h(px(btn)) + .px(px(6.0)) + .rounded(px(TOOLBAR_CHROME_BTN_RADIUS)) + .overflow_hidden() + .flex() + .items_center() + .text_size(px(TYPOGRAPHY.font_sm_px)) + .text_color(if is_ref { + palette.text_primary + } else { + chrome_link_color(palette) + }) + .snapshot("overlay.link_popup.open", Some("overlay.link_popup")) + .snapshot_text(label_text.clone()) + .child(label_text); + if interactive { + preview = preview + .cursor_pointer() + .hover(move |s| s.bg(hover_bg)) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(emit(cx, |_: &ClickEvent| { + OverlayEvent::LinkPopupAction(LinkPopupAction::Open) + })); + } + cursor_x += label_w + group_gap + sep_w + group_gap; + + let mut groups: Vec> = vec![vec![preview.into_any_element()]]; + + if scene.page_readonly { + groups.push(vec![toolbar_icon_button( + "link-popup-copy", + "overlay.link_popup.copy", + "overlay.link_popup", + "Copy link", + FlowRect::new(cursor_x, btn_y, btn, btn), + false, + interactive, + icon("CopyIcon", TOOLBAR_CHROME_ICON, palette.icon).into_any_element(), + OverlayEvent::LinkPopupAction(LinkPopupAction::Copy), + palette, + cx, + )]); + } else { + let mut g_actions = vec![toolbar_icon_button( + "link-popup-copy", + "overlay.link_popup.copy", + "overlay.link_popup", + "Copy link", + FlowRect::new(cursor_x, btn_y, btn, btn), + false, + interactive, + icon("CopyIcon", TOOLBAR_CHROME_ICON, palette.icon).into_any_element(), + OverlayEvent::LinkPopupAction(LinkPopupAction::Copy), + palette, + cx, + )]; + cursor_x += btn + 4.0; + if is_ref { + g_actions.push(toolbar_icon_button( + "link-popup-alias", + "overlay.link_popup.alias", + "overlay.link_popup", + "Edit Alias", + FlowRect::new(cursor_x, btn_y, btn, btn), + false, + interactive, + chrome_icon(ChromeIcon::Edit, TOOLBAR_CHROME_ICON, palette.icon), + OverlayEvent::LinkPopupAction(LinkPopupAction::EditAlias), + palette, + cx, + )); + } else { + g_actions.push(toolbar_icon_button( + "link-popup-edit", + "overlay.link_popup.edit", + "overlay.link_popup", + "Edit Description", + FlowRect::new(cursor_x, btn_y, btn, btn), + false, + interactive, + chrome_icon(ChromeIcon::Edit, TOOLBAR_CHROME_ICON, palette.icon), + OverlayEvent::LinkPopupAction(LinkPopupAction::Edit), + palette, + cx, + )); + } + groups.push(g_actions); + cursor_x += btn + group_gap + sep_w + group_gap; + + let (show_view, can_embed) = match &target_clone { + LinkPopupTarget::Link { url, .. } => { + (!touch, embed_view_kind_for_url(url).is_some()) + } + LinkPopupTarget::Reference { + can_convert, + can_embed, + .. + } => (!touch && *can_convert, *can_embed), + }; + if show_view { + let view_ink = if view_open { palette.brand } else { palette.text_primary - }) - .snapshot( - SharedString::from(format!("overlay.link_popup.{snap_suffix}")), - Some("overlay.link_popup"), - ) - .snapshot_text(label) - .child(label); - if interactive { - el = el - .cursor_pointer() - .hover(move |s| s.bg(hover_bg)) - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_click(emit(cx, move |_: &ClickEvent| { - OverlayEvent::LinkPopupAction(action) - })); - } - el - }; - - let mut root = place(placed_rect) - .id("link-popup") - .flex() - .items_center() - .gap(px(2.0)) - .p(px(pad)) - .rounded(px(TOOLBAR_RADIUS)) - .bg(palette.panel) - .border_1() - .border_color(palette.border) - .shadow(palette.theme.shadows("--affine-toolbar-shadow").into()) - .opacity(progress) - .snapshot("overlay.link_popup", Some("root.canvas")) - .snapshot_focused(interactive); - - if interactive { - root = root - .occlude() - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_mouse_down_out(emit(cx, |_: &MouseDownEvent| OverlayEvent::CloseLinkPopup)); - } - - let leading_icon = if is_ref { "LinkedPageIcon" } else { "LinkIcon" }; - root = root - .child( - div() + }; + let mut view_btn = div() + .id("link-popup-view") + .flex_none() + .w(px(92.0)) + .h(px(btn)) + .px(px(6.0)) + .rounded(px(TOOLBAR_CHROME_BTN_RADIUS)) .flex() .items_center() + .justify_center() .gap(px(4.0)) - .px(px(6.0)) - .w(px(label_w)) - .h(px(btn_h)) - .overflow_hidden() - .snapshot("overlay.link_popup.label", Some("overlay.link_popup")) - .snapshot_text(label_text.clone()) - .child(icon(leading_icon, 14.0, palette.icon)) - .child( - div() - .flex_1() - .overflow_hidden() - .whitespace_nowrap() - .text_size(px(TYPOGRAPHY.font_xs_px)) - .text_color(palette.text_secondary) - .child(label_text), - ), + .text_size(px(TYPOGRAPHY.font_xs_px)) + .font_weight(FontWeight::MEDIUM) + .text_color(view_ink) + .snapshot("overlay.link_popup.view", Some("overlay.link_popup")) + .snapshot_focused(view_open) + .snapshot_text("Inline view") + .child("Inline view") + .child(chrome_icon(ChromeIcon::ChevronDown, 12.0, view_ink)); + if interactive { + view_btn = view_btn + .cursor_pointer() + .hover(move |s| s.bg(hover_bg)) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(emit(cx, |_: &ClickEvent| { + OverlayEvent::ToggleBlockSubmenu(BlockToolbarSubmenu::LinkPopupView) + })); + } + groups.push(vec![view_btn.into_any_element()]); + cursor_x += 92.0 + group_gap + sep_w + group_gap; + } + + let more_ink = if more_open { + palette.brand + } else { + palette.icon + }; + groups.push(vec![toolbar_icon_button( + "link-popup-more", + "overlay.link_popup.more", + "overlay.link_popup", + "More", + FlowRect::new(cursor_x, btn_y, btn, btn), + more_open, + interactive, + chrome_icon(ChromeIcon::MoreVertical, TOOLBAR_CHROME_ICON, more_ink), + OverlayEvent::ToggleBlockSubmenu(BlockToolbarSubmenu::LinkPopupMore), + palette, + cx, + )]); + + let _ = can_embed; + } + + let mut submenu_panel = None; + + if interactive && !scene.page_readonly && view_open { + let can_embed = match &target_clone { + LinkPopupTarget::Link { url, .. } => embed_view_kind_for_url(url).is_some(), + LinkPopupTarget::Reference { can_embed, .. } => *can_embed, + }; + let mut rows: Vec<(&str, &str, bool, Option)> = vec![ + ("inline", "Inline view", true, None), + ( + "card", + "Card view", + false, + Some(LinkPopupAction::ConvertToCard), + ), + ]; + if can_embed { + rows.push(( + "embed", + "Embed view", + false, + Some(LinkPopupAction::ConvertToEmbed), + )); + } + let menu_h = (2.0 * (TOOLBAR_MENU_PADDING + TOOLBAR_CHROME_BORDER) + + rows.len() as f32 * TOOLBAR_MENU_ROW_H) + .round(); + let menu_placed = place_popover( + placed_rect, + (TOOLBAR_MENU_MIN_W, menu_h), + vp, + Placement::BelowStart, + 4.0, + POPOVER_EDGE_MARGIN, + ); + popup.submenu_rect = Some(menu_placed.rect); + let mut panel = toolbar_dropdown_panel( + "link-popup-view-menu", + menu_placed.rect, + progress, + interactive, + "overlay.link_popup.view_menu", + "overlay.link_popup", + palette, + ); + for (suffix, label, selected, act) in rows { + let ev = match act { + Some(action) => OverlayEvent::LinkPopupAction(action), + None => OverlayEvent::ToggleBlockSubmenu(BlockToolbarSubmenu::LinkPopupView), + }; + panel = panel.child(toolbar_menu_row( + format!("link-popup-view-{suffix}"), + format!("overlay.link_popup.{suffix}"), + "overlay.link_popup.view_menu", + label, + chrome_icon(ChromeIcon::Bookmark, TOOLBAR_MENU_ICON, palette.icon), + selected, + MenuActionVariant::Normal, + interactive, + ev, + palette, + cx, + )); + } + submenu_panel = Some(panel.into_any_element()); + } else if interactive && !scene.page_readonly && more_open { + let menu_h = + (2.0 * (TOOLBAR_MENU_PADDING + TOOLBAR_CHROME_BORDER) + TOOLBAR_MENU_ROW_H).round(); + let anchor = FlowRect::new( + (placed_rect.right() - TOOLBAR_MENU_MIN_W).max(placed_rect.x), + placed_rect.y, + TOOLBAR_MENU_MIN_W, + placed_rect.h, + ); + let menu_placed = place_popover( + anchor, + (TOOLBAR_MENU_MIN_W, menu_h), + vp, + Placement::BelowStart, + 4.0, + POPOVER_EDGE_MARGIN, + ); + popup.submenu_rect = Some(menu_placed.rect); + let unlink_label = if is_ref { "Delete" } else { "Remove link" }; + let panel = toolbar_dropdown_panel( + "link-popup-more-menu", + menu_placed.rect, + progress, + interactive, + "overlay.link_popup.more_menu", + "overlay.link_popup", + palette, ) - .child(div().flex_none().w(px(1.0)).h(px(16.0)).bg(palette.border)) - .child(make_btn( - "link-popup-open", - "open", - "Open \u{2197}", - 54.0, - LinkPopupAction::Open, + .child(toolbar_menu_row( + "link-popup-unlink", + "overlay.link_popup.unlink", + "overlay.link_popup.more_menu", + unlink_label, + if is_ref { + icon("DeleteIcon", TOOLBAR_MENU_ICON, palette.icon).into_any_element() + } else { + chrome_icon(ChromeIcon::Unlink, TOOLBAR_MENU_ICON, palette.icon) + }, + false, + MenuActionVariant::Destructive, + interactive, + OverlayEvent::LinkPopupAction(LinkPopupAction::Unlink), + palette, cx, )); - - if scene.page_readonly { - root = root.child(make_btn( - "link-popup-copy", - "copy", - "Copy", - 42.0, - LinkPopupAction::Copy, - cx, + submenu_panel = Some(panel.into_any_element()); + } + let submenu_rect = popup.submenu_rect; + let mut root = append_toolbar_groups( + toolbar_chrome_container( + "link-popup", + placed_rect, + progress, + interactive, + "overlay.link_popup", + palette, + ), + groups, + palette, + ); + if interactive { + root = root.on_mouse_down_out(cx.listener( + move |view, ev: &MouseDownEvent, window, cx| { + let (x, y) = (f32::from(ev.position.x), f32::from(ev.position.y)); + if submenu_rect.is_some_and(|r| r.contains(x, y)) { + return; + } + view.dispatch_overlay(OverlayEvent::CloseLinkPopup, window, cx); + }, )); - return Some(root.into_any_element()); } - - match target_clone { - LinkPopupTarget::Reference { - can_convert, - can_embed, - .. - } => { - root = root - .child(make_btn( - "link-popup-alias", - "alias", - "Alias", - 42.0, - LinkPopupAction::EditAlias, - cx, - )) - .child(make_btn( - "link-popup-copy", - "copy", - "Copy", - 42.0, - LinkPopupAction::Copy, - cx, - )); - if !touch && can_convert { - root = root.child(make_btn( - "link-popup-card", - "card", - "Card", - 42.0, - LinkPopupAction::ConvertToCard, - cx, - )); - if can_embed { - root = root.child(make_btn( - "link-popup-embed", - "embed", - "Embed", - 48.0, - LinkPopupAction::ConvertToEmbed, - cx, - )); - } - } - root = root.child(make_btn( - "link-popup-unlink", - "unlink", - "Remove", - 54.0, - LinkPopupAction::Unlink, - cx, - )); - } - LinkPopupTarget::Link { url, .. } => { - root = root - .child(make_btn( - "link-popup-edit", - "edit", - "Edit", - 38.0, - LinkPopupAction::Edit, - cx, - )) - .child(make_btn( - "link-popup-copy", - "copy", - "Copy", - 42.0, - LinkPopupAction::Copy, - cx, - )); - if !touch { - root = root.child(make_btn( - "link-popup-card", - "card", - "Card", - 42.0, - LinkPopupAction::ConvertToCard, - cx, - )); - if embed_view_kind_for_url(&url).is_some() { - root = root.child(make_btn( - "link-popup-embed", - "embed", - "Embed", - 48.0, - LinkPopupAction::ConvertToEmbed, - cx, - )); - } - } - root = root.child(make_btn( - "link-popup-unlink", - "unlink", - "Unlink", - 48.0, - LinkPopupAction::Unlink, - cx, - )); - } - } - - Some(root.into_any_element()) + let mut out = vec![root.into_any_element()]; + out.extend(submenu_panel); + out } } diff --git a/blocksuite/crates/editor/src/overlays/mod.rs b/blocksuite/crates/editor/src/overlays/mod.rs index 90534e650e..9145628384 100644 --- a/blocksuite/crates/editor/src/overlays/mod.rs +++ b/blocksuite/crates/editor/src/overlays/mod.rs @@ -9,12 +9,14 @@ mod block_menu; mod block_toggles; mod bookmark_prompt; mod bookmark_toolbar; +mod bookmark_touch_bar; mod callout_bar; mod caption_editor; mod code_lang_picker; mod code_toolbar; mod context_menu; mod drag; +mod embed_toolbar; mod embed_url; mod equation; mod events; @@ -39,6 +41,7 @@ mod slash_preview; mod state; mod table_cell; mod toolbar; +mod toolbar_chrome; mod transform; pub use attachment_toolbar::AttachmentToolbarAction; @@ -69,6 +72,7 @@ pub use drag::{ resolve_marquee_selection, resolve_tree_drop_target, }; use drag::{BlockDrag, DropIndicatorMotion, PageMarquee}; +pub use embed_toolbar::EmbedToolbarAction; pub use embed_url::{card_embed_kind_for_url, embed_view_kind_for_url}; pub use equation::{EquationEditor, EquationTarget}; use helpers::place_touch_docked_toolbar; @@ -120,12 +124,15 @@ pub use slash::{ slash_entries_with_caps, slash_item_by_id, slash_item_const, slash_rows, slash_rows_for_entries, slash_rows_for_query, slash_submenu_items, }; -pub use table_cell::{InlineTableCell, TableAxisMenu, TableCellDragMode, TableColResizeDrag}; -pub use toolbar::LinkBar; -pub use toolbar::{ - ActiveSelection, FormatAction, FormatMoreAction, LinkEditField, MarkState, SelectionFormat, - ToolbarSubmenu, marks_in_range, normalize_url, +pub use table_cell::{ + InlineTableCell, TableAddDrag, TableAddDragKind, TableAxisMenu, TableCellDragMode, + TableColResizeDrag, TableHoverState, }; +pub use toolbar::{ + ActiveSelection, FormatAction, FormatMoreAction, LinkBar, LinkEditField, MarkState, + SelectionFormat, ToolbarSubmenu, marks_in_range, normalize_url, +}; +pub use toolbar_chrome::*; pub use transform::OverlayScreenTransform; pub(crate) use paint_page::align_glyph; @@ -194,8 +201,7 @@ pub const TOOLBAR_RADIUS: f32 = 8.0; /// Padding between the toolbar's edge and its buttons. pub const TOOLBAR_PADDING: f32 = 4.0; pub(super) const TOOLBAR_GAP: f32 = 2.0; -pub(super) const TOOLBAR_ROW_GAP: f32 = 4.0; -/// Space on either side of the line between the mark buttons and the alignment buttons. +/// Space on either side of a separator line between toolbar button groups. pub(super) const TOOLBAR_SEPARATOR_MARGIN: f32 = 8.0; pub(super) const LINK_APPLY_WIDTH: f32 = 52.0; pub(super) const LINK_REMOVE_WIDTH: f32 = 64.0; @@ -244,10 +250,14 @@ pub struct OverlayScene<'a> { /// Code block currently holding the caret or included in whole-block selection. pub focused_code_block: Option<&'a str>, pub selected_image_block: Option<&'a str>, + /// Whether the host saves blob bytes as a file (the Web, or a registered download callback). + pub can_download_blobs: bool, /// Single `affine:attachment` block currently selected in whole-block selection, if any. pub selected_attachment_block: Option<&'a str>, /// Single `affine:bookmark` block currently selected in whole-block selection, if any. pub selected_bookmark_block: Option<&'a str>, + /// Single `EmbedLinkedDoc`/`EmbedSyncedDoc`/`ExternalEmbed` block selected, if any. + pub selected_embed_block: Option<&'a str>, /// Single `affine:callout` block currently selected in whole-block selection, if any. pub selected_callout_block: Option<&'a str>, /// Single `affine:latex` block currently selected in whole-block selection, if any. @@ -296,21 +306,19 @@ impl OverlayScene<'_> { } pub(super) fn world_to_screen(&self, rect: &FlowRect) -> FlowRect { - if let Some(t) = self.screen_transform { - t.rect_to_screen(rect) - } else { - rect.translated(self.geometry.column_x, TOPBAR_HEIGHT - self.scroll_y) + match self.screen_transform { + Some(t) => t.rect_to_screen(rect), + None => rect.translated(self.geometry.column_x, TOPBAR_HEIGHT - self.scroll_y), } } pub(super) fn screen_to_world(&self, x: f32, y: f32) -> (f32, f32) { - if let Some(t) = self.screen_transform { - t.screen_to_local(x, y) - } else { - ( + match self.screen_transform { + Some(t) => t.screen_to_local(x, y), + None => ( x - self.geometry.column_x, y - TOPBAR_HEIGHT + self.scroll_y, - ) + ), } } } @@ -339,6 +347,8 @@ pub struct Overlays { pub(super) last_scroll_y: Option, /// Chevrons in flight by block id: `0.0` collapsed to `1.0` expanded. pub(super) chevrons: HashMap, + /// Scroll offset of the `Highlight` dropdown when it is taller than the viewport allows. + pub(super) highlight_menu_scroll: f32, /// Active to-do checkbox 2-phase radial burst animations by block id (linear `0.0 -> 1.0`). pub(super) todo_pulses: HashMap, /// Sideways scroll of unwrapped code blocks by block id. @@ -358,10 +368,19 @@ pub struct Overlays { pub(super) image_lightbox: Option, pub(super) image_toolbar_rect: Option, pub(super) attachment_toolbar_rect: Option, + pub(super) image_submenu_rect: Option, pub(super) bookmark_toolbar_rect: Option, + pub(super) bookmark_submenu_rect: Option, + pub(super) embed_toolbar_rect: Option, + pub(super) embed_submenu_rect: Option, pub(super) callout_toolbar_rect: Option, + pub(super) callout_submenu_rect: Option, pub(super) callout_icon_picker_block: Option, pub(super) callout_icon_picker_rect: Option, + pub(super) block_submenu: Option, + pub(super) hovered_tooltip: Option, + pub image_hover: HoverController, + pub table_hover: TableHoverState, pub(super) touch_bar_scroll_x: f32, pub(super) touch_bar_block_id: Option, pub(super) keyboard_toolbar: KeyboardToolbarState, @@ -386,13 +405,19 @@ impl Overlays { self.slash_menu().and_then(|menu| menu.preview_rect), self.linked_doc_menu().and_then(|menu| menu.rect), self.link_popup().and_then(|popup| popup.rect), + self.link_popup().and_then(|popup| popup.submenu_rect), self.open_toolbar().and_then(|toolbar| toolbar.rect), self.open_toolbar().and_then(|toolbar| toolbar.submenu_rect), self.code_toolbar_rect, self.image_toolbar_rect, self.attachment_toolbar_rect, + self.image_submenu_rect, self.bookmark_toolbar_rect, + self.bookmark_submenu_rect, + self.embed_toolbar_rect, + self.embed_submenu_rect, self.callout_toolbar_rect, + self.callout_submenu_rect, self.callout_icon_picker_rect, self.code_lang_picker().and_then(|p| p.rect), self.code_more_menu().and_then(|m| m.rect), @@ -406,4 +431,51 @@ impl Overlays { .flatten() .any(|rect| rect.contains(x, y)) } + + pub fn new() -> Self { + Self::default() + } + + /// Reconcile popover state (formatting toolbar, slash/linked-doc fade-out) when editing + /// inside an Edgeless Note or EdgelessText where `page_layer` is not invoked. + pub fn reconcile_edgeless( + &mut self, + scene: &OverlayScene<'_>, + now_ms: f64, + window: &mut Window, + ) { + self.reconcile(scene, now_ms); + if self.in_flight(now_ms) { + window.request_animation_frame(); + } + } + /// Active `@` linked-document menu state, if open (not closing). + pub fn linked_doc_menu(&self) -> Option<&LinkedDocMenuState> { + self.linked_doc + .as_ref() + .filter(|menu| !menu.presence.closing) + } + + /// Mutable access to the open `@` linked-document menu state. + pub fn linked_doc_menu_mut(&mut self) -> Option<&mut LinkedDocMenuState> { + self.linked_doc + .as_mut() + .filter(|menu| !menu.presence.closing) + } + + /// Updates or clears the `@` linked-document menu state. + pub fn set_linked_doc_menu(&mut self, state: Option) { + self.linked_doc = state; + } + + /// Dismiss the `@` linked-document menu with a fade-out transition. + pub fn close_linked_doc(&mut self, now_ms: f64) -> bool { + match self.linked_doc_menu_mut() { + Some(menu) => { + menu.presence.close(now_ms); + true + } + None => false, + } + } } diff --git a/blocksuite/crates/editor/src/overlays/paint_page/handle.rs b/blocksuite/crates/editor/src/overlays/paint_page/handle.rs index 658ff149e5..89c5b9508d 100644 --- a/blocksuite/crates/editor/src/overlays/paint_page/handle.rs +++ b/blocksuite/crates/editor/src/overlays/paint_page/handle.rs @@ -647,10 +647,12 @@ mod tests { is_touch: false, focused_code_block: None, selected_image_block: None, + can_download_blobs: false, selected_attachment_block: None, selected_bookmark_block: None, selected_callout_block: None, selected_latex_block: None, + selected_embed_block: None, selection: None, screen_transform: None, suppress_floating_format_buttons: false, diff --git a/blocksuite/crates/editor/src/overlays/paint_page/media_controls.rs b/blocksuite/crates/editor/src/overlays/paint_page/media_controls.rs index e48bb35f64..fe25429ca3 100644 --- a/blocksuite/crates/editor/src/overlays/paint_page/media_controls.rs +++ b/blocksuite/crates/editor/src/overlays/paint_page/media_controls.rs @@ -2,7 +2,7 @@ //! caption click, corner resize handles), `affine:bookmark` (selection, double-click open), //! and `affine:callout` (icon picker trigger). -use blocksuite_playground_doc::read::{BlockContent, TextAlign as BlockAlign}; +use blocksuite_playground_doc::read::BlockContent; use ui::{AnyElement, ClickEvent, Context, MouseButton, SharedString, prelude::*, px}; use crate::{ @@ -32,7 +32,8 @@ impl Overlays { }; let img_world = img_local.translated(rect.x, rect.y); let selected = scene.selected_image_block == Some(block.block_id.as_str()); - let resizable = selected && !scene.page_readonly && block.body.is_resizable_image(); + let show_frame = selected && block.body.is_resizable_image(); + let resizable = show_frame && !scene.page_readonly; if viewport.intersects(&img_world) { let card_rect = FlowRect::new( @@ -47,7 +48,7 @@ impl Overlays { let mut card = place(viewport.to_local(&card_rect)) .id(SharedString::from(format!("image-card-{}", block.block_id))) .cursor_pointer() - .when(resizable, |el| el.border_2().border_color(palette.brand)) + .when(show_frame, |el| el.border_2().border_color(palette.brand)) .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_click(emit(cx, move |ev: &ClickEvent| { if ev.click_count() >= 2 && can_lightbox { @@ -68,14 +69,6 @@ impl Overlays { } if resizable { - let img_align = scene - .snapshot - .block(&block.block_id) - .and_then(|n| match &n.content { - BlockContent::Image { text_align, .. } => *text_align, - _ => None, - }) - .unwrap_or(BlockAlign::Center); for (suffix, corner_x, corner_y, side, cursor) in [ ( "resize_nw", @@ -106,11 +99,6 @@ impl Overlays { ui::CursorStyle::ResizeUpLeftDownRight, ), ] { - if (img_align == BlockAlign::Left && side == ImageResizeSide::Left) - || (img_align == BlockAlign::Right && side == ImageResizeSide::Right) - { - continue; - } let h_rect = FlowRect::new( (corner_x - CONTROL_HIT_SIZE * 0.5).round(), (corner_y - CONTROL_HIT_SIZE * 0.5).round(), @@ -187,6 +175,7 @@ impl Overlays { let select_ev = OverlayEvent::SelectBlock(block.block_id.clone()); let open_ev = OverlayEvent::OpenBookmarkUrl(url); let readonly = scene.page_readonly; + let ring = super::chrome_primary_border(palette); let mut card = place(viewport.to_local(&rect)) .id(SharedString::from(format!( "bookmark-card-{}", @@ -194,7 +183,7 @@ impl Overlays { ))) .rounded(px(8.0)) .cursor_pointer() - .when(selected, |el| el.border_2().border_color(palette.brand)) + .when(selected, |el| el.border_1().border_color(ring)) .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_click(emit(cx, move |ev: &ClickEvent| { if ev.click_count() >= 2 || readonly { @@ -221,7 +210,7 @@ impl Overlays { rect: FlowRect, scene: &OverlayScene<'_>, viewport: PageViewport, - palette: &Palette, + _palette: &Palette, cx: &mut Context, elements: &mut Vec, ) { @@ -239,7 +228,6 @@ impl Overlays { block_id: block.block_id.clone(), action: super::CalloutAction::ToggleIconPicker, }; - let hover_bg = palette.hover; let mut btn = place(viewport.to_local(&icon_rect)) .id(SharedString::from(format!( "callout-icon-{}", @@ -247,7 +235,7 @@ impl Overlays { ))) .rounded(px(4.0)) .cursor_pointer() - .hover(move |s| s.bg(hover_bg)) + .hover(|s| s.opacity(0.7)) .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_click(emit(cx, move |_: &ClickEvent| icon_ev.clone())); if viewport.fully_visible(&icon_rect) { diff --git a/blocksuite/crates/editor/src/overlays/paint_page/mod.rs b/blocksuite/crates/editor/src/overlays/paint_page/mod.rs index 99a243f5da..ba2afaa6bf 100644 --- a/blocksuite/crates/editor/src/overlays/paint_page/mod.rs +++ b/blocksuite/crates/editor/src/overlays/paint_page/mod.rs @@ -112,9 +112,12 @@ impl Overlays { CONTROL_HIT_SIZE, ); let event = OverlayEvent::ToggleCollapsed(block.block_id.clone()); + let hover_bg = palette.hover; let mut element = place(viewport.to_local(&target)) .id(SharedString::from(format!("collapse-{}", block.block_id))) + .rounded(px(4.0)) .cursor_pointer() + .hover(move |s| s.bg(hover_bg)) .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_click(emit(cx, move |_: &ClickEvent| event.clone())); if viewport.fully_visible(&target) { @@ -195,45 +198,39 @@ impl Overlays { ); } } - FlowKind::Code => self.push_code_toolbar( + FlowKind::Code => { + self.push_code_toolbar( + block, + rect, + scene, + viewport, + palette, + hover_filled, + now_ms, + cx, + &mut elements, + ); + self.push_block_hscrollbar( + block, + hovered, + scene, + viewport, + window.scale_factor(), + palette, + cx, + &mut elements, + ); + } + FlowKind::Database => self.push_block_hscrollbar( block, - rect, + hovered, scene, viewport, + window.scale_factor(), palette, - hover_filled, - now_ms, cx, &mut elements, ), - FlowKind::Database => { - let dragging = self - .hscroll_drag - .as_ref() - .is_some_and(|d| d.block_id == block.block_id); - if (hovered - || self.hscroll_hovered.as_deref() == Some(block.block_id.as_str()) - || dragging) - && !scene.is_touch - && scene.form_factor == crate::block_flow::FormFactor::Desktop - && let Some((bar_world, code)) = - scrollbar::block_hscrollbar_world_rect(block) - && viewport.intersects(&bar_world) - && let Some(el) = scrollbar::build_block_hscrollbar( - &block.block_id, - &block.snapshot_id, - viewport.to_local(&bar_world), - self.code_scroll_x_for(&block.block_id, code), - code.max_x, - dragging, - window.scale_factor(), - palette, - cx, - ) - { - elements.push(el); - } - } FlowKind::Image => self.push_image_controls( block, rect, @@ -302,32 +299,16 @@ impl Overlays { &mut elements, ), FlowKind::Table => { - let dragging = self - .hscroll_drag - .as_ref() - .is_some_and(|d| d.block_id == block.block_id); - if (hovered - || self.hscroll_hovered.as_deref() == Some(block.block_id.as_str()) - || dragging) - && !scene.is_touch - && scene.form_factor == crate::block_flow::FormFactor::Desktop - && let Some((bar_world, code)) = - scrollbar::block_hscrollbar_world_rect(block) - && viewport.intersects(&bar_world) - && let Some(el) = scrollbar::build_block_hscrollbar( - &block.block_id, - &block.snapshot_id, - viewport.to_local(&bar_world), - self.code_scroll_x_for(&block.block_id, code), - code.max_x, - dragging, - window.scale_factor(), - palette, - cx, - ) - { - elements.push(el); - } + self.push_block_hscrollbar( + block, + hovered, + scene, + viewport, + window.scale_factor(), + palette, + cx, + &mut elements, + ); let table_cells = scene.snapshot.block(&block.block_id).and_then(|n| match &n .content { @@ -537,22 +518,42 @@ impl Overlays { _ => None, }) { - let event = OverlayEvent::OpenEmbedDoc { page_id }; + let selected = scene.selected_embed_block == Some(block.block_id.as_str()); + let select_ev = OverlayEvent::SelectBlock(block.block_id.clone()); + let open_ev = OverlayEvent::OpenEmbedDoc { page_id }; + let page_readonly = scene.page_readonly; let hovered_synced = matches!(block.body.kind, FlowKind::EmbedSyncedDoc) && self.hovered.as_deref() == Some(block.block_id.as_str()); + let ring = super::chrome_primary_border(palette); let mut element = place(viewport.to_local(&rect)) .id(SharedString::from(format!("embed-doc-{}", block.block_id))) + .rounded(px(8.0)) .cursor_pointer() - .when(hovered_synced, |el| { - el.rounded(px(8.0)).border_1().border_color(palette.border) + .when(selected, |el| el.border_1().border_color(ring)) + .when(!selected && hovered_synced, |el| { + el.border_1().border_color(palette.border) }) .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_click(emit(cx, move |_: &ClickEvent| event.clone())); - if matches!(block.body.kind, FlowKind::EmbedSyncedDoc) { + .on_click(emit(cx, move |ev: &ClickEvent| { + if ev.click_count() >= 2 || page_readonly { + open_ev.clone() + } else { + select_ev.clone() + } + })); + if !selected && matches!(block.body.kind, FlowKind::EmbedSyncedDoc) { let border = palette.border; element = element .hover(move |s| s.rounded(px(8.0)).border_1().border_color(border)); } + if viewport.fully_visible(&rect) { + element = element + .snapshot( + SharedString::from(format!("{}.embed_card", block.snapshot_id)), + Some(PAGE_SURFACE_ID), + ) + .snapshot_focused(selected); + } elements.push(element.into_any_element()); } } @@ -661,12 +662,15 @@ impl Overlays { }, initial: latex.clone(), }; + let hover_bg = palette.hover; let element = place(viewport.to_local(&chip_rect)) .id(SharedString::from(format!( "inline-latex-{}-{}-{deco_idx}", block.block_id, deco.source_utf16.start ))) + .rounded(px(4.0)) .cursor_pointer() + .hover(move |s| s.bg(hover_bg)) .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_click(emit(cx, move |_: &ClickEvent| event.clone())); elements.push(element.into_any_element()); diff --git a/blocksuite/crates/editor/src/overlays/paint_popovers.rs b/blocksuite/crates/editor/src/overlays/paint_popovers.rs index f8537829f4..dedda8a071 100644 --- a/blocksuite/crates/editor/src/overlays/paint_popovers.rs +++ b/blocksuite/crates/editor/src/overlays/paint_popovers.rs @@ -7,9 +7,11 @@ use super::*; /// Side and alignment a popover prefers relative to its anchor. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Placement { - /// Above the anchor, centered on it. + /// Above the anchor, centered on it (`top`). Above, - /// Below the anchor, starting at its left edge. + /// Above the anchor, aligned to its left edge (`top-start`). + AboveStart, + /// Below the anchor, starting at its left edge (`bottom-start`). BelowStart, } @@ -48,7 +50,7 @@ pub fn place_popover( let fits_below = below_y + height <= bottom_limit; let preferred_side = match preferred { - Placement::Above => PopoverSide::Above, + Placement::Above | Placement::AboveStart => PopoverSide::Above, Placement::BelowStart => PopoverSide::Below, }; let side = match (preferred_side, fits_above, fits_below) { @@ -74,7 +76,7 @@ pub fn place_popover( let x = match preferred { Placement::Above => anchor.x + (anchor.w - width) / 2.0, - Placement::BelowStart => anchor.x, + Placement::AboveStart | Placement::BelowStart => anchor.x, }; let left_limit = viewport.x + edge_margin; let x = x @@ -107,6 +109,7 @@ impl Overlays { elements.extend(self.render_image_toolbar(scene, palette, cx)); elements.extend(self.render_attachment_toolbar(scene, palette, cx)); elements.extend(self.render_bookmark_toolbar(scene, palette, cx)); + elements.extend(self.render_embed_toolbar(scene, palette, cx)); elements.extend(self.render_callout_toolbar(scene, palette, cx)); elements.extend(self.render_code_lang_picker(scene, palette, now_ms, window, cx)); elements.extend(self.render_code_more_menu(scene, palette, now_ms, window, cx)); @@ -116,6 +119,13 @@ impl Overlays { elements.extend(self.render_equation(scene, palette, now_ms, window, cx)); elements.extend(self.render_bookmark(scene, palette, now_ms, window, cx)); elements.extend(self.render_keyboard_toolbar(scene, palette, cx)); + if let Some(tip) = self.hovered_tooltip.as_ref() { + elements.push(render_toolbar_tooltip( + tip, + scene.popover_viewport(), + palette, + )); + } elements } diff --git a/blocksuite/crates/editor/src/overlays/paint_toolbar/dropdowns.rs b/blocksuite/crates/editor/src/overlays/paint_toolbar/dropdowns.rs new file mode 100644 index 0000000000..0c43d0caad --- /dev/null +++ b/blocksuite/crates/editor/src/overlays/paint_toolbar/dropdowns.rs @@ -0,0 +1,338 @@ +//! Dropdown submenus for desktop `FormatToolbar` (`Turn into`, `Align`, `Highlight`, `More`) +//! built on the shared `ToolbarChrome` panel and row primitives. + +use blocksuite_playground_doc::read::TextAlign as BlockAlign; +use ui::{AnyElement, Context, FontWeight, ScrollEvent, SharedString, div, prelude::*, px}; + +use crate::{ + block_flow::FlowRect, + theme::{Palette, TYPOGRAPHY}, +}; + +use super::*; + +pub(super) fn render_turn_into_dropdown( + toolbar_rect: FlowRect, + viewport: FlowRect, + current_id: Option<&'static str>, + progress: f32, + interactive: bool, + palette: &Palette, + cx: &mut Context, +) -> Option<(FlowRect, AnyElement)> { + let items: Vec = FORMAT_TURN_INTO_IDS + .iter() + .map(|id| slash_item_const(id)) + .filter(|item| item.id != "divider") + .collect(); + let width = TOOLBAR_MENU_MIN_W.min((viewport.w - 2.0 * POPOVER_EDGE_MARGIN).max(140.0)); + let height = (2.0 * (TOOLBAR_MENU_PADDING + TOOLBAR_CHROME_BORDER) + + items.len() as f32 * TOOLBAR_MENU_ROW_H) + .min((viewport.h - 2.0 * POPOVER_EDGE_MARGIN).max(TOOLBAR_MENU_ROW_H + 16.0)) + .round(); + let placed = place_popover( + toolbar_rect, + (width, height), + viewport, + Placement::BelowStart, + 4.0, + POPOVER_EDGE_MARGIN, + ); + let mut panel = toolbar_dropdown_panel( + "format-turn-into-menu", + placed.rect, + progress, + interactive, + "overlay.format_toolbar.turn_into_menu", + "overlay.format_toolbar", + palette, + ); + for item in items { + let selected = current_id == Some(item.id); + let row = toolbar_menu_row( + format!("fmt-turn-{}", item.id), + format!("overlay.format_toolbar.turn_into.{}", item.id), + "overlay.format_toolbar.turn_into_menu", + item.title, + icon(item.icon, TOOLBAR_MENU_ICON, palette.icon).into_any_element(), + selected, + MenuActionVariant::Normal, + interactive, + OverlayEvent::FormatTurnInto(item.command), + palette, + cx, + ); + panel = panel.child(row); + } + Some((placed.rect, panel.into_any_element())) +} + +pub(super) fn render_align_dropdown( + toolbar_rect: FlowRect, + viewport: FlowRect, + current_align: Option, + progress: f32, + interactive: bool, + palette: &Palette, + cx: &mut Context, +) -> Option<(FlowRect, AnyElement)> { + let items = [ + ( + "align_left", + "Align Left", + BlockAlign::Left, + FormatAction::AlignLeft, + ), + ( + "align_center", + "Align Center", + BlockAlign::Center, + FormatAction::AlignCenter, + ), + ( + "align_right", + "Align Right", + BlockAlign::Right, + FormatAction::AlignRight, + ), + ]; + let width = TOOLBAR_MENU_MIN_W.min((viewport.w - 2.0 * POPOVER_EDGE_MARGIN).max(140.0)); + let height = (2.0 * (TOOLBAR_MENU_PADDING + TOOLBAR_CHROME_BORDER) + + items.len() as f32 * TOOLBAR_MENU_ROW_H) + .round(); + let placed = place_popover( + toolbar_rect, + (width, height), + viewport, + Placement::BelowStart, + 4.0, + POPOVER_EDGE_MARGIN, + ); + let mut panel = toolbar_dropdown_panel( + "format-align-menu", + placed.rect, + progress, + interactive, + "overlay.format_toolbar.align_menu", + "overlay.format_toolbar", + palette, + ); + for (id, label, align, action) in items { + let selected = current_align == Some(align); + let row = toolbar_menu_row( + format!("fmt-{id}"), + format!("overlay.format_toolbar.{id}"), + "overlay.format_toolbar.align_menu", + label, + align_glyph(align, palette.icon).into_any_element(), + selected, + MenuActionVariant::Normal, + interactive, + OverlayEvent::Format(action), + palette, + cx, + ); + panel = panel.child(row); + } + Some((placed.rect, panel.into_any_element())) +} + +/// The `Highlight` dropdown below its `button`, scrolled by `scroll` when the viewport is too +/// short for all of its rows. +#[allow(clippy::too_many_arguments)] +pub(super) fn render_highlight_dropdown( + button: FlowRect, + viewport: FlowRect, + marks: &MarkState, + scroll: &mut f32, + progress: f32, + interactive: bool, + palette: &Palette, + cx: &mut Context, +) -> Option<(FlowRect, AnyElement)> { + let heading_h = 22.0_f32; + let width = 200.0_f32.min((viewport.w - 2.0 * POPOVER_EDGE_MARGIN).max(160.0)); + let total_rows = HighlightColor::ALL.len() * 2; + let raw_h = 2.0 * (TOOLBAR_MENU_PADDING + TOOLBAR_CHROME_BORDER) + + 2.0 * heading_h + + total_rows as f32 * TOOLBAR_MENU_ROW_H + + 9.0; + // The taller side of the button bounds the menu, so it never covers the toolbar. + let room_below = viewport.bottom() - POPOVER_EDGE_MARGIN - button.bottom() - 4.0; + let room_above = button.y - 4.0 - viewport.y - POPOVER_EDGE_MARGIN; + let max_h = room_below.max(room_above).max(3.0 * TOOLBAR_MENU_ROW_H); + let height = raw_h.min(max_h).floor(); + let placed = place_popover( + button, + (width, height), + viewport, + Placement::BelowStart, + 4.0, + POPOVER_EDGE_MARGIN, + ); + let max_scroll = (raw_h - placed.rect.h).max(0.0).ceil(); + *scroll = scroll.clamp(0.0, max_scroll); + let mut panel = toolbar_dropdown_panel( + "format-highlight-menu", + placed.rect, + progress, + interactive, + "overlay.format_toolbar.highlight_menu", + "overlay.format_toolbar", + palette, + ); + if interactive && max_scroll > 0.0 { + let visible_h = placed.rect.h; + panel = panel.on_scroll(emit(cx, move |event: &ScrollEvent| { + OverlayEvent::HighlightMenuScroll(crate::scroll::wheel_delta(event, visible_h).1) + })); + } + let mut content = div().flex_none().flex().flex_col().mt(px(-*scroll)); + let border = chrome_border_color(palette); + for (section_idx, (section_id, heading, is_bg)) in [ + ("color", "Color", false), + ("background", "Background", true), + ] + .into_iter() + .enumerate() + { + if section_idx > 0 { + content = content.child(menu_horizontal_separator(palette)); + } + content = content.child( + div() + .flex_none() + .h(px(heading_h)) + .px(px(8.0)) + .flex() + .items_center() + .text_size(px(TYPOGRAPHY.font_xs_px)) + .font_weight(FontWeight::MEDIUM) + .text_color(palette.text_secondary) + .child(heading), + ); + for color in HighlightColor::ALL { + let selected = if is_bg { + marks.background.as_deref() == color.bg_css_var() + } else { + marks.color.as_deref() == color.fg_css_var() + }; + let fg = if is_bg { + palette.text_primary + } else { + color + .fg_css_var() + .and_then(|v| palette.theme.css_color(v)) + .unwrap_or(palette.text_primary) + }; + let bg = if is_bg { + color.bg_css_var().and_then(|v| palette.theme.css_color(v)) + } else { + None + }; + let label = match (color, is_bg) { + (HighlightColor::Default, false) => "Default color".to_string(), + (HighlightColor::Default, true) => "Default background".to_string(), + _ => color.label().to_string(), + }; + let ev = if is_bg { + OverlayEvent::FormatBgColor(color) + } else { + OverlayEvent::FormatTextColor(color) + }; + let row = toolbar_menu_row( + format!("fmt-hl-{section_id}-{}", color.id()), + format!( + "overlay.format_toolbar.highlight.{section_id}.{}", + color.id() + ), + "overlay.format_toolbar.highlight_menu", + SharedString::from(label), + duotone_text_badge(fg, bg, border), + selected, + MenuActionVariant::Normal, + interactive, + ev, + palette, + cx, + ); + content = content.child(row); + } + } + Some((placed.rect, panel.child(content).into_any_element())) +} + +pub(super) fn render_more_dropdown( + toolbar_rect: FlowRect, + viewport: FlowRect, + progress: f32, + interactive: bool, + palette: &Palette, + cx: &mut Context, +) -> Option<(FlowRect, AnyElement)> { + let width = TOOLBAR_MENU_MIN_W.min((viewport.w - 2.0 * POPOVER_EDGE_MARGIN).max(140.0)); + let height = + (2.0 * (TOOLBAR_MENU_PADDING + TOOLBAR_CHROME_BORDER) + 3.0 * TOOLBAR_MENU_ROW_H + 9.0) + .round(); + let anchor = FlowRect::new( + (toolbar_rect.right() - width).max(toolbar_rect.x), + toolbar_rect.y, + width, + toolbar_rect.h, + ); + let placed = place_popover( + anchor, + (width, height), + viewport, + Placement::BelowStart, + 4.0, + POPOVER_EDGE_MARGIN, + ); + let mut panel = toolbar_dropdown_panel( + "format-more-menu", + placed.rect, + progress, + interactive, + "overlay.format_toolbar.more_menu", + "overlay.format_toolbar", + palette, + ); + for (id, label, icon_name, action) in [ + ("copy", "Copy", "CopyIcon", FormatMoreAction::Copy), + ( + "duplicate", + "Duplicate", + "DuplicateIcon", + FormatMoreAction::Duplicate, + ), + ] { + panel = panel.child(toolbar_menu_row( + format!("fmt-more-{id}"), + format!("overlay.format_toolbar.more.{id}"), + "overlay.format_toolbar.more_menu", + label, + icon(icon_name, TOOLBAR_MENU_ICON, palette.icon).into_any_element(), + false, + MenuActionVariant::Normal, + interactive, + OverlayEvent::FormatMore(action), + palette, + cx, + )); + } + panel = panel.child(menu_horizontal_separator(palette)); + panel = panel.child(toolbar_menu_row( + "fmt-more-delete", + "overlay.format_toolbar.more.delete", + "overlay.format_toolbar.more_menu", + "Delete", + icon("DeleteIcon", TOOLBAR_MENU_ICON, palette.icon).into_any_element(), + false, + MenuActionVariant::Destructive, + interactive, + OverlayEvent::FormatMore(FormatMoreAction::Delete), + palette, + cx, + )); + Some((placed.rect, panel.into_any_element())) +} diff --git a/blocksuite/crates/editor/src/overlays/paint_toolbar/mod.rs b/blocksuite/crates/editor/src/overlays/paint_toolbar/mod.rs index abe0510471..d8037a3a13 100644 --- a/blocksuite/crates/editor/src/overlays/paint_toolbar/mod.rs +++ b/blocksuite/crates/editor/src/overlays/paint_toolbar/mod.rs @@ -1,21 +1,23 @@ -//! Desktop floating `FormatToolbar` painting (`overlay.format_toolbar`), including -//! `Turn into ▾` dropdown (reusing `SLASH_ITEMS`), `Highlight` 9+9 color/background palette -//! dropdown, `More (...)` dropdown, and dual-field `Text` + `Link` editor. +//! Desktop floating `FormatToolbar` painting (`overlay.format_toolbar`) using the shared +//! `ToolbarChrome`, including `Turn into ▾`, `Align ▾`, score-ordered inline marks, vertical +//! labelled `Highlight ▾`, `Create Table`, `Create Linked Doc`, `⋮ More`, and dual-field LinkBar. +mod dropdowns; mod link_fields; use blocksuite_playground_doc::read::TextAlign as BlockAlign; use ui::{ - AnyElement, ClickEvent, Context, FontWeight, MouseButton, SharedString, Window, div, - prelude::*, px, + AnyElement, ClickEvent, Context, FontWeight, MouseButton, MouseMoveEvent, SharedString, Window, + div, prelude::*, px, }; -use crate::{ - block_flow::FlowRect, - theme::{Palette, TYPOGRAPHY}, -}; +use crate::{block_flow::FlowRect, theme::Palette}; use super::*; +use dropdowns::{ + render_align_dropdown, render_highlight_dropdown, render_more_dropdown, + render_turn_into_dropdown, +}; use link_fields::{render_toolbar_link_row, render_toolbar_text_row}; impl Overlays { @@ -61,47 +63,69 @@ impl Overlays { let viewport = scene.popover_viewport(); let marks = toolbar.selection.marks.clone(); let align = toolbar.selection.align; + let current_turn_into_id = toolbar.selection.current_turn_into_id; + let can_create_table = toolbar.selection.can_create_table; let active_submenu = if link_only { None } else { toolbar.submenu }; + let show_more = !scene.suppress_floating_format_buttons; + let wide = viewport.w >= 460.0; + + // Compute exact content width for grouped ToolbarChrome layout. + let btn = TOOLBAR_CHROME_BTN; + let menu_btn_w = if wide { btn + 12.0 } else { btn + 8.0 }; // icon + chevron + let inner_gap = if wide { 4.0_f32 } else { 2.0_f32 }; + let group_gap = if wide { TOOLBAR_CHROME_GAP } else { 4.0_f32 }; + let chrome_px = if wide { TOOLBAR_CHROME_PX } else { 4.0_f32 }; + let sep_w = TOOLBAR_SEP_SLOT; + + // Groups: + // 1. Turn into (menu_btn_w) + // 2. Align (menu_btn_w) + // 3. Inline marks: wide => 7 (B I U S Code TeX Link), compact => 6 (B I U S Code Link) + // 4. Highlight (menu_btn_w) + // 5. Create Table (optional) + Create Linked Doc (wide only) + // 6. More (wide && show_more) + let inline_count = if wide { 7usize } else { 6usize }; + let mut group_widths = vec![menu_btn_w, menu_btn_w]; + group_widths.push(inline_count as f32 * btn + (inline_count - 1) as f32 * inner_gap); + group_widths.push(menu_btn_w); + if wide { + let conv_count = if can_create_table { 2usize } else { 1usize }; + group_widths.push(conv_count as f32 * btn + (conv_count - 1) as f32 * inner_gap); + if show_more { + group_widths.push(btn); + } + } + let seps = group_widths.len().saturating_sub(1); + let items_total: f32 = group_widths.iter().sum(); + let child_slots = group_widths.len() + seps; + let raw_inner_w = + items_total + seps as f32 * sep_w + child_slots.saturating_sub(1) as f32 * group_gap; + let border_px = TOOLBAR_CHROME_BORDER.ceil(); + let chrome_x = 2.0 * (chrome_px + border_px); + let max_w = (viewport.w - 2.0 * POPOVER_EDGE_MARGIN).max(200.0); + let width = (raw_inner_w + chrome_x).min(max_w).round(); + let inner_width = (width - chrome_x).max(160.0); - let actions: &[FormatAction] = if viewport.w >= 460.0 { - &FormatAction::ALL - } else { - &FormatAction::COMPACT - }; - let buttons = actions.len() as f32; - let chrome = 2.0 * (TOOLBAR_PADDING + POPOVER_BORDER); - let max_inner = (viewport.w - 2.0 * POPOVER_EDGE_MARGIN - chrome).max(200.0); - // Full 28px pills on desktop; compact to 24px pills on narrow (320px) viewports so all - // buttons stay >= 24x24 and never overflow the 8px viewport margins. - let sep_count = if viewport.w >= 460.0 { 3.0 } else { 2.0 }; - let full_sep = sep_count * (1.0 + 2.0 * TOOLBAR_SEPARATOR_MARGIN); - let full_inner = buttons * (TOOLBAR_BUTTON + TOOLBAR_GAP) + full_sep; - let (btn_size, btn_gap, sep_margin) = if full_inner <= max_inner { - (TOOLBAR_BUTTON, TOOLBAR_GAP, TOOLBAR_SEPARATOR_MARGIN) - } else { - (24.0, 1.0, 4.0) - }; - let sep_total = sep_count * (1.0 + 2.0 * sep_margin); - let inner_width = buttons * (btn_size + btn_gap) + sep_total; - let width = inner_width + chrome; let has_text_row = toolbar.link.is_some() && toolbar.link_text.is_some(); let link_rows = if toolbar.link.is_some() { if has_text_row { 2.0 } else { 1.0 } } else { 0.0 }; - let rows = if link_only { - link_rows + let height = if link_only { + link_rows * TOOLBAR_BUTTON + 2.0 * (TOOLBAR_PADDING + border_px) + } else if link_rows > 0.0 { + TOOLBAR_CHROME_HEIGHT + link_rows * TOOLBAR_BUTTON + 2.0 * border_px + 6.0 } else { - 1.0 + link_rows + (TOOLBAR_CHROME_HEIGHT + 2.0 * TOOLBAR_CHROME_BORDER).round() }; - let height = rows * TOOLBAR_BUTTON + (rows - 1.0) * TOOLBAR_ROW_GAP + chrome; + let placed = place_popover( anchor, (width, height), viewport, Placement::Above, - POPOVER_GAP, + TOOLBAR_CHROME_OFFSET, POPOVER_EDGE_MARGIN, ); toolbar.rect = Some(placed.rect); @@ -112,58 +136,60 @@ impl Overlays { } else { 0.0 }; - let field_width = - (inner_width - btn_gap - LINK_APPLY_WIDTH - remove_span - LINK_GAP).max(100.0); - let inset = POPOVER_BORDER + TOOLBAR_PADDING; - let base_row_offset = if link_only { - 0.0 + let field_width = (inner_width - LINK_APPLY_WIDTH - remove_span - LINK_GAP).max(100.0); + let inset_x = border_px + chrome_px; + let base_row_y = if link_only { + border_px + TOOLBAR_PADDING } else { - TOOLBAR_BUTTON + TOOLBAR_ROW_GAP + border_px + TOOLBAR_CHROME_HEIGHT }; if let Some(text_bar) = toolbar.link_text.as_mut() { text_bar.bounds = Some(FlowRect::new( - placed.rect.x + inset + btn_gap / 2.0, - placed.rect.y + inset + base_row_offset, - inner_width - btn_gap, + placed.rect.x + inset_x, + placed.rect.y + base_row_y, + inner_width, TOOLBAR_BUTTON, )); } if let Some(link) = toolbar.link.as_mut() { - let url_row_offset = if has_text_row { - base_row_offset + TOOLBAR_BUTTON + TOOLBAR_ROW_GAP + let url_y = if has_text_row { + base_row_y + TOOLBAR_BUTTON } else { - base_row_offset + base_row_y }; link.bounds = Some(FlowRect::new( - placed.rect.x + inset + btn_gap / 2.0, - placed.rect.y + inset + url_row_offset, + placed.rect.x + inset_x, + placed.rect.y + url_y, field_width, TOOLBAR_BUTTON, )); } - let radius = TOOLBAR_RADIUS - TOOLBAR_PADDING; let mut root = place(placed.rect) .id("format-toolbar") .flex() .flex_col() - .gap(px(TOOLBAR_ROW_GAP)) - .p(px(TOOLBAR_PADDING)) - .rounded(px(TOOLBAR_RADIUS)) - .bg(palette.panel) - .border_1() - .border_color(palette.border) - .shadow(palette.theme.shadows("--affine-toolbar-shadow").into()) + .px(px(chrome_px)) + .when(link_only, |el| el.py(px(TOOLBAR_PADDING))) + .when(!link_only && link_rows > 0.0, |el| el.pb(px(6.0))) + .rounded(px(TOOLBAR_CHROME_RADIUS)) + .bg(chrome_panel_bg(palette)) + .border(px(TOOLBAR_CHROME_BORDER)) + .border_color(chrome_border_color(palette)) + .shadow(palette.theme.shadows("--affine-overlay-shadow").into()) .opacity(progress) .snapshot("overlay.format_toolbar", Some("root.canvas")) .snapshot_focused(interactive); if interactive { - root = root.block_mouse_except_scroll(); + root = root + .block_mouse_except_scroll() + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()); } + // The `Highlight` dropdown opens below its own button. + let mut highlight_button = placed.rect; if !link_only { let hover = palette.hover; - let active_wash = palette.brand.opacity(0.12); let active_fg_swatch = marks .color .as_deref() @@ -173,122 +199,237 @@ impl Overlays { .as_deref() .and_then(|v| palette.theme.css_color(v)); - let mut row = div() - .flex_none() - .w(px(inner_width)) - .h(px(TOOLBAR_BUTTON)) - .flex() - .items_center(); - for &action in actions { - if matches!( - action, - FormatAction::Bold | FormatAction::AlignLeft | FormatAction::CreateLinkedDoc - ) { - row = row.child( - div() - .flex_none() - .w(px(1.0)) - .h(px(16.0)) - .mx(px(sep_margin)) - .bg(palette.border), - ); - } - let active = match action { - FormatAction::TurnInto => active_submenu == Some(ToolbarSubmenu::TurnInto), - FormatAction::Highlight => { - active_submenu == Some(ToolbarSubmenu::Highlight) - || marks.color.is_some() - || marks.background.is_some() - } - FormatAction::More => active_submenu == Some(ToolbarSubmenu::More), - FormatAction::Link => marks.link.is_some() || toolbar.link.is_some(), - _ => match (action.mark_key(), action.align()) { - (Some(key), _) => marks.has(key), - (_, Some(wanted)) => Some(wanted) == align, - _ => false, - }, - }; + let mut cursor_x = placed.rect.x + inset_x; + let btn_y = placed.rect.y + (TOOLBAR_CHROME_HEIGHT - btn) * 0.5; + let make_menu_btn = |action: FormatAction, + active: bool, + x: f32, + leading: AnyElement, + cx: &mut Context| + -> AnyElement { let ink = if active { palette.brand } else { palette.icon }; - let group = SharedString::from(format!("format-{}", action.id())); - let mut pill = div() - .flex_none() - .w(px(btn_size)) - .h(px(TOOLBAR_BUTTON)) - .rounded(px(radius)) - .flex() - .items_center() - .justify_center() - .when(active, |pill| pill.bg(active_wash)); - let mut button = div() + let tip = ToolbarTooltip { + label: action.label().to_string(), + anchor_screen: FlowRect::new(x, btn_y, menu_btn_w, btn), + }; + let mut el = div() .id(action.id()) - .group(group.clone()) .flex_none() - .w(px(btn_size + btn_gap)) - .h(px(TOOLBAR_BUTTON)) - .rounded(px(radius)) + .w(px(menu_btn_w)) + .h(px(btn)) + .rounded(px(TOOLBAR_CHROME_BTN_RADIUS)) .flex() .items_center() .justify_center() + .gap(px(1.0)) .snapshot( SharedString::from(format!("overlay.format_toolbar.{}", action.id())), Some("overlay.format_toolbar"), ) .snapshot_focused(active) - .snapshot_text(action.label()); + .snapshot_text(action.label()) + .child(leading) + .child(chrome_icon(ChromeIcon::ChevronDown, 12.0, ink)); if interactive { - pill = pill.group_hover(group, move |style| style.bg(hover)); - button = button + el = el .cursor_pointer() + .hover(move |s| s.bg(hover)) + .on_mouse_move(emit(cx, move |_: &MouseMoveEvent| { + OverlayEvent::SetToolbarTooltip(Some(tip.clone())) + })) .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_click(emit(cx, move |_: &ClickEvent| OverlayEvent::Format(action))); } - let icon_size = if btn_size < 26.0 { 16.0 } else { 18.0 }; - let content = match action { - FormatAction::TurnInto => pill.child( - div() - .flex() - .items_center() - .gap(px(1.0)) - .child(icon("TextIcon", icon_size - 2.0, ink)) - .child(icon("ToggleDownIcon", 10.0, ink)), - ), - FormatAction::InlineEquation => pill.child( - div() - .text_size(px(10.0)) - .font_weight(FontWeight::SEMIBOLD) - .text_color(ink) - .child("TeX"), - ), - FormatAction::Highlight => { - let bar_color = active_fg_swatch - .or(active_bg_swatch) - .unwrap_or(palette.brand); - pill.child( - div() - .flex() - .flex_col() - .items_center() - .justify_center() - .child( - div() - .text_size(px(12.0)) - .line_height(px(13.0)) - .font_weight(FontWeight::SEMIBOLD) - .text_color(active_fg_swatch.unwrap_or(ink)) - .child("A"), - ) - .child(div().w(px(12.0)).h(px(2.5)).rounded(px(1.0)).bg(bar_color)), - ) - } - _ => match (action.icon(), action.align()) { - (Some(name), _) => pill.child(icon(name, icon_size, ink)), - (None, align) => { - pill.child(align_glyph(align.unwrap_or(BlockAlign::Left), ink)) - } - }, + el.into_any_element() + }; + + let turn_active = active_submenu == Some(ToolbarSubmenu::TurnInto); + let turn_ink = if turn_active { + palette.brand + } else { + palette.icon + }; + let turn_icon_name = current_turn_into_id + .and_then(slash_item_by_id) + .map_or("TextIcon", |item| item.icon); + let g_turn = vec![make_menu_btn( + FormatAction::TurnInto, + turn_active, + cursor_x, + icon(turn_icon_name, TOOLBAR_CHROME_ICON, turn_ink).into_any_element(), + cx, + )]; + cursor_x += menu_btn_w + group_gap + sep_w + group_gap; + + let align_active = active_submenu == Some(ToolbarSubmenu::Align); + let align_ink = if align_active { + palette.brand + } else { + palette.icon + }; + let g_align = vec![make_menu_btn( + FormatAction::Align, + align_active, + cursor_x, + align_glyph(align.unwrap_or(BlockAlign::Left), align_ink).into_any_element(), + cx, + )]; + cursor_x += menu_btn_w + group_gap + sep_w + group_gap; + + let inline_actions: &[FormatAction] = if wide { + &[ + FormatAction::Bold, + FormatAction::Italic, + FormatAction::Underline, + FormatAction::Strike, + FormatAction::Code, + FormatAction::InlineEquation, + FormatAction::Link, + ] + } else { + &[ + FormatAction::Bold, + FormatAction::Italic, + FormatAction::Underline, + FormatAction::Strike, + FormatAction::Code, + FormatAction::Link, + ] + }; + let mut g_inline = Vec::with_capacity(inline_actions.len()); + for (i, &action) in inline_actions.iter().enumerate() { + let bx = cursor_x + i as f32 * (btn + inner_gap); + let active = match action { + FormatAction::Link => marks.link.is_some() || toolbar.link.is_some(), + _ => action.mark_key().is_some_and(|k| marks.has(k)), }; - row = row.child(button.child(content)); + let ink = if active { palette.brand } else { palette.icon }; + let glyph = match action { + FormatAction::InlineEquation => div() + .text_size(px(10.0)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(ink) + .child("TeX") + .into_any_element(), + _ => icon( + action.icon().unwrap_or("BoldIcon"), + TOOLBAR_CHROME_ICON, + ink, + ) + .into_any_element(), + }; + g_inline.push(toolbar_icon_button( + action.id(), + format!("overlay.format_toolbar.{}", action.id()), + "overlay.format_toolbar", + action.label(), + FlowRect::new(bx, btn_y, btn, btn), + active, + interactive, + glyph, + OverlayEvent::Format(action), + palette, + cx, + )); } + cursor_x += inline_actions.len() as f32 * btn + + inline_actions.len().saturating_sub(1) as f32 * inner_gap + + group_gap + + sep_w + + group_gap; + + let hl_active = active_submenu == Some(ToolbarSubmenu::Highlight) + || marks.color.is_some() + || marks.background.is_some(); + let hl_ink = if hl_active { + palette.brand + } else { + palette.icon + }; + let hl_badge = duotone_text_badge( + active_fg_swatch.unwrap_or(hl_ink), + active_bg_swatch, + chrome_border_color(palette), + ); + let g_highlight = vec![make_menu_btn( + FormatAction::Highlight, + hl_active, + cursor_x, + hl_badge, + cx, + )]; + highlight_button = FlowRect::new(cursor_x, placed.rect.y, menu_btn_w, placed.rect.h); + cursor_x += menu_btn_w + group_gap + sep_w + group_gap; + + let mut groups = vec![g_turn, g_align, g_inline, g_highlight]; + + if wide { + let mut g_conv = Vec::new(); + if can_create_table { + g_conv.push(toolbar_icon_button( + FormatAction::CreateTable.id(), + "overlay.format_toolbar.create_table", + "overlay.format_toolbar", + FormatAction::CreateTable.label(), + FlowRect::new(cursor_x, btn_y, btn, btn), + false, + interactive, + chrome_icon(ChromeIcon::DatabaseTable, TOOLBAR_CHROME_ICON, palette.icon), + OverlayEvent::Format(FormatAction::CreateTable), + palette, + cx, + )); + cursor_x += btn + inner_gap; + } + g_conv.push(toolbar_icon_button( + FormatAction::CreateLinkedDoc.id(), + "overlay.format_toolbar.create_linked_doc", + "overlay.format_toolbar", + FormatAction::CreateLinkedDoc.label(), + FlowRect::new(cursor_x, btn_y, btn, btn), + false, + interactive, + icon("LinkedPageIcon", TOOLBAR_CHROME_ICON, palette.icon).into_any_element(), + OverlayEvent::Format(FormatAction::CreateLinkedDoc), + palette, + cx, + )); + cursor_x += btn + group_gap + sep_w + group_gap; + groups.push(g_conv); + + if show_more { + let more_active = active_submenu == Some(ToolbarSubmenu::More); + let more_ink = if more_active { + palette.brand + } else { + palette.icon + }; + groups.push(vec![toolbar_icon_button( + FormatAction::More.id(), + "overlay.format_toolbar.more", + "overlay.format_toolbar", + FormatAction::More.label(), + FlowRect::new(cursor_x, btn_y, btn, btn), + more_active, + interactive, + chrome_icon(ChromeIcon::MoreVertical, TOOLBAR_CHROME_ICON, more_ink), + OverlayEvent::Format(FormatAction::More), + palette, + cx, + )]); + } + } + + let row = append_toolbar_groups( + div() + .flex_none() + .h(px(TOOLBAR_CHROME_HEIGHT)) + .flex() + .items_center() + .gap(px(group_gap)), + groups, + palette, + ); root = root.child(row); } @@ -299,8 +440,8 @@ impl Overlays { root = root.child(render_toolbar_text_row( link_text, inner_width, - btn_gap, - radius, + 0.0, + TOOLBAR_CHROME_BTN_RADIUS, interactive, active_field == LinkEditField::Text, palette, @@ -312,9 +453,9 @@ impl Overlays { root = root.child(render_toolbar_link_row( link, inner_width, - btn_gap, + 0.0, field_width, - radius, + TOOLBAR_CHROME_BTN_RADIUS, interactive, active_field == LinkEditField::Url, has_existing_link, @@ -325,21 +466,34 @@ impl Overlays { } out.push(root.into_any_element()); - // Render attached dropdown submenu (`Turn into ▾`, `Highlight` 9+9 palette, or `More`). + if active_submenu != Some(ToolbarSubmenu::Highlight) { + self.highlight_menu_scroll = 0.0; + } if let Some(submenu) = active_submenu { let sub_el = match submenu { ToolbarSubmenu::TurnInto => render_turn_into_dropdown( placed.rect, viewport, + current_turn_into_id, + progress, + interactive, + palette, + cx, + ), + ToolbarSubmenu::Align => render_align_dropdown( + placed.rect, + viewport, + align, progress, interactive, palette, cx, ), ToolbarSubmenu::Highlight => render_highlight_dropdown( - placed.rect, + highlight_button, viewport, &marks, + &mut self.highlight_menu_scroll, progress, interactive, palette, @@ -357,362 +511,3 @@ impl Overlays { out } } - -fn render_turn_into_dropdown( - toolbar_rect: FlowRect, - viewport: FlowRect, - progress: f32, - interactive: bool, - palette: &Palette, - cx: &mut Context, -) -> Option<(FlowRect, AnyElement)> { - let row_h = 28.0_f32; - let pad = 4.0_f32; - let width = 180.0_f32.min((viewport.w - 2.0 * POPOVER_EDGE_MARGIN).max(120.0)); - let height = (2.0 * (pad + POPOVER_BORDER) + FORMAT_TURN_INTO_IDS.len() as f32 * row_h) - .min((viewport.h - 2.0 * POPOVER_EDGE_MARGIN).max(row_h + 10.0)) - .round(); - let placed = place_popover( - toolbar_rect, - (width, height), - viewport, - Placement::BelowStart, - 4.0, - POPOVER_EDGE_MARGIN, - ); - let hover = palette.hover; - let mut panel = place(placed.rect) - .id("format-turn-into-menu") - .flex() - .flex_col() - .p(px(pad)) - .rounded(px(TOOLBAR_RADIUS)) - .bg(palette.panel) - .border_1() - .border_color(palette.border) - .shadow( - palette - .theme - .shadows("--affine-overlay-panel-shadow") - .into(), - ) - .overflow_hidden() - .opacity(progress) - .snapshot( - "overlay.format_toolbar.turn_into_menu", - Some("overlay.format_toolbar"), - ) - .snapshot_focused(interactive); - if interactive { - panel = panel - .occlude() - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()); - } - for slash_id in FORMAT_TURN_INTO_IDS { - let item = slash_item_const(slash_id); - let cmd = item.command; - let mut row = div() - .id(SharedString::from(format!("fmt-turn-{}", item.id))) - .flex_none() - .w_full() - .h(px(row_h)) - .px(px(8.0)) - .rounded(px(4.0)) - .flex() - .items_center() - .gap(px(8.0)) - .text_size(px(TYPOGRAPHY.font_xs_px)) - .text_color(palette.text_primary) - .snapshot( - SharedString::from(format!("overlay.format_toolbar.turn_into.{}", item.id)), - Some("overlay.format_toolbar.turn_into_menu"), - ) - .snapshot_text(item.title) - .child(icon(item.icon, 16.0, palette.icon)) - .child(item.title); - if interactive { - row = row - .cursor_pointer() - .hover(move |s| s.bg(hover)) - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_click(emit(cx, move |_: &ClickEvent| { - OverlayEvent::FormatTurnInto(cmd) - })); - } - panel = panel.child(row); - } - Some((placed.rect, panel.into_any_element())) -} - -fn render_highlight_dropdown( - toolbar_rect: FlowRect, - viewport: FlowRect, - marks: &MarkState, - progress: f32, - interactive: bool, - palette: &Palette, - cx: &mut Context, -) -> Option<(FlowRect, AnyElement)> { - let swatch = 24.0_f32; - let gap = 4.0_f32; - let pad = 8.0_f32; - let row_w = - HighlightColor::ALL.len() as f32 * swatch + (HighlightColor::ALL.len() - 1) as f32 * gap; - let width = (row_w + 2.0 * (pad + POPOVER_BORDER)) - .min((viewport.w - 2.0 * POPOVER_EDGE_MARGIN).max(160.0)) - .round(); - // 2 headers (16px) + 2 swatch rows (24px) + gaps + padding - let height = (2.0 * (pad + POPOVER_BORDER) + 2.0 * (16.0 + 4.0 + swatch) + 8.0).round(); - let placed = place_popover( - toolbar_rect, - (width, height), - viewport, - Placement::BelowStart, - 4.0, - POPOVER_EDGE_MARGIN, - ); - let hover = palette.hover; - let mut panel = place(placed.rect) - .id("format-highlight-menu") - .flex() - .flex_col() - .gap(px(6.0)) - .p(px(pad)) - .rounded(px(TOOLBAR_RADIUS)) - .bg(palette.panel) - .border_1() - .border_color(palette.border) - .shadow( - palette - .theme - .shadows("--affine-overlay-panel-shadow") - .into(), - ) - .opacity(progress) - .snapshot( - "overlay.format_toolbar.highlight_menu", - Some("overlay.format_toolbar"), - ) - .snapshot_focused(interactive); - if interactive { - panel = panel - .occlude() - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()); - } - - for (section_id, title, is_bg) in [ - ("color", "Color", false), - ("background", "Background", true), - ] { - let mut strip = div().flex().items_center().gap(px(gap)); - for color in HighlightColor::ALL { - let selected = if is_bg { - marks.background.as_deref() == color.bg_css_var() - } else { - marks.color.as_deref() == color.fg_css_var() - }; - let bg = if is_bg { - color - .bg_css_var() - .and_then(|v| palette.theme.css_color(v)) - .unwrap_or(palette.background_secondary) - } else { - palette.background_secondary - }; - let fg = if is_bg { - palette.text_primary - } else { - color - .fg_css_var() - .and_then(|v| palette.theme.css_color(v)) - .unwrap_or(palette.text_primary) - }; - let mut tile = div() - .id(SharedString::from(format!( - "fmt-hl-{section_id}-{}", - color.id() - ))) - .flex_none() - .w(px(swatch)) - .h(px(swatch)) - .rounded(px(4.0)) - .bg(bg) - .border_1() - .border_color(if selected { - palette.brand - } else { - palette.border - }) - .flex() - .items_center() - .justify_center() - .text_size(px(12.0)) - .font_weight(FontWeight::SEMIBOLD) - .text_color(fg) - .snapshot( - SharedString::from(format!( - "overlay.format_toolbar.highlight.{section_id}.{}", - color.id() - )), - Some("overlay.format_toolbar.highlight_menu"), - ) - .snapshot_focused(selected) - .snapshot_text(color.label()) - .child("A"); - if interactive { - tile = tile - .cursor_pointer() - .hover(move |s| s.bg(hover)) - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_click(emit(cx, move |_: &ClickEvent| { - if is_bg { - OverlayEvent::FormatBgColor(color) - } else { - OverlayEvent::FormatTextColor(color) - } - })); - } - strip = strip.child(tile); - } - panel = panel.child( - div() - .flex() - .flex_col() - .gap(px(4.0)) - .child( - div() - .h(px(16.0)) - .flex() - .items_center() - .text_size(px(TYPOGRAPHY.font_xs_px)) - .font_weight(FontWeight::MEDIUM) - .text_color(palette.text_secondary) - .child(title), - ) - .child(strip), - ); - } - - Some((placed.rect, panel.into_any_element())) -} - -fn render_more_dropdown( - toolbar_rect: FlowRect, - viewport: FlowRect, - progress: f32, - interactive: bool, - palette: &Palette, - cx: &mut Context, -) -> Option<(FlowRect, AnyElement)> { - let row_h = 28.0_f32; - let pad = 4.0_f32; - let width = 148.0_f32.min((viewport.w - 2.0 * POPOVER_EDGE_MARGIN).max(120.0)); - let items: [( - &'static str, - &'static str, - &'static str, - FormatMoreAction, - bool, - ); 3] = [ - ("copy", "Copy", "CopyIcon", FormatMoreAction::Copy, false), - ( - "duplicate", - "Duplicate", - "DuplicateIcon", - FormatMoreAction::Duplicate, - false, - ), - ( - "delete", - "Delete", - "DeleteIcon", - FormatMoreAction::Delete, - true, - ), - ]; - let height = (2.0 * (pad + POPOVER_BORDER) + items.len() as f32 * row_h).round(); - let anchor = FlowRect::new( - (toolbar_rect.right() - width).max(toolbar_rect.x), - toolbar_rect.y, - width, - toolbar_rect.h, - ); - let placed = place_popover( - anchor, - (width, height), - viewport, - Placement::BelowStart, - 4.0, - POPOVER_EDGE_MARGIN, - ); - let hover = palette.hover; - let danger = palette - .theme - .css_var("--affine-error-color") - .unwrap_or(palette.text_primary); - let mut panel = place(placed.rect) - .id("format-more-menu") - .flex() - .flex_col() - .p(px(pad)) - .rounded(px(TOOLBAR_RADIUS)) - .bg(palette.panel) - .border_1() - .border_color(palette.border) - .shadow( - palette - .theme - .shadows("--affine-overlay-panel-shadow") - .into(), - ) - .overflow_hidden() - .opacity(progress) - .snapshot( - "overlay.format_toolbar.more_menu", - Some("overlay.format_toolbar"), - ) - .snapshot_focused(interactive); - if interactive { - panel = panel - .occlude() - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()); - } - for (id, label, icon_name, action, is_danger) in items { - let ink = if is_danger { - danger - } else { - palette.text_primary - }; - let icon_ink = if is_danger { danger } else { palette.icon }; - let mut row = div() - .id(SharedString::from(format!("fmt-more-{id}"))) - .flex_none() - .w_full() - .h(px(row_h)) - .px(px(8.0)) - .rounded(px(4.0)) - .flex() - .items_center() - .gap(px(8.0)) - .text_size(px(TYPOGRAPHY.font_xs_px)) - .text_color(ink) - .snapshot( - SharedString::from(format!("overlay.format_toolbar.more.{id}")), - Some("overlay.format_toolbar.more_menu"), - ) - .snapshot_text(label) - .child(icon(icon_name, 16.0, icon_ink)) - .child(label); - if interactive { - row = row - .cursor_pointer() - .hover(move |s| s.bg(hover)) - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_click(emit(cx, move |_: &ClickEvent| { - OverlayEvent::FormatMore(action) - })); - } - panel = panel.child(row); - } - Some((placed.rect, panel.into_any_element())) -} diff --git a/blocksuite/crates/editor/src/overlays/scrollbar.rs b/blocksuite/crates/editor/src/overlays/scrollbar.rs index ac22304070..73321adeec 100644 --- a/blocksuite/crates/editor/src/overlays/scrollbar.rs +++ b/blocksuite/crates/editor/src/overlays/scrollbar.rs @@ -209,14 +209,17 @@ pub const HSCROLLBAR_HOVER_HEIGHT: f32 = 8.0; /// Minimum horizontal scrollbar thumb width in logical pixels. pub const HSCROLLBAR_MIN_THUMB: f32 = 32.0; -/// Compute the world-space `24px` interactive hitbox rect and scroll metrics for a wide -/// `affine:table` or `affine:database` block's bottom horizontal scrollbar. +/// Compute the world-space `24px` interactive hitbox rect and scroll metrics for the bottom +/// horizontal scrollbar of a wide `affine:table`, `affine:database`, or unwrapped `affine:code` +/// block. pub(super) fn block_hscrollbar_world_rect( block: &crate::block_flow::FlowBlock, ) -> Option<(crate::block_flow::FlowRect, crate::block_flow::CodeScroll)> { if !matches!( block.body.kind, - crate::block_flow::FlowKind::Table | crate::block_flow::FlowKind::Database + crate::block_flow::FlowKind::Table + | crate::block_flow::FlowKind::Database + | crate::block_flow::FlowKind::Code ) { return None; } @@ -237,7 +240,7 @@ pub(super) fn block_hscrollbar_world_rect( } /// Build a hover-revealed `4 -> 8px` horizontal scrollbar along the bottom edge of a wide -/// `affine:table` or `affine:database` (Table / Kanban) block. +/// `affine:table`, `affine:database` (Table / Kanban), or unwrapped `affine:code` block. #[allow(clippy::too_many_arguments)] pub(super) fn build_block_hscrollbar( block_id: &str, @@ -346,6 +349,50 @@ pub struct ScrollCodeOutcome { } impl super::Overlays { + /// Push the horizontal scrollbar of a wide block while the pointer is on it or drags it, on + /// desktop pointers only. + #[allow(clippy::too_many_arguments)] + pub(super) fn push_block_hscrollbar( + &self, + block: &crate::block_flow::FlowBlock, + hovered: bool, + scene: &super::OverlayScene<'_>, + viewport: crate::block_flow::PageViewport, + scale_factor: f32, + palette: &Palette, + cx: &mut Context, + elements: &mut Vec, + ) { + let dragging = self + .hscroll_drag + .as_ref() + .is_some_and(|d| d.block_id == block.block_id); + let revealed = + hovered || dragging || self.hscroll_hovered.as_deref() == Some(block.block_id.as_str()); + if !revealed + || scene.is_touch + || scene.form_factor != crate::block_flow::FormFactor::Desktop + { + return; + } + if let Some((bar_world, code)) = block_hscrollbar_world_rect(block) + && viewport.intersects(&bar_world) + && let Some(el) = build_block_hscrollbar( + &block.block_id, + &block.snapshot_id, + viewport.to_local(&bar_world), + self.code_scroll_x_for(&block.block_id, code), + code.max_x, + dragging, + scale_factor, + palette, + cx, + ) + { + elements.push(el); + } + } + /// Whether a horizontal block scrollbar thumb drag is currently active. pub fn is_hscroll_dragging(&self) -> bool { self.hscroll_drag.is_some() diff --git a/blocksuite/crates/editor/src/overlays/state.rs b/blocksuite/crates/editor/src/overlays/state.rs index 45ba20df48..ac1f51d7a9 100644 --- a/blocksuite/crates/editor/src/overlays/state.rs +++ b/blocksuite/crates/editor/src/overlays/state.rs @@ -35,6 +35,8 @@ impl Overlays { self.close_code_lang_picker(now_ms); self.close_code_more_menu(now_ms); self.callout_icon_picker_block = None; + self.block_submenu = None; + self.hovered_tooltip = None; self.drag = None; self.drop_indicator_motion = None; self.marquee = None; @@ -196,6 +198,9 @@ impl Overlays { self.set_handle_hot(handle_hot, now_ms); effects.redraw = true; } + if self.sync_hover_affordances(scene, x, y, now_ms) { + effects.redraw = true; + } } } OverlayEvent::PointerUp => { @@ -305,9 +310,19 @@ impl Overlays { effects.redraw = true; } } + OverlayEvent::HighlightMenuScroll(delta) => { + // Clamped to the menu when it is laid out. + self.highlight_menu_scroll = (self.highlight_menu_scroll - delta).max(0.0); + effects.redraw = true; + } // The selection is the editor's; the view sets it there. OverlayEvent::SetSelection(_) => {} - OverlayEvent::Format(action) => self.format(action, &mut effects), + OverlayEvent::Format(action) => { + self.format(action, &mut effects); + if self.toolbar_submenu().is_some() { + self.hovered_tooltip = None; + } + } OverlayEvent::FormatTurnInto(command) => { self.close_toolbar_submenu(); effects.edits.push(DocEdit::TurnInto(command)); @@ -363,7 +378,7 @@ impl Overlays { } OverlayEvent::SetCodeLanguage { .. } | OverlayEvent::OpenCodeLangPicker(_) - | OverlayEvent::CodeLangPickerScroll(_) + | OverlayEvent::CodeLangPickerScroll { .. } | OverlayEvent::CodeLangPickerHover(_) | OverlayEvent::SetBlockScrollX { .. } | OverlayEvent::StartBlockHScrollDrag { .. } @@ -480,10 +495,24 @@ impl Overlays { OverlayEvent::CloseLinkPopup => { effects.redraw = self.close_link_popup(now_ms); } - OverlayEvent::CloseContextMenu => { - effects.redraw = self.close_context_menu(now_ms); + OverlayEvent::CloseContextMenu => effects.redraw = self.close_context_menu(now_ms), + OverlayEvent::SetToolbarTooltip(tip) => { + // A tooltip never shows beside an open dropdown. + let tip = tip + .filter(|_| self.block_submenu.is_none() && self.toolbar_submenu().is_none()); + if self.hovered_tooltip != tip { + self.hovered_tooltip = tip; + effects.redraw = true; + } } - OverlayEvent::OpenLinkedDocMenu { .. } + OverlayEvent::ToggleBlockSubmenu(sub) => { + self.block_submenu = (self.block_submenu.as_ref() != Some(&sub)).then_some(sub); + self.hovered_tooltip = None; + effects.redraw = true; + } + OverlayEvent::EmbedToolbarAction { .. } + | OverlayEvent::CloseBlockSubmenu + | OverlayEvent::OpenLinkedDocMenu { .. } | OverlayEvent::SetLinkedDocQuery(_) | OverlayEvent::LinkedDocHover(_) | OverlayEvent::LinkedDocSelect(_) @@ -695,7 +724,8 @@ impl Overlays { return effects; } - if key == "escape" && self.close_toolbar_submenu() { + if key == "escape" && (self.close_toolbar_submenu() || self.block_submenu.take().is_some()) + { effects.handled = true; effects.redraw = true; return effects; diff --git a/blocksuite/crates/editor/src/overlays/table_cell.rs b/blocksuite/crates/editor/src/overlays/table_cell.rs index 94553a97a2..2be5bb8251 100644 --- a/blocksuite/crates/editor/src/overlays/table_cell.rs +++ b/blocksuite/crates/editor/src/overlays/table_cell.rs @@ -29,6 +29,35 @@ pub struct TableColResizeDrag { pub preview_width: f32, } +/// Kind of Simple Table hover add-bar drag (right bar = columns, bottom bar = rows, corner = both). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TableAddDragKind { + Row, + Column, + Both, +} + +/// Active drag on a Simple Table hover add bar or bottom-right corner button. +#[derive(Clone, Debug, PartialEq)] +pub struct TableAddDrag { + pub block_id: String, + pub kind: TableAddDragKind, + pub start_screen: (f32, f32), + pub preview_rows: usize, + pub preview_cols: usize, + pub moved: bool, +} + +/// Paint-only hover state for Simple Table (`affine:table`) desktop affordances. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TableHoverState { + pub block_id: Option, + pub row_id: Option, + pub column_id: Option, + pub hover_since_ms: f64, + pub add_drag: Option, +} + /// Focused `affine:table` cell edited directly in place against its live `Y.Text`. #[derive(Clone, Debug)] pub struct InlineTableCell { diff --git a/blocksuite/crates/editor/src/overlays/toolbar.rs b/blocksuite/crates/editor/src/overlays/toolbar.rs index a6656a06b8..7d8bdf551c 100644 --- a/blocksuite/crates/editor/src/overlays/toolbar.rs +++ b/blocksuite/crates/editor/src/overlays/toolbar.rs @@ -11,6 +11,7 @@ use super::*; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum FormatAction { TurnInto, + Align, Bold, Italic, Underline, @@ -19,6 +20,7 @@ pub enum FormatAction { InlineEquation, Highlight, Link, + CreateTable, AlignLeft, AlignCenter, AlignRight, @@ -43,27 +45,28 @@ pub enum LinkEditField { } impl FormatAction { - /// Full desktop toolbar buttons in order. - pub const ALL: [Self; 14] = [ + /// Full desktop toolbar buttons in BlockSuite score order (`Turn into` │ `Align ▾` │ + /// `B I U S Code TeX Link` │ `Highlight ▾` │ `Create Table` `Create Linked Doc` │ `⋮ More`). + pub const ALL: [Self; 13] = [ Self::TurnInto, + Self::Align, Self::Bold, Self::Italic, Self::Underline, Self::Strike, Self::Code, Self::InlineEquation, - Self::Highlight, Self::Link, - Self::AlignLeft, - Self::AlignCenter, - Self::AlignRight, + Self::Highlight, + Self::CreateTable, Self::CreateLinkedDoc, Self::More, ]; - /// Compact 11-button subset for narrow (`< 460 px`) viewports so every button stays `>= 24 px`. - pub const COMPACT: [Self; 11] = [ + /// Compact subset for narrow (`< 460 px`) viewports so every button stays `>= 24 px`. + pub const COMPACT: [Self; 9] = [ Self::TurnInto, + Self::Align, Self::Bold, Self::Italic, Self::Underline, @@ -71,15 +74,13 @@ impl FormatAction { Self::Code, Self::Highlight, Self::Link, - Self::AlignLeft, - Self::AlignCenter, - Self::AlignRight, ]; /// Last segment of the button's snapshot id. pub fn id(self) -> &'static str { match self { Self::TurnInto => "turn_into", + Self::Align => "align", Self::Bold => "bold", Self::Italic => "italic", Self::Underline => "underline", @@ -88,6 +89,7 @@ impl FormatAction { Self::InlineEquation => "inline_equation", Self::Highlight => "highlight", Self::Link => "link", + Self::CreateTable => "create_table", Self::AlignLeft => "align_left", Self::AlignCenter => "align_center", Self::AlignRight => "align_right", @@ -99,6 +101,7 @@ impl FormatAction { pub fn label(self) -> &'static str { match self { Self::TurnInto => "Turn into", + Self::Align => "Align", Self::Bold => "Bold", Self::Italic => "Italic", Self::Underline => "Underline", @@ -107,6 +110,7 @@ impl FormatAction { Self::InlineEquation => "Inline Equation", Self::Highlight => "Highlight", Self::Link => "Link", + Self::CreateTable => "Create Table", Self::AlignLeft => "Align Left", Self::AlignCenter => "Align Center", Self::AlignRight => "Align Right", @@ -118,6 +122,7 @@ impl FormatAction { pub(super) fn icon(self) -> Option<&'static str> { match self { Self::TurnInto => Some("TextIcon"), + Self::Align => None, Self::Bold => Some("BoldIcon"), Self::Italic => Some("ItalicIcon"), Self::Underline => Some("UnderLineIcon"), @@ -126,9 +131,10 @@ impl FormatAction { Self::InlineEquation => None, Self::Highlight => None, Self::Link => Some("LinkIcon"), + Self::CreateTable => None, Self::AlignLeft | Self::AlignCenter | Self::AlignRight => None, Self::CreateLinkedDoc => Some("LinkedPageIcon"), - Self::More => Some("MoreHorizontalIcon"), + Self::More => None, } } @@ -158,6 +164,7 @@ impl FormatAction { #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ToolbarSubmenu { TurnInto, + Align, Highlight, More, } @@ -300,6 +307,10 @@ pub struct SelectionFormat { pub align: Option, /// Selected plain text for single-block inline selections (seeds the `Text` field in LinkBar). pub selected_text: Option, + /// Slash item id of the primary selected block (for `Turn into ▾` icon and selected row). + pub current_turn_into_id: Option<&'static str>, + /// Whether `Create Table` is eligible (single-block text selection or paragraph/list block selection). + pub can_create_table: bool, } pub(super) use crate::inline_input::{Utf16ImeBuffer, utf16_to_byte}; @@ -644,41 +655,27 @@ impl Overlays { }; effects.redraw = true; match action { - FormatAction::TurnInto => { + FormatAction::TurnInto + | FormatAction::Align + | FormatAction::Highlight + | FormatAction::More => { toolbar.link = None; toolbar.link_text = None; toolbar.link_initial_text = None; toolbar.link_expected_prev_url = None; toolbar.standalone_link_block_id = None; - toolbar.submenu = if toolbar.submenu == Some(ToolbarSubmenu::TurnInto) { - None - } else { - Some(ToolbarSubmenu::TurnInto) + let target = match action { + FormatAction::TurnInto => ToolbarSubmenu::TurnInto, + FormatAction::Align => ToolbarSubmenu::Align, + FormatAction::Highlight => ToolbarSubmenu::Highlight, + _ => ToolbarSubmenu::More, }; + toolbar.submenu = (toolbar.submenu != Some(target)).then_some(target); } - FormatAction::Highlight => { - toolbar.link = None; - toolbar.link_text = None; - toolbar.link_initial_text = None; - toolbar.link_expected_prev_url = None; - toolbar.standalone_link_block_id = None; - toolbar.submenu = if toolbar.submenu == Some(ToolbarSubmenu::Highlight) { - None - } else { - Some(ToolbarSubmenu::Highlight) - }; - } - FormatAction::More => { - toolbar.link = None; - toolbar.link_text = None; - toolbar.link_initial_text = None; - toolbar.link_expected_prev_url = None; - toolbar.standalone_link_block_id = None; - toolbar.submenu = if toolbar.submenu == Some(ToolbarSubmenu::More) { - None - } else { - Some(ToolbarSubmenu::More) - }; + FormatAction::CreateTable => { + toolbar.submenu = None; + toolbar.submenu_rect = None; + effects.edits.push(DocEdit::CreateTableFromSelection); } FormatAction::InlineEquation => { toolbar.submenu = None; diff --git a/blocksuite/crates/editor/src/overlays/toolbar_chrome/hover.rs b/blocksuite/crates/editor/src/overlays/toolbar_chrome/hover.rs new file mode 100644 index 0000000000..6e37e3aa7b --- /dev/null +++ b/blocksuite/crates/editor/src/overlays/toolbar_chrome/hover.rs @@ -0,0 +1,314 @@ +//! Deterministic scheduler-clock hover controller (`500 ms` enter, `250 ms` leave, safe bridge) +//! and Page-mode hover affordance tracking for Image inner toolbars and Simple Tables. + +use super::{HOVER_ENTER_DELAY_MS, HOVER_LEAVE_DELAY_MS}; +use crate::{ + block_flow::{FlowKind, FlowRect, FormFactor}, + overlays::{OverlayScene, Overlays, TableHoverState}, +}; + +/// Lifecycle phase of a scheduler-clock hover-triggered surface. +#[derive(Clone, Debug, PartialEq)] +pub enum HoverPhase { + Idle, + Entering { + target: T, + since_ms: f64, + }, + Open { + target: T, + opened_ms: f64, + }, + Leaving { + target: T, + opened_ms: f64, + leave_since_ms: f64, + }, +} + +/// Pure scheduler-clock hover controller (`500 ms` enter, `250 ms` leave, safe bridge). +/// +/// Drives the desktop Image inner toolbar. +#[derive(Clone, Debug, PartialEq)] +pub struct HoverController { + pub enter_delay_ms: f64, + pub leave_delay_ms: f64, + pub phase: HoverPhase, +} + +impl Default for HoverController { + fn default() -> Self { + Self::new(HOVER_ENTER_DELAY_MS, HOVER_LEAVE_DELAY_MS) + } +} + +impl HoverController { + pub const fn new(enter_delay_ms: f64, leave_delay_ms: f64) -> Self { + Self { + enter_delay_ms, + leave_delay_ms, + phase: HoverPhase::Idle, + } + } + + /// Currently visible target (during `Open` or `Leaving` grace window). + pub fn active_target(&self) -> Option<&T> { + match &self.phase { + HoverPhase::Open { target, .. } | HoverPhase::Leaving { target, .. } => Some(target), + HoverPhase::Idle | HoverPhase::Entering { .. } => None, + } + } + + /// Pending target waiting for `enter_delay_ms`. + pub fn entering_target(&self) -> Option<&T> { + match &self.phase { + HoverPhase::Entering { target, .. } => Some(target), + _ => None, + } + } + + /// Next scheduler deadline (`ms`) when `tick` will transition state, if any. + pub fn next_deadline_ms(&self) -> Option { + match &self.phase { + HoverPhase::Entering { since_ms, .. } => Some(since_ms + self.enter_delay_ms), + HoverPhase::Leaving { leave_since_ms, .. } => { + Some(leave_since_ms + self.leave_delay_ms) + } + HoverPhase::Idle | HoverPhase::Open { .. } => None, + } + } + + /// Immediately reset to `Idle`. + pub fn reset(&mut self) -> bool { + let was_idle = matches!(self.phase, HoverPhase::Idle); + self.phase = HoverPhase::Idle; + !was_idle + } + + /// Pointer is hovering over the open floating surface or its safe bridge: cancel any pending leave. + pub fn keep_open(&mut self) -> bool { + if let HoverPhase::Leaving { + target, opened_ms, .. + } = std::mem::replace(&mut self.phase, HoverPhase::Idle) + { + self.phase = HoverPhase::Open { target, opened_ms }; + return true; + } + false + } + + /// Pointer left both target and floating surface: begin the `leave_delay_ms` grace window. + pub fn on_leave(&mut self, now_ms: f64) -> bool { + match std::mem::replace(&mut self.phase, HoverPhase::Idle) { + HoverPhase::Idle => false, + HoverPhase::Entering { .. } => true, + HoverPhase::Open { target, opened_ms } => { + self.phase = HoverPhase::Leaving { + target, + opened_ms, + leave_since_ms: now_ms, + }; + true + } + leaving @ HoverPhase::Leaving { .. } => { + self.phase = leaving; + false + } + } + } + + /// Advance state machine at `now_ms`. Returns `true` if visibility changed. + pub fn tick(&mut self, now_ms: f64) -> bool { + match std::mem::replace(&mut self.phase, HoverPhase::Idle) { + HoverPhase::Entering { target, since_ms } => { + if now_ms >= since_ms + self.enter_delay_ms { + self.phase = HoverPhase::Open { + target, + opened_ms: now_ms, + }; + true + } else { + self.phase = HoverPhase::Entering { target, since_ms }; + false + } + } + HoverPhase::Leaving { + target, + opened_ms, + leave_since_ms, + } => { + if now_ms >= leave_since_ms + self.leave_delay_ms { + self.phase = HoverPhase::Idle; + true + } else { + self.phase = HoverPhase::Leaving { + target, + opened_ms, + leave_since_ms, + }; + false + } + } + other => { + self.phase = other; + false + } + } + } +} + +impl HoverController { + /// Pointer entered or remains over `target`. + pub fn on_hover(&mut self, target: T, now_ms: f64) -> bool { + match &mut self.phase { + HoverPhase::Open { target: cur, .. } if *cur == target => false, + HoverPhase::Entering { target: cur, .. } if *cur == target => false, + HoverPhase::Leaving { + target: cur, + opened_ms, + .. + } if *cur == target => { + let opened = *opened_ms; + self.phase = HoverPhase::Open { + target, + opened_ms: opened, + }; + true + } + HoverPhase::Open { .. } | HoverPhase::Leaving { .. } => { + self.phase = HoverPhase::Entering { + target, + since_ms: now_ms, + }; + true + } + HoverPhase::Idle | HoverPhase::Entering { .. } => { + self.phase = HoverPhase::Entering { + target, + since_ms: now_ms, + }; + true + } + } + } +} + +/// True when `(x, y)` lies inside `surface`, `anchor`, or the safe corridor bridging them. +pub fn safe_bridge_contains(surface: FlowRect, anchor: FlowRect, x: f32, y: f32) -> bool { + let pad = 10.0; + let expanded = FlowRect::new( + surface.x - pad, + surface.y - pad, + surface.w + 2.0 * pad, + surface.h + 2.0 * pad, + ); + if expanded.contains(x, y) || anchor.contains(x, y) { + return true; + } + let bridge_top = anchor.y.min(surface.y) - 4.0; + let bridge_bottom = anchor.bottom().max(surface.bottom()) + 4.0; + let bridge_left = anchor.x.min(surface.x) - 4.0; + let bridge_right = anchor.right().max(surface.right()) + 4.0; + x >= bridge_left && x <= bridge_right && y >= bridge_top && y <= bridge_bottom +} + +impl Overlays { + /// Update the desktop 500 ms enter / 250 ms leave Image inner-toolbar hover controller + /// and Simple Table hover state on pointer move. + pub(crate) fn sync_hover_affordances( + &mut self, + scene: &OverlayScene<'_>, + x: f32, + y: f32, + now_ms: f64, + ) -> bool { + let mut changed = false; + let is_desktop = !scene.is_touch && scene.form_factor == FormFactor::Desktop; + if !is_desktop || scene.page_readonly { + return false; + } + if self + .hovered_tooltip + .as_ref() + .is_some_and(|tip| !tip.anchor_screen.contains(x, y)) + { + self.hovered_tooltip = None; + changed = true; + } + let on_img_bar = self.image_toolbar_rect.is_some_and(|r| r.contains(x, y)) + || self.image_submenu_rect.is_some_and(|r| r.contains(x, y)); + if on_img_bar { + changed |= self.image_hover.keep_open(); + } else { + let (wx, wy) = scene.screen_to_world(x, y); + let hit_img = scene.layout.blocks.iter().find_map(|b| { + if b.body.kind != FlowKind::Image { + return None; + } + let local = b.body.image_box()?; + let world = local.translated(b.x, b.y); + world.contains(wx, wy).then(|| b.block_id.clone()) + }); + match hit_img { + Some(bid) => changed |= self.image_hover.on_hover(bid, now_ms), + None => changed |= self.image_hover.on_leave(now_ms), + } + } + + if self.table_hover.add_drag.is_none() { + let (wx, wy) = scene.screen_to_world(x, y); + let hit_table = scene.layout.blocks.iter().find_map(|b| { + if b.body.kind != FlowKind::Table { + return None; + } + let r = b.rect(); + let expanded = FlowRect::new(r.x - 24.0, r.y - 22.0, r.w + 48.0, r.h + 44.0); + if !expanded.contains(wx, wy) { + return None; + } + let scroll_x = self.code_scroll_x(&b.block_id); + let lx = wx - b.x + scroll_x; + let ly = wy - b.y; + let cell = b + .body + .table_cells + .iter() + .find(|c| c.rect.contains(lx, ly)) + .or_else(|| { + b.body.table_cells.iter().min_by(|a, c| { + let da = (a.rect.x + a.rect.w * 0.5 - lx) + .hypot(a.rect.y + a.rect.h * 0.5 - ly); + let dc = (c.rect.x + c.rect.w * 0.5 - lx) + .hypot(c.rect.y + c.rect.h * 0.5 - ly); + da.total_cmp(&dc) + }) + }); + Some(( + b.block_id.clone(), + cell.map(|c| c.row_id.clone()), + cell.map(|c| c.column_id.clone()), + )) + }); + match hit_table { + Some((bid, rid, cid)) => { + if self.table_hover.block_id.as_deref() != Some(bid.as_str()) { + self.table_hover.hover_since_ms = now_ms; + changed = true; + } + if self.table_hover.row_id != rid || self.table_hover.column_id != cid { + changed = true; + } + self.table_hover.block_id = Some(bid); + self.table_hover.row_id = rid; + self.table_hover.column_id = cid; + } + None if self.table_hover.block_id.is_some() => { + self.table_hover = TableHoverState::default(); + changed = true; + } + None => {} + } + } + changed + } +} diff --git a/blocksuite/crates/editor/src/overlays/toolbar_chrome/icons.rs b/blocksuite/crates/editor/src/overlays/toolbar_chrome/icons.rs new file mode 100644 index 0000000000..f9fb1f6359 --- /dev/null +++ b/blocksuite/crates/editor/src/overlays/toolbar_chrome/icons.rs @@ -0,0 +1,366 @@ +//! Custom vector icons for `ToolbarChrome` items not present in `ui-tokens/icons.rs`. +//! +//! All glyphs author against a 20 × 20 logical viewBox and scale cleanly to any `side`. + +use ui::{ + AnyElement, Bounds, FontWeight, Hsla, PathBuilder, Pixels, Window, canvas, div, fill, point, + prelude::*, px, size, +}; + +/// Vector icon rendered locally by `ToolbarChrome`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum ChromeIcon { + MoreVertical, + Caption, + Bookmark, + Download, + DatabaseTable, + Palette, + Smile, + OpenInNew, + Edit, + Unlink, + ChevronDown, +} + +fn pt(origin_x: Pixels, origin_y: Pixels, s: f32, x: f32, y: f32) -> ui::Point { + point(origin_x + px(x * s), origin_y + px(y * s)) +} + +fn rect_fill( + window: &mut Window, + origin_x: Pixels, + origin_y: Pixels, + s: f32, + x: f32, + y: f32, + w: f32, + h: f32, + radius: f32, + color: Hsla, +) { + let b = Bounds::new( + point(origin_x + px(x * s), origin_y + px(y * s)), + size(px(w * s), px(h * s)), + ); + window.paint_quad(fill(b, color).corner_radii(px(radius * s))); +} + +fn stroke_poly( + window: &mut Window, + origin_x: Pixels, + origin_y: Pixels, + s: f32, + pts: &[(f32, f32)], + width: f32, + closed: bool, + color: Hsla, +) { + if pts.len() < 2 { + return; + } + let mut pb = PathBuilder::stroke(px((width * s).max(1.0))); + pb.move_to(pt(origin_x, origin_y, s, pts[0].0, pts[0].1)); + for &(x, y) in &pts[1..] { + pb.line_to(pt(origin_x, origin_y, s, x, y)); + } + if closed { + pb.close(); + } + if let Ok(path) = pb.build() { + window.paint_path(path, color); + } +} + +/// Paint a `ChromeIcon` inside a fixed `side × side` element. +pub fn chrome_icon(kind: ChromeIcon, side: f32, color: Hsla) -> AnyElement { + canvas( + |_, _, _| (), + move |bounds, _, window, _| { + let ox = bounds.origin.x; + let oy = bounds.origin.y; + let s = side / 20.0; + match kind { + ChromeIcon::MoreVertical => { + for cy in [5.0, 10.0, 15.0] { + rect_fill(window, ox, oy, s, 8.75, cy - 1.25, 2.5, 2.5, 1.25, color); + } + } + ChromeIcon::Caption => { + stroke_poly( + window, + ox, + oy, + s, + &[(3.5, 4.0), (16.5, 4.0), (16.5, 11.5), (3.5, 11.5)], + 1.4, + true, + color, + ); + rect_fill(window, ox, oy, s, 4.0, 14.0, 12.0, 1.5, 0.75, color); + rect_fill(window, ox, oy, s, 6.5, 16.8, 7.0, 1.5, 0.75, color); + } + ChromeIcon::Bookmark => { + stroke_poly( + window, + ox, + oy, + s, + &[ + (5.0, 3.5), + (15.0, 3.5), + (15.0, 16.8), + (10.0, 13.4), + (5.0, 16.8), + ], + 1.45, + true, + color, + ); + } + ChromeIcon::Download => { + stroke_poly( + window, + ox, + oy, + s, + &[(10.0, 3.5), (10.0, 13.0)], + 1.5, + false, + color, + ); + stroke_poly( + window, + ox, + oy, + s, + &[(6.5, 9.8), (10.0, 13.3), (13.5, 9.8)], + 1.5, + false, + color, + ); + stroke_poly( + window, + ox, + oy, + s, + &[(4.0, 13.5), (4.0, 16.5), (16.0, 16.5), (16.0, 13.5)], + 1.5, + false, + color, + ); + } + ChromeIcon::DatabaseTable => { + stroke_poly( + window, + ox, + oy, + s, + &[(3.0, 4.0), (17.0, 4.0), (17.0, 16.0), (3.0, 16.0)], + 1.4, + true, + color, + ); + rect_fill(window, ox, oy, s, 3.2, 7.6, 13.6, 1.3, 0.0, color); + rect_fill(window, ox, oy, s, 3.2, 11.6, 13.6, 1.2, 0.0, color); + rect_fill(window, ox, oy, s, 8.2, 4.2, 1.2, 11.6, 0.0, color); + rect_fill(window, ox, oy, s, 12.6, 4.2, 1.2, 11.6, 0.0, color); + } + ChromeIcon::Palette => { + stroke_poly( + window, + ox, + oy, + s, + &[ + (10.0, 3.2), + (14.6, 4.6), + (16.8, 8.8), + (15.6, 12.6), + (12.8, 12.8), + (12.2, 14.8), + (10.0, 16.8), + (5.4, 15.4), + (3.2, 10.2), + (5.2, 5.0), + ], + 1.4, + true, + color, + ); + for (dx, dy) in [(7.2, 8.2), (10.2, 6.4), (13.0, 8.2), (7.6, 11.8)] { + rect_fill(window, ox, oy, s, dx - 1.0, dy - 1.0, 2.0, 2.0, 1.0, color); + } + } + ChromeIcon::Smile => { + stroke_poly( + window, + ox, + oy, + s, + &[ + (10.0, 3.2), + (14.5, 4.8), + (16.8, 10.0), + (14.5, 15.2), + (10.0, 16.8), + (5.5, 15.2), + (3.2, 10.0), + (5.5, 4.8), + ], + 1.4, + true, + color, + ); + rect_fill(window, ox, oy, s, 6.8, 7.5, 1.8, 1.8, 0.9, color); + rect_fill(window, ox, oy, s, 11.4, 7.5, 1.8, 1.8, 0.9, color); + stroke_poly( + window, + ox, + oy, + s, + &[(6.8, 11.8), (8.4, 13.4), (11.6, 13.4), (13.2, 11.8)], + 1.35, + false, + color, + ); + } + ChromeIcon::OpenInNew => { + stroke_poly( + window, + ox, + oy, + s, + &[ + (11.0, 4.5), + (4.5, 4.5), + (4.5, 15.5), + (15.5, 15.5), + (15.5, 9.0), + ], + 1.4, + false, + color, + ); + stroke_poly( + window, + ox, + oy, + s, + &[(10.0, 10.0), (16.0, 4.0)], + 1.45, + false, + color, + ); + stroke_poly( + window, + ox, + oy, + s, + &[(12.2, 4.0), (16.0, 4.0), (16.0, 7.8)], + 1.45, + false, + color, + ); + } + ChromeIcon::Edit => { + stroke_poly( + window, + ox, + oy, + s, + &[ + (4.0, 16.0), + (4.8, 12.2), + (13.4, 3.6), + (16.4, 6.6), + (7.8, 15.2), + ], + 1.4, + true, + color, + ); + stroke_poly( + window, + ox, + oy, + s, + &[(11.5, 5.5), (14.5, 8.5)], + 1.3, + false, + color, + ); + } + ChromeIcon::Unlink => { + stroke_poly( + window, + ox, + oy, + s, + &[(8.5, 11.5), (6.0, 14.0), (4.2, 12.2), (6.7, 9.7)], + 1.45, + false, + color, + ); + stroke_poly( + window, + ox, + oy, + s, + &[(11.5, 8.5), (14.0, 6.0), (15.8, 7.8), (13.3, 10.3)], + 1.45, + false, + color, + ); + stroke_poly( + window, + ox, + oy, + s, + &[(4.5, 4.5), (15.5, 15.5)], + 1.45, + false, + color, + ); + } + ChromeIcon::ChevronDown => { + stroke_poly( + window, + ox, + oy, + s, + &[(6.0, 8.0), (10.0, 12.2), (14.0, 8.0)], + 1.55, + false, + color, + ); + } + } + }, + ) + .flex_none() + .w(px(side)) + .h(px(side)) + .into_any_element() +} + +/// Duotone `A` badge used in Highlight and Callout color menus (`20 × 20`, radius `4`). +pub fn duotone_text_badge(fg: Hsla, bg: Option, border: Hsla) -> AnyElement { + div() + .flex_none() + .w(px(20.0)) + .h(px(20.0)) + .rounded(px(4.0)) + .when_some(bg, |el, fill_col| el.bg(fill_col)) + .border_1() + .border_color(border) + .flex() + .items_center() + .justify_center() + .text_size(px(12.0)) + .line_height(px(12.0)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(fg) + .child("A") + .into_any_element() +} diff --git a/blocksuite/crates/editor/src/overlays/toolbar_chrome/mod.rs b/blocksuite/crates/editor/src/overlays/toolbar_chrome/mod.rs new file mode 100644 index 0000000000..61706e36f6 --- /dev/null +++ b/blocksuite/crates/editor/src/overlays/toolbar_chrome/mod.rs @@ -0,0 +1,523 @@ +//! Shared floating toolbar chrome (`ToolbarChrome`), hover `Tooltip`, and deterministic +//! scheduler-clock `HoverController` (500 ms enter / 250 ms leave + safe bridge). +//! +//! Aligns Page and block toolbars with BlockSuite `0.27.5` ``, +//! ``, ``, and `whenHover`. + +mod hover; +mod icons; + +pub use hover::{HoverController, HoverPhase, safe_bridge_contains}; +pub use icons::{ChromeIcon, chrome_icon, duotone_text_badge}; + +use ui::{ + AnyElement, ClickEvent, Context, Div, FontWeight, Hsla, MouseButton, MouseDownEvent, + MouseMoveEvent, ParentElement, SharedString, Stateful, div, prelude::*, px, +}; + +use crate::{ + block_flow::FlowRect, + theme::{Palette, TYPOGRAPHY}, +}; + +use super::{ + OverlayEvent, OverlayHost, OverlayScene, Overlays, POPOVER_EDGE_MARGIN, Placement, emit, place, + place_popover, +}; + +/// Content-box height of a desktop floating toolbar (`36px` + `0.5px` border). +pub const TOOLBAR_CHROME_HEIGHT: f32 = 36.0; +/// Horizontal padding inside a desktop floating toolbar (`0 6px`). +pub const TOOLBAR_CHROME_PX: f32 = 6.0; +/// Flex gap between top-level items/groups inside a desktop floating toolbar (`8px`). +pub const TOOLBAR_CHROME_GAP: f32 = 8.0; +/// Corner radius of a desktop floating toolbar (`8px`). +pub const TOOLBAR_CHROME_RADIUS: f32 = 8.0; +/// Hairline border thickness (`0.5px` `layer/insideBorder/border`). +pub const TOOLBAR_CHROME_BORDER: f32 = 0.5; +/// Desktop icon button footprint (`24 × 24`, radius `4px`). +pub const TOOLBAR_CHROME_BTN: f32 = 24.0; +/// Desktop icon size inside a `24 × 24` button (`20px`). +pub const TOOLBAR_CHROME_ICON: f32 = 20.0; +/// Desktop button corner radius (`4px`). +pub const TOOLBAR_CHROME_BTN_RADIUS: f32 = 4.0; +/// Offset from anchor to floating toolbar (`10px`). +pub const TOOLBAR_CHROME_OFFSET: f32 = 10.0; +/// Width of the full-height separator slot (`4px`, containing a `0.5px` line). +pub const TOOLBAR_SEP_SLOT: f32 = 4.0; +/// Dropdown menu panel padding (`8px`). +pub const TOOLBAR_MENU_PADDING: f32 = 8.0; +/// Dropdown menu minimum width (`176px`). +pub const TOOLBAR_MENU_MIN_W: f32 = 176.0; +/// Dropdown menu row height (`30px`). +pub const TOOLBAR_MENU_ROW_H: f32 = 30.0; +/// Dropdown menu icon size (`20px`). +pub const TOOLBAR_MENU_ICON: f32 = 20.0; +/// Tooltip offset above its anchor button (`8px`). +pub const TOOLTIP_OFFSET: f32 = 8.0; +/// Hover enter delay before opening hover-triggered surfaces (`500ms`). +pub const HOVER_ENTER_DELAY_MS: f64 = 500.0; +/// Hover leave delay before closing hover-triggered surfaces (`250ms`). +pub const HOVER_LEAVE_DELAY_MS: f64 = 250.0; + +/// Visual variant of a toolbar dropdown menu item. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum MenuActionVariant { + #[default] + Normal, + /// Neutral at rest; hover applies `--affine-background-error-color` + `--affine-error-color`. + Destructive, +} + +/// Active hover tooltip shown above a toolbar button (`8px` offset, `top`). +#[derive(Clone, Debug, PartialEq)] +pub struct ToolbarTooltip { + pub label: String, + pub anchor_screen: FlowRect, +} + +/// Active dropdown submenu on a block or inline toolbar (`ToolbarChrome` single-open invariant). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum BlockToolbarSubmenu { + ImageMore(String), + BookmarkView(String), + BookmarkStyle(String), + BookmarkMore(String), + CalloutColor(String), + CalloutMore(String), + EmbedView(String), + EmbedStyle(String), + EmbedMore(String), + LinkPopupView, + LinkPopupMore, +} + +/// Hairline border color (`--affine-v2-layer-insideBorder-border`). +pub fn chrome_border_color(palette: &Palette) -> Hsla { + palette + .theme + .css_var("--affine-v2-layer-insideBorder-border") + .unwrap_or(palette.border) +} + +/// Panel fill color (`--affine-v2-layer-background-overlayPanel`). +pub fn chrome_panel_bg(palette: &Palette) -> Hsla { + palette + .theme + .css_var("--affine-v2-layer-background-overlayPanel") + .unwrap_or(palette.panel) +} + +/// Primary outer selection ring color (`--affine-v2-layer-insideBorder-primaryBorder`). +pub fn chrome_primary_border(palette: &Palette) -> Hsla { + palette + .theme + .css_var("--affine-v2-layer-insideBorder-primaryBorder") + .unwrap_or(palette.brand) +} + +/// Destructive hover background (`--affine-background-error-color`). +pub fn chrome_error_bg(palette: &Palette) -> Hsla { + palette + .theme + .css_var("--affine-background-error-color") + .unwrap_or(palette.hover) +} + +/// Destructive hover foreground (`--affine-error-color`). +pub fn chrome_error_fg(palette: &Palette) -> Hsla { + palette + .theme + .css_var("--affine-error-color") + .unwrap_or(palette.text_primary) +} + +/// Link preview color (`--affine-link-color`). +pub fn chrome_link_color(palette: &Palette) -> Hsla { + palette + .theme + .css_var("--affine-link-color") + .unwrap_or(palette.brand) +} + +/// Build the shared desktop floating toolbar container (`h = 36`, `px = 6`, `gap = 8`, `radius = 8`, +/// `0.5px` insideBorder, `--affine-overlay-shadow`). +pub fn toolbar_chrome_container( + id: impl Into, + rect: FlowRect, + progress: f32, + interactive: bool, + snapshot_id: impl Into, + palette: &Palette, +) -> Stateful
{ + let mut root = place(rect) + .id(id.into()) + .px(px(TOOLBAR_CHROME_PX)) + .rounded(px(TOOLBAR_CHROME_RADIUS)) + .bg(chrome_panel_bg(palette)) + .border(px(TOOLBAR_CHROME_BORDER)) + .border_color(chrome_border_color(palette)) + .shadow(palette.theme.shadows("--affine-overlay-shadow").into()) + .flex() + .items_center() + .gap(px(TOOLBAR_CHROME_GAP)) + .opacity(progress) + .snapshot(snapshot_id.into(), Some("root.canvas")) + .snapshot_focused(interactive); + if interactive { + root = root + .block_mouse_except_scroll() + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()); + } + root +} + +/// Full-height `0.5px` vertical separator inside a `4px` slot, automatically placed between +/// top-level action groups. +pub fn toolbar_separator(palette: &Palette) -> AnyElement { + div() + .flex_none() + .w(px(TOOLBAR_SEP_SLOT)) + .h(px(TOOLBAR_CHROME_HEIGHT)) + .flex() + .items_center() + .justify_center() + .child( + div() + .w(px(0.5)) + .h(px(TOOLBAR_CHROME_HEIGHT)) + .bg(palette.border), + ) + .into_any_element() +} + +/// Horizontal `0.5px` separator between groups inside a dropdown menu. +pub fn menu_horizontal_separator(palette: &Palette) -> AnyElement { + div() + .flex_none() + .w_full() + .py(px(4.0)) + .child(div().w_full().h(px(0.5)).bg(palette.border)) + .into_any_element() +} + +/// Append grouped children to a toolbar container, inserting `toolbar_separator` automatically +/// between every non-empty group. +pub fn append_toolbar_groups( + mut container: P, + groups: Vec>, + palette: &Palette, +) -> P { + let mut first = true; + for group in groups { + if group.is_empty() { + continue; + } + if !first { + container = container.child(toolbar_separator(palette)); + } + first = false; + if group.len() == 1 { + if let Some(el) = group.into_iter().next() { + container = container.child(el); + } + } else { + let mut row = div().flex_none().flex().items_center().gap(px(4.0)); + for el in group { + row = row.child(el); + } + container = container.child(row); + } + } + container +} + +/// Build a standard `24 × 24` desktop toolbar icon button (radius `4`, hover `--affine-hover-color`, +/// active = icon `--affine-primary-color` with **no** background wash, hover tooltip, click on release). +#[allow(clippy::too_many_arguments)] +pub fn toolbar_icon_button( + id: impl Into, + snap_id: impl Into, + snap_parent: &'static str, + tooltip: &'static str, + anchor_screen: FlowRect, + active: bool, + interactive: bool, + content: AnyElement, + on_click_event: OverlayEvent, + palette: &Palette, + cx: &mut Context, +) -> AnyElement { + let hover = palette.hover; + let tip = ToolbarTooltip { + label: tooltip.to_string(), + anchor_screen, + }; + let mut btn = div() + .id(id.into()) + .flex_none() + .w(px(TOOLBAR_CHROME_BTN)) + .h(px(TOOLBAR_CHROME_BTN)) + .rounded(px(TOOLBAR_CHROME_BTN_RADIUS)) + .flex() + .items_center() + .justify_center() + .snapshot(snap_id.into(), Some(snap_parent)) + .snapshot_focused(active) + .snapshot_text(tooltip) + .child(content); + if interactive { + btn = btn + .cursor_pointer() + .hover(move |s| s.bg(hover)) + .on_mouse_move(emit(cx, move |_: &MouseMoveEvent| { + OverlayEvent::SetToolbarTooltip(Some(tip.clone())) + })) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(emit(cx, move |_: &ClickEvent| on_click_event.clone())); + } + btn.into_any_element() +} + +/// Build a shared dropdown menu panel (`padding = 8`, `min-w = 176`, `radius = 8`, +/// `0.5px` border, `--affine-overlay-shadow`). +pub fn toolbar_dropdown_panel( + id: impl Into, + rect: FlowRect, + progress: f32, + interactive: bool, + snap_id: impl Into, + snap_parent: &'static str, + palette: &Palette, +) -> Stateful
{ + let mut panel = place(rect) + .id(id.into()) + .flex() + .flex_col() + .p(px(TOOLBAR_MENU_PADDING)) + .rounded(px(TOOLBAR_CHROME_RADIUS)) + .bg(chrome_panel_bg(palette)) + .border(px(TOOLBAR_CHROME_BORDER)) + .border_color(chrome_border_color(palette)) + .shadow(palette.theme.shadows("--affine-overlay-shadow").into()) + .overflow_hidden() + .opacity(progress) + .snapshot(snap_id.into(), Some(snap_parent)) + .snapshot_focused(interactive); + if interactive { + panel = panel + .occlude() + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()); + } + panel +} + +/// Close the open block toolbar submenu on a press outside `panel` and its toolbar `bar`. A +/// press on the toolbar is left to its toggle buttons. +pub fn dismiss_submenu_outside( + panel: Stateful
, + bar: FlowRect, + cx: &mut Context, +) -> Stateful
{ + panel.on_mouse_down_out(cx.listener(move |view, ev: &MouseDownEvent, window, cx| { + if !bar.contains(f32::from(ev.position.x), f32::from(ev.position.y)) { + view.dispatch_overlay(OverlayEvent::CloseBlockSubmenu, window, cx); + } + })) +} + +impl Overlays { + /// Close the open toolbar submenu and its tooltip. Returns whether a submenu was open. + pub fn close_block_submenu(&mut self) -> bool { + self.hovered_tooltip = None; + self.block_submenu.take().is_some() + } + + /// Close the open toolbar submenu once the toolbar that owns it is no longer shown. + pub(super) fn retain_block_submenu(&mut self, scene: &OverlayScene<'_>) { + use BlockToolbarSubmenu as S; + let shown = match &self.block_submenu { + None => return, + Some(S::ImageMore(id)) => { + scene.selected_image_block == Some(id.as_str()) + || self.image_hover.active_target() == Some(id) + } + Some(S::BookmarkView(id) | S::BookmarkStyle(id) | S::BookmarkMore(id)) => { + scene.selected_bookmark_block == Some(id.as_str()) + } + Some(S::CalloutColor(id) | S::CalloutMore(id)) => { + scene.selected_callout_block == Some(id.as_str()) + } + Some(S::EmbedView(id) | S::EmbedStyle(id) | S::EmbedMore(id)) => { + scene.selected_embed_block == Some(id.as_str()) + } + Some(S::LinkPopupView | S::LinkPopupMore) => self.link_popup.is_some(), + }; + if !shown { + self.close_block_submenu(); + } + } +} + +/// Build a single dropdown menu row (`min-h = 30`, `px = 8`, `gap = 8`, `20px` icon, `font-sm`). +/// +/// `MenuActionVariant::Destructive` stays neutral at rest and switches to +/// `--affine-background-error-color` + `--affine-error-color` on hover. +#[allow(clippy::too_many_arguments)] +pub fn toolbar_menu_row( + id: impl Into, + snap_id: impl Into, + snap_parent: &'static str, + label: impl Into, + leading: AnyElement, + selected: bool, + variant: MenuActionVariant, + interactive: bool, + on_click_event: OverlayEvent, + palette: &Palette, + cx: &mut Context, +) -> AnyElement { + let label_str: SharedString = label.into(); + let hover_bg = match variant { + MenuActionVariant::Normal => palette.hover, + MenuActionVariant::Destructive => chrome_error_bg(palette), + }; + let hover_fg = match variant { + MenuActionVariant::Normal => palette.text_primary, + MenuActionVariant::Destructive => chrome_error_fg(palette), + }; + let mut row = div() + .id(id.into()) + .flex_none() + .w_full() + .h(px(TOOLBAR_MENU_ROW_H)) + .px(px(8.0)) + .rounded(px(TOOLBAR_CHROME_BTN_RADIUS)) + .flex() + .items_center() + .gap(px(8.0)) + .text_size(px(TYPOGRAPHY.font_sm_px)) + .text_color(palette.text_primary) + .when(selected, |el| el.bg(palette.hover)) + .snapshot(snap_id.into(), Some(snap_parent)) + .snapshot_focused(selected) + .snapshot_text(label_str.clone()) + .child(leading) + .child(label_str); + if interactive { + row = row + .cursor_pointer() + .hover(move |s| s.bg(hover_bg).text_color(hover_fg)) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(emit(cx, move |_: &ClickEvent| on_click_event.clone())); + } + row.into_any_element() +} + +/// Render a hover tooltip above `tooltip.anchor_screen` (`8px` offset, `Placement::Above`). +pub fn render_toolbar_tooltip( + tooltip: &ToolbarTooltip, + viewport: FlowRect, + palette: &Palette, +) -> AnyElement { + let est_w = (tooltip.label.chars().count() as f32 * 6.8 + 16.0).clamp(40.0, 220.0); + let h = 24.0_f32; + let placed = place_popover( + tooltip.anchor_screen, + (est_w, h), + viewport, + Placement::Above, + TOOLTIP_OFFSET, + POPOVER_EDGE_MARGIN, + ); + let bg = palette + .theme + .css_var("--affine-tooltip") + .unwrap_or(palette.text_primary); + let fg = palette + .theme + .css_var("--affine-pure-white") + .unwrap_or(palette.panel); + place(placed.rect) + .id("toolbar-tooltip") + .px(px(8.0)) + .rounded(px(4.0)) + .bg(bg) + .flex() + .items_center() + .justify_center() + .text_size(px(TYPOGRAPHY.font_xs_px)) + .font_weight(FontWeight::MEDIUM) + .text_color(fg) + .snapshot("overlay.toolbar_tooltip", Some("root.canvas")) + .snapshot_text(tooltip.label.clone()) + .child(tooltip.label.clone()) + .into_any_element() +} + +/// Extract hostname-only preview for bookmark/embed link chips (`https://www.affine.pro/docs` -> `affine.pro`). +pub fn hostname_preview(url: &str) -> String { + let trimmed = url.trim(); + let without_scheme = trimmed + .strip_prefix("https://") + .or_else(|| trimmed.strip_prefix("http://")) + .unwrap_or(trimmed); + let host = without_scheme + .split(['/', '?', '#']) + .next() + .unwrap_or(without_scheme); + let clean = host.strip_prefix("www.").unwrap_or(host); + if clean.is_empty() { + trimmed.to_string() + } else { + clean.to_string() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hover_controller_enter_500ms_leave_250ms_and_bridge_cancel() { + let mut ctrl = HoverController::::default(); + assert_eq!(ctrl.active_target(), None); + + assert!(ctrl.on_hover("img-1".into(), 100.0)); + assert_eq!(ctrl.next_deadline_ms(), Some(600.0)); + assert!(!ctrl.tick(599.0)); + assert_eq!(ctrl.active_target(), None); + + assert!(ctrl.tick(600.0)); + assert_eq!(ctrl.active_target().map(String::as_str), Some("img-1")); + assert_eq!(ctrl.next_deadline_ms(), None); + + // Leaving starts a 250 ms grace window while remaining visible. + assert!(ctrl.on_leave(700.0)); + assert_eq!(ctrl.active_target().map(String::as_str), Some("img-1")); + assert_eq!(ctrl.next_deadline_ms(), Some(950.0)); + + // Moving onto the surface or bridge cancels the pending leave. + assert!(ctrl.keep_open()); + assert_eq!(ctrl.next_deadline_ms(), None); + assert_eq!(ctrl.active_target().map(String::as_str), Some("img-1")); + + // Leaving again closes after 250 ms. + assert!(ctrl.on_leave(1000.0)); + assert!(!ctrl.tick(1249.0)); + assert_eq!(ctrl.active_target().map(String::as_str), Some("img-1")); + assert!(ctrl.tick(1250.0)); + assert_eq!(ctrl.active_target(), None); + } + + #[test] + fn hostname_preview_strips_scheme_www_and_path() { + for (input, expected) in [ + ("https://www.affine.pro/docs/guide?x=1", "affine.pro"), + ("http://github.com/toeverything/AFFiNE", "github.com"), + ("https://example.org", "example.org"), + ] { + assert_eq!(hostname_preview(input), expected, "input={input}"); + } + } +} diff --git a/blocksuite/crates/playground/Cargo.toml b/blocksuite/crates/playground/Cargo.toml index e99aff1305..8d182ee377 100644 --- a/blocksuite/crates/playground/Cargo.toml +++ b/blocksuite/crates/playground/Cargo.toml @@ -67,6 +67,7 @@ web-sys = { workspace = true, features = [ "Element", "HtmlAnchorElement", "HtmlCanvasElement", + "HtmlElement", "Location", "MessageEvent", "RequestInit", diff --git a/blocksuite/crates/playground/src/bin/bs_harness/states.rs b/blocksuite/crates/playground/src/bin/bs_harness/states.rs index a7e4d56986..e6c5d7e44a 100644 --- a/blocksuite/crates/playground/src/bin/bs_harness/states.rs +++ b/blocksuite/crates/playground/src/bin/bs_harness/states.rs @@ -131,7 +131,7 @@ impl OverlayState { Self::FormatToolbarOpen | Self::FormatToolbarFlippedTop => &[ "overlay.format_toolbar", "overlay.format_toolbar.bold", - "overlay.format_toolbar.align_right", + "overlay.format_toolbar.align", ], Self::FormatToolbarLink => &[ "overlay.format_toolbar", diff --git a/blocksuite/crates/playground/src/edgeless/edgeless_canvas_media_tests.rs b/blocksuite/crates/playground/src/edgeless/edgeless_canvas_media_tests.rs index 4b80d6ab71..d1e7400d5c 100644 --- a/blocksuite/crates/playground/src/edgeless/edgeless_canvas_media_tests.rs +++ b/blocksuite/crates/playground/src/edgeless/edgeless_canvas_media_tests.rs @@ -634,3 +634,141 @@ fn z_order_at_the_end_of_its_stream_writes_nothing() { .unwrap(); } } + +#[test] +fn canvas_media_download_requires_host_channel_and_cached_bytes() { + let (platform, app, win, hw) = start_edgeless_toolbar_view(); + let png: Vec = { + let mut buf = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([0x10, 0x80, 0xEE, 0xFF])) + .write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png) + .unwrap(); + buf + }; + let doc_bytes = b"hello-attachment".to_vec(); + + app.update(|cx| { + win.update(cx, |v, _, cx| { + v.set_edgeless_camera(0.0, 0.0, 1.0, cx); + let commit = v + .page_mut() + .unwrap() + .structural_edit(320, |page| { + page.add_block( + "img-dl", + BlockSpec::Image { + source_id: "img-dl-blob".into(), + width: 140.0, + height: 120.0, + caption: "Sketch".into(), + xywh: None, + }, + Some("surf"), + None, + 320, + )?; + page.set_block_xywh("img-dl", [200.0, 260.0, 140.0, 120.0], 320)?; + page.set_block_index("img-dl", "b2", 320)?; + page.add_block( + "att-dl", + BlockSpec::Attachment { + name: "spec.txt".into(), + size: doc_bytes.len() as i64, + mime_type: "text/plain".into(), + source_id: "att-dl-blob".into(), + caption: String::new(), + embed: false, + }, + Some("surf"), + None, + 320, + )?; + page.set_block_xywh("att-dl", [420.0, 260.0, 260.0, 88.0], 320)?; + page.set_block_index("att-dl", "b3", 320)?; + Ok(()) + }) + .unwrap() + .unwrap(); + v.did_edgeless_doc_commit(commit, cx); + }) + }) + .unwrap(); + + // (block_id, source_id, payload, filename, mime_type) + let targets = [ + ("img-dl", "img-dl-blob", &png, "Sketch.png", "image/png"), + ( + "att-dl", + "att-dl-blob", + &doc_bytes, + "spec.txt", + "text/plain", + ), + ]; + // (label, has_callback, has_bytes, expect_deliver) + let scenarios = [ + ("missing_callback", false, true, false), + ("missing_bytes", true, false, false), + ("channel_and_bytes", true, true, true), + ]; + + for (block_id, source_id, payload, expected_name, expected_mime) in targets { + for (label, has_callback, has_bytes, expect_deliver) in scenarios { + let received = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let sink = received.clone(); + app.update(|cx| { + win.update(cx, |v, _, cx| { + v.state.blobs.remove(source_id); + if has_bytes { + v.state + .blobs + .insert(source_id.into(), payload.clone().into()); + } + if has_callback { + v.set_on_blob_download(Some(Box::new(move |blob| { + sink.borrow_mut().push(blob); + }))); + } else { + v.set_on_blob_download(None); + } + v.edgeless_set_selection([block_id.into()], cx); + }) + }) + .unwrap(); + let snap = frame(&app, win, &hw); + let shown = snap + .elements + .contains_key("chrome.edgeless_element_toolbar.media_download"); + assert_eq!( + shown, expect_deliver, + "{block_id}/{label}: Download button visibility" + ); + if expect_deliver { + click( + &app, + win, + &hw, + &platform, + "chrome.edgeless_element_toolbar.media_download", + ); + let got = received.borrow(); + assert_eq!(got.len(), 1, "{block_id}/{label}: delivered once"); + assert_eq!(got[0].source_id, source_id); + assert_eq!(got[0].filename, expected_name); + assert_eq!(got[0].mime_type, expected_mime); + assert_eq!(&got[0].bytes, payload); + } else { + app.update(|cx| { + win.update(cx, |v, _, cx| { + v.apply_edgeless_element_action(EdgelessElementAction::MediaDownload, cx); + }) + }) + .unwrap(); + assert!( + received.borrow().is_empty(), + "{block_id}/{label}: hidden download must not deliver" + ); + } + } + } +} diff --git a/blocksuite/crates/playground/src/edgeless/edgeless_toolbar_actions_tests.rs b/blocksuite/crates/playground/src/edgeless/edgeless_toolbar_actions_tests.rs index 0baf337028..897481ce85 100644 --- a/blocksuite/crates/playground/src/edgeless/edgeless_toolbar_actions_tests.rs +++ b/blocksuite/crates/playground/src/edgeless/edgeless_toolbar_actions_tests.rs @@ -302,11 +302,13 @@ fn media_open_embed_doc_info_reload_download_toggle_and_canvas_block_duplicate() let seen = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); let sink = seen.clone(); - v.set_on_media_download(move |media| sink.borrow_mut().push(media.clone())); + v.set_on_blob_download(Some(Box::new(move |blob| sink.borrow_mut().push(blob)))); v.apply_edgeless_element_action(EdgelessElementAction::MediaDownload, cx); let downloads = seen.borrow(); assert_eq!(downloads.len(), 1); + assert_eq!(downloads[0].source_id, "img-blob-1"); assert_eq!(downloads[0].filename, "diagram.png"); + assert_eq!(downloads[0].mime_type, "image/png"); assert_eq!(downloads[0].bytes, png_bytes); v.apply_edgeless_element_action(EdgelessElementAction::Duplicate, cx); diff --git a/blocksuite/crates/playground/src/edgeless/edgeless_toolbar_bounds_tests.rs b/blocksuite/crates/playground/src/edgeless/edgeless_toolbar_bounds_tests.rs index 301fc78d82..66ffc2f201 100644 --- a/blocksuite/crates/playground/src/edgeless/edgeless_toolbar_bounds_tests.rs +++ b/blocksuite/crates/playground/src/edgeless/edgeless_toolbar_bounds_tests.rs @@ -510,6 +510,7 @@ fn edgeless_crdt_themed_color_encoding_group_naming_mindmap_bounds_mixed_brush_a &v.edgeless.authoring, v.theme, &v.theme.palette(), + |id| v.can_download_blob(id), ) .unwrap(); assert!( diff --git a/blocksuite/crates/playground/src/edgeless/edgeless_toolbar_interop_tests.rs b/blocksuite/crates/playground/src/edgeless/edgeless_toolbar_interop_tests.rs index 3844ad95e9..6567ccca76 100644 --- a/blocksuite/crates/playground/src/edgeless/edgeless_toolbar_interop_tests.rs +++ b/blocksuite/crates/playground/src/edgeless/edgeless_toolbar_interop_tests.rs @@ -139,6 +139,7 @@ fn edgeless_toolbar_line_width_font_size_and_note_in_page_offset() { &v.edgeless.authoring, PlaygroundTheme::Light, &PlaygroundTheme::Light.palette(), + |id| v.can_download_blob(id), ) .unwrap(); assert!(summary.is_highlighter_width); @@ -299,6 +300,7 @@ fn edgeless_toolbar_line_width_font_size_and_note_in_page_offset() { &v.edgeless.authoring, PlaygroundTheme::Light, &PlaygroundTheme::Light.palette(), + |id| v.can_download_blob(id), ) .unwrap(); assert!(!s.has_font_size); diff --git a/blocksuite/crates/playground/src/edgeless/edgeless_toolbar_polish_tests.rs b/blocksuite/crates/playground/src/edgeless/edgeless_toolbar_polish_tests.rs index 300c8a6bd8..c49a464b27 100644 --- a/blocksuite/crates/playground/src/edgeless/edgeless_toolbar_polish_tests.rs +++ b/blocksuite/crates/playground/src/edgeless/edgeless_toolbar_polish_tests.rs @@ -435,6 +435,7 @@ fn note_style_panel_exposes_six_shadows_border_radius_auto_height_and_scale() { &v.edgeless.authoring, PlaygroundTheme::Light, &PlaygroundTheme::Light.palette(), + |id| v.can_download_blob(id), ) .unwrap(); assert_eq!(sum.note_shadow, "--affine-note-shadow-float"); diff --git a/blocksuite/crates/playground/src/edgeless/element_toolbar.rs b/blocksuite/crates/playground/src/edgeless/element_toolbar.rs index b115aeef52..8ccc381c15 100644 --- a/blocksuite/crates/playground/src/edgeless/element_toolbar.rs +++ b/blocksuite/crates/playground/src/edgeless/element_toolbar.rs @@ -357,6 +357,7 @@ impl PlaygroundView { &self.edgeless.authoring, self.theme, &self.theme.palette(), + |source_id| self.can_download_blob(source_id), ); let next_scribbled = !summary.as_ref().is_some_and(|s| s.scribbled); let next_note_mode = if summary.as_ref().is_some_and(|s| s.note_in_page) { diff --git a/blocksuite/crates/playground/src/edgeless/element_toolbar_media_actions.rs b/blocksuite/crates/playground/src/edgeless/element_toolbar_media_actions.rs index baa76b3ed5..86b1b6d0f2 100644 --- a/blocksuite/crates/playground/src/edgeless/element_toolbar_media_actions.rs +++ b/blocksuite/crates/playground/src/edgeless/element_toolbar_media_actions.rs @@ -17,22 +17,11 @@ use crate::{ use super::{EdgelessElementAction, SpatialItemInfo, SpatialItemKind, prop_f32}; -/// Host-observable media/attachment download payload dispatched from Edgeless or Page toolbars. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct DownloadedMedia { - pub block_id: String, - pub source_id: String, - pub filename: String, - pub mime_type: String, - pub bytes: Vec, -} - -/// Runtime timer and media download hook owned by `PlaygroundView`. +/// Runtime timer state owned by `PlaygroundView` for Edgeless quick-connect previews. #[derive(Default)] pub(crate) struct EdgelessHostRuntime { pub(crate) quick_connect_hover_timer: Option>, pub(crate) quick_connect_hover_gen: u64, - pub(crate) on_media_download: Option>, } /// Caption of a captioned canvas block, empty when it has none. @@ -76,57 +65,7 @@ fn find_parent_block_id(snapshot: &PageSnapshot, block_id: &str) -> Option (&'static str, &'static str) { - if bytes.starts_with(b"\x89PNG\r\n\x1a\n") { - ("png", "image/png") - } else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) { - ("jpg", "image/jpeg") - } else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") { - ("gif", "image/gif") - } else if bytes.len() >= 12 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WEBP" { - ("webp", "image/webp") - } else if bytes.starts_with(b"BM") { - ("bmp", "image/bmp") - } else { - ("bin", "application/octet-stream") - } -} - -#[cfg(target_arch = "wasm32")] -fn trigger_web_download(filename: &str, mime_type: &str, bytes: &[u8]) { - use wasm_bindgen::JsCast; - let Some(window) = web_sys::window() else { - return; - }; - let Some(document) = window.document() else { - return; - }; - let array = js_sys::Uint8Array::from(bytes); - let parts = js_sys::Array::of1(&array.into()); - let bag = web_sys::BlobPropertyBag::new(); - bag.set_type(mime_type); - let Ok(blob) = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &bag) else { - return; - }; - let Ok(url) = web_sys::Url::create_object_url_with_blob(&blob) else { - return; - }; - if let Ok(el) = document.create_element("a") - && let Ok(anchor) = el.dyn_into::() - { - anchor.set_href(&url); - anchor.set_download(filename); - anchor.click(); - } - let _ = web_sys::Url::revoke_object_url(&url); -} - impl PlaygroundView { - /// Install a host callback invoked whenever a media or attachment download is triggered. - pub fn set_on_media_download(&mut self, callback: impl FnMut(&DownloadedMedia) + 'static) { - self.edgeless_runtime.on_media_download = Some(Box::new(callback)); - } - pub(super) fn apply_edgeless_media_action( &mut self, action: &EdgelessElementAction, @@ -269,7 +208,8 @@ impl PlaygroundView { self.apply_edgeless_media_reload(node, &block_id, cx); } EdgelessElementAction::MediaDownload => { - self.apply_edgeless_media_download(node, &block_id, cx); + self.edgeless.authoring.open_sub_menu = None; + self.download_media_block(&block_id, cx); } _ => {} } @@ -467,60 +407,4 @@ impl PlaygroundView { self.env_rev = self.env_rev.wrapping_add(1); cx.notify(); } - - fn apply_edgeless_media_download( - &mut self, - node: &BlockNode, - block_id: &str, - cx: &mut Context, - ) { - self.edgeless.authoring.open_sub_menu = None; - let (source_id, name_opt, mime_opt) = match &node.content { - BlockContent::Attachment { - source_id, - name, - mime_type, - .. - } if !source_id.is_empty() => ( - source_id.clone(), - (!name.is_empty()).then(|| name.clone()), - (!mime_type.is_empty()).then(|| mime_type.clone()), - ), - BlockContent::Image { - source_id, caption, .. - } if !source_id.is_empty() => ( - source_id.clone(), - (!caption.is_empty()).then(|| caption.clone()), - None, - ), - _ => return, - }; - let Some(bytes) = self - .state - .blobs - .get(&source_id) - .map(|b| b.as_slice().to_vec()) - else { - return; - }; - let (inferred_ext, inferred_mime) = infer_image_ext_and_mime(&bytes); - let mime_type = mime_opt.unwrap_or_else(|| inferred_mime.to_string()); - let filename = match name_opt { - Some(n) => n, - None => format!("{source_id}.{inferred_ext}"), - }; - #[cfg(target_arch = "wasm32")] - trigger_web_download(&filename, &mime_type, &bytes); - let payload = DownloadedMedia { - block_id: block_id.to_string(), - source_id, - filename, - mime_type, - bytes, - }; - if let Some(cb) = self.edgeless_runtime.on_media_download.as_mut() { - cb(&payload); - } - cx.notify(); - } } diff --git a/blocksuite/crates/playground/src/edgeless/mod.rs b/blocksuite/crates/playground/src/edgeless/mod.rs index 97ab37c9ce..e0ff1437c5 100644 --- a/blocksuite/crates/playground/src/edgeless/mod.rs +++ b/blocksuite/crates/playground/src/edgeless/mod.rs @@ -42,7 +42,6 @@ mod shape_picker; mod ungroup_ops; pub use blocksuite_editor::edgeless::*; -pub use element_toolbar_media_actions::DownloadedMedia; pub(crate) use element_toolbar_media_actions::EdgelessHostRuntime; pub(crate) use commands::find_surface_element; diff --git a/blocksuite/crates/playground/src/edgeless/paste_convert.rs b/blocksuite/crates/playground/src/edgeless/paste_convert.rs index ea1ace3465..cbc920387d 100644 --- a/blocksuite/crates/playground/src/edgeless/paste_convert.rs +++ b/blocksuite/crates/playground/src/edgeless/paste_convert.rs @@ -319,7 +319,7 @@ pub(super) fn surface_json_to_session_value(v: &Value) -> SessionValue { } } -pub(super) fn json_to_any(v: &Value) -> Any { +pub(crate) fn json_to_any(v: &Value) -> Any { match v { Value::Null => Any::Null, Value::Bool(b) => { diff --git a/blocksuite/crates/playground/src/edgeless/shape_picker.rs b/blocksuite/crates/playground/src/edgeless/shape_picker.rs index e8c10b020d..7bae812649 100644 --- a/blocksuite/crates/playground/src/edgeless/shape_picker.rs +++ b/blocksuite/crates/playground/src/edgeless/shape_picker.rs @@ -167,6 +167,7 @@ impl PlaygroundView { open_color_picker, palette, self.theme, + |source_id| self.can_download_blob(source_id), cx, ) }) diff --git a/blocksuite/crates/playground/src/image_cache.rs b/blocksuite/crates/playground/src/image_cache.rs index 4e75b2e6ca..5c4ea07355 100644 --- a/blocksuite/crates/playground/src/image_cache.rs +++ b/blocksuite/crates/playground/src/image_cache.rs @@ -1,4 +1,5 @@ -//! Bounded Undo LRU image store and cross-frame deferred GPU atlas reclamation. +//! Bounded Undo LRU image store, cross-frame deferred GPU atlas reclamation, and delivery of +//! image and attachment bytes to the host as file downloads. use std::{ collections::{BTreeSet, HashMap, HashSet}, @@ -6,9 +7,10 @@ use std::{ sync::Arc, }; -use ui::{ImageId, RenderImage, Window}; +use blocksuite_playground_doc::read::BlockContent; +use ui::{Context, ImageId, RenderImage, Window}; -use crate::block_flow::ImageSlot; +use crate::{PlaygroundView, block_flow::ImageSlot}; /// Maximum number of unreferenced decoded images retained for instant Undo without re-decoding. pub(crate) const UNREFERENCED_IMAGE_CACHE_MAX_ENTRIES: usize = 16; @@ -22,6 +24,69 @@ pub(crate) fn render_image_pixel_bytes(image: &RenderImage) -> usize { .sum() } +/// Media or attachment bytes that the host receives when the user downloads a block. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct DownloadedBlob { + pub source_id: String, + pub filename: String, + pub mime_type: String, + pub bytes: Vec, +} + +/// Host callback that takes ownership of each downloaded blob. +pub type BlobDownloadFn = Box; + +fn image_ext_and_mime(bytes: &[u8]) -> (&'static str, &'static str) { + if bytes.starts_with(b"\x89PNG\r\n\x1a\n") { + ("png", "image/png") + } else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) { + ("jpg", "image/jpeg") + } else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") { + ("gif", "image/gif") + } else if bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP" { + ("webp", "image/webp") + } else if bytes.starts_with(b"BM") { + ("bmp", "image/bmp") + } else { + ("bin", "application/octet-stream") + } +} + +/// Save the blob through a browser `` click. +#[cfg(target_family = "wasm")] +fn web_download(blob: &DownloadedBlob) -> bool { + use wasm_bindgen::JsCast; + let Some(document) = web_sys::window().and_then(|w| w.document()) else { + return false; + }; + let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(blob.bytes.as_slice()).into()); + let bag = web_sys::BlobPropertyBag::new(); + bag.set_type(&blob.mime_type); + let Ok(file) = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &bag) else { + return false; + }; + let Ok(url) = web_sys::Url::create_object_url_with_blob(&file) else { + return false; + }; + let clicked = document + .create_element("a") + .ok() + .and_then(|el| el.dyn_into::().ok()) + .map(|anchor| { + anchor.set_href(&url); + anchor.set_download(&blob.filename); + anchor.click(); + }) + .is_some(); + let _ = web_sys::Url::revoke_object_url(&url); + clicked +} + +#[cfg(not(target_family = "wasm"))] +fn web_download(_: &DownloadedBlob) -> bool { + false +} + /// Encapsulated decoded-image store for [`crate::PlaygroundView`]. /// /// Exposes read-only map lookup via [`Deref`] (never `DerefMut`) so every mutation flows @@ -35,6 +100,7 @@ pub(crate) struct ImageStore { access_gen: HashMap, gen_counter: u64, pending_dropped: HashMap>, + download_sink: Option, } impl Deref for ImageStore { @@ -50,6 +116,24 @@ impl ImageStore { Self::default() } + /// Whether a download reaches the user: the Web saves files itself, and a native host + /// needs a registered callback. + pub(crate) fn can_deliver_downloads(&self) -> bool { + cfg!(target_family = "wasm") || self.download_sink.is_some() + } + + /// Hand `blob` to the host callback, or else to the browser. Returns `false` when nothing + /// took it. + fn deliver_download(&mut self, blob: DownloadedBlob) -> bool { + match self.download_sink.as_mut() { + Some(sink) => { + sink(blob); + true + } + None => web_download(&blob), + } + } + pub(crate) fn queue_retired(&mut self, img: Arc) { self.pending_dropped.entry(img.id).or_insert(img); } @@ -224,6 +308,109 @@ impl ImageStore { } } +impl PlaygroundView { + /// Register the host callback that saves downloaded media or attachment bytes; `None` hides + /// `Download` on hosts without a browser. + pub fn set_on_blob_download(&mut self, callback: Option) { + self.images.download_sink = callback; + } + + /// Whether `source_id` has non-empty bytes cached in the document blob store. + pub(crate) fn has_blob_bytes(&self, source_id: &str) -> bool { + !source_id.is_empty() + && self + .state + .blobs + .get(source_id) + .is_some_and(|bytes| !bytes.is_empty()) + } + + /// Whether a block referencing `source_id` can deliver a download right now. + pub(crate) fn can_download_blob(&self, source_id: &str) -> bool { + self.images.can_deliver_downloads() && self.has_blob_bytes(source_id) + } + + /// Download the bytes of an `affine:image` or `affine:attachment` block through the single + /// host/Web download channel. Checks channel availability before copying blob bytes and shows + /// confirmation only after the host or browser took the bytes. + pub(crate) fn download_media_block(&mut self, block_id: &str, cx: &mut Context) -> bool { + if !self.images.can_deliver_downloads() { + return false; + } + let Some((source_id, raw_name, mime_opt, is_image)) = self + .snapshot + .as_ref() + .and_then(|s| s.block(block_id)) + .and_then(|n| match &n.content { + BlockContent::Image { + source_id, caption, .. + } if !source_id.is_empty() => { + Some((source_id.clone(), caption.trim().to_string(), None, true)) + } + BlockContent::Attachment { + source_id, + name, + mime_type, + .. + } if !source_id.is_empty() => Some(( + source_id.clone(), + name.trim().to_string(), + (!mime_type.trim().is_empty()).then(|| mime_type.trim().to_string()), + false, + )), + _ => None, + }) + else { + return false; + }; + let Some(bytes) = self + .state + .blobs + .get(&source_id) + .filter(|b| !b.is_empty()) + .map(|b| b.as_slice().to_vec()) + else { + return false; + }; + let (ext, inferred_mime) = image_ext_and_mime(&bytes); + let mime_type = mime_opt.unwrap_or_else(|| inferred_mime.to_string()); + let clean = raw_name.replace(['/', '\\'], "_"); + let filename = if is_image { + if clean.is_empty() { + format!("image.{ext}") + } else if clean + .rsplit_once('.') + .is_some_and(|(_, existing)| existing.eq_ignore_ascii_case(ext)) + { + clean + } else { + format!("{clean}.{ext}") + } + } else if clean.is_empty() { + format!("{source_id}.{ext}") + } else { + clean + }; + let blob = DownloadedBlob { + source_id, + filename, + mime_type, + bytes, + }; + if self.images.deliver_download(blob) { + let toast = if is_image { + "Image downloaded" + } else { + "File downloaded" + }; + self.show_timed_context_toast(toast, cx); + cx.notify(); + return true; + } + false + } +} + #[cfg(test)] mod tests { use std::{cell::RefCell, collections::BTreeSet, rc::Rc, sync::Arc}; diff --git a/blocksuite/crates/playground/src/layout_cache.rs b/blocksuite/crates/playground/src/layout_cache.rs index 83d895a7ff..2630d50047 100644 --- a/blocksuite/crates/playground/src/layout_cache.rs +++ b/blocksuite/crates/playground/src/layout_cache.rs @@ -470,10 +470,26 @@ impl PlaygroundView { cx.notify(); } + /// [`crate::block_flow::snapshot_has_math`] of `snapshot`, walked once per page and document + /// revision and reused in O(1) by every other frame. + pub(crate) fn snapshot_has_math_cached(&mut self, snapshot: &PageSnapshot) -> bool { + match &self.flow.has_math_cache { + Some((page_id, rev, has_math)) if *page_id == self.page_id && *rev == self.doc_rev => { + *has_math + } + _ => { + let has_math = crate::block_flow::snapshot_has_math(snapshot); + self.flow.has_math_cache = Some((self.page_id.clone(), self.doc_rev, has_math)); + has_math + } + } + } + pub(crate) fn ensure_layout(&mut self, width: f32, window: &Window) -> Option> { use std::hash::{Hash, Hasher}; let snapshot = self.snapshot.clone()?; + let has_math = self.snapshot_has_math_cached(&snapshot); let is_rtl = window.layout_direction().is_rtl(); let (now_ms, utc_offset_minutes) = self.local_calendar_clock(); let local_day = @@ -501,7 +517,7 @@ impl PlaygroundView { .then(|| self.table_cell.as_ref().map(|c| c.block_id.as_str())) .flatten(); let preview_rev = crate::block_flow::document_preview_revision( - &snapshot, + has_math, equation_draft.as_ref(), &self.flow.code_preview_blocks, ) diff --git a/blocksuite/crates/playground/src/lib.rs b/blocksuite/crates/playground/src/lib.rs index c3646b5f2d..2a0b674924 100644 --- a/blocksuite/crates/playground/src/lib.rs +++ b/blocksuite/crates/playground/src/lib.rs @@ -38,6 +38,7 @@ mod wasm_preview; #[cfg(not(target_arch = "wasm32"))] pub use block_flow::ensure_native_preview_providers_installed; pub use doc_panel::{DocPanelTab, DocStats, TocHeading, compute_doc_stats, extract_toc_headings}; +pub use image_cache::{BlobDownloadFn, DownloadedBlob}; pub use options::{PlaygroundMode, PlaygroundOptions}; pub use showcase::seed_showcase_doc; pub use touch_selection::{ @@ -136,8 +137,6 @@ pub(crate) struct ImageResizeDrag { pub(crate) use touch_interaction::{ModalTouchTarget, PopoverFlingTarget, TouchStrokeOwner}; -pub use edgeless::DownloadedMedia; - /// Interactive GPUI root view for desktop, Web canvas, and headless verification sessions. pub struct PlaygroundView { pub(crate) mode: PlaygroundMode, @@ -236,8 +235,7 @@ pub struct PlaygroundView { pub(crate) database_input: Option, pub(crate) context_toast_timer: Option>, pub(crate) link_hover_timer: Option>, - pub(crate) link_hover_gen: u64, - pub(crate) pending_link_hover: Option<(overlays::LinkPopupTarget, block_flow::FlowRect, u64)>, + pub(crate) link_hover_pending: Option, pub(crate) context_paste_task: Option>, pub(crate) context_menu_target: Option, pub(crate) last_opened_link_url: Option, @@ -405,8 +403,7 @@ impl PlaygroundView { database_input: None, context_toast_timer: None, link_hover_timer: None, - link_hover_gen: 0, - pending_link_hover: None, + link_hover_pending: None, context_paste_task: None, context_menu_target: None, last_opened_link_url: None, @@ -4415,6 +4412,59 @@ pub(crate) mod tests { ); } + #[test] + fn math_free_page_reuses_its_layout_across_preview_results_and_memoizes_math_detection() { + let mut doc = DocState::new("math-free", client_id_from_seed(0x4d41)).expect("doc"); + doc.workspace.initialize_meta().expect("meta"); + doc.workspace + .create_page(HOME_PAGE_ID, "Math free", 1) + .expect("page"); + let page = doc.workspace.ensure_page(HOME_PAGE_ID).expect("page"); + let mut seed = ShowcaseSeed { page, now_ms: 0 }; + let title = "Math free".to_string(); + seed.add("m-page", BlockSpec::Page { title }, None) + .expect("page"); + seed.add("m-note", BlockSpec::Note { xywh: None }, Some("m-page")) + .expect("note"); + seed.paragraph("m-text", ParagraphType::Text, "Plain words", "m-note") + .expect("paragraph"); + + let session = open(1280, 800, PlaygroundOptions::default()); + session.view(|view, cx| view.set_document(doc, cx)); + let layout = || { + session.app.update(|cx| { + session + .window + .update(cx, |view, window, _| view.ensure_layout(1280.0, window)) + .expect("update view") + .expect("layout") + }) + }; + let first = layout(); + crate::block_flow::bump_preview_revision(); + let second = layout(); + assert!( + Rc::ptr_eq(&first, &second), + "a preview result never lays out a page without math" + ); + + session.view(|view, _| { + let key = (view.page_id.clone(), view.doc_rev); + assert_eq!( + view.flow.has_math_cache, + Some((key.0.clone(), key.1, false)) + ); + let snapshot = view.snapshot.clone().expect("snapshot"); + // The same `(page id, document revision)` reuses the memo without walking the page. + view.flow.has_math_cache = Some((key.0.clone(), key.1, true)); + assert!(view.snapshot_has_math_cached(&snapshot)); + // A new revision walks the page again. + view.doc_rev += 1; + assert!(!view.snapshot_has_math_cached(&snapshot)); + assert_eq!(view.flow.has_math_cache, Some((key.0, key.1 + 1, false))); + }); + } + #[test] fn edgeless_note_layout_cache_invalidates_on_rtl_direction_switch() { let build_doc = || { diff --git a/blocksuite/crates/playground/src/overlays/mod.rs b/blocksuite/crates/playground/src/overlays/mod.rs index e341c673d8..e7133f3bd8 100644 --- a/blocksuite/crates/playground/src/overlays/mod.rs +++ b/blocksuite/crates/playground/src/overlays/mod.rs @@ -7,6 +7,7 @@ mod view_caption_paint; mod view_context_menu; mod view_edits; mod view_embed_controls; +mod view_embed_toolbar; mod view_format_bar; mod view_link_popup; mod view_linked_doc; @@ -27,10 +28,14 @@ mod tests_e1; #[cfg(test)] mod tests_e2_treednd_edgeless; #[cfg(test)] +mod tests_embed_views_downloads_and_tables; +#[cfg(test)] mod tests_image_and_slash_media; #[cfg(test)] mod tests_inline_caption_and_code_toolbar; #[cfg(test)] +mod tests_link_popup_and_block_submenus; +#[cfg(test)] mod tests_media_picker_and_touch; #[cfg(test)] mod tests_mouse_and_touch_resize; @@ -59,6 +64,7 @@ mod wasm_html_embeds; pub use blocksuite_editor::overlays::*; 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; @@ -371,7 +377,7 @@ mod tests { } /// State vector of the page: equal before and after means nothing was written. - fn written(&self) -> Vec { + pub(super) fn written(&self) -> Vec { self.view(|view, _| { view.document() .workspace @@ -419,7 +425,7 @@ mod tests { self.platform.run_until_parked(); } - fn press(&self, x: f32, y: f32, click_count: usize) { + pub(super) fn press(&self, x: f32, y: f32, click_count: usize) { self.pointer(x, y, false); self.headless .dispatch_input(PlatformInput::MouseDown(MouseDownEvent { @@ -432,7 +438,7 @@ mod tests { self.platform.run_until_parked(); } - fn release(&self, x: f32, y: f32) { + pub(super) fn release(&self, x: f32, y: f32) { self.headless .dispatch_input(PlatformInput::MouseUp(MouseUpEvent { button: MouseButton::Left, @@ -1090,6 +1096,50 @@ mod tests { assert!(!session.settle().elements.contains_key("overlay.slash_menu")); } + #[test] + fn typed_file_slash_commands_keep_their_text_on_hosts_without_a_file_picker() { + use blocksuite_editor::overlays::{SlashCommand, filter_slash_items_with_caps}; + let session = open(1280, 800, PlaygroundTheme::Light); + for (index, (query, command)) in [ + ("image", SlashCommand::Image), + ("attachment", SlashCommand::Attachment), + ("pdf", SlashCommand::Pdf), + ] + .into_iter() + .enumerate() + { + let block = format!("t-file-{query}"); + empty_paragraph(&session, &block, 2 + index as u64); + session.overlay(OverlayEvent::SetSelection(Some(ActiveSelection::caret( + &block, 0, + )))); + session.frame(); + session.insert(&format!("/{query}")); + let (image_ok, attachment_ok) = + session.view(|view, _| (view.can_pick_images(), view.can_pick_attachments())); + assert!( + !image_ok && !attachment_ok, + "headless host has no file picker" + ); + let menu_ids: Vec<_> = filter_slash_items_with_caps(query, true, false, false) + .iter() + .map(|item| item.id) + .collect(); + assert!( + !menu_ids.contains(&query), + "`/{query}` is filtered out: {menu_ids:?}" + ); + let written = session.written(); + session.update(|view, window, cx| { + view.run_slash_command(&block, command, true, window, cx) + .expect("run slash command"); + assert!(view.pending_media_pick.is_none()); + }); + assert_eq!(session.text(&block).plain, format!("/{query}")); + assert_eq!(session.written(), written, "`/{query}` writes nothing"); + } + } + #[test] fn typing_a_slash_filters_in_the_document_and_runs_as_one_undo_step() { let session = open(1280, 800, PlaygroundTheme::Light); @@ -1378,16 +1428,17 @@ mod tests { let toolbar = element(&frame, "overlay.format_toolbar"); assert_eq!(toolbar.opacity, 1.0); - assert_eq!((toolbar.corner_radius, toolbar.padding), (8.0, 4.0)); - // Above the selection's first line with the popover gap, centered on it. + assert_eq!(toolbar.corner_radius, 8.0); + // Above the selection's first line with the ToolbarChrome offset (10px), centered on it. let selection = element(&frame, "page.selection").bounds; - assert_eq!(toolbar.bounds.bottom() + POPOVER_GAP, selection.y); + assert_eq!(toolbar.bounds.bottom() + TOOLBAR_CHROME_OFFSET, selection.y); assert!((center(toolbar.bounds).0 - center(selection).0).abs() <= 1.0); for action in FormatAction::ALL { let button = element(&frame, &format!("overlay.format_toolbar.{}", action.id())); assert!(button.interactive, "{action:?}"); assert!( - button.bounds.width >= 28.0 && button.bounds.height >= 28.0, + button.bounds.width >= TOOLBAR_CHROME_BTN + && button.bounds.height >= TOOLBAR_CHROME_BTN, "{action:?}" ); assert_eq!(button.corner_radius, 4.0, "{action:?}"); @@ -1397,10 +1448,10 @@ mod tests { "{action:?}" ); } - // Buttons sit edge to edge, so the pointer never falls between two of them. + // Buttons within a ToolbarChrome group are separated by a 4px inner gap. let bold = element(&frame, "overlay.format_toolbar.bold").bounds; let italic = element(&frame, "overlay.format_toolbar.italic").bounds; - assert_eq!(bold.right(), italic.x); + assert_eq!(bold.right() + 4.0, italic.x); // Every mark toggles on, shows as active, and one undo takes it off again. for (action, read) in [ @@ -1444,17 +1495,26 @@ mod tests { Some(BlockContent::Paragraph { text_align, .. }) => text_align, _ => None, }; + let open_align = || { + let f = session.frame(); + if f.elements.contains_key("overlay.format_toolbar.align_menu") { + f + } else { + session.click(&f, "overlay.format_toolbar.align"); + session.frame() + } + }; assert_eq!(align(), None); - session.click(&session.frame(), "overlay.format_toolbar.align_center"); + session.click(&open_align(), "overlay.format_toolbar.align_center"); assert_eq!(align(), Some(BlockAlign::Center)); - let centered = session.frame(); + let centered = open_align(); assert!(element(¢ered, "overlay.format_toolbar.align_center").focused); assert!(!element(¢ered, "overlay.format_toolbar.align_left").focused); session.undo(); assert_eq!(align(), None); - session.click(&session.frame(), "overlay.format_toolbar.align_right"); + session.click(&open_align(), "overlay.format_toolbar.align_right"); assert_eq!(align(), Some(BlockAlign::Right)); - session.click(&session.frame(), "overlay.format_toolbar.align_left"); + session.click(&open_align(), "overlay.format_toolbar.align_left"); assert_eq!(align(), Some(BlockAlign::Left)); // The link field opens attached to the toolbar and takes the keyboard. @@ -1474,7 +1534,7 @@ mod tests { assert!(!linking.elements.contains_key("page.local_caret")); let grown = element(&linking, "overlay.format_toolbar").bounds; let single = element(&before, "overlay.format_toolbar").bounds; - assert_eq!(grown.height, single.height + 64.0); + assert_eq!(grown.height, single.height + 63.0); assert!( field.bounds.y >= element(&linking, "overlay.format_toolbar.bold") @@ -1573,12 +1633,13 @@ mod tests { assert_no_violations(&frame, "cross-block toolbar"); let toolbar = element(&frame, "overlay.format_toolbar").bounds; let first = element(&frame, "page.block.showcase-numbered-1").bounds; - assert_eq!(toolbar.bottom() + POPOVER_GAP, first.y); + assert_eq!(toolbar.bottom() + TOOLBAR_CHROME_OFFSET, first.y); session.click(&frame, "overlay.format_toolbar.bold"); assert!(bold("showcase-numbered-1", 6, 10) && bold("showcase-numbered-2", 0, 6)); assert!(!bold("showcase-numbered-1", 0, 6)); assert!(element(&session.frame(), "overlay.format_toolbar.bold").focused); // Alignment reaches every selected block, and all of it is one undo step each. + session.click(&session.frame(), "overlay.format_toolbar.align"); session.click(&session.frame(), "overlay.format_toolbar.align_right"); let aligned = |id: &str| match session.node(id).map(|node| node.content) { Some(BlockContent::List { text_align, .. }) => text_align, @@ -1629,15 +1690,15 @@ mod tests { assert_no_violations(&frame, "flipped toolbar"); let toolbar = element(&frame, "overlay.format_toolbar").bounds; let selection = element(&frame, "page.selection").bounds; - assert!(selection.y - TOPBAR_HEIGHT < toolbar.height + 2.0 * POPOVER_GAP); - assert_eq!(toolbar.y, selection.bottom() + POPOVER_GAP); + assert!(selection.y - TOPBAR_HEIGHT < toolbar.height + 2.0 * TOOLBAR_CHROME_OFFSET); + assert_eq!(toolbar.y, selection.bottom() + TOOLBAR_CHROME_OFFSET); // Scrolled back, the same selection has room above again. session.scroll(640.0, 400.0, 0.0, block_y); let frame = session.settle(); let toolbar = element(&frame, "overlay.format_toolbar").bounds; let selection = element(&frame, "page.selection").bounds; - assert_eq!(toolbar.bottom() + POPOVER_GAP, selection.y); + assert_eq!(toolbar.bottom() + TOOLBAR_CHROME_OFFSET, selection.y); } #[test] @@ -2535,12 +2596,22 @@ mod tests { paragraph("t-b", "B", "showcase-note", 2); let frame = select(("t-a", 0), ("t-b", 1)); assert_no_violations(&frame, "toolbar over an empty block"); - assert!(element(&frame, "overlay.format_toolbar.align_left").focused); - session.click(&frame, "overlay.format_toolbar.align_center"); + let open_align = |f: &FrameSnapshot| { + if f.elements.contains_key("overlay.format_toolbar.align_menu") { + f.clone() + } else { + session.click(f, "overlay.format_toolbar.align"); + session.frame() + } + }; + let align_menu = open_align(&frame); + assert!(element(&align_menu, "overlay.format_toolbar.align_left").focused); + session.click(&align_menu, "overlay.format_toolbar.align_center"); for id in ["t-a", "t-empty", "t-b"] { assert_eq!(aligned(id), Some(BlockAlign::Center), "{id}"); } - assert!(element(&session.frame(), "overlay.format_toolbar.align_center").focused); + let centered_menu = open_align(&session.frame()); + assert!(element(¢ered_menu, "overlay.format_toolbar.align_center").focused); session.undo(); for id in ["t-a", "t-empty", "t-b"] { assert_eq!(aligned(id), None, "{id}"); @@ -2556,8 +2627,9 @@ mod tests { .expect("align the empty paragraph"); }); let frame = select(("t-a", 0), ("t-b", 1)); + let mixed_menu = open_align(&frame); for id in ["align_left", "align_center", "align_right"] { - assert!(!element(&frame, &format!("overlay.format_toolbar.{id}")).focused); + assert!(!element(&mixed_menu, &format!("overlay.format_toolbar.{id}")).focused); } // A child that sets no alignment shows its parent's, as it is drawn. @@ -2573,8 +2645,9 @@ mod tests { }); assert_eq!(aligned("t-child"), None); let frame = select(("t-child", 0), ("t-child", 5)); - assert!(element(&frame, "overlay.format_toolbar.align_right").focused); - assert!(!element(&frame, "overlay.format_toolbar.align_left").focused); + let child_menu = open_align(&frame); + assert!(element(&child_menu, "overlay.format_toolbar.align_right").focused); + assert!(!element(&child_menu, "overlay.format_toolbar.align_left").focused); } #[test] diff --git a/blocksuite/crates/playground/src/overlays/tests_e1.rs b/blocksuite/crates/playground/src/overlays/tests_e1.rs index c9fd628315..b650c4c28b 100644 --- a/blocksuite/crates/playground/src/overlays/tests_e1.rs +++ b/blocksuite/crates/playground/src/overlays/tests_e1.rs @@ -355,11 +355,7 @@ mod tests { assert!(popup_frame.elements.contains_key("overlay.link_popup.open")); assert!(popup_frame.elements.contains_key("overlay.link_popup.edit")); assert!(popup_frame.elements.contains_key("overlay.link_popup.copy")); - assert!( - popup_frame - .elements - .contains_key("overlay.link_popup.unlink") - ); + assert!(popup_frame.elements.contains_key("overlay.link_popup.more")); // Unlink removes link mark in 1 undo step. session.overlay(OverlayEvent::LinkPopupAction(LinkPopupAction::Unlink)); diff --git a/blocksuite/crates/playground/src/overlays/tests_e2_treednd_edgeless.rs b/blocksuite/crates/playground/src/overlays/tests_e2_treednd_edgeless.rs index d13e2aa353..77da476f13 100644 --- a/blocksuite/crates/playground/src/overlays/tests_e2_treednd_edgeless.rs +++ b/blocksuite/crates/playground/src/overlays/tests_e2_treednd_edgeless.rs @@ -579,6 +579,7 @@ fn e2_edgeless_zoom_bar_bottom_left_fit_motion_and_element_toolbar_undo() { &v.edgeless.authoring, PlaygroundTheme::Light, &PlaygroundTheme::Light.palette(), + |id| v.can_download_blob(id), ) .expect("summary"); assert_eq!(summary.fill_color, expected_blue); @@ -1575,6 +1576,7 @@ mod block_menu_and_edgeless_toolbar_tests { &v.edgeless.authoring, PlaygroundTheme::Light, &PlaygroundTheme::Light.palette(), + |id| v.can_download_blob(id), ) .expect("Brush element must produce ElementToolbarSummary"); assert!(brush_summary.has_stroke && brush_summary.has_stroke_width); @@ -1588,6 +1590,7 @@ mod block_menu_and_edgeless_toolbar_tests { &v.edgeless.authoring, PlaygroundTheme::Light, &PlaygroundTheme::Light.palette(), + |id| v.can_download_blob(id), ) .expect("EdgelessText summary"); assert!(et_summary.has_stroke); diff --git a/blocksuite/crates/playground/src/overlays/tests_embed_views_downloads_and_tables.rs b/blocksuite/crates/playground/src/overlays/tests_embed_views_downloads_and_tables.rs new file mode 100644 index 0000000000..3faf912e83 --- /dev/null +++ b/blocksuite/crates/playground/src/overlays/tests_embed_views_downloads_and_tables.rs @@ -0,0 +1,939 @@ +//! Deterministic tests for embed view conversions, image downloads through a host channel, +//! `Create Table` from a block selection, table growth from real clicks and drags on the hover +//! add bars (and its cancellation), the axis pill menus and block toolbar dropdown rows under +//! real clicks, toolbar tooltips beside open dropdowns, table column resize handles, read-only +//! embed cards, and the `Highlight` dropdown placement, scroll and clipped row hits. + +#[cfg(test)] +mod tests { + use std::{cell::RefCell, rc::Rc}; + + use blocksuite_playground_doc::{ + read::{BlockContent, BlockNode, ExternalEmbedKind, TableData}, + schema::{BlockSpec, ParagraphType}, + session::PageDocSession, + }; + use y_octo::{Any, SessionValue, TextDeltaOp}; + + use crate::{ + DownloadedBlob, HOME_PAGE_ID, PlaygroundOptions, + overlays::{ + ActiveSelection, EmbedToolbarAction, FormatAction, ImageToolbarAction, OverlayEvent, + }, + room_client::DocState, + }; + + use super::super::tests::{Session, element, open_with_options}; + + fn tiny_png() -> Vec { + let img = image::RgbaImage::from_pixel(48, 32, image::Rgba([40, 120, 220, 255])); + let mut out = Vec::new(); + image::DynamicImage::ImageRgba8(img) + .write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png) + .expect("png encode"); + out + } + + /// A page with a note `n` whose blocks `build` adds, in a 1280 px wide window. + fn open_page( + height: u32, + options: PlaygroundOptions, + build: impl FnOnce(&mut DocState), + ) -> Session { + let session = open_with_options(1280, height, options); + let mut state = DocState::new("embed-views-tables", 94).unwrap(); + state + .workspace + .create_page(HOME_PAGE_ID, "Page", 1) + .unwrap(); + { + let page = state.workspace.page_mut(HOME_PAGE_ID).unwrap(); + page.add_block( + "page-root", + BlockSpec::Page { + title: "Page".into(), + }, + None, + None, + 1, + ) + .unwrap(); + page.add_block( + "n", + BlockSpec::Note { + xywh: Some("[0,0,800,600]".into()), + }, + Some("page-root"), + None, + 2, + ) + .unwrap(); + } + build(&mut state); + session.view(|v, cx| v.set_document(state, cx)); + let _ = session.settle(); + session + } + + fn home(state: &mut DocState) -> &mut PageDocSession { + state.workspace.page_mut(HOME_PAGE_ID).unwrap() + } + + fn add(page: &mut PageDocSession, id: &str, spec: BlockSpec) { + page.add_block(id, spec, Some("n"), None, 3).unwrap(); + } + + fn paragraph(text: &str) -> BlockSpec { + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: text.into(), + } + } + + fn table(rows: &[[&str; 2]]) -> BlockSpec { + BlockSpec::Table { + rows: rows + .iter() + .map(|r| r.iter().map(|c| c.to_string()).collect()) + .collect(), + } + } + + /// The single inline mark `name` of a paragraph's text. + fn inline_mark(node: &BlockNode, name: &str) -> Option { + let BlockContent::Paragraph { text, .. } = &node.content else { + return None; + }; + text.delta.iter().find_map(|op| match op { + TextDeltaOp::Insert { + format: Some(f), .. + } => f.get(name).cloned(), + _ => None, + }) + } + + fn object_field(value: &Any, key: &str) -> Option { + match value { + Any::Object(map) => map.get(key).cloned(), + _ => None, + } + } + + #[test] + fn embed_view_conversions_keep_targets_and_undo_in_one_step() { + let session = open_page(800, PlaygroundOptions::default(), |state| { + let page = home(state); + add( + page, + "e-linked", + BlockSpec::EmbedLinkedDoc { + page_id: "doc-a".into(), + style: "horizontal".into(), + caption: "Linked caption".into(), + }, + ); + page.set_block_prop( + "e-linked", + "prop:params", + SessionValue::Any(Any::Object(Box::new( + [("mode".to_string(), Any::String("edgeless".into()))] + .into_iter() + .collect(), + ))), + 4, + ) + .unwrap(); + add( + page, + "e-synced", + BlockSpec::EmbedSyncedDoc { + page_id: "doc-b".into(), + caption: "Synced caption".into(), + }, + ); + add( + page, + "e-ext", + BlockSpec::ExternalEmbed { + kind: ExternalEmbedKind::Youtube, + url: "https://www.youtube.com/watch?v=abc".into(), + title: Some("Clip".into()), + description: Some("A short clip".into()), + html: None, + caption: "Embed caption".into(), + }, + ); + }); + type Check = fn(&BlockNode); + let cases: [(&str, EmbedToolbarAction, Check); 6] = [ + ("e-linked", EmbedToolbarAction::ConvertToEmbed, |n| { + assert!(matches!(&n.content, + BlockContent::EmbedSyncedDoc { page_id, caption } + if page_id == "doc-a" && caption == "Linked caption")); + assert_eq!(n.props["prop:params"]["mode"], "edgeless"); + }), + ("e-synced", EmbedToolbarAction::ConvertToCard, |n| { + assert!(matches!(&n.content, + BlockContent::EmbedLinkedDoc { page_id, caption, .. } + if page_id == "doc-b" && caption == "Synced caption")); + }), + ("e-linked", EmbedToolbarAction::ConvertToInline, |n| { + let reference = inline_mark(n, "reference").expect("@reference chip"); + assert_eq!( + object_field(&reference, "type"), + Some(Any::String("LinkedPage".into())) + ); + assert_eq!( + object_field(&reference, "pageId"), + Some(Any::String("doc-a".into())) + ); + let params = object_field(&reference, "params").expect("params kept"); + assert_eq!( + object_field(¶ms, "mode"), + Some(Any::String("edgeless".into())) + ); + }), + ("e-synced", EmbedToolbarAction::ConvertToInline, |n| { + let reference = inline_mark(n, "reference").expect("@reference chip"); + assert_eq!( + object_field(&reference, "pageId"), + Some(Any::String("doc-b".into())) + ); + }), + ("e-ext", EmbedToolbarAction::ConvertToCard, |n| { + assert!(matches!(&n.content, + BlockContent::Bookmark { url, title, description, caption } + if url == "https://www.youtube.com/watch?v=abc" + && title.as_deref() == Some("Clip") + && description.as_deref() == Some("A short clip") + && caption == "Embed caption")); + }), + ("e-ext", EmbedToolbarAction::ConvertToInline, |n| { + let BlockContent::Paragraph { text, .. } = &n.content else { + panic!("Inline view is a paragraph"); + }; + assert_eq!(text.plain, "Clip"); + assert_eq!( + inline_mark(n, "link"), + Some(Any::String("https://www.youtube.com/watch?v=abc".into())) + ); + }), + ]; + for (block, action, check) in cases { + let original = session.node(block).expect("embed block"); + let slot = session + .node("n") + .unwrap() + .children + .iter() + .position(|c| c.id == block) + .unwrap(); + session.overlay(OverlayEvent::SelectBlock(block.into())); + let _ = session.settle(); + session.overlay(OverlayEvent::EmbedToolbarAction { + block_id: block.into(), + action, + }); + let _ = session.settle(); + assert!( + session.node(block).is_none(), + "{block} {action:?} replaces the block" + ); + let converted = session.node("n").unwrap().children[slot].clone(); + check(&converted); + assert_eq!( + session.view(|v, _| v.editor.block_selection.clone()), + vec![converted.id.clone()], + "{block} {action:?} selects the new block" + ); + + session.undo(); + let restored = session.node("n").unwrap().children[slot].clone(); + assert_eq!( + restored.id, block, + "one undo restores {block} after {action:?}" + ); + assert_eq!(restored.content, original.content); + assert_eq!(session.node("n").unwrap().children.len(), 3); + } + } + + #[test] + fn image_download_needs_bytes_and_a_host_channel() { + let png = tiny_png(); + let bytes = png.clone(); + let session = open_page(800, PlaygroundOptions::default(), move |state| { + state.blobs.insert("blob-img".into(), bytes.into()); + add( + home(state), + "img", + BlockSpec::Image { + source_id: "blob-img".into(), + caption: "Chart".into(), + width: 240.0, + height: 160.0, + xywh: None, + }, + ); + }); + session.overlay(OverlayEvent::SelectBlock("img".into())); + let frame = session.settle(); + assert!(frame.elements.contains_key("overlay.image_toolbar")); + assert!( + !frame + .elements + .contains_key("overlay.image_toolbar.download"), + "a native host without a download callback hides Download" + ); + session.overlay(OverlayEvent::ImageToolbarAction { + block_id: "img".into(), + action: ImageToolbarAction::Download, + }); + assert_eq!( + session.view(|v, _| v.overlays().context_toast_message().map(str::to_string)), + None, + "no confirmation when nothing received the bytes" + ); + + let received: Rc>> = Rc::default(); + let sink = received.clone(); + session.view(|v, cx| { + v.set_on_blob_download(Some(Box::new(move |blob| sink.borrow_mut().push(blob)))); + cx.notify(); + }); + let frame = session.settle(); + session.click(&frame, "overlay.image_toolbar.download"); + let got = received.borrow().clone(); + assert_eq!(got.len(), 1); + assert_eq!(got[0].bytes, png); + assert_eq!(got[0].filename, "Chart.png"); + assert_eq!(got[0].mime_type, "image/png"); + assert_eq!( + session.view(|v, _| v.overlays().context_toast_message().map(str::to_string)), + Some("Image downloaded".to_string()) + ); + } + + #[test] + fn create_table_from_block_selection_inserts_below_and_focuses_first_cell() { + let session = open_page(800, PlaygroundOptions::default(), |state| { + let page = home(state); + add(page, "p1", paragraph("Hello")); + add(page, "p2", paragraph("World")); + }); + session.overlay(OverlayEvent::SelectBlock("p1".into())); + let frame = session.settle(); + session.click(&frame, "overlay.format_toolbar.create_table"); + let _ = session.settle(); + let children = session.node("n").unwrap().children; + assert_eq!(children.len(), 3); + assert_eq!(children[0].id, "p1"); + assert_eq!(children[2].id, "p2"); + let BlockContent::Table(data) = &children[1].content else { + panic!("a table goes right below the selected block"); + }; + let focus = session.view(|v, _| { + v.table_cell + .as_ref() + .map(|c| (c.block_id.clone(), c.row_id.clone(), c.column_id.clone())) + }); + assert_eq!( + focus, + Some(( + children[1].id.clone(), + data.rows[0].row_id.clone(), + data.columns[0].column_id.clone() + )) + ); + assert!(session.view(|v, _| v.editor.block_selection.is_empty())); + } + + fn table_data(session: &Session) -> TableData { + match session.node("t").unwrap().content { + BlockContent::Table(t) => t, + _ => panic!("table"), + } + } + + /// Screen center of cell (`row`, `col`) of table `t`. + fn cell_center(session: &Session, row: usize, col: usize) -> (f32, f32) { + let data = table_data(session); + let (rid, cid) = (&data.rows[row].row_id, &data.columns[col].column_id); + session.view(|v, _| { + let layout = v.flow_layout().unwrap(); + let block = layout.block("t").unwrap(); + let hit = block + .body + .table_cells + .iter() + .find(|c| &c.row_id == rid && &c.column_id == cid) + .unwrap(); + let geom = v.current_page_geometry(1280.0); + ( + geom.column_x + block.x + hit.rect.x + hit.rect.w * 0.5, + crate::TOPBAR_HEIGHT + block.y + hit.rect.y + hit.rect.h * 0.5 - v.scroll_y, + ) + }) + } + + fn center(frame: &ui::FrameSnapshot, id: &str) -> (f32, f32) { + let b = element(frame, id).bounds; + (b.x + b.width * 0.5, b.y + b.height * 0.5) + } + + #[test] + fn table_hover_add_bars_append_on_a_real_click_or_forward_drag_and_cancel_back_or_backward() { + let session = open_page(800, PlaygroundOptions::default(), |state| { + add(home(state), "t", table(&[["a0", "b0"], ["a1", "b1"]])); + }); + let before = table_data(&session); + let tip = |frame: &ui::FrameSnapshot| { + frame + .elements + .get("overlay.table_hover.drag_tip") + .and_then(|e| e.text.clone()) + }; + // (bar, pointer travel after the press, back to the press point before the release, + // drag tip at the far point, rows × columns after the release) + let cases: [(&str, (f32, f32), bool, Option<&str>, (usize, usize)); 14] = [ + ( + "overlay.table_hover.add_row", + (0.0, 0.0), + false, + None, + (3, 2), + ), + ( + "overlay.table_hover.add_col", + (0.0, 0.0), + false, + None, + (2, 3), + ), + ( + "overlay.table_hover.add_corner", + (0.0, 0.0), + false, + None, + (3, 3), + ), + ( + "overlay.table_hover.add_row", + (0.0, 80.0), + false, + Some("+2 row"), + (4, 2), + ), + ( + "overlay.table_hover.add_col", + (170.0, 0.0), + false, + Some("+2 col"), + (2, 4), + ), + ( + "overlay.table_hover.add_corner", + (170.0, 80.0), + false, + Some("2×2"), + (4, 4), + ), + ( + "overlay.table_hover.add_row", + (0.0, 80.0), + true, + Some("+2 row"), + (2, 2), + ), + ( + "overlay.table_hover.add_col", + (170.0, 0.0), + true, + Some("+2 col"), + (2, 2), + ), + ( + "overlay.table_hover.add_corner", + (170.0, 80.0), + true, + Some("2×2"), + (2, 2), + ), + // A drag away from the table adds nothing. + ( + "overlay.table_hover.add_row", + (0.0, -72.0), + false, + None, + (2, 2), + ), + ( + "overlay.table_hover.add_col", + (-72.0, 0.0), + false, + None, + (2, 2), + ), + // A forward drag shorter than one step still adds one. + ( + "overlay.table_hover.add_col", + (40.0, 0.0), + false, + Some("+1 col"), + (2, 3), + ), + ( + "overlay.table_hover.add_corner", + (5.0, 5.0), + false, + Some("1×1"), + (3, 3), + ), + // A sideways slip along the row bar is still a click. + ( + "overlay.table_hover.add_row", + (8.0, 1.0), + false, + None, + (3, 2), + ), + ]; + for focused in [false, true] { + if focused { + let (x, y) = cell_center(&session, 0, 0); + session.press(x, y, 1); + session.release(x, y); + assert!( + session.view(|v, _| v.table_cell.is_some()), + "the cell takes focus" + ); + } + for (bar, (dx, dy), back, far_tip, dims) in cases { + let case = format!("{bar} {dx}x{dy} back={back} focused={focused}"); + let written = session.written(); + let can_undo = || session.view(|v, _| v.page().is_some_and(|p| p.can_undo())); + let could_undo = can_undo(); + let (x, y) = cell_center(&session, 0, 0); + session.pointer(x, y, false); + let frame = session.settle(); + let (bx, by) = center(&frame, bar); + // Crossing the gap from the cell onto the bar keeps the bars mounted. + for t in [0.25_f32, 0.5, 0.75, 1.0] { + session.pointer(x + (bx - x) * t, y + (by - y) * t, false); + let frame = session.frame(); + assert!( + frame.elements.contains_key(bar), + "{case}: {bar} stays at {t}" + ); + } + session.press(bx, by, 1); + if (dx, dy) != (0.0, 0.0) { + session.pointer(bx + dx * 0.5, by + dy * 0.5, true); + session.pointer(bx + dx, by + dy, true); + } + assert_eq!( + tip(&session.frame()).as_deref(), + far_tip, + "{case}: held tip" + ); + let (rx, ry) = if back { + session.pointer(bx, by, true); + assert_eq!(tip(&session.frame()), None, "{case}: no tip back home"); + (bx, by) + } else { + (bx + dx, by + dy) + }; + assert_eq!( + session.written(), + written, + "{case}: 0 writes before release" + ); + session.release(rx, ry); + let _ = session.settle(); + let after = table_data(&session); + assert_eq!((after.rows.len(), after.columns.len()), dims, "{case}"); + assert!( + session.view(|v, _| v.overlays.table_hover.add_drag.is_none()), + "{case}: the release ends the press" + ); + if dims == (2, 2) { + assert_eq!( + session.written(), + written, + "{case}: a cancelled drag writes 0" + ); + assert_eq!( + can_undo(), + could_undo, + "{case}: a cancelled drag leaves no undo step" + ); + continue; + } + assert_eq!( + after.rows[..2], + before.rows[..], + "{case}: rows append at the end" + ); + assert_eq!(after.columns[..2], before.columns[..], "{case}"); + session.undo(); + assert_eq!(table_data(&session), before, "{case}: one undo step"); + } + } + } + + #[test] + fn table_axis_pill_menus_act_on_real_clicks() { + type Check = fn(&TableData, &TableData) -> bool; + let cases: [(&str, &str, Check); 14] = [ + ("row_pill", "insert_before", |b, a| { + a.rows.len() == 3 && a.rows[0] == b.rows[0] && a.rows[2] == b.rows[1] + }), + ("row_pill", "insert_after", |b, a| { + a.rows.len() == 3 && a.rows[..2] == b.rows[..] + }), + ("row_pill", "move_earlier", |b, a| { + a.rows[0].row_id == b.rows[1].row_id && a.rows[1].row_id == b.rows[0].row_id + }), + ("row_pill", "move_later", |b, a| a == b), + ("row_pill", "clear", |b, a| { + let k = |r: usize, c: usize, t: &TableData| { + t.cells[&(t.rows[r].row_id.clone(), t.columns[c].column_id.clone())] + .text + .plain + .clone() + }; + k(1, 0, a).is_empty() && k(1, 1, a).is_empty() && k(0, 0, a) == k(0, 0, b) + }), + ("row_pill", "delete", |b, a| { + a.rows.len() == 1 && a.rows[0] == b.rows[0] + }), + ("row_pill", "bg_blue", |_, a| { + a.rows[1].background_color.is_some() + }), + ("col_pill", "insert_before", |b, a| { + a.columns.len() == 3 && a.columns[0] == b.columns[0] && a.columns[2] == b.columns[1] + }), + ("col_pill", "insert_after", |b, a| { + a.columns.len() == 3 && a.columns[..2] == b.columns[..] + }), + ("col_pill", "move_earlier", |b, a| { + a.columns[0].column_id == b.columns[1].column_id + }), + ("col_pill", "move_later", |b, a| a == b), + ("col_pill", "clear", |b, a| { + let k = |r: usize, c: usize, t: &TableData| { + t.cells[&(t.rows[r].row_id.clone(), t.columns[c].column_id.clone())] + .text + .plain + .clone() + }; + k(0, 1, a).is_empty() && k(1, 1, a).is_empty() && k(0, 0, a) == k(0, 0, b) + }), + ("col_pill", "delete", |b, a| { + a.columns.len() == 1 && a.columns[0] == b.columns[0] + }), + ("col_pill", "bg_blue", |_, a| { + a.columns[1].background_color.is_some() + }), + ]; + let session = open_page(800, PlaygroundOptions::default(), |state| { + add(home(state), "t", table(&[["a0", "b0"], ["a1", "b1"]])); + }); + let before = table_data(&session); + for (pill, item, check) in cases { + let case = format!("{pill} {item}"); + session.key("escape"); + let (x, y) = cell_center(&session, 1, 1); + session.pointer(x, y, false); + let frame = session.settle(); + session.click(&frame, &format!("overlay.table_hover.{pill}")); + let frame = session.settle(); + assert!( + frame + .elements + .contains_key("overlay.table_toolbar.axis_menu"), + "{case}: the pill opens its menu" + ); + session.click(&frame, &format!("overlay.table_toolbar.axis_menu.{item}")); + let _ = session.settle(); + let after = table_data(&session); + assert!(check(&before, &after), "{case}: {after:?}"); + if after != before { + session.undo(); + assert_eq!(table_data(&session), before, "{case}: one undo step"); + } + } + } + + #[test] + fn block_toolbar_dropdowns_hide_tooltips_and_rows_act_on_real_clicks() { + let png = tiny_png(); + let session = open_page(800, PlaygroundOptions::default(), move |state| { + state.blobs.insert("blob-img".into(), png.into()); + let page = home(state); + add( + page, + "bm", + BlockSpec::Bookmark { + url: "https://affine.pro".into(), + title: Some("AFFiNE".into()), + description: None, + }, + ); + add( + page, + "e-linked", + BlockSpec::EmbedLinkedDoc { + page_id: "doc-a".into(), + style: "horizontal".into(), + caption: String::new(), + }, + ); + add( + page, + "e-ext", + BlockSpec::ExternalEmbed { + kind: ExternalEmbedKind::Youtube, + url: "https://www.youtube.com/watch?v=abc".into(), + title: Some("Clip".into()), + description: None, + html: None, + caption: String::new(), + }, + ); + add( + page, + "img", + BlockSpec::Image { + source_id: "blob-img".into(), + caption: String::new(), + width: 240.0, + height: 160.0, + xywh: None, + }, + ); + }); + // (block, toolbar button, dropdown, row) + let cases = [ + ( + "bm", + "bookmark_toolbar.card", + "bookmark_toolbar.view_menu", + "bookmark_toolbar.inline", + ), + ( + "bm", + "bookmark_toolbar.style", + "bookmark_toolbar.style_menu", + "bookmark_toolbar.style.list", + ), + ( + "bm", + "bookmark_toolbar.more", + "bookmark_toolbar.more_menu", + "bookmark_toolbar.duplicate", + ), + ( + "e-linked", + "embed_toolbar.view", + "embed_toolbar.view_menu", + "embed_toolbar.view.embed", + ), + ( + "e-linked", + "embed_toolbar.style", + "embed_toolbar.style_menu", + "embed_toolbar.style.list", + ), + ( + "e-linked", + "embed_toolbar.more", + "embed_toolbar.more_menu", + "embed_toolbar.more.duplicate", + ), + ( + "e-ext", + "embed_toolbar.view", + "embed_toolbar.view_menu", + "embed_toolbar.view.card", + ), + ( + "e-ext", + "embed_toolbar.more", + "embed_toolbar.more_menu", + "embed_toolbar.more.duplicate", + ), + ( + "img", + "image_toolbar.more", + "image_toolbar.more_menu", + "image_toolbar.duplicate", + ), + ]; + let before = session.node("n").unwrap().children; + for (block, button, menu, row) in cases { + let (button, menu, row) = ( + format!("overlay.{button}"), + format!("overlay.{menu}"), + format!("overlay.{row}"), + ); + session.overlay(OverlayEvent::SelectBlock(block.into())); + let frame = session.settle(); + session.click(&frame, &button); + let frame = session.settle(); + assert!(frame.elements.contains_key(&menu), "{button} opens {menu}"); + let (bx, by) = center(&frame, &button); + session.pointer(bx, by + 1.0, false); + let frame = session.settle(); + assert!( + !frame.elements.contains_key("overlay.toolbar_tooltip"), + "{button}: no tooltip beside {menu}" + ); + session.click(&frame, &row); + let frame = session.settle(); + assert!(!frame.elements.contains_key(&menu), "{row} closes {menu}"); + assert_ne!( + session.node("n").unwrap().children, + before, + "{row} edits the page" + ); + session.undo(); + assert_eq!( + session.node("n").unwrap().children, + before, + "{row}: one undo step" + ); + } + } + + #[test] + fn column_resize_handle_of_a_hovered_table_focuses_that_table() { + let session = open_page(800, PlaygroundOptions::default(), |state| { + add(home(state), "t", table(&[["a0", "b0"], ["a1", "b1"]])); + }); + let card = session.view(|v, _| { + let layout = v.flow_layout().unwrap(); + let block = layout.block("t").unwrap(); + let geom = v.current_page_geometry(1280.0); + ( + geom.column_x + block.x + 20.0, + crate::TOPBAR_HEIGHT + block.y + 12.0, + ) + }); + session.pointer(card.0, card.1, false); + let frame = session.settle(); + let (_, handle) = frame + .elements + .iter() + .find(|(id, _)| id.starts_with("overlay.table_col_resize.")) + .expect("hovering a table shows its column resize handles"); + let (x, y) = ( + handle.bounds.x + handle.bounds.width * 0.5, + handle.bounds.y + handle.bounds.height * 0.5, + ); + session + .headless + .dispatch_input(ui::PlatformInput::MouseDown(ui::MouseDownEvent { + button: ui::MouseButton::Left, + position: ui::point(ui::px(x), ui::px(y)), + modifiers: ui::Modifiers::default(), + click_count: 1, + first_mouse: false, + })); + session.platform.run_until_parked(); + let (focused, dragging) = session.view(|v, _| { + ( + v.table_cell.as_ref().map(|c| c.block_id.clone()), + v.table_cell + .as_ref() + .is_some_and(|c| c.col_resize_drag.is_some()), + ) + }); + assert_eq!(focused.as_deref(), Some("t")); + assert!(dragging); + } + + #[test] + fn read_only_linked_doc_card_opens_its_page_on_a_single_click() { + let options = PlaygroundOptions { + page_readonly: true, + ..PlaygroundOptions::default() + }; + let session = open_page(800, options, |state| { + state.workspace.create_page("doc-a", "Target", 2).unwrap(); + add( + home(state), + "e-linked", + BlockSpec::EmbedLinkedDoc { + page_id: "doc-a".into(), + style: "horizontal".into(), + caption: String::new(), + }, + ); + }); + let frame = session.settle(); + session.click(&frame, "page.block.e-linked.embed_card"); + let _ = session.settle(); + assert_eq!( + session + .view(|v, _| v.last_opened_embed_doc.clone()) + .as_deref(), + Some("doc-a") + ); + } + + #[test] + fn highlight_dropdown_starts_at_its_button_scrolls_to_the_last_row_and_clips_row_hits() { + let session = open_page(420, PlaygroundOptions::default(), |state| { + add(home(state), "p1", paragraph("Hello world")); + }); + session.overlay(OverlayEvent::SetSelection(Some(ActiveSelection { + block_id: "p1".into(), + start_utf16: 0, + end_utf16: 5, + }))); + let _ = session.settle(); + session.overlay(OverlayEvent::Format(FormatAction::Highlight)); + let frame = session.settle(); + let button = element(&frame, "overlay.format_toolbar.highlight").bounds; + let menu = element(&frame, "overlay.format_toolbar.highlight_menu").bounds; + assert_eq!( + menu.x, button.x, + "the menu starts at the left edge of `A ▾`" + ); + assert!( + menu.y + menu.height <= 420.0, + "the menu stays inside the window" + ); + let last = "overlay.format_toolbar.highlight.background.grey"; + assert!( + frame + .elements + .get(last) + .is_none_or(|row| row.bounds.y + row.bounds.height > menu.y + menu.height), + "the last row starts below the fold" + ); + + session.overlay(OverlayEvent::HighlightMenuScroll(-2_000.0)); + let frame = session.settle(); + let menu = element(&frame, "overlay.format_toolbar.highlight_menu").bounds; + let row = element(&frame, last).bounds; + assert!( + row.y >= menu.y && row.y + row.height <= menu.y + menu.height, + "scrolling reveals `{last}` inside the menu" + ); + + // The rows scrolled out above the menu take no clicks. + let written = session.written(); + session + .headless + .simulate_click(ui::point(ui::px(menu.x + 40.0), ui::px(menu.y - 2.0))); + session.platform.run_until_parked(); + let _ = session.settle(); + assert_eq!( + session.written(), + written, + "no color applied outside the menu" + ); + } +} diff --git a/blocksuite/crates/playground/src/overlays/tests_image_and_slash_media.rs b/blocksuite/crates/playground/src/overlays/tests_image_and_slash_media.rs index ae61bfb18c..ceb3fbd61b 100644 --- a/blocksuite/crates/playground/src/overlays/tests_image_and_slash_media.rs +++ b/blocksuite/crates/playground/src/overlays/tests_image_and_slash_media.rs @@ -54,9 +54,11 @@ fn image_selection_toolbar_resize_align_caption_and_card_view_undo_cleanly() { }; tick(); - // 1. Scroll to `showcase-image` and select via real pointer click on `image_card`. + // 1. Scroll to `showcase-image` and select via real pointer click on `image_card`. The host + // saves downloads, so the toolbar offers `Download`. app.update(|cx| { win.update(cx, |v, _, cx| { + v.set_on_blob_download(Some(Box::new(|_| {}))); let y = v .flow_layout() .unwrap() @@ -93,10 +95,8 @@ fn image_selection_toolbar_resize_align_caption_and_card_view_undo_cleanly() { let violations = audit_frame_snapshot(&snap); assert!(violations.is_empty(), "audit violations: {violations:#?}"); assert!(snap.elements.contains_key("overlay.image_toolbar")); - assert!( - snap.elements - .contains_key("overlay.image_toolbar.card_view") - ); + assert!(snap.elements.contains_key("overlay.image_toolbar.download")); + assert!(snap.elements.contains_key("overlay.image_toolbar.more")); for corner in ["resize_nw", "resize_ne", "resize_sw", "resize_se"] { let key = format!("page.block.showcase-image.{corner}"); let el = snap @@ -227,25 +227,14 @@ fn image_selection_toolbar_resize_align_caption_and_card_view_undo_cleanly() { let img = blk.body.image_box().unwrap(); if expect_left_zero { assert_eq!(img.x, 0.0); - assert!( - !snap - .elements - .contains_key("page.block.showcase-image.resize_nw") - ); - assert!( - snap.elements - .contains_key("page.block.showcase-image.resize_se") - ); } else { assert!((img.right() - blk.body.width).abs() < 1.0); + } + for corner in ["resize_nw", "resize_ne", "resize_sw", "resize_se"] { assert!( snap.elements - .contains_key("page.block.showcase-image.resize_nw") - ); - assert!( - !snap - .elements - .contains_key("page.block.showcase-image.resize_se") + .contains_key(&format!("page.block.showcase-image.{corner}")), + "all four corner handles must remain visible regardless of alignment ({corner})" ); } }) diff --git a/blocksuite/crates/playground/src/overlays/tests_link_popup_and_block_submenus.rs b/blocksuite/crates/playground/src/overlays/tests_link_popup_and_block_submenus.rs new file mode 100644 index 0000000000..c5d115a3cf --- /dev/null +++ b/blocksuite/crates/playground/src/overlays/tests_link_popup_and_block_submenus.rs @@ -0,0 +1,327 @@ +//! Deterministic tests for the link popup dropdown rows under real clicks, the hover leave +//! delay of the link popup under a moving pointer, and the closing of block toolbar submenus. + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use blocksuite_playground_doc::{ + read::BlockContent, + schema::{BlockSpec, ParagraphType}, + session::PageDocSession, + }; + use y_octo::{Any, TextAttributes}; + + use crate::{ + HOME_PAGE_ID, PlaygroundTheme, TOPBAR_HEIGHT, + editor_session::DocPoint, + overlays::{ + ActiveSelection, BlockToolbarSubmenu, BookmarkCardStyle, BookmarkToolbarAction, + CalloutAction, LINK_HOVER_DELAY_MS, OverlayEvent, marks_in_range, + }, + room_client::DocState, + }; + + use super::super::tests::{Session, element, open}; + + /// A page with a note `n` whose blocks `build` adds. + fn open_page(build: impl FnOnce(&mut PageDocSession)) -> Session { + let session = open(1280, 800, PlaygroundTheme::Light); + let mut state = DocState::new("link-popup-submenus", 93).unwrap(); + state + .workspace + .create_page(HOME_PAGE_ID, "Page", 1) + .unwrap(); + { + let page = state.workspace.page_mut(HOME_PAGE_ID).unwrap(); + page.add_block( + "page-root", + BlockSpec::Page { + title: "Page".into(), + }, + None, + None, + 1, + ) + .unwrap(); + page.add_block( + "n", + BlockSpec::Note { + xywh: Some("[0,0,800,600]".into()), + }, + Some("page-root"), + None, + 2, + ) + .unwrap(); + build(page); + } + session.view(|v, cx| v.set_document(state, cx)); + let _ = session.settle(); + session + } + + fn linked_paragraph( + page: &mut PageDocSession, + id: &str, + text: &str, + link: (u64, u64), + url: &str, + ) { + page.add_block( + id, + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: text.into(), + }, + Some("n"), + None, + 3, + ) + .unwrap(); + page.format_text( + id, + "prop:text", + link.0, + link.1, + TextAttributes::from([("link".to_string(), Any::String(url.into()))]), + 4, + ) + .unwrap(); + } + + #[test] + fn link_popup_view_and_more_rows_act_on_a_real_click() { + let session = open_page(|page| { + linked_paragraph( + page, + "p-card", + "Visit AFFiNE docs", + (6, 6), + "https://www.affine.pro/docs/", + ); + linked_paragraph( + page, + "p-unlink", + "Read the guide", + (9, 5), + "https://example.com/", + ); + }); + + // `Inline view ▾` -> `Card view`: the press on the row lies outside the capsule. + session.overlay(OverlayEvent::SetSelection(Some(ActiveSelection::caret( + "p-card", 8, + )))); + let frame = session.settle(); + session.click(&frame, "overlay.link_popup.view"); + let frame = session.settle(); + session.click(&frame, "overlay.link_popup.card"); + let _ = session.settle(); + let note = session.node("n").expect("note"); + let card_at = note + .children + .iter() + .position(|c| matches!(&c.content, BlockContent::Bookmark { url, .. } if url == "https://www.affine.pro/docs/")) + .expect("Card view adds a bookmark card"); + assert_eq!( + note.children[card_at - 1].id, + "p-card", + "the card goes right below the link" + ); + assert_eq!(marks_in_range(&session.text("p-card"), 6, 12).link, None); + + // `⋮ More` -> `Remove link`. + session.overlay(OverlayEvent::SetSelection(Some(ActiveSelection::caret( + "p-unlink", 11, + )))); + let frame = session.settle(); + session.click(&frame, "overlay.link_popup.more"); + let frame = session.settle(); + session.click(&frame, "overlay.link_popup.unlink"); + let _ = session.settle(); + assert_eq!(marks_in_range(&session.text("p-unlink"), 9, 14).link, None); + } + + #[test] + fn hover_link_popup_closes_after_leave_delay_while_pointer_keeps_moving() { + let session = open_page(|page| { + linked_paragraph( + page, + "p-link", + "Visit AFFiNE site", + (6, 6), + "https://affine.pro/", + ); + }); + let (hx, hy) = session.view(|v, _| { + let layout = v.flow_layout().unwrap(); + let block = layout.block("p-link").unwrap(); + let geom = v.current_page_geometry(1280.0); + let caret = block.caret_rect(DocPoint::new("p-link", 8).caret).unwrap(); + ( + geom.column_x + caret.x + 4.0, + TOPBAR_HEIGHT + caret.y + caret.h * 0.5, + ) + }); + session.pointer(hx, hy, false); + session + .platform + .advance_clock(Duration::from_millis(LINK_HOVER_DELAY_MS as u64 + 10)); + session.platform.run_until_parked(); + assert!(session.settle().elements.contains_key("overlay.link_popup")); + + // Leave the link and keep moving every 80 ms over empty page space. + for step in 0..4 { + session.pointer(1200.0, 700.0 - step as f32 * 6.0, false); + assert!( + session.frame().elements.contains_key("overlay.link_popup"), + "{} ms after leaving the popup is still in its 250 ms leave delay", + step * 80 + ); + session.platform.advance_clock(Duration::from_millis(80)); + session.platform.run_until_parked(); + } + assert!( + !session.settle().elements.contains_key("overlay.link_popup"), + "320 ms of pointer moves after leaving must close the hover popup" + ); + } + + #[test] + fn block_toolbar_submenus_close_on_actions_reselection_and_outside_press() { + let session = open_page(|page| { + page.add_block( + "b-bm", + BlockSpec::Bookmark { + url: "https://affine.pro".into(), + title: Some("AFFiNE".into()), + description: None, + }, + Some("n"), + None, + 3, + ) + .unwrap(); + page.add_block( + "b-callout", + BlockSpec::Callout { + icon: "\u{1F4A1}".into(), + background_color: Some("grey".into()), + }, + Some("n"), + None, + 4, + ) + .unwrap(); + page.add_block( + "b-other", + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: "Other".into(), + }, + Some("n"), + None, + 5, + ) + .unwrap(); + }); + let open_menu = |block: &str, sub: BlockToolbarSubmenu, menu: &str| { + session.overlay(OverlayEvent::SelectBlock(block.into())); + session.overlay(OverlayEvent::ToggleBlockSubmenu(sub)); + assert!(session.settle().elements.contains_key(menu), "{menu} opens"); + }; + let cases = [ + ( + "b-bm", + BlockToolbarSubmenu::BookmarkStyle("b-bm".into()), + "overlay.bookmark_toolbar.style_menu", + OverlayEvent::BookmarkToolbarAction { + block_id: "b-bm".into(), + action: BookmarkToolbarAction::SetStyle(BookmarkCardStyle::List), + }, + ), + ( + "b-bm", + BlockToolbarSubmenu::BookmarkMore("b-bm".into()), + "overlay.bookmark_toolbar.more_menu", + OverlayEvent::BookmarkToolbarAction { + block_id: "b-bm".into(), + action: BookmarkToolbarAction::Copy, + }, + ), + ( + "b-callout", + BlockToolbarSubmenu::CalloutColor("b-callout".into()), + "overlay.callout_toolbar.color_menu", + OverlayEvent::CalloutAction { + block_id: "b-callout".into(), + action: CalloutAction::SetBackground("blue".into()), + }, + ), + ( + "b-callout", + BlockToolbarSubmenu::CalloutMore("b-callout".into()), + "overlay.callout_toolbar.more_menu", + OverlayEvent::CalloutAction { + block_id: "b-callout".into(), + action: CalloutAction::Delete, + }, + ), + ]; + for (block, sub, menu, action) in cases { + open_menu(block, sub, menu); + session.overlay(action); + assert!( + !session.settle().elements.contains_key(menu), + "{menu} closes after its action" + ); + } + + // Selecting another block and coming back shows the toolbar without the old submenu. + open_menu( + "b-bm", + BlockToolbarSubmenu::BookmarkMore("b-bm".into()), + "overlay.bookmark_toolbar.more_menu", + ); + session.overlay(OverlayEvent::SelectBlock("b-other".into())); + session.overlay(OverlayEvent::SelectBlock("b-bm".into())); + let frame = session.settle(); + assert!(frame.elements.contains_key("overlay.bookmark_toolbar")); + assert!( + !frame + .elements + .contains_key("overlay.bookmark_toolbar.more_menu") + ); + + // A press outside the submenu and its toolbar closes it; a press on the toolbar does not. + open_menu( + "b-bm", + BlockToolbarSubmenu::BookmarkMore("b-bm".into()), + "overlay.bookmark_toolbar.more_menu", + ); + let frame = session.settle(); + let bar = element(&frame, "overlay.bookmark_toolbar").bounds; + session.headless.simulate_click(ui::point( + ui::px(bar.x + 2.0), + ui::px(bar.y + bar.height * 0.5), + )); + session.platform.run_until_parked(); + assert!( + session + .settle() + .elements + .contains_key("overlay.bookmark_toolbar.more_menu") + ); + session + .headless + .simulate_click(ui::point(ui::px(1276.0), ui::px(TOPBAR_HEIGHT * 0.5))); + session.platform.run_until_parked(); + assert!( + !session + .settle() + .elements + .contains_key("overlay.bookmark_toolbar.more_menu") + ); + } +} diff --git a/blocksuite/crates/playground/src/overlays/tests_popovers_toolbars.rs b/blocksuite/crates/playground/src/overlays/tests_popovers_toolbars.rs index 532e0fc7d0..3809660bd9 100644 --- a/blocksuite/crates/playground/src/overlays/tests_popovers_toolbars.rs +++ b/blocksuite/crates/playground/src/overlays/tests_popovers_toolbars.rs @@ -186,8 +186,8 @@ mod tests { first_y, settled_popup.y, "link_popup must not shift y while fading in" ); - assert!(after_500.elements.contains_key("overlay.link_popup.card")); - assert!(after_500.elements.contains_key("overlay.link_popup.embed")); + assert!(after_500.elements.contains_key("overlay.link_popup.view")); + assert!(after_500.elements.contains_key("overlay.link_popup.more")); // Real pointer walks across the bridge gap onto `overlay.link_popup` without closing it. let mid_y = (hy + settled_popup.y) * 0.5; session.pointer(hx, mid_y, false); diff --git a/blocksuite/crates/playground/src/overlays/tests_slash_linked_table.rs b/blocksuite/crates/playground/src/overlays/tests_slash_linked_table.rs index 813f1a073d..f9c2eaeafc 100644 --- a/blocksuite/crates/playground/src/overlays/tests_slash_linked_table.rs +++ b/blocksuite/crates/playground/src/overlays/tests_slash_linked_table.rs @@ -1093,14 +1093,35 @@ mod tests { "1 Undo must revert the entire column resize drag" ); - // 3. Real mouse click on `Row ···` button -> axis menu opens -> `Escape` dismisses it, - // then click `Col ···` -> outside click dismisses it! + // 3. Hover table so the three-dot axis pills appear, click Row pill -> axis menu opens -> + // `Escape` dismisses it, then click Col pill -> outside click dismisses it! + let tbl_bounds = app.update(|cx| { + win.update(cx, |_, w, _| { + w.frame_snapshot() + .elements + .get("page.block.tbl") + .expect("table block mounted") + .bounds + }) + .unwrap() + }); + hw.dispatch_input(PlatformInput::MouseMove(ui::MouseMoveEvent { + position: point( + px(tbl_bounds.x + tbl_bounds.width * 0.5), + px(tbl_bounds.y + tbl_bounds.height * 0.5), + ), + pressed_button: None, + modifiers: Modifiers::default(), + })); + platform.advance_clock(std::time::Duration::from_millis(250)); + platform.run_until_parked(); + hw.request_frame(); let row_menu_btn = app.update(|cx| { win.update(cx, |_, w, _| { w.frame_snapshot() .elements - .get("overlay.table_toolbar.row_menu") - .expect("row_menu button mounted") + .get("overlay.table_hover.row_pill") + .expect("row_pill button mounted") .bounds }) .unwrap() @@ -1147,11 +1168,11 @@ mod tests { "Escape must dismiss table axis_menu" ); - // Click Col ··· then click outside -> on_mouse_down_out dismisses axis_menu. + // Click Col pill then click outside -> on_mouse_down_out dismisses axis_menu. let col_menu_btn = after_esc .elements - .get("overlay.table_toolbar.col_menu") - .expect("col_menu button mounted") + .get("overlay.table_hover.col_pill") + .expect("col_pill button mounted") .bounds; let cmx = col_menu_btn.x + col_menu_btn.width * 0.5; let cmy = col_menu_btn.y + col_menu_btn.height * 0.5; diff --git a/blocksuite/crates/playground/src/overlays/view.rs b/blocksuite/crates/playground/src/overlays/view.rs index 77ff79fc0c..f02acf0bba 100644 --- a/blocksuite/crates/playground/src/overlays/view.rs +++ b/blocksuite/crates/playground/src/overlays/view.rs @@ -51,6 +51,7 @@ impl PlaygroundView { let selected_image_block = self.selected_image_block_id(layout); let selected_attachment_block = self.selected_attachment_block_id(layout); let selected_bookmark_block = self.selected_bookmark_block_id(layout); + let selected_embed_block = self.selected_embed_block_id(layout); let selected_callout_block = self.selected_callout_block_id(layout); let selected_latex_block = self.selected_latex_block_id(layout); let avail_win_h = @@ -72,8 +73,10 @@ impl PlaygroundView { is_touch: self.is_touch_host(), focused_code_block, selected_image_block, + can_download_blobs: self.images.can_deliver_downloads(), selected_attachment_block, selected_bookmark_block, + selected_embed_block, selected_callout_block, selected_latex_block, selection, @@ -142,6 +145,9 @@ impl PlaygroundView { window: &mut Window, cx: &mut Context, ) { + if event.closes_block_submenu() && self.overlays.close_block_submenu() { + cx.notify(); + } match &event { OverlayEvent::OpenImageLightbox(_) => { self.dismiss_all_database_authoring(None, cx); @@ -636,7 +642,7 @@ impl PlaygroundView { && let Some(clean) = blocksuite_editor::clipboard::sanitize::sanitize_url(url) .filter(|u| !u.starts_with('#')) { - self.pending_link_hover = None; + self.link_hover_pending = None; self.link_hover_timer = None; self.overlays.close_link_popup(now_ms); self.last_opened_link_url = Some(clean.clone()); diff --git a/blocksuite/crates/playground/src/overlays/view_callout_bar.rs b/blocksuite/crates/playground/src/overlays/view_callout_bar.rs index eafe060b4c..5ff265ec22 100644 --- a/blocksuite/crates/playground/src/overlays/view_callout_bar.rs +++ b/blocksuite/crates/playground/src/overlays/view_callout_bar.rs @@ -32,6 +32,22 @@ impl PlaygroundView { .map(|b| b.block_id.as_str()) } + /// Single selected `EmbedLinkedDoc`, `EmbedSyncedDoc`, or `ExternalEmbed` block id in Page mode. + pub(crate) fn selected_embed_block_id<'a>(&self, layout: &'a FlowLayout) -> Option<&'a str> { + if self.editor.selection.is_some() || self.editor.block_selection.len() != 1 { + return None; + } + layout + .block(&self.editor.block_selection[0]) + .filter(|b| { + matches!( + b.body.kind, + FlowKind::EmbedLinkedDoc | FlowKind::EmbedSyncedDoc | FlowKind::ExternalEmbed + ) + }) + .map(|b| b.block_id.as_str()) + } + /// Single selected `affine:callout` block id in Page mode, if any. pub(crate) fn selected_callout_block_id<'a>(&self, layout: &'a FlowLayout) -> Option<&'a str> { if self.editor.selection.is_some() || self.editor.block_selection.len() != 1 { @@ -96,6 +112,10 @@ impl PlaygroundView { self.run_bookmark_toolbar_action(block_id, *action, window, cx); true } + OverlayEvent::EmbedToolbarAction { block_id, action } => { + self.run_embed_toolbar_action(block_id, *action, window, cx); + true + } _ => false, } } diff --git a/blocksuite/crates/playground/src/overlays/view_edits.rs b/blocksuite/crates/playground/src/overlays/view_edits.rs index 37f9fd948f..626e60c83f 100644 --- a/blocksuite/crates/playground/src/overlays/view_edits.rs +++ b/blocksuite/crates/playground/src/overlays/view_edits.rs @@ -105,6 +105,7 @@ impl PlaygroundView { DocEdit::CreateLinkedDocFromSelection => { self.run_create_linked_doc_from_selection(window, cx) } + DocEdit::CreateTableFromSelection => self.run_create_table_from_selection(window, cx), DocEdit::FormatMore(action) => self.run_format_more(action, window, cx), DocEdit::Equation { target, latex } => { self.equation_snapshot = None; @@ -466,7 +467,10 @@ impl PlaygroundView { } if matches!( command, - SlashCommand::Image | SlashCommand::Bookmark | SlashCommand::Attachment + SlashCommand::Image + | SlashCommand::Bookmark + | SlashCommand::Attachment + | SlashCommand::Pdf ) { return self.run_media_slash_command(block_id, node, command, strip, window, cx); } @@ -766,13 +770,9 @@ impl PlaygroundView { } } -/// What a slash command does to the document, and where it leaves the caret. #[derive(Clone)] enum SlashPlan { - /// Convert the block itself. Convert { caret: DocPoint }, - /// Add the new block below a block that cannot be converted. Insert { caret: DocPoint }, - /// Add a divider below the block, and an empty paragraph after it when `trailing`. Divider { trailing: bool, caret: DocPoint }, } diff --git a/blocksuite/crates/playground/src/overlays/view_embed_controls.rs b/blocksuite/crates/playground/src/overlays/view_embed_controls.rs index d911648f46..9b28b4fd97 100644 --- a/blocksuite/crates/playground/src/overlays/view_embed_controls.rs +++ b/blocksuite/crates/playground/src/overlays/view_embed_controls.rs @@ -596,6 +596,9 @@ impl PlaygroundView { } OverlayEvent::ImageToolbarAction { block_id, action } => { match action { + ImageToolbarAction::Download => { + self.download_media_block(block_id, cx); + } ImageToolbarAction::Caption => { self.dispatch_overlay( OverlayEvent::EditCaption { diff --git a/blocksuite/crates/playground/src/overlays/view_embed_toolbar.rs b/blocksuite/crates/playground/src/overlays/view_embed_toolbar.rs new file mode 100644 index 0000000000..845eec0ecc --- /dev/null +++ b/blocksuite/crates/playground/src/overlays/view_embed_toolbar.rs @@ -0,0 +1,273 @@ +//! PlaygroundView glue for the `overlay.embed_toolbar` actions on linked-doc, synced-doc, and +//! external embed blocks, including the `Inline` / `Card` / `Embed` view conversions. + +use blocksuite_editor::clipboard::sanitize::sanitize_url; +use blocksuite_playground_doc::{ + read::{BlockContent, BlockNode}, + schema::{BlockSpec, ParagraphType}, +}; +use ui::{Context, Window}; +use y_octo::{Any, SessionValue, TextAttributes}; + +use crate::{PlaygroundView, edgeless::paste_convert::json_to_any}; + +use super::{BlockMenuAction, DocEdit, EmbedToolbarAction, OverlayEvent, find_parent}; + +/// The block that replaces an embed block when its view changes. +struct ViewConversion { + spec: BlockSpec, + /// Properties that `spec` does not carry, written after the block is added. + props: Vec<(&'static str, Any)>, + /// Inline mark that covers the whole text of a paragraph target. + mark: Option<(&'static str, Any)>, +} + +/// The conversion `action` applies to `node`, or `None` when the block does not support it. +fn view_conversion(node: &BlockNode, action: EmbedToolbarAction) -> Option { + let params = node.props.get("prop:params").map(json_to_any); + let doc_props = || -> Vec<(&'static str, Any)> { + params.iter().map(|p| ("prop:params", p.clone())).collect() + }; + match (&node.content, action) { + ( + BlockContent::EmbedLinkedDoc { + page_id, caption, .. + }, + EmbedToolbarAction::ConvertToEmbed, + ) => Some(ViewConversion { + spec: BlockSpec::EmbedSyncedDoc { + page_id: page_id.clone(), + caption: caption.clone(), + }, + props: doc_props(), + mark: None, + }), + (BlockContent::EmbedSyncedDoc { page_id, caption }, EmbedToolbarAction::ConvertToCard) => { + Some(ViewConversion { + spec: BlockSpec::EmbedLinkedDoc { + page_id: page_id.clone(), + style: "horizontal".to_string(), + caption: caption.clone(), + }, + props: doc_props(), + mark: None, + }) + } + ( + BlockContent::EmbedLinkedDoc { page_id, .. } + | BlockContent::EmbedSyncedDoc { page_id, .. }, + EmbedToolbarAction::ConvertToInline, + ) => { + let mut reference = vec![ + ("type".to_string(), Any::String("LinkedPage".to_string())), + ("pageId".to_string(), Any::String(page_id.clone())), + ]; + reference.extend(params.map(|p| ("params".to_string(), p))); + Some(ViewConversion { + spec: BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: " ".to_string(), + }, + props: Vec::new(), + mark: Some(( + "reference", + Any::Object(Box::new(reference.into_iter().collect())), + )), + }) + } + ( + BlockContent::ExternalEmbed { + url, + title, + description, + caption, + .. + }, + EmbedToolbarAction::ConvertToCard | EmbedToolbarAction::ConvertToInline, + ) => { + let url = sanitize_url(url).filter(|u| !u.starts_with('#'))?; + if action == EmbedToolbarAction::ConvertToCard { + return Some(ViewConversion { + spec: BlockSpec::Bookmark { + url, + title: title.clone(), + description: description.clone(), + }, + props: (!caption.is_empty()) + .then(|| ("prop:caption", Any::String(caption.clone()))) + .into_iter() + .collect(), + mark: None, + }); + } + let label = title + .clone() + .filter(|t| !t.is_empty()) + .unwrap_or_else(|| url.clone()); + Some(ViewConversion { + spec: BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: label, + }, + props: Vec::new(), + mark: Some(("link", Any::String(url))), + }) + } + _ => None, + } +} + +impl PlaygroundView { + pub(super) fn run_embed_toolbar_action( + &mut self, + block_id: &str, + action: EmbedToolbarAction, + window: &mut Window, + cx: &mut Context, + ) { + let Some(node) = self + .snapshot + .as_ref() + .and_then(|s| s.block(block_id)) + .cloned() + else { + return; + }; + match action { + EmbedToolbarAction::Open => match &node.content { + BlockContent::EmbedLinkedDoc { page_id, .. } + | BlockContent::EmbedSyncedDoc { page_id, .. } => { + self.dispatch_overlay_event( + OverlayEvent::OpenEmbedDoc { + page_id: page_id.clone(), + }, + window, + cx, + ); + } + BlockContent::ExternalEmbed { url, .. } => { + if let Some(clean) = sanitize_url(url).filter(|u| !u.starts_with('#')) { + self.last_opened_link_url = Some(clean.clone()); + cx.open_url(&clean); + cx.notify(); + } + } + _ => {} + }, + EmbedToolbarAction::Caption => { + if !self.page_readonly { + self.dispatch_overlay_event( + OverlayEvent::EditCaption { + block_id: block_id.to_string(), + }, + window, + cx, + ); + } + } + EmbedToolbarAction::SetStyle(style) => { + if self.page_readonly { + return; + } + let _ = self.run_overlay_edit( + DocEdit::SetProp { + block_id: block_id.to_string(), + key: "prop:style", + value: Any::String(style.wire_value().to_string()), + }, + window, + cx, + ); + } + EmbedToolbarAction::Copy => { + let _ = self.execute_block_menu_action(block_id, BlockMenuAction::Copy, window, cx); + } + EmbedToolbarAction::Duplicate => { + let _ = self.execute_block_menu_action( + block_id, + BlockMenuAction::Duplicate, + window, + cx, + ); + } + EmbedToolbarAction::Delete => { + let _ = + self.execute_block_menu_action(block_id, BlockMenuAction::Delete, window, cx); + } + EmbedToolbarAction::ConvertToInline + | EmbedToolbarAction::ConvertToCard + | EmbedToolbarAction::ConvertToEmbed => { + if !self.page_readonly + && let Some(conversion) = view_conversion(&node, action) + { + self.replace_embed_block(block_id, conversion, window, cx); + } + } + } + } + + /// Replace `block_id` with the block of `conversion` at the same place in one undo step, + /// and select the new block. + fn replace_embed_block( + &mut self, + block_id: &str, + conversion: ViewConversion, + window: &mut Window, + cx: &mut Context, + ) { + let Some((parent_id, slot)) = self + .snapshot + .as_ref() + .and_then(|s| s.root.as_ref()) + .and_then(|root| find_parent(root, block_id)) + .map(|(parent, slot)| (parent.id.clone(), slot as u64)) + else { + return; + }; + let fresh = self.fresh_block_id(); + let now = self.now_ms(cx) as u64; + let before = self.selection_snapshot(); + let Ok(page) = self.page_mut() else { + return; + }; + let ViewConversion { spec, props, mark } = conversion; + let text_len = match &spec { + BlockSpec::Paragraph { text, .. } => text.encode_utf16().count() as u64, + _ => 0, + }; + let result = page.structural_edit(now, |page| { + page.add_block(&fresh, spec, Some(&parent_id), Some(slot + 1), now)?; + for (key, value) in props { + page.set_block_prop(&fresh, key, SessionValue::Any(value), now)?; + } + if let Some((name, value)) = mark { + page.format_text( + &fresh, + "prop:text", + 0, + text_len, + TextAttributes::from([(name.to_string(), value)]), + now, + )?; + } + page.delete_block_subtree(&parent_id, block_id, now)?; + Ok(()) + }); + let commit = match result { + Ok(commit) => commit, + Err(error) => { + eprintln!("embed view conversion: {error}"); + return; + } + }; + if commit.is_none() { + return; + } + if let Some(before) = before { + let _ = page.set_undo_selection_snapshot(before); + } + self.editor.last_typing = None; + self.did_edit(commit, None, window, cx); + self.set_block_selection(vec![fresh], false, window, cx); + } +} diff --git a/blocksuite/crates/playground/src/overlays/view_format_bar.rs b/blocksuite/crates/playground/src/overlays/view_format_bar.rs deleted file mode 100644 index d4f55347a8..0000000000 --- a/blocksuite/crates/playground/src/overlays/view_format_bar.rs +++ /dev/null @@ -1,1139 +0,0 @@ -//! Desktop `FormatToolbar` action handlers (`BlockSelection` format reading, dual-field -//! `Text`+`Link` editing, `InlineEquation`, `CreateLinkedDoc`, and `More: Copy/Duplicate/Delete`). - -use blocksuite_playground_doc::{ - DocError, DocResult, read::TextAlign as BlockAlign, schema::BlockSpec, -}; -use ui::{Context, Window}; -use y_octo::{Any, SessionValue, TextAttributes, TextDeltaOp, TextInsert}; - -use crate::{ - PlaygroundView, - block_flow::{FlowKind, FlowLayout, FlowRect}, - editor_session::{DocPoint, DocumentSelection}, -}; - -use super::{ - BlockFormatCache, BlockMenuAction, EquationTarget, FormatCache, FormatMoreAction, - LayoutCacheKey, MarkState, OverlayEvent, SelectionFormat, marks_in_range, -}; - -fn slice_utf16(text: &str, start: usize, end: usize) -> String { - if start >= end || text.is_empty() { - return String::new(); - } - let mut out = String::new(); - let mut u16_pos = 0usize; - let mut slice_start_byte: Option = None; - let mut slice_end_byte = text.len(); - let mut trailing_replacement = false; - - for (byte_idx, ch) in text.char_indices() { - let len = ch.len_utf16(); - let next_u16 = u16_pos + len; - if next_u16 <= start { - u16_pos = next_u16; - continue; - } - if u16_pos >= end { - if slice_start_byte.is_some() { - slice_end_byte = byte_idx; - } - break; - } - if u16_pos < start { - out.push('\u{FFFD}'); - if next_u16 >= end { - return out; - } - slice_start_byte = Some(byte_idx + ch.len_utf8()); - } else if next_u16 > end { - if slice_start_byte.is_some() { - slice_end_byte = byte_idx; - } - trailing_replacement = true; - break; - } else if slice_start_byte.is_none() { - slice_start_byte = Some(byte_idx); - } - u16_pos = next_u16; - } - if let Some(sb) = slice_start_byte - && sb < slice_end_byte - { - out.push_str(&text[sb..slice_end_byte]); - } - if trailing_replacement { - out.push('\u{FFFD}'); - } - out -} - -fn merge_shared_alignment(shared: &mut Option>, own: BlockAlign) { - *shared = Some(match *shared { - None => Some(own), - Some(all) => all.filter(|all| *all == own), - }); -} - -fn intersect_marks(marks: Option, slice: MarkState) -> MarkState { - match marks { - None => slice, - Some(all) => MarkState { - bold: all.bold && slice.bold, - italic: all.italic && slice.italic, - underline: all.underline && slice.underline, - strike: all.strike && slice.strike, - code: all.code && slice.code, - link: all.link.filter(|l| Some(l) == slice.link.as_ref()), - color: all.color.filter(|c| Some(c) == slice.color.as_ref()), - background: all - .background - .filter(|bg| Some(bg) == slice.background.as_ref()), - }, - } -} - -impl PlaygroundView { - /// What the formatting toolbar shows for the editor's selection: `None` unless the - /// selection is non-empty, no composition is running, and it covers paragraph or list - /// text only (or a whole-block `BlockSelection` covering paragraph/list blocks). - /// Marks, alignment, and single-block selected text are cached per selection and revision. - pub(crate) fn selection_format( - &mut self, - layout: &std::rc::Rc, - ) -> Option { - let Some(selection) = self.editor.selection.clone().filter(|s| !s.empty()) else { - if self.editor.composing() { - return None; - } - return self.block_selection_format(layout); - }; - if self.editor.composing() { - return None; - } - let fresh = self.overlays.format_cache.as_ref().is_some_and(|cache| { - cache.key.matches(self.doc_rev, layout) && cache.selection == selection - }); - if !fresh { - let value = self - .read_selection_format(&selection, layout) - .map(|(marks, align)| { - let selected_text = self - .single_block_selected_text(&selection, layout) - .map(ui::SharedString::from); - (marks, align, selected_text) - }); - self.overlays.format_cache = Some(FormatCache { - key: LayoutCacheKey::new(self.doc_rev, layout), - selection: selection.clone(), - value, - }); - } - let (marks, align, selected_text) = self.overlays.format_cache.as_ref()?.value.clone()?; - Some(SelectionFormat { - anchor_world: self.text_selection_geometry(layout)?.bounds()?, - marks, - align, - selected_text, - }) - } - - pub(super) fn read_selection_format( - &self, - selection: &DocumentSelection, - layout: &FlowLayout, - ) -> Option<(MarkState, Option)> { - let (start, end, a, b, _) = selection.ordered(layout)?; - let page = self.page()?; - let fallback_align = if layout.direction == ui::Direction::Rtl { - BlockAlign::Right - } else { - BlockAlign::Left - }; - let mut marks: Option = None; - let mut marks_absorbed = false; - // Every paragraph and list block the selection touches is aligned, empty ones too. - let mut shared_align: Option> = None; - for block in &layout.blocks[a..=b] { - let id = block.block_id.as_str(); - let is_text_block = - matches!(block.body.kind, FlowKind::Paragraph(_) | FlowKind::List(_)); - if is_text_block { - let own = block - .body - .text - .as_ref() - .map_or(fallback_align, |t| t.layout.block_align()); - merge_shared_alignment(&mut shared_align, own); - } - let from = if id == start.block_id { - start.offset() - } else { - 0 - }; - let to = if id == end.block_id { - end.offset() - } else { - block.body.plain.encode_utf16().count() as u64 - }; - if !block.editable() || to <= from { - continue; - } - // The title and code carry no inline marks; skip non-text blocks in cross-block - // selections so the desktop Format Bar stays mounted for the text blocks. - if !is_text_block { - if a == b { - return None; - } - continue; - } - if marks_absorbed { - continue; - } - let (text, _) = page.read_editable_text(id).ok()?; - let slice = marks_in_range(&text, from as usize, to as usize); - let next = intersect_marks(marks, slice); - if next.is_all_cleared() { - marks_absorbed = true; - } - marks = Some(next); - } - let marks = marks?; - Some((marks, shared_align.flatten())) - } - - /// Extract plain selected text for single-block selections so dual-field `LinkBar` - /// pre-fills its `Text` input. - pub(super) fn single_block_selected_text( - &self, - selection: &DocumentSelection, - layout: &FlowLayout, - ) -> Option { - if selection.anchor.block_id != selection.focus.block_id { - return None; - } - let block = layout.block(&selection.anchor.block_id)?; - let from = selection.anchor.offset().min(selection.focus.offset()) as usize; - let to = selection.anchor.offset().max(selection.focus.offset()) as usize; - if to <= from { - return None; - } - Some(slice_utf16(&block.body.plain, from, to)) - } - - /// Build a [`SelectionFormat`] for whole-block `BlockSelection` covering paragraph or list - /// blocks so the desktop Format Bar mounts on `Esc` / block selection. - pub(super) fn block_selection_format( - &mut self, - layout: &std::rc::Rc, - ) -> Option { - if self.editor.block_selection.is_empty() { - return None; - } - let cache_hit = self.overlays.block_format_cache.as_ref().is_some_and(|c| { - c.key.matches(self.doc_rev, layout) - && c.selected_ids.as_slice() == self.editor.block_selection.as_slice() - }); - if !cache_hit { - let computed = self.compute_block_selection_format(layout); - self.overlays.block_format_cache = Some(BlockFormatCache { - key: LayoutCacheKey::new(self.doc_rev, layout), - selected_ids: self.editor.block_selection.clone(), - value: computed, - }); - } - let (anchor_world, marks, align) = self - .overlays - .block_format_cache - .as_ref()? - .value - .as_ref()? - .clone(); - Some(SelectionFormat { - anchor_world, - marks, - align, - selected_text: None, - }) - } - - fn compute_block_selection_format( - &self, - layout: &FlowLayout, - ) -> Option<(FlowRect, MarkState, Option)> { - let page = self.page()?; - let mut selected: std::collections::HashSet<&str> = self - .editor - .block_selection - .iter() - .map(String::as_str) - .collect(); - let fallback_align = if layout.direction == ui::Direction::Rtl { - BlockAlign::Right - } else { - BlockAlign::Left - }; - let mut bounds: Option<(f32, f32, f32, f32)> = None; - let mut shared_align: Option> = None; - let mut marks: Option = None; - let mut marks_absorbed = false; - - for block in &layout.blocks { - if !selected.remove(block.block_id.as_str()) { - continue; - } - if matches!(block.body.kind, FlowKind::Paragraph(_) | FlowKind::List(_)) { - let r = block.rect(); - bounds = Some(match bounds { - None => (r.x, r.y, r.right(), r.bottom()), - Some((l, t, rb, b)) => { - (l.min(r.x), t.min(r.y), rb.max(r.right()), b.max(r.bottom())) - } - }); - let own = block - .body - .text - .as_ref() - .map_or(fallback_align, |t| t.layout.block_align()); - merge_shared_alignment(&mut shared_align, own); - - if !marks_absorbed && !block.body.plain.is_empty() { - let len = block.body.plain.encode_utf16().count(); - if len > 0 - && let Ok((text, _)) = page.read_editable_text(&block.block_id) - { - let slice = marks_in_range(&text, 0, len); - let next = intersect_marks(marks, slice); - if next.is_all_cleared() { - marks_absorbed = true; - } - marks = Some(next); - } - } - } - if selected.is_empty() { - break; - } - } - let (left, top, right, bottom) = bounds?; - let anchor_world = FlowRect::new(left, top, right - left, bottom - top); - Some(( - anchor_world, - marks.unwrap_or_default(), - shared_align.flatten(), - )) - } - - /// Apply dual-field `Text` + `Link` edit: replaces display text (if modified on a single-block - /// selection) and sets the `link` mark in one atomic undo step. - pub(super) fn apply_link_with_display_text( - &mut self, - url: Option, - expected_prev_url: Option, - expected_prev_text: Option, - display_text: Option, - window: &mut Window, - cx: &mut Context, - ) -> DocResult { - let Some(new_text) = display_text else { - return self.format_selection(None, Some((url, expected_prev_url)), window, cx); - }; - let Some(url_str) = url.clone() else { - return self.format_selection(None, Some((url, expected_prev_url)), window, cx); - }; - let Some(selection) = self.editor.selection.clone() else { - return Ok(()); - }; - if selection.anchor.block_id != selection.focus.block_id { - return self.format_selection(None, Some((url, expected_prev_url)), window, cx); - } - let block_id = selection.anchor.block_id.clone(); - let raw_from = selection.anchor.offset().min(selection.focus.offset()) as usize; - let raw_to = selection.anchor.offset().max(selection.focus.offset()) as usize; - if raw_to <= raw_from { - return Ok(()); - } - let Some((doc_text, _)) = self - .page() - .and_then(|p| p.read_editable_text(&block_id).ok()) - else { - return Ok(()); - }; - let live_len: usize = doc_text - .delta - .iter() - .map(|op| match op { - TextDeltaOp::Insert { - insert: TextInsert::Text(s), - .. - } => s.encode_utf16().count(), - TextDeltaOp::Insert { - insert: TextInsert::Embed(_), - .. - } => 1, - _ => 0, - }) - .sum(); - if raw_to > live_len { - return Ok(()); - } - if let Some(prev_text) = expected_prev_text.as_deref() - && slice_utf16(&doc_text.plain, raw_from, raw_to) != prev_text - { - return Ok(()); - } - let (from, to) = if let Some(prev_url) = expected_prev_url.as_deref() { - let spans = super::view_link_popup::matching_link_subranges( - &doc_text, raw_from, raw_to, prev_url, - ); - if spans.as_slice() != [(raw_from, raw_to)] { - return Ok(()); - } - (raw_from as u64, raw_to as u64) - } else { - (raw_from as u64, raw_to as u64) - }; - - // Preserve shared inline formatting attributes across `[from, to)` while updating `link`. - let shared = marks_in_range(&doc_text, from as usize, to as usize); - let mut attrs = TextAttributes::new(); - for (on, k) in [ - (shared.bold, "bold"), - (shared.italic, "italic"), - (shared.underline, "underline"), - (shared.strike, "strike"), - (shared.code, "code"), - ] { - if on { - attrs.insert(k.to_string(), Any::True); - } - } - if let Some(c) = shared.color { - attrs.insert("color".to_string(), Any::String(c)); - } - if let Some(bg) = shared.background { - attrs.insert("background".to_string(), Any::String(bg)); - } - attrs.insert("link".to_string(), Any::String(url_str)); - - let prop_key = self.editable_prop_for_block(&block_id); - let new_len = new_text.encode_utf16().count() as u64; - let now = self.now_ms(cx) as u64; - let before = self.selection_snapshot(); - let page = self.page_mut()?; - page.stop_capturing()?; - let mut delta = Vec::new(); - if from > 0 { - delta.push(TextDeltaOp::Retain { - retain: from, - format: None, - }); - } - delta.push(TextDeltaOp::Delete { delete: to - from }); - delta.push(TextDeltaOp::Insert { - insert: TextInsert::Text(new_text), - format: Some(attrs), - }); - let commit = page.apply_text_delta(&block_id, prop_key, &delta, now)?; - if commit.is_some() - && let Some(before) = before - { - page.set_undo_selection_snapshot(before)?; - } - page.stop_capturing()?; - self.editor.selection = Some(DocumentSelection { - anchor: DocPoint::new(&block_id, from), - focus: DocPoint::new(&block_id, from + new_len), - }); - self.editor.last_typing = None; - self.did_edit(commit, Some(&block_id), window, cx); - Ok(()) - } - - /// Convert the current text selection into an inline LaTeX equation chip (`latex` attribute on a - /// single space) and open `EquationEditor` pre-filled with the selected text. - pub(super) fn run_inline_equation_from_selection( - &mut self, - window: &mut Window, - cx: &mut Context, - ) -> DocResult { - let Some(selection) = self.editor.selection.clone() else { - return Ok(()); - }; - if selection.empty() || selection.anchor.block_id != selection.focus.block_id { - return Ok(()); - } - let block_id = selection.anchor.block_id.clone(); - let from = selection.anchor.offset().min(selection.focus.offset()); - let to = selection.anchor.offset().max(selection.focus.offset()); - let initial = self - .flow_layout() - .and_then(|layout| self.single_block_selected_text(&selection, &layout)) - .unwrap_or_default(); - let prop_key = self.editable_prop_for_block(&block_id); - let Some((doc_text, _)) = self - .page() - .and_then(|p| p.read_editable_text(&block_id).ok()) - else { - return Ok(()); - }; - let live_len = doc_text.plain.encode_utf16().count() as u64; - let to = to.min(live_len); - if from > to { - return Ok(()); - } - let now = self.now_ms(cx) as u64; - let before = self.selection_snapshot(); - let page = self.page_mut()?; - page.stop_capturing()?; - let mut delta = Vec::new(); - if from > 0 { - delta.push(TextDeltaOp::Retain { - retain: from, - format: None, - }); - } - if to > from { - delta.push(TextDeltaOp::Delete { delete: to - from }); - } - delta.push(TextDeltaOp::Insert { - insert: TextInsert::Text(" ".to_string()), - format: Some(TextAttributes::from([( - "latex".to_string(), - Any::String(initial.clone()), - )])), - }); - let commit = page.apply_text_delta(&block_id, prop_key, &delta, now)?; - if commit.is_some() - && let Some(before) = before - { - page.set_undo_selection_snapshot(before)?; - } - page.stop_capturing()?; - self.editor.selection = Some(DocumentSelection::caret(DocPoint::new(&block_id, from + 1))); - self.editor.last_typing = None; - self.did_edit(commit, Some(&block_id), window, cx); - self.dispatch_overlay_event( - OverlayEvent::OpenEquationEditor { - target: EquationTarget::Inline { - block_id, - utf16_offset: from, - }, - initial, - }, - window, - cx, - ); - Ok(()) - } - - /// Create a linked document titled with the selected text and replace the selection with an - /// inline `@reference` (`LinkedPage`) chip in one atomic undo step. - pub(super) fn run_create_linked_doc_from_selection( - &mut self, - window: &mut Window, - cx: &mut Context, - ) -> DocResult { - let Some(selection) = self.editor.selection.clone() else { - return Ok(()); - }; - if selection.empty() || selection.anchor.block_id != selection.focus.block_id { - return Ok(()); - } - let block_id = selection.anchor.block_id.clone(); - let from = selection.anchor.offset().min(selection.focus.offset()); - let to = selection.anchor.offset().max(selection.focus.offset()); - let title = self - .flow_layout() - .and_then(|layout| self.single_block_selected_text(&selection, &layout)) - .map(|t| t.trim().to_string()) - .filter(|t| !t.is_empty()) - .unwrap_or_else(|| "Untitled".to_string()); - let summary = self - .doc_directory_mut() - .create_linked_doc(&title, crate::directory::EditorDocMode::Page, None) - .map_err(|err| DocError::InvalidState(err.to_string()))?; - let now = self.now_ms(cx) as u64; - self.ensure_workspace_page_and_broadcast(&summary, now) - .map_err(|err| DocError::InvalidState(err.to_string()))?; - self.insert_inline_reference_chip( - &block_id, - from, - to - from, - summary.id.as_str(), - window, - cx, - ) - } - - /// Execute `Copy` / `Duplicate` / `Delete` from the desktop Format Bar's `More (...)` menu. - pub(super) fn run_format_more( - &mut self, - action: FormatMoreAction, - window: &mut Window, - cx: &mut Context, - ) -> DocResult { - let target_block = self - .editor - .selection - .as_ref() - .map(|s| s.focus.block_id.clone()) - .or_else(|| self.editor.block_selection.first().cloned()); - let Some(block_id) = target_block else { - return Ok(()); - }; - let mapped = match action { - FormatMoreAction::Copy => BlockMenuAction::Copy, - FormatMoreAction::Duplicate => BlockMenuAction::Duplicate, - FormatMoreAction::Delete => BlockMenuAction::Delete, - }; - self.execute_block_menu_action(&block_id, mapped, window, cx) - } - - /// Apply alignment to `Paragraph` and `List` blocks in `block_selection` when no text selection is active. - pub(super) fn align_block_selection( - &mut self, - align: BlockAlign, - window: &mut Window, - cx: &mut Context, - ) -> DocResult { - let Some(layout) = self.flow_layout() else { - return Ok(()); - }; - let ids: Vec = self - .editor - .block_selection - .iter() - .filter(|id| { - layout.block(id).is_some_and(|b| { - matches!(b.body.kind, FlowKind::Paragraph(_) | FlowKind::List(_)) - }) - }) - .cloned() - .collect(); - if ids.is_empty() { - return Ok(()); - } - let before = self.selection_snapshot(); - let now = self.now_ms(cx) as u64; - let page = self.page_mut()?; - page.stop_capturing()?; - let commit = page.structural_edit(now, |page| { - for id in &ids { - page.set_block_prop( - id, - "prop:textAlign", - SessionValue::Any(Any::String(align.as_str().to_string())), - now, - )?; - } - Ok(()) - })?; - if commit.is_some() - && let Some(before) = before - { - page.set_undo_selection_snapshot(before)?; - } - page.stop_capturing()?; - self.editor.last_typing = None; - self.did_edit(commit, None, window, cx); - Ok(()) - } - - /// Create an empty child paragraph inside an empty `affine:callout` and focus the caret in it. - pub(crate) fn focus_or_create_callout_child( - &mut self, - callout_id: &str, - window: &mut Window, - cx: &mut Context, - ) -> bool { - if self.page_readonly { - return false; - } - let first_child = self - .snapshot - .as_ref() - .and_then(|s| s.block(callout_id)) - .and_then(|n| n.children.first().map(|c| c.id.clone())); - if let Some(child_id) = first_child { - self.select_document_range( - DocumentSelection::caret(DocPoint::new(&child_id, 0)), - window, - cx, - ); - return true; - } - let new_id = self.fresh_block_id(); - let now = self.now_ms(cx) as u64; - let before = self.selection_snapshot(); - let commit = self.page_mut().ok().and_then(|page| { - let _ = page.stop_capturing(); - let c = page - .add_block( - &new_id, - BlockSpec::Paragraph { - paragraph_type: blocksuite_playground_doc::schema::ParagraphType::Text, - text: String::new(), - }, - Some(callout_id), - Some(0), - now, - ) - .ok() - .flatten(); - if c.is_some() - && let Some(before) = before - { - let _ = page.set_undo_selection_snapshot(before); - } - let _ = page.stop_capturing(); - c - }); - if commit.is_some() { - self.did_edit(commit, None, window, cx); - self.select_document_range( - DocumentSelection::caret(DocPoint::new(&new_id, 0)), - window, - cx, - ); - return true; - } - false - } -} - -impl PlaygroundView { - /// Focus a trailing empty paragraph or append a new empty paragraph below the last block - /// when the user clicks empty canvas space below the page's final block. - pub(super) fn handle_click_below_last_block( - &mut self, - last: &crate::block_flow::FlowBlock, - window: &mut Window, - cx: &mut Context, - ) { - if self.page_readonly { - return; - } - self.commit_active_preedit(window, cx); - if matches!(last.body.kind, FlowKind::Paragraph(_)) && last.body.plain.is_empty() { - self.select_document_range( - DocumentSelection::caret(DocPoint::new(&last.block_id, 0)), - window, - cx, - ); - window.request_virtual_keyboard(); - return; - } - let note_id = self.snapshot.as_ref().and_then(|snap| { - let root = snap.root.as_ref()?; - root.children - .iter() - .find(|c| c.is_page_visible_note() && c.walk().any(|n| n.id == last.block_id)) - .or_else(|| root.children.iter().find(|c| c.is_page_visible_note())) - .map(|c| c.id.clone()) - }); - let Some(note_id) = note_id else { - return; - }; - let before = self.selection_snapshot(); - let new_id = self.fresh_block_id(); - let now_ms = self.now_ms(cx) as u64; - let commit = self.page_mut().ok().and_then(|page| { - let _ = page.stop_capturing(); - let commit = page - .add_block( - &new_id, - BlockSpec::Paragraph { - paragraph_type: blocksuite_playground_doc::schema::ParagraphType::Text, - text: String::new(), - }, - Some(¬e_id), - None, - now_ms, - ) - .ok() - .flatten(); - if commit.is_some() - && let Some(before) = before - { - let _ = page.set_undo_selection_snapshot(before); - } - let _ = page.stop_capturing(); - commit - }); - if commit.is_some() { - self.did_edit(commit, None, window, cx); - self.select_document_range( - DocumentSelection::caret(DocPoint::new(&new_id, 0)), - window, - cx, - ); - window.request_virtual_keyboard(); - } - } -} - -#[cfg(test)] -mod tests { - use std::{cell::RefCell, rc::Rc}; - - use blocksuite_playground_doc::{ - read::TextAlign as BlockAlign, - schema::{BlockSpec, ParagraphType}, - }; - use ui::{ - AppContext as _, Application, Bounds, Direction, HeadlessPlatform, WindowBounds, - WindowHandle, WindowOptions, point, px, size, - }; - use y_octo::{Any, SessionValue}; - - use super::slice_utf16; - use crate::{ - DocState, PlaygroundOptions, PlaygroundView, - editor_session::{DocPoint, DocumentSelection}, - theme::register_bundled_fonts, - }; - - fn ref_slice_utf16(text: &str, start: usize, end: usize) -> String { - let units: Vec = text.encode_utf16().collect(); - let s = start.min(units.len()); - let e = end.min(units.len()); - if s >= e { - String::new() - } else { - String::from_utf16_lossy(&units[s..e]) - } - } - - #[test] - fn slice_utf16_matches_encode_utf16_across_bmp_surrogates_and_bounds() { - let samples = [ - "", - "hello world", - "a😀b", - "😀😀", - "中文🚀测试✨end", - "x\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}y", - ]; - for sample in samples { - let max_u16 = sample.encode_utf16().count(); - for start in 0..=(max_u16 + 2) { - for end in 0..=(max_u16 + 2) { - assert_eq!( - slice_utf16(sample, start, end), - ref_slice_utf16(sample, start, end), - "sample={sample:?} start={start} end={end}" - ); - } - } - } - } - - fn with_view( - direction: Direction, - f: impl FnOnce(&ui::ApplicationHandle, &WindowHandle, &ui::HeadlessWindow), - ) { - let platform = HeadlessPlatform::new(960, 640, 1.0); - let handle_cell: Rc>>> = - Rc::new(RefCell::new(None)); - let handle_out = handle_cell.clone(); - let app = Application::with_platform(platform.clone()).run_embedded(move |cx| { - register_bundled_fonts(cx).expect("fonts"); - let window = cx - .open_window( - WindowOptions { - window_bounds: Some(WindowBounds::Windowed(Bounds::new( - point(px(0.0), px(0.0)), - size(px(960.0), px(640.0)), - ))), - ..Default::default() - }, - |window, cx| { - window.set_root_layout_direction(direction); - cx.new(|cx| PlaygroundView::with_options(PlaygroundOptions::default(), cx)) - }, - ) - .expect("open window"); - *handle_out.borrow_mut() = Some(window); - }); - let window = handle_cell.borrow_mut().take().expect("window"); - let headless_win = platform.windows().into_iter().next().expect("headless win"); - f(&app, &window, &headless_win); - } - - #[test] - fn selection_format_reads_inherited_ltr_rtl_and_absorbing_block_selection_alignment() { - let cases = [ - (Direction::Ltr, Some("center"), None, BlockAlign::Center), - (Direction::Rtl, None, None, BlockAlign::Right), - (Direction::Rtl, None, Some("left"), BlockAlign::Left), - ]; - for (dir, parent_align, child_align, expected) in cases { - with_view(dir, |app, window, headless_win| { - let mut doc = DocState::new("align-doc", 91).expect("doc"); - doc.workspace - .create_page("align-doc", "Align", 1) - .expect("create page"); - let page = doc.workspace.page_mut("align-doc").expect("page"); - page.add_block( - "root", - BlockSpec::Page { - title: "Align".into(), - }, - None, - None, - 1, - ) - .expect("root"); - page.add_block( - "note", - BlockSpec::Note { xywh: None }, - Some("root"), - None, - 2, - ) - .expect("note"); - page.add_block( - "parent", - BlockSpec::Paragraph { - paragraph_type: ParagraphType::Text, - text: "Parent text".into(), - }, - Some("note"), - None, - 3, - ) - .expect("parent"); - if let Some(a) = parent_align { - page.set_block_prop( - "parent", - "prop:textAlign", - SessionValue::Any(Any::String(a.into())), - 4, - ) - .expect("parent align"); - } - page.add_block( - "child", - BlockSpec::Paragraph { - paragraph_type: ParagraphType::Text, - text: "Child text".into(), - }, - Some("parent"), - None, - 5, - ) - .expect("child"); - if let Some(a) = child_align { - page.set_block_prop( - "child", - "prop:textAlign", - SessionValue::Any(Any::String(a.into())), - 6, - ) - .expect("child align"); - } - // Extra trailing empty block with opposite alignment to test absorbing-state loop - // does not skip alignment/anchor computation for remaining blocks. - page.add_block( - "tail_empty", - BlockSpec::Paragraph { - paragraph_type: ParagraphType::Text, - text: String::new(), - }, - Some("note"), - None, - 7, - ) - .expect("tail"); - let opposite = match expected { - BlockAlign::Center => "right", - BlockAlign::Right => "center", - BlockAlign::Left => "center", - }; - page.set_block_prop( - "tail_empty", - "prop:textAlign", - SessionValue::Any(Any::String(opposite.into())), - 8, - ) - .expect("tail align"); - - app.update(|cx| { - window - .update(cx, |view, w, cx| { - view.set_document(doc, cx); - view.change_selection( - DocumentSelection { - anchor: DocPoint::new("child", 0), - focus: DocPoint::new("child", 5), - }, - w, - cx, - ); - }) - .expect("setup"); - }); - headless_win.request_frame(); - - app.update(|cx| { - window - .update(cx, |view, w, cx| { - let layout = view.flow_layout().expect("layout"); - let text_fmt = view.selection_format(&layout).expect("text format"); - assert_eq!( - text_fmt.align, - Some(expected), - "dir={dir:?} parent={parent_align:?} child={child_align:?} text" - ); - assert_eq!(text_fmt.selected_text.as_deref(), Some("Child")); - - // Whole-block selection on `child` alone matches expected alignment. - view.set_block_selection(vec!["child".into()], false, w, cx); - let blk_fmt = view.selection_format(&layout).expect("block format"); - assert_eq!(blk_fmt.align, Some(expected), "dir={dir:?} block single"); - - // Adding `tail_empty` (different alignment) after plain `child` (which - // already reaches mark absorbing state) must clear shared alignment - // and expand anchor_world to include `tail_empty`. - let child_rect = layout.block("child").unwrap().rect(); - let tail_rect = layout.block("tail_empty").unwrap().rect(); - view.set_block_selection( - vec!["child".into(), "tail_empty".into()], - false, - w, - cx, - ); - let multi_fmt = - view.selection_format(&layout).expect("multi block format"); - assert_eq!( - multi_fmt.align, None, - "mixed alignment must become None even after marks absorb" - ); - assert!( - multi_fmt.anchor_world.bottom() >= tail_rect.bottom() - 0.1 - && multi_fmt.anchor_world.y <= child_rect.y + 0.1 - ); - }) - .expect("verify"); - }); - }); - } - } - - #[test] - fn layout_cache_key_misses_new_rc_with_same_shape_and_duplicate_id_uses_first_row() { - with_view(Direction::Ltr, |app, window, headless_win| { - let mut doc = DocState::new("cache-doc", 92).expect("doc"); - doc.workspace - .create_page("cache-doc", "Cache", 1) - .expect("create page"); - let page = doc.workspace.page_mut("cache-doc").expect("page"); - page.add_block( - "root", - BlockSpec::Page { - title: "Cache".into(), - }, - None, - None, - 1, - ) - .expect("root"); - page.add_block( - "note", - BlockSpec::Note { xywh: None }, - Some("root"), - None, - 2, - ) - .expect("note"); - page.add_block( - "p1", - BlockSpec::Paragraph { - paragraph_type: ParagraphType::Text, - text: "Hello world".into(), - }, - Some("note"), - None, - 3, - ) - .expect("p1"); - - app.update(|cx| { - window - .update(cx, |view, w, cx| { - view.set_document(doc, cx); - view.set_block_selection(vec!["p1".into()], false, w, cx); - }) - .expect("setup"); - }); - headless_win.request_frame(); - - app.update(|cx| { - window - .update(cx, |view, w, _cx| { - let base_layout = view.flow_layout().expect("layout"); - let p1_orig = base_layout.block("p1").expect("p1"); - let make_p1 = |x: f32, y: f32| crate::block_flow::FlowBlock { - block_id: "p1".to_string(), - snapshot_id: p1_orig.snapshot_id.clone(), - x, - y, - has_gutter_chevron: false, - body: std::rc::Rc::clone(&p1_orig.body), - }; - let layout_a = std::rc::Rc::new(crate::block_flow::FlowLayout { - blocks: vec![make_p1(10.0, 20.0)], - width: 800.0, - height: 200.0, - direction: Direction::Ltr, - stats: Default::default(), - }); - let fmt_a = view.selection_format(&layout_a).expect("fmt a"); - assert_eq!(fmt_a.align, Some(BlockAlign::Left)); - assert!((fmt_a.anchor_world.x - 10.0).abs() < 0.01); - - // Drop layout_a before allocating layout_b with identical width, height, - // blocks.len(), and doc_rev to verify Weak ABA immunity. - drop(layout_a); - let layout_b = std::rc::Rc::new(crate::block_flow::FlowLayout { - blocks: vec![make_p1(58.0, 20.0)], - width: 800.0, - height: 200.0, - direction: Direction::Ltr, - stats: Default::default(), - }); - let fmt_b = view.selection_format(&layout_b).expect("fmt b"); - assert!((fmt_b.anchor_world.x - 58.0).abs() < 0.01); - - // Flip direction to RTL at the same doc_rev: fresh layout updates align. - w.set_root_layout_direction(Direction::Rtl); - let layout_rtl = view.ensure_layout(800.0, w).expect("rtl layout"); - let fmt_rtl = view.selection_format(&layout_rtl).expect("fmt rtl"); - assert_eq!(fmt_rtl.align, Some(BlockAlign::Right)); - - // Duplicate block_id in layout: first matching row wins for anchor_world. - let layout_dup = std::rc::Rc::new(crate::block_flow::FlowLayout { - blocks: vec![make_p1(58.0, 20.0), make_p1(999.0, 999.0)], - width: 800.0, - height: 200.0, - direction: Direction::Ltr, - stats: Default::default(), - }); - let fmt_dup = view.selection_format(&layout_dup).expect("fmt dup"); - assert!((fmt_dup.anchor_world.x - 58.0).abs() < 0.01); - assert!((fmt_dup.anchor_world.y - 20.0).abs() < 0.01); - assert!(fmt_dup.anchor_world.right() < 900.0); - - // Overlays::reset drops all caches. - view.overlays.reset(); - assert!(view.overlays.format_cache.is_none()); - assert!(view.overlays.block_format_cache.is_none()); - assert!(view.overlays.block_selection_rects_cache.is_none()); - }) - .expect("verify"); - }); - }); - } -} diff --git a/blocksuite/crates/playground/src/overlays/view_format_bar/actions.rs b/blocksuite/crates/playground/src/overlays/view_format_bar/actions.rs new file mode 100644 index 0000000000..067e68661b --- /dev/null +++ b/blocksuite/crates/playground/src/overlays/view_format_bar/actions.rs @@ -0,0 +1,501 @@ +//! `FormatToolbar` mutation actions and trailing-canvas click handler. + +use super::{ + Any, BlockAlign, BlockMenuAction, BlockSpec, Context, DocError, DocPoint, DocResult, + DocumentSelection, EquationTarget, FlowKind, FormatMoreAction, OverlayEvent, PlaygroundView, + SessionValue, TextAttributes, TextDeltaOp, TextInsert, Window, marks_in_range, slice_utf16, + view_link_popup, +}; + +impl PlaygroundView { + /// Insert a 2 × 2 table below the text selection or the last selected block, and focus its + /// first cell. + pub(crate) fn run_create_table_from_selection( + &mut self, + window: &mut Window, + cx: &mut Context, + ) -> DocResult { + let Some(anchor) = self + .editor + .selection + .as_ref() + .map(|s| s.focus.block_id.clone()) + .or_else(|| self.editor.block_selection.last().cloned()) + else { + return Ok(()); + }; + let empty_row = vec![String::new(), String::new()]; + let spec = BlockSpec::Table { + rows: vec![empty_row.clone(), empty_row], + }; + let Some(table_id) = + self.insert_sibling_after_block(&anchor, spec, false, true, window, cx)? + else { + return Ok(()); + }; + let first_cell = self + .snapshot + .as_ref() + .and_then(|s| s.block(&table_id)) + .and_then(|n| match &n.content { + blocksuite_playground_doc::read::BlockContent::Table(t) => Some(( + t.rows.first()?.row_id.clone(), + t.columns.first()?.column_id.clone(), + )), + _ => None, + }); + if let Some((row_id, column_id)) = first_cell { + self.editor.selection = None; + self.clear_block_selection_fields(); + self.focus_table_cell(table_id, row_id, column_id, None, window, cx); + } + Ok(()) + } + + /// Apply dual-field `Text` + `Link` edit: replaces display text (if modified on a single-block + /// selection) and sets the `link` mark in one atomic undo step. + pub(crate) fn apply_link_with_display_text( + &mut self, + url: Option, + expected_prev_url: Option, + expected_prev_text: Option, + display_text: Option, + window: &mut Window, + cx: &mut Context, + ) -> DocResult { + let Some(new_text) = display_text else { + return self.format_selection(None, Some((url, expected_prev_url)), window, cx); + }; + let Some(url_str) = url.clone() else { + return self.format_selection(None, Some((url, expected_prev_url)), window, cx); + }; + let Some(selection) = self.editor.selection.clone() else { + return Ok(()); + }; + if selection.anchor.block_id != selection.focus.block_id { + return self.format_selection(None, Some((url, expected_prev_url)), window, cx); + } + let block_id = selection.anchor.block_id.clone(); + let raw_from = selection.anchor.offset().min(selection.focus.offset()) as usize; + let raw_to = selection.anchor.offset().max(selection.focus.offset()) as usize; + if raw_to <= raw_from { + return Ok(()); + } + let Some((doc_text, _)) = self + .page() + .and_then(|p| p.read_editable_text(&block_id).ok()) + else { + return Ok(()); + }; + let live_len: usize = doc_text + .delta + .iter() + .map(|op| match op { + TextDeltaOp::Insert { + insert: TextInsert::Text(s), + .. + } => s.encode_utf16().count(), + TextDeltaOp::Insert { + insert: TextInsert::Embed(_), + .. + } => 1, + _ => 0, + }) + .sum(); + if raw_to > live_len { + return Ok(()); + } + if let Some(prev_text) = expected_prev_text.as_deref() + && slice_utf16(&doc_text.plain, raw_from, raw_to) != prev_text + { + return Ok(()); + } + let (from, to) = if let Some(prev_url) = expected_prev_url.as_deref() { + let spans = + view_link_popup::matching_link_subranges(&doc_text, raw_from, raw_to, prev_url); + if spans.as_slice() != [(raw_from, raw_to)] { + return Ok(()); + } + (raw_from as u64, raw_to as u64) + } else { + (raw_from as u64, raw_to as u64) + }; + + // Preserve shared inline formatting attributes across `[from, to)` while updating `link`. + let shared = marks_in_range(&doc_text, from as usize, to as usize); + let mut attrs = TextAttributes::new(); + for (on, k) in [ + (shared.bold, "bold"), + (shared.italic, "italic"), + (shared.underline, "underline"), + (shared.strike, "strike"), + (shared.code, "code"), + ] { + if on { + attrs.insert(k.to_string(), Any::True); + } + } + if let Some(c) = shared.color { + attrs.insert("color".to_string(), Any::String(c)); + } + if let Some(bg) = shared.background { + attrs.insert("background".to_string(), Any::String(bg)); + } + attrs.insert("link".to_string(), Any::String(url_str)); + + let prop_key = self.editable_prop_for_block(&block_id); + let new_len = new_text.encode_utf16().count() as u64; + let now = self.now_ms(cx) as u64; + let before = self.selection_snapshot(); + let page = self.page_mut()?; + page.stop_capturing()?; + let mut delta = Vec::new(); + if from > 0 { + delta.push(TextDeltaOp::Retain { + retain: from, + format: None, + }); + } + delta.push(TextDeltaOp::Delete { delete: to - from }); + delta.push(TextDeltaOp::Insert { + insert: TextInsert::Text(new_text), + format: Some(attrs), + }); + let commit = page.apply_text_delta(&block_id, prop_key, &delta, now)?; + if commit.is_some() + && let Some(before) = before + { + page.set_undo_selection_snapshot(before)?; + } + page.stop_capturing()?; + self.editor.selection = Some(DocumentSelection { + anchor: DocPoint::new(&block_id, from), + focus: DocPoint::new(&block_id, from + new_len), + }); + self.editor.last_typing = None; + self.did_edit(commit, Some(&block_id), window, cx); + Ok(()) + } + + /// Convert the current text selection into an inline LaTeX equation chip (`latex` attribute on a + /// single space) and open `EquationEditor` pre-filled with the selected text. + pub(crate) fn run_inline_equation_from_selection( + &mut self, + window: &mut Window, + cx: &mut Context, + ) -> DocResult { + let Some(selection) = self.editor.selection.clone() else { + return Ok(()); + }; + if selection.empty() || selection.anchor.block_id != selection.focus.block_id { + return Ok(()); + } + let block_id = selection.anchor.block_id.clone(); + let from = selection.anchor.offset().min(selection.focus.offset()); + let to = selection.anchor.offset().max(selection.focus.offset()); + let initial = self + .flow_layout() + .and_then(|layout| self.single_block_selected_text(&selection, &layout)) + .unwrap_or_default(); + let prop_key = self.editable_prop_for_block(&block_id); + let Some((doc_text, _)) = self + .page() + .and_then(|p| p.read_editable_text(&block_id).ok()) + else { + return Ok(()); + }; + let live_len = doc_text.plain.encode_utf16().count() as u64; + let to = to.min(live_len); + if from > to { + return Ok(()); + } + let now = self.now_ms(cx) as u64; + let before = self.selection_snapshot(); + let page = self.page_mut()?; + page.stop_capturing()?; + let mut delta = Vec::new(); + if from > 0 { + delta.push(TextDeltaOp::Retain { + retain: from, + format: None, + }); + } + if to > from { + delta.push(TextDeltaOp::Delete { delete: to - from }); + } + delta.push(TextDeltaOp::Insert { + insert: TextInsert::Text(" ".to_string()), + format: Some(TextAttributes::from([( + "latex".to_string(), + Any::String(initial.clone()), + )])), + }); + let commit = page.apply_text_delta(&block_id, prop_key, &delta, now)?; + if commit.is_some() + && let Some(before) = before + { + page.set_undo_selection_snapshot(before)?; + } + page.stop_capturing()?; + self.editor.selection = Some(DocumentSelection::caret(DocPoint::new(&block_id, from + 1))); + self.editor.last_typing = None; + self.did_edit(commit, Some(&block_id), window, cx); + self.dispatch_overlay_event( + OverlayEvent::OpenEquationEditor { + target: EquationTarget::Inline { + block_id, + utf16_offset: from, + }, + initial, + }, + window, + cx, + ); + Ok(()) + } + + /// Create a linked document titled with the selected text and replace the selection with an + /// inline `@reference` (`LinkedPage`) chip in one atomic undo step. + pub(crate) fn run_create_linked_doc_from_selection( + &mut self, + window: &mut Window, + cx: &mut Context, + ) -> DocResult { + let Some(selection) = self.editor.selection.clone() else { + return Ok(()); + }; + if selection.empty() || selection.anchor.block_id != selection.focus.block_id { + return Ok(()); + } + let block_id = selection.anchor.block_id.clone(); + let from = selection.anchor.offset().min(selection.focus.offset()); + let to = selection.anchor.offset().max(selection.focus.offset()); + let title = self + .flow_layout() + .and_then(|layout| self.single_block_selected_text(&selection, &layout)) + .map(|t| t.trim().to_string()) + .filter(|t| !t.is_empty()) + .unwrap_or_else(|| "Untitled".to_string()); + let summary = self + .doc_directory_mut() + .create_linked_doc(&title, crate::directory::EditorDocMode::Page, None) + .map_err(|err| DocError::InvalidState(err.to_string()))?; + let now = self.now_ms(cx) as u64; + self.ensure_workspace_page_and_broadcast(&summary, now) + .map_err(|err| DocError::InvalidState(err.to_string()))?; + self.insert_inline_reference_chip( + &block_id, + from, + to - from, + summary.id.as_str(), + window, + cx, + ) + } + + /// Execute `Copy` / `Duplicate` / `Delete` from the desktop Format Bar's `More (...)` menu. + pub(crate) fn run_format_more( + &mut self, + action: FormatMoreAction, + window: &mut Window, + cx: &mut Context, + ) -> DocResult { + let target_block = self + .editor + .selection + .as_ref() + .map(|s| s.focus.block_id.clone()) + .or_else(|| self.editor.block_selection.first().cloned()); + let Some(block_id) = target_block else { + return Ok(()); + }; + let mapped = match action { + FormatMoreAction::Copy => BlockMenuAction::Copy, + FormatMoreAction::Duplicate => BlockMenuAction::Duplicate, + FormatMoreAction::Delete => BlockMenuAction::Delete, + }; + self.execute_block_menu_action(&block_id, mapped, window, cx) + } + + /// Apply alignment to `Paragraph` and `List` blocks in `block_selection` when no text selection is active. + pub(crate) fn align_block_selection( + &mut self, + align: BlockAlign, + window: &mut Window, + cx: &mut Context, + ) -> DocResult { + let Some(layout) = self.flow_layout() else { + return Ok(()); + }; + let ids: Vec = self + .editor + .block_selection + .iter() + .filter(|id| { + layout.block(id).is_some_and(|b| { + matches!(b.body.kind, FlowKind::Paragraph(_) | FlowKind::List(_)) + }) + }) + .cloned() + .collect(); + if ids.is_empty() { + return Ok(()); + } + let before = self.selection_snapshot(); + let now = self.now_ms(cx) as u64; + let page = self.page_mut()?; + page.stop_capturing()?; + let commit = page.structural_edit(now, |page| { + for id in &ids { + page.set_block_prop( + id, + "prop:textAlign", + SessionValue::Any(Any::String(align.as_str().to_string())), + now, + )?; + } + Ok(()) + })?; + if commit.is_some() + && let Some(before) = before + { + page.set_undo_selection_snapshot(before)?; + } + page.stop_capturing()?; + self.editor.last_typing = None; + self.did_edit(commit, None, window, cx); + Ok(()) + } + + /// Create an empty child paragraph inside an empty `affine:callout` and focus the caret in it. + pub(crate) fn focus_or_create_callout_child( + &mut self, + callout_id: &str, + window: &mut Window, + cx: &mut Context, + ) -> bool { + if self.page_readonly { + return false; + } + let first_child = self + .snapshot + .as_ref() + .and_then(|s| s.block(callout_id)) + .and_then(|n| n.children.first().map(|c| c.id.clone())); + if let Some(child_id) = first_child { + self.select_document_range( + DocumentSelection::caret(DocPoint::new(&child_id, 0)), + window, + cx, + ); + return true; + } + let new_id = self.fresh_block_id(); + let now = self.now_ms(cx) as u64; + let before = self.selection_snapshot(); + let commit = self.page_mut().ok().and_then(|page| { + let _ = page.stop_capturing(); + let c = page + .add_block( + &new_id, + BlockSpec::Paragraph { + paragraph_type: blocksuite_playground_doc::schema::ParagraphType::Text, + text: String::new(), + }, + Some(callout_id), + Some(0), + now, + ) + .ok() + .flatten(); + if c.is_some() + && let Some(before) = before + { + let _ = page.set_undo_selection_snapshot(before); + } + let _ = page.stop_capturing(); + c + }); + if commit.is_some() { + self.did_edit(commit, None, window, cx); + self.select_document_range( + DocumentSelection::caret(DocPoint::new(&new_id, 0)), + window, + cx, + ); + return true; + } + false + } +} + +impl PlaygroundView { + /// Focus a trailing empty paragraph or append a new empty paragraph below the last block + /// when the user clicks empty canvas space below the page's final block. + pub(crate) fn handle_click_below_last_block( + &mut self, + last: &crate::block_flow::FlowBlock, + window: &mut Window, + cx: &mut Context, + ) { + if self.page_readonly { + return; + } + self.commit_active_preedit(window, cx); + if matches!(last.body.kind, FlowKind::Paragraph(_)) && last.body.plain.is_empty() { + self.select_document_range( + DocumentSelection::caret(DocPoint::new(&last.block_id, 0)), + window, + cx, + ); + window.request_virtual_keyboard(); + return; + } + let note_id = self.snapshot.as_ref().and_then(|snap| { + let root = snap.root.as_ref()?; + root.children + .iter() + .find(|c| c.is_page_visible_note() && c.walk().any(|n| n.id == last.block_id)) + .or_else(|| root.children.iter().find(|c| c.is_page_visible_note())) + .map(|c| c.id.clone()) + }); + let Some(note_id) = note_id else { + return; + }; + let before = self.selection_snapshot(); + let new_id = self.fresh_block_id(); + let now_ms = self.now_ms(cx) as u64; + let commit = self.page_mut().ok().and_then(|page| { + let _ = page.stop_capturing(); + let commit = page + .add_block( + &new_id, + BlockSpec::Paragraph { + paragraph_type: blocksuite_playground_doc::schema::ParagraphType::Text, + text: String::new(), + }, + Some(¬e_id), + None, + now_ms, + ) + .ok() + .flatten(); + if commit.is_some() + && let Some(before) = before + { + let _ = page.set_undo_selection_snapshot(before); + } + let _ = page.stop_capturing(); + commit + }); + if commit.is_some() { + self.did_edit(commit, None, window, cx); + self.select_document_range( + DocumentSelection::caret(DocPoint::new(&new_id, 0)), + window, + cx, + ); + window.request_virtual_keyboard(); + } + } +} diff --git a/blocksuite/crates/playground/src/overlays/view_format_bar/mod.rs b/blocksuite/crates/playground/src/overlays/view_format_bar/mod.rs new file mode 100644 index 0000000000..379280e6ef --- /dev/null +++ b/blocksuite/crates/playground/src/overlays/view_format_bar/mod.rs @@ -0,0 +1,368 @@ +//! Desktop `FormatToolbar` action handlers (`BlockSelection` format reading, dual-field +//! `Text`+`Link` editing, `InlineEquation`, `CreateLinkedDoc`, `CreateTable`, and `More`). + +mod actions; +#[cfg(test)] +mod tests; + +use blocksuite_playground_doc::{ + DocError, DocResult, read::TextAlign as BlockAlign, schema::BlockSpec, +}; +use ui::{Context, Window}; +use y_octo::{Any, SessionValue, TextAttributes, TextDeltaOp, TextInsert}; + +use crate::{ + PlaygroundView, + block_flow::{FlowKind, FlowLayout, FlowRect}, + editor_session::{DocPoint, DocumentSelection}, +}; + +use super::{ + BlockFormatCache, BlockMenuAction, EquationTarget, FormatCache, FormatMoreAction, + LayoutCacheKey, MarkState, OverlayEvent, SelectionFormat, marks_in_range, view_link_popup, +}; + +fn slice_utf16(text: &str, start: usize, end: usize) -> String { + if start >= end || text.is_empty() { + return String::new(); + } + let mut out = String::new(); + let mut u16_pos = 0usize; + let mut slice_start_byte: Option = None; + let mut slice_end_byte = text.len(); + let mut trailing_replacement = false; + + for (byte_idx, ch) in text.char_indices() { + let len = ch.len_utf16(); + let next_u16 = u16_pos + len; + if next_u16 <= start { + u16_pos = next_u16; + continue; + } + if u16_pos >= end { + if slice_start_byte.is_some() { + slice_end_byte = byte_idx; + } + break; + } + if u16_pos < start { + out.push('\u{FFFD}'); + if next_u16 >= end { + return out; + } + slice_start_byte = Some(byte_idx + ch.len_utf8()); + } else if next_u16 > end { + if slice_start_byte.is_some() { + slice_end_byte = byte_idx; + } + trailing_replacement = true; + break; + } else if slice_start_byte.is_none() { + slice_start_byte = Some(byte_idx); + } + u16_pos = next_u16; + } + if let Some(sb) = slice_start_byte + && sb < slice_end_byte + { + out.push_str(&text[sb..slice_end_byte]); + } + if trailing_replacement { + out.push('\u{FFFD}'); + } + out +} + +fn merge_shared_alignment(shared: &mut Option>, own: BlockAlign) { + *shared = Some(match *shared { + None => Some(own), + Some(all) => all.filter(|all| *all == own), + }); +} + +fn intersect_marks(marks: Option, slice: MarkState) -> MarkState { + match marks { + None => slice, + Some(all) => MarkState { + bold: all.bold && slice.bold, + italic: all.italic && slice.italic, + underline: all.underline && slice.underline, + strike: all.strike && slice.strike, + code: all.code && slice.code, + link: all.link.filter(|l| Some(l) == slice.link.as_ref()), + color: all.color.filter(|c| Some(c) == slice.color.as_ref()), + background: all + .background + .filter(|bg| Some(bg) == slice.background.as_ref()), + }, + } +} + +impl PlaygroundView { + /// What the formatting toolbar shows for the editor's selection: `None` unless the + /// selection is non-empty, no composition is running, and it covers paragraph or list + /// text only (or a whole-block `BlockSelection` covering paragraph/list blocks). + /// Marks, alignment, and single-block selected text are cached per selection and revision. + pub(crate) fn selection_format( + &mut self, + layout: &std::rc::Rc, + ) -> Option { + let Some(selection) = self.editor.selection.clone().filter(|s| !s.empty()) else { + if self.editor.composing() { + return None; + } + return self.block_selection_format(layout); + }; + if self.editor.composing() { + return None; + } + let fresh = self.overlays.format_cache.as_ref().is_some_and(|cache| { + cache.key.matches(self.doc_rev, layout) && cache.selection == selection + }); + if !fresh { + let value = self + .read_selection_format(&selection, layout) + .map(|(marks, align)| { + let selected_text = self + .single_block_selected_text(&selection, layout) + .map(ui::SharedString::from); + (marks, align, selected_text) + }); + self.overlays.format_cache = Some(FormatCache { + key: LayoutCacheKey::new(self.doc_rev, layout), + selection: selection.clone(), + value, + }); + } + let (marks, align, selected_text) = self.overlays.format_cache.as_ref()?.value.clone()?; + let single_block = selection.anchor.block_id == selection.focus.block_id; + let current_turn_into_id = layout + .block(&selection.anchor.block_id) + .and_then(|b| turn_into_id_for_kind(b.body.kind)); + Some(SelectionFormat { + anchor_world: self.text_selection_geometry(layout)?.bounds()?, + marks, + align, + selected_text, + current_turn_into_id, + can_create_table: single_block, + }) + } + + pub(super) fn read_selection_format( + &self, + selection: &DocumentSelection, + layout: &FlowLayout, + ) -> Option<(MarkState, Option)> { + let (start, end, a, b, _) = selection.ordered(layout)?; + let page = self.page()?; + let fallback_align = if layout.direction == ui::Direction::Rtl { + BlockAlign::Right + } else { + BlockAlign::Left + }; + let mut marks: Option = None; + let mut marks_absorbed = false; + // Every paragraph and list block the selection touches is aligned, empty ones too. + let mut shared_align: Option> = None; + for block in &layout.blocks[a..=b] { + let id = block.block_id.as_str(); + let is_text_block = + matches!(block.body.kind, FlowKind::Paragraph(_) | FlowKind::List(_)); + if is_text_block { + let own = block + .body + .text + .as_ref() + .map_or(fallback_align, |t| t.layout.block_align()); + merge_shared_alignment(&mut shared_align, own); + } + let from = if id == start.block_id { + start.offset() + } else { + 0 + }; + let to = if id == end.block_id { + end.offset() + } else { + block.body.plain.encode_utf16().count() as u64 + }; + if !block.editable() || to <= from { + continue; + } + // The title and code carry no inline marks; skip non-text blocks in cross-block + // selections so the desktop Format Bar stays mounted for the text blocks. + if !is_text_block { + if a == b { + return None; + } + continue; + } + if marks_absorbed { + continue; + } + let (text, _) = page.read_editable_text(id).ok()?; + let slice = marks_in_range(&text, from as usize, to as usize); + let next = intersect_marks(marks, slice); + if next.is_all_cleared() { + marks_absorbed = true; + } + marks = Some(next); + } + let marks = marks?; + Some((marks, shared_align.flatten())) + } + + /// Extract plain selected text for single-block selections so dual-field `LinkBar` + /// pre-fills its `Text` input. + pub(super) fn single_block_selected_text( + &self, + selection: &DocumentSelection, + layout: &FlowLayout, + ) -> Option { + if selection.anchor.block_id != selection.focus.block_id { + return None; + } + let block = layout.block(&selection.anchor.block_id)?; + let from = selection.anchor.offset().min(selection.focus.offset()) as usize; + let to = selection.anchor.offset().max(selection.focus.offset()) as usize; + if to <= from { + return None; + } + Some(slice_utf16(&block.body.plain, from, to)) + } + + /// Build a [`SelectionFormat`] for whole-block `BlockSelection` covering paragraph or list + /// blocks so the desktop Format Bar mounts on `Esc` / block selection. + pub(super) fn block_selection_format( + &mut self, + layout: &std::rc::Rc, + ) -> Option { + if self.editor.block_selection.is_empty() { + return None; + } + let cache_hit = self.overlays.block_format_cache.as_ref().is_some_and(|c| { + c.key.matches(self.doc_rev, layout) + && c.selected_ids.as_slice() == self.editor.block_selection.as_slice() + }); + if !cache_hit { + let computed = self.compute_block_selection_format(layout); + self.overlays.block_format_cache = Some(BlockFormatCache { + key: LayoutCacheKey::new(self.doc_rev, layout), + selected_ids: self.editor.block_selection.clone(), + value: computed, + }); + } + let (anchor_world, marks, align) = self + .overlays + .block_format_cache + .as_ref()? + .value + .as_ref()? + .clone(); + let current_turn_into_id = self + .editor + .block_selection + .first() + .and_then(|id| layout.block(id)) + .and_then(|b| turn_into_id_for_kind(b.body.kind)); + Some(SelectionFormat { + anchor_world, + marks, + align, + selected_text: None, + current_turn_into_id, + can_create_table: true, + }) + } +} + +fn turn_into_id_for_kind(kind: FlowKind) -> Option<&'static str> { + use blocksuite_playground_doc::schema::{ListType, ParagraphType}; + match kind { + FlowKind::Paragraph(ParagraphType::Text) => Some("text"), + FlowKind::Paragraph(ParagraphType::H1) => Some("h1"), + FlowKind::Paragraph(ParagraphType::H2) => Some("h2"), + FlowKind::Paragraph(ParagraphType::H3) => Some("h3"), + FlowKind::Paragraph(ParagraphType::H4) => Some("h4"), + FlowKind::Paragraph(ParagraphType::H5) => Some("h5"), + FlowKind::Paragraph(ParagraphType::H6) => Some("h6"), + FlowKind::Paragraph(ParagraphType::Quote) => Some("quote"), + FlowKind::List(ListType::Bulleted) => Some("bulleted"), + FlowKind::List(ListType::Numbered) => Some("numbered"), + FlowKind::List(ListType::Todo) => Some("todo"), + FlowKind::List(ListType::Toggle) => Some("toggle"), + FlowKind::Code => Some("code"), + FlowKind::Callout => Some("callout"), + _ => None, + } +} + +impl PlaygroundView { + fn compute_block_selection_format( + &self, + layout: &FlowLayout, + ) -> Option<(FlowRect, MarkState, Option)> { + let page = self.page()?; + let mut selected: std::collections::HashSet<&str> = self + .editor + .block_selection + .iter() + .map(String::as_str) + .collect(); + let fallback_align = if layout.direction == ui::Direction::Rtl { + BlockAlign::Right + } else { + BlockAlign::Left + }; + let mut bounds: Option<(f32, f32, f32, f32)> = None; + let mut shared_align: Option> = None; + let mut marks: Option = None; + let mut marks_absorbed = false; + + for block in &layout.blocks { + if !selected.remove(block.block_id.as_str()) { + continue; + } + if matches!(block.body.kind, FlowKind::Paragraph(_) | FlowKind::List(_)) { + let r = block.rect(); + bounds = Some(match bounds { + None => (r.x, r.y, r.right(), r.bottom()), + Some((l, t, rb, b)) => { + (l.min(r.x), t.min(r.y), rb.max(r.right()), b.max(r.bottom())) + } + }); + let own = block + .body + .text + .as_ref() + .map_or(fallback_align, |t| t.layout.block_align()); + merge_shared_alignment(&mut shared_align, own); + + if !marks_absorbed && !block.body.plain.is_empty() { + let len = block.body.plain.encode_utf16().count(); + if len > 0 + && let Ok((text, _)) = page.read_editable_text(&block.block_id) + { + let slice = marks_in_range(&text, 0, len); + let next = intersect_marks(marks, slice); + if next.is_all_cleared() { + marks_absorbed = true; + } + marks = Some(next); + } + } + } + if selected.is_empty() { + break; + } + } + let (left, top, right, bottom) = bounds?; + let anchor_world = FlowRect::new(left, top, right - left, bottom - top); + Some(( + anchor_world, + marks.unwrap_or_default(), + shared_align.flatten(), + )) + } +} diff --git a/blocksuite/crates/playground/src/overlays/view_format_bar/tests.rs b/blocksuite/crates/playground/src/overlays/view_format_bar/tests.rs new file mode 100644 index 0000000000..13c98cd2d7 --- /dev/null +++ b/blocksuite/crates/playground/src/overlays/view_format_bar/tests.rs @@ -0,0 +1,359 @@ +use std::{cell::RefCell, rc::Rc}; + +use blocksuite_playground_doc::{ + read::TextAlign as BlockAlign, + schema::{BlockSpec, ParagraphType}, +}; +use ui::{ + AppContext as _, Application, Bounds, Direction, HeadlessPlatform, WindowBounds, WindowHandle, + WindowOptions, point, px, size, +}; +use y_octo::{Any, SessionValue}; + +use super::slice_utf16; +use crate::{ + DocState, PlaygroundOptions, PlaygroundView, + editor_session::{DocPoint, DocumentSelection}, + theme::register_bundled_fonts, +}; + +fn ref_slice_utf16(text: &str, start: usize, end: usize) -> String { + let units: Vec = text.encode_utf16().collect(); + let s = start.min(units.len()); + let e = end.min(units.len()); + if s >= e { + String::new() + } else { + String::from_utf16_lossy(&units[s..e]) + } +} + +#[test] +fn slice_utf16_matches_encode_utf16_across_bmp_surrogates_and_bounds() { + let samples = [ + "", + "hello world", + "a😀b", + "😀😀", + "中文🚀测试✨end", + "x\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}y", + ]; + for sample in samples { + let max_u16 = sample.encode_utf16().count(); + for start in 0..=(max_u16 + 2) { + for end in 0..=(max_u16 + 2) { + assert_eq!( + slice_utf16(sample, start, end), + ref_slice_utf16(sample, start, end), + "sample={sample:?} start={start} end={end}" + ); + } + } + } +} + +fn with_view( + direction: Direction, + f: impl FnOnce(&ui::ApplicationHandle, &WindowHandle, &ui::HeadlessWindow), +) { + let platform = HeadlessPlatform::new(960, 640, 1.0); + let handle_cell: Rc>>> = + Rc::new(RefCell::new(None)); + let handle_out = handle_cell.clone(); + let app = Application::with_platform(platform.clone()).run_embedded(move |cx| { + register_bundled_fonts(cx).expect("fonts"); + let window = cx + .open_window( + WindowOptions { + window_bounds: Some(WindowBounds::Windowed(Bounds::new( + point(px(0.0), px(0.0)), + size(px(960.0), px(640.0)), + ))), + ..Default::default() + }, + |window, cx| { + window.set_root_layout_direction(direction); + cx.new(|cx| PlaygroundView::with_options(PlaygroundOptions::default(), cx)) + }, + ) + .expect("open window"); + *handle_out.borrow_mut() = Some(window); + }); + let window = handle_cell.borrow_mut().take().expect("window"); + let headless_win = platform.windows().into_iter().next().expect("headless win"); + f(&app, &window, &headless_win); +} + +#[test] +fn selection_format_reads_inherited_ltr_rtl_and_absorbing_block_selection_alignment() { + let cases = [ + (Direction::Ltr, Some("center"), None, BlockAlign::Center), + (Direction::Rtl, None, None, BlockAlign::Right), + (Direction::Rtl, None, Some("left"), BlockAlign::Left), + ]; + for (dir, parent_align, child_align, expected) in cases { + with_view(dir, |app, window, headless_win| { + let mut doc = DocState::new("align-doc", 91).expect("doc"); + doc.workspace + .create_page("align-doc", "Align", 1) + .expect("create page"); + let page = doc.workspace.page_mut("align-doc").expect("page"); + page.add_block( + "root", + BlockSpec::Page { + title: "Align".into(), + }, + None, + None, + 1, + ) + .expect("root"); + page.add_block( + "note", + BlockSpec::Note { xywh: None }, + Some("root"), + None, + 2, + ) + .expect("note"); + page.add_block( + "parent", + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: "Parent text".into(), + }, + Some("note"), + None, + 3, + ) + .expect("parent"); + if let Some(a) = parent_align { + page.set_block_prop( + "parent", + "prop:textAlign", + SessionValue::Any(Any::String(a.into())), + 4, + ) + .expect("parent align"); + } + page.add_block( + "child", + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: "Child text".into(), + }, + Some("parent"), + None, + 5, + ) + .expect("child"); + if let Some(a) = child_align { + page.set_block_prop( + "child", + "prop:textAlign", + SessionValue::Any(Any::String(a.into())), + 6, + ) + .expect("child align"); + } + // Extra trailing empty block with opposite alignment to test absorbing-state loop + // does not skip alignment/anchor computation for remaining blocks. + page.add_block( + "tail_empty", + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: String::new(), + }, + Some("note"), + None, + 7, + ) + .expect("tail"); + let opposite = match expected { + BlockAlign::Center => "right", + BlockAlign::Right => "center", + BlockAlign::Left => "center", + }; + page.set_block_prop( + "tail_empty", + "prop:textAlign", + SessionValue::Any(Any::String(opposite.into())), + 8, + ) + .expect("tail align"); + + app.update(|cx| { + window + .update(cx, |view, w, cx| { + view.set_document(doc, cx); + view.change_selection( + DocumentSelection { + anchor: DocPoint::new("child", 0), + focus: DocPoint::new("child", 5), + }, + w, + cx, + ); + }) + .expect("setup"); + }); + headless_win.request_frame(); + + app.update(|cx| { + window + .update(cx, |view, w, cx| { + let layout = view.flow_layout().expect("layout"); + let text_fmt = view.selection_format(&layout).expect("text format"); + assert_eq!( + text_fmt.align, + Some(expected), + "dir={dir:?} parent={parent_align:?} child={child_align:?} text" + ); + assert_eq!(text_fmt.selected_text.as_deref(), Some("Child")); + + // Whole-block selection on `child` alone matches expected alignment. + view.set_block_selection(vec!["child".into()], false, w, cx); + let blk_fmt = view.selection_format(&layout).expect("block format"); + assert_eq!(blk_fmt.align, Some(expected), "dir={dir:?} block single"); + + // Adding `tail_empty` (different alignment) after plain `child` (which + // already reaches mark absorbing state) must clear shared alignment + // and expand anchor_world to include `tail_empty`. + let child_rect = layout.block("child").unwrap().rect(); + let tail_rect = layout.block("tail_empty").unwrap().rect(); + view.set_block_selection( + vec!["child".into(), "tail_empty".into()], + false, + w, + cx, + ); + let multi_fmt = view.selection_format(&layout).expect("multi block format"); + assert_eq!( + multi_fmt.align, None, + "mixed alignment must become None even after marks absorb" + ); + assert!( + multi_fmt.anchor_world.bottom() >= tail_rect.bottom() - 0.1 + && multi_fmt.anchor_world.y <= child_rect.y + 0.1 + ); + }) + .expect("verify"); + }); + }); + } +} + +#[test] +fn layout_cache_key_misses_new_rc_with_same_shape_and_duplicate_id_uses_first_row() { + with_view(Direction::Ltr, |app, window, headless_win| { + let mut doc = DocState::new("cache-doc", 92).expect("doc"); + doc.workspace + .create_page("cache-doc", "Cache", 1) + .expect("create page"); + let page = doc.workspace.page_mut("cache-doc").expect("page"); + page.add_block( + "root", + BlockSpec::Page { + title: "Cache".into(), + }, + None, + None, + 1, + ) + .expect("root"); + page.add_block( + "note", + BlockSpec::Note { xywh: None }, + Some("root"), + None, + 2, + ) + .expect("note"); + page.add_block( + "p1", + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: "Hello world".into(), + }, + Some("note"), + None, + 3, + ) + .expect("p1"); + + app.update(|cx| { + window + .update(cx, |view, w, cx| { + view.set_document(doc, cx); + view.set_block_selection(vec!["p1".into()], false, w, cx); + }) + .expect("setup"); + }); + headless_win.request_frame(); + + app.update(|cx| { + window + .update(cx, |view, w, _cx| { + let base_layout = view.flow_layout().expect("layout"); + let p1_orig = base_layout.block("p1").expect("p1"); + let make_p1 = |x: f32, y: f32| crate::block_flow::FlowBlock { + block_id: "p1".to_string(), + snapshot_id: p1_orig.snapshot_id.clone(), + x, + y, + has_gutter_chevron: false, + body: std::rc::Rc::clone(&p1_orig.body), + }; + let layout_a = std::rc::Rc::new(crate::block_flow::FlowLayout { + blocks: vec![make_p1(10.0, 20.0)], + width: 800.0, + height: 200.0, + direction: Direction::Ltr, + stats: Default::default(), + }); + let fmt_a = view.selection_format(&layout_a).expect("fmt a"); + assert_eq!(fmt_a.align, Some(BlockAlign::Left)); + assert!((fmt_a.anchor_world.x - 10.0).abs() < 0.01); + + // Drop layout_a before allocating layout_b with identical width, height, + // blocks.len(), and doc_rev to verify Weak ABA immunity. + drop(layout_a); + let layout_b = std::rc::Rc::new(crate::block_flow::FlowLayout { + blocks: vec![make_p1(58.0, 20.0)], + width: 800.0, + height: 200.0, + direction: Direction::Ltr, + stats: Default::default(), + }); + let fmt_b = view.selection_format(&layout_b).expect("fmt b"); + assert!((fmt_b.anchor_world.x - 58.0).abs() < 0.01); + + // Flip direction to RTL at the same doc_rev: fresh layout updates align. + w.set_root_layout_direction(Direction::Rtl); + let layout_rtl = view.ensure_layout(800.0, w).expect("rtl layout"); + let fmt_rtl = view.selection_format(&layout_rtl).expect("fmt rtl"); + assert_eq!(fmt_rtl.align, Some(BlockAlign::Right)); + + // Duplicate block_id in layout: first matching row wins for anchor_world. + let layout_dup = std::rc::Rc::new(crate::block_flow::FlowLayout { + blocks: vec![make_p1(58.0, 20.0), make_p1(999.0, 999.0)], + width: 800.0, + height: 200.0, + direction: Direction::Ltr, + stats: Default::default(), + }); + let fmt_dup = view.selection_format(&layout_dup).expect("fmt dup"); + assert!((fmt_dup.anchor_world.x - 58.0).abs() < 0.01); + assert!((fmt_dup.anchor_world.y - 20.0).abs() < 0.01); + assert!(fmt_dup.anchor_world.right() < 900.0); + + // Overlays::reset drops all caches. + view.overlays.reset(); + assert!(view.overlays.format_cache.is_none()); + assert!(view.overlays.block_format_cache.is_none()); + assert!(view.overlays.block_selection_rects_cache.is_none()); + }) + .expect("verify"); + }); + }); +} diff --git a/blocksuite/crates/playground/src/overlays/view_link_popup/actions.rs b/blocksuite/crates/playground/src/overlays/view_link_popup/actions.rs index ad868aba60..66d113c47a 100644 --- a/blocksuite/crates/playground/src/overlays/view_link_popup/actions.rs +++ b/blocksuite/crates/playground/src/overlays/view_link_popup/actions.rs @@ -116,6 +116,8 @@ impl PlaygroundView { }, align: None, selected_text: None, + current_turn_into_id: None, + can_create_table: false, }; self.overlays .open_link_field_for_block(&fmt, Some(block_id), now_ms); diff --git a/blocksuite/crates/playground/src/overlays/view_link_popup/mod.rs b/blocksuite/crates/playground/src/overlays/view_link_popup/mod.rs index 1a1ac48919..f9be4d3ebe 100644 --- a/blocksuite/crates/playground/src/overlays/view_link_popup/mod.rs +++ b/blocksuite/crates/playground/src/overlays/view_link_popup/mod.rs @@ -20,6 +20,14 @@ use super::{ find_parent, }; +/// Desktop hover transition of the link popup that waits for its delay. +pub(crate) enum LinkHoverPending { + /// The pointer rests on a link or reference: open the popup after the enter delay. + Enter(LinkPopupTarget, FlowRect), + /// The pointer left the link and the popup: close the popup after the leave delay. + Leave, +} + thread_local! { static LINK_HIT_TEXT_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; } @@ -408,6 +416,8 @@ impl PlaygroundView { marks, align: None, selected_text: None, + current_turn_into_id: None, + can_create_table: false, }) } @@ -471,60 +481,66 @@ impl PlaygroundView { .overlays .retain_or_reopen_link_popup_on_hover(&scene, x, y, now_ms) { + self.link_hover_pending = None; + self.link_hover_timer = None; cx.notify(); return; } } - if let Some((target, anchor_world)) = self.hit_link_popup_target_at(x, y, window) { - if self - .overlays - .link_popup() - .is_some_and(|p| p.target == target) + let pending = match self.hit_link_popup_target_at(x, y, window) { + Some((target, _)) + if self + .overlays + .link_popup() + .is_some_and(|p| p.target == target) => { - self.pending_link_hover = None; + None + } + Some((target, anchor_world)) => Some(LinkHoverPending::Enter(target, anchor_world)), + None if self.overlays.link_popup().is_some_and(|p| p.from_hover) => { + Some(LinkHoverPending::Leave) + } + None => None, + }; + let unchanged = match (&self.link_hover_pending, &pending) { + (Some(LinkHoverPending::Enter(a, _)), Some(LinkHoverPending::Enter(b, _))) => a == b, + (Some(LinkHoverPending::Leave), Some(LinkHoverPending::Leave)) => true, + _ => false, + }; + if unchanged { + return; + } + let delay_ms = match &pending { + Some(LinkHoverPending::Enter(..)) => LINK_HOVER_DELAY_MS, + Some(LinkHoverPending::Leave) => super::HOVER_LEAVE_DELAY_MS, + None => { + self.link_hover_pending = None; self.link_hover_timer = None; return; } - if self - .pending_link_hover - .as_ref() - .is_some_and(|(pending_target, _, _)| pending_target == &target) - { - return; - } - self.link_hover_gen += 1; - let hover_gen = self.link_hover_gen; - self.pending_link_hover = Some((target.clone(), anchor_world, hover_gen)); - self.link_hover_timer = Some(cx.spawn(async move |this, cx| { - cx.background_executor() - .timer(std::time::Duration::from_millis(LINK_HOVER_DELAY_MS as u64)) - .await; - let _ = this.update(cx, |this, cx| { - let matches = this - .pending_link_hover - .as_ref() - .is_some_and(|(_, _, g)| *g == hover_gen); - if !matches { - return; + }; + self.link_hover_pending = pending; + // Replacing the task cancels the previous one, so only the latest transition fires. + self.link_hover_timer = Some(cx.spawn(async move |this, cx| { + cx.background_executor() + .timer(std::time::Duration::from_millis(delay_ms as u64)) + .await; + let _ = this.update(cx, |this, cx| { + let now_ms = this.now_ms(cx); + match this.link_hover_pending.take() { + Some(LinkHoverPending::Enter(target, anchor)) => { + this.overlays.open_link_popup(target, anchor, true, now_ms); } - if let Some((pending_target, pending_anchor, _)) = - this.pending_link_hover.take() + Some(LinkHoverPending::Leave) + if this.overlays.link_popup().is_some_and(|p| p.from_hover) => { - let now_ms = this.now_ms(cx); - this.overlays - .open_link_popup(pending_target, pending_anchor, true, now_ms); - cx.notify(); + this.overlays.close_link_popup(now_ms); } - }); - })); - } else { - self.pending_link_hover = None; - self.link_hover_timer = None; - if self.overlays.link_popup().is_some_and(|p| p.from_hover) { - self.overlays.close_link_popup(now_ms); + _ => return, + } cx.notify(); - } - } + }); + })); } /// Sync caret-triggered link/reference popup when a collapsed caret lands on a link or chip, diff --git a/blocksuite/crates/playground/src/overlays/view_mobile/mod.rs b/blocksuite/crates/playground/src/overlays/view_mobile/mod.rs index 226a87a4f8..b2a3e278b8 100644 --- a/blocksuite/crates/playground/src/overlays/view_mobile/mod.rs +++ b/blocksuite/crates/playground/src/overlays/view_mobile/mod.rs @@ -35,6 +35,8 @@ mod tests_retest_fixes; #[cfg(test)] mod tests_sync; #[cfg(test)] +mod tests_toolbar_chrome; +#[cfg(test)] mod tests_touch_gestures; #[cfg(test)] mod tests_touch_ux; diff --git a/blocksuite/crates/playground/src/overlays/view_mobile/tests_toolbar_chrome.rs b/blocksuite/crates/playground/src/overlays/view_mobile/tests_toolbar_chrome.rs new file mode 100644 index 0000000000..08fa7182a4 --- /dev/null +++ b/blocksuite/crates/playground/src/overlays/view_mobile/tests_toolbar_chrome.rs @@ -0,0 +1,479 @@ +//! Deterministic headless tests for shared `ToolbarChrome`, `Tooltip`, Image 500 ms hover inner +//! toolbar + 4-corner handles, LinkedDoc single-click select vs double-click open, FormatToolbar +//! `Align ▾` / `Highlight ▾` / `Create Table` / `⋮ More`, Bookmark/Callout toolbars, and Simple +//! Table hover add-bars & three-dot axis pills. + +use std::time::Duration; + +use blocksuite_playground_doc::{ + read::{BlockContent, TextAlign}, + schema::{BlockSpec, ParagraphType}, +}; +use ui::{ + DebugElementSnapshot, FrameSnapshot, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, + PlatformInput, point, px, +}; + +use crate::{ + HOME_PAGE_ID, PlaygroundTheme, + overlays::{ActiveSelection, FormatAction, OverlayEvent}, + room_client::DocState, +}; + +use super::tests::MobileSession; + +fn by_id<'a>(snap: &'a FrameSnapshot, id: &str) -> Option<&'a DebugElementSnapshot> { + snap.elements.get(id) +} + +fn load_state(s: &MobileSession, state: DocState) { + s.app.update(|cx| { + s.window + .update(cx, |v, _, cx| v.set_document(state, cx)) + .expect("set_document"); + }); + s.platform.run_until_parked(); +} + +fn save_evidence_png(s: &MobileSession, filename: &str) { + let Ok(dir) = std::env::var("TOOLBAR_EVIDENCE_DIR") else { + return; + }; + let dir = std::path::PathBuf::from(dir); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join(filename); + let img = s + .app + .update(|cx| s.window.update(cx, |_, window, _| window.render_to_image())); + if let Ok(Ok(image)) = img { + let _ = image.save(&path); + } +} + +fn make_png_240x160() -> Vec { + let mut img = image::RgbaImage::new(240, 160); + for (x, y, px_out) in img.enumerate_pixels_mut() { + let r = (48 + (x * 160 / 240)) as u8; + let g = (110 + (y * 110 / 160)) as u8; + let b = (210 - (x * 70 / 240)) as u8; + *px_out = image::Rgba([r, g, b, 255]); + } + let mut out = Vec::new(); + image::DynamicImage::ImageRgba8(img) + .write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png) + .expect("png encode"); + out +} + +fn click_at(s: &MobileSession, x: f32, y: f32, click_count: usize) { + s.headless + .dispatch_input(PlatformInput::MouseDown(MouseDownEvent { + button: MouseButton::Left, + position: point(px(x), px(y)), + modifiers: ui::Modifiers::default(), + click_count, + first_mouse: false, + })); + s.platform.run_until_parked(); + s.headless + .dispatch_input(PlatformInput::MouseUp(MouseUpEvent { + button: MouseButton::Left, + position: point(px(x), px(y)), + modifiers: ui::Modifiers::default(), + click_count, + })); + s.platform.run_until_parked(); +} + +fn move_to(s: &MobileSession, x: f32, y: f32, pressed: bool) { + s.headless + .dispatch_input(PlatformInput::MouseMove(MouseMoveEvent { + position: point(px(x), px(y)), + pressed_button: pressed.then_some(MouseButton::Left), + modifiers: ui::Modifiers::default(), + })); + s.platform.run_until_parked(); +} + +#[test] +fn format_toolbar_highlight_vertical_list_and_create_table() { + let s = MobileSession::open(1280, 800, PlaygroundTheme::Light); + let mut state = DocState::new("fmt-chrome", 11).expect("doc"); + state + .workspace + .create_page(HOME_PAGE_ID, "Fmt", 1) + .expect("page"); + { + let p = state.workspace.page_mut(HOME_PAGE_ID).expect("page"); + p.add_block( + "root", + BlockSpec::Page { + title: "Fmt".into(), + }, + None, + None, + 1, + ) + .expect("root"); + p.add_block( + "note", + BlockSpec::Note { xywh: None }, + Some("root"), + None, + 2, + ) + .expect("note"); + p.add_block( + "p1", + BlockSpec::Paragraph { + paragraph_type: ParagraphType::H2, + text: "Hello world".into(), + }, + Some("note"), + None, + 3, + ) + .expect("p1"); + } + load_state(&s, state); + let _ = s.frame(); + + s.overlay(OverlayEvent::SetSelection(Some(ActiveSelection { + block_id: "p1".into(), + start_utf16: 0, + end_utf16: 5, + }))); + let _ = s.frame(); + s.platform.advance_clock(Duration::from_millis(200)); + s.platform.run_until_parked(); + let f = s.frame(); + assert!(by_id(&f, "overlay.format_toolbar").is_some()); + assert!(by_id(&f, "overlay.format_toolbar.align").is_some()); + assert!(by_id(&f, "overlay.format_toolbar.create_table").is_some()); + assert!(by_id(&f, "overlay.format_toolbar.more").is_some()); + + // Open Highlight vertical dual-section labelled list. + s.overlay(OverlayEvent::Format(FormatAction::Highlight)); + let _ = s.frame(); + s.platform.advance_clock(Duration::from_millis(200)); + s.platform.run_until_parked(); + let f_hl = s.frame(); + save_evidence_png(&s, "after_format_highlight.png"); + assert!(by_id(&f_hl, "overlay.format_toolbar.highlight_menu").is_some()); + assert!(by_id(&f_hl, "overlay.format_toolbar.highlight.color.default").is_some()); + assert!(by_id(&f_hl, "overlay.format_toolbar.highlight.background.blue").is_some()); + + // Click Create Table -> inserts an affine:table block into the document. + s.overlay(OverlayEvent::Format(FormatAction::CreateTable)); + let _ = s.frame(); + let has_table = s.view(|v| { + v.page_snapshot() + .and_then(|snap| snap.root.as_ref()) + .is_some_and(|root| { + root.children.iter().any(|note| { + note.children + .iter() + .any(|b| matches!(b.content, BlockContent::Table(_))) + }) + }) + }); + assert!( + has_table, + "Create Table should insert an affine:table block" + ); +} + +#[test] +fn linked_doc_single_click_selects_and_double_click_opens() { + let s = MobileSession::open(1280, 800, PlaygroundTheme::Light); + let mut state = DocState::new("linked-click", 12).expect("doc"); + state + .workspace + .create_page(HOME_PAGE_ID, "Home", 1) + .expect("home page"); + state + .workspace + .create_page("doc:target", "Target Page", 1_795_731_000_000) + .expect("child page"); + { + let p = state.workspace.page_mut(HOME_PAGE_ID).expect("page"); + p.add_block( + "root", + BlockSpec::Page { + title: "Home".into(), + }, + None, + None, + 1, + ) + .expect("root"); + p.add_block( + "note", + BlockSpec::Note { xywh: None }, + Some("root"), + None, + 2, + ) + .expect("note"); + p.add_block( + "emb1", + BlockSpec::EmbedLinkedDoc { + page_id: "doc:target".into(), + style: "vertical".into(), + caption: String::new(), + }, + Some("note"), + None, + 3, + ) + .expect("emb1"); + } + load_state(&s, state); + let f0 = s.frame(); + let card = by_id(&f0, "page.block.emb1.embed_card").expect("embed card hit target"); + let cx_pt = card.bounds.x + card.bounds.width * 0.5; + let cy_pt = card.bounds.y + card.bounds.height * 0.5; + + // Single click selects and mounts embed toolbar without navigating away. + click_at(&s, cx_pt, cy_pt, 1); + let f1 = s.frame(); + save_evidence_png(&s, "after_linked_doc_bar.png"); + assert_eq!(s.view(|v| v.page_id.clone()).as_deref(), Some(HOME_PAGE_ID)); + assert!( + by_id(&f1, "overlay.embed_toolbar").is_some(), + "single-click on linked doc should mount overlay.embed_toolbar" + ); + + // Double click opens the target document. + click_at(&s, cx_pt, cy_pt, 2); + let _ = s.frame(); + assert_eq!(s.view(|v| v.page_id.clone()).as_deref(), Some("doc:target")); +} + +#[test] +fn image_500ms_hover_inner_bar_and_all_four_corner_handles() { + let s = MobileSession::open(1280, 800, PlaygroundTheme::Light); + let mut state = DocState::new("img-hover", 13).expect("doc"); + state + .workspace + .create_page(HOME_PAGE_ID, "Img", 1) + .expect("page"); + state + .blobs + .insert("blob-1".into(), make_png_240x160().into()); + { + let p = state.workspace.page_mut(HOME_PAGE_ID).expect("page"); + p.add_block( + "root", + BlockSpec::Page { + title: "Img".into(), + }, + None, + None, + 1, + ) + .expect("root"); + p.add_block( + "note", + BlockSpec::Note { xywh: None }, + Some("root"), + None, + 2, + ) + .expect("note"); + p.add_block( + "img1", + BlockSpec::Image { + source_id: "blob-1".into(), + caption: String::new(), + width: 320.0, + height: 200.0, + xywh: None, + }, + Some("note"), + None, + 3, + ) + .expect("img1"); + p.set_block_prop( + "img1", + "prop:textAlign", + y_octo::SessionValue::Any(y_octo::Any::String(TextAlign::Left.as_str().into())), + 4, + ) + .expect("align left"); + } + load_state(&s, state); + // A host with a download channel shows `Download` on images with bytes. + s.app.update(|cx| { + s.window + .update(cx, |v, _, _| v.set_on_blob_download(Some(Box::new(|_| {})))) + .expect("register download callback") + }); + let f0 = s.frame(); + let img_card = by_id(&f0, "page.block.img1.image_card").expect("image card bounds"); + + // Hover image: not visible at 300ms, visible after 500ms inside image bounds. + move_to( + &s, + img_card.bounds.x + img_card.bounds.width * 0.5, + img_card.bounds.y + img_card.bounds.height * 0.5, + false, + ); + s.platform.advance_clock(Duration::from_millis(300)); + s.platform.run_until_parked(); + let f_early = s.frame(); + assert!(by_id(&f_early, "overlay.image_toolbar").is_none()); + + s.platform.advance_clock(Duration::from_millis(250)); + s.platform.run_until_parked(); + let f_hover = s.frame(); + let bar = by_id(&f_hover, "overlay.image_toolbar") + .expect("500ms hover should mount inner image toolbar"); + assert!( + bar.bounds.y >= img_card.bounds.y + && (bar.bounds.x + bar.bounds.width) + <= (img_card.bounds.x + img_card.bounds.width + 2.0), + "desktop image toolbar should be placed inner top-right of image" + ); + assert!(by_id(&f_hover, "overlay.image_toolbar.download").is_some()); + assert!(by_id(&f_hover, "overlay.image_toolbar.more").is_some()); + + // Select left-aligned image: all 4 corner resize handles must be present. + s.overlay(OverlayEvent::SelectBlock("img1".into())); + let f_sel = s.frame(); + save_evidence_png(&s, "after_image_inner_hover.png"); + for corner in ["resize_nw", "resize_ne", "resize_sw", "resize_se"] { + assert!( + by_id(&f_sel, &format!("page.block.img1.{corner}")).is_some(), + "left-aligned image must show all 4 corner handles (missing {corner})" + ); + } +} + +#[test] +fn simple_table_hover_affordances_and_axis_pills_replace_text_bar() { + let s = MobileSession::open(1280, 800, PlaygroundTheme::Light); + let mut state = DocState::new("tbl-hover", 14).expect("doc"); + state + .workspace + .create_page(HOME_PAGE_ID, "Tbl", 1) + .expect("page"); + { + let p = state.workspace.page_mut(HOME_PAGE_ID).expect("page"); + p.add_block( + "root", + BlockSpec::Page { + title: "Tbl".into(), + }, + None, + None, + 1, + ) + .expect("root"); + p.add_block( + "note", + BlockSpec::Note { xywh: None }, + Some("root"), + None, + 2, + ) + .expect("note"); + p.add_block( + "t1", + BlockSpec::Table { + rows: vec![ + vec!["Alpha".into(), "Beta".into()], + vec!["Gamma".into(), "Delta".into()], + ], + }, + Some("note"), + None, + 3, + ) + .expect("table"); + } + load_state(&s, state); + let f0 = s.frame(); + let tbl = by_id(&f0, "page.block.t1").expect("table block"); + move_to( + &s, + tbl.bounds.x + tbl.bounds.width * 0.5, + tbl.bounds.y + tbl.bounds.height * 0.5, + false, + ); + s.platform.advance_clock(Duration::from_millis(250)); + s.platform.run_until_parked(); + let f_hover = s.frame(); + assert!( + by_id(&f_hover, "overlay.table_toolbar").is_none(), + "desktop Simple Table must not mount legacy +Row/-Col text toolbar" + ); + assert!(by_id(&f_hover, "overlay.table_hover.add_col").is_some()); + assert!(by_id(&f_hover, "overlay.table_hover.add_row").is_some()); + assert!(by_id(&f_hover, "overlay.table_hover.add_corner").is_some()); + let col_pill = by_id(&f_hover, "overlay.table_hover.col_pill").expect("top 28x16 col pill"); + assert!(by_id(&f_hover, "overlay.table_hover.row_pill").is_some()); + + // Clicking the column pill opens the axis menu. + click_at( + &s, + col_pill.bounds.x + col_pill.bounds.width * 0.5, + col_pill.bounds.y + col_pill.bounds.height * 0.5, + 1, + ); + let f_menu = s.frame(); + save_evidence_png(&s, "after_table_hover.png"); + assert!(by_id(&f_menu, "overlay.table_toolbar.axis_menu").is_some()); +} + +#[test] +fn bookmark_toolbar_uses_shared_chrome_with_hostname_and_dropdowns() { + let s = MobileSession::open(1280, 800, PlaygroundTheme::Light); + let mut state = DocState::new("bm-chrome", 15).expect("doc"); + state + .workspace + .create_page(HOME_PAGE_ID, "Bm", 1) + .expect("page"); + { + let p = state.workspace.page_mut(HOME_PAGE_ID).expect("page"); + p.add_block( + "root", + BlockSpec::Page { title: "Bm".into() }, + None, + None, + 1, + ) + .expect("root"); + p.add_block( + "note", + BlockSpec::Note { xywh: None }, + Some("root"), + None, + 2, + ) + .expect("note"); + p.add_block( + "bm1", + BlockSpec::Bookmark { + url: "https://www.affine.pro/docs".into(), + title: Some("AFFiNE Docs".into()), + description: Some("Workspace docs".into()), + }, + Some("note"), + None, + 3, + ) + .expect("bm1"); + } + load_state(&s, state); + let _ = s.frame(); + s.overlay(OverlayEvent::SelectBlock("bm1".into())); + let f = s.frame(); + save_evidence_png(&s, "after_bookmark_bar.png"); + assert!(by_id(&f, "overlay.bookmark_toolbar").is_some()); + assert!(by_id(&f, "overlay.bookmark_toolbar.open").is_some()); + assert!(by_id(&f, "overlay.bookmark_toolbar.card").is_some()); + assert!(by_id(&f, "overlay.bookmark_toolbar.style").is_some()); + assert!(by_id(&f, "overlay.bookmark_toolbar.more").is_some()); +} diff --git a/blocksuite/crates/playground/src/overlays/view_scrollbar.rs b/blocksuite/crates/playground/src/overlays/view_scrollbar.rs index 37fa7db440..29e8fca3ff 100644 --- a/blocksuite/crates/playground/src/overlays/view_scrollbar.rs +++ b/blocksuite/crates/playground/src/overlays/view_scrollbar.rs @@ -74,10 +74,11 @@ impl PlaygroundView { && self.overlays.dragged_block().is_none() && !self.overlays.marquee_active() { - if self - .table_cell - .as_ref() - .is_some_and(|c| c.dragging || c.col_resize_drag.is_some()) + 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; @@ -120,13 +121,8 @@ impl PlaygroundView { { self.finish_image_resize_drag(window, cx); } - if self - .table_cell - .as_ref() - .is_some_and(|c| c.col_resize_drag.is_some()) - { - self.finish_table_col_resize_drag(window, cx); - } + self.finish_table_add_drag(window, cx); + self.finish_table_col_resize_drag(window, cx); if let Some(cell) = self.table_cell.as_mut() { cell.dragging = false; } diff --git a/blocksuite/crates/playground/src/overlays/view_slash_blocks.rs b/blocksuite/crates/playground/src/overlays/view_slash_blocks.rs index 9dc85a6090..942e34a6d3 100644 --- a/blocksuite/crates/playground/src/overlays/view_slash_blocks.rs +++ b/blocksuite/crates/playground/src/overlays/view_slash_blocks.rs @@ -533,9 +533,8 @@ impl PlaygroundView { Ok(()) } - /// Execute `SlashCommand::Image`, `SlashCommand::Bookmark`, or `SlashCommand::Attachment`: - /// strips any typed `/query` from `block_id` immediately without inserting premature empty blocks, - /// then opens the URL prompt or triggers the host media/attachment file picker. + /// Execute `SlashCommand::Image`, `Bookmark`, `Attachment`, or `Pdf`: strips any typed `/query` + /// from `block_id` without inserting empty blocks, then opens the URL prompt or the file picker. pub(super) fn run_media_slash_command( &mut self, block_id: &str, @@ -546,7 +545,8 @@ impl PlaygroundView { cx: &mut Context, ) -> DocResult { if (command == SlashCommand::Image && !self.can_pick_images()) - || (command == SlashCommand::Attachment && !self.can_pick_attachments()) + || (matches!(command, SlashCommand::Attachment | SlashCommand::Pdf) + && !self.can_pick_attachments()) { return Ok(()); } @@ -591,7 +591,7 @@ impl PlaygroundView { cx, ); } - SlashCommand::Attachment => { + SlashCommand::Attachment | SlashCommand::Pdf => { self.trigger_attachment_picker(Some((block_id.to_string(), remaining_empty)), cx); } _ => {} diff --git a/blocksuite/crates/playground/src/overlays/view_slash_extended.rs b/blocksuite/crates/playground/src/overlays/view_slash_extended.rs index 0ea741fc99..5d87e2222e 100644 --- a/blocksuite/crates/playground/src/overlays/view_slash_extended.rs +++ b/blocksuite/crates/playground/src/overlays/view_slash_extended.rs @@ -384,14 +384,6 @@ impl PlaygroundView { self.strip_slash_trigger(block_id, strip, window, cx)?; self.format_mark(mark, window, cx) } - SlashCommand::Pdf => self.run_media_slash_command( - block_id, - node, - SlashCommand::Attachment, - strip, - window, - cx, - ), SlashCommand::Embed(kind) => { self.strip_slash_trigger(block_id, strip, window, cx)?; let now_ms = self.now_ms(cx); diff --git a/blocksuite/crates/playground/src/overlays/view_table_cell/mod.rs b/blocksuite/crates/playground/src/overlays/view_table_cell/mod.rs index 558b04a30c..4a55576091 100644 --- a/blocksuite/crates/playground/src/overlays/view_table_cell/mod.rs +++ b/blocksuite/crates/playground/src/overlays/view_table_cell/mod.rs @@ -3,6 +3,7 @@ mod paint; mod pointer; mod toolbar; +mod touch_bar; use std::rc::Rc; @@ -12,9 +13,9 @@ use ui::{Context, KeyDownEvent, Window}; use crate::{ PlaygroundView, TOPBAR_HEIGHT, - block_flow::FlowLayout, + block_flow::{FlowLayout, PageViewport}, edgeless::EdgelessInlineEdit, - overlays::{InlineTableCell, KEYBOARD_TOOLBAR_HEIGHT, TableCellDragMode}, + overlays::{InlineTableCell, KEYBOARD_TOOLBAR_HEIGHT, TableAddDragKind, TableCellDragMode}, }; /// How [`PlaygroundView::finish_inline_targets`] handles any in-flight IME preedit. diff --git a/blocksuite/crates/playground/src/overlays/view_table_cell/pointer.rs b/blocksuite/crates/playground/src/overlays/view_table_cell/pointer.rs index 2eb633c813..971fc60693 100644 --- a/blocksuite/crates/playground/src/overlays/view_table_cell/pointer.rs +++ b/blocksuite/crates/playground/src/overlays/view_table_cell/pointer.rs @@ -3,7 +3,7 @@ use ui::{Context, MouseButton, MouseMoveEvent, Window}; use y_octo::{Any, TextAttributes, TextDeltaOp, TextInsert}; -use super::TableCellDragMode; +use super::{TableAddDragKind as Kind, TableCellDragMode}; use crate::{ PlaygroundView, TOPBAR_HEIGHT, overlays::{LinkedDocMenuState, Presence}, @@ -282,8 +282,8 @@ impl PlaygroundView { .reveal_table_cell_x(&cell.block_id, cell_left, cell_right, caret_x, code); } - /// Extend the active table cell's text selection or update live column-resize preview while - /// dragging with the primary button (0 CRDT writes until release). + /// Extend the active table cell's text selection, update live column-resize preview, or + /// update Simple Table hover add-bar drag preview (0 CRDT writes until release). pub(crate) fn table_cell_mouse_move( &mut self, event: &MouseMoveEvent, @@ -291,18 +291,44 @@ impl PlaygroundView { cx: &mut Context, ) { if event.pressed_button != Some(MouseButton::Left) { - if self - .table_cell - .as_ref() - .is_some_and(|c| c.col_resize_drag.is_some()) - { - self.finish_table_col_resize_drag(window, cx); - } + self.finish_table_add_drag(window, cx); + self.finish_table_col_resize_drag(window, cx); if let Some(cell) = self.table_cell.as_mut() { cell.dragging = false; } return; } + 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; + // Only travel along the bar's own axis turns the press into a drag, so a small + // sideways slip still releases as a plain click. + drag.moved |= match drag.kind { + Kind::Row => dy.abs() > 4.0, + Kind::Column => dx.abs() > 4.0, + Kind::Both => dx.abs() > 4.0 || dy.abs() > 4.0, + }; + // Once the pointer moved, the counts follow the distance: forward travel adds at + // least one, and travel backward or back to the press point adds nothing. + if drag.moved { + let count = |d: f32, step: f32| { + if d <= 4.0 { + 0 + } else { + ((d / step).floor() as usize).clamp(1, 20) + } + }; + let (rows, cols) = (count(dy, 36.0), count(dx, 80.0)); + (drag.preview_rows, drag.preview_cols) = match drag.kind { + Kind::Row => (rows, 0), + Kind::Column => (0, cols), + Kind::Both if dx < -4.0 || dy < -4.0 || rows + cols == 0 => (0, 0), + Kind::Both => (rows, cols), + }; + } + cx.notify(); + return; + } if let Some(cell) = self.table_cell.as_mut() && let Some(drag) = cell.col_resize_drag.as_mut() { @@ -369,7 +395,7 @@ impl PlaygroundView { cx.notify(); } - /// Commit an active table column-resize drag as 1 single CRDT Undo step on pointer release. + /// Commit an active table column-resize drag on pointer release. pub(crate) fn finish_table_col_resize_drag( &mut self, window: &mut Window, @@ -394,4 +420,36 @@ impl PlaygroundView { cx.notify(); } } + + /// Commit an active Simple Table hover add-bar or corner press on pointer release: append + /// its rows and columns at the end of the table in one undo step, wherever the focused cell + /// is. A press without movement appends one row, one column, or both. + pub(crate) fn finish_table_add_drag(&mut self, window: &mut Window, cx: &mut Context) { + let Some(drag) = self.overlays.table_hover.add_drag.take() else { + return; + }; + if self.table_is_readonly() { + cx.notify(); + return; + } + let row_ids: Vec = (0..drag.preview_rows) + .map(|_| format!("row-{}", self.fresh_block_id())) + .collect(); + let column_ids: Vec = (0..drag.preview_cols) + .map(|_| format!("col-{}", self.fresh_block_id())) + .collect(); + let now_ms = self.now_ms(cx) as u64; + let res = self.page_mut().and_then(|page| { + page.append_table_rows_and_columns(&drag.block_id, &row_ids, &column_ids, now_ms) + }); + match res { + Ok(Some(commit)) => { + self.did_table_cell_commit(&drag.block_id, commit); + window.notify_text_input_changed(&self.editor_focus); + } + Ok(None) => {} + Err(err) => eprintln!("table append rows and columns: {err}"), + } + cx.notify(); + } } diff --git a/blocksuite/crates/playground/src/overlays/view_table_cell/toolbar.rs b/blocksuite/crates/playground/src/overlays/view_table_cell/toolbar.rs index bee1477e46..8aabcc09e6 100644 --- a/blocksuite/crates/playground/src/overlays/view_table_cell/toolbar.rs +++ b/blocksuite/crates/playground/src/overlays/view_table_cell/toolbar.rs @@ -1,16 +1,22 @@ -//! Table row/column action bar (`overlay.table_toolbar`), row/column `⋯` axis menu -//! (`overlay.table_toolbar.axis_menu`), column-width resize drag handles, and Edgeless Note -//! table toolbar mounting. +//! Simple Table (`affine:table`) desktop hover affordances (16 px add-column/add-row bars and +//! corner drag-to-add, 28 × 16 / 16 × 28 three-dot axis pills, 5 px `ew-resize` column dividers, +//! and axis action menus) plus mobile touch table toolbar. use ui::{ - AnyElement, FontWeight, MouseButton, MouseDownEvent, SharedString, Window, div, prelude::*, px, + AnyElement, CursorStyle, FontWeight, MouseButton, MouseDownEvent, SharedString, Window, div, + prelude::*, px, }; use crate::{ PlaygroundView, TOPBAR_HEIGHT, block_flow::{FlowLayout, FlowRect, PageViewport}, - overlays::{OverlayScreenTransform, TableAxisMenu, TableColResizeDrag}, - theme::Palette, + overlays::{ + OverlayScreenTransform, TOOLBAR_CHROME_BORDER, TOOLBAR_CHROME_RADIUS, TOOLBAR_MENU_MIN_W, + TOOLBAR_MENU_PADDING, TOOLBAR_MENU_ROW_H, TableAddDrag, TableAddDragKind, TableAxisMenu, + TableColResizeDrag, chrome_border_color, chrome_error_bg, chrome_error_fg, chrome_panel_bg, + menu_horizontal_separator, + }, + theme::{Palette, TYPOGRAPHY}, }; const TABLE_BG_SWATCHES: [(&str, Option<&str>, u32); 6] = [ @@ -27,8 +33,8 @@ const TABLE_BG_SWATCHES: [(&str, Option<&str>, u32); 6] = [ ]; impl PlaygroundView { - /// Row/column action bar + column resize handles + axis `⋯` menu for a focused `affine:table` - /// block in Page mode. + /// Hover-revealed add bars, 28 × 16 / 16 × 28 three-dot axis pills, 5 px `ew-resize` + /// column dividers, and axis action menu for `affine:table` in Page mode. pub(crate) fn render_table_toolbar( &self, layout: &FlowLayout, @@ -40,164 +46,488 @@ impl PlaygroundView { if self.table_is_readonly() || self.database_record_sheet.is_some() { return None; } - let cell = self.table_cell.as_ref()?; - let block = layout.block(&cell.block_id)?; - let (_, by, hit) = - Self::find_table_cell_hit(layout, &cell.block_id, &cell.row_id, &cell.column_id)?; - let cell_top = by + hit.rect.y; - let cell_bottom = cell_top + hit.rect.h; - if cell_bottom < v.scroll_y || cell_top > v.scroll_y + v.height { - return None; - } let touch = self.is_touch_host() || viewport_width < 600.0; if touch { + let cell = self.table_cell.as_ref()?; + let (_, by, hit) = + Self::find_table_cell_hit(layout, &cell.block_id, &cell.row_id, &cell.column_id)?; + let cell_top = by + hit.rect.y; + let cell_bottom = cell_top + hit.rect.h; + if cell_bottom < v.scroll_y || cell_top > v.scroll_y + v.height { + return None; + } return Some(self.build_touch_table_toolbar(v, viewport_width, palette, cx)); } - let scroll_x = self.overlays.code_scroll_x(&cell.block_id); - let (table_right, table_bottom) = block - .body - .table_cells - .iter() - .fold((0.0_f32, 0.0_f32), |(max_r, max_b), c| { - (max_r.max(c.rect.right()), max_b.max(c.rect.bottom())) - }); - let bar_h = 32.0; - let bar_w = 436.0; - let below_y = if table_bottom > 0.0 { - block.y + table_bottom + 8.0 - } else { - block.y + block.body.height - bar_h - 6.0 - }; - let bar_x = (v.column_x + block.x + 10.0) - .clamp(8.0, (viewport_width - bar_w - 8.0).max(8.0)) + let focused_cell = self.table_cell.as_ref(); + let active_block_id = focused_cell.map(|c| c.block_id.as_str()).or(self + .overlays + .table_hover + .block_id + .as_deref())?; + let block = layout.block(active_block_id)?; + if block.body.table_cells.is_empty() { + return None; + } + + let scroll_x = self.overlays.code_scroll_x(active_block_id); + let (min_x, min_y, max_r, max_b) = block.body.table_cells.iter().fold( + (f32::INFINITY, f32::INFINITY, 0.0_f32, 0.0_f32), + |(lx, ty, mr, mb), c| { + ( + lx.min(c.rect.x), + ty.min(c.rect.y), + mr.max(c.rect.right()), + mb.max(c.rect.bottom()), + ) + }, + ); + if !min_x.is_finite() || !min_y.is_finite() { + return None; + } + let table_screen_left = (v.column_x + block.x + min_x - scroll_x).round(); + let table_screen_right = (v.column_x + block.x + max_r - scroll_x) + .min(v.column_x + block.x + block.body.width) .round(); - let viewport_bottom_slot = v.scroll_y + v.height - bar_h - 8.0; - let raw_y = if below_y <= viewport_bottom_slot { - below_y + let table_screen_top = (block.y + min_y - v.scroll_y).round(); + let table_screen_bottom = (block.y + max_b - v.scroll_y).round(); + if table_screen_bottom < 0.0 || table_screen_top > v.height { + return None; + } + let vis_top = table_screen_top.max(0.0).ceil(); + let vis_bottom = table_screen_bottom.min(v.height).floor(); + let table_vis_h = (vis_bottom - vis_top).max(0.0); + let table_vis_w = (table_screen_right - table_screen_left).max(0.0); + + let now_ms = self.now_ms(cx); + let fade = if focused_cell.is_some() { + 1.0_f32 } else { - let min_in_table = block.y.max(v.scroll_y + 8.0); - let mut docked = viewport_bottom_slot.max(min_in_table); - if cell_bottom > docked - 4.0 && cell_top - bar_h - 6.0 >= min_in_table { - docked = cell_top - bar_h - 6.0; - } - docked + ((now_ms - self.overlays.table_hover.hover_since_ms) / 200.0).clamp(0.15, 1.0) as f32 }; - let screen_y = (raw_y - v.scroll_y) - .clamp(8.0, (v.height - bar_h - 8.0).max(8.0)) - .round(); let mut layer = div().absolute().inset_0(); - // Narrow 8 px column-width resize drag handles centered on each column's right border. - // The blue resize guide appears ONLY when hovered or actively dragging. - if let Some(first_row_id) = block.body.table_cells.first().map(|c| c.row_id.as_str()) { - let table_top_local = block + + // 1. 5 px `ew-resize` column-width resize handles centered on each column's right border. + if let Some(first_row_id) = block.body.table_cells.first().map(|c| c.row_id.as_str()) + && table_vis_h > 0.0 + { + let active_blue = palette + .theme + .css_var("--affine-v2-table-indicator-activated") + .unwrap_or(palette.brand); + for c_hit in block .body .table_cells .iter() - .map(|c| c.rect.y) - .fold(f32::INFINITY, f32::min); - let table_top_local = if table_top_local.is_finite() { - table_top_local - } else { - 10.0 - }; - let table_screen_top = block.y + table_top_local - v.scroll_y; - let table_screen_bottom = block.y + table_bottom - v.scroll_y; - let vis_top = table_screen_top.max(0.0).ceil(); - let vis_bottom = table_screen_bottom.min(v.height).floor(); - let grip_h = (vis_bottom - vis_top).max(0.0); - if grip_h > 0.0 { - for c_hit in block - .body - .table_cells - .iter() - .filter(|c| c.row_id == first_row_id) + .filter(|c| c.row_id == first_row_id) + { + let base_edge_x = v.column_x + block.x + c_hit.rect.right() - scroll_x; + let active_drag = focused_cell + .and_then(|c| c.col_resize_drag.as_ref()) + .filter(|d| d.column_id == c_hit.column_id); + let edge_x = match active_drag { + Some(d) => base_edge_x + (d.preview_width - d.start_width), + None => base_edge_x, + }; + if edge_x < v.column_x + block.x || edge_x > v.column_x + block.x + block.body.width { - let base_edge_x = v.column_x + block.x + c_hit.rect.right() - scroll_x; - let active_drag = cell - .col_resize_drag - .as_ref() - .filter(|d| d.column_id == c_hit.column_id); - let edge_x = match active_drag { - Some(d) => base_edge_x + (d.preview_width - d.start_width), - None => base_edge_x, - }; - if edge_x < v.column_x + block.x - || edge_x > v.column_x + block.x + block.body.width - { - continue; - } - let col_id = c_hit.column_id.clone(); - let col_w = c_hit.rect.w; - let is_dragging = active_drag.is_some(); - let snap_id = SharedString::from(format!("overlay.table_col_resize.{col_id}")); - let brand = palette.brand; - let guide_color = if is_dragging { - brand - } else { - ui::transparent_black() - }; - layer = layer.child( - div() - .id(SharedString::from(format!("tbl-col-resize-{col_id}"))) - .absolute() - .left(px((edge_x - 4.0).round())) - .top(px(vis_top)) - .w(px(8.0)) - .h(px(grip_h)) - .flex() - .items_center() - .justify_center() - .cursor(ui::CursorStyle::ResizeLeftRight) - .hover(move |s| s.bg(brand.opacity(0.22))) - .on_mouse_down( - MouseButton::Left, - cx.listener(move |this, ev: &MouseDownEvent, _, cx| { - cx.stop_propagation(); - 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(8.0)) - .h(px(grip_h)) - .flex() - .items_center() - .justify_center() - .snapshot(snap_id, Some("root.canvas")) - .child(div().w(px(2.0)).h(px(grip_h)).bg(guide_color)), - ), - ); + continue; } + let bid = active_block_id.to_string(); + let rid = first_row_id.to_string(); + let col_id = c_hit.column_id.clone(); + let col_w = c_hit.rect.w; + let is_dragging = active_drag.is_some(); + let snap_id = SharedString::from(format!("overlay.table_col_resize.{col_id}")); + let guide_color = if is_dragging { + active_blue + } else { + ui::transparent_black() + }; + layer = layer.child( + div() + .id(SharedString::from(format!("tbl-col-resize-{col_id}"))) + .absolute() + .left(px((edge_x - 2.5).round())) + .top(px(vis_top)) + .w(px(5.0)) + .h(px(table_vis_h)) + .flex() + .items_center() + .justify_center() + .cursor(CursorStyle::ResizeLeftRight) + .hover(move |s| s.bg(active_blue.opacity(0.35))) + .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) { + this.focus_table_cell( + bid.clone(), + rid.clone(), + col_id.clone(), + 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(5.0)) + .h(px(table_vis_h)) + .flex() + .items_center() + .justify_center() + .snapshot(snap_id, Some("root.canvas")) + .child(div().w(px(2.0)).h(px(table_vis_h)).bg(guide_color)), + ), + ); } } - layer = layer.child(self.build_desktop_table_toolbar(bar_x, screen_y, palette, cx)); - if let Some(axis_menu) = cell.axis_menu { + // 2. Hover-revealed 16 px add-column bar (right), add-row bar (bottom), and 16 × 16 corner. + let bar_idle = palette + .theme + .css_var("--affine-v2-table-indicator-hover") + .unwrap_or(palette.hover); + let bar_hover = palette + .theme + .css_var("--affine-v2-table-indicator-drag") + .unwrap_or(palette.border); + let plus_ink = palette.text_secondary; + let bid_owned = active_block_id.to_string(); + + let make_add_bar = |id: &'static str, + snap: &'static str, + rect: FlowRect, + cursor: CursorStyle, + kind: TableAddDragKind, + cx: &mut ui::Context| { + let bid = bid_owned.clone(); + let (init_r, init_c) = match kind { + TableAddDragKind::Row => (1, 0), + TableAddDragKind::Column => (0, 1), + TableAddDragKind::Both => (1, 1), + }; + div() + .id(id) + .absolute() + .left(px(rect.x)) + .top(px(rect.y)) + .w(px(rect.w)) + .h(px(rect.h)) + .rounded(px(4.0)) + .bg(bar_idle) + .opacity(fade) + .flex() + .items_center() + .justify_center() + .cursor(cursor) + .hover(move |s| s.bg(bar_hover)) + .text_size(px(12.0)) + .font_weight(FontWeight::MEDIUM) + .text_color(plus_ink) + .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: init_r, + preview_cols: init_c, + moved: false, + }); + cx.notify(); + }), + ) + .child( + div() + .w(px(rect.w)) + .h(px(rect.h)) + .flex() + .items_center() + .justify_center() + .snapshot(snap, Some("root.canvas")) + .snapshot_text("+") + .child("+"), + ) + }; + + if table_vis_h > 0.0 && table_screen_right + 18.0 <= viewport_width { + layer = layer.child(make_add_bar( + "tbl-hover-add-col", + "overlay.table_hover.add_col", + FlowRect::new(table_screen_right + 2.0, vis_top, 16.0, table_vis_h), + CursorStyle::ResizeLeftRight, + TableAddDragKind::Column, + cx, + )); + } + if table_vis_w > 0.0 && table_screen_bottom + 18.0 <= v.height { + layer = layer.child(make_add_bar( + "tbl-hover-add-row", + "overlay.table_hover.add_row", + FlowRect::new( + table_screen_left, + table_screen_bottom + 2.0, + table_vis_w, + 16.0, + ), + CursorStyle::ResizeUpDown, + TableAddDragKind::Row, + cx, + )); + } + if table_screen_right + 18.0 <= viewport_width && table_screen_bottom + 18.0 <= v.height { + layer = layer.child(make_add_bar( + "tbl-hover-add-corner", + "overlay.table_hover.add_corner", + FlowRect::new( + table_screen_right + 2.0, + table_screen_bottom + 2.0, + 16.0, + 16.0, + ), + CursorStyle::ResizeUpLeftDownRight, + TableAddDragKind::Both, + cx, + )); + } + + // Live drag-to-add N×M count badge. + if let Some(drag) = self.overlays.table_hover.add_drag.as_ref() + && drag.block_id == active_block_id + && drag.moved + && drag.preview_rows + drag.preview_cols > 0 + { + let tip = match drag.kind { + TableAddDragKind::Row => format!("+{} row", drag.preview_rows), + TableAddDragKind::Column => format!("+{} col", drag.preview_cols), + TableAddDragKind::Both => format!("{}×{}", drag.preview_rows, drag.preview_cols), + }; + let tip_bg = palette + .theme + .css_var("--affine-tooltip") + .unwrap_or(palette.text_primary); + let tip_fg = palette + .theme + .css_var("--affine-pure-white") + .unwrap_or(palette.panel); + layer = layer.child( + div() + .id("tbl-add-drag-tip") + .absolute() + .left(px((table_screen_right + 22.0).min(viewport_width - 72.0))) + .top(px((table_screen_bottom + 2.0).min(v.height - 28.0))) + .h(px(22.0)) + .px(px(6.0)) + .rounded(px(4.0)) + .bg(tip_bg) + .flex() + .items_center() + .justify_center() + .text_size(px(TYPOGRAPHY.font_xs_px)) + .font_weight(FontWeight::MEDIUM) + .text_color(tip_fg) + .snapshot("overlay.table_hover.drag_tip", Some("root.canvas")) + .snapshot_text(tip.clone()) + .child(tip), + ); + } + + // 3. Top 28 × 16 column pill & Left 16 × 28 row pill with three 3 px dots. + let target_row_id = focused_cell + .map(|c| c.row_id.as_str()) + .or(self.overlays.table_hover.row_id.as_deref()) + .or_else(|| block.body.table_cells.first().map(|c| c.row_id.as_str())); + let target_col_id = focused_cell + .map(|c| c.column_id.as_str()) + .or(self.overlays.table_hover.column_id.as_deref()) + .or_else(|| block.body.table_cells.first().map(|c| c.column_id.as_str())); + + let dot_color = palette + .theme + .css_var("--affine-v2-table-indicator-pointerDefault") + .unwrap_or(palette.icon); + let pill_bg = chrome_panel_bg(palette); + let pill_border = chrome_border_color(palette); + let pill_shadow = palette.theme.shadows("--affine-button-shadow"); + let mut col_pill_anchor = FlowRect::new(table_screen_left, table_screen_top, 28.0, 16.0); + let mut row_pill_anchor = FlowRect::new(table_screen_left, table_screen_top, 16.0, 28.0); + + if let (Some(rid), Some(cid)) = (target_row_id, target_col_id) + && let Some(cell_hit) = block + .body + .table_cells + .iter() + .find(|c| c.row_id == rid && c.column_id == cid) + { + let col_cx = v.column_x + block.x + cell_hit.rect.x + cell_hit.rect.w * 0.5 - scroll_x; + let col_x = (col_cx - 14.0) + .clamp(4.0, (viewport_width - 32.0).max(4.0)) + .round(); + let col_y = (table_screen_top - 18.0).max(4.0).round(); + col_pill_anchor = FlowRect::new(col_x, col_y, 28.0, 16.0); + + let (bid_c, rid_c, cid_c) = (bid_owned.clone(), rid.to_string(), cid.to_string()); + layer = layer.child( + div() + .id("tbl-col-pill") + .absolute() + .left(px(col_x)) + .top(px(col_y)) + .w(px(28.0)) + .h(px(16.0)) + .rounded(px(8.0)) + .bg(pill_bg) + .border(px(TOOLBAR_CHROME_BORDER)) + .border_color(pill_border) + .shadow(pill_shadow.clone().into()) + .opacity(fade) + .flex() + .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| { + this.open_table_axis_menu_for( + bid_c.clone(), + rid_c.clone(), + cid_c.clone(), + TableAxisMenu::Column, + win, + cx, + ); + })) + .child( + div() + .w(px(28.0)) + .h(px(16.0)) + .flex() + .items_center() + .justify_center() + .gap(px(2.5)) + .snapshot("overlay.table_hover.col_pill", Some("root.canvas")) + .child(div().w(px(3.0)).h(px(3.0)).rounded(px(1.5)).bg(dot_color)) + .child(div().w(px(3.0)).h(px(3.0)).rounded(px(1.5)).bg(dot_color)) + .child(div().w(px(3.0)).h(px(3.0)).rounded(px(1.5)).bg(dot_color)), + ), + ); + + let row_cy = block.y + cell_hit.rect.y + cell_hit.rect.h * 0.5 - v.scroll_y; + let row_x = (table_screen_left - 18.0).max(4.0).round(); + let row_y = (row_cy - 14.0) + .clamp(4.0, (v.height - 32.0).max(4.0)) + .round(); + row_pill_anchor = FlowRect::new(row_x, row_y, 16.0, 28.0); + + let (bid_r, rid_r, cid_r) = (bid_owned, rid.to_string(), cid.to_string()); + layer = layer.child( + div() + .id("tbl-row-pill") + .absolute() + .left(px(row_x)) + .top(px(row_y)) + .w(px(16.0)) + .h(px(28.0)) + .rounded(px(8.0)) + .bg(pill_bg) + .border(px(TOOLBAR_CHROME_BORDER)) + .border_color(pill_border) + .shadow(pill_shadow.clone().into()) + .opacity(fade) + .flex() + .flex_col() + .items_center() + .justify_center() + .cursor_pointer() + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(cx.listener(move |this, _, win, cx| { + this.open_table_axis_menu_for( + bid_r.clone(), + rid_r.clone(), + cid_r.clone(), + TableAxisMenu::Row, + win, + cx, + ); + })) + .child( + div() + .w(px(16.0)) + .h(px(28.0)) + .flex() + .flex_col() + .items_center() + .justify_center() + .gap(px(2.5)) + .snapshot("overlay.table_hover.row_pill", Some("root.canvas")) + .child(div().w(px(3.0)).h(px(3.0)).rounded(px(1.5)).bg(dot_color)) + .child(div().w(px(3.0)).h(px(3.0)).rounded(px(1.5)).bg(dot_color)) + .child(div().w(px(3.0)).h(px(3.0)).rounded(px(1.5)).bg(dot_color)), + ), + ); + } + + if let Some(axis_menu) = focused_cell.and_then(|c| c.axis_menu) { + let (ax, ay) = match axis_menu { + TableAxisMenu::Column => (col_pill_anchor.x, col_pill_anchor.bottom() + 4.0), + TableAxisMenu::Row => (row_pill_anchor.right() + 4.0, row_pill_anchor.y), + }; layer = layer.child(self.build_table_axis_menu( axis_menu, - bar_x + bar_w - 180.0, - screen_y + bar_h + 6.0, + ax, + ay, v.height, viewport_width, palette, cx, )); } - let _ = table_right; Some(layer.into_any_element()) } - /// Mount the floating desktop table toolbar when editing a table cell inside an Edgeless Note. + fn open_table_axis_menu_for( + &mut self, + block_id: String, + row_id: String, + column_id: String, + kind: TableAxisMenu, + window: &mut Window, + cx: &mut ui::Context, + ) { + let same_cell = self.table_cell.as_ref().is_some_and(|c| { + c.block_id == block_id && c.row_id == row_id && c.column_id == column_id + }); + if !same_cell { + self.focus_table_cell(block_id, row_id, column_id, None, window, cx); + } + if let Some(cell) = self.table_cell.as_mut() { + cell.axis_menu = if same_cell && cell.axis_menu == Some(kind) { + None + } else { + Some(kind) + }; + } + cx.notify(); + } + + /// Mount the axis menu when editing a table cell inside an Edgeless Note. pub(crate) fn render_edgeless_table_toolbar( &self, layout: &FlowLayout, @@ -212,213 +542,28 @@ impl PlaygroundView { let Some(cell) = self.table_cell.as_ref() else { return out; }; + let Some(axis_menu) = cell.axis_menu else { + return out; + }; let Some(block) = layout.block(&cell.block_id) else { return out; }; let Some(t) = transform else { return out; }; - let (_, table_bottom) = block - .body - .table_cells - .iter() - .fold((0.0_f32, 0.0_f32), |(max_r, max_b), c| { - (max_r.max(c.rect.right()), max_b.max(c.rect.bottom())) - }); - let world = FlowRect::new(block.x, block.y, block.body.width, table_bottom.max(40.0)); - let screen = t.rect_to_screen(&world); - let bar_w = 436.0; - let bar_h = 32.0; - let x = screen - .x - .clamp(8.0, (self.window_size.0 - bar_w - 8.0).max(8.0)) - .round(); - let y = (screen.bottom() + 8.0) - .clamp( - TOPBAR_HEIGHT + 8.0, - (self.window_size.1 - bar_h - 8.0).max(TOPBAR_HEIGHT + 8.0), - ) - .round(); - out.push(self.build_desktop_table_toolbar(x, y, palette, cx)); - if let Some(axis_menu) = cell.axis_menu { - out.push(self.build_table_axis_menu( - axis_menu, - x + bar_w - 180.0, - y + bar_h + 6.0, - self.window_size.1, - self.window_size.0, - palette, - cx, - )); - } + let screen = t.rect_to_screen(&FlowRect::new(block.x, block.y, block.body.width, 40.0)); + out.push(self.build_table_axis_menu( + axis_menu, + screen.x, + (screen.y + 8.0).max(TOPBAR_HEIGHT + 8.0), + self.window_size.1, + self.window_size.0, + palette, + cx, + )); out } - fn build_desktop_table_toolbar( - &self, - bar_x: f32, - screen_y: f32, - palette: &Palette, - cx: &mut ui::Context, - ) -> AnyElement { - let hover = palette.hover; - let btn = - |id: &'static str, - snap_suffix: &'static str, - label: &'static str, - on_click: fn(&mut Self, &mut Window, &mut ui::Context) -> bool| { - div() - .id(id) - .h(px(24.0)) - .px(px(6.0)) - .rounded(px(6.0)) - .flex() - .items_center() - .justify_center() - .cursor_pointer() - .hover(move |s| s.bg(hover)) - .text_size(px(11.0)) - .font_weight(FontWeight::MEDIUM) - .text_color(palette.text_primary) - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_click(cx.listener(move |this, _, win, cx| { - let _ = on_click(this, win, cx); - })) - .snapshot( - SharedString::from(format!("overlay.table_toolbar.{snap_suffix}")), - Some("overlay.table_toolbar"), - ) - .snapshot_text(label) - .child(label) - }; - let menu_btn = |id: &'static str, - snap_suffix: &'static str, - label: &'static str, - kind: TableAxisMenu| { - let active = self - .table_cell - .as_ref() - .is_some_and(|c| c.axis_menu == Some(kind)); - let ink = palette.text_secondary; - div() - .id(id) - .h(px(24.0)) - .px(px(6.0)) - .rounded(px(6.0)) - .flex() - .items_center() - .justify_center() - .gap(px(3.0)) - .cursor_pointer() - .when(active, |el| el.bg(hover)) - .hover(move |s| s.bg(hover)) - .text_size(px(11.0)) - .font_weight(FontWeight::MEDIUM) - .text_color(palette.text_primary) - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_click(cx.listener(move |this, _, _, cx| { - if let Some(cell) = this.table_cell.as_mut() { - cell.axis_menu = if cell.axis_menu == Some(kind) { - None - } else { - Some(kind) - }; - } - cx.notify(); - })) - .snapshot( - SharedString::from(format!("overlay.table_toolbar.{snap_suffix}")), - Some("overlay.table_toolbar"), - ) - .snapshot_text(label) - .child(label) - .child( - ui::canvas( - |_, _, _| (), - move |bounds, (), window, cx| { - crate::theme::IconPaint::named("MoreHorizontalIcon") - .paint(bounds, ink, window, cx); - }, - ) - .w(px(12.0)) - .h(px(12.0)), - ) - }; - - div() - .id("table-toolbar") - .absolute() - .left(px(bar_x)) - .top(px(screen_y)) - .h(px(32.0)) - .px(px(4.0)) - .rounded(px(8.0)) - .bg(palette.panel) - .border_1() - .border_color(palette.border) - .shadow( - palette - .theme - .shadows("--affine-overlay-panel-shadow") - .into(), - ) - .flex() - .items_center() - .gap(px(2.0)) - .occlude() - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .snapshot("overlay.table_toolbar", Some("root.canvas")) - .child(btn( - "tbl-add-row-before", - "add_row_before", - "+↑ Row", - Self::table_insert_row_before, - )) - .child(btn( - "tbl-add-row", - "add_row", - "+ Row", - Self::table_insert_row_after, - )) - .child(btn( - "tbl-del-row", - "del_row", - "- Row", - Self::table_delete_focused_row, - )) - .child(btn( - "tbl-add-col-before", - "add_col_before", - "+← Col", - Self::table_insert_column_before, - )) - .child(btn( - "tbl-add-col", - "add_col", - "+ Col", - Self::table_insert_column_after, - )) - .child(btn( - "tbl-del-col", - "del_col", - "- Col", - Self::table_delete_focused_column, - )) - .child(menu_btn( - "tbl-row-menu", - "row_menu", - "Row", - TableAxisMenu::Row, - )) - .child(menu_btn( - "tbl-col-menu", - "col_menu", - "Col", - TableAxisMenu::Column, - )) - .into_any_element() - } - #[allow(clippy::too_many_arguments)] fn build_table_axis_menu( &self, @@ -431,11 +576,14 @@ impl PlaygroundView { cx: &mut ui::Context, ) -> AnyElement { let is_row = axis == TableAxisMenu::Row; - let menu_w = 188.0; - let menu_h = 172.0; + let menu_w = TOOLBAR_MENU_MIN_W.max(196.0); + let menu_h = 264.0; let left = x.clamp(8.0, (viewport_w - menu_w - 8.0).max(8.0)).round(); let top = y.clamp(8.0, (viewport_h - menu_h - 8.0).max(8.0)).round(); let hover = palette.hover; + let err_bg = chrome_error_bg(palette); + let err_fg = chrome_error_fg(palette); + let mut swatches = div() .flex() .items_center() @@ -446,6 +594,7 @@ impl PlaygroundView { swatches = swatches.child( div() .id(SharedString::from(format!("tbl-bg-{name}"))) + .flex_none() .w(px(24.0)) .h(px(24.0)) .rounded(px(4.0)) @@ -471,24 +620,26 @@ impl PlaygroundView { |id: &'static str, snap: &'static str, label: &'static str, - danger: bool, + destructive: bool, f: Box)>| { + let h_bg = if destructive { err_bg } else { hover }; + let h_fg = if destructive { + err_fg + } else { + palette.text_primary + }; div() .id(id) .w_full() - .h(px(26.0)) + .h(px(TOOLBAR_MENU_ROW_H)) .px(px(8.0)) .rounded(px(4.0)) .flex() .items_center() .cursor_pointer() - .hover(move |s| s.bg(hover)) - .text_size(px(12.0)) - .text_color(if danger { - ui::rgb(0xeb4335).into() - } else { - palette.text_primary - }) + .text_size(px(TYPOGRAPHY.font_sm_px)) + .text_color(palette.text_primary) + .hover(move |s| s.bg(h_bg).text_color(h_fg)) .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_click(cx.listener(move |this, _, win, cx| f(this, win, cx))) .snapshot( @@ -498,14 +649,6 @@ impl PlaygroundView { .snapshot_text(label) .child(label) }; - let move_earlier_label = if is_row { "Move Up" } else { "Move Left" }; - let move_later_label = if is_row { "Move Down" } else { "Move Right" }; - let clear_label = if is_row { "Clear Row" } else { "Clear Column" }; - let delete_label = if is_row { - "Delete Row" - } else { - "Delete Column" - }; div() .id("table-axis-menu") @@ -513,20 +656,14 @@ impl PlaygroundView { .left(px(left)) .top(px(top)) .w(px(menu_w)) - .p(px(4.0)) - .rounded(px(8.0)) - .bg(palette.panel) - .border_1() - .border_color(palette.border) - .shadow( - palette - .theme - .shadows("--affine-overlay-panel-shadow") - .into(), - ) + .p(px(TOOLBAR_MENU_PADDING)) + .rounded(px(TOOLBAR_CHROME_RADIUS)) + .bg(chrome_panel_bg(palette)) + .border(px(TOOLBAR_CHROME_BORDER)) + .border_color(chrome_border_color(palette)) + .shadow(palette.theme.shadows("--affine-overlay-shadow").into()) .flex() .flex_col() - .gap(px(2.0)) .occlude() .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_mouse_down_out(cx.listener(|this, _, _, cx| { @@ -536,28 +673,56 @@ impl PlaygroundView { cx.notify(); } })) - .snapshot( - "overlay.table_toolbar.axis_menu", - Some("overlay.table_toolbar"), - ) + .snapshot("overlay.table_toolbar.axis_menu", Some("root.canvas")) .child( div() .px(px(8.0)) .py(px(2.0)) - .text_size(px(11.0)) + .text_size(px(TYPOGRAPHY.font_xs_px)) .font_weight(FontWeight::MEDIUM) .text_color(palette.text_secondary) - .child(if is_row { - "Row background" - } else { - "Column background" - }), + .child("Background color"), ) .child(swatches) + .child(menu_horizontal_separator(palette)) + .child(action_row( + "tbl-axis-insert-before", + "insert_before", + if is_row { + "Insert Above" + } else { + "Insert Left" + }, + false, + Box::new(move |this, win, cx| { + if is_row { + let _ = this.table_insert_row_before(win, cx); + } else { + let _ = this.table_insert_column_before(win, cx); + } + }), + )) + .child(action_row( + "tbl-axis-insert-after", + "insert_after", + if is_row { + "Insert Below" + } else { + "Insert Right" + }, + false, + Box::new(move |this, win, cx| { + if is_row { + let _ = this.table_insert_row_after(win, cx); + } else { + let _ = this.table_insert_column_after(win, cx); + } + }), + )) .child(action_row( "tbl-axis-earlier", "move_earlier", - move_earlier_label, + if is_row { "Move Up" } else { "Move Left" }, false, Box::new(move |this, win, cx| { let _ = this.table_move_axis(is_row, true, win, cx); @@ -566,16 +731,21 @@ impl PlaygroundView { .child(action_row( "tbl-axis-later", "move_later", - move_later_label, + if is_row { "Move Down" } else { "Move Right" }, false, Box::new(move |this, win, cx| { let _ = this.table_move_axis(is_row, false, win, cx); }), )) + .child(menu_horizontal_separator(palette)) .child(action_row( "tbl-axis-clear", "clear", - clear_label, + if is_row { + "Clear row contents" + } else { + "Clear column contents" + }, false, Box::new(move |this, win, cx| { let _ = this.table_clear_axis(is_row, win, cx); @@ -584,7 +754,11 @@ impl PlaygroundView { .child(action_row( "tbl-axis-delete", "delete", - delete_label, + if is_row { + "Delete Row" + } else { + "Delete Column" + }, true, Box::new(move |this, win, cx| { if is_row { @@ -596,127 +770,4 @@ impl PlaygroundView { )) .into_any_element() } - - fn build_touch_table_toolbar( - &self, - v: PageViewport, - viewport_width: f32, - palette: &Palette, - cx: &mut ui::Context, - ) -> AnyElement { - let hover = palette.hover; - let slot_h = super::KEYBOARD_TOOLBAR_HEIGHT; - let bar_w = viewport_width.max(240.0).floor(); - let screen_y = (v.height - self.ime_insets.last_bottom - slot_h) - .max(8.0) - .floor(); - let btn = - |id: &'static str, - snap_suffix: &'static str, - label: &'static str, - on_click: fn(&mut Self, &mut Window, &mut ui::Context) -> bool| { - div() - .id(id) - .min_w(px(44.0)) - .h(px(44.0)) - .px(px(8.0)) - .rounded(px(6.0)) - .flex() - .items_center() - .justify_center() - .cursor_pointer() - .hover(move |s| s.bg(hover)) - .text_size(px(12.0)) - .font_weight(FontWeight::MEDIUM) - .text_color(palette.text_primary) - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_click(cx.listener(move |this, _, win, cx| { - let _ = on_click(this, win, cx); - })) - .snapshot( - SharedString::from(format!("overlay.table_toolbar.{snap_suffix}")), - Some("overlay.table_toolbar"), - ) - .snapshot_text(label) - .child(label) - }; - let more_btn = div() - .id("tbl-more") - .min_w(px(44.0)) - .h(px(44.0)) - .px(px(8.0)) - .rounded(px(6.0)) - .flex() - .items_center() - .justify_center() - .cursor_pointer() - .hover(move |s| s.bg(hover)) - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_click(cx.listener(|this, _, win, cx| { - this.finish_inline_targets( - super::InlineTargetEnd::CommitPreedit, - Some(win), - Some(cx), - ); - cx.notify(); - })) - .snapshot("overlay.table_toolbar.more", Some("overlay.table_toolbar")) - .snapshot_text("More") - .child({ - let ink = palette.text_secondary; - ui::canvas( - |_, _, _| (), - move |bounds, (), window, cx| { - crate::theme::IconPaint::named("MoreHorizontalIcon") - .paint(bounds, ink, window, cx); - }, - ) - .w(px(16.0)) - .h(px(16.0)) - }); - div() - .id("table-toolbar") - .absolute() - .left(px(0.0)) - .top(px(screen_y)) - .w(px(bar_w)) - .h(px(slot_h)) - .px(px(8.0)) - .bg(palette.panel) - .border_1() - .border_color(palette.border) - .flex() - .items_center() - .justify_center() - .gap(px(4.0)) - .occlude() - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .snapshot("overlay.table_toolbar", Some("root.canvas")) - .child(btn( - "tbl-add-row", - "add_row", - "+ Row", - Self::table_insert_row_after, - )) - .child(btn( - "tbl-del-row", - "del_row", - "- Row", - Self::table_delete_focused_row, - )) - .child(btn( - "tbl-add-col", - "add_col", - "+ Col", - Self::table_insert_column_after, - )) - .child(btn( - "tbl-del-col", - "del_col", - "- Col", - Self::table_delete_focused_column, - )) - .child(more_btn) - .into_any_element() - } } diff --git a/blocksuite/crates/playground/src/overlays/view_table_cell/touch_bar.rs b/blocksuite/crates/playground/src/overlays/view_table_cell/touch_bar.rs new file mode 100644 index 0000000000..e8835dd755 --- /dev/null +++ b/blocksuite/crates/playground/src/overlays/view_table_cell/touch_bar.rs @@ -0,0 +1,133 @@ +//! Mobile bottom table action bar (`overlay.table_toolbar`) for touch viewports. + +use ui::{AnyElement, FontWeight, MouseButton, SharedString, Window, div, prelude::*, px}; + +use crate::{PlaygroundView, theme::Palette}; + +use super::PageViewport; + +impl PlaygroundView { + pub(super) fn build_touch_table_toolbar( + &self, + v: PageViewport, + viewport_width: f32, + palette: &Palette, + cx: &mut ui::Context, + ) -> AnyElement { + let hover = palette.hover; + let slot_h = super::KEYBOARD_TOOLBAR_HEIGHT; + let bar_w = viewport_width.max(240.0).floor(); + let screen_y = (v.height - self.ime_insets.last_bottom - slot_h) + .max(8.0) + .floor(); + let btn = + |id: &'static str, + snap_suffix: &'static str, + label: &'static str, + on_click: fn(&mut Self, &mut Window, &mut ui::Context) -> bool| { + div() + .id(id) + .min_w(px(44.0)) + .h(px(44.0)) + .px(px(8.0)) + .rounded(px(6.0)) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .hover(move |s| s.bg(hover)) + .text_size(px(12.0)) + .font_weight(FontWeight::MEDIUM) + .text_color(palette.text_primary) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(cx.listener(move |this, _, win, cx| { + let _ = on_click(this, win, cx); + })) + .snapshot( + SharedString::from(format!("overlay.table_toolbar.{snap_suffix}")), + Some("overlay.table_toolbar"), + ) + .snapshot_text(label) + .child(label) + }; + div() + .id("table-toolbar") + .absolute() + .left(px(0.0)) + .top(px(screen_y)) + .w(px(bar_w)) + .h(px(slot_h)) + .px(px(8.0)) + .bg(palette.panel) + .border_1() + .border_color(palette.border) + .flex() + .items_center() + .justify_center() + .gap(px(4.0)) + .occlude() + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .snapshot("overlay.table_toolbar", Some("root.canvas")) + .child(btn( + "tbl-add-row", + "add_row", + "+ Row", + Self::table_insert_row_after, + )) + .child(btn( + "tbl-del-row", + "del_row", + "- Row", + Self::table_delete_focused_row, + )) + .child(btn( + "tbl-add-col", + "add_col", + "+ Col", + Self::table_insert_column_after, + )) + .child(btn( + "tbl-del-col", + "del_col", + "- Col", + Self::table_delete_focused_column, + )) + .child( + div() + .id("tbl-more") + .min_w(px(44.0)) + .h(px(44.0)) + .px(px(8.0)) + .rounded(px(6.0)) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .hover(move |s| s.bg(hover)) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(cx.listener(|this, _, win, cx| { + this.finish_inline_targets( + super::InlineTargetEnd::CommitPreedit, + Some(win), + Some(cx), + ); + cx.notify(); + })) + .snapshot("overlay.table_toolbar.more", Some("overlay.table_toolbar")) + .snapshot_text("More") + .child({ + let ink = palette.text_secondary; + ui::canvas( + |_, _, _| (), + move |bounds, (), window, cx| { + crate::theme::IconPaint::named("MoreHorizontalIcon") + .paint(bounds, ink, window, cx); + }, + ) + .w(px(16.0)) + .h(px(16.0)) + }), + ) + .into_any_element() + } +} diff --git a/packages/frontend/scripts/web-smoke.mjs b/packages/frontend/scripts/web-smoke.mjs index 9618845c5d..a5c723d53c 100755 --- a/packages/frontend/scripts/web-smoke.mjs +++ b/packages/frontend/scripts/web-smoke.mjs @@ -414,11 +414,12 @@ async function checkLinkField(cdp) { `Unable to select in the second showcase block: ${JSON.stringify(paragraph)}` ); } - // The 14-button desktop toolbar is 481 px wide and centered 46 px above the selected - // line; its ninth button (Link, +277 px from left edge) opens the dual-field Text+URL - // editor with keyboard/IME focus starting in the empty URL field. + // A selection in one paragraph shows the full desktop toolbar with `Create Table`: + // 490 px wide and 37 px tall, centered on the selection 10 px above the selected line. + // Its `Link` button (center 299 px from the left edge, 18 px from the top) opens the + // dual-field Text+URL editor with keyboard/IME focus starting in the empty URL field. const midX = (from[0] + to[0]) / 2; - const link = [midX - 240.5 + 277, 243 - 46 + 19]; + const link = [midX - 245 + 299, 243 - 10 - 37 + 18]; await mouse('mouseMoved', link, 0); await mouse('mousePressed', link, 1); await mouse('mouseReleased', link, 0); @@ -462,12 +463,14 @@ async function checkLinkField(cdp) { // Dual-field LinkBar: clicking the Text row mirrors the selected paragraph slice, and // clicking back to the URL row restores focus to the typed/pasted URL. const selectedSlice = paragraph.value.slice(paragraph.offset, paragraph.end); - const textFieldPt = [midX, 243 - 8 - 102 + 5 + 32 + 14]; + // With both fields open the toolbar is 100 px tall: the Text row starts 37 px and the + // URL row 65 px below its top edge, and each row is 28 px tall. + const textFieldPt = [midX, 243 - 10 - 100 + 37 + 14]; await mouse('mouseMoved', textFieldPt, 0); await mouse('mousePressed', textFieldPt, 1); await mouse('mouseReleased', textFieldPt, 0); await waitValue(selectedSlice); - const urlFieldPt = [midX - 40, 243 - 8 - 102 + 5 + 64 + 14]; + const urlFieldPt = [midX - 40, 243 - 10 - 100 + 65 + 14]; await mouse('mouseMoved', urlFieldPt, 0); await mouse('mousePressed', urlFieldPt, 1); await mouse('mouseReleased', urlFieldPt, 0);