bite-gpui-ce 0.20260928.0

A community fork of Zed's GPU-accelerated UI framework
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
//! Creating Components Example
//!
//! This example demonstrates three different approaches to creating interactive
//! stateful components in GPUI:
//!
//! 1. `use_state` - Hook-like state scoped to an element's lifetime
//! 2. `RenderOnce` - Stateless component that receives state from parent
//! 3. `Render` - Entity-backed view with persistent internal state

#[path = "../shared/prelude.rs"]
mod example_prelude;

use example_prelude::init_example;
use gpui::colors::Colors;
use gpui::{
    App, Bounds, Context, Entity, IntoElement, Render, RenderOnce, Window, WindowBounds,
    WindowOptions, div, prelude::*, px, rgb, size,
};

// ============================================================================
// Approach 1: use_state
// ============================================================================
//
// `use_state` creates element-scoped state that persists across renders.
// It's similar to React's useState hook. The state is automatically tied
// to the element's identity via caller location or a provided key.
//
// Pros:
// - Simple, hook-like API
// - State is scoped to element lifetime
// - No boilerplate for simple state
//
// Cons:
// - Less explicit than Entity-backed state
// - State is tied to call site location

struct UseStateCounter {
    count: i32,
}

fn use_state_counter(colors: &Colors, window: &mut Window, cx: &mut App) -> impl IntoElement {
    let state: Entity<UseStateCounter> =
        window.use_state(cx, |_window, _cx| UseStateCounter { count: 0 });

    let count = state.read(cx).count;

    let error = rgb(0xd32f2f);
    let error_hover = rgb(0xe04545);
    let success = rgb(0x388e3c);
    let success_hover = rgb(0x43a047);

    div()
        .id("use-state-counter")
        .flex()
        .flex_col()
        .gap_2()
        .p_4()
        .rounded_lg()
        .bg(colors.container)
        .child(
            div()
                .text_sm()
                .text_color(colors.disabled)
                .child("use_state Counter"),
        )
        .child(
            div()
                .text_2xl()
                .text_color(colors.text)
                .child(format!("{}", count)),
        )
        .child(
            div()
                .flex()
                .gap_2()
                .child(
                    div()
                        .id("use-state-decrement")
                        .px_3()
                        .py_1()
                        .rounded_md()
                        .bg(error)
                        .text_color(colors.selected_text)
                        .cursor_pointer()
                        .hover(move |style| style.bg(error_hover))
                        .child("−")
                        .on_click({
                            let state = state.clone();
                            move |_, _, cx| {
                                state.update(cx, |state, cx| {
                                    state.count -= 1;
                                    cx.notify();
                                });
                            }
                        }),
                )
                .child(
                    div()
                        .id("use-state-increment")
                        .px_3()
                        .py_1()
                        .rounded_md()
                        .bg(success)
                        .text_color(colors.selected_text)
                        .cursor_pointer()
                        .hover(move |style| style.bg(success_hover))
                        .child("+")
                        .on_click(move |_, _, cx| {
                            state.update(cx, |state, cx| {
                                state.count += 1;
                                cx.notify();
                            });
                        }),
                ),
        )
}

// ============================================================================
// Approach 2: RenderOnce
// ============================================================================
//
// `RenderOnce` components are stateless and consumed when rendered.
// They receive all data as props and delegate state management to the parent.
// This is the recommended approach for presentational components.
//
// Pros:
// - Clear data flow (props down, events up)
// - Lightweight (no Entity allocation)
// - Easy to test
// - Highly composable
//
// Cons:
// - Cannot maintain internal state
// - Parent must manage all state

#[derive(IntoElement)]
struct RenderOnceCounter {
    colors: Colors,
    count: i32,
    on_increment: Option<Box<dyn Fn(&mut Window, &mut App) + 'static>>,
    on_decrement: Option<Box<dyn Fn(&mut Window, &mut App) + 'static>>,
}

impl RenderOnceCounter {
    fn new(colors: Colors, count: i32) -> Self {
        Self {
            colors,
            count,
            on_increment: None,
            on_decrement: None,
        }
    }

    fn on_increment(mut self, callback: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.on_increment = Some(Box::new(callback));
        self
    }

    fn on_decrement(mut self, callback: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.on_decrement = Some(Box::new(callback));
        self
    }
}

impl RenderOnce for RenderOnceCounter {
    fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
        let colors = self.colors;
        let error = rgb(0xd32f2f);
        let error_hover = rgb(0xe04545);
        let success = rgb(0x388e3c);
        let success_hover = rgb(0x43a047);

        div()
            .id("render-once-counter")
            .flex()
            .flex_col()
            .gap_2()
            .p_4()
            .rounded_lg()
            .bg(colors.container)
            .child(
                div()
                    .text_sm()
                    .text_color(colors.disabled)
                    .child("RenderOnce Counter"),
            )
            .child(
                div()
                    .text_2xl()
                    .text_color(colors.text)
                    .child(format!("{}", self.count)),
            )
            .child(
                div()
                    .flex()
                    .gap_2()
                    .child(
                        div()
                            .id("render-once-decrement")
                            .px_3()
                            .py_1()
                            .rounded_md()
                            .bg(error)
                            .text_color(colors.selected_text)
                            .cursor_pointer()
                            .hover(move |style| style.bg(error_hover))
                            .child("−")
                            .when_some(self.on_decrement, |element, callback| {
                                element.on_click(move |_, window, cx| callback(window, cx))
                            }),
                    )
                    .child(
                        div()
                            .id("render-once-increment")
                            .px_3()
                            .py_1()
                            .rounded_md()
                            .bg(success)
                            .text_color(colors.selected_text)
                            .cursor_pointer()
                            .hover(move |style| style.bg(success_hover))
                            .child("+")
                            .when_some(self.on_increment, |element, callback| {
                                element.on_click(move |_, window, cx| callback(window, cx))
                            }),
                    ),
            )
    }
}

// ============================================================================
// Approach 3: Render (Entity-backed)
// ============================================================================
//
// `Render` components are backed by an `Entity<T>` and maintain their own
// internal state. This is the recommended approach for complex components
// that need to manage their own state, subscribe to events, or spawn tasks.
//
// Pros:
// - Full control over internal state
// - Can subscribe to events and observe other entities
// - Can spawn async tasks
// - Has identity (can be passed around as Entity<T>)
//
// Cons:
// - More boilerplate
// - Higher memory overhead
// - More complex lifecycle

struct RenderCounter {
    count: i32,
}

impl RenderCounter {
    fn new() -> Self {
        Self { count: 0 }
    }

    fn increment(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
        self.count += 1;
        cx.notify();
    }

    fn decrement(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
        self.count -= 1;
        cx.notify();
    }
}

impl Render for RenderCounter {
    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let colors = Colors::for_appearance(window);
        let error = rgb(0xd32f2f);
        let error_hover = rgb(0xe04545);
        let success = rgb(0x388e3c);
        let success_hover = rgb(0x43a047);

        div()
            .id("render-counter")
            .flex()
            .flex_col()
            .gap_2()
            .p_4()
            .rounded_lg()
            .bg(colors.container)
            .child(
                div()
                    .text_sm()
                    .text_color(colors.disabled)
                    .child("Render Counter"),
            )
            .child(
                div()
                    .text_2xl()
                    .text_color(colors.text)
                    .child(format!("{}", self.count)),
            )
            .child(
                div()
                    .flex()
                    .gap_2()
                    .child(
                        div()
                            .id("render-decrement")
                            .px_3()
                            .py_1()
                            .rounded_md()
                            .bg(error)
                            .text_color(colors.selected_text)
                            .cursor_pointer()
                            .hover(move |style| style.bg(error_hover))
                            .child("−")
                            .on_click(cx.listener(|this, _, window, cx| {
                                this.decrement(window, cx);
                            })),
                    )
                    .child(
                        div()
                            .id("render-increment")
                            .px_3()
                            .py_1()
                            .rounded_md()
                            .bg(success)
                            .text_color(colors.selected_text)
                            .cursor_pointer()
                            .hover(move |style| style.bg(success_hover))
                            .child("+")
                            .on_click(cx.listener(|this, _, window, cx| {
                                this.increment(window, cx);
                            })),
                    ),
            )
    }
}

// ============================================================================
// Main Application
// ============================================================================

struct CreatingComponentsExample {
    render_counter: Entity<RenderCounter>,
    render_once_count: i32,
}

impl CreatingComponentsExample {
    fn new(cx: &mut Context<Self>) -> Self {
        Self {
            render_counter: cx.new(|_| RenderCounter::new()),
            render_once_count: 0,
        }
    }
}

impl Render for CreatingComponentsExample {
    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let colors = Colors::for_appearance(window);
        let render_once_count = self.render_once_count;
        let handle = cx.entity().downgrade();

        div()
            .id("main")
            .size_full()
            .flex()
            .flex_col()
            .gap_6()
            .p_8()
            .bg(colors.background)
            .overflow_scroll()
            .child(
                div()
                    .flex()
                    .flex_col()
                    .gap_2()
                    .child(
                        div()
                            .text_2xl()
                            .font_weight(gpui::FontWeight::BOLD)
                            .text_color(colors.text)
                            .child("Creating Components"),
                    )
                    .child(
                        div()
                            .text_sm()
                            .text_color(colors.disabled)
                            .child("Three approaches to stateful components in GPUI"),
                    ),
            )
            .child(
                div()
                    .flex()
                    .flex_row()
                    .gap_4()
                    .child(use_state_counter(&colors, window, cx))
                    .child(
                        RenderOnceCounter::new(colors.clone(), render_once_count)
                            .on_increment({
                                let handle = handle.clone();
                                move |_window, cx| {
                                    handle
                                        .update(cx, |this, cx| {
                                            this.render_once_count += 1;
                                            cx.notify();
                                        })
                                        .ok();
                                }
                            })
                            .on_decrement(move |_window, cx| {
                                handle
                                    .update(cx, |this, cx| {
                                        this.render_once_count -= 1;
                                        cx.notify();
                                    })
                                    .ok();
                            }),
                    )
                    .child(self.render_counter.clone()),
            )
    }
}

fn main() {
    gpui_ce_platform::application().run(|cx: &mut App| {
        let bounds = Bounds::centered(None, size(px(700.), px(400.)), cx);
        cx.open_window(
            WindowOptions {
                window_bounds: Some(WindowBounds::Windowed(bounds)),
                ..Default::default()
            },
            |_, cx| cx.new(|cx| CreatingComponentsExample::new(cx)),
        )
        .expect("Failed to open window");

        init_example(cx, "Creating Components");
    });
}