-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdashboard.js
More file actions
765 lines (711 loc) · 29.8 KB
/
dashboard.js
File metadata and controls
765 lines (711 loc) · 29.8 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
$(function () {
const API_NINJAS_KEY = 'vqtdn5h8Bc9o2ujlg6GboQ==5mItNDgsfYQBz9lc';
let editorInstance, currentFilePath = '';
let lastWorldTime = null, lastWorldTimeTs = null;
let contextTargetPath = null, contextTargetType = null;
const createProjectModal = new bootstrap.Modal(document.getElementById('createProjectModal'));
const cloneModal = new bootstrap.Modal(document.getElementById('cloneProjectModal'));
const linksModal = new bootstrap.Modal(document.getElementById('manageLinksModal'));
// Dark Mode Handling
function applySwalDarkmode() {
const isDarkMode = $('body').hasClass('darkmode');
Swal.update({
background: isDarkMode ? '#23262b' : '',
color: isDarkMode ? '#e0e0e0' : '',
customClass: { popup: isDarkMode ? 'swal2-darkmode' : '' }
});
$('table').toggleClass('table-dark', isDarkMode);
$('.swal2-select').css({
'background-color': isDarkMode ? '#2c2f36' : '',
'color': isDarkMode ? '#e0e0e0' : '',
'border': isDarkMode ? '1px solid #444' : ''
});
$('#explorerContextMenu').css({
'background-color': isDarkMode ? '#2c2f36' : '',
'color': isDarkMode ? '#e0e0e0' : '',
'border': isDarkMode ? '1px solid #444' : ''
});
$('#contextMenu').css({
'background-color': isDarkMode ? '#2c2f36' : '',
'color': isDarkMode ? '#e0e0e0' : '',
'border': isDarkMode ? '1px solid #444' : ''
});
$('.dropdown-item').css({ 'color': isDarkMode ? '#e0e0e0' : '' });
if (typeof monaco !== 'undefined' && editorInstance) {
monaco.editor.setTheme(isDarkMode ? 'vs-dark' : 'vs');
}
}
function setDarkMode(on) {
$('body').toggleClass('darkmode', on);
$('#darkmodeIcon').html(on ? '☀' : '☾');
localStorage.setItem('darkmode', on ? '1' : '0');
applySwalDarkmode();
}
// Loading Indicator
function showLoading(message = 'Loading...') {
Swal.fire({
title: message,
allowOutsideClick: false,
didOpen: () => Swal.showLoading()
});
applySwalDarkmode();
}
function hideLoading() {
Swal.close();
}
// Project Creation
$('#createProjectBtn').on('click', () => {
$('#projectName').val('');
$('#createProjectError').text('');
createProjectModal.show();
});
$('#createProjectForm').on('submit', function (e) {
e.preventDefault();
const name = $('#projectName').val().trim();
if (!/^[A-Za-z0-9_\- ]{1,32}$/.test(name)) {
Swal.fire({
icon: 'error',
title: 'Invalid project name',
text: 'Allowed: letters, numbers, spaces, -, _ (max 32 chars)'
});
applySwalDarkmode();
return;
}
Swal.fire({
title: 'Create project?',
text: `Create project "${name}"?`,
icon: 'question',
showCancelButton: true,
confirmButtonText: 'Create'
}).then(result => {
if (result.isConfirmed) {
showLoading('Creating project...');
$.post('api.php', { projectName: name }, (resp) => {
hideLoading();
if (resp.success) {
Swal.fire('Created!', '', 'success').then(() => location.reload());
} else {
Swal.fire('Error', resp.error || 'Failed to create project.', 'error');
}
applySwalDarkmode();
}, 'json').fail(() => {
hideLoading();
Swal.fire('Error', 'Failed to create project.', 'error');
applySwalDarkmode();
});
}
});
applySwalDarkmode();
});
// Project Search
$('#searchInput').on('input', function () {
const query = $(this).val().toLowerCase();
$('#projectGrid a.project-link').each(function () {
$(this).closest('.col').toggle($(this).data('name').toLowerCase().includes(query));
});
});
// Dark Mode Toggle
$('#darkmodeToggle').on('click', () => setDarkMode(!$('body').hasClass('darkmode')));
if (localStorage.getItem('darkmode') === '1' ||
(localStorage.getItem('darkmode') === null && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
setDarkMode(true);
} else {
applySwalDarkmode();
}
$('.rename-project-btn').on('click', function () {
const folder = $(this).data('folder');
Swal.fire({
title: 'Edit Project Name',
input: 'text',
inputValue: folder,
inputAttributes: { maxlength: 32, autocapitalize: 'off', autocorrect: 'off' },
showCancelButton: true,
confirmButtonText: 'Rename',
preConfirm: newName => {
if (!/^[A-Za-z0-9_\- ]{1,32}$/.test(newName)) {
Swal.showValidationMessage('Allowed: letters, numbers, spaces, -, _ (max 32 chars)');
return false;
}
if (newName === folder) {
Swal.showValidationMessage('Name is unchanged.');
return false;
}
return newName;
}
}).then(result => {
if (result.isConfirmed) {
showLoading('Renaming project...');
$.post('api.php', { renameProject: 1, oldName: folder, newName: result.value }, resp => {
hideLoading();
if (resp.success) {
Swal.fire('Renamed!', '', 'success').then(() => location.reload());
} else {
Swal.fire('Error', resp.error || 'Failed to rename folder.', 'error');
}
applySwalDarkmode();
}, 'json').fail(() => {
hideLoading();
Swal.fire('Error', 'Failed to rename folder.', 'error');
applySwalDarkmode();
});
}
});
applySwalDarkmode();
});
// Project Editing
$('.edit-project-btn').on('click', function () {
const folder = $(this).data('folder');
editorInstance.setValue('// select a file ...');
showLoading('Loading project...');
$.getJSON('api.php', { listFiles: 1, folder: folder }, resp => {
hideLoading();
if (!resp.success) {
Swal.fire('Error', resp.error || 'Failed to load files.', 'error');
return;
}
renderExplorer(folder, $('#editorExplorer'));
$('#editorModal').show();
});
});
// Project Deletion
$('.delete-project-btn').on('click', function () {
const name = $(this).data('folder');
Swal.fire({
title: 'Delete Project?',
text: `Are you sure you want to delete project "${name}"? This cannot be undone.`,
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Delete',
confirmButtonColor: '#d33'
}).then(result => {
if (result.isConfirmed) {
showLoading('Deleting project...');
$.post('api.php', { deleteProject: 1, name: name }, resp => {
hideLoading();
if (resp.success) {
Swal.fire('Deleted!', '', 'success').then(() => location.reload());
} else {
Swal.fire('Error', resp.error || 'Failed to delete folder.', 'error');
}
applySwalDarkmode();
}, 'json').fail(() => {
hideLoading();
Swal.fire('Error', 'Failed to delete folder.', 'error');
applySwalDarkmode();
});
}
});
applySwalDarkmode();
});
// Clock Functions
function fetchWorldClock() {
$.ajax({
url: 'https://api.api-ninjas.com/v1/worldtime?timezone=asia/jakarta',
method: 'GET',
dataType: 'json',
timeout: 3000,
headers: { 'X-Api-Key': API_NINJAS_KEY },
success: resp => {
if (resp?.datetime) {
lastWorldTime = new Date(resp.datetime.replace(' ', 'T'));
lastWorldTimeTs = Date.now();
updateClockDisplay();
} else {
updateClockLocal();
}
},
error: () => updateClockLocal()
});
}
function updateClockDisplay() {
if (lastWorldTime && lastWorldTimeTs) {
const now = new Date(lastWorldTime.getTime() + (Date.now() - lastWorldTimeTs));
const pad = n => n.toString().padStart(2, '0');
$('#realtimeClock').text(`${pad(now.getDate())} ${pad(now.getMonth() + 1)} ${now.getFullYear()} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())} (Jakarta)`);
} else {
updateClockLocal();
}
}
function updateClockLocal() {
const now = new Date();
const pad = n => n.toString().padStart(2, '0');
$('#realtimeClock').text(`${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())} (local)`);
}
fetchWorldClock();
setInterval(() => lastWorldTime ? updateClockDisplay() : updateClockLocal(), 1000);
setInterval(fetchWorldClock, 60000);
// GitHub Cloning
$('#cloneProjectBtn').on('click', () => {
$('#githubUrl').val('');
$('#cloneFolder').val('');
$('#cloneProjectError').text('');
cloneModal.show();
});
$('#cloneProjectForm').on('submit', function (e) {
e.preventDefault();
const url = $('#githubUrl').val().trim();
const folder = $('#cloneFolder').val().trim();
if (!/^(https:\/\/([^@]+@)?github\.com\/[^/]+\/[^/]+(\.git)?|git@github\.com:[^/]+\/[^/]+(\.git)?)$/i.test(url)) {
$('#cloneProjectError').text('Invalid GitHub URL.');
return;
}
if (!/^[A-Za-z0-9_\- ]{1,32}$/.test(folder)) {
$('#cloneProjectError').text('Invalid folder name.');
return;
}
$('#cloneProjectError').text('');
$('#cloneLog').text('');
Swal.fire({
title: 'Clone project?',
text: `Clone "${url}" into folder "${folder}"?`,
icon: 'question',
showCancelButton: true,
confirmButtonText: 'Clone'
}).then(result => {
if (result.isConfirmed) {
showLoading('Cloning project...');
$.post('api.php', { cloneGithub: 1, githubUrl: url, cloneFolder: folder }, resp => {
if (resp.success && resp.jobId) {
hideLoading();
Swal.fire({
icon: 'success',
title: 'Clone Complete!',
text: 'The GitHub project was cloned successfully.',
confirmButtonText: 'OK'
}).then(() => location.reload());
} else {
$('#cloneProjectError').text(resp.error || 'Clone failed.');
Swal.fire('Error', resp.error || 'Clone failed.', 'error');
}
applySwalDarkmode();
}, 'json');
}
});
applySwalDarkmode();
});
function pullProject(folder) {
Swal.fire({
title: 'Pull changes from GitHub?',
text: `Pull changes from GitHub for folder "${folder}"?`,
icon: 'question',
showCancelButton: true,
confirmButtonText: 'Pull'
}).then(result => {
if (result.isConfirmed) {
$.post('api.php', { pullGithub: true, folder: folder }, function(data) {
if (data.success) {
Swal.fire('Git Pull Started', 'Pulling changes for ' + folder, 'info');
applySwalDarkmode();
checkPullProgress(data.jobId, folder);
} else {
Swal.fire('Error', data.error, 'error');
applySwalDarkmode();
}
});
}
});
applySwalDarkmode();
}
function checkPullProgress(jobId, folder) {
$.post('api.php', { pullProgress: true, jobId: jobId }, function(data) {
if (data.done) {
if (data.success) {
Swal.fire('Git Pull Complete', 'Repository updated successfully.', 'success');
applySwalDarkmode();
} else {
Swal.fire('Git Pull Failed', data.error, 'error');
applySwalDarkmode();
}
} else {
// Update progress (e.g., show percentage in UI)
setTimeout(function() { checkPullProgress(jobId, folder); }, 1000);
}
});
}
// Link Management
$('#manageLinksBtn').on('click', () => {
$('#linkError').text('');
linksModal.show();
});
function loadLinks() {
$.get('link.txt', data => {
const lines = data.trim().split('\n').filter(line => line.trim() !== '');
const tbody = $('#linksTableBody').empty();
if (lines.length === 0) {
tbody.append('<tr><td colspan="3" class="text-center text-muted">No links available</td></tr>');
$('#link-marquee').text('Select a project to open');
} else {
const html = lines.map(line => {
const [url, label = url] = line.split('|').map(s => s.trim());
return `<a href="${url}" target="_blank">${label}</a>`;
}).join('');
$('#link-marquee').html(html);
lines.forEach(line => {
const [url, label = url] = line.split('|').map(s => s.trim());
tbody.append(`
<tr>
<td><input type="text" class="form-control form-control-sm link-url" value="${url}"></td>
<td><input type="text" class="form-control form-control-sm link-label" value="${label}"></td>
<td><button class="btn btn-danger btn-sm remove-link"><i class="fa fa-trash"></i></button></td>
</tr>
`);
});
}
}).fail(() => $('#link-marquee').text('Select a project to open'));
}
loadLinks();
$('#addLinkBtn').on('click', () => {
$('#linksTableBody').append(`
<tr>
<td><input type="text" class="form-control form-control-sm link-url" placeholder="https://example.com"></td>
<td><input type="text" class="form-control form-control-sm link-label" placeholder="My Project"></td>
<td><button class="btn btn-danger btn-sm remove-link"><i class="fa fa-trash"></i></button></td>
</tr>
`);
});
$(document).on('click', '.remove-link', function () {
$(this).closest('tr').remove();
});
$('#saveLinksBtn').on('click', () => {
const rows = [];
let error = false;
$('#linksTableBody tr').each(function () {
const url = $(this).find('.link-url').val().trim();
const label = $(this).find('.link-label').val().trim();
if (url) {
if (!/^https?:\/\/.+/i.test(url)) {
$('#linkError').text(`Invalid URL: ${url}`);
error = true;
return false;
}
rows.push(`${url}|${label || url}`);
}
});
if (error) return;
$.post('api.php', { saveLinks: 1, links: rows }, resp => {
if (resp.success) {
Swal.fire('Saved!', 'Links updated successfully', 'success').then(() => {
linksModal.hide();
location.reload();
});
applySwalDarkmode();
} else {
$('#linkError').text(resp.error || 'Failed to save links.');
}
applySwalDarkmode();
}, 'json').fail(() => $('#linkError').text('Failed to save links.'));
});
// Editor Functions
require.config({ paths: { vs: 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.45.0/min/vs' } });
require(['vs/editor/editor.main'], () => {
editorInstance = monaco.editor.create(document.getElementById('monacoEditor'), {
value: '// select a file...',
language: 'php',
theme: $('body').hasClass('darkmode') ? 'vs-dark' : 'vs',
automaticLayout: true
});
});
window.openFileInEditor = (path, content, language = 'php') => {
currentFilePath = path;
$('#editorFilename').text(path);
editorInstance.setValue(content);
monaco.editor.setModelLanguage(editorInstance.getModel(), language);
$('#editorModal').show();
};
window.closeEditor = () => $('#editorModal').hide();
window.saveFile = () => {
const content = editorInstance.getValue();
$.post('api.php', {
saveFile: 1,
folder: currentFilePath.split('/').slice(0, -1).join('/'),
file: currentFilePath.split('/').pop(),
content
}, resp => {
Swal.fire({
toast: true,
position: 'top-end',
icon: resp.success ? 'success' : 'error',
title: resp.success ? 'File saved!' : (resp.error || 'Save failed'),
showConfirmButton: false,
timer: resp.success ? 2000 : 3000
});
applySwalDarkmode();
}, 'json');
};
function renderExplorer(folder, container) {
$.getJSON('api.php', { listFiles: 1, folder }, resp => {
if (!resp.success) {
Swal.fire('Error', resp.error || 'Failed to load files.', 'error');
applySwalDarkmode();
return;
}
container.html(`
<div class="mb-2 d-flex justify-content-center gap-1">
<button class="btn btn-sm btn-primary create-file-btn" data-folder="${folder}" style="display:flex; align-items:center; gap:4px; font-size:0.85rem;">
<i class="fa fa-file"></i> File
</button>
<button class="btn btn-sm btn-success create-folder-btn" data-folder="${folder}" style="display:flex; align-items:center; gap:4px; font-size:0.85rem;">
<i class="fa fa-folder"></i> Folder
</button>
</div>
<div class="file-grid" style="display:flex; flex-direction:column; gap:4px; padding:2px;">
${resp.entries.filter(e => !['.', '..'].includes(e.name)).map(entry => `
<button class="file-item btn btn-sm ${entry.type === 'dir' ? 'btn-secondary' : 'btn-outline-primary'} text-start" data-path="${entry.path}" data-type="${entry.type}">
<i class="fa fa-${entry.type === 'dir' ? 'folder' : 'file-code'} me-1"></i> ${entry.name}
</button>
`).join('')}
</div>
`);
});
}
function guessLanguage(filename) {
const ext = filename.split('.').pop().toLowerCase();
return { js: 'javascript', php: 'php', html: 'html', css: 'css', json: 'json' }[ext] || 'plaintext';
}
$(document).on('click', '.file-item[data-type="file"]', function () {
const path = $(this).data('path');
$.getJSON('api.php', { getFile: 1, folder: path.split('/').slice(0, -1).join('/'), file: path.split('/').pop() }, resp => {
if (resp.success) {
openFileInEditor(path, resp.content, guessLanguage(path));
} else {
Swal.fire('Error', resp.error || 'Cannot open file', 'error');
applySwalDarkmode();
}
});
});
$(document).on('click', '.file-item[data-type="dir"]', function (e) {
e.stopPropagation();
const $btn = $(this);
const path = $btn.data('path');
if ($btn.hasClass('expanded')) {
$btn.next('ul').toggle();
return;
}
$.getJSON('api.php', { listFiles: 1, folder: path }, resp => {
if (!resp.success) {
Swal.fire('Error', resp.error || 'Failed to load folder.', 'error');
applySwalDarkmode();
return;
}
const subHtml = `<ul class="list-unstyled ms-3">${resp.entries.filter(e => !['.', '..'].includes(e.name)).map(entry => `
<li>
<button class="file-item btn btn-sm ${entry.type === 'dir' ? 'btn-secondary' : 'btn-outline-primary'} text-start" data-path="${entry.path}" data-type="${entry.type}">
<i class="fa fa-${entry.type === 'dir' ? 'folder' : 'file-code'} me-1"></i> ${entry.name}
</button>
</li>`).join('')}</ul>`;
$btn.after(subHtml);
$btn.addClass('expanded');
});
});
function refreshExplorer() {
const folder = $('.create-file-btn').data('folder') || $('.create-folder-btn').data('folder');
if (folder) renderExplorer(folder, $('#editorExplorer'));
}
$(document).on('click', '.create-file-btn', function () {
const folder = $(this).data('folder');
Swal.fire({
title: 'New File',
input: 'text',
inputPlaceholder: 'example.txt',
showCancelButton: true,
confirmButtonText: 'Create',
preConfirm: val => val.trim()
}).then(res => {
if (!res.isConfirmed) return;
$.post('api.php', { createFile: 1, folder, name: res.value }, resp => {
Swal.fire({
icon: resp.success ? 'success' : 'error',
title: resp.success ? 'Success!' : 'Error',
text: resp.success ? 'File created' : (resp.error || 'Failed to create file.')
});
if (resp.success) refreshExplorer();
applySwalDarkmode();
}, 'json');
});
applySwalDarkmode();
});
$(document).on('click', '.create-folder-btn', function () {
const folder = $(this).data('folder');
Swal.fire({
title: 'New Folder',
input: 'text',
inputPlaceholder: 'new-folder',
showCancelButton: true,
confirmButtonText: 'Create',
preConfirm: val => val.trim(),
didOpen: el => $(el).find('input').trigger('focus')
}).then(res => {
if (!res.isConfirmed) return;
$.post('api.php', { createFolder: 1, folder, name: res.value }, resp => {
Swal.fire({
icon: resp.success ? 'success' : 'error',
title: resp.success ? 'Success!' : 'Error',
text: resp.success ? 'Folder created' : (resp.error || 'Failed to create folder.')
});
if (resp.success) refreshExplorer();
applySwalDarkmode();
}, 'json');
});
applySwalDarkmode();
});
// Context Menu
$(document).on('contextmenu', '.file-item, .folder-item', function (e) {
e.preventDefault();
e.stopPropagation();
contextTargetPath = $(this).data('path');
contextTargetType = $(this).data('type');
$('#explorerContextMenu').css({ top: e.pageY, left: e.pageX }).show();
});
$(document).on('click contextmenu', e => {
if (!$(e.target).closest('#explorerContextMenu').length) {
$('#explorerContextMenu').hide();
}
});
$('#ctx-new-file').on('click', function (e) {
e.preventDefault();
$('#explorerContextMenu').hide();
Swal.fire({
title: 'New File Name',
input: 'text',
inputPlaceholder: 'example.txt',
showCancelButton: true,
confirmButtonText: 'Create',
preConfirm: val => val.trim()
}).then(result => {
if (!result.isConfirmed) return;
$.post('api.php', { createFile: 1, folder: contextTargetPath, name: result.value }, resp => {
Swal.fire({
icon: resp.success ? 'success' : 'error',
title: resp.success ? 'Success!' : 'Error',
text: resp.success ? 'File created' : (resp.error || 'Gagal membuat file')
});
if (resp.success) refreshExplorer();
applySwalDarkmode();
}, 'json');
});
applySwalDarkmode();
});
$('#ctx-new-folder').on('click', function (e) {
e.preventDefault();
$('#explorerContextMenu').hide();
Swal.fire({
title: 'New Folder Name',
input: 'text',
inputPlaceholder: 'new-folder',
showCancelButton: true,
confirmButtonText: 'Create',
preConfirm: val => val.trim()
}).then(result => {
if (!result.isConfirmed) return;
$.post('api.php', { createFolder: 1, folder: contextTargetPath, name: result.value }, resp => {
Swal.fire({
icon: resp.success ? 'success' : 'error',
title: resp.success ? 'Success!' : 'Error',
text: resp.success ? 'Folder created' : (resp.error || 'Gagal membuat folder')
});
if (resp.success) refreshExplorer();
applySwalDarkmode();
}, 'json');
});
applySwalDarkmode();
});
$('#ctx-delete').on('click', function (e) {
e.preventDefault();
$('#explorerContextMenu').hide();
if (!contextTargetPath) return;
Swal.fire({
title: 'Delete?',
text: `Are you sure you want to delete ${contextTargetType} \n${contextTargetPath}?`,
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Delete',
confirmButtonColor: '#d33'
}).then(res => {
if (!res.isConfirmed) return;
showLoading('Deleting...');
$.post('api.php', { deleteEntry: 1, path: contextTargetPath }, resp => {
hideLoading();
Swal.fire({
icon: resp.success ? 'success' : 'error',
title: resp.success ? 'Deleted!' : 'Error',
text: resp.success ? '' : (resp.error || 'Failed to delete.')
});
if (resp.success) refreshExplorer();
applySwalDarkmode();
}, 'json').fail(() => {
hideLoading();
Swal.fire('Error', 'Failed to delete.', 'error');
applySwalDarkmode();
});
});
applySwalDarkmode();
});
$('#ctx-rename').on('click', function (e) {
e.preventDefault();
$('#explorerContextMenu').hide();
if (!contextTargetPath) return;
const currentName = contextTargetPath.split(/[\\/]/).pop();
Swal.fire({
title: `Rename ${contextTargetType}`,
input: 'text',
inputValue: currentName,
showCancelButton: true,
confirmButtonText: 'Rename',
inputValidator: value => !value ? 'Name cannot be empty!' : null
}).then(res => {
if (!res.isConfirmed) return;
showLoading('Renaming...');
$.post('api.php', { renameEntry: 1, path: contextTargetPath, newName: res.value }, resp => {
hideLoading();
Swal.fire({
icon: resp.success ? 'success' : 'error',
title: resp.success ? 'Renamed!' : 'Error',
text: resp.success ? '' : (resp.error || 'Failed to rename.')
});
if (resp.success) refreshExplorer();
applySwalDarkmode();
}, 'json').fail(() => {
hideLoading();
Swal.fire('Error', 'Failed to rename.', 'error');
applySwalDarkmode();
});
});
applySwalDarkmode();
});
// Initialize
renderExplorer('.', $('#explorerRoot'));
window.pullProject = pullProject;
let selectedFolder = null;
$('.project-folder').on('contextmenu', function(e){
e.preventDefault();
selectedFolder = $(this);
const hasGit = !!selectedFolder.find('.pull-project-btn').length;
$('#contextMenu .pull-project').toggle(hasGit);
$('#contextMenu')
.css({ top: e.pageY + 'px', left: e.pageX + 'px' })
.show();
});
$(document).click(function(){
$('#contextMenu').hide();
});
// Edit Project
$('#contextMenu .edit-project').click(function(){
selectedFolder.find('.edit-project-btn').trigger('click');
$('#contextMenu').hide();
});
//rename Project
$('#contextMenu .rename-project').click(function(){
selectedFolder.find('.rename-project-btn').trigger('click');
$('#contextMenu').hide();
});
// Pull Project
$('#contextMenu .pull-project').click(function(){
selectedFolder.find('.pull-project-btn').trigger('click');
$('#contextMenu').hide();
});
// Delete Project
$('#contextMenu .delete-project').click(function(){
selectedFolder.find('.delete-project-btn').trigger('click');
$('#contextMenu').hide();
});
});