gpui-cn 0.3.0

shadcn-style components for GPUI, built on gpui-base.
Documentation
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
//! The open menu of a select: the panel, the search field, the rows in a
//! virtual list, and what stands in for them while empty or loading.

use std::rc::Rc;

use gpui_kit::{
    AnyElement, App, ElementId, Entity, FocusHandle, InteractiveElement as _, IntoElement, Length,
    MouseButton, ParentElement as _, Pixels, SharedString, StatefulInteractiveElement as _,
    Styled as _, Window,
    assets::IconName,
    base::{self, TestSupportExt as _, h_flex, v_flex},
    div,
    prelude::FluentBuilder as _,
};

use super::{
    item::{SelectEntry, SelectItem, SelectValue},
    state::SelectState,
};
use crate::{
    Icon, ScrollArea,
    menu::{
        MenuLook, MenuMotion, MenuPanels, TextMenuBuilder, label_block, line_slot, open_text_menu,
        row_line, separator,
    },
    touch_selection,
};

pub(super) type ItemRenderer<V> =
    Rc<dyn Fn(&SelectItem<V>, SelectRow, &mut Window, &mut App) -> AnyElement>;
pub(super) type LabelRenderer = Rc<dyn Fn(&SharedString, &mut Window, &mut App) -> AnyElement>;
pub(super) type PartRenderer = Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>;

/// The state of a row a custom item renderer draws; see
/// [`Select::render_item`](super::Select::render_item).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct SelectRow {
    highlighted: bool,
    selected: bool,
    disabled: bool,
}

impl SelectRow {
    /// Whether the keyboard or the pointer is on the row.
    pub fn is_highlighted(&self) -> bool {
        self.highlighted
    }

    /// Whether the row's item is selected.
    pub fn is_selected(&self) -> bool {
        self.selected
    }

    /// Whether the row's item is disabled.
    pub fn is_disabled(&self) -> bool {
        self.disabled
    }
}

/// What the rows of one menu are drawn from, owned by the list's row
/// builder, which outlives the render that made it.
pub(super) struct Rows<V: SelectValue> {
    pub id: ElementId,
    pub state: Entity<SelectState<V>>,
    pub look: MenuLook,
    pub render_item: Option<ItemRenderer<V>>,
    pub render_label: Option<LabelRenderer>,
    pub pointer_cursors: bool,
}

/// The menu: the search field, the rows in a scroll region, or the empty
/// or loading element.
pub(super) struct Menu<V: SelectValue> {
    pub rows: Rows<V>,
    pub content_focus: FocusHandle,
    pub width: Option<Length>,
    pub trigger_width: Pixels,
    pub empty_text: SharedString,
    pub render_empty: Option<PartRenderer>,
    pub render_loading: Option<PartRenderer>,
    pub motion: MenuMotion,
    /// Shapes the search field's right-click menu, as a field's does.
    pub search_menu_builder: Option<TextMenuBuilder>,
    /// Whether a right click on the search field opens its menu.
    pub search_menu_enabled: bool,
}

impl<V: SelectValue> Menu<V> {
    pub fn render(self, window: &mut Window, cx: &mut App) -> AnyElement {
        let Menu {
            rows,
            content_focus,
            width,
            trigger_width,
            empty_text,
            render_empty,
            render_loading,
            motion,
            search_menu_builder,
            search_menu_enabled,
        } = self;
        let look = rows.look.clone();
        let look = &look;
        let id = rows.id.clone();
        let state = rows.state.clone();
        let (list, row_count, row_hint, searching, search, search_menu) = {
            let state = state.read(cx);
            (
                state.list().clone(),
                state.row_count(),
                state.row_hint(cx),
                state.is_searching(),
                state.search_input().cloned(),
                state.search_menu().cloned(),
            )
        };
        let search_menu_open = search_menu
            .as_ref()
            .is_some_and(|menu| menu.read(cx).is_open());
        let menu_id = ElementId::NamedChild(id.clone().into(), "menu".into());
        let rows_id = ElementId::NamedChild(id.clone().into(), "rows".into());
        let rows_max_height = look.rows_max_height(search.is_some());
        // While a handler is still answering, the loading element stands
        // in for the rows, so what shows is never the answer to an older
        // query beside a promise of the new one. Without one the last rows
        // stay until the answer, and an empty menu shows nothing rather
        // than "No results" it may take back.
        let loading = searching
            .then(|| render_loading.as_ref().map(|render| render(window, cx)))
            .flatten();
        let body = if let Some(loading) = loading {
            loading
        } else if row_count == 0 {
            match (searching, render_empty) {
                (true, _) => div().into_any_element(),
                (false, Some(render)) => render(window, cx),
                (false, None) => div()
                    .py_6()
                    .text_center()
                    .text_color(look.muted_foreground)
                    .child(empty_text)
                    .into_any_element(),
            }
        } else {
            ScrollArea::list(rows_id, &list, row_hint, move |row, window, cx| {
                rows.render(row, window, cx)
            })
            .max_h(rows_max_height)
            .into_any_element()
        };
        v_flex()
            .id(menu_id)
            .test_support()
            .track_focus(&content_focus)
            .tab_group()
            .map(|this| match width {
                Some(width) => this.w(width),
                None => {
                    let min_width = if search.is_some() {
                        look.search_min_width
                    } else {
                        look.min_width
                    };
                    this.min_w(trigger_width.max(min_width))
                        .max_w(look.max_width)
                }
            })
            // The fade sits on the panel itself, since GPUI shapes the
            // shadow from the element that carries it.
            .relative()
            .top(motion.offset)
            .opacity(motion.opacity)
            .p(look.padding)
            .rounded(look.radius)
            .bg(look.surface)
            .border_1()
            .border_color(look.border)
            .shadow(look.shadow(motion.shadow_strength))
            .text_size(look.text_size)
            .line_height(look.line_height)
            .text_color(look.foreground)
            .on_mouse_down_out({
                let state = state.clone();
                let search = search.clone();
                let search_menu = search_menu.clone();
                move |_, window, cx| {
                    // The search box's touch edit menu and its right-click
                    // menu float outside the panel; a press on either is
                    // the search's, not a close.
                    let edit_menu_open = search.as_ref().is_some_and(|search| {
                        search
                            .read(cx)
                            .touch_selection()
                            .is_some_and(|selection| selection.is_menu_open())
                    }) || search_menu
                        .as_ref()
                        .is_some_and(|menu| menu.read(cx).is_open());
                    if !edit_menu_open {
                        state.update(cx, |state, cx| state.close(window, cx));
                    }
                }
            })
            .when_some(search, |this, search| {
                this.child(
                    h_flex()
                        .id(ElementId::NamedChild(id.clone().into(), "search".into()))
                        .test_support()
                        .flex_shrink_0()
                        .items_center()
                        .gap_2()
                        .h(look.search_height)
                        .px(look.row_padding)
                        .child(
                            Icon::from(IconName::Search)
                                .size_4()
                                .text_color(look.muted_foreground),
                        )
                        .child(
                            div()
                                .flex_1()
                                .min_w_0()
                                .child(base::input::Input::new(&search)),
                        )
                        .children(touch_selection::for_state(&search, window, cx))
                        .when_some(search_menu.filter(|_| search_menu_enabled), |this, menu| {
                            let input = search.clone();
                            let opener = menu.clone();
                            this.on_mouse_up(MouseButton::Right, move |event, window, cx| {
                                open_text_menu(
                                    &opener,
                                    &input,
                                    event.position,
                                    search_menu_builder.as_ref(),
                                    window,
                                    cx,
                                );
                            })
                            .when(search_menu_open, |this| {
                                this.child(MenuPanels::new(
                                    ElementId::NamedChild(id.clone().into(), "search-menu".into()),
                                    &menu,
                                ))
                            })
                        }),
                )
                .child(separator(look))
            })
            .child(body)
            .into_any_element()
    }
}

impl<V: SelectValue> Rows<V> {
    fn render(&self, row: usize, window: &mut Window, cx: &mut App) -> AnyElement {
        let Rows {
            id,
            state,
            look,
            render_item,
            render_label,
            pointer_cursors,
        } = self;
        let pointer_cursors = *pointer_cursors;
        let (entry, highlighted, selected, row_height) = {
            let state = state.read(cx);
            let Some(entry) = state.entry_at(row) else {
                return div().into_any_element();
            };
            let selected = entry
                .item()
                .is_some_and(|item| state.is_selected(item.value()));
            (
                entry.clone(),
                state.is_highlighted(row),
                selected,
                state.row_height(),
            )
        };
        match entry {
            SelectEntry::Separator => separator(look),
            SelectEntry::Label(text) => match render_label {
                Some(render) => div()
                    .w_full()
                    .child(render(&text, window, cx))
                    .into_any_element(),
                None => div()
                    .w_full()
                    .h(look.row_height)
                    .px(look.row_padding)
                    .flex()
                    .items_center()
                    .text_color(look.muted_foreground)
                    .child(text)
                    .into_any_element(),
            },
            SelectEntry::Item(item) => {
                let disabled = item.is_disabled();
                let value = item.value().clone();
                let choose_state = state.clone();
                let hover_state = state.clone();
                let content: Vec<AnyElement> = match render_item {
                    Some(render) => vec![render(
                        &item,
                        SelectRow {
                            highlighted,
                            selected,
                            disabled,
                        },
                        window,
                        cx,
                    )],
                    None => default_row_content(
                        &item,
                        &ElementId::NamedChild(id.clone().into(), item.key()),
                        selected,
                        look,
                        window,
                        cx,
                    ),
                };
                h_flex()
                    .id(ElementId::NamedChild(id.clone().into(), item.key()))
                    .test_support()
                    .w_full()
                    .items_center()
                    .gap_2()
                    // A fixed height is what a scroll to a far row counts
                    // on before the row is laid out.
                    .map(|this| match row_height {
                        Some(height) => this.h(height),
                        None => this.min_h(look.row_height),
                    })
                    .px(look.row_padding)
                    .py_1p5()
                    .rounded(look.row_radius)
                    .when(highlighted && !disabled, |this| this.bg(look.accent))
                    .text_color(if disabled {
                        look.muted_foreground
                    } else {
                        look.foreground
                    })
                    .map(|this| {
                        if !disabled && pointer_cursors {
                            this.cursor_pointer()
                        } else {
                            this.cursor_default()
                        }
                    })
                    .children(content)
                    // A pointer that moves over a row highlights it; a row that
                    // scrolls under a resting pointer does not, so the
                    // keyboard's highlight is not snatched back.
                    .on_mouse_move(move |_, _, cx| {
                        hover_state.update(cx, |state, cx| state.highlight_row(row, cx));
                    })
                    .on_click(move |_, window, cx| {
                        choose_state.update(cx, |state, cx| state.choose(&value, window, cx));
                    })
                    .into_any_element()
            }
        }
    }
}

/// The inside of an item row as the reference app draws it: the leading
/// element, the label over its description, and the check.
fn default_row_content<V: SelectValue>(
    item: &SelectItem<V>,
    row_id: &ElementId,
    selected: bool,
    look: &MenuLook,
    window: &mut Window,
    cx: &mut App,
) -> Vec<AnyElement> {
    let disabled = item.is_disabled();
    let part = |name: &'static str| ElementId::NamedChild(row_id.clone().into(), name.into());
    let leading = item.render_leading(window, cx).map(|leading| {
        line_slot(look)
            .id(part("leading"))
            .test_support()
            .child(leading)
    });
    let check = line_slot(look).child(div().size_4().when(selected, |this| {
        this.child(
            Icon::from(IconName::Check)
                .size_4()
                .text_color(if disabled {
                    look.muted_foreground
                } else {
                    look.indicator
                }),
        )
    }));
    vec![
        row_line()
            .children(leading)
            .child(
                div()
                    .id(part("label"))
                    .test_support()
                    .flex_1()
                    .min_w_0()
                    .child(label_block(
                        item.label().clone(),
                        item.description_text().cloned(),
                        look,
                    )),
            )
            .child(check)
            .into_any_element(),
    ]
}