Files
AFFiNE/packages/frontend/desktop/tests/docs_explorer_rows.rs
T
DarkSky 8da16f102f perf(desktop): read explorer tag names in place and align topbar chrome
Explorer row keys now read tag names from the shared document views
without a copy. Each frame of the docs explorer built a new string for
each tag of each document. With 1,024 documents and 4 tags each, one
frame now makes 4,182 fewer allocations (11,524 to 7,342).

Topbar and explorer icon buttons use the 4px radius and the hover
overlay of the web IconButton. The explorer row menu uses the vertical
"more" icon. The active app tab has a 1px innerBlackBorder ring outside
its bounds. A three-pane divider draws a 3px line in the primary button
color with a 15% soft glow (0 12px 21px 4px) on hover and while it
resizes.

Topbar, tab, menu and divider controls take numeric element IDs, and
their snapshot IDs build only in harness builds. An app tab keeps its
element ID by tab ID, so its state follows the tab when tabs before it
close.
2026-12-04 03:33:15 +09:00

278 lines
9.9 KiB
Rust

//! Docs explorer rows over a large tagged workspace: the per-frame allocations of the row keys,
//! and the row menu button.
use std::{
alloc::{GlobalAlloc, Layout, System},
cell::Cell,
};
use affine_desktop::{
DesktopAppState, DesktopRoute, DesktopShellView, palette_for, register_desktop_fonts,
};
use affine_store::directory::DocMode;
use ui::{
AppContext, Application, ApplicationHandle, Bounds, HeadlessPlatform, HeadlessWindow, Hsla,
MouseButton, MouseDownEvent, MouseMoveEvent, PlatformInput, Rgba, SnapshotRect, WindowBounds,
WindowHandle, WindowOptions, point, px, size,
};
use ui_tokens::ThemeMode;
thread_local! {
/// Allocation calls and requested bytes of this thread while `COUNTING` is set.
static COUNTS: Cell<(u64, u64)> = const { Cell::new((0, 0)) };
static COUNTING: Cell<bool> = const { Cell::new(false) };
}
/// The system allocator with per-thread totals, so a test can count what one frame allocates.
struct CountingAllocator;
fn record(bytes: usize) {
if COUNTING.try_with(Cell::get).unwrap_or(false) {
let _ = COUNTS.try_with(|counts| {
let (calls, total) = counts.get();
counts.set((calls + 1, total + bytes as u64));
});
}
}
// SAFETY: Every call goes to `System` with its arguments unchanged, and the totals are `Cell`s
// in thread-local storage that need no allocation.
unsafe impl GlobalAlloc for CountingAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
record(layout.size());
unsafe { System.alloc(layout) }
}
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
record(layout.size());
unsafe { System.alloc_zeroed(layout) }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
unsafe { System.dealloc(ptr, layout) }
}
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
record(new_size);
unsafe { System.realloc(ptr, layout, new_size) }
}
}
#[global_allocator]
static ALLOCATOR: CountingAllocator = CountingAllocator;
const DOCS: usize = 1_024;
const SHOWCASE_TAGS: [&str; 4] = ["rust", "architecture", "release", "design"];
struct Shell {
app: ApplicationHandle,
handle: WindowHandle<DesktopShellView>,
window: HeadlessWindow,
/// The most recently updated document: the first row.
first: String,
}
impl Shell {
fn new(theme: ThemeMode, tags_per_doc: usize) -> Self {
let mut state = DesktopAppState::seed_showcase(theme, "2026-12-02");
let mut last = String::new();
for index in 0..DOCS {
last = state.store.create_doc(
format!("Tagged document {index:04}"),
DocMode::Page,
None,
1_900_000_000_000 + index as i64,
);
let doc = state.store.docs.get_mut(&last).expect("new document");
doc.meta.tags = SHOWCASE_TAGS[..tags_per_doc]
.iter()
.map(|tag| (*tag).to_owned())
.collect();
}
// A metadata edit after the tag writes builds the views again.
assert!(
state
.store
.rename_doc(&last, "Tagged document last", 1_900_000_010_000)
);
state.navigate_active_pane(DesktopRoute::AllDocs);
let platform = HeadlessPlatform::new(1280, 800, 1.0);
let app = Application::with_platform(platform.clone()).run_embedded(|_| {});
let handle = app.update(|cx| {
register_desktop_fonts(cx).expect("desktop fonts");
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(Bounds::new(
point(px(0.0), px(0.0)),
size(px(1280.0), px(800.0)),
))),
..WindowOptions::default()
},
|_, cx| cx.new(|cx| DesktopShellView::new(state, cx)),
)
.expect("desktop window")
});
let window = platform.windows().remove(0);
window.request_frame();
window.request_frame();
Self {
app,
handle,
window,
first: last,
}
}
/// Allocation calls and bytes of one full frame of the shell.
fn frame_allocations(&self) -> (u64, u64) {
self.app.update(|cx| {
self.handle
.update(cx, |_, _, cx| cx.notify())
.expect("desktop view")
});
COUNTS.with(|counts| counts.set((0, 0)));
COUNTING.with(|counting| counting.set(true));
self.window.request_frame();
COUNTING.with(|counting| counting.set(false));
COUNTS.with(Cell::get)
}
fn bounds(&self, id: &str) -> SnapshotRect {
self.app.update(|cx| {
self.handle
.update(cx, |_, window, _| {
window.frame_snapshot().elements[id].bounds
})
.expect("desktop view")
})
}
fn contains(&self, id: &str) -> bool {
self.app.update(|cx| {
self.handle
.update(cx, |_, window, _| {
window.frame_snapshot().elements.contains_key(id)
})
.expect("desktop view")
})
}
fn image(&self) -> image::RgbaImage {
self.app.update(|cx| {
self.handle
.update(cx, |_, window, _| {
window.render_to_image().expect("frame image")
})
.expect("desktop view")
})
}
fn pointer(&self, x: f32, y: f32) {
self.window
.dispatch_input(PlatformInput::MouseMove(MouseMoveEvent {
position: point(px(x), px(y)),
..Default::default()
}));
self.window.request_frame();
}
}
#[test]
fn explorer_frame_allocations_do_not_grow_with_the_tags_of_every_document() {
let mut frames = Vec::new();
for tags in [0, SHOWCASE_TAGS.len()] {
let shell = Shell::new(ThemeMode::Light, tags);
assert!(shell.contains(&format!("desktop.list.doc.{}", shell.first)));
// The first counted frame can still fill caches: count the second.
shell.frame_allocations();
let (calls, bytes) = shell.frame_allocations();
println!("{DOCS} documents x {tags} tags: {calls} allocations, {bytes} bytes per frame");
frames.push(calls);
}
// Only the mounted rows draw their tags. Before the row keys read the tag names in place,
// every frame allocated one name per tag of every document.
let extra = frames[1] - frames[0];
assert!(
extra < DOCS as u64,
"{extra} extra allocations per frame for {} tags",
DOCS * SHOWCASE_TAGS.len()
);
}
fn rgb(color: Hsla) -> [f32; 3] {
let color = Rgba::from(color);
[color.r * 255.0, color.g * 255.0, color.b * 255.0]
}
#[test]
fn explorer_row_menu_button_is_a_vertical_icon_button_that_opens_and_closes_the_menu() {
for theme in [ThemeMode::Light, ThemeMode::Dark] {
let shell = Shell::new(theme, 0);
let palette = palette_for(theme);
let row = shell.bounds(&format!("desktop.list.doc.{}", shell.first));
shell.pointer(row.x + 40.0, row.y + row.height / 2.0);
let button = shell.bounds(&format!("desktop.explorer.doc_menu.{}", shell.first));
assert_eq!((button.width, button.height), (28.0, 28.0));
let row_hovered = shell.image();
// The glyph is three dots in a column: its ink is taller than wide.
let ink = (0..28u32)
.flat_map(|dy| (0..28u32).map(move |dx| (dx, dy)))
.filter(|&(dx, dy)| {
let pixel = row_hovered
.get_pixel(button.x as u32 + dx, button.y as u32 + dy)
.0;
let text = rgb(palette.text_secondary);
(0..3).all(|i| (f32::from(pixel[i]) - text[i]).abs() <= 48.0)
})
.collect::<Vec<_>>();
let span = |axis: fn(&(u32, u32)) -> u32| {
let values = ink.iter().map(axis);
values.clone().max().unwrap_or(0) - values.min().unwrap_or(0) + 1
};
let (width, height) = (span(|p| p.0), span(|p| p.1));
assert!(
!ink.is_empty() && height >= 2 * width,
"{theme:?}: glyph ink {width}x{height}"
);
// Hover paints the web hover overlay with a 4px radius: the pixel one in from the
// corner is inside a 4px corner and outside a 6px one.
shell.pointer(button.x + 14.0, button.y + 14.0);
let hovered = shell.image();
for (dx, dy) in [(1u32, 1u32), (1, 14)] {
let (x, y) = (button.x as u32 + dx, button.y as u32 + dy);
let under = row_hovered.get_pixel(x, y).0;
let alpha = Rgba::from(palette.hover_overlay).a;
let overlay = rgb(palette.hover_overlay);
let expected: [f32; 3] =
std::array::from_fn(|i| overlay[i] * alpha + f32::from(under[i]) * (1.0 - alpha));
let pixel = hovered.get_pixel(x, y).0;
let close = (0..3).all(|i| (f32::from(pixel[i]) - expected[i]).abs() <= 3.0);
assert!(
close,
"{theme:?} ({dx}, {dy}): {pixel:?}, expected {expected:?}"
);
}
shell
.window
.simulate_click(point(px(button.x + 14.0), px(button.y + 14.0)));
shell.window.request_frame();
assert!(shell.contains("desktop.explorer.menu"), "{theme:?}: menu");
shell
.window
.dispatch_input(PlatformInput::MouseDown(MouseDownEvent {
button: MouseButton::Left,
position: point(px(row.x + 40.0), px(790.0)),
click_count: 1,
..Default::default()
}));
shell.window.request_frame();
assert!(
!shell.contains("desktop.explorer.menu"),
"{theme:?}: menu closed"
);
}
}