feat(edgeless): add frame presentation

This commit is contained in:
DarkSky committed 2026-12-03 18:35:08 +09:00
1 parent 3a75ecff4c
commit db6580abe7
17 files changed
+1778 -103

No files matched your search

@@ -37,7 +37,7 @@ pub fn canvas_tool_cursor(
| EdgelessTool::Highlighter
| EdgelessTool::Text
| EdgelessTool::Frame => Some(ui::CursorStyle::Crosshair),
EdgelessTool::Select | EdgelessTool::Hand => None,
EdgelessTool::Select | EdgelessTool::Hand | EdgelessTool::Present => None,
}
}
@@ -16,6 +16,7 @@ mod order;
mod overlay;
mod overlay_label;
mod overlay_outline;
mod present;
mod quick_connect;
mod quick_connect_preview;
mod remote_presence;
@@ -98,3 +99,5 @@ use canvas::{
prepare_surface_block,
};
use quick_connect::build_connector_preview;
pub use present::{NavigatorMode, PresentationFrame, presentation_frames, presentation_mask};
@@ -0,0 +1,175 @@
use blocksuite_playground_doc::read::{BlockContent, PageSnapshot};
use ui::{Pixels, Size};
use super::{EdgelessCamera, WorldRect, parse_xywh};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum NavigatorMode {
#[default]
Fit,
Fill,
}
impl NavigatorMode {
pub fn toggled(self) -> Self {
match self {
Self::Fit => Self::Fill,
Self::Fill => Self::Fit,
}
}
pub fn camera(self, frame: WorldRect, viewport: Size<Pixels>) -> Option<EdgelessCamera> {
let (width, height) = (f32::from(viewport.width), f32::from(viewport.height));
if frame.is_empty() || width <= 0.0 || height <= 0.0 {
return None;
}
let (x_scale, y_scale) = (width / frame.w, height / frame.h);
let zoom = match self {
Self::Fit => x_scale.min(y_scale),
Self::Fill => x_scale.max(y_scale),
};
let (x, y) = frame.center();
let mut camera = EdgelessCamera::new(0.0, 0.0, zoom);
camera.pan_x = x - width / (2.0 * camera.zoom);
camera.pan_y = y - height / (2.0 * camera.zoom);
Some(camera)
}
}
#[derive(Debug, PartialEq)]
pub struct PresentationFrame {
pub id: String,
pub title: String,
pub bounds: Option<WorldRect>,
}
pub fn presentation_frames(snapshot: &PageSnapshot) -> Vec<PresentationFrame> {
let mut frames: Vec<_> = snapshot
.root
.iter()
.chain(&snapshot.detached)
.flat_map(|node| node.walk())
.filter_map(|node| {
let BlockContent::Frame { title, xywh } = &node.content else {
return None;
};
let order = node
.props
.get("prop:presentationIndex")
.and_then(|value| value.as_str())
.filter(|key| !key.is_empty());
let frame = PresentationFrame {
id: node.id.clone(),
title: title.plain.clone(),
bounds: parse_xywh(xywh).filter(|rect| !rect.is_empty()),
};
let key = order.unwrap_or_else(|| {
node.props
.get("prop:index")
.and_then(|value| value.as_str())
.unwrap_or("")
});
Some((order.is_none(), key, frame))
})
.collect();
frames.sort_by_key(|&(legacy, key, _)| (legacy, key));
frames.into_iter().map(|(_, _, frame)| frame).collect()
}
/// Return the four screen-space rectangles around the frame, clipped to the viewport.
pub fn presentation_mask(
frame: WorldRect,
camera: EdgelessCamera,
viewport: Size<Pixels>,
) -> [WorldRect; 4] {
let (width, height) = (f32::from(viewport.width), f32::from(viewport.height));
let x = |x: f32| ((x - camera.pan_x) * camera.zoom).clamp(0.0, width);
let y = |y: f32| ((y - camera.pan_y) * camera.zoom).clamp(0.0, height);
let (left, top, right, bottom) = (x(frame.x), y(frame.y), x(frame.right()), y(frame.bottom()));
[
WorldRect::new(0.0, 0.0, width, top),
WorldRect::new(0.0, bottom, width, height - bottom),
WorldRect::new(0.0, top, left, bottom - top),
WorldRect::new(right, top, width - right, bottom - top),
]
}
#[cfg(test)]
mod tests {
use super::*;
use ui::{px, size};
#[test]
fn legacy_frames_use_block_index_and_keep_traversal_order_on_ties() {
use blocksuite_playground_doc::read::BlockNode;
let frame = |id: &str, presentation: Option<&str>, index: &str| {
let mut props = std::collections::BTreeMap::new();
props.insert("prop:index".into(), index.into());
if let Some(presentation) = presentation {
props.insert("prop:presentationIndex".into(), presentation.into());
}
BlockNode {
id: id.into(),
flavour: "affine:frame".into(),
version: None,
content: BlockContent::Frame {
title: Default::default(),
xywh: "[0,0,100,100]".into(),
},
props,
children: Vec::new(),
}
};
let snapshot = PageSnapshot {
doc_id: "doc".into(),
root: None,
detached: vec![
frame("A", None, "a2"),
frame("B", Some(""), "a1"),
frame("C", None, "a1"),
frame("D", Some("a9"), "a9"),
frame("E", Some("a0"), "a9"),
],
};
let ids: Vec<_> = presentation_frames(&snapshot)
.into_iter()
.map(|frame| frame.id)
.collect();
assert_eq!(ids, ["E", "D", "B", "C", "A"]);
}
#[test]
fn camera_fits_or_fills_without_moving_the_center() {
for (width, height, fit, fill) in [(800.0, 600.0, 2.0, 3.0), (500.0, 200.0, 1.0, 1.25)] {
let viewport = size(px(width), px(height));
let frame = WorldRect::new(-130.0, 200.0, 400.0, 200.0);
for (mode, zoom) in [(NavigatorMode::Fit, fit), (NavigatorMode::Fill, fill)] {
let camera = mode.camera(frame, viewport).unwrap();
assert_eq!(camera.zoom, zoom);
assert_eq!(camera.viewport_center_world(viewport), frame.center());
}
}
}
#[test]
fn mask_clips_to_the_viewport_and_leaves_the_frame_open() {
let viewport = size(px(600.0), px(300.0));
let frame = WorldRect::new(50.0, 25.0, 100.0, 50.0);
assert_eq!(
presentation_mask(frame, EdgelessCamera::new(0.0, 0.0, 2.0), viewport),
[
WorldRect::new(0.0, 0.0, 600.0, 50.0),
WorldRect::new(0.0, 150.0, 600.0, 150.0),
WorldRect::new(0.0, 50.0, 100.0, 100.0),
WorldRect::new(300.0, 50.0, 300.0, 100.0),
]
);
let fill = NavigatorMode::Fill.camera(frame, viewport).unwrap();
assert!(
presentation_mask(frame, fill, viewport)
.into_iter()
.all(WorldRect::is_empty)
);
}
}
@@ -70,6 +70,7 @@ impl ShapePreset {
/// Host callbacks required by the Edgeless creation toolbar.
pub trait EdgelessToolbarHost: 'static + Sized {
fn edgeless_present_icon() -> &'static [u8];
fn edgeless_active_tool(&self) -> EdgelessTool;
fn edgeless_active_shape_type(&self) -> ShapePreset;
fn edgeless_toggle_shape_picker(&mut self, window: &mut Window, cx: &mut Context<Self>);
@@ -108,6 +109,7 @@ pub enum EdgelessTool {
Highlighter,
Text,
Frame,
Present,
}
impl EdgelessTool {
@@ -126,8 +128,52 @@ pub struct ShapePickerVisualState {
pub interactive: bool,
}
pub(super) const TOOLBAR_TOTAL_W: f32 = 9.0 * 28.0 + 8.0 * 2.0 + 2.0 * 4.0;
pub(super) const TOOLBAR_TOTAL_H: f32 = 28.0 + 2.0 * 4.0;
const BAR_MARGIN: f32 = 12.0;
const BAR_INNER_INSET: f32 = 4.0;
const BAR_PAD: f32 = BAR_INNER_INSET - 1.0;
const BAR_RADIUS: f32 = 8.0;
const BAR_INSET: f32 = 8.0;
const BTN_SIZE: f32 = 28.0;
const PRESENT_WIDTH: f32 = 36.0;
const BTN_RADIUS: f32 = 4.0;
const BTN_GAP: f32 = 2.0;
const TOOLS_PER_COMPACT_ROW: usize = 5;
const TOOL_COUNT: usize = 10;
struct ToolbarLayout {
left: f32,
height: f32,
button_gap: f32,
button_scale: f32,
tools_per_row: usize,
}
impl ToolbarLayout {
fn for_viewport(viewport_width: f32) -> Self {
let available = (viewport_width - 2.0 * BAR_INSET - 2.0 * BAR_INNER_INSET).max(0.0);
let single_row = (TOOL_COUNT - 1) as f32 * BTN_SIZE + PRESENT_WIDTH;
let (tools_per_row, button_gap, button_scale, height) = if available >= single_row {
let gap = ((available - single_row) / (TOOL_COUNT - 1) as f32).min(BTN_GAP);
(TOOL_COUNT, gap, 1.0, BTN_SIZE)
} else {
let compact_row = (TOOLS_PER_COMPACT_ROW - 1) as f32 * BTN_SIZE + PRESENT_WIDTH;
let gap = BTN_GAP.min(available / (2 * TOOLS_PER_COMPACT_ROW) as f32);
let scale =
((available - (TOOLS_PER_COMPACT_ROW - 1) as f32 * gap) / compact_row).min(1.0);
(TOOLS_PER_COMPACT_ROW, gap, scale, 2.0 * BTN_SIZE + BTN_GAP)
};
let width = ((tools_per_row - 1) as f32 * BTN_SIZE + PRESENT_WIDTH) * button_scale
+ (tools_per_row - 1) as f32 * button_gap
+ 2.0 * BAR_INNER_INSET;
Self {
left: ((viewport_width - width) * 0.5).round().max(BAR_INSET),
height: height + 2.0 * BAR_INNER_INSET,
button_gap,
button_scale,
tools_per_row,
}
}
}
fn active_pill_opacity(theme: PlaygroundTheme) -> f32 {
if theme == PlaygroundTheme::Dark {
@@ -150,13 +196,6 @@ pub fn build_edgeless_toolbar<V: EdgelessToolbarHost>(
theme: PlaygroundTheme,
cx: &mut Context<V>,
) -> AnyElement {
const BAR_MARGIN: f32 = 12.0;
const BAR_PAD: f32 = 4.0;
const BAR_RADIUS: f32 = 8.0;
const BTN_SIZE: f32 = 28.0;
const BTN_RADIUS: f32 = 4.0;
const BTN_GAP: f32 = 2.0;
let motion = chrome_motion_for_view(cx);
let shape_picker_open = shape_picker_state.as_ref().is_some_and(|s| s.interactive);
motion.update(cx, |s, cx| {
@@ -164,7 +203,7 @@ pub fn build_edgeless_toolbar<V: EdgelessToolbarHost>(
});
let shadows = theme.shadows("--affine-toolbar-shadow");
let tools: [(&'static str, &'static str, &'static str, EdgelessTool); 9] = [
let tools: [(&'static str, &'static str, &'static str, EdgelessTool); TOOL_COUNT] = [
(
"edgeless-tool-select",
"select",
@@ -214,14 +253,20 @@ pub fn build_edgeless_toolbar<V: EdgelessToolbarHost>(
"FrameIcon",
EdgelessTool::Frame,
),
(
"edgeless-tool-present",
"present",
"",
EdgelessTool::Present,
),
];
let bar_w = tools.len() as f32 * BTN_SIZE + (tools.len() - 1) as f32 * BTN_GAP + 2.0 * BAR_PAD;
let bar_left = ((viewport_width - bar_w) * 0.5).max(8.0).round();
let layout = ToolbarLayout::for_viewport(viewport_width);
let row = || div().flex().items_center().gap(px(layout.button_gap));
let mut tool_row = row();
let mut bar = div()
.absolute()
.left(px(bar_left))
.left(px(layout.left))
.bottom(px(BAR_MARGIN))
.p(px(BAR_PAD))
.rounded(px(BAR_RADIUS))
@@ -230,22 +275,29 @@ pub fn build_edgeless_toolbar<V: EdgelessToolbarHost>(
.border_color(palette.border)
.cursor_default()
.flex()
.flex_col()
.items_center()
.gap(px(BTN_GAP))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.snapshot("chrome.edgeless_toolbar", Some(EDGELESS_VIEWPORT_ID));
for (idx, (el_id, snap_suffix, icon_name, target_tool)) in tools.into_iter().enumerate() {
if idx == layout.tools_per_row {
bar = bar.child(tool_row);
tool_row = row();
}
let active = match (tool, target_tool) {
(EdgelessTool::Shape(_), EdgelessTool::Shape(_)) => true,
(a, b) => a == b,
};
let is_present = target_tool == EdgelessTool::Present;
let button_width = if is_present { PRESENT_WIDTH } else { BTN_SIZE } * layout.button_scale;
let target = ChromeHoverTarget::Tool(idx);
let m_down = motion.clone();
let icon_color = if active { palette.brand } else { palette.icon };
let mut btn = div()
.id(el_id)
.w(px(BTN_SIZE))
.w(px(button_width))
.h(px(BTN_SIZE))
.rounded(px(BTN_RADIUS))
.flex()
@@ -274,29 +326,36 @@ pub fn build_edgeless_toolbar<V: EdgelessToolbarHost>(
this.edgeless_select_tool(chosen, window, cx);
}),
)
.child(
.child(if is_present {
ui::svg()
.data(V::edgeless_present_icon())
.size(px(24.0_f32.min(button_width)))
.text_color(icon_color)
.into_any_element()
} else {
canvas(
|_, _, _| (),
move |bounds, _, window, cx| {
IconPaint::named(icon_name).paint(bounds, icon_color, window, cx);
},
)
.w(px(18.0))
.h(px(18.0)),
);
.size(px(18.0_f32.min(button_width)))
.into_any_element()
});
if active {
btn = btn.bg(palette.brand.opacity(active_pill_opacity(theme)));
}
btn = bind_chrome_button(btn, target, &motion, cx, active, palette, theme);
bar = bar.child(btn);
tool_row = tool_row.child(btn);
}
bar = bar.child(tool_row);
if !shadows.is_empty() {
bar = bar.shadow(shadows.clone().into());
}
let zoom_stacked = zoom_bar_stacks_above_toolbar(viewport_width, touch_mode, true);
let base_bottom = BAR_MARGIN + TOOLBAR_TOTAL_H + 8.0;
let base_bottom = BAR_MARGIN + layout.height + 8.0;
let target_bottom = if zoom_stacked {
base_bottom + zoom_bar_height(touch_mode) + 8.0
} else {
@@ -372,7 +431,7 @@ pub fn build_edgeless_toolbar<V: EdgelessToolbarHost>(
];
let sub_w = variants.len() as f32 * BTN_SIZE
+ (variants.len() - 1) as f32 * BTN_GAP
+ 2.0 * BAR_PAD;
+ 2.0 * BAR_INNER_INSET;
let sub_left = ((viewport_width - sub_w) * 0.5).max(8.0).round();
let mut sub = div()
.absolute()
@@ -450,8 +509,8 @@ pub fn build_edgeless_toolbar<V: EdgelessToolbarHost>(
});
let fallback_anchor = FlowRect::new(
bar_left + BAR_PAD,
(720.0 - BAR_MARGIN - TOOLBAR_TOTAL_H).max(8.0),
layout.left + BAR_INNER_INSET,
(720.0 - BAR_MARGIN - layout.height).max(8.0),
BTN_SIZE,
BTN_SIZE,
);
@@ -526,6 +585,10 @@ mod tests {
}
impl EdgelessToolbarHost for ToolbarView {
fn edgeless_present_icon() -> &'static [u8] {
ui_tokens::icons::FRAME.svg.as_bytes()
}
fn edgeless_active_tool(&self) -> EdgelessTool {
self.tool
}
@@ -559,8 +622,9 @@ mod tests {
}
impl Render for ToolbarView {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let palette = self.theme.palette();
let width = f32::from(window.viewport_size().width);
div()
.size_full()
.bg(palette.panel)
@@ -572,7 +636,7 @@ mod tests {
interactive: true,
}),
(brush_panel::DEFAULT_BRUSH_COLOR, BRUSH_LINE_WIDTHS[0]),
800.0,
width,
false,
&palette,
self.theme,
@@ -580,7 +644,7 @@ mod tests {
))
.child(build_zoom_controls(
1.0,
800.0,
width,
true,
false,
ui::Direction::Ltr,
@@ -597,6 +661,76 @@ mod tests {
}
}
#[test]
fn creation_toolbar_fits_and_stacks_with_zoom_at_narrow_widths() {
const TOOLS: [&str; 10] = [
"select",
"hand",
"note",
"shape",
"connector",
"brush",
"highlighter",
"text",
"frame",
"present",
];
for width in [160, 226, 260, 311, 312, 320, 800] {
let platform = HeadlessPlatform::new(width, 240, 1.0);
let app = Application::with_platform(platform.clone()).run_embedded(|cx| {
crate::register_bundled_fonts(cx).unwrap();
});
let handle = app.update(|cx| {
cx.open_window(ui::WindowOptions::default(), |_, cx| {
cx.new(|_| ToolbarView {
theme: PlaygroundTheme::Light,
tool: EdgelessTool::Shape(ShapePreset::Rect),
})
})
.unwrap()
});
platform.windows()[0].request_frame();
app.update(|cx| {
handle
.update(cx, |_, window, _| {
let elements = &window.frame_snapshot().elements;
let bar = elements["chrome.edgeless_toolbar"].bounds;
let zoom = elements["chrome.edgeless_zoom"].bounds;
let shape = elements["chrome.edgeless_toolbar.shape_picker"].bounds;
for (index, tool) in TOOLS.into_iter().enumerate() {
let button = &elements[&format!("chrome.edgeless_toolbar.{tool}")];
let bounds = button.bounds;
assert!(button.interactive, "{width}: {tool}");
assert!(bounds.x >= 8.0, "{width}: {tool} at {bounds:?}");
assert!(
bounds.x + bounds.width <= width as f32 - 8.0,
"{width}: {tool} at {bounds:?}"
);
assert_eq!(
bounds.y,
bar.y + 4.0 + if width < 312 && index >= 5 { 30.0 } else { 0.0 },
"{width}: {tool}"
);
}
if width <= 320 {
assert!(
zoom.y + zoom.height <= bar.y,
"{width}: zoom overlaps tools"
);
assert!(
shape.y + shape.height <= zoom.y,
"{width}: shape overlaps zoom"
);
} else {
assert!(zoom.x + zoom.width <= bar.x);
assert!(shape.y + shape.height <= bar.y);
}
})
.unwrap();
});
}
}
#[test]
fn hovered_edgeless_buttons_show_pressed_pixels_until_release() {
let cases: &[(EdgelessTool, &[&str])] = &[
@@ -73,8 +73,8 @@ pub(super) struct ToolButtonSpec {
pub(super) shortcut: Option<&'static str>,
}
/// Ordered creation-bar tool specs matching BlockSuite 0.27.5 (`default`..`frame`).
pub(super) const TOOL_SPECS: [ToolButtonSpec; 9] = [
/// Ordered creation-bar tool specs matching BlockSuite 0.27.5.
pub(super) const TOOL_SPECS: [ToolButtonSpec; 10] = [
ToolButtonSpec {
id: "select",
label: "Select",
@@ -120,6 +120,11 @@ pub(super) const TOOL_SPECS: [ToolButtonSpec; 9] = [
label: "Frame",
shortcut: Some("F"),
},
ToolButtonSpec {
id: "present",
label: "Present",
shortcut: None,
},
];
/// Metadata describing a shape sub-picker preset button.
@@ -7,7 +7,7 @@ use super::motion::{
};
use super::presets::{ChromeHoverTarget, TooltipOwner};
use super::{
EDGELESS_VIEWPORT_ID, FlowRect, Palette, PlaygroundTheme, TOOLBAR_TOTAL_H, TOOLBAR_TOTAL_W,
BAR_MARGIN, EDGELESS_VIEWPORT_ID, FlowRect, Palette, PlaygroundTheme, ToolbarLayout,
ZOOM_BAR_MARGIN, ZOOM_BAR_PAD, ZOOM_BAR_RADIUS, ZOOM_BTN_HEIGHT, ZOOM_BTN_RADIUS,
};
@@ -17,11 +17,11 @@ pub(super) fn zoom_bar_width(touch_mode: bool) -> f32 {
} else {
(28.0, 48.0, 28.0)
};
w_fit + w_step + w_reset + w_step + 3.0 * 4.0 + 2.0 * ZOOM_BAR_PAD
w_fit + w_step + w_reset + w_step + 3.0 * 4.0 + 2.0 * (ZOOM_BAR_PAD + 1.0)
}
pub(super) fn zoom_bar_height(touch_mode: bool) -> f32 {
(if touch_mode { 44.0 } else { ZOOM_BTN_HEIGHT }) + 2.0 * ZOOM_BAR_PAD
(if touch_mode { 44.0 } else { ZOOM_BTN_HEIGHT }) + 2.0 * (ZOOM_BAR_PAD + 1.0)
}
pub(super) fn zoom_bar_stacks_above_toolbar(
@@ -32,15 +32,14 @@ pub(super) fn zoom_bar_stacks_above_toolbar(
if !toolbar_visible {
return false;
}
let toolbar_left = ((viewport_width - TOOLBAR_TOTAL_W) * 0.5).max(8.0).round();
let toolbar_left = ToolbarLayout::for_viewport(viewport_width).left;
let zoom_right = ZOOM_BAR_MARGIN + zoom_bar_width(touch_mode) + 8.0;
zoom_right > toolbar_left
}
/// Build the logical bottom-left screen-space zoom control bar (`chrome.edgeless_zoom`):
/// LTR bottom-left, RTL automatically mirrored to bottom-right, ordered `[FitIcon] [−] [100%] [+]`.
/// On narrow viewports (`viewport_width < 660.0`) when `toolbar_visible` is `true`, stacks cleanly
/// above `chrome.edgeless_toolbar` so the two screen-space bars never overlap or clip.
/// If the bars would overlap, place the zoom bar above the creation toolbar.
#[allow(clippy::too_many_arguments)]
pub fn build_zoom_controls<V: 'static>(
zoom: f32,
@@ -131,7 +130,7 @@ pub fn build_zoom_controls<V: 'static>(
let zoom_bottom = if zoom_bar_stacks_above_toolbar(viewport_width, touch_mode, toolbar_visible)
{
ZOOM_BAR_MARGIN + safe_bottom + TOOLBAR_TOTAL_H + 8.0
BAR_MARGIN + safe_bottom + ToolbarLayout::for_viewport(viewport_width).height + 8.0
} else {
ZOOM_BAR_MARGIN + safe_bottom
};
+25 -26
View File
@@ -385,6 +385,10 @@ impl PlaygroundView {
if viewport_width > 0.0 && viewport_height > 0.0 {
self.edgeless.ensure_camera_initialized(&snapshot, vp_size);
}
let presenting = self.edgeless.authoring.tool == edgeless::EdgelessTool::Present;
if presenting {
self.update_presentation_camera(vp_size);
}
let now_ms = self.now_ms(cx);
self.edgeless.authoring.last_frame_now_ms = now_ms;
self.step_edgeless_fling(now_ms, window);
@@ -458,14 +462,18 @@ impl PlaygroundView {
};
edgeless::prepare_edgeless_scene(&mut self.edgeless, &prep_input, window)
};
let (zoom_controls, mut toolbar) = self.step_edgeless_controls_and_toolbar(
vp_origin,
vp_size,
viewport_width,
palette,
window,
cx,
);
let (canvas_controls, mut toolbar) = if presenting {
self.presentation_controls(vp_size, palette, cx)
} else {
self.step_edgeless_controls_and_toolbar(
vp_origin,
vp_size,
viewport_width,
palette,
window,
cx,
)
};
if self.active_note_touch_table_bar(viewport_width) {
toolbar = None;
}
@@ -508,10 +516,11 @@ impl PlaygroundView {
toolbar.is_none(),
caption_elements
.into_iter()
.chain([zoom_controls])
.chain([canvas_controls])
.chain(toolbar),
);
let needs_text_input = !self.has_non_text_modal_open()
let needs_text_input = !presenting
&& !self.has_non_text_modal_open()
&& (self.edgeless.authoring.inline_edit.is_some()
|| self.overlays.active_text_field().is_some()
|| !self.edgeless_readonly);
@@ -550,25 +559,15 @@ impl PlaygroundView {
.on_pinch(cx.listener(Self::on_edgeless_pinch))
.on_mouse_down(
MouseButton::Left,
cx.listener(|this, event: &ui::MouseDownEvent, window, cx| {
if this.edgeless_caption_mouse_down(event, window, cx) {
return;
}
if this.try_click_edgeless_note_latex(
f32::from(event.position.x),
f32::from(event.position.y),
event.click_count,
window,
cx,
) {
return;
}
this.on_edgeless_left_down(event, window, cx);
}),
cx.listener(Self::on_edgeless_canvas_press),
)
.on_mouse_down(
MouseButton::Right,
cx.listener(Self::edgeless_right_mouse_down),
cx.listener(|this, event, window, cx| {
if this.edgeless.authoring.tool != edgeless::EdgelessTool::Present {
this.edgeless_right_mouse_down(event, window, cx);
}
}),
)
.on_mouse_down(
MouseButton::Middle,
+1 -23
View File
@@ -556,32 +556,12 @@ impl PlaygroundView {
self.flow.database_state.mobile_readonly = self.database_readonly;
self.flow.database_state.clock_ms = self.local_calendar_now(cx).0;
self.layout = None;
self.edgeless = crate::edgeless::EdgelessCanvasState::new();
self.edgeless_camera_transition = None;
self.edgeless_shape_picker_presence = None;
self.edgeless_element_color_picker = None;
self.page_scroll_fling = None;
self.code_scroll_fling = None;
self.popover_scroll_fling = None;
self.edgeless_pan_fling = None;
self.scroll_axis_latch.reset();
self.active_touch_owner = crate::touch_interaction::TouchStrokeOwner::None;
self.modal_touch_target = crate::touch_interaction::ModalTouchTarget::None;
self.touch_long_press_anchor = None;
self.touch_selection_menu_open = false;
self.edgeless_readonly_selection_target = None;
self.caret_blink_task = None;
self.scrollbar_drag = None;
self.context_toast_timer = None;
self.context_paste_task = None;
self.context_menu_target = None;
self.reset_document_interaction();
self.last_opened_link_url = None;
self.last_link_popup_caret = None;
self.database_readonly_toast_shown = false;
self.database_record_sheet = None;
self.database_hover = Default::default();
self.pending_media_pick = None;
self.image_resize_drag = None;
self.doc_epoch = self.doc_epoch.wrapping_add(1);
self.state = state;
self.default_doc_directory = crate::directory::InMemoryDocDirectory::with_namespace(
@@ -600,8 +580,6 @@ impl PlaygroundView {
self.failed_pdf_blobs.clear();
self.pdf_page_indices.clear();
self.pdf_viewer.clear(&mut self.images);
self.keyboard_toolbar_dismissed = false;
self.ime_insets = crate::chrome::ImeInsetsState::default();
self.last_opened_embed_doc = None;
self.nav_history.clear();
self.page_id = None;
@@ -118,6 +118,10 @@ impl PlaygroundView {
window: &mut Window,
cx: &mut Context<Self>,
) {
if tool == EdgelessTool::Present {
self.toggle_presentation(window, cx);
return;
}
if self.edgeless_readonly {
return;
}
@@ -215,6 +219,9 @@ impl PlaygroundView {
window: &mut Window,
cx: &mut Context<Self>,
) -> bool {
if self.dismiss_presentation(cx) {
return true;
}
if self.edgeless.authoring.custom_color_editing
&& self.edgeless_element_color_picker.is_some()
{
@@ -271,6 +278,16 @@ impl PlaygroundView {
let cmd = m.secondary(cx);
let key = e.keystroke.key.as_str();
if self.edgeless.authoring.tool == EdgelessTool::Present {
if matches!(key, "tab" | "enter") {
return false;
}
if !cmd && !m.alt && !m.control && !m.shift {
self.presentation_key_down(key, cx);
}
return true;
}
// Custom `#RRGGBB` input inside the element toolbar color picker.
if self.edgeless.authoring.custom_color_editing
&& self.edgeless_element_color_picker.is_some()
@@ -122,6 +122,7 @@ impl EdgelessElementToolbarHost for PlaygroundView {
impl PlaygroundView {
pub(crate) fn reset_canvas_tool_panels(&mut self) {
self.reset_presentation();
self.dismiss_edgeless_element_popovers();
self.edgeless.authoring.element_panel_anchor = None;
self.edgeless.authoring.shape_picker_open = false;
@@ -17,6 +17,27 @@ use super::{
};
impl PlaygroundView {
pub(crate) fn on_edgeless_canvas_press(
&mut self,
event: &MouseDownEvent,
window: &mut Window,
cx: &mut Context<Self>,
) {
if self.edgeless.authoring.tool != EdgelessTool::Present
&& (self.edgeless_caption_mouse_down(event, window, cx)
|| self.try_click_edgeless_note_latex(
f32::from(event.position.x),
f32::from(event.position.y),
event.click_count,
window,
cx,
))
{
return;
}
self.on_edgeless_left_down(event, window, cx);
}
pub(crate) fn on_edgeless_left_down(
&mut self,
event: &MouseDownEvent,
@@ -24,6 +45,7 @@ impl PlaygroundView {
cx: &mut Context<Self>,
) {
self.editor_focus.focus(window, cx);
self.close_presentation_menu(cx);
if self.dismiss_edgeless_element_popovers() {
cx.notify();
}
@@ -43,6 +65,13 @@ impl PlaygroundView {
let wx = f32::from(world_pt.x);
let wy = f32::from(world_pt.y);
if self.edgeless.authoring.tool == EdgelessTool::Present
&& !self.edgeless.authoring.space_pan
&& !self.form_factor.is_touch_form_factor()
{
return;
}
let mindmap_button =
self.edgeless
.authoring
@@ -54,7 +83,10 @@ impl PlaygroundView {
// Mobile read-only Edgeless mode (`enable_mobile_edgeless_editing == false`), Hand tool,
// or Space-hold pans smoothly with left/single-finger drag and makes zero CRDT edits.
if self.edgeless_readonly
|| self.edgeless.authoring.tool == EdgelessTool::Hand
|| matches!(
self.edgeless.authoring.tool,
EdgelessTool::Hand | EdgelessTool::Present
)
|| self.edgeless.authoring.space_pan
{
self.edgeless_camera_transition = None;
@@ -381,7 +413,7 @@ impl PlaygroundView {
EdgelessTool::Text => {
self.create_edgeless_text_at(wx, wy, window, cx);
}
EdgelessTool::Hand => {}
EdgelessTool::Hand | EdgelessTool::Present => {}
}
}
}
@@ -47,6 +47,8 @@ mod paste;
pub(crate) mod paste_convert;
mod paste_url;
pub(crate) use paste_url::linked_card_url;
mod present;
mod present_toolbar;
mod quick_connect;
mod remote_presence;
mod shape_picker;
@@ -54,6 +56,8 @@ mod ungroup_ops;
pub use blocksuite_editor::edgeless::*;
pub(crate) use element_toolbar_media_actions::EdgelessHostRuntime;
pub use present::PRESENTATION_ICON;
pub(crate) use present::Presentation;
pub(crate) use commands::find_surface_element;
use commands::{
@@ -61,6 +65,10 @@ use commands::{
};
impl EdgelessToolbarHost for crate::PlaygroundView {
fn edgeless_present_icon() -> &'static [u8] {
PRESENTATION_ICON
}
fn edgeless_active_tool(&self) -> EdgelessTool {
self.edgeless.authoring.tool
}
@@ -118,6 +126,18 @@ impl EdgelessToolbarHost for crate::PlaygroundView {
}
impl crate::PlaygroundView {
pub(crate) fn reset_document_canvas(&mut self) {
self.reset_presentation();
self.edgeless = EdgelessCanvasState::new();
self.edgeless_camera_transition = None;
self.edgeless_shape_picker_presence = None;
self.edgeless_element_color_picker = None;
self.page_scroll_fling = None;
self.code_scroll_fling = None;
self.popover_scroll_fling = None;
self.edgeless_pan_fling = None;
}
/// True when Edgeless canvas writes and authoring mutations are disabled.
pub(crate) fn is_edgeless_write_readonly(&self) -> bool {
self.edgeless_readonly
@@ -0,0 +1,475 @@
use ui::{AnyElement, Context, Pixels, Size, Window, div, prelude::*, px};
use super::{
EdgelessTool, NavigatorMode, PresentationFrame, presentation_frames, presentation_mask,
};
use crate::{PlaygroundMode, PlaygroundView, theme::Palette};
#[derive(Default)]
pub(crate) struct Presentation {
pub(super) frames: Vec<PresentationFrame>,
pub(super) index: usize,
revision: Option<u64>,
viewport: Option<Size<Pixels>>,
pub(super) mode: NavigatorMode,
pub(super) black_background: bool,
pub(super) hide_toolbar: bool,
pub(super) menu: Option<Menu>,
pub(super) frame_scroll_y: f32,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum Menu {
Frames,
Settings,
}
impl Presentation {
pub(super) fn current(&self) -> Option<&PresentationFrame> {
self.frames.get(self.index)
}
}
impl PlaygroundView {
/// Start or stop frame presentation in this Edgeless editor.
pub fn toggle_presentation(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.mode != PlaygroundMode::Edgeless || self.snapshot.is_none() {
return;
}
self.editor_focus.focus(window, cx);
if self.edgeless.authoring.tool == EdgelessTool::Present {
self.stop_presentation(cx);
return;
}
let selected = (self.edgeless.authoring.selection.len() == 1)
.then(|| self.edgeless.authoring.selection.first().cloned())
.flatten();
self.finish_inline_targets(
crate::overlays::InlineTargetEnd::CommitPreedit,
Some(window),
Some(cx),
);
self.edgeless_commit_inline_edit(window, cx);
self.dismiss_all_database_authoring(None, cx);
self.reset_canvas_tool_panels();
self.doc_panel_tab = None;
self.overlays.close_context_menu(self.now_ms(cx));
self.edgeless.authoring.reset_transient();
self.edgeless.authoring.selection.clear();
self.edgeless.authoring.quick_connect_hover = None;
self.edgeless_readonly_selection_target = None;
self.edgeless.drag_pan_anchor = None;
self.edgeless_camera_transition = None;
self.edgeless_pan_fling = None;
let state = &mut self.edgeless_presentation;
state.index = 0;
state.revision = None;
state.viewport = None;
state.menu = None;
self.edgeless.authoring.tool = EdgelessTool::Present;
self.sync_presentation_frames();
let state = &mut self.edgeless_presentation;
if let Some(index) =
selected.and_then(|id| state.frames.iter().position(|frame| frame.id == id))
{
state.index = index;
}
self.center_presentation_frame(self.canvas_rect(window).1);
if self.edgeless_presentation.frames.is_empty() {
self.show_timed_context_toast(
"The presentation requires at least 1 frame. You can firstly create a frame.",
cx,
);
}
cx.notify();
}
pub(crate) fn reset_presentation(&mut self) {
if self.edgeless.authoring.tool == EdgelessTool::Present {
self.edgeless.authoring.tool = if self.edgeless_readonly {
EdgelessTool::Hand
} else {
EdgelessTool::Select
};
}
let state = &mut self.edgeless_presentation;
state.frames.clear();
state.index = 0;
state.revision = None;
state.viewport = None;
state.menu = None;
}
pub(super) fn stop_presentation(&mut self, cx: &mut Context<Self>) {
self.reset_presentation();
self.edgeless.authoring.reset_transient();
self.edgeless.drag_pan_anchor = None;
self.edgeless_pan_fling = None;
cx.notify();
}
pub(super) fn dismiss_presentation(&mut self, cx: &mut Context<Self>) -> bool {
if self.edgeless.authoring.tool != EdgelessTool::Present {
return false;
}
if self.edgeless_presentation.menu.take().is_some() {
cx.notify();
} else {
self.stop_presentation(cx);
}
true
}
pub(super) fn presentation_key_down(&mut self, key: &str, cx: &mut Context<Self>) {
match key {
"left" => self.step_presentation(false, cx),
"right" => self.step_presentation(true, cx),
"space" => self.edgeless.authoring.space_pan = true,
_ => {}
}
}
fn sync_presentation_frames(&mut self) {
let state = &mut self.edgeless_presentation;
if state.revision == Some(self.doc_rev) {
return;
}
let frames = self
.snapshot
.as_deref()
.map(presentation_frames)
.unwrap_or_default();
let next = state
.current()
.and_then(|current| frames.iter().position(|frame| frame.id == current.id))
.unwrap_or_else(|| state.index.min(frames.len().saturating_sub(1)));
if state.current() != frames.get(next) {
state.viewport = None;
}
state.index = next;
state.frames = frames;
state.revision = Some(self.doc_rev);
}
pub(crate) fn update_presentation_camera(&mut self, viewport: Size<Pixels>) {
self.sync_presentation_frames();
if self.edgeless_presentation.viewport != Some(viewport) {
self.center_presentation_frame(viewport);
}
}
pub(super) fn center_presentation_frame(&mut self, viewport: Size<Pixels>) {
let state = &mut self.edgeless_presentation;
if let Some(camera) = state
.current()
.and_then(|frame| state.mode.camera(frame.bounds?, viewport))
{
self.edgeless.camera = camera;
self.edgeless.camera_initialized = true;
self.edgeless_camera_transition = None;
self.edgeless_pan_fling = None;
}
state.viewport = Some(viewport);
}
pub(super) fn step_presentation(&mut self, forward: bool, cx: &mut Context<Self>) {
self.sync_presentation_frames();
let state = &self.edgeless_presentation;
if state.frames.is_empty() {
return;
}
let next = if forward {
(state.index + 1 < state.frames.len()).then_some(state.index + 1)
} else {
state.index.checked_sub(1)
};
if let Some(index) = next {
self.jump_to_presentation_frame(index, cx);
} else {
let message = if forward {
"You have reached the last frame"
} else {
"You have reached the first frame"
};
self.show_timed_context_toast(message, cx);
cx.notify();
}
}
pub(super) fn select_presentation_frame(&mut self, id: &str, cx: &mut Context<Self>) {
self.sync_presentation_frames();
if let Some(index) = self
.edgeless_presentation
.frames
.iter()
.position(|frame| frame.id == id)
{
self.jump_to_presentation_frame(index, cx);
}
}
fn jump_to_presentation_frame(&mut self, index: usize, cx: &mut Context<Self>) {
self.sync_presentation_frames();
if index < self.edgeless_presentation.frames.len() {
self.edgeless_presentation.index = index;
self.edgeless_presentation.menu = None;
self.center_presentation_frame(self.canvas_rect_cached().1);
cx.notify();
}
}
pub(crate) fn close_presentation_menu(&mut self, cx: &mut Context<Self>) {
if self.edgeless_presentation.menu.take().is_some() {
cx.notify();
}
}
pub(crate) fn presentation_controls(
&self,
viewport: Size<Pixels>,
palette: &Palette,
cx: &mut Context<Self>,
) -> (AnyElement, Option<AnyElement>) {
let state = &self.edgeless_presentation;
let mask = state
.black_background
.then(|| state.current()?.bounds)
.flatten();
let masks = mask
.into_iter()
.flat_map(|frame| presentation_mask(frame, self.edgeless.camera, viewport))
.filter(|rect| !rect.is_empty())
.map(|rect| {
div()
.absolute()
.left(px(rect.x))
.top(px(rect.y))
.w(px(rect.w))
.h(px(rect.h))
.bg(ui::black())
});
(
div()
.absolute()
.inset_0()
.children(masks)
.into_any_element(),
Some(self.presentation_toolbar(viewport, palette, cx)),
)
}
}
// Source: PresentationIcon in @blocksuite/icons 2.2.17.
pub const PRESENTATION_ICON: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"><path fill="currentColor" fill-rule="evenodd" d="M3.174 3.952c0-.426.346-.772.772-.772h15.957a.772.772 0 0 1 0 1.544h-.368v9.853h.367a.772.772 0 0 1 0 1.545h-7.206v1.661l3.942 2.252a.772.772 0 1 1-.766 1.341l-3.176-1.815v1.487a.772.772 0 0 1-1.544 0v-1.421l-3.062 1.75a.772.772 0 1 1-.766-1.341l3.828-2.188v-1.726H3.946a.772.772 0 1 1 0-1.545h.368V4.724h-.368a.77.77 0 0 1-.772-.772m2.684.772h12.133v9.853H5.858zm3.42 4.357a.772.772 0 0 0-1.545 0v2.28a.772.772 0 0 0 1.544 0zm2.646-2.482c.427 0 .772.346.772.772v3.99a.772.772 0 0 1-1.544 0V7.37c0-.426.346-.772.772-.772m4.192 3.622a.772.772 0 0 0-1.545 0v1.14a.772.772 0 1 0 1.545 0z" clip-rule="evenodd"/></svg>"#;
#[cfg(test)]
mod tests {
use super::*;
use crate::HOME_PAGE_ID;
use blocksuite_playground_doc::schema::BlockSpec;
use ui::{KeyDownEvent, Keystroke};
#[test]
fn presentation_uses_selected_frame_and_navigates_in_order_without_writes() {
let (_, app, handle, hw) =
super::super::edgeless_toolbar_tests::start_edgeless_toolbar_view();
app.update(|cx| {
handle
.update(cx, |view, window, cx| {
view.edit_document(cx, |doc| {
let page = doc.workspace.page_mut(HOME_PAGE_ID).unwrap();
for (id, title, index, geometry) in [
("later", "Later", Some("a1"), "[1200,0,600,400]"),
("earlier", "Earlier", Some("Zz"), "[0,500,800,300]"),
(
"legacy-first",
"First legacy",
Some(""),
"[1000,500,600,400]",
),
("legacy-last", "Last legacy", None, "[1000,1000,600,400]"),
] {
page.add_block(
id,
BlockSpec::Frame {
title: title.into(),
xywh: Some(geometry.into()),
presentation_index: index.map(str::to_string),
},
Some("surf"),
None,
100,
)
.unwrap();
if index.is_none() {
page.set_block_prop(
id,
"prop:presentationIndex",
y_octo::SessionValue::Any(y_octo::Any::Null),
101,
)
.unwrap();
}
}
});
view.edgeless_set_selection(["later".to_string()], cx);
view.toggle_presentation(window, cx);
let revision = view.doc_rev;
let state = &view.edgeless_presentation;
let ids: Vec<_> = state.frames.iter().map(|frame| frame.id.as_str()).collect();
assert_eq!(
ids,
[
"earlier",
"frame-outer",
"later",
"frame-empty",
"legacy-first",
"legacy-last"
]
);
assert_eq!(state.index, 2);
let (_, viewport) = view.canvas_rect(window);
assert_eq!(
view.edgeless_camera().viewport_center_world(viewport),
(1500.0, 200.0)
);
let key = |name| KeyDownEvent {
keystroke: Keystroke::parse(name).unwrap(),
is_held: false,
prefer_character_input: false,
};
for (name, index, toast) in [
("right", 3, None),
("right", 4, None),
("right", 5, None),
("right", 5, Some("You have reached the last frame")),
("left", 4, None),
("left", 3, None),
("left", 2, None),
("left", 1, None),
("left", 0, None),
("left", 0, Some("You have reached the first frame")),
] {
assert!(view.edgeless_key_down(&key(name), window, cx));
let state = &view.edgeless_presentation;
assert_eq!(state.index, index);
if let Some(message) = toast {
assert_eq!(view.overlays.context_toast_message(), Some(message));
}
let bounds = state.current().unwrap().bounds.unwrap();
let (actual_x, actual_y) =
view.edgeless_camera().viewport_center_world(viewport);
let (x, y) = bounds.center();
assert!((actual_x - x).abs() < 0.001 && (actual_y - y).abs() < 0.001);
}
view.edgeless_presentation.menu = Some(Menu::Settings);
assert!(view.dismiss_transient_on_escape(&key("escape"), window, cx));
assert_eq!(view.edgeless.authoring.tool, EdgelessTool::Present);
assert!(view.edgeless_presentation.menu.is_none());
assert!(view.dismiss_transient_on_escape(&key("escape"), window, cx));
assert_eq!(view.edgeless.authoring.tool, EdgelessTool::Select);
assert_eq!(view.doc_rev, revision);
})
.unwrap();
});
hw.request_frame();
}
#[test]
fn legacy_indices_control_the_starting_camera_and_right_arrow() {
let (_, app, handle, _) =
super::super::edgeless_toolbar_tests::start_edgeless_toolbar_view();
app.update(|cx| {
handle
.update(cx, |view, window, cx| {
view.edit_document(cx, |doc| {
let page = doc.workspace.page_mut(HOME_PAGE_ID).unwrap();
for id in ["frame-outer", "frame-empty"] {
page.delete_block_subtree("surf", id, 100).unwrap();
}
for (id, xywh, index) in [
("A", "[1000,500,600,400]", "a2"),
("B", "[0,0,200,200]", "a1"),
] {
page.add_block(
id,
BlockSpec::Frame {
title: id.into(),
xywh: Some(xywh.into()),
presentation_index: None,
},
Some("surf"),
None,
101,
)
.unwrap();
page.set_block_index(id, index, 102).unwrap();
page.set_block_prop(
id,
"prop:presentationIndex",
y_octo::SessionValue::Any(y_octo::Any::Null),
102,
)
.unwrap();
}
let snapshot = page.read_page_snapshot().unwrap();
let traversal: Vec<_> = snapshot
.root
.iter()
.flat_map(|root| root.walk())
.filter(|node| node.id == "A" || node.id == "B")
.map(|node| node.id.as_str())
.collect();
assert_eq!(traversal, ["A", "B"]);
});
view.toggle_presentation(window, cx);
let (_, viewport) = view.canvas_rect(window);
let right = KeyDownEvent {
keystroke: Keystroke::parse("right").unwrap(),
is_held: false,
prefer_character_input: false,
};
for (id, (x, y)) in [("B", (100.0, 100.0)), ("A", (1300.0, 700.0))] {
if id == "A" {
assert!(view.edgeless_key_down(&right, window, cx));
}
assert_eq!(view.edgeless_presentation.current().unwrap().id, id);
let (cx, cy) = view.edgeless_camera().viewport_center_world(viewport);
assert!((cx - x).abs() < 0.001 && (cy - y).abs() < 0.001);
}
})
.unwrap();
});
}
#[test]
fn readonly_empty_presentation_keeps_camera_and_exits_to_hand() {
let (_, app, handle, _) =
super::super::edgeless_toolbar_tests::start_edgeless_toolbar_view();
app.update(|cx| {
handle.update(cx, |view, window, cx| {
view.edit_document(cx, |doc| {
let page = doc.workspace.page_mut(HOME_PAGE_ID).unwrap();
for id in ["frame-outer", "frame-empty"] {
page.delete_block_subtree("surf", id, 100).unwrap();
}
});
view.set_edgeless_readonly(true, window, cx);
let camera = view.edgeless_camera();
view.toggle_presentation(window, cx);
assert!(view.edgeless_presentation.frames.is_empty());
assert_eq!(view.overlays.context_toast_message(), Some(
"The presentation requires at least 1 frame. You can firstly create a frame."
));
assert_eq!(view.edgeless_camera(), camera);
assert_eq!(view.edgeless.authoring.tool, EdgelessTool::Present);
view.toggle_presentation(window, cx);
assert_eq!(view.edgeless.authoring.tool, EdgelessTool::Hand);
}).unwrap();
});
}
}
@@ -0,0 +1,420 @@
use blocksuite_editor::{
scroll::{ScrollAxis, wheel_delta},
theme::IconPaint,
};
use ui::{
AnyElement, Context, Hsla, MouseButton, Pixels, Size, Stateful, Window, div, prelude::*, px,
svg,
};
use super::{EDGELESS_VIEWPORT_ID, NavigatorMode, PRESENTATION_ICON, present::Menu};
use crate::{PlaygroundView, theme::Palette};
const BOTTOM: f32 = 12.0;
const MENU_WIDTH: f32 = 280.0;
impl PlaygroundView {
pub(super) fn presentation_toolbar(
&self,
viewport: Size<Pixels>,
palette: &Palette,
cx: &mut Context<Self>,
) -> AnyElement {
let state = &self.edgeless_presentation;
let viewport_width = f32::from(viewport.width);
if state.hide_toolbar {
return div()
.absolute()
.right(px(BOTTOM))
.bottom(px(BOTTOM))
.p(px(4.0))
.rounded(px(8.0))
.bg(palette.panel)
.child(
action("show", "Show toolbar", palette, cx, |this, cx| {
this.edgeless_presentation.hide_toolbar = false;
cx.notify();
})
.child(icon(PRESENTATION_ICON, palette.icon)),
)
.into_any_element();
}
let dense = viewport_width < 554.0;
let title = (!dense).then(|| {
state
.current()
.map_or_else(|| "no frame".to_string(), |frame| frame.title.clone())
});
let current = usize::from(!state.frames.is_empty()) + state.index;
let count = format!("{current} / {}", state.frames.len());
let progress = action(
"current",
"Center current frame",
palette,
cx,
|this, cx| {
this.center_presentation_frame(this.canvas_rect_cached().1);
cx.notify();
},
)
.snapshot_text(count.clone())
.w(px(if dense { 54.0 } else { 140.0 }))
.gap(px(8.0))
.when_some(title.filter(|title| !title.is_empty()), |el, title| {
el.child(div().min_w(px(0.0)).truncate().child(title))
})
.child(
div()
.flex_shrink(0.0)
.text_color(palette.text_secondary)
.child(count),
);
let size_label = match state.mode {
NavigatorMode::Fit => "Fit",
NavigatorMode::Fill => "Fill",
};
let icon_color = palette.icon;
let warning = self
.theme
.css_var("--affine-warning-color")
.unwrap_or(palette.error);
let strip = div()
.id("presentation-controls")
.snapshot(
"chrome.edgeless_toolbar.presentation",
Some(EDGELESS_VIEWPORT_ID),
)
.flex()
.items_center()
.gap(px(if dense { 2.0 } else { 8.0 }))
.p(px(4.0))
.rounded(px(8.0))
.bg(palette.panel)
.shadow(self.theme.shadows("--affine-toolbar-shadow").into())
.text_size(px(14.0))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.child(
action("previous", "Previous", palette, cx, |this, cx| {
this.step_presentation(false, cx);
})
.child(icon(PREVIOUS_ICON, palette.icon)),
)
.child(progress)
.child(
action("next", "Next", palette, cx, |this, cx| {
this.step_presentation(true, cx);
})
.child(icon(NEXT_ICON, palette.icon)),
)
.child(divider(palette))
.child(
action("size", "Toggle Fit or Fill", palette, cx, |this, cx| {
let state = &mut this.edgeless_presentation;
state.mode = state.mode.toggled();
this.center_presentation_frame(this.canvas_rect_cached().1);
cx.notify();
})
.w(px(36.0))
.child(size_label),
)
.child(
action("order", "Frame Order", palette, cx, |this, cx| {
this.toggle_presentation_menu(Menu::Frames, cx);
})
.child(icon(ORDER_ICON, palette.icon)),
)
.child(
action("settings", "Playback Settings", palette, cx, |this, cx| {
this.toggle_presentation_menu(Menu::Settings, cx);
})
.child(
ui::canvas(
|_, _, _| (),
move |bounds, _, window, cx| {
IconPaint::named("SettingsIcon").paint(bounds, icon_color, window, cx);
},
)
.size(px(24.0)),
),
)
.child(divider(palette))
.child(
action(
"stop",
"Stop",
&Palette {
hover: warning.opacity(0.9),
..*palette
},
cx,
|this, cx| this.stop_presentation(cx),
)
.size(px(32.0))
.rounded(px(8.0))
.bg(warning)
.child(icon(STOP_ICON, ui::white())),
);
let menu = state.menu.map(|kind| {
let width = (viewport_width - 16.0).clamp(1.0, MENU_WIDTH);
let height = (f32::from(viewport.height) - 92.0).clamp(32.0, 281.0);
let left = (viewport_width * 0.5 + if dense { 42.0 } else { 89.0 } - width * 0.5)
.clamp(8.0, (viewport_width - width - 8.0).max(8.0));
let (name, title) = match kind {
Menu::Frames => ("order_menu", "Frame Order"),
Menu::Settings => ("settings_menu", "Playback Settings"),
};
let content = div()
.absolute()
.left(px(left))
.bottom(px(BOTTOM + 40.0 + 12.0))
.w(px(width))
.flex()
.flex_col()
.gap(px(4.0))
.p(px(8.0))
.rounded(px(8.0))
.bg(palette.panel)
.shadow(self.theme.shadows("--affine-menu-shadow").into())
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.snapshot(
format_args!("chrome.edgeless_toolbar.presentation.{name}"),
Some("chrome.edgeless_toolbar.presentation"),
)
.child(
div()
.h(px(26.0))
.px(px(8.0))
.flex()
.items_center()
.text_size(px(12.0))
.text_color(palette.text_secondary)
.child(title),
);
match kind {
Menu::Frames => content.child(self.presentation_frame_rows(height, palette, cx)),
Menu::Settings => content
.child(setting(
"black",
"Black background",
state.black_background,
palette,
cx,
|this, cx| {
this.edgeless_presentation.black_background =
!this.edgeless_presentation.black_background;
cx.notify();
},
))
.child(setting(
"hide",
"Hide toolbar",
state.hide_toolbar,
palette,
cx,
|this, cx| {
this.edgeless_presentation.hide_toolbar = true;
this.close_presentation_menu(cx);
},
)),
}
});
div()
.absolute()
.inset_0()
.child(
div()
.absolute()
.left_0()
.bottom(px(BOTTOM))
.w_full()
.flex()
.justify_center()
.child(strip),
)
.children(menu)
.into_any_element()
}
fn presentation_frame_rows(
&self,
max_height: f32,
palette: &Palette,
cx: &mut Context<Self>,
) -> impl IntoElement {
const ROW_HEIGHT: f32 = 30.0;
let state = &self.edgeless_presentation;
let content_height = state.frames.len() as f32 * ROW_HEIGHT;
let height = content_height.min(max_height);
let max_scroll = content_height - height;
let scroll_y = state.frame_scroll_y.clamp(0.0, max_scroll);
let hover = palette.hover;
let rows = state.frames.iter().enumerate().map(|(index, frame)| {
let id = frame.id.clone();
let label = if frame.title.is_empty() {
format!("Frame {}", index + 1)
} else {
frame.title.clone()
};
div()
.id(("presentation-frame", index))
.h(px(ROW_HEIGHT))
.w_full()
.flex_shrink(0.0)
.px(px(8.0))
.rounded(px(4.0))
.flex()
.items_center()
.hover(move |style| style.bg(hover))
.tab_index(0)
.cursor_pointer()
.when(index == state.index, |el| el.bg(hover))
.snapshot(
format_args!("chrome.edgeless_toolbar.presentation.order_menu.frame.{index}"),
Some("chrome.edgeless_toolbar.presentation.order_menu"),
)
.on_click(cx.listener(move |this, _, window, cx| {
this.editor_focus.focus(window, cx);
this.select_presentation_frame(&id, cx);
}))
.child(
div()
.min_w(px(0.0))
.truncate()
.text_size(px(14.0))
.child(label),
)
});
div()
.relative()
.h(px(height))
.overflow_hidden()
.on_scroll(cx.listener(move |this, event: &ui::ScrollEvent, _, cx| {
let (_, delta) = wheel_delta(event, height);
let mut axis =
ScrollAxis::new(this.edgeless_presentation.frame_scroll_y, max_scroll);
if axis.apply(delta) {
this.edgeless_presentation.frame_scroll_y = axis.offset;
cx.notify();
}
cx.stop_propagation();
}))
.child(
div()
.absolute()
.left_0()
.right(px(0.0))
.top(px(-scroll_y))
.flex()
.flex_col()
.children(rows),
)
}
fn toggle_presentation_menu(&mut self, menu: Menu, cx: &mut Context<Self>) {
let state = &mut self.edgeless_presentation;
state.menu = (state.menu != Some(menu)).then_some(menu);
state.frame_scroll_y = 0.0;
cx.notify();
}
}
fn divider(palette: &Palette) -> impl IntoElement {
div().w(px(0.5)).h(px(24.0)).bg(palette.border)
}
fn icon(data: &'static [u8], color: Hsla) -> impl IntoElement {
svg().data(data).size(px(24.0)).text_color(color)
}
fn action(
name: &'static str,
label: &'static str,
palette: &Palette,
cx: &mut Context<PlaygroundView>,
activate: impl Fn(&mut PlaygroundView, &mut Context<PlaygroundView>) + 'static,
) -> Stateful<ui::Div> {
let hover = palette.hover;
let mut button = div()
.id(name)
.snapshot(
format_args!("chrome.edgeless_toolbar.presentation.{name}"),
Some("chrome.edgeless_toolbar.presentation"),
)
.size(px(24.0))
.flex_shrink(0.0)
.flex()
.items_center()
.justify_center()
.rounded(px(4.0))
.tab_index(0)
.cursor_pointer()
.hover(move |style| style.bg(hover))
.focus_visible(move |style| style.bg(hover))
.on_click(cx.listener(move |this, _, window, cx| {
this.editor_focus.focus(window, cx);
activate(this, cx);
}));
let palette = *palette;
button
.interactivity()
.tooltip(move |_, cx| cx.new(|_| PresentationTooltip(label, palette)).into());
button
}
struct PresentationTooltip(&'static str, Palette);
impl ui::Render for PresentationTooltip {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div()
.px(px(8.0))
.py(px(4.0))
.rounded(px(4.0))
.bg(self.1.text_primary)
.text_color(self.1.panel)
.text_size(px(12.0))
.child(self.0)
}
}
fn setting(
name: &'static str,
label: &'static str,
checked: bool,
palette: &Palette,
cx: &mut Context<PlaygroundView>,
activate: impl Fn(&mut PlaygroundView, &mut Context<PlaygroundView>) + 'static,
) -> impl IntoElement {
action(name, label, palette, cx, activate)
.w_full()
.h(px(32.0))
.px(px(8.0))
.text_size(px(14.0))
.child(label)
.child(div().flex_1())
.child(
div()
.w(px(28.0))
.h(px(16.0))
.px(px(2.0))
.rounded(px(8.0))
.flex()
.items_center()
.bg(if checked {
palette.brand
} else {
palette.border
})
.children(checked.then(|| div().flex_1()))
.child(div().size(px(12.0)).rounded(px(6.0)).bg(ui::white())),
)
}
// Source: @blocksuite/icons 2.2.17.
const PREVIOUS_ICON: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"> <path fill="currentColor" fill-rule="evenodd" d="M7.53 7.47a.75.75 0 0 1 0 1.06l-2.72 2.72H21a.75.75 0 0 1 0 1.5H4.81l2.72 2.72a.75.75 0 1 1-1.06 1.06l-4-4a.75.75 0 0 1 0-1.06l4-4a.75.75 0 0 1 1.06 0" clip-rule="evenodd"/> </svg>"#;
const NEXT_ICON: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"> <path fill="currentColor" fill-rule="evenodd" d="M16.47 7.47a.75.75 0 0 1 1.06 0l4 4a.75.75 0 0 1 0 1.06l-4 4a.75.75 0 1 1-1.06-1.06l2.72-2.72H3a.75.75 0 0 1 0-1.5h16.19l-2.72-2.72a.75.75 0 0 1 0-1.06" clip-rule="evenodd"/> </svg>"#;
const ORDER_ICON: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"> <path fill="currentColor" fill-rule="evenodd" d="M11.754 3.802a.75.75 0 0 1 .631-.01l7.92 3.523a.75.75 0 0 1 .021 1.36l-8.08 3.904a.75.75 0 0 1-.632.01L3.696 9.067a.75.75 0 0 1-.021-1.36zm.34 1.502-6.312 3.05 6.124 2.723 6.312-3.049zm8.581 6.56a.75.75 0 0 1-.349 1.002l-8.08 3.904a.75.75 0 0 1-.632.01l-7.919-3.523a.75.75 0 0 1 .61-1.37l7.601 3.38 7.768-3.752a.75.75 0 0 1 1.001.35m0 4.31a.75.75 0 0 1-.349 1.001l-8.08 3.904a.75.75 0 0 1-.632.01l-7.919-3.522a.75.75 0 0 1 .61-1.371l7.601 3.381 7.768-3.752a.75.75 0 0 1 1.001.349" clip-rule="evenodd"/> </svg>"#;
const STOP_ICON: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"><path fill="currentColor" fill-rule="evenodd" d="M20.5 12a8.5 8.5 0 1 1-17 0 8.5 8.5 0 0 1 17 0m1.5 0c0 5.523-4.477 10-10 10S2 17.523 2 12 6.477 2 12 2s10 4.477 10 10M10 8a2 2 0 0 0-2 2v4a2 2 0 0 0 2 2h4a2 2 0 0 0 2-2v-4a2 2 0 0 0-2-2z" clip-rule="evenodd"/></svg>"#;
+21
View File
@@ -212,6 +212,7 @@ pub struct PlaygroundView {
/// Window size of the latest frame, in logical pixels.
pub(crate) window_size: (f32, f32),
pub(crate) edgeless: edgeless::EdgelessCanvasState,
pub(crate) edgeless_presentation: edgeless::Presentation,
pub(crate) edgeless_camera_transition: Option<edgeless::CameraTransition>,
pub(crate) edgeless_shape_picker_presence: Option<edgeless::ShapePickerPresence>,
pub(crate) edgeless_element_color_picker:
@@ -397,6 +398,7 @@ impl PlaygroundView {
max_scroll: 0.0,
window_size: (0.0, 0.0),
edgeless: edgeless::EdgelessCanvasState::new(),
edgeless_presentation: edgeless::Presentation::default(),
edgeless_camera_transition: None,
edgeless_shape_picker_presence: None,
edgeless_element_color_picker: None,
@@ -537,6 +539,25 @@ impl PlaygroundView {
self.pdf_previews.get(block_id).map(|p| p.page_index)
}
pub(crate) fn reset_document_interaction(&mut self) {
self.reset_document_canvas();
self.scroll_axis_latch.reset();
self.active_touch_owner = touch_interaction::TouchStrokeOwner::None;
self.modal_touch_target = touch_interaction::ModalTouchTarget::None;
self.touch_long_press_anchor = None;
self.touch_selection_menu_open = false;
self.edgeless_readonly_selection_target = None;
self.caret_blink_task = None;
self.scrollbar_drag = None;
self.context_toast_timer = None;
self.context_paste_task = None;
self.context_menu_target = None;
self.pending_media_pick = None;
self.image_resize_drag = None;
self.keyboard_toolbar_dismissed = false;
self.ime_insets = chrome::ImeInsetsState::default();
}
pub fn edgeless_camera(&self) -> edgeless::EdgelessCamera {
self.edgeless.camera
}
@@ -636,6 +636,22 @@ impl DesktopEditorHost {
self.pane_editors.get(&pane_id).map(|m| m.entity.clone())
}
pub(crate) fn toggle_pane_presentation(
&self,
pane_id: PaneId,
doc_id: &str,
window: &mut ui::Window,
cx: &mut Context<DesktopShellView>,
) {
if let Some(mounted) = self.pane_editors.get(&pane_id)
&& mounted.doc_id == doc_id
{
mounted
.entity
.update(cx, |view, cx| view.toggle_presentation(window, cx));
}
}
/// Heading at the reading position of the Page editor of `pane_id` while it shows
/// `doc_id`. `None` means the document title, above the first heading.
pub(crate) fn active_outline_heading<'a>(
@@ -2427,6 +2443,336 @@ pub(crate) mod tests {
}
}
fn add_presentation_frames(
view: &mut playground::PlaygroundView,
cx: &mut ui::Context<playground::PlaygroundView>,
) {
view.edit_document(cx, |doc| {
let page = doc.workspace.page_mut("doc-board").unwrap();
page.add_surface_element(
"surface-board",
"shape-overview",
"a6",
blocksuite_playground_doc::schema::SurfaceElementSpec::Shape {
shape_type: "rect".into(),
xywh: "[155,380,220,66]".into(),
filled: true,
seed: 104,
text: Some("Spatial canvas".into()),
},
4_999,
)
.unwrap();
for (id, title, index, xywh, children) in [
(
"frame-intro",
"Overview",
"a0",
[0.0, 45.0, 530.0, 465.0],
&["note-board", "shape-overview"][..],
),
(
"frame-flow",
"Route flow",
"a5",
[565.0, 55.0, 340.0, 350.0],
&["shape-sidebar", "shape-workbench", "conn-flow"][..],
),
] {
page.add_frame_with_children(
Some("surface-board"),
id,
title,
index,
xywh,
children,
5_000,
)
.unwrap();
}
});
view.set_edgeless_camera(-95.0, -155.0, 0.85, cx);
}
fn save_presentation_evidence(window: &ui::Window, theme: ThemeMode, stage: &str) {
let Some(dir) = std::env::var_os("PRESENT_EVIDENCE_DIR") else {
return;
};
let dir = std::path::PathBuf::from(dir);
std::fs::create_dir_all(&dir).unwrap();
let theme = match theme {
ThemeMode::Light => "light",
ThemeMode::Dark => "dark",
};
window
.render_to_image()
.unwrap()
.save(dir.join(format!("{stage}-{theme}.png")))
.unwrap();
}
#[test]
fn presentation_header_and_controls_use_the_mounted_editor() {
const CONTROL: &str = "chrome.edgeless_toolbar.presentation";
for theme in [ThemeMode::Light, ThemeMode::Dark] {
let mut state = DesktopAppState::seed_showcase(theme, "2026-12-02");
state.open_doc_in_active_pane("doc-board");
let (platform, app, handle, window) = open_test_shell(state, 1280, 800);
let frame = || {
window.request_frame();
platform.run_until_parked();
};
frame();
app.update(|cx| {
handle
.update(cx, |shell, _, cx| {
let pane = shell.state.split.active();
let editor = shell.editor_host().pane_entity(pane.id).unwrap();
editor.update(cx, add_presentation_frames);
})
.unwrap();
});
frame();
app.update(|cx| {
handle
.update(cx, |_, window, _| {
save_presentation_evidence(window, theme, "after");
})
.unwrap();
});
let click = |id: &str| {
let position = app.update(|cx| {
handle
.update(cx, |_, window, _| {
let b = window.frame_snapshot().elements[id].bounds;
point(px(b.x + b.width / 2.0), px(b.y + b.height / 2.0))
})
.unwrap()
});
window.dispatch_input(PlatformInput::MouseDown(MouseDownEvent {
button: MouseButton::Left,
position,
modifiers: ui::Modifiers::default(),
click_count: 1,
first_mouse: false,
}));
window.dispatch_input(PlatformInput::MouseUp(MouseUpEvent {
button: MouseButton::Left,
position,
modifiers: ui::Modifiers::default(),
click_count: 1,
}));
frame();
};
let assert_progress = |count: &str| {
app.update(|cx| {
handle
.update(cx, |_, window, _| {
let elements = &window.frame_snapshot().elements;
assert_eq!(
elements[&format!("{CONTROL}.current")].text.as_deref(),
Some(count)
);
})
.unwrap();
});
};
click("desktop.topbar.present");
assert_progress("1 / 2");
app.update(|cx| {
handle
.update(cx, |_, window, _| {
save_presentation_evidence(window, theme, "present")
})
.unwrap();
});
click(&format!("{CONTROL}.order"));
click(&format!("{CONTROL}.order_menu.frame.1"));
assert_progress("2 / 2");
click(&format!("{CONTROL}.previous"));
click(&format!("{CONTROL}.settings"));
click(&format!("{CONTROL}.black"));
app.update(|cx| {
handle
.update(cx, |_, window, _| {
let image = window.render_to_image().unwrap();
let viewport = window.frame_snapshot().elements["edgeless.viewport"].bounds;
let pixel = image.get_pixel(
(viewport.x + 3.0) as u32,
(viewport.y + viewport.height / 2.0) as u32,
);
assert_eq!(pixel.0, [0, 0, 0, 255]);
save_presentation_evidence(window, theme, "present-settings");
})
.unwrap();
});
click(&format!("{CONTROL}.hide"));
click(&format!("{CONTROL}.show"));
assert_progress("1 / 2");
click(&format!("{CONTROL}.stop"));
click("chrome.edgeless_toolbar.present");
assert_progress("1 / 2");
click("desktop.topbar.present");
app.update(|cx| {
handle
.update(cx, |_, window, _| {
assert!(!window.frame_snapshot().elements.contains_key(CONTROL));
})
.unwrap();
});
}
}
#[test]
fn present_starts_from_the_toolbar_in_a_narrow_split_pane() {
use crate::split_view::DocViewMode;
use blocksuite_editor::edgeless::{EdgelessTool, EdgelessToolbarHost};
for width in [700, 768] {
for theme in [ThemeMode::Light, ThemeMode::Dark] {
let mut state = DesktopAppState::seed_showcase(theme, "2026-12-02");
state.sidebar.open = true;
state.sidebar.width = 248.0;
state.open_doc_in_active_pane("doc-arch");
state.split.active_mut().set_mode(DocViewMode::Page);
state.open_doc_in_split_with_mode("doc-board".into(), DocViewMode::Edgeless);
let left = state.split.panes[0].id;
let right = state.split.panes[1].id;
let (platform, app, handle, window) = open_test_shell(state, width, 800);
let frame = || {
window.request_frame();
platform.run_until_parked();
};
frame();
app.update(|cx| {
handle
.update(cx, |shell, _, cx| {
let editor = shell.editor_host().pane_entity(right).unwrap();
editor.update(cx, add_presentation_frames);
})
.unwrap();
});
frame();
let center = app.update(|cx| {
handle
.update(cx, |shell, window, cx| {
let elements = &window.frame_snapshot().elements;
assert!(!elements.contains_key("desktop.topbar.1.present"));
assert_eq!(elements["desktop.sidebar"].bounds.width, 248.0);
let host = shell.editor_host();
let pg = host.pane_entity(right).unwrap();
let (origin, viewport) = pg.read(cx).canvas_rect(window);
let left_pg = host.pane_entity(left).unwrap();
let (left_origin, _) = left_pg.read(cx).canvas_rect(window);
assert_eq!(f32::from(left_origin.x), 248.0);
let pane_width = f32::from(viewport.width);
assert!((220.0..=260.0).contains(&pane_width), "{pane_width}");
let pane_x = f32::from(origin.x);
assert!(pane_x > f32::from(left_origin.x));
let present = &elements["chrome.edgeless_toolbar.present"];
let bounds = present.bounds;
assert!(present.interactive);
assert_eq!((bounds.width, bounds.height), (36.0, 28.0));
assert!(bounds.x >= pane_x + 8.0, "{width}: {bounds:?}");
assert!(
bounds.x + bounds.width <= pane_x + pane_width - 8.0,
"{width}: {bounds:?}, right pane {pane_x} + {pane_width}"
);
if width == 768 {
save_presentation_evidence(window, theme, "split-after");
}
point(
px(bounds.x + bounds.width / 2.0),
px(bounds.y + bounds.height / 2.0),
)
})
.unwrap()
});
window.dispatch_input(PlatformInput::MouseDown(MouseDownEvent {
button: MouseButton::Left,
position: center,
modifiers: ui::Modifiers::default(),
click_count: 1,
first_mouse: false,
}));
window.dispatch_input(PlatformInput::MouseUp(MouseUpEvent {
button: MouseButton::Left,
position: center,
modifiers: ui::Modifiers::default(),
click_count: 1,
}));
frame();
app.update(|cx| {
handle
.update(cx, |shell, window, cx| {
let host = shell.editor_host();
for (pane, tool) in
[(left, EdgelessTool::Select), (right, EdgelessTool::Present)]
{
let pg = host.pane_entity(pane).unwrap();
assert_eq!(pg.read(cx).edgeless_active_tool(), tool);
}
if width == 768 {
save_presentation_evidence(window, theme, "split-present");
}
})
.unwrap();
});
}
}
}
#[test]
fn escape_stops_presentation_before_closing_center_peek() {
let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02");
state.open_doc_in_active_pane("doc-arch");
state.open_peek_view("doc-board");
let (platform, app, handle, window) = open_test_shell(state, 1280, 800);
window.request_frame();
platform.run_until_parked();
app.update(|cx| {
handle
.update(cx, |shell, window, cx| {
let editor = shell.editor_host().peek_entity().unwrap();
editor.update(cx, |view, cx| view.toggle_presentation(window, cx));
})
.unwrap();
});
const TOOLBAR: &str = "chrome.edgeless_toolbar.presentation.current";
window.request_frame();
platform.run_until_parked();
app.update(|cx| {
handle
.update(cx, |_, window, _| {
assert_eq!(
window.frame_snapshot().elements[TOOLBAR].text.as_deref(),
Some("0 / 0")
);
})
.unwrap();
});
for stays_open in [true, false] {
app.update(|cx| {
ui::AnyWindowHandle::from(handle)
.update(cx, |_, window, cx| {
window.dispatch_keystroke(ui::Keystroke::parse("escape").unwrap(), cx);
})
.unwrap();
});
window.request_frame();
platform.run_until_parked();
app.update(|cx| {
handle
.update(cx, |shell, window, _| {
assert_eq!(shell.state.peek_view.is_open(), stays_open);
assert!(!window.frame_snapshot().elements.contains_key(TOOLBAR));
})
.unwrap();
});
}
}
#[test]
fn escape_dismisses_peek_shape_picker_before_restoring_source_focus() {
use std::time::Duration;
@@ -523,6 +523,39 @@ pub(super) fn render_detail_header(
if !journal && !hide_share {
header = header.child(share_button(id("share"), target.clone(), palette, cx));
}
if !journal && !entry.meta.trashed && mode == DocViewMode::Edgeless && width >= 400.0 {
let present_target = target.clone();
let present_id = if index == 0 {
id("present")
} else {
format!("desktop.topbar.{index}.present").into()
};
header = header.child(
button(
present_id,
false,
palette,
cx.listener(move |this, _, window, cx| {
if present_target.activate(this) {
this.editor_host.toggle_pane_presentation(
present_target.pane,
&present_target.doc,
window,
cx,
);
cx.notify();
}
}),
)
.size(px(24.0))
.child(
svg()
.data(playground::edgeless::PRESENTATION_ICON)
.size(px(24.0))
.text_color(palette.text_secondary),
),
);
}
let menu_target = target.clone();
let controls_from_more = u8::from(show_doc_actions) + u8::from(last) + u8::from(split_visible);
let menu_offset = f32::from(controls_from_more) * control_width
@@ -623,7 +656,7 @@ mod tests {
0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b)
}
struct TestHeader(Entity<DesktopShellView>);
struct TestHeader(Entity<DesktopShellView>, f32);
impl Render for TestHeader {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
@@ -635,8 +668,8 @@ mod tests {
first: true,
last: true,
split_visible: false,
width: 640.0,
right: 640.0,
width: self.1,
right: self.1,
bottom: HEADER_HEIGHT,
},
crate::palette_for(ThemeMode::Light),
@@ -646,14 +679,14 @@ mod tests {
}
}
fn render_header(state: DesktopAppState) -> ui::FrameSnapshot {
let platform = HeadlessPlatform::new(640, 80, 1.0);
fn render_header(state: DesktopAppState, width: u32) -> ui::FrameSnapshot {
let platform = HeadlessPlatform::new(width, 80, 1.0);
let app = Application::with_platform(platform.clone()).run_embedded(|_| {});
let header = app.update(|cx| {
register_desktop_fonts(cx).unwrap();
cx.open_window(WindowOptions::default(), |_, cx| {
let shell = cx.new(|cx| DesktopShellView::new(state, cx));
cx.new(|_| TestHeader(shell))
cx.new(|_| TestHeader(shell, width as f32))
})
.unwrap()
});
@@ -666,14 +699,31 @@ mod tests {
}
#[test]
fn edgeless_header_keeps_mode_controls_without_the_fullscreen_button() {
let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02");
state.navigate_active_pane(DesktopRoute::Doc("doc-board".into()));
assert_eq!(state.split.active().active_mode(), DocViewMode::Edgeless);
let frame = render_header(state);
assert!(frame.elements.contains_key("desktop.topbar.mode.edgeless"));
assert!(frame.elements.contains_key("desktop.topbar.more"));
assert!(!frame.elements.contains_key("desktop.topbar.present"));
fn present_requires_edgeless_and_at_least_400_pixels_in_the_pane() {
for (mode, width, trashed, visible) in [
(DocViewMode::Page, 1280, false, false),
(DocViewMode::Edgeless, 399, false, false),
(DocViewMode::Edgeless, 400, false, true),
(DocViewMode::Edgeless, 1280, false, true),
(DocViewMode::Edgeless, 1280, true, false),
] {
let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02");
state.navigate_active_pane(DesktopRoute::Doc("doc-board".into()));
state.split.active_mut().set_mode(mode);
if trashed {
assert!(state.store.trash_doc("doc-board", 1_000));
}
let frame = render_header(state, width);
assert_eq!(
frame.elements.contains_key("desktop.topbar.present"),
visible
);
if visible {
let present = &frame.elements["desktop.topbar.present"];
assert_eq!((present.bounds.width, present.bounds.height), (24.0, 24.0));
assert!(present.interactive);
}
}
}
#[test]
@@ -681,7 +731,7 @@ mod tests {
let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02");
state.navigate_active_pane(DesktopRoute::Doc("doc-journal-today".into()));
assert!(state.store.trash_doc("doc-journal-today", 1_000));
let frame = render_header(state);
let frame = render_header(state, 640);
assert!(frame.elements.contains_key("desktop.topbar.doc_info"));
assert!(!frame.elements.contains_key("desktop.topbar.journal_week"));
assert!(!frame.elements.contains_key("desktop.topbar.today"));