ESC
开源 6 分钟阅读

Zig 跨平台原生 UI 框架 nanoui 开源发布

nanoui 是一个用 Zig 语言编写的跨平台原生 UI 框架,支持 macOS 和 Linux(运行时依赖 GTK 3),内置示例画廊、Webview 示例及组件单元测试。项目目前处于 0.x 早期阶段,相关应用以子模块形式管理。

来源:GitHub

git clone --recursive https://github.com/justrach/nanoui
cd nanoui
zig build run-gallery # the native UI tour
zig build run-hello # the webview example
zig build test # unit and widget tests

You need Zig 0.17.0, plus the macOS SDK on a Mac (Xcode or the Command Line Tools). Linux apps need GTK 3 at run time and nothing at build time.

--recursive also fetches the apps, which live in their own repositories as submodules under apps/. To fetch them after a plain clone, run git submodule update --init.

To use nanoui in your own project, add a release to its build.zig.zon:

zig fetch –save git+https://github.com/justrach/nanoui#v0.2.0

Releases are tagged vMAJOR.MINOR.PATCH, as mygo’s are, and each is listed under Releases with what changed. While nanoui is 0.x, a minor release may change the API; a patch release won’t.

const Counter = struct {
 n: i64 = 0,

 fn view(s: *Counter, c: *ui.Context) void {
 const col = ui.div(c).column().sizeFull().center().gap(16);
 defer col.end();
 ui.textf(c, .{ .size = 56, .weight = .bold }, "{d}", .{s.n});
 if (ui.button(c, "Increment", .{ .variant = .primary }).clicked) s.n += 1;
 }
};

pub fn main(init: std.process.Init) !void {
 const app = try nanoui.App.create(init, .{ .name = "Counter" });
 defer app.destroy();
 var state: Counter = .{};
 _ = try app.newWindow(.{ .title = "Counter", .content = .{ .view = .init(&state, Counter.view) } });
 try app.run();
}

The nanoui gallery: buttons, toggles, sliders and a text field, drawn by nanoui

The gallery example, zig build run-gallery.

Views are immediate mode: a function of your state, run on every event. Widgets answer from the previous frame’s layout. When an interaction changes state, the frame is built again before it’s drawn, so the screen never lags the state.

.glass(.{}) fills a box with Liquid Glass, the material of macOS 26 and later, in place of a background. Whatever was painted under the box shows through it: frosted, bent near its edges as through the rim of a lens, and lit along a hairline rim. That includes content scrolling under a toolbar placed over it with absolute().

const bar = ui.div(c).absolute().offset(20, 20).w(420).h(56).row().itemsCenter().px(16).rounded(28).glass(.{}); defer bar.end(); ui.text(c, “On glass”, .{ .weight = .semibold }); ui.spacer(c); // A prominent button: glass tinted with the accent. const tap = ui.div(c).px(16).py(8).rounded(16).glass(.{ .tint = th.accent }).control(); defer tap.end(); ui.text(c, “Tap”, .{ .color = th.accent_text });

Regular glass frosts and lightens what shows through, or darkens it in dark mode, so text on it reads over anything. .style = .clear barely frosts it, for glass over photos and video. nanoui draws the glass itself, after mygo’s glass plugin and its measurements of AppKit’s NSGlassEffectView. Each pane averages and blurs what’s under it, then shades it on the GPU, and the CPU renderer computes the same pixels. It looks the same on Linux and Windows, and a test checks the two renderers agree.

ui.motion animates boxes the way gpui-motion does: every frame, you say where a box should be, and motion takes it there.

Motion keeps its state in the frame’s context, by box, so there are no objects to hold. It draws frames only while something moves, and jumps straight to the end when the system asks for reduced motion.

const f = ui.motion.frame(c, .{ .target = .{ .width = if (open) 320 else 180, .background = if (open) th.accent else th.surface }, .initial = .{ .y = 12, .opacity = 0 }, .press = .{ .scale = 0.96 }, .transition = .{ .spring = ui.motion.Spring.bouncy }, }); const card = ui.div(c).p(16).control().motion(f); defer card.end(); if (card.clicked()) open = !open;

// A toast that comes and goes: drawn while it shows, and while it leaves. if (ui.motion.present(c, “toast”, saved, .{ .initial = .{ .y = 24, .opacity = 0 }, .exit = .{ .opacity = 0 } })) |t| { const toast = ui.div(c).px(16).py(12).rounded(12).bg(th.text).motion(t); defer toast.end(); ui.text(c, “Saved”, .{ .color = th.background }); }

The gallery

The gallery’s Motion page.

nanoui.kit is a set of components after GPUI Kit, drawn by nanoui and moved by ui.motion:

const kit = nanoui.kit;

if (kit.button(c, “Delete”, .{ .variant = .danger, .icon = “trash” }).clicked) confirm = true; if (kit.dialog(c, “confirm”, &confirm, .{ .title = “Delete project?”, .ok = “Delete”, .ok_variant = .danger })) |d| { ui.text(c, “Its files and history go too.”, .{}); if (d.end() == .ok) toaster.push(.{ .status = .danger, .title = “Deleted” }); } _ = kit.tabs(c, &.{ “Overview”, “Activity”, “Settings” }, &tab, .{ .variant = .segmented }); toaster.view(c); // last: toasts over everything

Overlays are made of two new box properties: layer draws a box above the page and unclipped, and fixed places it from the window’s corner. Context.state keeps a widget’s small state between frames.

const Greeter = struct {
 pub const nanoui_params = .{ .greet = .{"name"} };

 pub fn greet(_: *Greeter, call: *nanoui.Call, name: []const u8) ![]const u8 {
 return std.fmt.allocPrint(call.arena, "Hello, {s}!", .{name});
 }
};

const Tick = nanoui.Event("tick", struct { uptime: u64 });

// in main:
try app.bind(&greeter);
try app.registerEvent(Tick);
_ = try app.newWindow(.{ .title = "Hello", .content = .{ .page = .{ .url = "/", .assets = &assets } } });
import { Greeter, onTick } from "/nanoui.js"; // generated, served by the app

document.body.textContent = await Greeter.greet("Ada");
onTick(({ uptime }) => console.log(uptime));

zig build gen writes nanoui.d.ts:

export declare const Greeter: { greet(name: string): Promise }; export declare function onTick(listener: (payload: TickPayload) => void): () => void;

Methods may return error unions; an error rejects the page’s promise with the error’s name. Assets are served from the nanoui://localhost/ scheme. Elements styled --app-region: drag move frameless windows.

var t: ui.Tester = undefined;
try t.init(gpa, .init(&state, Counter.view), .{});
defer t.deinit();
try t.clickText("Increment");
try std.testing.expect(t.hasText("1"));
try t.screenshot("/tmp/counter.png"); // rendered offscreen by the Metal renderer

The real apps run headless too:

zig-out/bin/gallery –nanoui-snapshot=shot.png –nanoui-script=“click:Tasks;type:Hi;key:enter” zig-out/bin/hello –nanoui-eval=‘nanoui.call(“Greeter.greet”,“Ada”).then(v => { nanoui.log(v); nanoui.window.close() })’

Platforms

nanoui loads what each platform has instead of linking it, so every platform builds from any machine. On a Mac, zig build -Dtarget=x86_64-linux-gnu or -Dtarget=x86_64-windows-gnu makes a Linux or Windows binary.

The CPU renderer matches the Metal one pixel for pixel, and a test compares them. zig build test -Dportable=true runs the Linux and Windows text and renderer on a Mac. Linux is also tested in a container (tools/linux.Dockerfile: GTK, fonts and a virtual display).

nanoterm: an agent nanoterm: a terminal of blocks, in the manner of Warp, with a coding agent (graff or Claude Code) over ACP. It has native visuals, a ⌘P launcher, and SSH sessions where the agent works on the remote host.

nanomon: an activity monitor in Codegraff colors, with cell graphs of CPU, memory, GPU, disk and network. You can quit several processes at once, and a graff bubble suggests what to quit.

nanostudio: a screen recorder and editor. It records a display or a window with its sound, then zooms where you clicked. You can trim, speed up and dress the take, and export it. Every frame, preview and export alike, is a nanoui view.

Download them for macOS: nanoterm · nanomon · nanostudio.

They live in apps/ as submodules, and each also builds on its own, fetching nanoui pinned by commit. To build one against the nanoui next to it, with your changes, use --fork: cd apps/nanomon && zig build run --fork=../...

Performance is measured headless with hillclimb/: the same scenes rendered through each framework’s own frames and offscreen Metal renderer, on an Apple M3 Ultra. The figures are medians per frame in milliseconds; lower is better.