mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-05 11:15:01 +03:00
perf(edgeless): reuse the note header index across frames
The Edgeless note header pass walked the root tree on each frame. It rebuilt two maps, copied the page title and formatted element ids. - Keep a NoteHeaderIndexCache in EdgelessCanvasState. The document epoch, the page id, the document revision and the snapshot allocation key the index. A frame without header candidates returns at once. - Collect the Frame title pills only for an expanded Page Note header. - Use static element id prefixes with a stable FNV-1a hash of the block id. - Format snapshot ids with format_args at each snapshot call. Release builds then keep no snapshot id text. Remove the SNAPSHOT_IDS cfg! constant. - Split chrome/note_header.rs into mod.rs and paint.rs. The fold reads the note lock and the lock of each parent Group from the current snapshot when it writes. A lock change after the last paint now applies. A visited set stops the walk on a Group cycle. check-invariants.sh now also rejects cfg! macros and multi-line cfg predicates that name the harness feature or test.
This commit is contained in:
1 parent
8402e3345f
commit
73c4150dc4
6 files changed
+1236
-797
No files matched your search
@@ -2,7 +2,7 @@
|
||||
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet, HashMap},
|
||||
rc::Rc,
|
||||
rc::{Rc, Weak},
|
||||
};
|
||||
|
||||
use blocksuite_playground_doc::read::{BlockContent, BlockNode, NoteDisplayMode, PageSnapshot};
|
||||
@@ -128,6 +128,88 @@ pub struct EdgelessCanvasState {
|
||||
note_database_rev: Option<(String, u64)>,
|
||||
/// Number of block bodies laid out during the most recent Edgeless frame.
|
||||
pub last_frame_relayouts: u64,
|
||||
/// Notes and synced-doc embeds that can carry a header, indexed per page snapshot.
|
||||
pub note_headers: NoteHeaderIndexCache,
|
||||
}
|
||||
|
||||
/// A root Note that can carry a header: its position in `root.children` and its id hash.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct NoteHeaderEntry {
|
||||
pub child_index: usize,
|
||||
pub id_hash: u64,
|
||||
}
|
||||
|
||||
/// A surface `embed-synced-doc` block: the page it shows and its id hash.
|
||||
pub struct EmbedHeaderEntry {
|
||||
pub target_page_id: String,
|
||||
pub id_hash: u64,
|
||||
}
|
||||
|
||||
/// Header index of one page snapshot. `sync` rebuilds it only when the document epoch, the
|
||||
/// page, the document revision, or the snapshot allocation changes. The held `Weak` keeps the
|
||||
/// allocation alive, so a later snapshot can never reuse the address of the indexed one.
|
||||
#[derive(Default)]
|
||||
pub struct NoteHeaderIndexCache {
|
||||
source: Option<(u64, String, u64, Weak<PageSnapshot>)>,
|
||||
notes: HashMap<String, NoteHeaderEntry>,
|
||||
surface_embeds: HashMap<String, EmbedHeaderEntry>,
|
||||
}
|
||||
|
||||
impl NoteHeaderIndexCache {
|
||||
pub fn sync(&mut self, doc_epoch: u64, page_id: &str, doc_rev: u64, snap: &Rc<PageSnapshot>) {
|
||||
if let Some((epoch, page, rev, weak)) = &self.source
|
||||
&& (*epoch, page.as_str(), *rev) == (doc_epoch, page_id, doc_rev)
|
||||
&& std::ptr::eq(weak.as_ptr(), Rc::as_ptr(snap))
|
||||
{
|
||||
return;
|
||||
}
|
||||
self.notes.clear();
|
||||
self.surface_embeds.clear();
|
||||
for (child_index, node) in snap.root.iter().flat_map(|r| r.children.iter().enumerate()) {
|
||||
match &node.content {
|
||||
BlockContent::Note { .. } => {
|
||||
let id_hash = fnv1a_64(&node.id);
|
||||
let entry = NoteHeaderEntry {
|
||||
child_index,
|
||||
id_hash,
|
||||
};
|
||||
self.notes.insert(node.id.clone(), entry);
|
||||
}
|
||||
BlockContent::Surface { .. } => {
|
||||
for child in &node.children {
|
||||
if let BlockContent::EmbedSyncedDoc { page_id, .. } = &child.content {
|
||||
let entry = EmbedHeaderEntry {
|
||||
target_page_id: page_id.clone(),
|
||||
id_hash: fnv1a_64(&child.id),
|
||||
};
|
||||
self.surface_embeds.insert(child.id.clone(), entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
self.source = Some((doc_epoch, page_id.to_owned(), doc_rev, Rc::downgrade(snap)));
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.notes.is_empty() && self.surface_embeds.is_empty()
|
||||
}
|
||||
|
||||
pub fn note(&self, id: &str) -> Option<NoteHeaderEntry> {
|
||||
self.notes.get(id).copied()
|
||||
}
|
||||
|
||||
pub fn surface_embed(&self, id: &str) -> Option<&EmbedHeaderEntry> {
|
||||
self.surface_embeds.get(id)
|
||||
}
|
||||
}
|
||||
|
||||
/// 64-bit FNV-1a hash, stable across runs and targets.
|
||||
fn fnv1a_64(s: &str) -> u64 {
|
||||
s.bytes().fold(0xcbf2_9ce4_8422_2325, |h, b| {
|
||||
(h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn is_spatial_surface_block(node: &BlockNode) -> bool {
|
||||
@@ -819,4 +901,67 @@ mod tests {
|
||||
assert_eq!(bounds.right(), 760.0);
|
||||
assert_eq!(bounds.bottom(), 440.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn note_header_index_rebuilds_only_for_a_new_epoch_page_revision_or_snapshot() {
|
||||
let snap_with = |note_id: &str| {
|
||||
let note = BlockNode {
|
||||
id: note_id.into(),
|
||||
flavour: "affine:note".into(),
|
||||
version: Some(1),
|
||||
props: BTreeMap::new(),
|
||||
content: BlockContent::Note {
|
||||
display_mode: NoteDisplayMode::Both,
|
||||
xywh: "[0,0,100,100]".into(),
|
||||
background: JsonValue::Null,
|
||||
hidden: false,
|
||||
},
|
||||
children: Vec::new(),
|
||||
};
|
||||
Rc::new(PageSnapshot {
|
||||
doc_id: "doc".into(),
|
||||
root: Some(BlockNode {
|
||||
id: "root".into(),
|
||||
flavour: "affine:page".into(),
|
||||
version: Some(2),
|
||||
props: BTreeMap::new(),
|
||||
content: BlockContent::Page {
|
||||
title: blocksuite_playground_doc::read::RichText::default(),
|
||||
},
|
||||
children: vec![note],
|
||||
}),
|
||||
detached: Vec::new(),
|
||||
})
|
||||
};
|
||||
let first = snap_with("a");
|
||||
let other = snap_with("b");
|
||||
// (epoch, page, revision, snapshot, indexed note, index kept)
|
||||
let steps: [(u64, &str, u64, &Rc<PageSnapshot>, &str, bool); 6] = [
|
||||
(0, "p", 1, &first, "a", false),
|
||||
(0, "p", 1, &first, "a", true),
|
||||
// Another allocation under the same epoch, page, and revision rebuilds it.
|
||||
(0, "p", 1, &other, "b", false),
|
||||
(1, "p", 1, &other, "b", false),
|
||||
(1, "q", 1, &other, "b", false),
|
||||
(1, "q", 2, &other, "b", false),
|
||||
];
|
||||
let mut cache = NoteHeaderIndexCache::default();
|
||||
let marker = NoteHeaderEntry {
|
||||
child_index: usize::MAX,
|
||||
id_hash: 0,
|
||||
};
|
||||
for (step, (epoch, page, rev, snap, note, kept)) in steps.into_iter().enumerate() {
|
||||
cache.notes.insert("marker".into(), marker);
|
||||
cache.sync(epoch, page, rev, snap);
|
||||
assert_eq!(cache.note("marker").is_some(), kept, "step {step}");
|
||||
let entry = cache
|
||||
.note(note)
|
||||
.unwrap_or_else(|| panic!("step {step}: {note}"));
|
||||
assert_eq!(entry.child_index, 0, "step {step}");
|
||||
assert_eq!(entry.id_hash, fnv1a_64(note), "step {step}");
|
||||
assert!(cache.surface_embed(note).is_none(), "step {step}");
|
||||
}
|
||||
assert_eq!(fnv1a_64(""), 0xcbf2_9ce4_8422_2325);
|
||||
assert_eq!(fnv1a_64("a"), 0xaf63_dc4c_8601_ec8c);
|
||||
}
|
||||
}
|
||||
@@ -1,771 +0,0 @@
|
||||
//! Edgeless `EdgelessNoteHeader`, Active Note `20px` halo shadow, bottom `MoreIndicator`
|
||||
//! fold/unfold control, and canvas `EmbedSyncedDoc` card top header bar.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use blocksuite_playground_doc::read::{BlockContent, BlockNode};
|
||||
use ui::{
|
||||
AnyElement, BorderStyle, Bounds, Context, Corners, Edges, ElementId, FontWeight, Hsla,
|
||||
MouseButton, PathBuilder, Pixels, SharedString, Window, canvas, div, point, prelude::*, px,
|
||||
size,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
DocPanelTab, PlaygroundTheme, PlaygroundView,
|
||||
edgeless::{
|
||||
self, EDGELESS_VIEWPORT_ID, NOTE_CARD_PADDING, SpatialItemInfo, SpatialItemKind, WorldRect,
|
||||
},
|
||||
theme::{IconPaint, Palette},
|
||||
};
|
||||
|
||||
const SNAPSHOT_IDS: bool = cfg!(any(test, feature = "harness"));
|
||||
|
||||
const HEADER_HEIGHT: f32 = 26.0;
|
||||
const HEADER_GAP: f32 = 4.0;
|
||||
const HEADER_BTN_SIZE: f32 = 24.0;
|
||||
const PAGE_HEADER_BUTTON: f32 = 32.0;
|
||||
const MORE_BTN_SIZE: f32 = 28.0;
|
||||
const FADE_MASK_HEIGHT: f32 = 34.0;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct ActiveNoteFrameStyle {
|
||||
bounds: Bounds<Pixels>,
|
||||
card_r: f32,
|
||||
extra: f32,
|
||||
dark: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct NoteScreenGeometry {
|
||||
sx: f32,
|
||||
sy: f32,
|
||||
sw: f32,
|
||||
sh: f32,
|
||||
scale: f32,
|
||||
zoom: f32,
|
||||
world_h: f32,
|
||||
radius: f32,
|
||||
}
|
||||
|
||||
struct HeaderBarSpec<'a> {
|
||||
id: SharedString,
|
||||
block_id: &'a str,
|
||||
readonly: bool,
|
||||
bounds: (f32, f32, f32, f32),
|
||||
scale: f32,
|
||||
px_pad: f32,
|
||||
title_size: f32,
|
||||
icon_size: f32,
|
||||
border_col: Hsla,
|
||||
icon_name: &'static str,
|
||||
title: &'a str,
|
||||
title_color: Hsla,
|
||||
bold: bool,
|
||||
leading: Option<AnyElement>,
|
||||
trailing: Vec<AnyElement>,
|
||||
snapshot_id: Option<String>,
|
||||
}
|
||||
|
||||
fn icon_canvas(icon_name: &'static str, size_px: f32, color: Hsla) -> AnyElement {
|
||||
let painter = move |bounds, (), window: &mut Window, cx: &mut ui::App| {
|
||||
IconPaint::named(icon_name).paint(bounds, color, window, cx);
|
||||
};
|
||||
canvas(|_, _, _| (), painter)
|
||||
.w(px(size_px))
|
||||
.h(px(size_px))
|
||||
.flex_none()
|
||||
.into_any_element()
|
||||
}
|
||||
|
||||
fn chevron_canvas(collapsed: bool, size_px: f32, color: Hsla) -> AnyElement {
|
||||
if collapsed {
|
||||
return icon_canvas("ArrowDownSmallIcon", size_px, color);
|
||||
}
|
||||
let painter = move |bounds: Bounds<Pixels>, (), window: &mut Window, _: &mut ui::App| {
|
||||
let (ox, oy) = (f32::from(bounds.origin.x), f32::from(bounds.origin.y));
|
||||
let (w, h) = (f32::from(bounds.size.width), f32::from(bounds.size.height));
|
||||
let mut pb = PathBuilder::stroke(px(1.6));
|
||||
pb.move_to(point(px(ox + w * 0.28), px(oy + h * 0.62)));
|
||||
pb.line_to(point(px(ox + w * 0.50), px(oy + h * 0.36)));
|
||||
pb.line_to(point(px(ox + w * 0.72), px(oy + h * 0.62)));
|
||||
if let Ok(path) = pb.build() {
|
||||
window.paint_path(path, color);
|
||||
}
|
||||
};
|
||||
canvas(|_, _, _| (), painter)
|
||||
.w(px(size_px))
|
||||
.h(px(size_px))
|
||||
.flex_none()
|
||||
.into_any_element()
|
||||
}
|
||||
|
||||
fn header_icon_button(
|
||||
id: impl Into<ElementId>,
|
||||
icon: (&'static str, Hsla),
|
||||
palette: &Palette,
|
||||
scale: f32,
|
||||
snapshot_id: Option<String>,
|
||||
on_click: impl Fn(&mut PlaygroundView, &mut Window, &mut Context<PlaygroundView>) + 'static,
|
||||
cx: &mut Context<PlaygroundView>,
|
||||
) -> AnyElement {
|
||||
let hover_bg = palette.hover;
|
||||
let listener = cx.listener(move |this, _, window, cx| {
|
||||
cx.stop_propagation();
|
||||
on_click(this, window, cx);
|
||||
});
|
||||
let mut btn = div()
|
||||
.id(id)
|
||||
.w(px(PAGE_HEADER_BUTTON * scale))
|
||||
.h(px(PAGE_HEADER_BUTTON * scale))
|
||||
.flex_none()
|
||||
.rounded(px(4.0 * scale));
|
||||
btn = btn
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.cursor_pointer()
|
||||
.hover(move |s| s.bg(hover_bg));
|
||||
btn = btn
|
||||
.child(icon_canvas(icon.0, 24.0 * scale, icon.1))
|
||||
.on_mouse_down(MouseButton::Left, listener);
|
||||
if let Some(sid) = snapshot_id {
|
||||
btn = btn.snapshot(sid, Some(EDGELESS_VIEWPORT_ID));
|
||||
}
|
||||
btn.into_any_element()
|
||||
}
|
||||
|
||||
fn docked_header_bar(
|
||||
spec: HeaderBarSpec<'_>,
|
||||
palette: &Palette,
|
||||
cx: &mut Context<PlaygroundView>,
|
||||
) -> AnyElement {
|
||||
let display = if spec.title.trim().is_empty() {
|
||||
"Untitled".to_string()
|
||||
} else {
|
||||
spec.title.trim().to_string()
|
||||
};
|
||||
let fw = if spec.bold {
|
||||
FontWeight::SEMIBOLD
|
||||
} else {
|
||||
FontWeight::MEDIUM
|
||||
};
|
||||
let scale = spec.scale;
|
||||
let label = div()
|
||||
.flex_1()
|
||||
.min_w(px(0.0))
|
||||
.text_size(px(spec.title_size * scale))
|
||||
.font_weight(fw)
|
||||
.text_color(spec.title_color)
|
||||
.truncate()
|
||||
.child(display.clone());
|
||||
let left_row = div()
|
||||
.flex_1()
|
||||
.min_w(px(0.0))
|
||||
.flex()
|
||||
.items_center()
|
||||
.overflow_hidden()
|
||||
.gap(px(4.0 * scale))
|
||||
.children(spec.leading)
|
||||
.child(icon_canvas(
|
||||
spec.icon_name,
|
||||
spec.icon_size * scale,
|
||||
palette.icon,
|
||||
))
|
||||
.child(label);
|
||||
let right_row = (!spec.trailing.is_empty()).then(|| {
|
||||
div()
|
||||
.flex_none()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap(px(4.0 * scale))
|
||||
.children(spec.trailing)
|
||||
});
|
||||
let (fx, fy, fw, fh) = spec.bounds;
|
||||
let mut bar = div()
|
||||
.id(spec.id)
|
||||
.absolute()
|
||||
.left(px(fx))
|
||||
.top(px(fy))
|
||||
.w(px(fw))
|
||||
.h(px(fh));
|
||||
bar = bar
|
||||
.px(px(spec.px_pad * scale))
|
||||
.rounded(px(6.0 * scale))
|
||||
.bg(palette.panel.opacity(0.95));
|
||||
bar = bar
|
||||
.border(px(scale))
|
||||
.border_color(spec.border_col)
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap(px(4.0 * scale))
|
||||
.child(left_row)
|
||||
.children(right_row);
|
||||
if !spec.readonly {
|
||||
let block_id = spec.block_id.to_string();
|
||||
bar = bar.on_mouse_down(
|
||||
MouseButton::Left,
|
||||
cx.listener(move |this, _, window, cx| {
|
||||
cx.stop_propagation();
|
||||
this.handle_edgeless_header_bar_mouse_down(&block_id, window, cx);
|
||||
}),
|
||||
);
|
||||
}
|
||||
if let Some(sid) = spec.snapshot_id {
|
||||
bar = bar
|
||||
.snapshot(sid, Some(EDGELESS_VIEWPORT_ID))
|
||||
.snapshot_text(display);
|
||||
}
|
||||
bar.into_any_element()
|
||||
}
|
||||
|
||||
fn full_overlay_canvas<F>(painter: F) -> AnyElement
|
||||
where
|
||||
F: Fn(Bounds<Pixels>, (), &mut Window, &mut ui::App) + 'static,
|
||||
{
|
||||
canvas(|_, _, _| (), painter)
|
||||
.absolute()
|
||||
.left(px(0.0))
|
||||
.top(px(0.0))
|
||||
.size_full()
|
||||
.into_any_element()
|
||||
}
|
||||
|
||||
fn note_resolved_fill(node: &BlockNode, theme: PlaygroundTheme, palette: &Palette) -> Hsla {
|
||||
node.props
|
||||
.get("prop:background")
|
||||
.and_then(|v| edgeless::resolve_edgeless_color(v, theme))
|
||||
.filter(|c| !c.is_transparent())
|
||||
.unwrap_or(palette.background)
|
||||
}
|
||||
|
||||
fn paint_active_note_frame(style: ActiveNoteFrameStyle) -> AnyElement {
|
||||
let painter = move |bounds: Bounds<Pixels>, (), window: &mut Window, _: &mut ui::App| {
|
||||
let (ox, oy) = (f32::from(bounds.origin.x), f32::from(bounds.origin.y));
|
||||
let bx = ox + f32::from(style.bounds.origin.x);
|
||||
let by = oy + f32::from(style.bounds.origin.y);
|
||||
let bw = f32::from(style.bounds.size.width);
|
||||
let bh = f32::from(style.bounds.size.height);
|
||||
let alphas: [f32; 4] = if style.dark {
|
||||
[0.24, 0.16, 0.09, 0.04]
|
||||
} else {
|
||||
[0.045, 0.032, 0.020, 0.010]
|
||||
};
|
||||
let mut prev = 0.0_f32;
|
||||
for (idx, alpha) in alphas.into_iter().enumerate() {
|
||||
let spread = style.extra * ((idx + 1) as f32 / 4.0);
|
||||
let rb = Bounds::new(
|
||||
point(px(bx - spread), px(by - spread)),
|
||||
size(px(bw + spread * 2.0), px(bh + spread * 2.0)),
|
||||
);
|
||||
window.paint_quad(ui::quad(
|
||||
rb,
|
||||
Corners::all(px(style.card_r + spread * 0.45)),
|
||||
ui::transparent_black(),
|
||||
Edges::all(px((spread - prev).max(0.5))),
|
||||
ui::hsla(0.0, 0.0, 0.0, alpha),
|
||||
BorderStyle::Solid,
|
||||
));
|
||||
prev = spread;
|
||||
}
|
||||
};
|
||||
full_overlay_canvas(painter)
|
||||
}
|
||||
|
||||
fn paint_note_collapse_fade(geom: NoteScreenGeometry, note_bg: Hsla) -> AnyElement {
|
||||
let grad_h = FADE_MASK_HEIGHT.min(geom.sh * 0.45).round();
|
||||
let gx = (geom.sx + 1.0).round();
|
||||
let gy = (geom.sy + geom.sh - grad_h - 1.0).round();
|
||||
let gw = (geom.sw - 2.0).max(1.0).round();
|
||||
let corner_r = (geom.radius * geom.scale * geom.zoom).max(2.0);
|
||||
let painter = move |bounds: Bounds<Pixels>, (), window: &mut Window, _: &mut ui::App| {
|
||||
let (ox, oy) = (f32::from(bounds.origin.x), f32::from(bounds.origin.y));
|
||||
let steps = 8_usize;
|
||||
let step_h = (grad_h / steps as f32).max(1.0);
|
||||
for i in 0..steps {
|
||||
let t = (i + 1) as f32 / steps as f32;
|
||||
let y = oy + gy + i as f32 * step_h;
|
||||
let h = if i + 1 == steps {
|
||||
(oy + gy + grad_h - y).max(1.0)
|
||||
} else {
|
||||
step_h + 0.5
|
||||
};
|
||||
let corners = if i + 1 == steps {
|
||||
Corners {
|
||||
top_left: px(0.0),
|
||||
top_right: px(0.0),
|
||||
bottom_left: px(corner_r),
|
||||
bottom_right: px(corner_r),
|
||||
}
|
||||
} else {
|
||||
Corners::all(px(0.0))
|
||||
};
|
||||
window.paint_quad(ui::quad(
|
||||
Bounds::new(point(px(ox + gx), px(y)), size(px(gw), px(h))),
|
||||
corners,
|
||||
note_bg.opacity(t * t * 0.96),
|
||||
Edges::all(px(0.0)),
|
||||
ui::transparent_black(),
|
||||
BorderStyle::Solid,
|
||||
));
|
||||
}
|
||||
};
|
||||
full_overlay_canvas(painter)
|
||||
}
|
||||
|
||||
impl PlaygroundView {
|
||||
/// BlockSuite `0.27.5` Active Note expanded outer frame padding (`20px` unscaled world units).
|
||||
pub(crate) const ACTIVE_NOTE_EXTRA_PADDING: f32 = 20.0;
|
||||
|
||||
fn note_screen_geometry(&self, item: &SpatialItemInfo, radius: f32) -> NoteScreenGeometry {
|
||||
let origin = point(px(0.0), px(0.0));
|
||||
let tl = self
|
||||
.edgeless
|
||||
.camera
|
||||
.world_to_screen(point(px(item.rect.x), px(item.rect.y)), origin);
|
||||
let zoom = self.edgeless.camera.zoom;
|
||||
NoteScreenGeometry {
|
||||
sx: f32::from(tl.x),
|
||||
sy: f32::from(tl.y),
|
||||
sw: item.rect.w * zoom,
|
||||
sh: item.rect.h * zoom,
|
||||
scale: item.scale,
|
||||
zoom,
|
||||
world_h: (item.rect.h / item.scale.max(0.1)).max(1.0),
|
||||
radius,
|
||||
}
|
||||
}
|
||||
|
||||
fn build_more_indicator(
|
||||
&self,
|
||||
note_id: &str,
|
||||
geom: NoteScreenGeometry,
|
||||
collapsed: bool,
|
||||
palette: &Palette,
|
||||
vp: (f32, f32),
|
||||
cx: &mut Context<Self>,
|
||||
) -> AnyElement {
|
||||
let bx = (geom.sx + (geom.sw - MORE_BTN_SIZE) * 0.5).round();
|
||||
let by = (geom.sy + geom.sh - MORE_BTN_SIZE - 4.0).round();
|
||||
let fully_visible =
|
||||
bx >= 0.0 && by >= 0.0 && bx + MORE_BTN_SIZE <= vp.0 && by + MORE_BTN_SIZE <= vp.1;
|
||||
let hover_bg = palette.hover;
|
||||
let note_id_owned = note_id.to_string();
|
||||
let shadows = palette.theme.shadows("--affine-toolbar-shadow");
|
||||
let listener = cx.listener(move |this, _, window, cx| {
|
||||
cx.stop_propagation();
|
||||
this.toggle_note_more_collapse(¬e_id_owned, Some(window), cx);
|
||||
});
|
||||
let mut pill = div()
|
||||
.id(SharedString::from(format!("note-more-{note_id}")))
|
||||
.absolute()
|
||||
.left(px(bx))
|
||||
.top(px(by))
|
||||
.w(px(MORE_BTN_SIZE))
|
||||
.h(px(MORE_BTN_SIZE));
|
||||
pill = pill
|
||||
.rounded(px(MORE_BTN_SIZE * 0.5))
|
||||
.bg(palette.panel)
|
||||
.border_1()
|
||||
.border_color(palette.border)
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.cursor_pointer();
|
||||
pill = pill
|
||||
.hover(move |s| s.bg(hover_bg))
|
||||
.child(chevron_canvas(collapsed, 16.0, palette.icon))
|
||||
.on_mouse_down(MouseButton::Left, listener);
|
||||
if !shadows.is_empty() {
|
||||
pill = pill.shadow(shadows.into());
|
||||
}
|
||||
if SNAPSHOT_IDS && fully_visible {
|
||||
pill = pill.snapshot(
|
||||
format!("edgeless.note.{note_id}.more_indicator"),
|
||||
Some(EDGELESS_VIEWPORT_ID),
|
||||
);
|
||||
}
|
||||
pill.into_any_element()
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn build_page_note_header(
|
||||
&self,
|
||||
note_id: &str,
|
||||
geom: NoteScreenGeometry,
|
||||
flags: (bool, bool, bool),
|
||||
can_fold: bool,
|
||||
readonly: bool,
|
||||
doc_title: &str,
|
||||
frame_pills: &[(f32, f32, f32, f32)],
|
||||
palette: &Palette,
|
||||
vp: (f32, f32),
|
||||
cx: &mut Context<Self>,
|
||||
) -> Option<AnyElement> {
|
||||
let (folded_only, is_active, _) = flags;
|
||||
let (hx, hy, hw, hh) = Self::compute_page_note_header_bounds(
|
||||
(geom.sx, geom.sy, geom.sw, geom.sh),
|
||||
geom.scale,
|
||||
geom.zoom,
|
||||
flags,
|
||||
frame_pills,
|
||||
)?;
|
||||
|
||||
let vis = hx >= 0.0 && hy >= 0.0 && hx + hw <= vp.0 && hy + hh <= vp.1;
|
||||
let scale = hh / Self::PAGE_NOTE_HEADER_HEIGHT;
|
||||
let model_width = hw / scale;
|
||||
let leading = can_fold.then(|| {
|
||||
let id_fold = note_id.to_string();
|
||||
header_icon_button(
|
||||
SharedString::from(format!("note-hdr-fold-{note_id}")),
|
||||
(
|
||||
if folded_only {
|
||||
"ToggleRightIcon"
|
||||
} else {
|
||||
"ToggleDownIcon"
|
||||
},
|
||||
palette.icon,
|
||||
),
|
||||
palette,
|
||||
scale,
|
||||
(SNAPSHOT_IDS && vis).then(|| format!("edgeless.note.{note_id}.header.toggle")),
|
||||
move |this, window, cx| {
|
||||
this.toggle_note_header_collapse(&id_fold, Some(window), cx);
|
||||
},
|
||||
cx,
|
||||
)
|
||||
});
|
||||
let mut trailing = Vec::new();
|
||||
if model_width >= 156.0 {
|
||||
trailing.push(header_icon_button(
|
||||
SharedString::from(format!("note-hdr-info-{note_id}")),
|
||||
("InformationIcon", palette.icon),
|
||||
palette,
|
||||
scale,
|
||||
(SNAPSHOT_IDS && vis).then(|| format!("edgeless.note.{note_id}.header.info")),
|
||||
move |this, _, cx| {
|
||||
this.set_doc_panel_tab(Some(DocPanelTab::Info), cx);
|
||||
},
|
||||
cx,
|
||||
));
|
||||
}
|
||||
if model_width >= 120.0 {
|
||||
let id_page = note_id.to_string();
|
||||
trailing.push(header_icon_button(
|
||||
SharedString::from(format!("note-hdr-page-{note_id}")),
|
||||
(
|
||||
"LinkedPageIcon",
|
||||
if is_active {
|
||||
palette.brand
|
||||
} else {
|
||||
palette.icon
|
||||
},
|
||||
),
|
||||
palette,
|
||||
scale,
|
||||
(SNAPSHOT_IDS && vis)
|
||||
.then(|| format!("edgeless.note.{note_id}.header.view_in_page")),
|
||||
move |this, window, cx| {
|
||||
this.open_note_in_page(&id_page, window, cx);
|
||||
},
|
||||
cx,
|
||||
));
|
||||
}
|
||||
Some(docked_header_bar(
|
||||
HeaderBarSpec {
|
||||
id: SharedString::from(format!("note-hdr-{note_id}")),
|
||||
block_id: note_id,
|
||||
readonly,
|
||||
bounds: (hx, hy, hw, hh),
|
||||
scale,
|
||||
px_pad: 7.0,
|
||||
title_size: 16.0,
|
||||
icon_size: 20.0,
|
||||
border_col: if is_active {
|
||||
palette.brand.opacity(0.65)
|
||||
} else {
|
||||
palette.border
|
||||
},
|
||||
icon_name: "PageIcon",
|
||||
title: doc_title,
|
||||
title_color: if is_active || folded_only {
|
||||
palette.text_primary
|
||||
} else {
|
||||
palette.text_secondary
|
||||
},
|
||||
bold: is_active || folded_only,
|
||||
leading,
|
||||
trailing,
|
||||
snapshot_id: (SNAPSHOT_IDS && vis)
|
||||
.then(|| format!("edgeless.note.{note_id}.header")),
|
||||
},
|
||||
palette,
|
||||
cx,
|
||||
))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn build_embed_synced_header(
|
||||
&self,
|
||||
block_id: &str,
|
||||
page_id: &str,
|
||||
geom: NoteScreenGeometry,
|
||||
readonly: bool,
|
||||
palette: &Palette,
|
||||
vp: (f32, f32),
|
||||
cx: &mut Context<Self>,
|
||||
) -> Option<AnyElement> {
|
||||
if geom.sw < 96.0 {
|
||||
return None;
|
||||
}
|
||||
let hx = geom.sx.round();
|
||||
let hw = geom.sw.round();
|
||||
let hh = HEADER_HEIGHT;
|
||||
let hy = if geom.sy >= hh + HEADER_GAP {
|
||||
(geom.sy - hh - HEADER_GAP).round()
|
||||
} else {
|
||||
(geom.sy + 4.0).round()
|
||||
};
|
||||
let vis = hx >= 0.0 && hy >= 0.0 && hx + hw <= vp.0 && hy + hh <= vp.1;
|
||||
let title = self.resolve_embed_doc_title(page_id);
|
||||
let compact = hw < 170.0;
|
||||
let open_w = if compact { HEADER_BTN_SIZE } else { 56.0 };
|
||||
let target_id = page_id.to_string();
|
||||
let hover_bg = palette.hover;
|
||||
let listener = cx.listener(move |this, _, window, cx| {
|
||||
cx.stop_propagation();
|
||||
this.open_embed_header_doc(&target_id, Some(window), cx);
|
||||
});
|
||||
let mut open_btn = div()
|
||||
.id(SharedString::from(format!("embed-hdr-open-{block_id}")))
|
||||
.w(px(open_w))
|
||||
.h(px(HEADER_BTN_SIZE))
|
||||
.flex_none();
|
||||
open_btn = open_btn
|
||||
.rounded(px(4.0))
|
||||
.px(px(if compact { 0.0 } else { 6.0 }))
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.gap(px(4.0))
|
||||
.cursor_pointer();
|
||||
open_btn = open_btn
|
||||
.hover(move |s| s.bg(hover_bg))
|
||||
.child(icon_canvas("LinkIcon", 12.0, palette.brand))
|
||||
.on_mouse_down(MouseButton::Left, listener);
|
||||
if !compact {
|
||||
open_btn = open_btn.child(
|
||||
div()
|
||||
.text_size(px(11.0))
|
||||
.font_weight(FontWeight::MEDIUM)
|
||||
.text_color(palette.brand)
|
||||
.child("Open"),
|
||||
);
|
||||
}
|
||||
if SNAPSHOT_IDS && vis {
|
||||
open_btn = open_btn.snapshot(
|
||||
format!("edgeless.block.{block_id}.header.open"),
|
||||
Some(EDGELESS_VIEWPORT_ID),
|
||||
);
|
||||
}
|
||||
|
||||
Some(docked_header_bar(
|
||||
HeaderBarSpec {
|
||||
id: SharedString::from(format!("embed-hdr-{block_id}")),
|
||||
block_id,
|
||||
readonly,
|
||||
bounds: (hx, hy, hw, hh),
|
||||
scale: 1.0,
|
||||
px_pad: 6.0,
|
||||
title_size: 12.0,
|
||||
icon_size: 14.0,
|
||||
border_col: palette.border,
|
||||
icon_name: "LinkedPageIcon",
|
||||
title: &title,
|
||||
title_color: palette.text_secondary,
|
||||
bold: false,
|
||||
leading: None,
|
||||
trailing: vec![open_btn.into_any_element()],
|
||||
snapshot_id: (SNAPSHOT_IDS && vis)
|
||||
.then(|| format!("edgeless.block.{block_id}.header")),
|
||||
},
|
||||
palette,
|
||||
cx,
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) fn render_edgeless_note_headers(
|
||||
&self,
|
||||
palette: &Palette,
|
||||
viewport_width: f32,
|
||||
viewport_height: f32,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Vec<AnyElement> {
|
||||
let Some(snap) = self.snapshot.as_ref() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(root) = snap.root.as_ref() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let page_note = Self::page_note_with_header(root);
|
||||
let doc_title = snap.title().to_string();
|
||||
let active_edit_id = self
|
||||
.edgeless
|
||||
.authoring
|
||||
.editing_spatial_block()
|
||||
.and_then(|(id, is_note)| is_note.then(|| id.to_string()));
|
||||
let origin = point(px(0.0), px(0.0));
|
||||
let zoom = self.edgeless.camera.zoom.max(0.05);
|
||||
let vis = self
|
||||
.edgeless
|
||||
.camera
|
||||
.visible_world_bounds(size(px(viewport_width), px(viewport_height)));
|
||||
let margin = 80.0 / zoom;
|
||||
let cull = WorldRect::new(
|
||||
vis.x - margin,
|
||||
vis.y - margin,
|
||||
vis.w + margin * 2.0,
|
||||
vis.h + margin * 2.0,
|
||||
);
|
||||
|
||||
let notes_by_id: HashMap<&str, &BlockNode> = root
|
||||
.children
|
||||
.iter()
|
||||
.filter(|n| matches!(n.content, BlockContent::Note { .. }))
|
||||
.map(|n| (n.id.as_str(), n))
|
||||
.collect();
|
||||
let surface_embeds: HashMap<&str, &str> = root
|
||||
.children
|
||||
.iter()
|
||||
.filter(|n| matches!(n.content, BlockContent::Surface { .. }))
|
||||
.flat_map(|s| s.children.iter())
|
||||
.filter_map(|c| match &c.content {
|
||||
BlockContent::EmbedSyncedDoc { page_id, .. } => {
|
||||
Some((c.id.as_str(), page_id.as_str()))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let frame_pills: Vec<(f32, f32, f32, f32)> = self
|
||||
.edgeless
|
||||
.authoring
|
||||
.painted_items
|
||||
.iter()
|
||||
.filter(|item| item.kind == SpatialItemKind::Frame)
|
||||
.filter_map(|item| {
|
||||
let pill = item.title_pill_rect?;
|
||||
let tl = self
|
||||
.edgeless
|
||||
.camera
|
||||
.world_to_screen(point(px(pill.x), px(pill.y)), origin);
|
||||
Some((
|
||||
f32::from(tl.x),
|
||||
f32::from(tl.y),
|
||||
pill.w * zoom,
|
||||
pill.h * zoom,
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
let readonly = self.is_edgeless_write_readonly();
|
||||
let dark = self.theme == PlaygroundTheme::Dark;
|
||||
|
||||
let mut elements = Vec::new();
|
||||
for item in self.edgeless.authoring.painted_items.iter() {
|
||||
if !item.rect.intersects(cull) {
|
||||
continue;
|
||||
}
|
||||
match item.kind {
|
||||
SpatialItemKind::Note => {
|
||||
let Some(&node) = notes_by_id.get(item.id.as_str()) else {
|
||||
continue;
|
||||
};
|
||||
let geom = self.note_screen_geometry(item, edgeless::note_border_radius(node));
|
||||
let note_bg = note_resolved_fill(node, self.theme, palette);
|
||||
let is_active = active_edit_id.as_deref() == Some(item.id.as_str());
|
||||
let is_selected = self.edgeless.authoring.selection.contains(&item.id);
|
||||
let collapse = edgeless::note_collapse(node);
|
||||
let collapsed_h = edgeless::note_collapsed_height(node);
|
||||
let can_fold = !readonly && !item.locked;
|
||||
let has_header = page_note.is_some_and(|note| note.id == item.id);
|
||||
let folded_only = has_header && Self::note_is_title_only(collapse, collapsed_h);
|
||||
let layout_content_h = self
|
||||
.edgeless
|
||||
.cached_note_layout(&item.id)
|
||||
.map(|l| l.height + 2.0 * NOTE_CARD_PADDING)
|
||||
.unwrap_or(0.0);
|
||||
|
||||
if is_active {
|
||||
let extra = Self::ACTIVE_NOTE_EXTRA_PADDING * geom.scale * geom.zoom;
|
||||
elements.push(paint_active_note_frame(ActiveNoteFrameStyle {
|
||||
bounds: Bounds::new(
|
||||
point(px(geom.sx), px(geom.sy)),
|
||||
size(px(geom.sw.max(1.0)), px(geom.sh.max(1.0))),
|
||||
),
|
||||
card_r: geom.radius * geom.scale * geom.zoom,
|
||||
extra,
|
||||
dark,
|
||||
}));
|
||||
}
|
||||
let show_fade =
|
||||
!folded_only && collapse && layout_content_h > geom.world_h + 2.0;
|
||||
if show_fade && geom.sh >= 48.0 && geom.sw >= 60.0 {
|
||||
elements.push(paint_note_collapse_fade(geom, note_bg));
|
||||
}
|
||||
if can_fold
|
||||
&& !has_header
|
||||
&& collapsed_h.is_some_and(|h| h != f64::from(layout_content_h))
|
||||
&& geom.sh >= 36.0
|
||||
&& geom.sw >= 64.0
|
||||
{
|
||||
elements.push(self.build_more_indicator(
|
||||
&item.id,
|
||||
geom,
|
||||
if collapse {
|
||||
layout_content_h >= geom.world_h
|
||||
} else {
|
||||
collapsed_h.is_some_and(|h| h >= f64::from(geom.world_h))
|
||||
},
|
||||
palette,
|
||||
(viewport_width, viewport_height),
|
||||
cx,
|
||||
));
|
||||
}
|
||||
if has_header
|
||||
&& let Some(hdr) = self.build_page_note_header(
|
||||
&item.id,
|
||||
geom,
|
||||
(folded_only, is_active, is_selected),
|
||||
can_fold,
|
||||
readonly,
|
||||
&doc_title,
|
||||
&frame_pills,
|
||||
palette,
|
||||
(viewport_width, viewport_height),
|
||||
cx,
|
||||
)
|
||||
{
|
||||
elements.push(hdr);
|
||||
}
|
||||
}
|
||||
SpatialItemKind::SurfaceBlock => {
|
||||
let Some(&page_id) = surface_embeds.get(item.id.as_str()) else {
|
||||
continue;
|
||||
};
|
||||
let geom = self.note_screen_geometry(item, 8.0);
|
||||
if let Some(hdr) = self.build_embed_synced_header(
|
||||
&item.id,
|
||||
page_id,
|
||||
geom,
|
||||
readonly,
|
||||
palette,
|
||||
(viewport_width, viewport_height),
|
||||
cx,
|
||||
) {
|
||||
elements.push(hdr);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
elements
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,476 @@
|
||||
//! Edgeless `EdgelessNoteHeader`, Active Note `20px` halo shadow, bottom `MoreIndicator`
|
||||
//! fold/unfold control, and canvas `EmbedSyncedDoc` card top header bar.
|
||||
|
||||
mod paint;
|
||||
|
||||
use ui::{AnyElement, Bounds, Context, FontWeight, MouseButton, div, point, prelude::*, px, size};
|
||||
|
||||
use crate::{
|
||||
DocPanelTab, PlaygroundTheme, PlaygroundView,
|
||||
edgeless::{self, EDGELESS_VIEWPORT_ID, NOTE_CARD_PADDING, SpatialItemKind, WorldRect},
|
||||
theme::Palette,
|
||||
};
|
||||
|
||||
use paint::{
|
||||
ActiveNoteFrameStyle, HeaderBarSpec, NoteScreenGeometry, chevron_canvas, docked_header_bar,
|
||||
header_element_id, header_icon_button, header_title, icon_canvas, note_resolved_fill,
|
||||
paint_active_note_frame, paint_note_collapse_fade,
|
||||
};
|
||||
|
||||
const HEADER_HEIGHT: f32 = 26.0;
|
||||
const HEADER_GAP: f32 = 4.0;
|
||||
const HEADER_BTN_SIZE: f32 = 24.0;
|
||||
const MORE_BTN_SIZE: f32 = 28.0;
|
||||
|
||||
impl PlaygroundView {
|
||||
/// BlockSuite `0.27.5` Active Note expanded outer frame padding (`20px` unscaled world units).
|
||||
pub(crate) const ACTIVE_NOTE_EXTRA_PADDING: f32 = 20.0;
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn build_more_indicator(
|
||||
&self,
|
||||
note_id: &str,
|
||||
id_hash: u64,
|
||||
geom: NoteScreenGeometry,
|
||||
collapsed: bool,
|
||||
palette: &Palette,
|
||||
vp: (f32, f32),
|
||||
cx: &mut Context<Self>,
|
||||
) -> AnyElement {
|
||||
let bx = (geom.sx + (geom.sw - MORE_BTN_SIZE) * 0.5).round();
|
||||
let by = (geom.sy + geom.sh - MORE_BTN_SIZE - 4.0).round();
|
||||
let fully_visible =
|
||||
bx >= 0.0 && by >= 0.0 && bx + MORE_BTN_SIZE <= vp.0 && by + MORE_BTN_SIZE <= vp.1;
|
||||
let hover_bg = palette.hover;
|
||||
let note_id_owned = note_id.to_string();
|
||||
let shadows = palette.theme.shadows("--affine-toolbar-shadow");
|
||||
let listener = cx.listener(move |this, _, window, cx| {
|
||||
cx.stop_propagation();
|
||||
this.toggle_note_more_collapse(¬e_id_owned, Some(window), cx);
|
||||
});
|
||||
let mut pill = div()
|
||||
.id(header_element_id("note-more", id_hash))
|
||||
.absolute()
|
||||
.left(px(bx))
|
||||
.top(px(by))
|
||||
.w(px(MORE_BTN_SIZE))
|
||||
.h(px(MORE_BTN_SIZE));
|
||||
pill = pill
|
||||
.rounded(px(MORE_BTN_SIZE * 0.5))
|
||||
.bg(palette.panel)
|
||||
.border_1()
|
||||
.border_color(palette.border)
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.cursor_pointer();
|
||||
pill = pill
|
||||
.hover(move |s| s.bg(hover_bg))
|
||||
.child(chevron_canvas(collapsed, 16.0, palette.icon))
|
||||
.on_mouse_down(MouseButton::Left, listener);
|
||||
if !shadows.is_empty() {
|
||||
pill = pill.shadow(shadows.into());
|
||||
}
|
||||
if fully_visible {
|
||||
pill = pill.snapshot(
|
||||
format_args!("edgeless.note.{note_id}.more_indicator"),
|
||||
Some(EDGELESS_VIEWPORT_ID),
|
||||
);
|
||||
}
|
||||
pill.into_any_element()
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn build_page_note_header(
|
||||
&self,
|
||||
note_id: &str,
|
||||
id_hash: u64,
|
||||
geom: NoteScreenGeometry,
|
||||
flags: (bool, bool, bool),
|
||||
can_fold: bool,
|
||||
readonly: bool,
|
||||
doc_title: &str,
|
||||
frame_pills: &[(f32, f32, f32, f32)],
|
||||
palette: &Palette,
|
||||
vp: (f32, f32),
|
||||
cx: &mut Context<Self>,
|
||||
) -> Option<AnyElement> {
|
||||
let (folded_only, is_active, _) = flags;
|
||||
let (hx, hy, hw, hh) = Self::compute_page_note_header_bounds(
|
||||
(geom.sx, geom.sy, geom.sw, geom.sh),
|
||||
geom.scale,
|
||||
geom.zoom,
|
||||
flags,
|
||||
frame_pills,
|
||||
)?;
|
||||
|
||||
let vis = hx >= 0.0 && hy >= 0.0 && hx + hw <= vp.0 && hy + hh <= vp.1;
|
||||
let scale = hh / Self::PAGE_NOTE_HEADER_HEIGHT;
|
||||
let model_width = hw / scale;
|
||||
let leading = can_fold.then(|| {
|
||||
let id_fold = note_id.to_string();
|
||||
let mut btn = header_icon_button(
|
||||
header_element_id("note-hdr-toggle", id_hash),
|
||||
(
|
||||
if folded_only {
|
||||
"ToggleRightIcon"
|
||||
} else {
|
||||
"ToggleDownIcon"
|
||||
},
|
||||
palette.icon,
|
||||
),
|
||||
palette,
|
||||
scale,
|
||||
move |this, window, cx| {
|
||||
this.toggle_note_header_collapse(&id_fold, Some(window), cx);
|
||||
},
|
||||
cx,
|
||||
);
|
||||
if vis {
|
||||
btn = btn.snapshot(
|
||||
format_args!("edgeless.note.{note_id}.header.toggle"),
|
||||
Some(EDGELESS_VIEWPORT_ID),
|
||||
);
|
||||
}
|
||||
btn.into_any_element()
|
||||
});
|
||||
let mut trailing = Vec::new();
|
||||
if model_width >= 156.0 {
|
||||
let mut btn = header_icon_button(
|
||||
header_element_id("note-hdr-info", id_hash),
|
||||
("InformationIcon", palette.icon),
|
||||
palette,
|
||||
scale,
|
||||
move |this, _, cx| {
|
||||
this.set_doc_panel_tab(Some(DocPanelTab::Info), cx);
|
||||
},
|
||||
cx,
|
||||
);
|
||||
if vis {
|
||||
btn = btn.snapshot(
|
||||
format_args!("edgeless.note.{note_id}.header.info"),
|
||||
Some(EDGELESS_VIEWPORT_ID),
|
||||
);
|
||||
}
|
||||
trailing.push(btn.into_any_element());
|
||||
}
|
||||
if model_width >= 120.0 {
|
||||
let id_page = note_id.to_string();
|
||||
let mut btn = header_icon_button(
|
||||
header_element_id("note-hdr-page", id_hash),
|
||||
(
|
||||
"LinkedPageIcon",
|
||||
if is_active {
|
||||
palette.brand
|
||||
} else {
|
||||
palette.icon
|
||||
},
|
||||
),
|
||||
palette,
|
||||
scale,
|
||||
move |this, window, cx| {
|
||||
this.open_note_in_page(&id_page, window, cx);
|
||||
},
|
||||
cx,
|
||||
);
|
||||
if vis {
|
||||
btn = btn.snapshot(
|
||||
format_args!("edgeless.note.{note_id}.header.view_in_page"),
|
||||
Some(EDGELESS_VIEWPORT_ID),
|
||||
);
|
||||
}
|
||||
trailing.push(btn.into_any_element());
|
||||
}
|
||||
let mut bar = docked_header_bar(
|
||||
HeaderBarSpec {
|
||||
id: header_element_id("note-hdr-bar", id_hash),
|
||||
block_id: note_id,
|
||||
readonly,
|
||||
bounds: (hx, hy, hw, hh),
|
||||
scale,
|
||||
px_pad: 7.0,
|
||||
title_size: 16.0,
|
||||
icon_size: 20.0,
|
||||
border_col: if is_active {
|
||||
palette.brand.opacity(0.65)
|
||||
} else {
|
||||
palette.border
|
||||
},
|
||||
icon_name: "PageIcon",
|
||||
title: doc_title,
|
||||
title_color: if is_active || folded_only {
|
||||
palette.text_primary
|
||||
} else {
|
||||
palette.text_secondary
|
||||
},
|
||||
bold: is_active || folded_only,
|
||||
leading,
|
||||
trailing,
|
||||
},
|
||||
palette,
|
||||
cx,
|
||||
);
|
||||
if vis {
|
||||
bar = bar
|
||||
.snapshot(
|
||||
format_args!("edgeless.note.{note_id}.header"),
|
||||
Some(EDGELESS_VIEWPORT_ID),
|
||||
)
|
||||
.snapshot_text(header_title(doc_title));
|
||||
}
|
||||
Some(bar.into_any_element())
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn build_embed_synced_header(
|
||||
&self,
|
||||
block_id: &str,
|
||||
id_hash: u64,
|
||||
page_id: &str,
|
||||
geom: NoteScreenGeometry,
|
||||
readonly: bool,
|
||||
palette: &Palette,
|
||||
vp: (f32, f32),
|
||||
cx: &mut Context<Self>,
|
||||
) -> Option<AnyElement> {
|
||||
if geom.sw < 96.0 {
|
||||
return None;
|
||||
}
|
||||
let hx = geom.sx.round();
|
||||
let hw = geom.sw.round();
|
||||
let hh = HEADER_HEIGHT;
|
||||
let hy = if geom.sy >= hh + HEADER_GAP {
|
||||
(geom.sy - hh - HEADER_GAP).round()
|
||||
} else {
|
||||
(geom.sy + 4.0).round()
|
||||
};
|
||||
let vis = hx >= 0.0 && hy >= 0.0 && hx + hw <= vp.0 && hy + hh <= vp.1;
|
||||
let title = self.resolve_embed_doc_title(page_id);
|
||||
let compact = hw < 170.0;
|
||||
let open_w = if compact { HEADER_BTN_SIZE } else { 56.0 };
|
||||
let target_id = page_id.to_string();
|
||||
let hover_bg = palette.hover;
|
||||
let listener = cx.listener(move |this, _, window, cx| {
|
||||
cx.stop_propagation();
|
||||
this.open_embed_header_doc(&target_id, Some(window), cx);
|
||||
});
|
||||
let mut open_btn = div()
|
||||
.id(header_element_id("embed-hdr-open", id_hash))
|
||||
.w(px(open_w))
|
||||
.h(px(HEADER_BTN_SIZE))
|
||||
.flex_none();
|
||||
open_btn = open_btn
|
||||
.rounded(px(4.0))
|
||||
.px(px(if compact { 0.0 } else { 6.0 }))
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.gap(px(4.0))
|
||||
.cursor_pointer();
|
||||
open_btn = open_btn
|
||||
.hover(move |s| s.bg(hover_bg))
|
||||
.child(icon_canvas("LinkIcon", 12.0, palette.brand))
|
||||
.on_mouse_down(MouseButton::Left, listener);
|
||||
if !compact {
|
||||
open_btn = open_btn.child(
|
||||
div()
|
||||
.text_size(px(11.0))
|
||||
.font_weight(FontWeight::MEDIUM)
|
||||
.text_color(palette.brand)
|
||||
.child("Open"),
|
||||
);
|
||||
}
|
||||
if vis {
|
||||
open_btn = open_btn.snapshot(
|
||||
format_args!("edgeless.block.{block_id}.header.open"),
|
||||
Some(EDGELESS_VIEWPORT_ID),
|
||||
);
|
||||
}
|
||||
|
||||
let mut bar = docked_header_bar(
|
||||
HeaderBarSpec {
|
||||
id: header_element_id("embed-hdr-bar", id_hash),
|
||||
block_id,
|
||||
readonly,
|
||||
bounds: (hx, hy, hw, hh),
|
||||
scale: 1.0,
|
||||
px_pad: 6.0,
|
||||
title_size: 12.0,
|
||||
icon_size: 14.0,
|
||||
border_col: palette.border,
|
||||
icon_name: "LinkedPageIcon",
|
||||
title: &title,
|
||||
title_color: palette.text_secondary,
|
||||
bold: false,
|
||||
leading: None,
|
||||
trailing: vec![open_btn.into_any_element()],
|
||||
},
|
||||
palette,
|
||||
cx,
|
||||
);
|
||||
if vis {
|
||||
bar = bar
|
||||
.snapshot(
|
||||
format_args!("edgeless.block.{block_id}.header"),
|
||||
Some(EDGELESS_VIEWPORT_ID),
|
||||
)
|
||||
.snapshot_text(header_title(&title));
|
||||
}
|
||||
Some(bar.into_any_element())
|
||||
}
|
||||
|
||||
pub(super) fn render_edgeless_note_headers(
|
||||
&mut self,
|
||||
palette: &Palette,
|
||||
viewport_width: f32,
|
||||
viewport_height: f32,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Vec<AnyElement> {
|
||||
let Some(snap) = self.snapshot.as_ref() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let page_id = self.page_id.as_deref().unwrap_or_default();
|
||||
self.edgeless
|
||||
.note_headers
|
||||
.sync(self.doc_epoch, page_id, self.doc_rev, snap);
|
||||
let this = &*self;
|
||||
let index = &this.edgeless.note_headers;
|
||||
let Some(root) = snap.root.as_ref().filter(|_| !index.is_empty()) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let page_note = Self::page_note_with_header(root);
|
||||
let doc_title = snap.title();
|
||||
let active_edit_id = this
|
||||
.edgeless
|
||||
.authoring
|
||||
.editing_spatial_block()
|
||||
.and_then(|(id, is_note)| is_note.then_some(id));
|
||||
let zoom = this.edgeless.camera.zoom.max(0.05);
|
||||
let vis = this
|
||||
.edgeless
|
||||
.camera
|
||||
.visible_world_bounds(size(px(viewport_width), px(viewport_height)));
|
||||
let margin = 80.0 / zoom;
|
||||
let cull = WorldRect::new(
|
||||
vis.x - margin,
|
||||
vis.y - margin,
|
||||
vis.w + margin * 2.0,
|
||||
vis.h + margin * 2.0,
|
||||
);
|
||||
let mut frame_pills: Option<Vec<(f32, f32, f32, f32)>> = None;
|
||||
let readonly = this.is_edgeless_write_readonly();
|
||||
let dark = this.theme == PlaygroundTheme::Dark;
|
||||
|
||||
let mut elements = Vec::new();
|
||||
for item in this.edgeless.authoring.painted_items.iter() {
|
||||
if !item.rect.intersects(cull) {
|
||||
continue;
|
||||
}
|
||||
match item.kind {
|
||||
SpatialItemKind::Note => {
|
||||
let Some(entry) = index.note(&item.id) else {
|
||||
continue;
|
||||
};
|
||||
let Some(node) = root.children.get(entry.child_index) else {
|
||||
continue;
|
||||
};
|
||||
let geom = this.note_screen_geometry(item, edgeless::note_border_radius(node));
|
||||
let note_bg = note_resolved_fill(node, this.theme, palette);
|
||||
let is_active = active_edit_id == Some(item.id.as_str());
|
||||
let is_selected = this.edgeless.authoring.selection.contains(&item.id);
|
||||
let collapse = edgeless::note_collapse(node);
|
||||
let collapsed_h = edgeless::note_collapsed_height(node);
|
||||
let can_fold = !readonly && !item.locked;
|
||||
let has_header = page_note.is_some_and(|note| note.id == item.id);
|
||||
let folded_only = has_header && Self::note_is_title_only(collapse, collapsed_h);
|
||||
let layout_content_h = this
|
||||
.edgeless
|
||||
.cached_note_layout(&item.id)
|
||||
.map(|l| l.height + 2.0 * NOTE_CARD_PADDING)
|
||||
.unwrap_or(0.0);
|
||||
|
||||
if is_active {
|
||||
let extra = Self::ACTIVE_NOTE_EXTRA_PADDING * geom.scale * geom.zoom;
|
||||
elements.push(paint_active_note_frame(ActiveNoteFrameStyle {
|
||||
bounds: Bounds::new(
|
||||
point(px(geom.sx), px(geom.sy)),
|
||||
size(px(geom.sw.max(1.0)), px(geom.sh.max(1.0))),
|
||||
),
|
||||
card_r: geom.radius * geom.scale * geom.zoom,
|
||||
extra,
|
||||
dark,
|
||||
}));
|
||||
}
|
||||
let show_fade =
|
||||
!folded_only && collapse && layout_content_h > geom.world_h + 2.0;
|
||||
if show_fade && geom.sh >= 48.0 && geom.sw >= 60.0 {
|
||||
elements.push(paint_note_collapse_fade(geom, note_bg));
|
||||
}
|
||||
if can_fold
|
||||
&& !has_header
|
||||
&& collapsed_h.is_some_and(|h| h != f64::from(layout_content_h))
|
||||
&& geom.sh >= 36.0
|
||||
&& geom.sw >= 64.0
|
||||
{
|
||||
elements.push(this.build_more_indicator(
|
||||
&item.id,
|
||||
entry.id_hash,
|
||||
geom,
|
||||
if collapse {
|
||||
layout_content_h >= geom.world_h
|
||||
} else {
|
||||
collapsed_h.is_some_and(|h| h >= f64::from(geom.world_h))
|
||||
},
|
||||
palette,
|
||||
(viewport_width, viewport_height),
|
||||
cx,
|
||||
));
|
||||
}
|
||||
if !has_header {
|
||||
continue;
|
||||
}
|
||||
let pills: &[(f32, f32, f32, f32)] = if folded_only {
|
||||
&[]
|
||||
} else {
|
||||
frame_pills.get_or_insert_with(|| this.frame_title_pill_rects(zoom))
|
||||
};
|
||||
if let Some(hdr) = this.build_page_note_header(
|
||||
&item.id,
|
||||
entry.id_hash,
|
||||
geom,
|
||||
(folded_only, is_active, is_selected),
|
||||
can_fold,
|
||||
readonly,
|
||||
doc_title,
|
||||
pills,
|
||||
palette,
|
||||
(viewport_width, viewport_height),
|
||||
cx,
|
||||
) {
|
||||
elements.push(hdr);
|
||||
}
|
||||
}
|
||||
SpatialItemKind::SurfaceBlock => {
|
||||
let Some(embed) = index.surface_embed(&item.id) else {
|
||||
continue;
|
||||
};
|
||||
let geom = this.note_screen_geometry(item, 8.0);
|
||||
if let Some(hdr) = this.build_embed_synced_header(
|
||||
&item.id,
|
||||
embed.id_hash,
|
||||
&embed.target_page_id,
|
||||
geom,
|
||||
readonly,
|
||||
palette,
|
||||
(viewport_width, viewport_height),
|
||||
cx,
|
||||
) {
|
||||
elements.push(hdr);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
elements
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
//! Paint helpers of the Edgeless Note header, the Active Note frame, and the collapse fade.
|
||||
|
||||
use blocksuite_playground_doc::read::BlockNode;
|
||||
use ui::{
|
||||
AnyElement, BorderStyle, Bounds, Context, Corners, Div, Edges, ElementId, FontWeight, Hsla,
|
||||
MouseButton, PathBuilder, Pixels, SharedString, Stateful, Window, canvas, div, point,
|
||||
prelude::*, px, size,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
PlaygroundTheme, PlaygroundView,
|
||||
edgeless::{self, SpatialItemInfo, SpatialItemKind},
|
||||
theme::{IconPaint, Palette},
|
||||
};
|
||||
|
||||
const PAGE_HEADER_BUTTON: f32 = 32.0;
|
||||
const FADE_MASK_HEIGHT: f32 = 34.0;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct ActiveNoteFrameStyle {
|
||||
pub(super) bounds: Bounds<Pixels>,
|
||||
pub(super) card_r: f32,
|
||||
pub(super) extra: f32,
|
||||
pub(super) dark: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct NoteScreenGeometry {
|
||||
pub(super) sx: f32,
|
||||
pub(super) sy: f32,
|
||||
pub(super) sw: f32,
|
||||
pub(super) sh: f32,
|
||||
pub(super) scale: f32,
|
||||
pub(super) zoom: f32,
|
||||
pub(super) world_h: f32,
|
||||
pub(super) radius: f32,
|
||||
}
|
||||
|
||||
pub(super) struct HeaderBarSpec<'a> {
|
||||
pub(super) id: ElementId,
|
||||
pub(super) block_id: &'a str,
|
||||
pub(super) readonly: bool,
|
||||
pub(super) bounds: (f32, f32, f32, f32),
|
||||
pub(super) scale: f32,
|
||||
pub(super) px_pad: f32,
|
||||
pub(super) title_size: f32,
|
||||
pub(super) icon_size: f32,
|
||||
pub(super) border_col: Hsla,
|
||||
pub(super) icon_name: &'static str,
|
||||
pub(super) title: &'a str,
|
||||
pub(super) title_color: Hsla,
|
||||
pub(super) bold: bool,
|
||||
pub(super) leading: Option<AnyElement>,
|
||||
pub(super) trailing: Vec<AnyElement>,
|
||||
}
|
||||
|
||||
/// Element id of one header control: a static prefix and the hash of the block id.
|
||||
pub(super) fn header_element_id(prefix: &'static str, id_hash: u64) -> ElementId {
|
||||
ElementId::NamedInteger(SharedString::new_static(prefix), id_hash)
|
||||
}
|
||||
|
||||
pub(super) fn icon_canvas(icon_name: &'static str, size_px: f32, color: Hsla) -> AnyElement {
|
||||
let painter = move |bounds, (), window: &mut Window, cx: &mut ui::App| {
|
||||
IconPaint::named(icon_name).paint(bounds, color, window, cx);
|
||||
};
|
||||
canvas(|_, _, _| (), painter)
|
||||
.w(px(size_px))
|
||||
.h(px(size_px))
|
||||
.flex_none()
|
||||
.into_any_element()
|
||||
}
|
||||
|
||||
pub(super) fn chevron_canvas(collapsed: bool, size_px: f32, color: Hsla) -> AnyElement {
|
||||
if collapsed {
|
||||
return icon_canvas("ArrowDownSmallIcon", size_px, color);
|
||||
}
|
||||
let painter = move |bounds: Bounds<Pixels>, (), window: &mut Window, _: &mut ui::App| {
|
||||
let (ox, oy) = (f32::from(bounds.origin.x), f32::from(bounds.origin.y));
|
||||
let (w, h) = (f32::from(bounds.size.width), f32::from(bounds.size.height));
|
||||
let mut pb = PathBuilder::stroke(px(1.6));
|
||||
pb.move_to(point(px(ox + w * 0.28), px(oy + h * 0.62)));
|
||||
pb.line_to(point(px(ox + w * 0.50), px(oy + h * 0.36)));
|
||||
pb.line_to(point(px(ox + w * 0.72), px(oy + h * 0.62)));
|
||||
if let Ok(path) = pb.build() {
|
||||
window.paint_path(path, color);
|
||||
}
|
||||
};
|
||||
canvas(|_, _, _| (), painter)
|
||||
.w(px(size_px))
|
||||
.h(px(size_px))
|
||||
.flex_none()
|
||||
.into_any_element()
|
||||
}
|
||||
|
||||
pub(super) fn header_icon_button(
|
||||
id: impl Into<ElementId>,
|
||||
icon: (&'static str, Hsla),
|
||||
palette: &Palette,
|
||||
scale: f32,
|
||||
on_click: impl Fn(&mut PlaygroundView, &mut Window, &mut Context<PlaygroundView>) + 'static,
|
||||
cx: &mut Context<PlaygroundView>,
|
||||
) -> Stateful<Div> {
|
||||
let hover_bg = palette.hover;
|
||||
let listener = cx.listener(move |this, _, window, cx| {
|
||||
cx.stop_propagation();
|
||||
on_click(this, window, cx);
|
||||
});
|
||||
let mut btn = div()
|
||||
.id(id)
|
||||
.w(px(PAGE_HEADER_BUTTON * scale))
|
||||
.h(px(PAGE_HEADER_BUTTON * scale))
|
||||
.flex_none()
|
||||
.rounded(px(4.0 * scale));
|
||||
btn = btn
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.cursor_pointer()
|
||||
.hover(move |s| s.bg(hover_bg));
|
||||
btn = btn
|
||||
.child(icon_canvas(icon.0, 24.0 * scale, icon.1))
|
||||
.on_mouse_down(MouseButton::Left, listener);
|
||||
btn
|
||||
}
|
||||
|
||||
/// The title a header shows: the trimmed title, or `Untitled` when it is blank.
|
||||
pub(super) fn header_title(title: &str) -> &str {
|
||||
match title.trim() {
|
||||
"" => "Untitled",
|
||||
trimmed => trimmed,
|
||||
}
|
||||
}
|
||||
|
||||
/// The docked header bar. The caller adds the harness snapshot, so that release builds keep
|
||||
/// no snapshot id text.
|
||||
pub(super) fn docked_header_bar(
|
||||
spec: HeaderBarSpec<'_>,
|
||||
palette: &Palette,
|
||||
cx: &mut Context<PlaygroundView>,
|
||||
) -> Stateful<Div> {
|
||||
let fw = if spec.bold {
|
||||
FontWeight::SEMIBOLD
|
||||
} else {
|
||||
FontWeight::MEDIUM
|
||||
};
|
||||
let scale = spec.scale;
|
||||
let label = div()
|
||||
.flex_1()
|
||||
.min_w(px(0.0))
|
||||
.text_size(px(spec.title_size * scale))
|
||||
.font_weight(fw)
|
||||
.text_color(spec.title_color)
|
||||
.truncate()
|
||||
.child(SharedString::from(header_title(spec.title)));
|
||||
let left_row = div()
|
||||
.flex_1()
|
||||
.min_w(px(0.0))
|
||||
.flex()
|
||||
.items_center()
|
||||
.overflow_hidden()
|
||||
.gap(px(4.0 * scale))
|
||||
.children(spec.leading)
|
||||
.child(icon_canvas(
|
||||
spec.icon_name,
|
||||
spec.icon_size * scale,
|
||||
palette.icon,
|
||||
))
|
||||
.child(label);
|
||||
let right_row = (!spec.trailing.is_empty()).then(|| {
|
||||
div()
|
||||
.flex_none()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap(px(4.0 * scale))
|
||||
.children(spec.trailing)
|
||||
});
|
||||
let (fx, fy, fw, fh) = spec.bounds;
|
||||
let mut bar = div()
|
||||
.id(spec.id)
|
||||
.absolute()
|
||||
.left(px(fx))
|
||||
.top(px(fy))
|
||||
.w(px(fw))
|
||||
.h(px(fh));
|
||||
bar = bar
|
||||
.px(px(spec.px_pad * scale))
|
||||
.rounded(px(6.0 * scale))
|
||||
.bg(palette.panel.opacity(0.95));
|
||||
bar = bar
|
||||
.border(px(scale))
|
||||
.border_color(spec.border_col)
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap(px(4.0 * scale))
|
||||
.child(left_row)
|
||||
.children(right_row);
|
||||
if !spec.readonly {
|
||||
let block_id = spec.block_id.to_string();
|
||||
bar = bar.on_mouse_down(
|
||||
MouseButton::Left,
|
||||
cx.listener(move |this, _, window, cx| {
|
||||
cx.stop_propagation();
|
||||
this.handle_edgeless_header_bar_mouse_down(&block_id, window, cx);
|
||||
}),
|
||||
);
|
||||
}
|
||||
bar
|
||||
}
|
||||
|
||||
pub(super) fn full_overlay_canvas<F>(painter: F) -> AnyElement
|
||||
where
|
||||
F: Fn(Bounds<Pixels>, (), &mut Window, &mut ui::App) + 'static,
|
||||
{
|
||||
canvas(|_, _, _| (), painter)
|
||||
.absolute()
|
||||
.left(px(0.0))
|
||||
.top(px(0.0))
|
||||
.size_full()
|
||||
.into_any_element()
|
||||
}
|
||||
|
||||
pub(super) fn note_resolved_fill(
|
||||
node: &BlockNode,
|
||||
theme: PlaygroundTheme,
|
||||
palette: &Palette,
|
||||
) -> Hsla {
|
||||
node.props
|
||||
.get("prop:background")
|
||||
.and_then(|v| edgeless::resolve_edgeless_color(v, theme))
|
||||
.filter(|c| !c.is_transparent())
|
||||
.unwrap_or(palette.background)
|
||||
}
|
||||
|
||||
pub(super) fn paint_active_note_frame(style: ActiveNoteFrameStyle) -> AnyElement {
|
||||
let painter = move |bounds: Bounds<Pixels>, (), window: &mut Window, _: &mut ui::App| {
|
||||
let (ox, oy) = (f32::from(bounds.origin.x), f32::from(bounds.origin.y));
|
||||
let bx = ox + f32::from(style.bounds.origin.x);
|
||||
let by = oy + f32::from(style.bounds.origin.y);
|
||||
let bw = f32::from(style.bounds.size.width);
|
||||
let bh = f32::from(style.bounds.size.height);
|
||||
let alphas: [f32; 4] = if style.dark {
|
||||
[0.24, 0.16, 0.09, 0.04]
|
||||
} else {
|
||||
[0.045, 0.032, 0.020, 0.010]
|
||||
};
|
||||
let mut prev = 0.0_f32;
|
||||
for (idx, alpha) in alphas.into_iter().enumerate() {
|
||||
let spread = style.extra * ((idx + 1) as f32 / 4.0);
|
||||
let rb = Bounds::new(
|
||||
point(px(bx - spread), px(by - spread)),
|
||||
size(px(bw + spread * 2.0), px(bh + spread * 2.0)),
|
||||
);
|
||||
window.paint_quad(ui::quad(
|
||||
rb,
|
||||
Corners::all(px(style.card_r + spread * 0.45)),
|
||||
ui::transparent_black(),
|
||||
Edges::all(px((spread - prev).max(0.5))),
|
||||
ui::hsla(0.0, 0.0, 0.0, alpha),
|
||||
BorderStyle::Solid,
|
||||
));
|
||||
prev = spread;
|
||||
}
|
||||
};
|
||||
full_overlay_canvas(painter)
|
||||
}
|
||||
|
||||
pub(super) fn paint_note_collapse_fade(geom: NoteScreenGeometry, note_bg: Hsla) -> AnyElement {
|
||||
let grad_h = FADE_MASK_HEIGHT.min(geom.sh * 0.45).round();
|
||||
let gx = (geom.sx + 1.0).round();
|
||||
let gy = (geom.sy + geom.sh - grad_h - 1.0).round();
|
||||
let gw = (geom.sw - 2.0).max(1.0).round();
|
||||
let corner_r = (geom.radius * geom.scale * geom.zoom).max(2.0);
|
||||
let painter = move |bounds: Bounds<Pixels>, (), window: &mut Window, _: &mut ui::App| {
|
||||
let (ox, oy) = (f32::from(bounds.origin.x), f32::from(bounds.origin.y));
|
||||
let steps = 8_usize;
|
||||
let step_h = (grad_h / steps as f32).max(1.0);
|
||||
for i in 0..steps {
|
||||
let t = (i + 1) as f32 / steps as f32;
|
||||
let y = oy + gy + i as f32 * step_h;
|
||||
let h = if i + 1 == steps {
|
||||
(oy + gy + grad_h - y).max(1.0)
|
||||
} else {
|
||||
step_h + 0.5
|
||||
};
|
||||
let corners = if i + 1 == steps {
|
||||
Corners {
|
||||
top_left: px(0.0),
|
||||
top_right: px(0.0),
|
||||
bottom_left: px(corner_r),
|
||||
bottom_right: px(corner_r),
|
||||
}
|
||||
} else {
|
||||
Corners::all(px(0.0))
|
||||
};
|
||||
window.paint_quad(ui::quad(
|
||||
Bounds::new(point(px(ox + gx), px(y)), size(px(gw), px(h))),
|
||||
corners,
|
||||
note_bg.opacity(t * t * 0.96),
|
||||
Edges::all(px(0.0)),
|
||||
ui::transparent_black(),
|
||||
BorderStyle::Solid,
|
||||
));
|
||||
}
|
||||
};
|
||||
full_overlay_canvas(painter)
|
||||
}
|
||||
|
||||
impl PlaygroundView {
|
||||
pub(super) fn note_screen_geometry(
|
||||
&self,
|
||||
item: &SpatialItemInfo,
|
||||
radius: f32,
|
||||
) -> NoteScreenGeometry {
|
||||
let origin = point(px(0.0), px(0.0));
|
||||
let tl = self
|
||||
.edgeless
|
||||
.camera
|
||||
.world_to_screen(point(px(item.rect.x), px(item.rect.y)), origin);
|
||||
let zoom = self.edgeless.camera.zoom;
|
||||
NoteScreenGeometry {
|
||||
sx: f32::from(tl.x),
|
||||
sy: f32::from(tl.y),
|
||||
sw: item.rect.w * zoom,
|
||||
sh: item.rect.h * zoom,
|
||||
scale: item.scale,
|
||||
zoom,
|
||||
world_h: (item.rect.h / item.scale.max(0.1)).max(1.0),
|
||||
radius,
|
||||
}
|
||||
}
|
||||
|
||||
/// Screen rects of the Frame title pills that a docked Page Note header steps around.
|
||||
pub(super) fn frame_title_pill_rects(&self, zoom: f32) -> Vec<(f32, f32, f32, f32)> {
|
||||
let origin = point(px(0.0), px(0.0));
|
||||
self.edgeless
|
||||
.authoring
|
||||
.painted_items
|
||||
.iter()
|
||||
.filter(|item| item.kind == SpatialItemKind::Frame)
|
||||
.filter_map(|item| {
|
||||
let pill = item.title_pill_rect?;
|
||||
let tl = self
|
||||
.edgeless
|
||||
.camera
|
||||
.world_to_screen(point(px(pill.x), px(pill.y)), origin);
|
||||
Some((
|
||||
f32::from(tl.x),
|
||||
f32::from(tl.y),
|
||||
pill.w * zoom,
|
||||
pill.h * zoom,
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Note header interactions, collapse and expand mutations, lock guards, and Page navigation.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use blocksuite_playground_doc::read::{BlockContent, BlockNode, PageSnapshot, SurfaceElementKind};
|
||||
use ui::{Context, Window};
|
||||
@@ -19,6 +19,8 @@ enum NoteCollapseMode {
|
||||
ExpandForEdit,
|
||||
}
|
||||
|
||||
/// Reads the lock of a Note from the current snapshot: its own `lockedBySelf` flag or the flag
|
||||
/// of any Group above it, across every Surface in the tree. A Group cycle ends the walk.
|
||||
fn snapshot_note_is_locked(snap: &PageSnapshot, note_id: &str) -> bool {
|
||||
let Some(root) = snap.root.as_ref() else {
|
||||
return false;
|
||||
@@ -42,16 +44,14 @@ fn snapshot_note_is_locked(snap: &PageSnapshot, note_id: &str) -> bool {
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut visited = HashSet::new();
|
||||
let mut cur = note_id;
|
||||
for _ in 0..16 {
|
||||
let Some(&(gid, locked)) = parent_group.get(cur) else {
|
||||
break;
|
||||
};
|
||||
while let Some(&(gid, locked)) = parent_group.get(cur) {
|
||||
if locked {
|
||||
return true;
|
||||
}
|
||||
if gid == cur {
|
||||
break;
|
||||
if !visited.insert(gid) {
|
||||
return false;
|
||||
}
|
||||
cur = gid;
|
||||
}
|
||||
@@ -61,16 +61,12 @@ fn snapshot_note_is_locked(snap: &PageSnapshot, note_id: &str) -> bool {
|
||||
impl PlaygroundView {
|
||||
pub(crate) const PAGE_NOTE_HEADER_HEIGHT: f32 = TITLE_ONLY_COLLAPSED_HEIGHT as f32;
|
||||
|
||||
/// Lock state at write time. A collaborator can lock or unlock the Note or a parent Group
|
||||
/// after the last paint, so this reads the current snapshot and never the painted items.
|
||||
pub(crate) fn is_note_locked(&self, note_id: &str) -> bool {
|
||||
self.edgeless
|
||||
.authoring
|
||||
.painted_items
|
||||
.iter()
|
||||
.any(|i| i.id == note_id && i.locked)
|
||||
|| self
|
||||
.snapshot
|
||||
.as_deref()
|
||||
.is_some_and(|snap| snapshot_note_is_locked(snap, note_id))
|
||||
self.snapshot
|
||||
.as_deref()
|
||||
.is_some_and(|snap| snapshot_note_is_locked(snap, note_id))
|
||||
}
|
||||
|
||||
pub(crate) fn handle_edgeless_header_bar_mouse_down(
|
||||
@@ -353,3 +349,167 @@ impl PlaygroundView {
|
||||
.unwrap_or_else(|| "Untitled".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use blocksuite_playground_doc::{
|
||||
read::PageSnapshot,
|
||||
schema::{BlockSpec, SurfaceElementSpec},
|
||||
session::PageDocSession,
|
||||
};
|
||||
use ui::{AppContext, HeadlessPlatform};
|
||||
use y_octo::{Any, SessionValue};
|
||||
|
||||
use super::note_collapse;
|
||||
use crate::{
|
||||
HOME_PAGE_ID, PlaygroundMode, PlaygroundOptions, PlaygroundView, room_client::DocState,
|
||||
};
|
||||
|
||||
/// Lock owners of the test Note: the Note, its Group in `surf`, and the Group in `surf2`
|
||||
/// that holds that Group.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Lock {
|
||||
Note,
|
||||
InnerGroup,
|
||||
OuterGroup,
|
||||
}
|
||||
|
||||
fn set_lock(page: &mut PageDocSession, lock: Lock, on: bool, now: u64) {
|
||||
let value = SessionValue::Any(if on { Any::True } else { Any::False });
|
||||
match lock {
|
||||
Lock::Note => page.set_block_prop("note", "prop:lockedBySelf", value, now),
|
||||
Lock::InnerGroup => {
|
||||
page.set_surface_element_field("surf", "g-inner", "lockedBySelf", value, now)
|
||||
}
|
||||
Lock::OuterGroup => {
|
||||
page.set_surface_element_field("surf2", "g-outer", "lockedBySelf", value, now)
|
||||
}
|
||||
}
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// A Note inside `g-inner` (Surface `surf`), inside `g-outer` (Surface `surf2`). With
|
||||
/// `cycle`, `g-inner` also lists `g-outer` as a child.
|
||||
fn build_doc(locked: Option<Lock>, cycle: bool) -> DocState {
|
||||
let mut state = DocState::new("w", 903).unwrap();
|
||||
state
|
||||
.workspace
|
||||
.create_page(HOME_PAGE_ID, "Locks", 1)
|
||||
.unwrap();
|
||||
let page = state.workspace.ensure_page(HOME_PAGE_ID).unwrap();
|
||||
let title = "Locks".into();
|
||||
page.add_block("root", BlockSpec::Page { title }, None, None, 1)
|
||||
.unwrap();
|
||||
for surface in ["surf", "surf2"] {
|
||||
page.add_block(surface, BlockSpec::Surface, Some("root"), None, 2)
|
||||
.unwrap();
|
||||
}
|
||||
let xywh = Some("[100,100,400,240]".into());
|
||||
page.add_block("note", BlockSpec::Note { xywh }, Some("root"), None, 3)
|
||||
.unwrap();
|
||||
let mut inner_children = vec!["note".to_string()];
|
||||
if cycle {
|
||||
inner_children.push("g-outer".into());
|
||||
}
|
||||
let groups = [
|
||||
("surf", "g-inner", "a0", inner_children),
|
||||
("surf2", "g-outer", "a1", vec!["g-inner".to_string()]),
|
||||
];
|
||||
for (surface, id, index, children) in groups {
|
||||
let title = id.to_string();
|
||||
let spec = SurfaceElementSpec::Group {
|
||||
seed: 1,
|
||||
title,
|
||||
children,
|
||||
};
|
||||
page.add_surface_element(surface, id, index, spec, 4)
|
||||
.unwrap();
|
||||
}
|
||||
if let Some(lock) = locked {
|
||||
set_lock(page, lock, true, 5);
|
||||
}
|
||||
state
|
||||
}
|
||||
|
||||
fn note_is_collapsed(snap: &PageSnapshot) -> bool {
|
||||
note_collapse(snap.block("note").unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn note_fold_reads_current_note_and_group_locks_across_surfaces_and_cycles() {
|
||||
// (lock at paint, lock change after paint, Group cycle, fold applies)
|
||||
let cases = [
|
||||
(None, Some((Lock::Note, true)), false, false),
|
||||
(None, Some((Lock::InnerGroup, true)), false, false),
|
||||
(None, Some((Lock::OuterGroup, true)), false, false),
|
||||
(None, Some((Lock::OuterGroup, true)), true, false),
|
||||
(Some(Lock::Note), Some((Lock::Note, false)), false, true),
|
||||
(
|
||||
Some(Lock::OuterGroup),
|
||||
Some((Lock::OuterGroup, false)),
|
||||
false,
|
||||
true,
|
||||
),
|
||||
(None, None, true, true),
|
||||
];
|
||||
for (case, (painted_lock, change, cycle, folds)) in cases.into_iter().enumerate() {
|
||||
let platform = HeadlessPlatform::new(1280, 800, 1.0);
|
||||
let app = ui::Application::with_platform(platform.clone()).run_embedded(|cx| {
|
||||
crate::register_bundled_fonts(cx).unwrap();
|
||||
});
|
||||
let state = build_doc(painted_lock, cycle);
|
||||
let win = app
|
||||
.update(|cx| {
|
||||
cx.open_window(ui::WindowOptions::default(), |_w, cx| {
|
||||
cx.new(|cx| {
|
||||
let options = PlaygroundOptions {
|
||||
mode: PlaygroundMode::Edgeless,
|
||||
..Default::default()
|
||||
};
|
||||
let mut view = PlaygroundView::with_options(options, cx);
|
||||
view.set_document(state, cx);
|
||||
view
|
||||
})
|
||||
})
|
||||
})
|
||||
.unwrap();
|
||||
platform.windows()[0].request_frame();
|
||||
app.update(|cx| {
|
||||
win.update(cx, |v, _, cx| {
|
||||
let painted_locked = |v: &PlaygroundView| {
|
||||
let items = &v.edgeless.authoring.painted_items;
|
||||
items.iter().find(|i| i.id == "note").map(|i| i.locked)
|
||||
};
|
||||
assert_eq!(
|
||||
painted_locked(v),
|
||||
Some(painted_lock.is_some()),
|
||||
"case {case}"
|
||||
);
|
||||
if let Some((lock, on)) = change {
|
||||
let commit = v
|
||||
.page_mut()
|
||||
.unwrap()
|
||||
.structural_edit(50, |p| {
|
||||
set_lock(p, lock, on, 50);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
v.did_edgeless_doc_commit(commit, cx);
|
||||
}
|
||||
// The paint is stale: no frame ran after the lock change.
|
||||
assert_eq!(
|
||||
painted_locked(v),
|
||||
Some(painted_lock.is_some()),
|
||||
"case {case}"
|
||||
);
|
||||
let applied = v.toggle_note_header_collapse("note", None, cx);
|
||||
assert_eq!(applied, folds, "case {case}");
|
||||
let snap = v.snapshot.clone().unwrap();
|
||||
assert_eq!(note_is_collapsed(&snap), folds, "case {case}");
|
||||
})
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -363,16 +363,90 @@ for view_dir in "$EDITOR_DIR" "$PLAYGROUND_DIR" "$DESKTOP_DIR" "$MOBILE_DIR"; do
|
||||
if grep -rn 'is_headless' "$view_dir/src" 2>/dev/null; then
|
||||
fail "is_headless branches are forbidden in $view_dir/src"
|
||||
fi
|
||||
TESTER_CFG_HITS=$(
|
||||
grep -rnE '#\[cfg\((any\(test|feature\s*=\s*"harness")' "$view_dir/src" 2>/dev/null \
|
||||
| grep -Ev "^$view_dir/src/(bin/|rich_text/mod\.rs:)" \
|
||||
|| true
|
||||
)
|
||||
if [ -n "$TESTER_CFG_HITS" ]; then
|
||||
echo "$TESTER_CFG_HITS" >&2
|
||||
fail "Inline harness/test cfg branches are forbidden in shipping $view_dir/src modules"
|
||||
fi
|
||||
done
|
||||
VIEW_DIRS="$EDITOR_DIR $PLAYGROUND_DIR $DESKTOP_DIR $MOBILE_DIR" python3 - <<'PY'
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# A tester branch is a `#[cfg(...)]` attribute or a `cfg!(...)` macro whose predicate names the
|
||||
# `harness` feature, an `any(...)` that admits `test` beside other builds, or (for `cfg!`, which is
|
||||
# a value in shipping code) any `test` predicate. A `#[cfg(...)]` on a `mod name;` line only
|
||||
# selects which files compile, so `any(..., test)` stays allowed there.
|
||||
CFG_START = re.compile(r"#\[cfg\(|\bcfg!\(")
|
||||
HARNESS = re.compile(r'feature\s*=\s*"harness"')
|
||||
TEST = re.compile(r"\btest\b")
|
||||
MOD_DECL = re.compile(r"\s*(?:#\[[^\]]*\]\s*)*(?:pub(?:\([^)]*\))?\s+)?mod\s+\w+\s*;")
|
||||
|
||||
def strip_test_mods_and_comments(src: str) -> str:
|
||||
"""Blank `#[cfg(test)] mod <name> { ... }` blocks and `//` comments, keeping line numbers."""
|
||||
lines = src.splitlines()
|
||||
out = []
|
||||
i = 0
|
||||
while i < len(lines):
|
||||
s = lines[i].strip()
|
||||
if s == "#[cfg(test)]" and i + 1 < len(lines) and re.match(r"^(pub(\([^)]*\))?\s+)?mod\s+\w+\s*\{", lines[i + 1].strip()):
|
||||
out.append("")
|
||||
i += 1
|
||||
depth = 0
|
||||
started = False
|
||||
while i < len(lines):
|
||||
line = lines[i]
|
||||
started |= "{" in line
|
||||
depth += line.count("{") - line.count("}")
|
||||
out.append("")
|
||||
i += 1
|
||||
if started and depth <= 0:
|
||||
break
|
||||
continue
|
||||
out.append(re.sub(r"//.*", "", lines[i]))
|
||||
i += 1
|
||||
return "\n".join(out)
|
||||
|
||||
def predicate(text: str, open_at: int) -> tuple[str, int]:
|
||||
depth = 0
|
||||
for j in range(open_at, len(text)):
|
||||
if text[j] == "(":
|
||||
depth += 1
|
||||
elif text[j] == ")":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return " ".join(text[open_at + 1 : j].split()), j
|
||||
return " ".join(text[open_at + 1 :].split()), len(text)
|
||||
|
||||
def is_tester(pred: str, is_macro: bool) -> bool:
|
||||
if HARNESS.search(pred):
|
||||
return True
|
||||
if is_macro:
|
||||
return bool(TEST.search(pred))
|
||||
return pred.startswith("any(") and bool(TEST.search(pred))
|
||||
|
||||
hits = []
|
||||
for view_dir in os.environ["VIEW_DIRS"].split():
|
||||
src_dir = Path(view_dir) / "src"
|
||||
if not src_dir.is_dir():
|
||||
continue
|
||||
for path in sorted(src_dir.rglob("*.rs")):
|
||||
rel = path.relative_to(src_dir).as_posix()
|
||||
if rel.startswith("bin/") or rel == "rich_text/mod.rs":
|
||||
continue
|
||||
text = strip_test_mods_and_comments(path.read_text(encoding="utf-8"))
|
||||
for m in CFG_START.finditer(text):
|
||||
is_macro = m.group(0).startswith("cfg!")
|
||||
pred, end = predicate(text, m.end() - 1)
|
||||
if not is_tester(pred, is_macro):
|
||||
continue
|
||||
if not is_macro and MOD_DECL.match(text, end + 2):
|
||||
continue
|
||||
line = text.count("\n", 0, m.start()) + 1
|
||||
hits.append(f"{path}:{line}: {m.group(0)}{pred})")
|
||||
|
||||
if hits:
|
||||
print("\n".join(hits), file=sys.stderr)
|
||||
print("ERROR: Inline harness/test cfg branches are forbidden in shipping view modules", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
PY
|
||||
|
||||
echo "==> Checking TOPBAR_HEIGHT single-source check in blocksuite/crates/playground/src"
|
||||
PLAYGROUND_DIR="$PLAYGROUND_DIR" python3 - <<'PY'
|
||||
|
||||
Reference in new issue
Block a user