mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-05 11:15:01 +03:00
feat(editor): add web CJK/RTL fallback, touch dispatch, and BlockSuite parity
Enable browser Canvas CJK and fullwidth punctuation fallback by default, bundle Noto Sans Arabic and Noto Sans Hebrew for native RTL shaping, and bridge touch tap and pan gestures to window mouse and scroll listeners. Align BlockSuite editor behavior with Web: - Trigger the linked-doc menu on mid-word `@`, `[[`, and `【【`. - Add all eight inline Markdown rules on ASCII space or Enter with IME guards and non-leaking trailing space or pending marks. - Support block-level Markdown on Enter and inside list and quote blocks. - Outdent nested empty list items on Enter and exit quote blocks on two Enter keys without an extra blank paragraph. - Use subsequence fuzzy matching in the slash menu, pass through Enter and arrow keys when in-document search has no match, and split Linked Page into New Doc and Linked Doc commands. - Add block conversion shortcuts, Mod-k link focus, and Escape / second Mod-a whole-block selection.
This commit is contained in:
1 parent
d63b1c7d3b
commit
6efd971122
23 files changed
+2135
-366
No files matched your search
@@ -33,12 +33,12 @@ These crates belong to the client Cargo workspace rooted at `packages/frontend/C
|
||||
### Overlays and block controls
|
||||
- **Who owns what**: `EditorSession` owns the text selection, the caret and every text edit. `Overlays` (`overlays/`) owns what floats above or reacts inside the page: the slash menu, the formatting toolbar, the drag handle with its drop indicator, hover, and the block controls. The overlays read the selection (as a `SelectionFormat`: its world-space box, the marks every selected unit carries, the shared alignment) and never paint a caret or a selection of their own.
|
||||
- **Data in, commands out**: `Overlays` takes an `OverlayScene` (page snapshot, world-space layout, window geometry) with an `OverlayEvent` or a key, and answers with `OverlayEffects`. The `PlaygroundView` glue in `overlays/{view,view_edits}.rs` feeds it input and carries the effects out; `lib.rs`, `chrome.rs` and `block_flow/` only carry hooks (`PagePaint` into `page_elements`, the page-layer elements and popovers into the element tree, listeners). `PlaygroundView::dispatch_overlay` is the entry for pointer listeners and for hosts and tests (`OpenSlashMenu`, `SetSlashQuery`, `SetSelection`, ...); `SetSelection` sets the editor's selection.
|
||||
- **Pointer and keys**: A press on the page dismisses the slash menu, the link field (unapplied) and a block drag, then goes to the editor; pointer moves and the release are handled at the window root, so a drag continues outside the page. The formatting toolbar waits while the button of a plain press is held and opens on release; a double or triple click opens it at once. Keys reach one handler, `editor_key_down`, which first offers them to the overlays: an open link field takes every key but the ones that type text, the slash menu takes `Up`, `Down`, `Tab`, `Shift+Tab`, `Enter` and `Escape` (`Tab` steps through the items and never indents the block; `Enter` without a match closes the menu and does not split the block), and everything else is the editor's. A pointer on an open popover does not change which block is hovered under it.
|
||||
- **Pointer and keys**: A press on the page dismisses the slash menu, the link field (unapplied) and a block drag, then goes to the editor; pointer moves and the release are handled at the window root, so a drag continues outside the page. The formatting toolbar waits while the button of a plain press is held and opens on release; a double or triple click opens it at once. Keys reach one handler, `editor_key_down`, which first offers them to the overlays: an open link field takes every key but the ones that type text, the slash menu takes `Up`, `Down`, `Tab`, `Shift+Tab`, `Enter` and `Escape` (`Tab` steps through the items and never indents the block; when triggered in-document with no matching items, `Enter`, `Up`, and `Down` close the menu and pass through to the editor), and everything else is the editor's. A pointer on an open popover does not change which block is hovered under it.
|
||||
- **Edits are single undo steps**: Every overlay edit goes through the editor's `PageDocSession`, stores the selection for undo, and is published like any editor commit. Marks use the editor's `format_mark`; a link and an alignment run in one `structural_edit` across the selected paragraph and list blocks; a to-do box, a collapse and a drop are isolated between `stop_capturing` calls, the drop through `reparent_block` so numbered runs are renumbered. A slash command is one `structural_edit`, following BlockSuite's `updateBlockType` and `appendDivider`: it removes the typed `/filter`, then a paragraph type, a list type or code converts the block with whatever text it has left (in place within a flavour, as a fresh block across flavours; a block without text of its own gets the new block below instead), and a divider goes right below the block, followed by an empty paragraph to type in when the block was the last of its parent. The caret stays where the command was typed, or moves to the block after a divider. One undo restores the typed command.
|
||||
- **Positioner**: `place_popover` is pure and works in screen space below the top bar: `Above` (formatting toolbar, centered on the selection) and `BelowStart` (slash menu, at the caret) flip to the other side when the preferred one would come closer than the edge margin to the top bar or the window bottom, and clamp horizontally inside the margins. Results are on the pixel grid.
|
||||
- **Overlay motion**: Popovers fade over 150 ms with an ease-out cubic `EaseOut` evaluated at scheduler time. An opening popover mounts on its first frame at zero opacity so its hitboxes are live immediately; a closed popover at zero opacity is unmounted, and one fading out carries no listeners and is dropped when the fade ends. Disclosure chevrons turn over the same 150 ms. Nothing here loops per frame.
|
||||
- **Slash menu** (`overlay.slash_menu`, rows `overlay.slash_menu.item.<id>`, `.group.<name>`, `.query`, `.empty`): Typing `/` at a caret in paragraph or list text, outside inline code, opens it on that character, remembered as a relative position (`EditorSession::slash_trigger`): text a peer inserts before the `/` moves the menu along. The text between the `/` and the caret is both document text and the filter (`query_in_document`); the menu closes when the caret leaves that text, whitespace follows the `/`, or the character at the position is no longer that `/` (deleted, or deleted and typed again by a peer), and a command never runs on text it did not open on. `Escape` leaves the text as typed. `OpenSlashMenu` opens the menu with a filter of its own, shown in a query row and edited by the menu's keys. Without matches the list keeps a `No results` row. Items follow BlockSuite's order in two groups (`Basic`: text, the six headings, code block, quote, divider, linked page [`SlashCommand::LinkedPage`]; `List`: bulleted, numbered, to-do, toggle); all six headings stay in the list itself so each is one filter away. Each icon sits in a bordered 28 px box, rows are 32 px, and the menu has no border, only its shadow.
|
||||
- **Linked-doc `@` menu** (`overlay.linked_doc_menu`, rows `overlay.linked_doc_menu.item.<idx>`, `overlay.linked_doc_menu.create`): Typing `@` at block start or immediately after whitespace in paragraph or list text (outside inline code) opens the linked-doc popover anchored at the caret (`EditorSession::linked_doc_trigger`), querying the active `WorkspaceDocDirectory` as the user types. `Up`/`Down` move selection across matched docs and the trailing Create row, `Enter` selects or creates the linked doc and replaces `@query` with a BlockSuite `InlineReference` (`LinkedPage`) chip in one undo step, and `Escape` closes the menu while leaving the typed text intact.
|
||||
- **Slash menu** (`overlay.slash_menu`, rows `overlay.slash_menu.item.<id>`, `.group.<name>`, `.query`, `.empty`): Typing `/` at a caret in paragraph or list text, outside inline code, opens it on that character, remembered as a relative position (`EditorSession::slash_trigger`): text a peer inserts before the `/` moves the menu along. The text between the `/` and the caret is both document text and the filter (`query_in_document`); the menu closes when the caret leaves that text, whitespace follows the `/`, or the character at the position is no longer that `/` (deleted, or deleted and typed again by a peer), and a command never runs on text it did not open on. `Escape` leaves the text as typed. `OpenSlashMenu` opens the menu with a filter of its own, shown in a query row and edited by the menu's keys. Filtering uses case- and whitespace-insensitive subsequence matching (`isFuzzyMatch`); without matches the list keeps a `No results` row. Items follow BlockSuite's order in two groups (`Basic`: text, the six headings, code block, quote, divider, new doc [`SlashCommand::NewDoc`], linked doc [`SlashCommand::LinkedDoc`]; `List`: bulleted, numbered, to-do, toggle); all six headings stay in the list itself so each is one filter away. Each icon sits in a bordered 28 px box, rows are 32 px, and the menu has no border, only its shadow.
|
||||
- **Linked-doc `@` menu** (`overlay.linked_doc_menu`, rows `overlay.linked_doc_menu.item.<idx>`, `overlay.linked_doc_menu.create`): Typing `@` anywhere in paragraph or list text (outside inline code), or typing `[[` or `【【` (which converts the pair into `@`), opens the linked-doc popover anchored at the caret (`EditorSession::linked_doc_trigger`), querying the active `WorkspaceDocDirectory` as the user types. `Up`/`Down` move selection across matched docs and the trailing Create row, `Enter` selects or creates the linked doc and replaces `@query` with a BlockSuite `InlineReference` (`LinkedPage`) chip in one undo step, and `Escape` closes the menu while leaving the typed text intact.
|
||||
- **Formatting toolbar** (`overlay.format_toolbar`, buttons `.bold`, `.italic`, `.underline`, `.strike`, `.code`, `.link`, `.align_left|center|right`, link field `.link_input`, `.link_apply`, `.link_remove`): shown above a finished, non-empty selection of paragraph and list text, single-block or across blocks, while no composition runs and no slash menu is up; a selection touching the title or code gets none. A mark button is active only when the whole selection carries the mark. Alignment goes on every paragraph and list block the selection touches, empty ones included, and a block that sets none reads as its nearest aligned ancestor's. The link field is a one-line text input of its own (`LinkBar`: text, selection, composition). While it is open it is the view's text input: every `EntityInputHandler` call goes to it, `editor.composing()` stays false, and the document's text, selection and composition are untouched until `Apply`; opening, closing and every change of it are reported with `notify_text_input_changed`. Caret keys, deletion, select-all, copy and cut are the field's, `Escape` abandons a composition before it closes the field, and a keyboard paste reads the clipboard where the platform can; in a browser the key keeps its default action so the `paste` event that follows reaches the field. It has the only caret; the document keeps showing the selection.
|
||||
- **Drag handle** (`overlay.drag_handle`, `overlay.drop_indicator`): mounted only for the hovered or dragged block, 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). A heading keeps the place beside its text for its collapse chevron: its handle sits one step further out, and is left away where the gutter has no room for both. A drag targets the nearest slot among the block's own siblings.
|
||||
- **Block controls**: `page.block.<id>.checkbox`, `.toggle` and `.collapse` are 24 px targets over the to-do box, the toggle chevron and the heading chevron (an expanded heading shows its chevron only while the pointer is on its row); `page.block.<id>.copy` appears on a hovered code block and reads `Copied` for 1.5 s on the scheduler clock. A sideways scroll over an unwrapped code block scrolls its lines inside `BlockBody::code_scroll` instead of the page; the caret, the selection, the bounds given to the input method, collaborators' carets and selections (translated per highlight span's own block scroll before clamping), and pointer hit-testing follow that scroll and stay inside the code area (`ScrolledCode`), and moving the caret scrolls it into view.
|
||||
|
||||
@@ -141,6 +141,8 @@ pub struct Preedit {
|
||||
#[derive(Default)]
|
||||
pub struct EditorSession {
|
||||
pub selection: Option<DocumentSelection>,
|
||||
/// Selected whole-block IDs in document order (entered via `Escape` or second `Mod-a`).
|
||||
pub block_selection: Vec<String>,
|
||||
pub goal_x: Option<f32>,
|
||||
pub preedit: Option<Preedit>,
|
||||
pub relative_selection: Option<SelectionSnapshot>,
|
||||
|
||||
@@ -11,9 +11,10 @@ pub enum SlashCommand {
|
||||
List(ListType),
|
||||
Divider,
|
||||
Code,
|
||||
/// Converts the current line into a newly created linked document and replaces it
|
||||
/// with an inline `LinkedPage` reference chip.
|
||||
LinkedPage,
|
||||
/// Creates a new empty document and inserts an inline `LinkedPage` reference chip at the caret.
|
||||
NewDoc,
|
||||
/// Replaces `/query` with `@` and opens the `@` linked-document picker at the caret.
|
||||
LinkedDoc,
|
||||
}
|
||||
|
||||
impl SlashCommand {
|
||||
@@ -35,7 +36,7 @@ impl SlashCommand {
|
||||
language: None,
|
||||
caption: String::new(),
|
||||
},
|
||||
Self::LinkedPage => BlockSpec::Paragraph {
|
||||
Self::NewDoc | Self::LinkedDoc => BlockSpec::Paragraph {
|
||||
paragraph_type: ParagraphType::Text,
|
||||
text: String::new(),
|
||||
},
|
||||
@@ -78,13 +79,13 @@ const fn slash_item(
|
||||
/// Every slash menu item, in menu order; items of one group are adjacent. The order is
|
||||
/// BlockSuite's (text, headings, code, quote, divider, then lists), with all six headings
|
||||
/// in the list itself so each is one filter away.
|
||||
pub const SLASH_ITEMS: [SlashItem; 15] = [
|
||||
pub const SLASH_ITEMS: [SlashItem; 16] = [
|
||||
slash_item(
|
||||
"text",
|
||||
"Text",
|
||||
"Basic",
|
||||
"TextIcon",
|
||||
&["paragraph", "plain"],
|
||||
&["plain"],
|
||||
SlashCommand::Paragraph(ParagraphType::Text),
|
||||
),
|
||||
slash_item(
|
||||
@@ -160,12 +161,20 @@ pub const SLASH_ITEMS: [SlashItem; 15] = [
|
||||
SlashCommand::Divider,
|
||||
),
|
||||
slash_item(
|
||||
"linked_page",
|
||||
"Linked Page",
|
||||
"new_doc",
|
||||
"New Doc",
|
||||
"Basic",
|
||||
"PlusIcon",
|
||||
&["subpage", "newdoc", "page"],
|
||||
SlashCommand::NewDoc,
|
||||
),
|
||||
slash_item(
|
||||
"linked_doc",
|
||||
"Linked Doc",
|
||||
"Basic",
|
||||
"LinkedPageIcon",
|
||||
&["subpage", "linkeddoc"],
|
||||
SlashCommand::LinkedPage,
|
||||
&["linkedpage", "at", "mention", "doc", "duallink"],
|
||||
SlashCommand::LinkedDoc,
|
||||
),
|
||||
slash_item(
|
||||
"bulleted",
|
||||
@@ -201,33 +210,90 @@ pub const SLASH_ITEMS: [SlashItem; 15] = [
|
||||
),
|
||||
];
|
||||
|
||||
/// Items matching `query`, in menu order: the query is found anywhere in a title (case and
|
||||
/// spaces ignored) or starts a keyword. An empty query matches every item.
|
||||
fn is_fuzzy_match(haystack: &str, needle: &str) -> bool {
|
||||
let mut chars = needle.chars();
|
||||
let Some(mut target) = chars.next() else {
|
||||
return true;
|
||||
};
|
||||
for ch in haystack
|
||||
.chars()
|
||||
.filter(|ch| !ch.is_whitespace())
|
||||
.flat_map(char::to_lowercase)
|
||||
{
|
||||
if ch == target {
|
||||
match chars.next() {
|
||||
Some(next) => target = next,
|
||||
None => return true,
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Subsequence score matching BlockSuite's `substringMatchScore` (`string.ts:44-75`):
|
||||
/// `[0.5, 1.0]` when `query` is a contiguous substring of `name`, `(0.0, 0.5)` for the
|
||||
/// longest common contiguous substring, and `0.0` when empty or longer than `name`.
|
||||
pub fn substring_match_score(name: &str, query: &str) -> f64 {
|
||||
let query_units: Vec<u16> = query.to_lowercase().encode_utf16().collect();
|
||||
let name_units: Vec<u16> = name.to_lowercase().encode_utf16().collect();
|
||||
if query_units.is_empty() || name_units.is_empty() || query_units.len() > name_units.len() {
|
||||
return 0.0;
|
||||
}
|
||||
let score = if name_units
|
||||
.windows(query_units.len())
|
||||
.any(|window| window == query_units.as_slice())
|
||||
{
|
||||
1.0 + query_units.len() as f64 / name_units.len() as f64
|
||||
} else {
|
||||
let mut max_match = 0usize;
|
||||
for i in 0..query_units.len() {
|
||||
for j in 0..name_units.len() {
|
||||
let mut len = 0usize;
|
||||
while i + len < query_units.len()
|
||||
&& j + len < name_units.len()
|
||||
&& query_units[i + len] == name_units[j + len]
|
||||
{
|
||||
len += 1;
|
||||
}
|
||||
if len > max_match {
|
||||
max_match = len;
|
||||
}
|
||||
}
|
||||
}
|
||||
max_match as f64 / name_units.len() as f64
|
||||
};
|
||||
0.5 * score
|
||||
}
|
||||
|
||||
/// Items matching `query`: case- and whitespace-insensitive subsequence match
|
||||
/// (`isFuzzyMatch`) against the item's title or any keyword, stably sorted by
|
||||
/// descending [`substring_match_score`] against the title when `query` is non-empty.
|
||||
/// An empty query returns every item in menu order.
|
||||
pub fn filter_slash_items(query: &str) -> Vec<&'static SlashItem> {
|
||||
let needle: String = query
|
||||
.chars()
|
||||
.filter(|ch| !ch.is_whitespace())
|
||||
.flat_map(char::to_lowercase)
|
||||
.collect();
|
||||
SLASH_ITEMS
|
||||
let mut matched: Vec<&'static SlashItem> = SLASH_ITEMS
|
||||
.iter()
|
||||
.filter(|item| {
|
||||
if needle.is_empty() {
|
||||
return true;
|
||||
}
|
||||
let title: String = item
|
||||
.title
|
||||
.chars()
|
||||
.filter(|ch| !ch.is_whitespace())
|
||||
.flat_map(char::to_lowercase)
|
||||
.collect();
|
||||
title.contains(&needle)
|
||||
needle.is_empty()
|
||||
|| is_fuzzy_match(item.title, &needle)
|
||||
|| item
|
||||
.keywords
|
||||
.iter()
|
||||
.any(|keyword| keyword.starts_with(&needle))
|
||||
.any(|keyword| is_fuzzy_match(keyword, &needle))
|
||||
})
|
||||
.collect()
|
||||
.collect();
|
||||
if !needle.is_empty() {
|
||||
let search_str = query.trim_start();
|
||||
matched.sort_by(|a, b| {
|
||||
substring_match_score(b.title, search_str)
|
||||
.total_cmp(&substring_match_score(a.title, search_str))
|
||||
});
|
||||
}
|
||||
matched
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
|
||||
@@ -85,6 +85,19 @@ impl Overlays {
|
||||
}
|
||||
}
|
||||
|
||||
/// Open the formatting toolbar (if needed) and focus its inline link field.
|
||||
pub fn open_link_field(&mut self, selection: &SelectionFormat, now_ms: f64) {
|
||||
self.close_slash(now_ms);
|
||||
self.sync_toolbar(Some(selection), now_ms);
|
||||
if let Some(toolbar) = self.open_toolbar_mut()
|
||||
&& toolbar.link.is_none()
|
||||
{
|
||||
toolbar.link = Some(LinkBar::new(
|
||||
toolbar.selection.marks.link.clone().unwrap_or_default(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Put pasted text into the link field, over its selection. Returns whether the
|
||||
/// field is open.
|
||||
pub fn link_insert(&mut self, text: &str) -> bool {
|
||||
@@ -435,8 +448,7 @@ impl Overlays {
|
||||
effects.redraw = true;
|
||||
match key {
|
||||
// `Tab` and `Shift+Tab` step through the items like the arrows, and never
|
||||
// reach the block; `Enter` without a match closes the menu and does not split
|
||||
// the block.
|
||||
// reach the block.
|
||||
"down" | "up" | "tab" if count > 0 => {
|
||||
let back = key == "up" || (key == "tab" && shift);
|
||||
menu.selected = (menu.selected + if back { count - 1 } else { 1 }) % count;
|
||||
@@ -444,11 +456,16 @@ impl Overlays {
|
||||
}
|
||||
"tab" => {}
|
||||
"enter" if count > 0 => self.execute_slash(None, now_ms, &mut effects),
|
||||
// When triggered in-document with no matching items, `Enter`, `Up`, and `Down`
|
||||
// close the menu and pass through to the editor.
|
||||
"enter" | "up" | "down" if menu.query_in_document => {
|
||||
self.close_slash(now_ms);
|
||||
effects.handled = false;
|
||||
}
|
||||
"enter" | "escape" => {
|
||||
self.close_slash(now_ms);
|
||||
}
|
||||
// Text typed after the `/` in the document is the editor's to edit, and with
|
||||
// no match left the arrows are the document's again.
|
||||
// Text typed after the `/` in the document is the editor's to edit.
|
||||
_ if menu.query_in_document => {
|
||||
effects.handled = false;
|
||||
effects.redraw = false;
|
||||
|
||||
@@ -62,6 +62,7 @@ pub struct InlineMarkSet {
|
||||
pub strike: bool,
|
||||
pub code: bool,
|
||||
pub link: Option<String>,
|
||||
pub latex: Option<String>,
|
||||
pub reference: Option<InlineReference>,
|
||||
/// Text color as stored in the document (`var(--token)` or a hex color).
|
||||
pub color: Option<String>,
|
||||
@@ -96,6 +97,7 @@ impl InlineMarkSet {
|
||||
strike: enabled("strike"),
|
||||
code: enabled("code"),
|
||||
link: string_attr(attrs.get("link")),
|
||||
latex: string_attr(attrs.get("latex")),
|
||||
reference,
|
||||
color: string_attr(attrs.get("color")),
|
||||
background: string_attr(attrs.get("background")),
|
||||
@@ -179,6 +181,17 @@ impl RichParagraph {
|
||||
append(" ", &label, true);
|
||||
}
|
||||
}
|
||||
TextInsert::Text(s) if marks.latex.is_some() && s.bytes().all(|b| b == b' ') => {
|
||||
let tex = marks.latex.as_deref().unwrap_or("");
|
||||
let label = if tex.is_empty() {
|
||||
"Equation".to_string()
|
||||
} else {
|
||||
tex.replace(['\r', '\n'], " ")
|
||||
};
|
||||
for _ in s.bytes() {
|
||||
append(" ", &label, true);
|
||||
}
|
||||
}
|
||||
TextInsert::Text(s) => append(s, s, false),
|
||||
TextInsert::Embed(values) => {
|
||||
let objects = "\u{fffc}".repeat(values.len());
|
||||
|
||||
@@ -15,17 +15,18 @@ use ui::{
|
||||
|
||||
pub use ui_tokens::{
|
||||
DARK_THEME, FONT_CODE, FONT_SANS, IconDef, LIGHT_THEME, TYPOGRAPHY, ThemeMode, ThemeTokens,
|
||||
bundled_font_bytes, icon_by_name, icons, tokens,
|
||||
bundled_font_bytes, bundled_script_font_bytes, icon_by_name, icons, tokens,
|
||||
};
|
||||
|
||||
/// Registers the tracked repository fonts (`Inter` and `IBM Plex Mono`) into the active
|
||||
/// `TextSystem`.
|
||||
/// Registers the tracked repository fonts (`Inter`, `IBM Plex Mono`, `Noto Sans Arabic`,
|
||||
/// and `Noto Sans Hebrew`) into the active `TextSystem`.
|
||||
///
|
||||
/// Must be called before opening any window across macOS, Linux headless, and Web Wasm.
|
||||
pub fn register_bundled_fonts(cx: &App) -> anyhow::Result<()> {
|
||||
cx.text_system().add_fonts(
|
||||
bundled_font_bytes()
|
||||
.into_iter()
|
||||
.chain(bundled_script_font_bytes())
|
||||
.map(Cow::Borrowed)
|
||||
.collect(),
|
||||
)
|
||||
|
||||
@@ -599,6 +599,11 @@ mod tests {
|
||||
for ch in "`code`".chars() {
|
||||
s.type_text(&ch.to_string())?;
|
||||
}
|
||||
assert_eq!(
|
||||
s.doc_json()?["blocks"]["p0"]["prop:text"],
|
||||
serde_json::json!([{"insert":"`code`"}])
|
||||
);
|
||||
s.key("enter", false, false);
|
||||
assert_eq!(
|
||||
s.doc_json()?["blocks"]["p0"]["prop:text"],
|
||||
serde_json::json!([{"insert":"code","attributes":{"code":true}}])
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
use blocksuite_playground_doc::{
|
||||
DocResult,
|
||||
read::BlockNode,
|
||||
schema::{ListType, ParagraphType},
|
||||
};
|
||||
use ui::{Context, KeyDownEvent, Window};
|
||||
|
||||
use super::*;
|
||||
use crate::overlays::SlashCommand;
|
||||
|
||||
pub(super) fn conversion_shortcut(key: &str, alt: bool, shift: bool) -> Option<SlashCommand> {
|
||||
if alt && !shift {
|
||||
return match key {
|
||||
"0" => Some(SlashCommand::Paragraph(ParagraphType::Text)),
|
||||
"1" => Some(SlashCommand::Paragraph(ParagraphType::H1)),
|
||||
"2" => Some(SlashCommand::Paragraph(ParagraphType::H2)),
|
||||
"3" => Some(SlashCommand::Paragraph(ParagraphType::H3)),
|
||||
"4" => Some(SlashCommand::Paragraph(ParagraphType::H4)),
|
||||
"5" => Some(SlashCommand::Paragraph(ParagraphType::H5)),
|
||||
"6" => Some(SlashCommand::Paragraph(ParagraphType::H6)),
|
||||
"8" => Some(SlashCommand::List(ListType::Bulleted)),
|
||||
"9" => Some(SlashCommand::List(ListType::Numbered)),
|
||||
"c" => Some(SlashCommand::Code),
|
||||
"d" => Some(SlashCommand::Divider),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
if shift && !alt {
|
||||
return match key {
|
||||
"0" | ")" => Some(SlashCommand::Paragraph(ParagraphType::Text)),
|
||||
"1" | "!" => Some(SlashCommand::Paragraph(ParagraphType::H1)),
|
||||
"2" | "@" => Some(SlashCommand::Paragraph(ParagraphType::H2)),
|
||||
"3" | "#" => Some(SlashCommand::Paragraph(ParagraphType::H3)),
|
||||
"4" | "$" => Some(SlashCommand::Paragraph(ParagraphType::H4)),
|
||||
"5" | "%" => Some(SlashCommand::Paragraph(ParagraphType::H5)),
|
||||
"6" | "^" => Some(SlashCommand::Paragraph(ParagraphType::H6)),
|
||||
"8" | "*" => Some(SlashCommand::List(ListType::Bulleted)),
|
||||
"9" | "(" => Some(SlashCommand::List(ListType::Numbered)),
|
||||
"d" => Some(SlashCommand::Divider),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
impl PlaygroundView {
|
||||
pub(super) fn block_selection_slice(&self) -> Option<crate::clipboard::Slice> {
|
||||
if self.editor.block_selection.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let snapshot = self.page_snapshot()?;
|
||||
let page = self.page()?;
|
||||
let root = snapshot.root.as_ref()?;
|
||||
let ids: BTreeSet<&str> = self
|
||||
.editor
|
||||
.block_selection
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.collect();
|
||||
let mut selected = BTreeMap::new();
|
||||
for node in page_content_roots(root).flat_map(BlockNode::walk) {
|
||||
if !ids.contains(node.id.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let delta = if text_content(node).is_some() {
|
||||
page.read_editable_text(&node.id).ok()?.0.delta
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
selected.insert(
|
||||
node.id.clone(),
|
||||
crate::clipboard::SliceBlock::from_node(
|
||||
node,
|
||||
page.export_slice_props(&node.id).ok()?,
|
||||
&delta,
|
||||
),
|
||||
);
|
||||
}
|
||||
let mut blocks = Vec::new();
|
||||
for child in page_content_roots(root) {
|
||||
crate::clipboard::SliceBlock::keep_selected(child, &mut selected, &mut blocks);
|
||||
}
|
||||
(!blocks.is_empty()).then(|| {
|
||||
crate::clipboard::Slice::new(
|
||||
self.state.workspace.room(),
|
||||
self.page_id.as_deref().unwrap_or(""),
|
||||
blocks,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn delete_selected_blocks(
|
||||
&mut self,
|
||||
w: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> DocResult {
|
||||
if self.editor.block_selection.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(snapshot) = self.snapshot.clone() else {
|
||||
return Ok(());
|
||||
};
|
||||
let Some(root) = snapshot.root.as_ref() else {
|
||||
return Ok(());
|
||||
};
|
||||
let selected_set: BTreeSet<String> = self.editor.block_selection.iter().cloned().collect();
|
||||
// Only remove top-level selected blocks (skip descendants whose ancestor is also selected).
|
||||
let mut top_selected: Vec<(String, String)> = Vec::new();
|
||||
for id in &self.editor.block_selection {
|
||||
let mut cur = id.as_str();
|
||||
let mut ancestor_selected = false;
|
||||
while let Some((parent, _)) = parent_of(&snapshot, cur) {
|
||||
if selected_set.contains(&parent.id) {
|
||||
ancestor_selected = true;
|
||||
break;
|
||||
}
|
||||
cur = &parent.id;
|
||||
}
|
||||
if !ancestor_selected && let Some((parent, _)) = parent_of(&snapshot, id) {
|
||||
top_selected.push((parent.id.clone(), id.clone()));
|
||||
}
|
||||
}
|
||||
let first_parent_id = top_selected
|
||||
.first()
|
||||
.map(|(parent_id, _)| parent_id.clone())
|
||||
.or_else(|| {
|
||||
root.children
|
||||
.iter()
|
||||
.find(|n| n.is_page_visible_note())
|
||||
.map(|n| n.id.clone())
|
||||
});
|
||||
let mut deleted_subtree_ids: BTreeSet<String> = BTreeSet::new();
|
||||
for (_, id) in &top_selected {
|
||||
if let Some(node) = snapshot.block(id) {
|
||||
for desc in node.walk() {
|
||||
deleted_subtree_ids.insert(desc.id.clone());
|
||||
}
|
||||
} else {
|
||||
deleted_subtree_ids.insert(id.clone());
|
||||
}
|
||||
}
|
||||
let remaining_editable = self.flow_layout().and_then(|layout| {
|
||||
layout
|
||||
.blocks
|
||||
.iter()
|
||||
.find(|b| {
|
||||
b.editable()
|
||||
&& !matches!(b.body.kind, block_flow::FlowKind::Title)
|
||||
&& !deleted_subtree_ids.contains(&b.block_id)
|
||||
})
|
||||
.map(|b| b.block_id.clone())
|
||||
});
|
||||
let fallback_id = self.fresh_block_id();
|
||||
let now = self.now_ms(cx) as u64;
|
||||
let page = self.page_mut()?;
|
||||
page.stop_capturing()?;
|
||||
let commit = page.structural_edit(now, |page| {
|
||||
for (parent_id, id) in &top_selected {
|
||||
let _ = page.delete_block_subtree(parent_id, id, now);
|
||||
}
|
||||
if remaining_editable.is_none()
|
||||
&& let Some(parent_id) = &first_parent_id
|
||||
{
|
||||
page.add_block(&fallback_id, paragraph(), Some(parent_id), Some(0), now)?;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
self.editor.block_selection.clear();
|
||||
let next_focus = remaining_editable.unwrap_or(fallback_id);
|
||||
self.editor.selection = Some(DocumentSelection::caret(DocPoint::new(next_focus, 0)));
|
||||
self.editor.last_typing = None;
|
||||
self.did_edit(commit, None, w, cx);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn handle_block_selection_key(
|
||||
&mut self,
|
||||
e: &KeyDownEvent,
|
||||
w: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> DocResult<bool> {
|
||||
if self.editor.block_selection.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
let m = e.keystroke.modifiers;
|
||||
let cmd = m.secondary(cx);
|
||||
let key = e.keystroke.key.as_str();
|
||||
match key {
|
||||
"escape" => {
|
||||
self.editor.block_selection.clear();
|
||||
cx.notify();
|
||||
Ok(true)
|
||||
}
|
||||
"backspace" | "delete" => {
|
||||
self.delete_selected_blocks(w, cx)?;
|
||||
Ok(true)
|
||||
}
|
||||
"enter" => {
|
||||
let last_id = self.editor.block_selection.last().cloned();
|
||||
if let Some(last_id) = last_id
|
||||
&& let Some(snapshot) = self.snapshot.clone()
|
||||
&& let Some((parent, slot)) = parent_of(&snapshot, &last_id)
|
||||
{
|
||||
let new_id = self.fresh_block_id();
|
||||
let now = self.now_ms(cx) as u64;
|
||||
let page = self.page_mut()?;
|
||||
page.stop_capturing()?;
|
||||
let commit = page.add_block(
|
||||
&new_id,
|
||||
paragraph(),
|
||||
Some(&parent.id),
|
||||
Some(slot as u64 + 1),
|
||||
now,
|
||||
)?;
|
||||
self.editor.block_selection.clear();
|
||||
self.editor.selection =
|
||||
Some(DocumentSelection::caret(DocPoint::new(new_id, 0)));
|
||||
self.editor.last_typing = None;
|
||||
self.did_edit(commit, None, w, cx);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
"c" | "x" if cmd => {
|
||||
if let Some(slice) = self.block_selection_slice() {
|
||||
crate::clipboard::write_slice(&slice, cx);
|
||||
if key == "x" {
|
||||
self.delete_selected_blocks(w, cx)?;
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
"a" if cmd => {
|
||||
if let Some(layout) = self.flow_layout() {
|
||||
self.editor.block_selection = layout
|
||||
.blocks
|
||||
.iter()
|
||||
.filter(|b| !matches!(b.body.kind, block_flow::FlowKind::Title))
|
||||
.map(|b| b.block_id.clone())
|
||||
.collect();
|
||||
cx.notify();
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
"z" if cmd => {
|
||||
self.editor.block_selection.clear();
|
||||
self.history(m.shift, w, cx)?;
|
||||
Ok(true)
|
||||
}
|
||||
"y" if cmd => {
|
||||
self.editor.block_selection.clear();
|
||||
self.history(true, w, cx)?;
|
||||
Ok(true)
|
||||
}
|
||||
_ => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn select_all_blocks(&mut self, w: &mut Window, cx: &mut Context<Self>) {
|
||||
if let Some(layout) = self.flow_layout() {
|
||||
let ids: Vec<String> = layout
|
||||
.blocks
|
||||
.iter()
|
||||
.filter(|b| !matches!(b.body.kind, block_flow::FlowKind::Title))
|
||||
.map(|b| b.block_id.clone())
|
||||
.collect();
|
||||
if !ids.is_empty() {
|
||||
self.editor.selection = None;
|
||||
self.editor.block_selection = ids;
|
||||
self.editor.pending_marks.clear();
|
||||
self.announce_selection(cx);
|
||||
w.notify_text_selection_changed(&self.editor_focus);
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn open_link_bar_shortcut(&mut self, w: &mut Window, cx: &mut Context<Self>) {
|
||||
let width = page_geometry(f32::from(w.viewport_size().width)).column_width;
|
||||
let Some(layout) = self.ensure_layout(width, w) else {
|
||||
return;
|
||||
};
|
||||
let Some(selection_format) = self.selection_format(&layout) else {
|
||||
return;
|
||||
};
|
||||
let now_ms = self.now_ms(cx);
|
||||
let before = self.link_input_state();
|
||||
self.overlays.open_link_field(&selection_format, now_ms);
|
||||
self.sync_link_input(before, w, cx);
|
||||
}
|
||||
}
|
||||
@@ -240,9 +240,9 @@ impl PlaygroundView {
|
||||
} as u64;
|
||||
if offset <= cursor {
|
||||
if matches!(insert, TextInsert::Embed(_))
|
||||
|| format
|
||||
.as_ref()
|
||||
.is_some_and(|attrs| attrs.contains_key("reference"))
|
||||
|| format.as_ref().is_some_and(|attrs| {
|
||||
attrs.contains_key("reference") || attrs.contains_key("latex")
|
||||
})
|
||||
{
|
||||
break;
|
||||
}
|
||||
@@ -403,17 +403,23 @@ impl PlaygroundView {
|
||||
}
|
||||
let before = sel.snapshot(self.page_mut()?)?;
|
||||
let mut focus = sel.focus.clone();
|
||||
let demote = matches!(
|
||||
node.content,
|
||||
BlockContent::List { .. }
|
||||
| BlockContent::Paragraph {
|
||||
kind: ParagraphType::Quote,
|
||||
..
|
||||
}
|
||||
) && ((text.is_empty() && key == "enter") || (backwards && offset == 0))
|
||||
|| (backwards
|
||||
&& offset == 0
|
||||
&& matches!(node.content,BlockContent::Paragraph {kind,..} if kind!=ParagraphType::Text));
|
||||
let nested_empty_list_enter = key == "enter"
|
||||
&& text.is_empty()
|
||||
&& matches!(node.content, BlockContent::List { .. })
|
||||
&& parent_of(&snapshot, &id)
|
||||
.is_some_and(|(parent, _)| matches!(parent.content, BlockContent::List { .. }));
|
||||
let demote = !nested_empty_list_enter
|
||||
&& (matches!(
|
||||
node.content,
|
||||
BlockContent::List { .. }
|
||||
| BlockContent::Paragraph {
|
||||
kind: ParagraphType::Quote,
|
||||
..
|
||||
}
|
||||
) && ((text.is_empty() && key == "enter") || (backwards && offset == 0))
|
||||
|| (backwards
|
||||
&& offset == 0
|
||||
&& matches!(node.content,BlockContent::Paragraph {kind,..} if kind!=ParagraphType::Text)));
|
||||
let last_nested = backwards
|
||||
&& offset == 0
|
||||
&& !code
|
||||
@@ -423,7 +429,7 @@ impl PlaygroundView {
|
||||
BlockContent::List { .. } | BlockContent::Paragraph { .. }
|
||||
) && pos + 1 == parent.children.len()
|
||||
});
|
||||
let commit = if last_nested {
|
||||
let commit = if last_nested || nested_empty_list_enter {
|
||||
self.page_mut()?.dedent_block(&id, now)?
|
||||
} else if demote {
|
||||
let fresh = self.fresh_block_id();
|
||||
@@ -472,10 +478,14 @@ impl PlaygroundView {
|
||||
}
|
||||
}
|
||||
let spec = match &node.content {
|
||||
BlockContent::Paragraph { kind, .. } if offset < n => BlockSpec::Paragraph {
|
||||
paragraph_type: *kind,
|
||||
text: String::new(),
|
||||
},
|
||||
BlockContent::Paragraph { kind, .. }
|
||||
if offset < n || *kind == ParagraphType::Quote =>
|
||||
{
|
||||
BlockSpec::Paragraph {
|
||||
paragraph_type: *kind,
|
||||
text: String::new(),
|
||||
}
|
||||
}
|
||||
BlockContent::List { kind, order, .. } => list(
|
||||
*kind,
|
||||
false,
|
||||
@@ -632,10 +642,57 @@ impl PlaygroundView {
|
||||
if self.overlays.link_field().is_some_and(LinkBar::composing) {
|
||||
return;
|
||||
}
|
||||
// Active whole-block selection intercepts navigation/edit/clipboard keys first.
|
||||
match self.handle_block_selection_key(e, w, cx) {
|
||||
Ok(true) => {
|
||||
w.prevent_default();
|
||||
cx.stop_propagation();
|
||||
return;
|
||||
}
|
||||
Ok(false) => {}
|
||||
Err(err) => {
|
||||
eprintln!("block selection command: {err}");
|
||||
w.prevent_default();
|
||||
cx.stop_propagation();
|
||||
return;
|
||||
}
|
||||
}
|
||||
let m = e.keystroke.modifiers;
|
||||
let cmd = m.secondary(cx);
|
||||
let key = e.keystroke.key.as_str();
|
||||
if cmd
|
||||
&& let Some(command) = block_selection::conversion_shortcut(key, m.alt, m.shift)
|
||||
&& let Some(block_id) = self
|
||||
.editor
|
||||
.selection
|
||||
.as_ref()
|
||||
.map(|sel| sel.focus.block_id.clone())
|
||||
{
|
||||
if let Err(err) = self.run_slash_command(&block_id, command, false, w, cx) {
|
||||
eprintln!("conversion shortcut {key}: {err}");
|
||||
}
|
||||
w.prevent_default();
|
||||
cx.stop_propagation();
|
||||
return;
|
||||
}
|
||||
let result = match key {
|
||||
"escape" => {
|
||||
if let Some(sel) = self.editor.selection.as_ref()
|
||||
&& let Some(layout) = self.flow_layout()
|
||||
&& layout
|
||||
.block(&sel.focus.block_id)
|
||||
.is_some_and(|b| !matches!(b.body.kind, block_flow::FlowKind::Title))
|
||||
{
|
||||
let block_id = sel.focus.block_id.clone();
|
||||
self.editor.selection = None;
|
||||
self.editor.block_selection = vec![block_id];
|
||||
self.editor.pending_marks.clear();
|
||||
self.announce_selection(cx);
|
||||
w.notify_text_selection_changed(&self.editor_focus);
|
||||
cx.notify();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
"left" | "right" | "up" | "down" | "home" | "end" => {
|
||||
self.navigate(
|
||||
key,
|
||||
@@ -649,30 +706,29 @@ impl PlaygroundView {
|
||||
}
|
||||
"enter" | "backspace" | "delete" | "tab" => self.edit_key(key, m.shift, w, cx),
|
||||
"a" if cmd => {
|
||||
let width = page_geometry(f32::from(w.viewport_size().width)).column_width;
|
||||
if let Some(sel) = self.editor.selection.clone()
|
||||
&& let Some(layout) = self.flow_layout()
|
||||
&& let Some(layout) = self.ensure_layout(width, w)
|
||||
&& let Some(block) = layout.block(&sel.focus.block_id)
|
||||
{
|
||||
let mut anchor = DocPoint::new(&block.block_id, 0);
|
||||
let mut focus = DocPoint::new(
|
||||
&block.block_id,
|
||||
block.body.plain.encode_utf16().count() as u64,
|
||||
);
|
||||
if (sel.anchor == anchor && sel.focus == focus
|
||||
|| sel.focus == anchor && sel.anchor == focus)
|
||||
&& let Some(first) = layout.blocks.iter().find(|b| b.editable())
|
||||
&& let Some(last) = layout.blocks.iter().rfind(|b| b.editable())
|
||||
{
|
||||
anchor = DocPoint::new(&first.block_id, 0);
|
||||
focus = DocPoint::new(
|
||||
&last.block_id,
|
||||
last.body.plain.encode_utf16().count() as u64,
|
||||
);
|
||||
let full_len = block.body.plain.encode_utf16().count() as u64;
|
||||
let anchor = DocPoint::new(&block.block_id, 0);
|
||||
let focus = DocPoint::new(&block.block_id, full_len);
|
||||
let already_full_block = full_len == 0
|
||||
|| (sel.anchor == anchor && sel.focus == focus)
|
||||
|| (sel.focus == anchor && sel.anchor == focus);
|
||||
if already_full_block {
|
||||
self.select_all_blocks(w, cx);
|
||||
} else {
|
||||
self.change_selection(DocumentSelection { anchor, focus }, w, cx);
|
||||
}
|
||||
self.change_selection(DocumentSelection { anchor, focus }, w, cx);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
"k" if cmd && !m.alt && !m.shift => {
|
||||
self.open_link_bar_shortcut(w, cx);
|
||||
Ok(())
|
||||
}
|
||||
"c" | "x" if cmd => {
|
||||
if let Some(slice) = self.clipboard_slice() {
|
||||
crate::clipboard::write_slice(&slice, cx);
|
||||
|
||||
@@ -3,11 +3,10 @@ use std::ops::Range;
|
||||
use blocksuite_playground_doc::{
|
||||
DocError, DocResult,
|
||||
read::{BlockNode, RichText},
|
||||
schema::{BlockSpec, ParagraphType},
|
||||
session::split_delta,
|
||||
};
|
||||
use ui::{AnyElement, Bounds, Pixels, div, size};
|
||||
use y_octo::{Any, TextAttributes, TextDeltaOp, TextInsert};
|
||||
use y_octo::{Any, TextDeltaOp, TextInsert};
|
||||
|
||||
use super::*;
|
||||
use crate::block_flow::{FlowBlock, FlowRect, PAGE_SURFACE_ID, PageViewport, ScrolledCode};
|
||||
@@ -226,6 +225,33 @@ impl PlaygroundView {
|
||||
palette: &Palette,
|
||||
) -> Vec<AnyElement> {
|
||||
let mut el = Vec::new();
|
||||
if !self.editor.block_selection.is_empty() {
|
||||
let mut first_block = true;
|
||||
for block_id in &self.editor.block_selection {
|
||||
let Some(block) = layout.block(block_id) else {
|
||||
continue;
|
||||
};
|
||||
let r = block.rect();
|
||||
if r.bottom() < v.scroll_y || r.y > v.scroll_y + v.height {
|
||||
continue;
|
||||
}
|
||||
let mut d = div()
|
||||
.absolute()
|
||||
.left(px(v.column_x + r.x))
|
||||
.top(px(r.y - v.scroll_y))
|
||||
.w(px(r.w.max(1.0)))
|
||||
.h(px(r.h))
|
||||
.rounded(px(4.0))
|
||||
.bg(palette.brand.opacity(0.14));
|
||||
if r.y >= v.scroll_y
|
||||
&& r.bottom() <= v.scroll_y + v.height
|
||||
&& std::mem::take(&mut first_block)
|
||||
{
|
||||
d = d.snapshot("page.block_selection", Some(PAGE_SURFACE_ID));
|
||||
}
|
||||
el.push(d.into_any_element());
|
||||
}
|
||||
}
|
||||
let scrolled = self.overlays.scrolled_code(layout);
|
||||
let mut first_box = true;
|
||||
let mut draw = |mut r: FlowRect, color: ui::Hsla, caret: bool| {
|
||||
@@ -287,6 +313,7 @@ impl PlaygroundView {
|
||||
}
|
||||
pub(super) fn begin_input(&mut self) {
|
||||
if self.editor.selection.is_none()
|
||||
&& self.editor.block_selection.is_empty()
|
||||
&& let Some(root) = self.page_snapshot().and_then(|s| s.root.as_ref())
|
||||
{
|
||||
self.editor.selection = Some(DocumentSelection::caret(DocPoint::new(&root.id, 0)));
|
||||
@@ -315,142 +342,6 @@ impl PlaygroundView {
|
||||
sel.clone()
|
||||
})
|
||||
}
|
||||
pub(super) fn apply_markdown(
|
||||
&mut self,
|
||||
sel: &DocumentSelection,
|
||||
typed: &str,
|
||||
w: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> DocResult<bool> {
|
||||
if !sel.empty() || self.editor.preedit.is_some() || typed.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(snapshot) = self.snapshot.as_ref().cloned() else {
|
||||
return Ok(false);
|
||||
};
|
||||
let id = &sel.focus.block_id;
|
||||
let Some(node) = snapshot.block(id) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let BlockContent::Paragraph {
|
||||
kind, text: rich, ..
|
||||
} = &node.content
|
||||
else {
|
||||
return Ok(false);
|
||||
};
|
||||
if *kind == ParagraphType::Quote {
|
||||
return Ok(false);
|
||||
}
|
||||
let offset = sel.focus.offset();
|
||||
let index = TextBiIndex::new(&rich.plain);
|
||||
let byte = index.utf16_to_utf8_clamped(offset);
|
||||
let mut prefix = rich.plain[..byte].to_owned();
|
||||
prefix.push_str(typed);
|
||||
let now = self.now_ms(cx) as u64;
|
||||
if let Some(spec) = markdown_block(&prefix) {
|
||||
let Some((parent, index)) = parent_of(&snapshot, id) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let replacement = self.fresh_block_id();
|
||||
let trailing = self.fresh_block_id();
|
||||
let divider = matches!(spec, BlockSpec::Divider);
|
||||
let code = matches!(spec, BlockSpec::Code { .. });
|
||||
let focus = if divider || spec.flavour() == node.flavour {
|
||||
id
|
||||
} else {
|
||||
&replacement
|
||||
};
|
||||
let page = self.page_mut()?;
|
||||
let before = sel.snapshot(page)?;
|
||||
let commit = page.structural_edit(now, |page| {
|
||||
if offset > 0 {
|
||||
page.remove_text(id, "prop:text", 0, offset, now)?;
|
||||
}
|
||||
if divider || code {
|
||||
page.add_block(
|
||||
&replacement,
|
||||
spec,
|
||||
Some(&parent.id),
|
||||
Some(index as u64),
|
||||
now,
|
||||
)?;
|
||||
if code {
|
||||
let remaining = page.read_editable_text(id)?.0;
|
||||
if !remaining.is_empty() {
|
||||
page.add_block(
|
||||
&trailing,
|
||||
paragraph(),
|
||||
Some(&parent.id),
|
||||
Some(index as u64 + 1),
|
||||
now,
|
||||
)?;
|
||||
page.apply_text_delta(&trailing, "prop:text", &remaining.delta, now)?;
|
||||
}
|
||||
page.remove_lifting_children(id, now)?;
|
||||
}
|
||||
} else {
|
||||
page.convert_markdown_block(id, &replacement, spec, now)?;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
if commit.is_some() {
|
||||
page.set_undo_selection_snapshot(before)?;
|
||||
}
|
||||
self.editor.selection = Some(DocumentSelection::caret(DocPoint::new(focus, 0)));
|
||||
self.editor.last_typing = None;
|
||||
self.did_edit(commit, None, w, cx);
|
||||
return Ok(true);
|
||||
}
|
||||
if let Some(body) = prefix.strip_suffix('`')
|
||||
&& let Some(open) = body.rfind('`')
|
||||
&& !body[open + 1..].is_empty()
|
||||
&& !body[open + 1..].contains('\n')
|
||||
{
|
||||
let from = body[..open].encode_utf16().count() as u64;
|
||||
// Preserve existing inline marks in the text between the delimiters.
|
||||
let existing = offset.saturating_sub(from + 1);
|
||||
let mut delta = vec![TextDeltaOp::Retain {
|
||||
retain: from,
|
||||
format: None,
|
||||
}];
|
||||
if from < offset {
|
||||
delta.push(TextDeltaOp::Delete { delete: 1 });
|
||||
}
|
||||
let attrs = Some(TextAttributes::from([("code".into(), Any::True)]));
|
||||
if existing > 0 {
|
||||
delta.push(TextDeltaOp::Retain {
|
||||
retain: existing,
|
||||
format: attrs.clone(),
|
||||
});
|
||||
}
|
||||
let content = &body[open + 1..];
|
||||
let ix = TextBiIndex::new(content);
|
||||
let new = &content[ix.utf16_to_utf8_clamped(existing)..];
|
||||
if !new.is_empty() {
|
||||
delta.push(TextDeltaOp::Insert {
|
||||
insert: TextInsert::Text(new.into()),
|
||||
format: attrs,
|
||||
});
|
||||
}
|
||||
let page = self.page_mut()?;
|
||||
let before = sel.snapshot(page)?;
|
||||
page.stop_capturing()?;
|
||||
let commit = page.apply_text_delta(id, "prop:text", &delta, now)?;
|
||||
if commit.is_some() {
|
||||
page.set_undo_selection_snapshot(before)?;
|
||||
}
|
||||
page.stop_capturing()?;
|
||||
self.editor.selection = Some(DocumentSelection::caret(DocPoint::new(
|
||||
id,
|
||||
from + ix.utf16_len(),
|
||||
)));
|
||||
self.editor.last_typing = None;
|
||||
self.did_edit(commit, Some(id), w, cx);
|
||||
return Ok(true);
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
pub(super) fn replace_selection(
|
||||
&mut self,
|
||||
sel: DocumentSelection,
|
||||
@@ -504,40 +395,58 @@ impl PlaygroundView {
|
||||
marks.remove(key);
|
||||
}
|
||||
}
|
||||
let is_rich_block = matches!(
|
||||
layout.blocks[a].body.kind,
|
||||
block_flow::FlowKind::Paragraph(_) | block_flow::FlowKind::List(_)
|
||||
);
|
||||
let outside_code = marks.get("code") != Some(&Any::True);
|
||||
// A `/` typed at a caret in paragraph or list text, outside inline code, opens
|
||||
// the slash menu at that character.
|
||||
let slash = (text == "/"
|
||||
&& sel.empty()
|
||||
&& matches!(
|
||||
layout.blocks[a].body.kind,
|
||||
block_flow::FlowKind::Paragraph(_) | block_flow::FlowKind::List(_)
|
||||
)
|
||||
&& marks.get("code") != Some(&Any::True))
|
||||
.then(|| (id.clone(), start.offset()));
|
||||
// An `@` typed at the start of a block or after whitespace in paragraph or list text,
|
||||
// outside inline code, opens the linked-document menu at that character.
|
||||
let linked_doc = (text == "@"
|
||||
&& sel.empty()
|
||||
&& matches!(
|
||||
layout.blocks[a].body.kind,
|
||||
block_flow::FlowKind::Paragraph(_) | block_flow::FlowKind::List(_)
|
||||
)
|
||||
&& marks.get("code") != Some(&Any::True)
|
||||
&& {
|
||||
let before_byte = TextBiIndex::new(layout.blocks[a].body.plain.as_str())
|
||||
.utf16_to_utf8_clamped(start.offset());
|
||||
layout.blocks[a].body.plain[..before_byte]
|
||||
.chars()
|
||||
.next_back()
|
||||
.is_none_or(char::is_whitespace)
|
||||
})
|
||||
.then(|| (id.clone(), start.offset()));
|
||||
let slash = (text == "/" && sel.empty() && is_rich_block && outside_code)
|
||||
.then(|| (id.clone(), start.offset()));
|
||||
|
||||
// Double-bracket `[[` or `【【` trigger converts to `@` and opens the linked-doc menu.
|
||||
let double_bracket_convert: Option<(u64, u64)> =
|
||||
if sel.empty() && is_rich_block && outside_code {
|
||||
if text == "[[" || text == "【【" {
|
||||
Some((start.offset(), 0))
|
||||
} else if text == "[" || text == "【" {
|
||||
let plain = layout.blocks[a].body.plain.as_str();
|
||||
let before_byte = TextBiIndex::new(plain).utf16_to_utf8_clamped(start.offset());
|
||||
let expected = if text == "[" { '[' } else { '【' };
|
||||
plain[..before_byte]
|
||||
.chars()
|
||||
.next_back()
|
||||
.filter(|&ch| ch == expected)
|
||||
.map(|ch| {
|
||||
let u16_len = ch.len_utf16() as u64;
|
||||
(start.offset().saturating_sub(u16_len), u16_len)
|
||||
})
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let (insert_text, effective_start, extra_delete, linked_doc) =
|
||||
if let Some((at_offset, prev_del)) = double_bracket_convert {
|
||||
("@", at_offset, prev_del, Some((id.clone(), at_offset)))
|
||||
} else {
|
||||
// An `@` typed anywhere in paragraph or list text, outside inline code,
|
||||
// opens the linked-document menu at that character.
|
||||
let at_trigger = (text == "@" && sel.empty() && is_rich_block && outside_code)
|
||||
.then(|| (id.clone(), start.offset()));
|
||||
(text, start.offset(), 0, at_trigger)
|
||||
};
|
||||
|
||||
let group = self
|
||||
.editor
|
||||
.last_typing
|
||||
.is_some_and(|t| now.saturating_sub(t) < 500)
|
||||
&& sel.empty()
|
||||
&& !cross;
|
||||
&& !cross
|
||||
&& extra_delete == 0;
|
||||
let blocks = RangeBlocks::between(
|
||||
self.page_snapshot()
|
||||
.ok_or_else(|| DocError::InvalidState("missing page".into()))?,
|
||||
@@ -550,18 +459,25 @@ impl PlaygroundView {
|
||||
if !group {
|
||||
page.stop_capturing()?;
|
||||
}
|
||||
let mut delta = vec![TextDeltaOp::Retain {
|
||||
retain: start.offset(),
|
||||
format: None,
|
||||
}];
|
||||
if !cross && end.offset() > start.offset() {
|
||||
let mut delta = Vec::new();
|
||||
if effective_start > 0 {
|
||||
delta.push(TextDeltaOp::Retain {
|
||||
retain: effective_start,
|
||||
format: None,
|
||||
});
|
||||
}
|
||||
if extra_delete > 0 {
|
||||
delta.push(TextDeltaOp::Delete {
|
||||
delete: extra_delete,
|
||||
});
|
||||
} else if !cross && end.offset() > start.offset() {
|
||||
delta.push(TextDeltaOp::Delete {
|
||||
delete: end.offset() - start.offset(),
|
||||
});
|
||||
}
|
||||
if !text.is_empty() {
|
||||
if !insert_text.is_empty() {
|
||||
delta.push(TextDeltaOp::Insert {
|
||||
insert: TextInsert::Text(text.into()),
|
||||
insert: TextInsert::Text(insert_text.into()),
|
||||
format: (!marks.is_empty()).then_some(marks),
|
||||
});
|
||||
}
|
||||
@@ -574,7 +490,7 @@ impl PlaygroundView {
|
||||
&blocks.survivors,
|
||||
now,
|
||||
)?;
|
||||
if !text.is_empty() {
|
||||
if !insert_text.is_empty() {
|
||||
page.apply_text_delta(&id, key, &delta, now)?;
|
||||
}
|
||||
Ok(())
|
||||
@@ -587,8 +503,9 @@ impl PlaygroundView {
|
||||
}
|
||||
self.editor.selection = Some(DocumentSelection::caret(DocPoint::new(
|
||||
&id,
|
||||
start.offset() + text.encode_utf16().count() as u64,
|
||||
effective_start + insert_text.encode_utf16().count() as u64,
|
||||
)));
|
||||
self.editor.block_selection.clear();
|
||||
self.editor.last_typing = (!cross).then_some(now);
|
||||
self.editor.preedit = None;
|
||||
self.did_edit(commit, (!cross).then_some(&id), w, cx);
|
||||
|
||||
@@ -377,60 +377,3 @@ pub(super) fn list(kind: ListType, checked: bool, order: Option<i32>) -> BlockSp
|
||||
order,
|
||||
}
|
||||
}
|
||||
pub(super) fn markdown_block(input: &str) -> Option<BlockSpec> {
|
||||
let spec = match input {
|
||||
"# " => "h1",
|
||||
"## " => "h2",
|
||||
"### " => "h3",
|
||||
"#### " => "h4",
|
||||
"##### " => "h5",
|
||||
"###### " => "h6",
|
||||
"> " => "quote",
|
||||
"- " | "* " => return Some(list(ListType::Bulleted, false, None)),
|
||||
s if s.ends_with(". ") => {
|
||||
let digits = s.strip_suffix(". ")?;
|
||||
if !digits.bytes().all(|c| c.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
let order = digits.parse::<i32>().ok().filter(|n| *n >= 0)?;
|
||||
return Some(list(ListType::Numbered, false, Some(order)));
|
||||
}
|
||||
"[] " | "[ ] " => return Some(list(ListType::Todo, false, None)),
|
||||
"[x] " => return Some(list(ListType::Todo, true, None)),
|
||||
s if s.strip_suffix(char::is_whitespace).is_some_and(|run| {
|
||||
run.len() >= 3
|
||||
&& matches!(run.as_bytes()[0], b'-' | b'*' | b'_')
|
||||
&& run.bytes().all(|b| b == run.as_bytes()[0])
|
||||
}) =>
|
||||
{
|
||||
return Some(BlockSpec::Divider);
|
||||
}
|
||||
s if s.starts_with("```") && s.ends_with([' ', '\n']) => {
|
||||
let language = &s[3..s.len() - 1];
|
||||
if !language
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '+' | '#' | '.' | '-'))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
return Some(BlockSpec::Code {
|
||||
text: String::new(),
|
||||
language: (!language.is_empty()).then(|| language.into()),
|
||||
caption: String::new(),
|
||||
});
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
Some(BlockSpec::Paragraph {
|
||||
paragraph_type: match spec {
|
||||
"h1" => ParagraphType::H1,
|
||||
"h2" => ParagraphType::H2,
|
||||
"h3" => ParagraphType::H3,
|
||||
"h4" => ParagraphType::H4,
|
||||
"h5" => ParagraphType::H5,
|
||||
"h6" => ParagraphType::H6,
|
||||
_ => ParagraphType::Quote,
|
||||
},
|
||||
text: String::new(),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,442 @@
|
||||
use blocksuite_playground_doc::{
|
||||
DocResult,
|
||||
read::BlockContent,
|
||||
schema::{BlockSpec, ListType, ParagraphType},
|
||||
};
|
||||
use ui::{Context, Window};
|
||||
use y_octo::{Any, TextAttributes, TextDeltaOp, TextInsert};
|
||||
|
||||
use super::*;
|
||||
use crate::rich_text::TextBiIndex;
|
||||
|
||||
pub(super) fn markdown_block(input: &str) -> Option<BlockSpec> {
|
||||
let trimmed = input.strip_suffix([' ', '\n'])?;
|
||||
let spec = match trimmed {
|
||||
"#" => ParagraphType::H1,
|
||||
"##" => ParagraphType::H2,
|
||||
"###" => ParagraphType::H3,
|
||||
"####" => ParagraphType::H4,
|
||||
"#####" => ParagraphType::H5,
|
||||
"######" => ParagraphType::H6,
|
||||
">" => ParagraphType::Quote,
|
||||
"-" | "*" | "+" => return Some(list(ListType::Bulleted, false, None)),
|
||||
s if s.ends_with('.') => {
|
||||
let digits = s.strip_suffix('.')?;
|
||||
if digits.is_empty() || !digits.bytes().all(|c| c.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
let order = digits.parse::<i32>().ok().filter(|n| *n >= 0)?;
|
||||
return Some(list(ListType::Numbered, false, Some(order)));
|
||||
}
|
||||
"[]" | "[ ]" => return Some(list(ListType::Todo, false, None)),
|
||||
"[x]" => return Some(list(ListType::Todo, true, None)),
|
||||
s if s.len() >= 3
|
||||
&& matches!(s.as_bytes()[0], b'-' | b'*' | b'_')
|
||||
&& s.bytes().all(|b| b == s.as_bytes()[0]) =>
|
||||
{
|
||||
return Some(BlockSpec::Divider);
|
||||
}
|
||||
s if s.starts_with("```") => {
|
||||
let language = &s[3..];
|
||||
if !language
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '+' | '#' | '.' | '-'))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
return Some(BlockSpec::Code {
|
||||
text: String::new(),
|
||||
language: (!language.is_empty()).then(|| language.into()),
|
||||
caption: String::new(),
|
||||
});
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
Some(BlockSpec::Paragraph {
|
||||
paragraph_type: spec,
|
||||
text: String::new(),
|
||||
})
|
||||
}
|
||||
|
||||
struct InlineMatch {
|
||||
/// Byte offset of the match start within `line`.
|
||||
start_byte: usize,
|
||||
/// Opening delimiter byte length.
|
||||
open_bytes: usize,
|
||||
/// Inner target byte length.
|
||||
target_bytes: usize,
|
||||
/// Closing delimiter byte length.
|
||||
close_bytes: usize,
|
||||
/// Attributes to apply.
|
||||
attrs: TextAttributes,
|
||||
/// If true, replaces the whole match with a single `" "` carrying `attrs` (inline latex).
|
||||
replace_with_embed_space: bool,
|
||||
}
|
||||
|
||||
fn match_delimited(line: &str, delim: &str, ch: char) -> Option<(usize, usize)> {
|
||||
let before_close = line.strip_suffix(delim)?;
|
||||
let mut search_end = before_close.len();
|
||||
while let Some(open) = before_close[..search_end].rfind(delim) {
|
||||
let preceded_by_same = before_close[..open].ends_with(ch);
|
||||
if !preceded_by_same {
|
||||
let target = &before_close[open + delim.len()..];
|
||||
if !target.is_empty() && !target.contains(ch) {
|
||||
let first = target.chars().next()?;
|
||||
let last = target.chars().next_back()?;
|
||||
if !first.is_whitespace() && first != ch && !last.is_whitespace() && last != ch {
|
||||
return Some((open, target.len()));
|
||||
}
|
||||
}
|
||||
}
|
||||
if open == 0 {
|
||||
break;
|
||||
}
|
||||
search_end = open;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn match_inline_link(line: &str) -> Option<InlineMatch> {
|
||||
let without_close = line.strip_suffix(')')?;
|
||||
let sep = without_close.rfind("](")?;
|
||||
let url = &without_close[sep + 2..];
|
||||
if url.is_empty() || url.contains(')') {
|
||||
return None;
|
||||
}
|
||||
let before_sep = &without_close[..sep];
|
||||
let open = before_sep.rfind('[')?;
|
||||
let label = &before_sep[open + 1..];
|
||||
if label.is_empty() || label.contains('[') || label.contains(']') {
|
||||
return None;
|
||||
}
|
||||
Some(InlineMatch {
|
||||
start_byte: open,
|
||||
open_bytes: 1,
|
||||
target_bytes: label.len(),
|
||||
close_bytes: 2 + url.len() + 1,
|
||||
attrs: TextAttributes::from([("link".into(), Any::String(url.to_string()))]),
|
||||
replace_with_embed_space: false,
|
||||
})
|
||||
}
|
||||
|
||||
fn match_inline_markdown(line: &str) -> Option<InlineMatch> {
|
||||
if let Some((open, target_len)) = match_delimited(line, "***", '*') {
|
||||
return Some(InlineMatch {
|
||||
start_byte: open,
|
||||
open_bytes: 3,
|
||||
target_bytes: target_len,
|
||||
close_bytes: 3,
|
||||
attrs: TextAttributes::from([("bold".into(), Any::True), ("italic".into(), Any::True)]),
|
||||
replace_with_embed_space: false,
|
||||
});
|
||||
}
|
||||
if let Some((open, target_len)) = match_delimited(line, "**", '*') {
|
||||
return Some(InlineMatch {
|
||||
start_byte: open,
|
||||
open_bytes: 2,
|
||||
target_bytes: target_len,
|
||||
close_bytes: 2,
|
||||
attrs: TextAttributes::from([("bold".into(), Any::True)]),
|
||||
replace_with_embed_space: false,
|
||||
});
|
||||
}
|
||||
if let Some((open, target_len)) = match_delimited(line, "*", '*') {
|
||||
return Some(InlineMatch {
|
||||
start_byte: open,
|
||||
open_bytes: 1,
|
||||
target_bytes: target_len,
|
||||
close_bytes: 1,
|
||||
attrs: TextAttributes::from([("italic".into(), Any::True)]),
|
||||
replace_with_embed_space: false,
|
||||
});
|
||||
}
|
||||
if let Some((open, target_len)) = match_delimited(line, "~~", '~') {
|
||||
return Some(InlineMatch {
|
||||
start_byte: open,
|
||||
open_bytes: 2,
|
||||
target_bytes: target_len,
|
||||
close_bytes: 2,
|
||||
attrs: TextAttributes::from([("strike".into(), Any::True)]),
|
||||
replace_with_embed_space: false,
|
||||
});
|
||||
}
|
||||
if let Some((open, target_len)) = match_delimited(line, "~", '~') {
|
||||
return Some(InlineMatch {
|
||||
start_byte: open,
|
||||
open_bytes: 1,
|
||||
target_bytes: target_len,
|
||||
close_bytes: 1,
|
||||
attrs: TextAttributes::from([("underline".into(), Any::True)]),
|
||||
replace_with_embed_space: false,
|
||||
});
|
||||
}
|
||||
if let Some((open, target_len)) = match_delimited(line, "`", '`') {
|
||||
return Some(InlineMatch {
|
||||
start_byte: open,
|
||||
open_bytes: 1,
|
||||
target_bytes: target_len,
|
||||
close_bytes: 1,
|
||||
attrs: TextAttributes::from([("code".into(), Any::True)]),
|
||||
replace_with_embed_space: false,
|
||||
});
|
||||
}
|
||||
if let Some(link) = match_inline_link(line) {
|
||||
return Some(link);
|
||||
}
|
||||
for delim in ["$$", "$"] {
|
||||
if let Some((open, target_len)) = match_delimited(line, delim, '$') {
|
||||
let content = &line[open + delim.len()..open + delim.len() + target_len];
|
||||
return Some(InlineMatch {
|
||||
start_byte: open,
|
||||
open_bytes: delim.len(),
|
||||
target_bytes: target_len,
|
||||
close_bytes: delim.len(),
|
||||
attrs: TextAttributes::from([("latex".into(), Any::String(content.to_string()))]),
|
||||
replace_with_embed_space: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
impl PlaygroundView {
|
||||
pub(super) fn apply_markdown(
|
||||
&mut self,
|
||||
sel: &DocumentSelection,
|
||||
typed: &str,
|
||||
w: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> DocResult<bool> {
|
||||
if !sel.empty()
|
||||
|| self.editor.preedit.is_some()
|
||||
|| (!typed.ends_with(' ') && !typed.ends_with('\n'))
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
let is_enter = typed.ends_with('\n');
|
||||
let typed_body = &typed[..typed.len() - 1];
|
||||
let Some(snapshot) = self.snapshot.as_ref().cloned() else {
|
||||
return Ok(false);
|
||||
};
|
||||
let id = &sel.focus.block_id;
|
||||
let Some(node) = snapshot.block(id) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let (rich, paragraph_kind, is_list) = match &node.content {
|
||||
BlockContent::Paragraph { kind, text, .. } => (text, Some(*kind), false),
|
||||
BlockContent::List { text, .. } => (text, None, true),
|
||||
_ => return Ok(false),
|
||||
};
|
||||
let offset = sel.focus.offset();
|
||||
let index = TextBiIndex::new(&rich.plain);
|
||||
let byte = index.utf16_to_utf8_clamped(offset);
|
||||
let before_caret = &rich.plain[..byte];
|
||||
|
||||
// 1. Block-level Markdown prefix (only on the first line of the block).
|
||||
if !before_caret.contains('\n') && !typed_body.contains('\n') {
|
||||
let mut prefix = before_caret.to_owned();
|
||||
prefix.push_str(typed);
|
||||
if let Some(spec) = markdown_block(&prefix) {
|
||||
let allowed = if is_list {
|
||||
matches!(
|
||||
spec,
|
||||
BlockSpec::Paragraph {
|
||||
paragraph_type: ParagraphType::H1
|
||||
| ParagraphType::H2
|
||||
| ParagraphType::H3
|
||||
| ParagraphType::H4
|
||||
| ParagraphType::H5
|
||||
| ParagraphType::H6
|
||||
| ParagraphType::Quote,
|
||||
..
|
||||
} | BlockSpec::Code { .. }
|
||||
)
|
||||
} else if paragraph_kind == Some(ParagraphType::Quote) {
|
||||
!matches!(
|
||||
spec,
|
||||
BlockSpec::Paragraph {
|
||||
paragraph_type: ParagraphType::Quote,
|
||||
..
|
||||
}
|
||||
)
|
||||
} else {
|
||||
!matches!(
|
||||
spec,
|
||||
BlockSpec::Paragraph { paragraph_type, .. }
|
||||
if Some(paragraph_type) == paragraph_kind
|
||||
)
|
||||
};
|
||||
if allowed && let Some((parent, slot)) = parent_of(&snapshot, id) {
|
||||
let now = self.now_ms(cx) as u64;
|
||||
let replacement = self.fresh_block_id();
|
||||
let trailing = self.fresh_block_id();
|
||||
let divider = matches!(spec, BlockSpec::Divider);
|
||||
let code = matches!(spec, BlockSpec::Code { .. });
|
||||
let focus = if divider || spec.flavour() == node.flavour {
|
||||
id.clone()
|
||||
} else {
|
||||
replacement.clone()
|
||||
};
|
||||
let page = self.page_mut()?;
|
||||
let before = sel.snapshot(page)?;
|
||||
let commit = page.structural_edit(now, |page| {
|
||||
if offset > 0 {
|
||||
page.remove_text(id, "prop:text", 0, offset, now)?;
|
||||
}
|
||||
if divider || code {
|
||||
page.add_block(
|
||||
&replacement,
|
||||
spec,
|
||||
Some(&parent.id),
|
||||
Some(slot as u64),
|
||||
now,
|
||||
)?;
|
||||
if code {
|
||||
let remaining = page.read_editable_text(id)?.0;
|
||||
if !remaining.is_empty() {
|
||||
page.add_block(
|
||||
&trailing,
|
||||
paragraph(),
|
||||
Some(&parent.id),
|
||||
Some(slot as u64 + 1),
|
||||
now,
|
||||
)?;
|
||||
page.apply_text_delta(
|
||||
&trailing,
|
||||
"prop:text",
|
||||
&remaining.delta,
|
||||
now,
|
||||
)?;
|
||||
}
|
||||
page.remove_lifting_children(id, now)?;
|
||||
}
|
||||
} else {
|
||||
page.convert_markdown_block(id, &replacement, spec, now)?;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
if commit.is_some() {
|
||||
page.set_undo_selection_snapshot(before)?;
|
||||
}
|
||||
self.editor.selection = Some(DocumentSelection::caret(DocPoint::new(focus, 0)));
|
||||
self.editor.pending_marks.clear();
|
||||
self.editor.last_typing = None;
|
||||
self.did_edit(commit, None, w, cx);
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Inline Markdown rules (ASCII space or Enter, outside inline code).
|
||||
let caret_marks = self.insertion_marks(&sel.focus)?;
|
||||
if caret_marks.get("code") == Some(&Any::True) {
|
||||
return Ok(false);
|
||||
}
|
||||
let mut combined = before_caret.to_owned();
|
||||
combined.push_str(typed_body);
|
||||
let combined_index = TextBiIndex::new(&combined);
|
||||
let line_start_byte = combined.rfind('\n').map_or(0, |pos| pos + 1);
|
||||
let line = &combined[line_start_byte..];
|
||||
let Some(matched) = match_inline_markdown(line) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let match_start_byte = line_start_byte + matched.start_byte;
|
||||
let match_start_utf16 = combined_index.utf8_to_utf16(match_start_byte);
|
||||
let open_utf16 = combined[match_start_byte..match_start_byte + matched.open_bytes]
|
||||
.encode_utf16()
|
||||
.count() as u64;
|
||||
let target_start_byte = match_start_byte + matched.open_bytes;
|
||||
let target_utf16 = combined[target_start_byte..target_start_byte + matched.target_bytes]
|
||||
.encode_utf16()
|
||||
.count() as u64;
|
||||
let close_start_byte = target_start_byte + matched.target_bytes;
|
||||
let close_utf16 = combined[close_start_byte..close_start_byte + matched.close_bytes]
|
||||
.encode_utf16()
|
||||
.count() as u64;
|
||||
|
||||
let mut outer_marks =
|
||||
self.insertion_marks(&DocPoint::new(id, match_start_utf16.min(offset)))?;
|
||||
for key in matched.attrs.keys() {
|
||||
outer_marks.remove(key);
|
||||
}
|
||||
|
||||
let now = self.now_ms(cx) as u64;
|
||||
let pre_insert = if is_enter { typed_body } else { typed };
|
||||
let pre_insert_utf16 = pre_insert.encode_utf16().count() as u64;
|
||||
|
||||
// Commit any newly typed characters (and trailing ASCII space) before `stop_capturing`,
|
||||
// so one Undo restores the raw markdown with its trailing space (e.g. `**bold** `),
|
||||
// and the trailing space already carries `outer_marks` without the newly added mark.
|
||||
if !pre_insert.is_empty() {
|
||||
let page = self.page_mut()?;
|
||||
let mut pre_delta = Vec::new();
|
||||
if offset > 0 {
|
||||
pre_delta.push(TextDeltaOp::Retain {
|
||||
retain: offset,
|
||||
format: None,
|
||||
});
|
||||
}
|
||||
pre_delta.push(TextDeltaOp::Insert {
|
||||
insert: TextInsert::Text(pre_insert.into()),
|
||||
format: (!outer_marks.is_empty()).then(|| outer_marks.clone()),
|
||||
});
|
||||
let pre_commit = page.apply_text_delta(id, "prop:text", &pre_delta, now)?;
|
||||
if let (Some(c), Some(page_id)) = (pre_commit, self.page_id.clone()) {
|
||||
self.send_page_update(&page_id, c.update);
|
||||
}
|
||||
}
|
||||
|
||||
let page = self.page_mut()?;
|
||||
let undo_sel = page.capture_selection_snapshot(
|
||||
id,
|
||||
offset + pre_insert_utf16,
|
||||
id,
|
||||
offset + pre_insert_utf16,
|
||||
)?;
|
||||
page.stop_capturing()?;
|
||||
|
||||
let mut delta = Vec::new();
|
||||
if match_start_utf16 > 0 {
|
||||
delta.push(TextDeltaOp::Retain {
|
||||
retain: match_start_utf16,
|
||||
format: None,
|
||||
});
|
||||
}
|
||||
let new_caret = if matched.replace_with_embed_space {
|
||||
let total_del = open_utf16 + target_utf16 + close_utf16;
|
||||
delta.push(TextDeltaOp::Delete { delete: total_del });
|
||||
delta.push(TextDeltaOp::Insert {
|
||||
insert: TextInsert::Text(" ".into()),
|
||||
format: Some(matched.attrs.clone()),
|
||||
});
|
||||
match_start_utf16 + 1 + u64::from(!is_enter)
|
||||
} else {
|
||||
delta.push(TextDeltaOp::Delete { delete: open_utf16 });
|
||||
delta.push(TextDeltaOp::Retain {
|
||||
retain: target_utf16,
|
||||
format: Some(matched.attrs.clone()),
|
||||
});
|
||||
delta.push(TextDeltaOp::Delete {
|
||||
delete: close_utf16,
|
||||
});
|
||||
match_start_utf16 + target_utf16 + u64::from(!is_enter)
|
||||
};
|
||||
|
||||
let commit = page.apply_text_delta(id, "prop:text", &delta, now)?;
|
||||
if commit.is_some() {
|
||||
page.set_undo_selection_snapshot(undo_sel)?;
|
||||
}
|
||||
page.stop_capturing()?;
|
||||
|
||||
self.editor.selection = Some(DocumentSelection::caret(DocPoint::new(id, new_caret)));
|
||||
self.editor.pending_marks.clear();
|
||||
if is_enter {
|
||||
for key in matched.attrs.keys() {
|
||||
self.editor.pending_marks.insert(key.clone(), None);
|
||||
}
|
||||
}
|
||||
self.editor.last_typing = None;
|
||||
self.did_edit(commit, Some(id), w, cx);
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
//! PlaygroundView glue for `blocksuite_editor::editor_session`.
|
||||
|
||||
mod block_selection;
|
||||
mod clipboard_ops;
|
||||
mod commands;
|
||||
mod composition;
|
||||
mod input_handler;
|
||||
mod markdown;
|
||||
|
||||
pub use blocksuite_editor::editor_session::*;
|
||||
#[cfg(test)]
|
||||
@@ -11,7 +13,7 @@ pub(crate) use commands::{
|
||||
HistoryRejectFault, set_history_reject_fault, take_history_reject_fallback_hits,
|
||||
};
|
||||
|
||||
use input_handler::{list, markdown_block, paragraph};
|
||||
use input_handler::{list, paragraph};
|
||||
|
||||
use blocksuite_playground_doc::{
|
||||
DocError, DocResult,
|
||||
@@ -117,6 +119,9 @@ impl PlaygroundView {
|
||||
pub fn document_selection(&self) -> Option<&DocumentSelection> {
|
||||
self.editor.selection.as_ref()
|
||||
}
|
||||
pub fn block_selection(&self) -> &[String] {
|
||||
&self.editor.block_selection
|
||||
}
|
||||
pub fn goal_x(&self) -> Option<f32> {
|
||||
self.editor.goal_x
|
||||
}
|
||||
@@ -142,6 +147,7 @@ impl PlaygroundView {
|
||||
self.doc_rev += 1;
|
||||
}
|
||||
self.editor.selection = Some(sel);
|
||||
self.editor.block_selection.clear();
|
||||
self.editor.pending_marks.clear();
|
||||
self.editor.last_typing = None;
|
||||
self.editor.goal_x = None;
|
||||
|
||||
@@ -4254,12 +4254,12 @@ mod tests {
|
||||
});
|
||||
assert!(has_chip, "expected InlineReference chip after @ selection");
|
||||
|
||||
// Also verify `/linked` (`SlashCommand::LinkedPage`) converts a line into a linked doc
|
||||
// + InlineReference chip.
|
||||
// Also verify `/newdoc` (`SlashCommand::NewDoc`) creates a new empty doc and inserts
|
||||
// an InlineReference chip at the caret while preserving surrounding text.
|
||||
if matches!(theme, PlaygroundTheme::Light) {
|
||||
let docs_before = session.view(|view, _| {
|
||||
view.query_linked_docs(&directory::DocQueryRequest::new("", 50))
|
||||
.expect("docs before /linked")
|
||||
.expect("docs before /newdoc")
|
||||
.items
|
||||
.len()
|
||||
});
|
||||
@@ -4278,7 +4278,7 @@ mod tests {
|
||||
view, None, "/", window, cx,
|
||||
);
|
||||
ui::EntityInputHandler::replace_text_in_range(
|
||||
view, None, "linked", window, cx,
|
||||
view, None, "newdoc", window, cx,
|
||||
);
|
||||
view.dispatch_overlay(
|
||||
overlays::OverlayEvent::SlashExecute(0),
|
||||
@@ -4286,12 +4286,12 @@ mod tests {
|
||||
cx,
|
||||
);
|
||||
})
|
||||
.expect("execute /linked");
|
||||
.expect("execute /newdoc");
|
||||
});
|
||||
let (docs_after, slash_chip) = session.view(|view, _| {
|
||||
let count = view
|
||||
.query_linked_docs(&directory::DocQueryRequest::new("", 50))
|
||||
.expect("docs after /linked")
|
||||
.expect("docs after /newdoc")
|
||||
.items
|
||||
.len();
|
||||
let chip = view
|
||||
@@ -4299,7 +4299,9 @@ mod tests {
|
||||
.and_then(|s| s.block("showcase-intro"))
|
||||
.and_then(overlays::block_text)
|
||||
.is_some_and(|t| {
|
||||
t.plain == " "
|
||||
t.plain.starts_with(' ')
|
||||
&& t.plain.len() > 1
|
||||
&& !t.plain.contains("/newdoc")
|
||||
&& t.delta.iter().any(|op| {
|
||||
matches!(
|
||||
op,
|
||||
@@ -4311,7 +4313,7 @@ mod tests {
|
||||
(count, chip)
|
||||
});
|
||||
assert_eq!(docs_after, docs_before + 1);
|
||||
assert!(slash_chip, "expected InlineReference chip after /linked");
|
||||
assert!(slash_chip, "expected InlineReference chip after /newdoc");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6831,4 +6833,809 @@ mod tests {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn send_key(session: &Session, key: &str, modifiers: ui::Modifiers) {
|
||||
session.app.update(|cx| {
|
||||
session
|
||||
.window
|
||||
.update(cx, |view, window, cx| {
|
||||
let event = ui::KeyDownEvent {
|
||||
keystroke: ui::Keystroke {
|
||||
modifiers,
|
||||
key: key.to_string(),
|
||||
key_char: None,
|
||||
},
|
||||
is_held: false,
|
||||
prefer_character_input: false,
|
||||
};
|
||||
view.editor_key_down(&event, window, cx);
|
||||
})
|
||||
.expect("dispatch key");
|
||||
});
|
||||
}
|
||||
|
||||
fn type_text(session: &Session, text: &str) {
|
||||
session.app.update(|cx| {
|
||||
session
|
||||
.window
|
||||
.update(cx, |view, window, cx| {
|
||||
ui::EntityInputHandler::replace_text_in_range(view, None, text, window, cx);
|
||||
})
|
||||
.expect("type text");
|
||||
});
|
||||
}
|
||||
|
||||
fn set_caret(session: &Session, block_id: &str, offset: u64) {
|
||||
session.app.update(|cx| {
|
||||
session
|
||||
.window
|
||||
.update(cx, |view, window, cx| {
|
||||
view.select_document_range(
|
||||
editor_session::DocumentSelection::caret(editor_session::DocPoint::new(
|
||||
block_id, offset,
|
||||
)),
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
})
|
||||
.expect("set caret");
|
||||
});
|
||||
}
|
||||
|
||||
fn cmd_mod() -> ui::Modifiers {
|
||||
if cfg!(target_os = "macos") {
|
||||
ui::Modifiers {
|
||||
platform: true,
|
||||
..Default::default()
|
||||
}
|
||||
} else {
|
||||
ui::Modifiers {
|
||||
control: true,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn s2_touch_tap_and_pan_scroll_work_at_mobile_viewport() {
|
||||
let session = open(390, 844, PlaygroundOptions::default());
|
||||
session.app.update(|cx| {
|
||||
session
|
||||
.window
|
||||
.update(cx, |_, window, _| {
|
||||
window.set_touch_gestures_enabled(true);
|
||||
})
|
||||
.expect("enable touch gestures");
|
||||
});
|
||||
let _ = session.frame();
|
||||
|
||||
// Tap inside the intro paragraph to place caret.
|
||||
let target_pos = session.view(|view, _| {
|
||||
let layout = view.flow_layout().expect("layout");
|
||||
let block = layout.block("showcase-intro").expect("intro");
|
||||
let geo = block_flow::page_geometry(390.0);
|
||||
point(
|
||||
px(geo.column_x + block.x + 20.0),
|
||||
px(TOPBAR_HEIGHT + block.y + 10.0),
|
||||
)
|
||||
});
|
||||
session
|
||||
.headless
|
||||
.dispatch_input(ui::PlatformInput::Touch(ui::TouchEvent {
|
||||
id: ui::TouchId(1),
|
||||
phase: ui::TouchPhase::Started,
|
||||
position: target_pos,
|
||||
predicted_position: None,
|
||||
force: None,
|
||||
}));
|
||||
session
|
||||
.headless
|
||||
.dispatch_input(ui::PlatformInput::Touch(ui::TouchEvent {
|
||||
id: ui::TouchId(1),
|
||||
phase: ui::TouchPhase::Ended,
|
||||
position: target_pos,
|
||||
predicted_position: None,
|
||||
force: None,
|
||||
}));
|
||||
let sel_block =
|
||||
session.view(|view, _| view.document_selection().map(|s| s.focus.block_id.clone()));
|
||||
assert_eq!(sel_block.as_deref(), Some("showcase-intro"));
|
||||
|
||||
// Pan finger upward (y: 400 -> 200) to scroll page downward (`scroll_y` increases).
|
||||
let scroll_before = session.view(|view, _| view.scroll_offset());
|
||||
session
|
||||
.headless
|
||||
.dispatch_input(ui::PlatformInput::Touch(ui::TouchEvent {
|
||||
id: ui::TouchId(2),
|
||||
phase: ui::TouchPhase::Started,
|
||||
position: point(px(195.0), px(400.0)),
|
||||
predicted_position: None,
|
||||
force: None,
|
||||
}));
|
||||
for y in [360.0_f32, 300.0, 240.0, 200.0] {
|
||||
session
|
||||
.headless
|
||||
.dispatch_input(ui::PlatformInput::Touch(ui::TouchEvent {
|
||||
id: ui::TouchId(2),
|
||||
phase: ui::TouchPhase::Moved,
|
||||
position: point(px(195.0), px(y)),
|
||||
predicted_position: None,
|
||||
force: None,
|
||||
}));
|
||||
}
|
||||
session
|
||||
.headless
|
||||
.dispatch_input(ui::PlatformInput::Touch(ui::TouchEvent {
|
||||
id: ui::TouchId(2),
|
||||
phase: ui::TouchPhase::Ended,
|
||||
position: point(px(195.0), px(200.0)),
|
||||
predicted_position: None,
|
||||
force: None,
|
||||
}));
|
||||
let scroll_after = session.view(|view, _| view.scroll_offset());
|
||||
assert!(
|
||||
scroll_after > scroll_before + 50.0,
|
||||
"upward touch pan must increase scroll_y: before={scroll_before}, after={scroll_after}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn s2_linked_doc_triggers_at_mid_word_and_double_brackets() {
|
||||
let session = open(1024, 720, PlaygroundOptions::default());
|
||||
let _ = session.frame();
|
||||
|
||||
for (prefix, trigger, expected_plain) in [
|
||||
("foo", "@", "foo@"),
|
||||
("bar", "[[", "bar@"),
|
||||
("baz[", "[", "baz@"),
|
||||
("中文", "【【", "中文@"),
|
||||
("中文【", "【", "中文@"),
|
||||
] {
|
||||
let block_id = session.view(|view, cx| {
|
||||
let id = view.fresh_block_id();
|
||||
view.edit_document(cx, |state| {
|
||||
let page = state.workspace.page_mut(HOME_PAGE_ID).expect("page");
|
||||
let snap = page.read_page_snapshot().expect("snap");
|
||||
let note_id = snap
|
||||
.root
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.children
|
||||
.iter()
|
||||
.find(|n| n.is_page_visible_note())
|
||||
.unwrap()
|
||||
.id
|
||||
.clone();
|
||||
page.add_block(
|
||||
&id,
|
||||
BlockSpec::Paragraph {
|
||||
paragraph_type: ParagraphType::Text,
|
||||
text: prefix.to_string(),
|
||||
},
|
||||
Some(¬e_id),
|
||||
None,
|
||||
100,
|
||||
)
|
||||
.expect("add block");
|
||||
});
|
||||
id
|
||||
});
|
||||
let _ = session.frame();
|
||||
set_caret(&session, &block_id, prefix.encode_utf16().count() as u64);
|
||||
type_text(&session, trigger);
|
||||
let (menu_open, plain) = session.view(|view, _| {
|
||||
let open = view.overlays().linked_doc_menu().is_some();
|
||||
let plain = view.block_text(&block_id).unwrap_or("").to_string();
|
||||
(open, plain)
|
||||
});
|
||||
assert!(
|
||||
menu_open,
|
||||
"trigger {trigger:?} after {prefix:?} must open @ menu"
|
||||
);
|
||||
assert_eq!(plain, expected_plain);
|
||||
send_key(&session, "escape", ui::Modifiers::default());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn s2_inline_markdown_rules_ime_guard_and_c1_keep_space_no_leak() {
|
||||
let session = open(1024, 720, PlaygroundOptions::default());
|
||||
let _ = session.frame();
|
||||
|
||||
let cases = [
|
||||
("***bi***", "bi", "bold", true),
|
||||
("**bold**", "bold", "bold", false),
|
||||
("*ital*", "ital", "italic", false),
|
||||
("~~del~~", "del", "strike", false),
|
||||
("~und~", "und", "underline", false),
|
||||
("`code`", "code", "code", false),
|
||||
("[site](https://affine.pro)", "site", "link", false),
|
||||
];
|
||||
|
||||
for (raw, expected_word, mark_key, also_italic) in cases {
|
||||
let block_id = session.view(|view, cx| {
|
||||
let id = view.fresh_block_id();
|
||||
view.edit_document(cx, |state| {
|
||||
let page = state.workspace.page_mut(HOME_PAGE_ID).expect("page");
|
||||
let snap = page.read_page_snapshot().expect("snap");
|
||||
let note_id = snap
|
||||
.root
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.children
|
||||
.iter()
|
||||
.find(|n| n.is_page_visible_note())
|
||||
.unwrap()
|
||||
.id
|
||||
.clone();
|
||||
page.add_block(
|
||||
&id,
|
||||
BlockSpec::Paragraph {
|
||||
paragraph_type: ParagraphType::Text,
|
||||
text: format!("a {raw}"),
|
||||
},
|
||||
Some(¬e_id),
|
||||
None,
|
||||
100,
|
||||
)
|
||||
.expect("add block");
|
||||
});
|
||||
id
|
||||
});
|
||||
let _ = session.frame();
|
||||
let full_len = format!("a {raw}").encode_utf16().count() as u64;
|
||||
set_caret(&session, &block_id, full_len);
|
||||
|
||||
// Fullwidth space must NOT trigger conversion.
|
||||
type_text(&session, "\u{3000}");
|
||||
assert!(
|
||||
session.view(|v, _| v.block_text(&block_id).unwrap_or("").ends_with('\u{3000}')),
|
||||
"fullwidth space must not trigger markdown for {raw}"
|
||||
);
|
||||
send_key(&session, "backspace", ui::Modifiers::default());
|
||||
|
||||
// ASCII space triggers C1-KeepSpaceNoLeak: keeps trailing space without new mark.
|
||||
type_text(&session, " ");
|
||||
type_text(&session, "z");
|
||||
session.view(|view, _| {
|
||||
let (rich, _) = view.page().unwrap().read_editable_text(&block_id).unwrap();
|
||||
assert_eq!(rich.plain, format!("a {expected_word} z"), "for {raw}");
|
||||
let marked_word = rich.delta.iter().any(|op| {
|
||||
matches!(
|
||||
op,
|
||||
y_octo::TextDeltaOp::Insert {
|
||||
insert: y_octo::TextInsert::Text(t),
|
||||
format: Some(f),
|
||||
} if t == expected_word
|
||||
&& f.contains_key(mark_key)
|
||||
&& (!also_italic || f.get("italic") == Some(&Any::True))
|
||||
)
|
||||
});
|
||||
assert!(
|
||||
marked_word,
|
||||
"expected mark {mark_key} on {expected_word} for {raw}"
|
||||
);
|
||||
let leaked_on_z = rich.delta.iter().any(|op| {
|
||||
matches!(
|
||||
op,
|
||||
y_octo::TextDeltaOp::Insert {
|
||||
insert: y_octo::TextInsert::Text(t),
|
||||
format: Some(f),
|
||||
} if t.contains('z')
|
||||
&& f.get(mark_key).is_some_and(|v| *v != Any::Null)
|
||||
)
|
||||
});
|
||||
assert!(
|
||||
!leaked_on_z,
|
||||
"mark {mark_key} must not leak onto trailing 'z' for {raw}: delta={:?}",
|
||||
rich.delta
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// Verify Enter trigger swallows Enter, leaves no trailing space, and does not leak mark.
|
||||
let enter_id = session.view(|view, cx| {
|
||||
let id = view.fresh_block_id();
|
||||
view.edit_document(cx, |state| {
|
||||
let page = state.workspace.page_mut(HOME_PAGE_ID).expect("page");
|
||||
let snap = page.read_page_snapshot().expect("snap");
|
||||
let note_id = snap
|
||||
.root
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.children
|
||||
.iter()
|
||||
.find(|n| n.is_page_visible_note())
|
||||
.unwrap()
|
||||
.id
|
||||
.clone();
|
||||
page.add_block(
|
||||
&id,
|
||||
BlockSpec::Paragraph {
|
||||
paragraph_type: ParagraphType::Text,
|
||||
text: "**hi**".into(),
|
||||
},
|
||||
Some(¬e_id),
|
||||
None,
|
||||
100,
|
||||
)
|
||||
.expect("add");
|
||||
});
|
||||
id
|
||||
});
|
||||
let _ = session.frame();
|
||||
set_caret(&session, &enter_id, 6);
|
||||
let blocks_before = session.view(|v, _| v.flow_layout().unwrap().blocks.len());
|
||||
send_key(&session, "enter", ui::Modifiers::default());
|
||||
type_text(&session, "x");
|
||||
session.view(|view, _| {
|
||||
assert_eq!(
|
||||
view.flow_layout().unwrap().blocks.len(),
|
||||
blocks_before,
|
||||
"Enter-triggered inline markdown must not split block"
|
||||
);
|
||||
let (rich, _) = view.page().unwrap().read_editable_text(&enter_id).unwrap();
|
||||
assert_eq!(rich.plain, "hix");
|
||||
let x_is_bold = rich.delta.iter().any(|op| {
|
||||
matches!(
|
||||
op,
|
||||
y_octo::TextDeltaOp::Insert {
|
||||
insert: y_octo::TextInsert::Text(t),
|
||||
format: Some(f),
|
||||
} if t.contains('x') && f.get("bold") == Some(&Any::True)
|
||||
)
|
||||
});
|
||||
assert!(!x_is_bold, "closed bold mark must not leak after Enter");
|
||||
});
|
||||
|
||||
// Verify inline `$E=mc^2$` conversion and zero `latex` mark leak even after caret move,
|
||||
// plus multi-character `type_text("**multi** ")` trigger.
|
||||
let latex_id = session.view(|view, cx| {
|
||||
let id = view.fresh_block_id();
|
||||
view.edit_document(cx, |state| {
|
||||
let page = state.workspace.page_mut(HOME_PAGE_ID).expect("page");
|
||||
let snap = page.read_page_snapshot().expect("snap");
|
||||
let note_id = snap
|
||||
.root
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.children
|
||||
.iter()
|
||||
.find(|n| n.is_page_visible_note())
|
||||
.unwrap()
|
||||
.id
|
||||
.clone();
|
||||
page.add_block(
|
||||
&id,
|
||||
BlockSpec::Paragraph {
|
||||
paragraph_type: ParagraphType::Text,
|
||||
text: "$E=mc^2$".into(),
|
||||
},
|
||||
Some(¬e_id),
|
||||
None,
|
||||
100,
|
||||
)
|
||||
.expect("add latex block");
|
||||
});
|
||||
id
|
||||
});
|
||||
let _ = session.frame();
|
||||
set_caret(&session, &latex_id, 8);
|
||||
send_key(&session, "enter", ui::Modifiers::default());
|
||||
// Reposition caret right after the inline formula (clearing pending_marks) and type "x".
|
||||
set_caret(&session, &latex_id, 1);
|
||||
type_text(&session, "x");
|
||||
type_text(&session, "**multi** ");
|
||||
session.view(|view, _| {
|
||||
let (rich, _) = view.page().unwrap().read_editable_text(&latex_id).unwrap();
|
||||
let has_latex = rich.delta.iter().any(|op| {
|
||||
matches!(
|
||||
op,
|
||||
y_octo::TextDeltaOp::Insert {
|
||||
insert: y_octo::TextInsert::Text(t),
|
||||
format: Some(f),
|
||||
} if t == " " && f.get("latex") == Some(&Any::String("E=mc^2".into()))
|
||||
)
|
||||
});
|
||||
assert!(has_latex, "expected inline latex node: {:?}", rich.delta);
|
||||
let x_has_latex = rich.delta.iter().any(|op| {
|
||||
matches!(
|
||||
op,
|
||||
y_octo::TextDeltaOp::Insert {
|
||||
insert: y_octo::TextInsert::Text(t),
|
||||
format: Some(f),
|
||||
} if t.contains('x') && f.contains_key("latex")
|
||||
)
|
||||
});
|
||||
assert!(
|
||||
!x_has_latex,
|
||||
"latex mark must not leak onto trailing 'x': {:?}",
|
||||
rich.delta
|
||||
);
|
||||
let has_multi_bold = rich.delta.iter().any(|op| {
|
||||
matches!(
|
||||
op,
|
||||
y_octo::TextDeltaOp::Insert {
|
||||
insert: y_octo::TextInsert::Text(t),
|
||||
format: Some(f),
|
||||
} if t == "multi" && f.get("bold") == Some(&Any::True)
|
||||
)
|
||||
});
|
||||
assert!(
|
||||
has_multi_bold,
|
||||
"multi-character type_text('**multi** ') must convert: {:?}",
|
||||
rich.delta
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn s2_block_markdown_enter_list_quote_and_quote_double_enter() {
|
||||
let session = open(1024, 720, PlaygroundOptions::default());
|
||||
let _ = session.frame();
|
||||
|
||||
// A.4: block prefix + Enter converts and swallows Enter.
|
||||
for (prefix, expect_flavour) in [
|
||||
("-", "affine:list"),
|
||||
("+", "affine:list"),
|
||||
("1.", "affine:list"),
|
||||
("##", "affine:paragraph"),
|
||||
("[]", "affine:list"),
|
||||
(">", "affine:paragraph"),
|
||||
] {
|
||||
let block_id = session.view(|view, cx| {
|
||||
let id = view.fresh_block_id();
|
||||
view.edit_document(cx, |state| {
|
||||
let page = state.workspace.page_mut(HOME_PAGE_ID).expect("page");
|
||||
let snap = page.read_page_snapshot().expect("snap");
|
||||
let note_id = snap
|
||||
.root
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.children
|
||||
.iter()
|
||||
.find(|n| n.is_page_visible_note())
|
||||
.unwrap()
|
||||
.id
|
||||
.clone();
|
||||
page.add_block(
|
||||
&id,
|
||||
BlockSpec::Paragraph {
|
||||
paragraph_type: ParagraphType::Text,
|
||||
text: prefix.into(),
|
||||
},
|
||||
Some(¬e_id),
|
||||
None,
|
||||
100,
|
||||
)
|
||||
.expect("add");
|
||||
});
|
||||
id
|
||||
});
|
||||
let _ = session.frame();
|
||||
let count_before = session.view(|v, _| v.flow_layout().unwrap().blocks.len());
|
||||
set_caret(&session, &block_id, prefix.len() as u64);
|
||||
send_key(&session, "enter", ui::Modifiers::default());
|
||||
let _ = session.frame();
|
||||
session.view(|view, _| {
|
||||
assert_eq!(
|
||||
view.flow_layout().unwrap().blocks.len(),
|
||||
count_before,
|
||||
"prefix {prefix} + Enter must not add extra block"
|
||||
);
|
||||
let focus_id = view.document_selection().unwrap().focus.block_id.clone();
|
||||
let node = view.page_snapshot().unwrap().block(&focus_id).unwrap();
|
||||
assert_eq!(node.flavour, expect_flavour, "for prefix {prefix}");
|
||||
});
|
||||
}
|
||||
|
||||
// A.7: quote("q") -> Enter -> Enter -> "after" yields strictly Quote("q") + Paragraph("after").
|
||||
let quote_id = session.view(|view, cx| {
|
||||
let id = view.fresh_block_id();
|
||||
view.edit_document(cx, |state| {
|
||||
let page = state.workspace.page_mut(HOME_PAGE_ID).expect("page");
|
||||
let snap = page.read_page_snapshot().expect("snap");
|
||||
let note_id = snap
|
||||
.root
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.children
|
||||
.iter()
|
||||
.find(|n| n.is_page_visible_note())
|
||||
.unwrap()
|
||||
.id
|
||||
.clone();
|
||||
page.add_block(
|
||||
&id,
|
||||
BlockSpec::Paragraph {
|
||||
paragraph_type: ParagraphType::Quote,
|
||||
text: "q".into(),
|
||||
},
|
||||
Some(¬e_id),
|
||||
None,
|
||||
100,
|
||||
)
|
||||
.expect("add quote");
|
||||
});
|
||||
id
|
||||
});
|
||||
let _ = session.frame();
|
||||
let blocks_before_quote = session.view(|v, _| v.flow_layout().unwrap().blocks.len());
|
||||
set_caret(&session, "e_id, 1);
|
||||
send_key(&session, "enter", ui::Modifiers::default());
|
||||
send_key(&session, "enter", ui::Modifiers::default());
|
||||
type_text(&session, "after");
|
||||
let _ = session.frame();
|
||||
session.view(|view, _| {
|
||||
assert_eq!(
|
||||
view.flow_layout().unwrap().blocks.len(),
|
||||
blocks_before_quote + 1,
|
||||
"quote double-enter must produce exactly 1 new block, not 2"
|
||||
);
|
||||
let after_id = view.document_selection().unwrap().focus.block_id.clone();
|
||||
let after_node = view.page_snapshot().unwrap().block(&after_id).unwrap();
|
||||
assert!(matches!(
|
||||
&after_node.content,
|
||||
BlockContent::Paragraph {
|
||||
kind: ParagraphType::Text,
|
||||
text,
|
||||
..
|
||||
} if text.plain == "after"
|
||||
));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn s2_nested_list_outdent_slash_c2_shortcuts_and_block_selection() {
|
||||
let session = open(1024, 720, PlaygroundOptions::default());
|
||||
let _ = session.frame();
|
||||
|
||||
// A.6: nested empty list Enter outdents first.
|
||||
let (parent_list, child_list) = session.view(|view, cx| {
|
||||
let p_id = view.fresh_block_id();
|
||||
let c_id = view.fresh_block_id();
|
||||
view.edit_document(cx, |state| {
|
||||
let page = state.workspace.page_mut(HOME_PAGE_ID).expect("page");
|
||||
let snap = page.read_page_snapshot().expect("snap");
|
||||
let note_id = snap
|
||||
.root
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.children
|
||||
.iter()
|
||||
.find(|n| n.is_page_visible_note())
|
||||
.unwrap()
|
||||
.id
|
||||
.clone();
|
||||
page.add_block(
|
||||
&p_id,
|
||||
BlockSpec::List {
|
||||
list_type: ListType::Bulleted,
|
||||
text: "parent".into(),
|
||||
checked: false,
|
||||
order: None,
|
||||
},
|
||||
Some(¬e_id),
|
||||
None,
|
||||
100,
|
||||
)
|
||||
.expect("add parent list");
|
||||
page.add_block(
|
||||
&c_id,
|
||||
BlockSpec::List {
|
||||
list_type: ListType::Bulleted,
|
||||
text: String::new(),
|
||||
checked: false,
|
||||
order: None,
|
||||
},
|
||||
Some(&p_id),
|
||||
None,
|
||||
101,
|
||||
)
|
||||
.expect("add child list");
|
||||
});
|
||||
(p_id, c_id)
|
||||
});
|
||||
let _ = session.frame();
|
||||
set_caret(&session, &child_list, 0);
|
||||
send_key(&session, "enter", ui::Modifiers::default());
|
||||
session.view(|view, _| {
|
||||
let snap = view.page_snapshot().unwrap();
|
||||
let node = snap.block(&child_list).unwrap();
|
||||
assert_eq!(
|
||||
node.flavour, "affine:list",
|
||||
"first Enter must keep affine:list"
|
||||
);
|
||||
assert_ne!(
|
||||
editor_session::parent_of(snap, &child_list).map(|(p, _)| p.id.as_str()),
|
||||
Some(parent_list.as_str()),
|
||||
"first Enter must outdent from parent list"
|
||||
);
|
||||
});
|
||||
// Second Enter at top level demotes to paragraph.
|
||||
send_key(&session, "enter", ui::Modifiers::default());
|
||||
session.view(|view, _| {
|
||||
let focus_id = view.document_selection().unwrap().focus.block_id.clone();
|
||||
let node = view.page_snapshot().unwrap().block(&focus_id).unwrap();
|
||||
assert_eq!(node.flavour, "affine:paragraph");
|
||||
});
|
||||
|
||||
// C.2: in-document slash with no match closes menu and passes Enter through to split.
|
||||
type_text(&session, "11");
|
||||
type_text(&session, "/");
|
||||
type_text(&session, "25");
|
||||
assert!(session.view(|v, _| v.overlays().slash_menu().is_some()));
|
||||
let blocks_before_enter = session.view(|v, _| v.flow_layout().unwrap().blocks.len());
|
||||
send_key(&session, "enter", ui::Modifiers::default());
|
||||
let _ = session.frame();
|
||||
session.view(|view, _| {
|
||||
assert!(
|
||||
view.overlays().slash_menu().is_none(),
|
||||
"C.2 must close slash menu"
|
||||
);
|
||||
assert_eq!(
|
||||
view.flow_layout().unwrap().blocks.len(),
|
||||
blocks_before_enter + 1,
|
||||
"C.2 must pass Enter through to split block"
|
||||
);
|
||||
});
|
||||
|
||||
// A.10: Mod-Alt-2 converts block to H2; Mod-k opens link bar on selection.
|
||||
let conv_block =
|
||||
session.view(|v, _| v.document_selection().unwrap().focus.block_id.clone());
|
||||
type_text(&session, "heading text");
|
||||
let mut alt_cmd = cmd_mod();
|
||||
alt_cmd.alt = true;
|
||||
send_key(&session, "2", alt_cmd);
|
||||
session.view(|view, _| {
|
||||
let node = view.page_snapshot().unwrap().block(&conv_block).unwrap();
|
||||
assert!(matches!(
|
||||
node.content,
|
||||
BlockContent::Paragraph {
|
||||
kind: ParagraphType::H2,
|
||||
..
|
||||
}
|
||||
));
|
||||
});
|
||||
// First Mod-a selects all text in block; Mod-k opens link field.
|
||||
send_key(&session, "a", cmd_mod());
|
||||
send_key(&session, "k", cmd_mod());
|
||||
assert!(
|
||||
session.view(|v, _| v.overlays().link_field().is_some()),
|
||||
"Mod-k must open formatting toolbar link field"
|
||||
);
|
||||
send_key(&session, "escape", ui::Modifiers::default());
|
||||
|
||||
// A.11: Escape selects current block; second Mod-a selects all content blocks.
|
||||
send_key(&session, "escape", ui::Modifiers::default());
|
||||
assert_eq!(
|
||||
session.view(|v, _| v.block_selection().to_vec()),
|
||||
vec![conv_block.clone()]
|
||||
);
|
||||
send_key(&session, "a", cmd_mod());
|
||||
let all_selected = session.view(|v, _| v.block_selection().len());
|
||||
assert!(
|
||||
all_selected > 1,
|
||||
"second Mod-a must select all content blocks"
|
||||
);
|
||||
send_key(&session, "escape", ui::Modifiers::default());
|
||||
assert!(session.view(|v, _| v.block_selection().is_empty()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn s2_delete_selected_parent_with_nested_child_creates_fallback_and_ignores_direct_typing() {
|
||||
let session = open(1024, 720, PlaygroundOptions::default());
|
||||
let mut state = DocState::new("nested-del", client_id_from_seed(77)).expect("doc");
|
||||
state.workspace.initialize_meta().expect("meta");
|
||||
state
|
||||
.workspace
|
||||
.create_page(HOME_PAGE_ID, "Nested Delete", 1)
|
||||
.expect("create page");
|
||||
let page = state.workspace.ensure_page(HOME_PAGE_ID).expect("page");
|
||||
page.structural_edit(1, |page| {
|
||||
page.add_block(
|
||||
"page-root",
|
||||
BlockSpec::Page {
|
||||
title: "Nested Delete".into(),
|
||||
},
|
||||
None,
|
||||
None,
|
||||
1,
|
||||
)?;
|
||||
page.add_block(
|
||||
"note-root",
|
||||
BlockSpec::Note { xywh: None },
|
||||
Some("page-root"),
|
||||
None,
|
||||
1,
|
||||
)?;
|
||||
page.add_block(
|
||||
"list-parent",
|
||||
BlockSpec::List {
|
||||
list_type: ListType::Bulleted,
|
||||
text: "parent".into(),
|
||||
checked: false,
|
||||
order: None,
|
||||
},
|
||||
Some("note-root"),
|
||||
None,
|
||||
1,
|
||||
)?;
|
||||
page.add_block(
|
||||
"list-child",
|
||||
BlockSpec::List {
|
||||
list_type: ListType::Bulleted,
|
||||
text: "child".into(),
|
||||
checked: false,
|
||||
order: None,
|
||||
},
|
||||
Some("list-parent"),
|
||||
None,
|
||||
1,
|
||||
)?;
|
||||
Ok(())
|
||||
})
|
||||
.expect("seed nested list");
|
||||
session.view(|view, cx| view.set_document(state, cx));
|
||||
let _ = session.frame();
|
||||
|
||||
set_caret(&session, "list-parent", 2);
|
||||
send_key(&session, "escape", ui::Modifiers::default());
|
||||
assert_eq!(
|
||||
session.view(|v, _| v.block_selection().to_vec()),
|
||||
vec!["list-parent".to_string()]
|
||||
);
|
||||
|
||||
// Direct printable typing while whole-block selection is active must not corrupt page title.
|
||||
type_text(&session, "ignored");
|
||||
assert_eq!(
|
||||
session.view(|v, _| v.block_text("page-root").unwrap_or("").to_string()),
|
||||
"Nested Delete"
|
||||
);
|
||||
|
||||
// Backspace deletes parent + nested child and creates a surviving empty paragraph.
|
||||
send_key(&session, "backspace", ui::Modifiers::default());
|
||||
let _ = session.frame();
|
||||
let focus_after_del = session.view(|view, _| {
|
||||
let snap = view.page_snapshot().unwrap();
|
||||
assert!(snap.block("list-parent").is_none());
|
||||
assert!(snap.block("list-child").is_none());
|
||||
let focus_id = view
|
||||
.document_selection()
|
||||
.expect("fallback selection")
|
||||
.focus
|
||||
.block_id
|
||||
.clone();
|
||||
assert!(
|
||||
snap.block(&focus_id).is_some(),
|
||||
"caret must point to a surviving block, not deleted child"
|
||||
);
|
||||
focus_id
|
||||
});
|
||||
|
||||
type_text(&session, "hello");
|
||||
assert_eq!(
|
||||
session.view(|v, _| v.block_text(&focus_after_del).unwrap_or("").to_string()),
|
||||
"hello"
|
||||
);
|
||||
|
||||
// Undo reverts typing and then restores the deleted parent + nested child subtree.
|
||||
send_key(&session, "z", cmd_mod());
|
||||
assert_eq!(
|
||||
session.view(|v, _| v.block_text(&focus_after_del).unwrap_or("").to_string()),
|
||||
""
|
||||
);
|
||||
send_key(&session, "z", cmd_mod());
|
||||
session.view(|view, _| {
|
||||
let snap = view.page_snapshot().unwrap();
|
||||
assert!(
|
||||
snap.block("list-parent").is_some(),
|
||||
"undo must restore parent list"
|
||||
);
|
||||
assert!(
|
||||
snap.block("list-child").is_some(),
|
||||
"undo must restore nested child list"
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -623,10 +623,14 @@ mod tests {
|
||||
assert_eq!(ids("code"), ["code"]);
|
||||
assert_eq!(ids("quote"), ["quote"]);
|
||||
assert_eq!(ids("div"), ["divider"]);
|
||||
assert_eq!(ids("linked"), ["linked_page"]);
|
||||
assert_eq!(ids("linked"), ["linked_doc"]);
|
||||
assert_eq!(ids("newdoc"), ["new_doc"]);
|
||||
assert_eq!(ids("tdl"), ["todo", "bulleted"]);
|
||||
assert_eq!(ids("do")[0], "new_doc");
|
||||
assert_eq!(ids("h")[0], "h1");
|
||||
assert_eq!(ids("HEADING"), ["h1", "h2", "h3", "h4", "h5", "h6"]);
|
||||
assert_eq!(ids("heading 3"), ["h3"]);
|
||||
assert_eq!(ids("list"), ["bulleted", "numbered", "todo", "toggle"]);
|
||||
assert_eq!(ids("list"), ["todo", "toggle", "bulleted", "numbered"]);
|
||||
assert!(ids("zzz").is_empty());
|
||||
// Every generated icon exists.
|
||||
for item in &SLASH_ITEMS {
|
||||
@@ -648,7 +652,7 @@ mod tests {
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(headers, ["Basic", "List"]);
|
||||
// BlockSuite's order: text, the headings, code, quote, divider, linked page, then the lists.
|
||||
// BlockSuite's order: text, the headings, code, quote, divider, new doc, linked doc, then the lists.
|
||||
assert_eq!(
|
||||
ids(""),
|
||||
[
|
||||
@@ -662,7 +666,8 @@ mod tests {
|
||||
"code",
|
||||
"quote",
|
||||
"divider",
|
||||
"linked_page",
|
||||
"new_doc",
|
||||
"linked_doc",
|
||||
"bulleted",
|
||||
"numbered",
|
||||
"todo",
|
||||
@@ -670,7 +675,7 @@ mod tests {
|
||||
]
|
||||
);
|
||||
assert_eq!(rows.first().map(|(_, y, _)| *y), Some(0.0));
|
||||
assert!(matches!(rows.last(), Some((SlashRow::Item(14), _, _))));
|
||||
assert!(matches!(rows.last(), Some((SlashRow::Item(15), _, _))));
|
||||
let (_, last_y, last_height) = rows[rows.len() - 1];
|
||||
assert_eq!(last_y + last_height, height);
|
||||
for pair in rows.windows(2) {
|
||||
@@ -2267,21 +2272,18 @@ mod tests {
|
||||
assert_eq!(session.written(), written);
|
||||
assert_eq!(parent(&session), place);
|
||||
|
||||
// Without a match they do nothing, and `Enter` closes the menu instead of
|
||||
// splitting the block.
|
||||
// Without a match `Tab` does nothing, while `Enter` closes the in-document menu
|
||||
// and passes through to split the block (C.2).
|
||||
session.insert("zzz");
|
||||
let written = session.written();
|
||||
let count = session.children("showcase-note").len();
|
||||
session.key("tab");
|
||||
session.shift("tab");
|
||||
assert_eq!(session.slash_query().as_deref(), Some("zzz"));
|
||||
session.key("enter");
|
||||
assert_eq!(session.slash_query(), None);
|
||||
assert_eq!(session.written(), written);
|
||||
assert_eq!(parent(&session), place);
|
||||
assert_eq!(session.children("showcase-note").len(), count);
|
||||
assert_eq!(session.children("showcase-note").len(), count + 1);
|
||||
assert_eq!(session.text("t-keys").plain, "/zzz");
|
||||
assert_eq!(session.caret(), Some(("t-keys".to_string(), 4)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -60,7 +60,7 @@ impl PlaygroundView {
|
||||
}
|
||||
|
||||
/// What the platform's text input sees of the link field: nothing while it is closed.
|
||||
pub(super) fn link_input_state(
|
||||
pub(crate) fn link_input_state(
|
||||
&self,
|
||||
) -> Option<(String, Range<usize>, bool, Option<Range<usize>>)> {
|
||||
let link = self.overlays.link_field()?;
|
||||
@@ -71,7 +71,7 @@ impl PlaygroundView {
|
||||
/// Tell the platform's text input (AppKit, the browser's mirror element) that the
|
||||
/// link field opened, closed, or changed its text, selection or composition since
|
||||
/// `before`: the field and the document take turns being the view's text input.
|
||||
pub(super) fn sync_link_input(
|
||||
pub(crate) fn sync_link_input(
|
||||
&mut self,
|
||||
before: Option<(String, Range<usize>, bool, Option<Range<usize>>)>,
|
||||
window: &mut Window,
|
||||
@@ -110,6 +110,7 @@ impl PlaygroundView {
|
||||
// Peers stop showing the caret, and a typed slash menu has no
|
||||
// caret left to filter by.
|
||||
self.editor.selection = None;
|
||||
self.editor.block_selection.clear();
|
||||
self.announce_selection(cx);
|
||||
self.sync_slash_trigger(cx);
|
||||
window.notify_text_selection_changed(&self.editor_focus);
|
||||
@@ -201,6 +202,7 @@ impl PlaygroundView {
|
||||
self.overlays.pointer_pressed(now_ms);
|
||||
self.sync_link_input(input, window, cx);
|
||||
self.editor.slash_trigger = None;
|
||||
self.editor.block_selection.clear();
|
||||
self.editor_mouse_down(event, window, cx);
|
||||
// A double or triple click selects at once; only a plain press starts a drag the
|
||||
// formatting toolbar waits for.
|
||||
@@ -429,7 +431,7 @@ impl PlaygroundView {
|
||||
/// What the formatting toolbar shows for the editor's selection: `None` unless the
|
||||
/// selection is non-empty, no composition is running, and it covers paragraph or list
|
||||
/// text only. Marks and alignment are read once per selection and document revision.
|
||||
pub(super) fn selection_format(&mut self, layout: &FlowLayout) -> Option<SelectionFormat> {
|
||||
pub(crate) fn selection_format(&mut self, layout: &FlowLayout) -> Option<SelectionFormat> {
|
||||
let selection = self.editor.selection.clone()?;
|
||||
if selection.empty() || self.editor.composing() {
|
||||
return None;
|
||||
|
||||
@@ -161,7 +161,7 @@ impl PlaygroundView {
|
||||
/// whatever text it has left, in place within a flavour and as a fresh block across
|
||||
/// flavours. A divider goes right below the block, followed by an empty paragraph to
|
||||
/// type in when the block was the last of its parent.
|
||||
pub(super) fn run_slash_command(
|
||||
pub(crate) fn run_slash_command(
|
||||
&mut self,
|
||||
block_id: &str,
|
||||
command: SlashCommand,
|
||||
@@ -203,13 +203,20 @@ impl PlaygroundView {
|
||||
.map_or(0, |selection| selection.focus.offset())
|
||||
});
|
||||
|
||||
if command == SlashCommand::LinkedPage {
|
||||
return self.run_linked_page_slash_command(block_id, strip, window, cx);
|
||||
if command == SlashCommand::NewDoc {
|
||||
return self.run_new_doc_slash_command(block_id, offset, strip, window, cx);
|
||||
}
|
||||
if command == SlashCommand::LinkedDoc {
|
||||
return self.run_linked_doc_slash_command(block_id, offset, strip, window, cx);
|
||||
}
|
||||
let fresh = self.fresh_block_id();
|
||||
let trailing = self.fresh_block_id();
|
||||
let text_block =
|
||||
|node: &BlockNode| matches!(node.flavour.as_str(), "affine:paragraph" | "affine:list");
|
||||
let text_block = |node: &BlockNode| {
|
||||
matches!(
|
||||
node.flavour.as_str(),
|
||||
"affine:paragraph" | "affine:list" | "affine:code"
|
||||
)
|
||||
};
|
||||
let plan = if command == SlashCommand::Divider {
|
||||
match parent.children.get(slot + 1) {
|
||||
None => SlashPlan::Divider {
|
||||
@@ -296,46 +303,78 @@ impl PlaygroundView {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Converts a block's remaining text (excluding any typed `/linked...` trigger) into a new
|
||||
/// linked document and replaces the block's text with a standard BlockSuite `LinkedPage`
|
||||
/// inline reference chip in a single undoable step.
|
||||
pub(super) fn run_linked_page_slash_command(
|
||||
/// 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.
|
||||
pub(super) fn run_new_doc_slash_command(
|
||||
&mut self,
|
||||
block_id: &str,
|
||||
offset: u64,
|
||||
strip: Option<(u64, u64)>,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> DocResult {
|
||||
let current_plain = self
|
||||
.page()
|
||||
.and_then(|page| page.read_editable_text(block_id).ok())
|
||||
.map(|(rich, _)| rich.plain)
|
||||
.unwrap_or_default();
|
||||
let total_u16 = current_plain.encode_utf16().count() as u64;
|
||||
let remaining = if let Some((slash, len)) = strip {
|
||||
let units: Vec<u16> = current_plain.encode_utf16().collect();
|
||||
let s = (slash as usize).min(units.len());
|
||||
let e = ((slash + len) as usize).min(units.len());
|
||||
let mut kept = Vec::with_capacity(units.len());
|
||||
kept.extend_from_slice(&units[..s]);
|
||||
kept.extend_from_slice(&units[e..]);
|
||||
String::from_utf16(&kept).unwrap_or_default()
|
||||
} else {
|
||||
current_plain
|
||||
};
|
||||
let title = if remaining.trim().is_empty() {
|
||||
"Untitled".to_string()
|
||||
} else {
|
||||
remaining.trim().to_string()
|
||||
};
|
||||
let summary = self
|
||||
.doc_directory_mut()
|
||||
.create_linked_doc(&title, crate::directory::EditorDocMode::Page, None)
|
||||
.create_linked_doc("Untitled", crate::directory::EditorDocMode::Page, None)
|
||||
.map_err(|err| DocError::InvalidState(err.to_string()))?;
|
||||
let now = self.now_ms(cx) as u64;
|
||||
self.ensure_workspace_page_and_broadcast(&summary, now)
|
||||
.map_err(|err| DocError::InvalidState(err.to_string()))?;
|
||||
self.insert_inline_reference_chip(block_id, 0, total_u16, summary.id.as_str(), window, cx)
|
||||
let delete_len = strip.map_or(0, |(_, len)| len);
|
||||
self.insert_inline_reference_chip(
|
||||
block_id,
|
||||
offset,
|
||||
delete_len,
|
||||
summary.id.as_str(),
|
||||
window,
|
||||
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(
|
||||
&mut self,
|
||||
block_id: &str,
|
||||
offset: u64,
|
||||
strip: Option<(u64, u64)>,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> DocResult {
|
||||
let now = self.now_ms(cx) as u64;
|
||||
let before = self.selection_snapshot();
|
||||
let delete_len = strip.map_or(0, |(_, len)| len);
|
||||
let mut delta = Vec::new();
|
||||
if offset > 0 {
|
||||
delta.push(y_octo::TextDeltaOp::Retain {
|
||||
retain: offset,
|
||||
format: None,
|
||||
});
|
||||
}
|
||||
if delete_len > 0 {
|
||||
delta.push(y_octo::TextDeltaOp::Delete { delete: delete_len });
|
||||
}
|
||||
delta.push(y_octo::TextDeltaOp::Insert {
|
||||
insert: y_octo::TextInsert::Text("@".into()),
|
||||
format: None,
|
||||
});
|
||||
let page = self.page_mut()?;
|
||||
page.stop_capturing()?;
|
||||
let commit = page.apply_text_delta(block_id, "prop:text", &delta, now)?;
|
||||
if commit.is_some()
|
||||
&& let Some(before) = before
|
||||
{
|
||||
page.set_undo_selection_snapshot(before)?;
|
||||
}
|
||||
self.editor.selection = Some(DocumentSelection::caret(DocPoint::new(
|
||||
block_id,
|
||||
offset + 1,
|
||||
)));
|
||||
self.editor.last_typing = None;
|
||||
self.did_edit(commit, Some(block_id), window, cx);
|
||||
self.open_typed_linked_doc_menu(block_id.to_string(), offset, cx);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Inserts a standard BlockSuite `LinkedPage` inline reference chip (single space with
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -39,6 +39,13 @@ pub const IBM_PLEX_MONO_ITALIC_TTF: &[u8] =
|
||||
pub const IBM_PLEX_MONO_BOLD_ITALIC_TTF: &[u8] =
|
||||
include_bytes!("../fonts/ibm-plex-mono/IBMPlexMono-BoldItalic.ttf");
|
||||
|
||||
/// Regular Noto Sans Arabic font face for contextual Arabic shaping.
|
||||
pub const NOTO_SANS_ARABIC_REGULAR_TTF: &[u8] =
|
||||
include_bytes!("../fonts/noto/NotoSansArabic-Regular.ttf");
|
||||
/// Regular Noto Sans Hebrew font face for Hebrew shaping.
|
||||
pub const NOTO_SANS_HEBREW_REGULAR_TTF: &[u8] =
|
||||
include_bytes!("../fonts/noto/NotoSansHebrew-Regular.ttf");
|
||||
|
||||
/// Returns all five bundled repository font byte slices in registration order.
|
||||
pub const fn bundled_font_bytes() -> [&'static [u8]; 5] {
|
||||
[
|
||||
@@ -50,6 +57,11 @@ pub const fn bundled_font_bytes() -> [&'static [u8]; 5] {
|
||||
]
|
||||
}
|
||||
|
||||
/// Returns bundled RTL script fallback fonts (Arabic and Hebrew) for native shaping.
|
||||
pub const fn bundled_script_font_bytes() -> [&'static [u8]; 2] {
|
||||
[NOTO_SANS_ARABIC_REGULAR_TTF, NOTO_SANS_HEBREW_REGULAR_TTF]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -58,7 +70,7 @@ mod tests {
|
||||
fn bundled_fonts_are_non_empty_ttf_blobs() {
|
||||
let fonts = bundled_font_bytes();
|
||||
assert_eq!(fonts.len(), 5);
|
||||
for bytes in fonts {
|
||||
for bytes in fonts.into_iter().chain(bundled_script_font_bytes()) {
|
||||
assert!(bytes.len() > 1024, "font payload is unexpectedly small");
|
||||
let tag = &bytes[..4];
|
||||
assert!(
|
||||
|
||||
@@ -20,9 +20,9 @@ pub enum CanvasFontFallback {
|
||||
/// Use only fonts loaded into GPUI.
|
||||
Disabled,
|
||||
/// Use Canvas for eligible emoji, including missing text-presentation symbols.
|
||||
#[default]
|
||||
Emoji,
|
||||
/// Also allow approximate independent rendering of eligible horizontal CJK text.
|
||||
#[default]
|
||||
EmojiAndCjk,
|
||||
}
|
||||
|
||||
@@ -114,8 +114,15 @@ fn is_cjk(grapheme: &str) -> bool {
|
||||
}
|
||||
|
||||
suffix.is_empty()
|
||||
&& (matches!(base, '\u{3131}'..='\u{3163}')
|
||||
|| "、。〈〉《》「」『』【】〔〕()[]{},.!?:;・ー々〆".contains(base))
|
||||
&& matches!(
|
||||
base,
|
||||
'\u{3000}'..='\u{303f}'
|
||||
| '\u{3131}'..='\u{3163}'
|
||||
| '\u{fe30}'..='\u{fe4f}'
|
||||
| '\u{ff01}'..='\u{ff60}'
|
||||
| '\u{ffe0}'..='\u{ffee}'
|
||||
| '“' | '”' | '‘' | '’' | '—' | '…' | '·' | '・' | 'ー'
|
||||
)
|
||||
}
|
||||
|
||||
fn is_single_modern_trailing_jamo(text: &str) -> bool {
|
||||
|
||||
@@ -2167,7 +2167,7 @@ impl Window {
|
||||
default_prevented: true,
|
||||
mouse_position,
|
||||
mouse_hit_test: HitTest::default(),
|
||||
touch_gestures_enabled: false,
|
||||
touch_gestures_enabled: cfg!(target_arch = "wasm32"),
|
||||
touch_gestures: crate::TouchGestureRecognizer::default(),
|
||||
touch_gesture_epoch: None,
|
||||
last_touch_gestures: SmallVec::new(),
|
||||
@@ -5652,8 +5652,9 @@ impl Window {
|
||||
self.touch_prediction_enabled
|
||||
}
|
||||
|
||||
/// Enables or disables touch gesture recognition on this window. Disabled by default so
|
||||
/// desktop and non-consumer surfaces do not enqueue gestures or schedule redraws on touch.
|
||||
/// Enables or disables touch gesture recognition on this window. Enabled by default on Web
|
||||
/// (`wasm32`) and disabled by default on other platforms so desktop and non-consumer surfaces
|
||||
/// do not enqueue gestures or schedule redraws on touch.
|
||||
pub fn set_touch_gestures_enabled(&mut self, enabled: bool) {
|
||||
self.touch_gestures_enabled = enabled;
|
||||
if !enabled {
|
||||
@@ -5668,6 +5669,7 @@ impl Window {
|
||||
if !self.touch_gestures_enabled {
|
||||
return;
|
||||
}
|
||||
self.mouse_position = event.position;
|
||||
let now = cx.background_executor().now();
|
||||
let epoch = *self.touch_gesture_epoch.get_or_insert(now);
|
||||
let now_ms = now.saturating_duration_since(epoch).as_millis() as u64;
|
||||
@@ -5677,7 +5679,29 @@ impl Window {
|
||||
.touch_gestures
|
||||
.feed(event, now_ms, direction, viewport_width);
|
||||
if !gestures.is_empty() {
|
||||
self.last_touch_gestures.extend(gestures);
|
||||
self.last_touch_gestures.extend(gestures.iter().copied());
|
||||
for gesture in gestures {
|
||||
match gesture {
|
||||
crate::TouchGesture::Tap { position, count } => {
|
||||
self.bridge_touch_tap(position, count as usize, cx);
|
||||
}
|
||||
crate::TouchGesture::PanUpdate {
|
||||
position, delta, ..
|
||||
} => {
|
||||
self.mouse_position = position;
|
||||
cx.propagate_event = true;
|
||||
let scroll = crate::ScrollEvent {
|
||||
position,
|
||||
delta: crate::ScrollDelta::Pixels(delta),
|
||||
modifiers: Modifiers::default(),
|
||||
touch_phase: crate::TouchPhase::Moved,
|
||||
source: crate::ScrollSource::Touch,
|
||||
};
|
||||
self.dispatch_mouse_event(&scroll, cx);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
self.refresh();
|
||||
}
|
||||
if event.phase == crate::TouchPhase::Started {
|
||||
@@ -5701,6 +5725,27 @@ impl Window {
|
||||
}
|
||||
}
|
||||
|
||||
fn bridge_touch_tap(&mut self, position: Point<Pixels>, click_count: usize, cx: &mut App) {
|
||||
self.mouse_position = position;
|
||||
cx.propagate_event = true;
|
||||
let down = crate::MouseDownEvent {
|
||||
button: MouseButton::Left,
|
||||
position,
|
||||
modifiers: Modifiers::default(),
|
||||
click_count,
|
||||
first_mouse: false,
|
||||
};
|
||||
self.dispatch_mouse_event(&down, cx);
|
||||
cx.propagate_event = true;
|
||||
let up = crate::MouseUpEvent {
|
||||
button: MouseButton::Left,
|
||||
position,
|
||||
modifiers: Modifiers::default(),
|
||||
click_count,
|
||||
};
|
||||
self.dispatch_mouse_event(&up, cx);
|
||||
}
|
||||
|
||||
/// Returns and clears touch gestures recognized during recent touch dispatch.
|
||||
pub fn take_touch_gestures(&mut self) -> SmallVec<[crate::TouchGesture; 2]> {
|
||||
std::mem::take(&mut self.last_touch_gestures)
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
use std::{cell::RefCell, rc::Rc};
|
||||
|
||||
use ui::{
|
||||
Application, Bounds, Context, HeadlessPlatform, IntoElement, MouseButton, MouseDownEvent,
|
||||
MouseUpEvent, PlatformInput, Render, TouchEvent, TouchId, TouchPhase, Window, WindowBounds,
|
||||
WindowHandle, WindowOptions, div, point, prelude::*, px, size,
|
||||
};
|
||||
|
||||
struct TouchProbeView {
|
||||
downs: Rc<RefCell<Vec<usize>>>,
|
||||
ups: Rc<RefCell<Vec<usize>>>,
|
||||
}
|
||||
|
||||
impl Render for TouchProbeView {
|
||||
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let downs = self.downs.clone();
|
||||
let ups = self.ups.clone();
|
||||
div()
|
||||
.size_full()
|
||||
.on_mouse_down(MouseButton::Left, move |ev: &MouseDownEvent, _, _| {
|
||||
downs.borrow_mut().push(ev.click_count);
|
||||
})
|
||||
.on_mouse_up(MouseButton::Left, move |ev: &MouseUpEvent, _, _| {
|
||||
ups.borrow_mut().push(ev.click_count);
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn touch_gestures_opt_in_off_wasm_and_double_tap_dispatches_two_clicks_not_three() {
|
||||
let platform = HeadlessPlatform::new(390, 844, 1.0);
|
||||
let downs = Rc::new(RefCell::new(Vec::new()));
|
||||
let ups = Rc::new(RefCell::new(Vec::new()));
|
||||
let handle_cell: Rc<RefCell<Option<WindowHandle<TouchProbeView>>>> =
|
||||
Rc::new(RefCell::new(None));
|
||||
let handle_out = handle_cell.clone();
|
||||
let d = downs.clone();
|
||||
let u = ups.clone();
|
||||
let app = Application::with_platform(platform.clone()).run_embedded(move |cx| {
|
||||
let window = cx
|
||||
.open_window(
|
||||
WindowOptions {
|
||||
window_bounds: Some(WindowBounds::Windowed(Bounds::new(
|
||||
point(px(0.0), px(0.0)),
|
||||
size(px(390.0), px(844.0)),
|
||||
))),
|
||||
..WindowOptions::default()
|
||||
},
|
||||
|_, cx| cx.new(|_| TouchProbeView { downs: d, ups: u }),
|
||||
)
|
||||
.expect("open headless window");
|
||||
*handle_out.borrow_mut() = Some(window);
|
||||
});
|
||||
let window = handle_cell.borrow_mut().take().expect("window handle");
|
||||
let headless = platform.windows().into_iter().next().expect("headless win");
|
||||
headless.request_frame();
|
||||
|
||||
let tap_pos = point(px(120.0), px(200.0));
|
||||
let send_tap = |id: u64| {
|
||||
headless.dispatch_input(PlatformInput::Touch(TouchEvent {
|
||||
id: TouchId(id),
|
||||
phase: TouchPhase::Started,
|
||||
position: tap_pos,
|
||||
predicted_position: None,
|
||||
force: None,
|
||||
}));
|
||||
headless.dispatch_input(PlatformInput::Touch(TouchEvent {
|
||||
id: TouchId(id),
|
||||
phase: TouchPhase::Ended,
|
||||
position: tap_pos,
|
||||
predicted_position: None,
|
||||
force: None,
|
||||
}));
|
||||
};
|
||||
|
||||
// Non-wasm windows disable touch gesture bridging by default.
|
||||
send_tap(1);
|
||||
assert!(
|
||||
downs.borrow().is_empty() && ups.borrow().is_empty(),
|
||||
"non-wasm window must not bridge touch taps until opted in"
|
||||
);
|
||||
|
||||
// After enabling touch gestures, two physical taps must emit click_count [1, 2] (not [1, 2, 2]).
|
||||
app.update(|cx| {
|
||||
window
|
||||
.update(cx, |_, window, _| {
|
||||
window.set_touch_gestures_enabled(true);
|
||||
})
|
||||
.expect("enable touch gestures");
|
||||
});
|
||||
|
||||
send_tap(2);
|
||||
send_tap(3);
|
||||
|
||||
assert_eq!(*downs.borrow(), vec![1, 2]);
|
||||
assert_eq!(*ups.borrow(), vec![1, 2]);
|
||||
}
|
||||
Reference in new issue
Block a user