aboutsummaryrefslogtreecommitdiffstats
path: root/apps/web/components/dashboard/settings/AddApiKey.tsx
blob: a4fd9c25598ff478bfbd5cde806c1f667c890462 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
"use client";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";

import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { z } from "zod";
import { useRouter } from "next/navigation";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm, SubmitErrorHandler } from "react-hook-form";
import { toast } from "@/components/ui/use-toast";
import { api } from "@/lib/trpc";
import { useState } from "react";
import { Check, Copy } from "lucide-react";
import { ActionButton } from "@/components/ui/action-button";

function ApiKeySuccess({ apiKey }: { apiKey: string }) {
  const [isCopied, setCopied] = useState(false);

  const onCopy = () => {
    navigator.clipboard.writeText(apiKey);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  return (
    <div>
      <div className="py-4">
        Note: please copy the key and store it somewhere safe. Once you close
        the dialog, you won&apos;t be able to access it again.
      </div>
      <div className="flex space-x-2 pt-2">
        <Input value={apiKey} readOnly />
        <Button onClick={onCopy}>
          {!isCopied ? (
            <Copy className="size-4" />
          ) : (
            <Check className="size-4" />
          )}
        </Button>
      </div>
    </div>
  );
}

function AddApiKeyForm({ onSuccess }: { onSuccess: (key: string) => void }) {
  const formSchema = z.object({
    name: z.string(),
  });
  const router = useRouter();
  const mutator = api.apiKeys.create.useMutation({
    onSuccess: (resp) => {
      onSuccess(resp.key);
      router.refresh();
    },
    onError: () => {
      toast({ description: "Something went wrong", variant: "destructive" });
    },
  });

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
  });

  async function onSubmit(value: z.infer<typeof formSchema>) {
    mutator.mutate({ name: value.name });
  }

  const onError: SubmitErrorHandler<z.infer<typeof formSchema>> = (errors) => {
    toast({
      description: Object.values(errors)
        .map((v) => v.message)
        .join("\n"),
      variant: "destructive",
    });
  };

  return (
    <Form {...form}>
      <form
        onSubmit={form.handleSubmit(onSubmit, onError)}
        className="flex w-full space-x-3 space-y-8 pt-4"
      >
        <FormField
          control={form.control}
          name="name"
          render={({ field }) => {
            return (
              <FormItem className="flex-1">
                <FormLabel>Name</FormLabel>
                <FormControl>
                  <Input type="text" placeholder="Name" {...field} />
                </FormControl>
                <FormDescription>
                  Give your API key a unique name
                </FormDescription>
                <FormMessage />
              </FormItem>
            );
          }}
        />
        <ActionButton
          className="h-full"
          type="submit"
          loading={mutator.isPending}
        >
          Create
        </ActionButton>
      </form>
    </Form>
  );
}

export default function AddApiKey() {
  const [key, setKey] = useState<string | undefined>(undefined);
  const [dialogOpen, setDialogOpen] = useState<boolean>(false);
  return (
    <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
      <DialogTrigger asChild>
        <Button>New API Key</Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>
            {key ? "Key was successfully created" : "Create API key"}
          </DialogTitle>
          <DialogDescription>
            {key ? (
              <ApiKeySuccess apiKey={key} />
            ) : (
              <AddApiKeyForm onSuccess={setKey} />
            )}
          </DialogDescription>
        </DialogHeader>
        <DialogFooter className="sm:justify-end">
          <DialogClose asChild>
            <Button
              type="button"
              variant="outline"
              onClick={() => setKey(undefined)}
            >
              Close
            </Button>
          </DialogClose>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}