Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ElectronShell.ts

50 lines1.4 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Option from "effect/Option";
5​
6import * as Electron from "electron";
7​
8const SAFE_EXTERNAL_PROTOCOLS = new Set(["http:", "https:"]);
9​
10export function parseSafeExternalUrl(rawUrl: unknown): Option.Option<string> {
11 if (typeof rawUrl !== "string") {
12 return Option.none();
13 }
14​
15 try {
16 const url = new URL(rawUrl);
17 return SAFE_EXTERNAL_PROTOCOLS.has(url.protocol) ? Option.some(url.href) : Option.none();
18 } catch {
19 return Option.none();
20 }
22​
23export interface ElectronShellShape {
24 readonly openExternal: (rawUrl: unknown) => Effect.Effect<boolean>;
25 readonly copyText: (text: string) => Effect.Effect<void>;
27​
28export class ElectronShell extends Context.Service<ElectronShell, ElectronShellShape>()(
29 "@t3tools/desktop/electron/ElectronShell",
30) {}
31​
32const make = ElectronShell.of({
33 openExternal: (rawUrl) =>
34 Option.match(parseSafeExternalUrl(rawUrl), {
35 onNone: () => Effect.succeed(false),
36 onSome: (externalUrl) =>
37 Effect.promise(() =>
38 Electron.shell.openExternal(externalUrl).then(
39 () => true,
40 () => false,
41 ),
42 ),
43 }),
44 copyText: (text) =>
45 Effect.sync(() => {
46 Electron.clipboard.writeText(text);
47 }),
48});
49​
50export const layer = Layer.succeed(ElectronShell, make);