add(element/radio-button): RadioButton Element implementation
Some checks failed
Zig Project Action / Lint, Spell-check and test zig project (push) Failing after 2m6s

This can be used to visualize the values of `bool`'s, which is relevant
when creating form's based on `struct`'s automatically.
This commit is contained in:
2025-07-13 21:02:28 +02:00
parent df78c7d6eb
commit 088e1a9246
4 changed files with 165 additions and 0 deletions

View File

@@ -416,6 +416,7 @@ pub fn App(comptime E: type) type {
pub const Button = element.Button(Event, Queue);
pub const Input = element.Input(Event, Queue);
pub const Progress = element.Progress(Event, Queue);
pub const RadioButton = element.RadioButton(Event);
pub const Scrollable = element.Scrollable(Event);
pub const Queue = queue.Queue(Event, 256);
};

View File

@@ -647,6 +647,70 @@ pub fn Button(Event: type, Queue: type) fn (meta.FieldEnum(Event)) type {
return button_struct.button_fn;
}
pub fn RadioButton(Event: type) type {
return struct {
configuration: Configuration,
value: bool,
pub const Configuration = struct {
// TODO support more user control for colors (i.e. background, foreground, checked, unchecked, etc.)
color: Color = .default,
style: enum(u1) {
squared,
rounded,
} = .rounded,
label: []const u8,
};
pub fn init(initial_value: bool, configuration: Configuration) @This() {
return .{
.value = initial_value,
.configuration = configuration,
};
}
pub fn element(this: *@This()) Element(Event) {
return .{
.ptr = this,
.vtable = &.{
.handle = handle,
.content = content,
},
};
}
fn handle(ctx: *anyopaque, event: Event) !void {
var this: *@This() = @ptrCast(@alignCast(ctx));
switch (event) {
// TODO should this also support key presses to accept?
.mouse => |mouse| if (mouse.button == .left and mouse.kind == .release) {
this.value = !this.value;
},
else => {},
}
}
fn content(ctx: *anyopaque, cells: []Cell, size: Point) !void {
const this: *@This() = @ptrCast(@alignCast(ctx));
assert(cells.len == @as(usize, size.x) * @as(usize, size.y));
cells[0].cp = switch (this.configuration.style) {
.rounded => if (this.value) '●' else '○',
.squared => if (this.value) '■' else '□',
};
cells[0].style.fg = this.configuration.color;
for (2.., this.configuration.label) |idx, cp| {
cells[idx].style.fg = this.configuration.color;
cells[idx].cp = cp;
// NOTE do not write over the contents of this `Container`'s `Size`
if (idx == cells.len - 1) break;
}
}
};
}
pub fn Progress(Event: type, Queue: type) fn (meta.FieldEnum(Event)) type {
// NOTE the struct is necessary, as otherwise I cannot point to the function I want to return
const progress_struct = struct {