diff --git a/blocksuite/crates/editor/src/overlays/link_popup.rs b/blocksuite/crates/editor/src/overlays/link_popup.rs index b253c8797d..c05e630bc8 100644 --- a/blocksuite/crates/editor/src/overlays/link_popup.rs +++ b/blocksuite/crates/editor/src/overlays/link_popup.rs @@ -130,15 +130,36 @@ impl Overlays { } } - /// True if `(x, y)` is inside the open link popup rect or the small hover bridge - /// connecting it to its anchor rect. - pub fn link_popup_contains_hover(&self, scene: &OverlayScene<'_>, x: f32, y: f32) -> bool { - let Some(popup) = self.link_popup() else { - return false; - }; - let Some(rect) = popup.rect else { - return false; + fn compute_link_popup_rect(popup: &LinkPopupState, scene: &OverlayScene<'_>) -> FlowRect { + let anchor = scene.world_to_screen(&popup.anchor_world); + let viewport = scene.popover_viewport(); + let touch = scene.form_factor != crate::block_flow::FormFactor::Desktop; + let btn_h = if touch { 32.0 } else { 26.0 }; + let pad = TOOLBAR_PADDING; + let is_ref = matches!(popup.target, LinkPopupTarget::Reference { .. }); + let label_text = popup.target.display_label(); + let est_label_w = (label_text.chars().count() as f32 * 7.6 + 20.0).clamp(64.0, 172.0); + let actions_w = if is_ref { + 54.0 + 44.0 + 44.0 + 54.0 + 12.0 + } else { + 54.0 + 42.0 + 44.0 + 48.0 + 12.0 }; + let raw_w = 2.0 * (pad + POPOVER_BORDER) + est_label_w + 13.0 + actions_w; + let max_w = (viewport.w - 2.0 * POPOVER_EDGE_MARGIN).max(180.0); + let width = raw_w.min(max_w).round(); + let height = (btn_h + 2.0 * (pad + POPOVER_BORDER)).round(); + place_popover( + anchor, + (width, height), + viewport, + Placement::BelowStart, + POPOVER_GAP, + POPOVER_EDGE_MARGIN, + ) + .rect + } + + fn rect_or_bridge_contains(rect: FlowRect, anchor: FlowRect, x: f32, y: f32) -> bool { let pad = 10.0; let expanded = FlowRect::new( rect.x - pad, @@ -149,7 +170,6 @@ impl Overlays { if expanded.contains(x, y) { return true; } - let anchor = scene.world_to_screen(&popup.anchor_world); let bridge_top = anchor.y.min(rect.y) - 4.0; let bridge_bottom = anchor.bottom().max(rect.bottom()) + 4.0; let bridge_left = anchor.x.min(rect.x) - 4.0; @@ -157,6 +177,49 @@ impl Overlays { x >= bridge_left && x <= bridge_right && y >= bridge_top && y <= bridge_bottom } + /// True if `(x, y)` is inside the open link popup rect or the small hover bridge + /// connecting it to its anchor rect (computing placement on the fly if `rect` has not yet + /// painted its first frame). If the popup just started fading from hover and the pointer + /// re-enters it while still visible, promotes it back to open so clicks never fall through. + pub fn retain_or_reopen_link_popup_on_hover( + &mut self, + scene: &OverlayScene<'_>, + x: f32, + y: f32, + now_ms: f64, + ) -> bool { + let Some(popup) = self.link_popup.as_mut() else { + return false; + }; + if popup.presence.gone(now_ms) { + return false; + } + let rect = popup + .rect + .unwrap_or_else(|| Self::compute_link_popup_rect(popup, scene)); + let anchor = scene.world_to_screen(&popup.anchor_world); + if !Self::rect_or_bridge_contains(rect, anchor, x, y) { + return false; + } + if popup.presence.closing { + popup.presence = popup.presence.reopened(now_ms); + } + true + } + + /// True if `(x, y)` is inside the open link popup rect or the small hover bridge + /// connecting it to its anchor rect. + pub fn link_popup_contains_hover(&self, scene: &OverlayScene<'_>, x: f32, y: f32) -> bool { + let Some(popup) = self.link_popup() else { + return false; + }; + let rect = popup + .rect + .unwrap_or_else(|| Self::compute_link_popup_rect(popup, scene)); + let anchor = scene.world_to_screen(&popup.anchor_world); + Self::rect_or_bridge_contains(rect, anchor, x, y) + } + pub(super) fn render_link_popup( &mut self, scene: &OverlayScene<'_>, @@ -190,35 +253,19 @@ impl Overlays { } return None; } - let anchor = scene.world_to_screen(&popup.anchor_world); - let viewport = scene.popover_viewport(); let touch = scene.form_factor != crate::block_flow::FormFactor::Desktop; let btn_h = if touch { 32.0 } else { 26.0 }; let pad = TOOLBAR_PADDING; let is_ref = matches!(popup.target, LinkPopupTarget::Reference { .. }); let label_text = popup.target.display_label().to_string(); - let est_label_w = (label_text.chars().count() as f32 * 7.6 + 20.0).clamp(64.0, 172.0); let actions_w = if is_ref { - // Open + Copy + Card + Remove 54.0 + 44.0 + 44.0 + 54.0 + 12.0 } else { - // Open + Edit + Copy + Unlink 54.0 + 42.0 + 44.0 + 48.0 + 12.0 }; - let raw_w = 2.0 * (pad + POPOVER_BORDER) + est_label_w + 13.0 + actions_w; - let max_w = (viewport.w - 2.0 * POPOVER_EDGE_MARGIN).max(180.0); - let width = raw_w.min(max_w).round(); - let label_w = (width - 2.0 * (pad + POPOVER_BORDER) - 13.0 - actions_w).max(36.0); - let height = (btn_h + 2.0 * (pad + POPOVER_BORDER)).round(); - let placed = place_popover( - anchor, - (width, height), - viewport, - Placement::BelowStart, - POPOVER_GAP, - POPOVER_EDGE_MARGIN, - ); - popup.rect = Some(placed.rect); + let placed_rect = Self::compute_link_popup_rect(popup, scene); + let label_w = (placed_rect.w - 2.0 * (pad + POPOVER_BORDER) - 13.0 - actions_w).max(36.0); + popup.rect = Some(placed_rect); let hover = palette.hover; let radius = TOOLBAR_RADIUS - TOOLBAR_PADDING; @@ -262,7 +309,7 @@ impl Overlays { el }; - let mut root = place(placed.rect) + let mut root = place(placed_rect) .id("link-popup") .flex() .items_center() diff --git a/blocksuite/crates/editor/src/overlays/mod.rs b/blocksuite/crates/editor/src/overlays/mod.rs index aa3b1bb36e..e92157737e 100644 --- a/blocksuite/crates/editor/src/overlays/mod.rs +++ b/blocksuite/crates/editor/src/overlays/mod.rs @@ -321,7 +321,12 @@ pub enum DocEdit { /// Align the selected blocks. Align(BlockAlign), /// Link the text selection to a URL, or clear its link. - Link(Option), + Link { + url: Option, + /// When editing an existing uniform link, preserves peer edits outside sub-ranges still + /// matching `expected_prev_url`. + expected_prev_url: Option, + }, /// Commit a LaTeX equation string to a block or inline target. Equation { target: EquationTarget, @@ -449,8 +454,6 @@ pub enum OverlayEvent { bytes: Vec, caption: String, }, - /// Show or hide the mobile bottom keyboard toolbar. - SetKeyboardToolbarVisible(bool), /// Scroll the horizontal mobile keyboard toolbar strip by `delta_x` px. KeyboardToolbarScroll(f32), /// Scroll the active mobile keyboard tool panel (`+`, `Turn into`, or `Highlight`) by `delta_y` px. diff --git a/blocksuite/crates/editor/src/overlays/paint_toolbar.rs b/blocksuite/crates/editor/src/overlays/paint_toolbar.rs index 177df75f0e..2a168d149d 100644 --- a/blocksuite/crates/editor/src/overlays/paint_toolbar.rs +++ b/blocksuite/crates/editor/src/overlays/paint_toolbar.rs @@ -25,8 +25,13 @@ impl Overlays { cx: &mut Context, ) -> Vec { let mut out = Vec::new(); - let suppress_buttons = - self.keyboard_toolbar.visible || scene.suppress_floating_format_buttons; + let standalone_link = self + .toolbar + .as_ref() + .is_some_and(|t| t.link.is_some() && t.standalone_link_block_id.is_some()); + let suppress_buttons = self.keyboard_toolbar.visible + || scene.suppress_floating_format_buttons + || standalone_link; let Some(toolbar) = self.toolbar.as_mut() else { return out; }; diff --git a/blocksuite/crates/editor/src/overlays/state.rs b/blocksuite/crates/editor/src/overlays/state.rs index 7e19c3f13f..4930a32831 100644 --- a/blocksuite/crates/editor/src/overlays/state.rs +++ b/blocksuite/crates/editor/src/overlays/state.rs @@ -497,7 +497,6 @@ impl Overlays { | OverlayEvent::CloseLinkedDocMenu | OverlayEvent::CreateLinkedDoc { .. } | OverlayEvent::LinkPopupAction(_) - | OverlayEvent::SetKeyboardToolbarVisible(_) | OverlayEvent::KeyboardToolbar(_) | OverlayEvent::InsertImageBytes { .. } | OverlayEvent::FocusTableCell { .. } diff --git a/blocksuite/crates/editor/src/overlays/toolbar.rs b/blocksuite/crates/editor/src/overlays/toolbar.rs index 1e921e310b..6514c5555e 100644 --- a/blocksuite/crates/editor/src/overlays/toolbar.rs +++ b/blocksuite/crates/editor/src/overlays/toolbar.rs @@ -352,6 +352,11 @@ pub(super) struct FormatToolbar { /// What the selection last reported; kept while the toolbar fades out. pub(super) selection: SelectionFormat, pub(super) link: Option, + /// Original URL when `link` was opened on text carrying a uniform link, so `apply_link` + /// preserves concurrent collaborator link edits outside sub-ranges still matching it. + pub(super) link_expected_prev_url: Option, + /// Block ID when `link` was opened explicitly on a non-toolbar block (e.g. `prop:title`). + pub(super) standalone_link_block_id: Option, pub(super) submenu: Option, pub(super) presence: Presence, /// Screen-space box of the toolbar as last laid out. @@ -428,14 +433,38 @@ impl Overlays { pub fn close_link_field(&mut self) { if let Some(toolbar) = self.toolbar.as_mut() { toolbar.link = None; + toolbar.link_expected_prev_url = None; + toolbar.standalone_link_block_id = None; toolbar.submenu = None; toolbar.submenu_rect = None; } } + /// Block ID of a standalone `LinkBar` opened on a non-toolbar block (such as `prop:title`). + pub fn standalone_link_block_id(&self) -> Option<&str> { + let toolbar = self.open_toolbar()?; + toolbar.link.as_ref()?; + toolbar.standalone_link_block_id.as_deref() + } + + /// Open the inline link field, optionally bound to a standalone block (e.g. `prop:title`). + pub fn open_link_field_for_block( + &mut self, + selection: &SelectionFormat, + standalone_block_id: Option, + now_ms: f64, + ) { + self.open_link_field(selection, now_ms); + if let Some(toolbar) = self.toolbar.as_mut() { + toolbar.standalone_link_block_id = standalone_block_id; + } + } + /// 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); + let init_url = selection.marks.link.clone().unwrap_or_default(); + let expected_prev = (!init_url.is_empty()).then(|| init_url.clone()); match self.toolbar.as_mut() { Some(toolbar) => { toolbar.selection = selection.clone(); @@ -443,17 +472,17 @@ impl Overlays { toolbar.submenu = None; toolbar.submenu_rect = None; if toolbar.link.is_none() { - toolbar.link = Some(LinkBar::new( - toolbar.selection.marks.link.clone().unwrap_or_default(), - )); + toolbar.link = Some(LinkBar::new(init_url)); + toolbar.link_expected_prev_url = expected_prev; + toolbar.standalone_link_block_id = None; } } None => { self.toolbar = Some(FormatToolbar { selection: selection.clone(), - link: Some(LinkBar::new( - selection.marks.link.clone().unwrap_or_default(), - )), + link: Some(LinkBar::new(init_url)), + link_expected_prev_url: expected_prev, + standalone_link_block_id: None, submenu: None, presence: Presence::opening(now_ms), rect: None, @@ -490,6 +519,8 @@ impl Overlays { self.toolbar = Some(FormatToolbar { selection: selection.clone(), link: None, + link_expected_prev_url: None, + standalone_link_block_id: None, submenu: None, presence: Presence::opening(now_ms), rect: None, @@ -498,6 +529,8 @@ impl Overlays { } (None, Some(toolbar)) => { toolbar.link = None; + toolbar.link_expected_prev_url = None; + toolbar.standalone_link_block_id = None; toolbar.submenu = None; toolbar.submenu_rect = None; toolbar.presence.close(now_ms); @@ -514,6 +547,8 @@ impl Overlays { match action { FormatAction::TurnInto => { toolbar.link = None; + toolbar.link_expected_prev_url = None; + toolbar.standalone_link_block_id = None; toolbar.submenu = if toolbar.submenu == Some(ToolbarSubmenu::TurnInto) { None } else { @@ -522,6 +557,8 @@ impl Overlays { } FormatAction::Highlight => { toolbar.link = None; + toolbar.link_expected_prev_url = None; + toolbar.standalone_link_block_id = None; toolbar.submenu = if toolbar.submenu == Some(ToolbarSubmenu::Highlight) { None } else { @@ -531,12 +568,19 @@ impl Overlays { FormatAction::Link => { toolbar.submenu = None; toolbar.submenu_rect = None; - toolbar.link = match toolbar.link { - Some(_) => None, - None => Some(LinkBar::new( - toolbar.selection.marks.link.clone().unwrap_or_default(), - )), - }; + toolbar.standalone_link_block_id = None; + match toolbar.link { + Some(_) => { + toolbar.link = None; + toolbar.link_expected_prev_url = None; + } + None => { + let init_url = toolbar.selection.marks.link.clone().unwrap_or_default(); + toolbar.link_expected_prev_url = + (!init_url.is_empty()).then(|| init_url.clone()); + toolbar.link = Some(LinkBar::new(init_url)); + } + } } _ => { toolbar.submenu = None; @@ -559,12 +603,23 @@ impl Overlays { let Some(link) = toolbar.link.take() else { return; }; + let expected_prev_url = toolbar.link_expected_prev_url.take(); + let standalone = toolbar.standalone_link_block_id.take().is_some(); effects.redraw = true; let url = normalize_url(&link.into_committed_text()); + if standalone { + self.toolbar = None; + } if remove { - effects.edits.push(DocEdit::Link(None)); + effects.edits.push(DocEdit::Link { + url: None, + expected_prev_url, + }); } else if !url.is_empty() { - effects.edits.push(DocEdit::Link(Some(url))); + effects.edits.push(DocEdit::Link { + url: Some(url), + expected_prev_url, + }); } } } diff --git a/blocksuite/crates/playground/src/bin/bs_harness/edgeless_evidence.rs b/blocksuite/crates/playground/src/bin/bs_harness/edgeless_evidence.rs index f4e8b0a12f..6abb55dc16 100644 --- a/blocksuite/crates/playground/src/bin/bs_harness/edgeless_evidence.rs +++ b/blocksuite/crates/playground/src/bin/bs_harness/edgeless_evidence.rs @@ -8,8 +8,8 @@ use blocksuite_playground_doc::schema::{ BlockSpec, MindmapNodeSpec, ParagraphType, SurfaceElementSpec, }; use playground::{ - HOME_PAGE_ID, PlaygroundMode, PlaygroundOptions, PlaygroundTheme, overlays::OverlayEvent, - room_client::DocState, seed_showcase_doc, + HOME_PAGE_ID, PlaygroundMode, PlaygroundOptions, PlaygroundTheme, room_client::DocState, + seed_showcase_doc, }; use super::{s3_evidence_fixtures::save_session_png, start_headless_session}; @@ -31,7 +31,6 @@ pub(super) fn render_edgeless_evidence(out_dir: &Path) -> Result<()> { session.view(|v, cx| v.set_document(state, cx))?; session.frame()?; session.select_text("showcase-intro", "collaborator's")?; - session.overlay(OverlayEvent::SetKeyboardToolbarVisible(true))?; session.settle(200); save_session_png( &session, diff --git a/blocksuite/crates/playground/src/bin/bs_harness/s3_evidence.rs b/blocksuite/crates/playground/src/bin/bs_harness/s3_evidence.rs index 48d29b463a..9aff1536d6 100644 --- a/blocksuite/crates/playground/src/bin/bs_harness/s3_evidence.rs +++ b/blocksuite/crates/playground/src/bin/bs_harness/s3_evidence.rs @@ -345,7 +345,6 @@ pub(super) fn render_s3_evidence(out_dir: &Path) -> Result<()> { start_utf16: 4, end_utf16: 4, })))?; - session.overlay(OverlayEvent::SetKeyboardToolbarVisible(true))?; for ch in "@plan".chars() { session.update(|v, w, cx| { v.replace_text_in_range(None, &ch.to_string(), w, cx); @@ -607,7 +606,6 @@ pub(super) fn render_s3_evidence(out_dir: &Path) -> Result<()> { column_id: "col-0".into(), screen_pos: None, })?; - session.overlay(OverlayEvent::SetKeyboardToolbarVisible(true))?; session.settle(200); save_session_png( &session, diff --git a/blocksuite/crates/playground/src/bin/bs_harness/states.rs b/blocksuite/crates/playground/src/bin/bs_harness/states.rs index f41c1026bc..c6b182bbc5 100644 --- a/blocksuite/crates/playground/src/bin/bs_harness/states.rs +++ b/blocksuite/crates/playground/src/bin/bs_harness/states.rs @@ -231,8 +231,8 @@ pub(super) fn apply_overlay_state(session: &HeadlessSession, state: OverlayState session.overlay(OverlayEvent::Format(FormatAction::Link))?; } OverlayState::MobileKeyboardSelection => { + session.update(|v, w, cx| v.set_form_factor(playground::FormFactor::Tablet, w, cx))?; session.select_text(INTRO, "bold")?; - session.overlay(OverlayEvent::SetKeyboardToolbarVisible(true))?; } OverlayState::DragHandleHover | OverlayState::DragDropIndicator => { let snapshot = session.scroll_block_to(QUOTE, 40.0)?; diff --git a/blocksuite/crates/playground/src/chrome/mod.rs b/blocksuite/crates/playground/src/chrome/mod.rs index c8046b7f1f..bdfdc2124d 100644 --- a/blocksuite/crates/playground/src/chrome/mod.rs +++ b/blocksuite/crates/playground/src/chrome/mod.rs @@ -78,17 +78,12 @@ impl PlaygroundView { && self.database_record_sheet.is_none() && self.table_cell.is_some() && !self.table_is_readonly(); - let auto_kb_visible = !self.database_record_sheet.is_some() + let next_kb_visible = !self.database_record_sheet.is_some() && !table_bar_owns_slot && !self.page_readonly && (is_mobile_slot || live_kb_inset > 0.0) && self.editor.selection.is_some() && !self.keyboard_toolbar_dismissed; - let next_kb_visible = if self.database_record_sheet.is_some() || table_bar_owns_slot { - false - } else { - self.keyboard_toolbar_forced.unwrap_or(auto_kb_visible) - }; self.overlays.set_keyboard_toolbar_visible(next_kb_visible); if !was_toolbar_visible && self.overlays.keyboard_toolbar_visible() { self.editor.reveal = true; @@ -393,7 +388,6 @@ impl ui::Render for PlaygroundView { .max(0.0); if self.ime_insets.last_keyboard > 0.0 && kb_inset == 0.0 { self.keyboard_toolbar_dismissed = true; - self.keyboard_toolbar_forced = None; self.overlays.set_keyboard_toolbar_visible(false); } else if kb_inset > 0.0 && self.ime_insets.last_keyboard == 0.0 { self.keyboard_toolbar_dismissed = false; diff --git a/blocksuite/crates/playground/src/doc_panel.rs b/blocksuite/crates/playground/src/doc_panel.rs index c996926430..7553430e6d 100644 --- a/blocksuite/crates/playground/src/doc_panel.rs +++ b/blocksuite/crates/playground/src/doc_panel.rs @@ -554,7 +554,6 @@ impl PlaygroundView { self.context_menu_target = None; self.last_opened_link_url = None; self.last_link_popup_caret = None; - self.keyboard_toolbar_forced = None; self.database_readonly_toast_shown = false; self.database_record_sheet = None; self.doc_epoch = self.doc_epoch.wrapping_add(1); diff --git a/blocksuite/crates/playground/src/lib.rs b/blocksuite/crates/playground/src/lib.rs index 9d56370306..ee593ed35f 100644 --- a/blocksuite/crates/playground/src/lib.rs +++ b/blocksuite/crates/playground/src/lib.rs @@ -277,7 +277,6 @@ pub struct PlaygroundView { pub(crate) context_menu_target: Option, pub(crate) last_opened_link_url: Option, pub(crate) last_link_popup_caret: Option<(editor_session::DocPoint, u64)>, - pub(crate) keyboard_toolbar_forced: Option, pub(crate) overlays: Overlays, pub(crate) equation_snapshot: Option, pub(crate) calendar_clock: Option, @@ -439,7 +438,6 @@ impl PlaygroundView { context_menu_target: None, last_opened_link_url: None, last_link_popup_caret: None, - keyboard_toolbar_forced: None, overlays: Overlays::new(), equation_snapshot: None, calendar_clock: None, @@ -643,7 +641,6 @@ impl PlaygroundView { if self.page_readonly != readonly { self.page_readonly = readonly; if readonly { - self.keyboard_toolbar_forced = None; self.overlays.set_keyboard_toolbar_visible(false); self.overlays.close_keyboard_toolbar_panel(); } diff --git a/blocksuite/crates/playground/src/overlays/mod.rs b/blocksuite/crates/playground/src/overlays/mod.rs index 0b9ab8ae2a..80c4b864ba 100644 --- a/blocksuite/crates/playground/src/overlays/mod.rs +++ b/blocksuite/crates/playground/src/overlays/mod.rs @@ -2836,7 +2836,9 @@ mod tests { .expect("add embed card"); }); - session.overlay(OverlayEvent::SetKeyboardToolbarVisible(true)); + session.overlay(OverlayEvent::SetSelection(Some(ActiveSelection::caret( + "bidi-p", 0, + )))); let frame = session.frame(); assert_no_violations(&frame, "mobile keyboard toolbar"); let bar = element(&frame, "overlay.keyboard_toolbar"); @@ -2923,7 +2925,6 @@ mod tests { session.overlay(OverlayEvent::SetSelection(Some(ActiveSelection::caret( "mob-p", 0, )))); - session.overlay(OverlayEvent::SetKeyboardToolbarVisible(true)); let visible_top: Vec<&str> = DEFAULT_KEYBOARD_TOOLBAR_ITEMS .iter() diff --git a/blocksuite/crates/playground/src/overlays/tests_e1.rs b/blocksuite/crates/playground/src/overlays/tests_e1.rs index bbb8d21f84..b7abf0dc7a 100644 --- a/blocksuite/crates/playground/src/overlays/tests_e1.rs +++ b/blocksuite/crates/playground/src/overlays/tests_e1.rs @@ -777,7 +777,180 @@ mod tests { "remaining 2..9 span matching https://a.example must be unlinked" ); - // 2. R10B-P0-1 + P1-6: Narrow `<600px` opens auto `KeyboardToolbar` (deducted in `popover_viewport`); + // 1b. Body & Title LinkPopup `Edit` + `LinkApply` preserve concurrent peer link edits + // made while the inline `LinkBar` field is open (and `prop:title` opens `link_only`). + let sv_p1 = peer.encode_state_vector_v1().unwrap(); + peer.format_text( + "p1", + "prop:text", + 0, + 9, + TextAttributes::from([("link".to_string(), Any::String("https://a.example".into()))]), + 21, + ) + .unwrap(); + peer.format_text( + "r", + "prop:title", + 2, + 7, + TextAttributes::from([("link".to_string(), Any::String("https://t.example".into()))]), + 22, + ) + .unwrap(); + let diff_p1 = peer.encode_diff_v1(&sv_p1).unwrap(); + session.app.update(|cx| { + session + .window + .update(cx, |v, _, cx| { + v.page_mut() + .unwrap() + .apply_remote_update_v1(&diff_p1) + .unwrap(); + v.refresh_document(); + cx.notify(); + }) + .unwrap(); + }); + let _ = session.frame(); + + // Open `Edit` on body `p1` (`0..9` = `https://a.example`), then peer changes `0..2` to `b.example`. + session.overlay(OverlayEvent::SetSelection(Some(ActiveSelection::caret( + "p1", 4, + )))); + let _ = session.settle(); + session.overlay(OverlayEvent::LinkPopupAction(LinkPopupAction::Edit)); + let body_edit_frame = session.settle(); + assert!( + body_edit_frame + .elements + .contains_key("overlay.format_toolbar.link_input") + ); + let sv_p1_mid = peer.encode_state_vector_v1().unwrap(); + peer.format_text( + "p1", + "prop:text", + 0, + 2, + TextAttributes::from([("link".to_string(), Any::String("https://b.example".into()))]), + 23, + ) + .unwrap(); + let diff_p1_mid = peer.encode_diff_v1(&sv_p1_mid).unwrap(); + session.app.update(|cx| { + session + .window + .update(cx, |v, _, cx| { + v.page_mut() + .unwrap() + .apply_remote_update_v1(&diff_p1_mid) + .unwrap(); + v.refresh_document(); + cx.notify(); + }) + .unwrap(); + }); + let _ = session.frame(); + session.app.update(|cx| { + session + .window + .update(cx, |v, w, cx| { + v.link_input(w, cx, |bar| { + let len = bar.text().encode_utf16().count(); + bar.replace(Some(0..len), "https://c.example"); + }) + .unwrap(); + }) + .unwrap(); + }); + session.overlay(OverlayEvent::LinkApply); + assert_eq!( + marks_in_range(&session.text("p1"), 0, 2).link.as_deref(), + Some("https://b.example"), + "peer edit on 0..2 while LinkBar was open must survive LinkApply" + ); + assert_eq!( + marks_in_range(&session.text("p1"), 2, 9).link.as_deref(), + Some("https://c.example"), + "remaining 2..9 matching original URL must update to https://c.example" + ); + + // Open `Edit` on title `r` (`2..9` = `https://t.example`) -> opens standalone `link_only` field! + session.overlay(OverlayEvent::SetSelection(Some(ActiveSelection::caret( + "r", 4, + )))); + let _ = session.settle(); + session.overlay(OverlayEvent::LinkPopupAction(LinkPopupAction::Edit)); + let title_edit_frame = session.settle(); + assert!( + title_edit_frame + .elements + .contains_key("overlay.format_toolbar.link_input"), + "title LinkPopup Edit must open inline LinkBar" + ); + assert!( + !title_edit_frame + .elements + .contains_key("overlay.format_toolbar.bold"), + "title LinkBar must render link_only without paragraph mark buttons" + ); + let sv_r_mid = peer.encode_state_vector_v1().unwrap(); + peer.format_text( + "r", + "prop:title", + 2, + 2, + TextAttributes::from([("link".to_string(), Any::String("https://d.example".into()))]), + 24, + ) + .unwrap(); + let diff_r_mid = peer.encode_diff_v1(&sv_r_mid).unwrap(); + session.app.update(|cx| { + session + .window + .update(cx, |v, _, cx| { + v.page_mut() + .unwrap() + .apply_remote_update_v1(&diff_r_mid) + .unwrap(); + v.refresh_document(); + cx.notify(); + }) + .unwrap(); + }); + let _ = session.frame(); + session.app.update(|cx| { + session + .window + .update(cx, |v, w, cx| { + v.link_input(w, cx, |bar| { + let len = bar.text().encode_utf16().count(); + bar.replace(Some(0..len), "https://e.example"); + }) + .unwrap(); + }) + .unwrap(); + }); + session.overlay(OverlayEvent::LinkApply); + let after_title_apply = session.settle(); + assert!( + !after_title_apply + .elements + .contains_key("overlay.format_toolbar"), + "standalone title LinkBar must close after LinkApply" + ); + assert_eq!( + marks_in_range(&session.text("r"), 2, 4).link.as_deref(), + Some("https://d.example"), + "peer title link edit on 2..4 must survive LinkApply" + ); + assert_eq!( + marks_in_range(&session.text("r"), 4, 9).link.as_deref(), + Some("https://e.example"), + "remaining title link span 4..9 must update to https://e.example" + ); + + // 2. Narrow `<600px` opens auto `KeyboardToolbar` (deducted in `popover_viewport`); // widening to `1280px` or clearing selection immediately clears `KeyboardToolbar` and restores // desktop `FormatToolbar`; `Overlays::reset()` also clears `visible`. let narrow = open(480, 800, PlaygroundTheme::Light); @@ -837,7 +1010,7 @@ mod tests { "widening viewport >= 600px must restore desktop FormatToolbar" ); - // 3. R10B-P0-2: iOS `should_forward_ios_touch_immediately` must return true on prose whenever + // 3. iOS `should_forward_ios_touch_immediately` must return true on prose whenever // `link_popup`, `linked_doc_menu`, `doc_panel_tab`, or `context_menu` is open. narrow.app.update(|cx| { narrow @@ -874,6 +1047,32 @@ mod tests { 102.0, ); assert!(v.should_forward_ios_touch_immediately(200.0, prose_y, w)); + v.select_document_range( + crate::editor_session::DocumentSelection::caret( + crate::editor_session::DocPoint::new("showcase-intro", 1), + ), + w, + cx, + ); + assert!( + v.document_selection_geometry(w).has_selection, + "document_selection_geometry must stay populated while link_popup is open" + ); + v.overlays.close_link_popup(103.0); + v.set_form_factor(crate::FormFactor::Phone, w, cx); + v.select_document_range( + crate::editor_session::DocumentSelection::caret( + crate::editor_session::DocPoint::new("showcase-intro", 0), + ), + w, + cx, + ); + let layout = v.flow_layout().unwrap(); + v.sync_link_popup_for_caret(&layout, 104.0); + assert!( + v.overlays.link_popup().is_none(), + "touch hosts must not auto-open link_popup from caret movement" + ); v.overlays.reset(); assert!(!v.overlays.keyboard_toolbar_visible()); }) diff --git a/blocksuite/crates/playground/src/overlays/view.rs b/blocksuite/crates/playground/src/overlays/view.rs index d660ab8de9..83c92dccdf 100644 --- a/blocksuite/crates/playground/src/overlays/view.rs +++ b/blocksuite/crates/playground/src/overlays/view.rs @@ -521,39 +521,8 @@ impl PlaygroundView { cx.notify(); return true; } - if let Some(menu) = self.overlays.linked_doc_menu() { - let row_count = menu.results.items.len() + 1; - let selected = menu.selected; - match event.keystroke.key.as_str() { - "down" => { - let next = (selected + 1) % row_count; - self.dispatch_overlay(OverlayEvent::LinkedDocHover(next), window, cx); - return true; - } - "up" => { - let next = (selected + row_count - 1) % row_count; - self.dispatch_overlay(OverlayEvent::LinkedDocHover(next), window, cx); - return true; - } - "tab" => { - let next = if event.keystroke.modifiers.shift { - (selected + row_count - 1) % row_count - } else { - (selected + 1) % row_count - }; - self.dispatch_overlay(OverlayEvent::LinkedDocHover(next), window, cx); - return true; - } - "enter" => { - self.dispatch_overlay(OverlayEvent::LinkedDocSelect(selected), window, cx); - return true; - } - "escape" => { - self.dispatch_overlay(OverlayEvent::CloseLinkedDocMenu, window, cx); - return true; - } - _ => {} - } + if self.handle_linked_doc_key_down(event, window, cx) { + return true; } let now_ms = self.now_ms(cx); let secondary = event.keystroke.modifiers.secondary(cx); @@ -580,19 +549,6 @@ impl PlaygroundView { Some(result) } - /// Scroll a code block sideways so the caret at world x `caret_x` stays in view. - pub(crate) fn reveal_code_caret(&mut self, block_id: &str, caret_x: f32) { - let Some(layout) = self.flow_layout() else { - return; - }; - if let Some(block) = layout.block(block_id) - && let Some(code) = block.body.code_scroll - { - self.overlays - .reveal_code_x(block_id, caret_x - block.x - code.area.x, code); - } - } - /// 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. @@ -698,7 +654,10 @@ impl PlaygroundView { && (self.editor.drag_mode == crate::editor_session::DragSelectionMode::Character || self.editor.drag_moved); let selection = (!self.page_readonly && !drag_hides_toolbar) - .then(|| self.selection_format(layout)) + .then(|| { + self.selection_format(layout) + .or_else(|| self.standalone_link_selection_format(layout)) + }) .flatten(); if !self.page_readonly { self.sync_link_popup_for_caret(layout, now_ms); diff --git a/blocksuite/crates/playground/src/overlays/view_edits.rs b/blocksuite/crates/playground/src/overlays/view_edits.rs index 6902ffd036..7c7ad1eae8 100644 --- a/blocksuite/crates/playground/src/overlays/view_edits.rs +++ b/blocksuite/crates/playground/src/overlays/view_edits.rs @@ -147,7 +147,10 @@ impl PlaygroundView { } DocEdit::ColorMark { key, value } => self.format_color_mark(key, value, window, cx), DocEdit::Align(align) => self.format_selection(Some(align), None, window, cx), - DocEdit::Link(url) => self.format_selection(None, Some(url), window, cx), + DocEdit::Link { + url, + expected_prev_url, + } => self.format_selection(None, Some((url, expected_prev_url)), window, cx), DocEdit::Equation { target, latex } => { self.equation_snapshot = None; match &target { @@ -273,7 +276,7 @@ impl PlaygroundView { pub(super) fn format_selection( &mut self, align: Option, - link: Option>, + link: Option<(Option, Option)>, window: &mut Window, cx: &mut Context, ) -> DocResult { @@ -287,15 +290,19 @@ impl PlaygroundView { return Ok(()); }; // Alignment goes on every paragraph and list block the selection touches, empty - // ones included; a link only where there is text to carry it. - let mut blocks: Vec<&str> = Vec::new(); - let mut ranges: Vec<(&str, u64, u64)> = Vec::new(); + // ones included; a link only where there is text to carry it (including `prop:title` + // when opened from a title link's `Edit` capsule). + let allow_title = link.is_some() && align.is_none(); + let mut blocks: Vec = Vec::new(); + let mut ranges: Vec<(String, &'static str, u64, u64)> = Vec::new(); for block in &layout.blocks[a..=b] { - if !matches!(block.body.kind, FlowKind::Paragraph(_) | FlowKind::List(_)) { + let valid = matches!(block.body.kind, FlowKind::Paragraph(_) | FlowKind::List(_)) + || (allow_title && matches!(block.body.kind, FlowKind::Title)); + if !valid { continue; } - let id = block.block_id.as_str(); - blocks.push(id); + let id = block.block_id.clone(); + let prop_key = self.editable_prop_for_block(&id); let from = if id == start.block_id { start.offset() } else { @@ -306,9 +313,33 @@ impl PlaygroundView { } else { block.body.plain.encode_utf16().count() as u64 }; - if to > from { - ranges.push((id, from, to - from)); + if align.is_some() { + blocks.push(id.clone()); } + if to > from { + if let Some((_, Some(prev_url))) = &link { + let sub = self + .page() + .and_then(|p| p.read_editable_text(&id).ok()) + .map(|(doc_text, _)| { + super::view_link_popup::matching_link_subranges( + &doc_text, + from as usize, + to as usize, + prev_url, + ) + }) + .unwrap_or_default(); + for (s, e) in sub { + ranges.push((id.clone(), prop_key, s as u64, (e - s) as u64)); + } + } else { + ranges.push((id, prop_key, from, to - from)); + } + } + } + if align.is_none() && ranges.is_empty() { + return Ok(()); } let now = self.now_ms(cx) as u64; let page = self.page_mut()?; @@ -324,12 +355,12 @@ impl PlaygroundView { )?; } } - if let Some(url) = &link { - for (id, from, len) in &ranges { + if let Some((url, _)) = &link { + for (id, prop_key, from, len) in &ranges { let value = url.clone().map_or(Any::Null, Any::String); page.format_text( id, - "prop:text", + prop_key, *from, *len, TextAttributes::from([("link".to_string(), value)]), diff --git a/blocksuite/crates/playground/src/overlays/view_embed_controls.rs b/blocksuite/crates/playground/src/overlays/view_embed_controls.rs index 4f4f01c7e2..562384ff45 100644 --- a/blocksuite/crates/playground/src/overlays/view_embed_controls.rs +++ b/blocksuite/crates/playground/src/overlays/view_embed_controls.rs @@ -10,6 +10,19 @@ use crate::{ use super::OverlayEvent; impl PlaygroundView { + /// Scroll a code block sideways so the caret at world x `caret_x` stays in view. + pub(crate) fn reveal_code_caret(&mut self, block_id: &str, caret_x: f32) { + let Some(layout) = self.flow_layout() else { + return; + }; + if let Some(block) = layout.block(block_id) + && let Some(code) = block.body.code_scroll + { + self.overlays + .reveal_code_x(block_id, caret_x - block.x - code.area.x, code); + } + } + pub(crate) fn sync_embeds_shielded(&mut self) { let embeds_shielded = self.doc_panel_tab.is_some() || self.overlays.slash_menu().is_some() diff --git a/blocksuite/crates/playground/src/overlays/view_link_popup.rs b/blocksuite/crates/playground/src/overlays/view_link_popup.rs index 18c0785feb..2c0691fefb 100644 --- a/blocksuite/crates/playground/src/overlays/view_link_popup.rs +++ b/blocksuite/crates/playground/src/overlays/view_link_popup.rs @@ -77,7 +77,7 @@ fn link_range_at( /// Collect all live UTF-16 sub-ranges inside `[clamp_start, clamp_end)` whose `link` /// attribute equals `expected_url`. -fn matching_link_subranges( +pub(super) fn matching_link_subranges( rich: &blocksuite_playground_doc::read::RichText, clamp_start: usize, clamp_end: usize, @@ -201,33 +201,16 @@ impl PlaygroundView { ); match &deco.kind { DecorationKind::ReferenceChip(r) if !r.page_id.is_empty() => { - let mid_wx = block.x - + text.x - + f32::from(deco.bounds.origin.x) - + f32::from(deco.bounds.size.width) * 0.5; - let hit = block - .hit_text(wx, wy) - .or_else(|| block.hit_text(mid_wx, wy))?; let match_ref = |o: usize| { reference_at(&doc_text, o) .filter(|(_, pid)| pid == &r.page_id) .map(|(pos, _)| pos) }; - let off = match_ref(hit.utf16_offset as usize) - .or_else(|| { - hit.utf16_offset - .checked_sub(1) - .and_then(|o| match_ref(o as usize)) - }) - .or_else(|| { - block.hit_text(mid_wx, wy).and_then(|m| { - match_ref(m.utf16_offset as usize).or_else(|| { - m.utf16_offset - .checked_sub(1) - .and_then(|o| match_ref(o as usize)) - }) - }) - })?; + let off = match_ref(deco.source_utf16.start as usize).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("")); return Some(( @@ -241,30 +224,14 @@ impl PlaygroundView { )); } DecorationKind::Link(url) if !url.is_empty() => { - let mid_wx = block.x - + text.x - + f32::from(deco.bounds.origin.x) - + f32::from(deco.bounds.size.width) * 0.5; - let hit = block - .hit_text(wx, wy) - .or_else(|| block.hit_text(mid_wx, wy))?; let match_link = |o: usize| link_range_at(&doc_text, o).filter(|(_, _, u)| u == url); - let (start, end, resolved_url) = match_link(hit.utf16_offset as usize) + let (start, end, resolved_url) = match_link(deco.source_utf16.start as usize) .or_else(|| { - hit.utf16_offset - .checked_sub(1) - .and_then(|o| match_link(o as usize)) - }) - .or_else(|| { - block.hit_text(mid_wx, wy).and_then(|m| { - match_link(m.utf16_offset as usize).or_else(|| { - m.utf16_offset - .checked_sub(1) - .and_then(|o| match_link(o as usize)) - }) - }) - })?; + let hit = block.hit_text(wx, wy)?; + let o = hit.utf16_offset as usize; + match_link(o).or_else(|| o.checked_sub(1).and_then(match_link)) + })?; return Some(( LinkPopupTarget::Link { block_id: block.block_id.clone(), @@ -281,7 +248,7 @@ impl PlaygroundView { None } - fn editable_prop_for_block(&self, block_id: &str) -> &'static str { + pub(super) fn editable_prop_for_block(&self, block_id: &str) -> &'static str { if self .snapshot .as_ref() @@ -294,6 +261,34 @@ impl PlaygroundView { } } + pub(super) fn standalone_link_selection_format( + &self, + layout: &FlowLayout, + ) -> Option { + let block_id = self.overlays.standalone_link_block_id()?; + let selection = self.editor.selection.as_ref()?; + if selection.empty() + || self.editor.composing() + || selection.anchor.block_id != block_id + || selection.focus.block_id != block_id + { + return None; + } + let anchor_world = super::bounding_rect(&self.selection_rects(layout))?; + let from = selection.anchor.offset().min(selection.focus.offset()) as usize; + let to = selection.anchor.offset().max(selection.focus.offset()) as usize; + let marks = self + .page() + .and_then(|p| p.read_editable_text(block_id).ok()) + .map(|(text, _)| super::marks_in_range(&text, from, to)) + .unwrap_or_default(); + Some(super::SelectionFormat { + anchor_world, + marks, + align: None, + }) + } + /// Hit-test an inline link or `@reference` chip at screen `(x, y)` for the lightweight capsule. pub(crate) fn hit_link_popup_target_at( &self, @@ -348,7 +343,11 @@ impl PlaygroundView { None, transform, ); - if self.overlays.link_popup_contains_hover(&scene, x, y) { + if self + .overlays + .retain_or_reopen_link_popup_on_hover(&scene, x, y, now_ms) + { + cx.notify(); return; } } @@ -429,35 +428,65 @@ impl PlaygroundView { return; }; + let deco_world = |range: std::ops::Range| -> FlowRect { + block + .body + .text + .as_ref() + .and_then(|t| match &t.layout { + FlowTextLayout::Rich(r) => r + .inline_decorations() + .iter() + .find(|d| { + (d.source_utf16.start as usize) < range.end + && range.start < (d.source_utf16.end as usize) + }) + .map(|d| { + FlowRect::new( + block.x + t.x + f32::from(d.bounds.origin.x), + block.y + t.y + f32::from(d.bounds.origin.y), + f32::from(d.bounds.size.width), + f32::from(d.bounds.size.height), + ) + }), + _ => None, + }) + .unwrap_or(anchor_world) + }; + let auto_open = !self.is_touch_host(); if let Some((ref_off, page_id)) = reference_at(&doc_text, offset).or_else(|| { offset .checked_sub(1) .and_then(|o| reference_at(&doc_text, o)) }) { - let title = self.resolve_ref_title(&page_id, ""); - self.overlays.open_link_popup( - LinkPopupTarget::Reference { - block_id: block_id.clone(), - utf16_offset: ref_off, - page_id, - title, - }, - anchor_world, - false, - now_ms, - ); + if auto_open { + let title = self.resolve_ref_title(&page_id, ""); + self.overlays.open_link_popup( + LinkPopupTarget::Reference { + block_id: block_id.clone(), + utf16_offset: ref_off, + page_id, + title, + }, + deco_world(ref_off..ref_off + 1), + false, + now_ms, + ); + } } else if let Some((start, end, url)) = link_range_at(&doc_text, offset) { - self.overlays.open_link_popup( - LinkPopupTarget::Link { - block_id: block_id.clone(), - start_utf16: start, - end_utf16: end, - url, - }, - anchor_world, - false, - now_ms, - ); + if auto_open { + self.overlays.open_link_popup( + LinkPopupTarget::Link { + block_id: block_id.clone(), + start_utf16: start, + end_utf16: end, + url, + }, + deco_world(start..end), + false, + now_ms, + ); + } } else if self.overlays.link_popup().is_some_and(|p| !p.from_hover) { self.overlays.close_link_popup(now_ms); } @@ -536,10 +565,24 @@ impl PlaygroundView { window, cx, ); - if let Some(layout) = self.flow_layout() - && let Some(fmt) = self.selection_format(&layout) - { - self.overlays.open_link_field(&fmt, now_ms); + if let Some(layout) = self.flow_layout() { + if let Some(mut fmt) = self.selection_format(&layout) { + fmt.marks.link = Some(url); + self.overlays.open_link_field(&fmt, now_ms); + } else if let Some(anchor_world) = + super::bounding_rect(&self.selection_rects(&layout)) + { + let fmt = super::SelectionFormat { + anchor_world, + marks: super::MarkState { + link: Some(url), + ..Default::default() + }, + align: None, + }; + self.overlays + .open_link_field_for_block(&fmt, Some(block_id), now_ms); + } } cx.notify(); } diff --git a/blocksuite/crates/playground/src/overlays/view_linked_doc.rs b/blocksuite/crates/playground/src/overlays/view_linked_doc.rs index 3ff8168195..fff9c237b1 100644 --- a/blocksuite/crates/playground/src/overlays/view_linked_doc.rs +++ b/blocksuite/crates/playground/src/overlays/view_linked_doc.rs @@ -1,11 +1,54 @@ use blocksuite_playground_doc::session::SelectionSnapshot; -use ui::{Context, Window}; +use ui::{Context, KeyDownEvent, Window}; use crate::PlaygroundView; use super::*; impl PlaygroundView { + pub(super) fn handle_linked_doc_key_down( + &mut self, + event: &KeyDownEvent, + window: &mut Window, + cx: &mut Context, + ) -> bool { + let Some(menu) = self.overlays.linked_doc_menu() else { + return false; + }; + let row_count = menu.results.items.len() + 1; + let selected = menu.selected; + match event.keystroke.key.as_str() { + "down" => { + let next = (selected + 1) % row_count; + self.dispatch_overlay(OverlayEvent::LinkedDocHover(next), window, cx); + true + } + "up" => { + let next = (selected + row_count - 1) % row_count; + self.dispatch_overlay(OverlayEvent::LinkedDocHover(next), window, cx); + true + } + "tab" => { + let next = if event.keystroke.modifiers.shift { + (selected + row_count - 1) % row_count + } else { + (selected + 1) % row_count + }; + self.dispatch_overlay(OverlayEvent::LinkedDocHover(next), window, cx); + true + } + "enter" => { + self.dispatch_overlay(OverlayEvent::LinkedDocSelect(selected), window, cx); + true + } + "escape" => { + self.dispatch_overlay(OverlayEvent::CloseLinkedDocMenu, window, cx); + true + } + _ => false, + } + } + /// Handles `@` linked-document overlay events. Returns `true` when consumed. pub(super) fn handle_linked_doc_event( &mut self, diff --git a/blocksuite/crates/playground/src/overlays/view_mobile/mod.rs b/blocksuite/crates/playground/src/overlays/view_mobile/mod.rs index 67a23ab9e7..3f3bbe0a91 100644 --- a/blocksuite/crates/playground/src/overlays/view_mobile/mod.rs +++ b/blocksuite/crates/playground/src/overlays/view_mobile/mod.rs @@ -72,15 +72,6 @@ impl PlaygroundView { cx: &mut Context, ) -> bool { match event { - OverlayEvent::SetKeyboardToolbarVisible(visible) => { - self.keyboard_toolbar_forced = Some(*visible); - self.overlays.set_keyboard_toolbar_visible(*visible); - if *visible { - self.sync_keyboard_toolbar_state(); - } - cx.notify(); - true - } OverlayEvent::KeyboardToolbar(action) => { self.run_keyboard_toolbar_action(*action, window, cx); true @@ -267,7 +258,6 @@ impl PlaygroundView { | KeyboardToolbarAction::DatabaseKanbanView => {} KeyboardToolbarAction::Dismiss => { self.keyboard_toolbar_dismissed = true; - self.keyboard_toolbar_forced = None; self.overlays.set_keyboard_toolbar_visible(false); window.notify_text_selection_changed(&self.editor_focus); cx.notify(); @@ -422,7 +412,6 @@ impl PlaygroundView { /// Notify the view when the host software keyboard is explicitly shown or hidden. pub fn set_software_keyboard_visible(&mut self, visible: bool, cx: &mut Context) { - self.keyboard_toolbar_forced = None; if !visible { self.keyboard_toolbar_dismissed = true; self.ime_insets.last_keyboard = 0.0; @@ -759,7 +748,6 @@ impl PlaygroundView { Some(cx), ); self.editor = Default::default(); - self.keyboard_toolbar_forced = None; self.last_link_popup_caret = None; self.overlays.reset(); self.reading_anchor = None; diff --git a/blocksuite/crates/playground/src/overlays/view_mobile/tests.rs b/blocksuite/crates/playground/src/overlays/view_mobile/tests.rs index 85e6a2e123..99e3700c4d 100644 --- a/blocksuite/crates/playground/src/overlays/view_mobile/tests.rs +++ b/blocksuite/crates/playground/src/overlays/view_mobile/tests.rs @@ -240,7 +240,6 @@ fn keyboard_toolbar_0275_highlights_marks_and_link_single_step_undo() { start_utf16: 6, end_utf16: 15, }))); - session.overlay(OverlayEvent::SetKeyboardToolbarVisible(true)); let frame = session.frame(); assert!(audit_frame_snapshot(&frame).is_empty()); assert_eq!( @@ -360,7 +359,6 @@ fn keyboard_toolbar_0275_local_dates_image_picker_bookmark_prompt_and_table_gate session.overlay(OverlayEvent::SetSelection(Some(ActiveSelection::caret( "ops-p2", 12, )))); - session.overlay(OverlayEvent::SetKeyboardToolbarVisible(true)); let base_count = session.block_count("showcase-note"); // Duplicate & Delete each undo in 1 step. diff --git a/blocksuite/crates/playground/src/overlays/view_mobile/tests_edgeless_parity.rs b/blocksuite/crates/playground/src/overlays/view_mobile/tests_edgeless_parity.rs index ce770e43a2..1f92f15871 100644 --- a/blocksuite/crates/playground/src/overlays/view_mobile/tests_edgeless_parity.rs +++ b/blocksuite/crates/playground/src/overlays/view_mobile/tests_edgeless_parity.rs @@ -37,7 +37,6 @@ fn mobile_selection_suppresses_floating_toolbar_except_link_input_bar() { start_utf16: 0, end_utf16: 9, }))); - s.overlay(OverlayEvent::SetKeyboardToolbarVisible(true)); let snap = s.frame(); assert!( s.view(|v| v.document_selection().is_some_and(|sel| !sel.empty())), diff --git a/blocksuite/crates/playground/src/overlays/view_mobile/tests_parity.rs b/blocksuite/crates/playground/src/overlays/view_mobile/tests_parity.rs index b61ef64d6e..753dc8f151 100644 --- a/blocksuite/crates/playground/src/overlays/view_mobile/tests_parity.rs +++ b/blocksuite/crates/playground/src/overlays/view_mobile/tests_parity.rs @@ -642,7 +642,6 @@ fn render_mobile_keyboard_toolbar_evidence() { s.overlay(OverlayEvent::SetSelection(Some(ActiveSelection::caret( "p-body", 0, )))); - s.overlay(OverlayEvent::SetKeyboardToolbarVisible(true)); s.save_png( &out_dir.join(format!("after-{tag}-01-default-{tname}.png")), &format!("after-{tag}-01-default-{tname}"), @@ -684,7 +683,6 @@ fn render_mobile_keyboard_toolbar_evidence() { column_id: "col-0".into(), screen_pos: None, }); - s.overlay(OverlayEvent::SetKeyboardToolbarVisible(true)); s.save_png( &out_dir.join(format!("after-{tag}-05-table-disabled.png")), &format!("after-{tag}-05-table-disabled"), diff --git a/blocksuite/crates/playground/src/overlays/view_table_cell/toolbar.rs b/blocksuite/crates/playground/src/overlays/view_table_cell/toolbar.rs index 59b869038e..f4470b4300 100644 --- a/blocksuite/crates/playground/src/overlays/view_table_cell/toolbar.rs +++ b/blocksuite/crates/playground/src/overlays/view_table_cell/toolbar.rs @@ -101,7 +101,18 @@ impl PlaygroundView { })) .snapshot("overlay.table_toolbar.more", Some("overlay.table_toolbar")) .snapshot_text("More") - .child("\u{22EF}"); + .child({ + let ink = palette.text_secondary; + ui::canvas( + |_, _, _| (), + move |bounds, (), window, cx| { + crate::theme::IconPaint::named("MoreHorizontalIcon") + .paint(bounds, ink, window, cx); + }, + ) + .w(px(16.0)) + .h(px(16.0)) + }); return Some( div() .id("table-toolbar") diff --git a/blocksuite/crates/playground/src/touch_selection/drag.rs b/blocksuite/crates/playground/src/touch_selection/drag.rs index 5a30477e6d..fa05a9c723 100644 --- a/blocksuite/crates/playground/src/touch_selection/drag.rs +++ b/blocksuite/crates/playground/src/touch_selection/drag.rs @@ -39,6 +39,7 @@ impl PlaygroundView { pub fn should_forward_ios_touch_immediately(&self, x: f32, y: f32, window: &Window) -> bool { if self.mode == PlaygroundMode::Edgeless || self.is_selection_suppressed_by_overlay() + || self.overlays.link_popup().is_some() || self.table_cell.is_some() { return true; diff --git a/blocksuite/crates/playground/src/touch_selection/mod.rs b/blocksuite/crates/playground/src/touch_selection/mod.rs index 472a8bca5e..f4cd08f960 100644 --- a/blocksuite/crates/playground/src/touch_selection/mod.rs +++ b/blocksuite/crates/playground/src/touch_selection/mod.rs @@ -182,7 +182,6 @@ impl PlaygroundView { || self.overlays.equation_editor().is_some() || self.overlays.link_field().is_some() || self.overlays.slash_menu().is_some() - || self.overlays.link_popup().is_some() || self.overlays.linked_doc_menu().is_some() || self.doc_panel_tab.is_some() || self.overlays.context_menu().is_some() diff --git a/blocksuite/crates/playground/web/index.html b/blocksuite/crates/playground/web/index.html index a24da34953..76b1dce08a 100644 --- a/blocksuite/crates/playground/web/index.html +++ b/blocksuite/crates/playground/web/index.html @@ -76,6 +76,7 @@ fonts.forEach((bytes, index) => { try { playgroundWasm.register_web_font(bytes); + window.__playgroundPreview?.registerFont?.(bytes); } catch (err) { throw new Error(`font ${fontUrls[index]}: ${err.message || err}`); } diff --git a/blocksuite/crates/playground/web/preview-workers.js b/blocksuite/crates/playground/web/preview-workers.js index 4ba7b8307b..6cf7c68366 100644 --- a/blocksuite/crates/playground/web/preview-workers.js +++ b/blocksuite/crates/playground/web/preview-workers.js @@ -11,9 +11,19 @@ export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.loc const pendingCode = new Map(); const cachedPdfBytes = new Map(); const mountedHtmlEmbeds = new Map(); + const registeredFonts = []; + let typstFontsSent = 0; let embedsShielded = false; let interactiveEmbedId = null; + function syncTypstFonts(worker) { + while (typstFontsSent < registeredFonts.length) { + const fontBytes = registeredFonts[typstFontsSent]; + typstFontsSent += 1; + worker.postMessage({ id: nextId++, op: 'register_font', fontBytes }); + } + } + function applyEmbedPointerEvents() { for (const [id, entry] of mountedHtmlEmbeds.entries()) { entry.iframe.style.pointerEvents = @@ -68,7 +78,47 @@ export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.loc applyEmbedPointerEvents(); } }; + const EMBED_WHEEL_BRIDGE = + ""; + const wrapEmbedBlobHtml = html => { + const m = /^\s*]*>/i.exec(html); + return m + ? `${html.slice(0, m[0].length)}${EMBED_WHEEL_BRIDGE}${html.slice(m[0].length)}` + : `${EMBED_WHEEL_BRIDGE}${html}`; + }; + const onWindowWheel = () => deactivateInteractiveEmbed(); + const onWindowMessage = event => { + const data = event?.data; + if (!data || data.type !== '__affine_embed_wheel') return; + let matchedIframe = null; + for (const entry of mountedHtmlEmbeds.values()) { + if (entry.iframe.contentWindow && entry.iframe.contentWindow === event.source) { + matchedIframe = entry.iframe; + break; + } + } + if (!matchedIframe) return; + deactivateInteractiveEmbed(); + const canvas = globalThis.document?.querySelector?.('canvas'); + if (canvas && typeof globalThis.WheelEvent === 'function') { + const r = + typeof matchedIframe.getBoundingClientRect === 'function' + ? matchedIframe.getBoundingClientRect() + : { left: 0, top: 0 }; + canvas.dispatchEvent( + new globalThis.WheelEvent('wheel', { + deltaX: Number(data.dx) || 0, + deltaY: Number(data.dy) || 0, + deltaMode: Number(data.dm) || 0, + clientX: (Number(r.left) || 0) + (Number(data.cx) || 0), + clientY: (Number(r.top) || 0) + (Number(data.cy) || 0), + bubbles: true, + cancelable: true, + }) + ); + } + }; if (typeof globalThis.window?.addEventListener === 'function') { globalThis.window.addEventListener('pointerdown', onWindowPointerDown, { @@ -78,6 +128,7 @@ export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.loc capture: true, passive: true, }); + globalThis.window.addEventListener('message', onWindowMessage); } if (globalThis.window) { globalThis.window.__playgroundPreviewDispose = () => { @@ -88,6 +139,7 @@ export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.loc globalThis.window.removeEventListener('wheel', onWindowWheel, { capture: true, }); + globalThis.window.removeEventListener('message', onWindowMessage); } for (const entry of mountedHtmlEmbeds.values()) { entry.iframe.remove?.(); @@ -312,6 +364,7 @@ export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.loc } else if (kind === 'typst' && typstWorker) { typstWorker.terminate?.(); typstWorker = null; + typstFontsSent = 0; } for (const [id, req] of pendingCode.entries()) { if (kind && req.kind !== kind) continue; @@ -351,11 +404,21 @@ export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.loc typstWorker.addEventListener('messageerror', () => failAllPendingCode('typst', 'typst worker messageerror') ); + typstFontsSent = 0; } + syncTypstFonts(typstWorker); return typstWorker; } window.__playgroundPreview = { + registerFont(bytes) { + const copy = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes || []); + if (copy.byteLength === 0) return; + registeredFonts.push(copy); + if (typstWorker) { + syncTypstFonts(typstWorker); + } + }, requestMath(latex, display, fontSizePt, colorCss, dpr) { const id = nextId++; pendingMath.set(id, { latex, display, fontSizePt, colorCss, dpr }); @@ -466,7 +529,7 @@ export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.loc let entry = mountedHtmlEmbeds.get(id); if (!entry) { const blobUrl = URL.createObjectURL( - new Blob([htmlStr], { type: 'text/html;charset=utf-8' }) + new Blob([wrapEmbedBlobHtml(htmlStr)], { type: 'text/html;charset=utf-8' }) ); const iframe = document.createElement('iframe'); // Never include allow-same-origin for user-authored HTML embeds or ```html previews. @@ -489,7 +552,7 @@ export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.loc } else if (entry.html !== htmlStr) { URL.revokeObjectURL(entry.blobUrl); const blobUrl = URL.createObjectURL( - new Blob([htmlStr], { type: 'text/html;charset=utf-8' }) + new Blob([wrapEmbedBlobHtml(htmlStr)], { type: 'text/html;charset=utf-8' }) ); entry.blobUrl = blobUrl; entry.html = htmlStr; diff --git a/packages/frontend/Cargo.toml b/packages/frontend/Cargo.toml index 7fe18cb457..90e1988a07 100644 --- a/packages/frontend/Cargo.toml +++ b/packages/frontend/Cargo.toml @@ -272,6 +272,34 @@ opt-level = "s" opt-level = "s" [profile.dev.package.comemo] opt-level = "s" +[profile.dev.package.wgpu-core] +opt-level = "s" +[profile.dev.package.wgpu-hal] +opt-level = "s" +[profile.dev.package.naga] +opt-level = "s" +[profile.dev.package.hayro] +opt-level = "s" +[profile.dev.package.hayro-interpret] +opt-level = "s" +[profile.dev.package.hayro-syntax] +opt-level = "s" +[profile.dev.package.hayro-font] +opt-level = "s" +[profile.dev.package.hayro-svg] +opt-level = "s" +[profile.dev.package.resvg] +opt-level = "s" +[profile.dev.package.usvg] +opt-level = "s" +[profile.dev.package.tiny-skia] +opt-level = "s" +[profile.dev.package.cosmic-text] +opt-level = "s" +[profile.dev.package.swash] +opt-level = "s" +[profile.dev.package.skrifa] +opt-level = "s" [profile.test] debug = 0 diff --git a/packages/frontend/hosts/android/kotlin/app/affine/pro/host/MainActivity.kt b/packages/frontend/hosts/android/kotlin/app/affine/pro/host/MainActivity.kt index 8cf0afdf73..cdec117437 100644 --- a/packages/frontend/hosts/android/kotlin/app/affine/pro/host/MainActivity.kt +++ b/packages/frontend/hosts/android/kotlin/app/affine/pro/host/MainActivity.kt @@ -1988,11 +1988,14 @@ internal class DocumentSelectionHandleView( handlePath.reset() handlePath.moveTo(tipX, tipY) if (leanLeft) { - handlePath.quadTo(tipX, centerY - radius * 0.4f, centerX + radius, centerY) + handlePath.lineTo(centerX, tipY) + handlePath.lineTo(tipX, centerY) } else { - handlePath.quadTo(tipX, centerY - radius * 0.4f, centerX - radius, centerY) + handlePath.lineTo(tipX, centerY) + handlePath.lineTo(centerX, tipY) } - handlePath.addCircle(centerX, centerY, radius, Path.Direction.CW) + handlePath.close() + handlePath.addCircle(centerX, centerY, radius, Path.Direction.CCW) canvas.drawPath(handlePath, handlePaint) } } @@ -2522,7 +2525,11 @@ internal class AffineSurfaceView( private var touchDownY = 0f private var touchMovedBeyondSlop = false - override fun onCheckIsTextEditor(): Boolean = true + override fun onCheckIsTextEditor(): Boolean { + if (autofillProvider()?.focusedFieldId() != null) return true + val handle = handleProvider() + return handle != 0L && NativeBridge.nativeWantsSoftwareKeyboard(handle) + } override fun onTouchEvent(event: MotionEvent): Boolean { val handle = handleProvider() @@ -2592,13 +2599,12 @@ internal class AffineSurfaceView( if (NativeBridge.nativeWantsSoftwareKeyboard(handle)) { if (requestedKb && !touchMovedBeyondSlop) { requestFocus() + imm?.restartInput(this) imm?.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT) } } else { imm?.hideSoftInputFromWindow(windowToken, 0) - if (NativeBridge.nativeGetFocusedBlockHash(handle) == 0L && autofillProvider()?.focusedFieldId() == null) { - clearFocus() - } + imm?.restartInput(this) } } } @@ -2664,7 +2670,7 @@ internal class AffineSurfaceView( return super.onGenericMotionEvent(event) } - override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection { + override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection? { val af = autofillProvider() if (af != null && af.focusedFieldId() != null) { outAttrs.inputType = if (af.isFocusedFieldMasked()) { @@ -2678,6 +2684,12 @@ internal class AffineSurfaceView( outAttrs.initialSelEnd = current.length return AutofillVirtualInputConnection(af, onMutated) } + val handle = handleProvider() + if (handle == 0L || !NativeBridge.nativeWantsSoftwareKeyboard(handle)) { + outAttrs.inputType = InputType.TYPE_NULL + outAttrs.imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI + return null + } val boundGen = af?.currentFocusGeneration() ?: 0L return createInputConnection( handleProvider, @@ -2889,6 +2901,7 @@ class AutofillVirtualInputConnection( class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCallback { private var nativeHandle: Long = 0L + private lateinit var rootContainer: FrameLayout private lateinit var surfaceView: AffineSurfaceView private lateinit var documentHandleView: DocumentSelectionHandleView private lateinit var bootstrapCoordinator: AndroidBootstrapCoordinator @@ -3155,7 +3168,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall } }, ) - val rootContainer = FrameLayout(this).apply { + rootContainer = FrameLayout(this).apply { setBackgroundColor(clearColorArgb) addView( surfaceView, @@ -3246,15 +3259,6 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall super.onDestroy() } - override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { - if (nativeHandle != 0L && ::surfaceView.isInitialized && !surfaceView.hasFocus()) { - if (event.isCtrlPressed || event.isMetaPressed) { - return surfaceView.onKeyDown(keyCode, event) - } - } - return super.onKeyDown(keyCode, event) - } - override fun doFrame(frameTimeNanos: Long) { frameCallbackPosted = false if (!frameLoopActive || !surfaceReady || nativeHandle == 0L) return @@ -3413,9 +3417,9 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall val nextBlockHash = NativeBridge.nativeGetFocusedBlockHash(nativeHandle) val wantsKeyboard = NativeBridge.nativeWantsSoftwareKeyboard(nativeHandle) val wantsCodeInput = NativeBridge.nativeWantsCodeInput(nativeHandle) - val keyboardActivated = !lastWantsKeyboard && wantsKeyboard + val wantsKeyboardChanged = wantsKeyboard != lastWantsKeyboard val codeModeChanged = wantsCodeInput != lastWantsCodeInput - if (nextSeq == lastImeChangeSeq && nextBlockHash == lastFocusedBlockHash && !keyboardActivated && wantsKeyboard == lastWantsKeyboard && !codeModeChanged) { + if (nextSeq == lastImeChangeSeq && nextBlockHash == lastFocusedBlockHash && !wantsKeyboardChanged && !codeModeChanged) { return } val blockChanged = nextBlockHash != lastFocusedBlockHash @@ -3426,13 +3430,10 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager ?: return if (!wantsKeyboard) { imm.hideSoftInputFromWindow(surfaceView.windowToken, 0) - if (nextBlockHash == 0L && !documentBufferController.isAutofillFocused()) { - surfaceView.clearFocus() - } } - if (blockChanged || keyboardActivated || codeModeChanged) { + if (blockChanged || wantsKeyboardChanged || codeModeChanged) { imm.restartInput(surfaceView) - } else { + } else if (wantsKeyboard) { imm.updateSelection( surfaceView, imeController.selectionStart(), @@ -3441,7 +3442,9 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall imeController.composingEnd(), ) } - pushCursorAnchorInfo(imm) + if (wantsKeyboard) { + pushCursorAnchorInfo(imm) + } } private fun pushCursorAnchorInfo(existingImm: InputMethodManager? = null) { @@ -3508,18 +3511,38 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall if (lastDarkTheme == isDark) return lastDarkTheme = isDark val isLight = !isDark + val bg = if (isDark) 0xFF141414.toInt() else 0xFFFFFFFF.toInt() + clearColorArgb = bg + if (::rootContainer.isInitialized) { + rootContainer.setBackgroundColor(bg) + } + window.decorView.setBackgroundColor(bg) + window.statusBarColor = Color.TRANSPARENT + window.navigationBarColor = Color.TRANSPARENT + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + window.isNavigationBarContrastEnforced = false + } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { - val mask = WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS + val mask = WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS or + WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS val appearance = if (isLight) mask else 0 window.insetsController?.setSystemBarsAppearance(appearance, mask) } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val decor = window.decorView - val flags = decor.systemUiVisibility - decor.systemUiVisibility = if (isLight) { + var flags = decor.systemUiVisibility + flags = if (isLight) { flags or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR } else { flags and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv() } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + flags = if (isLight) { + flags or View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR + } else { + flags and View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR.inv() + } + } + decor.systemUiVisibility = flags } } @@ -3541,7 +3564,6 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall } private fun installInsetsBridge(root: View) { - root.setBackgroundColor(0xFFFFFFFF.toInt()) root.setOnApplyWindowInsetsListener { v, insets -> forwardInsets(v, insets) insets diff --git a/packages/frontend/hosts/ios/Sources/MetalHostViewController.swift b/packages/frontend/hosts/ios/Sources/MetalHostViewController.swift index afa0a3445c..bb29f4e767 100644 --- a/packages/frontend/hosts/ios/Sources/MetalHostViewController.swift +++ b/packages/frontend/hosts/ios/Sources/MetalHostViewController.swift @@ -2105,7 +2105,12 @@ final class MetalHostViewController: } } + override var preferredStatusBarStyle: UIStatusBarStyle { + textRenderingBridge.isDarkCanvas ? .lightContent : .darkContent + } + private func applyClearColor(_ rgba: UInt32) { + let wasDark = textRenderingBridge.isDarkCanvas let bg = textRenderingBridge.applyClearColorRgba(rgba) if view.backgroundColor != bg { view.backgroundColor = bg @@ -2113,6 +2118,14 @@ final class MetalHostViewController: if hostView.backgroundColor != bg { hostView.backgroundColor = bg } + if view.window?.backgroundColor != bg { + view.window?.backgroundColor = bg + } + let expectedStyle: UIUserInterfaceStyle = textRenderingBridge.isDarkCanvas ? .dark : .light + if overrideUserInterfaceStyle != expectedStyle || textRenderingBridge.isDarkCanvas != wasDark { + overrideUserInterfaceStyle = expectedStyle + setNeedsStatusBarAppearanceUpdate() + } } private var isSystemSelectionGestureActive: Bool { diff --git a/packages/frontend/hosts/ios/Sources/TextRenderingBridge.swift b/packages/frontend/hosts/ios/Sources/TextRenderingBridge.swift index d976ab91ee..152764ce93 100644 --- a/packages/frontend/hosts/ios/Sources/TextRenderingBridge.swift +++ b/packages/frontend/hosts/ios/Sources/TextRenderingBridge.swift @@ -11,7 +11,7 @@ final class TextRenderingBridge { static let defaultClearColorRgba: UInt32 = 0xFAFA_FCFF let font = UIFont.systemFont(ofSize: 17, weight: .regular) - private var isDarkCanvas = false + private(set) var isDarkCanvas = false private var canvasBackgroundColor = UIColor( red: 250.0 / 255.0, green: 250.0 / 255.0, diff --git a/packages/frontend/hosts/ios/src/editor_runtime.rs b/packages/frontend/hosts/ios/src/editor_runtime.rs index 66aac0a8cd..73d292ad2c 100644 --- a/packages/frontend/hosts/ios/src/editor_runtime.rs +++ b/packages/frontend/hosts/ios/src/editor_runtime.rs @@ -244,7 +244,18 @@ impl IosEditorRuntime { if timestamp_sec.is_finite() { self.last_frame_timestamp_sec = timestamp_sec; } - IosHostState::DEFAULT_CLEAR_COLOR_RGBA + let is_dark = self + .app + .update(|cx| { + self.view + .read_with(cx, |v, _| v.theme() == playground::PlaygroundTheme::Dark) + }) + .unwrap_or(false); + if is_dark { + 0x1414_14FF + } else { + IosHostState::DEFAULT_CLEAR_COLOR_RGBA + } } pub(crate) fn set_form_factor(&mut self, form_factor: FormFactor) { diff --git a/packages/frontend/hosts/web/tests/preview-workers.test.mjs b/packages/frontend/hosts/web/tests/preview-workers.test.mjs index 7d1f311ec4..7a6ead00db 100644 --- a/packages/frontend/hosts/web/tests/preview-workers.test.mjs +++ b/packages/frontend/hosts/web/tests/preview-workers.test.mjs @@ -221,6 +221,23 @@ void test('reconcileHtmlEmbeds mounts, updates html blob URLs, shields, and unmo liveIframe.emit('pointerleave', {}); assert.equal(liveIframe.style.pointerEvents, 'none'); + // Cross-origin blob iframe wheel postMessage deactivates iframe capture immediately. + liveIframe.contentWindow = {}; + globalThis.window.emit('pointerdown', { clientX: 50, clientY: 100 }); + assert.equal(liveIframe.style.pointerEvents, 'auto'); + globalThis.window.emit('message', { + source: liveIframe.contentWindow, + data: { + type: '__affine_embed_wheel', + dx: 0, + dy: 120, + dm: 0, + cx: 10, + cy: 10, + }, + }); + assert.equal(liveIframe.style.pointerEvents, 'none'); + // Shield hides layer and disables iframe pointer events even after activation. globalThis.window.emit('pointerdown', { clientX: 50, clientY: 100 }); assert.equal(liveIframe.style.pointerEvents, 'auto'); @@ -273,8 +290,15 @@ void test('mermaid and typst worker errors fail pending requests instead of stal assert.equal(env.workers[1].terminated, false); assert.equal(env.workers[1].posted.length, 1); + bridge.registerFont(new Uint8Array([0, 1, 0, 0])); bridge.requestCodePreview('typst', '= Hello', true, 2); assert.equal(env.workers.length, 3); + assert.equal( + env.workers[2].posted[0].op, + 'register_font', + 'typst worker must receive registered web fonts before its first compile' + ); + assert.equal(env.workers[2].posted[1].source, '= Hello'); env.workers[2].emit('messageerror', {}); assert.equal( env.workers[2].terminated, @@ -290,7 +314,9 @@ void test('mermaid and typst worker errors fail pending requests instead of stal 4, 'must spawn a fresh typst worker after messageerror' ); - assert.equal(env.workers[3].posted.length, 1); + assert.equal(env.workers[3].posted.length, 2); + assert.equal(env.workers[3].posted[0].op, 'register_font'); + assert.equal(env.workers[3].posted[1].source, '= Retry'); } finally { env.restore(); }