diff --git a/blocksuite/crates/AGENTS.md b/blocksuite/crates/AGENTS.md index c364469bac..539f2f807b 100644 --- a/blocksuite/crates/AGENTS.md +++ b/blocksuite/crates/AGENTS.md @@ -39,14 +39,14 @@ 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` 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). +- **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 in Page mode or inside an Active Note (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 code`, `Line number`, `Copy as Markdown`, `Copy link`, `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`, and pinned `.delete` and `.more`. The touch More menu offers `Copy as Markdown`, `Copy link`, and `Duplicate`. Both menus keep the copy actions available on read-only pages. Collapsed code has 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`. A mouse image resize owns the pointer until the release, so the toolbar inside the image never takes the move or the release. Block-level `affine:latex` uses 2-step selection (first click selects block, second click opens `overlay.equation_editor`). A sideways scroll over an unwrapped code block scrolls its lines inside `BlockBody::code_scroll` instead of the page; the caret, selection, IME bounds, collaborators' carets/selections, and pointer hit-testing follow that scroll (`ScrolledCode`). +- **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 code`, `Line number`, `Copy as Markdown`, `Copy link to block`, `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`, and pinned `.delete` and `.more`. The touch More menu offers `Copy as Markdown`, `Copy link to block`, and `Duplicate`. Both menus keep the copy actions available on read-only pages. Collapsed code has 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`. A mouse image resize owns the pointer until the release, so the toolbar inside the image never takes the move or the release. Block-level `affine:latex` uses 2-step selection (first click selects block, second click opens `overlay.equation_editor`). A sideways scroll over an unwrapped code block scrolls its lines inside `BlockBody::code_scroll` instead of the page; the caret, selection, IME bounds, collaborators' carets/selections, and pointer hit-testing follow that scroll (`ScrolledCode`). - **Sizes and radii**: Interactive targets are at least 24 × 24 px on desktop (touch host controls `>= 44 pt` height). Desktop floating toolbars share `ToolbarChrome` (`toolbar_chrome/`): a 36 px tall bar with a 0.5 px border, 8 px radius, 24 × 24 px buttons with 20 px icons and 4 px radius, groups split by 4 px separator slots, a 10 px offset from the anchor, 8 px dropdown panels with 30 px rows, and tooltips 8 px above the hovered button after the shared 500 ms enter / 250 ms leave hover delay (none while a toolbar dropdown is open). On viewports `>= 460 px` the formatting toolbar shows every group (`Turn into`, `Align`, seven inline marks, `Highlight`, `Create Table` when allowed, `Create Linked Doc`, `More`) with 8 px group gaps and 6 px side padding: 490 px wide with `Create Table`, 462 px without. On viewports `< 460 px` it shows the `FormatAction::COMPACT` set (`Turn into`, `Align`, `Bold`, `Italic`, `Underline`, `Strike`, `Code`, `Link`, `Highlight`) with 4 px group gaps and 4 px side padding, 296 px wide, so it fits a 320 px window between its 8 px margins. All floating popovers and toolbars fade opacity monotonically in place over 150 ms with zero entrance/exit coordinate drift. - **Verification**: `bs-harness render --state ` renders one overlay state of the showcase, `bs-harness audit-states` audits every state in both themes at `1280` and `320` px, and `bs-harness record-demo ` writes the frames of a 60 fps walk through typing, composition, the slash menu, the toolbar and the block controls; all drive the view through input events, the input handler and `dispatch_overlay` only. diff --git a/blocksuite/crates/editor/src/overlays/code_toolbar/more_menu.rs b/blocksuite/crates/editor/src/overlays/code_toolbar/more_menu.rs index eddc79c12e..1754dfb886 100644 --- a/blocksuite/crates/editor/src/overlays/code_toolbar/more_menu.rs +++ b/blocksuite/crates/editor/src/overlays/code_toolbar/more_menu.rs @@ -185,6 +185,7 @@ impl Overlays { .items_center() .gap(px(8.0)) .text_size(px(13.0)) + .whitespace_nowrap() .text_color(palette.text_primary) .child(icon(glyph, 16.0, palette.icon)) .child(label) @@ -272,7 +273,7 @@ impl Overlays { .child(make_row( "copy_block_link", "LinkIcon", - "Copy link", + "Copy link to block", None, CodeMoreActionKind::CopyLink { generation, diff --git a/blocksuite/crates/playground/src/overlays/view_link_popup/active_note_tests.rs b/blocksuite/crates/playground/src/overlays/view_link_popup/active_note_tests.rs new file mode 100644 index 0000000000..42c67ad95d --- /dev/null +++ b/blocksuite/crates/playground/src/overlays/view_link_popup/active_note_tests.rs @@ -0,0 +1,267 @@ +use ui::{EntityInputHandler as _, point, px}; + +use crate::{ + PlaygroundMode, PlaygroundView, + block_flow::FlowRect, + overlays::{LINK_HOVER_DELAY_MS, TOOLBAR_CHROME_OFFSET, tests::Session}, + rich_text::DecorationKind, +}; + +use super::{LinkPopupTarget, OverlayEvent, matching_link_subranges, tests::open_links}; + +const POPUP: &str = "overlay.link_popup"; +const URL: &str = "https://same.example/"; +const NEW_URL: &str = "https://updated.example/"; + +fn advance(session: &Session) { + session + .platform + .advance_clock(std::time::Duration::from_millis(LINK_HOVER_DELAY_MS as u64)); + session.platform.run_until_parked(); +} + +fn link_screen(view: &PlaygroundView, id: &str) -> FlowRect { + let (_, layout, transform) = view.active_overlay_target().unwrap(); + let block = layout.block(id).unwrap(); + let text = block.body.text.as_ref().unwrap(); + let decoration = text + .layout + .decorations() + .iter() + .find(|d| { + matches!( + d.kind, + DecorationKind::Link(_) | DecorationKind::ReferenceChip(_) + ) + }) + .unwrap(); + let b = decoration.bounds; + transform.unwrap().rect_to_screen(&FlowRect::new( + block.x + text.x + f32::from(b.origin.x), + block.y + text.y + f32::from(b.origin.y), + b.size.width.into(), + b.size.height.into(), + )) +} + +fn hover(session: &Session, span: FlowRect) -> ui::FrameSnapshot { + session.pointer(span.x + span.w * 0.5, span.y + span.h * 0.5, false); + advance(session); + session.settle() +} + +fn check_popup_anchor(frame: &ui::FrameSnapshot, span: FlowRect) { + let popup = frame.elements[POPUP].bounds; + let above = (popup.bottom() + TOOLBAR_CHROME_OFFSET - span.y).abs() < 1.0; + let below = (popup.y - TOOLBAR_CHROME_OFFSET - span.bottom()).abs() < 1.0; + assert!(above || below, "{popup:?} should sit next to {span:?}"); + assert!(popup.x < span.right() && popup.right() > span.x); +} + +fn save_frame(session: &Session, name: &str) { + if let Some(dir) = std::env::var_os("EDGELESS_EVIDENCE_DIR") { + let dir = std::path::PathBuf::from(dir); + std::fs::create_dir_all(&dir).unwrap(); + session + .app + .update(|cx| { + session + .window + .update(cx, |_, window, _| window.render_to_image()) + .unwrap() + }) + .unwrap() + .save(dir.join(name)) + .unwrap(); + } +} + +#[test] +fn active_note_link_hover_actions_and_exit_at_camera_zooms() { + for zoom in [0.75, 0.45, 1.0] { + let (session, _) = open_links(); + session.view(|view, cx| { + view.set_mode_immediate(PlaygroundMode::Edgeless, cx); + view.set_edgeless_camera(-200.0, -140.0, zoom, cx); + }); + let _ = session.settle(); + session.app.update(|cx| { + session + .window + .update(cx, |view, window, cx| { + assert!(view.edgeless_begin_inline_edit("n", window, cx)); + }) + .unwrap(); + }); + let _ = session.settle(); + + let link = session.view(|view, _| link_screen(view, "p-two")); + let frame = hover(&session, link); + if zoom == 0.75 { + save_frame(&session, "active-note-link-zoom075.png"); + } + check_popup_anchor(&frame, link); + session.click(&frame, "overlay.link_popup.copy"); + assert_eq!( + session + .app + .update(|cx| cx.read_from_clipboard().and_then(|item| item.text())) + .as_deref(), + Some(URL) + ); + + session.click(&session.settle(), "overlay.link_popup.edit"); + let editor = session.settle(); + assert!( + editor + .elements + .contains_key("overlay.format_toolbar.link_input") + ); + session.app.update(|cx| { + session + .window + .update(cx, |view, window, cx| { + view.replace_text_in_range(Some(0..URL.len()), NEW_URL, window, cx); + }) + .unwrap(); + }); + session.click(&session.settle(), "overlay.format_toolbar.link_apply"); + let marks = |url| { + session.view(|view, _| { + let (text, _) = view.page().unwrap().read_editable_text("p-two").unwrap(); + matching_link_subranges(&text, 0, 20, url) + }) + }; + assert_eq!(marks(NEW_URL), [(2, 7)]); + assert_eq!(marks(URL), [(12, 17)]); + session.undo(); + assert!(marks(NEW_URL).is_empty()); + assert_eq!(marks(URL), [(2, 7), (12, 17)]); + + // Clear the range left by Undo before opening the hover capsule again. + session.overlay(OverlayEvent::SetSelection(None)); + let _ = session.settle(); + let link = session.view(|view, _| link_screen(view, "p-two")); + session.pointer(1100.0, 700.0, false); + session.click(&hover(&session, link), "overlay.link_popup.more"); + session.click(&session.settle(), "overlay.link_popup.unlink"); + assert_eq!(marks(URL), [(12, 17)]); + session.undo(); + assert_eq!(marks(URL), [(2, 7), (12, 17)]); + + session.overlay(OverlayEvent::SetSelection(None)); + let _ = session.settle(); + let reference = session.view(|view, _| link_screen(view, "p-ref")); + let frame = hover(&session, reference); + check_popup_anchor(&frame, reference); + assert!(session.view(|view, _| matches!( + view.overlays.link_popup().map(|p| &p.target), + Some(LinkPopupTarget::Reference { page_id, .. }) if page_id == "target" + ))); + + // A click outside the Note ends inline editing and dismisses an open capsule. + let outside = point(px(1100.0), px(700.0)); + session.headless.simulate_click(outside); + assert!(!session.settle().elements.contains_key(POPUP)); + assert!(session.view(|v, _| v.edgeless.authoring.editing_spatial_block().is_none())); + assert!(!hover(&session, link).elements.contains_key(POPUP)); + } +} + +#[test] +fn active_note_reference_hover_aligns_and_opens_in_offset_pane() { + use ui::{ + AppContext as _, Application, Entity, HeadlessPlatform, WindowOptions, div, prelude::*, + }; + + use crate::PlaygroundOptions; + + const PANE_X: f32 = 240.0; + const PANE_Y: f32 = 86.0; + + struct SplitPane(Entity); + + impl Render for SplitPane { + fn render(&mut self, _: &mut ui::Window, _: &mut ui::Context) -> impl IntoElement { + div().relative().size_full().child( + div() + .absolute() + .left(px(PANE_X)) + .top(px(PANE_Y)) + .w(px(800.0)) + .h(px(600.0)) + .child(self.0.clone()), + ) + } + } + + let platform = HeadlessPlatform::new(1280, 800, 1.0); + let app = Application::with_platform(platform.clone()).run_embedded(|cx| { + crate::register_bundled_fonts(cx).unwrap(); + }); + let win = app.update(|cx| { + cx.open_window(WindowOptions::default(), |_, cx| { + let editor = cx.new(|cx| { + let mut view = PlaygroundView::with_options( + PlaygroundOptions { + hide_chrome: true, + mode: PlaygroundMode::Edgeless, + ..Default::default() + }, + cx, + ); + view.set_document(super::tests::link_document().0, cx); + view.set_edgeless_camera(-300.0, -180.0, 0.75, cx); + view + }); + cx.new(|_| SplitPane(editor)) + }) + .unwrap() + }); + let headless = platform.windows().into_iter().next().unwrap(); + let frame = || { + headless.request_frame(); + app.update(|cx| { + win.update(cx, |_, w, _| w.frame_snapshot().clone()) + .unwrap() + }) + }; + let _ = frame(); + let _ = frame(); + app.update(|cx| { + win.update(cx, |host, w, cx| { + host.0.update(cx, |view, cx| { + assert_eq!(view.pane_origin(), point(px(PANE_X), px(PANE_Y))); + assert!(view.edgeless_begin_inline_edit("n", w, cx)); + }); + }) + .unwrap(); + }); + let _ = frame(); + let span = app.update(|cx| { + win.update(cx, |host, _, cx| link_screen(host.0.read(cx), "p-ref")) + .unwrap() + }); + headless.dispatch_input(ui::PlatformInput::MouseMove(ui::MouseMoveEvent { + position: point(px(span.x + span.w * 0.5), px(span.y + span.h * 0.5)), + pressed_button: None, + modifiers: ui::Modifiers::default(), + })); + platform.run_until_parked(); + platform.advance_clock(std::time::Duration::from_millis( + (LINK_HOVER_DELAY_MS + 200.0) as u64, + )); + platform.run_until_parked(); + let opened = frame(); + check_popup_anchor(&opened, span); + let open = opened.elements["overlay.link_popup.open"].bounds; + headless.simulate_click(point(px(open.x + open.width * 0.5), px(open.center_y()))); + platform.run_until_parked(); + assert!(app.update(|cx| { + win.update(cx, |host, _, cx| { + host.0.read(cx).page_id.as_deref() == Some("target") + }) + .unwrap() + })); + assert!(!frame().elements.contains_key(POPUP)); +} 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 6889afa1b7..fdca8ea43b 100644 --- a/blocksuite/crates/playground/src/overlays/view_link_popup/mod.rs +++ b/blocksuite/crates/playground/src/overlays/view_link_popup/mod.rs @@ -5,13 +5,17 @@ mod actions; mod memo; +#[cfg(test)] +mod active_note_tests; + use blocksuite_editor::clipboard::sanitize::sanitize_url; -use ui::{Context, Window, point, px}; +use ui::{Bounds, Context, Window, point, px}; use y_octo::{Any, TextDeltaOp, TextInsert}; use crate::{ FormFactor, PlaygroundMode, PlaygroundView, block_flow::{FlowBlock, FlowLayout, FlowRect, FlowTextLayout}, + edgeless::NOTE_CARD_PADDING, rich_text::DecorationKind, }; @@ -439,13 +443,35 @@ impl PlaygroundView { window: &Window, known: Option<&LinkPopupTarget>, ) -> Option<(LinkPopupTarget, FlowRect, bool)> { - if self.mode != PlaygroundMode::Page { + let (origin, canvas_size) = self.canvas_rect(window); + let position = point(px(x), px(y)); + if !Bounds::new(origin, canvas_size).contains(&position) { return None; } - let layout = self.flow_layout()?; - let (_, canvas_size) = self.canvas_rect(window); - let geom = self.current_page_geometry(f32::from(canvas_size.width)); - let (wx, wy) = self.window_to_page_world(point(px(x), px(y)), geom.column_x); + let (_, layout, transform) = self.active_overlay_target()?; + let (wx, wy) = if let Some(transform) = transform { + let note_id = self.active_link_note_id()?; + let note = self + .edgeless + .authoring + .painted_items + .iter() + .find(|item| item.id == note_id)?; + let (wx, wy) = transform.screen_to_local(x, y); + let content = FlowRect::new( + 0.0, + 0.0, + note.rect.w / note.scale - 2.0 * NOTE_CARD_PADDING, + note.rect.h / note.scale - 2.0 * NOTE_CARD_PADDING, + ); + if !content.contains(wx, wy) { + return None; + } + (wx, wy) + } else { + let geom = self.current_page_geometry(f32::from(canvas_size.width)); + self.window_to_page_world(position, geom.column_x) + }; for block in &layout.blocks { if !block.rect().contains(wx, wy) { continue; @@ -457,6 +483,11 @@ impl PlaygroundView { None } + fn active_link_note_id(&self) -> Option<&str> { + let (id, is_note) = self.edgeless.authoring.editing_spatial_block()?; + is_note.then_some(id) + } + /// Sync desktop hover-triggered link/reference popup on pointer move (non-focus-stealing). pub(crate) fn sync_link_popup_for_hover( &mut self, @@ -466,7 +497,13 @@ impl PlaygroundView { window: &Window, cx: &mut Context, ) { - if self.mode != PlaygroundMode::Page || self.form_factor != FormFactor::Desktop || pressed { + if self.form_factor != FormFactor::Desktop || pressed { + return; + } + let mode = self.mode; + if mode == PlaygroundMode::Edgeless && self.active_link_note_id().is_none() { + self.link_hover_pending = None; + self.link_hover_timer = None; return; } if self.overlays.slash_menu().is_some() @@ -553,14 +590,39 @@ impl PlaygroundView { }; self.link_hover_state().transition = next; // Replacing the task cancels the previous one, so only the latest transition fires. + let note_id = self.active_link_note_id().map(str::to_owned); 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 _ = this.update_in(cx, |this, window, cx| { + let transition = this.link_hover_state().transition.take(); + if this.mode != mode || this.active_link_note_id() != note_id.as_deref() { + return; + } let now_ms = this.now_ms(cx); - match this.link_hover_state().transition.take() { + match transition { Some(LinkHoverTransition::Enter(target, anchor)) => { + let (target, anchor) = if note_id.is_some() { + // The camera or viewport can move while the pointer stays still. + let p = window.mouse_position(); + let key = this.link_read_key(); + let known = this + .link_hover_pending + .as_ref() + .and_then(|state| kept(&state.hover, key.as_ref())); + let Some((current, anchor, _)) = + this.link_popup_target_at(p.x.into(), p.y.into(), window, known) + else { + return; + }; + if current != target { + return; + } + (current, anchor) + } else { + (target, anchor) + }; this.overlays.open_link_popup(target, anchor, true, now_ms); } Some(LinkHoverTransition::Leave) @@ -732,8 +794,7 @@ mod tests { /// `p-two`: two links to one URL. `p-emoji`: a link after a surrogate pair. `p-wrap`: one /// link over several lines. `p-ref`: a reference to the page `target`. - fn open_links() -> (Session, u64) { - let session = open(1280, 800, PlaygroundTheme::Light); + pub(super) fn link_document() -> (DocState, u64) { let mut state = DocState::new("link-hover-reuse", 94).unwrap(); state .workspace @@ -776,6 +837,12 @@ mod tests { Any::Object(Box::new(reference)), ); } + (state, wrapped_len) + } + + pub(super) fn open_links() -> (Session, u64) { + let session = open(1280, 800, PlaygroundTheme::Light); + let (state, wrapped_len) = link_document(); session.view(|v, cx| v.set_document(state, cx)); let _ = session.settle(); (session, wrapped_len)