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

CliCommandSettingsRow.tsx

88 lines3.0 KB

1import { useState } from "react";
2​
3import {
4 desktopCliCommandStateAtom,
5 getDesktopCliCommandBridge,
6 refreshDesktopCliCommandState,
7} from "~/state/desktopCliCommand";
8import { useEnvironmentQuery } from "~/state/query";
9import { Button } from "../ui/button";
10import { stackedThreadToast, toastManager } from "../ui/toast";
11import { SettingsRow } from "./settingsLayout";
12import { searchableSetting } from "./settingsSearch";
13​
14const FAILURE_TITLES = {
15 install: "Could not install t3",
16 uninstall: "Could not remove t3",
17 addToPath: "Could not add t3 to PATH",
18} as const;
19​
20/** The desktop `t3` command's state, and its actions with a toast on failure. */
21export function useDesktopCliCommand() {
22 const bridge = getDesktopCliCommandBridge();
23 const query = useEnvironmentQuery(bridge ? desktopCliCommandStateAtom : null);
24 const [pending, setPending] = useState(false);
25​
26 const run = (action: keyof typeof FAILURE_TITLES) => {
27 if (!bridge || pending) return;
28 setPending(true);
29 void bridge[action]()
30 .then(refreshDesktopCliCommandState)
31 .catch((error: unknown) => {
32 toastManager.add(
33 stackedThreadToast({
34 type: "error",
35 title: FAILURE_TITLES[action],
36 description: error instanceof Error ? error.message : "Something went wrong.",
37 }),
38 );
39 })
40 .finally(() => setPending(false));
41 };
42​
43 return {
44 state: bridge ? query.data : undefined,
45 busy: pending || query.isPending,
46 run,
47 };
49​
50export function CliCommandSettingsRow() {
51 const { state, busy, run } = useDesktopCliCommand();
52​
53 if (!state?.supported) return null;
54 const installed = state.installedPath !== null;
55 const description = state.shadowedBy
56 ? `Another t3 at ${state.shadowedBy} runs first in a new terminal. Remove it to use T3 Code's.`
57 : !installed
58 ? "Run T3 Code's CLI as `t3` from any terminal."
59 : state.onPath
60 ? `Installed at ${state.installedPath}. Open a new terminal to use it.`
61 : state.pathSetup?.added
62 ? `Installed at ${state.installedPath} and added to PATH in ${state.pathSetup.file}. Open a new terminal to use it.`
63 : `Installed at ${state.installedPath}, which is not on your PATH yet.${state.pathSetup ? "" : " Add its folder to your PATH to run `t3`."}`;
64​
65 return (
66 <SettingsRow
67 {...searchableSetting("cli-command")}
68 description={description}
69 control={
70 <div className="flex gap-2">
71 {state.pathSetup && !state.pathSetup.added ? (
72 <Button size="sm" variant="outline" disabled={busy} onClick={() => run("addToPath")}>
73 Add to PATH
74 </Button>
75 ) : null}
76 <Button
77 size="sm"
78 variant="outline"
79 disabled={busy || (!installed && Boolean(state.shadowedBy))}
80 onClick={() => run(installed ? "uninstall" : "install")}
81 >
82 {installed ? "Remove" : "Install"}
83 </Button>
84 </div>
85 }
86 />
87 );