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

desktopCliCommand.ts

55 lines1.8 KB

1import type { DesktopBridge, DesktopCliCommandState } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as Schema from "effect/Schema";
4import { Atom } from "effect/reactivity";
5​
6import { appAtomRegistry } from "~/rpc/atomRegistry";
7import { msg } from "gt-react";
8​
9import { m } from "../i18n/messages";
10​
11type DesktopCliCommandBridge = DesktopBridge["cliCommand"];
12​
13class DesktopCliCommandUnavailableError extends Schema.TaggedError<DesktopCliCommandUnavailableError>()(
14 "DesktopCliCommandUnavailableError",
15 {},
16) {
17 override get message(): string {
18 return m(msg("The t3 command is unavailable."));
19 }
21​
22class DesktopCliCommandLoadError extends Schema.TaggedError<DesktopCliCommandLoadError>()(
23 "DesktopCliCommandLoadError",
24 { cause: Schema.Defect() },
25) {
26 override get message(): string {
27 return m(msg("Failed to load the t3 command state."));
28 }
30​
31export function getDesktopCliCommandBridge(): DesktopCliCommandBridge | undefined {
32 return typeof window === "undefined" ? undefined : window.desktopBridge?.cliCommand;
34​
35const loadDesktopCliCommandState = Effect.fn("loadDesktopCliCommandState")(function* () {
36 const bridge = getDesktopCliCommandBridge();
37 if (!bridge) {
38 return yield* new DesktopCliCommandUnavailableError();
39 }
40 return yield* Effect.tryPromise({
41 try: (): Promise<DesktopCliCommandState> => bridge.getState(),
42 catch: (cause) => new DesktopCliCommandLoadError({ cause }),
43 });
44});
45​
46export const desktopCliCommandStateAtom = Atom.make(loadDesktopCliCommandState()).pipe(
47 // Keep the loaded state, but let the SWR wrapper revalidate when Settings remounts.
48 Atom.keepAlive,
49 Atom.swr({ staleTime: 30_000, revalidateOnMount: true }),
50 Atom.withLabel("desktop:cli-command:load"),
51);
52​
53export function refreshDesktopCliCommandState(): void {
54 appAtomRegistry.refresh(desktopCliCommandStateAtom);