forked from sqlchat/sqlchat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCreateConnectionModal.tsx
More file actions
453 lines (430 loc) · 14.9 KB
/
CreateConnectionModal.tsx
File metadata and controls
453 lines (430 loc) · 14.9 KB
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
import { cloneDeep, head } from "lodash-es";
import { ChangeEvent, useEffect, useState } from "react";
import { toast } from "react-hot-toast";
import TextareaAutosize from "react-textarea-autosize";
import { useConnectionStore } from "@/store";
import { Connection, Engine, ResponseObject, SSLOptions } from "@/types";
import Select from "./kit/Select";
import TextField from "./kit/TextField";
import Modal from "./kit/Modal";
import Icon from "./Icon";
import DataStorageBanner from "./DataStorageBanner";
import ActionConfirmModal from "./ActionConfirmModal";
import { useTranslation } from "react-i18next";
interface Props {
connection?: Connection;
close: () => void;
}
type SSLType = "none" | "ca-only" | "full";
type SSLFieldType = "ca" | "cert" | "key";
const SSLTypeOptions = [
{
label: "None",
value: "none",
},
{
label: "CA Only",
value: "ca-only",
},
{
label: "Full",
value: "full",
},
];
const defaultConnection: Connection = {
id: "",
title: "",
engineType: Engine.MySQL,
host: "",
port: "",
username: "",
password: "",
};
const CreateConnectionModal = (props: Props) => {
const { connection: editConnection, close } = props;
const { t } = useTranslation();
const connectionStore = useConnectionStore();
const [connection, setConnection] = useState<Connection>(defaultConnection);
const [showDeleteConnectionModal, setShowDeleteConnectionModal] =
useState(false);
const [sslType, setSSLType] = useState<SSLType>("none");
const [selectedSSLField, setSelectedSSLField] = useState<SSLFieldType>("ca");
const [isRequesting, setIsRequesting] = useState(false);
const showDatabaseField = connection.engineType === Engine.PostgreSQL;
const isEditing = editConnection !== undefined;
const allowSave = connection.host !== "" && connection.username !== "";
useEffect(() => {
const connection = isEditing ? editConnection : defaultConnection;
setConnection(connection);
if (connection.ssl) {
if (connection.ssl.ca && connection.ssl.cert && connection.ssl.key) {
setSSLType("full");
} else {
setSSLType("ca-only");
}
}
}, []);
useEffect(() => {
let ssl: SSLOptions | undefined = undefined;
if (sslType === "ca-only") {
ssl = {
ca: "",
};
} else if (sslType === "full") {
ssl = {
ca: "",
cert: "",
key: "",
};
}
setConnection((connection) => ({
...connection,
ssl: ssl,
}));
setSelectedSSLField("ca");
}, [sslType]);
const setPartialConnection = (state: Partial<Connection>) => {
setConnection({
...connection,
...state,
});
};
const handleSSLFileInputChange = (event: ChangeEvent<HTMLInputElement>) => {
const files = event.currentTarget.files;
if (!files || files.length === 0) {
return;
}
const file = files[0];
if (
file.type.startsWith("audio/") ||
file.type.startsWith("video/") ||
file.type.startsWith("image/")
) {
toast.error(`Invalid file type:${file.type}`);
return;
}
const fr = new FileReader();
fr.addEventListener("load", () => {
setPartialConnection({
ssl: {
...connection.ssl,
[selectedSSLField]: fr.result as string,
},
});
});
fr.addEventListener("error", () => {
toast.error("Failed to read file");
});
fr.readAsText(file);
};
const handleSSLValueChange = (event: ChangeEvent<HTMLTextAreaElement>) => {
setPartialConnection({
ssl: {
...connection.ssl,
[selectedSSLField]: event.target.value,
},
});
};
const handleCreateConnection = async () => {
if (isRequesting) {
return;
}
setIsRequesting(true);
const tempConnection = cloneDeep(connection);
if (!showDatabaseField) {
tempConnection.database = undefined;
}
try {
const response = await fetch("/api/connection/test", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
connection: tempConnection,
}),
});
const result = (await response.json()) as ResponseObject<boolean>;
if (result.message) {
toast.error(result.message);
return;
}
} catch (error) {
console.error(error);
toast.error("Failed to test connection");
} finally {
setIsRequesting(false);
}
try {
let connection: Connection;
if (isEditing) {
connectionStore.updateConnection(tempConnection.id, tempConnection);
connection = tempConnection;
} else {
connection = connectionStore.createConnection(tempConnection);
}
// Set the created connection as the current connection.
const databaseList = await connectionStore.getOrFetchDatabaseList(
connection,
true
);
connectionStore.setCurrentConnectionCtx({
connection: connection,
database: head(databaseList),
});
} catch (error) {
console.error(error);
setIsRequesting(false);
toast.error("Failed to create connection");
return;
}
setIsRequesting(false);
close();
};
const handleDeleteConnection = () => {
connectionStore.clearConnection((item) => item.id !== connection.id);
if (connectionStore.currentConnectionCtx?.connection.id === connection.id) {
connectionStore.setCurrentConnectionCtx(undefined);
}
close();
};
return (
<>
<Modal
title={isEditing ? t("connection.edit") : t("connection.new")}
onClose={close}
>
<div className="w-full flex flex-col justify-start items-start space-y-3 mt-2">
<DataStorageBanner
className="rounded-lg bg-white border dark:border-zinc-700 py-2 !justify-start"
alwaysShow={true}
/>
<div className="w-full flex flex-col">
<label className="block text-sm font-medium text-gray-700 mb-1">
{t("connection.database-type")}
</label>
<Select
className="w-full"
value={connection.engineType}
itemList={[
{ value: Engine.MySQL, label: "MySQL" },
{ value: Engine.PostgreSQL, label: "PostgreSQL" },
{ value: Engine.MSSQL, label: "MSSQL" },
]}
onValueChange={(value) =>
setPartialConnection({ engineType: value as Engine })
}
/>
</div>
<div className="w-full flex flex-col">
<label className="block text-sm font-medium text-gray-700 mb-1">
{t("connection.title")}
</label>
<TextField
placeholder="Title"
value={connection.title}
onChange={(value) => setPartialConnection({ title: value })}
/>
</div>
<div className="w-full flex flex-col">
<label className="block text-sm font-medium text-gray-700 mb-1">
{t("connection.host")}
</label>
<TextField
placeholder="Connection host"
value={connection.host}
onChange={(value) => setPartialConnection({ host: value })}
/>
</div>
<div className="w-full flex flex-col">
<label className="block text-sm font-medium text-gray-700 mb-1">
{t("connection.port")}
</label>
<TextField
placeholder="Connection port"
value={connection.port}
onChange={(value) => setPartialConnection({ port: value })}
/>
</div>
{showDatabaseField && (
<div className="w-full flex flex-col">
<label className="block text-sm font-medium text-gray-700 mb-1">
{t("connection.database-name")}
</label>
<TextField
placeholder="Connection database"
value={connection.database || ""}
onChange={(value) => setPartialConnection({ database: value })}
/>
</div>
)}
<div className="w-full flex flex-col">
<label className="block text-sm font-medium text-gray-700 mb-1">
{t("connection.username")}
</label>
<TextField
placeholder="Connection username"
value={connection.username || ""}
onChange={(value) => setPartialConnection({ username: value })}
/>
</div>
<div className="w-full flex flex-col">
<label className="block text-sm font-medium text-gray-700 mb-1">
{t("connection.password")}
</label>
<TextField
placeholder="Connection password"
type="password"
value={connection.password || ""}
onChange={(value) => setPartialConnection({ password: value })}
/>
</div>
<div className="w-full flex flex-col">
<label className="block text-sm font-medium text-gray-700 mb-1">
SSL
</label>
<div className="w-full flex flex-row justify-start items-start flex-wrap">
{SSLTypeOptions.map((option) => (
<label
key={option.value}
className="w-auto flex flex-row justify-start items-center cursor-pointer mr-3 mb-3"
>
<input
type="radio"
className="radio w-4 h-4 mr-1"
value={option.value}
checked={sslType === option.value}
onChange={(e) => setSSLType(e.target.value as SSLType)}
/>
<span className="text-sm">{option.label}</span>
</label>
))}
</div>
{sslType !== "none" && (
<>
<div className="text-sm space-x-3 mb-2">
<span
className={`leading-6 pb-1 border-b-2 border-transparent cursor-pointer opacity-60 hover:opacity-80 ${
selectedSSLField === "ca" &&
"!border-indigo-600 !opacity-100"
} `}
onClick={() => setSelectedSSLField("ca")}
>
CA Certificate
</span>
{sslType === "full" && (
<>
<span
className={`leading-6 pb-1 border-b-2 border-transparent cursor-pointer opacity-60 hover:opacity-80 ${
selectedSSLField === "key" &&
"!border-indigo-600 !opacity-100"
}`}
onClick={() => setSelectedSSLField("key")}
>
Client Key
</span>
<span
className={`leading-6 pb-1 border-b-2 border-transparent cursor-pointer opacity-60 hover:opacity-80 ${
selectedSSLField === "cert" &&
"!border-indigo-600 !opacity-100"
}`}
onClick={() => setSelectedSSLField("cert")}
>
Client Certificate
</span>
</>
)}
</div>
<div className="w-full h-auto relative">
<TextareaAutosize
className="w-full border resize-none rounded-lg text-sm p-3"
minRows={3}
maxRows={3}
value={
(connection.ssl && connection.ssl[selectedSSLField]) ?? ""
}
onChange={handleSSLValueChange}
/>
<div
className={`${
connection.ssl &&
connection.ssl[selectedSSLField] &&
"hidden"
} absolute top-3 left-4 text-gray-400 text-sm leading-6 pointer-events-none`}
>
<span className="">Input or </span>
<label className="pointer-events-auto border border-dashed px-2 py-1 rounded-lg cursor-pointer hover:border-gray-600 hover:text-gray-600">
upload file
<input
className="hidden"
type="file"
onChange={handleSSLFileInputChange}
/>
</label>
</div>
</div>
</>
)}
{connection.engineType === Engine.MSSQL && (
<div className="w-full flex flex-col">
<label className="block text-sm font-medium text-gray-700 mb-1">
Encrypt
</label>
<div className="w-full flex flex-row justify-start items-start flex-wrap">
<label className="flex items-center">
<input
type="checkbox"
className="form-checkbox h-4 w-4 text-indigo-600 transition duration-150 ease-in-out"
checked={connection.encrypt}
onChange={(e) =>
setPartialConnection({ encrypt: e.target.checked })
}
/>
<span className="ml-2 text-sm">Encrypt connection</span>
</label>
</div>
</div>
)}
</div>
</div>
<div className="modal-action w-full flex flex-row justify-between items-center space-x-2">
<div>
{isEditing && (
<button
className="btn btn-outline"
onClick={() => setShowDeleteConnectionModal(true)}
>
Delete
</button>
)}
</div>
<div className="space-x-2 flex flex-row justify-center">
<button className="btn btn-outline" onClick={close}>
{t("common.close")}
</button>
<button
className="btn"
disabled={isRequesting || !allowSave}
onClick={handleCreateConnection}
>
{isRequesting && (
<Icon.BiLoaderAlt className="w-4 h-auto animate-spin mr-1" />
)}
{t("common.save")}
</button>
</div>
</div>
</Modal>
{showDeleteConnectionModal && (
<ActionConfirmModal
title="Delete Connection"
content="Are you sure you want to delete this connection?"
confirmButtonStyle="btn-error"
close={() => setShowDeleteConnectionModal(false)}
confirm={() => handleDeleteConnection()}
/>
)}
</>
);
};
export default CreateConnectionModal;