示例工程 30-multi-window-state

30-multi-window-state/app/shared/ipc.ts

typescript · 2.7 KB

export const CH = {
  get: "windows:get",
  create: "windows:create",
  focus: "windows:focus",
  close: "windows:close",
  move: "windows:move",
  message: "windows:message",
  restore: "windows:restore",
  reset: "windows:reset",
  changed: "windows:changed",
} as const;

export type WindowRole = "main" | "settings" | "inspector" | "note";
export type AuxRole = Exclude<WindowRole, "main">;

export type Rect = { x: number; y: number; width: number; height: number };

export type PersistedState = {
  bounds: Partial<Record<WindowRole, Rect>>;
  open: WindowRole[];
};

export type WindowInfo = {
  id: number;
  role: WindowRole;
  title: string;
  bounds: Rect;
  visible: boolean;
  focused: boolean;
  displayId: number | null;
};

export type DisplayInfo = {
  id: number;
  workArea: Rect;
  scaleFactor: number;
  primary: boolean;
};

export type WindowEvent = {
  at: number;
  source: "hub" | "aux" | "system";
  text: string;
};

export type WindowsSnapshot = {
  windows: WindowInfo[];
  storePath: string;
  persisted: PersistedState;
  displays: DisplayInfo[];
  events: WindowEvent[];
  lastMessage: string;
  restoredCount: number;
};

const AUX_ROLES: AuxRole[] = ["settings", "inspector", "note"];

export function isAuxRole(value: unknown): value is AuxRole {
  return AUX_ROLES.includes(value as AuxRole);
}

export function assertRoleReq(
  value: unknown,
): asserts value is { role: AuxRole } {
  if (typeof value !== "object" || value === null) {
    throw new Error("BAD_ROLE_REQ");
  }
  const role = (value as { role?: unknown }).role;
  if (!isAuxRole(role)) throw new Error("BAD_ROLE_REQ");
}

export function assertIdReq(value: unknown): asserts value is { id: number } {
  if (typeof value !== "object" || value === null) {
    throw new Error("BAD_ID_REQ");
  }
  const id = (value as { id?: unknown }).id;
  if (typeof id !== "number" || !Number.isFinite(id) || id <= 0) {
    throw new Error("BAD_ID_REQ");
  }
}

export function assertMoveReq(
  value: unknown,
): asserts value is { id: number; dx: number; dy: number } {
  assertIdReq(value);
  const { dx, dy } = value as { dx?: unknown; dy?: unknown };
  if (
    typeof dx !== "number" ||
    typeof dy !== "number" ||
    !Number.isFinite(dx) ||
    !Number.isFinite(dy) ||
    Math.abs(dx) > 2000 ||
    Math.abs(dy) > 2000
  ) {
    throw new Error("BAD_MOVE_REQ");
  }
}

export function assertMessageReq(
  value: unknown,
): asserts value is { text: string } {
  if (typeof value !== "object" || value === null) {
    throw new Error("BAD_MESSAGE_REQ");
  }
  const text = (value as { text?: unknown }).text;
  if (typeof text !== "string" || text.length === 0 || text.length > 200) {
    throw new Error("BAD_MESSAGE_REQ");
  }
}