zippa-db 0.1.1

A fast, lightweight, cross-platform database client for PostgreSQL, MySQL, and SQLite.
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
//! The side panel beside a table's grid: the row the keyboard is on, laid out
//! as one field per column.
//!
//! A wide row is awkward to edit a cell at a time, so the panel follows the
//! grid's focused row and stages whatever is typed into the same overlay a grid
//! edit uses — the grid tints it, and the ordinary apply flow writes it. The
//! panel never writes anything itself.

use gpui_kit::component::button::{Button, ButtonVariants};
use gpui_kit::component::input::{Input, InputEvent, InputState, Textarea, TextareaState};
use gpui_kit::component::menu::{DropdownMenu, PopupMenuItem};
use gpui_kit::component::{ActiveTheme, IconName, Sizable, h_flex, v_flex};
use gpui_kit::{App, Context, Entity, EventEmitter, Focusable, Window, div, px};
use gpui_kit::{SharedString, prelude::*, rems};
use regex::Regex;

use crate::db::query::{self, Cell};
use crate::settings::Settings;
use crate::ui::data_grid::{DataGrid, GridEdit, RowStatus, needs_a_window};
use crate::ui::text_filter;

pub(crate) enum RowPanelEvent {
    CloseRequested,
}

impl EventEmitter<RowPanelEvent> for RowPanel {}

/// The most lines a text box grows to before it scrolls.
const TEXT_LINES: usize = 3;

/// Whether a column holds prose, which wants room to wrap rather than one line.
fn is_text_type(type_name: &str) -> bool {
    let name = type_name.trim_matches('"').to_ascii_uppercase();
    ["TEXT", "CHAR", "STRING", "CLOB", "JSON", "XML", "NAME"]
        .iter()
        .any(|kind| name.contains(kind))
}

/// One column's text box: a line for most types, a few lines for text.
enum Field {
    Line(Entity<InputState>),
    Area(Entity<TextareaState>),
}

impl Field {
    fn value(&self, cx: &App) -> String {
        match self {
            Field::Line(input) => input.read(cx).value().to_string(),
            Field::Area(input) => input.read(cx).value().to_string(),
        }
    }

    fn set_value(&self, text: String, window: &mut Window, cx: &mut App) {
        match self {
            Field::Line(input) => input.update(cx, |input, cx| input.set_value(text, window, cx)),
            Field::Area(input) => input.update(cx, |input, cx| input.set_value(text, window, cx)),
        }
    }

    fn is_focused(&self, window: &Window, cx: &App) -> bool {
        match self {
            Field::Line(input) => input.read(cx).focus_handle(cx).is_focused(window),
            Field::Area(input) => input.read(cx).focus_handle(cx).is_focused(window),
        }
    }
}

pub(crate) struct RowPanel {
    grid: Entity<DataGrid>,
    columns: Vec<String>,
    column_types: Vec<String>,
    focused_row: Option<usize>,
    /// One text box per column, index-aligned with `columns`.
    fields: Vec<Field>,
    filter_input: Entity<InputState>,
    filter: Option<Regex>,
}

impl RowPanel {
    pub(crate) fn new(grid: Entity<DataGrid>, window: &mut Window, cx: &mut Context<Self>) -> Self {
        let filter_input = cx.new(|cx| InputState::new(window, cx).placeholder("Filter columns"));
        cx.subscribe_in(&filter_input, window, Self::on_filter_event)
            .detach();
        cx.subscribe_in(&grid, window, Self::on_grid_edit).detach();

        let focused_row = grid.read(cx).focused_row(cx);
        Self {
            grid,
            columns: Vec::new(),
            column_types: Vec::new(),
            focused_row,
            fields: Vec::new(),
            filter_input,
            filter: None,
        }
    }

    /// Rebuild one field per column, as when a page brings a different set.
    pub(crate) fn sync_columns(
        &mut self,
        columns: &[String],
        column_types: &[String],
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.columns = columns.to_vec();
        self.column_types = column_types.to_vec();
        self.fields = (0..columns.len())
            .map(|col_ix| {
                let text = column_types.get(col_ix).is_some_and(|t| is_text_type(t));
                let on_event = move |this: &mut Self,
                                     event: &InputEvent,
                                     window: &mut Window,
                                     cx: &mut Context<Self>| {
                    if matches!(event, InputEvent::PressEnter { .. } | InputEvent::Blur) {
                        this.commit_field(col_ix, window, cx);
                    }
                };
                if text {
                    let field =
                        cx.new(|cx| TextareaState::new(window, cx).auto_grow(1, TEXT_LINES));
                    cx.subscribe_in(
                        &field,
                        window,
                        move |this, _, event: &InputEvent, window, cx| {
                            on_event(this, event, window, cx)
                        },
                    )
                    .detach();
                    Field::Area(field)
                } else {
                    let field = cx.new(|cx| InputState::new(window, cx));
                    cx.subscribe_in(
                        &field,
                        window,
                        move |this, _, event: &InputEvent, window, cx| {
                            on_event(this, event, window, cx)
                        },
                    )
                    .detach();
                    Field::Line(field)
                }
            })
            .collect();
        self.focused_row = self.grid.read(cx).focused_row(cx);
        self.reseed(true, window, cx);
    }

    fn on_filter_event(
        &mut self,
        input: &Entity<InputState>,
        event: &InputEvent,
        _window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        if !matches!(event, InputEvent::Change) {
            return;
        }
        let pattern = input.read(cx).value().trim().to_string();
        self.filter = text_filter::compile(&pattern);
        cx.notify();
    }

    fn on_grid_edit(
        &mut self,
        _: &Entity<DataGrid>,
        event: &GridEdit,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        match event {
            GridEdit::RowFocused(row) => {
                let moved = self.focused_row != *row;
                self.focused_row = *row;
                self.reseed(moved, window, cx);
            }
            GridEdit::Staged => self.reseed(false, window, cx),
            GridEdit::RowLeft { .. } => {}
        }
    }

    /// Put the focused row's values in the fields.
    ///
    /// A field being typed into keeps its text unless the row itself changed:
    /// another field's edit event would otherwise stomp it mid-keystroke.
    fn reseed(&mut self, row_changed: bool, window: &mut Window, cx: &mut Context<Self>) {
        cx.notify();
        let Some(row_ix) = self.focused_row else {
            return;
        };
        let Some(cells) = self.grid.read(cx).row_cells(row_ix, cx) else {
            return;
        };

        for (field, cell) in self.fields.iter().zip(cells) {
            if !row_changed && field.is_focused(window, cx) {
                continue;
            }
            // Raw text, the way the grid's own editor opens: a NULL is empty,
            // not the word.
            field.set_value(cell.unwrap_or_default(), window, cx);
        }
    }

    /// Stage what a field holds, the way the grid does when its editor closes.
    fn commit_field(&mut self, col_ix: usize, _window: &mut Window, cx: &mut Context<Self>) {
        let Some(row_ix) = self.focused_row else {
            return;
        };
        let Some(field) = self.fields.get(col_ix) else {
            return;
        };
        let Some(cells) = self.grid.read(cx).row_cells(row_ix, cx) else {
            return;
        };

        let text = field.value(cx);
        // A box that shows what the cell already holds has not been edited;
        // staging it would turn a NULL, shown empty, into an empty string.
        let current = cells.get(col_ix).cloned().flatten().unwrap_or_default();
        if text == current {
            return;
        }

        let coerce = Settings::global(cx).coerce_null_literal;
        let value: Cell = if coerce && text.eq_ignore_ascii_case("null") {
            None
        } else {
            Some(text)
        };
        self.grid
            .update(cx, |grid, cx| grid.stage_cell(row_ix, col_ix, value, cx));
    }

    fn render_header(&self, cx: &mut Context<Self>) -> impl IntoElement {
        h_flex()
            .gap_1()
            .p_2()
            .child(
                div().flex_1().child(
                    Input::new(&self.filter_input)
                        .id("row-panel-filter")
                        .small()
                        .cleanable(true),
                ),
            )
            .child(
                Button::new("row-panel-close")
                    .ghost()
                    .xsmall()
                    .icon(IconName::Close)
                    .accessibility_label("Hide row panel")
                    .tooltip("Hide row panel")
                    .on_click(cx.listener(|_, _, _, cx| cx.emit(RowPanelEvent::CloseRequested))),
            )
    }

    fn render_field(
        &self,
        row_ix: usize,
        col_ix: usize,
        status: RowStatus,
        cells: &[Cell],
        cx: &mut Context<Self>,
    ) -> impl IntoElement {
        let column = self.columns[col_ix].clone();
        let type_name = self.column_types.get(col_ix).cloned().unwrap_or_default();
        let cell = cells.get(col_ix).cloned().flatten();
        let deleted = status == RowStatus::Deleted;
        let editable = !deleted && self.grid.read(cx).is_field_editable(row_ix, col_ix, cx);

        let note = if deleted {
            None
        } else if query::is_placeholder(&cell) {
            Some("This value was not read back from the server.")
        } else if !editable {
            Some("This value cannot be edited here.")
        } else {
            None
        };
        let big = needs_a_window(&cell, &type_name);
        let staged = self.grid.read(cx).is_field_staged(row_ix, col_ix, cx);
        let draft = status == RowStatus::Draft;
        let grid = self.grid.clone();
        let menu_column = column.clone();

        let menu = Button::new(("row-panel-menu", col_ix))
            .ghost()
            .xsmall()
            .icon(IconName::Ellipsis)
            .accessibility_label(format!("Options for {menu_column}"))
            .tooltip("Field options")
            .dropdown_menu(move |menu, _window, _cx| {
                let stage = |label: &'static str, value: Cell| {
                    let grid = grid.clone();
                    PopupMenuItem::new(label)
                        .disabled(!editable)
                        .on_click(move |_, _, cx| {
                            let value = value.clone();
                            grid.update(cx, |grid, cx| grid.stage_cell(row_ix, col_ix, value, cx))
                        })
                };
                let reset = |label: &'static str, enabled: bool| {
                    let grid = grid.clone();
                    PopupMenuItem::new(label)
                        .disabled(!enabled)
                        .on_click(move |_, _, cx| {
                            grid.update(cx, |grid, cx| grid.reset_cell(row_ix, col_ix, cx))
                        })
                };
                let view = grid.clone();
                menu.item(stage("Set NULL", None))
                    .item(stage("Set empty string", Some(String::new())))
                    // Only a new row has a default to fall back on: a loaded
                    // row's cell has no way to say "whatever the server picks".
                    .item(reset("Set Default", editable && draft && staged))
                    .item(reset("Revert change", editable && !draft && staged))
                    .item(PopupMenuItem::separator())
                    .item(
                        PopupMenuItem::new("View whole value")
                            .disabled(!big)
                            .on_click(move |_, _, cx| {
                                view.update(cx, |grid, cx| grid.view_cell(row_ix, col_ix, cx))
                            }),
                    )
            });

        let input = match &self.fields[col_ix] {
            Field::Line(input) => Input::new(input)
                .xsmall()
                .readonly(!editable)
                .into_any_element(),
            Field::Area(input) => Textarea::new(input)
                .xsmall()
                .line_height(rems(1.0))
                .readonly(!editable)
                .into_any_element(),
        };

        v_flex()
            .child(
                h_flex()
                    .gap_1()
                    .justify_between()
                    .child(
                        div()
                            .text_size(px(10.))
                            .line_height(px(12.))
                            .text_color(cx.theme().muted_foreground)
                            .overflow_x_hidden()
                            .text_overflow(gpui_kit::TextOverflow::Truncate(
                                SharedString::new_static("…"),
                            ))
                            .child(format!("{column} · {type_name}")),
                    )
                    .child(menu),
            )
            .child(input)
            .when_some(note, |this, note| {
                this.child(
                    div()
                        .text_size(px(10.))
                        .text_color(cx.theme().muted_foreground)
                        .child(note),
                )
            })
    }
}

impl Render for RowPanel {
    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let status = self.focused_row.and_then(|row_ix| {
            self.grid
                .read(cx)
                .row_status(row_ix, cx)
                .map(|s| (row_ix, s))
        });

        let body = match status {
            None => v_flex()
                .flex_1()
                .items_center()
                .justify_center()
                .child(
                    div()
                        .text_sm()
                        .text_color(cx.theme().muted_foreground)
                        .child("Select a row to see its fields"),
                )
                .into_any_element(),
            Some((row_ix, status)) => {
                let cells = self.grid.read(cx).row_cells(row_ix, cx).unwrap_or_default();
                let shown: Vec<usize> = (0..self.columns.len().min(self.fields.len()))
                    .filter(|col_ix| match &self.filter {
                        Some(filter) => filter.is_match(&self.columns[*col_ix]),
                        None => true,
                    })
                    .collect();

                let none_shown = shown.is_empty();
                let fields: Vec<gpui_kit::AnyElement> = shown
                    .into_iter()
                    .map(|col_ix| {
                        self.render_field(row_ix, col_ix, status, &cells, cx)
                            .into_any_element()
                    })
                    .collect();

                v_flex()
                    .id("row-panel-fields")
                    .flex_1()
                    .min_h_0()
                    .overflow_y_scroll()
                    .gap_1()
                    .p_1()
                    .when(status == RowStatus::Deleted, |this| {
                        this.child(
                            div()
                                .text_xs()
                                .text_color(cx.theme().danger)
                                .child("Row marked for deletion"),
                        )
                    })
                    .when(status == RowStatus::Draft, |this| {
                        this.child(
                            div()
                                .text_xs()
                                .text_color(cx.theme().muted_foreground)
                                .child("New row"),
                        )
                    })
                    .when(none_shown, |this| {
                        this.child(
                            div()
                                .text_sm()
                                .text_color(cx.theme().muted_foreground)
                                .child("No columns match"),
                        )
                    })
                    .children(fields)
                    .into_any_element()
            }
        };

        v_flex()
            .size_full()
            .border_l_1()
            .border_color(cx.theme().border)
            .child(self.render_header(cx))
            .child(body)
    }
}

#[cfg(test)]
impl RowPanel {
    pub(crate) fn focused_row_for_test(&self) -> Option<usize> {
        self.focused_row
    }

    pub(crate) fn field_value_for_test(&self, col_ix: usize, cx: &App) -> String {
        self.fields[col_ix].value(cx)
    }

    pub(crate) fn set_field_for_test(
        &mut self,
        col_ix: usize,
        value: &str,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.fields[col_ix].set_value(value.to_string(), window, cx);
    }

    pub(crate) fn commit_field_for_test(
        &mut self,
        col_ix: usize,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.commit_field(col_ix, window, cx);
    }

    pub(crate) fn set_filter_for_test(
        &mut self,
        pattern: &str,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        // `set_value` is silent, unlike typing, so the matcher is set directly.
        self.filter_input.update(cx, |input, cx| {
            input.set_value(pattern.to_string(), window, cx)
        });
        self.filter = text_filter::compile(pattern.trim());
        cx.notify();
    }

    /// The columns the filter lets through.
    pub(crate) fn shown_columns_for_test(&self) -> Vec<String> {
        self.columns
            .iter()
            .filter(|name| self.filter.as_ref().is_none_or(|f| f.is_match(name)))
            .cloned()
            .collect()
    }
}