this repo has no description
1const std = @import("std");
2const vaxis = @import("vaxis");
3const vxfw = vaxis.vxfw;
4
5const Text = vxfw.Text;
6const ListView = vxfw.ListView;
7const Widget = vxfw.Widget;
8
9const Model = struct {
10 list_view: ListView,
11
12 pub fn widget(self: *Model) Widget {
13 return .{
14 .userdata = self,
15 .eventHandler = Model.typeErasedEventHandler,
16 .drawFn = Model.typeErasedDrawFn,
17 };
18 }
19
20 pub fn typeErasedEventHandler(ptr: *anyopaque, ctx: *vxfw.EventContext, event: vxfw.Event) anyerror!void {
21 const self: *Model = @ptrCast(@alignCast(ptr));
22 try ctx.requestFocus(self.list_view.widget());
23 switch (event) {
24 .key_press => |key| {
25 if (key.matches('q', .{}) or key.matchExact('c', .{ .ctrl = true })) {
26 ctx.quit = true;
27 return;
28 }
29 },
30 else => {},
31 }
32 }
33
34 fn typeErasedDrawFn(ptr: *anyopaque, ctx: vxfw.DrawContext) std.mem.Allocator.Error!vxfw.Surface {
35 const self: *Model = @ptrCast(@alignCast(ptr));
36 const max = ctx.max.size();
37
38 const list_view: vxfw.SubSurface = .{
39 .origin = .{ .row = 1, .col = 1 },
40 .surface = try self.list_view.draw(ctx),
41 };
42
43 const children = try ctx.arena.alloc(vxfw.SubSurface, 1);
44 children[0] = list_view;
45
46 return .{
47 .size = max,
48 .widget = self.widget(),
49 .buffer = &.{},
50 .children = children,
51 };
52 }
53};
54
55pub fn main(init: std.process.Init) !void {
56 const io = init.io;
57 const alloc = init.gpa;
58
59 var buffer: [1024]u8 = undefined;
60 var app: vxfw.App = try .init(io, alloc, init.environ_map, &buffer);
61 defer app.deinit();
62
63 const model = try alloc.create(Model);
64 defer alloc.destroy(model);
65
66 const n = 80;
67 var texts: std.ArrayList(Widget) = try .initCapacity(alloc, n);
68 var allocs: std.ArrayList(*Text) = try .initCapacity(alloc, n);
69 defer {
70 for (allocs.items) |tw| {
71 alloc.free(tw.text);
72 alloc.destroy(tw);
73 }
74 allocs.deinit(alloc);
75 texts.deinit(alloc);
76 }
77
78 for (0..n) |i| {
79 const t = std.fmt.allocPrint(alloc, "List Item {d} of {d}", .{ i, n }) catch "placeholder";
80 const tw = try alloc.create(Text);
81 tw.* = .{ .text = t };
82 _ = try allocs.append(alloc, tw);
83 _ = try texts.append(alloc, tw.widget());
84 }
85
86 model.* = .{
87 .list_view = .{
88 .wheel_scroll = 3,
89 .scroll = .{
90 .wants_cursor = true,
91 },
92 .children = .{ .slice = texts.items },
93 },
94 };
95
96 try app.run(model.widget(), .{});
97}
98
99test {
100 std.testing.refAllDecls(@This());
101}