test: streamline examples with quit texts
All checks were successful
Zig Project Action / Lint, Spell-check and test zig project (push) Successful in 24s

Improve some examples to provide visual feedback, i.e. for the button
exmample, with fixes to make them compilable with the `Scrollable`
element changes.
This commit is contained in:
2025-03-01 17:12:28 +01:00
parent af443c6bbf
commit caee008d50
5 changed files with 110 additions and 21 deletions

View File

@@ -7,10 +7,37 @@ const App = zterm.App(union(enum) {
const log = std.log.scoped(.default);
pub const Clickable = struct {
const QuitText = struct {
const text = "Press ctrl+c to quit.";
pub fn element(this: *@This()) App.Element {
return .{ .ptr = this, .vtable = &.{ .content = content } };
}
pub fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Size) !void {
_ = ctx;
std.debug.assert(cells.len == @as(usize, size.cols) * @as(usize, size.rows));
const row = 2;
const col = size.cols / 2 -| (text.len / 2);
const anchor = (row * size.cols) + col;
for (text, 0..) |cp, idx| {
cells[anchor + idx].style.fg = .white;
cells[anchor + idx].style.bg = .black;
cells[anchor + idx].cp = cp;
// NOTE: do not write over the contents of this `Container`'s `Size`
if (anchor + idx == cells.len - 1) break;
}
}
};
const Clickable = struct {
const text = "Press me";
queue: *App.Queue,
color: zterm.Color = .black,
pub fn element(this: *@This()) App.Element {
return .{
@@ -25,13 +52,20 @@ pub const Clickable = struct {
fn handle(ctx: *anyopaque, event: App.Event) !void {
const this: *@This() = @ptrCast(@alignCast(ctx));
switch (event) {
.mouse => |mouse| this.queue.push(.{ .click = @tagName(mouse.button) }),
.mouse => |mouse| {
var value = @intFromEnum(this.color);
value += 1;
value %= 17;
if (value == 0) value = 1;
this.color = @enumFromInt(value);
this.queue.push(.{ .click = @tagName(mouse.button) });
},
else => {},
}
}
fn content(ctx: *anyopaque, cells: []zterm.Cell, size: zterm.Size) !void {
_ = ctx;
const this: *@This() = @ptrCast(@alignCast(ctx));
std.debug.assert(cells.len == @as(usize, size.cols) * @as(usize, size.rows));
const row = size.rows / 2 -| (text.len / 2);
@@ -39,7 +73,8 @@ pub const Clickable = struct {
const anchor = (row * size.cols) + col;
for (text, 0..) |cp, idx| {
cells[anchor + idx].style.fg = .black;
cells[anchor + idx].style.fg = this.color;
cells[anchor + idx].style.emphasis = &.{.bold};
cells[anchor + idx].cp = cp;
// NOTE: do not write over the contents of this `Container`'s `Size`
@@ -63,10 +98,12 @@ pub fn main() !void {
var clickable: Clickable = .{ .queue = &app.queue };
const element = clickable.element();
var quit_text: QuitText = .{};
var container = try App.Container.init(allocator, .{
.rectangle = .{ .fill = .grey },
.layout = .{ .padding = .all(5) },
}, .{});
}, quit_text.element());
defer container.deinit();
try container.append(try App.Container.init(allocator, .{ .rectangle = .{ .fill = .light_grey } }, element));