feat: add support for menu header widgets

This commit is contained in:
CJ van den Berg 2024-03-28 22:02:45 +01:00
parent 0def007748
commit d4066ad396
2 changed files with 16 additions and 2 deletions

View file

@ -1,7 +1,6 @@
const std = @import("std");
const nc = @import("notcurses");
const tp = @import("thespian");
const log = @import("log");
const Widget = @import("Widget.zig");
const command = @import("command.zig");

View file

@ -64,6 +64,7 @@ pub fn State(ctx_type: type) type {
selected: ?usize = null,
render_idx: usize = 0,
selected_active: bool = false,
header_count: usize = 0,
const Self = @This();
const options_type = Options(ctx_type);
@ -74,6 +75,12 @@ pub fn State(ctx_type: type) type {
a.destroy(self);
}
pub fn add_header(self: *Self, w_: Widget) !*Widget {
self.header_count += 1;
try self.menu.add(w_);
return &self.menu.widgets.items[self.menu.widgets.items.len - 1].widget;
}
pub fn add_item(self: *Self, label: []const u8) !void {
try self.menu.add(try Button.create(*Self, self.a, self.menu.parent, .{
.ctx = self,
@ -94,6 +101,13 @@ pub fn State(ctx_type: type) type {
}));
}
pub fn reset_items(self: *Self) void {
for (self.menu.widgets.items, 0..) |*w, i|
if (i >= self.header_count)
w.widget.deinit(self.a);
self.menu.widgets.shrinkRetainingCapacity(self.header_count);
}
pub fn render(self: *Self, theme: *const Widget.Theme) bool {
return self.menu.render(theme);
}
@ -152,7 +166,8 @@ pub fn State(ctx_type: type) type {
pub fn activate_selected(self: *Self) void {
const selected = self.selected orelse return;
self.selected_active = true;
const button = self.menu.widgets.items[selected].widget.dynamic_cast(button_type) orelse return;
const pos = selected + self.header_count;
const button = self.menu.widgets.items[pos].widget.dynamic_cast(button_type) orelse return;
button.opts.on_click(button.opts.ctx, button);
}
};