forked from open-source-labs/dbSpy
-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathFeatureTab.tsx
586 lines (550 loc) · 23.1 KB
/
FeatureTab.tsx
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
// React & React Router & React Query Modules
import React, { useState, useRef, useEffect } from 'react';
import axios, { AxiosResponse } from 'axios';
import { NavLink } from 'react-router-dom';
import { useNavStore } from '../../store/navStore';
const linkbtn = 'mt-4 inline-block lg:mt-0 text-blue-200 hover:text-white mr-4';
// Functions imported:
import parseSql from '../../parse';
// Stores imported:
import useDataStore from '../../store/dataStore';
import useSchemaStore from '../../store/schemaStore';
import useFlowStore from '../../store/flowStore';
import useSettingsStore from '../../store/settingsStore';
import useCredentialsStore from '../../store/credentialsStore';
//import icon
import {
HomeIcon,
ConnectDatabaseIcon,
UploadSQLFileIcon,
ExportQueryIcon,
AddTableIcon,
DeleteTableIcon,
DeleteIcon,
UndoIcon,
RedoIcon,
SaveDatabaseIcon,
LoadDatabaseIcon,
SignOutIcon,
BuildDatabaseIcon,
} from '../../FeatureTabIcon';
// Components imported:
import QueryModal from '../Modals/QueryModal';
import DbNameInput from '../Modals/DbNameInput';
import LoadDbModal from '../Modals/LoadDbModal';
import DeleteDbModal from '../Modals/DeleteDbModal';
/** "FeatureTab" Component - a tab positioned in the left of the page to access features of the app; */
export default function FeatureTab(props: any) {
// dbSpy 8.0: get the state store in Zustand
const toggleClicked = useNavStore((state) => state.toggleClicked);
//STATE DECLARATION (dbSpy3.0)
const { setEdges, setNodes } = useFlowStore((state) => state);
const { dataStore, setDataStore } = useDataStore((state) => state);
//-- TO DELETE
// const { schemaStore, setSchemaStore, undoHandler, redoHandler } = useSchemaStore(
// (state) => state
// );
const { schemaStore, setSchemaStore, undoHandler, redoHandler, testTab } =
useSchemaStore((state) => state);
const { user, setUser } = useCredentialsStore((state: any) => state);
const { setWelcome, isSchema, setDarkMode, darkMode, setDBName } = useSettingsStore(
(state) => state
);
const [action, setAction] = useState(new Array());
const [queryModalOpened, setQueryModalOpened] = useState(false);
const [saveDbNameModalOpened, setSaveDbNameModalOpened] = useState(false);
const [loadDbModalOpened, setLoadDbModalOpened] = useState(false);
const [deleteDbModalOpened, setDeleteDbModalOpened] = useState(false);
const [nameArr, setNameArr] = useState<string[]>([]);
//END: STATE DECLARATION
//create references for HTML elements
const confirmModal: any = useRef();
/* When the user clicks, open the modal */
const openModal: any = (callback: any) => {
confirmModal.current.style.display = 'block';
confirmModal.current.style.zIndex = '100';
setAction([callback]);
};
/* When the user clicks 'yes' or 'no', close it */
const closeModal: any = (response: boolean) => {
confirmModal.current.style.display = 'none';
if (response) action[0]();
};
// HELPER FUNCTIONS
const connectDb = () => {
//if Flow is rendered, openModal
if (document.querySelector('.flow')) openModal(props.handleSidebar);
else props.handleSidebar();
};
const uploadSQL = () => {
//if Flow is rendered, openModal
if (document.querySelector('.flow')) openModal(getSchemaFromFile);
else getSchemaFromFile();
};
const buildDb = () => {
//if Flow is rendered, open modal
if (document.querySelector('.flow')) openModal(buildDatabase);
else buildDatabase();
};
const clearCanvas = () => {
//if Flow is rendered, open modal
if (document.querySelector('.flow')) openModal(clearCanvasTables);
else clearCanvasTables();
};
const getSchemaFromFile = () => {
// creating an input element for user to upload sql file
const input = document.createElement('input');
input.setAttribute('type', 'file');
input.click();
input.onchange = (e: any): void => {
const file = e.target.files[0];
const reader = new FileReader();
reader.readAsText(file);
reader.onload = (event: any) => {
//Parse the .sql file into a data structure that is same as "fetchedData" and store it into a variable named "parsedData"
const parsedData: any = parseSql(event.target.result);
setSchemaStore(parsedData);
setWelcome(false);
};
};
};
const buildDatabase = () => {
setNodes([]);
setEdges([]);
setWelcome(false);
};
const clearCanvasTables = () => {
setSchemaStore({});
setEdges([]);
setNodes([]);
setWelcome(false);
};
// Export QueryModal
const openQueryModal = () => {
setQueryModalOpened(true);
};
const closeQueryModal = () => {
setQueryModalOpened(false);
};
//SaveDbNameModal - dbSpy 7.0
const openSaveDbNameModal = () => {
if (!user) alert('Must sign in to save!');
else {
setSaveDbNameModalOpened(true);
}
};
const closeSaveDbNameModal = (input?: string) => {
//pull dbName from input field and send it to the database along with the schema. - dbSpy 7.0
if (input) {
saveSchema(input);
}
setSaveDbNameModalOpened(false);
};
// LoadDbModal
// Open loadDbName Modal and send get request to database to get&list all the databases name. - dbSpy 7.0
const openLoadDbModal = async (): Promise<string[]> => {
if (!user) {
alert('Must sign in to load!');
return Promise.reject('User not signed in');
} else {
const response = await axios
.get<string[]>('/api/saveFiles/allSave')
.then((res: AxiosResponse) => {
const nameArr = [];
for (let saveName of res.data.data) {
nameArr.push(saveName.SaveName);
}
setLoadDbModalOpened(true);
setNameArr(nameArr);
})
.catch((err) => {
console.error('Err', err);
return Promise.reject(err);
});
}
return [];
};
const openDeleteDbModal = async (): Promise<string[]> => {
if (!user) {
alert('Please sign in first!');
return Promise.reject('User not signed in');
} else {
const response = await axios
.get<string[]>('/api/saveFiles/allSave')
.then((res: AxiosResponse) => {
const nameArr = [];
for (let saveName of res.data.data) {
nameArr.push(saveName.SaveName);
}
setDeleteDbModalOpened(true);
setNameArr(nameArr);
})
.catch((err) => {
console.error('Err', err);
return Promise.reject(err);
});
}
return [];
};
// Load selected database - dbSpy 7.0
const closeLoadDbModal = (input?: string) => {
if (input) {
loadSchema(input);
setDBName(input);
}
setLoadDbModalOpened(false);
};
// Delete selected database - dbSpy 7.0
const closeDeleteDbModal = (input?: string) => {
if (input) {
deleteDatabase(input);
}
setDeleteDbModalOpened(false);
};
// Function for saving databases. Reworked for multiple saves - dbspy 7.0
const saveSchema = (inputName: string): void => {
//check to see if a table is present in the schemaStore
if (Object.keys(schemaStore).length !== 0) {
//Create request body with the schema to be saved and the inputted name to save it under
const postBody = {
schema: JSON.stringify(schemaStore),
SaveName: inputName,
TableData: JSON.stringify(dataStore),
};
//make a get request to see if the name already exists in the database
axios
.get<string[]>('/api/saveFiles/allSave')
.then((res: AxiosResponse) => {
const nameArr = [];
for (let saveName of res.data.data) {
nameArr.push(saveName.SaveName);
}
// if the name already exists then send to one route and if not then send to the other
// route with combined middleware.
if (nameArr.includes(inputName)) {
axios
.patch('/api/saveFiles/save', postBody)
.catch((err) => console.error('err', err));
} else {
axios
.post('/api/saveFiles/CreateAndSave', postBody)
.catch((err) => console.error('err', err));
}
})
.catch((err) => console.error('Err', err));
} else {
//if no table is present, send alert to the user
alert('No schema displayed.');
}
};
// Reworked for multiple loads - dbSpy 7.0
const loadSchema = async (inputName: string) => {
try {
//send the inputName along with the get request as query in the parameters.
const data = await fetch(`/api/saveFiles/loadSave?SaveName=${inputName}`);
if (data.status === 204) return alert('No database stored!');
const schemaString = await data.json();
setDataStore(JSON.parse(schemaString.tableData));
return setSchemaStore(JSON.parse(schemaString.data));
} catch (err) {
console.log(err);
console.error('err retrieve', err);
window.alert(err);
}
};
// Function for deleting databases - dbspy 7.0
const deleteDatabase = (inputName: string) => {
try {
//send the inputName along with the delete request as query in the parameters.
axios
.delete(`/api/saveFiles/deleteSave/${inputName}`)
.catch((err) => console.error('err', err));
} catch (err) {
console.log(err);
console.error('err retrieve', err);
window.alert(err);
}
};
// Clears session + reset store
const signoutSession = async () => {
await fetch(`/api/logout`);
window.open('/', '_self');
setSchemaStore({});
setUser(null);
};
//Toggle function for DarkMode
const toggleClass = (): void => {
const page = document.getElementById('body');
page!.classList.toggle('dark');
setDarkMode();
};
// END: HELPER FUNCTIONS
return (
<>
{/* PAGE */}
{/* dbSpy 8.0: added toggle button in Navbar to control FeatureTab */}
<div
className={`fixed top-10 left-0 h-full w-64 bg-blue z-10 transition-transform duration-300 ${
toggleClicked ? '-translate-x-full' : 'translate-x-0'
}`}
>
{/* TODO research / fix how to make the FeatureTab sit on pages like a regular block and not on top of other content -------------------------- */}
<aside
className="featureTab z-index-10 light:bg-sky-800 absolute inset-y-0 left-0 top-24 w-64"
aria-label="FeatureTab"
>
<div className="menuBar light:bg-sky-800 ml-3 overflow-auto rounded px-10 py-6 transition-colors duration-500">
<NavLink to="/" className={linkbtn}>
<div className="group inline-flex h-10 w-[160px] items-center justify-start gap-3 rounded-lg py-2 pl-1 pr-[54.52px]">
{/* width="28" height="28" viewBox="0 0 35 28" fill="none" */}
<HomeIcon />
<div className="inline-flex flex-col items-start justify-start pr-[2.48px]">
<span className="text-sm text-slate-900 group-hover:text-yellow-500 group-hover:underline dark:text-[#f8f4eb] dark:group-hover:text-yellow-300">
Home
</span>
</div>
</div>
</NavLink>
<button onClick={toggleClass}>
<div className="ItemLink group inline-flex h-10 w-[160px] items-center justify-start gap-0 rounded-lg py-2 pl-0 pr-0">
<svg
fill="none"
viewBox="0 0 24 24"
stroke-width="1.0"
stroke="currentColor"
className=" ml-2 mr-2 h-[24] stroke-current text-gray-500 group-hover:text-yellow-500 dark:text-[#f8f4eb] dark:group-hover:text-yellow-300"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M1.50488 10.7569C1.50488 16.4855 6.14803 21.1294 11.8756 21.1294C16.2396 21.1294 19.974 18.4335 21.5049 14.616C20.3104 15.0962 19.0033 15.3668 17.6372 15.3668C11.9095 15.3668 7.26642 10.7229 7.26642 4.99427C7.26642 3.63427 7.53299 2.3195 8.00876 1.12939C4.19637 2.66259 1.50488 6.39536 1.50488 10.7569Z"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
<span className="DarkMode text-sm font-normal leading-normal text-gray-900 group-hover:text-yellow-500 group-hover:underline dark:text-[#f8f4eb] dark:group-hover:text-yellow-300 ">
{darkMode === true ? 'Light' : 'Dark'} Mode
</span>
</div>
</button>
<p className=" mt-4 text-slate-900 dark:text-[#f8f4eb]">Action</p>
<hr />
<ul className=" space-y-0">
<li>
<a
onClick={connectDb}
className="dark: group flex cursor-pointer items-center rounded-lg p-2 text-sm font-normal text-gray-900 hover:text-yellow-500 hover:underline dark:text-[#f8f4eb] dark:hover:text-yellow-300"
data-testid="connect-database"
>
<ConnectDatabaseIcon />
<span className="ml-3">Connect Database</span>
</a>
</li>
<li>
<a
onClick={uploadSQL}
className="group flex cursor-pointer items-center rounded-lg p-2 text-sm font-normal text-gray-900 hover:text-yellow-500 hover:underline dark:text-[#f8f4eb] dark:hover:text-yellow-300"
>
<UploadSQLFileIcon />
<span className="ml-3 flex-1 whitespace-nowrap">Upload SQL File</span>
<span className="ml-3 inline-flex items-center justify-center rounded-full bg-gray-200 px-2 text-sm font-medium text-gray-800 dark:bg-gray-700 dark:text-gray-300"></span>
</a>
</li>
<li>
<a
onClick={buildDb}
className=" group flex cursor-pointer items-center rounded-lg p-2 text-sm font-normal text-gray-900 hover:text-yellow-500 hover:underline dark:text-[#f8f4eb] dark:hover:text-yellow-300"
>
<BuildDatabaseIcon />
<span className="ml-3 flex-1 whitespace-nowrap">Build Database</span>
</a>
</li>
{/* TODO: Add SAVE feature */}
<li>
<a
onClick={openQueryModal}
className="group flex cursor-pointer items-center rounded-lg p-2 text-sm font-normal text-gray-900 hover:text-yellow-500 hover:underline dark:text-[#f8f4eb] dark:hover:text-yellow-300 "
>
<ExportQueryIcon />
<span className="ml-3 flex-1 whitespace-nowrap">Export Query</span>
</a>
</li>
<br />
{/* ----------- 💙💙💙💙 Edit Tab (Build Tab) ------------------------- */}
<p className="text-slate-900 dark:text-[#f8f4eb]">Edit</p>
<hr />
{isSchema ? (
<li>
<a
onClick={() => {
props.openAddTableModal();
// if schemaStore is empty, initialize
if (!Object.keys(schemaStore).length) buildDatabase();
}}
id="addTable"
className="group flex cursor-pointer items-center rounded-lg p-2 text-sm font-normal text-gray-900 hover:text-yellow-500 hover:underline dark:text-[#f8f4eb] dark:hover:text-yellow-300 "
>
<AddTableIcon />
<span className="ml-3 flex-1 whitespace-nowrap">Add Table</span>
</a>
</li>
) : null}
{Object.keys(schemaStore).length ? (
<li>
<a
onClick={() => {
props.openDeleteTableModal();
}}
id="deleteTable"
className="group flex cursor-pointer items-center rounded-lg p-2 text-sm font-normal text-gray-900 hover:text-yellow-500 hover:underline dark:text-[#f8f4eb] dark:hover:text-yellow-300"
>
<DeleteTableIcon />
<span className="ml-3 flex-1 whitespace-nowrap">Delete Table</span>
</a>
</li>
) : null}
<li>
<a
onClick={clearCanvas}
className="group flex cursor-pointer items-center rounded-lg p-2 text-sm font-normal text-gray-900 hover:text-yellow-500 hover:underline dark:text-[#f8f4eb] dark:hover:text-yellow-300"
>
<DeleteIcon />
<span className="ml-3 flex-1 whitespace-nowrap">Clear Canvas</span>
</a>
</li>
{/* TODO: Add UNDO & REDO feature */}
<li>
<a
onClick={undoHandler}
className="group flex cursor-pointer items-center rounded-lg p-2 text-sm font-normal text-gray-900 hover:text-yellow-500 hover:underline dark:text-[#f8f4eb] dark:hover:text-yellow-300"
>
<UndoIcon />
<span className="ml-3 flex-1 whitespace-nowrap">Undo</span>
</a>
</li>
<li>
<a
onClick={redoHandler}
className="group flex cursor-pointer items-center rounded-lg p-2 text-sm font-normal text-gray-900 hover:text-yellow-500 hover:underline dark:text-[#f8f4eb] dark:hover:text-yellow-300"
>
<RedoIcon />
<span className="ml-3 flex-1 whitespace-nowrap">Redo</span>
</a>
</li>
<br />
{/* ----------- 💙💙💙💙 Test Tab -------------------------- */}
<p className="text-slate-900 dark:text-[#f8f4eb]">Test</p>
<hr />
{isSchema ? (
<li>
{/* ----- 💙💙 Test New Query Button -------- */}
<NavLink
to="/test-new-query"
className="group flex cursor-pointer items-center rounded-lg p-2 text-sm font-normal text-gray-900 hover:text-yellow-500 hover:underline dark:text-[#f8f4eb] dark:hover:text-yellow-300 "
>
<AddTableIcon />
<span className="ml-3 flex-1 whitespace-nowrap">Test New Query</span>
</NavLink>
</li>
) : null}
<li>
{/* ----- 💙💙 View Saved Queries Button -------- */}
<NavLink
to="/view-saved-queries"
className="group flex cursor-pointer items-center rounded-lg p-2 text-sm font-normal text-gray-900 hover:text-yellow-500 hover:underline dark:text-[#f8f4eb] dark:hover:text-yellow-300"
>
<AddTableIcon />
<span className="ml-3 flex-1 whitespace-nowrap">
View Saved Queries
</span>
</NavLink>
</li>
</ul>
<br />
<div className="historyBlock">
<p className=" text-slate-900 dark:text-[#f8f4eb]">Account</p>
<hr />
<ul className="mb-8 space-y-1">
<li>
<a
onClick={openSaveDbNameModal}
className="group flex cursor-pointer items-center rounded-lg p-2 text-sm font-normal text-gray-900 hover:text-yellow-500 hover:underline dark:text-[#f8f4eb] dark:hover:text-yellow-300"
>
<SaveDatabaseIcon />
<span className="ml-3 flex-1 whitespace-nowrap">Save Database</span>
</a>
</li>
<li>
<a
onClick={openLoadDbModal}
className="group flex cursor-pointer items-center rounded-lg p-2 text-sm font-normal text-gray-900 hover:text-yellow-500 hover:underline dark:text-[#f8f4eb] dark:hover:text-yellow-300"
>
<LoadDatabaseIcon />
<span className="ml-3 flex-1 whitespace-nowrap">Load Database</span>
</a>
</li>
<li>
<a
onClick={openDeleteDbModal}
className="group flex cursor-pointer items-center rounded-lg p-2 text-sm font-normal text-gray-900 hover:text-yellow-500 hover:underline dark:text-[#f8f4eb] dark:hover:text-yellow-300"
>
<DeleteIcon />
<span className="ml-3 flex-1 whitespace-nowrap">Delete Database</span>
</a>
</li>
{user ? (
<li>
<a
onClick={() => signoutSession()}
className="group flex cursor-pointer items-center rounded-lg p-2 text-sm font-normal text-gray-900 hover:text-yellow-500 hover:underline dark:text-[#f8f4eb] dark:hover:text-yellow-300"
>
<SignOutIcon />
<span className="ml-3 flex-1 whitespace-nowrap">Sign Out</span>
</a>
</li>
) : null}
</ul>
</div>
</div>
</aside>
{/* MODALS */}
{/* MODAL FOR CONFIRMATION POPUP */}
<div ref={confirmModal} id="confirmModal" className="confirmModal">
{/* <!-- Confirm Modal content --> */}
<div className="modal-content w-[30%] min-w-[300px] max-w-[550px] content-center rounded-md border-0 bg-[#f8f4eb] shadow-[0px_5px_10px_rgba(0,0,0,0.4)] dark:bg-slate-800 dark:shadow-[0px_5px_10px_#1e293b]">
<p className="mb-4 text-center text-slate-900 dark:text-[#f8f4eb]">
Are you sure you want to proceed? You will lose <strong>ALL</strong> unsaved
changes.
</p>
<div className="mx-auto flex w-[50%] max-w-[200px] justify-between">
<button
onClick={() => closeModal(true)}
className="modalButton text-slate-900 hover:opacity-70 dark:text-[#f8f4eb]"
>
Confirm
</button>
<button
onClick={() => closeModal(false)}
className="modalButton text-slate-900 hover:opacity-70 dark:text-[#f8f4eb]"
>
Cancel
</button>
</div>
</div>
</div>
{/* Query Output Modal */}
{/* Sending props to child components. */}
{queryModalOpened ? <QueryModal closeQueryModal={closeQueryModal} /> : null}
{saveDbNameModalOpened ? (
<DbNameInput closeSaveDbNameModal={closeSaveDbNameModal} />
) : null}
{loadDbModalOpened ? (
<LoadDbModal nameArr={nameArr} closeLoadDbModal={closeLoadDbModal} />
) : null}
{deleteDbModalOpened ? (
<DeleteDbModal nameArr={nameArr} closeDeleteDbModal={closeDeleteDbModal} />
) : null}
</div>
</>
);
}