feat(editor): add media card actions and table cell controls

This commit is contained in:
DarkSky committed 2026-12-05 09:15:06 +09:00
1 parent 169df763f2
commit 7b7d002327
40 files changed
+2965 -357

No files matched your search

+1 -1
View File
@@ -45,7 +45,7 @@ These crates belong to the client Cargo workspace rooted at `packages/frontend/C
- **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. A whole-block selection of a divider, equation, table, database, or unknown block shows the linked-document and More actions. `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. `Create Linked Doc` opens the `Create linked doc` title dialog (`LinkedDocSource`, prefilled with the first block when it is a heading); `Confirm` moves the whole blocks that the selection touches, with their subtrees and every property (marks, embeds, code text, and table and database cells included), into a new linked page titled with the input (`Untitled` when blank) and puts an `affine:embed-linked-doc` card in their place in one undo step, and `Cancel`, `Escape`, or an outside press write nothing; `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.
- **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`, unmodified `Tab` / `Shift+Tab` move to the end of the adjacent cell in row order without writing and stay on the first or last cell at the grid edges, `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; a non-empty selection within one cell uses the floating format toolbar for inline marks, links, and colors in one undo step.
- **Database authoring & mobile record sheet** (`database/{authoring,authoring_dispatch,cell_editor,column_ops,calendar_edit,filter_sort_bar,popover_overlay}.rs`, `playground/src/database_authoring/`, `overlays/view_mobile/record_sheet/`): `affine:database` (`Table`, `Kanban`, `Calendar`) supports typed `Y.Array` multi-select cells, incremental `Y.Text` splicing for row titles and rich-text cells (preserving marks and `@reference` embeds with zero writeback on no-op blur/`Enter`, unified on `AnchoredInlineInput` + `finish_inline_targets`), screen-space `Overlays` popovers (`ColumnMenu`, `SelectPicker`, `Filter`/`Sort`/`Group` panels, keeping block height invariant under `scroll_x > 0`), lossless Filter/Sort JSON patching with cascading column-delete cleanup, Kanban card title editing and type-safe lane creation, Calendar day `+` creation and reschedule drag, `@reference` (`LinkedPage`) title expansion across all four views (`resolve_rich_text_plain`), a `RecordSheet` bottom sheet that desktop shows as a centered record peek (on a writable page, clicking its title edits it in place, splicing each keystroke into the live row title `Y.Text` like a `title` cell so peer edits merge and one undo removes only the local typing, while `Enter`, `Escape`, an outside click, or closing the peek only end the edit and write nothing; clicking a checkbox flips it in one undo step; a double click on a Calendar event edits its title in place only right after its first click opened the peek), and `database_readonly` / `page_readonly` enforced across all mutation entry points.
- **Drag handle** (`overlay.drag_handle`, `overlay.drop_indicator`): 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 selects the block and opens `overlay.format_toolbar`. A second click on a single selected block clears the selection. Dragging resolves multi-level `TreeDropTarget` slots (`+24 px` horizontal indent steps reusing `Tab`'s parent-child legality predicate, moving collapsed heading sections atomically, and expanding a collapsed list parent on drop). A heading keeps the place beside its text for its collapse chevron, while non-heading `Paragraph` and `Quote` blocks with children expose a local-only disclosure chevron without writing `prop:collapsed` into CRDT.
- **Block controls & block toolbars**: `page.block.<id>.checkbox`, `.toggle` and `.collapse` are 24 px targets over the to-do box, the toggle chevron and the heading chevron (an expanded heading shows its chevron only while the pointer is on its row, and `page.block_selection` highlights merged visible nested subtrees while skipping collapsed children); all captioned blocks (`affine:image`, `affine:code`, `affine:bookmark`, `affine:attachment`, `affine:embed-linked-doc`, `affine:embed-synced-doc`, `affine:embed-*`, and `affine:surface-ref`) edit `prop:caption` directly in place via `AnchoredInlineInput` + `Utf16ImeBuffer` + `finish_inline_targets` (centered below content with `Write a caption` placeholder when empty, live untrimmed writes storing `""` within the 500 ms undo window, Page-mode `Enter` splitting into a sibling `affine:paragraph` in one `structural_edit`, `Escape`/blur hiding empty slots, and `page_readonly` visible read-only; no detached caption prompt). Desktop `affine:code` blocks show zero top-bar chrome at rest and reveal a borderless hover-only icon toolbar (`page.block.<id>.toolbar`, `.language`, optional `[Code | Preview]` segmented switcher `.preview_code`/`.preview`, uniform `28 × 28` `.copy` swapping `CopyIcon` → `DoneIcon` for 1.5 s with `context_toast`, `.collapse`, `.caption_btn` with `CaptionIcon`, and `.more` opening `overlay.code_more_menu` with `Wrap code`, `Line number`, `Copy as Markdown`, `Copy link to block`, `Duplicate`, and hover-red `Delete`; 0 ms enter / 250 ms leave delay / 100 ms fade, hidden on non-collapsed text selections; on Phone/Tablet/touch hosts, code blocks use `12 px` padding and line numbers default off via `code_line_number_default`, and focusing or selecting a code block docks a horizontally scrollable `>= 44 × 44 pt` bottom context toolbar via `place_touch_docked_toolbar` above `KeyboardToolbar` exposing `.language`, conditional `.preview`, `.copy`, `.caption_btn`, `.wrap`, `.line_number`, `.collapse`, and pinned `.delete` and `.more`. The touch More menu offers `Copy as Markdown`, `Copy link to block`, and `Duplicate`. Both menus keep the copy actions available on read-only pages. Collapsed code has an `80 px` collapsed fade with `padding-bottom: 0`. Selected `affine:image`, `affine:bookmark`, embed, and `affine:callout` blocks mount toolbars on the shared `ToolbarChrome`: `overlay.image_toolbar` (`Download` when the host can save the blob, `Caption`, `Align Left` / `Align Center` / `Align Right`, and `.more_menu` with `Copy`, `Duplicate`, `Turn into card view`, and `Delete`; hidden while `overlay.image_lightbox` is open; double-clicking an image opens fullscreen `overlay.image_lightbox` with uniform aspect-preserving zoom, clipped viewport drag-pan / proportional wheel & pinch zoom, and modal key capture), `overlay.bookmark_toolbar` (`.open`, a `Card view` dropdown `.view_menu` with `Inline view` / `Card view` / host-validated `Embed view`, a Page-mode `.style` dropdown `.style_menu` with `Large horizontal` / `Small horizontal`, `.caption`, and `.more_menu` with `Copy`, `Duplicate`, and `Delete`, plus inline `overlay.url_paste_menu` on plain URL paste), `overlay.embed_toolbar` (`.open`, `.preview`, `.view` / `.view_menu`, `.style` / `.style_menu`, `.caption`, and `.more_menu`), and `overlay.callout_toolbar` (`.icon` opening `overlay.callout_icon_picker` with `{"type":"emoji","unicode":...}` `IconData` Map items and `.remove`, a `Background` dropdown `.color` / `.color_menu` with 9 `0.27.5` semantic swatches `.bg.<name>`, and `.more_menu` with `Delete`), docking cleanly as horizontally scrollable `>= 44 × 44 pt` bottom context bars on touch viewports down to `360 pt`. A mouse image resize owns the pointer until the release, so the toolbar inside the image never takes the move or the release. Block-level `affine:latex` uses 2-step selection (first click selects block, second click opens `overlay.equation_editor`). A sideways scroll over an unwrapped code block scrolls its lines inside `BlockBody::code_scroll` instead of the page; the caret, selection, IME bounds, collaborators' carets/selections, and pointer hit-testing follow that scroll (`ScrolledCode`).
@@ -87,11 +87,12 @@ impl FlowPass<'_> {
pub(super) fn embed_linked_doc_body(
&mut self,
block_id: &str,
node: &BlockNode,
page_id: &str,
caption: &str,
width: f32,
) -> BlockBody {
let block_id = &node.id;
let doc_id = EditorDocId::from(page_id);
let preview = self
.input
@@ -107,11 +108,20 @@ impl FlowPass<'_> {
.get(page_id)
.map(String::as_str)
.filter(|s| !s.trim().is_empty());
let resolved_title = title_from_preview.or(title_from_map).unwrap_or("Untitled");
let alias = |key| {
node.props
.get(key)
.and_then(serde_json::Value::as_str)
.filter(|s| !s.trim().is_empty())
};
let resolved_title = alias("prop:title")
.or(title_from_preview)
.or(title_from_map)
.unwrap_or("Untitled");
let snippet = preview
.as_ref()
.map(|p| p.snippet.trim().to_string())
let snippet = alias("prop:description")
.map(str::to_owned)
.or_else(|| preview.as_ref().map(|p| p.snippet.trim().to_string()))
.filter(|s| !s.is_empty())
.or_else(|| {
self.input
@@ -510,6 +510,11 @@ impl<'a> FlowPass<'a> {
},
_ => 0,
};
let linked_doc_alias = matches!(&node.content, BlockContent::EmbedLinkedDoc { .. })
.then(|| {
["prop:title", "prop:description"]
.map(|key| node.props.get(key).and_then(|value| value.as_str()))
});
let caption_draft_for_node = self.caption_draft.filter(|d| d.block_id == node.id);
let fingerprint = (
&node.content,
@@ -529,7 +534,7 @@ impl<'a> FlowPass<'a> {
embed_card_state,
local_collapsed,
image_preview_sig,
extra_prop_sig,
(extra_prop_sig, linked_doc_alias),
caption_draft_for_node,
),
);
@@ -387,7 +387,7 @@ impl FlowPass<'_> {
),
BlockContent::EmbedLinkedDoc {
page_id, caption, ..
} => self.embed_linked_doc_body(&node.id, page_id, caption, width),
} => self.embed_linked_doc_body(node, page_id, caption, width),
BlockContent::EmbedSyncedDoc { page_id, caption } => {
self.embed_synced_doc_body(&node.id, page_id, caption, width)
}
@@ -0,0 +1,115 @@
use std::borrow::Cow;
/// Use an angle-delimited destination when a bare URL could close the Markdown link.
pub(super) fn link_destination(url: &str) -> Cow<'_, str> {
if !url
.chars()
.any(|c| c.is_whitespace() || matches!(c, '(' | ')' | '<' | '>' | '\\'))
{
return Cow::Borrowed(url);
}
let mut out = String::with_capacity(url.len() + 2);
out.push('<');
for ch in url.chars() {
if matches!(ch, '<' | '>' | '\\') {
out.push('\\');
}
out.push(ch);
}
out.push('>');
Cow::Owned(out)
}
/// Read an angle-delimited or bare destination, honoring backslash escapes.
pub(super) fn split_link_destination(input: &str) -> Option<(Cow<'_, str>, &str)> {
let angle = input.starts_with('<');
let body = if angle { &input[1..] } else { input };
let mut chars = body.char_indices().peekable();
let mut depth = 0;
let mut decoded = String::new();
let mut copied = 0;
while let Some((index, ch)) = chars.next() {
if ch == '\\'
&& let Some(&(next, punctuation)) = chars.peek()
&& punctuation.is_ascii_punctuation()
{
decoded.push_str(&body[copied..index]);
decoded.push(punctuation);
copied = next + punctuation.len_utf8();
chars.next();
continue;
}
if ch == '\n' || ch == '\r' || (angle && ch == '<') {
return None;
}
if !angle && ch == '(' {
depth += 1;
} else if !angle && ch == ')' && depth > 0 {
depth -= 1;
} else if (angle && ch == '>') || (!angle && ch == ')') {
let after = &body[index + 1..];
let tail = if angle {
after.strip_prefix(')')?
} else {
after
};
let destination = if copied == 0 {
Cow::Borrowed(&body[..index])
} else {
decoded.push_str(&body[copied..index]);
Cow::Owned(decoded)
};
return Some((destination, tail));
}
}
None
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use serde_json::json;
use y_octo::{Any, TextDeltaOp, TextInsert};
use crate::clipboard::{Slice, SliceBlock};
#[test]
fn media_and_inline_links_round_trip_an_unmatched_closing_parenthesis() {
const URL: &str = "https://example.com/report?filter=closed)&view=weekly";
const ESCAPED: &str = r"[Report](https://example.com/report?filter=closed\)&view=weekly)";
let inline = Slice::from_markdown(ESCAPED).expect("read escaped inline link");
let bookmark = Slice::new(
"workspace",
"page",
vec![SliceBlock {
kind: "block".into(),
id: "report".into(),
flavour: "affine:bookmark".into(),
version: None,
props: BTreeMap::from([
("title".into(), json!("Report")),
("url".into(), json!(URL)),
]),
children: Vec::new(),
}],
);
for source in [inline, bookmark] {
let markdown = source.to_markdown();
assert_eq!(markdown, format!("[Report](<{URL}>)"));
let parsed = Slice::from_markdown(&markdown).expect("read exported link");
let delta = parsed.content[0].delta();
let [
TextDeltaOp::Insert {
insert: TextInsert::Text(label),
format: Some(attrs),
},
] = delta.as_slice()
else {
panic!("expected one link run: {delta:?}");
};
assert_eq!(label, "Report");
assert_eq!(attrs.get("link"), Some(&Any::String(URL.into())));
}
}
}
@@ -0,0 +1,96 @@
use std::fmt::Write as _;
use serde_json::Value;
use super::{InlineReference, ReferenceLink, SliceBlock, link_destination, sanitize_url};
use crate::rich_text::InlineReferenceParams;
pub(super) fn media_to_markdown(
block: &SliceBlock,
reference_link: &ReferenceLink,
) -> Option<String> {
let prop = |key| {
block
.props
.get(key)
.and_then(Value::as_str)
.filter(|value| !value.is_empty())
};
let (label, url) = match block.flavour.as_str() {
"affine:embed-linked-doc" | "affine:embed-synced-doc" => {
let params = block.props.get("params");
let ids = |key| {
params
.and_then(|p| p.get(key))
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str)
.map(str::to_owned)
.collect()
};
reference_link(&InlineReference {
kind: "LinkedPage".into(),
page_id: prop("pageId")?.into(),
title: prop("title").map(str::to_owned),
params: Some(InlineReferenceParams {
mode: params
.and_then(|p| p.get("mode"))
.and_then(Value::as_str)
.map(str::to_owned),
block_ids: ids("blockIds"),
element_ids: ids("elementIds"),
}),
})?
}
"affine:image" | "affine:attachment" => {
let mut asset = String::new();
for byte in prop("sourceId")?.bytes() {
if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
asset.push(char::from(byte));
} else {
let _ = write!(asset, "%{byte:02X}");
}
}
let label = if block.flavour == "affine:image" {
prop("caption").or_else(|| prop("alt")).unwrap_or("Image")
} else {
prop("name").unwrap_or("Attachment")
};
(label.to_owned(), format!("assets/{asset}"))
}
"affine:bookmark" => (
prop("title").or_else(|| prop("url"))?.into(),
sanitize_url(prop("url")?)?,
),
flavour
if blocksuite_playground_doc::read::ExternalEmbedKind::from_flavour(flavour)
.is_some() =>
{
(
prop("title").or_else(|| prop("url"))?.into(),
sanitize_url(prop("url")?)?,
)
}
_ => return None,
};
let label = escape_link_label(&label);
let image = if block.flavour == "affine:image" {
"!"
} else {
""
};
Some(format!("{image}[{label}]({})", link_destination(&url)))
}
pub(super) fn escape_link_label(label: &str) -> String {
label
.chars()
.flat_map(|c| {
matches!(c, '\\' | '[' | ']')
.then_some('\\')
.into_iter()
.chain([c])
})
.collect()
}
@@ -9,6 +9,13 @@ use y_octo::{Any, TextAttributes, TextDeltaOp, TextInsert};
use super::{Slice, SliceBlock, sanitize::sanitize_url, text_value};
use crate::rich_text::{InlineMarkSet, InlineReference};
mod destination;
mod media;
use destination::{link_destination, split_link_destination};
use media::{escape_link_label, media_to_markdown};
/// Resolves an inline `@reference` to the title and URL of its Markdown link.
pub type ReferenceLink<'a> = dyn Fn(&InlineReference) -> Option<(String, String)> + 'a;
@@ -44,7 +51,9 @@ fn export_block(
*after_table = table.is_some();
let indent = " ".repeat(depth);
let inline = delta_to_markdown(&block.delta(), reference_link);
let media = media_to_markdown(block, reference_link);
match block.flavour.as_str() {
_ if media.is_some() => out.extend(media.map(|media| format!("{indent}{media}"))),
"affine:code" => {
let lang = block
.props
@@ -210,15 +219,7 @@ fn delta_to_markdown(delta: &[TextDeltaOp], reference_link: &ReferenceLink) -> S
.reference
.and_then(|reference| reference_link(&reference));
if let Some((title, _)) = &reference {
chunk = title
.chars()
.flat_map(|c| {
matches!(c, '\\' | '[' | ']')
.then_some('\\')
.into_iter()
.chain([c])
})
.collect();
chunk = escape_link_label(title);
}
if attrs.get("code") == Some(&Any::True) {
chunk = format!("`{chunk}`");
@@ -239,7 +240,7 @@ fn delta_to_markdown(delta: &[TextDeltaOp], reference_link: &ReferenceLink) -> S
_ => None,
});
if let Some(url) = url {
chunk = format!("[{chunk}]({url})");
chunk = format!("[{chunk}]({})", link_destination(&url));
}
}
out.push_str(&chunk);
@@ -477,26 +478,6 @@ fn rich_list_block(
b
}
/// Split a Markdown link/image destination at its matching `)`, supporting balanced
/// nested parentheses such as `https://example.com/a_(b)`.
fn split_balanced_paren(s: &str) -> Option<(&str, &str)> {
let mut depth = 0usize;
for (idx, ch) in s.char_indices() {
match ch {
'(' => depth += 1,
')' => {
if depth == 0 {
return Some((&s[..idx], &s[idx + 1..]));
}
depth -= 1;
}
'\n' => return None,
_ => {}
}
}
None
}
/// Parse inline Markdown (`**bold**`, `*italic*`, `~~strike~~`, `` `code` ``,
/// `[text](url)`, `$latex$`) into BlockSuite Y.Text delta operations with strict URL sanitization.
pub fn parse_inline_markdown(input: &str) -> Vec<TextDeltaOp> {
@@ -606,11 +587,11 @@ pub fn parse_inline_markdown(input: &str) -> Vec<TextDeltaOp> {
// Image ![alt](url)
if let Some(after) = rest.strip_prefix("![")
&& let Some((alt, after_alt)) = after.split_once("](")
&& let Some((url, tail)) = split_balanced_paren(after_alt)
&& let Some((url, tail)) = split_link_destination(after_alt)
{
flush(&mut plain, &mut ops);
let label = if alt.is_empty() { "image" } else { alt };
let format = sanitize_url(url)
let format = sanitize_url(&url)
.map(|clean| TextAttributes::from([("link".into(), Any::String(clean))]));
ops.push(TextDeltaOp::Insert {
insert: TextInsert::Text(label.to_string()),
@@ -622,10 +603,10 @@ pub fn parse_inline_markdown(input: &str) -> Vec<TextDeltaOp> {
// Link [label](url) with balanced parentheses support
if let Some(after) = rest.strip_prefix('[')
&& let Some((label, after_label)) = after.split_once("](")
&& let Some((url, tail)) = split_balanced_paren(after_label)
&& let Some((url, tail)) = split_link_destination(after_label)
{
flush(&mut plain, &mut ops);
let format = sanitize_url(url)
let format = sanitize_url(&url)
.map(|clean| TextAttributes::from([("link".into(), Any::String(clean))]));
ops.push(TextDeltaOp::Insert {
insert: TextInsert::Text(label.to_string()),
@@ -7,12 +7,18 @@ use ui::{
prelude::*, px,
};
use crate::theme::{FONT_SANS, Palette, TYPOGRAPHY};
use crate::{
block_flow::FlowRect,
theme::{FONT_SANS, Palette, TYPOGRAPHY},
};
use super::{
ChromeIcon, OverlayEvent, OverlayHost, OverlayScene, Overlays, POPOVER_BORDER,
POPOVER_EDGE_MARGIN, POPOVER_GAP, Placement, TOOLBAR_BUTTON, TOOLBAR_GAP, TOOLBAR_PADDING,
TOOLBAR_RADIUS, TOOLBAR_SEPARATOR_MARGIN, chrome_icon, emit, icon, place, place_popover,
BlockCopyRow, BlockToolbarSubmenu, ChromeIcon, MenuActionVariant, OverlayEvent, OverlayHost,
OverlayScene, Overlays, POPOVER_BORDER, POPOVER_EDGE_MARGIN, POPOVER_GAP, Placement,
TOOLBAR_BUTTON, TOOLBAR_CHROME_BORDER, TOOLBAR_GAP, TOOLBAR_MENU_ICON, TOOLBAR_MENU_MIN_W,
TOOLBAR_MENU_PADDING, TOOLBAR_MENU_ROW_H, TOOLBAR_PADDING, TOOLBAR_RADIUS,
TOOLBAR_SEPARATOR_MARGIN, block_copy_rows, chrome_icon, dismiss_submenu_outside, emit, icon,
menu_horizontal_separator, place, place_popover, toolbar_dropdown_panel, toolbar_menu_row,
};
/// Actions offered by the floating `overlay.attachment_toolbar` above a selected `affine:attachment`.
@@ -25,6 +31,8 @@ pub enum AttachmentToolbarAction {
OpenViewer,
Caption,
Copy,
CopyAsMarkdown,
CopyLinkToBlock,
Duplicate,
Delete,
}
@@ -82,8 +90,19 @@ impl Overlays {
scene: &OverlayScene<'_>,
palette: &Palette,
cx: &mut Context<V>,
) -> Option<AnyElement> {
) -> Vec<AnyElement> {
self.attachment_toolbar_rect = None;
self.attachment_submenu_rect = None;
self.render_attachment_toolbar_parts(scene, palette, cx)
.unwrap_or_default()
}
fn render_attachment_toolbar_parts<V: OverlayHost>(
&mut self,
scene: &OverlayScene<'_>,
palette: &Palette,
cx: &mut Context<V>,
) -> Option<Vec<AnyElement>> {
let block_id = scene.selected_attachment_block?;
if self
.bookmark_prompt()
@@ -110,6 +129,12 @@ impl Overlays {
let vp = scene.popover_viewport();
let touch = scene.is_touch || scene.form_factor.is_touch_form_factor();
// A desktop bar keeps the block clipboard actions and `Delete` in its `More` menu.
let more_open = !touch
&& matches!(
&self.block_submenu,
Some(BlockToolbarSubmenu::AttachmentMore(id)) if id == block_id
);
let compact_labels = touch || vp.w < 420.0;
let btn_size = if touch { 44.0_f32 } else { TOOLBAR_BUTTON };
let gap = if touch { 2.0_f32 } else { TOOLBAR_GAP };
@@ -159,7 +184,11 @@ impl Overlays {
inner_w += 2.0 * gap + 2.0 * sep_margin + 1.0;
}
}
inner_w += 4.0 * btn_size + 3.0 * gap;
inner_w += if touch {
4.0 * btn_size + 3.0 * gap
} else {
2.0 * btn_size + gap
};
if !is_pdf {
inner_w += btn_size + gap;
}
@@ -381,31 +410,64 @@ impl Overlays {
.into_any_element(),
cx,
));
row = row.child(make_icon_btn(
"copy",
false,
AttachmentToolbarAction::Copy,
icon("CopyIcon", icon_sz, palette.icon).into_any_element(),
cx,
));
row = row.child(make_icon_btn(
"duplicate",
false,
AttachmentToolbarAction::Duplicate,
icon("DuplicateIcon", icon_sz, palette.icon).into_any_element(),
cx,
));
let danger = palette
.theme
.css_var("--affine-error-color")
.unwrap_or(palette.icon);
row = row.child(make_icon_btn(
"delete",
false,
AttachmentToolbarAction::Delete,
icon("DeleteIcon", icon_sz, danger).into_any_element(),
cx,
));
if touch {
row = row.child(make_icon_btn(
"copy",
false,
AttachmentToolbarAction::Copy,
icon("CopyIcon", icon_sz, palette.icon).into_any_element(),
cx,
));
row = row.child(make_icon_btn(
"duplicate",
false,
AttachmentToolbarAction::Duplicate,
icon("DuplicateIcon", icon_sz, palette.icon).into_any_element(),
cx,
));
let danger = palette
.theme
.css_var("--affine-error-color")
.unwrap_or(palette.icon);
row = row.child(make_icon_btn(
"delete",
false,
AttachmentToolbarAction::Delete,
icon("DeleteIcon", icon_sz, danger).into_any_element(),
cx,
));
} else {
let toggle = OverlayEvent::ToggleBlockSubmenu(BlockToolbarSubmenu::AttachmentMore(
block_id.to_string(),
));
let ink = if more_open {
palette.brand
} else {
palette.icon
};
row = row.child(
div()
.id("att-tb-more")
.flex_none()
.w(px(btn_size))
.h(px(btn_size))
.rounded(px(4.0))
.flex()
.items_center()
.justify_center()
.cursor_pointer()
.when(more_open, |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| toggle.clone()))
.snapshot(
"overlay.attachment_toolbar.more",
Some("overlay.attachment_toolbar"),
)
.snapshot_focused(more_open)
.child(chrome_icon(ChromeIcon::MoreVertical, 16.0, ink)),
);
}
}
let root = place(rect)
@@ -423,7 +485,92 @@ impl Overlays {
.items_center()
.snapshot("overlay.attachment_toolbar", Some("root.canvas"))
.child(row);
Some(root.into_any_element())
let mut out = vec![root.into_any_element()];
if more_open && !scene.page_readonly {
out.push(self.render_attachment_more_menu(scene, rect, block_id, palette, cx));
}
Some(out)
}
/// The desktop `More` menu under the toolbar at `rect`: the block clipboard rows, then
/// `Delete`, as BlockSuite `0.27.5` `attachment/configs/toolbar.ts` places them.
fn render_attachment_more_menu<V: OverlayHost>(
&mut self,
scene: &OverlayScene<'_>,
rect: FlowRect,
block_id: &str,
palette: &Palette,
cx: &mut Context<V>,
) -> AnyElement {
let rows = block_copy_rows(scene);
let menu_h = (2.0 * (TOOLBAR_MENU_PADDING + TOOLBAR_CHROME_BORDER)
+ (rows.len() + 1) as f32 * TOOLBAR_MENU_ROW_H
+ 9.0)
.round();
let placed = place_popover(
FlowRect::new(
rect.right() - TOOLBAR_MENU_MIN_W,
rect.y,
TOOLBAR_MENU_MIN_W,
rect.h,
),
(TOOLBAR_MENU_MIN_W, menu_h),
scene.popover_viewport(),
Placement::BelowStart,
4.0,
POPOVER_EDGE_MARGIN,
);
self.attachment_submenu_rect = Some(placed.rect);
let event = |action| OverlayEvent::AttachmentToolbarAction {
block_id: block_id.to_string(),
action,
};
let mut panel = toolbar_dropdown_panel(
"attachment-more-menu",
placed.rect,
1.0,
true,
ui::snap_id!("overlay.attachment_toolbar.more_menu"),
"overlay.attachment_toolbar",
palette,
);
for row in rows {
let (suffix, label, icon_name) = row.label();
let action = match row {
BlockCopyRow::Copy => AttachmentToolbarAction::Copy,
BlockCopyRow::CopyAsMarkdown => AttachmentToolbarAction::CopyAsMarkdown,
BlockCopyRow::CopyLinkToBlock => AttachmentToolbarAction::CopyLinkToBlock,
BlockCopyRow::Duplicate => AttachmentToolbarAction::Duplicate,
};
panel = panel.child(toolbar_menu_row(
format!("att-more-{suffix}"),
ui::snap_id!("overlay.attachment_toolbar.more.{suffix}"),
"overlay.attachment_toolbar.more_menu",
label,
icon(icon_name, TOOLBAR_MENU_ICON, palette.icon).into_any_element(),
false,
MenuActionVariant::Normal,
true,
event(action),
palette,
cx,
));
}
panel = panel.child(menu_horizontal_separator(palette));
panel = panel.child(toolbar_menu_row(
"att-more-delete",
ui::snap_id!("overlay.attachment_toolbar.more.delete"),
"overlay.attachment_toolbar.more_menu",
"Delete",
icon("DeleteIcon", TOOLBAR_MENU_ICON, palette.icon).into_any_element(),
false,
MenuActionVariant::Destructive,
true,
event(AttachmentToolbarAction::Delete),
palette,
cx,
));
dismiss_submenu_outside(panel, rect, cx).into_any_element()
}
}
@@ -26,8 +26,9 @@ fn prompt_http_url(raw: &str) -> Option<String> {
}
/// Mode of the single-line block prompt (`Bookmark` URL creation/edit, `Embed` URL, or `@reference` alias).
#[derive(Clone, Debug, PartialEq, Eq)]
#[derive(Clone, Debug, PartialEq)]
pub enum BookmarkPromptKind {
CardAlias(super::CardAliasEdit),
/// Insert an `affine:bookmark` card after `block_id` (optionally replacing an empty
/// Slash-trigger paragraph).
BookmarkUrl {
@@ -230,6 +231,11 @@ impl Overlays {
let raw = prompt.input.clone().into_committed_text();
let block_id = prompt.block_id.clone();
match &prompt.kind {
BookmarkPromptKind::CardAlias(edit) => {
if !Self::save_card_alias(prompt, edit, effects) {
return;
}
}
BookmarkPromptKind::BookmarkUrl { remove_empty_block } => {
if let Some(url) = prompt_http_url(&raw) {
effects.edits.push(DocEdit::Bookmark {
@@ -333,6 +339,13 @@ impl Overlays {
{
return self.render_linked_doc_title_prompt(scene, palette, now_ms, window, cx);
}
if self
.bookmark
.as_ref()
.is_some_and(|p| matches!(p.kind, BookmarkPromptKind::CardAlias(_)))
{
return self.render_card_alias_prompt(scene, palette, now_ms, window, cx);
}
let prompt = self.bookmark.as_mut()?;
prompt.rect = None;
let progress = prompt.presence.progress(now_ms);
@@ -394,6 +407,7 @@ impl Overlays {
"overlay.bookmark_prompt.apply",
"overlay.bookmark_prompt.cancel",
),
BookmarkPromptKind::CardAlias(_) => return None,
BookmarkPromptKind::IframeUrl => (
SlashEmbedKind::Iframe.placeholder(),
"overlay.bookmark_prompt",
@@ -1,7 +1,8 @@
//! 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`.
//! (`overlay.bookmark_toolbar`): `Open`, `Copy link`, `Edit`, view switcher (`Inline` / active
//! `Card` / conditional `Embed`), Page-mode card style (`Horizontal` / `List`), `Caption`, and
//! the `Copy` / `Copy as Markdown` / `Copy link to block` / `Duplicate` / `Delete` menu, aligned
//! with BlockSuite `0.27.5` `bookmark/configs/toolbar.ts` and the AFFiNE linkable card actions.
use blocksuite_playground_doc::read::BlockContent;
use ui::{AnyElement, ClickEvent, Context, FontWeight, MouseButton, div, prelude::*, px};
@@ -12,14 +13,15 @@ use crate::{
};
use super::{
BlockToolbarSubmenu, ChromeIcon, MenuActionVariant, OverlayEvent, OverlayHost, OverlayScene,
Overlays, POPOVER_EDGE_MARGIN, Placement, TOOLBAR_CHROME_BORDER, TOOLBAR_CHROME_BTN,
TOOLBAR_CHROME_BTN_RADIUS, TOOLBAR_CHROME_GAP, TOOLBAR_CHROME_HEIGHT, TOOLBAR_CHROME_ICON,
TOOLBAR_CHROME_OFFSET, TOOLBAR_CHROME_PX, TOOLBAR_MENU_ICON, TOOLBAR_MENU_MIN_W,
TOOLBAR_MENU_PADDING, TOOLBAR_MENU_ROW_H, TOOLBAR_SEP_SLOT, append_toolbar_groups, chrome_icon,
chrome_link_color, dismiss_submenu_outside, embed_view_kind_for_url, emit, hostname_preview,
icon, menu_horizontal_separator, place_popover, toolbar_chrome_container,
toolbar_dropdown_panel, toolbar_icon_button, toolbar_menu_row,
BlockCopyRow, BlockToolbarSubmenu, ChromeIcon, MenuActionVariant, OverlayEvent, OverlayHost,
OverlayScene, Overlays, POPOVER_EDGE_MARGIN, Placement, TOOLBAR_CHROME_BORDER,
TOOLBAR_CHROME_BTN, TOOLBAR_CHROME_BTN_RADIUS, TOOLBAR_CHROME_GAP, TOOLBAR_CHROME_HEIGHT,
TOOLBAR_CHROME_ICON, TOOLBAR_CHROME_OFFSET, TOOLBAR_CHROME_PX, TOOLBAR_MENU_ICON,
TOOLBAR_MENU_MIN_W, TOOLBAR_MENU_PADDING, TOOLBAR_MENU_ROW_H, TOOLBAR_SEP_SLOT,
append_toolbar_groups, block_copy_rows, chrome_icon, chrome_link_color,
dismiss_submenu_outside, embed_view_kind_for_url, emit, hostname_preview, icon,
menu_horizontal_separator, place_popover, toolbar_chrome_container, toolbar_dropdown_panel,
toolbar_icon_button, toolbar_menu_row,
};
/// Card visual style for `affine:bookmark` (`prop:style`).
@@ -76,8 +78,17 @@ impl BookmarkCardStyle {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BookmarkToolbarAction {
Open,
Copy,
/// Copy the bookmark URL.
CopyLink,
/// Edit the bookmark URL.
Edit,
/// Edit the card title and description.
EditDescription,
/// Copy the bookmark URL from the touch toolbar.
Copy,
CopyBlock,
CopyAsMarkdown,
CopyLinkToBlock,
ConvertToInline,
ConvertToEmbed,
SetStyle(BookmarkCardStyle),
@@ -127,7 +138,9 @@ impl Overlays {
let touch = scene.is_touch || scene.form_factor != crate::block_flow::FormFactor::Desktop;
let vp = scene.popover_viewport();
let max_w = (vp.w - 2.0 * POPOVER_EDGE_MARGIN).max(200.0);
let desktop_raw = if can_embed { 474.0_f32 } else { 426.0_f32 };
let link_group_w = 2.0 * TOOLBAR_CHROME_BTN + TOOLBAR_CHROME_GAP;
let link_group_slot = link_group_w + TOOLBAR_SEP_SLOT + 2.0 * TOOLBAR_CHROME_GAP;
let desktop_raw = link_group_slot + if can_embed { 474.0_f32 } else { 426.0_f32 };
let hover_bg = palette.hover;
if touch || max_w < desktop_raw {
@@ -143,7 +156,8 @@ impl Overlays {
);
}
// Desktop `ToolbarChrome`: [hostname preview] │ Card view ▾ │ Style ▾ │ Caption │ ⋮ More
// Desktop `ToolbarChrome`:
// [hostname preview] │ Copy link, Edit │ Card view ▾ │ Style ▾ │ Caption │ ⋮ More
let block_id_owned = block_id.to_string();
let host = hostname_preview(url);
let btn = TOOLBAR_CHROME_BTN;
@@ -165,8 +179,8 @@ impl Overlays {
&self.block_submenu,
Some(BlockToolbarSubmenu::BookmarkMore(id)) if id == block_id
);
let group_widths = [preview_w, view_w, style_w, btn, btn];
let inner_w = group_widths.iter().sum::<f32>() + 4.0 * sep_w + 8.0 * group_gap;
let group_widths = [preview_w, link_group_w, view_w, style_w, btn, btn];
let inner_w = group_widths.iter().sum::<f32>() + 5.0 * sep_w + 10.0 * group_gap;
let width = (inner_w + 2.0 * (TOOLBAR_CHROME_PX + TOOLBAR_CHROME_BORDER))
.min(max_w)
.round();
@@ -213,6 +227,43 @@ impl Overlays {
.into_any_element();
cursor_x += preview_w + group_gap + sep_w + group_gap;
let mut link_group = Vec::with_capacity(2);
for (id, snap, label, glyph, action) in [
(
"bm-tb-copy-link",
ui::snap_id!("overlay.bookmark_toolbar.copy_link"),
"Copy link",
icon("CopyIcon", TOOLBAR_CHROME_ICON, palette.icon).into_any_element(),
BookmarkToolbarAction::CopyLink,
),
(
"bm-tb-edit",
ui::snap_id!("overlay.bookmark_toolbar.edit"),
"Edit Description",
chrome_icon(ChromeIcon::Edit, TOOLBAR_CHROME_ICON, palette.icon),
BookmarkToolbarAction::EditDescription,
),
] {
link_group.push(toolbar_icon_button(
id,
snap,
"overlay.bookmark_toolbar",
label,
FlowRect::new(cursor_x, btn_y, btn, btn),
false,
true,
glyph,
OverlayEvent::BookmarkToolbarAction {
block_id: block_id_owned.clone(),
action,
},
palette,
cx,
));
cursor_x += btn + group_gap;
}
cursor_x += sep_w + group_gap;
let view_ink = if view_open {
palette.brand
} else {
@@ -349,6 +400,7 @@ impl Overlays {
),
vec![
vec![preview_chip],
link_group,
vec![view_btn],
vec![style_btn],
vec![cap_btn],
@@ -484,8 +536,9 @@ impl Overlays {
}
out.push(dismiss_submenu_outside(panel, rect, cx).into_any_element());
} else if more_open {
let rows = block_copy_rows(scene);
let menu_h = (2.0 * (TOOLBAR_MENU_PADDING + TOOLBAR_CHROME_BORDER)
+ 3.0 * TOOLBAR_MENU_ROW_H
+ (rows.len() + 1) as f32 * TOOLBAR_MENU_ROW_H
+ 9.0)
.round();
let anchor = self.toolbar_bounds.anchor(
@@ -513,15 +566,14 @@ impl Overlays {
"overlay.bookmark_toolbar",
palette,
);
for (suffix, label, icon_name, action) in [
("copy", "Copy", "CopyIcon", BookmarkToolbarAction::Copy),
(
"duplicate",
"Duplicate",
"DuplicateIcon",
BookmarkToolbarAction::Duplicate,
),
] {
for row in rows {
let (suffix, label, icon_name) = row.label();
let action = match row {
BlockCopyRow::Copy => BookmarkToolbarAction::CopyBlock,
BlockCopyRow::CopyAsMarkdown => BookmarkToolbarAction::CopyAsMarkdown,
BlockCopyRow::CopyLinkToBlock => BookmarkToolbarAction::CopyLinkToBlock,
BlockCopyRow::Duplicate => BookmarkToolbarAction::Duplicate,
};
panel = panel.child(toolbar_menu_row(
format!("bm-more-{suffix}"),
ui::snap_id!("overlay.bookmark_toolbar.{suffix}"),
@@ -0,0 +1,517 @@
//! `Edit Description` popover of bookmark, card embed, and linked-doc cards (AFFiNE
//! `toggleEmbedCardEditModal`): a title field, a description field, `Reset` on a linked doc,
//! and `Save`. `Save` writes the trimmed title and description in one undo step and needs a
//! title. `Reset` clears the aliases of a linked doc. `Escape` and an outside press write
//! nothing.
use std::{cell::Cell, rc::Rc};
use ui::{
AnyElement, ClickEvent, Context, FontWeight, MouseDownEvent, SharedString, Window, div,
prelude::*, px,
};
use crate::{
block_flow::FlowRect,
theme::{Palette, TYPOGRAPHY},
};
use super::{
BookmarkPrompt, BookmarkPromptKind, DocEdit, LinkBar, OverlayEffects, OverlayEvent,
OverlayHost, OverlayScene, Overlays, POPOVER_EDGE_MARGIN, Placement, SingleLineInputSpec,
chrome_border_color, chrome_panel_bg, emit, paint_single_line_input_inner_sized, place,
place_popover,
};
use super::input_field::single_line_scroll_x;
const CARD_EDIT_WIDTH: f32 = 421.0;
const CARD_EDIT_PAD: f32 = 12.0;
const CARD_EDIT_FIELD_H: f32 = 28.0;
const CARD_EDIT_DESCRIPTION_H: f32 = 52.0;
const CARD_EDIT_BUTTON_H: f32 = 28.0;
const CARD_EDIT_OFFSET: f32 = 8.0;
/// The field of the card edit popover that takes text input.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CardAliasField {
Title,
Description,
}
/// State of the card edit popover beside its title field ([`BookmarkPrompt::input`]).
#[derive(Clone, Debug, PartialEq)]
pub struct CardAliasEdit {
pub description: LinkBar,
pub focus: CardAliasField,
/// The stored `(title, description)` properties, to skip a save that changes nothing.
pub stored: (Option<String>, Option<String>),
/// A linked doc card: its fields edit aliases of the document and `Reset` clears them.
pub linked_doc: bool,
}
impl BookmarkPrompt {
/// The field that takes text input: the description field of a card edit popover when it
/// has focus, else the prompt input.
pub fn active_input(&self) -> &LinkBar {
match &self.kind {
BookmarkPromptKind::CardAlias(edit) if edit.focus == CardAliasField::Description => {
&edit.description
}
_ => &self.input,
}
}
pub fn active_input_mut(&mut self) -> &mut LinkBar {
match &mut self.kind {
BookmarkPromptKind::CardAlias(edit) if edit.focus == CardAliasField::Description => {
&mut edit.description
}
_ => &mut self.input,
}
}
}
impl Overlays {
/// Open the card edit popover on `block_id` with the shown `title` and `description`.
/// `stored` holds the block's own title and description properties.
pub fn open_card_alias_prompt(
&mut self,
block_id: String,
(title, description): (String, String),
stored: (Option<String>, Option<String>),
linked_doc: bool,
now_ms: f64,
) {
let mut description = LinkBar::new(description);
let end = description.text().encode_utf16().count();
description.input.select(end..end);
let edit = CardAliasEdit {
description,
focus: CardAliasField::Title,
stored,
linked_doc,
};
self.open_single_line_prompt(block_id, BookmarkPromptKind::CardAlias(edit), title, now_ms);
// The title opens selected, as AFFiNE selects the title input.
if let Some(prompt) = self.bookmark_prompt_mut() {
prompt.input.input.select_all();
}
}
/// The open card edit popover, if any.
pub fn card_alias_prompt(&self) -> Option<(&BookmarkPrompt, &CardAliasEdit)> {
let prompt = self.bookmark_prompt()?;
match &prompt.kind {
BookmarkPromptKind::CardAlias(edit) => Some((prompt, edit)),
_ => None,
}
}
fn card_alias_edit_mut(&mut self) -> Option<&mut CardAliasEdit> {
match &mut self.bookmark_prompt_mut()?.kind {
BookmarkPromptKind::CardAlias(edit) => Some(edit),
_ => None,
}
}
/// Focus the clicked field and move its caret to the hit UTF-16 offset.
pub(in crate::overlays) fn click_card_alias_field(
&mut self,
field: CardAliasField,
offset: usize,
) -> bool {
let Some(prompt) = self.bookmark_prompt_mut() else {
return false;
};
let BookmarkPromptKind::CardAlias(edit) = &mut prompt.kind else {
return false;
};
prompt.input.unmark();
edit.description.unmark();
edit.focus = field;
prompt.active_input_mut().input.select(offset..offset);
true
}
/// Move text input to the other field of the card edit popover (`Tab`).
pub(in crate::overlays) fn toggle_card_alias_field(&mut self) -> bool {
let Some(edit) = self.card_alias_edit_mut() else {
return false;
};
edit.focus = match edit.focus {
CardAliasField::Title => CardAliasField::Description,
CardAliasField::Description => CardAliasField::Title,
};
true
}
/// `Save`: write the trimmed title and description. An empty title keeps the popover
/// open and writes nothing. Returns `false` when the popover stays open.
pub(in crate::overlays) fn save_card_alias(
prompt: &BookmarkPrompt,
edit: &CardAliasEdit,
effects: &mut OverlayEffects,
) -> bool {
let title = prompt.input.clone().into_committed_text().trim().to_owned();
if title.is_empty() {
return false;
}
let description = edit
.description
.clone()
.into_committed_text()
.trim()
.to_owned();
let next = (Some(title), Some(description));
if next != edit.stored {
effects.edits.push(DocEdit::SetCardAlias {
block_id: prompt.block_id.clone(),
title: next.0,
description: next.1,
});
}
true
}
/// `Reset`: clear the title and description aliases of a linked doc card.
pub(in crate::overlays) fn reset_card_alias(
&mut self,
now_ms: f64,
effects: &mut OverlayEffects,
) {
let Some((prompt, edit)) = self.card_alias_prompt() else {
return;
};
if !edit.linked_doc || edit.stored == (None, None) {
return;
}
effects.edits.push(DocEdit::SetCardAlias {
block_id: prompt.block_id.clone(),
title: None,
description: None,
});
self.close_bookmark_prompt_at(now_ms);
effects.redraw = true;
}
/// Render the card edit popover above the card (below it when the card is near the top).
pub(in crate::overlays) fn render_card_alias_prompt<V: OverlayHost>(
&mut self,
scene: &OverlayScene<'_>,
palette: &Palette,
now_ms: f64,
window: &mut Window,
cx: &mut Context<V>,
) -> Option<AnyElement> {
let prompt = self.bookmark.as_mut()?;
prompt.rect = None;
let progress = prompt.presence.progress(now_ms);
if prompt.presence.closing && progress <= 0.0 {
return None;
}
let interactive = !prompt.presence.closing;
let progress = if interactive {
progress.max(0.01)
} else {
progress
};
let anchor_world = scene.layout.block(&prompt.block_id).map(|b| b.rect())?;
if !scene.page_viewport().intersects(&anchor_world) {
return None;
}
let viewport = scene.popover_viewport();
let width = CARD_EDIT_WIDTH
.min(viewport.w - 2.0 * POPOVER_EDGE_MARGIN)
.max(200.0)
.floor();
let height = 4.0 * CARD_EDIT_PAD
+ CARD_EDIT_FIELD_H
+ CARD_EDIT_DESCRIPTION_H
+ CARD_EDIT_BUTTON_H
+ 1.0;
let placed = place_popover(
scene.world_to_screen(&anchor_world),
(width, height),
viewport,
Placement::AboveStart,
CARD_EDIT_OFFSET,
POPOVER_EDGE_MARGIN,
);
prompt.rect = Some(placed.rect);
let field_w = width - 2.0 * CARD_EDIT_PAD - 1.0;
let field_x = placed.rect.x + CARD_EDIT_PAD + 0.5;
let title_y = placed.rect.y + CARD_EDIT_PAD + 0.5;
let description_y = title_y + CARD_EDIT_FIELD_H + CARD_EDIT_PAD;
prompt.input.bounds = Some(FlowRect::new(field_x, title_y, field_w, CARD_EDIT_FIELD_H));
let BookmarkPromptKind::CardAlias(edit) = &mut prompt.kind else {
return None;
};
edit.description.bounds = Some(FlowRect::new(
field_x,
description_y,
field_w,
CARD_EDIT_DESCRIPTION_H,
));
let (title_ph, description_ph) = if edit.linked_doc {
(
"Add title alias",
"Add description alias (empty to inherit document content)",
)
} else {
("Write a title", "Write a description...")
};
let can_save = !prompt.input.text().trim().is_empty();
let can_reset = edit.linked_doc && edit.stored != (None, None);
let fields = [
(
CardAliasField::Title,
&prompt.input,
title_ph,
ui::snap_id!("overlay.embed_toolbar.card_edit_prompt.title"),
),
(
CardAliasField::Description,
&edit.description,
description_ph,
ui::snap_id!("overlay.embed_toolbar.card_edit_prompt.description"),
),
]
.map(|(field, bar, placeholder, snap)| {
card_alias_field(
field,
bar,
placeholder,
snap,
field_w,
interactive && edit.focus == field,
interactive,
palette,
window,
cx,
)
});
let mut actions = div()
.flex()
.child(div().flex_1())
.items_center()
.gap(px(8.0));
if edit.linked_doc {
actions = actions.child(card_alias_button(
"card-edit-reset",
ui::snap_id!("overlay.embed_toolbar.card_edit_prompt.reset"),
"Reset",
false,
interactive && can_reset,
OverlayEvent::CardAliasReset,
palette,
cx,
));
}
actions = actions.child(card_alias_button(
"card-edit-save",
ui::snap_id!("overlay.embed_toolbar.card_edit_prompt.save"),
"Save",
true,
interactive && can_save,
OverlayEvent::BookmarkApply,
palette,
cx,
));
let [title, description] = fields;
let mut root = place(placed.rect)
.id("card-edit-prompt")
.flex()
.flex_col()
.gap(px(CARD_EDIT_PAD))
.p(px(CARD_EDIT_PAD))
.rounded(px(4.0))
.bg(chrome_panel_bg(palette))
.border(px(0.5))
.border_color(chrome_border_color(palette))
.shadow(palette.theme.shadows("--affine-overlay-shadow").into())
.opacity(progress)
.snapshot(
"overlay.embed_toolbar.card_edit_prompt",
Some("root.canvas"),
)
.snapshot_focused(interactive)
.child(title)
.child(description)
.child(actions);
if interactive {
root = root
.occlude()
.on_mouse_down(ui::MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_mouse_down_out(emit(cx, |_: &MouseDownEvent| {
OverlayEvent::CloseBookmarkPrompt
}));
}
Some(root.into_any_element())
}
}
#[allow(clippy::too_many_arguments)]
fn card_alias_field<V: OverlayHost>(
field: CardAliasField,
bar: &LinkBar,
placeholder: &'static str,
snap: ui::SnapshotId,
width: f32,
focused: bool,
interactive: bool,
palette: &Palette,
window: &mut Window,
cx: &mut Context<V>,
) -> AnyElement {
let shown: SharedString = bar.text().into();
let field_height = match field {
CardAliasField::Title => CARD_EDIT_FIELD_H,
CardAliasField::Description => CARD_EDIT_DESCRIPTION_H,
};
let inner_height = field_height - 2.0;
let empty = shown.is_empty();
let caret_height = 16.0;
let text_room = (width - 22.0).max(16.0);
let input = paint_single_line_input_inner_sized(
bar,
&shown,
SingleLineInputSpec {
text_room,
inner_height,
caret_height,
caret_top: ((inner_height - caret_height) * 0.5).round(),
placeholder: "",
focused,
},
TYPOGRAPHY.font_sm_px,
palette,
window,
);
let text_origin = Rc::new(Cell::new(px(0.0)));
let mut inner = input.inner;
if interactive {
let text_origin = text_origin.clone();
inner = inner.child(
ui::canvas(
move |bounds, _, _| text_origin.set(bounds.origin.x),
|_, (), _, _| {},
)
.absolute()
.inset_0(),
);
}
let border = if focused {
palette.brand
} else {
palette.border
};
let mut el = div()
.id(match field {
CardAliasField::Title => "card-edit-title",
CardAliasField::Description => "card-edit-description",
})
.relative()
.flex_none()
.w(px(width))
.h(px(field_height))
.px(px(10.0))
.rounded(px(4.0))
.border_1()
.border_color(border)
.flex()
.items_center()
.overflow_hidden()
.text_size(px(TYPOGRAPHY.font_sm_px))
.snapshot(snap, Some("overlay.embed_toolbar.card_edit_prompt"))
.snapshot_focused(focused)
.snapshot_text(shown)
.child(inner)
.when(empty, |field| {
field.child(
div()
.absolute()
.inset_0()
.px(px(11.0))
.flex()
.items_center()
.text_size(px(TYPOGRAPHY.font_xs_px))
.line_height(px(16.0))
.text_color(palette.text_secondary)
.child(div().w_full().child(placeholder)),
)
});
if interactive {
let line = input.line;
let (selection, reversed) = bar.shown_selection();
let caret = if reversed {
selection.start
} else {
selection.end
};
let shown = bar.text();
let caret_byte = crate::inline_input::utf16_to_byte(&shown, caret);
let scroll = single_line_scroll_x(
line.width().into(),
line.x_for_index(caret_byte).into(),
text_room,
);
el = el.cursor(ui::CursorStyle::IBeam).on_mouse_down(
ui::MouseButton::Left,
emit(cx, move |event: &MouseDownEvent| {
let byte =
line.closest_index_for_x(event.position.x - text_origin.get() + px(scroll));
let offset = shown[..byte].encode_utf16().count();
OverlayEvent::CardAliasClick { field, offset }
}),
);
}
el.into_any_element()
}
#[allow(clippy::too_many_arguments)]
fn card_alias_button<V: OverlayHost>(
id: &'static str,
snap: ui::SnapshotId,
label: &'static str,
primary: bool,
enabled: bool,
event: OverlayEvent,
palette: &Palette,
cx: &mut Context<V>,
) -> AnyElement {
let (bg, fg) = if primary {
(palette.brand, palette.on_accent)
} else {
(palette.background, palette.text_primary)
};
let mut el = div()
.id(id)
.flex_none()
.h(px(CARD_EDIT_BUTTON_H))
.px(px(12.0))
.rounded(px(4.0))
.border_1()
.border_color(palette.border)
.bg(bg)
.flex()
.items_center()
.text_size(px(TYPOGRAPHY.font_xs_px))
.font_weight(FontWeight::MEDIUM)
.text_color(fg)
.snapshot(snap, Some("overlay.embed_toolbar.card_edit_prompt"))
.snapshot_text(label)
.child(label);
if enabled {
let hover = bg.opacity(0.88);
el = el
.cursor_pointer()
.hover(move |s| s.bg(hover))
.on_click(emit(cx, move |_: &ClickEvent| event.clone()));
} else if primary {
el = el.opacity(0.5);
} else {
el = el.text_color(palette.text_secondary.opacity(0.6));
}
el.into_any_element()
}
@@ -2,9 +2,13 @@
//! external embed blocks (YouTube / Figma / GitHub / Loom / Web / Iframe / Html), and
//! Page-mode `affine:surface-ref` blocks (`surface_ref`), built on the shared `ToolbarChrome`.
mod card_edit;
mod more_menu;
pub use card_edit::{CardAliasEdit, CardAliasField};
mod surface_ref;
use blocksuite_playground_doc::read::BlockContent;
use blocksuite_playground_doc::read::{BlockContent, ExternalEmbedKind};
use ui::{AnyElement, ClickEvent, Context, FontWeight, MouseButton, div, prelude::*, px};
use crate::{
@@ -28,7 +32,13 @@ pub enum EmbedToolbarAction {
ConvertToEmbed,
SetStyle(BookmarkCardStyle),
Caption,
/// Copy the card's link: the document URL of a linked or synced doc, else the embed URL.
CopyLink,
/// Edit the card title and description.
Edit,
Copy,
CopyAsMarkdown,
CopyLinkToBlock,
/// Copy the `?mode=edgeless` link to the whiteboard element of an `affine:surface-ref`.
CopyOriginalLink,
Duplicate,
@@ -125,6 +135,28 @@ impl Overlays {
),
_ => return Vec::new(),
};
// AFFiNE linkable card actions: `Copy link` and `Edit` on linked docs and on card
// embeds, `Copy link` alone on synced docs, `Copy original link` on an iframe.
let (copy_link_label, has_edit) = match &node.content {
BlockContent::EmbedLinkedDoc { .. } => (Some("Copy link"), true),
BlockContent::EmbedSyncedDoc { .. } => (Some("Copy link"), false),
BlockContent::ExternalEmbed { kind, url, .. } => match kind {
ExternalEmbedKind::Youtube
| ExternalEmbedKind::Figma
| ExternalEmbedKind::Github
| ExternalEmbedKind::Loom => (Some("Copy link"), true),
ExternalEmbedKind::Iframe if !url.is_empty() => (Some("Copy original link"), false),
_ => (None, false),
},
_ => (None, false),
};
let touch = scene.is_touch || scene.form_factor.is_touch_form_factor();
let (copy_link_label, has_edit) = if touch {
(None, false)
} else {
(copy_link_label, has_edit)
};
let link_count = usize::from(copy_link_label.is_some()) + usize::from(has_edit);
let target_mode = node
.props
.get("prop:params")
@@ -135,7 +167,6 @@ impl Overlays {
BookmarkCardStyle::from_wire(node.props.get("prop:style").and_then(|v| v.as_str()));
let block_id_owned = block_id.to_string();
let vp = scene.popover_viewport();
let touch = scene.is_touch || scene.form_factor.is_touch_form_factor();
let btn = if touch { 44.0 } else { TOOLBAR_CHROME_BTN };
let group_gap = if touch || vp.w < 460.0 {
2.0
@@ -201,6 +232,9 @@ impl Overlays {
if preview_w > 0.0 {
add_group(preview_w);
}
if link_count > 0 {
add_group(link_count as f32 * btn + (link_count - 1) as f32 * group_gap);
}
add_group(view_w);
if style_w > 0.0 {
add_group(style_w);
@@ -369,6 +403,49 @@ impl Overlays {
cursor_x += preview_w + group_gap + sep_w + group_gap;
}
if link_count > 0 {
let mut link_group = Vec::with_capacity(link_count);
let copy_link = copy_link_label.map(|label| {
(
"embed-tb-copy-link",
ui::snap_id!("overlay.embed_toolbar.copy_link"),
label,
icon("CopyIcon", TOOLBAR_CHROME_ICON, palette.icon).into_any_element(),
EmbedToolbarAction::CopyLink,
)
});
let edit = has_edit.then(|| {
(
"embed-tb-edit",
ui::snap_id!("overlay.embed_toolbar.edit"),
"Edit Description",
chrome_icon(ChromeIcon::Edit, TOOLBAR_CHROME_ICON, palette.icon),
EmbedToolbarAction::Edit,
)
});
for (id, snap, label, glyph, action) in copy_link.into_iter().chain(edit) {
link_group.push(toolbar_icon_button(
id,
snap,
"overlay.embed_toolbar",
label,
FlowRect::new(cursor_x, btn_y, btn, btn),
false,
true,
glyph,
OverlayEvent::EmbedToolbarAction {
block_id: block_id_owned.clone(),
action,
},
palette,
cx,
));
cursor_x += btn + group_gap;
}
groups.push(link_group);
cursor_x += sep_w + group_gap;
}
let toggle_view_ev = if open_menu_open {
OverlayEvent::EmbedToolbarAction {
block_id: block_id_owned.clone(),
@@ -669,79 +746,7 @@ impl Overlays {
}
out.push(dismiss_submenu_outside(panel, rect, cx).into_any_element());
} else if more_open {
let menu_h = (2.0 * (TOOLBAR_MENU_PADDING + TOOLBAR_CHROME_BORDER)
+ 3.0 * TOOLBAR_MENU_ROW_H
+ 9.0)
.round();
let anchor = self.toolbar_bounds.anchor(
"embed",
"embed-tb-more",
rect,
TOOLBAR_MENU_MIN_W,
scene.direction,
);
let menu_placed = place_popover(
anchor,
(TOOLBAR_MENU_MIN_W, menu_h),
vp,
Placement::BelowStart,
4.0,
POPOVER_EDGE_MARGIN,
);
self.embed_submenu_rect = Some(menu_placed.rect);
let mut panel = toolbar_dropdown_panel(
"embed-more-menu",
menu_placed.rect,
1.0,
true,
ui::snap_id!("overlay.embed_toolbar.more_menu"),
"overlay.embed_toolbar",
palette,
);
for (suffix, label, icon_name, action) in [
("copy", "Copy", "CopyIcon", EmbedToolbarAction::Copy),
(
"duplicate",
"Duplicate",
"DuplicateIcon",
EmbedToolbarAction::Duplicate,
),
] {
panel = panel.child(toolbar_menu_row(
format!("embed-more-{suffix}"),
ui::snap_id!("overlay.embed_toolbar.more.{suffix}"),
"overlay.embed_toolbar.more_menu",
label,
icon(icon_name, TOOLBAR_MENU_ICON, palette.icon).into_any_element(),
false,
MenuActionVariant::Normal,
true,
OverlayEvent::EmbedToolbarAction {
block_id: block_id_owned.clone(),
action,
},
palette,
cx,
));
}
panel = panel.child(menu_horizontal_separator(palette));
panel = panel.child(toolbar_menu_row(
"embed-more-delete",
ui::snap_id!("overlay.embed_toolbar.more.delete"),
"overlay.embed_toolbar.more_menu",
"Delete",
icon("DeleteIcon", TOOLBAR_MENU_ICON, palette.icon).into_any_element(),
false,
MenuActionVariant::Destructive,
true,
OverlayEvent::EmbedToolbarAction {
block_id: block_id_owned,
action: EmbedToolbarAction::Delete,
},
palette,
cx,
));
out.push(dismiss_submenu_outside(panel, rect, cx).into_any_element());
out.push(self.render_embed_more_menu(scene, rect, block_id, palette, cx));
}
out
@@ -0,0 +1,99 @@
//! The `More` menu of `overlay.embed_toolbar`: the block clipboard rows, then `Delete`.
use ui::{AnyElement, Context, prelude::*};
use crate::{block_flow::FlowRect, theme::Palette};
use super::EmbedToolbarAction;
use super::{
BlockCopyRow, MenuActionVariant, OverlayEvent, OverlayHost, OverlayScene, Overlays,
POPOVER_EDGE_MARGIN, Placement, TOOLBAR_CHROME_BORDER, TOOLBAR_MENU_ICON, TOOLBAR_MENU_MIN_W,
TOOLBAR_MENU_PADDING, TOOLBAR_MENU_ROW_H, block_copy_rows, dismiss_submenu_outside, icon,
menu_horizontal_separator, place_popover, toolbar_dropdown_panel, toolbar_menu_row,
};
impl Overlays {
/// Build the `More` dropdown under the toolbar at `rect` for `block_id`.
pub(super) fn render_embed_more_menu<V: OverlayHost>(
&mut self,
scene: &OverlayScene<'_>,
rect: FlowRect,
block_id: &str,
palette: &Palette,
cx: &mut Context<V>,
) -> AnyElement {
let rows = block_copy_rows(scene);
let menu_h = (2.0 * (TOOLBAR_MENU_PADDING + TOOLBAR_CHROME_BORDER)
+ (rows.len() + 1) as f32 * TOOLBAR_MENU_ROW_H
+ 9.0)
.round();
let anchor = self.toolbar_bounds.anchor(
"embed",
"embed-tb-more",
rect,
TOOLBAR_MENU_MIN_W,
scene.direction,
);
let menu_placed = place_popover(
anchor,
(TOOLBAR_MENU_MIN_W, menu_h),
scene.popover_viewport(),
Placement::BelowStart,
4.0,
POPOVER_EDGE_MARGIN,
);
self.embed_submenu_rect = Some(menu_placed.rect);
let mut panel = toolbar_dropdown_panel(
"embed-more-menu",
menu_placed.rect,
1.0,
true,
ui::snap_id!("overlay.embed_toolbar.more_menu"),
"overlay.embed_toolbar",
palette,
);
for row in rows {
let (suffix, label, icon_name) = row.label();
let action = match row {
BlockCopyRow::Copy => EmbedToolbarAction::Copy,
BlockCopyRow::CopyAsMarkdown => EmbedToolbarAction::CopyAsMarkdown,
BlockCopyRow::CopyLinkToBlock => EmbedToolbarAction::CopyLinkToBlock,
BlockCopyRow::Duplicate => EmbedToolbarAction::Duplicate,
};
panel = panel.child(toolbar_menu_row(
format!("embed-more-{suffix}"),
ui::snap_id!("overlay.embed_toolbar.more.{suffix}"),
"overlay.embed_toolbar.more_menu",
label,
icon(icon_name, TOOLBAR_MENU_ICON, palette.icon).into_any_element(),
false,
MenuActionVariant::Normal,
true,
OverlayEvent::EmbedToolbarAction {
block_id: block_id.to_owned(),
action,
},
palette,
cx,
));
}
panel = panel.child(menu_horizontal_separator(palette));
panel = panel.child(toolbar_menu_row(
"embed-more-delete",
ui::snap_id!("overlay.embed_toolbar.more.delete"),
"overlay.embed_toolbar.more_menu",
"Delete",
icon("DeleteIcon", TOOLBAR_MENU_ICON, palette.icon).into_any_element(),
false,
MenuActionVariant::Destructive,
true,
OverlayEvent::EmbedToolbarAction {
block_id: block_id.to_owned(),
action: EmbedToolbarAction::Delete,
},
palette,
cx,
));
dismiss_submenu_outside(panel, rect, cx).into_any_element()
}
}
@@ -17,6 +17,8 @@ pub enum SelectionFormatKind {
Text,
TextBlocks,
Blocks,
/// Text inside one table cell: inline marks, links, and highlight colors only.
TableCellText,
}
/// Copy, duplicate, or delete a block from a toolbar.
@@ -31,6 +33,11 @@ pub enum BlockMenuAction {
/// editor's document session as one undo step.
#[derive(Clone, Debug, PartialEq)]
pub enum DocEdit {
SetCardAlias {
block_id: String,
title: Option<String>,
description: Option<String>,
},
SetProp {
block_id: String,
key: &'static str,
@@ -71,6 +78,8 @@ pub enum DocEdit {
/// 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.
/// Exact link ranges originally selected in a table cell.
expected_prev_links: Option<super::SelectionLinkSpans>,
display_text: Option<String>,
},
/// Convert the current text selection into an inline LaTeX equation and open `EquationEditor`.
@@ -340,6 +349,11 @@ pub enum OverlayEvent {
},
/// Commit the bookmark URL prompt (no-op if empty/invalid or unchanged).
BookmarkApply,
CardAliasClick {
field: super::CardAliasField,
offset: usize,
},
CardAliasReset,
/// Dismiss the bookmark URL prompt without mutating the document.
CloseBookmarkPrompt,
/// Select an `affine:image` block in Page mode.
@@ -2,7 +2,7 @@ use ui::Keystroke;
use crate::block_flow::{CodeScroll, FlowLayout, ScrolledCode};
use super::{LinkBar, LinkEditField, Overlays, SlashMenu};
use super::{BookmarkPrompt, LinkBar, LinkEditField, Overlays, SlashMenu};
/// Text a keystroke types, if it types any. `secondary` is the platform's command
/// modifier.
@@ -108,7 +108,7 @@ impl Overlays {
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.bookmark_prompt().map(BookmarkPrompt::active_input))
.or_else(|| self.code_lang_picker().map(|picker| &picker.input))
.or_else(|| {
let tb = self.open_toolbar()?;
@@ -125,7 +125,9 @@ impl Overlays {
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);
return self
.bookmark_prompt_mut()
.map(BookmarkPrompt::active_input_mut);
}
if self.code_lang_picker().is_some() {
return self.code_lang_picker_mut().map(|picker| &mut picker.input);
@@ -524,6 +526,7 @@ impl Overlays {
self.image_toolbar_rect = None;
self.attachment_toolbar_rect = None;
self.image_submenu_rect = None;
self.attachment_submenu_rect = None;
self.bookmark_toolbar_rect = None;
self.bookmark_submenu_rect = None;
self.embed_toolbar_rect = None;
@@ -10,12 +10,13 @@ use ui::{
use crate::theme::Palette;
use super::{
BlockToolbarSubmenu, ChromeIcon, MenuActionVariant, OverlayEvent, OverlayHost, OverlayScene,
Overlays, POPOVER_BORDER, POPOVER_EDGE_MARGIN, Placement, TOOLBAR_CHROME_BORDER,
BlockCopyRow, BlockToolbarSubmenu, ChromeIcon, MenuActionVariant, OverlayEvent, OverlayHost,
OverlayScene, Overlays, POPOVER_BORDER, POPOVER_EDGE_MARGIN, Placement, TOOLBAR_CHROME_BORDER,
TOOLBAR_CHROME_BTN, TOOLBAR_CHROME_BTN_RADIUS, TOOLBAR_MENU_ICON, TOOLBAR_MENU_MIN_W,
TOOLBAR_MENU_PADDING, TOOLBAR_MENU_ROW_H, TOOLBAR_PADDING, TOOLBAR_RADIUS, ToolbarTooltip,
align_glyph, chrome_icon, chrome_panel_bg, dismiss_submenu_outside, emit, icon,
menu_horizontal_separator, place, place_popover, toolbar_dropdown_panel, toolbar_menu_row,
align_glyph, block_copy_rows, chrome_icon, chrome_panel_bg, dismiss_submenu_outside, emit,
icon, menu_horizontal_separator, place, place_popover, toolbar_dropdown_panel,
toolbar_menu_row,
};
/// Horizontal side of an `affine:image` corner resize handle (`nw`/`sw` = `Left`, `ne`/`se` = `Right`).
@@ -32,6 +33,8 @@ pub enum ImageToolbarAction {
Caption,
Align(BlockAlign),
Copy,
CopyAsMarkdown,
CopyLinkToBlock,
Duplicate,
TurnIntoCardView,
Delete,
@@ -500,7 +503,8 @@ impl Overlays {
let mut out = vec![row.into_any_element()];
if more_open {
let row_count = if has_blob { 4 } else { 3 };
let rows = block_copy_rows(scene);
let row_count = rows.len() + 1 + usize::from(has_blob);
let sep_count = if has_blob { 2 } else { 1 };
let menu_h = (2.0 * (TOOLBAR_MENU_PADDING + TOOLBAR_CHROME_BORDER)
+ row_count as f32 * TOOLBAR_MENU_ROW_H
@@ -531,15 +535,14 @@ impl Overlays {
"overlay.image_toolbar",
palette,
);
for (suffix, label, icon_name, action) in [
("copy", "Copy", "CopyIcon", ImageToolbarAction::Copy),
(
"duplicate",
"Duplicate",
"DuplicateIcon",
ImageToolbarAction::Duplicate,
),
] {
for row in rows {
let (suffix, label, icon_name) = row.label();
let action = match row {
BlockCopyRow::Copy => ImageToolbarAction::Copy,
BlockCopyRow::CopyAsMarkdown => ImageToolbarAction::CopyAsMarkdown,
BlockCopyRow::CopyLinkToBlock => ImageToolbarAction::CopyLinkToBlock,
BlockCopyRow::Duplicate => ImageToolbarAction::Duplicate,
};
panel = panel.child(toolbar_menu_row(
format!("img-more-{suffix}"),
ui::snap_id!("overlay.image_toolbar.{suffix}"),
+40 -2
View File
@@ -71,7 +71,7 @@ pub use drag::{
resolve_marquee_selection, resolve_tree_drop_target,
};
use drag::{BlockDrag, DropIndicatorMotion, PageMarquee};
pub use embed_toolbar::EmbedToolbarAction;
pub use embed_toolbar::{CardAliasEdit, CardAliasField, EmbedToolbarAction};
pub use embed_url::{card_embed_kind_for_url, embed_view_kind_for_url};
pub use equation::{EquationEditor, EquationTarget};
use helpers::place_touch_docked_toolbar;
@@ -130,7 +130,8 @@ pub use table_cell::{
};
pub use toolbar::{
ActiveSelection, FormatAction, FormatMoreAction, LinkBar, LinkEditField, MarkState,
SelectionFormat, ToolbarSubmenu, marks_in_range, normalize_url,
SelectionFormat, SelectionLinkSpans, ToolbarSubmenu, link_spans_in_range, marks_in_range,
normalize_url,
};
pub use toolbar_chrome::*;
pub use transform::OverlayScreenTransform;
@@ -483,6 +484,7 @@ pub struct Overlays {
pub(super) image_toolbar_rect: Option<FlowRect>,
pub(super) attachment_toolbar_rect: Option<FlowRect>,
pub(super) image_submenu_rect: Option<FlowRect>,
pub(super) attachment_submenu_rect: Option<FlowRect>,
pub(super) bookmark_toolbar_rect: Option<FlowRect>,
pub(super) bookmark_submenu_rect: Option<FlowRect>,
pub(super) embed_toolbar_rect: Option<FlowRect>,
@@ -541,6 +543,7 @@ impl Overlays {
self.image_toolbar_rect,
self.attachment_toolbar_rect,
self.image_submenu_rect,
self.attachment_submenu_rect,
self.bookmark_toolbar_rect,
self.bookmark_submenu_rect,
self.embed_toolbar_rect,
@@ -607,6 +610,41 @@ impl Overlays {
}
}
/// A row of the clipboard group in a block toolbar `More` menu.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum BlockCopyRow {
Copy,
CopyAsMarkdown,
CopyLinkToBlock,
Duplicate,
}
impl BlockCopyRow {
/// The snapshot suffix, the label, and the icon of the row.
pub(crate) fn label(self) -> (&'static str, &'static str, &'static str) {
match self {
Self::Copy => ("copy", "Copy", "CopyIcon"),
Self::CopyAsMarkdown => ("copy_markdown", "Copy as Markdown", "CopyIcon"),
Self::CopyLinkToBlock => ("copy_link_to_block", "Copy link to block", "LinkIcon"),
Self::Duplicate => ("duplicate", "Duplicate", "DuplicateIcon"),
}
}
}
/// The clipboard rows of a block toolbar `More` menu, in the AFFiNE order. A block link
/// opens a Page block, so a block inside an Edgeless note offers none.
pub(crate) fn block_copy_rows(scene: &OverlayScene<'_>) -> Vec<BlockCopyRow> {
let mut rows = vec![BlockCopyRow::Copy];
if !scene.is_touch && !scene.form_factor.is_touch_form_factor() {
rows.push(BlockCopyRow::CopyAsMarkdown);
if scene.screen_transform.is_none() {
rows.push(BlockCopyRow::CopyLinkToBlock);
}
}
rows.push(BlockCopyRow::Duplicate);
rows
}
#[cfg(test)]
mod pane_dismissal_tests {
use super::*;
@@ -74,10 +74,20 @@ impl Overlays {
let active_submenu = if link_only { None } else { toolbar.submenu };
let wide = viewport.w >= 460.0;
let text_actions = toolbar.selection.kind != SelectionFormatKind::Blocks;
let whole_blocks = toolbar.selection.kind != SelectionFormatKind::Text;
let show_more = !scene.suppress_floating_format_buttons && (wide || whole_blocks);
let show_convert = wide || !text_actions;
let compact_blocks = !wide && whole_blocks && text_actions;
let whole_blocks = matches!(
toolbar.selection.kind,
SelectionFormatKind::TextBlocks | SelectionFormatKind::Blocks
);
// A table cell selection offers the inline marks, the link, and highlight only.
let cell_text = toolbar.selection.kind == SelectionFormatKind::TableCellText;
// Only a single-block text selection carries its selected text.
let multi_block_text = toolbar.selection.kind == SelectionFormatKind::Text
&& toolbar.selection.selected_text.is_none();
let block_actions = whole_blocks || multi_block_text;
let show_more =
!scene.suppress_floating_format_buttons && !cell_text && (wide || block_actions);
let show_convert = !cell_text && (wide || !text_actions);
let compact_blocks = !wide && block_actions && text_actions;
// Compute exact content width for grouped ToolbarChrome layout.
let btn = TOOLBAR_CHROME_BTN;
@@ -103,7 +113,7 @@ impl Overlays {
let chrome_px = if wide { TOOLBAR_CHROME_PX } else { 4.0_f32 };
let sep_w = TOOLBAR_SEP_SLOT;
let inline_count = if wide { 7usize } else { 6usize };
let inline_count = if wide && !cell_text { 7usize } else { 6usize };
let mut group_count = 0usize;
let mut items_total = 0.0_f32;
let mut add_group = |w: f32| {
@@ -111,8 +121,10 @@ impl Overlays {
items_total += w;
};
if text_actions {
add_group(menu_btn_w);
add_group(menu_btn_w);
if !cell_text {
add_group(menu_btn_w);
add_group(menu_btn_w);
}
add_group(inline_count as f32 * btn + (inline_count - 1) as f32 * inner_gap);
add_group(menu_btn_w);
}
@@ -280,40 +292,44 @@ impl Overlays {
let mut groups = Vec::new();
if text_actions {
let turn_active = active_submenu == Some(ToolbarSubmenu::TurnInto);
let turn_ink = if turn_active {
palette.brand
} else {
palette.icon
};
let turn_icon_name = current_turn_into_id
.and_then(slash_item_by_id)
.map_or("TextIcon", |item| item.icon);
let g_turn = vec![make_menu_btn(
FormatAction::TurnInto,
turn_active,
cursor_x,
icon(turn_icon_name, TOOLBAR_CHROME_ICON, turn_ink).into_any_element(),
cx,
)];
cursor_x += menu_btn_w + group_gap + sep_w + group_gap;
if !cell_text {
let turn_active = active_submenu == Some(ToolbarSubmenu::TurnInto);
let turn_ink = if turn_active {
palette.brand
} else {
palette.icon
};
let turn_icon_name = current_turn_into_id
.and_then(slash_item_by_id)
.map_or("TextIcon", |item| item.icon);
let g_turn = vec![make_menu_btn(
FormatAction::TurnInto,
turn_active,
cursor_x,
icon(turn_icon_name, TOOLBAR_CHROME_ICON, turn_ink).into_any_element(),
cx,
)];
cursor_x += menu_btn_w + group_gap + sep_w + group_gap;
let align_active = active_submenu == Some(ToolbarSubmenu::Align);
let align_ink = if align_active {
palette.brand
} else {
palette.icon
};
let g_align = vec![make_menu_btn(
FormatAction::Align,
align_active,
cursor_x,
align_glyph(align.unwrap_or(BlockAlign::Left), align_ink).into_any_element(),
cx,
)];
cursor_x += menu_btn_w + group_gap + sep_w + group_gap;
let align_active = active_submenu == Some(ToolbarSubmenu::Align);
let align_ink = if align_active {
palette.brand
} else {
palette.icon
};
let g_align = vec![make_menu_btn(
FormatAction::Align,
align_active,
cursor_x,
align_glyph(align.unwrap_or(BlockAlign::Left), align_ink)
.into_any_element(),
cx,
)];
cursor_x += menu_btn_w + group_gap + sep_w + group_gap;
groups.extend([g_turn, g_align]);
}
let inline_actions: &[FormatAction] = if wide {
let inline_actions: &[FormatAction] = if wide && !cell_text {
&[
FormatAction::Bold,
FormatAction::Italic,
@@ -397,12 +413,7 @@ impl Overlays {
)];
cursor_x += menu_btn_w + group_gap + sep_w + group_gap;
groups.extend([
g_turn,
g_align,
vec![inline_row.into_any_element()],
g_highlight,
]);
groups.extend([vec![inline_row.into_any_element()], g_highlight]);
}
if show_convert {
@@ -577,7 +588,7 @@ impl Overlays {
),
viewport,
scene.screen_transform.is_none(),
(!show_convert && whole_blocks).then_some(&toolbar.selection),
(!show_convert && block_actions).then_some(&toolbar.selection),
&mut self.format_more_menu_scroll,
progress,
interactive,
@@ -447,6 +447,10 @@ impl Overlays {
}
}
OverlayEvent::BookmarkApply => self.apply_bookmark(now_ms, &mut effects),
OverlayEvent::CardAliasClick { field, offset } => {
effects.redraw = self.click_card_alias_field(field, offset);
}
OverlayEvent::CardAliasReset => self.reset_card_alias(now_ms, &mut effects),
OverlayEvent::CloseBookmarkPrompt => {
if self.close_bookmark_prompt_at(now_ms) {
effects.redraw = true;
@@ -629,6 +633,7 @@ impl Overlays {
effects.handled = true;
effects.redraw = true;
match key {
"tab" if self.toggle_card_alias_field() => {}
"enter" => match field_kind {
ActiveFieldKind::Equation => {
if shift {
@@ -1,3 +1,7 @@
mod selection;
pub use selection::{SelectionFormat, SelectionLinkSpans, link_spans_in_range};
use std::ops::Range;
use blocksuite_playground_doc::read::{RichText, TextAlign as BlockAlign};
@@ -309,24 +313,6 @@ impl ActiveSelection {
}
}
/// What the formatting toolbar reads from the editor's selection for one frame.
#[derive(Clone, Debug, PartialEq)]
pub struct SelectionFormat {
pub kind: SelectionFormatKind,
/// World-space box around the selected text.
pub anchor_world: FlowRect,
/// Marks every selected unit carries.
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<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 the selected paragraph and list blocks can become database rows.
pub can_create_table: bool,
}
pub(super) use crate::inline_input::{Utf16ImeBuffer, utf16_to_byte};
/// URL / single-line field attached to the formatting toolbar or equation editor.
@@ -441,6 +427,8 @@ pub(super) struct FormatToolbar {
/// 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>,
/// The table cell's link spans when the field opened.
link_expected_prev_spans: Option<SelectionLinkSpans>,
/// Block ID when `link` was opened explicitly on a non-toolbar block (e.g. `prop:title`).
pub(super) standalone_link_block_id: Option<String>,
pub(super) submenu: Option<ToolbarSubmenu>,
@@ -523,6 +511,7 @@ impl Overlays {
toolbar.link_initial_text = None;
toolbar.active_link_field = LinkEditField::Url;
toolbar.link_expected_prev_url = None;
toolbar.link_expected_prev_spans = None;
toolbar.standalone_link_block_id = None;
toolbar.submenu = None;
toolbar.submenu_rect = None;
@@ -589,6 +578,7 @@ impl Overlays {
toolbar.link_initial_text = init_text;
toolbar.active_link_field = LinkEditField::Url;
toolbar.link_expected_prev_url = expected_prev;
toolbar.link_expected_prev_spans = selection.link_spans.clone();
toolbar.standalone_link_block_id = None;
}
}
@@ -600,6 +590,7 @@ impl Overlays {
link_initial_text: init_text,
active_link_field: LinkEditField::Url,
link_expected_prev_url: expected_prev,
link_expected_prev_spans: selection.link_spans.clone(),
standalone_link_block_id: None,
submenu: None,
presence: Presence::opening(now_ms),
@@ -641,6 +632,7 @@ impl Overlays {
link_initial_text: None,
active_link_field: LinkEditField::Url,
link_expected_prev_url: None,
link_expected_prev_spans: None,
standalone_link_block_id: None,
submenu: None,
presence: Presence::opening(now_ms),
@@ -654,6 +646,7 @@ impl Overlays {
toolbar.link_initial_text = None;
toolbar.active_link_field = LinkEditField::Url;
toolbar.link_expected_prev_url = None;
toolbar.link_expected_prev_spans = None;
toolbar.standalone_link_block_id = None;
toolbar.submenu = None;
toolbar.submenu_rect = None;
@@ -677,6 +670,7 @@ impl Overlays {
toolbar.link_text = None;
toolbar.link_initial_text = None;
toolbar.link_expected_prev_url = None;
toolbar.link_expected_prev_spans = None;
toolbar.standalone_link_block_id = None;
let target = match action {
FormatAction::TurnInto => ToolbarSubmenu::TurnInto,
@@ -714,6 +708,7 @@ impl Overlays {
toolbar.link_initial_text = None;
toolbar.active_link_field = LinkEditField::Url;
toolbar.link_expected_prev_url = None;
toolbar.link_expected_prev_spans = None;
}
None => {
let init_url = toolbar.selection.marks.link.clone().unwrap_or_default();
@@ -724,6 +719,7 @@ impl Overlays {
.map(|s| s.to_string());
toolbar.link_expected_prev_url =
(!init_url.is_empty()).then(|| init_url.clone());
toolbar.link_expected_prev_spans = toolbar.selection.link_spans.clone();
toolbar.link = Some(LinkBar::new(init_url));
toolbar.link_text = init_text.clone().map(LinkBar::new);
toolbar.link_initial_text = init_text;
@@ -764,6 +760,7 @@ impl Overlays {
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 expected_prev_links = toolbar.link_expected_prev_spans.take();
let standalone = toolbar.standalone_link_block_id.take().is_some();
effects.redraw = true;
let url = normalize_url(&link.into_committed_text());
@@ -779,7 +776,8 @@ impl Overlays {
effects.edits.push(DocEdit::Link {
url: None,
expected_prev_url,
expected_prev_text: None,
expected_prev_text: initial_text.filter(|_| expected_prev_links.is_some()),
expected_prev_links,
display_text: None,
});
} else if !url.is_empty() {
@@ -787,6 +785,7 @@ impl Overlays {
url: Some(url),
expected_prev_url,
expected_prev_text: initial_text,
expected_prev_links,
display_text,
});
}
@@ -0,0 +1,62 @@
use blocksuite_playground_doc::read::RichText;
use y_octo::{Any, TextDeltaOp, TextInsert};
use super::{BlockAlign, FlowRect, MarkState, SelectionFormatKind};
/// Linked UTF-16 ranges within a selection, in document order.
pub type SelectionLinkSpans = Vec<(usize, usize, String)>;
/// Return the actual linked ranges, merging adjacent runs with the same URL.
pub fn link_spans_in_range(text: &RichText, start: usize, end: usize) -> SelectionLinkSpans {
let mut spans = SelectionLinkSpans::new();
let mut from = 0;
for op in &text.delta {
let TextDeltaOp::Insert { insert, format } = op else {
continue;
};
let to = from
+ match insert {
TextInsert::Text(value) => value.encode_utf16().count(),
TextInsert::Embed(items) => items.len(),
};
let a = from.max(start);
let b = to.min(end);
if a < b
&& let Some(Any::String(url)) = format.as_ref().and_then(|attrs| attrs.get("link"))
{
if let Some((_, previous_end, previous_url)) = spans.last_mut()
&& *previous_end == a
&& previous_url == url
{
*previous_end = b;
} else {
spans.push((a, b, url.clone()));
}
}
if to >= end {
break;
}
from = to;
}
spans
}
/// What the formatting toolbar reads from the editor's selection for one frame.
#[derive(Clone, Debug, PartialEq)]
pub struct SelectionFormat {
pub kind: SelectionFormatKind,
/// World-space box around the selected text.
pub anchor_world: FlowRect,
/// Marks every selected unit carries.
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<ui::SharedString>,
/// Exact link spans when editing a table cell. An empty list means the range has no link.
pub link_spans: Option<SelectionLinkSpans>,
/// Slash item id of the primary selected block (for `Turn into ▾` icon and selected row).
pub current_turn_into_id: Option<&'static str>,
/// Whether the selected paragraph and list blocks can become database rows.
pub can_create_table: bool,
}
@@ -159,6 +159,7 @@ pub struct ToolbarTooltip {
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum BlockToolbarSubmenu {
ImageMore(String),
AttachmentMore(String),
BookmarkView(String),
BookmarkStyle(String),
BookmarkMore(String),
@@ -488,6 +489,7 @@ impl Overlays {
scene.selected_image_block == Some(id.as_str())
|| self.image_hover.active_target() == Some(id)
}
Some(S::AttachmentMore(id)) => scene.selected_attachment_block == Some(id.as_str()),
Some(S::BookmarkView(id) | S::BookmarkStyle(id) | S::BookmarkMore(id)) => {
scene.selected_bookmark_block == Some(id.as_str())
}
@@ -760,6 +760,7 @@ impl PlaygroundView {
.then(|| {
self.selection_format(layout)
.or_else(|| self.standalone_link_selection_format(layout))
.or_else(|| self.table_cell_selection_format(layout))
})
.flatten();
if !self.page_readonly {
@@ -195,7 +195,13 @@ impl PlaygroundView {
BookmarkToolbarAction::Open => {
self.open_editor_url(url, cx);
}
BookmarkToolbarAction::Copy => {
BookmarkToolbarAction::CopyAsMarkdown => self.copy_media_block_markdown(block_id, cx),
BookmarkToolbarAction::CopyLinkToBlock => self.copy_media_block_link(block_id, cx),
BookmarkToolbarAction::CopyBlock => {
self.overlays.close_block_submenu();
let _ = self.execute_block_menu_action(block_id, BlockMenuAction::Copy, window, cx);
}
BookmarkToolbarAction::CopyLink | BookmarkToolbarAction::Copy => {
if !url.is_empty() {
cx.write_to_clipboard(ClipboardItem::new_string(url));
self.show_timed_context_toast("Link copied", cx);
@@ -205,10 +211,11 @@ impl PlaygroundView {
BookmarkToolbarAction::Edit => {
if !self.page_readonly {
self.overlays
.open_bookmark_edit_prompt(block_id.to_string(), url, now_ms);
.open_bookmark_edit_prompt(block_id.to_owned(), url, now_ms);
cx.notify();
}
}
BookmarkToolbarAction::EditDescription => self.open_media_card_alias(block_id, cx),
BookmarkToolbarAction::Caption => {
if !self.page_readonly {
self.dispatch_overlay_event(
@@ -50,7 +50,6 @@ impl PlaygroundView {
pub(crate) fn selection_snapshot(&self) -> Option<SelectionSnapshot> {
self.editor.selection.as_ref()?.snapshot(self.page()?).ok()
}
/// Carry out one overlay edit as a single undo step and publish it.
pub(super) fn run_overlay_edit(
&mut self,
@@ -63,8 +62,16 @@ impl PlaygroundView {
{
return Ok(());
}
if self.table_cell_overlay_edit(&edit, window, cx) {
return Ok(());
}
let now = self.now_ms(cx) as u64;
match edit {
DocEdit::SetCardAlias {
block_id,
title,
description,
} => self.set_media_card_alias(&block_id, title, description, window, cx),
DocEdit::Mark(key) => self.format_mark(key, window, cx),
DocEdit::TurnInto(command)
if matches!(command, SlashCommand::Equation | SlashCommand::Callout) =>
@@ -97,6 +104,7 @@ impl PlaygroundView {
expected_prev_url,
expected_prev_text,
display_text,
..
} => self.apply_link_with_display_text(
url,
expected_prev_url,
@@ -318,7 +326,6 @@ impl PlaygroundView {
}
}
}
/// Align the selected paragraph and list blocks, or set or clear the link of the
/// selected text, in one undo step.
pub(super) fn format_selection(
@@ -425,7 +432,6 @@ impl PlaygroundView {
self.did_edit(commit, None, window, cx);
Ok(())
}
/// Run a slash menu command on a block in one undo step, the way BlockSuite's menu
/// does.
///
@@ -593,7 +599,6 @@ impl PlaygroundView {
self.did_edit(commit, None, window, cx);
Ok(())
}
/// Creates a new empty document and inserts a standard BlockSuite `LinkedPage` inline
/// reference chip at `offset`, deleting only the typed `/query` (`strip`) and keeping
/// surrounding text intact, in a single undoable step.
@@ -622,7 +627,6 @@ impl PlaygroundView {
cx,
)
}
/// Replaces any typed `/query` with `@` at `offset` in a single undoable step and opens
/// the `@` linked-document picker at the caret.
pub(super) fn run_linked_doc_slash_command(
@@ -668,6 +668,10 @@ impl PlaygroundView {
cx,
);
}
ImageToolbarAction::CopyAsMarkdown => {
self.copy_media_block_markdown(block_id, cx)
}
ImageToolbarAction::CopyLinkToBlock => self.copy_media_block_link(block_id, cx),
ImageToolbarAction::Copy => {
let _ = self.execute_block_menu_action(
block_id,
@@ -213,6 +213,124 @@ impl PlaygroundView {
}
}
pub(in crate::overlays) fn copy_media_block_markdown(
&mut self,
block_id: &str,
cx: &mut Context<Self>,
) {
self.overlays.close_block_submenu();
let slice = self.slice_for_block_ids(&[block_id.to_owned()]);
self.copy_markdown(slice, cx);
cx.notify();
}
pub(in crate::overlays) fn copy_media_block_link(
&mut self,
block_id: &str,
cx: &mut Context<Self>,
) {
self.overlays.close_block_submenu();
self.copy_page_block_link(&[block_id.to_owned()], cx);
cx.notify();
}
pub(super) fn open_media_card_alias(&mut self, block_id: &str, cx: &mut Context<Self>) {
if self.page_readonly
|| (self.mode == crate::PlaygroundMode::Edgeless && self.edgeless_readonly)
{
return;
}
let Some(node) = self.page_snapshot().and_then(|page| page.block(block_id)) else {
return;
};
let stored_value = |key| {
node.props
.get(key)
.and_then(serde_json::Value::as_str)
.map(str::to_owned)
};
let stored = (stored_value("prop:title"), stored_value("prop:description"));
let linked_doc = if let BlockContent::EmbedLinkedDoc { page_id, .. } = &node.content {
Some(page_id.as_str())
} else {
None
};
let preview = linked_doc.and_then(|id| {
self.doc_directory()
.doc_preview(&crate::directory::EditorDocId::from(id))
});
let title = stored
.0
.clone()
.filter(|s| !s.is_empty())
.or_else(|| preview.as_ref().map(|preview| preview.title.clone()))
.unwrap_or_default();
let description = stored
.1
.clone()
.filter(|s| !s.is_empty())
.or_else(|| preview.map(|preview| preview.snippet))
.unwrap_or_default();
let is_linked_doc = linked_doc.is_some();
let now = self.now_ms(cx);
self.overlays.close_block_submenu();
self.overlays.open_card_alias_prompt(
block_id.to_owned(),
(title, description),
stored,
is_linked_doc,
now,
);
cx.notify();
}
pub(super) fn set_media_card_alias(
&mut self,
block_id: &str,
title: Option<String>,
description: Option<String>,
window: &mut Window,
cx: &mut Context<Self>,
) -> blocksuite_playground_doc::DocResult {
if !self
.page_snapshot()
.and_then(|page| page.block(block_id))
.is_some_and(|block| {
matches!(
block.content,
BlockContent::Bookmark { .. }
| BlockContent::EmbedLinkedDoc { .. }
| BlockContent::ExternalEmbed { .. }
)
})
{
return Ok(());
}
let before = self.selection_snapshot();
let now = self.now_ms(cx) as u64;
let page = self.page_mut()?;
let commit = page.structural_edit(now, |page| {
for (key, value) in [("prop:title", title), ("prop:description", description)] {
page.set_block_prop(
block_id,
key,
SessionValue::Any(value.map_or(Any::Null, Any::String)),
now,
)?;
}
Ok(())
})?;
if commit.is_some()
&& let Some(before) = before
{
page.set_undo_selection_snapshot(before)?;
}
self.editor.last_typing = None;
self.did_edit(commit, None, window, cx);
self.editor.reveal = false;
Ok(())
}
pub(super) fn run_embed_toolbar_action(
&mut self,
block_id: &str,
@@ -243,6 +361,36 @@ impl PlaygroundView {
}
match action {
EmbedToolbarAction::CopyOriginalLink => {}
EmbedToolbarAction::Edit => self.open_media_card_alias(block_id, cx),
EmbedToolbarAction::CopyAsMarkdown => self.copy_media_block_markdown(block_id, cx),
EmbedToolbarAction::CopyLinkToBlock => self.copy_media_block_link(block_id, cx),
EmbedToolbarAction::CopyLink => {
let url = match &node.content {
BlockContent::EmbedLinkedDoc { page_id, .. }
| BlockContent::EmbedSyncedDoc { page_id, .. } => {
let params = node.props.get("prop:params");
let request = super::open_doc_request_from_json_params(
page_id.clone(),
ReferenceOpenMode::ActiveView,
params,
);
Some(self.workspace_link_url(
page_id,
params.and_then(|v| v.get("mode")).and_then(|v| v.as_str()),
&request.block_ids,
&request.element_ids,
))
}
BlockContent::ExternalEmbed { url, .. } => {
(!url.is_empty()).then(|| url.clone())
}
_ => None,
};
if let Some(url) = url {
cx.write_to_clipboard(ui::ClipboardItem::new_string(url));
self.show_timed_context_toast("Copied link to clipboard", cx);
}
}
EmbedToolbarAction::ToggleOpenMenu => {
self.overlays.toggle_embed_open_menu(block_id);
cx.notify();
@@ -710,4 +858,323 @@ mod tests {
assert!(view.page_snapshot().unwrap().block("sr").is_none());
});
}
#[test]
fn linked_card_copy_and_alias_edit_update_the_cached_frame() {
use crate::directory::{EditorDocId, EditorDocPreview, InMemoryDocDirectory};
use ui::EntityInputHandler;
let session = surface_ref_page(900, 620, FormFactor::Desktop);
session.view(|view, cx| {
view.edit_document(cx, |state| {
state
.workspace
.page_mut(HOME_PAGE_ID)
.unwrap()
.add_block(
"linked",
BlockSpec::EmbedLinkedDoc {
page_id: "guide".into(),
style: "horizontal".into(),
caption: String::new(),
},
Some("note"),
None,
20,
)
.unwrap();
});
let mut directory = InMemoryDocDirectory::with_namespace("card-test");
directory.upsert_preview(
EditorDocId::from("guide"),
EditorDocPreview {
title: "Original title".into(),
snippet: "Original description".into(),
updated_at_ms: 0,
revision: 1,
},
);
view.set_doc_directory(Box::new(directory));
view.set_block_link_origin(Some("https://example.com"));
});
let select = || session.overlay(OverlayEvent::SelectBlock("linked".into()));
let click = |suffix: &str| {
session.click(
&session.settle(),
&format!("overlay.embed_toolbar.{suffix}"),
)
};
let clipboard = || session.view(|_, cx| cx.read_from_clipboard().unwrap().text().unwrap());
let body = || {
session.frame();
session.view(|view, _| {
view.flow_layout()
.unwrap()
.block("linked")
.unwrap()
.body
.clone()
})
};
let title = || body().plain.clone();
let change = |range, value: &str| {
session.app.update(|cx| {
session
.window
.update(cx, |v, w, cx| {
v.replace_text_in_range(range, value, w, cx);
})
.unwrap()
})
};
select();
assert_eq!(title(), "Original title");
click("copy_link");
assert!(clipboard().contains("/guide"));
let expected = session.view(|view, _| view.page_block_url(HOME_PAGE_ID, &["linked"]));
for row in ["copy_markdown", "copy_link_to_block"] {
click("more");
click(&format!("more.{row}"));
let copied = clipboard();
if row == "copy_markdown" {
assert!(
copied.starts_with('[') && copied.contains("](") && copied.ends_with("/guide)")
);
} else {
assert_eq!(copied, expected);
}
}
let original = body();
click("edit");
session.key("tab");
change(Some(0..20), "Description only");
click("card_edit_prompt.save");
assert!(!std::rc::Rc::ptr_eq(&original, &body()));
assert_eq!(title(), "Original title");
session.undo();
select();
click("edit");
change(None, "");
let before = session.written();
session.overlay(OverlayEvent::BookmarkApply);
assert_eq!(session.written(), before);
assert_eq!(title(), "Original title");
change(None, "Renamed");
session.key("tab");
change(Some(0..20), "Updated description");
click("card_edit_prompt.save");
assert_eq!(title(), "Renamed");
click("more");
click("more.copy_markdown");
assert!(clipboard().starts_with("[Renamed]("));
session.view(|view, _| {
assert_eq!(
view.page_snapshot().unwrap().block("linked").unwrap().props["prop:description"],
"Updated description"
);
});
session.undo();
assert_eq!(title(), "Original title");
select();
click("edit");
change(None, "Renamed");
click("card_edit_prompt.save");
assert_eq!(title(), "Renamed");
select();
click("edit");
click("card_edit_prompt.reset");
assert_eq!(title(), "Original title");
session.view(|view, _| {
assert!(
view.page_snapshot().unwrap().block("linked").unwrap().props["prop:description"]
.is_null()
);
});
session.undo();
assert_eq!(title(), "Renamed");
}
#[test]
fn media_more_copies_markdown_for_each_card_type() {
use blocksuite_playground_doc::read::ExternalEmbedKind;
use ui::ClipboardItem;
const URL: &str = "https://example.com/source";
let cases = [
(
BlockSpec::Bookmark {
url: URL.into(),
title: Some("Guide".into()),
description: None,
},
"bookmark_toolbar",
"copy_markdown",
format!("[Guide]({URL})"),
),
(
BlockSpec::ExternalEmbed {
kind: ExternalEmbedKind::Youtube,
url: URL.into(),
title: Some("Video".into()),
description: None,
html: None,
caption: String::new(),
},
"embed_toolbar",
"more.copy_markdown",
format!("[Video]({URL})"),
),
(
BlockSpec::EmbedLinkedDoc {
page_id: "guide".into(),
style: "horizontal".into(),
caption: String::new(),
},
"embed_toolbar",
"more.copy_markdown",
String::new(),
),
(
BlockSpec::EmbedSyncedDoc {
page_id: "guide".into(),
caption: String::new(),
},
"embed_toolbar",
"more.copy_markdown",
String::new(),
),
(
BlockSpec::Image {
source_id: "cover".into(),
caption: "Cover".into(),
width: 180.0,
height: 100.0,
xywh: None,
},
"image_toolbar",
"copy_markdown",
"![Cover](assets/cover)".into(),
),
(
BlockSpec::Attachment {
name: "Guide.pdf".into(),
size: 128,
mime_type: "application/pdf".into(),
source_id: "guide-file".into(),
caption: String::new(),
embed: false,
},
"attachment_toolbar",
"more.copy_markdown",
"[Guide.pdf](assets/guide-file)".into(),
),
];
for (spec, toolbar, row, expected) in cases {
let session = surface_ref_page(900, 680, FormFactor::Desktop);
session.view(|view, cx| {
view.edit_document(cx, |state| {
state
.workspace
.page_mut(HOME_PAGE_ID)
.unwrap()
.add_block("media", spec, Some("note"), Some(0), 20)
.unwrap();
});
cx.write_to_clipboard(ClipboardItem::new_string("PREVIOUS TEXT".into()));
});
session.overlay(OverlayEvent::SelectBlock("media".into()));
session.click(&session.settle(), &format!("overlay.{toolbar}.more"));
session.click(&session.settle(), &format!("overlay.{toolbar}.{row}"));
let actual = session.view(|_, cx| cx.read_from_clipboard().unwrap().text().unwrap());
let expected = if expected.is_empty() {
session.view(|v, _| {
let url = v.workspace_link_url("guide", None, &[] as &[&str], &[] as &[&str]);
format!("[Untitled]({url})")
})
} else {
expected
};
assert_eq!(actual, expected);
}
}
#[test]
fn card_alias_fields_place_the_caret_at_a_mouse_hit() {
use crate::theme::{FONT_SANS, TYPOGRAPHY};
use ui::{EntityInputHandler, TextRun};
let session = surface_ref_page(900, 620, FormFactor::Desktop);
session.view(|view, cx| {
view.edit_document(cx, |state| {
state
.workspace
.page_mut(HOME_PAGE_ID)
.unwrap()
.add_block(
"bookmark",
BlockSpec::Bookmark {
url: "https://example.com".into(),
title: Some("ABCDEFGH".into()),
description: Some("12345678".into()),
},
Some("note"),
Some(0),
20,
)
.unwrap();
})
});
session.overlay(OverlayEvent::SelectBlock("bookmark".into()));
session.click(&session.settle(), "overlay.bookmark_toolbar.edit");
for (field, text, insert) in [("title", "ABCDEFGH", "!"), ("description", "12345678", "?")]
{
let bounds = element(
&session.settle(),
&format!("overlay.embed_toolbar.card_edit_prompt.{field}"),
)
.bounds;
let advance = session.app.update(|cx| {
session
.window
.update(cx, |_, window, _| {
let line = window.text_system().shape_line(
text.into(),
px(TYPOGRAPHY.font_sm_px),
&[TextRun {
len: text.len(),
font: ui::font(FONT_SANS),
color: ui::rgb(0).into(),
background_color: None,
underline: None,
strikethrough: None,
}],
None,
);
f32::from(line.x_for_index(4))
})
.unwrap()
});
let x = bounds.x + 11.0 + advance;
let y = bounds.y + bounds.height * 0.5;
session.press(x, y, 1);
session.release(x, y);
session.app.update(|cx| {
session
.window
.update(cx, |v, w, cx| {
v.replace_text_in_range(None, insert, w, cx);
})
.unwrap()
});
}
session.click(
&session.settle(),
"overlay.embed_toolbar.card_edit_prompt.save",
);
session.view(|v, _| {
let node = v.page_snapshot().unwrap().block("bookmark").unwrap();
assert_eq!(node.props["prop:title"], "ABCD!EFGH");
assert_eq!(node.props["prop:description"], "1234?5678");
});
}
}
@@ -327,7 +327,11 @@ impl PlaygroundView {
}
}
fn copy_markdown(&mut self, slice: Option<crate::clipboard::Slice>, cx: &mut Context<Self>) {
pub(in crate::overlays) fn copy_markdown(
&mut self,
slice: Option<crate::clipboard::Slice>,
cx: &mut Context<Self>,
) {
if let Some(markdown) = slice
.map(|slice| slice.to_markdown_with(&|r| Some(self.reference_markdown_link(r))))
.filter(|text| !text.is_empty())
@@ -337,7 +341,11 @@ impl PlaygroundView {
}
}
fn copy_page_block_link(&mut self, ids: &[String], cx: &mut Context<Self>) {
pub(in crate::overlays) fn copy_page_block_link(
&mut self,
ids: &[String],
cx: &mut Context<Self>,
) {
if self.mode != crate::PlaygroundMode::Page || ids.is_empty() {
return;
}
@@ -23,7 +23,7 @@ use super::{
marks_in_range, view_link_popup,
};
fn slice_utf16(text: &str, start: usize, end: usize) -> String {
pub(super) fn slice_utf16(text: &str, start: usize, end: usize) -> String {
if start >= end || text.is_empty() {
return String::new();
}
@@ -146,6 +146,7 @@ impl PlaygroundView {
marks,
align,
selected_text,
link_spans: None,
current_turn_into_id,
can_create_table: !single_block
&& self.page_snapshot().is_some_and(|snapshot| {
@@ -283,6 +284,7 @@ impl PlaygroundView {
marks: MarkState::default(),
align: None,
selected_text: None,
link_spans: None,
current_turn_into_id: None,
can_create_table: false,
});
@@ -299,6 +301,7 @@ impl PlaygroundView {
marks,
align,
selected_text: None,
link_spans: None,
current_turn_into_id,
can_create_table: self.page_snapshot().is_some_and(|snapshot| {
self.can_convert_to_database(snapshot, &self.editor.block_selection)
@@ -396,3 +399,6 @@ impl PlaygroundView {
))
}
}
#[cfg(test)]
mod narrow_creation_tests;
@@ -0,0 +1,108 @@
use crate::{
DocState, HOME_PAGE_ID, PlaygroundOptions,
editor_session::{DocPoint, DocumentSelection},
overlays::{OverlayEvent, tests::open_with_options},
};
use blocksuite_playground_doc::{
read::BlockContent,
schema::{BlockSpec, ParagraphType},
};
#[test]
fn narrow_cross_paragraph_toolbar_more_executes_both_creation_actions() {
for (action, linked_doc) in [("create_table", false), ("create_linked_doc", true)] {
let s = open_with_options(
380,
480,
PlaygroundOptions {
hide_chrome: true,
..Default::default()
},
);
let mut state = DocState::new("narrow-create", 42).unwrap();
state
.workspace
.create_page(HOME_PAGE_ID, "Plan", 1)
.unwrap();
let page = state.workspace.ensure_page(HOME_PAGE_ID).unwrap();
for (id, parent, spec) in [
(
"root",
None,
BlockSpec::Page {
title: "Plan".into(),
},
),
("note", Some("root"), BlockSpec::Note { xywh: None }),
(
"a",
Some("note"),
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: "First task".into(),
},
),
(
"b",
Some("note"),
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: "Second task".into(),
},
),
] {
page.add_block(id, spec, parent, None, 2).unwrap();
}
s.view(|v, cx| v.set_document(state, cx));
s.settle();
s.app.update(|cx| {
s.window
.update(cx, |v, w, cx| {
v.change_selection(
DocumentSelection {
anchor: DocPoint::new("a", 0),
focus: DocPoint::new("b", 8),
},
w,
cx,
)
})
.unwrap()
});
s.click(&s.settle(), "overlay.format_toolbar.more");
let menu = s.settle();
for id in ["create_table", "create_linked_doc"] {
assert!(
menu.elements
.contains_key(&format!("overlay.format_toolbar.more.{id}"))
);
}
s.click(&menu, &format!("overlay.format_toolbar.more.{action}"));
if linked_doc {
assert!(s.view(|v, _| v.overlays.linked_doc_title_prompt().is_some()));
s.overlay(OverlayEvent::BookmarkApply);
}
s.view(|v, _| {
let note = v.page_snapshot().unwrap().block("note").unwrap();
assert_eq!(note.children.len(), 1);
assert!(if linked_doc {
matches!(
note.children[0].content,
BlockContent::EmbedLinkedDoc { .. }
)
} else {
matches!(note.children[0].content, BlockContent::Database(_))
});
});
s.undo();
assert!(s.view(|v, _| {
v.page_snapshot()
.unwrap()
.block("note")
.unwrap()
.children
.len()
== 2
}));
}
}
@@ -234,6 +234,7 @@ impl PlaygroundView {
},
align: None,
selected_text: None,
link_spans: None,
current_turn_into_id: None,
can_create_table: false,
};
@@ -383,6 +383,7 @@ impl PlaygroundView {
marks,
align: None,
selected_text: None,
link_spans: None,
current_turn_into_id: None,
can_create_table: false,
})
@@ -673,6 +673,12 @@ impl PlaygroundView {
cx,
);
}
AttachmentToolbarAction::CopyAsMarkdown if !readonly => {
self.copy_media_block_markdown(block_id, cx);
}
AttachmentToolbarAction::CopyLinkToBlock if !readonly => {
self.copy_media_block_link(block_id, cx);
}
AttachmentToolbarAction::Copy if !readonly => {
let _ = self.execute_block_menu_action(
block_id,
@@ -8,7 +8,7 @@ use crate::{
room_client::DocState,
};
fn open_table(width: u32, height: u32, options: PlaygroundOptions) -> Session {
pub(super) fn open_table(width: u32, height: u32, options: PlaygroundOptions) -> Session {
let session = open_with_options(width, height, options);
let mut state = DocState::new("table-controls", 42).unwrap();
state
@@ -64,7 +64,7 @@ fn save_evidence(session: &Session, filename: &str) {
}
/// Coordinates inside a cell, with an inset from its right and bottom edges.
fn cell_point(session: &Session, index: usize, right: f32, bottom: f32) -> (f32, f32) {
pub(super) fn cell_point(session: &Session, index: usize, right: f32, bottom: f32) -> (f32, f32) {
session.view(|view, _| {
let layout = view.flow_layout().unwrap();
let block = layout.block("table").unwrap();
@@ -135,7 +135,7 @@ fn table_controls_follow_host_and_embedding_in_narrow_viewports() {
}
}
fn table_data(session: &Session) -> TableData {
pub(super) fn table_data(session: &Session) -> TableData {
session.view(|view, _| {
view.page()
.unwrap()
@@ -385,6 +385,40 @@ fn table_cell_formats_and_wraps_selection_in_single_undo_steps() {
}
}
#[test]
fn table_cell_implicit_replacement_wraps_and_explicit_replacement_does_not() {
use ui::EntityInputHandler;
let session = open_table(900, 540, PlaygroundOptions::default());
let (x, y) = cell_point(&session, 0, 60.0, 18.0);
session.press(x, y, 3);
session.release(x, y);
for (range, expected, selection) in [(None, "[Item]", 1..5), (Some(0..4), "[", 1..1)] {
session.app.update(|cx| {
session
.window
.update(cx, |view, window, cx| {
view.table_cell.as_mut().unwrap().input.select_all();
view.replace_text_in_range(range, "[", window, cx);
})
.unwrap();
});
let text = || {
table_data(&session).cells[&("row-0".into(), "col-0".into())]
.text
.plain
.clone()
};
assert_eq!(text(), expected);
session.view(|view, _| {
assert_eq!(view.active_table_cell().unwrap().input.selection, selection);
});
session.undo();
assert_eq!(text(), "Item");
}
}
#[test]
fn column_axis_menu_opens_below_pill_and_flips_above_without_occlusion() {
use blocksuite_playground_doc::schema::ParagraphType;
@@ -0,0 +1,233 @@
//! The formatting toolbar over a text selection inside the focused `affine:table` cell:
//! inline marks, links, and highlight colors, each written to the cell text as one undo step.
use blocksuite_editor::inline_input::utf16_len;
use blocksuite_playground_doc::{read::BlockContent, session::split_delta};
use ui::{Context, Window};
use y_octo::{Any, TextAttributes, TextDeltaOp, TextInsert};
use crate::{
PlaygroundView,
block_flow::{FlowLayout, FlowRect},
overlays::{
DocEdit, SelectionFormat, SelectionFormatKind, bounding_rect, link_spans_in_range,
marks_in_range, view_format_bar::slice_utf16,
},
};
impl PlaygroundView {
/// The focused cell's non-empty text selection when the formatting toolbar may act on
/// it: no cell area, no composition, no table control in use, and a writable table.
fn table_cell_format_target(&self) -> Option<&super::InlineTableCell> {
self.table_cell.as_ref().filter(|cell| {
self.editor.selection.is_none()
&& cell.area.is_none()
&& !cell.input.selection.is_empty()
&& !cell.input.composing()
&& cell.axis_menu.is_none()
&& cell.axis_drag.is_none()
&& cell.col_resize_drag.is_none()
&& !self.table_is_readonly()
})
}
/// What the formatting toolbar shows for a text selection inside the focused cell. It
/// waits while a pointer drag selects text, like a body selection.
pub(crate) fn table_cell_selection_format(
&self,
layout: &FlowLayout,
) -> Option<SelectionFormat> {
let cell = self.table_cell_format_target().filter(|c| !c.dragging)?;
let selection = cell.input.selection.clone();
let BlockContent::Table(table) = &self.page_snapshot()?.block(&cell.block_id)?.content
else {
return None;
};
let text = &table
.cells
.get(&(cell.row_id.clone(), cell.column_id.clone()))?
.text;
let (bx, by, hit) =
Self::find_table_cell_hit(layout, &cell.block_id, &cell.row_id, &cell.column_id)?;
let line_h = hit.text.line_height();
let origin_x = bx + hit.text_origin.0 - self.overlays.code_scroll_x(&cell.block_id);
let origin_y = by + hit.text_origin.1;
let spans: Vec<FlowRect> = hit
.text
.selection_spans(selection.start, selection.end)
.into_iter()
.map(|(line, a, b)| {
FlowRect::new(
origin_x + a,
origin_y + line as f32 * line_h,
(b - a).max(1.0),
line_h,
)
})
.collect();
let anchor_world = bounding_rect(&spans)?;
Some(SelectionFormat {
kind: SelectionFormatKind::TableCellText,
anchor_world,
marks: marks_in_range(text, selection.start, selection.end),
align: None,
selected_text: Some(cell.input.selected_text().to_owned().into()),
link_spans: Some(link_spans_in_range(text, selection.start, selection.end)),
current_turn_into_id: None,
can_create_table: false,
})
}
/// Carry out a formatting toolbar edit on the focused cell's selection. Returns `false`
/// when the edit is not for a table cell.
pub(in crate::overlays) fn table_cell_overlay_edit(
&mut self,
edit: &DocEdit,
window: &mut Window,
cx: &mut Context<Self>,
) -> bool {
if self.table_cell_format_target().is_none() {
return false;
}
match edit {
DocEdit::Mark(mark) => self.toggle_table_cell_mark(mark, window, cx),
DocEdit::ColorMark { key, value } => self.format_table_cell_selection(
TextAttributes::from([(
(*key).to_owned(),
value.map_or(Any::Null, |v| Any::String(v.to_owned())),
)]),
window,
cx,
),
DocEdit::Link {
url,
display_text,
expected_prev_text,
expected_prev_links,
..
} => {
if self.table_cell_link_matches(
expected_prev_links.as_deref(),
expected_prev_text.as_deref(),
) {
self.link_table_cell_selection(
url.as_deref(),
display_text.as_deref(),
window,
cx,
);
}
}
_ => return false,
}
true
}
/// Compare the open link field's original selection against the current document.
fn table_cell_link_matches(
&self,
expected_links: Option<&[(usize, usize, String)]>,
expected_text: Option<&str>,
) -> bool {
let Some(cell) = self.table_cell.as_ref() else {
return false;
};
let Some(table) = self
.page()
.and_then(|page| page.read_table_block(&cell.block_id).ok().flatten())
else {
return false;
};
let Some(live_cell) = table
.cells
.get(&(cell.row_id.clone(), cell.column_id.clone()))
else {
return false;
};
let range = &cell.input.selection;
let text = &live_cell.text;
range.end <= utf16_len(&text.plain)
&& expected_text.is_some_and(|expected| {
slice_utf16(&text.plain, range.start, range.end) == expected
})
&& expected_links.is_some_and(|expected| {
link_spans_in_range(text, range.start, range.end).as_slice() == expected
})
}
/// Link the focused cell's selection to `url`, or clear its link when `url` is `None`. A
/// changed `display_text` replaces the selected text and keeps the marks of its first unit.
fn link_table_cell_selection(
&mut self,
url: Option<&str>,
display_text: Option<&str>,
window: &mut Window,
cx: &mut Context<Self>,
) {
let link = url.map_or(Any::Null, |url| Any::String(url.to_owned()));
let Some(cell) = self.table_cell.as_ref() else {
return;
};
let selection = cell.input.selection.clone();
let replacement = display_text
.filter(|text| url.is_some() && !text.is_empty() && *text != cell.input.selected_text())
.map(str::to_owned);
let Some(replacement) = replacement else {
self.format_table_cell_selection(
TextAttributes::from([("link".to_owned(), link)]),
window,
cx,
);
return;
};
let Some(mut format) = self.table_cell_first_selected_format() else {
return;
};
format.insert("link".to_owned(), link);
let mut delta = Vec::with_capacity(3);
if selection.start > 0 {
delta.push(TextDeltaOp::Retain {
retain: selection.start as u64,
format: None,
});
}
let inserted = utf16_len(&replacement);
delta.extend([
TextDeltaOp::Delete {
delete: selection.len() as u64,
},
TextDeltaOp::Insert {
insert: TextInsert::Text(replacement),
format: Some(format),
},
]);
self.commit_table_cell_delta(
&delta,
Some(selection.start..selection.start + inserted),
window,
cx,
);
}
/// The attributes of the first selected unit in the focused cell.
fn table_cell_first_selected_format(&self) -> Option<TextAttributes> {
let cell = self.table_cell.as_ref()?;
let BlockContent::Table(table) = &self.page_snapshot()?.block(&cell.block_id)?.content
else {
return None;
};
let text = &table
.cells
.get(&(cell.row_id.clone(), cell.column_id.clone()))?
.text;
let (_, tail) = split_delta(&text.delta, cell.input.selection.start as u64).ok()?;
Some(
tail.into_iter()
.find_map(|op| match op {
TextDeltaOp::Insert { format, .. } => Some(format.unwrap_or_default()),
_ => None,
})
.unwrap_or_default(),
)
}
}
@@ -2,6 +2,7 @@
mod area;
mod axis_drag;
mod format_bar;
mod navigation;
mod paint;
mod pointer;
@@ -16,9 +17,9 @@ mod controls_tests;
pub(crate) use pointer::TablePaintFrame;
use std::rc::Rc;
use std::{ops::Range, rc::Rc};
use blocksuite_editor::inline_input::{TextSplice, utf16_len};
use blocksuite_editor::inline_input::{TextSplice, Utf16ImeBuffer, utf16_len};
use blocksuite_playground_doc::read::{BlockContent, TableData};
use ui::{Context, Window};
@@ -38,6 +39,37 @@ pub(crate) enum InlineTargetEnd {
DiscardPreedit,
}
pub(crate) struct TableCellEdit<'a> {
pub(crate) input: TableCellEditInput<'a>,
}
pub(crate) struct TableCellEditInput<'a> {
buffer: &'a mut Utf16ImeBuffer,
wrap: Option<(String, &'static str)>,
}
impl TableCellEditInput<'_> {
pub(crate) fn replace(
&mut self,
range: Option<Range<usize>>,
text: &str,
) -> Option<TextSplice> {
if range.is_none()
&& !self.buffer.composing()
&& !self.buffer.selection.is_empty()
&& let Some(close) = rich_edit::closing_bracket(text)
{
self.wrap = Some((text.to_owned(), close));
return None;
}
self.buffer.replace(range, text)
}
pub(crate) fn unmark(&mut self) -> Option<TextSplice> {
self.buffer.unmark()
}
}
impl PlaygroundView {
pub(crate) fn uses_touch_table_bar(&self, viewport_width: f32) -> bool {
self.is_touch_host() || (!self.hide_chrome && viewport_width < 600.0)
@@ -305,7 +337,7 @@ impl PlaygroundView {
&mut self,
window: &mut Window,
cx: &mut Context<Self>,
f: impl FnOnce(&mut InlineTableCell) -> Option<TextSplice>,
f: impl FnOnce(&mut TableCellEdit<'_>) -> Option<TextSplice>,
) -> Option<()> {
if self.table_is_readonly() || self.has_table_area() {
return None;
@@ -313,7 +345,17 @@ impl PlaygroundView {
let (block_id, row_id, column_id, splice) = {
let cell = self.table_cell.as_mut()?;
cell.goal_x = None;
let splice = f(cell);
let mut edit = TableCellEdit {
input: TableCellEditInput {
buffer: &mut cell.input,
wrap: None,
},
};
let splice = f(&mut edit);
if let Some((open, close)) = edit.input.wrap {
self.wrap_table_cell_selection(&open, close, window, cx);
return Some(());
}
(
cell.block_id.clone(),
cell.row_id.clone(),
@@ -771,3 +813,10 @@ mod tests {
});
}
}
#[cfg(test)]
mod toolbar_tests;
#[cfg(test)]
use crate::overlays::{
FormatAction, HighlightColor, OverlayEvent, link_spans_in_range, tests::Session,
};
@@ -26,7 +26,7 @@ impl PlaygroundView {
}
let m = e.keystroke.modifiers;
let cmd = m.secondary(cx);
if composing || (e.prefer_character_input && key != "escape") {
if composing || (e.prefer_character_input && !matches!(key, "escape" | "tab")) {
if key == "escape" {
let _ = self.table_cell_input(window, cx, |cell| {
cell.input.cancel_preedit();
@@ -81,6 +81,7 @@ impl PlaygroundView {
return true;
}
"escape" => {}
"tab" => return false,
"v" | "z" | "y" if cmd => {}
_ => return true,
}
@@ -108,7 +109,11 @@ impl PlaygroundView {
}
true
}
"tab" => true,
"tab" if m.control || m.platform || m.alt || m.function => false,
"tab" => {
self.focus_table_cell_in_row_order(!m.shift, window, cx);
true
}
"enter" => {
let _ = self.table_cell_edit(window, cx, |c| c.input.replace(None, "\n"));
true
@@ -390,6 +395,37 @@ impl PlaygroundView {
Some((cell.block_id.clone(), rows, cols, r_idx, c_idx))
}
/// Move the focus to the next (`forward`) or previous cell in row-major order, with the
/// caret at the end of its text. The last cell (for `forward`) and the first cell keep
/// the focus. This changes focus only and writes nothing.
fn focus_table_cell_in_row_order(
&mut self,
forward: bool,
window: &mut Window,
cx: &mut Context<Self>,
) {
let Some((block_id, rows, cols, r, c)) = self.focused_table_grid() else {
return;
};
let index = r * cols.len() + c;
let target = if forward {
Some(index + 1).filter(|next| *next < rows.len() * cols.len())
} else {
index.checked_sub(1)
};
if let Some(target) = target {
let (row, col) = (target / cols.len(), target % cols.len());
self.focus_table_cell_at_edge(
block_id,
rows[row].clone(),
cols[col].clone(),
true,
window,
cx,
);
}
}
pub(super) fn focus_table_cell_at_edge(
&mut self,
block_id: String,
@@ -1,9 +1,24 @@
use std::ops::Range;
use blocksuite_playground_doc::{read::BlockContent, session::split_delta};
use ui::{Context, KeyDownEvent, Window};
use y_octo::{Any, TextAttributes, TextDeltaOp, TextInsert};
use crate::PlaygroundView;
/// The closing character that pairs with an opening bracket or quote.
pub(super) fn closing_bracket(open: &str) -> Option<&'static str> {
Some(match open {
"(" => ")",
"[" => "]",
"{" => "}",
"\"" => "\"",
"'" => "'",
"`" => "`",
_ => return None,
})
}
impl PlaygroundView {
pub(super) fn table_cell_rich_key(
&mut self,
@@ -12,27 +27,13 @@ impl PlaygroundView {
cx: &mut Context<Self>,
) -> Option<()> {
let cell = self.table_cell.as_ref()?;
let selection = cell.input.selection.clone();
if cell.area.is_some() || selection.is_empty() {
if cell.area.is_some() || cell.input.selection.is_empty() {
return None;
}
let stroke = &event.keystroke;
let modifiers = stroke.modifiers;
let command = modifiers.secondary(cx);
let block = cell.block_id.clone();
let row = cell.row_id.clone();
let column = cell.column_id.clone();
let start = selection.start as u64;
let len = selection.len() as u64;
let mut delta = Vec::with_capacity(4);
if start > 0 {
delta.push(TextDeltaOp::Retain {
retain: start,
format: None,
});
}
let wrapped = if command && !modifiers.alt {
if command && !modifiers.alt {
let mark = match (stroke.key.as_str(), modifiers.shift) {
("b", false) => "bold",
("i", false) => "italic",
@@ -41,61 +42,139 @@ impl PlaygroundView {
("e", false) => "code",
_ => return None,
};
if self.table_is_readonly() {
return Some(());
if !self.table_is_readonly() {
self.toggle_table_cell_mark(mark, window, cx);
}
let BlockContent::Table(table) = &self.page_snapshot()?.block(&block)?.content else {
return None;
};
let text = &table.cells.get(&(row.clone(), column.clone()))?.text;
let (_, tail) = split_delta(&text.delta, start).ok()?;
let (selected, _) = split_delta(&tail, len).ok()?;
let marked = selected.iter().all(|op| {
matches!(
op,
TextDeltaOp::Insert { format: Some(format), .. }
if format.get(mark) == Some(&Any::True)
)
});
let value = if marked { Any::Null } else { Any::True };
delta.push(TextDeltaOp::Retain {
retain: len,
format: Some(TextAttributes::from([(mark.to_owned(), value)])),
});
false
} else if !modifiers.platform && !modifiers.control && !self.table_is_readonly() {
let open = stroke.key_char.as_deref().unwrap_or(&stroke.key);
let close = match open {
"(" => ")",
"[" => "]",
"{" => "}",
"\"" | "'" | "`" => open,
_ => return None,
};
delta.extend([
TextDeltaOp::Insert {
insert: TextInsert::Text(open.into()),
format: None,
},
TextDeltaOp::Retain {
retain: len,
format: None,
},
TextDeltaOp::Insert {
insert: TextInsert::Text(close.into()),
format: None,
},
]);
true
} else {
return Some(());
}
if modifiers.platform || modifiers.control || self.table_is_readonly() {
return None;
}
let open = stroke.key_char.as_deref().unwrap_or(&stroke.key);
let close = closing_bracket(open)?;
self.wrap_table_cell_selection(open, close, window, cx);
Some(())
}
/// Whether every unit of the focused cell's selection carries `mark`.
pub(super) fn table_cell_selection_has_mark(&self, mark: &str) -> Option<bool> {
let cell = self.table_cell.as_ref()?;
let selection = cell.input.selection.clone();
let BlockContent::Table(table) = &self.page_snapshot()?.block(&cell.block_id)?.content
else {
return None;
};
let text = &table
.cells
.get(&(cell.row_id.clone(), cell.column_id.clone()))?
.text;
let (_, tail) = split_delta(&text.delta, selection.start as u64).ok()?;
let (selected, _) = split_delta(&tail, selection.len() as u64).ok()?;
Some(selected.iter().all(|op| {
matches!(
op,
TextDeltaOp::Insert { format: Some(format), .. }
if format.get(mark) == Some(&Any::True)
)
}))
}
let reversed = cell.input.reversed;
/// Toggle a boolean inline mark over the focused cell's selection in one undo step.
pub(super) fn toggle_table_cell_mark(
&mut self,
mark: &str,
window: &mut Window,
cx: &mut Context<Self>,
) {
let Some(marked) = self.table_cell_selection_has_mark(mark) else {
return;
};
let value = if marked { Any::Null } else { Any::True };
self.format_table_cell_selection(
TextAttributes::from([(mark.to_owned(), value)]),
window,
cx,
);
}
/// Write `attributes` over the focused cell's selection in one undo step.
pub(super) fn format_table_cell_selection(
&mut self,
attributes: TextAttributes,
window: &mut Window,
cx: &mut Context<Self>,
) {
let Some(selection) = self.table_cell.as_ref().map(|c| c.input.selection.clone()) else {
return;
};
let mut delta = retain_to(selection.start);
delta.push(TextDeltaOp::Retain {
retain: selection.len() as u64,
format: Some(attributes),
});
self.commit_table_cell_delta(&delta, None, window, cx);
}
/// Put `open` and `close` around the focused cell's non-empty selection in one undo step,
/// and keep the wrapped text selected.
pub(super) fn wrap_table_cell_selection(
&mut self,
open: &str,
close: &str,
window: &mut Window,
cx: &mut Context<Self>,
) {
let Some(selection) = self
.table_cell
.as_ref()
.map(|c| c.input.selection.clone())
.filter(|s| !s.is_empty())
else {
return;
};
let mut delta = retain_to(selection.start);
delta.extend([
TextDeltaOp::Insert {
insert: TextInsert::Text(open.into()),
format: None,
},
TextDeltaOp::Retain {
retain: selection.len() as u64,
format: None,
},
TextDeltaOp::Insert {
insert: TextInsert::Text(close.into()),
format: None,
},
]);
let shift = open.encode_utf16().count();
let wrapped = selection.start + shift..selection.end + shift;
self.commit_table_cell_delta(&delta, Some(wrapped), window, cx);
}
/// Apply `delta` to the focused cell's text as its own undo step. `select` sets the
/// selection after the edit; `None` keeps it.
pub(super) fn commit_table_cell_delta(
&mut self,
delta: &[TextDeltaOp],
select: Option<Range<usize>>,
window: &mut Window,
cx: &mut Context<Self>,
) {
let Some((block, row, column, reversed)) = self.table_cell.as_ref().map(|c| {
(
c.block_id.clone(),
c.row_id.clone(),
c.column_id.clone(),
c.input.reversed,
)
}) else {
return;
};
let now = self.now_ms(cx) as u64;
let result = self.page_mut().and_then(|page| {
page.stop_capturing()?;
let commit = page.apply_table_cell_text_delta(&block, &row, &column, &delta, now);
let commit = page.apply_table_cell_text_delta(&block, &row, &column, delta, now);
page.stop_capturing()?;
commit
});
@@ -103,9 +182,9 @@ impl PlaygroundView {
Ok(Some(commit)) => {
self.did_table_cell_commit(&block, commit);
self.sync_table_cell_from_snapshot();
if wrapped {
if let Some(range) = select {
self.table_cell_input(window, cx, |cell| {
cell.input.select(selection.start + 1..selection.end + 1);
cell.input.select(range);
cell.input.reversed = reversed;
});
} else {
@@ -116,6 +195,16 @@ impl PlaygroundView {
Ok(None) => {}
Err(error) => eprintln!("table cell edit: {error}"),
}
Some(())
}
}
fn retain_to(start: usize) -> Vec<TextDeltaOp> {
let mut delta = Vec::with_capacity(4);
if start > 0 {
delta.push(TextDeltaOp::Retain {
retain: start as u64,
format: None,
});
}
delta
}
@@ -5,7 +5,7 @@ use std::{cell::Cell, rc::Rc};
use ui::{AnyElement, FontWeight, MouseButton, div, prelude::*, px};
use crate::{
PlaygroundMode, PlaygroundView,
PlaygroundView,
block_flow::FlowRect,
overlays::{
TOOLBAR_CHROME_BORDER, TOOLBAR_CHROME_RADIUS, TOOLBAR_MENU_MIN_W, TOOLBAR_MENU_PADDING,
@@ -18,7 +18,9 @@ use crate::{
const AXIS_MENU_NATURAL_H: f32 = 327.0;
const AXIS_MENU_EDGE_MARGIN: f32 = 8.0;
const AXIS_MENU_GAP: f32 = 4.0;
const AXIS_MENU_MIN_SIDE_H: f32 = 160.0;
/// The smallest height that still shows one menu row inside the panel padding.
const AXIS_MENU_MIN_SCROLL_H: f32 =
TOOLBAR_MENU_ROW_H + 2.0 * (TOOLBAR_MENU_PADDING + TOOLBAR_CHROME_BORDER);
const SWATCHES: [(&str, &str, &str, &str); 9] = [
(
@@ -104,7 +106,7 @@ impl PlaygroundView {
(viewport_h - menu_h - AXIS_MENU_EDGE_MARGIN).max(AXIS_MENU_EDGE_MARGIN),
)
.round();
self.build_table_axis_menu_at(axis, left, top, menu_w, max_height, viewport_w, palette, cx)
self.build_table_axis_menu_at(axis, left, top, menu_w, None, palette, cx)
}
#[allow(clippy::too_many_arguments)]
@@ -121,7 +123,7 @@ impl PlaygroundView {
let menu_w = TOOLBAR_MENU_MIN_W.max(196.0);
let (left, top, max_height) =
place_table_axis_menu(axis, anchor, menu_w, top_margin, viewport_w, viewport_h);
self.build_table_axis_menu_at(axis, left, top, menu_w, max_height, viewport_w, palette, cx)
self.build_table_axis_menu_at(axis, left, top, menu_w, Some(max_height), palette, cx)
}
#[allow(clippy::too_many_arguments)]
@@ -131,8 +133,7 @@ impl PlaygroundView {
left: f32,
top: f32,
menu_w: f32,
max_height: f32,
viewport_w: f32,
scroll_height: Option<f32>,
palette: &Palette,
cx: &mut ui::Context<Self>,
) -> AnyElement {
@@ -275,9 +276,9 @@ impl PlaygroundView {
.child(label),
);
}
if self.mode != PlaygroundMode::Page || self.uses_touch_table_bar(viewport_w) {
let Some(max_height) = scroll_height else {
return menu.child(contents).into_any_element();
}
};
let visible = max_height - 2.0 * (TOOLBAR_MENU_PADDING + TOOLBAR_CHROME_BORDER.ceil());
let offset = self.overlays.table_axis_scroll.clone();
let max_scroll = Rc::new(Cell::new(0.0));
@@ -342,14 +343,16 @@ fn place_table_axis_menu(
max_vp_h,
);
}
// Neither side holds the whole menu: the roomier side takes it, scrolling inside,
// so the menu never covers the pill that opened it.
let side_room = room_above.max(room_below);
if side_room >= AXIS_MENU_MIN_SIDE_H {
if side_room >= AXIS_MENU_MIN_SCROLL_H {
let top = if room_above > room_below {
top_min.round()
} else {
below_y.round()
};
return (left, top, side_room);
return (left, top, side_room.floor());
}
let menu_h = AXIS_MENU_NATURAL_H.min(max_vp_h);
let top = below_y
@@ -426,7 +429,41 @@ fn table_axis_swatches(
#[cfg(test)]
mod tests {
use super::SWATCHES;
use super::{
AXIS_MENU_EDGE_MARGIN, AXIS_MENU_GAP, AXIS_MENU_NATURAL_H, FlowRect, SWATCHES,
TableAxisMenu, place_table_axis_menu,
};
#[test]
fn column_axis_menu_takes_the_roomier_side_without_covering_its_pill() {
// (viewport height, pill top, expected side): `true` is below the pill.
let top_margin = 48.0;
for (viewport_h, pill_y, below) in [
(240.0, 70.0, true),
(240.0, 180.0, false),
(300.0, 140.0, true),
(300.0, 170.0, false),
] {
let pill = FlowRect::new(40.0, pill_y, 24.0, 12.0);
let (left, top, max_h) = place_table_axis_menu(
TableAxisMenu::Column,
pill,
196.0,
top_margin,
320.0,
viewport_h,
);
let bottom = top + max_h;
assert!(max_h < AXIS_MENU_NATURAL_H, "{viewport_h} {pill_y}");
assert!(top >= top_margin && bottom <= viewport_h - AXIS_MENU_EDGE_MARGIN);
assert!(left >= AXIS_MENU_EDGE_MARGIN && left + 196.0 <= 320.0);
if below {
assert_eq!(top, (pill.bottom() + AXIS_MENU_GAP).round());
} else {
assert!(bottom <= pill.y - AXIS_MENU_GAP);
}
}
}
#[test]
fn table_axis_swatches_keep_control_ids_and_color_tokens() {
@@ -0,0 +1,339 @@
use super::controls_tests::{cell_point, open_table, table_data};
use crate::{HOME_PAGE_ID, PlaygroundOptions, room_client::DocState};
fn toolbar_table(options: PlaygroundOptions) -> super::Session {
let session = open_table(900, 540, options);
let seed = session.view(|view, cx| {
view.edit_document(cx, |state| {
let source = state.workspace.page_mut(HOME_PAGE_ID).unwrap();
source
.splice_table_cell_text("table", "row-0", "col-1", 0, 6, "B🧭", 5)
.unwrap();
source.encode_update_v1().unwrap()
})
});
let mut state = DocState::new("table-toolbar", 43).unwrap();
state
.workspace
.create_page(HOME_PAGE_ID, "Simple table", 1)
.unwrap();
state
.workspace
.ensure_page(HOME_PAGE_ID)
.unwrap()
.apply_remote_update_v1(&seed)
.unwrap();
session.view(|v, cx| v.set_document(state, cx));
session.settle();
session
}
#[test]
fn table_tab_moves_in_row_order_and_leaves_non_cell_tab_to_the_host() {
use ui::{KeyDownEvent, Keystroke, Modifiers};
for page_readonly in [false, true] {
let s = toolbar_table(PlaygroundOptions {
page_readonly,
..Default::default()
});
let before = s.written();
s.app.update(|cx| {
s.window
.update(cx, |v, window, cx| {
v.focus_table_cell(
"table".into(),
"row-0".into(),
"col-0".into(),
None,
window,
cx,
);
for (shift, row, col) in [
(true, "row-0", "col-0"),
(false, "row-0", "col-1"),
(false, "row-1", "col-0"),
(false, "row-1", "col-1"),
(false, "row-1", "col-1"),
(true, "row-1", "col-0"),
(true, "row-0", "col-1"),
(true, "row-0", "col-0"),
] {
let event = KeyDownEvent {
keystroke: Keystroke {
key: "tab".into(),
key_char: None,
modifiers: Modifiers {
shift,
..Default::default()
},
},
is_held: false,
prefer_character_input: false,
};
assert!(v.table_cell_key_down(&event, window, cx));
let cell = v.active_table_cell().unwrap();
assert_eq!((cell.row_id.as_str(), cell.column_id.as_str()), (row, col));
if !(shift
&& row == "row-0"
&& col == "col-0"
&& cell.input.selection.start == 0)
{
let end = cell.input.text().encode_utf16().count();
assert_eq!(cell.input.selection, end..end);
}
}
for modifiers in [
Modifiers {
control: true,
..Default::default()
},
Modifiers {
platform: true,
..Default::default()
},
Modifiers {
alt: true,
..Default::default()
},
] {
let event = KeyDownEvent {
keystroke: Keystroke {
key: "tab".into(),
key_char: None,
modifiers,
},
is_held: false,
prefer_character_input: false,
};
assert!(!v.table_cell_key_down(&event, window, cx));
}
let plain = KeyDownEvent {
keystroke: Keystroke {
key: "tab".into(),
key_char: None,
modifiers: Modifiers::default(),
},
is_held: false,
prefer_character_input: false,
};
v.table_cell.as_mut().unwrap().input.mark(None, "候", None);
assert!(!v.table_cell_key_down(&plain, window, cx));
let cell = v.table_cell.as_mut().unwrap();
cell.input.cancel_preedit();
cell.select_area((0, 0), (1, 1));
assert!(!v.table_cell_key_down(&plain, window, cx));
})
.unwrap()
});
assert_eq!(s.written(), before);
assert!(s.view(|v, _| !v.page().unwrap().can_undo()));
}
}
#[test]
fn table_inline_toolbar_marks_and_link_undo_and_remote_link_guard() {
use super::{FormatAction, HighlightColor, OverlayEvent};
use blocksuite_playground_doc::session::PageDocSession;
use ui::EntityInputHandler;
use y_octo::{Any, TextAttributes, TextDeltaOp};
const URL_A: &str = "https://example.com/a";
const URL_B: &str = "https://example.com/b";
let s = toolbar_table(PlaygroundOptions::default());
let text = || {
table_data(&s).cells[&("row-0".into(), "col-0".into())]
.text
.clone()
};
let mark = |key: &str| {
text().delta.iter().find_map(|op| match op {
TextDeltaOp::Insert {
format: Some(attrs),
..
} => attrs.get(key).cloned(),
_ => None,
})
};
let select = || {
let (x, y) = cell_point(&s, 0, 60.0, 18.0);
s.press(x, y, 3);
s.release(x, y);
s.view(|v, _| v.table_cell.as_mut().unwrap().input.select_all());
s.settle();
};
let input = |range, value: &str| {
s.app.update(|cx| {
s.window
.update(cx, |v, w, cx| {
v.replace_text_in_range(range, value, w, cx);
})
.unwrap()
})
};
select();
s.click(&s.settle(), "overlay.format_toolbar.bold");
assert_eq!(mark("bold"), Some(Any::True));
s.undo();
assert_eq!(mark("bold"), None);
select();
s.click(&s.settle(), "overlay.format_toolbar.highlight");
s.overlay(OverlayEvent::FormatBgColor(HighlightColor::Yellow));
assert!(mark("background").is_some());
s.undo();
assert_eq!(mark("background"), None);
select();
s.click(&s.settle(), "overlay.format_toolbar.link");
input(None, URL_A);
s.key("tab");
input(Some(0..4), "Plan");
s.overlay(OverlayEvent::LinkApply);
assert_eq!(text().plain, "Plan");
assert_eq!(mark("link"), Some(Any::String(URL_A.into())));
s.undo();
assert_eq!(text().plain, "Item");
assert_eq!(mark("link"), None);
let baseline = s.view(|v, _| v.page().unwrap().encode_update_v1().unwrap());
let mut peer = PageDocSession::new(HOME_PAGE_ID, 4242).unwrap();
peer.apply_remote_update_v1(&baseline).unwrap();
let mut set_peer_url = |url: &str, now| {
let commit = peer
.apply_table_cell_text_delta(
"table",
"row-0",
"col-0",
&[TextDeltaOp::Retain {
retain: 4,
format: Some(TextAttributes::from([(
"link".into(),
Any::String(url.into()),
)])),
}],
now,
)
.unwrap()
.unwrap();
s.view(|v, cx| {
v.edit_document(cx, |state| {
state
.workspace
.page_mut(HOME_PAGE_ID)
.unwrap()
.apply_remote_update_v1(&commit.update)
.unwrap();
})
});
};
set_peer_url(URL_A, 100);
select();
s.overlay(OverlayEvent::Format(FormatAction::Link));
assert_eq!(
s.view(|v, _| v.overlays.active_text_field().unwrap().text()),
URL_A
);
set_peer_url(URL_B, 101);
s.settle();
assert_eq!(
s.view(|v, _| v.overlays.active_text_field().unwrap().text()),
URL_A,
);
let before_remove = s.written();
assert!(s.view(|v, _| !v.page().unwrap().can_undo()));
s.overlay(OverlayEvent::LinkRemove);
assert_eq!(mark("link"), Some(Any::String(URL_B.into())));
assert_eq!(s.written(), before_remove);
assert!(s.view(|v, _| !v.page().unwrap().can_undo()));
}
#[test]
fn table_link_apply_rejects_a_new_partial_remote_link_and_accepts_unchanged_mixed_links() {
use super::{FormatAction, OverlayEvent, link_spans_in_range};
use blocksuite_playground_doc::session::PageDocSession;
use ui::EntityInputHandler;
use y_octo::{Any, TextAttributes, TextDeltaOp};
const LOCAL: &str = "https://example.com/a";
const PEER: &str = "https://example.com/b";
for peer_changes_after_open in [true, false] {
let s = toolbar_table(PlaygroundOptions::default());
let baseline = s.view(|v, _| v.page().unwrap().encode_update_v1().unwrap());
let mut peer = PageDocSession::new(HOME_PAGE_ID, 4242).unwrap();
peer.apply_remote_update_v1(&baseline).unwrap();
let update = peer
.apply_table_cell_text_delta(
"table",
"row-0",
"col-0",
&[TextDeltaOp::Retain {
retain: 2,
format: Some(TextAttributes::from([(
"link".into(),
Any::String(PEER.into()),
)])),
}],
100,
)
.unwrap()
.unwrap()
.update;
let receive = || {
s.view(|v, cx| {
v.edit_document(cx, |state| {
state
.workspace
.page_mut(HOME_PAGE_ID)
.unwrap()
.apply_remote_update_v1(&update)
.unwrap();
})
})
};
if !peer_changes_after_open {
receive();
}
let (x, y) = cell_point(&s, 0, 60.0, 18.0);
s.press(x, y, 3);
s.release(x, y);
s.view(|v, _| v.table_cell.as_mut().unwrap().input.select_all());
s.settle();
s.overlay(OverlayEvent::Format(FormatAction::Link));
s.app.update(|cx| {
s.window
.update(cx, |v, w, cx| {
v.replace_text_in_range(None, LOCAL, w, cx);
})
.unwrap()
});
if peer_changes_after_open {
receive();
s.settle();
}
assert_eq!(
s.view(|v, _| v.overlays.active_text_field().unwrap().text()),
LOCAL
);
let spans = || {
let text = &table_data(&s).cells[&("row-0".into(), "col-0".into())].text;
assert_eq!(text.plain, "Item");
link_spans_in_range(text, 0, 4)
};
let mixed = vec![(0, 2, PEER.to_owned())];
assert_eq!(spans(), mixed);
let before = s.written();
assert!(s.view(|v, _| !v.page().unwrap().can_undo()));
s.overlay(OverlayEvent::LinkApply);
if peer_changes_after_open {
assert_eq!(spans(), mixed);
assert_eq!(s.written(), before);
assert!(s.view(|v, _| !v.page().unwrap().can_undo()));
} else {
assert_eq!(spans(), vec![(0, 4, LOCAL.to_owned())]);
s.undo();
assert_eq!(spans(), mixed);
assert!(s.view(|v, _| !v.page().unwrap().can_undo()));
}
}
}