示例工程 29-menu-tray
29-menu-tray/app/shared/ipc.ts
export const CH = {
get: "menu:get",
invoke: "menu:invoke",
setFlag: "menu:set-flag",
popup: "menu:popup",
reset: "menu:reset",
changed: "menu:changed",
} as const;
export type FlagKey = "compact" | "statusbar";
export type MenuItemView = {
id?: string;
label: string;
accelerator?: string;
type: "normal" | "checkbox" | "separator";
checked?: boolean;
enabled?: boolean;
role?: string;
};
export type MenuGroup = {
label: string;
role?: string;
items: MenuItemView[];
};
export type MenuEvent = {
at: number;
source: "menu" | "tray" | "context" | "inspector";
id: string;
label: string;
};
export type MenuSnapshot = {
platform: string;
compact: boolean;
statusbar: boolean;
syncing: boolean;
lastEvent: string;
appMenu: MenuGroup[];
trayMenu: MenuItemView[];
contextMenu: MenuItemView[];
events: MenuEvent[];
trayIcon: string;
windowVisible: boolean;
trayCreated: boolean;
};
export function assertInvokeReq(
value: unknown,
): asserts value is { id: string } {
if (typeof value !== "object" || value === null) {
throw new Error("BAD_INVOKE_REQ");
}
const id = (value as { id?: unknown }).id;
if (typeof id !== "string" || id.length === 0 || id.length > 64) {
throw new Error("BAD_INVOKE_REQ");
}
}
export function assertFlagReq(
value: unknown,
): asserts value is { key: FlagKey; value: boolean } {
if (typeof value !== "object" || value === null) {
throw new Error("BAD_FLAG_REQ");
}
const { key, value: flag } = value as { key?: unknown; value?: unknown };
if ((key !== "compact" && key !== "statusbar") || typeof flag !== "boolean") {
throw new Error("BAD_FLAG_REQ");
}
}
export function assertPopupReq(
value: unknown,
): asserts value is { x: number; y: number } {
if (typeof value !== "object" || value === null) {
throw new Error("BAD_POPUP_REQ");
}
const { x, y } = value as { x?: unknown; y?: unknown };
if (
typeof x !== "number" ||
typeof y !== "number" ||
!Number.isFinite(x) ||
!Number.isFinite(y) ||
x < 0 ||
y < 0 ||
x > 10000 ||
y > 10000
) {
throw new Error("BAD_POPUP_REQ");
}
}