feat(edgeless): align element toolbar chrome, note style panel, media actions, and quick-connect preview

This commit is contained in:
DarkSky committed 2026-12-01 19:13:16 +09:00
1 parent 2144304032
commit 69cc024e71
53 files changed
+9020 -2464

No files matched your search

+2 -1
View File
@@ -57,7 +57,8 @@ These crates belong to the client Cargo workspace rooted at `packages/frontend/C
### Edgeless spatial canvas and interactive authoring
- **Spatial camera & canvas (`edgeless/`)**: `edgeless/camera.rs` (`EdgelessCamera`) manages pan/zoom (`[0.1, 6.0]`), cursor-anchored wheel zoom, and fit-to-bounds (initialized before building `chrome.edgeless_zoom` so Frame 1 displays the fitted zoom percentage). Clicking zoom bar buttons (`-` / `100%` / `+` / `Fit`, firing on pointer release with additive `±0.25` zoom steps and `>= 44 pt` touch targets on touch form factors) runs a closed-form 170 ms ease-out `CameraTransition` anchored on the world viewport center with smooth mid-flight retargeting (cancelled immediately by wheel, pinch, pan, or direct camera updates), and `chrome.edgeless_toolbar.shape_picker` opens and closes with a 230 ms ease-out slide-out (`12px -> 0px`) and fade (`ShapePickerPresence`, interactive from Frame 1). `edgeless/scene.rs` and `edgeless/canvas_paint.rs` prepare and render Surface-parented Frames and EdgelessText and root-parented Notes in a single snapshot pass. Note dimensions are world units. Layout uses the logical width divided by scale. Collapsed notes clip to the stored world height, which already includes scale. The canvas merges the block and vector paint streams by fractional index and Frame/Group ancestry (`prop:childElementIds` treats every present key as a frame member, and equal indices preserve source enumeration order within each stream — live incremental sync and independent multi-author merged updates follow `(Reverse(client), clock)` integration order, whereas a late-join single V1 snapshot with cross-client causal edits among equal-index overlapping elements can invert their tie-break paint/pick order until `y-octo` exposes per-map integration order). Equal indices continue the active stream, with blocks first at the start. Notes reuse their cached `BlockFlow::layout_nodes` during pan/zoom. All items paint under `edgeless.viewport`, with bottom-centered creation toolbar (`chrome.edgeless_toolbar`), logical bottom-start screen-space zoom controls (`chrome.edgeless_zoom`: `[FitIcon] [−] [100%] [+]`, mirrored in RTL and stacked cleanly above `chrome.edgeless_toolbar` on narrow viewports `< 660 px`), and floating selection property bar (`edgeless.element_toolbar` for Note, Shape, Connector, Brush, Highlighter, SurfaceText, EdgelessText, Frame, and Group styling). `bs-harness render --mode edgeless [--zoom <f32>] [--pan <x>,<y>]` renders spatial states, `bs-harness audit-states` audits Edgeless default + `0.5x` + `2.0x` + authoring states (`edgeless_selected`, `edgeless_marquee`, `edgeless_inline_edit`, `edgeless_authoring`) in Light/Dark at `1280` and `320` px, and `bs-harness bench` measures `edgeless_1k_pan_zoom_frame_ms` and asserts `edgeless_1k_pan_zoom_blocks_relayout == 0`.
- **Edgeless interactive authoring & inline IME editing (`edgeless/{toolbar,hit_test,overlay,label_editor,inline_edit,gestures,commit,commands}.rs`)**: `chrome.edgeless_toolbar` provides Select (`V`/`Escape`), Hand (`H` or holding `Space`), Note (`N`), Shape (`S` with rect/ellipse/diamond/triangle/rounded-rect picker), Connector (`C` with cardinal port snapping and live connector preview), Brush (`P`), Highlighter, Text (`T`), and Frame (`F`, populating `prop:childElementIds`). World-space hit-testing walks exact reverse paint order (inverse-rotated OBBs for shapes/texts, routed polyline distance from `SurfaceLayout` for connectors/strokes, exact `layout_inline` title pill and border for frames). Selection renders a screen-crisp `edgeless.selection_box`, 8 resize handles (`edgeless.handle.nw..w`), top rotation handle (`edgeless.handle.rotate`, `15°` snap with `Shift`), and `2×3` 6-dot `14px` Edgeless `gfx` drag handle (`edgeless.drag_handle`) on selected blocks; resize and rotation handles are suppressed while inline label editing is active, and the underlying static label is hidden until commit. Dragging, resizing, rotating, deleting (`Backspace`/`Delete`), and z-reordering (`[`/`]` via `fractional-indexing@3.2.0` keys in `blocksuite/blocksuite/crates/doc/src/fractional_index.rs`) commit single atomic undo steps on `PageDocSession` and broadcast over `RoomProtocol`. Double-clicking a Note or EdgelessText edits rich text inline via `EditorSession` + `EntityInputHandler` with camera-mapped `bounds_for_range`; double-clicking a Shape, Connector, SurfaceText, or Frame title edits its `Y.Text` inline (`edgeless.inline_edit`) with full UTF-16 + IME preedit support (clicking inside an active inline label commits any in-flight composition via `unmark` into its original replacement range before placing the caret, while body `change_selection` clears in-flight composition on click).
- **Edgeless interactive authoring & inline IME editing (`edgeless/{toolbar,hit_test,overlay,label_editor,inline_edit,gestures,commit,commands}.rs`)**: `chrome.edgeless_toolbar` provides Select (`V`/`Escape`), Hand (`H` or holding `Space`), Note (`N`), Shape (`S` with rect/ellipse/diamond/triangle/rounded-rect picker), Connector (`C` with cardinal port snapping and live connector preview), Brush (`P`), Highlighter, Text (`T`), and Frame (`F`, populating `prop:childElementIds`). World-space hit-testing walks exact reverse paint order (inverse-rotated OBBs for shapes/texts, routed polyline distance from `SurfaceLayout` for connectors/strokes, exact `layout_inline` title pill and border for frames). Selection renders a screen-crisp `edgeless.selection_box`, 8 resize handles (`edgeless.handle.nw..w`), four `12px` outer-corner rotation hit zones (`edgeless.handle.rotate`, `rotate_nw`, `rotate_se`, `rotate_sw`, `15°` snap with `Shift`), and `2×3` 6-dot `14px` Edgeless `gfx` drag handle (`edgeless.drag_handle`) on selected blocks; resize and rotation handles are suppressed while inline label editing is active, and the underlying static label is hidden until commit. Dragging, resizing, rotating, deleting (`Backspace`/`Delete`), and z-reordering (`[`/`]` via `fractional-indexing@3.2.0` keys in `blocksuite/blocksuite/crates/doc/src/fractional_index.rs`) commit single atomic undo steps on `PageDocSession` and broadcast over `RoomProtocol`. Double-clicking a Note or EdgelessText edits rich text inline via `EditorSession` + `EntityInputHandler` with camera-mapped `bounds_for_range`; double-clicking a Shape, Connector, SurfaceText, or Frame title edits its `Y.Text` inline (`edgeless.inline_edit`) with full UTF-16 + IME preedit support (clicking inside an active inline label commits any in-flight composition via `unmark` into its original replacement range before placing the caret, while body `change_selection` clears in-flight composition on click).
- **Canvas media blocks (`edgeless/canvas.rs`, `playground/src/overlays/view_caption_paint.rs`, `playground/src/edgeless/element_toolbar_media_actions.rs`)**: Image, bookmark, attachment, and embed blocks on the canvas paint their content top-aligned and clipped to `prop:xywh`, and their caption below that frame (`canvas_caption_shift`). An edited canvas caption draws `edgeless.caption_focus` and `edgeless.caption_caret`, takes every key before the canvas shortcuts, places the caret on a press inside its slot, and closes on `Enter`, `Escape`, a press outside it, a mode switch, or the deletion of its block. A card `Style` change and a `Card` / `Embed` view switch write the BlockSuite standard frame (`embed_card_size`) with the new style or block in one undo step, and the selection follows a replaced block. Z-order actions on a selection that already ends its paint stream (blocks or canvas elements) write nothing. Quick-connect clones step around shapes, notes, blocks, and brush or highlighter strokes. Downloads reach the host only through `set_on_media_download`; the view keeps no copy of the bytes.
### Surface reading and painting
+22 -47
View File
@@ -105,7 +105,7 @@ impl PageDocSession {
&& matches!(
v,
SessionValue::Any(Any::String(f))
if f == "affine:frame" || f == "affine:edgeless-text"
if is_surface_parented_flavour(f)
)
})
});
@@ -154,7 +154,7 @@ impl PageDocSession {
&& matches!(
v,
SessionValue::Any(Any::String(f))
if f == "affine:frame" || f == "affine:edgeless-text"
if is_surface_parented_flavour(f)
)
});
let note_id = write_pasted_block_subtree(page, &blocks_target, note)?;
@@ -737,49 +737,24 @@ impl PageDocSession {
Ok(())
})
}
/// Update `prop:xywh` on a spatial block (`affine:note`, `affine:frame`, `affine:edgeless-text`).
pub fn set_block_xywh(
&mut self,
block_id: &str,
xywh: [f64; 4],
now_ms: u64,
) -> DocResult<PageCommit> {
self.set_block_prop(
block_id,
"prop:xywh",
SessionValue::Any(Any::String(Self::format_xywh(xywh))),
now_ms,
)
}
/// Update `prop:index` on a spatial block.
pub fn set_block_index(
&mut self,
block_id: &str,
index: &str,
now_ms: u64,
) -> DocResult<PageCommit> {
self.set_block_prop(
block_id,
"prop:index",
SessionValue::Any(Any::String(index.to_string())),
now_ms,
)
}
/// Update `prop:rotate` on a spatial block (e.g. `affine:edgeless-text`).
pub fn set_block_rotate(
&mut self,
block_id: &str,
rotate: f64,
now_ms: u64,
) -> DocResult<PageCommit> {
self.set_block_prop(
block_id,
"prop:rotate",
SessionValue::Any(Any::Float64(rotate.into())),
now_ms,
)
}
}
fn is_surface_parented_flavour(flavour: &str) -> bool {
matches!(
flavour,
"affine:frame"
| "affine:edgeless-text"
| "affine:image"
| "affine:attachment"
| "affine:bookmark"
| "affine:embed-linked-doc"
| "affine:embed-synced-doc"
| "affine:embed-youtube"
| "affine:embed-figma"
| "affine:embed-github"
| "affine:embed-loom"
| "affine:embed-iframe"
| "affine:embed-html"
| "affine:embed-web"
)
}
@@ -476,4 +476,155 @@ impl PageDocSession {
}
Ok(())
}
/// Update `prop:xywh` on a spatial block (`affine:note`, `affine:frame`, `affine:edgeless-text`,
/// or canvas media/embed blocks).
pub fn set_block_xywh(
&mut self,
block_id: &str,
xywh: [f64; 4],
now_ms: u64,
) -> DocResult<PageCommit> {
self.set_block_prop(
block_id,
"prop:xywh",
SessionValue::Any(Any::String(Self::format_xywh(xywh))),
now_ms,
)
}
/// Update `prop:index` on a spatial block.
pub fn set_block_index(
&mut self,
block_id: &str,
index: &str,
now_ms: u64,
) -> DocResult<PageCommit> {
self.set_block_prop(
block_id,
"prop:index",
SessionValue::Any(Any::String(index.to_string())),
now_ms,
)
}
/// Update `prop:rotate` on a spatial block (e.g. `affine:edgeless-text` or canvas image).
pub fn set_block_rotate(
&mut self,
block_id: &str,
rotate: f64,
now_ms: u64,
) -> DocResult<PageCommit> {
self.set_block_prop(
block_id,
"prop:rotate",
SessionValue::Any(Any::Float64(rotate.into())),
now_ms,
)
}
/// Write a nested property inside `affine:note`'s `prop:edgeless` `Y.Map` (or its child `style`
/// `Y.Map`), upgrading legacy `Any::Object` containers to `Y.Map` and removing any flat dotted
/// key (`prop:edgeless.<path>`) so BlockSuite JS `0.27.5` `notes[i].props.edgeless` reads it.
pub fn set_note_edgeless_prop(
&mut self,
block_id: &str,
path: &[&str],
value: SessionValue,
now_ms: u64,
) -> DocResult<()> {
if path.is_empty() || path.len() > 2 {
return Ok(());
}
self.advance_time(now_ms);
let block_target = TypeTarget::Path(TypePath::root("blocks").key(block_id));
let edgeless_target = match self.session.get_map_value(&block_target, "prop:edgeless")? {
Some(SessionReadValue::Map(map_id)) => TypeTarget::Identity(map_id),
Some(SessionReadValue::Any(Any::Object(obj))) => {
let entries = any_object_to_nested_map_entries(*obj);
self.session.map_set(
&block_target,
"prop:edgeless".into(),
SessionValue::Map(entries),
)?;
TypeTarget::Path(TypePath::root("blocks").key(block_id).key("prop:edgeless"))
}
_ => {
self.session.map_set(
&block_target,
"prop:edgeless".into(),
SessionValue::Map(Vec::new()),
)?;
TypeTarget::Path(TypePath::root("blocks").key(block_id).key("prop:edgeless"))
}
};
if path.len() == 1 {
let key = path[0];
self.session.map_set(&edgeless_target, key.into(), value)?;
let flat_key = format!("prop:edgeless.{key}");
if self
.session
.get_map_value(&block_target, &flat_key)?
.is_some()
{
let _ = self.session.map_remove(&block_target, &flat_key);
}
return Ok(());
}
let sub = path[0];
let leaf = path[1];
let sub_target = match self.session.get_map_value(&edgeless_target, sub)? {
Some(SessionReadValue::Map(map_id)) => TypeTarget::Identity(map_id),
Some(SessionReadValue::Any(Any::Object(obj))) => {
let entries = any_object_to_nested_map_entries(*obj);
self.session
.map_set(&edgeless_target, sub.into(), SessionValue::Map(entries))?;
TypeTarget::Path(
TypePath::root("blocks")
.key(block_id)
.key("prop:edgeless")
.key(sub),
)
}
_ => {
self.session.map_set(
&edgeless_target,
sub.into(),
SessionValue::Map(Vec::new()),
)?;
TypeTarget::Path(
TypePath::root("blocks")
.key(block_id)
.key("prop:edgeless")
.key(sub),
)
}
};
self.session.map_set(&sub_target, leaf.into(), value)?;
let flat_key = format!("prop:edgeless.{sub}.{leaf}");
if self
.session
.get_map_value(&block_target, &flat_key)?
.is_some()
{
let _ = self.session.map_remove(&block_target, &flat_key);
}
Ok(())
}
}
fn any_object_to_nested_map_entries(
obj: y_octo::AHashMap<String, Any>,
) -> Vec<(String, SessionValue)> {
obj.into_iter()
.map(|(k, v)| match v {
Any::Object(inner) => (
k,
SessionValue::Map(any_object_to_nested_map_entries(*inner)),
),
other => (k, SessionValue::Any(other)),
})
.collect()
}
@@ -255,7 +255,7 @@ impl FlowPass<'_> {
let w = body.width.max(1.0);
let style = InlineStyle::new(FONT_SANS, TYPOGRAPHY.font_sm_px, 400.0, color);
let layout = self.plain_inline(text, style, w, 22.0, InlineAlign::Center);
let y = body.height + 4.0;
let y = body.height + CAPTION_GAP;
let slot_h = layout.height().max(22.0);
body.height = y + slot_h;
body.caption_slot = Some(super::CaptionSlot {
@@ -640,142 +640,6 @@ impl FlowPass<'_> {
self.push_caption(block_id, &mut body, caption);
body
}
#[allow(clippy::too_many_arguments)]
pub(super) fn bookmark_body(
&mut self,
block_id: &str,
url: &str,
title: Option<&str>,
description: Option<&str>,
card_style: Option<&str>,
caption: &str,
width: f32,
) -> BlockBody {
let style_kind = card_style.unwrap_or("horizontal");
let (card_w, card_h) = match style_kind {
"list" => (width, 48.0),
"vertical" => (width.min(360.0), 152.0),
"cube" => (width.min(168.0), 148.0),
_ => (width, BOOKMARK_HEIGHT),
};
// 1px border plus the content's 12px padding.
let pad = 13.0;
let inner = (card_w - 2.0 * pad).max(1.0);
let host = host_name(url);
let title = title.filter(|title| !title.is_empty()).unwrap_or(host);
// Without a fetched description the card falls back to the address itself.
let description = description
.filter(|description| !description.is_empty())
.unwrap_or(url);
let mut prims = vec![Prim::Quad {
rect: FlowRect::new(0.0, 0.0, card_w, card_h),
fill: Some(self.palette.background),
border: Some(self.palette.card_border),
radius: 8.0,
dashed: false,
}];
// Title row: 16px link icon centered on the 22px title line.
let title_style = InlineStyle::new(
FONT_SANS,
TYPOGRAPHY.font_sm_px,
600.0,
self.palette.text_primary,
);
let title_x = pad + 16.0 + 8.0;
let title_width = (card_w - title_x - pad).max(1.0);
let title_text = truncate_to_width(self.window, title, &title_style, title_width)
.text
.to_string();
prims.push(Prim::Icon {
rect: FlowRect::new(pad, pad + 3.0, 16.0, 16.0),
icon: IconPaint::named("LinkIcon"),
color: self.palette.icon,
});
prims.push(Prim::Text {
x: title_x,
y: pad,
layout: self.plain_inline(
&title_text,
title_style,
title_width,
22.0,
InlineAlign::Left,
),
clip: None,
});
if style_kind != "list" {
// Description: at most two 20px lines.
let description_style = InlineStyle::new(
FONT_SANS,
TYPOGRAPHY.font_xs_px,
400.0,
self.palette.text_primary,
);
let description_y = pad + 22.0 + 4.0;
prims.push(Prim::Text {
x: pad,
y: description_y,
layout: self.plain_inline(
description,
description_style,
inner,
20.0,
InlineAlign::Left,
),
clip: Some(FlowRect::new(pad, description_y, inner, 40.0)),
});
// Address row pinned to the bottom padding edge.
let url_style = InlineStyle::new(
FONT_SANS,
TYPOGRAPHY.font_xs_px,
400.0,
self.palette.text_secondary,
);
let url_text = truncate_to_width(self.window, host, &url_style, inner)
.text
.to_string();
prims.push(Prim::Text {
x: pad,
y: card_h - pad - 20.0,
layout: self.plain_inline(&url_text, url_style, inner, 20.0, InlineAlign::Left),
clip: None,
});
}
let mut body = BlockBody {
kind: FlowKind::Bookmark,
width,
height: card_h,
margin_top: CARD_BLOCK_MARGIN,
margin_bottom: CARD_BLOCK_MARGIN,
plain: title.to_string(),
prims,
text: None,
prefix: None,
code_scroll: None,
pdf_controls: None,
table_cells: Vec::new(),
caption_slot: None,
};
self.push_caption(block_id, &mut body, caption);
body
}
}
/// Host of a URL without scheme, credentials, port or path; the input itself if it has none.
pub(super) fn host_name(url: &str) -> &str {
let rest = url.split_once("://").map_or(url, |(_, rest)| rest);
let authority = rest.split(['/', '?', '#']).next().unwrap_or(rest);
let host = authority
.rsplit_once('@')
.map_or(authority, |(_, host)| host);
let host = host.split(':').next().unwrap_or(host);
if host.is_empty() { url } else { host }
}
#[cfg(test)]
@@ -354,6 +354,43 @@ impl BlockBody {
self.paint_prims(origin, state, window, cx);
}
/// Paint everything but the caption slot, so a canvas block can clip its content to its
/// frame and place the caption with [`Self::paint_caption`].
pub(crate) fn paint_content(
&self,
origin: Point<Pixels>,
state: BlockPaint,
window: &mut Window,
cx: &mut App,
) {
let content = self.prims.len() - usize::from(self.caption_slot.is_some());
for prim in &self.prims[..content] {
self.paint_single_prim(prim, origin, state, window, cx);
}
}
/// Paint only the caption slot text (the last prim `push_caption` adds).
pub(crate) fn paint_caption(
&self,
origin: Point<Pixels>,
state: BlockPaint,
window: &mut Window,
cx: &mut App,
) {
if self.caption_slot.is_some()
&& let Some(prim) = self.prims.last()
{
self.paint_single_prim(prim, origin, state, window, cx);
}
}
/// Height of the block content above its caption slot.
pub fn content_height(&self) -> f32 {
self.caption_slot
.as_ref()
.map_or(self.height, |slot| slot.rect.y - CAPTION_GAP)
}
fn paint_prims(
&self,
origin: Point<Pixels>,
@@ -0,0 +1,143 @@
//! Bookmark card bodies and the host-name helper their address rows use.
use crate::theme::{FONT_SANS, IconPaint, TYPOGRAPHY};
use super::*;
impl FlowPass<'_> {
#[allow(clippy::too_many_arguments)]
pub(super) fn bookmark_body(
&mut self,
block_id: &str,
url: &str,
title: Option<&str>,
description: Option<&str>,
card_style: Option<&str>,
caption: &str,
width: f32,
) -> BlockBody {
let style_kind = card_style.unwrap_or("horizontal");
// Horizontal and list cards span the block; vertical and cube cards keep their own width.
let (card_w, card_h) = match embed_card_size(style_kind) {
Some((w, h)) if matches!(style_kind, "vertical" | "cube") => (width.min(w), h),
Some((_, h)) if style_kind == "list" => (width, h),
_ => (width, BOOKMARK_HEIGHT),
};
// 1px border plus the content's 12px padding.
let pad = 13.0;
let inner = (card_w - 2.0 * pad).max(1.0);
let host = host_name(url);
let title = title.filter(|title| !title.is_empty()).unwrap_or(host);
// Without a fetched description the card falls back to the address itself.
let description = description
.filter(|description| !description.is_empty())
.unwrap_or(url);
let mut prims = vec![Prim::Quad {
rect: FlowRect::new(0.0, 0.0, card_w, card_h),
fill: Some(self.palette.background),
border: Some(self.palette.card_border),
radius: 8.0,
dashed: false,
}];
// Title row: 16px link icon centered on the 22px title line.
let title_style = InlineStyle::new(
FONT_SANS,
TYPOGRAPHY.font_sm_px,
600.0,
self.palette.text_primary,
);
let title_x = pad + 16.0 + 8.0;
let title_width = (card_w - title_x - pad).max(1.0);
let title_text = truncate_to_width(self.window, title, &title_style, title_width)
.text
.to_string();
prims.push(Prim::Icon {
rect: FlowRect::new(pad, pad + 3.0, 16.0, 16.0),
icon: IconPaint::named("LinkIcon"),
color: self.palette.icon,
});
prims.push(Prim::Text {
x: title_x,
y: pad,
layout: self.plain_inline(
&title_text,
title_style,
title_width,
22.0,
InlineAlign::Left,
),
clip: None,
});
if style_kind != "list" {
// Description: at most two 20px lines.
let description_style = InlineStyle::new(
FONT_SANS,
TYPOGRAPHY.font_xs_px,
400.0,
self.palette.text_primary,
);
let description_y = pad + 22.0 + 4.0;
prims.push(Prim::Text {
x: pad,
y: description_y,
layout: self.plain_inline(
description,
description_style,
inner,
20.0,
InlineAlign::Left,
),
clip: Some(FlowRect::new(pad, description_y, inner, 40.0)),
});
// Address row pinned to the bottom padding edge.
let url_style = InlineStyle::new(
FONT_SANS,
TYPOGRAPHY.font_xs_px,
400.0,
self.palette.text_secondary,
);
let url_text = truncate_to_width(self.window, host, &url_style, inner)
.text
.to_string();
prims.push(Prim::Text {
x: pad,
y: card_h - pad - 20.0,
layout: self.plain_inline(&url_text, url_style, inner, 20.0, InlineAlign::Left),
clip: None,
});
}
let mut body = BlockBody {
kind: FlowKind::Bookmark,
width,
height: card_h,
margin_top: CARD_BLOCK_MARGIN,
margin_bottom: CARD_BLOCK_MARGIN,
plain: title.to_string(),
prims,
text: None,
prefix: None,
code_scroll: None,
pdf_controls: None,
table_cells: Vec::new(),
caption_slot: None,
};
self.push_caption(block_id, &mut body, caption);
body
}
}
/// Host of a URL without scheme, credentials, port or path; the input itself if it has none.
pub(super) fn host_name(url: &str) -> &str {
let rest = url.split_once("://").map_or(url, |(_, rest)| rest);
let authority = rest.split(['/', '?', '#']).next().unwrap_or(rest);
let host = authority
.rsplit_once('@')
.map_or(authority, |(_, host)| host);
let host = host.split(':').next().unwrap_or(host);
if host.is_empty() { url } else { host }
}
@@ -431,7 +431,7 @@ impl FlowPass<'_> {
ExternalEmbedKind::Html => ui::rgb(0xf97316).into(),
ExternalEmbedKind::Iframe | ExternalEmbedKind::Web => self.palette.brand,
};
let host = super::blocks::host_name(url);
let host = super::bookmark_block::host_name(url);
let display_title = title
.map(str::trim)
.filter(|s| !s.is_empty())
+19 -1
View File
@@ -14,6 +14,7 @@
mod attachment_block;
mod blocks;
mod body;
mod bookmark_block;
mod code_preview;
mod embed_blocks;
mod inline;
@@ -114,6 +115,23 @@ pub const TEXT_BLOCK_MARGIN: f32 = 10.0;
pub const CARD_BLOCK_MARGIN: f32 = 18.0;
/// Height of a horizontal bookmark card.
pub const BOOKMARK_HEIGHT: f32 = 116.0;
/// Canvas size `(width, height)` of an embed card by its `prop:style`, as BlockSuite's
/// `EMBED_CARD_WIDTH` / `EMBED_CARD_HEIGHT` define it.
pub fn embed_card_size(style: &str) -> Option<(f32, f32)> {
Some(match style {
"horizontal" => (752.0, BOOKMARK_HEIGHT),
"list" => (752.0, 46.0),
"vertical" => (364.0, 390.0),
"cube" => (170.0, 114.0),
"cubeThick" => (170.0, 132.0),
"video" | "figma" | "html" => (752.0, 544.0),
"syncedDoc" => (800.0, 792.0),
_ => return None,
})
}
/// Gap between a captioned block's content and its caption slot.
pub const CAPTION_GAP: f32 = 4.0;
/// Height of the divider block container.
pub const DIVIDER_HEIGHT: f32 = 36.0;
/// Vertical and horizontal padding of the code block container.
@@ -479,7 +497,7 @@ pub(super) fn node_has_gutter_chevron(
#[cfg(test)]
mod tests {
use super::{blocks::host_name, inline::inline_segments, *};
use super::{bookmark_block::host_name, inline::inline_segments, *};
#[test]
fn number_prefix_cycles_numbers_letters_and_roman_numerals() {
@@ -10,7 +10,9 @@ use serde_json::Value as JsonValue;
use ui::{BorderStyle, Bounds, Hsla, Pixels, Point, Size, point, px};
use crate::{
block_flow::{BlockFlow, FlowLayout, ImageSlot, InlineLayout},
block_flow::{
BlockFlow, CAPTION_GAP, CaptionDraft, FlowBlock, FlowLayout, ImageSlot, InlineLayout,
},
editor_session::{DocPoint, DocumentSelection},
surface::{SurfaceLayout, WorldBounds},
theme::{Palette, PlaygroundTheme},
@@ -118,6 +120,8 @@ pub struct EdgelessCanvasState {
pub(super) note_flows: HashMap<String, CachedNoteFlow>,
pub(super) text_flows: HashMap<String, CachedNoteFlow>,
pub(super) surface_block_flows: HashMap<String, CachedNoteFlow>,
/// Caption being edited in place, laid out into the canvas block it belongs to.
pub caption_draft: Option<CaptionDraft>,
/// Number of block bodies laid out during the most recent Edgeless frame.
pub last_frame_relayouts: u64,
}
@@ -126,6 +130,8 @@ pub(super) fn is_spatial_surface_block(node: &BlockNode) -> bool {
matches!(
&node.content,
BlockContent::Image { .. }
| BlockContent::Attachment { .. }
| BlockContent::Bookmark { .. }
| BlockContent::EmbedLinkedDoc { .. }
| BlockContent::EmbedSyncedDoc { .. }
| BlockContent::ExternalEmbed { .. }
@@ -199,6 +205,12 @@ pub fn note_collapse(node: &BlockNode) -> bool {
.unwrap_or(false)
}
pub fn note_collapsed_height(node: &BlockNode) -> Option<f64> {
edgeless_prop(node, "prop:edgeless.collapsedHeight", &["collapsedHeight"])
.and_then(JsonValue::as_f64)
.filter(|v| v.is_finite() && *v > 0.0)
}
pub fn note_border_style(node: &BlockNode) -> Option<(BorderStyle, f32)> {
let style = edgeless_prop(
node,
@@ -283,6 +295,13 @@ impl EdgelessCanvasState {
}
}
/// Cached flow of a canvas media block (`image`, bookmark, attachment, or embed card).
pub fn cached_surface_block_layout(&self, block_id: &str) -> Option<Rc<FlowLayout>> {
self.surface_block_flows
.get(block_id)
.map(|c| c.layout.clone())
}
pub fn set_zoom_centered(
&mut self,
zoom: f32,
@@ -464,6 +483,14 @@ pub(super) struct PaintSurfaceBlock {
pub(super) layout: Rc<FlowLayout>,
}
/// Unscaled vertical shift that moves `block`'s caption slot from its flow position to
/// [`CAPTION_GAP`] below a canvas frame `frame_h` world px tall at `scale`, where BlockSuite
/// draws the caption of a canvas block.
pub fn canvas_caption_shift(block: &FlowBlock, frame_h: f32, scale: f32) -> Option<f32> {
let slot = block.body.caption_slot.as_ref()?;
Some(frame_h / scale + CAPTION_GAP - block.y - slot.rect.y)
}
pub(super) fn prepare_surface_block(
state: &mut EdgelessCanvasState,
child: &BlockNode,
@@ -513,6 +540,10 @@ pub(super) fn prepare_surface_block(
utc_offset_minutes: input.utc_offset_minutes,
utc_offset_at: input.utc_offset_at,
};
let draft = state
.caption_draft
.clone()
.filter(|d| d.block_id == child.id);
let entry = state
.surface_block_flows
.entry(child.id.clone())
@@ -538,6 +569,7 @@ pub(super) fn prepare_surface_block(
stats: Default::default(),
}),
});
entry.flow.caption_draft = draft;
let laid_out =
entry
.flow
@@ -549,6 +581,12 @@ pub(super) fn prepare_surface_block(
rc
}
};
// Content taller than the frame grows it; the caption stays outside, below the frame.
if !matches!(child.content, BlockContent::Image { .. })
&& let Some(block) = layout.blocks.first()
{
rect.h = rect.h.max(block.body.content_height() * scale);
}
let index = child
.props
.get("prop:index")
@@ -545,13 +545,10 @@ pub fn build_edgeless_layer_prepared(
bounds: clip_bounds,
},
|window| {
// The frame holds the content alone, top-aligned.
for block in &sb.layout.blocks {
let origin = point(
px(sb.rect.x + block.x),
px(sb.rect.y + block.y),
);
block.body.paint(
origin,
block.body.paint_content(
point(px(sb.rect.x + block.x), px(sb.rect.y)),
BlockPaint::default(),
window,
cx,
@@ -559,6 +556,22 @@ pub fn build_edgeless_layer_prepared(
}
},
);
for block in &sb.layout.blocks {
let Some(dy) =
super::canvas_caption_shift(block, sb.rect.h, sb.scale)
else {
continue;
};
block.body.paint_caption(
point(
px(sb.rect.x + block.x),
px(sb.rect.y + block.y + dy),
),
BlockPaint::default(),
window,
cx,
);
}
});
}
}
@@ -0,0 +1,445 @@
//! Line-width rail, font-size dropdown, and `4×2` Align & Distribute + Auto-arrange popover
//! for `chrome.edgeless_element_toolbar`.
use ui::{
AnyElement, Bounds, ClickEvent, Context, FontWeight, MouseButton, SharedString, canvas, div,
point, prelude::*, px, size,
};
use crate::{
block_flow::FlowRect,
overlays::{Placement, place_popover},
theme::{Palette, PlaygroundTheme, TYPOGRAPHY},
};
use super::{
AlignOp, BRUSH_LINE_WIDTHS, EDGELESS_VIEWPORT_ID, EdgelessElementAction,
EdgelessElementToolbarHost, ElementToolbarSummary, FONT_SIZE_LIST, HIGHLIGHTER_LINE_WIDTHS,
widgets::{attach_tooltip, isolate_floating_chrome, toolbar_chrome_tokens},
};
#[allow(clippy::too_many_arguments)]
pub(super) fn build_line_width_panel<V: EdgelessElementToolbarHost>(
summary: &ElementToolbarSummary,
trigger_rect: FlowRect,
viewport_width: f32,
viewport_height: f32,
palette: &Palette,
theme: PlaygroundTheme,
cx: &mut Context<V>,
) -> (AnyElement, FlowRect) {
let (panel_bg, border_col, shadows) = toolbar_chrome_tokens(palette, theme);
let widths: &[f64] = if summary.is_highlighter_width {
&HIGHLIGHTER_LINE_WIDTHS
} else {
&BRUSH_LINE_WIDTHS
};
const CELL: f32 = 26.0;
const GAP: f32 = 4.0;
const PAD: f32 = 6.0;
const READOUT_W: f32 = 38.0;
let sub_w = widths.len() as f32 * CELL
+ widths.len().saturating_sub(1) as f32 * GAP
+ GAP
+ READOUT_W
+ 2.0 * PAD
+ 2.0;
let sub_h = CELL + 2.0 * PAD + 2.0;
let vp_rect = FlowRect::new(0.0, 0.0, viewport_width, viewport_height);
let placed = place_popover(
trigger_rect,
(sub_w, sub_h),
vp_rect,
Placement::Above,
8.0,
10.0,
);
let hover_bg = palette.hover;
let brand = palette.brand;
let icon_col = palette.icon;
let rail_col = palette.border;
let mut sub = isolate_floating_chrome(
div()
.absolute()
.left(px(placed.rect.x))
.top(px(placed.rect.y))
.p(px(PAD))
.rounded(px(8.0))
.bg(panel_bg)
.border(px(0.5))
.border_color(border_col)
.flex()
.items_center()
.gap(px(GAP)),
)
.snapshot(
"chrome.edgeless_element_toolbar.sub_menu",
Some(EDGELESS_VIEWPORT_ID),
);
for (idx, &w_val) in widths.iter().enumerate() {
let active = (summary.stroke_width - w_val).abs() < 0.5;
let dot_px = 5.0 + idx as f32 * 2.0;
let w_int = w_val.round() as i32;
let show_left_rail = idx > 0;
let show_right_rail = idx + 1 < widths.len();
sub = sub.child(
div()
.id(SharedString::from(format!("el-tb-lw-{w_int}")))
.w(px(CELL))
.h(px(CELL))
.rounded(px(4.0))
.flex()
.items_center()
.justify_center()
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.when(active, |el| el.bg(hover_bg))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(
EdgelessElementAction::SetStrokeWidth(w_val),
window,
cx,
);
}))
.snapshot(
SharedString::from(format!("chrome.edgeless_element_toolbar.sub.lw_{w_int}")),
Some("chrome.edgeless_element_toolbar.sub_menu"),
)
.snapshot_text(format!("{w_int}px"))
.child(
canvas(
|_, _, _| (),
move |bounds, _, window, _| {
let ox = f32::from(bounds.origin.x);
let oy = f32::from(bounds.origin.y);
let bw = f32::from(bounds.size.width);
let bh = f32::from(bounds.size.height);
let cx_b = ox + bw * 0.5;
let cy_b = oy + bh * 0.5;
if show_left_rail {
window.paint_quad(ui::fill(
Bounds::new(
point(px(ox), px(cy_b - 0.75)),
size(px(bw * 0.5), px(1.5)),
),
rail_col,
));
}
if show_right_rail {
window.paint_quad(ui::fill(
Bounds::new(
point(px(cx_b), px(cy_b - 0.75)),
size(px(bw * 0.5), px(1.5)),
),
rail_col,
));
}
let r = dot_px * 0.5;
window.paint_quad(
ui::fill(
Bounds::new(
point(px(cx_b - r), px(cy_b - r)),
size(px(dot_px), px(dot_px)),
),
if active { brand } else { icon_col },
)
.corner_radii(px(r)),
);
},
)
.w(px(CELL))
.h(px(CELL)),
),
);
}
let readout = format!("{}px", summary.stroke_width.round() as i32);
sub = sub.child(
div()
.w(px(READOUT_W))
.h(px(CELL))
.flex()
.items_center()
.justify_center()
.text_size(px(TYPOGRAPHY.font_xs_px))
.font_weight(FontWeight::MEDIUM)
.text_color(palette.text_secondary)
.child(readout),
);
if !shadows.is_empty() {
sub = sub.shadow(shadows.into());
}
(sub.into_any_element(), placed.rect)
}
#[allow(clippy::too_many_arguments)]
pub(super) fn build_font_size_dropdown<V: EdgelessElementToolbarHost>(
summary: &ElementToolbarSummary,
trigger_rect: FlowRect,
viewport_width: f32,
viewport_height: f32,
palette: &Palette,
theme: PlaygroundTheme,
cx: &mut Context<V>,
) -> (AnyElement, FlowRect) {
let (panel_bg, border_col, shadows) = toolbar_chrome_tokens(palette, theme);
const ROW_H: f32 = 28.0;
const GAP: f32 = 2.0;
const PAD: f32 = 4.0;
const SUB_W: f32 = 84.0;
let sub_h = FONT_SIZE_LIST.len() as f32 * ROW_H
+ FONT_SIZE_LIST.len().saturating_sub(1) as f32 * GAP
+ 2.0 * PAD
+ 2.0;
let vp_rect = FlowRect::new(0.0, 0.0, viewport_width, viewport_height);
let placed = place_popover(
trigger_rect,
(SUB_W, sub_h),
vp_rect,
Placement::Above,
8.0,
10.0,
);
let hover_bg = palette.hover;
let brand = palette.brand;
let mut sub = isolate_floating_chrome(
div()
.absolute()
.left(px(placed.rect.x))
.top(px(placed.rect.y))
.w(px(SUB_W))
.p(px(PAD))
.rounded(px(8.0))
.bg(panel_bg)
.border(px(0.5))
.border_color(border_col)
.flex()
.flex_col()
.gap(px(GAP)),
)
.snapshot(
"chrome.edgeless_element_toolbar.sub_menu",
Some(EDGELESS_VIEWPORT_ID),
);
for &fs in &FONT_SIZE_LIST {
let active = (summary.font_size - fs).abs() < 0.5;
let fs_int = fs.round() as i32;
let label = format!("{fs_int}");
let text_col = if active { brand } else { palette.text_primary };
sub = sub.child(
div()
.id(SharedString::from(format!("el-tb-fs-{fs_int}")))
.w_full()
.h(px(ROW_H))
.px(px(10.0))
.rounded(px(4.0))
.flex()
.items_center()
.text_size(px(TYPOGRAPHY.font_xs_px))
.font_weight(FontWeight::MEDIUM)
.text_color(text_col)
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.when(active, |el| el.bg(hover_bg))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(
EdgelessElementAction::SetFontSize(fs),
window,
cx,
);
}))
.snapshot(
SharedString::from(format!("chrome.edgeless_element_toolbar.sub.fs_{fs_int}")),
Some("chrome.edgeless_element_toolbar.sub_menu"),
)
.snapshot_text(label.clone())
.child(div().flex_1().child(label))
.child(if active { "\u{2713}" } else { "" }),
);
}
if !shadows.is_empty() {
sub = sub.shadow(shadows.into());
}
(sub.into_any_element(), placed.rect)
}
#[allow(clippy::too_many_arguments)]
pub(super) fn build_align_grid_popover<V: EdgelessElementToolbarHost>(
summary: &ElementToolbarSummary,
trigger_rect: FlowRect,
viewport_width: f32,
viewport_height: f32,
palette: &Palette,
theme: PlaygroundTheme,
cx: &mut Context<V>,
) -> (AnyElement, FlowRect) {
let (panel_bg, border_col, shadows) = toolbar_chrome_tokens(palette, theme);
const CELL: f32 = 30.0;
const GAP: f32 = 4.0;
const PAD: f32 = 8.0;
const SUB_W: f32 = 4.0 * CELL + 3.0 * GAP + 2.0 * PAD + 2.0;
const SUB_H: f32 = 2.0 * CELL + GAP + 9.0 + 28.0 + 2.0 * PAD + 6.0;
let vp_rect = FlowRect::new(0.0, 0.0, viewport_width, viewport_height);
let placed = place_popover(
trigger_rect,
(SUB_W, SUB_H),
vp_rect,
Placement::BelowStart,
8.0,
10.0,
);
let hover_bg = palette.hover;
let icon_col = palette.icon;
let disabled_col = palette.text_secondary.opacity(0.4);
let rows: [[(&str, &str, &str, AlignOp, bool); 4]; 2] = [
[
("left", "Align left", "L", AlignOp::Left, true),
(
"center_h",
"Align center horizontally",
"C",
AlignOp::CenterH,
true,
),
("right", "Align right", "R", AlignOp::Right, true),
(
"dist_h",
"Distribute horizontally",
"DH",
AlignOp::DistributeH,
summary.can_distribute,
),
],
[
("top", "Align top", "T", AlignOp::Top, true),
(
"center_v",
"Align middle vertically",
"M",
AlignOp::CenterV,
true,
),
("bottom", "Align bottom", "B", AlignOp::Bottom, true),
(
"dist_v",
"Distribute vertically",
"DV",
AlignOp::DistributeV,
summary.can_distribute,
),
],
];
let mut sub = isolate_floating_chrome(
div()
.absolute()
.left(px(placed.rect.x))
.top(px(placed.rect.y))
.w(px(SUB_W))
.p(px(PAD))
.rounded(px(8.0))
.bg(panel_bg)
.border(px(0.5))
.border_color(border_col)
.flex()
.flex_col()
.gap(px(GAP)),
)
.snapshot(
"chrome.edgeless_element_toolbar.sub_menu",
Some(EDGELESS_VIEWPORT_ID),
);
for row_items in rows {
let mut row = div().flex().items_center().gap(px(GAP));
for (id, tip, short, op, enabled) in row_items {
let fg = if enabled { icon_col } else { disabled_col };
let mut cell = div()
.id(SharedString::from(format!("el-tb-align-{id}")))
.w(px(CELL))
.h(px(CELL))
.rounded(px(4.0))
.flex()
.items_center()
.justify_center()
.text_size(px(11.0))
.font_weight(FontWeight::SEMIBOLD)
.text_color(fg)
.snapshot(
SharedString::from(format!("chrome.edgeless_element_toolbar.sub.{id}")),
Some("chrome.edgeless_element_toolbar.sub_menu"),
)
.snapshot_text(tip)
.child(short);
if enabled {
cell = cell
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(EdgelessElementAction::Align(op), window, cx);
}));
}
row = row.child(attach_tooltip(cell, tip, palette));
}
sub = sub.child(row);
}
sub = sub
.child(
div()
.w_full()
.h(px(7.0))
.flex()
.items_center()
.child(div().w_full().h(px(0.5)).bg(border_col)),
)
.child(
div()
.id("el-tb-align-auto-arrange")
.w_full()
.h(px(28.0))
.px(px(8.0))
.rounded(px(4.0))
.flex()
.items_center()
.justify_center()
.text_size(px(TYPOGRAPHY.font_xs_px))
.font_weight(FontWeight::MEDIUM)
.text_color(palette.text_primary)
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(|this, _: &ClickEvent, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(
EdgelessElementAction::Align(AlignOp::AutoArrange),
window,
cx,
);
}))
.snapshot(
"chrome.edgeless_element_toolbar.sub.auto_arrange",
Some("chrome.edgeless_element_toolbar.sub_menu"),
)
.snapshot_text("Auto arrange")
.child("Auto arrange"),
);
if !shadows.is_empty() {
sub = sub.shadow(shadows.into());
}
(sub.into_any_element(), placed.rect)
}
@@ -0,0 +1,496 @@
//! Per-type button group builders for `chrome.edgeless_element_toolbar`.
use blocksuite_playground_doc::read::{ConnectorMode, StrokeStyle};
use ui::{BorderStyle, Bounds, Context, Corners, Edges, Hsla, point, prelude::*, px, size};
use crate::{block_flow::FlowRect, theme::Palette};
use super::{
EdgelessElementAction, EdgelessElementToolbarHost, ElementColorSlot, ElementSubMenu,
ElementToolbarSummary, ShapePreset,
media_toolbar::append_media_toolbar_items,
widgets::{
BAR_GAP, BTN_SIZE, align_action_btn, icon_action_btn, stroke_style_btn, swatch_btn,
text_action_btn, text_color_btn,
},
};
fn next_stroke_style(current: StrokeStyle) -> StrokeStyle {
match current {
StrokeStyle::Solid => StrokeStyle::Dash,
StrokeStyle::Dash => StrokeStyle::None,
StrokeStyle::None => StrokeStyle::Solid,
}
}
fn shape_preset_icon(preset: ShapePreset) -> &'static str {
match preset {
ShapePreset::Rect => "SquareIcon",
ShapePreset::Ellipse => "ShapeIcon",
ShapePreset::Diamond => "DiamondIcon",
ShapePreset::Triangle => "TriangleIcon",
ShapePreset::RoundedRect => "RoundedRectangleIcon",
}
}
fn connector_mode_icon(mode: ConnectorMode) -> &'static str {
match mode {
ConnectorMode::Straight => "ConnectorLIcon",
ConnectorMode::Orthogonal => "ConnectorEIcon",
ConnectorMode::Curve => "ConnectorCIcon",
}
}
#[allow(clippy::too_many_arguments)]
pub(super) fn append_per_type_items<V: EdgelessElementToolbarHost>(
mut bar: ui::Div,
summary: &ElementToolbarSummary,
open_color_picker: Option<ElementColorSlot>,
open_sub: Option<ElementSubMenu>,
palette: &Palette,
panel_bg: Hsla,
border_col: Hsla,
cursor_x: &mut f32,
bar_top: f32,
bar_h: f32,
sub_triggers: &mut Vec<(ElementSubMenu, FlowRect)>,
color_triggers: &mut Vec<(ElementColorSlot, FlowRect)>,
cx: &mut Context<V>,
) -> ui::Div {
if summary.has_frame_actions {
bar = bar
.child(text_action_btn(
"el-tb-rename",
"chrome.edgeless_element_toolbar.rename",
"Rename".to_string(),
54.0,
false,
false,
palette,
EdgelessElementAction::Rename,
cx,
))
.child(text_action_btn(
"el-tb-insert-page",
"chrome.edgeless_element_toolbar.insert_page",
"To Page".to_string(),
64.0,
false,
false,
palette,
EdgelessElementAction::InsertFrameIntoPage,
cx,
))
.child(text_action_btn(
"el-tb-ungroup",
"chrome.edgeless_element_toolbar.ungroup",
"Ungroup".to_string(),
58.0,
false,
false,
palette,
EdgelessElementAction::Ungroup,
cx,
));
*cursor_x += 54.0 + 64.0 + 58.0 + 3.0 * BAR_GAP;
} else if summary.has_group_actions {
bar = bar
.child(text_action_btn(
"el-tb-insert-group-page",
"chrome.edgeless_element_toolbar.insert_page",
"To Page".to_string(),
64.0,
false,
false,
palette,
EdgelessElementAction::InsertGroupIntoPage,
cx,
))
.child(text_action_btn(
"el-tb-rename",
"chrome.edgeless_element_toolbar.rename",
"Rename".to_string(),
54.0,
false,
false,
palette,
EdgelessElementAction::Rename,
cx,
))
.child(text_action_btn(
"el-tb-ungroup",
"chrome.edgeless_element_toolbar.ungroup",
"Ungroup".to_string(),
58.0,
false,
false,
palette,
EdgelessElementAction::Ungroup,
cx,
));
*cursor_x += 64.0 + 54.0 + 58.0 + 3.0 * BAR_GAP;
}
if let Some(mm) = &summary.mindmap {
sub_triggers.push((
ElementSubMenu::MindmapStyle,
FlowRect::new(*cursor_x, bar_top, 62.0, bar_h),
));
bar = bar.child(text_action_btn(
"el-tb-mm-style",
"chrome.edgeless_element_toolbar.mindmap_style",
format!("Style {}", mm.style as u8),
62.0,
open_sub == Some(ElementSubMenu::MindmapStyle),
true,
palette,
EdgelessElementAction::ToggleSubMenu(ElementSubMenu::MindmapStyle),
cx,
));
*cursor_x += 62.0 + BAR_GAP;
sub_triggers.push((
ElementSubMenu::MindmapLayout,
FlowRect::new(*cursor_x, bar_top, 62.0, bar_h),
));
bar = bar.child(text_action_btn(
"el-tb-mm-layout",
"chrome.edgeless_element_toolbar.mindmap_layout",
"Layout".to_string(),
62.0,
open_sub == Some(ElementSubMenu::MindmapLayout),
true,
palette,
EdgelessElementAction::ToggleSubMenu(ElementSubMenu::MindmapLayout),
cx,
));
*cursor_x += 62.0 + BAR_GAP;
if mm.has_children {
bar = bar.child(text_action_btn(
"el-tb-mm-fold",
"chrome.edgeless_element_toolbar.mindmap_collapse",
if mm.collapsed { "Expand" } else { "Fold" }.to_string(),
54.0,
mm.collapsed,
false,
palette,
EdgelessElementAction::ToggleMindmapCollapse,
cx,
));
*cursor_x += 54.0 + BAR_GAP;
}
}
if let Some(sb) = &summary.surface_block {
bar = append_media_toolbar_items(
bar,
sb,
open_sub,
palette,
cursor_x,
bar_top,
bar_h,
BAR_GAP,
sub_triggers,
cx,
);
}
if summary.has_shape_type {
sub_triggers.push((
ElementSubMenu::ShapeType,
FlowRect::new(*cursor_x, bar_top, BTN_SIZE, bar_h),
));
bar = bar.child(icon_action_btn(
"el-tb-shape-type",
"chrome.edgeless_element_toolbar.shape_type",
"Switch shape",
shape_preset_icon(summary.shape_preset),
open_sub == Some(ElementSubMenu::ShapeType),
palette,
EdgelessElementAction::ToggleSubMenu(ElementSubMenu::ShapeType),
cx,
));
*cursor_x += BTN_SIZE + BAR_GAP;
}
if summary.has_fill {
color_triggers.push((
ElementColorSlot::Fill,
FlowRect::new(*cursor_x, bar_top, BTN_SIZE, bar_h),
));
let active = open_color_picker == Some(ElementColorSlot::Fill);
let fill = summary.fill_color;
bar = bar.child(swatch_btn(
"el-tb-fill",
"chrome.edgeless_element_toolbar.fill",
"Fill color",
active,
palette,
ElementColorSlot::Fill,
move |bounds, window| {
let inset = 3.0;
let side = (f32::from(bounds.size.width) - 2.0 * inset).max(10.0);
window.paint_quad(ui::quad(
Bounds::new(
point(bounds.origin.x + px(inset), bounds.origin.y + px(inset)),
size(px(side), px(side)),
),
Corners::all(px(side * 0.5)),
fill,
Edges::all(px(0.5)),
border_col,
BorderStyle::Solid,
));
},
cx,
));
*cursor_x += BTN_SIZE + BAR_GAP;
}
if summary.has_stroke {
color_triggers.push((
ElementColorSlot::Stroke,
FlowRect::new(*cursor_x, bar_top, BTN_SIZE, bar_h),
));
let active = open_color_picker == Some(ElementColorSlot::Stroke);
let stroke = summary.stroke_color;
bar = bar.child(swatch_btn(
"el-tb-stroke",
"chrome.edgeless_element_toolbar.stroke",
"Border color",
active,
palette,
ElementColorSlot::Stroke,
move |bounds, window| {
let inset = 3.0;
let side = (f32::from(bounds.size.width) - 2.0 * inset).max(10.0);
window.paint_quad(ui::quad(
Bounds::new(
point(bounds.origin.x + px(inset), bounds.origin.y + px(inset)),
size(px(side), px(side)),
),
Corners::all(px(side * 0.5)),
panel_bg,
Edges::all(px(2.5)),
stroke,
BorderStyle::Solid,
));
},
cx,
));
*cursor_x += BTN_SIZE + BAR_GAP;
}
if summary.has_stroke_style {
bar = bar.child(stroke_style_btn(
summary.stroke_style,
next_stroke_style(summary.stroke_style),
palette,
cx,
));
*cursor_x += BTN_SIZE + BAR_GAP;
}
if summary.has_stroke_width {
sub_triggers.push((
ElementSubMenu::LineWidth,
FlowRect::new(*cursor_x, bar_top, 44.0, bar_h),
));
bar = bar.child(text_action_btn(
"el-tb-stroke-width",
"chrome.edgeless_element_toolbar.stroke_width",
format!("{}px", summary.stroke_width.round() as i32),
44.0,
open_sub == Some(ElementSubMenu::LineWidth),
true,
palette,
EdgelessElementAction::ToggleSubMenu(ElementSubMenu::LineWidth),
cx,
));
*cursor_x += 44.0 + BAR_GAP;
}
if summary.has_rough_style {
bar = bar.child(icon_action_btn(
"el-tb-rough",
"chrome.edgeless_element_toolbar.rough_style",
if summary.scribbled {
"Scribbled"
} else {
"General"
},
if summary.scribbled {
"PenIcon"
} else {
"SquareIcon"
},
summary.scribbled,
palette,
EdgelessElementAction::ToggleRoughStyle,
cx,
));
*cursor_x += BTN_SIZE + BAR_GAP;
}
if summary.has_connector_props {
sub_triggers.push((
ElementSubMenu::ConnectorMode,
FlowRect::new(*cursor_x, bar_top, BTN_SIZE, bar_h),
));
bar = bar.child(icon_action_btn(
"el-tb-conn-mode",
"chrome.edgeless_element_toolbar.connector_mode",
"Connector shape",
connector_mode_icon(summary.connector_mode),
open_sub == Some(ElementSubMenu::ConnectorMode),
palette,
EdgelessElementAction::ToggleSubMenu(ElementSubMenu::ConnectorMode),
cx,
));
*cursor_x += BTN_SIZE + BAR_GAP;
sub_triggers.push((
ElementSubMenu::ConnectorCaps,
FlowRect::new(*cursor_x, bar_top, 48.0, bar_h),
));
bar = bar.child(text_action_btn(
"el-tb-conn-caps",
"chrome.edgeless_element_toolbar.connector_caps",
"Caps".to_string(),
48.0,
open_sub == Some(ElementSubMenu::ConnectorCaps),
true,
palette,
EdgelessElementAction::ToggleSubMenu(ElementSubMenu::ConnectorCaps),
cx,
));
*cursor_x += 48.0 + BAR_GAP;
}
if summary.can_add_text {
bar = bar.child(icon_action_btn(
"el-tb-add-text",
"chrome.edgeless_element_toolbar.add_text",
"Add text",
"AddTextIcon",
false,
palette,
EdgelessElementAction::AddText,
cx,
));
*cursor_x += BTN_SIZE + BAR_GAP;
}
if summary.has_text_color {
color_triggers.push((
ElementColorSlot::Text,
FlowRect::new(*cursor_x, bar_top, BTN_SIZE, bar_h),
));
bar = bar.child(text_color_btn(
open_color_picker == Some(ElementColorSlot::Text),
summary.text_color,
palette,
cx,
));
*cursor_x += BTN_SIZE + BAR_GAP;
}
if summary.has_font_size {
sub_triggers.push((
ElementSubMenu::FontSize,
FlowRect::new(*cursor_x, bar_top, 44.0, bar_h),
));
bar = bar.child(text_action_btn(
"el-tb-font-size",
"chrome.edgeless_element_toolbar.font_size",
format!("{}px", summary.font_size.round() as i32),
44.0,
open_sub == Some(ElementSubMenu::FontSize),
true,
palette,
EdgelessElementAction::ToggleSubMenu(ElementSubMenu::FontSize),
cx,
));
*cursor_x += 44.0 + BAR_GAP;
}
if summary.has_text_align {
sub_triggers.push((
ElementSubMenu::TextAlign,
FlowRect::new(*cursor_x, bar_top, BTN_SIZE, bar_h),
));
bar = bar.child(align_action_btn(
summary.text_align,
open_sub == Some(ElementSubMenu::TextAlign),
palette,
cx,
));
*cursor_x += BTN_SIZE + BAR_GAP;
}
if summary.has_note_shadow {
let style_open = matches!(
open_sub,
Some(ElementSubMenu::NoteStyle | ElementSubMenu::NoteShadow)
);
sub_triggers.push((
ElementSubMenu::NoteStyle,
FlowRect::new(*cursor_x, bar_top, 56.0, bar_h),
));
sub_triggers.push((
ElementSubMenu::NoteShadow,
FlowRect::new(*cursor_x, bar_top, 56.0, bar_h),
));
bar = bar.child(text_action_btn(
"el-tb-note-style",
"chrome.edgeless_element_toolbar.note_style",
"Style".to_string(),
56.0,
style_open,
true,
palette,
EdgelessElementAction::ToggleSubMenu(ElementSubMenu::NoteStyle),
cx,
));
*cursor_x += 56.0 + BAR_GAP;
sub_triggers.push((
ElementSubMenu::NoteScale,
FlowRect::new(*cursor_x, bar_top, 54.0, bar_h),
));
bar = bar.child(text_action_btn(
"el-tb-note-scale",
"chrome.edgeless_element_toolbar.note_scale",
format!("{}%", (summary.note_scale * 100.0).round() as i32),
54.0,
open_sub == Some(ElementSubMenu::NoteScale),
true,
palette,
EdgelessElementAction::ToggleSubMenu(ElementSubMenu::NoteScale),
cx,
));
*cursor_x += 54.0 + BAR_GAP;
}
if summary.has_note_display {
let label = if summary.note_in_page {
"Displayed in Page"
} else {
"Display in Page"
};
bar = bar.child(text_action_btn(
"el-tb-note-display",
"chrome.edgeless_element_toolbar.note_display",
label.to_string(),
96.0,
summary.note_in_page,
false,
palette,
EdgelessElementAction::ToggleNoteDisplayMode,
cx,
));
*cursor_x += 96.0 + BAR_GAP;
}
bar
}
@@ -2,7 +2,7 @@
//! custom `#RRGGBB` input for `chrome.edgeless_element_toolbar`.
use ui::{
AnyElement, BorderStyle, Bounds, Context, Corners, Edges, FontWeight, MouseButton,
AnyElement, BorderStyle, Bounds, ClickEvent, Context, Corners, Edges, FontWeight, MouseButton,
SharedString, canvas, div, point, prelude::*, px, size,
};
@@ -16,6 +16,7 @@ use super::{
EDGELESS_VIEWPORT_ID, EdgelessAuthoringState, EdgelessElementAction,
EdgelessElementToolbarHost, ElementColorSlot, ElementToolbarSummary,
color_value_matches_swatch, palette_for_slot, parse_custom_hex_color,
widgets::{isolate_floating_chrome, toolbar_chrome_tokens},
};
#[allow(clippy::too_many_arguments)]
@@ -23,14 +24,14 @@ pub(super) fn build_color_picker_pill<V: EdgelessElementToolbarHost>(
slot: ElementColorSlot,
summary: &ElementToolbarSummary,
authoring: &EdgelessAuthoringState,
bar_rect: FlowRect,
trigger_rect: FlowRect,
viewport_width: f32,
viewport_height: f32,
palette: &Palette,
theme: PlaygroundTheme,
shadows: Vec<ui::BoxShadow>,
cx: &mut Context<V>,
) -> AnyElement {
) -> (AnyElement, FlowRect) {
let (panel_bg, border_col, shadows) = toolbar_chrome_tokens(palette, theme);
let (swatches, cols) = palette_for_slot(slot, summary.is_note_fill, summary.is_shape_text);
let current_val = match slot {
ElementColorSlot::Fill => &summary.fill_color_value,
@@ -52,16 +53,15 @@ pub(super) fn build_color_picker_pill<V: EdgelessElementToolbarHost>(
let vp_rect = FlowRect::new(0.0, 0.0, viewport_width, viewport_height);
let placed_sub = place_popover(
bar_rect,
trigger_rect,
(sub_w, sub_h),
vp_rect,
Placement::Above,
6.0,
8.0,
10.0,
);
let hover_bg = palette.hover;
let border_col = palette.border;
let brand_col = palette.brand;
let slash_col = theme
.css_color("--affine-error-color")
@@ -72,24 +72,25 @@ pub(super) fn build_color_picker_pill<V: EdgelessElementToolbarHost>(
ElementColorSlot::Text => "text",
};
let mut sub = div()
.absolute()
.left(px(placed_sub.rect.x))
.top(px(placed_sub.rect.y))
.w(px(sub_w))
.p(px(PAD))
.rounded(px(8.0))
.bg(palette.panel)
.border_1()
.border_color(palette.border)
.flex()
.flex_col()
.gap(px(CUSTOM_ROW_GAP))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.snapshot(
"chrome.edgeless_element_toolbar.color_picker",
Some(EDGELESS_VIEWPORT_ID),
);
let mut sub = isolate_floating_chrome(
div()
.absolute()
.left(px(placed_sub.rect.x))
.top(px(placed_sub.rect.y))
.w(px(sub_w))
.p(px(PAD))
.rounded(px(8.0))
.bg(panel_bg)
.border(px(0.5))
.border_color(border_col)
.flex()
.flex_col()
.gap(px(CUSTOM_ROW_GAP)),
)
.snapshot(
"chrome.edgeless_element_toolbar.color_picker",
Some(EDGELESS_VIEWPORT_ID),
);
let mut grid = div().flex().flex_col().gap(px(GAP));
for row_chunk in swatches.chunks(cols) {
@@ -127,20 +128,18 @@ pub(super) fn build_color_picker_pill<V: EdgelessElementToolbarHost>(
.justify_center()
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.on_mouse_down(
MouseButton::Left,
cx.listener(move |this, _, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(
EdgelessElementAction::SetColor {
slot,
color: wire_val.clone(),
},
window,
cx,
);
}),
)
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(
EdgelessElementAction::SetColor {
slot,
color: wire_val.clone(),
},
window,
cx,
);
}))
.snapshot(
snap_id,
Some("chrome.edgeless_element_toolbar.color_picker"),
@@ -331,5 +330,5 @@ pub(super) fn build_color_picker_pill<V: EdgelessElementToolbarHost>(
if !shadows.is_empty() {
sub = sub.shadow(shadows.into());
}
sub.into_any_element()
(sub.into_any_element(), placed_sub.rect)
}
@@ -0,0 +1,502 @@
//! Canvas context toolbar controls and style sub-menu for spatial media & embed blocks
//! (`Image`, `Attachment`, `Bookmark`, `EmbedLinkedDoc`, `EmbedSyncedDoc`, `ExternalEmbed`)
//! selected on the Edgeless canvas.
use blocksuite_playground_doc::read::{BlockContent, BlockNode};
use ui::{
AnyElement, ClickEvent, Context, FontWeight, MouseButton, SharedString, div, prelude::*, px,
};
use crate::{
block_flow::FlowRect,
overlays::{Placement, place_popover},
theme::{Palette, PlaygroundTheme, TYPOGRAPHY},
};
use super::{
EDGELESS_VIEWPORT_ID, EdgelessElementAction, EdgelessElementToolbarHost, ElementSubMenu,
SurfaceBlockKind, SurfaceBlockToolbarSummary, prop_f32,
widgets::{
BTN_SIZE, icon_action_btn, isolate_floating_chrome, text_action_btn, toolbar_chrome_tokens,
},
};
/// Build a `SurfaceBlockToolbarSummary` from a single selected canvas media/embed `BlockNode`.
pub(super) fn summarize_surface_block(node: &BlockNode) -> Option<SurfaceBlockToolbarSummary> {
let caption = node
.props
.get("prop:caption")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let card_style = node
.props
.get("prop:style")
.and_then(|v| v.as_str())
.unwrap_or("horizontal")
.to_string();
let is_embed_view = match &node.content {
BlockContent::Attachment { .. } => node
.props
.get("prop:embed")
.and_then(|v| v.as_bool())
.unwrap_or(false),
BlockContent::EmbedSyncedDoc { .. } | BlockContent::ExternalEmbed { .. } => true,
_ => false,
};
let can_toggle_view = match &node.content {
BlockContent::Attachment { .. }
| BlockContent::EmbedLinkedDoc { .. }
| BlockContent::EmbedSyncedDoc { .. }
| BlockContent::ExternalEmbed { .. } => true,
BlockContent::Bookmark { url, .. } => {
crate::overlays::embed_view_kind_for_url(url).is_some()
}
_ => false,
};
let can_download = match &node.content {
BlockContent::Image { source_id, .. } | BlockContent::Attachment { source_id, .. } => {
!source_id.is_empty()
}
_ => false,
};
let scale = prop_f32(node, "prop:scale", 1.0).clamp(0.25, 4.0);
let rotate_deg = prop_f32(node, "prop:rotate", 0.0);
let (kind, url, title) = match &node.content {
BlockContent::Image { .. } => (
SurfaceBlockKind::Image,
None,
node.props
.get("prop:sourceId")
.and_then(|v| v.as_str())
.unwrap_or("Image")
.to_string(),
),
BlockContent::Attachment { name, .. } => (SurfaceBlockKind::Attachment, None, name.clone()),
BlockContent::Bookmark { url, title, .. } => (
SurfaceBlockKind::Bookmark,
Some(url.clone()),
title.clone().unwrap_or_else(|| url.clone()),
),
BlockContent::EmbedLinkedDoc { page_id, .. } => (
SurfaceBlockKind::EmbedLinkedDoc,
Some(page_id.clone()),
page_id.clone(),
),
BlockContent::EmbedSyncedDoc { page_id, .. } => (
SurfaceBlockKind::EmbedSyncedDoc,
Some(page_id.clone()),
page_id.clone(),
),
BlockContent::ExternalEmbed { url, title, .. } => (
SurfaceBlockKind::ExternalEmbed,
Some(url.clone()),
title.clone().unwrap_or_else(|| url.clone()),
),
_ => return None,
};
Some(SurfaceBlockToolbarSummary {
block_id: node.id.clone(),
kind,
url,
title,
caption,
card_style,
is_embed_view,
can_toggle_view,
can_download,
scale,
rotate_deg,
})
}
/// Estimated widths for each button pushed by `append_media_toolbar_items`.
pub(super) fn media_toolbar_item_widths(sb: &SurfaceBlockToolbarSummary) -> Vec<f32> {
match sb.kind {
SurfaceBlockKind::Image => {
let mut w = vec![56.0, BTN_SIZE, 54.0];
if sb.can_download {
w.push(BTN_SIZE);
}
w
}
SurfaceBlockKind::Attachment => {
let mut w = vec![68.0, 62.0, 56.0];
if sb.can_download {
w.push(BTN_SIZE);
}
w
}
SurfaceBlockKind::Bookmark => {
let mut w = vec![64.0, BTN_SIZE];
if sb.can_toggle_view {
w.push(68.0);
}
w.extend([62.0, 56.0]);
w
}
SurfaceBlockKind::EmbedLinkedDoc
| SurfaceBlockKind::EmbedSyncedDoc
| SurfaceBlockKind::ExternalEmbed => vec![58.0, BTN_SIZE, 68.0, 56.0],
}
}
/// Append dedicated media/embed controls to the Edgeless element toolbar, recording trigger rects
/// for any dropdowns (`MediaStyle`, `MediaScale`).
#[allow(clippy::too_many_arguments)]
pub(super) fn append_media_toolbar_items<V: EdgelessElementToolbarHost>(
mut bar: ui::Div,
sb: &SurfaceBlockToolbarSummary,
open_sub: Option<ElementSubMenu>,
palette: &Palette,
cursor_x: &mut f32,
bar_top: f32,
bar_h: f32,
gap: f32,
trigger_rects: &mut Vec<(ElementSubMenu, FlowRect)>,
cx: &mut Context<V>,
) -> ui::Div {
let mut advance = |w: f32, menu: Option<ElementSubMenu>| {
if let Some(m) = menu {
trigger_rects.push((m, FlowRect::new(*cursor_x, bar_top, w, bar_h)));
}
*cursor_x += w + gap;
};
match sb.kind {
SurfaceBlockKind::Image => {
bar = bar.child(text_action_btn(
"el-tb-media-caption",
"chrome.edgeless_element_toolbar.media_caption",
"Caption".to_string(),
56.0,
!sb.caption.is_empty(),
false,
palette,
EdgelessElementAction::MediaCaption,
cx,
));
advance(56.0, None);
bar = bar.child(icon_action_btn(
"el-tb-media-rotate",
"chrome.edgeless_element_toolbar.media_rotate",
"Rotate 90°",
"RedoIcon",
false,
palette,
EdgelessElementAction::MediaRotateCw,
cx,
));
advance(BTN_SIZE, None);
let pct = (sb.scale * 100.0).round() as i32;
bar = bar.child(text_action_btn(
"el-tb-media-scale",
"chrome.edgeless_element_toolbar.media_scale",
format!("{pct}%"),
54.0,
open_sub == Some(ElementSubMenu::MediaScale),
true,
palette,
EdgelessElementAction::ToggleSubMenu(ElementSubMenu::MediaScale),
cx,
));
advance(54.0, Some(ElementSubMenu::MediaScale));
if sb.can_download {
bar = bar.child(icon_action_btn(
"el-tb-media-download",
"chrome.edgeless_element_toolbar.media_download",
"Download",
"AttachmentIcon",
false,
palette,
EdgelessElementAction::MediaDownload,
cx,
));
advance(BTN_SIZE, None);
}
}
SurfaceBlockKind::Attachment => {
let view_label = if sb.is_embed_view { "Embed" } else { "Card" };
bar = bar.child(text_action_btn(
"el-tb-media-view",
"chrome.edgeless_element_toolbar.media_view",
view_label.to_string(),
68.0,
sb.is_embed_view,
false,
palette,
EdgelessElementAction::MediaToggleView,
cx,
));
advance(68.0, None);
bar = bar.child(text_action_btn(
"el-tb-media-style",
"chrome.edgeless_element_toolbar.media_style",
"Style".to_string(),
62.0,
open_sub == Some(ElementSubMenu::MediaStyle),
true,
palette,
EdgelessElementAction::ToggleSubMenu(ElementSubMenu::MediaStyle),
cx,
));
advance(62.0, Some(ElementSubMenu::MediaStyle));
bar = bar.child(text_action_btn(
"el-tb-media-caption",
"chrome.edgeless_element_toolbar.media_caption",
"Caption".to_string(),
56.0,
!sb.caption.is_empty(),
false,
palette,
EdgelessElementAction::MediaCaption,
cx,
));
advance(56.0, None);
if sb.can_download {
bar = bar.child(icon_action_btn(
"el-tb-media-download",
"chrome.edgeless_element_toolbar.media_download",
"Download",
"AttachmentIcon",
false,
palette,
EdgelessElementAction::MediaDownload,
cx,
));
advance(BTN_SIZE, None);
}
}
SurfaceBlockKind::Bookmark => {
bar = bar.child(text_action_btn(
"el-tb-media-open",
"chrome.edgeless_element_toolbar.media_open",
"Open".to_string(),
64.0,
false,
false,
palette,
EdgelessElementAction::MediaOpenLink,
cx,
));
advance(64.0, None);
bar = bar.child(icon_action_btn(
"el-tb-media-copy-link",
"chrome.edgeless_element_toolbar.media_copy_link",
"Copy link",
"LinkIcon",
false,
palette,
EdgelessElementAction::MediaCopyLink,
cx,
));
advance(BTN_SIZE, None);
if sb.can_toggle_view {
let view_label = if sb.is_embed_view { "Embed" } else { "Card" };
bar = bar.child(text_action_btn(
"el-tb-media-view",
"chrome.edgeless_element_toolbar.media_view",
view_label.to_string(),
68.0,
sb.is_embed_view,
false,
palette,
EdgelessElementAction::MediaToggleView,
cx,
));
advance(68.0, None);
}
bar = bar.child(text_action_btn(
"el-tb-media-style",
"chrome.edgeless_element_toolbar.media_style",
"Style".to_string(),
62.0,
open_sub == Some(ElementSubMenu::MediaStyle),
true,
palette,
EdgelessElementAction::ToggleSubMenu(ElementSubMenu::MediaStyle),
cx,
));
advance(62.0, Some(ElementSubMenu::MediaStyle));
bar = bar.child(text_action_btn(
"el-tb-media-caption",
"chrome.edgeless_element_toolbar.media_caption",
"Caption".to_string(),
56.0,
!sb.caption.is_empty(),
false,
palette,
EdgelessElementAction::MediaCaption,
cx,
));
advance(56.0, None);
}
SurfaceBlockKind::EmbedLinkedDoc
| SurfaceBlockKind::EmbedSyncedDoc
| SurfaceBlockKind::ExternalEmbed => {
bar = bar.child(text_action_btn(
"el-tb-media-open",
"chrome.edgeless_element_toolbar.media_open",
"Open".to_string(),
58.0,
false,
false,
palette,
EdgelessElementAction::MediaOpenLink,
cx,
));
advance(58.0, None);
bar = bar.child(icon_action_btn(
"el-tb-media-copy-link",
"chrome.edgeless_element_toolbar.media_copy_link",
"Copy link",
"LinkIcon",
false,
palette,
EdgelessElementAction::MediaCopyLink,
cx,
));
advance(BTN_SIZE, None);
let view_label = if sb.is_embed_view { "Embed" } else { "Card" };
bar = bar.child(text_action_btn(
"el-tb-media-view",
"chrome.edgeless_element_toolbar.media_view",
view_label.to_string(),
68.0,
sb.is_embed_view,
false,
palette,
EdgelessElementAction::MediaToggleView,
cx,
));
advance(68.0, None);
bar = bar.child(text_action_btn(
"el-tb-media-caption",
"chrome.edgeless_element_toolbar.media_caption",
"Caption".to_string(),
56.0,
!sb.caption.is_empty(),
false,
palette,
EdgelessElementAction::MediaCaption,
cx,
));
advance(56.0, None);
}
}
bar
}
#[allow(clippy::too_many_arguments)]
pub(super) fn build_media_style_menu<V: EdgelessElementToolbarHost>(
sb: &SurfaceBlockToolbarSummary,
trigger_rect: FlowRect,
viewport_width: f32,
viewport_height: f32,
palette: &Palette,
theme: PlaygroundTheme,
cx: &mut Context<V>,
) -> (AnyElement, FlowRect) {
let (panel_bg, border_col, shadows) = toolbar_chrome_tokens(palette, theme);
let styles: &[(&str, &str)] = match sb.kind {
SurfaceBlockKind::Attachment => &[("horizontal", "Horizontal"), ("cube", "Vertical")],
_ => &[
("horizontal", "Horizontal"),
("list", "List"),
("vertical", "Vertical"),
("cube", "Cube"),
],
};
const ROW_H: f32 = 28.0;
const GAP: f32 = 2.0;
const PAD: f32 = 4.0;
const SUB_W: f32 = 124.0;
let sub_h =
styles.len() as f32 * ROW_H + styles.len().saturating_sub(1) as f32 * GAP + 2.0 * PAD + 2.0;
let vp_rect = FlowRect::new(0.0, 0.0, viewport_width, viewport_height);
let placed = place_popover(
trigger_rect,
(SUB_W, sub_h),
vp_rect,
Placement::BelowStart,
8.0,
10.0,
);
let hover_bg = palette.hover;
let brand = palette.brand;
let mut sub = isolate_floating_chrome(
div()
.absolute()
.left(px(placed.rect.x))
.top(px(placed.rect.y))
.w(px(SUB_W))
.p(px(PAD))
.rounded(px(8.0))
.bg(panel_bg)
.border(px(0.5))
.border_color(border_col)
.flex()
.flex_col()
.gap(px(GAP)),
)
.snapshot(
"chrome.edgeless_element_toolbar.sub_menu",
Some(EDGELESS_VIEWPORT_ID),
);
for &(key, label) in styles {
let active = sb.card_style.eq_ignore_ascii_case(key);
let fg = if active { brand } else { palette.text_primary };
let key_str = key.to_string();
sub = sub.child(
div()
.id(SharedString::from(format!("el-tb-mstyle-{key}")))
.w_full()
.h(px(ROW_H))
.px(px(10.0))
.rounded(px(4.0))
.flex()
.items_center()
.text_size(px(TYPOGRAPHY.font_xs_px))
.font_weight(FontWeight::MEDIUM)
.text_color(fg)
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(
EdgelessElementAction::MediaSetCardStyle(key_str.clone()),
window,
cx,
);
}))
.snapshot(
SharedString::from(format!("chrome.edgeless_element_toolbar.sub.style_{key}")),
Some("chrome.edgeless_element_toolbar.sub_menu"),
)
.snapshot_text(label)
.child(div().flex_1().child(label))
.child(if active { "\u{2713}" } else { "" }),
);
}
if !shadows.is_empty() {
sub = sub.shadow(shadows.into());
}
(sub.into_any_element(), placed.rect)
}
@@ -1,7 +1,13 @@
//! Floating property toolbar (`Element Toolbar`) above selected Edgeless elements
//! (`Shape`, `Note`, `Connector`, `Brush`/`Highlighter`, `Text`, `Frame`, `Group`, `Mindmap`, multi-select).
//! (`Shape`, `Note`, `Connector`, `Brush`/`Highlighter`, `Text`, `Frame`, `Group`, `Mindmap`,
//! canvas media/embed blocks, and multi-select).
mod align_and_pickers;
mod bar_items;
mod color_popover;
mod media_toolbar;
mod more_menu;
mod note_style_panel;
mod palettes;
mod popovers;
mod render;
@@ -26,19 +32,36 @@ use ui::{Context, Hsla, Window};
use super::{
EDGELESS_VIEWPORT_ID, EdgelessAuthoringState, EdgelessCamera, ShapePreset, SpatialItemInfo,
SpatialItemKind, WorldRect, note_scale, note_shadow_type, parse_xywh, prop_bool, prop_f32,
resolve_edgeless_color,
SpatialItemKind, WorldRect, note_border_radius, note_border_style, note_collapse, note_scale,
note_shadow_type, parse_xywh, prop_bool, prop_f32, resolve_edgeless_color,
};
/// Note shadow style presets matching BlockSuite `blocks/note/src/configs/toolbar.ts`.
pub const NOTE_SHADOW_PRESETS: [(&str, &str, &str); 5] = [
("box", "Box", "--affine-note-shadow-box"),
/// Note shadow style presets matching BlockSuite `blocks/note/src/configs/toolbar.ts`
/// and `edgeless-note-shadow-menu.ts` (6 presets including `Float`).
pub const NOTE_SHADOW_PRESETS: [(&str, &str, &str); 6] = [
("none", "No shadow", ""),
("box", "Default", "--affine-note-shadow-box"),
("film", "Film", "--affine-note-shadow-film"),
("sticker", "Sticker", "--affine-note-shadow-sticker"),
("paper", "Paper", "--affine-note-shadow-paper"),
("none", "None", ""),
("float", "Float", "--affine-note-shadow-float"),
];
/// Note border width presets matching BlockSuite `NOTE_BORDER_SIZE_OPTIONS`.
pub const NOTE_BORDER_SIZES: [f64; 6] = [2.0, 4.0, 6.0, 8.0, 10.0, 12.0];
/// Note corner radius presets matching BlockSuite `NOTE_CORNER_RADIUS_OPTIONS`.
pub const NOTE_CORNER_RADII: [(&str, f64); 5] = [
("None", 0.0),
("S", 8.0),
("M", 16.0),
("L", 24.0),
("XL", 32.0),
];
/// Note and canvas media scale presets matching BlockSuite `edgeless-note-scale-menu`.
pub const NOTE_SCALE_PRESETS: [f64; 6] = [0.5, 0.75, 1.0, 1.25, 1.5, 2.0];
/// Which color swatch picker sub-pill is currently open on the element toolbar.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ElementColorSlot {
@@ -51,15 +74,23 @@ pub enum ElementColorSlot {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ElementSubMenu {
Align,
ShapeType,
ConnectorMode,
ConnectorCaps,
TextAlign,
LineWidth,
FontSize,
NoteStyle,
NoteShadow,
NoteScale,
MediaStyle,
MediaScale,
MindmapStyle,
MindmapLayout,
More,
}
/// Multi-select alignment & distribution operations.
/// Multi-select alignment, distribution, and auto-arrange operations.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AlignOp {
Left,
@@ -70,6 +101,34 @@ pub enum AlignOp {
Bottom,
DistributeH,
DistributeV,
AutoArrange,
}
/// Classification of a spatial media/embed block selected on the Edgeless canvas.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SurfaceBlockKind {
Image,
Attachment,
Bookmark,
EmbedLinkedDoc,
EmbedSyncedDoc,
ExternalEmbed,
}
/// Summary of a single selected canvas media or embed block (`SpatialItemKind::SurfaceBlock`).
#[derive(Clone, Debug, PartialEq)]
pub struct SurfaceBlockToolbarSummary {
pub block_id: String,
pub kind: SurfaceBlockKind,
pub url: Option<String>,
pub title: String,
pub caption: String,
pub card_style: String,
pub is_embed_view: bool,
pub can_toggle_view: bool,
pub can_download: bool,
pub scale: f32,
pub rotate_deg: f32,
}
/// Property mutation, sub-picker toggle, or common element action dispatched from
@@ -98,10 +157,20 @@ pub enum EdgelessElementAction {
SetConnectorRearEndpoint(EndpointStyle),
FlipConnectorDirection,
AddConnectorLabel,
AddText,
DrawConnector,
SetNoteShadow(String),
SetNoteBorderStyle(StrokeStyle),
SetNoteBorderSize(f64),
SetNoteBorderRadius(f64),
ToggleNoteAutoHeight,
SetNoteScale(f64),
ToggleNoteDisplayMode,
SliceNoteAt(usize),
InsertFrameIntoPage,
InsertGroupIntoPage,
WrapInFrame,
ReleaseFromGroup,
Rename,
Group,
Ungroup,
@@ -113,10 +182,22 @@ pub enum EdgelessElementAction {
AddMindmapChild,
AddMindmapSibling,
BringToFront,
BringForward,
SendBackward,
SendToBack,
Copy,
Duplicate,
Delete,
MediaCaption,
MediaToggleView,
MediaSetCardStyle(String),
MediaOpenLink,
MediaCopyLink,
MediaDownload,
MediaRotateCw,
MediaSetScale(f64),
MediaReload,
MediaInfo,
}
/// Host callback for executing Edgeless element toolbar actions.
@@ -145,9 +226,12 @@ pub struct MindmapToolbarSummary {
#[derive(Clone, Debug)]
pub struct ElementToolbarSummary {
pub is_locked: bool,
pub can_release_from_group: bool,
pub can_wrap_frame: bool,
pub can_group: bool,
pub can_align: bool,
pub can_distribute: bool,
pub can_draw_connector: bool,
pub has_fill: bool,
pub has_stroke: bool,
pub has_text_color: bool,
@@ -158,14 +242,19 @@ pub struct ElementToolbarSummary {
pub has_font_size: bool,
pub has_shape_type: bool,
pub has_connector_props: bool,
pub shape_has_text: bool,
pub connector_has_label: bool,
pub can_add_text: bool,
pub has_note_display: bool,
pub has_note_shadow: bool,
pub note_is_page_root: bool,
pub has_frame_actions: bool,
pub has_group_actions: bool,
pub is_highlighter_width: bool,
pub is_note_fill: bool,
pub is_shape_text: bool,
pub mindmap: Option<MindmapToolbarSummary>,
pub surface_block: Option<SurfaceBlockToolbarSummary>,
pub fill_color: Hsla,
pub stroke_color: Hsla,
pub text_color: Hsla,
@@ -183,4 +272,9 @@ pub struct ElementToolbarSummary {
pub rear_endpoint: EndpointStyle,
pub note_in_page: bool,
pub note_shadow: String,
pub note_border_style: StrokeStyle,
pub note_border_size: f64,
pub note_border_radius: f64,
pub note_auto_height: bool,
pub note_scale: f32,
}
@@ -0,0 +1,296 @@
//! Right-side `⋮ More` dropdown menu for `chrome.edgeless_element_toolbar`
//! (BlockSuite `0.27.5` `misc.ts` / `more.ts`: 30 px rows, 176 px min width, 4-level z-order,
//! Copy / Duplicate / Reload / Info, and hover-only destructive red Delete).
use ui::{
AnyElement, ClickEvent, Context, FontWeight, Hsla, MouseButton, SharedString, canvas, div,
prelude::*, px,
};
use crate::{
block_flow::FlowRect,
overlays::{Placement, place_popover},
theme::{IconPaint, Palette, PlaygroundTheme, TYPOGRAPHY},
};
use super::{
EDGELESS_VIEWPORT_ID, EdgelessElementAction, EdgelessElementToolbarHost, ElementToolbarSummary,
SurfaceBlockKind,
widgets::{isolate_floating_chrome, toolbar_chrome_tokens},
};
const MENU_MIN_W: f32 = 200.0;
const ROW_H: f32 = 30.0;
const MENU_PAD: f32 = 6.0;
const ROW_GAP: f32 = 2.0;
const SEP_H: f32 = 9.0;
#[cfg(target_os = "macos")]
const COPY_SHORTCUT: &str = "⌘C";
#[cfg(not(target_os = "macos"))]
const COPY_SHORTCUT: &str = "Ctrl+C";
#[cfg(target_os = "macos")]
const DUPLICATE_SHORTCUT: &str = "⌘D";
#[cfg(not(target_os = "macos"))]
const DUPLICATE_SHORTCUT: &str = "Ctrl+D";
#[cfg(target_os = "macos")]
const DELETE_SHORTCUT: &str = "⌫";
#[cfg(not(target_os = "macos"))]
const DELETE_SHORTCUT: &str = "Del";
struct MoreMenuItem {
id: &'static str,
label: &'static str,
icon: &'static str,
shortcut: Option<&'static str>,
action: EdgelessElementAction,
destructive: bool,
}
fn menu_separator(border_col: Hsla) -> ui::Div {
div()
.w_full()
.h(px(SEP_H))
.flex()
.items_center()
.child(div().w_full().h(px(0.5)).bg(border_col))
}
#[allow(clippy::too_many_arguments)]
pub(super) fn build_more_menu<V: EdgelessElementToolbarHost>(
summary: &ElementToolbarSummary,
trigger_rect: FlowRect,
viewport_width: f32,
viewport_height: f32,
palette: &Palette,
theme: PlaygroundTheme,
cx: &mut Context<V>,
) -> (AnyElement, FlowRect) {
let (panel_bg, border_col, shadows) = toolbar_chrome_tokens(palette, theme);
let hover_bg = palette.hover;
let danger_fg = theme
.css_color("--affine-error-color")
.unwrap_or(palette.text_primary);
let danger_bg = theme
.css_color("--affine-background-error-color")
.unwrap_or(danger_fg.opacity(0.12));
let mut sections: Vec<Vec<MoreMenuItem>> = Vec::new();
if summary.has_frame_actions {
sections.push(vec![MoreMenuItem {
id: "insert_page",
label: "Insert into Page",
icon: "PageIcon",
shortcut: None,
action: EdgelessElementAction::InsertFrameIntoPage,
destructive: false,
}]);
} else if summary.has_group_actions {
sections.push(vec![MoreMenuItem {
id: "insert_group_page",
label: "Insert into Page",
icon: "PageIcon",
shortcut: None,
action: EdgelessElementAction::InsertGroupIntoPage,
destructive: false,
}]);
}
sections.push(vec![
MoreMenuItem {
id: "bring_to_front",
label: "Bring to front",
icon: "MoveRightIcon",
shortcut: None,
action: EdgelessElementAction::BringToFront,
destructive: false,
},
MoreMenuItem {
id: "bring_forward",
label: "Bring forward",
icon: "MoveRightIcon",
shortcut: None,
action: EdgelessElementAction::BringForward,
destructive: false,
},
MoreMenuItem {
id: "send_backward",
label: "Send backward",
icon: "MoveLeftIcon",
shortcut: None,
action: EdgelessElementAction::SendBackward,
destructive: false,
},
MoreMenuItem {
id: "send_to_back",
label: "Send to back",
icon: "MoveLeftIcon",
shortcut: None,
action: EdgelessElementAction::SendToBack,
destructive: false,
},
]);
let mut clip_section = vec![
MoreMenuItem {
id: "copy",
label: "Copy",
icon: "CopyIcon",
shortcut: Some(COPY_SHORTCUT),
action: EdgelessElementAction::Copy,
destructive: false,
},
MoreMenuItem {
id: "duplicate",
label: "Duplicate",
icon: "DuplicateIcon",
shortcut: Some(DUPLICATE_SHORTCUT),
action: EdgelessElementAction::Duplicate,
destructive: false,
},
];
if let Some(sb) = &summary.surface_block {
if matches!(
sb.kind,
SurfaceBlockKind::Bookmark
| SurfaceBlockKind::EmbedLinkedDoc
| SurfaceBlockKind::EmbedSyncedDoc
| SurfaceBlockKind::ExternalEmbed
) {
clip_section.push(MoreMenuItem {
id: "reload",
label: "Reload",
icon: "RedoIcon",
shortcut: None,
action: EdgelessElementAction::MediaReload,
destructive: false,
});
}
clip_section.push(MoreMenuItem {
id: "info",
label: "Info",
icon: "InformationIcon",
shortcut: None,
action: EdgelessElementAction::MediaInfo,
destructive: false,
});
}
sections.push(clip_section);
sections.push(vec![MoreMenuItem {
id: "delete",
label: "Delete",
icon: "DeleteIcon",
shortcut: Some(DELETE_SHORTCUT),
action: EdgelessElementAction::Delete,
destructive: true,
}]);
let total_rows: usize = sections.iter().map(Vec::len).sum();
let sep_count = sections.len().saturating_sub(1);
let menu_h = total_rows as f32 * ROW_H
+ total_rows.saturating_sub(1) as f32 * ROW_GAP
+ sep_count as f32 * SEP_H
+ 2.0 * MENU_PAD
+ 2.0;
let vp_rect = FlowRect::new(0.0, 0.0, viewport_width, viewport_height);
let placed = place_popover(
trigger_rect,
(MENU_MIN_W, menu_h),
vp_rect,
Placement::BelowStart,
8.0,
10.0,
);
let mut menu = isolate_floating_chrome(
div()
.absolute()
.left(px(placed.rect.x))
.top(px(placed.rect.y))
.w(px(MENU_MIN_W))
.p(px(MENU_PAD))
.rounded(px(8.0))
.bg(panel_bg)
.border(px(0.5))
.border_color(border_col)
.flex()
.flex_col()
.gap(px(ROW_GAP)),
)
.snapshot(
"chrome.edgeless_element_toolbar.more_menu",
Some(EDGELESS_VIEWPORT_ID),
);
for (sec_idx, section) in sections.into_iter().enumerate() {
if sec_idx > 0 {
menu = menu.child(menu_separator(border_col));
}
for item in section {
let icon_col = palette.icon;
let text_col = palette.text_primary;
let action = item.action.clone();
let icon_name = item.icon;
let destructive = item.destructive;
let mut row = div()
.id(SharedString::from(format!("el-tb-more-{}", item.id)))
.w_full()
.h(px(ROW_H))
.px(px(8.0))
.rounded(px(4.0))
.flex()
.items_center()
.gap(px(8.0))
.text_size(px(TYPOGRAPHY.font_xs_px))
.font_weight(FontWeight::MEDIUM)
.text_color(text_col)
.cursor_pointer()
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(action.clone(), window, cx);
}))
.snapshot(
SharedString::from(format!("chrome.edgeless_element_toolbar.more.{}", item.id)),
Some("chrome.edgeless_element_toolbar.more_menu"),
)
.snapshot_text(item.label)
.child(
canvas(
|_, _, _| (),
move |bounds, _, window, cx| {
IconPaint::named(icon_name).paint(bounds, icon_col, window, cx);
},
)
.w(px(18.0))
.h(px(18.0)),
)
.child(div().flex_1().child(item.label))
.when_some(item.shortcut, |row, sc| {
row.child(
div()
.text_size(px(11.0))
.font_weight(FontWeight::NORMAL)
.text_color(palette.text_secondary)
.child(sc),
)
});
if destructive {
row = row.hover(move |s| s.bg(danger_bg).text_color(danger_fg));
} else {
row = row.hover(move |s| s.bg(hover_bg));
}
menu = menu.child(row);
}
}
if !shadows.is_empty() {
menu = menu.shadow(shadows.into());
}
(menu.into_any_element(), placed.rect)
}
@@ -0,0 +1,512 @@
//! Complete Note style panel and scale dropdown for `chrome.edgeless_element_toolbar`
//! matching BlockSuite `blocks/note/src/configs/toolbar.ts` and `edgeless-note-style-panel.ts`:
//! - 9 Note background color swatches
//! - 6 Shadows including `Float` (`--affine-note-shadow-float`)
//! - Border style (`None` / `Solid` / `Dash`) + border width (`2..12`)
//! - Corner radius presets (`0 / 8 / 16 / 24 / 32`)
//! - Auto-height / custom-height toggle + `Scale %` dropdown (`50%..200%`).
use blocksuite_playground_doc::read::StrokeStyle;
use ui::{
AnyElement, BorderStyle, Bounds, ClickEvent, Context, Corners, Edges, FontWeight, MouseButton,
SharedString, canvas, div, point, prelude::*, px, size,
};
use crate::{
block_flow::FlowRect,
overlays::{Placement, place_popover},
theme::{Palette, PlaygroundTheme, TYPOGRAPHY},
};
use super::{
EDGELESS_VIEWPORT_ID, EdgelessElementAction, EdgelessElementToolbarHost, ElementColorSlot,
ElementToolbarSummary, NOTE_BACKGROUND_PALETTES, NOTE_BORDER_SIZES, NOTE_CORNER_RADII,
NOTE_SCALE_PRESETS, NOTE_SHADOW_PRESETS, color_value_matches_swatch,
widgets::{isolate_floating_chrome, toolbar_chrome_tokens},
};
fn section_title(label: &'static str, palette: &Palette) -> ui::Div {
div()
.text_size(px(11.0))
.font_weight(FontWeight::MEDIUM)
.text_color(palette.text_secondary)
.child(label)
}
#[allow(clippy::too_many_arguments)]
pub(super) fn build_note_style_panel<V: EdgelessElementToolbarHost>(
summary: &ElementToolbarSummary,
trigger_rect: FlowRect,
viewport_width: f32,
viewport_height: f32,
palette: &Palette,
theme: PlaygroundTheme,
cx: &mut Context<V>,
) -> (AnyElement, FlowRect) {
let (panel_bg, border_col, shadows) = toolbar_chrome_tokens(palette, theme);
let hover_bg = palette.hover;
let brand = palette.brand;
let slash_col = theme
.css_color("--affine-error-color")
.unwrap_or(palette.brand);
const PANEL_W: f32 = 274.0;
const PANEL_H: f32 = 316.0;
let vp_rect = FlowRect::new(0.0, 0.0, viewport_width, viewport_height);
let placed = place_popover(
trigger_rect,
(PANEL_W, PANEL_H),
vp_rect,
Placement::BelowStart,
8.0,
10.0,
);
let mut panel = isolate_floating_chrome(
div()
.absolute()
.left(px(placed.rect.x))
.top(px(placed.rect.y))
.w(px(PANEL_W))
.p(px(12.0))
.rounded(px(8.0))
.bg(panel_bg)
.border(px(0.5))
.border_color(border_col)
.flex()
.flex_col()
.gap(px(10.0)),
)
.snapshot(
"chrome.edgeless_element_toolbar.note_style_panel",
Some(EDGELESS_VIEWPORT_ID),
);
// 1. Background color swatches (9 Note colors).
panel = panel.child(section_title("Background", palette));
let mut color_row = div().flex().items_center().gap(px(4.0));
for swatch in NOTE_BACKGROUND_PALETTES {
let color = swatch.resolve_hsla(theme);
let is_transparent = swatch.is_transparent();
let selected = color_value_matches_swatch(&summary.fill_color_value, swatch, theme, false);
let wire_val = swatch.to_color_value();
let swatch_bg = if is_transparent {
ui::Hsla::white()
} else {
color
};
color_row = color_row.child(
div()
.id(SharedString::from(format!("el-tb-note-bg-{}", swatch.key)))
.w(px(24.0))
.h(px(24.0))
.rounded(px(12.0))
.flex()
.items_center()
.justify_center()
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(
EdgelessElementAction::SetColor {
slot: ElementColorSlot::Fill,
color: wire_val.clone(),
},
window,
cx,
);
}))
.snapshot(
SharedString::from(format!(
"chrome.edgeless_element_toolbar.note_style.bg.{}",
swatch.key
)),
Some("chrome.edgeless_element_toolbar.note_style_panel"),
)
.snapshot_text(swatch.key)
.child(
canvas(
|_, _, _| (),
move |bounds, _, window, _| {
let ox = f32::from(bounds.origin.x);
let oy = f32::from(bounds.origin.y);
let side = 16.0_f32;
let dx = (f32::from(bounds.size.width) - side) * 0.5;
let dy = (f32::from(bounds.size.height) - side) * 0.5;
if selected {
window.paint_quad(ui::quad(
Bounds::new(
point(px(ox + dx - 3.0), px(oy + dy - 3.0)),
size(px(side + 6.0), px(side + 6.0)),
),
Corners::all(px((side + 6.0) * 0.5)),
ui::transparent_black(),
Edges::all(px(1.5)),
brand,
BorderStyle::Solid,
));
}
window.paint_quad(ui::quad(
Bounds::new(
point(px(ox + dx), px(oy + dy)),
size(px(side), px(side)),
),
Corners::all(px(side * 0.5)),
swatch_bg,
Edges::all(px(0.5)),
border_col,
BorderStyle::Solid,
));
if is_transparent {
let mut pb = ui::PathBuilder::stroke(px(1.5));
pb.move_to(point(px(ox + dx + 3.0), px(oy + dy + side - 3.0)));
pb.line_to(point(px(ox + dx + side - 3.0), px(oy + dy + 3.0)));
if let Ok(path) = pb.build() {
window.paint_path(path, slash_col);
}
}
},
)
.w(px(24.0))
.h(px(24.0)),
),
);
}
panel = panel.child(color_row);
// 2. Shadow presets (6 presets including Float).
panel = panel.child(section_title("Shadow", palette));
let mut shadow_row = div().flex().flex_wrap().gap(px(4.0));
for &(id, label, token) in &NOTE_SHADOW_PRESETS {
let active = summary.note_shadow == token;
let token_str = token.to_string();
let fg = if active { brand } else { palette.text_primary };
let b_col = if active { brand } else { border_col };
shadow_row = shadow_row.child(
div()
.id(SharedString::from(format!("el-tb-note-shadow-{id}")))
.px(px(8.0))
.h(px(26.0))
.rounded(px(4.0))
.border(px(if active { 1.0 } else { 0.5 }))
.border_color(b_col)
.flex()
.items_center()
.justify_center()
.text_size(px(TYPOGRAPHY.font_xs_px))
.font_weight(FontWeight::MEDIUM)
.text_color(fg)
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(
EdgelessElementAction::SetNoteShadow(token_str.clone()),
window,
cx,
);
}))
.snapshot(
SharedString::from(format!(
"chrome.edgeless_element_toolbar.note_style.shadow.{id}"
)),
Some("chrome.edgeless_element_toolbar.note_style_panel"),
)
.snapshot_text(label)
.child(label),
);
}
panel = panel.child(shadow_row);
// 3. Border style (None / Solid / Dash) + Border size (2..12).
panel = panel.child(section_title("Border", palette));
let mut border_row = div().flex().items_center().gap(px(4.0));
for (id, label, style) in [
("none", "None", StrokeStyle::None),
("solid", "Solid", StrokeStyle::Solid),
("dash", "Dash", StrokeStyle::Dash),
] {
let active = summary.note_border_style == style;
let fg = if active { brand } else { palette.text_primary };
let b_col = if active { brand } else { border_col };
border_row = border_row.child(
div()
.id(SharedString::from(format!("el-tb-note-bs-{id}")))
.px(px(8.0))
.h(px(24.0))
.rounded(px(4.0))
.border(px(if active { 1.0 } else { 0.5 }))
.border_color(b_col)
.flex()
.items_center()
.justify_center()
.text_size(px(TYPOGRAPHY.font_xs_px))
.font_weight(FontWeight::MEDIUM)
.text_color(fg)
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(
EdgelessElementAction::SetNoteBorderStyle(style),
window,
cx,
);
}))
.snapshot(
SharedString::from(format!(
"chrome.edgeless_element_toolbar.note_style.border.{id}"
)),
Some("chrome.edgeless_element_toolbar.note_style_panel"),
)
.snapshot_text(label)
.child(label),
);
}
panel = panel.child(border_row);
let mut bsize_row = div().flex().items_center().gap(px(4.0));
for &bs in &NOTE_BORDER_SIZES {
let bs_i = bs.round() as i32;
let active = summary.note_border_style != StrokeStyle::None
&& (summary.note_border_size - bs).abs() < 0.5;
let fg = if active { brand } else { palette.text_primary };
let b_col = if active { brand } else { border_col };
bsize_row = bsize_row.child(
div()
.id(SharedString::from(format!("el-tb-note-bw-{bs_i}")))
.w(px(36.0))
.h(px(24.0))
.rounded(px(4.0))
.border(px(if active { 1.0 } else { 0.5 }))
.border_color(b_col)
.flex()
.items_center()
.justify_center()
.text_size(px(11.0))
.font_weight(FontWeight::MEDIUM)
.text_color(fg)
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(
EdgelessElementAction::SetNoteBorderSize(bs),
window,
cx,
);
}))
.snapshot(
SharedString::from(format!(
"chrome.edgeless_element_toolbar.note_style.border_size.{bs_i}"
)),
Some("chrome.edgeless_element_toolbar.note_style_panel"),
)
.snapshot_text(format!("{bs_i}px"))
.child(format!("{bs_i}px")),
);
}
panel = panel.child(bsize_row);
// 4. Corner radius presets (0 / 8 / 16 / 24 / 32).
panel = panel.child(section_title("Corner radius", palette));
let mut radius_row = div().flex().items_center().gap(px(4.0));
for &(label, rad) in &NOTE_CORNER_RADII {
let rad_i = rad.round() as i32;
let active = (summary.note_border_radius - rad).abs() < 0.5;
let fg = if active { brand } else { palette.text_primary };
let b_col = if active { brand } else { border_col };
radius_row = radius_row.child(
div()
.id(SharedString::from(format!("el-tb-note-rad-{rad_i}")))
.flex_1()
.h(px(24.0))
.rounded(px(4.0))
.border(px(if active { 1.0 } else { 0.5 }))
.border_color(b_col)
.flex()
.items_center()
.justify_center()
.text_size(px(11.0))
.font_weight(FontWeight::MEDIUM)
.text_color(fg)
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(
EdgelessElementAction::SetNoteBorderRadius(rad),
window,
cx,
);
}))
.snapshot(
SharedString::from(format!(
"chrome.edgeless_element_toolbar.note_style.radius.{rad_i}"
)),
Some("chrome.edgeless_element_toolbar.note_style_panel"),
)
.snapshot_text(label)
.child(label),
);
}
panel = panel.child(radius_row);
// 5. Auto-height toggle.
let auto_fg = if summary.note_auto_height {
brand
} else {
palette.text_primary
};
let auto_b = if summary.note_auto_height {
brand
} else {
border_col
};
let auto_label = if summary.note_auto_height {
"Height: Auto"
} else {
"Height: Custom"
};
panel = panel.child(
div()
.id("el-tb-note-auto-height")
.w_full()
.h(px(28.0))
.px(px(8.0))
.rounded(px(4.0))
.border(px(0.5))
.border_color(auto_b)
.flex()
.items_center()
.justify_center()
.text_size(px(TYPOGRAPHY.font_xs_px))
.font_weight(FontWeight::MEDIUM)
.text_color(auto_fg)
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(|this, _: &ClickEvent, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(
EdgelessElementAction::ToggleNoteAutoHeight,
window,
cx,
);
}))
.snapshot(
"chrome.edgeless_element_toolbar.note_style.auto_height",
Some("chrome.edgeless_element_toolbar.note_style_panel"),
)
.snapshot_text(auto_label)
.child(auto_label),
);
if !shadows.is_empty() {
panel = panel.shadow(shadows.into());
}
(panel.into_any_element(), placed.rect)
}
#[allow(clippy::too_many_arguments)]
pub(super) fn build_scale_dropdown<V: EdgelessElementToolbarHost>(
current_scale: f32,
is_media: bool,
trigger_rect: FlowRect,
viewport_width: f32,
viewport_height: f32,
palette: &Palette,
theme: PlaygroundTheme,
cx: &mut Context<V>,
) -> (AnyElement, FlowRect) {
let (panel_bg, border_col, shadows) = toolbar_chrome_tokens(palette, theme);
const ROW_H: f32 = 28.0;
const GAP: f32 = 2.0;
const PAD: f32 = 4.0;
const SUB_W: f32 = 92.0;
let sub_h = NOTE_SCALE_PRESETS.len() as f32 * ROW_H
+ NOTE_SCALE_PRESETS.len().saturating_sub(1) as f32 * GAP
+ 2.0 * PAD
+ 2.0;
let vp_rect = FlowRect::new(0.0, 0.0, viewport_width, viewport_height);
let placed = place_popover(
trigger_rect,
(SUB_W, sub_h),
vp_rect,
Placement::BelowStart,
8.0,
10.0,
);
let hover_bg = palette.hover;
let brand = palette.brand;
let mut sub = isolate_floating_chrome(
div()
.absolute()
.left(px(placed.rect.x))
.top(px(placed.rect.y))
.w(px(SUB_W))
.p(px(PAD))
.rounded(px(8.0))
.bg(panel_bg)
.border(px(0.5))
.border_color(border_col)
.flex()
.flex_col()
.gap(px(GAP)),
)
.snapshot(
"chrome.edgeless_element_toolbar.sub_menu",
Some(EDGELESS_VIEWPORT_ID),
);
for &sc in &NOTE_SCALE_PRESETS {
let pct = (sc * 100.0).round() as i32;
let active = (current_scale as f64 - sc).abs() < 0.02;
let label = format!("{pct}%");
let text_col = if active { brand } else { palette.text_primary };
let action = if is_media {
EdgelessElementAction::MediaSetScale(sc)
} else {
EdgelessElementAction::SetNoteScale(sc)
};
sub = sub.child(
div()
.id(SharedString::from(format!("el-tb-scale-{pct}")))
.w_full()
.h(px(ROW_H))
.px(px(10.0))
.rounded(px(4.0))
.flex()
.items_center()
.text_size(px(TYPOGRAPHY.font_xs_px))
.font_weight(FontWeight::MEDIUM)
.text_color(text_col)
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(action.clone(), window, cx);
}))
.snapshot(
SharedString::from(format!("chrome.edgeless_element_toolbar.sub.scale_{pct}")),
Some("chrome.edgeless_element_toolbar.sub_menu"),
)
.snapshot_text(label.clone())
.child(div().flex_1().child(label))
.child(if active { "\u{2713}" } else { "" }),
);
}
if !shadows.is_empty() {
sub = sub.shadow(shadows.into());
}
(sub.into_any_element(), placed.rect)
}
@@ -1,36 +1,55 @@
//! Sub-popovers anchored above `chrome.edgeless_element_toolbar`:
//! line-width rail, font-size dropdown, multi-select Align & Distribute, Connector endpoints,
//! Note shadow, and Mindmap style/layout.
//! Sub-popovers anchored horizontally to their respective trigger button on
//! `chrome.edgeless_element_toolbar`: line-width rail, font-size dropdown, `4×2` Align grid +
//! Auto arrange, Shape type picker, Connector mode/caps, Text align, Mindmap style/layout,
//! and dispatch to `more_menu`, `note_style_panel`, and `media_toolbar`.
use blocksuite_playground_doc::read::{EndpointStyle, MindmapLayoutType, MindmapStyle};
use blocksuite_playground_doc::read::{
ConnectorMode, EndpointStyle, MindmapLayoutType, MindmapStyle, TextAlign,
};
use ui::{
AnyElement, Bounds, Context, FontWeight, MouseButton, SharedString, canvas, div, point,
prelude::*, px, size,
AnyElement, ClickEvent, Context, FontWeight, MouseButton, SharedString, canvas, div, point,
prelude::*, px,
};
use crate::{
block_flow::FlowRect,
overlays::{PlacedPopover, Placement, place_popover},
theme::{Palette, TYPOGRAPHY},
overlays::{PlacedPopover, Placement, align_glyph, place_popover},
theme::{IconPaint, Palette, PlaygroundTheme, TYPOGRAPHY},
};
use super::{
AlignOp, BRUSH_LINE_WIDTHS, EDGELESS_VIEWPORT_ID, EdgelessAuthoringState, EdgelessCamera,
EdgelessElementAction, EdgelessElementToolbarHost, ElementSubMenu, ElementToolbarSummary,
FONT_SIZE_LIST, HIGHLIGHTER_LINE_WIDTHS, NOTE_SHADOW_PRESETS, SpatialItemKind,
EDGELESS_VIEWPORT_ID, EdgelessAuthoringState, EdgelessCamera, EdgelessElementAction,
EdgelessElementToolbarHost, ElementSubMenu, ElementToolbarSummary, ShapePreset,
SpatialItemKind,
align_and_pickers::{
build_align_grid_popover, build_font_size_dropdown, build_line_width_panel,
},
media_toolbar::build_media_style_menu,
more_menu::build_more_menu,
note_style_panel::{build_note_style_panel, build_scale_dropdown},
widgets::{attach_tooltip, isolate_floating_chrome, toolbar_chrome_tokens},
};
/// Place the floating toolbar above `anchor` while clearing any visible Frame header pill
/// or Frame top border that overlaps or crowds the candidate toolbar box.
pub(super) fn place_clearing_frame_pills(
/// Place the floating toolbar with `top-start` horizontal alignment (or centered when `centered`),
/// flipping below when near the top edge and clearing any colliding Frame title pills.
pub(super) fn place_toolbar_rect(
authoring: &EdgelessAuthoringState,
camera: EdgelessCamera,
vp_origin: ui::Point<ui::Pixels>,
anchor: FlowRect,
bar_size: (f32, f32),
vp_rect: FlowRect,
centered: bool,
) -> PlacedPopover {
let placed = place_popover(anchor, bar_size, vp_rect, Placement::Above, 10.0, 8.0);
let place = |a: FlowRect| -> PlacedPopover {
let mut p = place_popover(a, bar_size, vp_rect, Placement::Above, 10.0, 10.0);
if !centered {
let max_x = (vp_rect.right() - bar_size.0 - 10.0).max(vp_rect.x + 10.0);
p.rect.x = a.x.clamp(vp_rect.x + 10.0, max_x).round();
}
p
};
let placed = place(anchor);
let mut min_clear_y: Option<f32> = None;
for item in authoring.painted_items.iter() {
if item.kind != SpatialItemKind::Frame {
@@ -75,357 +94,377 @@ pub(super) fn place_clearing_frame_pills(
{
let lift = anchor.y - clear_top;
let lifted = FlowRect::new(anchor.x, clear_top, anchor.w, anchor.h + lift);
return place_popover(lifted, bar_size, vp_rect, Placement::Above, 10.0, 8.0);
return place(lifted);
}
placed
}
#[allow(clippy::too_many_arguments)]
fn build_line_width_panel<V: EdgelessElementToolbarHost>(
summary: &ElementToolbarSummary,
bar_rect: FlowRect,
fn build_icon_strip_menu<V: EdgelessElementToolbarHost>(
items: Vec<(
&'static str,
&'static str,
&'static str,
bool,
EdgelessElementAction,
)>,
trigger_rect: FlowRect,
viewport_width: f32,
viewport_height: f32,
palette: &Palette,
shadows: Vec<ui::BoxShadow>,
theme: PlaygroundTheme,
cx: &mut Context<V>,
) -> AnyElement {
let widths: &[f64] = if summary.is_highlighter_width {
&HIGHLIGHTER_LINE_WIDTHS
} else {
&BRUSH_LINE_WIDTHS
};
const CELL: f32 = 26.0;
) -> (AnyElement, FlowRect) {
let (panel_bg, border_col, shadows) = toolbar_chrome_tokens(palette, theme);
const BTN: f32 = 28.0;
const GAP: f32 = 4.0;
const PAD: f32 = 6.0;
const READOUT_W: f32 = 38.0;
let sub_w = widths.len() as f32 * CELL
+ widths.len().saturating_sub(1) as f32 * GAP
+ GAP
+ READOUT_W
+ 2.0 * PAD
+ 2.0;
let sub_h = CELL + 2.0 * PAD + 2.0;
let sub_w =
items.len() as f32 * BTN + items.len().saturating_sub(1) as f32 * GAP + 2.0 * PAD + 2.0;
let sub_h = BTN + 2.0 * PAD + 2.0;
let vp_rect = FlowRect::new(0.0, 0.0, viewport_width, viewport_height);
let placed_sub = place_popover(
bar_rect,
let placed = place_popover(
trigger_rect,
(sub_w, sub_h),
vp_rect,
Placement::Above,
6.0,
8.0,
10.0,
);
let hover_bg = palette.hover;
let brand = palette.brand;
let icon_col = palette.icon;
let rail_col = palette.border;
let mut sub = div()
.absolute()
.left(px(placed_sub.rect.x))
.top(px(placed_sub.rect.y))
.p(px(PAD))
.rounded(px(8.0))
.bg(palette.panel)
.border_1()
.border_color(palette.border)
.flex()
.items_center()
.gap(px(GAP))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.snapshot(
"chrome.edgeless_element_toolbar.sub_menu",
Some(EDGELESS_VIEWPORT_ID),
);
for (idx, &w_val) in widths.iter().enumerate() {
let active = (summary.stroke_width - w_val).abs() < 0.5;
let dot_px = 5.0 + idx as f32 * 2.0;
let w_int = w_val.round() as i32;
let show_left_rail = idx > 0;
let show_right_rail = idx + 1 < widths.len();
sub = sub.child(
div()
.id(SharedString::from(format!("el-tb-lw-{w_int}")))
.w(px(CELL))
.h(px(CELL))
.rounded(px(4.0))
.flex()
.items_center()
.justify_center()
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.when(active, |el| el.bg(brand.opacity(0.14)))
.on_mouse_down(
MouseButton::Left,
cx.listener(move |this, _, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(
EdgelessElementAction::SetStrokeWidth(w_val),
window,
cx,
);
}),
)
.snapshot(
SharedString::from(format!("chrome.edgeless_element_toolbar.sub.lw_{w_int}")),
Some("chrome.edgeless_element_toolbar.sub_menu"),
)
.snapshot_text(format!("{w_int}px"))
.child(
canvas(
|_, _, _| (),
move |bounds, _, window, _| {
let ox = f32::from(bounds.origin.x);
let oy = f32::from(bounds.origin.y);
let bw = f32::from(bounds.size.width);
let bh = f32::from(bounds.size.height);
let cx_b = ox + bw * 0.5;
let cy_b = oy + bh * 0.5;
if show_left_rail {
window.paint_quad(ui::fill(
Bounds::new(
point(px(ox), px(cy_b - 0.75)),
size(px(bw * 0.5), px(1.5)),
),
rail_col,
));
}
if show_right_rail {
window.paint_quad(ui::fill(
Bounds::new(
point(px(cx_b), px(cy_b - 0.75)),
size(px(bw * 0.5), px(1.5)),
),
rail_col,
));
}
let r = dot_px * 0.5;
window.paint_quad(
ui::fill(
Bounds::new(
point(px(cx_b - r), px(cy_b - r)),
size(px(dot_px), px(dot_px)),
),
if active { brand } else { icon_col },
)
.corner_radii(px(r)),
);
},
)
.w(px(CELL))
.h(px(CELL)),
),
);
}
let readout = format!("{}px", summary.stroke_width.round() as i32);
sub = sub.child(
let mut sub = isolate_floating_chrome(
div()
.w(px(READOUT_W))
.h(px(CELL))
.absolute()
.left(px(placed.rect.x))
.top(px(placed.rect.y))
.p(px(PAD))
.rounded(px(8.0))
.bg(panel_bg)
.border(px(0.5))
.border_color(border_col)
.flex()
.items_center()
.gap(px(GAP)),
)
.snapshot(
"chrome.edgeless_element_toolbar.sub_menu",
Some(EDGELESS_VIEWPORT_ID),
);
for (id, label, icon_name, active, action) in items {
let icon_col = if active { palette.brand } else { palette.icon };
let btn = div()
.id(SharedString::from(format!("el-tb-strip-{id}")))
.w(px(BTN))
.h(px(BTN))
.rounded(px(4.0))
.flex()
.items_center()
.justify_center()
.text_size(px(TYPOGRAPHY.font_xs_px))
.font_weight(FontWeight::MEDIUM)
.text_color(palette.text_secondary)
.child(readout),
);
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.when(active, |el| el.bg(hover_bg))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(action.clone(), window, cx);
}))
.snapshot(
SharedString::from(format!("chrome.edgeless_element_toolbar.sub.{id}")),
Some("chrome.edgeless_element_toolbar.sub_menu"),
)
.snapshot_text(label)
.child(
canvas(
|_, _, _| (),
move |bounds, _, window, cx| {
IconPaint::named(icon_name).paint(bounds, icon_col, window, cx);
},
)
.w(px(20.0))
.h(px(20.0)),
);
sub = sub.child(attach_tooltip(btn, label, palette));
}
if !shadows.is_empty() {
sub = sub.shadow(shadows.into());
}
sub.into_any_element()
}
#[allow(clippy::too_many_arguments)]
fn build_font_size_dropdown<V: EdgelessElementToolbarHost>(
summary: &ElementToolbarSummary,
bar_rect: FlowRect,
viewport_width: f32,
viewport_height: f32,
palette: &Palette,
shadows: Vec<ui::BoxShadow>,
cx: &mut Context<V>,
) -> AnyElement {
const ROW_H: f32 = 28.0;
const GAP: f32 = 2.0;
const PAD: f32 = 4.0;
const SUB_W: f32 = 84.0;
let sub_h = FONT_SIZE_LIST.len() as f32 * ROW_H
+ FONT_SIZE_LIST.len().saturating_sub(1) as f32 * GAP
+ 2.0 * PAD
+ 2.0;
let vp_rect = FlowRect::new(0.0, 0.0, viewport_width, viewport_height);
let placed_sub = place_popover(
bar_rect,
(SUB_W, sub_h),
vp_rect,
Placement::Above,
6.0,
8.0,
);
let hover_bg = palette.hover;
let brand = palette.brand;
let mut sub = div()
.absolute()
.left(px(placed_sub.rect.x))
.top(px(placed_sub.rect.y))
.w(px(SUB_W))
.p(px(PAD))
.rounded(px(8.0))
.bg(palette.panel)
.border_1()
.border_color(palette.border)
.flex()
.flex_col()
.gap(px(GAP))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.snapshot(
"chrome.edgeless_element_toolbar.sub_menu",
Some(EDGELESS_VIEWPORT_ID),
);
for &fs in &FONT_SIZE_LIST {
let active = (summary.font_size - fs).abs() < 0.5;
let fs_int = fs.round() as i32;
let label = format!("{fs_int}");
let text_col = if active { brand } else { palette.text_primary };
sub = sub.child(
div()
.id(SharedString::from(format!("el-tb-fs-{fs_int}")))
.w_full()
.h(px(ROW_H))
.px(px(10.0))
.rounded(px(4.0))
.flex()
.items_center()
.text_size(px(TYPOGRAPHY.font_xs_px))
.font_weight(FontWeight::MEDIUM)
.text_color(text_col)
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.when(active, |el| el.bg(brand.opacity(0.14)))
.on_mouse_down(
MouseButton::Left,
cx.listener(move |this, _, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(
EdgelessElementAction::SetFontSize(fs),
window,
cx,
);
}),
)
.snapshot(
SharedString::from(format!("chrome.edgeless_element_toolbar.sub.fs_{fs_int}")),
Some("chrome.edgeless_element_toolbar.sub_menu"),
)
.snapshot_text(label.clone())
.child(div().flex_1().child(label))
.child(if active { "\u{2713}" } else { "" }),
);
}
if !shadows.is_empty() {
sub = sub.shadow(shadows.into());
}
sub.into_any_element()
(sub.into_any_element(), placed.rect)
}
#[allow(clippy::too_many_arguments)]
pub(super) fn build_sub_menu_pill<V: EdgelessElementToolbarHost>(
menu: ElementSubMenu,
summary: &ElementToolbarSummary,
bar_rect: FlowRect,
trigger_rect: FlowRect,
viewport_width: f32,
viewport_height: f32,
palette: &Palette,
shadows: Vec<ui::BoxShadow>,
theme: PlaygroundTheme,
cx: &mut Context<V>,
) -> Option<AnyElement> {
if menu == ElementSubMenu::LineWidth && summary.has_stroke_width {
return Some(build_line_width_panel(
) -> Option<(AnyElement, FlowRect)> {
match menu {
ElementSubMenu::More => Some(build_more_menu(
summary,
bar_rect,
trigger_rect,
viewport_width,
viewport_height,
palette,
shadows,
theme,
cx,
));
}
if menu == ElementSubMenu::FontSize && summary.has_font_size {
return Some(build_font_size_dropdown(
summary,
bar_rect,
)),
ElementSubMenu::NoteStyle | ElementSubMenu::NoteShadow if summary.has_note_shadow => {
Some(build_note_style_panel(
summary,
trigger_rect,
viewport_width,
viewport_height,
palette,
theme,
cx,
))
}
ElementSubMenu::NoteScale if summary.has_note_shadow => Some(build_scale_dropdown(
summary.note_scale,
false,
trigger_rect,
viewport_width,
viewport_height,
palette,
shadows,
theme,
cx,
));
}
let vp_rect = FlowRect::new(0.0, 0.0, viewport_width, viewport_height);
let hover_bg = palette.hover;
let items: Vec<(&'static str, &'static str, bool, EdgelessElementAction)> = match menu {
ElementSubMenu::Align if summary.can_align => {
let mut list = vec![
)),
ElementSubMenu::MediaScale => summary.surface_block.as_ref().map(|sb| {
build_scale_dropdown(
sb.scale,
true,
trigger_rect,
viewport_width,
viewport_height,
palette,
theme,
cx,
)
}),
ElementSubMenu::MediaStyle => summary.surface_block.as_ref().map(|sb| {
build_media_style_menu(
sb,
trigger_rect,
viewport_width,
viewport_height,
palette,
theme,
cx,
)
}),
ElementSubMenu::LineWidth if summary.has_stroke_width => Some(build_line_width_panel(
summary,
trigger_rect,
viewport_width,
viewport_height,
palette,
theme,
cx,
)),
ElementSubMenu::FontSize if summary.has_font_size => Some(build_font_size_dropdown(
summary,
trigger_rect,
viewport_width,
viewport_height,
palette,
theme,
cx,
)),
ElementSubMenu::Align if summary.can_align => Some(build_align_grid_popover(
summary,
trigger_rect,
viewport_width,
viewport_height,
palette,
theme,
cx,
)),
ElementSubMenu::ShapeType if summary.has_shape_type => {
let items = vec![
(
"left",
"Left",
false,
EdgelessElementAction::Align(AlignOp::Left),
"rect",
"Rectangle",
"SquareIcon",
summary.shape_preset == ShapePreset::Rect,
EdgelessElementAction::SetShapeType(ShapePreset::Rect),
),
(
"center_h",
"Center",
false,
EdgelessElementAction::Align(AlignOp::CenterH),
"ellipse",
"Ellipse",
"ShapeIcon",
summary.shape_preset == ShapePreset::Ellipse,
EdgelessElementAction::SetShapeType(ShapePreset::Ellipse),
),
(
"right",
"Right",
false,
EdgelessElementAction::Align(AlignOp::Right),
"diamond",
"Diamond",
"DiamondIcon",
summary.shape_preset == ShapePreset::Diamond,
EdgelessElementAction::SetShapeType(ShapePreset::Diamond),
),
(
"top",
"Top",
false,
EdgelessElementAction::Align(AlignOp::Top),
"triangle",
"Triangle",
"TriangleIcon",
summary.shape_preset == ShapePreset::Triangle,
EdgelessElementAction::SetShapeType(ShapePreset::Triangle),
),
(
"center_v",
"Middle",
false,
EdgelessElementAction::Align(AlignOp::CenterV),
),
(
"bottom",
"Bottom",
false,
EdgelessElementAction::Align(AlignOp::Bottom),
"rounded_rect",
"Rounded rectangle",
"RoundedRectangleIcon",
summary.shape_preset == ShapePreset::RoundedRect,
EdgelessElementAction::SetShapeType(ShapePreset::RoundedRect),
),
];
if summary.can_distribute {
list.push((
"dist_h",
"Dist H",
false,
EdgelessElementAction::Align(AlignOp::DistributeH),
));
list.push((
"dist_v",
"Dist V",
false,
EdgelessElementAction::Align(AlignOp::DistributeV),
));
}
list
Some(build_icon_strip_menu(
items,
trigger_rect,
viewport_width,
viewport_height,
palette,
theme,
cx,
))
}
ElementSubMenu::ConnectorMode if summary.has_connector_props => {
let items = vec![
(
"curve",
"Curve",
"ConnectorCIcon",
summary.connector_mode == ConnectorMode::Curve,
EdgelessElementAction::SetConnectorMode(ConnectorMode::Curve),
),
(
"elbowed",
"Elbowed",
"ConnectorEIcon",
summary.connector_mode == ConnectorMode::Orthogonal,
EdgelessElementAction::SetConnectorMode(ConnectorMode::Orthogonal),
),
(
"straight",
"Straight",
"ConnectorLIcon",
summary.connector_mode == ConnectorMode::Straight,
EdgelessElementAction::SetConnectorMode(ConnectorMode::Straight),
),
];
Some(build_icon_strip_menu(
items,
trigger_rect,
viewport_width,
viewport_height,
palette,
theme,
cx,
))
}
ElementSubMenu::TextAlign if summary.has_text_align => {
let (panel_bg, border_col, shadows) = toolbar_chrome_tokens(palette, theme);
let sub_w = 3.0 * 28.0 + 2.0 * 4.0 + 14.0;
let sub_h = 28.0 + 14.0;
let vp_rect = FlowRect::new(0.0, 0.0, viewport_width, viewport_height);
let placed = place_popover(
trigger_rect,
(sub_w, sub_h),
vp_rect,
Placement::Above,
8.0,
10.0,
);
let hover_bg = palette.hover;
let mut sub = isolate_floating_chrome(
div()
.absolute()
.left(px(placed.rect.x))
.top(px(placed.rect.y))
.p(px(6.0))
.rounded(px(8.0))
.bg(panel_bg)
.border(px(0.5))
.border_color(border_col)
.flex()
.items_center()
.gap(px(4.0)),
)
.snapshot(
"chrome.edgeless_element_toolbar.sub_menu",
Some(EDGELESS_VIEWPORT_ID),
);
for (id, label, align) in [
("left", "Align left", TextAlign::Left),
("center", "Align center", TextAlign::Center),
("right", "Align right", TextAlign::Right),
] {
let active = summary.text_align == align;
let col = if active { palette.brand } else { palette.icon };
let btn = div()
.id(SharedString::from(format!("el-tb-ta-{id}")))
.w(px(28.0))
.h(px(28.0))
.rounded(px(4.0))
.flex()
.items_center()
.justify_center()
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.when(active, |el| el.bg(hover_bg))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(
EdgelessElementAction::SetTextAlign(align),
window,
cx,
);
}))
.snapshot(
SharedString::from(format!("chrome.edgeless_element_toolbar.sub.ta_{id}")),
Some("chrome.edgeless_element_toolbar.sub_menu"),
)
.snapshot_text(label)
.child(align_glyph(align, col));
sub = sub.child(attach_tooltip(btn, label, palette));
}
if !shadows.is_empty() {
sub = sub.shadow(shadows.into());
}
Some((sub.into_any_element(), placed.rect))
}
_ => build_text_chip_submenu(
menu,
summary,
trigger_rect,
viewport_width,
viewport_height,
palette,
theme,
cx,
),
}
}
#[allow(clippy::too_many_arguments)]
fn build_text_chip_submenu<V: EdgelessElementToolbarHost>(
menu: ElementSubMenu,
summary: &ElementToolbarSummary,
trigger_rect: FlowRect,
viewport_width: f32,
viewport_height: f32,
palette: &Palette,
theme: PlaygroundTheme,
cx: &mut Context<V>,
) -> Option<(AnyElement, FlowRect)> {
let (panel_bg, border_col, shadows) = toolbar_chrome_tokens(palette, theme);
let hover_bg = palette.hover;
let items: Vec<(&'static str, &'static str, bool, EdgelessElementAction)> = match menu {
ElementSubMenu::ConnectorCaps if summary.has_connector_props => {
let next_ep = |cur: EndpointStyle| match cur {
EndpointStyle::None => EndpointStyle::Arrow,
@@ -457,22 +496,8 @@ pub(super) fn build_sub_menu_pill<V: EdgelessElementToolbarHost>(
),
]
}
ElementSubMenu::NoteShadow if summary.has_note_shadow => NOTE_SHADOW_PRESETS
.iter()
.map(|&(id, label, token)| {
let active = summary.note_shadow == token;
(
id,
label,
active,
EdgelessElementAction::SetNoteShadow(token.to_string()),
)
})
.collect(),
ElementSubMenu::MindmapStyle => {
let Some(mm) = summary.mindmap.as_ref() else {
return None;
};
let mm = summary.mindmap.as_ref()?;
let cur = mm.style;
vec![
(
@@ -482,10 +507,10 @@ pub(super) fn build_sub_menu_pill<V: EdgelessElementToolbarHost>(
EdgelessElementAction::SetMindmapStyle(MindmapStyle::One),
),
(
"s2",
"Style 2",
cur == MindmapStyle::Two,
EdgelessElementAction::SetMindmapStyle(MindmapStyle::Two),
"s4",
"Style 4",
cur == MindmapStyle::Four,
EdgelessElementAction::SetMindmapStyle(MindmapStyle::Four),
),
(
"s3",
@@ -494,71 +519,71 @@ pub(super) fn build_sub_menu_pill<V: EdgelessElementToolbarHost>(
EdgelessElementAction::SetMindmapStyle(MindmapStyle::Three),
),
(
"s4",
"Style 4",
cur == MindmapStyle::Four,
EdgelessElementAction::SetMindmapStyle(MindmapStyle::Four),
"s2",
"Style 2",
cur == MindmapStyle::Two,
EdgelessElementAction::SetMindmapStyle(MindmapStyle::Two),
),
]
}
ElementSubMenu::MindmapLayout => {
let Some(mm) = summary.mindmap.as_ref() else {
return None;
};
let mm = summary.mindmap.as_ref()?;
let cur = mm.layout_type;
vec![
(
"right",
"Right",
cur == MindmapLayoutType::Right,
EdgelessElementAction::SetMindmapLayout(MindmapLayoutType::Right),
),
(
"balance",
"Balance",
cur == MindmapLayoutType::Balance,
EdgelessElementAction::SetMindmapLayout(MindmapLayoutType::Balance),
),
(
"left",
"Left",
cur == MindmapLayoutType::Left,
EdgelessElementAction::SetMindmapLayout(MindmapLayoutType::Left),
),
(
"balance",
"Radial",
cur == MindmapLayoutType::Balance,
EdgelessElementAction::SetMindmapLayout(MindmapLayoutType::Balance),
),
(
"right",
"Right",
cur == MindmapLayoutType::Right,
EdgelessElementAction::SetMindmapLayout(MindmapLayoutType::Right),
),
]
}
_ => return None,
};
let btn_w = 50.0_f32;
let sub_w = (items.len() as f32 * btn_w + (items.len().saturating_sub(1)) as f32 * 2.0 + 10.0)
.min((viewport_width - 16.0).max(80.0));
let sub_h = 34.0;
let placed_sub = place_popover(
bar_rect,
let btn_w = 54.0_f32;
let sub_w = (items.len() as f32 * btn_w + items.len().saturating_sub(1) as f32 * 4.0 + 14.0)
.min((viewport_width - 20.0).max(80.0));
let sub_h = 36.0;
let vp_rect = FlowRect::new(0.0, 0.0, viewport_width, viewport_height);
let placed = place_popover(
trigger_rect,
(sub_w, sub_h),
vp_rect,
Placement::Above,
6.0,
8.0,
10.0,
);
let mut sub = isolate_floating_chrome(
div()
.absolute()
.left(px(placed.rect.x))
.top(px(placed.rect.y))
.p(px(5.0))
.rounded(px(8.0))
.bg(panel_bg)
.border(px(0.5))
.border_color(border_col)
.flex()
.items_center()
.gap(px(4.0)),
)
.snapshot(
"chrome.edgeless_element_toolbar.sub_menu",
Some(EDGELESS_VIEWPORT_ID),
);
let mut sub = div()
.absolute()
.left(px(placed_sub.rect.x))
.top(px(placed_sub.rect.y))
.p(px(4.0))
.rounded(px(8.0))
.bg(palette.panel)
.border_1()
.border_color(palette.border)
.flex()
.items_center()
.gap(px(2.0))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.snapshot(
"chrome.edgeless_element_toolbar.sub_menu",
Some(EDGELESS_VIEWPORT_ID),
);
for (id, label, active, action) in items {
let text_col = if active {
palette.brand
@@ -579,14 +604,12 @@ pub(super) fn build_sub_menu_pill<V: EdgelessElementToolbarHost>(
.text_color(text_col)
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.when(active, |el| el.bg(palette.brand.opacity(0.14)))
.on_mouse_down(
MouseButton::Left,
cx.listener(move |this, _, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(action.clone(), window, cx);
}),
)
.when(active, |el| el.bg(hover_bg))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(action.clone(), window, cx);
}))
.snapshot(
SharedString::from(format!("chrome.edgeless_element_toolbar.sub.{id}")),
Some("chrome.edgeless_element_toolbar.sub_menu"),
@@ -598,5 +621,5 @@ pub(super) fn build_sub_menu_pill<V: EdgelessElementToolbarHost>(
if !shadows.is_empty() {
sub = sub.shadow(shadows.into());
}
Some(sub.into_any_element())
Some((sub.into_any_element(), placed.rect))
}
File diff suppressed because it is too large. Load diff
@@ -7,8 +7,9 @@ use crate::theme::{Palette, PlaygroundTheme};
use super::{
EdgelessAuthoringState, ElementToolbarSummary, MindmapToolbarSummary, ShapePreset,
SpatialItemInfo, SpatialItemKind, WorldRect, json_to_color_value, note_scale, note_shadow_type,
parse_xywh, prop_bool, prop_f32, resolve_edgeless_color,
SpatialItemInfo, SpatialItemKind, SurfaceBlockToolbarSummary, WorldRect, json_to_color_value,
note_border_radius, note_border_style, note_collapse, note_scale, note_shadow_type, parse_xywh,
prop_bool, prop_f32, resolve_edgeless_color,
};
fn resolve_endpoint_world_point(
@@ -267,13 +268,25 @@ pub fn summarize_element_toolbar(
.iter()
.filter(|i| i.kind != SpatialItemKind::Frame)
.count();
let can_wrap_frame = selected_count >= 2;
let can_group = non_frame_count >= 2;
let can_align = selected_count >= 2;
let can_distribute = selected_count >= 3;
let single = (selected_count == 1).then_some(selected_items[0]);
let can_release_from_group = single.is_some_and(|i| i.parent_group_id.is_some());
let can_draw_connector = single.is_some_and(|i| {
!matches!(
i.kind,
SpatialItemKind::Connector
| SpatialItemKind::Brush
| SpatialItemKind::Highlighter
| SpatialItemKind::Group
)
});
let has_frame_actions = single.is_some_and(|i| i.kind == SpatialItemKind::Frame);
let has_group_actions = single.is_some_and(|i| i.kind == SpatialItemKind::Group);
let mindmap = single.and_then(|i| find_mindmap_for_node(snapshot, &i.id));
let mut surface_block: Option<SurfaceBlockToolbarSummary> = None;
let mut has_fill = false;
let mut has_stroke = false;
@@ -285,8 +298,12 @@ pub fn summarize_element_toolbar(
let mut has_font_size = false;
let mut has_shape_type = false;
let mut has_connector_props = false;
let mut shape_has_text = false;
let mut connector_has_label = false;
let mut can_add_text = false;
let mut has_note_display = false;
let mut has_note_shadow = false;
let mut note_is_page_root = false;
let mut has_highlighter_width = false;
let mut has_standard_width = false;
let mut has_note_fill = false;
@@ -317,6 +334,25 @@ pub fn summarize_element_toolbar(
let mut rear_endpoint = EndpointStyle::Arrow;
let mut note_in_page = false;
let mut note_shadow = "--affine-note-shadow-box".to_string();
let mut note_border_style_val = StrokeStyle::None;
let mut note_border_size_val = 4.0_f64;
let mut note_border_radius_val = 8.0_f64;
let mut note_auto_height = true;
let mut note_scale_val = 1.0_f32;
let primary_page_note_id: Option<&str> = snapshot.root.as_ref().and_then(|root| {
let mut page_notes = root
.children
.iter()
.filter(|c| c.is_page_visible_note())
.map(|c| c.id.as_str());
let first = page_notes.next()?;
if page_notes.next().is_none() {
Some(first)
} else {
None
}
});
let mut got_fill = false;
let mut got_stroke = false;
@@ -346,10 +382,7 @@ pub fn summarize_element_toolbar(
has_rough_style = true;
has_shape_type = true;
}
has_text_color = true;
is_shape_text = true;
has_text_align = true;
has_font_size = true;
}
SpatialItemKind::Connector => {
has_stroke = true;
@@ -357,7 +390,6 @@ pub fn summarize_element_toolbar(
has_stroke_width = true;
has_standard_width = true;
has_rough_style = true;
has_font_size = true;
has_connector_props = true;
}
SpatialItemKind::Brush => {
@@ -382,8 +414,12 @@ pub fn summarize_element_toolbar(
SpatialItemKind::Note => {
has_fill = true;
has_note_fill = true;
has_note_display = true;
has_note_shadow = true;
if primary_page_note_id == Some(item.id.as_str()) {
note_is_page_root = true;
} else {
has_note_display = true;
}
}
SpatialItemKind::Frame => {
has_fill = true;
@@ -420,9 +456,24 @@ pub fn summarize_element_toolbar(
}
if !got_note_shadow {
note_shadow = note_shadow_type(node).to_string();
if let Some((bs, bw)) = note_border_style(node) {
note_border_style_val = match bs {
ui::BorderStyle::Solid => StrokeStyle::Solid,
ui::BorderStyle::Dashed => StrokeStyle::Dash,
};
note_border_size_val = bw as f64;
} else {
note_border_style_val = StrokeStyle::None;
}
note_border_radius_val = note_border_radius(node) as f64;
note_auto_height = !note_collapse(node);
note_scale_val = note_scale(node);
got_note_shadow = true;
}
}
if item.kind == SpatialItemKind::SurfaceBlock && single.is_some() {
surface_block = super::media_toolbar::summarize_surface_block(node);
}
if item.kind == SpatialItemKind::EdgelessText {
if !got_stroke && let Some(col) = node.props.get("prop:color") {
if let Some(c) = resolve_edgeless_color(col, theme) {
@@ -459,6 +510,15 @@ pub fn summarize_element_toolbar(
}
match &el.kind {
SurfaceElementKind::Shape(s) => {
let has_txt = !s.text.plain.is_empty();
if has_txt {
shape_has_text = true;
has_text_color = true;
has_text_align = true;
has_font_size = true;
} else if single.is_some() && mindmap.is_none() {
can_add_text = true;
}
if !got_fill {
if let Some(c) = theme.resolve_color_value(&s.fill_color) {
fill_color = c;
@@ -507,6 +567,14 @@ pub fn summarize_element_toolbar(
}
}
SurfaceElementKind::Connector(c) => {
let has_lbl = !c.text.plain.is_empty();
if has_lbl {
connector_has_label = true;
has_font_size = true;
has_text_align = true;
} else if single.is_some() {
can_add_text = true;
}
if !got_stroke {
if let Some(col) = theme.resolve_color_value(&c.stroke) {
stroke_color = col;
@@ -527,6 +595,10 @@ pub fn summarize_element_toolbar(
font_size = c.label_style.font_size;
got_font = true;
}
if !got_text_align && has_lbl {
text_align = c.label_style.text_align;
got_text_align = true;
}
if !got_connector {
connector_mode = c.mode;
front_endpoint = c.front_endpoint_style;
@@ -575,9 +647,12 @@ pub fn summarize_element_toolbar(
Some(ElementToolbarSummary {
is_locked,
can_release_from_group,
can_wrap_frame,
can_group,
can_align,
can_distribute,
can_draw_connector,
has_fill,
has_stroke,
has_text_color,
@@ -588,14 +663,19 @@ pub fn summarize_element_toolbar(
has_font_size,
has_shape_type,
has_connector_props,
shape_has_text,
connector_has_label,
can_add_text,
has_note_display,
has_note_shadow,
note_is_page_root,
has_frame_actions,
has_group_actions,
is_highlighter_width: has_highlighter_width && !has_standard_width,
is_note_fill: has_note_fill && !has_non_note_fill,
is_shape_text,
mindmap,
surface_block,
fill_color,
stroke_color,
text_color,
@@ -613,5 +693,10 @@ pub fn summarize_element_toolbar(
rear_endpoint,
note_in_page,
note_shadow,
note_border_style: note_border_style_val,
note_border_size: note_border_size_val,
note_border_radius: note_border_radius_val,
note_auto_height,
note_scale: note_scale_val,
})
}
@@ -1,177 +1,184 @@
//! Reusable button primitives for `chrome.edgeless_element_toolbar`.
//! Reusable 36 px chrome button, separator, and tooltip primitives for
//! `chrome.edgeless_element_toolbar` (aligned with BlockSuite `0.27.5` `editor-toolbar`).
use blocksuite_playground_doc::read::{StrokeStyle, TextAlign};
use ui::{
BorderStyle, Bounds, Context, Corners, Edges, FontWeight, MouseButton, canvas, div, point,
prelude::*, px, size,
BorderStyle, Bounds, ClickEvent, Context, Corners, Edges, FontWeight, Hsla, MouseButton,
SharedString, Window, canvas, div, point, prelude::*, px, size,
};
use crate::{
overlays::align_glyph,
theme::{IconPaint, Palette, TYPOGRAPHY},
theme::{IconPaint, Palette, PlaygroundTheme, TYPOGRAPHY},
};
use super::{EdgelessElementAction, EdgelessElementToolbarHost, ElementColorSlot};
pub(super) fn stroke_style_btn<V: EdgelessElementToolbarHost>(
style: StrokeStyle,
next_style: StrokeStyle,
icon_color: ui::Hsla,
hover_bg: ui::Hsla,
cx: &mut Context<V>,
pub(super) const BAR_HEIGHT: f32 = 36.0;
pub(super) const BAR_PAD_X: f32 = 6.0;
pub(super) const BAR_GAP: f32 = 8.0;
pub(super) const BAR_RADIUS: f32 = 8.0;
pub(super) const BTN_SIZE: f32 = 24.0;
pub(super) const ICON_SIZE: f32 = 20.0;
pub(super) const BTN_RADIUS: f32 = 4.0;
pub(super) const SEP_W: f32 = 4.0;
struct ToolbarTooltipView {
label: SharedString,
bg: Hsla,
fg: Hsla,
}
impl ui::Render for ToolbarTooltipView {
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.bg)
.text_size(px(12.0))
.font_weight(FontWeight::MEDIUM)
.text_color(self.fg)
.child(self.label.clone())
}
}
pub(super) fn attach_tooltip(
mut el: ui::Stateful<ui::Div>,
label: impl Into<SharedString>,
palette: &Palette,
) -> ui::Stateful<ui::Div> {
let style_label = match style {
StrokeStyle::Solid => "Solid",
StrokeStyle::Dash => "Dash",
StrokeStyle::None => "None",
let tip: SharedString = label.into();
let bg = palette.text_primary;
let fg = palette.panel;
el.interactivity().tooltip(move |_window, cx| {
cx.new(|_| ToolbarTooltipView {
label: tip.clone(),
bg,
fg,
})
.into()
});
el
}
/// Overlay panel background and 0.5 px border tokens matching BlockSuite `panelBaseStyle`.
pub(super) fn toolbar_chrome_tokens(
palette: &Palette,
theme: PlaygroundTheme,
) -> (Hsla, Hsla, Vec<ui::BoxShadow>) {
let panel_bg = theme
.css_color("--affine-background-overlay-panel-color")
.unwrap_or(palette.panel);
let border_col = theme
.css_color("--affine-v2-layer-insideBorder-border")
.unwrap_or(palette.border);
let shadows = {
let s = theme.shadows("--affine-overlay-shadow");
if s.is_empty() {
theme.shadows("--affine-toolbar-shadow")
} else {
s
}
};
(panel_bg, border_col, shadows)
}
/// Stop left/right/middle mouse presses and wheel scroll from leaking through floating chrome.
pub(super) fn isolate_floating_chrome(el: ui::Div) -> ui::Div {
el.cursor_default()
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_mouse_down(MouseButton::Right, |_, _, cx| cx.stop_propagation())
.on_mouse_down(MouseButton::Middle, |_, _, cx| cx.stop_propagation())
.on_scroll(|_, _, cx| cx.stop_propagation())
}
/// Full-height `0.5px` vertical separator inside a `4px` slot between action groups.
pub(super) fn toolbar_separator(border_col: Hsla) -> ui::Div {
div()
.id("el-tb-stroke-style")
.w(px(28.0))
.h(px(28.0))
.rounded(px(4.0))
.w(px(SEP_W))
.h(px(BAR_HEIGHT - 1.0))
.flex()
.items_center()
.justify_center()
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.on_mouse_down(
MouseButton::Left,
cx.listener(move |this, _, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(
EdgelessElementAction::SetStrokeStyle(next_style),
window,
cx,
);
}),
)
.snapshot(
"chrome.edgeless_element_toolbar.stroke_style",
Some("chrome.edgeless_element_toolbar"),
)
.snapshot_text(style_label)
.child(
canvas(
|_, _, _| (),
move |bounds, _, window, _| {
let cy = f32::from(bounds.origin.y) + f32::from(bounds.size.height) * 0.5;
let x0 = f32::from(bounds.origin.x) + 2.0;
let w = (f32::from(bounds.size.width) - 4.0).max(8.0);
match style {
StrokeStyle::Solid => {
window.paint_quad(ui::fill(
Bounds::new(point(px(x0), px(cy - 1.0)), size(px(w), px(2.0))),
icon_color,
));
}
StrokeStyle::Dash => {
for i in 0..3 {
let sx = x0 + i as f32 * 5.0;
window.paint_quad(ui::fill(
Bounds::new(
point(px(sx), px(cy - 1.0)),
size(px(3.5), px(2.0)),
),
icon_color,
));
}
}
StrokeStyle::None => {
window.paint_quad(ui::quad(
Bounds::new(
point(px(x0 + 2.0), px(cy - 5.0)),
size(px(10.0), px(10.0)),
),
Corners::all(px(5.0)),
ui::transparent_black(),
Edges::all(px(1.25)),
icon_color.opacity(0.5),
BorderStyle::Dashed,
));
}
}
},
)
.w(px(18.0))
.h(px(16.0)),
)
.child(div().w(px(0.5)).h(px(BAR_HEIGHT - 1.0)).bg(border_col))
}
#[allow(clippy::too_many_arguments)]
pub(super) fn swatch_btn<V: EdgelessElementToolbarHost>(
id: &'static str,
snap_id: &'static str,
label: &'static str,
active: bool,
hover_bg: ui::Hsla,
brand: ui::Hsla,
slot: ElementColorSlot,
paint: impl Fn(Bounds<ui::Pixels>, &mut ui::Window) + 'static,
cx: &mut Context<V>,
) -> ui::Stateful<ui::Div> {
div()
.id(id)
.w(px(28.0))
.h(px(28.0))
.rounded(px(4.0))
.flex()
.items_center()
.justify_center()
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.when(active, |el| el.bg(brand.opacity(0.14)))
.on_mouse_down(
MouseButton::Left,
cx.listener(move |this, _, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(
EdgelessElementAction::ToggleColorPicker(slot),
window,
cx,
);
}),
)
.snapshot(snap_id, Some("chrome.edgeless_element_toolbar"))
.snapshot_text(label)
.child(
canvas(
|_, _, _| (),
move |bounds, _, window, _| paint(bounds, window),
)
.w(px(26.0))
.h(px(26.0)),
)
/// Small downward chevron drawn inside dropdown trigger buttons (`EditorChevronDown`).
pub(super) fn chevron_down_glyph(color: Hsla) -> ui::Canvas<()> {
canvas(
|_, _, _| (),
move |bounds, _, window, _| {
let cx = f32::from(bounds.origin.x) + f32::from(bounds.size.width) * 0.5;
let cy = f32::from(bounds.origin.y) + f32::from(bounds.size.height) * 0.5;
let mut pb = ui::PathBuilder::stroke(px(1.25));
pb.move_to(point(px(cx - 3.0), px(cy - 1.5)));
pb.line_to(point(px(cx), px(cy + 1.8)));
pb.line_to(point(px(cx + 3.0), px(cy - 1.5)));
if let Ok(path) = pb.build() {
window.paint_path(path, color);
}
},
)
.w(px(10.0))
.h(px(10.0))
}
/// Vertical three-dot (`⋮`) glyph for the right-side More trigger (`MoreVerticalIcon`).
pub(super) fn more_vertical_glyph(color: Hsla) -> ui::Canvas<()> {
canvas(
|_, _, _| (),
move |bounds, _, window, _| {
let cx = f32::from(bounds.origin.x) + f32::from(bounds.size.width) * 0.5;
let cy = f32::from(bounds.origin.y) + f32::from(bounds.size.height) * 0.5;
for dy in [-5.0_f32, 0.0, 5.0] {
window.paint_quad(
ui::fill(
Bounds::new(
point(px(cx - 1.3), px(cy + dy - 1.3)),
size(px(2.6), px(2.6)),
),
color,
)
.corner_radii(px(1.3)),
);
}
},
)
.w(px(ICON_SIZE))
.h(px(ICON_SIZE))
}
/// 24×24 icon action button firing on mouse release (`on_click`) with active primary icon color
/// (no blue background) and hover tooltip.
#[allow(clippy::too_many_arguments)]
pub(super) fn icon_action_btn<V: EdgelessElementToolbarHost>(
id: &'static str,
snap_id: &'static str,
label: &'static str,
icon_name: &'static str,
icon_color: ui::Hsla,
hover_bg: ui::Hsla,
active: bool,
palette: &Palette,
action: EdgelessElementAction,
cx: &mut Context<V>,
) -> ui::Stateful<ui::Div> {
div()
let icon_color = if active { palette.brand } else { palette.icon };
let hover_bg = palette.hover;
let btn = div()
.id(id)
.w(px(28.0))
.h(px(28.0))
.rounded(px(4.0))
.w(px(BTN_SIZE))
.h(px(BTN_SIZE))
.rounded(px(BTN_RADIUS))
.flex()
.items_center()
.justify_center()
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.on_mouse_down(
MouseButton::Left,
cx.listener(move |this, _, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(action.clone(), window, cx);
}),
)
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(action.clone(), window, cx);
}))
.snapshot(snap_id, Some("chrome.edgeless_element_toolbar"))
.snapshot_text(label)
.child(
@@ -181,11 +188,112 @@ pub(super) fn icon_action_btn<V: EdgelessElementToolbarHost>(
IconPaint::named(icon_name).paint(bounds, icon_color, window, cx);
},
)
.w(px(16.0))
.h(px(16.0)),
)
.w(px(ICON_SIZE))
.h(px(ICON_SIZE)),
);
attach_tooltip(btn, label, palette)
}
/// 24 px high button with custom canvas glyph (e.g. `⋮ More`, stroke style, lock icon) firing
/// on release with hover tooltip.
#[allow(clippy::too_many_arguments)]
pub(super) fn custom_icon_btn<V: EdgelessElementToolbarHost>(
id: &'static str,
snap_id: &'static str,
label: &'static str,
width: f32,
palette: &Palette,
action: EdgelessElementAction,
child: impl IntoElement,
cx: &mut Context<V>,
) -> ui::Stateful<ui::Div> {
let hover_bg = palette.hover;
let btn = div()
.id(id)
.w(px(width))
.h(px(BTN_SIZE))
.rounded(px(BTN_RADIUS))
.flex()
.items_center()
.justify_center()
.gap(px(2.0))
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(action.clone(), window, cx);
}))
.snapshot(snap_id, Some("chrome.edgeless_element_toolbar"))
.snapshot_text(label)
.child(child);
attach_tooltip(btn, label, palette)
}
/// 24×24 swatch trigger button (active = primary ring, no blue background) firing on release.
#[allow(clippy::too_many_arguments)]
pub(super) fn swatch_btn<V: EdgelessElementToolbarHost>(
id: &'static str,
snap_id: &'static str,
label: &'static str,
active: bool,
palette: &Palette,
slot: ElementColorSlot,
paint: impl Fn(Bounds<ui::Pixels>, &mut Window) + 'static,
cx: &mut Context<V>,
) -> ui::Stateful<ui::Div> {
let hover_bg = palette.hover;
let brand = palette.brand;
let btn = div()
.id(id)
.w(px(BTN_SIZE))
.h(px(BTN_SIZE))
.rounded(px(BTN_RADIUS))
.flex()
.items_center()
.justify_center()
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(
EdgelessElementAction::ToggleColorPicker(slot),
window,
cx,
);
}))
.snapshot(snap_id, Some("chrome.edgeless_element_toolbar"))
.snapshot_text(label)
.child(
canvas(
|_, _, _| (),
move |bounds, _, window, _| {
paint(bounds, window);
if active {
let ring = Bounds::new(
point(bounds.origin.x + px(1.0), bounds.origin.y + px(1.0)),
size(bounds.size.width - px(2.0), bounds.size.height - px(2.0)),
);
window.paint_quad(ui::quad(
ring,
Corners::all(px(11.0)),
ui::transparent_black(),
Edges::all(px(1.5)),
brand,
BorderStyle::Solid,
));
}
},
)
.w(px(22.0))
.h(px(22.0)),
);
attach_tooltip(btn, label, palette)
}
/// Compact 24 px high label/dropdown button firing on release; active state uses primary color
/// only (no blue background), with optional trailing chevron.
#[allow(clippy::too_many_arguments)]
pub(super) fn text_action_btn<V: EdgelessElementToolbarHost>(
id: &'static str,
@@ -193,6 +301,7 @@ pub(super) fn text_action_btn<V: EdgelessElementToolbarHost>(
label: String,
width: f32,
active: bool,
has_chevron: bool,
palette: &Palette,
action: EdgelessElementAction,
cx: &mut Context<V>,
@@ -203,85 +312,139 @@ pub(super) fn text_action_btn<V: EdgelessElementToolbarHost>(
} else {
palette.text_primary
};
div()
let chevron_col = if active { palette.brand } else { palette.icon };
let tip = label.clone();
let mut btn = div()
.id(id)
.w(px(width))
.h(px(28.0))
.rounded(px(4.0))
.h(px(BTN_SIZE))
.px(px(4.0))
.rounded(px(BTN_RADIUS))
.flex()
.items_center()
.justify_center()
.gap(px(2.0))
.text_size(px(TYPOGRAPHY.font_xs_px))
.font_weight(FontWeight::MEDIUM)
.text_color(text_col)
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.when(active, |el| el.bg(palette.brand.opacity(0.14)))
.on_mouse_down(
MouseButton::Left,
cx.listener(move |this, _, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(action.clone(), window, cx);
}),
)
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(action.clone(), window, cx);
}))
.snapshot(snap_id, Some("chrome.edgeless_element_toolbar"))
.snapshot_text(label.clone())
.child(label)
.child(label);
if has_chevron {
btn = btn.child(chevron_down_glyph(chevron_col));
}
attach_tooltip(btn, tip, palette)
}
pub(super) fn stroke_style_btn<V: EdgelessElementToolbarHost>(
style: StrokeStyle,
next_style: StrokeStyle,
palette: &Palette,
cx: &mut Context<V>,
) -> ui::Stateful<ui::Div> {
let icon_color = palette.icon;
let style_label = match style {
StrokeStyle::Solid => "Border: Solid",
StrokeStyle::Dash => "Border: Dash",
StrokeStyle::None => "Border: None",
};
let glyph = canvas(
|_, _, _| (),
move |bounds, _, window, _| {
let cy = f32::from(bounds.origin.y) + f32::from(bounds.size.height) * 0.5;
let x0 = f32::from(bounds.origin.x) + 2.0;
let w = (f32::from(bounds.size.width) - 4.0).max(8.0);
match style {
StrokeStyle::Solid => {
window.paint_quad(ui::fill(
Bounds::new(point(px(x0), px(cy - 1.0)), size(px(w), px(2.0))),
icon_color,
));
}
StrokeStyle::Dash => {
for i in 0..3 {
let sx = x0 + i as f32 * 5.0;
window.paint_quad(ui::fill(
Bounds::new(point(px(sx), px(cy - 1.0)), size(px(3.5), px(2.0))),
icon_color,
));
}
}
StrokeStyle::None => {
window.paint_quad(ui::quad(
Bounds::new(point(px(x0 + 2.0), px(cy - 5.0)), size(px(10.0), px(10.0))),
Corners::all(px(5.0)),
ui::transparent_black(),
Edges::all(px(1.25)),
icon_color.opacity(0.5),
BorderStyle::Dashed,
));
}
}
},
)
.w(px(18.0))
.h(px(16.0));
custom_icon_btn(
"el-tb-stroke-style",
"chrome.edgeless_element_toolbar.stroke_style",
style_label,
BTN_SIZE,
palette,
EdgelessElementAction::SetStrokeStyle(next_style),
glyph,
cx,
)
}
pub(super) fn align_action_btn<V: EdgelessElementToolbarHost>(
align: TextAlign,
next_align: TextAlign,
icon_color: ui::Hsla,
hover_bg: ui::Hsla,
active: bool,
palette: &Palette,
cx: &mut Context<V>,
) -> ui::Stateful<ui::Div> {
let icon_color = if active { palette.brand } else { palette.icon };
let label = match align {
TextAlign::Left => "Align Left",
TextAlign::Center => "Align Center",
TextAlign::Right => "Align Right",
TextAlign::Left => "Text align: Left",
TextAlign::Center => "Text align: Center",
TextAlign::Right => "Text align: Right",
};
div()
.id("el-tb-text-align")
.w(px(28.0))
.h(px(28.0))
.rounded(px(4.0))
.flex()
.items_center()
.justify_center()
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.on_mouse_down(
MouseButton::Left,
cx.listener(move |this, _, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(
EdgelessElementAction::SetTextAlign(next_align),
window,
cx,
);
}),
)
.snapshot(
"chrome.edgeless_element_toolbar.text_align",
Some("chrome.edgeless_element_toolbar"),
)
.snapshot_text(label)
.child(align_glyph(align, icon_color))
custom_icon_btn(
"el-tb-text-align",
"chrome.edgeless_element_toolbar.text_align",
label,
BTN_SIZE,
palette,
EdgelessElementAction::ToggleSubMenu(super::ElementSubMenu::TextAlign),
align_glyph(align, icon_color),
cx,
)
}
pub(super) fn text_color_btn<V: EdgelessElementToolbarHost>(
active: bool,
text_color: ui::Hsla,
text_color: Hsla,
palette: &Palette,
cx: &mut Context<V>,
) -> ui::Stateful<ui::Div> {
let hover_bg = palette.hover;
div()
let letter_col = if active {
palette.brand
} else {
palette.text_primary
};
let btn = div()
.id("el-tb-text-color")
.w(px(28.0))
.h(px(28.0))
.rounded(px(4.0))
.w(px(BTN_SIZE))
.h(px(BTN_SIZE))
.rounded(px(BTN_RADIUS))
.flex()
.flex_col()
.items_center()
@@ -290,26 +453,24 @@ pub(super) fn text_color_btn<V: EdgelessElementToolbarHost>(
.text_size(px(11.0))
.line_height(px(12.0))
.font_weight(FontWeight::SEMIBOLD)
.text_color(palette.text_primary)
.text_color(letter_col)
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.when(active, |el| el.bg(palette.brand.opacity(0.14)))
.on_mouse_down(
MouseButton::Left,
cx.listener(|this, _, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(
EdgelessElementAction::ToggleColorPicker(ElementColorSlot::Text),
window,
cx,
);
}),
)
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(|this, _: &ClickEvent, window, cx| {
cx.stop_propagation();
this.edgeless_element_action(
EdgelessElementAction::ToggleColorPicker(ElementColorSlot::Text),
window,
cx,
);
}))
.snapshot(
"chrome.edgeless_element_toolbar.text_color",
Some("chrome.edgeless_element_toolbar"),
)
.snapshot_text("A")
.child("A")
.child(div().w(px(13.0)).h(px(2.5)).rounded(px(1.0)).bg(text_color))
.child(div().w(px(13.0)).h(px(2.5)).rounded(px(1.0)).bg(text_color));
attach_tooltip(btn, "Text color", palette)
}
@@ -0,0 +1,123 @@
//! Active Edgeless pointer gesture variants and live transform overrides.
use blocksuite_playground_doc::read::ConnectorMode;
use ui::{Pixels, Point};
use super::{HandleKind, QuickConnectDirection, ShapePreset, SpatialItemKind, WorldRect};
#[derive(Clone, Debug)]
pub struct DragItemInitial {
pub id: String,
pub kind: SpatialItemKind,
pub surface_id: Option<String>,
pub rect: WorldRect,
pub rotate_deg: f32,
pub points: Option<Vec<Vec<f64>>>,
pub connector_source: Option<(Option<String>, Option<[f64; 2]>)>,
pub connector_target: Option<(Option<String>, Option<[f64; 2]>)>,
pub connector_label_xywh: Option<[f64; 4]>,
}
/// Active pointer gesture on the Edgeless canvas.
#[derive(Clone, Debug)]
pub enum EdgelessGesture {
Pan {
start_screen: Point<Pixels>,
last_screen: Point<Pixels>,
moved: bool,
},
Marquee {
start_world: (f32, f32),
current_world: (f32, f32),
},
DragSelection {
start_world: (f32, f32),
current_world: (f32, f32),
initial: Vec<DragItemInitial>,
shift: bool,
alt_clone: bool,
pending_dblclick: Option<(String, (f32, f32))>,
},
ResizeSelection {
handle: HandleKind,
start_world: (f32, f32),
current_world: (f32, f32),
initial_box: WorldRect,
initial: Vec<DragItemInitial>,
shift: bool,
rotate_deg: f32,
},
RotateSelection {
id: String,
surface_id: Option<String>,
is_block: bool,
center_world: (f32, f32),
start_angle: f64,
initial_rotate: f64,
current_rotate: f64,
},
CreateShape {
shape_type: ShapePreset,
start_world: (f32, f32),
current_world: (f32, f32),
shift: bool,
},
CreateFrame {
start_world: (f32, f32),
current_world: (f32, f32),
},
CreateNote {
start_world: (f32, f32),
current_world: (f32, f32),
},
CreateConnector {
mode: ConnectorMode,
source_id: Option<String>,
source_port: Option<[f64; 2]>,
source_world: (f32, f32),
current_world: (f32, f32),
target_id: Option<String>,
target_port: Option<[f64; 2]>,
target_world: Option<(f32, f32)>,
},
DragConnectorEndpoint {
id: String,
surface_id: String,
is_start: bool,
mode: ConnectorMode,
fixed_id: Option<String>,
fixed_port: Option<[f64; 2]>,
fixed_world: (f32, f32),
current_world: (f32, f32),
snap_id: Option<String>,
snap_port: Option<[f64; 2]>,
snap_world: Option<(f32, f32)>,
},
DrawStroke {
highlighter: bool,
points_world: Vec<(f64, f64)>,
},
QuickConnect {
source_id: String,
source_surface_id: String,
direction: QuickConnectDirection,
source_world: (f32, f32),
start_screen: Point<Pixels>,
current_world: (f32, f32),
target_id: Option<String>,
target_port: Option<[f64; 2]>,
target_world: Option<(f32, f32)>,
dragged: bool,
},
SelectLabelText {
anchor_utf16: usize,
},
}
/// Live geometry override applied during an active drag/resize/rotate gesture before commit.
#[derive(Clone, Copy, Debug)]
pub struct LiveGeomOverride {
pub rect: WorldRect,
pub rotate_deg: Option<f32>,
pub delta: (f32, f32),
}
+29 -134
View File
@@ -9,10 +9,10 @@ use blocksuite_playground_doc::read::ConnectorMode;
use ui::{CursorStyle, Pixels, Point, point, px};
use super::{
EdgelessCamera, EdgelessInlineEdit, EdgelessLabelEditor, EdgelessTool, ResizeMode, ShapePreset,
WorldRect, constrain_shift_drag, distance_to_polyline, edgeless_handle_cursor,
point_in_rotated_rect, resized_rect_constrained, rotate_point_around,
snap_connector_port_on_items,
EdgelessCamera, EdgelessGesture, EdgelessInlineEdit, EdgelessLabelEditor, EdgelessTool,
LiveGeomOverride, ResizeMode, ShapePreset, WorldRect, constrain_shift_drag,
distance_to_polyline, edgeless_handle_cursor, point_in_rotated_rect, resized_rect_constrained,
rotate_point_around, snap_connector_port_on_items,
};
/// Interactive handle on the current Edgeless selection box.
@@ -98,125 +98,6 @@ pub struct SpatialItemInfo {
pub in_mindmap: bool,
}
/// Target of an inline UTF-16 + IME label editor on the Edgeless canvas.
#[derive(Clone, Debug)]
pub struct DragItemInitial {
pub id: String,
pub kind: SpatialItemKind,
pub surface_id: Option<String>,
pub rect: WorldRect,
pub rotate_deg: f32,
pub points: Option<Vec<Vec<f64>>>,
pub connector_source: Option<(Option<String>, Option<[f64; 2]>)>,
pub connector_target: Option<(Option<String>, Option<[f64; 2]>)>,
pub connector_label_xywh: Option<[f64; 4]>,
}
/// Active pointer gesture on the Edgeless canvas.
#[derive(Clone, Debug)]
pub enum EdgelessGesture {
Pan {
start_screen: Point<Pixels>,
last_screen: Point<Pixels>,
moved: bool,
},
Marquee {
start_world: (f32, f32),
current_world: (f32, f32),
},
DragSelection {
start_world: (f32, f32),
current_world: (f32, f32),
initial: Vec<DragItemInitial>,
shift: bool,
alt_clone: bool,
pending_dblclick: Option<(String, (f32, f32))>,
},
ResizeSelection {
handle: HandleKind,
start_world: (f32, f32),
current_world: (f32, f32),
initial_box: WorldRect,
initial: Vec<DragItemInitial>,
shift: bool,
rotate_deg: f32,
},
RotateSelection {
id: String,
surface_id: Option<String>,
is_block: bool,
center_world: (f32, f32),
start_angle: f64,
initial_rotate: f64,
current_rotate: f64,
},
CreateShape {
shape_type: ShapePreset,
start_world: (f32, f32),
current_world: (f32, f32),
shift: bool,
},
CreateFrame {
start_world: (f32, f32),
current_world: (f32, f32),
},
CreateNote {
start_world: (f32, f32),
current_world: (f32, f32),
},
CreateConnector {
mode: ConnectorMode,
source_id: Option<String>,
source_port: Option<[f64; 2]>,
source_world: (f32, f32),
current_world: (f32, f32),
target_id: Option<String>,
target_port: Option<[f64; 2]>,
target_world: Option<(f32, f32)>,
},
DragConnectorEndpoint {
id: String,
surface_id: String,
is_start: bool,
mode: ConnectorMode,
fixed_id: Option<String>,
fixed_port: Option<[f64; 2]>,
fixed_world: (f32, f32),
current_world: (f32, f32),
snap_id: Option<String>,
snap_port: Option<[f64; 2]>,
snap_world: Option<(f32, f32)>,
},
DrawStroke {
highlighter: bool,
points_world: Vec<(f64, f64)>,
},
QuickConnect {
source_id: String,
source_surface_id: String,
direction: super::QuickConnectDirection,
source_world: (f32, f32),
start_screen: Point<Pixels>,
current_world: (f32, f32),
target_id: Option<String>,
target_port: Option<[f64; 2]>,
target_world: Option<(f32, f32)>,
dragged: bool,
},
SelectLabelText {
anchor_utf16: usize,
},
}
/// Live geometry override applied during an active drag/resize/rotate gesture before commit.
#[derive(Clone, Copy, Debug)]
pub struct LiveGeomOverride {
pub rect: WorldRect,
pub rotate_deg: Option<f32>,
pub delta: (f32, f32),
}
/// Interactive authoring state owned by `EdgelessCanvasState`.
pub struct EdgelessAuthoringState {
pub tool: EdgelessTool,
@@ -231,6 +112,9 @@ pub struct EdgelessAuthoringState {
pub custom_color_hex: String,
pub custom_color_editing: bool,
pub hovered_note_slice: Option<(String, usize)>,
pub quick_connect_hover: Option<super::QuickConnectHoverState>,
pub toolbar_hitboxes: Vec<crate::block_flow::FlowRect>,
pub last_frame_now_ms: f64,
pub selection: BTreeSet<String>,
pub gesture: Option<EdgelessGesture>,
pub inline_edit: Option<EdgelessInlineEdit>,
@@ -256,6 +140,9 @@ impl Default for EdgelessAuthoringState {
custom_color_hex: String::new(),
custom_color_editing: false,
hovered_note_slice: None,
quick_connect_hover: None,
toolbar_hitboxes: Vec::new(),
last_frame_now_ms: 0.0,
selection: BTreeSet::new(),
gesture: None,
inline_edit: None,
@@ -526,6 +413,16 @@ impl EdgelessAuthoringState {
mode.unwrap_or(ResizeMode::None)
}
/// True when `screen_pt` (window coordinates) lies inside the floating element toolbar or
/// any open sub-popover/color-picker hitbox.
pub fn point_in_toolbar(&self, screen_pt: Point<Pixels>, vp_origin: Point<Pixels>) -> bool {
let vx = f32::from(screen_pt.x) - f32::from(vp_origin.x);
let vy = f32::from(screen_pt.y) - f32::from(vp_origin.y);
self.toolbar_hitboxes
.iter()
.any(|r| vx >= r.x && vx <= r.right() && vy >= r.y && vy <= r.bottom())
}
/// Resolve the active hover or gesture cursor for the Edgeless canvas at `screen_pt`.
pub fn cursor_for_pointer(
&self,
@@ -536,6 +433,9 @@ impl EdgelessAuthoringState {
camera: EdgelessCamera,
readonly: bool,
) -> Option<CursorStyle> {
if self.gesture.is_none() && self.point_in_toolbar(screen_pt, vp_origin) {
return Some(CursorStyle::Arrow);
}
if let Some(gesture) = &self.gesture {
return match gesture {
EdgelessGesture::ResizeSelection {
@@ -558,6 +458,12 @@ impl EdgelessAuthoringState {
return Some(CursorStyle::OpenHand);
}
if self.tool == EdgelessTool::Select && self.inline_edit.is_none() {
if let Some(single) = self.single_selected()
&& super::hit_test_auto_complete_arrow(single, screen_pt, vp_origin, camera)
.is_some()
{
return Some(CursorStyle::PointingHand);
}
if let Some(handle) = self.hit_test_handles(
screen_pt,
vp_origin,
@@ -610,17 +516,6 @@ impl EdgelessAuthoringState {
(px_s, py_s)
};
// Rotation handle (24px above top-center for single rotatable item).
if let Some(single) = single
&& single.kind.is_rotatable()
{
let rx = mx;
let ry = y0 - 24.0;
if (rx_pt - rx).hypot(ry_pt - ry) <= 10.0 {
return Some(HandleKind::Rotate);
}
}
// Edgeless gfx 2x3 drag handle left of single selected block (matches overlay.rs clamp).
if let Some(single) = single
&& single.kind.has_gfx_drag_handle()
+17 -13
View File
@@ -8,6 +8,7 @@ mod canvas_paint;
mod element_toolbar;
mod frame_membership;
mod geometry;
mod gesture_state;
mod hit_test;
mod label_editor;
mod note_slicer;
@@ -15,6 +16,7 @@ mod order;
mod overlay;
mod overlay_label;
mod quick_connect;
mod quick_connect_preview;
mod remote_presence;
mod scene;
mod scene_headers;
@@ -30,20 +32,21 @@ pub use camera::{
};
pub use canvas::{
EDGELESS_VIEWPORT_ID, EdgelessCanvasState, EdgelessRenderInput, NOTE_CARD_PADDING,
NOTE_MIN_WIDTH, note_border_radius, note_border_style, note_collapse, note_scale,
note_shadow_type, prop_bool, prop_f32, resolve_edgeless_color, rotated_bounds, spatial_blocks,
world_bounds, world_rect,
NOTE_MIN_WIDTH, canvas_caption_shift, note_border_radius, note_border_style, note_collapse,
note_collapsed_height, note_scale, note_shadow_type, prop_bool, prop_f32,
resolve_edgeless_color, rotated_bounds, spatial_blocks, world_bounds, world_rect,
};
pub use canvas_paint::{build_edgeless_layer, build_edgeless_layer_prepared};
pub use element_toolbar::{
AlignOp, BRUSH_LINE_WIDTHS, DEFAULT_HIGHLIGHTER_LINE_WIDTH, DEFAULT_PALETTES,
EdgelessElementAction, EdgelessElementToolbarHost, ElementColorSlot, ElementSubMenu,
ElementToolbarSummary, FONT_SIZE_LIST, HIGHLIGHTER_LINE_WIDTHS, MindmapToolbarSummary,
NOTE_BACKGROUND_PALETTES, NOTE_SHADOW_PRESETS, PaletteSwatch, SHAPE_TEXT_PALETTES,
adjust_color_alpha, build_edgeless_element_toolbar, color_value_matches_swatch,
is_neutral_shape_text_color, is_transparent_color, json_to_color_value,
measure_surface_text_xywh, palette_for_slot, parse_custom_hex_color, shape_text_color_for_fill,
summarize_element_toolbar, sync_selection_from_snapshot,
NOTE_BACKGROUND_PALETTES, NOTE_BORDER_SIZES, NOTE_CORNER_RADII, NOTE_SCALE_PRESETS,
NOTE_SHADOW_PRESETS, PaletteSwatch, SHAPE_TEXT_PALETTES, SurfaceBlockKind,
SurfaceBlockToolbarSummary, adjust_color_alpha, build_edgeless_element_toolbar,
color_value_matches_swatch, is_neutral_shape_text_color, is_transparent_color,
json_to_color_value, measure_surface_text_xywh, palette_for_slot, parse_custom_hex_color,
shape_text_color_for_fill, summarize_element_toolbar, sync_selection_from_snapshot,
};
pub use frame_membership::{
compute_frame_membership_updates, find_frame_containing_point, hovered_frame_for_drag,
@@ -54,10 +57,8 @@ pub use geometry::{
resized_rect, resized_rect_constrained, resized_rect_with_min, rotate_point_around,
snap_connector_port_on_items,
};
pub use hit_test::{
DragItemInitial, EdgelessAuthoringState, EdgelessGesture, HandleKind, SpatialItemInfo,
SpatialItemKind,
};
pub use gesture_state::{DragItemInitial, EdgelessGesture, LiveGeomOverride};
pub use hit_test::{EdgelessAuthoringState, HandleKind, SpatialItemInfo, SpatialItemKind};
pub use label_editor::{
EdgelessInlineEdit, EdgelessLabelEditor, LabelSplice, LabelTarget, ShapeTextStyle,
label_editor_screen_box, utf16_len, utf16_to_byte,
@@ -72,7 +73,10 @@ pub use overlay_label::{label_editor_text_origin, layout_label_editor_paragraph}
pub use quick_connect::{
AUTO_COMPLETE_OFFSET_PX, AUTO_COMPLETE_SIZE_PX, QUICK_CONNECT_GAP_WORLD, QuickConnectDirection,
auto_complete_arrow_center, build_auto_complete_arrows, cloned_shape_world_rect,
hit_test_auto_complete_arrow,
cloned_shape_world_rect_avoiding, hit_test_auto_complete_arrow,
};
pub use quick_connect_preview::{
QUICK_CONNECT_GHOST_DELAY_MS, QuickConnectHoverState, build_quick_connect_ghost_preview,
};
pub use remote_presence::{EdgelessRemotePeer, build_remote_presence_overlay};
pub use scene::{PreparedEdgelessScene, collect_frame_children, prepare_edgeless_scene};
@@ -227,65 +227,55 @@ pub fn build_edgeless_authoring_overlay(
}
}
// Top rotation handle for rotatable items (Shape / EdgelessText / SurfaceText / Image).
// Invisible 12px outer-corner rotation hit zones (replacing legacy top protruding knob).
if single_rotatable.is_some() {
let stem_a = rotate_point_around(mx, y0, mx, my, rot_deg);
let stem_b = rotate_point_around(mx, y0 - 20.0, mx, my, rot_deg);
let knob_c = rotate_point_around(mx, y0 - 24.0, mx, my, rot_deg);
let rx = (knob_c.0 - 5.0).round();
let ry = (knob_c.1 - 5.0).round();
elements.push(
canvas(
|_, _, _| (),
move |bounds, _, window, _| {
let ox = f32::from(bounds.origin.x);
let oy = f32::from(bounds.origin.y);
let mut pb = PathBuilder::stroke(px(1.5));
pb.move_to(point(px(ox + stem_a.0), px(oy + stem_a.1)));
pb.line_to(point(px(ox + stem_b.0), px(oy + stem_b.1)));
if let Ok(path) = pb.build() {
window.paint_path(path, brand);
}
},
)
.absolute()
.inset_0()
.into_any_element(),
);
let mut r_el = div()
.absolute()
.left(px(rx))
.top(px(ry))
.w(px(10.0))
.h(px(10.0))
.rounded(px(5.0))
.bg(handle_fill)
.border_2()
.border_color(brand);
if rx >= 0.0
&& ry >= 0.0
&& rx + 10.0 <= viewport_width
&& ry + 10.0 <= viewport_height
{
r_el =
r_el.snapshot(HandleKind::Rotate.snapshot_id(), Some(EDGELESS_VIEWPORT_ID));
let rotate_zones = [
("edgeless.handle.rotate_nw", x0 - 12.0, y0 - 12.0),
(HandleKind::Rotate.snapshot_id(), x1 + 12.0, y0 - 12.0),
("edgeless.handle.rotate_se", x1 + 12.0, y1 + 12.0),
("edgeless.handle.rotate_sw", x0 - 12.0, y1 + 12.0),
];
for (snap_id, zx, zy) in rotate_zones {
let (rzx, rzy) = rotate_point_around(zx, zy, mx, my, rot_deg);
let rx = (rzx - 6.0).round();
let ry = (rzy - 6.0).round();
if rx >= 0.0
&& ry >= 0.0
&& rx + 12.0 <= viewport_width
&& ry + 12.0 <= viewport_height
{
elements.push(
div()
.absolute()
.left(px(rx))
.top(px(ry))
.w(px(12.0))
.h(px(12.0))
.snapshot(snap_id, Some(EDGELESS_VIEWPORT_ID))
.into_any_element(),
);
}
}
elements.push(r_el.into_any_element());
}
// Four-way `auto-complete` quick-connect arrows around a single selected unlocked Shape
// (suppressed for MindMap member nodes, which use MindMap `+` / `Tab` / `Enter`).
// (and left/right `+` arrows on a single selected unlocked Note), plus 300ms ghost preview.
if authoring.gesture.is_none()
&& let Some(single) = authoring.single_selected()
&& single.kind == SpatialItemKind::Shape
&& matches!(single.kind, SpatialItemKind::Shape | SpatialItemKind::Note)
&& !single.in_mindmap
{
elements.extend(super::build_auto_complete_arrows(
single,
&authoring.painted_items,
authoring.quick_connect_hover.as_ref(),
authoring.last_frame_now_ms,
camera,
viewport_width,
viewport_height,
brand,
palette.icon,
palette.border,
palette.panel,
));
}
@@ -1,13 +1,19 @@
//! Four-way `auto-complete` quick-connect arrows for a single selected Edgeless `Shape`.
//! Four-way `auto-complete` quick-connect arrows for a single selected Edgeless `Shape`,
//! plus left/right `+` quick-create arrows for a single selected `Note` (aligned with
//! BlockSuite `edgeless-auto-complete.ts`: offset 22 px, gap 100, hover white disc + primary
//! solid arrow, and `300ms` ghost preview).
use ui::{
AnyElement, BorderStyle, Bounds, Corners, Edges, Hsla, PathBuilder, Pixels, Point, canvas, div,
point, prelude::*, px, size,
};
use super::{EDGELESS_VIEWPORT_ID, EdgelessCamera, SpatialItemInfo, SpatialItemKind, WorldRect};
use super::{
EDGELESS_VIEWPORT_ID, EdgelessCamera, QuickConnectHoverState, SpatialItemInfo, SpatialItemKind,
WorldRect, build_quick_connect_ghost_preview,
};
/// Cardinal direction of a quick-connect arrow around a selected `Shape`.
/// Cardinal direction of a quick-connect arrow around a selected `Shape` or `Note`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum QuickConnectDirection {
North,
@@ -18,6 +24,7 @@ pub enum QuickConnectDirection {
impl QuickConnectDirection {
pub const ALL: [Self; 4] = [Self::North, Self::East, Self::South, Self::West];
pub const NOTE_DIRS: [Self; 2] = [Self::West, Self::East];
/// Normalized `[0..1, 0..1]` port on the source shape facing this direction.
pub fn source_port(self) -> [f64; 2] {
@@ -71,13 +78,13 @@ impl QuickConnectDirection {
}
/// Screen-space offset from the selection box edge to the center of an auto-complete arrow pill.
pub const AUTO_COMPLETE_OFFSET_PX: f32 = 24.0;
pub const AUTO_COMPLETE_OFFSET_PX: f32 = 22.0;
/// Diameter of each auto-complete arrow pill in screen pixels.
pub const AUTO_COMPLETE_SIZE_PX: f32 = 20.0;
/// Default world-space gap between a source shape and a click-cloned quick-connect shape.
pub const QUICK_CONNECT_GAP_WORLD: f32 = 80.0;
pub const AUTO_COMPLETE_SIZE_PX: f32 = 24.0;
/// Default world-space gap between a source element and a quick-connect clone (`MAIN_GAP = 100`).
pub const QUICK_CONNECT_GAP_WORLD: f32 = 100.0;
/// Compute the world-space rectangle for a shape cloned in `dir` from `source_rect`.
/// Compute the world-space rectangle for an element cloned in `dir` from `source_rect`.
pub fn cloned_shape_world_rect(source_rect: WorldRect, dir: QuickConnectDirection) -> WorldRect {
match dir {
QuickConnectDirection::North => WorldRect::new(
@@ -107,6 +114,53 @@ pub fn cloned_shape_world_rect(source_rect: WorldRect, dir: QuickConnectDirectio
}
}
/// Compute the world-space rectangle for an element cloned in `dir` from `source_rect`,
/// stepping along the perpendicular axis if the default slot overlaps an existing canvas item
/// (shapes, notes, blocks, and brush or highlighter strokes; frames, groups, and connectors are
/// not obstacles).
pub fn cloned_shape_world_rect_avoiding(
source_rect: WorldRect,
dir: QuickConnectDirection,
source_id: &str,
items: &[SpatialItemInfo],
) -> WorldRect {
let base = cloned_shape_world_rect(source_rect, dir);
let collides = |cand: WorldRect| {
items.iter().any(|item| {
item.id != source_id
&& !matches!(
item.kind,
SpatialItemKind::Frame | SpatialItemKind::Group | SpatialItemKind::Connector
)
&& item.rect.intersects(cand)
})
};
if !collides(base) {
return base;
}
const STEP_GAP: f32 = 24.0;
for step in 1..=8 {
let s = step as f32;
let offsets = match dir {
QuickConnectDirection::East | QuickConnectDirection::West => [
(0.0, s * (base.h + STEP_GAP)),
(0.0, -s * (base.h + STEP_GAP)),
],
QuickConnectDirection::North | QuickConnectDirection::South => [
(s * (base.w + STEP_GAP), 0.0),
(-s * (base.w + STEP_GAP), 0.0),
],
};
for (dx, dy) in offsets {
let cand = WorldRect::new(base.x + dx, base.y + dy, base.w, base.h);
if !collides(cand) {
return cand;
}
}
}
base
}
/// Screen-space center `(x, y)` of the auto-complete arrow pill for `dir` around `sel_box`.
pub fn auto_complete_arrow_center(
sel_box: WorldRect,
@@ -123,27 +177,48 @@ pub fn auto_complete_arrow_center(
let mx = (x0 + x1) * 0.5;
let my = (y0 + y1) * 0.5;
match dir {
QuickConnectDirection::North => (mx, y0 - AUTO_COMPLETE_OFFSET_PX - 18.0),
QuickConnectDirection::North => (mx, y0 - AUTO_COMPLETE_OFFSET_PX),
QuickConnectDirection::East => (x1 + AUTO_COMPLETE_OFFSET_PX, my),
QuickConnectDirection::South => (mx, y1 + AUTO_COMPLETE_OFFSET_PX),
QuickConnectDirection::West => (x0 - AUTO_COMPLETE_OFFSET_PX, my),
}
}
/// Hit-test the 4 quick-connect arrow pills around a single selected unlocked Shape.
fn active_directions_for(
single: &SpatialItemInfo,
camera: EdgelessCamera,
) -> &'static [QuickConnectDirection] {
if single.locked || single.in_mindmap {
return &[];
}
match single.kind {
SpatialItemKind::Shape => &QuickConnectDirection::ALL,
SpatialItemKind::Note => {
if camera.zoom >= 1.5 {
&[QuickConnectDirection::East]
} else {
&QuickConnectDirection::NOTE_DIRS
}
}
_ => &[],
}
}
/// Hit-test quick-connect arrows around a single selected unlocked Shape (4 sides) or Note (L/R).
pub fn hit_test_auto_complete_arrow(
single: &SpatialItemInfo,
screen_pt: Point<Pixels>,
vp_origin: Point<Pixels>,
camera: EdgelessCamera,
) -> Option<QuickConnectDirection> {
if single.kind != SpatialItemKind::Shape || single.locked || single.in_mindmap {
let dirs = active_directions_for(single, camera);
if dirs.is_empty() {
return None;
}
let sx = f32::from(screen_pt.x);
let sy = f32::from(screen_pt.y);
let hit_r = AUTO_COMPLETE_SIZE_PX * 0.65;
for dir in QuickConnectDirection::ALL {
let hit_r = AUTO_COMPLETE_SIZE_PX * 0.75;
for &dir in dirs {
let (cx, cy) = auto_complete_arrow_center(single.rect, dir, camera, vp_origin);
if (sx - cx).hypot(sy - cy) <= hit_r {
return Some(dir);
@@ -152,22 +227,51 @@ pub fn hit_test_auto_complete_arrow(
None
}
/// Build the 4 screen-space `auto-complete` quick-connect arrow pills around a single selected Shape.
/// Build the quick-connect arrows (and optional `300ms` ghost preview) around a selected Shape or Note.
#[allow(clippy::too_many_arguments)]
pub fn build_auto_complete_arrows(
single: &SpatialItemInfo,
painted_items: &[SpatialItemInfo],
hover: Option<&QuickConnectHoverState>,
now_ms: f64,
camera: EdgelessCamera,
viewport_width: f32,
viewport_height: f32,
brand: Hsla,
icon_muted: Hsla,
border_col: Hsla,
panel_bg: Hsla,
) -> Vec<AnyElement> {
if single.kind != SpatialItemKind::Shape || single.locked || single.in_mindmap {
let dirs = active_directions_for(single, camera);
if dirs.is_empty() {
return Vec::new();
}
let is_note = single.kind == SpatialItemKind::Note;
let hovered_dir = hover
.filter(|h| h.source_id == single.id)
.map(|h| h.direction);
let vp_origin = point(px(0.0), px(0.0));
let half = AUTO_COMPLETE_SIZE_PX * 0.5;
let mut out = Vec::with_capacity(4);
for dir in QuickConnectDirection::ALL {
let mut out = Vec::with_capacity(dirs.len() + 1);
if let Some(h) = hover
&& h.source_id == single.id
&& h.ghost_visible(now_ms)
&& let Some(ghost) = build_quick_connect_ghost_preview(
single,
painted_items,
h.direction,
camera,
viewport_width,
viewport_height,
brand,
panel_bg,
)
{
out.push(ghost);
}
for &dir in dirs {
let (cx, cy) = auto_complete_arrow_center(single.rect, dir, camera, vp_origin);
let lx = (cx - half).round();
let ty = (cy - half).round();
@@ -178,6 +282,18 @@ pub fn build_auto_complete_arrows(
{
continue;
}
let is_hovered = hovered_dir == Some(dir);
let disc_bg = if is_hovered {
Hsla::white()
} else {
panel_bg.opacity(0.82)
};
let disc_border = if is_hovered {
brand.opacity(0.45)
} else {
border_col.opacity(0.7)
};
let glyph_col = if is_hovered { brand } else { icon_muted };
let mut el = div()
.absolute()
.left(px(lx))
@@ -185,19 +301,28 @@ pub fn build_auto_complete_arrows(
.w(px(AUTO_COMPLETE_SIZE_PX))
.h(px(AUTO_COMPLETE_SIZE_PX))
.rounded(px(half))
.bg(panel_bg)
.bg(disc_bg)
.border_1()
.border_color(brand.opacity(0.65))
.border_color(disc_border)
.flex()
.items_center()
.justify_center()
.cursor_pointer()
.child(
canvas(
|_, _, _| (),
move |bounds, _, window, _| paint_direction_chevron(bounds, dir, brand, window),
move |bounds, _, window, _| {
if is_note {
paint_plus_glyph(bounds, glyph_col, window);
} else if is_hovered {
paint_solid_arrow(bounds, dir, glyph_col, window);
} else {
paint_direction_chevron(bounds, dir, glyph_col, window);
}
},
)
.w(px(12.0))
.h(px(12.0)),
.w(px(14.0))
.h(px(14.0)),
);
el = el.snapshot(dir.snapshot_id(), Some(EDGELESS_VIEWPORT_ID));
out.push(el.into_any_element());
@@ -205,6 +330,48 @@ pub fn build_auto_complete_arrows(
out
}
fn paint_plus_glyph(bounds: Bounds<Pixels>, color: Hsla, window: &mut ui::Window) {
let cx = f32::from(bounds.origin.x) + f32::from(bounds.size.width) * 0.5;
let cy = f32::from(bounds.origin.y) + f32::from(bounds.size.height) * 0.5;
let mut pb = PathBuilder::stroke(px(1.6));
pb.move_to(point(px(cx - 4.0), px(cy)));
pb.line_to(point(px(cx + 4.0), px(cy)));
pb.move_to(point(px(cx), px(cy - 4.0)));
pb.line_to(point(px(cx), px(cy + 4.0)));
if let Ok(path) = pb.build() {
window.paint_path(path, color);
}
}
fn paint_solid_arrow(
bounds: Bounds<Pixels>,
dir: QuickConnectDirection,
color: Hsla,
window: &mut ui::Window,
) {
let cx = f32::from(bounds.origin.x) + f32::from(bounds.size.width) * 0.5;
let cy = f32::from(bounds.origin.y) + f32::from(bounds.size.height) * 0.5;
let (dx, dy) = dir.unit_vec();
let (px_v, py_v) = (-dy, dx);
let tip = point(px(cx + dx * 4.5), px(cy + dy * 4.5));
let wing_a = point(
px(cx - dx * 2.5 + px_v * 4.2),
px(cy - dy * 2.5 + py_v * 4.2),
);
let wing_b = point(
px(cx - dx * 2.5 - px_v * 4.2),
px(cy - dy * 2.5 - py_v * 4.2),
);
let mut pb = PathBuilder::fill();
pb.move_to(tip);
pb.line_to(wing_a);
pb.line_to(wing_b);
pb.close();
if let Ok(path) = pb.build() {
window.paint_path(path, color);
}
}
fn paint_direction_chevron(
bounds: Bounds<Pixels>,
dir: QuickConnectDirection,
@@ -323,10 +490,10 @@ mod tests {
fn cloned_shape_world_rect_places_all_four_directions_with_gap() {
let src = WorldRect::new(100.0, 200.0, 120.0, 80.0);
let cases = [
(QuickConnectDirection::North, (100.0, 40.0)),
(QuickConnectDirection::East, (300.0, 200.0)),
(QuickConnectDirection::South, (100.0, 360.0)),
(QuickConnectDirection::West, (-100.0, 200.0)),
(QuickConnectDirection::North, (100.0, 20.0)),
(QuickConnectDirection::East, (320.0, 200.0)),
(QuickConnectDirection::South, (100.0, 380.0)),
(QuickConnectDirection::West, (-120.0, 200.0)),
];
for (dir, (ex, ey)) in cases {
let r = cloned_shape_world_rect(src, dir);
@@ -0,0 +1,145 @@
//! Translucent `300ms` hover ghost preview for Edgeless Quick-Connect arrows (Shape & Note).
use ui::{
AnyElement, BorderStyle, Bounds, Corners, Edges, Hsla, PathBuilder, Pixels, Point, canvas, div,
point, prelude::*, px,
};
use super::{
EDGELESS_VIEWPORT_ID, EdgelessCamera, QuickConnectDirection, SpatialItemInfo, SpatialItemKind,
cloned_shape_world_rect_avoiding,
};
/// Deterministic hover dwell delay (ms) before the quick-connect ghost preview appears.
pub const QUICK_CONNECT_GHOST_DELAY_MS: f64 = 300.0;
/// Hover state tracking which quick-connect arrow is under the pointer and when hover began
/// on the deterministic scheduler clock (`now_ms`, zero wall-clock calls).
#[derive(Clone, Debug, PartialEq)]
pub struct QuickConnectHoverState {
pub source_id: String,
pub direction: QuickConnectDirection,
pub hovered_since_ms: f64,
}
impl QuickConnectHoverState {
pub fn ghost_visible(&self, now_ms: f64) -> bool {
now_ms - self.hovered_since_ms >= QUICK_CONNECT_GHOST_DELAY_MS
}
}
/// Build the translucent ghost preview element (target shape/note outline + connecting dashed line)
/// once the pointer has dwelled on a quick-connect arrow for at least `300ms`.
#[allow(clippy::too_many_arguments)]
pub fn build_quick_connect_ghost_preview(
single: &SpatialItemInfo,
painted_items: &[SpatialItemInfo],
dir: QuickConnectDirection,
camera: EdgelessCamera,
viewport_width: f32,
viewport_height: f32,
brand: Hsla,
panel_bg: Hsla,
) -> Option<AnyElement> {
let vp_origin = point(px(0.0), px(0.0));
let target_world =
cloned_shape_world_rect_avoiding(single.rect, dir, &single.id, painted_items);
let tl = camera.world_to_screen(point(px(target_world.x), px(target_world.y)), vp_origin);
let br = camera.world_to_screen(
point(px(target_world.right()), px(target_world.bottom())),
vp_origin,
);
let x = f32::from(tl.x).round();
let y = f32::from(tl.y).round();
let w = (f32::from(br.x) - f32::from(tl.x)).max(8.0).round();
let h = (f32::from(br.y) - f32::from(tl.y)).max(8.0).round();
if x + w < 0.0 || y + h < 0.0 || x > viewport_width || y > viewport_height {
return None;
}
let (sx_w, sy_w) = dir.source_world_anchor(single.rect);
let (tx_w, ty_w) = match dir {
QuickConnectDirection::North => {
(target_world.x + target_world.w * 0.5, target_world.bottom())
}
QuickConnectDirection::East => (target_world.x, target_world.y + target_world.h * 0.5),
QuickConnectDirection::South => (target_world.x + target_world.w * 0.5, target_world.y),
QuickConnectDirection::West => {
(target_world.right(), target_world.y + target_world.h * 0.5)
}
};
let s_pt: Point<Pixels> = camera.world_to_screen(point(px(sx_w), px(sy_w)), vp_origin);
let t_pt: Point<Pixels> = camera.world_to_screen(point(px(tx_w), px(ty_w)), vp_origin);
let is_note = single.kind == SpatialItemKind::Note;
let radius = if is_note {
8.0 * camera.zoom.clamp(0.4, 2.0)
} else {
6.0 * camera.zoom.clamp(0.4, 2.0)
};
let ghost_fill = if is_note {
panel_bg.opacity(0.45)
} else {
brand.opacity(0.12)
};
let ghost_border = brand.opacity(0.65);
let line_el = (!is_note).then(|| {
canvas(
|_, _, _| (),
move |bounds, _, window, _| {
let ox = f32::from(bounds.origin.x);
let oy = f32::from(bounds.origin.y);
let mut pb = PathBuilder::stroke(px(1.5));
pb.move_to(point(
px(ox + f32::from(s_pt.x)),
px(oy + f32::from(s_pt.y)),
));
pb.line_to(point(
px(ox + f32::from(t_pt.x)),
px(oy + f32::from(t_pt.y)),
));
if let Ok(path) = pb.build() {
window.paint_path(path, ghost_border);
}
},
)
.absolute()
.inset_0()
});
let ghost_card = div()
.absolute()
.left(px(x))
.top(px(y))
.w(px(w))
.h(px(h))
.snapshot(
"edgeless.auto_complete.ghost_preview",
Some(EDGELESS_VIEWPORT_ID),
)
.child(
canvas(
|_, _, _| (),
move |bounds, _, window, _| {
window.paint_quad(ui::quad(
Bounds::new(bounds.origin, bounds.size),
Corners::all(px(radius)),
ghost_fill,
Edges::all(px(1.5)),
ghost_border,
BorderStyle::Dashed,
));
},
)
.size_full(),
);
Some(
div()
.absolute()
.inset_0()
.children(line_el)
.child(ghost_card)
.into_any_element(),
)
}
+4
View File
@@ -60,14 +60,18 @@ wasm-bindgen.workspace = true
wasm-bindgen-futures.workspace = true
web-sys = { workspace = true, features = [
"BinaryType",
"Blob",
"BlobPropertyBag",
"CloseEvent",
"Document",
"Element",
"HtmlAnchorElement",
"HtmlCanvasElement",
"Location",
"MessageEvent",
"RequestInit",
"Response",
"Url",
"UrlSearchParams",
"WebSocket",
"Window",
@@ -283,9 +283,13 @@ impl PlaygroundView {
self.edgeless.ensure_camera_initialized(&snapshot, 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);
self.step_edgeless_camera_transition(now_ms, vp_size, window);
self.edgeless
.caption_draft
.clone_from(&self.flow.caption_draft);
let render_snapshot = self
.preedit_snapshot()
.map(Rc::new)
@@ -374,6 +378,7 @@ impl PlaygroundView {
editing_selection,
local_collapsed: Some(&self.flow.local_collapsed),
};
self.edgeless.authoring.last_frame_now_ms = self.now_ms(cx);
let layer = edgeless::build_edgeless_layer_prepared(
&mut self.edgeless,
prepared,
@@ -398,6 +403,8 @@ impl PlaygroundView {
.absolute()
.size_full()
});
let caption_elements =
self.edgeless_caption_elements(window, palette, self.caret_blink_alpha(now_ms));
div()
.relative()
@@ -419,6 +426,9 @@ impl PlaygroundView {
.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),
@@ -440,6 +450,7 @@ impl PlaygroundView {
cx.listener(Self::on_edgeless_pan_start),
)
.child(layer)
.children(caption_elements)
.children(input_overlay)
.into_any_element()
}
@@ -176,6 +176,35 @@ impl PlaygroundView {
cur_y += it.rect.h + gap;
}
}
AlignOp::AutoArrange => {
items.sort_by(|a, b| {
a.rect
.y
.total_cmp(&b.rect.y)
.then_with(|| a.rect.x.total_cmp(&b.rect.x))
});
let cols = (items.len() as f32).sqrt().ceil().max(1.0) as usize;
let gap = 24.0_f32;
let mut cur_y = min_y;
for row_items in items.chunks(cols) {
let mut cur_x = min_x;
let mut row_h = 0.0_f32;
for it in row_items {
updates.push((
it.clone(),
[
cur_x as f64,
cur_y as f64,
it.rect.w as f64,
it.rect.h as f64,
],
));
cur_x += it.rect.w + gap;
row_h = row_h.max(it.rect.h);
}
cur_y += row_h + gap;
}
}
}
let now_ms = self.now_ms(cx) as u64;
@@ -206,6 +206,7 @@ impl PlaygroundView {
.and_then(|page| page.read_page_snapshot().ok())
.map(std::rc::Rc::new);
self.doc_rev += 1;
self.sync_caption_editor_from_snapshot();
cx.notify();
}
}
@@ -114,10 +114,24 @@ impl PlaygroundView {
&mut || self.fresh_block_id(),
));
}
let prepared_notes: Vec<PastedBlockNode> = preallocated_notes
let mut prepared_notes: Vec<PastedBlockNode> = preallocated_notes
.iter()
.map(|n| paste::materialize_pasted_block_tree_with_offset(n, true, dx, dy, &id_map))
.collect();
for note in &mut prepared_notes {
let Ok(next_idx) = next_index_after(prev_index.as_deref()) else {
return false;
};
prev_index = Some(next_idx.clone());
if let Some((_, val)) = note.entries.iter_mut().find(|(k, _)| k == "prop:index") {
*val = SessionValue::Any(y_octo::Any::String(next_idx));
} else {
note.entries.push((
"prop:index".to_string(),
SessionValue::Any(y_octo::Any::String(next_idx)),
));
}
}
let mut remapped_elems: Vec<(String, Vec<(String, SessionValue)>)> =
Vec::with_capacity(surface_elems.len());
@@ -211,7 +225,21 @@ fn serialize_edgeless_ids(
} else if let Some(node) = find_block(snapshot, id)
&& matches!(
node.flavour.as_str(),
"affine:note" | "affine:frame" | "affine:edgeless-text"
"affine:note"
| "affine:frame"
| "affine:edgeless-text"
| "affine:image"
| "affine:attachment"
| "affine:bookmark"
| "affine:embed-linked-doc"
| "affine:embed-synced-doc"
| "affine:embed-youtube"
| "affine:embed-figma"
| "affine:embed-github"
| "affine:embed-loom"
| "affine:embed-iframe"
| "affine:embed-html"
| "affine:embed-web"
)
{
serialized_ids.insert(node.id.clone());
@@ -0,0 +1,636 @@
//! Real pointer and keyboard regressions for canvas media blocks: caption editing below the
//! block frame, card style and view switches with their standard frames, quick-connect
//! placement around strokes, and idempotent z-order at the ends of a paint stream.
use blocksuite_playground_doc::{
read::{BlockContent, SurfaceElementKind},
schema::{BlockSpec, SurfaceElementSpec},
};
use ui::{Keystroke, Modifiers, point, px};
use crate::PlaygroundView;
use super::{
EdgelessElementAction, EdgelessTool, QuickConnectDirection, auto_complete_arrow_center,
edgeless_toolbar_tests::start_edgeless_toolbar_view, find_surface_element, parse_xywh,
};
type Win = ui::WindowHandle<PlaygroundView>;
fn frame(app: &ui::ApplicationHandle, win: Win, hw: &ui::HeadlessWindow) -> ui::FrameSnapshot {
hw.request_frame();
app.update(|cx| win.update(cx, |_, w, _| w.frame_snapshot().clone()))
.unwrap()
}
fn click(
app: &ui::ApplicationHandle,
win: Win,
hw: &ui::HeadlessWindow,
platform: &ui::HeadlessPlatform,
id: &str,
) {
let snap = frame(app, win, hw);
let b = snap
.elements
.get(id)
.unwrap_or_else(|| panic!("missing {id}"))
.bounds;
hw.simulate_click(point(px(b.x + b.width * 0.5), px(b.y + b.height * 0.5)));
platform.run_until_parked();
}
/// Send one key the way a keyboard does: key handlers first, then text input.
fn keystroke(
app: &ui::ApplicationHandle,
win: Win,
hw: &ui::HeadlessWindow,
platform: &ui::HeadlessPlatform,
key: &str,
modifiers: Modifiers,
) {
hw.request_frame();
platform.run_until_parked();
let keystroke = Keystroke {
modifiers,
key: key.to_string(),
key_char: (key.chars().count() == 1 && modifiers == Modifiers::default())
.then(|| key.to_string()),
};
app.update(|cx| {
ui::AnyWindowHandle::from(win)
.update(cx, |_, window, cx| window.dispatch_keystroke(keystroke, cx))
.unwrap()
});
platform.run_until_parked();
}
/// Write the current frame to `$EDGELESS_EVIDENCE_DIR/<name>` when that variable is set.
fn save_evidence(app: &ui::ApplicationHandle, win: Win, name: &str) {
let Ok(dir) = std::env::var("EDGELESS_EVIDENCE_DIR") else {
return;
};
std::fs::create_dir_all(&dir).unwrap();
let img = app
.update(|cx| win.update(cx, |_, window, _| window.render_to_image()))
.unwrap()
.expect("render_to_image");
img.save(std::path::Path::new(&dir).join(name)).unwrap();
}
fn command() -> Modifiers {
Modifiers {
platform: true,
control: true,
..Modifiers::default()
}
}
fn seed_canvas_blocks(app: &ui::ApplicationHandle, win: Win) {
let png: Vec<u8> = {
let mut buf = Vec::new();
image::RgbaImage::from_fn(96, 96, |x, y| {
image::Rgba([0x22 + (x as u8), 0x66 + (y as u8), 0xCC, 0xFF])
})
.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
.unwrap();
buf
};
app.update(|cx| {
win.update(cx, |v, _, cx| {
v.state.blobs.insert("img-blob".into(), png.into());
let commit = v
.page_mut()
.unwrap()
.structural_edit(300, |page| {
page.add_block(
"img-cap",
BlockSpec::Image {
source_id: "img-blob".into(),
width: 120.0,
height: 120.0,
caption: String::new(),
xywh: None,
},
Some("surf"),
None,
300,
)?;
page.set_block_xywh("img-cap", [140.0, 420.0, 120.0, 120.0], 300)?;
page.set_block_index("img-cap", "aN", 300)?;
page.add_block(
"bm-style",
BlockSpec::Bookmark {
url: "https://www.youtube.com/watch?v=dQw4w9WgXcQ".into(),
title: Some("Demo Video".into()),
description: None,
},
Some("surf"),
None,
300,
)?;
page.set_block_xywh("bm-style", [640.0, 620.0, 320.0, 116.0], 300)?;
page.set_block_index("bm-style", "aO", 300)?;
page.set_block_caption("bm-style", "Talk", 300)?;
Ok(())
})
.unwrap()
.unwrap();
v.did_edgeless_doc_commit(commit, cx);
})
})
.unwrap();
}
fn caption_of(v: &PlaygroundView, id: &str) -> Option<String> {
let snap = v.page_snapshot()?;
let node = snap.block(id)?;
blocksuite_editor::overlays::block_caption_text(&node.content).map(str::to_string)
}
fn xywh_of(v: &PlaygroundView, id: &str) -> [f32; 4] {
let snap = v.page_snapshot().unwrap();
let r = parse_xywh(
snap.block(id)
.unwrap()
.props
.get("prop:xywh")
.and_then(|v| v.as_str())
.unwrap(),
)
.unwrap();
[r.x, r.y, r.w, r.h]
}
#[test]
fn canvas_image_caption_owns_keys_draws_below_frame_and_closes_cleanly() {
let (platform, app, win, hw) = start_edgeless_toolbar_view();
seed_canvas_blocks(&app, win);
app.update(|cx| {
win.update(cx, |v, _, cx| {
v.edgeless_set_selection(["img-cap".into()], cx)
})
})
.unwrap();
click(
&app,
win,
&hw,
&platform,
"chrome.edgeless_element_toolbar.media_caption",
);
let opened = app
.update(|cx| {
win.update(cx, |v, _, _| {
v.active_caption_editor().map(|ed| ed.block_id.clone())
})
})
.unwrap();
assert_eq!(opened.as_deref(), Some("img-cap"));
// Tool hotkeys (`n`, `t`) and `Backspace` edit the caption instead of the canvas.
for key in ["n", "o", "t", "e", "backspace", "k"] {
keystroke(&app, win, &hw, &platform, key, Modifiers::default());
}
let snap = frame(&app, win, &hw);
save_evidence(&app, win, "canvas-image-caption-editing.png");
let (tool, image_bottom, caption) = app
.update(|cx| {
win.update(cx, |v, _, _| {
let item = v
.edgeless
.authoring
.painted_items
.iter()
.find(|i| i.id == "img-cap")
.expect("image stays on the canvas")
.clone();
let bottom = v.edgeless.camera.world_to_screen(
point(px(item.rect.x), px(item.rect.bottom())),
point(px(0.0), px(crate::TOPBAR_HEIGHT)),
);
(
v.edgeless.authoring.tool,
f32::from(bottom.y),
caption_of(v, "img-cap"),
)
})
})
.unwrap();
assert_eq!(tool, EdgelessTool::Select);
assert_eq!(caption.as_deref(), Some("notk"));
let focus = snap
.elements
.get("edgeless.caption_focus")
.expect("caption slot is drawn while editing");
assert_eq!(focus.text.as_deref(), Some("notk"));
let caret = snap
.elements
.get("edgeless.caption_caret")
.expect("caret is drawn while editing")
.bounds;
assert!(
caret.y >= image_bottom && focus.bounds.y >= image_bottom,
"caption sits below the image frame: caret {caret:?}, frame bottom {image_bottom}"
);
// `Enter` closes the editor; one undo restores the empty caption.
keystroke(&app, win, &hw, &platform, "enter", Modifiers::default());
app.update(|cx| {
win.update(cx, |v, _, _| {
assert!(v.active_caption_editor().is_none());
assert_eq!(caption_of(v, "img-cap").as_deref(), Some("notk"));
})
})
.unwrap();
keystroke(&app, win, &hw, &platform, "z", command());
app.update(|cx| {
win.update(cx, |v, _, _| {
assert_eq!(caption_of(v, "img-cap").as_deref(), Some(""));
})
})
.unwrap();
// `Escape` commits and closes; deleting the block closes a reopened editor.
app.update(|cx| {
win.update(cx, |v, _, cx| {
v.edgeless_set_selection(["img-cap".into()], cx)
})
})
.unwrap();
click(
&app,
win,
&hw,
&platform,
"chrome.edgeless_element_toolbar.media_caption",
);
keystroke(&app, win, &hw, &platform, "x", Modifiers::default());
keystroke(&app, win, &hw, &platform, "escape", Modifiers::default());
app.update(|cx| {
win.update(cx, |v, _, cx| {
assert!(v.active_caption_editor().is_none());
assert_eq!(caption_of(v, "img-cap").as_deref(), Some("x"));
v.edgeless_set_selection(["img-cap".into()], cx);
})
})
.unwrap();
click(
&app,
win,
&hw,
&platform,
"chrome.edgeless_element_toolbar.media_caption",
);
app.update(|cx| {
win.update(cx, |v, _, cx| {
assert!(v.active_caption_editor().is_some());
let commit = v
.page_mut()
.unwrap()
.delete_block_subtree("surf", "img-cap", 400)
.unwrap()
.unwrap();
v.did_edgeless_doc_commit(commit, cx);
assert!(
v.active_caption_editor().is_none(),
"a deleted block leaves no caption editor behind"
);
})
})
.unwrap();
let snap = frame(&app, win, &hw);
assert!(!snap.elements.contains_key("edgeless.caption_focus"));
}
#[test]
fn canvas_caption_click_places_caret_and_outside_press_closes_it() {
let (platform, app, win, hw) = start_edgeless_toolbar_view();
seed_canvas_blocks(&app, win);
app.update(|cx| win.update(cx, |v, _, cx| v.set_edgeless_camera(300.0, 300.0, 1.0, cx)))
.unwrap();
let snap = frame(&app, win, &hw);
let card = snap.elements.get("edgeless.block.bm-style").unwrap().bounds;
// The caption `Talk` is centered just below the card frame.
hw.simulate_click(point(
px(card.x + card.width * 0.5),
px(card.y + card.height + 12.0),
));
platform.run_until_parked();
keystroke(&app, win, &hw, &platform, "s", Modifiers::default());
app.update(|cx| {
win.update(cx, |v, _, _| {
let ed = v.active_caption_editor().expect("press opens the caption");
assert_eq!(ed.block_id, "bm-style");
let caption = caption_of(v, "bm-style").unwrap();
assert_eq!(caption.len(), 5);
assert!(
caption.contains('s') && caption != "Talks",
"caret placed by the press"
);
})
})
.unwrap();
hw.simulate_click(point(px(40.0), px(700.0)));
platform.run_until_parked();
app.update(|cx| win.update(cx, |v, _, _| assert!(v.active_caption_editor().is_none())))
.unwrap();
}
#[test]
fn canvas_card_style_and_view_switches_write_standard_frames_in_one_undo_step() {
let (platform, app, win, hw) = start_edgeless_toolbar_view();
seed_canvas_blocks(&app, win);
let zoom = 1.0;
app.update(|cx| win.update(cx, |v, _, cx| v.set_edgeless_camera(400.0, 520.0, zoom, cx)))
.unwrap();
// (style, width, height) from BlockSuite `EMBED_CARD_WIDTH` / `EMBED_CARD_HEIGHT`.
for (style, w, h) in [
("cube", 170.0, 114.0),
("list", 752.0, 46.0),
("vertical", 364.0, 390.0),
("horizontal", 752.0, 116.0),
] {
app.update(|cx| {
win.update(cx, |v, _, cx| {
v.edgeless_set_selection(["bm-style".into()], cx);
v.apply_edgeless_element_action(
EdgelessElementAction::ToggleSubMenu(super::ElementSubMenu::MediaStyle),
cx,
);
})
})
.unwrap();
click(
&app,
win,
&hw,
&platform,
&format!("chrome.edgeless_element_toolbar.sub.style_{style}"),
);
let snap = frame(&app, win, &hw);
app.update(|cx| {
win.update(cx, |v, _, _| {
assert_eq!(xywh_of(v, "bm-style"), [640.0, 620.0, w, h], "{style}");
let item = v.edgeless.authoring.single_selected().unwrap();
assert_eq!(
(item.rect.w, item.rect.h),
(w, h),
"selection box of {style}"
);
})
})
.unwrap();
if style == "cube" {
save_evidence(&app, win, "canvas-bookmark-cube-selection.png");
}
let card = snap.elements.get("edgeless.block.bm-style").unwrap().bounds;
assert!(
(card.width - w * zoom).abs() < 0.5 && (card.height - h * zoom).abs() < 0.5,
"{style} card fills its frame: {card:?}"
);
}
app.update(|cx| {
win.update(cx, |v, _, cx| {
let commit = v.page_mut().unwrap().undo().unwrap().unwrap();
v.did_edgeless_doc_commit(commit, cx);
assert_eq!(xywh_of(v, "bm-style"), [640.0, 620.0, 364.0, 390.0]);
let snap = v.page_snapshot().unwrap();
assert_eq!(
snap.block("bm-style")
.unwrap()
.props
.get("prop:style")
.and_then(|s| s.as_str()),
Some("vertical"),
"one undo restores style and frame together"
);
})
})
.unwrap();
// Bookmark -> YouTube embed -> bookmark, each one undo step that the selection follows.
app.update(|cx| {
win.update(cx, |v, _, cx| {
v.edgeless_set_selection(["bm-style".into()], cx)
})
})
.unwrap();
click(
&app,
win,
&hw,
&platform,
"chrome.edgeless_element_toolbar.media_view",
);
frame(&app, win, &hw);
let embed_id = app
.update(|cx| {
win.update(cx, |v, _, _| {
let id = v.edgeless.authoring.single_selected().unwrap().id.clone();
let snap = v.page_snapshot().unwrap();
let node = snap.block(&id).unwrap();
assert!(matches!(node.content, BlockContent::ExternalEmbed { .. }));
assert_eq!(
node.props.get("prop:style").and_then(|s| s.as_str()),
Some("video")
);
assert_eq!(xywh_of(v, &id), [640.0, 620.0, 752.0, 544.0]);
assert_eq!(caption_of(v, &id).as_deref(), Some("Talk"));
id
})
})
.unwrap();
click(
&app,
win,
&hw,
&platform,
"chrome.edgeless_element_toolbar.media_view",
);
frame(&app, win, &hw);
app.update(|cx| {
win.update(cx, |v, _, cx| {
let id = v.edgeless.authoring.single_selected().unwrap().id.clone();
assert_ne!(id, embed_id);
let snap = v.page_snapshot().unwrap();
let node = snap.block(&id).unwrap();
assert!(matches!(
&node.content,
BlockContent::Bookmark { url, title, .. }
if url.contains("youtube.com") && title.as_deref() == Some("Demo Video")
));
assert_eq!(
node.props.get("prop:style").and_then(|s| s.as_str()),
Some("horizontal")
);
assert_eq!(xywh_of(v, &id), [640.0, 620.0, 752.0, 116.0]);
assert_eq!(caption_of(v, &id).as_deref(), Some("Talk"));
let commit = v.page_mut().unwrap().undo().unwrap().unwrap();
v.did_edgeless_doc_commit(commit, cx);
let snap = v.page_snapshot().unwrap();
assert!(snap.block(&id).is_none());
assert!(matches!(
snap.block(&embed_id).unwrap().content,
BlockContent::ExternalEmbed { .. }
));
})
})
.unwrap();
}
#[test]
fn quick_connect_south_clone_avoids_highlighter_stroke() {
let (platform, app, win, hw) = start_edgeless_toolbar_view();
app.update(|cx| {
win.update(cx, |v, _, cx| {
let commit = v
.page_mut()
.unwrap()
.structural_edit(300, |page| {
page.add_surface_element(
"surf",
"hl-south".to_string(),
"b1",
SurfaceElementSpec::Highlighter {
seed: 5,
points: vec![
vec![0.0, 0.0, 0.5],
vec![140.0, 100.0, 0.5],
vec![0.0, 200.0, 0.5],
],
xywh: "[430,300,140,200]".into(),
},
300,
)?;
Ok(())
})
.unwrap()
.unwrap();
v.did_edgeless_doc_commit(commit, cx);
v.edgeless_set_selection(["shape-a".into()], cx);
})
})
.unwrap();
frame(&app, win, &hw);
let arrow = app
.update(|cx| {
win.update(cx, |v, _, _| {
let single = v.edgeless.authoring.single_selected().unwrap().clone();
auto_complete_arrow_center(
single.rect,
QuickConnectDirection::South,
v.edgeless.camera,
point(px(0.0), px(crate::TOPBAR_HEIGHT)),
)
})
})
.unwrap();
hw.simulate_click(point(px(arrow.0), px(arrow.1)));
platform.run_until_parked();
frame(&app, win, &hw);
app.update(|cx| {
win.update(cx, |v, _, _| {
let snap = v.snapshot.as_ref().unwrap();
let stroke = v
.edgeless
.authoring
.painted_items
.iter()
.find(|i| i.id == "hl-south")
.unwrap()
.rect;
let clones: Vec<_> = v
.edgeless
.authoring
.painted_items
.iter()
.filter(|i| {
find_surface_element(snap, &i.id)
.is_some_and(|(_, el)| matches!(el.kind, SurfaceElementKind::Shape(_)))
&& !["shape-a", "shape-b", "shape-c", "mm-root", "mm-c1", "mm-c2"]
.contains(&i.id.as_str())
})
.collect();
assert_eq!(clones.len(), 1, "one clone from the south arrow");
assert!(
!clones[0].rect.intersects(stroke),
"clone {:?} covers the stroke {stroke:?}",
clones[0].rect
);
})
})
.unwrap();
}
#[test]
fn z_order_at_the_end_of_its_stream_writes_nothing() {
let (platform, app, win, hw) = start_edgeless_toolbar_view();
app.update(|cx| {
win.update(cx, |v, _, cx| {
let commit = v
.page_mut()
.unwrap()
.structural_edit(300, |page| {
page.add_surface_element(
"surf",
"shape-top".to_string(),
"b9",
SurfaceElementSpec::Shape {
shape_type: "rect".into(),
xywh: "[120,560,120,80]".into(),
seed: 31,
filled: true,
text: None,
},
300,
)?;
Ok(())
})
.unwrap()
.unwrap();
v.did_edgeless_doc_commit(commit, cx);
})
})
.unwrap();
// `shape-a` (`a1`) is the lowest canvas element and `shape-top` (`b9`) the highest; the
// frame and notes below or above them belong to the block stream.
for (id, item) in [
("shape-a", "send_backward"),
("shape-a", "send_to_back"),
("shape-top", "bring_forward"),
("shape-top", "bring_to_front"),
] {
let (doc, can_undo) = app
.update(|cx| {
win.update(cx, |v, _, cx| {
v.edgeless_set_selection([id.into()], cx);
let page = v.page().unwrap();
(page.encode_update_v1().unwrap(), page.can_undo())
})
})
.unwrap();
click(
&app,
win,
&hw,
&platform,
"chrome.edgeless_element_toolbar.more",
);
click(
&app,
win,
&hw,
&platform,
&format!("chrome.edgeless_element_toolbar.more.{item}"),
);
app.update(|cx| {
win.update(cx, |v, _, _| {
let page = v.page().unwrap();
assert_eq!(page.encode_update_v1().unwrap(), doc, "{id} {item}");
assert_eq!(page.can_undo(), can_undo, "{id} {item}");
})
})
.unwrap();
}
}
@@ -0,0 +1,528 @@
//! Regression tests for Edgeless `Display in Page` round-trip toggle, canvas media/embed
//! open/info/reload/download/view-toggle/duplicate actions, multi-select z-order step reorder,
//! and bounded `ReleaseFromGroup` with empty-group cleanup.
use blocksuite_playground_doc::{
read::{BlockContent, NoteDisplayMode},
schema::{BlockSpec, ParagraphType, SurfaceElementSpec},
session::PageDocSession,
};
use super::{
EdgelessElementAction, edgeless_toolbar_tests::start_edgeless_toolbar_view,
find_surface_element,
};
#[test]
fn note_display_in_page_round_trip_toggle_and_undo() {
let (_platform, app, win, hw) = start_edgeless_toolbar_view();
app.update(|cx| {
win.update(cx, |v, _, cx| {
let commit = v
.page_mut()
.unwrap()
.structural_edit(200, |page| {
page.add_block(
"note-extra",
BlockSpec::Note {
xywh: Some("[60,380,260,120]".into()),
},
Some("root"),
None,
200,
)?;
page.add_block(
"note-extra-p",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: "Secondary note".into(),
},
Some("note-extra"),
None,
200,
)?;
Ok(())
})
.unwrap()
.unwrap();
v.did_edgeless_doc_commit(commit, cx);
v.edgeless_set_selection(["note-extra".into()], cx);
})
})
.unwrap();
hw.request_frame();
// Starts as Both -> Display in Page is mounted.
let s1 = app
.update(|cx| win.update(cx, |_, w, _| w.frame_snapshot().clone()))
.unwrap();
assert!(
s1.elements
.contains_key("chrome.edgeless_element_toolbar.note_display")
);
// Toggle Both -> EdgelessOnly: switch must remain mounted so user can toggle back.
app.update(|cx| {
win.update(cx, |v, _, cx| {
v.apply_edgeless_element_action(EdgelessElementAction::ToggleNoteDisplayMode, cx);
})
})
.unwrap();
hw.request_frame();
let s2 = app
.update(|cx| win.update(cx, |_, w, _| w.frame_snapshot().clone()))
.unwrap();
assert!(
s2.elements
.contains_key("chrome.edgeless_element_toolbar.note_display"),
"Display in Page must remain mounted after switching to edgeless"
);
app.update(|cx| {
win.update(cx, |v, _, cx| {
let snap = v.page_snapshot().unwrap();
assert!(matches!(
snap.block("note-extra").unwrap().content,
BlockContent::Note {
display_mode: NoteDisplayMode::EdgelessOnly,
..
}
));
// Toggle EdgelessOnly -> Both.
v.apply_edgeless_element_action(EdgelessElementAction::ToggleNoteDisplayMode, cx);
let snap2 = v.page_snapshot().unwrap();
assert!(matches!(
snap2.block("note-extra").unwrap().content,
BlockContent::Note {
display_mode: NoteDisplayMode::Both,
..
}
));
// Undo -> EdgelessOnly, Undo -> Both.
let c1 = v.page_mut().unwrap().undo().unwrap().unwrap();
v.did_edgeless_doc_commit(c1, cx);
assert!(matches!(
v.page_snapshot()
.unwrap()
.block("note-extra")
.unwrap()
.content,
BlockContent::Note {
display_mode: NoteDisplayMode::EdgelessOnly,
..
}
));
let c2 = v.page_mut().unwrap().undo().unwrap().unwrap();
v.did_edgeless_doc_commit(c2, cx);
assert!(matches!(
v.page_snapshot()
.unwrap()
.block("note-extra")
.unwrap()
.content,
BlockContent::Note {
display_mode: NoteDisplayMode::Both,
..
}
));
})
})
.unwrap();
}
#[test]
fn media_open_embed_doc_info_reload_download_toggle_and_canvas_block_duplicate() {
let (_platform, app, win, hw) = start_edgeless_toolbar_view();
let png_bytes: Vec<u8> = {
let mut buf = Vec::new();
let img = image::RgbaImage::from_pixel(4, 4, image::Rgba([0x22, 0x66, 0xCC, 0xFF]));
img.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
.unwrap();
buf
};
let png_clone = png_bytes.clone();
app.update(|cx| {
win.update(cx, |v, _, cx| {
v.state
.workspace
.create_page("linked-target", "Linked Target Page", 240)
.unwrap();
let target_page = v.state.workspace.ensure_page("linked-target").unwrap();
target_page
.add_block(
"t-root",
BlockSpec::Page {
title: "Linked Target Page".into(),
},
None,
None,
240,
)
.unwrap();
v.state
.blobs
.insert("img-blob-1".into(), png_clone.clone().into());
let commit = v
.page_mut()
.unwrap()
.structural_edit(250, |page| {
page.add_block(
"embed-doc-1",
BlockSpec::EmbedLinkedDoc {
page_id: "linked-target".into(),
style: "horizontal".into(),
caption: "Spec".into(),
},
Some("surf"),
None,
250,
)?;
page.set_block_xywh("embed-doc-1", [120.0, 420.0, 320.0, 110.0], 250)?;
page.set_block_index("embed-doc-1", "aM", 250)?;
page.add_block(
"img-canvas-1",
BlockSpec::Image {
source_id: "img-blob-1".into(),
width: 120.0,
height: 120.0,
caption: "diagram.png".into(),
xywh: None,
},
Some("surf"),
None,
250,
)?;
page.set_block_xywh("img-canvas-1", [480.0, 420.0, 120.0, 120.0], 250)?;
page.set_block_index("img-canvas-1", "aN", 250)?;
page.add_block(
"bm-yt",
BlockSpec::Bookmark {
url: "https://www.youtube.com/watch?v=dQw4w9WgXcQ".into(),
title: Some("Demo Video".into()),
description: None,
},
Some("surf"),
None,
250,
)?;
page.set_block_xywh("bm-yt", [640.0, 420.0, 320.0, 116.0], 250)?;
page.set_block_index("bm-yt", "aO", 250)?;
Ok(())
})
.unwrap()
.unwrap();
v.did_edgeless_doc_commit(commit, cx);
})
})
.unwrap();
hw.request_frame();
// 1. EmbedLinkedDoc <-> EmbedSyncedDoc toggle in 1 undo step, 0 bogus prop:embed.
app.update(|cx| {
win.update(cx, |v, _, cx| {
v.edgeless_set_selection(["embed-doc-1".into()], cx);
v.apply_edgeless_element_action(EdgelessElementAction::MediaToggleView, cx);
})
})
.unwrap();
hw.request_frame();
let synced_id = app
.update(|cx| {
win.update(cx, |v, _, _| {
let id = v.edgeless.authoring.single_selected().unwrap().id.clone();
let snap = v.page_snapshot().unwrap();
let node = snap.block(&id).unwrap();
assert!(matches!(
&node.content,
BlockContent::EmbedSyncedDoc { page_id, .. } if page_id == "linked-target"
));
assert!(!node.props.contains_key("prop:embed"));
id
})
})
.unwrap();
app.update(|cx| {
win.update(cx, |v, _, cx| {
v.apply_edgeless_element_action(EdgelessElementAction::MediaToggleView, cx);
})
})
.unwrap();
hw.request_frame();
app.update(|cx| {
win.update(cx, |v, _, _| {
let id = v.edgeless.authoring.single_selected().unwrap().id.clone();
assert_ne!(id, synced_id);
let snap = v.page_snapshot().unwrap();
assert!(matches!(
&snap.block(&id).unwrap().content,
BlockContent::EmbedLinkedDoc { page_id, .. } if page_id == "linked-target"
));
})
})
.unwrap();
// 2. Embeddable YouTube bookmark converts to ExternalEmbed in 1 undo step.
app.update(|cx| {
win.update(cx, |v, _, cx| {
v.edgeless_set_selection(["bm-yt".into()], cx);
v.apply_edgeless_element_action(EdgelessElementAction::MediaToggleView, cx);
})
})
.unwrap();
hw.request_frame();
app.update(|cx| {
win.update(cx, |v, _, _| {
let id = v.edgeless.authoring.single_selected().unwrap().id.clone();
let snap = v.page_snapshot().unwrap();
let node = snap.block(&id).unwrap();
assert!(matches!(node.content, BlockContent::ExternalEmbed { .. }));
assert!(!node.props.contains_key("prop:embed"));
})
})
.unwrap();
// 3. Info opens doc_panel Info, Reload clears stale Unavailable slot, Download emits bytes, Duplicate clones canvas block.
app.update(|cx| {
win.update(cx, |v, _, cx| {
v.edgeless_set_selection(["img-canvas-1".into()], cx);
v.apply_edgeless_element_action(EdgelessElementAction::MediaInfo, cx);
assert_eq!(v.doc_panel_tab(), Some(crate::DocPanelTab::Info));
v.images.insert(
"img-blob-1".into(),
crate::block_flow::ImageSlot::Unavailable,
);
v.apply_edgeless_element_action(EdgelessElementAction::MediaReload, cx);
assert!(matches!(
v.images.get("img-blob-1"),
Some(crate::block_flow::ImageSlot::Ready(_))
));
let seen = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
let sink = seen.clone();
v.set_on_media_download(move |media| sink.borrow_mut().push(media.clone()));
v.apply_edgeless_element_action(EdgelessElementAction::MediaDownload, cx);
let downloads = seen.borrow();
assert_eq!(downloads.len(), 1);
assert_eq!(downloads[0].filename, "diagram.png");
assert_eq!(downloads[0].bytes, png_bytes);
v.apply_edgeless_element_action(EdgelessElementAction::Duplicate, cx);
})
})
.unwrap();
hw.request_frame();
app.update(|cx| {
win.update(cx, |v, _, cx| {
let dup_id = v.edgeless.authoring.single_selected().unwrap().id.clone();
assert_ne!(dup_id, "img-canvas-1");
let snap = v.page_snapshot().unwrap();
let dup_node = snap.block(&dup_id).expect("duplicated canvas image block");
assert!(matches!(dup_node.content, BlockContent::Image { .. }));
let rect = super::parse_xywh(
dup_node
.props
.get("prop:xywh")
.and_then(|v| v.as_str())
.unwrap(),
)
.unwrap();
assert!((rect.x - 504.0).abs() <= 1.0 && (rect.y - 444.0).abs() <= 1.0);
let orig_idx = snap
.block("img-canvas-1")
.unwrap()
.props
.get("prop:index")
.and_then(|v| v.as_str())
.unwrap();
let dup_idx = dup_node
.props
.get("prop:index")
.and_then(|v| v.as_str())
.unwrap();
assert!(
dup_idx > orig_idx,
"cloned block must get monotonic prop:index"
);
// 1 undo removes cloned block.
let c = v.page_mut().unwrap().undo().unwrap().unwrap();
v.did_edgeless_doc_commit(c, cx);
assert!(v.page_snapshot().unwrap().block(&dup_id).is_none());
})
})
.unwrap();
// 4. Open on EmbedLinkedDoc navigates to linked-target.
app.update(|cx| {
win.update(cx, |v, _, cx| {
let snap = v.page_snapshot().unwrap();
let linked_id = snap
.root
.as_ref()
.unwrap()
.walk()
.find(|n| matches!(n.content, BlockContent::EmbedLinkedDoc { .. }))
.unwrap()
.id
.clone();
v.edgeless_set_selection([linked_id], cx);
v.apply_edgeless_element_action(EdgelessElementAction::MediaOpenLink, cx);
assert_eq!(v.page_id.as_deref(), Some("linked-target"));
})
})
.unwrap();
}
#[test]
fn multi_select_step_reorder_and_bounded_release_from_group() {
let (_platform, app, win, hw) = start_edgeless_toolbar_view();
app.update(|cx| {
win.update(cx, |v, _, cx| {
let commit = v
.page_mut()
.unwrap()
.structural_edit(300, |page| {
for (id, idx, x) in [
("ord-a", "aP", 60.0),
("ord-b", "aQ", 160.0),
("ord-c", "aR", 260.0),
("grp-only", "aS", 400.0),
("after-grp", "aU", 520.0),
] {
page.add_surface_element(
"surf",
id.to_string(),
idx,
SurfaceElementSpec::Shape {
shape_type: "rect".into(),
xywh: PageDocSession::format_xywh([x, 560.0, 80.0, 60.0]),
seed: 41,
filled: true,
text: None,
},
300,
)?;
}
page.add_surface_element(
"surf",
"grp-solo".to_string(),
"aT",
SurfaceElementSpec::Group {
seed: 42,
title: "Solo".into(),
children: vec!["grp-only".into()],
},
300,
)?;
Ok(())
})
.unwrap()
.unwrap();
v.did_edgeless_doc_commit(commit, cx);
})
})
.unwrap();
hw.request_frame();
// 1. Multi-select adjacent [ord-a, ord-b] below ord-c -> BringForward moves both above ord-c keeping ord-c < ord-a < ord-b.
app.update(|cx| {
win.update(cx, |v, _, cx| {
v.edgeless_set_selection(["ord-a".into(), "ord-b".into()], cx);
v.apply_edgeless_element_action(EdgelessElementAction::BringForward, cx);
})
})
.unwrap();
hw.request_frame();
app.update(|cx| {
win.update(cx, |v, _, _| {
let snap = v.page_snapshot().unwrap();
let idx = |id: &str| find_surface_element(&snap, id).unwrap().1.index.clone();
assert!(
idx("ord-c") < idx("ord-a") && idx("ord-a") < idx("ord-b"),
"expected ord-c < ord-a < ord-b"
);
})
})
.unwrap();
// 2. Selecting the top two siblings [after-grp, ...] at the top boundary -> BringForward is a no-op (no reversal).
app.update(|cx| {
win.update(cx, |v, _, cx| {
let top_two: Vec<String> = v
.edgeless
.authoring
.painted_items
.iter()
.filter(|i| i.parent_group_id.is_none())
.rev()
.take(2)
.map(|i| i.id.clone())
.collect();
let before_rev = v.doc_rev;
v.edgeless_set_selection(top_two, cx);
v.apply_edgeless_element_action(EdgelessElementAction::BringForward, cx);
assert_eq!(
v.doc_rev, before_rev,
"BringForward on top boundary run must be a no-op"
);
})
})
.unwrap();
// 3. SendBackward on [ord-a, ord-b] moves both below ord-c keeping ord-a < ord-b < ord-c.
app.update(|cx| {
win.update(cx, |v, _, cx| {
v.edgeless_set_selection(["ord-a".into(), "ord-b".into()], cx);
v.apply_edgeless_element_action(EdgelessElementAction::SendBackward, cx);
})
})
.unwrap();
hw.request_frame();
app.update(|cx| {
win.update(cx, |v, _, _| {
let snap = v.page_snapshot().unwrap();
let idx = |id: &str| find_surface_element(&snap, id).unwrap().1.index.clone();
assert!(
idx("ord-a") < idx("ord-b") && idx("ord-b") < idx("ord-c"),
"expected ord-a < ord-b < ord-c"
);
})
})
.unwrap();
// 4. ReleaseFromGroup bounds index before `after-grp` and deletes the now-empty `grp-solo`.
app.update(|cx| {
win.update(cx, |v, _, cx| {
v.edgeless_set_selection(["grp-only".into()], cx);
assert!(v.edgeless_release_from_group(cx));
})
})
.unwrap();
hw.request_frame();
app.update(|cx| {
win.update(cx, |v, _, _| {
let snap = v.page_snapshot().unwrap();
assert!(
find_surface_element(&snap, "grp-solo").is_none(),
"empty group must be deleted atomically"
);
let rel_idx = find_surface_element(&snap, "grp-only")
.unwrap()
.1
.index
.clone();
let after_idx = find_surface_element(&snap, "after-grp")
.unwrap()
.1
.index
.clone();
assert!(
rel_idx < after_idx,
"released item ({rel_idx}) must stay before following sibling ({after_idx})"
);
})
})
.unwrap();
}
@@ -0,0 +1,766 @@
//! Deterministic tests and offscreen screenshot capture for Edgeless element toolbar chrome,
//! `⋮ More` menu, complete Note style panel, canvas media/embed toolbars, adjacent multi-group
//! batch ungroup indexing, hover cursor isolation, outer-corner rotation, and `300ms` quick-connect
//! ghost preview.
use std::{path::PathBuf, time::Duration};
use blocksuite_playground_doc::{
read::{BlockContent, ConnectorMode, StrokeStyle, SurfaceElementKind},
schema::{BlockSpec, SurfaceElementSpec},
session::PageDocSession,
};
use ui::{CursorStyle, Modifiers, MouseMoveEvent, PlatformInput, point, px};
use crate::theme::PlaygroundTheme;
use super::{
AlignOp, EdgelessElementAction, ElementSubMenu, NOTE_SHADOW_PRESETS,
QUICK_CONNECT_GHOST_DELAY_MS, QuickConnectDirection, auto_complete_arrow_center,
edgeless_toolbar_tests::start_edgeless_toolbar_view, find_surface_element,
summarize_element_toolbar,
};
fn maybe_save_evidence(
app: &ui::ApplicationHandle,
win: ui::WindowHandle<crate::PlaygroundView>,
filename: &str,
) {
if let Ok(dir) = std::env::var("EDGELESS_EVIDENCE_DIR") {
let out_dir = PathBuf::from(&dir);
std::fs::create_dir_all(&out_dir).unwrap();
let img = app
.update(|cx| win.update(cx, |_, window, _| window.render_to_image()))
.unwrap()
.expect("render_to_image failed");
img.save(out_dir.join(filename)).expect("save png failed");
}
}
#[test]
fn adjacent_multi_group_ungroup_preserves_monotonic_order_before_following_sibling() {
let (_platform, app, win, hw) = start_edgeless_toolbar_view();
// Seed two adjacent groups `grp-1` ([g1-a, g1-b]) and `grp-2` ([g2-a, g2-b]) followed by `after-sib`.
app.update(|cx| {
win.update(cx, |v, _, cx| {
let commit = v
.page_mut()
.unwrap()
.structural_edit(100, |page| {
for (id, idx, x) in [
("g1-a", "a1", 80.0),
("g1-b", "a2", 180.0),
("g2-a", "a3", 300.0),
("g2-b", "a4", 400.0),
("after-sib", "b5", 560.0),
] {
page.add_surface_element(
"surf",
id.to_string(),
idx,
SurfaceElementSpec::Shape {
shape_type: "rect".into(),
xywh: PageDocSession::format_xywh([x, 500.0, 80.0, 60.0]),
seed: 11,
filled: true,
text: None,
},
100,
)?;
}
page.add_surface_element(
"surf",
"grp-1".to_string(),
"b1",
SurfaceElementSpec::Group {
seed: 21,
title: "Group 1".into(),
children: vec!["g1-a".into(), "g1-b".into()],
},
100,
)?;
page.add_surface_element(
"surf",
"grp-2".to_string(),
"b2",
SurfaceElementSpec::Group {
seed: 22,
title: "Group 2".into(),
children: vec!["g2-a".into(), "g2-b".into()],
},
100,
)?;
Ok(())
})
.unwrap()
.unwrap();
v.did_edgeless_doc_commit(commit, cx);
v.edgeless_set_selection(["grp-1".into(), "grp-2".into()], cx);
})
})
.unwrap();
hw.request_frame();
let ungrouped = app
.update(|cx| win.update(cx, |v, _, cx| v.edgeless_ungroup_selection(cx)))
.unwrap();
assert!(
ungrouped,
"batch ungroup must succeed for two adjacent groups"
);
hw.request_frame();
app.update(|cx| {
win.update(cx, |v, _, _| {
let snap = v.page_snapshot().unwrap();
assert!(find_surface_element(&snap, "grp-1").is_none());
assert!(find_surface_element(&snap, "grp-2").is_none());
let idx = |id: &str| find_surface_element(&snap, id).unwrap().1.index.clone();
let i1a = idx("g1-a");
let i1b = idx("g1-b");
let i2a = idx("g2-a");
let i2b = idx("g2-b");
let iafter = idx("after-sib");
assert!(
i1a < i1b && i1b < i2a && i2a < i2b && i2b < iafter,
"expected strict monotonic order g1-a({i1a}) < g1-b({i1b}) < g2-a({i2a}) < g2-b({i2b}) < after-sib({iafter})"
);
})
})
.unwrap();
}
#[test]
fn shape_toolbar_36px_chrome_more_menu_add_text_and_hover_isolation() {
let (platform, app, win, hw) = start_edgeless_toolbar_view();
// 1. Add a textless shape and verify `Add text` appears while text controls stay hidden.
app.update(|cx| {
win.update(cx, |v, _, cx| {
let commit = v
.page_mut()
.unwrap()
.structural_edit(120, |page| {
page.add_surface_element(
"surf",
"shape-empty".to_string(),
"c1",
SurfaceElementSpec::Shape {
shape_type: "rect".into(),
xywh: PageDocSession::format_xywh([120.0, 260.0, 140.0, 80.0]),
seed: 31,
filled: true,
text: None,
},
120,
)?;
Ok(())
})
.unwrap()
.unwrap();
v.did_edgeless_doc_commit(commit, cx);
v.edgeless_set_selection(["shape-empty".into()], cx);
})
})
.unwrap();
hw.request_frame();
let empty_snap = app
.update(|cx| win.update(cx, |_, w, _| w.frame_snapshot().clone()))
.unwrap();
assert!(
empty_snap
.elements
.contains_key("chrome.edgeless_element_toolbar.add_text"),
"textless shape must expose Add text button"
);
assert!(
!empty_snap
.elements
.contains_key("chrome.edgeless_element_toolbar.font_size"),
"textless shape must hide font_size until text exists"
);
// 2. Select shape with text (`shape-a`), check 36px height, open `⋮ More` menu, hover Delete.
app.update(|cx| {
win.update(cx, |v, _, cx| {
v.set_edgeless_camera(320.0, 60.0, 1.0, cx);
v.edgeless_set_selection(["shape-a".into()], cx);
v.apply_edgeless_element_action(
EdgelessElementAction::ToggleSubMenu(ElementSubMenu::More),
cx,
);
})
})
.unwrap();
hw.request_frame();
let snap = app
.update(|cx| win.update(cx, |_, w, _| w.frame_snapshot().clone()))
.unwrap();
let bar = snap
.elements
.get("chrome.edgeless_element_toolbar")
.expect("toolbar must mount");
assert!(
(bar.bounds.height - 36.0).abs() <= 1.5,
"toolbar height should be 36px, got {}",
bar.bounds.height
);
for key in [
"chrome.edgeless_element_toolbar.more",
"chrome.edgeless_element_toolbar.more_menu",
"chrome.edgeless_element_toolbar.more.bring_to_front",
"chrome.edgeless_element_toolbar.more.bring_forward",
"chrome.edgeless_element_toolbar.more.send_backward",
"chrome.edgeless_element_toolbar.more.send_to_back",
"chrome.edgeless_element_toolbar.more.copy",
"chrome.edgeless_element_toolbar.more.duplicate",
"chrome.edgeless_element_toolbar.more.delete",
] {
assert!(snap.elements.contains_key(key), "missing {key}");
}
// Hover over the toolbar rect: cursor_for_pointer must stay Arrow (no resize/grab leak).
let bar_center = point(
px(bar.bounds.x + bar.bounds.width * 0.5),
px(bar.bounds.y + bar.bounds.height * 0.5),
);
hw.dispatch_input(PlatformInput::MouseMove(MouseMoveEvent {
position: bar_center,
pressed_button: None,
modifiers: Modifiers::default(),
}));
platform.run_until_parked();
let hover_cur = app
.update(|cx| win.update(cx, |v, _, _| v.edgeless.authoring.hover_cursor))
.unwrap();
assert_eq!(
hover_cur,
Some(CursorStyle::Arrow),
"toolbar must isolate canvas cursor"
);
// Move pointer onto Delete row in More menu for evidence screenshot.
let del_b = snap.elements["chrome.edgeless_element_toolbar.more.delete"].bounds;
hw.dispatch_input(PlatformInput::MouseMove(MouseMoveEvent {
position: point(
px(del_b.x + del_b.width * 0.5),
px(del_b.y + del_b.height * 0.5),
),
pressed_button: None,
modifiers: Modifiers::default(),
}));
platform.run_until_parked();
hw.request_frame();
maybe_save_evidence(&app, win, "after-shape-toolbar-more-menu.png");
// 3. Multi-select exposes Frame, Group, Align 4x2 + Auto arrange.
app.update(|cx| {
win.update(cx, |v, _, cx| {
v.edgeless_set_selection(["shape-a".into(), "shape-b".into()], cx);
v.apply_edgeless_element_action(
EdgelessElementAction::ToggleSubMenu(ElementSubMenu::Align),
cx,
);
})
})
.unwrap();
hw.request_frame();
let align_snap = app
.update(|cx| win.update(cx, |_, w, _| w.frame_snapshot().clone()))
.unwrap();
assert!(
align_snap
.elements
.contains_key("chrome.edgeless_element_toolbar.frame")
);
assert!(
align_snap
.elements
.contains_key("chrome.edgeless_element_toolbar.sub.auto_arrange")
);
app.update(|cx| {
win.update(cx, |v, _, cx| {
v.apply_edgeless_element_action(EdgelessElementAction::Align(AlignOp::AutoArrange), cx);
})
})
.unwrap();
}
#[test]
fn note_style_panel_exposes_six_shadows_border_radius_auto_height_and_scale() {
assert_eq!(NOTE_SHADOW_PRESETS.len(), 6);
assert!(
NOTE_SHADOW_PRESETS
.iter()
.any(|(id, _, tok)| *id == "float" && *tok == "--affine-note-shadow-float")
);
let (_platform, app, win, hw) = start_edgeless_toolbar_view();
app.update(|cx| {
win.update(cx, |v, _, cx| {
v.set_edgeless_camera(-20.0, 20.0, 1.0, cx);
v.edgeless_set_selection(["note-main".into()], cx);
v.apply_edgeless_element_action(
EdgelessElementAction::ToggleSubMenu(ElementSubMenu::NoteStyle),
cx,
);
})
})
.unwrap();
hw.request_frame();
let snap = app
.update(|cx| win.update(cx, |_, w, _| w.frame_snapshot().clone()))
.unwrap();
for key in [
"chrome.edgeless_element_toolbar.note_style",
"chrome.edgeless_element_toolbar.note_scale",
"chrome.edgeless_element_toolbar.note_style_panel",
"chrome.edgeless_element_toolbar.note_style.shadow.float",
"chrome.edgeless_element_toolbar.note_style.border.solid",
"chrome.edgeless_element_toolbar.note_style.border.dash",
"chrome.edgeless_element_toolbar.note_style.radius.16",
"chrome.edgeless_element_toolbar.note_style.auto_height",
] {
assert!(snap.elements.contains_key(key), "missing {key}");
}
// Primary page-root note hides `Display in Page`.
assert!(
!snap
.elements
.contains_key("chrome.edgeless_element_toolbar.note_display"),
"primary page-root note should hide Display in Page toggle"
);
// Apply Float shadow (keeps style panel open), Dash border, 16px radius, 125% scale and verify nested Y.Map CRDT props.
let before_rect = app
.update(|cx| {
win.update(cx, |v, _, _| {
v.edgeless.authoring.single_selected().unwrap().rect
})
})
.unwrap();
app.update(|cx| {
win.update(cx, |v, _, cx| {
v.apply_edgeless_element_action(
EdgelessElementAction::SetNoteShadow("--affine-note-shadow-float".into()),
cx,
);
assert_eq!(
v.edgeless.authoring.open_sub_menu,
Some(ElementSubMenu::NoteStyle),
"clicking a shadow preset must keep the Note style panel open"
);
v.apply_edgeless_element_action(
EdgelessElementAction::SetNoteBorderStyle(StrokeStyle::Dash),
cx,
);
v.apply_edgeless_element_action(EdgelessElementAction::SetNoteBorderSize(6.0), cx);
v.apply_edgeless_element_action(EdgelessElementAction::SetNoteBorderRadius(16.0), cx);
// Without `collapsedHeight`, ToggleNoteAutoHeight is a no-op (matches BlockSuite toolbar.ts).
v.apply_edgeless_element_action(EdgelessElementAction::ToggleNoteAutoHeight, cx);
v.apply_edgeless_element_action(EdgelessElementAction::SetNoteScale(1.25), cx);
// Re-open style panel for evidence screenshot.
v.apply_edgeless_element_action(
EdgelessElementAction::ToggleSubMenu(ElementSubMenu::NoteStyle),
cx,
);
})
})
.unwrap();
hw.request_frame();
maybe_save_evidence(&app, win, "after-note-style-panel.png");
app.update(|cx| {
win.update(cx, |v, _, _| {
let snap = v.page_snapshot().unwrap();
let note = snap.block("note-main").unwrap();
// Zero flat dotted keys; all style fields live inside nested `prop:edgeless` Y.Map.
for flat in [
"prop:edgeless.style.shadowType",
"prop:edgeless.style.borderStyle",
"prop:edgeless.style.borderSize",
"prop:edgeless.style.borderRadius",
"prop:edgeless.scale",
"prop:edgeless.collapse",
] {
assert!(
!note.props.contains_key(flat),
"note must not write flat dotted key {flat}"
);
}
// Reload from V1 Yjs binary update to verify nested Y.Map round-trip.
let v1 = v.page().unwrap().encode_update_v1().unwrap();
let mut reloaded = PageDocSession::new("reloaded", 999).unwrap();
reloaded.apply_remote_update_v1(&v1).unwrap();
let rsnap = reloaded.read_page_snapshot().unwrap();
let rnote = rsnap.block("note-main").unwrap();
let edg = rnote
.props
.get("prop:edgeless")
.and_then(|v| v.as_object())
.expect("nested prop:edgeless map");
let style = edg
.get("style")
.and_then(|v| v.as_object())
.expect("nested prop:edgeless.style map");
assert_eq!(
style.get("shadowType").and_then(|v| v.as_str()),
Some("--affine-note-shadow-float")
);
assert_eq!(
style.get("borderStyle").and_then(|v| v.as_str()),
Some("dash")
);
assert_eq!(style.get("borderSize").and_then(|v| v.as_f64()), Some(6.0));
assert_eq!(
style.get("borderRadius").and_then(|v| v.as_f64()),
Some(16.0)
);
assert_eq!(edg.get("scale").and_then(|v| v.as_f64()), Some(1.25));
let after_rect = v.edgeless.authoring.single_selected().unwrap().rect;
assert!(
(after_rect.w - before_rect.w * 1.25).abs() <= 2.0,
"SetNoteScale must scale xywh width proportionally: {} -> {}",
before_rect.w,
after_rect.w
);
let sum = summarize_element_toolbar(
&snap,
&v.edgeless.authoring,
PlaygroundTheme::Light,
&PlaygroundTheme::Light.palette(),
)
.unwrap();
assert_eq!(sum.note_shadow, "--affine-note-shadow-float");
assert_eq!(sum.note_border_style, StrokeStyle::Dash);
assert!((sum.note_border_size - 6.0).abs() < 0.01);
assert!((sum.note_border_radius - 16.0).abs() < 0.01);
assert!(
sum.note_auto_height,
"note without collapsedHeight must remain auto-height"
);
assert!((sum.note_scale - 1.25).abs() < 0.01);
})
})
.unwrap();
// When `collapsedHeight` is present, ToggleNoteAutoHeight toggles collapse & updates xywh.h.
app.update(|cx| {
win.update(cx, |v, _, cx| {
let commit = v
.page_mut()
.unwrap()
.structural_edit(180, |page| {
page.set_note_edgeless_prop(
"note-main",
&["collapsedHeight"],
y_octo::SessionValue::Any(y_octo::Any::Float64(120.0.into())),
180,
)
})
.unwrap()
.unwrap();
v.did_edgeless_doc_commit(commit, cx);
v.apply_edgeless_element_action(EdgelessElementAction::ToggleNoteAutoHeight, cx);
})
})
.unwrap();
hw.request_frame();
app.update(|cx| {
win.update(cx, |v, _, cx| {
let snap = v.page_snapshot().unwrap();
let note = snap.block("note-main").unwrap();
assert!(super::note_collapse(note));
let rect = super::parse_xywh(
note.props
.get("prop:xywh")
.and_then(|v| v.as_str())
.unwrap(),
)
.unwrap();
assert!(
(rect.h - 150.0).abs() <= 1.0,
"collapsed height must equal collapsedHeight * scale (120 * 1.25 = 150), got {}",
rect.h
);
v.apply_edgeless_element_action(EdgelessElementAction::ToggleNoteAutoHeight, cx);
let snap2 = v.page_snapshot().unwrap();
assert!(!super::note_collapse(snap2.block("note-main").unwrap()));
})
})
.unwrap();
}
#[test]
fn edgeless_canvas_media_and_bookmark_toolbar_actions_and_screenshot() {
let (_platform, app, win, hw) = start_edgeless_toolbar_view();
app.update(|cx| {
win.update(cx, |v, _, cx| {
let commit = v
.page_mut()
.unwrap()
.structural_edit(140, |page| {
page.add_block(
"bm-canvas",
BlockSpec::Bookmark {
url: "https://app.affine.pro/workspace/overview".into(),
title: Some("AFFiNE Workspace".into()),
description: Some("Knowledge base and whiteboard".into()),
},
Some("surf"),
None,
140,
)?;
page.set_block_xywh("bm-canvas", [160.0, 220.0, 360.0, 120.0], 140)?;
page.set_block_index("bm-canvas", "d1", 140)?;
Ok(())
})
.unwrap()
.unwrap();
v.did_edgeless_doc_commit(commit, cx);
v.set_edgeless_camera(80.0, 80.0, 1.0, cx);
v.edgeless_set_selection(["bm-canvas".into()], cx);
})
})
.unwrap();
hw.request_frame();
let snap = app
.update(|cx| win.update(cx, |_, w, _| w.frame_snapshot().clone()))
.unwrap();
for key in [
"chrome.edgeless_element_toolbar.media_open",
"chrome.edgeless_element_toolbar.media_copy_link",
"chrome.edgeless_element_toolbar.media_style",
"chrome.edgeless_element_toolbar.media_caption",
] {
assert!(snap.elements.contains_key(key), "missing {key}");
}
assert!(
!snap
.elements
.contains_key("chrome.edgeless_element_toolbar.media_view"),
"non-embeddable bookmark must hide Embed view toggle"
);
maybe_save_evidence(&app, win, "after-edgeless-media-toolbar.png");
// Clicking Caption on an uncaptioned block opens in-place caption editor with 0 CRDT writes.
app.update(|cx| {
win.update(cx, |v, window, cx| {
let rev_before = v.doc_rev;
v.apply_edgeless_element_action(EdgelessElementAction::MediaToggleView, cx);
assert_eq!(
v.doc_rev, rev_before,
"non-embeddable MediaToggleView must not mutate CRDT"
);
let before_v1 = v.page().unwrap().encode_update_v1().unwrap();
super::EdgelessElementToolbarHost::edgeless_element_action(
v,
EdgelessElementAction::MediaCaption,
window,
cx,
);
assert_eq!(
v.page().unwrap().encode_update_v1().unwrap(),
before_v1,
"MediaCaption must not write CRDT when opening empty caption"
);
let ed = v
.active_caption_editor()
.expect("inline caption editor must open");
assert_eq!(ed.block_id, "bm-canvas");
assert_eq!(ed.input.text, "");
v.finish_caption_editor(crate::overlays::InlineTargetEnd::DiscardPreedit, Some(cx));
// Seed a custom caption and verify MediaCaption opens editor preserving it with 0 writes.
let commit = v
.page_mut()
.unwrap()
.set_block_caption("bm-canvas", "Workspace Overview", 150)
.unwrap()
.unwrap();
v.did_edgeless_doc_commit(commit, cx);
let after_seed_v1 = v.page().unwrap().encode_update_v1().unwrap();
super::EdgelessElementToolbarHost::edgeless_element_action(
v,
EdgelessElementAction::MediaCaption,
window,
cx,
);
assert_eq!(
v.page().unwrap().encode_update_v1().unwrap(),
after_seed_v1,
"MediaCaption must not clear existing caption"
);
let ed2 = v
.active_caption_editor()
.expect("inline caption editor must reopen");
assert_eq!(ed2.input.text, "Workspace Overview");
v.finish_caption_editor(crate::overlays::InlineTargetEnd::DiscardPreedit, Some(cx));
v.apply_edgeless_element_action(
EdgelessElementAction::MediaSetCardStyle("vertical".into()),
cx,
);
})
})
.unwrap();
app.update(|cx| {
win.update(cx, |v, _, _| {
let snap = v.page_snapshot().unwrap();
let bm = snap.block("bm-canvas").unwrap();
assert!(
!bm.props.contains_key("prop:embed"),
"Bookmark must never receive bogus prop:embed"
);
assert_eq!(
bm.props.get("prop:caption").and_then(|v| v.as_str()),
Some("Workspace Overview")
);
assert_eq!(
bm.props.get("prop:style").and_then(|v| v.as_str()),
Some("vertical")
);
assert!(matches!(bm.content, BlockContent::Bookmark { .. }));
})
})
.unwrap();
}
#[test]
fn quick_connect_300ms_ghost_preview_and_outer_corner_rotate_zones() {
let (platform, app, win, hw) = start_edgeless_toolbar_view();
app.update(|cx| {
win.update(cx, |v, _, cx| {
v.set_edgeless_camera(320.0, 60.0, 1.0, cx);
v.edgeless_set_selection(["shape-a".into()], cx);
})
})
.unwrap();
hw.request_frame();
// Verify 4 outer-corner rotation zones exist and east quick-connect arrow center is hittable.
let (east_pt, snap0) = app
.update(|cx| {
win.update(cx, |v, w, _| {
let single = v.edgeless.authoring.single_selected().unwrap().clone();
let vp_origin = point(px(0.0), px(crate::TOPBAR_HEIGHT));
let (cx_s, cy_s) = auto_complete_arrow_center(
single.rect,
QuickConnectDirection::East,
v.edgeless.camera,
vp_origin,
);
(point(px(cx_s), px(cy_s)), w.frame_snapshot().clone())
})
})
.unwrap();
for key in [
"edgeless.handle.rotate",
"edgeless.handle.rotate_nw",
"edgeless.handle.rotate_se",
"edgeless.handle.rotate_sw",
] {
assert!(snap0.elements.contains_key(key), "missing {key}");
}
assert!(
!snap0
.elements
.contains_key("edgeless.auto_complete.ghost_preview"),
"ghost preview must not appear before hover"
);
// Hover East arrow -> cursor is PointingHand, no ghost preview yet (< 300ms).
hw.dispatch_input(PlatformInput::MouseMove(MouseMoveEvent {
position: east_pt,
pressed_button: None,
modifiers: Modifiers::default(),
}));
platform.run_until_parked();
hw.request_frame();
let (cur_hover, snap_early) = app
.update(|cx| {
win.update(cx, |v, w, _| {
(
v.edgeless.authoring.hover_cursor,
w.frame_snapshot().clone(),
)
})
})
.unwrap();
assert_eq!(cur_hover, Some(CursorStyle::PointingHand));
assert!(
!snap_early
.elements
.contains_key("edgeless.auto_complete.ghost_preview"),
"ghost preview must wait 300ms"
);
// Advance deterministic test clock by 300ms -> ghost preview renders!
platform.advance_clock(Duration::from_millis(
QUICK_CONNECT_GHOST_DELAY_MS as u64 + 10,
));
platform.run_until_parked();
hw.request_frame();
let snap_ghost = app
.update(|cx| win.update(cx, |_, w, _| w.frame_snapshot().clone()))
.unwrap();
assert!(
snap_ghost
.elements
.contains_key("edgeless.auto_complete.ghost_preview"),
"ghost preview must render after 300ms deterministic dwell"
);
maybe_save_evidence(&app, win, "after-quick-connect-ghost-preview.png");
// Moving pointer away clears ghost preview immediately.
hw.dispatch_input(PlatformInput::MouseMove(MouseMoveEvent {
position: point(px(16.0), px(crate::TOPBAR_HEIGHT + 16.0)),
pressed_button: None,
modifiers: Modifiers::default(),
}));
platform.run_until_parked();
hw.request_frame();
let snap_cleared = app
.update(|cx| win.update(cx, |_, w, _| w.frame_snapshot().clone()))
.unwrap();
assert!(
!snap_cleared
.elements
.contains_key("edgeless.auto_complete.ghost_preview"),
"ghost preview must clear immediately on pointer leave"
);
// Quick-connect click creates an Orthogonal connector with auto-ports (position: None).
let created = app
.update(|cx| {
win.update(cx, |v, _, cx| {
v.edgeless_quick_connect_click("shape-a", QuickConnectDirection::East, cx)
})
})
.unwrap();
let (_, conn_id) = created.expect("quick connect click must create shape and connector");
app.update(|cx| {
win.update(cx, |v, _, _| {
let snap = v.page_snapshot().unwrap();
let (_, conn_el) = find_surface_element(&snap, &conn_id).unwrap();
match &conn_el.kind {
SurfaceElementKind::Connector(c) => {
assert_eq!(c.mode, ConnectorMode::Orthogonal);
assert_eq!(c.source.position, None);
assert_eq!(c.target.position, None);
}
other => panic!("expected Connector, got {other:?}"),
}
})
})
.unwrap();
}
@@ -2,13 +2,8 @@
//! single-undo-step property updates and common actions across selected Shape / Note /
//! Connector / Text / Frame items.
use blocksuite_playground_doc::{
read::{
BlockContent, ColorValue, EndpointStyle, NoteDisplayMode, StrokeStyle, SurfaceElementKind,
},
session::PageDocSession,
};
use ui::{Context, Window, WindowTextSystem};
use blocksuite_playground_doc::read::{ColorValue, EndpointStyle, NoteDisplayMode, StrokeStyle};
use ui::{Context, Window};
use y_octo::{AHashMap, Any, SessionValue};
use crate::{PlaygroundView, theme::PlaygroundTheme};
@@ -16,7 +11,7 @@ use crate::{PlaygroundView, theme::PlaygroundTheme};
use super::{
DragItemInitial, EdgelessElementAction, EdgelessElementToolbarHost, ElementColorSlot,
ShapePreset, SpatialItemKind, element_toolbar_color::apply_color_to_element,
is_neutral_shape_text_color, measure_surface_text_xywh, parse_custom_hex_color,
parse_custom_hex_color,
};
fn endpoint_style_wire(ep: EndpointStyle) -> &'static str {
@@ -85,7 +80,9 @@ impl EdgelessElementToolbarHost for PlaygroundView {
) {
if matches!(
action,
EdgelessElementAction::Rename | EdgelessElementAction::AddConnectorLabel
EdgelessElementAction::Rename
| EdgelessElementAction::AddConnectorLabel
| EdgelessElementAction::AddText
) {
if let Some(id) = self
.edgeless
@@ -99,6 +96,15 @@ impl EdgelessElementToolbarHost for PlaygroundView {
}
return;
}
if matches!(
action,
EdgelessElementAction::MediaCaption | EdgelessElementAction::MediaOpenLink
) {
if !self.is_edgeless_write_readonly() {
self.apply_edgeless_media_action(&action, Some(window), cx);
}
return;
}
self.apply_edgeless_element_action(action, cx);
}
}
@@ -176,11 +182,42 @@ impl PlaygroundView {
self.edgeless_reorder_selection(true, cx);
return;
}
EdgelessElementAction::BringForward => {
self.dismiss_edgeless_element_popovers();
self.edgeless_step_reorder_selection(true, cx);
return;
}
EdgelessElementAction::SendBackward => {
self.dismiss_edgeless_element_popovers();
self.edgeless_step_reorder_selection(false, cx);
return;
}
EdgelessElementAction::SendToBack => {
self.dismiss_edgeless_element_popovers();
self.edgeless_reorder_selection(false, cx);
return;
}
EdgelessElementAction::WrapInFrame => {
self.dismiss_edgeless_element_popovers();
self.edgeless_wrap_selection_in_frame(cx);
return;
}
EdgelessElementAction::ReleaseFromGroup => {
self.dismiss_edgeless_element_popovers();
self.edgeless_release_from_group(cx);
return;
}
EdgelessElementAction::InsertGroupIntoPage => {
self.dismiss_edgeless_element_popovers();
self.edgeless_insert_group_into_page(cx);
return;
}
EdgelessElementAction::DrawConnector => {
self.dismiss_edgeless_element_popovers();
self.edgeless.authoring.tool = super::EdgelessTool::Connector;
cx.notify();
return;
}
EdgelessElementAction::Copy => {
self.dismiss_edgeless_element_popovers();
self.edgeless_copy_selection(false, cx);
@@ -236,7 +273,9 @@ impl PlaygroundView {
self.edgeless_add_mindmap_node(false, cx);
return;
}
EdgelessElementAction::Rename | EdgelessElementAction::AddConnectorLabel => {
EdgelessElementAction::Rename
| EdgelessElementAction::AddConnectorLabel
| EdgelessElementAction::AddText => {
return;
}
EdgelessElementAction::Delete => {
@@ -269,7 +308,11 @@ impl PlaygroundView {
}
return;
}
_ => {}
_ => {
if self.try_apply_extended_element_action(&action, cx) {
return;
}
}
}
if matches!(
@@ -284,12 +327,14 @@ impl PlaygroundView {
}
if matches!(
action,
EdgelessElementAction::SetNoteShadow(_)
| EdgelessElementAction::SetConnectorFrontEndpoint(_)
EdgelessElementAction::SetConnectorFrontEndpoint(_)
| EdgelessElementAction::SetConnectorRearEndpoint(_)
| EdgelessElementAction::FlipConnectorDirection
| EdgelessElementAction::SetStrokeWidth(_)
| EdgelessElementAction::SetFontSize(_)
| EdgelessElementAction::SetShapeType(_)
| EdgelessElementAction::SetConnectorMode(_)
| EdgelessElementAction::SetTextAlign(_)
) {
self.edgeless.authoring.open_sub_menu = None;
}
@@ -320,129 +365,11 @@ impl PlaygroundView {
NoteDisplayMode::Both.as_str()
};
// Pre-read connector label styles and recompute SurfaceText bounds for font-size updates.
let mut connector_label_styles: Vec<(String, Any)> = Vec::new();
let mut surface_text_xywhs: Vec<(String, String)> = Vec::new();
if let EdgelessElementAction::SetFontSize(fs) = &action
&& let Some(root) = snapshot.root.as_ref()
{
let ts = WindowTextSystem::new(cx.text_system().clone());
for node in root.walk() {
if let BlockContent::Surface { elements, .. } = &node.content {
for el in elements {
if !self.edgeless.authoring.selection.contains(&el.id) {
continue;
}
match &el.kind {
SurfaceElementKind::Connector(conn) => {
let mut map = AHashMap::default();
let color_any = match &conn.label_style.color {
blocksuite_playground_doc::read::ColorValue::Single(s) => {
Any::String(s.clone())
}
blocksuite_playground_doc::read::ColorValue::Themed {
light,
dark,
} => {
let mut c = AHashMap::default();
c.insert("light".into(), Any::String(light.clone()));
c.insert("dark".into(), Any::String(dark.clone()));
Any::Object(Box::new(c))
}
};
map.insert("color".into(), color_any);
map.insert("fontSize".into(), Any::Float64((*fs).into()));
map.insert(
"fontFamily".into(),
Any::String(conn.label_style.font_family.clone()),
);
map.insert(
"fontWeight".into(),
Any::String(conn.label_style.font_weight.clone()),
);
map.insert(
"fontStyle".into(),
Any::String(conn.label_style.font_style.clone()),
);
map.insert(
"textAlign".into(),
Any::String(conn.label_style.text_align.as_str().into()),
);
connector_label_styles
.push((el.id.clone(), Any::Object(Box::new(map))));
}
SurfaceElementKind::Text(t) => {
let xywh = measure_surface_text_xywh(t, *fs, self.theme, &ts);
surface_text_xywhs
.push((el.id.clone(), PageDocSession::format_xywh(xywh)));
}
_ => {}
}
}
}
}
}
let mut flipped_connectors: Vec<(String, Any, Any)> = Vec::new();
if matches!(action, EdgelessElementAction::FlipConnectorDirection)
&& let Some(root) = snapshot.root.as_ref()
{
for node in root.walk() {
if let BlockContent::Surface { elements, .. } = &node.content {
for el in elements {
if !self.edgeless.authoring.selection.contains(&el.id) {
continue;
}
if let SurfaceElementKind::Connector(conn) = &el.kind {
let ep_to_any =
|ep: &blocksuite_playground_doc::read::ConnectorEndpoint| {
let mut m = AHashMap::default();
if let Some(id) = &ep.id {
m.insert("id".into(), Any::String(id.clone()));
}
if let Some([x, y]) = ep.position {
m.insert(
"position".into(),
Any::Array(vec![
Any::Float64(x.into()),
Any::Float64(y.into()),
]),
);
}
Any::Object(Box::new(m))
};
flipped_connectors.push((
el.id.clone(),
ep_to_any(&conn.target),
ep_to_any(&conn.source),
));
}
}
}
}
}
let mut auto_shape_text_ids = std::collections::HashSet::new();
if matches!(
action,
EdgelessElementAction::SetColor {
slot: ElementColorSlot::Fill,
..
} | EdgelessElementAction::SetFillColor(_)
) && let Some(root) = snapshot.root.as_ref()
{
for node in root.walk() {
if let BlockContent::Surface { elements, .. } = &node.content {
for el in elements {
if self.edgeless.authoring.selection.contains(&el.id)
&& let SurfaceElementKind::Shape(s) = &el.kind
&& is_neutral_shape_text_color(&s.color)
{
auto_shape_text_ids.insert(el.id.clone());
}
}
}
}
}
// Pre-read connector label styles, flipped endpoints, and auto-contrast shape IDs.
let (connector_label_styles, surface_text_xywhs) =
self.precompute_font_size_updates(&snapshot, &action, cx);
let flipped_connectors = self.precompute_flipped_connectors(&snapshot, &action);
let auto_shape_text_ids = self.precompute_auto_shape_text_ids(&snapshot, &action);
let mixed_highlighter_and_standard = selected
.iter()
.any(|(_, k, _)| *k == SpatialItemKind::Highlighter)
@@ -742,9 +669,9 @@ impl PlaygroundView {
}
}
(EdgelessElementAction::SetNoteShadow(shadow), SpatialItemKind::Note) => {
page.set_block_prop(
page.set_note_edgeless_prop(
id,
"prop:edgeless.style.shadowType",
&["style", "shadowType"],
SessionValue::Any(Any::String(shadow.clone())),
now_ms,
)?;
@@ -0,0 +1,734 @@
//! Extended Edgeless element toolbar actions: 4-level z-order (`BringForward`/`SendBackward`),
//! `ReleaseFromGroup`, `InsertGroupIntoPage`, nested `Y.Map` Note style mutations, and
//! precomputation helpers for floating element toolbar transactions.
use std::collections::{BTreeMap, HashSet};
use blocksuite_playground_doc::{
fractional_index::{generate_key_between, generate_n_keys_between},
read::{BlockContent, PageSnapshot, StrokeStyle, SurfaceElementKind},
session::PageDocSession,
};
use ui::{Context, WindowTextSystem};
use y_octo::{AHashMap, Any, SessionValue};
use crate::PlaygroundView;
use super::{
EdgelessElementAction, ElementColorSlot, SpatialItemInfo, SpatialItemKind,
is_neutral_shape_text_color, measure_surface_text_xywh, next_index_after, note_collapse,
note_collapsed_height, note_scale, prev_index_before,
ungroup_ops::collect_direct_parent_groups,
};
fn note_border_style_wire(style: StrokeStyle) -> &'static str {
match style {
StrokeStyle::Solid => "solid",
StrokeStyle::Dash => "dash",
StrokeStyle::None => "none",
}
}
fn generate_run_keys(
lo: Option<&str>,
hi: Option<&str>,
count: usize,
forward: bool,
) -> Option<Vec<String>> {
if count == 0 {
return Some(Vec::new());
}
if let Ok(keys) = generate_n_keys_between(lo, hi, count) {
return Some(keys);
}
if forward {
let mut out = Vec::with_capacity(count);
let mut cursor = lo.map(str::to_string);
for _ in 0..count {
let next = next_index_after(cursor.as_deref()).ok()?;
cursor = Some(next.clone());
out.push(next);
}
Some(out)
} else {
let mut rev = Vec::with_capacity(count);
let mut cursor = hi.map(str::to_string);
for _ in 0..count {
let prev = prev_index_before(cursor.as_deref()).ok()?;
cursor = Some(prev.clone());
rev.push(prev);
}
rev.reverse();
Some(rev)
}
}
impl PlaygroundView {
/// Step selection forward or backward by one z-order layer (`BringForward` / `SendBackward`),
/// moving each contiguous selected run within its parent sibling list as an atomic unit
/// while treating runs already at the top/bottom boundary as a no-op.
pub(crate) fn edgeless_step_reorder_selection(
&mut self,
forward: bool,
cx: &mut Context<Self>,
) {
if self.is_edgeless_write_readonly() || self.edgeless.authoring.selection.is_empty() {
return;
}
let items = self.edgeless.authoring.painted_items.to_vec();
let selected_ids: HashSet<String> = items
.iter()
.filter(|i| self.edgeless.authoring.selection.contains(&i.id) && !i.locked)
.map(|i| i.id.clone())
.collect();
if selected_ids.is_empty() {
return;
}
// Siblings share a parent group and a paint stream (blocks or canvas elements).
let mut by_parent: BTreeMap<(Option<String>, bool), Vec<SpatialItemInfo>> = BTreeMap::new();
for item in items {
by_parent
.entry((item.parent_group_id.clone(), item.kind.is_block()))
.or_default()
.push(item);
}
let mut updates: Vec<(SpatialItemInfo, String)> = Vec::new();
for mut siblings in by_parent.into_values() {
let mut runs: Vec<(usize, usize)> = Vec::new();
let mut idx = 0usize;
while idx < siblings.len() {
if selected_ids.contains(siblings[idx].id.as_str()) {
let start = idx;
while idx + 1 < siblings.len()
&& selected_ids.contains(siblings[idx + 1].id.as_str())
{
idx += 1;
}
runs.push((start, idx));
}
idx += 1;
}
if runs.is_empty() {
continue;
}
if forward {
for (start, end) in runs.into_iter().rev() {
if end + 1 >= siblings.len() {
continue;
}
let lo = siblings[end + 1].index.clone();
let hi = siblings.get(end + 2).map(|s| s.index.clone());
let run_len = end - start + 1;
let Some(keys) = generate_run_keys(Some(&lo), hi.as_deref(), run_len, true)
else {
continue;
};
// Move the run [start..=end] right after the unselected sibling at `end + 1`.
let jumped = siblings.remove(end + 1);
siblings.insert(start, jumped);
for (offset, key) in keys.into_iter().enumerate() {
let slot = start + 1 + offset;
siblings[slot].index = key.clone();
updates.push((siblings[slot].clone(), key));
}
}
} else {
for (start, end) in runs {
if start == 0 {
continue;
}
let hi = siblings[start - 1].index.clone();
let lo = start
.checked_sub(2)
.and_then(|i| siblings.get(i))
.map(|s| s.index.clone());
let run_len = end - start + 1;
let Some(keys) = generate_run_keys(lo.as_deref(), Some(&hi), run_len, false)
else {
continue;
};
// Move the run [start..=end] right before the unselected sibling at `start - 1`.
let jumped = siblings.remove(start - 1);
siblings.insert(end, jumped);
for (offset, key) in keys.into_iter().enumerate() {
let slot = start - 1 + offset;
siblings[slot].index = key.clone();
updates.push((siblings[slot].clone(), key));
}
}
}
}
if updates.is_empty() {
return;
}
let now_ms = self.now_ms(cx) as u64;
let commit = self.page_mut().ok().and_then(|page| {
page.structural_edit(now_ms, move |page| {
for (item, key) in &updates {
if item.kind.is_block() {
page.set_block_index(&item.id, key, now_ms)?;
} else if let Some(sid) = &item.surface_id {
page.set_surface_element_field(
sid,
&item.id,
"index",
SessionValue::Any(Any::String(key.clone())),
now_ms,
)?;
}
}
Ok(())
})
.ok()
.flatten()
});
if let Some(commit) = commit {
self.did_edgeless_doc_commit(commit, cx);
}
}
/// Release a single selected element from its direct parent `Group`, bounding its new
/// fractional index before the group's immediate following sibling and removing the `Group`
/// atomically when it becomes empty.
pub(crate) fn edgeless_release_from_group(&mut self, cx: &mut Context<Self>) -> bool {
if self.is_edgeless_write_readonly() {
return false;
}
let Some(single) = self.edgeless.authoring.single_selected().cloned() else {
return false;
};
if single.locked {
return false;
}
let Some(snapshot) = self.snapshot.clone() else {
return false;
};
let parent_map = collect_direct_parent_groups(&snapshot);
let Some((group_sid, group_id)) = parent_map.get(&single.id).cloned() else {
return false;
};
let grandparent = parent_map.get(&group_id).cloned();
let gp_id_opt = grandparent.as_ref().map(|(_, gid)| gid.clone());
let siblings: Vec<&SpatialItemInfo> = self
.edgeless
.authoring
.painted_items
.iter()
.filter(|i| i.parent_group_id == gp_id_opt)
.collect();
let group_el = super::find_surface_element(&snapshot, &group_id).map(|(_, el)| el);
let group_index = group_el.map(|el| el.index.as_str());
let after_group_index = siblings
.iter()
.position(|i| i.id == group_id)
.and_then(|pos| siblings.get(pos + 1))
.map(|s| s.index.as_str());
let next_idx = group_index.and_then(|lo| {
generate_key_between(Some(lo), after_group_index)
.or_else(|_| next_index_after(Some(lo)))
.ok()
});
let group_becomes_empty = group_el.is_some_and(|el| match &el.kind {
SurfaceElementKind::Group { children, .. } => {
!children.iter().any(|cid| cid != &single.id)
}
_ => false,
});
let item_id = single.id.clone();
let is_block = single.kind.is_block();
let item_sid = single.surface_id.clone();
let now_ms = self.now_ms(cx) as u64;
let commit = self.page_mut().ok().and_then(|page| {
page.structural_edit(now_ms, move |page| {
page.update_group_children_delta(
&group_sid,
&group_id,
&[],
std::slice::from_ref(&item_id),
now_ms,
)?;
if let Some((gp_sid, gp_id)) = &grandparent {
let remove_from_gp: Vec<String> = if group_becomes_empty {
vec![group_id.clone()]
} else {
Vec::new()
};
page.update_group_children_delta(
gp_sid,
gp_id,
std::slice::from_ref(&item_id),
&remove_from_gp,
now_ms,
)?;
}
if group_becomes_empty {
let _ = page.remove_surface_element(&group_sid, &group_id, now_ms)?;
}
if let Some(idx) = &next_idx {
if is_block {
page.set_block_index(&item_id, idx, now_ms)?;
} else if let Some(sid) = &item_sid {
page.set_surface_element_field(
sid,
&item_id,
"index",
SessionValue::Any(Any::String(idx.clone())),
now_ms,
)?;
}
}
Ok(())
})
.ok()
.flatten()
});
if let Some(commit) = commit {
self.did_edgeless_doc_commit(commit, cx);
return true;
}
false
}
/// Insert a `affine:surface-ref` block referencing the selected Group into the primary Page Note.
pub(crate) fn edgeless_insert_group_into_page(&mut self, cx: &mut Context<Self>) -> bool {
if self.is_edgeless_write_readonly() || self.is_page_write_readonly() {
return false;
}
let Some(single) = self.edgeless.authoring.single_selected().cloned() else {
return false;
};
if single.kind != SpatialItemKind::Group || single.locked {
return false;
}
let Some(snapshot) = self.snapshot.clone() else {
return false;
};
let Some(root) = snapshot.root.as_ref() else {
return false;
};
let Some(note) = root.children.iter().find(|c| c.is_page_visible_note()) else {
return false;
};
let caption = super::find_surface_element(&snapshot, &single.id)
.and_then(|(_, el)| match &el.kind {
SurfaceElementKind::Group { title, .. } => Some(title.plain.clone()),
_ => None,
})
.unwrap_or_default();
let Some(cid) = self.page().map(|p| p.client_id()) else {
return false;
};
let ref_id = self.edgeless.authoring.next_id("sref", cid);
let note_id = note.id.clone();
let group_id = single.id.clone();
let now_ms = self.now_ms(cx) as u64;
let commit = self.page_mut().ok().and_then(|page| {
page.structural_edit(now_ms, move |page| {
page.add_block(
&ref_id,
blocksuite_playground_doc::schema::BlockSpec::SurfaceRef {
reference: group_id.clone(),
ref_flavour: "group".into(),
caption: caption.clone(),
},
Some(&note_id),
None,
now_ms,
)?;
Ok(())
})
.ok()
.flatten()
});
if let Some(commit) = commit {
self.did_edgeless_doc_commit(commit, cx);
return true;
}
false
}
/// Apply Note style panel or canvas media/embed block actions; returns `true` if handled.
pub(super) fn try_apply_extended_element_action(
&mut self,
action: &EdgelessElementAction,
cx: &mut Context<Self>,
) -> bool {
match action {
EdgelessElementAction::SetNoteBorderStyle(style) => {
let ids = self.selected_unlocked_note_ids();
if ids.is_empty() {
return true;
}
let wire = note_border_style_wire(*style).to_string();
let now_ms = self.now_ms(cx) as u64;
let commit = self.page_mut().ok().and_then(|page| {
page.structural_edit(now_ms, move |page| {
for id in &ids {
page.set_note_edgeless_prop(
id,
&["style", "borderStyle"],
SessionValue::Any(Any::String(wire.clone())),
now_ms,
)?;
}
Ok(())
})
.ok()
.flatten()
});
if let Some(c) = commit {
self.did_edgeless_doc_commit(c, cx);
}
true
}
EdgelessElementAction::SetNoteBorderSize(size) => {
let ids = self.selected_unlocked_note_ids();
if ids.is_empty() {
return true;
}
let size = *size;
let now_ms = self.now_ms(cx) as u64;
let commit = self.page_mut().ok().and_then(|page| {
page.structural_edit(now_ms, move |page| {
for id in &ids {
page.set_note_edgeless_prop(
id,
&["style", "borderSize"],
SessionValue::Any(Any::Float64(size.into())),
now_ms,
)?;
}
Ok(())
})
.ok()
.flatten()
});
if let Some(c) = commit {
self.did_edgeless_doc_commit(c, cx);
}
true
}
EdgelessElementAction::SetNoteBorderRadius(rad) => {
let ids = self.selected_unlocked_note_ids();
if ids.is_empty() {
return true;
}
let rad = *rad;
let now_ms = self.now_ms(cx) as u64;
let commit = self.page_mut().ok().and_then(|page| {
page.structural_edit(now_ms, move |page| {
for id in &ids {
page.set_note_edgeless_prop(
id,
&["style", "borderRadius"],
SessionValue::Any(Any::Float64(rad.into())),
now_ms,
)?;
}
Ok(())
})
.ok()
.flatten()
});
if let Some(c) = commit {
self.did_edgeless_doc_commit(c, cx);
}
true
}
EdgelessElementAction::ToggleNoteAutoHeight => {
let Some(snapshot) = self.snapshot.clone() else {
return true;
};
let updates: Vec<(String, bool, Option<[f64; 4]>)> = self
.edgeless
.authoring
.painted_items
.iter()
.filter(|i| {
self.edgeless.authoring.selection.contains(&i.id)
&& !i.locked
&& i.kind == SpatialItemKind::Note
})
.filter_map(|item| {
let node = snapshot.block(&item.id)?;
if note_collapse(node) {
Some((item.id.clone(), false, None))
} else {
let ch = note_collapsed_height(node)?;
let sc = note_scale(node) as f64;
let new_h = (ch * sc).max(40.0);
Some((
item.id.clone(),
true,
Some([
item.rect.x as f64,
item.rect.y as f64,
item.rect.w as f64,
new_h,
]),
))
}
})
.collect();
if updates.is_empty() {
return true;
}
let now_ms = self.now_ms(cx) as u64;
let commit = self.page_mut().ok().and_then(|page| {
page.structural_edit(now_ms, move |page| {
for (id, collapse, xywh) in &updates {
page.set_note_edgeless_prop(
id,
&["collapse"],
SessionValue::Any(if *collapse { Any::True } else { Any::False }),
now_ms,
)?;
if let Some(rect) = xywh {
page.set_block_xywh(id, *rect, now_ms)?;
}
}
Ok(())
})
.ok()
.flatten()
});
if let Some(c) = commit {
self.did_edgeless_doc_commit(c, cx);
}
true
}
EdgelessElementAction::SetNoteScale(scale) => {
self.edgeless.authoring.open_sub_menu = None;
let Some(snapshot) = self.snapshot.clone() else {
return true;
};
let target_scale = *scale;
let updates: Vec<(String, [f64; 4])> = self
.edgeless
.authoring
.painted_items
.iter()
.filter(|i| {
self.edgeless.authoring.selection.contains(&i.id)
&& !i.locked
&& i.kind == SpatialItemKind::Note
})
.filter_map(|item| {
let node = snapshot.block(&item.id)?;
let old_scale = (note_scale(node) as f64).max(0.1);
let ratio = (target_scale / old_scale).clamp(0.1, 10.0);
let new_w = (item.rect.w as f64 * ratio).max(40.0);
let new_h = (item.rect.h as f64 * ratio).max(40.0);
Some((
item.id.clone(),
[item.rect.x as f64, item.rect.y as f64, new_w, new_h],
))
})
.collect();
if updates.is_empty() {
return true;
}
let now_ms = self.now_ms(cx) as u64;
let commit = self.page_mut().ok().and_then(|page| {
page.structural_edit(now_ms, move |page| {
for (id, xywh) in &updates {
page.set_note_edgeless_prop(
id,
&["scale"],
SessionValue::Any(Any::Float64(target_scale.into())),
now_ms,
)?;
page.set_block_xywh(id, *xywh, now_ms)?;
}
Ok(())
})
.ok()
.flatten()
});
if let Some(c) = commit {
self.did_edgeless_doc_commit(c, cx);
}
true
}
EdgelessElementAction::MediaToggleView
| EdgelessElementAction::MediaSetCardStyle(_)
| EdgelessElementAction::MediaOpenLink
| EdgelessElementAction::MediaCopyLink
| EdgelessElementAction::MediaDownload
| EdgelessElementAction::MediaRotateCw
| EdgelessElementAction::MediaSetScale(_)
| EdgelessElementAction::MediaReload
| EdgelessElementAction::MediaInfo => {
self.apply_edgeless_media_action(action, None, cx);
true
}
_ => false,
}
}
fn selected_unlocked_note_ids(&self) -> Vec<String> {
self.edgeless
.authoring
.painted_items
.iter()
.filter(|i| {
self.edgeless.authoring.selection.contains(&i.id)
&& !i.locked
&& i.kind == SpatialItemKind::Note
})
.map(|i| i.id.clone())
.collect()
}
pub(super) fn precompute_font_size_updates(
&self,
snapshot: &PageSnapshot,
action: &EdgelessElementAction,
cx: &Context<Self>,
) -> (Vec<(String, Any)>, Vec<(String, String)>) {
let mut connector_label_styles = Vec::new();
let mut surface_text_xywhs = Vec::new();
if let EdgelessElementAction::SetFontSize(fs) = action
&& let Some(root) = snapshot.root.as_ref()
{
let ts = WindowTextSystem::new(cx.text_system().clone());
for node in root.walk() {
if let BlockContent::Surface { elements, .. } = &node.content {
for el in elements {
if !self.edgeless.authoring.selection.contains(&el.id) {
continue;
}
match &el.kind {
SurfaceElementKind::Connector(conn) => {
let mut map = AHashMap::default();
let color_any = match &conn.label_style.color {
blocksuite_playground_doc::read::ColorValue::Single(s) => {
Any::String(s.clone())
}
blocksuite_playground_doc::read::ColorValue::Themed {
light,
dark,
} => {
let mut c = AHashMap::default();
c.insert("light".into(), Any::String(light.clone()));
c.insert("dark".into(), Any::String(dark.clone()));
Any::Object(Box::new(c))
}
};
map.insert("color".into(), color_any);
map.insert("fontSize".into(), Any::Float64((*fs).into()));
map.insert(
"fontFamily".into(),
Any::String(conn.label_style.font_family.clone()),
);
map.insert(
"fontWeight".into(),
Any::String(conn.label_style.font_weight.clone()),
);
map.insert(
"fontStyle".into(),
Any::String(conn.label_style.font_style.clone()),
);
map.insert(
"textAlign".into(),
Any::String(conn.label_style.text_align.as_str().into()),
);
connector_label_styles
.push((el.id.clone(), Any::Object(Box::new(map))));
}
SurfaceElementKind::Text(t) => {
let xywh = measure_surface_text_xywh(t, *fs, self.theme, &ts);
surface_text_xywhs
.push((el.id.clone(), PageDocSession::format_xywh(xywh)));
}
_ => {}
}
}
}
}
}
(connector_label_styles, surface_text_xywhs)
}
pub(super) fn precompute_flipped_connectors(
&self,
snapshot: &PageSnapshot,
action: &EdgelessElementAction,
) -> Vec<(String, Any, Any)> {
let mut flipped = Vec::new();
if matches!(action, EdgelessElementAction::FlipConnectorDirection)
&& let Some(root) = snapshot.root.as_ref()
{
for node in root.walk() {
if let BlockContent::Surface { elements, .. } = &node.content {
for el in elements {
if !self.edgeless.authoring.selection.contains(&el.id) {
continue;
}
if let SurfaceElementKind::Connector(conn) = &el.kind {
let ep_to_any =
|ep: &blocksuite_playground_doc::read::ConnectorEndpoint| {
let mut m = AHashMap::default();
if let Some(id) = &ep.id {
m.insert("id".into(), Any::String(id.clone()));
}
if let Some([x, y]) = ep.position {
m.insert(
"position".into(),
Any::Array(vec![
Any::Float64(x.into()),
Any::Float64(y.into()),
]),
);
}
Any::Object(Box::new(m))
};
flipped.push((
el.id.clone(),
ep_to_any(&conn.target),
ep_to_any(&conn.source),
));
}
}
}
}
}
flipped
}
pub(super) fn precompute_auto_shape_text_ids(
&self,
snapshot: &PageSnapshot,
action: &EdgelessElementAction,
) -> HashSet<String> {
let mut out = HashSet::new();
if matches!(
action,
EdgelessElementAction::SetColor {
slot: ElementColorSlot::Fill,
..
} | EdgelessElementAction::SetFillColor(_)
) && let Some(root) = snapshot.root.as_ref()
{
for node in root.walk() {
if let BlockContent::Surface { elements, .. } = &node.content {
for el in elements {
if self.edgeless.authoring.selection.contains(&el.id)
&& let SurfaceElementKind::Shape(s) = &el.kind
&& is_neutral_shape_text_color(&s.color)
{
out.insert(el.id.clone());
}
}
}
}
}
out
}
}
@@ -0,0 +1,526 @@
//! Canvas media & embed block toolbar actions (`Caption`, `Card/Embed` view toggle,
//! `Style`, `Rotate`, `Scale`, `Open`, `Copy link`, `Reload`, `Info`, `Download`).
use blocksuite_playground_doc::{
read::{BlockContent, BlockNode, ExternalEmbedKind, PageSnapshot},
schema::{BlockSpec, json_to_session_value},
};
use ui::{ClipboardItem, Context, Window};
use y_octo::{Any, SessionValue};
use crate::{
BlobFetchState, DocPanelTab, PlaygroundView,
block_flow::{ImageSlot, embed_card_size},
overlays::{OverlayEvent, block_caption_text, embed_view_kind_for_url},
room_client::RoomCommand,
};
use super::{EdgelessElementAction, SpatialItemInfo, SpatialItemKind, prop_f32};
/// Host-observable media/attachment download payload dispatched from Edgeless or Page toolbars.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DownloadedMedia {
pub block_id: String,
pub source_id: String,
pub filename: String,
pub mime_type: String,
pub bytes: Vec<u8>,
}
/// Runtime timer and media download hook owned by `PlaygroundView`.
#[derive(Default)]
pub(crate) struct EdgelessHostRuntime {
pub(crate) quick_connect_hover_timer: Option<ui::Task<()>>,
pub(crate) quick_connect_hover_gen: u64,
pub(crate) on_media_download: Option<Box<dyn FnMut(&DownloadedMedia)>>,
}
/// Caption of a captioned canvas block, empty when it has none.
fn caption_of(node: &BlockNode) -> String {
block_caption_text(&node.content)
.unwrap_or_default()
.to_string()
}
/// Standard canvas frame of a card or embed `style`, at the block's scale and keeping its
/// top-left corner, as BlockSuite writes it when the style or the view changes.
fn standard_frame(single: &SpatialItemInfo, node: &BlockNode, style: &str) -> [f64; 4] {
let (w, h) = embed_card_size(style).unwrap_or((752.0, 544.0));
let scale = f64::from(prop_f32(node, "prop:scale", 1.0).clamp(0.1, 10.0));
[
f64::from(single.rect.x),
f64::from(single.rect.y),
f64::from(w) * scale,
f64::from(h) * scale,
]
}
/// `prop:style` BlockSuite gives an external embed in embed view.
fn embed_view_style(kind: ExternalEmbedKind) -> Option<&'static str> {
match kind {
ExternalEmbedKind::Youtube | ExternalEmbedKind::Loom => Some("video"),
ExternalEmbedKind::Figma => Some("figma"),
ExternalEmbedKind::Github => Some("horizontal"),
ExternalEmbedKind::Html => Some("html"),
ExternalEmbedKind::Iframe | ExternalEmbedKind::Web => None,
}
}
fn find_parent_block_id(snapshot: &PageSnapshot, block_id: &str) -> Option<String> {
let root = snapshot.root.as_ref()?;
for node in root.walk() {
if node.children.iter().any(|c| c.id == block_id) {
return Some(node.id.clone());
}
}
None
}
fn infer_image_ext_and_mime(bytes: &[u8]) -> (&'static str, &'static str) {
if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
("png", "image/png")
} else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) {
("jpg", "image/jpeg")
} else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
("gif", "image/gif")
} else if bytes.len() >= 12 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
("webp", "image/webp")
} else if bytes.starts_with(b"BM") {
("bmp", "image/bmp")
} else {
("bin", "application/octet-stream")
}
}
#[cfg(target_arch = "wasm32")]
fn trigger_web_download(filename: &str, mime_type: &str, bytes: &[u8]) {
use wasm_bindgen::JsCast;
let Some(window) = web_sys::window() else {
return;
};
let Some(document) = window.document() else {
return;
};
let array = js_sys::Uint8Array::from(bytes);
let parts = js_sys::Array::of1(&array.into());
let bag = web_sys::BlobPropertyBag::new();
bag.set_type(mime_type);
let Ok(blob) = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &bag) else {
return;
};
let Ok(url) = web_sys::Url::create_object_url_with_blob(&blob) else {
return;
};
if let Ok(el) = document.create_element("a")
&& let Ok(anchor) = el.dyn_into::<web_sys::HtmlAnchorElement>()
{
anchor.set_href(&url);
anchor.set_download(filename);
anchor.click();
}
let _ = web_sys::Url::revoke_object_url(&url);
}
impl PlaygroundView {
/// Install a host callback invoked whenever a media or attachment download is triggered.
pub fn set_on_media_download(&mut self, callback: impl FnMut(&DownloadedMedia) + 'static) {
self.edgeless_runtime.on_media_download = Some(Box::new(callback));
}
pub(super) fn apply_edgeless_media_action(
&mut self,
action: &EdgelessElementAction,
window: Option<&mut Window>,
cx: &mut Context<Self>,
) {
let Some(single) = self.edgeless.authoring.single_selected().cloned() else {
return;
};
if single.kind != SpatialItemKind::SurfaceBlock || single.locked {
return;
}
let Some(snapshot) = self.snapshot.clone() else {
return;
};
let Some(node) = snapshot.block(&single.id) else {
return;
};
let block_id = single.id.clone();
let now_ms = self.now_ms(cx) as u64;
match action {
EdgelessElementAction::MediaCaption => {
self.dismiss_edgeless_element_popovers();
if let Some(win) = window {
self.focus_caption(block_id, None, 1, false, win, cx);
}
}
EdgelessElementAction::MediaToggleView => {
self.apply_edgeless_media_toggle_view(&snapshot, node, &single, now_ms, cx);
}
EdgelessElementAction::MediaSetCardStyle(style) => {
self.edgeless.authoring.open_sub_menu = None;
let style = style.clone();
// Bookmark and linked-doc cards take the standard size of their new style.
let frame = matches!(
node.content,
BlockContent::Bookmark { .. } | BlockContent::EmbedLinkedDoc { .. }
)
.then(|| standard_frame(&single, node, &style));
let commit = self.page_mut().ok().and_then(|page| {
page.structural_edit(now_ms, move |page| {
page.set_block_prop(
&block_id,
"prop:style",
SessionValue::Any(Any::String(style.clone())),
now_ms,
)?;
if let Some(frame) = frame {
page.set_block_xywh(&block_id, frame, now_ms)?;
}
Ok(())
})
.ok()
.flatten()
});
if let Some(c) = commit {
self.did_edgeless_doc_commit(c, cx);
}
}
EdgelessElementAction::MediaRotateCw => {
let next_rot = ((single.rotate_deg as f64) + 90.0).rem_euclid(360.0);
let commit = self.page_mut().ok().and_then(|page| {
page.structural_edit(now_ms, move |page| {
page.set_block_rotate(&block_id, next_rot, now_ms)?;
Ok(())
})
.ok()
.flatten()
});
if let Some(c) = commit {
self.did_edgeless_doc_commit(c, cx);
}
}
EdgelessElementAction::MediaSetScale(scale) => {
self.edgeless.authoring.open_sub_menu = None;
let cur_scale = super::prop_f32(node, "prop:scale", 1.0).max(0.1) as f64;
let ratio = (*scale / cur_scale).clamp(0.1, 10.0);
let new_w = (single.rect.w as f64 * ratio).max(40.0);
let new_h = (single.rect.h as f64 * ratio).max(40.0);
let xywh = [single.rect.x as f64, single.rect.y as f64, new_w, new_h];
let scale = *scale;
let commit = self.page_mut().ok().and_then(|page| {
page.structural_edit(now_ms, move |page| {
page.set_block_prop(
&block_id,
"prop:scale",
SessionValue::Any(Any::Float64(scale.into())),
now_ms,
)?;
page.set_block_xywh(&block_id, xywh, now_ms)?;
Ok(())
})
.ok()
.flatten()
});
if let Some(c) = commit {
self.did_edgeless_doc_commit(c, cx);
}
}
EdgelessElementAction::MediaOpenLink => match &node.content {
BlockContent::Bookmark { url, .. } | BlockContent::ExternalEmbed { url, .. }
if url.starts_with("http://") || url.starts_with("https://") =>
{
cx.open_url(url);
}
BlockContent::EmbedLinkedDoc { page_id, .. }
| BlockContent::EmbedSyncedDoc { page_id, .. } => {
let target_page_id = page_id.clone();
if let Some(win) = window {
self.dispatch_overlay(
OverlayEvent::OpenEmbedDoc {
page_id: target_page_id,
},
win,
cx,
);
} else {
self.open_linked_doc(&target_page_id, None, cx);
}
}
_ => {}
},
EdgelessElementAction::MediaCopyLink => {
let link = match &node.content {
BlockContent::Bookmark { url, .. }
| BlockContent::ExternalEmbed { url, .. } => Some(url.clone()),
BlockContent::EmbedLinkedDoc { page_id, .. }
| BlockContent::EmbedSyncedDoc { page_id, .. } => Some(page_id.clone()),
_ => None,
};
if let Some(text) = link {
cx.write_to_clipboard(ClipboardItem::new_string(text));
}
}
EdgelessElementAction::MediaInfo => {
self.edgeless.authoring.open_sub_menu = None;
self.set_doc_panel_tab(Some(DocPanelTab::Info), cx);
}
EdgelessElementAction::MediaReload => {
self.apply_edgeless_media_reload(node, &block_id, cx);
}
EdgelessElementAction::MediaDownload => {
self.apply_edgeless_media_download(node, &block_id, cx);
}
_ => {}
}
}
fn apply_edgeless_media_toggle_view(
&mut self,
snapshot: &PageSnapshot,
node: &BlockNode,
single: &super::SpatialItemInfo,
now_ms: u64,
cx: &mut Context<Self>,
) {
let block_id = node.id.clone();
match &node.content {
BlockContent::Attachment { .. } => {
let cur = node
.props
.get("prop:embed")
.and_then(|v| v.as_bool())
.unwrap_or(false);
let next = !cur;
let commit = self.page_mut().ok().and_then(|page| {
page.structural_edit(now_ms, move |page| {
page.set_block_prop(
&block_id,
"prop:embed",
SessionValue::Any(if next { Any::True } else { Any::False }),
now_ms,
)?;
Ok(())
})
.ok()
.flatten()
});
if let Some(c) = commit {
self.did_edgeless_doc_commit(c, cx);
}
}
BlockContent::EmbedLinkedDoc { page_id, .. } => {
let spec = BlockSpec::EmbedSyncedDoc {
page_id: page_id.clone(),
caption: caption_of(node),
};
let frame = standard_frame(single, node, "syncedDoc");
self.replace_canvas_media_block(snapshot, node, spec, frame, None, now_ms, cx);
}
BlockContent::EmbedSyncedDoc { page_id, .. } => {
let spec = BlockSpec::EmbedLinkedDoc {
page_id: page_id.clone(),
style: "horizontal".to_string(),
caption: caption_of(node),
};
let frame = standard_frame(single, node, "horizontal");
self.replace_canvas_media_block(snapshot, node, spec, frame, None, now_ms, cx);
}
BlockContent::Bookmark {
url,
title,
description,
caption,
} => {
let Some(kind) = embed_view_kind_for_url(url) else {
return;
};
let style = embed_view_style(kind);
let spec = BlockSpec::ExternalEmbed {
kind,
url: url.clone(),
title: title.clone(),
description: description.clone(),
html: None,
caption: caption.clone(),
};
let frame = standard_frame(single, node, style.unwrap_or("video"));
self.replace_canvas_media_block(snapshot, node, spec, frame, style, now_ms, cx);
}
BlockContent::ExternalEmbed {
url,
title,
description,
..
} => {
let spec = BlockSpec::Bookmark {
url: url.clone(),
title: title.clone(),
description: description.clone(),
};
let frame = standard_frame(single, node, "horizontal");
self.replace_canvas_media_block(snapshot, node, spec, frame, None, now_ms, cx);
}
_ => {}
}
}
/// Replace a canvas block by `spec` at `frame` in one undo step, keeping its z-index,
/// rotation, scale, caption, and linked-doc `params`, and select the new block.
#[allow(clippy::too_many_arguments)]
fn replace_canvas_media_block(
&mut self,
snapshot: &PageSnapshot,
node: &BlockNode,
spec: BlockSpec,
frame: [f64; 4],
style: Option<&str>,
now_ms: u64,
cx: &mut Context<Self>,
) {
let Some(parent_id) = find_parent_block_id(snapshot, &node.id) else {
return;
};
let old_id = node.id.clone();
let fresh_id = self.fresh_block_id();
let index = node
.props
.get("prop:index")
.and_then(|v| v.as_str())
.unwrap_or("a0")
.to_string();
let caption = caption_of(node);
let carried: Vec<(&str, SessionValue)> = ["prop:rotate", "prop:scale", "prop:params"]
.into_iter()
.filter_map(|key| Some((key, json_to_session_value(node.props.get(key)?))))
.chain(style.map(|s| ("prop:style", SessionValue::Any(Any::String(s.to_string())))))
.collect();
let fresh_clone = fresh_id.clone();
let commit = self.page_mut().ok().and_then(|page| {
page.structural_edit(now_ms, move |page| {
page.add_block(&fresh_clone, spec, Some(&parent_id), None, now_ms)?;
page.set_block_xywh(&fresh_clone, frame, now_ms)?;
page.set_block_index(&fresh_clone, &index, now_ms)?;
for &(key, ref value) in &carried {
page.set_block_prop(&fresh_clone, key, value.clone(), now_ms)?;
}
if !caption.is_empty() {
page.set_block_caption(&fresh_clone, &caption, now_ms)?;
}
page.delete_block_subtree(&parent_id, &old_id, now_ms)?;
Ok(())
})
.ok()
.flatten()
});
if let Some(c) = commit {
self.did_edgeless_doc_commit(c, cx);
self.edgeless.authoring.selection.clear();
self.edgeless.authoring.selection.insert(fresh_id);
}
}
fn apply_edgeless_media_reload(
&mut self,
node: &BlockNode,
block_id: &str,
cx: &mut Context<Self>,
) {
self.edgeless.authoring.open_sub_menu = None;
let source_id = match &node.content {
BlockContent::Image { source_id, .. } | BlockContent::Attachment { source_id, .. }
if !source_id.is_empty() =>
{
Some(source_id.clone())
}
_ => None,
};
if let Some(sid) = source_id {
self.images.remove(&sid);
self.blob_fetches.remove(&sid);
if let Some(prev) = self.pdf_previews.remove(block_id) {
self.images.retire_render_image(prev.image);
}
self.pdf_preview_keys.remove(block_id);
self.failed_pdf_blobs.retain(|(s, _, _)| s != &sid);
if let Some(bytes) = self.state.blobs.get(&sid) {
if matches!(node.content, BlockContent::Image { .. }) {
let slot = crate::block_flow::decode_image(bytes)
.map_or(ImageSlot::Unavailable, ImageSlot::Ready);
self.images.insert(sid, slot);
} else {
let pdf_attachments = self.active_pdf_attachments();
self.refresh_pdf_previews(&pdf_attachments);
}
} else if let Some(room) = &self.room {
self.blob_fetches.insert(
sid.clone(),
BlobFetchState {
in_flight: true,
..BlobFetchState::default()
},
);
self.images.insert(sid.clone(), ImageSlot::Loading);
room.link.send(RoomCommand::FetchBlob(sid));
}
}
self.env_rev = self.env_rev.wrapping_add(1);
cx.notify();
}
fn apply_edgeless_media_download(
&mut self,
node: &BlockNode,
block_id: &str,
cx: &mut Context<Self>,
) {
self.edgeless.authoring.open_sub_menu = None;
let (source_id, name_opt, mime_opt) = match &node.content {
BlockContent::Attachment {
source_id,
name,
mime_type,
..
} if !source_id.is_empty() => (
source_id.clone(),
(!name.is_empty()).then(|| name.clone()),
(!mime_type.is_empty()).then(|| mime_type.clone()),
),
BlockContent::Image {
source_id, caption, ..
} if !source_id.is_empty() => (
source_id.clone(),
(!caption.is_empty()).then(|| caption.clone()),
None,
),
_ => return,
};
let Some(bytes) = self
.state
.blobs
.get(&source_id)
.map(|b| b.as_slice().to_vec())
else {
return;
};
let (inferred_ext, inferred_mime) = infer_image_ext_and_mime(&bytes);
let mime_type = mime_opt.unwrap_or_else(|| inferred_mime.to_string());
let filename = match name_opt {
Some(n) => n,
None => format!("{source_id}.{inferred_ext}"),
};
#[cfg(target_arch = "wasm32")]
trigger_web_download(&filename, &mime_type, &bytes);
let payload = DownloadedMedia {
block_id: block_id.to_string(),
source_id,
filename,
mime_type,
bytes,
};
if let Some(cb) = self.edgeless_runtime.on_media_download.as_mut() {
cb(&payload);
}
cx.notify();
}
}
@@ -2,14 +2,13 @@
use std::collections::BTreeSet;
use blocksuite_playground_doc::read::SurfaceElementKind;
use ui::{Context, MouseDownEvent, MouseMoveEvent, Window, point, px};
use crate::{PlaygroundView, TOPBAR_HEIGHT, editor_session::DocumentSelection};
use super::{
DragItemInitial, EdgelessGesture, EdgelessTool, HandleKind, NOTE_CARD_PADDING, SpatialItemKind,
find_surface_element, normalized_rect, point_in_rotated_rect, rotate_point_around,
EdgelessGesture, EdgelessTool, HandleKind, NOTE_CARD_PADDING, SpatialItemKind, normalized_rect,
point_in_rotated_rect, rotate_point_around,
};
impl PlaygroundView {
@@ -24,6 +23,7 @@ impl PlaygroundView {
cx.notify();
}
self.edgeless.authoring.hovered_note_slice = None;
self.edgeless.authoring.quick_connect_hover = None;
if self.doc_panel_tab.is_some() {
self.doc_panel_tab = None;
cx.notify();
@@ -164,7 +164,7 @@ impl PlaygroundView {
match self.edgeless.authoring.tool {
EdgelessTool::Select => {
// 0. Check 4-way `auto-complete` quick-connect arrows on a single selected unlocked Shape.
// 0. Check quick-connect arrows on a single selected unlocked Shape or Note.
if self.edgeless.authoring.inline_edit.is_none()
&& let Some(single) = self.edgeless.authoring.single_selected().cloned()
&& let Some(dir) = super::hit_test_auto_complete_arrow(
@@ -173,23 +173,29 @@ impl PlaygroundView {
vp_origin,
self.edgeless.camera,
)
&& let Some(surface_id) = single.surface_id.clone()
{
let src_world = dir.source_world_anchor(single.rect);
self.edgeless.authoring.gesture = Some(EdgelessGesture::QuickConnect {
source_id: single.id,
source_surface_id: surface_id,
direction: dir,
source_world: src_world,
start_screen: event.position,
current_world: (wx, wy),
target_id: None,
target_port: None,
target_world: None,
dragged: false,
});
cx.notify();
return;
if single.kind == SpatialItemKind::Note {
let _ = self.edgeless_quick_connect_note_click(&single.id, dir, cx);
cx.notify();
return;
}
if let Some(surface_id) = single.surface_id.clone() {
let src_world = dir.source_world_anchor(single.rect);
self.edgeless.authoring.gesture = Some(EdgelessGesture::QuickConnect {
source_id: single.id,
source_surface_id: surface_id,
direction: dir,
source_world: src_world,
start_screen: event.position,
current_world: (wx, wy),
target_id: None,
target_port: None,
target_world: None,
dragged: false,
});
cx.notify();
return;
}
}
// 1. Check active selection handles first.
let vp_w = self.window_size.0.max(1.0);
@@ -683,7 +689,15 @@ impl PlaygroundView {
let vp_w = self.window_size.0.max(1.0);
let vp_h = (self.window_size.1 - TOPBAR_HEIGHT).max(1.0);
let next_slice_hover = if !self.is_edgeless_write_readonly()
let over_toolbar = self.edgeless.authoring.gesture.is_none()
&& self
.edgeless
.authoring
.point_in_toolbar(event.position, vp_origin);
self.update_quick_connect_hover(over_toolbar, event.position, vp_origin, cx);
let next_slice_hover = if !over_toolbar
&& !self.is_edgeless_write_readonly()
&& self.edgeless.authoring.gesture.is_none()
&& self.edgeless.authoring.inline_edit.is_none()
&& let Some(snap) = self.snapshot.as_deref()
@@ -723,57 +737,4 @@ impl PlaygroundView {
cx.notify();
}
}
pub(super) fn collect_drag_initials(&self) -> Vec<DragItemInitial> {
let Some(snapshot) = &self.snapshot else {
return Vec::new();
};
let ids = self.expand_selection_with_containers(&self.edgeless.authoring.selection);
let mut out = Vec::new();
for item in self.edgeless.authoring.painted_items.iter() {
if !ids.contains(&item.id) || item.locked {
continue;
}
let mut points = None;
let mut connector_source = None;
let mut connector_target = None;
let mut connector_label_xywh = None;
if let Some((_, el)) = find_surface_element(snapshot, &item.id) {
match &el.kind {
SurfaceElementKind::Brush(s) | SurfaceElementKind::Highlighter(s) => {
points = Some(
s.points
.iter()
.map(|p| {
if s.simulated_pressure {
vec![p[0], p[1]]
} else {
vec![p[0], p[1], p[2]]
}
})
.collect(),
);
}
SurfaceElementKind::Connector(c) => {
connector_source = Some((c.source.id.clone(), c.source.position));
connector_target = Some((c.target.id.clone(), c.target.position));
connector_label_xywh = c.label_xywh;
}
_ => {}
}
}
out.push(DragItemInitial {
id: item.id.clone(),
kind: item.kind,
surface_id: item.surface_id.clone(),
rect: item.rect,
rotate_deg: item.rotate_deg,
points,
connector_source,
connector_target,
connector_label_xywh,
});
}
out
}
}
@@ -209,34 +209,39 @@ impl PlaygroundView {
let Some(snapshot) = self.snapshot.as_deref() else {
return false;
};
let direct_parent_group = super::lock_ops::collect_direct_parent_groups(snapshot);
let mut plans = Vec::new();
let mut next_selection: BTreeSet<String> = self.edgeless.authoring.selection.clone();
for id in &self.edgeless.authoring.selection {
if let Some((_, el)) = super::find_surface_element(snapshot, id)
&& !el.locked_by_self
&& matches!(
el.kind,
blocksuite_playground_doc::read::SurfaceElementKind::Group { .. }
)
&& let Some(plan) =
super::lock_ops::plan_ungroup_operation(snapshot, id, &direct_parent_group)
{
next_selection.remove(id);
for child in &plan.ordered_children {
next_selection.insert(child.id.clone());
}
plans.push(plan);
}
}
let direct_parent_group = super::ungroup_ops::collect_direct_parent_groups(snapshot);
let group_ids: Vec<String> = self
.edgeless
.authoring
.selection
.iter()
.filter(|id| {
super::find_surface_element(snapshot, id).is_some_and(|(_, el)| {
!el.locked_by_self && matches!(el.kind, SurfaceElementKind::Group { .. })
})
})
.cloned()
.collect();
let plans = super::ungroup_ops::plan_batch_ungroup_operations(
snapshot,
&group_ids,
&direct_parent_group,
);
if plans.is_empty() {
return false;
}
let mut next_selection: BTreeSet<String> = self.edgeless.authoring.selection.clone();
for plan in &plans {
next_selection.remove(&plan.group_id);
for child in &plan.ordered_children {
next_selection.insert(child.id.clone());
}
}
let now_ms = self.now_ms(cx) as u64;
let commit = self.page_mut().ok().and_then(|page| {
page.structural_edit(now_ms, move |page| {
for plan in &plans {
super::lock_ops::apply_ungroup_plan(page, plan, now_ms)?;
super::ungroup_ops::apply_ungroup_plan(page, plan, now_ms)?;
}
Ok(())
})
@@ -396,6 +401,28 @@ impl PlaygroundView {
if selected.is_empty() {
return;
}
// The selection already ends its paint stream (blocks or canvas elements): no new
// indices and no undo step.
let painted = &self.edgeless.authoring.painted_items;
let at_end = [true, false].into_iter().all(|blocks| {
let stream: Vec<&SpatialItemInfo> = painted
.iter()
.filter(|i| i.kind.is_block() == blocks)
.collect();
let picked = selected
.iter()
.filter(|s| s.kind.is_block() == blocks)
.count();
let end = if bring_to_front {
&stream[stream.len().saturating_sub(picked)..]
} else {
&stream[..picked.min(stream.len())]
};
end.iter().all(|i| selected.iter().any(|s| s.id == i.id))
});
if at_end {
return;
}
let now_ms = self.now_ms(cx) as u64;
let mut updates = Vec::new();
let ordered: Vec<SpatialItemInfo> = if bring_to_front {
@@ -7,276 +7,16 @@
use std::collections::{BTreeSet, HashMap, HashSet};
use blocksuite_playground_doc::{
DocResult,
fractional_index::generate_n_keys_between,
read::{BlockContent, NoteDisplayMode, PageSnapshot, SurfaceElementKind},
session::PageDocSession,
};
use blocksuite_playground_doc::read::{BlockContent, PageSnapshot, SurfaceElementKind};
use ui::Context;
use y_octo::{Any, SessionValue};
use crate::PlaygroundView;
use super::{SpatialItemInfo, SpatialItemKind, WorldRect, next_index_after, next_spatial_index};
#[derive(Clone, Debug)]
pub(super) struct UngroupChildUpdate {
pub id: String,
pub is_block: bool,
pub surface_id: Option<String>,
pub new_index: Option<String>,
}
#[derive(Clone, Debug)]
pub(super) struct UngroupPlan {
pub group_surface_id: String,
pub group_id: String,
pub parent_group: Option<(String, String)>,
pub ordered_children: Vec<UngroupChildUpdate>,
}
#[derive(Clone)]
struct SpatialIndexEntry {
id: String,
index: String,
is_block: bool,
surface_id: Option<String>,
seq: usize,
}
fn build_ungroup_indexes(
count: usize,
before_index: Option<&str>,
after_index: Option<&str>,
fallback_anchor: &str,
) -> Vec<String> {
if count == 0 {
return Vec::new();
}
generate_n_keys_between(before_index, after_index, count)
.or_else(|_| generate_n_keys_between(before_index, None, count))
.or_else(|_| generate_n_keys_between(Some(fallback_anchor), None, count))
.or_else(|_| generate_n_keys_between(None, None, count))
.unwrap_or_default()
}
pub(super) fn collect_direct_parent_groups(
snapshot: &PageSnapshot,
) -> HashMap<String, (String, String)> {
let mut map = HashMap::new();
let Some(root) = snapshot.root.as_ref() else {
return map;
};
for node in root.walk() {
let BlockContent::Surface { elements, .. } = &node.content else {
continue;
};
for el in elements {
if let SurfaceElementKind::Group { children, .. } = &el.kind {
for cid in children {
map.insert(cid.clone(), (node.id.clone(), el.id.clone()));
}
}
}
}
map
}
pub(super) fn plan_ungroup_operation(
snapshot: &PageSnapshot,
group_id: &str,
direct_parent_group: &HashMap<String, (String, String)>,
) -> Option<UngroupPlan> {
let root = snapshot.root.as_ref()?;
let (group_sid, group_el) = super::find_surface_element(snapshot, group_id)?;
let SurfaceElementKind::Group { children, .. } = &group_el.kind else {
return None;
};
let mut entries_by_id: HashMap<String, SpatialIndexEntry> = HashMap::new();
let mut all_entries: Vec<SpatialIndexEntry> = Vec::new();
let mut mindmap_members: HashSet<String> = HashSet::new();
let mut seq = 0usize;
let mut push_block = |node: &blocksuite_playground_doc::read::BlockNode| {
let idx = node
.props
.get("prop:index")
.and_then(|v| v.as_str())
.unwrap_or("a0")
.to_string();
let entry = SpatialIndexEntry {
id: node.id.clone(),
index: idx,
is_block: true,
surface_id: None,
seq,
};
seq += 1;
entries_by_id.insert(entry.id.clone(), entry.clone());
all_entries.push(entry);
};
for child in &root.children {
match &child.content {
BlockContent::Note { display_mode, .. }
if *display_mode != NoteDisplayMode::DocOnly =>
{
push_block(child);
}
BlockContent::Frame { .. } | BlockContent::EdgelessText { .. } => {
push_block(child);
}
BlockContent::Surface { .. } => {
for sc in &child.children {
match &sc.content {
BlockContent::Frame { .. }
| BlockContent::EdgelessText { .. }
| BlockContent::Image { .. }
| BlockContent::Attachment { .. }
| BlockContent::Bookmark { .. }
| BlockContent::ExternalEmbed { .. }
| BlockContent::SurfaceRef { .. }
| BlockContent::Latex { .. } => push_block(sc),
_ => {}
}
}
}
_ => {}
}
}
for child in &root.children {
if let BlockContent::Surface { elements, .. } = &child.content {
for el in elements {
if matches!(el.kind, SurfaceElementKind::Unknown { .. }) {
continue;
}
if let SurfaceElementKind::Mindmap(mm) = &el.kind {
for nid in mm.nodes.keys() {
mindmap_members.insert(nid.clone());
}
}
let entry = SpatialIndexEntry {
id: el.id.clone(),
index: el.index.clone(),
is_block: false,
surface_id: Some(child.id.clone()),
seq,
};
seq += 1;
entries_by_id.insert(entry.id.clone(), entry.clone());
all_entries.push(entry);
}
}
}
let mut ordered_entries: Vec<SpatialIndexEntry> = children
.iter()
.filter_map(|cid| entries_by_id.get(cid).cloned())
.collect();
ordered_entries.sort_by(|a, b| a.index.cmp(&b.index).then_with(|| a.seq.cmp(&b.seq)));
let parent_group = direct_parent_group.get(group_id).cloned();
let mut siblings: Vec<SpatialIndexEntry> = if let Some((_, ref pgid)) = parent_group {
super::find_surface_element(snapshot, pgid)
.and_then(|(_, pel)| match &pel.kind {
SurfaceElementKind::Group { children: pc, .. } => Some(
pc.iter()
.filter_map(|cid| entries_by_id.get(cid).cloned())
.collect::<Vec<_>>(),
),
_ => None,
})
.unwrap_or_default()
} else {
all_entries
.into_iter()
.filter(|e| {
!direct_parent_group.contains_key(&e.id) && !mindmap_members.contains(&e.id)
})
.collect()
};
siblings.sort_by(|a, b| a.index.cmp(&b.index).then_with(|| a.seq.cmp(&b.seq)));
let group_pos = siblings.iter().position(|s| s.id == group_id);
let before_sibling_index = group_pos
.and_then(|p| p.checked_sub(1))
.and_then(|i| siblings.get(i))
.map(|s| s.index.as_str());
let after_sibling_index = group_pos
.and_then(|p| siblings.get(p + 1))
.map(|s| s.index.as_str());
let next_indexes = build_ungroup_indexes(
ordered_entries.len(),
before_sibling_index,
after_sibling_index,
&group_el.index,
);
let ordered_children = ordered_entries
.into_iter()
.enumerate()
.map(|(idx, e)| {
let new_index = next_indexes
.get(idx)
.filter(|ni| ni.as_str() != e.index.as_str())
.cloned();
UngroupChildUpdate {
id: e.id,
is_block: e.is_block,
surface_id: e.surface_id,
new_index,
}
})
.collect();
Some(UngroupPlan {
group_surface_id: group_sid.to_string(),
group_id: group_id.to_string(),
parent_group,
ordered_children,
})
}
pub(super) fn apply_ungroup_plan(
page: &mut PageDocSession,
plan: &UngroupPlan,
now_ms: u64,
) -> DocResult<()> {
let child_ids: Vec<String> = plan.ordered_children.iter().map(|c| c.id.clone()).collect();
if let Some((psid, pgid)) = &plan.parent_group {
page.update_group_children_delta(
psid,
pgid,
&child_ids,
std::slice::from_ref(&plan.group_id),
now_ms,
)?;
}
for child in &plan.ordered_children {
if let Some(new_idx) = &child.new_index {
if child.is_block {
page.set_block_prop(
&child.id,
"prop:index",
SessionValue::Any(Any::String(new_idx.clone())),
now_ms,
)?;
} else if let Some(csid) = &child.surface_id {
page.set_surface_element_field(
csid,
&child.id,
"index",
SessionValue::Any(Any::String(new_idx.clone())),
now_ms,
)?;
}
}
}
page.remove_surface_element(&plan.group_surface_id, &plan.group_id, now_ms)?;
Ok(())
}
use super::{
SpatialItemInfo, SpatialItemKind, WorldRect, next_index_after, next_spatial_index,
ungroup_ops::{apply_ungroup_plan, plan_batch_ungroup_operations},
};
fn find_locked_ancestor_group(
snapshot: &PageSnapshot,
@@ -426,7 +166,7 @@ impl PlaygroundView {
cx: &mut Context<Self>,
) {
let mut next_selection: BTreeSet<String> = self.edgeless.authoring.selection.clone();
let mut ungroup_plans: Vec<UngroupPlan> = Vec::new();
let mut ungroup_group_ids: Vec<String> = Vec::new();
let mut ungrouped_ids: BTreeSet<String> = BTreeSet::new();
let mut unlock_blocks: Vec<String> = Vec::new();
let mut unlock_surface: Vec<(String, String)> = Vec::new();
@@ -437,28 +177,17 @@ impl PlaygroundView {
&& let Some((_, el)) = super::find_surface_element(snapshot, id)
&& matches!(el.kind, SurfaceElementKind::Group { .. })
{
if ungrouped_ids.insert(id.clone())
&& let Some(plan) = plan_ungroup_operation(snapshot, id, direct_parent_group)
{
if ungrouped_ids.insert(id.clone()) {
next_selection.remove(id);
for child in &plan.ordered_children {
next_selection.insert(child.id.clone());
}
ungroup_plans.push(plan);
ungroup_group_ids.push(id.clone());
}
} else if let Some(locked_gid) =
find_locked_ancestor_group(snapshot, id, direct_parent_group)
{
next_selection.remove(id);
next_selection.remove(&locked_gid);
if ungrouped_ids.insert(locked_gid.clone())
&& let Some(plan) =
plan_ungroup_operation(snapshot, &locked_gid, direct_parent_group)
{
for child in &plan.ordered_children {
next_selection.insert(child.id.clone());
}
ungroup_plans.push(plan);
if ungrouped_ids.insert(locked_gid.clone()) {
ungroup_group_ids.push(locked_gid);
}
if *is_block {
if snapshot
@@ -484,6 +213,14 @@ impl PlaygroundView {
unlock_surface.push((sid.clone(), id.clone()));
}
}
let ungroup_plans =
plan_batch_ungroup_operations(snapshot, &ungroup_group_ids, direct_parent_group);
for plan in &ungroup_plans {
next_selection.remove(&plan.group_id);
for child in &plan.ordered_children {
next_selection.insert(child.id.clone());
}
}
let plans_for_paint = ungroup_plans.clone();
let unlock_surface_ids: HashSet<String> =
@@ -6,19 +6,27 @@ mod commit;
mod connector_edit;
mod copy_cut;
#[cfg(test)]
mod edgeless_canvas_media_tests;
#[cfg(test)]
mod edgeless_element_toolbar_tests;
#[cfg(test)]
mod edgeless_guards_tests;
#[cfg(test)]
mod edgeless_text_fontsize_tests;
#[cfg(test)]
mod edgeless_toolbar_actions_tests;
#[cfg(test)]
mod edgeless_toolbar_bounds_tests;
#[cfg(test)]
mod edgeless_toolbar_interop_tests;
#[cfg(test)]
mod edgeless_toolbar_polish_tests;
#[cfg(test)]
mod edgeless_toolbar_tests;
mod element_toolbar;
mod element_toolbar_actions;
mod element_toolbar_color;
mod element_toolbar_media_actions;
mod gestures;
mod group_ops;
mod inline_edit;
@@ -31,8 +39,11 @@ pub(crate) mod paste_convert;
mod quick_connect;
mod remote_presence;
mod shape_picker;
mod ungroup_ops;
pub use blocksuite_editor::edgeless::*;
pub use element_toolbar_media_actions::DownloadedMedia;
pub(crate) use element_toolbar_media_actions::EdgelessHostRuntime;
pub(crate) use commands::find_surface_element;
use commands::{
@@ -3,7 +3,7 @@
//! drag connects to an existing hovered item or creates a cloned Shape at the drop point.
use blocksuite_playground_doc::{
read::{ColorValue, ShapeStyle, ShapeType, StrokeStyle, SurfaceElementKind},
read::{ColorValue, ConnectorMode, ShapeStyle, ShapeType, StrokeStyle, SurfaceElementKind},
schema::{ConnectorEndpointSpec, SurfaceElementSpec},
session::PageDocSession,
};
@@ -13,7 +13,7 @@ use y_octo::{AHashMap, Any, SessionValue};
use crate::PlaygroundView;
use super::{
QuickConnectDirection, WorldRect, cloned_shape_world_rect, find_surface_element,
QuickConnectDirection, WorldRect, cloned_shape_world_rect_avoiding, find_surface_element,
next_index_after, next_spatial_index,
};
@@ -47,6 +47,209 @@ fn stroke_style_wire(st: StrokeStyle) -> &'static str {
}
impl PlaygroundView {
/// Update quick-connect arrow hover state and schedule the deterministic `300ms` ghost preview wakeup.
pub(super) fn update_quick_connect_hover(
&mut self,
over_toolbar: bool,
position: ui::Point<ui::Pixels>,
vp_origin: ui::Point<ui::Pixels>,
cx: &mut Context<Self>,
) {
let next_qc_hover = if !over_toolbar
&& !self.is_edgeless_write_readonly()
&& self.edgeless.authoring.gesture.is_none()
&& self.edgeless.authoring.inline_edit.is_none()
&& self.edgeless.authoring.tool == super::EdgelessTool::Select
&& let Some(single) = self.edgeless.authoring.single_selected()
{
super::hit_test_auto_complete_arrow(single, position, vp_origin, self.edgeless.camera)
.map(|dir| (single.id.clone(), dir))
} else {
None
};
let qc_changed = match (&self.edgeless.authoring.quick_connect_hover, next_qc_hover) {
(Some(cur), Some((ref id, dir))) if cur.source_id == *id && cur.direction == dir => {
false
}
(_, Some((source_id, direction))) => {
let now_ms = self.now_ms(cx);
self.edgeless.authoring.last_frame_now_ms = now_ms;
self.edgeless.authoring.quick_connect_hover = Some(super::QuickConnectHoverState {
source_id: source_id.clone(),
direction,
hovered_since_ms: now_ms,
});
self.edgeless_runtime.quick_connect_hover_gen = self
.edgeless_runtime
.quick_connect_hover_gen
.wrapping_add(1);
let hover_gen = self.edgeless_runtime.quick_connect_hover_gen;
let delay =
std::time::Duration::from_millis(super::QUICK_CONNECT_GHOST_DELAY_MS as u64);
self.edgeless_runtime.quick_connect_hover_timer =
Some(cx.spawn(async move |this, cx| {
cx.background_executor().timer(delay).await;
let _ = this.update(cx, |view, cx| {
if view.edgeless_runtime.quick_connect_hover_gen == hover_gen
&& view
.edgeless
.authoring
.quick_connect_hover
.as_ref()
.is_some_and(|h| {
h.source_id == source_id && h.direction == direction
})
{
view.edgeless.authoring.last_frame_now_ms = view.now_ms(cx);
cx.notify();
}
});
}));
true
}
(Some(_), None) => {
self.edgeless_runtime.quick_connect_hover_gen = self
.edgeless_runtime
.quick_connect_hover_gen
.wrapping_add(1);
self.edgeless_runtime.quick_connect_hover_timer = None;
self.edgeless.authoring.quick_connect_hover = None;
true
}
(None, None) => false,
};
if qc_changed {
cx.notify();
}
}
pub(super) fn collect_drag_initials(&self) -> Vec<super::DragItemInitial> {
let Some(snapshot) = &self.snapshot else {
return Vec::new();
};
let ids = self.expand_selection_with_containers(&self.edgeless.authoring.selection);
let mut out = Vec::new();
for item in self.edgeless.authoring.painted_items.iter() {
if !ids.contains(&item.id) || item.locked {
continue;
}
let mut points = None;
let mut connector_source = None;
let mut connector_target = None;
let mut connector_label_xywh = None;
if let Some((_, el)) = find_surface_element(snapshot, &item.id) {
match &el.kind {
SurfaceElementKind::Brush(s) | SurfaceElementKind::Highlighter(s) => {
points = Some(
s.points
.iter()
.map(|p| {
if s.simulated_pressure {
vec![p[0], p[1]]
} else {
vec![p[0], p[1], p[2]]
}
})
.collect(),
);
}
SurfaceElementKind::Connector(c) => {
connector_source = Some((c.source.id.clone(), c.source.position));
connector_target = Some((c.target.id.clone(), c.target.position));
connector_label_xywh = c.label_xywh;
}
_ => {}
}
}
out.push(super::DragItemInitial {
id: item.id.clone(),
kind: item.kind,
surface_id: item.surface_id.clone(),
rect: item.rect,
rotate_deg: item.rotate_deg,
points,
connector_source,
connector_target,
connector_label_xywh,
});
}
out
}
/// Click a left/right `+` arrow on a selected Note: creates an adjacent Note at `MAIN_GAP`
/// in one atomic undo step and selects it.
pub fn edgeless_quick_connect_note_click(
&mut self,
source_id: &str,
direction: QuickConnectDirection,
cx: &mut Context<Self>,
) -> Option<String> {
if self.is_edgeless_write_readonly() {
return None;
}
let source_item = self
.edgeless
.authoring
.painted_items
.iter()
.find(|i| i.id == source_id && i.kind == super::SpatialItemKind::Note)?
.clone();
if source_item.locked {
return None;
}
let target_rect = cloned_shape_world_rect_avoiding(
source_item.rect,
direction,
source_id,
&self.edgeless.authoring.painted_items,
);
let snapshot = self.snapshot.clone()?;
let root_id = snapshot.root.as_ref()?.id.clone();
let next_idx = next_spatial_index(&snapshot).ok()?;
let cid = self.page()?.client_id();
let note_id = self.edgeless.authoring.next_id("note", cid);
let para_id = self.edgeless.authoring.next_id("para", cid);
let xywh = [
target_rect.x as f64,
target_rect.y as f64,
target_rect.w as f64,
target_rect.h as f64,
];
let note_id_clone = note_id.clone();
let now_ms = self.now_ms(cx) as u64;
let commit = self.page_mut().ok().and_then(|page| {
page.structural_edit(now_ms, move |page| {
page.add_block(
&note_id_clone,
blocksuite_playground_doc::schema::BlockSpec::Note {
xywh: Some(PageDocSession::format_xywh(xywh)),
},
Some(&root_id),
None,
now_ms,
)?;
page.set_block_index(&note_id_clone, &next_idx, now_ms)?;
page.add_block(
&para_id,
blocksuite_playground_doc::schema::BlockSpec::Paragraph {
text: String::new(),
paragraph_type: blocksuite_playground_doc::schema::ParagraphType::Text,
},
Some(&note_id_clone),
None,
now_ms,
)?;
Ok(())
})
.ok()
.flatten()
})?;
self.did_edgeless_doc_commit(commit, cx);
self.edgeless.authoring.selection.clear();
self.edgeless.authoring.selection.insert(note_id.clone());
Some(note_id)
}
/// Click an `auto-complete` arrow on `source_id` in `direction`:
/// clones the shape in that direction and attaches a Connector in one atomic undo step.
pub fn edgeless_quick_connect_click(
@@ -68,7 +271,12 @@ impl PlaygroundView {
if source_item.locked || source_item.in_mindmap {
return None;
}
let target_rect = cloned_shape_world_rect(source_item.rect, direction);
let target_rect = cloned_shape_world_rect_avoiding(
source_item.rect,
direction,
source_id,
&self.edgeless.authoring.painted_items,
);
self.edgeless_quick_connect_clone_at(
source_id,
source_item.surface_id.as_deref()?,
@@ -129,11 +337,9 @@ impl PlaygroundView {
let seed = ((cid as i32).wrapping_mul(29)
^ (self.edgeless.authoring.next_id_seq as i32 + 29).wrapping_mul(41))
| 1;
let mode = self.edgeless.authoring.connector_mode as i32;
let mode = ConnectorMode::Orthogonal as i32;
let sid = source_surface_id.to_string();
let src_id = source_id.to_string();
let src_port = direction.source_port();
let dst_port = target_port.unwrap_or(direction.target_port());
let conn_id_clone = conn_id.clone();
let now_ms = self.now_ms(cx) as u64;
let commit = self.page_mut().ok().and_then(|page| {
@@ -145,8 +351,8 @@ impl PlaygroundView {
SurfaceElementSpec::Connector {
mode,
seed,
source: ConnectorEndpointSpec::element(src_id.clone(), Some(src_port)),
target: ConnectorEndpointSpec::element(tid.clone(), Some(dst_port)),
source: ConnectorEndpointSpec::element(src_id.clone(), None),
target: ConnectorEndpointSpec::element(tid.clone(), target_port),
text: None,
label_xywh: None,
},
@@ -212,7 +418,8 @@ impl PlaygroundView {
^ (self.edgeless.authoring.next_id_seq as i32 + 19).wrapping_mul(31))
| 1;
let conn_seed = shape_seed.wrapping_add(7) | 1;
let mode = self.edgeless.authoring.connector_mode as i32;
let mode = ConnectorMode::Orthogonal as i32;
let _ = direction;
let sid = surface_id.to_string();
let src_id = source_id.to_string();
let new_shape_clone = new_shape_id.clone();
@@ -288,14 +495,8 @@ impl PlaygroundView {
SurfaceElementSpec::Connector {
mode,
seed: conn_seed,
source: ConnectorEndpointSpec::element(
src_id.clone(),
Some(direction.source_port()),
),
target: ConnectorEndpointSpec::element(
new_shape_clone.clone(),
Some(direction.target_port()),
),
source: ConnectorEndpointSpec::element(src_id.clone(), None),
target: ConnectorEndpointSpec::element(new_shape_clone.clone(), None),
text: None,
label_xywh: None,
},
@@ -153,7 +153,7 @@ impl PlaygroundView {
)
})
.flatten();
let element_toolbar = (toolbar_visible
let element_toolbar_built = (toolbar_visible
&& !self.edgeless.authoring.selection.is_empty()
&& self.form_factor != crate::block_flow::FormFactor::Phone)
.then(|| {
@@ -171,6 +171,13 @@ impl PlaygroundView {
)
})
.flatten();
let element_toolbar = if let Some((el, hitboxes)) = element_toolbar_built {
self.edgeless.authoring.toolbar_hitboxes = hitboxes;
Some(el)
} else {
self.edgeless.authoring.toolbar_hitboxes.clear();
None
};
let toolbar = toolbar_visible.then(|| {
let picker_state = self.edgeless_shape_picker_presence.and_then(|presence| {
let progress = presence.progress(now_ms);
@@ -0,0 +1,353 @@
//! Sequential rolling-cursor ungroup planning for Edgeless `Group` elements.
//!
//! Matches BlockSuite `ungroupCommand` semantics so ungrouping two or more adjacent (or nested)
//! groups in a single transaction produces strictly monotonic, collision-free fractional indices
//! that stay ordered before any following sibling.
use std::collections::{HashMap, HashSet};
use blocksuite_playground_doc::{
DocResult,
fractional_index::generate_n_keys_between,
read::{BlockContent, NoteDisplayMode, PageSnapshot, SurfaceElementKind},
session::PageDocSession,
};
use y_octo::{Any, SessionValue};
#[derive(Clone, Debug)]
pub(super) struct UngroupChildUpdate {
pub id: String,
pub is_block: bool,
pub surface_id: Option<String>,
pub new_index: Option<String>,
}
#[derive(Clone, Debug)]
pub(super) struct UngroupPlan {
pub group_surface_id: String,
pub group_id: String,
pub parent_group: Option<(String, String)>,
pub ordered_children: Vec<UngroupChildUpdate>,
}
#[derive(Clone)]
struct SpatialIndexEntry {
id: String,
index: String,
is_block: bool,
surface_id: Option<String>,
seq: usize,
}
fn build_ungroup_indexes(
count: usize,
before_index: Option<&str>,
after_index: Option<&str>,
fallback_anchor: &str,
) -> Vec<String> {
if count == 0 {
return Vec::new();
}
generate_n_keys_between(before_index, after_index, count)
.or_else(|_| generate_n_keys_between(before_index, None, count))
.or_else(|_| generate_n_keys_between(Some(fallback_anchor), None, count))
.or_else(|_| generate_n_keys_between(None, None, count))
.unwrap_or_default()
}
pub(super) fn collect_direct_parent_groups(
snapshot: &PageSnapshot,
) -> HashMap<String, (String, String)> {
let mut map = HashMap::new();
let Some(root) = snapshot.root.as_ref() else {
return map;
};
for node in root.walk() {
let BlockContent::Surface { elements, .. } = &node.content else {
continue;
};
for el in elements {
if let SurfaceElementKind::Group { children, .. } = &el.kind {
for cid in children {
map.insert(cid.clone(), (node.id.clone(), el.id.clone()));
}
}
}
}
map
}
fn group_ancestor_depth(id: &str, parent_of: &HashMap<String, (String, String)>) -> usize {
let mut depth = 0usize;
let mut cur = parent_of.get(id).map(|(_, g)| g.as_str());
while let Some(gid) = cur {
depth += 1;
if depth >= 16 {
break;
}
cur = parent_of
.get(gid)
.map(|(_, next)| next.as_str())
.filter(|next| *next != gid);
}
depth
}
/// Plan sequential ungroup operations for one or more `Group` elements in a single transaction,
/// advancing the rolling sibling cursor after each expansion so adjacent groups never collide
/// or overshoot subsequent siblings.
pub(super) fn plan_batch_ungroup_operations(
snapshot: &PageSnapshot,
group_ids: &[String],
direct_parent_group: &HashMap<String, (String, String)>,
) -> Vec<UngroupPlan> {
let Some(root) = snapshot.root.as_ref() else {
return Vec::new();
};
if group_ids.is_empty() {
return Vec::new();
}
let mut entries_by_id: HashMap<String, SpatialIndexEntry> = HashMap::new();
let mut all_entries: Vec<SpatialIndexEntry> = Vec::new();
let mut mindmap_members: HashSet<String> = HashSet::new();
let mut group_children_map: HashMap<String, Vec<String>> = HashMap::new();
let mut group_surface_map: HashMap<String, String> = HashMap::new();
let mut seq = 0usize;
let mut push_block = |node: &blocksuite_playground_doc::read::BlockNode| {
let idx = node
.props
.get("prop:index")
.and_then(|v| v.as_str())
.unwrap_or("a0")
.to_string();
let entry = SpatialIndexEntry {
id: node.id.clone(),
index: idx,
is_block: true,
surface_id: None,
seq,
};
seq += 1;
entries_by_id.insert(entry.id.clone(), entry.clone());
all_entries.push(entry);
};
for child in &root.children {
match &child.content {
BlockContent::Note { display_mode, .. }
if *display_mode != NoteDisplayMode::DocOnly =>
{
push_block(child);
}
BlockContent::Frame { .. } | BlockContent::EdgelessText { .. } => {
push_block(child);
}
BlockContent::Surface { .. } => {
for sc in &child.children {
match &sc.content {
BlockContent::Frame { .. }
| BlockContent::EdgelessText { .. }
| BlockContent::Image { .. }
| BlockContent::Attachment { .. }
| BlockContent::Bookmark { .. }
| BlockContent::EmbedLinkedDoc { .. }
| BlockContent::EmbedSyncedDoc { .. }
| BlockContent::ExternalEmbed { .. }
| BlockContent::SurfaceRef { .. }
| BlockContent::Latex { .. } => push_block(sc),
_ => {}
}
}
}
_ => {}
}
}
for child in &root.children {
if let BlockContent::Surface { elements, .. } = &child.content {
for el in elements {
if matches!(el.kind, SurfaceElementKind::Unknown { .. }) {
continue;
}
match &el.kind {
SurfaceElementKind::Mindmap(mm) => {
for nid in mm.nodes.keys() {
mindmap_members.insert(nid.clone());
}
}
SurfaceElementKind::Group { children, .. } => {
group_children_map.insert(el.id.clone(), children.clone());
group_surface_map.insert(el.id.clone(), child.id.clone());
}
_ => {}
}
let entry = SpatialIndexEntry {
id: el.id.clone(),
index: el.index.clone(),
is_block: false,
surface_id: Some(child.id.clone()),
seq,
};
seq += 1;
entries_by_id.insert(entry.id.clone(), entry.clone());
all_entries.push(entry);
}
}
}
let mut parent_of = direct_parent_group.clone();
let mut siblings_by_parent: HashMap<Option<String>, Vec<SpatialIndexEntry>> = HashMap::new();
let mut top_siblings: Vec<SpatialIndexEntry> = all_entries
.into_iter()
.filter(|e| !parent_of.contains_key(&e.id) && !mindmap_members.contains(&e.id))
.collect();
top_siblings.sort_by(|a, b| a.index.cmp(&b.index).then_with(|| a.seq.cmp(&b.seq)));
siblings_by_parent.insert(None, top_siblings);
for (gid, children) in &group_children_map {
let mut child_entries: Vec<SpatialIndexEntry> = children
.iter()
.filter_map(|cid| entries_by_id.get(cid).cloned())
.collect();
child_entries.sort_by(|a, b| a.index.cmp(&b.index).then_with(|| a.seq.cmp(&b.seq)));
siblings_by_parent.insert(Some(gid.clone()), child_entries);
}
let mut seen = HashSet::new();
let mut ordered_targets: Vec<String> = group_ids
.iter()
.filter(|id| group_surface_map.contains_key(*id) && seen.insert((*id).clone()))
.cloned()
.collect();
ordered_targets.sort_by(|a, b| {
let da = group_ancestor_depth(a, &parent_of);
let db = group_ancestor_depth(b, &parent_of);
let ea = entries_by_id.get(a);
let eb = entries_by_id.get(b);
da.cmp(&db)
.then_with(|| {
ea.map(|e| e.index.as_str())
.cmp(&eb.map(|e| e.index.as_str()))
})
.then_with(|| ea.map(|e| e.seq).cmp(&eb.map(|e| e.seq)))
});
let mut plans = Vec::with_capacity(ordered_targets.len());
for group_id in ordered_targets {
let Some(group_sid) = group_surface_map.get(&group_id).cloned() else {
continue;
};
let fallback_anchor = entries_by_id
.get(&group_id)
.map(|e| e.index.clone())
.unwrap_or_else(|| "a0".to_string());
let parent_group = parent_of.get(&group_id).cloned();
let parent_key = parent_group.as_ref().map(|(_, pgid)| pgid.clone());
let mut ordered_entries = siblings_by_parent
.remove(&Some(group_id.clone()))
.unwrap_or_default();
ordered_entries.sort_by(|a, b| a.index.cmp(&b.index).then_with(|| a.seq.cmp(&b.seq)));
let next_indexes = {
let siblings = siblings_by_parent.entry(parent_key.clone()).or_default();
let group_pos = siblings.iter().position(|s| s.id == group_id);
let before_index = group_pos
.and_then(|p| p.checked_sub(1))
.and_then(|i| siblings.get(i))
.map(|s| s.index.as_str());
let after_index = group_pos.and_then(|p| {
siblings[p + 1..]
.iter()
.find(|s| before_index.is_none_or(|b| s.index.as_str() > b))
.map(|s| s.index.as_str())
});
build_ungroup_indexes(
ordered_entries.len(),
before_index,
after_index,
&fallback_anchor,
)
};
let mut ordered_children = Vec::with_capacity(ordered_entries.len());
for (idx, entry) in ordered_entries.iter_mut().enumerate() {
let new_index = next_indexes
.get(idx)
.filter(|ni| ni.as_str() != entry.index.as_str())
.cloned();
if let Some(ni) = &new_index {
entry.index = ni.clone();
if let Some(stored) = entries_by_id.get_mut(&entry.id) {
stored.index = ni.clone();
}
}
if let Some(pg) = &parent_group {
parent_of.insert(entry.id.clone(), pg.clone());
} else {
parent_of.remove(&entry.id);
}
ordered_children.push(UngroupChildUpdate {
id: entry.id.clone(),
is_block: entry.is_block,
surface_id: entry.surface_id.clone(),
new_index,
});
}
parent_of.remove(&group_id);
if let Some(siblings) = siblings_by_parent.get_mut(&parent_key)
&& let Some(pos) = siblings.iter().position(|s| s.id == group_id)
{
siblings.splice(pos..=pos, ordered_entries);
}
plans.push(UngroupPlan {
group_surface_id: group_sid,
group_id,
parent_group,
ordered_children,
});
}
plans
}
pub(super) fn apply_ungroup_plan(
page: &mut PageDocSession,
plan: &UngroupPlan,
now_ms: u64,
) -> DocResult<()> {
let child_ids: Vec<String> = plan.ordered_children.iter().map(|c| c.id.clone()).collect();
if let Some((psid, pgid)) = &plan.parent_group {
page.update_group_children_delta(
psid,
pgid,
&child_ids,
std::slice::from_ref(&plan.group_id),
now_ms,
)?;
}
for child in &plan.ordered_children {
if let Some(new_idx) = &child.new_index {
if child.is_block {
page.set_block_prop(
&child.id,
"prop:index",
SessionValue::Any(Any::String(new_idx.clone())),
now_ms,
)?;
} else if let Some(csid) = &child.surface_id {
page.set_surface_element_field(
csid,
&child.id,
"index",
SessionValue::Any(Any::String(new_idx.clone())),
now_ms,
)?;
}
}
}
page.remove_surface_element(&plan.group_surface_id, &plan.group_id, now_ms)?;
Ok(())
}
@@ -586,23 +586,6 @@ impl PlaygroundView {
Ok(())
}
pub(crate) fn hit_test_flow_layout(layout: &FlowLayout, x: f32, y: f32) -> Option<DocPoint> {
// Vertical distance from `y` to a block, `0.0` inside its rows.
let gap = |b: &FlowBlock| {
let r = b.rect();
(r.y - y).max(y - r.bottom()).max(0.0)
};
let block = layout
.blocks
.iter()
.filter(|b| b.editable())
.min_by(|a, b| gap(a).total_cmp(&gap(b)))?;
Some(DocPoint {
block_id: block.block_id.clone(),
caret: block.hit_text(x, y)?,
})
}
pub(crate) fn editor_key_down(
&mut self,
e: &KeyDownEvent,
@@ -619,6 +602,14 @@ impl PlaygroundView {
cx.notify();
}
if self.mode == crate::PlaygroundMode::Edgeless {
// A caption edited on the canvas owns every key; unhandled ones arrive as text.
if self.caption_editor.is_some() {
if self.caption_editor_key_down(e, w, cx) {
w.prevent_default();
cx.stop_propagation();
}
return;
}
if self.edgeless_key_down(e, w, cx) {
w.prevent_default();
cx.stop_propagation();
@@ -778,10 +769,4 @@ impl PlaygroundView {
w.prevent_default();
cx.stop_propagation();
}
pub(crate) fn open_link_bar_from_toolbar(&mut self, w: &mut Window, cx: &mut Context<Self>) {
if self.mode == crate::PlaygroundMode::Page && self.page_readonly {
return;
}
self.open_link_bar_shortcut(w, cx);
}
}
@@ -358,6 +358,30 @@ impl PlaygroundView {
self.did_edit(commit, None, w, cx);
Ok(true)
}
pub(crate) fn hit_test_flow_layout(layout: &FlowLayout, x: f32, y: f32) -> Option<DocPoint> {
// Vertical distance from `y` to a block, `0.0` inside its rows.
let gap = |b: &FlowBlock| {
let r = b.rect();
(r.y - y).max(y - r.bottom()).max(0.0)
};
let block = layout
.blocks
.iter()
.filter(|b| b.editable())
.min_by(|a, b| gap(a).total_cmp(&gap(b)))?;
Some(DocPoint {
block_id: block.block_id.clone(),
caret: block.hit_text(x, y)?,
})
}
pub(crate) fn open_link_bar_from_toolbar(&mut self, w: &mut Window, cx: &mut Context<Self>) {
if self.mode == crate::PlaygroundMode::Page && self.page_readonly {
return;
}
self.open_link_bar_shortcut(w, cx);
}
}
#[cfg(test)]
@@ -76,6 +76,14 @@ impl ImageStore {
}
}
/// Remove one image slot by `source_id`, queueing any decoded [`RenderImage`] for GPU reclamation.
pub(crate) fn remove(&mut self, source_id: &str) {
self.access_gen.remove(source_id);
if let Some(ImageSlot::Ready(old)) = self.slots.remove(source_id) {
self.queue_retired(old);
}
}
/// Clear all slots on document switch and queue every decoded image for GPU reclamation.
pub(crate) fn clear(&mut self) {
let retired: Vec<Arc<RenderImage>> = self
+6 -61
View File
@@ -18,6 +18,7 @@ mod embed_preview_tests;
mod image_cache;
mod layout_cache;
mod media_picker;
mod options;
pub mod overlays;
mod page_scroll;
pub mod room_client;
@@ -37,6 +38,7 @@ mod wasm_preview;
#[cfg(not(target_arch = "wasm32"))]
pub use block_flow::ensure_native_preview_providers_installed;
pub use doc_panel::{DocPanelTab, DocStats, TocHeading, compute_doc_stats, extract_toc_headings};
pub use options::{PlaygroundMode, PlaygroundOptions};
pub use showcase::seed_showcase_doc;
pub use touch_selection::{
DocumentSelectionGeometry, SELECTION_ACTION_COPY, SELECTION_ACTION_CUT, SELECTION_ACTION_PASTE,
@@ -97,67 +99,6 @@ pub const SHOWCASE_PEER_NAME: &str = "Ada";
/// `sourceId` of the showcase image blob.
pub const SHOWCASE_IMAGE_ID: &str = "showcase-gradient";
/// Active view mode for the playground frame.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PlaygroundMode {
#[default]
Page,
Edgeless,
}
impl PlaygroundMode {
pub fn parse(value: &str) -> Option<Self> {
match value {
"page" => Some(Self::Page),
"edgeless" => Some(Self::Edgeless),
_ => None,
}
}
}
/// Initial configuration of a [`PlaygroundView`].
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PlaygroundOptions {
pub theme: PlaygroundTheme,
pub mode: PlaygroundMode,
/// Live room to join. Without one the view shows the built-in showcase document.
pub room: Option<RoomConfig>,
/// Primary pointer modality reported by the host platform.
pub pointer_kind: PointerKind,
/// Physical device form factor reported by the host platform.
pub form_factor: FormFactor,
/// When `true`, Page-mode text/block mutations are suppressed.
pub page_readonly: bool,
/// Defaults to `false`. When set to `true` (e.g. on touch hosts or via `?mobile=1`,
/// `?edgeless_readonly=1`, or `--edgeless-readonly`), Edgeless mode hides the creation
/// toolbar, disables element authoring/mutation, and pans smoothly on single-finger drags.
pub edgeless_readonly: bool,
/// When `true`, Database-block mutations are suppressed.
pub database_readonly: bool,
/// When `true`, the native host provides system selection handles, magnifier, and edit menu,
/// so the GPU editor never opens its fallback `touch_selection_menu`.
pub native_selection_ui: bool,
/// When `true` (iOS `UITextInteraction`), UIKit renders the authoritative cursor and selection
/// highlight views, so GPU suppresses local caret and selection highlight painting.
pub native_suppresses_gpu_caret_and_selection: bool,
}
impl PlaygroundOptions {
/// Builds Stage-1 options for a native touch host (`Phone` or `Tablet`):
/// Page editing enabled, Edgeless and Database read-only.
pub fn for_form_factor(form_factor: FormFactor) -> Self {
let caps = EditorCapabilities::for_form_factor(form_factor);
Self {
pointer_kind: caps.pointer_kind,
form_factor: caps.form_factor,
page_readonly: caps.page_readonly,
edgeless_readonly: caps.edgeless_readonly,
database_readonly: caps.database_readonly,
..Self::default()
}
}
}
pub(crate) const PILL_WIDTH: f32 = 186.0;
pub(crate) const PILL_PAGE_X: f64 = 4.0;
pub(crate) const PILL_EDGELESS_X: f64 = 94.0;
@@ -195,6 +136,8 @@ pub(crate) struct ImageResizeDrag {
pub(crate) use touch_interaction::{ModalTouchTarget, PopoverFlingTarget, TouchStrokeOwner};
pub use edgeless::DownloadedMedia;
/// Interactive GPUI root view for desktop, Web canvas, and headless verification sessions.
pub struct PlaygroundView {
pub(crate) mode: PlaygroundMode,
@@ -313,6 +256,7 @@ pub struct PlaygroundView {
pub(crate) copied_timer: Option<Task<()>>,
/// One-shot 800 ms timer that wakes the view to render the Slash hover/selection preview card.
pub(crate) slash_preview_timer: Option<Task<()>>,
pub(crate) edgeless_runtime: edgeless::EdgelessHostRuntime,
/// Active TOC Outline / DocInfo side panel tab, when open.
pub(crate) doc_panel_tab: Option<DocPanelTab>,
/// Vertical scroll offset for the TOC Outline heading list.
@@ -479,6 +423,7 @@ impl PlaygroundView {
image_resize_drag: None,
copied_timer: None,
slash_preview_timer: None,
edgeless_runtime: Default::default(),
_tasks: tasks,
};
view.flow.database_state.mobile_readonly = view.database_readonly;
@@ -0,0 +1,64 @@
//! View mode and initial configuration of a [`PlaygroundView`](crate::PlaygroundView).
use crate::{EditorCapabilities, FormFactor, PlaygroundTheme, PointerKind, RoomConfig};
/// Active view mode for the playground frame.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PlaygroundMode {
#[default]
Page,
Edgeless,
}
impl PlaygroundMode {
pub fn parse(value: &str) -> Option<Self> {
match value {
"page" => Some(Self::Page),
"edgeless" => Some(Self::Edgeless),
_ => None,
}
}
}
/// Initial configuration of a [`PlaygroundView`](crate::PlaygroundView).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PlaygroundOptions {
pub theme: PlaygroundTheme,
pub mode: PlaygroundMode,
/// Live room to join. Without one the view shows the built-in showcase document.
pub room: Option<RoomConfig>,
/// Primary pointer modality reported by the host platform.
pub pointer_kind: PointerKind,
/// Physical device form factor reported by the host platform.
pub form_factor: FormFactor,
/// When `true`, Page-mode text/block mutations are suppressed.
pub page_readonly: bool,
/// Defaults to `false`. When set to `true` (e.g. on touch hosts or via `?mobile=1`,
/// `?edgeless_readonly=1`, or `--edgeless-readonly`), Edgeless mode hides the creation
/// toolbar, disables element authoring/mutation, and pans smoothly on single-finger drags.
pub edgeless_readonly: bool,
/// When `true`, Database-block mutations are suppressed.
pub database_readonly: bool,
/// When `true`, the native host provides system selection handles, magnifier, and edit menu,
/// so the GPU editor never opens its fallback `touch_selection_menu`.
pub native_selection_ui: bool,
/// When `true` (iOS `UITextInteraction`), UIKit renders the authoritative cursor and selection
/// highlight views, so GPU suppresses local caret and selection highlight painting.
pub native_suppresses_gpu_caret_and_selection: bool,
}
impl PlaygroundOptions {
/// Builds Stage-1 options for a native touch host (`Phone` or `Tablet`):
/// Page editing enabled, Edgeless and Database read-only.
pub fn for_form_factor(form_factor: FormFactor) -> Self {
let caps = EditorCapabilities::for_form_factor(form_factor);
Self {
pointer_kind: caps.pointer_kind,
form_factor: caps.form_factor,
page_readonly: caps.page_readonly,
edgeless_readonly: caps.edgeless_readonly,
database_readonly: caps.database_readonly,
..Self::default()
}
}
}
@@ -3,6 +3,7 @@
mod view;
mod view_callout_bar;
mod view_caption;
mod view_caption_paint;
mod view_context_menu;
mod view_edits;
mod view_embed_controls;
@@ -1,10 +1,10 @@
//! In-place live `prop:caption` editing glue for all captioned blocks on [`PlaygroundView`].
use std::{ops::Range, rc::Rc};
use std::rc::Rc;
use blocksuite_editor::{
block_flow::{CaptionDraft, FlowLayout, FlowRect, PAGE_SURFACE_ID, PageViewport},
edgeless::{NOTE_CARD_PADDING, SpatialItemKind},
block_flow::{CaptionDraft, FlowLayout},
edgeless::{NOTE_CARD_PADDING, SpatialItemKind, canvas_caption_shift},
inline_input::{TextSplice, utf16_len, utf16_to_byte},
overlays::{
InlineCaptionEditor, OverlayScreenTransform, TableCellDragMode, block_caption_text,
@@ -13,15 +13,14 @@ use blocksuite_editor::{
};
use blocksuite_playground_doc::schema::{BlockSpec, ParagraphType};
use ui::{
AnyElement, Bounds, ClipboardItem, Context, KeyDownEvent, MouseButton, MouseMoveEvent, Pixels,
Point, Window, div, point, prelude::*, px, size,
ClipboardItem, Context, KeyDownEvent, MouseButton, MouseMoveEvent, Pixels, Point, Window,
point, px,
};
use crate::{
PlaygroundMode, PlaygroundView, TOPBAR_HEIGHT,
editor_session::{DocPoint, DocumentSelection},
overlays::InlineTargetEnd,
theme::Palette,
};
/// Normalize pasted text for single-line captions by replacing `\r\n`, `\r`, and `\n` with spaces.
@@ -47,7 +46,7 @@ impl PlaygroundView {
/// Resolve the containing `FlowLayout` and screen-space affine transform for `block_id`'s
/// caption slot in either Page mode or Edgeless mode (accounting for Note scale, rotation,
/// and camera pan/zoom).
fn caption_slot_screen_transform(
pub(super) fn caption_slot_screen_transform(
&self,
block_id: &str,
w: &Window,
@@ -70,15 +69,29 @@ impl PlaygroundView {
PlaygroundMode::Edgeless => {
let topbar = point(px(0.0), px(TOPBAR_HEIGHT));
for item in self.edgeless.authoring.painted_items.iter().rev() {
if !matches!(
item.kind,
SpatialItemKind::Note | SpatialItemKind::EdgelessText
) {
continue;
}
let is_note = item.kind == SpatialItemKind::Note;
let Some(layout) = self.edgeless.cached_block_layout(&item.id, is_note) else {
continue;
// `pad` insets a Note's flow; `dy` moves a canvas block's caption below its frame.
let (layout, pad, dy) = match item.kind {
SpatialItemKind::Note | SpatialItemKind::EdgelessText => {
let is_note = item.kind == SpatialItemKind::Note;
let Some(layout) = self.edgeless.cached_block_layout(&item.id, is_note)
else {
continue;
};
(layout, if is_note { NOTE_CARD_PADDING } else { 0.0 }, 0.0)
}
SpatialItemKind::SurfaceBlock if item.id == block_id => {
let Some(layout) = self.edgeless.cached_surface_block_layout(block_id)
else {
return None;
};
let dy = canvas_caption_shift(
layout.block(block_id)?,
item.rect.h,
item.scale,
)?;
(layout, 0.0, dy)
}
_ => continue,
};
if layout
.block(block_id)
@@ -87,11 +100,10 @@ impl PlaygroundView {
{
continue;
}
let pad = if is_note { NOTE_CARD_PADDING } else { 0.0 };
let origin_screen = self.edgeless.camera.world_to_screen(
point(
px(item.rect.x + pad * item.scale),
px(item.rect.y + pad * item.scale),
px(item.rect.y + (pad + dy) * item.scale),
),
topbar,
);
@@ -115,7 +127,7 @@ impl PlaygroundView {
}
}
fn hit_caption_screen_point(
pub(super) fn hit_caption_screen_point(
&self,
block_id: &str,
sx: f32,
@@ -630,160 +642,4 @@ impl PlaygroundView {
w,
)
}
/// Screen-space bounds for a UTF-16 range inside the focused caption slot (IME / selection).
pub(crate) fn caption_selection_bounds(
&self,
r: Range<usize>,
w: &Window,
) -> Vec<Bounds<Pixels>> {
let Some(ed) = self.caption_editor.as_ref() else {
return Vec::new();
};
let Some((layout, transform)) = self.caption_slot_screen_transform(&ed.block_id, w) else {
return Vec::new();
};
let Some(block) = layout.block(&ed.block_id) else {
return Vec::new();
};
let Some(slot) = block.body.caption_slot.as_ref() else {
return Vec::new();
};
let origin_x = block.x + slot.text_origin.0;
let origin_y = block.y + slot.text_origin.1;
let lh = slot.layout.line_height.max(22.0);
let to_bounds = |local: FlowRect| {
let s = transform.rect_to_screen(&local);
Bounds::new(point(px(s.x), px(s.y)), size(px(s.w), px(s.h)))
};
if slot.is_placeholder || r.start == r.end {
let (cx, line) = if slot.is_placeholder {
slot.layout.caret(0)
} else {
slot.layout.caret(r.start)
};
return vec![to_bounds(FlowRect::new(
origin_x + cx,
origin_y + line as f32 * lh,
1.5,
lh,
))];
}
slot.layout
.selection_spans(r.start, r.end)
.into_iter()
.map(|(line, x0, x1)| {
to_bounds(FlowRect::new(
origin_x + x0,
origin_y + line as f32 * lh,
(x1 - x0).max(1.0),
lh,
))
})
.collect()
}
/// Paint the focused caption slot's selection highlight, IME preedit underline, and blinking caret.
pub(crate) fn caption_selection_elements(
&self,
layout: &FlowLayout,
viewport: PageViewport,
palette: &Palette,
caret_alpha: f32,
) -> Vec<AnyElement> {
let Some(ed) = self.caption_editor.as_ref() else {
return Vec::new();
};
let Some(block) = layout.block(&ed.block_id) else {
return Vec::new();
};
let Some(slot) = block.body.caption_slot.as_ref() else {
return Vec::new();
};
let mut out = Vec::new();
let slot_world = slot.rect.translated(block.x, block.y);
if !viewport.intersects(&slot_world) {
return out;
}
let placed = |r: &FlowRect| {
let loc = viewport.to_local(r);
div()
.absolute()
.left(px(loc.x))
.top(px(loc.y))
.w(px(loc.w))
.h(px(loc.h))
};
out.push(
placed(&slot_world)
.snapshot("page.caption_focus", Some(PAGE_SURFACE_ID))
.snapshot_focused(true)
.snapshot_text(ed.input.display_text())
.into_any_element(),
);
let (sel, _) = ed.input.shown_selection();
let lh = slot.layout.line_height.max(22.0);
let text_world_x = block.x + slot.text_origin.0;
let text_world_y = block.y + slot.text_origin.1;
if !slot.is_placeholder && sel.start < sel.end {
for (line, x0, x1) in slot.layout.selection_spans(sel.start, sel.end) {
let r = FlowRect::new(
text_world_x + x0,
text_world_y + line as f32 * lh,
(x1 - x0).max(1.0),
lh,
);
if viewport.intersects(&r) {
out.push(
placed(&r)
.bg(palette.brand.opacity(0.22))
.into_any_element(),
);
}
}
}
if let Some(marked) = ed.input.marked_range()
&& !slot.is_placeholder
{
for (line, x0, x1) in slot.layout.selection_spans(marked.start, marked.end) {
let r = FlowRect::new(
text_world_x + x0,
text_world_y + (line + 1) as f32 * lh - 2.0,
(x1 - x0).max(1.0),
1.5,
);
if viewport.intersects(&r) {
out.push(placed(&r).bg(palette.brand).into_any_element());
}
}
}
if sel.start == sel.end && caret_alpha > 0.01 {
let (cx, line) = if slot.is_placeholder {
slot.layout.caret(0)
} else {
slot.layout.caret(sel.end)
};
let caret_h = 16.0_f32.min(lh);
let caret_world = FlowRect::new(
text_world_x + cx,
text_world_y + line as f32 * lh + (lh - caret_h) * 0.5,
1.5,
caret_h,
);
if viewport.intersects(&caret_world) {
out.push(
placed(&caret_world)
.bg(palette.brand.opacity(caret_alpha))
.snapshot("page.caption_caret", Some(PAGE_SURFACE_ID))
.into_any_element(),
);
}
}
out
}
}
@@ -0,0 +1,290 @@
//! Caret, selection, and IME geometry of the in-place caption editor: Page-mode elements in the
//! page layer, and screen-space elements plus pointer presses for canvas captions in Edgeless.
use std::ops::Range;
use blocksuite_editor::{
block_flow::{FlowLayout, FlowRect, PAGE_SURFACE_ID, PageViewport},
edgeless::SpatialItemKind,
};
use ui::{
AnyElement, Bounds, Context, MouseDownEvent, Pixels, Window, div, point, prelude::*, px, size,
};
use crate::{PlaygroundView, TOPBAR_HEIGHT, theme::Palette};
impl PlaygroundView {
/// Screen-space bounds for a UTF-16 range inside the focused caption slot (IME / selection).
pub(crate) fn caption_selection_bounds(
&self,
r: Range<usize>,
w: &Window,
) -> Vec<Bounds<Pixels>> {
let Some(ed) = self.caption_editor.as_ref() else {
return Vec::new();
};
let Some((layout, transform)) = self.caption_slot_screen_transform(&ed.block_id, w) else {
return Vec::new();
};
let Some(block) = layout.block(&ed.block_id) else {
return Vec::new();
};
let Some(slot) = block.body.caption_slot.as_ref() else {
return Vec::new();
};
let origin_x = block.x + slot.text_origin.0;
let origin_y = block.y + slot.text_origin.1;
let lh = slot.layout.line_height.max(22.0);
let to_bounds = |local: FlowRect| {
let s = transform.rect_to_screen(&local);
Bounds::new(point(px(s.x), px(s.y)), size(px(s.w), px(s.h)))
};
if slot.is_placeholder || r.start == r.end {
let (cx, line) = if slot.is_placeholder {
slot.layout.caret(0)
} else {
slot.layout.caret(r.start)
};
return vec![to_bounds(FlowRect::new(
origin_x + cx,
origin_y + line as f32 * lh,
1.5,
lh,
))];
}
slot.layout
.selection_spans(r.start, r.end)
.into_iter()
.map(|(line, x0, x1)| {
to_bounds(FlowRect::new(
origin_x + x0,
origin_y + line as f32 * lh,
(x1 - x0).max(1.0),
lh,
))
})
.collect()
}
/// Paint the focused caption slot's selection highlight, IME preedit underline, and blinking caret.
pub(crate) fn caption_selection_elements(
&self,
layout: &FlowLayout,
viewport: PageViewport,
palette: &Palette,
caret_alpha: f32,
) -> Vec<AnyElement> {
let Some(ed) = self.caption_editor.as_ref() else {
return Vec::new();
};
let Some(block) = layout.block(&ed.block_id) else {
return Vec::new();
};
let Some(slot) = block.body.caption_slot.as_ref() else {
return Vec::new();
};
let mut out = Vec::new();
let slot_world = slot.rect.translated(block.x, block.y);
if !viewport.intersects(&slot_world) {
return out;
}
let placed = |r: &FlowRect| {
let loc = viewport.to_local(r);
div()
.absolute()
.left(px(loc.x))
.top(px(loc.y))
.w(px(loc.w))
.h(px(loc.h))
};
out.push(
placed(&slot_world)
.snapshot("page.caption_focus", Some(PAGE_SURFACE_ID))
.snapshot_focused(true)
.snapshot_text(ed.input.display_text())
.into_any_element(),
);
let (sel, _) = ed.input.shown_selection();
let lh = slot.layout.line_height.max(22.0);
let text_world_x = block.x + slot.text_origin.0;
let text_world_y = block.y + slot.text_origin.1;
if !slot.is_placeholder && sel.start < sel.end {
for (line, x0, x1) in slot.layout.selection_spans(sel.start, sel.end) {
let r = FlowRect::new(
text_world_x + x0,
text_world_y + line as f32 * lh,
(x1 - x0).max(1.0),
lh,
);
if viewport.intersects(&r) {
out.push(
placed(&r)
.bg(palette.brand.opacity(0.22))
.into_any_element(),
);
}
}
}
if let Some(marked) = ed.input.marked_range()
&& !slot.is_placeholder
{
for (line, x0, x1) in slot.layout.selection_spans(marked.start, marked.end) {
let r = FlowRect::new(
text_world_x + x0,
text_world_y + (line + 1) as f32 * lh - 2.0,
(x1 - x0).max(1.0),
1.5,
);
if viewport.intersects(&r) {
out.push(placed(&r).bg(palette.brand).into_any_element());
}
}
}
if sel.start == sel.end && caret_alpha > 0.01 {
let (cx, line) = if slot.is_placeholder {
slot.layout.caret(0)
} else {
slot.layout.caret(sel.end)
};
let caret_h = 16.0_f32.min(lh);
let caret_world = FlowRect::new(
text_world_x + cx,
text_world_y + line as f32 * lh + (lh - caret_h) * 0.5,
1.5,
caret_h,
);
if viewport.intersects(&caret_world) {
out.push(
placed(&caret_world)
.bg(palette.brand.opacity(caret_alpha))
.snapshot("page.caption_caret", Some(PAGE_SURFACE_ID))
.into_any_element(),
);
}
}
out
}
/// Screen-space focus box, selection highlight, and blinking caret of a caption edited on
/// the Edgeless canvas, placed in the canvas layer whose origin is below the top bar.
pub(crate) fn edgeless_caption_elements(
&self,
window: &Window,
palette: &Palette,
caret_alpha: f32,
) -> Vec<AnyElement> {
let Some(ed) = self.caption_editor.as_ref() else {
return Vec::new();
};
let Some((layout, transform)) = self.caption_slot_screen_transform(&ed.block_id, window)
else {
return Vec::new();
};
let Some(block) = layout.block(&ed.block_id) else {
return Vec::new();
};
let Some(slot) = block.body.caption_slot.as_ref() else {
return Vec::new();
};
let placed = |r: Bounds<Pixels>| {
div()
.absolute()
.left(r.origin.x)
.top(r.origin.y - px(TOPBAR_HEIGHT))
.w(r.size.width)
.h(r.size.height)
};
let slot_rect = transform.rect_to_screen(&slot.rect.translated(block.x, block.y));
let mut out = vec![
placed(Bounds::new(
point(px(slot_rect.x), px(slot_rect.y)),
size(px(slot_rect.w), px(slot_rect.h)),
))
.snapshot(
"edgeless.caption_focus",
Some(blocksuite_editor::edgeless::EDGELESS_VIEWPORT_ID),
)
.snapshot_focused(true)
.snapshot_text(ed.input.display_text())
.into_any_element(),
];
let (sel, _) = ed.input.shown_selection();
let collapsed = sel.start == sel.end;
for r in self.caption_selection_bounds(sel, window) {
if collapsed {
if caret_alpha > 0.01 {
out.push(
placed(r)
.bg(palette.brand.opacity(caret_alpha))
.snapshot(
"edgeless.caption_caret",
Some(blocksuite_editor::edgeless::EDGELESS_VIEWPORT_ID),
)
.into_any_element(),
);
}
} else {
out.push(placed(r).bg(palette.brand.opacity(0.22)).into_any_element());
}
}
out
}
/// Route a primary press on the Edgeless canvas to a canvas block's caption slot: a press
/// on a shown caption places the caret there, and any other press first closes an open
/// caption editor. Returns `true` when the press belonged to a caption.
pub(crate) fn edgeless_caption_mouse_down(
&mut self,
event: &MouseDownEvent,
window: &mut Window,
cx: &mut Context<Self>,
) -> bool {
let (sx, sy) = (f32::from(event.position.x), f32::from(event.position.y));
let hit = self
.edgeless
.authoring
.painted_items
.iter()
.rev()
.filter(|item| item.kind == SpatialItemKind::SurfaceBlock && !item.locked)
.find(|item| self.caption_slot_contains(&item.id, sx, sy, window))
.map(|item| item.id.clone());
match hit {
Some(block_id) if !self.edgeless_readonly => {
self.focus_caption(
block_id,
Some((sx, sy)),
event.click_count,
event.modifiers.shift,
window,
cx,
);
true
}
_ => {
if self.finish_caption_editor(super::InlineTargetEnd::CommitPreedit, Some(cx)) {
cx.notify();
}
false
}
}
}
fn caption_slot_contains(&self, block_id: &str, sx: f32, sy: f32, window: &Window) -> bool {
let Some((layout, transform)) = self.caption_slot_screen_transform(block_id, window) else {
return false;
};
let (lx, ly) = transform.screen_to_local(sx, sy);
layout.block(block_id).is_some_and(|block| {
block.body.caption_slot.as_ref().is_some_and(|slot| {
let r = slot.rect.translated(block.x, block.y);
lx >= r.x && lx <= r.right() && ly >= r.y && ly <= r.bottom()
})
})
}
}