mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-05 11:15:01 +03:00
perf(editor): format code toolbar snapshot ids lazily and rank languages without heap keys
The desktop code toolbar, its More menu and the touch code toolbar now give `format_args!` directly to the snapshot call. Release builds format no snapshot ids for these controls. Harness builds record the same ids as before. The interactive element ids do not change. `filter_code_languages_ordered` keeps its signature and its order. It gives each catalog entry the dense order of its first entry in the history. Then it sorts one integer key for each match on the stack. The label match compares ASCII bytes without case, so a query makes no lowercase copy of each label. A table test compares the new order with the previous sort for all query prefixes, cases, aliases, duplicates and a history of 65,538 entries. `Palette` now has `error`, `error_background` and `focus_ring` from the theme tokens. The More menu and the touch toolbar read these fields. The colors do not change. Wheel and touch fling scrolls lend the collapsed block set to the overlay scene and do not clone it. This change also removes `ScrollAxis::set_max` and `ScrollAxis::snapped`, which had no production callers.
This commit is contained in:
1 parent
67ccd2fc3d
commit
a8ff41ccdf
8 files changed
+214
-69
No files matched your search
@@ -509,42 +509,63 @@ pub fn filter_code_languages_ordered(
|
||||
current_lang: &str,
|
||||
recent_langs: &[String],
|
||||
) -> Vec<(&'static str, &'static str)> {
|
||||
const N: usize = CODE_LANGUAGE_CATALOG.len();
|
||||
// The active language has order 0, recent languages 1..=N, and all other languages N + 1.
|
||||
const OTHER: u16 = N as u16 + 1;
|
||||
let needle = query.trim().to_ascii_lowercase();
|
||||
let active = canonical_code_language(current_lang);
|
||||
|
||||
let priority_bucket = |id: &str| -> (u8, usize) {
|
||||
if id == active {
|
||||
(0, 0)
|
||||
} else if let Some(pos) = recent_langs.iter().position(|r| r == id) {
|
||||
(1, pos)
|
||||
} else {
|
||||
(2, 0)
|
||||
// Give each catalog entry the dense order of its first occurrence in the history.
|
||||
let mut recent_order = [OTHER; N];
|
||||
let mut next = 1;
|
||||
for recent in recent_langs {
|
||||
if let Some(idx) = CODE_LANGUAGE_CATALOG
|
||||
.iter()
|
||||
.position(|spec| spec.id == recent.as_str())
|
||||
&& recent_order[idx] == OTHER
|
||||
{
|
||||
recent_order[idx] = next;
|
||||
next += 1;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
let mut ranked: Vec<(u8, u8, usize, usize, &'static str, &'static str)> = Vec::new();
|
||||
// Sort key: match rank, then order, then catalog index. The index makes each key unique.
|
||||
let mut keys = [0usize; N];
|
||||
let mut len = 0;
|
||||
for (idx, spec) in CODE_LANGUAGE_CATALOG.iter().enumerate() {
|
||||
let match_rank = if needle.is_empty() {
|
||||
0
|
||||
} else if (!spec.id.is_empty() && spec.id.starts_with(needle.as_str()))
|
||||
let match_rank = if needle.is_empty()
|
||||
|| (!spec.id.is_empty() && spec.id.starts_with(needle.as_str()))
|
||||
|| spec
|
||||
.aliases
|
||||
.iter()
|
||||
.any(|alias| alias.starts_with(needle.as_str()))
|
||||
{
|
||||
0
|
||||
} else if spec.label.to_ascii_lowercase().starts_with(needle.as_str()) {
|
||||
} else if spec
|
||||
.label
|
||||
.as_bytes()
|
||||
.get(..needle.len())
|
||||
.is_some_and(|head| head.eq_ignore_ascii_case(needle.as_bytes()))
|
||||
{
|
||||
1
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
let (bucket, recent_pos) = priority_bucket(spec.id);
|
||||
ranked.push((match_rank, bucket, recent_pos, idx, spec.id, spec.label));
|
||||
let order = if spec.id == active {
|
||||
0
|
||||
} else {
|
||||
usize::from(recent_order[idx])
|
||||
};
|
||||
keys[len] = (match_rank * (N + 2) + order) * N + idx;
|
||||
len += 1;
|
||||
}
|
||||
ranked.sort_by_key(|&(mr, bucket, rpos, idx, _, _)| (mr, bucket, rpos, idx));
|
||||
ranked
|
||||
.into_iter()
|
||||
.map(|(_, _, _, _, id, label)| (id, label))
|
||||
let keys = &mut keys[..len];
|
||||
keys.sort_unstable();
|
||||
keys.iter()
|
||||
.map(|key| {
|
||||
let spec = &CODE_LANGUAGE_CATALOG[key % N];
|
||||
(spec.id, spec.label)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -583,4 +604,125 @@ mod tests {
|
||||
assert_eq!(ordered[1], ("python", "Python"));
|
||||
assert_eq!(ordered[2], ("go", "Go"));
|
||||
}
|
||||
|
||||
/// The previous implementation: a stable sort of match rank, recent position and index.
|
||||
fn reference_order(
|
||||
query: &str,
|
||||
current_lang: &str,
|
||||
recent_langs: &[String],
|
||||
) -> Vec<(&'static str, &'static str)> {
|
||||
let needle = query.trim().to_ascii_lowercase();
|
||||
let active = canonical_code_language(current_lang);
|
||||
|
||||
let priority_bucket = |id: &str| -> (u8, usize) {
|
||||
if id == active {
|
||||
(0, 0)
|
||||
} else if let Some(pos) = recent_langs.iter().position(|r| r == id) {
|
||||
(1, pos)
|
||||
} else {
|
||||
(2, 0)
|
||||
}
|
||||
};
|
||||
|
||||
let mut ranked: Vec<(u8, u8, usize, usize, &'static str, &'static str)> = Vec::new();
|
||||
for (idx, spec) in CODE_LANGUAGE_CATALOG.iter().enumerate() {
|
||||
let match_rank = if needle.is_empty() {
|
||||
0
|
||||
} else if (!spec.id.is_empty() && spec.id.starts_with(needle.as_str()))
|
||||
|| spec
|
||||
.aliases
|
||||
.iter()
|
||||
.any(|alias| alias.starts_with(needle.as_str()))
|
||||
{
|
||||
0
|
||||
} else if spec.label.to_ascii_lowercase().starts_with(needle.as_str()) {
|
||||
1
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
let (bucket, recent_pos) = priority_bucket(spec.id);
|
||||
ranked.push((match_rank, bucket, recent_pos, idx, spec.id, spec.label));
|
||||
}
|
||||
ranked.sort_by_key(|&(mr, bucket, rpos, idx, _, _)| (mr, bucket, rpos, idx));
|
||||
ranked
|
||||
.into_iter()
|
||||
.map(|(_, _, _, _, id, label)| (id, label))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordered_filter_matches_the_reference_order_for_query_and_history_tables() {
|
||||
let owned = |ids: &[&str]| ids.iter().map(|id| id.to_string()).collect::<Vec<_>>();
|
||||
let mut short_queries: Vec<String> =
|
||||
["", " ", "zzzz", "TS", " Py ", "\u{e9}", "plain text"]
|
||||
.iter()
|
||||
.map(|q| q.to_string())
|
||||
.collect();
|
||||
let mut full_queries = std::collections::BTreeSet::from(
|
||||
["", " tS ", "\u{56fe}", "zzzz-no-match"].map(String::from),
|
||||
);
|
||||
for spec in CODE_LANGUAGE_CATALOG {
|
||||
for word in [spec.id, spec.label]
|
||||
.into_iter()
|
||||
.chain(spec.aliases.iter().copied())
|
||||
{
|
||||
for n in 1..=word.len().min(3) {
|
||||
if word.is_char_boundary(n) {
|
||||
short_queries.push(word[..n].to_string());
|
||||
short_queries.push(word[..n].to_ascii_uppercase());
|
||||
}
|
||||
}
|
||||
for (n, _) in word.char_indices() {
|
||||
full_queries.insert(word[..n].to_string());
|
||||
}
|
||||
full_queries.insert(word.to_string());
|
||||
}
|
||||
}
|
||||
short_queries.sort();
|
||||
short_queries.dedup();
|
||||
let short_histories = [
|
||||
owned(&[]),
|
||||
owned(&["rust"]),
|
||||
owned(&["python", "rust", "python"]),
|
||||
owned(&["nope", "typescript", "", "c"]),
|
||||
CODE_LANGUAGE_CATALOG
|
||||
.iter()
|
||||
.rev()
|
||||
.take(20)
|
||||
.map(|spec| spec.id.to_string())
|
||||
.collect(),
|
||||
];
|
||||
let full_histories = [owned(&["javascript", "go", "rust", "go"]), owned(&[])];
|
||||
let mut long_history = vec!["?".to_string(); 65_538];
|
||||
long_history[0] = "yaml".to_string();
|
||||
long_history[65_536] = "javascript".to_string();
|
||||
long_history[65_537] = "go".to_string();
|
||||
|
||||
let mut cases: Vec<(&str, &str, &[String])> = Vec::new();
|
||||
for query in &short_queries {
|
||||
for current in ["", "rust", "ts", "Plain", "nope", "typescript", "c"] {
|
||||
for history in &short_histories {
|
||||
cases.push((query.as_str(), current, history.as_slice()));
|
||||
}
|
||||
}
|
||||
}
|
||||
for query in &full_queries {
|
||||
for current in ["", "PY", "plain text", "UNKNOWN", "Rust"] {
|
||||
for history in &full_histories {
|
||||
cases.push((query.as_str(), current, history.as_slice()));
|
||||
}
|
||||
}
|
||||
}
|
||||
for query in ["", "j", "g"] {
|
||||
cases.push((query, "", long_history.as_slice()));
|
||||
}
|
||||
for (query, current, history) in cases {
|
||||
assert_eq!(
|
||||
filter_code_languages_ordered(query, current, history),
|
||||
reference_order(query, current, history),
|
||||
"query {query:?} current {current:?} history length {}",
|
||||
history.len()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -300,7 +300,7 @@ impl Overlays {
|
||||
if bar_visible {
|
||||
lang_btn = lang_btn
|
||||
.snapshot(
|
||||
SharedString::from(format!("{}.language", block.snapshot_id)),
|
||||
format_args!("{}.language", block.snapshot_id),
|
||||
Some(PAGE_SURFACE_ID),
|
||||
)
|
||||
.snapshot_text(lang_display);
|
||||
@@ -355,7 +355,7 @@ impl Overlays {
|
||||
if bar_visible {
|
||||
el = el
|
||||
.snapshot(
|
||||
SharedString::from(format!("{}.{suffix}", block.snapshot_id)),
|
||||
format_args!("{}.{suffix}", block.snapshot_id),
|
||||
Some(PAGE_SURFACE_ID),
|
||||
)
|
||||
.snapshot_focused(active)
|
||||
@@ -409,7 +409,7 @@ impl Overlays {
|
||||
if bar_visible {
|
||||
copy_btn = copy_btn
|
||||
.snapshot(
|
||||
SharedString::from(format!("{}.copy", block.snapshot_id)),
|
||||
format_args!("{}.copy", block.snapshot_id),
|
||||
Some(PAGE_SURFACE_ID),
|
||||
)
|
||||
.snapshot_focused(copied)
|
||||
@@ -449,7 +449,7 @@ impl Overlays {
|
||||
if bar_visible {
|
||||
el = el
|
||||
.snapshot(
|
||||
SharedString::from(format!("{}.{snap_suffix}", block.snapshot_id)),
|
||||
format_args!("{}.{snap_suffix}", block.snapshot_id),
|
||||
Some(PAGE_SURFACE_ID),
|
||||
)
|
||||
.snapshot_focused(focused)
|
||||
@@ -528,7 +528,7 @@ impl Overlays {
|
||||
.child(right_group);
|
||||
if bar_visible {
|
||||
bar = bar.snapshot(
|
||||
SharedString::from(format!("{}.toolbar", block.snapshot_id)),
|
||||
format_args!("{}.toolbar", block.snapshot_id),
|
||||
Some(PAGE_SURFACE_ID),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -93,14 +93,8 @@ impl Overlays {
|
||||
menu.rect = Some(placed.rect);
|
||||
|
||||
let hover_bg = palette.hover;
|
||||
let err_bg = palette
|
||||
.theme
|
||||
.css_var("--affine-background-error-color")
|
||||
.unwrap_or(ui::rgb(0xfee2e2).into());
|
||||
let err_fg = palette
|
||||
.theme
|
||||
.css_var("--affine-error-color")
|
||||
.unwrap_or(ui::rgb(0xeb4335).into());
|
||||
let err_bg = palette.error_background;
|
||||
let err_fg = palette.error;
|
||||
|
||||
let make_toggle_row = |suffix: &'static str,
|
||||
icon_name: Option<&'static str>,
|
||||
@@ -139,7 +133,7 @@ impl Overlays {
|
||||
.child(div().flex_1())
|
||||
.child(toggle_switch(on, palette))
|
||||
.snapshot(
|
||||
SharedString::from(format!("overlay.code_more_menu.{suffix}")),
|
||||
format_args!("overlay.code_more_menu.{suffix}"),
|
||||
Some("overlay.code_more_menu"),
|
||||
)
|
||||
.snapshot_focused(on)
|
||||
|
||||
@@ -82,10 +82,7 @@ impl Overlays {
|
||||
let chrome = 2.0 * (TOOLBAR_PADDING + POPOVER_BORDER);
|
||||
let hover_bg = palette.hover;
|
||||
let brand_bg = palette.brand.opacity(0.14);
|
||||
let danger = palette
|
||||
.theme
|
||||
.css_var("--affine-error-color")
|
||||
.unwrap_or(palette.icon);
|
||||
let danger = palette.error;
|
||||
let snap_prefix = flow_block.snapshot_id.clone();
|
||||
|
||||
let make_icon_item = |suffix: &'static str,
|
||||
@@ -96,7 +93,7 @@ impl Overlays {
|
||||
cx: &mut Context<V>|
|
||||
-> (f32, Box<dyn FnOnce(bool) -> AnyElement>) {
|
||||
let click_handler = emit(cx, move |_: &ClickEvent| ev.clone());
|
||||
let snap_id = SharedString::from(format!("{snap_prefix}.{suffix}"));
|
||||
let snap_prefix = snap_prefix.clone();
|
||||
let dom_id = SharedString::from(format!("code-touch-{suffix}-{block_id}"));
|
||||
(
|
||||
btn,
|
||||
@@ -117,7 +114,7 @@ impl Overlays {
|
||||
.child(glyph);
|
||||
if fully_visible {
|
||||
el = el
|
||||
.snapshot(snap_id, Some("root.canvas"))
|
||||
.snapshot(format_args!("{snap_prefix}.{suffix}"), Some("root.canvas"))
|
||||
.snapshot_focused(active)
|
||||
.snapshot_text(label);
|
||||
}
|
||||
@@ -134,7 +131,7 @@ impl Overlays {
|
||||
let lang_w = 80.0_f32;
|
||||
let lang_ev = OverlayEvent::OpenCodeLangPicker(block_id.to_string());
|
||||
let click_handler = emit(cx, move |_: &ClickEvent| lang_ev.clone());
|
||||
let snap_id = SharedString::from(format!("{snap_prefix}.language"));
|
||||
let snap_prefix = snap_prefix.clone();
|
||||
let dom_id = SharedString::from(format!("code-touch-lang-{block_id}"));
|
||||
let text_col = palette.text_primary;
|
||||
let chevron = icon("ArrowDownSmallIcon", 16.0, palette.icon);
|
||||
@@ -163,7 +160,7 @@ impl Overlays {
|
||||
.child(chevron);
|
||||
if fully_visible {
|
||||
el = el
|
||||
.snapshot(snap_id, Some("root.canvas"))
|
||||
.snapshot(format_args!("{snap_prefix}.language"), Some("root.canvas"))
|
||||
.snapshot_text(lang_display);
|
||||
}
|
||||
el.into_any_element()
|
||||
@@ -177,7 +174,7 @@ impl Overlays {
|
||||
let preview_label = if in_preview { "Code" } else { "Preview" };
|
||||
let preview_ev = OverlayEvent::ToggleCodePreview(block_id.to_string());
|
||||
let click_handler = emit(cx, move |_: &ClickEvent| preview_ev.clone());
|
||||
let snap_id = SharedString::from(format!("{snap_prefix}.preview"));
|
||||
let snap_prefix = snap_prefix.clone();
|
||||
let dom_id = SharedString::from(format!("code-touch-preview-{block_id}"));
|
||||
let text_col = if in_preview {
|
||||
palette.brand
|
||||
@@ -207,7 +204,7 @@ impl Overlays {
|
||||
.child(preview_label);
|
||||
if fully_visible {
|
||||
el = el
|
||||
.snapshot(snap_id, Some("root.canvas"))
|
||||
.snapshot(format_args!("{snap_prefix}.preview"), Some("root.canvas"))
|
||||
.snapshot_focused(in_preview)
|
||||
.snapshot_text(preview_label);
|
||||
}
|
||||
@@ -353,10 +350,7 @@ impl Overlays {
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap(px(gap))
|
||||
.snapshot(
|
||||
SharedString::from(format!("{snap_prefix}.toolbar")),
|
||||
Some("root.canvas"),
|
||||
)
|
||||
.snapshot(format_args!("{snap_prefix}.toolbar"), Some("root.canvas"))
|
||||
.child(strip);
|
||||
|
||||
if !scene.page_readonly {
|
||||
@@ -377,10 +371,7 @@ impl Overlays {
|
||||
.hover(move |s| s.bg(hover_bg))
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(emit(cx, move |_: &ClickEvent| del_ev.clone()))
|
||||
.snapshot(
|
||||
SharedString::from(format!("{snap_prefix}.delete")),
|
||||
Some("root.canvas"),
|
||||
)
|
||||
.snapshot(format_args!("{snap_prefix}.delete"), Some("root.canvas"))
|
||||
.snapshot_text("Delete")
|
||||
.child(icon("DeleteIcon", 16.0, danger));
|
||||
root = root
|
||||
|
||||
@@ -62,13 +62,6 @@ impl ScrollAxis {
|
||||
}
|
||||
}
|
||||
|
||||
/// Update the maximum scroll bound and clamp the current offset.
|
||||
#[inline]
|
||||
pub fn set_max(&mut self, max: f32) {
|
||||
self.max = max.max(0.0);
|
||||
self.offset = self.offset.clamp(0.0, self.max);
|
||||
}
|
||||
|
||||
/// Apply a signed scroll `delta`, returning `(consumed_delta, remaining_delta)`.
|
||||
///
|
||||
/// Never rounds `self.offset` and never discards subpixel deltas.
|
||||
@@ -91,12 +84,6 @@ impl ScrollAxis {
|
||||
let _ = self.scroll_by(delta);
|
||||
self.offset != prev
|
||||
}
|
||||
|
||||
/// Snap the current offset to the device pixel grid for painting.
|
||||
#[inline]
|
||||
pub fn snapped(&self, scale_factor: f32) -> f32 {
|
||||
snap_device_pixel(self.offset, scale_factor)
|
||||
}
|
||||
}
|
||||
|
||||
/// Locked dominant axis for a precise touch or trackpad scroll gesture.
|
||||
@@ -267,7 +254,7 @@ mod tests {
|
||||
assert!(rem.abs() < 1e-6);
|
||||
}
|
||||
assert!((axis.offset - 5.0).abs() < 1e-5);
|
||||
assert_eq!(axis.snapped(2.0), 5.0);
|
||||
assert_eq!(snap_device_pixel(axis.offset, 2.0), 5.0);
|
||||
|
||||
// Mixed subpixel sequence sums exactly.
|
||||
let mut sum_axis = ScrollAxis::new(0.0, 500.0);
|
||||
|
||||
@@ -369,6 +369,12 @@ pub struct Palette {
|
||||
pub edgeless_grid: Hsla,
|
||||
/// `--affine-pure-white`, ink on saturated presence colors.
|
||||
pub on_accent: Hsla,
|
||||
/// `--affine-error-color`, destructive actions.
|
||||
pub error: Hsla,
|
||||
/// `--affine-background-error-color`, the hover fill of destructive actions.
|
||||
pub error_background: Hsla,
|
||||
/// `--affine-blue-700`, the keyboard focus ring of list rows.
|
||||
pub focus_ring: Hsla,
|
||||
}
|
||||
|
||||
impl Palette {
|
||||
@@ -395,6 +401,9 @@ impl Palette {
|
||||
card_border: var("--affine-v2-layer-background-tertiary", tokens.border),
|
||||
edgeless_grid: hsla(tokens.edgeless_grid),
|
||||
on_accent: var("--affine-pure-white", tokens::Rgba::new(255, 255, 255, 255)),
|
||||
error: var("--affine-error-color", tokens.icon),
|
||||
error_background: var("--affine-background-error-color", tokens.hover),
|
||||
focus_ring: var("--affine-blue-700", tokens.primary),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -606,6 +615,30 @@ mod tests {
|
||||
assert_ne!(light.palette().background, dark.palette().background);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn palette_semantic_colors_match_their_tokens_in_both_themes() {
|
||||
let rgba = |r, g, b| hsla(tokens::Rgba::new(r, g, b, 255));
|
||||
for (theme, error, error_background, focus_ring) in [
|
||||
(
|
||||
PlaygroundTheme::Light,
|
||||
rgba(235, 67, 53),
|
||||
rgba(253, 236, 235),
|
||||
rgba(28, 129, 217),
|
||||
),
|
||||
(
|
||||
PlaygroundTheme::Dark,
|
||||
rgba(188, 54, 42),
|
||||
rgba(46, 26, 24),
|
||||
rgba(55, 106, 154),
|
||||
),
|
||||
] {
|
||||
let palette = theme.palette();
|
||||
assert_eq!(palette.error, error, "{theme:?}");
|
||||
assert_eq!(palette.error_background, error_background, "{theme:?}");
|
||||
assert_eq!(palette.focus_ring, focus_ring, "{theme:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shadow_tokens_expose_compile_time_layers_with_exact_semantics() {
|
||||
let light = PlaygroundTheme::Light;
|
||||
|
||||
@@ -285,13 +285,12 @@ impl PlaygroundView {
|
||||
if !horizontal_consumed
|
||||
&& let Some((snapshot, layout)) = self.snapshot.clone().zip(self.flow_layout())
|
||||
{
|
||||
let local_collapsed = self.flow.local_collapsed.clone();
|
||||
let scene = self.overlay_scene(
|
||||
&snapshot,
|
||||
&layout,
|
||||
window.layout_direction(),
|
||||
None,
|
||||
&local_collapsed,
|
||||
&self.flow.local_collapsed,
|
||||
);
|
||||
let outcome = self.overlays.scroll_code_split(
|
||||
&scene,
|
||||
|
||||
@@ -495,13 +495,12 @@ impl PlaygroundView {
|
||||
let geom = self.current_page_geometry(self.window_size.0);
|
||||
let sx = geom.column_x + block.x + block.body.width * 0.5;
|
||||
let sy = TOPBAR_HEIGHT + block.y + block.body.height * 0.5 - self.scroll_y;
|
||||
let local_collapsed = self.flow.local_collapsed.clone();
|
||||
let scene = self.overlay_scene(
|
||||
&snap,
|
||||
&layout,
|
||||
window.layout_direction(),
|
||||
None,
|
||||
&local_collapsed,
|
||||
&self.flow.local_collapsed,
|
||||
);
|
||||
self.overlays.scroll_code(&scene, sx, sy, -delta, 0.0)
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user