xonecas.io
79113
Ma

mini-coding-agent / files

mini-coding-agent / src / tui / picker.zig

2.3 KB
1const std = @import("std");
2const input = @import("input.zig");
3
4pub const Kind = enum { provider, model, thinking, history };
5
6pub const Action = enum { ignore, update, accept, cancel };
7
8pub const Picker = struct {
9    kind: Kind,
10    title: []const u8,
11    ids: []const []const u8 = &.{},
12    labels: []const []const u8 = &.{},
13    provider: []const u8 = "",
14    draft: []const u8 = "",
15    query: std.ArrayList(u8) = .empty,
16    matches: std.ArrayList(usize) = .empty,
17    sel: usize = 0,
18
19    pub fn refresh(self: *Picker, a: std.mem.Allocator) void {
20        self.matches.clearRetainingCapacity();
21        const query = self.query.items;
22        const n = @min(self.ids.len, self.labels.len);
23        for (self.ids[0..n], self.labels[0..n], 0..) |id, label, i| {
24            if (query.len != 0 and std.ascii.findIgnoreCase(label, query) == null and
25                std.ascii.findIgnoreCase(id, query) == null) continue;
26            self.matches.append(a, i) catch {};
27        }
28        self.sel = if (self.matches.items.len == 0) 0 else @min(self.sel, self.matches.items.len - 1);
29    }
30
31    pub fn key(self: *Picker, a: std.mem.Allocator, k: input.Key) Action {
32        switch (k) {
33            .text => |t| {
34                self.query.appendSlice(a, t) catch {};
35                self.sel = 0;
36                self.refresh(a);
37            },
38            .backspace => {
39                if (self.query.items.len == 0) return .ignore;
40                var start = self.query.items.len - 1;
41                while (start > 0 and (self.query.items[start] & 0xc0) == 0x80) start -= 1;
42                self.query.shrinkRetainingCapacity(start);
43                self.sel = 0;
44                self.refresh(a);
45            },
46            .up, .history_prev => {
47                if (self.sel == 0) return .ignore;
48                self.sel -= 1;
49            },
50            .down, .history_next => {
51                if (self.sel + 1 >= self.matches.items.len) return .ignore;
52                self.sel += 1;
53            },
54            .submit => return .accept,
55            .escape, .interrupt => return .cancel,
56            else => return .ignore,
57        }
58        return .update;
59    }
60
61    pub fn current(self: *const Picker) ?[]const u8 {
62        if (self.matches.items.len == 0) return null;
63        return self.ids[self.matches.items[self.sel]];
64    }
65};