mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-05 11:15:01 +03:00
fix(web): isolate pane embeds and cancel stale previews
Track HTML embeds by pane. Hide the embeds in a pane while its overlays are open. Clear desktop pane and peek embeds on routes without documents. Keep code preview requests pending until SVG decode completes. Settle pending requests when their worker stops. Release Blob URLs when decode or worker startup fails.
This commit is contained in:
1 parent
b3152da6d7
commit
1fb17ea47d
9 files changed
+1522
-367
No files matched your search
@@ -1,6 +1,13 @@
|
||||
//! Document Outline (TOC) and DocInfo statistics drawer panel for [`PlaygroundView`].
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::{
|
||||
cell::Cell,
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicU8, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
use blocksuite_playground_doc::{
|
||||
read::{BlockContent, BlockNode, PageSnapshot},
|
||||
@@ -11,6 +18,11 @@ use y_octo::{Any, TextDeltaOp};
|
||||
|
||||
use crate::{
|
||||
PlaygroundView,
|
||||
block_flow::{
|
||||
PageGeometry, PreviewWakeupSubscription, notify_preview_wakeup,
|
||||
page_geometry_with_full_width, subscribe_preview_wakeup,
|
||||
},
|
||||
overlays::InlineTargetEnd,
|
||||
theme::{Palette, TYPOGRAPHY},
|
||||
};
|
||||
|
||||
@@ -39,6 +51,18 @@ pub struct DocStats {
|
||||
pub linked_docs: Vec<String>,
|
||||
}
|
||||
|
||||
fn heading_level(kind: &ParagraphType) -> Option<u8> {
|
||||
match kind {
|
||||
ParagraphType::H1 => Some(1),
|
||||
ParagraphType::H2 => Some(2),
|
||||
ParagraphType::H3 => Some(3),
|
||||
ParagraphType::H4 => Some(4),
|
||||
ParagraphType::H5 => Some(5),
|
||||
ParagraphType::H6 => Some(6),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract ordered H1–H6 headings from visible page notes.
|
||||
pub fn extract_toc_headings(snapshot: &PageSnapshot) -> Vec<TocHeading> {
|
||||
let mut out = Vec::new();
|
||||
@@ -47,25 +71,19 @@ pub fn extract_toc_headings(snapshot: &PageSnapshot) -> Vec<TocHeading> {
|
||||
};
|
||||
for note in root.children.iter().filter(|n| n.is_page_visible_note()) {
|
||||
for node in note.walk() {
|
||||
if let BlockContent::Paragraph { kind, text, .. } = &node.content {
|
||||
let level = match kind {
|
||||
ParagraphType::H1 => 1,
|
||||
ParagraphType::H2 => 2,
|
||||
ParagraphType::H3 => 3,
|
||||
ParagraphType::H4 => 4,
|
||||
ParagraphType::H5 => 5,
|
||||
ParagraphType::H6 => 6,
|
||||
_ => continue,
|
||||
};
|
||||
if let BlockContent::Paragraph { kind, text, .. } = &node.content
|
||||
&& let Some(level) = heading_level(kind)
|
||||
{
|
||||
let title = text.plain.trim();
|
||||
let text = if title.is_empty() {
|
||||
format!("Heading {level}")
|
||||
} else {
|
||||
title.to_string()
|
||||
};
|
||||
out.push(TocHeading {
|
||||
block_id: node.id.clone(),
|
||||
level,
|
||||
text: if title.is_empty() {
|
||||
format!("Heading {level}")
|
||||
} else {
|
||||
title.to_string()
|
||||
},
|
||||
text,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -130,15 +148,7 @@ fn collect_node_stats(
|
||||
match &node.content {
|
||||
BlockContent::Page { title } => count_text(&title.plain),
|
||||
BlockContent::Paragraph { kind, text, .. } => {
|
||||
if matches!(
|
||||
kind,
|
||||
ParagraphType::H1
|
||||
| ParagraphType::H2
|
||||
| ParagraphType::H3
|
||||
| ParagraphType::H4
|
||||
| ParagraphType::H5
|
||||
| ParagraphType::H6
|
||||
) {
|
||||
if heading_level(kind).is_some() {
|
||||
*headings += 1;
|
||||
}
|
||||
count_text(&text.plain);
|
||||
@@ -165,6 +175,16 @@ fn collect_node_stats(
|
||||
}
|
||||
}
|
||||
|
||||
fn doc_panel_bounds(viewport_width: f32, rtl: bool) -> (f32, f32) {
|
||||
let panel_w = (viewport_width - 24.0).clamp(200.0, 268.0);
|
||||
let left = if rtl {
|
||||
12.0
|
||||
} else {
|
||||
(viewport_width - panel_w - 12.0).max(12.0)
|
||||
};
|
||||
(left, panel_w)
|
||||
}
|
||||
|
||||
impl PlaygroundView {
|
||||
/// Open, switch, or close the TOC / DocInfo side panel.
|
||||
pub fn set_doc_panel_tab(&mut self, tab: Option<DocPanelTab>, cx: &mut ui::Context<Self>) {
|
||||
@@ -188,12 +208,7 @@ impl PlaygroundView {
|
||||
let viewport_height = (f32::from(viewport.height) - self.topbar_height())
|
||||
.max(0.0)
|
||||
.floor();
|
||||
let panel_w = (viewport_width - 24.0).clamp(200.0, 268.0);
|
||||
let left = if window.layout_direction().is_rtl() {
|
||||
12.0
|
||||
} else {
|
||||
(viewport_width - panel_w - 12.0).max(12.0)
|
||||
};
|
||||
let (left, panel_w) = doc_panel_bounds(viewport_width, window.layout_direction().is_rtl());
|
||||
Some(blocksuite_editor::block_flow::FlowRect::new(
|
||||
left,
|
||||
self.topbar_height() + 12.0,
|
||||
@@ -223,27 +238,19 @@ impl PlaygroundView {
|
||||
) -> impl IntoElement + use<> {
|
||||
let active = self.doc_panel_tab.is_some();
|
||||
let hover = palette.hover;
|
||||
let fg = if active {
|
||||
palette.brand
|
||||
let (fg, bg, border) = if active {
|
||||
(palette.brand, palette.brand.opacity(0.14), palette.brand)
|
||||
} else {
|
||||
palette.text_primary
|
||||
(palette.text_primary, palette.background, palette.border)
|
||||
};
|
||||
let mut btn = div()
|
||||
.id("doc-panel-toggle")
|
||||
.flex_none()
|
||||
.h(px(crate::THEME_TOGGLE_SIZE))
|
||||
.rounded(px(8.0))
|
||||
.bg(if active {
|
||||
palette.brand.opacity(0.14)
|
||||
} else {
|
||||
palette.background
|
||||
})
|
||||
.bg(bg)
|
||||
.border_1()
|
||||
.border_color(if active {
|
||||
palette.brand
|
||||
} else {
|
||||
palette.border
|
||||
})
|
||||
.border_color(border)
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
@@ -253,26 +260,23 @@ impl PlaygroundView {
|
||||
.font_weight(FontWeight::MEDIUM)
|
||||
.text_color(fg)
|
||||
.on_click(cx.listener(|this, _, _, cx| {
|
||||
this.doc_panel_tab = if this.doc_panel_tab.is_some() {
|
||||
None
|
||||
} else {
|
||||
Some(DocPanelTab::Outline)
|
||||
};
|
||||
this.doc_panel_tab = this.doc_panel_tab.is_none().then_some(DocPanelTab::Outline);
|
||||
cx.notify();
|
||||
}))
|
||||
.snapshot("chrome.doc_panel_toggle", Some("chrome.topbar"))
|
||||
.snapshot_focused(active)
|
||||
.snapshot_text("Outline");
|
||||
if compact {
|
||||
let bar = |w| div().w(px(w)).h(px(1.5)).rounded(px(1.0)).bg(fg);
|
||||
btn = btn.w(px(crate::THEME_TOGGLE_SIZE)).child(
|
||||
div()
|
||||
.w(px(14.0))
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(3.0))
|
||||
.child(div().w(px(14.0)).h(px(1.5)).rounded(px(1.0)).bg(fg))
|
||||
.child(div().w(px(10.0)).h(px(1.5)).rounded(px(1.0)).bg(fg))
|
||||
.child(div().w(px(12.0)).h(px(1.5)).rounded(px(1.0)).bg(fg)),
|
||||
.child(bar(14.0))
|
||||
.child(bar(10.0))
|
||||
.child(bar(12.0)),
|
||||
);
|
||||
} else {
|
||||
btn = btn.px(px(10.0)).child("Outline");
|
||||
@@ -290,44 +294,33 @@ impl PlaygroundView {
|
||||
) -> Option<AnyElement> {
|
||||
let tab = self.doc_panel_tab?;
|
||||
let snapshot = self.snapshot.as_ref()?;
|
||||
let panel_w = (viewport_width - 24.0).clamp(200.0, 268.0);
|
||||
let narrow_viewport = viewport_width < 600.0;
|
||||
let left = if direction.is_rtl() {
|
||||
12.0
|
||||
} else {
|
||||
(viewport_width - panel_w - 12.0).max(12.0)
|
||||
};
|
||||
let (left, panel_w) = doc_panel_bounds(viewport_width, direction.is_rtl());
|
||||
let hover = palette.hover;
|
||||
|
||||
let tab_btn = |id: &'static str, label: &'static str, target: DocPanelTab| {
|
||||
let is_active = tab == target;
|
||||
let clear = ui::transparent_black();
|
||||
let (bg, border, fg) = if is_active {
|
||||
(palette.background, palette.border, palette.text_primary)
|
||||
} else {
|
||||
(clear, clear, palette.text_secondary)
|
||||
};
|
||||
div()
|
||||
.id(id)
|
||||
.flex_1()
|
||||
.h(px(28.0))
|
||||
.rounded(px(4.0))
|
||||
.bg(if is_active {
|
||||
palette.background
|
||||
} else {
|
||||
ui::transparent_black()
|
||||
})
|
||||
.bg(bg)
|
||||
.border_1()
|
||||
.border_color(if is_active {
|
||||
palette.border
|
||||
} else {
|
||||
ui::transparent_black()
|
||||
})
|
||||
.border_color(border)
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.cursor_pointer()
|
||||
.text_size(px(TYPOGRAPHY.font_xs_px))
|
||||
.font_weight(FontWeight::MEDIUM)
|
||||
.text_color(if is_active {
|
||||
palette.text_primary
|
||||
} else {
|
||||
palette.text_secondary
|
||||
})
|
||||
.text_color(fg)
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(cx.listener(move |this, _, _, cx| {
|
||||
this.doc_panel_tab = Some(target);
|
||||
@@ -382,6 +375,8 @@ impl PlaygroundView {
|
||||
let indent = f32::from(h.level.saturating_sub(1)) * 12.0;
|
||||
let target_id = h.block_id.clone();
|
||||
let label = SharedString::from(h.text.clone());
|
||||
let snap_id =
|
||||
SharedString::from(format!("overlay.doc_panel.heading.{}", h.block_id));
|
||||
list_inner = list_inner.child(
|
||||
div()
|
||||
.id(SharedString::from(format!("toc-{}", h.block_id)))
|
||||
@@ -409,13 +404,7 @@ impl PlaygroundView {
|
||||
cx.notify();
|
||||
}
|
||||
}))
|
||||
.snapshot(
|
||||
SharedString::from(format!(
|
||||
"overlay.doc_panel.heading.{}",
|
||||
h.block_id
|
||||
)),
|
||||
Some("overlay.doc_panel"),
|
||||
)
|
||||
.snapshot(snap_id, Some("overlay.doc_panel"))
|
||||
.snapshot_text(label.clone())
|
||||
.child(label),
|
||||
);
|
||||
@@ -452,6 +441,10 @@ impl PlaygroundView {
|
||||
("Headings", stats.headings.to_string()),
|
||||
("References", stats.linked_docs.len().to_string()),
|
||||
] {
|
||||
let snap_id = SharedString::from(format!(
|
||||
"overlay.doc_panel.stat.{}",
|
||||
key.to_ascii_lowercase()
|
||||
));
|
||||
body = body.child(
|
||||
div()
|
||||
.h(px(28.0))
|
||||
@@ -464,13 +457,7 @@ impl PlaygroundView {
|
||||
div()
|
||||
.font_weight(FontWeight::MEDIUM)
|
||||
.text_color(palette.text_primary)
|
||||
.snapshot(
|
||||
SharedString::from(format!(
|
||||
"overlay.doc_panel.stat.{}",
|
||||
key.to_ascii_lowercase()
|
||||
)),
|
||||
Some("overlay.doc_panel"),
|
||||
)
|
||||
.snapshot(snap_id, Some("overlay.doc_panel"))
|
||||
.snapshot_text(val.clone())
|
||||
.child(val),
|
||||
),
|
||||
@@ -561,11 +548,7 @@ impl PlaygroundView {
|
||||
|
||||
/// Replace the shown document, e.g. with one prepared by a host or a test.
|
||||
pub fn set_document(&mut self, state: crate::DocState, cx: &mut ui::Context<Self>) {
|
||||
self.finish_inline_targets(
|
||||
crate::overlays::InlineTargetEnd::DiscardPreedit,
|
||||
None,
|
||||
Some(cx),
|
||||
);
|
||||
self.finish_inline_targets(InlineTargetEnd::DiscardPreedit, None, Some(cx));
|
||||
self.editor = Default::default();
|
||||
self.full_width_pages.clear();
|
||||
self.overlays.reset();
|
||||
@@ -633,10 +616,9 @@ impl PlaygroundView {
|
||||
|
||||
pub(crate) fn render_nav_back(
|
||||
&self,
|
||||
palette: &crate::theme::Palette,
|
||||
palette: &Palette,
|
||||
cx: &mut ui::Context<Self>,
|
||||
) -> Option<ui::AnyElement> {
|
||||
use ui::{FontWeight, InteractiveElement, IntoElement, ParentElement, Styled, div, px};
|
||||
) -> Option<AnyElement> {
|
||||
if self.nav_history.is_empty() {
|
||||
return None;
|
||||
}
|
||||
@@ -686,17 +668,39 @@ impl PlaygroundView {
|
||||
.is_some_and(|id| self.full_width_pages.contains(id))
|
||||
}
|
||||
|
||||
pub(crate) fn current_page_geometry(
|
||||
&self,
|
||||
viewport_width: f32,
|
||||
) -> crate::block_flow::PageGeometry {
|
||||
crate::block_flow::page_geometry_with_full_width(
|
||||
viewport_width,
|
||||
self.is_current_page_full_width(),
|
||||
)
|
||||
pub(crate) fn current_page_geometry(&self, viewport_width: f32) -> PageGeometry {
|
||||
page_geometry_with_full_width(viewport_width, self.is_current_page_full_width())
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub(crate) const WAKEUP_PDF: u8 = 1 << 0;
|
||||
#[allow(dead_code)]
|
||||
pub(crate) const WAKEUP_DIAGRAM_OR_MATH: u8 = 1 << 1;
|
||||
const WAKEUP_ALL: u8 = WAKEUP_PDF | WAKEUP_DIAGRAM_OR_MATH;
|
||||
|
||||
std::thread_local! {
|
||||
static CURRENT_WAKEUP_KIND: Cell<u8> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn notify_preview_wakeup_kind(kind: u8) {
|
||||
let prev = CURRENT_WAKEUP_KIND.with(|slot| slot.replace(kind));
|
||||
notify_preview_wakeup();
|
||||
CURRENT_WAKEUP_KIND.with(|slot| slot.set(prev));
|
||||
}
|
||||
|
||||
fn subscribe_typed_wakeup(
|
||||
pending: Arc<AtomicU8>,
|
||||
tx: async_channel::Sender<()>,
|
||||
) -> PreviewWakeupSubscription {
|
||||
subscribe_preview_wakeup(Arc::new(move || {
|
||||
let kind = CURRENT_WAKEUP_KIND.with(|s| if s.get() == 0 { WAKEUP_ALL } else { s.get() });
|
||||
pending.fetch_or(kind, Ordering::Release);
|
||||
let _ = tx.try_send(());
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) fn install_preview_wakeup(
|
||||
tasks: &mut Vec<ui::Task<()>>,
|
||||
cx: &mut ui::Context<PlaygroundView>,
|
||||
@@ -708,17 +712,22 @@ pub(crate) fn install_preview_wakeup(
|
||||
return;
|
||||
}
|
||||
let (wakeup_tx, wakeup_rx) = async_channel::bounded::<()>(1);
|
||||
let wakeup_sub = crate::block_flow::subscribe_preview_wakeup(std::sync::Arc::new(move || {
|
||||
let _ = wakeup_tx.try_send(());
|
||||
}));
|
||||
let pending = Arc::new(AtomicU8::new(0));
|
||||
let wakeup_sub = subscribe_typed_wakeup(Arc::clone(&pending), wakeup_tx);
|
||||
tasks.push(cx.spawn(async move |this, cx| {
|
||||
let _keep_alive = wakeup_sub;
|
||||
while wakeup_rx.recv().await.is_ok() {
|
||||
let kinds = pending.swap(0, Ordering::AcqRel);
|
||||
if kinds == 0 {
|
||||
continue;
|
||||
}
|
||||
if this
|
||||
.update(cx, |view, cx| {
|
||||
let attachments = view.active_pdf_attachments();
|
||||
view.refresh_pdf_previews(&attachments);
|
||||
view.refresh_pdf_viewer_pages();
|
||||
if kinds & WAKEUP_PDF != 0 {
|
||||
let attachments = view.active_pdf_attachments();
|
||||
view.refresh_pdf_previews(&attachments);
|
||||
view.refresh_pdf_viewer_pages();
|
||||
}
|
||||
cx.notify();
|
||||
})
|
||||
.is_err()
|
||||
@@ -770,16 +779,49 @@ impl crate::PlaygroundOptions {
|
||||
other => anyhow::bail!("unknown flag: {other}"),
|
||||
}
|
||||
}
|
||||
match (room, relay) {
|
||||
(Some(room), relay) => {
|
||||
let config = crate::room_client::RoomConfig::new(&room, relay.as_deref());
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
config.validate_native()?;
|
||||
options.room = Some(config);
|
||||
}
|
||||
(None, Some(_)) => anyhow::bail!("--relay requires --room <room>"),
|
||||
(None, None) => {}
|
||||
if let Some(room) = room {
|
||||
let config = crate::room_client::RoomConfig::new(&room, relay.as_deref());
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
config.validate_native()?;
|
||||
options.room = Some(config);
|
||||
} else if relay.is_some() {
|
||||
anyhow::bail!("--relay requires --room <room>");
|
||||
}
|
||||
Ok(options)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::{Arc, atomic::AtomicU8, atomic::Ordering};
|
||||
|
||||
#[test]
|
||||
fn preview_wakeup_routes_diagram_math_without_pdf_refresh_and_coalesces_bits() {
|
||||
let (tx1, rx1) = async_channel::bounded(1);
|
||||
let (tx2, rx2) = async_channel::bounded(1);
|
||||
let p1 = Arc::new(AtomicU8::new(0));
|
||||
let p2 = Arc::new(AtomicU8::new(0));
|
||||
let _s1 = subscribe_typed_wakeup(Arc::clone(&p1), tx1);
|
||||
let _s2 = subscribe_typed_wakeup(Arc::clone(&p2), tx2);
|
||||
|
||||
notify_preview_wakeup_kind(WAKEUP_DIAGRAM_OR_MATH);
|
||||
assert!(rx1.try_recv().is_ok());
|
||||
assert!(rx2.try_recv().is_ok());
|
||||
assert_eq!(p1.swap(0, Ordering::AcqRel), WAKEUP_DIAGRAM_OR_MATH);
|
||||
assert_eq!(p2.swap(0, Ordering::AcqRel), WAKEUP_DIAGRAM_OR_MATH);
|
||||
|
||||
// Coalescing diagram/math followed by PDF preserves PDF bit on all panes.
|
||||
notify_preview_wakeup_kind(WAKEUP_DIAGRAM_OR_MATH);
|
||||
notify_preview_wakeup_kind(WAKEUP_PDF);
|
||||
assert!(rx1.try_recv().is_ok());
|
||||
assert!(rx2.try_recv().is_ok());
|
||||
assert_eq!(p1.swap(0, Ordering::AcqRel), WAKEUP_ALL);
|
||||
assert_eq!(p2.swap(0, Ordering::AcqRel), WAKEUP_ALL);
|
||||
|
||||
// Raw notify_preview_wakeup() (native/legacy callers) wakes with all bits.
|
||||
crate::block_flow::notify_preview_wakeup();
|
||||
assert!(rx1.try_recv().is_ok());
|
||||
assert_eq!(p1.swap(0, Ordering::AcqRel), WAKEUP_ALL);
|
||||
}
|
||||
}
|
||||
@@ -270,6 +270,8 @@ pub struct PlaygroundView {
|
||||
pub(crate) embedded_bounds: Option<(f32, f32)>,
|
||||
pub(crate) embedded_probe: Rc<std::cell::Cell<Option<(f32, f32, f32, f32)>>>,
|
||||
pub(crate) embedded_probe_initialized: bool,
|
||||
pub(crate) html_embed_scope_id: u64,
|
||||
pub(crate) host_embeds_shielded: bool,
|
||||
pub(crate) _tasks: Vec<Task<()>>,
|
||||
}
|
||||
|
||||
@@ -438,6 +440,8 @@ impl PlaygroundView {
|
||||
copied_timer: None,
|
||||
slash_preview_timer: None,
|
||||
edgeless_runtime: Default::default(),
|
||||
html_embed_scope_id: Self::alloc_html_embed_scope_id(),
|
||||
host_embeds_shielded: false,
|
||||
_tasks: tasks,
|
||||
};
|
||||
view.flow.database_state.mobile_readonly = view.database_readonly;
|
||||
|
||||
@@ -1,112 +1,577 @@
|
||||
//! Reconciles active HTML code-block previews and HTML external embeds against DOM `#embed-layer`.
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
impl crate::PlaygroundView {
|
||||
/// Reconcile every active HTML code preview and active `ExternalEmbedKind::Html` iframe
|
||||
/// against `#embed-layer` on every frame.
|
||||
pub(crate) fn reconcile_wasm_html_embeds(&self, viewport_width: f32, viewport_height: f32) {
|
||||
use std::cell::RefCell;
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
collections::{BTreeMap, BTreeSet, HashMap},
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
};
|
||||
|
||||
use blocksuite_playground_doc::read::{BlockContent, ExternalEmbedKind};
|
||||
use blocksuite_playground_doc::read::{BlockContent, ExternalEmbedKind, PageSnapshot};
|
||||
|
||||
use crate::{
|
||||
PlaygroundMode,
|
||||
block_flow::{CODE_PADDING, CodePreviewKind, EmbedCardState},
|
||||
wasm_preview::{HtmlEmbedMount, reconcile_html_embeds},
|
||||
use crate::{
|
||||
PlaygroundMode,
|
||||
block_flow::{CODE_PADDING, CodePreviewKind, EmbedCardState},
|
||||
};
|
||||
|
||||
static NEXT_HTML_EMBED_SCOPE_ID: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize)]
|
||||
pub(crate) struct ScopedHtmlEmbedMount {
|
||||
pub id: String,
|
||||
pub html: String,
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub w: f32,
|
||||
pub h: f32,
|
||||
pub visible: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ScopedHtmlEmbedRegistry {
|
||||
scopes: BTreeMap<u64, Vec<ScopedHtmlEmbedMount>>,
|
||||
last_reconciled_json: String,
|
||||
}
|
||||
|
||||
impl ScopedHtmlEmbedRegistry {
|
||||
fn update_scope(
|
||||
&mut self,
|
||||
scope_id: u64,
|
||||
mounts: Vec<ScopedHtmlEmbedMount>,
|
||||
) -> Option<Vec<ScopedHtmlEmbedMount>> {
|
||||
if mounts.is_empty() {
|
||||
let removed_non_empty = self
|
||||
.scopes
|
||||
.remove(&scope_id)
|
||||
.is_some_and(|prev| !prev.is_empty());
|
||||
if !removed_non_empty {
|
||||
return None;
|
||||
}
|
||||
} else {
|
||||
if self.scopes.get(&scope_id) == Some(&mounts) {
|
||||
return None;
|
||||
}
|
||||
self.scopes.insert(scope_id, mounts);
|
||||
}
|
||||
self.diff_aggregated()
|
||||
}
|
||||
|
||||
fn diff_aggregated(&mut self) -> Option<Vec<ScopedHtmlEmbedMount>> {
|
||||
let total: usize = self.scopes.values().map(Vec::len).sum();
|
||||
let mut aggregated = Vec::with_capacity(total);
|
||||
for mounts in self.scopes.values() {
|
||||
aggregated.extend(mounts.iter().cloned());
|
||||
}
|
||||
let next_json = if aggregated.is_empty() {
|
||||
"[]".to_string()
|
||||
} else {
|
||||
serde_json::to_string(&aggregated).unwrap_or_else(|_| "[]".to_string())
|
||||
};
|
||||
if self.last_reconciled_json == next_json {
|
||||
return None;
|
||||
}
|
||||
self.last_reconciled_json = next_json;
|
||||
Some(aggregated)
|
||||
}
|
||||
}
|
||||
|
||||
if self.mode != PlaygroundMode::Page {
|
||||
reconcile_html_embeds(&[]);
|
||||
std::thread_local! {
|
||||
static SCOPED_HTML_EMBEDS: RefCell<ScopedHtmlEmbedRegistry> =
|
||||
RefCell::new(ScopedHtmlEmbedRegistry::default());
|
||||
}
|
||||
|
||||
fn apply_scoped_html_embeds(scope_id: u64, mounts: Vec<ScopedHtmlEmbedMount>) {
|
||||
let next = SCOPED_HTML_EMBEDS.with(|slot| slot.borrow_mut().update_scope(scope_id, mounts));
|
||||
if let Some(aggregated) = next {
|
||||
reconcile_platform_html_embeds(aggregated);
|
||||
}
|
||||
}
|
||||
|
||||
fn reconcile_platform_html_embeds(aggregated: Vec<ScopedHtmlEmbedMount>) {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let entries: Vec<crate::wasm_preview::HtmlEmbedMount> = aggregated
|
||||
.into_iter()
|
||||
.map(|m| crate::wasm_preview::HtmlEmbedMount {
|
||||
id: m.id,
|
||||
html: m.html,
|
||||
x: m.x,
|
||||
y: m.y,
|
||||
w: m.w,
|
||||
h: m.h,
|
||||
visible: m.visible,
|
||||
})
|
||||
.collect();
|
||||
crate::wasm_preview::reconcile_html_embeds(&entries);
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let _ = aggregated;
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct PageBlockBounds<'a> {
|
||||
block_id: &'a str,
|
||||
x: f32,
|
||||
y: f32,
|
||||
width: f32,
|
||||
height: f32,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn collect_page_html_embed_mounts<'a>(
|
||||
scope_id: u64,
|
||||
mode: PlaygroundMode,
|
||||
snapshot: Option<&PageSnapshot>,
|
||||
blocks: impl IntoIterator<Item = PageBlockBounds<'a>>,
|
||||
code_preview_blocks: &BTreeSet<String>,
|
||||
embed_states: &HashMap<String, EmbedCardState>,
|
||||
embeds_shielded: bool,
|
||||
column_x: f32,
|
||||
vp_left: f32,
|
||||
vp_top: f32,
|
||||
vp_bottom: f32,
|
||||
scroll_y: f32,
|
||||
) -> Vec<ScopedHtmlEmbedMount> {
|
||||
if mode != PlaygroundMode::Page
|
||||
|| (code_preview_blocks.is_empty()
|
||||
&& !embed_states
|
||||
.values()
|
||||
.any(|state| *state == EmbedCardState::Active))
|
||||
{
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(snap) = snapshot else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let mut mounts = Vec::new();
|
||||
let mut push_mount = |id: String,
|
||||
html: String,
|
||||
b: PageBlockBounds<'a>,
|
||||
pad_x: f32,
|
||||
pad_y: f32,
|
||||
header_h: f32| {
|
||||
let top = (vp_top + b.y + header_h - scroll_y).max(vp_top);
|
||||
let bot = (vp_top + b.y + b.height - pad_y - scroll_y).min(vp_bottom);
|
||||
let (w, h) = ((b.width - pad_x * 2.0).max(0.0), (bot - top).max(0.0));
|
||||
mounts.push(ScopedHtmlEmbedMount {
|
||||
id,
|
||||
html,
|
||||
x: vp_left + column_x + b.x + pad_x,
|
||||
y: top,
|
||||
w,
|
||||
h,
|
||||
visible: !embeds_shielded && w > 0.0 && h > 0.0,
|
||||
});
|
||||
};
|
||||
|
||||
for b in blocks {
|
||||
let is_code_preview = code_preview_blocks.contains(b.block_id);
|
||||
let is_active_embed = embed_states.get(b.block_id) == Some(&EmbedCardState::Active);
|
||||
if !is_code_preview && !is_active_embed {
|
||||
continue;
|
||||
}
|
||||
let Some(node) = snap.block(b.block_id) else {
|
||||
continue;
|
||||
};
|
||||
match &node.content {
|
||||
BlockContent::Code { language, text, .. }
|
||||
if is_code_preview
|
||||
&& CodePreviewKind::from_language(language) == Some(CodePreviewKind::Html) =>
|
||||
{
|
||||
let (pad_x, pad_y) = CODE_PADDING;
|
||||
push_mount(
|
||||
format!("p{scope_id}-code-html-{}", b.block_id),
|
||||
text.clone(),
|
||||
b,
|
||||
pad_x,
|
||||
pad_y,
|
||||
34.0,
|
||||
);
|
||||
}
|
||||
BlockContent::ExternalEmbed {
|
||||
kind: ExternalEmbedKind::Html,
|
||||
html,
|
||||
..
|
||||
} if is_active_embed => {
|
||||
push_mount(
|
||||
format!("p{scope_id}-ext-html-{}", b.block_id),
|
||||
html.clone().unwrap_or_default(),
|
||||
b,
|
||||
14.0,
|
||||
14.0,
|
||||
48.0,
|
||||
);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
mounts
|
||||
}
|
||||
|
||||
impl crate::PlaygroundView {
|
||||
pub(crate) fn alloc_html_embed_scope_id() -> u64 {
|
||||
NEXT_HTML_EMBED_SCOPE_ID.fetch_add(1, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Clear all HTML embed mounts owned by this view scope and reconcile `#embed-layer`.
|
||||
pub fn clear_wasm_html_embeds(&self) {
|
||||
apply_scoped_html_embeds(self.html_embed_scope_id, Vec::new());
|
||||
}
|
||||
|
||||
/// Enable or disable an HTML code-block preview on this view.
|
||||
pub fn set_html_code_preview_active(
|
||||
&mut self,
|
||||
block_id: &str,
|
||||
active: bool,
|
||||
cx: &mut ui::Context<Self>,
|
||||
) {
|
||||
let changed = if active {
|
||||
self.flow.code_preview_blocks.insert(block_id.to_string())
|
||||
} else {
|
||||
self.flow.code_preview_blocks.remove(block_id)
|
||||
};
|
||||
if changed {
|
||||
self.env_rev += 1;
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
|
||||
/// Hide or restore this view's HTML embed mounts when occluded by a host-shell modal.
|
||||
pub fn set_host_embeds_shielded(&mut self, shielded: bool, cx: &mut ui::Context<Self>) {
|
||||
if self.host_embeds_shielded == shielded {
|
||||
return;
|
||||
}
|
||||
let (Some(snap), Some(layout)) = (self.snapshot.as_ref(), self.flow_layout()) else {
|
||||
reconcile_html_embeds(&[]);
|
||||
self.host_embeds_shielded = shielded;
|
||||
let (w, h) = self.embedded_bounds.unwrap_or_else(|| {
|
||||
(
|
||||
self.window_size.0,
|
||||
(self.window_size.1 - self.topbar_height()).max(0.0),
|
||||
)
|
||||
});
|
||||
if w > 0.0 && h > 0.0 {
|
||||
self.reconcile_wasm_html_embeds(w, h);
|
||||
}
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// Return `(mount_id, visible)` pairs currently registered for this view's HTML embed scope.
|
||||
pub fn wasm_html_embed_mounts(&self) -> Vec<(String, bool)> {
|
||||
SCOPED_HTML_EMBEDS.with(|slot| {
|
||||
slot.borrow()
|
||||
.scopes
|
||||
.get(&self.html_embed_scope_id)
|
||||
.map(|mounts| mounts.iter().map(|m| (m.id.clone(), m.visible)).collect())
|
||||
.unwrap_or_default()
|
||||
})
|
||||
}
|
||||
|
||||
/// Reconcile every active HTML code preview and active `ExternalEmbedKind::Html` iframe
|
||||
/// for this view scope against `#embed-layer` on every frame.
|
||||
pub fn reconcile_wasm_html_embeds(&self, viewport_width: f32, viewport_height: f32) {
|
||||
if self.mode != PlaygroundMode::Page
|
||||
|| (self.flow.code_preview_blocks.is_empty()
|
||||
&& !self
|
||||
.flow
|
||||
.embed_states
|
||||
.values()
|
||||
.any(|state| *state == EmbedCardState::Active))
|
||||
{
|
||||
apply_scoped_html_embeds(self.html_embed_scope_id, Vec::new());
|
||||
return;
|
||||
}
|
||||
let Some(layout) = self.flow_layout() else {
|
||||
apply_scoped_html_embeds(self.html_embed_scope_id, Vec::new());
|
||||
return;
|
||||
};
|
||||
|
||||
let geom = self.current_page_geometry(viewport_width);
|
||||
let origin = self.canvas_origin();
|
||||
let vp_left = f32::from(origin.x);
|
||||
let vp_top = f32::from(origin.y);
|
||||
let vp_bottom = vp_top + viewport_height;
|
||||
let mut mounts = Vec::new();
|
||||
|
||||
let mut push_mount = |id: String,
|
||||
html: String,
|
||||
b: &crate::block_flow::FlowBlock,
|
||||
pad_x: f32,
|
||||
pad_y: f32,
|
||||
header_h: f32| {
|
||||
let top = (vp_top + b.y + header_h - self.scroll_y).max(vp_top);
|
||||
let bot = (vp_top + b.y + b.body.height - pad_y - self.scroll_y).min(vp_bottom);
|
||||
let (w, h) = ((b.body.width - pad_x * 2.0).max(0.0), (bot - top).max(0.0));
|
||||
mounts.push(HtmlEmbedMount {
|
||||
id,
|
||||
html,
|
||||
x: vp_left + geom.column_x + b.x + pad_x,
|
||||
y: top,
|
||||
w,
|
||||
h,
|
||||
visible: !self.flow.embeds_shielded && w > 0.0 && h > 0.0,
|
||||
});
|
||||
};
|
||||
|
||||
for b in &layout.blocks {
|
||||
let Some(node) = snap.block(&b.block_id) else {
|
||||
continue;
|
||||
};
|
||||
match &node.content {
|
||||
BlockContent::Code { language, text, .. }
|
||||
if self.flow.code_preview_blocks.contains(&b.block_id)
|
||||
&& CodePreviewKind::from_language(language)
|
||||
== Some(CodePreviewKind::Html) =>
|
||||
{
|
||||
let (pad_x, pad_y) = CODE_PADDING;
|
||||
push_mount(
|
||||
format!("code-html-{}", b.block_id),
|
||||
text.clone(),
|
||||
b,
|
||||
pad_x,
|
||||
pad_y,
|
||||
34.0,
|
||||
);
|
||||
}
|
||||
BlockContent::ExternalEmbed {
|
||||
kind: ExternalEmbedKind::Html,
|
||||
html,
|
||||
..
|
||||
} if self.flow.embed_states.get(&b.block_id) == Some(&EmbedCardState::Active) => {
|
||||
push_mount(
|
||||
format!("ext-html-{}", b.block_id),
|
||||
html.clone().unwrap_or_default(),
|
||||
b,
|
||||
14.0,
|
||||
14.0,
|
||||
48.0,
|
||||
);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
thread_local! {
|
||||
static LAST_RECONCILED_JSON: RefCell<String> = const { RefCell::new(String::new()) };
|
||||
}
|
||||
let next_json = if mounts.is_empty() {
|
||||
"[]".to_string()
|
||||
} else {
|
||||
serde_json::to_string(&mounts).unwrap_or_else(|_| "[]".to_string())
|
||||
};
|
||||
let changed = LAST_RECONCILED_JSON.with(|slot| {
|
||||
let mut prev = slot.borrow_mut();
|
||||
if *prev == next_json {
|
||||
false
|
||||
} else {
|
||||
*prev = next_json;
|
||||
true
|
||||
}
|
||||
let blocks = layout.blocks.iter().map(|b| PageBlockBounds {
|
||||
block_id: &b.block_id,
|
||||
x: b.x,
|
||||
y: b.y,
|
||||
width: b.body.width,
|
||||
height: b.body.height,
|
||||
});
|
||||
if changed {
|
||||
reconcile_html_embeds(&mounts);
|
||||
}
|
||||
let mounts = collect_page_html_embed_mounts(
|
||||
self.html_embed_scope_id,
|
||||
self.mode,
|
||||
self.snapshot.as_deref(),
|
||||
blocks,
|
||||
&self.flow.code_preview_blocks,
|
||||
&self.flow.embed_states,
|
||||
self.flow.embeds_shielded || self.host_embeds_shielded,
|
||||
geom.column_x,
|
||||
vp_left,
|
||||
vp_top,
|
||||
vp_top + viewport_height,
|
||||
self.scroll_y,
|
||||
);
|
||||
apply_scoped_html_embeds(self.html_embed_scope_id, mounts);
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for crate::PlaygroundView {
|
||||
fn drop(&mut self) {
|
||||
apply_scoped_html_embeds(self.html_embed_scope_id, Vec::new());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use blocksuite_playground_doc::{
|
||||
schema::{BlockSpec, ParagraphType},
|
||||
session::PageDocSession,
|
||||
};
|
||||
|
||||
fn sample_mount(scope_id: u64, block_id: &str, x: f32, html: &str) -> ScopedHtmlEmbedMount {
|
||||
ScopedHtmlEmbedMount {
|
||||
id: format!("p{scope_id}-code-html-{block_id}"),
|
||||
html: html.to_string(),
|
||||
x,
|
||||
y: 80.0,
|
||||
w: 400.0,
|
||||
h: 160.0,
|
||||
visible: true,
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_test(
|
||||
reg: &mut ScopedHtmlEmbedRegistry,
|
||||
calls: &mut usize,
|
||||
scope_id: u64,
|
||||
mounts: Vec<ScopedHtmlEmbedMount>,
|
||||
) -> Option<Vec<ScopedHtmlEmbedMount>> {
|
||||
let res = reg.update_scope(scope_id, mounts);
|
||||
if res.is_some() {
|
||||
*calls += 1;
|
||||
}
|
||||
res
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scoped_registry_isolates_split_panes_drops_removed_views_and_skips_empty_frames() {
|
||||
let mut reg = ScopedHtmlEmbedRegistry::default();
|
||||
let mut reconcile_calls = 0usize;
|
||||
|
||||
// Empty frames on Page and Edgeless panes trigger 0 reconciliations.
|
||||
assert_eq!(
|
||||
apply_test(&mut reg, &mut reconcile_calls, 1, Vec::new()),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
apply_test(&mut reg, &mut reconcile_calls, 2, Vec::new()),
|
||||
None
|
||||
);
|
||||
assert_eq!(reconcile_calls, 0);
|
||||
|
||||
// Page pane 1 mounts one HTML embed; Edgeless pane 2 alternating frames must not clear it.
|
||||
let m1 = sample_mount(1, "b1", 40.0, "<p>left</p>");
|
||||
let out = apply_test(&mut reg, &mut reconcile_calls, 1, vec![m1.clone()])
|
||||
.expect("initial mount reconciles");
|
||||
assert_eq!(out, vec![m1.clone()]);
|
||||
assert_eq!(reconcile_calls, 1);
|
||||
|
||||
assert_eq!(
|
||||
apply_test(&mut reg, &mut reconcile_calls, 2, Vec::new()),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
apply_test(&mut reg, &mut reconcile_calls, 1, vec![m1.clone()]),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
apply_test(&mut reg, &mut reconcile_calls, 2, Vec::new()),
|
||||
None
|
||||
);
|
||||
assert_eq!(reconcile_calls, 1);
|
||||
assert_eq!(reg.scopes.get(&1), Some(&vec![m1.clone()]));
|
||||
|
||||
// Two Page panes showing the same block get distinct scoped IDs and stay stable across frames.
|
||||
let m2 = sample_mount(2, "b1", 520.0, "<p>left</p>");
|
||||
let out = apply_test(&mut reg, &mut reconcile_calls, 2, vec![m2.clone()])
|
||||
.expect("second page mount reconciles");
|
||||
assert_eq!(out.len(), 2);
|
||||
assert_ne!(out[0].id, out[1].id);
|
||||
assert_eq!(out, vec![m1.clone(), m2.clone()]);
|
||||
assert_eq!(reconcile_calls, 2);
|
||||
assert_eq!(
|
||||
apply_test(&mut reg, &mut reconcile_calls, 1, vec![m1.clone()]),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
apply_test(&mut reg, &mut reconcile_calls, 2, vec![m2.clone()]),
|
||||
None
|
||||
);
|
||||
assert_eq!(reconcile_calls, 2);
|
||||
|
||||
// Switching pane 1 to Edgeless (empty) or dropping pane 1 keeps pane 2's mount intact.
|
||||
let out = apply_test(&mut reg, &mut reconcile_calls, 1, Vec::new())
|
||||
.expect("clearing pane 1 reconciles down to pane 2");
|
||||
assert_eq!(out, vec![m2.clone()]);
|
||||
assert_eq!(reconcile_calls, 3);
|
||||
assert_eq!(
|
||||
apply_test(&mut reg, &mut reconcile_calls, 1, Vec::new()),
|
||||
None
|
||||
);
|
||||
assert_eq!(reconcile_calls, 3);
|
||||
|
||||
// Re-adding pane 1 then removing pane 2 cleans up pane 2 while preserving pane 1.
|
||||
assert_eq!(
|
||||
apply_test(&mut reg, &mut reconcile_calls, 1, vec![m1.clone()]),
|
||||
Some(vec![m1.clone(), m2])
|
||||
);
|
||||
let out = apply_test(&mut reg, &mut reconcile_calls, 2, Vec::new())
|
||||
.expect("dropping pane 2 removes its mount");
|
||||
assert_eq!(out, vec![m1]);
|
||||
let out = apply_test(&mut reg, &mut reconcile_calls, 1, Vec::new())
|
||||
.expect("dropping final pane clears #embed-layer");
|
||||
assert!(out.is_empty());
|
||||
assert_eq!(
|
||||
apply_test(&mut reg, &mut reconcile_calls, 1, Vec::new()),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collect_page_html_embed_mounts_skips_non_preview_blocks_and_prefixes_scope_id() {
|
||||
let mut session = PageDocSession::new("doc:test", 1).unwrap();
|
||||
session
|
||||
.add_block("page", BlockSpec::Page { title: "T".into() }, None, None, 1)
|
||||
.unwrap();
|
||||
session
|
||||
.add_block(
|
||||
"note",
|
||||
BlockSpec::Note { xywh: None },
|
||||
Some("page"),
|
||||
None,
|
||||
2,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let mut block_ids = Vec::with_capacity(1001);
|
||||
for i in 0..1000 {
|
||||
let id = format!("p-{i}");
|
||||
session
|
||||
.add_block(
|
||||
&id,
|
||||
BlockSpec::Paragraph {
|
||||
paragraph_type: ParagraphType::Text,
|
||||
text: format!("Line {i}"),
|
||||
},
|
||||
Some("note"),
|
||||
None,
|
||||
i as u64 + 3,
|
||||
)
|
||||
.unwrap();
|
||||
block_ids.push((id, i as f32 * 24.0, 24.0_f32));
|
||||
}
|
||||
session
|
||||
.add_block(
|
||||
"code-1",
|
||||
BlockSpec::Code {
|
||||
language: Some("html".into()),
|
||||
text: "<h1>Hi</h1>".into(),
|
||||
caption: String::new(),
|
||||
},
|
||||
Some("note"),
|
||||
None,
|
||||
1003,
|
||||
)
|
||||
.unwrap();
|
||||
block_ids.push(("code-1".to_string(), 24_000.0, 200.0));
|
||||
|
||||
let snapshot = session.read_page_snapshot().unwrap();
|
||||
let make_bounds = || {
|
||||
block_ids.iter().map(|(id, y, h)| PageBlockBounds {
|
||||
block_id: id,
|
||||
x: 0.0,
|
||||
y: *y,
|
||||
width: 600.0,
|
||||
height: *h,
|
||||
})
|
||||
};
|
||||
|
||||
// Empty preview/embed sets short-circuit immediately even with 1001 blocks.
|
||||
let empty_previews = BTreeSet::new();
|
||||
let empty_embeds = HashMap::new();
|
||||
assert!(
|
||||
collect_page_html_embed_mounts(
|
||||
7,
|
||||
PlaygroundMode::Page,
|
||||
Some(&snapshot),
|
||||
make_bounds(),
|
||||
&empty_previews,
|
||||
&empty_embeds,
|
||||
false,
|
||||
24.0,
|
||||
480.0,
|
||||
48.0,
|
||||
848.0,
|
||||
0.0,
|
||||
)
|
||||
.is_empty()
|
||||
);
|
||||
|
||||
let previews = BTreeSet::from(["code-1".to_string()]);
|
||||
let mounts = collect_page_html_embed_mounts(
|
||||
7,
|
||||
PlaygroundMode::Page,
|
||||
Some(&snapshot),
|
||||
make_bounds(),
|
||||
&previews,
|
||||
&empty_embeds,
|
||||
false,
|
||||
24.0,
|
||||
480.0,
|
||||
48.0,
|
||||
848.0,
|
||||
23_980.0,
|
||||
);
|
||||
assert_eq!(mounts.len(), 1);
|
||||
assert_eq!(mounts[0].id, "p7-code-html-code-1");
|
||||
assert_eq!(mounts[0].html, "<h1>Hi</h1>");
|
||||
assert!(mounts[0].visible);
|
||||
|
||||
// Shielded views keep the mount bounds while forcing `visible: false`.
|
||||
let shielded = collect_page_html_embed_mounts(
|
||||
7,
|
||||
PlaygroundMode::Page,
|
||||
Some(&snapshot),
|
||||
make_bounds(),
|
||||
&previews,
|
||||
&empty_embeds,
|
||||
true,
|
||||
24.0,
|
||||
480.0,
|
||||
48.0,
|
||||
848.0,
|
||||
23_980.0,
|
||||
);
|
||||
assert_eq!(shielded.len(), 1);
|
||||
assert!(!shielded[0].visible);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn view_drop_unregisters_its_html_embed_scope_from_thread_registry() {
|
||||
let scope_id = crate::PlaygroundView::alloc_html_embed_scope_id();
|
||||
apply_scoped_html_embeds(
|
||||
scope_id,
|
||||
vec![sample_mount(scope_id, "b1", 10.0, "<b>x</b>")],
|
||||
);
|
||||
SCOPED_HTML_EMBEDS.with(|slot| {
|
||||
assert!(slot.borrow().scopes.contains_key(&scope_id));
|
||||
});
|
||||
let other = crate::PlaygroundView::alloc_html_embed_scope_id();
|
||||
apply_scoped_html_embeds(other, vec![sample_mount(other, "b2", 500.0, "<b>y</b>")]);
|
||||
apply_scoped_html_embeds(scope_id, Vec::new());
|
||||
SCOPED_HTML_EMBEDS.with(|slot| {
|
||||
let reg = slot.borrow();
|
||||
assert!(!reg.scopes.contains_key(&scope_id));
|
||||
assert!(reg.scopes.contains_key(&other));
|
||||
});
|
||||
apply_scoped_html_embeds(other, Vec::new());
|
||||
}
|
||||
}
|
||||
@@ -29,9 +29,6 @@ extern "C" {
|
||||
|
||||
#[wasm_bindgen(js_namespace = ["window", "__playgroundPreview"], js_name = reconcileHtmlEmbeds, catch)]
|
||||
fn js_reconcile_html_embeds(entries_json: &str) -> Result<(), JsValue>;
|
||||
|
||||
#[wasm_bindgen(js_namespace = ["window", "__playgroundPreview"], js_name = shieldEmbeds, catch)]
|
||||
fn js_shield_embeds(shielded: bool) -> Result<(), JsValue>;
|
||||
}
|
||||
|
||||
/// Active HTML embed/preview descriptor reconciled against DOM `#embed-layer` every frame.
|
||||
@@ -88,10 +85,8 @@ pub(crate) fn reconcile_html_embeds(entries: &[HtmlEmbedMount]) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Toggles pointer/visibility shielding on `#embed-layer` whenever an overlay or panel opens.
|
||||
pub(crate) fn sync_embed_shield(shielded: bool) {
|
||||
let _ = js_shield_embeds(shielded);
|
||||
}
|
||||
/// HTML embed reconciliation applies each pane's shield in the same frame.
|
||||
pub(crate) fn sync_embed_shield(_shielded: bool) {}
|
||||
|
||||
fn with_media_target(
|
||||
request_id: Option<u64>,
|
||||
|
||||
@@ -26,9 +26,10 @@ use crate::{
|
||||
MAX_SINGLE_PDF_PAGE_RGBA_BYTES, MathPreviewProvider, MathRenderResult, MathRenderSlot,
|
||||
PdfAsyncPageResult, PdfPageCount, PdfPageProvider, PdfPreviewPage,
|
||||
bump_latex_formula_revision, bump_preview_revision, fast_pdf_content_hash, hsla_to_css_hex,
|
||||
notify_preview_wakeup, register_code_preview_provider, register_math_preview_provider,
|
||||
register_pdf_page_provider, rgba_pixels_to_render_image,
|
||||
register_code_preview_provider, register_math_preview_provider, register_pdf_page_provider,
|
||||
rgba_pixels_to_render_image,
|
||||
},
|
||||
doc_panel::{WAKEUP_DIAGRAM_OR_MATH, WAKEUP_PDF, notify_preview_wakeup_kind},
|
||||
theme::PlaygroundTheme,
|
||||
wasm_pdf_state::{CountStep, PageStep, WasmPdfState, WorkerPlan},
|
||||
};
|
||||
@@ -368,7 +369,7 @@ pub fn deliver_code_preview(
|
||||
fifo_insert(map, order, MAX_CODE_PREVIEW_CACHE_ENTRIES, key, result);
|
||||
}
|
||||
crate::block_flow::bump_code_preview_revision(kind_enum, &source_for_rev);
|
||||
notify_preview_wakeup();
|
||||
notify_preview_wakeup_kind(WAKEUP_DIAGRAM_OR_MATH);
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
@@ -407,7 +408,7 @@ pub fn deliver_code_preview_error(
|
||||
);
|
||||
}
|
||||
crate::block_flow::bump_code_preview_revision(kind_enum, &source_for_rev);
|
||||
notify_preview_wakeup();
|
||||
notify_preview_wakeup_kind(WAKEUP_DIAGRAM_OR_MATH);
|
||||
}
|
||||
|
||||
/// Callback invoked by `preview-workers.js` when a RaTeX math formula finishes rasterizing.
|
||||
@@ -451,7 +452,7 @@ pub fn deliver_math_preview(
|
||||
fifo_insert(map, order, MAX_MATH_CACHE_ENTRIES, key, result);
|
||||
}
|
||||
bump_latex_formula_revision(&latex_for_rev);
|
||||
notify_preview_wakeup();
|
||||
notify_preview_wakeup_kind(WAKEUP_DIAGRAM_OR_MATH);
|
||||
}
|
||||
|
||||
/// Callback invoked by `preview-workers.js` when RaTeX reports a definitive syntax/parse error
|
||||
@@ -486,13 +487,13 @@ pub fn deliver_math_error(
|
||||
);
|
||||
}
|
||||
bump_latex_formula_revision(&latex_for_rev);
|
||||
notify_preview_wakeup();
|
||||
notify_preview_wakeup_kind(WAKEUP_DIAGRAM_OR_MATH);
|
||||
}
|
||||
|
||||
fn wake_after_pdf_delivery(wake: bool) {
|
||||
if wake {
|
||||
bump_preview_revision();
|
||||
notify_preview_wakeup();
|
||||
notify_preview_wakeup_kind(WAKEUP_PDF);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,12 +11,15 @@ export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.loc
|
||||
const pendingCode = new Map();
|
||||
// `docId`s open in the current PDF worker. The bytes stay with the Rust session.
|
||||
const openPdfDocs = new Set();
|
||||
let detachMathWorker = null;
|
||||
let detachPdfWorker = null;
|
||||
let detachMermaidWorker = null;
|
||||
let detachTypstWorker = null;
|
||||
const workerBlobUrls = new WeakMap();
|
||||
const mountedHtmlEmbeds = new Map();
|
||||
const registeredFonts = [];
|
||||
let mermaidFontsSent = 0;
|
||||
let typstFontsSent = 0;
|
||||
let embedsShielded = false;
|
||||
let interactiveEmbedId = null;
|
||||
|
||||
function syncMermaidFonts(worker) {
|
||||
@@ -37,8 +40,7 @@ export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.loc
|
||||
|
||||
function applyEmbedPointerEvents() {
|
||||
for (const [id, entry] of mountedHtmlEmbeds.entries()) {
|
||||
entry.iframe.style.pointerEvents =
|
||||
!embedsShielded && interactiveEmbedId === id ? 'auto' : 'none';
|
||||
entry.iframe.style.pointerEvents = interactiveEmbedId === id ? 'auto' : 'none';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,10 +56,6 @@ export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.loc
|
||||
}
|
||||
|
||||
const onWindowPointerDown = event => {
|
||||
if (embedsShielded) {
|
||||
deactivateInteractiveEmbed();
|
||||
return;
|
||||
}
|
||||
let hitId = null;
|
||||
for (const [id, entry] of mountedHtmlEmbeds.entries()) {
|
||||
if (entry.iframe.style.display === 'none') continue;
|
||||
@@ -141,36 +139,54 @@ export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.loc
|
||||
});
|
||||
globalThis.window.addEventListener('message', onWindowMessage);
|
||||
}
|
||||
function dispose() {
|
||||
if (typeof globalThis.window?.removeEventListener === 'function') {
|
||||
globalThis.window.removeEventListener('pointerdown', onWindowPointerDown, {
|
||||
capture: true,
|
||||
});
|
||||
globalThis.window.removeEventListener('wheel', onWindowWheel, {
|
||||
capture: true,
|
||||
});
|
||||
globalThis.window.removeEventListener('message', onWindowMessage);
|
||||
}
|
||||
interactiveEmbedId = null;
|
||||
for (const entry of mountedHtmlEmbeds.values()) {
|
||||
entry.iframe.remove?.();
|
||||
URL.revokeObjectURL(entry.blobUrl);
|
||||
}
|
||||
mountedHtmlEmbeds.clear();
|
||||
failAllPendingMath();
|
||||
failAllPendingCode(null, 'preview bridge disposed');
|
||||
// Fails the PDF requests on their way and terminates the worker with its documents.
|
||||
failAllPendingPdf();
|
||||
}
|
||||
|
||||
if (globalThis.window) {
|
||||
globalThis.window.__playgroundPreviewDispose = () => {
|
||||
if (typeof globalThis.window?.removeEventListener === 'function') {
|
||||
globalThis.window.removeEventListener('pointerdown', onWindowPointerDown, {
|
||||
capture: true,
|
||||
});
|
||||
globalThis.window.removeEventListener('wheel', onWindowWheel, {
|
||||
capture: true,
|
||||
});
|
||||
globalThis.window.removeEventListener('message', onWindowMessage);
|
||||
}
|
||||
for (const entry of mountedHtmlEmbeds.values()) {
|
||||
entry.iframe.remove?.();
|
||||
URL.revokeObjectURL(entry.blobUrl);
|
||||
}
|
||||
mountedHtmlEmbeds.clear();
|
||||
// Fails the PDF requests on their way and terminates the worker with its documents.
|
||||
failAllPendingPdf();
|
||||
};
|
||||
globalThis.window.__playgroundPreviewDispose = dispose;
|
||||
}
|
||||
|
||||
function terminateWorker(worker) {
|
||||
if (!worker) return;
|
||||
const blobUrl = workerBlobUrls.get(worker);
|
||||
if (blobUrl) {
|
||||
workerBlobUrls.delete(worker);
|
||||
URL.revokeObjectURL(blobUrl);
|
||||
}
|
||||
worker.terminate?.();
|
||||
}
|
||||
|
||||
function failAllPendingMath() {
|
||||
const entries = Array.from(pendingMath.values());
|
||||
pendingMath.clear();
|
||||
if (mathWorker) {
|
||||
mathWorker.terminate?.();
|
||||
const deadWorker = mathWorker;
|
||||
mathWorker = null;
|
||||
detachMathWorker?.();
|
||||
detachMathWorker = null;
|
||||
terminateWorker(deadWorker);
|
||||
}
|
||||
for (const req of entries) {
|
||||
wasmExports.deliver_math_error(
|
||||
wasmExports.deliver_math_error?.(
|
||||
req.latex,
|
||||
req.display,
|
||||
req.fontSizePt,
|
||||
@@ -189,7 +205,7 @@ export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.loc
|
||||
detachPdfWorker?.();
|
||||
detachPdfWorker = null;
|
||||
openPdfDocs.clear();
|
||||
deadWorker.terminate?.();
|
||||
terminateWorker(deadWorker);
|
||||
}
|
||||
|
||||
function failAllPendingPdf() {
|
||||
@@ -199,9 +215,9 @@ export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.loc
|
||||
// One answer per request sent: the Rust state counts each unanswered request.
|
||||
for (const req of entries) {
|
||||
if (req.op === 'pdf_open') {
|
||||
wasmExports.deliver_pdf_open_error(req.docId);
|
||||
wasmExports.deliver_pdf_open_error?.(req.docId);
|
||||
} else if (req.op === 'pdf_render') {
|
||||
wasmExports.deliver_pdf_page_error(req.docId, req.pageIndex, req.scale);
|
||||
wasmExports.deliver_pdf_page_error?.(req.docId, req.pageIndex, req.scale);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -219,7 +235,14 @@ export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.loc
|
||||
"for (const e of __q) globalThis.dispatchEvent(new MessageEvent('message', { data: e.data, ports: e.ports }));",
|
||||
].join('\n');
|
||||
const blobUrl = URL.createObjectURL(new Blob([src], { type: 'text/javascript' }));
|
||||
return new Worker(blobUrl, { type: 'module' });
|
||||
try {
|
||||
const worker = new Worker(blobUrl, { type: 'module' });
|
||||
workerBlobUrls.set(worker, blobUrl);
|
||||
return worker;
|
||||
} catch (err) {
|
||||
URL.revokeObjectURL(blobUrl);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
function resolveWorkerAsset(key, fallbackRel) {
|
||||
@@ -230,19 +253,21 @@ export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.loc
|
||||
|
||||
function ensureMathWorker() {
|
||||
if (!mathWorker) {
|
||||
mathWorker = spawnWorker(
|
||||
const ownWorker = spawnWorker(
|
||||
resolveWorkerAsset('mathScript', './workers/math-worker.js'),
|
||||
resolveWorkerAsset('mathWasm', './workers/math-worker.wasm')
|
||||
);
|
||||
mathWorker.addEventListener('error', failAllPendingMath);
|
||||
mathWorker.addEventListener('messageerror', failAllPendingMath);
|
||||
mathWorker.addEventListener('message', event => {
|
||||
const onFailure = () => {
|
||||
if (ownWorker === mathWorker) failAllPendingMath();
|
||||
};
|
||||
const onMessage = event => {
|
||||
if (ownWorker !== mathWorker) return;
|
||||
const msg = event?.data;
|
||||
if (!msg || !pendingMath.has(msg.id)) return;
|
||||
const req = pendingMath.get(msg.id);
|
||||
pendingMath.delete(msg.id);
|
||||
if (!msg.ok || !msg.result?.rgba) {
|
||||
wasmExports.deliver_math_error(
|
||||
wasmExports.deliver_math_error?.(
|
||||
req.latex,
|
||||
req.display,
|
||||
req.fontSizePt,
|
||||
@@ -251,7 +276,7 @@ export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.loc
|
||||
);
|
||||
return;
|
||||
}
|
||||
wasmExports.deliver_math_preview(
|
||||
wasmExports.deliver_math_preview?.(
|
||||
req.latex,
|
||||
req.display,
|
||||
req.fontSizePt,
|
||||
@@ -264,7 +289,16 @@ export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.loc
|
||||
msg.result.heightPx,
|
||||
msg.result.rgba
|
||||
);
|
||||
});
|
||||
};
|
||||
ownWorker.addEventListener('error', onFailure);
|
||||
ownWorker.addEventListener('messageerror', onFailure);
|
||||
ownWorker.addEventListener('message', onMessage);
|
||||
detachMathWorker = () => {
|
||||
ownWorker.removeEventListener?.('error', onFailure);
|
||||
ownWorker.removeEventListener?.('messageerror', onFailure);
|
||||
ownWorker.removeEventListener?.('message', onMessage);
|
||||
};
|
||||
mathWorker = ownWorker;
|
||||
}
|
||||
return mathWorker;
|
||||
}
|
||||
@@ -382,74 +416,86 @@ export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.loc
|
||||
return { svg: patchedSvg, widthPt: wAttr, heightPt: hAttr };
|
||||
}
|
||||
|
||||
async function handleCodeMessage(event) {
|
||||
const msg = event?.data;
|
||||
if (!msg || !pendingCode.has(msg.id)) return;
|
||||
const req = pendingCode.get(msg.id);
|
||||
pendingCode.delete(msg.id);
|
||||
if (!msg.ok || !msg.result?.svg) {
|
||||
wasmExports.deliver_code_preview_error?.(
|
||||
req.kind,
|
||||
req.source,
|
||||
req.dark,
|
||||
req.dpr,
|
||||
msg.error || 'render failed'
|
||||
);
|
||||
return;
|
||||
}
|
||||
async function rasterizeSvg(svg, dpr) {
|
||||
const resolved = resolveSvgIntrinsicSize(svg);
|
||||
const url = URL.createObjectURL(new Blob([resolved.svg], { type: 'image/svg+xml' }));
|
||||
let img;
|
||||
try {
|
||||
const resolved = resolveSvgIntrinsicSize(msg.result.svg);
|
||||
const blob = new Blob([resolved.svg], { type: 'image/svg+xml' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const img = new Image();
|
||||
img = new Image();
|
||||
await new Promise((resolve, reject) => {
|
||||
img.onload = resolve;
|
||||
img.onerror = reject;
|
||||
img.src = url;
|
||||
});
|
||||
} finally {
|
||||
URL.revokeObjectURL(url);
|
||||
const scale = Math.max(1, Math.min(4, req.dpr || 2));
|
||||
const wPt = Math.max(1, resolved.widthPt || img.naturalWidth || 320);
|
||||
const hPt = Math.max(1, resolved.heightPt || img.naturalHeight || 160);
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = Math.round(wPt * scale);
|
||||
canvas.height = Math.round(hPt * scale);
|
||||
const ctx = canvas.getContext('2d');
|
||||
ctx.scale(scale, scale);
|
||||
ctx.drawImage(img, 0, 0, wPt, hPt);
|
||||
const rgba = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
|
||||
wasmExports.deliver_code_preview?.(
|
||||
req.kind,
|
||||
req.source,
|
||||
req.dark,
|
||||
req.dpr,
|
||||
wPt,
|
||||
hPt,
|
||||
canvas.width,
|
||||
canvas.height,
|
||||
new Uint8Array(rgba.buffer)
|
||||
);
|
||||
} catch (err) {
|
||||
wasmExports.deliver_code_preview_error?.(
|
||||
req.kind,
|
||||
req.source,
|
||||
req.dark,
|
||||
req.dpr,
|
||||
String(err)
|
||||
);
|
||||
}
|
||||
|
||||
const scale = Math.max(1, Math.min(4, dpr || 2));
|
||||
const wPt = Math.max(1, resolved.widthPt || img.naturalWidth || 320);
|
||||
const hPt = Math.max(1, resolved.heightPt || img.naturalHeight || 160);
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = Math.round(wPt * scale);
|
||||
canvas.height = Math.round(hPt * scale);
|
||||
const ctx = canvas.getContext('2d');
|
||||
ctx.scale(scale, scale);
|
||||
ctx.drawImage(img, 0, 0, wPt, hPt);
|
||||
const rgba = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
|
||||
return [wPt, hPt, canvas.width, canvas.height, new Uint8Array(rgba.buffer)];
|
||||
}
|
||||
|
||||
async function handleCodeMessage(event, kind, ownWorker) {
|
||||
if (ownWorker !== (kind === 'mermaid' ? mermaidWorker : typstWorker)) return;
|
||||
const msg = event?.data;
|
||||
const req = pendingCode.get(msg?.id);
|
||||
if (!req || req.kind !== kind || req.decoding) return;
|
||||
|
||||
let pixels;
|
||||
let error = msg.error || 'render failed';
|
||||
if (msg.ok && msg.result?.svg) {
|
||||
req.decoding = true;
|
||||
try {
|
||||
pixels = await rasterizeSvg(msg.result.svg, req.dpr);
|
||||
} catch (err) {
|
||||
error = String(err);
|
||||
}
|
||||
if (
|
||||
ownWorker !== (kind === 'mermaid' ? mermaidWorker : typstWorker) ||
|
||||
pendingCode.get(msg.id) !== req
|
||||
) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
pendingCode.delete(msg.id);
|
||||
if (pixels) {
|
||||
wasmExports.deliver_code_preview?.(req.kind, req.source, req.dark, req.dpr, ...pixels);
|
||||
} else {
|
||||
wasmExports.deliver_code_preview_error?.(req.kind, req.source, req.dark, req.dpr, error);
|
||||
}
|
||||
}
|
||||
|
||||
function dropCodeWorker(kind) {
|
||||
if ((!kind || kind === 'mermaid') && mermaidWorker) {
|
||||
const deadWorker = mermaidWorker;
|
||||
mermaidWorker = null;
|
||||
mermaidFontsSent = 0;
|
||||
detachMermaidWorker?.();
|
||||
detachMermaidWorker = null;
|
||||
terminateWorker(deadWorker);
|
||||
}
|
||||
if ((!kind || kind === 'typst') && typstWorker) {
|
||||
const deadWorker = typstWorker;
|
||||
typstWorker = null;
|
||||
typstFontsSent = 0;
|
||||
detachTypstWorker?.();
|
||||
detachTypstWorker = null;
|
||||
terminateWorker(deadWorker);
|
||||
}
|
||||
}
|
||||
|
||||
function failAllPendingCode(kind, reason = 'code preview worker error') {
|
||||
if (kind === 'mermaid' && mermaidWorker) {
|
||||
mermaidWorker.terminate?.();
|
||||
mermaidWorker = null;
|
||||
mermaidFontsSent = 0;
|
||||
} else if (kind === 'typst' && typstWorker) {
|
||||
typstWorker.terminate?.();
|
||||
typstWorker = null;
|
||||
typstFontsSent = 0;
|
||||
}
|
||||
dropCodeWorker(kind);
|
||||
for (const [id, req] of pendingCode.entries()) {
|
||||
if (kind && req.kind !== kind) continue;
|
||||
pendingCode.delete(id);
|
||||
@@ -466,30 +512,56 @@ export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.loc
|
||||
function ensureDiagramWorker(kind) {
|
||||
if (kind === 'mermaid') {
|
||||
if (!mermaidWorker) {
|
||||
mermaidWorker = spawnWorker(
|
||||
const ownWorker = spawnWorker(
|
||||
resolveWorkerAsset('mermaidScript', './workers/mermaid-worker.js'),
|
||||
resolveWorkerAsset('mermaidWasm', './workers/mermaid-worker.wasm')
|
||||
);
|
||||
mermaidWorker.addEventListener('message', handleCodeMessage);
|
||||
mermaidWorker.addEventListener('error', () => failAllPendingCode('mermaid', 'mermaid worker error'));
|
||||
mermaidWorker.addEventListener('messageerror', () =>
|
||||
failAllPendingCode('mermaid', 'mermaid worker messageerror')
|
||||
);
|
||||
const onMessage = event => handleCodeMessage(event, 'mermaid', ownWorker);
|
||||
const onError = () => {
|
||||
if (ownWorker === mermaidWorker) failAllPendingCode('mermaid', 'mermaid worker error');
|
||||
};
|
||||
const onMessageError = () => {
|
||||
if (ownWorker === mermaidWorker) {
|
||||
failAllPendingCode('mermaid', 'mermaid worker messageerror');
|
||||
}
|
||||
};
|
||||
ownWorker.addEventListener('message', onMessage);
|
||||
ownWorker.addEventListener('error', onError);
|
||||
ownWorker.addEventListener('messageerror', onMessageError);
|
||||
detachMermaidWorker = () => {
|
||||
ownWorker.removeEventListener?.('message', onMessage);
|
||||
ownWorker.removeEventListener?.('error', onError);
|
||||
ownWorker.removeEventListener?.('messageerror', onMessageError);
|
||||
};
|
||||
mermaidWorker = ownWorker;
|
||||
mermaidFontsSent = 0;
|
||||
}
|
||||
syncMermaidFonts(mermaidWorker);
|
||||
return mermaidWorker;
|
||||
}
|
||||
if (!typstWorker) {
|
||||
typstWorker = spawnWorker(
|
||||
const ownWorker = spawnWorker(
|
||||
resolveWorkerAsset('typstScript', './workers/typst-worker.js'),
|
||||
resolveWorkerAsset('typstWasm', './workers/typst-worker.wasm')
|
||||
);
|
||||
typstWorker.addEventListener('message', handleCodeMessage);
|
||||
typstWorker.addEventListener('error', () => failAllPendingCode('typst', 'typst worker error'));
|
||||
typstWorker.addEventListener('messageerror', () =>
|
||||
failAllPendingCode('typst', 'typst worker messageerror')
|
||||
);
|
||||
const onMessage = event => handleCodeMessage(event, 'typst', ownWorker);
|
||||
const onError = () => {
|
||||
if (ownWorker === typstWorker) failAllPendingCode('typst', 'typst worker error');
|
||||
};
|
||||
const onMessageError = () => {
|
||||
if (ownWorker === typstWorker) {
|
||||
failAllPendingCode('typst', 'typst worker messageerror');
|
||||
}
|
||||
};
|
||||
ownWorker.addEventListener('message', onMessage);
|
||||
ownWorker.addEventListener('error', onError);
|
||||
ownWorker.addEventListener('messageerror', onMessageError);
|
||||
detachTypstWorker = () => {
|
||||
ownWorker.removeEventListener?.('message', onMessage);
|
||||
ownWorker.removeEventListener?.('error', onError);
|
||||
ownWorker.removeEventListener?.('messageerror', onMessageError);
|
||||
};
|
||||
typstWorker = ownWorker;
|
||||
typstFontsSent = 0;
|
||||
}
|
||||
syncTypstFonts(typstWorker);
|
||||
@@ -533,7 +605,7 @@ export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.loc
|
||||
input.click();
|
||||
}
|
||||
|
||||
window.__playgroundPreview = {
|
||||
const bridge = {
|
||||
registerFont(bytes) {
|
||||
const copy = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes || []);
|
||||
if (copy.byteLength === 0) return;
|
||||
@@ -722,6 +794,7 @@ export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.loc
|
||||
const existing = mountedHtmlEmbeds.get(item.id);
|
||||
if (existing) {
|
||||
existing.iframe.style.display = 'none';
|
||||
if (interactiveEmbedId === item.id) deactivateInteractiveEmbed();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -731,16 +804,10 @@ export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.loc
|
||||
}
|
||||
}
|
||||
},
|
||||
shieldEmbeds(shielded) {
|
||||
embedsShielded = Boolean(shielded);
|
||||
if (embedsShielded) {
|
||||
interactiveEmbedId = null;
|
||||
}
|
||||
const layer = globalThis.document?.getElementById('embed-layer');
|
||||
if (!layer) return;
|
||||
layer.style.visibility = embedsShielded ? 'hidden' : 'visible';
|
||||
layer.style.pointerEvents = 'none';
|
||||
applyEmbedPointerEvents();
|
||||
},
|
||||
dispose,
|
||||
};
|
||||
if (globalThis.window) {
|
||||
globalThis.window.__playgroundPreview = bridge;
|
||||
}
|
||||
return bridge;
|
||||
}
|
||||
@@ -39,6 +39,8 @@ pub struct DesktopEditorHost {
|
||||
pub(crate) workspace_origins: HashMap<String, String>,
|
||||
pane_editors: HashMap<PaneId, MountedEditor>,
|
||||
peek_editor: Option<MountedEditor>,
|
||||
rendered_panes_this_frame: Vec<PaneId>,
|
||||
peek_rendered_this_frame: bool,
|
||||
syncing: bool,
|
||||
}
|
||||
|
||||
@@ -338,6 +340,7 @@ impl DesktopEditorHost {
|
||||
view.set_readonly_immediate(readonly, cx);
|
||||
view.set_embedded_bounds(width, height);
|
||||
if switched_doc {
|
||||
view.clear_wasm_html_embeds();
|
||||
Some(load_doc_into_playground(
|
||||
view,
|
||||
doc_id,
|
||||
@@ -399,7 +402,7 @@ impl DesktopEditorHost {
|
||||
.map(String::as_str);
|
||||
let pg_mode = to_pg_mode(mode);
|
||||
if let Some(mounted) = self.pane_editors.get_mut(&pane_id) {
|
||||
return Self::update_mounted(
|
||||
let entity = Self::update_mounted(
|
||||
mounted,
|
||||
origin,
|
||||
doc_id,
|
||||
@@ -410,6 +413,10 @@ impl DesktopEditorHost {
|
||||
store,
|
||||
cx,
|
||||
);
|
||||
if entity.is_some() {
|
||||
self.rendered_panes_this_frame.push(pane_id);
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
let mounted = Self::mount_editor(
|
||||
origin,
|
||||
@@ -423,6 +430,7 @@ impl DesktopEditorHost {
|
||||
)?;
|
||||
let entity = mounted.entity.clone();
|
||||
self.pane_editors.insert(pane_id, mounted);
|
||||
self.rendered_panes_this_frame.push(pane_id);
|
||||
Some(entity)
|
||||
}
|
||||
|
||||
@@ -447,7 +455,7 @@ impl DesktopEditorHost {
|
||||
.get(&store.active_workspace().id)
|
||||
.map(String::as_str);
|
||||
if let Some(mounted) = self.peek_editor.as_mut() {
|
||||
return Self::update_mounted(
|
||||
let entity = Self::update_mounted(
|
||||
mounted,
|
||||
origin,
|
||||
doc_id,
|
||||
@@ -458,6 +466,10 @@ impl DesktopEditorHost {
|
||||
store,
|
||||
cx,
|
||||
);
|
||||
if entity.is_some() {
|
||||
self.peek_rendered_this_frame = true;
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
let mounted = Self::mount_editor(
|
||||
origin,
|
||||
@@ -471,12 +483,52 @@ impl DesktopEditorHost {
|
||||
)?;
|
||||
let entity = mounted.entity.clone();
|
||||
self.peek_editor = Some(mounted);
|
||||
self.peek_rendered_this_frame = true;
|
||||
Some(entity)
|
||||
}
|
||||
|
||||
/// Reset per-frame render tracking before building workbench panes and modals.
|
||||
pub(crate) fn begin_html_embed_frame(&mut self) {
|
||||
self.rendered_panes_this_frame.clear();
|
||||
self.peek_rendered_this_frame = false;
|
||||
}
|
||||
|
||||
/// Clear HTML embeds for unrendered panes / closed `PeekView` and shield rendered panes
|
||||
/// whenever a top-level workbench modal covers the canvas.
|
||||
pub(crate) fn sync_html_embeds(
|
||||
&self,
|
||||
panes_shielded: bool,
|
||||
cx: &mut Context<DesktopShellView>,
|
||||
) {
|
||||
for (pane_id, mounted) in &self.pane_editors {
|
||||
if self.rendered_panes_this_frame.contains(pane_id) {
|
||||
mounted.entity.update(cx, |view, cx| {
|
||||
view.set_host_embeds_shielded(panes_shielded, cx)
|
||||
});
|
||||
} else {
|
||||
mounted.entity.read(cx).clear_wasm_html_embeds();
|
||||
}
|
||||
}
|
||||
if let Some(mounted) = &self.peek_editor {
|
||||
if self.peek_rendered_this_frame {
|
||||
mounted
|
||||
.entity
|
||||
.update(cx, |view, cx| view.set_host_embeds_shielded(false, cx));
|
||||
} else {
|
||||
mounted.entity.read(cx).clear_wasm_html_embeds();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop any mounted pane editors for panes that have been closed.
|
||||
pub fn retain_panes(&mut self, active_ids: &[PaneId]) {
|
||||
self.pane_editors.retain(|id, _| active_ids.contains(id));
|
||||
pub fn retain_panes(&mut self, active_ids: &[PaneId], cx: &Context<DesktopShellView>) {
|
||||
self.pane_editors.retain(|id, mounted| {
|
||||
let keep = active_ids.contains(id);
|
||||
if !keep {
|
||||
mounted.entity.read(cx).clear_wasm_html_embeds();
|
||||
}
|
||||
keep
|
||||
});
|
||||
}
|
||||
|
||||
/// Return the mounted `Entity<PlaygroundView>` for `pane_id`, if any.
|
||||
@@ -1507,4 +1559,329 @@ mod tests {
|
||||
"second edit after switching away and back must succeed and sync"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn desktop_route_switches_peek_close_and_modals_reconcile_html_embeds() {
|
||||
use crate::{
|
||||
DesktopModal,
|
||||
peek_view::PeekAction,
|
||||
split_view::{DesktopRoute, DocViewMode},
|
||||
};
|
||||
use affine_store::directory::DocMode;
|
||||
|
||||
let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02");
|
||||
let doc_a = state.create_new_doc(DocMode::Page);
|
||||
let doc_b = state.create_new_doc(DocMode::Page);
|
||||
for (doc_id, html_id, html) in [
|
||||
(&doc_a, "html-a", "<h1>Pane A</h1>"),
|
||||
(&doc_b, "html-b", "<h1>Pane B</h1>"),
|
||||
] {
|
||||
let entry = state.store.docs.get_mut(doc_id).unwrap();
|
||||
let note_id = entry.note_id.clone();
|
||||
entry
|
||||
.session
|
||||
.add_block(
|
||||
html_id,
|
||||
BlockSpec::Code {
|
||||
language: Some("html".into()),
|
||||
text: html.into(),
|
||||
caption: String::new(),
|
||||
},
|
||||
Some(¬e_id),
|
||||
None,
|
||||
1_764_400_000,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
state.open_doc_in_active_pane(&doc_a);
|
||||
state.open_doc_in_split(&doc_b);
|
||||
let pane_0 = state.split.panes[0].id;
|
||||
let pane_1 = state.split.panes[1].id;
|
||||
state.split.panes[1].set_mode(DocViewMode::Page);
|
||||
|
||||
let (platform, app, wh, hw) = open_test_shell(state, 1440, 900);
|
||||
let frame = || {
|
||||
hw.request_frame();
|
||||
platform.run_until_parked();
|
||||
};
|
||||
let reconcile_pane = |cx: &mut ui::App, pane_id: crate::split_view::PaneId| {
|
||||
wh.update(cx, |shell, window, cx| {
|
||||
let pg = shell.editor_host().pane_entity(pane_id).unwrap();
|
||||
pg.read(cx).reconcile_wasm_html_embeds(
|
||||
f32::from(window.viewport_size().width) * 0.5,
|
||||
814.0,
|
||||
);
|
||||
})
|
||||
.unwrap();
|
||||
};
|
||||
frame();
|
||||
|
||||
// Enable HTML code previews in both split panes and verify initial mounts.
|
||||
app.update(|cx| {
|
||||
wh.update(cx, |shell, _, cx| {
|
||||
for (pane_id, block_id) in [(pane_0, "html-a"), (pane_1, "html-b")] {
|
||||
let pg = shell.editor_host().pane_entity(pane_id).unwrap();
|
||||
pg.update(cx, |view, cx| {
|
||||
view.set_html_code_preview_active(block_id, true, cx);
|
||||
});
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
frame();
|
||||
app.update(|cx| {
|
||||
reconcile_pane(cx, pane_0);
|
||||
reconcile_pane(cx, pane_1);
|
||||
wh.update(cx, |shell, _, cx| {
|
||||
let m0 = shell
|
||||
.editor_host()
|
||||
.pane_entity(pane_0)
|
||||
.unwrap()
|
||||
.read(cx)
|
||||
.wasm_html_embed_mounts();
|
||||
let m1 = shell
|
||||
.editor_host()
|
||||
.pane_entity(pane_1)
|
||||
.unwrap()
|
||||
.read(cx)
|
||||
.wasm_html_embed_mounts();
|
||||
assert_eq!(m0.len(), 1);
|
||||
assert!(m0[0].1, "pane 0 mount must start visible");
|
||||
assert_eq!(m1.len(), 1);
|
||||
assert!(m1[0].1, "pane 1 mount must start visible");
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
|
||||
// 1. Switching pane 0 to non-doc routes or missing docs clears ONLY pane 0's embeds.
|
||||
for route in [
|
||||
DesktopRoute::AllDocs,
|
||||
DesktopRoute::Favorites,
|
||||
DesktopRoute::Journals,
|
||||
DesktopRoute::Trash,
|
||||
DesktopRoute::Doc("nonexistent-doc".into()),
|
||||
] {
|
||||
app.update(|cx| {
|
||||
wh.update(cx, |shell, _, cx| {
|
||||
shell.state_mut().split.focus_pane(0);
|
||||
shell.state_mut().navigate_active_pane(route.clone());
|
||||
cx.notify();
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
frame();
|
||||
app.update(|cx| {
|
||||
wh.update(cx, |shell, _, cx| {
|
||||
let m0 = shell
|
||||
.editor_host()
|
||||
.pane_entity(pane_0)
|
||||
.unwrap()
|
||||
.read(cx)
|
||||
.wasm_html_embed_mounts();
|
||||
let m1 = shell
|
||||
.editor_host()
|
||||
.pane_entity(pane_1)
|
||||
.unwrap()
|
||||
.read(cx)
|
||||
.wasm_html_embed_mounts();
|
||||
assert!(
|
||||
m0.is_empty(),
|
||||
"route {route:?} must clear pane 0 HTML embeds, got {m0:?}"
|
||||
);
|
||||
assert_eq!(m1.len(), 1);
|
||||
assert!(m1[0].1, "pane 1 mount must stay intact across pane 0 nav");
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
}
|
||||
|
||||
// Navigate pane 0 back to doc_a and re-enable HTML preview.
|
||||
app.update(|cx| {
|
||||
wh.update(cx, |shell, _, cx| {
|
||||
shell.state_mut().split.focus_pane(0);
|
||||
shell
|
||||
.state_mut()
|
||||
.navigate_active_pane(DesktopRoute::Doc(doc_a.clone()));
|
||||
cx.notify();
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
frame();
|
||||
app.update(|cx| {
|
||||
wh.update(cx, |shell, _, cx| {
|
||||
let pg = shell.editor_host().pane_entity(pane_0).unwrap();
|
||||
pg.update(cx, |view, cx| {
|
||||
view.set_html_code_preview_active("html-a", true, cx);
|
||||
});
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
frame();
|
||||
app.update(|cx| reconcile_pane(cx, pane_0));
|
||||
|
||||
// 2. Top-level modals (QuickSearch, Settings) shield background panes and restore on close.
|
||||
for open_modal in [
|
||||
|s: &mut DesktopAppState| s.open_quick_search(),
|
||||
|s: &mut DesktopAppState| s.open_settings(),
|
||||
] {
|
||||
app.update(|cx| {
|
||||
wh.update(cx, |shell, _, cx| {
|
||||
open_modal(shell.state_mut());
|
||||
cx.notify();
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
frame();
|
||||
app.update(|cx| {
|
||||
wh.update(cx, |shell, _, cx| {
|
||||
for pid in [pane_0, pane_1] {
|
||||
let mounts = shell
|
||||
.editor_host()
|
||||
.pane_entity(pid)
|
||||
.unwrap()
|
||||
.read(cx)
|
||||
.wasm_html_embed_mounts();
|
||||
assert_eq!(mounts.len(), 1);
|
||||
assert!(
|
||||
!mounts[0].1,
|
||||
"modal must shield pane {pid} HTML embed visibility"
|
||||
);
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
|
||||
app.update(|cx| {
|
||||
wh.update(cx, |shell, _, cx| {
|
||||
shell.state_mut().quick_search.close();
|
||||
shell.state_mut().close_modal();
|
||||
assert!(shell.state().modal.is_none());
|
||||
cx.notify();
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
frame();
|
||||
app.update(|cx| {
|
||||
wh.update(cx, |shell, _, cx| {
|
||||
for pid in [pane_0, pane_1] {
|
||||
let mounts = shell
|
||||
.editor_host()
|
||||
.pane_entity(pid)
|
||||
.unwrap()
|
||||
.read(cx)
|
||||
.wasm_html_embed_mounts();
|
||||
assert_eq!(mounts.len(), 1);
|
||||
assert!(mounts[0].1, "closing modal must restore pane {pid} embed");
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
}
|
||||
|
||||
// 3. PeekView shields background panes while rendering its own HTML embed, and closing
|
||||
// PeekView (or covering it with QuickSearch) clears peek_editor's scope and restores panes.
|
||||
app.update(|cx| {
|
||||
wh.update(cx, |shell, _, cx| {
|
||||
shell.state_mut().open_peek_view(&doc_b);
|
||||
cx.notify();
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
frame();
|
||||
app.update(|cx| {
|
||||
wh.update(cx, |shell, _, cx| {
|
||||
let peek = shell.editor_host().peek_entity().unwrap();
|
||||
peek.update(cx, |view, cx| {
|
||||
view.set_html_code_preview_active("html-b", true, cx);
|
||||
});
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
frame();
|
||||
app.update(|cx| {
|
||||
wh.update(cx, |shell, _, cx| {
|
||||
let peek = shell.editor_host().peek_entity().unwrap();
|
||||
peek.read(cx).reconcile_wasm_html_embeds(744.0, 444.0);
|
||||
let peek_mounts = peek.read(cx).wasm_html_embed_mounts();
|
||||
assert_eq!(peek_mounts.len(), 1);
|
||||
assert!(
|
||||
peek_mounts[0].1,
|
||||
"PeekView own HTML embed must stay visible"
|
||||
);
|
||||
for pid in [pane_0, pane_1] {
|
||||
let mounts = shell
|
||||
.editor_host()
|
||||
.pane_entity(pid)
|
||||
.unwrap()
|
||||
.read(cx)
|
||||
.wasm_html_embed_mounts();
|
||||
assert!(!mounts[0].1, "PeekView must shield background pane {pid}");
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
|
||||
// Opening QuickSearch while peek_view.doc_id is still set clears peek_editor's scope.
|
||||
app.update(|cx| {
|
||||
wh.update(cx, |shell, _, cx| {
|
||||
shell.state_mut().quick_search.open();
|
||||
cx.notify();
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
frame();
|
||||
app.update(|cx| {
|
||||
wh.update(cx, |shell, _, cx| {
|
||||
let peek = shell.editor_host().peek_entity().unwrap();
|
||||
assert!(peek.read(cx).wasm_html_embed_mounts().is_empty());
|
||||
shell.state_mut().quick_search.close();
|
||||
shell.state_mut().apply_peek_action(PeekAction::Close);
|
||||
shell.state_mut().modal = Some(DesktopModal::Settings);
|
||||
shell.state_mut().close_modal();
|
||||
cx.notify();
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
frame();
|
||||
app.update(|cx| {
|
||||
wh.update(cx, |shell, _, cx| {
|
||||
let peek = shell.editor_host().peek_entity().unwrap();
|
||||
assert!(
|
||||
peek.read(cx).wasm_html_embed_mounts().is_empty(),
|
||||
"closing PeekView must clear peek_editor HTML embeds"
|
||||
);
|
||||
for pid in [pane_0, pane_1] {
|
||||
let mounts = shell
|
||||
.editor_host()
|
||||
.pane_entity(pid)
|
||||
.unwrap()
|
||||
.read(cx)
|
||||
.wasm_html_embed_mounts();
|
||||
assert!(
|
||||
mounts[0].1,
|
||||
"closing PeekView must restore pane {pid} HTML embed"
|
||||
);
|
||||
}
|
||||
// 4. Closing split pane 1 clears its scope without affecting pane 0.
|
||||
shell.state_mut().split.close_pane(1);
|
||||
cx.notify();
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
frame();
|
||||
app.update(|cx| {
|
||||
wh.update(cx, |shell, _, cx| {
|
||||
assert!(shell.editor_host().pane_entity(pane_1).is_none());
|
||||
let m0 = shell
|
||||
.editor_host()
|
||||
.pane_entity(pane_0)
|
||||
.unwrap()
|
||||
.read(cx)
|
||||
.wasm_html_embed_mounts();
|
||||
assert_eq!(m0.len(), 1);
|
||||
assert!(m0[0].1);
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -222,7 +222,15 @@ impl Render for DesktopShellView {
|
||||
// never discards uncommitted Yjs V1 edits.
|
||||
self.editor_host.sync_all(&mut self.state.store, cx);
|
||||
let active_pane_ids: Vec<_> = self.state.split.panes.iter().map(|p| p.id).collect();
|
||||
self.editor_host.retain_panes(&active_pane_ids);
|
||||
self.editor_host.retain_panes(&active_pane_ids, cx);
|
||||
self.editor_host.begin_html_embed_frame();
|
||||
|
||||
let quick_search_open = self.state.quick_search.open;
|
||||
let peek_open = !quick_search_open && self.state.peek_view.doc_id.is_some();
|
||||
let settings_open = !quick_search_open
|
||||
&& !peek_open
|
||||
&& matches!(self.state.modal, Some(DesktopModal::Settings));
|
||||
let panes_shielded = quick_search_open || peek_open || settings_open;
|
||||
|
||||
let palette = palette_for(self.state.theme);
|
||||
let vp = window.viewport_size();
|
||||
@@ -540,14 +548,14 @@ impl Render for DesktopShellView {
|
||||
));
|
||||
}
|
||||
|
||||
if self.state.quick_search.open {
|
||||
if quick_search_open {
|
||||
root = root.child(render_quick_search_modal(
|
||||
&self.state.quick_search,
|
||||
&self.state.store,
|
||||
palette,
|
||||
cx,
|
||||
));
|
||||
} else if let Some(peek_doc_id) = self.state.peek_view.doc_id.clone() {
|
||||
} else if peek_open && let Some(peek_doc_id) = self.state.peek_view.doc_id.clone() {
|
||||
let width = (vp_w - 32.0).clamp(0.0, 780.0);
|
||||
let height = (vp_h - 32.0).clamp(0.0, 580.0);
|
||||
let peek_ox = (vp_w - width) * 0.5 + 18.0;
|
||||
@@ -569,7 +577,7 @@ impl Render for DesktopShellView {
|
||||
palette,
|
||||
cx,
|
||||
));
|
||||
} else if matches!(self.state.modal, Some(DesktopModal::Settings)) {
|
||||
} else if settings_open {
|
||||
root = root.child(render_settings_modal(
|
||||
self.state.theme_preference,
|
||||
self.state.settings_scroll_y,
|
||||
@@ -580,6 +588,8 @@ impl Render for DesktopShellView {
|
||||
));
|
||||
}
|
||||
|
||||
self.editor_host.sync_html_embeds(panes_shielded, cx);
|
||||
|
||||
root
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,9 +41,7 @@ function createFakeDom() {
|
||||
this.posted.push(msg);
|
||||
}
|
||||
emit(type, event) {
|
||||
for (const fn of this.listeners.get(type) || []) {
|
||||
fn(event);
|
||||
}
|
||||
return Promise.all((this.listeners.get(type) || []).map(fn => fn(event)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,7 +140,7 @@ function createFakeDom() {
|
||||
};
|
||||
}
|
||||
|
||||
void test('reconcileHtmlEmbeds mounts, updates html blob URLs, shields, and unmounts stale iframes without allow-same-origin', () => {
|
||||
void test('reconcileHtmlEmbeds mounts, updates html blob URLs, and unmounts stale iframes without allow-same-origin', () => {
|
||||
const env = createFakeDom();
|
||||
try {
|
||||
installPlaygroundPreviewBridge({});
|
||||
@@ -239,13 +237,6 @@ void test('reconcileHtmlEmbeds mounts, updates html blob URLs, shields, and unmo
|
||||
});
|
||||
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');
|
||||
activeBridge.shieldEmbeds(true);
|
||||
assert.equal(env.embedLayer.style.visibility, 'hidden');
|
||||
assert.equal(liveIframe.style.pointerEvents, 'none');
|
||||
|
||||
// Switching mode / deleting block reconciles to [] and unmounts + revokes blob URL.
|
||||
const secondUrl = liveIframe.src;
|
||||
activeBridge.reconcileHtmlEmbeds([]);
|
||||
@@ -259,6 +250,148 @@ void test('reconcileHtmlEmbeds mounts, updates html blob URLs, shields, and unmo
|
||||
}
|
||||
});
|
||||
|
||||
void test('a hidden split pane releases its iframe and leaves the other pane visible and interactive', () => {
|
||||
const env = createFakeDom();
|
||||
try {
|
||||
const bridge = installPlaygroundPreviewBridge({});
|
||||
const left = { id: 'p1-html', x: 10, y: 10, w: 100, h: 100, visible: true };
|
||||
const right = { ...left, id: 'p2-html', x: 210 };
|
||||
bridge.reconcileHtmlEmbeds([left, right]);
|
||||
const [leftFrame, rightFrame] = env.children;
|
||||
assert.equal(leftFrame.style.display, 'block');
|
||||
assert.equal(rightFrame.style.display, 'block');
|
||||
assert.notEqual(env.embedLayer.style.visibility, 'hidden');
|
||||
|
||||
globalThis.window.emit('pointerdown', { clientX: 50, clientY: 50 });
|
||||
assert.equal(leftFrame.style.pointerEvents, 'auto');
|
||||
bridge.reconcileHtmlEmbeds([{ ...left, visible: false }, right]);
|
||||
assert.equal(leftFrame.style.display, 'none');
|
||||
assert.equal(leftFrame.style.pointerEvents, 'none');
|
||||
assert.equal(rightFrame.style.display, 'block');
|
||||
assert.notEqual(env.embedLayer.style.visibility, 'hidden');
|
||||
|
||||
globalThis.window.emit('pointerdown', { clientX: 250, clientY: 50 });
|
||||
assert.equal(rightFrame.style.pointerEvents, 'auto');
|
||||
bridge.reconcileHtmlEmbeds([right]);
|
||||
assert.deepEqual(env.children, [rightFrame]);
|
||||
assert.equal(rightFrame.style.display, 'block');
|
||||
assert.equal(rightFrame.style.pointerEvents, 'auto');
|
||||
assert.notEqual(env.embedLayer.style.visibility, 'hidden');
|
||||
} finally {
|
||||
env.restore();
|
||||
}
|
||||
});
|
||||
|
||||
for (const kind of ['mermaid', 'typst']) {
|
||||
for (const cancellation of ['dispose', 'worker error']) {
|
||||
void test(`${kind} settles once when ${cancellation} interrupts SVG decode`, async () => {
|
||||
const env = createFakeDom();
|
||||
const originalImage = globalThis.Image;
|
||||
let img;
|
||||
globalThis.Image = class {
|
||||
constructor() {
|
||||
img = this;
|
||||
}
|
||||
};
|
||||
try {
|
||||
const events = [];
|
||||
const bridge = installPlaygroundPreviewBridge({
|
||||
deliver_code_preview: () => events.push('success'),
|
||||
deliver_code_preview_error: (...args) => events.push(args),
|
||||
});
|
||||
bridge.requestCodePreview(kind, 'source', false, 1);
|
||||
const [worker] = env.workers;
|
||||
const [{ id }] = worker.posted;
|
||||
const completion = worker.emit('message', {
|
||||
data: {
|
||||
id,
|
||||
ok: true,
|
||||
result: { svg: '<svg width="2" height="2"/>' },
|
||||
},
|
||||
});
|
||||
assert.deepEqual(events, []);
|
||||
const svgUrl = img.src;
|
||||
if (cancellation === 'dispose') {
|
||||
bridge.dispose();
|
||||
} else {
|
||||
await worker.emit('error', {});
|
||||
}
|
||||
const reason =
|
||||
cancellation === 'dispose'
|
||||
? 'preview bridge disposed'
|
||||
: `${kind} worker error`;
|
||||
const expected = [[kind, 'source', false, 1, reason]];
|
||||
assert.deepEqual(events, expected);
|
||||
img.onload();
|
||||
await completion;
|
||||
assert.deepEqual(events, expected);
|
||||
assert.deepEqual(env.revoked, [worker.url, svgUrl]);
|
||||
} finally {
|
||||
globalThis.Image = originalImage;
|
||||
env.restore();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void test('SVG decode failure revokes its Blob URL and settles the preview once', async () => {
|
||||
const env = createFakeDom();
|
||||
const originalImage = globalThis.Image;
|
||||
let img;
|
||||
globalThis.Image = class {
|
||||
constructor() {
|
||||
img = this;
|
||||
}
|
||||
};
|
||||
try {
|
||||
const errors = [];
|
||||
const bridge = installPlaygroundPreviewBridge({
|
||||
deliver_code_preview_error: (...args) => errors.push(args),
|
||||
});
|
||||
bridge.requestCodePreview('mermaid', 'source', false, 1);
|
||||
const [worker] = env.workers;
|
||||
const [{ id }] = worker.posted;
|
||||
const completion = worker.emit('message', {
|
||||
data: { id, ok: true, result: { svg: '<svg width="2" height="2"/>' } },
|
||||
});
|
||||
img.onerror(new Error('decode failed'));
|
||||
await completion;
|
||||
bridge.dispose();
|
||||
assert.deepEqual(errors, [
|
||||
['mermaid', 'source', false, 1, 'Error: decode failed'],
|
||||
]);
|
||||
assert.deepEqual(env.revoked, [img.src, worker.url]);
|
||||
} finally {
|
||||
globalThis.Image = originalImage;
|
||||
env.restore();
|
||||
}
|
||||
});
|
||||
|
||||
void test('worker construction failure revokes its Blob URL and settles the preview once', () => {
|
||||
const env = createFakeDom();
|
||||
let failedUrl;
|
||||
globalThis.Worker = class {
|
||||
constructor(url) {
|
||||
failedUrl = url;
|
||||
throw new Error('worker blocked');
|
||||
}
|
||||
};
|
||||
try {
|
||||
const errors = [];
|
||||
const bridge = installPlaygroundPreviewBridge({
|
||||
deliver_code_preview_error: (...args) => errors.push(args),
|
||||
});
|
||||
bridge.requestCodePreview('typst', 'source', true, 2);
|
||||
bridge.dispose();
|
||||
assert.deepEqual(errors, [
|
||||
['typst', 'source', true, 2, 'Error: worker blocked'],
|
||||
]);
|
||||
assert.deepEqual(env.revoked, [failedUrl]);
|
||||
} finally {
|
||||
env.restore();
|
||||
}
|
||||
});
|
||||
|
||||
void test('mermaid and typst worker errors fail pending requests instead of stalling in Pending', () => {
|
||||
const env = createFakeDom();
|
||||
try {
|
||||
@@ -509,7 +642,7 @@ void test('mermaid SVG with width="100%" + viewBox rasterizes at intrinsic viewB
|
||||
bridge.requestCodePreview('mermaid', 'flowchart LR; A-->B-->C', false, 2);
|
||||
assert.equal(env.workers.length, 1);
|
||||
const reqId = env.workers[0].posted[0].id;
|
||||
env.workers[0].emit('message', {
|
||||
await env.workers[0].emit('message', {
|
||||
data: {
|
||||
id: reqId,
|
||||
ok: true,
|
||||
@@ -518,7 +651,6 @@ void test('mermaid SVG with width="100%" + viewBox rasterizes at intrinsic viewB
|
||||
},
|
||||
},
|
||||
});
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
assert.equal(delivered.length, 1);
|
||||
assert.equal(delivered[0].wPt, 840);
|
||||
assert.equal(delivered[0].hPt, 310);
|
||||
@@ -752,3 +884,65 @@ void test('PDF bridge answers every sent request on a crash, ignores a late erro
|
||||
env.restore();
|
||||
}
|
||||
});
|
||||
|
||||
void test('dispose terminates math, mermaid, typst, and pdf workers, fails pending requests, and lazily respawns on reuse', () => {
|
||||
const env = createFakeDom();
|
||||
try {
|
||||
const errors = [];
|
||||
const bridge = installPlaygroundPreviewBridge({
|
||||
deliver_math_error(latex) {
|
||||
errors.push(['math', latex]);
|
||||
},
|
||||
deliver_code_preview_error(kind, source) {
|
||||
errors.push([kind, source]);
|
||||
},
|
||||
deliver_pdf_open_error(docId) {
|
||||
errors.push(['pdf', docId]);
|
||||
},
|
||||
});
|
||||
bridge.registerFont(new Uint8Array([1, 2, 3, 4]));
|
||||
bridge.requestMath('x^2', false, 16, '#000', 2);
|
||||
bridge.requestCodePreview('mermaid', 'graph TD; A-->B', false, 2);
|
||||
bridge.requestCodePreview('typst', '= Hello', true, 2);
|
||||
bridge.openPdf(11, new Uint8Array([37, 80, 68, 70]));
|
||||
|
||||
assert.equal(env.workers.length, 4);
|
||||
assert.equal(
|
||||
env.workers.every(w => !w.terminated),
|
||||
true
|
||||
);
|
||||
|
||||
bridge.dispose();
|
||||
assert.equal(
|
||||
env.workers.every(w => w.terminated),
|
||||
true,
|
||||
'dispose() must terminate every active preview worker'
|
||||
);
|
||||
assert.deepEqual(errors, [
|
||||
['math', 'x^2'],
|
||||
['mermaid', 'graph TD; A-->B'],
|
||||
['typst', '= Hello'],
|
||||
['pdf', 11],
|
||||
]);
|
||||
assert.equal(bridge.isPdfOpen(11), false);
|
||||
|
||||
// Calling dispose() again is a safe no-op.
|
||||
bridge.dispose();
|
||||
assert.equal(env.workers.length, 4);
|
||||
|
||||
// Subsequent preview requests lazily respawn fresh workers and re-sync registered fonts.
|
||||
bridge.requestMath('y^2', false, 16, '#000', 2);
|
||||
bridge.requestCodePreview('mermaid', 'graph LR; C-->D', false, 2);
|
||||
bridge.requestCodePreview('typst', '= Next', true, 2);
|
||||
bridge.openPdf(12, new Uint8Array([37, 80, 68, 70]));
|
||||
assert.equal(env.workers.length, 8);
|
||||
assert.equal(
|
||||
env.workers.slice(4).every(w => !w.terminated),
|
||||
true
|
||||
);
|
||||
assert.equal(env.workers[5].posted[0].op, 'register_font');
|
||||
assert.equal(env.workers[6].posted[0].op, 'register_font');
|
||||
} finally {
|
||||
env.restore();
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user