Skip to content

Commit

Permalink
chore: 🤖 electron-trpc
Browse files Browse the repository at this point in the history
  • Loading branch information
meetqy committed Jun 23, 2023
1 parent 46c3b9d commit b196c9f
Show file tree
Hide file tree
Showing 6 changed files with 67 additions and 259 deletions.
109 changes: 20 additions & 89 deletions apps/electron/main/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import { app, ipcMain, shell, type IpcMain } from "electron";
import { createIPCHandler } from "electron-trpc/main";

import "./security-restrictions";
import type cp from "child_process";
import { app, ipcMain, shell } from "electron";
import { createIPCHandler } from "electron-trpc/main";
import ip from "ip";

import { appRouter } from "@acme/api";
Expand All @@ -11,7 +9,7 @@ import { closeAssetsServer } from "@acme/assets-server";
import globalApp from "./global";
import LibraryIPC from "./ipc/library";
import { syncIpc } from "./ipc/sync";
import { getWindow, pageUrl } from "./mainWindow";
import { getWindow } from "./mainWindow";
import { createWebServer } from "./src/createWebServer";
import createMenu from "./src/menu";
import createTray from "./src/tray";
Expand Down Expand Up @@ -93,45 +91,26 @@ if (process.platform === "darwin") {
app
.whenReady()
.then(() => {
// getWindow()
// .then(async (win) => {
// createIPCHandler({ router: appRouter, windows: [win] });
// // 托盘图标
// createTray();
// // 创建 Web/Assets 服务
// nextjsWebChild = await createWebServer();
// if (!nextjsWebChild) {
// throw Error("NextJS child process was not created, exiting...");
// }
// })
// .catch((err) => {
// throw err;
// });
getWindow()
.then(async (win) => {
createIPCHandler({ router: appRouter, windows: [win] });

// 托盘图标
createTray();

// 创建 Web/Assets 服务
nextjsWebChild = await createWebServer();
if (!nextjsWebChild) {
throw Error("NextJS child process was not created, exiting...");
}
})
.catch((err) => {
throw err;
});
})
.catch((e) => console.error("Failed create window:", e));

// function validateSender(frame: Electron.WebFrameMain) {
// const frameUrlObj = new URL(frame.url);
// const pageUrlObj = new URL(pageUrl);

// if (import.meta.env.DEV && import.meta.env.VITE_DEV_SERVER_URL !== undefined) {
// // during dev
// if (frameUrlObj.host === pageUrlObj.host) return true;
// } else {
// // during prod and test
// if (frameUrlObj.protocol === "file:") return true;
// }

// return false;
// }

export function initIpcHandle({ ipcMain }: { ipcMain: IpcMain }) {
// // https://www.electronjs.org/docs/latest/tutorial/security#17-validate-the-sender-of-all-ipc-messages
// ipcMain.handle("electron-trpc", (event: Electron.IpcMainInvokeEvent, opts: IPCRequestOptions) => {
// if (!validateSender(event.senderFrame)) return null;
// return resolveIPCResponse(opts);
// });

app.on("ready", () => {
ipcMain.handle("open-url", (event, url: string) => {
void shell.openExternal(url);
});
Expand All @@ -150,52 +129,4 @@ export function initIpcHandle({ ipcMain }: { ipcMain: IpcMain }) {
LibraryIPC.choose(ipcMain);
LibraryIPC.update(ipcMain);
syncIpc(ipcMain);
}

// functional happy path, types get inferred
// async function resolveIPCResponse(opts: IPCRequestOptions) {
// const { path, type, input } = opts;
// const { procedures } = appRouter._def;
// const ctx = createContext();

// try {
// const output = await callProcedure({
// ctx,
// path,
// procedures,
// rawInput: input,
// type,
// });

// return {
// result: output,
// status: "success",
// };
// } catch (e) {
// return {
// result: e,
// status: "error",
// };
// }
// }

app.on("ready", () => {
getWindow()
.then(async (win) => {
createIPCHandler({ router: appRouter, windows: [win] });

// 托盘图标
createTray();

// 创建 Web/Assets 服务
nextjsWebChild = await createWebServer();
if (!nextjsWebChild) {
throw Error("NextJS child process was not created, exiting...");
}
})
.catch((err) => {
throw err;
});
// initIpcHandle({ ipcMain });
// createIPCHandler({ ipcMain });
});
147 changes: 0 additions & 147 deletions apps/electron/main/security-restrictions.ts

This file was deleted.

27 changes: 27 additions & 0 deletions apps/electron/preload/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import { type TRPCResponseMessage } from "@trpc/server/rpc";
import { contextBridge, ipcRenderer, type IpcRendererEvent } from "electron";
import { type RendererGlobalElectronTRPC } from "types";

import { type Library } from "@acme/db";
import { type EagleEmit, type EagleEmitOption } from "@acme/eagle";

const exposeElectronTRPC = () => {
const electronTRPC: RendererGlobalElectronTRPC = {
sendMessage: (operation: unknown) => ipcRenderer.send("electron-trpc", operation),
Expand All @@ -14,4 +17,28 @@ const exposeElectronTRPC = () => {

process.once("loaded", () => {
exposeElectronTRPC();

contextBridge.exposeInMainWorld("electronAPI", {
library: {
choose: () => ipcRenderer.invoke("library-choose"),
update: (dir: string) => ipcRenderer.invoke("library-update", dir),
assetsServer: (librarys: Library[]) => ipcRenderer.invoke("library-assets-server", librarys),
},
sync: (library: Library) => ipcRenderer.send("sync", library),
onEagleSyncProgress: (listener: EagleEmit) =>
ipcRenderer.on("on-eagle-sync-progress", (_e, ...args) => {
const options = args[0] as EagleEmitOption;
listener(options);
}),
openUrl: (url: string) => ipcRenderer.invoke("open-url", url),
getEnv: () => ipcRenderer.invoke("get-env"),
});

contextBridge.exposeInMainWorld("electronENV", {
ip: process.env["IP"],
web_port: process.env["WEB_PORT"],
assets_port: process.env["ASSETS_PORT"],
name: process.env["APP_NAME"],
version: process.env["APP_VERSION"],
});
});
22 changes: 1 addition & 21 deletions apps/electron/renderer/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { TRPCClientError, type TRPCLink } from "@trpc/client";
import { type AnyRouter, type inferRouterError } from "@trpc/server";
import { observable } from "@trpc/server/observable";
import { type TRPCResultMessage } from "@trpc/server/rpc";
import { ipcLink } from "electron-trpc/renderer";
import { useState } from "react";
import superjson from "superjson";

import { IPCResponse } from "../../types";
// import Home from "./Home";
import HelloElectron from "./HelloElectron";
import { trpc } from "./utils/trpc";

function App() {
Expand All @@ -29,19 +24,4 @@ function App() {
);
}

function HelloElectron() {
const { data } = trpc.greeting.useQuery({ name: "Electron" });
trpc.subscription.useSubscription(undefined, {
onData: (data) => {
console.log(data);
},
});

if (!data) {
return null;
}

return <div>{data.text}</div>;
}

export default App;
18 changes: 18 additions & 0 deletions apps/electron/renderer/src/HelloElectron.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { trpc } from "./utils/trpc";

function HelloElectron() {
const { data } = trpc.greeting.useQuery({ name: "Electron" });
trpc.subscription.useSubscription(undefined, {
onData: (data) => {
console.log(data);
},
});

if (!data) {
return null;
}

return <div>{data.text}</div>;
}

export default HelloElectron;
3 changes: 1 addition & 2 deletions packages/api/src/root.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { EventEmitter } from "events";
import { observable } from "@trpc/server/observable";
import { set, z } from "zod";
import { z } from "zod";

import { configRouter } from "./router/config";
import { foldersRouter } from "./router/folder";
Expand All @@ -20,7 +20,6 @@ export const appRouter = t.router({
config: configRouter,
tags: tagsRouter,
folders: foldersRouter,

greeting: t.procedure.input(z.object({ name: z.string() })).query((req) => {
const { input } = req;

Expand Down

0 comments on commit b196c9f

Please sign in to comment.