mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-05 11:15:01 +03:00
feat(blocksuite): add inline popovers, block toolbars, and overlay polish
Add inline link and linked-doc 500ms hover popovers, dual-field text+link editing, and Inline/Card/Embed view conversion. Extend the desktop format toolbar with inline equation, linked-doc creation, More submenu, and block-selection mounting. Add block-level controls for code blocks (searchable language picker, line numbers, 8-line collapse), block/note LaTeX 2-step editing, image double-click lightbox, bookmark style toolbar, and callout 44px layout with emoji and 9-color toolbar. Include targeted fixes: - Flatten H4-H6 in touch Slash menus and hide scrolled-out desktop Slash preview cards. - Allow Slash Copy in page_readonly mode. - Preserve nested Y.Map background and readonly guard in Edgeless note slicer, guard locked mindmap descendants on delete, and skip dangling mindmap children. - Consume click when dismissing active Calendar inline edit and restrict selected-day '+' visibility to touch form factors. - Expand Page block_selection highlight to cover visible nested subtrees (skipping collapsed children) and align Move Up / Move Down icons in the block menu.
This commit is contained in:
1 parent
57f32a5b6a
commit
c02056c82d
59 files changed
+8311
-1446
No files matched your search
@@ -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.<id>`, `.group.<name>`, `.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.<idx>`, `.journal.<idx>`, `.create`, `.create_edgeless`, `.input_mask`; `overlay.link_popup`): 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 or placing the caret on an inline link or `@reference` chip (or single-tapping in mobile edit mode; mobile read-only single-tap opens directly, and edit-mode double-tap selects words without navigating) opens the non-focus-stealing `overlay.link_popup` capsule (`Open ↗`, `Edit`, `Copy`, `Unlink` / `Card` & `Remove`).
|
||||
- **Formatting toolbar** (`overlay.format_toolbar`, buttons `.turn_into`, `.bold`, `.italic`, `.underline`, `.strike`, `.code`, `.highlight`, `.link`, `.align_left|center|right`, dropdowns `.turn_into_menu`, `.highlight_menu`, link field `.link_input`, `.link_apply`, `.link_remove`): shown above a finished, non-empty selection of paragraph and list text, single-block or across blocks, while no composition runs and no slash menu is up; a selection touching 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. A mark button is active only when the whole selection carries the mark. Alignment goes on every paragraph and list block the selection touches, empty ones included, and a block that sets none reads as its nearest aligned ancestor's. The link field is a one-line text input of its own (`LinkBar`: text, selection, composition). While it is open it is the view's text input: every `EntityInputHandler` call goes to it, `editor.composing()` stays false, and the document's text, selection and composition are untouched until `Apply`; opening, closing and every change of it are reported with `notify_text_input_changed`. Caret keys, deletion, select-all, copy and cut are the field's, `Escape` abandons a composition before it closes the field, and a keyboard paste reads the clipboard where the platform can; in a browser the key keeps its default action so the `paste` event that follows reaches the field. It has the only caret; the document keeps showing the selection.
|
||||
- **Linked-doc `@` menu & lightweight link/reference capsule** (`overlay.linked_doc_menu`, rows `overlay.linked_doc_menu.item.<idx>`, `.journal.<idx>`, `.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).
|
||||
- **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.<id>`, docked panel `overlay.keyboard_toolbar.panel.<group>.<id>`, 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`), and a read-only mobile `RecordSheet` bottom sheet (`database_readonly` / `page_readonly` enforced across all mutation entry points).
|
||||
- **Drag handle & block menu** (`overlay.drag_handle`, `overlay.drop_indicator`, `overlay.block_menu`): mounted only for the hovered or dragged block (suppressed in `page_readonly`), 24 px left of the block and never closer than 4 px to the window edge. Inside its 24 px target it draws BlockSuite's Page-mode grabber: a 4 × 12 px vertical bar while the pointer is on the block's row, narrowing to a 2 × 12 px vertical bar once hovered or dragged (the 2 × 3 six-dot 14 px pill is reserved for Edgeless `gfx` drag handles). Clicking the handle toggles `overlay.block_menu` (`Copy`, `Duplicate` with subtree + database `prop:cells` row-key remapping, `Turn into ▸` submenu reusing `SLASH_ITEMS` on explicit `block_selection` only without expanding collapsed-heading body blocks, `Move up`, `Move down`, `Delete`) and sets `block_selection` on the target block; dragging resolves multi-level `TreeDropTarget` slots (`+24 px` horizontal indent steps reusing `Tab`'s parent-child legality predicate, moving collapsed heading sections atomically, and expanding a collapsed list parent on drop). A heading keeps the place beside its text for its collapse chevron, while non-heading `Paragraph` and `Quote` blocks with children expose a local-only disclosure chevron without writing `prop:collapsed` into CRDT.
|
||||
- **Block controls**: `page.block.<id>.checkbox`, `.toggle` and `.collapse` are 24 px targets over the to-do box, the toggle chevron and the heading chevron (an expanded heading shows its chevron only while the pointer is on its row); `page.block.<id>.copy` appears on a hovered code block at fixed `28 × 28 px`, swaps `CopyIcon` to `CheckIcon` in place for 1.5 s on the scheduler clock (never shifting adjacent `Wrap`/`Preview` buttons), and shows the shared `context_toast`. A sideways scroll over an unwrapped code block scrolls its lines inside `BlockBody::code_scroll` instead of the page; the caret, the selection, the bounds given to the input method, collaborators' carets and selections (translated per highlight span's own block scroll before clamping), and pointer hit-testing follow that scroll and stay inside the code area (`ScrolledCode`), and moving the caret scrolls it into view.
|
||||
- **Sizes and radii**: Interactive targets are at least 24 × 24 px (toolbar buttons 28 × 28, edge to edge). Rows and buttons round concentrically with their container: 8 px menu with 4 px padding and 4 px rows (BlockSuite pads its menu `8px 4px 8px 8px`; 4 px all around keeps the radii concentric), 8 px toolbar with 4 px padding and 4 px buttons (`gap = 2px, pad = 4px`, intentionally compact relative to JS `8px / 0 6px` so the toolbar fits a 320 px window between its 8 px margins). The toolbar is 374 px wide (11 buttons plus two separators), with 8 px on either side of the separators around `Turn into` and the alignment buttons.
|
||||
- **Block controls & block toolbars**: `page.block.<id>.checkbox`, `.toggle` and `.collapse` are 24 px targets over the to-do box, the toggle chevron and the heading chevron (an expanded heading shows its chevron only while the pointer is on its row, and `page.block_selection` highlights merged visible nested subtrees while skipping collapsed children); `page.block.<id>.language`, `.copy`, `.wrap`, `.line_numbers`, `.fold`, and `.preview` appear on `affine:code` blocks (with `>= 44 × 44 pt` hit targets on touch hosts, searchable scrollable 25-language `overlay.code_lang_picker`, `prop:lineNumber`, and 8-line `prop:collapsed` fold with 3-band fade mask; `copy` swaps `CopyIcon` to `CheckIcon` in place for 1.5 s on the scheduler clock and shows `context_toast`). Selected `affine:image`, `affine:bookmark`, and `affine:callout` blocks mount `overlay.image_toolbar` (hidden while `overlay.image_lightbox` is open; double-clicking an image opens fullscreen `overlay.image_lightbox` with uniform aspect-preserving zoom, clipped viewport pan/wheel zoom, and modal key capture), `overlay.bookmark_toolbar` (`Inline` / active `Card` / host-validated `Embed` + Page `Wide`/`Compact` style toggle, plus inline `overlay.url_paste_menu` on plain URL paste), and `overlay.callout_toolbar` + `overlay.callout_icon_picker` (`{"type":"emoji","unicode":...}` `IconData` Map + `Remove` icon + 9 `0.27.5` semantic background swatches), docking cleanly into the bottom context-bar slot on touch viewports down to `360 pt`. Block-level `affine:latex` uses 2-step selection (first click selects block, second click opens `overlay.equation_editor`). A sideways scroll over an unwrapped code block scrolls its lines inside `BlockBody::code_scroll` instead of the page; the caret, selection, IME bounds, collaborators' carets/selections, and pointer hit-testing follow that scroll (`ScrolledCode`).
|
||||
- **Sizes and radii**: Interactive targets are at least 24 × 24 px on desktop (toolbar buttons 28 × 28, edge to edge; touch host controls `>= 44 pt` height). Rows and buttons round concentrically with their container: 8 px menu with 4 px padding and 4 px rows, 8 px toolbar with 4 px padding and 4 px buttons (`gap = 2px, pad = 4px`, compacting to 24 px `FormatAction::COMPACT` pills on viewports `< 460 px` so the toolbar fits a 320 px window between its 8 px margins; on wide desktop viewports `>= 460 px`, the 14-button toolbar is 481 px wide with three 1 px separators). All floating popovers fade opacity monotonically in place over 150 ms with zero entrance/exit coordinate drift.
|
||||
- **Verification**: `bs-harness render --state <name>` renders one overlay state of the showcase, `bs-harness audit-states` audits every state in both themes at `1280` and `320` px, and `bs-harness record-demo <dir>` writes the frames of a 60 fps walk through typing, composition, the slash menu, the toolbar and the block controls; all drive the view through input events, the input handler and `dispatch_overlay` only.
|
||||
|
||||
### Rich paragraph layout
|
||||
|
||||
@@ -88,6 +88,9 @@ impl SnapshotReader<'_> {
|
||||
props: &BTreeMap<String, JsonValue>,
|
||||
) -> String {
|
||||
if let Some(icon) = props.get("prop:icon") {
|
||||
if icon.is_null() {
|
||||
return String::new();
|
||||
}
|
||||
if let Some(unicode) = icon.get("unicode").and_then(JsonValue::as_str)
|
||||
&& !unicode.is_empty()
|
||||
{
|
||||
@@ -98,11 +101,7 @@ impl SnapshotReader<'_> {
|
||||
{
|
||||
return name.to_string();
|
||||
}
|
||||
if let Some(s) = icon.as_str()
|
||||
&& !s.is_empty()
|
||||
{
|
||||
return s.to_string();
|
||||
}
|
||||
return String::new();
|
||||
}
|
||||
if let Some(emoji) = string(entries.get("prop:emoji")).filter(|s| !s.is_empty()) {
|
||||
return emoji;
|
||||
|
||||
@@ -188,6 +188,26 @@ pub fn is_leaf_flavour(flavour: &str) -> bool {
|
||||
)
|
||||
}
|
||||
|
||||
/// Construct the canonical BlockSuite `0.27.5` `prop:icon` CRDT value (`IconData` Map
|
||||
/// `{"type": "emoji", "unicode": ...}`), or `Any::Null` when the icon is removed.
|
||||
pub fn callout_icon_value(unicode: &str) -> SessionValue {
|
||||
let trimmed = unicode.trim();
|
||||
if trimmed.is_empty() {
|
||||
SessionValue::Any(Any::Null)
|
||||
} else {
|
||||
SessionValue::Map(vec![
|
||||
(
|
||||
"type".to_string(),
|
||||
SessionValue::Any(Any::String("emoji".to_string())),
|
||||
),
|
||||
(
|
||||
"unicode".to_string(),
|
||||
SessionValue::Any(Any::String(trimmed.to_string())),
|
||||
),
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
impl BlockSpec {
|
||||
pub fn flavour(&self) -> &'static str {
|
||||
match self {
|
||||
@@ -572,19 +592,7 @@ impl BlockSpec {
|
||||
icon
|
||||
};
|
||||
entries.extend([
|
||||
(
|
||||
"prop:icon".to_string(),
|
||||
SessionValue::Map(vec![
|
||||
(
|
||||
"type".to_string(),
|
||||
SessionValue::Any(Any::String("emoji".to_string())),
|
||||
),
|
||||
(
|
||||
"unicode".to_string(),
|
||||
SessionValue::Any(Any::String(unicode)),
|
||||
),
|
||||
]),
|
||||
),
|
||||
("prop:icon".to_string(), callout_icon_value(&unicode)),
|
||||
("prop:text".to_string(), text_value("")),
|
||||
(
|
||||
"prop:backgroundColorName".to_string(),
|
||||
|
||||
@@ -6,7 +6,9 @@ use std::collections::BTreeMap;
|
||||
|
||||
use y_octo::{SessionValue, TextDeltaOp, TextInsert};
|
||||
|
||||
pub use blocks::{BlockSpec, ListType, ParagraphType, UnknownBlock, is_leaf_flavour};
|
||||
pub use blocks::{
|
||||
BlockSpec, ListType, ParagraphType, UnknownBlock, callout_icon_value, is_leaf_flavour,
|
||||
};
|
||||
pub use database::{
|
||||
DatabaseCellSpec, DatabaseColumnSpec, DatabaseSpec, DatabaseViewSpec, json_to_session_value,
|
||||
};
|
||||
|
||||
@@ -253,16 +253,19 @@ impl FlowPass<'_> {
|
||||
});
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn code_body(
|
||||
&mut self,
|
||||
block_id: &str,
|
||||
language: &str,
|
||||
wrap: bool,
|
||||
explicit_line_number: Option<bool>,
|
||||
collapsed: bool,
|
||||
text: &str,
|
||||
caption: &str,
|
||||
width: f32,
|
||||
) -> BlockBody {
|
||||
const CODE_COLLAPSED_LINES: usize = 8;
|
||||
let (pad_y, pad_x) = CODE_PADDING;
|
||||
let line_height = TYPOGRAPHY.font_xs_px + 8.0;
|
||||
let code_style = InlineStyle::new(
|
||||
@@ -286,6 +289,14 @@ impl FlowPass<'_> {
|
||||
};
|
||||
let code_width = (width - code_x - pad_x).max(1.0);
|
||||
|
||||
let all_lines: Vec<&str> = text.split('\n').collect();
|
||||
let is_collapsed_cut = collapsed && all_lines.len() > CODE_COLLAPSED_LINES;
|
||||
let visible_lines = if is_collapsed_cut {
|
||||
&all_lines[..CODE_COLLAPSED_LINES]
|
||||
} else {
|
||||
all_lines.as_slice()
|
||||
};
|
||||
|
||||
let mut prims = Vec::new();
|
||||
let mut y = pad_y;
|
||||
let mut code_pieces = Vec::new();
|
||||
@@ -294,7 +305,7 @@ impl FlowPass<'_> {
|
||||
let mut widest_line = 0.0_f32;
|
||||
let highlighted_lines = crate::highlight::highlight_block_cached(block_id, language, text);
|
||||
let theme_mode = self.input.theme.mode();
|
||||
for (index, line) in text.split('\n').enumerate() {
|
||||
for (index, line) in visible_lines.iter().enumerate() {
|
||||
let hl_spans = highlighted_lines
|
||||
.get(index)
|
||||
.map(|hl| hl.spans.as_slice())
|
||||
@@ -385,28 +396,54 @@ impl FlowPass<'_> {
|
||||
dashed: false,
|
||||
},
|
||||
);
|
||||
let label = if language.is_empty() {
|
||||
"Plain Text"
|
||||
} else {
|
||||
language
|
||||
};
|
||||
if is_collapsed_cut {
|
||||
// 3-band bottom gradient fade mask over the lower 36px of collapsed code blocks.
|
||||
let fade_h = 36.0_f32.min(height * 0.4);
|
||||
let band_h = (fade_h / 3.0).ceil();
|
||||
for (i, alpha) in [0.28_f32, 0.62, 0.92].into_iter().enumerate() {
|
||||
let by = (height - fade_h + i as f32 * band_h).max(0.0);
|
||||
let bh = (height - by).min(band_h + 1.0).max(0.0);
|
||||
prims.push(Prim::Quad {
|
||||
rect: FlowRect::new(0.0, by, width, bh),
|
||||
fill: Some(self.palette.code_background.opacity(alpha)),
|
||||
border: None,
|
||||
radius: if i == 2 { CODE_RADIUS } else { 0.0 },
|
||||
dashed: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
let label_text = crate::overlays::display_code_language(language);
|
||||
let label_style = InlineStyle::new(
|
||||
FONT_SANS,
|
||||
TYPOGRAPHY.font_xs_px,
|
||||
400.0,
|
||||
500.0,
|
||||
self.palette.text_secondary,
|
||||
);
|
||||
let label_layout = self.plain_inline(label, label_style, f32::MAX, 16.0, InlineAlign::Left);
|
||||
let max_label_w = (width - 2.0 * pad_x).clamp(48.0, 132.0);
|
||||
let text_max_w = (max_label_w - 14.0).max(24.0);
|
||||
let truncated_label = truncate_to_width(self.window, &label_text, &label_style, text_max_w);
|
||||
let label_layout = self.plain_inline(
|
||||
&truncated_label.text,
|
||||
label_style,
|
||||
text_max_w,
|
||||
16.0,
|
||||
InlineAlign::Left,
|
||||
);
|
||||
prims.push(Prim::Text {
|
||||
x: pad_x,
|
||||
y: 8.0,
|
||||
layout: label_layout,
|
||||
clip: Some(FlowRect::new(
|
||||
pad_x,
|
||||
8.0,
|
||||
(width - 2.0 * pad_x).max(0.0),
|
||||
16.0,
|
||||
)),
|
||||
clip: Some(FlowRect::new(pad_x, 8.0, text_max_w, 16.0)),
|
||||
});
|
||||
prims.push(Prim::Icon {
|
||||
rect: FlowRect::new(
|
||||
pad_x + f32::from(truncated_label.width) + 3.0,
|
||||
11.0,
|
||||
10.0,
|
||||
10.0,
|
||||
),
|
||||
icon: IconPaint::named("ToggleDownIcon"),
|
||||
color: self.palette.text_secondary,
|
||||
});
|
||||
|
||||
let mut body = BlockBody {
|
||||
@@ -616,12 +653,20 @@ impl FlowPass<'_> {
|
||||
url: &str,
|
||||
title: Option<&str>,
|
||||
description: Option<&str>,
|
||||
card_style: Option<&str>,
|
||||
caption: &str,
|
||||
width: f32,
|
||||
) -> BlockBody {
|
||||
let style_kind = card_style.unwrap_or("horizontal");
|
||||
let (card_w, card_h) = match style_kind {
|
||||
"list" => (width, 48.0),
|
||||
"vertical" => (width.min(360.0), 152.0),
|
||||
"cube" => (width.min(168.0), 148.0),
|
||||
_ => (width, BOOKMARK_HEIGHT),
|
||||
};
|
||||
// 1px border plus the content's 12px padding.
|
||||
let pad = 13.0;
|
||||
let inner = (width - 2.0 * pad).max(1.0);
|
||||
let inner = (card_w - 2.0 * pad).max(1.0);
|
||||
let host = host_name(url);
|
||||
let title = title.filter(|title| !title.is_empty()).unwrap_or(host);
|
||||
// Without a fetched description the card falls back to the address itself.
|
||||
@@ -630,7 +675,7 @@ impl FlowPass<'_> {
|
||||
.unwrap_or(url);
|
||||
|
||||
let mut prims = vec![Prim::Quad {
|
||||
rect: FlowRect::new(0.0, 0.0, width, BOOKMARK_HEIGHT),
|
||||
rect: FlowRect::new(0.0, 0.0, card_w, card_h),
|
||||
fill: Some(self.palette.background),
|
||||
border: Some(self.palette.card_border),
|
||||
radius: 8.0,
|
||||
@@ -645,7 +690,7 @@ impl FlowPass<'_> {
|
||||
self.palette.text_primary,
|
||||
);
|
||||
let title_x = pad + 16.0 + 8.0;
|
||||
let title_width = (width - title_x - pad).max(1.0);
|
||||
let title_width = (card_w - title_x - pad).max(1.0);
|
||||
let title_text = truncate_to_width(self.window, title, &title_style, title_width)
|
||||
.text
|
||||
.to_string();
|
||||
@@ -667,48 +712,50 @@ impl FlowPass<'_> {
|
||||
clip: None,
|
||||
});
|
||||
|
||||
// Description: at most two 20px lines.
|
||||
let description_style = InlineStyle::new(
|
||||
FONT_SANS,
|
||||
TYPOGRAPHY.font_xs_px,
|
||||
400.0,
|
||||
self.palette.text_primary,
|
||||
);
|
||||
let description_y = pad + 22.0 + 4.0;
|
||||
prims.push(Prim::Text {
|
||||
x: pad,
|
||||
y: description_y,
|
||||
layout: self.plain_inline(
|
||||
description,
|
||||
description_style,
|
||||
inner,
|
||||
20.0,
|
||||
InlineAlign::Left,
|
||||
),
|
||||
clip: Some(FlowRect::new(pad, description_y, inner, 40.0)),
|
||||
});
|
||||
if style_kind != "list" {
|
||||
// Description: at most two 20px lines.
|
||||
let description_style = InlineStyle::new(
|
||||
FONT_SANS,
|
||||
TYPOGRAPHY.font_xs_px,
|
||||
400.0,
|
||||
self.palette.text_primary,
|
||||
);
|
||||
let description_y = pad + 22.0 + 4.0;
|
||||
prims.push(Prim::Text {
|
||||
x: pad,
|
||||
y: description_y,
|
||||
layout: self.plain_inline(
|
||||
description,
|
||||
description_style,
|
||||
inner,
|
||||
20.0,
|
||||
InlineAlign::Left,
|
||||
),
|
||||
clip: Some(FlowRect::new(pad, description_y, inner, 40.0)),
|
||||
});
|
||||
|
||||
// Address row pinned to the bottom padding edge.
|
||||
let url_style = InlineStyle::new(
|
||||
FONT_SANS,
|
||||
TYPOGRAPHY.font_xs_px,
|
||||
400.0,
|
||||
self.palette.text_secondary,
|
||||
);
|
||||
let url_text = truncate_to_width(self.window, host, &url_style, inner)
|
||||
.text
|
||||
.to_string();
|
||||
prims.push(Prim::Text {
|
||||
x: pad,
|
||||
y: BOOKMARK_HEIGHT - pad - 20.0,
|
||||
layout: self.plain_inline(&url_text, url_style, inner, 20.0, InlineAlign::Left),
|
||||
clip: None,
|
||||
});
|
||||
// Address row pinned to the bottom padding edge.
|
||||
let url_style = InlineStyle::new(
|
||||
FONT_SANS,
|
||||
TYPOGRAPHY.font_xs_px,
|
||||
400.0,
|
||||
self.palette.text_secondary,
|
||||
);
|
||||
let url_text = truncate_to_width(self.window, host, &url_style, inner)
|
||||
.text
|
||||
.to_string();
|
||||
prims.push(Prim::Text {
|
||||
x: pad,
|
||||
y: card_h - pad - 20.0,
|
||||
layout: self.plain_inline(&url_text, url_style, inner, 20.0, InlineAlign::Left),
|
||||
clip: None,
|
||||
});
|
||||
}
|
||||
|
||||
let mut body = BlockBody {
|
||||
kind: FlowKind::Bookmark,
|
||||
width,
|
||||
height: BOOKMARK_HEIGHT,
|
||||
height: card_h,
|
||||
margin_top: CARD_BLOCK_MARGIN,
|
||||
margin_bottom: CARD_BLOCK_MARGIN,
|
||||
plain: title.to_string(),
|
||||
|
||||
@@ -479,6 +479,35 @@ impl<'a> FlowPass<'a> {
|
||||
.image_resize_preview
|
||||
.filter(|(id, _, _)| *id == node.id)
|
||||
.map(|(_, w, h)| (w.to_bits(), h.to_bits()));
|
||||
let extra_prop_sig: u8 = match &node.content {
|
||||
BlockContent::Bookmark { .. } => {
|
||||
match node.props.get("prop:style").and_then(|v| v.as_str()) {
|
||||
Some("list") => 1,
|
||||
Some("vertical") => 2,
|
||||
Some("cube") => 3,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
BlockContent::Code { .. } => {
|
||||
let ln = match node.props.get("prop:lineNumber").and_then(|v| v.as_bool()) {
|
||||
None => 0,
|
||||
Some(false) => 1,
|
||||
Some(true) => 2,
|
||||
};
|
||||
let col = u8::from(
|
||||
node.props
|
||||
.get("prop:collapsed")
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false),
|
||||
);
|
||||
ln | (col << 2)
|
||||
}
|
||||
BlockContent::Callout { .. } => match node.children.first().map(|c| &c.content) {
|
||||
Some(BlockContent::Paragraph { kind, .. }) => (*kind as u8).wrapping_add(1),
|
||||
_ => 0,
|
||||
},
|
||||
_ => 0,
|
||||
};
|
||||
let fingerprint = (
|
||||
&node.content,
|
||||
node.children.is_empty(),
|
||||
@@ -497,6 +526,7 @@ impl<'a> FlowPass<'a> {
|
||||
embed_card_state,
|
||||
local_collapsed,
|
||||
image_preview_sig,
|
||||
extra_prop_sig,
|
||||
),
|
||||
);
|
||||
let body = self.body(&node.id, &fingerprint, |pass| {
|
||||
@@ -541,8 +571,8 @@ impl<'a> FlowPass<'a> {
|
||||
if shows_children && !node.children.is_empty() {
|
||||
if is_callout {
|
||||
// Horizontal callout layout (`callout-block-styles.ts`):
|
||||
// emoji sits at `(x + 10, block_top + 5)` and child content starts on the
|
||||
// SAME row at `(x + 44, block_top + 5)` with width `width - 54`.
|
||||
// emoji sits at `(x + 12, block_top + 10)` and child content starts on the
|
||||
// SAME row at `(x + 46, block_top + 10)` with width `width - 58`.
|
||||
let pad_top = super::rich_blocks::CALLOUT_PAD_Y;
|
||||
let pad_x = super::rich_blocks::CALLOUT_PAD_X;
|
||||
let content_indent = pad_x
|
||||
|
||||
@@ -8,11 +8,11 @@ use super::{
|
||||
};
|
||||
|
||||
pub(super) const CALLOUT_MARGIN_Y: f32 = 8.0;
|
||||
pub(super) const CALLOUT_PAD_X: f32 = 10.0;
|
||||
pub(super) const CALLOUT_PAD_Y: f32 = 5.0;
|
||||
pub(super) const CALLOUT_PAD_X: f32 = 12.0;
|
||||
pub(super) const CALLOUT_PAD_Y: f32 = 10.0;
|
||||
pub(super) const CALLOUT_ICON_SLOT: f32 = 24.0;
|
||||
pub(super) const CALLOUT_CONTENT_GAP: f32 = 10.0;
|
||||
pub(super) const CALLOUT_MIN_HEIGHT: f32 = 34.0;
|
||||
pub(super) const CALLOUT_MIN_HEIGHT: f32 = 44.0;
|
||||
|
||||
fn format_byte_size(bytes: i64) -> String {
|
||||
let b = bytes.max(0) as f64;
|
||||
@@ -61,82 +61,95 @@ impl FlowPass<'_> {
|
||||
text: &str,
|
||||
background_color: Option<&str>,
|
||||
has_children: bool,
|
||||
first_child_heading_level: Option<u8>,
|
||||
width: f32,
|
||||
) -> BlockBody {
|
||||
let fill = semantic_callout_background(background_color, self.input.theme);
|
||||
|
||||
let icon_text = if icon.trim().is_empty() {
|
||||
"\u{1F4A1}"
|
||||
} else {
|
||||
icon.trim()
|
||||
};
|
||||
let icon_x = mirror_x_in_width(CALLOUT_PAD_X, CALLOUT_ICON_SLOT, width, self.direction);
|
||||
let icon_style = InlineStyle::new(
|
||||
FONT_SANS,
|
||||
(TYPOGRAPHY.font_base_px * 1.2).round(),
|
||||
400.0,
|
||||
self.palette.text_primary,
|
||||
);
|
||||
let icon_layout = self.plain_inline(
|
||||
icon_text,
|
||||
icon_style,
|
||||
CALLOUT_ICON_SLOT,
|
||||
CALLOUT_ICON_SLOT,
|
||||
InlineAlign::Center,
|
||||
);
|
||||
let mut glyph_count = 0usize;
|
||||
let mut has_notdef = false;
|
||||
for piece in &icon_layout.pieces {
|
||||
for run in &piece.shaped.runs {
|
||||
for glyph in &run.glyphs {
|
||||
glyph_count += 1;
|
||||
if glyph.id.0 == 0 {
|
||||
has_notdef = true;
|
||||
let icon_trimmed = icon.trim();
|
||||
let has_icon = !icon_trimmed.is_empty();
|
||||
let icon_prim = if has_icon {
|
||||
let icon_x = mirror_x_in_width(CALLOUT_PAD_X, CALLOUT_ICON_SLOT, width, self.direction);
|
||||
// Shift emoji down to match first-line heading baseline when first child is H1–H3.
|
||||
let heading_shift = match first_child_heading_level {
|
||||
Some(1) => 8.0,
|
||||
Some(2) => 5.0,
|
||||
Some(3) => 3.0,
|
||||
_ => 0.0,
|
||||
};
|
||||
let icon_y = CALLOUT_PAD_Y + heading_shift;
|
||||
let icon_style = InlineStyle::new(
|
||||
FONT_SANS,
|
||||
(TYPOGRAPHY.font_base_px * 1.2).round(),
|
||||
400.0,
|
||||
self.palette.text_primary,
|
||||
);
|
||||
let icon_layout = self.plain_inline(
|
||||
icon_trimmed,
|
||||
icon_style,
|
||||
CALLOUT_ICON_SLOT,
|
||||
CALLOUT_ICON_SLOT,
|
||||
InlineAlign::Center,
|
||||
);
|
||||
let mut glyph_count = 0usize;
|
||||
let mut has_notdef = false;
|
||||
for piece in &icon_layout.pieces {
|
||||
for run in &piece.shaped.runs {
|
||||
for glyph in &run.glyphs {
|
||||
glyph_count += 1;
|
||||
if glyph.id.0 == 0 {
|
||||
has_notdef = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let icon_prim = if glyph_count > 0 && !has_notdef {
|
||||
Prim::Text {
|
||||
x: icon_x,
|
||||
y: CALLOUT_PAD_Y,
|
||||
layout: icon_layout,
|
||||
clip: None,
|
||||
}
|
||||
Some(if glyph_count > 0 && !has_notdef {
|
||||
Prim::Text {
|
||||
x: icon_x,
|
||||
y: icon_y,
|
||||
layout: icon_layout,
|
||||
clip: None,
|
||||
}
|
||||
} else {
|
||||
let fallback_name = match icon_trimmed {
|
||||
"\u{1F4A1}" | "info" | "tip" | "bulb" | "\u{2139}" | "\u{2139}\u{FE0F}" => {
|
||||
"InformationIcon"
|
||||
}
|
||||
"\u{26A0}" | "\u{26A0}\u{FE0F}" | "\u{1F525}" | "\u{2757}" | "warn"
|
||||
| "warning" => "WarningIcon",
|
||||
_ => "QuoteIcon",
|
||||
};
|
||||
Prim::Icon {
|
||||
rect: FlowRect::new(icon_x + 2.0, icon_y + 2.0, 20.0, 20.0),
|
||||
icon: IconPaint::named(fallback_name),
|
||||
color: self.palette.icon,
|
||||
}
|
||||
})
|
||||
} else {
|
||||
let fallback_name = match icon_text {
|
||||
"\u{1F4A1}" | "info" | "tip" | "bulb" | "\u{2139}" | "\u{2139}\u{FE0F}" => {
|
||||
"InformationIcon"
|
||||
}
|
||||
"\u{26A0}" | "\u{26A0}\u{FE0F}" | "\u{1F525}" | "\u{2757}" | "warn" | "warning" => {
|
||||
"WarningIcon"
|
||||
}
|
||||
_ => "QuoteIcon",
|
||||
};
|
||||
Prim::Icon {
|
||||
rect: FlowRect::new(icon_x + 2.0, CALLOUT_PAD_Y + 2.0, 20.0, 20.0),
|
||||
icon: IconPaint::named(fallback_name),
|
||||
color: self.palette.icon,
|
||||
}
|
||||
None
|
||||
};
|
||||
|
||||
let title_trimmed = text.trim();
|
||||
let content_offset_x = CALLOUT_PAD_X + CALLOUT_ICON_SLOT + CALLOUT_CONTENT_GAP;
|
||||
let content_offset_x = if has_icon {
|
||||
CALLOUT_PAD_X + CALLOUT_ICON_SLOT + CALLOUT_CONTENT_GAP
|
||||
} else {
|
||||
CALLOUT_PAD_X
|
||||
};
|
||||
let text_w = (width - content_offset_x - CALLOUT_PAD_X).max(1.0);
|
||||
let title_x = match self.direction {
|
||||
ui::Direction::Ltr => content_offset_x,
|
||||
ui::Direction::Rtl => CALLOUT_PAD_X,
|
||||
};
|
||||
let mut prims = vec![
|
||||
Prim::Quad {
|
||||
rect: FlowRect::new(0.0, 0.0, width, CALLOUT_MIN_HEIGHT),
|
||||
fill,
|
||||
border: None,
|
||||
radius: 8.0,
|
||||
dashed: false,
|
||||
},
|
||||
icon_prim,
|
||||
];
|
||||
let mut prims = vec![Prim::Quad {
|
||||
rect: FlowRect::new(0.0, 0.0, width, CALLOUT_MIN_HEIGHT),
|
||||
fill,
|
||||
border: None,
|
||||
radius: 8.0,
|
||||
dashed: false,
|
||||
}];
|
||||
if let Some(ip) = icon_prim {
|
||||
prims.push(ip);
|
||||
}
|
||||
let content_h = if !title_trimmed.is_empty() {
|
||||
let title_style = InlineStyle::new(
|
||||
FONT_SANS,
|
||||
@@ -177,10 +190,10 @@ impl FlowPass<'_> {
|
||||
height,
|
||||
margin_top: CALLOUT_MARGIN_Y,
|
||||
margin_bottom: if has_children { 0.0 } else { CALLOUT_MARGIN_Y },
|
||||
plain: if title_trimmed.is_empty() {
|
||||
icon_text.to_string()
|
||||
} else {
|
||||
format!("{icon_text} {title_trimmed}")
|
||||
plain: match (has_icon, title_trimmed.is_empty()) {
|
||||
(true, true) => icon_trimmed.to_string(),
|
||||
(true, false) => format!("{icon_trimmed} {title_trimmed}"),
|
||||
(false, _) => title_trimmed.to_string(),
|
||||
},
|
||||
prims,
|
||||
text: None,
|
||||
@@ -562,11 +575,17 @@ impl FlowPass<'_> {
|
||||
}
|
||||
let explicit_line_number =
|
||||
node.props.get("prop:lineNumber").and_then(|v| v.as_bool());
|
||||
let collapsed = node
|
||||
.props
|
||||
.get("prop:collapsed")
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false);
|
||||
self.code_body(
|
||||
&node.id,
|
||||
language,
|
||||
*wrap,
|
||||
explicit_line_number,
|
||||
collapsed,
|
||||
text,
|
||||
caption,
|
||||
width,
|
||||
@@ -592,13 +611,17 @@ impl FlowPass<'_> {
|
||||
title,
|
||||
description,
|
||||
caption,
|
||||
} => self.bookmark_body(
|
||||
url,
|
||||
title.as_deref(),
|
||||
description.as_deref(),
|
||||
caption,
|
||||
width,
|
||||
),
|
||||
} => {
|
||||
let style = node.props.get("prop:style").and_then(|v| v.as_str());
|
||||
self.bookmark_body(
|
||||
url,
|
||||
title.as_deref(),
|
||||
description.as_deref(),
|
||||
style,
|
||||
caption,
|
||||
width,
|
||||
)
|
||||
}
|
||||
BlockContent::Latex { latex } => {
|
||||
let effective = match self.input.equation_draft {
|
||||
Some(EquationDraft::Block {
|
||||
@@ -613,13 +636,25 @@ impl FlowPass<'_> {
|
||||
icon,
|
||||
text,
|
||||
background_color,
|
||||
} => self.callout_body(
|
||||
icon,
|
||||
&text.plain,
|
||||
background_color.as_deref(),
|
||||
!node.children.is_empty(),
|
||||
width,
|
||||
),
|
||||
} => {
|
||||
let first_heading = node.children.first().and_then(|c| match &c.content {
|
||||
BlockContent::Paragraph { kind, .. } => match kind {
|
||||
blocksuite_playground_doc::schema::ParagraphType::H1 => Some(1),
|
||||
blocksuite_playground_doc::schema::ParagraphType::H2 => Some(2),
|
||||
blocksuite_playground_doc::schema::ParagraphType::H3 => Some(3),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
});
|
||||
self.callout_body(
|
||||
icon,
|
||||
&text.plain,
|
||||
background_color.as_deref(),
|
||||
!node.children.is_empty(),
|
||||
first_heading,
|
||||
width,
|
||||
)
|
||||
}
|
||||
BlockContent::Table(table) => self.table_body(
|
||||
table,
|
||||
width,
|
||||
|
||||
@@ -637,7 +637,8 @@ pub(super) fn render_calendar_view(
|
||||
));
|
||||
let show_plus = day_plus_allowed
|
||||
&& (is_today
|
||||
|| ctx.ui_state.calendar_selected_day == Some(day.day_index)
|
||||
|| (ctx.form_factor.is_touch_form_factor()
|
||||
&& ctx.ui_state.calendar_selected_day == Some(day.day_index))
|
||||
|| ctx.ui_state.calendar_hovered_day == Some(day.day_index));
|
||||
super::calendar_edit::render_calendar_day_controls(
|
||||
ctx,
|
||||
|
||||
@@ -13,7 +13,7 @@ use crate::{
|
||||
use super::{
|
||||
CONTEXT_MENU_PADDING, CONTEXT_MENU_RADIUS, CONTEXT_MENU_ROW_HEIGHT, OverlayEvent, OverlayHost,
|
||||
POPOVER_BORDER, POPOVER_EDGE_MARGIN, Presence, SLASH_ITEMS, SlashCommand, SlashItem, emit,
|
||||
icon, place, place_context_menu,
|
||||
icon, icon_rotated, place, place_context_menu,
|
||||
};
|
||||
|
||||
/// Width of the drag-handle block action menu in logical pixels.
|
||||
@@ -178,7 +178,8 @@ pub(super) fn render_block_menu<V: OverlayHost>(
|
||||
id: &'static str,
|
||||
snap_id: &'static str,
|
||||
label: &'static str,
|
||||
icon_name: Option<&'static str>,
|
||||
icon_name: &'static str,
|
||||
icon_turn: f32,
|
||||
enabled: bool,
|
||||
danger: bool,
|
||||
action: BlockMenuAction,
|
||||
@@ -226,12 +227,8 @@ pub(super) fn render_block_menu<V: OverlayHost>(
|
||||
}
|
||||
}));
|
||||
}
|
||||
if let Some(name) = icon_name {
|
||||
row = row.child(icon(name, 16.0, icon_fg));
|
||||
} else {
|
||||
row = row.child(div().flex_none().w(px(16.0)).h(px(16.0)));
|
||||
}
|
||||
row.child(label)
|
||||
row.child(icon_rotated(icon_name, 16.0, icon_turn, icon_fg))
|
||||
.child(label)
|
||||
};
|
||||
|
||||
let mut turn_into_row = div()
|
||||
@@ -345,7 +342,8 @@ pub(super) fn render_block_menu<V: OverlayHost>(
|
||||
"blk-move-up",
|
||||
"overlay.block_menu.move_up",
|
||||
"Move Up",
|
||||
None,
|
||||
"ToggleDownIcon",
|
||||
std::f32::consts::PI,
|
||||
menu.can_move_up,
|
||||
false,
|
||||
BlockMenuAction::MoveUp,
|
||||
@@ -356,7 +354,8 @@ pub(super) fn render_block_menu<V: OverlayHost>(
|
||||
"blk-move-down",
|
||||
"overlay.block_menu.move_down",
|
||||
"Move Down",
|
||||
None,
|
||||
"ToggleDownIcon",
|
||||
0.0,
|
||||
menu.can_move_down,
|
||||
false,
|
||||
BlockMenuAction::MoveDown,
|
||||
@@ -367,7 +366,8 @@ pub(super) fn render_block_menu<V: OverlayHost>(
|
||||
"blk-duplicate",
|
||||
"overlay.block_menu.duplicate",
|
||||
"Duplicate",
|
||||
Some("DuplicateIcon"),
|
||||
"DuplicateIcon",
|
||||
0.0,
|
||||
true,
|
||||
false,
|
||||
BlockMenuAction::Duplicate,
|
||||
@@ -378,7 +378,8 @@ pub(super) fn render_block_menu<V: OverlayHost>(
|
||||
"blk-copy",
|
||||
"overlay.block_menu.copy",
|
||||
"Copy",
|
||||
Some("CopyIcon"),
|
||||
"CopyIcon",
|
||||
0.0,
|
||||
true,
|
||||
false,
|
||||
BlockMenuAction::Copy,
|
||||
@@ -390,7 +391,8 @@ pub(super) fn render_block_menu<V: OverlayHost>(
|
||||
"blk-delete",
|
||||
"overlay.block_menu.delete",
|
||||
"Delete",
|
||||
Some("DeleteIcon"),
|
||||
"DeleteIcon",
|
||||
0.0,
|
||||
true,
|
||||
true,
|
||||
BlockMenuAction::Delete,
|
||||
|
||||
@@ -16,7 +16,7 @@ const BOOKMARK_CANCEL_WIDTH: f32 = 56.0;
|
||||
const BOOKMARK_PAD: f32 = 6.0;
|
||||
const BOOKMARK_GAP: f32 = 4.0;
|
||||
|
||||
/// Mode of the single-line block prompt (`Bookmark` URL, `Embed` URL, or `Caption` editing).
|
||||
/// Mode of the single-line block prompt (`Bookmark` URL creation/edit, `Embed` URL, `Caption`, or `@reference` alias).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum BookmarkPromptKind {
|
||||
/// Insert an `affine:bookmark` card after `block_id` (optionally replacing an empty
|
||||
@@ -27,8 +27,16 @@ pub enum BookmarkPromptKind {
|
||||
kind: SlashEmbedKind,
|
||||
remove_empty_block: bool,
|
||||
},
|
||||
/// Update `prop:url` on an existing `affine:bookmark` block.
|
||||
BookmarkEdit { initial_url: String },
|
||||
/// Edit `prop:caption` on `block_id` (`initial` skips no-op writes).
|
||||
Caption { initial: String },
|
||||
/// Edit custom display alias (`reference.title`) on an inline `@reference` chip.
|
||||
ReferenceAlias {
|
||||
utf16_offset: usize,
|
||||
page_id: String,
|
||||
initial: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// Floating single-line prompt shared by `Bookmark` URL insertion and `Caption` editing.
|
||||
@@ -104,6 +112,44 @@ impl Overlays {
|
||||
);
|
||||
}
|
||||
|
||||
/// Open and focus the URL editor for an existing `affine:bookmark` block.
|
||||
pub fn open_bookmark_edit_prompt(
|
||||
&mut self,
|
||||
block_id: String,
|
||||
initial_url: String,
|
||||
now_ms: f64,
|
||||
) {
|
||||
let seed = initial_url.clone();
|
||||
self.open_single_line_prompt(
|
||||
block_id,
|
||||
BookmarkPromptKind::BookmarkEdit { initial_url },
|
||||
seed,
|
||||
now_ms,
|
||||
);
|
||||
}
|
||||
|
||||
/// Open and focus the custom alias editor for an inline `@reference` chip.
|
||||
pub fn open_reference_alias_prompt(
|
||||
&mut self,
|
||||
block_id: String,
|
||||
utf16_offset: usize,
|
||||
page_id: String,
|
||||
initial: String,
|
||||
now_ms: f64,
|
||||
) {
|
||||
let seed = initial.clone();
|
||||
self.open_single_line_prompt(
|
||||
block_id,
|
||||
BookmarkPromptKind::ReferenceAlias {
|
||||
utf16_offset,
|
||||
page_id,
|
||||
initial,
|
||||
},
|
||||
seed,
|
||||
now_ms,
|
||||
);
|
||||
}
|
||||
|
||||
fn open_single_line_prompt(
|
||||
&mut self,
|
||||
block_id: String,
|
||||
@@ -183,6 +229,22 @@ impl Overlays {
|
||||
effects.embed_insert = Some((block_id, kind, url, remove_empty_block));
|
||||
}
|
||||
}
|
||||
BookmarkPromptKind::BookmarkEdit { initial_url } => {
|
||||
let url = if raw.trim().starts_with('/') {
|
||||
String::new()
|
||||
} else {
|
||||
normalize_url(&raw)
|
||||
};
|
||||
if (url.starts_with("http://") || url.starts_with("https://"))
|
||||
&& url != *initial_url
|
||||
{
|
||||
effects.edits.push(DocEdit::SetProp {
|
||||
block_id,
|
||||
key: "prop:url",
|
||||
value: Any::String(url),
|
||||
});
|
||||
}
|
||||
}
|
||||
BookmarkPromptKind::Caption { initial } => {
|
||||
let trimmed = raw.trim().to_string();
|
||||
if trimmed != *initial {
|
||||
@@ -192,6 +254,21 @@ impl Overlays {
|
||||
});
|
||||
}
|
||||
}
|
||||
BookmarkPromptKind::ReferenceAlias {
|
||||
utf16_offset,
|
||||
page_id,
|
||||
initial,
|
||||
} => {
|
||||
let trimmed = raw.trim().to_string();
|
||||
if trimmed != *initial {
|
||||
effects.edits.push(DocEdit::SetReferenceAlias {
|
||||
block_id,
|
||||
utf16_offset: *utf16_offset,
|
||||
page_id: page_id.clone(),
|
||||
alias: (!trimmed.is_empty()).then_some(trimmed),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(prompt) = self.bookmark_prompt_mut() {
|
||||
prompt.presence.close(now_ms);
|
||||
@@ -321,7 +398,7 @@ impl Overlays {
|
||||
));
|
||||
}
|
||||
let (placeholder, snap_root, snap_input, snap_apply, snap_cancel) = match &prompt.kind {
|
||||
BookmarkPromptKind::BookmarkUrl { .. } => (
|
||||
BookmarkPromptKind::BookmarkUrl { .. } | BookmarkPromptKind::BookmarkEdit { .. } => (
|
||||
"Paste or type a bookmark link",
|
||||
"overlay.bookmark_prompt",
|
||||
"overlay.bookmark_prompt.input",
|
||||
@@ -342,6 +419,13 @@ impl Overlays {
|
||||
"overlay.caption_prompt.apply",
|
||||
"overlay.caption_prompt.cancel",
|
||||
),
|
||||
BookmarkPromptKind::ReferenceAlias { .. } => (
|
||||
"Custom alias (empty resets)",
|
||||
"overlay.reference_alias_prompt",
|
||||
"overlay.reference_alias_prompt.input",
|
||||
"overlay.reference_alias_prompt.apply",
|
||||
"overlay.reference_alias_prompt.cancel",
|
||||
),
|
||||
};
|
||||
inner = inner.child(if text.is_empty() {
|
||||
div()
|
||||
@@ -454,9 +538,11 @@ impl Overlays {
|
||||
.snapshot_text("Cancel")
|
||||
.child("Cancel");
|
||||
|
||||
let brand_hover = palette.brand.opacity(0.88);
|
||||
if interactive {
|
||||
apply = apply
|
||||
.cursor_pointer()
|
||||
.hover(move |s| s.bg(brand_hover))
|
||||
.on_click(emit(cx, |_: &ClickEvent| OverlayEvent::BookmarkApply));
|
||||
cancel = cancel
|
||||
.cursor_pointer()
|
||||
|
||||
@@ -0,0 +1,379 @@
|
||||
//! Floating / bottom-docked selection toolbar for `affine:bookmark` blocks
|
||||
//! (`overlay.bookmark_toolbar`): `Open`, `Edit`, view switcher (`Inline` / active `Card` /
|
||||
//! conditional `Embed`), Page-mode card style (`Horizontal` / `List`), `Caption`, `Copy`,
|
||||
//! `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, SharedString, div,
|
||||
prelude::*, px,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
block_flow::FlowRect,
|
||||
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,
|
||||
};
|
||||
|
||||
/// Card visual style for `affine:bookmark` (`prop:style`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum BookmarkCardStyle {
|
||||
Horizontal,
|
||||
List,
|
||||
Vertical,
|
||||
Cube,
|
||||
}
|
||||
|
||||
impl BookmarkCardStyle {
|
||||
pub const ALL: [Self; 4] = [Self::Horizontal, Self::List, Self::Vertical, Self::Cube];
|
||||
pub const PAGE_STYLES: [Self; 2] = [Self::Horizontal, Self::List];
|
||||
|
||||
pub const fn wire_value(self) -> &'static str {
|
||||
match self {
|
||||
Self::Horizontal => "horizontal",
|
||||
Self::List => "list",
|
||||
Self::Vertical => "vertical",
|
||||
Self::Cube => "cube",
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Horizontal => "Wide",
|
||||
Self::List => "Compact",
|
||||
Self::Vertical => "Vertical",
|
||||
Self::Cube => "Cube",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_wire(raw: Option<&str>) -> Self {
|
||||
match raw.unwrap_or("horizontal") {
|
||||
"list" => Self::List,
|
||||
"vertical" => Self::Vertical,
|
||||
"cube" => Self::Cube,
|
||||
_ => Self::Horizontal,
|
||||
}
|
||||
}
|
||||
|
||||
/// Toggle between Page-mode bookmark styles (`horizontal` <-> `list`, matching JS
|
||||
/// `bookmark/configs/toolbar.ts:248-255` which filters out Edgeless-only `vertical`/`cube`).
|
||||
pub const fn next_in_page(self) -> Self {
|
||||
match self {
|
||||
Self::Horizontal => Self::List,
|
||||
Self::List | Self::Vertical | Self::Cube => Self::Horizontal,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Actions offered by `overlay.bookmark_toolbar`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum BookmarkToolbarAction {
|
||||
Open,
|
||||
Copy,
|
||||
Edit,
|
||||
ConvertToInline,
|
||||
ConvertToEmbed,
|
||||
SetStyle(BookmarkCardStyle),
|
||||
Caption,
|
||||
Duplicate,
|
||||
Delete,
|
||||
}
|
||||
|
||||
impl Overlays {
|
||||
pub(super) fn render_bookmark_toolbar<V: OverlayHost>(
|
||||
&mut self,
|
||||
scene: &OverlayScene<'_>,
|
||||
palette: &Palette,
|
||||
cx: &mut Context<V>,
|
||||
) -> Option<AnyElement> {
|
||||
self.bookmark_toolbar_rect = None;
|
||||
if scene.page_readonly {
|
||||
return None;
|
||||
}
|
||||
let block_id = scene.selected_bookmark_block?;
|
||||
if self
|
||||
.bookmark_prompt()
|
||||
.is_some_and(|p| p.block_id == block_id)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let flow_block = scene.layout.block(block_id)?;
|
||||
let block_world = flow_block.rect();
|
||||
if !scene.anchor_visible(&block_world) {
|
||||
return None;
|
||||
}
|
||||
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 can_embed = embed_view_kind_for_url(url).is_some();
|
||||
let current_style =
|
||||
BookmarkCardStyle::from_wire(node.props.get("prop:style").and_then(|v| v.as_str()));
|
||||
let touch = scene.form_factor != crate::block_flow::FormFactor::Desktop;
|
||||
let btn_h = if touch { 44.0 } else { TOOLBAR_BUTTON };
|
||||
let vp = scene.popover_viewport();
|
||||
let pad = TOOLBAR_PADDING;
|
||||
let max_w = (vp.w - 2.0 * POPOVER_EDGE_MARGIN).max(200.0);
|
||||
let compact_touch = touch && max_w < 410.0;
|
||||
let gap = if compact_touch { 1.0 } else { TOOLBAR_GAP };
|
||||
let icon_w = if compact_touch {
|
||||
34.0
|
||||
} else if touch {
|
||||
42.0
|
||||
} else {
|
||||
TOOLBAR_BUTTON
|
||||
};
|
||||
let desktop_raw = if can_embed { 462.0_f32 } else { 414.0_f32 };
|
||||
let width = if touch { max_w } else { desktop_raw.min(max_w) }.round();
|
||||
let height = (btn_h + 2.0 * (pad + POPOVER_BORDER)).round();
|
||||
|
||||
let rect = if touch {
|
||||
FlowRect::new(
|
||||
(vp.x + (vp.w - width) * 0.5).round(),
|
||||
(vp.bottom() - height - POPOVER_EDGE_MARGIN).round(),
|
||||
width,
|
||||
height,
|
||||
)
|
||||
} else {
|
||||
place_popover(
|
||||
scene.world_to_screen(&block_world),
|
||||
(width, height),
|
||||
vp,
|
||||
Placement::Above,
|
||||
POPOVER_GAP,
|
||||
POPOVER_EDGE_MARGIN,
|
||||
)
|
||||
.rect
|
||||
};
|
||||
self.bookmark_toolbar_rect = Some(rect);
|
||||
|
||||
let hover_bg = palette.hover;
|
||||
let danger = palette
|
||||
.theme
|
||||
.css_var("--affine-error-color")
|
||||
.unwrap_or(palette.icon);
|
||||
let make_text_btn = |suffix: &'static str,
|
||||
label: &'static str,
|
||||
w: f32,
|
||||
touch_compact_w: f32,
|
||||
accent: bool,
|
||||
active: bool,
|
||||
action: Option<BookmarkToolbarAction>,
|
||||
cx: &mut Context<V>| {
|
||||
let eff_w = if compact_touch {
|
||||
touch_compact_w
|
||||
} else if touch {
|
||||
w.max(40.0)
|
||||
} else {
|
||||
w
|
||||
};
|
||||
let mut el = div()
|
||||
.id(SharedString::from(format!("bm-tb-{suffix}")))
|
||||
.flex_none()
|
||||
.w(px(eff_w))
|
||||
.h(px(btn_h))
|
||||
.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 make_icon_btn = |suffix: &'static str,
|
||||
icon_name: &'static str,
|
||||
active: bool,
|
||||
is_danger: bool,
|
||||
action: BookmarkToolbarAction,
|
||||
cx: &mut Context<V>| {
|
||||
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(icon_w))
|
||||
.h(px(btn_h))
|
||||
.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()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap(px(gap))
|
||||
.child(make_text_btn(
|
||||
"open",
|
||||
if compact_touch {
|
||||
"Open"
|
||||
} else {
|
||||
"Open \u{2197}"
|
||||
},
|
||||
50.0,
|
||||
38.0,
|
||||
true,
|
||||
false,
|
||||
Some(BookmarkToolbarAction::Open),
|
||||
cx,
|
||||
))
|
||||
.child(make_text_btn(
|
||||
"edit",
|
||||
"Edit",
|
||||
36.0,
|
||||
32.0,
|
||||
false,
|
||||
false,
|
||||
Some(BookmarkToolbarAction::Edit),
|
||||
cx,
|
||||
))
|
||||
.child(make_text_btn(
|
||||
"inline",
|
||||
"Inline",
|
||||
40.0,
|
||||
36.0,
|
||||
false,
|
||||
false,
|
||||
Some(BookmarkToolbarAction::ConvertToInline),
|
||||
cx,
|
||||
))
|
||||
.child(make_text_btn(
|
||||
"card", "Card", 38.0, 34.0, false, true, None, cx,
|
||||
));
|
||||
if can_embed {
|
||||
row = row.child(make_text_btn(
|
||||
"embed",
|
||||
"Embed",
|
||||
46.0,
|
||||
40.0,
|
||||
false,
|
||||
false,
|
||||
Some(BookmarkToolbarAction::ConvertToEmbed),
|
||||
cx,
|
||||
));
|
||||
}
|
||||
row = row
|
||||
.child(make_text_btn(
|
||||
"style",
|
||||
if compact_touch {
|
||||
match current_style {
|
||||
BookmarkCardStyle::List => "List",
|
||||
_ => "Wide",
|
||||
}
|
||||
} else {
|
||||
current_style.label()
|
||||
},
|
||||
56.0,
|
||||
36.0,
|
||||
false,
|
||||
false,
|
||||
Some(BookmarkToolbarAction::SetStyle(
|
||||
current_style.next_in_page(),
|
||||
)),
|
||||
cx,
|
||||
))
|
||||
.child(make_icon_btn(
|
||||
"caption",
|
||||
"AddTextIcon",
|
||||
has_caption,
|
||||
false,
|
||||
BookmarkToolbarAction::Caption,
|
||||
cx,
|
||||
))
|
||||
.child(make_icon_btn(
|
||||
"copy",
|
||||
"CopyIcon",
|
||||
false,
|
||||
false,
|
||||
BookmarkToolbarAction::Copy,
|
||||
cx,
|
||||
));
|
||||
if !touch {
|
||||
row = row.child(make_icon_btn(
|
||||
"duplicate",
|
||||
"DuplicateIcon",
|
||||
false,
|
||||
false,
|
||||
BookmarkToolbarAction::Duplicate,
|
||||
cx,
|
||||
));
|
||||
}
|
||||
row = row.child(make_icon_btn(
|
||||
"delete",
|
||||
"DeleteIcon",
|
||||
false,
|
||||
true,
|
||||
BookmarkToolbarAction::Delete,
|
||||
cx,
|
||||
));
|
||||
|
||||
let root = place(rect)
|
||||
.id("bookmark-toolbar")
|
||||
.occlude()
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_mouse_down_out(|_: &MouseDownEvent, _, _| {})
|
||||
.p(px(pad))
|
||||
.rounded(px(TOOLBAR_RADIUS))
|
||||
.bg(palette.panel)
|
||||
.border_1()
|
||||
.border_color(palette.border)
|
||||
.shadow(palette.theme.shadows("--affine-toolbar-shadow").into())
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.snapshot("overlay.bookmark_toolbar", Some("root.canvas"))
|
||||
.child(row);
|
||||
Some(root.into_any_element())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,445 @@
|
||||
//! Floating / bottom-docked Callout toolbar (`overlay.callout_toolbar`) and Emoji/Icon
|
||||
//! picker (`overlay.callout_icon_picker`) aligned with BlockSuite `0.27.5` `callout/configs/toolbar.ts`.
|
||||
|
||||
use blocksuite_playground_doc::read::BlockContent;
|
||||
use ui::{
|
||||
AnyElement, ClickEvent, Context, FontWeight, MouseButton, MouseDownEvent, SharedString, div,
|
||||
prelude::*, px,
|
||||
};
|
||||
|
||||
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,
|
||||
};
|
||||
|
||||
/// 9 semantic Callout background color options matching JS `0.27.5` `callout/configs/toolbar.ts:26-36`.
|
||||
pub const CALLOUT_BG_COLORS: [(&str, &str); 9] = [
|
||||
("default", "--affine-v2-block-callout-background-grey"),
|
||||
("red", "--affine-v2-block-callout-background-red"),
|
||||
("orange", "--affine-v2-block-callout-background-orange"),
|
||||
("yellow", "--affine-v2-block-callout-background-yellow"),
|
||||
("green", "--affine-v2-block-callout-background-green"),
|
||||
("teal", "--affine-v2-block-callout-background-teal"),
|
||||
("blue", "--affine-v2-block-callout-background-blue"),
|
||||
("purple", "--affine-v2-block-callout-background-purple"),
|
||||
("grey", "--affine-v2-block-callout-background-grey"),
|
||||
];
|
||||
|
||||
/// Curated Callout icon/emoji presets offered in the icon picker (`6 × 2` grid + `Remove`).
|
||||
pub const CALLOUT_ICON_PRESETS: [&str; 12] = [
|
||||
"\u{1F4A1}", // 💡
|
||||
"\u{2139}\u{FE0F}", // ℹ️
|
||||
"\u{26A0}\u{FE0F}", // ⚠️
|
||||
"\u{1F525}", // 🔥
|
||||
"\u{2705}", // ✅
|
||||
"\u{274C}", // ❌
|
||||
"\u{1F4CC}", // 📌
|
||||
"\u{1F4DD}", // 📝
|
||||
"\u{1F680}", // 🚀
|
||||
"\u{2B50}", // ⭐
|
||||
"\u{1F3AF}", // 🎯
|
||||
"\u{1F512}", // 🔒
|
||||
];
|
||||
|
||||
/// Actions offered by the Callout toolbar and icon picker.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum CalloutAction {
|
||||
ToggleIconPicker,
|
||||
SetIcon(String),
|
||||
SetBackground(String),
|
||||
Delete,
|
||||
}
|
||||
|
||||
impl Overlays {
|
||||
/// Open or toggle the Callout emoji/icon picker for `block_id`.
|
||||
pub fn toggle_callout_icon_picker(&mut self, block_id: String) -> bool {
|
||||
if self.callout_icon_picker_block.as_deref() == Some(block_id.as_str()) {
|
||||
self.callout_icon_picker_block = None;
|
||||
} else {
|
||||
self.callout_icon_picker_block = Some(block_id);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Close the Callout emoji/icon picker if open.
|
||||
pub fn close_callout_icon_picker(&mut self) -> bool {
|
||||
self.callout_icon_picker_block.take().is_some()
|
||||
}
|
||||
|
||||
pub(super) fn handle_callout_action(
|
||||
&mut self,
|
||||
block_id: &str,
|
||||
action: &CalloutAction,
|
||||
effects: &mut OverlayEffects,
|
||||
) {
|
||||
match action {
|
||||
CalloutAction::ToggleIconPicker => {
|
||||
effects.redraw = self.toggle_callout_icon_picker(block_id.to_string());
|
||||
}
|
||||
CalloutAction::SetIcon(icon_val) => {
|
||||
self.callout_icon_picker_block = None;
|
||||
effects.edits.push(DocEdit::SetCalloutIcon {
|
||||
block_id: block_id.to_string(),
|
||||
unicode: icon_val.clone(),
|
||||
});
|
||||
effects.redraw = true;
|
||||
}
|
||||
CalloutAction::SetBackground(bg) => {
|
||||
let wire = if bg.eq_ignore_ascii_case("default") {
|
||||
"grey".to_string()
|
||||
} else {
|
||||
bg.clone()
|
||||
};
|
||||
effects.edits.push(DocEdit::SetProp {
|
||||
block_id: block_id.to_string(),
|
||||
key: "prop:backgroundColorName",
|
||||
value: y_octo::Any::String(wire),
|
||||
});
|
||||
effects.redraw = true;
|
||||
}
|
||||
CalloutAction::Delete => {
|
||||
self.callout_icon_picker_block = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn render_callout_toolbar<V: OverlayHost>(
|
||||
&mut self,
|
||||
scene: &OverlayScene<'_>,
|
||||
palette: &Palette,
|
||||
cx: &mut Context<V>,
|
||||
) -> Vec<AnyElement> {
|
||||
self.callout_toolbar_rect = None;
|
||||
self.callout_icon_picker_rect = None;
|
||||
if scene.page_readonly {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(block_id) = scene
|
||||
.selected_callout_block
|
||||
.or(self.callout_icon_picker_block.as_deref())
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
let block_id_owned = block_id.to_string();
|
||||
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((current_icon, raw_bg)) =
|
||||
scene
|
||||
.snapshot
|
||||
.block(block_id)
|
||||
.and_then(|n| match &n.content {
|
||||
BlockContent::Callout {
|
||||
icon,
|
||||
background_color,
|
||||
..
|
||||
} => Some((
|
||||
icon.trim().to_string(),
|
||||
background_color
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.unwrap_or("")
|
||||
.to_ascii_lowercase(),
|
||||
)),
|
||||
_ => None,
|
||||
})
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let touch = scene.form_factor != crate::block_flow::FormFactor::Desktop;
|
||||
let btn_h = if touch { 44.0 } else { TOOLBAR_BUTTON };
|
||||
let vp = scene.popover_viewport();
|
||||
let pad = TOOLBAR_PADDING;
|
||||
let max_w = (vp.w - 2.0 * POPOVER_EDGE_MARGIN).max(200.0);
|
||||
let compact_touch = touch && max_w < 410.0;
|
||||
let btn_w = if compact_touch {
|
||||
36.0
|
||||
} else if touch {
|
||||
44.0
|
||||
} else {
|
||||
TOOLBAR_BUTTON
|
||||
};
|
||||
let swatch = if compact_touch {
|
||||
22.0
|
||||
} else if touch {
|
||||
26.0
|
||||
} else {
|
||||
22.0
|
||||
};
|
||||
let swatch_gap = if compact_touch { 3.0 } else { 4.0 };
|
||||
let bar_gap = if compact_touch { 4.0 } else { 6.0 };
|
||||
let raw_w = 2.0 * (pad + POPOVER_BORDER)
|
||||
+ btn_w
|
||||
+ 9.0 * swatch
|
||||
+ 8.0 * swatch_gap
|
||||
+ btn_w
|
||||
+ 2.0
|
||||
+ 4.0 * bar_gap;
|
||||
let width = if touch { max_w } else { raw_w.min(max_w) }.round();
|
||||
let height = (btn_h + 2.0 * (pad + POPOVER_BORDER)).round();
|
||||
|
||||
let rect = if touch {
|
||||
FlowRect::new(
|
||||
(vp.x + (vp.w - width) * 0.5).round(),
|
||||
(vp.bottom() - height - POPOVER_EDGE_MARGIN).round(),
|
||||
width,
|
||||
height,
|
||||
)
|
||||
} else {
|
||||
place_popover(
|
||||
scene.world_to_screen(&block_world),
|
||||
(width, height),
|
||||
vp,
|
||||
Placement::Above,
|
||||
POPOVER_GAP,
|
||||
POPOVER_EDGE_MARGIN,
|
||||
)
|
||||
.rect
|
||||
};
|
||||
self.callout_toolbar_rect = Some(rect);
|
||||
|
||||
let hover_bg = palette.hover;
|
||||
let danger = palette
|
||||
.theme
|
||||
.css_var("--affine-error-color")
|
||||
.unwrap_or(palette.icon);
|
||||
let picker_open =
|
||||
self.callout_icon_picker_block.as_deref() == Some(block_id_owned.as_str());
|
||||
|
||||
let icon_btn_ev = OverlayEvent::CalloutAction {
|
||||
block_id: block_id_owned.clone(),
|
||||
action: CalloutAction::ToggleIconPicker,
|
||||
};
|
||||
let icon_snap_label = if current_icon.is_empty() {
|
||||
"Add icon".to_string()
|
||||
} else {
|
||||
current_icon.clone()
|
||||
};
|
||||
let mut icon_btn = div()
|
||||
.id("callout-tb-icon")
|
||||
.flex_none()
|
||||
.w(px(btn_w))
|
||||
.h(px(btn_h))
|
||||
.rounded(px(4.0))
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.cursor_pointer()
|
||||
.when(picker_open, |el| el.bg(palette.brand.opacity(0.14)))
|
||||
.hover(move |s| s.bg(hover_bg))
|
||||
.text_size(px(15.0))
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(emit(cx, move |_: &ClickEvent| icon_btn_ev.clone()))
|
||||
.snapshot(
|
||||
"overlay.callout_toolbar.icon",
|
||||
Some("overlay.callout_toolbar"),
|
||||
)
|
||||
.snapshot_focused(picker_open)
|
||||
.snapshot_text(icon_snap_label);
|
||||
icon_btn = if current_icon.is_empty() {
|
||||
icon_btn.child(icon("InformationIcon", 16.0, palette.icon))
|
||||
} else {
|
||||
icon_btn.child(current_icon.clone())
|
||||
};
|
||||
|
||||
let mut swatches = div().flex().items_center().gap(px(swatch_gap));
|
||||
for (name, css_var) in CALLOUT_BG_COLORS {
|
||||
let selected = if name == "default" {
|
||||
raw_bg.is_empty() || raw_bg == "default"
|
||||
} else {
|
||||
raw_bg == name
|
||||
};
|
||||
let fill = palette
|
||||
.theme
|
||||
.css_var(css_var)
|
||||
.unwrap_or(palette.background_secondary);
|
||||
let ev = OverlayEvent::CalloutAction {
|
||||
block_id: block_id_owned.clone(),
|
||||
action: CalloutAction::SetBackground(name.to_string()),
|
||||
};
|
||||
swatches = swatches.child(
|
||||
div()
|
||||
.id(SharedString::from(format!("callout-bg-{name}")))
|
||||
.flex_none()
|
||||
.w(px(swatch))
|
||||
.h(px(swatch))
|
||||
.rounded(px(swatch * 0.5))
|
||||
.bg(fill)
|
||||
.border_1()
|
||||
.border_color(if selected {
|
||||
palette.brand
|
||||
} else {
|
||||
palette.border
|
||||
})
|
||||
.cursor_pointer()
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(emit(cx, move |_: &ClickEvent| ev.clone()))
|
||||
.snapshot(
|
||||
SharedString::from(format!("overlay.callout_toolbar.bg.{name}")),
|
||||
Some("overlay.callout_toolbar"),
|
||||
)
|
||||
.snapshot_focused(selected)
|
||||
.snapshot_text(name),
|
||||
);
|
||||
}
|
||||
|
||||
let del_ev = OverlayEvent::CalloutAction {
|
||||
block_id: block_id_owned.clone(),
|
||||
action: CalloutAction::Delete,
|
||||
};
|
||||
let del_btn = div()
|
||||
.id("callout-tb-delete")
|
||||
.flex_none()
|
||||
.w(px(btn_w))
|
||||
.h(px(btn_h))
|
||||
.rounded(px(4.0))
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.cursor_pointer()
|
||||
.hover(move |s| s.bg(hover_bg))
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(emit(cx, move |_: &ClickEvent| del_ev.clone()))
|
||||
.snapshot(
|
||||
"overlay.callout_toolbar.delete",
|
||||
Some("overlay.callout_toolbar"),
|
||||
)
|
||||
.child(icon("DeleteIcon", 16.0, danger));
|
||||
|
||||
let mut out = Vec::new();
|
||||
let bar = place(rect)
|
||||
.id("callout-toolbar")
|
||||
.occlude()
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_mouse_down_out(|_: &MouseDownEvent, _, _| {})
|
||||
.p(px(pad))
|
||||
.rounded(px(TOOLBAR_RADIUS))
|
||||
.bg(palette.panel)
|
||||
.border_1()
|
||||
.border_color(palette.border)
|
||||
.shadow(palette.theme.shadows("--affine-toolbar-shadow").into())
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.gap(px(bar_gap))
|
||||
.snapshot("overlay.callout_toolbar", Some("root.canvas"))
|
||||
.child(icon_btn)
|
||||
.child(div().flex_none().w(px(1.0)).h(px(16.0)).bg(palette.divider))
|
||||
.child(swatches)
|
||||
.child(div().flex_none().w(px(1.0)).h(px(16.0)).bg(palette.divider))
|
||||
.child(del_btn);
|
||||
out.push(bar.into_any_element());
|
||||
|
||||
if picker_open {
|
||||
// 6 columns × 2 rows of 30px emoji tiles + Remove button row below.
|
||||
let picker_w = 220.0_f32;
|
||||
let picker_h = 114.0_f32;
|
||||
let pref = if touch {
|
||||
Placement::Above
|
||||
} else {
|
||||
Placement::BelowStart
|
||||
};
|
||||
let placed = place_popover(
|
||||
rect,
|
||||
(picker_w, picker_h),
|
||||
vp,
|
||||
pref,
|
||||
4.0,
|
||||
POPOVER_EDGE_MARGIN,
|
||||
);
|
||||
self.callout_icon_picker_rect = Some(placed.rect);
|
||||
let mut grid = div().flex().flex_wrap().gap(px(4.0));
|
||||
for (idx, emoji) in CALLOUT_ICON_PRESETS.iter().enumerate() {
|
||||
let ev = OverlayEvent::CalloutAction {
|
||||
block_id: block_id_owned.clone(),
|
||||
action: CalloutAction::SetIcon((*emoji).to_string()),
|
||||
};
|
||||
grid = grid.child(
|
||||
div()
|
||||
.id(SharedString::from(format!("callout-emoji-{idx}")))
|
||||
.flex_none()
|
||||
.w(px(30.0))
|
||||
.h(px(30.0))
|
||||
.rounded(px(4.0))
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.cursor_pointer()
|
||||
.hover(move |s| s.bg(hover_bg))
|
||||
.text_size(px(TYPOGRAPHY.font_base_px))
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(emit(cx, move |_: &ClickEvent| ev.clone()))
|
||||
.snapshot(
|
||||
SharedString::from(format!("overlay.callout_icon_picker.item.{idx}")),
|
||||
Some("overlay.callout_icon_picker"),
|
||||
)
|
||||
.snapshot_text(*emoji)
|
||||
.child(*emoji),
|
||||
);
|
||||
}
|
||||
let remove_ev = OverlayEvent::CalloutAction {
|
||||
block_id: block_id_owned,
|
||||
action: CalloutAction::SetIcon(String::new()),
|
||||
};
|
||||
let remove_btn = div()
|
||||
.id("callout-emoji-remove")
|
||||
.flex_none()
|
||||
.w_full()
|
||||
.h(px(24.0))
|
||||
.rounded(px(4.0))
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.cursor_pointer()
|
||||
.hover(move |s| s.bg(hover_bg))
|
||||
.text_size(px(TYPOGRAPHY.font_xs_px))
|
||||
.font_weight(FontWeight::MEDIUM)
|
||||
.text_color(palette.text_secondary)
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(emit(cx, move |_: &ClickEvent| remove_ev.clone()))
|
||||
.snapshot(
|
||||
"overlay.callout_icon_picker.remove",
|
||||
Some("overlay.callout_icon_picker"),
|
||||
)
|
||||
.snapshot_text("Remove")
|
||||
.child("Remove");
|
||||
let picker = place(placed.rect)
|
||||
.id("callout-icon-picker")
|
||||
.occlude()
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_mouse_down_out(emit(cx, |_: &MouseDownEvent| {
|
||||
OverlayEvent::CloseCalloutIconPicker
|
||||
}))
|
||||
.p(px(8.0))
|
||||
.rounded(px(TOOLBAR_RADIUS))
|
||||
.bg(palette.panel)
|
||||
.border_1()
|
||||
.border_color(palette.border)
|
||||
.shadow(
|
||||
palette
|
||||
.theme
|
||||
.shadows("--affine-overlay-panel-shadow")
|
||||
.into(),
|
||||
)
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(4.0))
|
||||
.snapshot("overlay.callout_icon_picker", Some("root.canvas"))
|
||||
.child(grid)
|
||||
.child(remove_btn);
|
||||
out.push(picker.into_any_element());
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,553 @@
|
||||
//! Searchable, scrollable code-block language selector (`overlay.code_lang_picker`) wired to
|
||||
//! `OverlayEvent::SetCodeLanguage`, plus capitalized display names (`"Rust"`, `"TypeScript"`, ...).
|
||||
|
||||
use ui::{
|
||||
AnyElement, ClickEvent, Context, FontWeight, MouseButton, MouseDownEvent, ScrollDelta,
|
||||
ScrollEvent, SharedString, Window, div, prelude::*, px,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
block_flow::{CODE_PADDING, FlowRect},
|
||||
theme::{Palette, TYPOGRAPHY},
|
||||
};
|
||||
|
||||
use super::{
|
||||
LinkBar, OverlayEvent, OverlayHost, OverlayScene, Overlays, POPOVER_BORDER,
|
||||
POPOVER_EDGE_MARGIN, Placement, Presence, TOOLBAR_RADIUS, emit, place, place_popover,
|
||||
};
|
||||
|
||||
const VISIBLE_LANG_ROWS: usize = 8;
|
||||
|
||||
/// Canonical BlockSuite / Shiki language catalog `(wire_id, display_label)`.
|
||||
pub const CODE_LANGUAGES: &[(&str, &str)] = &[
|
||||
("", "Plain Text"),
|
||||
("rust", "Rust"),
|
||||
("typescript", "TypeScript"),
|
||||
("javascript", "JavaScript"),
|
||||
("python", "Python"),
|
||||
("go", "Go"),
|
||||
("java", "Java"),
|
||||
("c", "C"),
|
||||
("cpp", "C++"),
|
||||
("csharp", "C#"),
|
||||
("swift", "Swift"),
|
||||
("kotlin", "Kotlin"),
|
||||
("html", "HTML"),
|
||||
("css", "CSS"),
|
||||
("json", "JSON"),
|
||||
("yaml", "YAML"),
|
||||
("toml", "TOML"),
|
||||
("sql", "SQL"),
|
||||
("bash", "Bash"),
|
||||
("markdown", "Markdown"),
|
||||
("mermaid", "Mermaid"),
|
||||
("typst", "Typst"),
|
||||
("diff", "Diff"),
|
||||
("graphql", "GraphQL"),
|
||||
("docker", "Dockerfile"),
|
||||
];
|
||||
|
||||
/// Format a wire `prop:language` value into its capitalized display name (`"rust"` -> `"Rust"`).
|
||||
pub fn display_code_language(raw: &str) -> String {
|
||||
let trimmed = raw.trim();
|
||||
if trimmed.is_empty()
|
||||
|| trimmed.eq_ignore_ascii_case("plain")
|
||||
|| trimmed.eq_ignore_ascii_case("plain text")
|
||||
{
|
||||
return "Plain Text".to_string();
|
||||
}
|
||||
let lower = trimmed.to_ascii_lowercase();
|
||||
for &(id, label) in CODE_LANGUAGES {
|
||||
if !id.is_empty() && id == lower {
|
||||
return label.to_string();
|
||||
}
|
||||
}
|
||||
match lower.as_str() {
|
||||
"ts" => "TypeScript".to_string(),
|
||||
"js" => "JavaScript".to_string(),
|
||||
"py" => "Python".to_string(),
|
||||
"cs" => "C#".to_string(),
|
||||
"yml" => "YAML".to_string(),
|
||||
"sh" | "shell" => "Bash".to_string(),
|
||||
"md" => "Markdown".to_string(),
|
||||
"dockerfile" => "Dockerfile".to_string(),
|
||||
_ => {
|
||||
let mut chars = trimmed.chars();
|
||||
match chars.next() {
|
||||
Some(first) => format!("{}{}", first.to_uppercase(), chars.as_str()),
|
||||
None => "Plain Text".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Filter [`CODE_LANGUAGES`] by case-insensitive substring match against wire id or display label.
|
||||
pub fn filter_code_languages(query: &str) -> Vec<(&'static str, &'static str)> {
|
||||
let needle = query.trim().to_ascii_lowercase();
|
||||
if needle.is_empty() {
|
||||
return CODE_LANGUAGES.to_vec();
|
||||
}
|
||||
CODE_LANGUAGES
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|(id, label)| {
|
||||
id.contains(needle.as_str()) || label.to_ascii_lowercase().contains(needle.as_str())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Open state of the searchable code-block language picker.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct CodeLangPicker {
|
||||
pub block_id: String,
|
||||
pub input: LinkBar,
|
||||
pub selected: usize,
|
||||
pub scroll_offset: usize,
|
||||
pub presence: Presence,
|
||||
pub rect: Option<FlowRect>,
|
||||
}
|
||||
|
||||
impl CodeLangPicker {
|
||||
pub fn ensure_selected_visible(&mut self, total: usize) {
|
||||
if total == 0 {
|
||||
self.selected = 0;
|
||||
self.scroll_offset = 0;
|
||||
return;
|
||||
}
|
||||
self.selected = self.selected.min(total - 1);
|
||||
let max_scroll = total.saturating_sub(VISIBLE_LANG_ROWS);
|
||||
if self.selected < self.scroll_offset {
|
||||
self.scroll_offset = self.selected;
|
||||
} else if self.selected >= self.scroll_offset + VISIBLE_LANG_ROWS {
|
||||
self.scroll_offset = self.selected + 1 - VISIBLE_LANG_ROWS;
|
||||
}
|
||||
self.scroll_offset = self.scroll_offset.min(max_scroll);
|
||||
}
|
||||
}
|
||||
|
||||
impl Overlays {
|
||||
/// Active (non-closing) code language picker.
|
||||
pub fn code_lang_picker(&self) -> Option<&CodeLangPicker> {
|
||||
self.code_lang_picker
|
||||
.as_ref()
|
||||
.filter(|p| !p.presence.closing)
|
||||
}
|
||||
|
||||
/// Mutable access to the open code language picker.
|
||||
pub fn code_lang_picker_mut(&mut self) -> Option<&mut CodeLangPicker> {
|
||||
self.code_lang_picker
|
||||
.as_mut()
|
||||
.filter(|p| !p.presence.closing)
|
||||
}
|
||||
|
||||
/// Open (or toggle off if already open for `block_id`) the searchable code language picker.
|
||||
pub fn open_code_lang_picker(&mut self, block_id: String, current_lang: &str, now_ms: f64) {
|
||||
if self
|
||||
.code_lang_picker()
|
||||
.is_some_and(|p| p.block_id == block_id)
|
||||
{
|
||||
self.close_code_lang_picker(now_ms);
|
||||
return;
|
||||
}
|
||||
self.close_slash(now_ms);
|
||||
self.close_linked_doc(now_ms);
|
||||
self.close_link_field();
|
||||
self.close_equation_editor_at(now_ms);
|
||||
self.close_bookmark_prompt_at(now_ms);
|
||||
let presence = match self.code_lang_picker.take() {
|
||||
Some(prev) => prev.presence.reopened(now_ms),
|
||||
None => Presence::opening(now_ms),
|
||||
};
|
||||
let norm = match current_lang.trim().to_ascii_lowercase().as_str() {
|
||||
"plain" | "plain text" => String::new(),
|
||||
"dockerfile" => "docker".to_string(),
|
||||
other => other.to_string(),
|
||||
};
|
||||
let initial_idx = CODE_LANGUAGES
|
||||
.iter()
|
||||
.position(|(id, _)| *id == norm)
|
||||
.unwrap_or(0);
|
||||
let mut picker = CodeLangPicker {
|
||||
block_id,
|
||||
input: LinkBar::new(String::new()),
|
||||
selected: initial_idx,
|
||||
scroll_offset: 0,
|
||||
presence,
|
||||
rect: None,
|
||||
};
|
||||
picker.ensure_selected_visible(CODE_LANGUAGES.len());
|
||||
self.code_lang_picker = Some(picker);
|
||||
}
|
||||
|
||||
/// Dismiss the code language picker with a fade-out transition.
|
||||
pub fn close_code_lang_picker(&mut self, now_ms: f64) -> bool {
|
||||
match self.code_lang_picker_mut() {
|
||||
Some(picker) => {
|
||||
picker.presence.close(now_ms);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn render_code_lang_picker<V: OverlayHost>(
|
||||
&mut self,
|
||||
scene: &OverlayScene<'_>,
|
||||
palette: &Palette,
|
||||
now_ms: f64,
|
||||
_window: &mut Window,
|
||||
cx: &mut Context<V>,
|
||||
) -> Option<AnyElement> {
|
||||
let picker = self.code_lang_picker.as_mut()?;
|
||||
picker.rect = None;
|
||||
let progress = picker.presence.progress(now_ms);
|
||||
if picker.presence.closing && progress <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let interactive = !picker.presence.closing;
|
||||
let progress = if interactive {
|
||||
progress.max(0.01)
|
||||
} else {
|
||||
progress
|
||||
};
|
||||
let block = scene.layout.block(&picker.block_id)?;
|
||||
let (_, pad_x) = CODE_PADDING;
|
||||
let anchor_world = FlowRect::new(block.x + pad_x, block.y + 8.0, 120.0, 22.0);
|
||||
if !scene.anchor_visible(&anchor_world) {
|
||||
return None;
|
||||
}
|
||||
let query = picker.input.text();
|
||||
let items = filter_code_languages(&query);
|
||||
picker.ensure_selected_visible(items.len());
|
||||
let max_rows = items.len().clamp(1, VISIBLE_LANG_ROWS);
|
||||
let row_h = 26.0_f32;
|
||||
let search_h = 28.0_f32;
|
||||
let pad = 6.0_f32;
|
||||
let width = 196.0_f32;
|
||||
let height =
|
||||
(2.0 * (pad + POPOVER_BORDER) + search_h + 6.0 + max_rows as f32 * row_h).round();
|
||||
let anchor = scene.world_to_screen(&anchor_world);
|
||||
let viewport = scene.popover_viewport();
|
||||
let placed = place_popover(
|
||||
anchor,
|
||||
(width, height),
|
||||
viewport,
|
||||
Placement::BelowStart,
|
||||
4.0,
|
||||
POPOVER_EDGE_MARGIN,
|
||||
);
|
||||
picker.rect = Some(placed.rect);
|
||||
|
||||
let block_id = picker.block_id.clone();
|
||||
let selected_idx = picker.selected;
|
||||
let scroll_off = picker.scroll_offset;
|
||||
let hover_bg = palette.hover;
|
||||
let current_lang = scene
|
||||
.snapshot
|
||||
.block(&block_id)
|
||||
.and_then(|n| match &n.content {
|
||||
blocksuite_playground_doc::read::BlockContent::Code { language, .. } => {
|
||||
let l = language.trim().to_ascii_lowercase();
|
||||
Some(if l == "dockerfile" {
|
||||
"docker".to_string()
|
||||
} else if l == "plain" || l == "plain text" {
|
||||
String::new()
|
||||
} else {
|
||||
l
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
let search_box = div()
|
||||
.flex_none()
|
||||
.w_full()
|
||||
.h(px(search_h))
|
||||
.px(px(8.0))
|
||||
.rounded(px(4.0))
|
||||
.bg(palette.background)
|
||||
.border_1()
|
||||
.border_color(palette.brand)
|
||||
.flex()
|
||||
.items_center()
|
||||
.text_size(px(TYPOGRAPHY.font_xs_px))
|
||||
.text_color(if query.is_empty() {
|
||||
palette.placeholder
|
||||
} else {
|
||||
palette.text_primary
|
||||
})
|
||||
.snapshot(
|
||||
"overlay.code_lang_picker.search",
|
||||
Some("overlay.code_lang_picker"),
|
||||
)
|
||||
.snapshot_focused(true)
|
||||
.snapshot_text(query.clone())
|
||||
.child(if query.is_empty() {
|
||||
"Search language...".to_string()
|
||||
} else {
|
||||
query
|
||||
});
|
||||
|
||||
let mut list = div().flex().flex_col().overflow_hidden();
|
||||
for (idx, &(wire_id, label)) in items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.skip(scroll_off)
|
||||
.take(VISIBLE_LANG_ROWS)
|
||||
{
|
||||
let is_current = current_lang == wire_id;
|
||||
let is_sel = idx == selected_idx;
|
||||
let bid = block_id.clone();
|
||||
let lang = wire_id.to_string();
|
||||
let mut row = div()
|
||||
.id(SharedString::from(format!("code-lang-row-{idx}")))
|
||||
.flex_none()
|
||||
.w_full()
|
||||
.h(px(row_h))
|
||||
.px(px(8.0))
|
||||
.rounded(px(4.0))
|
||||
.flex()
|
||||
.items_center()
|
||||
.text_size(px(TYPOGRAPHY.font_xs_px))
|
||||
.font_weight(if is_current {
|
||||
FontWeight::SEMIBOLD
|
||||
} else {
|
||||
FontWeight::NORMAL
|
||||
})
|
||||
.text_color(if is_current {
|
||||
palette.brand
|
||||
} else {
|
||||
palette.text_primary
|
||||
})
|
||||
.when(is_sel, |el| el.bg(hover_bg))
|
||||
.snapshot(
|
||||
SharedString::from(format!(
|
||||
"overlay.code_lang_picker.item.{}",
|
||||
if wire_id.is_empty() { "plain" } else { wire_id }
|
||||
)),
|
||||
Some("overlay.code_lang_picker"),
|
||||
)
|
||||
.snapshot_focused(is_current)
|
||||
.snapshot_text(label)
|
||||
.child(label);
|
||||
if interactive {
|
||||
row = row
|
||||
.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::SetCodeLanguage {
|
||||
block_id: bid.clone(),
|
||||
language: lang.clone(),
|
||||
}
|
||||
}));
|
||||
}
|
||||
list = list.child(row);
|
||||
}
|
||||
if items.is_empty() {
|
||||
list = list.child(
|
||||
div()
|
||||
.h(px(row_h))
|
||||
.px(px(8.0))
|
||||
.flex()
|
||||
.items_center()
|
||||
.text_size(px(TYPOGRAPHY.font_xs_px))
|
||||
.text_color(palette.text_secondary)
|
||||
.child("No matching language"),
|
||||
);
|
||||
}
|
||||
|
||||
let mut root = place(placed.rect)
|
||||
.id("code-lang-picker")
|
||||
.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.code_lang_picker", Some("root.canvas"))
|
||||
.snapshot_focused(interactive)
|
||||
.child(search_box)
|
||||
.child(list);
|
||||
if interactive {
|
||||
root = root
|
||||
.occlude()
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_scroll(cx.listener(|view: &mut V, ev: &ScrollEvent, w, cx| {
|
||||
cx.stop_propagation();
|
||||
let dy = match ev.delta {
|
||||
ScrollDelta::Pixels(p) => f32::from(p.y),
|
||||
ScrollDelta::Lines(l) => l.y * 26.0,
|
||||
};
|
||||
if dy.abs() > 0.1 {
|
||||
let rows = if dy < 0.0 { 1 } else { -1 };
|
||||
view.dispatch_overlay(OverlayEvent::CodeLangPickerScroll(rows), w, cx);
|
||||
}
|
||||
}))
|
||||
.on_mouse_down_out(emit(cx, |_: &MouseDownEvent| {
|
||||
OverlayEvent::CloseCodeLangPicker
|
||||
}));
|
||||
}
|
||||
Some(root.into_any_element())
|
||||
}
|
||||
|
||||
pub(super) fn handle_code_and_media_event(
|
||||
&mut self,
|
||||
event: &OverlayEvent,
|
||||
scene: Option<&OverlayScene<'_>>,
|
||||
now_ms: f64,
|
||||
effects: &mut super::OverlayEffects,
|
||||
) {
|
||||
match event {
|
||||
OverlayEvent::OpenCodeLangPicker(block_id) => {
|
||||
let current_lang = scene
|
||||
.and_then(|s| s.snapshot.block(block_id))
|
||||
.and_then(|n| match &n.content {
|
||||
blocksuite_playground_doc::read::BlockContent::Code {
|
||||
language, ..
|
||||
} => Some(language.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or("");
|
||||
self.open_code_lang_picker(block_id.clone(), current_lang, now_ms);
|
||||
effects.redraw = true;
|
||||
}
|
||||
OverlayEvent::CodeLangPickerScroll(delta_rows) => {
|
||||
if let Some(picker) = self.code_lang_picker_mut() {
|
||||
let total = filter_code_languages(&picker.input.text()).len();
|
||||
let max_scroll = total.saturating_sub(VISIBLE_LANG_ROWS);
|
||||
picker.scroll_offset = picker
|
||||
.scroll_offset
|
||||
.saturating_add_signed(*delta_rows)
|
||||
.min(max_scroll);
|
||||
effects.redraw = true;
|
||||
}
|
||||
}
|
||||
OverlayEvent::CloseCodeLangPicker => {
|
||||
effects.redraw = self.close_code_lang_picker(now_ms);
|
||||
}
|
||||
OverlayEvent::ToggleCodeLineNumber(block_id) => {
|
||||
let current = scene
|
||||
.and_then(|s| s.snapshot.block(block_id))
|
||||
.and_then(|n| n.props.get("prop:lineNumber").and_then(|v| v.as_bool()))
|
||||
.unwrap_or(
|
||||
scene.is_none_or(|s| s.form_factor != crate::block_flow::FormFactor::Phone),
|
||||
);
|
||||
effects.edits.push(super::DocEdit::SetProp {
|
||||
block_id: block_id.clone(),
|
||||
key: "prop:lineNumber",
|
||||
value: if current {
|
||||
y_octo::Any::False
|
||||
} else {
|
||||
y_octo::Any::True
|
||||
},
|
||||
});
|
||||
effects.redraw = true;
|
||||
}
|
||||
OverlayEvent::ToggleCodeCollapsed(block_id) => {
|
||||
let current = scene
|
||||
.and_then(|s| s.snapshot.block(block_id))
|
||||
.and_then(|n| n.props.get("prop:collapsed").and_then(|v| v.as_bool()))
|
||||
.unwrap_or(false);
|
||||
effects.edits.push(super::DocEdit::SetProp {
|
||||
block_id: block_id.clone(),
|
||||
key: "prop:collapsed",
|
||||
value: if current {
|
||||
y_octo::Any::False
|
||||
} else {
|
||||
y_octo::Any::True
|
||||
},
|
||||
});
|
||||
effects.redraw = true;
|
||||
}
|
||||
OverlayEvent::OpenImageLightbox(block_id) => {
|
||||
self.open_image_lightbox(block_id.clone(), now_ms);
|
||||
effects.redraw = true;
|
||||
}
|
||||
OverlayEvent::ImageLightboxZoom(delta) => {
|
||||
effects.redraw = self.set_image_lightbox_zoom(*delta);
|
||||
}
|
||||
OverlayEvent::ImageLightboxPan { dx, dy } => {
|
||||
effects.redraw = self.pan_image_lightbox(*dx, *dy);
|
||||
}
|
||||
OverlayEvent::CloseImageLightbox => {
|
||||
effects.redraw = self.close_image_lightbox(now_ms);
|
||||
}
|
||||
OverlayEvent::CalloutAction { block_id, action } => {
|
||||
self.handle_callout_action(block_id, action, effects);
|
||||
}
|
||||
OverlayEvent::CloseCalloutIconPicker => {
|
||||
effects.redraw = self.close_callout_icon_picker();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn handle_code_lang_picker_key(
|
||||
&mut self,
|
||||
key: &str,
|
||||
now_ms: f64,
|
||||
effects: &mut super::OverlayEffects,
|
||||
) -> bool {
|
||||
let Some(picker) = self.code_lang_picker_mut() else {
|
||||
return false;
|
||||
};
|
||||
let items = filter_code_languages(&picker.input.text());
|
||||
match key {
|
||||
"up" | "down" => {
|
||||
let len = items.len();
|
||||
if len > 0 {
|
||||
let cur = picker.selected.min(len - 1);
|
||||
picker.selected = if key == "down" {
|
||||
(cur + 1) % len
|
||||
} else {
|
||||
(cur + len - 1) % len
|
||||
};
|
||||
picker.ensure_selected_visible(len);
|
||||
effects.redraw = true;
|
||||
}
|
||||
effects.handled = true;
|
||||
true
|
||||
}
|
||||
"enter" => {
|
||||
if let Some(&(wire_id, _)) =
|
||||
items.get(picker.selected.min(items.len().saturating_sub(1)))
|
||||
{
|
||||
let block_id = picker.block_id.clone();
|
||||
self.close_code_lang_picker(now_ms);
|
||||
effects.edits.push(super::DocEdit::SetProp {
|
||||
block_id,
|
||||
key: "prop:language",
|
||||
value: super::helpers::normalize_code_language(wire_id),
|
||||
});
|
||||
} else {
|
||||
self.close_code_lang_picker(now_ms);
|
||||
}
|
||||
effects.handled = true;
|
||||
effects.redraw = true;
|
||||
true
|
||||
}
|
||||
"escape" => {
|
||||
if picker.input.composing() {
|
||||
picker.input.cancel_preedit();
|
||||
} else {
|
||||
self.close_code_lang_picker(now_ms);
|
||||
}
|
||||
effects.handled = true;
|
||||
effects.redraw = true;
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,8 @@ pub const CONTEXT_MENU_ROW_HEIGHT: f32 = 30.0;
|
||||
const CONTEXT_MENU_SEPARATOR_HEIGHT: f32 = 9.0;
|
||||
/// Duration of the clipboard fallback toast in milliseconds on the scheduler clock.
|
||||
pub const CONTEXT_TOAST_MS: u64 = 2_200;
|
||||
/// Enter/exit fade and slide duration for the bottom toast.
|
||||
pub const TOAST_MOTION_MS: f64 = 230.0;
|
||||
|
||||
/// Command executed when clicking a desktop context menu item.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -138,6 +140,8 @@ impl ContextMenuState {
|
||||
pub struct ContextToast {
|
||||
pub message: String,
|
||||
pub generation: u64,
|
||||
/// Scheduler-clock fade-in transition (`230ms`), seeded on first render when absent.
|
||||
pub fade: Option<super::EaseOut>,
|
||||
}
|
||||
|
||||
/// Place a context menu anchored at `(anchor_x, anchor_y)` inside `viewport`, flipping
|
||||
@@ -374,12 +378,19 @@ pub(super) fn render_context_menu<V: OverlayHost>(
|
||||
Some(root.into_any_element())
|
||||
}
|
||||
|
||||
/// Render the transient clipboard shortcut hint toast centered near the bottom of the viewport.
|
||||
/// Render the transient clipboard shortcut hint toast centered near the bottom of the viewport,
|
||||
/// avoiding soft-keyboard and mobile toolbar insets with a `230ms` fade+slide transition.
|
||||
pub(super) fn render_context_toast(
|
||||
toast: &ContextToast,
|
||||
toast: &mut ContextToast,
|
||||
viewport: FlowRect,
|
||||
bottom_clearance: f32,
|
||||
now_ms: f64,
|
||||
palette: &Palette,
|
||||
) -> AnyElement {
|
||||
let _ = toast
|
||||
.fade
|
||||
.get_or_insert_with(|| super::EaseOut::with_duration(1.0, 1.0, now_ms, TOAST_MOTION_MS));
|
||||
let progress = 1.0_f32;
|
||||
let est_w = (toast.message.chars().count() as f32 * 7.2 + 32.0).max(228.0);
|
||||
let width = est_w.min((viewport.w - 2.0 * POPOVER_EDGE_MARGIN).max(120.0));
|
||||
let height = 34.0;
|
||||
@@ -389,20 +400,21 @@ pub(super) fn render_context_toast(
|
||||
(viewport.right() - POPOVER_EDGE_MARGIN - width).max(viewport.x + POPOVER_EDGE_MARGIN),
|
||||
)
|
||||
.round();
|
||||
let y = (viewport.bottom() - height - 64.0)
|
||||
let base_y = (viewport.bottom() - bottom_clearance - height - 16.0)
|
||||
.clamp(
|
||||
viewport.y + POPOVER_EDGE_MARGIN,
|
||||
(viewport.bottom() - POPOVER_EDGE_MARGIN - height)
|
||||
.max(viewport.y + POPOVER_EDGE_MARGIN),
|
||||
)
|
||||
.round();
|
||||
place(FlowRect::new(x, y, width, height))
|
||||
place(FlowRect::new(x, base_y, width, height))
|
||||
.px(px(12.0))
|
||||
.rounded(px(8.0))
|
||||
.bg(palette.panel)
|
||||
.border_1()
|
||||
.border_color(palette.border)
|
||||
.shadow(palette.theme.shadows("--affine-toolbar-shadow").into())
|
||||
.opacity(progress)
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
@@ -471,6 +483,7 @@ impl super::Overlays {
|
||||
self.context_toast = Some(ContextToast {
|
||||
message: message.into(),
|
||||
generation,
|
||||
fade: None,
|
||||
});
|
||||
generation
|
||||
}
|
||||
@@ -526,6 +539,10 @@ impl super::Overlays {
|
||||
.block_menu
|
||||
.as_ref()
|
||||
.is_some_and(|m| m.presence.in_flight(now_ms) || m.presence.closing)
|
||||
|| self
|
||||
.context_toast
|
||||
.as_ref()
|
||||
.is_some_and(|t| t.fade.is_none_or(|f| !f.is_finished(now_ms)))
|
||||
{
|
||||
window.request_animation_frame();
|
||||
}
|
||||
@@ -544,8 +561,16 @@ impl super::Overlays {
|
||||
menu, viewport, palette, now_ms, cx,
|
||||
));
|
||||
}
|
||||
if let Some(toast) = self.context_toast.as_ref() {
|
||||
elements.push(render_context_toast(toast, viewport, palette));
|
||||
let kb_clearance = self.keyboard_toolbar_reserved_height(window_size.1);
|
||||
let bottom_clearance = kb_clearance.max(48.0);
|
||||
if let Some(toast) = self.context_toast.as_mut() {
|
||||
elements.push(render_context_toast(
|
||||
toast,
|
||||
viewport,
|
||||
bottom_clearance,
|
||||
now_ms,
|
||||
palette,
|
||||
));
|
||||
}
|
||||
elements
|
||||
}
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
//! Canonical `0.27.5`-compatible URL classification for `Card` and `Embed` view conversions
|
||||
//! (`EmbedOptionProvider` + `GenericEmbedConfig` in BlockSuite `0.27.5`).
|
||||
//!
|
||||
//! Hostname and path segments are parsed structurally (never via raw URL substring matching),
|
||||
//! and `ExternalEmbedKind::Web` (`affine:embed-web`) is never emitted.
|
||||
|
||||
use blocksuite_playground_doc::read::ExternalEmbedKind;
|
||||
|
||||
use crate::clipboard::sanitize::sanitize_url;
|
||||
|
||||
/// AFFiNE Cloud/Canary domains excluded from generic iframe embedding (`generic.ts:17-23`).
|
||||
const AFFINE_EXCLUDED_DOMAINS: &[&str] = &[
|
||||
"app.affine.pro",
|
||||
"insider.affine.pro",
|
||||
"affine.fail",
|
||||
"toeverything.app",
|
||||
"apple.getaffineapp.com",
|
||||
];
|
||||
|
||||
struct ParsedHttpUrl<'a> {
|
||||
scheme: &'a str,
|
||||
host: String,
|
||||
path: &'a str,
|
||||
query: &'a str,
|
||||
}
|
||||
|
||||
fn parse_http_url(raw: &str) -> Option<ParsedHttpUrl<'_>> {
|
||||
let trimmed = raw.trim();
|
||||
if trimmed.len() > 1000 {
|
||||
return None;
|
||||
}
|
||||
let (scheme, rest) = if let Some(r) = trimmed
|
||||
.get(..8)
|
||||
.filter(|p| p.eq_ignore_ascii_case("https://"))
|
||||
.and_then(|_| trimmed.get(8..))
|
||||
{
|
||||
("https", r)
|
||||
} else if let Some(r) = trimmed
|
||||
.get(..7)
|
||||
.filter(|p| p.eq_ignore_ascii_case("http://"))
|
||||
.and_then(|_| trimmed.get(7..))
|
||||
{
|
||||
("http", r)
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
let without_frag = rest.split('#').next().unwrap_or(rest);
|
||||
let (authority_and_path, query) = match without_frag.split_once('?') {
|
||||
Some((ap, q)) => (ap, q),
|
||||
None => (without_frag, ""),
|
||||
};
|
||||
let (authority, path) = match authority_and_path.find('/') {
|
||||
Some(idx) => (&authority_and_path[..idx], &authority_and_path[idx..]),
|
||||
None => (authority_and_path, "/"),
|
||||
};
|
||||
// Reject userinfo (`user@host`) and empty authorities.
|
||||
if authority.is_empty() || authority.contains('@') {
|
||||
return None;
|
||||
}
|
||||
let host_part = if authority.starts_with('[') {
|
||||
let end = authority.find(']')?;
|
||||
&authority[..=end]
|
||||
} else {
|
||||
authority.split(':').next().unwrap_or(authority)
|
||||
};
|
||||
let host = host_part.trim().to_ascii_lowercase();
|
||||
if host.is_empty() || !host.contains('.') && host != "localhost" {
|
||||
return None;
|
||||
}
|
||||
Some(ParsedHttpUrl {
|
||||
scheme,
|
||||
host,
|
||||
path,
|
||||
query,
|
||||
})
|
||||
}
|
||||
|
||||
fn is_youtube_embed(p: &ParsedHttpUrl<'_>) -> bool {
|
||||
let is_id = |s: &str| {
|
||||
!s.is_empty()
|
||||
&& s.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
|
||||
};
|
||||
if p.host == "youtu.be" {
|
||||
let seg = p
|
||||
.path
|
||||
.trim_start_matches('/')
|
||||
.split('/')
|
||||
.next()
|
||||
.unwrap_or("");
|
||||
return is_id(seg);
|
||||
}
|
||||
if matches!(
|
||||
p.host.as_str(),
|
||||
"youtube.com" | "www.youtube.com" | "m.youtube.com"
|
||||
) {
|
||||
for pair in p.query.split('&') {
|
||||
if let Some(val) = pair.strip_prefix("v=")
|
||||
&& is_id(val)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
let mut segs = p.path.trim_start_matches('/').split('/');
|
||||
if let (Some(prefix), Some(id)) = (segs.next(), segs.next())
|
||||
&& matches!(prefix, "embed" | "v" | "shorts" | "live")
|
||||
&& is_id(id)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn is_figma_embed(p: &ParsedHttpUrl<'_>) -> bool {
|
||||
if p.scheme != "https" {
|
||||
return false;
|
||||
}
|
||||
if p.host != "figma.com" && !p.host.ends_with(".figma.com") {
|
||||
return false;
|
||||
}
|
||||
let mut segs = p.path.trim_start_matches('/').split('/');
|
||||
let Some(kind) = segs.next() else {
|
||||
return false;
|
||||
};
|
||||
let Some(file_key) = segs.next() else {
|
||||
return false;
|
||||
};
|
||||
!kind.is_empty()
|
||||
&& kind
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
|
||||
&& (22..=128).contains(&file_key.len())
|
||||
&& file_key.chars().all(|c| c.is_ascii_alphanumeric())
|
||||
}
|
||||
|
||||
fn is_loom_embed(p: &ParsedHttpUrl<'_>) -> bool {
|
||||
if p.host != "loom.com" && p.host != "www.loom.com" {
|
||||
return false;
|
||||
}
|
||||
let mut segs = p.path.trim_start_matches('/').split('/');
|
||||
matches!(segs.next(), Some("share"))
|
||||
&& segs
|
||||
.next()
|
||||
.is_some_and(|id| !id.is_empty() && id.chars().all(|c| c.is_ascii_alphanumeric()))
|
||||
}
|
||||
|
||||
fn is_github_card(p: &ParsedHttpUrl<'_>) -> bool {
|
||||
if p.host != "github.com" && p.host != "www.github.com" {
|
||||
return false;
|
||||
}
|
||||
let segs: Vec<&str> = p
|
||||
.path
|
||||
.trim_matches('/')
|
||||
.split('/')
|
||||
.filter(|s| !s.is_empty())
|
||||
.collect();
|
||||
segs.len() == 4
|
||||
&& matches!(segs[2], "issue" | "issues" | "pull" | "pulls")
|
||||
&& segs[3].chars().all(|c| c.is_ascii_digit())
|
||||
}
|
||||
|
||||
fn is_generic_https_iframe(p: &ParsedHttpUrl<'_>) -> bool {
|
||||
if p.scheme != "https" || p.host == "localhost" {
|
||||
return false;
|
||||
}
|
||||
!AFFINE_EXCLUDED_DOMAINS
|
||||
.iter()
|
||||
.any(|d| p.host == *d || p.host.ends_with(&format!(".{d}")))
|
||||
}
|
||||
|
||||
/// Resolve specialized `Card view` embed kind (`EmbedOptionConfig.viewType === 'card'`).
|
||||
/// Returns `Some(Github)` for GitHub issue/PR URLs; `None` means standard `affine:bookmark`.
|
||||
pub fn card_embed_kind_for_url(url: &str) -> Option<ExternalEmbedKind> {
|
||||
let clean = sanitize_url(url).filter(|u| !u.starts_with('#'))?;
|
||||
let parsed = parse_http_url(&clean)?;
|
||||
if is_github_card(&parsed) {
|
||||
Some(ExternalEmbedKind::Github)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve `Embed view` flavour (`EmbedOptionProvider` `viewType === 'embed'` + `GenericEmbedConfig`
|
||||
/// `affine:embed-iframe`). Returns `None` when the URL cannot be embedded in JS `0.27.5`.
|
||||
pub fn embed_view_kind_for_url(url: &str) -> Option<ExternalEmbedKind> {
|
||||
let clean = sanitize_url(url).filter(|u| !u.starts_with('#'))?;
|
||||
let parsed = parse_http_url(&clean)?;
|
||||
if is_youtube_embed(&parsed) {
|
||||
Some(ExternalEmbedKind::Youtube)
|
||||
} else if is_figma_embed(&parsed) {
|
||||
Some(ExternalEmbedKind::Figma)
|
||||
} else if is_loom_embed(&parsed) {
|
||||
Some(ExternalEmbedKind::Loom)
|
||||
} else if is_generic_https_iframe(&parsed) {
|
||||
Some(ExternalEmbedKind::Iframe)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn host_parsing_prevents_query_substring_spoofing_and_web_flavour() {
|
||||
assert_eq!(
|
||||
embed_view_kind_for_url("https://www.youtube.com/watch?v=dQw4w9WgXcQ"),
|
||||
Some(ExternalEmbedKind::Youtube)
|
||||
);
|
||||
assert_eq!(
|
||||
embed_view_kind_for_url("https://evil.example/?u=https://youtube.com/watch?v=abc"),
|
||||
Some(ExternalEmbedKind::Iframe)
|
||||
);
|
||||
assert_eq!(
|
||||
card_embed_kind_for_url("https://evil.example/?u=github.com/org/repo/pull/1"),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
card_embed_kind_for_url("https://github.com/toeverything/AFFiNE/pull/42"),
|
||||
Some(ExternalEmbedKind::Github)
|
||||
);
|
||||
assert_eq!(embed_view_kind_for_url("http://plain.example/page"), None);
|
||||
assert_eq!(
|
||||
embed_view_kind_for_url("https://app.affine.pro/workspace/abc"),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,33 @@
|
||||
use ui::Keystroke;
|
||||
|
||||
use crate::block_flow::{CodeScroll, FlowLayout, ScrolledCode};
|
||||
|
||||
use super::Overlays;
|
||||
use super::{LinkBar, LinkEditField, Overlays, SlashMenu};
|
||||
|
||||
/// Text a keystroke types, if it types any. `secondary` is the platform's command
|
||||
/// modifier.
|
||||
pub(super) fn typed_text(keystroke: &Keystroke, secondary: bool) -> Option<String> {
|
||||
let modifiers = &keystroke.modifiers;
|
||||
if secondary || modifiers.function {
|
||||
return None;
|
||||
}
|
||||
if let Some(text) = keystroke
|
||||
.key_char
|
||||
.as_ref()
|
||||
.filter(|text| !text.is_empty() && !text.chars().any(char::is_control))
|
||||
{
|
||||
return Some(text.clone());
|
||||
}
|
||||
let mut chars = keystroke.key.chars();
|
||||
match (chars.next(), chars.next()) {
|
||||
(Some(ch), None) if !modifiers.alt => Some(if modifiers.shift {
|
||||
ch.to_uppercase().collect()
|
||||
} else {
|
||||
ch.to_string()
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn push_toggle_code_wrap(
|
||||
block_id: String,
|
||||
@@ -37,6 +64,64 @@ pub(super) fn normalize_code_language(language: &str) -> y_octo::Any {
|
||||
}
|
||||
|
||||
impl Overlays {
|
||||
/// The slash menu, while it is open.
|
||||
pub fn slash_menu(&self) -> Option<&SlashMenu> {
|
||||
self.slash.as_ref().filter(|menu| !menu.presence.closing)
|
||||
}
|
||||
|
||||
/// Whether the formatting toolbar is open.
|
||||
pub fn format_toolbar_open(&self) -> bool {
|
||||
self.open_toolbar().is_some()
|
||||
}
|
||||
|
||||
/// Text of the toolbar's link field, while that field is open.
|
||||
pub fn link_url(&self) -> Option<&str> {
|
||||
self.link_field().map(LinkBar::url)
|
||||
}
|
||||
|
||||
/// The toolbar's link field, while it is open.
|
||||
pub fn link_field(&self) -> Option<&LinkBar> {
|
||||
self.open_toolbar()?.link.as_ref()
|
||||
}
|
||||
|
||||
pub fn link_field_mut(&mut self) -> Option<&mut LinkBar> {
|
||||
self.open_toolbar_mut()?.link.as_mut()
|
||||
}
|
||||
|
||||
/// Whichever overlay text field currently owns text input (equation, bookmark, code lang search, or link).
|
||||
pub fn active_text_field(&self) -> Option<&LinkBar> {
|
||||
self.equation_editor()
|
||||
.map(|editor| &editor.input)
|
||||
.or_else(|| self.bookmark_prompt().map(|prompt| &prompt.input))
|
||||
.or_else(|| self.code_lang_picker().map(|picker| &picker.input))
|
||||
.or_else(|| {
|
||||
let tb = self.open_toolbar()?;
|
||||
if tb.active_link_field == LinkEditField::Text {
|
||||
tb.link_text.as_ref().or(tb.link.as_ref())
|
||||
} else {
|
||||
tb.link.as_ref()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn active_text_field_mut(&mut self) -> Option<&mut LinkBar> {
|
||||
if self.equation_editor().is_some() {
|
||||
return self.equation_editor_mut().map(|editor| &mut editor.input);
|
||||
}
|
||||
if self.bookmark_prompt().is_some() {
|
||||
return self.bookmark_prompt_mut().map(|prompt| &mut prompt.input);
|
||||
}
|
||||
if self.code_lang_picker().is_some() {
|
||||
return self.code_lang_picker_mut().map(|picker| &mut picker.input);
|
||||
}
|
||||
let tb = self.open_toolbar_mut()?;
|
||||
if tb.active_link_field == LinkEditField::Text && tb.link_text.is_some() {
|
||||
tb.link_text.as_mut()
|
||||
} else {
|
||||
tb.link.as_mut()
|
||||
}
|
||||
}
|
||||
|
||||
/// Sideways scroll of a code/table/database block.
|
||||
pub fn code_scroll_x(&self, block_id: &str) -> f32 {
|
||||
self.code_scroll.get(block_id).copied().unwrap_or(0.0)
|
||||
@@ -432,7 +517,13 @@ impl Overlays {
|
||||
self.link_popup = None;
|
||||
self.equation = None;
|
||||
self.bookmark = None;
|
||||
self.code_lang_picker = None;
|
||||
self.image_lightbox = None;
|
||||
self.image_toolbar_rect = None;
|
||||
self.bookmark_toolbar_rect = None;
|
||||
self.callout_toolbar_rect = None;
|
||||
self.callout_icon_picker_block = None;
|
||||
self.callout_icon_picker_rect = None;
|
||||
self.context_menu = None;
|
||||
self.block_menu = None;
|
||||
self.context_toast = None;
|
||||
@@ -483,8 +574,18 @@ impl Overlays {
|
||||
.block_menu
|
||||
.as_ref()
|
||||
.is_some_and(|menu| menu.presence.in_flight(now_ms) || menu.presence.closing)
|
||||
|| self
|
||||
.code_lang_picker
|
||||
.as_ref()
|
||||
.is_some_and(|p| p.presence.in_flight(now_ms) || p.presence.closing)
|
||||
|| self
|
||||
.image_lightbox
|
||||
.as_ref()
|
||||
.is_some_and(|lb| lb.presence.in_flight(now_ms) || lb.presence.closing)
|
||||
}
|
||||
}
|
||||
|
||||
impl Overlays {
|
||||
/// Drop state that no longer matches the page, and finished transitions.
|
||||
pub(super) fn reconcile(&mut self, scene: &super::OverlayScene<'_>, now_ms: f64) {
|
||||
let layout = scene.layout;
|
||||
@@ -591,5 +692,19 @@ impl Overlays {
|
||||
}) {
|
||||
self.block_menu = None;
|
||||
}
|
||||
if self
|
||||
.code_lang_picker
|
||||
.as_ref()
|
||||
.is_some_and(|p| p.presence.gone(now_ms) || layout.block(&p.block_id).is_none())
|
||||
{
|
||||
self.code_lang_picker = None;
|
||||
}
|
||||
if self
|
||||
.image_lightbox
|
||||
.as_ref()
|
||||
.is_some_and(|lb| lb.presence.gone(now_ms) || layout.block(&lb.block_id).is_none())
|
||||
{
|
||||
self.image_lightbox = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
//! Fullscreen image preview Lightbox (`overlay.image_lightbox`) opened by double-clicking
|
||||
//! an `affine:image` block, with uniform aspect-preserving zoom (`25%..400%`), viewport clipping
|
||||
//! and pan, mouse-wheel zoom, caption bar, and modal key capture.
|
||||
|
||||
use blocksuite_playground_doc::read::BlockContent;
|
||||
use ui::{
|
||||
AnyElement, ClickEvent, Context, FontWeight, MouseButton, ScrollDelta, ScrollEvent,
|
||||
SharedString, div, img, prelude::*, px,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
block_flow::{FlowRect, ImageSlot},
|
||||
theme::{Palette, TYPOGRAPHY},
|
||||
};
|
||||
|
||||
use super::{
|
||||
OverlayEvent, OverlayHost, OverlayScene, Overlays, Presence, emit, icon_rotated, place,
|
||||
};
|
||||
|
||||
/// Active fullscreen image Lightbox state.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ImageLightboxState {
|
||||
pub block_id: String,
|
||||
pub zoom: f32,
|
||||
pub pan: (f32, f32),
|
||||
pub presence: Presence,
|
||||
}
|
||||
|
||||
impl Overlays {
|
||||
/// Active (non-closing) image Lightbox, if open.
|
||||
pub fn image_lightbox(&self) -> Option<&ImageLightboxState> {
|
||||
self.image_lightbox
|
||||
.as_ref()
|
||||
.filter(|lb| !lb.presence.closing)
|
||||
}
|
||||
|
||||
/// Open the fullscreen image Lightbox for `block_id` at `1.0x` zoom.
|
||||
pub fn open_image_lightbox(&mut self, block_id: String, now_ms: f64) {
|
||||
self.close_slash(now_ms);
|
||||
self.close_linked_doc(now_ms);
|
||||
self.close_link_popup(now_ms);
|
||||
self.close_context_menu(now_ms);
|
||||
self.close_block_menu(now_ms);
|
||||
let presence = match self.image_lightbox.take() {
|
||||
Some(prev) => prev.presence.reopened(now_ms),
|
||||
None => Presence::opening(now_ms),
|
||||
};
|
||||
self.image_lightbox = Some(ImageLightboxState {
|
||||
block_id,
|
||||
zoom: 1.0,
|
||||
pan: (0.0, 0.0),
|
||||
presence,
|
||||
});
|
||||
}
|
||||
|
||||
/// Adjust the Lightbox zoom factor (clamped to `[0.25, 4.0]`; `0.0` resets to `1.0` and clears pan).
|
||||
pub fn set_image_lightbox_zoom(&mut self, delta: f32) -> bool {
|
||||
let Some(lb) = self
|
||||
.image_lightbox
|
||||
.as_mut()
|
||||
.filter(|lb| !lb.presence.closing)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let next = if delta == 0.0 {
|
||||
1.0
|
||||
} else {
|
||||
(lb.zoom + delta).clamp(0.25, 4.0)
|
||||
};
|
||||
let reset_pan = delta == 0.0 || next <= 1.0;
|
||||
let changed = (next - lb.zoom).abs() > 0.001 || (reset_pan && lb.pan != (0.0, 0.0));
|
||||
lb.zoom = next;
|
||||
if reset_pan {
|
||||
lb.pan = (0.0, 0.0);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Pan the zoomed Lightbox image by `(dx, dy)` in logical px.
|
||||
pub fn pan_image_lightbox(&mut self, dx: f32, dy: f32) -> bool {
|
||||
let Some(lb) = self
|
||||
.image_lightbox
|
||||
.as_mut()
|
||||
.filter(|lb| !lb.presence.closing)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
if (dx.abs() + dy.abs()) < 0.01 {
|
||||
return false;
|
||||
}
|
||||
lb.pan.0 += dx;
|
||||
lb.pan.1 += dy;
|
||||
true
|
||||
}
|
||||
|
||||
/// Close the image Lightbox with a fade-out transition.
|
||||
pub fn close_image_lightbox(&mut self, now_ms: f64) -> bool {
|
||||
match self
|
||||
.image_lightbox
|
||||
.as_mut()
|
||||
.filter(|lb| !lb.presence.closing)
|
||||
{
|
||||
Some(lb) => {
|
||||
lb.presence.close(now_ms);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn render_image_lightbox<V: OverlayHost>(
|
||||
&mut self,
|
||||
scene: &OverlayScene<'_>,
|
||||
images: &std::collections::HashMap<String, ImageSlot>,
|
||||
palette: &Palette,
|
||||
now_ms: f64,
|
||||
cx: &mut Context<V>,
|
||||
) -> Option<AnyElement> {
|
||||
let lb_mut = self.image_lightbox.as_mut()?;
|
||||
let progress = lb_mut.presence.progress(now_ms);
|
||||
if lb_mut.presence.closing && progress <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let interactive = !lb_mut.presence.closing;
|
||||
let progress = if interactive {
|
||||
progress.max(0.01)
|
||||
} else {
|
||||
progress
|
||||
};
|
||||
let block_id = lb_mut.block_id.clone();
|
||||
let zoom = lb_mut.zoom;
|
||||
let (source_id, caption) =
|
||||
scene
|
||||
.snapshot
|
||||
.block(&block_id)
|
||||
.and_then(|n| match &n.content {
|
||||
BlockContent::Image {
|
||||
source_id, caption, ..
|
||||
} => Some((source_id.as_str(), caption.as_str())),
|
||||
_ => None,
|
||||
})?;
|
||||
let Some(ImageSlot::Ready(render_img)) = images.get(source_id) else {
|
||||
return None;
|
||||
};
|
||||
let (win_w, win_h) = scene.window;
|
||||
let touch = scene.form_factor != crate::block_flow::FormFactor::Desktop;
|
||||
let ctrl_h = if touch { 44.0 } else { 30.0 };
|
||||
let ctrl_min_w = if touch { 44.0 } else { 30.0 };
|
||||
let natural = render_img.size(0);
|
||||
let nw = (natural.width.0 as f32).max(1.0);
|
||||
let nh = (natural.height.0 as f32).max(1.0);
|
||||
let fit_max_w = (win_w - 96.0).max(120.0);
|
||||
let fit_max_h = (win_h - 140.0).max(120.0);
|
||||
let fit = (fit_max_w / nw).min(fit_max_h / nh).min(1.0);
|
||||
// Single uniform scale factor preserves exact aspect ratio across all zoom levels.
|
||||
let min_scale = 48.0 / nw.max(nh);
|
||||
let scale = (fit * zoom).max(min_scale);
|
||||
let img_w = (nw * scale).round().max(1.0);
|
||||
let img_h = (nh * scale).round().max(1.0);
|
||||
let clip_max_w = (win_w - 24.0).max(120.0);
|
||||
let clip_max_h = (win_h - 108.0).max(120.0);
|
||||
let viewport_w = img_w.min(clip_max_w).round();
|
||||
let viewport_h = img_h.min(clip_max_h).round();
|
||||
let max_pan_x = ((img_w - viewport_w).max(0.0)) * 0.5;
|
||||
let max_pan_y = ((img_h - viewport_h).max(0.0)) * 0.5;
|
||||
lb_mut.pan.0 = lb_mut.pan.0.clamp(-max_pan_x, max_pan_x);
|
||||
lb_mut.pan.1 = lb_mut.pan.1.clamp(-max_pan_y, max_pan_y);
|
||||
let (pan_x, pan_y) = lb_mut.pan;
|
||||
let img_left = ((viewport_w - img_w) * 0.5 + pan_x).round();
|
||||
let img_top = ((viewport_h - img_h) * 0.5 + pan_y).round();
|
||||
let pct_label = format!("{}%", (zoom * 100.0).round() as i32);
|
||||
|
||||
let make_ctrl = |id: &'static str,
|
||||
snap_suffix: &'static str,
|
||||
label: String,
|
||||
ev: OverlayEvent,
|
||||
cx: &mut Context<V>| {
|
||||
let mut el = div()
|
||||
.id(id)
|
||||
.flex_none()
|
||||
.min_w(px(ctrl_min_w))
|
||||
.px(px(10.0))
|
||||
.h(px(ctrl_h))
|
||||
.rounded(px(6.0))
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.text_size(px(TYPOGRAPHY.font_xs_px))
|
||||
.font_weight(FontWeight::MEDIUM)
|
||||
.text_color(palette.text_primary)
|
||||
.snapshot(
|
||||
SharedString::from(format!("overlay.image_lightbox.{snap_suffix}")),
|
||||
Some("overlay.image_lightbox"),
|
||||
)
|
||||
.snapshot_text(label.clone())
|
||||
.child(label);
|
||||
if interactive {
|
||||
let hover = palette.hover;
|
||||
el = el
|
||||
.cursor_pointer()
|
||||
.hover(move |s| s.bg(hover))
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(emit(cx, move |_: &ClickEvent| ev.clone()));
|
||||
}
|
||||
el
|
||||
};
|
||||
|
||||
let controls = div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap(px(4.0))
|
||||
.p(px(4.0))
|
||||
.rounded(px(8.0))
|
||||
.bg(palette.panel)
|
||||
.border_1()
|
||||
.border_color(palette.border)
|
||||
.shadow(palette.theme.shadows("--affine-toolbar-shadow").into())
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.child(make_ctrl(
|
||||
"lightbox-zoom-out",
|
||||
"zoom_out",
|
||||
"\u{2212}".into(),
|
||||
OverlayEvent::ImageLightboxZoom(-0.25),
|
||||
cx,
|
||||
))
|
||||
.child(make_ctrl(
|
||||
"lightbox-zoom-reset",
|
||||
"zoom_reset",
|
||||
pct_label,
|
||||
OverlayEvent::ImageLightboxZoom(0.0),
|
||||
cx,
|
||||
))
|
||||
.child(make_ctrl(
|
||||
"lightbox-zoom-in",
|
||||
"zoom_in",
|
||||
"+".into(),
|
||||
OverlayEvent::ImageLightboxZoom(0.25),
|
||||
cx,
|
||||
))
|
||||
.child(
|
||||
div()
|
||||
.id("lightbox-close")
|
||||
.flex_none()
|
||||
.w(px(ctrl_min_w))
|
||||
.h(px(ctrl_h))
|
||||
.rounded(px(6.0))
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.cursor_pointer()
|
||||
.hover({
|
||||
let hover = palette.hover;
|
||||
move |s| s.bg(hover)
|
||||
})
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(emit(cx, |_: &ClickEvent| OverlayEvent::CloseImageLightbox))
|
||||
.snapshot(
|
||||
"overlay.image_lightbox.close",
|
||||
Some("overlay.image_lightbox"),
|
||||
)
|
||||
.snapshot_text("Close")
|
||||
.child(icon_rotated(
|
||||
"PlusIcon",
|
||||
16.0,
|
||||
std::f32::consts::FRAC_PI_4,
|
||||
palette.icon,
|
||||
)),
|
||||
);
|
||||
|
||||
let image_el = div()
|
||||
.id("image-lightbox-viewport")
|
||||
.relative()
|
||||
.w(px(viewport_w))
|
||||
.h(px(viewport_h))
|
||||
.rounded(px(6.0))
|
||||
.overflow_hidden()
|
||||
.snapshot(
|
||||
"overlay.image_lightbox.viewport",
|
||||
Some("overlay.image_lightbox"),
|
||||
)
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(|_: &ClickEvent, _, cx| cx.stop_propagation())
|
||||
.child(
|
||||
div()
|
||||
.absolute()
|
||||
.left(px(img_left))
|
||||
.top(px(img_top))
|
||||
.w(px(img_w))
|
||||
.h(px(img_h))
|
||||
.snapshot(
|
||||
"overlay.image_lightbox.image",
|
||||
Some("overlay.image_lightbox.viewport"),
|
||||
)
|
||||
.child(img(render_img.clone()).w(px(img_w)).h(px(img_h))),
|
||||
);
|
||||
|
||||
let mut backdrop = place(FlowRect::new(0.0, 0.0, win_w, win_h))
|
||||
.id("image-lightbox")
|
||||
.bg(ui::hsla(0.0, 0.0, 0.0, 0.72 * progress))
|
||||
.opacity(progress)
|
||||
.flex()
|
||||
.flex_col()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.gap(px(14.0))
|
||||
.snapshot("overlay.image_lightbox", Some("root.canvas"))
|
||||
.snapshot_focused(interactive)
|
||||
.child(image_el)
|
||||
.when(!caption.is_empty(), |el| {
|
||||
el.child(
|
||||
div()
|
||||
.px(px(12.0))
|
||||
.py(px(4.0))
|
||||
.rounded(px(6.0))
|
||||
.bg(palette.panel.opacity(0.92))
|
||||
.text_size(px(TYPOGRAPHY.font_xs_px))
|
||||
.text_color(palette.text_primary)
|
||||
.child(caption.to_string()),
|
||||
)
|
||||
})
|
||||
.child(controls);
|
||||
if interactive {
|
||||
backdrop = backdrop
|
||||
.occlude()
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_scroll(cx.listener(|view: &mut V, ev: &ScrollEvent, w, cx| {
|
||||
cx.stop_propagation();
|
||||
let dy = match ev.delta {
|
||||
ScrollDelta::Pixels(p) => f32::from(p.y),
|
||||
ScrollDelta::Lines(l) => l.y * 24.0,
|
||||
};
|
||||
if dy.abs() > 0.1 {
|
||||
let step = if dy > 0.0 { 0.25 } else { -0.25 };
|
||||
view.dispatch_overlay(OverlayEvent::ImageLightboxZoom(step), w, cx);
|
||||
}
|
||||
}))
|
||||
.on_click(emit(cx, |_: &ClickEvent| OverlayEvent::CloseImageLightbox));
|
||||
}
|
||||
Some(backdrop.into_any_element())
|
||||
}
|
||||
}
|
||||
@@ -40,7 +40,7 @@ impl Overlays {
|
||||
cx: &mut Context<V>,
|
||||
) -> Option<AnyElement> {
|
||||
self.image_toolbar_rect = None;
|
||||
if scene.page_readonly {
|
||||
if scene.page_readonly || self.image_lightbox().is_some() {
|
||||
return None;
|
||||
}
|
||||
let block_id = scene.selected_image_block?;
|
||||
@@ -75,36 +75,67 @@ impl Overlays {
|
||||
})?;
|
||||
|
||||
// Buttons: Caption | AlignLeft AlignCenter AlignRight | Copy Duplicate [CardView] Delete
|
||||
let touch = scene.form_factor != crate::block_flow::FormFactor::Desktop;
|
||||
let btn_h = if touch { 44.0 } else { TOOLBAR_BUTTON };
|
||||
let btn_count = if has_blob { 8usize } else { 7usize };
|
||||
let sep_count = 2usize;
|
||||
let inner_w = btn_count as f32 * TOOLBAR_BUTTON
|
||||
+ (btn_count.saturating_sub(1 + sep_count)) as f32 * TOOLBAR_GAP
|
||||
+ sep_count as f32 * (2.0 * TOOLBAR_SEPARATOR_MARGIN + 1.0);
|
||||
let width = inner_w + 2.0 * (TOOLBAR_PADDING + POPOVER_BORDER);
|
||||
let height = TOOLBAR_BUTTON + 2.0 * (TOOLBAR_PADDING + POPOVER_BORDER);
|
||||
let vp = scene.popover_viewport();
|
||||
let max_w = (vp.w - 2.0 * POPOVER_EDGE_MARGIN).max(200.0);
|
||||
let chrome = 2.0 * (TOOLBAR_PADDING + POPOVER_BORDER);
|
||||
let sep_margin = if touch && max_w < 400.0 {
|
||||
2.0
|
||||
} else {
|
||||
TOOLBAR_SEPARATOR_MARGIN
|
||||
};
|
||||
let gap = if touch && max_w < 400.0 {
|
||||
1.0
|
||||
} else {
|
||||
TOOLBAR_GAP
|
||||
};
|
||||
let seps_w = sep_count as f32 * (2.0 * sep_margin + 1.0);
|
||||
let gaps_w = (btn_count.saturating_sub(1 + sep_count)) as f32 * gap;
|
||||
let btn_w = if touch {
|
||||
((max_w - chrome - seps_w - gaps_w) / btn_count as f32)
|
||||
.floor()
|
||||
.clamp(36.0, 44.0)
|
||||
} else {
|
||||
TOOLBAR_BUTTON
|
||||
};
|
||||
let inner_w = btn_count as f32 * btn_w + gaps_w + seps_w;
|
||||
let width = if touch { max_w } else { inner_w + chrome };
|
||||
let height = btn_h + chrome;
|
||||
let anchor_screen = scene.world_to_screen(&img_world);
|
||||
let block_screen = scene.world_to_screen(&flow_block.rect());
|
||||
let vp = scene.popover_viewport();
|
||||
let mut placed = place_popover(
|
||||
anchor_screen,
|
||||
(width, height),
|
||||
vp,
|
||||
Placement::Above,
|
||||
POPOVER_GAP,
|
||||
POPOVER_EDGE_MARGIN,
|
||||
);
|
||||
let vp_min_x = vp.x + POPOVER_EDGE_MARGIN;
|
||||
let vp_max_x = (vp.right() - POPOVER_EDGE_MARGIN - width).max(vp_min_x);
|
||||
let col_min_x = block_screen.x.clamp(vp_min_x, vp_max_x);
|
||||
let col_max_x = (block_screen.right() - width).clamp(col_min_x, vp_max_x);
|
||||
placed.rect.x = placed.rect.x.clamp(col_min_x, col_max_x);
|
||||
self.image_toolbar_rect = Some(placed.rect);
|
||||
let rect = if touch {
|
||||
crate::block_flow::FlowRect::new(
|
||||
(vp.x + (vp.w - width) * 0.5).round(),
|
||||
(vp.bottom() - height - POPOVER_EDGE_MARGIN).round(),
|
||||
width.round(),
|
||||
height.round(),
|
||||
)
|
||||
} else {
|
||||
let mut placed = place_popover(
|
||||
anchor_screen,
|
||||
(width, height),
|
||||
vp,
|
||||
Placement::Above,
|
||||
POPOVER_GAP,
|
||||
POPOVER_EDGE_MARGIN,
|
||||
);
|
||||
let vp_min_x = vp.x + POPOVER_EDGE_MARGIN;
|
||||
let vp_max_x = (vp.right() - POPOVER_EDGE_MARGIN - width).max(vp_min_x);
|
||||
let col_min_x = block_screen.x.clamp(vp_min_x, vp_max_x);
|
||||
let col_max_x = (block_screen.right() - width).clamp(col_min_x, vp_max_x);
|
||||
placed.rect.x = placed.rect.x.clamp(col_min_x, col_max_x);
|
||||
placed.rect
|
||||
};
|
||||
self.image_toolbar_rect = Some(rect);
|
||||
|
||||
let hover_bg = palette.hover;
|
||||
let sep = || {
|
||||
div()
|
||||
.flex_none()
|
||||
.mx(px(TOOLBAR_SEPARATOR_MARGIN))
|
||||
.mx(px(sep_margin))
|
||||
.w(px(1.0))
|
||||
.h(px(16.0))
|
||||
.bg(palette.divider)
|
||||
@@ -121,8 +152,8 @@ impl Overlays {
|
||||
div()
|
||||
.id(SharedString::from(format!("img-tb-{id_suffix}")))
|
||||
.flex_none()
|
||||
.w(px(TOOLBAR_BUTTON))
|
||||
.h(px(TOOLBAR_BUTTON))
|
||||
.w(px(btn_w))
|
||||
.h(px(btn_h))
|
||||
.rounded(px(4.0))
|
||||
.flex()
|
||||
.items_center()
|
||||
@@ -145,7 +176,7 @@ impl Overlays {
|
||||
.into_any_element()
|
||||
};
|
||||
|
||||
let mut row = div().flex().items_center().gap(px(TOOLBAR_GAP));
|
||||
let mut row = div().flex().items_center().gap(px(gap));
|
||||
row = row.child(make_btn(
|
||||
"caption",
|
||||
has_caption,
|
||||
@@ -214,7 +245,7 @@ impl Overlays {
|
||||
cx,
|
||||
));
|
||||
|
||||
let root = place(placed.rect)
|
||||
let root = place(rect)
|
||||
.id("image-toolbar")
|
||||
.occlude()
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
@@ -227,6 +258,7 @@ impl Overlays {
|
||||
.shadow(palette.theme.shadows("--affine-toolbar-shadow").into())
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.snapshot("overlay.image_toolbar", Some("root.canvas"))
|
||||
.child(row);
|
||||
Some(root.into_any_element())
|
||||
|
||||
@@ -13,10 +13,31 @@ use crate::{
|
||||
|
||||
use super::{
|
||||
OverlayEvent, OverlayHost, OverlayScene, Overlays, POPOVER_BORDER, POPOVER_EDGE_MARGIN,
|
||||
POPOVER_GAP, Placement, Presence, TOOLBAR_PADDING, TOOLBAR_RADIUS, emit, icon, place,
|
||||
place_popover,
|
||||
POPOVER_GAP, Placement, Presence, TOOLBAR_PADDING, TOOLBAR_RADIUS, embed_view_kind_for_url,
|
||||
emit, icon, place, place_popover,
|
||||
};
|
||||
|
||||
/// Desktop hover delay before opening the inline link / `@reference` floating capsule (ms).
|
||||
pub const LINK_HOVER_DELAY_MS: f64 = 500.0;
|
||||
|
||||
/// Compact domain + path preview for an inline URL (`https://www.affine.pro/docs/` -> `affine.pro/docs`).
|
||||
pub fn domain_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 without_www = without_scheme
|
||||
.strip_prefix("www.")
|
||||
.unwrap_or(without_scheme);
|
||||
let clean = without_www.trim_end_matches('/');
|
||||
if clean.is_empty() {
|
||||
trimmed.to_string()
|
||||
} else {
|
||||
clean.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Target inspected by the lightweight link / reference capsule.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum LinkPopupTarget {
|
||||
@@ -31,6 +52,10 @@ pub enum LinkPopupTarget {
|
||||
utf16_offset: usize,
|
||||
page_id: String,
|
||||
title: String,
|
||||
/// False when inside `affine:table` or `affine:database` (`reference/configs/toolbar.ts:220`).
|
||||
can_convert: bool,
|
||||
/// False when self-referencing, targeting a node (`params`), or inside `edgeless-text` / `embed-synced-doc`.
|
||||
can_embed: bool,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -41,14 +66,14 @@ impl LinkPopupTarget {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn display_label(&self) -> &str {
|
||||
pub fn display_label(&self) -> String {
|
||||
match self {
|
||||
Self::Link { url, .. } => url.as_str(),
|
||||
Self::Link { url, .. } => domain_preview(url),
|
||||
Self::Reference { title, .. } => {
|
||||
if title.is_empty() {
|
||||
"Untitled"
|
||||
"Untitled".to_string()
|
||||
} else {
|
||||
title.as_str()
|
||||
title.clone()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -60,8 +85,10 @@ impl LinkPopupTarget {
|
||||
pub enum LinkPopupAction {
|
||||
Open,
|
||||
Edit,
|
||||
EditAlias,
|
||||
Copy,
|
||||
ConvertToCard,
|
||||
ConvertToEmbed,
|
||||
Unlink,
|
||||
}
|
||||
|
||||
@@ -130,20 +157,48 @@ 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 is_ref = matches!(popup.target, LinkPopupTarget::Reference { .. });
|
||||
let label_text = popup.target.display_label();
|
||||
let est_label_w = (label_text.chars().count() as f32 * 7.6 + 20.0).clamp(64.0, 172.0);
|
||||
let actions_w = if is_ref {
|
||||
54.0 + 44.0 + 44.0 + 54.0 + 12.0
|
||||
} else {
|
||||
54.0 + 42.0 + 44.0 + 48.0 + 12.0
|
||||
};
|
||||
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 max_w = (viewport.w - 2.0 * POPOVER_EDGE_MARGIN).max(180.0);
|
||||
let width = raw_w.min(max_w).round();
|
||||
@@ -178,9 +233,7 @@ impl Overlays {
|
||||
}
|
||||
|
||||
/// True if `(x, y)` is inside the open link popup rect or the small hover bridge
|
||||
/// connecting it to its anchor rect (computing placement on the fly if `rect` has not yet
|
||||
/// painted its first frame). If the popup just started fading from hover and the pointer
|
||||
/// re-enters it while still visible, promotes it back to open so clicks never fall through.
|
||||
/// connecting it to its anchor rect.
|
||||
pub fn retain_or_reopen_link_popup_on_hover(
|
||||
&mut self,
|
||||
scene: &OverlayScene<'_>,
|
||||
@@ -227,7 +280,6 @@ impl Overlays {
|
||||
now_ms: f64,
|
||||
cx: &mut Context<V>,
|
||||
) -> Option<AnyElement> {
|
||||
// Suppress while format toolbar, slash menu, or text field owns the anchor.
|
||||
if self.open_toolbar().is_some()
|
||||
|| self.slash_menu().is_some()
|
||||
|| self.linked_doc_menu().is_some()
|
||||
@@ -257,30 +309,26 @@ impl Overlays {
|
||||
let btn_h = if touch { 32.0 } else { 26.0 };
|
||||
let pad = TOOLBAR_PADDING;
|
||||
let is_ref = matches!(popup.target, LinkPopupTarget::Reference { .. });
|
||||
let label_text = popup.target.display_label().to_string();
|
||||
let actions_w = if is_ref {
|
||||
54.0 + 44.0 + 44.0 + 54.0 + 12.0
|
||||
} else {
|
||||
54.0 + 42.0 + 44.0 + 48.0 + 12.0
|
||||
};
|
||||
let label_text = popup.target.display_label();
|
||||
let actions_w = Self::actions_width_for_target(&popup.target, scene.page_readonly, touch);
|
||||
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 hover = palette.hover;
|
||||
let radius = TOOLBAR_RADIUS - TOOLBAR_PADDING;
|
||||
let hover_bg = palette.hover;
|
||||
let make_btn = |id: &'static str,
|
||||
snap_suffix: &'static str,
|
||||
text: &'static str,
|
||||
w: f32,
|
||||
label: &'static str,
|
||||
btn_w: f32,
|
||||
action: LinkPopupAction,
|
||||
cx: &mut Context<V>| {
|
||||
let mut el = div()
|
||||
.id(id)
|
||||
.flex_none()
|
||||
.w(px(w))
|
||||
.w(px(btn_w))
|
||||
.h(px(btn_h))
|
||||
.rounded(px(radius))
|
||||
.rounded(px(4.0))
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
@@ -295,12 +343,12 @@ impl Overlays {
|
||||
SharedString::from(format!("overlay.link_popup.{snap_suffix}")),
|
||||
Some("overlay.link_popup"),
|
||||
)
|
||||
.snapshot_text(text)
|
||||
.child(text);
|
||||
.snapshot_text(label)
|
||||
.child(label);
|
||||
if interactive {
|
||||
el = el
|
||||
.cursor_pointer()
|
||||
.hover(move |s| s.bg(hover))
|
||||
.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)
|
||||
@@ -313,7 +361,7 @@ impl Overlays {
|
||||
.id("link-popup")
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap(px(4.0))
|
||||
.gap(px(2.0))
|
||||
.p(px(pad))
|
||||
.rounded(px(TOOLBAR_RADIUS))
|
||||
.bg(palette.panel)
|
||||
@@ -322,8 +370,8 @@ impl Overlays {
|
||||
.shadow(palette.theme.shadows("--affine-toolbar-shadow").into())
|
||||
.opacity(progress)
|
||||
.snapshot("overlay.link_popup", Some("root.canvas"))
|
||||
.snapshot_focused(interactive)
|
||||
.snapshot_text(label_text.clone());
|
||||
.snapshot_focused(interactive);
|
||||
|
||||
if interactive {
|
||||
root = root
|
||||
.occlude()
|
||||
@@ -331,25 +379,23 @@ impl Overlays {
|
||||
.on_mouse_down_out(emit(cx, |_: &MouseDownEvent| OverlayEvent::CloseLinkPopup));
|
||||
}
|
||||
|
||||
let icon_name = if is_ref { "LinkedPageIcon" } else { "LinkIcon" };
|
||||
let leading_icon = if is_ref { "LinkedPageIcon" } else { "LinkIcon" };
|
||||
root = root
|
||||
.child(
|
||||
div()
|
||||
.flex_none()
|
||||
.w(px(label_w))
|
||||
.h(px(btn_h))
|
||||
.px(px(4.0))
|
||||
.flex()
|
||||
.items_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(icon_name, 14.0, palette.icon))
|
||||
.child(icon(leading_icon, 14.0, palette.icon))
|
||||
.child(
|
||||
div()
|
||||
.flex_1()
|
||||
.min_w(px(0.0))
|
||||
.overflow_hidden()
|
||||
.whitespace_nowrap()
|
||||
.text_size(px(TYPOGRAPHY.font_xs_px))
|
||||
@@ -367,25 +413,62 @@ impl Overlays {
|
||||
cx,
|
||||
));
|
||||
|
||||
if is_ref {
|
||||
root = root
|
||||
.child(make_btn(
|
||||
"link-popup-copy",
|
||||
"copy",
|
||||
"Copy",
|
||||
44.0,
|
||||
LinkPopupAction::Copy,
|
||||
cx,
|
||||
))
|
||||
.child(make_btn(
|
||||
"link-popup-card",
|
||||
"card",
|
||||
"Card",
|
||||
44.0,
|
||||
LinkPopupAction::ConvertToCard,
|
||||
cx,
|
||||
))
|
||||
.child(make_btn(
|
||||
if scene.page_readonly {
|
||||
root = root.child(make_btn(
|
||||
"link-popup-copy",
|
||||
"copy",
|
||||
"Copy",
|
||||
42.0,
|
||||
LinkPopupAction::Copy,
|
||||
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",
|
||||
@@ -393,25 +476,46 @@ impl Overlays {
|
||||
LinkPopupAction::Unlink,
|
||||
cx,
|
||||
));
|
||||
} else {
|
||||
root = root
|
||||
.child(make_btn(
|
||||
"link-popup-edit",
|
||||
"edit",
|
||||
"Edit",
|
||||
42.0,
|
||||
LinkPopupAction::Edit,
|
||||
cx,
|
||||
))
|
||||
.child(make_btn(
|
||||
"link-popup-copy",
|
||||
"copy",
|
||||
"Copy",
|
||||
44.0,
|
||||
LinkPopupAction::Copy,
|
||||
cx,
|
||||
))
|
||||
.child(make_btn(
|
||||
}
|
||||
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",
|
||||
@@ -419,6 +523,7 @@ impl Overlays {
|
||||
LinkPopupAction::Unlink,
|
||||
cx,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Some(root.into_any_element())
|
||||
|
||||
@@ -6,13 +6,19 @@
|
||||
|
||||
mod block_menu;
|
||||
mod bookmark_prompt;
|
||||
mod bookmark_toolbar;
|
||||
mod callout_bar;
|
||||
mod code_lang_picker;
|
||||
mod context_menu;
|
||||
mod drag;
|
||||
mod embed_url;
|
||||
mod equation;
|
||||
mod helpers;
|
||||
mod image_lightbox;
|
||||
mod image_toolbar;
|
||||
mod keyboard_toolbar;
|
||||
mod link_popup;
|
||||
mod motion;
|
||||
mod paint_linked_doc;
|
||||
mod paint_page;
|
||||
mod paint_popovers;
|
||||
@@ -29,9 +35,15 @@ mod transform;
|
||||
|
||||
pub use block_menu::{BLOCK_MENU_WIDTH, BlockMenuAction, BlockMenuState};
|
||||
pub use bookmark_prompt::{BookmarkPrompt, BookmarkPromptKind};
|
||||
pub use bookmark_toolbar::{BookmarkCardStyle, BookmarkToolbarAction};
|
||||
pub use callout_bar::{CALLOUT_BG_COLORS, CALLOUT_ICON_PRESETS, CalloutAction};
|
||||
pub use code_lang_picker::{
|
||||
CODE_LANGUAGES, CodeLangPicker, display_code_language, filter_code_languages,
|
||||
};
|
||||
pub use context_menu::{
|
||||
CONTEXT_MENU_PADDING, CONTEXT_MENU_RADIUS, CONTEXT_MENU_ROW_HEIGHT, CONTEXT_MENU_WIDTH,
|
||||
CONTEXT_TOAST_MS, ContextMenuAction, ContextMenuState, ContextToast, place_context_menu,
|
||||
CONTEXT_TOAST_MS, ContextMenuAction, ContextMenuState, ContextToast, TOAST_MOTION_MS,
|
||||
place_context_menu,
|
||||
};
|
||||
pub use drag::{
|
||||
ADD_BLOCK_BUTTON_GAP, ADD_BLOCK_BUTTON_SIZE, DATABASE_HEADER_HOVER_HEIGHT,
|
||||
@@ -42,7 +54,10 @@ pub use drag::{
|
||||
resolve_marquee_selection, resolve_tree_drop_target,
|
||||
};
|
||||
use drag::{BlockDrag, DropIndicatorMotion, PageMarquee};
|
||||
pub use embed_url::{card_embed_kind_for_url, embed_view_kind_for_url};
|
||||
pub use equation::{EquationEditor, EquationTarget};
|
||||
use helpers::typed_text;
|
||||
pub use image_lightbox::ImageLightboxState;
|
||||
pub use image_toolbar::{ImageResizeSide, ImageToolbarAction};
|
||||
pub use keyboard_toolbar::{
|
||||
DEFAULT_KEYBOARD_TOOLBAR_ITEMS, HighlightColor, KEYBOARD_TOOL_PANEL_HEIGHT,
|
||||
@@ -52,11 +67,16 @@ pub use keyboard_toolbar::{
|
||||
TURN_INTO_PANEL_ITEMS, ToolPanelGroupSpec, ToolbarActionSpec, ToolbarItemSpec,
|
||||
is_flavour_supported,
|
||||
};
|
||||
pub use link_popup::{LinkPopupAction, LinkPopupState, LinkPopupTarget};
|
||||
pub use link_popup::{
|
||||
LINK_HOVER_DELAY_MS, LinkPopupAction, LinkPopupState, LinkPopupTarget, domain_preview,
|
||||
};
|
||||
pub use motion::{EaseOut, Presence, ease_out_cubic};
|
||||
pub use paint_linked_doc::{
|
||||
LinkedDocJournalItem, LinkedDocMenuState, LinkedDocRowKind, linked_doc_journal_entries,
|
||||
};
|
||||
pub use paint_page::{block_text, bounding_rect, find_parent, shared_alignment};
|
||||
pub use paint_page::{
|
||||
block_selection_visual_rects, block_text, bounding_rect, find_parent, shared_alignment,
|
||||
};
|
||||
pub use paint_popovers::{PlacedPopover, Placement, PopoverSide, place_popover};
|
||||
pub use scrollbar::{
|
||||
SCROLLBAR_EDGE_INSET, SCROLLBAR_HIT_WIDTH, SCROLLBAR_MIN_THUMB, SCROLLBAR_VERTICAL_INSET,
|
||||
@@ -73,13 +93,15 @@ pub use slash::{
|
||||
pub use table_cell::{InlineTableCell, TableAxisMenu, TableCellDragMode, TableColResizeDrag};
|
||||
pub use toolbar::LinkBar;
|
||||
pub use toolbar::{
|
||||
ActiveSelection, FormatAction, MarkState, SelectionFormat, ToolbarSubmenu, marks_in_range,
|
||||
normalize_url,
|
||||
ActiveSelection, FormatAction, FormatMoreAction, LinkEditField, MarkState, SelectionFormat,
|
||||
ToolbarSubmenu, marks_in_range, normalize_url,
|
||||
};
|
||||
pub use transform::OverlayScreenTransform;
|
||||
|
||||
pub(crate) use paint_page::align_glyph;
|
||||
use paint_page::{caret_world_rect, drag_handle_rect, emit, hover_block, icon, place, text_len};
|
||||
use paint_page::{
|
||||
caret_world_rect, drag_handle_rect, emit, hover_block, icon, icon_rotated, place, text_len,
|
||||
};
|
||||
use toolbar::{FormatToolbar, utf16_to_byte};
|
||||
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
@@ -173,95 +195,6 @@ pub(super) const COPY_BUTTON_INSET: f32 = 4.0;
|
||||
/// A pointer this close to a block's row still counts as hovering it.
|
||||
pub(super) const HOVER_SLACK: f32 = 9.0;
|
||||
|
||||
/// Ease-out cubic of a normalized time `t`.
|
||||
pub fn ease_out_cubic(t: f64) -> f64 {
|
||||
let t = t.clamp(0.0, 1.0);
|
||||
1.0 - (1.0 - t).powi(3)
|
||||
}
|
||||
|
||||
/// A scalar transition from `from` to `to` over [`OVERLAY_MOTION_MS`], eased out cubically
|
||||
/// and evaluated as a pure function of scheduler time.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct EaseOut {
|
||||
from: f64,
|
||||
to: f64,
|
||||
clock: Motion,
|
||||
}
|
||||
|
||||
impl EaseOut {
|
||||
pub fn new(from: f64, to: f64, start_ms: f64) -> Self {
|
||||
Self::with_duration(from, to, start_ms, OVERLAY_MOTION_MS)
|
||||
}
|
||||
|
||||
pub fn with_duration(from: f64, to: f64, start_ms: f64, duration_ms: f64) -> Self {
|
||||
Self {
|
||||
from,
|
||||
to,
|
||||
clock: Motion::new(0.0, 1.0, MotionCurve::Linear, start_ms, duration_ms),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn value_at(&self, now_ms: f64) -> f64 {
|
||||
if self.clock.is_finished(now_ms) {
|
||||
return self.to;
|
||||
}
|
||||
self.from + (self.to - self.from) * ease_out_cubic(self.clock.value_at(now_ms))
|
||||
}
|
||||
|
||||
pub fn is_finished(&self, now_ms: f64) -> bool {
|
||||
self.clock.is_finished(now_ms)
|
||||
}
|
||||
}
|
||||
|
||||
/// Fade of a popover: in while it opens, out once it is dismissed.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Presence {
|
||||
pub fade: EaseOut,
|
||||
pub closing: bool,
|
||||
}
|
||||
|
||||
impl Presence {
|
||||
pub fn opening(now_ms: f64) -> Self {
|
||||
Self {
|
||||
fade: EaseOut::new(0.0, 1.0, now_ms),
|
||||
closing: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Open again from wherever a fade-out got to.
|
||||
pub fn reopened(self, now_ms: f64) -> Self {
|
||||
if self.closing {
|
||||
Self {
|
||||
fade: EaseOut::new(self.fade.value_at(now_ms), 1.0, now_ms),
|
||||
closing: false,
|
||||
}
|
||||
} else {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
pub fn close(&mut self, now_ms: f64) {
|
||||
if !self.closing {
|
||||
*self = Self {
|
||||
fade: EaseOut::new(self.fade.value_at(now_ms), 0.0, now_ms),
|
||||
closing: true,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
pub fn progress(&self, now_ms: f64) -> f32 {
|
||||
self.fade.value_at(now_ms) as f32
|
||||
}
|
||||
|
||||
pub fn in_flight(&self, now_ms: f64) -> bool {
|
||||
!self.fade.is_finished(now_ms)
|
||||
}
|
||||
|
||||
pub fn gone(&self, now_ms: f64) -> bool {
|
||||
self.closing && self.fade.is_finished(now_ms)
|
||||
}
|
||||
}
|
||||
|
||||
/// A document edit an overlay asks the view for. The view carries each out through the
|
||||
/// editor's document session as one undo step.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -296,13 +229,24 @@ pub enum DocEdit {
|
||||
},
|
||||
/// Align the selected blocks.
|
||||
Align(BlockAlign),
|
||||
/// Link the text selection to a URL, or clear its link.
|
||||
/// Link the text selection to a URL, or clear its link, optionally updating display text.
|
||||
Link {
|
||||
url: Option<String>,
|
||||
/// When editing an existing uniform link, preserves peer edits outside sub-ranges still
|
||||
/// matching `expected_prev_url`.
|
||||
expected_prev_url: Option<String>,
|
||||
/// Original selected text when the dual-field `Text` + `Link` editor opened, used to
|
||||
/// abort stale display-text replacement if a peer modified or partially unlinked the span.
|
||||
expected_prev_text: Option<String>,
|
||||
/// Optional updated display text from the dual-field `Text` + `Link` editor.
|
||||
display_text: Option<String>,
|
||||
},
|
||||
/// Convert the current text selection into an inline LaTeX equation and open `EquationEditor`.
|
||||
InlineEquationFromSelection,
|
||||
/// Create a linked document from the current text selection and replace it with an `@reference`.
|
||||
CreateLinkedDocFromSelection,
|
||||
/// Execute a command from the desktop formatting toolbar's `More (...)` dropdown.
|
||||
FormatMore(FormatMoreAction),
|
||||
/// Commit a LaTeX equation string to a block or inline target.
|
||||
Equation {
|
||||
target: EquationTarget,
|
||||
@@ -316,6 +260,15 @@ pub enum DocEdit {
|
||||
},
|
||||
/// Update `prop:caption` on `block_id` as one undo step.
|
||||
SetCaption { block_id: String, caption: String },
|
||||
/// Set or clear `prop:icon` (`IconData` Map `{"type":"emoji","unicode":...}` or `Null`) on a Callout.
|
||||
SetCalloutIcon { block_id: String, unicode: String },
|
||||
/// Update custom alias (`reference.title`) on an inline `@reference` chip as one undo step.
|
||||
SetReferenceAlias {
|
||||
block_id: String,
|
||||
utf16_offset: usize,
|
||||
page_id: String,
|
||||
alias: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Something that happened to the overlays: input routed by the view, or a call of the
|
||||
@@ -358,6 +311,10 @@ pub enum OverlayEvent {
|
||||
FormatTextColor(HighlightColor),
|
||||
/// Apply or clear a background highlight color from desktop `FormatToolbar`'s `Highlight` palette.
|
||||
FormatBgColor(HighlightColor),
|
||||
/// Execute a command from desktop `FormatToolbar`'s `More (...)` dropdown.
|
||||
FormatMore(FormatMoreAction),
|
||||
/// Focus either the `Text` or `Url` input inside the dual-field `LinkBar`.
|
||||
FocusLinkField(LinkEditField),
|
||||
LinkApply,
|
||||
LinkRemove,
|
||||
/// Text pasted into the link field.
|
||||
@@ -372,6 +329,43 @@ pub enum OverlayEvent {
|
||||
block_id: String,
|
||||
language: String,
|
||||
},
|
||||
/// Open or toggle the searchable code-block language picker.
|
||||
OpenCodeLangPicker(String),
|
||||
/// Scroll the searchable code-block language picker list by `delta_rows`.
|
||||
CodeLangPickerScroll(isize),
|
||||
/// Dismiss the searchable code-block language picker.
|
||||
CloseCodeLangPicker,
|
||||
/// Toggle `prop:lineNumber` on an `affine:code` block as one undo step.
|
||||
ToggleCodeLineNumber(String),
|
||||
/// Toggle `prop:collapsed` (8-line fold) on an `affine:code` block as one undo step.
|
||||
ToggleCodeCollapsed(String),
|
||||
/// Select a single block into `block_selection` (e.g., first click on block LaTeX / Bookmark / Callout).
|
||||
SelectBlock(String),
|
||||
/// Open the fullscreen image Lightbox for `block_id`.
|
||||
OpenImageLightbox(String),
|
||||
/// Adjust image Lightbox zoom (`0.0` resets to `100%`).
|
||||
ImageLightboxZoom(f32),
|
||||
/// Pan the zoomed image inside the open Lightbox by `(dx, dy)` logical px.
|
||||
ImageLightboxPan {
|
||||
dx: f32,
|
||||
dy: f32,
|
||||
},
|
||||
/// Close the fullscreen image Lightbox.
|
||||
CloseImageLightbox,
|
||||
/// Open a Bookmark block's external URL.
|
||||
OpenBookmarkUrl(String),
|
||||
/// Execute a command from `overlay.bookmark_toolbar`.
|
||||
BookmarkToolbarAction {
|
||||
block_id: String,
|
||||
action: BookmarkToolbarAction,
|
||||
},
|
||||
/// Execute a command from `overlay.callout_toolbar` or `overlay.callout_icon_picker`.
|
||||
CalloutAction {
|
||||
block_id: String,
|
||||
action: CalloutAction,
|
||||
},
|
||||
/// Dismiss the Callout emoji/icon picker.
|
||||
CloseCalloutIconPicker,
|
||||
/// Toggle transient visual preview mode on a `mermaid`, `typst`, or `html` code block.
|
||||
ToggleCodePreview(String),
|
||||
/// Click or activate an external embed card (`Idle` -> `Selected` -> `Active`).
|
||||
@@ -587,6 +581,12 @@ pub struct OverlayScene<'a> {
|
||||
pub focused_code_block: Option<&'a str>,
|
||||
/// Single `affine:image` block currently selected in whole-block selection, if any.
|
||||
pub selected_image_block: Option<&'a str>,
|
||||
/// Single `affine:bookmark` block currently selected in whole-block selection, if any.
|
||||
pub selected_bookmark_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.
|
||||
pub selected_latex_block: Option<&'a str>,
|
||||
/// The editor's finished, formattable text selection, for frames.
|
||||
pub selection: Option<&'a SelectionFormat>,
|
||||
/// Optional camera-mapped transform when editing inside an Edgeless Note / EdgelessText.
|
||||
@@ -687,7 +687,13 @@ pub struct Overlays {
|
||||
pub(super) link_popup: Option<LinkPopupState>,
|
||||
pub(super) equation: Option<EquationEditor>,
|
||||
pub(super) bookmark: Option<BookmarkPrompt>,
|
||||
pub(super) code_lang_picker: Option<CodeLangPicker>,
|
||||
pub(super) image_lightbox: Option<ImageLightboxState>,
|
||||
pub(super) image_toolbar_rect: Option<FlowRect>,
|
||||
pub(super) bookmark_toolbar_rect: Option<FlowRect>,
|
||||
pub(super) callout_toolbar_rect: Option<FlowRect>,
|
||||
pub(super) callout_icon_picker_block: Option<String>,
|
||||
pub(super) callout_icon_picker_rect: Option<FlowRect>,
|
||||
pub(super) keyboard_toolbar: KeyboardToolbarState,
|
||||
pub(super) context_menu: Option<ContextMenuState>,
|
||||
pub(super) block_menu: Option<BlockMenuState>,
|
||||
@@ -745,46 +751,4 @@ impl Overlays {
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The slash menu, while it is open.
|
||||
pub fn slash_menu(&self) -> Option<&SlashMenu> {
|
||||
self.slash.as_ref().filter(|menu| !menu.presence.closing)
|
||||
}
|
||||
|
||||
/// Whether the formatting toolbar is open.
|
||||
pub fn format_toolbar_open(&self) -> bool {
|
||||
self.open_toolbar().is_some()
|
||||
}
|
||||
|
||||
/// Text of the toolbar's link field, while that field is open.
|
||||
pub fn link_url(&self) -> Option<&str> {
|
||||
self.link_field().map(LinkBar::url)
|
||||
}
|
||||
|
||||
/// The toolbar's link field, while it is open.
|
||||
pub fn link_field(&self) -> Option<&LinkBar> {
|
||||
self.open_toolbar()?.link.as_ref()
|
||||
}
|
||||
|
||||
pub fn link_field_mut(&mut self) -> Option<&mut LinkBar> {
|
||||
self.open_toolbar_mut()?.link.as_mut()
|
||||
}
|
||||
|
||||
/// Whichever overlay text field currently owns text input (equation, bookmark, or link).
|
||||
pub fn active_text_field(&self) -> Option<&LinkBar> {
|
||||
self.equation_editor()
|
||||
.map(|editor| &editor.input)
|
||||
.or_else(|| self.bookmark_prompt().map(|prompt| &prompt.input))
|
||||
.or_else(|| self.link_field())
|
||||
}
|
||||
|
||||
pub fn active_text_field_mut(&mut self) -> Option<&mut LinkBar> {
|
||||
if self.equation_editor().is_some() {
|
||||
return self.equation_editor_mut().map(|editor| &mut editor.input);
|
||||
}
|
||||
if self.bookmark_prompt().is_some() {
|
||||
return self.bookmark_prompt_mut().map(|prompt| &mut prompt.input);
|
||||
}
|
||||
self.link_field_mut()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
//! Pure scheduler-clock motion primitives (`EaseOut` and popover `Presence`).
|
||||
|
||||
use ui::{Motion, MotionCurve};
|
||||
|
||||
use super::OVERLAY_MOTION_MS;
|
||||
|
||||
/// Ease-out cubic of a normalized time `t`.
|
||||
pub fn ease_out_cubic(t: f64) -> f64 {
|
||||
let t = t.clamp(0.0, 1.0);
|
||||
1.0 - (1.0 - t).powi(3)
|
||||
}
|
||||
|
||||
/// A scalar transition from `from` to `to` over [`OVERLAY_MOTION_MS`], eased out cubically
|
||||
/// and evaluated as a pure function of scheduler time.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct EaseOut {
|
||||
from: f64,
|
||||
to: f64,
|
||||
clock: Motion,
|
||||
}
|
||||
|
||||
impl EaseOut {
|
||||
pub fn new(from: f64, to: f64, start_ms: f64) -> Self {
|
||||
Self::with_duration(from, to, start_ms, OVERLAY_MOTION_MS)
|
||||
}
|
||||
|
||||
pub fn with_duration(from: f64, to: f64, start_ms: f64, duration_ms: f64) -> Self {
|
||||
Self {
|
||||
from,
|
||||
to,
|
||||
clock: Motion::new(0.0, 1.0, MotionCurve::Linear, start_ms, duration_ms),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn value_at(&self, now_ms: f64) -> f64 {
|
||||
if self.clock.is_finished(now_ms) {
|
||||
return self.to;
|
||||
}
|
||||
self.from + (self.to - self.from) * ease_out_cubic(self.clock.value_at(now_ms))
|
||||
}
|
||||
|
||||
pub fn is_finished(&self, now_ms: f64) -> bool {
|
||||
self.clock.is_finished(now_ms)
|
||||
}
|
||||
}
|
||||
|
||||
/// Fade of a popover: in while it opens, out once it is dismissed.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Presence {
|
||||
pub fade: EaseOut,
|
||||
pub closing: bool,
|
||||
}
|
||||
|
||||
impl Presence {
|
||||
pub fn opening(now_ms: f64) -> Self {
|
||||
Self {
|
||||
fade: EaseOut::new(0.0, 1.0, now_ms),
|
||||
closing: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Open again from wherever a fade-out got to.
|
||||
pub fn reopened(self, now_ms: f64) -> Self {
|
||||
if self.closing {
|
||||
Self {
|
||||
fade: EaseOut::new(self.fade.value_at(now_ms), 1.0, now_ms),
|
||||
closing: false,
|
||||
}
|
||||
} else {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
pub fn close(&mut self, now_ms: f64) {
|
||||
if !self.closing {
|
||||
*self = Self {
|
||||
fade: EaseOut::new(self.fade.value_at(now_ms), 0.0, now_ms),
|
||||
closing: true,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
pub fn progress(&self, now_ms: f64) -> f32 {
|
||||
self.fade.value_at(now_ms) as f32
|
||||
}
|
||||
|
||||
pub fn in_flight(&self, now_ms: f64) -> bool {
|
||||
!self.fade.is_finished(now_ms)
|
||||
}
|
||||
|
||||
pub fn gone(&self, now_ms: f64) -> bool {
|
||||
self.closing && self.fade.is_finished(now_ms)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Interactive Page-layer controls for `affine:code` (Copy, Wrap, Preview)
|
||||
//! and `affine:embed-*` external embed cards (real block selection + external URL open).
|
||||
|
||||
use blocksuite_playground_doc::read::{BlockContent, ExternalEmbedKind, TextAlign as BlockAlign};
|
||||
use blocksuite_playground_doc::read::{BlockContent, ExternalEmbedKind};
|
||||
use ui::{
|
||||
AnyElement, ClickEvent, Context, FontWeight, Hsla, MouseButton, SharedString, prelude::*, px,
|
||||
};
|
||||
@@ -14,8 +14,8 @@ use crate::{
|
||||
};
|
||||
|
||||
use super::{
|
||||
CONTROL_HIT_SIZE, COPY_BUTTON_INSET, COPY_BUTTON_SIZE, ImageResizeSide, OverlayEvent,
|
||||
OverlayHost, OverlayScene, Overlays, emit, icon, place,
|
||||
COPY_BUTTON_INSET, COPY_BUTTON_SIZE, OverlayEvent, OverlayHost, OverlayScene, Overlays, emit,
|
||||
icon, place,
|
||||
};
|
||||
|
||||
fn check_icon_glyph(color: Hsla) -> AnyElement {
|
||||
@@ -57,32 +57,108 @@ impl Overlays {
|
||||
let copied = self.copied_block() == Some(block.block_id.as_str());
|
||||
let focused = scene.focused_code_block == Some(block.block_id.as_str());
|
||||
let touch_browse = scene.form_factor != crate::block_flow::FormFactor::Desktop;
|
||||
let (code_lang, code_wrap) = scene
|
||||
.snapshot
|
||||
.block(&block.block_id)
|
||||
.and_then(|n| match &n.content {
|
||||
BlockContent::Code { language, wrap, .. } => Some((language.as_str(), *wrap)),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or(("", false));
|
||||
let (code_lang, code_wrap, code_line_number, code_collapsed, code_line_count, has_caption) =
|
||||
scene
|
||||
.snapshot
|
||||
.block(&block.block_id)
|
||||
.and_then(|n| match &n.content {
|
||||
BlockContent::Code {
|
||||
language,
|
||||
wrap,
|
||||
text,
|
||||
caption,
|
||||
} => Some((
|
||||
language.as_str(),
|
||||
*wrap,
|
||||
n.props
|
||||
.get("prop:lineNumber")
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(!touch_browse),
|
||||
n.props
|
||||
.get("prop:collapsed")
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false),
|
||||
text.split('\n').count(),
|
||||
!caption.is_empty(),
|
||||
)),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or(("", false, !touch_browse, false, 0, false));
|
||||
let preview_kind = CodePreviewKind::from_language(code_lang)
|
||||
.filter(|k| crate::block_flow::code_preview_supported(*k));
|
||||
if !hovered && !copied && !focused && !touch_browse && preview_kind.is_none() {
|
||||
return;
|
||||
}
|
||||
let subtle = touch_browse && !hovered && !focused && !copied;
|
||||
// Fixed 28x28 button geometry: swaps CopyIcon -> CheckIcon in place so adjacent
|
||||
// Wrap / Preview buttons never shift horizontally when copied.
|
||||
// Left-top clickable language switcher button (`page.block.<id>.language`), capped on
|
||||
// narrow viewports so it never overlaps the first line of code or top-right buttons.
|
||||
let touch_hit = scene.form_factor != crate::block_flow::FormFactor::Desktop;
|
||||
if !scene.page_readonly {
|
||||
let (_, pad_x) = crate::block_flow::CODE_PADDING;
|
||||
let lang_w = (rect.w - 2.0 * pad_x).clamp(56.0, 124.0);
|
||||
let lang_h = if touch_hit { 44.0 } else { 24.0 };
|
||||
let lang_y = if touch_hit {
|
||||
(rect.y - 6.0).max(0.0)
|
||||
} else {
|
||||
rect.y + 4.0
|
||||
};
|
||||
let lang_rect = FlowRect::new(rect.x + pad_x - 4.0, lang_y, lang_w, lang_h);
|
||||
if viewport.intersects(&lang_rect) {
|
||||
let lang_ev = OverlayEvent::OpenCodeLangPicker(block.block_id.clone());
|
||||
let lang_display = super::display_code_language(code_lang);
|
||||
let mut lang_btn = place(viewport.to_local(&lang_rect))
|
||||
.id(SharedString::from(format!("code-lang-{}", block.block_id)))
|
||||
.rounded(px(4.0))
|
||||
.cursor_pointer()
|
||||
.hover(move |s| s.bg(hover_filled))
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(emit(cx, move |_: &ClickEvent| lang_ev.clone()));
|
||||
if viewport.fully_visible(&lang_rect) {
|
||||
lang_btn = lang_btn
|
||||
.snapshot(
|
||||
SharedString::from(format!("{}.language", block.snapshot_id)),
|
||||
Some(PAGE_SURFACE_ID),
|
||||
)
|
||||
.snapshot_text(lang_display);
|
||||
}
|
||||
elements.push(lang_btn.into_any_element());
|
||||
}
|
||||
}
|
||||
// Fixed 28x28 visual box inside a 44x44 touch hit target on touch hosts: swaps
|
||||
// CopyIcon -> CheckIcon in place so adjacent Wrap / Preview buttons never shift.
|
||||
let width = COPY_BUTTON_SIZE;
|
||||
let target = FlowRect::new(
|
||||
let visual_copy = FlowRect::new(
|
||||
rect.right() - COPY_BUTTON_INSET - width,
|
||||
rect.y + COPY_BUTTON_INSET,
|
||||
width,
|
||||
COPY_BUTTON_SIZE,
|
||||
);
|
||||
let hit_pad = if touch_hit { 8.0 } else { 0.0 };
|
||||
let target = FlowRect::new(
|
||||
visual_copy.x - hit_pad,
|
||||
visual_copy.y - hit_pad,
|
||||
visual_copy.w + 2.0 * hit_pad,
|
||||
visual_copy.h + 2.0 * hit_pad,
|
||||
);
|
||||
let event = OverlayEvent::CopyCode(block.block_id.clone());
|
||||
let mut element = place(viewport.to_local(&target))
|
||||
.id(SharedString::from(format!("copy-{}", block.block_id)))
|
||||
let glyph = if copied {
|
||||
check_icon_glyph(palette.brand).into_any_element()
|
||||
} else {
|
||||
icon(
|
||||
"CopyIcon",
|
||||
16.0,
|
||||
if subtle {
|
||||
palette.icon.opacity(0.55)
|
||||
} else {
|
||||
palette.icon
|
||||
},
|
||||
)
|
||||
.into_any_element()
|
||||
};
|
||||
let pill = ui::div()
|
||||
.flex_none()
|
||||
.w(px(width))
|
||||
.h(px(COPY_BUTTON_SIZE))
|
||||
.rounded(px(CODE_RADIUS - COPY_BUTTON_INSET))
|
||||
.bg(if copied {
|
||||
palette.brand.opacity(0.14)
|
||||
@@ -102,11 +178,18 @@ impl Overlays {
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.cursor_pointer()
|
||||
.hover(move |style| style.bg(hover_filled))
|
||||
.child(glyph);
|
||||
let mut element = place(viewport.to_local(&target))
|
||||
.id(SharedString::from(format!("copy-{}", block.block_id)))
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.cursor_pointer()
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(emit(cx, move |_: &ClickEvent| event.clone()));
|
||||
if viewport.fully_visible(&target) {
|
||||
.on_click(emit(cx, move |_: &ClickEvent| event.clone()))
|
||||
.child(pill);
|
||||
if viewport.fully_visible(&visual_copy) {
|
||||
element = element
|
||||
.snapshot(
|
||||
SharedString::from(format!("{}.copy", block.snapshot_id)),
|
||||
@@ -115,29 +198,24 @@ impl Overlays {
|
||||
.snapshot_focused(copied || focused)
|
||||
.snapshot_text(if copied { "Copied" } else { "Copy" });
|
||||
}
|
||||
let element = if copied {
|
||||
element.child(check_icon_glyph(palette.brand))
|
||||
} else {
|
||||
element.child(icon(
|
||||
"CopyIcon",
|
||||
16.0,
|
||||
if subtle {
|
||||
palette.icon.opacity(0.55)
|
||||
} else {
|
||||
palette.icon
|
||||
},
|
||||
))
|
||||
};
|
||||
elements.push(element.into_any_element());
|
||||
|
||||
let mut cursor_x = target.x - 4.0;
|
||||
let mut cursor_x = visual_copy.x - 4.0;
|
||||
let wrap_w = 46.0;
|
||||
if cursor_x - wrap_w >= rect.x + 96.0 {
|
||||
cursor_x -= wrap_w;
|
||||
let wrap_rect = FlowRect::new(cursor_x, target.y, wrap_w, COPY_BUTTON_SIZE);
|
||||
let wrap_hit_h = if touch_hit { 44.0 } else { COPY_BUTTON_SIZE };
|
||||
let wrap_hit_y = if touch_hit {
|
||||
visual_copy.y - 8.0
|
||||
} else {
|
||||
visual_copy.y
|
||||
};
|
||||
let wrap_rect = FlowRect::new(cursor_x, wrap_hit_y, wrap_w, wrap_hit_h);
|
||||
let wrap_ev = OverlayEvent::ToggleCodeWrap(block.block_id.clone());
|
||||
let mut wrap_el = place(viewport.to_local(&wrap_rect))
|
||||
.id(SharedString::from(format!("wrap-{}", block.block_id)))
|
||||
let wrap_pill = ui::div()
|
||||
.flex_none()
|
||||
.w(px(wrap_w))
|
||||
.h(px(COPY_BUTTON_SIZE))
|
||||
.rounded(px(CODE_RADIUS - COPY_BUTTON_INSET))
|
||||
.bg(if code_wrap {
|
||||
palette.brand.opacity(0.14)
|
||||
@@ -153,7 +231,6 @@ impl Overlays {
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.cursor_pointer()
|
||||
.hover(move |s| s.bg(hover_filled))
|
||||
.text_size(px(11.0))
|
||||
.font_weight(FontWeight::MEDIUM)
|
||||
@@ -162,10 +239,17 @@ impl Overlays {
|
||||
} else {
|
||||
palette.text_secondary
|
||||
})
|
||||
.child("Wrap");
|
||||
let mut wrap_el = place(viewport.to_local(&wrap_rect))
|
||||
.id(SharedString::from(format!("wrap-{}", block.block_id)))
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.cursor_pointer()
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(emit(cx, move |_: &ClickEvent| wrap_ev.clone()))
|
||||
.child("Wrap");
|
||||
if viewport.fully_visible(&wrap_rect) {
|
||||
.child(wrap_pill);
|
||||
if viewport.fully_visible(&visual_copy) {
|
||||
wrap_el = wrap_el
|
||||
.snapshot(
|
||||
SharedString::from(format!("{}.wrap", block.snapshot_id)),
|
||||
@@ -178,6 +262,157 @@ impl Overlays {
|
||||
cursor_x -= 4.0;
|
||||
}
|
||||
|
||||
// Desktop-only extra code controls: Line number (`#`), 8-line Collapse/Expand, Caption.
|
||||
let narrow = touch_browse || rect.w < 460.0;
|
||||
if !narrow && !scene.page_readonly {
|
||||
let ln_w = 28.0;
|
||||
if cursor_x - ln_w >= rect.x + 132.0 {
|
||||
cursor_x -= ln_w;
|
||||
let ln_rect = FlowRect::new(cursor_x, target.y, ln_w, COPY_BUTTON_SIZE);
|
||||
let ln_ev = OverlayEvent::ToggleCodeLineNumber(block.block_id.clone());
|
||||
let mut ln_el = place(viewport.to_local(&ln_rect))
|
||||
.id(SharedString::from(format!("lineno-{}", block.block_id)))
|
||||
.rounded(px(CODE_RADIUS - COPY_BUTTON_INSET))
|
||||
.bg(if code_line_number {
|
||||
palette.brand.opacity(0.14)
|
||||
} else {
|
||||
palette.background
|
||||
})
|
||||
.border_1()
|
||||
.border_color(if code_line_number {
|
||||
palette.brand
|
||||
} else {
|
||||
palette.border
|
||||
})
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.cursor_pointer()
|
||||
.hover(move |s| s.bg(hover_filled))
|
||||
.text_size(px(11.0))
|
||||
.font_weight(FontWeight::MEDIUM)
|
||||
.text_color(if code_line_number {
|
||||
palette.brand
|
||||
} else {
|
||||
palette.text_secondary
|
||||
})
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(emit(cx, move |_: &ClickEvent| ln_ev.clone()))
|
||||
.child("#");
|
||||
if viewport.fully_visible(&ln_rect) {
|
||||
ln_el = ln_el
|
||||
.snapshot(
|
||||
SharedString::from(format!("{}.line_number", block.snapshot_id)),
|
||||
Some(PAGE_SURFACE_ID),
|
||||
)
|
||||
.snapshot_focused(code_line_number)
|
||||
.snapshot_text("Line numbers");
|
||||
}
|
||||
elements.push(ln_el.into_any_element());
|
||||
cursor_x -= 4.0;
|
||||
}
|
||||
|
||||
if code_line_count > 8 || code_collapsed {
|
||||
let fold_w = 56.0;
|
||||
if cursor_x - fold_w >= rect.x + 132.0 {
|
||||
cursor_x -= fold_w;
|
||||
let fold_rect = FlowRect::new(cursor_x, target.y, fold_w, COPY_BUTTON_SIZE);
|
||||
let fold_ev = OverlayEvent::ToggleCodeCollapsed(block.block_id.clone());
|
||||
let fold_label = if code_collapsed { "Expand" } else { "Collapse" };
|
||||
let mut fold_el = place(viewport.to_local(&fold_rect))
|
||||
.id(SharedString::from(format!("fold-{}", block.block_id)))
|
||||
.rounded(px(CODE_RADIUS - COPY_BUTTON_INSET))
|
||||
.bg(if code_collapsed {
|
||||
palette.brand.opacity(0.14)
|
||||
} else {
|
||||
palette.background
|
||||
})
|
||||
.border_1()
|
||||
.border_color(if code_collapsed {
|
||||
palette.brand
|
||||
} else {
|
||||
palette.border
|
||||
})
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.cursor_pointer()
|
||||
.hover(move |s| s.bg(hover_filled))
|
||||
.text_size(px(11.0))
|
||||
.font_weight(FontWeight::MEDIUM)
|
||||
.text_color(if code_collapsed {
|
||||
palette.brand
|
||||
} else {
|
||||
palette.text_secondary
|
||||
})
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(emit(cx, move |_: &ClickEvent| fold_ev.clone()))
|
||||
.child(fold_label);
|
||||
if viewport.fully_visible(&fold_rect) {
|
||||
fold_el = fold_el
|
||||
.snapshot(
|
||||
SharedString::from(format!("{}.collapse", block.snapshot_id)),
|
||||
Some(PAGE_SURFACE_ID),
|
||||
)
|
||||
.snapshot_focused(code_collapsed)
|
||||
.snapshot_text(fold_label);
|
||||
}
|
||||
elements.push(fold_el.into_any_element());
|
||||
cursor_x -= 4.0;
|
||||
}
|
||||
}
|
||||
|
||||
let cap_w = 28.0;
|
||||
if cursor_x - cap_w >= rect.x + 132.0 {
|
||||
cursor_x -= cap_w;
|
||||
let cap_rect = FlowRect::new(cursor_x, target.y, cap_w, COPY_BUTTON_SIZE);
|
||||
let cap_ev = OverlayEvent::OpenCaptionPrompt {
|
||||
block_id: block.block_id.clone(),
|
||||
};
|
||||
let mut cap_el = place(viewport.to_local(&cap_rect))
|
||||
.id(SharedString::from(format!("code-cap-{}", block.block_id)))
|
||||
.rounded(px(CODE_RADIUS - COPY_BUTTON_INSET))
|
||||
.bg(if has_caption {
|
||||
palette.brand.opacity(0.14)
|
||||
} else {
|
||||
palette.background
|
||||
})
|
||||
.border_1()
|
||||
.border_color(if has_caption {
|
||||
palette.brand
|
||||
} else {
|
||||
palette.border
|
||||
})
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.cursor_pointer()
|
||||
.hover(move |s| s.bg(hover_filled))
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(emit(cx, move |_: &ClickEvent| cap_ev.clone()))
|
||||
.child(icon(
|
||||
"AddTextIcon",
|
||||
15.0,
|
||||
if has_caption {
|
||||
palette.brand
|
||||
} else {
|
||||
palette.icon
|
||||
},
|
||||
));
|
||||
if viewport.fully_visible(&cap_rect) {
|
||||
cap_el = cap_el
|
||||
.snapshot(
|
||||
SharedString::from(format!("{}.caption_btn", block.snapshot_id)),
|
||||
Some(PAGE_SURFACE_ID),
|
||||
)
|
||||
.snapshot_focused(has_caption)
|
||||
.snapshot_text("Caption");
|
||||
}
|
||||
elements.push(cap_el.into_any_element());
|
||||
cursor_x -= 4.0;
|
||||
}
|
||||
}
|
||||
|
||||
if preview_kind.is_some() {
|
||||
let prev_w = 56.0;
|
||||
if cursor_x - prev_w >= rect.x + 96.0 {
|
||||
@@ -314,173 +549,4 @@ impl Overlays {
|
||||
elements.push(act_btn.into_any_element());
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn push_image_controls<V: OverlayHost>(
|
||||
&self,
|
||||
block: &FlowBlock,
|
||||
rect: FlowRect,
|
||||
scene: &OverlayScene<'_>,
|
||||
viewport: PageViewport,
|
||||
palette: &Palette,
|
||||
cx: &mut Context<V>,
|
||||
elements: &mut Vec<AnyElement>,
|
||||
) {
|
||||
let Some(img_local) = block.body.image_box() else {
|
||||
return;
|
||||
};
|
||||
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();
|
||||
|
||||
if viewport.intersects(&img_world) {
|
||||
let card_rect = FlowRect::new(
|
||||
img_world.x.round(),
|
||||
img_world.y.round(),
|
||||
img_world.w.round().max(CONTROL_HIT_SIZE),
|
||||
img_world.h.round().max(CONTROL_HIT_SIZE),
|
||||
);
|
||||
let select_ev = OverlayEvent::SelectImageBlock(block.block_id.clone());
|
||||
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))
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(emit(cx, move |_: &ClickEvent| select_ev.clone()));
|
||||
if viewport.fully_visible(&card_rect) {
|
||||
card = card
|
||||
.snapshot(
|
||||
SharedString::from(format!("{}.image_card", block.snapshot_id)),
|
||||
Some(PAGE_SURFACE_ID),
|
||||
)
|
||||
.snapshot_focused(selected);
|
||||
}
|
||||
elements.push(card.into_any_element());
|
||||
}
|
||||
|
||||
if !scene.page_readonly && block.body.height > img_local.bottom() + 1.0 {
|
||||
let cap_y = (rect.y + img_local.bottom()).round();
|
||||
let cap_h = (rect.bottom() - cap_y).max(CONTROL_HIT_SIZE).round();
|
||||
let cap_rect = FlowRect::new(
|
||||
rect.x.round(),
|
||||
cap_y,
|
||||
rect.w.round().max(CONTROL_HIT_SIZE),
|
||||
cap_h,
|
||||
);
|
||||
if viewport.intersects(&cap_rect) {
|
||||
let cap_ev = OverlayEvent::OpenCaptionPrompt {
|
||||
block_id: block.block_id.clone(),
|
||||
};
|
||||
let mut cap = place(viewport.to_local(&cap_rect))
|
||||
.id(SharedString::from(format!(
|
||||
"image-caption-{}",
|
||||
block.block_id
|
||||
)))
|
||||
.cursor(ui::CursorStyle::IBeam)
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(emit(cx, move |_: &ClickEvent| cap_ev.clone()));
|
||||
if viewport.fully_visible(&cap_rect) {
|
||||
cap = cap.snapshot(
|
||||
SharedString::from(format!("{}.caption", block.snapshot_id)),
|
||||
Some(PAGE_SURFACE_ID),
|
||||
);
|
||||
}
|
||||
elements.push(cap.into_any_element());
|
||||
}
|
||||
}
|
||||
|
||||
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",
|
||||
img_world.x,
|
||||
img_world.y,
|
||||
ImageResizeSide::Left,
|
||||
ui::CursorStyle::ResizeUpLeftDownRight,
|
||||
),
|
||||
(
|
||||
"resize_ne",
|
||||
img_world.right(),
|
||||
img_world.y,
|
||||
ImageResizeSide::Right,
|
||||
ui::CursorStyle::ResizeUpRightDownLeft,
|
||||
),
|
||||
(
|
||||
"resize_sw",
|
||||
img_world.x,
|
||||
img_world.bottom(),
|
||||
ImageResizeSide::Left,
|
||||
ui::CursorStyle::ResizeUpRightDownLeft,
|
||||
),
|
||||
(
|
||||
"resize_se",
|
||||
img_world.right(),
|
||||
img_world.bottom(),
|
||||
ImageResizeSide::Right,
|
||||
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(),
|
||||
CONTROL_HIT_SIZE,
|
||||
CONTROL_HIT_SIZE,
|
||||
);
|
||||
if !viewport.intersects(&h_rect) {
|
||||
continue;
|
||||
}
|
||||
let bid = block.block_id.clone();
|
||||
let knob = ui::div()
|
||||
.flex_none()
|
||||
.w(px(10.0))
|
||||
.h(px(10.0))
|
||||
.rounded(px(5.0))
|
||||
.bg(palette.panel)
|
||||
.border_2()
|
||||
.border_color(palette.brand);
|
||||
let mut handle = place(viewport.to_local(&h_rect))
|
||||
.id(SharedString::from(format!("{suffix}-{}", block.block_id)))
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.cursor(cursor)
|
||||
.on_mouse_down(
|
||||
MouseButton::Left,
|
||||
cx.listener(move |view: &mut V, ev: &ui::MouseDownEvent, w, cx| {
|
||||
cx.stop_propagation();
|
||||
view.dispatch_overlay(
|
||||
OverlayEvent::ImageResizeStart {
|
||||
block_id: bid.clone(),
|
||||
side,
|
||||
start_x: f32::from(ev.position.x),
|
||||
},
|
||||
w,
|
||||
cx,
|
||||
);
|
||||
}),
|
||||
)
|
||||
.child(knob);
|
||||
if viewport.fully_visible(&h_rect) {
|
||||
handle = handle.snapshot(
|
||||
SharedString::from(format!("{}.{suffix}", block.snapshot_id)),
|
||||
Some(PAGE_SURFACE_ID),
|
||||
);
|
||||
}
|
||||
elements.push(handle.into_any_element());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -116,10 +116,26 @@ pub(crate) fn place(rect: FlowRect) -> Div {
|
||||
|
||||
/// A generated icon as a fixed-size element.
|
||||
pub(crate) fn icon(name: &'static str, side: f32, color: Hsla) -> impl IntoElement {
|
||||
icon_rotated(name, side, 0.0, color)
|
||||
}
|
||||
|
||||
/// A generated icon rotated clockwise by `turn` radians around its center.
|
||||
pub(crate) fn icon_rotated(
|
||||
name: &'static str,
|
||||
side: f32,
|
||||
turn: f32,
|
||||
color: Hsla,
|
||||
) -> impl IntoElement {
|
||||
let icon = IconPaint::named(name);
|
||||
canvas(
|
||||
|_, _, _| (),
|
||||
move |bounds, _, window, cx| icon.paint(bounds, color, window, cx),
|
||||
move |bounds, _, window, cx| {
|
||||
if turn.abs() > 1e-5 {
|
||||
icon.paint_rotated(bounds, color, turn, window, cx);
|
||||
} else {
|
||||
icon.paint(bounds, color, window, cx);
|
||||
}
|
||||
},
|
||||
)
|
||||
.flex_none()
|
||||
.w(px(side))
|
||||
@@ -312,3 +328,68 @@ pub fn bounding_rect(rects: &[FlowRect]) -> Option<FlowRect> {
|
||||
}
|
||||
Some(FlowRect::new(left, top, right - left, bottom - top))
|
||||
}
|
||||
|
||||
/// World-space selection highlight boxes for `block_selection`.
|
||||
///
|
||||
/// Each selected block expands to cover its currently visible nested subtree (omitting
|
||||
/// collapsed/hidden descendants not present in `layout`), matching Web
|
||||
/// `<affine-block-selection>`. Selected descendants already covered by a selected ancestor
|
||||
/// are skipped so nested highlights do not double-blend.
|
||||
pub fn block_selection_visual_rects(
|
||||
snapshot: Option<&blocksuite_playground_doc::read::PageSnapshot>,
|
||||
layout: &FlowLayout,
|
||||
selected_ids: &[String],
|
||||
) -> Vec<FlowRect> {
|
||||
if selected_ids.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let selected_set: std::collections::HashSet<&str> =
|
||||
selected_ids.iter().map(String::as_str).collect();
|
||||
let mut covered_descendants: std::collections::HashSet<&str> = std::collections::HashSet::new();
|
||||
if let Some(root) = snapshot.and_then(|s| s.root.as_ref()) {
|
||||
fn mark_descendants<'a>(
|
||||
node: &'a BlockNode,
|
||||
ancestor_selected: bool,
|
||||
selected: &std::collections::HashSet<&str>,
|
||||
covered: &mut std::collections::HashSet<&'a str>,
|
||||
) {
|
||||
if ancestor_selected {
|
||||
covered.insert(node.id.as_str());
|
||||
}
|
||||
let next_ancestor = ancestor_selected || selected.contains(node.id.as_str());
|
||||
for child in &node.children {
|
||||
mark_descendants(child, next_ancestor, selected, covered);
|
||||
}
|
||||
}
|
||||
mark_descendants(root, false, &selected_set, &mut covered_descendants);
|
||||
}
|
||||
|
||||
fn collect_visible_subtree(node: &BlockNode, layout: &FlowLayout, rects: &mut Vec<FlowRect>) {
|
||||
if let Some(block) = layout.block(&node.id) {
|
||||
rects.push(block.rect());
|
||||
}
|
||||
for child in &node.children {
|
||||
collect_visible_subtree(child, layout, rects);
|
||||
}
|
||||
}
|
||||
|
||||
let mut out = Vec::with_capacity(selected_ids.len());
|
||||
for block_id in selected_ids {
|
||||
if covered_descendants.contains(block_id.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let Some(block) = layout.block(block_id) else {
|
||||
continue;
|
||||
};
|
||||
let mut rects = vec![block.rect()];
|
||||
if let Some(node) = snapshot.and_then(|s| s.block(block_id)) {
|
||||
for child in &node.children {
|
||||
collect_visible_subtree(child, layout, &mut rects);
|
||||
}
|
||||
}
|
||||
if let Some(union) = bounding_rect(&rects) {
|
||||
out.push(union);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
//! Interactive Page-layer controls for `affine:image` (selection, double-click Lightbox,
|
||||
//! 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 ui::{AnyElement, ClickEvent, Context, MouseButton, SharedString, prelude::*, px};
|
||||
|
||||
use crate::{
|
||||
block_flow::{FlowBlock, FlowRect, PAGE_SURFACE_ID, PageViewport},
|
||||
theme::Palette,
|
||||
};
|
||||
|
||||
use super::{
|
||||
CONTROL_HIT_SIZE, ImageResizeSide, OverlayEvent, OverlayHost, OverlayScene, Overlays, emit,
|
||||
place,
|
||||
};
|
||||
|
||||
impl Overlays {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn push_image_controls<V: OverlayHost>(
|
||||
&self,
|
||||
block: &FlowBlock,
|
||||
rect: FlowRect,
|
||||
scene: &OverlayScene<'_>,
|
||||
viewport: PageViewport,
|
||||
palette: &Palette,
|
||||
cx: &mut Context<V>,
|
||||
elements: &mut Vec<AnyElement>,
|
||||
) {
|
||||
let Some(img_local) = block.body.image_box() else {
|
||||
return;
|
||||
};
|
||||
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();
|
||||
|
||||
if viewport.intersects(&img_world) {
|
||||
let card_rect = FlowRect::new(
|
||||
img_world.x.round(),
|
||||
img_world.y.round(),
|
||||
img_world.w.round().max(CONTROL_HIT_SIZE),
|
||||
img_world.h.round().max(CONTROL_HIT_SIZE),
|
||||
);
|
||||
let select_ev = OverlayEvent::SelectImageBlock(block.block_id.clone());
|
||||
let lightbox_ev = OverlayEvent::OpenImageLightbox(block.block_id.clone());
|
||||
let can_lightbox = block.body.is_resizable_image();
|
||||
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))
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(emit(cx, move |ev: &ClickEvent| {
|
||||
if ev.click_count() >= 2 && can_lightbox {
|
||||
lightbox_ev.clone()
|
||||
} else {
|
||||
select_ev.clone()
|
||||
}
|
||||
}));
|
||||
if viewport.fully_visible(&card_rect) {
|
||||
card = card
|
||||
.snapshot(
|
||||
SharedString::from(format!("{}.image_card", block.snapshot_id)),
|
||||
Some(PAGE_SURFACE_ID),
|
||||
)
|
||||
.snapshot_focused(selected);
|
||||
}
|
||||
elements.push(card.into_any_element());
|
||||
}
|
||||
|
||||
if !scene.page_readonly && block.body.height > img_local.bottom() + 1.0 {
|
||||
let cap_y = (rect.y + img_local.bottom()).round();
|
||||
let cap_h = (rect.bottom() - cap_y).max(CONTROL_HIT_SIZE).round();
|
||||
let cap_rect = FlowRect::new(
|
||||
rect.x.round(),
|
||||
cap_y,
|
||||
rect.w.round().max(CONTROL_HIT_SIZE),
|
||||
cap_h,
|
||||
);
|
||||
if viewport.intersects(&cap_rect) {
|
||||
let cap_ev = OverlayEvent::OpenCaptionPrompt {
|
||||
block_id: block.block_id.clone(),
|
||||
};
|
||||
let mut cap = place(viewport.to_local(&cap_rect))
|
||||
.id(SharedString::from(format!(
|
||||
"image-caption-{}",
|
||||
block.block_id
|
||||
)))
|
||||
.cursor(ui::CursorStyle::IBeam)
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(emit(cx, move |_: &ClickEvent| cap_ev.clone()));
|
||||
if viewport.fully_visible(&cap_rect) {
|
||||
cap = cap.snapshot(
|
||||
SharedString::from(format!("{}.caption", block.snapshot_id)),
|
||||
Some(PAGE_SURFACE_ID),
|
||||
);
|
||||
}
|
||||
elements.push(cap.into_any_element());
|
||||
}
|
||||
}
|
||||
|
||||
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",
|
||||
img_world.x,
|
||||
img_world.y,
|
||||
ImageResizeSide::Left,
|
||||
ui::CursorStyle::ResizeUpLeftDownRight,
|
||||
),
|
||||
(
|
||||
"resize_ne",
|
||||
img_world.right(),
|
||||
img_world.y,
|
||||
ImageResizeSide::Right,
|
||||
ui::CursorStyle::ResizeUpRightDownLeft,
|
||||
),
|
||||
(
|
||||
"resize_sw",
|
||||
img_world.x,
|
||||
img_world.bottom(),
|
||||
ImageResizeSide::Left,
|
||||
ui::CursorStyle::ResizeUpRightDownLeft,
|
||||
),
|
||||
(
|
||||
"resize_se",
|
||||
img_world.right(),
|
||||
img_world.bottom(),
|
||||
ImageResizeSide::Right,
|
||||
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(),
|
||||
CONTROL_HIT_SIZE,
|
||||
CONTROL_HIT_SIZE,
|
||||
);
|
||||
if !viewport.intersects(&h_rect) {
|
||||
continue;
|
||||
}
|
||||
let bid = block.block_id.clone();
|
||||
let knob = ui::div()
|
||||
.flex_none()
|
||||
.w(px(10.0))
|
||||
.h(px(10.0))
|
||||
.rounded(px(5.0))
|
||||
.bg(palette.panel)
|
||||
.border_2()
|
||||
.border_color(palette.brand);
|
||||
let mut handle = place(viewport.to_local(&h_rect))
|
||||
.id(SharedString::from(format!("{suffix}-{}", block.block_id)))
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.cursor(cursor)
|
||||
.on_mouse_down(
|
||||
MouseButton::Left,
|
||||
cx.listener(move |view: &mut V, ev: &ui::MouseDownEvent, w, cx| {
|
||||
cx.stop_propagation();
|
||||
view.dispatch_overlay(
|
||||
OverlayEvent::ImageResizeStart {
|
||||
block_id: bid.clone(),
|
||||
side,
|
||||
start_x: f32::from(ev.position.x),
|
||||
},
|
||||
w,
|
||||
cx,
|
||||
);
|
||||
}),
|
||||
)
|
||||
.child(knob);
|
||||
if viewport.fully_visible(&h_rect) {
|
||||
handle = handle.snapshot(
|
||||
SharedString::from(format!("{}.{suffix}", block.snapshot_id)),
|
||||
Some(PAGE_SURFACE_ID),
|
||||
);
|
||||
}
|
||||
elements.push(handle.into_any_element());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn push_bookmark_controls<V: OverlayHost>(
|
||||
&self,
|
||||
block: &FlowBlock,
|
||||
rect: FlowRect,
|
||||
scene: &OverlayScene<'_>,
|
||||
viewport: PageViewport,
|
||||
palette: &Palette,
|
||||
cx: &mut Context<V>,
|
||||
elements: &mut Vec<AnyElement>,
|
||||
) {
|
||||
let Some(url) = scene
|
||||
.snapshot
|
||||
.block(&block.block_id)
|
||||
.and_then(|n| match &n.content {
|
||||
BlockContent::Bookmark { url, .. } => Some(url.clone()),
|
||||
_ => None,
|
||||
})
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let selected = scene.selected_bookmark_block == Some(block.block_id.as_str());
|
||||
let select_ev = OverlayEvent::SelectBlock(block.block_id.clone());
|
||||
let open_ev = OverlayEvent::OpenBookmarkUrl(url);
|
||||
let readonly = scene.page_readonly;
|
||||
let mut card = place(viewport.to_local(&rect))
|
||||
.id(SharedString::from(format!(
|
||||
"bookmark-card-{}",
|
||||
block.block_id
|
||||
)))
|
||||
.rounded(px(8.0))
|
||||
.cursor_pointer()
|
||||
.when(selected, |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 || readonly {
|
||||
open_ev.clone()
|
||||
} else {
|
||||
select_ev.clone()
|
||||
}
|
||||
}));
|
||||
if viewport.fully_visible(&rect) {
|
||||
card = card
|
||||
.snapshot(
|
||||
SharedString::from(format!("{}.bookmark_card", block.snapshot_id)),
|
||||
Some(PAGE_SURFACE_ID),
|
||||
)
|
||||
.snapshot_focused(selected);
|
||||
}
|
||||
elements.push(card.into_any_element());
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn push_callout_controls<V: OverlayHost>(
|
||||
&self,
|
||||
block: &FlowBlock,
|
||||
rect: FlowRect,
|
||||
scene: &OverlayScene<'_>,
|
||||
viewport: PageViewport,
|
||||
palette: &Palette,
|
||||
cx: &mut Context<V>,
|
||||
elements: &mut Vec<AnyElement>,
|
||||
) {
|
||||
if scene.page_readonly {
|
||||
return;
|
||||
}
|
||||
let touch = scene.form_factor != crate::block_flow::FormFactor::Desktop;
|
||||
let icon_rect = if touch {
|
||||
FlowRect::new(rect.x, rect.y, 44.0, 44.0)
|
||||
} else {
|
||||
FlowRect::new(rect.x + 8.0, rect.y + 8.0, 28.0, 28.0)
|
||||
};
|
||||
if viewport.intersects(&icon_rect) {
|
||||
let icon_ev = OverlayEvent::CalloutAction {
|
||||
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-{}",
|
||||
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| icon_ev.clone()));
|
||||
if viewport.fully_visible(&icon_rect) {
|
||||
btn = btn.snapshot(
|
||||
SharedString::from(format!("{}.callout_icon", block.snapshot_id)),
|
||||
Some(PAGE_SURFACE_ID),
|
||||
);
|
||||
}
|
||||
elements.push(btn.into_any_element());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,16 @@
|
||||
mod controls;
|
||||
mod geometry;
|
||||
mod handle;
|
||||
mod media_controls;
|
||||
|
||||
pub(crate) use geometry::align_glyph;
|
||||
pub(super) use geometry::{
|
||||
add_block_button_rect, caret_world_rect, drag_handle_rect, emit, hover_block, icon, place,
|
||||
text_len,
|
||||
add_block_button_rect, caret_world_rect, drag_handle_rect, emit, hover_block, icon,
|
||||
icon_rotated, place, text_len,
|
||||
};
|
||||
pub use geometry::{
|
||||
block_selection_visual_rects, block_text, bounding_rect, find_parent, shared_alignment,
|
||||
};
|
||||
pub use geometry::{block_text, bounding_rect, find_parent, shared_alignment};
|
||||
|
||||
use blocksuite_playground_doc::{read::BlockContent, schema::ListType};
|
||||
use ui::{
|
||||
@@ -222,7 +225,10 @@ impl Overlays {
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let event = OverlayEvent::OpenEquationEditor {
|
||||
let already_selected =
|
||||
scene.selected_latex_block == Some(block.block_id.as_str());
|
||||
let select_ev = OverlayEvent::SelectBlock(block.block_id.clone());
|
||||
let open_ev = OverlayEvent::OpenEquationEditor {
|
||||
target: EquationTarget::Block {
|
||||
block_id: block.block_id.clone(),
|
||||
},
|
||||
@@ -235,12 +241,36 @@ impl Overlays {
|
||||
.cursor_pointer()
|
||||
.hover(move |style| style.bg(hover_bg))
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(emit(cx, move |_: &ClickEvent| event.clone()));
|
||||
.on_click(emit(cx, move |ev: &ClickEvent| {
|
||||
if already_selected || ev.click_count() >= 2 {
|
||||
open_ev.clone()
|
||||
} else {
|
||||
select_ev.clone()
|
||||
}
|
||||
}));
|
||||
if hovered {
|
||||
element = element.bg(hover_bg);
|
||||
}
|
||||
elements.push(element.into_any_element());
|
||||
}
|
||||
FlowKind::Bookmark => self.push_bookmark_controls(
|
||||
block,
|
||||
rect,
|
||||
scene,
|
||||
viewport,
|
||||
palette,
|
||||
cx,
|
||||
&mut elements,
|
||||
),
|
||||
FlowKind::Callout => self.push_callout_controls(
|
||||
block,
|
||||
rect,
|
||||
scene,
|
||||
viewport,
|
||||
palette,
|
||||
cx,
|
||||
&mut elements,
|
||||
),
|
||||
FlowKind::Table => {
|
||||
let table_cells = scene.snapshot.block(&block.block_id).and_then(|n| match &n
|
||||
.content
|
||||
@@ -413,33 +443,61 @@ impl Overlays {
|
||||
_ => {}
|
||||
}
|
||||
if let Some(body_text) = &block.body.text {
|
||||
for deco in body_text.layout.decorations() {
|
||||
if let DecorationKind::LatexChip(latex) = &deco.kind {
|
||||
let chip_rect = FlowRect::new(
|
||||
rect.x + body_text.x + f32::from(deco.bounds.origin.x),
|
||||
rect.y + body_text.y + f32::from(deco.bounds.origin.y),
|
||||
f32::from(deco.bounds.size.width),
|
||||
f32::from(deco.bounds.size.height),
|
||||
);
|
||||
if !viewport.intersects(&chip_rect) {
|
||||
continue;
|
||||
let is_desktop = scene.form_factor == crate::block_flow::FormFactor::Desktop;
|
||||
for (deco_idx, deco) in body_text.layout.decorations().iter().enumerate() {
|
||||
let chip_rect = FlowRect::new(
|
||||
rect.x + body_text.x + f32::from(deco.bounds.origin.x),
|
||||
rect.y + body_text.y + f32::from(deco.bounds.origin.y),
|
||||
f32::from(deco.bounds.size.width),
|
||||
f32::from(deco.bounds.size.height),
|
||||
);
|
||||
if !viewport.intersects(&chip_rect) {
|
||||
continue;
|
||||
}
|
||||
match &deco.kind {
|
||||
DecorationKind::LatexChip(latex) => {
|
||||
let event = OverlayEvent::OpenEquationEditor {
|
||||
target: EquationTarget::Inline {
|
||||
block_id: block.block_id.clone(),
|
||||
utf16_offset: deco.source_utf16.start,
|
||||
},
|
||||
initial: latex.clone(),
|
||||
};
|
||||
let element = place(viewport.to_local(&chip_rect))
|
||||
.id(SharedString::from(format!(
|
||||
"inline-latex-{}-{}-{deco_idx}",
|
||||
block.block_id, deco.source_utf16.start
|
||||
)))
|
||||
.cursor_pointer()
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(emit(cx, move |_: &ClickEvent| event.clone()));
|
||||
elements.push(element.into_any_element());
|
||||
}
|
||||
let event = OverlayEvent::OpenEquationEditor {
|
||||
target: EquationTarget::Inline {
|
||||
block_id: block.block_id.clone(),
|
||||
utf16_offset: deco.source_utf16.start,
|
||||
},
|
||||
initial: latex.clone(),
|
||||
};
|
||||
let element = place(viewport.to_local(&chip_rect))
|
||||
.id(SharedString::from(format!(
|
||||
"inline-latex-{}-{}",
|
||||
block.block_id, deco.source_utf16.start
|
||||
)))
|
||||
.cursor_pointer()
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(emit(cx, move |_: &ClickEvent| event.clone()));
|
||||
elements.push(element.into_any_element());
|
||||
DecorationKind::Link(_) if is_desktop => {
|
||||
let element = place(viewport.to_local(&chip_rect))
|
||||
.id(SharedString::from(format!(
|
||||
"inline-link-hover-{}-{}-{deco_idx}",
|
||||
block.block_id, deco.source_utf16.start
|
||||
)))
|
||||
.cursor_pointer();
|
||||
elements.push(element.into_any_element());
|
||||
}
|
||||
DecorationKind::ReferenceChip(_) if is_desktop => {
|
||||
let hover_bg = palette.hover;
|
||||
let border_hot = palette.icon;
|
||||
let element = place(viewport.to_local(&chip_rect))
|
||||
.id(SharedString::from(format!(
|
||||
"inline-ref-hover-{}-{}-{deco_idx}",
|
||||
block.block_id, deco.source_utf16.start
|
||||
)))
|
||||
.rounded(px(4.0))
|
||||
.cursor_pointer()
|
||||
.hover(move |s| {
|
||||
s.bg(hover_bg).border_b_1().border_color(border_hot)
|
||||
});
|
||||
elements.push(element.into_any_element());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,6 +104,9 @@ impl Overlays {
|
||||
let mut elements = Vec::new();
|
||||
elements.extend(self.render_toolbar(scene, palette, now_ms, window, cx));
|
||||
elements.extend(self.render_image_toolbar(scene, palette, cx));
|
||||
elements.extend(self.render_bookmark_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_slash(scene, palette, now_ms, cx));
|
||||
elements.extend(self.render_linked_doc(scene, palette, now_ms, cx));
|
||||
elements.extend(self.render_link_popup(scene, palette, now_ms, cx));
|
||||
@@ -112,4 +115,16 @@ impl Overlays {
|
||||
elements.extend(self.render_keyboard_toolbar(scene, palette, cx));
|
||||
elements
|
||||
}
|
||||
|
||||
/// Render the fullscreen `affine:image` Lightbox above all popovers when open.
|
||||
pub fn render_lightbox<V: OverlayHost>(
|
||||
&mut self,
|
||||
scene: &OverlayScene<'_>,
|
||||
images: &std::collections::HashMap<String, crate::block_flow::ImageSlot>,
|
||||
palette: &Palette,
|
||||
now_ms: f64,
|
||||
cx: &mut Context<V>,
|
||||
) -> Option<AnyElement> {
|
||||
self.render_image_lightbox(scene, images, palette, now_ms, cx)
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,7 @@ fn slash_context_for_scene(scene: &OverlayScene<'_>, block_id: &str) -> SlashCon
|
||||
SlashContext {
|
||||
in_edgeless_text,
|
||||
in_edgeless_canvas,
|
||||
flatten_submenus: scene.form_factor.is_touch_form_factor(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -510,11 +511,12 @@ impl Overlays {
|
||||
} else if interactive
|
||||
&& !scene.form_factor.is_touch_form_factor()
|
||||
&& now_ms - menu.hover_since_ms >= SLASH_PREVIEW_DELAY_MS
|
||||
&& let Some(selected_y) = selected_row_screen_y
|
||||
&& let Some(entry) = entries.get(selected).copied()
|
||||
&& let Some((preview_el, preview_rect)) = slash_preview::render_slash_preview_card(
|
||||
entry,
|
||||
placed.rect,
|
||||
selected_row_screen_y.unwrap_or(placed.rect.y),
|
||||
selected_y,
|
||||
viewport,
|
||||
palette,
|
||||
progress,
|
||||
@@ -727,7 +729,7 @@ impl Overlays {
|
||||
effects.slash_preview_timer = true;
|
||||
}
|
||||
}
|
||||
_ => match super::state::typed_text(keystroke, secondary) {
|
||||
_ => match super::typed_text(keystroke, secondary) {
|
||||
Some(text) => {
|
||||
menu.query.push_str(&text);
|
||||
menu.selected = 0;
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
//! Dual-field `Text` + `Link` editor rows mounted inside the desktop `FormatToolbar`.
|
||||
//!
|
||||
//! New-link mode hides `Remove`; invalid or empty URLs disable `Apply`.
|
||||
|
||||
use ui::{
|
||||
ClickEvent, Context, FontWeight, Hsla, MouseButton, SharedString, TextRun, Window, div,
|
||||
prelude::*, px,
|
||||
};
|
||||
|
||||
use crate::theme::{FONT_SANS, Palette, TYPOGRAPHY};
|
||||
|
||||
use super::{
|
||||
LINK_APPLY_WIDTH, LINK_GAP, LINK_REMOVE_WIDTH, LinkBar, LinkEditField, OverlayEvent,
|
||||
OverlayHost, POPOVER_BORDER, TOOLBAR_BUTTON, emit, normalize_url, utf16_to_byte,
|
||||
};
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn paint_input_inner(
|
||||
bar: &LinkBar,
|
||||
field_width: f32,
|
||||
placeholder: &'static str,
|
||||
focused: bool,
|
||||
palette: &Palette,
|
||||
window: &mut Window,
|
||||
) -> ui::Div {
|
||||
let text_room = (field_width - 2.0 * (8.0 + POPOVER_BORDER)).max(16.0);
|
||||
let inner_height = TOOLBAR_BUTTON - 2.0 * POPOVER_BORDER;
|
||||
let caret_height = 16.0;
|
||||
let caret_top = (inner_height - caret_height) / 2.0;
|
||||
let text = bar.text();
|
||||
let (selection, reversed) = bar.shown_selection();
|
||||
let marked = bar.marked_range();
|
||||
let mut font = ui::font(FONT_SANS);
|
||||
font.weight = FontWeight::NORMAL;
|
||||
font.fallbacks = Some(crate::default_font_fallbacks());
|
||||
let shown = SharedString::from(text.clone());
|
||||
let line = window.text_system().shape_line(
|
||||
shown.clone(),
|
||||
px(TYPOGRAPHY.font_xs_px),
|
||||
&[TextRun {
|
||||
len: shown.len(),
|
||||
font,
|
||||
color: palette.text_primary,
|
||||
background_color: None,
|
||||
underline: None,
|
||||
strikethrough: None,
|
||||
}],
|
||||
None,
|
||||
);
|
||||
let x_at = |offset: usize| f32::from(line.x_for_index(utf16_to_byte(&text, offset)));
|
||||
let text_width = f32::from(line.width());
|
||||
let caret_x = x_at(if reversed {
|
||||
selection.start
|
||||
} else {
|
||||
selection.end
|
||||
});
|
||||
let scroll = if text_width + 1.0 <= text_room {
|
||||
0.0
|
||||
} else {
|
||||
(caret_x + 1.0 - text_room)
|
||||
.clamp(0.0, text_width + 1.0 - text_room)
|
||||
.round()
|
||||
};
|
||||
let mut inner = div()
|
||||
.relative()
|
||||
.flex_none()
|
||||
.w(px(text_room))
|
||||
.h(px(inner_height))
|
||||
.overflow_hidden();
|
||||
let strip = |from: usize, to: usize, top: f32, height: f32, color: Hsla| {
|
||||
div()
|
||||
.absolute()
|
||||
.left(px((x_at(from) - scroll).round()))
|
||||
.top(px(top))
|
||||
.w(px((x_at(to) - x_at(from)).round().max(1.0)))
|
||||
.h(px(height))
|
||||
.bg(color)
|
||||
};
|
||||
if focused && marked.is_none() && !selection.is_empty() {
|
||||
inner = inner.child(strip(
|
||||
selection.start,
|
||||
selection.end,
|
||||
caret_top,
|
||||
caret_height,
|
||||
palette.brand.opacity(0.22),
|
||||
));
|
||||
}
|
||||
let caption = |left: f32, color: Hsla, content: SharedString| {
|
||||
div()
|
||||
.absolute()
|
||||
.left(px(left))
|
||||
.top(px(0.0))
|
||||
.h(px(inner_height))
|
||||
.flex()
|
||||
.items_center()
|
||||
.whitespace_nowrap()
|
||||
.text_color(color)
|
||||
.child(content)
|
||||
};
|
||||
inner = inner.child(if text.is_empty() {
|
||||
caption(1.0, palette.placeholder, placeholder.into())
|
||||
} else {
|
||||
caption(-scroll, palette.text_primary, shown)
|
||||
});
|
||||
if focused && let Some(m) = &marked {
|
||||
let (s, e) = (selection.start, selection.end);
|
||||
let ul = caret_top + caret_height;
|
||||
inner = inner.child(strip(m.start, m.end, ul - 1.0, 1.0, palette.text_secondary));
|
||||
if s < e {
|
||||
inner = inner
|
||||
.child(strip(
|
||||
s,
|
||||
e,
|
||||
caret_top,
|
||||
caret_height,
|
||||
palette.brand.opacity(0.18),
|
||||
))
|
||||
.child(strip(s, e, ul - 2.0, 2.0, palette.brand));
|
||||
}
|
||||
}
|
||||
if focused {
|
||||
inner = inner.child(
|
||||
div()
|
||||
.absolute()
|
||||
.left(px((caret_x - scroll).round()))
|
||||
.top(px(caret_top))
|
||||
.w(px(1.0))
|
||||
.h(px(caret_height))
|
||||
.bg(palette.text_primary),
|
||||
);
|
||||
}
|
||||
inner
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn render_toolbar_text_row<V: OverlayHost>(
|
||||
link_text: &LinkBar,
|
||||
inner_width: f32,
|
||||
btn_gap: f32,
|
||||
radius: f32,
|
||||
interactive: bool,
|
||||
focused: bool,
|
||||
palette: &Palette,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<V>,
|
||||
) -> ui::Div {
|
||||
let field_width = (inner_width - btn_gap).max(100.0);
|
||||
let inner = paint_input_inner(
|
||||
link_text,
|
||||
field_width,
|
||||
"Display text",
|
||||
focused,
|
||||
palette,
|
||||
window,
|
||||
);
|
||||
let mut field = div()
|
||||
.id("link_text_input")
|
||||
.flex_none()
|
||||
.w(px(field_width))
|
||||
.h(px(TOOLBAR_BUTTON))
|
||||
.px(px(8.0))
|
||||
.rounded(px(radius))
|
||||
.bg(palette.background)
|
||||
.border_1()
|
||||
.border_color(if focused {
|
||||
palette.brand
|
||||
} else {
|
||||
palette.border
|
||||
})
|
||||
.flex()
|
||||
.items_center()
|
||||
.overflow_hidden()
|
||||
.text_size(px(TYPOGRAPHY.font_xs_px))
|
||||
.snapshot(
|
||||
"overlay.format_toolbar.link_text_input",
|
||||
Some("overlay.format_toolbar"),
|
||||
)
|
||||
.snapshot_focused(focused)
|
||||
.snapshot_text(link_text.text())
|
||||
.child(inner);
|
||||
if interactive {
|
||||
field = field
|
||||
.cursor(ui::CursorStyle::IBeam)
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(emit(cx, |_: &ClickEvent| {
|
||||
OverlayEvent::FocusLinkField(LinkEditField::Text)
|
||||
}));
|
||||
}
|
||||
div()
|
||||
.flex_none()
|
||||
.w(px(inner_width))
|
||||
.h(px(TOOLBAR_BUTTON))
|
||||
.px(px(btn_gap / 2.0))
|
||||
.flex()
|
||||
.items_center()
|
||||
.child(field)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn render_toolbar_link_row<V: OverlayHost>(
|
||||
link: &LinkBar,
|
||||
inner_width: f32,
|
||||
btn_gap: f32,
|
||||
field_width: f32,
|
||||
radius: f32,
|
||||
interactive: bool,
|
||||
focused: bool,
|
||||
has_existing_link: bool,
|
||||
palette: &Palette,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<V>,
|
||||
) -> ui::Div {
|
||||
let hover = palette.hover;
|
||||
let text = link.text();
|
||||
let url_valid = !normalize_url(&text).is_empty();
|
||||
let inner = paint_input_inner(
|
||||
link,
|
||||
field_width,
|
||||
"Paste or type a link",
|
||||
focused,
|
||||
palette,
|
||||
window,
|
||||
);
|
||||
let mut field = div()
|
||||
.id("link_url_input")
|
||||
.flex_none()
|
||||
.w(px(field_width))
|
||||
.h(px(TOOLBAR_BUTTON))
|
||||
.px(px(8.0))
|
||||
.rounded(px(radius))
|
||||
.bg(palette.background)
|
||||
.border_1()
|
||||
.border_color(if focused {
|
||||
palette.brand
|
||||
} else {
|
||||
palette.border
|
||||
})
|
||||
.flex()
|
||||
.items_center()
|
||||
.overflow_hidden()
|
||||
.text_size(px(TYPOGRAPHY.font_xs_px))
|
||||
.snapshot(
|
||||
"overlay.format_toolbar.link_input",
|
||||
Some("overlay.format_toolbar"),
|
||||
)
|
||||
.snapshot_focused(focused)
|
||||
.snapshot_text(text)
|
||||
.child(inner);
|
||||
if interactive {
|
||||
field = field
|
||||
.cursor(ui::CursorStyle::IBeam)
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(emit(cx, |_: &ClickEvent| {
|
||||
OverlayEvent::FocusLinkField(LinkEditField::Url)
|
||||
}));
|
||||
}
|
||||
let label = |width: f32| {
|
||||
div()
|
||||
.flex_none()
|
||||
.w(px(width))
|
||||
.h(px(TOOLBAR_BUTTON))
|
||||
.rounded(px(radius))
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.text_size(px(TYPOGRAPHY.font_xs_px))
|
||||
.font_weight(FontWeight::MEDIUM)
|
||||
};
|
||||
let brand_hover = palette.brand.opacity(0.88);
|
||||
let mut apply = label(LINK_APPLY_WIDTH)
|
||||
.id("link_apply")
|
||||
.bg(if url_valid {
|
||||
palette.brand
|
||||
} else {
|
||||
palette.brand.opacity(0.38)
|
||||
})
|
||||
.text_color(palette.on_accent)
|
||||
.snapshot(
|
||||
"overlay.format_toolbar.link_apply",
|
||||
Some("overlay.format_toolbar"),
|
||||
)
|
||||
.snapshot_focused(url_valid)
|
||||
.snapshot_text("Apply")
|
||||
.child("Apply");
|
||||
if interactive && url_valid {
|
||||
apply = apply
|
||||
.cursor_pointer()
|
||||
.hover(move |style| style.bg(brand_hover))
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(emit(cx, |_: &ClickEvent| OverlayEvent::LinkApply));
|
||||
}
|
||||
|
||||
let mut row = div()
|
||||
.flex_none()
|
||||
.w(px(inner_width))
|
||||
.h(px(TOOLBAR_BUTTON))
|
||||
.px(px(btn_gap / 2.0))
|
||||
.flex()
|
||||
.items_center()
|
||||
.child(field.mr(px(LINK_GAP)))
|
||||
.child(apply);
|
||||
|
||||
if has_existing_link {
|
||||
let mut remove_pill = label(LINK_REMOVE_WIDTH)
|
||||
.text_color(palette.text_secondary)
|
||||
.child("Remove");
|
||||
let mut remove = div()
|
||||
.id("link_remove")
|
||||
.group("link-remove")
|
||||
.flex_none()
|
||||
.w(px(LINK_REMOVE_WIDTH + LINK_GAP))
|
||||
.h(px(TOOLBAR_BUTTON))
|
||||
.pl(px(LINK_GAP))
|
||||
.rounded(px(radius))
|
||||
.snapshot(
|
||||
"overlay.format_toolbar.link_remove",
|
||||
Some("overlay.format_toolbar"),
|
||||
)
|
||||
.snapshot_text("Remove");
|
||||
if interactive {
|
||||
remove_pill = remove_pill.group_hover("link-remove", move |style| style.bg(hover));
|
||||
remove = remove
|
||||
.cursor_pointer()
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(emit(cx, |_: &ClickEvent| OverlayEvent::LinkRemove));
|
||||
}
|
||||
row = row.child(remove.child(remove_pill));
|
||||
}
|
||||
row
|
||||
}
|
||||
+207
-216
@@ -1,19 +1,22 @@
|
||||
//! Desktop floating `FormatToolbar` painting (`overlay.format_toolbar`), including
|
||||
//! `Turn into ▾` dropdown (reusing `SLASH_ITEMS`), `Highlight` 9+9 color/background palette
|
||||
//! dropdown, and inline `LinkBar` field.
|
||||
//! dropdown, `More (...)` dropdown, and dual-field `Text` + `Link` editor.
|
||||
|
||||
mod link_fields;
|
||||
|
||||
use blocksuite_playground_doc::read::TextAlign as BlockAlign;
|
||||
use ui::{
|
||||
AnyElement, ClickEvent, Context, FontWeight, Hsla, MouseButton, SharedString, TextRun, Window,
|
||||
div, prelude::*, px,
|
||||
AnyElement, ClickEvent, Context, FontWeight, MouseButton, SharedString, Window, div,
|
||||
prelude::*, px,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
block_flow::FlowRect,
|
||||
theme::{FONT_SANS, Palette, TYPOGRAPHY},
|
||||
theme::{Palette, TYPOGRAPHY},
|
||||
};
|
||||
|
||||
use super::*;
|
||||
use link_fields::{render_toolbar_link_row, render_toolbar_text_row};
|
||||
|
||||
impl Overlays {
|
||||
pub(super) fn render_toolbar<V: OverlayHost>(
|
||||
@@ -60,25 +63,37 @@ impl Overlays {
|
||||
let align = toolbar.selection.align;
|
||||
let active_submenu = if link_only { None } else { toolbar.submenu };
|
||||
|
||||
let buttons = FormatAction::ALL.len() as f32;
|
||||
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
|
||||
// 11 buttons stay >= 24x24 and never overflow the 8px viewport margins.
|
||||
let full_sep = 2.0 * (1.0 + 2.0 * TOOLBAR_SEPARATOR_MARGIN);
|
||||
// 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 = 2.0 * (1.0 + 2.0 * sep_margin);
|
||||
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 rows = if toolbar.link.is_some() && !link_only {
|
||||
2.0
|
||||
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 {
|
||||
1.0
|
||||
0.0
|
||||
};
|
||||
let rows = if link_only {
|
||||
link_rows
|
||||
} else {
|
||||
1.0 + link_rows
|
||||
};
|
||||
let height = rows * TOOLBAR_BUTTON + (rows - 1.0) * TOOLBAR_ROW_GAP + chrome;
|
||||
let placed = place_popover(
|
||||
@@ -91,18 +106,37 @@ impl Overlays {
|
||||
);
|
||||
toolbar.rect = Some(placed.rect);
|
||||
|
||||
let has_existing_link = toolbar.link_expected_prev_url.is_some();
|
||||
let remove_span = if has_existing_link {
|
||||
LINK_REMOVE_WIDTH + LINK_GAP
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let field_width =
|
||||
inner_width - btn_gap - LINK_APPLY_WIDTH - LINK_REMOVE_WIDTH - 2.0 * LINK_GAP;
|
||||
(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
|
||||
} else {
|
||||
TOOLBAR_BUTTON + TOOLBAR_ROW_GAP
|
||||
};
|
||||
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,
|
||||
TOOLBAR_BUTTON,
|
||||
));
|
||||
}
|
||||
if let Some(link) = toolbar.link.as_mut() {
|
||||
let inset = POPOVER_BORDER + TOOLBAR_PADDING;
|
||||
let row_offset = if link_only {
|
||||
0.0
|
||||
let url_row_offset = if has_text_row {
|
||||
base_row_offset + TOOLBAR_BUTTON + TOOLBAR_ROW_GAP
|
||||
} else {
|
||||
TOOLBAR_BUTTON + TOOLBAR_ROW_GAP
|
||||
base_row_offset
|
||||
};
|
||||
link.bounds = Some(FlowRect::new(
|
||||
placed.rect.x + inset + btn_gap / 2.0,
|
||||
placed.rect.y + inset + row_offset,
|
||||
placed.rect.y + inset + url_row_offset,
|
||||
field_width,
|
||||
TOOLBAR_BUTTON,
|
||||
));
|
||||
@@ -126,8 +160,11 @@ impl Overlays {
|
||||
.h(px(TOOLBAR_BUTTON))
|
||||
.flex()
|
||||
.items_center();
|
||||
for action in FormatAction::ALL {
|
||||
if matches!(action, FormatAction::Bold | FormatAction::AlignLeft) {
|
||||
for &action in actions {
|
||||
if matches!(
|
||||
action,
|
||||
FormatAction::Bold | FormatAction::AlignLeft | FormatAction::CreateLinkedDoc
|
||||
) {
|
||||
row = row.child(
|
||||
div()
|
||||
.flex_none()
|
||||
@@ -144,6 +181,7 @@ impl Overlays {
|
||||
|| 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),
|
||||
@@ -195,6 +233,13 @@ impl Overlays {
|
||||
.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)
|
||||
@@ -245,6 +290,22 @@ impl Overlays {
|
||||
root = root.occlude();
|
||||
}
|
||||
|
||||
let active_field = toolbar.active_link_field;
|
||||
if let Some(link_text) = &toolbar.link_text
|
||||
&& toolbar.link.is_some()
|
||||
{
|
||||
root = root.child(render_toolbar_text_row(
|
||||
link_text,
|
||||
inner_width,
|
||||
btn_gap,
|
||||
radius,
|
||||
interactive,
|
||||
active_field == LinkEditField::Text,
|
||||
palette,
|
||||
window,
|
||||
cx,
|
||||
));
|
||||
}
|
||||
if let Some(link) = &toolbar.link {
|
||||
root = root.child(render_toolbar_link_row(
|
||||
link,
|
||||
@@ -253,6 +314,8 @@ impl Overlays {
|
||||
field_width,
|
||||
radius,
|
||||
interactive,
|
||||
active_field == LinkEditField::Url,
|
||||
has_existing_link,
|
||||
palette,
|
||||
window,
|
||||
cx,
|
||||
@@ -260,7 +323,7 @@ impl Overlays {
|
||||
}
|
||||
out.push(root.into_any_element());
|
||||
|
||||
// Render attached dropdown submenu (`Turn into ▾` or `Highlight` 9+9 palette).
|
||||
// Render attached dropdown submenu (`Turn into ▾`, `Highlight` 9+9 palette, or `More`).
|
||||
if let Some(submenu) = active_submenu {
|
||||
let sub_el = match submenu {
|
||||
ToolbarSubmenu::TurnInto => render_turn_into_dropdown(
|
||||
@@ -280,6 +343,9 @@ impl Overlays {
|
||||
palette,
|
||||
cx,
|
||||
),
|
||||
ToolbarSubmenu::More => {
|
||||
render_more_dropdown(placed.rect, viewport, progress, interactive, palette, cx)
|
||||
}
|
||||
};
|
||||
if let Some((sub_rect, el)) = sub_el {
|
||||
toolbar.submenu_rect = Some(sub_rect);
|
||||
@@ -290,202 +356,6 @@ impl Overlays {
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn render_toolbar_link_row<V: OverlayHost>(
|
||||
link: &LinkBar,
|
||||
inner_width: f32,
|
||||
btn_gap: f32,
|
||||
field_width: f32,
|
||||
radius: f32,
|
||||
interactive: bool,
|
||||
palette: &Palette,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<V>,
|
||||
) -> ui::Div {
|
||||
let hover = palette.hover;
|
||||
let text_room = (field_width - 2.0 * (8.0 + POPOVER_BORDER)).max(16.0);
|
||||
let inner_height = TOOLBAR_BUTTON - 2.0 * POPOVER_BORDER;
|
||||
let caret_height = 16.0;
|
||||
let caret_top = (inner_height - caret_height) / 2.0;
|
||||
let text = link.text();
|
||||
let (selection, reversed) = link.shown_selection();
|
||||
let marked = link.marked_range();
|
||||
let mut font = ui::font(FONT_SANS);
|
||||
font.weight = FontWeight::NORMAL;
|
||||
font.fallbacks = Some(crate::default_font_fallbacks());
|
||||
let shown = SharedString::from(text.clone());
|
||||
let line = window.text_system().shape_line(
|
||||
shown.clone(),
|
||||
px(TYPOGRAPHY.font_xs_px),
|
||||
&[TextRun {
|
||||
len: shown.len(),
|
||||
font,
|
||||
color: palette.text_primary,
|
||||
background_color: None,
|
||||
underline: None,
|
||||
strikethrough: None,
|
||||
}],
|
||||
None,
|
||||
);
|
||||
let x_at = |offset: usize| f32::from(line.x_for_index(utf16_to_byte(&text, offset)));
|
||||
let text_width = f32::from(line.width());
|
||||
let caret_x = x_at(if reversed {
|
||||
selection.start
|
||||
} else {
|
||||
selection.end
|
||||
});
|
||||
let scroll = if text_width + 1.0 <= text_room {
|
||||
0.0
|
||||
} else {
|
||||
(caret_x + 1.0 - text_room)
|
||||
.clamp(0.0, text_width + 1.0 - text_room)
|
||||
.round()
|
||||
};
|
||||
let mut inner = div()
|
||||
.relative()
|
||||
.flex_none()
|
||||
.w(px(text_room))
|
||||
.h(px(inner_height))
|
||||
.overflow_hidden();
|
||||
let strip = |from: usize, to: usize, top: f32, height: f32, color: Hsla| {
|
||||
div()
|
||||
.absolute()
|
||||
.left(px((x_at(from) - scroll).round()))
|
||||
.top(px(top))
|
||||
.w(px((x_at(to) - x_at(from)).round().max(1.0)))
|
||||
.h(px(height))
|
||||
.bg(color)
|
||||
};
|
||||
if marked.is_none() && !selection.is_empty() {
|
||||
inner = inner.child(strip(
|
||||
selection.start,
|
||||
selection.end,
|
||||
caret_top,
|
||||
caret_height,
|
||||
palette.brand.opacity(0.22),
|
||||
));
|
||||
}
|
||||
let caption = |left: f32, color: Hsla, text: SharedString| {
|
||||
div()
|
||||
.absolute()
|
||||
.left(px(left))
|
||||
.top(px(0.0))
|
||||
.h(px(inner_height))
|
||||
.flex()
|
||||
.items_center()
|
||||
.whitespace_nowrap()
|
||||
.text_color(color)
|
||||
.child(text)
|
||||
};
|
||||
inner = inner.child(if text.is_empty() {
|
||||
caption(1.0, palette.placeholder, "Paste or type a link".into())
|
||||
} else {
|
||||
caption(-scroll, palette.text_primary, shown)
|
||||
});
|
||||
if let Some(m) = &marked {
|
||||
let (s, e) = (selection.start, selection.end);
|
||||
let ul = caret_top + caret_height;
|
||||
inner = inner.child(strip(m.start, m.end, ul - 1.0, 1.0, palette.text_secondary));
|
||||
if s < e {
|
||||
inner = inner
|
||||
.child(strip(
|
||||
s,
|
||||
e,
|
||||
caret_top,
|
||||
caret_height,
|
||||
palette.brand.opacity(0.18),
|
||||
))
|
||||
.child(strip(s, e, ul - 2.0, 2.0, palette.brand));
|
||||
}
|
||||
}
|
||||
inner = inner.child(
|
||||
div()
|
||||
.absolute()
|
||||
.left(px((caret_x - scroll).round()))
|
||||
.top(px(caret_top))
|
||||
.w(px(1.0))
|
||||
.h(px(caret_height))
|
||||
.bg(palette.text_primary),
|
||||
);
|
||||
let field = div()
|
||||
.flex_none()
|
||||
.w(px(field_width))
|
||||
.h(px(TOOLBAR_BUTTON))
|
||||
.px(px(8.0))
|
||||
.rounded(px(radius))
|
||||
.bg(palette.background)
|
||||
.border_1()
|
||||
.border_color(palette.brand)
|
||||
.flex()
|
||||
.items_center()
|
||||
.overflow_hidden()
|
||||
.text_size(px(TYPOGRAPHY.font_xs_px))
|
||||
.snapshot(
|
||||
"overlay.format_toolbar.link_input",
|
||||
Some("overlay.format_toolbar"),
|
||||
)
|
||||
.snapshot_focused(true)
|
||||
.snapshot_text(text)
|
||||
.child(inner);
|
||||
let label = |width: f32| {
|
||||
div()
|
||||
.flex_none()
|
||||
.w(px(width))
|
||||
.h(px(TOOLBAR_BUTTON))
|
||||
.rounded(px(radius))
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.text_size(px(TYPOGRAPHY.font_xs_px))
|
||||
.font_weight(FontWeight::MEDIUM)
|
||||
};
|
||||
let mut apply = label(LINK_APPLY_WIDTH)
|
||||
.id("link_apply")
|
||||
.bg(palette.brand)
|
||||
.text_color(palette.on_accent)
|
||||
.snapshot(
|
||||
"overlay.format_toolbar.link_apply",
|
||||
Some("overlay.format_toolbar"),
|
||||
)
|
||||
.snapshot_text("Apply")
|
||||
.child("Apply");
|
||||
let mut remove_pill = label(LINK_REMOVE_WIDTH)
|
||||
.text_color(palette.text_secondary)
|
||||
.child("Remove");
|
||||
let mut remove = div()
|
||||
.id("link_remove")
|
||||
.group("link-remove")
|
||||
.flex_none()
|
||||
.w(px(LINK_REMOVE_WIDTH + LINK_GAP))
|
||||
.h(px(TOOLBAR_BUTTON))
|
||||
.pl(px(LINK_GAP))
|
||||
.rounded(px(radius))
|
||||
.snapshot(
|
||||
"overlay.format_toolbar.link_remove",
|
||||
Some("overlay.format_toolbar"),
|
||||
)
|
||||
.snapshot_text("Remove");
|
||||
if interactive {
|
||||
apply = apply
|
||||
.cursor_pointer()
|
||||
.on_click(emit(cx, |_: &ClickEvent| OverlayEvent::LinkApply));
|
||||
remove_pill = remove_pill.group_hover("link-remove", move |style| style.bg(hover));
|
||||
remove = remove
|
||||
.cursor_pointer()
|
||||
.on_click(emit(cx, |_: &ClickEvent| OverlayEvent::LinkRemove));
|
||||
}
|
||||
div()
|
||||
.flex_none()
|
||||
.w(px(inner_width))
|
||||
.h(px(TOOLBAR_BUTTON))
|
||||
.px(px(btn_gap / 2.0))
|
||||
.flex()
|
||||
.items_center()
|
||||
.child(field.mr(px(LINK_GAP)))
|
||||
.child(apply)
|
||||
.child(remove.child(remove_pill))
|
||||
}
|
||||
|
||||
fn render_turn_into_dropdown<V: OverlayHost>(
|
||||
toolbar_rect: FlowRect,
|
||||
viewport: FlowRect,
|
||||
@@ -723,3 +593,124 @@ fn render_highlight_dropdown<V: OverlayHost>(
|
||||
|
||||
Some((placed.rect, panel.into_any_element()))
|
||||
}
|
||||
|
||||
fn render_more_dropdown<V: OverlayHost>(
|
||||
toolbar_rect: FlowRect,
|
||||
viewport: FlowRect,
|
||||
progress: f32,
|
||||
interactive: bool,
|
||||
palette: &Palette,
|
||||
cx: &mut Context<V>,
|
||||
) -> 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()))
|
||||
}
|
||||
@@ -55,6 +55,8 @@ pub struct SlashContext {
|
||||
pub in_edgeless_text: bool,
|
||||
/// True when editing inside an Edgeless canvas container (Note or EdgelessText).
|
||||
pub in_edgeless_canvas: bool,
|
||||
/// True on touch form factors so `H4–H6` render flatly instead of collapsing into a submenu.
|
||||
pub flatten_submenus: bool,
|
||||
}
|
||||
|
||||
/// What a slash menu item turns the anchor block into, inserts, or executes on the block.
|
||||
@@ -255,7 +257,7 @@ pub fn slash_entries_in_context(
|
||||
can_pick_attachments,
|
||||
context,
|
||||
);
|
||||
if !query.trim().is_empty() {
|
||||
if !query.trim().is_empty() || context.flatten_submenus {
|
||||
return items.into_iter().map(SlashEntry::Item).collect();
|
||||
}
|
||||
let mut entries = Vec::with_capacity(items.len());
|
||||
|
||||
@@ -6,31 +6,6 @@ use crate::block_flow::FlowRect;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Text a keystroke types, if it types any. `secondary` is the platform's command
|
||||
/// modifier.
|
||||
pub(super) fn typed_text(keystroke: &Keystroke, secondary: bool) -> Option<String> {
|
||||
let modifiers = &keystroke.modifiers;
|
||||
if secondary || modifiers.function {
|
||||
return None;
|
||||
}
|
||||
if let Some(text) = keystroke
|
||||
.key_char
|
||||
.as_ref()
|
||||
.filter(|text| !text.is_empty() && !text.chars().any(char::is_control))
|
||||
{
|
||||
return Some(text.clone());
|
||||
}
|
||||
let mut chars = keystroke.key.chars();
|
||||
match (chars.next(), chars.next()) {
|
||||
(Some(ch), None) if !modifiers.alt => Some(if modifiers.shift {
|
||||
ch.to_uppercase().collect()
|
||||
} else {
|
||||
ch.to_string()
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl Overlays {
|
||||
pub(super) fn open_slash_mut(&mut self) -> Option<&mut SlashMenu> {
|
||||
self.slash.as_mut().filter(|menu| !menu.presence.closing)
|
||||
@@ -58,6 +33,8 @@ impl Overlays {
|
||||
self.close_link_field();
|
||||
self.close_equation_editor_at(now_ms);
|
||||
self.close_bookmark_prompt_at(now_ms);
|
||||
self.close_code_lang_picker(now_ms);
|
||||
self.callout_icon_picker_block = None;
|
||||
self.drag = None;
|
||||
self.drop_indicator_motion = None;
|
||||
self.marquee = None;
|
||||
@@ -194,6 +171,10 @@ impl Overlays {
|
||||
self.open_toolbar().and_then(|toolbar| toolbar.rect),
|
||||
self.open_toolbar().and_then(|toolbar| toolbar.submenu_rect),
|
||||
self.image_toolbar_rect,
|
||||
self.bookmark_toolbar_rect,
|
||||
self.callout_toolbar_rect,
|
||||
self.callout_icon_picker_rect,
|
||||
self.code_lang_picker().and_then(|p| p.rect),
|
||||
self.equation_editor().and_then(|editor| editor.rect),
|
||||
self.bookmark_prompt().and_then(|prompt| prompt.rect),
|
||||
self.context_menu().and_then(|menu| menu.rect),
|
||||
@@ -304,6 +285,9 @@ impl Overlays {
|
||||
});
|
||||
let utf16_offset = utf16_offset.min(text_len(scene, &block_id));
|
||||
self.open_slash(block_id, utf16_offset, anchor_world, false, now_ms);
|
||||
if let Some(menu) = self.open_slash_mut() {
|
||||
menu.context.flatten_submenus = scene.form_factor.is_touch_form_factor();
|
||||
}
|
||||
effects.slash_preview_timer = true;
|
||||
effects.redraw = true;
|
||||
}
|
||||
@@ -360,6 +344,14 @@ impl Overlays {
|
||||
});
|
||||
effects.redraw = true;
|
||||
}
|
||||
OverlayEvent::FormatMore(action) => {
|
||||
self.close_toolbar_submenu();
|
||||
effects.edits.push(DocEdit::FormatMore(action));
|
||||
effects.redraw = true;
|
||||
}
|
||||
OverlayEvent::FocusLinkField(field) => {
|
||||
effects.redraw = self.focus_link_field(field);
|
||||
}
|
||||
OverlayEvent::LinkApply => self.apply_link(false, &mut effects),
|
||||
OverlayEvent::LinkRemove => self.apply_link(true, &mut effects),
|
||||
OverlayEvent::Paste(text) => effects.redraw = self.link_insert(&text),
|
||||
@@ -458,6 +450,7 @@ impl Overlays {
|
||||
super::helpers::push_toggle_code_wrap(block_id, scene, &mut effects);
|
||||
}
|
||||
OverlayEvent::SetCodeLanguage { block_id, language } => {
|
||||
self.close_code_lang_picker(now_ms);
|
||||
effects.edits.push(DocEdit::SetProp {
|
||||
block_id,
|
||||
key: "prop:language",
|
||||
@@ -465,6 +458,19 @@ impl Overlays {
|
||||
});
|
||||
effects.redraw = true;
|
||||
}
|
||||
OverlayEvent::OpenCodeLangPicker(_)
|
||||
| OverlayEvent::CodeLangPickerScroll(_)
|
||||
| OverlayEvent::CloseCodeLangPicker
|
||||
| OverlayEvent::ToggleCodeLineNumber(_)
|
||||
| OverlayEvent::ToggleCodeCollapsed(_)
|
||||
| OverlayEvent::OpenImageLightbox(_)
|
||||
| OverlayEvent::ImageLightboxZoom(_)
|
||||
| OverlayEvent::ImageLightboxPan { .. }
|
||||
| OverlayEvent::CloseImageLightbox
|
||||
| OverlayEvent::CalloutAction { .. }
|
||||
| OverlayEvent::CloseCalloutIconPicker => {
|
||||
self.handle_code_and_media_event(&event, scene, now_ms, &mut effects);
|
||||
}
|
||||
OverlayEvent::ToggleCodePreview(_) | OverlayEvent::ExternalEmbedInteract { .. } => {}
|
||||
OverlayEvent::DragStart(block_id) => {
|
||||
self.start_drag(block_id, Vec::new(), now_ms);
|
||||
@@ -569,6 +575,9 @@ impl Overlays {
|
||||
| OverlayEvent::InsertImageBytes { .. }
|
||||
| OverlayEvent::InsertAttachmentBytes { .. }
|
||||
| OverlayEvent::SelectImageBlock(_)
|
||||
| OverlayEvent::SelectBlock(_)
|
||||
| OverlayEvent::OpenBookmarkUrl(_)
|
||||
| OverlayEvent::BookmarkToolbarAction { .. }
|
||||
| OverlayEvent::ImageResizeStart { .. }
|
||||
| OverlayEvent::ImageToolbarAction { .. }
|
||||
| OverlayEvent::FocusTableCell { .. }
|
||||
@@ -639,16 +648,40 @@ impl Overlays {
|
||||
return effects;
|
||||
}
|
||||
|
||||
if self.image_lightbox().is_some() {
|
||||
match key {
|
||||
"escape" => effects.redraw = self.close_image_lightbox(now_ms),
|
||||
"+" | "=" => effects.redraw = self.set_image_lightbox_zoom(0.25),
|
||||
"-" | "_" => effects.redraw = self.set_image_lightbox_zoom(-0.25),
|
||||
"0" => effects.redraw = self.set_image_lightbox_zoom(0.0),
|
||||
_ => {}
|
||||
}
|
||||
effects.handled = true;
|
||||
return effects;
|
||||
}
|
||||
if key == "escape" && self.close_callout_icon_picker() {
|
||||
effects.handled = true;
|
||||
effects.redraw = true;
|
||||
return effects;
|
||||
}
|
||||
if self.code_lang_picker().is_some()
|
||||
&& self.handle_code_lang_picker_key(key, now_ms, &mut effects)
|
||||
{
|
||||
return effects;
|
||||
}
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum ActiveFieldKind {
|
||||
Equation,
|
||||
Bookmark,
|
||||
CodeLang,
|
||||
Link,
|
||||
}
|
||||
let active_kind = if self.equation_editor().is_some() {
|
||||
Some(ActiveFieldKind::Equation)
|
||||
} else if self.bookmark_prompt().is_some() {
|
||||
Some(ActiveFieldKind::Bookmark)
|
||||
} else if self.code_lang_picker().is_some() {
|
||||
Some(ActiveFieldKind::CodeLang)
|
||||
} else if self.link_field().is_some() {
|
||||
Some(ActiveFieldKind::Link)
|
||||
} else {
|
||||
@@ -679,8 +712,20 @@ impl Overlays {
|
||||
}
|
||||
}
|
||||
ActiveFieldKind::Bookmark => self.apply_bookmark(now_ms, &mut effects),
|
||||
ActiveFieldKind::CodeLang => {}
|
||||
ActiveFieldKind::Link => self.apply_link(false, &mut effects),
|
||||
},
|
||||
"tab" if field_kind == ActiveFieldKind::Link && !secondary => {
|
||||
let next = if self
|
||||
.open_toolbar()
|
||||
.is_some_and(|t| t.active_link_field == LinkEditField::Text)
|
||||
{
|
||||
LinkEditField::Url
|
||||
} else {
|
||||
LinkEditField::Text
|
||||
};
|
||||
self.focus_link_field(next);
|
||||
}
|
||||
"up" | "down" if field_kind == ActiveFieldKind::Equation && !secondary => {
|
||||
if let Some(editor) = self.equation_editor_mut() {
|
||||
editor.move_vertical_line(key == "down", shift);
|
||||
@@ -688,14 +733,15 @@ impl Overlays {
|
||||
}
|
||||
"escape" => match field_kind {
|
||||
ActiveFieldKind::Equation => {
|
||||
self.close_equation_editor_at(now_ms);
|
||||
let _ = self.close_equation_editor_at(now_ms);
|
||||
}
|
||||
ActiveFieldKind::Bookmark => {
|
||||
self.close_bookmark_prompt_at(now_ms);
|
||||
let _ = self.close_bookmark_prompt_at(now_ms);
|
||||
}
|
||||
ActiveFieldKind::Link => {
|
||||
self.close_link_field();
|
||||
ActiveFieldKind::CodeLang => {
|
||||
let _ = self.close_code_lang_picker(now_ms);
|
||||
}
|
||||
ActiveFieldKind::Link => self.close_link_field(),
|
||||
},
|
||||
"v" if secondary => effects.paste = true,
|
||||
"c" | "x" if secondary => {
|
||||
|
||||
@@ -16,16 +16,53 @@ pub enum FormatAction {
|
||||
Underline,
|
||||
Strike,
|
||||
Code,
|
||||
InlineEquation,
|
||||
Highlight,
|
||||
Link,
|
||||
AlignLeft,
|
||||
AlignCenter,
|
||||
AlignRight,
|
||||
CreateLinkedDoc,
|
||||
More,
|
||||
}
|
||||
|
||||
/// Command inside the desktop formatting toolbar's `More (...)` dropdown.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum FormatMoreAction {
|
||||
Copy,
|
||||
Duplicate,
|
||||
Delete,
|
||||
}
|
||||
|
||||
/// Active input field inside the formatting toolbar's dual-field `Text` + `Link` editor.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub enum LinkEditField {
|
||||
Text,
|
||||
#[default]
|
||||
Url,
|
||||
}
|
||||
|
||||
impl FormatAction {
|
||||
/// Toolbar buttons in order; separators sit after `TurnInto` and before the alignment group.
|
||||
pub const ALL: [Self; 11] = [
|
||||
/// Full desktop toolbar buttons in order.
|
||||
pub const ALL: [Self; 14] = [
|
||||
Self::TurnInto,
|
||||
Self::Bold,
|
||||
Self::Italic,
|
||||
Self::Underline,
|
||||
Self::Strike,
|
||||
Self::Code,
|
||||
Self::InlineEquation,
|
||||
Self::Highlight,
|
||||
Self::Link,
|
||||
Self::AlignLeft,
|
||||
Self::AlignCenter,
|
||||
Self::AlignRight,
|
||||
Self::CreateLinkedDoc,
|
||||
Self::More,
|
||||
];
|
||||
|
||||
/// Compact 11-button subset for narrow (`< 460 px`) viewports so every button stays `>= 24 px`.
|
||||
pub const COMPACT: [Self; 11] = [
|
||||
Self::TurnInto,
|
||||
Self::Bold,
|
||||
Self::Italic,
|
||||
@@ -48,11 +85,14 @@ impl FormatAction {
|
||||
Self::Underline => "underline",
|
||||
Self::Strike => "strike",
|
||||
Self::Code => "code",
|
||||
Self::InlineEquation => "inline_equation",
|
||||
Self::Highlight => "highlight",
|
||||
Self::Link => "link",
|
||||
Self::AlignLeft => "align_left",
|
||||
Self::AlignCenter => "align_center",
|
||||
Self::AlignRight => "align_right",
|
||||
Self::CreateLinkedDoc => "create_linked_doc",
|
||||
Self::More => "more",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,11 +104,14 @@ impl FormatAction {
|
||||
Self::Underline => "Underline",
|
||||
Self::Strike => "Strikethrough",
|
||||
Self::Code => "Inline Code",
|
||||
Self::InlineEquation => "Inline Equation",
|
||||
Self::Highlight => "Highlight",
|
||||
Self::Link => "Link",
|
||||
Self::AlignLeft => "Align Left",
|
||||
Self::AlignCenter => "Align Center",
|
||||
Self::AlignRight => "Align Right",
|
||||
Self::CreateLinkedDoc => "Create Linked Doc",
|
||||
Self::More => "More",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,9 +123,12 @@ impl FormatAction {
|
||||
Self::Underline => Some("UnderLineIcon"),
|
||||
Self::Strike => Some("StrikeThroughIcon"),
|
||||
Self::Code => Some("CodeIcon"),
|
||||
Self::InlineEquation => None,
|
||||
Self::Highlight => None,
|
||||
Self::Link => Some("LinkIcon"),
|
||||
Self::AlignLeft | Self::AlignCenter | Self::AlignRight => None,
|
||||
Self::CreateLinkedDoc => Some("LinkedPageIcon"),
|
||||
Self::More => Some("MoreHorizontalIcon"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,6 +159,7 @@ impl FormatAction {
|
||||
pub enum ToolbarSubmenu {
|
||||
TurnInto,
|
||||
Highlight,
|
||||
More,
|
||||
}
|
||||
|
||||
/// Marks carried by every unit of a text range.
|
||||
@@ -245,6 +292,8 @@ pub struct SelectionFormat {
|
||||
pub marks: MarkState,
|
||||
/// Alignment the selected blocks share, `None` when they differ.
|
||||
pub align: Option<BlockAlign>,
|
||||
/// Selected plain text for single-block inline selections (seeds the `Text` field in LinkBar).
|
||||
pub selected_text: Option<String>,
|
||||
}
|
||||
|
||||
pub(super) use crate::inline_input::{Utf16ImeBuffer, utf16_to_byte};
|
||||
@@ -352,6 +401,12 @@ pub(super) struct FormatToolbar {
|
||||
/// What the selection last reported; kept while the toolbar fades out.
|
||||
pub(super) selection: SelectionFormat,
|
||||
pub(super) link: Option<LinkBar>,
|
||||
/// Optional display-text field paired with `link` for dual-field `Text` + `Link` editing.
|
||||
pub(super) link_text: Option<LinkBar>,
|
||||
/// Original display text when `link_text` was opened, to skip no-op text replacement.
|
||||
pub(super) link_initial_text: Option<String>,
|
||||
/// Which field (`Text` vs `Url`) currently owns keyboard/IME input.
|
||||
pub(super) active_link_field: LinkEditField,
|
||||
/// Original URL when `link` was opened on text carrying a uniform link, so `apply_link`
|
||||
/// preserves concurrent collaborator link edits outside sub-ranges still matching it.
|
||||
pub(super) link_expected_prev_url: Option<String>,
|
||||
@@ -433,6 +488,9 @@ impl Overlays {
|
||||
pub fn close_link_field(&mut self) {
|
||||
if let Some(toolbar) = self.toolbar.as_mut() {
|
||||
toolbar.link = None;
|
||||
toolbar.link_text = None;
|
||||
toolbar.link_initial_text = None;
|
||||
toolbar.active_link_field = LinkEditField::Url;
|
||||
toolbar.link_expected_prev_url = None;
|
||||
toolbar.standalone_link_block_id = None;
|
||||
toolbar.submenu = None;
|
||||
@@ -440,6 +498,27 @@ impl Overlays {
|
||||
}
|
||||
}
|
||||
|
||||
/// Switch keyboard/IME focus between the `Text` and `Url` fields of the open dual-field LinkBar.
|
||||
pub fn focus_link_field(&mut self, field: LinkEditField) -> bool {
|
||||
let Some(toolbar) = self.open_toolbar_mut() else {
|
||||
return false;
|
||||
};
|
||||
if toolbar.link.is_none() {
|
||||
return false;
|
||||
}
|
||||
let target = if field == LinkEditField::Text && toolbar.link_text.is_some() {
|
||||
LinkEditField::Text
|
||||
} else {
|
||||
LinkEditField::Url
|
||||
};
|
||||
if toolbar.active_link_field != target {
|
||||
toolbar.active_link_field = target;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Block ID of a standalone `LinkBar` opened on a non-toolbar block (such as `prop:title`).
|
||||
pub fn standalone_link_block_id(&self) -> Option<&str> {
|
||||
let toolbar = self.open_toolbar()?;
|
||||
@@ -465,6 +544,8 @@ impl Overlays {
|
||||
self.close_slash(now_ms);
|
||||
let init_url = selection.marks.link.clone().unwrap_or_default();
|
||||
let expected_prev = (!init_url.is_empty()).then(|| init_url.clone());
|
||||
let init_text = selection.selected_text.clone();
|
||||
let link_text_bar = init_text.clone().map(LinkBar::new);
|
||||
match self.toolbar.as_mut() {
|
||||
Some(toolbar) => {
|
||||
toolbar.selection = selection.clone();
|
||||
@@ -473,6 +554,9 @@ impl Overlays {
|
||||
toolbar.submenu_rect = None;
|
||||
if toolbar.link.is_none() {
|
||||
toolbar.link = Some(LinkBar::new(init_url));
|
||||
toolbar.link_text = link_text_bar;
|
||||
toolbar.link_initial_text = init_text;
|
||||
toolbar.active_link_field = LinkEditField::Url;
|
||||
toolbar.link_expected_prev_url = expected_prev;
|
||||
toolbar.standalone_link_block_id = None;
|
||||
}
|
||||
@@ -481,6 +565,9 @@ impl Overlays {
|
||||
self.toolbar = Some(FormatToolbar {
|
||||
selection: selection.clone(),
|
||||
link: Some(LinkBar::new(init_url)),
|
||||
link_text: link_text_bar,
|
||||
link_initial_text: init_text,
|
||||
active_link_field: LinkEditField::Url,
|
||||
link_expected_prev_url: expected_prev,
|
||||
standalone_link_block_id: None,
|
||||
submenu: None,
|
||||
@@ -519,6 +606,9 @@ impl Overlays {
|
||||
self.toolbar = Some(FormatToolbar {
|
||||
selection: selection.clone(),
|
||||
link: None,
|
||||
link_text: None,
|
||||
link_initial_text: None,
|
||||
active_link_field: LinkEditField::Url,
|
||||
link_expected_prev_url: None,
|
||||
standalone_link_block_id: None,
|
||||
submenu: None,
|
||||
@@ -529,6 +619,9 @@ impl Overlays {
|
||||
}
|
||||
(None, Some(toolbar)) => {
|
||||
toolbar.link = None;
|
||||
toolbar.link_text = None;
|
||||
toolbar.link_initial_text = None;
|
||||
toolbar.active_link_field = LinkEditField::Url;
|
||||
toolbar.link_expected_prev_url = None;
|
||||
toolbar.standalone_link_block_id = None;
|
||||
toolbar.submenu = None;
|
||||
@@ -547,6 +640,8 @@ impl Overlays {
|
||||
match action {
|
||||
FormatAction::TurnInto => {
|
||||
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) {
|
||||
@@ -557,6 +652,8 @@ impl Overlays {
|
||||
}
|
||||
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) {
|
||||
@@ -565,6 +662,28 @@ impl Overlays {
|
||||
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::InlineEquation => {
|
||||
toolbar.submenu = None;
|
||||
toolbar.submenu_rect = None;
|
||||
effects.edits.push(DocEdit::InlineEquationFromSelection);
|
||||
}
|
||||
FormatAction::CreateLinkedDoc => {
|
||||
toolbar.submenu = None;
|
||||
toolbar.submenu_rect = None;
|
||||
effects.edits.push(DocEdit::CreateLinkedDocFromSelection);
|
||||
}
|
||||
FormatAction::Link => {
|
||||
toolbar.submenu = None;
|
||||
toolbar.submenu_rect = None;
|
||||
@@ -572,13 +691,20 @@ impl Overlays {
|
||||
match toolbar.link {
|
||||
Some(_) => {
|
||||
toolbar.link = None;
|
||||
toolbar.link_text = None;
|
||||
toolbar.link_initial_text = None;
|
||||
toolbar.active_link_field = LinkEditField::Url;
|
||||
toolbar.link_expected_prev_url = None;
|
||||
}
|
||||
None => {
|
||||
let init_url = toolbar.selection.marks.link.clone().unwrap_or_default();
|
||||
let init_text = toolbar.selection.selected_text.clone();
|
||||
toolbar.link_expected_prev_url =
|
||||
(!init_url.is_empty()).then(|| init_url.clone());
|
||||
toolbar.link = Some(LinkBar::new(init_url));
|
||||
toolbar.link_text = init_text.clone().map(LinkBar::new);
|
||||
toolbar.link_initial_text = init_text;
|
||||
toolbar.active_link_field = LinkEditField::Url;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -595,18 +721,34 @@ impl Overlays {
|
||||
}
|
||||
|
||||
/// Write the link field to the selection (or clear the selection's link) and close the
|
||||
/// field.
|
||||
/// field. Rejects empty or invalid URLs when applying so the field stays open for correction.
|
||||
pub(super) fn apply_link(&mut self, remove: bool, effects: &mut OverlayEffects) {
|
||||
let Some(toolbar) = self.open_toolbar_mut() else {
|
||||
return;
|
||||
};
|
||||
if !remove {
|
||||
let Some(link) = toolbar.link.as_ref() else {
|
||||
return;
|
||||
};
|
||||
if normalize_url(&link.text()).is_empty() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
let Some(link) = toolbar.link.take() else {
|
||||
return;
|
||||
};
|
||||
let link_text = toolbar.link_text.take();
|
||||
let initial_text = toolbar.link_initial_text.take();
|
||||
toolbar.active_link_field = LinkEditField::Url;
|
||||
let expected_prev_url = toolbar.link_expected_prev_url.take();
|
||||
let standalone = toolbar.standalone_link_block_id.take().is_some();
|
||||
effects.redraw = true;
|
||||
let url = normalize_url(&link.into_committed_text());
|
||||
let display_text = link_text.and_then(|bar| {
|
||||
let committed = bar.into_committed_text();
|
||||
(!committed.is_empty() && initial_text.as_deref() != Some(committed.as_str()))
|
||||
.then_some(committed)
|
||||
});
|
||||
if standalone {
|
||||
self.toolbar = None;
|
||||
}
|
||||
@@ -614,11 +756,15 @@ impl Overlays {
|
||||
effects.edits.push(DocEdit::Link {
|
||||
url: None,
|
||||
expected_prev_url,
|
||||
expected_prev_text: None,
|
||||
display_text: None,
|
||||
});
|
||||
} else if !url.is_empty() {
|
||||
effects.edits.push(DocEdit::Link {
|
||||
url: Some(url),
|
||||
expected_prev_url,
|
||||
expected_prev_text: initial_text,
|
||||
display_text,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,8 +78,15 @@ impl PlaygroundView {
|
||||
&& self.database_record_sheet.is_none()
|
||||
&& self.table_cell.is_some()
|
||||
&& !self.table_is_readonly();
|
||||
let block_bar_owns_slot = is_mobile_slot
|
||||
&& self.database_record_sheet.is_none()
|
||||
&& self.editor.selection.is_none()
|
||||
&& (self.selected_image_block_id(&layout).is_some()
|
||||
|| self.selected_bookmark_block_id(&layout).is_some()
|
||||
|| self.selected_callout_block_id(&layout).is_some());
|
||||
let next_kb_visible = !self.database_record_sheet.is_some()
|
||||
&& !table_bar_owns_slot
|
||||
&& !block_bar_owns_slot
|
||||
&& !self.page_readonly
|
||||
&& (is_mobile_slot || live_kb_inset > 0.0)
|
||||
&& self.editor.selection.is_some()
|
||||
@@ -369,7 +376,21 @@ impl PlaygroundView {
|
||||
}))
|
||||
.on_scroll(cx.listener(Self::on_edgeless_scroll))
|
||||
.on_pinch(cx.listener(Self::on_edgeless_pinch))
|
||||
.on_mouse_down(MouseButton::Left, cx.listener(Self::on_edgeless_left_down))
|
||||
.on_mouse_down(
|
||||
MouseButton::Left,
|
||||
cx.listener(|this, event: &ui::MouseDownEvent, window, cx| {
|
||||
if this.try_click_edgeless_note_latex(
|
||||
f32::from(event.position.x),
|
||||
f32::from(event.position.y),
|
||||
event.click_count,
|
||||
window,
|
||||
cx,
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this.on_edgeless_left_down(event, window, cx);
|
||||
}),
|
||||
)
|
||||
.on_mouse_down(
|
||||
MouseButton::Right,
|
||||
cx.listener(Self::edgeless_right_mouse_down),
|
||||
|
||||
@@ -324,6 +324,11 @@ impl PlaygroundView {
|
||||
block_id, local_x, local_y, click_x, pos_x, pos_y, None,
|
||||
);
|
||||
let st = self.flow.database_state.state_for(block_id);
|
||||
let dismissed_calendar_inline = st
|
||||
.authoring
|
||||
.active_cell
|
||||
.as_ref()
|
||||
.is_some_and(|ed| ed.calendar_day_index.is_some());
|
||||
if st.authoring.column_menu.is_some()
|
||||
|| st.authoring.active_cell.is_some()
|
||||
|| st.authoring.toolbar_panel.is_some()
|
||||
@@ -335,6 +340,9 @@ impl PlaygroundView {
|
||||
self.sync_database_authoring_input(window, cx);
|
||||
self.env_rev += 1;
|
||||
cx.notify();
|
||||
if dismissed_calendar_inline {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
@@ -338,6 +338,37 @@ fn narrow_calendar_capsule_inline_edit_follows_caret_and_hides_day_plus_while_ed
|
||||
"clicking hidden `+` corner while editing must not create a new calendar event"
|
||||
);
|
||||
assert!(app.update(|cx| win.read(cx).unwrap().database_input.is_none()));
|
||||
assert_eq!(
|
||||
app.update(|cx| {
|
||||
win.read(cx)
|
||||
.unwrap()
|
||||
.flow
|
||||
.database_state
|
||||
.state_for(&db_id)
|
||||
.calendar_selected_day
|
||||
}),
|
||||
None,
|
||||
"clicking to dismiss active Calendar inline edit must consume the click without selecting a day"
|
||||
);
|
||||
// On desktop, selecting a non-today day without hovering it must NOT keep `+` visible.
|
||||
app.update(|cx| {
|
||||
win.update(cx, |v, _, cx| {
|
||||
v.flow
|
||||
.database_state
|
||||
.set_calendar_selected_day(&db_id, Some(capsule_day));
|
||||
v.flow.database_state.set_calendar_hovered_day(&db_id, None);
|
||||
v.env_rev += 1;
|
||||
cx.notify();
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
tick();
|
||||
let (selected_only_plus, selected_only_hovered) = plus_state();
|
||||
assert!(!selected_only_hovered);
|
||||
assert!(
|
||||
selected_only_plus <= 1,
|
||||
"desktop calendar_selected_day must not force `+` visible on non-hovered days, got {selected_only_plus}"
|
||||
);
|
||||
|
||||
// 3. No day shows `+` while the event is dragged, neither the source nor the target day.
|
||||
let (cx0, cy0) = (f32::from(capsule_pt.x), f32::from(capsule_pt.y));
|
||||
|
||||
@@ -308,3 +308,127 @@ fn mobile_edgeless_default_showcase_keeps_frame_title_unoccluded_by_note_header(
|
||||
.expect("save png failed");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn note_slicer_background_map_and_mindmap_locked_and_dangling_guards() {
|
||||
let (platform, app, win, hw) = start_edgeless_toolbar_view();
|
||||
|
||||
// 1. Note Slicer preserves `{light, dark}` background as a nested Y.Map and respects edgeless_readonly.
|
||||
let sliced = app
|
||||
.update(|cx| {
|
||||
win.update(cx, |v, _, cx| {
|
||||
let page = v.page_mut().unwrap();
|
||||
let mut bg = y_octo::AHashMap::default();
|
||||
bg.insert("light".to_string(), Any::String("#fff3d6".into()));
|
||||
bg.insert("dark".to_string(), Any::String("#3a2e1a".into()));
|
||||
page.set_block_prop(
|
||||
"note-main",
|
||||
"prop:background",
|
||||
SessionValue::Map(
|
||||
bg.into_iter()
|
||||
.map(|(k, v)| (k, SessionValue::Any(v)))
|
||||
.collect(),
|
||||
),
|
||||
10,
|
||||
)
|
||||
.unwrap();
|
||||
v.refresh_document();
|
||||
v.edgeless_set_selection(["note-main".into()], cx);
|
||||
v.edgeless_readonly = true;
|
||||
assert!(
|
||||
v.edgeless_slice_selected_note(1, cx).is_none(),
|
||||
"edgeless_readonly must block note slicing"
|
||||
);
|
||||
v.edgeless_readonly = false;
|
||||
v.edgeless_slice_selected_note(1, cx)
|
||||
.expect("slice note-main")
|
||||
})
|
||||
})
|
||||
.unwrap();
|
||||
hw.request_frame();
|
||||
app.update(|cx| {
|
||||
win.update(cx, |v, _, _| {
|
||||
let snap = v.snapshot.as_ref().unwrap();
|
||||
let bg = snap
|
||||
.block(&sliced)
|
||||
.unwrap()
|
||||
.props
|
||||
.get("prop:background")
|
||||
.expect("sliced note must preserve prop:background");
|
||||
assert_eq!(bg["light"], "#fff3d6");
|
||||
assert_eq!(bg["dark"], "#3a2e1a");
|
||||
})
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
// 2. MindMap subtree delete refuses when any descendant is locked; dangling shape id is skipped
|
||||
// cleanly during layout switch and sibling creation.
|
||||
app.update(|cx| {
|
||||
win.update(cx, |v, _, cx| {
|
||||
v.edgeless_set_selection(["mm-c1".into()], cx);
|
||||
assert!(v.edgeless_add_mindmap_node(true, cx));
|
||||
let grandchild = v
|
||||
.edgeless
|
||||
.authoring
|
||||
.selection
|
||||
.iter()
|
||||
.next()
|
||||
.cloned()
|
||||
.expect("grandchild selected");
|
||||
let page = v.page_mut().unwrap();
|
||||
page.set_surface_element_field(
|
||||
"surf",
|
||||
&grandchild,
|
||||
"lockedBySelf",
|
||||
SessionValue::Any(Any::True),
|
||||
20,
|
||||
)
|
||||
.unwrap();
|
||||
page.apply_mindmap_children_delta(
|
||||
"surf",
|
||||
"mm-1",
|
||||
&[(
|
||||
"mm-dangling-missing".to_string(),
|
||||
blocksuite_playground_doc::schema::MindmapNodeSpec {
|
||||
index: "a9".into(),
|
||||
parent: Some("mm-root".into()),
|
||||
collapsed: false,
|
||||
},
|
||||
)],
|
||||
&[],
|
||||
)
|
||||
.unwrap();
|
||||
v.refresh_document();
|
||||
|
||||
// Attempt to delete unlocked parent `mm-c1` whose descendant `grandchild` is locked:
|
||||
// the entire subtree deletion must be refused.
|
||||
v.edgeless_set_selection(["mm-c1".into()], cx);
|
||||
v.edgeless_delete_selection(cx);
|
||||
let snap = v.snapshot.as_ref().unwrap();
|
||||
assert!(
|
||||
find_surface_element(snap, "mm-c1").is_some(),
|
||||
"parent must survive when a cascading descendant is locked"
|
||||
);
|
||||
assert!(
|
||||
find_surface_element(snap, &grandchild).is_some(),
|
||||
"locked descendant must survive"
|
||||
);
|
||||
|
||||
// Layout switch and sibling add must succeed despite the dangling shape entry.
|
||||
v.edgeless_set_selection(["mm-c2".into()], cx);
|
||||
assert!(
|
||||
v.edgeless_set_mindmap_layout(
|
||||
blocksuite_playground_doc::read::MindmapLayoutType::Left,
|
||||
cx
|
||||
),
|
||||
"layout switch must skip dangling missing shape entries"
|
||||
);
|
||||
assert!(
|
||||
v.edgeless_add_mindmap_node(false, cx),
|
||||
"adding sibling must skip dangling missing shape entries"
|
||||
);
|
||||
})
|
||||
})
|
||||
.unwrap();
|
||||
let _ = platform;
|
||||
}
|
||||
@@ -261,6 +261,9 @@ impl PlaygroundView {
|
||||
.map(|(_, eid)| eid.clone())
|
||||
.collect();
|
||||
let mm_plan = plan_mindmap_deletes(&snapshot, &deleting_surface_ids);
|
||||
if !mm_plan.refused_surface_elements.is_empty() {
|
||||
surface_elements.retain(|(_, eid)| !mm_plan.refused_surface_elements.contains(eid));
|
||||
}
|
||||
for extra in mm_plan.extra_surface_elements {
|
||||
if !surface_elements.contains(&extra) {
|
||||
surface_elements.push(extra);
|
||||
|
||||
@@ -40,6 +40,9 @@ pub(super) struct MindmapDeletePlan {
|
||||
/// Additional `(surface_id, element_id)` surface elements to delete (descendant shapes, or the
|
||||
/// entire `mindmap` + all its shapes when the root node is deleted).
|
||||
pub extra_surface_elements: Vec<(String, String)>,
|
||||
/// Selected surface element ids whose MindMap subtree deletion was refused because a
|
||||
/// cascading descendant is locked.
|
||||
pub refused_surface_elements: BTreeSet<String>,
|
||||
/// Incremental `(surface_id, mindmap_id, removed_node_ids)` removals on surviving `children` `Y.Map`s.
|
||||
pub mindmap_removals: Vec<(String, String, Vec<String>)>,
|
||||
/// Post-delete `(surface_id, node_id, xywh)` relayout updates for surviving MindMap nodes.
|
||||
@@ -146,31 +149,29 @@ fn compute_relayout_xywh(
|
||||
rects: &BTreeMap<String, [f64; 4]>,
|
||||
min_sizes: &BTreeMap<String, (f64, f64)>,
|
||||
) -> Vec<(String, [f64; 4])> {
|
||||
let initial_bounds: BTreeMap<String, WorldBounds> = mm
|
||||
let mut live_mm = mm.clone();
|
||||
live_mm.nodes.retain(|id, _| rects.contains_key(id));
|
||||
let initial_bounds: BTreeMap<String, WorldBounds> = live_mm
|
||||
.nodes
|
||||
.keys()
|
||||
.map(|id| {
|
||||
let [x, y, w, h] = rects.get(id).copied().unwrap_or([
|
||||
0.0,
|
||||
0.0,
|
||||
MINDMAP_DEFAULT_NODE_W,
|
||||
MINDMAP_DEFAULT_NODE_H,
|
||||
]);
|
||||
.filter_map(|id| {
|
||||
let [x, y, w, h] = rects.get(id).copied()?;
|
||||
let (min_w, min_h) = min_sizes
|
||||
.get(id)
|
||||
.copied()
|
||||
.unwrap_or((MINDMAP_MIN_NODE_W, MINDMAP_MIN_NODE_H));
|
||||
(
|
||||
Some((
|
||||
id.clone(),
|
||||
WorldBounds {
|
||||
xywh: [x, y, w.max(min_w), h.max(min_h)],
|
||||
rotate: 0.0,
|
||||
},
|
||||
)
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
compute_mindmap_layout(mm, &initial_bounds)
|
||||
compute_mindmap_layout(&live_mm, &initial_bounds)
|
||||
.into_iter()
|
||||
.filter(|(id, _)| rects.contains_key(id))
|
||||
.map(|(id, b)| (id, b.xywh))
|
||||
.collect()
|
||||
}
|
||||
@@ -183,6 +184,7 @@ pub(super) fn plan_mindmap_deletes(
|
||||
) -> MindmapDeletePlan {
|
||||
let mut plan = MindmapDeletePlan {
|
||||
extra_surface_elements: Vec::new(),
|
||||
refused_surface_elements: BTreeSet::new(),
|
||||
mindmap_removals: Vec::new(),
|
||||
relayout_xywh: Vec::new(),
|
||||
};
|
||||
@@ -193,13 +195,16 @@ pub(super) fn plan_mindmap_deletes(
|
||||
let BlockContent::Surface { elements, .. } = &node.content else {
|
||||
continue;
|
||||
};
|
||||
let locked_ids: BTreeSet<&str> = elements
|
||||
.iter()
|
||||
.filter(|e| e.locked_by_self)
|
||||
.map(|e| e.id.as_str())
|
||||
.collect();
|
||||
let existing_ids: BTreeSet<&str> = elements.iter().map(|e| e.id.as_str()).collect();
|
||||
for el in elements {
|
||||
let SurfaceElementKind::Mindmap(mm) = &el.kind else {
|
||||
continue;
|
||||
};
|
||||
if el.locked_by_self {
|
||||
continue;
|
||||
}
|
||||
let hit_nodes: BTreeSet<String> = mm
|
||||
.nodes
|
||||
.keys()
|
||||
@@ -210,6 +215,10 @@ pub(super) fn plan_mindmap_deletes(
|
||||
if hit_nodes.is_empty() && !deleting_mm_itself {
|
||||
continue;
|
||||
}
|
||||
if el.locked_by_self {
|
||||
plan.refused_surface_elements.extend(hit_nodes);
|
||||
continue;
|
||||
}
|
||||
let root_id = mm
|
||||
.nodes
|
||||
.iter()
|
||||
@@ -226,12 +235,19 @@ pub(super) fn plan_mindmap_deletes(
|
||||
let delete_entire =
|
||||
deleting_mm_itself || root_id.as_ref().is_some_and(|r| hit_nodes.contains(r));
|
||||
if delete_entire {
|
||||
if mm.nodes.keys().any(|nid| locked_ids.contains(nid.as_str())) {
|
||||
if deleting_mm_itself {
|
||||
plan.refused_surface_elements.insert(el.id.clone());
|
||||
}
|
||||
plan.refused_surface_elements.extend(hit_nodes);
|
||||
continue;
|
||||
}
|
||||
if !deleting_mm_itself {
|
||||
plan.extra_surface_elements
|
||||
.push((node.id.clone(), el.id.clone()));
|
||||
}
|
||||
for nid in mm.nodes.keys() {
|
||||
if !deleting_surface_ids.contains(nid) {
|
||||
if !deleting_surface_ids.contains(nid) && existing_ids.contains(nid.as_str()) {
|
||||
plan.extra_surface_elements
|
||||
.push((node.id.clone(), nid.clone()));
|
||||
}
|
||||
@@ -240,7 +256,7 @@ pub(super) fn plan_mindmap_deletes(
|
||||
}
|
||||
|
||||
// Expand non-root deletions to all descendants in `mm.nodes`.
|
||||
let mut cascade: BTreeSet<String> = hit_nodes;
|
||||
let mut cascade: BTreeSet<String> = hit_nodes.clone();
|
||||
let mut changed = true;
|
||||
while changed {
|
||||
changed = false;
|
||||
@@ -256,8 +272,12 @@ pub(super) fn plan_mindmap_deletes(
|
||||
}
|
||||
}
|
||||
}
|
||||
if cascade.iter().any(|nid| locked_ids.contains(nid.as_str())) {
|
||||
plan.refused_surface_elements.extend(hit_nodes);
|
||||
continue;
|
||||
}
|
||||
for nid in &cascade {
|
||||
if !deleting_surface_ids.contains(nid) {
|
||||
if !deleting_surface_ids.contains(nid) && existing_ids.contains(nid.as_str()) {
|
||||
plan.extra_surface_elements
|
||||
.push((node.id.clone(), nid.clone()));
|
||||
}
|
||||
@@ -330,6 +350,7 @@ impl PlaygroundView {
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.map_err(|err| eprintln!("mindmap structural_edit: {err}"))
|
||||
.ok()
|
||||
.flatten()
|
||||
});
|
||||
@@ -378,6 +399,7 @@ impl PlaygroundView {
|
||||
)?;
|
||||
Ok(())
|
||||
})
|
||||
.map_err(|err| eprintln!("mindmap structural_edit: {err}"))
|
||||
.ok()
|
||||
.flatten()
|
||||
});
|
||||
@@ -423,6 +445,7 @@ impl PlaygroundView {
|
||||
page.apply_mindmap_children_delta(&surface_id, &mindmap_id, &upserts, &[])?;
|
||||
Ok(())
|
||||
})
|
||||
.map_err(|err| eprintln!("mindmap structural_edit: {err}"))
|
||||
.ok()
|
||||
.flatten()
|
||||
});
|
||||
@@ -565,6 +588,7 @@ impl PlaygroundView {
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.map_err(|err| eprintln!("mindmap structural_edit: {err}"))
|
||||
.ok()
|
||||
.flatten()
|
||||
});
|
||||
|
||||
@@ -107,15 +107,15 @@ impl PlaygroundView {
|
||||
SessionValue::Any(Any::String(display_mode.as_str().into())),
|
||||
now_ms,
|
||||
)?;
|
||||
let empty_map = HashMap::new();
|
||||
if let Some(bg) = background.as_ref() {
|
||||
page.set_block_prop(
|
||||
&new_note_clone,
|
||||
"prop:background",
|
||||
SessionValue::Any(json_to_any(bg)),
|
||||
block_json_to_session_value(bg, &empty_map),
|
||||
now_ms,
|
||||
)?;
|
||||
}
|
||||
let empty_map = HashMap::new();
|
||||
for (k, v) in &edgeless_props {
|
||||
let val = if k == "prop:edgeless" {
|
||||
block_json_to_session_value(v, &empty_map)
|
||||
@@ -135,6 +135,7 @@ impl PlaygroundView {
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.map_err(|err| eprintln!("note slicer structural_edit: {err}"))
|
||||
.ok()
|
||||
.flatten()
|
||||
})?;
|
||||
|
||||
@@ -8,9 +8,8 @@ use super::EdgelessRemotePeer;
|
||||
impl PlaygroundView {
|
||||
/// Build deterministic Edgeless remote presence snapshots from the current room awareness.
|
||||
/// Reads BlockSuite `selectionV2` entries of type `"cursor"` (`{ x, y }`) and `"surface"`
|
||||
/// (`{ elements: [...] }`) strictly scoped to `self.page_id`. Top-level `cursor` is only
|
||||
/// consulted when the peer's awareness explicitly has a matching `selectionV2` entry for
|
||||
/// `self.page_id`, so peers on another page never leak onto the active canvas.
|
||||
/// (`{ elements: [...] }`) strictly scoped to `self.page_id`, so peers on another page
|
||||
/// never leak onto the active canvas.
|
||||
pub(crate) fn edgeless_remote_peers(&self, palette: &Palette) -> Vec<EdgelessRemotePeer> {
|
||||
const FALLBACK_COLORS: [&str; 8] = [
|
||||
"--affine-multi-players-purple",
|
||||
|
||||
@@ -375,11 +375,11 @@ impl PlaygroundView {
|
||||
let mut el = Vec::new();
|
||||
if !self.editor.block_selection.is_empty() {
|
||||
let mut first_block = true;
|
||||
for block_id in &self.editor.block_selection {
|
||||
let Some(block) = layout.block(block_id) else {
|
||||
continue;
|
||||
};
|
||||
let r = block.rect();
|
||||
for r in overlays::block_selection_visual_rects(
|
||||
self.snapshot.as_deref(),
|
||||
layout,
|
||||
&self.editor.block_selection,
|
||||
) {
|
||||
if r.bottom() < v.scroll_y || r.y > v.scroll_y + v.height {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -298,6 +298,9 @@ pub struct PlaygroundView {
|
||||
pub(crate) database_hover_table: Option<database_authoring::TableHoverState>,
|
||||
pub(crate) database_input: Option<database_authoring::DatabaseInlineSession>,
|
||||
pub(crate) context_toast_timer: Option<Task<()>>,
|
||||
pub(crate) link_hover_timer: Option<Task<()>>,
|
||||
pub(crate) link_hover_gen: u64,
|
||||
pub(crate) pending_link_hover: Option<(overlays::LinkPopupTarget, block_flow::FlowRect, u64)>,
|
||||
pub(crate) context_paste_task: Option<Task<()>>,
|
||||
pub(crate) context_menu_target: Option<overlays::ContextTargetSnapshot>,
|
||||
pub(crate) last_opened_link_url: Option<String>,
|
||||
@@ -323,18 +326,6 @@ pub struct PlaygroundView {
|
||||
pub(crate) _tasks: Vec<Task<()>>,
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
fn fresh_client_id() -> u64 {
|
||||
blocksuite_playground_doc::random_client_id()
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
fn fresh_client_id() -> u64 {
|
||||
blocksuite_playground_doc::client_id_from_seed(
|
||||
(js_sys::Math::random() * 9_007_199_254_740_992.0) as u64,
|
||||
)
|
||||
}
|
||||
|
||||
impl PlaygroundView {
|
||||
/// Open the built-in showcase document in the light theme.
|
||||
pub fn new(cx: &mut Context<Self>) -> Self {
|
||||
@@ -346,7 +337,7 @@ impl PlaygroundView {
|
||||
let mut tasks = Vec::new();
|
||||
let (state, room) = match options.room {
|
||||
Some(config) => {
|
||||
let state = DocState::new(&config.room, fresh_client_id())
|
||||
let state = DocState::new(&config.room, view_room::fresh_client_id())
|
||||
.expect("generated client ids are always in the 53-bit range");
|
||||
let link = room_client::connect(config.clone());
|
||||
let events = link.events().clone();
|
||||
@@ -471,6 +462,9 @@ impl PlaygroundView {
|
||||
database_hover_table: None,
|
||||
database_input: None,
|
||||
context_toast_timer: None,
|
||||
link_hover_timer: None,
|
||||
link_hover_gen: 0,
|
||||
pending_link_hover: None,
|
||||
context_paste_task: None,
|
||||
context_menu_target: None,
|
||||
last_opened_link_url: None,
|
||||
@@ -685,6 +679,7 @@ impl PlaygroundView {
|
||||
pub fn set_page_readonly(&mut self, readonly: bool, cx: &mut Context<Self>) {
|
||||
if self.page_readonly != readonly {
|
||||
self.page_readonly = readonly;
|
||||
self.last_link_popup_caret = None;
|
||||
if readonly {
|
||||
self.pending_media_pick = None;
|
||||
self.cancel_image_resize_drag();
|
||||
@@ -10321,14 +10316,14 @@ pub(crate) mod tests {
|
||||
.find(|b| b.block_id == "b-callout-p")
|
||||
.expect("callout child");
|
||||
assert!(
|
||||
(child.rect().y - (callout.rect().y + 5.0)).abs() <= 2.0,
|
||||
"callout child must sit on same row at top+5 (callout.y={}, child.y={})",
|
||||
(child.rect().y - (callout.rect().y + 10.0)).abs() <= 2.0,
|
||||
"callout child must sit on same row at top+10 (callout.y={}, child.y={})",
|
||||
callout.rect().y,
|
||||
child.rect().y
|
||||
);
|
||||
assert!(
|
||||
(child.rect().x - (callout.rect().x + 44.0)).abs() <= 2.0,
|
||||
"callout child must start at x+44 (callout.x={}, child.x={})",
|
||||
(child.rect().x - (callout.rect().x + 46.0)).abs() <= 2.0,
|
||||
"callout child must start at x+46 (callout.x={}, child.x={})",
|
||||
callout.rect().x,
|
||||
child.rect().x
|
||||
);
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
//! PlaygroundView glue for `blocksuite_editor::overlays`.
|
||||
|
||||
mod view;
|
||||
mod view_callout_bar;
|
||||
mod view_context_menu;
|
||||
mod view_edits;
|
||||
mod view_embed_controls;
|
||||
mod view_format_bar;
|
||||
mod view_link_popup;
|
||||
mod view_linked_doc;
|
||||
mod view_mobile;
|
||||
@@ -24,6 +26,8 @@ mod tests_media_picker_and_touch;
|
||||
#[cfg(test)]
|
||||
mod tests_mouse_and_touch_resize;
|
||||
#[cfg(test)]
|
||||
mod tests_popovers_toolbars;
|
||||
#[cfg(test)]
|
||||
mod tests_slash_linked_table;
|
||||
#[cfg(test)]
|
||||
mod tests_tree_dnd_and_marquee;
|
||||
@@ -160,7 +164,7 @@ mod tests {
|
||||
})
|
||||
}
|
||||
|
||||
fn view<R>(
|
||||
pub(super) fn view<R>(
|
||||
&self,
|
||||
f: impl FnOnce(&mut PlaygroundView, &mut Context<PlaygroundView>) -> R,
|
||||
) -> R {
|
||||
@@ -268,7 +272,7 @@ mod tests {
|
||||
|
||||
/// Type text the way a keyboard does: each key goes to the key handlers first
|
||||
/// and, when none of them takes it, to the input handler as text.
|
||||
fn type_text(&self, text: &str) {
|
||||
pub(super) fn type_text(&self, text: &str) {
|
||||
for ch in text.chars() {
|
||||
self.frame();
|
||||
self.platform.run_until_parked();
|
||||
@@ -287,7 +291,7 @@ mod tests {
|
||||
}
|
||||
|
||||
/// A key with the platform's command modifier.
|
||||
fn command(&self, key: &str) {
|
||||
pub(super) fn command(&self, key: &str) {
|
||||
self.keystroke(Keystroke {
|
||||
modifiers: Modifiers {
|
||||
platform: true,
|
||||
@@ -456,7 +460,7 @@ mod tests {
|
||||
}
|
||||
|
||||
/// Select the first occurrence of `needle` in a block; returns the UTF-16 range.
|
||||
fn select(&self, block_id: &str, needle: &str) -> (usize, usize) {
|
||||
pub(super) fn select(&self, block_id: &str, needle: &str) -> (usize, usize) {
|
||||
let plain = self.text(block_id).plain;
|
||||
let at = plain.find(needle).expect("needle in block text");
|
||||
let start = plain[..at].encode_utf16().count();
|
||||
@@ -1450,17 +1454,21 @@ 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 + 32.0);
|
||||
assert_eq!(grown.height, single.height + 64.0);
|
||||
assert!(
|
||||
field.bounds.y
|
||||
>= element(&linking, "overlay.format_toolbar.bold")
|
||||
.bounds
|
||||
.bottom()
|
||||
);
|
||||
for id in ["link_apply", "link_remove"] {
|
||||
let button = element(&linking, &format!("overlay.format_toolbar.{id}"));
|
||||
assert!(button.interactive && button.bounds.height >= 28.0, "{id}");
|
||||
}
|
||||
// New-link mode hides `Remove` and disables `Apply` until a valid URL is entered.
|
||||
assert!(
|
||||
!linking
|
||||
.elements
|
||||
.contains_key("overlay.format_toolbar.link_remove")
|
||||
);
|
||||
let apply_btn = element(&linking, "overlay.format_toolbar.link_apply");
|
||||
assert!(apply_btn.bounds.height >= 28.0 && !apply_btn.focused);
|
||||
let text_before = session.text(block).plain;
|
||||
// Typed keys reach the field as text through the input handler, like text from
|
||||
// an input method, and none of it reaches the document.
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -117,6 +117,7 @@ mod tests {
|
||||
let edgeless_text_ctx = SlashContext {
|
||||
in_edgeless_text: true,
|
||||
in_edgeless_canvas: true,
|
||||
flatten_submenus: false,
|
||||
};
|
||||
let items_in_et = filter_slash_items_in_context("", true, true, true, edgeless_text_ctx);
|
||||
for forbidden in [
|
||||
@@ -1259,9 +1260,31 @@ mod tests {
|
||||
!snap.elements.contains_key("overlay.slash_menu.preview"),
|
||||
"Phone 390x844 must never paint Slash preview card after >=850ms for query `{query}`"
|
||||
);
|
||||
if query.is_empty() {
|
||||
assert!(
|
||||
!snap
|
||||
.elements
|
||||
.contains_key("overlay.slash_menu.item.other_headings"),
|
||||
"Phone 390x844 must flatten H4-H6 instead of showing Other Headings submenu"
|
||||
);
|
||||
assert!(
|
||||
snap.elements.contains_key("overlay.slash_menu.item.h4"),
|
||||
"Phone 390x844 unfiltered Slash menu must expose H4 flatly"
|
||||
);
|
||||
if let Ok(dir) = std::env::var("POPOVERS_EVIDENCE_DIR") {
|
||||
let out_dir = std::path::PathBuf::from(dir);
|
||||
std::fs::create_dir_all(&out_dir).expect("create evidence dir");
|
||||
let img = app
|
||||
.update(|cx| win.update(cx, |_, w, _| w.render_to_image()).unwrap())
|
||||
.expect("render phone slash menu");
|
||||
img.save(out_dir.join("07-touch-slash-flat-h4-h6.png"))
|
||||
.expect("save phone slash menu PNG");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Desktop (1280x800): shows preview card after 800ms without intersecting menu_rect.
|
||||
// 2. Desktop (1280x800): shows preview card after 800ms without intersecting menu_rect,
|
||||
// keeps Other Headings submenu, and hides preview once the selected row scrolls out.
|
||||
let desktop = open(1280, 800, PlaygroundTheme::Light);
|
||||
desktop.overlay(OverlayEvent::SetSelection(Some(ActiveSelection::caret(
|
||||
block, 0,
|
||||
@@ -1277,6 +1300,12 @@ mod tests {
|
||||
.advance_clock(Duration::from_millis(SLASH_PREVIEW_DELAY_MS as u64 + 50));
|
||||
desktop.platform.run_until_parked();
|
||||
let desk_snap = desktop.frame();
|
||||
assert!(
|
||||
desk_snap
|
||||
.elements
|
||||
.contains_key("overlay.slash_menu.item.other_headings"),
|
||||
"Desktop unfiltered Slash menu must keep Other Headings submenu"
|
||||
);
|
||||
let menu_b = element(&desk_snap, "overlay.slash_menu").bounds;
|
||||
let prev_b = element(&desk_snap, "overlay.slash_menu.preview").bounds;
|
||||
let disjoint = prev_b.x >= menu_b.x + menu_b.width || prev_b.x + prev_b.width <= menu_b.x;
|
||||
@@ -1284,6 +1313,14 @@ mod tests {
|
||||
disjoint,
|
||||
"Desktop preview card must never intersect menu_rect: menu={menu_b:?}, preview={prev_b:?}"
|
||||
);
|
||||
desktop.overlay(OverlayEvent::SlashScroll(-600.0));
|
||||
let scrolled_snap = desktop.frame();
|
||||
assert!(
|
||||
!scrolled_snap
|
||||
.elements
|
||||
.contains_key("overlay.slash_menu.preview"),
|
||||
"Desktop Slash preview card must hide when selected row scrolls out of viewport"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1314,8 +1351,9 @@ mod tests {
|
||||
let _ = session.frame();
|
||||
session.overlay(OverlayEvent::SlashExecute(0));
|
||||
let _ = session.frame();
|
||||
let (rev_after, text_after) = session.app.update(|cx| {
|
||||
session
|
||||
let (rev_after, text_after, copied_text) = session.app.update(|cx| {
|
||||
let copied = cx.read_from_clipboard().and_then(|item| item.text());
|
||||
let (rev, text) = session
|
||||
.window
|
||||
.update(cx, |v, _, _| {
|
||||
(
|
||||
@@ -1323,7 +1361,8 @@ mod tests {
|
||||
v.block_text(block).unwrap().to_string(),
|
||||
)
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
(rev, text, copied)
|
||||
});
|
||||
assert_eq!(
|
||||
rev_after, rev_before,
|
||||
@@ -1333,6 +1372,12 @@ mod tests {
|
||||
text_after, text_before,
|
||||
"executing /copy in page_readonly must not delete `/copy` trigger text"
|
||||
);
|
||||
assert!(
|
||||
copied_text
|
||||
.as_deref()
|
||||
.is_some_and(|s| s.contains(&text_before)),
|
||||
"executing /copy in page_readonly must copy block content to clipboard, got {copied_text:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::{ops::Range, time::Duration};
|
||||
|
||||
use blocksuite_playground_doc::read::{PageSnapshot, TextAlign as BlockAlign};
|
||||
use blocksuite_playground_doc::read::PageSnapshot;
|
||||
use ui::{AnyElement, ClipboardItem, Context, KeyDownEvent, MouseDownEvent, Window};
|
||||
|
||||
use crate::{
|
||||
@@ -49,6 +49,9 @@ impl PlaygroundView {
|
||||
) -> OverlayScene<'a> {
|
||||
let focused_code_block = self.focused_code_block_id(layout);
|
||||
let selected_image_block = self.selected_image_block_id(layout);
|
||||
let selected_bookmark_block = self.selected_bookmark_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 =
|
||||
(self.window_size.1 - self.ime_insets.last_bottom).max(crate::TOPBAR_HEIGHT);
|
||||
let bottom_toolbar_inset = self.overlays.keyboard_toolbar_reserved_height(avail_win_h);
|
||||
@@ -64,6 +67,9 @@ impl PlaygroundView {
|
||||
form_factor: self.form_factor,
|
||||
focused_code_block,
|
||||
selected_image_block,
|
||||
selected_bookmark_block,
|
||||
selected_callout_block,
|
||||
selected_latex_block,
|
||||
selection,
|
||||
screen_transform,
|
||||
suppress_floating_format_buttons: self.native_selection_ui,
|
||||
@@ -136,10 +142,12 @@ impl PlaygroundView {
|
||||
self.pending_media_pick = None;
|
||||
self.cancel_image_resize_drag();
|
||||
self.finish_inline_targets(InlineTargetEnd::CommitPreedit, Some(window), Some(cx));
|
||||
let now_ms = self.now_ms(cx);
|
||||
self.overlays.close_link_field();
|
||||
self.overlays.close_equation_editor();
|
||||
self.overlays.close_bookmark_prompt();
|
||||
self.overlays.close_equation_editor_at(now_ms);
|
||||
self.overlays.close_bookmark_prompt_at(now_ms);
|
||||
self.equation_snapshot = None;
|
||||
self.last_link_popup_caret = None;
|
||||
match selection {
|
||||
Some(selection) => {
|
||||
self.keyboard_toolbar_dismissed = false;
|
||||
@@ -222,6 +230,7 @@ impl PlaygroundView {
|
||||
return;
|
||||
}
|
||||
_ if self.handle_embed_and_code_event(&event, window, cx) => return,
|
||||
_ if self.handle_bookmark_and_callout_event(&event, window, cx) => return,
|
||||
_ if self.handle_context_menu_event(&event, window, cx) => return,
|
||||
_ if self.handle_linked_doc_event(&event, window, cx) => return,
|
||||
_ if self.handle_link_popup_event(&event, window, cx) => return,
|
||||
@@ -418,6 +427,19 @@ impl PlaygroundView {
|
||||
self.editor_focus.focus(window, cx);
|
||||
return;
|
||||
}
|
||||
let dismissed_calendar_block = self.database_input.as_ref().and_then(|s| {
|
||||
let block_id = s.target.block_id();
|
||||
(!s.target.is_popover_field()
|
||||
&& self
|
||||
.flow
|
||||
.database_state
|
||||
.state_for(block_id)
|
||||
.authoring
|
||||
.active_cell
|
||||
.as_ref()
|
||||
.is_some_and(|ed| ed.calendar_day_index.is_some()))
|
||||
.then(|| block_id.to_string())
|
||||
});
|
||||
self.finish_inline_targets(InlineTargetEnd::CommitPreedit, Some(window), Some(cx));
|
||||
self.overlays.pointer_pressed(now_ms);
|
||||
if self.overlays.equation_editor().is_none() {
|
||||
@@ -456,8 +478,18 @@ impl PlaygroundView {
|
||||
}) {
|
||||
self.dismiss_all_database_authoring(Some(&block_id), cx);
|
||||
let prev_slot = self.database_input.as_ref().map(|s| s.target.clone());
|
||||
let consumed =
|
||||
self.click_database_point(&block_id, local_x, local_y, Some(window), cx);
|
||||
let consumed = if dismissed_calendar_block.as_deref() == Some(block_id.as_str()) {
|
||||
let _ = self.try_click_database_authoring(
|
||||
&block_id,
|
||||
local_x,
|
||||
local_y,
|
||||
Some(window),
|
||||
cx,
|
||||
);
|
||||
true
|
||||
} else {
|
||||
self.click_database_point(&block_id, local_x, local_y, Some(window), cx)
|
||||
};
|
||||
if self.database_input.as_ref().is_some_and(|s| {
|
||||
!s.target.is_popover_field()
|
||||
&& prev_slot.as_ref().is_none_or(|p| !p.same_slot(&s.target))
|
||||
@@ -497,16 +529,25 @@ impl PlaygroundView {
|
||||
);
|
||||
return;
|
||||
}
|
||||
// Clicking a non-editable block (Bookmark, Image, Divider, Database body, Table frame)
|
||||
// Clicking a non-editable block (Bookmark, Image, Divider, Callout, Database body, Table frame)
|
||||
// or its horizontal row band selects that whole block into `block_selection` instead
|
||||
// of snapping the caret to a distant editable block.
|
||||
if let Some(non_editable_id) = layout.blocks.iter().find_map(|block| {
|
||||
// of snapping the caret to a distant editable block. Clicking an empty Callout creates
|
||||
// and focuses a child paragraph so the user can type immediately.
|
||||
if let Some((non_editable_id, is_callout)) = layout.blocks.iter().find_map(|block| {
|
||||
(!block.editable()
|
||||
&& (block.rect().contains(world_x, world_y)
|
||||
|| (world_y >= block.rect().y && world_y <= block.rect().bottom())))
|
||||
.then(|| block.block_id.clone())
|
||||
.then(|| {
|
||||
(
|
||||
block.block_id.clone(),
|
||||
matches!(block.body.kind, FlowKind::Callout),
|
||||
)
|
||||
})
|
||||
}) {
|
||||
self.editor_focus.focus(window, cx);
|
||||
if is_callout && self.focus_or_create_callout_child(&non_editable_id, window, cx) {
|
||||
return;
|
||||
}
|
||||
self.set_block_selection(vec![non_editable_id], false, window, cx);
|
||||
if in_page_margin {
|
||||
self.arm_page_marquee(
|
||||
@@ -551,6 +592,22 @@ impl PlaygroundView {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// On desktop, left-clicking an inline link opens the URL directly (matching BlockSuite
|
||||
// `affine-link.ts`), unless Alt is held to force caret placement inside the link.
|
||||
if !self.is_touch_host()
|
||||
&& !event.modifiers.alt
|
||||
&& let Some((LinkPopupTarget::Link { url, .. }, _)) = &clicked_popup
|
||||
&& let Some(clean) = blocksuite_editor::clipboard::sanitize::sanitize_url(url)
|
||||
.filter(|u| !u.starts_with('#'))
|
||||
{
|
||||
self.pending_link_hover = None;
|
||||
self.link_hover_timer = None;
|
||||
self.overlays.close_link_popup(now_ms);
|
||||
self.last_opened_link_url = Some(clean.clone());
|
||||
cx.open_url(&clean);
|
||||
cx.notify();
|
||||
return;
|
||||
}
|
||||
let suppress_kb_for_popup =
|
||||
clicked_popup.is_some() && self.is_touch_host() && self.keyboard_toolbar_dismissed;
|
||||
let was_dismissed = self.keyboard_toolbar_dismissed;
|
||||
@@ -629,92 +686,6 @@ impl PlaygroundView {
|
||||
Some(result)
|
||||
}
|
||||
|
||||
/// 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. Marks and alignment are read once per selection and document revision.
|
||||
pub(crate) fn selection_format(&mut self, layout: &FlowLayout) -> Option<SelectionFormat> {
|
||||
let selection = self.editor.selection.clone()?;
|
||||
if selection.empty() || self.editor.composing() {
|
||||
return None;
|
||||
}
|
||||
let fresh = self
|
||||
.overlays
|
||||
.format_cache
|
||||
.as_ref()
|
||||
.is_some_and(|(rev, cached, _)| *rev == self.doc_rev && *cached == selection);
|
||||
if !fresh {
|
||||
let state = self.read_selection_format(&selection, layout);
|
||||
self.overlays.format_cache = Some((self.doc_rev, selection, state));
|
||||
}
|
||||
let (marks, align) = self.overlays.format_cache.as_ref()?.2.clone()?;
|
||||
Some(SelectionFormat {
|
||||
anchor_world: bounding_rect(&self.selection_rects(layout))?,
|
||||
marks,
|
||||
align,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn read_selection_format(
|
||||
&self,
|
||||
selection: &DocumentSelection,
|
||||
layout: &FlowLayout,
|
||||
) -> Option<(MarkState, Option<BlockAlign>)> {
|
||||
let (start, end, a, b, _) = selection.ordered(layout)?;
|
||||
let page = self.page()?;
|
||||
let mut marks: Option<MarkState> = None;
|
||||
// Every paragraph and list block the selection touches is aligned, empty ones too.
|
||||
let mut ids: Vec<&str> = Vec::new();
|
||||
for block in &layout.blocks[a..=b] {
|
||||
let id = block.block_id.as_str();
|
||||
if matches!(block.body.kind, FlowKind::Paragraph(_) | FlowKind::List(_)) {
|
||||
ids.push(id);
|
||||
}
|
||||
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.
|
||||
if !matches!(block.body.kind, FlowKind::Paragraph(_) | FlowKind::List(_)) {
|
||||
return None;
|
||||
}
|
||||
let (text, _) = page.read_editable_text(id).ok()?;
|
||||
let slice = marks_in_range(&text, from as usize, to as usize);
|
||||
marks = Some(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(|link| Some(link) == 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()),
|
||||
},
|
||||
});
|
||||
}
|
||||
let marks = marks?;
|
||||
let mut shared = None;
|
||||
shared_alignment(
|
||||
self.page_snapshot()?.root.as_ref()?,
|
||||
BlockAlign::Left,
|
||||
&ids,
|
||||
&mut shared,
|
||||
);
|
||||
Some((marks, shared.flatten()))
|
||||
}
|
||||
|
||||
/// Build what the overlays draw inside the page viewport for this frame, and the
|
||||
/// per-block paint state.
|
||||
pub(crate) fn overlay_page_layer(
|
||||
|
||||
@@ -0,0 +1,380 @@
|
||||
//! PlaygroundView glue for Bookmark toolbar, Callout toolbar/icon picker, `SelectBlock`
|
||||
//! (2-step LaTeX selection), and Edgeless Note LaTeX click interception.
|
||||
|
||||
use blocksuite_editor::clipboard::sanitize::sanitize_url;
|
||||
use blocksuite_playground_doc::{
|
||||
read::BlockContent,
|
||||
schema::{BlockSpec, ParagraphType},
|
||||
};
|
||||
use ui::{ClipboardItem, Context, Window, point, px};
|
||||
use y_octo::{Any, SessionValue, TextAttributes};
|
||||
|
||||
use crate::{
|
||||
PlaygroundMode, PlaygroundView,
|
||||
block_flow::{FlowKind, FlowLayout, FlowTextLayout},
|
||||
rich_text::DecorationKind,
|
||||
};
|
||||
|
||||
use super::{
|
||||
BlockMenuAction, BookmarkToolbarAction, CalloutAction, EquationTarget, OverlayEvent,
|
||||
embed_view_kind_for_url, find_parent,
|
||||
};
|
||||
|
||||
impl PlaygroundView {
|
||||
/// Single selected `affine:bookmark` block id in Page mode, if any.
|
||||
pub(crate) fn selected_bookmark_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::Bookmark))
|
||||
.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 {
|
||||
return None;
|
||||
}
|
||||
layout
|
||||
.block(&self.editor.block_selection[0])
|
||||
.filter(|b| matches!(b.body.kind, FlowKind::Callout))
|
||||
.map(|b| b.block_id.as_str())
|
||||
}
|
||||
|
||||
/// Single selected `affine:latex` block id in Page or Edgeless Note mode, if any.
|
||||
pub(super) fn selected_latex_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::Latex))
|
||||
.map(|b| b.block_id.as_str())
|
||||
}
|
||||
|
||||
/// Handle Bookmark, Callout, and `SelectBlock` overlay events in `PlaygroundView`.
|
||||
pub(super) fn handle_bookmark_and_callout_event(
|
||||
&mut self,
|
||||
event: &OverlayEvent,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> bool {
|
||||
match event {
|
||||
OverlayEvent::SelectBlock(block_id) => {
|
||||
self.editor_focus.focus(window, cx);
|
||||
self.set_block_selection(vec![block_id.clone()], false, window, cx);
|
||||
cx.notify();
|
||||
true
|
||||
}
|
||||
OverlayEvent::OpenBookmarkUrl(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();
|
||||
}
|
||||
true
|
||||
}
|
||||
OverlayEvent::CalloutAction {
|
||||
block_id,
|
||||
action: CalloutAction::Delete,
|
||||
} => {
|
||||
if !self.page_readonly
|
||||
&& let Err(error) = self.execute_block_menu_action(
|
||||
block_id,
|
||||
BlockMenuAction::Delete,
|
||||
window,
|
||||
cx,
|
||||
)
|
||||
{
|
||||
eprintln!("callout delete: {error}");
|
||||
}
|
||||
true
|
||||
}
|
||||
OverlayEvent::BookmarkToolbarAction { block_id, action } => {
|
||||
self.run_bookmark_toolbar_action(block_id, *action, window, cx);
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn run_bookmark_toolbar_action(
|
||||
&mut self,
|
||||
block_id: &str,
|
||||
action: BookmarkToolbarAction,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
let now_ms = self.now_ms(cx);
|
||||
let (url, bm_title, bm_desc, bm_caption) = self
|
||||
.snapshot
|
||||
.as_ref()
|
||||
.and_then(|s| s.block(block_id))
|
||||
.and_then(|n| match &n.content {
|
||||
BlockContent::Bookmark {
|
||||
url,
|
||||
title,
|
||||
description,
|
||||
caption,
|
||||
} => Some((
|
||||
url.clone(),
|
||||
title.clone(),
|
||||
description.clone(),
|
||||
caption.clone(),
|
||||
)),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_default();
|
||||
match action {
|
||||
BookmarkToolbarAction::Open => {
|
||||
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();
|
||||
}
|
||||
}
|
||||
BookmarkToolbarAction::Copy => {
|
||||
if !url.is_empty() {
|
||||
cx.write_to_clipboard(ClipboardItem::new_string(url));
|
||||
self.show_timed_context_toast("Link copied", cx);
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
BookmarkToolbarAction::Edit => {
|
||||
if !self.page_readonly {
|
||||
self.overlays
|
||||
.open_bookmark_edit_prompt(block_id.to_string(), url, now_ms);
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
BookmarkToolbarAction::Caption => {
|
||||
if !self.page_readonly {
|
||||
self.dispatch_overlay_event(
|
||||
OverlayEvent::OpenCaptionPrompt {
|
||||
block_id: block_id.to_string(),
|
||||
},
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
}
|
||||
}
|
||||
BookmarkToolbarAction::SetStyle(style) => {
|
||||
if self.page_readonly {
|
||||
return;
|
||||
}
|
||||
let before = self.selection_snapshot();
|
||||
let now = now_ms as u64;
|
||||
if let Ok(page) = self.page_mut() {
|
||||
let _ = page.stop_capturing();
|
||||
let commit = match page.set_block_prop(
|
||||
block_id,
|
||||
"prop:style",
|
||||
SessionValue::Any(Any::String(style.wire_value().to_string())),
|
||||
now,
|
||||
) {
|
||||
Ok(commit) => commit,
|
||||
Err(error) => {
|
||||
eprintln!("bookmark set style: {error}");
|
||||
None
|
||||
}
|
||||
};
|
||||
if commit.is_some()
|
||||
&& let Some(before) = before
|
||||
{
|
||||
let _ = page.set_undo_selection_snapshot(before);
|
||||
}
|
||||
let _ = page.stop_capturing();
|
||||
self.editor.last_typing = None;
|
||||
self.did_edit(commit, None, window, cx);
|
||||
}
|
||||
}
|
||||
BookmarkToolbarAction::ConvertToInline | BookmarkToolbarAction::ConvertToEmbed => {
|
||||
if self.page_readonly {
|
||||
return;
|
||||
}
|
||||
let Some(clean_url) = sanitize_url(&url).filter(|u| !u.starts_with('#')) else {
|
||||
return;
|
||||
};
|
||||
let Some(snapshot) = self.snapshot.clone() else {
|
||||
return;
|
||||
};
|
||||
let Some((parent, slot)) = snapshot
|
||||
.root
|
||||
.as_ref()
|
||||
.and_then(|root| find_parent(root, block_id))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let is_inline = action == BookmarkToolbarAction::ConvertToInline;
|
||||
let inline_label = bm_title
|
||||
.clone()
|
||||
.filter(|s| !s.is_empty())
|
||||
.or_else(|| (!bm_caption.is_empty()).then(|| bm_caption.clone()))
|
||||
.unwrap_or_else(|| clean_url.clone());
|
||||
let spec = if is_inline {
|
||||
BlockSpec::Paragraph {
|
||||
paragraph_type: ParagraphType::Text,
|
||||
text: inline_label.clone(),
|
||||
}
|
||||
} else {
|
||||
let Some(kind) = embed_view_kind_for_url(&clean_url) else {
|
||||
return;
|
||||
};
|
||||
BlockSpec::ExternalEmbed {
|
||||
kind,
|
||||
url: clean_url.clone(),
|
||||
title: bm_title,
|
||||
description: bm_desc,
|
||||
html: None,
|
||||
caption: bm_caption,
|
||||
}
|
||||
};
|
||||
let parent_id = parent.id.clone();
|
||||
let fresh = self.fresh_block_id();
|
||||
let now = now_ms as u64;
|
||||
let before = self.selection_snapshot();
|
||||
if let Ok(page) = self.page_mut() {
|
||||
let _ = page.stop_capturing();
|
||||
let commit = match page.structural_edit(now, |page| {
|
||||
page.add_block(&fresh, spec, Some(&parent_id), Some(slot as u64 + 1), now)?;
|
||||
if is_inline {
|
||||
let len = inline_label.encode_utf16().count() as u64;
|
||||
if len > 0 {
|
||||
page.format_text(
|
||||
&fresh,
|
||||
"prop:text",
|
||||
0,
|
||||
len,
|
||||
TextAttributes::from([(
|
||||
"link".to_string(),
|
||||
Any::String(clean_url.clone()),
|
||||
)]),
|
||||
now,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
page.delete_block_subtree(&parent_id, block_id, now)?;
|
||||
Ok(())
|
||||
}) {
|
||||
Ok(commit) => commit,
|
||||
Err(error) => {
|
||||
eprintln!("bookmark convert: {error}");
|
||||
None
|
||||
}
|
||||
};
|
||||
if commit.is_some() {
|
||||
if let Some(before) = before {
|
||||
let _ = page.set_undo_selection_snapshot(before);
|
||||
}
|
||||
let _ = page.stop_capturing();
|
||||
self.editor.last_typing = None;
|
||||
self.did_edit(commit, None, window, cx);
|
||||
self.set_block_selection(vec![fresh], false, window, cx);
|
||||
} else {
|
||||
let _ = page.stop_capturing();
|
||||
}
|
||||
}
|
||||
}
|
||||
BookmarkToolbarAction::Duplicate => {
|
||||
if !self.page_readonly
|
||||
&& let Err(error) = self.execute_block_menu_action(
|
||||
block_id,
|
||||
BlockMenuAction::Duplicate,
|
||||
window,
|
||||
cx,
|
||||
)
|
||||
{
|
||||
eprintln!("bookmark duplicate: {error}");
|
||||
}
|
||||
}
|
||||
BookmarkToolbarAction::Delete => {
|
||||
if !self.page_readonly
|
||||
&& let Err(error) = self.execute_block_menu_action(
|
||||
block_id,
|
||||
BlockMenuAction::Delete,
|
||||
window,
|
||||
cx,
|
||||
)
|
||||
{
|
||||
eprintln!("bookmark delete: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Intercept clicks on block-level `affine:latex` or inline `LatexChip` inside an active
|
||||
/// Edgeless Note edit session.
|
||||
pub(crate) fn try_click_edgeless_note_latex(
|
||||
&mut self,
|
||||
screen_x: f32,
|
||||
screen_y: f32,
|
||||
click_count: usize,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> bool {
|
||||
if self.mode != PlaygroundMode::Edgeless || self.edgeless_readonly {
|
||||
return false;
|
||||
}
|
||||
let Some((snapshot, layout, Some(transform))) = self.active_overlay_target() else {
|
||||
return false;
|
||||
};
|
||||
let (wx, wy) = transform.screen_to_local(screen_x, screen_y);
|
||||
for block in &layout.blocks {
|
||||
if !block.rect().contains(wx, wy) {
|
||||
continue;
|
||||
}
|
||||
if matches!(block.body.kind, FlowKind::Latex) {
|
||||
let already_selected = self.editor.block_selection.len() == 1
|
||||
&& self.editor.block_selection[0] == block.block_id;
|
||||
if already_selected || click_count >= 2 {
|
||||
let initial = snapshot
|
||||
.block(&block.block_id)
|
||||
.and_then(|n| match &n.content {
|
||||
BlockContent::Latex { latex } => Some(latex.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_default();
|
||||
self.dispatch_overlay_event(
|
||||
OverlayEvent::OpenEquationEditor {
|
||||
target: EquationTarget::Block {
|
||||
block_id: block.block_id.clone(),
|
||||
},
|
||||
initial,
|
||||
},
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
} else {
|
||||
self.set_block_selection(vec![block.block_id.clone()], false, window, cx);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if let Some(text) = &block.body.text
|
||||
&& let FlowTextLayout::Rich(rich) = &text.layout
|
||||
{
|
||||
let pt = point(px(wx - block.x - text.x), px(wy - block.y - text.y));
|
||||
for deco in rich.inline_decorations() {
|
||||
if let DecorationKind::LatexChip(latex) = &deco.kind
|
||||
&& deco.bounds.contains(&pt)
|
||||
{
|
||||
self.dispatch_overlay_event(
|
||||
OverlayEvent::OpenEquationEditor {
|
||||
target: EquationTarget::Inline {
|
||||
block_id: block.block_id.clone(),
|
||||
utf16_offset: deco.source_utf16.start,
|
||||
},
|
||||
initial: latex.clone(),
|
||||
},
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
@@ -51,76 +51,6 @@ impl PlaygroundView {
|
||||
self.editor.selection.as_ref()?.snapshot(self.page()?).ok()
|
||||
}
|
||||
|
||||
/// 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<Self>,
|
||||
) {
|
||||
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()?;
|
||||
// Prefer the Page-visible note owning `last.block_id`, never an edgeless-only note.
|
||||
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: 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();
|
||||
}
|
||||
}
|
||||
|
||||
/// Carry out one overlay edit as a single undo step and publish it.
|
||||
pub(super) fn run_overlay_edit(
|
||||
&mut self,
|
||||
@@ -142,17 +72,40 @@ impl PlaygroundView {
|
||||
.selection
|
||||
.as_ref()
|
||||
.map(|sel| sel.focus.block_id.clone())
|
||||
.or_else(|| self.editor.block_selection.first().cloned())
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
self.run_slash_command(&block_id, command, false, window, cx)
|
||||
}
|
||||
DocEdit::ColorMark { key, value } => self.format_color_mark(key, value, window, cx),
|
||||
DocEdit::Align(align) => self.format_selection(Some(align), None, window, cx),
|
||||
DocEdit::Align(align) => {
|
||||
if self.editor.selection.is_some() {
|
||||
self.format_selection(Some(align), None, window, cx)
|
||||
} else {
|
||||
self.align_block_selection(align, window, cx)
|
||||
}
|
||||
}
|
||||
DocEdit::Link {
|
||||
url,
|
||||
expected_prev_url,
|
||||
} => self.format_selection(None, Some((url, expected_prev_url)), window, cx),
|
||||
expected_prev_text,
|
||||
display_text,
|
||||
} => self.apply_link_with_display_text(
|
||||
url,
|
||||
expected_prev_url,
|
||||
expected_prev_text,
|
||||
display_text,
|
||||
window,
|
||||
cx,
|
||||
),
|
||||
DocEdit::InlineEquationFromSelection => {
|
||||
self.run_inline_equation_from_selection(window, cx)
|
||||
}
|
||||
DocEdit::CreateLinkedDocFromSelection => {
|
||||
self.run_create_linked_doc_from_selection(window, cx)
|
||||
}
|
||||
DocEdit::FormatMore(action) => self.run_format_more(action, window, cx),
|
||||
DocEdit::Equation { target, latex } => {
|
||||
self.equation_snapshot = None;
|
||||
match &target {
|
||||
@@ -257,6 +210,79 @@ impl PlaygroundView {
|
||||
self.editor.reveal = false;
|
||||
Ok(())
|
||||
}
|
||||
DocEdit::SetCalloutIcon { block_id, unicode } => {
|
||||
let before = self.selection_snapshot();
|
||||
let page = self.page_mut()?;
|
||||
page.stop_capturing()?;
|
||||
let commit = page.set_block_prop(
|
||||
&block_id,
|
||||
"prop:icon",
|
||||
blocksuite_playground_doc::schema::callout_icon_value(&unicode),
|
||||
now,
|
||||
)?;
|
||||
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);
|
||||
self.editor.reveal = false;
|
||||
Ok(())
|
||||
}
|
||||
DocEdit::SetReferenceAlias {
|
||||
block_id,
|
||||
utf16_offset,
|
||||
page_id,
|
||||
alias,
|
||||
} => {
|
||||
let Some(mut ref_obj) = self
|
||||
.page()
|
||||
.and_then(|p| p.read_editable_text(&block_id).ok())
|
||||
.and_then(|(doc_text, _)| {
|
||||
super::view_link_popup::reference_object_at(
|
||||
&doc_text,
|
||||
utf16_offset,
|
||||
&page_id,
|
||||
)
|
||||
})
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
match alias.filter(|t| !t.is_empty()) {
|
||||
Some(title) => {
|
||||
ref_obj.insert("title".to_string(), Any::String(title));
|
||||
}
|
||||
None => {
|
||||
ref_obj.remove("title");
|
||||
}
|
||||
}
|
||||
let prop_key = self.editable_prop_for_block(&block_id);
|
||||
let before = self.selection_snapshot();
|
||||
let page = self.page_mut()?;
|
||||
page.stop_capturing()?;
|
||||
let commit = page.format_text(
|
||||
&block_id,
|
||||
prop_key,
|
||||
utf16_offset as u64,
|
||||
1,
|
||||
TextAttributes::from([(
|
||||
"reference".to_string(),
|
||||
Any::Object(Box::new(ref_obj)),
|
||||
)]),
|
||||
now,
|
||||
)?;
|
||||
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, Some(&block_id), window, cx);
|
||||
Ok(())
|
||||
}
|
||||
DocEdit::ReorderMany {
|
||||
parent_id,
|
||||
child_ids,
|
||||
|
||||
@@ -97,7 +97,7 @@ impl PlaygroundView {
|
||||
}
|
||||
|
||||
/// Block id of a singly selected `affine:image` block in Page mode, if any.
|
||||
pub(super) fn selected_image_block_id<'a>(&self, layout: &'a FlowLayout) -> Option<&'a str> {
|
||||
pub(crate) fn selected_image_block_id<'a>(&self, layout: &'a FlowLayout) -> Option<&'a str> {
|
||||
if self.editor.selection.is_some() || self.editor.block_selection.len() != 1 {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,659 @@
|
||||
//! 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::{
|
||||
BlockMenuAction, EquationTarget, FormatMoreAction, MarkState, OverlayEvent, SelectionFormat,
|
||||
bounding_rect, marks_in_range, shared_alignment,
|
||||
};
|
||||
|
||||
fn slice_utf16(text: &str, start: usize, end: usize) -> String {
|
||||
let units: Vec<u16> = 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])
|
||||
}
|
||||
}
|
||||
|
||||
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 and alignment are read once per selection and document revision.
|
||||
pub(crate) fn selection_format(&mut self, layout: &FlowLayout) -> Option<SelectionFormat> {
|
||||
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(|(rev, cached, _)| *rev == self.doc_rev && *cached == selection);
|
||||
if !fresh {
|
||||
let state = self.read_selection_format(&selection, layout);
|
||||
self.overlays.format_cache = Some((self.doc_rev, selection.clone(), state));
|
||||
}
|
||||
let (marks, align) = self.overlays.format_cache.as_ref()?.2.clone()?;
|
||||
let selected_text = self.single_block_selected_text(&selection, layout);
|
||||
Some(SelectionFormat {
|
||||
anchor_world: bounding_rect(&self.selection_rects(layout))?,
|
||||
marks,
|
||||
align,
|
||||
selected_text,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn read_selection_format(
|
||||
&self,
|
||||
selection: &DocumentSelection,
|
||||
layout: &FlowLayout,
|
||||
) -> Option<(MarkState, Option<BlockAlign>)> {
|
||||
let (start, end, a, b, _) = selection.ordered(layout)?;
|
||||
let page = self.page()?;
|
||||
let mut marks: Option<MarkState> = None;
|
||||
// Every paragraph and list block the selection touches is aligned, empty ones too.
|
||||
let mut ids: Vec<&str> = Vec::new();
|
||||
for block in &layout.blocks[a..=b] {
|
||||
let id = block.block_id.as_str();
|
||||
if matches!(block.body.kind, FlowKind::Paragraph(_) | FlowKind::List(_)) {
|
||||
ids.push(id);
|
||||
}
|
||||
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 !matches!(block.body.kind, FlowKind::Paragraph(_) | FlowKind::List(_)) {
|
||||
if a == b {
|
||||
return None;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let (text, _) = page.read_editable_text(id).ok()?;
|
||||
let slice = marks_in_range(&text, from as usize, to as usize);
|
||||
marks = Some(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(|link| Some(link) == 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()),
|
||||
},
|
||||
});
|
||||
}
|
||||
let marks = marks?;
|
||||
let mut shared = None;
|
||||
shared_alignment(
|
||||
self.page_snapshot()?.root.as_ref()?,
|
||||
BlockAlign::Left,
|
||||
&ids,
|
||||
&mut shared,
|
||||
);
|
||||
Some((marks, shared.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<String> {
|
||||
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(&self, layout: &FlowLayout) -> Option<SelectionFormat> {
|
||||
if self.editor.block_selection.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let page = self.page()?;
|
||||
let mut rects: Vec<FlowRect> = Vec::new();
|
||||
let mut ids: Vec<&str> = Vec::new();
|
||||
let mut marks: Option<MarkState> = None;
|
||||
|
||||
for block_id in &self.editor.block_selection {
|
||||
let Some(block) = layout.block(block_id) else {
|
||||
continue;
|
||||
};
|
||||
if !matches!(block.body.kind, FlowKind::Paragraph(_) | FlowKind::List(_)) {
|
||||
continue;
|
||||
}
|
||||
rects.push(block.rect());
|
||||
ids.push(block.block_id.as_str());
|
||||
let len = block.body.plain.encode_utf16().count();
|
||||
if len > 0
|
||||
&& let Ok((text, _)) = page.read_editable_text(block_id)
|
||||
{
|
||||
let slice = marks_in_range(&text, 0, len);
|
||||
marks = Some(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()),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
if ids.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let anchor_world = bounding_rect(&rects)?;
|
||||
let mut shared = None;
|
||||
if let Some(root) = self.page_snapshot().and_then(|s| s.root.as_ref()) {
|
||||
shared_alignment(root, BlockAlign::Left, &ids, &mut shared);
|
||||
}
|
||||
Some(SelectionFormat {
|
||||
anchor_world,
|
||||
marks: marks.unwrap_or_default(),
|
||||
align: shared.flatten(),
|
||||
selected_text: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// 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<String>,
|
||||
expected_prev_url: Option<String>,
|
||||
expected_prev_text: Option<String>,
|
||||
display_text: Option<String>,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> 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();
|
||||
if shared.bold {
|
||||
attrs.insert("bold".to_string(), Any::True);
|
||||
}
|
||||
if shared.italic {
|
||||
attrs.insert("italic".to_string(), Any::True);
|
||||
}
|
||||
if shared.underline {
|
||||
attrs.insert("underline".to_string(), Any::True);
|
||||
}
|
||||
if shared.strike {
|
||||
attrs.insert("strike".to_string(), Any::True);
|
||||
}
|
||||
if shared.code {
|
||||
attrs.insert("code".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<Self>,
|
||||
) -> 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<Self>,
|
||||
) -> 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<Self>,
|
||||
) -> 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<Self>,
|
||||
) -> DocResult {
|
||||
let Some(layout) = self.flow_layout() else {
|
||||
return Ok(());
|
||||
};
|
||||
let ids: Vec<String> = 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<Self>,
|
||||
) -> 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<Self>,
|
||||
) {
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,519 @@
|
||||
//! Action handlers for the non-focus-stealing `link-popup` / `reference-popup` capsule:
|
||||
//! `Open`, `Edit`, `EditAlias`, `Copy`, `ConvertToCard`, `ConvertToEmbed`, and `Unlink`,
|
||||
//! matching BlockSuite `0.27.5` `link/configs/toolbar.ts` and `reference/configs/toolbar.ts`.
|
||||
|
||||
use blocksuite_playground_doc::schema::BlockSpec;
|
||||
use ui::{ClipboardItem, Context, Window};
|
||||
use y_octo::{Any, SessionValue, TextAttributes};
|
||||
|
||||
use crate::{
|
||||
PlaygroundView,
|
||||
editor_session::{DocPoint, DocumentSelection},
|
||||
};
|
||||
|
||||
use super::{
|
||||
LinkPopupAction, LinkPopupTarget, OverlayEvent, bounding_rect, card_embed_kind_for_url,
|
||||
embed_view_kind_for_url, find_parent, matching_link_subranges, reference_at,
|
||||
reference_object_at, sanitize_external_url,
|
||||
};
|
||||
|
||||
fn slice_utf16_range(text: &str, start: usize, end: usize) -> String {
|
||||
let units: Vec<u16> = 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])
|
||||
}
|
||||
}
|
||||
|
||||
impl PlaygroundView {
|
||||
/// Handle actions emitted by the lightweight link / `@reference` capsule.
|
||||
pub(in crate::overlays) fn handle_link_popup_event(
|
||||
&mut self,
|
||||
event: &OverlayEvent,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> bool {
|
||||
let OverlayEvent::LinkPopupAction(action) = event else {
|
||||
return false;
|
||||
};
|
||||
let Some(target) = self.overlays.link_popup().map(|p| p.target.clone()) else {
|
||||
return true;
|
||||
};
|
||||
let now_ms = self.now_ms(cx);
|
||||
match (action, target) {
|
||||
(LinkPopupAction::Open, LinkPopupTarget::Link { url, .. }) => {
|
||||
self.overlays.close_link_popup(now_ms);
|
||||
if let Some(clean) = sanitize_external_url(&url) {
|
||||
self.last_opened_link_url = Some(clean.clone());
|
||||
cx.open_url(&clean);
|
||||
}
|
||||
cx.notify();
|
||||
}
|
||||
(LinkPopupAction::Open, LinkPopupTarget::Reference { page_id, .. }) => {
|
||||
self.overlays.close_link_popup(now_ms);
|
||||
self.open_linked_doc(&page_id, Some(window), cx);
|
||||
}
|
||||
(
|
||||
LinkPopupAction::Edit,
|
||||
LinkPopupTarget::Link {
|
||||
block_id,
|
||||
start_utf16,
|
||||
end_utf16,
|
||||
url,
|
||||
},
|
||||
) => {
|
||||
self.overlays.close_link_popup(now_ms);
|
||||
if self.page_readonly {
|
||||
return true;
|
||||
}
|
||||
let live_spans = self
|
||||
.page()
|
||||
.and_then(|p| p.read_editable_text(&block_id).ok())
|
||||
.map(|(doc_text, _)| {
|
||||
matching_link_subranges(&doc_text, start_utf16, end_utf16, &url)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let caret_off = self
|
||||
.editor
|
||||
.selection
|
||||
.as_ref()
|
||||
.filter(|s| s.focus.block_id == block_id)
|
||||
.map(|s| s.focus.offset() as usize);
|
||||
let Some((live_start, live_end)) = caret_off
|
||||
.and_then(|off| {
|
||||
live_spans
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|(s, e)| off >= *s && off <= *e)
|
||||
})
|
||||
.or_else(|| live_spans.first().copied())
|
||||
else {
|
||||
cx.notify();
|
||||
return true;
|
||||
};
|
||||
self.select_document_range(
|
||||
DocumentSelection {
|
||||
anchor: DocPoint::new(&block_id, live_start as u64),
|
||||
focus: DocPoint::new(&block_id, live_end as u64),
|
||||
},
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
if let Some(layout) = self.flow_layout() {
|
||||
if let Some(mut fmt) = self.selection_format(&layout) {
|
||||
fmt.marks.link = Some(url);
|
||||
self.overlays.open_link_field(&fmt, now_ms);
|
||||
} else if let Some(anchor_world) = bounding_rect(&self.selection_rects(&layout))
|
||||
{
|
||||
let fmt = super::SelectionFormat {
|
||||
anchor_world,
|
||||
marks: super::MarkState {
|
||||
link: Some(url),
|
||||
..Default::default()
|
||||
},
|
||||
align: None,
|
||||
selected_text: None,
|
||||
};
|
||||
self.overlays
|
||||
.open_link_field_for_block(&fmt, Some(block_id), now_ms);
|
||||
}
|
||||
}
|
||||
cx.notify();
|
||||
}
|
||||
(
|
||||
LinkPopupAction::EditAlias,
|
||||
LinkPopupTarget::Reference {
|
||||
block_id,
|
||||
utf16_offset,
|
||||
page_id,
|
||||
title,
|
||||
..
|
||||
},
|
||||
) => {
|
||||
self.overlays.close_link_popup(now_ms);
|
||||
if self.page_readonly {
|
||||
return true;
|
||||
}
|
||||
self.overlays.open_reference_alias_prompt(
|
||||
block_id,
|
||||
utf16_offset,
|
||||
page_id,
|
||||
title,
|
||||
now_ms,
|
||||
);
|
||||
cx.notify();
|
||||
}
|
||||
(LinkPopupAction::Copy, LinkPopupTarget::Link { url, .. }) => {
|
||||
cx.write_to_clipboard(ClipboardItem::new_string(url));
|
||||
self.show_timed_context_toast("Link copied", cx);
|
||||
cx.notify();
|
||||
}
|
||||
(LinkPopupAction::Copy, LinkPopupTarget::Reference { page_id, .. }) => {
|
||||
cx.write_to_clipboard(ClipboardItem::new_string(format!("affine://doc/{page_id}")));
|
||||
self.show_timed_context_toast("Link copied", cx);
|
||||
cx.notify();
|
||||
}
|
||||
(
|
||||
LinkPopupAction::ConvertToCard | LinkPopupAction::ConvertToEmbed,
|
||||
LinkPopupTarget::Link {
|
||||
block_id,
|
||||
start_utf16,
|
||||
end_utf16,
|
||||
url,
|
||||
},
|
||||
) => {
|
||||
self.overlays.close_link_popup(now_ms);
|
||||
if self.page_readonly {
|
||||
return true;
|
||||
}
|
||||
let Some(clean_url) = sanitize_external_url(&url) else {
|
||||
cx.notify();
|
||||
return true;
|
||||
};
|
||||
let Some(snapshot) = self.snapshot.clone() else {
|
||||
return true;
|
||||
};
|
||||
let Some((parent, slot)) = snapshot
|
||||
.root
|
||||
.as_ref()
|
||||
.and_then(|root| find_parent(root, &block_id))
|
||||
else {
|
||||
return true;
|
||||
};
|
||||
let has_children = !parent.children[slot].children.is_empty();
|
||||
let Some((doc_text, _)) = self
|
||||
.page()
|
||||
.and_then(|p| p.read_editable_text(&block_id).ok())
|
||||
else {
|
||||
return true;
|
||||
};
|
||||
let live_spans = matching_link_subranges(&doc_text, start_utf16, end_utf16, &url);
|
||||
if live_spans.is_empty() {
|
||||
cx.notify();
|
||||
return true;
|
||||
}
|
||||
let total_utf16 = doc_text.plain.encode_utf16().count();
|
||||
let spans_entire_block =
|
||||
!has_children && live_spans.len() == 1 && live_spans[0] == (0, total_utf16);
|
||||
let link_label: String = live_spans
|
||||
.iter()
|
||||
.map(|&(s, e)| slice_utf16_range(&doc_text.plain, s, e))
|
||||
.collect();
|
||||
let title_opt =
|
||||
(!link_label.is_empty() && link_label != clean_url && link_label != url)
|
||||
.then_some(link_label);
|
||||
|
||||
let spec = if *action == LinkPopupAction::ConvertToEmbed {
|
||||
let Some(kind) = embed_view_kind_for_url(&clean_url) else {
|
||||
cx.notify();
|
||||
return true;
|
||||
};
|
||||
BlockSpec::ExternalEmbed {
|
||||
kind,
|
||||
url: clean_url,
|
||||
title: None,
|
||||
description: None,
|
||||
html: None,
|
||||
caption: String::new(),
|
||||
}
|
||||
} else if let Some(card_kind) = card_embed_kind_for_url(&clean_url) {
|
||||
BlockSpec::ExternalEmbed {
|
||||
kind: card_kind,
|
||||
url: clean_url,
|
||||
title: title_opt,
|
||||
description: None,
|
||||
html: None,
|
||||
caption: String::new(),
|
||||
}
|
||||
} else {
|
||||
BlockSpec::Bookmark {
|
||||
url: clean_url,
|
||||
title: title_opt,
|
||||
description: None,
|
||||
}
|
||||
};
|
||||
let prop_key = self.editable_prop_for_block(&block_id);
|
||||
let parent_id = parent.id.clone();
|
||||
let new_id = self.fresh_block_id();
|
||||
let before = self.selection_snapshot();
|
||||
let now = now_ms as u64;
|
||||
if let Ok(page) = self.page_mut()
|
||||
&& let Ok(commit) = page.structural_edit(now, |page| {
|
||||
page.add_block(
|
||||
&new_id,
|
||||
spec,
|
||||
Some(&parent_id),
|
||||
Some(slot as u64 + 1),
|
||||
now,
|
||||
)?;
|
||||
if spans_entire_block {
|
||||
page.delete_block_subtree(&parent_id, &block_id, now)?;
|
||||
} else {
|
||||
for (seg_start, seg_end) in &live_spans {
|
||||
let seg_len = seg_end.saturating_sub(*seg_start) as u64;
|
||||
if seg_len > 0 {
|
||||
page.format_text(
|
||||
&block_id,
|
||||
prop_key,
|
||||
*seg_start as u64,
|
||||
seg_len,
|
||||
TextAttributes::from([("link".to_string(), Any::Null)]),
|
||||
now,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
{
|
||||
if commit.is_some() {
|
||||
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![new_id], false, window, cx);
|
||||
}
|
||||
}
|
||||
}
|
||||
(
|
||||
LinkPopupAction::ConvertToCard | LinkPopupAction::ConvertToEmbed,
|
||||
LinkPopupTarget::Reference {
|
||||
block_id,
|
||||
utf16_offset,
|
||||
page_id,
|
||||
..
|
||||
},
|
||||
) => {
|
||||
self.overlays.close_link_popup(now_ms);
|
||||
if self.page_readonly {
|
||||
return true;
|
||||
}
|
||||
let Some((doc_text, _)) = self
|
||||
.page()
|
||||
.and_then(|p| p.read_editable_text(&block_id).ok())
|
||||
else {
|
||||
cx.notify();
|
||||
return true;
|
||||
};
|
||||
let Some(ref_obj) = reference_object_at(&doc_text, utf16_offset, &page_id) else {
|
||||
cx.notify();
|
||||
return true;
|
||||
};
|
||||
let (can_convert, can_embed) =
|
||||
self.reference_conversion_flags(&block_id, &page_id, &doc_text, utf16_offset);
|
||||
let is_embed = *action == LinkPopupAction::ConvertToEmbed;
|
||||
if !can_convert || (is_embed && !can_embed) {
|
||||
cx.notify();
|
||||
return true;
|
||||
}
|
||||
let Some(snapshot) = self.snapshot.clone() else {
|
||||
return true;
|
||||
};
|
||||
let Some((parent, slot)) = snapshot
|
||||
.root
|
||||
.as_ref()
|
||||
.and_then(|root| find_parent(root, &block_id))
|
||||
else {
|
||||
return true;
|
||||
};
|
||||
let has_children = !parent.children[slot].children.is_empty();
|
||||
let total_utf16 = doc_text.plain.encode_utf16().count();
|
||||
let spans_entire_block = !has_children && total_utf16 == 1 && utf16_offset == 0;
|
||||
let alias_title = ref_obj.get("title").and_then(|v| match v {
|
||||
Any::String(s) if !s.is_empty() => Some(s.clone()),
|
||||
_ => None,
|
||||
});
|
||||
let doc_title =
|
||||
self.resolve_ref_title(&page_id, alias_title.as_deref().unwrap_or(""));
|
||||
let ref_description = ref_obj.get("description").cloned();
|
||||
let ref_params = ref_obj.get("params").cloned();
|
||||
|
||||
let prop_key = self.editable_prop_for_block(&block_id);
|
||||
let parent_id = parent.id.clone();
|
||||
let new_id = self.fresh_block_id();
|
||||
let spec = if is_embed {
|
||||
BlockSpec::EmbedSyncedDoc {
|
||||
page_id: page_id.clone(),
|
||||
caption: String::new(),
|
||||
}
|
||||
} else {
|
||||
BlockSpec::EmbedLinkedDoc {
|
||||
page_id: page_id.clone(),
|
||||
style: "horizontal".to_string(),
|
||||
caption: String::new(),
|
||||
}
|
||||
};
|
||||
let before = self.selection_snapshot();
|
||||
let now = now_ms as u64;
|
||||
if let Ok(page) = self.page_mut()
|
||||
&& let Ok(commit) = page.structural_edit(now, |page| {
|
||||
page.add_block(
|
||||
&new_id,
|
||||
spec,
|
||||
Some(&parent_id),
|
||||
Some(slot as u64 + 1),
|
||||
now,
|
||||
)?;
|
||||
if let Some(params_val) = ref_params {
|
||||
page.set_block_prop(
|
||||
&new_id,
|
||||
"prop:params",
|
||||
SessionValue::Any(params_val),
|
||||
now,
|
||||
)?;
|
||||
}
|
||||
if !is_embed {
|
||||
if let Some(t) = alias_title {
|
||||
page.set_block_prop(
|
||||
&new_id,
|
||||
"prop:title",
|
||||
SessionValue::Any(Any::String(t)),
|
||||
now,
|
||||
)?;
|
||||
}
|
||||
if let Some(desc_val) = ref_description {
|
||||
page.set_block_prop(
|
||||
&new_id,
|
||||
"prop:description",
|
||||
SessionValue::Any(desc_val),
|
||||
now,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
if spans_entire_block {
|
||||
page.delete_block_subtree(&parent_id, &block_id, now)?;
|
||||
} else {
|
||||
page.remove_text(&block_id, prop_key, utf16_offset as u64, 1, now)?;
|
||||
if !doc_title.is_empty() {
|
||||
page.insert_text(
|
||||
&block_id,
|
||||
prop_key,
|
||||
utf16_offset as u64,
|
||||
&doc_title,
|
||||
now,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
{
|
||||
if commit.is_some() {
|
||||
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![new_id], false, window, cx);
|
||||
}
|
||||
}
|
||||
}
|
||||
(
|
||||
LinkPopupAction::Unlink,
|
||||
LinkPopupTarget::Link {
|
||||
block_id,
|
||||
start_utf16,
|
||||
end_utf16,
|
||||
url,
|
||||
},
|
||||
) => {
|
||||
self.overlays.close_link_popup(now_ms);
|
||||
if self.page_readonly {
|
||||
return true;
|
||||
}
|
||||
let live_spans = self
|
||||
.page()
|
||||
.and_then(|p| p.read_editable_text(&block_id).ok())
|
||||
.map(|(doc_text, _)| {
|
||||
matching_link_subranges(&doc_text, start_utf16, end_utf16, &url)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
if live_spans.is_empty() {
|
||||
cx.notify();
|
||||
return true;
|
||||
}
|
||||
let prop_key = self.editable_prop_for_block(&block_id);
|
||||
let before = self.selection_snapshot();
|
||||
let now = now_ms as u64;
|
||||
if let Ok(page) = self.page_mut()
|
||||
&& let Ok(commit) = page.structural_edit(now, |page| {
|
||||
for (seg_start, seg_end) in &live_spans {
|
||||
let seg_len = seg_end.saturating_sub(*seg_start) as u64;
|
||||
if seg_len > 0 {
|
||||
page.format_text(
|
||||
&block_id,
|
||||
prop_key,
|
||||
*seg_start as u64,
|
||||
seg_len,
|
||||
TextAttributes::from([("link".to_string(), Any::Null)]),
|
||||
now,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
{
|
||||
if commit.is_some()
|
||||
&& let Some(before) = before
|
||||
{
|
||||
let _ = page.set_undo_selection_snapshot(before);
|
||||
}
|
||||
self.editor.last_typing = None;
|
||||
self.did_edit(commit, Some(&block_id), window, cx);
|
||||
}
|
||||
}
|
||||
(
|
||||
LinkPopupAction::Unlink,
|
||||
LinkPopupTarget::Reference {
|
||||
block_id,
|
||||
utf16_offset,
|
||||
page_id,
|
||||
..
|
||||
},
|
||||
) => {
|
||||
self.overlays.close_link_popup(now_ms);
|
||||
if self.page_readonly {
|
||||
return true;
|
||||
}
|
||||
let still_matches = self
|
||||
.page()
|
||||
.and_then(|p| p.read_editable_text(&block_id).ok())
|
||||
.is_some_and(|(doc_text, _)| {
|
||||
reference_at(&doc_text, utf16_offset).as_ref()
|
||||
== Some(&(utf16_offset, page_id.clone()))
|
||||
});
|
||||
if !still_matches {
|
||||
cx.notify();
|
||||
return true;
|
||||
}
|
||||
let prop_key = self.editable_prop_for_block(&block_id);
|
||||
let before = self.selection_snapshot();
|
||||
let now = now_ms as u64;
|
||||
if let Ok(page) = self.page_mut()
|
||||
&& let Ok(commit) = page.structural_edit(now, |page| {
|
||||
page.remove_text(&block_id, prop_key, utf16_offset as u64, 1, now)?;
|
||||
Ok(())
|
||||
})
|
||||
{
|
||||
if commit.is_some()
|
||||
&& let Some(before) = before
|
||||
{
|
||||
let _ = page.set_undo_selection_snapshot(before);
|
||||
}
|
||||
self.editor.selection = Some(DocumentSelection::caret(DocPoint::new(
|
||||
&block_id,
|
||||
utf16_offset as u64,
|
||||
)));
|
||||
self.editor.last_typing = None;
|
||||
self.did_edit(commit, Some(&block_id), window, cx);
|
||||
}
|
||||
}
|
||||
(LinkPopupAction::Edit, LinkPopupTarget::Reference { .. })
|
||||
| (LinkPopupAction::EditAlias, LinkPopupTarget::Link { .. }) => {}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
+179
-291
@@ -1,20 +1,24 @@
|
||||
//! PlaygroundView glue for the non-focus-stealing `link-popup` / `reference-popup` capsule:
|
||||
//! desktop hover + caret tracking, mobile edit-mode single-tap capsule (no accidental jumps),
|
||||
//! and `Open` / `Edit` / `Copy` / `Card` / `Unlink` actions.
|
||||
//! desktop 500ms hover + caret tracking, mobile edit-mode single-tap capsule (no accidental jumps),
|
||||
//! and `Open` / `Edit` / `Alias` / `Copy` / `Card` / `Embed` / `Unlink` actions.
|
||||
|
||||
mod actions;
|
||||
|
||||
use blocksuite_editor::clipboard::sanitize::sanitize_url;
|
||||
use blocksuite_playground_doc::schema::BlockSpec;
|
||||
use ui::{ClipboardItem, Context, Window, point, px};
|
||||
use y_octo::{Any, TextAttributes, TextDeltaOp, TextInsert};
|
||||
use ui::{Context, Window, point, px};
|
||||
use y_octo::{Any, TextDeltaOp, TextInsert};
|
||||
|
||||
use crate::{
|
||||
FormFactor, PlaygroundMode, PlaygroundView, TOPBAR_HEIGHT,
|
||||
block_flow::{FlowBlock, FlowLayout, FlowRect, FlowTextLayout},
|
||||
editor_session::{DocPoint, DocumentSelection},
|
||||
rich_text::DecorationKind,
|
||||
};
|
||||
|
||||
use super::{CONTEXT_TOAST_MS, LinkPopupAction, LinkPopupTarget, OverlayEvent, find_parent};
|
||||
use super::{
|
||||
CONTEXT_TOAST_MS, LINK_HOVER_DELAY_MS, LinkPopupAction, LinkPopupTarget, MarkState,
|
||||
OverlayEvent, SelectionFormat, bounding_rect, card_embed_kind_for_url, embed_view_kind_for_url,
|
||||
find_parent,
|
||||
};
|
||||
|
||||
fn sanitize_external_url(raw: &str) -> Option<String> {
|
||||
let clean = sanitize_url(raw)?;
|
||||
@@ -116,7 +120,7 @@ pub(super) fn matching_link_subranges(
|
||||
}
|
||||
|
||||
/// Find an inline `LinkedPage` reference chip at UTF-16 `offset` (or immediately before caret).
|
||||
fn reference_at(
|
||||
pub(super) fn reference_at(
|
||||
rich: &blocksuite_playground_doc::read::RichText,
|
||||
offset: usize,
|
||||
) -> Option<(usize, String)> {
|
||||
@@ -143,6 +147,71 @@ fn reference_at(
|
||||
None
|
||||
}
|
||||
|
||||
/// Read and clone the live `reference` `Any::Object` at exact `utf16_offset` if its `pageId` matches.
|
||||
pub(super) fn reference_object_at(
|
||||
rich: &blocksuite_playground_doc::read::RichText,
|
||||
utf16_offset: usize,
|
||||
expected_page_id: &str,
|
||||
) -> Option<y_octo::AHashMap<String, Any>> {
|
||||
let mut pos = 0usize;
|
||||
for op in &rich.delta {
|
||||
let TextDeltaOp::Insert { insert, format } = op else {
|
||||
continue;
|
||||
};
|
||||
let len = match insert {
|
||||
TextInsert::Text(s) => s.encode_utf16().count(),
|
||||
TextInsert::Embed(_) => 1,
|
||||
};
|
||||
if pos == utf16_offset
|
||||
&& len == 1
|
||||
&& let Some(Any::Object(obj)) = format.as_ref().and_then(|a| a.get("reference"))
|
||||
&& matches!(obj.get("type"), Some(Any::String(t)) if t == "LinkedPage")
|
||||
&& matches!(obj.get("pageId"), Some(Any::String(pid)) if pid == expected_page_id)
|
||||
{
|
||||
return Some((**obj).clone());
|
||||
}
|
||||
pos += len;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn has_block_or_element_params(ref_obj: &y_octo::AHashMap<String, Any>) -> bool {
|
||||
let Some(Any::Object(params)) = ref_obj.get("params") else {
|
||||
return false;
|
||||
};
|
||||
let non_empty = |key: &str| match params.get(key) {
|
||||
Some(Any::Array(a)) => !a.is_empty(),
|
||||
Some(Any::String(s)) => !s.is_empty(),
|
||||
_ => false,
|
||||
};
|
||||
non_empty("blockIds") || non_empty("elementIds")
|
||||
}
|
||||
|
||||
fn block_has_ancestor_flavour(
|
||||
node: &blocksuite_playground_doc::read::BlockNode,
|
||||
target_id: &str,
|
||||
flavours: &[&str],
|
||||
) -> bool {
|
||||
fn walk(
|
||||
cur: &blocksuite_playground_doc::read::BlockNode,
|
||||
target_id: &str,
|
||||
flavours: &[&str],
|
||||
in_match: bool,
|
||||
) -> Option<bool> {
|
||||
let now_match = in_match || flavours.contains(&cur.flavour.as_str());
|
||||
if cur.id == target_id {
|
||||
return Some(now_match);
|
||||
}
|
||||
for child in &cur.children {
|
||||
if let Some(found) = walk(child, target_id, flavours, now_match) {
|
||||
return Some(found);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
walk(node, target_id, flavours, false).unwrap_or(false)
|
||||
}
|
||||
|
||||
impl PlaygroundView {
|
||||
/// Show a scheduler-timed transient context toast (2.2s), reusing the single `context_toast`.
|
||||
pub(crate) fn show_timed_context_toast(&mut self, message: &str, cx: &mut Context<Self>) {
|
||||
@@ -213,12 +282,20 @@ impl PlaygroundView {
|
||||
})?;
|
||||
let title =
|
||||
self.resolve_ref_title(&r.page_id, r.title.as_deref().unwrap_or(""));
|
||||
let (can_convert, can_embed) = self.reference_conversion_flags(
|
||||
&block.block_id,
|
||||
&r.page_id,
|
||||
&doc_text,
|
||||
off,
|
||||
);
|
||||
return Some((
|
||||
LinkPopupTarget::Reference {
|
||||
block_id: block.block_id.clone(),
|
||||
utf16_offset: off,
|
||||
page_id: r.page_id.clone(),
|
||||
title,
|
||||
can_convert,
|
||||
can_embed,
|
||||
},
|
||||
world_rect,
|
||||
));
|
||||
@@ -248,6 +325,34 @@ impl PlaygroundView {
|
||||
None
|
||||
}
|
||||
|
||||
pub(super) fn reference_conversion_flags(
|
||||
&self,
|
||||
block_id: &str,
|
||||
page_id: &str,
|
||||
doc_text: &blocksuite_playground_doc::read::RichText,
|
||||
utf16_offset: usize,
|
||||
) -> (bool, bool) {
|
||||
let root = self.snapshot.as_ref().and_then(|s| s.root.as_ref());
|
||||
let in_table_or_db = root.is_some_and(|r| {
|
||||
block_has_ancestor_flavour(r, block_id, &["affine:table", "affine:database"])
|
||||
});
|
||||
let can_convert = !in_table_or_db;
|
||||
let in_edgeless_or_synced = root.is_some_and(|r| {
|
||||
block_has_ancestor_flavour(
|
||||
r,
|
||||
block_id,
|
||||
&["affine:edgeless-text", "affine:embed-synced-doc"],
|
||||
)
|
||||
});
|
||||
let links_to_node = reference_object_at(doc_text, utf16_offset, page_id)
|
||||
.is_some_and(|obj| has_block_or_element_params(&obj));
|
||||
let can_embed = can_convert
|
||||
&& Some(page_id) != self.page_id.as_deref()
|
||||
&& !in_edgeless_or_synced
|
||||
&& !links_to_node;
|
||||
(can_convert, can_embed)
|
||||
}
|
||||
|
||||
pub(super) fn editable_prop_for_block(&self, block_id: &str) -> &'static str {
|
||||
if self
|
||||
.snapshot
|
||||
@@ -286,6 +391,7 @@ impl PlaygroundView {
|
||||
anchor_world,
|
||||
marks,
|
||||
align: None,
|
||||
selected_text: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -354,12 +460,54 @@ impl PlaygroundView {
|
||||
}
|
||||
}
|
||||
if let Some((target, anchor_world)) = self.hit_link_popup_target_at(x, y, window) {
|
||||
self.overlays
|
||||
.open_link_popup(target, anchor_world, true, now_ms);
|
||||
cx.notify();
|
||||
} else if self.overlays.link_popup().is_some_and(|p| p.from_hover) {
|
||||
self.overlays.close_link_popup(now_ms);
|
||||
cx.notify();
|
||||
if self
|
||||
.overlays
|
||||
.link_popup()
|
||||
.is_some_and(|p| p.target == target)
|
||||
{
|
||||
self.pending_link_hover = 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;
|
||||
}
|
||||
if let Some((pending_target, pending_anchor, _)) =
|
||||
this.pending_link_hover.take()
|
||||
{
|
||||
let now_ms = this.now_ms(cx);
|
||||
this.overlays
|
||||
.open_link_popup(pending_target, pending_anchor, true, now_ms);
|
||||
cx.notify();
|
||||
}
|
||||
});
|
||||
}));
|
||||
} 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);
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -417,15 +565,25 @@ impl PlaygroundView {
|
||||
self.last_link_popup_caret = Some(caret_key);
|
||||
let block_id = &sel.focus.block_id;
|
||||
let offset = sel.focus.offset() as usize;
|
||||
let Some(block) = layout.block(block_id) else {
|
||||
return;
|
||||
};
|
||||
let may_have_links_or_refs = block.body.text.as_ref().is_some_and(|t| match &t.layout {
|
||||
FlowTextLayout::Rich(r) => !r.inline_decorations().is_empty(),
|
||||
FlowTextLayout::Plain(_) => true,
|
||||
});
|
||||
if !may_have_links_or_refs {
|
||||
if self.overlays.link_popup().is_some_and(|p| !p.from_hover) {
|
||||
self.overlays.close_link_popup(now_ms);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let Some(page) = self.page() else {
|
||||
return;
|
||||
};
|
||||
let Ok((doc_text, _)) = page.read_editable_text(block_id) else {
|
||||
return;
|
||||
};
|
||||
let Some(block) = layout.block(block_id) else {
|
||||
return;
|
||||
};
|
||||
let Some(anchor_world) = block.caret_rect(sel.focus.caret) else {
|
||||
return;
|
||||
};
|
||||
@@ -463,12 +621,16 @@ impl PlaygroundView {
|
||||
}) {
|
||||
if auto_open {
|
||||
let title = self.resolve_ref_title(&page_id, "");
|
||||
let (can_convert, can_embed) =
|
||||
self.reference_conversion_flags(block_id, &page_id, &doc_text, ref_off);
|
||||
self.overlays.open_link_popup(
|
||||
LinkPopupTarget::Reference {
|
||||
block_id: block_id.clone(),
|
||||
utf16_offset: ref_off,
|
||||
page_id,
|
||||
title,
|
||||
can_convert,
|
||||
can_embed,
|
||||
},
|
||||
deco_world(ref_off..ref_off + 1),
|
||||
false,
|
||||
@@ -493,278 +655,4 @@ impl PlaygroundView {
|
||||
self.overlays.close_link_popup(now_ms);
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle actions emitted by the lightweight link / `@reference` capsule.
|
||||
pub(super) fn handle_link_popup_event(
|
||||
&mut self,
|
||||
event: &OverlayEvent,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> bool {
|
||||
let OverlayEvent::LinkPopupAction(action) = event else {
|
||||
return false;
|
||||
};
|
||||
let Some(target) = self.overlays.link_popup().map(|p| p.target.clone()) else {
|
||||
return true;
|
||||
};
|
||||
let now_ms = self.now_ms(cx);
|
||||
match (action, target) {
|
||||
(LinkPopupAction::Open, LinkPopupTarget::Link { url, .. }) => {
|
||||
self.overlays.close_link_popup(now_ms);
|
||||
if let Some(clean) = sanitize_external_url(&url) {
|
||||
self.last_opened_link_url = Some(clean.clone());
|
||||
cx.open_url(&clean);
|
||||
}
|
||||
cx.notify();
|
||||
}
|
||||
(LinkPopupAction::Open, LinkPopupTarget::Reference { page_id, .. }) => {
|
||||
self.overlays.close_link_popup(now_ms);
|
||||
self.open_linked_doc(&page_id, Some(window), cx);
|
||||
}
|
||||
(
|
||||
LinkPopupAction::Edit,
|
||||
LinkPopupTarget::Link {
|
||||
block_id,
|
||||
start_utf16,
|
||||
end_utf16,
|
||||
url,
|
||||
},
|
||||
) => {
|
||||
self.overlays.close_link_popup(now_ms);
|
||||
if self.page_readonly {
|
||||
return true;
|
||||
}
|
||||
let live_spans = self
|
||||
.page()
|
||||
.and_then(|p| p.read_editable_text(&block_id).ok())
|
||||
.map(|(doc_text, _)| {
|
||||
matching_link_subranges(&doc_text, start_utf16, end_utf16, &url)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let caret_off = self
|
||||
.editor
|
||||
.selection
|
||||
.as_ref()
|
||||
.filter(|s| s.focus.block_id == block_id)
|
||||
.map(|s| s.focus.offset() as usize);
|
||||
let Some((live_start, live_end)) = caret_off
|
||||
.and_then(|off| {
|
||||
live_spans
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|(s, e)| off >= *s && off <= *e)
|
||||
})
|
||||
.or_else(|| live_spans.first().copied())
|
||||
else {
|
||||
cx.notify();
|
||||
return true;
|
||||
};
|
||||
self.select_document_range(
|
||||
DocumentSelection {
|
||||
anchor: DocPoint::new(&block_id, live_start as u64),
|
||||
focus: DocPoint::new(&block_id, live_end as u64),
|
||||
},
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
if let Some(layout) = self.flow_layout() {
|
||||
if let Some(mut fmt) = self.selection_format(&layout) {
|
||||
fmt.marks.link = Some(url);
|
||||
self.overlays.open_link_field(&fmt, now_ms);
|
||||
} else if let Some(anchor_world) =
|
||||
super::bounding_rect(&self.selection_rects(&layout))
|
||||
{
|
||||
let fmt = super::SelectionFormat {
|
||||
anchor_world,
|
||||
marks: super::MarkState {
|
||||
link: Some(url),
|
||||
..Default::default()
|
||||
},
|
||||
align: None,
|
||||
};
|
||||
self.overlays
|
||||
.open_link_field_for_block(&fmt, Some(block_id), now_ms);
|
||||
}
|
||||
}
|
||||
cx.notify();
|
||||
}
|
||||
(LinkPopupAction::Copy, LinkPopupTarget::Link { url, .. }) => {
|
||||
cx.write_to_clipboard(ClipboardItem::new_string(url));
|
||||
self.show_timed_context_toast("Link copied", cx);
|
||||
cx.notify();
|
||||
}
|
||||
(LinkPopupAction::Copy, LinkPopupTarget::Reference { page_id, .. }) => {
|
||||
cx.write_to_clipboard(ClipboardItem::new_string(format!("affine://doc/{page_id}")));
|
||||
self.show_timed_context_toast("Link copied", cx);
|
||||
cx.notify();
|
||||
}
|
||||
(
|
||||
LinkPopupAction::ConvertToCard,
|
||||
LinkPopupTarget::Reference {
|
||||
block_id,
|
||||
utf16_offset,
|
||||
page_id,
|
||||
..
|
||||
},
|
||||
) => {
|
||||
self.overlays.close_link_popup(now_ms);
|
||||
if self.page_readonly {
|
||||
return true;
|
||||
}
|
||||
let still_matches = self
|
||||
.page()
|
||||
.and_then(|p| p.read_editable_text(&block_id).ok())
|
||||
.is_some_and(|(doc_text, _)| {
|
||||
reference_at(&doc_text, utf16_offset).as_ref()
|
||||
== Some(&(utf16_offset, page_id.clone()))
|
||||
});
|
||||
if !still_matches {
|
||||
cx.notify();
|
||||
return true;
|
||||
}
|
||||
let Some(snapshot) = self.snapshot.clone() else {
|
||||
return true;
|
||||
};
|
||||
let Some((parent, slot)) = snapshot
|
||||
.root
|
||||
.as_ref()
|
||||
.and_then(|root| find_parent(root, &block_id))
|
||||
else {
|
||||
return true;
|
||||
};
|
||||
let prop_key = self.editable_prop_for_block(&block_id);
|
||||
let parent_id = parent.id.clone();
|
||||
let new_id = self.fresh_block_id();
|
||||
let before = self.selection_snapshot();
|
||||
let now = now_ms as u64;
|
||||
if let Ok(page) = self.page_mut()
|
||||
&& let Ok(commit) = page.structural_edit(now, |page| {
|
||||
page.remove_text(&block_id, prop_key, utf16_offset as u64, 1, now)?;
|
||||
page.add_block(
|
||||
&new_id,
|
||||
BlockSpec::EmbedLinkedDoc {
|
||||
page_id,
|
||||
style: "horizontal".to_string(),
|
||||
caption: String::new(),
|
||||
},
|
||||
Some(&parent_id),
|
||||
Some(slot as u64 + 1),
|
||||
now,
|
||||
)?;
|
||||
Ok(())
|
||||
})
|
||||
{
|
||||
if commit.is_some()
|
||||
&& let Some(before) = before
|
||||
{
|
||||
let _ = page.set_undo_selection_snapshot(before);
|
||||
}
|
||||
self.editor.last_typing = None;
|
||||
self.did_edit(commit, None, window, cx);
|
||||
}
|
||||
}
|
||||
(
|
||||
LinkPopupAction::Unlink,
|
||||
LinkPopupTarget::Link {
|
||||
block_id,
|
||||
start_utf16,
|
||||
end_utf16,
|
||||
url,
|
||||
},
|
||||
) => {
|
||||
self.overlays.close_link_popup(now_ms);
|
||||
if self.page_readonly {
|
||||
return true;
|
||||
}
|
||||
let live_spans = self
|
||||
.page()
|
||||
.and_then(|p| p.read_editable_text(&block_id).ok())
|
||||
.map(|(doc_text, _)| {
|
||||
matching_link_subranges(&doc_text, start_utf16, end_utf16, &url)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
if live_spans.is_empty() {
|
||||
cx.notify();
|
||||
return true;
|
||||
}
|
||||
let prop_key = self.editable_prop_for_block(&block_id);
|
||||
let before = self.selection_snapshot();
|
||||
let now = now_ms as u64;
|
||||
if let Ok(page) = self.page_mut()
|
||||
&& let Ok(commit) = page.structural_edit(now, |page| {
|
||||
for (seg_start, seg_end) in &live_spans {
|
||||
let seg_len = seg_end.saturating_sub(*seg_start) as u64;
|
||||
if seg_len > 0 {
|
||||
page.format_text(
|
||||
&block_id,
|
||||
prop_key,
|
||||
*seg_start as u64,
|
||||
seg_len,
|
||||
TextAttributes::from([("link".to_string(), Any::Null)]),
|
||||
now,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
{
|
||||
if commit.is_some()
|
||||
&& let Some(before) = before
|
||||
{
|
||||
let _ = page.set_undo_selection_snapshot(before);
|
||||
}
|
||||
self.editor.last_typing = None;
|
||||
self.did_edit(commit, Some(&block_id), window, cx);
|
||||
}
|
||||
}
|
||||
(
|
||||
LinkPopupAction::Unlink,
|
||||
LinkPopupTarget::Reference {
|
||||
block_id,
|
||||
utf16_offset,
|
||||
page_id,
|
||||
..
|
||||
},
|
||||
) => {
|
||||
self.overlays.close_link_popup(now_ms);
|
||||
if self.page_readonly {
|
||||
return true;
|
||||
}
|
||||
let still_matches = self
|
||||
.page()
|
||||
.and_then(|p| p.read_editable_text(&block_id).ok())
|
||||
.is_some_and(|(doc_text, _)| {
|
||||
reference_at(&doc_text, utf16_offset).as_ref()
|
||||
== Some(&(utf16_offset, page_id.clone()))
|
||||
});
|
||||
if !still_matches {
|
||||
cx.notify();
|
||||
return true;
|
||||
}
|
||||
let prop_key = self.editable_prop_for_block(&block_id);
|
||||
let before = self.selection_snapshot();
|
||||
let now = now_ms as u64;
|
||||
if let Ok(page) = self.page_mut()
|
||||
&& let Ok(commit) = page.structural_edit(now, |page| {
|
||||
page.remove_text(&block_id, prop_key, utf16_offset as u64, 1, now)?;
|
||||
Ok(())
|
||||
})
|
||||
{
|
||||
if commit.is_some()
|
||||
&& let Some(before) = before
|
||||
{
|
||||
let _ = page.set_undo_selection_snapshot(before);
|
||||
}
|
||||
self.editor.selection = Some(DocumentSelection::caret(DocPoint::new(
|
||||
&block_id,
|
||||
utf16_offset as u64,
|
||||
)));
|
||||
self.editor.last_typing = None;
|
||||
self.did_edit(commit, Some(&block_id), window, cx);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -586,6 +586,10 @@ impl PlaygroundView {
|
||||
self.page_readonly = self.page_readonly || caps.page_readonly;
|
||||
self.set_edgeless_readonly(caps.edgeless_readonly, window, cx);
|
||||
self.set_database_mobile_readonly(caps.database_readonly, cx);
|
||||
if caps.form_factor == crate::FormFactor::Desktop {
|
||||
self.overlays.set_keyboard_toolbar_visible(false);
|
||||
self.touch_selection_menu_open = false;
|
||||
}
|
||||
if changed {
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
@@ -224,7 +224,15 @@ impl PlaygroundView {
|
||||
transform,
|
||||
&local_collapsed,
|
||||
);
|
||||
self.overlays.popovers(&scene, palette, now_ms, window, cx)
|
||||
let mut out = self.overlays.popovers(&scene, palette, now_ms, window, cx);
|
||||
out.extend(self.overlays.render_lightbox(
|
||||
&scene,
|
||||
&self.images,
|
||||
palette,
|
||||
now_ms,
|
||||
cx,
|
||||
));
|
||||
out
|
||||
}
|
||||
} else {
|
||||
Vec::new()
|
||||
|
||||
@@ -221,9 +221,9 @@ impl PlaygroundView {
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> DocResult {
|
||||
if (self.mode == crate::PlaygroundMode::Page && self.page_readonly)
|
||||
|| (self.mode == crate::PlaygroundMode::Edgeless && self.edgeless_readonly)
|
||||
{
|
||||
let readonly = (self.mode == crate::PlaygroundMode::Page && self.page_readonly)
|
||||
|| (self.mode == crate::PlaygroundMode::Edgeless && self.edgeless_readonly);
|
||||
if readonly && command != SlashCommand::Copy {
|
||||
return Ok(());
|
||||
}
|
||||
let snapshot = self
|
||||
@@ -713,7 +713,7 @@ impl PlaygroundView {
|
||||
Ok(())
|
||||
}
|
||||
SlashCommand::Copy | SlashCommand::Delete => {
|
||||
if command == SlashCommand::Copy {
|
||||
if command == SlashCommand::Copy && !readonly {
|
||||
self.strip_slash_trigger(block_id, strip, window, cx)?;
|
||||
}
|
||||
let action = if command == SlashCommand::Copy {
|
||||
|
||||
@@ -497,6 +497,20 @@ pub fn register_web_font(bytes: &[u8]) -> Result<(), wasm_bindgen::JsError> {
|
||||
|
||||
/// Opens the fullscreen playground window on the page canvas.
|
||||
///
|
||||
/// Generate a random 53-bit CRDT client id for a new live room session.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub(crate) fn fresh_client_id() -> u64 {
|
||||
blocksuite_playground_doc::random_client_id()
|
||||
}
|
||||
|
||||
/// Generate a random 53-bit CRDT client id for a new live room session on Wasm.
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub(crate) fn fresh_client_id() -> u64 {
|
||||
blocksuite_playground_doc::client_id_from_seed(
|
||||
(js_sys::Math::random() * 9_007_199_254_740_992.0) as u64,
|
||||
)
|
||||
}
|
||||
|
||||
/// The standalone playground page calls this after it registered its fonts with
|
||||
/// [`register_web_font`]. It throws before it starts the application when the
|
||||
/// fonts miss a required family. The Web thin host (`/host/`) loads the same
|
||||
|
||||
@@ -57,8 +57,8 @@ final class LegacyLocalStorageProbe: NSObject, WKNavigationDelegate {
|
||||
static let legacyOrigin = "capacitor://localhost"
|
||||
static let probeURLString = "capacitor://localhost/__affine_probe__"
|
||||
static let localWorkspaceKey = "affine-local-workspace"
|
||||
nonisolated static let defaultNavigationTimeoutSeconds: TimeInterval = 15.0
|
||||
nonisolated static let defaultEvaluationTimeoutSeconds: TimeInterval = 10.0
|
||||
nonisolated static let defaultNavigationTimeoutSeconds: TimeInterval = 30.0
|
||||
nonisolated static let defaultEvaluationTimeoutSeconds: TimeInterval = 15.0
|
||||
|
||||
/// Shared warm WebContent process pool reused across probe calls to avoid cold XPC churn.
|
||||
private static let sharedProcessPool = WKProcessPool()
|
||||
|
||||
@@ -1655,7 +1655,18 @@ struct IosHostS3SmokeTest {
|
||||
let probeHostWindow = UIWindow(frame: CGRect(x: 0, y: 0, width: 390, height: 844))
|
||||
probeHostWindow.rootViewController = UIViewController()
|
||||
probeHostWindow.makeKeyAndVisible()
|
||||
defer { probeHostWindow.isHidden = true }
|
||||
// Under `simctl spawn` (`@main async` -> `dispatchMain()`), keep `CFRunLoopGetMain()` pumped
|
||||
// so cold `WKWebView` / `WebContent` XPC callbacks never starve on loaded CI runners.
|
||||
let runLoopPump = DispatchSource.makeTimerSource(queue: .main)
|
||||
runLoopPump.schedule(deadline: .now(), repeating: .milliseconds(15))
|
||||
runLoopPump.setEventHandler {
|
||||
_ = CFRunLoopRunInMode(.defaultMode, 0.002, true)
|
||||
}
|
||||
runLoopPump.resume()
|
||||
defer {
|
||||
runLoopPump.cancel()
|
||||
probeHostWindow.isHidden = true
|
||||
}
|
||||
|
||||
// 1b) Deterministic fail-closed probe timeout test (0ms wall-clock via injected timeoutScheduler):
|
||||
// when LegacyLocalStorageProbe fails/times out, HostBootstrapCoordinator MUST fail closed
|
||||
|
||||
@@ -427,9 +427,11 @@ async function checkLinkField(cdp) {
|
||||
if (!paragraph.value.startsWith('This page')) {
|
||||
throw new Error(`Unable to select in the second showcase block: ${JSON.stringify(paragraph)}`);
|
||||
}
|
||||
// The toolbar is 374 px wide and centered 46 px above the selected line; its eighth
|
||||
// button (Link) opens the link field, which then is what the hidden textarea mirrors.
|
||||
const link = [(from[0] + to[0]) / 2 - 187 + 247, 243 - 46 + 19];
|
||||
// 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.
|
||||
const midX = (from[0] + to[0]) / 2;
|
||||
const link = [midX - 240.5 + 277, 243 - 46 + 19];
|
||||
await mouse('mouseMoved',link,0);
|
||||
await mouse('mousePressed',link,1);
|
||||
await mouse('mouseReleased',link,0);
|
||||
@@ -467,6 +469,20 @@ async function checkLinkField(cdp) {
|
||||
if (ignored) throw new Error('The paste event was not taken by the link field');
|
||||
await waitValue('你好.affine.pro');
|
||||
|
||||
// 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];
|
||||
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];
|
||||
await mouse('mouseMoved',urlFieldPt,0);
|
||||
await mouse('mousePressed',urlFieldPt,1);
|
||||
await mouse('mouseReleased',urlFieldPt,0);
|
||||
await waitValue('你好.affine.pro');
|
||||
|
||||
// Closing the field hands the text input back to the paragraph, untouched.
|
||||
await key('Escape','Escape',27);
|
||||
await waitValue(paragraph.value);
|
||||
|
||||
Reference in new issue
Block a user