-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
4105 lines (3866 loc) · 184 KB
/
app.js
File metadata and controls
4105 lines (3866 loc) · 184 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
// Mini VS Code-like playground
(function(){
const STORAGE_KEY = 'mini_vscode_files_v1'
// default files
const DEFAULT_FILES = {
// start empty by default per user request
}
// Toggle comment for selection or current line, language-aware by filename
function toggleCommentSelection(){
if(!editor) return
const session = editor.getSession()
const sel = editor.getSelectionRange()
const startRow = sel.start.row
const endRow = sel.end.row
const file = active || ''
// choose comment style by extension
const ext = (file.split('.').pop() || '').toLowerCase()
let style = 'line' // or 'block'
let linePrefix = '//'
let blockStart = '/*', blockEnd = '*/'
if(ext === 'html' || ext === 'htm'){
style = 'block'; blockStart = '<!--'; blockEnd = '-->'
}else if(ext === 'css' || ext === 'scss' || ext === 'sass'){
style = 'block'; blockStart = '/*'; blockEnd = '*/'
}else if(ext === 'js' || ext === 'ts' || ext === 'jsx' || ext === 'mjs' || ext === 'cjs'){
style = 'line'; linePrefix = '//'
}else if(ext === 'py'){
style = 'line'; linePrefix = '#'
}else if(ext === 'euph'){
style = 'block'; blockStart = '/*'; blockEnd = '*/'
}else{
// default to line comments when feasible
style = 'line'; linePrefix = '//'
}
// If selection spans multiple rows, operate on all rows
if(startRow !== endRow || sel.start.column !== sel.end.column){
const lines = session.getLines(startRow, endRow + 1)
if(style === 'line'){
const allCommented = lines.every(l=> l.trim().startsWith(linePrefix))
for(let r = startRow; r <= endRow; r++){
const text = session.getLine(r)
if(allCommented){
// remove first occurrence of prefix
const idx = text.indexOf(linePrefix)
if(idx >= 0){
const before = text.substring(0, idx)
const after = text.substring(idx + linePrefix.length)
session.replace({start:{row:r, column:0}, end:{row:r, column:text.length}}, (before + after).replace(/^\s*/, ''))
}
}else{
session.replace({start:{row:r, column:0}, end:{row:r, column:text.length}}, linePrefix + ' ' + text)
}
}
}else{
// block style: wrap or unwrap selection
const selText = editor.getSelectedText()
if(selText.startsWith(blockStart) && selText.endsWith(blockEnd)){
// remove block markers
const inner = selText.substring(blockStart.length, selText.length - blockEnd.length)
editor.session.replace(sel, inner)
}else{
editor.session.replace(sel, blockStart + '\n' + selText + '\n' + blockEnd)
}
}
}else{
// no selection: toggle comment on current line
const r = startRow
const text = session.getLine(r)
if(style === 'line'){
if(text.trim().startsWith(linePrefix)){
// remove first occurrence
const idx = text.indexOf(linePrefix)
if(idx >= 0){
const before = text.substring(0, idx)
const after = text.substring(idx + linePrefix.length)
session.replace({start:{row:r, column:0}, end:{row:r, column:text.length}}, (before + after).replace(/^\s*/, ''))
}
}else{
session.replace({start:{row:r, column:0}, end:{row:r, column:text.length}}, linePrefix + ' ' + text)
}
}else{
// block comment the line
if(text.trim().startsWith(blockStart) && text.trim().endsWith(blockEnd)){
// unwrap
const inner = text.trim().slice(blockStart.length, text.trim().length - blockEnd.length)
session.replace({start:{row:r, column:0}, end:{row:r, column:text.length}}, inner)
}else{
session.replace({start:{row:r, column:0}, end:{row:r, column:text.length}}, blockStart + text + blockEnd)
}
}
}
// keep selection and focus
editor.focus()
scheduleDirtyUpdate()
}
let files = {}
let tabs = [] // filenames
let active = null
// track collapsed state for folders (keys include trailing slash)
let collapsedFolders = {}
// per-file in-memory buffers track current edited content (unsaved)
const buffers = {}
// per-file Ace EditSession instances so each file has its own undo history
const sessions = {}
// lastSaved holds the last persisted content for each file (used for gutter diffing)
const lastSaved = {}
// track which gutter rows we've decorated per-file so we can clear them
const gutterDecorations = {}
// UI elements
const fileListEl = document.getElementById('file-list')
const newBtn = document.getElementById('new-file')
const saveBtn = document.getElementById('save-file')
const newFolderBtn = document.getElementById('new-folder')
const tabsEl = document.getElementById('tabs')
const runBtn = document.getElementById('run-preview')
const togglePreviewBtn = document.getElementById('toggle-preview')
const stopBtn = document.getElementById('stop-preview')
const previewEl = document.getElementById('preview')
const statusLeft = document.getElementById('status-left')
const statusRight = document.getElementById('status-right')
// Ace Editor placeholder — will be initialized after Ace loads
let editor = null
let euphModeInstance = null
let buildOutlineFn = null
// global problems/errors list so various tools can push diagnostics
let errors = []
let currentFolder = ''
function ensureAceLoaded(cb){
if(window.ace){ return cb() }
const s = document.createElement('script')
s.src = 'https://cdnjs.cloudflare.com/ajax/libs/ace/1.15.0/ace.js'
s.onload = ()=> cb()
s.onerror = ()=>{
console.error('Failed to load Ace editor')
try{ showDialog('Error','Failed to load the editor. Check your internet connection.') }catch(e){ console.error('Modal unavailable') }
}
document.head.appendChild(s)
}
// Generic dialog helpers (returns Promises)
function showDialog(title, message, {showCancel=false} = {}){
return new Promise((resolve)=>{
const modal = document.getElementById('dialog-modal')
const titleEl = document.getElementById('dialog-title')
const body = document.getElementById('dialog-body')
const ok = document.getElementById('dialog-ok')
const cancel = document.getElementById('dialog-cancel')
const close = document.getElementById('dialog-close')
if(!modal || !titleEl || !body) { alert(message); return resolve(false) }
titleEl.textContent = title || ''
body.innerHTML = message || ''
modal.style.display = 'flex'
cancel.style.display = showCancel? '' : 'none'
const cleanup = (val)=>{ modal.style.display = 'none'; ok.removeEventListener('click', onOk); cancel.removeEventListener('click', onCancel); close.removeEventListener('click', onCancel); resolve(val) }
const onOk = ()=> cleanup(true)
const onCancel = ()=> cleanup(false)
ok.addEventListener('click', onOk)
cancel.addEventListener('click', onCancel)
close.addEventListener('click', onCancel)
})
}
function showConfirm(title, message){ return showDialog(title, message, {showCancel:true}) }
function setupEditor(){
try{ if(typeof registerEuphMode === 'function') registerEuphMode() }catch(e){}
editor = ace.edit('editor')
// Remove Ace's built-in settings shortcut (Ctrl+, / Command+,) which
// opens an editor settings panel that we don't want in this UI.
try{
const cmds = editor && editor.commands && editor.commands.commands
if(cmds){
Object.keys(cmds).forEach(name => {
try{
const cmd = cmds[name]
const bk = cmd && cmd.bindKey
let win = null, mac = null
if(typeof bk === 'string') { win = bk; mac = bk }
else if(bk && typeof bk === 'object') { win = bk.win; mac = bk.mac }
const hasCtrlComma = (s)=> !!(s && typeof s === 'string' && s.toLowerCase().includes(',') && s.toLowerCase().includes('ctrl'))
const hasCmdComma = (s)=> !!(s && typeof s === 'string' && s.toLowerCase().includes(',') && (s.toLowerCase().includes('command') || s.toLowerCase().includes('cmd')))
if(hasCtrlComma(win) || hasCmdComma(mac)){
try{ editor.commands.removeCommand(name) }catch(_){ }
}
}catch(e){}
})
}
}catch(e){}
editor.setTheme('ace/theme/monokai')
editor.setOptions({fontSize:14, showPrintMargin:false})
// attach context menu to editor
editor.on('contextmenu', (e) => {
e.preventDefault()
const menu = document.getElementById('context-menu')
const target = e.domEvent.target
let filename = null
const li = target.closest('#file-list li')
if(li && li.dataset && li.dataset.name) filename = li.dataset.name
const isProblems = !!target.closest('#console') || !!target.closest('#error-list')
Array.from(menu.querySelectorAll('.ctx-item')).forEach(it => {
const scope = it.getAttribute('data-scope') || 'both'
if(scope === 'both') it.style.display = ''
else if(scope === 'file') it.style.display = filename ? '' : 'none'
else if(scope === 'global') it.style.display = filename ? 'none' : ''
else if(scope === 'console') it.style.display = isProblems ? '' : 'none'
})
menu.style.display = 'block'
menu.style.left = e.clientX + 'px'
menu.style.top = e.clientY + 'px'
menu.dataset.target = filename || (isProblems ? 'console' : '')
})
editor.session.setMode('ace/mode/html')
// Bind editor keys to open the custom search panel and navigate matches
try{
editor.commands.addCommand({
name: 'openCustomSearch',
bindKey: {win: 'Ctrl-F', mac: 'Command-F'},
exec: function() {
const panel = document.getElementById('search-panel')
const input = document.getElementById('search-input')
if(panel){ panel.style.display = ''; if(input){ input.focus(); input.select(); } }
}
})
editor.commands.addCommand({
name: 'nextCustomSearch',
bindKey: {win: 'Ctrl-G', mac: 'Command-G'},
exec: function(){ window.dispatchEvent(new KeyboardEvent('keydown', {key:'g', ctrlKey:true, metaKey:false})) }
})
editor.commands.addCommand({
name: 'prevCustomSearch',
bindKey: {win: 'Ctrl-Shift-G', mac: 'Command-Shift-G'},
exec: function(){ window.dispatchEvent(new KeyboardEvent('keydown', {key:'g', ctrlKey:true, shiftKey:true, metaKey:false})) }
})
}catch(e){ /* ignore if commands fail */ }
// update cursor status when moving
editor.getSession().on('change', ()=> updateCursorStatus())
editor.selection.on('changeCursor', updateCursorStatus)
// keep menu items in sync with selection state
try{ editor.getSession().on('change', ()=> { if(typeof updateMenuConditionals === 'function') updateMenuConditionals() }) }catch(e){}
try{ editor.selection.on('changeSelection', ()=> { if(typeof updateMenuConditionals === 'function') updateMenuConditionals() }) }catch(e){}
// setup outline (simple AST-like outline for HTML/JS)
try{
const outlineEl = document.getElementById('outline-sidebar') || document.getElementById('outline-list')
function buildOutline(){
if(!outlineEl) return
const text = editor.getValue()
const lines = text.split(/\n/)
const items = []
if(active && active.endsWith('.html')){
// find headings
lines.forEach((ln, i)=>{
const m = ln.match(/<h([1-6])[^>]*>(.*?)<\/h\1>/i)
if(m){ items.push({label: m[2].replace(/<[^>]+>/g,''), line: i}) }
})
}else if(active && (active.endsWith('.js') || active.endsWith('.ts'))){
// find function and class declarations (improved patterns)
lines.forEach((ln, i)=>{
let m = ln.match(/function\s+([a-zA-Z0-9_\$]+)\s*\(/)
if(m) { items.push({label: 'fn ' + m[1] + ' (line ' + (i+1) + ')', line: i}); return }
m = ln.match(/class\s+([A-Z_a-z0-9\$]+)/)
if(m) { items.push({label: 'class ' + m[1] + ' (line ' + (i+1) + ')', line: i}); return }
m = ln.match(/(?:const|let|var)\s+([a-zA-Z0-9_\$]+)\s*=\s*function\s*\(/)
if(m) { items.push({label: 'fn ' + m[1] + ' (line ' + (i+1) + ')', line: i}); return }
m = ln.match(/(?:const|let|var)\s+([a-zA-Z0-9_\$]+)\s*=\s*\([^\)]*\)\s*=>/) // arrow fn
if(m) { items.push({label: 'fn ' + m[1] + ' (line ' + (i+1) + ')', line: i}); return }
m = ln.match(/export\s+default\s+function\s*([a-zA-Z0-9_\$]*)/)
if(m) { items.push({label: 'export default ' + (m[1]||'') + ' (line ' + (i+1) + ')', line: i}); return }
m = ln.match(/export\s+(?:function|class)\s+([a-zA-Z0-9_\$]+)/)
if(m) { items.push({label: 'export ' + m[1] + ' (line ' + (i+1) + ')', line: i}); return }
// show TODOs inline in outline as lightweight indicators
m = ln.match(/\b(TODO|FIXME)\b[:\s-]*(.*)/i)
if(m) { items.push({label: m[1].toUpperCase() + ': ' + (m[2]||'').trim() + ' (line ' + (i+1) + ')', line: i}); return }
})
} else {
// fallback: show top-level tags
lines.forEach((ln,i)=>{
const m = ln.match(/<([a-zA-Z0-9\-]+)(\s|>)/)
if(m) items.push({label: '<' + m[1] + '>', line:i})
})
}
outlineEl.innerHTML = ''
if(items.length===0){ outlineEl.textContent = 'No outline entries' ; return }
items.forEach(it=>{
const el = document.createElement('div')
el.className = 'outline-item'
el.style.display = 'flex'
el.style.justifyContent = 'space-between'
el.style.padding = '6px 8px'
el.style.cursor = 'pointer'
el.style.color = 'var(--muted)'
const left = document.createElement('div')
left.style.display = 'flex'
left.style.gap = '8px'
const kind = document.createElement('span')
kind.className = 'outline-kind'
kind.textContent = (it.label && it.label.split(' ')[0]) || ''
kind.style.opacity = '0.8'
kind.style.fontSize = '12px'
kind.style.color = 'var(--muted)'
const lbl = document.createElement('span')
lbl.textContent = it.label
lbl.style.fontSize = '13px'
left.appendChild(kind)
left.appendChild(lbl)
const rn = document.createElement('span')
rn.textContent = (it.line+1)
rn.style.opacity = '0.6'
rn.style.fontSize = '12px'
el.appendChild(left)
el.appendChild(rn)
el.addEventListener('click', ()=>{
editor.focus()
editor.gotoLine(it.line+1, 0, true)
})
outlineEl.appendChild(el)
})
}
editor.getSession().on('change', ()=> { buildOutline(); scheduleDirtyUpdate(); debouncedLint(); if(active) buffers[active] = editor.getValue() })
// expose buildOutline for openFile to refresh outline immediately
buildOutlineFn = buildOutline
editor.selection.on('changeCursor', ()=> {})
setTimeout(()=> buildOutline(), 200)
}catch(e){ console.warn('outline not available', e) }
// --- Occurrence highlighting & multi-change support ---
try{
const Range = ace.require && ace.require('ace/range') ? ace.require('ace/range').Range : null
let occMarkerIds = []
let lastClickedTerm = null
let lastClickedType = null
function clearOccurrenceHighlights(){
try{
// Remove markers from the session they were created on. Support
// both legacy numeric ids and {id, sess} objects.
occMarkerIds.forEach(obj=>{
try{
if(typeof obj === 'number'){
try{ editor.getSession().removeMarker(obj) }catch(_){ }
}else if(obj && obj.id && obj.sess && typeof obj.sess.removeMarker === 'function'){
try{ obj.sess.removeMarker(obj.id) }catch(_){ }
}else if(obj && obj.id){
try{ editor.getSession().removeMarker(obj.id) }catch(_){ }
}
}catch(e){}
})
occMarkerIds = []
}catch(e){}
}
function tokenMatches(a, b){
// robust comparison: compare base token families before '.' and allow substring matches
if(!a || !b) return false
try{
const A = String(a).split('.')[0]
const B = String(b).split('.')[0]
if(A === B) return true
if(String(b).indexOf(String(a)) !== -1) return true
if(String(a).indexOf(String(b)) !== -1) return true
}catch(e){ }
return false
}
function highlightOccurrences(term, tokenType){
clearOccurrenceHighlights()
if(!term || !term.trim()) return
const s = editor.getSession(); const doc = s.getDocument(); const lines = doc.getAllLines()
const needle = term
// Prefer token-aware matching when tokenType provided
for(let r=0;r<lines.length;r++){
try{
const toks = s.getTokens(r) || []
let col = 0
for(let ti=0; ti<toks.length; ti++){
const tk = toks[ti]
const raw = (tk.value || '')
const norm = raw.replace(/[<>\\/]/g,'').trim()
const matchesType = tokenType ? tokenMatches(tokenType, tk.type) : true
if(matchesType && norm && norm === needle){
// compute start column for this token by using accumulated col
const startCol = col
const endCol = startCol + raw.length
// validate range values before adding marker to avoid orphan markers
if(Range && Number.isFinite(startCol) && Number.isFinite(endCol) && endCol > startCol){
const lineLen = (lines[r] || '').length
if(startCol >= 0 && startCol <= lineLen && endCol >= 0 && endCol <= lineLen + 1){
const range = new Range(r, startCol, r, endCol)
try{ const id = s.addMarker(range, 'ace_occurrence', 'text', false); if(typeof id !== 'undefined' && id !== null){ occMarkerIds.push({id: id, sess: s}) } else { console.warn('mini-vsc: occurrence addMarker returned invalid id', range, s===editor.getSession()) } }catch(e){ console.warn('mini-vsc: addMarker error', e) }
}
}
}
col += (tk.value || '').length
}
}catch(e){
// fallback to simple substring search per-line
const line = lines[r] || ''
let idx = 0
while(true){
const found = line.indexOf(needle, idx)
if(found === -1) break
const startCol = found
const endCol = found + Math.max(1, needle.length)
if(Range && Number.isFinite(startCol) && Number.isFinite(endCol) && endCol > startCol){
const lineLen = (line || '').length
if(startCol >= 0 && startCol <= lineLen && endCol >= 0 && endCol <= lineLen + 1){
const range = new Range(r, startCol, r, startCol + needle.length)
try{ const id = s.addMarker(range, 'ace_occurrence', 'text', false); if(typeof id !== 'undefined' && id !== null){ occMarkerIds.push({id: id, sess: s}) } else { console.warn('mini-vsc: occurrence addMarker returned invalid id', range, s===editor.getSession()) } }catch(e){ console.warn('mini-vsc: addMarker error', e) }
}
}
idx = found + Math.max(1, needle.length)
}
}
}
}
function handleClickOrSelect(e){
try{
// If there's an active selection (user dragged), prefer that
const selRange = editor && editor.getSelectionRange && editor.getSelectionRange()
if(selRange && !selRange.isEmpty && !selRange.isEmpty()){
const selected = editor.getSelectedText() || ''
if(selected && selected.trim()){
lastClickedTerm = selected
lastClickedType = null
window._miniVSC._lastClickedTermVal = lastClickedTerm
window._miniVSC._lastClickedTypeVal = lastClickedType
highlightOccurrences(selected, null)
try{ const el = document.querySelector('[data-action="changeAll"]'); if(el) el.style.display = '' }catch(e){}
return
}
}
const pos = (e && e.getDocumentPosition) ? e.getDocumentPosition() : (editor && editor.getCursorPosition && editor.getCursorPosition())
if(!pos) return
const tok = (editor.session && editor.session.getTokenAt) ? editor.session.getTokenAt(pos.row, pos.column) : null
let term = ''
let tokenType = null
if(tok){ tokenType = tok.type; term = (tok.value||'').replace(/[<>\\/]/g,'').trim() }
if(!term){
const wr = editor.session.getWordRange(pos.row, pos.column)
term = editor.session.getTextRange(wr) || ''
}
if(term && term.trim()){
lastClickedTerm = term
lastClickedType = tokenType
window._miniVSC._lastClickedTermVal = term
window._miniVSC._lastClickedTypeVal = tokenType
highlightOccurrences(term, tokenType)
try{ const el = document.querySelector('[data-action="changeAll"]'); if(el) el.style.display = '' }catch(e){}
}else{
lastClickedTerm = null
lastClickedType = null
window._miniVSC._lastClickedTermVal = null
window._miniVSC._lastClickedTypeVal = null
clearOccurrenceHighlights()
try{ const el = document.querySelector('[data-action="changeAll"]'); if(el) el.style.display = 'none' }catch(e){}
}
}catch(e){}
}
// wire both click and mouseup (covers click and drag selection end)
editor.on('click', handleClickOrSelect)
try{ editor.on('mouseup', handleClickOrSelect) }catch(e){}
try{ editor.selection && editor.selection.on && editor.selection.on('changeSelection', function(){ setTimeout(()=>{ try{ handleClickOrSelect() }catch(e){} }, 10) }) }catch(e){}
// expose helper on window for debugging
window._miniVSC = window._miniVSC || {}
window._miniVSC.highlightOccurrences = highlightOccurrences
window._miniVSC.clearOccurrenceHighlights = clearOccurrenceHighlights
window._miniVSC._lastClickedTerm = () => window._miniVSC._lastClickedTermVal || lastClickedTerm
window._miniVSC._lastClickedType = () => window._miniVSC._lastClickedTypeVal || lastClickedType
window._miniVSC._lastClickedTermVal = window._miniVSC._lastClickedTermVal || null
window._miniVSC._lastClickedTypeVal = window._miniVSC._lastClickedTypeVal || null
}catch(e){ console.warn('occurrence highlighting failed', e) }
// Remove any pre-existing custom markers (from prior runs or older bugs)
function removeCustomMarkersFromSession(sess){
try{
if(!sess || typeof sess.getMarkers !== 'function') return
const markers = sess.getMarkers(false) || {}
Object.keys(markers).forEach(k=>{
try{
const m = markers[k]
const cls = (m && m.clazz) ? m.clazz : (m && m.clazzName) ? m.clazzName : ''
if(!cls) return
if(cls.indexOf('ace_occurrence')!==-1 || cls.indexOf('ace_search_highlight')!==-1 || cls.indexOf('ace_search_active')!==-1){
try{ sess.removeMarker(Number(k)) }catch(e){}
}
}catch(e){}
})
}catch(e){}
}
try{ removeCustomMarkersFromSession(editor.getSession()) }catch(e){}
}
// Register a lightweight Ace mode for .euph/.huph files to provide basic colouring
function registerEuphMode(){
try{
if(euphModeInstance || !window.ace) return
const oop = ace.require('ace/lib/oop')
const TextMode = ace.require('ace/mode/text').Mode
const TextHighlightRules = ace.require('ace/mode/text_highlight_rules').TextHighlightRules
const EuphHighlightRules = function(){
const measureDurations = 'semiquaver|quaver|minim|crochet|crotchet|demisemiquaver'
const tuplets = 'triplet|quintuplet|sextuplet|septuplet|octuplet|nontuplet|dectuplet|undectuplet|duodectuplet'
const otherCommands = 'tremolo|measure'
const durations = Array.from(DURATIONS).join('|')
this.$rules = {
start: [
{ token: 'euph_measure_duration', regex: '\\b(' + measureDurations + ')Measure\\b', caseInsensitive: true },
{ token: 'euph_tuplet', regex: '\\b(' + tuplets + ')\\b', caseInsensitive: true },
{ token: 'euph_command', regex: '\\b(' + otherCommands + ')\\b', caseInsensitive: true },
{ token: 'euph_duration', regex: '\\b(' + durations + ')\\b', caseInsensitive: true },
{ token: 'euph_pitch', regex: '\\b[a-g][#`n]?\\d\\b', caseInsensitive: true },
{ token: 'euph_chord', regex: '\\[.*?\\]' },
{ token: 'comment', regex: '/\\*[\\s\\S]*?\\*/' },
{ token: 'euph_rest', regex: '\\brest\\b', caseInsensitive: true },
{ token: 'euph_bar', regex: '\\|' },
{ token: 'euph_tupletp', regex: '-' },
{ defaultToken: 'text' }
]
}
}
oop.inherits(EuphHighlightRules, TextHighlightRules)
const Mode = function(){
this.HighlightRules = EuphHighlightRules
}
oop.inherits(Mode, TextMode)
Mode.prototype.$id = 'ace/mode/euph'
try{
// define module so Ace can reference by name
ace.define('ace/mode/euph', ['require','exports','module','ace/lib/oop','ace/mode/text','ace/mode/text_highlight_rules'], function(require, exports, module){
const oop = require('ace/lib/oop')
const TextMode = require('ace/mode/text').Mode
const TextHighlightRules = require('ace/mode/text_highlight_rules').TextHighlightRules
function EuphHighlightRulesLocal(){
const measureDurations = 'semiquaver|quaver|minim|crochet|crotchet|demisemiquaver'
const tuplets = 'triplet|quintuplet|sextuplet|septuplet|octuplet|nontuplet|dectuplet|undectuplet|duodectuplet'
const otherCommands = 'tremolo|measure'
const durations = Array.from(DURATIONS).join('|')
this.$rules = {
start: [
{ token: 'euph_measure_duration', regex: '\\b(' + measureDurations + ')Measure\\b', caseInsensitive: true },
{ token: 'euph_tuplet', regex: '\\b(' + tuplets + ')\\b', caseInsensitive: true },
{ token: 'euph_command', regex: '\\b(' + otherCommands + ')\\b', caseInsensitive: true },
{ token: 'euph_duration', regex: '\\b(' + durations + ')\\b', caseInsensitive: true },
{ token: 'euph_pitch', regex: '\\b[a-g][#`n]?\\d\\b', caseInsensitive: true },
{ token: 'euph_chord', regex: '\\[.*?\\]' },
{ token: 'comment', regex: '/\\*[\\s\\S]*?\\*/' },
{ token: 'euph_rest', regex: '\\brest\\b', caseInsensitive: true },
{ token: 'euph_bar', regex: '\\|' },
{ token: 'euph_tupletp', regex: '-' },
{ defaultToken: 'text' }
]
}
}
oop.inherits(EuphHighlightRulesLocal, TextHighlightRules)
const ModeLocal = function(){ this.HighlightRules = EuphHighlightRulesLocal }
oop.inherits(ModeLocal, TextMode)
exports.Mode = ModeLocal
})
euphModeInstance = 'ace/mode/euph'
// inject styling for euph tokens to mimic euph.html colours
try{
const sid = 'mini-vsc-euph-styles'
if(!document.getElementById(sid)){
const s = document.createElement('style')
s.id = sid
s.textContent = `
.ace_editor .ace_euph_pitch { color: #00ff00; }
.ace_editor .ace_euph_duration { color: #00bfff; }
.ace_editor .ace_euph_measure_duration { color: #ff5555; }
.ace_editor .ace_euph_tuplet { color: #ff00ff; }
.ace_editor .ace_euph_command { color: #ffa500; }
.ace_editor .ace_euph_rest { color: #ffff00; }
.ace_editor .ace_euph_chord { color: #00ffff; }
.ace_editor .ace_comment { color: #888; }
.ace_editor .ace_euph_bar, .ace_editor .ace_euph_tupletp { color: #ffffff; }
`
document.head.appendChild(s)
}
}catch(e){}
}catch(e){
// fallback to instance when define fails
euphModeInstance = new Mode()
}
}catch(e){ console.warn('registerEuphMode failed', e) }
}
// helper debounce
function debounce(fn, delay){
let t = null
return function(...args){
clearTimeout(t)
t = setTimeout(()=> fn.apply(this, args), delay)
}
}
// update dirty indicators when editor content changes
// create a single debounced updater so repeated calls debounce correctly
const debouncedDirtyUpdate = debounce(()=>{ renderTabs(); renderFileList() }, 120)
function scheduleDirtyUpdate(){ if(editor) debouncedDirtyUpdate() }
// debounced lint-on-type
const debouncedLint = debounce(()=>{ try{ if(settings.lintOnType) runLint() }catch(e){} }, 800)
// storage helpers
function loadFromStorage(){
try{
const raw = localStorage.getItem(STORAGE_KEY)
if(raw){ files = JSON.parse(raw) }
else { files = {...DEFAULT_FILES} }
}catch(e){ files = {...DEFAULT_FILES} }
// initialize lastSaved snapshots for gutter diffing
try{
Object.keys(files).forEach(n=> lastSaved[n] = files[n])
}catch(e){}
}
function saveToStorage(){
try{
// sanitize files before storing: keep strings and folder markers
const safe = {}
Object.keys(files).forEach(k => {
const v = files[k]
if(typeof v === 'string' || v === '__folder__') safe[k] = v
})
localStorage.setItem(STORAGE_KEY, JSON.stringify(safe))
files = Object.assign({}, safe)
}catch(e){ console.error('saveToStorage', e) }
updatePlayMenuVisibility()
}
function buildTree(){
const tree = {}
for(const path in files){
if(files[path] === '__folder__'){
const parts = path.split('/').slice(0, -1)
let current = tree
for(const part of parts){
if(!current[part]) current[part] = {}
current = current[part]
}
}else{
const parts = path.split('/')
let current = tree
for(let i=0; i<parts.length; i++){
const part = parts[i]
if(i === parts.length - 1){
current[part] = files[path]
}else{
if(!current[part]) current[part] = {}
current = current[part]
}
}
}
}
return tree
}
function getAvailablePath(desired){
if(!files[desired]) return desired
// try adding suffix (1), (2), ... before extension
const parts = desired.split('/')
const base = parts.pop()
const prefix = parts.length? parts.join('/') + '/' : ''
const m = base.match(/^(.*?)(\.[^.]*)?$/)
const nameOnly = m ? m[1] : base
const ext = m && m[2] ? m[2] : ''
let i = 1
while(true){
const cand = prefix + nameOnly + ' (' + i + ')' + ext
if(!files[cand]) return cand
i++
}
}
function ensureParentFolders(path){
const parts = path.split('/')
if(parts.length <= 1) return
let cur = ''
for(let i=0;i<parts.length-1;i++){
cur += parts[i] + '/'
if(!files[cur]) files[cur] = '__folder__'
}
}
function moveFile(oldPath, newPath){
if(oldPath === newPath || !(oldPath in files)) return
// avoid accidental overwrites: pick an available path if needed
if(files[newPath] && files[newPath] !== '__folder__'){
newPath = getAvailablePath(newPath)
}
// ensure any parent folders for the destination path exist
ensureParentFolders(newPath)
files[newPath] = files[oldPath]
delete files[oldPath]
if(buffers[oldPath]){ buffers[newPath] = buffers[oldPath]; delete buffers[oldPath] }
if(sessions[oldPath]){ sessions[newPath] = sessions[oldPath]; delete sessions[oldPath] }
if(lastSaved[oldPath]){ lastSaved[newPath] = lastSaved[oldPath]; delete lastSaved[oldPath] }
if(gutterDecorations[oldPath]){ gutterDecorations[newPath] = gutterDecorations[oldPath]; delete gutterDecorations[oldPath] }
const ti = tabs.indexOf(oldPath)
if(ti >= 0) tabs[ti] = newPath
if(active === oldPath) active = newPath
saveToStorage()
renderFileList()
renderTabs()
}
function getAvailableFolderPath(desired){
if(!files[desired]) return desired
const base = desired.replace(/\/$/, '')
let i = 1
while(true){
const cand = base + ' (' + i + ')/'
if(!files[cand]) return cand
i++
}
}
function moveFolder(oldPath, destFolder){
// oldPath expected to end with '/'
if(!oldPath || !oldPath.endsWith('/')) return
if(!(oldPath in files)) return
// build destination base (destFolder should end with '/').
// If destFolder is empty (root), keep it empty to avoid leading '/'.
if(destFolder && !destFolder.endsWith('/')) destFolder = destFolder + '/'
const folderName = oldPath.replace(/\/$/, '').split('/').pop()
let newBase = destFolder + folderName + '/'
if(files[newBase]) newBase = getAvailableFolderPath(newBase)
ensureParentFolders(newBase)
const keys = Object.keys(files)
// move all keys under oldPath (including the folder marker)
keys.forEach(k => {
if(k === oldPath || k.indexOf(oldPath) === 0){
const rel = k.substring(oldPath.length)
const destKey = newBase + rel
files[destKey] = files[k]
if(buffers[k]){ buffers[destKey] = buffers[k]; delete buffers[k] }
if(sessions[k]){ sessions[destKey] = sessions[k]; delete sessions[k] }
if(lastSaved[k]){ lastSaved[destKey] = lastSaved[k]; delete lastSaved[k] }
if(gutterDecorations[k]){ gutterDecorations[destKey] = gutterDecorations[k]; delete gutterDecorations[k] }
const ti = tabs.indexOf(k); if(ti>=0) tabs[ti] = destKey
if(active === k) active = destKey
delete files[k]
}
})
saveToStorage(); renderFileList(); renderTabs()
}
function updateBreadcrumb(){
const bc = document.getElementById('editor-breadcrumb')
if(bc){
bc.innerHTML = '<span class="crumb">' + escapeHtml(currentFolder) + '</span>'
}
}
function showPlaceholder(){
const ph = document.getElementById('editor-placeholder')
if(ph) ph.style.display = 'flex'
if(editor) editor.setValue('')
}
// Settings persistence: remembers UI options like word wrap, autoRefresh, ui-scale and bottom height
const SETTINGS_KEY = 'mini_vsc_settings_v1'
let settings = { wordWrap: false, autoRefresh: false, uiScale: 1, lintOnSave: true, lintOnType: true, autoSave: false, includeAllResources: false, lineEnding: 'LF' }
function loadSettings(){
try{ const s = localStorage.getItem(SETTINGS_KEY); if(s) settings = Object.assign(settings, JSON.parse(s)) }catch(e){}
}
function saveSettings(){
try{ localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings)); updateStatus('Settings saved') }catch(e){ console.error('saveSettings', e) }
}
// persist collapsed folder state alongside other settings
function persistCollapsedState(){
try{ settings.collapsedFolders = Object.assign({}, collapsedFolders); saveSettings() }catch(e){}
}
function applySettings(){
try{
// word wrap
if(editor && editor.getSession){ editor.getSession().setUseWrapMode(!!settings.wordWrap) }
// auto refresh
autoRefresh = !!settings.autoRefresh
// ui scale
try{ document.documentElement.style.setProperty('--ui-scale', String(settings.uiScale || 1)) }catch(e){}
// bottom panel height restored elsewhere
}catch(e){ console.error('applySettings', e) }
}
// UI helpers
function renderFileList(){
const tree = buildTree()
fileListEl.innerHTML = ''
function renderDir(dir, prefix, ul){
for(const [name, value] of Object.entries(dir)){
const fullPath = prefix + name
const li = document.createElement('li')
// Normalize dataset name: include trailing slash for folders so
// callers can reliably detect folder keys (files store raw paths)
li.dataset.name = (typeof value === 'object') ? (fullPath + '/') : fullPath
if(typeof value !== 'string') li.classList.add('folder')
li.tabIndex = 0
li.draggable = true
li.addEventListener('dragstart', (e) => {
const dragKey = (typeof value === 'object') ? (fullPath + '/') : fullPath
e.dataTransfer.setData('text/plain', dragKey)
})
// left-side (icon + label)
const left = document.createElement('div')
left.style.display = 'flex'
left.style.alignItems = 'center'
left.style.flex = '1'
const ico = document.createElement('span')
ico.className = 'file-icon'
ico.style.marginRight = '8px'
ico.style.opacity = '0.95'
ico.style.width = '20px'
ico.style.display = 'inline-block'
ico.style.textAlign = 'center'
if(typeof value === 'string'){
try{ ico.innerHTML = iconFor(name) }catch(e){ ico.textContent = '' }
}else{
ico.innerHTML = '<span class="msr">folder</span>'
}
const nameSpan = document.createElement('span')
nameSpan.className = 'file-name'
nameSpan.textContent = name
nameSpan.style.flex = '1'
nameSpan.style.cursor = 'pointer'
if(typeof value === 'string'){
nameSpan.addEventListener('click', ()=> openFile(fullPath))
nameSpan.addEventListener('dblclick', (e)=>{ e.stopPropagation(); startRename(fullPath) })
}else{
// set currentFolder to include trailing slash to simplify concatenation
nameSpan.addEventListener('click', () => { currentFolder = fullPath + '/'; active = null; updateBreadcrumb(); showPlaceholder() })
}
left.appendChild(ico)
left.appendChild(nameSpan)
li.appendChild(left)
if(typeof value === 'string'){
// delete button for files — wrap into a header so the delete
// button always aligns to the right regardless of filename width
const del = document.createElement('button')
del.className = 'btn-close small'
del.title = 'Delete file'
del.innerHTML = '<span class="msr">delete</span>'
del.addEventListener('click', (e)=>{ e.stopPropagation(); deleteFile(fullPath) })
// show dirty indicator
const buf = (buffers.hasOwnProperty(fullPath)) ? buffers[fullPath] : ( (fullPath === active && editor) ? editor.getValue() : files[fullPath] || '' )
const dirty = buf !== (files[fullPath]||'')
if(dirty){
const d = document.createElement('span')
d.className = 'dirty-indicator'
d.title = 'Unsaved changes'
nameSpan.appendChild(d)
}
// create a row container so the left content and delete button are
// spaced apart and the delete button is always at the same x-position
try{
if(left && left.parentNode === li) li.removeChild(left)
const row = document.createElement('div')
row.className = 'file-row'
row.style.display = 'flex'
row.style.justifyContent = 'space-between'
row.style.alignItems = 'center'
row.appendChild(left)
row.appendChild(del)
li.appendChild(row)
}catch(e){
// fallback
li.appendChild(del)
}
}else{
// folder, add a toggle and sub ul
const toggle = document.createElement('span')
toggle.className = 'folder-toggle msr'
toggle.textContent = collapsedFolders[fullPath + '/'] ? 'chevron_right' : 'expand_more'
toggle.style.cursor = 'pointer'
toggle.style.marginRight = '6px'
left.insertBefore(toggle, nameSpan)
const subUl = document.createElement('ul')
subUl.className = 'folder-children' + (collapsedFolders[fullPath + '/'] ? ' collapsed' : '')
li.appendChild(subUl)
// render children with a trailing prefix so all child paths are correct
renderDir(value, fullPath + '/', subUl)
// Drop handlers: use the folder path (with trailing slash) to build
// the destination path consistently.
const folderDest = fullPath + '/'
subUl.addEventListener('drop', (e) => {
e.preventDefault();
const dragged = e.dataTransfer.getData('text/plain');
if(!dragged || !(dragged in files)) return;
if(files[dragged] === '__folder__'){
moveFolder(dragged, folderDest)
}else{
const fileName = dragged.split('/').pop();
moveFile(dragged, folderDest + fileName)
}
})
subUl.addEventListener('dragover', (e) => e.preventDefault())
// delete button for folders (will be moved into header)
const del = document.createElement('button')
del.className = 'btn-close small'
del.title = 'Delete folder'
del.innerHTML = '<span class="msr">delete</span>'
del.addEventListener('click', (e)=>{ e.stopPropagation(); deleteFile(folderDest) })
// Replace the flat `li` layout with a header container so the
// children `ul` appears underneath the folder header instead of
// beside it (fixes files appearing to the right of folders).
try{
// remove the previously appended `left` and insert into header
if(left && left.parentNode === li) li.removeChild(left)
const header = document.createElement('div')
header.className = 'folder-header'
header.style.display = 'flex'
header.style.justifyContent = 'space-between'
header.style.alignItems = 'center'
header.appendChild(left)
header.appendChild(del)
// insert header before the children list so children render below
li.insertBefore(header, subUl)
}catch(e){}
li.addEventListener('drop', (e) => {
e.preventDefault();
const dragged = e.dataTransfer.getData('text/plain');
if(!dragged || dragged === fullPath || !(dragged in files)) return;
if(files[dragged] === '__folder__'){
moveFolder(dragged, folderDest)
}else{
const fileName = dragged.split('/').pop();
moveFile(dragged, folderDest + fileName)
}
})
li.addEventListener('dragover', (e) => e.preventDefault())
// toggle click: expand/collapse using CSS class for smooth transition
toggle.addEventListener('click', (e)=>{
e.stopPropagation(); const key = fullPath + '/'; collapsedFolders[key] = !collapsedFolders[key];
if(collapsedFolders[key]) subUl.classList.add('collapsed')
else subUl.classList.remove('collapsed')
toggle.textContent = collapsedFolders[key] ? 'chevron_right' : 'expand_more'
try{ persistCollapsedState() }catch(e){}
})
}
if(fullPath === active) li.classList.add('active')
ul.appendChild(li)
}
}
// Render a virtual top-level "Project" folder to give the illusion
// that the whole workspace is inside a single project container.
// Users can drop files onto this project header to move them to root.
const projectLi = document.createElement('li')
projectLi.className = 'folder project-root'
const projLeft = document.createElement('div')
projLeft.style.display = 'flex'
projLeft.style.alignItems = 'center'
projLeft.style.flex = '1'
const projIco = document.createElement('span')
projIco.className = 'file-icon'
projIco.style.marginRight = '8px'
projIco.innerHTML = '<span class="msr">folder_open</span>'
const projToggle = document.createElement('span')
projToggle.className = 'folder-toggle msr'
projToggle.textContent = collapsedFolders['project/'] ? 'chevron_right' : 'expand_more'
projToggle.style.cursor = 'pointer'
projToggle.style.marginRight = '6px'
const projLabel = document.createElement('span')
projLabel.className = 'file-name'
projLabel.textContent = 'Project'
projLabel.style.flex = '1'
projLabel.style.cursor = 'pointer'
projLabel.addEventListener('click', ()=>{ currentFolder = ''; active = null; updateBreadcrumb(); showPlaceholder() })