Reduce render allocations and redundant work in core components

This commit is contained in:
2026-11-09 14:35:15 +07:00
parent 73f7dc31d4
commit 122f9b12ae
19 changed files with 174 additions and 139 deletions
+1 -1
View File
@@ -304,7 +304,7 @@ impl RenderOnce for AlertsView {
let theme = cx.theme();
let enter_duration = theme.motion.overlay;
let entries: Vec<AlertEntry> = self.alerts.read(cx).entries().to_vec();
let entries = self.alerts.read(cx).entries();
deferred(
div()
+4 -4
View File
@@ -604,8 +604,8 @@ where
div()
.id(("option", row))
.debug_selector({
let name = format!("{id}-option-{row}");
move || name
let id = id.clone();
move || format!("{id}-option-{row}")
})
.flex()
.items_center()
@@ -681,8 +681,8 @@ where
let panel = v_flex()
.id((id.clone(), "panel"))
.debug_selector({
let name = format!("{id}-panel");
move || name
let id = id.clone();
move || format!("{id}-panel")
})
.w(popup_width)
.p_1()
+4 -4
View File
@@ -335,8 +335,8 @@ impl Render for CommandPaletteState {
h_flex()
.id(("command", row))
.debug_selector({
let name = format!("{id}-command-{row}");
move || name
let id = id.clone();
move || format!("{id}-command-{row}")
})
.gap_2()
.px_2()
@@ -409,8 +409,8 @@ impl Render for CommandPaletteState {
let panel = v_flex()
.id((id.clone(), "panel"))
.debug_selector({
let name = format!("{id}-panel");
move || name
let id = id.clone();
move || format!("{id}-panel")
})
.key_context(COMMAND_PALETTE_CONTEXT)
.role(Role::Dialog)
+3 -3
View File
@@ -422,10 +422,10 @@ impl RenderOnce for DropdownMenu {
let items = if self.open {
self.items
.map(|build| build(window, cx))
.unwrap_or_default()
.map(|build| Rc::from(build(window, cx)))
.unwrap_or_else(|| Rc::from([]))
} else {
Vec::new()
Rc::from([])
};
if let Some(panel) = anchored_menu_panel(
+6 -6
View File
@@ -95,8 +95,8 @@ impl RenderOnce for Field {
let title = div()
.debug_selector({
let name = format!("{id}-label");
move || name
let id = id.clone();
move || format!("{id}-label")
})
.text_size(metrics.text_size)
.child(self.label.clone());
@@ -105,16 +105,16 @@ impl RenderOnce for Field {
.items_center()
.gap_2()
.debug_selector({
let name = format!("{id}-control");
move || name
let id = id.clone();
move || format!("{id}-control")
})
.children(self.control);
let error = self.error.map(|error| {
div()
.debug_selector({
let name = format!("{id}-error");
move || name
let id = id.clone();
move || format!("{id}-error")
})
.text_size(metrics.caption_size)
.text_color(error_color)
+5 -1
View File
@@ -2051,7 +2051,11 @@ impl RenderOnce for Input {
canvas
.with_animation(
animation_id,
Animation::new(CARET_BLINK_INTERVAL * 2).repeat(),
// The blink needs four repaints per period,
// not the display's refresh rate.
Animation::new(CARET_BLINK_INTERVAL * 2)
.repeat()
.with_max_fps(4.0),
|canvas, _| canvas,
)
.into_any_element()
+4 -4
View File
@@ -336,11 +336,11 @@ impl RenderOnce for Menu {
let items = if self.open {
match self.items {
Some(build) => build(window, cx),
None => Vec::new(),
Some(build) => Rc::from(build(window, cx)),
None => Rc::from([]),
}
} else {
Vec::new()
Rc::from([])
};
if let Some(panel) = anchored_menu_panel(
@@ -372,7 +372,7 @@ pub(crate) fn anchored_menu_panel(
cx: &mut App,
id: &ElementId,
open: bool,
items: Vec<MenuItem>,
items: Rc<[MenuItem]>,
initial_selection: Option<usize>,
preselect: bool,
on_change: Option<ChangeHandler>,
+26 -20
View File
@@ -9,7 +9,7 @@ use gpui::{
};
use gpui_native_icons::{IconRole, icon};
use gpui_native_theme::{ActiveTheme as _, Size};
use gpui_native_utils::{adjacent_selectable, focus_handle, focus_ring};
use gpui_native_utils::{focus_handle, focus_ring};
use crate::common::{Sizable, StyledExt, h_flex};
@@ -64,7 +64,8 @@ where
T: Clone + PartialEq + 'static,
{
id: ElementId,
options: Vec<SegmentedOption<T>>,
/// Shared with the per-segment and key handlers, so captures are bumps.
options: Rc<[SegmentedOption<T>]>,
selected: T,
a11y_label: Option<SharedString>,
size: Size,
@@ -82,7 +83,7 @@ where
{
Self {
id: id.into(),
options: Vec::new(),
options: Rc::from([]),
selected,
a11y_label: None,
size: Size::Small,
@@ -163,12 +164,12 @@ where
.options
.iter()
.position(|segment| segment.value == self.selected);
let option_count = self.options.len();
let selectable: Vec<usize> = (0..self.options.len()).collect();
let on_change = self.on_change.clone();
let key_on_change = on_change.clone();
let key_options = self.options.clone();
let key_selectable = selectable.clone();
let options = self.options.clone();
let label = self
.a11y_label
@@ -176,14 +177,13 @@ where
.unwrap_or_else(|| SharedString::from(self.id.to_string()));
window.with_element_namespace(self.id.clone(), |window| {
let focus = focus_handle(&self.id, window, cx);
let geometry: Entity<Vec<Option<Bounds<gpui::Pixels>>>> =
window.use_keyed_state("segmented-geometry", cx, |_, _| Vec::new());
let track_origin: Entity<Option<Point<gpui::Pixels>>> =
window.use_keyed_state("segmented-track-origin", cx, |_, _| None);
let focus = focus_handle(&self.id, window, cx);
let anim_config = SpringConfig::new(500., 35., 1.);
let track_point = *track_origin.read(cx);
@@ -197,12 +197,13 @@ where
let segments = self
.options
.into_iter()
.iter()
.enumerate()
.map(move |(index, segment)| {
let is_selected = Some(index) == selected_index;
let on_change = on_change.clone();
let value = segment.value;
let options = options.clone();
let content_color = if is_selected {
foreground
} else {
@@ -228,7 +229,7 @@ where
.when_some(segment.icon, |segment, role| {
segment.child(icon(role).size(icon_size).color(content_color))
})
.child(segment.label)
.child(segment.label.clone())
.child(
canvas(
{
@@ -251,8 +252,9 @@ where
move |_, window, cx| {
if Some(index) != selected_index
&& let Some(on_change) = &on_change
&& let Some(option) = options.get(index)
{
on_change(value.clone(), window, cx);
on_change(option.value.clone(), window, cx);
}
}
})
@@ -319,22 +321,26 @@ where
.on_key_down({
move |event: &KeyDownEvent, window, cx| {
let target = match event.keystroke.key.as_str() {
"right" => {
adjacent_selectable(&key_selectable, selected_index, true)
}
"left" => {
adjacent_selectable(&key_selectable, selected_index, false)
}
"home" => key_selectable.first().copied(),
"end" => key_selectable.last().copied(),
"right" => match selected_index {
Some(index) => {
index.checked_add(1).filter(|next| *next < option_count)
}
None => (option_count > 0).then_some(0),
},
"left" => selected_index.and_then(|index| index.checked_sub(1)),
"home" => (option_count > 0).then_some(0),
"end" => option_count.checked_sub(1),
_ => return,
};
if let Some(next) = target
&& Some(next) != selected_index
&& let Some(on_change) = &key_on_change
&& let Some(option) = key_options.get(next)
{
on_change(key_options[next].value.clone(), window, cx);
on_change(option.value.clone(), window, cx);
}
cx.stop_propagation();
}
})
+9 -15
View File
@@ -206,24 +206,18 @@ where
.position(|option| &option.value == value)
});
let trigger_options = self.options.clone();
let trigger_selected = self.selected.clone();
let trigger_placeholder = self.placeholder.clone();
// The trigger's text is fixed at render time; only it moves into the closure.
let trigger_text = selected_index
.and_then(|index| self.options.get(index))
.map(|option| option.label.clone())
.unwrap_or_else(|| self.placeholder.clone());
let trigger_has_value = self.selected.is_some();
let trigger_id = self.id.clone();
let trigger_label = label.clone();
let trigger_style = self.style;
let trigger = move |_window: &mut Window, _cx: &mut App| {
let text = trigger_selected
.as_ref()
.and_then(|value| {
trigger_options
.iter()
.find(|option| &option.value == value)
.map(|option| option.label.clone())
})
.unwrap_or_else(|| trigger_placeholder.clone());
h_flex()
.id((trigger_id.clone(), "select-trigger"))
.debug_selector(|| "select-trigger".to_string())
@@ -240,7 +234,7 @@ where
.border_color(rest_border)
.bg(input)
.text_size(metrics.text_size)
.text_color(if trigger_selected.is_some() {
.text_color(if trigger_has_value {
foreground
} else {
muted_foreground
@@ -249,7 +243,7 @@ where
trigger.shadow(focus_ring(ring))
})
.hover(|style| style.bg(muted).border_color(hover_border))
.child(text)
.child(trigger_text.clone())
.child(
icon(IconRole::ChevronDown)
.size(icon_size)
+1 -4
View File
@@ -133,10 +133,7 @@ impl RenderOnce for Switch {
div()
.flex_none()
.relative()
.debug_selector({
let name = format!("{id}-track");
move || name
})
.debug_selector(move || format!("{id}-track"))
.w(track_width)
.h(track_height)
.rounded(theme.radius.full)
+9 -7
View File
@@ -34,8 +34,8 @@ impl Tooltip {
{
let text = text.into();
let anchor_id = anchor_id.into();
move |_window, cx| {
let anchor = anchor_bounds(&anchor_id, cx);
move |window, cx| {
let anchor = anchor_bounds(window.window_handle().window_id(), &anchor_id, cx);
cx.new(|_| Self {
text: text.clone(),
anchor,
@@ -92,11 +92,13 @@ impl Render for Tooltip {
let origin = window.mouse_position() + point(px(1.), px(1.));
let viewport_height = window.viewport_size().height;
let height = anchor_bounds(&ElementId::from(PANEL_BOUNDS_ID), cx)
.map(|bounds| bounds.size.height)
.unwrap_or_else(|| {
text_size * 1.5 + window.rem_size() * 0.5 + BORDER_WIDTH * 2.0
});
let height = anchor_bounds(
window.window_handle().window_id(),
&ElementId::from(PANEL_BOUNDS_ID),
cx,
)
.map(|bounds| bounds.size.height)
.unwrap_or_else(|| text_size * 1.5 + window.rem_size() * 0.5 + BORDER_WIDTH * 2.0);
let below = viewport_height - spacing_unit - parent.bottom();
let above = parent.top() - spacing_unit;
+37 -8
View File
@@ -1,3 +1,5 @@
use std::{cell::Cell, rc::Rc, time::Duration};
use gpui::{
AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, SharedString,
Styled as _, TestAppContext, VisualTestContext, Window, div,
@@ -9,10 +11,12 @@ use gpui_native_core::input::{Input, InputState};
struct FieldHost {
url: Entity<InputState>,
renders: Rc<Cell<usize>>,
}
impl Render for FieldHost {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.renders.set(self.renders.get() + 1);
let url_error = self
.url
.read(cx)
@@ -34,15 +38,27 @@ impl Render for FieldHost {
/// A field page in a real window; the url input is focused unless
/// `focus` is false, which leaves the page truly idle.
fn field_host(focus: bool) -> (TestAppContext, Entity<InputState>, VisualTestContext) {
fn field_host(
focus: bool,
) -> (
TestAppContext,
Entity<InputState>,
VisualTestContext,
Rc<Cell<usize>>,
) {
let cx = TestAppContext::single();
cx.update(init);
let renders = Rc::new(Cell::new(0));
let renders_for_host = renders.clone();
let (url, window) = cx.update(|cx| {
let url = InputState::new(cx);
let url_for_host = url.clone();
let window = cx
.open_window(gpui::WindowOptions::default(), |_, cx| {
cx.new(|_| FieldHost { url: url_for_host })
cx.new(|_| FieldHost {
url: url_for_host,
renders: renders_for_host.clone(),
})
})
.unwrap();
(url, window)
@@ -55,12 +71,12 @@ fn field_host(focus: bool) -> (TestAppContext, Entity<InputState>, VisualTestCon
}
window.draw(cx).clear(cx);
});
(cx, url, visual)
(cx, url, visual, renders)
}
#[test]
fn an_idle_field_page_schedules_no_frames() {
let (_cx, _url, mut visual) = field_host(false);
let (_cx, _url, mut visual, _renders) = field_host(false);
let frames = visual.update(|window, cx| window.simulate_next_frame(cx));
assert_eq!(
frames, 0,
@@ -68,12 +84,25 @@ fn an_idle_field_page_schedules_no_frames() {
);
}
/// The caret blink is fps-capped: it must never demand a next frame, and its
/// redraws arrive on the executor timer at the blink cadence.
#[test]
fn a_focused_field_page_schedules_frames_for_its_blink() {
let (_cx, _url, mut visual) = field_host(true);
fn a_focused_field_blink_is_fps_capped_and_still_redraws() {
let (cx, _url, mut visual, renders) = field_host(true);
let renders_after_focus = renders.get();
let frames = visual.update(|window, cx| window.simulate_next_frame(cx));
assert_eq!(
frames, 0,
"the blink must be fps-capped, not per-frame scheduled"
);
// The blink redraws through the executor timer (4 fps cap).
cx.executor().advance_clock(Duration::from_millis(251));
cx.run_until_parked();
visual.update(|window, cx| window.draw(cx).clear(cx));
assert!(
frames > 0,
"the focused caret's blink needs frames to redraw at the blink cadence"
renders.get() > renders_after_focus,
"the capped blink must still redraw its page"
);
}