Repository navigation
Expand file tree
/
Copy pathrenderer.js
More file actions
1951 lines (1671 loc) · 58.7 KB
/
Copy pathrenderer.js
File metadata and controls
1951 lines (1671 loc) · 58.7 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
// State
let currentSkill = null;
let currentSkillDir = null; // Skill directory path for multi-file operations
let currentFile = null; // { path, name, type, editable, metadata }
let editor = null;
let zipPath = null;
let hasUnsavedChanges = false;
let autoSaveDebounceTimer = null;
let fileTree = null; // Current skill's file tree
let contextMenuTarget = null; // Target node for context menu operations
let suppressEditorChange = false;
let currentSkillItem = null; // Active skill element in the list
let currentFileTreeContainer = null; // Active skill's file tree wrapper
let pendingImport = null; // { tempPath, skillName } for import conflict resolution
// Monaco Editor Setup
if (typeof require !== 'undefined' && typeof require.config === 'function') {
require.config({ paths: { vs: 'node_modules/monaco-editor/min/vs' } });
require(['vs/editor/editor.main'], function () {
editor = monaco.editor.create(document.getElementById('editor'), {
value: '',
language: 'markdown',
theme: 'vs-dark',
fontSize: 14,
lineNumbers: 'on',
minimap: { enabled: false },
scrollBeyondLastLine: false,
automaticLayout: true,
wordWrap: 'on',
fontFamily: "'Lora', Georgia, serif",
lineHeight: 24,
suggest: { enabled: false },
quickSuggestions: { enabled: false },
tabCompletion: 'off',
wordBasedSuggestions: 'off',
acceptSuggestionOnEnter: 'off',
acceptSuggestionOnCommitCharacter: false,
parameterHints: { enabled: false }
});
// Custom theme matching Claude colors
monaco.editor.defineTheme('claude-dark', {
base: 'vs-dark',
inherit: true,
rules: [
{ token: 'comment', foreground: 'b0aea5' },
{ token: 'keyword', foreground: 'd97757' },
{ token: 'string', foreground: '788c5d' },
{ token: 'number', foreground: '6a9bcc' }
],
colors: {
'editor.background': '#141413',
'editor.foreground': '#faf9f5',
'editorLineNumber.foreground': '#b0aea5',
'editor.selectionBackground': '#d9775733',
'editor.lineHighlightBackground': '#faf9f50a'
}
});
monaco.editor.setTheme('claude-dark');
// Auto-save on change with debounce
editor.onDidChangeModelContent(() => {
if (suppressEditorChange) {
return;
}
hasUnsavedChanges = true;
// Clear previous debounce timer
if (autoSaveDebounceTimer) {
clearTimeout(autoSaveDebounceTimer);
}
// Set new debounce timer for 2 seconds
autoSaveDebounceTimer = setTimeout(() => {
autoSave();
}, 2000);
});
loadSkills();
});
} else {
// Fallback: Load skills if Monaco fails to load
setTimeout(() => {
try {
loadSkills();
} catch (e) {
console.error('Failed to load skills:', e);
}
}, 100);
}
// DOM Elements
const newSkillBtn = document.getElementById('newSkillBtn');
const importSkillBtn = document.getElementById('importSkillBtn');
const openSkillBtn = document.getElementById('openSkillBtn');
const packageBtn = document.getElementById('packageBtn');
const deleteBtn = document.getElementById('deleteBtn');
const dragZone = document.getElementById('dragZone');
const emptyState = document.getElementById('emptyState');
const newSkillModal = document.getElementById('newSkillModal');
const cancelBtn = document.getElementById('cancelBtn');
const createBtn = document.getElementById('createBtn');
const skillNameInput = document.getElementById('skillNameInput');
const skillDescInput = document.getElementById('skillDescInput');
const skillsList = document.getElementById('skillsList');
const editorTitle = document.getElementById('editorTitle');
const deleteConfirmModal = document.getElementById('deleteConfirmModal');
const deleteCancelBtn = document.getElementById('deleteCancelBtn');
const deleteConfirmBtn = document.getElementById('deleteConfirmBtn');
const deleteSkillName = document.getElementById('deleteSkillName');
// Multi-file UI elements
const contextMenu = document.getElementById('contextMenu');
const createItemModal = document.getElementById('createItemModal');
const createItemTitle = document.getElementById('createItemTitle');
const itemNameInput = document.getElementById('itemNameInput');
const itemNameHint = document.getElementById('itemNameHint');
const createItemCancelBtn = document.getElementById('createItemCancelBtn');
const createItemConfirmBtn = document.getElementById('createItemConfirmBtn');
const deleteItemModal = document.getElementById('deleteItemModal');
const deleteItemTitle = document.getElementById('deleteItemTitle');
const deleteItemMessage = document.getElementById('deleteItemMessage');
const deleteItemCancelBtn = document.getElementById('deleteItemCancelBtn');
const deleteItemConfirmBtn = document.getElementById('deleteItemConfirmBtn');
const renameModal = document.getElementById('renameModal');
const renameInput = document.getElementById('renameInput');
const renameCancelBtn = document.getElementById('renameCancelBtn');
const renameConfirmBtn = document.getElementById('renameConfirmBtn');
// Import modal elements
const importConflictModal = document.getElementById('importConflictModal');
const importConflictName = document.getElementById('importConflictName');
const importOverwriteBtn = document.getElementById('importOverwriteBtn');
const importRenameBtn = document.getElementById('importRenameBtn');
const importCancelBtn = document.getElementById('importCancelBtn');
const importRenameModal = document.getElementById('importRenameModal');
const importRenameInput = document.getElementById('importRenameInput');
const importRenameCancelBtn = document.getElementById('importRenameCancelBtn');
const importRenameConfirmBtn = document.getElementById('importRenameConfirmBtn');
const uploadDropZone = document.getElementById('uploadDropZone');
const fileNotEditablePlaceholder = document.getElementById('fileNotEditablePlaceholder');
const fileNotEditableInfo = document.getElementById('fileNotEditableInfo');
const fileInfo = document.getElementById('fileInfo');
function deactivateDragZone() {
if (!dragZone) {
return;
}
dragZone.classList.remove('active');
zipPath = null;
}
const modalConfirmPairs = [
{ modal: newSkillModal, confirmButton: createBtn },
{ modal: deleteConfirmModal, confirmButton: deleteConfirmBtn },
{ modal: createItemModal, confirmButton: createItemConfirmBtn },
{ modal: deleteItemModal, confirmButton: deleteItemConfirmBtn },
{ modal: renameModal, confirmButton: renameConfirmBtn },
{ modal: importRenameModal, confirmButton: importRenameConfirmBtn }
];
// Test listener for input debugging
// Utility functions
function normalizePath(pathString) {
return typeof pathString === 'string' ? pathString.replace(/\\/g, '/') : pathString;
}
function getParentDirectory(pathString) {
const normalized = normalizePath(pathString || '');
if (!normalized) return '';
const segments = normalized.split('/');
segments.pop();
return segments.join('/');
}
function getRelativePath(fullPath, basePath) {
// Extract relative path from a full path using the base path
const normalizedFull = normalizePath(fullPath);
const normalizedBase = normalizePath(basePath);
if (!normalizedFull || !normalizedBase) {
return normalizedFull;
}
if (!normalizedFull.startsWith(normalizedBase + '/')) {
return normalizedFull;
}
return normalizedFull.substring(normalizedBase.length + 1);
}
function getFileIcon(node) {
if (node.type === 'folder') return '📁';
const ext = node.name.split('.').pop().toLowerCase();
const icons = {
'md': '📝',
'txt': '📄',
'js': '🔨',
'py': '🐍',
'json': '⚙️',
'html': '🌐',
'css': '🎨',
'yaml': '⚙️',
'yml': '⚙️',
'sh': '💻',
'rb': '💎',
};
return icons[ext] || '📄';
}
function formatFileSize(bytes) {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
}
function getActiveModalConfirmButton() {
for (const { modal, confirmButton } of modalConfirmPairs) {
if (modal && confirmButton && modal.classList.contains('active')) {
return confirmButton;
}
}
return null;
}
function setEditorContent(value, options = {}) {
if (!editor) return;
const { markClean = true } = options;
suppressEditorChange = true;
try {
editor.setValue(value);
} finally {
suppressEditorChange = false;
}
if (markClean) {
hasUnsavedChanges = false;
if (autoSaveDebounceTimer) {
clearTimeout(autoSaveDebounceTimer);
autoSaveDebounceTimer = null;
}
}
}
function refreshActiveFileHighlight() {
document.querySelectorAll('.file-tree-node.file.active').forEach(node => node.classList.remove('active'));
if (!currentFile || !currentFile.path) {
return;
}
const nodeId = `file-node-${currentFile.path.replace(/\//g, '-')}`;
const activeNode = document.getElementById(nodeId);
if (activeNode) {
activeNode.classList.add('active');
}
}
function renderFileTree(nodes) {
if (!nodes || nodes.length === 0) {
return '<div class="file-tree-empty" style="color: var(--mid-gray); padding: 16px 8px; font-size: 12px;">No files</div>';
}
let html = '';
for (const node of nodes) {
// node.path already contains the complete relative path from backend
const nodeId = `file-node-${node.path.replace(/\//g, '-')}`;
if (node.type === 'folder') {
const hasChildren = node.children && node.children.length > 0;
html += `<div class="file-tree-node folder" data-node-id="${nodeId}" data-node-path="${node.path}" data-node-type="folder" data-expanded="true">`;
// Always show toggle (even for empty folders - they can have items added to them)
html += `<div class="file-tree-toggle expanded" data-toggle="${nodeId}"></div>`;
html += `<span class="file-tree-icon folder-icon">${hasChildren ? '📂' : '📁'}</span>`;
html += `<span class="folder-name">${node.name}</span>`;
html += `</div>`;
// Always create children container (even if empty, for future items)
html += `<div class="file-tree-children expanded" id="${nodeId}">`;
if (hasChildren) {
html += renderFileTree(node.children);
}
html += `</div>`;
} else {
const editable = node.editable ? 'editable' : 'not-editable';
html += `<div class="file-tree-node file ${editable}" data-node-id="${nodeId}" data-node-path="${node.path}" data-node-type="file" data-editable="${node.editable ? 'true' : 'false'}">`;
html += `<div class="file-tree-toggle" style="visibility: hidden;"></div>`;
html += `<span class="file-tree-icon">${getFileIcon(node)}</span>`;
html += `<span>${node.name}</span>`;
html += `</div>`;
}
}
return html;
}
async function loadFileTree() {
if (!currentSkill || !currentFileTreeContainer) {
return;
}
try {
const result = await window.electronAPI.listSkillFiles(currentSkill.path);
if (result.success) {
fileTree = result.files;
const html = renderFileTree(fileTree);
currentFileTreeContainer.innerHTML = html;
attachRootDropHandlers(currentFileTreeContainer);
attachFileTreeEventListeners(currentFileTreeContainer);
refreshActiveFileHighlight();
} else {
showNotification('Failed to load files: ' + (result.error || 'Unknown error'), 'error');
}
} catch (error) {
console.error('Error loading file tree:', error);
showNotification('Error loading files', 'error');
}
}
function attachFileTreeEventListeners(root) {
const scope = root || document;
// File click to load
scope.querySelectorAll('.file-tree-node.file').forEach(node => {
// Make files draggable
node.setAttribute('draggable', 'true');
node.addEventListener('click', async (e) => {
e.stopPropagation();
await autoSave();
const nodePath = node.getAttribute('data-node-path');
loadFileFromTree(nodePath);
});
node.addEventListener('contextmenu', (e) => {
e.preventDefault();
e.stopPropagation();
contextMenuTarget = node;
const nodePath = node.getAttribute('data-node-path');
showContextMenu(e.clientX, e.clientY, 'file');
});
// Drag start - store what file is being dragged
node.addEventListener('dragstart', (e) => {
const filePath = node.getAttribute('data-node-path');
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/plain', filePath);
e.dataTransfer.setData('application/x-skill-file', filePath);
node.classList.add('dragging');
});
node.addEventListener('dragend', (e) => {
node.classList.remove('dragging');
});
});
// Folder click to expand/collapse (anywhere on the row)
scope.querySelectorAll('.file-tree-node.folder').forEach(node => {
node.addEventListener('click', (e) => {
e.stopPropagation();
toggleFolder(node);
});
node.addEventListener('contextmenu', (e) => {
e.preventDefault();
e.stopPropagation();
contextMenuTarget = node;
const nodePath = node.getAttribute('data-node-path');
showContextMenu(e.clientX, e.clientY, 'folder');
});
// Add drag-and-drop support for folders
node.addEventListener('dragenter', (e) => {
e.preventDefault();
e.stopPropagation();
node.classList.add('drag-over');
});
node.addEventListener('dragover', (e) => {
e.preventDefault();
e.stopPropagation();
// Check if it's internal or external file
const types = Array.from(e.dataTransfer.types);
if (types.includes('application/x-skill-file')) {
e.dataTransfer.dropEffect = 'move';
} else {
e.dataTransfer.dropEffect = 'copy';
}
});
node.addEventListener('dragleave', (e) => {
// Only remove highlight if we're actually leaving the folder node
// Check if the relatedTarget (where we're going) is NOT a child of this node
if (!node.contains(e.relatedTarget)) {
node.classList.remove('drag-over');
}
});
node.addEventListener('drop', async (e) => {
e.preventDefault();
e.stopPropagation();
node.classList.remove('drag-over');
if (!currentSkill) {
return;
}
const targetFolder = node.getAttribute('data-node-path');
// Check if this is an internal file move
// Try custom MIME type first, then fall back to text/plain
let internalFilePath = e.dataTransfer.getData('application/x-skill-file');
if (!internalFilePath) {
internalFilePath = e.dataTransfer.getData('text/plain');
}
// Check if it's actually an internal file (has no slashes at start, indicating a relative path)
if (internalFilePath && !internalFilePath.startsWith('/') && !internalFilePath.startsWith('file:')) {
await moveFileToFolder(internalFilePath, targetFolder);
return;
}
// Otherwise, it's an external file upload
const items = e.dataTransfer.items;
if (!items || items.length === 0) {
return;
}
const filesToUpload = [];
const entries = Array.from(items)
.map(item => item.webkitGetAsEntry ? item.webkitGetAsEntry() : null)
.filter(Boolean);
const traverseFileTree = async (entry, path = '') => {
if (entry.isFile) {
const file = await new Promise((resolve, reject) => {
entry.file(resolve, reject);
});
const data = await file.arrayBuffer();
filesToUpload.push({
name: path ? `${path}/${file.name}` : file.name,
data: new Uint8Array(data)
});
} else if (entry.isDirectory) {
const reader = entry.createReader();
const entries = await new Promise((resolve, reject) => {
reader.readEntries(resolve, reject);
});
for (const childEntry of entries) {
await traverseFileTree(childEntry, path ? `${path}/${entry.name}` : entry.name);
}
}
};
for (const entry of entries) {
await traverseFileTree(entry);
}
if (filesToUpload.length > 0) {
await uploadFiles(filesToUpload.map(f => ({
arrayBuffer: () => Promise.resolve(f.data),
webkitRelativePath: f.name,
name: f.name.split('/').pop()
})), targetFolder, true);
}
});
});
// Folder toggle icon click (in addition to folder row)
scope.querySelectorAll('.file-tree-toggle').forEach(toggle => {
toggle.addEventListener('click', (e) => {
e.stopPropagation();
const folderNode = toggle.closest('.file-tree-node.folder');
if (folderNode) {
toggleFolder(folderNode);
}
});
});
}
function toggleFolder(folderNode) {
const nodeId = folderNode.getAttribute('data-node-id');
const toggle = folderNode.querySelector('.file-tree-toggle');
const folderIcon = folderNode.querySelector('.folder-icon');
const childrenContainer = document.getElementById(nodeId);
if (!childrenContainer) return;
// Toggle expanded state
const isExpanded = folderNode.getAttribute('data-expanded') === 'true';
folderNode.setAttribute('data-expanded', !isExpanded);
// Update toggle icon
toggle.classList.toggle('expanded');
toggle.classList.toggle('collapsed');
// Update folder icon
if (folderIcon) {
folderIcon.textContent = isExpanded ? '📁' : '📂';
}
// Update children visibility
childrenContainer.classList.toggle('expanded');
childrenContainer.classList.toggle('collapsed');
}
async function loadFileFromTree(filePath) {
if (!currentSkill || !currentSkillDir) return;
deactivateDragZone();
// Auto-save before switching files
await autoSave();
// Ensure filePath is relative
const relativeFilePath = getRelativePath(filePath, currentSkillDir);
const fullPath = `${currentSkillDir}/${relativeFilePath}`;
try {
const result = await window.electronAPI.loadFile({ filePath: fullPath });
if (result.success) {
currentFile = {
...result.metadata,
path: relativeFilePath // Always store relative path (override metadata's full path)
};
// Update active highlighting
refreshActiveFileHighlight();
// Update editor based on editability
if (result.metadata.editable) {
setEditorContent(result.content);
editor.getModel().setLanguage(getLanguageMode(filePath));
fileNotEditablePlaceholder.style.display = 'none';
emptyState.style.display = 'none';
document.getElementById('editor').style.display = 'flex';
// Force focus on the Monaco editor
setTimeout(() => {
editor.focus();
}, 50);
} else {
document.getElementById('editor').style.display = 'none';
emptyState.style.display = 'none';
fileNotEditablePlaceholder.style.display = 'flex';
const typeInfo = `Type: ${result.metadata.type} | Size: ${formatFileSize(result.metadata.size)}`;
fileNotEditableInfo.textContent = typeInfo;
}
// Update toolbar
editorTitle.textContent = `${currentSkill.name} / ${currentFile.name}`;
fileInfo.textContent = result.metadata.editable ? '' : '(Not editable)';
packageBtn.disabled = false;
} else {
showNotification('Failed to load file: ' + (result.error || 'Unknown error'), 'error');
}
} catch (error) {
console.error('Error loading file:', error);
showNotification('Error loading file', 'error');
}
}
function getLanguageMode(filePath) {
const ext = filePath.split('.').pop().toLowerCase();
const modes = {
'md': 'markdown',
'txt': 'plaintext',
'js': 'javascript',
'py': 'python',
'json': 'json',
'html': 'html',
'css': 'css',
'yaml': 'yaml',
'yml': 'yaml',
'sh': 'shell',
};
return modes[ext] || 'plaintext';
}
function showContextMenu(x, y, type) {
const contextMenuItems = contextMenu.querySelectorAll('.context-menu-item');
if (type === 'file') {
// Show/hide items based on file operations
contextMenuItems.forEach(item => {
const action = item.getAttribute('data-action');
if (action === 'new-file' || action === 'new-folder' || action === 'upload-files' || action === 'upload-folder') {
item.style.display = 'none';
} else {
item.style.display = 'block';
}
});
} else {
// Show all items for folder
contextMenuItems.forEach(item => item.style.display = 'block');
}
contextMenu.style.display = 'block';
contextMenu.style.left = x + 'px';
contextMenu.style.top = y + 'px';
}
function hideContextMenu() {
contextMenu.style.display = 'none';
// Don't clear contextMenuTarget here - it's needed for modal operations
// It will be cleared when the modal is closed or action is completed
}
// Event Listeners
newSkillBtn.addEventListener('click', async () => {
await autoSave();
newSkillModal.classList.add('active');
skillNameInput.focus();
});
cancelBtn.addEventListener('click', () => {
newSkillModal.classList.remove('active');
skillNameInput.value = '';
skillDescInput.value = '';
});
createBtn.addEventListener('click', async () => {
const name = skillNameInput.value.trim();
const description = skillDescInput.value.trim();
if (!name) {
showNotification('Please enter a skill name', 'error');
return;
}
// Validate skill name: lowercase letters, numbers, and hyphens only (Claude Desktop requirement)
if (!/^[a-z0-9-]+$/.test(name)) {
showNotification('Skill name can only contain lowercase letters, numbers, and hyphens (e.g., my-awesome-skill)', 'error');
return;
}
if (name.length > 255) {
showNotification('Skill name is too long (max 255 characters)', 'error');
return;
}
if (description.length > 500) {
showNotification('Description is too long (max 500 characters)', 'error');
return;
}
// Auto-save current skill before creating new one
await autoSave();
// Create template with proper escaping - use YAML formatting
const yamlName = name.replace(/"/g, '\\"');
const yamlDesc = (description || 'A custom Claude skill').replace(/"/g, '\\"');
const template = `---
name: "${yamlName}"
description: "${yamlDesc}"
---
`;
const result = await window.electronAPI.createSkill({
name,
description,
content: template
});
if (result.success) {
newSkillModal.classList.remove('active');
skillNameInput.value = '';
skillDescInput.value = '';
const skills = await loadSkills();
const newSkill = skills.find(s => s.name === name);
if (newSkill) {
await loadSkill(newSkill);
}
} else {
showNotification('Failed to create skill: ' + (result.error || 'Unknown error'), 'error');
}
});
openSkillBtn.addEventListener('click', async () => {
await autoSave();
const result = await window.electronAPI.openFileDialog();
if (result.success) {
const loadResult = await window.electronAPI.loadSkill(result.filePath);
if (loadResult.success) {
const importedPath = normalizePath(loadResult.path || result.filePath);
const skills = await loadSkills();
const importedSkill = skills.find(s => s.path === importedPath);
if (importedSkill) {
await loadSkill(importedSkill);
} else {
deactivateDragZone();
currentSkill = {
path: importedPath,
name: extractSkillName(importedPath),
description: ''
};
currentSkillDir = getParentDirectory(importedPath);
currentFile = null;
setEditorContent(loadResult.content);
const editorElement = document.getElementById('editor');
if (editorElement) {
editorElement.style.display = 'flex';
}
fileNotEditablePlaceholder.style.display = 'none';
emptyState.style.display = 'none';
editorTitle.textContent = currentSkill.name;
fileInfo.textContent = '';
packageBtn.disabled = false;
deleteBtn.disabled = false;
await loadFileTree();
}
if (loadResult.imported) {
showNotification(`Imported "${extractSkillName(importedPath)}" into your library`, 'success');
}
} else {
showNotification('Failed to load skill: ' + (loadResult.error || 'Unknown error'), 'error');
}
}
});
// Import .skill file handler
importSkillBtn.addEventListener('click', async () => {
await autoSave();
const result = await window.electronAPI.openSkillFileDialog();
if (!result.success) return;
const importResult = await window.electronAPI.importSkillPackage({
filePath: result.filePath
});
if (!importResult.success) {
showNotification('Failed to import: ' + (importResult.error || 'Unknown error'), 'error');
return;
}
if (importResult.conflict) {
// Store pending import info and show conflict modal
pendingImport = { tempPath: importResult.tempPath, skillName: importResult.skillName };
importConflictName.textContent = importResult.skillName;
importConflictModal.classList.add('active');
} else {
// No conflict, import completed
showNotification(`Imported "${importResult.skillName}" successfully`, 'success');
const skills = await loadSkills();
// Auto-select the imported skill
const importedSkill = skills.find(s => s.name === importResult.skillName);
if (importedSkill) {
await loadSkill(importedSkill);
}
}
});
// Import conflict modal handlers
importOverwriteBtn.addEventListener('click', async () => {
if (!pendingImport) return;
importConflictModal.classList.remove('active');
const result = await window.electronAPI.confirmImportSkill({
tempPath: pendingImport.tempPath,
skillName: pendingImport.skillName,
action: 'overwrite'
});
if (result.success) {
showNotification(`Imported "${result.skillName}" successfully (overwrote existing)`, 'success');
const skills = await loadSkills();
const importedSkill = skills.find(s => s.name === result.skillName);
if (importedSkill) {
await loadSkill(importedSkill);
}
} else {
showNotification('Failed to import: ' + (result.error || 'Unknown error'), 'error');
}
pendingImport = null;
});
importRenameBtn.addEventListener('click', () => {
if (!pendingImport) return;
importConflictModal.classList.remove('active');
// Suggest a new name by appending -2
importRenameInput.value = pendingImport.skillName + '-2';
importRenameModal.classList.add('active');
importRenameInput.focus();
importRenameInput.select();
});
importCancelBtn.addEventListener('click', async () => {
importConflictModal.classList.remove('active');
if (pendingImport) {
// Clean up temp files
await window.electronAPI.confirmImportSkill({
tempPath: pendingImport.tempPath,
action: 'cancel'
});
pendingImport = null;
}
});
// Import rename modal handlers
importRenameCancelBtn.addEventListener('click', async () => {
importRenameModal.classList.remove('active');
if (pendingImport) {
// Clean up temp files
await window.electronAPI.confirmImportSkill({
tempPath: pendingImport.tempPath,
action: 'cancel'
});
pendingImport = null;
}
});
importRenameConfirmBtn.addEventListener('click', async () => {
if (!pendingImport) return;
const newName = importRenameInput.value.trim();
if (!newName) {
showNotification('Please enter a skill name', 'error');
return;
}
// Validate skill name: lowercase letters, numbers, and hyphens only
if (!/^[a-z0-9-]+$/.test(newName)) {
showNotification('Skill name can only contain lowercase letters, numbers, and hyphens', 'error');
return;
}
importRenameModal.classList.remove('active');
const result = await window.electronAPI.confirmImportSkill({
tempPath: pendingImport.tempPath,
skillName: newName,
action: 'rename'
});
if (result.success) {
showNotification(`Imported "${result.skillName}" successfully`, 'success');
const skills = await loadSkills();
const importedSkill = skills.find(s => s.name === result.skillName);
if (importedSkill) {
await loadSkill(importedSkill);
}
} else {
showNotification('Failed to import: ' + (result.error || 'Unknown error'), 'error');
}
pendingImport = null;
});
packageBtn.addEventListener('click', async () => {
if (!currentSkill) return;
// Auto-save before packaging
await autoSave();
// Create ZIP
const result = await window.electronAPI.createZip({
skillPath: currentSkill.path,
skillName: currentSkill.name
});
if (result.success) {
zipPath = result.zipPath;
dragZone.classList.add('active');
showNotification('Package created! Drag to Claude Desktop to install', 'success');
} else {
showNotification('Failed to create package', 'error');
}
});
deleteBtn.addEventListener('click', async () => {
if (!currentSkill) return;
// Show confirmation modal
deleteSkillName.textContent = currentSkill.name;
deleteConfirmModal.classList.add('active');
});
deleteCancelBtn.addEventListener('click', () => {
deleteConfirmModal.classList.remove('active');
});
deleteConfirmBtn.addEventListener('click', async () => {
if (!currentSkill) return;
// Close modal immediately
deleteConfirmModal.classList.remove('active');
// Delete the skill
const result = await window.electronAPI.deleteSkill({
skillPath: currentSkill.path
});
if (result.success) {
// Clear editor state
currentSkill = null;
currentSkillItem = null;
currentFileTreeContainer = null;
setEditorContent('');
document.getElementById('editor').style.display = 'none';
fileNotEditablePlaceholder.style.display = 'none';
emptyState.style.display = 'flex';
editorTitle.textContent = 'No skill loaded';
packageBtn.disabled = true;
deleteBtn.disabled = true;
deactivateDragZone();
// Reload skills list
await loadSkills();
// Show success notification
showNotification(`Skill deleted successfully`, 'success');
} else {
showNotification(`Failed to delete skill: ${result.error || 'Unknown error'}`, 'error');
}
});
// Native file drag functionality using Electron API
dragZone.addEventListener('dragstart', (e) => {
if (!zipPath) {
e.preventDefault();
return;
}
e.preventDefault();
if (e.dataTransfer) {
e.dataTransfer.effectAllowed = 'copy';
e.dataTransfer.setData('text/plain', currentSkill ? currentSkill.name : 'skill-package');
}
// Initiate native file drag operation through Electron
// Browser's drag gesture continues while IPC message triggers native drag
window.electronAPI.startDrag(zipPath, currentSkill ? currentSkill.name : 'skill');
});
dragZone.addEventListener('dragend', (e) => {
setTimeout(() => {
deactivateDragZone();
showNotification('Skill package ready to install in Claude Desktop', 'success');
}, 100);
});
// Listen for drag errors from main process
window.electronAPI.onDragError((message) => {
showNotification(`Drag failed: ${message}`, 'error');
});
// Functions
async function loadSkills() {
const rawSkills = await window.electronAPI.listSkills();
const skills = rawSkills.map(skill => ({
...skill,
path: normalizePath(skill.path)
}));
const activeSkillPath = currentSkill ? normalizePath(currentSkill.path) : null;
skillsList.innerHTML = '';
skills.forEach(skill => {
const item = document.createElement('div');
item.className = 'skill-item';
item.dataset.skillPath = skill.path;
const header = document.createElement('div');
header.className = 'skill-header';
const headerText = document.createElement('div');
headerText.className = 'skill-header-text';
const nameDiv = document.createElement('div');
nameDiv.className = 'skill-name';
nameDiv.textContent = skill.name;
const descDiv = document.createElement('div');
descDiv.className = 'skill-desc';
descDiv.textContent = skill.description || '';
headerText.appendChild(nameDiv);
headerText.appendChild(descDiv);
const toggle = document.createElement('span');
toggle.className = 'skill-toggle';
toggle.textContent = '▸';
header.appendChild(headerText);
header.appendChild(toggle);