---
title: "快速开始 — zenit Zig UI 文档"
description: "创建一个独立于 zenit 仓库、可以构建和运行的原生 macOS 应用。"
url: https://zenit.z.express/zh/docs/guide/getting-started
language: zh-CN
alternate_en: https://zenit.z.express/docs/guide/getting-started.md
alternate_es: https://zenit.z.express/es/docs/guide/getting-started.md
alternate_ja: https://zenit.z.express/ja/docs/guide/getting-started.md
alternate_ko: https://zenit.z.express/ko/docs/guide/getting-started.md
alternate_fr: https://zenit.z.express/fr/docs/guide/getting-started.md
alternate_de: https://zenit.z.express/de/docs/guide/getting-started.md
project: zenit v0.1.0-alpha (Zig 0.15.2, macOS)
source: https://github.com/version-next/zenit
---

# 快速开始

创建一个独立于 zenit 仓库、可以构建和运行的原生 macOS 应用。

用 Claude Code 或其他 Agent 开发？先装上 zenit UI dev Skill。

它把这份手册、组件选型表和真实项目踩过的坑打包成 Agent 能按需加载的说明，写出的代码直接符合 zenit 的约定。

[下载 Skill.zip · 54 KB](https://zenit.z.express/downloads/zenit-ui-dev.zip)[安装说明](https://zenit.z.express/zh/docs/guide/ai-skill)

## 准备环境

当前版本面向 macOS，Apple Silicon 是持续验证的平台。开始前确认系统具有 Zig 0.15.2 与 Xcode Command Line Tools；只有运行端到端测试时才需要 Bun。

```sh
zig version
xcode-select -p
```

> WARNING
> 
> **版本必须一致。** 模板在 `build.zig.zon` 中声明 `minimum_zig_version = "0.15.2"`；其他版本可能在构建 API 或包指纹上产生难以理解的错误。

## 创建项目

从仓库里的 `templates/minimal-app` 开始。它是一个完整的下游项目：

`templates/minimal-app`

```
minimal-app/
├── README.md
├── build.zig          # zenit.attach() + run / app steps
├── build.zig.zon      # declares the zenit dependency
├── e2e/
│   └── record-demo.ts # drives and records the app through the Harness
└── src/
    └── main.zig       # counter-button app
```

1.  **复制模板**
    
    把 templates/minimal-app 复制到 zenit 仓库之外的新目录。
    
2.  **调整依赖路径**
    
    模板默认 `.path = "../../"`，只在仓库内部有效。复制后改成新项目到 zenit checkout 的相对路径（相对 build.zig.zon 所在目录），或用 `zig fetch --save=zenit <url>` 固定到某个发布版本。
    
3.  **生成唯一指纹**
    
    不要沿用模板的 .fingerprint，否则两个项目会在 Zig 包缓存里冲突。删除这一行并运行一次 zig build，按错误提示填回生成值。顺手把 .name = .myapp 改成你的包名。
    

```sh
git clone https://github.com/version-next/zenit.git
cp -R zenit/templates/minimal-app ./myapp
cd myapp   # then set .zenit = .{ .path = "../zenit" } in build.zig.zon
zig build
```

## 连接 zenit

`build.zig.zon` 声明依赖；`build.zig` 用 `@import("zenit")` 拿到 zenit 自己的构建 API。

`build.zig.zon`

```zig
.{
    .name = .myapp,
    .version = "0.1.0",
    .fingerprint = 0x8798022a7f8e220e, // replace: delete this line, run zig build once
    .minimum_zig_version = "0.15.2",

    .dependencies = .{
        // Relative to this file. Absolute paths are rejected by Zig 0.15.2.
        .zenit = .{ .path = "../zenit" },
    },

    .paths = .{
        "README.md",
        "build.zig",
        "build.zig.zon",
        "e2e",
        "src",
    },
}
```

下面是模板里的 build.zig 原文。它不只是 attach 一行，还包含测试开关转发、Harness 客户端安装、run 步骤与 .app 打包：

`build.zig`

```zig
const std = @import("std");
const zenit = @import("zenit");

pub fn build(b: *std.Build) void {
    const target = b.standardTargetOptions(.{});
    const optimize = b.standardOptimizeOption(.{});
    const test_mode = b.option(bool, "test-mode", "Enable the Zenit automation harness") orelse false;
    const e2e_port = b.option(u16, "e2e-port", "Zenit Harness RPC directory suffix") orelse 19816;

    const zenit_dep = b.dependency("zenit", .{
        .target = target,
        .optimize = optimize,
        // Dependency build options are isolated in Zig. Forward these
        // explicitly so `zig build -Dtest-mode=true` reaches Zenit.
        .@"test-mode" = test_mode,
        .@"e2e-port" = e2e_port,
    });

    const exe = b.addExecutable(.{
        .name = "myapp",
        .root_module = b.createModule(.{
            .root_source_file = b.path("src/main.zig"),
            .target = target,
            .optimize = optimize,
        }),
    });

    zenit.attach(zenit_dep, exe);
    zenit.installHarnessClient(b, zenit_dep);

    b.installArtifact(exe);

    const run_cmd = b.addRunArtifact(exe);
    run_cmd.step.dependOn(b.getInstallStep());
    const run_step = b.step("run", "Run the app");
    run_step.dependOn(&run_cmd.step);

    // Optional: `zig build app` packages a double-clickable .app bundle.
    if (target.result.os.tag == .macos) {
        const bundled = zenit.bundleApp(b, .{
            .exe = exe,
            .display_name = "My App",
            .bundle_id = "com.example.myapp",
            .version = "0.1.0",
            .signing = .ad_hoc,
        });
        const app_step = b.step("app", "Build the .app bundle");
        app_step.dependOn(bundled.final_step);
    }
}
```

| 调用 | 作用 |
| --- | --- |
| `zenit.attach(zenit_dep, exe)` | 给 exe 加上 ui 与 zenit\_app 两个模块导入，编译 5 个 macOS ObjC 桥接，链接 Cocoa、Metal、CoreText 等系统框架 |
| `.@"test-mode" / .@"e2e-port"` | Zig 的依赖选项是隔离的，必须显式转发，zig build -Dtest-mode=true 才能到达 zenit |
| `zenit.installHarnessClient(b, zenit_dep)` | 把类型化的 Harness 客户端装到 zig-out/share/zenit/harness/client.ts，供 e2e/record-demo.ts 使用 |
| `zenit.bundleApp(b, .{ ... })` | 生成可双击的 zig-out/<display\_name>.app，示例使用 ad-hoc 签名 |

## 挂载第一棵 UI 树

`App.runWith` 创建根 Scope、调用一次挂载函数并接管事件循环。挂载函数的签名必须是 `fn (cx: *ui.Cx, scope: *ui.Scope) anyerror!*ui.Node`，应用只负责返回根节点。

`src/main.zig`

```zig
const std = @import("std");
const ui = @import("ui");
const App = @import("zenit_app").App;

const Counter = struct {
    n: u32 = 0,
    label: ?*ui.Node = null,
    buf: [32]u8 = undefined,

    pub fn increment(self: *Counter) void {
        self.n += 1;
        const node = self.label orelse return;
        const content = std.fmt.bufPrint(&self.buf, "Clicked {d} times", .{self.n}) catch return;
        if (node.getText()) |old| {
            var t = old;
            t.content = content;
            node.setText(t);
        }
        node.markRenderDirty();
    }
};

fn mountUi(cx: *ui.Cx, scope: *ui.Scope) anyerror!*ui.Node {
    const allocator = cx.allocator;

    const counter = try cx.bindState(Counter, .{});
    const click = cx.on(Counter, counter, Counter.increment);

    const root = try ui.box(cx, .{
        .width = .fill(),
        .height = .fill(),
        .direction = .column,
        .gap = 16,
        .padding = ui.Padding.all(40),
        .background = cx.tokens.color.bg_primary,
        .align_items = .center,
        .justify = .center,
    }, .{});

    try root.appendChild(allocator, try ui.text(cx, "Hello, zenit!", .{
        .font_size = 24,
        .font_weight = 600,
        .color = cx.tokens.color.fg_primary,
    }));

    const button = try ui.widgets.Button(.{
        .label = "Click me",
        .variant = .primary,
        .on_click = click,
    }).mount(scope, cx);
    button.meta.ownership.meta.test_id = "counter.increment";
    try root.appendChild(allocator, button);

    const label = try ui.text(cx, "Clicked 0 times", .{
        .font_size = 14,
        .color = cx.tokens.color.fg_secondary,
    });
    try root.appendChild(allocator, label);
    counter.label = label;

    return root;
}

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();

    const app = try App.init(gpa.allocator(), .{
        .window = .{ .width = 640, .height = 480, .title = "Hello, zenit" },
    });
    defer app.deinit();

    try app.runWith(mountUi);
}
```

`cx.bindState` 让 Cx 持有 `Counter`，`cx.on` 把它的方法变成按钮回调；`test_id` 让 E2E 脚本可以按语义找到按钮。

> NOTE
> 
> **模板为了最小而手动改文本。** 这里的缓冲区属于 `Counter`，地址稳定，所以直接借用给 `setText` 是安全的。真实应用中更常见的写法是把计数放进 Signal，用 `ui.textFmt` 自动更新，见[响应式系统](https://zenit.z.express/zh/docs/guide/reactivity)。

## 构建与运行

```sh
zig build run   # build and run the unbundled executable
zig build app   # package zig-out/My App.app (macOS)
```

[Video](https://zenit.z.express/media/hello-button.mp4?v=b4d2b8f8a0)

从构建产物启动的真实 Hello Button.app（examples/hello\_button，与模板同一个计数按钮）：Harness 用 hand 光标连续点击三次，文本更新为 Clicked 3 times。窗口、组件和响应都来自上面的公开 API。

模板还自带一段录制脚本：`zig build -Dtest-mode=true` 后启动应用，再运行 `e2e/record-demo.ts` 就能得到同样的录像，详见 [E2E 自动化](https://zenit.z.express/zh/docs/advanced/e2e)。

> TIP
> 
> **下一步。** 能看到窗口后，先学习项目结构与 UI 树；不要急着封装自己的组件体系，zenit 已经提供组件、主题和响应式原语。
