feat(editor): add canvas document opening, table conversion, and URL autolinks

This commit is contained in:
DarkSky committed 2026-12-04 19:13:57 +09:00
1 parent 1916183e6c
commit 575b2fdddf
18 files changed
+961 -129

No files matched your search

+1 -1
View File
@@ -40,7 +40,7 @@ These crates belong to the client Cargo workspace rooted at `packages/frontend/C
- **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"`], then one `Frame: <title>` row per frame of the document (presentation order) and one `Group: <title>` row per group, each inserting an `affine:surface-ref` to it in one undo step (like `Frame` and `Mind Map`, the new reference becomes the only selected block), `Date` [`Today`/`Tomorrow`/`Yesterday` `YYYY-MM-DD`, `Now` `YYYY-MM-DD HH:MM`, shown as the row subtitles in local time when the menu opens on a typed `/`], `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 the row's BlockSuite tooltip `overlay.slash_menu.preview` (178 px wide: the row's `0.27.5` tooltip figure, 170 px wide and 68, 89, or 106 px tall, drawn by `slash_preview/figure.rs` from the figure tables in `slash_preview/figures_*.rs` with embedded screenshots as plain areas, over a caption, centered on the row 6 px past its end edge, on the start side when the end side has less than 12 px; rows without a BlockSuite tooltip show none). 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`, `overlay.reference_alias_prompt`): Typing `@` anywhere in paragraph, list, or `affine:table` cell text (outside inline code), or typing `[[` or `【【` (which converts the pair into `@`), opens the linked-doc popover anchored at the caret (`EditorSession::linked_doc_trigger`), querying the active `WorkspaceDocDirectory` as the user types inside a height-capped scrollable list with keyboard auto-scroll, `More` expansion, `Journal` dynamic date entries (`Today`/`Tomorrow`/`Yesterday` showing `YYYY-MM-DD` subtitles and calendar-validated `YYYY-MM-DD` input rejecting impossible dates such as `2026-02-31`), and `New` Page/Edgeless creation. `Up`/`Down`/`Ctrl+N`/`Ctrl+P`/`Tab`/`Shift+Tab` move selection across all matched docs, Journal entries, and `New` rows without indenting the underlying block, `Enter` selects or creates the linked doc and replaces `@query` with a BlockSuite `InlineReference` (`LinkedPage`) chip in one undo step, `Escape` closes the menu while leaving the typed text intact, and selection changes (`←`/`→`, clicks, remote edits) sync `sync_linked_doc_trigger` so moving before `@` or leaving the trigger range closes the menu immediately. Hovering an inline link or `@reference` chip for 500 ms on desktop in Page mode or inside an Active Note (keeping the capsule open across the hover bridge onto `overlay.link_popup`), placing the caret on it, or single-tapping in mobile edit mode (mobile read-only single-tap and desktop left-click open directly; `page_readonly` exposes only `Open ↗` and `Copy`) opens the non-focus-stealing `overlay.link_popup` toolbar on the shared `ToolbarChrome`: the label preview `.open`, `.copy`, `.edit` for links or `.alias` for references, a `.view` dropdown (`.view_menu`: `Inline view`, `Card view`, and conditional `Embed view`; links show it on desktop only), and `.more` (`.more_menu` with `Remove link` for links or `Delete` for references).
- **Formatting toolbar** (`overlay.format_toolbar`, buttons `.turn_into`, `.align`, `.bold`, `.italic`, `.underline`, `.strike`, `.code`, `.inline_equation`, `.link`, `.highlight`, `.create_table`, `.create_linked_doc`, `.more`, dropdowns `.turn_into_menu`, `.align_menu` with `.align_left|center|right`, `.highlight_menu`, `.more_menu`, dual-field link editor `.link_text_input`, `.link_input`, `.link_apply`, `.link_remove`): shown above a finished, non-empty selection of paragraph and list text (or a whole-block `BlockSelection` covering paragraph/list blocks), while no composition runs and no slash menu is up (`FormFactor::Desktop` auto-collapses any open `KeyboardToolbar`); a selection touching only the title or code gets none. `Turn into ▾` converts blocks via the shared `SLASH_ITEMS` registry in one undo step; `Highlight` exposes 9 foreground + 9 background swatches writing BlockSuite delta `color`/`background` attributes (with Default clearing) in one undo step; `TeX` (`InlineEquation`) wraps the selection into an inline `latex` chip and opens `EquationEditor`; `CreateLinkedDoc` creates a linked page titled with the selection and replaces it with an `@reference` chip in one undo step; `More` exposes `Copy` / `Copy as Markdown` / `Copy link to block` / `Duplicate` / `Delete`. Page selections can copy a link to all selected blocks. The editor parses the ordered block list for a page link handler, or opens the first block in the single-block handler. The link action is hidden inside an Edgeless note. `Copy as Markdown` writes each inline `@reference` as `[title](url)`. The title is the reference alias, else the page title, else `Untitled`. The URL is the workspace page URL with the `mode`, `blockIds` and `elementIds` of the reference. 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).
- **Formatting toolbar** (`overlay.format_toolbar`, buttons `.turn_into`, `.align`, `.bold`, `.italic`, `.underline`, `.strike`, `.code`, `.inline_equation`, `.link`, `.highlight`, `.create_table`, `.create_linked_doc`, `.more`, dropdowns `.turn_into_menu`, `.align_menu` with `.align_left|center|right`, `.highlight_menu`, `.more_menu`, dual-field link editor `.link_text_input`, `.link_input`, `.link_apply`, `.link_remove`): shown above a finished, non-empty selection of paragraph and list text (or a whole-block `BlockSelection` covering paragraph/list blocks), while no composition runs and no slash menu is up (`FormFactor::Desktop` auto-collapses any open `KeyboardToolbar`); a selection touching only the title or code gets none. `Turn into ▾` converts blocks via the shared `SLASH_ITEMS` registry in one undo step; `Highlight` exposes 9 foreground + 9 background swatches writing BlockSuite delta `color`/`background` attributes (with Default clearing) in one undo step; `TeX` (`InlineEquation`) wraps the selection into an inline `latex` chip and opens `EquationEditor`; `Create Table` moves a multi-block text selection or a whole-block selection of paragraphs and lists into a Table database at the first block, with one undo step. `CreateLinkedDoc` creates a linked page titled with the selection and replaces it with an `@reference` chip in one undo step; `More` exposes `Copy` / `Copy as Markdown` / `Copy link to block` / `Duplicate` / `Delete`. Page selections can copy a link to all selected blocks. The editor parses the ordered block list for a page link handler, or opens the first block in the single-block handler. The link action is hidden inside an Edgeless note. `Copy as Markdown` writes each inline `@reference` as `[title](url)`. The title is the reference alias, else the page title, else `Untitled`. The URL is the workspace page URL with the `mode`, `blockIds` and `elementIds` of the reference. 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.
@@ -15,6 +15,7 @@ mod summary;
mod typography;
mod widgets;
pub use more_menu::EdgelessMoreDocActions;
pub use palettes::{
BRUSH_LINE_WIDTHS, DEFAULT_HIGHLIGHTER_LINE_WIDTH, DEFAULT_PALETTES, FONT_SIZE_LIST,
HIGHLIGHTER_LINE_WIDTHS, NOTE_BACKGROUND_PALETTES, PaletteSwatch, SHAPE_TEXT_PALETTES,
@@ -134,6 +135,15 @@ pub struct SurfaceBlockToolbarSummary {
pub rotate_deg: f32,
}
/// Destination for a linked document opened from an Edgeless card.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EdgelessDocOpenMode {
ActiveView,
SplitView,
NewTab,
CenterPeek,
}
/// Property mutation, sub-picker toggle, or common element action dispatched from
/// `chrome.edgeless_element_toolbar`.
#[derive(Clone, Debug, PartialEq)]
@@ -194,6 +204,7 @@ pub enum EdgelessElementAction {
Copy,
CopyElementLink,
CopyAsMarkdown,
OpenLinkedDoc(EdgelessDocOpenMode),
GroupSection,
Duplicate,
Delete,
@@ -14,11 +14,20 @@ use crate::{
};
use super::{
EDGELESS_VIEWPORT_ID, EdgelessElementAction, EdgelessElementToolbarHost, ElementToolbarSummary,
SurfaceBlockKind,
EDGELESS_VIEWPORT_ID, EdgelessDocOpenMode, EdgelessElementAction, EdgelessElementToolbarHost,
ElementToolbarSummary, SurfaceBlockKind,
widgets::{isolate_floating_chrome, paint_group_action_icon, toolbar_chrome_tokens},
};
#[derive(Clone, Copy, Debug, Default)]
pub struct EdgelessMoreDocActions {
pub can_open: bool,
pub same_doc: bool,
pub split_view: bool,
pub new_tab: bool,
pub center_peek: bool,
}
const MENU_MIN_W: f32 = 220.0;
const ROW_H: f32 = 30.0;
const MENU_PAD: f32 = 6.0;
@@ -62,6 +71,7 @@ fn menu_separator(border_col: Hsla) -> ui::Div {
#[allow(clippy::too_many_arguments)]
pub(super) fn build_more_menu<V: EdgelessElementToolbarHost>(
summary: &ElementToolbarSummary,
docs: EdgelessMoreDocActions,
trigger_rect: FlowRect,
viewport_width: f32,
viewport_height: f32,
@@ -240,6 +250,54 @@ pub(super) fn build_more_menu<V: EdgelessElementToolbarHost>(
}
sections.push(clip_section);
if docs.can_open {
use EdgelessDocOpenMode::{ActiveView, CenterPeek, NewTab, SplitView};
sections.push(
[
(
true,
"open_this_doc",
"Open this doc",
"ExpandFullIcon",
ActiveView,
),
(
docs.split_view,
"open_split_view",
"Open in split view",
"SplitViewIcon",
SplitView,
),
(
docs.new_tab,
"open_new_tab",
"Open in new tab",
"OpenInNewIcon",
NewTab,
),
(
docs.center_peek,
"open_center_peek",
"Open in center peek",
"CenterPeekIcon",
CenterPeek,
),
]
.into_iter()
.filter(|(show, ..)| *show)
.map(|(_, id, label, icon, mode)| MoreMenuItem {
id,
label,
icon,
shortcut: None,
action: EdgelessElementAction::OpenLinkedDoc(mode),
destructive: false,
})
.collect(),
);
}
sections.push(vec![MoreMenuItem {
id: "delete",
label: "Delete",
@@ -304,6 +362,8 @@ pub(super) fn build_more_menu<V: EdgelessElementToolbarHost>(
let icon_col = palette.icon;
let text_col = palette.text_primary;
let action = item.action.clone();
let enabled = !(docs.same_doc
&& action == EdgelessElementAction::OpenLinkedDoc(EdgelessDocOpenMode::ActiveView));
let icon_name = item.icon;
let destructive = item.destructive;
let mut row = div()
@@ -319,12 +379,16 @@ pub(super) fn build_more_menu<V: EdgelessElementToolbarHost>(
.text_size(px(TYPOGRAPHY.font_xs_px))
.font_weight(FontWeight::MEDIUM)
.text_color(text_col)
.cursor_pointer()
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(action.clone(), window, cx);
}))
.when(enabled, |row| {
row.cursor_pointer().on_click(cx.listener(
move |this, _: &ClickEvent, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(action.clone(), window, cx);
},
))
})
.when(!enabled, |row| row.opacity(0.45))
.snapshot(
format_args!("chrome.edgeless_element_toolbar.more.{}", item.id),
Some("chrome.edgeless_element_toolbar.more_menu"),
@@ -354,7 +418,7 @@ pub(super) fn build_more_menu<V: EdgelessElementToolbarHost>(
});
if destructive {
row = row.hover(move |s| s.bg(danger_bg).text_color(danger_fg));
} else {
} else if enabled {
row = row.hover(move |s| s.bg(hover_bg));
}
menu = menu.child(row);
@@ -196,6 +196,7 @@ fn build_icon_strip_menu<V: EdgelessElementToolbarHost>(
pub(super) fn build_sub_menu_pill<V: EdgelessElementToolbarHost>(
menu: ElementSubMenu,
summary: &ElementToolbarSummary,
more_doc_actions: super::EdgelessMoreDocActions,
trigger_rect: FlowRect,
viewport_width: f32,
viewport_height: f32,
@@ -219,6 +220,7 @@ pub(super) fn build_sub_menu_pill<V: EdgelessElementToolbarHost>(
}
ElementSubMenu::More => Some(build_more_menu(
summary,
more_doc_actions,
trigger_rect,
viewport_width,
viewport_height,
@@ -11,7 +11,8 @@ use crate::{
use super::{
EDGELESS_VIEWPORT_ID, EdgelessAuthoringState, EdgelessCamera, EdgelessElementAction,
EdgelessElementToolbarHost, ElementColorSlot, ElementSubMenu, SpatialItemKind,
EdgelessElementToolbarHost, EdgelessMoreDocActions, ElementColorSlot, ElementSubMenu,
SpatialItemKind,
bar_items::append_per_type_items,
color_popover::build_color_picker_pill,
popovers::{build_sub_menu_pill, place_toolbar_rect},
@@ -82,6 +83,7 @@ pub fn build_edgeless_element_toolbar<V: EdgelessElementToolbarHost>(
palette: &Palette,
theme: PlaygroundTheme,
can_download_blob: impl Fn(&str) -> bool,
more_doc_actions: EdgelessMoreDocActions,
window: &mut Window,
cx: &mut Context<V>,
) -> Option<(AnyElement, Vec<FlowRect>)> {
@@ -474,6 +476,7 @@ pub fn build_edgeless_element_toolbar<V: EdgelessElementToolbarHost>(
&& let Some((sub_el, sub_rect)) = build_sub_menu_pill(
menu,
&summary,
more_doc_actions,
trigger,
viewport_width,
viewport_height,
+9 -8
View File
@@ -41,14 +41,15 @@ pub use canvas::{
pub use canvas_paint::{build_edgeless_layer, build_edgeless_layer_prepared, canvas_tool_cursor};
pub use element_toolbar::{
AlignOp, BRUSH_LINE_WIDTHS, DEFAULT_HIGHLIGHTER_LINE_WIDTH, DEFAULT_PALETTES,
EdgelessElementAction, EdgelessElementToolbarHost, ElementColorSlot, ElementSubMenu,
ElementToolbarSummary, FONT_SIZE_LIST, HIGHLIGHTER_LINE_WIDTHS, MindmapToolbarSummary,
NOTE_BACKGROUND_PALETTES, NOTE_BORDER_SIZES, NOTE_CORNER_RADII, NOTE_SCALE_PRESETS,
NOTE_SHADOW_PRESETS, PaletteSwatch, SHAPE_TEXT_PALETTES, SurfaceBlockKind,
SurfaceBlockToolbarSummary, adjust_color_alpha, build_edgeless_element_toolbar,
color_value_matches_swatch, is_neutral_shape_text_color, is_transparent_color,
json_to_color_value, measure_surface_text_xywh, palette_for_slot, parse_custom_hex_color,
shape_text_color_for_fill, summarize_element_toolbar, sync_selection_from_snapshot,
EdgelessDocOpenMode, EdgelessElementAction, EdgelessElementToolbarHost, EdgelessMoreDocActions,
ElementColorSlot, ElementSubMenu, ElementToolbarSummary, FONT_SIZE_LIST,
HIGHLIGHTER_LINE_WIDTHS, MindmapToolbarSummary, NOTE_BACKGROUND_PALETTES, NOTE_BORDER_SIZES,
NOTE_CORNER_RADII, NOTE_SCALE_PRESETS, NOTE_SHADOW_PRESETS, PaletteSwatch, SHAPE_TEXT_PALETTES,
SurfaceBlockKind, SurfaceBlockToolbarSummary, adjust_color_alpha,
build_edgeless_element_toolbar, color_value_matches_swatch, is_neutral_shape_text_color,
is_transparent_color, json_to_color_value, measure_surface_text_xywh, palette_for_slot,
parse_custom_hex_color, shape_text_color_for_fill, summarize_element_toolbar,
sync_selection_from_snapshot,
};
pub use frame_membership::{
compute_frame_membership_updates, find_frame_containing_point, hovered_frame_for_drag,
@@ -21,6 +21,11 @@ use dropdowns::{
use link_fields::{render_toolbar_link_row, render_toolbar_text_row};
impl Overlays {
/// Return the host's new-tab, split-view, and center-peek capabilities.
pub fn open_doc_destinations(&self, scene: &OverlayScene<'_>) -> (bool, bool, bool) {
super::link_popup::desktop_open_items_available(self, scene)
}
pub(super) fn render_toolbar<V: OverlayHost>(
&mut self,
scene: &OverlayScene<'_>,
@@ -322,7 +322,7 @@ pub struct SelectionFormat {
pub selected_text: Option<ui::SharedString>,
/// Slash item id of the primary selected block (for `Turn into ▾` icon and selected row).
pub current_turn_into_id: Option<&'static str>,
/// Whether `Create Table` is eligible (single-block text selection or paragraph/list block selection).
/// Whether the selected paragraph and list blocks can become database rows.
pub can_create_table: bool,
}
@@ -685,11 +685,13 @@ impl Overlays {
};
toolbar.submenu = (toolbar.submenu != Some(target)).then_some(target);
}
FormatAction::CreateTable => {
FormatAction::CreateTable if toolbar.selection.can_create_table => {
toolbar.submenu = None;
toolbar.submenu_rect = None;
self.hovered_tooltip = None;
effects.edits.push(DocEdit::CreateTableFromSelection);
}
FormatAction::CreateTable => {}
FormatAction::InlineEquation => {
toolbar.submenu = None;
toolbar.submenu_rect = None;
@@ -13,8 +13,8 @@ use crate::{
};
use super::{
DragItemInitial, EdgelessElementAction, EdgelessElementToolbarHost, ElementColorSlot,
ShapePreset, SpatialItemKind, element_toolbar_color::apply_color_to_element,
DragItemInitial, EdgelessDocOpenMode, EdgelessElementAction, EdgelessElementToolbarHost,
ElementColorSlot, ShapePreset, SpatialItemKind, element_toolbar_color::apply_color_to_element,
parse_custom_hex_color,
};
@@ -107,6 +107,10 @@ impl EdgelessElementToolbarHost for PlaygroundView {
}
return;
}
if let EdgelessElementAction::OpenLinkedDoc(mode) = action {
self.open_edgeless_linked_doc(mode, window, cx);
return;
}
if matches!(
action,
EdgelessElementAction::MediaCaption | EdgelessElementAction::MediaOpenLink
@@ -143,8 +147,10 @@ impl PlaygroundView {
{
return None;
}
let snapshot = self.snapshot.as_ref()?;
let more_doc_actions = self.edgeless_more_doc_actions(snapshot, window);
super::build_edgeless_element_toolbar(
self.snapshot.as_ref()?,
snapshot,
&self.edgeless.authoring,
self.edgeless.camera,
f32::from(viewport.width),
@@ -153,11 +159,41 @@ impl PlaygroundView {
palette,
self.theme,
|source_id| self.can_download_blob(source_id),
more_doc_actions,
window,
cx,
)
}
fn open_edgeless_linked_doc(
&mut self,
mode: EdgelessDocOpenMode,
window: &mut Window,
cx: &mut Context<Self>,
) {
use crate::overlays::{ReferenceOpenMode, open_doc_request_from_json_params};
use EdgelessDocOpenMode::{ActiveView, CenterPeek, NewTab, SplitView};
let Some(snapshot) = self.snapshot.as_ref() else {
return;
};
let Some((page_id, params)) = self.edgeless_linked_doc_target(snapshot) else {
return;
};
let caps = self.edgeless_more_doc_actions(snapshot, window);
let open_mode = match mode {
ActiveView if !caps.same_doc => ReferenceOpenMode::ActiveView,
SplitView if caps.split_view => ReferenceOpenMode::SplitView,
NewTab if caps.new_tab => ReferenceOpenMode::NewTab,
CenterPeek if caps.center_peek => ReferenceOpenMode::CenterPeek,
_ => return,
};
let request = open_doc_request_from_json_params(page_id.into(), open_mode, params);
self.dismiss_edgeless_element_popovers();
self.dispatch_open_doc_request(request, window, cx);
cx.notify();
}
fn sync_element_panel(&mut self, viewport: ui::Size<ui::Pixels>) {
let state = &self.edgeless.authoring;
if state.open_sub_menu.is_none() && self.edgeless_element_color_picker.is_none() {
@@ -704,6 +704,54 @@ impl PlaygroundView {
}
}
pub(super) fn edgeless_linked_doc_target<'a>(
&self,
snapshot: &'a PageSnapshot,
) -> Option<(&'a str, Option<&'a serde_json::Value>)> {
let node = snapshot.block(&self.edgeless.authoring.single_selected()?.id)?;
match &node.content {
BlockContent::EmbedLinkedDoc { page_id, .. }
| BlockContent::EmbedSyncedDoc { page_id, .. }
if !page_id.is_empty() =>
{
Some((page_id, node.props.get("prop:params")))
}
_ => None,
}
}
pub(super) fn edgeless_more_doc_actions(
&self,
snapshot: &PageSnapshot,
window: &ui::Window,
) -> super::EdgelessMoreDocActions {
use crate::block_flow::FlowLayout;
let Some((page_id, _)) = self.edgeless_linked_doc_target(snapshot) else {
return super::EdgelessMoreDocActions::default();
};
let layout = FlowLayout {
blocks: Vec::new(),
width: 0.0,
height: 0.0,
direction: ui::Direction::Ltr,
stats: Default::default(),
};
let collapsed = Default::default();
let mut scene = self.overlay_scene(snapshot, &layout, ui::Direction::Ltr, None, &collapsed);
let width = f32::from(window.viewport_size().width);
scene.pane_origin.x = ui::px(0.0);
scene.window.0 = width;
let (new_tab, split_view, center_peek) = self.overlays.open_doc_destinations(&scene);
super::EdgelessMoreDocActions {
can_open: true,
same_doc: self.active_doc_id() == Some(page_id),
split_view: split_view && width >= 640.0,
new_tab,
center_peek,
}
}
pub(super) fn precompute_flipped_connectors(
&self,
snapshot: &PageSnapshot,
@@ -220,6 +220,83 @@ fn match_inline_markdown(line: &str) -> Option<InlineMatch> {
None
}
fn match_bare_url(line: &str, delta: &[TextDeltaOp]) -> Option<InlineMatch> {
let candidate = line.rsplit(' ').next()?;
let (scheme, rest) = candidate.split_once("://")?;
if !(scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https"))
|| rest.is_empty()
|| rest.starts_with(['/', '?', '#'])
|| candidate.chars().any(char::is_whitespace)
|| candidate.contains(['\\', '<', '>', '"'])
{
return None;
}
crate::clipboard::sanitize::sanitize_url(candidate)?;
let host = {
#[cfg(target_family = "wasm")]
{
web_sys::Url::new(candidate).ok()?.hostname()
}
#[cfg(not(target_family = "wasm"))]
{
url::Url::parse(candidate).ok()?.host_str()?.to_owned()
}
};
let tld = host.rsplit('.').next()?;
if !matches!(
tld,
"cat"
| "co"
| "com"
| "de"
| "dev"
| "edu"
| "eu"
| "gov"
| "info"
| "io"
| "jp"
| "me"
| "mil"
| "moe"
| "net"
| "org"
| "pro"
| "ru"
| "top"
| "uk"
| "xyz"
) {
return None;
}
let start_byte = line.len() - candidate.len();
let start = line[..start_byte].encode_utf16().count() as u64;
let length = candidate.encode_utf16().count() as u64;
let (_, tail) = blocksuite_playground_doc::session::split_delta(delta, start).ok()?;
let (target, _) = blocksuite_playground_doc::session::split_delta(&tail, length).ok()?;
if target.iter().any(|op| match op {
TextDeltaOp::Insert {
insert: TextInsert::Text(_),
format,
} => format.as_ref().is_some_and(|marks| {
marks.get("code") == Some(&Any::True)
|| matches!(marks.get("link"), Some(Any::String(_)))
}),
_ => true,
}) {
return None;
}
Some(InlineMatch {
start_byte,
open_bytes: 0,
target_bytes: candidate.len(),
close_bytes: 0,
attrs: TextAttributes::from([("link".into(), Any::String(candidate.into()))]),
replace_with_embed_space: false,
})
}
impl PlaygroundView {
pub(super) fn apply_markdown(
&mut self,
@@ -438,7 +515,13 @@ impl PlaygroundView {
return Ok(true);
}
let Some(matched) = match_inline_markdown(line) else {
let Some(matched) = match_inline_markdown(line).or_else(|| {
if typed == " " && line_start_byte == 0 {
match_bare_url(line, &rich.delta)
} else {
None
}
}) else {
return Ok(false);
};
let match_start_byte = line_start_byte + matched.start_byte;
@@ -512,14 +595,18 @@ impl PlaygroundView {
});
match_start_utf16 + 1 + u64::from(!is_enter)
} else {
delta.push(TextDeltaOp::Delete { delete: open_utf16 });
if open_utf16 > 0 {
delta.push(TextDeltaOp::Delete { delete: open_utf16 });
}
delta.push(TextDeltaOp::Retain {
retain: target_utf16,
format: Some(matched.attrs.clone()),
});
delta.push(TextDeltaOp::Delete {
delete: close_utf16,
});
if close_utf16 > 0 {
delta.push(TextDeltaOp::Delete {
delete: close_utf16,
});
}
match_start_utf16 + target_utf16 + u64::from(!is_enter)
};
@@ -557,3 +644,35 @@ impl PlaygroundView {
Ok(true)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bare_url_matches_only_unmarked_http_text_with_a_common_tld() {
for (text, mark, expected) in [
("https://example.com/docs", None, Some(0)),
("😀 https://example.org?q=one", None, Some("😀 ".len())),
("http://[invalid", None, None),
("https://localhost", None, None),
("example.com", None, None),
("https://example.com", Some(("code", Any::True)), None),
(
"https://example.com",
Some(("link", Any::String("https://elsewhere.com".into()))),
None,
),
] {
let delta = [TextDeltaOp::Insert {
insert: TextInsert::Text(text.into()),
format: mark.map(|(name, value)| TextAttributes::from([(name.into(), value)])),
}];
assert_eq!(
match_bare_url(text, &delta).map(|matched| matched.start_byte),
expected,
"{text}"
);
}
}
}
@@ -1743,7 +1743,12 @@ mod tests {
assert_eq!(toolbar.bounds.bottom() + TOOLBAR_CHROME_OFFSET, selection.y);
assert!((center(toolbar.bounds).0 - center(selection).0).abs() <= 1.0);
for action in FormatAction::ALL {
let button = element(&frame, &format!("overlay.format_toolbar.{}", action.id()));
let id = format!("overlay.format_toolbar.{}", action.id());
if action == FormatAction::CreateTable {
assert!(!frame.elements.contains_key(&id));
continue;
}
let button = element(&frame, &id);
assert!(button.interactive, "{action:?}");
assert!(
button.bounds.width >= TOOLBAR_CHROME_BTN
@@ -1916,6 +1921,18 @@ mod tests {
.elements
.contains_key("overlay.format_toolbar")
);
session.update(|view, window, cx| {
view.select_document_range(
DocumentSelection {
anchor: DocPoint::new("showcase-h2", 0),
focus: DocPoint::new("showcase-quote", 5),
},
window,
cx,
);
});
assert!(element(&session.settle(), "overlay.format_toolbar.create_table").interactive);
}
#[test]
@@ -888,37 +888,463 @@ mod tests {
}
#[test]
fn create_table_from_block_selection_inserts_below_and_focuses_first_cell() {
fn create_table_converts_selected_blocks_in_place_and_undo_restores_the_selection() {
use crate::editor_session::{DocPoint, DocumentSelection};
for (theme, tag) in [
(PlaygroundTheme::Light, "light"),
(PlaygroundTheme::Dark, "dark"),
] {
for is_text_range in [false, true] {
let session = open_page(
800,
PlaygroundOptions {
theme,
..Default::default()
},
|state| {
let page = home(state);
add(page, "p1", paragraph("Roadmap"));
add(page, "p2", paragraph("Research"));
add(page, "p3", paragraph("Shipping"));
},
);
if is_text_range {
session.app.update(|cx| {
session
.window
.update(cx, |view, window, cx| {
view.change_selection(
DocumentSelection {
anchor: DocPoint::new("p1", 3),
focus: DocPoint::new("p2", 3),
},
window,
cx,
);
})
.unwrap()
});
} else {
session.overlay(OverlayEvent::SelectBlock("p1".into()));
}
let frame = session.settle();
if is_text_range {
save_editor_interaction_evidence(&session, &format!("{tag}-table-before.png"));
}
session.click(&frame, "overlay.format_toolbar.create_table");
let converted = session.settle();
assert!(!converted.elements.contains_key("overlay.toolbar_tooltip"));
if is_text_range {
save_editor_interaction_evidence(&session, &format!("{tag}-table-after.png"));
}
let children = session.node("n").unwrap().children;
let BlockContent::Database(data) = &children[0].content else {
panic!("the database should replace the selection in place");
};
assert_eq!(data.views[0].mode.as_str(), "table");
let titles: Vec<_> = data
.rows
.iter()
.map(|row| row.title.plain.as_str())
.collect();
assert_eq!(
titles,
if is_text_range {
vec!["Roadmap", "Research"]
} else {
vec!["Roadmap"]
}
);
assert_eq!(children.last().unwrap().id, "p3");
assert!(session.view(|v, _| v.editor.block_selection.is_empty()));
session.undo();
let restored = session.node("n").unwrap().children;
assert_eq!(
restored.iter().map(|b| b.id.as_str()).collect::<Vec<_>>(),
["p1", "p2", "p3"]
);
}
}
}
#[test]
fn create_table_moves_whole_block_subtree_as_rows_and_undo_restores_nesting() {
for (theme, tag) in [
(PlaygroundTheme::Light, "light"),
(PlaygroundTheme::Dark, "dark"),
] {
let session = open_page(
800,
PlaygroundOptions {
theme,
..Default::default()
},
|state| {
let page = home(state);
add(page, "parent", paragraph("Roadmap"));
page.add_block("child", paragraph("Research"), Some("parent"), None, 1)
.unwrap();
page.add_block("grandchild", paragraph("Shipping"), Some("child"), None, 1)
.unwrap();
add(page, "sibling", paragraph("Outside selection"));
},
);
session.overlay(OverlayEvent::SelectBlock("parent".into()));
let frame = session.settle();
save_editor_interaction_evidence(&session, &format!("{tag}-nested-table-before.png"));
session.click(&frame, "overlay.format_toolbar.create_table");
let _ = session.settle();
save_editor_interaction_evidence(&session, &format!("{tag}-nested-table-after.png"));
let note = session.node("n").unwrap();
let [database, sibling] = &note.children[..] else {
panic!("expected the database and the unselected sibling");
};
let BlockContent::Database(data) = &database.content else {
panic!("expected a database");
};
let titles: Vec<_> = data
.rows
.iter()
.map(|row| row.title.plain.as_str())
.collect();
assert_eq!(titles, ["Roadmap", "Research", "Shipping"]);
let row_ids: Vec<_> = database
.children
.iter()
.map(|row| row.id.as_str())
.collect();
assert_eq!(row_ids, ["parent", "child", "grandchild"]);
assert_eq!(sibling.id, "sibling");
session.undo();
let restored = session.node("n").unwrap();
assert_eq!(restored.children.len(), 2);
assert_eq!(restored.children[0].id, "parent");
assert_eq!(restored.children[0].children[0].id, "child");
assert_eq!(
restored.children[0].children[0].children[0].id,
"grandchild"
);
assert_eq!(restored.children[1].id, "sibling");
}
}
#[test]
fn create_table_rejects_dividers_in_block_subtrees_and_text_ranges() {
use crate::editor_session::{DocPoint, DocumentSelection};
let session = open_page(800, PlaygroundOptions::default(), |state| {
let page = home(state);
add(page, "p1", paragraph("Hello"));
add(page, "p2", paragraph("World"));
add(page, "parent", paragraph("Roadmap"));
page.add_block("divider", BlockSpec::Divider, Some("parent"), None, 1)
.unwrap();
add(page, "sibling", paragraph("Shipping"));
});
session.overlay(OverlayEvent::SelectBlock("p1".into()));
let frame = session.settle();
session.click(&frame, "overlay.format_toolbar.create_table");
let _ = session.settle();
let children = session.node("n").unwrap().children;
assert_eq!(children.len(), 3);
assert_eq!(children[0].id, "p1");
assert_eq!(children[2].id, "p2");
let BlockContent::Table(data) = &children[1].content else {
panic!("a table goes right below the selected block");
let original = session.node("n").unwrap();
for text_range in [false, true] {
if text_range {
session.app.update(|cx| {
session
.window
.update(cx, |view, window, cx| {
view.change_selection(
DocumentSelection {
anchor: DocPoint::new("parent", 3),
focus: DocPoint::new("sibling", 3),
},
window,
cx,
);
})
.unwrap();
});
} else {
session.overlay(OverlayEvent::SelectBlock("parent".into()));
}
let frame = session.settle();
assert!(frame.elements.contains_key("overlay.format_toolbar"));
assert!(
!frame
.elements
.contains_key("overlay.format_toolbar.create_table")
);
session.app.update(|cx| {
session
.window
.update(cx, |view, window, cx| {
view.run_create_table_from_selection(window, cx).unwrap();
})
.unwrap();
});
assert_eq!(session.node("n").unwrap(), original);
}
}
#[test]
fn create_table_rejects_blocks_with_a_database_ancestor() {
use blocksuite_playground_doc::schema::DatabaseSpec;
let session = open_page(800, PlaygroundOptions::default(), |state| {
let page = home(state);
add(
page,
"database",
BlockSpec::Database(DatabaseSpec::default()),
);
page.add_block("row", paragraph("Roadmap"), Some("database"), None, 1)
.unwrap();
page.add_block("child", paragraph("Research"), Some("row"), None, 1)
.unwrap();
});
let original = session.node("database").unwrap();
for id in ["row", "child"] {
session.app.update(|cx| {
session
.window
.update(cx, |view, window, cx| {
view.editor.selection = None;
view.editor.block_selection = vec![id.into()];
view.run_create_table_from_selection(window, cx).unwrap();
})
.unwrap();
});
assert_eq!(session.node("database").unwrap(), original);
}
}
fn save_editor_interaction_evidence(session: &Session, filename: &str) {
let Ok(dir) = std::env::var("EDITOR_INTERACTION_EVIDENCE_DIR") else {
return;
};
let focus = session.view(|v, _| {
v.table_cell
.as_ref()
.map(|c| (c.block_id.clone(), c.row_id.clone(), c.column_id.clone()))
});
assert_eq!(
focus,
Some((
children[1].id.clone(),
data.rows[0].row_id.clone(),
data.columns[0].column_id.clone()
))
);
assert!(session.view(|v, _| v.editor.block_selection.is_empty()));
std::fs::create_dir_all(&dir).expect("evidence directory");
let frame = session
.app
.update(|cx| {
session
.window
.update(cx, |_, window, _| window.render_to_image())
.expect("window")
})
.expect("render evidence");
frame
.save(std::path::Path::new(&dir).join(filename))
.expect("save evidence");
}
#[test]
fn edgeless_more_opens_linked_and_synced_cards_with_host_modes() {
use crate::PlaygroundMode;
for (theme, tag, synced, width, same_doc) in [
(PlaygroundTheme::Light, "light-linked", false, 1280, false),
(PlaygroundTheme::Dark, "dark-linked", false, 1280, false),
(PlaygroundTheme::Light, "light-synced", true, 1280, false),
(PlaygroundTheme::Dark, "dark-synced", true, 1280, false),
(PlaygroundTheme::Light, "narrow", false, 639, true),
] {
let target = if same_doc { HOME_PAGE_ID } else { "doc:target" };
let options = PlaygroundOptions {
theme,
mode: PlaygroundMode::Edgeless,
..Default::default()
};
let session = open_at(width, 760, options, |state| {
if !same_doc {
state
.workspace
.create_page(target, "Release roadmap", 1)
.unwrap();
let linked = state.workspace.page_mut(target).unwrap();
linked
.add_block(
"target-root",
BlockSpec::Page {
title: "Release roadmap".into(),
},
None,
None,
1,
)
.unwrap();
linked
.add_block(
"target-note",
BlockSpec::Note { xywh: None },
Some("target-root"),
None,
2,
)
.unwrap();
linked
.add_block(
"target-body",
paragraph("Review the release milestones."),
Some("target-note"),
None,
3,
)
.unwrap();
}
let page = home(state);
add(page, "plan", paragraph("Release planning"));
page.add_block("surface", BlockSpec::Surface, Some("page-root"), None, 3)
.unwrap();
let spec = if synced {
BlockSpec::EmbedSyncedDoc {
page_id: target.into(),
caption: String::new(),
}
} else {
BlockSpec::EmbedLinkedDoc {
page_id: target.into(),
style: "horizontal".into(),
caption: String::new(),
}
};
page.add_block("card", spec, Some("surface"), None, 4)
.unwrap();
page.set_block_prop(
"card",
"prop:xywh",
SessionValue::Any(Any::String("[960,150,300,140]".into())),
5,
)
.unwrap();
});
let requests = Rc::new(RefCell::new(Vec::<OpenDocRequest>::new()));
session.view(|v, cx| {
let received = requests.clone();
v.set_open_doc_handler(move |request, _, _| received.borrow_mut().push(request));
v.edgeless.authoring.selection.insert("card".into());
cx.notify();
});
let toolbar = session.settle();
session.click(&toolbar, "chrome.edgeless_element_toolbar.more");
let frame = session.settle();
let item = |suffix: &str| format!("chrome.edgeless_element_toolbar.more.{suffix}");
assert_eq!(
frame.elements.contains_key(&item("open_split_view")),
width >= 640
);
if !same_doc {
save_editor_interaction_evidence(&session, &format!("{tag}-edgeless-open.png"));
}
for (suffix, mode) in [
("open_this_doc", ReferenceOpenMode::ActiveView),
("open_split_view", ReferenceOpenMode::SplitView),
("open_new_tab", ReferenceOpenMode::NewTab),
("open_center_peek", ReferenceOpenMode::CenterPeek),
] {
if mode == ReferenceOpenMode::SplitView && width < 640 {
continue;
}
let frame = session.settle();
let frame = if frame.elements.contains_key(&item(suffix)) {
frame
} else {
session.click(&frame, "chrome.edgeless_element_toolbar.more");
session.settle()
};
let before = requests.borrow().len();
session.click(&frame, &item(suffix));
let requests = requests.borrow();
if same_doc && mode == ReferenceOpenMode::ActiveView {
assert_eq!(requests.len(), before);
} else {
assert_eq!(requests.len(), before + 1);
assert_eq!(requests[before].doc_id, target);
assert_eq!(requests[before].open_mode, mode);
}
}
}
}
#[test]
fn bare_url_space_preserves_the_raw_link_through_markdown_copy_and_two_undos() {
for (theme, tag, url) in [
(
PlaygroundTheme::Light,
"light",
"https://example.com/roadmap",
),
(PlaygroundTheme::Dark, "dark", "https://example.com/roadmap"),
(
PlaygroundTheme::Light,
"light-uppercase",
"HTTPS://EXAMPLE.COM/Roadmap",
),
(
PlaygroundTheme::Dark,
"dark-uppercase",
"HTTP://EXAMPLE.ORG",
),
(
PlaygroundTheme::Light,
"light-unicode",
"https://example.org/東京",
),
] {
let session = open_page(
800,
PlaygroundOptions {
theme,
..Default::default()
},
|state| {
add(home(state), "url", paragraph(url));
},
);
let url_utf16 = url.encode_utf16().count();
session.overlay(OverlayEvent::SetSelection(Some(ActiveSelection {
block_id: "url".into(),
start_utf16: url_utf16,
end_utf16: url_utf16,
})));
let _ = session.settle();
save_editor_interaction_evidence(&session, &format!("{tag}-url-before.png"));
session.type_text(" ");
let _ = session.settle();
save_editor_interaction_evidence(&session, &format!("{tag}-url-after.png"));
let text = session.text("url");
assert_eq!(text.plain, format!("{url} "));
assert!(matches!(&text.delta[..], [
TextDeltaOp::Insert {
insert: y_octo::TextInsert::Text(value), format: Some(marks),
},
TextDeltaOp::Insert {
insert: y_octo::TextInsert::Text(space), format: None,
},
] if value == url && marks.get("link") == Some(&Any::String(url.into())) && space == " "));
session.select("url", url);
let frame = session.settle();
session.click(&frame, "overlay.format_toolbar.more");
let frame = session.settle();
session.click(&frame, "overlay.format_toolbar.more.copy_markdown");
let markdown = session
.view(|_, cx| cx.read_from_clipboard().and_then(|item| item.text()))
.expect("copied Markdown");
assert_eq!(markdown, format!("[{url}]({url})"));
session.undo();
let text = session.text("url");
assert_eq!(text.plain, format!("{url} "));
assert!(
text.delta
.iter()
.all(|op| matches!(op, TextDeltaOp::Insert { format: None, .. }))
);
session.undo();
let text = session.text("url");
assert_eq!(text.plain, url);
assert!(matches!(
&text.delta[..],
[TextDeltaOp::Insert { format: None, .. }]
));
}
}
fn table_data(session: &Session) -> TableData {
@@ -16,50 +16,6 @@ use crate::{
};
impl PlaygroundView {
/// Insert a 2 × 2 table below the text selection or the last selected block, and focus its
/// first cell.
pub(crate) fn run_create_table_from_selection(
&mut self,
window: &mut Window,
cx: &mut Context<Self>,
) -> DocResult {
let Some(anchor) = self
.editor
.selection
.as_ref()
.map(|s| s.focus.block_id.clone())
.or_else(|| self.editor.block_selection.last().cloned())
else {
return Ok(());
};
let empty_row = vec![String::new(), String::new()];
let spec = BlockSpec::Table {
rows: vec![empty_row.clone(), empty_row],
};
let Some(table_id) =
self.insert_sibling_after_block(&anchor, spec, false, true, window, cx)?
else {
return Ok(());
};
let first_cell = self
.snapshot
.as_ref()
.and_then(|s| s.block(&table_id))
.and_then(|n| match &n.content {
blocksuite_playground_doc::read::BlockContent::Table(t) => Some((
t.rows.first()?.row_id.clone(),
t.columns.first()?.column_id.clone(),
)),
_ => None,
});
if let Some((row_id, column_id)) = first_cell {
self.editor.selection = None;
self.clear_block_selection_fields();
self.focus_table_cell(table_id, row_id, column_id, None, window, cx);
}
Ok(())
}
/// Apply dual-field `Text` + `Link` edit: replaces display text (if modified on a single-block
/// selection) and sets the `link` mark in one atomic undo step.
pub(crate) fn apply_link_with_display_text(
@@ -359,7 +315,11 @@ impl PlaygroundView {
.collect()
}
fn format_text_block_ids(&self, snapshot: &PageSnapshot, layout: &FlowLayout) -> Vec<String> {
pub(super) fn format_text_block_ids(
&self,
snapshot: &PageSnapshot,
layout: &FlowLayout,
) -> Vec<String> {
let Some((start, end, _, _, _)) = self
.editor
.selection
@@ -0,0 +1,144 @@
use std::collections::HashSet;
use blocksuite_playground_doc::{
DocResult,
read::PageSnapshot,
schema::{BlockSpec, DatabaseSpec, DatabaseViewSpec},
};
use serde_json::json;
use ui::{Context, Window};
use crate::PlaygroundView;
struct ConversionSource {
block_id: String,
parent_id: String,
slot: usize,
}
impl PlaygroundView {
pub(super) fn can_convert_to_database(&self, snapshot: &PageSnapshot, ids: &[String]) -> bool {
self.database_conversion_sources(snapshot, ids).is_some()
}
fn database_conversion_sources(
&self,
snapshot: &PageSnapshot,
ids: &[String],
) -> Option<Vec<ConversionSource>> {
let whole_blocks = self.editor.selection.is_none();
let min_blocks = if whole_blocks { 1 } else { 2 };
if self.database_readonly() || ids.len() < min_blocks {
return None;
}
let root = snapshot.root.as_ref()?;
let mut remaining: HashSet<_> = ids.iter().map(String::as_str).collect();
let mut sources = Vec::new();
let mut pending = vec![(root, None, 0, false, false)];
while let Some((block, parent_id, slot, selected_ancestor, inside_database)) = pending.pop()
{
if remaining.is_empty() && !selected_ancestor {
break;
}
let selected = remaining.remove(block.id.as_str()) || selected_ancestor;
if selected {
if inside_database
|| !matches!(block.flavour.as_str(), "affine:paragraph" | "affine:list")
{
return None;
}
sources.push(ConversionSource {
block_id: block.id.clone(),
parent_id: String::from(parent_id?),
slot,
});
}
pending.extend(
block
.children
.iter()
.enumerate()
.rev()
.map(|(slot, child)| {
(
child,
Some(block.id.as_str()),
slot,
whole_blocks && selected,
inside_database || block.flavour == "affine:database",
)
}),
);
}
remaining.is_empty().then_some(sources)
}
pub(crate) fn run_create_table_from_selection(
&mut self,
window: &mut Window,
cx: &mut Context<Self>,
) -> DocResult {
let Some(snapshot) = self.page_snapshot() else {
return Ok(());
};
let text_ids;
let ids = if self.editor.selection.is_some() {
let Some(layout) = self.flow_layout() else {
return Ok(());
};
text_ids = self.format_text_block_ids(snapshot, &layout);
&text_ids
} else {
&self.editor.block_selection
};
let Some(sources) = self.database_conversion_sources(snapshot, ids) else {
return Ok(());
};
let Some(first) = sources.first() else {
return Ok(());
};
let before = self.selection_snapshot();
let database = self.fresh_block_id();
let now = self.now_ms(cx) as u64;
let page = self.page_mut()?;
let commit = page.structural_edit(now, |page| {
page.add_block(
&database,
BlockSpec::Database(DatabaseSpec {
title: "Database".into(),
views: vec![DatabaseViewSpec {
id: "view-table".into(),
name: "Table View".into(),
mode: "table".into(),
raw: json!({
"columns": [{"id": "title", "width": 220}],
"filter": {"type": "group", "op": "and", "conditions": []},
"header": {"titleColumn": "title", "iconColumn": "type"}
}),
}],
..DatabaseSpec::default()
}),
Some(&first.parent_id),
Some(first.slot as u64),
now,
)?;
for (row, source) in sources.iter().enumerate() {
page.reparent_block(
&source.block_id,
&source.parent_id,
&database,
row as u64,
now,
)?;
}
Ok(())
})?;
if let Some(before) = before {
page.set_undo_selection_snapshot(before)?;
}
self.editor.selection = None;
self.clear_block_selection_fields();
self.did_edit(commit, None, window, cx);
Ok(())
}
}
@@ -2,6 +2,7 @@
//! `Text`+`Link` editing, `InlineEquation`, `CreateLinkedDoc`, `CreateTable`, and `More`).
mod actions;
mod convert;
#[cfg(test)]
mod tests;
@@ -145,7 +146,13 @@ impl PlaygroundView {
align,
selected_text,
current_turn_into_id,
can_create_table: single_block,
can_create_table: !single_block
&& self.page_snapshot().is_some_and(|snapshot| {
self.can_convert_to_database(
snapshot,
&self.format_text_block_ids(snapshot, layout),
)
}),
})
}
@@ -272,7 +279,9 @@ impl PlaygroundView {
align,
selected_text: None,
current_turn_into_id,
can_create_table: true,
can_create_table: self.page_snapshot().is_some_and(|snapshot| {
self.can_convert_to_database(snapshot, &self.editor.block_selection)
}),
})
}
}
@@ -6,7 +6,7 @@
use std::time::Duration;
use blocksuite_playground_doc::{
read::{BlockContent, TextAlign},
read::TextAlign,
schema::{BlockSpec, ParagraphType},
};
use ui::{
@@ -96,7 +96,7 @@ fn move_to(s: &MobileSession, x: f32, y: f32, pressed: bool) {
}
#[test]
fn format_toolbar_highlight_vertical_list_and_create_table() {
fn format_toolbar_highlight_vertical_list_and_table_selection_gate() {
let s = MobileSession::open(1280, 800, PlaygroundTheme::Light);
let mut state = DocState::new("fmt-chrome", 11).expect("doc");
state
@@ -149,7 +149,7 @@ fn format_toolbar_highlight_vertical_list_and_create_table() {
let f = s.frame();
assert!(by_id(&f, "overlay.format_toolbar").is_some());
assert!(by_id(&f, "overlay.format_toolbar.align").is_some());
assert!(by_id(&f, "overlay.format_toolbar.create_table").is_some());
assert!(by_id(&f, "overlay.format_toolbar.create_table").is_none());
assert!(by_id(&f, "overlay.format_toolbar.more").is_some());
// Open Highlight vertical dual-section labelled list.
@@ -163,24 +163,10 @@ fn format_toolbar_highlight_vertical_list_and_create_table() {
assert!(by_id(&f_hl, "overlay.format_toolbar.highlight.color.default").is_some());
assert!(by_id(&f_hl, "overlay.format_toolbar.highlight.background.blue").is_some());
// Click Create Table -> inserts an affine:table block into the document.
s.overlay(OverlayEvent::Format(FormatAction::CreateTable));
let _ = s.frame();
let has_table = s.view(|v| {
v.page_snapshot()
.and_then(|snap| snap.root.as_ref())
.is_some_and(|root| {
root.children.iter().any(|note| {
note.children
.iter()
.any(|b| matches!(b.content, BlockContent::Table(_)))
})
})
});
assert!(
has_table,
"Create Table should insert an affine:table block"
);
s.overlay(OverlayEvent::SelectBlock("p1".into()));
s.platform.advance_clock(Duration::from_millis(200));
s.platform.run_until_parked();
assert!(by_id(&s.frame(), "overlay.format_toolbar.create_table").is_some());
}
#[test]
+4 -5
View File
@@ -419,12 +419,11 @@ async function checkLinkField(cdp) {
`Unable to select in the second showcase block: ${JSON.stringify(paragraph)}`
);
}
// A selection in one paragraph shows the full desktop toolbar with `Create Table`:
// 490 px wide and 37 px tall, centered on the selection 10 px above the selected line.
// Its `Link` button (center 299 px from the left edge, 18 px from the top) opens the
// dual-field Text+URL editor with keyboard/IME focus starting in the empty URL field.
// A selection in one paragraph shows a 462 px toolbar without Create Table.
// It sits 10 px above the selected line and is 37 px tall.
// The Link button center is 299 px from the left edge and 18 px from the top.
const midX = (from[0] + to[0]) / 2;
const link = [midX - 245 + 299, 243 - 10 - 37 + 18];
const link = [midX - 462 / 2 + 299, 243 - 10 - 37 + 18];
await mouse('mouseMoved', link, 0);
await mouse('mousePressed', link, 1);
await mouse('mouseReleased', link, 0);