diff --git a/blocksuite/crates/editor/src/block_flow/mod.rs b/blocksuite/crates/editor/src/block_flow/mod.rs index 9bf276585a..4a283c6601 100644 --- a/blocksuite/crates/editor/src/block_flow/mod.rs +++ b/blocksuite/crates/editor/src/block_flow/mod.rs @@ -72,10 +72,10 @@ pub use preview::{ PdfPreviewPage, PdfStagingMailbox, bump_latex_formula_revision, bump_preview_revision, can_render_pdf_pages, clamp_pdf_raster_scale, document_preview_revision, downsample_rgba_2x_until_cap, fast_pdf_content_hash, hsla_to_css_hex, latex_formula_revision, - parse_pdf_document, parse_pdf_document_arc, parse_pdf_document_scoped, parse_pdf_renderer, - preview_revision, register_math_preview_provider, register_pdf_page_provider, - render_math_cached, render_pdf_page, request_pdf_page_for_ui, rgba_pixels_to_render_image, - snapshot_has_math, + node_has_math, parse_pdf_document, parse_pdf_document_arc, parse_pdf_document_scoped, + parse_pdf_renderer, preview_revision, register_math_preview_provider, + register_pdf_page_provider, render_math_cached, render_pdf_page, request_pdf_page_for_ui, + rgba_pixels_to_render_image, snapshot_has_math, }; pub use surface_ref::surface_ref_target_bounds; pub use viewport::{ diff --git a/blocksuite/crates/editor/src/block_flow/preview.rs b/blocksuite/crates/editor/src/block_flow/preview.rs index 6ba4172e18..9f9a78ff43 100644 --- a/blocksuite/crates/editor/src/block_flow/preview.rs +++ b/blocksuite/crates/editor/src/block_flow/preview.rs @@ -102,14 +102,11 @@ fn rich_text_has_inline_latex(text: &RichText) -> bool { }) } -/// Whether `snapshot` holds any block or inline LaTeX: `affine:latex` blocks, and inline -/// equations in paragraph, list, callout, simple table cell, and database title, row title, -/// and rich-text cell text. -pub fn snapshot_has_math(snapshot: &blocksuite_playground_doc::read::PageSnapshot) -> bool { - let Some(root) = snapshot.root.as_ref() else { - return false; - }; - root.walk().any(|node| match &node.content { +/// Whether `node` itself, without its children, holds block or inline LaTeX: an `affine:latex` +/// block, or an inline equation in paragraph, list, callout, simple table cell, or database +/// title, row title, and rich-text cell text. +pub fn node_has_math(node: &BlockNode) -> bool { + match &node.content { BlockContent::Latex { .. } => true, BlockContent::Paragraph { text, .. } | BlockContent::List { text, .. } @@ -120,7 +117,15 @@ pub fn snapshot_has_math(snapshot: &blocksuite_playground_doc::read::PageSnapsho .any(|c| rich_text_has_inline_latex(&c.text)), BlockContent::Database(db) => database_rich_texts(db).any(rich_text_has_inline_latex), _ => false, - }) + } +} + +/// Whether a block of `snapshot` holds math (see [`node_has_math`]). +pub fn snapshot_has_math(snapshot: &blocksuite_playground_doc::read::PageSnapshot) -> bool { + snapshot + .root + .as_ref() + .is_some_and(|root| root.walk().any(node_has_math)) } /// Every rich text an `affine:database` block renders: its title, row titles, and rich-text cells. diff --git a/blocksuite/crates/editor/src/overlays/paint_page/mod.rs b/blocksuite/crates/editor/src/overlays/paint_page/mod.rs index cc38b0a8d1..c8e216e379 100644 --- a/blocksuite/crates/editor/src/overlays/paint_page/mod.rs +++ b/blocksuite/crates/editor/src/overlays/paint_page/mod.rs @@ -31,6 +31,16 @@ use crate::{ use super::*; +/// Writes its text only when something formats it, so snapshot text costs nothing in builds +/// without element snapshots. +struct LazyDisplay(F); + +impl) -> std::fmt::Result> std::fmt::Display for LazyDisplay { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + (self.0)(f) + } +} + impl Overlays { /// Build what the overlays draw inside the page viewport, in the viewport element's /// coordinates and above every block: block controls, the drag handle and the drop @@ -309,12 +319,9 @@ impl Overlays { cx, &mut elements, ); - let table_cells = scene.snapshot.block(&block.block_id).and_then(|n| match &n - .content - { - BlockContent::Table(t) => Some(&t.cells), - _ => None, - }); + // Only element snapshots read the cell text, so the table lookup runs on the + // first formatted cell and never in a build without snapshots. + let table_cells = std::cell::OnceCell::new(); let table_scroll_x = self.code_scroll_x(&block.block_id); let vis_left = rect.x; let vis_right = rect.right(); @@ -329,13 +336,6 @@ impl Overlays { if !viewport.intersects(&target) { continue; } - let initial = table_cells - .and_then(|cells| { - cells - .get(&(cell.row_id.clone(), cell.column_id.clone())) - .map(|c| c.text.plain.clone()) - }) - .unwrap_or_default(); let (bid, rid, cid) = ( block.block_id.clone(), cell.row_id.clone(), @@ -372,7 +372,24 @@ impl Overlays { ), Some(PAGE_SURFACE_ID), ) - .snapshot_text(initial); + .snapshot_text(format_args!( + "{}", + LazyDisplay(|f: &mut std::fmt::Formatter<'_>| { + let cells = table_cells.get_or_init(|| { + scene.snapshot.block(&block.block_id).and_then(|n| { + match &n.content { + BlockContent::Table(t) => Some(&t.cells), + _ => None, + } + }) + }); + let key = (cell.row_id.clone(), cell.column_id.clone()); + match cells.and_then(|cells| cells.get(&key)) { + Some(c) => f.write_str(&c.text.plain), + None => Ok(()), + } + }) + )); } elements.push(element.into_any_element()); } diff --git a/blocksuite/crates/editor/src/overlays/scrollbar.rs b/blocksuite/crates/editor/src/overlays/scrollbar.rs index 73321adeec..d993431da2 100644 --- a/blocksuite/crates/editor/src/overlays/scrollbar.rs +++ b/blocksuite/crates/editor/src/overlays/scrollbar.rs @@ -315,7 +315,7 @@ pub(super) fn build_block_hscrollbar( }), ) .snapshot( - ui::SharedString::from(format!("{snapshot_id}.hscrollbar")), + format_args!("{snapshot_id}.hscrollbar"), Some(PAGE_SURFACE_ID), ) .child( diff --git a/blocksuite/crates/editor/src/overlays/state.rs b/blocksuite/crates/editor/src/overlays/state.rs index ac1f51d7a9..73397ddae1 100644 --- a/blocksuite/crates/editor/src/overlays/state.rs +++ b/blocksuite/crates/editor/src/overlays/state.rs @@ -21,6 +21,14 @@ impl Overlays { } } + /// Whether a link or reference popup is open or still fading out. A popup that fades out + /// opens again when the pointer comes back over it or its hover bridge. + pub fn has_live_or_closing_link_popup(&self, now_ms: f64) -> bool { + self.link_popup + .as_ref() + .is_some_and(|popup| !popup.presence.gone(now_ms)) + } + /// The primary button went down on the page: the slash menu, linked-doc menu, the link /// field, context menu, and a block drag end. pub fn pointer_pressed(&mut self, now_ms: f64) { diff --git a/blocksuite/crates/playground/src/editor_session/mod.rs b/blocksuite/crates/playground/src/editor_session/mod.rs index 7caa428bcf..6d2833e6fd 100644 --- a/blocksuite/crates/playground/src/editor_session/mod.rs +++ b/blocksuite/crates/playground/src/editor_session/mod.rs @@ -28,7 +28,7 @@ use blocksuite_playground_doc::{ use ui::{MouseButton, MouseDownEvent, MouseMoveEvent, Pixels, Point}; use super::*; -use crate::block_flow::{FlowBlock, FlowRect}; +use crate::block_flow::{FlowBlock, FlowRect, node_has_math}; impl PlaygroundView { pub(crate) fn page(&self) -> Option<&PageDocSession> { @@ -514,6 +514,7 @@ impl PlaygroundView { let Some(node) = node_mut(root, id) else { return false; }; + let old_has_math = node_has_math(node); let key = match &mut node.content { BlockContent::Page { title } => { *title = rich; @@ -536,8 +537,10 @@ impl PlaygroundView { id.to_owned() }); } + let new_has_math = node_has_math(node); node.props.insert(key.into(), value); self.doc_rev += 1; + self.advance_math_cache(self.doc_rev - 1, old_has_math, new_has_math); true } diff --git a/blocksuite/crates/playground/src/layout_cache.rs b/blocksuite/crates/playground/src/layout_cache.rs index e619fdc516..20bf841b00 100644 --- a/blocksuite/crates/playground/src/layout_cache.rs +++ b/blocksuite/crates/playground/src/layout_cache.rs @@ -458,6 +458,8 @@ impl PlaygroundView { *has_math } _ => { + #[cfg(test)] + tests::MATH_WALKS.set(tests::MATH_WALKS.get() + 1); let has_math = crate::block_flow::snapshot_has_math(snapshot); self.flow.has_math_cache = Some((self.page_id.clone(), self.doc_rev, has_math)); has_math @@ -465,11 +467,25 @@ impl PlaygroundView { } } + /// Carries the math memo across a text edit of one block that moved the document from + /// `prev_rev` to the current revision, given whether the block held math before and after + /// the edit. A block that lost its math may have held the last formula, so the memo is + /// dropped and the next frame walks the document again. + pub(crate) fn advance_math_cache(&mut self, prev_rev: u64, old_has: bool, new_has: bool) { + self.flow.has_math_cache = match self.flow.has_math_cache.take() { + Some((page_id, rev, has_math)) + if page_id == self.page_id && rev == prev_rev && !(old_has && !new_has) => + { + Some((page_id, self.doc_rev, has_math || new_has)) + } + _ => None, + }; + } + pub(crate) fn ensure_layout(&mut self, width: f32, window: &Window) -> Option> { use std::hash::{Hash, Hasher}; let snapshot = self.snapshot.clone()?; - let has_math = self.snapshot_has_math_cached(&snapshot); let is_rtl = window.layout_direction().is_rtl(); let (now_ms, utc_offset_minutes) = self.local_calendar_clock(); let local_day = @@ -493,6 +509,11 @@ impl PlaygroundView { latex: editor.committed_draft().to_string(), }, }); + // An equation draft or a code preview already follows every preview result, so the + // document is not walked for math. + let has_math = equation_draft.is_none() + && self.flow.code_preview_blocks.is_empty() + && self.snapshot_has_math_cached(&snapshot); let focused_table = (!self.table_is_readonly()) .then(|| self.table_cell.as_ref().map(|c| c.block_id.as_str())) .flatten(); @@ -586,3 +607,185 @@ impl PlaygroundView { Some(layout) } } + +#[cfg(test)] +mod tests { + use blocksuite_playground_doc::{ + schema::{BlockSpec, ParagraphType}, + session::PageDocSession, + }; + use ui::{AppContext, Context}; + use y_octo::{Any, TextAttributes}; + + use super::*; + use crate::room_client::DocState; + + thread_local! { + pub(super) static MATH_WALKS: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + + const PARAGRAPHS: usize = 10_000; + + type Commit = y_octo::SessionCommit; + + /// `PARAGRAPHS` plain paragraphs `p`, then the plain paragraphs `m1` and `m2`. + fn plain_page() -> DocState { + let mut state = DocState::new("math-memo", 21).unwrap(); + state + .workspace + .create_page(HOME_PAGE_ID, "Page", 1) + .unwrap(); + let page = state.workspace.ensure_page(HOME_PAGE_ID).unwrap(); + let root = BlockSpec::Page { + title: "Page".into(), + }; + page.add_block("root", root, None, None, 1).unwrap(); + let note = BlockSpec::Note { xywh: None }; + page.add_block("note", note, Some("root"), None, 2).unwrap(); + let ids = (0..PARAGRAPHS).map(|i| format!("p{i}")); + for id in ids.chain(["m1".to_string(), "m2".to_string()]) { + let spec = BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: "x y".into(), + }; + page.add_block(&id, spec, Some("note"), None, 3).unwrap(); + } + state + } + + fn add_formula(page: &mut PageDocSession, id: &str, now: u64) -> Option { + let latex = TextAttributes::from([("latex".to_string(), Any::String("x^2".into()))]); + page.format_text(id, "prop:text", 0, 1, latex, now).unwrap() + } + + #[test] + fn text_edits_carry_the_math_memo_and_other_edits_walk_the_page() { + type TextEdit = fn(&mut PageDocSession, u64) -> Option; + type ViewEdit = fn(&mut PlaygroundView, &mut Window, &mut Context); + enum Step { + Text(&'static str, TextEdit), + View(ViewEdit), + } + let rows: [(&str, Step, usize, bool); 10] = [ + ( + "keystroke in a page without math", + Step::Text("p5000", |p, t| { + p.insert_text("p5000", "prop:text", 0, "a", t).unwrap() + }), + 0, + false, + ), + ( + "formula added", + Step::Text("m1", |p, t| add_formula(p, "m1", t)), + 0, + true, + ), + ( + "second formula added", + Step::Text("m2", |p, t| add_formula(p, "m2", t)), + 0, + true, + ), + ( + "keystroke beside formulas", + Step::Text("p1", |p, t| { + p.insert_text("p1", "prop:text", 0, "a", t).unwrap() + }), + 0, + true, + ), + ( + "keystroke in a block that keeps its formula", + Step::Text("m1", |p, t| { + p.insert_text("m1", "prop:text", 2, "a", t).unwrap() + }), + 0, + true, + ), + ( + "a formula removed while another stays", + Step::Text("m1", |p, t| { + p.remove_text("m1", "prop:text", 0, 1, t).unwrap() + }), + 1, + true, + ), + ( + "the last formula removed", + Step::Text("m2", |p, t| { + p.remove_text("m2", "prop:text", 0, 1, t).unwrap() + }), + 1, + false, + ), + ( + "undo", + Step::View(|v, w, cx| v.history(false, w, cx).unwrap()), + 1, + true, + ), + ( + "redo", + Step::View(|v, w, cx| v.history(true, w, cx).unwrap()), + 1, + false, + ), + ( + "full document refresh", + Step::View(|v, _, _| v.refresh_document()), + 1, + false, + ), + ]; + + let platform = ui::HeadlessPlatform::new(1280, 800, 1.0); + let app = ui::Application::with_platform(platform).run_embedded(|cx| { + crate::register_bundled_fonts(cx).unwrap(); + }); + let win = app + .update(|cx| { + cx.open_window(ui::WindowOptions::default(), |_, cx| { + cx.new(PlaygroundView::new) + }) + }) + .unwrap(); + app.update(|cx| { + win.update(cx, |view, w, cx| { + crate::block_flow::bump_preview_revision(); + view.set_document(plain_page(), cx); + let snapshot = view.snapshot.clone().unwrap(); + assert!(!view.snapshot_has_math_cached(&snapshot)); + for (now, (name, step, walks, has_math)) in (1_000..).step_by(1_000).zip(rows) { + match step { + Step::Text(id, edit) => { + let page = view.page_mut().unwrap(); + page.stop_capturing().unwrap(); + let commit = edit(page, now); + page.stop_capturing().unwrap(); + assert!(commit.is_some(), "{name}: the edit writes"); + view.did_edit(commit, Some(id), w, cx); + } + Step::View(edit) => edit(view, w, cx), + } + let snapshot = view.snapshot.clone().unwrap(); + let before = MATH_WALKS.get(); + assert_eq!(view.snapshot_has_math_cached(&snapshot), has_math, "{name}"); + assert_eq!(MATH_WALKS.get() - before, walks, "{name}: page walks"); + assert_eq!( + crate::block_flow::snapshot_has_math(&snapshot), + has_math, + "{name}: the memo matches a walk" + ); + let preview_rev = crate::block_flow::document_preview_revision( + has_math, + None, + &BTreeSet::new(), + ); + assert_eq!(preview_rev != 0, has_math, "{name}: preview revision"); + } + }) + .unwrap() + }); + } +} diff --git a/blocksuite/crates/playground/src/overlays/view_link_popup/memo.rs b/blocksuite/crates/playground/src/overlays/view_link_popup/memo.rs new file mode 100644 index 0000000000..9e175ce0d7 --- /dev/null +++ b/blocksuite/crates/playground/src/overlays/view_link_popup/memo.rs @@ -0,0 +1,167 @@ +//! 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 super::{LinkPopupTarget, matching_link_subranges, reference_at}; + +/// Desktop hover transition of the link popup that waits for its delay. +pub(super) enum LinkHoverTransition { + /// The pointer rests on a link or reference: open the popup at the line segment under the + /// pointer after the enter delay. + Enter(LinkPopupTarget, FlowRect), + /// The pointer left the link and the popup: close the popup after the leave delay. + Leave, +} + +/// The desktop link hover state of one view. The view drops it with itself, so two views +/// never share a target. +#[derive(Default)] +pub(crate) struct LinkHoverPending { + pub(super) transition: Option, + /// 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)>, +} + +/// The text a link popup target was read from: one page of one loaded document at one +/// revision, read against one set of page titles and one read-only state. +#[derive(Clone, PartialEq, Eq)] +pub(super) struct LinkReadKey { + page_id: String, + doc_epoch: u64, + doc_rev: u64, + page_rev: u64, + env_rev: u64, + readonly: bool, +} + +/// The target of `slot` when it was read at `key`. +pub(super) fn kept<'a>( + slot: &'a Option<(LinkReadKey, LinkPopupTarget)>, + key: Option<&LinkReadKey>, +) -> Option<&'a LinkPopupTarget> { + slot.as_ref() + .filter(|(at, _)| Some(at) == key) + .map(|(_, target)| target) +} + +/// Whether `target` is what the text gives for a decoration of `kind` that starts at +/// `deco_start`: the link run that holds the start, or the reference that starts there. +pub(super) fn target_names_decoration( + target: &LinkPopupTarget, + block_id: &str, + kind: &DecorationKind, + deco_start: usize, +) -> bool { + target.block_id() == block_id + && match (target, kind) { + ( + LinkPopupTarget::Link { + start_utf16, + end_utf16, + url, + .. + }, + DecorationKind::Link(u), + ) => url == u && (*start_utf16..*end_utf16).contains(&deco_start), + ( + LinkPopupTarget::Reference { + utf16_offset, + page_id, + .. + }, + DecorationKind::ReferenceChip(r), + ) => *page_id == r.page_id && *utf16_offset == deco_start, + _ => false, + } +} + +impl PlaygroundView { + pub(super) fn link_read_key(&self) -> Option { + let page = self.page()?; + Some(LinkReadKey { + page_id: self.page_id.clone()?, + doc_epoch: self.doc_epoch, + doc_rev: self.doc_rev, + page_rev: page.revision(), + env_rev: self.env_rev, + readonly: self.page_readonly, + }) + } + + pub(super) fn link_hover_state(&mut self) -> &mut LinkHoverPending { + 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 + .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)); + } + } + + /// `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 { + let (doc_text, _) = self.page()?.read_editable_text(target.block_id()).ok()?; + match target { + LinkPopupTarget::Link { + start_utf16, + end_utf16, + url, + .. + } => (matching_link_subranges(&doc_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, + }) + } + } + } +} diff --git a/blocksuite/crates/playground/src/overlays/view_link_popup/mod.rs b/blocksuite/crates/playground/src/overlays/view_link_popup/mod.rs index 9f540c13f8..6889afa1b7 100644 --- a/blocksuite/crates/playground/src/overlays/view_link_popup/mod.rs +++ b/blocksuite/crates/playground/src/overlays/view_link_popup/mod.rs @@ -3,6 +3,7 @@ //! and `Open` / `Edit` / `Alias` / `Copy` / `Card` / `Embed` / `Unlink` actions. mod actions; +mod memo; use blocksuite_editor::clipboard::sanitize::sanitize_url; use ui::{Context, Window, point, px}; @@ -20,13 +21,8 @@ use super::{ find_parent, }; -/// Desktop hover transition of the link popup that waits for its delay. -pub(crate) enum LinkHoverPending { - /// The pointer rests on a link or reference: open the popup after the enter delay. - Enter(LinkPopupTarget, FlowRect), - /// The pointer left the link and the popup: close the popup after the leave delay. - Leave, -} +pub(crate) use memo::LinkHoverPending; +use memo::{LinkHoverTransition, kept, target_names_decoration}; thread_local! { static LINK_HIT_TEXT_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; @@ -199,29 +195,30 @@ fn has_block_or_element_params(ref_obj: &y_octo::AHashMap) -> bool non_empty("blockIds") || non_empty("elementIds") } -fn block_has_ancestor_flavour( +/// Whether `target_id` or one of its ancestors is a table or a database, and whether it or one +/// of its ancestors is an edgeless text or a synced doc, in one walk of the tree. +fn reference_container_flags( node: &blocksuite_playground_doc::read::BlockNode, target_id: &str, - flavours: &[&str], -) -> bool { +) -> (bool, bool) { fn walk( cur: &blocksuite_playground_doc::read::BlockNode, target_id: &str, - flavours: &[&str], - in_match: bool, - ) -> Option { - let now_match = in_match || flavours.contains(&cur.flavour.as_str()); + (in_table, in_edgeless): (bool, bool), + ) -> Option<(bool, bool)> { + let flavour = cur.flavour.as_str(); + let flags = ( + in_table || matches!(flavour, "affine:table" | "affine:database"), + in_edgeless || matches!(flavour, "affine:edgeless-text" | "affine:embed-synced-doc"), + ); if cur.id == target_id { - return Some(now_match); + return Some(flags); } - for child in &cur.children { - if let Some(found) = walk(child, target_id, flavours, now_match) { - return Some(found); - } - } - None + cur.children + .iter() + .find_map(|child| walk(child, target_id, flags)) } - walk(node, target_id, flavours, false).unwrap_or(false) + walk(node, target_id, (false, false)).unwrap_or((false, false)) } impl PlaygroundView { @@ -266,12 +263,17 @@ impl PlaygroundView { Some(self.page()?.read_editable_text(block_id).ok()?.0) } + /// 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( &self, block: &FlowBlock, wx: f32, wy: f32, - ) -> Option<(LinkPopupTarget, FlowRect)> { + known: Option<&LinkPopupTarget>, + ) -> Option<(LinkPopupTarget, FlowRect, bool)> { let text = block.body.text.as_ref()?; let FlowTextLayout::Rich(rich) = &text.layout else { return None; @@ -290,7 +292,14 @@ impl PlaygroundView { f32::from(deco.bounds.size.width), f32::from(deco.bounds.size.height), ); - match &deco.kind { + let deco_start = deco.source_utf16.start as usize; + let names = |target: &LinkPopupTarget| { + target_names_decoration(target, &block.block_id, &deco.kind, deco_start) + }; + if let Some(target) = known.filter(|target| names(target)) { + return Some((target.clone(), world_rect, false)); + } + 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| { @@ -298,7 +307,7 @@ impl PlaygroundView { .filter(|(_, pid)| pid == &r.page_id) .map(|(pos, _)| pos) }; - let off = match_ref(deco.source_utf16.start as usize).or_else(|| { + 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)) @@ -311,40 +320,37 @@ impl PlaygroundView { &doc_text, off, ); - return Some(( - LinkPopupTarget::Reference { - block_id: block.block_id.clone(), - utf16_offset: off, - page_id: r.page_id.clone(), - title, - can_convert, - can_embed, - }, - world_rect, - )); + LinkPopupTarget::Reference { + block_id: block.block_id.clone(), + utf16_offset: off, + page_id: r.page_id.clone(), + title, + can_convert, + can_embed, + } } DecorationKind::Link(url) if !url.is_empty() => { let doc_text = self.link_hit_text(&block.block_id)?; let match_link = |o: usize| link_range_at(&doc_text, o).filter(|(_, _, u)| u == url); - let (start, end, resolved_url) = match_link(deco.source_utf16.start as usize) - .or_else(|| { + let (start, end, resolved_url) = match_link(deco_start).or_else(|| { 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(), - start_utf16: start, - end_utf16: end, - url: resolved_url, - }, - world_rect, - )); + LinkPopupTarget::Link { + block_id: block.block_id.clone(), + start_utf16: start, + end_utf16: end, + url: resolved_url, + } } - _ => {} - } + _ => continue, + }; + // A target found from the point under the pointer, because the layout and the text + // disagree at the start of the decoration, does not name the decoration and is not kept. + let keep = names(&target); + return Some((target, world_rect, keep)); } None } @@ -356,18 +362,12 @@ impl PlaygroundView { doc_text: &blocksuite_playground_doc::read::RichText, utf16_offset: usize, ) -> (bool, bool) { - let root = self.snapshot.as_ref().and_then(|s| s.root.as_ref()); - let in_table_or_db = root.is_some_and(|r| { - block_has_ancestor_flavour(r, block_id, &["affine:table", "affine:database"]) - }); + let (in_table_or_db, in_edgeless_or_synced) = self + .snapshot + .as_ref() + .and_then(|s| s.root.as_ref()) + .map_or((false, false), |r| reference_container_flags(r, block_id)); let can_convert = !in_table_or_db; - let in_edgeless_or_synced = root.is_some_and(|r| { - block_has_ancestor_flavour( - r, - block_id, - &["affine:edgeless-text", "affine:embed-synced-doc"], - ) - }); let links_to_node = reference_object_at(doc_text, utf16_offset, page_id) .is_some_and(|obj| has_block_or_element_params(&obj)); let can_embed = can_convert @@ -428,6 +428,17 @@ impl PlaygroundView { y: f32, window: &Window, ) -> Option<(LinkPopupTarget, FlowRect)> { + self.link_popup_target_at(x, y, window, None) + .map(|(target, anchor, _)| (target, anchor)) + } + + fn link_popup_target_at( + &self, + x: f32, + y: f32, + window: &Window, + known: Option<&LinkPopupTarget>, + ) -> Option<(LinkPopupTarget, FlowRect, bool)> { if self.mode != PlaygroundMode::Page { return None; } @@ -439,7 +450,7 @@ impl PlaygroundView { if !block.rect().contains(wx, wy) { continue; } - if let Some(hit) = self.link_or_ref_in_block(block, wx, wy) { + if let Some(hit) = self.link_or_ref_in_block(block, wx, wy, known) { return Some(hit); } } @@ -467,31 +478,42 @@ impl PlaygroundView { return; } let now_ms = self.now_ms(cx); - if let Some((snapshot, layout, transform)) = self.active_overlay_target() { - let local_collapsed = self.flow.local_collapsed.clone(); + if self.overlays.has_live_or_closing_link_popup(now_ms) + && let Some((snapshot, layout, transform)) = self.active_overlay_target() + { let scene = self.overlay_scene_with_transform( &snapshot, &layout, window.layout_direction(), None, transform, - &local_collapsed, + &self.flow.local_collapsed, ); let (lx, ly) = self.window_to_canvas_local(point(px(x), px(y))); - if self.overlays.retain_or_reopen_link_popup_on_hover( - &scene, - lx, - ly + self.topbar_height(), - now_ms, - ) { - self.link_hover_pending = None; + let ly = ly + self.topbar_height(); + if self + .overlays + .retain_or_reopen_link_popup_on_hover(&scene, lx, ly, now_ms) + { + self.link_hover_state().transition = None; self.link_hover_timer = None; cx.notify(); return; } } - let pending = match self.hit_link_popup_target_at(x, y, window) { - Some((target, _)) + let key = self.link_read_key(); + let known = self + .link_hover_pending + .as_ref() + .and_then(|state| kept(&state.hover, key.as_ref())); + let hit = self.link_popup_target_at(x, y, window, known); + if let Some((target, _, true)) = &hit + && let Some(key) = key + { + self.link_hover_state().hover = Some((key, target.clone())); + } + let next = match hit { + Some((target, ..)) if self .overlays .link_popup() @@ -499,30 +521,37 @@ impl PlaygroundView { { None } - Some((target, anchor_world)) => Some(LinkHoverPending::Enter(target, anchor_world)), + Some((target, anchor_world, _)) => { + Some(LinkHoverTransition::Enter(target, anchor_world)) + } None if self.overlays.link_popup().is_some_and(|p| p.from_hover) => { - Some(LinkHoverPending::Leave) + Some(LinkHoverTransition::Leave) } None => None, }; - let unchanged = match (&self.link_hover_pending, &pending) { - (Some(LinkHoverPending::Enter(a, _)), Some(LinkHoverPending::Enter(b, _))) => a == b, - (Some(LinkHoverPending::Leave), Some(LinkHoverPending::Leave)) => true, - _ => false, - }; - if unchanged { - return; + // The same transition keeps its timer. A wrapped link moves its anchor to the line + // segment under the pointer. + match (&mut self.link_hover_state().transition, &next) { + ( + Some(LinkHoverTransition::Enter(a, anchor)), + Some(LinkHoverTransition::Enter(b, next_anchor)), + ) if a == b => { + *anchor = *next_anchor; + return; + } + (Some(LinkHoverTransition::Leave), Some(LinkHoverTransition::Leave)) => return, + _ => {} } - let delay_ms = match &pending { - Some(LinkHoverPending::Enter(..)) => LINK_HOVER_DELAY_MS, - Some(LinkHoverPending::Leave) => super::HOVER_LEAVE_DELAY_MS, + let delay_ms = match &next { + Some(LinkHoverTransition::Enter(..)) => LINK_HOVER_DELAY_MS, + Some(LinkHoverTransition::Leave) => super::HOVER_LEAVE_DELAY_MS, None => { - self.link_hover_pending = None; + self.link_hover_state().transition = None; self.link_hover_timer = None; return; } }; - self.link_hover_pending = pending; + self.link_hover_state().transition = next; // Replacing the task cancels the previous one, so only the latest transition fires. self.link_hover_timer = Some(cx.spawn(async move |this, cx| { cx.background_executor() @@ -530,11 +559,11 @@ impl PlaygroundView { .await; let _ = this.update(cx, |this, cx| { let now_ms = this.now_ms(cx); - match this.link_hover_pending.take() { - Some(LinkHoverPending::Enter(target, anchor)) => { + match this.link_hover_state().transition.take() { + Some(LinkHoverTransition::Enter(target, anchor)) => { this.overlays.open_link_popup(target, anchor, true, now_ms); } - Some(LinkHoverPending::Leave) + Some(LinkHoverTransition::Leave) if this.overlays.link_popup().is_some_and(|p| p.from_hover) => { this.overlays.close_link_popup(now_ms); @@ -553,39 +582,7 @@ impl PlaygroundView { return; } let page_rev = self.page().map_or(0, |p| p.revision()); - if let Some(existing) = self - .overlays - .link_popup() - .map(|p| (p.target.clone(), p.from_hover)) - && existing.1 - { - let still_valid = self - .page() - .and_then(|page| page.read_editable_text(existing.0.block_id()).ok()) - .is_some_and(|(doc_text, _)| match &existing.0 { - LinkPopupTarget::Link { - start_utf16, - end_utf16, - url, - .. - } => { - let spans = - matching_link_subranges(&doc_text, *start_utf16, *end_utf16, url); - spans.len() == 1 && spans[0] == (*start_utf16, *end_utf16) - } - LinkPopupTarget::Reference { - utf16_offset, - page_id, - .. - } => { - reference_at(&doc_text, *utf16_offset).as_ref() - == Some(&(*utf16_offset, page_id.clone())) - } - }); - if !still_valid { - self.overlays.close_link_popup(now_ms); - } - } + self.confirm_hover_link_popup(now_ms); let Some(sel) = self.editor.selection.as_ref().filter(|s| s.empty()) else { self.last_link_popup_caret = None; if self.overlays.link_popup().is_some_and(|p| !p.from_hover) { @@ -691,3 +688,418 @@ impl PlaygroundView { } } } + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use blocksuite_playground_doc::{ + schema::{BlockSpec, ParagraphType}, + session::PageDocSession, + }; + use y_octo::{Any, TextAttributes}; + + use crate::{ + HOME_PAGE_ID, PlaygroundTheme, PlaygroundView, TOPBAR_HEIGHT, + block_flow::FlowRect, + editor_session::DocPoint, + overlays::{ + HOVER_LEAVE_DELAY_MS, LINK_HOVER_DELAY_MS, LinkPopupAction, LinkPopupTarget, + OVERLAY_MOTION_MS, OverlayEvent, + }, + room_client::DocState, + }; + + use super::super::tests::{Session, open}; + use super::{LinkHoverTransition, matching_link_subranges}; + + const URL: &str = "https://same.example/"; + const WRAPPED: &str = "https://wrapped.example/"; + + fn paragraph(page: &mut PageDocSession, id: &str, text: &str, clock: u64) { + let spec = BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: text.into(), + }; + page.add_block(id, spec, Some("n"), None, clock).unwrap(); + } + + fn mark(page: &mut PageDocSession, id: &str, (at, len): (u64, u64), key: &str, value: Any) { + let attrs = TextAttributes::from([(key.to_string(), value)]); + page.format_text(id, "prop:text", at, len, attrs, 9) + .unwrap(); + } + + /// `p-two`: two links to one URL. `p-emoji`: a link after a surrogate pair. `p-wrap`: one + /// link over several lines. `p-ref`: a reference to the page `target`. + fn open_links() -> (Session, u64) { + let session = open(1280, 800, PlaygroundTheme::Light); + let mut state = DocState::new("link-hover-reuse", 94).unwrap(); + state + .workspace + .create_page(HOME_PAGE_ID, "Page", 1) + .unwrap(); + state.workspace.create_page("target", "Target", 2).unwrap(); + let wrapped = "word ".repeat(60); + let wrapped_len = wrapped.len() as u64; + { + let page = state.workspace.page_mut(HOME_PAGE_ID).unwrap(); + let root = BlockSpec::Page { + title: "Page".into(), + }; + page.add_block("page-root", root, None, None, 3).unwrap(); + let note = BlockSpec::Note { + xywh: Some("[0,0,800,600]".into()), + }; + page.add_block("n", note, Some("page-root"), None, 4) + .unwrap(); + paragraph(page, "p-two", "A link1 and link2 end", 5); + paragraph(page, "p-emoji", "\u{1F600} emoji link", 6); + paragraph(page, "p-wrap", &wrapped, 7); + paragraph(page, "p-ref", "See here", 8); + for (id, range, url) in [ + ("p-two", (2, 5), URL), + ("p-two", (12, 5), URL), + ("p-emoji", (9, 4), URL), + ("p-wrap", (0, wrapped_len), WRAPPED), + ] { + mark(page, id, range, "link", Any::String(url.into())); + } + let mut reference = y_octo::AHashMap::default(); + reference.insert("type".to_string(), Any::String("LinkedPage".into())); + reference.insert("pageId".to_string(), Any::String("target".into())); + mark( + page, + "p-ref", + (4, 1), + "reference", + Any::Object(Box::new(reference)), + ); + } + session.view(|v, cx| v.set_document(state, cx)); + let _ = session.settle(); + (session, wrapped_len) + } + + /// The caret box of `offset` in `block`, in world coordinates. + fn caret_world(session: &Session, block: &str, offset: u64) -> FlowRect { + session.view(|v, _| { + v.flow_layout() + .unwrap() + .block(block) + .unwrap() + .caret_rect(DocPoint::new(block, offset).caret) + .unwrap() + }) + } + + fn screen_point(session: &Session, block: &str, offset: u64) -> (f32, f32) { + let caret = caret_world(session, block, offset); + let column_x = session.view(|v, _| v.current_page_geometry(1280.0).column_x); + ( + column_x + caret.x + 2.0, + TOPBAR_HEIGHT + caret.y + caret.h * 0.5, + ) + } + + fn advance(session: &Session, ms: f64) { + session + .platform + .advance_clock(Duration::from_millis(ms as u64)); + session.platform.run_until_parked(); + } + + /// Move the pointer over `offset` in `block`. Gives the target and the anchor that wait to + /// open, and how many times the move read the text. + fn hover( + session: &Session, + block: &str, + offset: u64, + ) -> (Option<(LinkPopupTarget, FlowRect)>, u64) { + let (x, y) = screen_point(session, block, offset); + let before = PlaygroundView::link_hit_text_reads(); + session.pointer(x, y, false); + let reads = PlaygroundView::link_hit_text_reads() - before; + let pending = + session.view( + |v, _| match v.link_hover_pending.as_ref()?.transition.as_ref()? { + LinkHoverTransition::Enter(target, anchor) => Some((target.clone(), *anchor)), + LinkHoverTransition::Leave => None, + }, + ); + (pending, reads) + } + + fn link(block: &str, start_utf16: usize, end_utf16: usize, url: &str) -> LinkPopupTarget { + LinkPopupTarget::Link { + block_id: block.into(), + start_utf16, + end_utf16, + url: url.into(), + } + } + + fn reference(title: &str) -> LinkPopupTarget { + LinkPopupTarget::Reference { + block_id: "p-ref".into(), + utf16_offset: 4, + page_id: "target".into(), + title: title.into(), + can_convert: true, + can_embed: true, + } + } + + #[test] + fn hover_reuses_link_and_reference_targets_until_text_or_titles_change() { + let (session, wrapped_len) = open_links(); + let wrapped = link("p-wrap", 0, wrapped_len as usize, WRAPPED); + let append_text = |v: &mut PlaygroundView| { + let page = v.state.workspace.page_mut(HOME_PAGE_ID).unwrap(); + page.insert_text("p-ref", "prop:text", 9, "!", 20).unwrap(); + v.refresh_document(); + }; + let rename_target = |v: &mut PlaygroundView| { + v.state + .workspace + .set_page_title("target", "Renamed") + .unwrap(); + v.refresh_document(); + }; + type Edit<'a> = Option<&'a dyn Fn(&mut PlaygroundView)>; + let rows: [(&str, Edit, &str, u64, u64, LinkPopupTarget); 11] = [ + ("first hover", None, "p-two", 3, 1, link("p-two", 2, 7, URL)), + ("same link", None, "p-two", 5, 0, link("p-two", 2, 7, URL)), + ( + "second link, same URL", + None, + "p-two", + 14, + 1, + link("p-two", 12, 17, URL), + ), + ( + "link after an emoji", + None, + "p-emoji", + 10, + 1, + link("p-emoji", 9, 13, URL), + ), + ( + "first line of a wrapped link", + None, + "p-wrap", + 2, + 1, + wrapped.clone(), + ), + ( + "last line of the same link", + None, + "p-wrap", + wrapped_len - 3, + 0, + wrapped, + ), + ("reference", None, "p-ref", 4, 1, reference("Target")), + ("same reference", None, "p-ref", 4, 0, reference("Target")), + ( + "after a text edit", + Some(&append_text), + "p-ref", + 4, + 1, + reference("Target"), + ), + ( + "after a target rename", + Some(&rename_target), + "p-ref", + 4, + 1, + reference("Renamed"), + ), + ( + "same reference again", + None, + "p-ref", + 4, + 0, + reference("Renamed"), + ), + ]; + for (name, edit, block, offset, reads, expected) in rows { + if let Some(edit) = edit { + session.view(|v, _| edit(v)); + session.frame(); + } + let (pending, read) = hover(&session, block, offset); + assert_eq!(pending.map(|(t, _)| t), Some(expected), "{name}: target"); + assert_eq!(read, reads, "{name}: text reads"); + } + } + + /// Pages `m` and `z` hold the same paragraph `p` with a link to `URL` over `0..m_len` and + /// `0..z_len`. Both pages take the same edits, so their revisions match. + fn same_shape_pages(name: &str, m_len: u64, z_len: u64) -> DocState { + let mut state = DocState::new(name, 95).unwrap(); + for (id, len) in [("m", m_len), ("z", z_len)] { + state.workspace.create_page(id, "Same", 1).unwrap(); + let page = state.workspace.page_mut(id).unwrap(); + let root = BlockSpec::Page { + title: "Same".into(), + }; + page.add_block("page-root", root, None, None, 2).unwrap(); + let note = BlockSpec::Note { xywh: None }; + page.add_block("n", note, Some("page-root"), None, 3) + .unwrap(); + paragraph(page, "p", "abcdefghij", 4); + mark(page, "p", (0, len), "link", Any::String(URL.into())); + } + state + } + + #[test] + fn hover_targets_stay_in_their_page_document_and_view() { + let shown = |session: &Session, state: Option, page: &str| { + session.view(|v, cx| { + if let Some(state) = state { + v.set_document(state, cx); + } + v.set_active_page_id(page, cx); + }); + session.frame(); + }; + let first = open(1280, 800, PlaygroundTheme::Light); + let second = open(1280, 800, PlaygroundTheme::Light); + let revisions = + |state: &DocState| ["m", "z"].map(|id| state.workspace.page(id).unwrap().revision()); + let state = same_shape_pages("link-memo-a", 9, 3); + let [m_rev, z_rev] = revisions(&state); + assert_eq!(m_rev, z_rev, "both pages are at the same revision"); + shown(&first, Some(state), "z"); + type Step<'a> = ( + &'a str, + &'a Session, + Option<(Option, &'a str)>, + usize, + u64, + ); + let run = |steps: Vec| { + for (name, session, switch, end, reads) in steps { + if let Some((state, page)) = switch { + if state.is_none() { + session.view(|v, _| { + v.state.workspace.ensure_page("a").unwrap(); + v.refresh_document(); + }); + } + shown(session, state, page); + } + let (pending, read) = hover(session, "p", 1); + assert_eq!( + pending.map(|(t, _)| t), + Some(link("p", 0, end, URL)), + "{name}: target" + ); + assert_eq!(read, reads, "{name}: text reads"); + } + }; + run(vec![ + ("page z", &first, None, 3, 1), + ("page z again", &first, None, 3, 0), + ("page m after a new page", &first, Some((None, "m")), 9, 1), + ]); + advance(&first, LINK_HOVER_DELAY_MS + 10.0); + first.overlay(OverlayEvent::LinkPopupAction(LinkPopupAction::Unlink)); + let left = first.view(|v, _| { + let (text, _) = v.page().unwrap().read_editable_text("p").unwrap(); + matching_link_subranges(&text, 0, 10, URL) + }); + assert_eq!(left, [], "unlink removes the whole link of page m"); + run(vec![ + ( + "page m of another document", + &first, + Some((Some(same_shape_pages("link-memo-b", 6, 3)), "m")), + 6, + 1, + ), + ( + "another view", + &second, + Some((Some(same_shape_pages("link-memo-a", 4, 3)), "m")), + 4, + 1, + ), + ("first view again", &first, None, 6, 0), + ]); + } + + #[test] + fn open_reference_popup_takes_the_new_title_of_its_page() { + let (session, _) = open_links(); + hover(&session, "p-ref", 4); + advance(&session, LINK_HOVER_DELAY_MS + 10.0); + let popup_target = + || session.view(|v, _| v.overlays.link_popup().map(|p| p.target.clone())); + assert_eq!(popup_target(), Some(reference("Target"))); + session.view(|v, _| { + v.state + .workspace + .set_page_title("target", "Renamed") + .unwrap(); + v.refresh_document(); + }); + session.frame(); + assert_eq!(popup_target(), Some(reference("Renamed"))); + } + + #[test] + fn wrapped_link_popup_opens_at_the_line_under_the_pointer() { + let (session, wrapped_len) = open_links(); + let first_line = caret_world(&session, "p-wrap", 2); + let second_line = (3..wrapped_len) + .find(|&o| caret_world(&session, "p-wrap", o).y > first_line.y) + .unwrap(); + let line_y = caret_world(&session, "p-wrap", second_line + 1); + let (first, _) = hover(&session, "p-wrap", 2); + let first_anchor = first.unwrap().1; + advance(&session, 200.0); + let (second, _) = hover(&session, "p-wrap", second_line + 1); + let anchor = second.unwrap().1; + assert!( + anchor.y > first_anchor.y, + "the pending anchor follows the pointer" + ); + // The timer of the first move still runs: the popup opens one delay after it. + advance(&session, LINK_HOVER_DELAY_MS - 190.0); + let opened = session.view(|v, _| v.overlays.link_popup().map(|p| p.anchor_world)); + assert_eq!(opened, Some(anchor)); + let mid = line_y.y + line_y.h * 0.5; + assert!((anchor.y..anchor.y + anchor.h).contains(&mid)); + } + + #[test] + fn hover_popup_returns_from_its_bridge_until_its_fade_ends() { + let (session, _) = open_links(); + let (hx, hy) = screen_point(&session, "p-emoji", 10); + let advance = |ms: f64| advance(&session, ms); + let popup_open = || session.view(|v, _| v.overlays.link_popup().is_some()); + session.pointer(hx, hy, false); + advance(LINK_HOVER_DELAY_MS + 10.0); + assert!(popup_open(), "the hover popup opens after the enter delay"); + for (away_ms, open) in [ + (HOVER_LEAVE_DELAY_MS - 1.0, true), + (HOVER_LEAVE_DELAY_MS + OVERLAY_MOTION_MS * 0.5, true), + (HOVER_LEAVE_DELAY_MS + OVERLAY_MOTION_MS + 50.0, false), + ] { + session.pointer(1200.0, 700.0, false); + advance(away_ms); + session.pointer(hx, hy, false); + assert_eq!(popup_open(), open, "back on the link after {away_ms} ms"); + session.frame(); + } + } +} diff --git a/packages/frontend/scripts/check-snapshot-prefixes.mjs b/packages/frontend/scripts/check-snapshot-prefixes.mjs index 09287f43d0..7fd1b331e6 100644 --- a/packages/frontend/scripts/check-snapshot-prefixes.mjs +++ b/packages/frontend/scripts/check-snapshot-prefixes.mjs @@ -35,6 +35,13 @@ export const ZERO_IN_PRODUCTION = Object.freeze([ 'overlay.attachment_toolbar.', 'overlay.code_more_menu.', 'overlay.code_lang_picker.item.', + 'overlay.bookmark_toolbar.', + 'overlay.embed_toolbar.', + 'overlay.format_toolbar.', + 'overlay.image_toolbar.', + 'overlay.link_popup.', + 'overlay.callout_toolbar.', + 'overlay.page_scrollbar', ]); const WASM_MAGIC = new Uint8Array([0x00, 0x61, 0x73, 0x6d]);