mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-05 11:15:01 +03:00
fix(editor): resolve and dismiss desktop reference popups
This commit is contained in:
1 parent
f447fbee6a
commit
9e9e564d3b
5 files changed
+1164
-210
No files matched your search
@@ -3,9 +3,8 @@
|
||||
//! non-editable media/embed block selection, inline link/`@ref` clicks, and text carets.
|
||||
|
||||
use blocksuite_editor::{
|
||||
block_flow::{FlowBlock, FlowKind, FlowRect},
|
||||
block_flow::{FlowKind, FlowRect},
|
||||
overlays::{LinkPopupTarget, OverlayEvent},
|
||||
rich_text::DecorationKind,
|
||||
};
|
||||
use ui::{Context, MouseDownEvent, Window};
|
||||
|
||||
@@ -313,62 +312,7 @@ impl PlaygroundView {
|
||||
.blocks
|
||||
.iter()
|
||||
.find(|b| b.rect().contains(flow_x, flow_y))?;
|
||||
self.active_note_link_in_block(block, flow_x, flow_y)
|
||||
}
|
||||
|
||||
fn active_note_link_in_block(
|
||||
&self,
|
||||
block: &FlowBlock,
|
||||
flow_x: f32,
|
||||
flow_y: f32,
|
||||
) -> Option<(LinkPopupTarget, FlowRect)> {
|
||||
let text = block.body.text.as_ref()?;
|
||||
let lx = flow_x - (block.x + text.x);
|
||||
let ly = flow_y - (block.y + text.y);
|
||||
for deco in text.layout.decorations() {
|
||||
let b = deco.bounds;
|
||||
let bx = f32::from(b.origin.x);
|
||||
let by = f32::from(b.origin.y);
|
||||
let bw = f32::from(b.size.width);
|
||||
let bh = f32::from(b.size.height);
|
||||
if lx < bx || lx > bx + bw || ly < by || ly > by + bh {
|
||||
continue;
|
||||
}
|
||||
let anchor = FlowRect::new(block.x + text.x + bx, block.y + text.y + by, bw, bh);
|
||||
match &deco.kind {
|
||||
DecorationKind::Link(url) => {
|
||||
return Some((
|
||||
LinkPopupTarget::Link {
|
||||
block_id: block.block_id.clone(),
|
||||
start_utf16: deco.source_utf16.start as usize,
|
||||
end_utf16: deco.source_utf16.end as usize,
|
||||
url: url.clone(),
|
||||
},
|
||||
anchor,
|
||||
));
|
||||
}
|
||||
DecorationKind::ReferenceChip(inline_ref) => {
|
||||
let page_id = inline_ref.page_id.clone();
|
||||
let title = self
|
||||
.page_titles
|
||||
.get(&page_id)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| "Untitled".to_string());
|
||||
return Some((
|
||||
LinkPopupTarget::Reference {
|
||||
block_id: block.block_id.clone(),
|
||||
utf16_offset: deco.source_utf16.start as usize,
|
||||
page_id,
|
||||
title,
|
||||
can_convert: true,
|
||||
can_embed: true,
|
||||
},
|
||||
anchor,
|
||||
));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
let (target, anchor, _) = self.link_or_ref_in_block(block, flow_x, flow_y, None)?;
|
||||
Some((self.map_target_for_preedit_commit(target)?, anchor))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,545 @@
|
||||
use std::{cell::Cell, rc::Rc, time::Duration};
|
||||
|
||||
use blocksuite_playground_doc::schema::{BlockSpec, ParagraphType};
|
||||
use ui::{
|
||||
Application, ApplicationHandle, Bounds, Context, Entity, EntityInputHandler, FrameSnapshot,
|
||||
HeadlessPlatform, HeadlessWindow, Modifiers, MouseButton, MouseDownEvent, MouseExitEvent,
|
||||
MouseMoveEvent, Pixels, PlatformInput, Point, Window, WindowBounds, WindowHandle,
|
||||
WindowOptions, div, point, prelude::*, px, size,
|
||||
};
|
||||
use y_octo::{Any, TextAttributes};
|
||||
|
||||
use crate::{
|
||||
PlaygroundMode, PlaygroundOptions, PlaygroundView,
|
||||
block_flow::FlowRect,
|
||||
directory::{EditorDocId, EditorDocPreview, InMemoryDocDirectory},
|
||||
editor_session::{DocPoint, DocumentSelection},
|
||||
overlays::{LINK_HOVER_DELAY_MS, OVERLAY_MOTION_MS},
|
||||
rich_text::DecorationKind,
|
||||
room_client::DocState,
|
||||
theme::register_bundled_fonts,
|
||||
};
|
||||
|
||||
use super::{LinkPopupTarget, reference_at};
|
||||
|
||||
const POPUP: &str = "overlay.link_popup";
|
||||
const OPEN: &str = "overlay.link_popup.open";
|
||||
const TITLE: &str = "Offline Sync Protocol v1";
|
||||
const ARCH: &str = "doc-arch";
|
||||
const SYNC: &str = "doc-sync";
|
||||
|
||||
struct Host {
|
||||
editor: Entity<PlaygroundView>,
|
||||
panel: Option<Bounds<Pixels>>,
|
||||
}
|
||||
|
||||
impl Render for Host {
|
||||
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
|
||||
div()
|
||||
.relative()
|
||||
.size_full()
|
||||
.child(
|
||||
div()
|
||||
.absolute()
|
||||
.left(px(240.0))
|
||||
.top_0()
|
||||
.w(px(1040.0))
|
||||
.h(px(800.0))
|
||||
.child(self.editor.clone()),
|
||||
)
|
||||
.children(self.panel.map(|bounds| {
|
||||
div()
|
||||
.absolute()
|
||||
.left(bounds.origin.x)
|
||||
.top(bounds.origin.y)
|
||||
.w(bounds.size.width)
|
||||
.h(bounds.size.height)
|
||||
.occlude()
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
struct Desktop {
|
||||
platform: Rc<HeadlessPlatform>,
|
||||
app: ApplicationHandle,
|
||||
handle: WindowHandle<Host>,
|
||||
window: HeadlessWindow,
|
||||
}
|
||||
|
||||
fn directory(title: &str) -> InMemoryDocDirectory {
|
||||
let mut directory = InMemoryDocDirectory::new();
|
||||
directory.upsert_preview(
|
||||
EditorDocId::from(SYNC),
|
||||
EditorDocPreview {
|
||||
title: title.into(),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
directory
|
||||
}
|
||||
|
||||
impl Desktop {
|
||||
fn open() -> Self {
|
||||
Self::open_with_references("See here", &[(4, None)])
|
||||
}
|
||||
|
||||
fn open_with_references(text: &str, references: &[(u64, Option<&str>)]) -> Self {
|
||||
let mut document = DocState::new(ARCH, 94).unwrap();
|
||||
document
|
||||
.workspace
|
||||
.create_page(ARCH, "Architecture", 1)
|
||||
.unwrap();
|
||||
let page = document.workspace.page_mut(ARCH).unwrap();
|
||||
for (id, spec, parent) in [
|
||||
(
|
||||
"page",
|
||||
BlockSpec::Page {
|
||||
title: "Architecture".into(),
|
||||
},
|
||||
None,
|
||||
),
|
||||
("surface", BlockSpec::Surface, Some("page")),
|
||||
(
|
||||
"note",
|
||||
BlockSpec::Note {
|
||||
xywh: Some("[40,60,520,420]".into()),
|
||||
},
|
||||
Some("page"),
|
||||
),
|
||||
(
|
||||
"p",
|
||||
BlockSpec::Paragraph {
|
||||
paragraph_type: ParagraphType::Text,
|
||||
text: text.into(),
|
||||
},
|
||||
Some("note"),
|
||||
),
|
||||
] {
|
||||
page.add_block(id, spec, parent, None, 2).unwrap();
|
||||
}
|
||||
for &(offset, title) in references {
|
||||
let mut reference = y_octo::AHashMap::from_iter([
|
||||
("type".into(), Any::String("LinkedPage".into())),
|
||||
("pageId".into(), Any::String(SYNC.into())),
|
||||
]);
|
||||
if let Some(title) = title {
|
||||
reference.insert("title".into(), Any::String(title.into()));
|
||||
}
|
||||
page.format_text(
|
||||
"p",
|
||||
"prop:text",
|
||||
offset,
|
||||
1,
|
||||
TextAttributes::from([("reference".into(), Any::Object(Box::new(reference)))]),
|
||||
3,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let platform = HeadlessPlatform::new(1280, 800, 1.0);
|
||||
let handle = Rc::new(Cell::new(None));
|
||||
let output = handle.clone();
|
||||
let app = Application::with_platform(platform.clone()).run_embedded(move |cx| {
|
||||
register_bundled_fonts(cx).unwrap();
|
||||
let editor = cx.new(|cx| {
|
||||
let mut view = PlaygroundView::with_options(
|
||||
PlaygroundOptions {
|
||||
hide_chrome: true,
|
||||
..Default::default()
|
||||
},
|
||||
cx,
|
||||
);
|
||||
view.set_embedded_bounds(1040.0, 800.0);
|
||||
view.set_doc_directory(Box::new(directory(TITLE)));
|
||||
view.set_document(document, cx);
|
||||
view.set_active_page_id(ARCH, cx);
|
||||
view
|
||||
});
|
||||
output.set(Some(
|
||||
cx.open_window(
|
||||
WindowOptions {
|
||||
window_bounds: Some(WindowBounds::Windowed(Bounds::new(
|
||||
point(px(0.0), px(0.0)),
|
||||
size(px(1280.0), px(800.0)),
|
||||
))),
|
||||
..Default::default()
|
||||
},
|
||||
|_, cx| {
|
||||
cx.new(|_| Host {
|
||||
editor,
|
||||
panel: None,
|
||||
})
|
||||
},
|
||||
)
|
||||
.unwrap(),
|
||||
));
|
||||
});
|
||||
let handle = handle.take().unwrap();
|
||||
let window = platform.windows().into_iter().next().unwrap();
|
||||
let desktop = Self {
|
||||
platform,
|
||||
app,
|
||||
handle,
|
||||
window,
|
||||
};
|
||||
desktop.frame();
|
||||
desktop
|
||||
}
|
||||
|
||||
fn editor<R>(
|
||||
&self,
|
||||
f: impl FnOnce(&mut PlaygroundView, &mut Window, &mut Context<PlaygroundView>) -> R,
|
||||
) -> R {
|
||||
self.app.update(|app| {
|
||||
self.handle
|
||||
.update(app, |host, window, cx| {
|
||||
host.editor.update(cx, |editor, cx| f(editor, window, cx))
|
||||
})
|
||||
.unwrap()
|
||||
})
|
||||
}
|
||||
|
||||
fn frame(&self) -> FrameSnapshot {
|
||||
self.window.request_frame();
|
||||
self.platform.run_until_parked();
|
||||
self.app.update(|app| {
|
||||
self.handle
|
||||
.update(app, |_, window, _| window.frame_snapshot().clone())
|
||||
.unwrap()
|
||||
})
|
||||
}
|
||||
|
||||
fn advance(&self, ms: f64) -> FrameSnapshot {
|
||||
self.platform
|
||||
.advance_clock(Duration::from_millis(ms as u64));
|
||||
self.platform.run_until_parked();
|
||||
self.frame()
|
||||
}
|
||||
|
||||
fn input(&self, input: PlatformInput) {
|
||||
self.window.dispatch_input(input);
|
||||
self.platform.run_until_parked();
|
||||
}
|
||||
|
||||
fn move_to(&self, position: Point<Pixels>) {
|
||||
self.input(PlatformInput::MouseMove(MouseMoveEvent {
|
||||
position,
|
||||
..Default::default()
|
||||
}));
|
||||
}
|
||||
|
||||
fn panel(&self, panel: Option<Bounds<Pixels>>) {
|
||||
self.app.update(|app| {
|
||||
self.handle
|
||||
.update(app, |host, _, cx| {
|
||||
host.panel = panel;
|
||||
cx.notify();
|
||||
})
|
||||
.unwrap()
|
||||
});
|
||||
self.frame();
|
||||
}
|
||||
|
||||
fn reference_point(&self) -> Point<Pixels> {
|
||||
self.reference_point_at(4)
|
||||
}
|
||||
|
||||
fn reference_point_at(&self, offset: u64) -> Point<Pixels> {
|
||||
self.editor(|v, window, _| {
|
||||
let (_, layout, transform) = v.active_overlay_target().unwrap();
|
||||
let block = layout.block("p").unwrap();
|
||||
let text = block.body.text.as_ref().unwrap();
|
||||
let deco = text
|
||||
.layout
|
||||
.decorations()
|
||||
.iter()
|
||||
.find(|d| {
|
||||
d.source_utf16.start == offset
|
||||
&& matches!(d.kind, DecorationKind::ReferenceChip(_))
|
||||
})
|
||||
.unwrap();
|
||||
let x =
|
||||
block.x + text.x + f32::from(deco.bounds.origin.x + deco.bounds.size.width / 2.0);
|
||||
let y =
|
||||
block.y + text.y + f32::from(deco.bounds.origin.y + deco.bounds.size.height / 2.0);
|
||||
if let Some(transform) = transform {
|
||||
let screen = transform.rect_to_screen(&FlowRect::new(x, y, 0.0, 0.0));
|
||||
return point(px(screen.x), px(screen.y));
|
||||
}
|
||||
let (origin, size) = v.canvas_rect(window);
|
||||
let geom = v.current_page_geometry(size.width.into());
|
||||
origin + point(px(geom.column_x + x), px(y - v.scroll_offset()))
|
||||
})
|
||||
}
|
||||
|
||||
fn open_hover(&self, chip: Point<Pixels>) -> FrameSnapshot {
|
||||
self.move_to(chip);
|
||||
self.frame();
|
||||
self.advance(LINK_HOVER_DELAY_MS);
|
||||
self.advance(OVERLAY_MOTION_MS + 1.0)
|
||||
}
|
||||
}
|
||||
|
||||
fn center(frame: &FrameSnapshot, id: &str) -> Point<Pixels> {
|
||||
let bounds = frame.elements[id].bounds;
|
||||
point(
|
||||
px(bounds.x + bounds.width / 2.0),
|
||||
px(bounds.y + bounds.height / 2.0),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn desktop_cross_document_title_updates_for_page_hover_caret_and_active_note() {
|
||||
let desktop = Desktop::open();
|
||||
desktop.editor(|v, _, _| assert!(v.state.workspace.page(SYNC).is_none()));
|
||||
let chip = desktop.reference_point();
|
||||
assert_eq!(
|
||||
desktop.open_hover(chip).elements[OPEN].text.as_deref(),
|
||||
Some(TITLE)
|
||||
);
|
||||
for from_hover in [true, false] {
|
||||
if !from_hover {
|
||||
desktop.editor(|v, window, cx| {
|
||||
v.change_selection(DocumentSelection::caret(DocPoint::new("p", 4)), window, cx);
|
||||
});
|
||||
}
|
||||
for title in [TITLE, "Offline Sync Protocol v2", ""] {
|
||||
desktop.editor(|v, _, cx| {
|
||||
v.set_doc_directory(Box::new(directory(title)));
|
||||
v.env_rev += 1;
|
||||
cx.notify();
|
||||
});
|
||||
let frame = desktop.advance(OVERLAY_MOTION_MS + 1.0);
|
||||
let expected = if title.is_empty() { "Untitled" } else { title };
|
||||
assert_eq!(frame.elements[OPEN].text.as_deref(), Some(expected));
|
||||
desktop.editor(|v, _, _| {
|
||||
assert_eq!(v.overlays.link_popup().unwrap().from_hover, from_hover);
|
||||
});
|
||||
}
|
||||
}
|
||||
desktop.editor(|v, _, cx| {
|
||||
v.set_doc_directory(Box::new(directory(TITLE)));
|
||||
v.env_rev += 1;
|
||||
v.set_mode_immediate(PlaygroundMode::Edgeless, cx);
|
||||
v.set_edgeless_camera(-200.0, -140.0, 1.0, cx);
|
||||
});
|
||||
desktop.frame();
|
||||
desktop.editor(|v, window, cx| assert!(v.edgeless_begin_inline_edit("note", window, cx)));
|
||||
desktop.frame();
|
||||
let chip = desktop.reference_point();
|
||||
assert_eq!(
|
||||
desktop.open_hover(chip).elements[OPEN].text.as_deref(),
|
||||
Some(TITLE)
|
||||
);
|
||||
desktop.window.simulate_click(chip);
|
||||
assert_eq!(
|
||||
desktop.advance(OVERLAY_MOTION_MS + 1.0).elements[OPEN]
|
||||
.text
|
||||
.as_deref(),
|
||||
Some(TITLE)
|
||||
);
|
||||
desktop.editor(|v, _, _| assert!(!v.overlays.link_popup().unwrap().from_hover));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn desktop_reference_keeps_its_alias_when_clicked_before_the_preedit_frame() {
|
||||
check_clicked_reference_after_preedit(None, false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn desktop_reference_keeps_its_alias_when_clicked_after_the_preedit_frame() {
|
||||
check_clicked_reference_after_preedit(None, true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn desktop_reference_keeps_its_alias_when_clicked_between_preedit_updates() {
|
||||
check_clicked_reference_after_preedit(Some("𠮷abc"), false);
|
||||
}
|
||||
|
||||
fn check_clicked_reference_after_preedit(earlier_preedit: Option<&str>, render_preedit: bool) {
|
||||
for mode in [PlaygroundMode::Page, PlaygroundMode::Edgeless] {
|
||||
let desktop = Desktop::open_with_references(
|
||||
"See xx here",
|
||||
&[(4, Some("Alias A")), (7, Some("Alias B"))],
|
||||
);
|
||||
if mode == PlaygroundMode::Edgeless {
|
||||
desktop.editor(|v, _, cx| {
|
||||
v.set_mode_immediate(mode, cx);
|
||||
v.set_edgeless_camera(-200.0, -140.0, 1.0, cx);
|
||||
});
|
||||
desktop.frame();
|
||||
desktop.editor(|v, w, cx| assert!(v.edgeless_begin_inline_edit("note", w, cx)));
|
||||
desktop.frame();
|
||||
}
|
||||
let preedit = "𠮷a";
|
||||
let moved = 10;
|
||||
if let Some(earlier) = earlier_preedit {
|
||||
desktop.editor(|v, w, cx| {
|
||||
v.select_document_range(DocumentSelection::caret(DocPoint::new("p", 0)), w, cx);
|
||||
v.replace_and_mark_text_in_range(None, earlier, None, w, cx);
|
||||
});
|
||||
desktop.frame();
|
||||
}
|
||||
let old_offset = 7 + earlier_preedit.map_or(0, |text| text.encode_utf16().count() as u64);
|
||||
let old_chip = desktop.reference_point_at(old_offset);
|
||||
let check_popup = |from_hover| {
|
||||
desktop.editor(|v, _, _| {
|
||||
let popup = v.overlays.link_popup().unwrap();
|
||||
assert_eq!(popup.from_hover, from_hover);
|
||||
assert!(
|
||||
matches!(
|
||||
&popup.target,
|
||||
LinkPopupTarget::Reference { block_id, utf16_offset, page_id, .. }
|
||||
if block_id == "p" && *utf16_offset == moved && page_id == SYNC
|
||||
),
|
||||
"{mode:?}, preedit frame {render_preedit}, popup {:?}",
|
||||
popup.target
|
||||
);
|
||||
});
|
||||
};
|
||||
desktop.editor(|v, w, cx| {
|
||||
if earlier_preedit.is_none() {
|
||||
v.select_document_range(DocumentSelection::caret(DocPoint::new("p", 0)), w, cx);
|
||||
}
|
||||
v.replace_and_mark_text_in_range(None, preedit, None, w, cx);
|
||||
assert!(v.editor.composing());
|
||||
let (text, _) = v.page().unwrap().read_editable_text("p").unwrap();
|
||||
assert_eq!(reference_at(&text, 4), Some((4, SYNC.into())));
|
||||
assert_eq!(reference_at(&text, 7), Some((7, SYNC.into())));
|
||||
});
|
||||
let chip = if render_preedit {
|
||||
desktop.frame();
|
||||
let chip = desktop.reference_point_at(moved as u64);
|
||||
assert_ne!(chip, old_chip);
|
||||
assert_eq!(
|
||||
desktop.open_hover(chip).elements[OPEN].text.as_deref(),
|
||||
Some(TITLE)
|
||||
);
|
||||
check_popup(true);
|
||||
desktop.editor(|v, _, _| assert!(v.editor.composing()));
|
||||
chip
|
||||
} else {
|
||||
old_chip
|
||||
};
|
||||
desktop.window.simulate_click(chip);
|
||||
desktop.editor(|v, _, _| {
|
||||
assert!(!v.editor.composing());
|
||||
let (text, _) = v.page().unwrap().read_editable_text("p").unwrap();
|
||||
assert!(text.plain.starts_with(preedit));
|
||||
assert_eq!(reference_at(&text, 4), None);
|
||||
assert_eq!(reference_at(&text, 7), Some((7, SYNC.into())));
|
||||
assert_eq!(reference_at(&text, moved), Some((moved, SYNC.into())));
|
||||
});
|
||||
check_popup(false);
|
||||
assert_eq!(
|
||||
desktop.advance(OVERLAY_MOTION_MS + 1.0).elements[OPEN]
|
||||
.text
|
||||
.as_deref(),
|
||||
Some(TITLE),
|
||||
);
|
||||
check_popup(false);
|
||||
|
||||
for (title, expected) in [
|
||||
("Offline Sync Protocol v2", "Offline Sync Protocol v2"),
|
||||
("", "Alias B"),
|
||||
] {
|
||||
desktop.editor(|v, _, cx| {
|
||||
v.set_doc_directory(Box::new(directory(title)));
|
||||
cx.notify();
|
||||
});
|
||||
assert_eq!(
|
||||
desktop.frame().elements[OPEN].text.as_deref(),
|
||||
Some(expected)
|
||||
);
|
||||
check_popup(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn desktop_hover_survives_its_menu_and_closes_on_occlusion_or_exit() {
|
||||
let desktop = Desktop::open();
|
||||
let panel = Bounds::new(point(px(1040.0), px(200.0)), size(px(220.0), px(200.0)));
|
||||
desktop.panel(Some(panel));
|
||||
let chip = desktop.reference_point();
|
||||
let covered = point(px(1150.0), px(300.0));
|
||||
let sidebar = point(px(100.0), px(300.0));
|
||||
let frame = desktop.open_hover(chip);
|
||||
let view = center(&frame, "overlay.link_popup.view");
|
||||
desktop.move_to(view);
|
||||
assert!(desktop.frame().elements.contains_key(OPEN));
|
||||
desktop.window.simulate_click(view);
|
||||
let frame = desktop.frame();
|
||||
let submenu = center(&frame, "overlay.link_popup.view_menu");
|
||||
desktop.move_to(submenu);
|
||||
assert!(
|
||||
desktop
|
||||
.advance(LINK_HOVER_DELAY_MS)
|
||||
.elements
|
||||
.contains_key(OPEN)
|
||||
);
|
||||
desktop.move_to(covered);
|
||||
assert!(
|
||||
!desktop
|
||||
.advance(OVERLAY_MOTION_MS + 1.0)
|
||||
.elements
|
||||
.contains_key(POPUP)
|
||||
);
|
||||
|
||||
for destination in [covered, sidebar] {
|
||||
desktop.move_to(chip);
|
||||
desktop.frame();
|
||||
desktop.move_to(destination);
|
||||
assert!(
|
||||
!desktop
|
||||
.advance(LINK_HOVER_DELAY_MS)
|
||||
.elements
|
||||
.contains_key(POPUP)
|
||||
);
|
||||
}
|
||||
|
||||
assert!(desktop.open_hover(chip).elements.contains_key(OPEN));
|
||||
desktop.input(PlatformInput::MouseExited(MouseExitEvent {
|
||||
position: point(px(1300.0), px(800.0)),
|
||||
..Default::default()
|
||||
}));
|
||||
assert!(
|
||||
!desktop
|
||||
.advance(OVERLAY_MOTION_MS + 1.0)
|
||||
.elements
|
||||
.contains_key(POPUP)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn desktop_hover_cancels_on_shift_click_and_stationary_modal_cover() {
|
||||
let desktop = Desktop::open();
|
||||
let chip = desktop.reference_point();
|
||||
assert!(desktop.open_hover(chip).elements.contains_key(OPEN));
|
||||
desktop.input(PlatformInput::MouseDown(MouseDownEvent {
|
||||
button: MouseButton::Left,
|
||||
click_count: 1,
|
||||
position: chip,
|
||||
modifiers: Modifiers {
|
||||
shift: true,
|
||||
..Default::default()
|
||||
},
|
||||
first_mouse: false,
|
||||
}));
|
||||
desktop.editor(|v, _, _| assert!(!v.overlays.link_popup().is_some_and(|p| p.from_hover)));
|
||||
|
||||
let desktop = Desktop::open();
|
||||
let chip = desktop.reference_point();
|
||||
desktop.move_to(chip);
|
||||
desktop.frame();
|
||||
desktop.panel(Some(Bounds::new(
|
||||
point(px(240.0), px(0.0)),
|
||||
size(px(1040.0), px(800.0)),
|
||||
)));
|
||||
assert!(
|
||||
!desktop
|
||||
.advance(LINK_HOVER_DELAY_MS)
|
||||
.elements
|
||||
.contains_key(POPUP)
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,27 @@
|
||||
//! What the desktop link hover of one view keeps between pointer moves and frames: the
|
||||
//! transition that waits for its delay and the targets read from the text.
|
||||
|
||||
use crate::{PlaygroundView, block_flow::FlowRect, rich_text::DecorationKind};
|
||||
use std::{
|
||||
cell::Cell,
|
||||
rc::{Rc, Weak},
|
||||
};
|
||||
|
||||
use super::{LinkPopupTarget, matching_link_subranges, reference_at};
|
||||
use blocksuite_playground_doc::{read::RichText, session::split_delta};
|
||||
use ui::{
|
||||
AnyElement, Context, DispatchPhase, HitboxBehavior, HitboxId, MouseButton, MouseDownEvent,
|
||||
MouseExitEvent, MouseMoveEvent, Pixels, Point, prelude::*,
|
||||
};
|
||||
use y_octo::{Any, TextDeltaOp, TextInsert};
|
||||
|
||||
use crate::{
|
||||
FormFactor, PlaygroundMode, PlaygroundView,
|
||||
block_flow::{FlowLayout, FlowRect},
|
||||
directory::EditorDocId,
|
||||
editor_session::{DocPoint, RangeBlocks},
|
||||
rich_text::{DecorationKind, TextBiIndex},
|
||||
};
|
||||
|
||||
use super::{LinkPopupTarget, matching_link_subranges, reference_at, reference_object_at};
|
||||
|
||||
/// Desktop hover transition of the link popup that waits for its delay.
|
||||
pub(super) enum LinkHoverTransition {
|
||||
@@ -19,10 +37,29 @@ pub(super) enum LinkHoverTransition {
|
||||
#[derive(Default)]
|
||||
pub(crate) struct LinkHoverPending {
|
||||
pub(super) transition: Option<LinkHoverTransition>,
|
||||
pub(super) pointer: Option<Point<Pixels>>,
|
||||
pub(super) hitbox: Rc<Cell<Option<HitboxId>>>,
|
||||
/// The last target found under the pointer from the start of its decoration.
|
||||
pub(super) hover: Option<(LinkReadKey, LinkPopupTarget)>,
|
||||
/// The last open hover popup target that the text confirmed.
|
||||
pub(super) confirmed: Option<(LinkReadKey, LinkPopupTarget)>,
|
||||
confirmed: Option<(LinkReadKey, LinkPopupTarget)>,
|
||||
confirmed_page_title: Option<String>,
|
||||
painted_preedit: Option<PaintedPreedit>,
|
||||
}
|
||||
|
||||
struct PopupPreedit<T> {
|
||||
start: DocPoint,
|
||||
end: DocPoint,
|
||||
text: T,
|
||||
}
|
||||
|
||||
struct PaintedPreedit {
|
||||
doc_rev: u64,
|
||||
doc_epoch: u64,
|
||||
page_rev: u64,
|
||||
nonce: u64,
|
||||
layout: Weak<FlowLayout>,
|
||||
composition: PopupPreedit<String>,
|
||||
}
|
||||
|
||||
/// The text a link popup target was read from: one page of one loaded document at one
|
||||
@@ -35,6 +72,8 @@ pub(super) struct LinkReadKey {
|
||||
page_rev: u64,
|
||||
env_rev: u64,
|
||||
readonly: bool,
|
||||
composed: bool,
|
||||
painted_preedit_rev: Option<u64>,
|
||||
}
|
||||
|
||||
/// The target of `slot` when it was read at `key`.
|
||||
@@ -78,7 +117,249 @@ pub(super) fn target_names_decoration(
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn reference_override(rich: &RichText, offset: usize, page_id: &str) -> String {
|
||||
let Some(reference) = reference_object_at(rich, offset, page_id) else {
|
||||
return String::new();
|
||||
};
|
||||
match reference.get("title") {
|
||||
Some(Any::String(title)) => title.clone(),
|
||||
_ => match reference.get("params") {
|
||||
Some(Any::Object(params)) => match params.get("title") {
|
||||
Some(Any::String(title)) => title.clone(),
|
||||
_ => String::new(),
|
||||
},
|
||||
_ => String::new(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
impl PlaygroundView {
|
||||
pub(super) fn record_popup_preedit(&mut self) {
|
||||
if self.mode == PlaygroundMode::Page
|
||||
&& self.editor.composing()
|
||||
&& !self.layout_has_active_preedit()
|
||||
{
|
||||
return;
|
||||
}
|
||||
let Some(layout) = self.flow_layout().filter(|_| self.editor.composing()) else {
|
||||
if let Some(state) = self.link_hover_pending.as_mut() {
|
||||
state.painted_preedit = None;
|
||||
}
|
||||
return;
|
||||
};
|
||||
let nonce = self.editor.preedit_nonce();
|
||||
if self
|
||||
.cached_popup_preedit()
|
||||
.is_some_and(|old| old.doc_rev == self.doc_rev && old.nonce == nonce)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let Some(composition) = self.popup_preedit() else {
|
||||
return;
|
||||
};
|
||||
let Some(page) = self.page() else {
|
||||
return;
|
||||
};
|
||||
let painted = PaintedPreedit {
|
||||
doc_rev: self.doc_rev,
|
||||
doc_epoch: self.doc_epoch,
|
||||
page_rev: page.revision(),
|
||||
nonce,
|
||||
layout: Rc::downgrade(&layout),
|
||||
composition: PopupPreedit {
|
||||
start: composition.start,
|
||||
end: composition.end,
|
||||
text: composition.text.to_owned(),
|
||||
},
|
||||
};
|
||||
self.link_hover_state().painted_preedit = Some(painted);
|
||||
}
|
||||
|
||||
fn cached_popup_preedit(&self) -> Option<&PaintedPreedit> {
|
||||
let painted = self.link_hover_pending.as_ref()?.painted_preedit.as_ref()?;
|
||||
if painted.doc_epoch != self.doc_epoch || painted.page_rev != self.page()?.revision() {
|
||||
return None;
|
||||
}
|
||||
let layout = self.flow_layout()?;
|
||||
(painted.layout.as_ptr() == Rc::as_ptr(&layout)).then_some(painted)
|
||||
}
|
||||
|
||||
fn layout_has_active_preedit(&self) -> bool {
|
||||
self.editor.preedit.is_some()
|
||||
&& match self.mode {
|
||||
// Marking text clears dirty_text. The Page layout pass sets it after
|
||||
// it builds the layout from the preedit snapshot.
|
||||
PlaygroundMode::Page => self.layout.is_some() && self.dirty_text.is_some(),
|
||||
PlaygroundMode::Edgeless => self.cached_popup_preedit().is_some_and(|painted| {
|
||||
painted.doc_rev == self.doc_rev && painted.nonce == self.editor.preedit_nonce()
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve the same relative selection and direction as the body IME.
|
||||
fn popup_preedit(&self) -> Option<PopupPreedit<&str>> {
|
||||
let pre = self.editor.preedit.as_ref()?;
|
||||
let selection = self
|
||||
.page()?
|
||||
.resolve_selection_snapshot(&pre.replacement)
|
||||
.ok()??;
|
||||
let (start, end) = if pre.backward {
|
||||
(selection.focus, selection.anchor)
|
||||
} else {
|
||||
(selection.anchor, selection.focus)
|
||||
};
|
||||
Some(PopupPreedit {
|
||||
start: DocPoint::new(start.0, start.1),
|
||||
end: DocPoint::new(end.0, end.1),
|
||||
text: &pre.text,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn popup_layout_text(&self, block_id: &str) -> Option<RichText> {
|
||||
if self.layout_has_active_preedit() {
|
||||
return self.composed_block_rich_text(block_id, self.popup_preedit().as_ref());
|
||||
}
|
||||
self.composed_block_rich_text(
|
||||
block_id,
|
||||
self.cached_popup_preedit()
|
||||
.map(|painted| &painted.composition),
|
||||
)
|
||||
}
|
||||
|
||||
fn composed_block_rich_text(
|
||||
&self,
|
||||
block_id: &str,
|
||||
composition: Option<&PopupPreedit<impl AsRef<str>>>,
|
||||
) -> Option<RichText> {
|
||||
let page = self.page()?;
|
||||
if let Some(PopupPreedit { start, end, text }) = composition {
|
||||
if block_id == start.block_id {
|
||||
let text = text.as_ref();
|
||||
let left = page.read_editable_text(&start.block_id).ok()?.0;
|
||||
let right = if end.block_id == start.block_id {
|
||||
None
|
||||
} else {
|
||||
Some(page.read_editable_text(&end.block_id).ok()?.0)
|
||||
};
|
||||
let right = right.as_ref().unwrap_or(&left);
|
||||
let (mut delta, _) = split_delta(&left.delta, start.offset()).ok()?;
|
||||
let (_, suffix) = split_delta(&right.delta, end.offset()).ok()?;
|
||||
let a = TextBiIndex::new(&left.plain).utf16_to_utf8_clamped(start.offset());
|
||||
let b = TextBiIndex::new(&right.plain).utf16_to_utf8_clamped(end.offset());
|
||||
let plain = format!("{}{}{}", &left.plain[..a], text, &right.plain[b..]);
|
||||
delta.push(TextDeltaOp::Insert {
|
||||
insert: TextInsert::Text(text.to_owned()),
|
||||
format: None,
|
||||
});
|
||||
delta.extend(suffix);
|
||||
return Some(RichText { delta, plain });
|
||||
}
|
||||
if block_id == end.block_id {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(page.read_editable_text(block_id).ok()?.0)
|
||||
}
|
||||
|
||||
pub(crate) fn map_target_for_preedit_commit(
|
||||
&self,
|
||||
mut target: LinkPopupTarget,
|
||||
) -> Option<LinkPopupTarget> {
|
||||
if self.layout_has_active_preedit() {
|
||||
return Some(target);
|
||||
}
|
||||
let current = self.popup_preedit();
|
||||
let prior = self.cached_popup_preedit();
|
||||
if current.is_none() && prior.is_none() {
|
||||
return Some(target);
|
||||
}
|
||||
let (block_id, from, to) = match &mut target {
|
||||
LinkPopupTarget::Reference {
|
||||
block_id,
|
||||
utf16_offset,
|
||||
..
|
||||
} => (block_id, utf16_offset, None),
|
||||
LinkPopupTarget::Link {
|
||||
block_id,
|
||||
start_utf16,
|
||||
end_utf16,
|
||||
..
|
||||
} => (block_id, start_utf16, Some(end_utf16)),
|
||||
};
|
||||
let mut range = *from..to.as_deref().copied().unwrap_or(*from + 1);
|
||||
// An earlier IME update may still be on screen. First recover its document offsets.
|
||||
if let Some(prior) = prior
|
||||
&& *block_id == prior.composition.start.block_id
|
||||
{
|
||||
let PopupPreedit { start, end, text } = &prior.composition;
|
||||
let start_offset = start.offset() as usize;
|
||||
let insert_end = start_offset + text.encode_utf16().count();
|
||||
if range.start >= insert_end {
|
||||
let end_offset = end.offset() as usize;
|
||||
range =
|
||||
end_offset + (range.start - insert_end)..end_offset + (range.end - insert_end);
|
||||
block_id.clone_from(&end.block_id);
|
||||
} else if range.end > start_offset {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if let Some(PopupPreedit { start, end, text }) = current.as_ref() {
|
||||
let start_offset = start.offset() as usize;
|
||||
let end_offset = end.offset() as usize;
|
||||
if *block_id == end.block_id && range.start >= end_offset {
|
||||
let insert_end = start_offset + text.encode_utf16().count();
|
||||
range =
|
||||
insert_end + (range.start - end_offset)..insert_end + (range.end - end_offset);
|
||||
block_id.clone_from(&start.block_id);
|
||||
} else if (*block_id == start.block_id && range.end > start_offset)
|
||||
|| (*block_id != start.block_id && *block_id == end.block_id)
|
||||
|| (start.block_id != end.block_id
|
||||
&& RangeBlocks::between_in_scope(
|
||||
self.page_snapshot()?,
|
||||
&self.active_content_scope(),
|
||||
&start.block_id,
|
||||
&end.block_id,
|
||||
)?
|
||||
.intermediate
|
||||
.contains(block_id))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
}
|
||||
*from = range.start;
|
||||
if let Some(to) = to {
|
||||
*to = range.end;
|
||||
}
|
||||
self.validate_popup_target(
|
||||
&target,
|
||||
&self.composed_block_rich_text(target.block_id(), current.as_ref())?,
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn reference_popup_target(
|
||||
&self,
|
||||
text: &RichText,
|
||||
block_id: &str,
|
||||
offset: usize,
|
||||
page_id: &str,
|
||||
) -> Option<LinkPopupTarget> {
|
||||
let (at, id) = reference_at(text, offset)?;
|
||||
if at != offset || id != page_id {
|
||||
return None;
|
||||
}
|
||||
let title = self.resolve_ref_title(page_id, &reference_override(text, offset, page_id));
|
||||
let (can_convert, can_embed) =
|
||||
self.reference_conversion_flags(block_id, page_id, text, offset);
|
||||
Some(LinkPopupTarget::Reference {
|
||||
block_id: block_id.to_owned(),
|
||||
utf16_offset: offset,
|
||||
page_id: id,
|
||||
title,
|
||||
can_convert,
|
||||
can_embed,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn link_read_key(&self) -> Option<LinkReadKey> {
|
||||
let page = self.page()?;
|
||||
Some(LinkReadKey {
|
||||
@@ -88,6 +369,8 @@ impl PlaygroundView {
|
||||
page_rev: page.revision(),
|
||||
env_rev: self.env_rev,
|
||||
readonly: self.page_readonly,
|
||||
composed: self.layout_has_active_preedit(),
|
||||
painted_preedit_rev: self.cached_popup_preedit().map(|painted| painted.doc_rev),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -95,73 +378,320 @@ impl PlaygroundView {
|
||||
self.link_hover_pending.get_or_insert_default()
|
||||
}
|
||||
|
||||
/// Close an open hover popup whose target the text no longer holds, and bring its title
|
||||
/// and view choices in line with the text and the page titles. The text is read one time
|
||||
/// per revision.
|
||||
pub(super) fn confirm_hover_link_popup(&mut self, now_ms: f64) {
|
||||
let Some((target, anchor)) = self
|
||||
fn reference_page_title(&self, page_id: &str) -> Option<String> {
|
||||
self.page_titles
|
||||
.get(page_id)
|
||||
.filter(|t| !t.is_empty())
|
||||
.cloned()
|
||||
.or_else(|| {
|
||||
self.doc_directory()
|
||||
.doc_preview(&EditorDocId::from(page_id))
|
||||
.map(|preview| preview.title)
|
||||
.filter(|t| !t.is_empty())
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn resolve_ref_title(&self, page_id: &str, fallback: &str) -> String {
|
||||
self.reference_page_title(page_id).unwrap_or_else(|| {
|
||||
if fallback.is_empty() {
|
||||
"Untitled"
|
||||
} else {
|
||||
fallback
|
||||
}
|
||||
.to_owned()
|
||||
})
|
||||
}
|
||||
|
||||
pub(in crate::overlays) fn has_desktop_link_hover_watch(&self) -> bool {
|
||||
self.form_factor == FormFactor::Desktop
|
||||
&& (self
|
||||
.overlays
|
||||
.link_popup()
|
||||
.is_some_and(|popup| popup.from_hover)
|
||||
|| self
|
||||
.link_hover_pending
|
||||
.as_ref()
|
||||
.is_some_and(|state| state.transition.is_some()))
|
||||
}
|
||||
|
||||
fn dismiss_desktop_link_hover(&mut self, cx: &mut Context<Self>) {
|
||||
let pending = self
|
||||
.link_hover_pending
|
||||
.as_mut()
|
||||
.and_then(|state| state.transition.take())
|
||||
.is_some();
|
||||
if pending {
|
||||
self.link_hover_timer = None;
|
||||
}
|
||||
let closed = self
|
||||
.overlays
|
||||
.link_popup()
|
||||
.filter(|p| p.from_hover)
|
||||
.map(|p| (p.target.clone(), p.anchor_world))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let key = self.link_read_key();
|
||||
let state = self.link_hover_pending.as_ref();
|
||||
if state.and_then(|state| kept(&state.confirmed, key.as_ref())) == Some(&target) {
|
||||
return;
|
||||
}
|
||||
let Some(current) = self.current_link_popup_target(&target) else {
|
||||
self.overlays.close_link_popup(now_ms);
|
||||
return;
|
||||
};
|
||||
// A rename of the target page or a move into a table changes the title or the view
|
||||
// choices of the open reference popup.
|
||||
if current != target {
|
||||
self.overlays
|
||||
.open_link_popup(current.clone(), anchor, true, now_ms);
|
||||
}
|
||||
if let Some(key) = key {
|
||||
self.link_hover_state().confirmed = Some((key, current));
|
||||
.is_some_and(|popup| popup.from_hover)
|
||||
&& self.overlays.close_link_popup(self.now_ms(cx));
|
||||
if pending || closed {
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
|
||||
/// `target` as the text and the page titles give it now, or `None` when the text no longer
|
||||
/// holds it.
|
||||
fn current_link_popup_target(&self, target: &LinkPopupTarget) -> Option<LinkPopupTarget> {
|
||||
let (doc_text, _) = self.page()?.read_editable_text(target.block_id()).ok()?;
|
||||
pub(in crate::overlays) fn desktop_link_hover_watch(&self, cx: &Context<Self>) -> AnyElement {
|
||||
let view = cx.weak_entity();
|
||||
let (pointer, watch_hitbox) = self
|
||||
.link_hover_pending
|
||||
.as_ref()
|
||||
.map_or((None, None), |state| {
|
||||
(state.pointer, Some(state.hitbox.clone()))
|
||||
});
|
||||
let reference_press = cx.listener(|this, event: &MouseDownEvent, window, cx| {
|
||||
let (x, y) = this.window_to_canvas_local(event.position);
|
||||
let y = y + this.topbar_height();
|
||||
let over_popup = this.overlays.link_popup().is_some_and(|popup| {
|
||||
[popup.rect, popup.submenu_rect]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.any(|r| r.contains(x, y))
|
||||
});
|
||||
if !over_popup
|
||||
&& matches!(
|
||||
this.hit_link_popup_target_at(
|
||||
event.position.x.into(),
|
||||
event.position.y.into(),
|
||||
window
|
||||
),
|
||||
Some((LinkPopupTarget::Reference { .. }, _))
|
||||
)
|
||||
{
|
||||
this.dismiss_desktop_link_hover(cx);
|
||||
}
|
||||
});
|
||||
ui::canvas(
|
||||
move |bounds, window, _| {
|
||||
let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
|
||||
if let Some(watch_hitbox) = watch_hitbox {
|
||||
watch_hitbox.set(Some(hitbox.id));
|
||||
}
|
||||
hitbox
|
||||
},
|
||||
move |_, hitbox, window, cx| {
|
||||
// A modal can cover the editor while the mouse stays in place.
|
||||
let hovered = hitbox.is_hovered(window);
|
||||
if !hovered && pointer == Some(window.mouse_position()) {
|
||||
let deferred_view = view.clone();
|
||||
cx.defer(move |cx| {
|
||||
let _ = deferred_view
|
||||
.update(cx, |this, cx| this.dismiss_desktop_link_hover(cx));
|
||||
});
|
||||
}
|
||||
let move_hit = hitbox.id;
|
||||
let move_view = view.clone();
|
||||
window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
|
||||
if phase == DispatchPhase::Bubble && !move_hit.is_hovered(window) {
|
||||
let _ =
|
||||
move_view.update(cx, |this, cx| this.dismiss_desktop_link_hover(cx));
|
||||
}
|
||||
});
|
||||
let down_view = view.clone();
|
||||
window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
|
||||
if phase != DispatchPhase::Capture {
|
||||
return;
|
||||
}
|
||||
if !hitbox.is_hovered(window) {
|
||||
let _ =
|
||||
down_view.update(cx, |this, cx| this.dismiss_desktop_link_hover(cx));
|
||||
} else if event.button == MouseButton::Left
|
||||
&& event.click_count == 1
|
||||
&& !event.modifiers.alt
|
||||
{
|
||||
reference_press(event, window, cx);
|
||||
}
|
||||
});
|
||||
window.on_mouse_event(move |_: &MouseExitEvent, phase, _, cx| {
|
||||
if phase == DispatchPhase::Capture {
|
||||
let _ = view.update(cx, |this, cx| this.dismiss_desktop_link_hover(cx));
|
||||
}
|
||||
});
|
||||
},
|
||||
)
|
||||
.absolute()
|
||||
.inset_0()
|
||||
.size_full()
|
||||
.into_any_element()
|
||||
}
|
||||
|
||||
pub(super) fn schedule_link_hover(&mut self, delay_ms: f64, cx: &mut Context<Self>) {
|
||||
let mode = self.mode;
|
||||
let note_id = self.active_link_note_id().map(str::to_owned);
|
||||
// Replacing the task cancels the previous transition.
|
||||
self.link_hover_timer = Some(cx.spawn(async move |this, cx| {
|
||||
cx.background_executor()
|
||||
.timer(std::time::Duration::from_millis(delay_ms as u64))
|
||||
.await;
|
||||
let _ = this.update_in(cx, |this, window, cx| {
|
||||
let state = this.link_hover_state();
|
||||
let transition = state.transition.take();
|
||||
let pointer = state.pointer;
|
||||
let hitbox = state.hitbox.get();
|
||||
cx.notify();
|
||||
if this.mode != mode || this.active_link_note_id() != note_id.as_deref() {
|
||||
return;
|
||||
}
|
||||
let now_ms = this.now_ms(cx);
|
||||
match transition {
|
||||
Some(LinkHoverTransition::Enter(target, anchor)) => {
|
||||
let mouse = window.mouse_position();
|
||||
if pointer.is_some_and(|p| {
|
||||
p != mouse || hitbox.is_some_and(|id| !id.is_hovered(window))
|
||||
}) {
|
||||
return;
|
||||
}
|
||||
let (target, anchor) = if pointer.is_some() || note_id.is_some() {
|
||||
// Scroll and camera moves can move the target under a stationary pointer.
|
||||
let key = this.link_read_key();
|
||||
let known = this
|
||||
.link_hover_pending
|
||||
.as_ref()
|
||||
.and_then(|state| kept(&state.hover, key.as_ref()));
|
||||
let Some((current, anchor, _)) = this.link_popup_target_at(
|
||||
mouse.x.into(),
|
||||
mouse.y.into(),
|
||||
window,
|
||||
known,
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
if current != target {
|
||||
return;
|
||||
}
|
||||
(current, anchor)
|
||||
} else {
|
||||
(target, anchor)
|
||||
};
|
||||
this.overlays.open_link_popup(target, anchor, true, now_ms);
|
||||
}
|
||||
Some(LinkHoverTransition::Leave)
|
||||
if this.overlays.link_popup().is_some_and(|p| p.from_hover) =>
|
||||
{
|
||||
this.overlays.close_link_popup(now_ms);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
/// Revalidate the open reference or hover target when its source text or title changes.
|
||||
pub(super) fn confirm_link_popup(&mut self, now_ms: f64) {
|
||||
let Some(popup) = self.overlays.link_popup().filter(|popup| {
|
||||
popup.from_hover || matches!(popup.target, LinkPopupTarget::Reference { .. })
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
let target = &popup.target;
|
||||
// The host can update its shared directory without editing this document.
|
||||
let page_title = match target {
|
||||
LinkPopupTarget::Reference { page_id, .. } => self.reference_page_title(page_id),
|
||||
_ => None,
|
||||
};
|
||||
let key = self.link_read_key();
|
||||
let confirmed = self.link_hover_pending.as_ref().is_some_and(|state| {
|
||||
state.confirmed_page_title == page_title
|
||||
&& kept(&state.confirmed, key.as_ref()) == Some(target)
|
||||
});
|
||||
let anchor = if !popup.from_hover && !self.editor.composing() {
|
||||
self.reference_popup_anchor(target)
|
||||
.unwrap_or(popup.anchor_world)
|
||||
} else {
|
||||
popup.anchor_world
|
||||
};
|
||||
if confirmed {
|
||||
if anchor != popup.anchor_world {
|
||||
self.overlays
|
||||
.open_link_popup(target.clone(), anchor, false, now_ms);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let Some(current) = self.current_link_popup_target(target, popup.from_hover) else {
|
||||
self.overlays.close_link_popup(now_ms);
|
||||
return;
|
||||
};
|
||||
let refresh_hover = self
|
||||
.link_hover_pending
|
||||
.as_ref()
|
||||
.and_then(|state| state.hover.as_ref())
|
||||
.is_some_and(|(_, hover)| hover == target);
|
||||
if current != *target || anchor != popup.anchor_world {
|
||||
self.overlays
|
||||
.open_link_popup(current.clone(), anchor, popup.from_hover, now_ms);
|
||||
}
|
||||
if let Some(key) = key {
|
||||
let state = self.link_hover_state();
|
||||
if refresh_hover {
|
||||
state.hover = Some((key.clone(), current.clone()));
|
||||
}
|
||||
state.confirmed = Some((key, current));
|
||||
state.confirmed_page_title = page_title;
|
||||
}
|
||||
}
|
||||
|
||||
fn reference_popup_anchor(&self, target: &LinkPopupTarget) -> Option<FlowRect> {
|
||||
let LinkPopupTarget::Reference {
|
||||
block_id,
|
||||
utf16_offset,
|
||||
..
|
||||
} = target
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let layout = self.flow_layout()?;
|
||||
let block = layout.block(block_id)?;
|
||||
let text = block.body.text.as_ref()?;
|
||||
let deco = text.layout.decorations().iter().find(|deco| {
|
||||
let offset = deco.source_utf16.start as usize;
|
||||
offset == *utf16_offset && target_names_decoration(target, block_id, &deco.kind, offset)
|
||||
})?;
|
||||
Some(FlowRect::new(
|
||||
block.x + text.x + f32::from(deco.bounds.origin.x),
|
||||
block.y + text.y + f32::from(deco.bounds.origin.y),
|
||||
f32::from(deco.bounds.size.width),
|
||||
f32::from(deco.bounds.size.height),
|
||||
))
|
||||
}
|
||||
|
||||
fn current_link_popup_target(
|
||||
&self,
|
||||
target: &LinkPopupTarget,
|
||||
from_hover: bool,
|
||||
) -> Option<LinkPopupTarget> {
|
||||
let Some(page) = self.page() else {
|
||||
return (!from_hover).then(|| target.clone());
|
||||
};
|
||||
let text = if from_hover {
|
||||
self.popup_layout_text(target.block_id())?
|
||||
} else {
|
||||
page.read_editable_text(target.block_id()).ok()?.0
|
||||
};
|
||||
self.validate_popup_target(target, &text)
|
||||
}
|
||||
|
||||
fn validate_popup_target(
|
||||
&self,
|
||||
target: &LinkPopupTarget,
|
||||
text: &RichText,
|
||||
) -> Option<LinkPopupTarget> {
|
||||
match target {
|
||||
LinkPopupTarget::Link {
|
||||
start_utf16,
|
||||
end_utf16,
|
||||
url,
|
||||
..
|
||||
} => (matching_link_subranges(&doc_text, *start_utf16, *end_utf16, url)
|
||||
} => (matching_link_subranges(text, *start_utf16, *end_utf16, url)
|
||||
== [(*start_utf16, *end_utf16)])
|
||||
.then(|| target.clone()),
|
||||
LinkPopupTarget::Reference {
|
||||
block_id,
|
||||
utf16_offset,
|
||||
page_id,
|
||||
title,
|
||||
..
|
||||
} => {
|
||||
let (at, pid) = reference_at(&doc_text, *utf16_offset)?;
|
||||
if at != *utf16_offset || pid != *page_id {
|
||||
return None;
|
||||
}
|
||||
let (can_convert, can_embed) =
|
||||
self.reference_conversion_flags(block_id, page_id, &doc_text, at);
|
||||
Some(LinkPopupTarget::Reference {
|
||||
block_id: block_id.clone(),
|
||||
utf16_offset: at,
|
||||
page_id: pid,
|
||||
title: self.resolve_ref_title(page_id, title),
|
||||
can_convert,
|
||||
can_embed,
|
||||
})
|
||||
}
|
||||
} => self.reference_popup_target(text, block_id, *utf16_offset, page_id),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,8 @@ mod memo;
|
||||
|
||||
#[cfg(test)]
|
||||
mod active_note_tests;
|
||||
#[cfg(test)]
|
||||
mod desktop_hover_tests;
|
||||
|
||||
use blocksuite_editor::clipboard::sanitize::sanitize_url;
|
||||
use ui::{Bounds, Context, Window, point, px};
|
||||
@@ -240,37 +242,23 @@ impl PlaygroundView {
|
||||
}));
|
||||
}
|
||||
|
||||
fn resolve_ref_title(&self, page_id: &str, fallback: &str) -> String {
|
||||
self.page_titles
|
||||
.get(page_id)
|
||||
.filter(|t| !t.is_empty())
|
||||
.cloned()
|
||||
.unwrap_or_else(|| {
|
||||
if fallback.is_empty() {
|
||||
"Untitled".to_string()
|
||||
} else {
|
||||
fallback.to_string()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// How many times the calling thread read the CRDT text of a block to resolve the link
|
||||
/// or the reference under a pointer. Text without one under the pointer adds nothing.
|
||||
pub fn link_hit_text_reads() -> u64 {
|
||||
LINK_HIT_TEXT_READS.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
/// CRDT text of `block_id`, which locates the link or the reference under a pointer.
|
||||
/// Read the text in the coordinate space of the hit layout.
|
||||
fn link_hit_text(&self, block_id: &str) -> Option<blocksuite_playground_doc::read::RichText> {
|
||||
LINK_HIT_TEXT_READS.with(|reads| reads.set(reads.get() + 1));
|
||||
Some(self.page()?.read_editable_text(block_id).ok()?.0)
|
||||
self.popup_layout_text(block_id)
|
||||
}
|
||||
|
||||
/// The link or the reference under world `(wx, wy)` in `block`, with the line segment of
|
||||
/// its decoration under the pointer. A decoration that names `known` gives it again
|
||||
/// without a read of the text. The flag tells whether a new read found a target that names
|
||||
/// its decoration, which a later hover may reuse.
|
||||
fn link_or_ref_in_block(
|
||||
pub(crate) fn link_or_ref_in_block(
|
||||
&self,
|
||||
block: &FlowBlock,
|
||||
wx: f32,
|
||||
@@ -305,32 +293,7 @@ impl PlaygroundView {
|
||||
let target = match &deco.kind {
|
||||
DecorationKind::ReferenceChip(r) if !r.page_id.is_empty() => {
|
||||
let doc_text = self.link_hit_text(&block.block_id)?;
|
||||
let match_ref = |o: usize| {
|
||||
reference_at(&doc_text, o)
|
||||
.filter(|(_, pid)| pid == &r.page_id)
|
||||
.map(|(pos, _)| pos)
|
||||
};
|
||||
let off = match_ref(deco_start).or_else(|| {
|
||||
let hit = block.hit_text(wx, wy)?;
|
||||
let o = hit.utf16_offset as usize;
|
||||
match_ref(o).or_else(|| o.checked_sub(1).and_then(match_ref))
|
||||
})?;
|
||||
let title =
|
||||
self.resolve_ref_title(&r.page_id, r.title.as_deref().unwrap_or(""));
|
||||
let (can_convert, can_embed) = self.reference_conversion_flags(
|
||||
&block.block_id,
|
||||
&r.page_id,
|
||||
&doc_text,
|
||||
off,
|
||||
);
|
||||
LinkPopupTarget::Reference {
|
||||
block_id: block.block_id.clone(),
|
||||
utf16_offset: off,
|
||||
page_id: r.page_id.clone(),
|
||||
title,
|
||||
can_convert,
|
||||
can_embed,
|
||||
}
|
||||
self.reference_popup_target(&doc_text, &block.block_id, deco_start, &r.page_id)?
|
||||
}
|
||||
DecorationKind::Link(url) if !url.is_empty() => {
|
||||
let doc_text = self.link_hit_text(&block.block_id)?;
|
||||
@@ -431,8 +394,8 @@ impl PlaygroundView {
|
||||
y: f32,
|
||||
window: &Window,
|
||||
) -> Option<(LinkPopupTarget, FlowRect)> {
|
||||
self.link_popup_target_at(x, y, window, None)
|
||||
.map(|(target, anchor, _)| (target, anchor))
|
||||
let (target, anchor, _) = self.link_popup_target_at(x, y, window, None)?;
|
||||
Some((self.map_target_for_preedit_commit(target)?, anchor))
|
||||
}
|
||||
|
||||
fn link_popup_target_at(
|
||||
@@ -488,8 +451,7 @@ impl PlaygroundView {
|
||||
if self.form_factor != FormFactor::Desktop || pressed {
|
||||
return;
|
||||
}
|
||||
let mode = self.mode;
|
||||
if mode == PlaygroundMode::Edgeless && self.active_link_note_id().is_none() {
|
||||
if self.mode == PlaygroundMode::Edgeless && self.active_link_note_id().is_none() {
|
||||
self.link_hover_pending = None;
|
||||
self.link_hover_timer = None;
|
||||
return;
|
||||
@@ -502,6 +464,8 @@ impl PlaygroundView {
|
||||
{
|
||||
return;
|
||||
}
|
||||
self.link_hover_state().pointer =
|
||||
(window.mouse_position() == point(px(x), px(y))).then_some(window.mouse_position());
|
||||
let now_ms = self.now_ms(cx);
|
||||
if self.overlays.has_live_or_closing_link_popup(now_ms)
|
||||
&& let Some((snapshot, layout, transform)) = self.active_overlay_target()
|
||||
@@ -571,61 +535,23 @@ impl PlaygroundView {
|
||||
Some(LinkHoverTransition::Enter(..)) => LINK_HOVER_DELAY_MS,
|
||||
Some(LinkHoverTransition::Leave) => super::HOVER_LEAVE_DELAY_MS,
|
||||
None => {
|
||||
self.link_hover_state().transition = None;
|
||||
self.link_hover_timer = None;
|
||||
if self.link_hover_state().transition.take().is_some() {
|
||||
self.link_hover_timer = None;
|
||||
cx.notify();
|
||||
}
|
||||
return;
|
||||
}
|
||||
};
|
||||
let was_watching = self.has_desktop_link_hover_watch();
|
||||
self.link_hover_state().transition = next;
|
||||
// Replacing the task cancels the previous one, so only the latest transition fires.
|
||||
let note_id = self.active_link_note_id().map(str::to_owned);
|
||||
self.link_hover_timer = Some(cx.spawn(async move |this, cx| {
|
||||
cx.background_executor()
|
||||
.timer(std::time::Duration::from_millis(delay_ms as u64))
|
||||
.await;
|
||||
let _ = this.update_in(cx, |this, window, cx| {
|
||||
let transition = this.link_hover_state().transition.take();
|
||||
if this.mode != mode || this.active_link_note_id() != note_id.as_deref() {
|
||||
return;
|
||||
}
|
||||
let now_ms = this.now_ms(cx);
|
||||
match transition {
|
||||
Some(LinkHoverTransition::Enter(target, anchor)) => {
|
||||
let (target, anchor) = if note_id.is_some() {
|
||||
// The camera or viewport can move while the pointer stays still.
|
||||
let p = window.mouse_position();
|
||||
let key = this.link_read_key();
|
||||
let known = this
|
||||
.link_hover_pending
|
||||
.as_ref()
|
||||
.and_then(|state| kept(&state.hover, key.as_ref()));
|
||||
let Some((current, anchor, _)) =
|
||||
this.link_popup_target_at(p.x.into(), p.y.into(), window, known)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if current != target {
|
||||
return;
|
||||
}
|
||||
(current, anchor)
|
||||
} else {
|
||||
(target, anchor)
|
||||
};
|
||||
this.overlays.open_link_popup(target, anchor, true, now_ms);
|
||||
}
|
||||
Some(LinkHoverTransition::Leave)
|
||||
if this.overlays.link_popup().is_some_and(|p| p.from_hover) =>
|
||||
{
|
||||
this.overlays.close_link_popup(now_ms);
|
||||
}
|
||||
_ => return,
|
||||
}
|
||||
cx.notify();
|
||||
});
|
||||
}));
|
||||
self.schedule_link_hover(delay_ms, cx);
|
||||
if !was_watching {
|
||||
self.link_hover_state().hitbox.set(None);
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
|
||||
/// Revalidate the open hover popup before it is painted.
|
||||
/// Revalidate the open popup before it is painted.
|
||||
pub(crate) fn sync_hover_link_popup(&mut self, now_ms: f64) {
|
||||
if self.mode == PlaygroundMode::Edgeless && self.active_link_note_id().is_none() {
|
||||
self.link_hover_pending = None;
|
||||
@@ -633,15 +559,17 @@ impl PlaygroundView {
|
||||
self.overlays.close_link_popup(now_ms);
|
||||
return;
|
||||
}
|
||||
self.confirm_hover_link_popup(now_ms);
|
||||
self.record_popup_preedit();
|
||||
self.confirm_link_popup(now_ms);
|
||||
}
|
||||
|
||||
/// Sync the caret popup when a collapsed caret lands on a link or chip.
|
||||
pub(crate) fn sync_link_popup_for_caret(&mut self, layout: &FlowLayout, now_ms: f64) {
|
||||
self.sync_hover_link_popup(now_ms);
|
||||
if self.mode != PlaygroundMode::Page {
|
||||
return;
|
||||
}
|
||||
self.record_popup_preedit();
|
||||
self.confirm_link_popup(now_ms);
|
||||
let page_rev = self.page().map_or(0, |p| p.revision());
|
||||
let Some(sel) = self.editor.selection.as_ref().filter(|s| s.empty()) else {
|
||||
self.last_link_popup_caret = None;
|
||||
@@ -712,7 +640,10 @@ impl PlaygroundView {
|
||||
.and_then(|o| reference_at(&doc_text, o))
|
||||
}) {
|
||||
if auto_open {
|
||||
let title = self.resolve_ref_title(&page_id, "");
|
||||
let title = self.resolve_ref_title(
|
||||
&page_id,
|
||||
&memo::reference_override(&doc_text, ref_off, &page_id),
|
||||
);
|
||||
let (can_convert, can_embed) =
|
||||
self.reference_conversion_flags(block_id, &page_id, &doc_text, ref_off);
|
||||
self.overlays.open_link_popup(
|
||||
|
||||
@@ -350,6 +350,10 @@ impl PlaygroundView {
|
||||
cx,
|
||||
));
|
||||
elements.push(Self::image_resize_pointer_capture(cx));
|
||||
if self.has_desktop_link_hover_watch() {
|
||||
// Put the hitbox above the popup menus and below the modal layers.
|
||||
elements.push(self.desktop_link_hover_watch(cx));
|
||||
}
|
||||
elements
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user