When to Use
Use the low-level Element trait when:
- Need fine-grained control over layout calculation
- Building complex, performance-critical components
- Implementing custom layout algorithms (masonry, circular, etc.)
- High-level
Render/RenderOnce APIs are insufficient
Prefer Render/RenderOnce for: Simple components, standard layouts, declarative UI
Quick Start
The Element trait provides direct control over three rendering phases:
impl Element for MyElement {
type RequestLayoutState = MyLayoutState; // Data passed to later phases
type PrepaintState = MyPaintState; // Data for painting
fn id(&self) -> Option<ElementId> {
Some(self.id.clone())
}
fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
None
}
// Phase 1: Calculate sizes and positions
fn request_layout(&mut self, .., window: &mut Window, cx: &mut App)
-> (LayoutId, Self::RequestLayoutState)
{
let layout_id = window.request_layout(
Style { size: size(px(200.), px(100.)), ..default() },
vec![],
cx
);
(layout_id, MyLayoutState { /* ... */ })
}
// Phase 2: Create hitboxes, prepare for painting
fn prepaint(&mut self, .., bounds: Bounds<Pixels>, layout: &mut Self::RequestLayoutState,
window: &mut Window, cx: &mut App) -> Self::PrepaintState
{
let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
MyPaintState { hitbox }
}
// Phase 3: Render and handle interactions
fn paint(&mut self, .., bounds: Bounds<Pixels>, layout: &mut Self::RequestLayoutState,
paint_state: &mut Self::PrepaintState, window: &mut Window, cx: &mut App)
{
window.paint_quad(paint_quad(bounds, Corners::all(px(4.)), cx.theme().background));
window.on_mouse_event({
let hitbox = paint_state.hitbox.clone();
move |event: &MouseDownEvent, phase, window, cx| {
if hitbox.is_hovered(window) && phase.bubble() {
// Handle interaction
cx.stop_propagation();
}
}
});
}
}
// Enable element to be used as child
impl IntoElement for MyElement {
type Element = Self;
fn into_element(self) -> Self::Element { self }
}
Core Concepts
Three-Phase Rendering
- request_layout: Calculate sizes and positions, return layout ID and state
- prepaint: Create hitboxes, compute final bounds, prepare for painting
- paint: Render element, set up interactions (mouse events, cursor styles)
State Flow
RequestLayoutState → PrepaintState → paint
State flows in one direction through associated types, passed as mutable references between phases.
Key Operations
- Layout:
window.request_layout(style, children, cx) - Create layout node
- Hitboxes:
window.insert_hitbox(bounds, behavior) - Create interaction area
- Painting:
window.paint_quad(...) - Render visual content
- Events:
window.on_mouse_event(handler) - Handle user input
Reference Documentation
Complete API Documentation
- Element Trait API: See api-reference.md
- Associated types, methods, parameters, return values
- Hitbox system, event handling, cursor styles
Implementation Guides
Examples: See examples.md
- Simple text element with highlighting
- Interactive element with selection
- Complex element with child management
Best Practices: See best-practices.md
- State management, performance optimization
- Interaction handling, layout strategies
- Error handling, testing, common pitfalls
Common Patterns: See patterns.md
- Text rendering, container, interactive, composite, scrollable patterns
- Pattern selection guide
Advanced Patterns: See advanced-patterns.md
- Custom layout algorithms (masonry, circular)
- Element composition with traits
- Async updates, memoization, virtual lists
Converted and distributed by TomeVault | Claim this content
1---2name: gpui-element3description: Implementing custom elements using GPUI's low-level Element API (vs. high-level Render/RenderOnce APIs). Use when you need maximum control over layout, prepaint, and paint phases for complex, performance-critical custom UI components that cannot be achieved with Render/RenderOnce traits.4metadata:5 source: https://skillmd.com/skills/mahabdalla/gpui-element6---78## When to Use910Use the low-level `Element` trait when:11- Need fine-grained control over layout calculation12- Building complex, performance-critical components13- Implementing custom layout algorithms (masonry, circular, etc.)14- High-level `Render`/`RenderOnce` APIs are insufficient1516**Prefer `Render`/`RenderOnce` for:** Simple components, standard layouts, declarative UI1718## Quick Start1920The `Element` trait provides direct control over three rendering phases:2122```rust23impl Element for MyElement {24 type RequestLayoutState = MyLayoutState; // Data passed to later phases25 type PrepaintState = MyPaintState; // Data for painting2627 fn id(&self) -> Option<ElementId> {28 Some(self.id.clone())29 }3031 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {32 None33 }3435 // Phase 1: Calculate sizes and positions36 fn request_layout(&mut self, .., window: &mut Window, cx: &mut App)37 -> (LayoutId, Self::RequestLayoutState)38 {39 let layout_id = window.request_layout(40 Style { size: size(px(200.), px(100.)), ..default() },41 vec![],42 cx43 );44 (layout_id, MyLayoutState { /* ... */ })45 }4647 // Phase 2: Create hitboxes, prepare for painting48 fn prepaint(&mut self, .., bounds: Bounds<Pixels>, layout: &mut Self::RequestLayoutState,49 window: &mut Window, cx: &mut App) -> Self::PrepaintState50 {51 let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);52 MyPaintState { hitbox }53 }5455 // Phase 3: Render and handle interactions56 fn paint(&mut self, .., bounds: Bounds<Pixels>, layout: &mut Self::RequestLayoutState,57 paint_state: &mut Self::PrepaintState, window: &mut Window, cx: &mut App)58 {59 window.paint_quad(paint_quad(bounds, Corners::all(px(4.)), cx.theme().background));6061 window.on_mouse_event({62 let hitbox = paint_state.hitbox.clone();63 move |event: &MouseDownEvent, phase, window, cx| {64 if hitbox.is_hovered(window) && phase.bubble() {65 // Handle interaction66 cx.stop_propagation();67 }68 }69 });70 }71}7273// Enable element to be used as child74impl IntoElement for MyElement {75 type Element = Self;76 fn into_element(self) -> Self::Element { self }77}78```7980## Core Concepts8182### Three-Phase Rendering83841. **request_layout**: Calculate sizes and positions, return layout ID and state852. **prepaint**: Create hitboxes, compute final bounds, prepare for painting863. **paint**: Render element, set up interactions (mouse events, cursor styles)8788### State Flow8990```91RequestLayoutState → PrepaintState → paint92```9394State flows in one direction through associated types, passed as mutable references between phases.9596### Key Operations9798- **Layout**: `window.request_layout(style, children, cx)` - Create layout node99- **Hitboxes**: `window.insert_hitbox(bounds, behavior)` - Create interaction area100- **Painting**: `window.paint_quad(...)` - Render visual content101- **Events**: `window.on_mouse_event(handler)` - Handle user input102103## Reference Documentation104105### Complete API Documentation106- **Element Trait API**: See [api-reference.md](references/api-reference.md)107 - Associated types, methods, parameters, return values108 - Hitbox system, event handling, cursor styles109110### Implementation Guides111- **Examples**: See [examples.md](references/examples.md)112 - Simple text element with highlighting113 - Interactive element with selection114 - Complex element with child management115116- **Best Practices**: See [best-practices.md](references/best-practices.md)117 - State management, performance optimization118 - Interaction handling, layout strategies119 - Error handling, testing, common pitfalls120121- **Common Patterns**: See [patterns.md](references/patterns.md)122 - Text rendering, container, interactive, composite, scrollable patterns123 - Pattern selection guide124125- **Advanced Patterns**: See [advanced-patterns.md](references/advanced-patterns.md)126 - Custom layout algorithms (masonry, circular)127 - Element composition with traits128 - Async updates, memoization, virtual lists129130---131> Converted and distributed by [TomeVault](https://tomevault.io) | [Claim this content](https://tomevault.io/claim/longbridge/gpui-component)