NarraLeaf
NarraLeaf DesktopRenderer

Main Events

从 NarraLeaf 渲染器调用主进程 handlers

NarraLeaf 提供用户级 renderer-to-main event API。在应用代码中,先在 AppWindow 上注册 handler,再从渲染器使用 requestMaininvokeMainEvent 调用

应用自己的功能不需要导入 IPCEventType、实现 IPCHandler,也不需要知道 NarraLeaf 内置 channel 名称

注册 Handler

main/index.ts
import { AppConfig } from "narraleaf";

const app = new AppConfig().create();

app.onReady(async () => {
    const win = await app.launchApp();

    win.handleUserEvent<{ id: string }, { ok: boolean }>(
        "example:ping",
        ({ id }) => {
            app.logger.info("ping", id);
            return { ok: true };
        },
    );
});

requestMain

当你愿意在调用点提供泛型 request/response 类型时,可以使用 requestMain 做简单调用

import { requestMain } from "narraleaf/renderer";

const result = await requestMain<{ id: string }, { ok: boolean }>(
    "example:ping",
    { id: "intro" },
);

当主进程报告失败时,requestMain 会抛出错误

类型化 Events

通过 TypeScript declaration merging 扩展 MainProcessEventMap,然后调用 invokeMainEvent

renderer/narraleaf-events.d.ts
import type { MainProcessEventEntry } from "narraleaf/renderer";

declare module "narraleaf/renderer" {
    interface MainProcessEventMap {
        "example:ping": MainProcessEventEntry<
            { id: string },
            { ok: boolean }
        >;
    }
}
import { invokeMainEvent } from "narraleaf/renderer";

const result = await invokeMainEvent("example:ping", {
    id: "intro",
});

在扩展 MainProcessEventMap 之前,不存在可用的类型化 event key

何时使用

当功能必须留在主进程中时使用 main events,例如原生对话框、文件系统访问、外部进程调用和应用自定义存储

游戏存档和应用播放状态请优先使用内置渲染器 API,例如 useSaveActionuseSavedGamesuseApp

更底层的 IPC

NarraLeaf 内部通过 preload bridge 实现这些调用。那些内置 IPC 契约属于框架管线;除非你正在扩展 NarraLeaf 本身,否则请使用上面的用户事件 API

本页目录