guise-ui 0.10.0

A Mantine-inspired component library for gpui, Zed's GPU-accelerated UI framework.
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
//! `DataView` — a collection-bound list/grid (gpui entity).
//!
//! The collection-binding counterpart to [`crate::reactive::Binding`]: the view
//! observes a `Signal<Vec<T>>` and repaints whenever the collection changes —
//! no manual wiring. Filtering and sorting are *projections* applied at render
//! time over the borrowed data (NSArrayController-style): the source vector is
//! never copied or reordered, the view just renders a filtered + sorted list of
//! indices into it.
//!
//! ```ignore
//! let todos = use_state(cx, vec!["Write docs".to_string(), "Ship".to_string()]);
//! let view = cx.new(|cx| {
//!     DataView::new(cx, &todos)
//!         .item(|todo, _ix, _window, _cx| {
//!             Text::new(todo.clone()).into_any_element()
//!         })
//!         .sort_by(|a, b| a.cmp(b))
//!         .selectable()
//! });
//! cx.subscribe(&view, |_, _, DataViewEvent::Selected(ix), _| {
//!     println!("picked source row {ix}");
//! })
//! .detach();
//!
//! // Anywhere, later: the view repaints by itself.
//! todos.update(cx, |list| list.push("Celebrate".into()));
//! ```

use std::cmp::Ordering;
use std::ops::Range;

use gpui::prelude::*;
use gpui::{
    div, px, uniform_list, AnyElement, App, Context, EventEmitter, IntoElement, SharedString,
    Window,
};

use super::Content;
use crate::reactive::Signal;
use crate::style::{surface, Variant};
use crate::theme::{theme, Size};

/// Emitted when a selectable item is clicked. Carries the item's index into
/// the **source** vector (not its display position), so it stays valid under
/// any filter/sort projection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DataViewEvent {
    Selected(usize),
}

/// How the items flow.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DataViewLayout {
    /// A vertical list (the default).
    #[default]
    List,
    /// Rows of `n` equal-width cells.
    Grid(usize),
}

type ItemBuilder<T> = Box<dyn Fn(&T, usize, &mut Window, &mut App) -> AnyElement + 'static>;
type FilterFn<T> = Box<dyn Fn(&T) -> bool + 'static>;
type SortFn<T> = Box<dyn Fn(&T, &T) -> Ordering + 'static>;
type FilterRef<'a, T> = Option<&'a dyn Fn(&T) -> bool>;
type SortRef<'a, T> = Option<&'a dyn Fn(&T, &T) -> Ordering>;

/// A signal-bound collection view. Create with
/// `cx.new(|cx| DataView::new(cx, &signal).item(...))`.
pub struct DataView<T: 'static> {
    source: Signal<Vec<T>>,
    item: Option<ItemBuilder<T>>,
    filter: Option<FilterFn<T>>,
    sort: Option<SortFn<T>>,
    layout: DataViewLayout,
    gap: Size,
    empty: Option<Content>,
    selectable: bool,
    selected: Option<usize>,
    height: Option<f32>,
}

impl<T: 'static> EventEmitter<DataViewEvent> for DataView<T> {}

impl<T: 'static> DataView<T> {
    /// Bind the view to a collection signal. Every `set`/`update` on the
    /// signal repaints the view.
    pub fn new(cx: &mut Context<Self>, source: &Signal<Vec<T>>) -> Self {
        cx.observe(source.entity(), |this, source, cx| {
            // Drop a selection whose item fell off the end: keeping the stale
            // index would hand callers an out-of-range value and silently
            // re-select whatever item lands there after the source regrows.
            let len = source.read(cx).len();
            if this.selected.is_some_and(|i| i >= len) {
                this.selected = None;
            }
            cx.notify();
        })
        .detach();
        DataView {
            source: source.clone(),
            item: None,
            filter: None,
            sort: None,
            layout: DataViewLayout::List,
            gap: Size::Sm,
            empty: None,
            selectable: false,
            selected: None,
            height: None,
        }
    }

    /// Fix the view height (px) and virtualize: only the items in view are
    /// built each frame. Items (or grid rows) must share one height. Applies
    /// to both layouts — a `Grid(n)` virtualizes whole rows of `n` cells.
    pub fn height(mut self, height: f32) -> Self {
        self.height = Some(height.max(0.0));
        self
    }

    /// The item template, re-invoked every frame with the borrowed item and
    /// its source index — items always show live data.
    pub fn item<E>(
        mut self,
        template: impl Fn(&T, usize, &mut Window, &mut App) -> E + 'static,
    ) -> Self
    where
        E: IntoElement,
    {
        self.item = Some(Box::new(move |item, ix, window, cx| {
            template(item, ix, window, cx).into_any_element()
        }));
        self
    }

    /// Show only the items matching `pred`. A projection: the source vector
    /// is untouched.
    pub fn filter(mut self, pred: impl Fn(&T) -> bool + 'static) -> Self {
        self.filter = Some(Box::new(pred));
        self
    }

    /// Display order (stable sort). A projection: the source vector is
    /// untouched.
    pub fn sort_by(mut self, cmp: impl Fn(&T, &T) -> Ordering + 'static) -> Self {
        self.sort = Some(Box::new(cmp));
        self
    }

    pub fn layout(mut self, layout: DataViewLayout) -> Self {
        self.layout = layout;
        self
    }

    /// Spacing between items (default `Sm`).
    pub fn gap(mut self, gap: Size) -> Self {
        self.gap = gap;
        self
    }

    /// Shown when the projection yields nothing (empty source or everything
    /// filtered out). Rebuilt each render.
    pub fn empty<E>(mut self, content: impl Fn(&mut Window, &mut App) -> E + 'static) -> Self
    where
        E: IntoElement,
    {
        self.empty = Some(Box::new(move |window, cx| {
            content(window, cx).into_any_element()
        }));
        self
    }

    /// Enable single selection: items get hover/selected styling and clicks
    /// emit [`DataViewEvent::Selected`].
    pub fn selectable(mut self) -> Self {
        self.selectable = true;
        self
    }

    /// The selected **source** index, if any.
    pub fn selected_index(&self) -> Option<usize> {
        self.selected
    }
}

/// The display order: indices into `items`, filtered then stably sorted.
fn projection<T>(items: &[T], filter: FilterRef<'_, T>, sort: SortRef<'_, T>) -> Vec<usize> {
    let mut order: Vec<usize> = (0..items.len())
        .filter(|&i| filter.is_none_or(|keep| keep(&items[i])))
        .collect();
    if let Some(cmp) = sort {
        order.sort_by(|&a, &b| cmp(&items[a], &items[b]));
    }
    order
}

impl<T: 'static> DataView<T> {
    /// Build the wrapped cells for a range of **display** positions. The
    /// projected items are built while the source entity is leased; the
    /// template borrows each item in place — no clone of the collection.
    fn build_cells(
        &mut self,
        display: Range<usize>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> Vec<AnyElement> {
        let t = theme(cx);
        let radius = t.radius(t.default_radius);
        let hover_bg = t.surface_hover().hsla();
        // Same treatment as an active NavLink: the primary color's Light
        // (tinted) surface.
        let sel = surface(t, t.primary_color, Variant::Light);
        let (selected_bg, selected_fg) = (sel.bg, sel.fg);

        let template = self.item.as_ref();
        let filter = self.filter.as_deref();
        let sort = self.sort.as_deref();
        let entity = self.source.entity().clone();
        let built: Vec<(usize, AnyElement)> = entity.update(cx, |items, cx| {
            let order = projection(items, filter, sort);
            match template {
                Some(build) => order
                    .into_iter()
                    .skip(display.start)
                    .take(display.len())
                    .map(|i| (i, build(&items[i], i, window, cx)))
                    .collect(),
                None => Vec::new(),
            }
        });

        let selectable = self.selectable;
        // The source observer prunes out-of-range selections, so this index
        // is always valid for the current collection.
        let selected = self.selected;

        built
            .into_iter()
            .map(|(source_ix, element)| {
                if !selectable {
                    return element;
                }
                let is_selected = selected == Some(source_ix);
                let mut cell = div()
                    .id(("guise-dataview-item", source_ix))
                    .px(px(10.0))
                    .py(px(8.0))
                    .rounded(px(radius))
                    .cursor_pointer()
                    .child(element)
                    .on_click(cx.listener(move |this, _ev, _window, cx| {
                        this.selected = Some(source_ix);
                        cx.emit(DataViewEvent::Selected(source_ix));
                        cx.notify();
                    }));
                cell = if is_selected {
                    cell.bg(selected_bg).text_color(selected_fg)
                } else {
                    cell.hover(move |s| s.bg(hover_bg))
                };
                cell.into_any_element()
            })
            .collect()
    }

    /// One virtualized grid row: `cols` equal-width cells, padded at the tail.
    fn build_grid_row(
        &mut self,
        row_ix: usize,
        cols: usize,
        gap: f32,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> AnyElement {
        let start = row_ix * cols;
        let cells = self.build_cells(start..start + cols, window, cx);
        let mut wrapped: Vec<_> = cells
            .into_iter()
            .map(|cell| div().flex_1().min_w(px(0.0)).child(cell))
            .collect();
        while wrapped.len() < cols {
            wrapped.push(div().flex_1().min_w(px(0.0)));
        }
        div()
            .flex()
            .gap(px(gap))
            .pb(px(gap))
            .children(wrapped)
            .into_any_element()
    }

    /// Length of the current projection (display item count).
    fn projected_len(&mut self, cx: &mut Context<Self>) -> usize {
        let filter = self.filter.as_deref();
        let sort = self.sort.as_deref();
        let entity = self.source.entity().clone();
        entity.update(cx, |items, _| projection(items, filter, sort).len())
    }
}

impl<T: 'static> Render for DataView<T> {
    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let t = theme(cx);
        let gap = t.spacing(self.gap);
        let dimmed = t.dimmed().hsla();
        let font_sm = t.font_size(Size::Sm);

        let count = if self.item.is_some() {
            self.projected_len(cx)
        } else {
            0
        };

        if count == 0 {
            let content = match &self.empty {
                Some(build) => build(window, cx),
                None => div()
                    .text_size(px(font_sm))
                    .text_color(dimmed)
                    .child(SharedString::new_static("Nothing to show"))
                    .into_any_element(),
            };
            return div()
                .w_full()
                .flex()
                .justify_center()
                .py(px(16.0))
                .child(content)
                .into_any_element();
        }

        // Virtualized: uniform_list over display items (List) or whole rows
        // of `cols` cells (Grid). Only the viewport slice is built per frame.
        if let Some(height) = self.height {
            let list = match self.layout {
                DataViewLayout::List => uniform_list(
                    "guise-dataview-body",
                    count,
                    cx.processor(move |this, range: Range<usize>, window, cx| {
                        this.build_cells(range, window, cx)
                            .into_iter()
                            .map(|cell| div().pb(px(gap)).child(cell).into_any_element())
                            .collect::<Vec<_>>()
                    }),
                ),
                DataViewLayout::Grid(cols) => {
                    let cols = cols.max(1);
                    let rows = count.div_ceil(cols);
                    uniform_list(
                        "guise-dataview-body",
                        rows,
                        cx.processor(move |this, range: Range<usize>, window, cx| {
                            range
                                .map(|row_ix| this.build_grid_row(row_ix, cols, gap, window, cx))
                                .collect::<Vec<_>>()
                        }),
                    )
                }
            };
            return div()
                .w_full()
                .child(list.h(px(height)).w_full())
                .into_any_element();
        }

        let cells = self.build_cells(0..count, window, cx);
        let root = div().w_full().flex().flex_col().gap(px(gap));
        match self.layout {
            DataViewLayout::List => root.children(cells).into_any_element(),
            DataViewLayout::Grid(cols) => {
                let cols = cols.max(1);
                let mut rows = Vec::new();
                let mut row = Vec::new();
                for (i, cell) in cells.into_iter().enumerate() {
                    row.push(div().flex_1().min_w(px(0.0)).child(cell));
                    if row.len() == cols || i + 1 == count {
                        // Pad the last row so cells keep equal widths.
                        while row.len() < cols {
                            row.push(div().flex_1().min_w(px(0.0)));
                        }
                        rows.push(div().flex().gap(px(gap)).children(std::mem::take(&mut row)));
                    }
                }
                root.children(rows).into_any_element()
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn identity_without_projections() {
        assert_eq!(projection(&[10, 20, 30], None, None), vec![0, 1, 2]);
        assert_eq!(projection::<i32>(&[], None, None), Vec::<usize>::new());
    }

    #[test]
    fn filter_keeps_source_indices() {
        let even = |n: &i32| n % 2 == 0;
        let order = projection(&[1, 2, 3, 4, 5, 6], Some(&even), None);
        assert_eq!(order, vec![1, 3, 5]);
    }

    #[test]
    fn sort_orders_indices_without_moving_items() {
        let cmp = |a: &i32, b: &i32| a.cmp(b);
        let items = [30, 10, 20];
        let order = projection(&items, None, Some(&cmp));
        assert_eq!(order, vec![1, 2, 0]);
        // The source is untouched; the order just points into it.
        assert_eq!(items, [30, 10, 20]);
    }

    #[test]
    fn filter_then_sort_compose() {
        let over_two = |n: &i32| *n > 2;
        let desc = |a: &i32, b: &i32| b.cmp(a);
        let order = projection(&[1, 4, 3, 2, 5], Some(&over_two), Some(&desc));
        assert_eq!(order, vec![4, 1, 2]); // values 5, 4, 3
    }

    #[test]
    fn sort_is_stable_for_equal_keys() {
        let by_len = |a: &&str, b: &&str| a.len().cmp(&b.len());
        let items = ["bb", "aa", "c", "dd"];
        let order = projection(&items, None, Some(&by_len));
        // "c" first, then the three two-char items in source order.
        assert_eq!(order, vec![2, 0, 1, 3]);
    }
}