Skip to main content

gpui_base/
element_ext.rs

1use gpui::{
2    App, Bounds, ElementId, IntoElement, ParentElement, Pixels, Styled as _, Window, canvas,
3};
4
5use crate::TextSelectionScopeId;
6
7/// Extends a GPUI parent element with post-layout prepaint observation.
8pub trait ElementExt: ParentElement + Sized {
9    /// Marks this element subtree as belonging to a text-selection scope.
10    fn text_selection_scope(self, scope: TextSelectionScopeId) -> impl IntoElement
11    where
12        Self: IntoElement,
13    {
14        crate::text_selection::text_selection_scope(scope, self)
15    }
16
17    /// Keeps the window's text selection when this element is pressed, for
18    /// one that acts on the selection, such as a button beside it: pressing
19    /// anywhere on it neither clears the selection nor starts a new one, so
20    /// its click still finds the selection. `id` must be unique among this
21    /// element's children. Works inside a cached view.
22    ///
23    /// The window remembers each element marked this way until it closes, so
24    /// mark the row of buttons, not each row of a long list.
25    fn keep_text_selection(self, id: impl Into<ElementId>) -> Self {
26        self.child(crate::text_selection::keep_text_selection(id.into()))
27    }
28
29    /// Invokes `callback` during prepaint with this element's resolved bounds.
30    fn on_prepaint<F>(self, callback: F) -> Self
31    where
32        F: FnOnce(Bounds<Pixels>, &mut Window, &mut App) + 'static,
33    {
34        self.child(
35            canvas(
36                move |bounds, window, cx| callback(bounds, window, cx),
37                |_, _, _, _| {},
38            )
39            // Without an inset, an absolute child starts after the padding but
40            // is still sized to the padding box, overhanging the far edges.
41            .absolute()
42            .top_0()
43            .left_0()
44            .size_full(),
45        )
46    }
47}
48
49impl<T: ParentElement> ElementExt for T {}