-
-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathNewConnectionModal.tsx
More file actions
1525 lines (1464 loc) · 56.1 KB
/
NewConnectionModal.tsx
File metadata and controls
1525 lines (1464 loc) · 56.1 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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { useState, useEffect, useMemo, useCallback, useRef } from "react";
import { useTranslation } from "react-i18next";
import {
X,
Check,
AlertCircle,
Loader2,
Database,
Settings,
XCircle,
FolderOpen,
CheckSquare,
Square,
Plug,
Info,
} from "lucide-react";
import { invoke } from "@tauri-apps/api/core";
import { open } from "@tauri-apps/plugin-dialog";
import clsx from "clsx";
import { SshConnectionsModal } from "./SshConnectionsModal";
import { Select } from "../ui/Select";
import { SlotAnchor } from "../ui/SlotAnchor";
import { useDrivers } from "../../hooks/useDrivers";
import { usePluginSlotRegistry } from "../../hooks/usePluginSlotRegistry";
import { Modal } from "../ui/Modal";
import type { PluginManifest } from "../../types/plugins";
import { loadSshConnections, type SshConnection } from "../../utils/ssh";
import { isMultiDatabaseCapable } from "../../utils/database";
import { fetchConnectionWithCredentials } from "../../utils/credentials";
import { getDriverIcon, getDriverColorStyle } from "../../utils/driverUI";
import {
looksLikeConnectionString,
parseConnectionString,
toConnectionParams,
} from "../../utils/connectionStringParser";
interface ConnectionParams {
driver: string;
host?: string;
port?: number;
username?: string;
password?: string;
database: string | string[];
ssl_mode?: string;
ssl_ca?: string;
ssl_cert?: string;
ssl_key?: string;
// SSH
ssh_enabled?: boolean;
ssh_connection_id?: string;
// Legacy SSH fields (for backward compatibility)
ssh_host?: string;
ssh_port?: number;
ssh_user?: string;
ssh_password?: string;
ssh_key_file?: string;
ssh_key_passphrase?: string;
save_in_keychain?: boolean;
}
interface SavedConnection {
id: string;
name: string;
params: ConnectionParams;
}
interface NewConnectionModalProps {
isOpen: boolean;
onClose: () => void;
onSave?: () => void;
initialConnection?: SavedConnection | null;
}
const FieldInput = ({
label,
value,
onChange,
type = "text",
placeholder,
autoFocus,
className,
}: {
label: string;
value: string | number | undefined;
onChange: (v: string) => void;
type?: string;
placeholder?: string;
autoFocus?: boolean;
className?: string;
}) => (
<div className={clsx("flex flex-col gap-1", className)}>
<label className="text-[10px] uppercase font-semibold tracking-wider text-muted">
{label}
</label>
<input
type={type}
value={value ?? ""}
onChange={(e) => onChange(e.target.value)}
placeholder={placeholder}
autoFocus={autoFocus}
autoCorrect="off"
autoCapitalize="off"
autoComplete="off"
spellCheck={false}
className="w-full px-3 py-2 bg-base border border-strong rounded-md text-sm text-primary placeholder:text-muted placeholder:italic focus:border-blue-500 focus:outline-none transition-colors"
/>
</div>
);
export const NewConnectionModal = ({
isOpen,
onClose,
onSave,
initialConnection,
}: NewConnectionModalProps) => {
const { t } = useTranslation();
const { drivers } = useDrivers();
// ── form state ──
const [driver, setDriver] = useState<string>("mysql");
const activeDriver = drivers.find((d) => d.id === driver) ?? drivers[0];
const [name, setName] = useState("");
const [formData, setFormData] = useState<Partial<ConnectionParams>>({
host: "localhost",
port: 3306,
username: "",
database: "",
ssl_mode: "",
ssh_enabled: false,
ssh_port: 22,
});
const [selectedDatabasesState, setSelectedDatabasesState] = useState<
string[]
>([]);
const [dbSearchQuery, setDbSearchQuery] = useState("");
const [passwordDirty, setPasswordDirty] = useState(false);
const [sshPasswordDirty, setSshPasswordDirty] = useState(false);
const [connectionString, setConnectionString] = useState("");
const [connectionStringError, setConnectionStringError] = useState<
string | null
>(null);
// ── tab ──
const [activeTab, setActiveTab] = useState<"general" | "databases" | "ssh" | "ssl">(
"general",
);
// ── SSH ──
const [sshConnections, setSshConnections] = useState<SshConnection[]>([]);
const [isSshModalOpen, setIsSshModalOpen] = useState(false);
const [sshMode, setSshMode] = useState<"existing" | "inline">("existing");
// ── databases ──
const [availableDatabases, setAvailableDatabases] = useState<string[]>([]);
const [loadingDatabases, setLoadingDatabases] = useState(false);
const [databaseLoadError, setDatabaseLoadError] = useState<string | null>(
null,
);
// ── connection test ──
const [status, setStatus] = useState<
"idle" | "testing" | "saving" | "success" | "error"
>("idle");
const [message, setMessage] = useState("");
const [testResult, setTestResult] = useState<"success" | "error" | null>(
null,
);
// ── validation errors ──
const [nameError, setNameError] = useState(false);
const nameInputRef = useRef<HTMLInputElement>(null);
const [databasesTabError, setDatabasesTabError] = useState(false);
// ── capabilities ──
const noConnectionRequired =
activeDriver?.capabilities?.no_connection_required === true;
const isNetworkDriver =
!noConnectionRequired &&
activeDriver?.capabilities?.file_based === false &&
!activeDriver?.capabilities?.folder_based;
const connectionStringEnabled =
activeDriver?.capabilities?.connection_string ??
activeDriver?.capabilities?.connectionString ??
true;
const connectionStringPlaceholder =
activeDriver?.capabilities?.connection_string_example?.trim() ||
activeDriver?.capabilities?.connectionStringExample?.trim() ||
t("newConnection.connectionStringPlaceholder", {
defaultValue: "e.g. mysql://user:pass@localhost:3306/db",
});
const isMultiDb = isMultiDatabaseCapable(activeDriver?.capabilities);
// ── plugin slot: connection-modal.connection_content ──
const slotRegistry = usePluginSlotRegistry();
const onDatabaseChange = useCallback((value: string) => {
setFormData((prev) => ({ ...prev, database: value }));
}, []);
const dbFieldSlotContext = useMemo(
() => ({
driver,
database: typeof formData.database === "string" ? formData.database : "",
onDatabaseChange,
connectionName: name,
}),
[driver, formData.database, onDatabaseChange, name],
);
const hasConnectionContentSlot =
noConnectionRequired &&
slotRegistry.getSlotContributions(
"connection-modal.connection_content",
dbFieldSlotContext,
).length > 0;
// ── helpers ──
const loadSshConnectionsList = async () => {
const result = await loadSshConnections();
setSshConnections(result);
};
const updateField = (
field: keyof ConnectionParams,
value: string | number | boolean | undefined,
) => {
setFormData((prev) => ({ ...prev, [field]: value }));
};
const loadDatabases = async (overrides?: Partial<ConnectionParams>) => {
const effectiveDriver = overrides?.driver ?? driver;
const targetDriver = drivers.find((d) => d.id === effectiveDriver);
if (
targetDriver?.capabilities?.file_based === true ||
targetDriver?.capabilities?.folder_based === true
) {
return;
}
setLoadingDatabases(true);
setDatabaseLoadError(null);
try {
const listParams: Partial<ConnectionParams> = {
...formData,
...overrides,
driver: effectiveDriver,
port:
overrides?.port != null
? Number(overrides.port)
: formData.port != null
? Number(formData.port)
: undefined,
};
const databases = await invoke<string[]>("list_databases", {
request: {
params: { ...listParams },
connection_id: initialConnection?.id,
},
});
setAvailableDatabases(databases);
if (initialConnection) {
// Pre-select databases already associated with the connection
const existing = Array.isArray(initialConnection.params.database)
? initialConnection.params.database
: initialConnection.params.database
? [initialConnection.params.database as string]
: [];
setSelectedDatabasesState((prev) => {
const merged = Array.from(new Set([...existing, ...prev]));
return merged.filter((db) => databases.includes(db));
});
}
} catch (err) {
const errorMsg =
typeof err === "string"
? err
: err instanceof Error
? err.message
: t("newConnection.failLoadDatabases");
setDatabaseLoadError(errorMsg);
setAvailableDatabases([]);
} finally {
setLoadingDatabases(false);
}
};
// ── init form on open ──
useEffect(() => {
if (!isOpen) return;
const init = async () => {
// Reset common state first so it's always clean even if async calls below fail
setStatus("idle");
setMessage("");
setTestResult(null);
setActiveTab("general");
setAvailableDatabases([]);
setDatabaseLoadError(null);
setPasswordDirty(false);
setSshPasswordDirty(false);
setDbSearchQuery("");
setConnectionString("");
setConnectionStringError(null);
setNameError(false);
setDatabasesTabError(false);
if (initialConnection) {
setName(initialConnection.name);
setDriver(initialConnection.params.driver);
const db = initialConnection.params.database;
setSshMode(
initialConnection.params.ssh_connection_id ? "existing" : "inline",
);
let params = initialConnection.params;
try {
const fullConn = await fetchConnectionWithCredentials(
initialConnection.id,
);
params = fullConn.params;
} catch {
// fallback: use params without secrets (backend will retrieve from keychain)
}
if (Array.isArray(db)) {
setSelectedDatabasesState(db);
setFormData({ ...params, database: db[0] ?? "" });
} else {
setSelectedDatabasesState([]);
setFormData({ ...params });
}
// Auto-load available databases when editing a multi-db connection
const editDriver = drivers.find(
(d) => d.id === initialConnection.params.driver,
);
if (isMultiDatabaseCapable(editDriver?.capabilities)) {
loadDatabases(params);
}
} else {
setName("");
setDriver("mysql");
setFormData({
host: "localhost",
port: 3306,
username: "",
database: "",
ssh_enabled: false,
ssh_port: 22,
});
setSelectedDatabasesState([]);
setSshMode("existing");
}
await loadSshConnectionsList();
};
void init();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isOpen, initialConnection]);
const handleDriverChange = (newDriver: string) => {
setDriver(newDriver);
setFormData({
driver: newDriver,
host: "",
port: drivers.find((d) => d.id === newDriver)?.default_port ?? undefined,
username: "",
password: "",
database: "",
ssl_mode: "",
ssh_enabled: false,
ssh_connection_id: undefined,
ssh_host: undefined,
ssh_port: 22,
ssh_user: undefined,
ssh_password: undefined,
ssh_key_file: undefined,
ssh_key_passphrase: undefined,
save_in_keychain: false,
});
setSelectedDatabasesState([]);
setDbSearchQuery("");
setAvailableDatabases([]);
setDatabaseLoadError(null);
setStatus("idle");
setMessage("");
setActiveTab("general");
setConnectionString("");
setConnectionStringError(null);
setNameError(false);
setDatabasesTabError(false);
};
const testConnection = async () => {
setStatus("testing");
setMessage("");
setTestResult(null);
try {
const testParams: Partial<ConnectionParams> = {
driver,
...formData,
port: formData.port != null ? Number(formData.port) : undefined,
database: isMultiDb
? (selectedDatabasesState[0] ??
(typeof formData.database === "string" ? formData.database : ""))
: formData.database,
};
const result = await invoke<string>("test_connection", {
request: {
params: { ...testParams },
connection_id: initialConnection?.id,
},
});
setStatus("success");
setMessage(result);
setTestResult("success");
setTimeout(() => {
setTestResult(null);
setStatus("idle");
setMessage("");
}, 3000);
return true;
} catch (err) {
setStatus("error");
const msg =
typeof err === "string"
? err
: err instanceof Error
? err.message
: JSON.stringify(err);
setMessage(msg);
setTestResult("error");
setTimeout(() => {
setTestResult(null);
setStatus("idle");
}, 3000);
return false;
}
};
const saveConnection = async () => {
if (!name.trim()) {
setStatus("error");
setMessage(t("newConnection.nameRequired"));
setTestResult("error");
setNameError(true);
nameInputRef.current?.focus();
return;
}
if (isMultiDb) {
if (selectedDatabasesState.length === 0) {
setStatus("error");
setMessage(t("newConnection.noDatabasesSelected"));
setTestResult("error");
setActiveTab("databases");
setDatabasesTabError(true);
return;
}
} else if (
!noConnectionRequired &&
(!formData.database ||
(typeof formData.database === "string" && !formData.database.trim()))
) {
setStatus("error");
setMessage(t("newConnection.dbNameRequired"));
setTestResult("error");
return;
}
setStatus("saving");
setMessage("");
setTestResult(null);
try {
const params: Partial<ConnectionParams> = {
driver,
...formData,
port: formData.port != null ? Number(formData.port) : undefined,
database: isMultiDb
? selectedDatabasesState.length === 1
? selectedDatabasesState[0]
: selectedDatabasesState
: formData.database,
};
if (initialConnection) {
if (!params.password?.trim()) delete params.password;
if (!params.ssh_password?.trim()) delete params.ssh_password;
await invoke("update_connection", {
id: initialConnection.id,
name,
params,
});
} else {
await invoke("save_connection", { name, params });
}
if (onSave) onSave();
onClose();
} catch (err) {
setStatus("error");
setMessage(typeof err === "string" ? err : t("newConnection.failSave"));
setTestResult("error");
}
};
// ── connection string import ──
const handleConnectionStringChange = (value: string) => {
setConnectionString(value);
setConnectionStringError(null);
if (!value.trim()) {
return;
}
const parserDrivers = drivers.map((item) => ({
id: item.id,
capabilities: item.capabilities,
}));
if (looksLikeConnectionString(value, parserDrivers)) {
const result = parseConnectionString(value, parserDrivers);
if (result.success) {
const parsed = toConnectionParams(result.params);
const newDriver = parsed.driver || driver;
const parsedDriver = drivers.find((item) => item.id === newDriver);
const parsedIsMultiDb = isMultiDatabaseCapable(
parsedDriver?.capabilities,
);
const parsedFields: Partial<ConnectionParams> = {
driver: newDriver,
host: parsed.host || "localhost",
port: parsed.port,
username: parsed.username || "",
password: parsed.password || "",
database: parsed.database || "",
};
if (parsedIsMultiDb && parsed.database) {
setSelectedDatabasesState([parsed.database]);
setActiveTab("databases");
}
if (newDriver !== driver) {
setDriver(newDriver);
}
setFormData((prev) => ({
...prev,
...parsedFields,
}));
void loadDatabases(parsedFields);
} else {
setConnectionStringError(result.error);
}
}
};
const handleClearConnectionString = () => {
setConnectionString("");
setConnectionStringError(null);
};
// ── rendered general tab content ──
const generalTabContent = (
<div className="space-y-4">
{/* API-based: no connection form needed — plugin may provide custom content via slot */}
{noConnectionRequired ? (
hasConnectionContentSlot ? (
<SlotAnchor
name="connection-modal.connection_content"
context={dbFieldSlotContext}
/>
) : (
<div className="flex flex-col items-center justify-center py-10 gap-3 text-muted">
<Info size={22} className="opacity-40" />
<p className="text-xs text-center">
{t("newConnection.noGeneralSettings", {
defaultValue: "No general settings available for this driver.",
})}
</p>
</div>
)
) : activeDriver?.capabilities?.file_based === true ||
activeDriver?.capabilities?.folder_based === true ? (
<div className="flex flex-col gap-1">
<label className="text-[10px] uppercase font-semibold tracking-wider text-muted">
{activeDriver.capabilities.folder_based
? t("newConnection.folderPath")
: t("newConnection.filePath")}
</label>
<div className="flex gap-2">
<input
type="text"
value={
typeof formData.database === "string" ? formData.database : ""
}
onChange={(e) => updateField("database", e.target.value)}
autoCorrect="off"
autoCapitalize="off"
autoComplete="off"
spellCheck={false}
className="flex-1 px-3 py-2 bg-base border border-strong rounded-md text-sm text-primary placeholder:text-muted placeholder:italic focus:border-blue-500 focus:outline-none transition-colors"
placeholder={
activeDriver.capabilities.folder_based
? t("newConnection.folderPathPlaceholder")
: t("newConnection.filePathPlaceholder")
}
/>
<button
type="button"
onClick={async () => {
const selected = await open({
multiple: false,
directory: activeDriver.capabilities.folder_based,
});
if (selected) updateField("database", selected);
}}
className="px-3 py-2 bg-base hover:bg-surface-secondary border border-strong rounded-md text-muted hover:text-primary transition-colors"
title={
activeDriver.capabilities.folder_based
? t("newConnection.browseFolder")
: t("newConnection.browseFile")
}
>
<FolderOpen size={15} />
</button>
</div>
</div>
) : (
<>
{connectionStringEnabled && (
<div className="flex flex-col gap-1">
<div className="flex items-center justify-between">
<label className="text-[10px] uppercase font-semibold tracking-wider text-muted">
{t("newConnection.connectionString", {
defaultValue: "Connection String",
})}
</label>
{connectionString && (
<button
type="button"
onClick={handleClearConnectionString}
className="text-xs text-muted hover:text-primary transition-colors"
>
{t("common.clear", { defaultValue: "Clear" })}
</button>
)}
</div>
<div className="flex gap-2">
<input
type="text"
value={connectionString}
onChange={(e) => handleConnectionStringChange(e.target.value)}
autoCorrect="off"
autoCapitalize="off"
autoComplete="off"
spellCheck={false}
className={clsx(
"flex-1 px-3 py-2 bg-base border rounded-md text-sm text-primary placeholder:text-muted placeholder:italic focus:border-blue-500 focus:outline-none transition-colors",
connectionStringError ? "border-red-500" : "border-strong",
)}
placeholder={connectionStringPlaceholder}
/>
{connectionString && !connectionStringError && (
<div className="px-3 py-2 bg-green-900/20 border border-green-500/30 rounded-md text-green-400 flex items-center">
<Check size={15} />
</div>
)}
</div>
{connectionStringError && (
<div className="flex items-center gap-1 text-xs text-red-400 mt-0.5">
<AlertCircle size={11} /> {connectionStringError}
</div>
)}
</div>
)}
{/* Host + Port */}
<div
className={clsx(
"grid gap-3",
driver === "postgres" ? "grid-cols-4" : "grid-cols-3",
)}
>
<FieldInput
className="col-span-2"
label={t("newConnection.host")}
value={formData.host}
onChange={(v) => updateField("host", v)}
placeholder="localhost"
/>
<FieldInput
label={t("newConnection.port")}
value={formData.port}
onChange={(v) => updateField("port", v)}
type="number"
placeholder={driver === "mysql" ? "3306" : "5432"}
/>
</div>
{/* User + Password */}
<div className="grid grid-cols-2 gap-3">
<FieldInput
label={t("newConnection.username")}
value={formData.username}
onChange={(v) => updateField("username", v)}
placeholder={t("newConnection.usernamePlaceholder")}
/>
<FieldInput
label={t("newConnection.password")}
value={formData.password}
onChange={(v) => {
setPasswordDirty(true);
updateField("password", v);
}}
type="password"
placeholder={
initialConnection && !passwordDirty && !formData.password
? "••••••••"
: t("newConnection.passwordPlaceholder")
}
/>
</div>
{/* Database (single) — only shown for non-multi-db drivers */}
{!isMultiDb && (
<div className="flex flex-col gap-1">
<div className="flex items-center justify-between">
<label className="text-[10px] uppercase font-semibold tracking-wider text-muted">
{t("newConnection.dbName")}
</label>
<button
type="button"
onClick={() => {
void loadDatabases();
}}
disabled={
loadingDatabases || !formData.host || !formData.username
}
className="flex items-center gap-1 text-xs text-blue-400 hover:text-blue-300 disabled:text-muted disabled:cursor-not-allowed transition-colors"
>
{loadingDatabases ? (
<Loader2 size={11} className="animate-spin" />
) : (
<Database size={11} />
)}
{loadingDatabases
? t("newConnection.loadingDatabases")
: t("newConnection.loadDatabases")}
</button>
</div>
{availableDatabases.length > 0 ? (
<Select
value={
typeof formData.database === "string"
? formData.database || null
: null
}
options={availableDatabases}
onChange={(val) => updateField("database", val)}
placeholder={t("newConnection.selectDatabase")}
searchPlaceholder={t("common.search")}
noResultsLabel={t("newConnection.noDatabasesFound")}
/>
) : (
<input
type="text"
value={
typeof formData.database === "string"
? formData.database
: ""
}
onChange={(e) => updateField("database", e.target.value)}
autoCorrect="off"
autoCapitalize="off"
autoComplete="off"
spellCheck={false}
className="w-full px-3 py-2 bg-base border border-strong rounded-md text-sm text-primary placeholder:text-muted placeholder:italic focus:border-blue-500 focus:outline-none transition-colors"
placeholder={t("newConnection.dbNamePlaceholder")}
/>
)}
{databaseLoadError && (
<div className="flex items-center gap-1 text-xs text-red-400 mt-0.5">
<AlertCircle size={11} /> {databaseLoadError}
</div>
)}
</div>
)}
{/* Keychain */}
<label className="flex items-center gap-2 cursor-pointer select-none w-fit">
<input
type="checkbox"
checked={!!formData.save_in_keychain}
onChange={(e) => {
updateField("save_in_keychain", e.target.checked);
}}
className="accent-blue-500 w-3.5 h-3.5 rounded"
/>
<span className="text-xs text-secondary">
{t("newConnection.saveKeychain")}
</span>
</label>
</>
)}
</div>
);
// ── rendered Databases tab content (multi-db selection) ──
const databasesTabContent = (
<div className="space-y-3">
<div className="flex items-center justify-between">
<p className="text-xs text-muted">
{t("newConnection.selectDatabasesHint", {
defaultValue: "Select the databases to include in this connection.",
})}
</p>
<button
type="button"
onClick={() => {
void loadDatabases();
}}
disabled={loadingDatabases || !formData.host || !formData.username}
className="flex items-center gap-1 text-xs text-blue-400 hover:text-blue-300 disabled:text-muted disabled:cursor-not-allowed transition-colors shrink-0"
>
{loadingDatabases ? (
<Loader2 size={11} className="animate-spin" />
) : (
<Database size={11} />
)}
{loadingDatabases
? t("newConnection.loadingDatabases")
: t("newConnection.loadDatabases")}
</button>
</div>
{databaseLoadError && (
<div className="flex items-center gap-1 text-xs text-red-400">
<AlertCircle size={11} /> {databaseLoadError}
</div>
)}
{availableDatabases.length > 0 ? (
<div className="border border-strong rounded-md overflow-hidden">
<div className="flex items-center gap-2 px-2.5 py-1.5 border-b border-default bg-base">
<input
type="text"
value={dbSearchQuery}
onChange={(e) => setDbSearchQuery(e.target.value)}
placeholder={t("common.search")}
autoCorrect="off"
autoCapitalize="off"
autoComplete="off"
spellCheck={false}
className="flex-1 bg-transparent text-xs text-primary placeholder:text-muted outline-none"
/>
<button
type="button"
onClick={() => {
const filteredDbs = availableDatabases.filter((db) =>
db.toLowerCase().includes(dbSearchQuery.toLowerCase()),
);
const allSel = filteredDbs.every((db) =>
selectedDatabasesState.includes(db),
);
if (allSel) {
setSelectedDatabasesState((prev) =>
prev.filter((db) => !filteredDbs.includes(db)),
);
} else {
setSelectedDatabasesState((prev) =>
Array.from(new Set([...prev, ...filteredDbs])),
);
if (databasesTabError) setDatabasesTabError(false);
}
}}
className="text-xs text-blue-400 hover:text-blue-300 whitespace-nowrap shrink-0"
>
{availableDatabases
.filter((db) =>
db.toLowerCase().includes(dbSearchQuery.toLowerCase()),
)
.every((db) => selectedDatabasesState.includes(db))
? t("sidebar.deselectAll")
: t("sidebar.selectAll")}
</button>
</div>
<div className="max-h-[300px] overflow-y-auto">
{availableDatabases
.filter((db) =>
db.toLowerCase().includes(dbSearchQuery.toLowerCase()),
)
.map((db) => {
const sel = selectedDatabasesState.includes(db);
return (
<div
key={db}
onClick={() => {
setSelectedDatabasesState((prev) =>
sel ? prev.filter((d) => d !== db) : [...prev, db],
);
if (databasesTabError && !sel)
setDatabasesTabError(false);
}}
className={clsx(
"flex items-center gap-2 px-2.5 py-1.5 cursor-pointer text-sm transition-colors hover:bg-surface-secondary select-none",
sel ? "text-primary" : "text-muted",
)}
>
<span
className={clsx(
"shrink-0",
sel ? "text-blue-500" : "text-muted",
)}
>
{sel ? <CheckSquare size={13} /> : <Square size={13} />}
</span>
<span className="truncate">{db}</span>
</div>
);
})}
</div>
<div className="px-2.5 py-1.5 border-t border-default bg-base text-xs text-muted">
{selectedDatabasesState.length > 0
? t("newConnection.selectedDatabases", {
count: selectedDatabasesState.length,
})
: t("newConnection.noDatabasesSelected")}
</div>
</div>
) : (
<div className="flex flex-col items-center justify-center py-8 gap-2 text-muted border border-dashed border-strong rounded-md">
<Database size={20} className="opacity-40" />
<p className="text-xs">
{t("newConnection.loadDatabasesHint", {
defaultValue:
"Click Load Databases to fetch available databases.",
})}
</p>
</div>
)}
</div>
);
// ── rendered SSL tab content ──
const sslTabContent = (
<div className="space-y-4">
<p className="text-xs text-muted">
{t("newConnection.sslDescription", {
defaultValue: "Configure SSL/TLS certificates for secure MySQL connections (optional).",
})}
</p>
{/* SSL Mode */}
<div className="flex flex-col gap-1">
<label className="text-[10px] uppercase font-semibold tracking-wider text-muted">
{t("newConnection.sslMode", { defaultValue: "SSL Mode" })}
</label>
<Select
value={formData.ssl_mode || (driver === "postgres" ? "prefer" : "required")}
options={
driver === "postgres"
? ["disable", "allow", "prefer", "require"]
: ["disabled", "preferred", "required", "verify_ca", "verify_identity"]
}
labels={
driver === "postgres"
? {
disable: t("newConnection.sslModes.disable", { defaultValue: "Disable" }),
allow: t("newConnection.sslModes.allow", { defaultValue: "Allow" }),
prefer: t("newConnection.sslModes.prefer", { defaultValue: "Prefer" }),
require: t("newConnection.sslModes.require", { defaultValue: "Require" }),
}
: {
disabled: t("newConnection.sslModes.disabled", { defaultValue: "Disabled" }),
preferred: t("newConnection.sslModes.preferred", { defaultValue: "Preferred" }),
required: t("newConnection.sslModes.required", { defaultValue: "Required" }),
verify_ca: t("newConnection.sslModes.verify_ca", { defaultValue: "Verify CA" }),
verify_identity: t("newConnection.sslModes.verify_identity", { defaultValue: "Verify Identity" }),
}
}
onChange={(v) => updateField("ssl_mode", v)}
searchable={false}
/>
</div>
{/* SSL Certificate Files */}
{formData.ssl_mode && formData.ssl_mode !== "disable" && formData.ssl_mode !== "disabled" && (
<div className="space-y-3 pt-2">
<p className="text-xs text-muted">
{t("newConnection.sslCertificatesOptional", {
defaultValue: "Certificate paths are optional. Leave empty to use system defaults.",
})}
</p>
{/* CA Certificate */}
<div className="flex flex-col gap-1">
<label className="text-[10px] uppercase font-semibold tracking-wider text-muted">
{t("newConnection.sslCa", { defaultValue: "CA Certificate" })}
</label>
<div className="flex gap-2">
<input
type="text"
value={formData.ssl_ca || ""}
onChange={(e) => updateField("ssl_ca", e.target.value)}
placeholder="/path/to/ca-cert.pem"